diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 2041f92e9c5..5d7ebc676e1 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-nodejs-mono-repo:latest - digest: sha256:94d55995d53fb47e6e265a2e02bfdb778ccaaef4f3618a0ea881b0ee559e88bf + digest: sha256:2e454636c6197216df757d53b0f865c1c7dcf57c92c489a612375bfca981ee81 # created: 2026-02-19T18:08:41.831765454Z diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index ae7db338588..c56b20068ee 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -9,3 +9,5 @@ * @googleapis/cloud-sdk-nodejs-team /handwritten/bigquery @googleapis/bigquery-team /handwritten/cloud-profiler @googleapis/cloud-profiler-team +/handwritten/spanner @googleapis/spanner-team +/handwritten/storage @googleapis/gcs-team diff --git a/.github/workflows/conformance-test.yaml b/.github/workflows/conformance-test.yaml new file mode 100644 index 00000000000..845d280462d --- /dev/null +++ b/.github/workflows/conformance-test.yaml @@ -0,0 +1,21 @@ +on: + push: + branches: + - main + paths: + - 'handwritten/storage/**' + pull_request: + paths: + - 'handwritten/storage/**' +name: conformance +jobs: + conformance-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 14 + - run: node --version + - run: cd handwritten/storage && npm install + - run: cd handwritten/storage && npm run conformance-test diff --git a/.github/workflows/system-tests-against-emulator.yaml b/.github/workflows/system-tests-against-emulator.yaml new file mode 100644 index 00000000000..01551f4688c --- /dev/null +++ b/.github/workflows/system-tests-against-emulator.yaml @@ -0,0 +1,28 @@ +on: + push: + branches: + - main + pull_request: +name: system-tests-against-emulator +jobs: + test: + runs-on: ubuntu-latest + + services: + emulator: + image: gcr.io/cloud-spanner-emulator/emulator:latest + ports: + - 9010:9010 + - 9020:9020 + + steps: + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + - run: node --version + - run: npm install + - run: npm run system-test + env: + SPANNER_EMULATOR_HOST: localhost:9010 + GCLOUD_PROJECT: emulator-test-project diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9afa1ee8000..e02e4bb0f08 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,12 +1,14 @@ { - "handwritten/datastore": "10.1.0", - "handwritten/logging-winston": "6.0.1", "handwritten/bigquery": "8.2.0", "handwritten/cloud-profiler": "6.0.4", + "handwritten/datastore": "10.1.0", "handwritten/logging-bunyan": "5.1.1", - "packages/gapic-node-processing": "0.1.6", + "handwritten/logging-winston": "6.0.1", + "handwritten/spanner": "8.6.0", + "handwritten/storage": "7.19.0", + "packages/gapic-node-processing": "0.1.7", "packages/google-ads-admanager": "0.5.0", - "packages/google-ads-datamanager": "0.1.0", + "packages/google-ads-datamanager": "0.2.0", "packages/google-ai-generativelanguage": "3.7.0", "packages/google-analytics-admin": "9.0.1", "packages/google-analytics-data": "5.2.1", @@ -22,7 +24,7 @@ "packages/google-chat": "0.23.0", "packages/google-cloud-accessapproval": "4.2.1", "packages/google-cloud-advisorynotifications": "2.2.1", - "packages/google-cloud-aiplatform": "6.4.0", + "packages/google-cloud-aiplatform": "6.5.0", "packages/google-cloud-alloydb": "2.4.0", "packages/google-cloud-apigateway": "4.2.1", "packages/google-cloud-apigeeconnect": "4.2.1", @@ -59,7 +61,7 @@ "packages/google-cloud-clouddms": "4.1.1", "packages/google-cloud-cloudsecuritycompliance": "0.2.0", "packages/google-cloud-commerce-consumer-procurement": "0.7.1", - "packages/google-cloud-compute": "6.7.0", + "packages/google-cloud-compute": "6.8.0", "packages/google-cloud-confidentialcomputing": "2.2.2", "packages/google-cloud-config": "0.11.1", "packages/google-cloud-configdelivery": "0.1.1", @@ -76,11 +78,11 @@ "packages/google-cloud-dataqna": "4.1.1", "packages/google-cloud-datastream": "4.3.1", "packages/google-cloud-deploy": "5.2.1", - "packages/google-cloud-developerconnect": "0.6.1", + "packages/google-cloud-developerconnect": "0.7.0", "packages/google-cloud-devicestreaming": "0.2.1", "packages/google-cloud-dialogflow": "7.5.0", "packages/google-cloud-dialogflow-cx": "5.7.0", - "packages/google-cloud-discoveryengine": "2.5.2", + "packages/google-cloud-discoveryengine": "2.5.3", "packages/google-cloud-dns": "5.3.1", "packages/google-cloud-documentai": "9.5.0", "packages/google-cloud-domains": "4.2.1", @@ -105,7 +107,7 @@ "packages/google-cloud-ids": "4.2.1", "packages/google-cloud-iot": "5.2.1", "packages/google-cloud-kms": "5.4.0", - "packages/google-cloud-kms-inventory": "2.4.0", + "packages/google-cloud-kms-inventory": "2.5.0", "packages/google-cloud-language": "7.2.1", "packages/google-cloud-licensemanager": "0.1.1", "packages/google-cloud-lifesciences": "4.2.1", @@ -124,7 +126,7 @@ "packages/google-cloud-monitoring": "5.3.1", "packages/google-cloud-netapp": "0.16.0", "packages/google-cloud-networkconnectivity": "4.6.0", - "packages/google-cloud-networkmanagement": "5.2.0", + "packages/google-cloud-networkmanagement": "5.3.0", "packages/google-cloud-networksecurity": "3.3.1", "packages/google-cloud-networkservices": "0.12.0", "packages/google-cloud-notebooks": "4.2.1", @@ -160,9 +162,9 @@ "packages/google-cloud-servicedirectory": "6.1.1", "packages/google-cloud-servicehealth": "0.7.1", "packages/google-cloud-shell": "4.1.1", - "packages/google-cloud-speech": "7.2.1", + "packages/google-cloud-speech": "7.3.0", "packages/google-cloud-sql": "0.24.0", - "packages/google-cloud-storagebatchoperations": "0.2.0", + "packages/google-cloud-storagebatchoperations": "0.3.0", "packages/google-cloud-storageinsights": "2.2.1", "packages/google-cloud-support": "2.2.1", "packages/google-cloud-talent": "7.1.1", @@ -171,7 +173,7 @@ "packages/google-cloud-texttospeech": "6.4.0", "packages/google-cloud-tpu": "4.1.1", "packages/google-cloud-translate": "9.3.0", - "packages/google-cloud-vectorsearch": "0.2.0", + "packages/google-cloud-vectorsearch": "0.3.0", "packages/google-cloud-video-livestream": "2.2.1", "packages/google-cloud-video-stitcher": "3.2.1", "packages/google-cloud-video-transcoder": "4.4.1", @@ -182,7 +184,7 @@ "packages/google-cloud-vpcaccess": "4.2.1", "packages/google-cloud-webrisk": "5.3.1", "packages/google-cloud-websecurityscanner": "4.2.1", - "packages/google-cloud-workflows": "5.0.0", + "packages/google-cloud-workflows": "5.1.0", "packages/google-cloud-workstations": "2.2.1", "packages/google-container": "6.7.0", "packages/google-dataflow": "4.1.1", @@ -223,5 +225,8 @@ "packages/google-storagetransfer": "4.2.1", "packages/google-streetview-publish": "0.4.1", "packages/grafeas": "6.1.1", - "packages/typeless-sample-bot": "3.1.1" + "packages/typeless-sample-bot": "3.1.1", + "packages/google-cloud-visionai": "0.1.0", + "packages/google-cloud-workloadmanager": "0.1.0", + "packages/google-cloud-ces": "0.1.0" } diff --git a/changelog.json b/changelog.json index fe7b26aa31e..55e7506dc8d 100644 --- a/changelog.json +++ b/changelog.json @@ -1,6 +1,328 @@ { "repository": "googleapis/google-cloud-node", "entries": [ + { + "changes": [ + { + "type": "feat", + "sha": "77042f508c0e4d03569ef4eae7e0dd8f235cd469", + "message": "[ces] add public libraries for CES v1beta", + "issues": [ + "7285" + ] + }, + { + "type": "feat", + "sha": "9146f2714244d2e7c50220ccb4380b738acab857", + "message": "Add initial files for google.cloud.ces.v1", + "issues": [ + "7241" + ] + }, + { + "type": "fix", + "sha": "41c2ff2851b5fdadabf4f9bd3500167c34b32ff7", + "message": "[gkeconnect-gateway] remove unused GatewayServiceClient", + "issues": [ + "6775" + ] + } + ], + "version": "0.1.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/ces", + "id": "82a005b5-f13a-4f62-b6e3-6e88408f9ae1", + "createTime": "2026-03-02T16:41:40.032Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "8a30212142e5403294368da827cb33d3b167209d", + "message": "Add initial files for google.cloud.workloadmanager.v1", + "issues": [ + "7265" + ] + }, + { + "type": "fix", + "sha": "41c2ff2851b5fdadabf4f9bd3500167c34b32ff7", + "message": "[gkeconnect-gateway] remove unused GatewayServiceClient", + "issues": [ + "6775" + ] + } + ], + "version": "0.1.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/workloadmanager", + "id": "69c8f974-5f6f-4363-b9d7-8db7adc29259", + "createTime": "2026-03-02T16:41:40.001Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "1cc4a84c3cab7894d8877488dcd7454aef62a8a2", + "message": "Add initial files for google.cloud.visionai.v1", + "issues": [ + "7275" + ] + }, + { + "type": "fix", + "sha": "41c2ff2851b5fdadabf4f9bd3500167c34b32ff7", + "message": "[gkeconnect-gateway] remove unused GatewayServiceClient", + "issues": [ + "6775" + ] + } + ], + "version": "0.1.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/visionai", + "id": "2b2a2e09-ed6f-4239-8005-a9309c8964db", + "createTime": "2026-03-02T16:41:39.968Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "faf79df319ddd7d732413aa0b745160bfb815198", + "message": "Expand workflows to receive both workflows and executions", + "issues": [ + "7271" + ] + }, + { + "type": "fix", + "sha": "41c2ff2851b5fdadabf4f9bd3500167c34b32ff7", + "message": "[gkeconnect-gateway] remove unused GatewayServiceClient", + "issues": [ + "6775" + ] + } + ], + "version": "5.1.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/workflows", + "id": "3eba0a4f-2744-4eb9-8d9c-ad4d2b45ab98", + "createTime": "2026-03-02T16:41:39.937Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "0faaf8cf11c10c807fad495758c33e601589cf4c", + "message": "[vectorsearch] introduce new v1 vectorsearch surface and make it default version", + "issues": [ + "7273" + ], + "breakingChangeNote": "[vectorsearch] introduce new v1 vectorsearch surface and make it default version ([#7273](https://github.com/googleapis/google-cloud-node/issues/7273))" + } + ], + "version": "0.3.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/vectorsearch", + "id": "8d909ea4-d3b1-4642-b846-3bb70801ad20", + "createTime": "2026-03-02T16:41:39.898Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "4b8da3eefef2c4af0f39f186b4d60257fa146eae", + "message": "[storagebatchoperations] add new transformation `update_object_custom_context`", + "issues": [ + "7309" + ] + } + ], + "version": "0.3.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/storagebatchoperations", + "id": "d5ce6e2d-882a-4987-bbff-bae0c22ef452", + "createTime": "2026-03-02T16:41:39.867Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "4373c581d895ad3785f1b3493bda83def6a0024c", + "message": "Adds endpointing sensitivity to streaming recognition features", + "issues": [ + "7270" + ] + } + ], + "version": "7.3.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/speech", + "id": "4524053f-fd26-4b60-ae8c-df2b6f8bf957", + "createTime": "2026-03-02T16:41:39.833Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "d6fb4665242b13e9c8b29ae3df6696155076297d", + "message": "[networkmanagement] Add API fields related to GKE Pods and Network Policies", + "issues": [ + "7292" + ] + } + ], + "version": "5.3.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/network-management", + "id": "f87378b8-a21d-4633-853c-e0ce5b6e78af", + "createTime": "2026-03-02T16:41:39.799Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "34a365988184038c96de95cf0d8bf4bb5d8a8ccf", + "message": "[inventory] Add support for project level key usage tracking", + "issues": [] + } + ], + "version": "2.5.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/kms-inventory", + "id": "54be806f-3d7a-449d-b521-33ec30ba360e", + "createTime": "2026-03-02T16:41:39.764Z" + }, + { + "changes": [ + { + "type": "fix", + "sha": "a28d23fde5441c969b380dbd0dff0dc48836c01e", + "message": "Enable google-cloud-discoveryengine tests to run on windows", + "issues": [] + }, + { + "type": "fix", + "sha": "f9b1ee9a92eb12f57a56db1bf591d3ec3afb4864", + "message": "Try an alternative bash script for windows compatibility without an additional dependency", + "issues": [] + }, + { + "type": "fix", + "sha": "23b81e4ae4c2dbe26f3731df4bd6cac9c687753b", + "message": "Enable google-cloud-discoveryengine tests to run on windows", + "issues": [] + } + ], + "version": "2.5.3", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/discoveryengine", + "id": "394651a4-0bfd-4335-b80e-b65dba1fef35", + "createTime": "2026-03-02T16:41:39.736Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "b23e571f96992f373cc6c413d026f322e8e58176", + "message": "[developerconnect] Add Secure Source Manager and Generic HTTP Endpoint connection types", + "issues": [ + "7284" + ] + } + ], + "version": "0.7.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/developerconnect", + "id": "300f53ce-1df2-4071-9efd-2dba3822b202", + "createTime": "2026-03-02T16:41:39.704Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "1bacdf222c3995c0b3e44d972c952645367e3fa0", + "message": "[compute] Update Compute Engine v1beta API to revision 20260213", + "issues": [ + "7296" + ] + }, + { + "type": "feat", + "sha": "2d1a22c828cd8dfecb2083d3bc270210a79a41e3", + "message": "[compute] Update Compute Engine v1beta API to revision 20260106 (#1147)", + "issues": [ + "7272" + ] + } + ], + "version": "6.8.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/compute", + "id": "974dfa02-4a93-42e2-9fcd-8cb33113b9db", + "createTime": "2026-03-02T16:41:39.673Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "9f91e0513bf7a60239aef5e4222993184c63fbb2", + "message": "Add `traffic_type, tool_use_prompt_tokens_details` to message `GenerateContentResponse.UsageMetadata`", + "issues": [ + "7266" + ] + } + ], + "version": "6.5.0", + "language": "JAVASCRIPT", + "artifactName": "@google-cloud/aiplatform", + "id": "b753f790-11a4-4fc1-a364-393a85e1e90c", + "createTime": "2026-03-02T16:41:39.642Z" + }, + { + "changes": [ + { + "type": "feat", + "sha": "32115d95be2fc2e06da22aa5101c94ddb3bf82db", + "message": "[datamanager] add `UserListService` for creating and managing user lists", + "issues": [ + "7290" + ] + } + ], + "version": "0.2.0", + "language": "JAVASCRIPT", + "artifactName": "@google-ads/datamanager", + "id": "9b0bb1b0-9564-4ab3-81d3-cd76c26a94b2", + "createTime": "2026-03-02T16:41:39.608Z" + }, + { + "changes": [ + { + "type": "fix", + "sha": "f1456f9e8bdd5c2b2d579d6a451036d98b8ee26e", + "message": "Bug preventing apiPath generation when apiId includes letter v", + "issues": [] + }, + { + "type": "fix", + "sha": "6d705f413ead1e2adfe3dc1d703d4637ab36b6d9", + "message": "Bug preventing apiPath generation when apiId includes letter v", + "issues": [] + }, + { + "type": "fix", + "sha": "76baebbdc05758953af5550b71f3144a7eafbfb4", + "message": "Bug preventing apiPath generation when apiId includes letter v", + "issues": [] + } + ], + "version": "0.1.7", + "language": "JAVASCRIPT", + "artifactName": "gapic-node-processing", + "id": "0bce40fb-fc26-4fef-ba28-8f1c2c90521c", + "createTime": "2026-03-02T16:41:39.566Z" + }, { "changes": [ { @@ -68363,5 +68685,5 @@ "createTime": "2023-01-28T04:18:24.718Z" } ], - "updateTime": "2026-02-19T13:03:03.636Z" + "updateTime": "2026-03-02T16:41:40.032Z" } \ No newline at end of file diff --git a/ci/run_conditional_tests.sh b/ci/run_conditional_tests.sh index 1dc4fb72458..573a74e2c04 100755 --- a/ci/run_conditional_tests.sh +++ b/ci/run_conditional_tests.sh @@ -88,7 +88,7 @@ tests_with_credentials="packages/google-analytics-admin/ packages/google-area120 # on Windows due to incompatible npm scripts. # # Until these packages can be updated to be OS agnostic, we will skip them on Windows. -windows_exempt_tests=".github/scripts/fixtures/ .github/scripts/tests/ packages/gapic-node-processing/ packages/google-cloud-discoveryengine/ packages/typeless-sample-bot/" +windows_exempt_tests=".github/scripts/fixtures/ .github/scripts/tests/ packages/gapic-node-processing/ packages/typeless-sample-bot/" for subdir in ${subdirs[@]}; do for d in `ls -d ${subdir}/*/`; do diff --git a/handwritten/spanner/.OwlBot.yaml b/handwritten/spanner/.OwlBot.yaml new file mode 100644 index 00000000000..0e4f41709ed --- /dev/null +++ b/handwritten/spanner/.OwlBot.yaml @@ -0,0 +1,30 @@ +# Copyright 2021 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. + + +deep-remove-regex: + - /owl-bot-staging + +deep-copy-regex: + - source: /google/spanner/(v.*)/.*-nodejs + dest: /owl-bot-staging/spanner/$1 + - source: /google/spanner/(admin/database/v.*)/.*-nodejs + dest: /owl-bot-staging/spanner/$1 + - source: /google/spanner/(admin/instance/v.*)/.*-nodejs + dest: /owl-bot-staging/spanner/$1 + - source: /google/spanner/(executor/v.*)/.*-nodejs + dest: /owl-bot-staging/spanner/$1 + +begin-after-commit-hash: 46f25fb1121747b994ff5818963fda84b5e6bfd3 + diff --git a/handwritten/spanner/.devcontainer/Dockerfile b/handwritten/spanner/.devcontainer/Dockerfile new file mode 100644 index 00000000000..a90e0fbda36 --- /dev/null +++ b/handwritten/spanner/.devcontainer/Dockerfile @@ -0,0 +1,16 @@ +ARG VARIANT="18" +FROM mcr.microsoft.com/devcontainers/typescript-node:${VARIANT} + +RUN apt-get update && export DEBIAN_FRONTEND=noninteractive + +RUN type -p curl >/dev/null || (apt-get install curl -y) + +# install gh +RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \ +&& chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \ +&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null \ +&& apt-get update \ +&& apt-get install gh -y + +# install gloud sdk +RUN echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] http://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list && curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - && apt-get update -y && apt-get install google-cloud-cli -y \ No newline at end of file diff --git a/handwritten/spanner/.devcontainer/devcontainer.json b/handwritten/spanner/.devcontainer/devcontainer.json new file mode 100644 index 00000000000..138324fdd2b --- /dev/null +++ b/handwritten/spanner/.devcontainer/devcontainer.json @@ -0,0 +1,24 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/typescript-node +{ + "name": "Node.js & TypeScript", + "build": { + // Sets the run context to one level up instead of the .devcontainer folder. + "args": { "VARIANT": "18" }, + // Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename. + "dockerfile": "Dockerfile" + }, + + "postCreateCommand": "bash .devcontainer/postCreate.sh", + + "customizations": { + "vscode": { + "settings": { + "debug.javascript.autoAttachFilter":"smart" + }, + "extensions": [ + "ms-azuretools.vscode-docker" + ] + } + } +} diff --git a/handwritten/spanner/.devcontainer/postCreate.sh b/handwritten/spanner/.devcontainer/postCreate.sh new file mode 100644 index 00000000000..b627d596f0f --- /dev/null +++ b/handwritten/spanner/.devcontainer/postCreate.sh @@ -0,0 +1,4 @@ +echo "Post Create Starting" + +npm install +npm test \ No newline at end of file diff --git a/handwritten/spanner/.eslintignore b/handwritten/spanner/.eslintignore new file mode 100644 index 00000000000..ea5b04aebe6 --- /dev/null +++ b/handwritten/spanner/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/coverage +test/fixtures +build/ +docs/ +protos/ +samples/generated/ diff --git a/handwritten/spanner/.eslintrc.json b/handwritten/spanner/.eslintrc.json new file mode 100644 index 00000000000..78215349546 --- /dev/null +++ b/handwritten/spanner/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "./node_modules/gts" +} diff --git a/handwritten/spanner/.gitattributes b/handwritten/spanner/.gitattributes new file mode 100644 index 00000000000..33739cb74e4 --- /dev/null +++ b/handwritten/spanner/.gitattributes @@ -0,0 +1,4 @@ +*.ts text eol=lf +*.js text eol=lf +protos/* linguist-generated +**/api-extractor.json linguist-language=JSON-with-Comments diff --git a/handwritten/spanner/.gitignore b/handwritten/spanner/.gitignore new file mode 100644 index 00000000000..d4f03a0df2e --- /dev/null +++ b/handwritten/spanner/.gitignore @@ -0,0 +1,14 @@ +**/*.log +**/node_modules +/.coverage +/coverage +/.nyc_output +/docs/ +/out/ +/build/ +system-test/secrets.js +system-test/*key.json +*.lock +.DS_Store +package-lock.json +__pycache__ diff --git a/handwritten/spanner/.jsdoc.js b/handwritten/spanner/.jsdoc.js new file mode 100644 index 00000000000..89dbb7cd9e2 --- /dev/null +++ b/handwritten/spanner/.jsdoc.js @@ -0,0 +1,55 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +'use strict'; + +module.exports = { + opts: { + readme: './README.md', + package: './package.json', + template: './node_modules/jsdoc-fresh', + recurse: true, + verbose: true, + destination: './docs/' + }, + plugins: [ + 'plugins/markdown', + 'jsdoc-region-tag' + ], + source: { + excludePattern: '(^|\\/|\\\\)[._]', + include: [ + 'build/src', + 'protos' + ], + includePattern: '\\.js$' + }, + templates: { + copyright: 'Copyright 2026 Google LLC', + includeDate: false, + sourceFiles: false, + systemName: '@google-cloud/spanner', + theme: 'lumen', + default: { + outputSourceFiles: false + } + }, + markdown: { + idInHeadings: true + } +}; diff --git a/handwritten/spanner/.kokoro/.gitattributes b/handwritten/spanner/.kokoro/.gitattributes new file mode 100644 index 00000000000..87acd4f484e --- /dev/null +++ b/handwritten/spanner/.kokoro/.gitattributes @@ -0,0 +1 @@ +* linguist-generated=true diff --git a/handwritten/spanner/.kokoro/cleanup.sh b/handwritten/spanner/.kokoro/cleanup.sh new file mode 100755 index 00000000000..cd841d81e5f --- /dev/null +++ b/handwritten/spanner/.kokoro/cleanup.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=/home/node/.npm-global + +# Setup service account credentials. +export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/spanner-key.json +export GCLOUD_PROJECT=long-door-651 + +cd $(dirname $0)/.. + +npm install + +npm run cleanup diff --git a/handwritten/spanner/.kokoro/common.cfg b/handwritten/spanner/.kokoro/common.cfg new file mode 100644 index 00000000000..f115a8b7026 --- /dev/null +++ b/handwritten/spanner/.kokoro/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-spanner/handwritten/spanner/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/test.sh" +} diff --git a/handwritten/spanner/.kokoro/continuous/node18/common.cfg b/handwritten/spanner/.kokoro/continuous/node18/common.cfg new file mode 100644 index 00000000000..f115a8b7026 --- /dev/null +++ b/handwritten/spanner/.kokoro/continuous/node18/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-spanner/handwritten/spanner/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/test.sh" +} diff --git a/handwritten/spanner/.kokoro/continuous/node18/lint.cfg b/handwritten/spanner/.kokoro/continuous/node18/lint.cfg new file mode 100644 index 00000000000..8aeed86c220 --- /dev/null +++ b/handwritten/spanner/.kokoro/continuous/node18/lint.cfg @@ -0,0 +1,4 @@ +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/lint.sh" +} diff --git a/handwritten/spanner/.kokoro/continuous/node18/samples-test.cfg b/handwritten/spanner/.kokoro/continuous/node18/samples-test.cfg new file mode 100644 index 00000000000..3c4bbe887e3 --- /dev/null +++ b/handwritten/spanner/.kokoro/continuous/node18/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/spanner/.kokoro/continuous/node18/system-test.cfg b/handwritten/spanner/.kokoro/continuous/node18/system-test.cfg new file mode 100644 index 00000000000..b50a1195edc --- /dev/null +++ b/handwritten/spanner/.kokoro/continuous/node18/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/spanner/.kokoro/continuous/node18/test.cfg b/handwritten/spanner/.kokoro/continuous/node18/test.cfg new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/spanner/.kokoro/docs.sh b/handwritten/spanner/.kokoro/docs.sh new file mode 100755 index 00000000000..85901242b5e --- /dev/null +++ b/handwritten/spanner/.kokoro/docs.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +cd $(dirname $0)/.. + +npm install + +npm run docs-test diff --git a/handwritten/spanner/.kokoro/lint.sh b/handwritten/spanner/.kokoro/lint.sh new file mode 100755 index 00000000000..c7ffa6438b0 --- /dev/null +++ b/handwritten/spanner/.kokoro/lint.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global +export PATH="${NPM_CONFIG_PREFIX}/bin:${PATH}" + +# Ensure the npm global directory is writable, otherwise rebuild `npm` +mkdir -p ${NPM_CONFIG_PREFIX}/lib +npm config -g ls || npm i -g npm@`npm --version` + +cd $(dirname $0)/.. + +npm install + +# Install and link samples +if [ -f samples/package.json ]; then + cd samples/ + npm link ../ + npm install + cd .. +fi + +npm run lint diff --git a/handwritten/spanner/.kokoro/populate-secrets.sh b/handwritten/spanner/.kokoro/populate-secrets.sh new file mode 100755 index 00000000000..deb2b199eb4 --- /dev/null +++ b/handwritten/spanner/.kokoro/populate-secrets.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# Copyright 2020 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. + +# This file is called in the early stage of `trampoline_v2.sh` to +# populate secrets needed for the CI builds. + +set -eo pipefail + +function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;} +function msg { println "$*" >&2 ;} +function println { printf '%s\n' "$(now) $*" ;} + +# Populates requested secrets set in SECRET_MANAGER_KEYS + +# In Kokoro CI builds, we use the service account attached to the +# Kokoro VM. This means we need to setup auth on other CI systems. +# For local run, we just use the gcloud command for retrieving the +# secrets. + +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + GCLOUD_COMMANDS=( + "docker" + "run" + "--entrypoint=gcloud" + "--volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR}" + "gcr.io/google.com/cloudsdktool/cloud-sdk" + ) + if [[ "${TRAMPOLINE_CI:-}" == "kokoro" ]]; then + SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" + else + echo "Authentication for this CI system is not implemented yet." + exit 2 + # TODO: Determine appropriate SECRET_LOCATION and the GCLOUD_COMMANDS. + fi +else + # For local run, use /dev/shm or temporary directory for + # KOKORO_GFILE_DIR. + if [[ -d "/dev/shm" ]]; then + export KOKORO_GFILE_DIR=/dev/shm + else + export KOKORO_GFILE_DIR=$(mktemp -d -t ci-XXXXXXXX) + fi + SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" + GCLOUD_COMMANDS=("gcloud") +fi + +msg "Creating folder on disk for secrets: ${SECRET_LOCATION}" +mkdir -p ${SECRET_LOCATION} + +for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g") +do + msg "Retrieving secret ${key}" + "${GCLOUD_COMMANDS[@]}" \ + secrets versions access latest \ + --project cloud-devrel-kokoro-resources \ + --secret $key > \ + "$SECRET_LOCATION/$key" + if [[ $? == 0 ]]; then + msg "Secret written to ${SECRET_LOCATION}/${key}" + else + msg "Error retrieving secret ${key}" + exit 2 + fi +done diff --git a/handwritten/spanner/.kokoro/presubmit/node18/common.cfg b/handwritten/spanner/.kokoro/presubmit/node18/common.cfg new file mode 100644 index 00000000000..f115a8b7026 --- /dev/null +++ b/handwritten/spanner/.kokoro/presubmit/node18/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-spanner/handwritten/spanner/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/test.sh" +} diff --git a/handwritten/spanner/.kokoro/presubmit/node18/samples-test.cfg b/handwritten/spanner/.kokoro/presubmit/node18/samples-test.cfg new file mode 100644 index 00000000000..3c4bbe887e3 --- /dev/null +++ b/handwritten/spanner/.kokoro/presubmit/node18/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/spanner/.kokoro/presubmit/node18/system-test-regular-session.cfg b/handwritten/spanner/.kokoro/presubmit/node18/system-test-regular-session.cfg new file mode 100644 index 00000000000..ffed97284db --- /dev/null +++ b/handwritten/spanner/.kokoro/presubmit/node18/system-test-regular-session.cfg @@ -0,0 +1,27 @@ +# Download resources(service account key, etc.) for system tests when multiplexed session is enabled +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} + +env_vars: { + key: "GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS" + value: "false" +} + +env_vars: { + key: "GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS" + value: "false" +} + +env_vars: { + key: "GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW" + value: "false" +} \ No newline at end of file diff --git a/handwritten/spanner/.kokoro/presubmit/node18/system-test.cfg b/handwritten/spanner/.kokoro/presubmit/node18/system-test.cfg new file mode 100644 index 00000000000..b50a1195edc --- /dev/null +++ b/handwritten/spanner/.kokoro/presubmit/node18/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/spanner/.kokoro/presubmit/node18/test.cfg b/handwritten/spanner/.kokoro/presubmit/node18/test.cfg new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/spanner/.kokoro/presubmit/windows/common.cfg b/handwritten/spanner/.kokoro/presubmit/windows/common.cfg new file mode 100644 index 00000000000..d6e25e0b1b8 --- /dev/null +++ b/handwritten/spanner/.kokoro/presubmit/windows/common.cfg @@ -0,0 +1,2 @@ +# Format: //devtools/kokoro/config/proto/build.proto + diff --git a/handwritten/spanner/.kokoro/presubmit/windows/test.cfg b/handwritten/spanner/.kokoro/presubmit/windows/test.cfg new file mode 100644 index 00000000000..f6f23ee43a1 --- /dev/null +++ b/handwritten/spanner/.kokoro/presubmit/windows/test.cfg @@ -0,0 +1,2 @@ +# Use the test file directly +build_file: "nodejs-spanner/handwritten/spanner/.kokoro/test.bat" diff --git a/handwritten/spanner/.kokoro/publish.sh b/handwritten/spanner/.kokoro/publish.sh new file mode 100755 index 00000000000..ca1d47af347 --- /dev/null +++ b/handwritten/spanner/.kokoro/publish.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +# Start the releasetool reporter +python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script + +cd $(dirname $0)/.. + +NPM_TOKEN=$(cat $KOKORO_KEYSTORE_DIR/73713_google-cloud-npm-token-1) +echo "//wombat-dressing-room.appspot.com/:_authToken=${NPM_TOKEN}" > ~/.npmrc + +npm install +npm pack . +# npm provides no way to specify, observe, or predict the name of the tarball +# file it generates. We have to look in the current directory for the freshest +# .tgz file. +TARBALL=$(ls -1 -t *.tgz | head -1) + +npm publish --access=public --registry=https://wombat-dressing-room.appspot.com "$TARBALL" + +# Kokoro collects *.tgz and package-lock.json files and stores them in Placer +# so we can generate SBOMs and attestations. +# However, we *don't* want Kokoro to collect package-lock.json and *.tgz files +# that happened to be installed with dependencies. +find node_modules -name package-lock.json -o -name "*.tgz" | xargs rm -f \ No newline at end of file diff --git a/handwritten/spanner/.kokoro/release/cleanup.cfg b/handwritten/spanner/.kokoro/release/cleanup.cfg new file mode 100644 index 00000000000..fd3d30eb3a0 --- /dev/null +++ b/handwritten/spanner/.kokoro/release/cleanup.cfg @@ -0,0 +1,27 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +# Use the trampoline script to run in docker. +build_file: "nodejs-spanner/handwritten/spanner/.kokoro/trampoline.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:8-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/cleanup.sh" +} diff --git a/handwritten/spanner/.kokoro/release/common.cfg b/handwritten/spanner/.kokoro/release/common.cfg new file mode 100644 index 00000000000..3ba2eb095fe --- /dev/null +++ b/handwritten/spanner/.kokoro/release/common.cfg @@ -0,0 +1,8 @@ +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "yoshi-automation-github-key" + } + } +} diff --git a/handwritten/spanner/.kokoro/release/docs-devsite.cfg b/handwritten/spanner/.kokoro/release/docs-devsite.cfg new file mode 100644 index 00000000000..e4a1172942c --- /dev/null +++ b/handwritten/spanner/.kokoro/release/docs-devsite.cfg @@ -0,0 +1,26 @@ +# service account used to publish up-to-date docs. +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +# doc publications use a Python image. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-spanner/handwritten/spanner/.kokoro/trampoline_v2.sh" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/release/docs-devsite.sh" +} diff --git a/handwritten/spanner/.kokoro/release/docs-devsite.sh b/handwritten/spanner/.kokoro/release/docs-devsite.sh new file mode 100755 index 00000000000..81a89f6c172 --- /dev/null +++ b/handwritten/spanner/.kokoro/release/docs-devsite.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# Copyright 2021 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. + +set -eo pipefail + +if [[ -z "$CREDENTIALS" ]]; then + # if CREDENTIALS are explicitly set, assume we're testing locally + # and don't set NPM_CONFIG_PREFIX. + export NPM_CONFIG_PREFIX=${HOME}/.npm-global + export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin" + cd $(dirname $0)/../.. +fi + +npm install +npm install --no-save @google-cloud/cloud-rad@^0.4.0 +# publish docs to devsite +npx @google-cloud/cloud-rad . cloud-rad diff --git a/handwritten/spanner/.kokoro/release/docs.cfg b/handwritten/spanner/.kokoro/release/docs.cfg new file mode 100644 index 00000000000..3e74f70d200 --- /dev/null +++ b/handwritten/spanner/.kokoro/release/docs.cfg @@ -0,0 +1,26 @@ +# service account used to publish up-to-date docs. +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +# doc publications use a Python image. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-spanner/handwritten/spanner/.kokoro/trampoline_v2.sh" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/release/docs.sh" +} diff --git a/handwritten/spanner/.kokoro/release/docs.sh b/handwritten/spanner/.kokoro/release/docs.sh new file mode 100755 index 00000000000..e9079a60530 --- /dev/null +++ b/handwritten/spanner/.kokoro/release/docs.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +# Copyright 2019 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. + +set -eo pipefail + +# 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. + export NPM_CONFIG_PREFIX=${HOME}/.npm-global + export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin" + cd $(dirname $0)/../.. +fi +npm install +npm run docs + +# create docs.metadata, based on package.json and .repo-metadata.json. +npm i json@9.0.6 -g +python3 -m docuploader create-metadata \ + --name=$(cat .repo-metadata.json | json name) \ + --version=$(cat package.json | json version) \ + --language=$(cat .repo-metadata.json | json language) \ + --distribution-name=$(cat .repo-metadata.json | json distribution_name) \ + --product-page=$(cat .repo-metadata.json | json product_documentation) \ + --github-repository=$(cat .repo-metadata.json | json repo) \ + --issue-tracker=$(cat .repo-metadata.json | json issue_tracker) +cp docs.metadata ./docs/docs.metadata + +# deploy the docs. +if [[ -z "$CREDENTIALS" ]]; then + CREDENTIALS=${KOKORO_KEYSTORE_DIR}/73713_docuploader_service_account +fi +if [[ -z "$BUCKET" ]]; then + BUCKET=docs-staging +fi +python3 -m docuploader upload ./docs --credentials $CREDENTIALS --staging-bucket $BUCKET diff --git a/handwritten/spanner/.kokoro/release/publish.cfg b/handwritten/spanner/.kokoro/release/publish.cfg new file mode 100644 index 00000000000..29842f29a88 --- /dev/null +++ b/handwritten/spanner/.kokoro/release/publish.cfg @@ -0,0 +1,51 @@ +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google-cloud-npm-token-1" + } + } +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-spanner/handwritten/spanner/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-spanner/handwritten/spanner/.kokoro/publish.sh" +} + +# Store the packages we uploaded to npmjs.com and their corresponding +# package-lock.jsons in Placer. That way, we have a record of exactly +# what we published, and which version of which tools we used to publish +# it, which we can use to generate SBOMs and attestations. +action { + define_artifacts { + regex: "github/**/*.tgz" + regex: "github/**/package-lock.json" + strip_prefix: "github" + } +} diff --git a/handwritten/spanner/.kokoro/samples-test.sh b/handwritten/spanner/.kokoro/samples-test.sh new file mode 100755 index 00000000000..a05dabce172 --- /dev/null +++ b/handwritten/spanner/.kokoro/samples-test.sh @@ -0,0 +1,76 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +# 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 +export GCLOUD_PROJECT=long-door-651 + +cd $(dirname $0)/.. + +# Run a pre-test hook, if a pre-samples-test.sh is in the project +if [ -f .kokoro/pre-samples-test.sh ]; then + set +x + . .kokoro/pre-samples-test.sh + set -x +fi + +if [ -f samples/package.json ]; then + npm install + + # Install and link samples + cd samples/ + npm link ../ + npm install + cd .. + # If tests are running against main branch, configure flakybot + # to open issues on failures: + if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP + else + # Check if there are any changes in the "samples" directory only for presubmits. + if git diff --quiet HEAD main -- samples/; then + echo "No changes detected in the samples directory. Skipping sample tests." + exit 0 + fi + fi + + npm run samples-test +fi + +# codecov combines coverage across integration and unit tests. Include +# the logic below for any environment you wish to collect coverage for: +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 + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/spanner/.kokoro/system-test.sh b/handwritten/spanner/.kokoro/system-test.sh new file mode 100755 index 00000000000..a90d5cfec89 --- /dev/null +++ b/handwritten/spanner/.kokoro/system-test.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +# Setup service account credentials. +export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/secret_manager/long-door-651-kokoro-system-test-service-account +export GCLOUD_PROJECT=long-door-651 + +cd $(dirname $0)/.. + +# Run a pre-test hook, if a pre-system-test.sh is in the project +if [ -f .kokoro/pre-system-test.sh ]; then + set +x + . .kokoro/pre-system-test.sh + set -x +fi + +npm install + +# If tests are running against main branch, configure flakybot +# to open issues on failures: +if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP +fi + +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=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 + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/spanner/.kokoro/test.bat b/handwritten/spanner/.kokoro/test.bat new file mode 100644 index 00000000000..caf825656c2 --- /dev/null +++ b/handwritten/spanner/.kokoro/test.bat @@ -0,0 +1,33 @@ +@rem Copyright 2018 Google LLC. All rights reserved. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. + +@echo "Starting Windows build" + +cd /d %~dp0 +cd .. + +@rem npm path is not currently set in our image, we should fix this next time +@rem we upgrade Node.js in the image: +SET PATH=%PATH%;/cygdrive/c/Program Files/nodejs/npm + +call nvm use 18 +call which node + +call npm install || goto :error +call npm run test || goto :error + +goto :EOF + +:error +exit /b 1 diff --git a/handwritten/spanner/.kokoro/test.sh b/handwritten/spanner/.kokoro/test.sh new file mode 100755 index 00000000000..0d9f6392a75 --- /dev/null +++ b/handwritten/spanner/.kokoro/test.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +cd $(dirname $0)/.. + +npm install +# If tests are running against main branch, configure flakybot +# to open issues on failures: +if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP +fi +# Unit tests exercise the entire API surface, which may include +# deprecation warnings: +export MOCHA_THROW_DEPRECATION=false +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=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 + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/spanner/.kokoro/trampoline.sh b/handwritten/spanner/.kokoro/trampoline.sh new file mode 100755 index 00000000000..f693a1ce7aa --- /dev/null +++ b/handwritten/spanner/.kokoro/trampoline.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This file is not used any more, but we keep this file for making it +# easy to roll back. +# TODO: Remove this file from the template. + +set -eo pipefail + +# Always run the cleanup script, regardless of the success of bouncing into +# the container. +function cleanup() { + chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + echo "cleanup"; +} +trap cleanup EXIT + +$(dirname $0)/populate-secrets.sh # Secret Manager secrets. +python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" diff --git a/handwritten/spanner/.kokoro/trampoline_v2.sh b/handwritten/spanner/.kokoro/trampoline_v2.sh new file mode 100755 index 00000000000..2ed993bbdff --- /dev/null +++ b/handwritten/spanner/.kokoro/trampoline_v2.sh @@ -0,0 +1,513 @@ +#!/usr/bin/env bash +# Copyright 2020 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. + +# trampoline_v2.sh +# +# If you want to make a change to this file, consider doing so at: +# https://github.com/googlecloudplatform/docker-ci-helper +# +# This script is for running CI builds. For Kokoro builds, we +# set this script to `build_file` field in the Kokoro configuration. + +# This script does 3 things. +# +# 1. Prepare the Docker image for the test +# 2. Run the Docker with appropriate flags to run the test +# 3. Upload the newly built Docker image +# +# in a way that is somewhat compatible with trampoline_v1. +# +# These environment variables are required: +# TRAMPOLINE_IMAGE: The docker image to use. +# TRAMPOLINE_DOCKERFILE: The location of the Dockerfile. +# +# You can optionally change these environment variables: +# TRAMPOLINE_IMAGE_UPLOAD: +# (true|false): Whether to upload the Docker image after the +# successful builds. +# TRAMPOLINE_BUILD_FILE: The script to run in the docker container. +# TRAMPOLINE_WORKSPACE: The workspace path in the docker container. +# Defaults to /workspace. +# Potentially there are some repo specific envvars in .trampolinerc in +# the project root. +# +# Here is an example for running this script. +# TRAMPOLINE_IMAGE=gcr.io/cloud-devrel-kokoro-resources/node:18-user \ +# TRAMPOLINE_BUILD_FILE=.kokoro/system-test.sh \ +# .kokoro/trampoline_v2.sh + +set -euo pipefail + +TRAMPOLINE_VERSION="2.0.7" + +if command -v tput >/dev/null && [[ -n "${TERM:-}" ]]; then + readonly IO_COLOR_RED="$(tput setaf 1)" + readonly IO_COLOR_GREEN="$(tput setaf 2)" + readonly IO_COLOR_YELLOW="$(tput setaf 3)" + readonly IO_COLOR_RESET="$(tput sgr0)" +else + readonly IO_COLOR_RED="" + readonly IO_COLOR_GREEN="" + readonly IO_COLOR_YELLOW="" + readonly IO_COLOR_RESET="" +fi + +function function_exists { + [ $(LC_ALL=C type -t $1)"" == "function" ] +} + +# Logs a message using the given color. The first argument must be one +# of the IO_COLOR_* variables defined above, such as +# "${IO_COLOR_YELLOW}". The remaining arguments will be logged in the +# given color. The log message will also have an RFC-3339 timestamp +# prepended (in UTC). You can disable the color output by setting +# TERM=vt100. +function log_impl() { + local color="$1" + shift + local timestamp="$(date -u "+%Y-%m-%dT%H:%M:%SZ")" + echo "================================================================" + echo "${color}${timestamp}:" "$@" "${IO_COLOR_RESET}" + echo "================================================================" +} + +# Logs the given message with normal coloring and a timestamp. +function log() { + log_impl "${IO_COLOR_RESET}" "$@" +} + +# Logs the given message in green with a timestamp. +function log_green() { + log_impl "${IO_COLOR_GREEN}" "$@" +} + +# Logs the given message in yellow with a timestamp. +function log_yellow() { + log_impl "${IO_COLOR_YELLOW}" "$@" +} + +# Logs the given message in red with a timestamp. +function log_red() { + log_impl "${IO_COLOR_RED}" "$@" +} + +readonly tmpdir=$(mktemp -d -t ci-XXXXXXXX) +readonly tmphome="${tmpdir}/h" +mkdir -p "${tmphome}" + +function cleanup() { + rm -rf "${tmpdir}" +} +trap cleanup EXIT + +RUNNING_IN_CI="${RUNNING_IN_CI:-false}" + +# The workspace in the container, defaults to /workspace. +TRAMPOLINE_WORKSPACE="${TRAMPOLINE_WORKSPACE:-/workspace}" + +pass_down_envvars=( + # TRAMPOLINE_V2 variables. + # Tells scripts whether they are running as part of CI or not. + "RUNNING_IN_CI" + # Indicates which CI system we're in. + "TRAMPOLINE_CI" + # Indicates the version of the script. + "TRAMPOLINE_VERSION" + # Contains path to build artifacts being executed. + "KOKORO_BUILD_ARTIFACTS_SUBDIR" +) + +log_yellow "Building with Trampoline ${TRAMPOLINE_VERSION}" + +# Detect which CI systems we're in. If we're in any of the CI systems +# we support, `RUNNING_IN_CI` will be true and `TRAMPOLINE_CI` will be +# the name of the CI system. Both envvars will be passing down to the +# container for telling which CI system we're in. +if [[ -n "${KOKORO_BUILD_ID:-}" ]]; then + # descriptive env var for indicating it's on CI. + RUNNING_IN_CI="true" + TRAMPOLINE_CI="kokoro" + if [[ "${TRAMPOLINE_USE_LEGACY_SERVICE_ACCOUNT:-}" == "true" ]]; then + if [[ ! -f "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" ]]; then + log_red "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json does not exist. Did you forget to mount cloud-devrel-kokoro-resources/trampoline? Aborting." + exit 1 + fi + # This service account will be activated later. + TRAMPOLINE_SERVICE_ACCOUNT="${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" + else + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + gcloud auth list + fi + log_yellow "Configuring Container Registry access" + gcloud auth configure-docker --quiet + fi + pass_down_envvars+=( + # KOKORO dynamic variables. + "KOKORO_BUILD_NUMBER" + "KOKORO_BUILD_ID" + "KOKORO_JOB_NAME" + "KOKORO_GIT_COMMIT" + "KOKORO_GITHUB_COMMIT" + "KOKORO_GITHUB_PULL_REQUEST_NUMBER" + "KOKORO_GITHUB_PULL_REQUEST_COMMIT" + # For flakybot + "KOKORO_GITHUB_COMMIT_URL" + "KOKORO_GITHUB_PULL_REQUEST_URL" + "GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS" + "GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS" + "GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW" + ) +elif [[ "${TRAVIS:-}" == "true" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="travis" + pass_down_envvars+=( + "TRAVIS_BRANCH" + "TRAVIS_BUILD_ID" + "TRAVIS_BUILD_NUMBER" + "TRAVIS_BUILD_WEB_URL" + "TRAVIS_COMMIT" + "TRAVIS_COMMIT_MESSAGE" + "TRAVIS_COMMIT_RANGE" + "TRAVIS_JOB_NAME" + "TRAVIS_JOB_NUMBER" + "TRAVIS_JOB_WEB_URL" + "TRAVIS_PULL_REQUEST" + "TRAVIS_PULL_REQUEST_BRANCH" + "TRAVIS_PULL_REQUEST_SHA" + "TRAVIS_PULL_REQUEST_SLUG" + "TRAVIS_REPO_SLUG" + "TRAVIS_SECURE_ENV_VARS" + "TRAVIS_TAG" + ) +elif [[ -n "${GITHUB_RUN_ID:-}" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="github-workflow" + pass_down_envvars+=( + "GITHUB_WORKFLOW" + "GITHUB_RUN_ID" + "GITHUB_RUN_NUMBER" + "GITHUB_ACTION" + "GITHUB_ACTIONS" + "GITHUB_ACTOR" + "GITHUB_REPOSITORY" + "GITHUB_EVENT_NAME" + "GITHUB_EVENT_PATH" + "GITHUB_SHA" + "GITHUB_REF" + "GITHUB_HEAD_REF" + "GITHUB_BASE_REF" + ) +elif [[ "${CIRCLECI:-}" == "true" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="circleci" + pass_down_envvars+=( + "CIRCLE_BRANCH" + "CIRCLE_BUILD_NUM" + "CIRCLE_BUILD_URL" + "CIRCLE_COMPARE_URL" + "CIRCLE_JOB" + "CIRCLE_NODE_INDEX" + "CIRCLE_NODE_TOTAL" + "CIRCLE_PREVIOUS_BUILD_NUM" + "CIRCLE_PROJECT_REPONAME" + "CIRCLE_PROJECT_USERNAME" + "CIRCLE_REPOSITORY_URL" + "CIRCLE_SHA1" + "CIRCLE_STAGE" + "CIRCLE_USERNAME" + "CIRCLE_WORKFLOW_ID" + "CIRCLE_WORKFLOW_JOB_ID" + "CIRCLE_WORKFLOW_UPSTREAM_JOB_IDS" + "CIRCLE_WORKFLOW_WORKSPACE_ID" + ) +fi + +# Configure the service account for pulling the docker image. +function repo_root() { + local dir="$1" + while [[ ! -d "${dir}/.git" ]]; do + dir="$(dirname "$dir")" + done + echo "${dir}" +} + +# Detect the project root. In CI builds, we assume the script is in +# the git tree and traverse from there, otherwise, traverse from `pwd` +# to find `.git` directory. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + PROGRAM_PATH="$(realpath "$0")" + PROGRAM_DIR="$(dirname "${PROGRAM_PATH}")" + PROJECT_ROOT="$(repo_root "${PROGRAM_DIR}")/handwritten/spanner" +else + PROJECT_ROOT="$(repo_root $(pwd))/handwritten/spanner" +fi + +log_yellow "Changing to the project root: ${PROJECT_ROOT}." +cd "${PROJECT_ROOT}" + +# Auto-injected conditional check +# Check if the package directory has changes. If not, skip tests. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + # The package path is hardcoded during migration + RELATIVE_PKG_PATH="handwritten/spanner" + + echo "Checking for changes in ${RELATIVE_PKG_PATH}..." + + # Determine the diff range based on the CI system/event + # Safe default: HEAD~1..HEAD + DIFF_RANGE="HEAD~1..HEAD" + + if git diff --quiet "${DIFF_RANGE}" -- "${RELATIVE_PKG_PATH}"; then + echo "No changes detected in ${RELATIVE_PKG_PATH}. Skipping tests." + exit 0 + else + echo "Changes detected in ${RELATIVE_PKG_PATH}. Proceeding with tests." + fi +fi + +# To support relative path for `TRAMPOLINE_SERVICE_ACCOUNT`, we need +# to use this environment variable in `PROJECT_ROOT`. +if [[ -n "${TRAMPOLINE_SERVICE_ACCOUNT:-}" ]]; then + + mkdir -p "${tmpdir}/gcloud" + gcloud_config_dir="${tmpdir}/gcloud" + + log_yellow "Using isolated gcloud config: ${gcloud_config_dir}." + export CLOUDSDK_CONFIG="${gcloud_config_dir}" + + log_yellow "Using ${TRAMPOLINE_SERVICE_ACCOUNT} for authentication." + gcloud auth activate-service-account \ + --key-file "${TRAMPOLINE_SERVICE_ACCOUNT}" + log_yellow "Configuring Container Registry access" + gcloud auth configure-docker --quiet +fi + +required_envvars=( + # The basic trampoline configurations. + "TRAMPOLINE_IMAGE" + "TRAMPOLINE_BUILD_FILE" +) + +if [[ -f "${PROJECT_ROOT}/.trampolinerc" ]]; then + source "${PROJECT_ROOT}/.trampolinerc" +fi + +log_yellow "Checking environment variables." +for e in "${required_envvars[@]}" +do + if [[ -z "${!e:-}" ]]; then + log "Missing ${e} env var. Aborting." + exit 1 + fi +done + +# We want to support legacy style TRAMPOLINE_BUILD_FILE used with V1 +# script: e.g. "github/repo-name/.kokoro/run_tests.sh" +TRAMPOLINE_BUILD_FILE="${TRAMPOLINE_BUILD_FILE#github/*/}" +log_yellow "Using TRAMPOLINE_BUILD_FILE: ${TRAMPOLINE_BUILD_FILE}" + +# ignore error on docker operations and test execution +set +e + +log_yellow "Preparing Docker image." +# We only download the docker image in CI builds. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + # Download the docker image specified by `TRAMPOLINE_IMAGE` + + # We may want to add --max-concurrent-downloads flag. + + log_yellow "Start pulling the Docker image: ${TRAMPOLINE_IMAGE}." + if docker pull "${TRAMPOLINE_IMAGE}"; then + log_green "Finished pulling the Docker image: ${TRAMPOLINE_IMAGE}." + has_image="true" + else + log_red "Failed pulling the Docker image: ${TRAMPOLINE_IMAGE}." + has_image="false" + fi +else + # For local run, check if we have the image. + if docker images "${TRAMPOLINE_IMAGE}" | grep "${TRAMPOLINE_IMAGE%:*}"; then + has_image="true" + else + has_image="false" + fi +fi + + +# The default user for a Docker container has uid 0 (root). To avoid +# creating root-owned files in the build directory we tell docker to +# use the current user ID. +user_uid="$(id -u)" +user_gid="$(id -g)" +user_name="$(id -un)" + +# To allow docker in docker, we add the user to the docker group in +# the host os. +docker_gid=$(cut -d: -f3 < <(getent group docker)) + +update_cache="false" +if [[ "${TRAMPOLINE_DOCKERFILE:-none}" != "none" ]]; then + # Build the Docker image from the source. + context_dir=$(dirname "${TRAMPOLINE_DOCKERFILE}") + docker_build_flags=( + "-f" "${TRAMPOLINE_DOCKERFILE}" + "-t" "${TRAMPOLINE_IMAGE}" + "--build-arg" "UID=${user_uid}" + "--build-arg" "USERNAME=${user_name}" + ) + if [[ "${has_image}" == "true" ]]; then + docker_build_flags+=("--cache-from" "${TRAMPOLINE_IMAGE}") + fi + + log_yellow "Start building the docker image." + if [[ "${TRAMPOLINE_VERBOSE:-false}" == "true" ]]; then + echo "docker build" "${docker_build_flags[@]}" "${context_dir}" + fi + + # ON CI systems, we want to suppress docker build logs, only + # output the logs when it fails. + if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + if docker build "${docker_build_flags[@]}" "${context_dir}" \ + > "${tmpdir}/docker_build.log" 2>&1; then + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + cat "${tmpdir}/docker_build.log" + fi + + log_green "Finished building the docker image." + update_cache="true" + else + log_red "Failed to build the Docker image, aborting." + log_yellow "Dumping the build logs:" + cat "${tmpdir}/docker_build.log" + exit 1 + fi + else + if docker build "${docker_build_flags[@]}" "${context_dir}"; then + log_green "Finished building the docker image." + update_cache="true" + else + log_red "Failed to build the Docker image, aborting." + exit 1 + fi + fi +else + if [[ "${has_image}" != "true" ]]; then + log_red "We do not have ${TRAMPOLINE_IMAGE} locally, aborting." + exit 1 + fi +fi + +# We use an array for the flags so they are easier to document. +docker_flags=( + # Remove the container after it exists. + "--rm" + + # Use the host network. + "--network=host" + + # Run in priviledged mode. We are not using docker for sandboxing or + # isolation, just for packaging our dev tools. + "--privileged" + + # Run the docker script with the user id. Because the docker image gets to + # write in ${PWD} you typically want this to be your user id. + # To allow docker in docker, we need to use docker gid on the host. + "--user" "${user_uid}:${docker_gid}" + + # Pass down the USER. + "--env" "USER=${user_name}" + + # Mount the project directory inside the Docker container. + "--volume" "${PROJECT_ROOT}:${TRAMPOLINE_WORKSPACE}" + "--workdir" "${TRAMPOLINE_WORKSPACE}" + "--env" "PROJECT_ROOT=${TRAMPOLINE_WORKSPACE}" + + # Mount the temporary home directory. + "--volume" "${tmphome}:/h" + "--env" "HOME=/h" + + # Allow docker in docker. + "--volume" "/var/run/docker.sock:/var/run/docker.sock" + + # Mount the /tmp so that docker in docker can mount the files + # there correctly. + "--volume" "/tmp:/tmp" + # Pass down the KOKORO_GFILE_DIR and KOKORO_KEYSTORE_DIR + # TODO(tmatsuo): This part is not portable. + "--env" "TRAMPOLINE_SECRET_DIR=/secrets" + "--volume" "${KOKORO_GFILE_DIR:-/dev/shm}:/secrets/gfile" + "--env" "KOKORO_GFILE_DIR=/secrets/gfile" + "--volume" "${KOKORO_KEYSTORE_DIR:-/dev/shm}:/secrets/keystore" + "--env" "KOKORO_KEYSTORE_DIR=/secrets/keystore" +) + +# Add an option for nicer output if the build gets a tty. +if [[ -t 0 ]]; then + docker_flags+=("-it") +fi + +# Passing down env vars +for e in "${pass_down_envvars[@]}" +do + if [[ -n "${!e:-}" ]]; then + docker_flags+=("--env" "${e}=${!e}") + fi +done + +# If arguments are given, all arguments will become the commands run +# in the container, otherwise run TRAMPOLINE_BUILD_FILE. +if [[ $# -ge 1 ]]; then + log_yellow "Running the given commands '" "${@:1}" "' in the container." + readonly commands=("${@:1}") + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" + fi + docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" +else + log_yellow "Running the tests in a Docker container." + docker_flags+=("--entrypoint=${TRAMPOLINE_BUILD_FILE}") + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" + fi + docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" +fi + + +test_retval=$? + +if [[ ${test_retval} -eq 0 ]]; then + log_green "Build finished with ${test_retval}" +else + log_red "Build finished with ${test_retval}" +fi + +# Only upload it when the test passes. +if [[ "${update_cache}" == "true" ]] && \ + [[ $test_retval == 0 ]] && \ + [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]]; then + log_yellow "Uploading the Docker image." + if docker push "${TRAMPOLINE_IMAGE}"; then + log_green "Finished uploading the Docker image." + else + log_red "Failed uploading the Docker image." + fi + # Call trampoline_after_upload_hook if it's defined. + if function_exists trampoline_after_upload_hook; then + trampoline_after_upload_hook + fi + +fi + +exit "${test_retval}" diff --git a/handwritten/spanner/.mocharc.js b/handwritten/spanner/.mocharc.js new file mode 100644 index 00000000000..2431859019f --- /dev/null +++ b/handwritten/spanner/.mocharc.js @@ -0,0 +1,29 @@ +// Copyright 2026 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. +const config = { + "enable-source-maps": true, + "throw-deprecation": true, + "timeout": 10000, + "recursive": true +} +if (process.env.MOCHA_THROW_DEPRECATION === 'false') { + delete config['throw-deprecation']; +} +if (process.env.MOCHA_REPORTER) { + config.reporter = process.env.MOCHA_REPORTER; +} +if (process.env.MOCHA_REPORTER_OUTPUT) { + config['reporter-option'] = `output=${process.env.MOCHA_REPORTER_OUTPUT}`; +} +module.exports = config diff --git a/handwritten/spanner/.nycrc b/handwritten/spanner/.nycrc new file mode 100644 index 00000000000..b18d5472b62 --- /dev/null +++ b/handwritten/spanner/.nycrc @@ -0,0 +1,24 @@ +{ + "report-dir": "./.coverage", + "reporter": ["text", "lcov"], + "exclude": [ + "**/*-test", + "**/.coverage", + "**/apis", + "**/benchmark", + "**/conformance", + "**/docs", + "**/samples", + "**/scripts", + "**/protos", + "**/test", + "**/*.d.ts", + ".jsdoc.js", + "**/.jsdoc.js", + "karma.conf.js", + "webpack-tests.config.js", + "webpack.config.js" + ], + "exclude-after-remap": false, + "all": true +} diff --git a/handwritten/spanner/.prettierignore b/handwritten/spanner/.prettierignore new file mode 100644 index 00000000000..9340ad9b86d --- /dev/null +++ b/handwritten/spanner/.prettierignore @@ -0,0 +1,6 @@ +**/node_modules +**/coverage +test/fixtures +build/ +docs/ +protos/ diff --git a/handwritten/spanner/.prettierrc.js b/handwritten/spanner/.prettierrc.js new file mode 100644 index 00000000000..d2eddc2ed89 --- /dev/null +++ b/handwritten/spanner/.prettierrc.js @@ -0,0 +1,17 @@ +// Copyright 2026 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. + +module.exports = { + ...require('gts/.prettierrc.json') +} diff --git a/handwritten/spanner/.readme-partials.yml b/handwritten/spanner/.readme-partials.yml new file mode 100644 index 00000000000..e5b253f6b79 --- /dev/null +++ b/handwritten/spanner/.readme-partials.yml @@ -0,0 +1,49 @@ +introduction: |- + [Cloud Spanner](https://cloud.google.com/spanner/docs/) is a fully managed, mission-critical, relational database service that + offers transactional consistency at global scale, schemas, SQL (ANSI 2011 with extensions), + and automatic, synchronous replication for high availability. + +body: |- + ## Metrics + + Cloud Spanner client supports [client-side metrics](https://cloud.google.com/spanner/docs/view-manage-client-side-metrics) that you can use along with server-side metrics to optimize performance and troubleshoot performance issues if they occur. + + Client-side metrics are measured from the time a request leaves your application to the time your application receives the response. + In contrast, server-side metrics are measured from the time Spanner receives a request until the last byte of data is sent to the client. + + These metrics are enabled by default. You can opt out of using client-side metrics with the following code: + + ```javascript + const spanner = new Spanner({ + disableBuiltInMetrics: true + }); + ``` + + You can also disable these metrics by setting `SPANNER_DISABLE_BUILTIN_METRICS` to `true`. + + > Note: Client-side metrics needs `monitoring.timeSeries.create` IAM permission to export metrics data. Ask your administrator to grant your service account the [Monitoring Metric Writer](https://cloud.google.com/iam/docs/roles-permissions/monitoring#monitoring.metricWriter) (roles/monitoring.metricWriter) IAM role on the project. + + ## Traces + Refer to the Observability README to know more about tracing support in the Cloud Spanner client. + + ## Multiplexed Sessions + + Spanner's Multiplexed Sessions is now default enabled session mode in node client. This feature helps reduce + session management overhead and minimize session-related errors. + + For a detailed explanation on multiplexed sessions, please refer to the [official documentation](https://cloud.google.com/spanner/docs/sessions#multiplexed_sessions). + + ## Regular Sessions + + To use regular sessions, disable the multiplexed sessions and set the following environment variables to `false`: + + * **For Read-Only Transactions:** + - `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS` + * **For Partitioned Operations:** + - `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS` + - `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS` + * **For Read-Write Transactions:** + - `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS` + - `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW` + + For a detailed explanation on session modes and env configurations, please refer to the [official documentation](https://cloud.google.com/spanner/docs/sessions). diff --git a/handwritten/spanner/.repo-metadata.json b/handwritten/spanner/.repo-metadata.json new file mode 100644 index 00000000000..a6f35590c2c --- /dev/null +++ b/handwritten/spanner/.repo-metadata.json @@ -0,0 +1,16 @@ +{ + "name": "spanner", + "name_pretty": "Cloud Spanner", + "product_documentation": "https://cloud.google.com/spanner/docs/", + "client_documentation": "https://cloud.google.com/nodejs/docs/reference/spanner/latest", + "issue_tracker": "https://issuetracker.google.com/issues?q=componentid:190851%2B%20status:open", + "release_level": "stable", + "language": "nodejs", + "repo": "googleapis/google-cloud-node", + "distribution_name": "@google-cloud/spanner", + "api_id": "spanner.googleapis.com", + "requires_billing": true, + "codeowner_team": "@googleapis/spanner-team", + "api_shortname": "spanner", + "library_type": "GAPIC_COMBO" +} diff --git a/handwritten/spanner/.trampolinerc b/handwritten/spanner/.trampolinerc new file mode 100644 index 00000000000..dea7e9541e6 --- /dev/null +++ b/handwritten/spanner/.trampolinerc @@ -0,0 +1,52 @@ +# Copyright 2020 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. + +# Template for .trampolinerc + +# Add required env vars here. +required_envvars+=( +) + +# Add env vars which are passed down into the container here. +pass_down_envvars+=( + "AUTORELEASE_PR" + "VERSION" +) + +# Prevent unintentional override on the default image. +if [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]] && \ + [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + echo "Please set TRAMPOLINE_IMAGE if you want to upload the Docker image." + exit 1 +fi + +# Define the default value if it makes sense. +if [[ -z "${TRAMPOLINE_IMAGE_UPLOAD:-}" ]]; then + TRAMPOLINE_IMAGE_UPLOAD="" +fi + +if [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + TRAMPOLINE_IMAGE="" +fi + +if [[ -z "${TRAMPOLINE_DOCKERFILE:-}" ]]; then + TRAMPOLINE_DOCKERFILE="" +fi + +if [[ -z "${TRAMPOLINE_BUILD_FILE:-}" ]]; then + TRAMPOLINE_BUILD_FILE="" +fi + +# Secret Manager secrets. +source ${PROJECT_ROOT}/handwritten/spanner/.kokoro/populate-secrets.sh diff --git a/handwritten/spanner/CHANGELOG.md b/handwritten/spanner/CHANGELOG.md new file mode 100644 index 00000000000..c3b79867501 --- /dev/null +++ b/handwritten/spanner/CHANGELOG.md @@ -0,0 +1,1788 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/nodejs-spanner?activeTab=versions + +## [8.6.0](https://github.com/googleapis/nodejs-spanner/compare/v8.5.0...v8.6.0) (2026-01-28) + + +### Features + +* Refactor and deprecate databaseRole and Session Labels SessionPoolOptions ([#2511](https://github.com/googleapis/nodejs-spanner/issues/2511)) ([163534c](https://github.com/googleapis/nodejs-spanner/commit/163534c8545a3f1378b001eb118b12f98b4cc1e5)) + + +### Bug Fixes + +* Ensure all data is consumed before emitting end event in PartialResultStream ([#2516](https://github.com/googleapis/nodejs-spanner/issues/2516)) ([210ef50](https://github.com/googleapis/nodejs-spanner/commit/210ef506cd80f4604e4a135fdfe937190eab5750)) + +## [8.5.0](https://github.com/googleapis/nodejs-spanner/compare/v8.4.0...v8.5.0) (2026-01-22) + + +### Features + +* Added OUTPUT_ONLY annotations to create_time and update_time in InternalRange to reflect existing service behavior ([#2505](https://github.com/googleapis/nodejs-spanner/issues/2505)) ([1058683](https://github.com/googleapis/nodejs-spanner/commit/105868339b1d2b7d7701a6b7591b85e3a1ca4098)) + + +### Bug Fixes + +* UUID type backward compatibility ([#2509](https://github.com/googleapis/nodejs-spanner/issues/2509)) ([7abb33c](https://github.com/googleapis/nodejs-spanner/commit/7abb33ca523b612f171def64c1ceb0cb7d162e82)) + +## [8.4.0](https://github.com/googleapis/nodejs-spanner/compare/v8.3.1...v8.4.0) (2026-01-09) + + +### Features + +* Add a ClientContext field to Spanner requests ([#2493](https://github.com/googleapis/nodejs-spanner/issues/2493)) ([37504ad](https://github.com/googleapis/nodejs-spanner/commit/37504adcc37a7e95acfb2530313ff783d0c1fe7d)) +* Exposing total CPU related fields in AutoscalingConfig ([#2490](https://github.com/googleapis/nodejs-spanner/issues/2490)) ([508f0ff](https://github.com/googleapis/nodejs-spanner/commit/508f0ff95636b004f4200522018a199263eda8ca)) +* **spanner:** Support for type UUID ([#2482](https://github.com/googleapis/nodejs-spanner/issues/2482)) ([0047e94](https://github.com/googleapis/nodejs-spanner/commit/0047e9407d86521571626c69011b70307f83f8ba)) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v5.0.6 ([#2452](https://github.com/googleapis/nodejs-spanner/issues/2452)) ([f9e6b86](https://github.com/googleapis/nodejs-spanner/commit/f9e6b86ff4da03110642c17e5ebc8fac8d903d3a)) +* Flaky metric test ([#2472](https://github.com/googleapis/nodejs-spanner/issues/2472)) ([e169cc5](https://github.com/googleapis/nodejs-spanner/commit/e169cc5344d38812b1ebf20c7a987715a73d6f79)) +* Memory leak and deadlock due to error event in multiplexed session ([#2477](https://github.com/googleapis/nodejs-spanner/issues/2477)) ([c624619](https://github.com/googleapis/nodejs-spanner/commit/c624619a3960892b1d2d412ff79faa5a74de45df)) +* Presubmit failure for samples backups test ([#2492](https://github.com/googleapis/nodejs-spanner/issues/2492)) ([01eb3d5](https://github.com/googleapis/nodejs-spanner/commit/01eb3d5801ddb21517f185b9d585fbce4fa1475c)) +* Type check for key in deleteRows ([#2486](https://github.com/googleapis/nodejs-spanner/issues/2486)) ([7347a16](https://github.com/googleapis/nodejs-spanner/commit/7347a1628ad8635b8f84b36ad1d3850b78862ac7)) +* Type mismatch in Snapshot.run error handler ([#2487](https://github.com/googleapis/nodejs-spanner/issues/2487)) ([4ac0360](https://github.com/googleapis/nodejs-spanner/commit/4ac036047e3a03c073300f288c746389a38d8e42)) + +## [8.3.1](https://github.com/googleapis/nodejs-spanner/compare/v8.3.0...v8.3.1) (2025-11-19) + + +### Bug Fixes + +* Remove Console logging ([e673acd](https://github.com/googleapis/nodejs-spanner/commit/e673acdba717380d25eca6d978272c43950eb1e8)) + +## [8.3.0](https://github.com/googleapis/nodejs-spanner/compare/v8.2.2...v8.3.0) (2025-11-11) + + +### Features + +* Exposing AutoscalingConfig in InstancePartition ([#2449](https://github.com/googleapis/nodejs-spanner/issues/2449)) ([2defcc8](https://github.com/googleapis/nodejs-spanner/commit/2defcc81de4191293cd2d4aa493a0a9dc68f37ce)) +* Multiplexed session as default session mode ([#2451](https://github.com/googleapis/nodejs-spanner/issues/2451)) ([9ef0565](https://github.com/googleapis/nodejs-spanner/commit/9ef0565ca2cc9af18477503b43a506fd7c0c3c33)) + + +### Bug Fixes + +* Configure gRPC keep alive as 120 sec ([#2445](https://github.com/googleapis/nodejs-spanner/issues/2445)) ([f280e7c](https://github.com/googleapis/nodejs-spanner/commit/f280e7ca7cc60a67da8a5a0b3ada5f414c9e9a5f)) +* **deps:** Update dependency google-gax to v5.0.4 ([#2430](https://github.com/googleapis/nodejs-spanner/issues/2430)) ([4cbed94](https://github.com/googleapis/nodejs-spanner/commit/4cbed94dd74567f12620a493cebace5b2c9196bc)) + +## [8.2.2](https://github.com/googleapis/nodejs-spanner/compare/v8.2.1...v8.2.2) (2025-10-07) + + +### Bug Fixes + +* Correctly determine project ID for metrics export ([#2427](https://github.com/googleapis/nodejs-spanner/issues/2427)) ([0d63312](https://github.com/googleapis/nodejs-spanner/commit/0d633126a87c1274abfd59550cb94052a819fcaa)) +* Metrics Export Error log ([#2425](https://github.com/googleapis/nodejs-spanner/issues/2425)) ([110923e](https://github.com/googleapis/nodejs-spanner/commit/110923ea1dc6f6c891e0f70406b3839224a25b9e)) + +## [8.2.1](https://github.com/googleapis/nodejs-spanner/compare/v8.2.0...v8.2.1) (2025-09-12) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v5.0.3 ([#2371](https://github.com/googleapis/nodejs-spanner/issues/2371)) ([8a175e2](https://github.com/googleapis/nodejs-spanner/commit/8a175e2e5cc8d0ed81faee7b24b59b5026758a59)) +* Disable afe_connectivity_error_count metric ([af72d70](https://github.com/googleapis/nodejs-spanner/commit/af72d707c8857d5596bd2b93830e52c8e152967f)) + +## [8.2.0](https://github.com/googleapis/nodejs-spanner/compare/v8.1.0...v8.2.0) (2025-08-26) + + +### Features + +* **spanner:** Add support for multiplexed session for r/w transactions ([#2351](https://github.com/googleapis/nodejs-spanner/issues/2351)) ([6a9f1a2](https://github.com/googleapis/nodejs-spanner/commit/6a9f1a2b2c0dad955593571c71e9d4b6c9e7eeee)) +* **spanner:** Support setting read lock mode ([#2388](https://github.com/googleapis/nodejs-spanner/issues/2388)) ([bd66f61](https://github.com/googleapis/nodejs-spanner/commit/bd66f61f3ecac65678d31cbc841c11cd0fb7c3da)) + + +### Bug Fixes + +* **deps:** Add uuid to dependencies ([#2376](https://github.com/googleapis/nodejs-spanner/issues/2376)) ([0b2060b](https://github.com/googleapis/nodejs-spanner/commit/0b2060b4ad7302ab23ac757e79fe760e34e81083)) +* **deps:** Update dependency @grpc/proto-loader to ^0.8.0 ([#2354](https://github.com/googleapis/nodejs-spanner/issues/2354)) ([75dc4da](https://github.com/googleapis/nodejs-spanner/commit/75dc4daf114cbc4eb4669ed6cb042af051cdce63)) +* **deps:** Update dependency google-gax to v5.0.1 ([#2362](https://github.com/googleapis/nodejs-spanner/issues/2362)) ([9223470](https://github.com/googleapis/nodejs-spanner/commit/922347014ac3966ec4a48116b61ba4850edf0b50)) +* Provide option to disable built in metrics ([#2380](https://github.com/googleapis/nodejs-spanner/issues/2380)) ([b378e2e](https://github.com/googleapis/nodejs-spanner/commit/b378e2ed6739acf76f3f3f27090311129dd83473)) +* Race condition among transactions when running parallely ([#2369](https://github.com/googleapis/nodejs-spanner/issues/2369)) ([f8b6f63](https://github.com/googleapis/nodejs-spanner/commit/f8b6f6340f4f04e04213fdf0a9665d643f474eeb)) + +## [8.1.0](https://github.com/googleapis/nodejs-spanner/compare/v8.0.0...v8.1.0) (2025-07-28) + + +### Features + +* Add Custom OpenTelemetry Exporter in for Service Metrics ([#2272](https://github.com/googleapis/nodejs-spanner/issues/2272)) ([610d1b9](https://github.com/googleapis/nodejs-spanner/commit/610d1b989ba186c0758791343deaa7f683c4bd26)) +* Add methods from gax to cache proto root and process custom error details ([#2330](https://github.com/googleapis/nodejs-spanner/issues/2330)) ([1b3931a](https://github.com/googleapis/nodejs-spanner/commit/1b3931a799bdd052adc91703e59e1d0c83270065)) +* Add metrics tracers ([#2319](https://github.com/googleapis/nodejs-spanner/issues/2319)) ([192bf2b](https://github.com/googleapis/nodejs-spanner/commit/192bf2bb603bca4ac481fcfd1f04974173adc6a1)) +* Add support for AFE latency metrics ([#2348](https://github.com/googleapis/nodejs-spanner/issues/2348)) ([0666f05](https://github.com/googleapis/nodejs-spanner/commit/0666f05d589e2f229b44dffae8e9649220bccf8b)) +* Add throughput_mode to UpdateDatabaseDdlRequest to be used by Spanner Migration Tool. See https://github.com/GoogleCloudPlatform/spanner-migration-tool ([#2304](https://github.com/googleapis/nodejs-spanner/issues/2304)) ([a29af56](https://github.com/googleapis/nodejs-spanner/commit/a29af56ae3c31f07115cb938bcf3f0f77241b725)) +* Operation, Attempt, and GFE metrics ([#2328](https://github.com/googleapis/nodejs-spanner/issues/2328)) ([646e6ea](https://github.com/googleapis/nodejs-spanner/commit/646e6ea6f1dc5fa1937e512ae9e81ae4d2637ed0)) +* Proto changes for an internal api ([#2356](https://github.com/googleapis/nodejs-spanner/issues/2356)) ([380e770](https://github.com/googleapis/nodejs-spanner/commit/380e7705a23a692168db386ba5426c91bf1587b6)) +* **spanner:** A new field `snapshot_timestamp` is added to message `.google.spanner.v1.CommitResponse` ([#2350](https://github.com/googleapis/nodejs-spanner/issues/2350)) ([0875cd8](https://github.com/googleapis/nodejs-spanner/commit/0875cd82e99fa6c95ab38807e09c5921303775f8)) +* **spanner:** Add new change_stream.proto ([#2315](https://github.com/googleapis/nodejs-spanner/issues/2315)) ([57d67be](https://github.com/googleapis/nodejs-spanner/commit/57d67be2e3b6d6ac2a8a903acf8613b27a049c3b)) +* **spanner:** Add tpc support ([#2333](https://github.com/googleapis/nodejs-spanner/issues/2333)) ([a381cab](https://github.com/googleapis/nodejs-spanner/commit/a381cab92c31373a6a10edca0f8a8bdfc4415e4b)) +* Track precommit token in r/w apis(multiplexed session) ([#2312](https://github.com/googleapis/nodejs-spanner/issues/2312)) ([3676bfa](https://github.com/googleapis/nodejs-spanner/commit/3676bfa60725c43f85a04ead87943be92e4a99f0)) + + +### Bug Fixes + +* Docs-test ([#2297](https://github.com/googleapis/nodejs-spanner/issues/2297)) ([61c571c](https://github.com/googleapis/nodejs-spanner/commit/61c571c729c2a065df6ff166db784a6e6eaef74d)) +* Ensure context propagation works in Node.js 22 with async/await ([#2326](https://github.com/googleapis/nodejs-spanner/issues/2326)) ([e8cdbed](https://github.com/googleapis/nodejs-spanner/commit/e8cdbedd55f049b8c7766e97388ed045fedd1b4e)) +* Pass the Span correctly ([#2332](https://github.com/googleapis/nodejs-spanner/issues/2332)) ([edaee77](https://github.com/googleapis/nodejs-spanner/commit/edaee7791b2d814f749ed35119dd705924984a78)) +* System test against emulator ([#2339](https://github.com/googleapis/nodejs-spanner/issues/2339)) ([2a6af4c](https://github.com/googleapis/nodejs-spanner/commit/2a6af4c36484f44929a2fac80d8f225dad5d702c)) +* Unhandled exceptions from gax ([#2338](https://github.com/googleapis/nodejs-spanner/issues/2338)) ([6428bcd](https://github.com/googleapis/nodejs-spanner/commit/6428bcd2980852c1bdbc4c3d0ab210a139e5f193)) + + +### Performance Improvements + +* Skip gRPC trailers for StreamingRead & ExecuteStreamingSql ([#2313](https://github.com/googleapis/nodejs-spanner/issues/2313)) ([8bd0781](https://github.com/googleapis/nodejs-spanner/commit/8bd0781e8b434a421f0e0f3395439a5a86c7847c)) + +## [8.0.0](https://github.com/googleapis/nodejs-spanner/compare/v7.21.0...v8.0.0) (2025-05-12) + + +### ⚠ BREAKING CHANGES + +* remove the arrify package ([#2292](https://github.com/googleapis/nodejs-spanner/issues/2292)) +* migrate to Node 18 ([#2271](https://github.com/googleapis/nodejs-spanner/issues/2271)) + +### Features + +* Add promise based signatures for createQueryPartitions ([#2284](https://github.com/googleapis/nodejs-spanner/issues/2284)) ([255d8a6](https://github.com/googleapis/nodejs-spanner/commit/255d8a6a5749b6a05cd87dd7444cab7dd75d3e42)) +* Add promise based signatures on createReadPartitions ([#2300](https://github.com/googleapis/nodejs-spanner/issues/2300)) ([7b8a1f7](https://github.com/googleapis/nodejs-spanner/commit/7b8a1f70f0de3aa5886a2cde9325c9a36222a311)) +* Support promise based signatures for execute method ([#2301](https://github.com/googleapis/nodejs-spanner/issues/2301)) ([bb857e1](https://github.com/googleapis/nodejs-spanner/commit/bb857e18459f717d67b9b3d144c2b022178363cb)) + + +### Bug Fixes + +* **deps:** Update dependency @google-cloud/kms to v5 ([#2289](https://github.com/googleapis/nodejs-spanner/issues/2289)) ([1ccb505](https://github.com/googleapis/nodejs-spanner/commit/1ccb505935e70b6f576f06e566325146ee68f3ff)) +* **deps:** Update dependency @google-cloud/precise-date to v5 ([#2290](https://github.com/googleapis/nodejs-spanner/issues/2290)) ([44f7575](https://github.com/googleapis/nodejs-spanner/commit/44f7575efd3751d0595beef2ec4eb9f39bc426d7)) +* **deps:** Update dependency big.js to v7 ([#2286](https://github.com/googleapis/nodejs-spanner/issues/2286)) ([0911297](https://github.com/googleapis/nodejs-spanner/commit/0911297cc33aec93c09ef2be42413f20c75fc2bf)) + + +### Miscellaneous Chores + +* Migrate to Node 18 ([#2271](https://github.com/googleapis/nodejs-spanner/issues/2271)) ([cab3f22](https://github.com/googleapis/nodejs-spanner/commit/cab3f229ccb2189bd5af0c25a3006b553f8a5453)) +* Remove the arrify package ([#2292](https://github.com/googleapis/nodejs-spanner/issues/2292)) ([e8f5ca1](https://github.com/googleapis/nodejs-spanner/commit/e8f5ca15125d570949769e6e66f0d911cb21f58d)) + +## [7.21.0](https://github.com/googleapis/nodejs-spanner/compare/v7.20.0...v7.21.0) (2025-04-15) + + +### Features + +* Adding sample for pre-split feature ([#2274](https://github.com/googleapis/nodejs-spanner/issues/2274)) ([3d5f080](https://github.com/googleapis/nodejs-spanner/commit/3d5f08065fdf40a1c441d97a049d7dacf1a5be93)) + + +### Bug Fixes + +* Adding span attributes for request tag and transaction tag ([#2236](https://github.com/googleapis/nodejs-spanner/issues/2236)) ([3f69dad](https://github.com/googleapis/nodejs-spanner/commit/3f69dad36cfdeb4effd191e0d38079ead1bd6654)) + +## [7.20.0](https://github.com/googleapis/nodejs-spanner/compare/v7.19.1...v7.20.0) (2025-04-11) + + +### Features + +* Add support for Interval ([#2192](https://github.com/googleapis/nodejs-spanner/issues/2192)) ([8c886cb](https://github.com/googleapis/nodejs-spanner/commit/8c886cbc0d7523fb99e65cfc5d8f565b630e26f0)) +* **debugging:** Implement x-goog-spanner-request-id propagation per request ([#2205](https://github.com/googleapis/nodejs-spanner/issues/2205)) ([e42caea](https://github.com/googleapis/nodejs-spanner/commit/e42caeaaa656c395d240f4af412ddb947f29c59b)) +* **spanner:** Add support for snapshot isolation ([#2245](https://github.com/googleapis/nodejs-spanner/issues/2245)) ([b60a683](https://github.com/googleapis/nodejs-spanner/commit/b60a683c0e1ddbf704766eb99f102fed925a348c)) +* **spanner:** Support for Multiplexed Session Partitioned Ops ([#2252](https://github.com/googleapis/nodejs-spanner/issues/2252)) ([e7ce471](https://github.com/googleapis/nodejs-spanner/commit/e7ce471332f6e73614638b96ed54c87095d785a2)) + +## [7.19.1](https://github.com/googleapis/nodejs-spanner/compare/v7.19.0...v7.19.1) (2025-03-13) + + +### Bug Fixes + +* CreateQueryPartition with query params ([91f5afd](https://github.com/googleapis/nodejs-spanner/commit/91f5afda53bd9c46fcd1a1fe33f579b6aed5223a)) + +## [7.19.0](https://github.com/googleapis/nodejs-spanner/compare/v7.18.1...v7.19.0) (2025-02-26) + + +### Features + +* Add AddSplitPoints API ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* Paging changes for bigquery ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* **spanner:** A new enum `IsolationLevel` is added ([#2225](https://github.com/googleapis/nodejs-spanner/issues/2225)) ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* **spanner:** A new field `isolation_level` is added to message `.google.spanner.v1.TransactionOptions` ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* **spanner:** Add instance partitions field in backup proto ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* **spanner:** Add support for Multiplexed Session for Read Only Tran… ([#2214](https://github.com/googleapis/nodejs-spanner/issues/2214)) ([3a7a51b](https://github.com/googleapis/nodejs-spanner/commit/3a7a51bee00730c2daf1b9791b45f75531c14a2c)) +* **x-goog-spanner-request-id:** Add bases ([#2211](https://github.com/googleapis/nodejs-spanner/issues/2211)) ([0008038](https://github.com/googleapis/nodejs-spanner/commit/000803812e670ce0f4bac4a6460351f2b08ec660)) + + +### Bug Fixes + +* Add x-goog-request params to headers for LRO-polling methods ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* Error from fill method should not be emitted ([#2233](https://github.com/googleapis/nodejs-spanner/issues/2233)) ([2cc44cf](https://github.com/googleapis/nodejs-spanner/commit/2cc44cf238bd18f5a456c76ddb8280c2252c2e87)), closes [#2103](https://github.com/googleapis/nodejs-spanner/issues/2103) +* Finalize fixing typings for headers in generator ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* Fix typings for headers in generator ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* Remove extra protos in ESM & capture ESM in headers ([e4d389a](https://github.com/googleapis/nodejs-spanner/commit/e4d389a23ff4b73b2d0774ad31a84c9a6c19e306)) +* Rollback with no id ([#2231](https://github.com/googleapis/nodejs-spanner/issues/2231)) ([a6919b1](https://github.com/googleapis/nodejs-spanner/commit/a6919b15bd01ed93c62d32533d78181cbd333f5e)), closes [#2103](https://github.com/googleapis/nodejs-spanner/issues/2103) + +## [7.18.1](https://github.com/googleapis/nodejs-spanner/compare/v7.18.0...v7.18.1) (2025-02-05) + + +### Bug Fixes + +* Fix NodeJS release ([#2229](https://github.com/googleapis/nodejs-spanner/issues/2229)) ([f830fc8](https://github.com/googleapis/nodejs-spanner/commit/f830fc82ce666902db3cddc667326dc2731c14a1)) + +## [7.18.0](https://github.com/googleapis/nodejs-spanner/compare/v7.17.1...v7.18.0) (2025-01-29) + + +### Features + +* Add gcp client attributes for Opentelemetry traces ([#2215](https://github.com/googleapis/nodejs-spanner/issues/2215)) ([d2ff046](https://github.com/googleapis/nodejs-spanner/commit/d2ff046854b4139af6e3a6f0d2122619cdf83131)) + +## [7.17.1](https://github.com/googleapis/nodejs-spanner/compare/v7.17.0...v7.17.1) (2025-01-03) + + +### Bug Fixes + +* Remove default global trace context propagator ([#2209](https://github.com/googleapis/nodejs-spanner/issues/2209)) ([7898e0c](https://github.com/googleapis/nodejs-spanner/commit/7898e0ce0477e2d4327822ac26a2674203b47a64)), closes [#2208](https://github.com/googleapis/nodejs-spanner/issues/2208) + +## [7.17.0](https://github.com/googleapis/nodejs-spanner/compare/v7.16.0...v7.17.0) (2024-12-27) + + +### Features + +* Add the last statement option to ExecuteSqlRequest and ExecuteBatchDmlRequest ([#2196](https://github.com/googleapis/nodejs-spanner/issues/2196)) ([223f167](https://github.com/googleapis/nodejs-spanner/commit/223f167c1c9bc4da26155637eabbcabce5487ede)) +* Enable e2e tracing ([#2202](https://github.com/googleapis/nodejs-spanner/issues/2202)) ([3cc257e](https://github.com/googleapis/nodejs-spanner/commit/3cc257e99925594776b9a1886f0173ce2dfe904f)) + + +### Bug Fixes + +* Span events Issue 2166 ([#2184](https://github.com/googleapis/nodejs-spanner/issues/2184)) ([97ed577](https://github.com/googleapis/nodejs-spanner/commit/97ed5776dbdf5e90f8398fffea08e2a968045f9b)) + +## [7.16.0](https://github.com/googleapis/nodejs-spanner/compare/v7.15.0...v7.16.0) (2024-11-09) + + +### Features + +* **spanner:** Add support for Cloud Spanner Default Backup Schedules ([#2135](https://github.com/googleapis/nodejs-spanner/issues/2135)) ([19f137c](https://github.com/googleapis/nodejs-spanner/commit/19f137c870796d60902be8d9d3a82f4abcfc693f)) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v4.4.1 ([#2100](https://github.com/googleapis/nodejs-spanner/issues/2100)) ([2e94bcd](https://github.com/googleapis/nodejs-spanner/commit/2e94bcd06d99a98c7767281e8035d000e186692b)) + +## [7.15.0](https://github.com/googleapis/nodejs-spanner/compare/v7.14.0...v7.15.0) (2024-10-30) + + +### Features + +* (observability, samples): add tracing end-to-end sample ([#2130](https://github.com/googleapis/nodejs-spanner/issues/2130)) ([66d99e8](https://github.com/googleapis/nodejs-spanner/commit/66d99e836cd2bfbb3b0f78980ec2b499f9e5e563)) +* (observability) add spans for BatchTransaction and Table ([#2115](https://github.com/googleapis/nodejs-spanner/issues/2115)) ([d51aae9](https://github.com/googleapis/nodejs-spanner/commit/d51aae9c9c3c0e6319d81c2809573ae54675acf3)), closes [#2114](https://github.com/googleapis/nodejs-spanner/issues/2114) +* (observability) Add support for OpenTelemetry traces and allow observability options to be passed. ([#2131](https://github.com/googleapis/nodejs-spanner/issues/2131)) ([5237e11](https://github.com/googleapis/nodejs-spanner/commit/5237e118befb4b7fe4aea76a80a91e822d7a22e4)), closes [#2079](https://github.com/googleapis/nodejs-spanner/issues/2079) +* (observability) propagate database name for every span generated to aid in quick debugging ([#2155](https://github.com/googleapis/nodejs-spanner/issues/2155)) ([0342e74](https://github.com/googleapis/nodejs-spanner/commit/0342e74721a0684d8195a6299c3a634eefc2b522)) +* (observability) trace Database.batchCreateSessions + SessionPool.createSessions ([#2145](https://github.com/googleapis/nodejs-spanner/issues/2145)) ([f489c94](https://github.com/googleapis/nodejs-spanner/commit/f489c9479fa5402f0c960cf896fd3be0e946f182)) +* (observability): trace Database.runPartitionedUpdate ([#2176](https://github.com/googleapis/nodejs-spanner/issues/2176)) ([701e226](https://github.com/googleapis/nodejs-spanner/commit/701e22660d5ac9f0b3e940ad656b9ca6c479251d)), closes [#2079](https://github.com/googleapis/nodejs-spanner/issues/2079) +* (observability): trace Database.runTransactionAsync ([#2167](https://github.com/googleapis/nodejs-spanner/issues/2167)) ([d0fe178](https://github.com/googleapis/nodejs-spanner/commit/d0fe178623c1c48245d11bcea97fcd340b6615af)), closes [#207](https://github.com/googleapis/nodejs-spanner/issues/207) +* Allow multiple KMS keys to create CMEK database/backup ([#2099](https://github.com/googleapis/nodejs-spanner/issues/2099)) ([51bc8a7](https://github.com/googleapis/nodejs-spanner/commit/51bc8a7445ab8b3d2239493b69d9c271c1086dde)) +* **observability:** Fix bugs found from product review + negative cases ([#2158](https://github.com/googleapis/nodejs-spanner/issues/2158)) ([cbc86fa](https://github.com/googleapis/nodejs-spanner/commit/cbc86fa80498af6bd745eebb9443612936e26d4e)) +* **observability:** Trace Database methods ([#2119](https://github.com/googleapis/nodejs-spanner/issues/2119)) ([1f06871](https://github.com/googleapis/nodejs-spanner/commit/1f06871f7aca386756e8691013602b069697bb87)), closes [#2114](https://github.com/googleapis/nodejs-spanner/issues/2114) +* **observability:** Trace Database.batchWriteAtLeastOnce ([#2157](https://github.com/googleapis/nodejs-spanner/issues/2157)) ([2a19ef1](https://github.com/googleapis/nodejs-spanner/commit/2a19ef1af4f6fd1b81d08afc15db76007859a0b9)), closes [#2079](https://github.com/googleapis/nodejs-spanner/issues/2079) +* **observability:** Trace Transaction ([#2122](https://github.com/googleapis/nodejs-spanner/issues/2122)) ([a464bdb](https://github.com/googleapis/nodejs-spanner/commit/a464bdb5cbb7856b7a08dac3ff48132948b65792)), closes [#2114](https://github.com/googleapis/nodejs-spanner/issues/2114) + + +### Bug Fixes + +* Exact staleness timebound ([#2143](https://github.com/googleapis/nodejs-spanner/issues/2143)) ([f01516e](https://github.com/googleapis/nodejs-spanner/commit/f01516ec6ba44730622cfb050c52cd93f30bba7a)), closes [#2129](https://github.com/googleapis/nodejs-spanner/issues/2129) +* GetMetadata for Session ([#2124](https://github.com/googleapis/nodejs-spanner/issues/2124)) ([2fd63ac](https://github.com/googleapis/nodejs-spanner/commit/2fd63acb87ce06a02d7fdfa78d836dbd7ad59a26)), closes [#2123](https://github.com/googleapis/nodejs-spanner/issues/2123) + +## [7.14.0](https://github.com/googleapis/nodejs-spanner/compare/v7.13.0...v7.14.0) (2024-08-14) + + +### Features + +* **spanner:** Add resource reference annotation to backup schedules ([#2093](https://github.com/googleapis/nodejs-spanner/issues/2093)) ([df539e6](https://github.com/googleapis/nodejs-spanner/commit/df539e665fe5d8fe01084b8d8cf6094c89b13d48)) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v4.3.9 ([#2094](https://github.com/googleapis/nodejs-spanner/issues/2094)) ([487efc0](https://github.com/googleapis/nodejs-spanner/commit/487efc091e0e143d3c59ac63d66005133b1ef2e5)) + +## [7.13.0](https://github.com/googleapis/nodejs-spanner/compare/v7.12.0...v7.13.0) (2024-08-09) + + +### Features + +* **spanner:** Add support for Cloud Spanner Incremental Backups ([#2085](https://github.com/googleapis/nodejs-spanner/issues/2085)) ([33b9645](https://github.com/googleapis/nodejs-spanner/commit/33b9645d6096e0d77d30fab6aadf5d92da973a67)) + + +### Bug Fixes + +* Unhandled exception error catch ([#2091](https://github.com/googleapis/nodejs-spanner/issues/2091)) ([e277752](https://github.com/googleapis/nodejs-spanner/commit/e277752fad961908e37e37d88d7b6a61d61a078e)) + +## [7.12.0](https://github.com/googleapis/nodejs-spanner/compare/v7.11.0...v7.12.0) (2024-08-02) + + +### Features + +* Grpc keep alive settings ([#2086](https://github.com/googleapis/nodejs-spanner/issues/2086)) ([7712c35](https://github.com/googleapis/nodejs-spanner/commit/7712c35be21863015bb709f5f89d9ef0bb656024)) + +## [7.11.0](https://github.com/googleapis/nodejs-spanner/compare/v7.10.0...v7.11.0) (2024-07-29) + + +### Features + +* Add support for blind writes ([#2065](https://github.com/googleapis/nodejs-spanner/issues/2065)) ([62fc0a4](https://github.com/googleapis/nodejs-spanner/commit/62fc0a47327017c115466b9e89e53dbd778579af)) +* **spanner:** Add samples for instance partitions ([#2083](https://github.com/googleapis/nodejs-spanner/issues/2083)) ([b91e284](https://github.com/googleapis/nodejs-spanner/commit/b91e2849056df9894e0590cb71e21c13319e6d70)) + +## [7.10.0](https://github.com/googleapis/nodejs-spanner/compare/v7.9.1...v7.10.0) (2024-07-19) + + +### Features + +* Add field lock_hint in spanner.proto ([47520e9](https://github.com/googleapis/nodejs-spanner/commit/47520e927b0fdcc60cb67378b8b49f44329f210b)) +* Add field order_by in spanner.proto ([47520e9](https://github.com/googleapis/nodejs-spanner/commit/47520e927b0fdcc60cb67378b8b49f44329f210b)) +* Add QueryCancellationAction message in executor protos ([47520e9](https://github.com/googleapis/nodejs-spanner/commit/47520e927b0fdcc60cb67378b8b49f44329f210b)) +* Add support for change streams transaction exclusion option for Batch Write ([#2070](https://github.com/googleapis/nodejs-spanner/issues/2070)) ([2a9e443](https://github.com/googleapis/nodejs-spanner/commit/2a9e44328acda310db2d0d65d32ad82d77a9fcb0)) +* **spanner:** Add support for Cloud Spanner Scheduled Backups ([#2045](https://github.com/googleapis/nodejs-spanner/issues/2045)) ([47520e9](https://github.com/googleapis/nodejs-spanner/commit/47520e927b0fdcc60cb67378b8b49f44329f210b)) +* Update Nodejs generator to send API versions in headers for GAPICs ([47520e9](https://github.com/googleapis/nodejs-spanner/commit/47520e927b0fdcc60cb67378b8b49f44329f210b)) + + +### Bug Fixes + +* Callback in getDatabaseDialect ([#2078](https://github.com/googleapis/nodejs-spanner/issues/2078)) ([7e4a8e9](https://github.com/googleapis/nodejs-spanner/commit/7e4a8e9ad4f785b15b68aaa06b6480098d7995ba)) +* **deps:** Update dependency google-gax to v4.3.8 ([#2077](https://github.com/googleapis/nodejs-spanner/issues/2077)) ([e927880](https://github.com/googleapis/nodejs-spanner/commit/e927880ff786a2528a2bbb063a244af3c42ff69c)) + +## [7.9.1](https://github.com/googleapis/nodejs-spanner/compare/v7.9.0...v7.9.1) (2024-06-26) + + +### Bug Fixes + +* Retry with timeout ([#2071](https://github.com/googleapis/nodejs-spanner/issues/2071)) ([a943257](https://github.com/googleapis/nodejs-spanner/commit/a943257a0402b26fd80196057a9724fd28fc5c1b)) + +## [7.9.0](https://github.com/googleapis/nodejs-spanner/compare/v7.8.0...v7.9.0) (2024-06-21) + + +### Features + +* **spanner:** Add support for batchWrite ([#2054](https://github.com/googleapis/nodejs-spanner/issues/2054)) ([06aab6e](https://github.com/googleapis/nodejs-spanner/commit/06aab6e39bbce9e3786f1ac631c80e8909197e92)) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v4.3.4 ([#2051](https://github.com/googleapis/nodejs-spanner/issues/2051)) ([80abf06](https://github.com/googleapis/nodejs-spanner/commit/80abf06ba8ef9497318ffc597b83fb63e4408f9c)) +* **deps:** Update dependency google-gax to v4.3.5 ([#2055](https://github.com/googleapis/nodejs-spanner/issues/2055)) ([702c9b0](https://github.com/googleapis/nodejs-spanner/commit/702c9b0f34e6cc34233c5aa52b97601b19f70980)) +* **deps:** Update dependency google-gax to v4.3.6 ([#2057](https://github.com/googleapis/nodejs-spanner/issues/2057)) ([74ebf1e](https://github.com/googleapis/nodejs-spanner/commit/74ebf1e45cddf614c180295f3a761a8f84c5cb32)) +* **deps:** Update dependency google-gax to v4.3.7 ([#2068](https://github.com/googleapis/nodejs-spanner/issues/2068)) ([28fec6c](https://github.com/googleapis/nodejs-spanner/commit/28fec6ca505d78d725efc123950be978e0c84ab7)) + +## [7.8.0](https://github.com/googleapis/nodejs-spanner/compare/v7.7.0...v7.8.0) (2024-05-24) + + +### Features + +* Add `RESOURCE_EXHAUSTED` to the list of retryable error codes ([#2032](https://github.com/googleapis/nodejs-spanner/issues/2032)) ([a4623c5](https://github.com/googleapis/nodejs-spanner/commit/a4623c560c16fa1f37a06cb57a5e47a1d6759d27)) +* Add support for multi region encryption config ([81fa610](https://github.com/googleapis/nodejs-spanner/commit/81fa610895fe709cbb7429896493a67407a6343c)) +* Add support for Proto columns ([#1991](https://github.com/googleapis/nodejs-spanner/issues/1991)) ([ae59c7f](https://github.com/googleapis/nodejs-spanner/commit/ae59c7f957660e08cd5965b5e67694fa1ccc0057)) +* **spanner:** Add support for change streams transaction exclusion option ([#2049](https://github.com/googleapis/nodejs-spanner/issues/2049)) ([d95cab5](https://github.com/googleapis/nodejs-spanner/commit/d95cab5abe50cdb56cbc1d6d935aee29526e1096)) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v4.3.3 ([#2038](https://github.com/googleapis/nodejs-spanner/issues/2038)) ([d86c1b0](https://github.com/googleapis/nodejs-spanner/commit/d86c1b0c21c7c95e3110221b3ca6ff9ff3b4a088)) +* Drop table statement ([#2036](https://github.com/googleapis/nodejs-spanner/issues/2036)) ([f31d7b2](https://github.com/googleapis/nodejs-spanner/commit/f31d7b205d74d4a783f0d5159dd5b62efe968fe6)) + +## [7.7.0](https://github.com/googleapis/nodejs-spanner/compare/v7.6.0...v7.7.0) (2024-04-17) + + +### Features + +* OptimisticLock option for getTransaction method ([#2028](https://github.com/googleapis/nodejs-spanner/issues/2028)) ([dacf869](https://github.com/googleapis/nodejs-spanner/commit/dacf8697b20752041684710982035b4c97837d28)) +* **spanner:** Adding `EXPECTED_FULFILLMENT_PERIOD` to the indicate instance creation times (with `FULFILLMENT_PERIOD_NORMAL` or `FULFILLMENT_PERIOD_EXTENDED` ENUM) with the extended instance creation time triggered by On-Demand Capacity Feature ([#2024](https://github.com/googleapis/nodejs-spanner/issues/2024)) ([5292e03](https://github.com/googleapis/nodejs-spanner/commit/5292e035c5278ba6806f9e1eb84809ed893b1e37)) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v4.3.2 ([#2026](https://github.com/googleapis/nodejs-spanner/issues/2026)) ([0ee9831](https://github.com/googleapis/nodejs-spanner/commit/0ee98319f291f552a0afc52629d12af9969d1d10)) + +## [7.6.0](https://github.com/googleapis/nodejs-spanner/compare/v7.5.0...v7.6.0) (2024-03-26) + + +### Features + +* Add instance partition support to spanner instance proto ([#2001](https://github.com/googleapis/nodejs-spanner/issues/2001)) ([4381047](https://github.com/googleapis/nodejs-spanner/commit/43810478e81d3a234e7fa94af90fd49ca379dd98)) +* Managed Autoscaler ([#2015](https://github.com/googleapis/nodejs-spanner/issues/2015)) ([547ca1b](https://github.com/googleapis/nodejs-spanner/commit/547ca1b0da8c5c5e28f85fbd4ea16af21e20c980)) +* **spanner:** Add a sample for max commit delays ([#1993](https://github.com/googleapis/nodejs-spanner/issues/1993)) ([91c7204](https://github.com/googleapis/nodejs-spanner/commit/91c7204e2c8f62e229d7a2b2a0ff059d421dd984)) +* **spanner:** Add support for float32 ([#2020](https://github.com/googleapis/nodejs-spanner/issues/2020)) ([99e2c1d](https://github.com/googleapis/nodejs-spanner/commit/99e2c1d4791a5ca86fdccb3f600aa4592efe0a45)) + +## [7.5.0](https://github.com/googleapis/nodejs-spanner/compare/v7.4.0...v7.5.0) (2024-03-04) + + +### Features + +* **spanner:** Add emulator support for the admin client autogenerated API samples ([#1994](https://github.com/googleapis/nodejs-spanner/issues/1994)) ([e2fe5b7](https://github.com/googleapis/nodejs-spanner/commit/e2fe5b748c3077078fa43e4bfa427fef603656a9)) + + +### Bug Fixes + +* Revert untyped param type feature ([#2012](https://github.com/googleapis/nodejs-spanner/issues/2012)) ([49fa60d](https://github.com/googleapis/nodejs-spanner/commit/49fa60dd0735fe66db33f7b9137dba0821eb5184)) + +## [7.4.0](https://github.com/googleapis/nodejs-spanner/compare/v7.3.0...v7.4.0) (2024-02-23) + + +### Features + +* **spanner:** Add PG.OID support ([#1948](https://github.com/googleapis/nodejs-spanner/issues/1948)) ([cf9df7a](https://github.com/googleapis/nodejs-spanner/commit/cf9df7a54c21ac995bbea9ad82c3544e4aff41b6)) +* Untyped param types ([#1869](https://github.com/googleapis/nodejs-spanner/issues/1869)) ([6ef44c3](https://github.com/googleapis/nodejs-spanner/commit/6ef44c383a90bf6ae95de531c83e21d2d58da159)) +* Update TransactionOptions to include new option exclude_txn_from_change_streams ([#1998](https://github.com/googleapis/nodejs-spanner/issues/1998)) ([937a7a1](https://github.com/googleapis/nodejs-spanner/commit/937a7a13f8c7660e21d34ebbaecad426b2bacd99)) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v4.3.1 ([#1995](https://github.com/googleapis/nodejs-spanner/issues/1995)) ([bed4832](https://github.com/googleapis/nodejs-spanner/commit/bed4832445e72c7116fe5495c79d989664220b38)) +* Only reset pending value with resume token ([#2000](https://github.com/googleapis/nodejs-spanner/issues/2000)) ([f337089](https://github.com/googleapis/nodejs-spanner/commit/f337089567d7d92c9467e311be7d72b0a7dc8047)), closes [#1959](https://github.com/googleapis/nodejs-spanner/issues/1959) + +## [7.3.0](https://github.com/googleapis/nodejs-spanner/compare/v7.2.0...v7.3.0) (2024-02-08) + + +### Features + +* **spanner:** Add maxCommitDelay support ([#1992](https://github.com/googleapis/nodejs-spanner/issues/1992)) ([9f84408](https://github.com/googleapis/nodejs-spanner/commit/9f8440843fd8926a37ec300a318dad33b83b4f97)) + + +### Bug Fixes + +* **deps:** Update dependency google-gax to v4.1.0 ([#1981](https://github.com/googleapis/nodejs-spanner/issues/1981)) ([2a36150](https://github.com/googleapis/nodejs-spanner/commit/2a36150cb61e9abeef073724189cc651d29d8776)) +* **deps:** Update dependency google-gax to v4.2.0 ([#1988](https://github.com/googleapis/nodejs-spanner/issues/1988)) ([005589a](https://github.com/googleapis/nodejs-spanner/commit/005589a7727ee87948a55a6c7710f5150fc1c6a7)) +* **deps:** Update dependency google-gax to v4.2.1 ([#1989](https://github.com/googleapis/nodejs-spanner/issues/1989)) ([d2ae995](https://github.com/googleapis/nodejs-spanner/commit/d2ae9952e7449ce2321e69a6be36c9d50d863095)) +* **deps:** Update dependency google-gax to v4.3.0 ([#1990](https://github.com/googleapis/nodejs-spanner/issues/1990)) ([e625753](https://github.com/googleapis/nodejs-spanner/commit/e625753a37393f32d9e449aa7324763082f6c923)) + +## [7.2.0](https://github.com/googleapis/nodejs-spanner/compare/v7.1.0...v7.2.0) (2024-01-11) + + +### Features + +* Support for Directed Reads ([#1966](https://github.com/googleapis/nodejs-spanner/issues/1966)) ([c0a4363](https://github.com/googleapis/nodejs-spanner/commit/c0a43638c81dd769cc55e021cc4cf1d93db8a72a)) + + +### Bug Fixes + +* **deps:** Update dependency @google-cloud/precise-date to v4 ([#1903](https://github.com/googleapis/nodejs-spanner/issues/1903)) ([7464c8b](https://github.com/googleapis/nodejs-spanner/commit/7464c8b2412a9b718cd8981363cb982aebbe3723)) +* **deps:** Update dependency @types/stack-trace to v0.0.33 ([#1952](https://github.com/googleapis/nodejs-spanner/issues/1952)) ([45ab751](https://github.com/googleapis/nodejs-spanner/commit/45ab751da1f0f73bc06c8b8e0007b457fa75518f)) +* **deps:** Update dependency retry-request to v7 ([#1934](https://github.com/googleapis/nodejs-spanner/issues/1934)) ([c575c80](https://github.com/googleapis/nodejs-spanner/commit/c575c80b17e5fdf2cbba24c806fa21f26c2010dc)) + +## [7.1.0](https://github.com/googleapis/nodejs-spanner/compare/v7.0.0...v7.1.0) (2023-11-16) + + +### Features + +* Add PG.OID type cod annotation ([69192b5](https://github.com/googleapis/nodejs-spanner/commit/69192b50ead0bde98676cb647ba4bf8a3112bb02)) +* **spanner:** Add autoscaling config to the instance proto ([#1935](https://github.com/googleapis/nodejs-spanner/issues/1935)) ([fe285c6](https://github.com/googleapis/nodejs-spanner/commit/fe285c67074ba36aaf5b49ea867c0d5851d83717)) +* **spanner:** Add directed_read_option in spanner.proto ([69192b5](https://github.com/googleapis/nodejs-spanner/commit/69192b50ead0bde98676cb647ba4bf8a3112bb02)) + + +### Bug Fixes + +* **deps:** Update dependency @types/stack-trace to v0.0.31 ([#1924](https://github.com/googleapis/nodejs-spanner/issues/1924)) ([96af405](https://github.com/googleapis/nodejs-spanner/commit/96af4051c6717dfcbbc6e117e3ecd7f8e9dd758a)) +* **deps:** Update dependency @types/stack-trace to v0.0.32 ([#1939](https://github.com/googleapis/nodejs-spanner/issues/1939)) ([cb66474](https://github.com/googleapis/nodejs-spanner/commit/cb66474e995a90c1288e70842f723c51f1ffd37d)) +* **deps:** Update dependency google-gax to v4.0.4 ([#1926](https://github.com/googleapis/nodejs-spanner/issues/1926)) ([361fe6a](https://github.com/googleapis/nodejs-spanner/commit/361fe6a812f56c6834f1f7c7db60fc1083243768)) +* **deps:** Update dependency google-gax to v4.0.5 ([#1937](https://github.com/googleapis/nodejs-spanner/issues/1937)) ([ab26075](https://github.com/googleapis/nodejs-spanner/commit/ab260759be2fcc9ff80342f710b4c807742da2c5)) + +## [7.0.0](https://github.com/googleapis/nodejs-spanner/compare/v6.16.0...v7.0.0) (2023-08-30) + + +### ⚠ BREAKING CHANGES + +* upgrade to Node 14 ([#1890](https://github.com/googleapis/nodejs-spanner/issues/1890)) + +### Bug Fixes + +* Idwaiter with multiple requests ([#1910](https://github.com/googleapis/nodejs-spanner/issues/1910)) ([83dd1f8](https://github.com/googleapis/nodejs-spanner/commit/83dd1f8201d07898bd3ddff9e339dfbcef7d7ace)) + + +### Miscellaneous Chores + +* Upgrade to Node 14 ([#1890](https://github.com/googleapis/nodejs-spanner/issues/1890)) ([0024772](https://github.com/googleapis/nodejs-spanner/commit/0024772b750de404cd44771e320fe89cd430f064)) + +## [6.16.0](https://github.com/googleapis/nodejs-spanner/compare/v6.15.0...v6.16.0) (2023-08-07) + + +### Features + +* Bit reverse sequence ([#1846](https://github.com/googleapis/nodejs-spanner/issues/1846)) ([4154c02](https://github.com/googleapis/nodejs-spanner/commit/4154c02f4c5ac1aa23f4c7c61521ab6fbabadfb8)) + + +### Bug Fixes + +* Databoost tests ([#1870](https://github.com/googleapis/nodejs-spanner/issues/1870)) ([45e13c7](https://github.com/googleapis/nodejs-spanner/commit/45e13c70607abf717d533a8c5b1c58752a5439cb)) + +## [6.15.0](https://github.com/googleapis/nodejs-spanner/compare/v6.14.0...v6.15.0) (2023-08-04) + + +### Features + +* Enable leader aware routing by default. This update contains performance optimisations that will reduce the latency of read/write transactions that originate from a region other than the default leader region. ([6852d99](https://github.com/googleapis/nodejs-spanner/commit/6852d99b858eb323ac3fc5e61905b8bf59486062)) + +## [6.14.0](https://github.com/googleapis/nodejs-spanner/compare/v6.13.0...v6.14.0) (2023-07-21) + + +### Features + +* Foreign key delete cascade testing, samples ([#1825](https://github.com/googleapis/nodejs-spanner/issues/1825)) ([74a54b0](https://github.com/googleapis/nodejs-spanner/commit/74a54b03f0d73a62edd524fa8d0248aea7ddf344)) +* Set LAR as False ([#1883](https://github.com/googleapis/nodejs-spanner/issues/1883)) ([ed510e8](https://github.com/googleapis/nodejs-spanner/commit/ed510e8545876e188e7bd782b6db80e677c3063c)) + +## [6.13.0](https://github.com/googleapis/nodejs-spanner/compare/v6.12.0...v6.13.0) (2023-07-21) + + +### Features + +* Enable leader aware routing by default. This update contains performance optimisations that will reduce the latency of read/write transactions that originate from a region other than the default leader region. ([87cd5e6](https://github.com/googleapis/nodejs-spanner/commit/87cd5e6ecdf6d888dd0e7fe712b7070c58b32d42)) + + +### Bug Fixes + +* **deps:** Update dependency yargs to v17 ([#1866](https://github.com/googleapis/nodejs-spanner/issues/1866)) ([24e321f](https://github.com/googleapis/nodejs-spanner/commit/24e321f6327cfdfc191a84bb47d80a156eff5be9)) + +## [6.12.0](https://github.com/googleapis/nodejs-spanner/compare/v6.11.0...v6.12.0) (2023-06-19) + + +### Features + +* Databoostenabled for Query and Read partitions ([#1784](https://github.com/googleapis/nodejs-spanner/issues/1784)) ([66ff70c](https://github.com/googleapis/nodejs-spanner/commit/66ff70cd377d5e3f60a6796bc36bab3a39337f31)) + +## [6.11.0](https://github.com/googleapis/nodejs-spanner/compare/v6.10.1...v6.11.0) (2023-06-06) + + +### Features + +* **spanner:** Add DdlStatementActionInfo and add actions to UpdateDatabaseDdlMetadata ([#1860](https://github.com/googleapis/nodejs-spanner/issues/1860)) ([3e86f36](https://github.com/googleapis/nodejs-spanner/commit/3e86f369b927e3bf0a2046bd13d0b6a39a9bb076)) +* Testing for fgac in pg ([#1811](https://github.com/googleapis/nodejs-spanner/issues/1811)) ([c48945f](https://github.com/googleapis/nodejs-spanner/commit/c48945f536685d6e4ee4097cfac7d5f57853553e)) + +## [6.10.1](https://github.com/googleapis/nodejs-spanner/compare/v6.10.0...v6.10.1) (2023-05-30) + + +### Bug Fixes + +* Set database admin and instance as having handwritten layers (republish docs) ([3e3e624](https://github.com/googleapis/nodejs-spanner/commit/3e3e624187013d62a5ff479386fb8961f279b5ca)) + +## [6.10.0](https://github.com/googleapis/nodejs-spanner/compare/v6.9.0...v6.10.0) (2023-05-17) + + +### Features + +* Add support for UpdateDatabase ([#1802](https://github.com/googleapis/nodejs-spanner/issues/1802)) ([f4fbe71](https://github.com/googleapis/nodejs-spanner/commit/f4fbe71d819fde9a237f25b03af228b27cf58689)) +* Add support for UpdateDatabase in Cloud Spanner ([#1848](https://github.com/googleapis/nodejs-spanner/issues/1848)) ([dd9d505](https://github.com/googleapis/nodejs-spanner/commit/dd9d505e1480b9f45f0f4a09b0abca8282d5fceb)) + + +### Bug Fixes + +* Set grpc useragent ([#1847](https://github.com/googleapis/nodejs-spanner/issues/1847)) ([021e54e](https://github.com/googleapis/nodejs-spanner/commit/021e54ef469d7d95bae64c687b65489cbfc56cfa)) + +## [6.9.0](https://github.com/googleapis/nodejs-spanner/compare/v6.8.0...v6.9.0) (2023-04-26) + + +### Features + +* Leader aware routing ([#1783](https://github.com/googleapis/nodejs-spanner/issues/1783)) ([0703f41](https://github.com/googleapis/nodejs-spanner/commit/0703f4160c4a0b4c9f9f716174daca110ab8e50f)) + +## [6.8.0](https://github.com/googleapis/nodejs-spanner/compare/v6.7.2...v6.8.0) (2023-04-06) + + +### Features + +* Adding new fields for Serverless analytics ([#1816](https://github.com/googleapis/nodejs-spanner/issues/1816)) ([2a6ca6f](https://github.com/googleapis/nodejs-spanner/commit/2a6ca6f09215752f9451d625ac02837e9d70b66a)) + + +### Bug Fixes + +* Begin transaction foes not handle error ([#1833](https://github.com/googleapis/nodejs-spanner/issues/1833)) ([6ecd366](https://github.com/googleapis/nodejs-spanner/commit/6ecd366da7183d502c710cb5c879984c276b12db)) +* Correcting the proto field Id for field data_boost_enabled ([#1827](https://github.com/googleapis/nodejs-spanner/issues/1827)) ([7f6d4cc](https://github.com/googleapis/nodejs-spanner/commit/7f6d4ccce9269197312f2d795ef854e1789e8fce)) +* Logic for retrying specifiied internal errors ([#1822](https://github.com/googleapis/nodejs-spanner/issues/1822)) ([f915bd1](https://github.com/googleapis/nodejs-spanner/commit/f915bd16cf7e817243e46a319b3e6f270b24bf68)), closes [#1808](https://github.com/googleapis/nodejs-spanner/issues/1808) + +## [6.7.2](https://github.com/googleapis/nodejs-spanner/compare/v6.7.1...v6.7.2) (2023-02-17) + + +### Bug Fixes + +* Tests emit empty metadata before emitting unspecified error ([14ef031](https://github.com/googleapis/nodejs-spanner/commit/14ef0318db756e7debad8599b1e274b8877291e1)) + +## [6.7.1](https://github.com/googleapis/nodejs-spanner/compare/v6.7.0...v6.7.1) (2023-01-23) + + +### Bug Fixes + +* Change of tag for fgac ([#1780](https://github.com/googleapis/nodejs-spanner/issues/1780)) ([d75b6dd](https://github.com/googleapis/nodejs-spanner/commit/d75b6dd79ffc2442cbd7a14f1ea952edc6678a64)) +* **codec:** Use index to determine array struct member value ([#1775](https://github.com/googleapis/nodejs-spanner/issues/1775)) ([fc2b695](https://github.com/googleapis/nodejs-spanner/commit/fc2b695d9ea6b65df856b4b081a75165009413ee)), closes [#1774](https://github.com/googleapis/nodejs-spanner/issues/1774) + +## [6.7.0](https://github.com/googleapis/nodejs-spanner/compare/v6.6.0...v6.7.0) (2023-01-17) + + +### Features + +* Added SuggestConversationSummary RPC ([#1744](https://github.com/googleapis/nodejs-spanner/issues/1744)) ([14346f3](https://github.com/googleapis/nodejs-spanner/commit/14346f3cf8ed0cb0a93c255dc520dc62887c0e1a)) + +## [6.6.0](https://github.com/googleapis/nodejs-spanner/compare/v6.5.0...v6.6.0) (2022-12-16) + + +### Features + +* Export data types in index.ts ([#1726](https://github.com/googleapis/nodejs-spanner/issues/1726)) ([844f57f](https://github.com/googleapis/nodejs-spanner/commit/844f57fa5e79e5e5a5ede80df5e117004427f201)), closes [#1720](https://github.com/googleapis/nodejs-spanner/issues/1720) +* Fgac support and samples ([#1751](https://github.com/googleapis/nodejs-spanner/issues/1751)) ([0a394df](https://github.com/googleapis/nodejs-spanner/commit/0a394df9bfa193d79edc4c3a3d26238f361c0d45)) + + +### Bug Fixes + +* Add sleep after admin request intensive tests ([#1758](https://github.com/googleapis/nodejs-spanner/issues/1758)) ([7643ceb](https://github.com/googleapis/nodejs-spanner/commit/7643ceb7cde9f420539877b86fdb0d38b254348d)) + +## [6.5.0](https://github.com/googleapis/nodejs-spanner/compare/v6.4.0...v6.5.0) (2022-11-30) + + +### Features + +* Inline BeginTransaction with first statement ([#1692](https://github.com/googleapis/nodejs-spanner/issues/1692)) ([d1b95d2](https://github.com/googleapis/nodejs-spanner/commit/d1b95d21e2c8cb0eff88351265cad248870bb3ea)) + + +### Bug Fixes + +* Cleanup different types of session pools ([#1739](https://github.com/googleapis/nodejs-spanner/issues/1739)) ([6f55187](https://github.com/googleapis/nodejs-spanner/commit/6f551877ea0d4b67e3c734377bdadd5d570cf839)) +* **deps:** Use google-gax v3.5.2 ([#1732](https://github.com/googleapis/nodejs-spanner/issues/1732)) ([8341b1f](https://github.com/googleapis/nodejs-spanner/commit/8341b1fa5dfcf0b286892efb8b57c7ad694cdbb8)) + +## [6.4.0](https://github.com/googleapis/nodejs-spanner/compare/v6.3.0...v6.4.0) (2022-10-27) + + +### Features + +* Adding support and samples for Jsonb data type in spangres ([#1729](https://github.com/googleapis/nodejs-spanner/issues/1729)) ([f050354](https://github.com/googleapis/nodejs-spanner/commit/f0503547012ab0ac8a04524ecf7bc92807f35379)) +* Update result_set.proto to return undeclared parameters in ExecuteSql API ([eaa445e](https://github.com/googleapis/nodejs-spanner/commit/eaa445ed314190abefc17e3672bb5e200142618b)) +* Update transaction.proto to include different lock modes ([#1723](https://github.com/googleapis/nodejs-spanner/issues/1723)) ([eaa445e](https://github.com/googleapis/nodejs-spanner/commit/eaa445ed314190abefc17e3672bb5e200142618b)) + +## [6.3.0](https://github.com/googleapis/nodejs-spanner/compare/v6.2.0...v6.3.0) (2022-10-03) + + +### Features + +* Support customer managed instance configurations ([#1611](https://github.com/googleapis/nodejs-spanner/issues/1611)) ([bbe8f69](https://github.com/googleapis/nodejs-spanner/commit/bbe8f697e8838e358973cd4a5f2db9e2d4df5349)) + + +### Bug Fixes + +* **deps:** Update dependency @google-cloud/precise-date to v3 ([#1676](https://github.com/googleapis/nodejs-spanner/issues/1676)) ([3f20ec4](https://github.com/googleapis/nodejs-spanner/commit/3f20ec47bbf89e1f72546a8ebf41a8b4ba93832f)) +* Do not import the whole google-gax from proto JS ([#1553](https://github.com/googleapis/nodejs-spanner/issues/1553)) ([#1700](https://github.com/googleapis/nodejs-spanner/issues/1700)) ([f9c2640](https://github.com/googleapis/nodejs-spanner/commit/f9c2640e054659a2e8299b8f989fa7936d04b0d7)) +* use google-gax v3.3.0 ([f9c2640](https://github.com/googleapis/nodejs-spanner/commit/f9c2640e054659a2e8299b8f989fa7936d04b0d7)) + +## [6.2.0](https://github.com/googleapis/nodejs-spanner/compare/v6.1.4...v6.2.0) (2022-09-16) + + +### Features + +* Add custom instance config operations ([#1712](https://github.com/googleapis/nodejs-spanner/issues/1712)) ([4b7716b](https://github.com/googleapis/nodejs-spanner/commit/4b7716be5409698e21bb79edec5cdf1019047de8)) + + +### Bug Fixes + +* Allow passing gax instance to client constructor ([#1698](https://github.com/googleapis/nodejs-spanner/issues/1698)) ([588c1a2](https://github.com/googleapis/nodejs-spanner/commit/588c1a2e0c449cfcb86cac73da32dd5794ee2baa)) +* **deps:** Use grpc-gcp v1.0.0 ([#1710](https://github.com/googleapis/nodejs-spanner/issues/1710)) ([12eab9d](https://github.com/googleapis/nodejs-spanner/commit/12eab9d628b72b5a7fc88f3d5e932b7a4d70dce2)) +* Move runtime dependencies from dev dependencies to dependencies ([#1704](https://github.com/googleapis/nodejs-spanner/issues/1704)) ([b2c1c0f](https://github.com/googleapis/nodejs-spanner/commit/b2c1c0f93653af6cc7bd9893ca14394f2a631b68)) +* Preserve default values in x-goog-request-params header ([#1711](https://github.com/googleapis/nodejs-spanner/issues/1711)) ([f1ae513](https://github.com/googleapis/nodejs-spanner/commit/f1ae51301d4ea9b0ed1ad4d4762c249fef9f8d08)) + +## [6.1.4](https://github.com/googleapis/nodejs-spanner/compare/v6.1.3...v6.1.4) (2022-09-06) + + +### Bug Fixes + +* Add hashes to requirements.txt ([#1544](https://github.com/googleapis/nodejs-spanner/issues/1544)) ([#1697](https://github.com/googleapis/nodejs-spanner/issues/1697)) ([61a1468](https://github.com/googleapis/nodejs-spanner/commit/61a1468fb0282bad642e643fc98a19d63acdcd1c)) +* Better support for fallback mode ([#1694](https://github.com/googleapis/nodejs-spanner/issues/1694)) ([bbc8831](https://github.com/googleapis/nodejs-spanner/commit/bbc88317149a3d86c50ccfd98092d5bfb77a104e)) +* Change import long to require ([#1695](https://github.com/googleapis/nodejs-spanner/issues/1695)) ([9283f4b](https://github.com/googleapis/nodejs-spanner/commit/9283f4bdfaea0ceececacbb80df3c37bd522b657)) +* **deps:** Update dependency @google-cloud/projectify to v3 ([#1678](https://github.com/googleapis/nodejs-spanner/issues/1678)) ([e3c1499](https://github.com/googleapis/nodejs-spanner/commit/e3c1499d0bdcbe3b578c5e7dc1d725630a1a0a30)) +* **deps:** Update dependency protobufjs to v7 ([#1686](https://github.com/googleapis/nodejs-spanner/issues/1686)) ([2839d23](https://github.com/googleapis/nodejs-spanner/commit/2839d2317ca7368d288ee9d7feb806f0ac2069c6)) +* Target new spanner db admin service config ([#1685](https://github.com/googleapis/nodejs-spanner/issues/1685)) ([2495c07](https://github.com/googleapis/nodejs-spanner/commit/2495c0723be70cf679ffa9e86f45199dbcd8c77b)) +* Test case fix to avoid the latest typescript dependency issue ([#1703](https://github.com/googleapis/nodejs-spanner/issues/1703)) ([6282f64](https://github.com/googleapis/nodejs-spanner/commit/6282f64560510ae54be26d992d168091f7e943bc)) + +## [6.1.3](https://github.com/googleapis/nodejs-spanner/compare/v6.1.2...v6.1.3) (2022-07-07) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/common to v4 ([#1663](https://github.com/googleapis/nodejs-spanner/issues/1663)) ([487c58c](https://github.com/googleapis/nodejs-spanner/commit/487c58ce2a2dbf21cdc1b43ea53d68ea6edbfd81)) + +## [6.1.2](https://github.com/googleapis/nodejs-spanner/compare/v6.1.1...v6.1.2) (2022-07-07) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/kms to v3 ([#1664](https://github.com/googleapis/nodejs-spanner/issues/1664)) ([42f41e9](https://github.com/googleapis/nodejs-spanner/commit/42f41e99f3cba9c3bdb981f70d6423c48adbc0d6)) + +## [6.1.1](https://github.com/googleapis/nodejs-spanner/compare/v6.1.0...v6.1.1) (2022-07-06) + + +### Bug Fixes + +* call Promise.race without a long pending promise to prevent memory leak ([#1657](https://github.com/googleapis/nodejs-spanner/issues/1657)) ([768acb6](https://github.com/googleapis/nodejs-spanner/commit/768acb6279914dfe84e372afc1d83dd76ca3dd4d)) +* **deps:** update dependency yargs to v17 ([#1537](https://github.com/googleapis/nodejs-spanner/issues/1537)) ([1039f68](https://github.com/googleapis/nodejs-spanner/commit/1039f68c7b459c2abeef4388fd8541576d374b66)) + +## [6.1.0](https://github.com/googleapis/nodejs-spanner/compare/v6.0.0...v6.1.0) (2022-07-04) + + +### Features + +* add Session creator role ([91ef6d3](https://github.com/googleapis/nodejs-spanner/commit/91ef6d373a1ed2c7e191de4003571270bfc4e895)) +* Adding two new fields for Instance create_time and update_time ([#1641](https://github.com/googleapis/nodejs-spanner/issues/1641)) ([91ef6d3](https://github.com/googleapis/nodejs-spanner/commit/91ef6d373a1ed2c7e191de4003571270bfc4e895)) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/promisify to v3 ([#1629](https://github.com/googleapis/nodejs-spanner/issues/1629)) ([1467956](https://github.com/googleapis/nodejs-spanner/commit/1467956314c77f66034fa3db166ba68d7c2aba2d)) +* Improve spanner.date handling of years before 1000AD ([#1654](https://github.com/googleapis/nodejs-spanner/issues/1654)) ([fd89a29](https://github.com/googleapis/nodejs-spanner/commit/fd89a294dcab017dbbe7000bce613b0d4ed60f96)) + +## [6.0.0](https://github.com/googleapis/nodejs-spanner/compare/v5.18.0...v6.0.0) (2022-06-07) + + +### ⚠ BREAKING CHANGES + +* update library to use Node 12 (#1637) + +### Features + +* Adding IT for date and commit timestamp ([#1621](https://github.com/googleapis/nodejs-spanner/issues/1621)) ([1367aa7](https://github.com/googleapis/nodejs-spanner/commit/1367aa7dc9818be5610dfc5ae67d09652e7009e5)) +* AuditConfig for IAM v1 ([#1599](https://github.com/googleapis/nodejs-spanner/issues/1599)) ([c358d66](https://github.com/googleapis/nodejs-spanner/commit/c358d668ca2a25f99ab73a4b6c1ebbe09c34d4de)) + + +### Bug Fixes + +* **deps:** update dependency grpc-gcp to ^0.4.0 ([#1603](https://github.com/googleapis/nodejs-spanner/issues/1603)) ([f00b3c6](https://github.com/googleapis/nodejs-spanner/commit/f00b3c65e58c2f36e69a05fef0b3c9bc68a4ee55)) +* fixes for dynamic routing and streaming descriptors ([#1639](https://github.com/googleapis/nodejs-spanner/issues/1639)) ([977a543](https://github.com/googleapis/nodejs-spanner/commit/977a543d693ca2f2e8bb303be6df592aa4def1dd)) +* pin version for nodejs gax-node ([#1617](https://github.com/googleapis/nodejs-spanner/issues/1617)) ([fb0017f](https://github.com/googleapis/nodejs-spanner/commit/fb0017ffab3cfa41cd132df4511a47fb68439bf5)) + + +### Build System + +* update library to use Node 12 ([#1637](https://github.com/googleapis/nodejs-spanner/issues/1637)) ([994acf3](https://github.com/googleapis/nodejs-spanner/commit/994acf3edd7c261085f58722fa2f86f95b3a56f3)) + +## [5.18.0](https://github.com/googleapis/nodejs-spanner/compare/v5.17.0...v5.18.0) (2022-04-03) + + +### Features + +* add support for Cross region backup proto changes ([#1587](https://github.com/googleapis/nodejs-spanner/issues/1587)) ([9439ca4](https://github.com/googleapis/nodejs-spanner/commit/9439ca4cf260923a7cb90e0568864cb719ab8fc6)) +* integration testing for postgres dialect ([#1593](https://github.com/googleapis/nodejs-spanner/issues/1593)) ([ebe06a6](https://github.com/googleapis/nodejs-spanner/commit/ebe06a6cefbeacc37c40f2474b9d265b78c846e2)) +* Postgres Numeric and database support ([#1592](https://github.com/googleapis/nodejs-spanner/issues/1592)) ([7ca3975](https://github.com/googleapis/nodejs-spanner/commit/7ca3975c5e25e78983f77df9e921642c90874f90)) +* Spanner copy backup ([#1530](https://github.com/googleapis/nodejs-spanner/issues/1530)) ([cefb1b4](https://github.com/googleapis/nodejs-spanner/commit/cefb1b4c831997e5c52122c5e6c3fd9cd9cb2c76)) + + +### Bug Fixes + +* removing table_catalog from schema information ([#1595](https://github.com/googleapis/nodejs-spanner/issues/1595)) ([8bcbd95](https://github.com/googleapis/nodejs-spanner/commit/8bcbd95e7423f03aa16ffd500fca998f75c8d0cf)) + +## [5.17.0](https://github.com/googleapis/nodejs-spanner/compare/v5.16.3...v5.17.0) (2022-03-09) + + +### Features + +* Refactor create database options schema to accept array ([#1578](https://github.com/googleapis/nodejs-spanner/issues/1578)) ([b1c88ac](https://github.com/googleapis/nodejs-spanner/commit/b1c88accee3770bb94e6a7d73e767eaa426a86a3)) + +### [5.16.3](https://github.com/googleapis/nodejs-spanner/compare/v5.16.3...v5.16.3) (2022-01-31) + + +### Miscellaneous Chores + +* Release-As: 5.16.3 ([#1556](https://github.com/googleapis/nodejs-spanner/issues/1556)) ([31f5fbc](https://github.com/googleapis/nodejs-spanner/commit/31f5fbc6d890fd7296497d6992a7d186ea786476)) + +### [5.16.3](https://github.com/googleapis/nodejs-spanner/compare/v5.16.3...v5.16.3) (2022-01-21) + + +### Miscellaneous Chores + +* Release-As: 5.16.3 ([#1556](https://github.com/googleapis/nodejs-spanner/issues/1556)) ([31f5fbc](https://github.com/googleapis/nodejs-spanner/commit/31f5fbc6d890fd7296497d6992a7d186ea786476)) + +### [5.16.3](https://github.com/googleapis/nodejs-spanner/compare/v5.16.2...v5.16.3) (2022-01-19) + + +### Bug Fixes + +* for merging when array/struct chunks contain null ([#1541](https://github.com/googleapis/nodejs-spanner/issues/1541)) ([72871fc](https://github.com/googleapis/nodejs-spanner/commit/72871fca5b67aec3af633484ff70a73be55372be)) + +### [5.16.2](https://github.com/googleapis/nodejs-spanner/compare/v5.16.1...v5.16.2) (2022-01-17) + + +### Bug Fixes + +* fix for new @types/node version ([#1542](https://github.com/googleapis/nodejs-spanner/issues/1542)) ([4b56c58](https://github.com/googleapis/nodejs-spanner/commit/4b56c584fa85ab8b22867157566ce7245daa8d8d)) + +### [5.16.1](https://www.github.com/googleapis/nodejs-spanner/compare/v5.16.0...v5.16.1) (2021-12-29) + + +### Bug Fixes + +* change in region ([#1523](https://www.github.com/googleapis/nodejs-spanner/issues/1523)) ([6caefc4](https://www.github.com/googleapis/nodejs-spanner/commit/6caefc4a0aafaa786a1d4b3fe3501d005d03bf6e)) + +## [5.16.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.15.2...v5.16.0) (2021-12-09) + + +### Features + +* add eslintignore for sameple generated code ([#1302](https://www.github.com/googleapis/nodejs-spanner/issues/1302)) ([#1520](https://www.github.com/googleapis/nodejs-spanner/issues/1520)) ([f835b72](https://www.github.com/googleapis/nodejs-spanner/commit/f835b721210d01b11d7f5751ee06f13518e7fe0f)) + + +### Bug Fixes + +* **build:** set default branch to main ([#1469](https://www.github.com/googleapis/nodejs-spanner/issues/1469)) ([152985a](https://www.github.com/googleapis/nodejs-spanner/commit/152985a1f783534e6b3e3ce332a1333dec67269d)) +* **cloud-rad:** move comments for TSDoc ([#1509](https://www.github.com/googleapis/nodejs-spanner/issues/1509)) ([1c49922](https://www.github.com/googleapis/nodejs-spanner/commit/1c49922c75bd56dbd0456318bee8a336eb088156)) + +### [5.15.2](https://www.github.com/googleapis/nodejs-spanner/compare/v5.15.1...v5.15.2) (2021-09-10) + + +### Bug Fixes + +* never try to create a negative number of sessions ([#1467](https://www.github.com/googleapis/nodejs-spanner/issues/1467)) ([13f5153](https://www.github.com/googleapis/nodejs-spanner/commit/13f51537ab13e0cd5a1fb9142f76796b1911809c)) + +### [5.15.1](https://www.github.com/googleapis/nodejs-spanner/compare/v5.15.0...v5.15.1) (2021-09-08) + + +### Bug Fixes + +* **deps:** google-gax v2.17.1 ([#1429](https://www.github.com/googleapis/nodejs-spanner/issues/1429)) ([3a1517c](https://www.github.com/googleapis/nodejs-spanner/commit/3a1517cff95bd00598935b30859c7991b4d4c4ca)) + +## [5.15.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.14.0...v5.15.0) (2021-08-26) + + +### Features + +* add support for JSON data type ([#1368](https://www.github.com/googleapis/nodejs-spanner/issues/1368)) ([b8d6fe5](https://www.github.com/googleapis/nodejs-spanner/commit/b8d6fe5b1e767576ba42d57d2e4e4597bca27883)) + +## [5.14.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.13.1...v5.14.0) (2021-08-24) + + +### Features + +* turns on self-signed JWT feature flag ([#1455](https://www.github.com/googleapis/nodejs-spanner/issues/1455)) ([2867a80](https://www.github.com/googleapis/nodejs-spanner/commit/2867a80319c07b4d40e88026409722f26db47631)) + +### [5.13.1](https://www.github.com/googleapis/nodejs-spanner/compare/v5.13.0...v5.13.1) (2021-08-17) + + +### Bug Fixes + +* **deps:** google-gax v2.24.1 ([#1452](https://www.github.com/googleapis/nodejs-spanner/issues/1452)) ([7379eb2](https://www.github.com/googleapis/nodejs-spanner/commit/7379eb260a8fe4a37b71ccf9ad9e2e17d9669c5f)) + +## [5.13.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.12.0...v5.13.0) (2021-08-04) + + +### Features + +* add GetInstanceConfig function ([#1438](https://www.github.com/googleapis/nodejs-spanner/issues/1438)) ([24b3524](https://www.github.com/googleapis/nodejs-spanner/commit/24b35242d3ce52e16a5fa04ff949ca44a6608396)) + + +### Bug Fixes + +* adding option to skip back up tests ([#1445](https://www.github.com/googleapis/nodejs-spanner/issues/1445)) ([e189e5a](https://www.github.com/googleapis/nodejs-spanner/commit/e189e5a03c6e40d3adc64233e72d9d9748e0bc0a)) + +## [5.12.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.11.1...v5.12.0) (2021-07-08) + + +### Features + +* add tagging support ([#1419](https://www.github.com/googleapis/nodejs-spanner/issues/1419)) ([4770dab](https://www.github.com/googleapis/nodejs-spanner/commit/4770dab607e50e81d79c8c4c8fafbb278cb08954)) + +### [5.11.1](https://www.github.com/googleapis/nodejs-spanner/compare/v5.11.0...v5.11.1) (2021-07-07) + + +### Bug Fixes + +* add close method to Spanner client ([#1416](https://www.github.com/googleapis/nodejs-spanner/issues/1416)) ([69cd0b4](https://www.github.com/googleapis/nodejs-spanner/commit/69cd0b474ab6c836724813fd8bea88ec2e1ac9f5)), closes [#1306](https://www.github.com/googleapis/nodejs-spanner/issues/1306) + +## [5.11.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.10.0...v5.11.0) (2021-07-01) + + +### Features + +* **spanner:** add leader_options to InstanceConfig and default_leader to Database ([#1414](https://www.github.com/googleapis/nodejs-spanner/issues/1414)) ([e67adc2](https://www.github.com/googleapis/nodejs-spanner/commit/e67adc281d603d741af49d957eff05fd4184d38e)) + +## [5.10.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.9.3...v5.10.0) (2021-06-30) + + +### Features + +* create instances with processing units ([#1279](https://www.github.com/googleapis/nodejs-spanner/issues/1279)) ([05c2135](https://www.github.com/googleapis/nodejs-spanner/commit/05c213522a32627186ad9b474b416c1b9996df1f)) + + +### Bug Fixes + +* replace projectId placeholder in formatted names ([#1407](https://www.github.com/googleapis/nodejs-spanner/issues/1407)) ([4364d2b](https://www.github.com/googleapis/nodejs-spanner/commit/4364d2b25638384a6a1bea2e283b1219b4e5cdf3)), closes [#1375](https://www.github.com/googleapis/nodejs-spanner/issues/1375) + +### [5.9.3](https://www.github.com/googleapis/nodejs-spanner/compare/v5.9.2...v5.9.3) (2021-06-29) + + +### Bug Fixes + +* **deps:** require google-gax v2.17.0 ([#1409](https://www.github.com/googleapis/nodejs-spanner/issues/1409)) ([080d82f](https://www.github.com/googleapis/nodejs-spanner/commit/080d82f455324d2010187904532032e7905e14ac)) + +### [5.9.2](https://www.github.com/googleapis/nodejs-spanner/compare/v5.9.1...v5.9.2) (2021-06-25) + + +### Bug Fixes + +* reset buffered chunked value before retry ([#1397](https://www.github.com/googleapis/nodejs-spanner/issues/1397)) ([da2ca7b](https://www.github.com/googleapis/nodejs-spanner/commit/da2ca7b15539119fada7869c206ad24460d8edfa)), closes [#1392](https://www.github.com/googleapis/nodejs-spanner/issues/1392) + +### [5.9.1](https://www.github.com/googleapis/nodejs-spanner/compare/v5.9.0...v5.9.1) (2021-06-24) + + +### Bug Fixes + +* make request optional in all cases ([#1400](https://www.github.com/googleapis/nodejs-spanner/issues/1400)) ([0b78770](https://www.github.com/googleapis/nodejs-spanner/commit/0b78770bfef6f463abb0f336999f7dfd61b5b2fe)) + +## [5.9.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.8.1...v5.9.0) (2021-06-14) + + +### Features + +* **spanner:** add processing_units to Instance resource ([#1398](https://www.github.com/googleapis/nodejs-spanner/issues/1398)) ([878cd3f](https://www.github.com/googleapis/nodejs-spanner/commit/878cd3f1596526b6e4e2457babd3dc2c2add11ad)) + +### [5.8.1](https://www.github.com/googleapis/nodejs-spanner/compare/v5.8.0...v5.8.1) (2021-06-10) + + +### Bug Fixes + +* unknown errors should not be retried ([#1388](https://www.github.com/googleapis/nodejs-spanner/issues/1388)) ([1d6f4e2](https://www.github.com/googleapis/nodejs-spanner/commit/1d6f4e2923bc1ac20c0a73c342332ec2ae259812)), closes [#1387](https://www.github.com/googleapis/nodejs-spanner/issues/1387) + +## [5.8.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.7.0...v5.8.0) (2021-06-07) + + +### Features + +* support setting `optimizerStatisticsPackage` ([#1225](https://www.github.com/googleapis/nodejs-spanner/issues/1225)) ([dadc6dc](https://www.github.com/googleapis/nodejs-spanner/commit/dadc6dcf5c01e1bb380555fa9ea2ba9182af049c)) + + +### Bug Fixes + +* ensure table funcs accept gaxOptions directly ([#1371](https://www.github.com/googleapis/nodejs-spanner/issues/1371)) ([2c57c16](https://www.github.com/googleapis/nodejs-spanner/commit/2c57c1631a93d545bab52e309a5acd7641a747f3)) +* lint issue ([#1372](https://www.github.com/googleapis/nodejs-spanner/issues/1372)) ([3be0b4b](https://www.github.com/googleapis/nodejs-spanner/commit/3be0b4b51c8a76c7682101851d94e0611a87bc24)) + +## [5.7.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.6.1...v5.7.0) (2021-04-21) + + +### Features + +* regenerate protos with new types ([#1335](https://www.github.com/googleapis/nodejs-spanner/issues/1335)) ([cc6980e](https://www.github.com/googleapis/nodejs-spanner/commit/cc6980e364ea641f55b4ff1a765b22333352419a)) +* support RPC priority ([#1282](https://www.github.com/googleapis/nodejs-spanner/issues/1282)) ([8c82694](https://www.github.com/googleapis/nodejs-spanner/commit/8c8269437291a96aaed97db6684f7c8907f1fe43)) + + +### Bug Fixes + +* prevent unhandled promise rejection while projectId or credential not found ([#1340](https://www.github.com/googleapis/nodejs-spanner/issues/1340)) ([47ce076](https://www.github.com/googleapis/nodejs-spanner/commit/47ce0765cce4bdf8513917c86ec1db9c53f97618)) +* prevent unhandled promise rejections while creating session ([#1332](https://www.github.com/googleapis/nodejs-spanner/issues/1332)) ([b62bf5e](https://www.github.com/googleapis/nodejs-spanner/commit/b62bf5e1a96c495f73512a97419ecf98915b457e)) + +### [5.6.1](https://www.github.com/googleapis/nodejs-spanner/compare/v5.6.0...v5.6.1) (2021-03-30) + + +### Bug Fixes + +* remove acquire timeout listener on return of session ([#1327](https://www.github.com/googleapis/nodejs-spanner/issues/1327)) ([72c7cce](https://www.github.com/googleapis/nodejs-spanner/commit/72c7cce0cc00631a0ce46cdb2bf66a0ee48d615b)), closes [#1324](https://www.github.com/googleapis/nodejs-spanner/issues/1324) + +## [5.6.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.5.0...v5.6.0) (2021-03-20) + + +### Features + +* customer-managed encryption keys ([#1274](https://www.github.com/googleapis/nodejs-spanner/issues/1274)) ([51cabc7](https://www.github.com/googleapis/nodejs-spanner/commit/51cabc7a6d8c96a86acbbeea3a357c261248ddb4)) + + +### Bug Fixes + +* remove common protos ([#1320](https://www.github.com/googleapis/nodejs-spanner/issues/1320)) ([a73f9fc](https://www.github.com/googleapis/nodejs-spanner/commit/a73f9fc534019186e262a3e5ac6a78f156e7a56d)) +* run [spanner_batch_client] independently ([#1318](https://www.github.com/googleapis/nodejs-spanner/issues/1318)) ([3844ff8](https://www.github.com/googleapis/nodejs-spanner/commit/3844ff89cb53aeeefe7309ce82f31200a0de3ae2)) + +## [5.5.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.4.0...v5.5.0) (2021-02-19) + + +### Features + +* add option for returning Spanner commit stats ([#1297](https://www.github.com/googleapis/nodejs-spanner/issues/1297)) ([bc286e2](https://www.github.com/googleapis/nodejs-spanner/commit/bc286e24b1d6f83cd09bdaad2023e8347ab1d12e)) +* adds PITR fields to backup and database ([#1299](https://www.github.com/googleapis/nodejs-spanner/issues/1299)) ([d7556c8](https://www.github.com/googleapis/nodejs-spanner/commit/d7556c89b92e2a9ab65f1f928faf8c452bf24a7c)) +* adds style enumeration ([#1292](https://www.github.com/googleapis/nodejs-spanner/issues/1292)) ([dcf7013](https://www.github.com/googleapis/nodejs-spanner/commit/dcf7013907f8e232d0b99303a6d30be598944db9)) +* CommitStats in CommitResponse ([#1254](https://www.github.com/googleapis/nodejs-spanner/issues/1254)) ([e3730d2](https://www.github.com/googleapis/nodejs-spanner/commit/e3730d219fb395d1ce8416b1e7cdecb0c8ad995e)) +* Point In Time Recovery (PITR) ([#1250](https://www.github.com/googleapis/nodejs-spanner/issues/1250)) ([c53f677](https://www.github.com/googleapis/nodejs-spanner/commit/c53f677fe33ca5ed6fc65e8ee350f365d03a7642)) +* return ResultSetMetadata for query ([#1308](https://www.github.com/googleapis/nodejs-spanner/issues/1308)) ([6625ef2](https://www.github.com/googleapis/nodejs-spanner/commit/6625ef2168ade370596ffefe92fc75640cf9f6f1)) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v7 ([#1305](https://www.github.com/googleapis/nodejs-spanner/issues/1305)) ([329c901](https://www.github.com/googleapis/nodejs-spanner/commit/329c901927885c6fd34f99c71abead15ff10f7d8)) +* **sample-test:** ensure instance is created before proceeding with tests ([#1291](https://www.github.com/googleapis/nodejs-spanner/issues/1291)) ([577357a](https://www.github.com/googleapis/nodejs-spanner/commit/577357ab8f8cdac70f5483312c7618c6e403fd26)) +* wrong gaxOptions argument in sample ([#1294](https://www.github.com/googleapis/nodejs-spanner/issues/1294)) ([8fec23a](https://www.github.com/googleapis/nodejs-spanner/commit/8fec23a28accbaa28cfb980bac406c50b1935e32)) + +## [5.4.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.3.0...v5.4.0) (2020-12-02) + + +### Features + +* support callbacks with database getRestoreInfo(), getState(), getOperations() ([#1230](https://www.github.com/googleapis/nodejs-spanner/issues/1230)) ([b56758b](https://www.github.com/googleapis/nodejs-spanner/commit/b56758b0e832c6471d14bd88b4580d21d5696fdd)) + + +### Bug Fixes + +* **browser:** check for fetch on window ([32ac608](https://www.github.com/googleapis/nodejs-spanner/commit/32ac6082383d5265f5022d97f23173e8786f4a82)) +* do not modify options object, use defaultScopes ([#1264](https://www.github.com/googleapis/nodejs-spanner/issues/1264)) ([6628c6a](https://www.github.com/googleapis/nodejs-spanner/commit/6628c6a81d427b8bb8bb1a42ae63f991b1cf73c9)) +* **deps:** update dependency big.js to v6 ([#1244](https://www.github.com/googleapis/nodejs-spanner/issues/1244)) ([259a51e](https://www.github.com/googleapis/nodejs-spanner/commit/259a51ee0726aa8f0b7717acd5253ecb77b16038)) +* do not create sessions after getDatabases call ([#1228](https://www.github.com/googleapis/nodejs-spanner/issues/1228)) ([53d5f37](https://www.github.com/googleapis/nodejs-spanner/commit/53d5f371d54c64dd095ac9ec721d05adf2c7d064)) +* **deps:** update dependency @google-cloud/precise-date to v2 ([#1240](https://www.github.com/googleapis/nodejs-spanner/issues/1240)) ([38dfec2](https://www.github.com/googleapis/nodejs-spanner/commit/38dfec22dd00f4d69750fc20e66c2395a9c6d3b3)) +* **deps:** update dependency yargs to v16 ([#1233](https://www.github.com/googleapis/nodejs-spanner/issues/1233)) ([75fd09a](https://www.github.com/googleapis/nodejs-spanner/commit/75fd09acb5a9a728a8b6403f44351e4b9b44b723)) + +## [5.3.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.2.1...v5.3.0) (2020-09-04) + + +### Features + +* accept gaxOptions in Database and Session #delete() ([#1206](https://www.github.com/googleapis/nodejs-spanner/issues/1206)) ([2444e8e](https://www.github.com/googleapis/nodejs-spanner/commit/2444e8e45f409e783fcbf059d487d50eb4e12d88)) +* add resource header prefix ([#1196](https://www.github.com/googleapis/nodejs-spanner/issues/1196)) ([99744b6](https://www.github.com/googleapis/nodejs-spanner/commit/99744b6e3c7e61e185949913279edae35a234dce)) +* return full nextQuery object in paginated calls ([#1199](https://www.github.com/googleapis/nodejs-spanner/issues/1199)) ([445015f](https://www.github.com/googleapis/nodejs-spanner/commit/445015f82243611fc8de3213957fda352fff4783)) +* set metadata during getBackups and getMetadata calls ([#1198](https://www.github.com/googleapis/nodejs-spanner/issues/1198)) ([aa500a5](https://www.github.com/googleapis/nodejs-spanner/commit/aa500a517a4f825f4440936158f72a0bcc63cd35)) +* spanner NUMERIC support ([#1163](https://www.github.com/googleapis/nodejs-spanner/issues/1163)) ([4724ba3](https://www.github.com/googleapis/nodejs-spanner/commit/4724ba3937de9481356084fc5e8254d8691583e5)) +* Spanner numeric type, add Node 8 tests ([#1189](https://www.github.com/googleapis/nodejs-spanner/issues/1189)) ([c2bc40e](https://www.github.com/googleapis/nodejs-spanner/commit/c2bc40e9b71b658d68c7377d5598cc1a0ef0f75d)) + + +### Bug Fixes + +* `Database not found` could be returned after create() ([#1220](https://www.github.com/googleapis/nodejs-spanner/issues/1220)) ([1fddbb9](https://www.github.com/googleapis/nodejs-spanner/commit/1fddbb9847068a607e72993c2c4c09b796b70089)), closes [#1219](https://www.github.com/googleapis/nodejs-spanner/issues/1219) [#1219](https://www.github.com/googleapis/nodejs-spanner/issues/1219) +* batch transaction should use a session from the pool ([#1207](https://www.github.com/googleapis/nodejs-spanner/issues/1207)) ([0708baa](https://www.github.com/googleapis/nodejs-spanner/commit/0708baab276def6cad0f0f3c4b7589084380c2d8)), closes [#1200](https://www.github.com/googleapis/nodejs-spanner/issues/1200) +* handle potential errors when creating stream ([#1208](https://www.github.com/googleapis/nodejs-spanner/issues/1208)) ([fcf35f5](https://www.github.com/googleapis/nodejs-spanner/commit/fcf35f5749b47b47425285eca5da47b987b0e7cf)), closes [#1078](https://www.github.com/googleapis/nodejs-spanner/issues/1078) +* retry PDML on Aborted and Internal errors ([#1205](https://www.github.com/googleapis/nodejs-spanner/issues/1205)) ([2b97bac](https://www.github.com/googleapis/nodejs-spanner/commit/2b97bacf4188f2344f23971ec667d3e20f04d420)), closes [#1197](https://www.github.com/googleapis/nodejs-spanner/issues/1197) +* update minimum gax version to 2.7.0 ([#1213](https://www.github.com/googleapis/nodejs-spanner/issues/1213)) ([224de8f](https://www.github.com/googleapis/nodejs-spanner/commit/224de8f0e69e2e951be6596d83079012736cdc20)), closes [#1209](https://www.github.com/googleapis/nodejs-spanner/issues/1209) +* **spanner:** update UpdateBackup to be retryable ([#1194](https://www.github.com/googleapis/nodejs-spanner/issues/1194)) ([e53a247](https://www.github.com/googleapis/nodejs-spanner/commit/e53a2471beff22a61c8e17098ba1a9b6cff3caf0)) +* typeo in nodejs .gitattribute ([#1178](https://www.github.com/googleapis/nodejs-spanner/issues/1178)) ([439d5af](https://www.github.com/googleapis/nodejs-spanner/commit/439d5af2124cc02f24e097d8101f9d6843de9b20)) + +### [5.2.1](https://www.github.com/googleapis/nodejs-spanner/compare/v5.2.0...v5.2.1) (2020-07-07) + + +### Bug Fixes + +* remove error listener to prevent memory leak ([#1168](https://www.github.com/googleapis/nodejs-spanner/issues/1168)) ([523bd67](https://www.github.com/googleapis/nodejs-spanner/commit/523bd67ed6d5ecbfe9abce0f1b6ed4cce2c07b30)) + + +### Performance Improvements + +* increase default min sessions to 25 ([#1167](https://www.github.com/googleapis/nodejs-spanner/issues/1167)) ([e4aba27](https://www.github.com/googleapis/nodejs-spanner/commit/e4aba27d307e5932b223121af5bea37a7418bb20)) + +## [5.2.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.1.0...v5.2.0) (2020-06-30) + + +### Features + +* add code sample for creating an instance ([#1073](https://www.github.com/googleapis/nodejs-spanner/issues/1073)) ([ab6dc62](https://www.github.com/googleapis/nodejs-spanner/commit/ab6dc62061e6893ec170b07fc3ffebbd2a4179f8)) +* **secrets:** begin migration to secret manager from keystore ([#1092](https://www.github.com/googleapis/nodejs-spanner/issues/1092)) ([2031652](https://www.github.com/googleapis/nodejs-spanner/commit/2031652e062004d06a18605dc45fdd00bd52989f)) + + +### Bug Fixes + +* handle fallback option properly ([#1146](https://www.github.com/googleapis/nodejs-spanner/issues/1146)) ([70d3f2c](https://www.github.com/googleapis/nodejs-spanner/commit/70d3f2c1cd89f71d777b6bc06b48931b8e075417)) +* **samples-test:** race condition in deleteData sample ([#1156](https://www.github.com/googleapis/nodejs-spanner/issues/1156)) ([39d8f0c](https://www.github.com/googleapis/nodejs-spanner/commit/39d8f0cf28f0d7df76d3d0f0d967d1ce574df3ce)) +* race condition in "should transfer value from one record to another using DML statements within a transaction test" ([#1159](https://www.github.com/googleapis/nodejs-spanner/issues/1159)) ([0c46714](https://www.github.com/googleapis/nodejs-spanner/commit/0c4671460b265965482afb1894deacdc60900ee7)) +* set displayName in CreateInstance sample ([#1145](https://www.github.com/googleapis/nodejs-spanner/issues/1145)) ([f9e47d9](https://www.github.com/googleapis/nodejs-spanner/commit/f9e47d9e1b9067b7488ad73b67b656efc4bb93d7)) +* set instanceId to the given id ([#1094](https://www.github.com/googleapis/nodejs-spanner/issues/1094)) ([8973cbc](https://www.github.com/googleapis/nodejs-spanner/commit/8973cbcc9158b37650af2edb6015c575da1cc3ec)), closes [#1093](https://www.github.com/googleapis/nodejs-spanner/issues/1093) +* unskip PDML tests when run against emulator ([#1150](https://www.github.com/googleapis/nodejs-spanner/issues/1150)) ([8465482](https://www.github.com/googleapis/nodejs-spanner/commit/8465482fad3b40b524f0d3e255983ddd75440e3e)) +* update DELETE samples to match docs ([#1072](https://www.github.com/googleapis/nodejs-spanner/issues/1072)) ([3336e04](https://www.github.com/googleapis/nodejs-spanner/commit/3336e04f6ff75539712d62ce2afabc70d8738150)) +* update node issue template ([#1157](https://www.github.com/googleapis/nodejs-spanner/issues/1157)) ([27d0699](https://www.github.com/googleapis/nodejs-spanner/commit/27d0699851c24b49a77ad7e2751804a7911d698c)) + + +### Performance Improvements + +* use write fraction when resizing pool ([#1031](https://www.github.com/googleapis/nodejs-spanner/issues/1031)) ([58f773b](https://www.github.com/googleapis/nodejs-spanner/commit/58f773b17459a96abcd3b5345aaaf497a2386840)) + +## [5.1.0](https://www.github.com/googleapis/nodejs-spanner/compare/v5.0.0...v5.1.0) (2020-06-04) + + +### Features + +* expose displayName in createInstance ([#798](https://www.github.com/googleapis/nodejs-spanner/issues/798)) ([39efda1](https://www.github.com/googleapis/nodejs-spanner/commit/39efda194d2d11a578f209e6c149b0ae2974ee27)) +* increase sessions in the pool in batches ([#963](https://www.github.com/googleapis/nodejs-spanner/issues/963)) ([91c53cb](https://www.github.com/googleapis/nodejs-spanner/commit/91c53cb6f6504f48ee3c974dbb8fb2821c226325)) +* support callbacks for exists(), getState(), getExpireTime() methods ([#1070](https://www.github.com/googleapis/nodejs-spanner/issues/1070)) ([7736080](https://www.github.com/googleapis/nodejs-spanner/commit/7736080f0e2a46c7ef8c44c278bff2bec2f28953)) + + +### Bug Fixes + +* always clean up stale instances if any ([#1030](https://www.github.com/googleapis/nodejs-spanner/issues/1030)) ([87c7edc](https://www.github.com/googleapis/nodejs-spanner/commit/87c7edcb2c3ba729b1e278bb191b695b0cd376cb)) +* pause request stream on backpressure ([#936](https://www.github.com/googleapis/nodejs-spanner/issues/936)) ([558692f](https://www.github.com/googleapis/nodejs-spanner/commit/558692f55cc551db2bd72464b130051a9b28378f)), closes [#934](https://www.github.com/googleapis/nodejs-spanner/issues/934) + +## [5.0.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.8.0...v5.0.0) (2020-05-14) + + +### ⚠ BREAKING CHANGES + +* **types:** properly format listing methods with gaxOptions (#925) +* **types:** types for createInstance (#805) +* add typings for top level object (#781) +* **deps:** update dependency @google-cloud/common to v3 (#875) +* drop Node.js 8 support. + +### Features + +* add typings for top level object ([#781](https://www.github.com/googleapis/nodejs-spanner/issues/781)) ([c2b6f68](https://www.github.com/googleapis/nodejs-spanner/commit/c2b6f685c2f36866ddaa434c923be417de0f89ec)) +* check status of long running operation by its name ([#937](https://www.github.com/googleapis/nodejs-spanner/issues/937)) ([5035e11](https://www.github.com/googleapis/nodejs-spanner/commit/5035e11f55a28def0d524a8e6ea7671367cd345e)) +* run and runStream can return query stats ([#857](https://www.github.com/googleapis/nodejs-spanner/issues/857)) ([1656e4f](https://www.github.com/googleapis/nodejs-spanner/commit/1656e4f14f0dd24f530f36ecf1ccf34b51e726fb)) +* spanner backup and restore support ([#855](https://www.github.com/googleapis/nodejs-spanner/issues/855)) ([967903c](https://www.github.com/googleapis/nodejs-spanner/commit/967903c4152e283f5a09dbd1b8ab3c9bc66728d3)) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/common to v3 ([#875](https://www.github.com/googleapis/nodejs-spanner/issues/875)) ([f3da343](https://www.github.com/googleapis/nodejs-spanner/commit/f3da3430645ae277ae40410b6494ea8477937610)) +* **deps:** update dependency @google-cloud/paginator to v3 ([#871](https://www.github.com/googleapis/nodejs-spanner/issues/871)) ([d3b2f2c](https://www.github.com/googleapis/nodejs-spanner/commit/d3b2f2c48a21e41700877677bb2041b368773e36)) +* **deps:** update dependency @google-cloud/precise-date to v2 ([#873](https://www.github.com/googleapis/nodejs-spanner/issues/873)) ([8e8b29c](https://www.github.com/googleapis/nodejs-spanner/commit/8e8b29c389d68d0f872726655c9022d899a3ea3c)) +* **deps:** update dependency @google-cloud/projectify to v2 ([#870](https://www.github.com/googleapis/nodejs-spanner/issues/870)) ([e77460b](https://www.github.com/googleapis/nodejs-spanner/commit/e77460b6cc005049833f206f3fa74fc722ee3536)) +* **deps:** update dependency @google-cloud/promisify to v2 ([#868](https://www.github.com/googleapis/nodejs-spanner/issues/868)) ([afe4b15](https://www.github.com/googleapis/nodejs-spanner/commit/afe4b1518aadee91fb339512470e550295f89c4d)) +* **types:** fix type of ReadRequest ([#876](https://www.github.com/googleapis/nodejs-spanner/issues/876)) ([990fec2](https://www.github.com/googleapis/nodejs-spanner/commit/990fec20c482e11f48b8b7fbaacae8f395e93db9)) +* **types:** properly format listing methods with gaxOptions ([#925](https://www.github.com/googleapis/nodejs-spanner/issues/925)) ([23958ae](https://www.github.com/googleapis/nodejs-spanner/commit/23958ae48f49306cf38755831db091fef16998fb)) +* delete old instances then create new instance ([#955](https://www.github.com/googleapis/nodejs-spanner/issues/955)) ([96813f8](https://www.github.com/googleapis/nodejs-spanner/commit/96813f81913322f6c9a84aa9c7757029ce5f48eb)) +* remove eslint, update gax, fix generated protos, run the generator ([#897](https://www.github.com/googleapis/nodejs-spanner/issues/897)) ([7cfba21](https://www.github.com/googleapis/nodejs-spanner/commit/7cfba215b436e997919a9816bd076c62cce90bbf)) +* remove src/common-grpc/operation.ts ([#879](https://www.github.com/googleapis/nodejs-spanner/issues/879)) ([a30d2b4](https://www.github.com/googleapis/nodejs-spanner/commit/a30d2b47b2ccbbdf0d473281a4f76584c4850659)), closes [#878](https://www.github.com/googleapis/nodejs-spanner/issues/878) +* remove typescript conversion leftovers ([#901](https://www.github.com/googleapis/nodejs-spanner/issues/901)) ([ccf1b61](https://www.github.com/googleapis/nodejs-spanner/commit/ccf1b61bcf060a72c35712c5d0e529fad9684724)) +* skip some tests when run against the emulator ([#933](https://www.github.com/googleapis/nodejs-spanner/issues/933)) ([2d91757](https://www.github.com/googleapis/nodejs-spanner/commit/2d917575dade110cbb3418d5d48c6fd0e77fae63)) +* update spanner package in sample ([#930](https://www.github.com/googleapis/nodejs-spanner/issues/930)) ([5624b7b](https://www.github.com/googleapis/nodejs-spanner/commit/5624b7bafb585adcbd0a7c9d53f728ff77afb1fa)) +* use DELETE FROM for consistency ([#923](https://www.github.com/googleapis/nodejs-spanner/issues/923)) ([0854c70](https://www.github.com/googleapis/nodejs-spanner/commit/0854c70d810ea05e5077d4c1a801040347415cfd)) +* **types:** types for createInstance ([#805](https://www.github.com/googleapis/nodejs-spanner/issues/805)) ([67b0f54](https://www.github.com/googleapis/nodejs-spanner/commit/67b0f54c65b51ff9cec313f67c4ea54dab7c8123)) + + +### Build System + +* drop node8 and convert to TypeScript ([#888](https://www.github.com/googleapis/nodejs-spanner/issues/888)) ([4116f81](https://www.github.com/googleapis/nodejs-spanner/commit/4116f81ec9715fde14b48e0daa6930bb8c502dbe)) + +## [4.8.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.7.0...v4.8.0) (2020-03-12) + + +### Features + +* add backups API ([#851](https://www.github.com/googleapis/nodejs-spanner/issues/851)) ([faf224d](https://www.github.com/googleapis/nodejs-spanner/commit/faf224dc4010337829eb0b6ecd7df274f1de5fff)) +* add support for QueryOptions ([#846](https://www.github.com/googleapis/nodejs-spanner/issues/846)) ([c1098c5](https://www.github.com/googleapis/nodejs-spanner/commit/c1098c5f4509918cacd3942b8f09354c88a85bb9)) + +## [4.7.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.6.2...v4.7.0) (2020-02-27) + + +### Features + +* export protos in src/index.ts ([0fa0f93](https://www.github.com/googleapis/nodejs-spanner/commit/0fa0f933ac9655278a4684bfa9e07cc912442fbf)) + +### [4.6.2](https://www.github.com/googleapis/nodejs-spanner/compare/v4.6.1...v4.6.2) (2020-02-14) + + +### Bug Fixes + +* Correctly parse metadata from BatchDML response + fix flaky system test ([#825](https://www.github.com/googleapis/nodejs-spanner/issues/825)) ([8b95da7](https://www.github.com/googleapis/nodejs-spanner/commit/8b95da7c68694d7a4ce5644e82d8485d01efb434)) +* retry 'Session not found' errors on getSnapshot ([#819](https://www.github.com/googleapis/nodejs-spanner/issues/819)) ([59bafbf](https://www.github.com/googleapis/nodejs-spanner/commit/59bafbfbcfe1fc3c45291a6fab6a343299123905)) +* retry 'Session not found' for r/w tx ([#824](https://www.github.com/googleapis/nodejs-spanner/issues/824)) ([1b393c4](https://www.github.com/googleapis/nodejs-spanner/commit/1b393c4c940d196232f8fc6ac99dbb5d1fd61e4d)) + +### [4.6.1](https://www.github.com/googleapis/nodejs-spanner/compare/v4.6.0...v4.6.1) (2020-01-29) + + +### Bug Fixes + +* enum, bytes, and Long types now accept strings ([#816](https://www.github.com/googleapis/nodejs-spanner/issues/816)) ([e63914d](https://www.github.com/googleapis/nodejs-spanner/commit/e63914d19813400daa2b08abfba43e1d87abfe7b)) +* fixed wrong return type of Database.run(..) ([#810](https://www.github.com/googleapis/nodejs-spanner/issues/810)) ([10c31d8](https://www.github.com/googleapis/nodejs-spanner/commit/10c31d80fdde2b91f2498ffcbc90a20a83c1a454)), closes [#809](https://www.github.com/googleapis/nodejs-spanner/issues/809) +* retry Session not found for Database.run(..) ([#812](https://www.github.com/googleapis/nodejs-spanner/issues/812)) ([6a48fd6](https://www.github.com/googleapis/nodejs-spanner/commit/6a48fd61bc6f424865e5a265bc1d7bac81454a7d)) +* use PreciseDate instead of Date for min read timestamp ([#807](https://www.github.com/googleapis/nodejs-spanner/issues/807)) ([da8c2f8](https://www.github.com/googleapis/nodejs-spanner/commit/da8c2f85b55346d99a9eacc4249e6d6cd1a14556)) + +## [4.6.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.5.2...v4.6.0) (2020-01-16) + + +### Features + +* add fieldNames option in instance#getMetadata() ([#760](https://www.github.com/googleapis/nodejs-spanner/issues/760)) ([fa3154e](https://www.github.com/googleapis/nodejs-spanner/commit/fa3154ebe6754ecce1dd7b32442bda0eb27842f6)) + +### [4.5.2](https://www.github.com/googleapis/nodejs-spanner/compare/v4.5.1...v4.5.2) (2020-01-15) + + +### Bug Fixes + +* max backoff should be 32 seconds ([#792](https://www.github.com/googleapis/nodejs-spanner/issues/792)) ([c697240](https://www.github.com/googleapis/nodejs-spanner/commit/c697240c0f1c5d55bee63732b7346e7c95f25dcc)) +* retry executeStreamingSql when error code is retryable ([#795](https://www.github.com/googleapis/nodejs-spanner/issues/795)) ([1491858](https://www.github.com/googleapis/nodejs-spanner/commit/149185809fe32e05504d398849f7eadfe864fb6b)), closes [#620](https://www.github.com/googleapis/nodejs-spanner/issues/620) + +### [4.5.1](https://www.github.com/googleapis/nodejs-spanner/compare/v4.5.0...v4.5.1) (2020-01-08) + + +### Bug Fixes + +* session pool should only create session if pending<=waiters ([#791](https://www.github.com/googleapis/nodejs-spanner/issues/791)) ([75345b1](https://www.github.com/googleapis/nodejs-spanner/commit/75345b18d37937b60a89c6b039c6b3a39b0ea6b7)), closes [#790](https://www.github.com/googleapis/nodejs-spanner/issues/790) + +## [4.5.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.4.1...v4.5.0) (2020-01-06) + + +### Features + +* include potential leaked session stacktraces in error ([#759](https://www.github.com/googleapis/nodejs-spanner/issues/759)) ([1c0cf27](https://www.github.com/googleapis/nodejs-spanner/commit/1c0cf27b6c502fe7cc03f9b4c9191d746761b8b6)) + + +### Bug Fixes + +* clear stack of session while preparing new r/w tx ([#768](https://www.github.com/googleapis/nodejs-spanner/issues/768)) ([c852709](https://www.github.com/googleapis/nodejs-spanner/commit/c852709cf509d174ff140ad946fbbc20e5594aba)) +* delete env var after test if it was not set ([#774](https://www.github.com/googleapis/nodejs-spanner/issues/774)) ([7a1f40d](https://www.github.com/googleapis/nodejs-spanner/commit/7a1f40d5041e217363722d5a8b45c181f7a1510a)) +* end readWrite transaction in sample ([#766](https://www.github.com/googleapis/nodejs-spanner/issues/766)) ([f419e27](https://www.github.com/googleapis/nodejs-spanner/commit/f419e27e24eb8df78633d8245c364a709e58d007)) +* return different databases for different pool options ([#754](https://www.github.com/googleapis/nodejs-spanner/issues/754)) ([106c7a5](https://www.github.com/googleapis/nodejs-spanner/commit/106c7a513052631cf08f1db23ed099d2e3178635)) +* session pool should use push/pop and return sessions lifo ([#776](https://www.github.com/googleapis/nodejs-spanner/issues/776)) ([384bde1](https://www.github.com/googleapis/nodejs-spanner/commit/384bde1848f2fc72f52601f5b57af17dadebca69)) +* transaction runner should not timeout before first attempt ([#789](https://www.github.com/googleapis/nodejs-spanner/issues/789)) ([c75076e](https://www.github.com/googleapis/nodejs-spanner/commit/c75076e01b8480386289c237bc01d0ea2b42c85c)), closes [#786](https://www.github.com/googleapis/nodejs-spanner/issues/786) +* year zero was not accepted for SpannerDate ([#783](https://www.github.com/googleapis/nodejs-spanner/issues/783)) ([0ceb862](https://www.github.com/googleapis/nodejs-spanner/commit/0ceb862beac57f3732e0097d808b62dbdfa5d3a9)) + +### [4.4.1](https://www.github.com/googleapis/nodejs-spanner/compare/v4.4.0...v4.4.1) (2019-12-16) + + +### Bug Fixes + +* get stacktrace before any async method call ([#756](https://www.github.com/googleapis/nodejs-spanner/issues/756)) ([3091a78](https://www.github.com/googleapis/nodejs-spanner/commit/3091a7849985330828703018b43f6cfabc0e381a)) + +## [4.4.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.3.0...v4.4.0) (2019-12-10) + + +### Features + +* add plural and singular resource descriptor ([#737](https://www.github.com/googleapis/nodejs-spanner/issues/737)) ([11658bf](https://www.github.com/googleapis/nodejs-spanner/commit/11658bfae8467e6788bb492895e7afb9202c59f4)) +* add replica support ([#726](https://www.github.com/googleapis/nodejs-spanner/issues/726)) ([dea3e59](https://www.github.com/googleapis/nodejs-spanner/commit/dea3e599759f374773ed5e4180187e79f518a7b6)) + + +### Bug Fixes + +* changes to default rpc timeouts ([da066fc](https://www.github.com/googleapis/nodejs-spanner/commit/da066fc916df4468c5f7d0538aadc5677c5bdb33)) +* **deps:** pin TypeScript below 3.7.0 ([7b1e07b](https://www.github.com/googleapis/nodejs-spanner/commit/7b1e07b33f31f93adf125a19db03fa6d5baf0b6b)) +* **deps:** update dependency yargs to v15 ([#736](https://www.github.com/googleapis/nodejs-spanner/issues/736)) ([e289890](https://www.github.com/googleapis/nodejs-spanner/commit/e2898907511a3426c6c42204c80765716a3317a6)) +* **docs:** snippets are now replaced in jsdoc comments ([#731](https://www.github.com/googleapis/nodejs-spanner/issues/731)) ([843ce6f](https://www.github.com/googleapis/nodejs-spanner/commit/843ce6f1cf14f14ab05c9983f6f5b7a8428fa6c7)) +* createInstance should return a value ([#747](https://www.github.com/googleapis/nodejs-spanner/issues/747)) ([16c013f](https://www.github.com/googleapis/nodejs-spanner/commit/16c013f04a02cbc07222f1d571ff0b016646c672)) +* include long import in proto typescript declaration file ([#732](https://www.github.com/googleapis/nodejs-spanner/issues/732)) ([6fe0757](https://www.github.com/googleapis/nodejs-spanner/commit/6fe0757d659e7c0835fc8c40b4617c688ce69551)) +* restore SessionLeakError name after super call ([#745](https://www.github.com/googleapis/nodejs-spanner/issues/745)) ([d04609b](https://www.github.com/googleapis/nodejs-spanner/commit/d04609b40023b411c08052f503baa54610062994)) + +## [4.3.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.2.0...v4.3.0) (2019-11-05) + + +### Features + +* **database:** batch create sessions ([#692](https://www.github.com/googleapis/nodejs-spanner/issues/692)) ([21f83b1](https://www.github.com/googleapis/nodejs-spanner/commit/21f83b1b13e12fb413138267dd4dc1bdaa24ccb9)) + + +### Bug Fixes + +* **deps:** bump google-gax to 1.7.5 ([#712](https://www.github.com/googleapis/nodejs-spanner/issues/712)) ([03384d4](https://www.github.com/googleapis/nodejs-spanner/commit/03384d4b93a66c758f1db75fa5efa1572f5c1eaf)) +* don't wrap SpannerDate so timezone does not affect results ([#711](https://www.github.com/googleapis/nodejs-spanner/issues/711)) ([86c0ae5](https://www.github.com/googleapis/nodejs-spanner/commit/86c0ae5fbdddccd915689bbfff3af8834ec64d12)) + +## [4.2.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.1.0...v4.2.0) (2019-10-02) + + +### Bug Fixes + +* adjust timeout values ([#700](https://www.github.com/googleapis/nodejs-spanner/issues/700)) ([4571f15](https://www.github.com/googleapis/nodejs-spanner/commit/4571f15)) +* use compatible version of google-gax ([d312a8f](https://www.github.com/googleapis/nodejs-spanner/commit/d312a8f)) + + +### Features + +* .d.ts for protos ([4d3d649](https://www.github.com/googleapis/nodejs-spanner/commit/4d3d649)) + +## [4.1.0](https://www.github.com/googleapis/nodejs-spanner/compare/v4.0.2...v4.1.0) (2019-09-16) + + +### Bug Fixes + +* **deps:** update dependency yargs to v14 ([#680](https://www.github.com/googleapis/nodejs-spanner/issues/680)) ([add2f05](https://www.github.com/googleapis/nodejs-spanner/commit/add2f05)) +* **types:** import request types from teeny-request ([#682](https://www.github.com/googleapis/nodejs-spanner/issues/682)) ([a1ecd80](https://www.github.com/googleapis/nodejs-spanner/commit/a1ecd80)) +* set proper version # for x-goog-api-client ([#681](https://www.github.com/googleapis/nodejs-spanner/issues/681)) ([f300fad](https://www.github.com/googleapis/nodejs-spanner/commit/f300fad)) + + +### Features + +* load protos from JSON, grpc-fallback support ([0b3fb90](https://www.github.com/googleapis/nodejs-spanner/commit/0b3fb90)) +* support batch create sessions ([#685](https://www.github.com/googleapis/nodejs-spanner/issues/685)) ([7bc58cf](https://www.github.com/googleapis/nodejs-spanner/commit/7bc58cf)) +* use JSON proto for transaction-runner ([#690](https://www.github.com/googleapis/nodejs-spanner/issues/690)) ([279fc97](https://www.github.com/googleapis/nodejs-spanner/commit/279fc97)) + +### [4.0.2](https://www.github.com/googleapis/nodejs-spanner/compare/v4.0.1...v4.0.2) (2019-08-09) + + +### Bug Fixes + +* allow calls with no request, add JSON proto ([4a478a7](https://www.github.com/googleapis/nodejs-spanner/commit/4a478a7)) +* **deps:** use the latest extend ([#678](https://www.github.com/googleapis/nodejs-spanner/issues/678)) ([a094fdd](https://www.github.com/googleapis/nodejs-spanner/commit/a094fdd)) + +### [4.0.1](https://www.github.com/googleapis/nodejs-spanner/compare/v4.0.0...v4.0.1) (2019-07-29) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/paginator to v2 ([#668](https://www.github.com/googleapis/nodejs-spanner/issues/668)) ([86d3638](https://www.github.com/googleapis/nodejs-spanner/commit/86d3638)) +* **deps:** update dependency google-auth-library to v5 ([#669](https://www.github.com/googleapis/nodejs-spanner/issues/669)) ([c6d165e](https://www.github.com/googleapis/nodejs-spanner/commit/c6d165e)) +* **docs:** move docs under overloads to be picked up by JSDoc ([#666](https://www.github.com/googleapis/nodejs-spanner/issues/666)) ([be10eb1](https://www.github.com/googleapis/nodejs-spanner/commit/be10eb1)) + +## [4.0.0](https://www.github.com/googleapis/nodejs-spanner/compare/v3.1.0...v4.0.0) (2019-07-19) + + +### ⚠ BREAKING CHANGES + +* **deps:** this will ship async/await in the generated code +* upgrade engines field to >=8.10.0 (#587) + +### Bug Fixes + +* **deps:** update dependency @google-cloud/common-grpc to v1 ([#607](https://www.github.com/googleapis/nodejs-spanner/issues/607)) ([084dc8c](https://www.github.com/googleapis/nodejs-spanner/commit/084dc8c)) +* **deps:** update dependency @google-cloud/paginator to ^0.2.0 ([#560](https://www.github.com/googleapis/nodejs-spanner/issues/560)) ([8fe33a1](https://www.github.com/googleapis/nodejs-spanner/commit/8fe33a1)) +* **deps:** update dependency @google-cloud/paginator to v1 ([#593](https://www.github.com/googleapis/nodejs-spanner/issues/593)) ([bfb2255](https://www.github.com/googleapis/nodejs-spanner/commit/bfb2255)) +* **deps:** update dependency @google-cloud/precise-date to v1 ([#600](https://www.github.com/googleapis/nodejs-spanner/issues/600)) ([f52494f](https://www.github.com/googleapis/nodejs-spanner/commit/f52494f)) +* **deps:** update dependency @google-cloud/projectify to v1 ([#591](https://www.github.com/googleapis/nodejs-spanner/issues/591)) ([22713c1](https://www.github.com/googleapis/nodejs-spanner/commit/22713c1)) +* **deps:** update dependency @google-cloud/promisify to v1 ([#592](https://www.github.com/googleapis/nodejs-spanner/issues/592)) ([cb76922](https://www.github.com/googleapis/nodejs-spanner/commit/cb76922)) +* **deps:** update dependency arrify to v2 ([#577](https://www.github.com/googleapis/nodejs-spanner/issues/577)) ([6e0ddc8](https://www.github.com/googleapis/nodejs-spanner/commit/6e0ddc8)) +* **deps:** update dependency google-auth-library to v4 ([#599](https://www.github.com/googleapis/nodejs-spanner/issues/599)) ([21b9995](https://www.github.com/googleapis/nodejs-spanner/commit/21b9995)) +* **deps:** update dependency google-gax to ^0.26.0 ([#586](https://www.github.com/googleapis/nodejs-spanner/issues/586)) ([0f88be2](https://www.github.com/googleapis/nodejs-spanner/commit/0f88be2)) +* **deps:** update dependency merge-stream to v2 ([#624](https://www.github.com/googleapis/nodejs-spanner/issues/624)) ([3aa676d](https://www.github.com/googleapis/nodejs-spanner/commit/3aa676d)) +* **deps:** update dependency p-queue to v4 ([#558](https://www.github.com/googleapis/nodejs-spanner/issues/558)) ([7547e21](https://www.github.com/googleapis/nodejs-spanner/commit/7547e21)) +* **deps:** update dependency p-queue to v5 ([#578](https://www.github.com/googleapis/nodejs-spanner/issues/578)) ([7827fb4](https://www.github.com/googleapis/nodejs-spanner/commit/7827fb4)) +* **deps:** update dependency p-queue to v6.0.2 ([#643](https://www.github.com/googleapis/nodejs-spanner/issues/643)) ([ace1359](https://www.github.com/googleapis/nodejs-spanner/commit/ace1359)) +* **deps:** upgrade to google-gax 1.x ([#651](https://www.github.com/googleapis/nodejs-spanner/issues/651)) ([a32e838](https://www.github.com/googleapis/nodejs-spanner/commit/a32e838)) +* **docs:** add google.type namespace ([#605](https://www.github.com/googleapis/nodejs-spanner/issues/605)) ([5cc6dc1](https://www.github.com/googleapis/nodejs-spanner/commit/5cc6dc1)) +* **docs:** link to reference docs section on googleapis.dev ([#654](https://www.github.com/googleapis/nodejs-spanner/issues/654)) ([2379dc2](https://www.github.com/googleapis/nodejs-spanner/commit/2379dc2)) +* **docs:** move to new client docs URL ([#647](https://www.github.com/googleapis/nodejs-spanner/issues/647)) ([7dec1bd](https://www.github.com/googleapis/nodejs-spanner/commit/7dec1bd)) +* **transaction:** set/update seqno for all sql requests ([#661](https://www.github.com/googleapis/nodejs-spanner/issues/661)) ([102cae1](https://www.github.com/googleapis/nodejs-spanner/commit/102cae1)) +* DEADLINE_EXCEEDED is no longer retried ([#598](https://www.github.com/googleapis/nodejs-spanner/issues/598)) ([1cac4fc](https://www.github.com/googleapis/nodejs-spanner/commit/1cac4fc)) +* include 'x-goog-request-params' header in requests ([#573](https://www.github.com/googleapis/nodejs-spanner/issues/573)) ([e0cb9dc](https://www.github.com/googleapis/nodejs-spanner/commit/e0cb9dc)) +* treat deadline errors as idempotent ([#602](https://www.github.com/googleapis/nodejs-spanner/issues/602)) ([b3d494a](https://www.github.com/googleapis/nodejs-spanner/commit/b3d494a)) +* update retry config ([#650](https://www.github.com/googleapis/nodejs-spanner/issues/650)) ([f1e8104](https://www.github.com/googleapis/nodejs-spanner/commit/f1e8104)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#587](https://www.github.com/googleapis/nodejs-spanner/issues/587)) ([970d335](https://www.github.com/googleapis/nodejs-spanner/commit/970d335)) + + +### Features + +* add .repo-metadata.json and move to new README template ([#636](https://www.github.com/googleapis/nodejs-spanner/issues/636)) ([11007cf](https://www.github.com/googleapis/nodejs-spanner/commit/11007cf)) +* support apiEndpoint override ([#634](https://www.github.com/googleapis/nodejs-spanner/issues/634)) ([6a5eb36](https://www.github.com/googleapis/nodejs-spanner/commit/6a5eb36)) +* support apiEndpoint override in client constructor ([#639](https://www.github.com/googleapis/nodejs-spanner/issues/639)) ([f6ebb27](https://www.github.com/googleapis/nodejs-spanner/commit/f6ebb27)) + + +### Miscellaneous Chores + +* **deps:** update dependency gts to v1 ([#584](https://www.github.com/googleapis/nodejs-spanner/issues/584)) ([135ac6d](https://www.github.com/googleapis/nodejs-spanner/commit/135ac6d)) + +## v3.1.0 + +03-06-2019 20:13 PST + +### New Features +- feat(transaction): batch dml ([#550](https://github.com/googleapis/nodejs-spanner/pull/550)) + +### Dependencies +- chore(deps): update dependency @types/sinon to v7.0.9 ([#553](https://github.com/googleapis/nodejs-spanner/pull/553)) +- chore(deps): fix broken dep types ([#549](https://github.com/googleapis/nodejs-spanner/pull/549)) + +### Documentation +- docs: Update grammar ([#544](https://github.com/googleapis/nodejs-spanner/pull/544)) + +### Internal / Testing Changes +- chore: update proto docs and code style +- chore(deps): use bundled p-queue types ([#547](https://github.com/googleapis/nodejs-spanner/pull/547)) +- build: update release configuration ([#545](https://github.com/googleapis/nodejs-spanner/pull/545)) +- build: use node10 to run samples-test, system-test etc ([#551](https://github.com/googleapis/nodejs-spanner/pull/551)) + +## v3.0.0 + +02-25-2019 12:38 PST + +### Breaking Changes +- breaking: refactor(transaction): split logic into new classes ([#506](https://github.com/googleapis/nodejs-spanner/pull/506)) +- breaking: feat(timestamp): create new date/timestamp classes ([#517](https://github.com/googleapis/nodejs-spanner/pull/517)) +- fix: run generator to bring in streaming retry configs ([#448](https://github.com/googleapis/nodejs-spanner/pull/448)) + +#### Read-only Transactions (Snapshots) are no longer runnable via `Database#runTransaction` ([#506](https://github.com/googleapis/nodejs-spanner/pull/506)) + +`Database#runTransaction` is useful if want to replay a Transaction in its entirety in case you run into an `ABORTED` error. This should never happen with Snapshots, so it felt like it was time to create a new method just for them. *This change also means that `runTransaction` will only ever return read-write transactions.* + +Before + +```js +const bounds = { + readOnly: true, + strong: true, +}; + +database.runTransaction(bounds, (err, transaction) => { + // ... +}); +``` + +After + +```js +const bounds = { + strong: true, +}; + +database.getSnapshot(bounds, (err, snapshot) => { + // ... +}); +``` + +#### Timestamp bounds now offer nanosecond precision ([#506](https://github.com/googleapis/nodejs-spanner/pull/506)) + +This change allows you to specify a Snapshot read timestamp with more precision. Previously one could only specify in seconds, but now we support both milliseconds and nanoseconds. + +Before + +```js +const bounds = { + exactStaleness: 5 +}; + +const bounds = { + readTimestamp: Date.now() +}; +``` + +After + +```js +const bounds = { + // millisecond precision for staleness + exactStaleness: 5000, + + // or if you need nano/micro precision for staleness + exactStaleness: {seconds: 5, nanos: 321} // => 5000000321 nanoseconds +}; + +const bounds = { + readTimestamp: Spanner.timestamp('2019-01-12T00:30:35.381101032Z') +}; +``` + +#### Transaction#end changes. ([#506](https://github.com/googleapis/nodejs-spanner/pull/506)) + +Transactions saw a sizeable refactor with this version, previously `end()` performed a number of asynchronous tasks when called, however this is no longer true. Because of this, there isn't much of a need to track when end is finished, so we've dropped the callback parameter. + +Additionally, `end()` will now be called automatically for failed calls to `Transaction#commit()` and `Transaction#rollback()`. If your code calls end after a failed commit/rollback, it will simply no-op. + +Before + +```js +transaction.end(callback); +``` + +After + +```js +transaction.end(); +callback(); +``` + +#### Session#beginTransaction was removed ([#506](https://github.com/googleapis/nodejs-spanner/pull/506)) + +Spanner supports 4 different types of Transactions: + +* ReadWrite +* ReadOnly +* PartitionedDml +* Batch + +Using one method for all types became cumbersome when trying to manage the various options available to each, now each type has its own method. + +Before + +```js +const transaction = await session.beginTransaction({readWrite: true}); +const snapshot = await session.beginTransaction({readOnly: true}); +``` + +After + +```js +const transaction = session.transaction(); +await transaction.begin(); + +const snapshot = session.snapshot({strong: true}); +await snapshot.begin(); +``` + +#### Timestamps now represented by [`@google-cloud/precise-time`](https://github.com/googleapis/nodejs-precise-date) ([#517](https://github.com/googleapis/nodejs-spanner/pull/517)) + +While Spanner supports timestamps with nanosecond precision, JavaScript Dates do not. So we created the `PreciseDate` object which extends the native Date and adds both microsecond and nanosecond support. + +Before + +```js +const timestamp = Spanner.timestamp('2019-01-12T00:30:35.381101032Z'); +// => {value: '2019-01-12T00:30:35.381Z'} +``` + +After + +```js +// PreciseDate object +const timestamp = Spanner.timestamp('2019-01-12T00:30:35.381101032Z'); +timestamp.toJSON(); // => '2019-01-12T00:30:35.381101032Z' +timestamp.toFullTimeString(); // => '1547253035381101032' (nanoseconds) +``` + +#### SpannerDate now extends the native Date object. ([#517](https://github.com/googleapis/nodejs-spanner/pull/517)) + +Since Timestamps saw an update, it made sense to give Spanner Date objects a similar update. The `Spanner.date()` method now returns a native Date object. + +Before + +```js +const date = Spanner.date('3-22-2018'); +// => {value: '2018-3-22'} +``` + +After + +```js +// Date object +const date = Spanner.date('3-22-2018'); +date.toJSON(); // => '2018-3-22' +``` + +### New Features +- refactor(types): enable noImplicitAny in session-pool.ts ([#508](https://github.com/googleapis/nodejs-spanner/pull/508)) +- refactor(table): improve typescript defs ([#495](https://github.com/googleapis/nodejs-spanner/pull/495)) +- refactor(ts): partial-result-stream types/refactor ([#488](https://github.com/googleapis/nodejs-spanner/pull/488)) +- refactor(codec): improve typescript defs ([#490](https://github.com/googleapis/nodejs-spanner/pull/490)) +- chore(SessionPool): improve typescript types ([#479](https://github.com/googleapis/nodejs-spanner/pull/479)) +- chore(typescript): add types for spanner gapic ([#487](https://github.com/googleapis/nodejs-spanner/pull/487)) +- refactor(ts): enable noImplicitAny on src/session.ts ([#457](https://github.com/googleapis/nodejs-spanner/pull/457)) + +### Bug Fixes +- fix: throw on invalid credentials ([#522](https://github.com/googleapis/nodejs-spanner/pull/522)) +- fix(transaction): re-use session in transaction runners ([#540](https://github.com/googleapis/nodejs-spanner/pull/540)) + +### Dependencies +- chore(deps): update dependency mocha to v6 ([#532](https://github.com/googleapis/nodejs-spanner/pull/532)) +- fix(deps): update dependency @google-cloud/promisify to ^0.4.0 ([#524](https://github.com/googleapis/nodejs-spanner/pull/524)) +- chore(deps): update dependency @types/p-retry to v3 ([#521](https://github.com/googleapis/nodejs-spanner/pull/521)) +- fix(deps): update dependency yargs to v13 ([#520](https://github.com/googleapis/nodejs-spanner/pull/520)) +- fix(deps): update dependency @google-cloud/common-grpc to ^0.10.0 ([#504](https://github.com/googleapis/nodejs-spanner/pull/504)) +- fix(deps): update dependency google-gax to ^0.25.0 ([#505](https://github.com/googleapis/nodejs-spanner/pull/505)) +- chore(deps): update dependency eslint-config-prettier to v4 ([#502](https://github.com/googleapis/nodejs-spanner/pull/502)) +- fix(deps): update dependency google-gax to ^0.24.0 ([#501](https://github.com/googleapis/nodejs-spanner/pull/501)) +- fix(deps): update dependency google-auth-library to v3 ([#498](https://github.com/googleapis/nodejs-spanner/pull/498)) +- fix(deps): update dependency google-gax to ^0.23.0 ([#496](https://github.com/googleapis/nodejs-spanner/pull/496)) +- chore(deps): update dependency concat-stream to v2 ([#489](https://github.com/googleapis/nodejs-spanner/pull/489)) +- refactor: removed async from dependency list ([#449](https://github.com/googleapis/nodejs-spanner/pull/449)) +- chore(deps): update dependency @types/sinon to v7 ([#480](https://github.com/googleapis/nodejs-spanner/pull/480)) +- fix(deps): update dependency p-retry to v3 ([#481](https://github.com/googleapis/nodejs-spanner/pull/481)) +- chore(deps): update dependency typescript to ~3.2.0 ([#459](https://github.com/googleapis/nodejs-spanner/pull/459)) + +### Documentation +- docs: fixed example for table.upsert() ([#533](https://github.com/googleapis/nodejs-spanner/pull/533)) +- docs: update links in contrib guide ([#525](https://github.com/googleapis/nodejs-spanner/pull/525)) +- docs: update contributing path in README ([#515](https://github.com/googleapis/nodejs-spanner/pull/515)) +- docs: add lint/fix example to contributing guide ([#512](https://github.com/googleapis/nodejs-spanner/pull/512)) +- docs: fix example comments ([#511](https://github.com/googleapis/nodejs-spanner/pull/511)) +- chore: update proto licenses +- build: check broken links in generated docs ([#491](https://github.com/googleapis/nodejs-spanner/pull/491)) +- fix(docs): remove unused long running operations and IAM types +- refactor: modernize sample tests ([#484](https://github.com/googleapis/nodejs-spanner/pull/484)) +- docs: fix links in docstrings ([#467](https://github.com/googleapis/nodejs-spanner/pull/467)) +- docs: fix typo ([#465](https://github.com/googleapis/nodejs-spanner/pull/465)) +- chore: update license file ([#464](https://github.com/googleapis/nodejs-spanner/pull/464)) +- docs: update readme badges ([#462](https://github.com/googleapis/nodejs-spanner/pull/462)) +- docs(samples): Add sample to delete using a mutation. ([#458](https://github.com/googleapis/nodejs-spanner/pull/458)) + +### Internal / Testing Changes +- chore: add spanner_grpc_config.json and enable grpc-gcp support for spanner ([#503](https://github.com/googleapis/nodejs-spanner/pull/503)) +- build: use linkinator for docs test ([#523](https://github.com/googleapis/nodejs-spanner/pull/523)) +- build: create docs test npm scripts ([#519](https://github.com/googleapis/nodejs-spanner/pull/519)) +- build: test using @grpc/grpc-js in CI ([#516](https://github.com/googleapis/nodejs-spanner/pull/516)) +- chore: move CONTRIBUTING.md to root ([#514](https://github.com/googleapis/nodejs-spanner/pull/514)) +- refactor: improve generated code style. ([#510](https://github.com/googleapis/nodejs-spanner/pull/510)) +- build: ignore googleapis.com in doc link check ([#500](https://github.com/googleapis/nodejs-spanner/pull/500)) +- fix: fix the sample tests ([#486](https://github.com/googleapis/nodejs-spanner/pull/486)) +- chore(build): inject yoshi automation key ([#478](https://github.com/googleapis/nodejs-spanner/pull/478)) +- chore: update nyc and eslint configs ([#477](https://github.com/googleapis/nodejs-spanner/pull/477)) +- chore: fix publish.sh permission +x ([#475](https://github.com/googleapis/nodejs-spanner/pull/475)) +- fix(build): fix Kokoro release script ([#474](https://github.com/googleapis/nodejs-spanner/pull/474)) +- build: add Kokoro configs for autorelease ([#473](https://github.com/googleapis/nodejs-spanner/pull/473)) +- chore: always nyc report before calling codecov ([#469](https://github.com/googleapis/nodejs-spanner/pull/469)) +- chore: nyc ignore build/test by default ([#468](https://github.com/googleapis/nodejs-spanner/pull/468)) +- fix(build): fix system key decryption ([#460](https://github.com/googleapis/nodejs-spanner/pull/460)) +- chore: temporarily disable gts ([#534](https://github.com/googleapis/nodejs-spanner/pull/534)) + +## v2.2.1 + +11-28-2018 10:43 PST + + +### Implementation Changes +- Update package.json to include the build directory ([#454](https://github.com/googleapis/nodejs-spanner/pull/454)) + +## v2.2.0 + +11-27-2018 09:13 PST + + +### Implementation Changes +- fix: transaction async error handling that not thrown the full error ([#447](https://github.com/googleapis/nodejs-spanner/pull/447)) +- fix(transaction): accept json options in run/runStream ([#446](https://github.com/googleapis/nodejs-spanner/pull/446)) +- refactor(transaction): error handling ([#360](https://github.com/googleapis/nodejs-spanner/pull/360)) +- refactor(ts): enable noImplicitThis in the tsconfig ([#411](https://github.com/googleapis/nodejs-spanner/pull/411)) +- refactor(ts): use import/export for local files ([#408](https://github.com/googleapis/nodejs-spanner/pull/408)) +- refactor(ts): add type packages for many things ([#406](https://github.com/googleapis/nodejs-spanner/pull/406)) +- refactor(ts): convert tests to typescript ([#404](https://github.com/googleapis/nodejs-spanner/pull/404)) +- refactor(typescript): rename src and system-test files to *.ts ([#402](https://github.com/googleapis/nodejs-spanner/pull/402)) +- refactor(typescript): perform initial TypeScript conversion ([#384](https://github.com/googleapis/nodejs-spanner/pull/384)) +- fix: Only run mutations inside of a transaction. ([#361](https://github.com/googleapis/nodejs-spanner/pull/361)) + +### New Features +- feat(session): add label support ([#373](https://github.com/googleapis/nodejs-spanner/pull/373)) + +### Dependencies +- chore(deps): update dependency @types/sinon to v5.0.7 ([#444](https://github.com/googleapis/nodejs-spanner/pull/444)) +- fix: Pin @types/sinon to last compatible version ([#443](https://github.com/googleapis/nodejs-spanner/pull/443)) +- chore(deps): update dependency @types/p-queue to v3 ([#440](https://github.com/googleapis/nodejs-spanner/pull/440)) +- fix(deps): update dependency google-gax to ^0.22.0 ([#435](https://github.com/googleapis/nodejs-spanner/pull/435)) +- chore(deps): update dependency gts to ^0.9.0 ([#434](https://github.com/googleapis/nodejs-spanner/pull/434)) +- chore(deps): update dependency @google-cloud/nodejs-repo-tools to v3 ([#429](https://github.com/googleapis/nodejs-spanner/pull/429)) +- chore(deps): update dependency @types/is to v0.0.21 ([#426](https://github.com/googleapis/nodejs-spanner/pull/426)) +- fix(deps): update dependency through2 to v3 ([#423](https://github.com/googleapis/nodejs-spanner/pull/423)) +- chore: remove unused google-proto-files dep ([#421](https://github.com/googleapis/nodejs-spanner/pull/421)) +- chore(deps): update dependency eslint-plugin-node to v8 ([#407](https://github.com/googleapis/nodejs-spanner/pull/407)) +- refactor: drop dependency on delay ([#383](https://github.com/googleapis/nodejs-spanner/pull/383)) +- fix(deps): update dependency google-proto-files to ^0.17.0 ([#369](https://github.com/googleapis/nodejs-spanner/pull/369)) +- chore(deps): update dependency sinon to v7 ([#371](https://github.com/googleapis/nodejs-spanner/pull/371)) + +### Documentation +- docs(samples): updated samples code to use async await ([#385](https://github.com/googleapis/nodejs-spanner/pull/385)) +- Add Cloud Spanner DML/PDML samples. ([#366](https://github.com/googleapis/nodejs-spanner/pull/366)) + +### Internal / Testing Changes +- chore: add synth.metadata +- test: fix broken tests ([#441](https://github.com/googleapis/nodejs-spanner/pull/441)) +- refactor(samples): convert ava tests to mocha ([#400](https://github.com/googleapis/nodejs-spanner/pull/400)) +- chore: update eslintignore config ([#433](https://github.com/googleapis/nodejs-spanner/pull/433)) +- chore(build): fix lint rules and build for generated code ([#430](https://github.com/googleapis/nodejs-spanner/pull/430)) +- chore: drop contributors from multiple places ([#427](https://github.com/googleapis/nodejs-spanner/pull/427)) +- chore: use latest npm on Windows ([#425](https://github.com/googleapis/nodejs-spanner/pull/425)) +- fix: update source location for synth ([#422](https://github.com/googleapis/nodejs-spanner/pull/422)) +- fix: re-enable linting and formatting ([#420](https://github.com/googleapis/nodejs-spanner/pull/420)) +- chore: improve typescript config and types ([#417](https://github.com/googleapis/nodejs-spanner/pull/417)) +- chore: update CircleCI config ([#416](https://github.com/googleapis/nodejs-spanner/pull/416)) +- chore: run gts fix ([#413](https://github.com/googleapis/nodejs-spanner/pull/413)) +- chore: remove old issue template ([#397](https://github.com/googleapis/nodejs-spanner/pull/397)) +- chore: update issue templates ([#401](https://github.com/googleapis/nodejs-spanner/pull/401)) +- build: run tests on node11 ([#395](https://github.com/googleapis/nodejs-spanner/pull/395)) +- chores(build): do not collect sponge.xml from windows builds ([#389](https://github.com/googleapis/nodejs-spanner/pull/389)) +- chores(build): run codecov on continuous builds ([#386](https://github.com/googleapis/nodejs-spanner/pull/386)) +- chore: update new issue template ([#382](https://github.com/googleapis/nodejs-spanner/pull/382)) +- fix(tests): use unique label for tests ([#367](https://github.com/googleapis/nodejs-spanner/pull/367)) +- build: fix codecov uploading on Kokoro ([#372](https://github.com/googleapis/nodejs-spanner/pull/372)) +- build(kokoro): test with spanner key ([#364](https://github.com/googleapis/nodejs-spanner/pull/364)) + +## v2.1.0 + +### Implementation Changes +- chore: use arrow functions ([#359](https://github.com/googleapis/nodejs-spanner/pull/359)) +- fix: change exists to return false on error code 5 ([#353](https://github.com/googleapis/nodejs-spanner/pull/353)) +- Switch to let/const ([#328](https://github.com/googleapis/nodejs-spanner/pull/328)) +- Minor: wrap the inner error on retried transactions and return when deadline exceeded ([#309](https://github.com/googleapis/nodejs-spanner/pull/309)) +- chore: convert index to es6 class ([#306](https://github.com/googleapis/nodejs-spanner/pull/306)) +- Fix p-retry is accepting function not object/promise ([#312](https://github.com/googleapis/nodejs-spanner/pull/312)) + +### New Features +- feat: dml/pdml support ([#348](https://github.com/googleapis/nodejs-spanner/pull/348)) +- feat(table): drop method and additional error handling to delete ([#358](https://github.com/googleapis/nodejs-spanner/pull/358)) +- feat(PartialResultStream): emit raw responses as event ([#357](https://github.com/googleapis/nodejs-spanner/pull/357)) +- feat(transaction): add backup backoff delay ([#350](https://github.com/googleapis/nodejs-spanner/pull/350)) + +### Dependencies +- chore(deps): update dependency eslint-plugin-prettier to v3 ([#351](https://github.com/googleapis/nodejs-spanner/pull/351)) +- fix(deps): update dependency @google-cloud/common-grpc to ^0.9.0 ([#339](https://github.com/googleapis/nodejs-spanner/pull/339)) +- fix(deps): update dependency google-gax to ^0.20.0 ([#327](https://github.com/googleapis/nodejs-spanner/pull/327)) +- fix(deps): update dependency delay to v4 ([#322](https://github.com/googleapis/nodejs-spanner/pull/322)) +- fix: upgrade to the latest common-grpc ([#320](https://github.com/googleapis/nodejs-spanner/pull/320)) +- fix(deps): update dependency google-auth-library to v2 ([#319](https://github.com/googleapis/nodejs-spanner/pull/319)) +- fix(deps): update dependency p-queue to v3 ([#317](https://github.com/googleapis/nodejs-spanner/pull/317)) +- chore(deps): update dependency nyc to v13 ([#314](https://github.com/googleapis/nodejs-spanner/pull/314)) + +### Documentation +- docs: add typedefs for commit timestamp ([#356](https://github.com/googleapis/nodejs-spanner/pull/356)) +- docs: various jsdoc fixes ([#352](https://github.com/googleapis/nodejs-spanner/pull/352)) + +### Internal / Testing Changes +- chore: update auto-generated config ([#362](https://github.com/googleapis/nodejs-spanner/pull/362)) +- chore: change queries to return expected values ([#355](https://github.com/googleapis/nodejs-spanner/pull/355)) +- Update CI config ([#354](https://github.com/googleapis/nodejs-spanner/pull/354)) +- chore: make sure workloadb benchmark runs properly ([#349](https://github.com/googleapis/nodejs-spanner/pull/349)) +- test: Add delay for system test. ([#16](https://github.com/googleapis/nodejs-spanner/pull/16)) +- Update QuickStart to use "new" syntax for creating Spanner client. ([#344](https://github.com/googleapis/nodejs-spanner/pull/344)) +- test: remove appveyor config ([#342](https://github.com/googleapis/nodejs-spanner/pull/342)) +- Update CI config ([#341](https://github.com/googleapis/nodejs-spanner/pull/341)) +- Fix the failing lint rules ([#338](https://github.com/googleapis/nodejs-spanner/pull/338)) +- Enable prefer-const in the eslint config ([#337](https://github.com/googleapis/nodejs-spanner/pull/337)) +- soften assertion in system tests ([#335](https://github.com/googleapis/nodejs-spanner/pull/335)) +- Update protos and comments ([#334](https://github.com/googleapis/nodejs-spanner/pull/334)) +- fix string comparison in system test ([#333](https://github.com/googleapis/nodejs-spanner/pull/333)) +- Enable no-var in eslint ([#331](https://github.com/googleapis/nodejs-spanner/pull/331)) +- Add synth templates ([#330](https://github.com/googleapis/nodejs-spanner/pull/330)) +- test: throw on deprecation ([#279](https://github.com/googleapis/nodejs-spanner/pull/279)) +- Retry npm install in CI ([#323](https://github.com/googleapis/nodejs-spanner/pull/323)) +- Re-generate library using /synth.py ([#316](https://github.com/googleapis/nodejs-spanner/pull/316)) +- Fix color highlighting in CHANGELOG.md ([#313](https://github.com/googleapis/nodejs-spanner/pull/313)) +- Update sample dependency @google-cloud/spanner to v2 ([#310](https://github.com/googleapis/nodejs-spanner/pull/310)) +- Re-generate library using /synth.py ([#308](https://github.com/googleapis/nodejs-spanner/pull/308)) + +## v2.0.0 + +### Breaking Changes +- Drop support for Node.js v4.x.x and v9.x.x (#226) + +- Use es style imports (#302) + The import syntax for this library has changed to be [es module](https://nodejs.org/api/esm.html) compliant. + + #### Old code + ```js + const spanner = require('@google-cloud/spanner')(); + // or + const Spanner = require('@google-cloud/spanner'); + const spanner = new Spanner(); + ``` + + #### New code + ```js + const {Spanner} = require('@google-cloud/spanner'); + const spanner = new Spanner(); + ``` + +### New Features +- add runTransactionAsync method (#294) + ```js + const {Spanner} = require('@google-cloud/spanner'); + const spanner = new Spanner(); + + const instance = spanner.instance('my-instance'); + const database = instance.database('my-database'); + + await database.runTransactionAsync(async (transaction) => { + const [rows] = await transaction.run('SELECT * FROM MyTable'); + const data = rows.map(row => row.thing); + await transaction.commit(); + return data; + }).then(data => { + // ... + }); + ``` +- feature(database): make session pool hot swappable (#243) + +### Implementation Changes +- feat: use es style imports (#302) +- fix: perform type check on grpc value (#300) +- chore: use es classes in a few places (#297) +- chore: do not use npm ci (#292) +- chore: split the common module (#289) +- test: fix strict equal assertions (#287) +- chore: ignore package-lock.json (#286) +- chore: use let and const (#283) +- chore: update renovate config (#281) +- Re-generate library using /synth.py (#282) +- chore: use assert.deepStrictEqual instead of assert.deepEqual (#274) +- chore: require node 8 for samples (#273) +- test: use strictEqual in tests (#267) +- use node_library not not internal generate method (#247) +- Configure Renovate (#239) +- fix: drop support for node.js 4.x and 9.x (#226) + +### Dependencies +- fix(deps): update dependency google-gax to ^0.19.0 (#298) +- chore(deps): update dependency eslint-config-prettier to v3 (#295) +- fix(deps): update dependency google-gax to ^0.18.0 (#278) +- chore(deps): update dependency eslint-plugin-node to v7 (#266) +- refactor: update auth library, common-grpc (#256) +- fix(deps): update dependency yargs to v12 (#254) +- chore(deps): update dependency yargs to v12 (#252) +- chore(deps): update dependency sinon to v6.0.1 (#250) +- chore(package): update eslint to version 5.0.0 (#240) +- chore: update sample lockfiles (#246) +- Update to support google-gax v0.17 (#244) +- fix(package): update @google-cloud/common-grpc to version 0.7.1 (#235) +- refactor: drop dependency on safe-buffer (#232) +- refactor: remove dependency generic-pool (#231) +- refactor: drop dependency on lodash.flatten (#233) +- refactor: remove array-uniq as dependency (#227) +- refactor: remove string-obj-format (#229) +- refactor: remove methmeth as a dependency (#228) +- chore: upgrade several dependencies (#221) + +### Internal / Testing Changes +- chore: move mocha options to mocha.opts (#272) +- refactor: drop repo-tool as an exec wrapper (#248) +- fix: update linking for samples (#242) +- Adding Spanner STRUCT param samples (#219) diff --git a/handwritten/spanner/CODE_OF_CONDUCT.md b/handwritten/spanner/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..2add2547a81 --- /dev/null +++ b/handwritten/spanner/CODE_OF_CONDUCT.md @@ -0,0 +1,94 @@ + +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/handwritten/spanner/CONTRIBUTING.md b/handwritten/spanner/CONTRIBUTING.md new file mode 100644 index 00000000000..7b36f0328a8 --- /dev/null +++ b/handwritten/spanner/CONTRIBUTING.md @@ -0,0 +1,76 @@ +# How to become a contributor and submit your own code + +**Table of contents** + +* [Contributor License Agreements](#contributor-license-agreements) +* [Contributing a patch](#contributing-a-patch) +* [Running the tests](#running-the-tests) +* [Releasing the library](#releasing-the-library) + +## Contributor License Agreements + +We'd love to accept your sample apps and patches! Before we can take them, we +have to jump a couple of legal hurdles. + +Please fill out either the individual or corporate Contributor License Agreement +(CLA). + + * If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). + * If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. Once we receive it, we'll be able to +accept your pull requests. + +## Contributing A Patch + +1. Submit an issue describing your proposed change to the repo in question. +1. The repo owner will respond to your issue promptly. +1. If your proposed change is accepted, and you haven't already done so, sign a + Contributor License Agreement (see details above). +1. Fork the desired repo, develop and test your code changes. +1. Ensure that your code adheres to the existing style in the code to which + you are contributing. +1. Ensure that your code has an appropriate set of tests which all pass. +1. Title your pull request following [Conventional Commits](https://www.conventionalcommits.org/) styling. +1. Submit a pull request. + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Enable billing for your project][billing]. +1. [Enable the Cloud Spanner API][enable_api]. +1. [Set up authentication with a service account][auth] so you can access the + API from your local workstation. + + +## Running the tests + +1. [Prepare your environment for Node.js setup][setup]. + +1. Install dependencies: + + npm install + +1. Run the tests: + + # Run unit tests. + npm test + + # Run sample integration tests. + npm run samples-test + + # Run all system tests. + npm run system-test + +1. Lint (and maybe fix) any changes: + + npm run fix + +[setup]: https://cloud.google.com/nodejs/docs/setup +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=spanner.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/getting-started \ No newline at end of file diff --git a/handwritten/spanner/LICENSE b/handwritten/spanner/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/handwritten/spanner/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/handwritten/spanner/OBSERVABILITY.md b/handwritten/spanner/OBSERVABILITY.md new file mode 100644 index 00000000000..ce82cab99bb --- /dev/null +++ b/handwritten/spanner/OBSERVABILITY.md @@ -0,0 +1,132 @@ +## Observability with OpenTelemetry + +This Cloud Spanner client supports [OpenTelemetry Traces](https://opentelemetry.io/), which gives insight into the client internals and aids in debugging/troubleshooting production issues. + +By default, the functionality is disabled. You shall need to add OpenTelemetry dependencies, and must configure and +enable OpenTelemetry with appropriate exporters at the startup of your application: + +**Table of contents:** + +* [Observability](#observability) + * [Tracing](#tracing) + * [OpenTelemetry Dependencies](#opentelemetry-dependencies) + * [OpenTelemetry Configuration](#opentelemetry-configuration) + * [SQL Statement span annotation](#sql-statement-span-annotation) + * [OpenTelemetry gRCP instrumentation](#opentelemetry-grpc-instrumentation) + * [Tracing Sample](#tracing-sample) + +### Tracing + +#### OpenTelemetry Dependencies + +Add the following dependencies in your `package.json` or install them directly. +```javascript +// Required packages for OpenTelemetry SDKs +"@opentelemetry/sdk-trace-base": "^1.26.0", +"@opentelemetry/sdk-trace-node": "^1.26.0", + +// Package to use Google Cloud Trace exporter +"@google-cloud/opentelemetry-cloud-trace-exporter": "^2.4.1", + +// Packages to enable gRPC instrumentation +"@opentelemetry/instrumentation": "^0.53.0", +"@opentelemetry/instrumentation-grpc": "^0.53.0", +``` + +#### OpenTelemetry Configuration + +```javascript +const { + NodeTracerProvider, + TraceIdRatioBasedSampler, +} = require('@opentelemetry/sdk-trace-node'); +const { + BatchSpanProcessor, +} = require('@opentelemetry/sdk-trace-base'); +const { + TraceExporter, +} = require('@google-cloud/opentelemetry-cloud-trace-exporter'); +const exporter = new TraceExporter(); + +// Create the tracerProvider that the exporter shall be attached to. +const provider = new NodeTracerProvider({ + resource: resource, + spanProcessors: [new BatchSpanProcessor(exporter)] +}); + +// Create the Cloud Spanner Client. +const {Spanner} = require('@google-cloud/spanner'); +const spanner = new Spanner({ + projectId: projectId, + observabilityOptions: { + // Inject the TracerProvider via SpannerOptions or + // register it as a global by invoking `provider.register()` + tracerProvider: provider, + }, +}); +``` + +#### SQL Statement span annotation + +To allow your SQL statements to be annotated in the appropriate spans, you need to opt-in, because +SQL statements can contain sensitive personally-identifiable-information (PII). + +You can opt-in by either: + +* Setting the environment variable `SPANNER_ENABLE_EXTENDED_TRACING=true` before your application is started +* In code, setting `enableExtendedTracing: true` in your SpannerOptions before creating the Cloud Spanner client + +```javascript +const spanner = new Spanner({ + projectId: projectId, + observabilityOptions: { + tracerProvider: provider, + enableExtendedTracing: true, + } +}), +``` + +#### End to end tracing + +In addition to client-side tracing, you can opt in for end-to-end tracing. End-to-end tracing helps you understand and debug latency issues that are specific to Spanner. Refer [here](https://cloud.google.com/spanner/docs/tracing-overview) for more information. + +To configure end-to-end tracing. + +1. Opt in for end-to-end tracing. You can opt-in by either: +* Setting the environment variable `SPANNER_ENABLE_END_TO_END_TRACING=true` before your application is started +* In code, setting `enableEndToEndTracing: true` in your SpannerOptions before creating the Cloud Spanner client + +```javascript +const spanner = new Spanner({ + projectId: projectId, + observabilityOptions: { + tracerProvider: provider, + enableEndToEndTracing: true, + } +}), +``` + +2. Set the trace context propagation in OpenTelemetry. +```javascript +const {propagation} = require('@opentelemetry/api'); +const {W3CTraceContextPropagator} = require('@opentelemetry/core'); +propagation.setGlobalPropagator(new W3CTraceContextPropagator()); +``` + +#### OpenTelemetry gRPC instrumentation + +Optionally, you can enable OpenTelemetry gRPC instrumentation which produces traces of executed remote procedure calls (RPCs) +in your programs by these imports and instantiation. You could pass in the traceProvider or register it globally +by invoking `tracerProvider.register()` + +```javascript + const {registerInstrumentations} = require('@opentelemetry/instrumentation'); + const {GrpcInstrumentation} = require('@opentelemetry/instrumentation-grpc'); + registerInstrumentations({ + tracerProvider: tracerProvider, + instrumentations: [new GrpcInstrumentation()], + }); +``` + +#### Tracing Sample +For more information please see this [sample code](./samples/observability-traces.js) diff --git a/handwritten/spanner/README.md b/handwritten/spanner/README.md new file mode 100644 index 00000000000..2f55e5c9aff --- /dev/null +++ b/handwritten/spanner/README.md @@ -0,0 +1,329 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Cloud Spanner: Node.js Client](https://github.com/googleapis/nodejs-spanner) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/@google-cloud/spanner.svg)](https://www.npmjs.com/package/@google-cloud/spanner) + + + + +[Cloud Spanner](https://cloud.google.com/spanner/docs/) is a fully managed, mission-critical, relational database service that +offers transactional consistency at global scale, schemas, SQL (ANSI 2011 with extensions), +and automatic, synchronous replication for high availability. + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/nodejs-spanner/blob/main/CHANGELOG.md). + +* [Cloud Spanner Node.js Client API Reference][client-docs] +* [Cloud Spanner Documentation][product-docs] +* [github.com/googleapis/nodejs-spanner](https://github.com/googleapis/nodejs-spanner) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + * [Before you begin](#before-you-begin) + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Enable billing for your project][billing]. +1. [Enable the Cloud Spanner API][enable_api]. +1. [Set up authentication][auth] so you can access the + API from your local workstation. + +### Installing the client library + +```bash +npm install @google-cloud/spanner +``` + + +### Using the client library + +```javascript +// Imports the Google Cloud client library +const {Spanner} = require('@google-cloud/spanner'); + +// Creates a client +const spanner = new Spanner({projectId}); + +// Gets a reference to a Cloud Spanner instance and database +const instance = spanner.instance(instanceId); +const database = instance.database(databaseId); + +// The query to execute +const query = { + sql: 'SELECT 1', +}; + +// Execute a simple SQL statement +const [rows] = await database.run(query); +console.log(`Query: ${rows.length} found.`); +rows.forEach(row => console.log(row)); + +``` +## Metrics + +Cloud Spanner client supports [client-side metrics](https://cloud.google.com/spanner/docs/view-manage-client-side-metrics) that you can use along with server-side metrics to optimize performance and troubleshoot performance issues if they occur. + +Client-side metrics are measured from the time a request leaves your application to the time your application receives the response. +In contrast, server-side metrics are measured from the time Spanner receives a request until the last byte of data is sent to the client. + +These metrics are enabled by default. You can opt out of using client-side metrics with the following code: + +```javascript +const spanner = new Spanner({ + disableBuiltInMetrics: true +}); +``` + +You can also disable these metrics by setting `SPANNER_DISABLE_BUILTIN_METRICS` to `true`. + +> Note: Client-side metrics needs `monitoring.timeSeries.create` IAM permission to export metrics data. Ask your administrator to grant your service account the [Monitoring Metric Writer](https://cloud.google.com/iam/docs/roles-permissions/monitoring#monitoring.metricWriter) (roles/monitoring.metricWriter) IAM role on the project. + +## Traces +Refer to the Observability README to know more about tracing support in the Cloud Spanner client. + +## Multiplexed Sessions + +Spanner's Multiplexed Sessions is now default enabled session mode in node client. This feature helps reduce +session management overhead and minimize session-related errors. + +For a detailed explanation on multiplexed sessions, please refer to the [official documentation](https://cloud.google.com/spanner/docs/sessions#multiplexed_sessions). + +## Regular Sessions + +To use regular sessions, disable the multiplexed sessions and set the following environment variables to `false`: + +* **For Read-Only Transactions:** +- `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS` +* **For Partitioned Operations:** +- `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS` +- `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS` +* **For Read-Write Transactions:** +- `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS` +- `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW` + +For a detailed explanation on session modes and env configurations, please refer to the [official documentation](https://cloud.google.com/spanner/docs/sessions). + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-spanner/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Add and drop new database role | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/add-and-drop-new-database-role.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/add-and-drop-new-database-role.js,samples/README.md) | +| Backups-cancel | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-cancel.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-cancel.js,samples/README.md) | +| Copies a source backup | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-copy-with-multiple-kms-keys.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-copy-with-multiple-kms-keys.js,samples/README.md) | +| Copies a source backup | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-copy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-copy.js,samples/README.md) | +| Backups-create-with-encryption-key | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-create-with-encryption-key.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-create-with-encryption-key.js,samples/README.md) | +| Backups-create-with-multiple-kms-keys | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-create-with-multiple-kms-keys.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-create-with-multiple-kms-keys.js,samples/README.md) | +| Backups-create | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-create.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-create.js,samples/README.md) | +| Backups-delete | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-delete.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-delete.js,samples/README.md) | +| Backups-get-database-operations | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-get-database-operations.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-get-database-operations.js,samples/README.md) | +| Backups-get-operations | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-get-operations.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-get-operations.js,samples/README.md) | +| Backups-get | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-get.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-get.js,samples/README.md) | +| Backups-restore-with-encryption-key | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-restore-with-encryption-key.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-restore-with-encryption-key.js,samples/README.md) | +| Backups-restore-with-multiple-kms-keys | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-restore-with-multiple-kms-keys.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-restore-with-multiple-kms-keys.js,samples/README.md) | +| Backups-restore | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-restore.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-restore.js,samples/README.md) | +| Backups-update | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups-update.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups-update.js,samples/README.md) | +| Backups | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/backups.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/backups.js,samples/README.md) | +| Batch Write | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/batch-write.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/batch-write.js,samples/README.md) | +| Batch | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/batch.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/batch.js,samples/README.md) | +| Creates a full backup schedule | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/create-full-backup-schedule.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/create-full-backup-schedule.js,samples/README.md) | +| Creates an incremental backup schedule | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/create-incremental-backup-schedule.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/create-incremental-backup-schedule.js,samples/README.md) | +| Create-instance-without-default-backup-schedules | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/create-instance-without-default-backup-schedules.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/create-instance-without-default-backup-schedules.js,samples/README.md) | +| CRUD | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/crud.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/crud.js,samples/README.md) | +| Adds split points to a database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-add-split-points.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-add-split-points.js,samples/README.md) | +| Creates a new database with a specific default leader | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-create-with-default-leader.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-create-with-default-leader.js,samples/README.md) | +| Database-create-with-encryption-key | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-create-with-encryption-key.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-create-with-encryption-key.js,samples/README.md) | +| Database-create-with-multiple-kms-keys | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-create-with-multiple-kms-keys.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-create-with-multiple-kms-keys.js,samples/README.md) | +| Database-create-with-version-retention-period | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-create-with-version-retention-period.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-create-with-version-retention-period.js,samples/README.md) | +| Gets the schema definition of an existing database | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-get-ddl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-get-ddl.js,samples/README.md) | +| Gets the default leader option of an existing database | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-get-default-leader.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-get-default-leader.js,samples/README.md) | +| Updates the default leader of an existing database | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-update-default-leader.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-update-default-leader.js,samples/README.md) | +| Updates a Cloud Spanner Database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/database-update.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/database-update.js,samples/README.md) | +| Datatypes | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/datatypes.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/datatypes.js,samples/README.md) | +| Deletes a backup schedule | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/delete-backup-schedule.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/delete-backup-schedule.js,samples/README.md) | +| Runs an execute sql request with directed read options | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/directed-reads.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/directed-reads.js,samples/README.md) | +| Delete using DML returning. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/dml-returning-delete.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/dml-returning-delete.js,samples/README.md) | +| Insert using DML returning. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/dml-returning-insert.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/dml-returning-insert.js,samples/README.md) | +| Update using DML returning. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/dml-returning-update.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/dml-returning-update.js,samples/README.md) | +| DML | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/dml.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/dml.js,samples/README.md) | +| Enable fine grained access control | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/enable-fine-grained-access.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/enable-fine-grained-access.js,samples/README.md) | +| Gets a backup schedule | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/get-backup-schedule.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/get-backup-schedule.js,samples/README.md) | +| Get-commit-stats | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/get-commit-stats.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/get-commit-stats.js,samples/README.md) | +| List database roles | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/get-database-roles.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/get-database-roles.js,samples/README.md) | +| Gets the instance config metadata for the configuration nam6 | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/get-instance-config.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/get-instance-config.js,samples/README.md) | +| Creates a new value-storing index | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/index-create-storing.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/index-create-storing.js,samples/README.md) | +| Creates a new index | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/index-create.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/index-create.js,samples/README.md) | +| Executes a read-only SQL query using an existing index. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/index-query-data.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/index-query-data.js,samples/README.md) | +| Reads data using an existing storing index. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/index-read-data-with-storing.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/index-read-data-with-storing.js,samples/README.md) | +| Read data using an existing index. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/index-read-data.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/index-read-data.js,samples/README.md) | +| Indexing | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/indexing.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/indexing.js,samples/README.md) | +| Creates a user-managed instance configuration. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-config-create.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-config-create.js,samples/README.md) | +| Deletes a user-managed instance configuration. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-config-delete.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-config-delete.js,samples/README.md) | +| Lists the instance configuration operations. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-config-get-operations.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-config-get-operations.js,samples/README.md) | +| Updates a user-managed instance configuration. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-config-update.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-config-update.js,samples/README.md) | +| Creates a new instance partition | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-partition-create.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-partition-create.js,samples/README.md) | +| Updates an instance. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-update.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-update.js,samples/README.md) | +| Creates a instance with asymmetric autoscaling config. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-with-asymmetric-autoscaling-config.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-with-asymmetric-autoscaling-config.js,samples/README.md) | +| Creates a instance with autoscaling config. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-with-autoscaling-config.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-with-autoscaling-config.js,samples/README.md) | +| Instance-with-processing-units | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance-with-processing-units.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance-with-processing-units.js,samples/README.md) | +| Instance | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/instance.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/instance.js,samples/README.md) | +| Json-add-column | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/json-add-column.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/json-add-column.js,samples/README.md) | +| Json-query-parameter | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/json-query-parameter.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/json-query-parameter.js,samples/README.md) | +| Json-update-data | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/json-update-data.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/json-update-data.js,samples/README.md) | +| Lists backup schedules of a database | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/list-backup-schedules.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/list-backup-schedules.js,samples/README.md) | +| Lists all databases on the selected instance | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/list-databases.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/list-databases.js,samples/README.md) | +| Lists all the available instance configs for the selected project. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/list-instance-configs.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/list-instance-configs.js,samples/README.md) | +| Executes request with max commit delay | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/max-commit-delay.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/max-commit-delay.js,samples/README.md) | +| Numeric-add-column | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/numeric-add-column.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/numeric-add-column.js,samples/README.md) | +| Numeric-query-parameter | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/numeric-query-parameter.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/numeric-query-parameter.js,samples/README.md) | +| Numeric-update-data | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/numeric-update-data.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/numeric-update-data.js,samples/README.md) | +| Observability (Tracing) with OpenTelemetry using OTLP | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/observability-traces-otlp.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/observability-traces-otlp.js,samples/README.md) | +| Observability (Tracing) with OpenTelemetry | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/observability-traces.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/observability-traces.js,samples/README.md) | +| Adds a column to an existing table in a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-add-column.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-add-column.js,samples/README.md) | +| Showcase the rules for case-sensitivity and case folding for a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-case-sensitivity.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-case-sensitivity.js,samples/README.md) | +| Creates a PostgreSQL Database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-database-create.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-database-create.js,samples/README.md) | +| Use cast operator to cast from one data type to another in a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-datatypes-casting.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-datatypes-casting.js,samples/README.md) | +| Execute a batch of DML statements on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-dml-batch.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-dml-batch.js,samples/README.md) | +| Updates data in a table in a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-dml-getting-started-update.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-dml-getting-started-update.js,samples/README.md) | +| Execute a Partitioned DML on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-dml-partitioned.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-dml-partitioned.js,samples/README.md) | +| Delete using DML returning on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-dml-returning-delete.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-dml-returning-delete.js,samples/README.md) | +| Insert using DML returning on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-dml-returning-insert.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-dml-returning-insert.js,samples/README.md) | +| Update using DML returning on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-dml-returning-update.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-dml-returning-update.js,samples/README.md) | +| Execute a DML statement with parameters on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-dml-with-parameter.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-dml-with-parameter.js,samples/README.md) | +| Calls a server side function on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-functions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-functions.js,samples/README.md) | +| Creates a new storing index in a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-index-create-storing.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-index-create-storing.js,samples/README.md) | +| Created interleaved table hierarchy using PostgreSQL dialect. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-interleaving.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-interleaving.js,samples/README.md) | +| Showcase how add a jsonb column in a PostgreSQL table. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-jsonb-add-column.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-jsonb-add-column.js,samples/README.md) | +| Showcase how query data to a jsonb column in a PostgreSQL table. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-jsonb-query-parameter.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-jsonb-query-parameter.js,samples/README.md) | +| Showcase how update data to a jsonb column in a PostgreSQL table. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-jsonb-update-data.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-jsonb-update-data.js,samples/README.md) | +| Showcase how to work with the PostgreSQL NUMERIC/DECIMAL data type on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-numeric-data-type.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-numeric-data-type.js,samples/README.md) | +| Showcases how a Spanner PostgreSQL database orders null values in a query. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-ordering-nulls.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-ordering-nulls.js,samples/README.md) | +| Execute a query with parameters on a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-query-parameter.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-query-parameter.js,samples/README.md) | +| Query the information schema metadata in a Spanner PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-schema-information.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-schema-information.js,samples/README.md) | +| Alters a sequence in a PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-sequence-alter.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-sequence-alter.js,samples/README.md) | +| Creates sequence in PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-sequence-create.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-sequence-create.js,samples/README.md) | +| Drops a sequence in PostgreSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/pg-sequence-drop.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/pg-sequence-drop.js,samples/README.md) | +| Proto-query-data | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/proto-query-data.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/proto-query-data.js,samples/README.md) | +| Creates a new database with a proto column and enum | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/proto-type-add-column.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/proto-type-add-column.js,samples/README.md) | +| Proto-update-data-dml | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/proto-update-data-dml.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/proto-update-data-dml.js,samples/README.md) | +| Proto-update-data | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/proto-update-data.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/proto-update-data.js,samples/README.md) | +| Queryoptions | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/queryoptions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/queryoptions.js,samples/README.md) | +| Quickstart | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | +| Read data with database role | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/read-data-with-database-role.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/read-data-with-database-role.js,samples/README.md) | +| Performs a read-write transaction with read lock mode option | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/read-lock-mode.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/read-lock-mode.js,samples/README.md) | +| Performs a read-write transaction with isolation level option | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/repeatable-reads.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/repeatable-reads.js,samples/README.md) | +| Sets a request tag for a single query | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/request-tag.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/request-tag.js,samples/README.md) | +| Run Batch update with RPC priority | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/rpc-priority-batch-dml.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/rpc-priority-batch-dml.js,samples/README.md) | +| Run partitioned update with RPC priority | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/rpc-priority-partitioned-dml.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/rpc-priority-partitioned-dml.js,samples/README.md) | +| Create partitions with RPC priority | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/rpc-priority-query-partitions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/rpc-priority-query-partitions.js,samples/README.md) | +| Read data with RPC Priority | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/rpc-priority-read.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/rpc-priority-read.js,samples/README.md) | +| Query data with RPC Priority | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/rpc-priority-run.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/rpc-priority-run.js,samples/README.md) | +| Run transaction with RPC priority | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/rpc-priority-transaction.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/rpc-priority-transaction.js,samples/README.md) | +| Schema | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/schema.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/schema.js,samples/README.md) | +| Alters a sequence in a GoogleSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/sequence-alter.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/sequence-alter.js,samples/README.md) | +| Creates sequence in GoogleSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/sequence-create.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/sequence-create.js,samples/README.md) | +| Drops a sequence in GoogleSQL database. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/sequence-drop.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/sequence-drop.js,samples/README.md) | +| Executes a read/write transaction with statement timeout | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/statement-timeout.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/statement-timeout.js,samples/README.md) | +| Struct | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/struct.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/struct.js,samples/README.md) | +| Alters a table with foreign key delete cascade action | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/table-alter-with-foreign-key-delete-cascade.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/table-alter-with-foreign-key-delete-cascade.js,samples/README.md) | +| Creates a table with foreign key delete cascade action | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/table-create-with-foreign-key-delete-cascade.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/table-create-with-foreign-key-delete-cascade.js,samples/README.md) | +| Drops a foreign key constraint with delete cascade action | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/table-drop-foreign-key-constraint-delete-cascade.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/table-drop-foreign-key-constraint-delete-cascade.js,samples/README.md) | +| Timestamp | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/timestamp.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/timestamp.js,samples/README.md) | +| Executes a read/write transaction with transaction and request tags | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/transaction-tag.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/transaction-tag.js,samples/README.md) | +| Executes a read/write transaction with transaction timeout | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/transaction-timeout.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/transaction-timeout.js,samples/README.md) | +| Transaction | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/transaction.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/transaction.js,samples/README.md) | +| Updates a backup schedule | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/update-backup-schedule.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/update-backup-schedule.js,samples/README.md) | +| Updates an instance. | [source code](https://github.com/googleapis/nodejs-spanner/blob/main/samples/update-instance-default-backup-schedule-type.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-spanner&page=editor&open_in_editor=samples/update-instance-default-backup-schedule-type.js,samples/README.md) | + + + +The [Cloud Spanner Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install @google-cloud/spanner@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-spanner/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-spanner/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/spanner/latest +[product-docs]: https://cloud.google.com/spanner/docs/ +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=spanner.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/handwritten/spanner/benchmark/.eslintrc.yml b/handwritten/spanner/benchmark/.eslintrc.yml new file mode 100644 index 00000000000..282535f55f6 --- /dev/null +++ b/handwritten/spanner/benchmark/.eslintrc.yml @@ -0,0 +1,3 @@ +--- +rules: + no-console: off diff --git a/handwritten/spanner/benchmark/README.md b/handwritten/spanner/benchmark/README.md new file mode 100644 index 00000000000..8524b54d512 --- /dev/null +++ b/handwritten/spanner/benchmark/README.md @@ -0,0 +1,70 @@ +# YCSB Benchmarks + +Implements [YCSB](https://github.com/brianfrankcooper/YCSB) clients for cloud +Spanner in Node.js. + +Visit [YCSBClientCloudSpanner](https://github.com/haih-g/YCSBClientCloudSpanner) +for more details. + +## Setup + +First you need to setup a Cloud Spanner instance and database. Then you can use +[YCSB](https://github.com/brianfrankcooper/YCSB) to load the database. Then you +can run the client benchmarks. + +### Set up the database + +```sh +$ gcloud spanner instances create ycsb-instance --nodes 1 \ + --config regional-us-central1 --description YCSB +$ gcloud spanner databases create ycsb --instance ycsb-instance +$ gcloud spanner databases ddl update ycsb --instance ycsb-instance \ + --ddl="CREATE TABLE usertable ( + id STRING(MAX), + field0 STRING(MAX), + field1 STRING(MAX), + field2 STRING(MAX), + field3 STRING(MAX), + field4 STRING(MAX), + field5 STRING(MAX), + field6 STRING(MAX), + field7 STRING(MAX), + field8 STRING(MAX), + field9 STRING(MAX), + ) PRIMARY KEY(id)" +``` + +### Use YCSB to load data + +You need to set up some environment variables first. You should use your own +gcloud credentials and project. + +```sh +$ export GOOGLE_APPLICATION_CREDENTIALS=/usr/local/google/home/haih/cloud-spanner-client-benchmark.json +$ export GCLOUD_PROJECT=cloud-spanner-client-benchmark +``` + +Then download YCSB and load the database. + +```sh +$ curl https://storage.googleapis.com/cloud-spanner-ycsb-custom-release/ycsb-cloudspanner-binding-0.13.0.tar.gz | tar -xzv +$ ycsb-cloudspanner-binding-0.13.0/bin/ycsb load cloudspanner \ + -P ycsb-cloudspanner-binding-0.13.0/workloads/workloada \ + -p table=usertable -p cloudspanner.instance=ycsb-instance \ + -p recordcount=5000 -p operationcount=100 -p cloudspanner.database=ycsb \ + -threads 32 +``` + +## Run benchmarks + +```sh +$ npm run ycsb +``` + +Or if you want complete control over the parameters. + +```sh +node benchmarks/ycsb.js run -P benchmarks/workloada -p table=usertable \ + -p cloudspanner.instance=ycsb-542756a4 -p recordcount=5000 \ + -p operationcount=100 -p cloudspanner.database=ycsb -p num_worker=1 +``` diff --git a/handwritten/spanner/benchmark/benchmarking-multiplexed-session.js b/handwritten/spanner/benchmark/benchmarking-multiplexed-session.js new file mode 100644 index 00000000000..44b90161c0e --- /dev/null +++ b/handwritten/spanner/benchmark/benchmarking-multiplexed-session.js @@ -0,0 +1,261 @@ +/*! + * Copyright 2025 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const {randomUUID} = require('crypto'); + +const thread_execution_times = []; +const transaction_times = []; +async function main( + instanceId, + databaseId, + projectId, + method, + numThreads, + numQueries, +) { + const {Spanner} = require('../build/src'); + const {performance} = require('perf_hooks'); + const spanner = new Spanner({ + projectId: projectId, + }); + + // Gets a reference to a Cloud Spanner instance and database + const instance = spanner.instance(instanceId); + const database = instance.database(databaseId); + + // generate random read queries + function generateReadQuery() { + const id = Math.floor(Math.random() * 10000) + 1; + const query = { + sql: 'SELECT SingerId from Singers WHERE SingerId = @id', + params: {id: id}, + }; + return query; + } + + // generate random update queries + function generateUpdateQuery() { + const id = Math.floor(Math.random() * 10000) + 1; + const name = randomUUID(); + const query = { + sql: 'UPDATE Singers SET FirstName = @name WHERE SingerId = @id', + params: { + id: id, + name: name, + }, + }; + return query; + } + // warm up queries(~5-6 min) + for (let i = 0; i < 60000; i++) { + await database.run(generateReadQuery()); + } + + // case: read and DML + async function readAndDML() { + const startThreadTime = performance.now(); + + for (let i = 0; i < numQueries; i++) { + const startTime = performance.now(); + await database.runTransactionAsync(async tx => { + const [rows] = await tx.run(generateReadQuery()); + rows.forEach(row => { + const json = row.toJSON(); + console.log(`SingerId: ${json.SingerId}`); + }); + await tx.runUpdate(generateUpdateQuery()); + await tx.commit(); + console.log('transaction done.'); + }); + const operationTime = performance.now() - startTime; + // push the time taken by transaction to the array + transaction_times.push(operationTime); + } + + // push the time taken by thread to the array + thread_execution_times.push( + (performance.now() - startThreadTime).toFixed(2), + ); + } + + // case: mutations only + async function mutationsOnly() { + const startThreadTime = performance.now(); + + for (let i = 0; i < numQueries; i++) { + const startTime = performance.now(); + await database.runTransactionAsync(async tx => { + const id = Math.floor(Math.random() * 10000) + 1; + const name = randomUUID(); + tx.upsert('Singers', [{SingerId: id, FirstName: name}]); + await tx.commit(); + console.log('transaction done.'); + }); + const operationTime = performance.now() - startTime; + // push the time taken by transaction to the array + transaction_times.push(operationTime); + } + + // push the time taken by thread to the array + thread_execution_times.push( + (performance.now() - startThreadTime).toFixed(2), + ); + } + + // case: read and mutations + async function readAndMutations() { + const startThreadTime = performance.now(); + + for (let i = 0; i < numQueries; i++) { + const startTime = performance.now(); + await database.runTransactionAsync(async tx => { + const [rows] = await tx.run(generateReadQuery()); + rows.forEach(row => { + const json = row.toJSON(); + console.log(`SingerId: ${json.SingerId}`); + }); + const id = Math.floor(Math.random() * 10000) + 1; + const name = randomUUID(); + tx.upsert('Singers', [{SingerId: id, FirstName: name}]); + await tx.commit(); + console.log('transaction done.'); + }); + const operationTime = performance.now() - startTime; + // push the time taken by transaction to the array + transaction_times.push(operationTime); + } + + // push the time taken by thread to the array + thread_execution_times.push( + (performance.now() - startThreadTime).toFixed(2), + ); + } + + // case: single use transaction + async function singleUseTxn() { + const startThreadTime = performance.now(); + + for (let i = 0; i < numQueries; i++) { + const startTime = performance.now(); + await database.run(generateReadQuery()); + const operationTime = performance.now() - startTime; + // push the time taken by transaction to the array + transaction_times.push(operationTime); + } + + // push the time taken by thread to the array + thread_execution_times.push( + (performance.now() - startThreadTime).toFixed(2), + ); + } + + // case: multi use transaction + async function multiUseTxn() { + const startThreadTime = performance.now(); + + for (let i = 0; i < numQueries; i++) { + const startTime = performance.now(); + const [txn] = await database.getSnapshot(); + // run 4 queries to make 4 RPC calls + await txn.run(generateReadQuery()); + await txn.run(generateReadQuery()); + await txn.run(generateReadQuery()); + await txn.run(generateReadQuery()); + txn.end(); + const operationTime = (performance.now() - startTime).toFixed(2); + // push the time taken by transaction to the array + transaction_times.push(operationTime); + } + + // push the time taken by thread to the array + thread_execution_times.push( + (performance.now() - startThreadTime).toFixed(2), + ); + } + + function calculatePercentiles(latencies) { + // Step 1: Sort the array + const sortedLatencies = latencies.slice().sort((a, b) => a - b); + + // Step 2: Calculate average + const sum = sortedLatencies.reduce((acc, num) => acc + parseFloat(num), 0); + const average = (sum / sortedLatencies.length).toFixed(2); + + // Step 3: Calculate p50 (50th percentile) + const p50Index = Math.floor(0.5 * sortedLatencies.length); + const p50Latency = parseFloat(sortedLatencies[p50Index]).toFixed(2); + + // Step 4: Calculate p90 (90th percentile) + const p90Index = Math.floor(0.9 * sortedLatencies.length); + const p90Latency = parseFloat(sortedLatencies[p90Index]).toFixed(2); + + // Step 5: Calculate p99 (99th percentile) + const p99Index = Math.floor(0.99 * sortedLatencies.length); + const p99Latency = parseFloat(sortedLatencies[p99Index]).toFixed(2); + + return { + avg: average, + p50: p50Latency, + p90: p90Latency, + p99: p99Latency, + }; + } + + // run the threads concurrently + async function runConcurrently() { + const methodMap = { + readAndDML: readAndDML, + readAndMutations: readAndMutations, + mutationsOnly: mutationsOnly, + singleUseTxn: singleUseTxn, + multiUseTxn: multiUseTxn, + }; + const funcToRun = methodMap[method]; + const promises = []; + for (let i = 0; i < numThreads; i++) { + promises.push(funcToRun()); + } + await Promise.all(promises); + // print the time taken by each thread + console.log('excution time taken by threads are: '); + thread_execution_times.forEach(executionTime => { + console.log(executionTime); + }); + } + + try { + // wait for all the threads to complete the execution + await runConcurrently(); + // calculate percentiles + const percentiles = calculatePercentiles(transaction_times); + // print percentiles results + console.log(`average Latency: ${percentiles.avg}`); + console.log(`p50 Latency: ${percentiles.p50}`); + console.log(`p90 Latency: ${percentiles.p90}`); + console.log(`p99 Latency: ${percentiles.p99}`); + } catch (error) { + // log error if any + console.log('error: ', error); + } +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/spanner/benchmark/bin/ycsb b/handwritten/spanner/benchmark/bin/ycsb new file mode 100755 index 00000000000..def7796f6f1 --- /dev/null +++ b/handwritten/spanner/benchmark/bin/ycsb @@ -0,0 +1,43 @@ +#!/bin/bash + +# Copyright 2018 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 + +# A YCSB-like executable that can be integrated into PerfKitBenchmarker. +# +# It is intended to be run in a VM that is brought up by PerfKitBenchmarker +# with node.js, npm, and google-cloud for nodejs installed. The environment can +# be configured as follows: +# +# curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh \ +# | bash +# export NVM_DIR="$HOME/.nvm" +# [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" +# nvm install stable' +# nvm alias default stable') +# npm install --save express @google-cloud/storage @google-cloud/common-grpc \ +# binary-search-bounds dedent fs path stats-lite yargs checkpoint-stream +# lodash.chunk merge-stream google-gax lodash.flatten delay p-queue \ +# stack-trace lodash.snakecase lodash.random time-span +# sudo sudo apt-get -y install git +# git clone https://github.com/googleapis/nodejs-spanner.git + +export NVM_DIR="$HOME/.nvm" +[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +ln -s ${HOME}/nodejs-spanner/src ${DIR}/../../src +ln -s ${HOME}/node_modules ${DIR}/../node_modules + +node ${DIR}/../ycsb.js run "${@:4}" diff --git a/handwritten/spanner/benchmark/spanner.ts b/handwritten/spanner/benchmark/spanner.ts new file mode 100644 index 00000000000..a62b474a6c1 --- /dev/null +++ b/handwritten/spanner/benchmark/spanner.ts @@ -0,0 +1,726 @@ +/*! + * Copyright 2020 Google LLC. All Rights Reserved. + * + * 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 {grpc} from 'google-gax'; +import {Database, Instance, SessionPool, Snapshot, Spanner} from '../src'; +import * as mock from '../test/mockserver/mockspanner'; +import {SimulatedExecutionTime} from '../test/mockserver/mockspanner'; +import * as mockInstanceAdmin from '../test/mockserver/mockinstanceadmin'; +import * as mockDatabaseAdmin from '../test/mockserver/mockdatabaseadmin'; +import {google} from '../protos/protos'; +import {SessionPoolOptions} from '../src/session-pool'; +import protobuf = google.spanner.v1; +import {performance} from 'perf_hooks'; + +let spannerMock; +const server = new grpc.Server(); +const selectSql = 'SELECT 1'; +const updateSql = 'UPDATE FOO SET BAR=1 WHERE BAZ=2'; +let port: number; +let spanner: Spanner; +let instance: Instance; +let dbCounter = 1; + +/** + * This file contains four standardized benchmark tests for Spanner using an + * in-memory mock Spanner server. The simulated network latency and execution + * times have been selected to be realistic, but at the same time also equal + * and repeatable to different platforms for easy comparison. + * + * The four benchmarks are: + * 1. burstRead: Execute a burst of read-only operations using single-use + * transactions. This is intended to benchmark the ability of the session + * pool to quickly create and hand out new sessions on demand. + * 2. burstWrite: Execute a burst of read/write transactions containing one + * update statement. This is intended to benchmark the ability of the session + * pool to quickly create and hand out new write-prepared sessions on demand. + * 3. burstReadAndWrite: Execute a burst of read and write operations in + * parallel. This is intended to benchmark the ability of the session pool + * to quickly create and hand out both read and write-prepared sessions in + * parallel on demand. + * 4. steadyIncrease: Execute a stream of read operations that all hold on to + * the session for a while. This will force the session pool to grow + * step-by-step up to the max number of sessions in the pool. This is + * intended to benchmark the ability of the session pool to efficiently + * increase the number of sessions in the pool, but not necessarily in + * parallel. + */ +require('yargs') + .demand(1) + .command('burstRead', 'Benchmarks a burst of read operations', {}, () => + runBurstRead().then(() => console.log('Benchmark finished')), + ) + .example('node $0 burstRead') + .command('burstWrite', 'Benchmarks a burst of write operations', {}, () => + runBurstWrite().then(() => console.log('Benchmark finished')), + ) + .example('node $0 burstWrite') + .command( + 'burstReadAndWrite', + 'Benchmarks a burst of read and write operations', + {}, + () => runBurstReadAndWrite().then(() => console.log('Benchmark finished')), + ) + .example('node $0 burstReadAndWrite') + .command( + 'multipleWriteBursts', + 'Benchmarks a burst of read and then write operations', + {}, + () => + runMultipleWriteBursts().then(() => console.log('Benchmark finished')), + ) + .example('node $0 multipleWriteBursts') + .command( + 'oneReadTransactionPerSecond', + 'Benchmarks on avg one read tx per second', + {}, + () => + runOneReadTransactionPerSecond().then(() => + console.log('Benchmark finished'), + ), + ) + .example('node $0 oneReadTransactionPerSecond') + .command( + 'oneWriteTransactionPerSecond', + 'Benchmarks on avg one write tx per second', + {}, + () => + runOneWriteTransactionPerSecond().then(() => + console.log('Benchmark finished'), + ), + ) + .example('node $0 oneWriteTransactionPerSecond') + .command( + 'oneReadAndOneWriteTransactionPerSecond', + 'Benchmarks on avg one read and one write tx per second', + {}, + () => + runOneReadAndOneWriteTransactionPerSecond().then(() => + console.log('Benchmark finished'), + ), + ) + .example('node $0 oneReadAndOneWriteTransactionPerSecond') + .command( + 'steadyIncrease', + 'Benchmarks getting max sessions sequentially', + {}, + () => runSteadyIncrease().then(() => console.log('Benchmark finished')), + ) + .example('node $0 steadyIncrease') + .wrap(120) + .recommendCommands() + .strict() + .help().argv; + +async function runBurstRead() { + await setup(); + await burstRead(); + shutdown(); +} + +async function runBurstWrite() { + await setup(); + await burstWrite(); + shutdown(); +} + +async function runBurstReadAndWrite() { + await setup(); + await burstReadAndWrite(); + shutdown(); +} + +async function runMultipleWriteBursts() { + await setup(); + await multipleWriteBursts(); + shutdown(); +} + +async function runOneReadTransactionPerSecond() { + await setup(); + await oneReadTransactionPerSecond(); + shutdown(); +} + +async function runOneWriteTransactionPerSecond() { + await setup(); + await oneWriteTransactionPerSecond(); + shutdown(); +} + +async function runOneReadAndOneWriteTransactionPerSecond() { + await setup(); + await oneReadAndOneWriteTransactionPerSecond(); + shutdown(); +} + +async function runSteadyIncrease() { + await setup(); + await steadyIncrease(); + shutdown(); +} + +function newTestDatabase(options?: SessionPoolOptions): Database { + return instance.database(`database-${dbCounter++}`, options); +} + +/** + * Sets up the mocked benchmark server with standardized execution times and + * network latency. Results for both a simple SELECT and a simple UPDATE + * statement are mocked on the server. + */ +async function setup() { + const NETWORK_LATENCY_TIME = 10; + const BATCH_CREATE_SESSIONS_MIN_TIME = 10; + const BATCH_CREATE_SESSIONS_RND_TIME = 10; + const BEGIN_TRANSACTION_MIN_TIME = 1; + const BEGIN_TRANSACTION_RND_TIME = 1; + const COMMIT_TRANSACTION_MIN_TIME = 5; + const COMMIT_TRANSACTION_RND_TIME = 5; + const ROLLBACK_TRANSACTION_MIN_TIME = 1; + const ROLLBACK_TRANSACTION_RND_TIME = 1; + const EXECUTE_STREAMING_SQL_MIN_TIME = 10; + const EXECUTE_STREAMING_SQL_RND_TIME = 10; + const EXECUTE_SQL_MIN_TIME = 10; + const EXECUTE_SQL_RND_TIME = 10; + + spannerMock = mock.createMockSpanner(server); + mockInstanceAdmin.createMockInstanceAdmin(server); + mockDatabaseAdmin.createMockDatabaseAdmin(server); + + port = await new Promise((resolve, reject) => { + server.bindAsync( + '0.0.0.0:0', + grpc.ServerCredentials.createInsecure(), + (err, assignedPort) => { + if (err) { + reject(err); + } else { + resolve(assignedPort); + } + }, + ); + }); + server.start(); + + spannerMock.setExecutionTime( + spannerMock.batchCreateSessions, + SimulatedExecutionTime.ofMinAndRandomExecTime( + NETWORK_LATENCY_TIME + BATCH_CREATE_SESSIONS_MIN_TIME, + BATCH_CREATE_SESSIONS_RND_TIME, + ), + ); + spannerMock.setExecutionTime( + spannerMock.beginTransaction, + SimulatedExecutionTime.ofMinAndRandomExecTime( + NETWORK_LATENCY_TIME + BEGIN_TRANSACTION_MIN_TIME, + BEGIN_TRANSACTION_RND_TIME, + ), + ); + spannerMock.setExecutionTime( + spannerMock.commit, + SimulatedExecutionTime.ofMinAndRandomExecTime( + NETWORK_LATENCY_TIME + COMMIT_TRANSACTION_MIN_TIME, + COMMIT_TRANSACTION_RND_TIME, + ), + ); + spannerMock.setExecutionTime( + spannerMock.rollback, + SimulatedExecutionTime.ofMinAndRandomExecTime( + NETWORK_LATENCY_TIME + ROLLBACK_TRANSACTION_MIN_TIME, + ROLLBACK_TRANSACTION_RND_TIME, + ), + ); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofMinAndRandomExecTime( + NETWORK_LATENCY_TIME + EXECUTE_STREAMING_SQL_MIN_TIME, + EXECUTE_STREAMING_SQL_RND_TIME, + ), + ); + spannerMock.setExecutionTime( + spannerMock.executeSql, + SimulatedExecutionTime.ofMinAndRandomExecTime( + NETWORK_LATENCY_TIME + EXECUTE_SQL_MIN_TIME, + EXECUTE_SQL_RND_TIME, + ), + ); + spannerMock.putStatementResult( + selectSql, + mock.StatementResult.resultSet(createSelect1ResultSet()), + ); + spannerMock.putStatementResult( + updateSql, + mock.StatementResult.updateCount(1), + ); + + spanner = new Spanner({ + projectId: 'fake-project-id', + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + }); + // Gets a reference to a Cloud Spanner instance and database + instance = spanner.instance('instance'); +} + +/** + * Shutdown the benchmark server. + */ +function shutdown() { + server.tryShutdown(() => {}); + console.log('Server closed'); +} + +/** + * Executes the burstRead benchmark. + */ +async function burstRead() { + console.log('Starting burstRead'); + const HOLD_SESSION_TIME = 100; + const RND_WAIT_TIME_BETWEEN_REQUESTS = 10; + const NUM_BURST_READ = 3200; + // Value 'undefined' is used to warm up the compiler. + for (const incStep of [undefined, 1, 10, 20, 25, 30, 40, 50, 100]) { + spannerMock.resetRequests(); + const database = newTestDatabase({ + min: 100, + max: 400, + incStep: incStep, + }); + const pool = database.pool_ as SessionPool; + try { + if (incStep) { + console.time(`burstRead incStep ${incStep}`); + } + const promises = queueReadOperations( + database, + NUM_BURST_READ, + RND_WAIT_TIME_BETWEEN_REQUESTS, + HOLD_SESSION_TIME, + ); + await Promise.all(promises); + if (incStep) { + console.timeEnd(`burstRead incStep ${incStep}`); + console.log(`Current session pool size: ${pool.size}`); + } + } finally { + await database.close(); + } + } +} + +/** + * Executes the burstWrite benchmark. + */ +async function burstWrite() { + console.log('Starting burstWrite'); + const RND_WAIT_TIME_BETWEEN_REQUESTS = 10; + const NUM_BURST_WRITE = 3200; + // Value 'undefined' is used to warm up the compiler. + for (const incStep of [undefined, 1, 10, 20, 25, 30, 40, 50, 100]) { + const database = newTestDatabase({ + min: 100, + max: 400, + incStep: incStep, + }); + const pool = database.pool_ as SessionPool; + try { + if (incStep) { + console.time(`burstWrite incStep ${incStep}`); + } + const promises = queueWriteOperations( + database, + NUM_BURST_WRITE, + RND_WAIT_TIME_BETWEEN_REQUESTS, + ); + await Promise.all(promises); + if (incStep) { + console.timeEnd(`burstWrite incStep ${incStep}`); + console.log(`Current session pool size: ${pool.size}`); + } + } finally { + await database.close(); + } + } +} + +/** + * Executes the burstReadAndWrite benchmark. + */ +async function burstReadAndWrite() { + console.log('Starting burstReadAndWrite'); + const HOLD_SESSION_TIME = 100; + const RND_WAIT_TIME_BETWEEN_REQUESTS = 10; + const NUM_BURST_READ = 1600; + const NUM_BURST_WRITE = 1600; + // Value 'undefined' is used to warm up the compiler. + for (const incStep of [undefined, 1, 10, 20, 25, 30, 40, 50, 100]) { + const database = newTestDatabase({ + min: 100, + max: 400, + incStep: incStep, + }); + const pool = database.pool_ as SessionPool; + try { + if (incStep) { + console.time(`burstReadAndWrite incStep ${incStep}`); + } + const readPromises = queueReadOperations( + database, + NUM_BURST_READ, + RND_WAIT_TIME_BETWEEN_REQUESTS, + HOLD_SESSION_TIME, + ); + const writePromises = queueWriteOperations( + database, + NUM_BURST_WRITE, + RND_WAIT_TIME_BETWEEN_REQUESTS, + ); + await Promise.all(readPromises.concat(writePromises)); + if (incStep) { + console.timeEnd(`burstReadAndWrite incStep ${incStep}`); + console.log(`Current session pool size: ${pool.size}`); + } + } finally { + await database.close(); + } + } +} + +async function multipleWriteBursts() { + console.log('Starting multipleWriteBursts'); + const RND_WAIT_TIME_BETWEEN_REQUESTS = 10; + const NUM_BURSTS = 4; + const NUM_BURST_WRITE = 3200; + const WAIT_BETWEEN_BURSTS = 500; + // Value 'undefined' is used to warm up the compiler. + for (const incStep of [undefined, 1, 10, 20, 25, 30, 40, 50, 100]) { + const database = newTestDatabase({ + min: 100, + max: 400, + incStep: incStep, + }); + const pool = database.pool_ as SessionPool; + try { + if (incStep) { + console.time(`multipleWriteBursts incStep ${incStep}`); + } + for (let i = 0; i < NUM_BURSTS; i++) { + const writePromises = queueWriteOperations( + database, + NUM_BURST_WRITE, + RND_WAIT_TIME_BETWEEN_REQUESTS, + ); + await Promise.all(writePromises); + await new Promise(resolve => setTimeout(resolve, WAIT_BETWEEN_BURSTS)); + } + if (incStep) { + console.timeEnd(`multipleWriteBursts incStep ${incStep}`); + console.log(`Current session pool size: ${pool.size}`); + } + } finally { + await database.close(); + } + } +} + +async function oneReadTransactionPerSecond() { + console.log('Starting oneReadTransactionPerSecond'); + const RND_WAIT_TIME_BETWEEN_REQUESTS = 100000; + const NUM_TRANSACTIONS = RND_WAIT_TIME_BETWEEN_REQUESTS / 1000; + for (const minSessions of [0, 25]) { + const database = newTestDatabase({ + min: minSessions, + }); + const pool = database.pool_ as SessionPool; + try { + // Execute a batch of write requests to initialize the session pool with only + // write sessions. The dynamic scaling of the session pool should automatically + // change this into an appropriate number of read sessions as the test runs. + await queueWriteOperations(database, pool.options.incStep!, 0); + const readPromises = queueReadOperations( + database, + NUM_TRANSACTIONS, + RND_WAIT_TIME_BETWEEN_REQUESTS, + 0, + ); + readPromises.forEach(p => + p.then(t => { + console.log(`Time taken: ${t}ms`); + }), + ); + const t = await Promise.all(readPromises); + const max = Math.max(...t); + const min = Math.min(...t); + const sum = t.reduce((a, b) => a + b, 0); + const avg = sum / t.length || 0; + const p90 = percentile(t, 0.9); + console.log(`Max: ${max}`); + console.log(`Min: ${min}`); + console.log(`Avg: ${avg}`); + console.log(`P90: ${p90}`); + console.log(`Current session pool size: ${pool.size}`); + } finally { + await database.close(); + } + } +} + +async function oneWriteTransactionPerSecond() { + console.log('Starting oneWriteTransactionPerSecond'); + const RND_WAIT_TIME_BETWEEN_REQUESTS = 100000; + const NUM_TRANSACTIONS = RND_WAIT_TIME_BETWEEN_REQUESTS / 1000; + for (const minSessions of [0, 25]) { + const database = newTestDatabase({ + min: minSessions, + }); + const pool = database.pool_ as SessionPool; + try { + // Execute one read request to initialize the session pool. + await queueReadOperations(database, 1, 0, 0); + const writePromises = queueWriteOperations( + database, + NUM_TRANSACTIONS, + RND_WAIT_TIME_BETWEEN_REQUESTS, + ); + writePromises.forEach(p => + p.then(t => { + console.log(`Time taken: ${t}ms`); + }), + ); + const t = await Promise.all(writePromises); + const max = Math.max(...t); + const min = Math.min(...t); + const sum = t.reduce((a, b) => a + b, 0); + const avg = sum / t.length || 0; + const p90 = percentile(t, 0.9); + console.log(`Max: ${max}`); + console.log(`Min: ${min}`); + console.log(`Avg: ${avg}`); + console.log(`P90: ${p90}`); + console.log(`Current session pool size: ${pool.size}`); + } finally { + await database.close(); + } + } +} + +async function oneReadAndOneWriteTransactionPerSecond() { + console.log('Starting oneReadAndOneWriteTransactionPerSecond'); + const RND_WAIT_TIME_BETWEEN_REQUESTS = 100000; + const NUM_READ_TRANSACTIONS = RND_WAIT_TIME_BETWEEN_REQUESTS / 1000; + const NUM_WRITE_TRANSACTIONS = RND_WAIT_TIME_BETWEEN_REQUESTS / 1000; + for (const minSessions of [0, 25]) { + const database = newTestDatabase({ + min: minSessions, + }); + const pool = database.pool_ as SessionPool; + try { + const readPromises = queueReadOperations( + database, + NUM_READ_TRANSACTIONS, + RND_WAIT_TIME_BETWEEN_REQUESTS, + 0, + ); + const writePromises = queueWriteOperations( + database, + NUM_WRITE_TRANSACTIONS, + RND_WAIT_TIME_BETWEEN_REQUESTS, + ); + readPromises.forEach(p => + p.then(t => { + console.log(`Read tx: ${t}ms`); + }), + ); + writePromises.forEach(p => + p.then(t => { + console.log(`Write tx: ${t}ms`); + }), + ); + const t = await Promise.all(readPromises.concat(writePromises)); + const max = Math.max(...t); + const min = Math.min(...t); + const sum = t.reduce((a, b) => a + b, 0); + const avg = sum / t.length || 0; + const p90 = percentile(t, 0.9); + console.log(`Max: ${max}`); + console.log(`Min: ${min}`); + console.log(`Avg: ${avg}`); + console.log(`P90: ${p90}`); + console.log(`Current session pool size: ${pool.size}`); + } finally { + await database.close(); + } + } +} + +/** + * Executes the steadyIncrease benchmark. + */ +async function steadyIncrease() { + console.log('Starting steadyIncrease'); + // Value 'undefined' is used to warm up the compiler. + for (const incStep of [undefined, 1, 10, 20, 25, 30, 40, 50, 100]) { + const database = newTestDatabase({ + min: 100, + max: 400, + incStep: incStep, + }); + const pool = database.pool_ as SessionPool; + const snapshots: Snapshot[] = []; + try { + if (incStep) { + console.time(`steadyIncrease incStep ${incStep}`); + } + for (let i = 0; i < pool.options.max!; i++) { + const [snapshot] = await database.getSnapshot(); + snapshots.unshift(snapshot); + } + for (const snapshot of snapshots) { + snapshot.end(); + } + if (incStep) { + console.timeEnd(`steadyIncrease incStep ${incStep}`); + console.log(`Current session pool size: ${pool.size}`); + } + } finally { + await database.close(); + } + } +} + +/** + * Generates and submits read operations in parallel to the mock benchmark + * server. + * @param database The database to submit the queries to + * @param numRequests The number of read requests to submit. + * @param waitBetweenRequests The time to wait between each read request. This + * time will be used as the upper bound to get a + * randomized value for each request to simulate + * requests that come in at random intervals. + * @param holdSessionTime The time that the transaction should hold on to the + * session. This simulates the application performing + * calculations or other operations on the data that have + * been returned by Spanner. The time is used as an upper + * bound to get a randomized value for each request. + */ +function queueReadOperations( + database: Database, + numRequests: number, + waitBetweenRequests: number, + holdSessionTime: number, +): Promise[] { + const promises: Promise[] = []; + for (let run = 0; run < numRequests; run++) { + promises.unshift( + new Promise(resolve => { + setTimeout(async () => { + const t1 = performance.now(); + let p: Promise; + database + .runStream(selectSql) + .on('data', async () => { + p = new Promise(r => { + setTimeout(() => { + r(); + }, Math.random() * holdSessionTime); + }); + }) + .on('end', async () => { + await p; + resolve(performance.now() - t1); + }); + }, Math.random() * waitBetweenRequests); + }), + ); + } + return promises; +} + +/** + * Generates and submits write operations in parallel to the mock benchmark + * server. + * @param database The database to submit the updates to + * @param numRequests The number of write requests to submit. + * @param waitBetweenRequests The time to wait between each write request. This + * time will be used as the upper bound to get a + * randomized value for each request to simulate + * requests that come in at random intervals. + */ +function queueWriteOperations( + database: Database, + numRequests: number, + waitBetweenRequests: number, +): Promise[] { + const promises: Promise[] = []; + for (let run = 0; run < numRequests; run++) { + promises.unshift( + new Promise((resolve, rejects) => { + setTimeout(() => { + const t1 = performance.now(); + database.runTransaction((err, tx) => { + tx! + .runUpdate(updateSql) + .then(() => + tx! + .commit() + .then(() => resolve(performance.now() - t1)) + .catch(err => { + rejects(err); + }), + ) + .catch(err => { + rejects(err); + }); + }); + }, Math.random() * waitBetweenRequests); + }), + ); + } + return promises; +} + +/** Creates a simple result set for SELECT 1. */ +function createSelect1ResultSet(): protobuf.ResultSet { + const fields = [ + protobuf.StructType.Field.create({ + name: 'NUM', + type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + return protobuf.ResultSet.create({ + metadata, + rows: [{values: [{stringValue: '1'}]}], + }); +} + +function percentile(arr, p) { + const sorted = arr.sort((a, b) => a - b); + const pos = (sorted.length - 1) * p; + const base = Math.floor(pos); + const rest = pos - base; + if (sorted[base + 1] !== undefined) { + return sorted[base] + rest * (sorted[base + 1] - sorted[base]); + } else { + return sorted[base]; + } +} diff --git a/handwritten/spanner/benchmark/workload.js b/handwritten/spanner/benchmark/workload.js new file mode 100644 index 00000000000..ddce8cf6ea2 --- /dev/null +++ b/handwritten/spanner/benchmark/workload.js @@ -0,0 +1,123 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const crypto = require('crypto'); +const PQueue = require('p-queue'); +const random = require('lodash.random'); +const timeSpan = require('time-span'); + +const OPERATIONS = [ + 'readproportion', + 'updateproportion', + 'scanproportion', + 'insertproportion', +]; + +class Workload { + constructor(database, options) { + this.database = database; + this.options = options; + + this.queue = new PQueue(); + this.weights = []; + this.totalWeight = 0; + this.operations = []; + this.latencies = {}; + this.opCounts = {}; + this.totalOpCount = 0; + + for (const operation of OPERATIONS) { + const weight = parseFloat(this.options.get(operation)); + + if (weight <= 0) { + continue; + } + + const shortOpName = operation.replace('proportion', ''); + + this.operations.push(shortOpName); + this.latencies[shortOpName] = []; + this.totalWeight += weight; + this.weights.push(this.totalWeight); + } + } + + getRandomKey() { + return this.keys[random(this.keys.length - 1)]; + } + + loadKeys() { + return this.database + .run(`SELECT u.id FROM ${this.options.get('table')} u`) + .then(data => data[0].map(row => row[0].value)) + .then(keys => (this.keys = keys)); + } + + run() { + const operationCount = parseInt(this.options.get('operationcount')); + const end = timeSpan(); + + for (let i = 0; i < operationCount; i++) { + const randomWeight = Math.random() * this.totalWeight; + + for (let j = 0; j < this.weights.length; j++) { + const weight = this.weights[j]; + const operation = this.operations[j]; + + if (randomWeight <= weight) { + this.queue.add(() => this.runOperation(operation)); + break; + } + } + } + + return this.queue.onIdle().then(() => (this.duration = end())); + } + + runOperation(operation) { + if (typeof this[operation] !== 'function') { + throw new Error(`unsupported operation: ${operation.type}`); + } + + const end = timeSpan(); + + return this[operation]().then(() => this.latencies[operation].push(end())); + } + + read() { + const tableName = this.options.get('table'); + const id = this.getRandomKey(); + const query = `SELECT u.* FROM ${tableName} u WHERE u.id="${id}"`; + + return this.database.run(query, {readOnly: true}); + } + + update() { + const tableName = this.options.get('table'); + const id = this.getRandomKey(); + const field = `field${random(9)}`; + const value = crypto.randomBytes(100).toString('hex'); + + return this.database.runTransactionAsync(transaction => { + transaction.update(tableName, {id, [field]: value}); + return transaction.commit(); + }); + } +} + +module.exports = Workload; diff --git a/handwritten/spanner/benchmark/workloada b/handwritten/spanner/benchmark/workloada new file mode 100644 index 00000000000..dfe51c1be46 --- /dev/null +++ b/handwritten/spanner/benchmark/workloada @@ -0,0 +1,4 @@ +readproportion=0.95 +updateproportion=0.05 +scanproportion=0 +insertproportion=0 diff --git a/handwritten/spanner/benchmark/workloadb b/handwritten/spanner/benchmark/workloadb new file mode 100644 index 00000000000..3cdf324b3be --- /dev/null +++ b/handwritten/spanner/benchmark/workloadb @@ -0,0 +1,4 @@ +readproportion=0.5 +updateproportion=0.5 +scanproportion=0 +insertproportion=0 diff --git a/handwritten/spanner/benchmark/ycsb.js b/handwritten/spanner/benchmark/ycsb.js new file mode 100644 index 00000000000..055d565282b --- /dev/null +++ b/handwritten/spanner/benchmark/ycsb.js @@ -0,0 +1,140 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; + +const bounds = require('binary-search-bounds'); +const dedent = require('dedent'); +const fs = require('fs'); +const path = require('path'); +const stats = require('stats-lite'); + +const {Spanner} = require('../'); +const Workload = require('./workload'); + +require('yargs') + .version(false) + .strict() + .command( + 'run [args]', + 'Run the workload', + { + P: { + alias: 'workload', + type: 'string', + description: 'The path to a YCSB workload file', + coerce: parseWorkloadFile, + }, + p: { + alias: 'parameter', + description: 'The key=value pair of parameter', + coerce: parseKeyValuePairs, + }, + b: { + alias: 'num_bucket', + default: 1000, + type: 'number', + describe: 'The number of buckets in output', + }, + }, + runWorkloads, + ).argv; + +function formatOptions(argv) { + const options = argv.workload.concat(argv.parameter, [ + ['numBucket', argv.num_bucket], + ]); + + return new Map(options); +} + +function parseKeyValuePairs(pairs) { + return pairs.map(pair => pair.split('=')); +} + +function parseWorkloadFile(filePath) { + const contents = fs.readFileSync(path.resolve(filePath)); + return parseKeyValuePairs(contents.toString().split('\n')); +} + +function printMetrics(workload) { + const numBucket = workload.options.get('numBucket'); + let totalOps = 0; + + workload.operations.forEach(operation => { + totalOps += workload.latencies[operation].length; + }); + + console.log( + dedent`[OVERALL], RunTime(ms), ${workload.duration} + [OVERALL], Throughput(ops/sec), ${totalOps / (workload.duration / 1000)}`, + ); + + workload.operations.forEach(operation => { + const lats = workload.latencies[operation].sort((a, b) => a - b); + const ops = lats.length; + const opName = `[${operation.toUpperCase()}]`; + + console.log( + dedent`${opName}, Operations, ${ops} + ${opName}, AverageLatency(us), ${stats.mean(lats)} + ${opName}, LatencyVariance(us), ${stats.stdev(lats)} + ${opName}, MinLatency(us), ${lats[0]} + ${opName}, MaxLatency(us), ${lats[lats.length - 1]} + ${opName}, 95thPercentileLatency(us), ${stats.percentile(lats, 0.95)} + ${opName}, 99thPercentileLatency(us), ${stats.percentile(lats, 0.99)} + ${opName}, 99.9thPercentileLatency(us), ${stats.percentile(lats, 0.999)} + ${opName}, Return=OK, ${ops}`, + ); + + for (let i = 0; i < numBucket; i++) { + const hi = bounds.lt(lats, i + 1); + const lo = bounds.le(lats, i); + console.log(`${opName}, ${i}, ${hi - lo}`); + } + + const lo = bounds.le(lats, numBucket); + console.log(`${opName}, ${numBucket}, ${ops - lo}`); + }); +} + +function runWorkload(database, options) { + const workload = new Workload(database, options); + + return workload + .loadKeys() + .then(() => workload.run()) + .then(() => printMetrics(workload)) + .catch(err => console.error(err)); +} + +function runWorkloads(argv) { + const options = formatOptions(argv); + + const spanner = new Spanner({ + projectId: options.get('cloudspanner.project'), + }); + + const database = spanner + .instance(options.get('cloudspanner.instance')) + .database(options.get('cloudspanner.database')); + + return Promise.all( + Array(options.get('num_worker') || 1) + .fill(0) + .map(() => runWorkload(database, options)), + ); +} diff --git a/handwritten/spanner/bin/README.md b/handwritten/spanner/bin/README.md new file mode 100644 index 00000000000..45104f29521 --- /dev/null +++ b/handwritten/spanner/bin/README.md @@ -0,0 +1,13 @@ +# benchwrapper + +benchwrapper is a lightweight gRPC server that wraps the Spanner library for +benchmarking purposes. + +## Running + +``` +cd nodejs-spanner +npm install +export SPANNER_EMULATOR_HOST=localhost:8080 +npm run benchwrapper -- --port 8081 +``` \ No newline at end of file diff --git a/handwritten/spanner/bin/benchwrapper.js b/handwritten/spanner/bin/benchwrapper.js new file mode 100644 index 00000000000..231c7634f9a --- /dev/null +++ b/handwritten/spanner/bin/benchwrapper.js @@ -0,0 +1,149 @@ +// Copyright 2019 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. + +const {grpc} = require('google-gax'); +const protoLoader = require('@grpc/proto-loader'); +const {Spanner} = require('../build/src'); + +const argv = require('yargs') + .option('port', { + description: 'The port that the Node.js benchwrapper should run on.', + type: 'number', + demand: true, + }) + .parse(); + +const PROTO_PATH = __dirname + '/spanner.proto'; +const packageDefinition = protoLoader.loadSync(PROTO_PATH, { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, +}); +const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); +const spannerBenchWrapper = protoDescriptor.spanner_bench; + +// The benchwrapper should only be executed against an emulator. +if (!process.env.SPANNER_EMULATOR_HOST) { + throw new Error( + 'This benchmarking server only works when connected to an emulator. Please set SPANNER_EMULATOR_HOST.', + ); +} +// This will connect the Spanner client to an emulator, as SPANNER_EMULATOR_HOST has been set. +const spannerClient = new Spanner(); + +// Implementation of SpannerBenchWrapper.Read method. +function Read(call, callback) { + const instance = spannerClient.instance('someinstance'); + const database = instance.database('somedatabase'); + let tx; + database + .getSnapshot() + .then(data => { + tx = data[0]; + return tx.run(call.request.query); + }) + .then(data => { + const [rows] = data; + // Just iterate over all rows. + rows.forEach(() => {}); + }) + .finally(() => { + if (tx) { + tx.end(); + } + callback(null, {}); + }); +} + +// Implementation of SpannerBenchWrapper.Insert method. +function Insert(call, callback) { + const instance = spannerClient.instance('someinstance'); + const database = instance.database('somedatabase'); + database.runTransaction((err, transaction) => { + if (err) { + callback(err); + return; + } + call.request.singers.forEach(singer => { + transaction.insert('Singers', { + SingerId: singer.id, + FirstName: singer.first_name, + LastName: singer.last_name, + }); + }); + transaction.commit(err => { + if (err) { + callback(err); + } else { + callback(null, {}); + } + }); + }); +} + +// Implementation of SpannerBenchWrapper.Insert method. +function Update(call, callback) { + const instance = spannerClient.instance('someinstance'); + const database = instance.database('somedatabase'); + database.runTransaction((err, transaction) => { + if (err) { + callback(err); + return; + } + transaction.batchUpdate(call.request.queries, (err, rowCounts) => { + if (err) { + callback( + new grpc.StatusBuilder() + .withCode(err.code) + .withDetails(err.details || err.message) + .withMetadata(err.metadata) + .build(), + ); + transaction.rollback().then(() => {}); + return; + } + // Iterate over all rowCounts. + rowCounts.forEach(() => {}); + transaction.commit(err => { + if (err) { + callback(err); + } else { + callback(null, {}); + } + }); + }); + }); +} + +// Create and start a benchwrapper server. +const server = new grpc.Server(); +server.addService(spannerBenchWrapper['SpannerBenchWrapper']['service'], { + Read: Read, + Insert: Insert, + Update: Update, +}); +console.log('starting benchwrapper for Spanner on localhost:' + argv.port); +server.bindAsync( + '0.0.0.0:' + argv.port, + grpc.ServerCredentials.createInsecure(), + err => { + if (err) { + console.error(err); + return; + } + server.start(); + }, +); diff --git a/handwritten/spanner/bin/benchwrapper_test_client.js b/handwritten/spanner/bin/benchwrapper_test_client.js new file mode 100644 index 00000000000..a7fc5d46808 --- /dev/null +++ b/handwritten/spanner/bin/benchwrapper_test_client.js @@ -0,0 +1,75 @@ +// Copyright 2019 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. + +// This is a simple test client for the Spanner benchwrapper. + +const {grpc} = require('google-gax'); +const protoLoader = require('@grpc/proto-loader'); + +const argv = require('yargs') + .option('port', { + description: 'The port that the benchwrapper client should connect to.', + type: 'number', + demand: true, + }) + .parse(); + +const PROTO_PATH = __dirname + '/spanner.proto'; +const packageDefinition = protoLoader.loadSync(PROTO_PATH, { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, +}); +const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); +const spannerBenchWrapper = protoDescriptor.spanner_bench; + +console.log(`connecting to localhost:${argv.port}`); +const client = new spannerBenchWrapper.SpannerBenchWrapper( + `localhost:${argv.port}`, + grpc.credentials.createInsecure(), +); +const readReq = { + Query: 'SELECT 1 AS COL1 UNION ALL SELECT 2 AS COL1', +}; +const insertReq = { + singers: [ + {id: '1', firstName: 'Lana', lastName: 'Del Rey'}, + {id: '2', firstName: 'Taylor', lastName: 'Swift'}, + ], +}; +const updateReq = { + Queries: [ + 'UPDATE sometable SET foo=1 WHERE bar=2', + 'UPDATE sometable SET foo=2 WHERE bar=1', + ], +}; +client.read(readReq, (err, result) => { + callback('read', err, result); +}); +client.insert(insertReq, (err, result) => { + callback('insert', err, result); +}); +client.update(updateReq, (err, result) => { + callback('update', err, result); +}); + +function callback(method, err, result) { + if (err) { + console.log(`${method} failed with error ${err}`); + return; + } + console.log(`${method} executed with result ${result}`); +} diff --git a/handwritten/spanner/bin/spanner.proto b/handwritten/spanner/bin/spanner.proto new file mode 100644 index 00000000000..10153a4ccad --- /dev/null +++ b/handwritten/spanner/bin/spanner.proto @@ -0,0 +1,73 @@ +// Copyright 2019 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. + +syntax = "proto3"; + +package spanner_bench; +option java_multiple_files = true; +option java_package = "com.google.cloud.benchwrapper"; + +message Singer { + int64 id = 1; + string first_name = 2; + string last_name = 3; + string singer_info = 4; +} + +message Album { + int64 id = 1; + int64 singer_id = 2; + string album_title = 3; +} + +message ReadQuery { + // The query to use in the read call. + string query = 1; +} + +message InsertQuery { + // The query to use in the insert call. + repeated Singer singers = 1; + repeated Album albums = 2; +} + +message UpdateQuery { + // The queries to use in the update call. + repeated string queries = 1; +} + +message EmptyResponse {} + +service SpannerBenchWrapper { + // Read represents operations like Go's ReadOnlyTransaction.Query, Java's + // ReadOnlyTransaction.executeQuery, Python's snapshot.read, and Node's + // Transaction.Read. + // + // It will typically be used to read many items. + rpc Read(ReadQuery) returns (EmptyResponse) {} + + // Insert represents operations like Go's Client.Apply, Java's + // DatabaseClient.writeAtLeastOnce, Python's transaction.commit, and Node's + // Transaction.Commit. + // + // It will typically be used to insert many items. + rpc Insert(InsertQuery) returns (EmptyResponse) {} + + // Update represents operations like Go's ReadWriteTransaction.BatchUpdate, + // Java's TransactionRunner.run, Python's Batch.update, and Node's + // Transaction.BatchUpdate. + // + // It will typically be used to update many items. + rpc Update(UpdateQuery) returns (EmptyResponse) {} +} \ No newline at end of file diff --git a/handwritten/spanner/linkinator.config.json b/handwritten/spanner/linkinator.config.json new file mode 100644 index 00000000000..cbd5b15dcff --- /dev/null +++ b/handwritten/spanner/linkinator.config.json @@ -0,0 +1,17 @@ +{ + "recurse": true, + "skip": [ + "https://codecov.io/gh/googleapis/", + "www.googleapis.com", + "img.shields.io", + "https://console.cloud.google.com/cloudshell", + "https://support.google.com", + "^https://github\\.com/googleapis/nodejs-spanner/blob/[^/]+/samples/.*" + ], + "silent": true, + "concurrency": 5, + "retry": true, + "retryErrors": true, + "retryErrorsCount": 5, + "retryErrorsJitter": 3000 +} diff --git a/handwritten/spanner/observability-test/batch-transaction.ts b/handwritten/spanner/observability-test/batch-transaction.ts new file mode 100644 index 00000000000..47c124d3922 --- /dev/null +++ b/handwritten/spanner/observability-test/batch-transaction.ts @@ -0,0 +1,247 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable prefer-rest-params */ + +import {util} from '@google-cloud/common'; +import * as pfy from '@google-cloud/promisify'; +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +const { + AlwaysOnSampler, + NodeTracerProvider, + InMemorySpanExporter, +} = require('@opentelemetry/sdk-trace-node'); +// eslint-disable-next-line n/no-extraneous-require +const {SimpleSpanProcessor} = require('@opentelemetry/sdk-trace-base'); +import {Session, Spanner} from '../src'; +import * as bt from '../src/batch-transaction'; + +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'BatchTransaction') { + return; + } + assert.deepStrictEqual(options.exclude, ['identifier']); + }, +}); + +class FakeTimestamp { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const fakeCodec: any = { + encode: util.noop, + Timestamp: FakeTimestamp, + Int() {}, + Float() {}, + SpannerDate() {}, + convertProtoTimestampToDate() {}, +}; + +const SPANNER = { + routeToLeaderEnabled: true, +}; + +const INSTANCE = { + parent: SPANNER, +}; + +const DATABASE = { + formattedName_: 'database', + parent: INSTANCE, +}; + +class FakeTransaction { + calledWith_: IArguments; + session; + constructor(session) { + this.calledWith_ = arguments; + this.session = session; + } + static encodeKeySet(): object { + return {}; + } + static encodeParams(): object { + return {}; + } + + _getSpanner(): Spanner { + return SPANNER as Spanner; + } + + run() {} + read() {} +} + +describe('BatchTransaction', () => { + const sandbox = sinon.createSandbox(); + + // tslint:disable-next-line variable-name + let BatchTransaction: typeof bt.BatchTransaction; + let batchTransaction: bt.BatchTransaction; + + before(() => { + BatchTransaction = proxyquire('../src/batch-transaction.js', { + '@google-cloud/precise-date': {PreciseDate: FakeTimestamp}, + '@google-cloud/promisify': fakePfy, + './codec.js': {codec: fakeCodec}, + './transaction.js': {Snapshot: FakeTransaction}, + }).BatchTransaction; + }); + + const traceExporter = new InMemorySpanExporter(); + const sampler = new AlwaysOnSampler(); + + const provider = new NodeTracerProvider({ + sampler: sampler, + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + afterEach(() => { + traceExporter.reset(); + sandbox.restore(); + }); + + const REQUEST = sandbox.stub(); + const SESSION = { + parent: DATABASE, + formattedName_: 'abcdef', + request: REQUEST, + }; + const ID = '0xdeadbeef'; + + const PARTITIONS = [{partitionToken: 'a'}, {partitionToken: 'b'}]; + const RESPONSE = {partitions: PARTITIONS}; + + beforeEach(() => { + batchTransaction = new BatchTransaction(SESSION as {} as Session); + batchTransaction.session = SESSION as {} as Session; + batchTransaction.id = ID; + batchTransaction._observabilityOptions = {tracerProvider: provider}; + REQUEST.callsFake((_, callback) => callback(null, RESPONSE)); + }); + + const GAX_OPTS = {}; + + const QUERY = { + sql: 'SELECT * FROM Singers', + gaxOptions: GAX_OPTS, + params: {}, + types: {}, + }; + + it('createQueryPartitions', done => { + batchTransaction.createQueryPartitions(QUERY, err => { + assert.ifError(err); + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 2, 'Exactly 2 spans expected'); + + // Sort the spans by duration. + spans.sort((spanA, spanB) => { + spanA.duration < spanB.duration; + }); + + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + }); + + const expectedSpanNames = [ + 'CloudSpanner.BatchTransaction.createPartitions_', + 'CloudSpanner.BatchTransaction.createQueryPartitions', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that createPartitions_ is a child span of createQueryPartitions. + const spanCreatePartitions_ = spans[0]; + const spanCreateQueryPartitions = spans[1]; + assert.ok( + spanCreateQueryPartitions.spanContext().traceId, + 'Expected that createQueryPartitions has a defined traceId', + ); + assert.ok( + spanCreatePartitions_.spanContext().traceId, + 'Expected that createPartitions_ has a defined traceId', + ); + assert.deepStrictEqual( + spanCreatePartitions_.spanContext().traceId, + spanCreateQueryPartitions.spanContext().traceId, + 'Expected that both spans share a traceId', + ); + assert.ok( + spanCreateQueryPartitions.spanContext().spanId, + 'Expected that createQueryPartitions has a defined spanId', + ); + assert.ok( + spanCreatePartitions_.spanContext().spanId, + 'Expected that createPartitions_ has a defined spanId', + ); + assert.deepStrictEqual( + spanCreatePartitions_.parentSpanContext.spanId, + spanCreateQueryPartitions.spanContext().spanId, + 'Expected that createQueryPartitions is the parent to createPartitions_', + ); + done(); + }); + }); + + it('createReadPartitions', done => { + const REQUEST = sandbox.stub(); + const response = {}; + REQUEST.callsFake((_, callback) => callback(null, response)); + + batchTransaction.createReadPartitions(QUERY, err => { + assert.ifError(err); + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 2, 'Exactly 2 spans expected'); + + // Sort the spans by duration. + spans.sort((spanA, spanB) => { + spanA.duration < spanB.duration; + }); + + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + }); + const expectedSpanNames = [ + 'CloudSpanner.BatchTransaction.createPartitions_', + 'CloudSpanner.BatchTransaction.createReadPartitions', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + done(); + }); + }); +}); diff --git a/handwritten/spanner/observability-test/database.ts b/handwritten/spanner/observability-test/database.ts new file mode 100644 index 00000000000..d905ea086d5 --- /dev/null +++ b/handwritten/spanner/observability-test/database.ts @@ -0,0 +1,2212 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable prefer-rest-params */ + +import * as through from 'through2'; +import {EventEmitter} from 'events'; +import * as assert from 'assert'; +import * as extend from 'extend'; +import {google} from '../protos/protos'; +import { + BatchWriteOptions, + CommitCallback, + CommitOptions, + MutationSet, +} from '../src/transaction'; +import {util} from '@google-cloud/common'; +import {Transform} from 'stream'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +const {SpanStatusCode} = require('@opentelemetry/api'); +const { + AlwaysOnSampler, + NodeTracerProvider, + InMemorySpanExporter, +} = require('@opentelemetry/sdk-trace-node'); +// eslint-disable-next-line n/no-extraneous-require +const { + ReadableSpan, + SimpleSpanProcessor, +} = require('@opentelemetry/sdk-trace-base'); +import * as db from '../src/database'; +import {Instance, MutationGroup, Spanner} from '../src'; +import * as pfy from '@google-cloud/promisify'; +import {grpc} from 'google-gax'; +import {MockError} from '../test/mockserver/mockspanner'; +import {FakeSessionFactory} from '../test/database'; +import {RunTransactionOptions} from '../src/transaction-runner'; +const {generateWithAllSpansHaveDBName} = require('./helper'); + +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'Database') { + return; + } + assert.deepStrictEqual(options.exclude, [ + 'batchTransaction', + 'batchWriteAtLeastOnce', + 'getRestoreInfo', + 'getState', + 'getDatabaseDialect', + 'getOperations', + 'runTransaction', + 'runTransactionAsync', + 'table', + 'session', + ]); + }, +}); + +class FakeBatchTransaction { + calledWith_: IArguments; + id?: string; + readTimestamp?: {seconds: number; nanos: number}; + constructor() { + this.calledWith_ = arguments; + } +} + +class FakeGrpcServiceObject extends EventEmitter { + calledWith_: IArguments; + constructor() { + super(); + this.calledWith_ = arguments; + } +} + +function fakePartialResultStream(this: Function & {calledWith_: IArguments}) { + this.calledWith_ = arguments; + return this; +} + +class FakeSession { + calledWith_: IArguments; + formattedName_: any; + constructor() { + this.calledWith_ = arguments; + } + partitionedDml(): FakeTransaction { + return new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.PartitionedDml, + ); + } + snapshot(): FakeTransaction { + return new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + } +} + +class FakeSessionPool extends EventEmitter { + calledWith_: IArguments; + constructor() { + super(); + this.calledWith_ = arguments; + } + open() {} + getSession() {} + release() {} +} + +class FakeTable { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +class FakeTransaction extends EventEmitter { + calledWith_: IArguments; + _options!: google.spanner.v1.ITransactionOptions; + private _queuedMutations: google.spanner.v1.Mutation[]; + constructor(options) { + super(); + this._options = options; + this.calledWith_ = arguments; + this._queuedMutations = []; + } + begin() {} + end() {} + runStream(): Transform { + return through.obj(); + } + runUpdate() {} + setQueuedMutations(mutation) { + this._queuedMutations = mutation; + } + setReadWriteTransactionOptions(options: RunTransactionOptions) {} + commit( + options?: CommitOptions, + callback?: CommitCallback, + ): void | Promise { + if (callback) { + callback(null, {commitTimestamp: {seconds: 1, nanos: 0}}); + } + return Promise.resolve({commitTimestamp: {seconds: 1, nanos: 0}}); + } +} + +class FakeTransactionRunner { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + // eslint-disable-next-line @typescript-eslint/no-this-alias + } + async run(): Promise {} +} + +class FakeAsyncTransactionRunner { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } + async run(): Promise { + return {} as T; + } +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const fakeCodec: any = { + encode: util.noop, + Int() {}, + Float() {}, + SpannerDate() {}, +}; + +class FakeAbortError { + error; + constructor(err) { + this.error = err; + } +} + +const fakeRetry = fn => { + return fn(); +}; + +fakeRetry.AbortError = FakeAbortError; + +describe('Database', () => { + const sandbox = sinon.createSandbox(); + + // tslint:disable-next-line variable-name + let Database: typeof db.Database; + // tslint:disable-next-line variable-name + let DatabaseCached: typeof db.Database; + + const SPANNER = { + routeToLeaderEnabled: true, + } as {} as Spanner; + + const INSTANCE = { + request: util.noop, + requestStream: util.noop, + formattedName_: 'instance-name', + databases_: new Map(), + parent: SPANNER, + } as {} as Instance; + + const NAME = 'table-name'; + + const POOL_OPTIONS = {}; + + let database; + + before(() => { + Database = proxyquire('../src/database.js', { + './common-grpc/service-object': { + GrpcServiceObject: FakeGrpcServiceObject, + }, + '@google-cloud/promisify': fakePfy, + 'p-retry': fakeRetry, + './batch-transaction': {BatchTransaction: FakeBatchTransaction}, + './codec': {codec: fakeCodec}, + './partial-result-stream': {partialResultStream: fakePartialResultStream}, + './session-pool': {SessionPool: FakeSessionPool}, + './session-factory': {SessionFactory: FakeSessionFactory}, + './session': {Session: FakeSession}, + './table': {Table: FakeTable}, + './transaction-runner': { + TransactionRunner: FakeTransactionRunner, + AsyncTransactionRunner: FakeAsyncTransactionRunner, + }, + }).Database; + DatabaseCached = Object.assign({}, Database); + }); + + const withAllSpansHaveDBName = generateWithAllSpansHaveDBName( + INSTANCE.formattedName_ + '/databases/' + NAME, + ); + + beforeEach(() => { + fakeCodec.encode = util.noop; + extend(Database, DatabaseCached); + INSTANCE._observabilityOptions = { + tracerProvider: provider, + enableExtendedTracing: false, + }; + database = new Database(INSTANCE, NAME, POOL_OPTIONS); + database.parent = INSTANCE; + database.databaseRole = 'parent_role'; + const gaxOpts = {}; + const options: { + a: string; + gaxOptions?: {}; + } = {a: 'a', gaxOptions: gaxOpts}; + + const expectedReqOpts = extend({}, options, { + database: database.formattedName_, + }); + delete expectedReqOpts.gaxOptions; + }); + + const traceExporter = new InMemorySpanExporter(); + const sampler = new AlwaysOnSampler(); + + const provider = new NodeTracerProvider({ + sampler: sampler, + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + afterEach(() => { + sandbox.restore(); + traceExporter.forceFlush(); + traceExporter.reset(); + }); + + it('getSessions without error', done => { + const ARGS = [null, [], {}]; + database.request = (config, callback) => { + callback(...ARGS); + }; + + database.getSessions((err, sessions) => { + assert.ifError(err); + assert.ok(sessions); + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.getSessions']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span's status code is UNSET. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Expected an OK span status', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + + it('getSessions with error', done => { + const ARGS = [new Error('our error'), null, {}]; + database.request = (config, callback) => { + callback(...ARGS); + }; + + database.getSessions((err, sessions) => { + assert.ok(err); + assert.ok(!sessions); + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.getSessions']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'our error', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + + describe('batchCreateSessions', () => { + it('without error', done => { + const ARGS = [null, [{}]]; + database.request = (config, callback) => { + callback(...ARGS); + }; + + database.batchCreateSessions(10, (err, sessions) => { + assert.ifError(err); + assert.ok(sessions); + + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.batchCreateSessions']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span didn't encounter an error. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status code', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + + it('with error', done => { + const ARGS = [new Error('batchCreateSessions.error'), null]; + database.request = (config, callback) => { + callback(...ARGS); + }; + + database.batchCreateSessions(10, (err, sessions) => { + assert.ok(err); + assert.ok(!sessions); + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.batchCreateSessions']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'batchCreateSessions.error', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + }); + + describe('getSnapshot', () => { + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakeSnapshot: FakeTransaction; + + let beginSnapshotStub: sinon.SinonStub; + let getSessionStub: sinon.SinonStub; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakeSnapshot = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + + beginSnapshotStub = ( + sandbox.stub(fakeSnapshot, 'begin') as sinon.SinonStub + ).callsFake(callback => callback(null)); + + getSessionStub = ( + sandbox.stub(fakeSessionFactory, 'getSession') as sinon.SinonStub + ).callsFake(callback => callback(null, fakeSession)); + + sandbox.stub(fakeSession, 'snapshot').returns(fakeSnapshot); + + sandbox.stub(fakeSessionFactory, 'isMultiplexedEnabled').returns(false); + }); + + it('with error', done => { + const fakeError = new Error('our snapshot error'); + + getSessionStub.callsFake(callback => callback(fakeError, null)); + + database.getSnapshot(err => { + assert.strictEqual(err, fakeError); + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.getSnapshot']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'our snapshot error', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + + it('with retries on `begin` errors with `Session not found`', done => { + const fakeError = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError; + + const fakeSession2 = new FakeSession(); + const fakeSnapshot2 = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + (sandbox.stub(fakeSnapshot2, 'begin') as sinon.SinonStub).callsFake( + callback => callback(null), + ); + sandbox.stub(fakeSession2, 'snapshot').returns(fakeSnapshot2); + + getSessionStub + .onFirstCall() + .callsFake(callback => callback(null, fakeSession)) + .onSecondCall() + .callsFake(callback => callback(null, fakeSession2)); + beginSnapshotStub.callsFake(callback => callback(fakeError)); + + // The first session that was not found should be released back into the + // pool, so that the pool can remove it from its inventory. + const releaseStub = sandbox.stub(fakeSessionFactory, 'release'); + + database.getSnapshot(async (err, snapshot) => { + assert.ifError(err); + assert.strictEqual(snapshot, fakeSnapshot2); + // The first session that error should already have been released back + // to the pool. + assert.strictEqual(releaseStub.callCount, 1); + // Ending the valid snapshot will release its session back into the + // pool. + snapshot.emit('end'); + assert.strictEqual(releaseStub.callCount, 2); + + await provider.forceFlush(); + await traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.getSnapshot', + 'CloudSpanner.Database.getSnapshot', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the first span actually produced an error that was recorded. + const parentSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + parentSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'Session not found', + parentSpan.status.message.toString(), + 'Mismatched span status message', + ); + + // Ensure that the second span is a child of the first span. + const secondRetrySpan = spans[1]; + assert.ok( + parentSpan.spanContext().traceId, + 'Expected that the initial parent span has a defined traceId', + ); + assert.ok( + secondRetrySpan.spanContext().traceId, + 'Expected that the second retry span has a defined traceId', + ); + assert.deepStrictEqual( + parentSpan.spanContext().traceId, + secondRetrySpan.spanContext().traceId, + 'Expected that both spans share a traceId', + ); + assert.ok( + parentSpan.spanContext().spanId, + 'Expected that the initial parent span has a defined spanId', + ); + assert.ok( + secondRetrySpan.spanContext().spanId, + 'Expected that the second retry span has a defined spanId', + ); + assert.deepStrictEqual( + secondRetrySpan.parentSpanContext.spanId, + parentSpan.spanContext().spanId, + 'Expected that secondRetrySpan is the child to parentSpan', + ); + + const expectedEventNames = ['No session available']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + }); + + describe('createBatchTransaction', () => { + const SESSION = {}; + const RESPONSE = {a: 'b'}; + + beforeEach(() => { + database.sessionFactory_ = { + getSession(callback) { + callback(null, SESSION); + }, + }; + }); + + it('with session error', done => { + const error = new Error('with session error'); + + database.sessionFactory_ = { + getSession(callback) { + callback(error); + }, + }; + + database.createBatchTransaction((err, transaction, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(transaction, null); + assert.strictEqual(resp, undefined); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createBatchTransaction', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'with session error', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + + it('with no error', done => { + const opts = {a: 'b'}; + + const fakeTransaction = { + begin(callback) { + callback(null, RESPONSE); + }, + once() {}, + end() {}, + }; + + database.batchTransaction = (identifier, options) => { + assert.deepStrictEqual(identifier, {session: SESSION}); + assert.strictEqual(options, opts); + return fakeTransaction; + }; + + database.createBatchTransaction(opts, async (err, transaction, resp) => { + assert.strictEqual(err, null); + assert.strictEqual(transaction, fakeTransaction); + assert.strictEqual(resp, RESPONSE); + transaction!.end(); + + await provider.forceFlush(); + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createBatchTransaction', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + `No span status message expected\n\tGot: undefined\n\tWant: ${firstSpan.status.message}`, + ); + + const expectedEventNames = ['Using Session']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + + it('with begin transaction error', done => { + const error = new Error('our createBatchTransaction error'); + + const fakeTransaction = { + begin(callback) { + callback(error, RESPONSE); + }, + once() {}, + end() {}, + }; + + database.batchTransaction = () => { + return fakeTransaction; + }; + + database.createBatchTransaction((err, transaction, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(transaction, null); + assert.strictEqual(resp, RESPONSE); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createBatchTransaction', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'our createBatchTransaction error', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + }); + + describe('getTransaction', () => { + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakeTransaction: FakeTransaction; + + let getSessionStub: sinon.SinonStub; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakeTransaction = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadWrite, + ); + + getSessionStub = ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForReadWrite', + ) as sinon.SinonStub + ).callsFake(callback => { + callback(null, fakeSession, fakeTransaction); + }); + }); + + it('with pool errors', done => { + const fakeError = new Error('pool error'); + + getSessionStub.callsFake(callback => callback(fakeError)); + + database.getTransaction( + {requestOptions: {transactionTag: 'transaction-tag'}}, + async err => { + assert.strictEqual(err, fakeError); + + await provider.forceFlush(); + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + const expectedSpanNames = ['CloudSpanner.Database.getTransaction']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // In the event of a sessionPool error, we should not have events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `event names mismatch:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'pool error', + firstSpan.status.message, + 'Mismatched span status message', + ); + assert.strictEqual( + spans[0].attributes['transaction.tag'], + 'transaction-tag', + ); + done(); + }, + ); + }); + + it('with no errors', done => { + database.getTransaction((err, transaction) => { + assert.ifError(err); + assert.strictEqual(transaction, fakeTransaction); + transaction!.end(); + + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.getTransaction']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that we have specific events. + const expectedEventNames = ['Using Session']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `event names mismatch:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + `Unexpected span status code: ${firstSpan.status.code}`, + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + `Unexpected status message: ${firstSpan.status.message}`, + ); + + done(); + }); + }); + }); + + describe('writeAtLeastOnce', () => { + const mutations = new MutationSet(); + mutations.insert('MyTable', { + Key: 'k3', + Thing: 'xyz', + }); + + const SESSION = new FakeSession(); + const RESPONSE = {commitTimestamp: {seconds: 1, nanos: 0}}; + const TRANSACTION = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadWrite, + ); + + let sessionFactory: FakeSessionFactory; + + beforeEach(() => { + sessionFactory = database.sessionFactory_; + (sandbox.stub(sessionFactory, 'getSession') as sinon.SinonStub).callsFake( + callback => { + callback(null, SESSION, TRANSACTION); + }, + ); + sandbox.stub(sessionFactory, 'isMultiplexedEnabled').returns(false); + }); + + it('should return any errors getting a session', done => { + const fakeErr = new Error('getting session error'); + + (sessionFactory.getSession as sinon.SinonStub).callsFake(callback => + callback(fakeErr, null, null), + ); + + database.writeAtLeastOnce(mutations, err => { + assert.deepStrictEqual(err, fakeErr); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.writeAtLeastOnce']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'getting session error', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + + it('with empty mutation should return successful CommitResponse', done => { + const fakeMutations = new MutationSet(); + try { + database.writeAtLeastOnce(fakeMutations, (err, response) => { + assert.ifError(err); + assert.deepStrictEqual( + response.commitTimestamp, + RESPONSE.commitTimestamp, + ); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.writeAtLeastOnce']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status code', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + + const expectedEventNames = ['Using Session']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + } catch (error) { + assert(error instanceof Error); + } + }); + + it('with error on null mutation should catch thrown error', done => { + try { + database.writeAtLeastOnce(null, () => {}); + } catch (err) { + // Performing a substring search on the error because + // depending on the version of Node.js, the error might be either of: + // * Cannot read properties of null (reading 'proto') + // * Cannot read property 'proto' of null + (err as grpc.ServiceError).message.includes('Cannot read propert'); + (err as grpc.ServiceError).message.includes('of null'); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.writeAtLeastOnce']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + + const errorMessage = firstSpan.status.message; + assert.ok( + errorMessage.includes( + "Cannot read properties of null (reading 'proto')", + ) || errorMessage.includes("Cannot read property 'proto' of null"), + ); + + // We expect an exception to have been caught as well as a Session event. + const expectedEventNames = ['Using Session', 'exception']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + } + }); + }); + + describe('batchWriteAtLeastOnce', () => { + const mutationGroup1 = new MutationGroup(); + mutationGroup1.insert('MyTable', { + Key: 'ks1', + Thing: 'abc', + }); + const mutationGroup2 = new MutationGroup(); + mutationGroup2.insert('MyTable', { + Key: 'ks2', + Thing: 'xyz', + }); + + const mutationGroups = [mutationGroup1, mutationGroup2]; + + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakeDataStream: Transform; + let getSessionStub: sinon.SinonStub; + + const options = { + requestOptions: { + transactionTag: 'batch-write-tag', + }, + excludeTxnFromChangeStream: true, + gaxOptions: {autoPaginate: false}, + } as BatchWriteOptions; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakeDataStream = through.obj(); + + getSessionStub = ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForReadWrite', + ) as sinon.SinonStub + ).callsFake(callback => callback(null, fakeSession)); + + sandbox.stub(database, 'requestStream').returns(fakeDataStream); + }); + + it('on retry with "Session not found" error', done => { + const sessionNotFoundError = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as grpc.ServiceError; + let retryCount = 0; + + database + .batchWriteAtLeastOnce(mutationGroups, options) + .on('data', () => {}) + .on('error', err => { + assert.fail(err); + }) + .on('end', () => { + assert.strictEqual(retryCount, 1); + + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.batchWriteAtLeastOnce', + 'CloudSpanner.Database.batchWriteAtLeastOnce', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + + assert.deepStrictEqual( + firstSpan.status.message, + sessionNotFoundError.message, + ); + + // The last span should not have an error status. + const lastSpan = spans[spans.length - 1]; + assert.strictEqual( + SpanStatusCode.UNSET, + lastSpan.status.code, + 'Unexpected span status', + ); + + assert.deepStrictEqual(lastSpan.status.message, undefined); + + const expectedEventNames = [ + 'Using Session', + 'No session available', + 'Using Session', + ]; + assert.deepStrictEqual(actualEventNames, expectedEventNames); + assert.strictEqual( + spans[0].attributes['transaction.tag'], + 'batch-write-tag', + ); + done(); + }); + + fakeDataStream.emit('error', sessionNotFoundError); + retryCount++; + }); + + it('on getSession errors', done => { + const fakeError = new Error('err'); + + getSessionStub.callsFake(callback => callback(fakeError)); + database + .batchWriteAtLeastOnce(mutationGroups, options) + .on('error', err => { + assert.strictEqual(err, fakeError); + + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.batchWriteAtLeastOnce', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + + assert.deepStrictEqual(firstSpan.status.message, fakeError.message); + + const expectedEventNames = []; + assert.deepStrictEqual(expectedEventNames, actualEventNames); + + done(); + }); + }); + + it('with no errors', done => { + getSessionStub.callsFake(callback => callback(null, {})); + database + .batchWriteAtLeastOnce(mutationGroups, options) + .on('data', () => {}) + .on('error', assert.ifError) + .on('end', () => { + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.batchWriteAtLeastOnce', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status code', + ); + + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + + const expectedEventNames = ['Using Session']; + assert.deepStrictEqual(actualEventNames, expectedEventNames); + + done(); + }); + + fakeDataStream.emit('data', 'response'); + fakeDataStream.end('end'); + }); + }); + + describe('runTransaction', () => { + const SESSION = new FakeSession(); + const TRANSACTION = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadWrite, + ); + + let fakeSessionFactory: FakeSessionFactory; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + + ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForReadWrite', + ) as sinon.SinonStub + ).callsFake(callback => { + callback(null, SESSION, TRANSACTION); + }); + }); + + it('with error getting session', done => { + const fakeErr = new Error('getting a session'); + + (fakeSessionFactory.getSessionForReadWrite as sinon.SinonStub).callsFake( + callback => callback(fakeErr), + ); + + database.runTransaction( + {requestOptions: {transactionTag: 'transaction-tag'}}, + err => { + assert.strictEqual(err, fakeErr); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.runTransaction']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'getting a session', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + assert.strictEqual( + spans[0].attributes['transaction.tag'], + 'transaction-tag', + ); + done(); + }, + ); + }); + + it('with other errors when running the transaction', done => { + const fakeError = new Error('internal rejects err'); + + sandbox.stub(FakeTransactionRunner.prototype, 'run').rejects(fakeError); + + database.runTransaction(err => { + assert.strictEqual(err, fakeError); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.runTransaction']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'internal rejects err', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + }); + + describe('runTransactionAsync', () => { + const SESSION = new FakeSession(); + const TRANSACTION = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadWrite, + ); + + let fakeSessionFactory: FakeSessionFactory; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForReadWrite', + ) as sinon.SinonStub + ).callsFake(callback => { + callback(null, SESSION, TRANSACTION); + }); + }); + + it('with no error', async () => { + const fakeValue = {}; + + sandbox + .stub(FakeAsyncTransactionRunner.prototype, 'run') + .resolves(fakeValue); + + const value = await database.runTransactionAsync( + {requestOptions: {transactionTag: 'transaction-tag'}}, + async txn => { + const result = await txn.run('SELECT 1'); + await txn.commit(); + return result; + }, + ); + + assert.strictEqual(value, fakeValue); + + await provider.forceFlush(); + await traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.runTransactionAsync']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + + const expectedEventNames = ['Using Session']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + assert.strictEqual( + spans[0].attributes['transaction.tag'], + 'transaction-tag', + ); + }); + + it('with error', async () => { + const ourException = new Error('our thrown error'); + sandbox + .stub(FakeAsyncTransactionRunner.prototype, 'run') + .throws(ourException); + + await assert.rejects(async () => { + await database.runTransactionAsync(async txn => { + const result = await txn.run('SELECT 1'); + await txn.commit(); + return result; + }); + }, ourException); + + await provider.forceFlush(); + await traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.runTransactionAsync']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + firstSpan.status.code, + SpanStatusCode.ERROR, + 'Unexpected span status', + ); + assert.strictEqual( + firstSpan.status.message, + ourException.message, + 'Unexpected span status message', + ); + + const expectedEventNames = ['Using Session', 'exception']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + }); + }); + + describe('runStream', () => { + const QUERY = { + sql: 'SELECT * FROM table', + a: 'b', + c: 'd', + requestOptions: {requestTag: 'request-tag'}, + }; + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakeSession2: FakeSession; + let fakeSnapshot: FakeTransaction; + let fakeSnapshot2: FakeTransaction; + let fakeStream: Transform; + let fakeStream2: Transform; + + let getSessionStub: sinon.SinonStub; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakeSession2 = new FakeSession(); + fakeSnapshot = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + fakeSnapshot2 = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + fakeStream = through.obj(); + fakeStream2 = through.obj(); + + getSessionStub = ( + sandbox.stub(fakeSessionFactory, 'getSession') as sinon.SinonStub + ) + .onFirstCall() + .callsFake(callback => callback(null, fakeSession)) + .onSecondCall() + .callsFake(callback => callback(null, fakeSession2)); + + sandbox.stub(fakeSession, 'snapshot').returns(fakeSnapshot); + + sandbox.stub(fakeSession2, 'snapshot').returns(fakeSnapshot2); + + sandbox.stub(fakeSnapshot, 'runStream').returns(fakeStream); + + sandbox.stub(fakeSnapshot2, 'runStream').returns(fakeStream2); + + sandbox.stub(fakeSessionFactory, 'isMultiplexedEnabled').returns(false); + }); + + it('with error on `getSession`', done => { + const fakeError = new Error('getSession error'); + + getSessionStub.onFirstCall().callsFake(callback => callback(fakeError)); + + database.runStream(QUERY).on('error', err => { + assert.strictEqual(err, fakeError); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.runStream']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'getSession error', + firstSpan.status.message, + 'Mismatched span status message', + ); + + // We don't expect events. + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + assert.strictEqual(spans[0].attributes['request.tag'], 'request-tag'); + done(); + }); + }); + + it('propagation on stream/transaction errors', done => { + const fakeError = new Error('propagation err'); + const endStub = sandbox.stub(fakeSnapshot, 'end'); + + database.runStream(QUERY).on('error', err => { + assert.strictEqual(err, fakeError); + assert.strictEqual(endStub.callCount, 1); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'Exactly 1 span expected'); + withAllSpansHaveDBName(spans); + + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.Database.runStream']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Expected an ERROR span status', + ); + assert.strictEqual( + 'propagation err', + firstSpan.status.message, + 'Mismatched span status message', + ); + + const expectedEventNames = ['Using Session']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + + fakeStream.destroy(fakeError); + }); + + it('retries with "Session not found" error', done => { + const sessionNotFoundError = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as grpc.ServiceError; + const endStub = sandbox.stub(fakeSnapshot, 'end'); + const endStub2 = sandbox.stub(fakeSnapshot2, 'end'); + let rows = 0; + + database + .runStream(QUERY) + .on('data', () => rows++) + .on('error', err => { + assert.fail(err); + }) + .on('end', async () => { + assert.strictEqual(endStub.callCount, 1); + assert.strictEqual(endStub2.callCount, 1); + assert.strictEqual(rows, 1); + + await provider.forceFlush(); + await traceExporter.forceFlush(); + + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 2, 'Exactly 2 spans expected'); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.runStream', + 'CloudSpanner.Database.runStream', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the span actually produced an error that was recorded. + const lastSpan = spans[0]; + assert.deepStrictEqual( + SpanStatusCode.ERROR, + lastSpan.status.code, + 'Expected an ERROR span status', + ); + assert.deepStrictEqual( + 'Session not found', + lastSpan.status.message, + 'Mismatched span status message', + ); + + // Ensure that the final span that got retries did not error. + const firstSpan = spans[1]; + assert.deepStrictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status code', + ); + assert.deepStrictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + + const expectedEventNames = [ + 'Using Session', + 'No session available', + 'Using Session', + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + + fakeStream.emit('error', sessionNotFoundError); + fakeStream2.push('row1'); + fakeStream2.push(null); + }); + }); + + describe('runPartitionedUpdate', () => { + const QUERY = { + sql: 'INSERT INTO `MyTable` (Key, Thing) VALUES(@key, @thing)', + params: { + key: 'k999', + thing: 'abc', + }, + requestOptions: {requestTag: 'request-tag'}, + }; + + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakePartitionedDml = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.PartitionedDml, + ); + + let getSessionStub; + let beginStub; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakePartitionedDml = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.PartitionedDml, + ); + + getSessionStub = ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForPartitionedOps', + ) as sinon.SinonStub + ).callsFake(callback => { + callback(null, fakeSession); + }); + + sandbox.stub(fakeSession, 'partitionedDml').returns(fakePartitionedDml); + + beginStub = ( + sandbox.stub(fakePartitionedDml, 'begin') as sinon.SinonStub + ).callsFake(callback => callback(null)); + + ( + sandbox.stub(fakePartitionedDml, 'runUpdate') as sinon.SinonStub + ).callsFake((_, callback) => callback(null)); + }); + + interface traceExportResults { + spanNames: string[]; + spans: (typeof ReadableSpan)[]; + eventNames: string[]; + } + + async function getTraceExportResults(): Promise { + await provider.forceFlush(); + await traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + return Promise.resolve({ + spanNames: actualSpanNames, + spans: spans, + eventNames: actualEventNames, + }); + } + + it('with pool errors', done => { + const fakeError = new Error('err'); + + getSessionStub.callsFake(callback => callback(fakeError)); + database.runPartitionedUpdate(QUERY, async (err, rowCount) => { + assert.strictEqual(err, fakeError); + assert.strictEqual(rowCount, 0); + + const exportResults = await getTraceExportResults(); + const actualSpanNames = exportResults.spanNames; + const spans = exportResults.spans; + const actualEventNames = exportResults.eventNames; + + const expectedSpanNames = [ + 'CloudSpanner.Database.runPartitionedUpdate', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the first span actually produced an error that was recorded. + const parentSpan = spans[0]; + assert.deepStrictEqual( + SpanStatusCode.ERROR, + parentSpan.status.code, + 'Expected an ERROR span status', + ); + assert.deepStrictEqual( + fakeError.message, + parentSpan.status.message.toString(), + 'Mismatched span status message', + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + assert.strictEqual(spans[0].attributes['request.tag'], 'request-tag'); + done(); + }); + }); + + it('with begin errors', done => { + const fakeError = new Error('err'); + + beginStub.callsFake(callback => callback(fakeError)); + + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(fakeSession); + + database.runPartitionedUpdate(QUERY, async (err, rowCount) => { + assert.strictEqual(err, fakeError); + assert.strictEqual(rowCount, 0); + assert.strictEqual(releaseStub.callCount, 1); + + const exportResults = await getTraceExportResults(); + const actualSpanNames = exportResults.spanNames; + const spans = exportResults.spans; + const actualEventNames = exportResults.eventNames; + + const expectedSpanNames = [ + 'CloudSpanner.Database.runPartitionedUpdate', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the first span actually produced an error that was recorded. + const parentSpan = spans[0]; + assert.deepStrictEqual( + SpanStatusCode.ERROR, + parentSpan.status.code, + 'Expected an ERROR span status', + ); + assert.deepStrictEqual( + fakeError.message, + parentSpan.status.message.toString(), + 'Mismatched span status message', + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + done(); + }); + }); + + it('session released on transaction end', done => { + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(fakeSession); + + database.runPartitionedUpdate(QUERY, async () => { + const exportResults = await getTraceExportResults(); + const actualSpanNames = exportResults.spanNames; + const spans = exportResults.spans; + const actualEventNames = exportResults.eventNames; + + const expectedSpanNames = [ + 'CloudSpanner.Database.runPartitionedUpdate', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Ensure that the first span actually produced an error that was recorded. + const parentSpan = spans[0]; + assert.deepStrictEqual( + SpanStatusCode.UNSET, + parentSpan.status.code, + 'Unexpected span status', + ); + assert.deepStrictEqual( + undefined, + parentSpan.status.message, + 'Mismatched span status message', + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + done(); + }); + + fakePartitionedDml.emit('end'); + assert.strictEqual(releaseStub.callCount, 1); + }); + }); +}); diff --git a/handwritten/spanner/observability-test/helper.ts b/handwritten/spanner/observability-test/helper.ts new file mode 100644 index 00000000000..6ce1ba8b6a4 --- /dev/null +++ b/handwritten/spanner/observability-test/helper.ts @@ -0,0 +1,95 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 {ContextManager, context} from '@opentelemetry/api'; +import * as assert from 'assert'; +const {ReadableSpan} = require('@opentelemetry/sdk-trace-base'); +import {SEMATTRS_DB_NAME} from '@opentelemetry/semantic-conventions'; + +export const createSessionEvents = [ + 'Requesting a multiplexed session', + 'Created a multiplexed session', +]; + +export const batchCreateSessionsEvents = [ + 'Requesting 25 sessions', + 'Creating 25 sessions', + 'Requested for 25 sessions returned 25', +]; + +export const waitingSessionsEvents = [ + 'Waiting for a multiplexed session to become available', + 'Acquired multiplexed session', + 'Using Session', +]; + +export const cacheSessionEvents = ['Cache hit: has usable multiplexed session']; + +/** + * This utility exists as a test helper because mocha has builtin "context" + * and referring to context causes type/value collision errors. + */ +export function setGlobalContextManager(manager: ContextManager) { + context.setGlobalContextManager(manager); +} + +/** + * This utility exists as a test helper because mocha has builtin "context" + * and referring to context causes type/value collision errors. + */ +export function disableContextAndManager(manager: ContextManager) { + manager.disable(); + context.disable(); +} + +export function generateWithAllSpansHaveDBName(dbName: String): Function { + return function (spans: (typeof ReadableSpan)[]) { + spans.forEach(span => { + assert.deepStrictEqual( + span.attributes[SEMATTRS_DB_NAME], + dbName, + `Span ${span.name} has mismatched DB_NAME`, + ); + }); + }; +} + +export async function verifySpansAndEvents( + traceExporter, + expectedSpans, + expectedEvents, +) { + await traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + const actualEventNames: string[] = []; + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + assert.deepStrictEqual( + actualSpanNames, + expectedSpans, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpans}`, + ); + assert.deepStrictEqual( + actualEventNames, + expectedEvents, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEvents}`, + ); +} diff --git a/handwritten/spanner/observability-test/observability.ts b/handwritten/spanner/observability-test/observability.ts new file mode 100644 index 00000000000..99e90bb0662 --- /dev/null +++ b/handwritten/spanner/observability-test/observability.ts @@ -0,0 +1,476 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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. + */ + +const assert = require('assert'); +const { + AlwaysOffSampler, + AlwaysOnSampler, + NodeTracerProvider, + InMemorySpanExporter, +} = require('@opentelemetry/sdk-trace-node'); +const {SpanStatusCode, TracerProvider} = require('@opentelemetry/api'); +// eslint-disable-next-line n/no-extraneous-require +const {SimpleSpanProcessor} = require('@opentelemetry/sdk-trace-base'); +const { + TRACER_NAME, + TRACER_VERSION, + SPAN_NAMESPACE_PREFIX, + getActiveOrNoopSpan, + setSpanError, + setSpanErrorAndException, + startTrace, +} = require('../src/instrument'); +const { + ATTR_OTEL_SCOPE_NAME, + ATTR_OTEL_SCOPE_VERSION, + SEMATTRS_DB_NAME, + SEMATTRS_DB_SQL_TABLE, + SEMATTRS_DB_STATEMENT, + SEMATTRS_DB_SYSTEM, + SEMATTRS_EXCEPTION_MESSAGE, +} = require('@opentelemetry/semantic-conventions'); + +const {disableContextAndManager, setGlobalContextManager} = require('./helper'); + +const { + AsyncHooksContextManager, +} = require('@opentelemetry/context-async-hooks'); + +describe('startTrace', () => { + const globalExporter = new InMemorySpanExporter(); + const sampler = new AlwaysOnSampler(); + + const globalProvider = new NodeTracerProvider({ + sampler: sampler, + exporter: globalExporter, + spanProcessors: [new SimpleSpanProcessor(globalExporter)], + }); + globalProvider.register(); + + const contextManager = new AsyncHooksContextManager(); + setGlobalContextManager(contextManager); + + afterEach(() => { + globalExporter.forceFlush(); + }); + + after(async () => { + globalExporter.forceFlush(); + await globalProvider.shutdown(); + disableContextAndManager(contextManager); + }); + + it('with TracerProvider in global configuration', () => { + startTrace('mySpan', {}, span => { + span.end(); + + assert.equal( + span.name, + SPAN_NAMESPACE_PREFIX + '.mySpan', + 'name mismatch', + ); + }); + }); + + it('with TracerProvider in options, skips using global TracerProvider', () => { + const overridingExporter = new InMemorySpanExporter(); + const overridingProvider = new NodeTracerProvider({ + sampler: sampler, + exporter: overridingExporter, + spanProcessors: [new SimpleSpanProcessor(overridingExporter)], + }); + + startTrace( + 'aSpan', + {opts: {tracerProvider: overridingProvider}}, + async span => { + await new Promise(resolve => setTimeout(resolve, 400)); + span.end(); + + const gotSpansFromGlobal = globalExporter.getFinishedSpans(); + assert.strictEqual( + gotSpansFromGlobal.length, + 0, + 'Expected no spans from the global tracerProvider and exporter but got ${gotSpansFromGlobal.length}', + ); + + const gotSpansFromCurrent = overridingExporter.getFinishedSpans(); + assert.strictEqual( + gotSpansFromCurrent.length, + 1, + 'Expected exactly 1 span but got ${gotSpansFromCurrent.length}', + ); + + overridingExporter.forceFlush(); + await overridingProvider.shutdown(); + }, + ); + }); + + it('sanity check: TRACER_NAME, TRACER_VERSION', () => { + assert.equal(!TRACER_NAME, false, 'TRACER_NAME must be set'); + assert.equal(!TRACER_VERSION, false, 'TRACER_VERSION must be set'); + }); + + it('with semantic attributes', () => { + const opts = { + tableName: 'table', + dbName: 'projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID', + }; + startTrace('aSpan', opts, span => { + assert.equal( + span.attributes[ATTR_OTEL_SCOPE_NAME], + TRACER_NAME, + 'Missing OTEL_SCOPE_NAME attribute', + ); + + assert.equal( + span.attributes[ATTR_OTEL_SCOPE_VERSION], + TRACER_VERSION, + 'Missing OTEL_SCOPE_VERSION attribute', + ); + + assert.equal( + span.attributes['gcp.client.service'], + 'spanner', + 'Missing gcp.client.service attribute', + ); + + assert.equal( + span.attributes['gcp.client.version'], + TRACER_VERSION, + 'Missing gcp.client.version attribute', + ); + + assert.equal( + span.attributes['gcp.client.repo'], + 'googleapis/nodejs-spanner', + 'Missing gcp.client.repo attribute', + ); + + assert.equal( + span.attributes['gcp.resource.name'], + '//spanner.googleapis.com/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID', + 'Missing gcp.resource.name attribute', + ); + + assert.equal( + span.attributes[SEMATTRS_DB_SQL_TABLE], + 'table', + 'Missing DB_SQL_TABLE attribute', + ); + + assert.equal( + span.attributes[SEMATTRS_DB_NAME], + 'projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID', + 'Missing DB_NAME attribute', + ); + }); + }); + + it('with enableExtendedTracing=true, no sql value set', () => { + const opts = {opts: {enableExtendedTracing: true}}; + startTrace('aSpan', opts, span => { + assert.equal( + span.attributes[SEMATTRS_DB_STATEMENT], + undefined, + 'Unexpected DB_STATEMENT attribute', + ); + }); + }); + + it('with enableExtendedTracing=true, sql string value set', () => { + const opts = { + opts: {enableExtendedTracing: true}, + sql: 'SELECT CURRENT_TIMESTAMP()', + }; + + startTrace('aSpan', opts, span => { + assert.equal( + span.attributes[SEMATTRS_DB_STATEMENT], + 'SELECT CURRENT_TIMESTAMP()', + 'Mismatched DB_STATEMENT attribute', + ); + }); + }); + + it('with enableExtendedTracing=false, sql string value set', () => { + const opts = { + opts: {enableExtendedTracing: false}, + sql: 'SELECt CURRENT_TIMESTAMP()', + }; + + startTrace('aSpan', opts, span => { + assert.equal( + span.attributes[SEMATTRS_DB_STATEMENT], + undefined, + 'Mismatched DB_STATEMENT attribute', + ); + }); + }); + + it('with enableExtendedTracing=true, sql ExecuteSqlRequest value set', () => { + const req = {sql: 'SELECT 1=1'}; + const opts = { + opts: {enableExtendedTracing: true}, + sql: req, + }; + + startTrace('aSpan', opts, span => { + assert.equal( + span.attributes[SEMATTRS_DB_STATEMENT], + 'SELECT 1=1', + 'Mismatched DB_STATEMENT attribute', + ); + }); + }); + + it('with enableExtendedTracing=false, sql ExecuteSqlRequest value set', () => { + const req = {sql: 'SELECT 1=1'}; + const opts = { + opts: {enableExtendedTracing: true}, + sql: req, + }; + + startTrace('aSpan', opts, span => { + assert.equal( + span.attributes[SEMATTRS_DB_STATEMENT], + req.sql, + 'Mismatched DB_STATEMENT attribute', + ); + }); + }); + + it('alwaysOffSampler used, no spans exported', () => { + const overridingExporter = new InMemorySpanExporter(); + const overridingProvider = new NodeTracerProvider({ + sampler: new AlwaysOffSampler(), + exporter: overridingExporter, + spanProcessors: [new SimpleSpanProcessor(overridingExporter)], + }); + overridingProvider.register(); + + startTrace( + 'aSpan', + {opts: {tracerProvider: overridingProvider}}, + async span => { + await new Promise(resolve => setTimeout(resolve, 400)); + span.end(); + + const gotSpansFromGlobal = globalExporter.getFinishedSpans(); + assert.strictEqual( + gotSpansFromGlobal.length, + 0, + 'Expected no spans but got ${gotSpansFromGlobal.length}', + ); + + const gotSpansFromCurrent = overridingExporter.getFinishedSpans(); + assert.strictEqual( + gotSpansFromCurrent.length, + 0, + 'Expected no spans but got ${gotSpansFromCurrent.length}', + ); + + overridingExporter.forceFlush(); + await overridingProvider.shutdown(); + }, + ); + }); +}); + +describe('getActiveOrNoopSpan', () => { + let globalProvider: typeof TracerProvider; + let exporter: typeof InMemorySpanExporter; + + before(() => { + exporter = new InMemorySpanExporter(); + globalProvider = new NodeTracerProvider({ + sampler: new AlwaysOffSampler(), + exporter: exporter, + spanProcessors: [new SimpleSpanProcessor(exporter)], + }); + globalProvider.register(); + }); + + beforeEach(() => { + exporter.forceFlush(); + }); + + after(async () => { + await globalProvider.shutdown(); + }); + + it('with no value should return a noopSpan and nothing exported', () => { + const span = getActiveOrNoopSpan(); + assert.strictEqual(!span, false, 'the span MUST not be null regardless'); + span.updateName('aSpan should not crash'); + span.setStatus({message: 'done here'}); + }); + + it('with a started span should return the currently active one', () => { + startTrace('aSpan', {}, span => { + const activeSpan = getActiveOrNoopSpan(); + assert.strictEqual( + span.name, + SPAN_NAMESPACE_PREFIX + '.aSpan', + 'names must match', + ); + assert.strictEqual( + span.name, + activeSpan.name, + `names must match between activeSpan or current one\n\tGot: ${span.name}\n\tWant: ${activeSpan.name}`, + ); + assert.strictEqual( + span.startTime, + activeSpan.startTime, + 'startTimes must match', + ); + assert.ok( + span.duration, + undefined, + 'the unended span must have an undefined duration', + ); + assert.ok( + activeSpan.duration, + undefined, + 'the unended span must have an undefined duration, got ${activeSpan.duration}', + ); + assert.strictEqual( + span.duration, + activeSpan.duration, + 'durations must match', + ); + span.end(); + }); + }); +}); + +describe('setError', () => { + const exporter = new InMemorySpanExporter(); + const provider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: exporter, + spanProcessors: [new SimpleSpanProcessor(exporter)], + }); + provider.register(); + + const contextManager = new AsyncHooksContextManager(); + setGlobalContextManager(contextManager); + + afterEach(() => { + exporter.forceFlush(); + }); + + after(async () => { + exporter.forceFlush(); + await provider.shutdown(); + disableContextAndManager(contextManager); + }); + + it('passing in null error or null span should have no effect', () => { + startTrace('aSpan', {opts: {tracerProvider: provider}}, span => { + const status1 = span.status; + let res = setSpanError(span, null); + assert.strictEqual(res, false, 'nothing was set'); + const status2 = span.status; + assert.strictEqual( + status1, + status2, + 'setting null error should have no effect', + ); + + res = setSpanError(null, null); + assert.strictEqual(res, false, 'nothing was set'); + }); + }); + + it('a non-empty string should set the message', () => { + startTrace('aSpan', {opts: {tracerProvider: provider}}, span => { + const res = setSpanError(span, 'this one'); + assert.strictEqual(res, true, 'value was set'); + span.end(); + + const spans = exporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'exactly 1 span must be exported'); + + const expSpan = spans[0]; + const status2 = expSpan.status; + assert.strictEqual(status2.message, 'this one'); + assert.strictEqual(status2.code, SpanStatusCode.ERROR); + }); + }); +}); + +describe('setErrorAndException', () => { + const exporter = new InMemorySpanExporter(); + const provider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: exporter, + spanProcessors: [new SimpleSpanProcessor(exporter)], + }); + provider.register(); + + const contextManager = new AsyncHooksContextManager(); + setGlobalContextManager(contextManager); + + afterEach(() => { + exporter.forceFlush(); + }); + + after(async () => { + await provider.shutdown(); + disableContextAndManager(contextManager); + }); + + it('passing in null error or null span should have no effect', () => { + startTrace('aSpan', {opts: {tracerProvider: provider}}, span => { + const status1 = span.status; + let res = setSpanErrorAndException(span, null); + assert.strictEqual(res, false, 'nothing was set'); + const status2 = span.status; + assert.strictEqual( + status1, + status2, + 'setting null error should have no effect', + ); + + res = setSpanErrorAndException(null, null); + assert.strictEqual(res, false, 'nothing was set'); + }); + }); + + it('a non-empty string should set the message', () => { + startTrace('aSpan', {opts: {tracerProvider: provider}}, span => { + const res = setSpanErrorAndException(span, 'this one'); + assert.strictEqual(res, true, 'value was set'); + span.end(); + + const spans = exporter.getFinishedSpans(); + assert.strictEqual(spans.length, 1, 'exactly 1 span must be exported'); + + const expSpan = spans[0]; + const status2 = expSpan.status; + assert.strictEqual(status2.message, 'this one'); + assert.strictEqual(status2.code, SpanStatusCode.ERROR); + + assert.strictEqual( + expSpan.events[0].attributes[SEMATTRS_EXCEPTION_MESSAGE], + 'this one', + 'the exception must have been recorded', + ); + }); + }); +}); diff --git a/handwritten/spanner/observability-test/session-pool.ts b/handwritten/spanner/observability-test/session-pool.ts new file mode 100644 index 00000000000..8864e3993fd --- /dev/null +++ b/handwritten/spanner/observability-test/session-pool.ts @@ -0,0 +1,218 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import * as extend from 'extend'; +import PQueue from 'p-queue'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import stackTrace = require('stack-trace'); +const { + AlwaysOnSampler, + NodeTracerProvider, + InMemorySpanExporter, +} = require('@opentelemetry/sdk-trace-node'); +// eslint-disable-next-line n/no-extraneous-require +const {SimpleSpanProcessor} = require('@opentelemetry/sdk-trace-base'); +// eslint-disable-next-line n/no-extraneous-require +const {SpanStatusCode} = require('@opentelemetry/api'); + +import {Database} from '../src/database'; +import {Session} from '../src/session'; +import * as sp from '../src/session-pool'; + +let pQueueOverride: typeof PQueue | null = null; + +function FakePQueue(options) { + return new (pQueueOverride || PQueue)(options); +} + +FakePQueue.default = FakePQueue; + +class FakeTransaction { + options; + constructor(options?) { + this.options = options; + } + async begin(): Promise {} +} + +const fakeStackTrace = extend({}, stackTrace); + +describe('SessionPool', () => { + let sessionPool: sp.SessionPool; + // tslint:disable-next-line variable-name + let SessionPool: typeof sp.SessionPool; + + function noop() {} + const DATABASE = { + batchCreateSessions: noop, + databaseRole: 'parent_role', + } as unknown as Database; + + const sandbox = sinon.createSandbox(); + sandbox.stub().throws('Should not be called.'); + + const createSession = (name = 'id', props?): Session => { + props = props || {}; + + return Object.assign(new Session(DATABASE, name), props, { + create: sandbox.stub().resolves(), + delete: sandbox.stub().resolves(), + keepAlive: sandbox.stub().resolves(), + transaction: sandbox.stub().returns(new FakeTransaction()), + }); + }; + + before(() => { + SessionPool = proxyquire('../src/session-pool.js', { + 'p-queue': FakePQueue, + 'stack-trace': fakeStackTrace, + }).SessionPool; + }); + + afterEach(() => { + pQueueOverride = null; + sandbox.restore(); + }); + + const traceExporter = new InMemorySpanExporter(); + const sampler = new AlwaysOnSampler(); + const provider = new NodeTracerProvider({ + sampler: sampler, + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + beforeEach(() => { + DATABASE.session = createSession; + DATABASE._observabilityOptions = { + tracerProvider: provider, + }; + sessionPool = new SessionPool(DATABASE); + sessionPool._observabilityOptions = DATABASE._observabilityOptions; + traceExporter.reset(); + }); + + describe('_createSessions', () => { + const OPTIONS = 3; + it('on exception from Database.batchCreateSessions', async () => { + const ourException = new Error('this fails intentionally'); + sandbox.stub(DATABASE, 'batchCreateSessions').throws(ourException); + sandbox.stub(sessionPool, 'release'); + + await assert.rejects(async () => { + await sessionPool._createSessions(OPTIONS); + }, ourException); + + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.SessionPool.createSessions']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + 'Requesting 3 sessions', + 'Creating 3 sessions', + 'Requested for 3 sessions returned 0', + 'exception', + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Unexpected an span status code', + ); + assert.strictEqual( + ourException.message, + firstSpan.status.message, + 'Unexpected span status message', + ); + }); + + it('without error', async () => { + const RESPONSE = [[{}, {}, {}]]; + + sandbox.stub(DATABASE, 'batchCreateSessions').resolves(RESPONSE); + sandbox.stub(sessionPool, 'release'); + + await sessionPool._createSessions(OPTIONS); + assert.strictEqual(sessionPool.size, 3); + + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = ['CloudSpanner.SessionPool.createSessions']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + 'Requesting 3 sessions', + 'Creating 3 sessions', + 'Requested for 3 sessions returned 3', + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected an span status code', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + }); + }); +}); diff --git a/handwritten/spanner/observability-test/spanner.ts b/handwritten/spanner/observability-test/spanner.ts new file mode 100644 index 00000000000..d298c7d7dd3 --- /dev/null +++ b/handwritten/spanner/observability-test/spanner.ts @@ -0,0 +1,2027 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {grpc} from 'google-gax'; +import {google} from '../protos/protos'; +import {Database, Instance, Spanner} from '../src'; +import {MutationSet} from '../src/transaction'; +import protobuf = google.spanner.v1; +import v1 = google.spanner.v1; +import * as mock from '../test/mockserver/mockspanner'; +import * as mockInstanceAdmin from '../test/mockserver/mockinstanceadmin'; +import * as mockDatabaseAdmin from '../test/mockserver/mockdatabaseadmin'; +import * as sinon from 'sinon'; +import {Row} from '../src/partial-result-stream'; +import {END_TO_END_TRACING_HEADER} from '../src/common'; +import {MetricsTracerFactory} from '../src/metrics/metrics-tracer-factory'; +const { + AlwaysOnSampler, + NodeTracerProvider, + InMemorySpanExporter, +} = require('@opentelemetry/sdk-trace-node'); +// eslint-disable-next-line n/no-extraneous-require +const {SimpleSpanProcessor} = require('@opentelemetry/sdk-trace-base'); +const {SpanStatusCode} = require('@opentelemetry/api'); +const { + disableContextAndManager, + generateWithAllSpansHaveDBName, + setGlobalContextManager, + verifySpansAndEvents, + createSessionEvents, + waitingSessionsEvents, + cacheSessionEvents, +} = require('./helper'); +const { + AsyncHooksContextManager, +} = require('@opentelemetry/context-async-hooks'); + +const {ObservabilityOptions} = require('../src/instrument'); +const selectSql = 'SELECT 1'; +const updateSql = 'UPDATE FOO SET BAR=1 WHERE BAZ=2'; + +async function disableMetrics(sandbox?: sinon.SinonSandbox) { + if (sandbox) { + if ( + Object.prototype.hasOwnProperty.call( + process.env, + 'SPANNER_DISABLE_BUILTIN_METRICS', + ) + ) { + sandbox.replace(process.env, 'SPANNER_DISABLE_BUILTIN_METRICS', 'true'); + } else { + sandbox.define(process.env, 'SPANNER_DISABLE_BUILTIN_METRICS', 'true'); + } + } + await MetricsTracerFactory.resetInstance(); + MetricsTracerFactory.enabled = false; +} + +/** A simple result set for SELECT 1. */ +function createSelect1ResultSet(): protobuf.ResultSet { + const fields = [ + protobuf.StructType.Field.create({ + name: 'NUM', + type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + return protobuf.ResultSet.create({ + metadata, + rows: [{values: [{stringValue: '1'}]}], + }); +} + +interface setupResults { + server: grpc.Server; + spanner: Spanner; + spannerMock: mock.MockSpanner; +} + +async function setup( + observabilityOptions?: typeof ObservabilityOptions, + sandbox?: sinon.SinonSandbox, +): Promise { + const server = new grpc.Server(); + const spannerMock = mock.createMockSpanner(server); + mockInstanceAdmin.createMockInstanceAdmin(server); + mockDatabaseAdmin.createMockDatabaseAdmin(server); + + const port: number = await new Promise((resolve, reject) => { + server.bindAsync( + '0.0.0.0:0', + grpc.ServerCredentials.createInsecure(), + (err, assignedPort) => { + if (err) { + reject(err); + } else { + resolve(assignedPort); + } + }, + ); + }); + + spannerMock.putStatementResult( + selectSql, + mock.StatementResult.resultSet(createSelect1ResultSet()), + ); + spannerMock.putStatementResult( + updateSql, + mock.StatementResult.updateCount(1), + ); + + await disableMetrics(sandbox); + const spanner = new Spanner({ + projectId: 'observability-project-id', + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + observabilityOptions: observabilityOptions, + }); + + return Promise.resolve({ + spanner: spanner, + server: server, + spannerMock: spannerMock, + }); +} + +describe('EndToEnd', async () => { + const sandbox = sinon.createSandbox(); + const contextManager = new AsyncHooksContextManager(); + setGlobalContextManager(contextManager); + afterEach(() => { + disableContextAndManager(contextManager); + }); + + const traceExporter = new InMemorySpanExporter(); + const sampler = new AlwaysOnSampler(); + const tracerProvider = new NodeTracerProvider({ + sampler: sampler, + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + const setupResult = await setup( + { + tracerProvider: tracerProvider, + enableExtendedTracing: false, + }, + sandbox, + ); + + const server = setupResult.server; + const spannerMock = setupResult.spannerMock; + const spanner = setupResult.spanner; + const instance = spanner.instance('instance'); + + after(async () => { + spanner.close(); + await server.tryShutdown(() => {}); + sandbox.restore(); + }); + + afterEach(async () => { + await tracerProvider.forceFlush(); + await traceExporter.reset(); + spannerMock.resetRequests(); + }); + + const database = instance.database('database'); + + beforeEach(async () => { + // To deflake expectations of session creation, let's + // issue out a warm-up request request that'll ensure + // that the MultiplexedSession is created deterministically. + await database.run('SELECT 1'); + // Clear out any present traces to make a clean slate for testing. + traceExporter.forceFlush(); + traceExporter.reset(); + }); + + describe('Database', () => { + it('getSessions', async () => { + await database.getSessions(); + const expectedSpanNames = ['CloudSpanner.Database.getSessions']; + const expectedEventNames = []; + + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + }); + + it('getSnapshot', done => { + database.getSnapshot((err, transaction) => { + assert.ifError(err); + + transaction!.run('SELECT 1', async err => { + assert.ifError(err); + transaction!.end(); + const expectedSpanNames = [ + 'CloudSpanner.Snapshot.begin', + 'CloudSpanner.Database.getSnapshot', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + ]; + const expectedEventNames = [ + 'Begin Transaction', + 'Transaction Creation Done', + ...cacheSessionEvents, + 'Starting stream', + ]; + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + done(); + }); + }); + }); + + it('getTransaction', done => { + database.getTransaction(async (err, transaction) => { + assert.ifError(err); + assert.ok(transaction); + transaction!.end(); + void transaction!.commit(); + + const expectedSpanNames = ['CloudSpanner.Database.getTransaction']; + const expectedEventNames = [...cacheSessionEvents, 'Using Session']; + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + done(); + }); + }); + + it('runStream', done => { + database + .runStream('SELECT 1') + .on('data', () => {}) + .once('error', assert.ifError) + .on('end', async () => { + const expectedSpanNames = [ + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Database.runStream', + ]; + const expectedEventNames = [ + 'Starting stream', + ...cacheSessionEvents, + 'Using Session', + ]; + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + + done(); + }); + }); + + it('run', async () => { + await database.run('SELECT 1'); + const expectedSpanNames = [ + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Database.runStream', + 'CloudSpanner.Database.run', + ]; + const expectedEventNames = [ + 'Starting stream', + ...cacheSessionEvents, + 'Using Session', + ]; + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + }); + + it('runTransaction', done => { + database.runTransaction(async (err, transaction) => { + assert.ifError(err); + await transaction!.run('SELECT 1'); + await transaction!.commit(); + await transaction!.end(); + const expectedSpanNames = [ + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + 'CloudSpanner.Transaction.commit', + 'CloudSpanner.Database.runTransaction', + ]; + const expectedEventNames = [ + 'Starting stream', + 'Transaction Creation Done', + 'Starting Commit', + 'Commit Done', + ...cacheSessionEvents, + ]; + + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + done(); + }); + }); + + it('runTransactionAsync', async () => { + await database.runTransactionAsync(async transaction => { + await transaction!.run('SELECT 1'); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + 'CloudSpanner.Database.runTransactionAsync', + ]; + const expectedEventNames = [ + 'Starting stream', + 'Transaction Creation Done', + ...cacheSessionEvents, + 'Using Session', + ]; + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + }); + + it('writeAtLeastOnce', done => { + const blankMutations = new MutationSet(); + database.writeAtLeastOnce(blankMutations, async (err, response) => { + assert.ifError(err); + assert.ok(response); + const expectedSpanNames = [ + 'CloudSpanner.Transaction.commit', + 'CloudSpanner.Database.writeAtLeastOnce', + ]; + const expectedEventNames = [ + 'Starting Commit', + 'Commit Done', + ...cacheSessionEvents, + 'Using Session', + ]; + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + done(); + }); + }); + + it('batchCreateSessions', done => { + database.batchCreateSessions(5, async err => { + assert.ifError(err); + const expectedSpanNames = ['CloudSpanner.Database.batchCreateSessions']; + const expectedEventNames = []; + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + done(); + + it('runPartitionedUpdate', async () => { + await database.runPartitionedUpdate({ + sql: updateSql, + }); + + const expectedSpanNames = [ + 'CloudSpanner.Snapshot.begin', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + 'CloudSpanner.Dml.runUpdate', + 'CloudSpanner.PartitionedDml.runUpdate', + 'CloudSpanner.Database.runPartitionedUpdate', + ]; + const expectedEventNames = [ + 'Begin Transaction', + 'Transaction Creation Done', + 'Starting stream', + 'Acquiring session', + 'Cache hit: has usable session', + 'Acquired session', + ]; + verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + }); + }); + }); + }); +}); + +describe('ObservabilityOptions injection and propagation', async () => { + let sandbox; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + }); + + afterEach(() => { + sandbox.restore(); + }); + + it('Passed into Spanner, Instance and Database', async () => { + const traceExporter = new InMemorySpanExporter(); + const tracerProvider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + const observabilityOptions: typeof ObservabilityOptions = { + tracerProvider: tracerProvider, + enableExtendedTracing: true, + }; + + const setupResult = await setup(observabilityOptions, sandbox); + const spanner = setupResult.spanner; + const server = setupResult.server; + const spannerMock = setupResult.spannerMock; + + after(async () => { + traceExporter.reset(); + await tracerProvider.shutdown(); + spannerMock.resetRequests(); + spanner.close(); + server.tryShutdown(() => {}); + sandbox.restore(); + }); + + // Ensure that the same observability configuration is set on the Spanner client. + assert.deepStrictEqual(spanner._observabilityOptions, observabilityOptions); + + // Acquire a handle to the Instance through spanner.instance. + const instanceByHandle = spanner.instance('instance'); + assert.deepStrictEqual( + instanceByHandle._observabilityOptions, + observabilityOptions, + ); + + // Create the Instance by means of a constructor directly. + const instanceByConstructor = new Instance(spanner, 'myInstance'); + assert.deepStrictEqual( + instanceByConstructor._observabilityOptions, + observabilityOptions, + ); + + // Acquire a handle to the Database through instance.database. + const databaseByHandle = instanceByHandle.database('database'); + assert.deepStrictEqual( + databaseByHandle._observabilityOptions, + observabilityOptions, + ); + + // Create the Database by means of a constructor directly. + const databaseByConstructor = new Database( + instanceByConstructor, + 'myDatabase', + ); + assert.deepStrictEqual( + databaseByConstructor._observabilityOptions, + observabilityOptions, + ); + }); + + describe('Transaction', async () => { + const traceExporter = new InMemorySpanExporter(); + const tracerProvider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + const observabilityOptions: typeof ObservabilityOptions = { + tracerProvider: tracerProvider, + enableExtendedTracing: true, + }; + const setupResult = await setup(observabilityOptions, sandbox); + const spanner = setupResult.spanner; + const server = setupResult.server; + const spannerMock = setupResult.spannerMock; + + after(async () => { + traceExporter.reset(); + await tracerProvider.shutdown(); + spannerMock.resetRequests(); + spanner.close(); + server.tryShutdown(() => {}); + }); + + let database: Database; + beforeEach(async () => { + const instance = spanner.instance('instance'); + database = instance.database('database'); + + // To deflake expectations of session creation, let's + // issue out a warm-up request request that'll ensure + // that the MultiplexedSession is created deterministically. + await database.run('SELECT 1'); + // Clear out any present traces to make a clean slate for testing. + traceExporter.forceFlush(); + traceExporter.reset(); + }); + + afterEach(() => { + spannerMock.resetRequests(); + }); + + const db = spanner.instance('instance').database('database'); + const withAllSpansHaveDBName = generateWithAllSpansHaveDBName( + db.formattedName_, + ); + + it('run', async () => { + let txn; + try { + [txn] = await database.getTransaction(); + await txn.run('SELECT 1'); + await tracerProvider.forceFlush(); + traceExporter.forceFlush(); + + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + const expectedSpanNames = [ + 'CloudSpanner.Database.getTransaction', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + ...cacheSessionEvents, + 'Using Session', + 'Starting stream', + 'Transaction Creation Done', + ]; + assert.strictEqual( + actualEventNames.every(value => expectedEventNames.includes(value)), + true, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + } catch (err) { + assert.ifError(err); + } finally { + txn.end(); + } + }); + + it('Transaction.begin+Dml.runUpdate', done => { + database.getTransaction(async (err, tx) => { + assert.ifError(err); + + // Firstly erase the prior spans so that we can have only Transaction spans. + traceExporter.reset(); + + await tx!.begin(); + tx!.runUpdate(updateSql, async err => { + assert.ifError(err); + tx!.end(); + + await tracerProvider.forceFlush(); + await traceExporter.forceFlush(); + + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Snapshot.begin', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + 'CloudSpanner.Dml.runUpdate', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + 'Begin Transaction', + 'Transaction Creation Done', + 'Starting stream', + ]; + assert.deepStrictEqual( + actualEventNames.every(value => expectedEventNames.includes(value)), + true, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + }); + + it('runStream', done => { + let rowCount = 0; + database.getTransaction((err, tx) => { + assert.ifError(err); + tx! + .runStream(selectSql) + .on('data', () => rowCount++) + .on('error', assert.ifError) + .on('stats', () => {}) + .on('end', async () => { + tx!.end(); + + await tracerProvider.forceFlush(); + traceExporter.forceFlush(); + + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.getTransaction', + 'CloudSpanner.Snapshot.runStream', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + ...cacheSessionEvents, + 'Using Session', + 'Starting stream', + 'Transaction Creation Done', + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + }); + + it('rollback', done => { + database.getTransaction(async (err, tx) => { + assert.ifError(err); + + // Firstly erase the prior spans so that we can have only Transaction spans. + traceExporter.reset(); + + await tx!.begin(); + + tx!.runUpdate(updateSql, async err => { + assert.ifError(err); + tx!.rollback(async () => { + tx!.end(); + await tracerProvider.forceFlush(); + traceExporter.forceFlush(); + + const spans = traceExporter.getFinishedSpans(); + withAllSpansHaveDBName(spans); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Snapshot.begin', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + 'CloudSpanner.Dml.runUpdate', + 'CloudSpanner.Transaction.rollback', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + 'Begin Transaction', + 'Transaction Creation Done', + 'Starting stream', + ]; + assert.strictEqual( + actualEventNames.every(value => + expectedEventNames.includes(value), + ), + true, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + }); + }); + }); + + it('Propagates spans to the injected not global TracerProvider', async () => { + const globalTraceExporter = new InMemorySpanExporter(); + const globalTracerProvider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: globalTraceExporter, + spanProcessors: [new SimpleSpanProcessor(globalTraceExporter)], + }); + globalTracerProvider.register(); + + const injectedTraceExporter = new InMemorySpanExporter(); + const injectedTracerProvider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: injectedTraceExporter, + spanProcessors: [new SimpleSpanProcessor(injectedTraceExporter)], + }); + + const observabilityOptions: typeof ObservabilityOptions = { + tracerProvider: injectedTracerProvider, + enableExtendedTracing: true, + }; + const setupResult = await setup(observabilityOptions, sandbox); + const spanner = setupResult.spanner; + const server = setupResult.server; + const spannerMock = setupResult.spannerMock; + + const instance = spanner.instance('instance'); + const database = instance.database('database'); + + const withAllSpansHaveDBName = generateWithAllSpansHaveDBName( + database.formattedName_, + ); + + try { + await database.run('SELECT 1'); + injectedTraceExporter.forceFlush(); + globalTraceExporter.forceFlush(); + const spansFromInjected = injectedTraceExporter.getFinishedSpans(); + const spansFromGlobal = globalTraceExporter.getFinishedSpans(); + assert.strictEqual( + spansFromGlobal.length, + 0, + 'Expecting no spans from the global exporter', + ); + assert.strictEqual( + spansFromInjected.length > 0, + true, + 'Expecting spans from the injected exporter', + ); + + spansFromInjected.sort((spanA, spanB) => { + spanA.startTime < spanB.startTime; + }); + withAllSpansHaveDBName(spansFromInjected); + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spansFromInjected.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Database.runStream', + 'CloudSpanner.Database.run', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + const expectedEventNames = [ + ...createSessionEvents, + 'Starting stream', + ...waitingSessionsEvents, + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + } catch (err) { + assert.ifError(err); + } finally { + injectedTraceExporter.reset(); + await injectedTracerProvider.shutdown(); + spannerMock.resetRequests(); + spanner.close(); + server.tryShutdown(() => {}); + } + }); +}); + +describe('E2E traces with async/await', async () => { + let server: grpc.Server; + let spanner: Spanner; + let spannerMock: mock.MockSpanner; + let traceExporter: typeof InMemorySpanExporter; + let provider: typeof NodeTracerProvider; + let observabilityOptions: typeof ObservabilityOptions; + let sandbox; + + beforeEach(async () => { + sandbox = sinon.createSandbox(); + traceExporter = new InMemorySpanExporter(); + provider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + observabilityOptions = { + tracerProvider: provider, + enableExtendedTracing: true, + }; + const setupResult = await setup(observabilityOptions, sandbox); + spanner = setupResult.spanner; + server = setupResult.server; + spannerMock = setupResult.spannerMock; + }); + + afterEach(async () => { + traceExporter.reset(); + provider.shutdown(); + spannerMock.resetRequests(); + spanner.close(); + server.tryShutdown(() => {}); + sandbox.restore(); + }); + + function assertAsyncAwaitExpectations() { + // See https://github.com/googleapis/nodejs-spanner/issues/2146. + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Database.runStream', + 'CloudSpanner.Database.run', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // We need to ensure a strict relationship between the spans. + // runSpan -------------------| + // |-runStream ----------| + const runStreamSpan = spans[spans.length - 2]; + const runSpan = spans[spans.length - 1]; + assert.ok( + runSpan.spanContext().traceId, + 'Expected that runSpan has a defined traceId', + ); + assert.ok( + runStreamSpan.spanContext().traceId, + 'Expected that runStreamSpan has a defined traceId', + ); + assert.deepStrictEqual( + runStreamSpan.parentSpanContext.spanId, + runSpan.spanContext().spanId, + `Expected that runSpan(spanId=${runSpan.spanContext().spanId}) is the parent to runStreamSpan(parentSpanId=${runStreamSpan.parentSpanContext.spanId})`, + ); + assert.deepStrictEqual( + runSpan.spanContext().traceId, + runStreamSpan.spanContext().traceId, + 'Expected that both spans share a traceId', + ); + assert.ok( + runStreamSpan.spanContext().spanId, + 'Expected that runStreamSpan has a defined spanId', + ); + assert.ok( + runSpan.spanContext().spanId, + 'Expected that runSpan has a defined spanId', + ); + + const databaseCreateSessionSpan = spans[0]; + assert.strictEqual( + databaseCreateSessionSpan.name, + 'CloudSpanner.Database.createSession', + ); + const multiplexedSessionCreateSessionSpan = spans[1]; + assert.strictEqual( + multiplexedSessionCreateSessionSpan.name, + 'CloudSpanner.MultiplexedSession.createSession', + ); + assert.ok( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + 'Expecting a defined multiplexedSessionCreateSession traceId', + ); + assert.deepStrictEqual( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + databaseCreateSessionSpan.spanContext().traceId, + 'Expected the same traceId', + ); + assert.deepStrictEqual( + databaseCreateSessionSpan.parentSpanContext.spanId, + multiplexedSessionCreateSessionSpan.spanContext().spanId, + 'Expected that multiplexedSession.createSession is the parent to db.creassionSession', + ); + + // Assert that despite all being exported, MultiplexedSession.createSession + // is not in the same trace as runStream, createSessions is invoked at + // Spanner Client instantiation, thus before database.run is invoked. + assert.notEqual( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + runSpan.spanContext().traceId, + 'Did not expect the same traceId', + ); + + // Finally check for the collective expected event names. + const expectedEventNames = [ + ...createSessionEvents, + 'Starting stream', + ...waitingSessionsEvents, + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + } + + it('async/await correctly parents trace spans', async () => { + // See https://github.com/googleapis/nodejs-spanner/issues/2146. + async function main() { + const instance = spanner.instance('testing'); + const database = instance.database('db-1'); + + const query = { + sql: selectSql, + }; + + const [rows] = await database.run(query); + + rows.forEach(row => { + row.toJSON(); + }); + + provider.forceFlush(); + } + + await main(); + assertAsyncAwaitExpectations(); + }); + + it('callback correctly parents trace spans', done => { + function main(onComplete) { + const instance = spanner.instance('testing'); + const database = instance.database('db-1'); + + const query = { + sql: selectSql, + }; + + database.run(query, (err, rows) => { + rows.forEach(row => { + row.toJSON(); + }); + + provider.forceFlush(); + onComplete(); + }); + } + + main(() => { + assertAsyncAwaitExpectations(); + done(); + }); + }); +}); + +describe('Negative cases', async () => { + let server: grpc.Server; + let spanner: Spanner; + let spannerMock: mock.MockSpanner; + let traceExporter: typeof InMemorySpanExporter; + let provider: typeof NodeTracerProvider; + let observabilityOptions: typeof ObservabilityOptions; + let sandbox; + + const selectSql1p = 'SELECT 1p'; + const messageBadSelect1p = `Missing whitespace between literal and alias [at 1:9] +SELECT 1p + ^`; + const insertAlreadyExistentDataSql = + "INSERT INTO Singers(firstName, SingerId) VALUES('Foo', 1)"; + const messageBadInsertAlreadyExistent = + 'Failed to insert row with primary key ({pk#SingerId:1}) due to previously existing row'; + + beforeEach(async () => { + sandbox = sinon.createSandbox(); + traceExporter = new InMemorySpanExporter(); + provider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + observabilityOptions = { + tracerProvider: provider, + enableExtendedTracing: true, + }; + const setupResult = await setup(observabilityOptions, sandbox); + spanner = setupResult.spanner; + server = setupResult.server; + spannerMock = setupResult.spannerMock; + + const serverErr = { + message: messageBadSelect1p, + code: grpc.status.INVALID_ARGUMENT, + } as mock.MockError; + spannerMock.putStatementResult( + selectSql1p, + mock.StatementResult.error(serverErr), + ); + + const insertAlreadyExistentErr = { + message: messageBadInsertAlreadyExistent, + code: grpc.status.ALREADY_EXISTS, + } as mock.MockError; + spannerMock.putStatementResult( + insertAlreadyExistentDataSql, + mock.StatementResult.error(insertAlreadyExistentErr), + ); + }); + + afterEach(async () => { + traceExporter.reset(); + provider.shutdown(); + spannerMock.resetRequests(); + spanner.close(); + server.tryShutdown(() => {}); + sandbox.restore(); + }); + + function assertRunBadSyntaxExpectations() { + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + spans.sort((spanA, spanB) => { + return spanA.startTime < spanB.startTime; + }); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Database.runStream', + 'CloudSpanner.Database.run', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // We need to ensure a strict relationship between the spans. + // runSpan -------------------| + // |-runStream ----------| + const runStreamSpan = spans[spans.length - 2]; + const runSpan = spans[spans.length - 1]; + assert.ok( + runSpan.spanContext().traceId, + 'Expected that runSpan has a defined traceId', + ); + assert.ok( + runStreamSpan.spanContext().traceId, + 'Expected that runStreamSpan has a defined traceId', + ); + assert.deepStrictEqual( + runStreamSpan.parentSpanContext.spanId, + runSpan.spanContext().spanId, + `Expected that runSpan(spanId=${runSpan.spanContext().spanId}) is the parent to runStreamSpan(parentSpanId=${runStreamSpan.parentSpanId})`, + ); + assert.deepStrictEqual( + runSpan.spanContext().traceId, + runStreamSpan.spanContext().traceId, + 'Expected that both spans share a traceId', + ); + assert.ok( + runStreamSpan.spanContext().spanId, + 'Expected that runStreamSpan has a defined spanId', + ); + assert.ok( + runSpan.spanContext().spanId, + 'Expected that runSpan has a defined spanId', + ); + + const databaseCreateSessionSpan = spans[0]; + assert.strictEqual( + databaseCreateSessionSpan.name, + 'CloudSpanner.Database.createSession', + ); + const multiplexedSessionCreateSessionSpan = spans[1]; + assert.strictEqual( + multiplexedSessionCreateSessionSpan.name, + 'CloudSpanner.MultiplexedSession.createSession', + ); + assert.ok( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + 'Expecting a defined multiplexedSessionCreateSession traceId', + ); + assert.deepStrictEqual( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + databaseCreateSessionSpan.spanContext().traceId, + 'Expected the same traceId', + ); + assert.deepStrictEqual( + databaseCreateSessionSpan.parentSpanContext.spanId, + multiplexedSessionCreateSessionSpan.spanContext().spanId, + 'Expected that multiplexedSession.createSession is the parent to db.creassionSession', + ); + + // Assert that despite all being exported, MultiplexedSession.createSession + // is not in the same trace as runStream, createSessions is invoked at + // Spanner Client instantiation, thus before database.run is invoked. + assert.notEqual( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + runSpan.spanContext().traceId, + 'Did not expect the same traceId', + ); + + // Ensure that the last span has an error. + assert.deepStrictEqual( + runStreamSpan.status.code, + SpanStatusCode.ERROR, + 'Expected an error status', + ); + + const want = '3 INVALID_ARGUMENT: ' + messageBadSelect1p; + assert.deepStrictEqual( + runStreamSpan.status.message, + want, + `Mismatched status message:\n\n\tGot: '${runStreamSpan.status.message}'\n\tWant: '${want}'`, + ); + + // Finally check for the collective expected event names. + const expectedEventNames = [ + ...createSessionEvents, + 'Starting stream', + ...waitingSessionsEvents, + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + } + + it('database.run with bad syntax: async/await', async () => { + const instance = spanner.instance('instance'); + const database = instance.database('database'); + + try { + await database.run(selectSql1p); + } catch (e) { + // This catch is meant to ensure that we + // can assert on the generated spans. + } finally { + provider.forceFlush(); + } + + assertRunBadSyntaxExpectations(); + }); + + it('database.run with bad syntax: callback', done => { + const instance = spanner.instance('instance'); + const database = instance.database('database'); + + database.run(selectSql1p, err => { + assert.ok(err); + provider.forceFlush(); + assertRunBadSyntaxExpectations(); + done(); + }); + }); + + function assertDatabaseRunPlusAwaitTransactionForAlreadyExistentData() { + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + spans.sort((spanA, spanB) => { + return spanA.startTime < spanB.startTime; + }); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + 'CloudSpanner.Snapshot.begin', + 'CloudSpanner.Snapshot.begin', + 'CloudSpanner.Transaction.commit', + 'CloudSpanner.Transaction.commit', + 'CloudSpanner.Database.runTransactionAsync', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + const spanSnapshotRun = spans[3]; + assert.strictEqual(spanSnapshotRun.name, 'CloudSpanner.Snapshot.run'); + const wantSpanErr = '6 ALREADY_EXISTS: ' + messageBadInsertAlreadyExistent; + assert.deepStrictEqual( + spanSnapshotRun.status.code, + SpanStatusCode.ERROR, + 'Unexpected status code', + ); + assert.deepStrictEqual( + spanSnapshotRun.status.message, + wantSpanErr, + 'Unexpexcted error message', + ); + + const databaseCreateSessionSpan = spans[0]; + assert.strictEqual( + databaseCreateSessionSpan.name, + 'CloudSpanner.Database.createSession', + ); + const multiplexedSessionCreateSessionSpan = spans[1]; + assert.strictEqual( + multiplexedSessionCreateSessionSpan.name, + 'CloudSpanner.MultiplexedSession.createSession', + ); + assert.ok( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + 'Expecting a defined multiplexedSessionCreateSession traceId', + ); + assert.deepStrictEqual( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + databaseCreateSessionSpan.spanContext().traceId, + 'Expected the same traceId', + ); + assert.deepStrictEqual( + databaseCreateSessionSpan.parentSpanContext.spanId, + multiplexedSessionCreateSessionSpan.spanContext().spanId, + 'Expected that multiplexedSession.createSession is the parent to db.creassionSession', + ); + + // We need to ensure a strict relationship between the spans. + // |-Database.runTransactionAsync |-------------------------------------| + // |-Snapshot.run |------------------------| + // |-Snapshot.runStream |---------------------| + // |-Transaction.commit |--------| + // |-Snapshot.begin |------| + // |-Snapshot.commit |-----| + const spanDatabaseRunTransactionAsync = spans[spans.length - 1]; + assert.deepStrictEqual( + spanDatabaseRunTransactionAsync.name, + 'CloudSpanner.Database.runTransactionAsync', + `${actualSpanNames}`, + ); + const spanTransactionCommit0 = spans[spans.length - 2]; + assert.strictEqual( + spanTransactionCommit0.name, + 'CloudSpanner.Transaction.commit', + ); + assert.deepStrictEqual( + spanTransactionCommit0.parentSpanContext.spanId, + spanDatabaseRunTransactionAsync.spanContext().spanId, + 'Expected that Database.runTransaction is the parent to Transaction.commmit', + ); + + assert.deepStrictEqual( + spanSnapshotRun.parentSpanContext.spanId, + spanDatabaseRunTransactionAsync.spanContext().spanId, + 'Expected that Database.runTransaction is the parent to Snapshot.run', + ); + + // Assert that despite all being exported, MultiplexedSession.createSessions + // is not in the same trace as runStream, createSessions is invoked at + // Spanner Client instantiation, thus before database.run is invoked. + assert.notEqual( + multiplexedSessionCreateSessionSpan.spanContext().traceId, + spanDatabaseRunTransactionAsync.spanContext().traceId, + 'Did not expect the same traceId', + ); + + // Finally check for the collective expected event names. + const expectedEventNames = [ + ...createSessionEvents, + 'Starting stream', + 'Stream broken. Safe to retry', + 'Begin Transaction', + 'Transaction Creation Done', + 'Begin Transaction', + 'Transaction Creation Done', + 'Starting Commit', + 'Commit Done', + ...waitingSessionsEvents, + 'exception', + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + } + + it('database.runTransaction with async/await for INSERT with existent data + transaction.commit', async () => { + const instance = spanner.instance('instance'); + const database = instance.database('database'); + + const update = { + sql: insertAlreadyExistentDataSql, + }; + + try { + await database.runTransactionAsync(async transaction => { + try { + await transaction!.run(update); + } finally { + await transaction!.commit(); + } + }); + } catch (e) { + assert.strictEqual( + (e as grpc.ServiceError).code, + grpc.status.ALREADY_EXISTS, + ); + } + + provider.forceFlush(); + assertDatabaseRunPlusAwaitTransactionForAlreadyExistentData(); + }); +}); + +describe('Traces for ExecuteStream broken stream retries', () => { + let sandbox: sinon.SinonSandbox; + const selectSql = 'SELECT NUM, NAME FROM NUMBERS'; + const select1 = 'SELECT 1'; + const invalidSql = 'SELECT * FROM FOO'; + const insertSql = "INSERT INTO NUMBER (NUM, NAME) VALUES (4, 'Four')"; + const selectAllTypes = 'SELECT * FROM TABLE_WITH_ALL_TYPES'; + const insertSqlForAllTypes = `INSERT INTO TABLE_WITH_ALL_TYPES( + COLBOOL, COLINT64, COLFLOAT64, COLNUMERIC, COLSTRING, COLBYTES, COLJSON, COLDATE, COLTIMESTAMP + ) VALUES ( + @bool, @int64, @float64, @numeric, @string, @bytes, @json, @date, @timestamp + )`; + const updateSql = "UPDATE NUMBER SET NAME='Unknown' WHERE NUM IN (5, 6)"; + const fooNotFoundErr = Object.assign(new Error('Table FOO not found'), { + code: grpc.status.NOT_FOUND, + }); + const server = new grpc.Server(); + const spannerMock = mock.createMockSpanner(server); + mockInstanceAdmin.createMockInstanceAdmin(server); + mockDatabaseAdmin.createMockDatabaseAdmin(server); + let port: number; + let spanner: Spanner; + let instance: Instance; + let dbCounter = 1; + + const traceExporter = new InMemorySpanExporter(); + const tracerProvider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + function newTestDatabase(): Database { + return instance.database(`database-${dbCounter++}`); + } + + before(async () => { + sandbox = sinon.createSandbox(); + port = await new Promise((resolve, reject) => { + server.bindAsync( + '0.0.0.0:0', + grpc.ServerCredentials.createInsecure(), + (err, assignedPort) => { + if (err) { + reject(err); + } else { + resolve(assignedPort); + } + }, + ); + }); + spannerMock.putStatementResult( + selectSql, + mock.StatementResult.resultSet(mock.createSimpleResultSet()), + ); + spannerMock.putStatementResult( + select1, + mock.StatementResult.resultSet(mock.createSelect1ResultSet()), + ); + spannerMock.putStatementResult( + selectAllTypes, + mock.StatementResult.resultSet(mock.createResultSetWithAllDataTypes()), + ); + spannerMock.putStatementResult( + invalidSql, + mock.StatementResult.error(fooNotFoundErr), + ); + spannerMock.putStatementResult( + insertSql, + mock.StatementResult.updateCount(1), + ); + spannerMock.putStatementResult( + insertSqlForAllTypes, + mock.StatementResult.updateCount(1), + ); + spannerMock.putStatementResult( + updateSql, + mock.StatementResult.updateCount(2), + ); + + const observabilityOptions: typeof ObservabilityOptions = { + tracerProvider: tracerProvider, + enableExtendedTracing: true, + }; + spanner = new Spanner({ + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + observabilityOptions: observabilityOptions, + }); + // Gets a reference to a Cloud Spanner instance and database + instance = spanner.instance('instance'); + }); + + after(() => { + spanner.close(); + server.tryShutdown(() => {}); + sandbox.restore(); + }); + + beforeEach(async () => { + spannerMock.resetRequests(); + spannerMock.removeExecutionTimes(); + await tracerProvider.forceFlush(); + await traceExporter.forceFlush(); + await traceExporter.reset(); + }); + + describe('PartialResultStream', () => { + beforeEach(() => { + traceExporter.reset(); + }); + const streamIndexes = [1, 2]; + streamIndexes.forEach(index => { + it('should retry UNAVAILABLE during streaming', async () => { + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + const [rows] = await database.run(selectSql); + assert.strictEqual(rows.length, 3); + await database.close(); + }); + + it('should retry UNAVAILABLE during streaming with txn ID from inline begin response', async () => { + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + const database = newTestDatabase(); + + await database.runTransactionAsync(async tx => { + await tx.run(selectSql); + await tx.commit(); + }); + await database.close(); + + const requests = spannerMock + .getRequests() + .filter(val => (val as v1.ExecuteSqlRequest).sql) + .map(req => req as v1.ExecuteSqlRequest); + assert.strictEqual(requests.length, 2); + assert.ok( + requests[0].transaction?.begin!.readWrite, + 'inline txn is not set.', + ); + assert.ok( + requests[1].transaction!.id, + 'Transaction ID is not used for retries.', + ); + assert.ok( + requests[1].resumeToken, + 'Resume token is not set for the retried', + ); + }); + + it('should retry UNAVAILABLE during streaming with txn ID from inline begin response with parallel queries', async () => { + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + const database = newTestDatabase(); + + await database.runTransactionAsync(async tx => { + const [rows1, rows2] = await Promise.all([ + tx!.run(selectSql), + tx!.run(selectSql), + ]); + assert.equal(rows1.length, 3); + assert.equal(rows2.length, 3); + await tx.commit(); + }); + await database.close(); + + const requests = spannerMock + .getRequests() + .filter(val => (val as v1.ExecuteSqlRequest).sql) + .map(req => req as v1.ExecuteSqlRequest); + assert.strictEqual(requests.length, 3); + assert.ok( + requests[0].transaction?.begin!.readWrite, + 'inline txn is not set.', + ); + assert.ok( + requests[1].transaction!.id, + 'Transaction ID is not used for retries.', + ); + assert.ok( + requests[1].resumeToken, + 'Resume token is not set for the retried', + ); + const commitRequests = spannerMock + .getRequests() + .filter(val => (val as v1.CommitRequest).mutations) + .map(req => req as v1.CommitRequest); + assert.strictEqual(commitRequests.length, 1); + assert.deepStrictEqual( + requests[1].transaction!.id, + requests[2].transaction!.id, + ); + assert.deepStrictEqual( + requests[1].transaction!.id, + commitRequests[0].transactionId, + ); + const beginTxnRequests = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequests.length, 0); + }); + + it('should not retry non-retryable error during streaming', async () => { + const database = newTestDatabase(); + const err = { + message: 'Test error', + streamIndex: index, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + try { + await database.run(selectSql); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as grpc.ServiceError).message, + '2 UNKNOWN: Test error', + ); + } + await database.close(); + }); + + it('should retry UNAVAILABLE during streaming with a callback', done => { + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + database.run(selectSql, (err, rows) => { + assert.ifError(err); + assert.strictEqual(rows!.length, 3); + database + .close() + .then(() => done()) + .catch(err => done(err)); + }); + }); + + it('should not retry non-retryable error during streaming with a callback', done => { + const database = newTestDatabase(); + const err = { + message: 'Non-retryable error', + streamIndex: index, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + database.run(selectSql, err => { + assert.ok(err, 'Missing expected error'); + assert.strictEqual(err!.message, '2 UNKNOWN: Non-retryable error'); + database + .close() + .then(() => done()) + .catch(err => done(err)); + }); + }); + + it('should emit non-retryable error during streaming to stream', done => { + const database = newTestDatabase(); + + const err = { + message: 'Non-retryable error', + streamIndex: index, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + const receivedRows: Row[] = []; + database + .runStream(selectSql) + // We will receive data for the partial result sets that are + // returned before the error occurs. + .on('data', row => { + receivedRows.push(row); + }) + .on('end', () => { + assert.fail('Missing expected error'); + }) + .on('error', err => { + assert.strictEqual(err.message, '2 UNKNOWN: Non-retryable error'); + database + .close() + .then(() => { + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + spans.sort((spanA, spanB) => { + return spanA.startTime < spanB.startTime; + }); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Database.runStream', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Finally check for the collective expected event names. + const expectedEventNames = [ + ...createSessionEvents, + 'Starting stream', + 'Transaction Creation Done', + ...waitingSessionsEvents, + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }) + .catch(err => done(err)); + }); + }); + }); + }); + + it('should retry UNAVAILABLE from executeStreamingSql with multiple errors during streaming', async () => { + const database = newTestDatabase(); + const errors: mock.MockError[] = []; + for (const index of [0, 1, 1, 2, 2]) { + errors.push({ + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as mock.MockError); + } + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofErrors(errors), + ); + const [rows] = await database.run(selectSql); + assert.strictEqual(rows.length, 3); + await database.close(); + + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + spans.sort((spanA, spanB) => { + return spanA.startTime < spanB.startTime; + }); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Database.runStream', + 'CloudSpanner.Database.run', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Finally check for the collective expected event names. + const expectedEventNames = [ + ...createSessionEvents, + 'Starting stream', + 'Re-attempting start stream', + 'Resuming stream', + 'Resuming stream', + 'Resuming stream', + 'Resuming stream', + ...waitingSessionsEvents, + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + }); + + it('should retry UNAVAILABLE on update', async () => { + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + + await database.runTransactionAsync(async tx => { + const [updateCount] = await tx!.runUpdate(insertSql); + assert.strictEqual(updateCount, 1); + await tx!.commit(); + }); + await database.close(); + + // The span for a successful invocation of database.runTransaction + // can only be ended after the calling function is completed. + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Snapshot.run', + 'CloudSpanner.Dml.runUpdate', + 'CloudSpanner.Snapshot.begin', + 'CloudSpanner.Transaction.commit', + 'CloudSpanner.Transaction.commit', + 'CloudSpanner.Database.runTransactionAsync', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + // Finally check for the collective expected event names. + const expectedEventNames = [ + ...createSessionEvents, + 'Starting stream', + 'Re-attempting start stream', + 'Begin Transaction', + 'Transaction Creation Done', + 'Starting Commit', + 'Commit Done', + ...waitingSessionsEvents, + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + }); + + it('should not retry non-retryable error on update', async () => { + const database = newTestDatabase(); + const err = { + message: 'Permanent error', + // We need to specify a non-retryable error code to prevent the entire + // transaction to retry. Not specifying an error code, will result in + // an error with code UNKNOWN, which again will retry the transaction. + code: grpc.status.INVALID_ARGUMENT, + } as mock.MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + mock.SimulatedExecutionTime.ofError(err), + ); + let attempts = 0; + + await database.runTransactionAsync(async tx => { + attempts++; + await tx!.runUpdate(insertSql, err => { + assert.ok(err, 'Missing expected error'); + assert.strictEqual(err!.code, grpc.status.INVALID_ARGUMENT); + assert.strictEqual(attempts, 1); + tx! + .commit() + .then(() => { + database.close().catch(assert.ifError); + }) + .catch(assert.ifError); + }); + }); + assert.deepStrictEqual( + attempts, + 1, + 'runTransactionAsync.attempt must be 1', + ); + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Database.runTransactionAsync', + ]; + + const expectedEventNames = [ + ...createSessionEvents, + ...waitingSessionsEvents, + ]; + await verifySpansAndEvents( + traceExporter, + expectedSpanNames, + expectedEventNames, + ); + }); +}); + +describe('End to end tracing headers', () => { + let sandbox; + let server: grpc.Server; + let spanner: Spanner; + let spannerMock: mock.MockSpanner; + let observabilityOptions: typeof ObservabilityOptions; + + beforeEach(async () => { + sandbox = sinon.createSandbox(); + observabilityOptions = { + enableEndToEndTracing: true, + }; + + const setupResult = await setup(observabilityOptions, sandbox); + spanner = setupResult.spanner; + server = setupResult.server; + spannerMock = setupResult.spannerMock; + }); + + afterEach(async () => { + spannerMock.resetRequests(); + spanner.close(); + server.tryShutdown(() => {}); + sandbox.restore(); + }); + + it('run', async () => { + const instance = spanner.instance('instance'); + const database = instance.database('database'); + let txn; + try { + [txn] = await database.getTransaction(); + await txn.run('SELECT 1'); + let metadataCountWithE2EHeader = 0; + let metadataCountWithTraceParent = 0; + spannerMock.getMetadata().forEach(metadata => { + if (metadata.get(END_TO_END_TRACING_HEADER)[0] !== undefined) { + metadataCountWithE2EHeader++; + assert.strictEqual( + metadata.get(END_TO_END_TRACING_HEADER)[0], + 'true', + ); + } + if (metadata.get('traceparent')[0] !== undefined) { + metadataCountWithTraceParent++; + } + }); + + // Create Session for multiplexed session(default) and Select 1 request. + assert.strictEqual(spannerMock.getRequests().length, 2); + assert.strictEqual(metadataCountWithE2EHeader, 2); + assert.strictEqual(metadataCountWithTraceParent, 2); + } catch (err) { + assert.ifError(err); + } finally { + txn.end(); + } + }); +}); diff --git a/handwritten/spanner/observability-test/table.ts b/handwritten/spanner/observability-test/table.ts new file mode 100644 index 00000000000..26db0ff42b2 --- /dev/null +++ b/handwritten/spanner/observability-test/table.ts @@ -0,0 +1,338 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 * as pfy from '@google-cloud/promisify'; +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import * as through from 'through2'; + +const { + AlwaysOnSampler, + NodeTracerProvider, + InMemorySpanExporter, +} = require('@opentelemetry/sdk-trace-node'); +import {SpanStatusCode} from '@opentelemetry/api'; + +// eslint-disable-next-line n/no-extraneous-require +const {SimpleSpanProcessor} = require('@opentelemetry/sdk-trace-base'); + +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'Table') { + return; + } + assert.deepStrictEqual(options.exclude, ['delete', 'drop']); + }, +}); + +class FakeTransaction { + commit(gaxOptions, callback) { + callback(null, {}); + } + createReadStream() { + return through.obj(); + } + deleteRows() {} + end() {} + insert() {} + replace() {} + upsert() {} + update() {} +} + +describe('Table', () => { + const sandbox = sinon.createSandbox(); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Table: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let TableCached: any; + let table; + let transaction: FakeTransaction; + + const DATABASE = { + formattedName_: 'formatted-db-name', + runTransaction: (opts, callback) => callback(null, transaction), + getSnapshot: (options, callback) => callback(null, transaction), + }; + + const traceExporter = new InMemorySpanExporter(); + const sampler = new AlwaysOnSampler(); + const provider = new NodeTracerProvider({ + sampler: sampler, + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + const NAME = 'table-name'; + + const ROW = {}; + + const mutateRowsOptions = { + requestOptions: {transactionTag: 'transaction-tag'}, + }; + + before(() => { + Table = proxyquire('../src/table.js', { + '@google-cloud/promisify': fakePfy, + }).Table; + TableCached = extend({}, Table); + }); + + beforeEach(() => { + extend(Table, TableCached); + table = new Table(DATABASE, NAME); + transaction = new FakeTransaction(); + table._observabilityOptions = {tracerProvider: provider}; + }); + + afterEach(() => { + sandbox.restore(); + traceExporter.reset(); + }); + + function getExportedSpans(minCount: number) { + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + assert.strictEqual( + spans.length >= minCount, + true, + `at least ${minCount} spans expected`, + ); + + // Sort the spans by duration. + spans.sort((spanA, spanB) => { + spanA.duration < spanB.duration; + }); + + return spans; + } + + function spanNames(spans) { + const actualSpanNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + }); + return actualSpanNames; + } + + function verifySpanAttributes(span) { + const attributes = span.attributes; + assert.strictEqual(attributes['transaction.tag'], 'transaction-tag'); + assert.strictEqual(attributes['db.sql.table'], 'table-name'); + assert.strictEqual(attributes['db.name'], 'formatted-db-name'); + } + + it('deleteRows', done => { + const KEYS = ['key']; + const stub = ( + sandbox.stub(transaction, 'deleteRows') as sinon.SinonStub + ).withArgs(table.name, KEYS); + + sandbox.stub(transaction, 'commit').callsFake((opts, callback) => { + callback(); + }); + + table.deleteRows(KEYS, mutateRowsOptions, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + const spans = getExportedSpans(1); + const actualSpanNames = spanNames(spans); + const expectedSpanNames = ['CloudSpanner.Table.deleteRows']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + verifySpanAttributes(spans[0]); + done(); + }); + }); + + it('insert', done => { + const stub = ( + sandbox.stub(transaction, 'insert') as sinon.SinonStub + ).withArgs(table.name, ROW); + + table.insert(ROW, mutateRowsOptions, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + const spans = getExportedSpans(1); + const actualSpanNames = spanNames(spans); + const expectedSpanNames = ['CloudSpanner.Table.insert']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + verifySpanAttributes(spans[0]); + done(); + }); + }); + + it('insert with an error', done => { + const fakeError = new Error('err'); + sandbox + .stub(DATABASE, 'runTransaction') + .callsFake((opts, callback) => callback(fakeError)); + + table.insert(ROW, mutateRowsOptions, err => { + assert.strictEqual(err, fakeError); + + const gotSpans = getExportedSpans(1); + const gotSpanStatus = gotSpans[0].status; + const wantSpanStatus = { + code: SpanStatusCode.ERROR, + message: fakeError.message, + }; + assert.deepStrictEqual( + gotSpanStatus, + wantSpanStatus, + `mismatch in span status:\n\tGot: ${JSON.stringify(gotSpanStatus)}\n\tWant: ${JSON.stringify(wantSpanStatus)}`, + ); + + const actualSpanNames = spanNames(gotSpans); + const expectedSpanNames = ['CloudSpanner.Table.insert']; + + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + verifySpanAttributes(gotSpans[0]); + done(); + }); + }); + + it('upsert', done => { + const stub = ( + sandbox.stub(transaction, 'upsert') as sinon.SinonStub + ).withArgs(table.name, ROW); + + table.upsert(ROW, mutateRowsOptions, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + + const gotSpans = getExportedSpans(1); + + const actualSpanNames = spanNames(gotSpans); + const expectedSpanNames = ['CloudSpanner.Table.upsert']; + + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + verifySpanAttributes(gotSpans[0]); + done(); + }); + }); + + it('upsert with an error', done => { + const fakeError = new Error('err'); + sandbox + .stub(DATABASE, 'runTransaction') + .callsFake((opts, callback) => callback(fakeError)); + + table.upsert(ROW, mutateRowsOptions, err => { + assert.strictEqual(err, fakeError); + + const gotSpans = getExportedSpans(1); + + const gotSpanStatus = gotSpans[0].status; + const wantSpanStatus = { + code: SpanStatusCode.ERROR, + message: fakeError.message, + }; + assert.deepStrictEqual( + gotSpanStatus, + wantSpanStatus, + `mismatch in span status:\n\tGot: ${JSON.stringify(gotSpanStatus)}\n\tWant: ${JSON.stringify(wantSpanStatus)}`, + ); + + const actualSpanNames = spanNames(gotSpans); + const expectedSpanNames = ['CloudSpanner.Table.upsert']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + verifySpanAttributes[gotSpans[0]]; + done(); + }); + }); + + it('replace', done => { + const stub = ( + sandbox.stub(transaction, 'replace') as sinon.SinonStub + ).withArgs(table.name, ROW); + + table.replace(ROW, mutateRowsOptions, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + + const gotSpans = getExportedSpans(1); + + const actualSpanNames = spanNames(gotSpans); + const expectedSpanNames = ['CloudSpanner.Table.replace']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + verifySpanAttributes(gotSpans[0]); + done(); + }); + }); + + it('replace with an error', done => { + const fakeError = new Error('err'); + sandbox + .stub(DATABASE, 'runTransaction') + .callsFake((opts, callback) => callback(fakeError)); + + table.replace(ROW, mutateRowsOptions, err => { + assert.strictEqual(err, fakeError); + const gotSpans = getExportedSpans(1); + const gotSpanStatus = gotSpans[0].status; + const wantSpanStatus = { + code: SpanStatusCode.ERROR, + message: fakeError.message, + }; + assert.deepStrictEqual( + gotSpanStatus, + wantSpanStatus, + `mismatch in span status:\n\tGot: ${JSON.stringify(gotSpanStatus)}\n\tWant: ${JSON.stringify(wantSpanStatus)}`, + ); + + const actualSpanNames = spanNames(gotSpans); + const expectedSpanNames = ['CloudSpanner.Table.replace']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + verifySpanAttributes(gotSpans[0]); + + done(); + }); + }); +}); diff --git a/handwritten/spanner/observability-test/transaction.ts b/handwritten/spanner/observability-test/transaction.ts new file mode 100644 index 00000000000..c89c1b0a925 --- /dev/null +++ b/handwritten/spanner/observability-test/transaction.ts @@ -0,0 +1,782 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import {EventEmitter} from 'events'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; + +import {codec} from '../src/codec'; +const { + AlwaysOnSampler, + NodeTracerProvider, + InMemorySpanExporter, +} = require('@opentelemetry/sdk-trace-node'); +// eslint-disable-next-line n/no-extraneous-require +const {SpanStatusCode} = require('@opentelemetry/api'); +const { + ReadableSpan, + SimpleSpanProcessor, +} = require('@opentelemetry/sdk-trace-base'); +const {generateWithAllSpansHaveDBName} = require('./helper'); +import {ExecuteSqlRequest, ReadRequest} from '../src/transaction'; + +describe('Transaction', () => { + const sandbox = sinon.createSandbox(); + + const REQUEST = sandbox.stub(); + const REQUEST_STREAM = sandbox.stub(); + const SESSION_NAME = 'session-123'; + + const SPANNER = { + routeToLeaderEnabled: true, + directedReadOptions: {}, + }; + + const INSTANCE = { + parent: SPANNER, + }; + + const DATABASE = { + formattedName_: 'formatted-database-name', + parent: INSTANCE, + }; + + const withAllSpansHaveDBName = generateWithAllSpansHaveDBName( + DATABASE.formattedName_, + ); + + const SESSION = { + parent: DATABASE, + formattedName_: SESSION_NAME, + request: REQUEST, + requestStream: REQUEST_STREAM, + _observabilityOptions: {}, + }; + + const PARTIAL_RESULT_STREAM = sandbox.stub(); + const PROMISIFY_ALL = sandbox.stub(); + + let Snapshot; + let Transaction; + let transaction; + let snapshot; + + before(() => { + const txns = proxyquire('../src/transaction', { + '@google-cloud/promisify': {promisifyAll: PROMISIFY_ALL}, + './codec': {codec}, + './partial-result-stream': {partialResultStream: PARTIAL_RESULT_STREAM}, + }); + + Snapshot = txns.Snapshot; + Transaction = txns.Transaction; + }); + + let traceExporter: typeof InMemorySpanExporter; + let tracerProvider: typeof NodeTracerProvider; + + beforeEach(() => { + traceExporter = new InMemorySpanExporter(); + const sampler = new AlwaysOnSampler(); + + tracerProvider = new NodeTracerProvider({ + sampler: sampler, + exporter: traceExporter, + spanProcessors: [new SimpleSpanProcessor(traceExporter)], + }); + + const SNAPSHOT_OPTIONS = {a: 'b', c: 'd'}; + sandbox.stub(Snapshot, 'encodeTimestampBounds').returns(SNAPSHOT_OPTIONS); + SESSION._observabilityOptions = {tracerProvider: tracerProvider}; + snapshot = new Snapshot(SESSION); + snapshot._observabilityOptions = {tracerProvider: tracerProvider}; + + transaction = new Transaction(SESSION); + }); + + afterEach(async () => { + sandbox.restore(); + await tracerProvider.forceFlush(); + traceExporter.reset(); + }); + + after(async () => { + await tracerProvider.shutdown(); + }); + + interface spanExportResults { + spans: (typeof ReadableSpan)[]; + spanNames: string[]; + spanEventNames: string[]; + } + + function extractExportedSpans(): spanExportResults { + traceExporter.forceFlush(); + const spans = traceExporter.getFinishedSpans(); + + // Sort the spans by startTime. + spans.sort((spanA, spanB) => { + spanA.startTime < spanB.startTime; + }); + + const spanNames: string[] = []; + const eventNames: string[] = []; + spans.forEach(span => { + spanNames.push(span.name); + span.events.forEach(event => { + eventNames.push(event.name); + }); + }); + + return { + spans: spans, + spanNames: spanNames, + spanEventNames: eventNames, + } as spanExportResults; + } + + describe('Snapshot', () => { + describe('begin', () => { + const BEGIN_RESPONSE = { + id: Buffer.from('transaction-id-123'), + }; + + it('without error', done => { + REQUEST.callsFake((_, callback) => callback(null, BEGIN_RESPONSE)); + + snapshot.begin((err, resp) => { + assert.ifError(err); + assert.strictEqual(resp, BEGIN_RESPONSE); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Snapshot.begin']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + 'Begin Transaction', + 'Transaction Creation Done', + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + done(); + }); + }); + + it('with error', done => { + const fakeError = new Error('begin.error'); + + REQUEST.callsFake((_, callback) => callback(fakeError)); + + snapshot.begin(err => { + assert.strictEqual(err, fakeError); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Snapshot.begin']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = ['Begin Transaction']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Unexpected an span status code', + ); + assert.strictEqual( + 'begin.error', + firstSpan.status.message, + 'Unexpected span status message', + ); + + done(); + }); + }); + }); + + describe('read', () => { + const TABLE = 'my-table-123'; + + let fakeStream; + + beforeEach(() => { + fakeStream = new EventEmitter(); + sandbox.stub(snapshot, 'createReadStream').returns(fakeStream); + }); + + it('with error', done => { + const fakeError = new Error('read.error'); + + snapshot.read(TABLE, {}, err => { + assert.strictEqual(err, fakeError); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Snapshot.read']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Unexpected an span status code', + ); + assert.strictEqual( + 'read.error', + firstSpan.status.message, + 'Unexpected span status message', + ); + + done(); + }); + + fakeStream.emit('error', fakeError); + }); + + it('without error', done => { + const fakeRows = [{a: 'b'}, {c: 'd'}, {e: 'f'}]; + + snapshot.read(TABLE, {}, (err, rows) => { + assert.ifError(err); + assert.deepStrictEqual(rows, fakeRows); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Snapshot.read']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected an span status code', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + + done(); + }); + + fakeRows.forEach(row => fakeStream.emit('data', row)); + fakeStream.emit('end'); + }); + }); + + describe('run', () => { + const QUERY = 'SELET * FROM `MyTable`'; + + let fakeStream; + + beforeEach(() => { + fakeStream = new EventEmitter(); + sandbox.stub(snapshot, 'runStream').returns(fakeStream); + }); + + it('without error', done => { + const fakeRows = [{a: 'b'}, {c: 'd'}, {e: 'f'}]; + + snapshot.run(QUERY, (err, rows) => { + assert.ifError(err); + assert.deepStrictEqual(rows, fakeRows); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Snapshot.run']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected an span status code', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + done(); + }); + + fakeRows.forEach(row => fakeStream.emit('data', row)); + fakeStream.emit('end'); + }); + + it('with errors', done => { + const fakeError = new Error('run.error'); + + snapshot.run(QUERY, err => { + assert.strictEqual(err, fakeError); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Snapshot.run']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Unexpected an span status code', + ); + assert.strictEqual( + 'run.error', + firstSpan.status.message, + 'Unexpected span status message', + ); + + done(); + }); + + fakeStream.emit('error', fakeError); + }); + }); + + describe('runStream', () => { + const QUERY = { + sql: 'SELECT * FROM `MyTable`', + }; + + beforeEach(() => { + PARTIAL_RESULT_STREAM.callsFake(makeRequest => makeRequest()); + }); + + it('with error', done => { + REQUEST_STREAM.resetHistory(); + + const fakeQuery: ExecuteSqlRequest = Object.assign({}, QUERY, { + params: {a: undefined}, + requestOptions: {requestTag: 'request-tag'}, + }); + + snapshot.requestOptions = {transactionTag: 'transaction-tag'}; + const stream = snapshot.runStream(fakeQuery); + stream.on('error', error => { + assert.strictEqual( + error.message, + 'Value of type undefined not recognized.', + ); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Snapshot.runStream']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = ['Starting stream', 'exception']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Unexpected an span status code', + ); + assert.strictEqual( + 'Value of type undefined not recognized.', + firstSpan.status.message, + 'Unexpected span status message', + ); + + const attributes = exportResults.spans[0].attributes; + assert.strictEqual(attributes['transaction.tag'], 'transaction-tag'); + assert.strictEqual(attributes['db.name'], 'formatted-database-name'); + assert.strictEqual(attributes['request.tag'], 'request-tag'); + done(); + }); + assert.ok(!REQUEST_STREAM.called, 'No request should be made'); + }); + }); + + describe('createReadStream', () => { + const TABLE = 'my-table-123'; + + beforeEach(() => { + PARTIAL_RESULT_STREAM.callsFake(makeRequest => makeRequest()); + }); + + it('without error', done => { + const fakeStream = new EventEmitter(); + REQUEST_STREAM.returns(fakeStream); + const request: ReadRequest = { + requestOptions: {requestTag: 'request-tag'}, + }; + snapshot.requestOptions = {transactionTag: 'transaction-tag'}; + const stream = snapshot.createReadStream(TABLE, request); + stream.on('end', () => { + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + + const expectedSpanNames = ['CloudSpanner.Snapshot.createReadStream']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const attributes = exportResults.spans[0].attributes; + assert.strictEqual(attributes['transaction.tag'], 'transaction-tag'); + assert.strictEqual(attributes['db.sql.table'], TABLE); + assert.strictEqual(attributes['db.name'], 'formatted-database-name'); + assert.strictEqual(attributes['request.tag'], 'request-tag'); + done(); + }); + fakeStream.emit('end'); + }); + }); + }); + + describe('rollback', () => { + const ID = 'transaction-id-0xdedabeef'; + + beforeEach(() => { + transaction.id = ID; + }); + + it('no error with unset `id`', done => { + const expectedError = new Error( + 'Transaction ID is unknown, nothing to rollback.', + ); + delete transaction.id; + + transaction.rollback(err => { + assert.deepStrictEqual(err, null); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Transaction.rollback']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + 'Transaction ID is unknown, nothing to rollback.', + ]; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status code', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + + done(); + }); + }); + + it('with request error', done => { + const fakeError = new Error('our request error'); + transaction.request = (config, callback) => { + callback(fakeError); + }; + + transaction.rollback(err => { + assert.deepStrictEqual(err, fakeError); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Transaction.rollback']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Unexpected span status code', + ); + assert.strictEqual( + 'our request error', + firstSpan.status.message, + 'Unexpected span status message', + ); + + done(); + }); + }); + + it('with no error', done => { + transaction.request = (config, callback) => { + callback(null); + }; + + transaction.rollback(err => { + assert.ifError(err); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Transaction.rollback']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = []; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status code', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + + done(); + }); + }); + }); + + describe('commit', () => { + it('without error', done => { + const id = 'transaction-id-123'; + const transactionTag = 'bar'; + transaction.id = id; + transaction.requestOptions = {transactionTag}; + + transaction.request = (config, callback) => { + callback(null, {}); + }; + + transaction.commit(err => { + assert.ifError(err); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Transaction.commit']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = ['Starting Commit', 'Commit Done']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.UNSET, + firstSpan.status.code, + 'Unexpected span status code', + ); + assert.strictEqual( + undefined, + firstSpan.status.message, + 'Unexpected span status message', + ); + + done(); + }); + }); + + it('with generic error', () => { + const fakeError = new Error('commit.error'); + transaction.request = (config, callback) => { + callback(fakeError, {}); + }; + + transaction.commit(err => { + assert.strictEqual(err, fakeError); + + const exportResults = extractExportedSpans(); + const actualSpanNames = exportResults.spanNames; + const actualEventNames = exportResults.spanEventNames; + + const expectedSpanNames = ['CloudSpanner.Transaction.commit']; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = ['Starting Commit', 'Commit failed']; + assert.deepStrictEqual( + actualEventNames, + expectedEventNames, + `Unexpected events:\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + + // Ensure that the final span that got retries did not error. + const spans = exportResults.spans; + + const firstSpan = spans[0]; + assert.strictEqual( + SpanStatusCode.ERROR, + firstSpan.status.code, + 'Unexpected span status code', + ); + assert.strictEqual( + fakeError.message, + firstSpan.status.message, + 'Unexpected span status message', + ); + + withAllSpansHaveDBName(spans); + }); + }); + }); +}); diff --git a/handwritten/spanner/owlbot.py b/handwritten/spanner/owlbot.py new file mode 100644 index 00000000000..21a9b60576b --- /dev/null +++ b/handwritten/spanner/owlbot.py @@ -0,0 +1,72 @@ +# Copyright 2021 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. + +import synthtool as s +import synthtool.gcp as gcp +import synthtool.languages.node_mono_repo as node +import logging +from pathlib import Path +from synthtool import _tracked_paths +from synthtool import shell +import shutil + +staging = Path("owl-bot-staging/spanner") + +if staging.is_dir(): + logging.info(f"Copying files from staging directory ${staging}.") + + # nodejs-spanner is composed of 3 APIs: SpannerClient, SpannerAdminDatabase and + # SpannerAdminInstance, all 3 are exported in src/v1/index.js + # Excluding auto-generated system test since Spanner has its own packing test + excludes=["src/index.ts", "src/v1/index.ts", "README.md", "package.json", + "system-test/*", "system-test/fixtures/sample/*", "system-test/fixtures/sample/src/*", + "tsconfig.json"] + + # Copy spanner library. + for version in ['v1']: + library = staging / version + _tracked_paths.add(library) + s.copy([library], destination="handwritten/spanner", excludes=excludes) + + excludes += ["webpack.config.js", ".jsdoc.js"] + + # Copy the admin/database library. + for version in ['v1']: + library = staging / 'admin' / 'database' / version + _tracked_paths.add(library) + s.copy([library], excludes=excludes) + + # Copy the admin/instance library. + for version in ['v1']: + library = staging / 'admin' / 'instance' / version + _tracked_paths.add(library) + s.copy([library], excludes=excludes) + + # Copy the spanner/executor library. + for version in ['v1']: + library = staging / 'executor' / version + _tracked_paths.add(library) + s.copy([library], excludes=excludes) + + # The staging directory should never be merged into the main branch. + shutil.rmtree(staging) + +common_templates = gcp.CommonTemplates() +templates = common_templates.node_mono_repo_library(relative_dir="handwritten/spanner", source_location='build/src') +s.copy(templates, destination="handwritten/spanner", excludes=[".kokoro/samples-test.sh", ".kokoro/trampoline_v2.sh", ".github/release-trigger.yml", ".github/sync-repo-settings.yaml", "README.md"]) + +node.postprocess_gapic_library_hermetic(relative_dir="handwritten/spanner") + +# Remove generated samples from veneer library: +shell.run(('rm', '-rf', 'handwritten/spanner/samples/generated'), hide_output = False) diff --git a/handwritten/spanner/package.json b/handwritten/spanner/package.json new file mode 100644 index 00000000000..eb3cac0449f --- /dev/null +++ b/handwritten/spanner/package.json @@ -0,0 +1,144 @@ +{ + "name": "@google-cloud/spanner", + "description": "Cloud Spanner Client Library for Node.js", + "version": "8.6.0", + "license": "Apache-2.0", + "author": "Google Inc.", + "engines": { + "node": ">=18" + }, + "repository": { + "type": "git", + "directory": "handwritten/spanner", + "url": "https://github.com/googleapis/google-cloud-node.git" + }, + "main": "./build/src/index.js", + "types": "./build/src/index.d.ts", + "files": [ + "build/protos", + "build/src", + "!build/src/**/*.map" + ], + "keywords": [ + "google apis client", + "google api client", + "google apis", + "google api", + "google", + "google cloud platform", + "google cloud", + "cloud", + "spanner" + ], + "scripts": { + "docs": "jsdoc -c .jsdoc.js", + "predocs": "npm run compile", + "lint": "gts check", + "samples-test-with-archived": "cd samples/ && npm link ../ && npm test-with-archived && cd ../", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 1600000", + "observability-test": "mocha build/observability-test --timeout 1600000", + "cleanup": "mocha scripts/cleanup.js --timeout 30000", + "test": "mocha build/test build/test/common build/observability-test", + "ycsb": "node ./benchmark/ycsb.js run -P ./benchmark/workloada -p table=usertable -p cloudspanner.instance=ycsb-instance -p operationcount=100 -p cloudspanner.database=ycsb", + "fix": "gts fix", + "clean": "gts clean", + "compile": "tsc -p . && cp -r protos build && cp -r test/data build/test", + "prepare": "npm run compile-protos && npm run compile", + "pretest": "npm run compile", + "presystem-test": "npm run compile", + "preobservability-test": "npm run compile", + "proto": "compileProtos src", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "benchwrapper": "node bin/benchwrapper.js", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean", + "compile-protos": "compileProtos src", + "coverage": "c8 mocha build/test build/test/common && c8 report --check-coverage" + }, + "dependencies": { + "@babel/core": "7.27.7", + "@babel/helpers": "7.27.6", + "@babel/traverse": "7.27.7", + "@google-cloud/common": "^6.0.0", + "@google-cloud/monitoring": "^5.0.0", + "@google-cloud/opentelemetry-resource-util": "^2.4.0", + "@google-cloud/precise-date": "^5.0.0", + "@google-cloud/projectify": "^5.0.0", + "@google-cloud/promisify": "^5.0.0", + "@grpc/grpc-js": "^1.13.2", + "@grpc/proto-loader": "^0.8.0", + "@opentelemetry/api": "^1.9.0", + "@opentelemetry/context-async-hooks": "^2.0.0", + "@opentelemetry/core": "^2.0.0", + "@opentelemetry/resources": "^1.8.0", + "@opentelemetry/sdk-metrics": "^1.30.1", + "@opentelemetry/semantic-conventions": "^1.30.0", + "@types/big.js": "^6.2.2", + "@types/stack-trace": "^0.0.33", + "big.js": "^7.0.0", + "checkpoint-stream": "^0.1.2", + "duplexify": "^4.1.3", + "events-intercept": "^2.0.0", + "extend": "^3.0.2", + "google-auth-library": "^10.0.0-rc.1", + "google-gax": "5.0.6", + "grpc-gcp": "^1.0.1", + "lodash.snakecase": "^4.1.1", + "merge-stream": "^2.0.0", + "p-queue": "^6.0.2", + "protobufjs": "^7.4.0", + "retry-request": "^8.0.0", + "split-array-stream": "^2.0.0", + "stack-trace": "0.0.10", + "stream-events": "^1.0.5", + "teeny-request": "^10.0.0", + "through2": "^4.0.2", + "uuid": "^11.1.0" + }, + "devDependencies": { + "@opentelemetry/sdk-trace-base": "^2.0.0", + "@opentelemetry/sdk-trace-node": "^2.0.0", + "@types/concat-stream": "^2.0.3", + "@types/extend": "^3.0.4", + "@types/is": "^0.0.25", + "@types/lodash.snakecase": "^4.1.9", + "@types/merge-stream": "^2.0.0", + "@types/mocha": "^10.0.10", + "@types/mv": "^2.1.4", + "@types/ncp": "^2.0.8", + "@types/proxyquire": "^1.3.31", + "@types/request": "^2.48.12", + "@types/sinon": "^21.0.0", + "@types/through2": "^2.0.41", + "binary-search-bounds": "^2.0.5", + "c8": "^10.1.3", + "codecov": "^3.8.3", + "concat-stream": "^2.0.0", + "dedent": "^1.5.3", + "execa": "^5.0.0", + "gapic-tools": "^1.0.1", + "gts": "^6.0.2", + "jsdoc": "^4.0.4", + "jsdoc-fresh": "^5.0.0", + "jsdoc-region-tag": "^4.0.0", + "linkinator": "^6.1.2", + "lodash.random": "^3.2.0", + "long": "^5.3.2", + "mocha": "^11.1.0", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nise": "^6.1.1", + "p-limit": "^3.0.1", + "path-to-regexp": "^8.2.0", + "proxyquire": "^2.1.3", + "sinon": "^21.0.0", + "stats-lite": "^2.2.0", + "time-span": "4.0.0", + "tmp": "^0.2.3", + "typescript": "^5.8.2", + "yargs": "^17.7.2" + }, + "homepage": "https://github.com/googleapis/google-cloud-node/tree/main/handwritten/spanner" +} diff --git a/handwritten/spanner/protos/google/spanner/admin/database/v1/backup.proto b/handwritten/spanner/protos/google/spanner/admin/database/v1/backup.proto new file mode 100644 index 00000000000..6898814c421 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/admin/database/v1/backup.proto @@ -0,0 +1,773 @@ +// 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. + +syntax = "proto3"; + +package google.spanner.admin.database.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/timestamp.proto"; +import "google/spanner/admin/database/v1/common.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.Admin.Database.V1"; +option go_package = "cloud.google.com/go/spanner/admin/database/apiv1/databasepb;databasepb"; +option java_multiple_files = true; +option java_outer_classname = "BackupProto"; +option java_package = "com.google.spanner.admin.database.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\Admin\\Database\\V1"; +option ruby_package = "Google::Cloud::Spanner::Admin::Database::V1"; + +// A backup of a Cloud Spanner database. +message Backup { + option (google.api.resource) = { + type: "spanner.googleapis.com/Backup" + pattern: "projects/{project}/instances/{instance}/backups/{backup}" + }; + + // Indicates the current state of the backup. + enum State { + // Not specified. + STATE_UNSPECIFIED = 0; + + // The pending backup is still being created. Operations on the + // backup may fail with `FAILED_PRECONDITION` in this state. + CREATING = 1; + + // The backup is complete and ready for use. + READY = 2; + } + + // Required for the + // [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup] + // operation. Name of the database from which this backup was created. This + // needs to be in the same instance as the backup. Values are of the form + // `projects//instances//databases/`. + string database = 2 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + }]; + + // The backup will contain an externally consistent copy of the database at + // the timestamp specified by `version_time`. If `version_time` is not + // specified, the system will set `version_time` to the `create_time` of the + // backup. + google.protobuf.Timestamp version_time = 9; + + // Required for the + // [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup] + // operation. The expiration time of the backup, with microseconds + // granularity that must be at least 6 hours and at most 366 days + // from the time the CreateBackup request is processed. Once the `expire_time` + // has passed, the backup is eligible to be automatically deleted by Cloud + // Spanner to free the resources used by the backup. + google.protobuf.Timestamp expire_time = 3; + + // Output only for the + // [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup] + // operation. Required for the + // [UpdateBackup][google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackup] + // operation. + // + // A globally unique identifier for the backup which cannot be + // changed. Values are of the form + // `projects//instances//backups/[a-z][a-z0-9_\-]*[a-z0-9]` + // The final segment of the name must be between 2 and 60 characters + // in length. + // + // The backup is stored in the location(s) specified in the instance + // configuration of the instance containing the backup, identified + // by the prefix of the backup name of the form + // `projects//instances/`. + string name = 1; + + // Output only. The time the + // [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup] + // request is received. If the request does not specify `version_time`, the + // `version_time` of the backup will be equivalent to the `create_time`. + google.protobuf.Timestamp create_time = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Size of the backup in bytes. + int64 size_bytes = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The number of bytes that will be freed by deleting this + // backup. This value will be zero if, for example, this backup is part of an + // incremental backup chain and younger backups in the chain require that we + // keep its data. For backups not in an incremental backup chain, this is + // always the size of the backup. This value may change if backups on the same + // chain get created, deleted or expired. + int64 freeable_size_bytes = 15 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. For a backup in an incremental backup chain, this is the + // storage space needed to keep the data that has changed since the previous + // backup. For all other backups, this is always the size of the backup. This + // value may change if backups on the same chain get deleted or expired. + // + // This field can be used to calculate the total storage space used by a set + // of backups. For example, the total space used by all backups of a database + // can be computed by summing up this field. + int64 exclusive_size_bytes = 16 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The current state of the backup. + State state = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The names of the restored databases that reference the backup. + // The database names are of + // the form `projects//instances//databases/`. + // Referencing databases may exist in different instances. The existence of + // any referencing database prevents the backup from being deleted. When a + // restored database from the backup enters the `READY` state, the reference + // to the backup is removed. + repeated string referencing_databases = 7 [ + (google.api.field_behavior) = OUTPUT_ONLY, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Output only. The encryption information for the backup. + EncryptionInfo encryption_info = 8 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The encryption information for the backup, whether it is + // protected by one or more KMS keys. The information includes all Cloud + // KMS key versions used to encrypt the backup. The `encryption_status' field + // inside of each `EncryptionInfo` is not populated. At least one of the key + // versions must be available for the backup to be restored. If a key version + // is revoked in the middle of a restore, the restore behavior is undefined. + repeated EncryptionInfo encryption_information = 13 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The database dialect information for the backup. + DatabaseDialect database_dialect = 10 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The names of the destination backups being created by copying + // this source backup. The backup names are of the form + // `projects//instances//backups/`. + // Referencing backups may exist in different instances. The existence of + // any referencing backup prevents the backup from being deleted. When the + // copy operation is done (either successfully completed or cancelled or the + // destination backup is deleted), the reference to the backup is removed. + repeated string referencing_backups = 11 [ + (google.api.field_behavior) = OUTPUT_ONLY, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Backup" } + ]; + + // Output only. The max allowed expiration time of the backup, with + // microseconds granularity. A backup's expiration time can be configured in + // multiple APIs: CreateBackup, UpdateBackup, CopyBackup. When updating or + // copying an existing backup, the expiration time specified must be + // less than `Backup.max_expire_time`. + google.protobuf.Timestamp max_expire_time = 12 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. List of backup schedule URIs that are associated with + // creating this backup. This is only applicable for scheduled backups, and + // is empty for on-demand backups. + // + // To optimize for storage, whenever possible, multiple schedules are + // collapsed together to create one backup. In such cases, this field captures + // the list of all backup schedule URIs that are associated with creating + // this backup. If collapsing is not done, then this field captures the + // single backup schedule URI associated with creating this backup. + repeated string backup_schedules = 14 [ + (google.api.field_behavior) = OUTPUT_ONLY, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/BackupSchedule" + } + ]; + + // Output only. Populated only for backups in an incremental backup chain. + // Backups share the same chain id if and only if they belong to the same + // incremental backup chain. Use this field to determine which backups are + // part of the same incremental backup chain. The ordering of backups in the + // chain can be determined by ordering the backup `version_time`. + string incremental_backup_chain_id = 17 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Data deleted at a time older than this is guaranteed not to be + // retained in order to support this backup. For a backup in an incremental + // backup chain, this is the version time of the oldest backup that exists or + // ever existed in the chain. For all other backups, this is the version time + // of the backup. This field can be used to understand what data is being + // retained by the backup system. + google.protobuf.Timestamp oldest_version_time = 18 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The instance partition(s) storing the backup. + // + // This is the same as the list of the instance partition(s) that the database + // had footprint in at the backup's `version_time`. + repeated BackupInstancePartition instance_partitions = 19 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// The request for +// [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup]. +message CreateBackupRequest { + // Required. The name of the instance in which the backup will be + // created. This must be the same instance that contains the database the + // backup will be created from. The backup will be stored in the + // location(s) specified in the instance configuration of this + // instance. Values are of the form + // `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Required. The id of the backup to be created. The `backup_id` appended to + // `parent` forms the full backup name of the form + // `projects//instances//backups/`. + string backup_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The backup to create. + Backup backup = 3 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The encryption configuration used to encrypt the backup. If this + // field is not specified, the backup will use the same encryption + // configuration as the database by default, namely + // [encryption_type][google.spanner.admin.database.v1.CreateBackupEncryptionConfig.encryption_type] + // = `USE_DATABASE_ENCRYPTION`. + CreateBackupEncryptionConfig encryption_config = 4 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Metadata type for the operation returned by +// [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup]. +message CreateBackupMetadata { + // The name of the backup being created. + string name = 1 [ + (google.api.resource_reference) = { type: "spanner.googleapis.com/Backup" } + ]; + + // The name of the database the backup is created from. + string database = 2 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + }]; + + // The progress of the + // [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup] + // operation. + OperationProgress progress = 3; + + // The time at which cancellation of this operation was received. + // [Operations.CancelOperation][google.longrunning.Operations.CancelOperation] + // starts asynchronous cancellation on a long-running operation. The server + // makes a best effort to cancel the operation, but success is not guaranteed. + // Clients can use + // [Operations.GetOperation][google.longrunning.Operations.GetOperation] or + // other methods to check whether the cancellation succeeded or whether the + // operation completed despite cancellation. On successful cancellation, + // the operation is not deleted; instead, it becomes an operation with + // an [Operation.error][google.longrunning.Operation.error] value with a + // [google.rpc.Status.code][google.rpc.Status.code] of 1, + // corresponding to `Code.CANCELLED`. + google.protobuf.Timestamp cancel_time = 4; +} + +// The request for +// [CopyBackup][google.spanner.admin.database.v1.DatabaseAdmin.CopyBackup]. +message CopyBackupRequest { + // Required. The name of the destination instance that will contain the backup + // copy. Values are of the form: `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Required. The id of the backup copy. + // The `backup_id` appended to `parent` forms the full backup_uri of the form + // `projects//instances//backups/`. + string backup_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The source backup to be copied. + // The source backup needs to be in READY state for it to be copied. + // Once CopyBackup is in progress, the source backup cannot be deleted or + // cleaned up on expiration until CopyBackup is finished. + // Values are of the form: + // `projects//instances//backups/`. + string source_backup = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Backup" } + ]; + + // Required. The expiration time of the backup in microsecond granularity. + // The expiration time must be at least 6 hours and at most 366 days + // from the `create_time` of the source backup. Once the `expire_time` has + // passed, the backup is eligible to be automatically deleted by Cloud Spanner + // to free the resources used by the backup. + google.protobuf.Timestamp expire_time = 4 + [(google.api.field_behavior) = REQUIRED]; + + // Optional. The encryption configuration used to encrypt the backup. If this + // field is not specified, the backup will use the same encryption + // configuration as the source backup by default, namely + // [encryption_type][google.spanner.admin.database.v1.CopyBackupEncryptionConfig.encryption_type] + // = `USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION`. + CopyBackupEncryptionConfig encryption_config = 5 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Metadata type for the operation returned by +// [CopyBackup][google.spanner.admin.database.v1.DatabaseAdmin.CopyBackup]. +message CopyBackupMetadata { + // The name of the backup being created through the copy operation. + // Values are of the form + // `projects//instances//backups/`. + string name = 1 [ + (google.api.resource_reference) = { type: "spanner.googleapis.com/Backup" } + ]; + + // The name of the source backup that is being copied. + // Values are of the form + // `projects//instances//backups/`. + string source_backup = 2 [ + (google.api.resource_reference) = { type: "spanner.googleapis.com/Backup" } + ]; + + // The progress of the + // [CopyBackup][google.spanner.admin.database.v1.DatabaseAdmin.CopyBackup] + // operation. + OperationProgress progress = 3; + + // The time at which cancellation of CopyBackup operation was received. + // [Operations.CancelOperation][google.longrunning.Operations.CancelOperation] + // starts asynchronous cancellation on a long-running operation. The server + // makes a best effort to cancel the operation, but success is not guaranteed. + // Clients can use + // [Operations.GetOperation][google.longrunning.Operations.GetOperation] or + // other methods to check whether the cancellation succeeded or whether the + // operation completed despite cancellation. On successful cancellation, + // the operation is not deleted; instead, it becomes an operation with + // an [Operation.error][google.longrunning.Operation.error] value with a + // [google.rpc.Status.code][google.rpc.Status.code] of 1, + // corresponding to `Code.CANCELLED`. + google.protobuf.Timestamp cancel_time = 4; +} + +// The request for +// [UpdateBackup][google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackup]. +message UpdateBackupRequest { + // Required. The backup to update. `backup.name`, and the fields to be updated + // as specified by `update_mask` are required. Other fields are ignored. + // Update is only supported for the following fields: + // * `backup.expire_time`. + Backup backup = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. A mask specifying which fields (e.g. `expire_time`) in the + // Backup resource should be updated. This mask is relative to the Backup + // resource, not to the request message. The field mask must always be + // specified; this prevents any future fields from being erased accidentally + // by clients that do not know about them. + google.protobuf.FieldMask update_mask = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [GetBackup][google.spanner.admin.database.v1.DatabaseAdmin.GetBackup]. +message GetBackupRequest { + // Required. Name of the backup. + // Values are of the form + // `projects//instances//backups/`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Backup" } + ]; +} + +// The request for +// [DeleteBackup][google.spanner.admin.database.v1.DatabaseAdmin.DeleteBackup]. +message DeleteBackupRequest { + // Required. Name of the backup to delete. + // Values are of the form + // `projects//instances//backups/`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Backup" } + ]; +} + +// The request for +// [ListBackups][google.spanner.admin.database.v1.DatabaseAdmin.ListBackups]. +message ListBackupsRequest { + // Required. The instance to list backups from. Values are of the + // form `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // An expression that filters the list of returned backups. + // + // A filter expression consists of a field name, a comparison operator, and a + // value for filtering. + // The value must be a string, a number, or a boolean. The comparison operator + // must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + // Colon `:` is the contains operator. Filter rules are not case sensitive. + // + // The following fields in the + // [Backup][google.spanner.admin.database.v1.Backup] are eligible for + // filtering: + // + // * `name` + // * `database` + // * `state` + // * `create_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + // * `expire_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + // * `version_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + // * `size_bytes` + // * `backup_schedules` + // + // You can combine multiple expressions by enclosing each expression in + // parentheses. By default, expressions are combined with AND logic, but + // you can specify AND, OR, and NOT logic explicitly. + // + // Here are a few examples: + // + // * `name:Howl` - The backup's name contains the string "howl". + // * `database:prod` + // - The database's name contains the string "prod". + // * `state:CREATING` - The backup is pending creation. + // * `state:READY` - The backup is fully created and ready for use. + // * `(name:howl) AND (create_time < \"2018-03-28T14:50:00Z\")` + // - The backup name contains the string "howl" and `create_time` + // of the backup is before 2018-03-28T14:50:00Z. + // * `expire_time < \"2018-03-28T14:50:00Z\"` + // - The backup `expire_time` is before 2018-03-28T14:50:00Z. + // * `size_bytes > 10000000000` - The backup's size is greater than 10GB + // * `backup_schedules:daily` + // - The backup is created from a schedule with "daily" in its name. + string filter = 2; + + // Number of backups to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 3; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.database.v1.ListBackupsResponse.next_page_token] + // from a previous + // [ListBackupsResponse][google.spanner.admin.database.v1.ListBackupsResponse] + // to the same `parent` and with the same `filter`. + string page_token = 4; +} + +// The response for +// [ListBackups][google.spanner.admin.database.v1.DatabaseAdmin.ListBackups]. +message ListBackupsResponse { + // The list of matching backups. Backups returned are ordered by `create_time` + // in descending order, starting from the most recent `create_time`. + repeated Backup backups = 1; + + // `next_page_token` can be sent in a subsequent + // [ListBackups][google.spanner.admin.database.v1.DatabaseAdmin.ListBackups] + // call to fetch more of the matching backups. + string next_page_token = 2; +} + +// The request for +// [ListBackupOperations][google.spanner.admin.database.v1.DatabaseAdmin.ListBackupOperations]. +message ListBackupOperationsRequest { + // Required. The instance of the backup operations. Values are of + // the form `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // An expression that filters the list of returned backup operations. + // + // A filter expression consists of a field name, a + // comparison operator, and a value for filtering. + // The value must be a string, a number, or a boolean. The comparison operator + // must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + // Colon `:` is the contains operator. Filter rules are not case sensitive. + // + // The following fields in the [operation][google.longrunning.Operation] + // are eligible for filtering: + // + // * `name` - The name of the long-running operation + // * `done` - False if the operation is in progress, else true. + // * `metadata.@type` - the type of metadata. For example, the type string + // for + // [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata] + // is + // `type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata`. + // * `metadata.` - any field in metadata.value. + // `metadata.@type` must be specified first if filtering on metadata + // fields. + // * `error` - Error associated with the long-running operation. + // * `response.@type` - the type of response. + // * `response.` - any field in response.value. + // + // You can combine multiple expressions by enclosing each expression in + // parentheses. By default, expressions are combined with AND logic, but + // you can specify AND, OR, and NOT logic explicitly. + // + // Here are a few examples: + // + // * `done:true` - The operation is complete. + // * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + // `metadata.database:prod` - Returns operations where: + // * The operation's metadata type is + // [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. + // * The source database name of backup contains the string "prod". + // * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + // `(metadata.name:howl) AND` \ + // `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ + // `(error:*)` - Returns operations where: + // * The operation's metadata type is + // [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. + // * The backup name contains the string "howl". + // * The operation started before 2018-03-28T14:50:00Z. + // * The operation resulted in an error. + // * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) AND` \ + // `(metadata.source_backup:test) AND` \ + // `(metadata.progress.start_time < \"2022-01-18T14:50:00Z\") AND` \ + // `(error:*)` - Returns operations where: + // * The operation's metadata type is + // [CopyBackupMetadata][google.spanner.admin.database.v1.CopyBackupMetadata]. + // * The source backup name contains the string "test". + // * The operation started before 2022-01-18T14:50:00Z. + // * The operation resulted in an error. + // * `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + // `(metadata.database:test_db)) OR` \ + // `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) + // AND` \ + // `(metadata.source_backup:test_bkp)) AND` \ + // `(error:*)` - Returns operations where: + // * The operation's metadata matches either of criteria: + // * The operation's metadata type is + // [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata] + // AND the source database name of the backup contains the string + // "test_db" + // * The operation's metadata type is + // [CopyBackupMetadata][google.spanner.admin.database.v1.CopyBackupMetadata] + // AND the source backup name contains the string "test_bkp" + // * The operation resulted in an error. + string filter = 2; + + // Number of operations to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 3; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.database.v1.ListBackupOperationsResponse.next_page_token] + // from a previous + // [ListBackupOperationsResponse][google.spanner.admin.database.v1.ListBackupOperationsResponse] + // to the same `parent` and with the same `filter`. + string page_token = 4; +} + +// The response for +// [ListBackupOperations][google.spanner.admin.database.v1.DatabaseAdmin.ListBackupOperations]. +message ListBackupOperationsResponse { + // The list of matching backup [long-running + // operations][google.longrunning.Operation]. Each operation's name will be + // prefixed by the backup's name. The operation's + // [metadata][google.longrunning.Operation.metadata] field type + // `metadata.type_url` describes the type of the metadata. Operations returned + // include those that are pending or have completed/failed/canceled within the + // last 7 days. Operations returned are ordered by + // `operation.metadata.value.progress.start_time` in descending order starting + // from the most recently started operation. + repeated google.longrunning.Operation operations = 1; + + // `next_page_token` can be sent in a subsequent + // [ListBackupOperations][google.spanner.admin.database.v1.DatabaseAdmin.ListBackupOperations] + // call to fetch more of the matching metadata. + string next_page_token = 2; +} + +// Information about a backup. +message BackupInfo { + // Name of the backup. + string backup = 1 [ + (google.api.resource_reference) = { type: "spanner.googleapis.com/Backup" } + ]; + + // The backup contains an externally consistent copy of `source_database` at + // the timestamp specified by `version_time`. If the + // [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup] + // request did not specify `version_time`, the `version_time` of the backup is + // equivalent to the `create_time`. + google.protobuf.Timestamp version_time = 4; + + // The time the + // [CreateBackup][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackup] + // request was received. + google.protobuf.Timestamp create_time = 2; + + // Name of the database the backup was created from. + string source_database = 3 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + }]; +} + +// Encryption configuration for the backup to create. +message CreateBackupEncryptionConfig { + // Encryption types for the backup. + enum EncryptionType { + // Unspecified. Do not use. + ENCRYPTION_TYPE_UNSPECIFIED = 0; + + // Use the same encryption configuration as the database. This is the + // default option when + // [encryption_config][google.spanner.admin.database.v1.CreateBackupEncryptionConfig] + // is empty. For example, if the database is using + // `Customer_Managed_Encryption`, the backup will be using the same Cloud + // KMS key as the database. + USE_DATABASE_ENCRYPTION = 1; + + // Use Google default encryption. + GOOGLE_DEFAULT_ENCRYPTION = 2; + + // Use customer managed encryption. If specified, `kms_key_name` + // must contain a valid Cloud KMS key. + CUSTOMER_MANAGED_ENCRYPTION = 3; + } + + // Required. The encryption type of the backup. + EncryptionType encryption_type = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The Cloud KMS key that will be used to protect the backup. + // This field should be set only when + // [encryption_type][google.spanner.admin.database.v1.CreateBackupEncryptionConfig.encryption_type] + // is `CUSTOMER_MANAGED_ENCRYPTION`. Values are of the form + // `projects//locations//keyRings//cryptoKeys/`. + string kms_key_name = 2 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKey" + } + ]; + + // Optional. Specifies the KMS configuration for the one or more keys used to + // protect the backup. Values are of the form + // `projects//locations//keyRings//cryptoKeys/`. + // + // The keys referenced by kms_key_names must fully cover all + // regions of the backup's instance configuration. Some examples: + // * For single region instance configs, specify a single regional + // location KMS key. + // * For multi-regional instance configs of type GOOGLE_MANAGED, + // either specify a multi-regional location KMS key or multiple regional + // location KMS keys that cover all regions in the instance config. + // * For an instance config of type USER_MANAGED, please specify only + // regional location KMS keys to cover each region in the instance config. + // Multi-regional location KMS keys are not supported for USER_MANAGED + // instance configs. + repeated string kms_key_names = 3 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKey" + } + ]; +} + +// Encryption configuration for the copied backup. +message CopyBackupEncryptionConfig { + // Encryption types for the backup. + enum EncryptionType { + // Unspecified. Do not use. + ENCRYPTION_TYPE_UNSPECIFIED = 0; + + // This is the default option for + // [CopyBackup][google.spanner.admin.database.v1.DatabaseAdmin.CopyBackup] + // when + // [encryption_config][google.spanner.admin.database.v1.CopyBackupEncryptionConfig] + // is not specified. For example, if the source backup is using + // `Customer_Managed_Encryption`, the backup will be using the same Cloud + // KMS key as the source backup. + USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION = 1; + + // Use Google default encryption. + GOOGLE_DEFAULT_ENCRYPTION = 2; + + // Use customer managed encryption. If specified, either `kms_key_name` or + // `kms_key_names` must contain valid Cloud KMS key(s). + CUSTOMER_MANAGED_ENCRYPTION = 3; + } + + // Required. The encryption type of the backup. + EncryptionType encryption_type = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The Cloud KMS key that will be used to protect the backup. + // This field should be set only when + // [encryption_type][google.spanner.admin.database.v1.CopyBackupEncryptionConfig.encryption_type] + // is `CUSTOMER_MANAGED_ENCRYPTION`. Values are of the form + // `projects//locations//keyRings//cryptoKeys/`. + string kms_key_name = 2 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKey" + } + ]; + + // Optional. Specifies the KMS configuration for the one or more keys used to + // protect the backup. Values are of the form + // `projects//locations//keyRings//cryptoKeys/`. + // Kms keys specified can be in any order. + // + // The keys referenced by kms_key_names must fully cover all + // regions of the backup's instance configuration. Some examples: + // * For single region instance configs, specify a single regional + // location KMS key. + // * For multi-regional instance configs of type GOOGLE_MANAGED, + // either specify a multi-regional location KMS key or multiple regional + // location KMS keys that cover all regions in the instance config. + // * For an instance config of type USER_MANAGED, please specify only + // regional location KMS keys to cover each region in the instance config. + // Multi-regional location KMS keys are not supported for USER_MANAGED + // instance configs. + repeated string kms_key_names = 3 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKey" + } + ]; +} + +// The specification for full backups. +// A full backup stores the entire contents of the database at a given +// version time. +message FullBackupSpec {} + +// The specification for incremental backup chains. +// An incremental backup stores the delta of changes between a previous +// backup and the database contents at a given version time. An +// incremental backup chain consists of a full backup and zero or more +// successive incremental backups. The first backup created for an +// incremental backup chain is always a full backup. +message IncrementalBackupSpec {} + +// Instance partition information for the backup. +message BackupInstancePartition { + // A unique identifier for the instance partition. Values are of the form + // `projects//instances//instancePartitions/` + string instance_partition = 1 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/InstancePartition" + }]; +} diff --git a/handwritten/spanner/protos/google/spanner/admin/database/v1/backup_schedule.proto b/handwritten/spanner/protos/google/spanner/admin/database/v1/backup_schedule.proto new file mode 100644 index 00000000000..c273516ae09 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/admin/database/v1/backup_schedule.proto @@ -0,0 +1,230 @@ +// 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. + +syntax = "proto3"; + +package google.spanner.admin.database.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/timestamp.proto"; +import "google/spanner/admin/database/v1/backup.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.Admin.Database.V1"; +option go_package = "cloud.google.com/go/spanner/admin/database/apiv1/databasepb;databasepb"; +option java_multiple_files = true; +option java_outer_classname = "BackupScheduleProto"; +option java_package = "com.google.spanner.admin.database.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\Admin\\Database\\V1"; +option ruby_package = "Google::Cloud::Spanner::Admin::Database::V1"; + +// Defines specifications of the backup schedule. +message BackupScheduleSpec { + // Required. + oneof schedule_spec { + // Cron style schedule specification. + CrontabSpec cron_spec = 1; + } +} + +// BackupSchedule expresses the automated backup creation specification for a +// Spanner database. +// Next ID: 10 +message BackupSchedule { + option (google.api.resource) = { + type: "spanner.googleapis.com/BackupSchedule" + pattern: "projects/{project}/instances/{instance}/databases/{database}/backupSchedules/{schedule}" + plural: "backupSchedules" + singular: "backupSchedule" + }; + + // Identifier. Output only for the + // [CreateBackupSchedule][DatabaseAdmin.CreateBackupSchededule] operation. + // Required for the + // [UpdateBackupSchedule][google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackupSchedule] + // operation. A globally unique identifier for the backup schedule which + // cannot be changed. Values are of the form + // `projects//instances//databases//backupSchedules/[a-z][a-z0-9_\-]*[a-z0-9]` + // The final segment of the name must be between 2 and 60 characters in + // length. + string name = 1 [(google.api.field_behavior) = IDENTIFIER]; + + // Optional. The schedule specification based on which the backup creations + // are triggered. + BackupScheduleSpec spec = 6 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The retention duration of a backup that must be at least 6 hours + // and at most 366 days. The backup is eligible to be automatically deleted + // once the retention period has elapsed. + google.protobuf.Duration retention_duration = 3 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The encryption configuration that will be used to encrypt the + // backup. If this field is not specified, the backup will use the same + // encryption configuration as the database. + CreateBackupEncryptionConfig encryption_config = 4 + [(google.api.field_behavior) = OPTIONAL]; + + // Required. Backup type spec determines the type of backup that is created by + // the backup schedule. Currently, only full backups are supported. + oneof backup_type_spec { + // The schedule creates only full backups. + FullBackupSpec full_backup_spec = 7; + + // The schedule creates incremental backup chains. + IncrementalBackupSpec incremental_backup_spec = 8; + } + + // Output only. The timestamp at which the schedule was last updated. + // If the schedule has never been updated, this field contains the timestamp + // when the schedule was first created. + google.protobuf.Timestamp update_time = 9 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// CrontabSpec can be used to specify the version time and frequency at +// which the backup should be created. +message CrontabSpec { + // Required. Textual representation of the crontab. User can customize the + // backup frequency and the backup version time using the cron + // expression. The version time must be in UTC timezone. + // + // The backup will contain an externally consistent copy of the + // database at the version time. Allowed frequencies are 12 hour, 1 day, + // 1 week and 1 month. Examples of valid cron specifications: + // * `0 2/12 * * * ` : every 12 hours at (2, 14) hours past midnight in UTC. + // * `0 2,14 * * * ` : every 12 hours at (2,14) hours past midnight in UTC. + // * `0 2 * * * ` : once a day at 2 past midnight in UTC. + // * `0 2 * * 0 ` : once a week every Sunday at 2 past midnight in UTC. + // * `0 2 8 * * ` : once a month on 8th day at 2 past midnight in UTC. + string text = 1 [(google.api.field_behavior) = REQUIRED]; + + // Output only. The time zone of the times in `CrontabSpec.text`. Currently + // only UTC is supported. + string time_zone = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Schedule backups will contain an externally consistent copy + // of the database at the version time specified in + // `schedule_spec.cron_spec`. However, Spanner may not initiate the creation + // of the scheduled backups at that version time. Spanner will initiate + // the creation of scheduled backups within the time window bounded by the + // version_time specified in `schedule_spec.cron_spec` and version_time + + // `creation_window`. + google.protobuf.Duration creation_window = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// The request for +// [CreateBackupSchedule][google.spanner.admin.database.v1.DatabaseAdmin.CreateBackupSchedule]. +message CreateBackupScheduleRequest { + // Required. The name of the database that this backup schedule applies to. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Required. The Id to use for the backup schedule. The `backup_schedule_id` + // appended to `parent` forms the full backup schedule name of the form + // `projects//instances//databases//backupSchedules/`. + string backup_schedule_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The backup schedule to create. + BackupSchedule backup_schedule = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [GetBackupSchedule][google.spanner.admin.database.v1.DatabaseAdmin.GetBackupSchedule]. +message GetBackupScheduleRequest { + // Required. The name of the schedule to retrieve. + // Values are of the form + // `projects//instances//databases//backupSchedules/`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/BackupSchedule" + } + ]; +} + +// The request for +// [DeleteBackupSchedule][google.spanner.admin.database.v1.DatabaseAdmin.DeleteBackupSchedule]. +message DeleteBackupScheduleRequest { + // Required. The name of the schedule to delete. + // Values are of the form + // `projects//instances//databases//backupSchedules/`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/BackupSchedule" + } + ]; +} + +// The request for +// [ListBackupSchedules][google.spanner.admin.database.v1.DatabaseAdmin.ListBackupSchedules]. +message ListBackupSchedulesRequest { + // Required. Database is the parent resource whose backup schedules should be + // listed. Values are of the form + // projects//instances//databases/ + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Optional. Number of backup schedules to be returned in the response. If 0 + // or less, defaults to the server's maximum allowed page size. + int32 page_size = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.database.v1.ListBackupSchedulesResponse.next_page_token] + // from a previous + // [ListBackupSchedulesResponse][google.spanner.admin.database.v1.ListBackupSchedulesResponse] + // to the same `parent`. + string page_token = 4 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [ListBackupSchedules][google.spanner.admin.database.v1.DatabaseAdmin.ListBackupSchedules]. +message ListBackupSchedulesResponse { + // The list of backup schedules for a database. + repeated BackupSchedule backup_schedules = 1; + + // `next_page_token` can be sent in a subsequent + // [ListBackupSchedules][google.spanner.admin.database.v1.DatabaseAdmin.ListBackupSchedules] + // call to fetch more of the schedules. + string next_page_token = 2; +} + +// The request for +// [UpdateBackupScheduleRequest][google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackupSchedule]. +message UpdateBackupScheduleRequest { + // Required. The backup schedule to update. `backup_schedule.name`, and the + // fields to be updated as specified by `update_mask` are required. Other + // fields are ignored. + BackupSchedule backup_schedule = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. A mask specifying which fields in the BackupSchedule resource + // should be updated. This mask is relative to the BackupSchedule resource, + // not to the request message. The field mask must always be + // specified; this prevents any future fields from being erased + // accidentally. + google.protobuf.FieldMask update_mask = 2 + [(google.api.field_behavior) = REQUIRED]; +} diff --git a/handwritten/spanner/protos/google/spanner/admin/database/v1/common.proto b/handwritten/spanner/protos/google/spanner/admin/database/v1/common.proto new file mode 100644 index 00000000000..c494b8cf780 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/admin/database/v1/common.proto @@ -0,0 +1,132 @@ +// 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. + +syntax = "proto3"; + +package google.spanner.admin.database.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/timestamp.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.Admin.Database.V1"; +option go_package = "cloud.google.com/go/spanner/admin/database/apiv1/databasepb;databasepb"; +option java_multiple_files = true; +option java_outer_classname = "CommonProto"; +option java_package = "com.google.spanner.admin.database.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\Admin\\Database\\V1"; +option ruby_package = "Google::Cloud::Spanner::Admin::Database::V1"; +option (google.api.resource_definition) = { + type: "cloudkms.googleapis.com/CryptoKey" + pattern: "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}" +}; +option (google.api.resource_definition) = { + type: "cloudkms.googleapis.com/CryptoKeyVersion" + pattern: "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}" +}; + +// Encapsulates progress related information for a Cloud Spanner long +// running operation. +message OperationProgress { + // Percent completion of the operation. + // Values are between 0 and 100 inclusive. + int32 progress_percent = 1; + + // Time the request was received. + google.protobuf.Timestamp start_time = 2; + + // If set, the time at which this operation failed or was completed + // successfully. + google.protobuf.Timestamp end_time = 3; +} + +// Encryption configuration for a Cloud Spanner database. +message EncryptionConfig { + // The Cloud KMS key to be used for encrypting and decrypting + // the database. Values are of the form + // `projects//locations//keyRings//cryptoKeys/`. + string kms_key_name = 2 [(google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKey" + }]; + + // Specifies the KMS configuration for the one or more keys used to encrypt + // the database. Values are of the form + // `projects//locations//keyRings//cryptoKeys/`. + // + // The keys referenced by kms_key_names must fully cover all + // regions of the database instance configuration. Some examples: + // * For single region database instance configs, specify a single regional + // location KMS key. + // * For multi-regional database instance configs of type GOOGLE_MANAGED, + // either specify a multi-regional location KMS key or multiple regional + // location KMS keys that cover all regions in the instance config. + // * For a database instance config of type USER_MANAGED, please specify only + // regional location KMS keys to cover each region in the instance config. + // Multi-regional location KMS keys are not supported for USER_MANAGED + // instance configs. + repeated string kms_key_names = 3 [(google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKey" + }]; +} + +// Encryption information for a Cloud Spanner database or backup. +message EncryptionInfo { + // Possible encryption types. + enum Type { + // Encryption type was not specified, though data at rest remains encrypted. + TYPE_UNSPECIFIED = 0; + + // The data is encrypted at rest with a key that is + // fully managed by Google. No key version or status will be populated. + // This is the default state. + GOOGLE_DEFAULT_ENCRYPTION = 1; + + // The data is encrypted at rest with a key that is + // managed by the customer. The active version of the key. `kms_key_version` + // will be populated, and `encryption_status` may be populated. + CUSTOMER_MANAGED_ENCRYPTION = 2; + } + + // Output only. The type of encryption. + Type encryption_type = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. If present, the status of a recent encrypt/decrypt call on + // underlying data for this database or backup. Regardless of status, data is + // always encrypted at rest. + google.rpc.Status encryption_status = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. A Cloud KMS key version that is being used to protect the + // database or backup. + string kms_key_version = 2 [ + (google.api.field_behavior) = OUTPUT_ONLY, + (google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKeyVersion" + } + ]; +} + +// Indicates the dialect type of a database. +enum DatabaseDialect { + // Default value. This value will create a database with the + // GOOGLE_STANDARD_SQL dialect. + DATABASE_DIALECT_UNSPECIFIED = 0; + + // GoogleSQL supported SQL. + GOOGLE_STANDARD_SQL = 1; + + // PostgreSQL supported SQL. + POSTGRESQL = 2; +} diff --git a/handwritten/spanner/protos/google/spanner/admin/database/v1/spanner_database_admin.proto b/handwritten/spanner/protos/google/spanner/admin/database/v1/spanner_database_admin.proto new file mode 100644 index 00000000000..d41a4114c20 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/admin/database/v1/spanner_database_admin.proto @@ -0,0 +1,1314 @@ +// 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. + +syntax = "proto3"; + +package google.spanner.admin.database.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/iam/v1/iam_policy.proto"; +import "google/iam/v1/policy.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/rpc/status.proto"; +import "google/spanner/admin/database/v1/backup.proto"; +import "google/spanner/admin/database/v1/backup_schedule.proto"; +import "google/spanner/admin/database/v1/common.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.Admin.Database.V1"; +option go_package = "cloud.google.com/go/spanner/admin/database/apiv1/databasepb;databasepb"; +option java_multiple_files = true; +option java_outer_classname = "SpannerDatabaseAdminProto"; +option java_package = "com.google.spanner.admin.database.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\Admin\\Database\\V1"; +option ruby_package = "Google::Cloud::Spanner::Admin::Database::V1"; +option (google.api.resource_definition) = { + type: "spanner.googleapis.com/Instance" + pattern: "projects/{project}/instances/{instance}" +}; +option (google.api.resource_definition) = { + type: "spanner.googleapis.com/InstancePartition" + pattern: "projects/{project}/instances/{instance}/instancePartitions/{instance_partition}" +}; + +// Cloud Spanner Database Admin API +// +// The Cloud Spanner Database Admin API can be used to: +// * create, drop, and list databases +// * update the schema of pre-existing databases +// * create, delete, copy and list backups for a database +// * restore a database from an existing backup +service DatabaseAdmin { + option (google.api.default_host) = "spanner.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/spanner.admin"; + + // Lists Cloud Spanner databases. + rpc ListDatabases(ListDatabasesRequest) returns (ListDatabasesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/instances/*}/databases" + }; + option (google.api.method_signature) = "parent"; + } + + // Creates a new Cloud Spanner database and starts to prepare it for serving. + // The returned [long-running operation][google.longrunning.Operation] will + // have a name of the format `/operations/` and + // can be used to track preparation of the database. The + // [metadata][google.longrunning.Operation.metadata] field type is + // [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. + // The [response][google.longrunning.Operation.response] field type is + // [Database][google.spanner.admin.database.v1.Database], if successful. + rpc CreateDatabase(CreateDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/instances/*}/databases" + body: "*" + }; + option (google.api.method_signature) = "parent,create_statement"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.database.v1.Database" + metadata_type: "google.spanner.admin.database.v1.CreateDatabaseMetadata" + }; + } + + // Gets the state of a Cloud Spanner database. + rpc GetDatabase(GetDatabaseRequest) returns (Database) { + option (google.api.http) = { + get: "/v1/{name=projects/*/instances/*/databases/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates a Cloud Spanner database. The returned + // [long-running operation][google.longrunning.Operation] can be used to track + // the progress of updating the database. If the named database does not + // exist, returns `NOT_FOUND`. + // + // While the operation is pending: + // + // * The database's + // [reconciling][google.spanner.admin.database.v1.Database.reconciling] + // field is set to true. + // * Cancelling the operation is best-effort. If the cancellation succeeds, + // the operation metadata's + // [cancel_time][google.spanner.admin.database.v1.UpdateDatabaseMetadata.cancel_time] + // is set, the updates are reverted, and the operation terminates with a + // `CANCELLED` status. + // * New UpdateDatabase requests will return a `FAILED_PRECONDITION` error + // until the pending operation is done (returns successfully or with + // error). + // * Reading the database via the API continues to give the pre-request + // values. + // + // Upon completion of the returned operation: + // + // * The new values are in effect and readable via the API. + // * The database's + // [reconciling][google.spanner.admin.database.v1.Database.reconciling] + // field becomes false. + // + // The returned [long-running operation][google.longrunning.Operation] will + // have a name of the format + // `projects//instances//databases//operations/` + // and can be used to track the database modification. The + // [metadata][google.longrunning.Operation.metadata] field type is + // [UpdateDatabaseMetadata][google.spanner.admin.database.v1.UpdateDatabaseMetadata]. + // The [response][google.longrunning.Operation.response] field type is + // [Database][google.spanner.admin.database.v1.Database], if successful. + rpc UpdateDatabase(UpdateDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{database.name=projects/*/instances/*/databases/*}" + body: "database" + }; + option (google.api.method_signature) = "database,update_mask"; + option (google.longrunning.operation_info) = { + response_type: "Database" + metadata_type: "UpdateDatabaseMetadata" + }; + } + + // Updates the schema of a Cloud Spanner database by + // creating/altering/dropping tables, columns, indexes, etc. The returned + // [long-running operation][google.longrunning.Operation] will have a name of + // the format `/operations/` and can be used to + // track execution of the schema change(s). The + // [metadata][google.longrunning.Operation.metadata] field type is + // [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. + // The operation has no response. + rpc UpdateDatabaseDdl(UpdateDatabaseDdlRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{database=projects/*/instances/*/databases/*}/ddl" + body: "*" + }; + option (google.api.method_signature) = "database,statements"; + option (google.longrunning.operation_info) = { + response_type: "google.protobuf.Empty" + metadata_type: "google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata" + }; + } + + // Drops (aka deletes) a Cloud Spanner database. + // Completed backups for the database will be retained according to their + // `expire_time`. + // Note: Cloud Spanner might continue to accept requests for a few seconds + // after the database has been deleted. + rpc DropDatabase(DropDatabaseRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{database=projects/*/instances/*/databases/*}" + }; + option (google.api.method_signature) = "database"; + } + + // Returns the schema of a Cloud Spanner database as a list of formatted + // DDL statements. This method does not show pending schema updates, those may + // be queried using the [Operations][google.longrunning.Operations] API. + rpc GetDatabaseDdl(GetDatabaseDdlRequest) returns (GetDatabaseDdlResponse) { + option (google.api.http) = { + get: "/v1/{database=projects/*/instances/*/databases/*}/ddl" + }; + option (google.api.method_signature) = "database"; + } + + // Sets the access control policy on a database or backup resource. + // Replaces any existing policy. + // + // Authorization requires `spanner.databases.setIamPolicy` + // permission on [resource][google.iam.v1.SetIamPolicyRequest.resource]. + // For backups, authorization requires `spanner.backups.setIamPolicy` + // permission on [resource][google.iam.v1.SetIamPolicyRequest.resource]. + rpc SetIamPolicy(google.iam.v1.SetIamPolicyRequest) + returns (google.iam.v1.Policy) { + option (google.api.http) = { + post: "/v1/{resource=projects/*/instances/*/databases/*}:setIamPolicy" + body: "*" + additional_bindings { + post: "/v1/{resource=projects/*/instances/*/backups/*}:setIamPolicy" + body: "*" + } + additional_bindings { + post: "/v1/{resource=projects/*/instances/*/databases/*/backupSchedules/*}:setIamPolicy" + body: "*" + } + }; + option (google.api.method_signature) = "resource,policy"; + } + + // Gets the access control policy for a database or backup resource. + // Returns an empty policy if a database or backup exists but does not have a + // policy set. + // + // Authorization requires `spanner.databases.getIamPolicy` permission on + // [resource][google.iam.v1.GetIamPolicyRequest.resource]. + // For backups, authorization requires `spanner.backups.getIamPolicy` + // permission on [resource][google.iam.v1.GetIamPolicyRequest.resource]. + rpc GetIamPolicy(google.iam.v1.GetIamPolicyRequest) + returns (google.iam.v1.Policy) { + option (google.api.http) = { + post: "/v1/{resource=projects/*/instances/*/databases/*}:getIamPolicy" + body: "*" + additional_bindings { + post: "/v1/{resource=projects/*/instances/*/backups/*}:getIamPolicy" + body: "*" + } + additional_bindings { + post: "/v1/{resource=projects/*/instances/*/databases/*/backupSchedules/*}:getIamPolicy" + body: "*" + } + }; + option (google.api.method_signature) = "resource"; + } + + // Returns permissions that the caller has on the specified database or backup + // resource. + // + // Attempting this RPC on a non-existent Cloud Spanner database will + // result in a NOT_FOUND error if the user has + // `spanner.databases.list` permission on the containing Cloud + // Spanner instance. Otherwise returns an empty set of permissions. + // Calling this method on a backup that does not exist will + // result in a NOT_FOUND error if the user has + // `spanner.backups.list` permission on the containing instance. + rpc TestIamPermissions(google.iam.v1.TestIamPermissionsRequest) + returns (google.iam.v1.TestIamPermissionsResponse) { + option (google.api.http) = { + post: "/v1/{resource=projects/*/instances/*/databases/*}:testIamPermissions" + body: "*" + additional_bindings { + post: "/v1/{resource=projects/*/instances/*/backups/*}:testIamPermissions" + body: "*" + } + additional_bindings { + post: "/v1/{resource=projects/*/instances/*/databases/*/backupSchedules/*}:testIamPermissions" + body: "*" + } + additional_bindings { + post: "/v1/{resource=projects/*/instances/*/databases/*/databaseRoles/*}:testIamPermissions" + body: "*" + } + }; + option (google.api.method_signature) = "resource,permissions"; + } + + // Starts creating a new Cloud Spanner Backup. + // The returned backup [long-running operation][google.longrunning.Operation] + // will have a name of the format + // `projects//instances//backups//operations/` + // and can be used to track creation of the backup. The + // [metadata][google.longrunning.Operation.metadata] field type is + // [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. + // The [response][google.longrunning.Operation.response] field type is + // [Backup][google.spanner.admin.database.v1.Backup], if successful. + // Cancelling the returned operation will stop the creation and delete the + // backup. There can be only one pending backup creation per database. Backup + // creation of different databases can run concurrently. + rpc CreateBackup(CreateBackupRequest) returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/instances/*}/backups" + body: "backup" + }; + option (google.api.method_signature) = "parent,backup,backup_id"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.database.v1.Backup" + metadata_type: "google.spanner.admin.database.v1.CreateBackupMetadata" + }; + } + + // Starts copying a Cloud Spanner Backup. + // The returned backup [long-running operation][google.longrunning.Operation] + // will have a name of the format + // `projects//instances//backups//operations/` + // and can be used to track copying of the backup. The operation is associated + // with the destination backup. + // The [metadata][google.longrunning.Operation.metadata] field type is + // [CopyBackupMetadata][google.spanner.admin.database.v1.CopyBackupMetadata]. + // The [response][google.longrunning.Operation.response] field type is + // [Backup][google.spanner.admin.database.v1.Backup], if successful. + // Cancelling the returned operation will stop the copying and delete the + // destination backup. Concurrent CopyBackup requests can run on the same + // source backup. + rpc CopyBackup(CopyBackupRequest) returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/instances/*}/backups:copy" + body: "*" + }; + option (google.api.method_signature) = + "parent,backup_id,source_backup,expire_time"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.database.v1.Backup" + metadata_type: "google.spanner.admin.database.v1.CopyBackupMetadata" + }; + } + + // Gets metadata on a pending or completed + // [Backup][google.spanner.admin.database.v1.Backup]. + rpc GetBackup(GetBackupRequest) returns (Backup) { + option (google.api.http) = { + get: "/v1/{name=projects/*/instances/*/backups/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates a pending or completed + // [Backup][google.spanner.admin.database.v1.Backup]. + rpc UpdateBackup(UpdateBackupRequest) returns (Backup) { + option (google.api.http) = { + patch: "/v1/{backup.name=projects/*/instances/*/backups/*}" + body: "backup" + }; + option (google.api.method_signature) = "backup,update_mask"; + } + + // Deletes a pending or completed + // [Backup][google.spanner.admin.database.v1.Backup]. + rpc DeleteBackup(DeleteBackupRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/instances/*/backups/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists completed and pending backups. + // Backups returned are ordered by `create_time` in descending order, + // starting from the most recent `create_time`. + rpc ListBackups(ListBackupsRequest) returns (ListBackupsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/instances/*}/backups" + }; + option (google.api.method_signature) = "parent"; + } + + // Create a new database by restoring from a completed backup. The new + // database must be in the same project and in an instance with the same + // instance configuration as the instance containing + // the backup. The returned database [long-running + // operation][google.longrunning.Operation] has a name of the format + // `projects//instances//databases//operations/`, + // and can be used to track the progress of the operation, and to cancel it. + // The [metadata][google.longrunning.Operation.metadata] field type is + // [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata]. + // The [response][google.longrunning.Operation.response] type + // is [Database][google.spanner.admin.database.v1.Database], if + // successful. Cancelling the returned operation will stop the restore and + // delete the database. + // There can be only one database being restored into an instance at a time. + // Once the restore operation completes, a new restore operation can be + // initiated, without waiting for the optimize operation associated with the + // first restore to complete. + rpc RestoreDatabase(RestoreDatabaseRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/instances/*}/databases:restore" + body: "*" + }; + option (google.api.method_signature) = "parent,database_id,backup"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.database.v1.Database" + metadata_type: "google.spanner.admin.database.v1.RestoreDatabaseMetadata" + }; + } + + // Lists database [longrunning-operations][google.longrunning.Operation]. + // A database operation has a name of the form + // `projects//instances//databases//operations/`. + // The long-running operation + // [metadata][google.longrunning.Operation.metadata] field type + // `metadata.type_url` describes the type of the metadata. Operations returned + // include those that have completed/failed/canceled within the last 7 days, + // and pending operations. + rpc ListDatabaseOperations(ListDatabaseOperationsRequest) + returns (ListDatabaseOperationsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/instances/*}/databaseOperations" + }; + option (google.api.method_signature) = "parent"; + } + + // Lists the backup [long-running operations][google.longrunning.Operation] in + // the given instance. A backup operation has a name of the form + // `projects//instances//backups//operations/`. + // The long-running operation + // [metadata][google.longrunning.Operation.metadata] field type + // `metadata.type_url` describes the type of the metadata. Operations returned + // include those that have completed/failed/canceled within the last 7 days, + // and pending operations. Operations returned are ordered by + // `operation.metadata.value.progress.start_time` in descending order starting + // from the most recently started operation. + rpc ListBackupOperations(ListBackupOperationsRequest) + returns (ListBackupOperationsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/instances/*}/backupOperations" + }; + option (google.api.method_signature) = "parent"; + } + + // Lists Cloud Spanner database roles. + rpc ListDatabaseRoles(ListDatabaseRolesRequest) + returns (ListDatabaseRolesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/instances/*/databases/*}/databaseRoles" + }; + option (google.api.method_signature) = "parent"; + } + + // Adds split points to specified tables, indexes of a database. + rpc AddSplitPoints(AddSplitPointsRequest) returns (AddSplitPointsResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/instances/*/databases/*}:addSplitPoints" + body: "*" + }; + option (google.api.method_signature) = "database,split_points"; + } + + // Creates a new backup schedule. + rpc CreateBackupSchedule(CreateBackupScheduleRequest) + returns (BackupSchedule) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/instances/*/databases/*}/backupSchedules" + body: "backup_schedule" + }; + option (google.api.method_signature) = + "parent,backup_schedule,backup_schedule_id"; + } + + // Gets backup schedule for the input schedule name. + rpc GetBackupSchedule(GetBackupScheduleRequest) returns (BackupSchedule) { + option (google.api.http) = { + get: "/v1/{name=projects/*/instances/*/databases/*/backupSchedules/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates a backup schedule. + rpc UpdateBackupSchedule(UpdateBackupScheduleRequest) + returns (BackupSchedule) { + option (google.api.http) = { + patch: "/v1/{backup_schedule.name=projects/*/instances/*/databases/*/backupSchedules/*}" + body: "backup_schedule" + }; + option (google.api.method_signature) = "backup_schedule,update_mask"; + } + + // Deletes a backup schedule. + rpc DeleteBackupSchedule(DeleteBackupScheduleRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/instances/*/databases/*/backupSchedules/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists all the backup schedules for the database. + rpc ListBackupSchedules(ListBackupSchedulesRequest) + returns (ListBackupSchedulesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/instances/*/databases/*}/backupSchedules" + }; + option (google.api.method_signature) = "parent"; + } + + // This is an internal API called by Spanner Graph jobs. You should never need + // to call this API directly. + rpc InternalUpdateGraphOperation(InternalUpdateGraphOperationRequest) + returns (InternalUpdateGraphOperationResponse) { + option (google.api.method_signature) = "database,operation_id"; + } +} + +// Information about the database restore. +message RestoreInfo { + // The type of the restore source. + RestoreSourceType source_type = 1; + + // Information about the source used to restore the database. + oneof source_info { + // Information about the backup used to restore the database. The backup + // may no longer exist. + BackupInfo backup_info = 2; + } +} + +// A Cloud Spanner database. +message Database { + option (google.api.resource) = { + type: "spanner.googleapis.com/Database" + pattern: "projects/{project}/instances/{instance}/databases/{database}" + }; + + // Indicates the current state of the database. + enum State { + // Not specified. + STATE_UNSPECIFIED = 0; + + // The database is still being created. Operations on the database may fail + // with `FAILED_PRECONDITION` in this state. + CREATING = 1; + + // The database is fully created and ready for use. + READY = 2; + + // The database is fully created and ready for use, but is still + // being optimized for performance and cannot handle full load. + // + // In this state, the database still references the backup + // it was restore from, preventing the backup + // from being deleted. When optimizations are complete, the full performance + // of the database will be restored, and the database will transition to + // `READY` state. + READY_OPTIMIZING = 3; + } + + // Required. The name of the database. Values are of the form + // `projects//instances//databases/`, + // where `` is as specified in the `CREATE DATABASE` + // statement. This name can be passed to other API methods to + // identify the database. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Output only. The current database state. + State state = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. If exists, the time at which the database creation started. + google.protobuf.Timestamp create_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Applicable only for restored databases. Contains information + // about the restore source. + RestoreInfo restore_info = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. For databases that are using customer managed encryption, this + // field contains the encryption configuration for the database. + // For databases that are using Google default or other types of encryption, + // this field is empty. + EncryptionConfig encryption_config = 5 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. For databases that are using customer managed encryption, this + // field contains the encryption information for the database, such as + // all Cloud KMS key versions that are in use. The `encryption_status' field + // inside of each `EncryptionInfo` is not populated. + // + // For databases that are using Google default or other types of encryption, + // this field is empty. + // + // This field is propagated lazily from the backend. There might be a delay + // from when a key version is being used and when it appears in this field. + repeated EncryptionInfo encryption_info = 8 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The period in which Cloud Spanner retains all versions of data + // for the database. This is the same as the value of version_retention_period + // database option set using + // [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl]. + // Defaults to 1 hour, if not set. + string version_retention_period = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Earliest timestamp at which older versions of the data can be + // read. This value is continuously updated by Cloud Spanner and becomes stale + // the moment it is queried. If you are using this value to recover data, make + // sure to account for the time from the moment when the value is queried to + // the moment when you initiate the recovery. + google.protobuf.Timestamp earliest_version_time = 7 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The read-write region which contains the database's leader + // replicas. + // + // This is the same as the value of default_leader + // database option set using DatabaseAdmin.CreateDatabase or + // DatabaseAdmin.UpdateDatabaseDdl. If not explicitly set, this is empty. + string default_leader = 9 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The dialect of the Cloud Spanner Database. + DatabaseDialect database_dialect = 10 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Whether drop protection is enabled for this database. Defaults to false, + // if not set. For more details, please see how to [prevent accidental + // database + // deletion](https://cloud.google.com/spanner/docs/prevent-database-deletion). + bool enable_drop_protection = 11; + + // Output only. If true, the database is being updated. If false, there are no + // ongoing update operations for the database. + bool reconciling = 12 [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// The request for +// [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases]. +message ListDatabasesRequest { + // Required. The instance whose databases should be listed. + // Values are of the form `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Number of databases to be returned in the response. If 0 or less, + // defaults to the server's maximum allowed page size. + int32 page_size = 3; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.database.v1.ListDatabasesResponse.next_page_token] + // from a previous + // [ListDatabasesResponse][google.spanner.admin.database.v1.ListDatabasesResponse]. + string page_token = 4; +} + +// The response for +// [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases]. +message ListDatabasesResponse { + // Databases that matched the request. + repeated Database databases = 1; + + // `next_page_token` can be sent in a subsequent + // [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases] + // call to fetch more of the matching databases. + string next_page_token = 2; +} + +// The request for +// [CreateDatabase][google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase]. +message CreateDatabaseRequest { + // Required. The name of the instance that will serve the new database. + // Values are of the form `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Required. A `CREATE DATABASE` statement, which specifies the ID of the + // new database. The database ID must conform to the regular expression + // `[a-z][a-z0-9_\-]*[a-z0-9]` and be between 2 and 30 characters in length. + // If the database ID is a reserved word or if it contains a hyphen, the + // database ID must be enclosed in backticks (`` ` ``). + string create_statement = 2 [(google.api.field_behavior) = REQUIRED]; + + // Optional. A list of DDL statements to run inside the newly created + // database. Statements can create tables, indexes, etc. These + // statements execute atomically with the creation of the database: + // if there is an error in any statement, the database is not created. + repeated string extra_statements = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The encryption configuration for the database. If this field is + // not specified, Cloud Spanner will encrypt/decrypt all data at rest using + // Google default encryption. + EncryptionConfig encryption_config = 4 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The dialect of the Cloud Spanner Database. + DatabaseDialect database_dialect = 5 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Proto descriptors used by CREATE/ALTER PROTO BUNDLE statements in + // 'extra_statements' above. + // Contains a protobuf-serialized + // [google.protobuf.FileDescriptorSet](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto). + // To generate it, [install](https://grpc.io/docs/protoc-installation/) and + // run `protoc` with --include_imports and --descriptor_set_out. For example, + // to generate for moon/shot/app.proto, run + // ``` + // $protoc --proto_path=/app_path --proto_path=/lib_path \ + // --include_imports \ + // --descriptor_set_out=descriptors.data \ + // moon/shot/app.proto + // ``` + // For more details, see protobuffer [self + // description](https://developers.google.com/protocol-buffers/docs/techniques#self-description). + bytes proto_descriptors = 6 [(google.api.field_behavior) = OPTIONAL]; +} + +// Metadata type for the operation returned by +// [CreateDatabase][google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase]. +message CreateDatabaseMetadata { + // The database being created. + string database = 1 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + }]; +} + +// The request for +// [GetDatabase][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabase]. +message GetDatabaseRequest { + // Required. The name of the requested database. Values are of the form + // `projects//instances//databases/`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; +} + +// The request for +// [UpdateDatabase][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase]. +message UpdateDatabaseRequest { + // Required. The database to update. + // The `name` field of the database is of the form + // `projects//instances//databases/`. + Database database = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The list of fields to update. Currently, only + // `enable_drop_protection` field can be updated. + google.protobuf.FieldMask update_mask = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// Metadata type for the operation returned by +// [UpdateDatabase][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase]. +message UpdateDatabaseMetadata { + // The request for + // [UpdateDatabase][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase]. + UpdateDatabaseRequest request = 1; + + // The progress of the + // [UpdateDatabase][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase] + // operation. + OperationProgress progress = 2; + + // The time at which this operation was cancelled. If set, this operation is + // in the process of undoing itself (which is best-effort). + google.protobuf.Timestamp cancel_time = 3; +} + +// Enqueues the given DDL statements to be applied, in order but not +// necessarily all at once, to the database schema at some point (or +// points) in the future. The server checks that the statements +// are executable (syntactically valid, name tables that exist, etc.) +// before enqueueing them, but they may still fail upon +// later execution (e.g., if a statement from another batch of +// statements is applied first and it conflicts in some way, or if +// there is some data-related problem like a `NULL` value in a column to +// which `NOT NULL` would be added). If a statement fails, all +// subsequent statements in the batch are automatically cancelled. +// +// Each batch of statements is assigned a name which can be used with +// the [Operations][google.longrunning.Operations] API to monitor +// progress. See the +// [operation_id][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.operation_id] +// field for more details. +message UpdateDatabaseDdlRequest { + // Required. The database to update. + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Required. DDL statements to be applied to the database. + repeated string statements = 2 [(google.api.field_behavior) = REQUIRED]; + + // If empty, the new update request is assigned an + // automatically-generated operation ID. Otherwise, `operation_id` + // is used to construct the name of the resulting + // [Operation][google.longrunning.Operation]. + // + // Specifying an explicit operation ID simplifies determining + // whether the statements were executed in the event that the + // [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] + // call is replayed, or the return value is otherwise lost: the + // [database][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database] + // and `operation_id` fields can be combined to form the + // [name][google.longrunning.Operation.name] of the resulting + // [longrunning.Operation][google.longrunning.Operation]: + // `/operations/`. + // + // `operation_id` should be unique within the database, and must be + // a valid identifier: `[a-z][a-z0-9_]*`. Note that + // automatically-generated operation IDs always begin with an + // underscore. If the named operation already exists, + // [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] + // returns `ALREADY_EXISTS`. + string operation_id = 3; + + // Optional. Proto descriptors used by CREATE/ALTER PROTO BUNDLE statements. + // Contains a protobuf-serialized + // [google.protobuf.FileDescriptorSet](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto). + // To generate it, [install](https://grpc.io/docs/protoc-installation/) and + // run `protoc` with --include_imports and --descriptor_set_out. For example, + // to generate for moon/shot/app.proto, run + // ``` + // $protoc --proto_path=/app_path --proto_path=/lib_path \ + // --include_imports \ + // --descriptor_set_out=descriptors.data \ + // moon/shot/app.proto + // ``` + // For more details, see protobuffer [self + // description](https://developers.google.com/protocol-buffers/docs/techniques#self-description). + bytes proto_descriptors = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. This field is exposed to be used by the Spanner Migration Tool. + // For more details, see + // [SMT](https://github.com/GoogleCloudPlatform/spanner-migration-tool). + bool throughput_mode = 5 [(google.api.field_behavior) = OPTIONAL]; +} + +// Action information extracted from a DDL statement. This proto is used to +// display the brief info of the DDL statement for the operation +// [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl]. +message DdlStatementActionInfo { + // The action for the DDL statement, e.g. CREATE, ALTER, DROP, GRANT, etc. + // This field is a non-empty string. + string action = 1; + + // The entity type for the DDL statement, e.g. TABLE, INDEX, VIEW, etc. + // This field can be empty string for some DDL statement, + // e.g. for statement "ANALYZE", `entity_type` = "". + string entity_type = 2; + + // The entity name(s) being operated on the DDL statement. + // E.g. + // 1. For statement "CREATE TABLE t1(...)", `entity_names` = ["t1"]. + // 2. For statement "GRANT ROLE r1, r2 ...", `entity_names` = ["r1", "r2"]. + // 3. For statement "ANALYZE", `entity_names` = []. + repeated string entity_names = 3; +} + +// Metadata type for the operation returned by +// [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl]. +message UpdateDatabaseDdlMetadata { + // The database being modified. + string database = 1 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + }]; + + // For an update this list contains all the statements. For an + // individual statement, this list contains only that statement. + repeated string statements = 2; + + // Reports the commit timestamps of all statements that have + // succeeded so far, where `commit_timestamps[i]` is the commit + // timestamp for the statement `statements[i]`. + repeated google.protobuf.Timestamp commit_timestamps = 3; + + // Output only. When true, indicates that the operation is throttled e.g. + // due to resource constraints. When resources become available the operation + // will resume and this field will be false again. + bool throttled = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // The progress of the + // [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] + // operations. All DDL statements will have continuously updating progress, + // and `progress[i]` is the operation progress for `statements[i]`. Also, + // `progress[i]` will have start time and end time populated with commit + // timestamp of operation, as well as a progress of 100% once the operation + // has completed. + repeated OperationProgress progress = 5; + + // The brief action info for the DDL statements. + // `actions[i]` is the brief info for `statements[i]`. + repeated DdlStatementActionInfo actions = 6; +} + +// The request for +// [DropDatabase][google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase]. +message DropDatabaseRequest { + // Required. The database to be dropped. + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; +} + +// The request for +// [GetDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl]. +message GetDatabaseDdlRequest { + // Required. The database whose schema we wish to get. + // Values are of the form + // `projects//instances//databases/` + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; +} + +// The response for +// [GetDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl]. +message GetDatabaseDdlResponse { + // A list of formatted DDL statements defining the schema of the database + // specified in the request. + repeated string statements = 1; + + // Proto descriptors stored in the database. + // Contains a protobuf-serialized + // [google.protobuf.FileDescriptorSet](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto). + // For more details, see protobuffer [self + // description](https://developers.google.com/protocol-buffers/docs/techniques#self-description). + bytes proto_descriptors = 2; +} + +// The request for +// [ListDatabaseOperations][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseOperations]. +message ListDatabaseOperationsRequest { + // Required. The instance of the database operations. + // Values are of the form `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // An expression that filters the list of returned operations. + // + // A filter expression consists of a field name, a + // comparison operator, and a value for filtering. + // The value must be a string, a number, or a boolean. The comparison operator + // must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + // Colon `:` is the contains operator. Filter rules are not case sensitive. + // + // The following fields in the [Operation][google.longrunning.Operation] + // are eligible for filtering: + // + // * `name` - The name of the long-running operation + // * `done` - False if the operation is in progress, else true. + // * `metadata.@type` - the type of metadata. For example, the type string + // for + // [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata] + // is + // `type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata`. + // * `metadata.` - any field in metadata.value. + // `metadata.@type` must be specified first, if filtering on metadata + // fields. + // * `error` - Error associated with the long-running operation. + // * `response.@type` - the type of response. + // * `response.` - any field in response.value. + // + // You can combine multiple expressions by enclosing each expression in + // parentheses. By default, expressions are combined with AND logic. However, + // you can specify AND, OR, and NOT logic explicitly. + // + // Here are a few examples: + // + // * `done:true` - The operation is complete. + // * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata) AND` \ + // `(metadata.source_type:BACKUP) AND` \ + // `(metadata.backup_info.backup:backup_howl) AND` \ + // `(metadata.name:restored_howl) AND` \ + // `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ + // `(error:*)` - Return operations where: + // * The operation's metadata type is + // [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata]. + // * The database is restored from a backup. + // * The backup name contains "backup_howl". + // * The restored database's name contains "restored_howl". + // * The operation started before 2018-03-28T14:50:00Z. + // * The operation resulted in an error. + string filter = 2; + + // Number of operations to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 3; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.database.v1.ListDatabaseOperationsResponse.next_page_token] + // from a previous + // [ListDatabaseOperationsResponse][google.spanner.admin.database.v1.ListDatabaseOperationsResponse] + // to the same `parent` and with the same `filter`. + string page_token = 4; +} + +// The response for +// [ListDatabaseOperations][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseOperations]. +message ListDatabaseOperationsResponse { + // The list of matching database [long-running + // operations][google.longrunning.Operation]. Each operation's name will be + // prefixed by the database's name. The operation's + // [metadata][google.longrunning.Operation.metadata] field type + // `metadata.type_url` describes the type of the metadata. + repeated google.longrunning.Operation operations = 1; + + // `next_page_token` can be sent in a subsequent + // [ListDatabaseOperations][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseOperations] + // call to fetch more of the matching metadata. + string next_page_token = 2; +} + +// The request for +// [RestoreDatabase][google.spanner.admin.database.v1.DatabaseAdmin.RestoreDatabase]. +message RestoreDatabaseRequest { + // Required. The name of the instance in which to create the + // restored database. This instance must be in the same project and + // have the same instance configuration as the instance containing + // the source backup. Values are of the form + // `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Required. The id of the database to create and restore to. This + // database must not already exist. The `database_id` appended to + // `parent` forms the full database name of the form + // `projects//instances//databases/`. + string database_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The source from which to restore. + oneof source { + // Name of the backup from which to restore. Values are of the form + // `projects//instances//backups/`. + string backup = 3 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/Backup" + }]; + } + + // Optional. An encryption configuration describing the encryption type and + // key resources in Cloud KMS used to encrypt/decrypt the database to restore + // to. If this field is not specified, the restored database will use the same + // encryption configuration as the backup by default, namely + // [encryption_type][google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.encryption_type] + // = `USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION`. + RestoreDatabaseEncryptionConfig encryption_config = 4 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Encryption configuration for the restored database. +message RestoreDatabaseEncryptionConfig { + // Encryption types for the database to be restored. + enum EncryptionType { + // Unspecified. Do not use. + ENCRYPTION_TYPE_UNSPECIFIED = 0; + + // This is the default option when + // [encryption_config][google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig] + // is not specified. + USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION = 1; + + // Use Google default encryption. + GOOGLE_DEFAULT_ENCRYPTION = 2; + + // Use customer managed encryption. If specified, `kms_key_name` must + // must contain a valid Cloud KMS key. + CUSTOMER_MANAGED_ENCRYPTION = 3; + } + + // Required. The encryption type of the restored database. + EncryptionType encryption_type = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The Cloud KMS key that will be used to encrypt/decrypt the + // restored database. This field should be set only when + // [encryption_type][google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.encryption_type] + // is `CUSTOMER_MANAGED_ENCRYPTION`. Values are of the form + // `projects//locations//keyRings//cryptoKeys/`. + string kms_key_name = 2 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKey" + } + ]; + + // Optional. Specifies the KMS configuration for the one or more keys used to + // encrypt the database. Values are of the form + // `projects//locations//keyRings//cryptoKeys/`. + // + // The keys referenced by kms_key_names must fully cover all + // regions of the database instance configuration. Some examples: + // * For single region database instance configs, specify a single regional + // location KMS key. + // * For multi-regional database instance configs of type GOOGLE_MANAGED, + // either specify a multi-regional location KMS key or multiple regional + // location KMS keys that cover all regions in the instance config. + // * For a database instance config of type USER_MANAGED, please specify only + // regional location KMS keys to cover each region in the instance config. + // Multi-regional location KMS keys are not supported for USER_MANAGED + // instance configs. + repeated string kms_key_names = 3 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.resource_reference) = { + type: "cloudkms.googleapis.com/CryptoKey" + } + ]; +} + +// Metadata type for the long-running operation returned by +// [RestoreDatabase][google.spanner.admin.database.v1.DatabaseAdmin.RestoreDatabase]. +message RestoreDatabaseMetadata { + // Name of the database being created and restored to. + string name = 1 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + }]; + + // The type of the restore source. + RestoreSourceType source_type = 2; + + // Information about the source used to restore the database, as specified by + // `source` in + // [RestoreDatabaseRequest][google.spanner.admin.database.v1.RestoreDatabaseRequest]. + oneof source_info { + // Information about the backup used to restore the database. + BackupInfo backup_info = 3; + } + + // The progress of the + // [RestoreDatabase][google.spanner.admin.database.v1.DatabaseAdmin.RestoreDatabase] + // operation. + OperationProgress progress = 4; + + // The time at which cancellation of this operation was received. + // [Operations.CancelOperation][google.longrunning.Operations.CancelOperation] + // starts asynchronous cancellation on a long-running operation. The server + // makes a best effort to cancel the operation, but success is not guaranteed. + // Clients can use + // [Operations.GetOperation][google.longrunning.Operations.GetOperation] or + // other methods to check whether the cancellation succeeded or whether the + // operation completed despite cancellation. On successful cancellation, + // the operation is not deleted; instead, it becomes an operation with + // an [Operation.error][google.longrunning.Operation.error] value with a + // [google.rpc.Status.code][google.rpc.Status.code] of 1, corresponding to + // `Code.CANCELLED`. + google.protobuf.Timestamp cancel_time = 5; + + // If exists, the name of the long-running operation that will be used to + // track the post-restore optimization process to optimize the performance of + // the restored database, and remove the dependency on the restore source. + // The name is of the form + // `projects//instances//databases//operations/` + // where the is the name of database being created and restored to. + // The metadata type of the long-running operation is + // [OptimizeRestoredDatabaseMetadata][google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata]. + // This long-running operation will be automatically created by the system + // after the RestoreDatabase long-running operation completes successfully. + // This operation will not be created if the restore was not successful. + string optimize_database_operation_name = 6; +} + +// Metadata type for the long-running operation used to track the progress +// of optimizations performed on a newly restored database. This long-running +// operation is automatically created by the system after the successful +// completion of a database restore, and cannot be cancelled. +message OptimizeRestoredDatabaseMetadata { + // Name of the restored database being optimized. + string name = 1 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + }]; + + // The progress of the post-restore optimizations. + OperationProgress progress = 2; +} + +// Indicates the type of the restore source. +enum RestoreSourceType { + // No restore associated. + TYPE_UNSPECIFIED = 0; + + // A backup was used as the source of the restore. + BACKUP = 1; +} + +// A Cloud Spanner database role. +message DatabaseRole { + option (google.api.resource) = { + type: "spanner.googleapis.com/DatabaseRole" + pattern: "projects/{project}/instances/{instance}/databases/{database}/databaseRoles/{role}" + }; + + // Required. The name of the database role. Values are of the form + // `projects//instances//databases//databaseRoles/` + // where `` is as specified in the `CREATE ROLE` DDL statement. + string name = 1 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [ListDatabaseRoles][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseRoles]. +message ListDatabaseRolesRequest { + // Required. The database whose roles should be listed. + // Values are of the form + // `projects//instances//databases/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Number of database roles to be returned in the response. If 0 or less, + // defaults to the server's maximum allowed page size. + int32 page_size = 2; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.database.v1.ListDatabaseRolesResponse.next_page_token] + // from a previous + // [ListDatabaseRolesResponse][google.spanner.admin.database.v1.ListDatabaseRolesResponse]. + string page_token = 3; +} + +// The response for +// [ListDatabaseRoles][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseRoles]. +message ListDatabaseRolesResponse { + // Database roles that matched the request. + repeated DatabaseRole database_roles = 1; + + // `next_page_token` can be sent in a subsequent + // [ListDatabaseRoles][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseRoles] + // call to fetch more of the matching roles. + string next_page_token = 2; +} + +// The request for +// [AddSplitPoints][google.spanner.admin.database.v1.DatabaseAdmin.AddSplitPoints]. +message AddSplitPointsRequest { + // Required. The database on whose tables/indexes split points are to be + // added. Values are of the form + // `projects//instances//databases/`. + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Required. The split points to add. + repeated SplitPoints split_points = 2 + [(google.api.field_behavior) = REQUIRED]; + + // Optional. A user-supplied tag associated with the split points. + // For example, "intital_data_load", "special_event_1". + // Defaults to "CloudAddSplitPointsAPI" if not specified. + // The length of the tag must not exceed 50 characters,else will be trimmed. + // Only valid UTF8 characters are allowed. + string initiator = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [AddSplitPoints][google.spanner.admin.database.v1.DatabaseAdmin.AddSplitPoints]. +message AddSplitPointsResponse {} + +// The split points of a table/index. +message SplitPoints { + // A split key. + message Key { + // Required. The column values making up the split key. + google.protobuf.ListValue key_parts = 1 + [(google.api.field_behavior) = REQUIRED]; + } + + // The table to split. + string table = 1; + + // The index to split. + // If specified, the `table` field must refer to the index's base table. + string index = 2; + + // Required. The list of split keys, i.e., the split boundaries. + repeated Key keys = 3 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The expiration timestamp of the split points. + // A timestamp in the past means immediate expiration. + // The maximum value can be 30 days in the future. + // Defaults to 10 days in the future if not specified. + google.protobuf.Timestamp expire_time = 5 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Internal request proto, do not use directly. +message InternalUpdateGraphOperationRequest { + // Internal field, do not use directly. + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + // Internal field, do not use directly. + string operation_id = 2 [(google.api.field_behavior) = REQUIRED]; + // Internal field, do not use directly. + string vm_identity_token = 5 [(google.api.field_behavior) = REQUIRED]; + // Internal field, do not use directly. + double progress = 3 [(google.api.field_behavior) = OPTIONAL]; + // Internal field, do not use directly. + google.rpc.Status status = 6 [(google.api.field_behavior) = OPTIONAL]; +} + +// Internal response proto, do not use directly. +message InternalUpdateGraphOperationResponse {} diff --git a/handwritten/spanner/protos/google/spanner/admin/instance/v1/common.proto b/handwritten/spanner/protos/google/spanner/admin/instance/v1/common.proto new file mode 100644 index 00000000000..0b5282c7d87 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/admin/instance/v1/common.proto @@ -0,0 +1,64 @@ +// 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. + +syntax = "proto3"; + +package google.spanner.admin.instance.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.Admin.Instance.V1"; +option go_package = "cloud.google.com/go/spanner/admin/instance/apiv1/instancepb;instancepb"; +option java_multiple_files = true; +option java_outer_classname = "CommonProto"; +option java_package = "com.google.spanner.admin.instance.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\Admin\\Instance\\V1"; +option ruby_package = "Google::Cloud::Spanner::Admin::Instance::V1"; + +// Encapsulates progress related information for a Cloud Spanner long +// running instance operations. +message OperationProgress { + // Percent completion of the operation. + // Values are between 0 and 100 inclusive. + int32 progress_percent = 1; + + // Time the request was received. + google.protobuf.Timestamp start_time = 2; + + // If set, the time at which this operation failed or was completed + // successfully. + google.protobuf.Timestamp end_time = 3; +} + +// Indicates the expected fulfillment period of an operation. +enum FulfillmentPeriod { + // Not specified. + FULFILLMENT_PERIOD_UNSPECIFIED = 0; + + // Normal fulfillment period. The operation is expected to complete within + // minutes. + FULFILLMENT_PERIOD_NORMAL = 1; + + // Extended fulfillment period. It can take up to an hour for the operation + // to complete. + FULFILLMENT_PERIOD_EXTENDED = 2; +} + +// ReplicaSelection identifies replicas with common properties. +message ReplicaSelection { + // Required. Name of the location of the replicas (e.g., "us-central1"). + string location = 1 [(google.api.field_behavior) = REQUIRED]; +} diff --git a/handwritten/spanner/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto b/handwritten/spanner/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto new file mode 100644 index 00000000000..d16ab2ca583 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto @@ -0,0 +1,2184 @@ +// 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. + +syntax = "proto3"; + +package google.spanner.admin.instance.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/iam/v1/iam_policy.proto"; +import "google/iam/v1/policy.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; +import "google/protobuf/timestamp.proto"; +import "google/spanner/admin/instance/v1/common.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.Admin.Instance.V1"; +option go_package = "cloud.google.com/go/spanner/admin/instance/apiv1/instancepb;instancepb"; +option java_multiple_files = true; +option java_outer_classname = "SpannerInstanceAdminProto"; +option java_package = "com.google.spanner.admin.instance.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\Admin\\Instance\\V1"; +option ruby_package = "Google::Cloud::Spanner::Admin::Instance::V1"; + +// Cloud Spanner Instance Admin API +// +// The Cloud Spanner Instance Admin API can be used to create, delete, +// modify and list instances. Instances are dedicated Cloud Spanner serving +// and storage resources to be used by Cloud Spanner databases. +// +// Each instance has a "configuration", which dictates where the +// serving resources for the Cloud Spanner instance are located (e.g., +// US-central, Europe). Configurations are created by Google based on +// resource availability. +// +// Cloud Spanner billing is based on the instances that exist and their +// sizes. After an instance exists, there are no additional +// per-database or per-operation charges for use of the instance +// (though there may be additional network bandwidth charges). +// Instances offer isolation: problems with databases in one instance +// will not affect other instances. However, within an instance +// databases can affect each other. For example, if one database in an +// instance receives a lot of requests and consumes most of the +// instance resources, fewer resources are available for other +// databases in that instance, and their performance may suffer. +service InstanceAdmin { + option (google.api.default_host) = "spanner.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/spanner.admin"; + + // Lists the supported instance configurations for a given project. + // + // Returns both Google-managed configurations and user-managed + // configurations. + rpc ListInstanceConfigs(ListInstanceConfigsRequest) + returns (ListInstanceConfigsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*}/instanceConfigs" + }; + option (google.api.method_signature) = "parent"; + } + + // Gets information about a particular instance configuration. + rpc GetInstanceConfig(GetInstanceConfigRequest) returns (InstanceConfig) { + option (google.api.http) = { + get: "/v1/{name=projects/*/instanceConfigs/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates an instance configuration and begins preparing it to be used. The + // returned long-running operation + // can be used to track the progress of preparing the new + // instance configuration. The instance configuration name is assigned by the + // caller. If the named instance configuration already exists, + // `CreateInstanceConfig` returns `ALREADY_EXISTS`. + // + // Immediately after the request returns: + // + // * The instance configuration is readable via the API, with all requested + // attributes. The instance configuration's + // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] + // field is set to true. Its state is `CREATING`. + // + // While the operation is pending: + // + // * Cancelling the operation renders the instance configuration immediately + // unreadable via the API. + // * Except for deleting the creating resource, all other attempts to modify + // the instance configuration are rejected. + // + // Upon completion of the returned operation: + // + // * Instances can be created using the instance configuration. + // * The instance configuration's + // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] + // field becomes false. Its state becomes `READY`. + // + // The returned long-running operation will + // have a name of the format + // `/operations/` and can be used to track + // creation of the instance configuration. The + // metadata field type is + // [CreateInstanceConfigMetadata][google.spanner.admin.instance.v1.CreateInstanceConfigMetadata]. + // The response field type is + // [InstanceConfig][google.spanner.admin.instance.v1.InstanceConfig], if + // successful. + // + // Authorization requires `spanner.instanceConfigs.create` permission on + // the resource + // [parent][google.spanner.admin.instance.v1.CreateInstanceConfigRequest.parent]. + rpc CreateInstanceConfig(CreateInstanceConfigRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*}/instanceConfigs" + body: "*" + }; + option (google.api.method_signature) = + "parent,instance_config,instance_config_id"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.instance.v1.InstanceConfig" + metadata_type: "google.spanner.admin.instance.v1.CreateInstanceConfigMetadata" + }; + } + + // Updates an instance configuration. The returned + // long-running operation can be used to track + // the progress of updating the instance. If the named instance configuration + // does not exist, returns `NOT_FOUND`. + // + // Only user-managed configurations can be updated. + // + // Immediately after the request returns: + // + // * The instance configuration's + // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] + // field is set to true. + // + // While the operation is pending: + // + // * Cancelling the operation sets its metadata's + // [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.cancel_time]. + // The operation is guaranteed to succeed at undoing all changes, after + // which point it terminates with a `CANCELLED` status. + // * All other attempts to modify the instance configuration are rejected. + // * Reading the instance configuration via the API continues to give the + // pre-request values. + // + // Upon completion of the returned operation: + // + // * Creating instances using the instance configuration uses the new + // values. + // * The new values of the instance configuration are readable via the API. + // * The instance configuration's + // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] + // field becomes false. + // + // The returned long-running operation will + // have a name of the format + // `/operations/` and can be used to track + // the instance configuration modification. The + // metadata field type is + // [UpdateInstanceConfigMetadata][google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata]. + // The response field type is + // [InstanceConfig][google.spanner.admin.instance.v1.InstanceConfig], if + // successful. + // + // Authorization requires `spanner.instanceConfigs.update` permission on + // the resource [name][google.spanner.admin.instance.v1.InstanceConfig.name]. + rpc UpdateInstanceConfig(UpdateInstanceConfigRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{instance_config.name=projects/*/instanceConfigs/*}" + body: "*" + }; + option (google.api.method_signature) = "instance_config,update_mask"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.instance.v1.InstanceConfig" + metadata_type: "google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata" + }; + } + + // Deletes the instance configuration. Deletion is only allowed when no + // instances are using the configuration. If any instances are using + // the configuration, returns `FAILED_PRECONDITION`. + // + // Only user-managed configurations can be deleted. + // + // Authorization requires `spanner.instanceConfigs.delete` permission on + // the resource [name][google.spanner.admin.instance.v1.InstanceConfig.name]. + rpc DeleteInstanceConfig(DeleteInstanceConfigRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/instanceConfigs/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists the user-managed instance configuration long-running + // operations in the given project. An instance + // configuration operation has a name of the form + // `projects//instanceConfigs//operations/`. + // The long-running operation + // metadata field type + // `metadata.type_url` describes the type of the metadata. Operations returned + // include those that have completed/failed/canceled within the last 7 days, + // and pending operations. Operations returned are ordered by + // `operation.metadata.value.start_time` in descending order starting + // from the most recently started operation. + rpc ListInstanceConfigOperations(ListInstanceConfigOperationsRequest) + returns (ListInstanceConfigOperationsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*}/instanceConfigOperations" + }; + option (google.api.method_signature) = "parent"; + } + + // Lists all instances in the given project. + rpc ListInstances(ListInstancesRequest) returns (ListInstancesResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*}/instances" + }; + option (google.api.method_signature) = "parent"; + } + + // Lists all instance partitions for the given instance. + rpc ListInstancePartitions(ListInstancePartitionsRequest) + returns (ListInstancePartitionsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/instances/*}/instancePartitions" + }; + option (google.api.method_signature) = "parent"; + } + + // Gets information about a particular instance. + rpc GetInstance(GetInstanceRequest) returns (Instance) { + option (google.api.http) = { + get: "/v1/{name=projects/*/instances/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates an instance and begins preparing it to begin serving. The + // returned long-running operation + // can be used to track the progress of preparing the new + // instance. The instance name is assigned by the caller. If the + // named instance already exists, `CreateInstance` returns + // `ALREADY_EXISTS`. + // + // Immediately upon completion of this request: + // + // * The instance is readable via the API, with all requested attributes + // but no allocated resources. Its state is `CREATING`. + // + // Until completion of the returned operation: + // + // * Cancelling the operation renders the instance immediately unreadable + // via the API. + // * The instance can be deleted. + // * All other attempts to modify the instance are rejected. + // + // Upon completion of the returned operation: + // + // * Billing for all successfully-allocated resources begins (some types + // may have lower than the requested levels). + // * Databases can be created in the instance. + // * The instance's allocated resource levels are readable via the API. + // * The instance's state becomes `READY`. + // + // The returned long-running operation will + // have a name of the format `/operations/` and + // can be used to track creation of the instance. The + // metadata field type is + // [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. + // The response field type is + // [Instance][google.spanner.admin.instance.v1.Instance], if successful. + rpc CreateInstance(CreateInstanceRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*}/instances" + body: "*" + }; + option (google.api.method_signature) = "parent,instance_id,instance"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.instance.v1.Instance" + metadata_type: "google.spanner.admin.instance.v1.CreateInstanceMetadata" + }; + } + + // Updates an instance, and begins allocating or releasing resources + // as requested. The returned long-running operation can be used to track the + // progress of updating the instance. If the named instance does not + // exist, returns `NOT_FOUND`. + // + // Immediately upon completion of this request: + // + // * For resource types for which a decrease in the instance's allocation + // has been requested, billing is based on the newly-requested level. + // + // Until completion of the returned operation: + // + // * Cancelling the operation sets its metadata's + // [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], + // and begins restoring resources to their pre-request values. The + // operation is guaranteed to succeed at undoing all resource changes, + // after which point it terminates with a `CANCELLED` status. + // * All other attempts to modify the instance are rejected. + // * Reading the instance via the API continues to give the pre-request + // resource levels. + // + // Upon completion of the returned operation: + // + // * Billing begins for all successfully-allocated resources (some types + // may have lower than the requested levels). + // * All newly-reserved resources are available for serving the instance's + // tables. + // * The instance's new resource levels are readable via the API. + // + // The returned long-running operation will + // have a name of the format `/operations/` and + // can be used to track the instance modification. The + // metadata field type is + // [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. + // The response field type is + // [Instance][google.spanner.admin.instance.v1.Instance], if successful. + // + // Authorization requires `spanner.instances.update` permission on + // the resource [name][google.spanner.admin.instance.v1.Instance.name]. + rpc UpdateInstance(UpdateInstanceRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{instance.name=projects/*/instances/*}" + body: "*" + }; + option (google.api.method_signature) = "instance,field_mask"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.instance.v1.Instance" + metadata_type: "google.spanner.admin.instance.v1.UpdateInstanceMetadata" + }; + } + + // Deletes an instance. + // + // Immediately upon completion of the request: + // + // * Billing ceases for all of the instance's reserved resources. + // + // Soon afterward: + // + // * The instance and *all of its databases* immediately and + // irrevocably disappear from the API. All data in the databases + // is permanently deleted. + rpc DeleteInstance(DeleteInstanceRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/instances/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Sets the access control policy on an instance resource. Replaces any + // existing policy. + // + // Authorization requires `spanner.instances.setIamPolicy` on + // [resource][google.iam.v1.SetIamPolicyRequest.resource]. + rpc SetIamPolicy(google.iam.v1.SetIamPolicyRequest) + returns (google.iam.v1.Policy) { + option (google.api.http) = { + post: "/v1/{resource=projects/*/instances/*}:setIamPolicy" + body: "*" + }; + option (google.api.method_signature) = "resource,policy"; + } + + // Gets the access control policy for an instance resource. Returns an empty + // policy if an instance exists but does not have a policy set. + // + // Authorization requires `spanner.instances.getIamPolicy` on + // [resource][google.iam.v1.GetIamPolicyRequest.resource]. + rpc GetIamPolicy(google.iam.v1.GetIamPolicyRequest) + returns (google.iam.v1.Policy) { + option (google.api.http) = { + post: "/v1/{resource=projects/*/instances/*}:getIamPolicy" + body: "*" + }; + option (google.api.method_signature) = "resource"; + } + + // Returns permissions that the caller has on the specified instance resource. + // + // Attempting this RPC on a non-existent Cloud Spanner instance resource will + // result in a NOT_FOUND error if the user has `spanner.instances.list` + // permission on the containing Google Cloud Project. Otherwise returns an + // empty set of permissions. + rpc TestIamPermissions(google.iam.v1.TestIamPermissionsRequest) + returns (google.iam.v1.TestIamPermissionsResponse) { + option (google.api.http) = { + post: "/v1/{resource=projects/*/instances/*}:testIamPermissions" + body: "*" + }; + option (google.api.method_signature) = "resource,permissions"; + } + + // Gets information about a particular instance partition. + rpc GetInstancePartition(GetInstancePartitionRequest) + returns (InstancePartition) { + option (google.api.http) = { + get: "/v1/{name=projects/*/instances/*/instancePartitions/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Creates an instance partition and begins preparing it to be used. The + // returned long-running operation + // can be used to track the progress of preparing the new instance partition. + // The instance partition name is assigned by the caller. If the named + // instance partition already exists, `CreateInstancePartition` returns + // `ALREADY_EXISTS`. + // + // Immediately upon completion of this request: + // + // * The instance partition is readable via the API, with all requested + // attributes but no allocated resources. Its state is `CREATING`. + // + // Until completion of the returned operation: + // + // * Cancelling the operation renders the instance partition immediately + // unreadable via the API. + // * The instance partition can be deleted. + // * All other attempts to modify the instance partition are rejected. + // + // Upon completion of the returned operation: + // + // * Billing for all successfully-allocated resources begins (some types + // may have lower than the requested levels). + // * Databases can start using this instance partition. + // * The instance partition's allocated resource levels are readable via the + // API. + // * The instance partition's state becomes `READY`. + // + // The returned long-running operation will + // have a name of the format + // `/operations/` and can be used to + // track creation of the instance partition. The + // metadata field type is + // [CreateInstancePartitionMetadata][google.spanner.admin.instance.v1.CreateInstancePartitionMetadata]. + // The response field type is + // [InstancePartition][google.spanner.admin.instance.v1.InstancePartition], if + // successful. + rpc CreateInstancePartition(CreateInstancePartitionRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/instances/*}/instancePartitions" + body: "*" + }; + option (google.api.method_signature) = + "parent,instance_partition,instance_partition_id"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.instance.v1.InstancePartition" + metadata_type: "google.spanner.admin.instance.v1.CreateInstancePartitionMetadata" + }; + } + + // Deletes an existing instance partition. Requires that the + // instance partition is not used by any database or backup and is not the + // default instance partition of an instance. + // + // Authorization requires `spanner.instancePartitions.delete` permission on + // the resource + // [name][google.spanner.admin.instance.v1.InstancePartition.name]. + rpc DeleteInstancePartition(DeleteInstancePartitionRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/instances/*/instancePartitions/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates an instance partition, and begins allocating or releasing resources + // as requested. The returned long-running operation can be used to track the + // progress of updating the instance partition. If the named instance + // partition does not exist, returns `NOT_FOUND`. + // + // Immediately upon completion of this request: + // + // * For resource types for which a decrease in the instance partition's + // allocation has been requested, billing is based on the newly-requested + // level. + // + // Until completion of the returned operation: + // + // * Cancelling the operation sets its metadata's + // [cancel_time][google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.cancel_time], + // and begins restoring resources to their pre-request values. The + // operation is guaranteed to succeed at undoing all resource changes, + // after which point it terminates with a `CANCELLED` status. + // * All other attempts to modify the instance partition are rejected. + // * Reading the instance partition via the API continues to give the + // pre-request resource levels. + // + // Upon completion of the returned operation: + // + // * Billing begins for all successfully-allocated resources (some types + // may have lower than the requested levels). + // * All newly-reserved resources are available for serving the instance + // partition's tables. + // * The instance partition's new resource levels are readable via the API. + // + // The returned long-running operation will + // have a name of the format + // `/operations/` and can be used to + // track the instance partition modification. The + // metadata field type is + // [UpdateInstancePartitionMetadata][google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata]. + // The response field type is + // [InstancePartition][google.spanner.admin.instance.v1.InstancePartition], if + // successful. + // + // Authorization requires `spanner.instancePartitions.update` permission on + // the resource + // [name][google.spanner.admin.instance.v1.InstancePartition.name]. + rpc UpdateInstancePartition(UpdateInstancePartitionRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + patch: "/v1/{instance_partition.name=projects/*/instances/*/instancePartitions/*}" + body: "*" + }; + option (google.api.method_signature) = "instance_partition,field_mask"; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.instance.v1.InstancePartition" + metadata_type: "google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata" + }; + } + + // Lists instance partition long-running operations in the given instance. + // An instance partition operation has a name of the form + // `projects//instances//instancePartitions//operations/`. + // The long-running operation + // metadata field type + // `metadata.type_url` describes the type of the metadata. Operations returned + // include those that have completed/failed/canceled within the last 7 days, + // and pending operations. Operations returned are ordered by + // `operation.metadata.value.start_time` in descending order starting from the + // most recently started operation. + // + // Authorization requires `spanner.instancePartitionOperations.list` + // permission on the resource + // [parent][google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest.parent]. + rpc ListInstancePartitionOperations(ListInstancePartitionOperationsRequest) + returns (ListInstancePartitionOperationsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/instances/*}/instancePartitionOperations" + }; + option (google.api.method_signature) = "parent"; + } + + // Moves an instance to the target instance configuration. You can use the + // returned long-running operation to track + // the progress of moving the instance. + // + // `MoveInstance` returns `FAILED_PRECONDITION` if the instance meets any of + // the following criteria: + // + // * Is undergoing a move to a different instance configuration + // * Has backups + // * Has an ongoing update + // * Contains any CMEK-enabled databases + // * Is a free trial instance + // + // While the operation is pending: + // + // * All other attempts to modify the instance, including changes to its + // compute capacity, are rejected. + // * The following database and backup admin operations are rejected: + // + // * `DatabaseAdmin.CreateDatabase` + // * `DatabaseAdmin.UpdateDatabaseDdl` (disabled if default_leader is + // specified in the request.) + // * `DatabaseAdmin.RestoreDatabase` + // * `DatabaseAdmin.CreateBackup` + // * `DatabaseAdmin.CopyBackup` + // + // * Both the source and target instance configurations are subject to + // hourly compute and storage charges. + // * The instance might experience higher read-write latencies and a higher + // transaction abort rate. However, moving an instance doesn't cause any + // downtime. + // + // The returned long-running operation has + // a name of the format + // `/operations/` and can be used to track + // the move instance operation. The + // metadata field type is + // [MoveInstanceMetadata][google.spanner.admin.instance.v1.MoveInstanceMetadata]. + // The response field type is + // [Instance][google.spanner.admin.instance.v1.Instance], + // if successful. + // Cancelling the operation sets its metadata's + // [cancel_time][google.spanner.admin.instance.v1.MoveInstanceMetadata.cancel_time]. + // Cancellation is not immediate because it involves moving any data + // previously moved to the target instance configuration back to the original + // instance configuration. You can use this operation to track the progress of + // the cancellation. Upon successful completion of the cancellation, the + // operation terminates with `CANCELLED` status. + // + // If not cancelled, upon completion of the returned operation: + // + // * The instance successfully moves to the target instance + // configuration. + // * You are billed for compute and storage in target instance + // configuration. + // + // Authorization requires the `spanner.instances.update` permission on + // the resource [instance][google.spanner.admin.instance.v1.Instance]. + // + // For more details, see + // [Move an instance](https://cloud.google.com/spanner/docs/move-instance). + rpc MoveInstance(MoveInstanceRequest) returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=projects/*/instances/*}:move" + body: "*" + }; + option (google.longrunning.operation_info) = { + response_type: "google.spanner.admin.instance.v1.MoveInstanceResponse" + metadata_type: "google.spanner.admin.instance.v1.MoveInstanceMetadata" + }; + } +} + +message ReplicaInfo { + // Indicates the type of replica. See the [replica types + // documentation](https://cloud.google.com/spanner/docs/replication#replica_types) + // for more details. + enum ReplicaType { + // Not specified. + TYPE_UNSPECIFIED = 0; + + // Read-write replicas support both reads and writes. These replicas: + // + // * Maintain a full copy of your data. + // * Serve reads. + // * Can vote whether to commit a write. + // * Participate in leadership election. + // * Are eligible to become a leader. + READ_WRITE = 1; + + // Read-only replicas only support reads (not writes). Read-only replicas: + // + // * Maintain a full copy of your data. + // * Serve reads. + // * Do not participate in voting to commit writes. + // * Are not eligible to become a leader. + READ_ONLY = 2; + + // Witness replicas don't support reads but do participate in voting to + // commit writes. Witness replicas: + // + // * Do not maintain a full copy of data. + // * Do not serve reads. + // * Vote whether to commit writes. + // * Participate in leader election but are not eligible to become leader. + WITNESS = 3; + } + + // The location of the serving resources, e.g., "us-central1". + string location = 1; + + // The type of replica. + ReplicaType type = 2; + + // If true, this location is designated as the default leader location where + // leader replicas are placed. See the [region types + // documentation](https://cloud.google.com/spanner/docs/instances#region_types) + // for more details. + bool default_leader_location = 3; +} + +// A possible configuration for a Cloud Spanner instance. Configurations +// define the geographic placement of nodes and their replication. +message InstanceConfig { + option (google.api.resource) = { + type: "spanner.googleapis.com/InstanceConfig" + pattern: "projects/{project}/instanceConfigs/{instance_config}" + plural: "instanceConfigs" + singular: "instanceConfig" + }; + + // The type of this configuration. + enum Type { + // Unspecified. + TYPE_UNSPECIFIED = 0; + + // Google-managed configuration. + GOOGLE_MANAGED = 1; + + // User-managed configuration. + USER_MANAGED = 2; + } + + // Indicates the current state of the instance configuration. + enum State { + // Not specified. + STATE_UNSPECIFIED = 0; + + // The instance configuration is still being created. + CREATING = 1; + + // The instance configuration is fully created and ready to be used to + // create instances. + READY = 2; + } + + // Describes the availability for free instances to be created in an instance + // configuration. + enum FreeInstanceAvailability { + // Not specified. + FREE_INSTANCE_AVAILABILITY_UNSPECIFIED = 0; + + // Indicates that free instances are available to be created in this + // instance configuration. + AVAILABLE = 1; + + // Indicates that free instances are not supported in this instance + // configuration. + UNSUPPORTED = 2; + + // Indicates that free instances are currently not available to be created + // in this instance configuration. + DISABLED = 3; + + // Indicates that additional free instances cannot be created in this + // instance configuration because the project has reached its limit of free + // instances. + QUOTA_EXCEEDED = 4; + } + + // Indicates the quorum type of this instance configuration. + enum QuorumType { + // Quorum type not specified. + QUORUM_TYPE_UNSPECIFIED = 0; + + // An instance configuration tagged with `REGION` quorum type forms a write + // quorum in a single region. + REGION = 1; + + // An instance configuration tagged with the `DUAL_REGION` quorum type forms + // a write quorum with exactly two read-write regions in a multi-region + // configuration. + // + // This instance configuration requires failover in the event of + // regional failures. + DUAL_REGION = 2; + + // An instance configuration tagged with the `MULTI_REGION` quorum type + // forms a write quorum from replicas that are spread across more than one + // region in a multi-region configuration. + MULTI_REGION = 3; + } + + // A unique identifier for the instance configuration. Values + // are of the form + // `projects//instanceConfigs/[a-z][-a-z0-9]*`. + // + // User instance configuration must start with `custom-`. + string name = 1; + + // The name of this instance configuration as it appears in UIs. + string display_name = 2; + + // Output only. Whether this instance configuration is a Google-managed or + // user-managed configuration. + Type config_type = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // The geographic placement of nodes in this instance configuration and their + // replication properties. + // + // To create user-managed configurations, input + // `replicas` must include all replicas in `replicas` of the `base_config` + // and include one or more replicas in the `optional_replicas` of the + // `base_config`. + repeated ReplicaInfo replicas = 3; + + // Output only. The available optional replicas to choose from for + // user-managed configurations. Populated for Google-managed configurations. + repeated ReplicaInfo optional_replicas = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Base configuration name, e.g. projects//instanceConfigs/nam3, + // based on which this configuration is created. Only set for user-managed + // configurations. `base_config` must refer to a configuration of type + // `GOOGLE_MANAGED` in the same project as this configuration. + string base_config = 7 [(google.api.resource_reference) = { + type: "spanner.googleapis.com/InstanceConfig" + }]; + + // Cloud Labels are a flexible and lightweight mechanism for organizing cloud + // resources into groups that reflect a customer's organizational needs and + // deployment strategies. Cloud Labels can be used to filter collections of + // resources. They can be used to control how resource metrics are aggregated. + // And they can be used as arguments to policy management rules (e.g. route, + // firewall, load balancing, etc.). + // + // * Label keys must be between 1 and 63 characters long and must conform to + // the following regular expression: `[a-z][a-z0-9_-]{0,62}`. + // * Label values must be between 0 and 63 characters long and must conform + // to the regular expression `[a-z0-9_-]{0,63}`. + // * No more than 64 labels can be associated with a given resource. + // + // See https://goo.gl/xmQnxf for more information on and examples of labels. + // + // If you plan to use labels in your own code, please note that additional + // characters may be allowed in the future. Therefore, you are advised to use + // an internal label representation, such as JSON, which doesn't rely upon + // specific characters being disallowed. For example, representing labels + // as the string: name + "_" + value would prove problematic if we were to + // allow "_" in a future release. + map labels = 8; + + // etag is used for optimistic concurrency control as a way + // to help prevent simultaneous updates of a instance configuration from + // overwriting each other. It is strongly suggested that systems make use of + // the etag in the read-modify-write cycle to perform instance configuration + // updates in order to avoid race conditions: An etag is returned in the + // response which contains instance configurations, and systems are expected + // to put that etag in the request to update instance configuration to ensure + // that their change is applied to the same version of the instance + // configuration. If no etag is provided in the call to update the instance + // configuration, then the existing instance configuration is overwritten + // blindly. + string etag = 9; + + // Allowed values of the "default_leader" schema option for databases in + // instances that use this instance configuration. + repeated string leader_options = 4; + + // Output only. If true, the instance configuration is being created or + // updated. If false, there are no ongoing operations for the instance + // configuration. + bool reconciling = 10 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The current instance configuration state. Applicable only for + // `USER_MANAGED` configurations. + State state = 11 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Describes whether free instances are available to be created + // in this instance configuration. + FreeInstanceAvailability free_instance_availability = 12 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The `QuorumType` of the instance configuration. + QuorumType quorum_type = 18 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The storage limit in bytes per processing unit. + int64 storage_limit_per_processing_unit = 19 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// ReplicaComputeCapacity describes the amount of server resources that are +// allocated to each replica identified by the replica selection. +message ReplicaComputeCapacity { + // Required. Identifies replicas by specified properties. + // All replicas in the selection have the same amount of compute capacity. + ReplicaSelection replica_selection = 1 + [(google.api.field_behavior) = REQUIRED]; + + // Compute capacity allocated to each replica identified by the specified + // selection. + // The unit is selected based on the unit used to specify the instance size + // for non-autoscaling instances, or the unit used in autoscaling limit for + // autoscaling instances. + oneof compute_capacity { + // The number of nodes allocated to each replica. + // + // This may be zero in API responses for instances that are not yet in + // state `READY`. + int32 node_count = 2; + + // The number of processing units allocated to each replica. + // + // This may be zero in API responses for instances that are not yet in + // state `READY`. + int32 processing_units = 3; + } +} + +// Autoscaling configuration for an instance. +message AutoscalingConfig { + // The autoscaling limits for the instance. Users can define the minimum and + // maximum compute capacity allocated to the instance, and the autoscaler will + // only scale within that range. Users can either use nodes or processing + // units to specify the limits, but should use the same unit to set both the + // min_limit and max_limit. + message AutoscalingLimits { + // The minimum compute capacity for the instance. + oneof min_limit { + // Minimum number of nodes allocated to the instance. If set, this number + // should be greater than or equal to 1. + int32 min_nodes = 1; + + // Minimum number of processing units allocated to the instance. If set, + // this number should be multiples of 1000. + int32 min_processing_units = 2; + } + + // The maximum compute capacity for the instance. The maximum compute + // capacity should be less than or equal to 10X the minimum compute + // capacity. + oneof max_limit { + // Maximum number of nodes allocated to the instance. If set, this number + // should be greater than or equal to min_nodes. + int32 max_nodes = 3; + + // Maximum number of processing units allocated to the instance. If set, + // this number should be multiples of 1000 and be greater than or equal to + // min_processing_units. + int32 max_processing_units = 4; + } + } + + // The autoscaling targets for an instance. + message AutoscalingTargets { + // Optional. The target high priority cpu utilization percentage that the + // autoscaler should be trying to achieve for the instance. This number is + // on a scale from 0 (no utilization) to 100 (full utilization). The valid + // range is [10, 90] inclusive. If not specified or set to 0, the autoscaler + // skips scaling based on high priority CPU utilization. + int32 high_priority_cpu_utilization_percent = 1 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The target total CPU utilization percentage that the autoscaler + // should be trying to achieve for the instance. This number is on a scale + // from 0 (no utilization) to 100 (full utilization). The valid range is + // [10, 90] inclusive. If not specified or set to 0, the autoscaler skips + // scaling based on total CPU utilization. If both + // `high_priority_cpu_utilization_percent` and + // `total_cpu_utilization_percent` are specified, the autoscaler provisions + // the larger of the two required compute capacities to satisfy both + // targets. + int32 total_cpu_utilization_percent = 4 + [(google.api.field_behavior) = OPTIONAL]; + + // Required. The target storage utilization percentage that the autoscaler + // should be trying to achieve for the instance. This number is on a scale + // from 0 (no utilization) to 100 (full utilization). The valid range is + // [10, 99] inclusive. + int32 storage_utilization_percent = 2 + [(google.api.field_behavior) = REQUIRED]; + } + + // AsymmetricAutoscalingOption specifies the scaling of replicas identified by + // the given selection. + message AsymmetricAutoscalingOption { + // Overrides the top-level autoscaling configuration for the replicas + // identified by `replica_selection`. All fields in this message are + // optional. Any unspecified fields will use the corresponding values from + // the top-level autoscaling configuration. + message AutoscalingConfigOverrides { + // Optional. If specified, overrides the min/max limit in the top-level + // autoscaling configuration for the selected replicas. + AutoscalingLimits autoscaling_limits = 1 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If specified, overrides the autoscaling target + // high_priority_cpu_utilization_percent in the top-level autoscaling + // configuration for the selected replicas. + int32 autoscaling_target_high_priority_cpu_utilization_percent = 2 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If specified, overrides the + // autoscaling target `total_cpu_utilization_percent` + // in the top-level autoscaling configuration for the selected replicas. + int32 autoscaling_target_total_cpu_utilization_percent = 4 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If true, disables high priority CPU autoscaling for the + // selected replicas and ignores + // [high_priority_cpu_utilization_percent][google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.high_priority_cpu_utilization_percent] + // in the top-level autoscaling configuration. + // + // When setting this field to true, setting + // [autoscaling_target_high_priority_cpu_utilization_percent][google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.autoscaling_target_high_priority_cpu_utilization_percent] + // field to a non-zero value for the same replica is not supported. + // + // If false, the + // [autoscaling_target_high_priority_cpu_utilization_percent][google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.autoscaling_target_high_priority_cpu_utilization_percent] + // field in the replica will be used if set to a non-zero value. + // Otherwise, the + // [high_priority_cpu_utilization_percent][google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.high_priority_cpu_utilization_percent] + // field in the top-level autoscaling configuration will be used. + // + // Setting both + // [disable_high_priority_cpu_autoscaling][google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.disable_high_priority_cpu_autoscaling] + // and + // [disable_total_cpu_autoscaling][google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.disable_total_cpu_autoscaling] + // to true for the same replica is not supported. + bool disable_high_priority_cpu_autoscaling = 5 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If true, disables total CPU autoscaling for the selected + // replicas and ignores + // [total_cpu_utilization_percent][google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.total_cpu_utilization_percent] + // in the top-level autoscaling configuration. + // + // When setting this field to true, setting + // [autoscaling_target_total_cpu_utilization_percent][google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.autoscaling_target_total_cpu_utilization_percent] + // field to a non-zero value for the same replica is not supported. + // + // If false, the + // [autoscaling_target_total_cpu_utilization_percent][google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.autoscaling_target_total_cpu_utilization_percent] + // field in the replica will be used if set to a non-zero value. + // Otherwise, the + // [total_cpu_utilization_percent][google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.total_cpu_utilization_percent] + // field in the top-level autoscaling configuration will be used. + // + // Setting both + // [disable_high_priority_cpu_autoscaling][google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.disable_high_priority_cpu_autoscaling] + // and + // [disable_total_cpu_autoscaling][google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.disable_total_cpu_autoscaling] + // to true for the same replica is not supported. + bool disable_total_cpu_autoscaling = 6 + [(google.api.field_behavior) = OPTIONAL]; + } + + // Required. Selects the replicas to which this AsymmetricAutoscalingOption + // applies. Only read-only replicas are supported. + ReplicaSelection replica_selection = 1 + [(google.api.field_behavior) = REQUIRED]; + + // Optional. Overrides applied to the top-level autoscaling configuration + // for the selected replicas. + AutoscalingConfigOverrides overrides = 2 + [(google.api.field_behavior) = OPTIONAL]; + } + + // Required. Autoscaling limits for an instance. + AutoscalingLimits autoscaling_limits = 1 + [(google.api.field_behavior) = REQUIRED]; + + // Required. The autoscaling targets for an instance. + AutoscalingTargets autoscaling_targets = 2 + [(google.api.field_behavior) = REQUIRED]; + + // Optional. Optional asymmetric autoscaling options. + // Replicas matching the replica selection criteria will be autoscaled + // independently from other replicas. The autoscaler will scale the replicas + // based on the utilization of replicas identified by the replica selection. + // Replica selections should not overlap with each other. + // + // Other replicas (those do not match any replica selection) will be + // autoscaled together and will have the same compute capacity allocated to + // them. + repeated AsymmetricAutoscalingOption asymmetric_autoscaling_options = 3 + [(google.api.field_behavior) = OPTIONAL]; +} + +// An isolated set of Cloud Spanner resources on which databases can be hosted. +message Instance { + option (google.api.resource) = { + type: "spanner.googleapis.com/Instance" + pattern: "projects/{project}/instances/{instance}" + plural: "instances" + singular: "instance" + }; + + // Indicates the current state of the instance. + enum State { + // Not specified. + STATE_UNSPECIFIED = 0; + + // The instance is still being created. Resources may not be + // available yet, and operations such as database creation may not + // work. + CREATING = 1; + + // The instance is fully created and ready to do work such as + // creating databases. + READY = 2; + } + + // The type of this instance. The type can be used to distinguish product + // variants, that can affect aspects like: usage restrictions, quotas and + // billing. Currently this is used to distinguish FREE_INSTANCE vs PROVISIONED + // instances. + enum InstanceType { + // Not specified. + INSTANCE_TYPE_UNSPECIFIED = 0; + + // Provisioned instances have dedicated resources, standard usage limits and + // support. + PROVISIONED = 1; + + // Free instances provide no guarantee for dedicated resources, + // [node_count, processing_units] should be 0. They come + // with stricter usage limits and limited support. + FREE_INSTANCE = 2; + } + + // The edition selected for this instance. Different editions provide + // different capabilities at different price points. + enum Edition { + // Edition not specified. + EDITION_UNSPECIFIED = 0; + + // Standard edition. + STANDARD = 1; + + // Enterprise edition. + ENTERPRISE = 2; + + // Enterprise Plus edition. + ENTERPRISE_PLUS = 3; + } + + // Indicates the + // [default backup + // schedule](https://cloud.google.com/spanner/docs/backup#default-backup-schedules) + // behavior for new databases within the instance. + enum DefaultBackupScheduleType { + // Not specified. + DEFAULT_BACKUP_SCHEDULE_TYPE_UNSPECIFIED = 0; + + // A default backup schedule isn't created automatically when a new database + // is created in the instance. + NONE = 1; + + // A default backup schedule is created automatically when a new database + // is created in the instance. The default backup schedule creates a full + // backup every 24 hours. These full backups are retained for 7 days. + // You can edit or delete the default backup schedule once it's created. + AUTOMATIC = 2; + } + + // Required. A unique identifier for the instance, which cannot be changed + // after the instance is created. Values are of the form + // `projects//instances/[a-z][-a-z0-9]*[a-z0-9]`. The final + // segment of the name must be between 2 and 64 characters in length. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The name of the instance's configuration. Values are of the form + // `projects//instanceConfigs/`. See + // also [InstanceConfig][google.spanner.admin.instance.v1.InstanceConfig] and + // [ListInstanceConfigs][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs]. + string config = 2 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/InstanceConfig" + } + ]; + + // Required. The descriptive name for this instance as it appears in UIs. + // Must be unique per project and between 4 and 30 characters in length. + string display_name = 3 [(google.api.field_behavior) = REQUIRED]; + + // The number of nodes allocated to this instance. At most, one of either + // `node_count` or `processing_units` should be present in the message. + // + // Users can set the `node_count` field to specify the target number of nodes + // allocated to the instance. + // + // If autoscaling is enabled, `node_count` is treated as an `OUTPUT_ONLY` + // field and reflects the current number of nodes allocated to the instance. + // + // This might be zero in API responses for instances that are not yet in the + // `READY` state. + // + // + // For more information, see + // [Compute capacity, nodes, and processing + // units](https://cloud.google.com/spanner/docs/compute-capacity). + int32 node_count = 5; + + // The number of processing units allocated to this instance. At most, one of + // either `processing_units` or `node_count` should be present in the message. + // + // Users can set the `processing_units` field to specify the target number of + // processing units allocated to the instance. + // + // If autoscaling is enabled, `processing_units` is treated as an + // `OUTPUT_ONLY` field and reflects the current number of processing units + // allocated to the instance. + // + // This might be zero in API responses for instances that are not yet in the + // `READY` state. + // + // + // For more information, see + // [Compute capacity, nodes and processing + // units](https://cloud.google.com/spanner/docs/compute-capacity). + int32 processing_units = 9; + + // Output only. Lists the compute capacity per ReplicaSelection. A replica + // selection identifies a set of replicas with common properties. Replicas + // identified by a ReplicaSelection are scaled with the same compute capacity. + repeated ReplicaComputeCapacity replica_compute_capacity = 19 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. The autoscaling configuration. Autoscaling is enabled if this + // field is set. When autoscaling is enabled, node_count and processing_units + // are treated as OUTPUT_ONLY fields and reflect the current compute capacity + // allocated to the instance. + AutoscalingConfig autoscaling_config = 17 + [(google.api.field_behavior) = OPTIONAL]; + + // Output only. The current instance state. For + // [CreateInstance][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance], + // the state must be either omitted or set to `CREATING`. For + // [UpdateInstance][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance], + // the state must be either omitted or set to `READY`. + State state = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Cloud Labels are a flexible and lightweight mechanism for organizing cloud + // resources into groups that reflect a customer's organizational needs and + // deployment strategies. Cloud Labels can be used to filter collections of + // resources. They can be used to control how resource metrics are aggregated. + // And they can be used as arguments to policy management rules (e.g. route, + // firewall, load balancing, etc.). + // + // * Label keys must be between 1 and 63 characters long and must conform to + // the following regular expression: `[a-z][a-z0-9_-]{0,62}`. + // * Label values must be between 0 and 63 characters long and must conform + // to the regular expression `[a-z0-9_-]{0,63}`. + // * No more than 64 labels can be associated with a given resource. + // + // See https://goo.gl/xmQnxf for more information on and examples of labels. + // + // If you plan to use labels in your own code, please note that additional + // characters may be allowed in the future. And so you are advised to use an + // internal label representation, such as JSON, which doesn't rely upon + // specific characters being disallowed. For example, representing labels + // as the string: name + "_" + value would prove problematic if we were to + // allow "_" in a future release. + map labels = 7; + + // The `InstanceType` of the current instance. + InstanceType instance_type = 10; + + // Deprecated. This field is not populated. + repeated string endpoint_uris = 8; + + // Output only. The time at which the instance was created. + google.protobuf.Timestamp create_time = 11 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The time at which the instance was most recently updated. + google.protobuf.Timestamp update_time = 12 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Free instance metadata. Only populated for free instances. + FreeInstanceMetadata free_instance_metadata = 13; + + // Optional. The `Edition` of the current instance. + Edition edition = 20 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Controls the default backup schedule behavior for new databases + // within the instance. By default, a backup schedule is created automatically + // when a new database is created in a new instance. + // + // Note that the `AUTOMATIC` value isn't permitted for free instances, + // as backups and backup schedules aren't supported for free instances. + // + // In the `GetInstance` or `ListInstances` response, if the value of + // `default_backup_schedule_type` isn't set, or set to `NONE`, Spanner doesn't + // create a default backup schedule for new databases in the instance. + DefaultBackupScheduleType default_backup_schedule_type = 23 + [(google.api.field_behavior) = OPTIONAL]; +} + +// The request for +// [ListInstanceConfigs][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs]. +message ListInstanceConfigsRequest { + // Required. The name of the project for which a list of supported instance + // configurations is requested. Values are of the form + // `projects/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudresourcemanager.googleapis.com/Project" + } + ]; + + // Number of instance configurations to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 2; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.instance.v1.ListInstanceConfigsResponse.next_page_token] + // from a previous + // [ListInstanceConfigsResponse][google.spanner.admin.instance.v1.ListInstanceConfigsResponse]. + string page_token = 3; +} + +// The response for +// [ListInstanceConfigs][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs]. +message ListInstanceConfigsResponse { + // The list of requested instance configurations. + repeated InstanceConfig instance_configs = 1; + + // `next_page_token` can be sent in a subsequent + // [ListInstanceConfigs][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs] + // call to fetch more of the matching instance configurations. + string next_page_token = 2; +} + +// The request for +// [GetInstanceConfigRequest][google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig]. +message GetInstanceConfigRequest { + // Required. The name of the requested instance configuration. Values are of + // the form `projects//instanceConfigs/`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/InstanceConfig" + } + ]; +} + +// The request for +// [CreateInstanceConfig][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceConfig]. +message CreateInstanceConfigRequest { + // Required. The name of the project in which to create the instance + // configuration. Values are of the form `projects/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudresourcemanager.googleapis.com/Project" + } + ]; + + // Required. The ID of the instance configuration to create. Valid identifiers + // are of the form `custom-[-a-z0-9]*[a-z0-9]` and must be between 2 and 64 + // characters in length. The `custom-` prefix is required to avoid name + // conflicts with Google-managed configurations. + string instance_config_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The `InstanceConfig` proto of the configuration to create. + // `instance_config.name` must be + // `/instanceConfigs/`. + // `instance_config.base_config` must be a Google-managed configuration name, + // e.g. /instanceConfigs/us-east1, /instanceConfigs/nam3. + InstanceConfig instance_config = 3 [(google.api.field_behavior) = REQUIRED]; + + // An option to validate, but not actually execute, a request, + // and provide the same response. + bool validate_only = 4; +} + +// The request for +// [UpdateInstanceConfig][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceConfig]. +message UpdateInstanceConfigRequest { + // Required. The user instance configuration to update, which must always + // include the instance configuration name. Otherwise, only fields mentioned + // in + // [update_mask][google.spanner.admin.instance.v1.UpdateInstanceConfigRequest.update_mask] + // need be included. To prevent conflicts of concurrent updates, + // [etag][google.spanner.admin.instance.v1.InstanceConfig.reconciling] can + // be used. + InstanceConfig instance_config = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. A mask specifying which fields in + // [InstanceConfig][google.spanner.admin.instance.v1.InstanceConfig] should be + // updated. The field mask must always be specified; this prevents any future + // fields in [InstanceConfig][google.spanner.admin.instance.v1.InstanceConfig] + // from being erased accidentally by clients that do not know about them. Only + // display_name and labels can be updated. + google.protobuf.FieldMask update_mask = 2 + [(google.api.field_behavior) = REQUIRED]; + + // An option to validate, but not actually execute, a request, + // and provide the same response. + bool validate_only = 3; +} + +// The request for +// [DeleteInstanceConfig][google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstanceConfig]. +message DeleteInstanceConfigRequest { + // Required. The name of the instance configuration to be deleted. + // Values are of the form + // `projects//instanceConfigs/` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/InstanceConfig" + } + ]; + + // Used for optimistic concurrency control as a way to help prevent + // simultaneous deletes of an instance configuration from overwriting each + // other. If not empty, the API + // only deletes the instance configuration when the etag provided matches the + // current status of the requested instance configuration. Otherwise, deletes + // the instance configuration without checking the current status of the + // requested instance configuration. + string etag = 2; + + // An option to validate, but not actually execute, a request, + // and provide the same response. + bool validate_only = 3; +} + +// The request for +// [ListInstanceConfigOperations][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigOperations]. +message ListInstanceConfigOperationsRequest { + // Required. The project of the instance configuration operations. + // Values are of the form `projects/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudresourcemanager.googleapis.com/Project" + } + ]; + + // An expression that filters the list of returned operations. + // + // A filter expression consists of a field name, a + // comparison operator, and a value for filtering. + // The value must be a string, a number, or a boolean. The comparison operator + // must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + // Colon `:` is the contains operator. Filter rules are not case sensitive. + // + // The following fields in the Operation are eligible for filtering: + // + // * `name` - The name of the long-running operation + // * `done` - False if the operation is in progress, else true. + // * `metadata.@type` - the type of metadata. For example, the type string + // for + // [CreateInstanceConfigMetadata][google.spanner.admin.instance.v1.CreateInstanceConfigMetadata] + // is + // `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata`. + // * `metadata.` - any field in metadata.value. + // `metadata.@type` must be specified first, if filtering on metadata + // fields. + // * `error` - Error associated with the long-running operation. + // * `response.@type` - the type of response. + // * `response.` - any field in response.value. + // + // You can combine multiple expressions by enclosing each expression in + // parentheses. By default, expressions are combined with AND logic. However, + // you can specify AND, OR, and NOT logic explicitly. + // + // Here are a few examples: + // + // * `done:true` - The operation is complete. + // * `(metadata.@type=` \ + // `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata) + // AND` \ + // `(metadata.instance_config.name:custom-config) AND` \ + // `(metadata.progress.start_time < \"2021-03-28T14:50:00Z\") AND` \ + // `(error:*)` - Return operations where: + // * The operation's metadata type is + // [CreateInstanceConfigMetadata][google.spanner.admin.instance.v1.CreateInstanceConfigMetadata]. + // * The instance configuration name contains "custom-config". + // * The operation started before 2021-03-28T14:50:00Z. + // * The operation resulted in an error. + string filter = 2; + + // Number of operations to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 3; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.next_page_token] + // from a previous + // [ListInstanceConfigOperationsResponse][google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse] + // to the same `parent` and with the same `filter`. + string page_token = 4; +} + +// The response for +// [ListInstanceConfigOperations][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigOperations]. +message ListInstanceConfigOperationsResponse { + // The list of matching instance configuration long-running operations. Each + // operation's name will be + // prefixed by the name of the instance configuration. The operation's + // metadata field type + // `metadata.type_url` describes the type of the metadata. + repeated google.longrunning.Operation operations = 1; + + // `next_page_token` can be sent in a subsequent + // [ListInstanceConfigOperations][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigOperations] + // call to fetch more of the matching metadata. + string next_page_token = 2; +} + +// The request for +// [GetInstance][google.spanner.admin.instance.v1.InstanceAdmin.GetInstance]. +message GetInstanceRequest { + // Required. The name of the requested instance. Values are of the form + // `projects//instances/`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // If field_mask is present, specifies the subset of + // [Instance][google.spanner.admin.instance.v1.Instance] fields that should be + // returned. If absent, all + // [Instance][google.spanner.admin.instance.v1.Instance] fields are returned. + google.protobuf.FieldMask field_mask = 2; +} + +// The request for +// [CreateInstance][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance]. +message CreateInstanceRequest { + // Required. The name of the project in which to create the instance. Values + // are of the form `projects/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudresourcemanager.googleapis.com/Project" + } + ]; + + // Required. The ID of the instance to create. Valid identifiers are of the + // form `[a-z][-a-z0-9]*[a-z0-9]` and must be between 2 and 64 characters in + // length. + string instance_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The instance to create. The name may be omitted, but if + // specified must be `/instances/`. + Instance instance = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [ListInstances][google.spanner.admin.instance.v1.InstanceAdmin.ListInstances]. +message ListInstancesRequest { + // Required. The name of the project for which a list of instances is + // requested. Values are of the form `projects/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudresourcemanager.googleapis.com/Project" + } + ]; + + // Number of instances to be returned in the response. If 0 or less, defaults + // to the server's maximum allowed page size. + int32 page_size = 2; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.instance.v1.ListInstancesResponse.next_page_token] + // from a previous + // [ListInstancesResponse][google.spanner.admin.instance.v1.ListInstancesResponse]. + string page_token = 3; + + // An expression for filtering the results of the request. Filter rules are + // case insensitive. The fields eligible for filtering are: + // + // * `name` + // * `display_name` + // * `labels.key` where key is the name of a label + // + // Some examples of using filters are: + // + // * `name:*` --> The instance has a name. + // * `name:Howl` --> The instance's name contains the string "howl". + // * `name:HOWL` --> Equivalent to above. + // * `NAME:howl` --> Equivalent to above. + // * `labels.env:*` --> The instance has the label "env". + // * `labels.env:dev` --> The instance has the label "env" and the value of + // the label contains the string "dev". + // * `name:howl labels.env:dev` --> The instance's name contains "howl" and + // it has the label "env" with its value + // containing "dev". + string filter = 4; + + // Deadline used while retrieving metadata for instances. + // Instances whose metadata cannot be retrieved within this deadline will be + // added to + // [unreachable][google.spanner.admin.instance.v1.ListInstancesResponse.unreachable] + // in + // [ListInstancesResponse][google.spanner.admin.instance.v1.ListInstancesResponse]. + google.protobuf.Timestamp instance_deadline = 5; +} + +// The response for +// [ListInstances][google.spanner.admin.instance.v1.InstanceAdmin.ListInstances]. +message ListInstancesResponse { + // The list of requested instances. + repeated Instance instances = 1; + + // `next_page_token` can be sent in a subsequent + // [ListInstances][google.spanner.admin.instance.v1.InstanceAdmin.ListInstances] + // call to fetch more of the matching instances. + string next_page_token = 2; + + // The list of unreachable instances. + // It includes the names of instances whose metadata could not be retrieved + // within + // [instance_deadline][google.spanner.admin.instance.v1.ListInstancesRequest.instance_deadline]. + repeated string unreachable = 3; +} + +// The request for +// [UpdateInstance][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance]. +message UpdateInstanceRequest { + // Required. The instance to update, which must always include the instance + // name. Otherwise, only fields mentioned in + // [field_mask][google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask] + // need be included. + Instance instance = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. A mask specifying which fields in + // [Instance][google.spanner.admin.instance.v1.Instance] should be updated. + // The field mask must always be specified; this prevents any future fields in + // [Instance][google.spanner.admin.instance.v1.Instance] from being erased + // accidentally by clients that do not know about them. + google.protobuf.FieldMask field_mask = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [DeleteInstance][google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance]. +message DeleteInstanceRequest { + // Required. The name of the instance to be deleted. Values are of the form + // `projects//instances/` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; +} + +// Metadata type for the operation returned by +// [CreateInstance][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance]. +message CreateInstanceMetadata { + // The instance being created. + Instance instance = 1; + + // The time at which the + // [CreateInstance][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance] + // request was received. + google.protobuf.Timestamp start_time = 2; + + // The time at which this operation was cancelled. If set, this operation is + // in the process of undoing itself (which is guaranteed to succeed) and + // cannot be cancelled again. + google.protobuf.Timestamp cancel_time = 3; + + // The time at which this operation failed or was completed successfully. + google.protobuf.Timestamp end_time = 4; + + // The expected fulfillment period of this create operation. + FulfillmentPeriod expected_fulfillment_period = 5; +} + +// Metadata type for the operation returned by +// [UpdateInstance][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance]. +message UpdateInstanceMetadata { + // The desired end state of the update. + Instance instance = 1; + + // The time at which + // [UpdateInstance][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance] + // request was received. + google.protobuf.Timestamp start_time = 2; + + // The time at which this operation was cancelled. If set, this operation is + // in the process of undoing itself (which is guaranteed to succeed) and + // cannot be cancelled again. + google.protobuf.Timestamp cancel_time = 3; + + // The time at which this operation failed or was completed successfully. + google.protobuf.Timestamp end_time = 4; + + // The expected fulfillment period of this update operation. + FulfillmentPeriod expected_fulfillment_period = 5; +} + +// Free instance specific metadata that is kept even after an instance has been +// upgraded for tracking purposes. +message FreeInstanceMetadata { + // Allows users to change behavior when a free instance expires. + enum ExpireBehavior { + // Not specified. + EXPIRE_BEHAVIOR_UNSPECIFIED = 0; + + // When the free instance expires, upgrade the instance to a provisioned + // instance. + FREE_TO_PROVISIONED = 1; + + // When the free instance expires, disable the instance, and delete it + // after the grace period passes if it has not been upgraded. + REMOVE_AFTER_GRACE_PERIOD = 2; + } + + // Output only. Timestamp after which the instance will either be upgraded or + // scheduled for deletion after a grace period. ExpireBehavior is used to + // choose between upgrading or scheduling the free instance for deletion. This + // timestamp is set during the creation of a free instance. + google.protobuf.Timestamp expire_time = 1 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. If present, the timestamp at which the free instance was + // upgraded to a provisioned instance. + google.protobuf.Timestamp upgrade_time = 2 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Specifies the expiration behavior of a free instance. The default of + // ExpireBehavior is `REMOVE_AFTER_GRACE_PERIOD`. This can be modified during + // or after creation, and before expiration. + ExpireBehavior expire_behavior = 3; +} + +// Metadata type for the operation returned by +// [CreateInstanceConfig][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceConfig]. +message CreateInstanceConfigMetadata { + // The target instance configuration end state. + InstanceConfig instance_config = 1; + + // The progress of the + // [CreateInstanceConfig][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceConfig] + // operation. + OperationProgress progress = 2; + + // The time at which this operation was cancelled. + google.protobuf.Timestamp cancel_time = 3; +} + +// Metadata type for the operation returned by +// [UpdateInstanceConfig][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceConfig]. +message UpdateInstanceConfigMetadata { + // The desired instance configuration after updating. + InstanceConfig instance_config = 1; + + // The progress of the + // [UpdateInstanceConfig][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceConfig] + // operation. + OperationProgress progress = 2; + + // The time at which this operation was cancelled. + google.protobuf.Timestamp cancel_time = 3; +} + +// An isolated set of Cloud Spanner resources that databases can define +// placements on. +message InstancePartition { + option (google.api.resource) = { + type: "spanner.googleapis.com/InstancePartition" + pattern: "projects/{project}/instances/{instance}/instancePartitions/{instance_partition}" + plural: "instancePartitions" + singular: "instancePartition" + }; + + // Indicates the current state of the instance partition. + enum State { + // Not specified. + STATE_UNSPECIFIED = 0; + + // The instance partition is still being created. Resources may not be + // available yet, and operations such as creating placements using this + // instance partition may not work. + CREATING = 1; + + // The instance partition is fully created and ready to do work such as + // creating placements and using in databases. + READY = 2; + } + + // Required. A unique identifier for the instance partition. Values are of the + // form + // `projects//instances//instancePartitions/[a-z][-a-z0-9]*[a-z0-9]`. + // The final segment of the name must be between 2 and 64 characters in + // length. An instance partition's name cannot be changed after the instance + // partition is created. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The name of the instance partition's configuration. Values are of + // the form `projects//instanceConfigs/`. See also + // [InstanceConfig][google.spanner.admin.instance.v1.InstanceConfig] and + // [ListInstanceConfigs][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs]. + string config = 2 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/InstanceConfig" + } + ]; + + // Required. The descriptive name for this instance partition as it appears in + // UIs. Must be unique per project and between 4 and 30 characters in length. + string display_name = 3 [(google.api.field_behavior) = REQUIRED]; + + // Compute capacity defines amount of server and storage resources that are + // available to the databases in an instance partition. At most, one of either + // `node_count` or` processing_units` should be present in the message. For + // more information, see + // [Compute capacity, nodes, and processing + // units](https://cloud.google.com/spanner/docs/compute-capacity). + oneof compute_capacity { + // The number of nodes allocated to this instance partition. + // + // Users can set the `node_count` field to specify the target number of + // nodes allocated to the instance partition. + // + // This may be zero in API responses for instance partitions that are not + // yet in state `READY`. + int32 node_count = 5; + + // The number of processing units allocated to this instance partition. + // + // Users can set the `processing_units` field to specify the target number + // of processing units allocated to the instance partition. + // + // This might be zero in API responses for instance partitions that are not + // yet in the `READY` state. + int32 processing_units = 6; + } + + // Optional. The autoscaling configuration. Autoscaling is enabled if this + // field is set. When autoscaling is enabled, fields in compute_capacity are + // treated as OUTPUT_ONLY fields and reflect the current compute capacity + // allocated to the instance partition. + AutoscalingConfig autoscaling_config = 13 + [(google.api.field_behavior) = OPTIONAL]; + + // Output only. The current instance partition state. + State state = 7 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The time at which the instance partition was created. + google.protobuf.Timestamp create_time = 8 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The time at which the instance partition was most recently + // updated. + google.protobuf.Timestamp update_time = 9 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The names of the databases that reference this + // instance partition. Referencing databases should share the parent instance. + // The existence of any referencing database prevents the instance partition + // from being deleted. + repeated string referencing_databases = 10 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Deprecated: This field is not populated. + // Output only. The names of the backups that reference this instance + // partition. Referencing backups should share the parent instance. The + // existence of any referencing backup prevents the instance partition from + // being deleted. + repeated string referencing_backups = 11 + [deprecated = true, (google.api.field_behavior) = OUTPUT_ONLY]; + + // Used for optimistic concurrency control as a way + // to help prevent simultaneous updates of a instance partition from + // overwriting each other. It is strongly suggested that systems make use of + // the etag in the read-modify-write cycle to perform instance partition + // updates in order to avoid race conditions: An etag is returned in the + // response which contains instance partitions, and systems are expected to + // put that etag in the request to update instance partitions to ensure that + // their change will be applied to the same version of the instance partition. + // If no etag is provided in the call to update instance partition, then the + // existing instance partition is overwritten blindly. + string etag = 12; +} + +// Metadata type for the operation returned by +// [CreateInstancePartition][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstancePartition]. +message CreateInstancePartitionMetadata { + // The instance partition being created. + InstancePartition instance_partition = 1; + + // The time at which the + // [CreateInstancePartition][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstancePartition] + // request was received. + google.protobuf.Timestamp start_time = 2; + + // The time at which this operation was cancelled. If set, this operation is + // in the process of undoing itself (which is guaranteed to succeed) and + // cannot be cancelled again. + google.protobuf.Timestamp cancel_time = 3; + + // The time at which this operation failed or was completed successfully. + google.protobuf.Timestamp end_time = 4; +} + +// The request for +// [CreateInstancePartition][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstancePartition]. +message CreateInstancePartitionRequest { + // Required. The name of the instance in which to create the instance + // partition. Values are of the form + // `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Required. The ID of the instance partition to create. Valid identifiers are + // of the form `[a-z][-a-z0-9]*[a-z0-9]` and must be between 2 and 64 + // characters in length. + string instance_partition_id = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The instance partition to create. The instance_partition.name may + // be omitted, but if specified must be + // `/instancePartitions/`. + InstancePartition instance_partition = 3 + [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [DeleteInstancePartition][google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstancePartition]. +message DeleteInstancePartitionRequest { + // Required. The name of the instance partition to be deleted. + // Values are of the form + // `projects/{project}/instances/{instance}/instancePartitions/{instance_partition}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/InstancePartition" + } + ]; + + // Optional. If not empty, the API only deletes the instance partition when + // the etag provided matches the current status of the requested instance + // partition. Otherwise, deletes the instance partition without checking the + // current status of the requested instance partition. + string etag = 2; +} + +// The request for +// [GetInstancePartition][google.spanner.admin.instance.v1.InstanceAdmin.GetInstancePartition]. +message GetInstancePartitionRequest { + // Required. The name of the requested instance partition. Values are of + // the form + // `projects/{project}/instances/{instance}/instancePartitions/{instance_partition}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/InstancePartition" + } + ]; +} + +// The request for +// [UpdateInstancePartition][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstancePartition]. +message UpdateInstancePartitionRequest { + // Required. The instance partition to update, which must always include the + // instance partition name. Otherwise, only fields mentioned in + // [field_mask][google.spanner.admin.instance.v1.UpdateInstancePartitionRequest.field_mask] + // need be included. + InstancePartition instance_partition = 1 + [(google.api.field_behavior) = REQUIRED]; + + // Required. A mask specifying which fields in + // [InstancePartition][google.spanner.admin.instance.v1.InstancePartition] + // should be updated. The field mask must always be specified; this prevents + // any future fields in + // [InstancePartition][google.spanner.admin.instance.v1.InstancePartition] + // from being erased accidentally by clients that do not know about them. + google.protobuf.FieldMask field_mask = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// Metadata type for the operation returned by +// [UpdateInstancePartition][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstancePartition]. +message UpdateInstancePartitionMetadata { + // The desired end state of the update. + InstancePartition instance_partition = 1; + + // The time at which + // [UpdateInstancePartition][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstancePartition] + // request was received. + google.protobuf.Timestamp start_time = 2; + + // The time at which this operation was cancelled. If set, this operation is + // in the process of undoing itself (which is guaranteed to succeed) and + // cannot be cancelled again. + google.protobuf.Timestamp cancel_time = 3; + + // The time at which this operation failed or was completed successfully. + google.protobuf.Timestamp end_time = 4; +} + +// The request for +// [ListInstancePartitions][google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitions]. +message ListInstancePartitionsRequest { + // Required. The instance whose instance partitions should be listed. Values + // are of the form `projects//instances/`. Use `{instance} + // = '-'` to list instance partitions for all Instances in a project, e.g., + // `projects/myproject/instances/-`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Number of instance partitions to be returned in the response. If 0 or less, + // defaults to the server's maximum allowed page size. + int32 page_size = 2; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.instance.v1.ListInstancePartitionsResponse.next_page_token] + // from a previous + // [ListInstancePartitionsResponse][google.spanner.admin.instance.v1.ListInstancePartitionsResponse]. + string page_token = 3; + + // Optional. Deadline used while retrieving metadata for instance partitions. + // Instance partitions whose metadata cannot be retrieved within this deadline + // will be added to + // [unreachable][google.spanner.admin.instance.v1.ListInstancePartitionsResponse.unreachable] + // in + // [ListInstancePartitionsResponse][google.spanner.admin.instance.v1.ListInstancePartitionsResponse]. + google.protobuf.Timestamp instance_partition_deadline = 4 + [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [ListInstancePartitions][google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitions]. +message ListInstancePartitionsResponse { + // The list of requested instancePartitions. + repeated InstancePartition instance_partitions = 1; + + // `next_page_token` can be sent in a subsequent + // [ListInstancePartitions][google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitions] + // call to fetch more of the matching instance partitions. + string next_page_token = 2; + + // The list of unreachable instances or instance partitions. + // It includes the names of instances or instance partitions whose metadata + // could not be retrieved within + // [instance_partition_deadline][google.spanner.admin.instance.v1.ListInstancePartitionsRequest.instance_partition_deadline]. + repeated string unreachable = 3; +} + +// The request for +// [ListInstancePartitionOperations][google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitionOperations]. +message ListInstancePartitionOperationsRequest { + // Required. The parent instance of the instance partition operations. + // Values are of the form `projects//instances/`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Optional. An expression that filters the list of returned operations. + // + // A filter expression consists of a field name, a + // comparison operator, and a value for filtering. + // The value must be a string, a number, or a boolean. The comparison operator + // must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + // Colon `:` is the contains operator. Filter rules are not case sensitive. + // + // The following fields in the Operation are eligible for filtering: + // + // * `name` - The name of the long-running operation + // * `done` - False if the operation is in progress, else true. + // * `metadata.@type` - the type of metadata. For example, the type string + // for + // [CreateInstancePartitionMetadata][google.spanner.admin.instance.v1.CreateInstancePartitionMetadata] + // is + // `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata`. + // * `metadata.` - any field in metadata.value. + // `metadata.@type` must be specified first, if filtering on metadata + // fields. + // * `error` - Error associated with the long-running operation. + // * `response.@type` - the type of response. + // * `response.` - any field in response.value. + // + // You can combine multiple expressions by enclosing each expression in + // parentheses. By default, expressions are combined with AND logic. However, + // you can specify AND, OR, and NOT logic explicitly. + // + // Here are a few examples: + // + // * `done:true` - The operation is complete. + // * `(metadata.@type=` \ + // `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata) + // AND` \ + // `(metadata.instance_partition.name:custom-instance-partition) AND` \ + // `(metadata.start_time < \"2021-03-28T14:50:00Z\") AND` \ + // `(error:*)` - Return operations where: + // * The operation's metadata type is + // [CreateInstancePartitionMetadata][google.spanner.admin.instance.v1.CreateInstancePartitionMetadata]. + // * The instance partition name contains "custom-instance-partition". + // * The operation started before 2021-03-28T14:50:00Z. + // * The operation resulted in an error. + string filter = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Number of operations to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.next_page_token] + // from a previous + // [ListInstancePartitionOperationsResponse][google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse] + // to the same `parent` and with the same `filter`. + string page_token = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Deadline used while retrieving metadata for instance partition + // operations. Instance partitions whose operation metadata cannot be + // retrieved within this deadline will be added to + // [unreachable_instance_partitions][google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.unreachable_instance_partitions] + // in + // [ListInstancePartitionOperationsResponse][google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse]. + google.protobuf.Timestamp instance_partition_deadline = 5 + [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [ListInstancePartitionOperations][google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitionOperations]. +message ListInstancePartitionOperationsResponse { + // The list of matching instance partition long-running operations. Each + // operation's name will be + // prefixed by the instance partition's name. The operation's + // metadata field type + // `metadata.type_url` describes the type of the metadata. + repeated google.longrunning.Operation operations = 1; + + // `next_page_token` can be sent in a subsequent + // [ListInstancePartitionOperations][google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitionOperations] + // call to fetch more of the matching metadata. + string next_page_token = 2; + + // The list of unreachable instance partitions. + // It includes the names of instance partitions whose operation metadata could + // not be retrieved within + // [instance_partition_deadline][google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest.instance_partition_deadline]. + repeated string unreachable_instance_partitions = 3; +} + +// The request for +// [MoveInstance][google.spanner.admin.instance.v1.InstanceAdmin.MoveInstance]. +message MoveInstanceRequest { + // Required. The instance to move. + // Values are of the form `projects//instances/`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Instance" + } + ]; + + // Required. The target instance configuration where to move the instance. + // Values are of the form `projects//instanceConfigs/`. + string target_config = 2 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/InstanceConfig" + } + ]; +} + +// The response for +// [MoveInstance][google.spanner.admin.instance.v1.InstanceAdmin.MoveInstance]. +message MoveInstanceResponse {} + +// Metadata type for the operation returned by +// [MoveInstance][google.spanner.admin.instance.v1.InstanceAdmin.MoveInstance]. +message MoveInstanceMetadata { + // The target instance configuration where to move the instance. + // Values are of the form `projects//instanceConfigs/`. + string target_config = 1; + + // The progress of the + // [MoveInstance][google.spanner.admin.instance.v1.InstanceAdmin.MoveInstance] + // operation. + // [progress_percent][google.spanner.admin.instance.v1.OperationProgress.progress_percent] + // is reset when cancellation is requested. + OperationProgress progress = 2; + + // The time at which this operation was cancelled. + google.protobuf.Timestamp cancel_time = 3; +} diff --git a/handwritten/spanner/protos/google/spanner/executor/v1/cloud_executor.proto b/handwritten/spanner/protos/google/spanner/executor/v1/cloud_executor.proto new file mode 100644 index 00000000000..5ca3b25ac2a --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/executor/v1/cloud_executor.proto @@ -0,0 +1,1604 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.executor.v1; + +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/timestamp.proto"; +import "google/rpc/status.proto"; +import "google/spanner/admin/database/v1/backup.proto"; +import "google/spanner/admin/database/v1/common.proto"; +import "google/spanner/admin/database/v1/spanner_database_admin.proto"; +import "google/spanner/admin/instance/v1/spanner_instance_admin.proto"; +import "google/spanner/v1/spanner.proto"; +import "google/spanner/v1/type.proto"; + +option go_package = "cloud.google.com/go/spanner/executor/apiv1/executorpb;executorpb"; +option java_multiple_files = true; +option java_outer_classname = "CloudExecutorProto"; +option java_package = "com.google.spanner.executor.v1"; + +// Service that executes SpannerActions asynchronously. +service SpannerExecutorProxy { + option (google.api.default_host) = "spanner-cloud-executor.googleapis.com"; + + // ExecuteActionAsync is a streaming call that starts executing a new Spanner + // action. + // + // For each request, the server will reply with one or more responses, but + // only the last response will contain status in the outcome. + // + // Responses can be matched to requests by action_id. It is allowed to have + // multiple actions in flight--in that case, actions are be executed in + // parallel. + rpc ExecuteActionAsync(stream SpannerAsyncActionRequest) + returns (stream SpannerAsyncActionResponse) {} +} + +// Request to executor service that start a new Spanner action. +message SpannerAsyncActionRequest { + // Action id to uniquely identify this action request. + int32 action_id = 1; + + // The actual SpannerAction to perform. + SpannerAction action = 2; +} + +// Response from executor service. +message SpannerAsyncActionResponse { + // Action id corresponds to the request. + int32 action_id = 1; + + // If action results are split into multiple responses, only the last response + // can and should contain status. + SpannerActionOutcome outcome = 2; +} + +// SpannerAction defines a primitive action that can be performed against +// Spanner, such as begin or commit a transaction, or perform a read or +// mutation. +message SpannerAction { + // Database against which to perform action. + // In a context where a series of actions take place, an action may omit + // database path if it applies to the same database as the previous action. + string database_path = 1; + + // Configuration options for Spanner backend + SpannerOptions spanner_options = 2; + + // Action represents a spanner action kind, there will only be one action kind + // per SpannerAction. + oneof action { + // Action to start a transaction. + StartTransactionAction start = 10; + + // Action to finish a transaction. + FinishTransactionAction finish = 11; + + // Action to do a normal read. + ReadAction read = 20; + + // Action to do a query. + QueryAction query = 21; + + // Action to buffer a mutation. + MutationAction mutation = 22; + + // Action to a DML. + DmlAction dml = 23; + + // Action to a batch DML. + BatchDmlAction batch_dml = 24; + + // Action to write a mutation. + WriteMutationsAction write = 25; + + // Action to a partitioned update. + PartitionedUpdateAction partitioned_update = 27; + + // Action that contains any administrative operation, like database, + // instance manipulation. + AdminAction admin = 30; + + // Action to start a batch transaction. + StartBatchTransactionAction start_batch_txn = 40; + + // Action to close a batch transaction. + CloseBatchTransactionAction close_batch_txn = 41; + + // Action to generate database partitions for batch read. + GenerateDbPartitionsForReadAction generate_db_partitions_read = 42; + + // Action to generate database partitions for batch query. + GenerateDbPartitionsForQueryAction generate_db_partitions_query = 43; + + // Action to execute batch actions on generated partitions. + ExecutePartitionAction execute_partition = 44; + + // Action to execute change stream query. + ExecuteChangeStreamQuery execute_change_stream_query = 50; + + // Query cancellation action for testing the cancellation of a query. + QueryCancellationAction query_cancellation = 51; + + // Action to adapt a message. + AdaptMessageAction adapt_message = 52; + } +} + +// A single read request. +message ReadAction { + // The table to read at. + string table = 1; + + // The index to read at if it's an index read. + optional string index = 2; + + // List of columns must begin with the key columns used for the read. + repeated string column = 3; + + // Keys for performing this read. + KeySet keys = 4; + + // Limit on number of rows to read. If set, must be positive. + int32 limit = 5; +} + +// A SQL query request. +message QueryAction { + // Parameter that bind to placeholders in the SQL string + message Parameter { + // Name of the parameter (with no leading @). + string name = 1; + + // Type of the parameter. + google.spanner.v1.Type type = 2; + + // Value of the parameter. + Value value = 3; + } + + // The SQL string. + string sql = 1; + + // Parameters for the SQL string. + repeated Parameter params = 2; +} + +// A single DML statement. +message DmlAction { + // DML statement. + QueryAction update = 1; + + // Whether to autocommit the transaction after executing the DML statement, + // if the Executor supports autocommit. + optional bool autocommit_if_supported = 2; + + // Whether to set this DML statement as the last statement in the + // transaction. The transaction should be committed after processing this DML + // statement. + optional bool last_statement = 3; +} + +// Batch of DML statements invoked using batched execution. +message BatchDmlAction { + // DML statements. + repeated QueryAction updates = 1; + + // Whether to set this request with the last statement option in the + // transaction. The transaction should be committed after processing this + // request. + optional bool last_statements = 2; +} + +// Value represents a single value that can be read or written to/from +// Spanner. +message Value { + // Exactly one of the following fields will be present. + oneof value_type { + // If is_null is set, then this value is null. + bool is_null = 1; + + // Int type value. It's used for all integer number types, like int32 and + // int64. + int64 int_value = 2; + + // Bool type value. + bool bool_value = 3; + + // Double type value. It's used for all float point types, like float and + // double. + double double_value = 4; + + // Bytes type value, stored in CORD. It's also used for PROTO type value. + bytes bytes_value = 5; + + // String type value, stored in CORD. + string string_value = 6; + + // Struct type value. It contains a ValueList representing the values in + // this struct. + ValueList struct_value = 7; + + // Timestamp type value. + google.protobuf.Timestamp timestamp_value = 8; + + // Date type value. Date is specified as a number of days since Unix epoch. + int32 date_days_value = 9; + + // If set, holds the sentinel value for the transaction CommitTimestamp. + bool is_commit_timestamp = 10; + + // Array type value. The underlying Valuelist should have values that have + // the same type. + ValueList array_value = 11; + } + + // Type of array element. Only set if value is an array. + optional google.spanner.v1.Type array_type = 12; +} + +// KeyRange represents a range of rows in a table or index. +// +// A range has a start key and an end key. These keys can be open or +// closed, indicating if the range includes rows with that key. +// +// Keys are represented by "ValueList", where the ith value in the list +// corresponds to the ith component of the table or index primary key. +message KeyRange { + // Type controls whether "start" and "limit" are open or closed. By default, + // "start" is closed, and "limit" is open. + enum Type { + // "TYPE_UNSPECIFIED" is equivalent to "CLOSED_OPEN". + TYPE_UNSPECIFIED = 0; + + // [start,limit] + CLOSED_CLOSED = 1; + + // [start,limit) + CLOSED_OPEN = 2; + + // (start,limit] + OPEN_CLOSED = 3; + + // (start,limit) + OPEN_OPEN = 4; + } + + // "start" and "limit" must have the same number of key parts, + // though they may name only a prefix of the table or index key. + // The start key of this KeyRange. + ValueList start = 1; + + // The end key of this KeyRange. + ValueList limit = 2; + + // "start" and "limit" type for this KeyRange. + optional Type type = 3; +} + +// KeySet defines a collection of Spanner keys and/or key ranges. All +// the keys are expected to be in the same table. The keys need not be +// sorted in any particular way. +message KeySet { + // A list of specific keys. Entries in "keys" should have exactly as + // many elements as there are columns in the primary or index key + // with which this "KeySet" is used. + repeated ValueList point = 1; + + // A list of key ranges. + repeated KeyRange range = 2; + + // For convenience "all" can be set to "true" to indicate that this + // "KeySet" matches all keys in the table or index. Note that any keys + // specified in "keys" or "ranges" are only yielded once. + bool all = 3; +} + +// List of values. +message ValueList { + // Values contained in this ValueList. + repeated Value value = 1; +} + +// A single mutation request. +message MutationAction { + // Arguments to Insert, InsertOrUpdate, and Replace operations. + message InsertArgs { + // The names of the columns to be written. + repeated string column = 1; + + // Type information for the "values" entries below. + repeated google.spanner.v1.Type type = 2; + + // The values to be written. + repeated ValueList values = 3; + } + + // Arguments to Update. + message UpdateArgs { + // The columns to be updated. Identical to InsertArgs.column. + repeated string column = 1; + + // Type information for "values". Identical to InsertArgs.type. + repeated google.spanner.v1.Type type = 2; + + // The values to be updated. Identical to InsertArgs.values. + repeated ValueList values = 3; + } + + // Mod represents the write action that will be perform to a table. Each mod + // will specify exactly one action, from insert, update, insert_or_update, + // replace and delete. + message Mod { + // The table to write. + string table = 1; + + // Exactly one of the remaining elements may be present. + // Insert new rows into "table". + InsertArgs insert = 2; + + // Update columns stored in existing rows of "table". + UpdateArgs update = 3; + + // Insert or update existing rows of "table". + InsertArgs insert_or_update = 4; + + // Replace existing rows of "table". + InsertArgs replace = 5; + + // Delete rows from "table". + KeySet delete_keys = 6; + } + + // Mods that contained in this mutation. + repeated Mod mod = 1; +} + +// WriteMutationAction defines an action of flushing the mutation so they +// are visible to subsequent operations in the transaction. +message WriteMutationsAction { + // The mutation to write. + MutationAction mutation = 1; +} + +// PartitionedUpdateAction defines an action to execute a partitioned DML +// which runs different partitions in parallel. +message PartitionedUpdateAction { + message ExecutePartitionedUpdateOptions { + // RPC Priority + optional google.spanner.v1.RequestOptions.Priority rpc_priority = 1; + + // Transaction tag + optional string tag = 2; + } + + // Options for partitioned update. + optional ExecutePartitionedUpdateOptions options = 1; + + // Partitioned dml query. + QueryAction update = 2; +} + +// StartTransactionAction defines an action of initializing a transaction. +message StartTransactionAction { + // Concurrency is for read-only transactions and must be omitted for + // read-write transactions. + optional Concurrency concurrency = 1; + + // Metadata about tables and columns that will be involved in this + // transaction. It is to convert values of key parts correctly. + repeated TableMetadata table = 2; + + // Transaction_seed contains workid and op pair for this transaction, used for + // testing. + string transaction_seed = 3; + + // Execution options (e.g., whether transaction is opaque, optimistic, + // excluded from change streams). + optional TransactionExecutionOptions execution_options = 4; +} + +// Concurrency for read-only transactions. +message Concurrency { + // Concurrency mode set for read-only transactions, exactly one mode below + // should be set. + oneof concurrency_mode { + // Indicates a read at a consistent timestamp that is specified relative to + // now. That is, if the caller has specified an exact staleness of s + // seconds, we will read at now - s. + double staleness_seconds = 1; + + // Indicates a boundedly stale read that reads at a timestamp >= T. + int64 min_read_timestamp_micros = 2; + + // Indicates a boundedly stale read that is at most N seconds stale. + double max_staleness_seconds = 3; + + // Indicates a read at a consistent timestamp. + int64 exact_timestamp_micros = 4; + + // Indicates a strong read, must only be set to true, or unset. + bool strong = 5; + + // Indicates a batch read, must only be set to true, or unset. + bool batch = 6; + } + + // True if exact_timestamp_micros is set, and the chosen timestamp is that of + // a snapshot epoch. + bool snapshot_epoch_read = 7; + + // If set, this is a snapshot epoch read constrained to read only the + // specified log scope root table, and its children. Will not be set for full + // database epochs. + string snapshot_epoch_root_table = 8; + + // Set only when batch is true. + int64 batch_read_timestamp_micros = 9; +} + +// TableMetadata contains metadata of a single table. +message TableMetadata { + // Table name. + string name = 1; + + // Columns, in the same order as in the schema. + repeated ColumnMetadata column = 2; + + // Keys, in order. Column name is currently not populated. + repeated ColumnMetadata key_column = 3; +} + +// ColumnMetadata represents metadata of a single column. +message ColumnMetadata { + // Column name. + string name = 1; + + // Column type. + google.spanner.v1.Type type = 2; +} + +message TransactionExecutionOptions { + // Whether optimistic concurrency should be used to execute this transaction. + bool optimistic = 1; + + // Whether traffic from this transaction will be excluded from tracking change + // streams with allow_txn_exclusion=true. + bool exclude_from_change_streams = 2; + + // Whether serializable isolation with optimistic mode concurrency should be + // used to execute this transaction. + bool serializable_optimistic = 3; + + // Whether snapshot isolation with optimistic mode concurrency should be used + // to execute this transaction. + bool snapshot_isolation_optimistic = 4; + + // Whether snapshot isolation with pessimistic mode concurrency should be used + // to execute this transaction. + bool snapshot_isolation_pessimistic = 5; + + // Whether to exclude mutations of this transaction from the allowed tracking + // change streams. + bool exclude_txn_from_change_streams = 6; +} + +// FinishTransactionAction defines an action of finishing a transaction. +message FinishTransactionAction { + // Mode indicates how the transaction should be finished. + enum Mode { + // "MODE_UNSPECIFIED" is equivalent to "COMMIT". + MODE_UNSPECIFIED = 0; + + // Commit the transaction. + COMMIT = 1; + + // Drop the transaction without committing it. + ABANDON = 2; + } + + // Defines how exactly the transaction should be completed, e.g. with + // commit or abortion. + Mode mode = 1; +} + +// AdminAction defines all the cloud spanner admin actions, including +// instance/database admin ops, backup ops and operation actions. +message AdminAction { + // Exactly one of the actions below will be performed in AdminAction. + oneof action { + // Action that creates a user instance config. + CreateUserInstanceConfigAction create_user_instance_config = 1; + + // Action that updates a user instance config. + UpdateUserInstanceConfigAction update_user_instance_config = 2; + + // Action that deletes a user instance config. + DeleteUserInstanceConfigAction delete_user_instance_config = 3; + + // Action that gets a user instance config. + GetCloudInstanceConfigAction get_cloud_instance_config = 4; + + // Action that lists user instance configs. + ListCloudInstanceConfigsAction list_instance_configs = 5; + + // Action that creates a Cloud Spanner instance. + CreateCloudInstanceAction create_cloud_instance = 6; + + // Action that updates a Cloud Spanner instance. + UpdateCloudInstanceAction update_cloud_instance = 7; + + // Action that deletes a Cloud Spanner instance. + DeleteCloudInstanceAction delete_cloud_instance = 8; + + // Action that lists Cloud Spanner instances. + ListCloudInstancesAction list_cloud_instances = 9; + + // Action that retrieves a Cloud Spanner instance. + GetCloudInstanceAction get_cloud_instance = 10; + + // Action that creates a Cloud Spanner database. + CreateCloudDatabaseAction create_cloud_database = 11; + + // Action that updates the schema of a Cloud Spanner database. + UpdateCloudDatabaseDdlAction update_cloud_database_ddl = 12; + + // Action that updates the schema of a Cloud Spanner database. + UpdateCloudDatabaseAction update_cloud_database = 27; + + // Action that drops a Cloud Spanner database. + DropCloudDatabaseAction drop_cloud_database = 13; + + // Action that lists Cloud Spanner databases. + ListCloudDatabasesAction list_cloud_databases = 14; + + // Action that lists Cloud Spanner database operations. + ListCloudDatabaseOperationsAction list_cloud_database_operations = 15; + + // Action that restores a Cloud Spanner database from a backup. + RestoreCloudDatabaseAction restore_cloud_database = 16; + + // Action that gets a Cloud Spanner database. + GetCloudDatabaseAction get_cloud_database = 17; + + // Action that creates a Cloud Spanner database backup. + CreateCloudBackupAction create_cloud_backup = 18; + + // Action that copies a Cloud Spanner database backup. + CopyCloudBackupAction copy_cloud_backup = 19; + + // Action that gets a Cloud Spanner database backup. + GetCloudBackupAction get_cloud_backup = 20; + + // Action that updates a Cloud Spanner database backup. + UpdateCloudBackupAction update_cloud_backup = 21; + + // Action that deletes a Cloud Spanner database backup. + DeleteCloudBackupAction delete_cloud_backup = 22; + + // Action that lists Cloud Spanner database backups. + ListCloudBackupsAction list_cloud_backups = 23; + + // Action that lists Cloud Spanner database backup operations. + ListCloudBackupOperationsAction list_cloud_backup_operations = 24; + + // Action that gets an operation. + GetOperationAction get_operation = 25; + + // Action that cancels an operation. + CancelOperationAction cancel_operation = 26; + + // Action that changes quorum of a Cloud Spanner database. + ChangeQuorumCloudDatabaseAction change_quorum_cloud_database = 28; + + // Action that adds splits to a Cloud Spanner database. + AddSplitPointsAction add_split_points = 29; + } +} + +// Action that creates a user instance config. +message CreateUserInstanceConfigAction { + // User instance config ID (not path), e.g. "custom-config". + string user_config_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; + + // Base config ID, e.g. "test-config". + string base_config_id = 3; + + // Replicas that should be included in the user config. + repeated google.spanner.admin.instance.v1.ReplicaInfo replicas = 4; +} + +// Action that updates a user instance config. +message UpdateUserInstanceConfigAction { + // User instance config ID (not path), e.g. "custom-config". + string user_config_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; + + // The descriptive name for this instance config as it appears in UIs. + optional string display_name = 3; + + // labels. + map labels = 4; +} + +// Action that gets a user instance config. +message GetCloudInstanceConfigAction { + // Instance config ID (not path), e.g. "custom-config". + string instance_config_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; +} + +// Action that deletes a user instance configs. +message DeleteUserInstanceConfigAction { + // User instance config ID (not path), e.g. "custom-config". + string user_config_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; +} + +// Action that lists user instance configs. +message ListCloudInstanceConfigsAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Number of instance configs to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + optional int32 page_size = 2; + + // If non-empty, "page_token" should contain a next_page_token + // from a previous ListInstanceConfigsResponse to the same "parent". + optional string page_token = 3; +} + +// Action that creates a Cloud Spanner instance. +message CreateCloudInstanceAction { + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; + + // Instance config ID, e.g. "test-config". + string instance_config_id = 3; + + // Number of nodes (processing_units should not be set or set to 0 if used). + optional int32 node_count = 4; + + // Number of processing units (node_count should be set to 0 if used). + optional int32 processing_units = 6; + + // The autoscaling config for this instance. If non-empty, an autoscaling + // instance will be created (processing_units and node_count should be set to + // 0 if used). + optional google.spanner.admin.instance.v1.AutoscalingConfig + autoscaling_config = 7; + + // labels. + map labels = 5; + + // The edition of the instance. + google.spanner.admin.instance.v1.Instance.Edition edition = 8; +} + +// Action that updates a Cloud Spanner instance. +message UpdateCloudInstanceAction { + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; + + // The descriptive name for this instance as it appears in UIs. + // Must be unique per project and between 4 and 30 characters in length. + optional string display_name = 3; + + // The number of nodes allocated to this instance. At most one of either + // node_count or processing_units should be present in the message. + optional int32 node_count = 4; + + // The number of processing units allocated to this instance. At most one of + // processing_units or node_count should be present in the message. + optional int32 processing_units = 5; + + // The autoscaling config for this instance. If non-empty, this instance is + // using autoscaling (processing_units and node_count should be set to + // 0 if used). + optional google.spanner.admin.instance.v1.AutoscalingConfig + autoscaling_config = 7; + + // labels. + map labels = 6; + + // The edition of the instance. + google.spanner.admin.instance.v1.Instance.Edition edition = 8; +} + +// Action that deletes a Cloud Spanner instance. +message DeleteCloudInstanceAction { + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; +} + +// Action that creates a Cloud Spanner database. +message CreateCloudDatabaseAction { + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; + + // Cloud database ID (not full path), e.g. "db0". + string database_id = 3; + + // SDL statements to apply to the new database. + repeated string sdl_statement = 4; + + // The KMS key used to encrypt the database to be created if the database + // should be CMEK protected. + google.spanner.admin.database.v1.EncryptionConfig encryption_config = 5; + + // Optional SQL dialect (GOOGLESQL or POSTGRESQL). Default: GOOGLESQL. + optional string dialect = 6; + + optional bytes proto_descriptors = 7; +} + +// Action that updates the schema of a Cloud Spanner database. +message UpdateCloudDatabaseDdlAction { + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; + + // Cloud database ID (not full path), e.g. "db0". + string database_id = 3; + + // SDL statements to apply to the database. + repeated string sdl_statement = 4; + + // Op ID can be used to track progress of the update. If set, it must be + // unique per database. If not set, Cloud Spanner will generate operation ID + // automatically. + string operation_id = 5; + + optional bytes proto_descriptors = 6; +} + +// Action that updates a Cloud Spanner database. +message UpdateCloudDatabaseAction { + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; + + // Cloud database name (not full path), e.g. "db0". + string database_name = 3; + + // Updated value of enable_drop_protection, this is the only field that has + // supported to be updated. + bool enable_drop_protection = 4; +} + +// Action that drops a Cloud Spanner database. +message DropCloudDatabaseAction { + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 1; + + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 2; + + // Cloud database ID (not full path), e.g. "db0". + string database_id = 3; +} + +// Action that changes quorum of a Cloud Spanner database. +message ChangeQuorumCloudDatabaseAction { + // The fully qualified uri of the database whose quorum has to be changed. + optional string database_uri = 1; + + // The locations of the serving regions, e.g. "asia-south1". + repeated string serving_locations = 2; +} + +// A single Adapt message request. +message AdaptMessageAction { + // The fully qualified uri of the database to send AdaptMessage to. + string database_uri = 1; + + // The protocol to use for the request. + string protocol = 2; + + // The payload of the request. + bytes payload = 3; + + // Attachments to be sent with the request. + map attachments = 4; + + // The query to be sent with the request. + string query = 5; + + // If true, the action will send a Prepare request first and then an + // Execute request right after to execute the query. This is only supported + // for Cloud Client path. + bool prepare_then_execute = 6; +} + +// Action that lists Cloud Spanner databases. +message ListCloudDatabasesAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path) to list databases from, e.g. "test-instance". + string instance_id = 2; + + // Number of databases to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 3; + + // If non-empty, "page_token" should contain a next_page_token + // from a previous ListDatabasesResponse to the same "parent" + // and with the same "filter". + string page_token = 4; +} + +// Action that lists Cloud Spanner instances. +message ListCloudInstancesAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // A filter expression that filters what operations are returned in the + // response. + // The expression must specify the field name, a comparison operator, + // and the value that you want to use for filtering. + // Refer spanner_instance_admin.proto.ListInstancesRequest for + // detail. + optional string filter = 2; + + // Number of instances to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + optional int32 page_size = 3; + + // If non-empty, "page_token" should contain a next_page_token + // from a previous ListInstancesResponse to the same "parent" + // and with the same "filter". + optional string page_token = 4; +} + +// Action that retrieves a Cloud Spanner instance. +message GetCloudInstanceAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path) to retrieve the instance from, + // e.g. "test-instance". + string instance_id = 2; +} + +// Action that lists Cloud Spanner database operations. +message ListCloudDatabaseOperationsAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path) to list database operations from, + // e.g. "test-instance". + string instance_id = 2; + + // A filter expression that filters what operations are returned in the + // response. + // The expression must specify the field name, a comparison operator, + // and the value that you want to use for filtering. + // Refer spanner_database_admin.proto.ListDatabaseOperationsRequest for + // detail. + string filter = 3; + + // Number of databases to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 4; + + // If non-empty, "page_token" should contain a next_page_token + // from a previous ListDatabaseOperationsResponse to the same "parent" + // and with the same "filter". + string page_token = 5; +} + +// Action that restores a Cloud Spanner database from a backup. +message RestoreCloudDatabaseAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path) containing the backup, e.g. "backup-instance". + string backup_instance_id = 2; + + // The id of the backup from which to restore, e.g. "test-backup". + string backup_id = 3; + + // Cloud instance ID (not path) containing the database, e.g. + // "database-instance". + string database_instance_id = 4; + + // The id of the database to create and restore to, e.g. "db0". Note that this + // database must not already exist. + string database_id = 5; + + // The KMS key(s) used to encrypt the restored database to be created if the + // restored database should be CMEK protected. + google.spanner.admin.database.v1.EncryptionConfig encryption_config = 7; +} + +// Action that gets a Cloud Spanner database. +message GetCloudDatabaseAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 2; + + // The id of the database to get, e.g. "db0". + string database_id = 3; +} + +// Action that creates a Cloud Spanner database backup. +message CreateCloudBackupAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 2; + + // The id of the backup to be created, e.g. "test-backup". + string backup_id = 3; + + // The id of the database from which this backup was + // created, e.g. "db0". Note that this needs to be in the + // same instance as the backup. + string database_id = 4; + + // Output only. The expiration time of the backup, which must be at least 6 + // hours and at most 366 days from the time the request is received. + google.protobuf.Timestamp expire_time = 5 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // The version time of the backup, which must be within the time range of + // [earliest_version_time, NOW], where earliest_version_time is retrieved by + // cloud spanner frontend API (See details: go/cs-pitr-lite-design). + optional google.protobuf.Timestamp version_time = 6; + + // The KMS key(s) used to encrypt the backup to be created if the backup + // should be CMEK protected. + google.spanner.admin.database.v1.EncryptionConfig encryption_config = 7; +} + +// Action that copies a Cloud Spanner database backup. +message CopyCloudBackupAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 2; + + // The id of the backup to be created, e.g. "test-backup". + string backup_id = 3; + + // The fully qualified uri of the source backup from which this + // backup was copied. eg. + // "projects//instances//backups/". + string source_backup = 4; + + // Output only. The expiration time of the backup, which must be at least 6 + // hours and at most 366 days from the time the request is received. + google.protobuf.Timestamp expire_time = 5 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// Action that gets a Cloud Spanner database backup. +message GetCloudBackupAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 2; + + // The id of the backup to get, e.g. "test-backup". + string backup_id = 3; +} + +// Action that updates a Cloud Spanner database backup. +message UpdateCloudBackupAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 2; + + // The id of the backup to update, e.g. "test-backup". + string backup_id = 3; + + // Output only. Updated value of expire_time, this is the only field + // that supported to be updated. + google.protobuf.Timestamp expire_time = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// Action that deletes a Cloud Spanner database backup. +message DeleteCloudBackupAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 2; + + // The id of the backup to delete, e.g. "test-backup". + string backup_id = 3; +} + +// Action that lists Cloud Spanner database backups. +message ListCloudBackupsAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path) to list backups from, e.g. "test-instance". + string instance_id = 2; + + // A filter expression that filters backups listed in the response. + // The expression must specify the field name, a comparison operator, + // and the value that you want to use for filtering. + // Refer backup.proto.ListBackupsRequest for detail. + string filter = 3; + + // Number of backups to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 4; + + // If non-empty, "page_token" should contain a next_page_token + // from a previous ListBackupsResponse to the same "parent" + // and with the same "filter". + string page_token = 5; +} + +// Action that lists Cloud Spanner database backup operations. +message ListCloudBackupOperationsAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path) to list backup operations from, + // e.g. "test-instance". + string instance_id = 2; + + // A filter expression that filters what operations are returned in the + // response. + // The expression must specify the field name, a comparison operator, + // and the value that you want to use for filtering. + // Refer backup.proto.ListBackupOperationsRequest for detail. + string filter = 3; + + // Number of backups to be returned in the response. If 0 or + // less, defaults to the server's maximum allowed page size. + int32 page_size = 4; + + // If non-empty, "page_token" should contain a next_page_token + // from a previous ListBackupOperationsResponse to the same "parent" + // and with the same "filter". + string page_token = 5; +} + +// Action that gets an operation. +message GetOperationAction { + // The name of the operation resource. + string operation = 1; +} + +// Query cancellation action defines the long running query and the cancel query +// format depening on the Cloud database dialect. +message QueryCancellationAction { + // Long running query. + string long_running_sql = 1; + + // Format of the cancel query for the cloud database dialect. + string cancel_query = 2; +} + +// Action that cancels an operation. +message CancelOperationAction { + // The name of the operation resource to be cancelled. + string operation = 1; +} + +// Action that adds a split point to a Cloud Spanner database. +message AddSplitPointsAction { + // Cloud project ID, e.g. "spanner-cloud-systest". + string project_id = 1; + + // Cloud instance ID (not path), e.g. "test-instance". + string instance_id = 2; + + // Cloud database ID (not full path), e.g. "db0". + string database_id = 3; + + // The split points to add. + repeated google.spanner.admin.database.v1.SplitPoints split_points = 4; +} + +// Starts a batch read-only transaction in executor. Successful outcomes of this +// action will contain batch_txn_id--the identificator that can be used to start +// the same transaction in other Executors to parallelize partition processing. +// +// Example of a batch read flow: +// 1. Start batch transaction with a timestamp (StartBatchTransactionAction) +// 2. Generate database partitions for a read or query +// (GenerateDbPartitionsForReadAction/GenerateDbPartitionsForQueryAction) +// 3. Call ExecutePartitionAction for some or all partitions, process rows +// 4. Clean up the transaction (CloseBatchTransactionAction). +// +// More sophisticated example, with parallel processing: +// 1. Start batch transaction with a timestamp (StartBatchTransactionAction), +// note the returned BatchTransactionId +// 2. Generate database partitions for a read or query +// (GenerateDbPartitionsForReadAction/GenerateDbPartitionsForQueryAction) +// 3. Distribute the partitions over a pool of workers, along with the +// transaction ID. +// +// In each worker: +// 4-1. StartBatchTransactionAction with the given transaction ID +// 4-2. ExecutePartitionAction for each partition it got, process read results +// 4-3. Close (not cleanup) the transaction (CloseBatchTransactionAction). +// +// When all workers are done: +// 5. Cleanup the transaction (CloseBatchTransactionAction). This can be done +// either by the last worker to finish the job, or by the main Executor that +// initialized this transaction in the first place. It is also possible to clean +// it up with a brand new Executor -- just execute StartBatchTransactionAction +// with the ID, then clean it up right away. +// +// Cleaning up is optional, but recommended. +message StartBatchTransactionAction { + // To start a new transaction, specify an exact timestamp. Alternatively, an + // existing batch transaction ID can be used. Either one of two must be + // set. + oneof param { + // The exact timestamp to start the batch transaction. + google.protobuf.Timestamp batch_txn_time = 1; + + // ID of a batch read-only transaction. It can be used to start the same + // batch transaction on multiple executors and parallelize partition + // processing. + bytes tid = 2; + } + + // Database role to assume while performing this action. Setting the + // database_role will enforce additional role-based access checks on this + // action. + string cloud_database_role = 3; +} + +// Closes or cleans up the currently opened batch read-only transaction. +// +// Once a transaction is closed, the Executor can be disposed of or used to +// start start another transaction. Closing a batch transaction in one Executor +// doesn't affect the transaction's state in other Executors that also read from +// it. +// +// When a transaction is cleaned up, it becomes globally invalid. Cleaning up is +// optional, but recommended. +message CloseBatchTransactionAction { + // Indicates whether the transaction needs to be cleaned up. + bool cleanup = 1; +} + +// Generate database partitions for the given read. Successful outcomes will +// contain database partitions in the db_partition field. +message GenerateDbPartitionsForReadAction { + // Read to generate partitions for. + ReadAction read = 1; + + // Metadata related to the tables involved in the read. + repeated TableMetadata table = 2; + + // Desired size of data in each partition. Spanner doesn't guarantee to + // respect this value. + optional int64 desired_bytes_per_partition = 3; + + // If set, the desired max number of partitions. Spanner doesn't guarantee to + // respect this value. + optional int64 max_partition_count = 4; +} + +// Generate database partitions for the given query. Successful outcomes will +// contain database partitions in the db_partition field. +message GenerateDbPartitionsForQueryAction { + // Query to generate partitions for. + QueryAction query = 1; + + // Desired size of data in each partition. Spanner doesn't guarantee to + // respect this value. + optional int64 desired_bytes_per_partition = 2; +} + +// Identifies a database partition generated for a particular read or query. To +// read rows from the partition, use ExecutePartitionAction. +message BatchPartition { + // Serialized Partition instance. + bytes partition = 1; + + // The partition token decrypted from partition. + bytes partition_token = 2; + + // Table name is set iff the partition was generated for a read (as opposed to + // a query). + optional string table = 3; + + // Index name if the partition was generated for an index read. + optional string index = 4; +} + +// Performs a read or query for the given partitions. This action must be +// executed in the context of the same transaction that was used to generate +// given partitions. +message ExecutePartitionAction { + // Batch partition to execute on. + BatchPartition partition = 1; +} + +// Execute a change stream TVF query. +message ExecuteChangeStreamQuery { + // Name for this change stream. + string name = 1; + + // Specifies that records with commit_timestamp greater than or equal to + // start_time should be returned. + google.protobuf.Timestamp start_time = 2; + + // Specifies that records with commit_timestamp less than or equal to + // end_time should be returned. + optional google.protobuf.Timestamp end_time = 3; + + // Specifies which change stream partition to query, based on the content of + // child partitions records. + optional string partition_token = 4; + + // Read options for this change stream query. + repeated string read_options = 5; + + // Determines how frequently a heartbeat ChangeRecord will be returned in case + // there are no transactions committed in this partition, in milliseconds. + optional int32 heartbeat_milliseconds = 6; + + // Deadline for this change stream query, in seconds. + optional int64 deadline_seconds = 7; + + // Database role to assume while performing this action. This should only be + // set for cloud requests. Setting the database role will enforce additional + // role-based access checks on this action. + optional string cloud_database_role = 8; +} + +// SpannerActionOutcome defines a result of execution of a single SpannerAction. +message SpannerActionOutcome { + // If an outcome is split into multiple parts, status will be set only in the + // last part. + optional google.rpc.Status status = 1; + + // Transaction timestamp. It must be set for successful committed actions. + optional google.protobuf.Timestamp commit_time = 2; + + // Result of a ReadAction. This field must be set for ReadActions even if + // no rows were read. + optional ReadResult read_result = 3; + + // Result of a Query. This field must be set for Queries even if no rows were + // read. + optional QueryResult query_result = 4; + + // This bit indicates that Spanner has restarted the current transaction. It + // means that the client should replay all the reads and writes. + // Setting it to true is only valid in the context of a read-write + // transaction, as an outcome of a committing FinishTransactionAction. + optional bool transaction_restarted = 5; + + // In successful StartBatchTransactionAction outcomes, this contains the ID of + // the transaction. + optional bytes batch_txn_id = 6; + + // Generated database partitions (result of a + // GenetageDbPartitionsForReadAction/GenerateDbPartitionsForQueryAction). + repeated BatchPartition db_partition = 7; + + // Result of admin related actions. + optional AdminResult admin_result = 8; + + // Stores rows modified by query in single DML or batch DML action. + // In case of batch DML action, stores 0 as row count of errored DML query. + repeated int64 dml_rows_modified = 9; + + // Change stream records returned by a change stream query. + repeated ChangeStreamRecord change_stream_records = 10; + + // If not zero, it indicates the read timestamp to use for validating + // the SnapshotIsolation transaction. + optional int64 snapshot_isolation_txn_read_timestamp = 11; +} + +// AdminResult contains admin action results, for database/backup/operation. +message AdminResult { + // Results of cloud backup related actions. + CloudBackupResponse backup_response = 1; + + // Results of operation related actions. + OperationResponse operation_response = 2; + + // Results of database related actions. + CloudDatabaseResponse database_response = 3; + + // Results of instance related actions. + CloudInstanceResponse instance_response = 4; + + // Results of instance config related actions. + CloudInstanceConfigResponse instance_config_response = 5; +} + +// CloudBackupResponse contains results returned by cloud backup related +// actions. +message CloudBackupResponse { + // List of backups returned by ListCloudBackupsAction. + repeated google.spanner.admin.database.v1.Backup listed_backups = 1; + + // List of operations returned by ListCloudBackupOperationsAction. + repeated google.longrunning.Operation listed_backup_operations = 2; + + // "next_page_token" can be sent in a subsequent list action + // to fetch more of the matching data. + string next_page_token = 3; + + // Backup returned by GetCloudBackupAction/UpdateCloudBackupAction. + google.spanner.admin.database.v1.Backup backup = 4; +} + +// OperationResponse contains results returned by operation related actions. +message OperationResponse { + // List of operations returned by ListOperationsAction. + repeated google.longrunning.Operation listed_operations = 1; + + // "next_page_token" can be sent in a subsequent list action + // to fetch more of the matching data. + string next_page_token = 2; + + // Operation returned by GetOperationAction. + google.longrunning.Operation operation = 3; +} + +// CloudInstanceResponse contains results returned by cloud instance related +// actions. +message CloudInstanceResponse { + // List of instances returned by ListCloudInstancesAction. + repeated google.spanner.admin.instance.v1.Instance listed_instances = 1; + + // "next_page_token" can be sent in a subsequent list action + // to fetch more of the matching data. + string next_page_token = 2; + + // Instance returned by GetCloudInstanceAction + google.spanner.admin.instance.v1.Instance instance = 3; +} + +// CloudInstanceConfigResponse contains results returned by cloud instance +// config related actions. +message CloudInstanceConfigResponse { + // List of instance configs returned by ListCloudInstanceConfigsAction. + repeated google.spanner.admin.instance.v1.InstanceConfig + listed_instance_configs = 1; + + // "next_page_token" can be sent in a subsequent list action + // to fetch more of the matching data. + string next_page_token = 2; + + // Instance config returned by GetCloudInstanceConfigAction. + google.spanner.admin.instance.v1.InstanceConfig instance_config = 3; +} + +// CloudDatabaseResponse contains results returned by cloud database related +// actions. +message CloudDatabaseResponse { + // List of databases returned by ListCloudDatabasesAction. + repeated google.spanner.admin.database.v1.Database listed_databases = 1; + + // List of operations returned by ListCloudDatabaseOperationsAction. + repeated google.longrunning.Operation listed_database_operations = 2; + + // "next_page_token" can be sent in a subsequent list action + // to fetch more of the matching data. + string next_page_token = 3; + + // Database returned by GetCloudDatabaseAction + google.spanner.admin.database.v1.Database database = 4; +} + +// ReadResult contains rows read. +message ReadResult { + // Table name. + string table = 1; + + // Index name, if read from an index. + optional string index = 2; + + // Request index (multiread only). + optional int32 request_index = 3; + + // Rows read. Each row is a struct with multiple fields, one for each column + // in read result. All rows have the same type. + repeated ValueList row = 4; + + // The type of rows read. It must be set if at least one row was read. + optional google.spanner.v1.StructType row_type = 5; +} + +// QueryResult contains result of a Query. +message QueryResult { + // Rows read. Each row is a struct with multiple fields, one for each column + // in read result. All rows have the same type. + repeated ValueList row = 1; + + // The type of rows read. It must be set if at least one row was read. + optional google.spanner.v1.StructType row_type = 2; +} + +// Raw ChangeStream records. +// Encodes one of: DataChangeRecord, HeartbeatRecord, ChildPartitionsRecord +// returned from the ChangeStream API. +message ChangeStreamRecord { + // Record represents one type of the change stream record. + oneof record { + // Data change record. + DataChangeRecord data_change = 1; + + // Child partitions record. + ChildPartitionsRecord child_partition = 2; + + // Heartbeat record. + HeartbeatRecord heartbeat = 3; + } +} + +// ChangeStream data change record. +message DataChangeRecord { + // Column types. + message ColumnType { + // Column name. + string name = 1; + + // Column type in JSON. + string type = 2; + + // Whether the column is a primary key column. + bool is_primary_key = 3; + + // The position of the column as defined in the schema. + int64 ordinal_position = 4; + } + + // Describes the changes that were made. + message Mod { + // The primary key values in JSON. + string keys = 1; + + // The new values of the changed columns in JSON. Only contain the non-key + // columns. + string new_values = 2; + + // The old values of the changed columns in JSON. Only contain the non-key + // columns. + string old_values = 3; + } + + // The timestamp in which the change was committed. + google.protobuf.Timestamp commit_time = 1; + + // The sequence number for the record within the transaction. + string record_sequence = 2; + + // A globally unique string that represents the transaction in which the + // change was committed. + string transaction_id = 3; + + // Indicates whether this is the last record for a transaction in the current + // partition. + bool is_last_record = 4; + + // Name of the table affected by the change. + string table = 5; + + // Column types defined in the schema. + repeated ColumnType column_types = 6; + + // Changes made in the transaction. + repeated Mod mods = 7; + + // Describes the type of change. One of INSERT, UPDATE or DELETE. + string mod_type = 8; + + // One of value capture type: NEW_VALUES, OLD_VALUES, OLD_AND_NEW_VALUES. + string value_capture_type = 9; + + // Number of records in transactions. + int64 record_count = 10; + + // Number of partitions in transactions. + int64 partition_count = 11; + + // Transaction tag info. + string transaction_tag = 12; + + // Whether the transaction is a system transactionn. + bool is_system_transaction = 13; +} + +// ChangeStream child partition record. +message ChildPartitionsRecord { + // A single child partition. + message ChildPartition { + // Partition token string used to identify the child partition in queries. + string token = 1; + + // Parent partition tokens of this child partition. + repeated string parent_partition_tokens = 2; + } + + // Data change records returned from child partitions in this child partitions + // record will have a commit timestamp greater than or equal to start_time. + google.protobuf.Timestamp start_time = 1; + + // A monotonically increasing sequence number that can be used to define the + // ordering of the child partitions record when there are multiple child + // partitions records returned with the same start_time in a particular + // partition. + string record_sequence = 2; + + // A set of child partitions and their associated information. + repeated ChildPartition child_partitions = 3; +} + +// ChangeStream heartbeat record. +message HeartbeatRecord { + // Timestamp for this heartbeat check. + google.protobuf.Timestamp heartbeat_time = 1; +} + +// Options for Cloud Spanner Service. +message SpannerOptions { + // Options for configuring the session pool + SessionPoolOptions session_pool_options = 1; +} + +// Options for the session pool used by the DatabaseClient. +message SessionPoolOptions { + // passing this as true, will make applicable RPCs use multiplexed sessions + // instead of regular sessions + bool use_multiplexed = 1; +} diff --git a/handwritten/spanner/protos/google/spanner/v1/change_stream.proto b/handwritten/spanner/protos/google/spanner/v1/change_stream.proto new file mode 100644 index 00000000000..e7d12e6084c --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/change_stream.proto @@ -0,0 +1,451 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/spanner/v1/type.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "ChangeStreamProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// Spanner Change Streams enable customers to capture and stream out changes to +// their Spanner databases in real-time. A change stream +// can be created with option partition_mode='IMMUTABLE_KEY_RANGE' or +// partition_mode='MUTABLE_KEY_RANGE'. +// +// This message is only used in Change Streams created with the option +// partition_mode='MUTABLE_KEY_RANGE'. Spanner automatically creates a special +// Table-Valued Function (TVF) along with each Change Streams. The function +// provides access to the change stream's records. The function is named +// READ_ (where is the +// name of the change stream), and it returns a table with only one column +// called ChangeRecord. +message ChangeStreamRecord { + // A data change record contains a set of changes to a table with the same + // modification type (insert, update, or delete) committed at the same commit + // timestamp in one change stream partition for the same transaction. Multiple + // data change records can be returned for the same transaction across + // multiple change stream partitions. + message DataChangeRecord { + // Metadata for a column. + message ColumnMetadata { + // Name of the column. + string name = 1; + + // Type of the column. + Type type = 2; + + // Indicates whether the column is a primary key column. + bool is_primary_key = 3; + + // Ordinal position of the column based on the original table definition + // in the schema starting with a value of 1. + int64 ordinal_position = 4; + } + + // Returns the value and associated metadata for a particular field of the + // [Mod][google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod]. + message ModValue { + // Index within the repeated + // [column_metadata][google.spanner.v1.ChangeStreamRecord.DataChangeRecord.column_metadata] + // field, to obtain the column metadata for the column that was modified. + int32 column_metadata_index = 1; + + // The value of the column. + google.protobuf.Value value = 2; + } + + // A mod describes all data changes in a watched table row. + message Mod { + // Returns the value of the primary key of the modified row. + repeated ModValue keys = 1; + + // Returns the old values before the change for the modified columns. + // Always empty for + // [INSERT][google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType.INSERT], + // or if old values are not being captured specified by + // [value_capture_type][google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType]. + repeated ModValue old_values = 2; + + // Returns the new values after the change for the modified columns. + // Always empty for + // [DELETE][google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType.DELETE]. + repeated ModValue new_values = 3; + } + + // Mod type describes the type of change Spanner applied to the data. For + // example, if the client submits an INSERT_OR_UPDATE request, Spanner will + // perform an insert if there is no existing row and return ModType INSERT. + // Alternatively, if there is an existing row, Spanner will perform an + // update and return ModType UPDATE. + enum ModType { + // Not specified. + MOD_TYPE_UNSPECIFIED = 0; + + // Indicates data was inserted. + INSERT = 10; + + // Indicates existing data was updated. + UPDATE = 20; + + // Indicates existing data was deleted. + DELETE = 30; + } + + // Value capture type describes which values are recorded in the data + // change record. + enum ValueCaptureType { + // Not specified. + VALUE_CAPTURE_TYPE_UNSPECIFIED = 0; + + // Records both old and new values of the modified watched columns. + OLD_AND_NEW_VALUES = 10; + + // Records only new values of the modified watched columns. + NEW_VALUES = 20; + + // Records new values of all watched columns, including modified and + // unmodified columns. + NEW_ROW = 30; + + // Records the new values of all watched columns, including modified and + // unmodified columns. Also records the old values of the modified + // columns. + NEW_ROW_AND_OLD_VALUES = 40; + } + + // Indicates the timestamp in which the change was committed. + // DataChangeRecord.commit_timestamps, + // PartitionStartRecord.start_timestamps, + // PartitionEventRecord.commit_timestamps, and + // PartitionEndRecord.end_timestamps can have the same value in the same + // partition. + google.protobuf.Timestamp commit_timestamp = 1; + + // Record sequence numbers are unique and monotonically increasing (but not + // necessarily contiguous) for a specific timestamp across record + // types in the same partition. To guarantee ordered processing, the reader + // should process records (of potentially different types) in + // record_sequence order for a specific timestamp in the same partition. + // + // The record sequence number ordering across partitions is only meaningful + // in the context of a specific transaction. Record sequence numbers are + // unique across partitions for a specific transaction. Sort the + // DataChangeRecords for the same + // [server_transaction_id][google.spanner.v1.ChangeStreamRecord.DataChangeRecord.server_transaction_id] + // by + // [record_sequence][google.spanner.v1.ChangeStreamRecord.DataChangeRecord.record_sequence] + // to reconstruct the ordering of the changes within the transaction. + string record_sequence = 2; + + // Provides a globally unique string that represents the transaction in + // which the change was committed. Multiple transactions can have the same + // commit timestamp, but each transaction has a unique + // server_transaction_id. + string server_transaction_id = 3; + + // Indicates whether this is the last record for a transaction in the + // current partition. Clients can use this field to determine when all + // records for a transaction in the current partition have been received. + bool is_last_record_in_transaction_in_partition = 4; + + // Name of the table affected by the change. + string table = 5; + + // Provides metadata describing the columns associated with the + // [mods][google.spanner.v1.ChangeStreamRecord.DataChangeRecord.mods] listed + // below. + repeated ColumnMetadata column_metadata = 6; + + // Describes the changes that were made. + repeated Mod mods = 7; + + // Describes the type of change. + ModType mod_type = 8; + + // Describes the value capture type that was specified in the change stream + // configuration when this change was captured. + ValueCaptureType value_capture_type = 9; + + // Indicates the number of data change records that are part of this + // transaction across all change stream partitions. This value can be used + // to assemble all the records associated with a particular transaction. + int32 number_of_records_in_transaction = 10; + + // Indicates the number of partitions that return data change records for + // this transaction. This value can be helpful in assembling all records + // associated with a particular transaction. + int32 number_of_partitions_in_transaction = 11; + + // Indicates the transaction tag associated with this transaction. + string transaction_tag = 12; + + // Indicates whether the transaction is a system transaction. System + // transactions include those issued by time-to-live (TTL), column backfill, + // etc. + bool is_system_transaction = 13; + } + + // A heartbeat record is returned as a progress indicator, when there are no + // data changes or any other partition record types in the change stream + // partition. + message HeartbeatRecord { + // Indicates the timestamp at which the query has returned all the records + // in the change stream partition with timestamp <= heartbeat timestamp. + // The heartbeat timestamp will not be the same as the timestamps of other + // record types in the same partition. + google.protobuf.Timestamp timestamp = 1; + } + + // A partition start record serves as a notification that the client should + // schedule the partitions to be queried. PartitionStartRecord returns + // information about one or more partitions. + message PartitionStartRecord { + // Start timestamp at which the partitions should be queried to return + // change stream records with timestamps >= start_timestamp. + // DataChangeRecord.commit_timestamps, + // PartitionStartRecord.start_timestamps, + // PartitionEventRecord.commit_timestamps, and + // PartitionEndRecord.end_timestamps can have the same value in the same + // partition. + google.protobuf.Timestamp start_timestamp = 1; + + // Record sequence numbers are unique and monotonically increasing (but not + // necessarily contiguous) for a specific timestamp across record + // types in the same partition. To guarantee ordered processing, the reader + // should process records (of potentially different types) in + // record_sequence order for a specific timestamp in the same partition. + string record_sequence = 2; + + // Unique partition identifiers to be used in queries. + repeated string partition_tokens = 3; + } + + // A partition end record serves as a notification that the client should stop + // reading the partition. No further records are expected to be retrieved on + // it. + message PartitionEndRecord { + // End timestamp at which the change stream partition is terminated. All + // changes generated by this partition will have timestamps <= + // end_timestamp. DataChangeRecord.commit_timestamps, + // PartitionStartRecord.start_timestamps, + // PartitionEventRecord.commit_timestamps, and + // PartitionEndRecord.end_timestamps can have the same value in the same + // partition. PartitionEndRecord is the last record returned for a + // partition. + google.protobuf.Timestamp end_timestamp = 1; + + // Record sequence numbers are unique and monotonically increasing (but not + // necessarily contiguous) for a specific timestamp across record + // types in the same partition. To guarantee ordered processing, the reader + // should process records (of potentially different types) in + // record_sequence order for a specific timestamp in the same partition. + string record_sequence = 2; + + // Unique partition identifier describing the terminated change stream + // partition. + // [partition_token][google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.partition_token] + // is equal to the partition token of the change stream partition currently + // queried to return this PartitionEndRecord. + string partition_token = 3; + } + + // A partition event record describes key range changes for a change stream + // partition. The changes to a row defined by its primary key can be captured + // in one change stream partition for a specific time range, and then be + // captured in a different change stream partition for a different time range. + // This movement of key ranges across change stream partitions is a reflection + // of activities, such as Spanner's dynamic splitting and load balancing, etc. + // Processing this event is needed if users want to guarantee processing of + // the changes for any key in timestamp order. If time ordered processing of + // changes for a primary key is not needed, this event can be ignored. + // To guarantee time ordered processing for each primary key, if the event + // describes move-ins, the reader of this partition needs to wait until the + // readers of the source partitions have processed all records with timestamps + // <= this PartitionEventRecord.commit_timestamp, before advancing beyond this + // PartitionEventRecord. If the event describes move-outs, the reader can + // notify the readers of the destination partitions that they can continue + // processing. + message PartitionEventRecord { + // Describes move-in of the key ranges into the change stream partition + // identified by + // [partition_token][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.partition_token]. + // + // To maintain processing the changes for a particular key in timestamp + // order, the query processing the change stream partition identified by + // [partition_token][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.partition_token] + // should not advance beyond the partition event record commit timestamp + // until the queries processing the source change stream partitions have + // processed all change stream records with timestamps <= the partition + // event record commit timestamp. + message MoveInEvent { + // An unique partition identifier describing the source change stream + // partition that recorded changes for the key range that is moving + // into this partition. + string source_partition_token = 1; + } + + // Describes move-out of the key ranges out of the change stream partition + // identified by + // [partition_token][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.partition_token]. + // + // To maintain processing the changes for a particular key in timestamp + // order, the query processing the + // [MoveOutEvent][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent] + // in the partition identified by + // [partition_token][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.partition_token] + // should inform the queries processing the destination partitions that + // they can unblock and proceed processing records past the + // [commit_timestamp][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.commit_timestamp]. + message MoveOutEvent { + // An unique partition identifier describing the destination change + // stream partition that will record changes for the key range that is + // moving out of this partition. + string destination_partition_token = 1; + } + + // Indicates the commit timestamp at which the key range change occurred. + // DataChangeRecord.commit_timestamps, + // PartitionStartRecord.start_timestamps, + // PartitionEventRecord.commit_timestamps, and + // PartitionEndRecord.end_timestamps can have the same value in the same + // partition. + google.protobuf.Timestamp commit_timestamp = 1; + + // Record sequence numbers are unique and monotonically increasing (but not + // necessarily contiguous) for a specific timestamp across record + // types in the same partition. To guarantee ordered processing, the reader + // should process records (of potentially different types) in + // record_sequence order for a specific timestamp in the same partition. + string record_sequence = 2; + + // Unique partition identifier describing the partition this event + // occurred on. + // [partition_token][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.partition_token] + // is equal to the partition token of the change stream partition currently + // queried to return this PartitionEventRecord. + string partition_token = 3; + + // Set when one or more key ranges are moved into the change stream + // partition identified by + // [partition_token][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.partition_token]. + // + // Example: Two key ranges are moved into partition (P1) from partition (P2) + // and partition (P3) in a single transaction at timestamp T. + // + // The PartitionEventRecord returned in P1 will reflect the move as: + // + // PartitionEventRecord { + // commit_timestamp: T + // partition_token: "P1" + // move_in_events { + // source_partition_token: "P2" + // } + // move_in_events { + // source_partition_token: "P3" + // } + // } + // + // The PartitionEventRecord returned in P2 will reflect the move as: + // + // PartitionEventRecord { + // commit_timestamp: T + // partition_token: "P2" + // move_out_events { + // destination_partition_token: "P1" + // } + // } + // + // The PartitionEventRecord returned in P3 will reflect the move as: + // + // PartitionEventRecord { + // commit_timestamp: T + // partition_token: "P3" + // move_out_events { + // destination_partition_token: "P1" + // } + // } + repeated MoveInEvent move_in_events = 4; + + // Set when one or more key ranges are moved out of the change stream + // partition identified by + // [partition_token][google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.partition_token]. + // + // Example: Two key ranges are moved out of partition (P1) to partition (P2) + // and partition (P3) in a single transaction at timestamp T. + // + // The PartitionEventRecord returned in P1 will reflect the move as: + // + // PartitionEventRecord { + // commit_timestamp: T + // partition_token: "P1" + // move_out_events { + // destination_partition_token: "P2" + // } + // move_out_events { + // destination_partition_token: "P3" + // } + // } + // + // The PartitionEventRecord returned in P2 will reflect the move as: + // + // PartitionEventRecord { + // commit_timestamp: T + // partition_token: "P2" + // move_in_events { + // source_partition_token: "P1" + // } + // } + // + // The PartitionEventRecord returned in P3 will reflect the move as: + // + // PartitionEventRecord { + // commit_timestamp: T + // partition_token: "P3" + // move_in_events { + // source_partition_token: "P1" + // } + // } + repeated MoveOutEvent move_out_events = 5; + } + + // One of the change stream subrecords. + oneof record { + // Data change record describing a data change for a change stream + // partition. + DataChangeRecord data_change_record = 1; + + // Heartbeat record describing a heartbeat for a change stream partition. + HeartbeatRecord heartbeat_record = 2; + + // Partition start record describing a new change stream partition. + PartitionStartRecord partition_start_record = 3; + + // Partition end record describing a terminated change stream partition. + PartitionEndRecord partition_end_record = 4; + + // Partition event record describing key range changes for a change stream + // partition. + PartitionEventRecord partition_event_record = 5; + } +} diff --git a/handwritten/spanner/protos/google/spanner/v1/commit_response.proto b/handwritten/spanner/protos/google/spanner/v1/commit_response.proto new file mode 100644 index 00000000000..6e445912202 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/commit_response.proto @@ -0,0 +1,64 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/protobuf/timestamp.proto"; +import "google/spanner/v1/transaction.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "CommitResponseProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// The response for [Commit][google.spanner.v1.Spanner.Commit]. +message CommitResponse { + // Additional statistics about a commit. + message CommitStats { + // The total number of mutations for the transaction. Knowing the + // `mutation_count` value can help you maximize the number of mutations + // in a transaction and minimize the number of API round trips. You can + // also monitor this value to prevent transactions from exceeding the system + // [limit](https://cloud.google.com/spanner/quotas#limits_for_creating_reading_updating_and_deleting_data). + // If the number of mutations exceeds the limit, the server returns + // [INVALID_ARGUMENT](https://cloud.google.com/spanner/docs/reference/rest/v1/Code#ENUM_VALUES.INVALID_ARGUMENT). + int64 mutation_count = 1; + } + + // The Cloud Spanner timestamp at which the transaction committed. + google.protobuf.Timestamp commit_timestamp = 1; + + // The statistics about this `Commit`. Not returned by default. + // For more information, see + // [CommitRequest.return_commit_stats][google.spanner.v1.CommitRequest.return_commit_stats]. + CommitStats commit_stats = 2; + + // You must examine and retry the commit if the following is populated. + oneof MultiplexedSessionRetry { + // If specified, transaction has not committed yet. + // You must retry the commit with the new precommit token. + MultiplexedSessionPrecommitToken precommit_token = 4; + } + + // If `TransactionOptions.isolation_level` is set to + // `IsolationLevel.REPEATABLE_READ`, then the snapshot timestamp is the + // timestamp at which all reads in the transaction ran. This timestamp is + // never returned. + google.protobuf.Timestamp snapshot_timestamp = 5; +} diff --git a/handwritten/spanner/protos/google/spanner/v1/keys.proto b/handwritten/spanner/protos/google/spanner/v1/keys.proto new file mode 100644 index 00000000000..5e30e831e64 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/keys.proto @@ -0,0 +1,163 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/protobuf/struct.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "KeysProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// KeyRange represents a range of rows in a table or index. +// +// A range has a start key and an end key. These keys can be open or +// closed, indicating if the range includes rows with that key. +// +// Keys are represented by lists, where the ith value in the list +// corresponds to the ith component of the table or index primary key. +// Individual values are encoded as described +// [here][google.spanner.v1.TypeCode]. +// +// For example, consider the following table definition: +// +// CREATE TABLE UserEvents ( +// UserName STRING(MAX), +// EventDate STRING(10) +// ) PRIMARY KEY(UserName, EventDate); +// +// The following keys name rows in this table: +// +// ["Bob", "2014-09-23"] +// ["Alfred", "2015-06-12"] +// +// Since the `UserEvents` table's `PRIMARY KEY` clause names two +// columns, each `UserEvents` key has two elements; the first is the +// `UserName`, and the second is the `EventDate`. +// +// Key ranges with multiple components are interpreted +// lexicographically by component using the table or index key's declared +// sort order. For example, the following range returns all events for +// user `"Bob"` that occurred in the year 2015: +// +// "start_closed": ["Bob", "2015-01-01"] +// "end_closed": ["Bob", "2015-12-31"] +// +// Start and end keys can omit trailing key components. This affects the +// inclusion and exclusion of rows that exactly match the provided key +// components: if the key is closed, then rows that exactly match the +// provided components are included; if the key is open, then rows +// that exactly match are not included. +// +// For example, the following range includes all events for `"Bob"` that +// occurred during and after the year 2000: +// +// "start_closed": ["Bob", "2000-01-01"] +// "end_closed": ["Bob"] +// +// The next example retrieves all events for `"Bob"`: +// +// "start_closed": ["Bob"] +// "end_closed": ["Bob"] +// +// To retrieve events before the year 2000: +// +// "start_closed": ["Bob"] +// "end_open": ["Bob", "2000-01-01"] +// +// The following range includes all rows in the table: +// +// "start_closed": [] +// "end_closed": [] +// +// This range returns all users whose `UserName` begins with any +// character from A to C: +// +// "start_closed": ["A"] +// "end_open": ["D"] +// +// This range returns all users whose `UserName` begins with B: +// +// "start_closed": ["B"] +// "end_open": ["C"] +// +// Key ranges honor column sort order. For example, suppose a table is +// defined as follows: +// +// CREATE TABLE DescendingSortedTable { +// Key INT64, +// ... +// ) PRIMARY KEY(Key DESC); +// +// The following range retrieves all rows with key values between 1 +// and 100 inclusive: +// +// "start_closed": ["100"] +// "end_closed": ["1"] +// +// Note that 100 is passed as the start, and 1 is passed as the end, +// because `Key` is a descending column in the schema. +message KeyRange { + // The start key must be provided. It can be either closed or open. + oneof start_key_type { + // If the start is closed, then the range includes all rows whose + // first `len(start_closed)` key columns exactly match `start_closed`. + google.protobuf.ListValue start_closed = 1; + + // If the start is open, then the range excludes rows whose first + // `len(start_open)` key columns exactly match `start_open`. + google.protobuf.ListValue start_open = 2; + } + + // The end key must be provided. It can be either closed or open. + oneof end_key_type { + // If the end is closed, then the range includes all rows whose + // first `len(end_closed)` key columns exactly match `end_closed`. + google.protobuf.ListValue end_closed = 3; + + // If the end is open, then the range excludes rows whose first + // `len(end_open)` key columns exactly match `end_open`. + google.protobuf.ListValue end_open = 4; + } +} + +// `KeySet` defines a collection of Cloud Spanner keys and/or key ranges. All +// the keys are expected to be in the same table or index. The keys need +// not be sorted in any particular way. +// +// If the same key is specified multiple times in the set (for example +// if two ranges, two keys, or a key and a range overlap), Cloud Spanner +// behaves as if the key were only specified once. +message KeySet { + // A list of specific keys. Entries in `keys` should have exactly as + // many elements as there are columns in the primary or index key + // with which this `KeySet` is used. Individual key values are + // encoded as described [here][google.spanner.v1.TypeCode]. + repeated google.protobuf.ListValue keys = 1; + + // A list of key ranges. See [KeyRange][google.spanner.v1.KeyRange] for more + // information about key range specifications. + repeated KeyRange ranges = 2; + + // For convenience `all` can be set to `true` to indicate that this + // `KeySet` matches all keys in the table or index. Note that any keys + // specified in `keys` or `ranges` are only yielded once. + bool all = 3; +} diff --git a/handwritten/spanner/protos/google/spanner/v1/location.proto b/handwritten/spanner/protos/google/spanner/v1/location.proto new file mode 100644 index 00000000000..870dc0ec0a9 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/location.proto @@ -0,0 +1,388 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/protobuf/struct.proto"; +import "google/spanner/v1/type.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "LocationProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// A `Range` represents a range of keys in a database. The keys themselves +// are encoded in "sortable string format", also known as ssformat. Consult +// Spanner's open source client libraries for details on the encoding. +// +// Each range represents a contiguous range of rows, possibly from multiple +// tables/indexes. Each range is associated with a single paxos group (known as +// a "group" throughout this API), a split (which names the exact range within +// the group), and a generation that can be used to determine whether a given +// `Range` represents a newer or older location for the key range. +message Range { + // The start key of the range, inclusive. Encoded in "sortable string format" + // (ssformat). + bytes start_key = 1; + + // The limit key of the range, exclusive. Encoded in "sortable string format" + // (ssformat). + bytes limit_key = 2; + + // The UID of the paxos group where this range is stored. UIDs are unique + // within the database. References `Group.group_uid`. + uint64 group_uid = 3; + + // A group can store multiple ranges of keys. Each key range is named by an + // ID (the split ID). Within a group, split IDs are unique. The `split_id` + // names the exact split in `group_uid` where this range is stored. + uint64 split_id = 4; + + // `generation` indicates the freshness of the range information contained + // in this proto. Generations can be compared lexicographically; if generation + // A is greater than generation B, then the `Range` corresponding to A is + // newer than the `Range` corresponding to B, and should be used + // preferentially. + bytes generation = 5; +} + +// A `Tablet` represents a single replica of a `Group`. A tablet is served by a +// single server at a time, and can move between servers due to server death or +// simply load balancing. +message Tablet { + // Indicates the role of the tablet. + enum Role { + // Not specified. + ROLE_UNSPECIFIED = 0; + + // The tablet can perform reads and (if elected leader) writes. + READ_WRITE = 1; + + // The tablet can only perform reads. + READ_ONLY = 2; + } + + // The UID of the tablet, unique within the database. Matches the + // `tablet_uids` and `leader_tablet_uid` fields in `Group`. + uint64 tablet_uid = 1; + + // The address of the server that is serving this tablet -- either an IP + // address or DNS hostname and a port number. + string server_address = 2; + + // Where this tablet is located. This is the name of a Google Cloud region, + // such as "us-central1". + string location = 3; + + // The role of the tablet. + Role role = 4; + + // `incarnation` indicates the freshness of the tablet information contained + // in this proto. Incarnations can be compared lexicographically; if + // incarnation A is greater than incarnation B, then the `Tablet` + // corresponding to A is newer than the `Tablet` corresponding to B, and + // should be used preferentially. + bytes incarnation = 5; + + // Distances help the client pick the closest tablet out of the list of + // tablets for a given request. Tablets with lower distances should generally + // be preferred. Tablets with the same distance are approximately equally + // close; the client can choose arbitrarily. + // + // Distances do not correspond precisely to expected latency, geographical + // distance, or anything else. Distances should be compared only between + // tablets of the same group; they are not meaningful between different + // groups. + // + // A value of zero indicates that the tablet may be in the same zone as + // the client, and have minimum network latency. A value less than or equal to + // five indicates that the tablet is thought to be in the same region as the + // client, and may have a few milliseconds of network latency. Values greater + // than five are most likely in a different region, with non-trivial network + // latency. + // + // Clients should use the following algorithm: + // * If the request is using a directed read, eliminate any tablets that + // do not match the directed read's target zone and/or replica type. + // * (Read-write transactions only) Choose leader tablet if it has an + // distance <=5. + // * Group and sort tablets by distance. Choose a random + // tablet with the lowest distance. If the request + // is not a directed read, only consider replicas with distances <=5. + // * Send the request to the fallback endpoint. + // + // The tablet picked by this algorithm may be skipped, either because it is + // marked as `skip` by the server or because the corresponding server is + // unreachable, flow controlled, etc. Skipped tablets should be added to the + // `skipped_tablet_uid` field in `RoutingHint`; the algorithm above should + // then be re-run without including the skipped tablet(s) to pick the next + // best tablet. + uint32 distance = 6; + + // If true, the tablet should not be chosen by the client. Typically, this + // signals that the tablet is unhealthy in some way. Tablets with `skip` + // set to true should be reported back to the server in + // `RoutingHint.skipped_tablet_uid`; this cues the server to send updated + // information for this tablet should it become usable again. + bool skip = 7; +} + +// A `Group` represents a paxos group in a database. A group is a set of +// tablets that are replicated across multiple servers. Groups may have a leader +// tablet. Groups store one (or sometimes more) ranges of keys. +message Group { + // The UID of the paxos group, unique within the database. Matches the + // `group_uid` field in `Range`. + uint64 group_uid = 1; + + // A list of tablets that are part of the group. Note that this list may not + // be exhaustive; it will only include tablets the server considers useful + // to the client. The returned list is ordered ascending by distance. + // + // Tablet UIDs reference `Tablet.tablet_uid`. + repeated Tablet tablets = 2; + + // The last known leader tablet of the group as an index into `tablets`. May + // be negative if the group has no known leader. + int32 leader_index = 3; + + // `generation` indicates the freshness of the group information (including + // leader information) contained in this proto. Generations can be compared + // lexicographically; if generation A is greater than generation B, then the + // `Group` corresponding to A is newer than the `Group` corresponding to B, + // and should be used preferentially. + bytes generation = 4; +} + +// A `KeyRecipe` provides the metadata required to translate reads, mutations, +// and queries into a byte array in "sortable string format" (ssformat)that can +// be used with `Range`s to route requests. Note that the client *must* tolerate +// `KeyRecipe`s that appear to be invalid, since the `KeyRecipe` format may +// change over time. Requests with invalid `KeyRecipe`s should be routed to a +// default server. +message KeyRecipe { + // An ssformat key is composed of a sequence of tag numbers and key column + // values. `Part` represents a single tag or key column value. + message Part { + // The remaining fields encode column values. + enum Order { + // Default value, equivalent to `ASCENDING`. + ORDER_UNSPECIFIED = 0; + + // The key is ascending - corresponds to `ASC` in the schema definition. + ASCENDING = 1; + + // The key is descending - corresponds to `DESC` in the schema definition. + DESCENDING = 2; + } + + // The null order of the key column. This dictates where NULL values sort + // in the sorted order. Note that columns which are `NOT NULL` can have a + // special encoding. + enum NullOrder { + // Default value. This value is unused. + NULL_ORDER_UNSPECIFIED = 0; + + // NULL values sort before any non-NULL values. + NULLS_FIRST = 1; + + // NULL values sort after any non-NULL values. + NULLS_LAST = 2; + + // The column does not support NULL values. + NOT_NULL = 3; + } + + // If non-zero, `tag` is the only field present in this `Part`. The part + // is encoded by appending `tag` to the ssformat key. + uint32 tag = 1; + + // Whether the key column is sorted ascending or descending. Only present + // if `tag` is zero. + Order order = 2; + + // How NULLs are represented in the encoded key part. Only present if `tag` + // is zero. + NullOrder null_order = 3; + + // The type of the key part. Only present if `tag` is zero. + Type type = 4; + + // Only present if `tag` is zero. + oneof value_type { + // `identifier` is the name of the column or query parameter. + string identifier = 5; + + // The constant value of the key part. + // It is present when query uses a constant as a part of the key. + google.protobuf.Value value = 6; + + // If true, the client is responsible to fill in the value randomly. + // It's relevant only for the INT64 type. + bool random = 8; + } + + // It is a repeated field to support fetching key columns from nested + // structs, such as `STRUCT` query parameters. + repeated int32 struct_identifiers = 7; + } + + // A recipe can be associated with a table, index, or query. Tables recipes + // are used to encode read and write keys; index recipes are used for index + // reads, and query recipes are used only for SQL queries. + oneof target { + // A table name, matching the name from the database schema. + string table_name = 1; + + // An index name, matching the name from the database schema. + string index_name = 2; + + // The UID of a query, matching the UID from `RoutingHint`. + uint64 operation_uid = 3; + } + + // Parts are in the order they should appear in the encoded key. + repeated Part part = 4; +} + +// A `RecipeList` contains a list of `KeyRecipe`s, which share the same +// schema generation. +message RecipeList { + // The schema generation of the recipes. To be sent to the server in + // `RoutingHint.schema_generation` whenever one of the recipes is used. + // `schema_generation` values are comparable with each other; if generation A + // compares greater than generation B, then A is a more recent schema than B. + // Clients should in general aim to cache only the latest schema generation, + // and discard more stale recipes. + bytes schema_generation = 1; + + // A list of recipes to be cached. + repeated KeyRecipe recipe = 3; +} + +// A `CacheUpdate` expresses a set of changes the client should incorporate into +// its location cache. These changes may or may not be newer than what the +// client has in its cache, and should be discarded if necessary. `CacheUpdate`s +// can be obtained in response to requests that included a `RoutingHint` +// field, but may also be obtained by explicit location-fetching RPCs which may +// be added in the future. +message CacheUpdate { + // An internal ID for the database. Database names can be reused if a database + // is deleted and re-created. Each time the database is re-created, it will + // get a new database ID, which will never be re-used for any other database. + uint64 database_id = 1; + + // A list of ranges to be cached. + repeated Range range = 2; + + // A list of groups to be cached. + repeated Group group = 3; + + // A list of recipes to be cached. + RecipeList key_recipes = 5; +} + +// `RoutingHint` can be optionally added to location-aware Spanner +// requests. It gives the server hints that can be used to route the request to +// an appropriate server, potentially significantly decreasing latency and +// improving throughput. To achieve improved performance, most fields must be +// filled in with accurate values. +// +// The presence of a valid `RoutingHint` tells the server that the client +// is location-aware. +// +// `RoutingHint` does not change the semantics of the request; it is +// purely a performance hint; the request will perform the same actions on the +// database's data as if `RoutingHint` were not present. However, if +// the `RoutingHint` is incomplete or incorrect, the response may include +// a `CacheUpdate` the client can use to correct its location cache. +message RoutingHint { + // A tablet that was skipped by the client. See `Tablet.tablet_uid` and + // `Tablet.incarnation`. + message SkippedTablet { + // The tablet UID of the tablet that was skipped. See `Tablet.tablet_uid`. + uint64 tablet_uid = 1; + + // The incarnation of the tablet that was skipped. See `Tablet.incarnation`. + bytes incarnation = 2; + } + + // A session-scoped unique ID for the operation, computed client-side. + // Requests with the same `operation_uid` should have a shared 'shape', + // meaning that some fields are expected to be the same, such as the SQL + // query, the target table/columns (for reads) etc. Requests with the same + // `operation_uid` are meant to differ only in fields like keys/key + // ranges/query parameters, transaction IDs, etc. + // + // `operation_uid` must be non-zero for `RoutingHint` to be valid. + uint64 operation_uid = 1; + + // The database ID of the database being accessed, see + // `CacheUpdate.database_id`. Should match the cache entries that were used + // to generate the rest of the fields in this `RoutingHint`. + uint64 database_id = 2; + + // The schema generation of the recipe that was used to generate `key` and + // `limit_key`. See also `RecipeList.schema_generation`. + bytes schema_generation = 3; + + // The key / key range that this request accesses. For operations that + // access a single key, `key` should be set and `limit_key` should be empty. + // For operations that access a key range, `key` and `limit_key` should both + // be set, to the inclusive start and exclusive end of the range respectively. + // + // The keys are encoded in "sortable string format" (ssformat), using a + // `KeyRecipe` that is appropriate for the request. See `KeyRecipe` for more + // details. + bytes key = 4; + + // If this request targets a key range, this is the exclusive end of the + // range. See `key` for more details. + bytes limit_key = 5; + + // The group UID of the group that the client believes serves the range + // defined by `key` and `limit_key`. See `Range.group_uid` for more details. + uint64 group_uid = 6; + + // The split ID of the split that the client believes contains the range + // defined by `key` and `limit_key`. See `Range.split_id` for more details. + uint64 split_id = 7; + + // The tablet UID of the tablet from group `group_uid` that the client + // believes is best to serve this request. See `Group.local_tablet_uids` and + // `Group.leader_tablet_uid`. + uint64 tablet_uid = 8; + + // If the client had multiple options for tablet selection, and some of its + // first choices were unhealthy (e.g., the server is unreachable, or + // `Tablet.skip` is true), this field will contain the tablet UIDs of those + // tablets, with their incarnations. The server may include a `CacheUpdate` + // with new locations for those tablets. + repeated SkippedTablet skipped_tablet_uid = 9; + + // If present, the client's current location. This should be the name of a + // Google Cloud zone or region, such as "us-central1". + // + // If absent, the client's location will be assumed to be the same as the + // location of the server the client ends up connected to. + // + // Locations are primarily valuable for clients that connect from regions + // other than the ones that contain the Spanner database. + string client_location = 10; +} diff --git a/handwritten/spanner/protos/google/spanner/v1/mutation.proto b/handwritten/spanner/protos/google/spanner/v1/mutation.proto new file mode 100644 index 00000000000..7e3306a2038 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/mutation.proto @@ -0,0 +1,156 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/spanner/v1/keys.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "MutationProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// A modification to one or more Cloud Spanner rows. Mutations can be +// applied to a Cloud Spanner database by sending them in a +// [Commit][google.spanner.v1.Spanner.Commit] call. +message Mutation { + // Arguments to [insert][google.spanner.v1.Mutation.insert], + // [update][google.spanner.v1.Mutation.update], + // [insert_or_update][google.spanner.v1.Mutation.insert_or_update], and + // [replace][google.spanner.v1.Mutation.replace] operations. + message Write { + // Required. The table whose rows will be written. + string table = 1 [(google.api.field_behavior) = REQUIRED]; + + // The names of the columns in + // [table][google.spanner.v1.Mutation.Write.table] to be written. + // + // The list of columns must contain enough columns to allow + // Cloud Spanner to derive values for all primary key columns in the + // row(s) to be modified. + repeated string columns = 2; + + // The values to be written. `values` can contain more than one + // list of values. If it does, then multiple rows are written, one + // for each entry in `values`. Each list in `values` must have + // exactly as many entries as there are entries in + // [columns][google.spanner.v1.Mutation.Write.columns] above. Sending + // multiple lists is equivalent to sending multiple `Mutation`s, each + // containing one `values` entry and repeating + // [table][google.spanner.v1.Mutation.Write.table] and + // [columns][google.spanner.v1.Mutation.Write.columns]. Individual values in + // each list are encoded as described [here][google.spanner.v1.TypeCode]. + repeated google.protobuf.ListValue values = 3; + } + + // Arguments to [delete][google.spanner.v1.Mutation.delete] operations. + message Delete { + // Required. The table whose rows will be deleted. + string table = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The primary keys of the rows within + // [table][google.spanner.v1.Mutation.Delete.table] to delete. The primary + // keys must be specified in the order in which they appear in the `PRIMARY + // KEY()` clause of the table's equivalent DDL statement (the DDL statement + // used to create the table). Delete is idempotent. The transaction will + // succeed even if some or all rows do not exist. + KeySet key_set = 2 [(google.api.field_behavior) = REQUIRED]; + } + + // Arguments to [send][google.spanner.v1.Mutation.send] operations. + message Send { + // Required. The queue to which the message will be sent. + string queue = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The primary key of the message to be sent. + google.protobuf.ListValue key = 2 [(google.api.field_behavior) = REQUIRED]; + + // The time at which Spanner will begin attempting to deliver the message. + // If `deliver_time` is not set, Spanner will deliver the message + // immediately. If `deliver_time` is in the past, Spanner will replace it + // with a value closer to the current time. + google.protobuf.Timestamp deliver_time = 3; + + // The payload of the message. + google.protobuf.Value payload = 4; + } + + // Arguments to [ack][google.spanner.v1.Mutation.ack] operations. + message Ack { + // Required. The queue where the message to be acked is stored. + string queue = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The primary key of the message to be acked. + google.protobuf.ListValue key = 2 [(google.api.field_behavior) = REQUIRED]; + + // By default, an attempt to ack a message that does not exist will fail + // with a `NOT_FOUND` error. With `ignore_not_found` set to true, the ack + // will succeed even if the message does not exist. This is useful for + // unconditionally acking a message, even if it is missing or has already + // been acked. + bool ignore_not_found = 3; + } + + // Required. The operation to perform. + oneof operation { + // Insert new rows in a table. If any of the rows already exist, + // the write or transaction fails with error `ALREADY_EXISTS`. + Write insert = 1; + + // Update existing rows in a table. If any of the rows does not + // already exist, the transaction fails with error `NOT_FOUND`. + Write update = 2; + + // Like [insert][google.spanner.v1.Mutation.insert], except that if the row + // already exists, then its column values are overwritten with the ones + // provided. Any column values not explicitly written are preserved. + // + // When using + // [insert_or_update][google.spanner.v1.Mutation.insert_or_update], just as + // when using [insert][google.spanner.v1.Mutation.insert], all `NOT NULL` + // columns in the table must be given a value. This holds true even when the + // row already exists and will therefore actually be updated. + Write insert_or_update = 3; + + // Like [insert][google.spanner.v1.Mutation.insert], except that if the row + // already exists, it is deleted, and the column values provided are + // inserted instead. Unlike + // [insert_or_update][google.spanner.v1.Mutation.insert_or_update], this + // means any values not explicitly written become `NULL`. + // + // In an interleaved table, if you create the child table with the + // `ON DELETE CASCADE` annotation, then replacing a parent row + // also deletes the child rows. Otherwise, you must delete the + // child rows before you replace the parent row. + Write replace = 4; + + // Delete rows from a table. Succeeds whether or not the named + // rows were present. + Delete delete = 5; + + // Send a message to a queue. + Send send = 6; + + // Ack a message from a queue. + Ack ack = 7; + } +} diff --git a/handwritten/spanner/protos/google/spanner/v1/query_plan.proto b/handwritten/spanner/protos/google/spanner/v1/query_plan.proto new file mode 100644 index 00000000000..5850ff97fb2 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/query_plan.proto @@ -0,0 +1,156 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/struct.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "QueryPlanProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// Node information for nodes appearing in a +// [QueryPlan.plan_nodes][google.spanner.v1.QueryPlan.plan_nodes]. +message PlanNode { + // The kind of [PlanNode][google.spanner.v1.PlanNode]. Distinguishes between + // the two different kinds of nodes that can appear in a query plan. + enum Kind { + // Not specified. + KIND_UNSPECIFIED = 0; + + // Denotes a Relational operator node in the expression tree. Relational + // operators represent iterative processing of rows during query execution. + // For example, a `TableScan` operation that reads rows from a table. + RELATIONAL = 1; + + // Denotes a Scalar node in the expression tree. Scalar nodes represent + // non-iterable entities in the query plan. For example, constants or + // arithmetic operators appearing inside predicate expressions or references + // to column names. + SCALAR = 2; + } + + // Metadata associated with a parent-child relationship appearing in a + // [PlanNode][google.spanner.v1.PlanNode]. + message ChildLink { + // The node to which the link points. + int32 child_index = 1; + + // The type of the link. For example, in Hash Joins this could be used to + // distinguish between the build child and the probe child, or in the case + // of the child being an output variable, to represent the tag associated + // with the output variable. + string type = 2; + + // Only present if the child node is + // [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] and corresponds to an + // output variable of the parent node. The field carries the name of the + // output variable. For example, a `TableScan` operator that reads rows from + // a table will have child links to the `SCALAR` nodes representing the + // output variables created for each column that is read by the operator. + // The corresponding `variable` fields will be set to the variable names + // assigned to the columns. + string variable = 3; + } + + // Condensed representation of a node and its subtree. Only present for + // `SCALAR` [PlanNode(s)][google.spanner.v1.PlanNode]. + message ShortRepresentation { + // A string representation of the expression subtree rooted at this node. + string description = 1; + + // A mapping of (subquery variable name) -> (subquery node id) for cases + // where the `description` string of this node references a `SCALAR` + // subquery contained in the expression subtree rooted at this node. The + // referenced `SCALAR` subquery may not necessarily be a direct child of + // this node. + map subqueries = 2; + } + + // The `PlanNode`'s index in [node + // list][google.spanner.v1.QueryPlan.plan_nodes]. + int32 index = 1; + + // Used to determine the type of node. May be needed for visualizing + // different kinds of nodes differently. For example, If the node is a + // [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] node, it will have a + // condensed representation which can be used to directly embed a description + // of the node in its parent. + Kind kind = 2; + + // The display name for the node. + string display_name = 3; + + // List of child node `index`es and their relationship to this parent. + repeated ChildLink child_links = 4; + + // Condensed representation for + // [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] nodes. + ShortRepresentation short_representation = 5; + + // Attributes relevant to the node contained in a group of key-value pairs. + // For example, a Parameter Reference node could have the following + // information in its metadata: + // + // { + // "parameter_reference": "param1", + // "parameter_type": "array" + // } + google.protobuf.Struct metadata = 6; + + // The execution statistics associated with the node, contained in a group of + // key-value pairs. Only present if the plan was returned as a result of a + // profile query. For example, number of executions, number of rows/time per + // execution etc. + google.protobuf.Struct execution_stats = 7; +} + +// Output of query advisor analysis. +message QueryAdvisorResult { + // Recommendation to add new indexes to run queries more efficiently. + message IndexAdvice { + // Optional. DDL statements to add new indexes that will improve the query. + repeated string ddl = 1 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Estimated latency improvement factor. For example if the query + // currently takes 500 ms to run and the estimated latency with new indexes + // is 100 ms this field will be 5. + double improvement_factor = 2 [(google.api.field_behavior) = OPTIONAL]; + } + + // Optional. Index Recommendation for a query. This is an optional field and + // the recommendation will only be available when the recommendation + // guarantees significant improvement in query performance. + repeated IndexAdvice index_advice = 1 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Contains an ordered list of nodes appearing in the query plan. +message QueryPlan { + // The nodes in the query plan. Plan nodes are returned in pre-order starting + // with the plan root. Each [PlanNode][google.spanner.v1.PlanNode]'s `id` + // corresponds to its index in `plan_nodes`. + repeated PlanNode plan_nodes = 1; + + // Optional. The advise/recommendations for a query. Currently this field will + // be serving index recommendations for a query. + QueryAdvisorResult query_advice = 2 [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/handwritten/spanner/protos/google/spanner/v1/result_set.proto b/handwritten/spanner/protos/google/spanner/v1/result_set.proto new file mode 100644 index 00000000000..3851d688ce2 --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/result_set.proto @@ -0,0 +1,260 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/struct.proto"; +import "google/spanner/v1/location.proto"; +import "google/spanner/v1/query_plan.proto"; +import "google/spanner/v1/transaction.proto"; +import "google/spanner/v1/type.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "ResultSetProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// Results from [Read][google.spanner.v1.Spanner.Read] or +// [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. +message ResultSet { + // Metadata about the result set, such as row type information. + ResultSetMetadata metadata = 1; + + // Each element in `rows` is a row whose format is defined by + // [metadata.row_type][google.spanner.v1.ResultSetMetadata.row_type]. The ith + // element in each row matches the ith field in + // [metadata.row_type][google.spanner.v1.ResultSetMetadata.row_type]. Elements + // are encoded based on type as described [here][google.spanner.v1.TypeCode]. + repeated google.protobuf.ListValue rows = 2; + + // Query plan and execution statistics for the SQL statement that + // produced this result set. These can be requested by setting + // [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode]. + // DML statements always produce stats containing the number of rows + // modified, unless executed using the + // [ExecuteSqlRequest.QueryMode.PLAN][google.spanner.v1.ExecuteSqlRequest.QueryMode.PLAN] + // [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode]. + // Other fields might or might not be populated, based on the + // [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode]. + ResultSetStats stats = 3; + + // Optional. A precommit token is included if the read-write transaction is on + // a multiplexed session. Pass the precommit token with the highest sequence + // number from this transaction attempt to the + // [Commit][google.spanner.v1.Spanner.Commit] request for this transaction. + MultiplexedSessionPrecommitToken precommit_token = 5 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A cache update expresses a set of changes the client should + // incorporate into its location cache. The client should discard the changes + // if they are older than the data it already has. This data can be obtained + // in response to requests that included a `RoutingHint` field, but may also + // be obtained by explicit location-fetching RPCs which may be added in the + // future. + CacheUpdate cache_update = 6 [(google.api.field_behavior) = OPTIONAL]; +} + +// Partial results from a streaming read or SQL query. Streaming reads and +// SQL queries better tolerate large result sets, large rows, and large +// values, but are a little trickier to consume. +message PartialResultSet { + // Metadata about the result set, such as row type information. + // Only present in the first response. + ResultSetMetadata metadata = 1; + + // A streamed result set consists of a stream of values, which might + // be split into many `PartialResultSet` messages to accommodate + // large rows and/or large values. Every N complete values defines a + // row, where N is equal to the number of entries in + // [metadata.row_type.fields][google.spanner.v1.StructType.fields]. + // + // Most values are encoded based on type as described + // [here][google.spanner.v1.TypeCode]. + // + // It's possible that the last value in values is "chunked", + // meaning that the rest of the value is sent in subsequent + // `PartialResultSet`(s). This is denoted by the + // [chunked_value][google.spanner.v1.PartialResultSet.chunked_value] field. + // Two or more chunked values can be merged to form a complete value as + // follows: + // + // * `bool/number/null`: can't be chunked + // * `string`: concatenate the strings + // * `list`: concatenate the lists. If the last element in a list is a + // `string`, `list`, or `object`, merge it with the first element in + // the next list by applying these rules recursively. + // * `object`: concatenate the (field name, field value) pairs. If a + // field name is duplicated, then apply these rules recursively + // to merge the field values. + // + // Some examples of merging: + // + // Strings are concatenated. + // "foo", "bar" => "foobar" + // + // Lists of non-strings are concatenated. + // [2, 3], [4] => [2, 3, 4] + // + // Lists are concatenated, but the last and first elements are merged + // because they are strings. + // ["a", "b"], ["c", "d"] => ["a", "bc", "d"] + // + // Lists are concatenated, but the last and first elements are merged + // because they are lists. Recursively, the last and first elements + // of the inner lists are merged because they are strings. + // ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"] + // + // Non-overlapping object fields are combined. + // {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"} + // + // Overlapping object fields are merged. + // {"a": "1"}, {"a": "2"} => {"a": "12"} + // + // Examples of merging objects containing lists of strings. + // {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]} + // + // For a more complete example, suppose a streaming SQL query is + // yielding a result set whose rows contain a single string + // field. The following `PartialResultSet`s might be yielded: + // + // { + // "metadata": { ... } + // "values": ["Hello", "W"] + // "chunked_value": true + // "resume_token": "Af65..." + // } + // { + // "values": ["orl"] + // "chunked_value": true + // } + // { + // "values": ["d"] + // "resume_token": "Zx1B..." + // } + // + // This sequence of `PartialResultSet`s encodes two rows, one + // containing the field value `"Hello"`, and a second containing the + // field value `"World" = "W" + "orl" + "d"`. + // + // Not all `PartialResultSet`s contain a `resume_token`. Execution can only be + // resumed from a previously yielded `resume_token`. For the above sequence of + // `PartialResultSet`s, resuming the query with `"resume_token": "Af65..."` + // yields results from the `PartialResultSet` with value "orl". + repeated google.protobuf.Value values = 2; + + // If true, then the final value in + // [values][google.spanner.v1.PartialResultSet.values] is chunked, and must be + // combined with more values from subsequent `PartialResultSet`s to obtain a + // complete field value. + bool chunked_value = 3; + + // Streaming calls might be interrupted for a variety of reasons, such + // as TCP connection loss. If this occurs, the stream of results can + // be resumed by re-sending the original request and including + // `resume_token`. Note that executing any other transaction in the + // same session invalidates the token. + bytes resume_token = 4; + + // Query plan and execution statistics for the statement that produced this + // streaming result set. These can be requested by setting + // [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] + // and are sent only once with the last response in the stream. This field is + // also present in the last response for DML statements. + ResultSetStats stats = 5; + + // Optional. A precommit token is included if the read-write transaction + // has multiplexed sessions enabled. Pass the precommit token with the highest + // sequence number from this transaction attempt to the + // [Commit][google.spanner.v1.Spanner.Commit] request for this transaction. + MultiplexedSessionPrecommitToken precommit_token = 8 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Indicates whether this is the last `PartialResultSet` in the + // stream. The server might optionally set this field. Clients shouldn't rely + // on this field being set in all cases. + bool last = 9 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A cache update expresses a set of changes the client should + // incorporate into its location cache. The client should discard the changes + // if they are older than the data it already has. This data can be obtained + // in response to requests that included a `RoutingHint` field, but may also + // be obtained by explicit location-fetching RPCs which may be added in the + // future. + CacheUpdate cache_update = 10 [(google.api.field_behavior) = OPTIONAL]; +} + +// Metadata about a [ResultSet][google.spanner.v1.ResultSet] or +// [PartialResultSet][google.spanner.v1.PartialResultSet]. +message ResultSetMetadata { + // Indicates the field names and types for the rows in the result + // set. For example, a SQL query like `"SELECT UserId, UserName FROM + // Users"` could return a `row_type` value like: + // + // "fields": [ + // { "name": "UserId", "type": { "code": "INT64" } }, + // { "name": "UserName", "type": { "code": "STRING" } }, + // ] + StructType row_type = 1; + + // If the read or SQL query began a transaction as a side-effect, the + // information about the new transaction is yielded here. + Transaction transaction = 2; + + // A SQL query can be parameterized. In PLAN mode, these parameters can be + // undeclared. This indicates the field names and types for those undeclared + // parameters in the SQL query. For example, a SQL query like `"SELECT * FROM + // Users where UserId = @userId and UserName = @userName "` could return a + // `undeclared_parameters` value like: + // + // "fields": [ + // { "name": "UserId", "type": { "code": "INT64" } }, + // { "name": "UserName", "type": { "code": "STRING" } }, + // ] + StructType undeclared_parameters = 3; +} + +// Additional statistics about a [ResultSet][google.spanner.v1.ResultSet] or +// [PartialResultSet][google.spanner.v1.PartialResultSet]. +message ResultSetStats { + // [QueryPlan][google.spanner.v1.QueryPlan] for the query associated with this + // result. + QueryPlan query_plan = 1; + + // Aggregated statistics from the execution of the query. Only present when + // the query is profiled. For example, a query could return the statistics as + // follows: + // + // { + // "rows_returned": "3", + // "elapsed_time": "1.22 secs", + // "cpu_time": "1.19 secs" + // } + google.protobuf.Struct query_stats = 2; + + // The number of rows modified by the DML statement. + oneof row_count { + // Standard DML returns an exact count of rows that were modified. + int64 row_count_exact = 3; + + // Partitioned DML doesn't offer exactly-once semantics, so it + // returns a lower bound of the rows modified. + int64 row_count_lower_bound = 4; + } +} diff --git a/handwritten/spanner/protos/google/spanner/v1/spanner.proto b/handwritten/spanner/protos/google/spanner/v1/spanner.proto new file mode 100644 index 00000000000..525cc2ba47a --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/spanner.proto @@ -0,0 +1,1419 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import public "google/spanner/v1/commit_response.proto"; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; +import "google/rpc/status.proto"; +import "google/spanner/v1/keys.proto"; +import "google/spanner/v1/location.proto"; +import "google/spanner/v1/mutation.proto"; +import "google/spanner/v1/result_set.proto"; +import "google/spanner/v1/transaction.proto"; +import "google/spanner/v1/type.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "SpannerProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; +option (google.api.resource_definition) = { + type: "spanner.googleapis.com/Database" + pattern: "projects/{project}/instances/{instance}/databases/{database}" +}; + +// Cloud Spanner API +// +// The Cloud Spanner API can be used to manage sessions and execute +// transactions on data stored in Cloud Spanner databases. +service Spanner { + option (google.api.default_host) = "spanner.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/cloud-platform," + "https://www.googleapis.com/auth/spanner.data"; + + // Creates a new session. A session can be used to perform + // transactions that read and/or modify data in a Cloud Spanner database. + // Sessions are meant to be reused for many consecutive + // transactions. + // + // Sessions can only execute one transaction at a time. To execute + // multiple concurrent read-write/write-only transactions, create + // multiple sessions. Note that standalone reads and queries use a + // transaction internally, and count toward the one transaction + // limit. + // + // Active sessions use additional server resources, so it's a good idea to + // delete idle and unneeded sessions. + // Aside from explicit deletes, Cloud Spanner can delete sessions when no + // operations are sent for more than an hour. If a session is deleted, + // requests to it return `NOT_FOUND`. + // + // Idle sessions can be kept alive by sending a trivial SQL query + // periodically, for example, `"SELECT 1"`. + rpc CreateSession(CreateSessionRequest) returns (Session) { + option (google.api.http) = { + post: "/v1/{database=projects/*/instances/*/databases/*}/sessions" + body: "*" + }; + option (google.api.method_signature) = "database"; + } + + // Creates multiple new sessions. + // + // This API can be used to initialize a session cache on the clients. + // See https://goo.gl/TgSFN2 for best practices on session cache management. + rpc BatchCreateSessions(BatchCreateSessionsRequest) + returns (BatchCreateSessionsResponse) { + option (google.api.http) = { + post: "/v1/{database=projects/*/instances/*/databases/*}/sessions:batchCreate" + body: "*" + }; + option (google.api.method_signature) = "database,session_count"; + } + + // Gets a session. Returns `NOT_FOUND` if the session doesn't exist. + // This is mainly useful for determining whether a session is still + // alive. + rpc GetSession(GetSessionRequest) returns (Session) { + option (google.api.http) = { + get: "/v1/{name=projects/*/instances/*/databases/*/sessions/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists all sessions in a given database. + rpc ListSessions(ListSessionsRequest) returns (ListSessionsResponse) { + option (google.api.http) = { + get: "/v1/{database=projects/*/instances/*/databases/*}/sessions" + }; + option (google.api.method_signature) = "database"; + } + + // Ends a session, releasing server resources associated with it. This + // asynchronously triggers the cancellation of any operations that are running + // with this session. + rpc DeleteSession(DeleteSessionRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/instances/*/databases/*/sessions/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Executes an SQL statement, returning all results in a single reply. This + // method can't be used to return a result set larger than 10 MiB; + // if the query yields more data than that, the query fails with + // a `FAILED_PRECONDITION` error. + // + // Operations inside read-write transactions might return `ABORTED`. If + // this occurs, the application should restart the transaction from + // the beginning. See [Transaction][google.spanner.v1.Transaction] for more + // details. + // + // Larger result sets can be fetched in streaming fashion by calling + // [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] + // instead. + // + // The query string can be SQL or [Graph Query Language + // (GQL)](https://cloud.google.com/spanner/docs/reference/standard-sql/graph-intro). + rpc ExecuteSql(ExecuteSqlRequest) returns (ResultSet) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeSql" + body: "*" + }; + } + + // Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the + // result set as a stream. Unlike + // [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there is no limit on + // the size of the returned result set. However, no individual row in the + // result set can exceed 100 MiB, and no column value can exceed 10 MiB. + // + // The query string can be SQL or [Graph Query Language + // (GQL)](https://cloud.google.com/spanner/docs/reference/standard-sql/graph-intro). + rpc ExecuteStreamingSql(ExecuteSqlRequest) returns (stream PartialResultSet) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeStreamingSql" + body: "*" + }; + } + + // Executes a batch of SQL DML statements. This method allows many statements + // to be run with lower latency than submitting them sequentially with + // [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. + // + // Statements are executed in sequential order. A request can succeed even if + // a statement fails. The + // [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status] + // field in the response provides information about the statement that failed. + // Clients must inspect this field to determine whether an error occurred. + // + // Execution stops after the first failed statement; the remaining statements + // are not executed. + rpc ExecuteBatchDml(ExecuteBatchDmlRequest) + returns (ExecuteBatchDmlResponse) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeBatchDml" + body: "*" + }; + } + + // Reads rows from the database using key lookups and scans, as a + // simple key/value style alternative to + // [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method can't be + // used to return a result set larger than 10 MiB; if the read matches more + // data than that, the read fails with a `FAILED_PRECONDITION` + // error. + // + // Reads inside read-write transactions might return `ABORTED`. If + // this occurs, the application should restart the transaction from + // the beginning. See [Transaction][google.spanner.v1.Transaction] for more + // details. + // + // Larger result sets can be yielded in streaming fashion by calling + // [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. + rpc Read(ReadRequest) returns (ResultSet) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:read" + body: "*" + }; + } + + // Like [Read][google.spanner.v1.Spanner.Read], except returns the result set + // as a stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no + // limit on the size of the returned result set. However, no individual row in + // the result set can exceed 100 MiB, and no column value can exceed + // 10 MiB. + rpc StreamingRead(ReadRequest) returns (stream PartialResultSet) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:streamingRead" + body: "*" + }; + } + + // Begins a new transaction. This step can often be skipped: + // [Read][google.spanner.v1.Spanner.Read], + // [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and + // [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a + // side-effect. + rpc BeginTransaction(BeginTransactionRequest) returns (Transaction) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:beginTransaction" + body: "*" + }; + option (google.api.method_signature) = "session,options"; + } + + // Commits a transaction. The request includes the mutations to be + // applied to rows in the database. + // + // `Commit` might return an `ABORTED` error. This can occur at any time; + // commonly, the cause is conflicts with concurrent + // transactions. However, it can also happen for a variety of other + // reasons. If `Commit` returns `ABORTED`, the caller should retry + // the transaction from the beginning, reusing the same session. + // + // On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, + // for example, if the client job experiences a 1+ hour networking failure. + // At that point, Cloud Spanner has lost track of the transaction outcome and + // we recommend that you perform another read from the database to see the + // state of things as they are now. + rpc Commit(CommitRequest) returns (CommitResponse) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:commit" + body: "*" + }; + option (google.api.method_signature) = "session,transaction_id,mutations"; + option (google.api.method_signature) = + "session,single_use_transaction,mutations"; + } + + // Rolls back a transaction, releasing any locks it holds. It's a good + // idea to call this for any transaction that includes one or more + // [Read][google.spanner.v1.Spanner.Read] or + // [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and ultimately + // decides not to commit. + // + // `Rollback` returns `OK` if it successfully aborts the transaction, the + // transaction was already aborted, or the transaction isn't + // found. `Rollback` never returns `ABORTED`. + rpc Rollback(RollbackRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:rollback" + body: "*" + }; + option (google.api.method_signature) = "session,transaction_id"; + } + + // Creates a set of partition tokens that can be used to execute a query + // operation in parallel. Each of the returned partition tokens can be used + // by [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] to + // specify a subset of the query result to read. The same session and + // read-only transaction must be used by the `PartitionQueryRequest` used to + // create the partition tokens and the `ExecuteSqlRequests` that use the + // partition tokens. + // + // Partition tokens become invalid when the session used to create them + // is deleted, is idle for too long, begins a new transaction, or becomes too + // old. When any of these happen, it isn't possible to resume the query, and + // the whole operation must be restarted from the beginning. + rpc PartitionQuery(PartitionQueryRequest) returns (PartitionResponse) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:partitionQuery" + body: "*" + }; + } + + // Creates a set of partition tokens that can be used to execute a read + // operation in parallel. Each of the returned partition tokens can be used + // by [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to specify a + // subset of the read result to read. The same session and read-only + // transaction must be used by the `PartitionReadRequest` used to create the + // partition tokens and the `ReadRequests` that use the partition tokens. + // There are no ordering guarantees on rows returned among the returned + // partition tokens, or even within each individual `StreamingRead` call + // issued with a `partition_token`. + // + // Partition tokens become invalid when the session used to create them + // is deleted, is idle for too long, begins a new transaction, or becomes too + // old. When any of these happen, it isn't possible to resume the read, and + // the whole operation must be restarted from the beginning. + rpc PartitionRead(PartitionReadRequest) returns (PartitionResponse) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:partitionRead" + body: "*" + }; + } + + // Batches the supplied mutation groups in a collection of efficient + // transactions. All mutations in a group are committed atomically. However, + // mutations across groups can be committed non-atomically in an unspecified + // order and thus, they must be independent of each other. Partial failure is + // possible, that is, some groups might have been committed successfully, + // while some might have failed. The results of individual batches are + // streamed into the response as the batches are applied. + // + // `BatchWrite` requests are not replay protected, meaning that each mutation + // group can be applied more than once. Replays of non-idempotent mutations + // can have undesirable effects. For example, replays of an insert mutation + // can produce an already exists error or if you use generated or commit + // timestamp-based keys, it can result in additional rows being added to the + // mutation's table. We recommend structuring your mutation groups to be + // idempotent to avoid this issue. + rpc BatchWrite(BatchWriteRequest) returns (stream BatchWriteResponse) { + option (google.api.http) = { + post: "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:batchWrite" + body: "*" + }; + option (google.api.method_signature) = "session,mutation_groups"; + } +} + +// The request for [CreateSession][google.spanner.v1.Spanner.CreateSession]. +message CreateSessionRequest { + // Required. The database in which the new session is created. + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Required. The session to create. + Session session = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [BatchCreateSessions][google.spanner.v1.Spanner.BatchCreateSessions]. +message BatchCreateSessionsRequest { + // Required. The database in which the new sessions are created. + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Parameters to apply to each created session. + Session session_template = 2; + + // Required. The number of sessions to be created in this batch call. At least + // one session is created. The API can return fewer than the requested number + // of sessions. If a specific number of sessions are desired, the client can + // make additional calls to `BatchCreateSessions` (adjusting + // [session_count][google.spanner.v1.BatchCreateSessionsRequest.session_count] + // as necessary). + int32 session_count = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// The response for +// [BatchCreateSessions][google.spanner.v1.Spanner.BatchCreateSessions]. +message BatchCreateSessionsResponse { + // The freshly created sessions. + repeated Session session = 1; +} + +// A session in the Cloud Spanner API. +message Session { + option (google.api.resource) = { + type: "spanner.googleapis.com/Session" + pattern: "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}" + plural: "sessions" + singular: "session" + }; + + // Output only. The name of the session. This is always system-assigned. + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // The labels for the session. + // + // * Label keys must be between 1 and 63 characters long and must conform to + // the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`. + // * Label values must be between 0 and 63 characters long and must conform + // to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`. + // * No more than 64 labels can be associated with a given session. + // + // See https://goo.gl/xmQnxf for more information on and examples of labels. + map labels = 2; + + // Output only. The timestamp when the session is created. + google.protobuf.Timestamp create_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The approximate timestamp when the session is last used. It's + // typically earlier than the actual last use time. + google.protobuf.Timestamp approximate_last_use_time = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // The database role which created this session. + string creator_role = 5; + + // Optional. If `true`, specifies a multiplexed session. Use a multiplexed + // session for multiple, concurrent operations including any combination of + // read-only and read-write transactions. Use + // [`sessions.create`][google.spanner.v1.Spanner.CreateSession] to create + // multiplexed sessions. Don't use + // [BatchCreateSessions][google.spanner.v1.Spanner.BatchCreateSessions] to + // create a multiplexed session. You can't delete or list multiplexed + // sessions. + bool multiplexed = 6 [(google.api.field_behavior) = OPTIONAL]; +} + +// The request for [GetSession][google.spanner.v1.Spanner.GetSession]. +message GetSessionRequest { + // Required. The name of the session to retrieve. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; +} + +// The request for [ListSessions][google.spanner.v1.Spanner.ListSessions]. +message ListSessionsRequest { + // Required. The database in which to list sessions. + string database = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "spanner.googleapis.com/Database" + } + ]; + + // Number of sessions to be returned in the response. If 0 or less, defaults + // to the server's maximum allowed page size. + int32 page_size = 2; + + // If non-empty, `page_token` should contain a + // [next_page_token][google.spanner.v1.ListSessionsResponse.next_page_token] + // from a previous + // [ListSessionsResponse][google.spanner.v1.ListSessionsResponse]. + string page_token = 3; + + // An expression for filtering the results of the request. Filter rules are + // case insensitive. The fields eligible for filtering are: + // + // * `labels.key` where key is the name of a label + // + // Some examples of using filters are: + // + // * `labels.env:*` --> The session has the label "env". + // * `labels.env:dev` --> The session has the label "env" and the value of + // the label contains the string "dev". + string filter = 4; +} + +// The response for [ListSessions][google.spanner.v1.Spanner.ListSessions]. +message ListSessionsResponse { + // The list of requested sessions. + repeated Session sessions = 1; + + // `next_page_token` can be sent in a subsequent + // [ListSessions][google.spanner.v1.Spanner.ListSessions] call to fetch more + // of the matching sessions. + string next_page_token = 2; +} + +// The request for [DeleteSession][google.spanner.v1.Spanner.DeleteSession]. +message DeleteSessionRequest { + // Required. The name of the session to delete. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; +} + +// Common request options for various APIs. +message RequestOptions { + // The relative priority for requests. Note that priority isn't applicable + // for [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction]. + // + // The priority acts as a hint to the Cloud Spanner scheduler and doesn't + // guarantee priority or order of execution. For example: + // + // * Some parts of a write operation always execute at `PRIORITY_HIGH`, + // regardless of the specified priority. This can cause you to see an + // increase in high priority workload even when executing a low priority + // request. This can also potentially cause a priority inversion where a + // lower priority request is fulfilled ahead of a higher priority + // request. + // * If a transaction contains multiple operations with different priorities, + // Cloud Spanner doesn't guarantee to process the higher priority + // operations first. There might be other constraints to satisfy, such as + // the order of operations. + enum Priority { + // `PRIORITY_UNSPECIFIED` is equivalent to `PRIORITY_HIGH`. + PRIORITY_UNSPECIFIED = 0; + + // This specifies that the request is low priority. + PRIORITY_LOW = 1; + + // This specifies that the request is medium priority. + PRIORITY_MEDIUM = 2; + + // This specifies that the request is high priority. + PRIORITY_HIGH = 3; + } + + // Container for various pieces of client-owned context attached to a request. + message ClientContext { + // Optional. Map of parameter name to value for this request. These values + // will be returned by any SECURE_CONTEXT() calls invoked by this request + // (e.g., by queries against Parameterized Secure Views). + map secure_context = 1 + [(google.api.field_behavior) = OPTIONAL]; + } + + // Priority for the request. + Priority priority = 1; + + // A per-request tag which can be applied to queries or reads, used for + // statistics collection. + // Both `request_tag` and `transaction_tag` can be specified for a read or + // query that belongs to a transaction. + // This field is ignored for requests where it's not applicable (for example, + // `CommitRequest`). + // Legal characters for `request_tag` values are all printable characters + // (ASCII 32 - 126) and the length of a request_tag is limited to 50 + // characters. Values that exceed this limit are truncated. + // Any leading underscore (_) characters are removed from the string. + string request_tag = 2; + + // A tag used for statistics collection about this transaction. + // Both `request_tag` and `transaction_tag` can be specified for a read or + // query that belongs to a transaction. + // To enable tagging on a transaction, `transaction_tag` must be set to the + // same value for all requests belonging to the same transaction, including + // [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction]. + // If this request doesn't belong to any transaction, `transaction_tag` is + // ignored. + // Legal characters for `transaction_tag` values are all printable characters + // (ASCII 32 - 126) and the length of a `transaction_tag` is limited to 50 + // characters. Values that exceed this limit are truncated. + // Any leading underscore (_) characters are removed from the string. + string transaction_tag = 3; + + // Optional. Optional context that may be needed for some requests. + ClientContext client_context = 4 [(google.api.field_behavior) = OPTIONAL]; +} + +// The `DirectedReadOptions` can be used to indicate which replicas or regions +// should be used for non-transactional reads or queries. +// +// `DirectedReadOptions` can only be specified for a read-only transaction, +// otherwise the API returns an `INVALID_ARGUMENT` error. +message DirectedReadOptions { + // The directed read replica selector. + // Callers must provide one or more of the following fields for replica + // selection: + // + // * `location` - The location must be one of the regions within the + // multi-region configuration of your database. + // * `type` - The type of the replica. + // + // Some examples of using replica_selectors are: + // + // * `location:us-east1` --> The "us-east1" replica(s) of any available type + // is used to process the request. + // * `type:READ_ONLY` --> The "READ_ONLY" type replica(s) in the nearest + // available location are used to process the + // request. + // * `location:us-east1 type:READ_ONLY` --> The "READ_ONLY" type replica(s) + // in location "us-east1" is used to process + // the request. + message ReplicaSelection { + // Indicates the type of replica. + enum Type { + // Not specified. + TYPE_UNSPECIFIED = 0; + + // Read-write replicas support both reads and writes. + READ_WRITE = 1; + + // Read-only replicas only support reads (not writes). + READ_ONLY = 2; + } + + // The location or region of the serving requests, for example, "us-east1". + string location = 1; + + // The type of replica. + Type type = 2; + } + + // An `IncludeReplicas` contains a repeated set of `ReplicaSelection` which + // indicates the order in which replicas should be considered. + message IncludeReplicas { + // The directed read replica selector. + repeated ReplicaSelection replica_selections = 1; + + // If `true`, Spanner doesn't route requests to a replica outside the + // <`include_replicas` list when all of the specified replicas are + // unavailable or unhealthy. Default value is `false`. + bool auto_failover_disabled = 2; + } + + // An ExcludeReplicas contains a repeated set of ReplicaSelection that should + // be excluded from serving requests. + message ExcludeReplicas { + // The directed read replica selector. + repeated ReplicaSelection replica_selections = 1; + } + + // Required. At most one of either `include_replicas` or `exclude_replicas` + // should be present in the message. + oneof replicas { + // `Include_replicas` indicates the order of replicas (as they appear in + // this list) to process the request. If `auto_failover_disabled` is set to + // `true` and all replicas are exhausted without finding a healthy replica, + // Spanner waits for a replica in the list to become available, requests + // might fail due to `DEADLINE_EXCEEDED` errors. + IncludeReplicas include_replicas = 1; + + // `Exclude_replicas` indicates that specified replicas should be excluded + // from serving requests. Spanner doesn't route requests to the replicas + // in this list. + ExcludeReplicas exclude_replicas = 2; + } +} + +// The request for [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and +// [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]. +message ExecuteSqlRequest { + // Mode in which the statement must be processed. + enum QueryMode { + // The default mode. Only the statement results are returned. + NORMAL = 0; + + // This mode returns only the query plan, without any results or + // execution statistics information. + PLAN = 1; + + // This mode returns the query plan, overall execution statistics, + // operator level execution statistics along with the results. This has a + // performance overhead compared to the other modes. It isn't recommended + // to use this mode for production traffic. + PROFILE = 2; + + // This mode returns the overall (but not operator-level) execution + // statistics along with the results. + WITH_STATS = 3; + + // This mode returns the query plan, overall (but not operator-level) + // execution statistics along with the results. + WITH_PLAN_AND_STATS = 4; + } + + // Query optimizer configuration. + message QueryOptions { + // An option to control the selection of optimizer version. + // + // This parameter allows individual queries to pick different query + // optimizer versions. + // + // Specifying `latest` as a value instructs Cloud Spanner to use the + // latest supported query optimizer version. If not specified, Cloud Spanner + // uses the optimizer version set at the database level options. Any other + // positive integer (from the list of supported optimizer versions) + // overrides the default optimizer version for query execution. + // + // The list of supported optimizer versions can be queried from + // `SPANNER_SYS.SUPPORTED_OPTIMIZER_VERSIONS`. + // + // Executing a SQL statement with an invalid optimizer version fails with + // an `INVALID_ARGUMENT` error. + // + // See + // https://cloud.google.com/spanner/docs/query-optimizer/manage-query-optimizer + // for more information on managing the query optimizer. + // + // The `optimizer_version` statement hint has precedence over this setting. + string optimizer_version = 1; + + // An option to control the selection of optimizer statistics package. + // + // This parameter allows individual queries to use a different query + // optimizer statistics package. + // + // Specifying `latest` as a value instructs Cloud Spanner to use the latest + // generated statistics package. If not specified, Cloud Spanner uses + // the statistics package set at the database level options, or the latest + // package if the database option isn't set. + // + // The statistics package requested by the query has to be exempt from + // garbage collection. This can be achieved with the following DDL + // statement: + // + // ```sql + // ALTER STATISTICS SET OPTIONS (allow_gc=false) + // ``` + // + // The list of available statistics packages can be queried from + // `INFORMATION_SCHEMA.SPANNER_STATISTICS`. + // + // Executing a SQL statement with an invalid optimizer statistics package + // or with a statistics package that allows garbage collection fails with + // an `INVALID_ARGUMENT` error. + string optimizer_statistics_package = 2; + } + + // Required. The session in which the SQL query should be performed. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // The transaction to use. + // + // For queries, if none is provided, the default is a temporary read-only + // transaction with strong concurrency. + // + // Standard DML statements require a read-write transaction. To protect + // against replays, single-use transactions are not supported. The caller + // must either supply an existing transaction ID or begin a new transaction. + // + // Partitioned DML requires an existing Partitioned DML transaction ID. + TransactionSelector transaction = 2; + + // Required. The SQL string. + string sql = 3 [(google.api.field_behavior) = REQUIRED]; + + // Parameter names and values that bind to placeholders in the SQL string. + // + // A parameter placeholder consists of the `@` character followed by the + // parameter name (for example, `@firstName`). Parameter names must conform + // to the naming requirements of identifiers as specified at + // https://cloud.google.com/spanner/docs/lexical#identifiers. + // + // Parameters can appear anywhere that a literal value is expected. The same + // parameter name can be used more than once, for example: + // + // `"WHERE id > @msg_id AND id < @msg_id + 100"` + // + // It's an error to execute a SQL statement with unbound parameters. + google.protobuf.Struct params = 4; + + // It isn't always possible for Cloud Spanner to infer the right SQL type + // from a JSON value. For example, values of type `BYTES` and values + // of type `STRING` both appear in + // [params][google.spanner.v1.ExecuteSqlRequest.params] as JSON strings. + // + // In these cases, you can use `param_types` to specify the exact + // SQL type for some or all of the SQL statement parameters. See the + // definition of [Type][google.spanner.v1.Type] for more information + // about SQL types. + map param_types = 5; + + // If this request is resuming a previously interrupted SQL statement + // execution, `resume_token` should be copied from the last + // [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the + // interruption. Doing this enables the new SQL statement execution to resume + // where the last one left off. The rest of the request parameters must + // exactly match the request that yielded this token. + bytes resume_token = 6; + + // Used to control the amount of debugging information returned in + // [ResultSetStats][google.spanner.v1.ResultSetStats]. If + // [partition_token][google.spanner.v1.ExecuteSqlRequest.partition_token] is + // set, [query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] can only + // be set to + // [QueryMode.NORMAL][google.spanner.v1.ExecuteSqlRequest.QueryMode.NORMAL]. + QueryMode query_mode = 7; + + // If present, results are restricted to the specified partition + // previously created using `PartitionQuery`. There must be an exact + // match for the values of fields common to this message and the + // `PartitionQueryRequest` message used to create this `partition_token`. + bytes partition_token = 8; + + // A per-transaction sequence number used to identify this request. This field + // makes each request idempotent such that if the request is received multiple + // times, at most one succeeds. + // + // The sequence number must be monotonically increasing within the + // transaction. If a request arrives for the first time with an out-of-order + // sequence number, the transaction can be aborted. Replays of previously + // handled requests yield the same response as the first execution. + // + // Required for DML statements. Ignored for queries. + int64 seqno = 9; + + // Query optimizer configuration to use for the given query. + QueryOptions query_options = 10; + + // Common options for this request. + RequestOptions request_options = 11; + + // Directed read options for this request. + DirectedReadOptions directed_read_options = 15; + + // If this is for a partitioned query and this field is set to `true`, the + // request is executed with Spanner Data Boost independent compute resources. + // + // If the field is set to `true` but the request doesn't set + // `partition_token`, the API returns an `INVALID_ARGUMENT` error. + bool data_boost_enabled = 16; + + // Optional. If set to `true`, this statement marks the end of the + // transaction. After this statement executes, you must commit or abort the + // transaction. Attempts to execute any other requests against this + // transaction (including reads and queries) are rejected. + // + // For DML statements, setting this option might cause some error reporting to + // be deferred until commit time (for example, validation of unique + // constraints). Given this, successful execution of a DML statement shouldn't + // be assumed until a subsequent `Commit` call completes successfully. + bool last_statement = 17 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If present, it makes the Spanner requests location-aware. + // + // It gives the server hints that can be used to route the request + // to an appropriate server, potentially significantly decreasing latency and + // improving throughput. To achieve improved performance, most fields must be + // filled in with accurate values. + RoutingHint routing_hint = 18 [(google.api.field_behavior) = OPTIONAL]; +} + +// The request for [ExecuteBatchDml][google.spanner.v1.Spanner.ExecuteBatchDml]. +message ExecuteBatchDmlRequest { + // A single DML statement. + message Statement { + // Required. The DML string. + string sql = 1 [(google.api.field_behavior) = REQUIRED]; + + // Parameter names and values that bind to placeholders in the DML string. + // + // A parameter placeholder consists of the `@` character followed by the + // parameter name (for example, `@firstName`). Parameter names can contain + // letters, numbers, and underscores. + // + // Parameters can appear anywhere that a literal value is expected. The + // same parameter name can be used more than once, for example: + // + // `"WHERE id > @msg_id AND id < @msg_id + 100"` + // + // It's an error to execute a SQL statement with unbound parameters. + google.protobuf.Struct params = 2; + + // It isn't always possible for Cloud Spanner to infer the right SQL type + // from a JSON value. For example, values of type `BYTES` and values + // of type `STRING` both appear in + // [params][google.spanner.v1.ExecuteBatchDmlRequest.Statement.params] as + // JSON strings. + // + // In these cases, `param_types` can be used to specify the exact + // SQL type for some or all of the SQL statement parameters. See the + // definition of [Type][google.spanner.v1.Type] for more information + // about SQL types. + map param_types = 3; + } + + // Required. The session in which the DML statements should be performed. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // Required. The transaction to use. Must be a read-write transaction. + // + // To protect against replays, single-use transactions are not supported. The + // caller must either supply an existing transaction ID or begin a new + // transaction. + TransactionSelector transaction = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The list of statements to execute in this batch. Statements are + // executed serially, such that the effects of statement `i` are visible to + // statement `i+1`. Each statement must be a DML statement. Execution stops at + // the first failed statement; the remaining statements are not executed. + // + // Callers must provide at least one statement. + repeated Statement statements = 3 [(google.api.field_behavior) = REQUIRED]; + + // Required. A per-transaction sequence number used to identify this request. + // This field makes each request idempotent such that if the request is + // received multiple times, at most one succeeds. + // + // The sequence number must be monotonically increasing within the + // transaction. If a request arrives for the first time with an out-of-order + // sequence number, the transaction might be aborted. Replays of previously + // handled requests yield the same response as the first execution. + int64 seqno = 4 [(google.api.field_behavior) = REQUIRED]; + + // Common options for this request. + RequestOptions request_options = 5; + + // Optional. If set to `true`, this request marks the end of the transaction. + // After these statements execute, you must commit or abort the transaction. + // Attempts to execute any other requests against this transaction + // (including reads and queries) are rejected. + // + // Setting this option might cause some error reporting to be deferred until + // commit time (for example, validation of unique constraints). Given this, + // successful execution of statements shouldn't be assumed until a subsequent + // `Commit` call completes successfully. + bool last_statements = 6 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [ExecuteBatchDml][google.spanner.v1.Spanner.ExecuteBatchDml]. Contains a list +// of [ResultSet][google.spanner.v1.ResultSet] messages, one for each DML +// statement that has successfully executed, in the same order as the statements +// in the request. If a statement fails, the status in the response body +// identifies the cause of the failure. +// +// To check for DML statements that failed, use the following approach: +// +// 1. Check the status in the response message. The +// [google.rpc.Code][google.rpc.Code] enum +// value `OK` indicates that all statements were executed successfully. +// 2. If the status was not `OK`, check the number of result sets in the +// response. If the response contains `N` +// [ResultSet][google.spanner.v1.ResultSet] messages, then statement `N+1` in +// the request failed. +// +// Example 1: +// +// * Request: 5 DML statements, all executed successfully. +// * Response: 5 [ResultSet][google.spanner.v1.ResultSet] messages, with the +// status `OK`. +// +// Example 2: +// +// * Request: 5 DML statements. The third statement has a syntax error. +// * Response: 2 [ResultSet][google.spanner.v1.ResultSet] messages, and a syntax +// error (`INVALID_ARGUMENT`) +// status. The number of [ResultSet][google.spanner.v1.ResultSet] messages +// indicates that the third statement failed, and the fourth and fifth +// statements were not executed. +message ExecuteBatchDmlResponse { + // One [ResultSet][google.spanner.v1.ResultSet] for each statement in the + // request that ran successfully, in the same order as the statements in the + // request. Each [ResultSet][google.spanner.v1.ResultSet] does not contain any + // rows. The [ResultSetStats][google.spanner.v1.ResultSetStats] in each + // [ResultSet][google.spanner.v1.ResultSet] contain the number of rows + // modified by the statement. + // + // Only the first [ResultSet][google.spanner.v1.ResultSet] in the response + // contains valid [ResultSetMetadata][google.spanner.v1.ResultSetMetadata]. + repeated ResultSet result_sets = 1; + + // If all DML statements are executed successfully, the status is `OK`. + // Otherwise, the error status of the first failed statement. + google.rpc.Status status = 2; + + // Optional. A precommit token is included if the read-write transaction + // is on a multiplexed session. Pass the precommit token with the highest + // sequence number from this transaction attempt should be passed to the + // [Commit][google.spanner.v1.Spanner.Commit] request for this transaction. + MultiplexedSessionPrecommitToken precommit_token = 3 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Options for a `PartitionQueryRequest` and `PartitionReadRequest`. +message PartitionOptions { + // **Note:** This hint is currently ignored by `PartitionQuery` and + // `PartitionRead` requests. + // + // The desired data size for each partition generated. The default for this + // option is currently 1 GiB. This is only a hint. The actual size of each + // partition can be smaller or larger than this size request. + int64 partition_size_bytes = 1; + + // **Note:** This hint is currently ignored by `PartitionQuery` and + // `PartitionRead` requests. + // + // The desired maximum number of partitions to return. For example, this + // might be set to the number of workers available. The default for this + // option is currently 10,000. The maximum value is currently 200,000. This + // is only a hint. The actual number of partitions returned can be smaller or + // larger than this maximum count request. + int64 max_partitions = 2; +} + +// The request for [PartitionQuery][google.spanner.v1.Spanner.PartitionQuery] +message PartitionQueryRequest { + // Required. The session used to create the partitions. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // Read-only snapshot transactions are supported, read and write and + // single-use transactions are not. + TransactionSelector transaction = 2; + + // Required. The query request to generate partitions for. The request fails + // if the query isn't root partitionable. For a query to be root + // partitionable, it needs to satisfy a few conditions. For example, if the + // query execution plan contains a distributed union operator, then it must be + // the first operator in the plan. For more information about other + // conditions, see [Read data in + // parallel](https://cloud.google.com/spanner/docs/reads#read_data_in_parallel). + // + // The query request must not contain DML commands, such as `INSERT`, + // `UPDATE`, or `DELETE`. Use + // [`ExecuteStreamingSql`][google.spanner.v1.Spanner.ExecuteStreamingSql] with + // a `PartitionedDml` transaction for large, partition-friendly DML + // operations. + string sql = 3 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Parameter names and values that bind to placeholders in the SQL + // string. + // + // A parameter placeholder consists of the `@` character followed by the + // parameter name (for example, `@firstName`). Parameter names can contain + // letters, numbers, and underscores. + // + // Parameters can appear anywhere that a literal value is expected. The same + // parameter name can be used more than once, for example: + // + // `"WHERE id > @msg_id AND id < @msg_id + 100"` + // + // It's an error to execute a SQL statement with unbound parameters. + google.protobuf.Struct params = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. It isn't always possible for Cloud Spanner to infer the right SQL + // type from a JSON value. For example, values of type `BYTES` and values of + // type `STRING` both appear in + // [params][google.spanner.v1.PartitionQueryRequest.params] as JSON strings. + // + // In these cases, `param_types` can be used to specify the exact + // SQL type for some or all of the SQL query parameters. See the + // definition of [Type][google.spanner.v1.Type] for more information + // about SQL types. + map param_types = 5 [(google.api.field_behavior) = OPTIONAL]; + + // Additional options that affect how many partitions are created. + PartitionOptions partition_options = 6; +} + +// The request for [PartitionRead][google.spanner.v1.Spanner.PartitionRead] +message PartitionReadRequest { + // Required. The session used to create the partitions. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // Read only snapshot transactions are supported, read/write and single use + // transactions are not. + TransactionSelector transaction = 2; + + // Required. The name of the table in the database to be read. + string table = 3 [(google.api.field_behavior) = REQUIRED]; + + // If non-empty, the name of an index on + // [table][google.spanner.v1.PartitionReadRequest.table]. This index is used + // instead of the table primary key when interpreting + // [key_set][google.spanner.v1.PartitionReadRequest.key_set] and sorting + // result rows. See [key_set][google.spanner.v1.PartitionReadRequest.key_set] + // for further information. + string index = 4; + + // The columns of [table][google.spanner.v1.PartitionReadRequest.table] to be + // returned for each row matching this request. + repeated string columns = 5; + + // Required. `key_set` identifies the rows to be yielded. `key_set` names the + // primary keys of the rows in + // [table][google.spanner.v1.PartitionReadRequest.table] to be yielded, unless + // [index][google.spanner.v1.PartitionReadRequest.index] is present. If + // [index][google.spanner.v1.PartitionReadRequest.index] is present, then + // [key_set][google.spanner.v1.PartitionReadRequest.key_set] instead names + // index keys in [index][google.spanner.v1.PartitionReadRequest.index]. + // + // It isn't an error for the `key_set` to name rows that don't + // exist in the database. Read yields nothing for nonexistent rows. + KeySet key_set = 6 [(google.api.field_behavior) = REQUIRED]; + + // Additional options that affect how many partitions are created. + PartitionOptions partition_options = 9; +} + +// Information returned for each partition returned in a +// PartitionResponse. +message Partition { + // This token can be passed to `Read`, `StreamingRead`, `ExecuteSql`, or + // `ExecuteStreamingSql` requests to restrict the results to those identified + // by this partition token. + bytes partition_token = 1; +} + +// The response for [PartitionQuery][google.spanner.v1.Spanner.PartitionQuery] +// or [PartitionRead][google.spanner.v1.Spanner.PartitionRead] +message PartitionResponse { + // Partitions created by this request. + repeated Partition partitions = 1; + + // Transaction created by this request. + Transaction transaction = 2; +} + +// The request for [Read][google.spanner.v1.Spanner.Read] and +// [StreamingRead][google.spanner.v1.Spanner.StreamingRead]. +message ReadRequest { + // An option to control the order in which rows are returned from a read. + enum OrderBy { + // Default value. + // + // `ORDER_BY_UNSPECIFIED` is equivalent to `ORDER_BY_PRIMARY_KEY`. + ORDER_BY_UNSPECIFIED = 0; + + // Read rows are returned in primary key order. + // + // In the event that this option is used in conjunction with the + // `partition_token` field, the API returns an `INVALID_ARGUMENT` error. + ORDER_BY_PRIMARY_KEY = 1; + + // Read rows are returned in any order. + ORDER_BY_NO_ORDER = 2; + } + + // A lock hint mechanism for reads done within a transaction. + enum LockHint { + // Default value. + // + // `LOCK_HINT_UNSPECIFIED` is equivalent to `LOCK_HINT_SHARED`. + LOCK_HINT_UNSPECIFIED = 0; + + // Acquire shared locks. + // + // By default when you perform a read as part of a read-write transaction, + // Spanner acquires shared read locks, which allows other reads to still + // access the data until your transaction is ready to commit. When your + // transaction is committing and writes are being applied, the transaction + // attempts to upgrade to an exclusive lock for any data you are writing. + // For more information about locks, see [Lock + // modes](https://cloud.google.com/spanner/docs/introspection/lock-statistics#explain-lock-modes). + LOCK_HINT_SHARED = 1; + + // Acquire exclusive locks. + // + // Requesting exclusive locks is beneficial if you observe high write + // contention, which means you notice that multiple transactions are + // concurrently trying to read and write to the same data, resulting in a + // large number of aborts. This problem occurs when two transactions + // initially acquire shared locks and then both try to upgrade to exclusive + // locks at the same time. In this situation both transactions are waiting + // for the other to give up their lock, resulting in a deadlocked situation. + // Spanner is able to detect this occurring and force one of the + // transactions to abort. However, this is a slow and expensive operation + // and results in lower performance. In this case it makes sense to acquire + // exclusive locks at the start of the transaction because then when + // multiple transactions try to act on the same data, they automatically get + // serialized. Each transaction waits its turn to acquire the lock and + // avoids getting into deadlock situations. + // + // Because the exclusive lock hint is just a hint, it shouldn't be + // considered equivalent to a mutex. In other words, you shouldn't use + // Spanner exclusive locks as a mutual exclusion mechanism for the execution + // of code outside of Spanner. + // + // **Note:** Request exclusive locks judiciously because they block others + // from reading that data for the entire transaction, rather than just when + // the writes are being performed. Unless you observe high write contention, + // you should use the default of shared read locks so you don't prematurely + // block other clients from reading the data that you're writing to. + LOCK_HINT_EXCLUSIVE = 2; + } + + // Required. The session in which the read should be performed. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // The transaction to use. If none is provided, the default is a + // temporary read-only transaction with strong concurrency. + TransactionSelector transaction = 2; + + // Required. The name of the table in the database to be read. + string table = 3 [(google.api.field_behavior) = REQUIRED]; + + // If non-empty, the name of an index on + // [table][google.spanner.v1.ReadRequest.table]. This index is used instead of + // the table primary key when interpreting + // [key_set][google.spanner.v1.ReadRequest.key_set] and sorting result rows. + // See [key_set][google.spanner.v1.ReadRequest.key_set] for further + // information. + string index = 4; + + // Required. The columns of [table][google.spanner.v1.ReadRequest.table] to be + // returned for each row matching this request. + repeated string columns = 5 [(google.api.field_behavior) = REQUIRED]; + + // Required. `key_set` identifies the rows to be yielded. `key_set` names the + // primary keys of the rows in [table][google.spanner.v1.ReadRequest.table] to + // be yielded, unless [index][google.spanner.v1.ReadRequest.index] is present. + // If [index][google.spanner.v1.ReadRequest.index] is present, then + // [key_set][google.spanner.v1.ReadRequest.key_set] instead names index keys + // in [index][google.spanner.v1.ReadRequest.index]. + // + // If the [partition_token][google.spanner.v1.ReadRequest.partition_token] + // field is empty, rows are yielded in table primary key order (if + // [index][google.spanner.v1.ReadRequest.index] is empty) or index key order + // (if [index][google.spanner.v1.ReadRequest.index] is non-empty). If the + // [partition_token][google.spanner.v1.ReadRequest.partition_token] field + // isn't empty, rows are yielded in an unspecified order. + // + // It isn't an error for the `key_set` to name rows that don't + // exist in the database. Read yields nothing for nonexistent rows. + KeySet key_set = 6 [(google.api.field_behavior) = REQUIRED]; + + // If greater than zero, only the first `limit` rows are yielded. If `limit` + // is zero, the default is no limit. A limit can't be specified if + // `partition_token` is set. + int64 limit = 8; + + // If this request is resuming a previously interrupted read, + // `resume_token` should be copied from the last + // [PartialResultSet][google.spanner.v1.PartialResultSet] yielded before the + // interruption. Doing this enables the new read to resume where the last read + // left off. The rest of the request parameters must exactly match the request + // that yielded this token. + bytes resume_token = 9; + + // If present, results are restricted to the specified partition + // previously created using `PartitionRead`. There must be an exact + // match for the values of fields common to this message and the + // PartitionReadRequest message used to create this partition_token. + bytes partition_token = 10; + + // Common options for this request. + RequestOptions request_options = 11; + + // Directed read options for this request. + DirectedReadOptions directed_read_options = 14; + + // If this is for a partitioned read and this field is set to `true`, the + // request is executed with Spanner Data Boost independent compute resources. + // + // If the field is set to `true` but the request doesn't set + // `partition_token`, the API returns an `INVALID_ARGUMENT` error. + bool data_boost_enabled = 15; + + // Optional. Order for the returned rows. + // + // By default, Spanner returns result rows in primary key order except for + // PartitionRead requests. For applications that don't require rows to be + // returned in primary key (`ORDER_BY_PRIMARY_KEY`) order, setting + // `ORDER_BY_NO_ORDER` option allows Spanner to optimize row retrieval, + // resulting in lower latencies in certain cases (for example, bulk point + // lookups). + OrderBy order_by = 16 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Lock Hint for the request, it can only be used with read-write + // transactions. + LockHint lock_hint = 17 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If present, it makes the Spanner requests location-aware. + // + // It gives the server hints that can be used to route the request + // to an appropriate server, potentially significantly decreasing latency and + // improving throughput. To achieve improved performance, most fields must be + // filled in with accurate values. + RoutingHint routing_hint = 18 [(google.api.field_behavior) = OPTIONAL]; +} + +// The request for +// [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction]. +message BeginTransactionRequest { + // Required. The session in which the transaction runs. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // Required. Options for the new transaction. + TransactionOptions options = 2 [(google.api.field_behavior) = REQUIRED]; + + // Common options for this request. + // Priority is ignored for this request. Setting the priority in this + // `request_options` struct doesn't do anything. To set the priority for a + // transaction, set it on the reads and writes that are part of this + // transaction instead. + RequestOptions request_options = 3; + + // Optional. Required for read-write transactions on a multiplexed session + // that commit mutations but don't perform any reads or queries. You must + // randomly select one of the mutations from the mutation set and send it as a + // part of this request. + Mutation mutation_key = 4 [(google.api.field_behavior) = OPTIONAL]; +} + +// The request for [Commit][google.spanner.v1.Spanner.Commit]. +message CommitRequest { + // Required. The session in which the transaction to be committed is running. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // Required. The transaction in which to commit. + oneof transaction { + // Commit a previously-started transaction. + bytes transaction_id = 2; + + // Execute mutations in a temporary transaction. Note that unlike + // commit of a previously-started transaction, commit with a + // temporary transaction is non-idempotent. That is, if the + // `CommitRequest` is sent to Cloud Spanner more than once (for + // instance, due to retries in the application, or in the + // transport library), it's possible that the mutations are + // executed more than once. If this is undesirable, use + // [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction] and + // [Commit][google.spanner.v1.Spanner.Commit] instead. + TransactionOptions single_use_transaction = 3; + } + + // The mutations to be executed when this transaction commits. All + // mutations are applied atomically, in the order they appear in + // this list. + repeated Mutation mutations = 4; + + // If `true`, then statistics related to the transaction is included in + // the [CommitResponse][google.spanner.v1.CommitResponse.commit_stats]. + // Default value is `false`. + bool return_commit_stats = 5; + + // Optional. The amount of latency this request is configured to incur in + // order to improve throughput. If this field isn't set, Spanner assumes + // requests are relatively latency sensitive and automatically determines an + // appropriate delay time. You can specify a commit delay value between 0 and + // 500 ms. + google.protobuf.Duration max_commit_delay = 8 + [(google.api.field_behavior) = OPTIONAL]; + + // Common options for this request. + RequestOptions request_options = 6; + + // Optional. If the read-write transaction was executed on a multiplexed + // session, then you must include the precommit token with the highest + // sequence number received in this transaction attempt. Failing to do so + // results in a `FailedPrecondition` error. + MultiplexedSessionPrecommitToken precommit_token = 9 + [(google.api.field_behavior) = OPTIONAL]; +} + +// The request for [Rollback][google.spanner.v1.Spanner.Rollback]. +message RollbackRequest { + // Required. The session in which the transaction to roll back is running. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // Required. The transaction to roll back. + bytes transaction_id = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for [BatchWrite][google.spanner.v1.Spanner.BatchWrite]. +message BatchWriteRequest { + // A group of mutations to be committed together. Related mutations should be + // placed in a group. For example, two mutations inserting rows with the same + // primary key prefix in both parent and child tables are related. + message MutationGroup { + // Required. The mutations in this group. + repeated Mutation mutations = 1 [(google.api.field_behavior) = REQUIRED]; + } + + // Required. The session in which the batch request is to be run. + string session = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "spanner.googleapis.com/Session" } + ]; + + // Common options for this request. + RequestOptions request_options = 3; + + // Required. The groups of mutations to be applied. + repeated MutationGroup mutation_groups = 4 + [(google.api.field_behavior) = REQUIRED]; + + // Optional. If you don't set the `exclude_txn_from_change_streams` option or + // if it's set to `false`, then any change streams monitoring columns modified + // by transactions will capture the updates made within that transaction. + bool exclude_txn_from_change_streams = 5 + [(google.api.field_behavior) = OPTIONAL]; +} + +// The result of applying a batch of mutations. +message BatchWriteResponse { + // The mutation groups applied in this batch. The values index into the + // `mutation_groups` field in the corresponding `BatchWriteRequest`. + repeated int32 indexes = 1; + + // An `OK` status indicates success. Any other status indicates a failure. + google.rpc.Status status = 2; + + // The commit timestamp of the transaction that applied this batch. + // Present if status is OK and the mutation groups were applied, absent + // otherwise. + // + // For mutation groups with conditions, a status=OK and missing + // commit_timestamp means that the mutation groups were not applied due to the + // condition not being satisfied after evaluation. + google.protobuf.Timestamp commit_timestamp = 3; +} diff --git a/handwritten/spanner/protos/google/spanner/v1/transaction.proto b/handwritten/spanner/protos/google/spanner/v1/transaction.proto new file mode 100644 index 00000000000..dfdf3b11a1b --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/transaction.proto @@ -0,0 +1,309 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "TransactionProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// Options to use for transactions. +message TransactionOptions { + // Message type to initiate a read-write transaction. Currently this + // transaction type has no options. + message ReadWrite { + // `ReadLockMode` is used to set the read lock mode for read-write + // transactions. + enum ReadLockMode { + // Default value. + // + // * If isolation level is + // [REPEATABLE_READ][google.spanner.v1.TransactionOptions.IsolationLevel.REPEATABLE_READ], + // then it is an error to specify `read_lock_mode`. Locking semantics + // default to `OPTIMISTIC`. No validation checks are done for reads, + // except to validate that the data that was served at the snapshot time + // is unchanged at commit time in the following cases: + // 1. reads done as part of queries that use `SELECT FOR UPDATE` + // 2. reads done as part of statements with a `LOCK_SCANNED_RANGES` + // hint + // 3. reads done as part of DML statements + // * At all other isolation levels, if `read_lock_mode` is the default + // value, then pessimistic read locks are used. + READ_LOCK_MODE_UNSPECIFIED = 0; + + // Pessimistic lock mode. + // + // Read locks are acquired immediately on read. + // Semantics described only applies to + // [SERIALIZABLE][google.spanner.v1.TransactionOptions.IsolationLevel.SERIALIZABLE] + // isolation. + PESSIMISTIC = 1; + + // Optimistic lock mode. + // + // Locks for reads within the transaction are not acquired on read. + // Instead the locks are acquired on a commit to validate that + // read/queried data has not changed since the transaction started. + // Semantics described only applies to + // [SERIALIZABLE][google.spanner.v1.TransactionOptions.IsolationLevel.SERIALIZABLE] + // isolation. + OPTIMISTIC = 2; + } + + // Read lock mode for the transaction. + ReadLockMode read_lock_mode = 1; + + // Optional. Clients should pass the transaction ID of the previous + // transaction attempt that was aborted if this transaction is being + // executed on a multiplexed session. + bytes multiplexed_session_previous_transaction_id = 2 + [(google.api.field_behavior) = OPTIONAL]; + } + + // Message type to initiate a Partitioned DML transaction. + message PartitionedDml {} + + // Message type to initiate a read-only transaction. + message ReadOnly { + // How to choose the timestamp for the read-only transaction. + oneof timestamp_bound { + // Read at a timestamp where all previously committed transactions + // are visible. + bool strong = 1; + + // Executes all reads at a timestamp >= `min_read_timestamp`. + // + // This is useful for requesting fresher data than some previous + // read, or data that is fresh enough to observe the effects of some + // previously committed transaction whose timestamp is known. + // + // Note that this option can only be used in single-use transactions. + // + // A timestamp in RFC3339 UTC \"Zulu\" format, accurate to nanoseconds. + // Example: `"2014-10-02T15:01:23.045123456Z"`. + google.protobuf.Timestamp min_read_timestamp = 2; + + // Read data at a timestamp >= `NOW - max_staleness` + // seconds. Guarantees that all writes that have committed more + // than the specified number of seconds ago are visible. Because + // Cloud Spanner chooses the exact timestamp, this mode works even if + // the client's local clock is substantially skewed from Cloud Spanner + // commit timestamps. + // + // Useful for reading the freshest data available at a nearby + // replica, while bounding the possible staleness if the local + // replica has fallen behind. + // + // Note that this option can only be used in single-use + // transactions. + google.protobuf.Duration max_staleness = 3; + + // Executes all reads at the given timestamp. Unlike other modes, + // reads at a specific timestamp are repeatable; the same read at + // the same timestamp always returns the same data. If the + // timestamp is in the future, the read is blocked until the + // specified timestamp, modulo the read's deadline. + // + // Useful for large scale consistent reads such as mapreduces, or + // for coordinating many reads against a consistent snapshot of the + // data. + // + // A timestamp in RFC3339 UTC \"Zulu\" format, accurate to nanoseconds. + // Example: `"2014-10-02T15:01:23.045123456Z"`. + google.protobuf.Timestamp read_timestamp = 4; + + // Executes all reads at a timestamp that is `exact_staleness` + // old. The timestamp is chosen soon after the read is started. + // + // Guarantees that all writes that have committed more than the + // specified number of seconds ago are visible. Because Cloud Spanner + // chooses the exact timestamp, this mode works even if the client's + // local clock is substantially skewed from Cloud Spanner commit + // timestamps. + // + // Useful for reading at nearby replicas without the distributed + // timestamp negotiation overhead of `max_staleness`. + google.protobuf.Duration exact_staleness = 5; + } + + // If true, the Cloud Spanner-selected read timestamp is included in + // the [Transaction][google.spanner.v1.Transaction] message that describes + // the transaction. + bool return_read_timestamp = 6; + } + + // `IsolationLevel` is used when setting the [isolation + // level](https://cloud.google.com/spanner/docs/isolation-levels) for a + // transaction. + enum IsolationLevel { + // Default value. + // + // If the value is not specified, the `SERIALIZABLE` isolation level is + // used. + ISOLATION_LEVEL_UNSPECIFIED = 0; + + // All transactions appear as if they executed in a serial order, even if + // some of the reads, writes, and other operations of distinct transactions + // actually occurred in parallel. Spanner assigns commit timestamps that + // reflect the order of committed transactions to implement this property. + // Spanner offers a stronger guarantee than serializability called external + // consistency. For more information, see + // [TrueTime and external + // consistency](https://cloud.google.com/spanner/docs/true-time-external-consistency#serializability). + SERIALIZABLE = 1; + + // All reads performed during the transaction observe a consistent snapshot + // of the database, and the transaction is only successfully committed in + // the absence of conflicts between its updates and any concurrent updates + // that have occurred since that snapshot. Consequently, in contrast to + // `SERIALIZABLE` transactions, only write-write conflicts are detected in + // snapshot transactions. + // + // This isolation level does not support read-only and partitioned DML + // transactions. + // + // When `REPEATABLE_READ` is specified on a read-write transaction, the + // locking semantics default to `OPTIMISTIC`. + REPEATABLE_READ = 2; + } + + // Required. The type of transaction. + oneof mode { + // Transaction may write. + // + // Authorization to begin a read-write transaction requires + // `spanner.databases.beginOrRollbackReadWriteTransaction` permission + // on the `session` resource. + ReadWrite read_write = 1; + + // Partitioned DML transaction. + // + // Authorization to begin a Partitioned DML transaction requires + // `spanner.databases.beginPartitionedDmlTransaction` permission + // on the `session` resource. + PartitionedDml partitioned_dml = 3; + + // Transaction does not write. + // + // Authorization to begin a read-only transaction requires + // `spanner.databases.beginReadOnlyTransaction` permission + // on the `session` resource. + ReadOnly read_only = 2; + } + + // When `exclude_txn_from_change_streams` is set to `true`, it prevents read + // or write transactions from being tracked in change streams. + // + // * If the DDL option `allow_txn_exclusion` is set to `true`, then the + // updates + // made within this transaction aren't recorded in the change stream. + // + // * If you don't set the DDL option `allow_txn_exclusion` or if it's + // set to `false`, then the updates made within this transaction are + // recorded in the change stream. + // + // When `exclude_txn_from_change_streams` is set to `false` or not set, + // modifications from this transaction are recorded in all change streams + // that are tracking columns modified by these transactions. + // + // The `exclude_txn_from_change_streams` option can only be specified + // for read-write or partitioned DML transactions, otherwise the API returns + // an `INVALID_ARGUMENT` error. + bool exclude_txn_from_change_streams = 5; + + // Isolation level for the transaction. + IsolationLevel isolation_level = 6; +} + +// A transaction. +message Transaction { + // `id` may be used to identify the transaction in subsequent + // [Read][google.spanner.v1.Spanner.Read], + // [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], + // [Commit][google.spanner.v1.Spanner.Commit], or + // [Rollback][google.spanner.v1.Spanner.Rollback] calls. + // + // Single-use read-only transactions do not have IDs, because + // single-use transactions do not support multiple requests. + bytes id = 1; + + // For snapshot read-only transactions, the read timestamp chosen + // for the transaction. Not returned by default: see + // [TransactionOptions.ReadOnly.return_read_timestamp][google.spanner.v1.TransactionOptions.ReadOnly.return_read_timestamp]. + // + // A timestamp in RFC3339 UTC \"Zulu\" format, accurate to nanoseconds. + // Example: `"2014-10-02T15:01:23.045123456Z"`. + google.protobuf.Timestamp read_timestamp = 2; + + // A precommit token is included in the response of a BeginTransaction + // request if the read-write transaction is on a multiplexed session and + // a mutation_key was specified in the + // [BeginTransaction][google.spanner.v1.BeginTransactionRequest]. + // The precommit token with the highest sequence number from this transaction + // attempt should be passed to the [Commit][google.spanner.v1.Spanner.Commit] + // request for this transaction. + MultiplexedSessionPrecommitToken precommit_token = 3; +} + +// This message is used to select the transaction in which a +// [Read][google.spanner.v1.Spanner.Read] or +// [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] call runs. +// +// See [TransactionOptions][google.spanner.v1.TransactionOptions] for more +// information about transactions. +message TransactionSelector { + // If no fields are set, the default is a single use transaction + // with strong concurrency. + oneof selector { + // Execute the read or SQL query in a temporary transaction. + // This is the most efficient way to execute a transaction that + // consists of a single SQL query. + TransactionOptions single_use = 1; + + // Execute the read or SQL query in a previously-started transaction. + bytes id = 2; + + // Begin a new transaction and execute this read or SQL query in + // it. The transaction ID of the new transaction is returned in + // [ResultSetMetadata.transaction][google.spanner.v1.ResultSetMetadata.transaction], + // which is a [Transaction][google.spanner.v1.Transaction]. + TransactionOptions begin = 3; + } +} + +// When a read-write transaction is executed on a multiplexed session, +// this precommit token is sent back to the client +// as a part of the [Transaction][google.spanner.v1.Transaction] message in the +// [BeginTransaction][google.spanner.v1.BeginTransactionRequest] response and +// also as a part of the [ResultSet][google.spanner.v1.ResultSet] and +// [PartialResultSet][google.spanner.v1.PartialResultSet] responses. +message MultiplexedSessionPrecommitToken { + // Opaque precommit token. + bytes precommit_token = 1; + + // An incrementing seq number is generated on every precommit token + // that is returned. Clients should remember the precommit token with the + // highest sequence number from the current transaction attempt. + int32 seq_num = 2; +} diff --git a/handwritten/spanner/protos/google/spanner/v1/type.proto b/handwritten/spanner/protos/google/spanner/v1/type.proto new file mode 100644 index 00000000000..e3e85a770af --- /dev/null +++ b/handwritten/spanner/protos/google/spanner/v1/type.proto @@ -0,0 +1,214 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.spanner.v1; + +import "google/api/field_behavior.proto"; + +option csharp_namespace = "Google.Cloud.Spanner.V1"; +option go_package = "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb"; +option java_multiple_files = true; +option java_outer_classname = "TypeProto"; +option java_package = "com.google.spanner.v1"; +option php_namespace = "Google\\Cloud\\Spanner\\V1"; +option ruby_package = "Google::Cloud::Spanner::V1"; + +// `Type` indicates the type of a Cloud Spanner value, as might be stored in a +// table cell or returned from an SQL query. +message Type { + // Required. The [TypeCode][google.spanner.v1.TypeCode] for this type. + TypeCode code = 1 [(google.api.field_behavior) = REQUIRED]; + + // If [code][google.spanner.v1.Type.code] == + // [ARRAY][google.spanner.v1.TypeCode.ARRAY], then `array_element_type` is the + // type of the array elements. + Type array_element_type = 2; + + // If [code][google.spanner.v1.Type.code] == + // [STRUCT][google.spanner.v1.TypeCode.STRUCT], then `struct_type` provides + // type information for the struct's fields. + StructType struct_type = 3; + + // The [TypeAnnotationCode][google.spanner.v1.TypeAnnotationCode] that + // disambiguates SQL type that Spanner will use to represent values of this + // type during query processing. This is necessary for some type codes because + // a single [TypeCode][google.spanner.v1.TypeCode] can be mapped to different + // SQL types depending on the SQL dialect. + // [type_annotation][google.spanner.v1.Type.type_annotation] typically is not + // needed to process the content of a value (it doesn't affect serialization) + // and clients can ignore it on the read path. + TypeAnnotationCode type_annotation = 4; + + // If [code][google.spanner.v1.Type.code] == + // [PROTO][google.spanner.v1.TypeCode.PROTO] or + // [code][google.spanner.v1.Type.code] == + // [ENUM][google.spanner.v1.TypeCode.ENUM], then `proto_type_fqn` is the fully + // qualified name of the proto type representing the proto/enum definition. + string proto_type_fqn = 5; +} + +// `StructType` defines the fields of a +// [STRUCT][google.spanner.v1.TypeCode.STRUCT] type. +message StructType { + // Message representing a single field of a struct. + message Field { + // The name of the field. For reads, this is the column name. For + // SQL queries, it is the column alias (e.g., `"Word"` in the + // query `"SELECT 'hello' AS Word"`), or the column name (e.g., + // `"ColName"` in the query `"SELECT ColName FROM Table"`). Some + // columns might have an empty name (e.g., `"SELECT + // UPPER(ColName)"`). Note that a query result can contain + // multiple fields with the same name. + string name = 1; + + // The type of the field. + Type type = 2; + } + + // The list of fields that make up this struct. Order is + // significant, because values of this struct type are represented as + // lists, where the order of field values matches the order of + // fields in the [StructType][google.spanner.v1.StructType]. In turn, the + // order of fields matches the order of columns in a read request, or the + // order of fields in the `SELECT` clause of a query. + repeated Field fields = 1; +} + +// `TypeCode` is used as part of [Type][google.spanner.v1.Type] to +// indicate the type of a Cloud Spanner value. +// +// Each legal value of a type can be encoded to or decoded from a JSON +// value, using the encodings described below. All Cloud Spanner values can +// be `null`, regardless of type; `null`s are always encoded as a JSON +// `null`. +enum TypeCode { + // Not specified. + TYPE_CODE_UNSPECIFIED = 0; + + // Encoded as JSON `true` or `false`. + BOOL = 1; + + // Encoded as `string`, in decimal format. + INT64 = 2; + + // Encoded as `number`, or the strings `"NaN"`, `"Infinity"`, or + // `"-Infinity"`. + FLOAT64 = 3; + + // Encoded as `number`, or the strings `"NaN"`, `"Infinity"`, or + // `"-Infinity"`. + FLOAT32 = 15; + + // Encoded as `string` in RFC 3339 timestamp format. The time zone + // must be present, and must be `"Z"`. + // + // If the schema has the column option + // `allow_commit_timestamp=true`, the placeholder string + // `"spanner.commit_timestamp()"` can be used to instruct the system + // to insert the commit timestamp associated with the transaction + // commit. + TIMESTAMP = 4; + + // Encoded as `string` in RFC 3339 date format. + DATE = 5; + + // Encoded as `string`. + STRING = 6; + + // Encoded as a base64-encoded `string`, as described in RFC 4648, + // section 4. + BYTES = 7; + + // Encoded as `list`, where the list elements are represented + // according to + // [array_element_type][google.spanner.v1.Type.array_element_type]. + ARRAY = 8; + + // Encoded as `list`, where list element `i` is represented according + // to [struct_type.fields[i]][google.spanner.v1.StructType.fields]. + STRUCT = 9; + + // Encoded as `string`, in decimal format or scientific notation format. + // Decimal format: + // `[+-]Digits[.[Digits]]` or + // `[+-][Digits].Digits` + // + // Scientific notation: + // `[+-]Digits[.[Digits]][ExponentIndicator[+-]Digits]` or + // `[+-][Digits].Digits[ExponentIndicator[+-]Digits]` + // (ExponentIndicator is `"e"` or `"E"`) + NUMERIC = 10; + + // Encoded as a JSON-formatted `string` as described in RFC 7159. The + // following rules are applied when parsing JSON input: + // + // - Whitespace characters are not preserved. + // - If a JSON object has duplicate keys, only the first key is preserved. + // - Members of a JSON object are not guaranteed to have their order + // preserved. + // - JSON array elements will have their order preserved. + JSON = 11; + + // Encoded as a base64-encoded `string`, as described in RFC 4648, + // section 4. + PROTO = 13; + + // Encoded as `string`, in decimal format. + ENUM = 14; + + // Encoded as `string`, in `ISO8601` duration format - + // `P[n]Y[n]M[n]DT[n]H[n]M[n[.fraction]]S` + // where `n` is an integer. + // For example, `P1Y2M3DT4H5M6.5S` represents time duration of 1 year, 2 + // months, 3 days, 4 hours, 5 minutes, and 6.5 seconds. + INTERVAL = 16; + + // Encoded as `string`, in lower-case hexa-decimal format, as described + // in RFC 9562, section 4. + UUID = 17; +} + +// `TypeAnnotationCode` is used as a part of [Type][google.spanner.v1.Type] to +// disambiguate SQL types that should be used for a given Cloud Spanner value. +// Disambiguation is needed because the same Cloud Spanner type can be mapped to +// different SQL types depending on SQL dialect. TypeAnnotationCode doesn't +// affect the way value is serialized. +enum TypeAnnotationCode { + // Not specified. + TYPE_ANNOTATION_CODE_UNSPECIFIED = 0; + + // PostgreSQL compatible NUMERIC type. This annotation needs to be applied to + // [Type][google.spanner.v1.Type] instances having + // [NUMERIC][google.spanner.v1.TypeCode.NUMERIC] type code to specify that + // values of this type should be treated as PostgreSQL NUMERIC values. + // Currently this annotation is always needed for + // [NUMERIC][google.spanner.v1.TypeCode.NUMERIC] when a client interacts with + // PostgreSQL-enabled Spanner databases. + PG_NUMERIC = 2; + + // PostgreSQL compatible JSONB type. This annotation needs to be applied to + // [Type][google.spanner.v1.Type] instances having + // [JSON][google.spanner.v1.TypeCode.JSON] type code to specify that values of + // this type should be treated as PostgreSQL JSONB values. Currently this + // annotation is always needed for [JSON][google.spanner.v1.TypeCode.JSON] + // when a client interacts with PostgreSQL-enabled Spanner databases. + PG_JSONB = 3; + + // PostgreSQL compatible OID type. This annotation can be used by a client + // interacting with PostgreSQL-enabled Spanner database to specify that a + // value should be treated using the semantics of the OID type. + PG_OID = 4; +} diff --git a/handwritten/spanner/protos/protos.d.ts b/handwritten/spanner/protos/protos.d.ts new file mode 100644 index 00000000000..2beea4b0984 --- /dev/null +++ b/handwritten/spanner/protos/protos.d.ts @@ -0,0 +1,43817 @@ +// Copyright 2026 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 type {protobuf as $protobuf} from "google-gax"; +import Long = require("long"); +/** Namespace google. */ +export namespace google { + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a Duration. */ + interface IDuration { + + /** Duration seconds */ + seconds?: (number|Long|string|null); + + /** Duration nanos */ + nanos?: (number|null); + } + + /** Represents a Duration. */ + class Duration implements IDuration { + + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); + + /** Duration seconds. */ + public seconds: (number|Long|string); + + /** Duration nanos. */ + public nanos: number; + + /** + * Creates a new Duration instance using the specified properties. + * @param [properties] Properties to set + * @returns Duration instance + */ + public static create(properties?: google.protobuf.IDuration): google.protobuf.Duration; + + /** + * Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. + * @param message Duration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Duration message, length delimited. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. + * @param message Duration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Duration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Duration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Duration; + + /** + * Decodes a Duration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Duration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Duration; + + /** + * Verifies a Duration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); + + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; + + /** + * Creates a new FileDescriptorSet instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorSet instance + */ + public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; + + /** + * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @param message FileDescriptorSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; + + /** + * Verifies a FileDescriptorSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Edition enum. */ + enum Edition { + EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, + EDITION_PROTO2 = 998, + EDITION_PROTO3 = 999, + EDITION_2023 = 1000, + EDITION_2024 = 1001, + EDITION_1_TEST_ONLY = 1, + EDITION_2_TEST_ONLY = 2, + EDITION_99997_TEST_ONLY = 99997, + EDITION_99998_TEST_ONLY = 99998, + EDITION_99999_TEST_ONLY = 99999, + EDITION_MAX = 2147483647 + } + + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { + + /** FileDescriptorProto name */ + name?: (string|null); + + /** FileDescriptorProto package */ + "package"?: (string|null); + + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); + + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); + + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); + + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); + + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); + + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax */ + syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + } + + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { + + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); + + /** FileDescriptorProto name. */ + public name: string; + + /** FileDescriptorProto package. */ + public package: string; + + /** FileDescriptorProto dependency. */ + public dependency: string[]; + + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; + + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; + + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; + + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; + + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); + + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + + /** FileDescriptorProto syntax. */ + public syntax: string; + + /** FileDescriptorProto edition. */ + public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FileDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FileDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; + + /** + * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @param message FileDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; + + /** + * Verifies a FileDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { + + /** DescriptorProto name */ + name?: (string|null); + + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); + } + + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { + + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); + + /** DescriptorProto name. */ + public name: string; + + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; + + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; + + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; + + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); + + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + + /** DescriptorProto reservedName. */ + public reservedName: string[]; + + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + + /** + * Creates a new DescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns DescriptorProto instance + */ + public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; + + /** + * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @param message DescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; + + /** + * Verifies a DescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DescriptorProto { + + /** Properties of an ExtensionRange. */ + interface IExtensionRange { + + /** ExtensionRange start */ + start?: (number|null); + + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); + } + + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { + + /** + * Constructs a new ExtensionRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + + /** ExtensionRange start. */ + public start: number; + + /** ExtensionRange end. */ + public end: number; + + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + + /** + * Creates a new ExtensionRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @param message ExtensionRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Verifies an ExtensionRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservedRange. */ + interface IReservedRange { + + /** ReservedRange start */ + start?: (number|null); + + /** ReservedRange end */ + end?: (number|null); + } + + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { + + /** + * Constructs a new ReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + + /** ReservedRange start. */ + public start: number; + + /** ReservedRange end. */ + public end: number; + + /** + * Creates a new ReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservedRange instance + */ + public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @param message ReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Decodes a ReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Verifies a ReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|keyof typeof google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: (google.protobuf.ExtensionRangeOptions.VerificationState|keyof typeof google.protobuf.ExtensionRangeOptions.VerificationState); + + /** + * Creates a new ExtensionRangeOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ExtensionRangeOptions instance + */ + public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions; + + /** + * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @param message ExtensionRangeOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions; + + /** + * Verifies an ExtensionRangeOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a new Declaration instance using the specified properties. + * @param [properties] Properties to set + * @returns Declaration instance + */ + public static create(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Encodes the specified Declaration message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.Declaration.verify|verify} messages. + * @param message Declaration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.ExtensionRangeOptions.IDeclaration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Declaration message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.Declaration.verify|verify} messages. + * @param message Declaration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.ExtensionRangeOptions.IDeclaration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Declaration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Declaration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Decodes a Declaration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Declaration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Verifies a Declaration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + enum VerificationState { + DECLARATION = 0, + UNVERIFIED = 1 + } + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|keyof typeof google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|keyof typeof google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: (google.protobuf.FieldDescriptorProto.Label|keyof typeof google.protobuf.FieldDescriptorProto.Label); + + /** FieldDescriptorProto type. */ + public type: (google.protobuf.FieldDescriptorProto.Type|keyof typeof google.protobuf.FieldDescriptorProto.Type); + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; + + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + + /** + * Creates a new FieldDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldDescriptorProto instance + */ + public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; + + /** + * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @param message FieldDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; + + /** + * Verifies a FieldDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldDescriptorProto { + + /** Type enum. */ + enum Type { + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + TYPE_GROUP = 10, + TYPE_MESSAGE = 11, + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + TYPE_SINT32 = 17, + TYPE_SINT64 = 18 + } + + /** Label enum. */ + enum Label { + LABEL_OPTIONAL = 1, + LABEL_REPEATED = 3, + LABEL_REQUIRED = 2 + } + } + + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { + + /** OneofDescriptorProto name */ + name?: (string|null); + + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } + + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { + + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); + + /** OneofDescriptorProto name. */ + public name: string; + + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); + + /** + * Creates a new OneofDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofDescriptorProto instance + */ + public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; + + /** + * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @param message OneofDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; + + /** + * Verifies an OneofDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { + + /** EnumDescriptorProto name */ + name?: (string|null); + + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); + } + + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { + + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); + + /** EnumDescriptorProto name. */ + public name: string; + + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; + + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + + /** + * Creates a new EnumDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; + + /** + * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @param message EnumDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; + + /** + * Verifies an EnumDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates a new EnumReservedRange instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumReservedRange instance + */ + public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @param message EnumReservedRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Verifies an EnumReservedRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { + + /** EnumValueDescriptorProto name */ + name?: (string|null); + + /** EnumValueDescriptorProto number */ + number?: (number|null); + + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } + + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + + /** EnumValueDescriptorProto name. */ + public name: string; + + /** EnumValueDescriptorProto number. */ + public number: number; + + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); + + /** + * Creates a new EnumValueDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueDescriptorProto instance + */ + public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; + + /** + * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @param message EnumValueDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; + + /** + * Verifies an EnumValueDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { + + /** ServiceDescriptorProto name */ + name?: (string|null); + + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); + + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } + + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a new ServiceDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceDescriptorProto instance + */ + public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; + + /** + * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @param message ServiceDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; + + /** + * Verifies a ServiceDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a new MethodDescriptorProto instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodDescriptorProto instance + */ + public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; + + /** + * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @param message MethodDescriptorProto message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; + + /** + * Verifies a MethodDescriptorProto message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { + + /** FileOptions javaPackage */ + javaPackage?: (string|null); + + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); + + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); + + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); + + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); + + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|keyof typeof google.protobuf.FileOptions.OptimizeMode|null); + + /** FileOptions goPackage */ + goPackage?: (string|null); + + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); + + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); + + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); + + /** FileOptions deprecated */ + deprecated?: (boolean|null); + + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); + + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); + + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); + + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } + + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { + + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); + + /** FileOptions javaPackage. */ + public javaPackage: string; + + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; + + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; + + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; + + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; + + /** FileOptions optimizeFor. */ + public optimizeFor: (google.protobuf.FileOptions.OptimizeMode|keyof typeof google.protobuf.FileOptions.OptimizeMode); + + /** FileOptions goPackage. */ + public goPackage: string; + + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; + + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; + + /** FileOptions deprecated. */ + public deprecated: boolean; + + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; + + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; + + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FileOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FileOptions instance + */ + public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; + + /** + * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @param message FileOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FileOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; + + /** + * Decodes a FileOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; + + /** + * Verifies a FileOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + enum OptimizeMode { + SPEED = 1, + CODE_SIZE = 2, + LITE_RUNTIME = 3 + } + } + + /** Properties of a MessageOptions. */ + interface IMessageOptions { + + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); + + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); + + /** MessageOptions deprecated */ + deprecated?: (boolean|null); + + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); + + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } + + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { + + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); + + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; + + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; + + /** MessageOptions deprecated. */ + public deprecated: boolean; + + /** MessageOptions mapEntry. */ + public mapEntry: boolean; + + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MessageOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MessageOptions instance + */ + public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; + + /** + * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @param message MessageOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MessageOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; + + /** + * Decodes a MessageOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; + + /** + * Verifies a MessageOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldOptions. */ + interface IFieldOptions { + + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|keyof typeof google.protobuf.FieldOptions.CType|null); + + /** FieldOptions packed */ + packed?: (boolean|null); + + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|keyof typeof google.protobuf.FieldOptions.JSType|null); + + /** FieldOptions lazy */ + lazy?: (boolean|null); + + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + + /** FieldOptions deprecated */ + deprecated?: (boolean|null); + + /** FieldOptions weak */ + weak?: (boolean|null); + + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|keyof typeof google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } + + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { + + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); + + /** FieldOptions ctype. */ + public ctype: (google.protobuf.FieldOptions.CType|keyof typeof google.protobuf.FieldOptions.CType); + + /** FieldOptions packed. */ + public packed: boolean; + + /** FieldOptions jstype. */ + public jstype: (google.protobuf.FieldOptions.JSType|keyof typeof google.protobuf.FieldOptions.JSType); + + /** FieldOptions lazy. */ + public lazy: boolean; + + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + + /** FieldOptions deprecated. */ + public deprecated: boolean; + + /** FieldOptions weak. */ + public weak: boolean; + + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: (google.protobuf.FieldOptions.OptionRetention|keyof typeof google.protobuf.FieldOptions.OptionRetention); + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new FieldOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldOptions instance + */ + public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; + + /** + * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @param message FieldOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; + + /** + * Decodes a FieldOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; + + /** + * Verifies a FieldOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FieldOptions { + + /** CType enum. */ + enum CType { + STRING = 0, + CORD = 1, + STRING_PIECE = 2 + } + + /** JSType enum. */ + enum JSType { + JS_NORMAL = 0, + JS_STRING = 1, + JS_NUMBER = 2 + } + + /** OptionRetention enum. */ + enum OptionRetention { + RETENTION_UNKNOWN = 0, + RETENTION_RUNTIME = 1, + RETENTION_SOURCE = 2 + } + + /** OptionTargetType enum. */ + enum OptionTargetType { + TARGET_TYPE_UNKNOWN = 0, + TARGET_TYPE_FILE = 1, + TARGET_TYPE_EXTENSION_RANGE = 2, + TARGET_TYPE_MESSAGE = 3, + TARGET_TYPE_FIELD = 4, + TARGET_TYPE_ONEOF = 5, + TARGET_TYPE_ENUM = 6, + TARGET_TYPE_ENUM_ENTRY = 7, + TARGET_TYPE_SERVICE = 8, + TARGET_TYPE_METHOD = 9 + } + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** EditionDefault value. */ + public value: string; + + /** + * Creates a new EditionDefault instance using the specified properties. + * @param [properties] Properties to set + * @returns EditionDefault instance + */ + public static create(properties?: google.protobuf.FieldOptions.IEditionDefault): google.protobuf.FieldOptions.EditionDefault; + + /** + * Encodes the specified EditionDefault message. Does not implicitly {@link google.protobuf.FieldOptions.EditionDefault.verify|verify} messages. + * @param message EditionDefault message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IEditionDefault, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EditionDefault message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.EditionDefault.verify|verify} messages. + * @param message EditionDefault message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IEditionDefault, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EditionDefault message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EditionDefault + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.EditionDefault; + + /** + * Decodes an EditionDefault message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EditionDefault + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.EditionDefault; + + /** + * Verifies an EditionDefault message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + } + + /** Represents a FeatureSupport. */ + class FeatureSupport implements IFeatureSupport { + + /** + * Constructs a new FeatureSupport. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IFeatureSupport); + + /** FeatureSupport editionIntroduced. */ + public editionIntroduced: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FeatureSupport message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSupport + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Creates a plain object from a FeatureSupport message. Also converts values to other types if specified. + * @param message FeatureSupport + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.FeatureSupport, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSupport to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSupport + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an OneofOptions. */ + interface IOneofOptions { + + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { + + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); + + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new OneofOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns OneofOptions instance + */ + public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; + + /** + * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @param message OneofOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OneofOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; + + /** + * Decodes an OneofOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; + + /** + * Verifies an OneofOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumOptions. */ + interface IEnumOptions { + + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); + + /** EnumOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { + + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumOptions instance + */ + public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; + + /** + * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @param message EnumOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; + + /** + * Decodes an EnumOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; + + /** + * Verifies an EnumOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { + + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); + + /** EnumValueOptions deprecated. */ + public deprecated: boolean; + + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new EnumValueOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns EnumValueOptions instance + */ + public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; + + /** + * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @param message EnumValueOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; + + /** + * Verifies an EnumValueOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ServiceOptions. */ + interface IServiceOptions { + + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); + + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); + + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } + + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { + + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); + + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ServiceOptions deprecated. */ + public deprecated: boolean; + + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new ServiceOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ServiceOptions instance + */ + public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; + + /** + * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @param message ServiceOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; + + /** + * Verifies a ServiceOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodOptions. */ + interface IMethodOptions { + + /** MethodOptions deprecated */ + deprecated?: (boolean|null); + + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|keyof typeof google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); + + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); + + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } + + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { + + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); + + /** MethodOptions deprecated. */ + public deprecated: boolean; + + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: (google.protobuf.MethodOptions.IdempotencyLevel|keyof typeof google.protobuf.MethodOptions.IdempotencyLevel); + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a new MethodOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodOptions instance + */ + public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; + + /** + * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @param message MethodOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; + + /** + * Decodes a MethodOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; + + /** + * Verifies a MethodOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0, + NO_SIDE_EFFECTS = 1, + IDEMPOTENT = 2 + } + } + + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { + + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); + + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|Long|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|Long|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|Buffer|string|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|Long|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|Long|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: (Uint8Array|Buffer|string); + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates a new UninterpretedOption instance using the specified properties. + * @param [properties] Properties to set + * @returns UninterpretedOption instance + */ + public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; + + /** + * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @param message UninterpretedOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; + + /** + * Verifies an UninterpretedOption message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a new NamePart instance using the specified properties. + * @param [properties] Properties to set + * @returns NamePart instance + */ + public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; + + /** + * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @param message NamePart message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NamePart message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; + + /** + * Decodes a NamePart message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; + + /** + * Verifies a NamePart message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|keyof typeof google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|keyof typeof google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|keyof typeof google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|keyof typeof google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|keyof typeof google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: (google.protobuf.FeatureSet.FieldPresence|keyof typeof google.protobuf.FeatureSet.FieldPresence); + + /** FeatureSet enumType. */ + public enumType: (google.protobuf.FeatureSet.EnumType|keyof typeof google.protobuf.FeatureSet.EnumType); + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: (google.protobuf.FeatureSet.RepeatedFieldEncoding|keyof typeof google.protobuf.FeatureSet.RepeatedFieldEncoding); + + /** FeatureSet utf8Validation. */ + public utf8Validation: (google.protobuf.FeatureSet.Utf8Validation|keyof typeof google.protobuf.FeatureSet.Utf8Validation); + + /** FeatureSet messageEncoding. */ + public messageEncoding: (google.protobuf.FeatureSet.MessageEncoding|keyof typeof google.protobuf.FeatureSet.MessageEncoding); + + /** FeatureSet jsonFormat. */ + public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + + /** + * Creates a new FeatureSet instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSet instance + */ + public static create(properties?: google.protobuf.IFeatureSet): google.protobuf.FeatureSet; + + /** + * Encodes the specified FeatureSet message. Does not implicitly {@link google.protobuf.FeatureSet.verify|verify} messages. + * @param message FeatureSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFeatureSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSet message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.verify|verify} messages. + * @param message FeatureSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFeatureSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet; + + /** + * Decodes a FeatureSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet; + + /** + * Verifies a FeatureSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + enum FieldPresence { + FIELD_PRESENCE_UNKNOWN = 0, + EXPLICIT = 1, + IMPLICIT = 2, + LEGACY_REQUIRED = 3 + } + + /** EnumType enum. */ + enum EnumType { + ENUM_TYPE_UNKNOWN = 0, + OPEN = 1, + CLOSED = 2 + } + + /** RepeatedFieldEncoding enum. */ + enum RepeatedFieldEncoding { + REPEATED_FIELD_ENCODING_UNKNOWN = 0, + PACKED = 1, + EXPANDED = 2 + } + + /** Utf8Validation enum. */ + enum Utf8Validation { + UTF8_VALIDATION_UNKNOWN = 0, + VERIFY = 2, + NONE = 3 + } + + /** MessageEncoding enum. */ + enum MessageEncoding { + MESSAGE_ENCODING_UNKNOWN = 0, + LENGTH_PREFIXED = 1, + DELIMITED = 2 + } + + /** JsonFormat enum. */ + enum JsonFormat { + JSON_FORMAT_UNKNOWN = 0, + ALLOW = 1, + LEGACY_BEST_EFFORT = 2 + } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VisibilityFeature { + + /** DefaultSymbolVisibility enum. */ + enum DefaultSymbolVisibility { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0, + EXPORT_ALL = 1, + EXPORT_TOP_LEVEL = 2, + LOCAL_ALL = 3, + STRICT = 4 + } + } + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSetDefaults instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSetDefaults instance + */ + public static create(properties?: google.protobuf.IFeatureSetDefaults): google.protobuf.FeatureSetDefaults; + + /** + * Encodes the specified FeatureSetDefaults message. Does not implicitly {@link google.protobuf.FeatureSetDefaults.verify|verify} messages. + * @param message FeatureSetDefaults message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFeatureSetDefaults, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSetDefaults message, length delimited. Does not implicitly {@link google.protobuf.FeatureSetDefaults.verify|verify} messages. + * @param message FeatureSetDefaults message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFeatureSetDefaults, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSetDefaults message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSetDefaults + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSetDefaults; + + /** + * Decodes a FeatureSetDefaults message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSetDefaults + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSetDefaults; + + /** + * Verifies a FeatureSetDefaults message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSetEditionDefault overridableFeatures */ + overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures */ + fixedFeatures?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSetEditionDefault overridableFeatures. */ + public overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures. */ + public fixedFeatures?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a new FeatureSetEditionDefault instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSetEditionDefault instance + */ + public static create(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Encodes the specified FeatureSetEditionDefault message. Does not implicitly {@link google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.verify|verify} messages. + * @param message FeatureSetEditionDefault message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSetEditionDefault message, length delimited. Does not implicitly {@link google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.verify|verify} messages. + * @param message FeatureSetEditionDefault message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSetEditionDefault message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSetEditionDefault + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Decodes a FeatureSetEditionDefault message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSetEditionDefault + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Verifies a FeatureSetEditionDefault message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { + + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } + + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { + + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); + + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; + + /** + * Creates a new SourceCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SourceCodeInfo instance + */ + public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; + + /** + * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @param message SourceCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; + + /** + * Verifies a SourceCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SourceCodeInfo { + + /** Properties of a Location. */ + interface ILocation { + + /** Location path */ + path?: (number[]|null); + + /** Location span */ + span?: (number[]|null); + + /** Location leadingComments */ + leadingComments?: (string|null); + + /** Location trailingComments */ + trailingComments?: (string|null); + + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + + /** Location path. */ + public path: number[]; + + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; + + /** + * Creates a new Location instance using the specified properties. + * @param [properties] Properties to set + * @returns Location instance + */ + public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Location message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; + + /** + * Verifies a Location message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { + + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } + + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { + + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); + + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; + + /** + * Creates a new GeneratedCodeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GeneratedCodeInfo instance + */ + public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; + + /** + * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @param message GeneratedCodeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; + + /** + * Verifies a GeneratedCodeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|keyof typeof google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } + + /** Represents an Annotation. */ + class Annotation implements IAnnotation { + + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); + + /** Annotation path. */ + public path: number[]; + + /** Annotation sourceFile. */ + public sourceFile: string; + + /** Annotation begin. */ + public begin: number; + + /** Annotation end. */ + public end: number; + + /** Annotation semantic. */ + public semantic: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|keyof typeof google.protobuf.GeneratedCodeInfo.Annotation.Semantic); + + /** + * Creates a new Annotation instance using the specified properties. + * @param [properties] Properties to set + * @returns Annotation instance + */ + public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @param message Annotation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Annotation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Decodes an Annotation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Verifies an Annotation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + enum Semantic { + NONE = 0, + SET = 1, + ALIAS = 2 + } + } + } + + /** SymbolVisibility enum. */ + enum SymbolVisibility { + VISIBILITY_UNSET = 0, + VISIBILITY_LOCAL = 1, + VISIBILITY_EXPORT = 2 + } + + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|Buffer|string|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: (Uint8Array|Buffer|string); + + /** + * Creates a new Any instance using the specified properties. + * @param [properties] Properties to set + * @returns Any instance + */ + public static create(properties?: google.protobuf.IAny): google.protobuf.Any; + + /** + * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. + * @param message Any message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. + * @param message Any message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Any message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Any + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any; + + /** + * Decodes an Any message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Any + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any; + + /** + * Verifies an Any message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates a new Empty instance using the specified properties. + * @param [properties] Properties to set + * @returns Empty instance + */ + public static create(properties?: google.protobuf.IEmpty): google.protobuf.Empty; + + /** + * Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @param message Empty message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @param message Empty message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Empty message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Empty + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Empty; + + /** + * Decodes an Empty message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Empty + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Empty; + + /** + * Verifies an Empty message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a new FieldMask instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldMask instance + */ + public static create(properties?: google.protobuf.IFieldMask): google.protobuf.FieldMask; + + /** + * Encodes the specified FieldMask message. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. + * @param message FieldMask message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldMask message, length delimited. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. + * @param message FieldMask message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldMask message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldMask + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldMask; + + /** + * Decodes a FieldMask message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldMask + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldMask; + + /** + * Verifies a FieldMask message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|Long|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); + } + + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { + + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|Long|string); + + /** Timestamp nanos. */ + public nanos: number; + + /** + * Creates a new Timestamp instance using the specified properties. + * @param [properties] Properties to set + * @returns Timestamp instance + */ + public static create(properties?: google.protobuf.ITimestamp): google.protobuf.Timestamp; + + /** + * Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. + * @param message Timestamp message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. + * @param message Timestamp message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Timestamp message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Timestamp + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Timestamp; + + /** + * Decodes a Timestamp message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Timestamp + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Timestamp; + + /** + * Verifies a Timestamp message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a new Struct instance using the specified properties. + * @param [properties] Properties to set + * @returns Struct instance + */ + public static create(properties?: google.protobuf.IStruct): google.protobuf.Struct; + + /** + * Encodes the specified Struct message. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. + * @param message Struct message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Struct message, length delimited. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. + * @param message Struct message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Struct message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Struct + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Struct; + + /** + * Decodes a Struct message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Struct + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Struct; + + /** + * Verifies a Struct message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|keyof typeof google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|keyof typeof google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a new Value instance using the specified properties. + * @param [properties] Properties to set + * @returns Value instance + */ + public static create(properties?: google.protobuf.IValue): google.protobuf.Value; + + /** + * Encodes the specified Value message. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. + * @param message Value message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Value message, length delimited. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. + * @param message Value message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Value message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Value + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Value; + + /** + * Decodes a Value message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Value + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Value; + + /** + * Verifies a Value message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + enum NullValue { + NULL_VALUE = 0 + } + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a new ListValue instance using the specified properties. + * @param [properties] Properties to set + * @returns ListValue instance + */ + public static create(properties?: google.protobuf.IListValue): google.protobuf.ListValue; + + /** + * Encodes the specified ListValue message. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. + * @param message ListValue message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListValue message, length delimited. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. + * @param message ListValue message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListValue message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ListValue; + + /** + * Decodes a ListValue message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ListValue; + + /** + * Verifies a ListValue message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of an ErrorInfo. */ + interface IErrorInfo { + + /** ErrorInfo reason */ + reason?: (string|null); + + /** ErrorInfo domain */ + domain?: (string|null); + + /** ErrorInfo metadata */ + metadata?: ({ [k: string]: string }|null); + } + + /** Represents an ErrorInfo. */ + class ErrorInfo implements IErrorInfo { + + /** + * Constructs a new ErrorInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IErrorInfo); + + /** ErrorInfo reason. */ + public reason: string; + + /** ErrorInfo domain. */ + public domain: string; + + /** ErrorInfo metadata. */ + public metadata: { [k: string]: string }; + + /** + * Creates a new ErrorInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns ErrorInfo instance + */ + public static create(properties?: google.rpc.IErrorInfo): google.rpc.ErrorInfo; + + /** + * Encodes the specified ErrorInfo message. Does not implicitly {@link google.rpc.ErrorInfo.verify|verify} messages. + * @param message ErrorInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IErrorInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ErrorInfo message, length delimited. Does not implicitly {@link google.rpc.ErrorInfo.verify|verify} messages. + * @param message ErrorInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IErrorInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ErrorInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ErrorInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.ErrorInfo; + + /** + * Decodes an ErrorInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ErrorInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.ErrorInfo; + + /** + * Verifies an ErrorInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ErrorInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ErrorInfo + */ + public static fromObject(object: { [k: string]: any }): google.rpc.ErrorInfo; + + /** + * Creates a plain object from an ErrorInfo message. Also converts values to other types if specified. + * @param message ErrorInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.ErrorInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ErrorInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ErrorInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RetryInfo. */ + interface IRetryInfo { + + /** RetryInfo retryDelay */ + retryDelay?: (google.protobuf.IDuration|null); + } + + /** Represents a RetryInfo. */ + class RetryInfo implements IRetryInfo { + + /** + * Constructs a new RetryInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IRetryInfo); + + /** RetryInfo retryDelay. */ + public retryDelay?: (google.protobuf.IDuration|null); + + /** + * Creates a new RetryInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns RetryInfo instance + */ + public static create(properties?: google.rpc.IRetryInfo): google.rpc.RetryInfo; + + /** + * Encodes the specified RetryInfo message. Does not implicitly {@link google.rpc.RetryInfo.verify|verify} messages. + * @param message RetryInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IRetryInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RetryInfo message, length delimited. Does not implicitly {@link google.rpc.RetryInfo.verify|verify} messages. + * @param message RetryInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IRetryInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RetryInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RetryInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.RetryInfo; + + /** + * Decodes a RetryInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RetryInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.RetryInfo; + + /** + * Verifies a RetryInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RetryInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RetryInfo + */ + public static fromObject(object: { [k: string]: any }): google.rpc.RetryInfo; + + /** + * Creates a plain object from a RetryInfo message. Also converts values to other types if specified. + * @param message RetryInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.RetryInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RetryInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RetryInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DebugInfo. */ + interface IDebugInfo { + + /** DebugInfo stackEntries */ + stackEntries?: (string[]|null); + + /** DebugInfo detail */ + detail?: (string|null); + } + + /** Represents a DebugInfo. */ + class DebugInfo implements IDebugInfo { + + /** + * Constructs a new DebugInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IDebugInfo); + + /** DebugInfo stackEntries. */ + public stackEntries: string[]; + + /** DebugInfo detail. */ + public detail: string; + + /** + * Creates a new DebugInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns DebugInfo instance + */ + public static create(properties?: google.rpc.IDebugInfo): google.rpc.DebugInfo; + + /** + * Encodes the specified DebugInfo message. Does not implicitly {@link google.rpc.DebugInfo.verify|verify} messages. + * @param message DebugInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IDebugInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DebugInfo message, length delimited. Does not implicitly {@link google.rpc.DebugInfo.verify|verify} messages. + * @param message DebugInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IDebugInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DebugInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DebugInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.DebugInfo; + + /** + * Decodes a DebugInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DebugInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.DebugInfo; + + /** + * Verifies a DebugInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DebugInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DebugInfo + */ + public static fromObject(object: { [k: string]: any }): google.rpc.DebugInfo; + + /** + * Creates a plain object from a DebugInfo message. Also converts values to other types if specified. + * @param message DebugInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.DebugInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DebugInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DebugInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QuotaFailure. */ + interface IQuotaFailure { + + /** QuotaFailure violations */ + violations?: (google.rpc.QuotaFailure.IViolation[]|null); + } + + /** Represents a QuotaFailure. */ + class QuotaFailure implements IQuotaFailure { + + /** + * Constructs a new QuotaFailure. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IQuotaFailure); + + /** QuotaFailure violations. */ + public violations: google.rpc.QuotaFailure.IViolation[]; + + /** + * Creates a new QuotaFailure instance using the specified properties. + * @param [properties] Properties to set + * @returns QuotaFailure instance + */ + public static create(properties?: google.rpc.IQuotaFailure): google.rpc.QuotaFailure; + + /** + * Encodes the specified QuotaFailure message. Does not implicitly {@link google.rpc.QuotaFailure.verify|verify} messages. + * @param message QuotaFailure message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IQuotaFailure, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified QuotaFailure message, length delimited. Does not implicitly {@link google.rpc.QuotaFailure.verify|verify} messages. + * @param message QuotaFailure message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IQuotaFailure, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a QuotaFailure message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns QuotaFailure + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.QuotaFailure; + + /** + * Decodes a QuotaFailure message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns QuotaFailure + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.QuotaFailure; + + /** + * Verifies a QuotaFailure message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a QuotaFailure message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QuotaFailure + */ + public static fromObject(object: { [k: string]: any }): google.rpc.QuotaFailure; + + /** + * Creates a plain object from a QuotaFailure message. Also converts values to other types if specified. + * @param message QuotaFailure + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.QuotaFailure, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QuotaFailure to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QuotaFailure + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace QuotaFailure { + + /** Properties of a Violation. */ + interface IViolation { + + /** Violation subject */ + subject?: (string|null); + + /** Violation description */ + description?: (string|null); + } + + /** Represents a Violation. */ + class Violation implements IViolation { + + /** + * Constructs a new Violation. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.QuotaFailure.IViolation); + + /** Violation subject. */ + public subject: string; + + /** Violation description. */ + public description: string; + + /** + * Creates a new Violation instance using the specified properties. + * @param [properties] Properties to set + * @returns Violation instance + */ + public static create(properties?: google.rpc.QuotaFailure.IViolation): google.rpc.QuotaFailure.Violation; + + /** + * Encodes the specified Violation message. Does not implicitly {@link google.rpc.QuotaFailure.Violation.verify|verify} messages. + * @param message Violation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.QuotaFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Violation message, length delimited. Does not implicitly {@link google.rpc.QuotaFailure.Violation.verify|verify} messages. + * @param message Violation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.QuotaFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Violation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Violation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.QuotaFailure.Violation; + + /** + * Decodes a Violation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Violation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.QuotaFailure.Violation; + + /** + * Verifies a Violation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Violation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Violation + */ + public static fromObject(object: { [k: string]: any }): google.rpc.QuotaFailure.Violation; + + /** + * Creates a plain object from a Violation message. Also converts values to other types if specified. + * @param message Violation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.QuotaFailure.Violation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Violation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Violation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a PreconditionFailure. */ + interface IPreconditionFailure { + + /** PreconditionFailure violations */ + violations?: (google.rpc.PreconditionFailure.IViolation[]|null); + } + + /** Represents a PreconditionFailure. */ + class PreconditionFailure implements IPreconditionFailure { + + /** + * Constructs a new PreconditionFailure. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IPreconditionFailure); + + /** PreconditionFailure violations. */ + public violations: google.rpc.PreconditionFailure.IViolation[]; + + /** + * Creates a new PreconditionFailure instance using the specified properties. + * @param [properties] Properties to set + * @returns PreconditionFailure instance + */ + public static create(properties?: google.rpc.IPreconditionFailure): google.rpc.PreconditionFailure; + + /** + * Encodes the specified PreconditionFailure message. Does not implicitly {@link google.rpc.PreconditionFailure.verify|verify} messages. + * @param message PreconditionFailure message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IPreconditionFailure, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PreconditionFailure message, length delimited. Does not implicitly {@link google.rpc.PreconditionFailure.verify|verify} messages. + * @param message PreconditionFailure message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IPreconditionFailure, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PreconditionFailure message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PreconditionFailure + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.PreconditionFailure; + + /** + * Decodes a PreconditionFailure message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PreconditionFailure + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.PreconditionFailure; + + /** + * Verifies a PreconditionFailure message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PreconditionFailure message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PreconditionFailure + */ + public static fromObject(object: { [k: string]: any }): google.rpc.PreconditionFailure; + + /** + * Creates a plain object from a PreconditionFailure message. Also converts values to other types if specified. + * @param message PreconditionFailure + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.PreconditionFailure, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PreconditionFailure to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PreconditionFailure + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PreconditionFailure { + + /** Properties of a Violation. */ + interface IViolation { + + /** Violation type */ + type?: (string|null); + + /** Violation subject */ + subject?: (string|null); + + /** Violation description */ + description?: (string|null); + } + + /** Represents a Violation. */ + class Violation implements IViolation { + + /** + * Constructs a new Violation. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.PreconditionFailure.IViolation); + + /** Violation type. */ + public type: string; + + /** Violation subject. */ + public subject: string; + + /** Violation description. */ + public description: string; + + /** + * Creates a new Violation instance using the specified properties. + * @param [properties] Properties to set + * @returns Violation instance + */ + public static create(properties?: google.rpc.PreconditionFailure.IViolation): google.rpc.PreconditionFailure.Violation; + + /** + * Encodes the specified Violation message. Does not implicitly {@link google.rpc.PreconditionFailure.Violation.verify|verify} messages. + * @param message Violation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.PreconditionFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Violation message, length delimited. Does not implicitly {@link google.rpc.PreconditionFailure.Violation.verify|verify} messages. + * @param message Violation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.PreconditionFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Violation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Violation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.PreconditionFailure.Violation; + + /** + * Decodes a Violation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Violation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.PreconditionFailure.Violation; + + /** + * Verifies a Violation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Violation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Violation + */ + public static fromObject(object: { [k: string]: any }): google.rpc.PreconditionFailure.Violation; + + /** + * Creates a plain object from a Violation message. Also converts values to other types if specified. + * @param message Violation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.PreconditionFailure.Violation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Violation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Violation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a BadRequest. */ + interface IBadRequest { + + /** BadRequest fieldViolations */ + fieldViolations?: (google.rpc.BadRequest.IFieldViolation[]|null); + } + + /** Represents a BadRequest. */ + class BadRequest implements IBadRequest { + + /** + * Constructs a new BadRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IBadRequest); + + /** BadRequest fieldViolations. */ + public fieldViolations: google.rpc.BadRequest.IFieldViolation[]; + + /** + * Creates a new BadRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns BadRequest instance + */ + public static create(properties?: google.rpc.IBadRequest): google.rpc.BadRequest; + + /** + * Encodes the specified BadRequest message. Does not implicitly {@link google.rpc.BadRequest.verify|verify} messages. + * @param message BadRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IBadRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BadRequest message, length delimited. Does not implicitly {@link google.rpc.BadRequest.verify|verify} messages. + * @param message BadRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IBadRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BadRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.BadRequest; + + /** + * Decodes a BadRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.BadRequest; + + /** + * Verifies a BadRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BadRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BadRequest + */ + public static fromObject(object: { [k: string]: any }): google.rpc.BadRequest; + + /** + * Creates a plain object from a BadRequest message. Also converts values to other types if specified. + * @param message BadRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.BadRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BadRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BadRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace BadRequest { + + /** Properties of a FieldViolation. */ + interface IFieldViolation { + + /** FieldViolation field */ + field?: (string|null); + + /** FieldViolation description */ + description?: (string|null); + } + + /** Represents a FieldViolation. */ + class FieldViolation implements IFieldViolation { + + /** + * Constructs a new FieldViolation. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.BadRequest.IFieldViolation); + + /** FieldViolation field. */ + public field: string; + + /** FieldViolation description. */ + public description: string; + + /** + * Creates a new FieldViolation instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldViolation instance + */ + public static create(properties?: google.rpc.BadRequest.IFieldViolation): google.rpc.BadRequest.FieldViolation; + + /** + * Encodes the specified FieldViolation message. Does not implicitly {@link google.rpc.BadRequest.FieldViolation.verify|verify} messages. + * @param message FieldViolation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.BadRequest.IFieldViolation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldViolation message, length delimited. Does not implicitly {@link google.rpc.BadRequest.FieldViolation.verify|verify} messages. + * @param message FieldViolation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.BadRequest.IFieldViolation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldViolation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldViolation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.BadRequest.FieldViolation; + + /** + * Decodes a FieldViolation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldViolation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.BadRequest.FieldViolation; + + /** + * Verifies a FieldViolation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldViolation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldViolation + */ + public static fromObject(object: { [k: string]: any }): google.rpc.BadRequest.FieldViolation; + + /** + * Creates a plain object from a FieldViolation message. Also converts values to other types if specified. + * @param message FieldViolation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.BadRequest.FieldViolation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldViolation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldViolation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a RequestInfo. */ + interface IRequestInfo { + + /** RequestInfo requestId */ + requestId?: (string|null); + + /** RequestInfo servingData */ + servingData?: (string|null); + } + + /** Represents a RequestInfo. */ + class RequestInfo implements IRequestInfo { + + /** + * Constructs a new RequestInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IRequestInfo); + + /** RequestInfo requestId. */ + public requestId: string; + + /** RequestInfo servingData. */ + public servingData: string; + + /** + * Creates a new RequestInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns RequestInfo instance + */ + public static create(properties?: google.rpc.IRequestInfo): google.rpc.RequestInfo; + + /** + * Encodes the specified RequestInfo message. Does not implicitly {@link google.rpc.RequestInfo.verify|verify} messages. + * @param message RequestInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IRequestInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RequestInfo message, length delimited. Does not implicitly {@link google.rpc.RequestInfo.verify|verify} messages. + * @param message RequestInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IRequestInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RequestInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RequestInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.RequestInfo; + + /** + * Decodes a RequestInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RequestInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.RequestInfo; + + /** + * Verifies a RequestInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RequestInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RequestInfo + */ + public static fromObject(object: { [k: string]: any }): google.rpc.RequestInfo; + + /** + * Creates a plain object from a RequestInfo message. Also converts values to other types if specified. + * @param message RequestInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.RequestInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RequestInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RequestInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ResourceInfo. */ + interface IResourceInfo { + + /** ResourceInfo resourceType */ + resourceType?: (string|null); + + /** ResourceInfo resourceName */ + resourceName?: (string|null); + + /** ResourceInfo owner */ + owner?: (string|null); + + /** ResourceInfo description */ + description?: (string|null); + } + + /** Represents a ResourceInfo. */ + class ResourceInfo implements IResourceInfo { + + /** + * Constructs a new ResourceInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IResourceInfo); + + /** ResourceInfo resourceType. */ + public resourceType: string; + + /** ResourceInfo resourceName. */ + public resourceName: string; + + /** ResourceInfo owner. */ + public owner: string; + + /** ResourceInfo description. */ + public description: string; + + /** + * Creates a new ResourceInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns ResourceInfo instance + */ + public static create(properties?: google.rpc.IResourceInfo): google.rpc.ResourceInfo; + + /** + * Encodes the specified ResourceInfo message. Does not implicitly {@link google.rpc.ResourceInfo.verify|verify} messages. + * @param message ResourceInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IResourceInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResourceInfo message, length delimited. Does not implicitly {@link google.rpc.ResourceInfo.verify|verify} messages. + * @param message ResourceInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IResourceInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResourceInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.ResourceInfo; + + /** + * Decodes a ResourceInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.ResourceInfo; + + /** + * Verifies a ResourceInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResourceInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceInfo + */ + public static fromObject(object: { [k: string]: any }): google.rpc.ResourceInfo; + + /** + * Creates a plain object from a ResourceInfo message. Also converts values to other types if specified. + * @param message ResourceInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.ResourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Help. */ + interface IHelp { + + /** Help links */ + links?: (google.rpc.Help.ILink[]|null); + } + + /** Represents a Help. */ + class Help implements IHelp { + + /** + * Constructs a new Help. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IHelp); + + /** Help links. */ + public links: google.rpc.Help.ILink[]; + + /** + * Creates a new Help instance using the specified properties. + * @param [properties] Properties to set + * @returns Help instance + */ + public static create(properties?: google.rpc.IHelp): google.rpc.Help; + + /** + * Encodes the specified Help message. Does not implicitly {@link google.rpc.Help.verify|verify} messages. + * @param message Help message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IHelp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Help message, length delimited. Does not implicitly {@link google.rpc.Help.verify|verify} messages. + * @param message Help message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IHelp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Help message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Help + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Help; + + /** + * Decodes a Help message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Help + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Help; + + /** + * Verifies a Help message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Help message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Help + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Help; + + /** + * Creates a plain object from a Help message. Also converts values to other types if specified. + * @param message Help + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Help, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Help to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Help + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Help { + + /** Properties of a Link. */ + interface ILink { + + /** Link description */ + description?: (string|null); + + /** Link url */ + url?: (string|null); + } + + /** Represents a Link. */ + class Link implements ILink { + + /** + * Constructs a new Link. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.Help.ILink); + + /** Link description. */ + public description: string; + + /** Link url. */ + public url: string; + + /** + * Creates a new Link instance using the specified properties. + * @param [properties] Properties to set + * @returns Link instance + */ + public static create(properties?: google.rpc.Help.ILink): google.rpc.Help.Link; + + /** + * Encodes the specified Link message. Does not implicitly {@link google.rpc.Help.Link.verify|verify} messages. + * @param message Link message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.Help.ILink, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Link message, length delimited. Does not implicitly {@link google.rpc.Help.Link.verify|verify} messages. + * @param message Link message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.Help.ILink, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Link message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Link + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Help.Link; + + /** + * Decodes a Link message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Link + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Help.Link; + + /** + * Verifies a Link message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Link message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Link + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Help.Link; + + /** + * Creates a plain object from a Link message. Also converts values to other types if specified. + * @param message Link + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Help.Link, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Link to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Link + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a LocalizedMessage. */ + interface ILocalizedMessage { + + /** LocalizedMessage locale */ + locale?: (string|null); + + /** LocalizedMessage message */ + message?: (string|null); + } + + /** Represents a LocalizedMessage. */ + class LocalizedMessage implements ILocalizedMessage { + + /** + * Constructs a new LocalizedMessage. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.ILocalizedMessage); + + /** LocalizedMessage locale. */ + public locale: string; + + /** LocalizedMessage message. */ + public message: string; + + /** + * Creates a new LocalizedMessage instance using the specified properties. + * @param [properties] Properties to set + * @returns LocalizedMessage instance + */ + public static create(properties?: google.rpc.ILocalizedMessage): google.rpc.LocalizedMessage; + + /** + * Encodes the specified LocalizedMessage message. Does not implicitly {@link google.rpc.LocalizedMessage.verify|verify} messages. + * @param message LocalizedMessage message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.ILocalizedMessage, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified LocalizedMessage message, length delimited. Does not implicitly {@link google.rpc.LocalizedMessage.verify|verify} messages. + * @param message LocalizedMessage message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.ILocalizedMessage, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a LocalizedMessage message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns LocalizedMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.LocalizedMessage; + + /** + * Decodes a LocalizedMessage message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns LocalizedMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.LocalizedMessage; + + /** + * Verifies a LocalizedMessage message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a LocalizedMessage message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LocalizedMessage + */ + public static fromObject(object: { [k: string]: any }): google.rpc.LocalizedMessage; + + /** + * Creates a plain object from a LocalizedMessage message. Also converts values to other types if specified. + * @param message LocalizedMessage + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.LocalizedMessage, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LocalizedMessage to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LocalizedMessage + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a new Status instance using the specified properties. + * @param [properties] Properties to set + * @returns Status instance + */ + public static create(properties?: google.rpc.IStatus): google.rpc.Status; + + /** + * Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages. + * @param message Status message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages. + * @param message Status message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Status message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Status + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Status; + + /** + * Decodes a Status message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Status + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Status; + + /** + * Verifies a Status message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace spanner. */ + namespace spanner { + + /** Namespace admin. */ + namespace admin { + + /** Namespace database. */ + namespace database { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of a Backup. */ + interface IBackup { + + /** Backup database */ + database?: (string|null); + + /** Backup versionTime */ + versionTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup name */ + name?: (string|null); + + /** Backup createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Backup sizeBytes */ + sizeBytes?: (number|Long|string|null); + + /** Backup freeableSizeBytes */ + freeableSizeBytes?: (number|Long|string|null); + + /** Backup exclusiveSizeBytes */ + exclusiveSizeBytes?: (number|Long|string|null); + + /** Backup state */ + state?: (google.spanner.admin.database.v1.Backup.State|keyof typeof google.spanner.admin.database.v1.Backup.State|null); + + /** Backup referencingDatabases */ + referencingDatabases?: (string[]|null); + + /** Backup encryptionInfo */ + encryptionInfo?: (google.spanner.admin.database.v1.IEncryptionInfo|null); + + /** Backup encryptionInformation */ + encryptionInformation?: (google.spanner.admin.database.v1.IEncryptionInfo[]|null); + + /** Backup databaseDialect */ + databaseDialect?: (google.spanner.admin.database.v1.DatabaseDialect|keyof typeof google.spanner.admin.database.v1.DatabaseDialect|null); + + /** Backup referencingBackups */ + referencingBackups?: (string[]|null); + + /** Backup maxExpireTime */ + maxExpireTime?: (google.protobuf.ITimestamp|null); + + /** Backup backupSchedules */ + backupSchedules?: (string[]|null); + + /** Backup incrementalBackupChainId */ + incrementalBackupChainId?: (string|null); + + /** Backup oldestVersionTime */ + oldestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Backup instancePartitions */ + instancePartitions?: (google.spanner.admin.database.v1.IBackupInstancePartition[]|null); + } + + /** Represents a Backup. */ + class Backup implements IBackup { + + /** + * Constructs a new Backup. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IBackup); + + /** Backup database. */ + public database: string; + + /** Backup versionTime. */ + public versionTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup name. */ + public name: string; + + /** Backup createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Backup sizeBytes. */ + public sizeBytes: (number|Long|string); + + /** Backup freeableSizeBytes. */ + public freeableSizeBytes: (number|Long|string); + + /** Backup exclusiveSizeBytes. */ + public exclusiveSizeBytes: (number|Long|string); + + /** Backup state. */ + public state: (google.spanner.admin.database.v1.Backup.State|keyof typeof google.spanner.admin.database.v1.Backup.State); + + /** Backup referencingDatabases. */ + public referencingDatabases: string[]; + + /** Backup encryptionInfo. */ + public encryptionInfo?: (google.spanner.admin.database.v1.IEncryptionInfo|null); + + /** Backup encryptionInformation. */ + public encryptionInformation: google.spanner.admin.database.v1.IEncryptionInfo[]; + + /** Backup databaseDialect. */ + public databaseDialect: (google.spanner.admin.database.v1.DatabaseDialect|keyof typeof google.spanner.admin.database.v1.DatabaseDialect); + + /** Backup referencingBackups. */ + public referencingBackups: string[]; + + /** Backup maxExpireTime. */ + public maxExpireTime?: (google.protobuf.ITimestamp|null); + + /** Backup backupSchedules. */ + public backupSchedules: string[]; + + /** Backup incrementalBackupChainId. */ + public incrementalBackupChainId: string; + + /** Backup oldestVersionTime. */ + public oldestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Backup instancePartitions. */ + public instancePartitions: google.spanner.admin.database.v1.IBackupInstancePartition[]; + + /** + * Creates a new Backup instance using the specified properties. + * @param [properties] Properties to set + * @returns Backup instance + */ + public static create(properties?: google.spanner.admin.database.v1.IBackup): google.spanner.admin.database.v1.Backup; + + /** + * Encodes the specified Backup message. Does not implicitly {@link google.spanner.admin.database.v1.Backup.verify|verify} messages. + * @param message Backup message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IBackup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Backup message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.Backup.verify|verify} messages. + * @param message Backup message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IBackup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Backup message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Backup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.Backup; + + /** + * Decodes a Backup message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Backup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.Backup; + + /** + * Verifies a Backup message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Backup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Backup + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.Backup; + + /** + * Creates a plain object from a Backup message. Also converts values to other types if specified. + * @param message Backup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.Backup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Backup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Backup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Backup { + + /** State enum. */ + enum State { + STATE_UNSPECIFIED = 0, + CREATING = 1, + READY = 2 + } + } + + /** Properties of a CreateBackupRequest. */ + interface ICreateBackupRequest { + + /** CreateBackupRequest parent */ + parent?: (string|null); + + /** CreateBackupRequest backupId */ + backupId?: (string|null); + + /** CreateBackupRequest backup */ + backup?: (google.spanner.admin.database.v1.IBackup|null); + + /** CreateBackupRequest encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.ICreateBackupEncryptionConfig|null); + } + + /** Represents a CreateBackupRequest. */ + class CreateBackupRequest implements ICreateBackupRequest { + + /** + * Constructs a new CreateBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICreateBackupRequest); + + /** CreateBackupRequest parent. */ + public parent: string; + + /** CreateBackupRequest backupId. */ + public backupId: string; + + /** CreateBackupRequest backup. */ + public backup?: (google.spanner.admin.database.v1.IBackup|null); + + /** CreateBackupRequest encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.ICreateBackupEncryptionConfig|null); + + /** + * Creates a new CreateBackupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateBackupRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICreateBackupRequest): google.spanner.admin.database.v1.CreateBackupRequest; + + /** + * Encodes the specified CreateBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupRequest.verify|verify} messages. + * @param message CreateBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICreateBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupRequest.verify|verify} messages. + * @param message CreateBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateBackupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateBackupRequest; + + /** + * Decodes a CreateBackupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateBackupRequest; + + /** + * Verifies a CreateBackupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateBackupRequest; + + /** + * Creates a plain object from a CreateBackupRequest message. Also converts values to other types if specified. + * @param message CreateBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CreateBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateBackupMetadata. */ + interface ICreateBackupMetadata { + + /** CreateBackupMetadata name */ + name?: (string|null); + + /** CreateBackupMetadata database */ + database?: (string|null); + + /** CreateBackupMetadata progress */ + progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** CreateBackupMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CreateBackupMetadata. */ + class CreateBackupMetadata implements ICreateBackupMetadata { + + /** + * Constructs a new CreateBackupMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICreateBackupMetadata); + + /** CreateBackupMetadata name. */ + public name: string; + + /** CreateBackupMetadata database. */ + public database: string; + + /** CreateBackupMetadata progress. */ + public progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** CreateBackupMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new CreateBackupMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateBackupMetadata instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICreateBackupMetadata): google.spanner.admin.database.v1.CreateBackupMetadata; + + /** + * Encodes the specified CreateBackupMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupMetadata.verify|verify} messages. + * @param message CreateBackupMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICreateBackupMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateBackupMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupMetadata.verify|verify} messages. + * @param message CreateBackupMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateBackupMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateBackupMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateBackupMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateBackupMetadata; + + /** + * Decodes a CreateBackupMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateBackupMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateBackupMetadata; + + /** + * Verifies a CreateBackupMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateBackupMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateBackupMetadata; + + /** + * Creates a plain object from a CreateBackupMetadata message. Also converts values to other types if specified. + * @param message CreateBackupMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CreateBackupMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CopyBackupRequest. */ + interface ICopyBackupRequest { + + /** CopyBackupRequest parent */ + parent?: (string|null); + + /** CopyBackupRequest backupId */ + backupId?: (string|null); + + /** CopyBackupRequest sourceBackup */ + sourceBackup?: (string|null); + + /** CopyBackupRequest expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** CopyBackupRequest encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.ICopyBackupEncryptionConfig|null); + } + + /** Represents a CopyBackupRequest. */ + class CopyBackupRequest implements ICopyBackupRequest { + + /** + * Constructs a new CopyBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICopyBackupRequest); + + /** CopyBackupRequest parent. */ + public parent: string; + + /** CopyBackupRequest backupId. */ + public backupId: string; + + /** CopyBackupRequest sourceBackup. */ + public sourceBackup: string; + + /** CopyBackupRequest expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** CopyBackupRequest encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.ICopyBackupEncryptionConfig|null); + + /** + * Creates a new CopyBackupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CopyBackupRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICopyBackupRequest): google.spanner.admin.database.v1.CopyBackupRequest; + + /** + * Encodes the specified CopyBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupRequest.verify|verify} messages. + * @param message CopyBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICopyBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CopyBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupRequest.verify|verify} messages. + * @param message CopyBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICopyBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CopyBackupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CopyBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CopyBackupRequest; + + /** + * Decodes a CopyBackupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CopyBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CopyBackupRequest; + + /** + * Verifies a CopyBackupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CopyBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CopyBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CopyBackupRequest; + + /** + * Creates a plain object from a CopyBackupRequest message. Also converts values to other types if specified. + * @param message CopyBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CopyBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CopyBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CopyBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CopyBackupMetadata. */ + interface ICopyBackupMetadata { + + /** CopyBackupMetadata name */ + name?: (string|null); + + /** CopyBackupMetadata sourceBackup */ + sourceBackup?: (string|null); + + /** CopyBackupMetadata progress */ + progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** CopyBackupMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CopyBackupMetadata. */ + class CopyBackupMetadata implements ICopyBackupMetadata { + + /** + * Constructs a new CopyBackupMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICopyBackupMetadata); + + /** CopyBackupMetadata name. */ + public name: string; + + /** CopyBackupMetadata sourceBackup. */ + public sourceBackup: string; + + /** CopyBackupMetadata progress. */ + public progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** CopyBackupMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new CopyBackupMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns CopyBackupMetadata instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICopyBackupMetadata): google.spanner.admin.database.v1.CopyBackupMetadata; + + /** + * Encodes the specified CopyBackupMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupMetadata.verify|verify} messages. + * @param message CopyBackupMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICopyBackupMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CopyBackupMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupMetadata.verify|verify} messages. + * @param message CopyBackupMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICopyBackupMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CopyBackupMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CopyBackupMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CopyBackupMetadata; + + /** + * Decodes a CopyBackupMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CopyBackupMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CopyBackupMetadata; + + /** + * Verifies a CopyBackupMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CopyBackupMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CopyBackupMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CopyBackupMetadata; + + /** + * Creates a plain object from a CopyBackupMetadata message. Also converts values to other types if specified. + * @param message CopyBackupMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CopyBackupMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CopyBackupMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CopyBackupMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateBackupRequest. */ + interface IUpdateBackupRequest { + + /** UpdateBackupRequest backup */ + backup?: (google.spanner.admin.database.v1.IBackup|null); + + /** UpdateBackupRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateBackupRequest. */ + class UpdateBackupRequest implements IUpdateBackupRequest { + + /** + * Constructs a new UpdateBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IUpdateBackupRequest); + + /** UpdateBackupRequest backup. */ + public backup?: (google.spanner.admin.database.v1.IBackup|null); + + /** UpdateBackupRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new UpdateBackupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateBackupRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IUpdateBackupRequest): google.spanner.admin.database.v1.UpdateBackupRequest; + + /** + * Encodes the specified UpdateBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupRequest.verify|verify} messages. + * @param message UpdateBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IUpdateBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupRequest.verify|verify} messages. + * @param message UpdateBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateBackupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateBackupRequest; + + /** + * Decodes an UpdateBackupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateBackupRequest; + + /** + * Verifies an UpdateBackupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateBackupRequest; + + /** + * Creates a plain object from an UpdateBackupRequest message. Also converts values to other types if specified. + * @param message UpdateBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.UpdateBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupRequest. */ + interface IGetBackupRequest { + + /** GetBackupRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupRequest. */ + class GetBackupRequest implements IGetBackupRequest { + + /** + * Constructs a new GetBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IGetBackupRequest); + + /** GetBackupRequest name. */ + public name: string; + + /** + * Creates a new GetBackupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetBackupRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IGetBackupRequest): google.spanner.admin.database.v1.GetBackupRequest; + + /** + * Encodes the specified GetBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupRequest.verify|verify} messages. + * @param message GetBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IGetBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupRequest.verify|verify} messages. + * @param message GetBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IGetBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetBackupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetBackupRequest; + + /** + * Decodes a GetBackupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetBackupRequest; + + /** + * Verifies a GetBackupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetBackupRequest; + + /** + * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. + * @param message GetBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.GetBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupRequest. */ + interface IDeleteBackupRequest { + + /** DeleteBackupRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupRequest. */ + class DeleteBackupRequest implements IDeleteBackupRequest { + + /** + * Constructs a new DeleteBackupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IDeleteBackupRequest); + + /** DeleteBackupRequest name. */ + public name: string; + + /** + * Creates a new DeleteBackupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteBackupRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IDeleteBackupRequest): google.spanner.admin.database.v1.DeleteBackupRequest; + + /** + * Encodes the specified DeleteBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupRequest.verify|verify} messages. + * @param message DeleteBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IDeleteBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupRequest.verify|verify} messages. + * @param message DeleteBackupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IDeleteBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteBackupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.DeleteBackupRequest; + + /** + * Decodes a DeleteBackupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.DeleteBackupRequest; + + /** + * Verifies a DeleteBackupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.DeleteBackupRequest; + + /** + * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. + * @param message DeleteBackupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.DeleteBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsRequest. */ + interface IListBackupsRequest { + + /** ListBackupsRequest parent */ + parent?: (string|null); + + /** ListBackupsRequest filter */ + filter?: (string|null); + + /** ListBackupsRequest pageSize */ + pageSize?: (number|null); + + /** ListBackupsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListBackupsRequest. */ + class ListBackupsRequest implements IListBackupsRequest { + + /** + * Constructs a new ListBackupsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListBackupsRequest); + + /** ListBackupsRequest parent. */ + public parent: string; + + /** ListBackupsRequest filter. */ + public filter: string; + + /** ListBackupsRequest pageSize. */ + public pageSize: number; + + /** ListBackupsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListBackupsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListBackupsRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListBackupsRequest): google.spanner.admin.database.v1.ListBackupsRequest; + + /** + * Encodes the specified ListBackupsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsRequest.verify|verify} messages. + * @param message ListBackupsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListBackupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListBackupsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsRequest.verify|verify} messages. + * @param message ListBackupsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListBackupsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListBackupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupsRequest; + + /** + * Decodes a ListBackupsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListBackupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupsRequest; + + /** + * Verifies a ListBackupsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupsRequest; + + /** + * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. + * @param message ListBackupsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListBackupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsResponse. */ + interface IListBackupsResponse { + + /** ListBackupsResponse backups */ + backups?: (google.spanner.admin.database.v1.IBackup[]|null); + + /** ListBackupsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListBackupsResponse. */ + class ListBackupsResponse implements IListBackupsResponse { + + /** + * Constructs a new ListBackupsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListBackupsResponse); + + /** ListBackupsResponse backups. */ + public backups: google.spanner.admin.database.v1.IBackup[]; + + /** ListBackupsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListBackupsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListBackupsResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListBackupsResponse): google.spanner.admin.database.v1.ListBackupsResponse; + + /** + * Encodes the specified ListBackupsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsResponse.verify|verify} messages. + * @param message ListBackupsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListBackupsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListBackupsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsResponse.verify|verify} messages. + * @param message ListBackupsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListBackupsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListBackupsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupsResponse; + + /** + * Decodes a ListBackupsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListBackupsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupsResponse; + + /** + * Verifies a ListBackupsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupsResponse; + + /** + * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. + * @param message ListBackupsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListBackupsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupOperationsRequest. */ + interface IListBackupOperationsRequest { + + /** ListBackupOperationsRequest parent */ + parent?: (string|null); + + /** ListBackupOperationsRequest filter */ + filter?: (string|null); + + /** ListBackupOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListBackupOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListBackupOperationsRequest. */ + class ListBackupOperationsRequest implements IListBackupOperationsRequest { + + /** + * Constructs a new ListBackupOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListBackupOperationsRequest); + + /** ListBackupOperationsRequest parent. */ + public parent: string; + + /** ListBackupOperationsRequest filter. */ + public filter: string; + + /** ListBackupOperationsRequest pageSize. */ + public pageSize: number; + + /** ListBackupOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListBackupOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListBackupOperationsRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListBackupOperationsRequest): google.spanner.admin.database.v1.ListBackupOperationsRequest; + + /** + * Encodes the specified ListBackupOperationsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsRequest.verify|verify} messages. + * @param message ListBackupOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListBackupOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListBackupOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsRequest.verify|verify} messages. + * @param message ListBackupOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListBackupOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListBackupOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupOperationsRequest; + + /** + * Decodes a ListBackupOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListBackupOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupOperationsRequest; + + /** + * Verifies a ListBackupOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListBackupOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupOperationsRequest; + + /** + * Creates a plain object from a ListBackupOperationsRequest message. Also converts values to other types if specified. + * @param message ListBackupOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListBackupOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupOperationsResponse. */ + interface IListBackupOperationsResponse { + + /** ListBackupOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListBackupOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListBackupOperationsResponse. */ + class ListBackupOperationsResponse implements IListBackupOperationsResponse { + + /** + * Constructs a new ListBackupOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListBackupOperationsResponse); + + /** ListBackupOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListBackupOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListBackupOperationsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListBackupOperationsResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListBackupOperationsResponse): google.spanner.admin.database.v1.ListBackupOperationsResponse; + + /** + * Encodes the specified ListBackupOperationsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsResponse.verify|verify} messages. + * @param message ListBackupOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListBackupOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListBackupOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsResponse.verify|verify} messages. + * @param message ListBackupOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListBackupOperationsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListBackupOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupOperationsResponse; + + /** + * Decodes a ListBackupOperationsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListBackupOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupOperationsResponse; + + /** + * Verifies a ListBackupOperationsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListBackupOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupOperationsResponse; + + /** + * Creates a plain object from a ListBackupOperationsResponse message. Also converts values to other types if specified. + * @param message ListBackupOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListBackupOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BackupInfo. */ + interface IBackupInfo { + + /** BackupInfo backup */ + backup?: (string|null); + + /** BackupInfo versionTime */ + versionTime?: (google.protobuf.ITimestamp|null); + + /** BackupInfo createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** BackupInfo sourceDatabase */ + sourceDatabase?: (string|null); + } + + /** Represents a BackupInfo. */ + class BackupInfo implements IBackupInfo { + + /** + * Constructs a new BackupInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IBackupInfo); + + /** BackupInfo backup. */ + public backup: string; + + /** BackupInfo versionTime. */ + public versionTime?: (google.protobuf.ITimestamp|null); + + /** BackupInfo createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** BackupInfo sourceDatabase. */ + public sourceDatabase: string; + + /** + * Creates a new BackupInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns BackupInfo instance + */ + public static create(properties?: google.spanner.admin.database.v1.IBackupInfo): google.spanner.admin.database.v1.BackupInfo; + + /** + * Encodes the specified BackupInfo message. Does not implicitly {@link google.spanner.admin.database.v1.BackupInfo.verify|verify} messages. + * @param message BackupInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IBackupInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BackupInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupInfo.verify|verify} messages. + * @param message BackupInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IBackupInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BackupInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BackupInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.BackupInfo; + + /** + * Decodes a BackupInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BackupInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.BackupInfo; + + /** + * Verifies a BackupInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BackupInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupInfo + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.BackupInfo; + + /** + * Creates a plain object from a BackupInfo message. Also converts values to other types if specified. + * @param message BackupInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.BackupInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateBackupEncryptionConfig. */ + interface ICreateBackupEncryptionConfig { + + /** CreateBackupEncryptionConfig encryptionType */ + encryptionType?: (google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType|keyof typeof google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType|null); + + /** CreateBackupEncryptionConfig kmsKeyName */ + kmsKeyName?: (string|null); + + /** CreateBackupEncryptionConfig kmsKeyNames */ + kmsKeyNames?: (string[]|null); + } + + /** Represents a CreateBackupEncryptionConfig. */ + class CreateBackupEncryptionConfig implements ICreateBackupEncryptionConfig { + + /** + * Constructs a new CreateBackupEncryptionConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICreateBackupEncryptionConfig); + + /** CreateBackupEncryptionConfig encryptionType. */ + public encryptionType: (google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType|keyof typeof google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType); + + /** CreateBackupEncryptionConfig kmsKeyName. */ + public kmsKeyName: string; + + /** CreateBackupEncryptionConfig kmsKeyNames. */ + public kmsKeyNames: string[]; + + /** + * Creates a new CreateBackupEncryptionConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateBackupEncryptionConfig instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICreateBackupEncryptionConfig): google.spanner.admin.database.v1.CreateBackupEncryptionConfig; + + /** + * Encodes the specified CreateBackupEncryptionConfig message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupEncryptionConfig.verify|verify} messages. + * @param message CreateBackupEncryptionConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICreateBackupEncryptionConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateBackupEncryptionConfig message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupEncryptionConfig.verify|verify} messages. + * @param message CreateBackupEncryptionConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateBackupEncryptionConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateBackupEncryptionConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateBackupEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateBackupEncryptionConfig; + + /** + * Decodes a CreateBackupEncryptionConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateBackupEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateBackupEncryptionConfig; + + /** + * Verifies a CreateBackupEncryptionConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateBackupEncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupEncryptionConfig + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateBackupEncryptionConfig; + + /** + * Creates a plain object from a CreateBackupEncryptionConfig message. Also converts values to other types if specified. + * @param message CreateBackupEncryptionConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CreateBackupEncryptionConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupEncryptionConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupEncryptionConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CreateBackupEncryptionConfig { + + /** EncryptionType enum. */ + enum EncryptionType { + ENCRYPTION_TYPE_UNSPECIFIED = 0, + USE_DATABASE_ENCRYPTION = 1, + GOOGLE_DEFAULT_ENCRYPTION = 2, + CUSTOMER_MANAGED_ENCRYPTION = 3 + } + } + + /** Properties of a CopyBackupEncryptionConfig. */ + interface ICopyBackupEncryptionConfig { + + /** CopyBackupEncryptionConfig encryptionType */ + encryptionType?: (google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType|keyof typeof google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType|null); + + /** CopyBackupEncryptionConfig kmsKeyName */ + kmsKeyName?: (string|null); + + /** CopyBackupEncryptionConfig kmsKeyNames */ + kmsKeyNames?: (string[]|null); + } + + /** Represents a CopyBackupEncryptionConfig. */ + class CopyBackupEncryptionConfig implements ICopyBackupEncryptionConfig { + + /** + * Constructs a new CopyBackupEncryptionConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICopyBackupEncryptionConfig); + + /** CopyBackupEncryptionConfig encryptionType. */ + public encryptionType: (google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType|keyof typeof google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType); + + /** CopyBackupEncryptionConfig kmsKeyName. */ + public kmsKeyName: string; + + /** CopyBackupEncryptionConfig kmsKeyNames. */ + public kmsKeyNames: string[]; + + /** + * Creates a new CopyBackupEncryptionConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns CopyBackupEncryptionConfig instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICopyBackupEncryptionConfig): google.spanner.admin.database.v1.CopyBackupEncryptionConfig; + + /** + * Encodes the specified CopyBackupEncryptionConfig message. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupEncryptionConfig.verify|verify} messages. + * @param message CopyBackupEncryptionConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICopyBackupEncryptionConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CopyBackupEncryptionConfig message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupEncryptionConfig.verify|verify} messages. + * @param message CopyBackupEncryptionConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICopyBackupEncryptionConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CopyBackupEncryptionConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CopyBackupEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CopyBackupEncryptionConfig; + + /** + * Decodes a CopyBackupEncryptionConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CopyBackupEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CopyBackupEncryptionConfig; + + /** + * Verifies a CopyBackupEncryptionConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CopyBackupEncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CopyBackupEncryptionConfig + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CopyBackupEncryptionConfig; + + /** + * Creates a plain object from a CopyBackupEncryptionConfig message. Also converts values to other types if specified. + * @param message CopyBackupEncryptionConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CopyBackupEncryptionConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CopyBackupEncryptionConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CopyBackupEncryptionConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CopyBackupEncryptionConfig { + + /** EncryptionType enum. */ + enum EncryptionType { + ENCRYPTION_TYPE_UNSPECIFIED = 0, + USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION = 1, + GOOGLE_DEFAULT_ENCRYPTION = 2, + CUSTOMER_MANAGED_ENCRYPTION = 3 + } + } + + /** Properties of a FullBackupSpec. */ + interface IFullBackupSpec { + } + + /** Represents a FullBackupSpec. */ + class FullBackupSpec implements IFullBackupSpec { + + /** + * Constructs a new FullBackupSpec. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IFullBackupSpec); + + /** + * Creates a new FullBackupSpec instance using the specified properties. + * @param [properties] Properties to set + * @returns FullBackupSpec instance + */ + public static create(properties?: google.spanner.admin.database.v1.IFullBackupSpec): google.spanner.admin.database.v1.FullBackupSpec; + + /** + * Encodes the specified FullBackupSpec message. Does not implicitly {@link google.spanner.admin.database.v1.FullBackupSpec.verify|verify} messages. + * @param message FullBackupSpec message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IFullBackupSpec, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FullBackupSpec message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.FullBackupSpec.verify|verify} messages. + * @param message FullBackupSpec message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IFullBackupSpec, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FullBackupSpec message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FullBackupSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.FullBackupSpec; + + /** + * Decodes a FullBackupSpec message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FullBackupSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.FullBackupSpec; + + /** + * Verifies a FullBackupSpec message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FullBackupSpec message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FullBackupSpec + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.FullBackupSpec; + + /** + * Creates a plain object from a FullBackupSpec message. Also converts values to other types if specified. + * @param message FullBackupSpec + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.FullBackupSpec, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FullBackupSpec to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FullBackupSpec + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an IncrementalBackupSpec. */ + interface IIncrementalBackupSpec { + } + + /** Represents an IncrementalBackupSpec. */ + class IncrementalBackupSpec implements IIncrementalBackupSpec { + + /** + * Constructs a new IncrementalBackupSpec. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IIncrementalBackupSpec); + + /** + * Creates a new IncrementalBackupSpec instance using the specified properties. + * @param [properties] Properties to set + * @returns IncrementalBackupSpec instance + */ + public static create(properties?: google.spanner.admin.database.v1.IIncrementalBackupSpec): google.spanner.admin.database.v1.IncrementalBackupSpec; + + /** + * Encodes the specified IncrementalBackupSpec message. Does not implicitly {@link google.spanner.admin.database.v1.IncrementalBackupSpec.verify|verify} messages. + * @param message IncrementalBackupSpec message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IIncrementalBackupSpec, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified IncrementalBackupSpec message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.IncrementalBackupSpec.verify|verify} messages. + * @param message IncrementalBackupSpec message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IIncrementalBackupSpec, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an IncrementalBackupSpec message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns IncrementalBackupSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.IncrementalBackupSpec; + + /** + * Decodes an IncrementalBackupSpec message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns IncrementalBackupSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.IncrementalBackupSpec; + + /** + * Verifies an IncrementalBackupSpec message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an IncrementalBackupSpec message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IncrementalBackupSpec + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.IncrementalBackupSpec; + + /** + * Creates a plain object from an IncrementalBackupSpec message. Also converts values to other types if specified. + * @param message IncrementalBackupSpec + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.IncrementalBackupSpec, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IncrementalBackupSpec to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IncrementalBackupSpec + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BackupInstancePartition. */ + interface IBackupInstancePartition { + + /** BackupInstancePartition instancePartition */ + instancePartition?: (string|null); + } + + /** Represents a BackupInstancePartition. */ + class BackupInstancePartition implements IBackupInstancePartition { + + /** + * Constructs a new BackupInstancePartition. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IBackupInstancePartition); + + /** BackupInstancePartition instancePartition. */ + public instancePartition: string; + + /** + * Creates a new BackupInstancePartition instance using the specified properties. + * @param [properties] Properties to set + * @returns BackupInstancePartition instance + */ + public static create(properties?: google.spanner.admin.database.v1.IBackupInstancePartition): google.spanner.admin.database.v1.BackupInstancePartition; + + /** + * Encodes the specified BackupInstancePartition message. Does not implicitly {@link google.spanner.admin.database.v1.BackupInstancePartition.verify|verify} messages. + * @param message BackupInstancePartition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IBackupInstancePartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BackupInstancePartition message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupInstancePartition.verify|verify} messages. + * @param message BackupInstancePartition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IBackupInstancePartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BackupInstancePartition message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BackupInstancePartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.BackupInstancePartition; + + /** + * Decodes a BackupInstancePartition message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BackupInstancePartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.BackupInstancePartition; + + /** + * Verifies a BackupInstancePartition message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BackupInstancePartition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupInstancePartition + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.BackupInstancePartition; + + /** + * Creates a plain object from a BackupInstancePartition message. Also converts values to other types if specified. + * @param message BackupInstancePartition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.BackupInstancePartition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupInstancePartition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupInstancePartition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationProgress. */ + interface IOperationProgress { + + /** OperationProgress progressPercent */ + progressPercent?: (number|null); + + /** OperationProgress startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** OperationProgress endTime */ + endTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an OperationProgress. */ + class OperationProgress implements IOperationProgress { + + /** + * Constructs a new OperationProgress. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IOperationProgress); + + /** OperationProgress progressPercent. */ + public progressPercent: number; + + /** OperationProgress startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** OperationProgress endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new OperationProgress instance using the specified properties. + * @param [properties] Properties to set + * @returns OperationProgress instance + */ + public static create(properties?: google.spanner.admin.database.v1.IOperationProgress): google.spanner.admin.database.v1.OperationProgress; + + /** + * Encodes the specified OperationProgress message. Does not implicitly {@link google.spanner.admin.database.v1.OperationProgress.verify|verify} messages. + * @param message OperationProgress message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IOperationProgress, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OperationProgress message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.OperationProgress.verify|verify} messages. + * @param message OperationProgress message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IOperationProgress, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OperationProgress message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OperationProgress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.OperationProgress; + + /** + * Decodes an OperationProgress message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OperationProgress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.OperationProgress; + + /** + * Verifies an OperationProgress message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OperationProgress message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationProgress + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.OperationProgress; + + /** + * Creates a plain object from an OperationProgress message. Also converts values to other types if specified. + * @param message OperationProgress + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.OperationProgress, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationProgress to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationProgress + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EncryptionConfig. */ + interface IEncryptionConfig { + + /** EncryptionConfig kmsKeyName */ + kmsKeyName?: (string|null); + + /** EncryptionConfig kmsKeyNames */ + kmsKeyNames?: (string[]|null); + } + + /** Represents an EncryptionConfig. */ + class EncryptionConfig implements IEncryptionConfig { + + /** + * Constructs a new EncryptionConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IEncryptionConfig); + + /** EncryptionConfig kmsKeyName. */ + public kmsKeyName: string; + + /** EncryptionConfig kmsKeyNames. */ + public kmsKeyNames: string[]; + + /** + * Creates a new EncryptionConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns EncryptionConfig instance + */ + public static create(properties?: google.spanner.admin.database.v1.IEncryptionConfig): google.spanner.admin.database.v1.EncryptionConfig; + + /** + * Encodes the specified EncryptionConfig message. Does not implicitly {@link google.spanner.admin.database.v1.EncryptionConfig.verify|verify} messages. + * @param message EncryptionConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IEncryptionConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EncryptionConfig message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.EncryptionConfig.verify|verify} messages. + * @param message EncryptionConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IEncryptionConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EncryptionConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.EncryptionConfig; + + /** + * Decodes an EncryptionConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.EncryptionConfig; + + /** + * Verifies an EncryptionConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EncryptionConfig + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.EncryptionConfig; + + /** + * Creates a plain object from an EncryptionConfig message. Also converts values to other types if specified. + * @param message EncryptionConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.EncryptionConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EncryptionConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EncryptionConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EncryptionInfo. */ + interface IEncryptionInfo { + + /** EncryptionInfo encryptionType */ + encryptionType?: (google.spanner.admin.database.v1.EncryptionInfo.Type|keyof typeof google.spanner.admin.database.v1.EncryptionInfo.Type|null); + + /** EncryptionInfo encryptionStatus */ + encryptionStatus?: (google.rpc.IStatus|null); + + /** EncryptionInfo kmsKeyVersion */ + kmsKeyVersion?: (string|null); + } + + /** Represents an EncryptionInfo. */ + class EncryptionInfo implements IEncryptionInfo { + + /** + * Constructs a new EncryptionInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IEncryptionInfo); + + /** EncryptionInfo encryptionType. */ + public encryptionType: (google.spanner.admin.database.v1.EncryptionInfo.Type|keyof typeof google.spanner.admin.database.v1.EncryptionInfo.Type); + + /** EncryptionInfo encryptionStatus. */ + public encryptionStatus?: (google.rpc.IStatus|null); + + /** EncryptionInfo kmsKeyVersion. */ + public kmsKeyVersion: string; + + /** + * Creates a new EncryptionInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns EncryptionInfo instance + */ + public static create(properties?: google.spanner.admin.database.v1.IEncryptionInfo): google.spanner.admin.database.v1.EncryptionInfo; + + /** + * Encodes the specified EncryptionInfo message. Does not implicitly {@link google.spanner.admin.database.v1.EncryptionInfo.verify|verify} messages. + * @param message EncryptionInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IEncryptionInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified EncryptionInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.EncryptionInfo.verify|verify} messages. + * @param message EncryptionInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IEncryptionInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an EncryptionInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns EncryptionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.EncryptionInfo; + + /** + * Decodes an EncryptionInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns EncryptionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.EncryptionInfo; + + /** + * Verifies an EncryptionInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an EncryptionInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EncryptionInfo + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.EncryptionInfo; + + /** + * Creates a plain object from an EncryptionInfo message. Also converts values to other types if specified. + * @param message EncryptionInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.EncryptionInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EncryptionInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EncryptionInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EncryptionInfo { + + /** Type enum. */ + enum Type { + TYPE_UNSPECIFIED = 0, + GOOGLE_DEFAULT_ENCRYPTION = 1, + CUSTOMER_MANAGED_ENCRYPTION = 2 + } + } + + /** DatabaseDialect enum. */ + enum DatabaseDialect { + DATABASE_DIALECT_UNSPECIFIED = 0, + GOOGLE_STANDARD_SQL = 1, + POSTGRESQL = 2 + } + + /** Properties of a BackupScheduleSpec. */ + interface IBackupScheduleSpec { + + /** BackupScheduleSpec cronSpec */ + cronSpec?: (google.spanner.admin.database.v1.ICrontabSpec|null); + } + + /** Represents a BackupScheduleSpec. */ + class BackupScheduleSpec implements IBackupScheduleSpec { + + /** + * Constructs a new BackupScheduleSpec. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IBackupScheduleSpec); + + /** BackupScheduleSpec cronSpec. */ + public cronSpec?: (google.spanner.admin.database.v1.ICrontabSpec|null); + + /** BackupScheduleSpec scheduleSpec. */ + public scheduleSpec?: "cronSpec"; + + /** + * Creates a new BackupScheduleSpec instance using the specified properties. + * @param [properties] Properties to set + * @returns BackupScheduleSpec instance + */ + public static create(properties?: google.spanner.admin.database.v1.IBackupScheduleSpec): google.spanner.admin.database.v1.BackupScheduleSpec; + + /** + * Encodes the specified BackupScheduleSpec message. Does not implicitly {@link google.spanner.admin.database.v1.BackupScheduleSpec.verify|verify} messages. + * @param message BackupScheduleSpec message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IBackupScheduleSpec, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BackupScheduleSpec message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupScheduleSpec.verify|verify} messages. + * @param message BackupScheduleSpec message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IBackupScheduleSpec, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BackupScheduleSpec message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BackupScheduleSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.BackupScheduleSpec; + + /** + * Decodes a BackupScheduleSpec message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BackupScheduleSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.BackupScheduleSpec; + + /** + * Verifies a BackupScheduleSpec message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BackupScheduleSpec message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupScheduleSpec + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.BackupScheduleSpec; + + /** + * Creates a plain object from a BackupScheduleSpec message. Also converts values to other types if specified. + * @param message BackupScheduleSpec + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.BackupScheduleSpec, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupScheduleSpec to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupScheduleSpec + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BackupSchedule. */ + interface IBackupSchedule { + + /** BackupSchedule name */ + name?: (string|null); + + /** BackupSchedule spec */ + spec?: (google.spanner.admin.database.v1.IBackupScheduleSpec|null); + + /** BackupSchedule retentionDuration */ + retentionDuration?: (google.protobuf.IDuration|null); + + /** BackupSchedule encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.ICreateBackupEncryptionConfig|null); + + /** BackupSchedule fullBackupSpec */ + fullBackupSpec?: (google.spanner.admin.database.v1.IFullBackupSpec|null); + + /** BackupSchedule incrementalBackupSpec */ + incrementalBackupSpec?: (google.spanner.admin.database.v1.IIncrementalBackupSpec|null); + + /** BackupSchedule updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BackupSchedule. */ + class BackupSchedule implements IBackupSchedule { + + /** + * Constructs a new BackupSchedule. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IBackupSchedule); + + /** BackupSchedule name. */ + public name: string; + + /** BackupSchedule spec. */ + public spec?: (google.spanner.admin.database.v1.IBackupScheduleSpec|null); + + /** BackupSchedule retentionDuration. */ + public retentionDuration?: (google.protobuf.IDuration|null); + + /** BackupSchedule encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.ICreateBackupEncryptionConfig|null); + + /** BackupSchedule fullBackupSpec. */ + public fullBackupSpec?: (google.spanner.admin.database.v1.IFullBackupSpec|null); + + /** BackupSchedule incrementalBackupSpec. */ + public incrementalBackupSpec?: (google.spanner.admin.database.v1.IIncrementalBackupSpec|null); + + /** BackupSchedule updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule backupTypeSpec. */ + public backupTypeSpec?: ("fullBackupSpec"|"incrementalBackupSpec"); + + /** + * Creates a new BackupSchedule instance using the specified properties. + * @param [properties] Properties to set + * @returns BackupSchedule instance + */ + public static create(properties?: google.spanner.admin.database.v1.IBackupSchedule): google.spanner.admin.database.v1.BackupSchedule; + + /** + * Encodes the specified BackupSchedule message. Does not implicitly {@link google.spanner.admin.database.v1.BackupSchedule.verify|verify} messages. + * @param message BackupSchedule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IBackupSchedule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BackupSchedule message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupSchedule.verify|verify} messages. + * @param message BackupSchedule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IBackupSchedule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BackupSchedule message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BackupSchedule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.BackupSchedule; + + /** + * Decodes a BackupSchedule message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BackupSchedule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.BackupSchedule; + + /** + * Verifies a BackupSchedule message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BackupSchedule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackupSchedule + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.BackupSchedule; + + /** + * Creates a plain object from a BackupSchedule message. Also converts values to other types if specified. + * @param message BackupSchedule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.BackupSchedule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackupSchedule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackupSchedule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CrontabSpec. */ + interface ICrontabSpec { + + /** CrontabSpec text */ + text?: (string|null); + + /** CrontabSpec timeZone */ + timeZone?: (string|null); + + /** CrontabSpec creationWindow */ + creationWindow?: (google.protobuf.IDuration|null); + } + + /** Represents a CrontabSpec. */ + class CrontabSpec implements ICrontabSpec { + + /** + * Constructs a new CrontabSpec. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICrontabSpec); + + /** CrontabSpec text. */ + public text: string; + + /** CrontabSpec timeZone. */ + public timeZone: string; + + /** CrontabSpec creationWindow. */ + public creationWindow?: (google.protobuf.IDuration|null); + + /** + * Creates a new CrontabSpec instance using the specified properties. + * @param [properties] Properties to set + * @returns CrontabSpec instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICrontabSpec): google.spanner.admin.database.v1.CrontabSpec; + + /** + * Encodes the specified CrontabSpec message. Does not implicitly {@link google.spanner.admin.database.v1.CrontabSpec.verify|verify} messages. + * @param message CrontabSpec message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICrontabSpec, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CrontabSpec message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CrontabSpec.verify|verify} messages. + * @param message CrontabSpec message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICrontabSpec, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CrontabSpec message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CrontabSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CrontabSpec; + + /** + * Decodes a CrontabSpec message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CrontabSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CrontabSpec; + + /** + * Verifies a CrontabSpec message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CrontabSpec message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CrontabSpec + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CrontabSpec; + + /** + * Creates a plain object from a CrontabSpec message. Also converts values to other types if specified. + * @param message CrontabSpec + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CrontabSpec, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CrontabSpec to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CrontabSpec + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateBackupScheduleRequest. */ + interface ICreateBackupScheduleRequest { + + /** CreateBackupScheduleRequest parent */ + parent?: (string|null); + + /** CreateBackupScheduleRequest backupScheduleId */ + backupScheduleId?: (string|null); + + /** CreateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.spanner.admin.database.v1.IBackupSchedule|null); + } + + /** Represents a CreateBackupScheduleRequest. */ + class CreateBackupScheduleRequest implements ICreateBackupScheduleRequest { + + /** + * Constructs a new CreateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICreateBackupScheduleRequest); + + /** CreateBackupScheduleRequest parent. */ + public parent: string; + + /** CreateBackupScheduleRequest backupScheduleId. */ + public backupScheduleId: string; + + /** CreateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.spanner.admin.database.v1.IBackupSchedule|null); + + /** + * Creates a new CreateBackupScheduleRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateBackupScheduleRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICreateBackupScheduleRequest): google.spanner.admin.database.v1.CreateBackupScheduleRequest; + + /** + * Encodes the specified CreateBackupScheduleRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupScheduleRequest.verify|verify} messages. + * @param message CreateBackupScheduleRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICreateBackupScheduleRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateBackupScheduleRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupScheduleRequest.verify|verify} messages. + * @param message CreateBackupScheduleRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateBackupScheduleRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateBackupScheduleRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateBackupScheduleRequest; + + /** + * Decodes a CreateBackupScheduleRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateBackupScheduleRequest; + + /** + * Verifies a CreateBackupScheduleRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateBackupScheduleRequest; + + /** + * Creates a plain object from a CreateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message CreateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CreateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupScheduleRequest. */ + interface IGetBackupScheduleRequest { + + /** GetBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupScheduleRequest. */ + class GetBackupScheduleRequest implements IGetBackupScheduleRequest { + + /** + * Constructs a new GetBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IGetBackupScheduleRequest); + + /** GetBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a new GetBackupScheduleRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetBackupScheduleRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IGetBackupScheduleRequest): google.spanner.admin.database.v1.GetBackupScheduleRequest; + + /** + * Encodes the specified GetBackupScheduleRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupScheduleRequest.verify|verify} messages. + * @param message GetBackupScheduleRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IGetBackupScheduleRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetBackupScheduleRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupScheduleRequest.verify|verify} messages. + * @param message GetBackupScheduleRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IGetBackupScheduleRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetBackupScheduleRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetBackupScheduleRequest; + + /** + * Decodes a GetBackupScheduleRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetBackupScheduleRequest; + + /** + * Verifies a GetBackupScheduleRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetBackupScheduleRequest; + + /** + * Creates a plain object from a GetBackupScheduleRequest message. Also converts values to other types if specified. + * @param message GetBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.GetBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupScheduleRequest. */ + interface IDeleteBackupScheduleRequest { + + /** DeleteBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupScheduleRequest. */ + class DeleteBackupScheduleRequest implements IDeleteBackupScheduleRequest { + + /** + * Constructs a new DeleteBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IDeleteBackupScheduleRequest); + + /** DeleteBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a new DeleteBackupScheduleRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteBackupScheduleRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IDeleteBackupScheduleRequest): google.spanner.admin.database.v1.DeleteBackupScheduleRequest; + + /** + * Encodes the specified DeleteBackupScheduleRequest message. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupScheduleRequest.verify|verify} messages. + * @param message DeleteBackupScheduleRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IDeleteBackupScheduleRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteBackupScheduleRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupScheduleRequest.verify|verify} messages. + * @param message DeleteBackupScheduleRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IDeleteBackupScheduleRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteBackupScheduleRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.DeleteBackupScheduleRequest; + + /** + * Decodes a DeleteBackupScheduleRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.DeleteBackupScheduleRequest; + + /** + * Verifies a DeleteBackupScheduleRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.DeleteBackupScheduleRequest; + + /** + * Creates a plain object from a DeleteBackupScheduleRequest message. Also converts values to other types if specified. + * @param message DeleteBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.DeleteBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesRequest. */ + interface IListBackupSchedulesRequest { + + /** ListBackupSchedulesRequest parent */ + parent?: (string|null); + + /** ListBackupSchedulesRequest pageSize */ + pageSize?: (number|null); + + /** ListBackupSchedulesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListBackupSchedulesRequest. */ + class ListBackupSchedulesRequest implements IListBackupSchedulesRequest { + + /** + * Constructs a new ListBackupSchedulesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListBackupSchedulesRequest); + + /** ListBackupSchedulesRequest parent. */ + public parent: string; + + /** ListBackupSchedulesRequest pageSize. */ + public pageSize: number; + + /** ListBackupSchedulesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListBackupSchedulesRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListBackupSchedulesRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListBackupSchedulesRequest): google.spanner.admin.database.v1.ListBackupSchedulesRequest; + + /** + * Encodes the specified ListBackupSchedulesRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupSchedulesRequest.verify|verify} messages. + * @param message ListBackupSchedulesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListBackupSchedulesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListBackupSchedulesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupSchedulesRequest.verify|verify} messages. + * @param message ListBackupSchedulesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupSchedulesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListBackupSchedulesRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListBackupSchedulesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupSchedulesRequest; + + /** + * Decodes a ListBackupSchedulesRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListBackupSchedulesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupSchedulesRequest; + + /** + * Verifies a ListBackupSchedulesRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListBackupSchedulesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupSchedulesRequest; + + /** + * Creates a plain object from a ListBackupSchedulesRequest message. Also converts values to other types if specified. + * @param message ListBackupSchedulesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListBackupSchedulesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesResponse. */ + interface IListBackupSchedulesResponse { + + /** ListBackupSchedulesResponse backupSchedules */ + backupSchedules?: (google.spanner.admin.database.v1.IBackupSchedule[]|null); + + /** ListBackupSchedulesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListBackupSchedulesResponse. */ + class ListBackupSchedulesResponse implements IListBackupSchedulesResponse { + + /** + * Constructs a new ListBackupSchedulesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListBackupSchedulesResponse); + + /** ListBackupSchedulesResponse backupSchedules. */ + public backupSchedules: google.spanner.admin.database.v1.IBackupSchedule[]; + + /** ListBackupSchedulesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListBackupSchedulesResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListBackupSchedulesResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListBackupSchedulesResponse): google.spanner.admin.database.v1.ListBackupSchedulesResponse; + + /** + * Encodes the specified ListBackupSchedulesResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupSchedulesResponse.verify|verify} messages. + * @param message ListBackupSchedulesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListBackupSchedulesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListBackupSchedulesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupSchedulesResponse.verify|verify} messages. + * @param message ListBackupSchedulesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupSchedulesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListBackupSchedulesResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListBackupSchedulesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupSchedulesResponse; + + /** + * Decodes a ListBackupSchedulesResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListBackupSchedulesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupSchedulesResponse; + + /** + * Verifies a ListBackupSchedulesResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListBackupSchedulesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupSchedulesResponse; + + /** + * Creates a plain object from a ListBackupSchedulesResponse message. Also converts values to other types if specified. + * @param message ListBackupSchedulesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListBackupSchedulesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateBackupScheduleRequest. */ + interface IUpdateBackupScheduleRequest { + + /** UpdateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.spanner.admin.database.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateBackupScheduleRequest. */ + class UpdateBackupScheduleRequest implements IUpdateBackupScheduleRequest { + + /** + * Constructs a new UpdateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IUpdateBackupScheduleRequest); + + /** UpdateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.spanner.admin.database.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new UpdateBackupScheduleRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateBackupScheduleRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IUpdateBackupScheduleRequest): google.spanner.admin.database.v1.UpdateBackupScheduleRequest; + + /** + * Encodes the specified UpdateBackupScheduleRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupScheduleRequest.verify|verify} messages. + * @param message UpdateBackupScheduleRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IUpdateBackupScheduleRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateBackupScheduleRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupScheduleRequest.verify|verify} messages. + * @param message UpdateBackupScheduleRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateBackupScheduleRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateBackupScheduleRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateBackupScheduleRequest; + + /** + * Decodes an UpdateBackupScheduleRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateBackupScheduleRequest; + + /** + * Verifies an UpdateBackupScheduleRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateBackupScheduleRequest; + + /** + * Creates a plain object from an UpdateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message UpdateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.UpdateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents a DatabaseAdmin */ + class DatabaseAdmin extends $protobuf.rpc.Service { + + /** + * Constructs a new DatabaseAdmin service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new DatabaseAdmin service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): DatabaseAdmin; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDatabasesResponse + */ + public listDatabases(request: google.spanner.admin.database.v1.IListDatabasesRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListDatabasesCallback): void; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @returns Promise + */ + public listDatabases(request: google.spanner.admin.database.v1.IListDatabasesRequest): Promise; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createDatabase(request: google.spanner.admin.database.v1.ICreateDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabaseCallback): void; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @returns Promise + */ + public createDatabase(request: google.spanner.admin.database.v1.ICreateDatabaseRequest): Promise; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Database + */ + public getDatabase(request: google.spanner.admin.database.v1.IGetDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseCallback): void; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @returns Promise + */ + public getDatabase(request: google.spanner.admin.database.v1.IGetDatabaseRequest): Promise; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateDatabase(request: google.spanner.admin.database.v1.IUpdateDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseCallback): void; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @returns Promise + */ + public updateDatabase(request: google.spanner.admin.database.v1.IUpdateDatabaseRequest): Promise; + + /** + * Calls UpdateDatabaseDdl. + * @param request UpdateDatabaseDdlRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateDatabaseDdl(request: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdlCallback): void; + + /** + * Calls UpdateDatabaseDdl. + * @param request UpdateDatabaseDdlRequest message or plain object + * @returns Promise + */ + public updateDatabaseDdl(request: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest): Promise; + + /** + * Calls DropDatabase. + * @param request DropDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public dropDatabase(request: google.spanner.admin.database.v1.IDropDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.DropDatabaseCallback): void; + + /** + * Calls DropDatabase. + * @param request DropDatabaseRequest message or plain object + * @returns Promise + */ + public dropDatabase(request: google.spanner.admin.database.v1.IDropDatabaseRequest): Promise; + + /** + * Calls GetDatabaseDdl. + * @param request GetDatabaseDdlRequest message or plain object + * @param callback Node-style callback called with the error, if any, and GetDatabaseDdlResponse + */ + public getDatabaseDdl(request: google.spanner.admin.database.v1.IGetDatabaseDdlRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdlCallback): void; + + /** + * Calls GetDatabaseDdl. + * @param request GetDatabaseDdlRequest message or plain object + * @returns Promise + */ + public getDatabaseDdl(request: google.spanner.admin.database.v1.IGetDatabaseDdlRequest): Promise; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.SetIamPolicyCallback): void; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRequest message or plain object + * @returns Promise + */ + public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest): Promise; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetIamPolicyCallback): void; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRequest message or plain object + * @returns Promise + */ + public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest): Promise; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and TestIamPermissionsResponse + */ + public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.TestIamPermissionsCallback): void; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRequest message or plain object + * @returns Promise + */ + public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest): Promise; + + /** + * Calls CreateBackup. + * @param request CreateBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createBackup(request: google.spanner.admin.database.v1.ICreateBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.CreateBackupCallback): void; + + /** + * Calls CreateBackup. + * @param request CreateBackupRequest message or plain object + * @returns Promise + */ + public createBackup(request: google.spanner.admin.database.v1.ICreateBackupRequest): Promise; + + /** + * Calls CopyBackup. + * @param request CopyBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public copyBackup(request: google.spanner.admin.database.v1.ICopyBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.CopyBackupCallback): void; + + /** + * Calls CopyBackup. + * @param request CopyBackupRequest message or plain object + * @returns Promise + */ + public copyBackup(request: google.spanner.admin.database.v1.ICopyBackupRequest): Promise; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Backup + */ + public getBackup(request: google.spanner.admin.database.v1.IGetBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetBackupCallback): void; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @returns Promise + */ + public getBackup(request: google.spanner.admin.database.v1.IGetBackupRequest): Promise; + + /** + * Calls UpdateBackup. + * @param request UpdateBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Backup + */ + public updateBackup(request: google.spanner.admin.database.v1.IUpdateBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackupCallback): void; + + /** + * Calls UpdateBackup. + * @param request UpdateBackupRequest message or plain object + * @returns Promise + */ + public updateBackup(request: google.spanner.admin.database.v1.IUpdateBackupRequest): Promise; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackup(request: google.spanner.admin.database.v1.IDeleteBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.DeleteBackupCallback): void; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @returns Promise + */ + public deleteBackup(request: google.spanner.admin.database.v1.IDeleteBackupRequest): Promise; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupsResponse + */ + public listBackups(request: google.spanner.admin.database.v1.IListBackupsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListBackupsCallback): void; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @returns Promise + */ + public listBackups(request: google.spanner.admin.database.v1.IListBackupsRequest): Promise; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public restoreDatabase(request: google.spanner.admin.database.v1.IRestoreDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.RestoreDatabaseCallback): void; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @returns Promise + */ + public restoreDatabase(request: google.spanner.admin.database.v1.IRestoreDatabaseRequest): Promise; + + /** + * Calls ListDatabaseOperations. + * @param request ListDatabaseOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDatabaseOperationsResponse + */ + public listDatabaseOperations(request: google.spanner.admin.database.v1.IListDatabaseOperationsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseOperationsCallback): void; + + /** + * Calls ListDatabaseOperations. + * @param request ListDatabaseOperationsRequest message or plain object + * @returns Promise + */ + public listDatabaseOperations(request: google.spanner.admin.database.v1.IListDatabaseOperationsRequest): Promise; + + /** + * Calls ListBackupOperations. + * @param request ListBackupOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupOperationsResponse + */ + public listBackupOperations(request: google.spanner.admin.database.v1.IListBackupOperationsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListBackupOperationsCallback): void; + + /** + * Calls ListBackupOperations. + * @param request ListBackupOperationsRequest message or plain object + * @returns Promise + */ + public listBackupOperations(request: google.spanner.admin.database.v1.IListBackupOperationsRequest): Promise; + + /** + * Calls ListDatabaseRoles. + * @param request ListDatabaseRolesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDatabaseRolesResponse + */ + public listDatabaseRoles(request: google.spanner.admin.database.v1.IListDatabaseRolesRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseRolesCallback): void; + + /** + * Calls ListDatabaseRoles. + * @param request ListDatabaseRolesRequest message or plain object + * @returns Promise + */ + public listDatabaseRoles(request: google.spanner.admin.database.v1.IListDatabaseRolesRequest): Promise; + + /** + * Calls AddSplitPoints. + * @param request AddSplitPointsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and AddSplitPointsResponse + */ + public addSplitPoints(request: google.spanner.admin.database.v1.IAddSplitPointsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.AddSplitPointsCallback): void; + + /** + * Calls AddSplitPoints. + * @param request AddSplitPointsRequest message or plain object + * @returns Promise + */ + public addSplitPoints(request: google.spanner.admin.database.v1.IAddSplitPointsRequest): Promise; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public createBackupSchedule(request: google.spanner.admin.database.v1.ICreateBackupScheduleRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.CreateBackupScheduleCallback): void; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @returns Promise + */ + public createBackupSchedule(request: google.spanner.admin.database.v1.ICreateBackupScheduleRequest): Promise; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public getBackupSchedule(request: google.spanner.admin.database.v1.IGetBackupScheduleRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetBackupScheduleCallback): void; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @returns Promise + */ + public getBackupSchedule(request: google.spanner.admin.database.v1.IGetBackupScheduleRequest): Promise; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public updateBackupSchedule(request: google.spanner.admin.database.v1.IUpdateBackupScheduleRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackupScheduleCallback): void; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @returns Promise + */ + public updateBackupSchedule(request: google.spanner.admin.database.v1.IUpdateBackupScheduleRequest): Promise; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackupSchedule(request: google.spanner.admin.database.v1.IDeleteBackupScheduleRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.DeleteBackupScheduleCallback): void; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @returns Promise + */ + public deleteBackupSchedule(request: google.spanner.admin.database.v1.IDeleteBackupScheduleRequest): Promise; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupSchedulesResponse + */ + public listBackupSchedules(request: google.spanner.admin.database.v1.IListBackupSchedulesRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListBackupSchedulesCallback): void; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @returns Promise + */ + public listBackupSchedules(request: google.spanner.admin.database.v1.IListBackupSchedulesRequest): Promise; + + /** + * Calls InternalUpdateGraphOperation. + * @param request InternalUpdateGraphOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and InternalUpdateGraphOperationResponse + */ + public internalUpdateGraphOperation(request: google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.InternalUpdateGraphOperationCallback): void; + + /** + * Calls InternalUpdateGraphOperation. + * @param request InternalUpdateGraphOperationRequest message or plain object + * @returns Promise + */ + public internalUpdateGraphOperation(request: google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest): Promise; + } + + namespace DatabaseAdmin { + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listDatabases}. + * @param error Error, if any + * @param [response] ListDatabasesResponse + */ + type ListDatabasesCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListDatabasesResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|createDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getDatabase}. + * @param error Error, if any + * @param [response] Database + */ + type GetDatabaseCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.Database) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|updateDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|updateDatabaseDdl}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateDatabaseDdlCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|dropDatabase}. + * @param error Error, if any + * @param [response] Empty + */ + type DropDatabaseCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getDatabaseDdl}. + * @param error Error, if any + * @param [response] GetDatabaseDdlResponse + */ + type GetDatabaseDdlCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.GetDatabaseDdlResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|setIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type SetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type GetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|testIamPermissions}. + * @param error Error, if any + * @param [response] TestIamPermissionsResponse + */ + type TestIamPermissionsCallback = (error: (Error|null), response?: google.iam.v1.TestIamPermissionsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|createBackup}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateBackupCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|copyBackup}. + * @param error Error, if any + * @param [response] Operation + */ + type CopyBackupCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getBackup}. + * @param error Error, if any + * @param [response] Backup + */ + type GetBackupCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.Backup) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|updateBackup}. + * @param error Error, if any + * @param [response] Backup + */ + type UpdateBackupCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.Backup) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|deleteBackup}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listBackups}. + * @param error Error, if any + * @param [response] ListBackupsResponse + */ + type ListBackupsCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListBackupsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|restoreDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type RestoreDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listDatabaseOperations}. + * @param error Error, if any + * @param [response] ListDatabaseOperationsResponse + */ + type ListDatabaseOperationsCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListDatabaseOperationsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listBackupOperations}. + * @param error Error, if any + * @param [response] ListBackupOperationsResponse + */ + type ListBackupOperationsCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListBackupOperationsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listDatabaseRoles}. + * @param error Error, if any + * @param [response] ListDatabaseRolesResponse + */ + type ListDatabaseRolesCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListDatabaseRolesResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|addSplitPoints}. + * @param error Error, if any + * @param [response] AddSplitPointsResponse + */ + type AddSplitPointsCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.AddSplitPointsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|createBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type CreateBackupScheduleCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type GetBackupScheduleCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|updateBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type UpdateBackupScheduleCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|deleteBackupSchedule}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupScheduleCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listBackupSchedules}. + * @param error Error, if any + * @param [response] ListBackupSchedulesResponse + */ + type ListBackupSchedulesCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListBackupSchedulesResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|internalUpdateGraphOperation}. + * @param error Error, if any + * @param [response] InternalUpdateGraphOperationResponse + */ + type InternalUpdateGraphOperationCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse) => void; + } + + /** Properties of a RestoreInfo. */ + interface IRestoreInfo { + + /** RestoreInfo sourceType */ + sourceType?: (google.spanner.admin.database.v1.RestoreSourceType|keyof typeof google.spanner.admin.database.v1.RestoreSourceType|null); + + /** RestoreInfo backupInfo */ + backupInfo?: (google.spanner.admin.database.v1.IBackupInfo|null); + } + + /** Represents a RestoreInfo. */ + class RestoreInfo implements IRestoreInfo { + + /** + * Constructs a new RestoreInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IRestoreInfo); + + /** RestoreInfo sourceType. */ + public sourceType: (google.spanner.admin.database.v1.RestoreSourceType|keyof typeof google.spanner.admin.database.v1.RestoreSourceType); + + /** RestoreInfo backupInfo. */ + public backupInfo?: (google.spanner.admin.database.v1.IBackupInfo|null); + + /** RestoreInfo sourceInfo. */ + public sourceInfo?: "backupInfo"; + + /** + * Creates a new RestoreInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns RestoreInfo instance + */ + public static create(properties?: google.spanner.admin.database.v1.IRestoreInfo): google.spanner.admin.database.v1.RestoreInfo; + + /** + * Encodes the specified RestoreInfo message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreInfo.verify|verify} messages. + * @param message RestoreInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IRestoreInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RestoreInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreInfo.verify|verify} messages. + * @param message RestoreInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IRestoreInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RestoreInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RestoreInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.RestoreInfo; + + /** + * Decodes a RestoreInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RestoreInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.RestoreInfo; + + /** + * Verifies a RestoreInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RestoreInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreInfo + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.RestoreInfo; + + /** + * Creates a plain object from a RestoreInfo message. Also converts values to other types if specified. + * @param message RestoreInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.RestoreInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Database. */ + interface IDatabase { + + /** Database name */ + name?: (string|null); + + /** Database state */ + state?: (google.spanner.admin.database.v1.Database.State|keyof typeof google.spanner.admin.database.v1.Database.State|null); + + /** Database createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Database restoreInfo */ + restoreInfo?: (google.spanner.admin.database.v1.IRestoreInfo|null); + + /** Database encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + + /** Database encryptionInfo */ + encryptionInfo?: (google.spanner.admin.database.v1.IEncryptionInfo[]|null); + + /** Database versionRetentionPeriod */ + versionRetentionPeriod?: (string|null); + + /** Database earliestVersionTime */ + earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database defaultLeader */ + defaultLeader?: (string|null); + + /** Database databaseDialect */ + databaseDialect?: (google.spanner.admin.database.v1.DatabaseDialect|keyof typeof google.spanner.admin.database.v1.DatabaseDialect|null); + + /** Database enableDropProtection */ + enableDropProtection?: (boolean|null); + + /** Database reconciling */ + reconciling?: (boolean|null); + } + + /** Represents a Database. */ + class Database implements IDatabase { + + /** + * Constructs a new Database. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IDatabase); + + /** Database name. */ + public name: string; + + /** Database state. */ + public state: (google.spanner.admin.database.v1.Database.State|keyof typeof google.spanner.admin.database.v1.Database.State); + + /** Database createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Database restoreInfo. */ + public restoreInfo?: (google.spanner.admin.database.v1.IRestoreInfo|null); + + /** Database encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + + /** Database encryptionInfo. */ + public encryptionInfo: google.spanner.admin.database.v1.IEncryptionInfo[]; + + /** Database versionRetentionPeriod. */ + public versionRetentionPeriod: string; + + /** Database earliestVersionTime. */ + public earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database defaultLeader. */ + public defaultLeader: string; + + /** Database databaseDialect. */ + public databaseDialect: (google.spanner.admin.database.v1.DatabaseDialect|keyof typeof google.spanner.admin.database.v1.DatabaseDialect); + + /** Database enableDropProtection. */ + public enableDropProtection: boolean; + + /** Database reconciling. */ + public reconciling: boolean; + + /** + * Creates a new Database instance using the specified properties. + * @param [properties] Properties to set + * @returns Database instance + */ + public static create(properties?: google.spanner.admin.database.v1.IDatabase): google.spanner.admin.database.v1.Database; + + /** + * Encodes the specified Database message. Does not implicitly {@link google.spanner.admin.database.v1.Database.verify|verify} messages. + * @param message Database message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IDatabase, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Database message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.Database.verify|verify} messages. + * @param message Database message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IDatabase, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Database message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Database + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.Database; + + /** + * Decodes a Database message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Database + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.Database; + + /** + * Verifies a Database message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Database message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Database + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.Database; + + /** + * Creates a plain object from a Database message. Also converts values to other types if specified. + * @param message Database + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.Database, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Database to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Database + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Database { + + /** State enum. */ + enum State { + STATE_UNSPECIFIED = 0, + CREATING = 1, + READY = 2, + READY_OPTIMIZING = 3 + } + } + + /** Properties of a ListDatabasesRequest. */ + interface IListDatabasesRequest { + + /** ListDatabasesRequest parent */ + parent?: (string|null); + + /** ListDatabasesRequest pageSize */ + pageSize?: (number|null); + + /** ListDatabasesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListDatabasesRequest. */ + class ListDatabasesRequest implements IListDatabasesRequest { + + /** + * Constructs a new ListDatabasesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListDatabasesRequest); + + /** ListDatabasesRequest parent. */ + public parent: string; + + /** ListDatabasesRequest pageSize. */ + public pageSize: number; + + /** ListDatabasesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListDatabasesRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListDatabasesRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListDatabasesRequest): google.spanner.admin.database.v1.ListDatabasesRequest; + + /** + * Encodes the specified ListDatabasesRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesRequest.verify|verify} messages. + * @param message ListDatabasesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListDatabasesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListDatabasesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesRequest.verify|verify} messages. + * @param message ListDatabasesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabasesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListDatabasesRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListDatabasesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabasesRequest; + + /** + * Decodes a ListDatabasesRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListDatabasesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabasesRequest; + + /** + * Verifies a ListDatabasesRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabasesRequest; + + /** + * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. + * @param message ListDatabasesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListDatabasesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabasesResponse. */ + interface IListDatabasesResponse { + + /** ListDatabasesResponse databases */ + databases?: (google.spanner.admin.database.v1.IDatabase[]|null); + + /** ListDatabasesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDatabasesResponse. */ + class ListDatabasesResponse implements IListDatabasesResponse { + + /** + * Constructs a new ListDatabasesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListDatabasesResponse); + + /** ListDatabasesResponse databases. */ + public databases: google.spanner.admin.database.v1.IDatabase[]; + + /** ListDatabasesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListDatabasesResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListDatabasesResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListDatabasesResponse): google.spanner.admin.database.v1.ListDatabasesResponse; + + /** + * Encodes the specified ListDatabasesResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesResponse.verify|verify} messages. + * @param message ListDatabasesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListDatabasesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListDatabasesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesResponse.verify|verify} messages. + * @param message ListDatabasesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabasesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListDatabasesResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListDatabasesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabasesResponse; + + /** + * Decodes a ListDatabasesResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListDatabasesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabasesResponse; + + /** + * Verifies a ListDatabasesResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabasesResponse; + + /** + * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. + * @param message ListDatabasesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListDatabasesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseRequest. */ + interface ICreateDatabaseRequest { + + /** CreateDatabaseRequest parent */ + parent?: (string|null); + + /** CreateDatabaseRequest createStatement */ + createStatement?: (string|null); + + /** CreateDatabaseRequest extraStatements */ + extraStatements?: (string[]|null); + + /** CreateDatabaseRequest encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + + /** CreateDatabaseRequest databaseDialect */ + databaseDialect?: (google.spanner.admin.database.v1.DatabaseDialect|keyof typeof google.spanner.admin.database.v1.DatabaseDialect|null); + + /** CreateDatabaseRequest protoDescriptors */ + protoDescriptors?: (Uint8Array|Buffer|string|null); + } + + /** Represents a CreateDatabaseRequest. */ + class CreateDatabaseRequest implements ICreateDatabaseRequest { + + /** + * Constructs a new CreateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICreateDatabaseRequest); + + /** CreateDatabaseRequest parent. */ + public parent: string; + + /** CreateDatabaseRequest createStatement. */ + public createStatement: string; + + /** CreateDatabaseRequest extraStatements. */ + public extraStatements: string[]; + + /** CreateDatabaseRequest encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + + /** CreateDatabaseRequest databaseDialect. */ + public databaseDialect: (google.spanner.admin.database.v1.DatabaseDialect|keyof typeof google.spanner.admin.database.v1.DatabaseDialect); + + /** CreateDatabaseRequest protoDescriptors. */ + public protoDescriptors: (Uint8Array|Buffer|string); + + /** + * Creates a new CreateDatabaseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateDatabaseRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICreateDatabaseRequest): google.spanner.admin.database.v1.CreateDatabaseRequest; + + /** + * Encodes the specified CreateDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseRequest.verify|verify} messages. + * @param message CreateDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICreateDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseRequest.verify|verify} messages. + * @param message CreateDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateDatabaseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateDatabaseRequest; + + /** + * Decodes a CreateDatabaseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateDatabaseRequest; + + /** + * Verifies a CreateDatabaseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateDatabaseRequest; + + /** + * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. + * @param message CreateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CreateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseMetadata. */ + interface ICreateDatabaseMetadata { + + /** CreateDatabaseMetadata database */ + database?: (string|null); + } + + /** Represents a CreateDatabaseMetadata. */ + class CreateDatabaseMetadata implements ICreateDatabaseMetadata { + + /** + * Constructs a new CreateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ICreateDatabaseMetadata); + + /** CreateDatabaseMetadata database. */ + public database: string; + + /** + * Creates a new CreateDatabaseMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateDatabaseMetadata instance + */ + public static create(properties?: google.spanner.admin.database.v1.ICreateDatabaseMetadata): google.spanner.admin.database.v1.CreateDatabaseMetadata; + + /** + * Encodes the specified CreateDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseMetadata.verify|verify} messages. + * @param message CreateDatabaseMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ICreateDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseMetadata.verify|verify} messages. + * @param message CreateDatabaseMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateDatabaseMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateDatabaseMetadata; + + /** + * Decodes a CreateDatabaseMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateDatabaseMetadata; + + /** + * Verifies a CreateDatabaseMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateDatabaseMetadata; + + /** + * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. + * @param message CreateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.CreateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetDatabaseRequest. */ + interface IGetDatabaseRequest { + + /** GetDatabaseRequest name */ + name?: (string|null); + } + + /** Represents a GetDatabaseRequest. */ + class GetDatabaseRequest implements IGetDatabaseRequest { + + /** + * Constructs a new GetDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IGetDatabaseRequest); + + /** GetDatabaseRequest name. */ + public name: string; + + /** + * Creates a new GetDatabaseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetDatabaseRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IGetDatabaseRequest): google.spanner.admin.database.v1.GetDatabaseRequest; + + /** + * Encodes the specified GetDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseRequest.verify|verify} messages. + * @param message GetDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IGetDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseRequest.verify|verify} messages. + * @param message GetDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IGetDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetDatabaseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetDatabaseRequest; + + /** + * Decodes a GetDatabaseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetDatabaseRequest; + + /** + * Verifies a GetDatabaseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetDatabaseRequest; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @param message GetDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseRequest. */ + interface IUpdateDatabaseRequest { + + /** UpdateDatabaseRequest database */ + database?: (google.spanner.admin.database.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateDatabaseRequest. */ + class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + + /** + * Constructs a new UpdateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IUpdateDatabaseRequest); + + /** UpdateDatabaseRequest database. */ + public database?: (google.spanner.admin.database.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new UpdateDatabaseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateDatabaseRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IUpdateDatabaseRequest): google.spanner.admin.database.v1.UpdateDatabaseRequest; + + /** + * Encodes the specified UpdateDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseRequest.verify|verify} messages. + * @param message UpdateDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IUpdateDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseRequest.verify|verify} messages. + * @param message UpdateDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateDatabaseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateDatabaseRequest; + + /** + * Decodes an UpdateDatabaseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateDatabaseRequest; + + /** + * Verifies an UpdateDatabaseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateDatabaseRequest; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @param message UpdateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseMetadata. */ + interface IUpdateDatabaseMetadata { + + /** UpdateDatabaseMetadata request */ + request?: (google.spanner.admin.database.v1.IUpdateDatabaseRequest|null); + + /** UpdateDatabaseMetadata progress */ + progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** UpdateDatabaseMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UpdateDatabaseMetadata. */ + class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + + /** + * Constructs a new UpdateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IUpdateDatabaseMetadata); + + /** UpdateDatabaseMetadata request. */ + public request?: (google.spanner.admin.database.v1.IUpdateDatabaseRequest|null); + + /** UpdateDatabaseMetadata progress. */ + public progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** UpdateDatabaseMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new UpdateDatabaseMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateDatabaseMetadata instance + */ + public static create(properties?: google.spanner.admin.database.v1.IUpdateDatabaseMetadata): google.spanner.admin.database.v1.UpdateDatabaseMetadata; + + /** + * Encodes the specified UpdateDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseMetadata.verify|verify} messages. + * @param message UpdateDatabaseMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IUpdateDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseMetadata.verify|verify} messages. + * @param message UpdateDatabaseMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateDatabaseMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateDatabaseMetadata; + + /** + * Decodes an UpdateDatabaseMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateDatabaseMetadata; + + /** + * Verifies an UpdateDatabaseMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateDatabaseMetadata; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @param message UpdateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseDdlRequest. */ + interface IUpdateDatabaseDdlRequest { + + /** UpdateDatabaseDdlRequest database */ + database?: (string|null); + + /** UpdateDatabaseDdlRequest statements */ + statements?: (string[]|null); + + /** UpdateDatabaseDdlRequest operationId */ + operationId?: (string|null); + + /** UpdateDatabaseDdlRequest protoDescriptors */ + protoDescriptors?: (Uint8Array|Buffer|string|null); + + /** UpdateDatabaseDdlRequest throughputMode */ + throughputMode?: (boolean|null); + } + + /** Represents an UpdateDatabaseDdlRequest. */ + class UpdateDatabaseDdlRequest implements IUpdateDatabaseDdlRequest { + + /** + * Constructs a new UpdateDatabaseDdlRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest); + + /** UpdateDatabaseDdlRequest database. */ + public database: string; + + /** UpdateDatabaseDdlRequest statements. */ + public statements: string[]; + + /** UpdateDatabaseDdlRequest operationId. */ + public operationId: string; + + /** UpdateDatabaseDdlRequest protoDescriptors. */ + public protoDescriptors: (Uint8Array|Buffer|string); + + /** UpdateDatabaseDdlRequest throughputMode. */ + public throughputMode: boolean; + + /** + * Creates a new UpdateDatabaseDdlRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateDatabaseDdlRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest): google.spanner.admin.database.v1.UpdateDatabaseDdlRequest; + + /** + * Encodes the specified UpdateDatabaseDdlRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.verify|verify} messages. + * @param message UpdateDatabaseDdlRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateDatabaseDdlRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.verify|verify} messages. + * @param message UpdateDatabaseDdlRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateDatabaseDdlRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateDatabaseDdlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateDatabaseDdlRequest; + + /** + * Decodes an UpdateDatabaseDdlRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateDatabaseDdlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateDatabaseDdlRequest; + + /** + * Verifies an UpdateDatabaseDdlRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateDatabaseDdlRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseDdlRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateDatabaseDdlRequest; + + /** + * Creates a plain object from an UpdateDatabaseDdlRequest message. Also converts values to other types if specified. + * @param message UpdateDatabaseDdlRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.UpdateDatabaseDdlRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseDdlRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseDdlRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DdlStatementActionInfo. */ + interface IDdlStatementActionInfo { + + /** DdlStatementActionInfo action */ + action?: (string|null); + + /** DdlStatementActionInfo entityType */ + entityType?: (string|null); + + /** DdlStatementActionInfo entityNames */ + entityNames?: (string[]|null); + } + + /** Represents a DdlStatementActionInfo. */ + class DdlStatementActionInfo implements IDdlStatementActionInfo { + + /** + * Constructs a new DdlStatementActionInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IDdlStatementActionInfo); + + /** DdlStatementActionInfo action. */ + public action: string; + + /** DdlStatementActionInfo entityType. */ + public entityType: string; + + /** DdlStatementActionInfo entityNames. */ + public entityNames: string[]; + + /** + * Creates a new DdlStatementActionInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns DdlStatementActionInfo instance + */ + public static create(properties?: google.spanner.admin.database.v1.IDdlStatementActionInfo): google.spanner.admin.database.v1.DdlStatementActionInfo; + + /** + * Encodes the specified DdlStatementActionInfo message. Does not implicitly {@link google.spanner.admin.database.v1.DdlStatementActionInfo.verify|verify} messages. + * @param message DdlStatementActionInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IDdlStatementActionInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DdlStatementActionInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DdlStatementActionInfo.verify|verify} messages. + * @param message DdlStatementActionInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IDdlStatementActionInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DdlStatementActionInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DdlStatementActionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.DdlStatementActionInfo; + + /** + * Decodes a DdlStatementActionInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DdlStatementActionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.DdlStatementActionInfo; + + /** + * Verifies a DdlStatementActionInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DdlStatementActionInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DdlStatementActionInfo + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.DdlStatementActionInfo; + + /** + * Creates a plain object from a DdlStatementActionInfo message. Also converts values to other types if specified. + * @param message DdlStatementActionInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.DdlStatementActionInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DdlStatementActionInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DdlStatementActionInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseDdlMetadata. */ + interface IUpdateDatabaseDdlMetadata { + + /** UpdateDatabaseDdlMetadata database */ + database?: (string|null); + + /** UpdateDatabaseDdlMetadata statements */ + statements?: (string[]|null); + + /** UpdateDatabaseDdlMetadata commitTimestamps */ + commitTimestamps?: (google.protobuf.ITimestamp[]|null); + + /** UpdateDatabaseDdlMetadata throttled */ + throttled?: (boolean|null); + + /** UpdateDatabaseDdlMetadata progress */ + progress?: (google.spanner.admin.database.v1.IOperationProgress[]|null); + + /** UpdateDatabaseDdlMetadata actions */ + actions?: (google.spanner.admin.database.v1.IDdlStatementActionInfo[]|null); + } + + /** Represents an UpdateDatabaseDdlMetadata. */ + class UpdateDatabaseDdlMetadata implements IUpdateDatabaseDdlMetadata { + + /** + * Constructs a new UpdateDatabaseDdlMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata); + + /** UpdateDatabaseDdlMetadata database. */ + public database: string; + + /** UpdateDatabaseDdlMetadata statements. */ + public statements: string[]; + + /** UpdateDatabaseDdlMetadata commitTimestamps. */ + public commitTimestamps: google.protobuf.ITimestamp[]; + + /** UpdateDatabaseDdlMetadata throttled. */ + public throttled: boolean; + + /** UpdateDatabaseDdlMetadata progress. */ + public progress: google.spanner.admin.database.v1.IOperationProgress[]; + + /** UpdateDatabaseDdlMetadata actions. */ + public actions: google.spanner.admin.database.v1.IDdlStatementActionInfo[]; + + /** + * Creates a new UpdateDatabaseDdlMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateDatabaseDdlMetadata instance + */ + public static create(properties?: google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata): google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; + + /** + * Encodes the specified UpdateDatabaseDdlMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.verify|verify} messages. + * @param message UpdateDatabaseDdlMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateDatabaseDdlMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.verify|verify} messages. + * @param message UpdateDatabaseDdlMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateDatabaseDdlMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateDatabaseDdlMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; + + /** + * Decodes an UpdateDatabaseDdlMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateDatabaseDdlMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; + + /** + * Verifies an UpdateDatabaseDdlMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateDatabaseDdlMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseDdlMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; + + /** + * Creates a plain object from an UpdateDatabaseDdlMetadata message. Also converts values to other types if specified. + * @param message UpdateDatabaseDdlMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseDdlMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseDdlMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DropDatabaseRequest. */ + interface IDropDatabaseRequest { + + /** DropDatabaseRequest database */ + database?: (string|null); + } + + /** Represents a DropDatabaseRequest. */ + class DropDatabaseRequest implements IDropDatabaseRequest { + + /** + * Constructs a new DropDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IDropDatabaseRequest); + + /** DropDatabaseRequest database. */ + public database: string; + + /** + * Creates a new DropDatabaseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DropDatabaseRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IDropDatabaseRequest): google.spanner.admin.database.v1.DropDatabaseRequest; + + /** + * Encodes the specified DropDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.DropDatabaseRequest.verify|verify} messages. + * @param message DropDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IDropDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DropDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DropDatabaseRequest.verify|verify} messages. + * @param message DropDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IDropDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DropDatabaseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DropDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.DropDatabaseRequest; + + /** + * Decodes a DropDatabaseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DropDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.DropDatabaseRequest; + + /** + * Verifies a DropDatabaseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DropDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DropDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.DropDatabaseRequest; + + /** + * Creates a plain object from a DropDatabaseRequest message. Also converts values to other types if specified. + * @param message DropDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.DropDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DropDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DropDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetDatabaseDdlRequest. */ + interface IGetDatabaseDdlRequest { + + /** GetDatabaseDdlRequest database */ + database?: (string|null); + } + + /** Represents a GetDatabaseDdlRequest. */ + class GetDatabaseDdlRequest implements IGetDatabaseDdlRequest { + + /** + * Constructs a new GetDatabaseDdlRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IGetDatabaseDdlRequest); + + /** GetDatabaseDdlRequest database. */ + public database: string; + + /** + * Creates a new GetDatabaseDdlRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetDatabaseDdlRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IGetDatabaseDdlRequest): google.spanner.admin.database.v1.GetDatabaseDdlRequest; + + /** + * Encodes the specified GetDatabaseDdlRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlRequest.verify|verify} messages. + * @param message GetDatabaseDdlRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IGetDatabaseDdlRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetDatabaseDdlRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlRequest.verify|verify} messages. + * @param message GetDatabaseDdlRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IGetDatabaseDdlRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetDatabaseDdlRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetDatabaseDdlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetDatabaseDdlRequest; + + /** + * Decodes a GetDatabaseDdlRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetDatabaseDdlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetDatabaseDdlRequest; + + /** + * Verifies a GetDatabaseDdlRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetDatabaseDdlRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseDdlRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetDatabaseDdlRequest; + + /** + * Creates a plain object from a GetDatabaseDdlRequest message. Also converts values to other types if specified. + * @param message GetDatabaseDdlRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.GetDatabaseDdlRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseDdlRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseDdlRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetDatabaseDdlResponse. */ + interface IGetDatabaseDdlResponse { + + /** GetDatabaseDdlResponse statements */ + statements?: (string[]|null); + + /** GetDatabaseDdlResponse protoDescriptors */ + protoDescriptors?: (Uint8Array|Buffer|string|null); + } + + /** Represents a GetDatabaseDdlResponse. */ + class GetDatabaseDdlResponse implements IGetDatabaseDdlResponse { + + /** + * Constructs a new GetDatabaseDdlResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IGetDatabaseDdlResponse); + + /** GetDatabaseDdlResponse statements. */ + public statements: string[]; + + /** GetDatabaseDdlResponse protoDescriptors. */ + public protoDescriptors: (Uint8Array|Buffer|string); + + /** + * Creates a new GetDatabaseDdlResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns GetDatabaseDdlResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IGetDatabaseDdlResponse): google.spanner.admin.database.v1.GetDatabaseDdlResponse; + + /** + * Encodes the specified GetDatabaseDdlResponse message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlResponse.verify|verify} messages. + * @param message GetDatabaseDdlResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IGetDatabaseDdlResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetDatabaseDdlResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlResponse.verify|verify} messages. + * @param message GetDatabaseDdlResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IGetDatabaseDdlResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetDatabaseDdlResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetDatabaseDdlResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetDatabaseDdlResponse; + + /** + * Decodes a GetDatabaseDdlResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetDatabaseDdlResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetDatabaseDdlResponse; + + /** + * Verifies a GetDatabaseDdlResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetDatabaseDdlResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseDdlResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetDatabaseDdlResponse; + + /** + * Creates a plain object from a GetDatabaseDdlResponse message. Also converts values to other types if specified. + * @param message GetDatabaseDdlResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.GetDatabaseDdlResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseDdlResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseDdlResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabaseOperationsRequest. */ + interface IListDatabaseOperationsRequest { + + /** ListDatabaseOperationsRequest parent */ + parent?: (string|null); + + /** ListDatabaseOperationsRequest filter */ + filter?: (string|null); + + /** ListDatabaseOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListDatabaseOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListDatabaseOperationsRequest. */ + class ListDatabaseOperationsRequest implements IListDatabaseOperationsRequest { + + /** + * Constructs a new ListDatabaseOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListDatabaseOperationsRequest); + + /** ListDatabaseOperationsRequest parent. */ + public parent: string; + + /** ListDatabaseOperationsRequest filter. */ + public filter: string; + + /** ListDatabaseOperationsRequest pageSize. */ + public pageSize: number; + + /** ListDatabaseOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListDatabaseOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListDatabaseOperationsRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListDatabaseOperationsRequest): google.spanner.admin.database.v1.ListDatabaseOperationsRequest; + + /** + * Encodes the specified ListDatabaseOperationsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsRequest.verify|verify} messages. + * @param message ListDatabaseOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListDatabaseOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListDatabaseOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsRequest.verify|verify} messages. + * @param message ListDatabaseOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabaseOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListDatabaseOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListDatabaseOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabaseOperationsRequest; + + /** + * Decodes a ListDatabaseOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListDatabaseOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabaseOperationsRequest; + + /** + * Verifies a ListDatabaseOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListDatabaseOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabaseOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabaseOperationsRequest; + + /** + * Creates a plain object from a ListDatabaseOperationsRequest message. Also converts values to other types if specified. + * @param message ListDatabaseOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListDatabaseOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabaseOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabaseOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabaseOperationsResponse. */ + interface IListDatabaseOperationsResponse { + + /** ListDatabaseOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListDatabaseOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDatabaseOperationsResponse. */ + class ListDatabaseOperationsResponse implements IListDatabaseOperationsResponse { + + /** + * Constructs a new ListDatabaseOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListDatabaseOperationsResponse); + + /** ListDatabaseOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListDatabaseOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListDatabaseOperationsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListDatabaseOperationsResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListDatabaseOperationsResponse): google.spanner.admin.database.v1.ListDatabaseOperationsResponse; + + /** + * Encodes the specified ListDatabaseOperationsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsResponse.verify|verify} messages. + * @param message ListDatabaseOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListDatabaseOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListDatabaseOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsResponse.verify|verify} messages. + * @param message ListDatabaseOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabaseOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListDatabaseOperationsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListDatabaseOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabaseOperationsResponse; + + /** + * Decodes a ListDatabaseOperationsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListDatabaseOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabaseOperationsResponse; + + /** + * Verifies a ListDatabaseOperationsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListDatabaseOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabaseOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabaseOperationsResponse; + + /** + * Creates a plain object from a ListDatabaseOperationsResponse message. Also converts values to other types if specified. + * @param message ListDatabaseOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListDatabaseOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabaseOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabaseOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseRequest. */ + interface IRestoreDatabaseRequest { + + /** RestoreDatabaseRequest parent */ + parent?: (string|null); + + /** RestoreDatabaseRequest databaseId */ + databaseId?: (string|null); + + /** RestoreDatabaseRequest backup */ + backup?: (string|null); + + /** RestoreDatabaseRequest encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig|null); + } + + /** Represents a RestoreDatabaseRequest. */ + class RestoreDatabaseRequest implements IRestoreDatabaseRequest { + + /** + * Constructs a new RestoreDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IRestoreDatabaseRequest); + + /** RestoreDatabaseRequest parent. */ + public parent: string; + + /** RestoreDatabaseRequest databaseId. */ + public databaseId: string; + + /** RestoreDatabaseRequest backup. */ + public backup?: (string|null); + + /** RestoreDatabaseRequest encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig|null); + + /** RestoreDatabaseRequest source. */ + public source?: "backup"; + + /** + * Creates a new RestoreDatabaseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns RestoreDatabaseRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IRestoreDatabaseRequest): google.spanner.admin.database.v1.RestoreDatabaseRequest; + + /** + * Encodes the specified RestoreDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseRequest.verify|verify} messages. + * @param message RestoreDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IRestoreDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RestoreDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseRequest.verify|verify} messages. + * @param message RestoreDatabaseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IRestoreDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RestoreDatabaseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RestoreDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.RestoreDatabaseRequest; + + /** + * Decodes a RestoreDatabaseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RestoreDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.RestoreDatabaseRequest; + + /** + * Verifies a RestoreDatabaseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.RestoreDatabaseRequest; + + /** + * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. + * @param message RestoreDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.RestoreDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreDatabaseEncryptionConfig. */ + interface IRestoreDatabaseEncryptionConfig { + + /** RestoreDatabaseEncryptionConfig encryptionType */ + encryptionType?: (google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType|keyof typeof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType|null); + + /** RestoreDatabaseEncryptionConfig kmsKeyName */ + kmsKeyName?: (string|null); + + /** RestoreDatabaseEncryptionConfig kmsKeyNames */ + kmsKeyNames?: (string[]|null); + } + + /** Represents a RestoreDatabaseEncryptionConfig. */ + class RestoreDatabaseEncryptionConfig implements IRestoreDatabaseEncryptionConfig { + + /** + * Constructs a new RestoreDatabaseEncryptionConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig); + + /** RestoreDatabaseEncryptionConfig encryptionType. */ + public encryptionType: (google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType|keyof typeof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType); + + /** RestoreDatabaseEncryptionConfig kmsKeyName. */ + public kmsKeyName: string; + + /** RestoreDatabaseEncryptionConfig kmsKeyNames. */ + public kmsKeyNames: string[]; + + /** + * Creates a new RestoreDatabaseEncryptionConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns RestoreDatabaseEncryptionConfig instance + */ + public static create(properties?: google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig): google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig; + + /** + * Encodes the specified RestoreDatabaseEncryptionConfig message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.verify|verify} messages. + * @param message RestoreDatabaseEncryptionConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RestoreDatabaseEncryptionConfig message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.verify|verify} messages. + * @param message RestoreDatabaseEncryptionConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RestoreDatabaseEncryptionConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RestoreDatabaseEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig; + + /** + * Decodes a RestoreDatabaseEncryptionConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RestoreDatabaseEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig; + + /** + * Verifies a RestoreDatabaseEncryptionConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RestoreDatabaseEncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseEncryptionConfig + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig; + + /** + * Creates a plain object from a RestoreDatabaseEncryptionConfig message. Also converts values to other types if specified. + * @param message RestoreDatabaseEncryptionConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseEncryptionConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseEncryptionConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace RestoreDatabaseEncryptionConfig { + + /** EncryptionType enum. */ + enum EncryptionType { + ENCRYPTION_TYPE_UNSPECIFIED = 0, + USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION = 1, + GOOGLE_DEFAULT_ENCRYPTION = 2, + CUSTOMER_MANAGED_ENCRYPTION = 3 + } + } + + /** Properties of a RestoreDatabaseMetadata. */ + interface IRestoreDatabaseMetadata { + + /** RestoreDatabaseMetadata name */ + name?: (string|null); + + /** RestoreDatabaseMetadata sourceType */ + sourceType?: (google.spanner.admin.database.v1.RestoreSourceType|keyof typeof google.spanner.admin.database.v1.RestoreSourceType|null); + + /** RestoreDatabaseMetadata backupInfo */ + backupInfo?: (google.spanner.admin.database.v1.IBackupInfo|null); + + /** RestoreDatabaseMetadata progress */ + progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** RestoreDatabaseMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata optimizeDatabaseOperationName */ + optimizeDatabaseOperationName?: (string|null); + } + + /** Represents a RestoreDatabaseMetadata. */ + class RestoreDatabaseMetadata implements IRestoreDatabaseMetadata { + + /** + * Constructs a new RestoreDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IRestoreDatabaseMetadata); + + /** RestoreDatabaseMetadata name. */ + public name: string; + + /** RestoreDatabaseMetadata sourceType. */ + public sourceType: (google.spanner.admin.database.v1.RestoreSourceType|keyof typeof google.spanner.admin.database.v1.RestoreSourceType); + + /** RestoreDatabaseMetadata backupInfo. */ + public backupInfo?: (google.spanner.admin.database.v1.IBackupInfo|null); + + /** RestoreDatabaseMetadata progress. */ + public progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** RestoreDatabaseMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata optimizeDatabaseOperationName. */ + public optimizeDatabaseOperationName: string; + + /** RestoreDatabaseMetadata sourceInfo. */ + public sourceInfo?: "backupInfo"; + + /** + * Creates a new RestoreDatabaseMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns RestoreDatabaseMetadata instance + */ + public static create(properties?: google.spanner.admin.database.v1.IRestoreDatabaseMetadata): google.spanner.admin.database.v1.RestoreDatabaseMetadata; + + /** + * Encodes the specified RestoreDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseMetadata.verify|verify} messages. + * @param message RestoreDatabaseMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IRestoreDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RestoreDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseMetadata.verify|verify} messages. + * @param message RestoreDatabaseMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IRestoreDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RestoreDatabaseMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RestoreDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.RestoreDatabaseMetadata; + + /** + * Decodes a RestoreDatabaseMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RestoreDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.RestoreDatabaseMetadata; + + /** + * Verifies a RestoreDatabaseMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.RestoreDatabaseMetadata; + + /** + * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. + * @param message RestoreDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.RestoreDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OptimizeRestoredDatabaseMetadata. */ + interface IOptimizeRestoredDatabaseMetadata { + + /** OptimizeRestoredDatabaseMetadata name */ + name?: (string|null); + + /** OptimizeRestoredDatabaseMetadata progress */ + progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + } + + /** Represents an OptimizeRestoredDatabaseMetadata. */ + class OptimizeRestoredDatabaseMetadata implements IOptimizeRestoredDatabaseMetadata { + + /** + * Constructs a new OptimizeRestoredDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata); + + /** OptimizeRestoredDatabaseMetadata name. */ + public name: string; + + /** OptimizeRestoredDatabaseMetadata progress. */ + public progress?: (google.spanner.admin.database.v1.IOperationProgress|null); + + /** + * Creates a new OptimizeRestoredDatabaseMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns OptimizeRestoredDatabaseMetadata instance + */ + public static create(properties?: google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata): google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata; + + /** + * Encodes the specified OptimizeRestoredDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata.verify|verify} messages. + * @param message OptimizeRestoredDatabaseMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OptimizeRestoredDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata.verify|verify} messages. + * @param message OptimizeRestoredDatabaseMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OptimizeRestoredDatabaseMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OptimizeRestoredDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata; + + /** + * Decodes an OptimizeRestoredDatabaseMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OptimizeRestoredDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata; + + /** + * Verifies an OptimizeRestoredDatabaseMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OptimizeRestoredDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OptimizeRestoredDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata; + + /** + * Creates a plain object from an OptimizeRestoredDatabaseMetadata message. Also converts values to other types if specified. + * @param message OptimizeRestoredDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OptimizeRestoredDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OptimizeRestoredDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** RestoreSourceType enum. */ + enum RestoreSourceType { + TYPE_UNSPECIFIED = 0, + BACKUP = 1 + } + + /** Properties of a DatabaseRole. */ + interface IDatabaseRole { + + /** DatabaseRole name */ + name?: (string|null); + } + + /** Represents a DatabaseRole. */ + class DatabaseRole implements IDatabaseRole { + + /** + * Constructs a new DatabaseRole. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IDatabaseRole); + + /** DatabaseRole name. */ + public name: string; + + /** + * Creates a new DatabaseRole instance using the specified properties. + * @param [properties] Properties to set + * @returns DatabaseRole instance + */ + public static create(properties?: google.spanner.admin.database.v1.IDatabaseRole): google.spanner.admin.database.v1.DatabaseRole; + + /** + * Encodes the specified DatabaseRole message. Does not implicitly {@link google.spanner.admin.database.v1.DatabaseRole.verify|verify} messages. + * @param message DatabaseRole message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IDatabaseRole, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DatabaseRole message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DatabaseRole.verify|verify} messages. + * @param message DatabaseRole message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IDatabaseRole, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DatabaseRole message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DatabaseRole + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.DatabaseRole; + + /** + * Decodes a DatabaseRole message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DatabaseRole + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.DatabaseRole; + + /** + * Verifies a DatabaseRole message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DatabaseRole message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DatabaseRole + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.DatabaseRole; + + /** + * Creates a plain object from a DatabaseRole message. Also converts values to other types if specified. + * @param message DatabaseRole + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.DatabaseRole, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DatabaseRole to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DatabaseRole + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabaseRolesRequest. */ + interface IListDatabaseRolesRequest { + + /** ListDatabaseRolesRequest parent */ + parent?: (string|null); + + /** ListDatabaseRolesRequest pageSize */ + pageSize?: (number|null); + + /** ListDatabaseRolesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListDatabaseRolesRequest. */ + class ListDatabaseRolesRequest implements IListDatabaseRolesRequest { + + /** + * Constructs a new ListDatabaseRolesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListDatabaseRolesRequest); + + /** ListDatabaseRolesRequest parent. */ + public parent: string; + + /** ListDatabaseRolesRequest pageSize. */ + public pageSize: number; + + /** ListDatabaseRolesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListDatabaseRolesRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListDatabaseRolesRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListDatabaseRolesRequest): google.spanner.admin.database.v1.ListDatabaseRolesRequest; + + /** + * Encodes the specified ListDatabaseRolesRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseRolesRequest.verify|verify} messages. + * @param message ListDatabaseRolesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListDatabaseRolesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListDatabaseRolesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseRolesRequest.verify|verify} messages. + * @param message ListDatabaseRolesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabaseRolesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListDatabaseRolesRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListDatabaseRolesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabaseRolesRequest; + + /** + * Decodes a ListDatabaseRolesRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListDatabaseRolesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabaseRolesRequest; + + /** + * Verifies a ListDatabaseRolesRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListDatabaseRolesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabaseRolesRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabaseRolesRequest; + + /** + * Creates a plain object from a ListDatabaseRolesRequest message. Also converts values to other types if specified. + * @param message ListDatabaseRolesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListDatabaseRolesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabaseRolesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabaseRolesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabaseRolesResponse. */ + interface IListDatabaseRolesResponse { + + /** ListDatabaseRolesResponse databaseRoles */ + databaseRoles?: (google.spanner.admin.database.v1.IDatabaseRole[]|null); + + /** ListDatabaseRolesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDatabaseRolesResponse. */ + class ListDatabaseRolesResponse implements IListDatabaseRolesResponse { + + /** + * Constructs a new ListDatabaseRolesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IListDatabaseRolesResponse); + + /** ListDatabaseRolesResponse databaseRoles. */ + public databaseRoles: google.spanner.admin.database.v1.IDatabaseRole[]; + + /** ListDatabaseRolesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListDatabaseRolesResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListDatabaseRolesResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IListDatabaseRolesResponse): google.spanner.admin.database.v1.ListDatabaseRolesResponse; + + /** + * Encodes the specified ListDatabaseRolesResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseRolesResponse.verify|verify} messages. + * @param message ListDatabaseRolesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IListDatabaseRolesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListDatabaseRolesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseRolesResponse.verify|verify} messages. + * @param message ListDatabaseRolesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabaseRolesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListDatabaseRolesResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListDatabaseRolesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabaseRolesResponse; + + /** + * Decodes a ListDatabaseRolesResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListDatabaseRolesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabaseRolesResponse; + + /** + * Verifies a ListDatabaseRolesResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListDatabaseRolesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabaseRolesResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabaseRolesResponse; + + /** + * Creates a plain object from a ListDatabaseRolesResponse message. Also converts values to other types if specified. + * @param message ListDatabaseRolesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.ListDatabaseRolesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabaseRolesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabaseRolesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AddSplitPointsRequest. */ + interface IAddSplitPointsRequest { + + /** AddSplitPointsRequest database */ + database?: (string|null); + + /** AddSplitPointsRequest splitPoints */ + splitPoints?: (google.spanner.admin.database.v1.ISplitPoints[]|null); + + /** AddSplitPointsRequest initiator */ + initiator?: (string|null); + } + + /** Represents an AddSplitPointsRequest. */ + class AddSplitPointsRequest implements IAddSplitPointsRequest { + + /** + * Constructs a new AddSplitPointsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IAddSplitPointsRequest); + + /** AddSplitPointsRequest database. */ + public database: string; + + /** AddSplitPointsRequest splitPoints. */ + public splitPoints: google.spanner.admin.database.v1.ISplitPoints[]; + + /** AddSplitPointsRequest initiator. */ + public initiator: string; + + /** + * Creates a new AddSplitPointsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns AddSplitPointsRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IAddSplitPointsRequest): google.spanner.admin.database.v1.AddSplitPointsRequest; + + /** + * Encodes the specified AddSplitPointsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.AddSplitPointsRequest.verify|verify} messages. + * @param message AddSplitPointsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IAddSplitPointsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AddSplitPointsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.AddSplitPointsRequest.verify|verify} messages. + * @param message AddSplitPointsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IAddSplitPointsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AddSplitPointsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AddSplitPointsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.AddSplitPointsRequest; + + /** + * Decodes an AddSplitPointsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AddSplitPointsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.AddSplitPointsRequest; + + /** + * Verifies an AddSplitPointsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AddSplitPointsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AddSplitPointsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.AddSplitPointsRequest; + + /** + * Creates a plain object from an AddSplitPointsRequest message. Also converts values to other types if specified. + * @param message AddSplitPointsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.AddSplitPointsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AddSplitPointsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AddSplitPointsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AddSplitPointsResponse. */ + interface IAddSplitPointsResponse { + } + + /** Represents an AddSplitPointsResponse. */ + class AddSplitPointsResponse implements IAddSplitPointsResponse { + + /** + * Constructs a new AddSplitPointsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IAddSplitPointsResponse); + + /** + * Creates a new AddSplitPointsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns AddSplitPointsResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IAddSplitPointsResponse): google.spanner.admin.database.v1.AddSplitPointsResponse; + + /** + * Encodes the specified AddSplitPointsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.AddSplitPointsResponse.verify|verify} messages. + * @param message AddSplitPointsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IAddSplitPointsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AddSplitPointsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.AddSplitPointsResponse.verify|verify} messages. + * @param message AddSplitPointsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IAddSplitPointsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AddSplitPointsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AddSplitPointsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.AddSplitPointsResponse; + + /** + * Decodes an AddSplitPointsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AddSplitPointsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.AddSplitPointsResponse; + + /** + * Verifies an AddSplitPointsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AddSplitPointsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AddSplitPointsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.AddSplitPointsResponse; + + /** + * Creates a plain object from an AddSplitPointsResponse message. Also converts values to other types if specified. + * @param message AddSplitPointsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.AddSplitPointsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AddSplitPointsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AddSplitPointsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SplitPoints. */ + interface ISplitPoints { + + /** SplitPoints table */ + table?: (string|null); + + /** SplitPoints index */ + index?: (string|null); + + /** SplitPoints keys */ + keys?: (google.spanner.admin.database.v1.SplitPoints.IKey[]|null); + + /** SplitPoints expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a SplitPoints. */ + class SplitPoints implements ISplitPoints { + + /** + * Constructs a new SplitPoints. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.ISplitPoints); + + /** SplitPoints table. */ + public table: string; + + /** SplitPoints index. */ + public index: string; + + /** SplitPoints keys. */ + public keys: google.spanner.admin.database.v1.SplitPoints.IKey[]; + + /** SplitPoints expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new SplitPoints instance using the specified properties. + * @param [properties] Properties to set + * @returns SplitPoints instance + */ + public static create(properties?: google.spanner.admin.database.v1.ISplitPoints): google.spanner.admin.database.v1.SplitPoints; + + /** + * Encodes the specified SplitPoints message. Does not implicitly {@link google.spanner.admin.database.v1.SplitPoints.verify|verify} messages. + * @param message SplitPoints message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.ISplitPoints, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SplitPoints message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.SplitPoints.verify|verify} messages. + * @param message SplitPoints message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.ISplitPoints, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SplitPoints message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SplitPoints + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.SplitPoints; + + /** + * Decodes a SplitPoints message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SplitPoints + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.SplitPoints; + + /** + * Verifies a SplitPoints message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SplitPoints message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SplitPoints + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.SplitPoints; + + /** + * Creates a plain object from a SplitPoints message. Also converts values to other types if specified. + * @param message SplitPoints + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.SplitPoints, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SplitPoints to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SplitPoints + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SplitPoints { + + /** Properties of a Key. */ + interface IKey { + + /** Key keyParts */ + keyParts?: (google.protobuf.IListValue|null); + } + + /** Represents a Key. */ + class Key implements IKey { + + /** + * Constructs a new Key. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.SplitPoints.IKey); + + /** Key keyParts. */ + public keyParts?: (google.protobuf.IListValue|null); + + /** + * Creates a new Key instance using the specified properties. + * @param [properties] Properties to set + * @returns Key instance + */ + public static create(properties?: google.spanner.admin.database.v1.SplitPoints.IKey): google.spanner.admin.database.v1.SplitPoints.Key; + + /** + * Encodes the specified Key message. Does not implicitly {@link google.spanner.admin.database.v1.SplitPoints.Key.verify|verify} messages. + * @param message Key message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.SplitPoints.IKey, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Key message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.SplitPoints.Key.verify|verify} messages. + * @param message Key message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.SplitPoints.IKey, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Key message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Key + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.SplitPoints.Key; + + /** + * Decodes a Key message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Key + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.SplitPoints.Key; + + /** + * Verifies a Key message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Key message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Key + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.SplitPoints.Key; + + /** + * Creates a plain object from a Key message. Also converts values to other types if specified. + * @param message Key + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.SplitPoints.Key, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Key to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Key + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an InternalUpdateGraphOperationRequest. */ + interface IInternalUpdateGraphOperationRequest { + + /** InternalUpdateGraphOperationRequest database */ + database?: (string|null); + + /** InternalUpdateGraphOperationRequest operationId */ + operationId?: (string|null); + + /** InternalUpdateGraphOperationRequest vmIdentityToken */ + vmIdentityToken?: (string|null); + + /** InternalUpdateGraphOperationRequest progress */ + progress?: (number|null); + + /** InternalUpdateGraphOperationRequest status */ + status?: (google.rpc.IStatus|null); + } + + /** Represents an InternalUpdateGraphOperationRequest. */ + class InternalUpdateGraphOperationRequest implements IInternalUpdateGraphOperationRequest { + + /** + * Constructs a new InternalUpdateGraphOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest); + + /** InternalUpdateGraphOperationRequest database. */ + public database: string; + + /** InternalUpdateGraphOperationRequest operationId. */ + public operationId: string; + + /** InternalUpdateGraphOperationRequest vmIdentityToken. */ + public vmIdentityToken: string; + + /** InternalUpdateGraphOperationRequest progress. */ + public progress: number; + + /** InternalUpdateGraphOperationRequest status. */ + public status?: (google.rpc.IStatus|null); + + /** + * Creates a new InternalUpdateGraphOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns InternalUpdateGraphOperationRequest instance + */ + public static create(properties?: google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest): google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest; + + /** + * Encodes the specified InternalUpdateGraphOperationRequest message. Does not implicitly {@link google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest.verify|verify} messages. + * @param message InternalUpdateGraphOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InternalUpdateGraphOperationRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest.verify|verify} messages. + * @param message InternalUpdateGraphOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InternalUpdateGraphOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InternalUpdateGraphOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest; + + /** + * Decodes an InternalUpdateGraphOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InternalUpdateGraphOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest; + + /** + * Verifies an InternalUpdateGraphOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InternalUpdateGraphOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InternalUpdateGraphOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest; + + /** + * Creates a plain object from an InternalUpdateGraphOperationRequest message. Also converts values to other types if specified. + * @param message InternalUpdateGraphOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InternalUpdateGraphOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InternalUpdateGraphOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an InternalUpdateGraphOperationResponse. */ + interface IInternalUpdateGraphOperationResponse { + } + + /** Represents an InternalUpdateGraphOperationResponse. */ + class InternalUpdateGraphOperationResponse implements IInternalUpdateGraphOperationResponse { + + /** + * Constructs a new InternalUpdateGraphOperationResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse); + + /** + * Creates a new InternalUpdateGraphOperationResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns InternalUpdateGraphOperationResponse instance + */ + public static create(properties?: google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse): google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse; + + /** + * Encodes the specified InternalUpdateGraphOperationResponse message. Does not implicitly {@link google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse.verify|verify} messages. + * @param message InternalUpdateGraphOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InternalUpdateGraphOperationResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse.verify|verify} messages. + * @param message InternalUpdateGraphOperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InternalUpdateGraphOperationResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InternalUpdateGraphOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse; + + /** + * Decodes an InternalUpdateGraphOperationResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InternalUpdateGraphOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse; + + /** + * Verifies an InternalUpdateGraphOperationResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InternalUpdateGraphOperationResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InternalUpdateGraphOperationResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse; + + /** + * Creates a plain object from an InternalUpdateGraphOperationResponse message. Also converts values to other types if specified. + * @param message InternalUpdateGraphOperationResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InternalUpdateGraphOperationResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InternalUpdateGraphOperationResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Namespace instance. */ + namespace instance { + + /** Namespace v1. */ + namespace v1 { + + /** Properties of an OperationProgress. */ + interface IOperationProgress { + + /** OperationProgress progressPercent */ + progressPercent?: (number|null); + + /** OperationProgress startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** OperationProgress endTime */ + endTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an OperationProgress. */ + class OperationProgress implements IOperationProgress { + + /** + * Constructs a new OperationProgress. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IOperationProgress); + + /** OperationProgress progressPercent. */ + public progressPercent: number; + + /** OperationProgress startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** OperationProgress endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new OperationProgress instance using the specified properties. + * @param [properties] Properties to set + * @returns OperationProgress instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IOperationProgress): google.spanner.admin.instance.v1.OperationProgress; + + /** + * Encodes the specified OperationProgress message. Does not implicitly {@link google.spanner.admin.instance.v1.OperationProgress.verify|verify} messages. + * @param message OperationProgress message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IOperationProgress, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OperationProgress message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.OperationProgress.verify|verify} messages. + * @param message OperationProgress message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IOperationProgress, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OperationProgress message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OperationProgress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.OperationProgress; + + /** + * Decodes an OperationProgress message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OperationProgress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.OperationProgress; + + /** + * Verifies an OperationProgress message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OperationProgress message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationProgress + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.OperationProgress; + + /** + * Creates a plain object from an OperationProgress message. Also converts values to other types if specified. + * @param message OperationProgress + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.OperationProgress, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationProgress to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationProgress + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** FulfillmentPeriod enum. */ + enum FulfillmentPeriod { + FULFILLMENT_PERIOD_UNSPECIFIED = 0, + FULFILLMENT_PERIOD_NORMAL = 1, + FULFILLMENT_PERIOD_EXTENDED = 2 + } + + /** Properties of a ReplicaSelection. */ + interface IReplicaSelection { + + /** ReplicaSelection location */ + location?: (string|null); + } + + /** Represents a ReplicaSelection. */ + class ReplicaSelection implements IReplicaSelection { + + /** + * Constructs a new ReplicaSelection. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IReplicaSelection); + + /** ReplicaSelection location. */ + public location: string; + + /** + * Creates a new ReplicaSelection instance using the specified properties. + * @param [properties] Properties to set + * @returns ReplicaSelection instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IReplicaSelection): google.spanner.admin.instance.v1.ReplicaSelection; + + /** + * Encodes the specified ReplicaSelection message. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaSelection.verify|verify} messages. + * @param message ReplicaSelection message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IReplicaSelection, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReplicaSelection message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaSelection.verify|verify} messages. + * @param message ReplicaSelection message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IReplicaSelection, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReplicaSelection message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReplicaSelection + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ReplicaSelection; + + /** + * Decodes a ReplicaSelection message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReplicaSelection + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ReplicaSelection; + + /** + * Verifies a ReplicaSelection message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReplicaSelection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReplicaSelection + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ReplicaSelection; + + /** + * Creates a plain object from a ReplicaSelection message. Also converts values to other types if specified. + * @param message ReplicaSelection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ReplicaSelection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReplicaSelection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReplicaSelection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents an InstanceAdmin */ + class InstanceAdmin extends $protobuf.rpc.Service { + + /** + * Constructs a new InstanceAdmin service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new InstanceAdmin service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): InstanceAdmin; + + /** + * Calls ListInstanceConfigs. + * @param request ListInstanceConfigsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListInstanceConfigsResponse + */ + public listInstanceConfigs(request: google.spanner.admin.instance.v1.IListInstanceConfigsRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigsCallback): void; + + /** + * Calls ListInstanceConfigs. + * @param request ListInstanceConfigsRequest message or plain object + * @returns Promise + */ + public listInstanceConfigs(request: google.spanner.admin.instance.v1.IListInstanceConfigsRequest): Promise; + + /** + * Calls GetInstanceConfig. + * @param request GetInstanceConfigRequest message or plain object + * @param callback Node-style callback called with the error, if any, and InstanceConfig + */ + public getInstanceConfig(request: google.spanner.admin.instance.v1.IGetInstanceConfigRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfigCallback): void; + + /** + * Calls GetInstanceConfig. + * @param request GetInstanceConfigRequest message or plain object + * @returns Promise + */ + public getInstanceConfig(request: google.spanner.admin.instance.v1.IGetInstanceConfigRequest): Promise; + + /** + * Calls CreateInstanceConfig. + * @param request CreateInstanceConfigRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createInstanceConfig(request: google.spanner.admin.instance.v1.ICreateInstanceConfigRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceConfigCallback): void; + + /** + * Calls CreateInstanceConfig. + * @param request CreateInstanceConfigRequest message or plain object + * @returns Promise + */ + public createInstanceConfig(request: google.spanner.admin.instance.v1.ICreateInstanceConfigRequest): Promise; + + /** + * Calls UpdateInstanceConfig. + * @param request UpdateInstanceConfigRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateInstanceConfig(request: google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceConfigCallback): void; + + /** + * Calls UpdateInstanceConfig. + * @param request UpdateInstanceConfigRequest message or plain object + * @returns Promise + */ + public updateInstanceConfig(request: google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest): Promise; + + /** + * Calls DeleteInstanceConfig. + * @param request DeleteInstanceConfigRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteInstanceConfig(request: google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstanceConfigCallback): void; + + /** + * Calls DeleteInstanceConfig. + * @param request DeleteInstanceConfigRequest message or plain object + * @returns Promise + */ + public deleteInstanceConfig(request: google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest): Promise; + + /** + * Calls ListInstanceConfigOperations. + * @param request ListInstanceConfigOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListInstanceConfigOperationsResponse + */ + public listInstanceConfigOperations(request: google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigOperationsCallback): void; + + /** + * Calls ListInstanceConfigOperations. + * @param request ListInstanceConfigOperationsRequest message or plain object + * @returns Promise + */ + public listInstanceConfigOperations(request: google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest): Promise; + + /** + * Calls ListInstances. + * @param request ListInstancesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListInstancesResponse + */ + public listInstances(request: google.spanner.admin.instance.v1.IListInstancesRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.ListInstancesCallback): void; + + /** + * Calls ListInstances. + * @param request ListInstancesRequest message or plain object + * @returns Promise + */ + public listInstances(request: google.spanner.admin.instance.v1.IListInstancesRequest): Promise; + + /** + * Calls ListInstancePartitions. + * @param request ListInstancePartitionsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListInstancePartitionsResponse + */ + public listInstancePartitions(request: google.spanner.admin.instance.v1.IListInstancePartitionsRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitionsCallback): void; + + /** + * Calls ListInstancePartitions. + * @param request ListInstancePartitionsRequest message or plain object + * @returns Promise + */ + public listInstancePartitions(request: google.spanner.admin.instance.v1.IListInstancePartitionsRequest): Promise; + + /** + * Calls GetInstance. + * @param request GetInstanceRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Instance + */ + public getInstance(request: google.spanner.admin.instance.v1.IGetInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceCallback): void; + + /** + * Calls GetInstance. + * @param request GetInstanceRequest message or plain object + * @returns Promise + */ + public getInstance(request: google.spanner.admin.instance.v1.IGetInstanceRequest): Promise; + + /** + * Calls CreateInstance. + * @param request CreateInstanceRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createInstance(request: google.spanner.admin.instance.v1.ICreateInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceCallback): void; + + /** + * Calls CreateInstance. + * @param request CreateInstanceRequest message or plain object + * @returns Promise + */ + public createInstance(request: google.spanner.admin.instance.v1.ICreateInstanceRequest): Promise; + + /** + * Calls UpdateInstance. + * @param request UpdateInstanceRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateInstance(request: google.spanner.admin.instance.v1.IUpdateInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceCallback): void; + + /** + * Calls UpdateInstance. + * @param request UpdateInstanceRequest message or plain object + * @returns Promise + */ + public updateInstance(request: google.spanner.admin.instance.v1.IUpdateInstanceRequest): Promise; + + /** + * Calls DeleteInstance. + * @param request DeleteInstanceRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteInstance(request: google.spanner.admin.instance.v1.IDeleteInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstanceCallback): void; + + /** + * Calls DeleteInstance. + * @param request DeleteInstanceRequest message or plain object + * @returns Promise + */ + public deleteInstance(request: google.spanner.admin.instance.v1.IDeleteInstanceRequest): Promise; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.SetIamPolicyCallback): void; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRequest message or plain object + * @returns Promise + */ + public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest): Promise; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.GetIamPolicyCallback): void; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRequest message or plain object + * @returns Promise + */ + public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest): Promise; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and TestIamPermissionsResponse + */ + public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.TestIamPermissionsCallback): void; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRequest message or plain object + * @returns Promise + */ + public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest): Promise; + + /** + * Calls GetInstancePartition. + * @param request GetInstancePartitionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and InstancePartition + */ + public getInstancePartition(request: google.spanner.admin.instance.v1.IGetInstancePartitionRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.GetInstancePartitionCallback): void; + + /** + * Calls GetInstancePartition. + * @param request GetInstancePartitionRequest message or plain object + * @returns Promise + */ + public getInstancePartition(request: google.spanner.admin.instance.v1.IGetInstancePartitionRequest): Promise; + + /** + * Calls CreateInstancePartition. + * @param request CreateInstancePartitionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createInstancePartition(request: google.spanner.admin.instance.v1.ICreateInstancePartitionRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.CreateInstancePartitionCallback): void; + + /** + * Calls CreateInstancePartition. + * @param request CreateInstancePartitionRequest message or plain object + * @returns Promise + */ + public createInstancePartition(request: google.spanner.admin.instance.v1.ICreateInstancePartitionRequest): Promise; + + /** + * Calls DeleteInstancePartition. + * @param request DeleteInstancePartitionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteInstancePartition(request: google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstancePartitionCallback): void; + + /** + * Calls DeleteInstancePartition. + * @param request DeleteInstancePartitionRequest message or plain object + * @returns Promise + */ + public deleteInstancePartition(request: google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest): Promise; + + /** + * Calls UpdateInstancePartition. + * @param request UpdateInstancePartitionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateInstancePartition(request: google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstancePartitionCallback): void; + + /** + * Calls UpdateInstancePartition. + * @param request UpdateInstancePartitionRequest message or plain object + * @returns Promise + */ + public updateInstancePartition(request: google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest): Promise; + + /** + * Calls ListInstancePartitionOperations. + * @param request ListInstancePartitionOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListInstancePartitionOperationsResponse + */ + public listInstancePartitionOperations(request: google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitionOperationsCallback): void; + + /** + * Calls ListInstancePartitionOperations. + * @param request ListInstancePartitionOperationsRequest message or plain object + * @returns Promise + */ + public listInstancePartitionOperations(request: google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest): Promise; + + /** + * Calls MoveInstance. + * @param request MoveInstanceRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public moveInstance(request: google.spanner.admin.instance.v1.IMoveInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.MoveInstanceCallback): void; + + /** + * Calls MoveInstance. + * @param request MoveInstanceRequest message or plain object + * @returns Promise + */ + public moveInstance(request: google.spanner.admin.instance.v1.IMoveInstanceRequest): Promise; + } + + namespace InstanceAdmin { + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstanceConfigs}. + * @param error Error, if any + * @param [response] ListInstanceConfigsResponse + */ + type ListInstanceConfigsCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.ListInstanceConfigsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|getInstanceConfig}. + * @param error Error, if any + * @param [response] InstanceConfig + */ + type GetInstanceConfigCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.InstanceConfig) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|createInstanceConfig}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateInstanceConfigCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|updateInstanceConfig}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateInstanceConfigCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|deleteInstanceConfig}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteInstanceConfigCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstanceConfigOperations}. + * @param error Error, if any + * @param [response] ListInstanceConfigOperationsResponse + */ + type ListInstanceConfigOperationsCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstances}. + * @param error Error, if any + * @param [response] ListInstancesResponse + */ + type ListInstancesCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.ListInstancesResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstancePartitions}. + * @param error Error, if any + * @param [response] ListInstancePartitionsResponse + */ + type ListInstancePartitionsCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.ListInstancePartitionsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|getInstance}. + * @param error Error, if any + * @param [response] Instance + */ + type GetInstanceCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.Instance) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|createInstance}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateInstanceCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|updateInstance}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateInstanceCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|deleteInstance}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteInstanceCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|setIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type SetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|getIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type GetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|testIamPermissions}. + * @param error Error, if any + * @param [response] TestIamPermissionsResponse + */ + type TestIamPermissionsCallback = (error: (Error|null), response?: google.iam.v1.TestIamPermissionsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|getInstancePartition}. + * @param error Error, if any + * @param [response] InstancePartition + */ + type GetInstancePartitionCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.InstancePartition) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|createInstancePartition}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateInstancePartitionCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|deleteInstancePartition}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteInstancePartitionCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|updateInstancePartition}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateInstancePartitionCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstancePartitionOperations}. + * @param error Error, if any + * @param [response] ListInstancePartitionOperationsResponse + */ + type ListInstancePartitionOperationsCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse) => void; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|moveInstance}. + * @param error Error, if any + * @param [response] Operation + */ + type MoveInstanceCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of a ReplicaInfo. */ + interface IReplicaInfo { + + /** ReplicaInfo location */ + location?: (string|null); + + /** ReplicaInfo type */ + type?: (google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType|keyof typeof google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType|null); + + /** ReplicaInfo defaultLeaderLocation */ + defaultLeaderLocation?: (boolean|null); + } + + /** Represents a ReplicaInfo. */ + class ReplicaInfo implements IReplicaInfo { + + /** + * Constructs a new ReplicaInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IReplicaInfo); + + /** ReplicaInfo location. */ + public location: string; + + /** ReplicaInfo type. */ + public type: (google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType|keyof typeof google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType); + + /** ReplicaInfo defaultLeaderLocation. */ + public defaultLeaderLocation: boolean; + + /** + * Creates a new ReplicaInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns ReplicaInfo instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IReplicaInfo): google.spanner.admin.instance.v1.ReplicaInfo; + + /** + * Encodes the specified ReplicaInfo message. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaInfo.verify|verify} messages. + * @param message ReplicaInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IReplicaInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReplicaInfo message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaInfo.verify|verify} messages. + * @param message ReplicaInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IReplicaInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReplicaInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReplicaInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ReplicaInfo; + + /** + * Decodes a ReplicaInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReplicaInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ReplicaInfo; + + /** + * Verifies a ReplicaInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReplicaInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReplicaInfo + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ReplicaInfo; + + /** + * Creates a plain object from a ReplicaInfo message. Also converts values to other types if specified. + * @param message ReplicaInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ReplicaInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReplicaInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReplicaInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ReplicaInfo { + + /** ReplicaType enum. */ + enum ReplicaType { + TYPE_UNSPECIFIED = 0, + READ_WRITE = 1, + READ_ONLY = 2, + WITNESS = 3 + } + } + + /** Properties of an InstanceConfig. */ + interface IInstanceConfig { + + /** InstanceConfig name */ + name?: (string|null); + + /** InstanceConfig displayName */ + displayName?: (string|null); + + /** InstanceConfig configType */ + configType?: (google.spanner.admin.instance.v1.InstanceConfig.Type|keyof typeof google.spanner.admin.instance.v1.InstanceConfig.Type|null); + + /** InstanceConfig replicas */ + replicas?: (google.spanner.admin.instance.v1.IReplicaInfo[]|null); + + /** InstanceConfig optionalReplicas */ + optionalReplicas?: (google.spanner.admin.instance.v1.IReplicaInfo[]|null); + + /** InstanceConfig baseConfig */ + baseConfig?: (string|null); + + /** InstanceConfig labels */ + labels?: ({ [k: string]: string }|null); + + /** InstanceConfig etag */ + etag?: (string|null); + + /** InstanceConfig leaderOptions */ + leaderOptions?: (string[]|null); + + /** InstanceConfig reconciling */ + reconciling?: (boolean|null); + + /** InstanceConfig state */ + state?: (google.spanner.admin.instance.v1.InstanceConfig.State|keyof typeof google.spanner.admin.instance.v1.InstanceConfig.State|null); + + /** InstanceConfig freeInstanceAvailability */ + freeInstanceAvailability?: (google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability|keyof typeof google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability|null); + + /** InstanceConfig quorumType */ + quorumType?: (google.spanner.admin.instance.v1.InstanceConfig.QuorumType|keyof typeof google.spanner.admin.instance.v1.InstanceConfig.QuorumType|null); + + /** InstanceConfig storageLimitPerProcessingUnit */ + storageLimitPerProcessingUnit?: (number|Long|string|null); + } + + /** Represents an InstanceConfig. */ + class InstanceConfig implements IInstanceConfig { + + /** + * Constructs a new InstanceConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IInstanceConfig); + + /** InstanceConfig name. */ + public name: string; + + /** InstanceConfig displayName. */ + public displayName: string; + + /** InstanceConfig configType. */ + public configType: (google.spanner.admin.instance.v1.InstanceConfig.Type|keyof typeof google.spanner.admin.instance.v1.InstanceConfig.Type); + + /** InstanceConfig replicas. */ + public replicas: google.spanner.admin.instance.v1.IReplicaInfo[]; + + /** InstanceConfig optionalReplicas. */ + public optionalReplicas: google.spanner.admin.instance.v1.IReplicaInfo[]; + + /** InstanceConfig baseConfig. */ + public baseConfig: string; + + /** InstanceConfig labels. */ + public labels: { [k: string]: string }; + + /** InstanceConfig etag. */ + public etag: string; + + /** InstanceConfig leaderOptions. */ + public leaderOptions: string[]; + + /** InstanceConfig reconciling. */ + public reconciling: boolean; + + /** InstanceConfig state. */ + public state: (google.spanner.admin.instance.v1.InstanceConfig.State|keyof typeof google.spanner.admin.instance.v1.InstanceConfig.State); + + /** InstanceConfig freeInstanceAvailability. */ + public freeInstanceAvailability: (google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability|keyof typeof google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability); + + /** InstanceConfig quorumType. */ + public quorumType: (google.spanner.admin.instance.v1.InstanceConfig.QuorumType|keyof typeof google.spanner.admin.instance.v1.InstanceConfig.QuorumType); + + /** InstanceConfig storageLimitPerProcessingUnit. */ + public storageLimitPerProcessingUnit: (number|Long|string); + + /** + * Creates a new InstanceConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns InstanceConfig instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IInstanceConfig): google.spanner.admin.instance.v1.InstanceConfig; + + /** + * Encodes the specified InstanceConfig message. Does not implicitly {@link google.spanner.admin.instance.v1.InstanceConfig.verify|verify} messages. + * @param message InstanceConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IInstanceConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstanceConfig message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.InstanceConfig.verify|verify} messages. + * @param message InstanceConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IInstanceConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstanceConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstanceConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.InstanceConfig; + + /** + * Decodes an InstanceConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstanceConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.InstanceConfig; + + /** + * Verifies an InstanceConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstanceConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstanceConfig + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.InstanceConfig; + + /** + * Creates a plain object from an InstanceConfig message. Also converts values to other types if specified. + * @param message InstanceConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.InstanceConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstanceConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstanceConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace InstanceConfig { + + /** Type enum. */ + enum Type { + TYPE_UNSPECIFIED = 0, + GOOGLE_MANAGED = 1, + USER_MANAGED = 2 + } + + /** State enum. */ + enum State { + STATE_UNSPECIFIED = 0, + CREATING = 1, + READY = 2 + } + + /** FreeInstanceAvailability enum. */ + enum FreeInstanceAvailability { + FREE_INSTANCE_AVAILABILITY_UNSPECIFIED = 0, + AVAILABLE = 1, + UNSUPPORTED = 2, + DISABLED = 3, + QUOTA_EXCEEDED = 4 + } + + /** QuorumType enum. */ + enum QuorumType { + QUORUM_TYPE_UNSPECIFIED = 0, + REGION = 1, + DUAL_REGION = 2, + MULTI_REGION = 3 + } + } + + /** Properties of a ReplicaComputeCapacity. */ + interface IReplicaComputeCapacity { + + /** ReplicaComputeCapacity replicaSelection */ + replicaSelection?: (google.spanner.admin.instance.v1.IReplicaSelection|null); + + /** ReplicaComputeCapacity nodeCount */ + nodeCount?: (number|null); + + /** ReplicaComputeCapacity processingUnits */ + processingUnits?: (number|null); + } + + /** Represents a ReplicaComputeCapacity. */ + class ReplicaComputeCapacity implements IReplicaComputeCapacity { + + /** + * Constructs a new ReplicaComputeCapacity. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IReplicaComputeCapacity); + + /** ReplicaComputeCapacity replicaSelection. */ + public replicaSelection?: (google.spanner.admin.instance.v1.IReplicaSelection|null); + + /** ReplicaComputeCapacity nodeCount. */ + public nodeCount?: (number|null); + + /** ReplicaComputeCapacity processingUnits. */ + public processingUnits?: (number|null); + + /** ReplicaComputeCapacity computeCapacity. */ + public computeCapacity?: ("nodeCount"|"processingUnits"); + + /** + * Creates a new ReplicaComputeCapacity instance using the specified properties. + * @param [properties] Properties to set + * @returns ReplicaComputeCapacity instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IReplicaComputeCapacity): google.spanner.admin.instance.v1.ReplicaComputeCapacity; + + /** + * Encodes the specified ReplicaComputeCapacity message. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaComputeCapacity.verify|verify} messages. + * @param message ReplicaComputeCapacity message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IReplicaComputeCapacity, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReplicaComputeCapacity message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaComputeCapacity.verify|verify} messages. + * @param message ReplicaComputeCapacity message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IReplicaComputeCapacity, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReplicaComputeCapacity message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReplicaComputeCapacity + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ReplicaComputeCapacity; + + /** + * Decodes a ReplicaComputeCapacity message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReplicaComputeCapacity + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ReplicaComputeCapacity; + + /** + * Verifies a ReplicaComputeCapacity message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReplicaComputeCapacity message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReplicaComputeCapacity + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ReplicaComputeCapacity; + + /** + * Creates a plain object from a ReplicaComputeCapacity message. Also converts values to other types if specified. + * @param message ReplicaComputeCapacity + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ReplicaComputeCapacity, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReplicaComputeCapacity to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReplicaComputeCapacity + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AutoscalingConfig. */ + interface IAutoscalingConfig { + + /** AutoscalingConfig autoscalingLimits */ + autoscalingLimits?: (google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits|null); + + /** AutoscalingConfig autoscalingTargets */ + autoscalingTargets?: (google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets|null); + + /** AutoscalingConfig asymmetricAutoscalingOptions */ + asymmetricAutoscalingOptions?: (google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption[]|null); + } + + /** Represents an AutoscalingConfig. */ + class AutoscalingConfig implements IAutoscalingConfig { + + /** + * Constructs a new AutoscalingConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IAutoscalingConfig); + + /** AutoscalingConfig autoscalingLimits. */ + public autoscalingLimits?: (google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits|null); + + /** AutoscalingConfig autoscalingTargets. */ + public autoscalingTargets?: (google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets|null); + + /** AutoscalingConfig asymmetricAutoscalingOptions. */ + public asymmetricAutoscalingOptions: google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption[]; + + /** + * Creates a new AutoscalingConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns AutoscalingConfig instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IAutoscalingConfig): google.spanner.admin.instance.v1.AutoscalingConfig; + + /** + * Encodes the specified AutoscalingConfig message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.verify|verify} messages. + * @param message AutoscalingConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IAutoscalingConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AutoscalingConfig message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.verify|verify} messages. + * @param message AutoscalingConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IAutoscalingConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AutoscalingConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AutoscalingConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.AutoscalingConfig; + + /** + * Decodes an AutoscalingConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AutoscalingConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.AutoscalingConfig; + + /** + * Verifies an AutoscalingConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AutoscalingConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AutoscalingConfig + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.AutoscalingConfig; + + /** + * Creates a plain object from an AutoscalingConfig message. Also converts values to other types if specified. + * @param message AutoscalingConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.AutoscalingConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AutoscalingConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AutoscalingConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace AutoscalingConfig { + + /** Properties of an AutoscalingLimits. */ + interface IAutoscalingLimits { + + /** AutoscalingLimits minNodes */ + minNodes?: (number|null); + + /** AutoscalingLimits minProcessingUnits */ + minProcessingUnits?: (number|null); + + /** AutoscalingLimits maxNodes */ + maxNodes?: (number|null); + + /** AutoscalingLimits maxProcessingUnits */ + maxProcessingUnits?: (number|null); + } + + /** Represents an AutoscalingLimits. */ + class AutoscalingLimits implements IAutoscalingLimits { + + /** + * Constructs a new AutoscalingLimits. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits); + + /** AutoscalingLimits minNodes. */ + public minNodes?: (number|null); + + /** AutoscalingLimits minProcessingUnits. */ + public minProcessingUnits?: (number|null); + + /** AutoscalingLimits maxNodes. */ + public maxNodes?: (number|null); + + /** AutoscalingLimits maxProcessingUnits. */ + public maxProcessingUnits?: (number|null); + + /** AutoscalingLimits minLimit. */ + public minLimit?: ("minNodes"|"minProcessingUnits"); + + /** AutoscalingLimits maxLimit. */ + public maxLimit?: ("maxNodes"|"maxProcessingUnits"); + + /** + * Creates a new AutoscalingLimits instance using the specified properties. + * @param [properties] Properties to set + * @returns AutoscalingLimits instance + */ + public static create(properties?: google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits): google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits; + + /** + * Encodes the specified AutoscalingLimits message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.verify|verify} messages. + * @param message AutoscalingLimits message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AutoscalingLimits message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.verify|verify} messages. + * @param message AutoscalingLimits message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AutoscalingLimits message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AutoscalingLimits + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits; + + /** + * Decodes an AutoscalingLimits message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AutoscalingLimits + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits; + + /** + * Verifies an AutoscalingLimits message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AutoscalingLimits message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AutoscalingLimits + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits; + + /** + * Creates a plain object from an AutoscalingLimits message. Also converts values to other types if specified. + * @param message AutoscalingLimits + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AutoscalingLimits to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AutoscalingLimits + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AutoscalingTargets. */ + interface IAutoscalingTargets { + + /** AutoscalingTargets highPriorityCpuUtilizationPercent */ + highPriorityCpuUtilizationPercent?: (number|null); + + /** AutoscalingTargets totalCpuUtilizationPercent */ + totalCpuUtilizationPercent?: (number|null); + + /** AutoscalingTargets storageUtilizationPercent */ + storageUtilizationPercent?: (number|null); + } + + /** Represents an AutoscalingTargets. */ + class AutoscalingTargets implements IAutoscalingTargets { + + /** + * Constructs a new AutoscalingTargets. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets); + + /** AutoscalingTargets highPriorityCpuUtilizationPercent. */ + public highPriorityCpuUtilizationPercent: number; + + /** AutoscalingTargets totalCpuUtilizationPercent. */ + public totalCpuUtilizationPercent: number; + + /** AutoscalingTargets storageUtilizationPercent. */ + public storageUtilizationPercent: number; + + /** + * Creates a new AutoscalingTargets instance using the specified properties. + * @param [properties] Properties to set + * @returns AutoscalingTargets instance + */ + public static create(properties?: google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets): google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets; + + /** + * Encodes the specified AutoscalingTargets message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.verify|verify} messages. + * @param message AutoscalingTargets message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AutoscalingTargets message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.verify|verify} messages. + * @param message AutoscalingTargets message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AutoscalingTargets message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AutoscalingTargets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets; + + /** + * Decodes an AutoscalingTargets message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AutoscalingTargets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets; + + /** + * Verifies an AutoscalingTargets message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AutoscalingTargets message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AutoscalingTargets + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets; + + /** + * Creates a plain object from an AutoscalingTargets message. Also converts values to other types if specified. + * @param message AutoscalingTargets + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AutoscalingTargets to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AutoscalingTargets + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AsymmetricAutoscalingOption. */ + interface IAsymmetricAutoscalingOption { + + /** AsymmetricAutoscalingOption replicaSelection */ + replicaSelection?: (google.spanner.admin.instance.v1.IReplicaSelection|null); + + /** AsymmetricAutoscalingOption overrides */ + overrides?: (google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides|null); + } + + /** Represents an AsymmetricAutoscalingOption. */ + class AsymmetricAutoscalingOption implements IAsymmetricAutoscalingOption { + + /** + * Constructs a new AsymmetricAutoscalingOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption); + + /** AsymmetricAutoscalingOption replicaSelection. */ + public replicaSelection?: (google.spanner.admin.instance.v1.IReplicaSelection|null); + + /** AsymmetricAutoscalingOption overrides. */ + public overrides?: (google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides|null); + + /** + * Creates a new AsymmetricAutoscalingOption instance using the specified properties. + * @param [properties] Properties to set + * @returns AsymmetricAutoscalingOption instance + */ + public static create(properties?: google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption): google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption; + + /** + * Encodes the specified AsymmetricAutoscalingOption message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.verify|verify} messages. + * @param message AsymmetricAutoscalingOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AsymmetricAutoscalingOption message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.verify|verify} messages. + * @param message AsymmetricAutoscalingOption message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AsymmetricAutoscalingOption message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AsymmetricAutoscalingOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption; + + /** + * Decodes an AsymmetricAutoscalingOption message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AsymmetricAutoscalingOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption; + + /** + * Verifies an AsymmetricAutoscalingOption message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AsymmetricAutoscalingOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AsymmetricAutoscalingOption + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption; + + /** + * Creates a plain object from an AsymmetricAutoscalingOption message. Also converts values to other types if specified. + * @param message AsymmetricAutoscalingOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AsymmetricAutoscalingOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AsymmetricAutoscalingOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace AsymmetricAutoscalingOption { + + /** Properties of an AutoscalingConfigOverrides. */ + interface IAutoscalingConfigOverrides { + + /** AutoscalingConfigOverrides autoscalingLimits */ + autoscalingLimits?: (google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits|null); + + /** AutoscalingConfigOverrides autoscalingTargetHighPriorityCpuUtilizationPercent */ + autoscalingTargetHighPriorityCpuUtilizationPercent?: (number|null); + + /** AutoscalingConfigOverrides autoscalingTargetTotalCpuUtilizationPercent */ + autoscalingTargetTotalCpuUtilizationPercent?: (number|null); + + /** AutoscalingConfigOverrides disableHighPriorityCpuAutoscaling */ + disableHighPriorityCpuAutoscaling?: (boolean|null); + + /** AutoscalingConfigOverrides disableTotalCpuAutoscaling */ + disableTotalCpuAutoscaling?: (boolean|null); + } + + /** Represents an AutoscalingConfigOverrides. */ + class AutoscalingConfigOverrides implements IAutoscalingConfigOverrides { + + /** + * Constructs a new AutoscalingConfigOverrides. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides); + + /** AutoscalingConfigOverrides autoscalingLimits. */ + public autoscalingLimits?: (google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits|null); + + /** AutoscalingConfigOverrides autoscalingTargetHighPriorityCpuUtilizationPercent. */ + public autoscalingTargetHighPriorityCpuUtilizationPercent: number; + + /** AutoscalingConfigOverrides autoscalingTargetTotalCpuUtilizationPercent. */ + public autoscalingTargetTotalCpuUtilizationPercent: number; + + /** AutoscalingConfigOverrides disableHighPriorityCpuAutoscaling. */ + public disableHighPriorityCpuAutoscaling: boolean; + + /** AutoscalingConfigOverrides disableTotalCpuAutoscaling. */ + public disableTotalCpuAutoscaling: boolean; + + /** + * Creates a new AutoscalingConfigOverrides instance using the specified properties. + * @param [properties] Properties to set + * @returns AutoscalingConfigOverrides instance + */ + public static create(properties?: google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides): google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides; + + /** + * Encodes the specified AutoscalingConfigOverrides message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.verify|verify} messages. + * @param message AutoscalingConfigOverrides message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AutoscalingConfigOverrides message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.verify|verify} messages. + * @param message AutoscalingConfigOverrides message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AutoscalingConfigOverrides message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AutoscalingConfigOverrides + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides; + + /** + * Decodes an AutoscalingConfigOverrides message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AutoscalingConfigOverrides + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides; + + /** + * Verifies an AutoscalingConfigOverrides message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AutoscalingConfigOverrides message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AutoscalingConfigOverrides + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides; + + /** + * Creates a plain object from an AutoscalingConfigOverrides message. Also converts values to other types if specified. + * @param message AutoscalingConfigOverrides + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AutoscalingConfigOverrides to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AutoscalingConfigOverrides + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Properties of an Instance. */ + interface IInstance { + + /** Instance name */ + name?: (string|null); + + /** Instance config */ + config?: (string|null); + + /** Instance displayName */ + displayName?: (string|null); + + /** Instance nodeCount */ + nodeCount?: (number|null); + + /** Instance processingUnits */ + processingUnits?: (number|null); + + /** Instance replicaComputeCapacity */ + replicaComputeCapacity?: (google.spanner.admin.instance.v1.IReplicaComputeCapacity[]|null); + + /** Instance autoscalingConfig */ + autoscalingConfig?: (google.spanner.admin.instance.v1.IAutoscalingConfig|null); + + /** Instance state */ + state?: (google.spanner.admin.instance.v1.Instance.State|keyof typeof google.spanner.admin.instance.v1.Instance.State|null); + + /** Instance labels */ + labels?: ({ [k: string]: string }|null); + + /** Instance instanceType */ + instanceType?: (google.spanner.admin.instance.v1.Instance.InstanceType|keyof typeof google.spanner.admin.instance.v1.Instance.InstanceType|null); + + /** Instance endpointUris */ + endpointUris?: (string[]|null); + + /** Instance createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Instance updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** Instance freeInstanceMetadata */ + freeInstanceMetadata?: (google.spanner.admin.instance.v1.IFreeInstanceMetadata|null); + + /** Instance edition */ + edition?: (google.spanner.admin.instance.v1.Instance.Edition|keyof typeof google.spanner.admin.instance.v1.Instance.Edition|null); + + /** Instance defaultBackupScheduleType */ + defaultBackupScheduleType?: (google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType|keyof typeof google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType|null); + } + + /** Represents an Instance. */ + class Instance implements IInstance { + + /** + * Constructs a new Instance. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IInstance); + + /** Instance name. */ + public name: string; + + /** Instance config. */ + public config: string; + + /** Instance displayName. */ + public displayName: string; + + /** Instance nodeCount. */ + public nodeCount: number; + + /** Instance processingUnits. */ + public processingUnits: number; + + /** Instance replicaComputeCapacity. */ + public replicaComputeCapacity: google.spanner.admin.instance.v1.IReplicaComputeCapacity[]; + + /** Instance autoscalingConfig. */ + public autoscalingConfig?: (google.spanner.admin.instance.v1.IAutoscalingConfig|null); + + /** Instance state. */ + public state: (google.spanner.admin.instance.v1.Instance.State|keyof typeof google.spanner.admin.instance.v1.Instance.State); + + /** Instance labels. */ + public labels: { [k: string]: string }; + + /** Instance instanceType. */ + public instanceType: (google.spanner.admin.instance.v1.Instance.InstanceType|keyof typeof google.spanner.admin.instance.v1.Instance.InstanceType); + + /** Instance endpointUris. */ + public endpointUris: string[]; + + /** Instance createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Instance updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** Instance freeInstanceMetadata. */ + public freeInstanceMetadata?: (google.spanner.admin.instance.v1.IFreeInstanceMetadata|null); + + /** Instance edition. */ + public edition: (google.spanner.admin.instance.v1.Instance.Edition|keyof typeof google.spanner.admin.instance.v1.Instance.Edition); + + /** Instance defaultBackupScheduleType. */ + public defaultBackupScheduleType: (google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType|keyof typeof google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType); + + /** + * Creates a new Instance instance using the specified properties. + * @param [properties] Properties to set + * @returns Instance instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IInstance): google.spanner.admin.instance.v1.Instance; + + /** + * Encodes the specified Instance message. Does not implicitly {@link google.spanner.admin.instance.v1.Instance.verify|verify} messages. + * @param message Instance message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IInstance, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Instance message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.Instance.verify|verify} messages. + * @param message Instance message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IInstance, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Instance message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Instance + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.Instance; + + /** + * Decodes an Instance message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Instance + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.Instance; + + /** + * Verifies an Instance message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Instance message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Instance + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.Instance; + + /** + * Creates a plain object from an Instance message. Also converts values to other types if specified. + * @param message Instance + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.Instance, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Instance to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Instance + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Instance { + + /** State enum. */ + enum State { + STATE_UNSPECIFIED = 0, + CREATING = 1, + READY = 2 + } + + /** InstanceType enum. */ + enum InstanceType { + INSTANCE_TYPE_UNSPECIFIED = 0, + PROVISIONED = 1, + FREE_INSTANCE = 2 + } + + /** Edition enum. */ + enum Edition { + EDITION_UNSPECIFIED = 0, + STANDARD = 1, + ENTERPRISE = 2, + ENTERPRISE_PLUS = 3 + } + + /** DefaultBackupScheduleType enum. */ + enum DefaultBackupScheduleType { + DEFAULT_BACKUP_SCHEDULE_TYPE_UNSPECIFIED = 0, + NONE = 1, + AUTOMATIC = 2 + } + } + + /** Properties of a ListInstanceConfigsRequest. */ + interface IListInstanceConfigsRequest { + + /** ListInstanceConfigsRequest parent */ + parent?: (string|null); + + /** ListInstanceConfigsRequest pageSize */ + pageSize?: (number|null); + + /** ListInstanceConfigsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListInstanceConfigsRequest. */ + class ListInstanceConfigsRequest implements IListInstanceConfigsRequest { + + /** + * Constructs a new ListInstanceConfigsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstanceConfigsRequest); + + /** ListInstanceConfigsRequest parent. */ + public parent: string; + + /** ListInstanceConfigsRequest pageSize. */ + public pageSize: number; + + /** ListInstanceConfigsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListInstanceConfigsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstanceConfigsRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstanceConfigsRequest): google.spanner.admin.instance.v1.ListInstanceConfigsRequest; + + /** + * Encodes the specified ListInstanceConfigsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsRequest.verify|verify} messages. + * @param message ListInstanceConfigsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstanceConfigsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstanceConfigsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsRequest.verify|verify} messages. + * @param message ListInstanceConfigsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstanceConfigsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstanceConfigsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstanceConfigsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstanceConfigsRequest; + + /** + * Decodes a ListInstanceConfigsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstanceConfigsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstanceConfigsRequest; + + /** + * Verifies a ListInstanceConfigsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstanceConfigsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstanceConfigsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstanceConfigsRequest; + + /** + * Creates a plain object from a ListInstanceConfigsRequest message. Also converts values to other types if specified. + * @param message ListInstanceConfigsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstanceConfigsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstanceConfigsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstanceConfigsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstanceConfigsResponse. */ + interface IListInstanceConfigsResponse { + + /** ListInstanceConfigsResponse instanceConfigs */ + instanceConfigs?: (google.spanner.admin.instance.v1.IInstanceConfig[]|null); + + /** ListInstanceConfigsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListInstanceConfigsResponse. */ + class ListInstanceConfigsResponse implements IListInstanceConfigsResponse { + + /** + * Constructs a new ListInstanceConfigsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstanceConfigsResponse); + + /** ListInstanceConfigsResponse instanceConfigs. */ + public instanceConfigs: google.spanner.admin.instance.v1.IInstanceConfig[]; + + /** ListInstanceConfigsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListInstanceConfigsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstanceConfigsResponse instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstanceConfigsResponse): google.spanner.admin.instance.v1.ListInstanceConfigsResponse; + + /** + * Encodes the specified ListInstanceConfigsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsResponse.verify|verify} messages. + * @param message ListInstanceConfigsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstanceConfigsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstanceConfigsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsResponse.verify|verify} messages. + * @param message ListInstanceConfigsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstanceConfigsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstanceConfigsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstanceConfigsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstanceConfigsResponse; + + /** + * Decodes a ListInstanceConfigsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstanceConfigsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstanceConfigsResponse; + + /** + * Verifies a ListInstanceConfigsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstanceConfigsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstanceConfigsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstanceConfigsResponse; + + /** + * Creates a plain object from a ListInstanceConfigsResponse message. Also converts values to other types if specified. + * @param message ListInstanceConfigsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstanceConfigsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstanceConfigsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstanceConfigsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetInstanceConfigRequest. */ + interface IGetInstanceConfigRequest { + + /** GetInstanceConfigRequest name */ + name?: (string|null); + } + + /** Represents a GetInstanceConfigRequest. */ + class GetInstanceConfigRequest implements IGetInstanceConfigRequest { + + /** + * Constructs a new GetInstanceConfigRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IGetInstanceConfigRequest); + + /** GetInstanceConfigRequest name. */ + public name: string; + + /** + * Creates a new GetInstanceConfigRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetInstanceConfigRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IGetInstanceConfigRequest): google.spanner.admin.instance.v1.GetInstanceConfigRequest; + + /** + * Encodes the specified GetInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceConfigRequest.verify|verify} messages. + * @param message GetInstanceConfigRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IGetInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceConfigRequest.verify|verify} messages. + * @param message GetInstanceConfigRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IGetInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetInstanceConfigRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.GetInstanceConfigRequest; + + /** + * Decodes a GetInstanceConfigRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.GetInstanceConfigRequest; + + /** + * Verifies a GetInstanceConfigRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetInstanceConfigRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.GetInstanceConfigRequest; + + /** + * Creates a plain object from a GetInstanceConfigRequest message. Also converts values to other types if specified. + * @param message GetInstanceConfigRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.GetInstanceConfigRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetInstanceConfigRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetInstanceConfigRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateInstanceConfigRequest. */ + interface ICreateInstanceConfigRequest { + + /** CreateInstanceConfigRequest parent */ + parent?: (string|null); + + /** CreateInstanceConfigRequest instanceConfigId */ + instanceConfigId?: (string|null); + + /** CreateInstanceConfigRequest instanceConfig */ + instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** CreateInstanceConfigRequest validateOnly */ + validateOnly?: (boolean|null); + } + + /** Represents a CreateInstanceConfigRequest. */ + class CreateInstanceConfigRequest implements ICreateInstanceConfigRequest { + + /** + * Constructs a new CreateInstanceConfigRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.ICreateInstanceConfigRequest); + + /** CreateInstanceConfigRequest parent. */ + public parent: string; + + /** CreateInstanceConfigRequest instanceConfigId. */ + public instanceConfigId: string; + + /** CreateInstanceConfigRequest instanceConfig. */ + public instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** CreateInstanceConfigRequest validateOnly. */ + public validateOnly: boolean; + + /** + * Creates a new CreateInstanceConfigRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateInstanceConfigRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.ICreateInstanceConfigRequest): google.spanner.admin.instance.v1.CreateInstanceConfigRequest; + + /** + * Encodes the specified CreateInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceConfigRequest.verify|verify} messages. + * @param message CreateInstanceConfigRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.ICreateInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceConfigRequest.verify|verify} messages. + * @param message CreateInstanceConfigRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.ICreateInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateInstanceConfigRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.CreateInstanceConfigRequest; + + /** + * Decodes a CreateInstanceConfigRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.CreateInstanceConfigRequest; + + /** + * Verifies a CreateInstanceConfigRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateInstanceConfigRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.CreateInstanceConfigRequest; + + /** + * Creates a plain object from a CreateInstanceConfigRequest message. Also converts values to other types if specified. + * @param message CreateInstanceConfigRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.CreateInstanceConfigRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateInstanceConfigRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateInstanceConfigRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateInstanceConfigRequest. */ + interface IUpdateInstanceConfigRequest { + + /** UpdateInstanceConfigRequest instanceConfig */ + instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** UpdateInstanceConfigRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + + /** UpdateInstanceConfigRequest validateOnly */ + validateOnly?: (boolean|null); + } + + /** Represents an UpdateInstanceConfigRequest. */ + class UpdateInstanceConfigRequest implements IUpdateInstanceConfigRequest { + + /** + * Constructs a new UpdateInstanceConfigRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest); + + /** UpdateInstanceConfigRequest instanceConfig. */ + public instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** UpdateInstanceConfigRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** UpdateInstanceConfigRequest validateOnly. */ + public validateOnly: boolean; + + /** + * Creates a new UpdateInstanceConfigRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateInstanceConfigRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest): google.spanner.admin.instance.v1.UpdateInstanceConfigRequest; + + /** + * Encodes the specified UpdateInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceConfigRequest.verify|verify} messages. + * @param message UpdateInstanceConfigRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceConfigRequest.verify|verify} messages. + * @param message UpdateInstanceConfigRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateInstanceConfigRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.UpdateInstanceConfigRequest; + + /** + * Decodes an UpdateInstanceConfigRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.UpdateInstanceConfigRequest; + + /** + * Verifies an UpdateInstanceConfigRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateInstanceConfigRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.UpdateInstanceConfigRequest; + + /** + * Creates a plain object from an UpdateInstanceConfigRequest message. Also converts values to other types if specified. + * @param message UpdateInstanceConfigRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.UpdateInstanceConfigRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateInstanceConfigRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateInstanceConfigRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteInstanceConfigRequest. */ + interface IDeleteInstanceConfigRequest { + + /** DeleteInstanceConfigRequest name */ + name?: (string|null); + + /** DeleteInstanceConfigRequest etag */ + etag?: (string|null); + + /** DeleteInstanceConfigRequest validateOnly */ + validateOnly?: (boolean|null); + } + + /** Represents a DeleteInstanceConfigRequest. */ + class DeleteInstanceConfigRequest implements IDeleteInstanceConfigRequest { + + /** + * Constructs a new DeleteInstanceConfigRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest); + + /** DeleteInstanceConfigRequest name. */ + public name: string; + + /** DeleteInstanceConfigRequest etag. */ + public etag: string; + + /** DeleteInstanceConfigRequest validateOnly. */ + public validateOnly: boolean; + + /** + * Creates a new DeleteInstanceConfigRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteInstanceConfigRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest): google.spanner.admin.instance.v1.DeleteInstanceConfigRequest; + + /** + * Encodes the specified DeleteInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceConfigRequest.verify|verify} messages. + * @param message DeleteInstanceConfigRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceConfigRequest.verify|verify} messages. + * @param message DeleteInstanceConfigRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteInstanceConfigRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.DeleteInstanceConfigRequest; + + /** + * Decodes a DeleteInstanceConfigRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.DeleteInstanceConfigRequest; + + /** + * Verifies a DeleteInstanceConfigRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteInstanceConfigRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.DeleteInstanceConfigRequest; + + /** + * Creates a plain object from a DeleteInstanceConfigRequest message. Also converts values to other types if specified. + * @param message DeleteInstanceConfigRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.DeleteInstanceConfigRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteInstanceConfigRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteInstanceConfigRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstanceConfigOperationsRequest. */ + interface IListInstanceConfigOperationsRequest { + + /** ListInstanceConfigOperationsRequest parent */ + parent?: (string|null); + + /** ListInstanceConfigOperationsRequest filter */ + filter?: (string|null); + + /** ListInstanceConfigOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListInstanceConfigOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListInstanceConfigOperationsRequest. */ + class ListInstanceConfigOperationsRequest implements IListInstanceConfigOperationsRequest { + + /** + * Constructs a new ListInstanceConfigOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest); + + /** ListInstanceConfigOperationsRequest parent. */ + public parent: string; + + /** ListInstanceConfigOperationsRequest filter. */ + public filter: string; + + /** ListInstanceConfigOperationsRequest pageSize. */ + public pageSize: number; + + /** ListInstanceConfigOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListInstanceConfigOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstanceConfigOperationsRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest): google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest; + + /** + * Encodes the specified ListInstanceConfigOperationsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest.verify|verify} messages. + * @param message ListInstanceConfigOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstanceConfigOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest.verify|verify} messages. + * @param message ListInstanceConfigOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstanceConfigOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstanceConfigOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest; + + /** + * Decodes a ListInstanceConfigOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstanceConfigOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest; + + /** + * Verifies a ListInstanceConfigOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstanceConfigOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstanceConfigOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest; + + /** + * Creates a plain object from a ListInstanceConfigOperationsRequest message. Also converts values to other types if specified. + * @param message ListInstanceConfigOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstanceConfigOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstanceConfigOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstanceConfigOperationsResponse. */ + interface IListInstanceConfigOperationsResponse { + + /** ListInstanceConfigOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListInstanceConfigOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListInstanceConfigOperationsResponse. */ + class ListInstanceConfigOperationsResponse implements IListInstanceConfigOperationsResponse { + + /** + * Constructs a new ListInstanceConfigOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse); + + /** ListInstanceConfigOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListInstanceConfigOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListInstanceConfigOperationsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstanceConfigOperationsResponse instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse): google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse; + + /** + * Encodes the specified ListInstanceConfigOperationsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.verify|verify} messages. + * @param message ListInstanceConfigOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstanceConfigOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.verify|verify} messages. + * @param message ListInstanceConfigOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstanceConfigOperationsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstanceConfigOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse; + + /** + * Decodes a ListInstanceConfigOperationsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstanceConfigOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse; + + /** + * Verifies a ListInstanceConfigOperationsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstanceConfigOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstanceConfigOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse; + + /** + * Creates a plain object from a ListInstanceConfigOperationsResponse message. Also converts values to other types if specified. + * @param message ListInstanceConfigOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstanceConfigOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstanceConfigOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetInstanceRequest. */ + interface IGetInstanceRequest { + + /** GetInstanceRequest name */ + name?: (string|null); + + /** GetInstanceRequest fieldMask */ + fieldMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents a GetInstanceRequest. */ + class GetInstanceRequest implements IGetInstanceRequest { + + /** + * Constructs a new GetInstanceRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IGetInstanceRequest); + + /** GetInstanceRequest name. */ + public name: string; + + /** GetInstanceRequest fieldMask. */ + public fieldMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new GetInstanceRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetInstanceRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IGetInstanceRequest): google.spanner.admin.instance.v1.GetInstanceRequest; + + /** + * Encodes the specified GetInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceRequest.verify|verify} messages. + * @param message GetInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IGetInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceRequest.verify|verify} messages. + * @param message GetInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IGetInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetInstanceRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.GetInstanceRequest; + + /** + * Decodes a GetInstanceRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.GetInstanceRequest; + + /** + * Verifies a GetInstanceRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetInstanceRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.GetInstanceRequest; + + /** + * Creates a plain object from a GetInstanceRequest message. Also converts values to other types if specified. + * @param message GetInstanceRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.GetInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetInstanceRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetInstanceRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateInstanceRequest. */ + interface ICreateInstanceRequest { + + /** CreateInstanceRequest parent */ + parent?: (string|null); + + /** CreateInstanceRequest instanceId */ + instanceId?: (string|null); + + /** CreateInstanceRequest instance */ + instance?: (google.spanner.admin.instance.v1.IInstance|null); + } + + /** Represents a CreateInstanceRequest. */ + class CreateInstanceRequest implements ICreateInstanceRequest { + + /** + * Constructs a new CreateInstanceRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.ICreateInstanceRequest); + + /** CreateInstanceRequest parent. */ + public parent: string; + + /** CreateInstanceRequest instanceId. */ + public instanceId: string; + + /** CreateInstanceRequest instance. */ + public instance?: (google.spanner.admin.instance.v1.IInstance|null); + + /** + * Creates a new CreateInstanceRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateInstanceRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.ICreateInstanceRequest): google.spanner.admin.instance.v1.CreateInstanceRequest; + + /** + * Encodes the specified CreateInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceRequest.verify|verify} messages. + * @param message CreateInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.ICreateInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceRequest.verify|verify} messages. + * @param message CreateInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.ICreateInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateInstanceRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.CreateInstanceRequest; + + /** + * Decodes a CreateInstanceRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.CreateInstanceRequest; + + /** + * Verifies a CreateInstanceRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateInstanceRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.CreateInstanceRequest; + + /** + * Creates a plain object from a CreateInstanceRequest message. Also converts values to other types if specified. + * @param message CreateInstanceRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.CreateInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateInstanceRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateInstanceRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstancesRequest. */ + interface IListInstancesRequest { + + /** ListInstancesRequest parent */ + parent?: (string|null); + + /** ListInstancesRequest pageSize */ + pageSize?: (number|null); + + /** ListInstancesRequest pageToken */ + pageToken?: (string|null); + + /** ListInstancesRequest filter */ + filter?: (string|null); + + /** ListInstancesRequest instanceDeadline */ + instanceDeadline?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListInstancesRequest. */ + class ListInstancesRequest implements IListInstancesRequest { + + /** + * Constructs a new ListInstancesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstancesRequest); + + /** ListInstancesRequest parent. */ + public parent: string; + + /** ListInstancesRequest pageSize. */ + public pageSize: number; + + /** ListInstancesRequest pageToken. */ + public pageToken: string; + + /** ListInstancesRequest filter. */ + public filter: string; + + /** ListInstancesRequest instanceDeadline. */ + public instanceDeadline?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new ListInstancesRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstancesRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstancesRequest): google.spanner.admin.instance.v1.ListInstancesRequest; + + /** + * Encodes the specified ListInstancesRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesRequest.verify|verify} messages. + * @param message ListInstancesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstancesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstancesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesRequest.verify|verify} messages. + * @param message ListInstancesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstancesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstancesRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstancesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstancesRequest; + + /** + * Decodes a ListInstancesRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstancesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstancesRequest; + + /** + * Verifies a ListInstancesRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstancesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstancesRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstancesRequest; + + /** + * Creates a plain object from a ListInstancesRequest message. Also converts values to other types if specified. + * @param message ListInstancesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstancesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstancesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstancesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstancesResponse. */ + interface IListInstancesResponse { + + /** ListInstancesResponse instances */ + instances?: (google.spanner.admin.instance.v1.IInstance[]|null); + + /** ListInstancesResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListInstancesResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListInstancesResponse. */ + class ListInstancesResponse implements IListInstancesResponse { + + /** + * Constructs a new ListInstancesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstancesResponse); + + /** ListInstancesResponse instances. */ + public instances: google.spanner.admin.instance.v1.IInstance[]; + + /** ListInstancesResponse nextPageToken. */ + public nextPageToken: string; + + /** ListInstancesResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a new ListInstancesResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstancesResponse instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstancesResponse): google.spanner.admin.instance.v1.ListInstancesResponse; + + /** + * Encodes the specified ListInstancesResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesResponse.verify|verify} messages. + * @param message ListInstancesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstancesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstancesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesResponse.verify|verify} messages. + * @param message ListInstancesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstancesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstancesResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstancesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstancesResponse; + + /** + * Decodes a ListInstancesResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstancesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstancesResponse; + + /** + * Verifies a ListInstancesResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstancesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstancesResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstancesResponse; + + /** + * Creates a plain object from a ListInstancesResponse message. Also converts values to other types if specified. + * @param message ListInstancesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstancesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstancesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstancesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateInstanceRequest. */ + interface IUpdateInstanceRequest { + + /** UpdateInstanceRequest instance */ + instance?: (google.spanner.admin.instance.v1.IInstance|null); + + /** UpdateInstanceRequest fieldMask */ + fieldMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateInstanceRequest. */ + class UpdateInstanceRequest implements IUpdateInstanceRequest { + + /** + * Constructs a new UpdateInstanceRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IUpdateInstanceRequest); + + /** UpdateInstanceRequest instance. */ + public instance?: (google.spanner.admin.instance.v1.IInstance|null); + + /** UpdateInstanceRequest fieldMask. */ + public fieldMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new UpdateInstanceRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateInstanceRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IUpdateInstanceRequest): google.spanner.admin.instance.v1.UpdateInstanceRequest; + + /** + * Encodes the specified UpdateInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceRequest.verify|verify} messages. + * @param message UpdateInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IUpdateInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceRequest.verify|verify} messages. + * @param message UpdateInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IUpdateInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateInstanceRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.UpdateInstanceRequest; + + /** + * Decodes an UpdateInstanceRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.UpdateInstanceRequest; + + /** + * Verifies an UpdateInstanceRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateInstanceRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.UpdateInstanceRequest; + + /** + * Creates a plain object from an UpdateInstanceRequest message. Also converts values to other types if specified. + * @param message UpdateInstanceRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.UpdateInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateInstanceRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateInstanceRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteInstanceRequest. */ + interface IDeleteInstanceRequest { + + /** DeleteInstanceRequest name */ + name?: (string|null); + } + + /** Represents a DeleteInstanceRequest. */ + class DeleteInstanceRequest implements IDeleteInstanceRequest { + + /** + * Constructs a new DeleteInstanceRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IDeleteInstanceRequest); + + /** DeleteInstanceRequest name. */ + public name: string; + + /** + * Creates a new DeleteInstanceRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteInstanceRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IDeleteInstanceRequest): google.spanner.admin.instance.v1.DeleteInstanceRequest; + + /** + * Encodes the specified DeleteInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceRequest.verify|verify} messages. + * @param message DeleteInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IDeleteInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceRequest.verify|verify} messages. + * @param message DeleteInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IDeleteInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteInstanceRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.DeleteInstanceRequest; + + /** + * Decodes a DeleteInstanceRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.DeleteInstanceRequest; + + /** + * Verifies a DeleteInstanceRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteInstanceRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.DeleteInstanceRequest; + + /** + * Creates a plain object from a DeleteInstanceRequest message. Also converts values to other types if specified. + * @param message DeleteInstanceRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.DeleteInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteInstanceRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteInstanceRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateInstanceMetadata. */ + interface ICreateInstanceMetadata { + + /** CreateInstanceMetadata instance */ + instance?: (google.spanner.admin.instance.v1.IInstance|null); + + /** CreateInstanceMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstanceMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstanceMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstanceMetadata expectedFulfillmentPeriod */ + expectedFulfillmentPeriod?: (google.spanner.admin.instance.v1.FulfillmentPeriod|keyof typeof google.spanner.admin.instance.v1.FulfillmentPeriod|null); + } + + /** Represents a CreateInstanceMetadata. */ + class CreateInstanceMetadata implements ICreateInstanceMetadata { + + /** + * Constructs a new CreateInstanceMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.ICreateInstanceMetadata); + + /** CreateInstanceMetadata instance. */ + public instance?: (google.spanner.admin.instance.v1.IInstance|null); + + /** CreateInstanceMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstanceMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstanceMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstanceMetadata expectedFulfillmentPeriod. */ + public expectedFulfillmentPeriod: (google.spanner.admin.instance.v1.FulfillmentPeriod|keyof typeof google.spanner.admin.instance.v1.FulfillmentPeriod); + + /** + * Creates a new CreateInstanceMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateInstanceMetadata instance + */ + public static create(properties?: google.spanner.admin.instance.v1.ICreateInstanceMetadata): google.spanner.admin.instance.v1.CreateInstanceMetadata; + + /** + * Encodes the specified CreateInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceMetadata.verify|verify} messages. + * @param message CreateInstanceMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.ICreateInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceMetadata.verify|verify} messages. + * @param message CreateInstanceMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.ICreateInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateInstanceMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.CreateInstanceMetadata; + + /** + * Decodes a CreateInstanceMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.CreateInstanceMetadata; + + /** + * Verifies a CreateInstanceMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateInstanceMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateInstanceMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.CreateInstanceMetadata; + + /** + * Creates a plain object from a CreateInstanceMetadata message. Also converts values to other types if specified. + * @param message CreateInstanceMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.CreateInstanceMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateInstanceMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateInstanceMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateInstanceMetadata. */ + interface IUpdateInstanceMetadata { + + /** UpdateInstanceMetadata instance */ + instance?: (google.spanner.admin.instance.v1.IInstance|null); + + /** UpdateInstanceMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstanceMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstanceMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstanceMetadata expectedFulfillmentPeriod */ + expectedFulfillmentPeriod?: (google.spanner.admin.instance.v1.FulfillmentPeriod|keyof typeof google.spanner.admin.instance.v1.FulfillmentPeriod|null); + } + + /** Represents an UpdateInstanceMetadata. */ + class UpdateInstanceMetadata implements IUpdateInstanceMetadata { + + /** + * Constructs a new UpdateInstanceMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IUpdateInstanceMetadata); + + /** UpdateInstanceMetadata instance. */ + public instance?: (google.spanner.admin.instance.v1.IInstance|null); + + /** UpdateInstanceMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstanceMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstanceMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstanceMetadata expectedFulfillmentPeriod. */ + public expectedFulfillmentPeriod: (google.spanner.admin.instance.v1.FulfillmentPeriod|keyof typeof google.spanner.admin.instance.v1.FulfillmentPeriod); + + /** + * Creates a new UpdateInstanceMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateInstanceMetadata instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IUpdateInstanceMetadata): google.spanner.admin.instance.v1.UpdateInstanceMetadata; + + /** + * Encodes the specified UpdateInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceMetadata.verify|verify} messages. + * @param message UpdateInstanceMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IUpdateInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceMetadata.verify|verify} messages. + * @param message UpdateInstanceMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IUpdateInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateInstanceMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.UpdateInstanceMetadata; + + /** + * Decodes an UpdateInstanceMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.UpdateInstanceMetadata; + + /** + * Verifies an UpdateInstanceMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateInstanceMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateInstanceMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.UpdateInstanceMetadata; + + /** + * Creates a plain object from an UpdateInstanceMetadata message. Also converts values to other types if specified. + * @param message UpdateInstanceMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.UpdateInstanceMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateInstanceMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateInstanceMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FreeInstanceMetadata. */ + interface IFreeInstanceMetadata { + + /** FreeInstanceMetadata expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** FreeInstanceMetadata upgradeTime */ + upgradeTime?: (google.protobuf.ITimestamp|null); + + /** FreeInstanceMetadata expireBehavior */ + expireBehavior?: (google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior|keyof typeof google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior|null); + } + + /** Represents a FreeInstanceMetadata. */ + class FreeInstanceMetadata implements IFreeInstanceMetadata { + + /** + * Constructs a new FreeInstanceMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IFreeInstanceMetadata); + + /** FreeInstanceMetadata expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** FreeInstanceMetadata upgradeTime. */ + public upgradeTime?: (google.protobuf.ITimestamp|null); + + /** FreeInstanceMetadata expireBehavior. */ + public expireBehavior: (google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior|keyof typeof google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior); + + /** + * Creates a new FreeInstanceMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns FreeInstanceMetadata instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IFreeInstanceMetadata): google.spanner.admin.instance.v1.FreeInstanceMetadata; + + /** + * Encodes the specified FreeInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.FreeInstanceMetadata.verify|verify} messages. + * @param message FreeInstanceMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IFreeInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FreeInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.FreeInstanceMetadata.verify|verify} messages. + * @param message FreeInstanceMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IFreeInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FreeInstanceMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FreeInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.FreeInstanceMetadata; + + /** + * Decodes a FreeInstanceMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FreeInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.FreeInstanceMetadata; + + /** + * Verifies a FreeInstanceMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FreeInstanceMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FreeInstanceMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.FreeInstanceMetadata; + + /** + * Creates a plain object from a FreeInstanceMetadata message. Also converts values to other types if specified. + * @param message FreeInstanceMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.FreeInstanceMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FreeInstanceMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FreeInstanceMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FreeInstanceMetadata { + + /** ExpireBehavior enum. */ + enum ExpireBehavior { + EXPIRE_BEHAVIOR_UNSPECIFIED = 0, + FREE_TO_PROVISIONED = 1, + REMOVE_AFTER_GRACE_PERIOD = 2 + } + } + + /** Properties of a CreateInstanceConfigMetadata. */ + interface ICreateInstanceConfigMetadata { + + /** CreateInstanceConfigMetadata instanceConfig */ + instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** CreateInstanceConfigMetadata progress */ + progress?: (google.spanner.admin.instance.v1.IOperationProgress|null); + + /** CreateInstanceConfigMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CreateInstanceConfigMetadata. */ + class CreateInstanceConfigMetadata implements ICreateInstanceConfigMetadata { + + /** + * Constructs a new CreateInstanceConfigMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata); + + /** CreateInstanceConfigMetadata instanceConfig. */ + public instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** CreateInstanceConfigMetadata progress. */ + public progress?: (google.spanner.admin.instance.v1.IOperationProgress|null); + + /** CreateInstanceConfigMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new CreateInstanceConfigMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateInstanceConfigMetadata instance + */ + public static create(properties?: google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata): google.spanner.admin.instance.v1.CreateInstanceConfigMetadata; + + /** + * Encodes the specified CreateInstanceConfigMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceConfigMetadata.verify|verify} messages. + * @param message CreateInstanceConfigMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateInstanceConfigMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceConfigMetadata.verify|verify} messages. + * @param message CreateInstanceConfigMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateInstanceConfigMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateInstanceConfigMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.CreateInstanceConfigMetadata; + + /** + * Decodes a CreateInstanceConfigMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateInstanceConfigMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.CreateInstanceConfigMetadata; + + /** + * Verifies a CreateInstanceConfigMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateInstanceConfigMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateInstanceConfigMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.CreateInstanceConfigMetadata; + + /** + * Creates a plain object from a CreateInstanceConfigMetadata message. Also converts values to other types if specified. + * @param message CreateInstanceConfigMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.CreateInstanceConfigMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateInstanceConfigMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateInstanceConfigMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateInstanceConfigMetadata. */ + interface IUpdateInstanceConfigMetadata { + + /** UpdateInstanceConfigMetadata instanceConfig */ + instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** UpdateInstanceConfigMetadata progress */ + progress?: (google.spanner.admin.instance.v1.IOperationProgress|null); + + /** UpdateInstanceConfigMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UpdateInstanceConfigMetadata. */ + class UpdateInstanceConfigMetadata implements IUpdateInstanceConfigMetadata { + + /** + * Constructs a new UpdateInstanceConfigMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata); + + /** UpdateInstanceConfigMetadata instanceConfig. */ + public instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** UpdateInstanceConfigMetadata progress. */ + public progress?: (google.spanner.admin.instance.v1.IOperationProgress|null); + + /** UpdateInstanceConfigMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new UpdateInstanceConfigMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateInstanceConfigMetadata instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata): google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata; + + /** + * Encodes the specified UpdateInstanceConfigMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.verify|verify} messages. + * @param message UpdateInstanceConfigMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateInstanceConfigMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.verify|verify} messages. + * @param message UpdateInstanceConfigMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateInstanceConfigMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateInstanceConfigMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata; + + /** + * Decodes an UpdateInstanceConfigMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateInstanceConfigMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata; + + /** + * Verifies an UpdateInstanceConfigMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateInstanceConfigMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateInstanceConfigMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata; + + /** + * Creates a plain object from an UpdateInstanceConfigMetadata message. Also converts values to other types if specified. + * @param message UpdateInstanceConfigMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateInstanceConfigMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateInstanceConfigMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an InstancePartition. */ + interface IInstancePartition { + + /** InstancePartition name */ + name?: (string|null); + + /** InstancePartition config */ + config?: (string|null); + + /** InstancePartition displayName */ + displayName?: (string|null); + + /** InstancePartition nodeCount */ + nodeCount?: (number|null); + + /** InstancePartition processingUnits */ + processingUnits?: (number|null); + + /** InstancePartition autoscalingConfig */ + autoscalingConfig?: (google.spanner.admin.instance.v1.IAutoscalingConfig|null); + + /** InstancePartition state */ + state?: (google.spanner.admin.instance.v1.InstancePartition.State|keyof typeof google.spanner.admin.instance.v1.InstancePartition.State|null); + + /** InstancePartition createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** InstancePartition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** InstancePartition referencingDatabases */ + referencingDatabases?: (string[]|null); + + /** InstancePartition referencingBackups */ + referencingBackups?: (string[]|null); + + /** InstancePartition etag */ + etag?: (string|null); + } + + /** Represents an InstancePartition. */ + class InstancePartition implements IInstancePartition { + + /** + * Constructs a new InstancePartition. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IInstancePartition); + + /** InstancePartition name. */ + public name: string; + + /** InstancePartition config. */ + public config: string; + + /** InstancePartition displayName. */ + public displayName: string; + + /** InstancePartition nodeCount. */ + public nodeCount?: (number|null); + + /** InstancePartition processingUnits. */ + public processingUnits?: (number|null); + + /** InstancePartition autoscalingConfig. */ + public autoscalingConfig?: (google.spanner.admin.instance.v1.IAutoscalingConfig|null); + + /** InstancePartition state. */ + public state: (google.spanner.admin.instance.v1.InstancePartition.State|keyof typeof google.spanner.admin.instance.v1.InstancePartition.State); + + /** InstancePartition createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** InstancePartition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** InstancePartition referencingDatabases. */ + public referencingDatabases: string[]; + + /** InstancePartition referencingBackups. */ + public referencingBackups: string[]; + + /** InstancePartition etag. */ + public etag: string; + + /** InstancePartition computeCapacity. */ + public computeCapacity?: ("nodeCount"|"processingUnits"); + + /** + * Creates a new InstancePartition instance using the specified properties. + * @param [properties] Properties to set + * @returns InstancePartition instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IInstancePartition): google.spanner.admin.instance.v1.InstancePartition; + + /** + * Encodes the specified InstancePartition message. Does not implicitly {@link google.spanner.admin.instance.v1.InstancePartition.verify|verify} messages. + * @param message InstancePartition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IInstancePartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstancePartition message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.InstancePartition.verify|verify} messages. + * @param message InstancePartition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IInstancePartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstancePartition message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstancePartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.InstancePartition; + + /** + * Decodes an InstancePartition message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstancePartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.InstancePartition; + + /** + * Verifies an InstancePartition message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstancePartition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstancePartition + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.InstancePartition; + + /** + * Creates a plain object from an InstancePartition message. Also converts values to other types if specified. + * @param message InstancePartition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.InstancePartition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstancePartition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstancePartition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace InstancePartition { + + /** State enum. */ + enum State { + STATE_UNSPECIFIED = 0, + CREATING = 1, + READY = 2 + } + } + + /** Properties of a CreateInstancePartitionMetadata. */ + interface ICreateInstancePartitionMetadata { + + /** CreateInstancePartitionMetadata instancePartition */ + instancePartition?: (google.spanner.admin.instance.v1.IInstancePartition|null); + + /** CreateInstancePartitionMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstancePartitionMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstancePartitionMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CreateInstancePartitionMetadata. */ + class CreateInstancePartitionMetadata implements ICreateInstancePartitionMetadata { + + /** + * Constructs a new CreateInstancePartitionMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata); + + /** CreateInstancePartitionMetadata instancePartition. */ + public instancePartition?: (google.spanner.admin.instance.v1.IInstancePartition|null); + + /** CreateInstancePartitionMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstancePartitionMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** CreateInstancePartitionMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new CreateInstancePartitionMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateInstancePartitionMetadata instance + */ + public static create(properties?: google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata): google.spanner.admin.instance.v1.CreateInstancePartitionMetadata; + + /** + * Encodes the specified CreateInstancePartitionMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstancePartitionMetadata.verify|verify} messages. + * @param message CreateInstancePartitionMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateInstancePartitionMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstancePartitionMetadata.verify|verify} messages. + * @param message CreateInstancePartitionMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateInstancePartitionMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateInstancePartitionMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.CreateInstancePartitionMetadata; + + /** + * Decodes a CreateInstancePartitionMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateInstancePartitionMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.CreateInstancePartitionMetadata; + + /** + * Verifies a CreateInstancePartitionMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateInstancePartitionMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateInstancePartitionMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.CreateInstancePartitionMetadata; + + /** + * Creates a plain object from a CreateInstancePartitionMetadata message. Also converts values to other types if specified. + * @param message CreateInstancePartitionMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.CreateInstancePartitionMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateInstancePartitionMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateInstancePartitionMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateInstancePartitionRequest. */ + interface ICreateInstancePartitionRequest { + + /** CreateInstancePartitionRequest parent */ + parent?: (string|null); + + /** CreateInstancePartitionRequest instancePartitionId */ + instancePartitionId?: (string|null); + + /** CreateInstancePartitionRequest instancePartition */ + instancePartition?: (google.spanner.admin.instance.v1.IInstancePartition|null); + } + + /** Represents a CreateInstancePartitionRequest. */ + class CreateInstancePartitionRequest implements ICreateInstancePartitionRequest { + + /** + * Constructs a new CreateInstancePartitionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.ICreateInstancePartitionRequest); + + /** CreateInstancePartitionRequest parent. */ + public parent: string; + + /** CreateInstancePartitionRequest instancePartitionId. */ + public instancePartitionId: string; + + /** CreateInstancePartitionRequest instancePartition. */ + public instancePartition?: (google.spanner.admin.instance.v1.IInstancePartition|null); + + /** + * Creates a new CreateInstancePartitionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateInstancePartitionRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.ICreateInstancePartitionRequest): google.spanner.admin.instance.v1.CreateInstancePartitionRequest; + + /** + * Encodes the specified CreateInstancePartitionRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstancePartitionRequest.verify|verify} messages. + * @param message CreateInstancePartitionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.ICreateInstancePartitionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateInstancePartitionRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstancePartitionRequest.verify|verify} messages. + * @param message CreateInstancePartitionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.ICreateInstancePartitionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateInstancePartitionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.CreateInstancePartitionRequest; + + /** + * Decodes a CreateInstancePartitionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.CreateInstancePartitionRequest; + + /** + * Verifies a CreateInstancePartitionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateInstancePartitionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateInstancePartitionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.CreateInstancePartitionRequest; + + /** + * Creates a plain object from a CreateInstancePartitionRequest message. Also converts values to other types if specified. + * @param message CreateInstancePartitionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.CreateInstancePartitionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateInstancePartitionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateInstancePartitionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteInstancePartitionRequest. */ + interface IDeleteInstancePartitionRequest { + + /** DeleteInstancePartitionRequest name */ + name?: (string|null); + + /** DeleteInstancePartitionRequest etag */ + etag?: (string|null); + } + + /** Represents a DeleteInstancePartitionRequest. */ + class DeleteInstancePartitionRequest implements IDeleteInstancePartitionRequest { + + /** + * Constructs a new DeleteInstancePartitionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest); + + /** DeleteInstancePartitionRequest name. */ + public name: string; + + /** DeleteInstancePartitionRequest etag. */ + public etag: string; + + /** + * Creates a new DeleteInstancePartitionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteInstancePartitionRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest): google.spanner.admin.instance.v1.DeleteInstancePartitionRequest; + + /** + * Encodes the specified DeleteInstancePartitionRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstancePartitionRequest.verify|verify} messages. + * @param message DeleteInstancePartitionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteInstancePartitionRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstancePartitionRequest.verify|verify} messages. + * @param message DeleteInstancePartitionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteInstancePartitionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.DeleteInstancePartitionRequest; + + /** + * Decodes a DeleteInstancePartitionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.DeleteInstancePartitionRequest; + + /** + * Verifies a DeleteInstancePartitionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteInstancePartitionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteInstancePartitionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.DeleteInstancePartitionRequest; + + /** + * Creates a plain object from a DeleteInstancePartitionRequest message. Also converts values to other types if specified. + * @param message DeleteInstancePartitionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.DeleteInstancePartitionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteInstancePartitionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteInstancePartitionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetInstancePartitionRequest. */ + interface IGetInstancePartitionRequest { + + /** GetInstancePartitionRequest name */ + name?: (string|null); + } + + /** Represents a GetInstancePartitionRequest. */ + class GetInstancePartitionRequest implements IGetInstancePartitionRequest { + + /** + * Constructs a new GetInstancePartitionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IGetInstancePartitionRequest); + + /** GetInstancePartitionRequest name. */ + public name: string; + + /** + * Creates a new GetInstancePartitionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetInstancePartitionRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IGetInstancePartitionRequest): google.spanner.admin.instance.v1.GetInstancePartitionRequest; + + /** + * Encodes the specified GetInstancePartitionRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstancePartitionRequest.verify|verify} messages. + * @param message GetInstancePartitionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IGetInstancePartitionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetInstancePartitionRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstancePartitionRequest.verify|verify} messages. + * @param message GetInstancePartitionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IGetInstancePartitionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetInstancePartitionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.GetInstancePartitionRequest; + + /** + * Decodes a GetInstancePartitionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.GetInstancePartitionRequest; + + /** + * Verifies a GetInstancePartitionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetInstancePartitionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetInstancePartitionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.GetInstancePartitionRequest; + + /** + * Creates a plain object from a GetInstancePartitionRequest message. Also converts values to other types if specified. + * @param message GetInstancePartitionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.GetInstancePartitionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetInstancePartitionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetInstancePartitionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateInstancePartitionRequest. */ + interface IUpdateInstancePartitionRequest { + + /** UpdateInstancePartitionRequest instancePartition */ + instancePartition?: (google.spanner.admin.instance.v1.IInstancePartition|null); + + /** UpdateInstancePartitionRequest fieldMask */ + fieldMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateInstancePartitionRequest. */ + class UpdateInstancePartitionRequest implements IUpdateInstancePartitionRequest { + + /** + * Constructs a new UpdateInstancePartitionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest); + + /** UpdateInstancePartitionRequest instancePartition. */ + public instancePartition?: (google.spanner.admin.instance.v1.IInstancePartition|null); + + /** UpdateInstancePartitionRequest fieldMask. */ + public fieldMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new UpdateInstancePartitionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateInstancePartitionRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest): google.spanner.admin.instance.v1.UpdateInstancePartitionRequest; + + /** + * Encodes the specified UpdateInstancePartitionRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstancePartitionRequest.verify|verify} messages. + * @param message UpdateInstancePartitionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateInstancePartitionRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstancePartitionRequest.verify|verify} messages. + * @param message UpdateInstancePartitionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateInstancePartitionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.UpdateInstancePartitionRequest; + + /** + * Decodes an UpdateInstancePartitionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.UpdateInstancePartitionRequest; + + /** + * Verifies an UpdateInstancePartitionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateInstancePartitionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateInstancePartitionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.UpdateInstancePartitionRequest; + + /** + * Creates a plain object from an UpdateInstancePartitionRequest message. Also converts values to other types if specified. + * @param message UpdateInstancePartitionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.UpdateInstancePartitionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateInstancePartitionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateInstancePartitionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateInstancePartitionMetadata. */ + interface IUpdateInstancePartitionMetadata { + + /** UpdateInstancePartitionMetadata instancePartition */ + instancePartition?: (google.spanner.admin.instance.v1.IInstancePartition|null); + + /** UpdateInstancePartitionMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstancePartitionMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstancePartitionMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UpdateInstancePartitionMetadata. */ + class UpdateInstancePartitionMetadata implements IUpdateInstancePartitionMetadata { + + /** + * Constructs a new UpdateInstancePartitionMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata); + + /** UpdateInstancePartitionMetadata instancePartition. */ + public instancePartition?: (google.spanner.admin.instance.v1.IInstancePartition|null); + + /** UpdateInstancePartitionMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstancePartitionMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** UpdateInstancePartitionMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new UpdateInstancePartitionMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateInstancePartitionMetadata instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata): google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata; + + /** + * Encodes the specified UpdateInstancePartitionMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.verify|verify} messages. + * @param message UpdateInstancePartitionMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateInstancePartitionMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.verify|verify} messages. + * @param message UpdateInstancePartitionMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateInstancePartitionMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateInstancePartitionMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata; + + /** + * Decodes an UpdateInstancePartitionMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateInstancePartitionMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata; + + /** + * Verifies an UpdateInstancePartitionMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateInstancePartitionMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateInstancePartitionMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata; + + /** + * Creates a plain object from an UpdateInstancePartitionMetadata message. Also converts values to other types if specified. + * @param message UpdateInstancePartitionMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateInstancePartitionMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateInstancePartitionMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstancePartitionsRequest. */ + interface IListInstancePartitionsRequest { + + /** ListInstancePartitionsRequest parent */ + parent?: (string|null); + + /** ListInstancePartitionsRequest pageSize */ + pageSize?: (number|null); + + /** ListInstancePartitionsRequest pageToken */ + pageToken?: (string|null); + + /** ListInstancePartitionsRequest instancePartitionDeadline */ + instancePartitionDeadline?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListInstancePartitionsRequest. */ + class ListInstancePartitionsRequest implements IListInstancePartitionsRequest { + + /** + * Constructs a new ListInstancePartitionsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstancePartitionsRequest); + + /** ListInstancePartitionsRequest parent. */ + public parent: string; + + /** ListInstancePartitionsRequest pageSize. */ + public pageSize: number; + + /** ListInstancePartitionsRequest pageToken. */ + public pageToken: string; + + /** ListInstancePartitionsRequest instancePartitionDeadline. */ + public instancePartitionDeadline?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new ListInstancePartitionsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstancePartitionsRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstancePartitionsRequest): google.spanner.admin.instance.v1.ListInstancePartitionsRequest; + + /** + * Encodes the specified ListInstancePartitionsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionsRequest.verify|verify} messages. + * @param message ListInstancePartitionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstancePartitionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstancePartitionsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionsRequest.verify|verify} messages. + * @param message ListInstancePartitionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstancePartitionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstancePartitionsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstancePartitionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstancePartitionsRequest; + + /** + * Decodes a ListInstancePartitionsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstancePartitionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstancePartitionsRequest; + + /** + * Verifies a ListInstancePartitionsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstancePartitionsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstancePartitionsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstancePartitionsRequest; + + /** + * Creates a plain object from a ListInstancePartitionsRequest message. Also converts values to other types if specified. + * @param message ListInstancePartitionsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstancePartitionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstancePartitionsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstancePartitionsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstancePartitionsResponse. */ + interface IListInstancePartitionsResponse { + + /** ListInstancePartitionsResponse instancePartitions */ + instancePartitions?: (google.spanner.admin.instance.v1.IInstancePartition[]|null); + + /** ListInstancePartitionsResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListInstancePartitionsResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListInstancePartitionsResponse. */ + class ListInstancePartitionsResponse implements IListInstancePartitionsResponse { + + /** + * Constructs a new ListInstancePartitionsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstancePartitionsResponse); + + /** ListInstancePartitionsResponse instancePartitions. */ + public instancePartitions: google.spanner.admin.instance.v1.IInstancePartition[]; + + /** ListInstancePartitionsResponse nextPageToken. */ + public nextPageToken: string; + + /** ListInstancePartitionsResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a new ListInstancePartitionsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstancePartitionsResponse instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstancePartitionsResponse): google.spanner.admin.instance.v1.ListInstancePartitionsResponse; + + /** + * Encodes the specified ListInstancePartitionsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionsResponse.verify|verify} messages. + * @param message ListInstancePartitionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstancePartitionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstancePartitionsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionsResponse.verify|verify} messages. + * @param message ListInstancePartitionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstancePartitionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstancePartitionsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstancePartitionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstancePartitionsResponse; + + /** + * Decodes a ListInstancePartitionsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstancePartitionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstancePartitionsResponse; + + /** + * Verifies a ListInstancePartitionsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstancePartitionsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstancePartitionsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstancePartitionsResponse; + + /** + * Creates a plain object from a ListInstancePartitionsResponse message. Also converts values to other types if specified. + * @param message ListInstancePartitionsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstancePartitionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstancePartitionsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstancePartitionsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstancePartitionOperationsRequest. */ + interface IListInstancePartitionOperationsRequest { + + /** ListInstancePartitionOperationsRequest parent */ + parent?: (string|null); + + /** ListInstancePartitionOperationsRequest filter */ + filter?: (string|null); + + /** ListInstancePartitionOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListInstancePartitionOperationsRequest pageToken */ + pageToken?: (string|null); + + /** ListInstancePartitionOperationsRequest instancePartitionDeadline */ + instancePartitionDeadline?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListInstancePartitionOperationsRequest. */ + class ListInstancePartitionOperationsRequest implements IListInstancePartitionOperationsRequest { + + /** + * Constructs a new ListInstancePartitionOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest); + + /** ListInstancePartitionOperationsRequest parent. */ + public parent: string; + + /** ListInstancePartitionOperationsRequest filter. */ + public filter: string; + + /** ListInstancePartitionOperationsRequest pageSize. */ + public pageSize: number; + + /** ListInstancePartitionOperationsRequest pageToken. */ + public pageToken: string; + + /** ListInstancePartitionOperationsRequest instancePartitionDeadline. */ + public instancePartitionDeadline?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new ListInstancePartitionOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstancePartitionOperationsRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest): google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest; + + /** + * Encodes the specified ListInstancePartitionOperationsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest.verify|verify} messages. + * @param message ListInstancePartitionOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstancePartitionOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest.verify|verify} messages. + * @param message ListInstancePartitionOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstancePartitionOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstancePartitionOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest; + + /** + * Decodes a ListInstancePartitionOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstancePartitionOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest; + + /** + * Verifies a ListInstancePartitionOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstancePartitionOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstancePartitionOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest; + + /** + * Creates a plain object from a ListInstancePartitionOperationsRequest message. Also converts values to other types if specified. + * @param message ListInstancePartitionOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstancePartitionOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstancePartitionOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstancePartitionOperationsResponse. */ + interface IListInstancePartitionOperationsResponse { + + /** ListInstancePartitionOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListInstancePartitionOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ListInstancePartitionOperationsResponse unreachableInstancePartitions */ + unreachableInstancePartitions?: (string[]|null); + } + + /** Represents a ListInstancePartitionOperationsResponse. */ + class ListInstancePartitionOperationsResponse implements IListInstancePartitionOperationsResponse { + + /** + * Constructs a new ListInstancePartitionOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse); + + /** ListInstancePartitionOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListInstancePartitionOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** ListInstancePartitionOperationsResponse unreachableInstancePartitions. */ + public unreachableInstancePartitions: string[]; + + /** + * Creates a new ListInstancePartitionOperationsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstancePartitionOperationsResponse instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse): google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse; + + /** + * Encodes the specified ListInstancePartitionOperationsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.verify|verify} messages. + * @param message ListInstancePartitionOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstancePartitionOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.verify|verify} messages. + * @param message ListInstancePartitionOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstancePartitionOperationsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstancePartitionOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse; + + /** + * Decodes a ListInstancePartitionOperationsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstancePartitionOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse; + + /** + * Verifies a ListInstancePartitionOperationsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstancePartitionOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstancePartitionOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse; + + /** + * Creates a plain object from a ListInstancePartitionOperationsResponse message. Also converts values to other types if specified. + * @param message ListInstancePartitionOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstancePartitionOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstancePartitionOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MoveInstanceRequest. */ + interface IMoveInstanceRequest { + + /** MoveInstanceRequest name */ + name?: (string|null); + + /** MoveInstanceRequest targetConfig */ + targetConfig?: (string|null); + } + + /** Represents a MoveInstanceRequest. */ + class MoveInstanceRequest implements IMoveInstanceRequest { + + /** + * Constructs a new MoveInstanceRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IMoveInstanceRequest); + + /** MoveInstanceRequest name. */ + public name: string; + + /** MoveInstanceRequest targetConfig. */ + public targetConfig: string; + + /** + * Creates a new MoveInstanceRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns MoveInstanceRequest instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IMoveInstanceRequest): google.spanner.admin.instance.v1.MoveInstanceRequest; + + /** + * Encodes the specified MoveInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceRequest.verify|verify} messages. + * @param message MoveInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IMoveInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MoveInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceRequest.verify|verify} messages. + * @param message MoveInstanceRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IMoveInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MoveInstanceRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MoveInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.MoveInstanceRequest; + + /** + * Decodes a MoveInstanceRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MoveInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.MoveInstanceRequest; + + /** + * Verifies a MoveInstanceRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MoveInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MoveInstanceRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.MoveInstanceRequest; + + /** + * Creates a plain object from a MoveInstanceRequest message. Also converts values to other types if specified. + * @param message MoveInstanceRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.MoveInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MoveInstanceRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MoveInstanceRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MoveInstanceResponse. */ + interface IMoveInstanceResponse { + } + + /** Represents a MoveInstanceResponse. */ + class MoveInstanceResponse implements IMoveInstanceResponse { + + /** + * Constructs a new MoveInstanceResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IMoveInstanceResponse); + + /** + * Creates a new MoveInstanceResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns MoveInstanceResponse instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IMoveInstanceResponse): google.spanner.admin.instance.v1.MoveInstanceResponse; + + /** + * Encodes the specified MoveInstanceResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceResponse.verify|verify} messages. + * @param message MoveInstanceResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IMoveInstanceResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MoveInstanceResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceResponse.verify|verify} messages. + * @param message MoveInstanceResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IMoveInstanceResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MoveInstanceResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MoveInstanceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.MoveInstanceResponse; + + /** + * Decodes a MoveInstanceResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MoveInstanceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.MoveInstanceResponse; + + /** + * Verifies a MoveInstanceResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MoveInstanceResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MoveInstanceResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.MoveInstanceResponse; + + /** + * Creates a plain object from a MoveInstanceResponse message. Also converts values to other types if specified. + * @param message MoveInstanceResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.MoveInstanceResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MoveInstanceResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MoveInstanceResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MoveInstanceMetadata. */ + interface IMoveInstanceMetadata { + + /** MoveInstanceMetadata targetConfig */ + targetConfig?: (string|null); + + /** MoveInstanceMetadata progress */ + progress?: (google.spanner.admin.instance.v1.IOperationProgress|null); + + /** MoveInstanceMetadata cancelTime */ + cancelTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a MoveInstanceMetadata. */ + class MoveInstanceMetadata implements IMoveInstanceMetadata { + + /** + * Constructs a new MoveInstanceMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.admin.instance.v1.IMoveInstanceMetadata); + + /** MoveInstanceMetadata targetConfig. */ + public targetConfig: string; + + /** MoveInstanceMetadata progress. */ + public progress?: (google.spanner.admin.instance.v1.IOperationProgress|null); + + /** MoveInstanceMetadata cancelTime. */ + public cancelTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new MoveInstanceMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns MoveInstanceMetadata instance + */ + public static create(properties?: google.spanner.admin.instance.v1.IMoveInstanceMetadata): google.spanner.admin.instance.v1.MoveInstanceMetadata; + + /** + * Encodes the specified MoveInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceMetadata.verify|verify} messages. + * @param message MoveInstanceMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.admin.instance.v1.IMoveInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MoveInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceMetadata.verify|verify} messages. + * @param message MoveInstanceMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.admin.instance.v1.IMoveInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MoveInstanceMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MoveInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.MoveInstanceMetadata; + + /** + * Decodes a MoveInstanceMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MoveInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.MoveInstanceMetadata; + + /** + * Verifies a MoveInstanceMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MoveInstanceMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MoveInstanceMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.MoveInstanceMetadata; + + /** + * Creates a plain object from a MoveInstanceMetadata message. Also converts values to other types if specified. + * @param message MoveInstanceMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.admin.instance.v1.MoveInstanceMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MoveInstanceMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MoveInstanceMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + } + + /** Namespace executor. */ + namespace executor { + + /** Namespace v1. */ + namespace v1 { + + /** Represents a SpannerExecutorProxy */ + class SpannerExecutorProxy extends $protobuf.rpc.Service { + + /** + * Constructs a new SpannerExecutorProxy service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new SpannerExecutorProxy service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): SpannerExecutorProxy; + + /** + * Calls ExecuteActionAsync. + * @param request SpannerAsyncActionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and SpannerAsyncActionResponse + */ + public executeActionAsync(request: google.spanner.executor.v1.ISpannerAsyncActionRequest, callback: google.spanner.executor.v1.SpannerExecutorProxy.ExecuteActionAsyncCallback): void; + + /** + * Calls ExecuteActionAsync. + * @param request SpannerAsyncActionRequest message or plain object + * @returns Promise + */ + public executeActionAsync(request: google.spanner.executor.v1.ISpannerAsyncActionRequest): Promise; + } + + namespace SpannerExecutorProxy { + + /** + * Callback as used by {@link google.spanner.executor.v1.SpannerExecutorProxy|executeActionAsync}. + * @param error Error, if any + * @param [response] SpannerAsyncActionResponse + */ + type ExecuteActionAsyncCallback = (error: (Error|null), response?: google.spanner.executor.v1.SpannerAsyncActionResponse) => void; + } + + /** Properties of a SpannerAsyncActionRequest. */ + interface ISpannerAsyncActionRequest { + + /** SpannerAsyncActionRequest actionId */ + actionId?: (number|null); + + /** SpannerAsyncActionRequest action */ + action?: (google.spanner.executor.v1.ISpannerAction|null); + } + + /** Represents a SpannerAsyncActionRequest. */ + class SpannerAsyncActionRequest implements ISpannerAsyncActionRequest { + + /** + * Constructs a new SpannerAsyncActionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ISpannerAsyncActionRequest); + + /** SpannerAsyncActionRequest actionId. */ + public actionId: number; + + /** SpannerAsyncActionRequest action. */ + public action?: (google.spanner.executor.v1.ISpannerAction|null); + + /** + * Creates a new SpannerAsyncActionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns SpannerAsyncActionRequest instance + */ + public static create(properties?: google.spanner.executor.v1.ISpannerAsyncActionRequest): google.spanner.executor.v1.SpannerAsyncActionRequest; + + /** + * Encodes the specified SpannerAsyncActionRequest message. Does not implicitly {@link google.spanner.executor.v1.SpannerAsyncActionRequest.verify|verify} messages. + * @param message SpannerAsyncActionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ISpannerAsyncActionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SpannerAsyncActionRequest message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerAsyncActionRequest.verify|verify} messages. + * @param message SpannerAsyncActionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ISpannerAsyncActionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SpannerAsyncActionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SpannerAsyncActionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.SpannerAsyncActionRequest; + + /** + * Decodes a SpannerAsyncActionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SpannerAsyncActionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.SpannerAsyncActionRequest; + + /** + * Verifies a SpannerAsyncActionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SpannerAsyncActionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SpannerAsyncActionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.SpannerAsyncActionRequest; + + /** + * Creates a plain object from a SpannerAsyncActionRequest message. Also converts values to other types if specified. + * @param message SpannerAsyncActionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.SpannerAsyncActionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SpannerAsyncActionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SpannerAsyncActionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SpannerAsyncActionResponse. */ + interface ISpannerAsyncActionResponse { + + /** SpannerAsyncActionResponse actionId */ + actionId?: (number|null); + + /** SpannerAsyncActionResponse outcome */ + outcome?: (google.spanner.executor.v1.ISpannerActionOutcome|null); + } + + /** Represents a SpannerAsyncActionResponse. */ + class SpannerAsyncActionResponse implements ISpannerAsyncActionResponse { + + /** + * Constructs a new SpannerAsyncActionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ISpannerAsyncActionResponse); + + /** SpannerAsyncActionResponse actionId. */ + public actionId: number; + + /** SpannerAsyncActionResponse outcome. */ + public outcome?: (google.spanner.executor.v1.ISpannerActionOutcome|null); + + /** + * Creates a new SpannerAsyncActionResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns SpannerAsyncActionResponse instance + */ + public static create(properties?: google.spanner.executor.v1.ISpannerAsyncActionResponse): google.spanner.executor.v1.SpannerAsyncActionResponse; + + /** + * Encodes the specified SpannerAsyncActionResponse message. Does not implicitly {@link google.spanner.executor.v1.SpannerAsyncActionResponse.verify|verify} messages. + * @param message SpannerAsyncActionResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ISpannerAsyncActionResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SpannerAsyncActionResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerAsyncActionResponse.verify|verify} messages. + * @param message SpannerAsyncActionResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ISpannerAsyncActionResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SpannerAsyncActionResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SpannerAsyncActionResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.SpannerAsyncActionResponse; + + /** + * Decodes a SpannerAsyncActionResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SpannerAsyncActionResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.SpannerAsyncActionResponse; + + /** + * Verifies a SpannerAsyncActionResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SpannerAsyncActionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SpannerAsyncActionResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.SpannerAsyncActionResponse; + + /** + * Creates a plain object from a SpannerAsyncActionResponse message. Also converts values to other types if specified. + * @param message SpannerAsyncActionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.SpannerAsyncActionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SpannerAsyncActionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SpannerAsyncActionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SpannerAction. */ + interface ISpannerAction { + + /** SpannerAction databasePath */ + databasePath?: (string|null); + + /** SpannerAction spannerOptions */ + spannerOptions?: (google.spanner.executor.v1.ISpannerOptions|null); + + /** SpannerAction start */ + start?: (google.spanner.executor.v1.IStartTransactionAction|null); + + /** SpannerAction finish */ + finish?: (google.spanner.executor.v1.IFinishTransactionAction|null); + + /** SpannerAction read */ + read?: (google.spanner.executor.v1.IReadAction|null); + + /** SpannerAction query */ + query?: (google.spanner.executor.v1.IQueryAction|null); + + /** SpannerAction mutation */ + mutation?: (google.spanner.executor.v1.IMutationAction|null); + + /** SpannerAction dml */ + dml?: (google.spanner.executor.v1.IDmlAction|null); + + /** SpannerAction batchDml */ + batchDml?: (google.spanner.executor.v1.IBatchDmlAction|null); + + /** SpannerAction write */ + write?: (google.spanner.executor.v1.IWriteMutationsAction|null); + + /** SpannerAction partitionedUpdate */ + partitionedUpdate?: (google.spanner.executor.v1.IPartitionedUpdateAction|null); + + /** SpannerAction admin */ + admin?: (google.spanner.executor.v1.IAdminAction|null); + + /** SpannerAction startBatchTxn */ + startBatchTxn?: (google.spanner.executor.v1.IStartBatchTransactionAction|null); + + /** SpannerAction closeBatchTxn */ + closeBatchTxn?: (google.spanner.executor.v1.ICloseBatchTransactionAction|null); + + /** SpannerAction generateDbPartitionsRead */ + generateDbPartitionsRead?: (google.spanner.executor.v1.IGenerateDbPartitionsForReadAction|null); + + /** SpannerAction generateDbPartitionsQuery */ + generateDbPartitionsQuery?: (google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction|null); + + /** SpannerAction executePartition */ + executePartition?: (google.spanner.executor.v1.IExecutePartitionAction|null); + + /** SpannerAction executeChangeStreamQuery */ + executeChangeStreamQuery?: (google.spanner.executor.v1.IExecuteChangeStreamQuery|null); + + /** SpannerAction queryCancellation */ + queryCancellation?: (google.spanner.executor.v1.IQueryCancellationAction|null); + + /** SpannerAction adaptMessage */ + adaptMessage?: (google.spanner.executor.v1.IAdaptMessageAction|null); + } + + /** Represents a SpannerAction. */ + class SpannerAction implements ISpannerAction { + + /** + * Constructs a new SpannerAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ISpannerAction); + + /** SpannerAction databasePath. */ + public databasePath: string; + + /** SpannerAction spannerOptions. */ + public spannerOptions?: (google.spanner.executor.v1.ISpannerOptions|null); + + /** SpannerAction start. */ + public start?: (google.spanner.executor.v1.IStartTransactionAction|null); + + /** SpannerAction finish. */ + public finish?: (google.spanner.executor.v1.IFinishTransactionAction|null); + + /** SpannerAction read. */ + public read?: (google.spanner.executor.v1.IReadAction|null); + + /** SpannerAction query. */ + public query?: (google.spanner.executor.v1.IQueryAction|null); + + /** SpannerAction mutation. */ + public mutation?: (google.spanner.executor.v1.IMutationAction|null); + + /** SpannerAction dml. */ + public dml?: (google.spanner.executor.v1.IDmlAction|null); + + /** SpannerAction batchDml. */ + public batchDml?: (google.spanner.executor.v1.IBatchDmlAction|null); + + /** SpannerAction write. */ + public write?: (google.spanner.executor.v1.IWriteMutationsAction|null); + + /** SpannerAction partitionedUpdate. */ + public partitionedUpdate?: (google.spanner.executor.v1.IPartitionedUpdateAction|null); + + /** SpannerAction admin. */ + public admin?: (google.spanner.executor.v1.IAdminAction|null); + + /** SpannerAction startBatchTxn. */ + public startBatchTxn?: (google.spanner.executor.v1.IStartBatchTransactionAction|null); + + /** SpannerAction closeBatchTxn. */ + public closeBatchTxn?: (google.spanner.executor.v1.ICloseBatchTransactionAction|null); + + /** SpannerAction generateDbPartitionsRead. */ + public generateDbPartitionsRead?: (google.spanner.executor.v1.IGenerateDbPartitionsForReadAction|null); + + /** SpannerAction generateDbPartitionsQuery. */ + public generateDbPartitionsQuery?: (google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction|null); + + /** SpannerAction executePartition. */ + public executePartition?: (google.spanner.executor.v1.IExecutePartitionAction|null); + + /** SpannerAction executeChangeStreamQuery. */ + public executeChangeStreamQuery?: (google.spanner.executor.v1.IExecuteChangeStreamQuery|null); + + /** SpannerAction queryCancellation. */ + public queryCancellation?: (google.spanner.executor.v1.IQueryCancellationAction|null); + + /** SpannerAction adaptMessage. */ + public adaptMessage?: (google.spanner.executor.v1.IAdaptMessageAction|null); + + /** SpannerAction action. */ + public action?: ("start"|"finish"|"read"|"query"|"mutation"|"dml"|"batchDml"|"write"|"partitionedUpdate"|"admin"|"startBatchTxn"|"closeBatchTxn"|"generateDbPartitionsRead"|"generateDbPartitionsQuery"|"executePartition"|"executeChangeStreamQuery"|"queryCancellation"|"adaptMessage"); + + /** + * Creates a new SpannerAction instance using the specified properties. + * @param [properties] Properties to set + * @returns SpannerAction instance + */ + public static create(properties?: google.spanner.executor.v1.ISpannerAction): google.spanner.executor.v1.SpannerAction; + + /** + * Encodes the specified SpannerAction message. Does not implicitly {@link google.spanner.executor.v1.SpannerAction.verify|verify} messages. + * @param message SpannerAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ISpannerAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SpannerAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerAction.verify|verify} messages. + * @param message SpannerAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ISpannerAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SpannerAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SpannerAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.SpannerAction; + + /** + * Decodes a SpannerAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SpannerAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.SpannerAction; + + /** + * Verifies a SpannerAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SpannerAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SpannerAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.SpannerAction; + + /** + * Creates a plain object from a SpannerAction message. Also converts values to other types if specified. + * @param message SpannerAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.SpannerAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SpannerAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SpannerAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadAction. */ + interface IReadAction { + + /** ReadAction table */ + table?: (string|null); + + /** ReadAction index */ + index?: (string|null); + + /** ReadAction column */ + column?: (string[]|null); + + /** ReadAction keys */ + keys?: (google.spanner.executor.v1.IKeySet|null); + + /** ReadAction limit */ + limit?: (number|null); + } + + /** Represents a ReadAction. */ + class ReadAction implements IReadAction { + + /** + * Constructs a new ReadAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IReadAction); + + /** ReadAction table. */ + public table: string; + + /** ReadAction index. */ + public index?: (string|null); + + /** ReadAction column. */ + public column: string[]; + + /** ReadAction keys. */ + public keys?: (google.spanner.executor.v1.IKeySet|null); + + /** ReadAction limit. */ + public limit: number; + + /** + * Creates a new ReadAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadAction instance + */ + public static create(properties?: google.spanner.executor.v1.IReadAction): google.spanner.executor.v1.ReadAction; + + /** + * Encodes the specified ReadAction message. Does not implicitly {@link google.spanner.executor.v1.ReadAction.verify|verify} messages. + * @param message ReadAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IReadAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ReadAction.verify|verify} messages. + * @param message ReadAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IReadAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ReadAction; + + /** + * Decodes a ReadAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ReadAction; + + /** + * Verifies a ReadAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ReadAction; + + /** + * Creates a plain object from a ReadAction message. Also converts values to other types if specified. + * @param message ReadAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ReadAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryAction. */ + interface IQueryAction { + + /** QueryAction sql */ + sql?: (string|null); + + /** QueryAction params */ + params?: (google.spanner.executor.v1.QueryAction.IParameter[]|null); + } + + /** Represents a QueryAction. */ + class QueryAction implements IQueryAction { + + /** + * Constructs a new QueryAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IQueryAction); + + /** QueryAction sql. */ + public sql: string; + + /** QueryAction params. */ + public params: google.spanner.executor.v1.QueryAction.IParameter[]; + + /** + * Creates a new QueryAction instance using the specified properties. + * @param [properties] Properties to set + * @returns QueryAction instance + */ + public static create(properties?: google.spanner.executor.v1.IQueryAction): google.spanner.executor.v1.QueryAction; + + /** + * Encodes the specified QueryAction message. Does not implicitly {@link google.spanner.executor.v1.QueryAction.verify|verify} messages. + * @param message QueryAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IQueryAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified QueryAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.QueryAction.verify|verify} messages. + * @param message QueryAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IQueryAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a QueryAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns QueryAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.QueryAction; + + /** + * Decodes a QueryAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns QueryAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.QueryAction; + + /** + * Verifies a QueryAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a QueryAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.QueryAction; + + /** + * Creates a plain object from a QueryAction message. Also converts values to other types if specified. + * @param message QueryAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.QueryAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace QueryAction { + + /** Properties of a Parameter. */ + interface IParameter { + + /** Parameter name */ + name?: (string|null); + + /** Parameter type */ + type?: (google.spanner.v1.IType|null); + + /** Parameter value */ + value?: (google.spanner.executor.v1.IValue|null); + } + + /** Represents a Parameter. */ + class Parameter implements IParameter { + + /** + * Constructs a new Parameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.QueryAction.IParameter); + + /** Parameter name. */ + public name: string; + + /** Parameter type. */ + public type?: (google.spanner.v1.IType|null); + + /** Parameter value. */ + public value?: (google.spanner.executor.v1.IValue|null); + + /** + * Creates a new Parameter instance using the specified properties. + * @param [properties] Properties to set + * @returns Parameter instance + */ + public static create(properties?: google.spanner.executor.v1.QueryAction.IParameter): google.spanner.executor.v1.QueryAction.Parameter; + + /** + * Encodes the specified Parameter message. Does not implicitly {@link google.spanner.executor.v1.QueryAction.Parameter.verify|verify} messages. + * @param message Parameter message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.QueryAction.IParameter, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Parameter message, length delimited. Does not implicitly {@link google.spanner.executor.v1.QueryAction.Parameter.verify|verify} messages. + * @param message Parameter message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.QueryAction.IParameter, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Parameter message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Parameter + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.QueryAction.Parameter; + + /** + * Decodes a Parameter message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Parameter + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.QueryAction.Parameter; + + /** + * Verifies a Parameter message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Parameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Parameter + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.QueryAction.Parameter; + + /** + * Creates a plain object from a Parameter message. Also converts values to other types if specified. + * @param message Parameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.QueryAction.Parameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Parameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Parameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a DmlAction. */ + interface IDmlAction { + + /** DmlAction update */ + update?: (google.spanner.executor.v1.IQueryAction|null); + + /** DmlAction autocommitIfSupported */ + autocommitIfSupported?: (boolean|null); + + /** DmlAction lastStatement */ + lastStatement?: (boolean|null); + } + + /** Represents a DmlAction. */ + class DmlAction implements IDmlAction { + + /** + * Constructs a new DmlAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IDmlAction); + + /** DmlAction update. */ + public update?: (google.spanner.executor.v1.IQueryAction|null); + + /** DmlAction autocommitIfSupported. */ + public autocommitIfSupported?: (boolean|null); + + /** DmlAction lastStatement. */ + public lastStatement?: (boolean|null); + + /** + * Creates a new DmlAction instance using the specified properties. + * @param [properties] Properties to set + * @returns DmlAction instance + */ + public static create(properties?: google.spanner.executor.v1.IDmlAction): google.spanner.executor.v1.DmlAction; + + /** + * Encodes the specified DmlAction message. Does not implicitly {@link google.spanner.executor.v1.DmlAction.verify|verify} messages. + * @param message DmlAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IDmlAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DmlAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DmlAction.verify|verify} messages. + * @param message DmlAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IDmlAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DmlAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DmlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.DmlAction; + + /** + * Decodes a DmlAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DmlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.DmlAction; + + /** + * Verifies a DmlAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DmlAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DmlAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.DmlAction; + + /** + * Creates a plain object from a DmlAction message. Also converts values to other types if specified. + * @param message DmlAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.DmlAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DmlAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DmlAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchDmlAction. */ + interface IBatchDmlAction { + + /** BatchDmlAction updates */ + updates?: (google.spanner.executor.v1.IQueryAction[]|null); + + /** BatchDmlAction lastStatements */ + lastStatements?: (boolean|null); + } + + /** Represents a BatchDmlAction. */ + class BatchDmlAction implements IBatchDmlAction { + + /** + * Constructs a new BatchDmlAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IBatchDmlAction); + + /** BatchDmlAction updates. */ + public updates: google.spanner.executor.v1.IQueryAction[]; + + /** BatchDmlAction lastStatements. */ + public lastStatements?: (boolean|null); + + /** + * Creates a new BatchDmlAction instance using the specified properties. + * @param [properties] Properties to set + * @returns BatchDmlAction instance + */ + public static create(properties?: google.spanner.executor.v1.IBatchDmlAction): google.spanner.executor.v1.BatchDmlAction; + + /** + * Encodes the specified BatchDmlAction message. Does not implicitly {@link google.spanner.executor.v1.BatchDmlAction.verify|verify} messages. + * @param message BatchDmlAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IBatchDmlAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BatchDmlAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.BatchDmlAction.verify|verify} messages. + * @param message BatchDmlAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IBatchDmlAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BatchDmlAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BatchDmlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.BatchDmlAction; + + /** + * Decodes a BatchDmlAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BatchDmlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.BatchDmlAction; + + /** + * Verifies a BatchDmlAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BatchDmlAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchDmlAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.BatchDmlAction; + + /** + * Creates a plain object from a BatchDmlAction message. Also converts values to other types if specified. + * @param message BatchDmlAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.BatchDmlAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchDmlAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchDmlAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value isNull */ + isNull?: (boolean|null); + + /** Value intValue */ + intValue?: (number|Long|string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value doubleValue */ + doubleValue?: (number|null); + + /** Value bytesValue */ + bytesValue?: (Uint8Array|Buffer|string|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value structValue */ + structValue?: (google.spanner.executor.v1.IValueList|null); + + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value dateDaysValue */ + dateDaysValue?: (number|null); + + /** Value isCommitTimestamp */ + isCommitTimestamp?: (boolean|null); + + /** Value arrayValue */ + arrayValue?: (google.spanner.executor.v1.IValueList|null); + + /** Value arrayType */ + arrayType?: (google.spanner.v1.IType|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IValue); + + /** Value isNull. */ + public isNull?: (boolean|null); + + /** Value intValue. */ + public intValue?: (number|Long|string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value doubleValue. */ + public doubleValue?: (number|null); + + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|Buffer|string|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value structValue. */ + public structValue?: (google.spanner.executor.v1.IValueList|null); + + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); + + /** Value dateDaysValue. */ + public dateDaysValue?: (number|null); + + /** Value isCommitTimestamp. */ + public isCommitTimestamp?: (boolean|null); + + /** Value arrayValue. */ + public arrayValue?: (google.spanner.executor.v1.IValueList|null); + + /** Value arrayType. */ + public arrayType?: (google.spanner.v1.IType|null); + + /** Value valueType. */ + public valueType?: ("isNull"|"intValue"|"boolValue"|"doubleValue"|"bytesValue"|"stringValue"|"structValue"|"timestampValue"|"dateDaysValue"|"isCommitTimestamp"|"arrayValue"); + + /** + * Creates a new Value instance using the specified properties. + * @param [properties] Properties to set + * @returns Value instance + */ + public static create(properties?: google.spanner.executor.v1.IValue): google.spanner.executor.v1.Value; + + /** + * Encodes the specified Value message. Does not implicitly {@link google.spanner.executor.v1.Value.verify|verify} messages. + * @param message Value message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IValue, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Value message, length delimited. Does not implicitly {@link google.spanner.executor.v1.Value.verify|verify} messages. + * @param message Value message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IValue, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Value message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Value + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.Value; + + /** + * Decodes a Value message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Value + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.Value; + + /** + * Verifies a Value message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a KeyRange. */ + interface IKeyRange { + + /** KeyRange start */ + start?: (google.spanner.executor.v1.IValueList|null); + + /** KeyRange limit */ + limit?: (google.spanner.executor.v1.IValueList|null); + + /** KeyRange type */ + type?: (google.spanner.executor.v1.KeyRange.Type|keyof typeof google.spanner.executor.v1.KeyRange.Type|null); + } + + /** Represents a KeyRange. */ + class KeyRange implements IKeyRange { + + /** + * Constructs a new KeyRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IKeyRange); + + /** KeyRange start. */ + public start?: (google.spanner.executor.v1.IValueList|null); + + /** KeyRange limit. */ + public limit?: (google.spanner.executor.v1.IValueList|null); + + /** KeyRange type. */ + public type?: (google.spanner.executor.v1.KeyRange.Type|keyof typeof google.spanner.executor.v1.KeyRange.Type|null); + + /** + * Creates a new KeyRange instance using the specified properties. + * @param [properties] Properties to set + * @returns KeyRange instance + */ + public static create(properties?: google.spanner.executor.v1.IKeyRange): google.spanner.executor.v1.KeyRange; + + /** + * Encodes the specified KeyRange message. Does not implicitly {@link google.spanner.executor.v1.KeyRange.verify|verify} messages. + * @param message KeyRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IKeyRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified KeyRange message, length delimited. Does not implicitly {@link google.spanner.executor.v1.KeyRange.verify|verify} messages. + * @param message KeyRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IKeyRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a KeyRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns KeyRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.KeyRange; + + /** + * Decodes a KeyRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns KeyRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.KeyRange; + + /** + * Verifies a KeyRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a KeyRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns KeyRange + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.KeyRange; + + /** + * Creates a plain object from a KeyRange message. Also converts values to other types if specified. + * @param message KeyRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.KeyRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this KeyRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for KeyRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace KeyRange { + + /** Type enum. */ + enum Type { + TYPE_UNSPECIFIED = 0, + CLOSED_CLOSED = 1, + CLOSED_OPEN = 2, + OPEN_CLOSED = 3, + OPEN_OPEN = 4 + } + } + + /** Properties of a KeySet. */ + interface IKeySet { + + /** KeySet point */ + point?: (google.spanner.executor.v1.IValueList[]|null); + + /** KeySet range */ + range?: (google.spanner.executor.v1.IKeyRange[]|null); + + /** KeySet all */ + all?: (boolean|null); + } + + /** Represents a KeySet. */ + class KeySet implements IKeySet { + + /** + * Constructs a new KeySet. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IKeySet); + + /** KeySet point. */ + public point: google.spanner.executor.v1.IValueList[]; + + /** KeySet range. */ + public range: google.spanner.executor.v1.IKeyRange[]; + + /** KeySet all. */ + public all: boolean; + + /** + * Creates a new KeySet instance using the specified properties. + * @param [properties] Properties to set + * @returns KeySet instance + */ + public static create(properties?: google.spanner.executor.v1.IKeySet): google.spanner.executor.v1.KeySet; + + /** + * Encodes the specified KeySet message. Does not implicitly {@link google.spanner.executor.v1.KeySet.verify|verify} messages. + * @param message KeySet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IKeySet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified KeySet message, length delimited. Does not implicitly {@link google.spanner.executor.v1.KeySet.verify|verify} messages. + * @param message KeySet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IKeySet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a KeySet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns KeySet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.KeySet; + + /** + * Decodes a KeySet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns KeySet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.KeySet; + + /** + * Verifies a KeySet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a KeySet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns KeySet + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.KeySet; + + /** + * Creates a plain object from a KeySet message. Also converts values to other types if specified. + * @param message KeySet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.KeySet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this KeySet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for KeySet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ValueList. */ + interface IValueList { + + /** ValueList value */ + value?: (google.spanner.executor.v1.IValue[]|null); + } + + /** Represents a ValueList. */ + class ValueList implements IValueList { + + /** + * Constructs a new ValueList. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IValueList); + + /** ValueList value. */ + public value: google.spanner.executor.v1.IValue[]; + + /** + * Creates a new ValueList instance using the specified properties. + * @param [properties] Properties to set + * @returns ValueList instance + */ + public static create(properties?: google.spanner.executor.v1.IValueList): google.spanner.executor.v1.ValueList; + + /** + * Encodes the specified ValueList message. Does not implicitly {@link google.spanner.executor.v1.ValueList.verify|verify} messages. + * @param message ValueList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IValueList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ValueList message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ValueList.verify|verify} messages. + * @param message ValueList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IValueList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ValueList message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ValueList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ValueList; + + /** + * Decodes a ValueList message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ValueList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ValueList; + + /** + * Verifies a ValueList message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ValueList message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ValueList + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ValueList; + + /** + * Creates a plain object from a ValueList message. Also converts values to other types if specified. + * @param message ValueList + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ValueList, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ValueList to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ValueList + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MutationAction. */ + interface IMutationAction { + + /** MutationAction mod */ + mod?: (google.spanner.executor.v1.MutationAction.IMod[]|null); + } + + /** Represents a MutationAction. */ + class MutationAction implements IMutationAction { + + /** + * Constructs a new MutationAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IMutationAction); + + /** MutationAction mod. */ + public mod: google.spanner.executor.v1.MutationAction.IMod[]; + + /** + * Creates a new MutationAction instance using the specified properties. + * @param [properties] Properties to set + * @returns MutationAction instance + */ + public static create(properties?: google.spanner.executor.v1.IMutationAction): google.spanner.executor.v1.MutationAction; + + /** + * Encodes the specified MutationAction message. Does not implicitly {@link google.spanner.executor.v1.MutationAction.verify|verify} messages. + * @param message MutationAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IMutationAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MutationAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.MutationAction.verify|verify} messages. + * @param message MutationAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IMutationAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MutationAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MutationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.MutationAction; + + /** + * Decodes a MutationAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MutationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.MutationAction; + + /** + * Verifies a MutationAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MutationAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MutationAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.MutationAction; + + /** + * Creates a plain object from a MutationAction message. Also converts values to other types if specified. + * @param message MutationAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.MutationAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MutationAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MutationAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MutationAction { + + /** Properties of an InsertArgs. */ + interface IInsertArgs { + + /** InsertArgs column */ + column?: (string[]|null); + + /** InsertArgs type */ + type?: (google.spanner.v1.IType[]|null); + + /** InsertArgs values */ + values?: (google.spanner.executor.v1.IValueList[]|null); + } + + /** Represents an InsertArgs. */ + class InsertArgs implements IInsertArgs { + + /** + * Constructs a new InsertArgs. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.MutationAction.IInsertArgs); + + /** InsertArgs column. */ + public column: string[]; + + /** InsertArgs type. */ + public type: google.spanner.v1.IType[]; + + /** InsertArgs values. */ + public values: google.spanner.executor.v1.IValueList[]; + + /** + * Creates a new InsertArgs instance using the specified properties. + * @param [properties] Properties to set + * @returns InsertArgs instance + */ + public static create(properties?: google.spanner.executor.v1.MutationAction.IInsertArgs): google.spanner.executor.v1.MutationAction.InsertArgs; + + /** + * Encodes the specified InsertArgs message. Does not implicitly {@link google.spanner.executor.v1.MutationAction.InsertArgs.verify|verify} messages. + * @param message InsertArgs message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.MutationAction.IInsertArgs, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InsertArgs message, length delimited. Does not implicitly {@link google.spanner.executor.v1.MutationAction.InsertArgs.verify|verify} messages. + * @param message InsertArgs message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.MutationAction.IInsertArgs, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InsertArgs message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InsertArgs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.MutationAction.InsertArgs; + + /** + * Decodes an InsertArgs message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InsertArgs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.MutationAction.InsertArgs; + + /** + * Verifies an InsertArgs message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InsertArgs message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InsertArgs + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.MutationAction.InsertArgs; + + /** + * Creates a plain object from an InsertArgs message. Also converts values to other types if specified. + * @param message InsertArgs + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.MutationAction.InsertArgs, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InsertArgs to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InsertArgs + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateArgs. */ + interface IUpdateArgs { + + /** UpdateArgs column */ + column?: (string[]|null); + + /** UpdateArgs type */ + type?: (google.spanner.v1.IType[]|null); + + /** UpdateArgs values */ + values?: (google.spanner.executor.v1.IValueList[]|null); + } + + /** Represents an UpdateArgs. */ + class UpdateArgs implements IUpdateArgs { + + /** + * Constructs a new UpdateArgs. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.MutationAction.IUpdateArgs); + + /** UpdateArgs column. */ + public column: string[]; + + /** UpdateArgs type. */ + public type: google.spanner.v1.IType[]; + + /** UpdateArgs values. */ + public values: google.spanner.executor.v1.IValueList[]; + + /** + * Creates a new UpdateArgs instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateArgs instance + */ + public static create(properties?: google.spanner.executor.v1.MutationAction.IUpdateArgs): google.spanner.executor.v1.MutationAction.UpdateArgs; + + /** + * Encodes the specified UpdateArgs message. Does not implicitly {@link google.spanner.executor.v1.MutationAction.UpdateArgs.verify|verify} messages. + * @param message UpdateArgs message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.MutationAction.IUpdateArgs, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateArgs message, length delimited. Does not implicitly {@link google.spanner.executor.v1.MutationAction.UpdateArgs.verify|verify} messages. + * @param message UpdateArgs message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.MutationAction.IUpdateArgs, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateArgs message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateArgs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.MutationAction.UpdateArgs; + + /** + * Decodes an UpdateArgs message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateArgs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.MutationAction.UpdateArgs; + + /** + * Verifies an UpdateArgs message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateArgs message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateArgs + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.MutationAction.UpdateArgs; + + /** + * Creates a plain object from an UpdateArgs message. Also converts values to other types if specified. + * @param message UpdateArgs + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.MutationAction.UpdateArgs, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateArgs to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateArgs + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Mod. */ + interface IMod { + + /** Mod table */ + table?: (string|null); + + /** Mod insert */ + insert?: (google.spanner.executor.v1.MutationAction.IInsertArgs|null); + + /** Mod update */ + update?: (google.spanner.executor.v1.MutationAction.IUpdateArgs|null); + + /** Mod insertOrUpdate */ + insertOrUpdate?: (google.spanner.executor.v1.MutationAction.IInsertArgs|null); + + /** Mod replace */ + replace?: (google.spanner.executor.v1.MutationAction.IInsertArgs|null); + + /** Mod deleteKeys */ + deleteKeys?: (google.spanner.executor.v1.IKeySet|null); + } + + /** Represents a Mod. */ + class Mod implements IMod { + + /** + * Constructs a new Mod. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.MutationAction.IMod); + + /** Mod table. */ + public table: string; + + /** Mod insert. */ + public insert?: (google.spanner.executor.v1.MutationAction.IInsertArgs|null); + + /** Mod update. */ + public update?: (google.spanner.executor.v1.MutationAction.IUpdateArgs|null); + + /** Mod insertOrUpdate. */ + public insertOrUpdate?: (google.spanner.executor.v1.MutationAction.IInsertArgs|null); + + /** Mod replace. */ + public replace?: (google.spanner.executor.v1.MutationAction.IInsertArgs|null); + + /** Mod deleteKeys. */ + public deleteKeys?: (google.spanner.executor.v1.IKeySet|null); + + /** + * Creates a new Mod instance using the specified properties. + * @param [properties] Properties to set + * @returns Mod instance + */ + public static create(properties?: google.spanner.executor.v1.MutationAction.IMod): google.spanner.executor.v1.MutationAction.Mod; + + /** + * Encodes the specified Mod message. Does not implicitly {@link google.spanner.executor.v1.MutationAction.Mod.verify|verify} messages. + * @param message Mod message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.MutationAction.IMod, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Mod message, length delimited. Does not implicitly {@link google.spanner.executor.v1.MutationAction.Mod.verify|verify} messages. + * @param message Mod message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.MutationAction.IMod, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Mod message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.MutationAction.Mod; + + /** + * Decodes a Mod message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.MutationAction.Mod; + + /** + * Verifies a Mod message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Mod message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Mod + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.MutationAction.Mod; + + /** + * Creates a plain object from a Mod message. Also converts values to other types if specified. + * @param message Mod + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.MutationAction.Mod, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Mod to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Mod + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a WriteMutationsAction. */ + interface IWriteMutationsAction { + + /** WriteMutationsAction mutation */ + mutation?: (google.spanner.executor.v1.IMutationAction|null); + } + + /** Represents a WriteMutationsAction. */ + class WriteMutationsAction implements IWriteMutationsAction { + + /** + * Constructs a new WriteMutationsAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IWriteMutationsAction); + + /** WriteMutationsAction mutation. */ + public mutation?: (google.spanner.executor.v1.IMutationAction|null); + + /** + * Creates a new WriteMutationsAction instance using the specified properties. + * @param [properties] Properties to set + * @returns WriteMutationsAction instance + */ + public static create(properties?: google.spanner.executor.v1.IWriteMutationsAction): google.spanner.executor.v1.WriteMutationsAction; + + /** + * Encodes the specified WriteMutationsAction message. Does not implicitly {@link google.spanner.executor.v1.WriteMutationsAction.verify|verify} messages. + * @param message WriteMutationsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IWriteMutationsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WriteMutationsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.WriteMutationsAction.verify|verify} messages. + * @param message WriteMutationsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IWriteMutationsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WriteMutationsAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WriteMutationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.WriteMutationsAction; + + /** + * Decodes a WriteMutationsAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WriteMutationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.WriteMutationsAction; + + /** + * Verifies a WriteMutationsAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WriteMutationsAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteMutationsAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.WriteMutationsAction; + + /** + * Creates a plain object from a WriteMutationsAction message. Also converts values to other types if specified. + * @param message WriteMutationsAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.WriteMutationsAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteMutationsAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteMutationsAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionedUpdateAction. */ + interface IPartitionedUpdateAction { + + /** PartitionedUpdateAction options */ + options?: (google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions|null); + + /** PartitionedUpdateAction update */ + update?: (google.spanner.executor.v1.IQueryAction|null); + } + + /** Represents a PartitionedUpdateAction. */ + class PartitionedUpdateAction implements IPartitionedUpdateAction { + + /** + * Constructs a new PartitionedUpdateAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IPartitionedUpdateAction); + + /** PartitionedUpdateAction options. */ + public options?: (google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions|null); + + /** PartitionedUpdateAction update. */ + public update?: (google.spanner.executor.v1.IQueryAction|null); + + /** + * Creates a new PartitionedUpdateAction instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionedUpdateAction instance + */ + public static create(properties?: google.spanner.executor.v1.IPartitionedUpdateAction): google.spanner.executor.v1.PartitionedUpdateAction; + + /** + * Encodes the specified PartitionedUpdateAction message. Does not implicitly {@link google.spanner.executor.v1.PartitionedUpdateAction.verify|verify} messages. + * @param message PartitionedUpdateAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IPartitionedUpdateAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionedUpdateAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.PartitionedUpdateAction.verify|verify} messages. + * @param message PartitionedUpdateAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IPartitionedUpdateAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionedUpdateAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionedUpdateAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.PartitionedUpdateAction; + + /** + * Decodes a PartitionedUpdateAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionedUpdateAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.PartitionedUpdateAction; + + /** + * Verifies a PartitionedUpdateAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionedUpdateAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionedUpdateAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.PartitionedUpdateAction; + + /** + * Creates a plain object from a PartitionedUpdateAction message. Also converts values to other types if specified. + * @param message PartitionedUpdateAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.PartitionedUpdateAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionedUpdateAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionedUpdateAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PartitionedUpdateAction { + + /** Properties of an ExecutePartitionedUpdateOptions. */ + interface IExecutePartitionedUpdateOptions { + + /** ExecutePartitionedUpdateOptions rpcPriority */ + rpcPriority?: (google.spanner.v1.RequestOptions.Priority|keyof typeof google.spanner.v1.RequestOptions.Priority|null); + + /** ExecutePartitionedUpdateOptions tag */ + tag?: (string|null); + } + + /** Represents an ExecutePartitionedUpdateOptions. */ + class ExecutePartitionedUpdateOptions implements IExecutePartitionedUpdateOptions { + + /** + * Constructs a new ExecutePartitionedUpdateOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions); + + /** ExecutePartitionedUpdateOptions rpcPriority. */ + public rpcPriority?: (google.spanner.v1.RequestOptions.Priority|keyof typeof google.spanner.v1.RequestOptions.Priority|null); + + /** ExecutePartitionedUpdateOptions tag. */ + public tag?: (string|null); + + /** + * Creates a new ExecutePartitionedUpdateOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ExecutePartitionedUpdateOptions instance + */ + public static create(properties?: google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions): google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions; + + /** + * Encodes the specified ExecutePartitionedUpdateOptions message. Does not implicitly {@link google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.verify|verify} messages. + * @param message ExecutePartitionedUpdateOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExecutePartitionedUpdateOptions message, length delimited. Does not implicitly {@link google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.verify|verify} messages. + * @param message ExecutePartitionedUpdateOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExecutePartitionedUpdateOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExecutePartitionedUpdateOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions; + + /** + * Decodes an ExecutePartitionedUpdateOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExecutePartitionedUpdateOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions; + + /** + * Verifies an ExecutePartitionedUpdateOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExecutePartitionedUpdateOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePartitionedUpdateOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions; + + /** + * Creates a plain object from an ExecutePartitionedUpdateOptions message. Also converts values to other types if specified. + * @param message ExecutePartitionedUpdateOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutePartitionedUpdateOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutePartitionedUpdateOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a StartTransactionAction. */ + interface IStartTransactionAction { + + /** StartTransactionAction concurrency */ + concurrency?: (google.spanner.executor.v1.IConcurrency|null); + + /** StartTransactionAction table */ + table?: (google.spanner.executor.v1.ITableMetadata[]|null); + + /** StartTransactionAction transactionSeed */ + transactionSeed?: (string|null); + + /** StartTransactionAction executionOptions */ + executionOptions?: (google.spanner.executor.v1.ITransactionExecutionOptions|null); + } + + /** Represents a StartTransactionAction. */ + class StartTransactionAction implements IStartTransactionAction { + + /** + * Constructs a new StartTransactionAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IStartTransactionAction); + + /** StartTransactionAction concurrency. */ + public concurrency?: (google.spanner.executor.v1.IConcurrency|null); + + /** StartTransactionAction table. */ + public table: google.spanner.executor.v1.ITableMetadata[]; + + /** StartTransactionAction transactionSeed. */ + public transactionSeed: string; + + /** StartTransactionAction executionOptions. */ + public executionOptions?: (google.spanner.executor.v1.ITransactionExecutionOptions|null); + + /** + * Creates a new StartTransactionAction instance using the specified properties. + * @param [properties] Properties to set + * @returns StartTransactionAction instance + */ + public static create(properties?: google.spanner.executor.v1.IStartTransactionAction): google.spanner.executor.v1.StartTransactionAction; + + /** + * Encodes the specified StartTransactionAction message. Does not implicitly {@link google.spanner.executor.v1.StartTransactionAction.verify|verify} messages. + * @param message StartTransactionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IStartTransactionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified StartTransactionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.StartTransactionAction.verify|verify} messages. + * @param message StartTransactionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IStartTransactionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a StartTransactionAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns StartTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.StartTransactionAction; + + /** + * Decodes a StartTransactionAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns StartTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.StartTransactionAction; + + /** + * Verifies a StartTransactionAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a StartTransactionAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StartTransactionAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.StartTransactionAction; + + /** + * Creates a plain object from a StartTransactionAction message. Also converts values to other types if specified. + * @param message StartTransactionAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.StartTransactionAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StartTransactionAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StartTransactionAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Concurrency. */ + interface IConcurrency { + + /** Concurrency stalenessSeconds */ + stalenessSeconds?: (number|null); + + /** Concurrency minReadTimestampMicros */ + minReadTimestampMicros?: (number|Long|string|null); + + /** Concurrency maxStalenessSeconds */ + maxStalenessSeconds?: (number|null); + + /** Concurrency exactTimestampMicros */ + exactTimestampMicros?: (number|Long|string|null); + + /** Concurrency strong */ + strong?: (boolean|null); + + /** Concurrency batch */ + batch?: (boolean|null); + + /** Concurrency snapshotEpochRead */ + snapshotEpochRead?: (boolean|null); + + /** Concurrency snapshotEpochRootTable */ + snapshotEpochRootTable?: (string|null); + + /** Concurrency batchReadTimestampMicros */ + batchReadTimestampMicros?: (number|Long|string|null); + } + + /** Represents a Concurrency. */ + class Concurrency implements IConcurrency { + + /** + * Constructs a new Concurrency. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IConcurrency); + + /** Concurrency stalenessSeconds. */ + public stalenessSeconds?: (number|null); + + /** Concurrency minReadTimestampMicros. */ + public minReadTimestampMicros?: (number|Long|string|null); + + /** Concurrency maxStalenessSeconds. */ + public maxStalenessSeconds?: (number|null); + + /** Concurrency exactTimestampMicros. */ + public exactTimestampMicros?: (number|Long|string|null); + + /** Concurrency strong. */ + public strong?: (boolean|null); + + /** Concurrency batch. */ + public batch?: (boolean|null); + + /** Concurrency snapshotEpochRead. */ + public snapshotEpochRead: boolean; + + /** Concurrency snapshotEpochRootTable. */ + public snapshotEpochRootTable: string; + + /** Concurrency batchReadTimestampMicros. */ + public batchReadTimestampMicros: (number|Long|string); + + /** Concurrency concurrencyMode. */ + public concurrencyMode?: ("stalenessSeconds"|"minReadTimestampMicros"|"maxStalenessSeconds"|"exactTimestampMicros"|"strong"|"batch"); + + /** + * Creates a new Concurrency instance using the specified properties. + * @param [properties] Properties to set + * @returns Concurrency instance + */ + public static create(properties?: google.spanner.executor.v1.IConcurrency): google.spanner.executor.v1.Concurrency; + + /** + * Encodes the specified Concurrency message. Does not implicitly {@link google.spanner.executor.v1.Concurrency.verify|verify} messages. + * @param message Concurrency message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IConcurrency, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Concurrency message, length delimited. Does not implicitly {@link google.spanner.executor.v1.Concurrency.verify|verify} messages. + * @param message Concurrency message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IConcurrency, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Concurrency message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Concurrency + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.Concurrency; + + /** + * Decodes a Concurrency message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Concurrency + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.Concurrency; + + /** + * Verifies a Concurrency message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Concurrency message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Concurrency + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.Concurrency; + + /** + * Creates a plain object from a Concurrency message. Also converts values to other types if specified. + * @param message Concurrency + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.Concurrency, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Concurrency to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Concurrency + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TableMetadata. */ + interface ITableMetadata { + + /** TableMetadata name */ + name?: (string|null); + + /** TableMetadata column */ + column?: (google.spanner.executor.v1.IColumnMetadata[]|null); + + /** TableMetadata keyColumn */ + keyColumn?: (google.spanner.executor.v1.IColumnMetadata[]|null); + } + + /** Represents a TableMetadata. */ + class TableMetadata implements ITableMetadata { + + /** + * Constructs a new TableMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ITableMetadata); + + /** TableMetadata name. */ + public name: string; + + /** TableMetadata column. */ + public column: google.spanner.executor.v1.IColumnMetadata[]; + + /** TableMetadata keyColumn. */ + public keyColumn: google.spanner.executor.v1.IColumnMetadata[]; + + /** + * Creates a new TableMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns TableMetadata instance + */ + public static create(properties?: google.spanner.executor.v1.ITableMetadata): google.spanner.executor.v1.TableMetadata; + + /** + * Encodes the specified TableMetadata message. Does not implicitly {@link google.spanner.executor.v1.TableMetadata.verify|verify} messages. + * @param message TableMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ITableMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TableMetadata message, length delimited. Does not implicitly {@link google.spanner.executor.v1.TableMetadata.verify|verify} messages. + * @param message TableMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ITableMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TableMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TableMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.TableMetadata; + + /** + * Decodes a TableMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TableMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.TableMetadata; + + /** + * Verifies a TableMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TableMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TableMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.TableMetadata; + + /** + * Creates a plain object from a TableMetadata message. Also converts values to other types if specified. + * @param message TableMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.TableMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TableMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TableMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ColumnMetadata. */ + interface IColumnMetadata { + + /** ColumnMetadata name */ + name?: (string|null); + + /** ColumnMetadata type */ + type?: (google.spanner.v1.IType|null); + } + + /** Represents a ColumnMetadata. */ + class ColumnMetadata implements IColumnMetadata { + + /** + * Constructs a new ColumnMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IColumnMetadata); + + /** ColumnMetadata name. */ + public name: string; + + /** ColumnMetadata type. */ + public type?: (google.spanner.v1.IType|null); + + /** + * Creates a new ColumnMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns ColumnMetadata instance + */ + public static create(properties?: google.spanner.executor.v1.IColumnMetadata): google.spanner.executor.v1.ColumnMetadata; + + /** + * Encodes the specified ColumnMetadata message. Does not implicitly {@link google.spanner.executor.v1.ColumnMetadata.verify|verify} messages. + * @param message ColumnMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IColumnMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ColumnMetadata message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ColumnMetadata.verify|verify} messages. + * @param message ColumnMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IColumnMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ColumnMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ColumnMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ColumnMetadata; + + /** + * Decodes a ColumnMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ColumnMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ColumnMetadata; + + /** + * Verifies a ColumnMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ColumnMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ColumnMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ColumnMetadata; + + /** + * Creates a plain object from a ColumnMetadata message. Also converts values to other types if specified. + * @param message ColumnMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ColumnMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ColumnMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ColumnMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TransactionExecutionOptions. */ + interface ITransactionExecutionOptions { + + /** TransactionExecutionOptions optimistic */ + optimistic?: (boolean|null); + + /** TransactionExecutionOptions excludeFromChangeStreams */ + excludeFromChangeStreams?: (boolean|null); + + /** TransactionExecutionOptions serializableOptimistic */ + serializableOptimistic?: (boolean|null); + + /** TransactionExecutionOptions snapshotIsolationOptimistic */ + snapshotIsolationOptimistic?: (boolean|null); + + /** TransactionExecutionOptions snapshotIsolationPessimistic */ + snapshotIsolationPessimistic?: (boolean|null); + + /** TransactionExecutionOptions excludeTxnFromChangeStreams */ + excludeTxnFromChangeStreams?: (boolean|null); + } + + /** Represents a TransactionExecutionOptions. */ + class TransactionExecutionOptions implements ITransactionExecutionOptions { + + /** + * Constructs a new TransactionExecutionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ITransactionExecutionOptions); + + /** TransactionExecutionOptions optimistic. */ + public optimistic: boolean; + + /** TransactionExecutionOptions excludeFromChangeStreams. */ + public excludeFromChangeStreams: boolean; + + /** TransactionExecutionOptions serializableOptimistic. */ + public serializableOptimistic: boolean; + + /** TransactionExecutionOptions snapshotIsolationOptimistic. */ + public snapshotIsolationOptimistic: boolean; + + /** TransactionExecutionOptions snapshotIsolationPessimistic. */ + public snapshotIsolationPessimistic: boolean; + + /** TransactionExecutionOptions excludeTxnFromChangeStreams. */ + public excludeTxnFromChangeStreams: boolean; + + /** + * Creates a new TransactionExecutionOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns TransactionExecutionOptions instance + */ + public static create(properties?: google.spanner.executor.v1.ITransactionExecutionOptions): google.spanner.executor.v1.TransactionExecutionOptions; + + /** + * Encodes the specified TransactionExecutionOptions message. Does not implicitly {@link google.spanner.executor.v1.TransactionExecutionOptions.verify|verify} messages. + * @param message TransactionExecutionOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ITransactionExecutionOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TransactionExecutionOptions message, length delimited. Does not implicitly {@link google.spanner.executor.v1.TransactionExecutionOptions.verify|verify} messages. + * @param message TransactionExecutionOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ITransactionExecutionOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TransactionExecutionOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TransactionExecutionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.TransactionExecutionOptions; + + /** + * Decodes a TransactionExecutionOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TransactionExecutionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.TransactionExecutionOptions; + + /** + * Verifies a TransactionExecutionOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TransactionExecutionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionExecutionOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.TransactionExecutionOptions; + + /** + * Creates a plain object from a TransactionExecutionOptions message. Also converts values to other types if specified. + * @param message TransactionExecutionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.TransactionExecutionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionExecutionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionExecutionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FinishTransactionAction. */ + interface IFinishTransactionAction { + + /** FinishTransactionAction mode */ + mode?: (google.spanner.executor.v1.FinishTransactionAction.Mode|keyof typeof google.spanner.executor.v1.FinishTransactionAction.Mode|null); + } + + /** Represents a FinishTransactionAction. */ + class FinishTransactionAction implements IFinishTransactionAction { + + /** + * Constructs a new FinishTransactionAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IFinishTransactionAction); + + /** FinishTransactionAction mode. */ + public mode: (google.spanner.executor.v1.FinishTransactionAction.Mode|keyof typeof google.spanner.executor.v1.FinishTransactionAction.Mode); + + /** + * Creates a new FinishTransactionAction instance using the specified properties. + * @param [properties] Properties to set + * @returns FinishTransactionAction instance + */ + public static create(properties?: google.spanner.executor.v1.IFinishTransactionAction): google.spanner.executor.v1.FinishTransactionAction; + + /** + * Encodes the specified FinishTransactionAction message. Does not implicitly {@link google.spanner.executor.v1.FinishTransactionAction.verify|verify} messages. + * @param message FinishTransactionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IFinishTransactionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FinishTransactionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.FinishTransactionAction.verify|verify} messages. + * @param message FinishTransactionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IFinishTransactionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FinishTransactionAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FinishTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.FinishTransactionAction; + + /** + * Decodes a FinishTransactionAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FinishTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.FinishTransactionAction; + + /** + * Verifies a FinishTransactionAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FinishTransactionAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FinishTransactionAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.FinishTransactionAction; + + /** + * Creates a plain object from a FinishTransactionAction message. Also converts values to other types if specified. + * @param message FinishTransactionAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.FinishTransactionAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FinishTransactionAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FinishTransactionAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FinishTransactionAction { + + /** Mode enum. */ + enum Mode { + MODE_UNSPECIFIED = 0, + COMMIT = 1, + ABANDON = 2 + } + } + + /** Properties of an AdminAction. */ + interface IAdminAction { + + /** AdminAction createUserInstanceConfig */ + createUserInstanceConfig?: (google.spanner.executor.v1.ICreateUserInstanceConfigAction|null); + + /** AdminAction updateUserInstanceConfig */ + updateUserInstanceConfig?: (google.spanner.executor.v1.IUpdateUserInstanceConfigAction|null); + + /** AdminAction deleteUserInstanceConfig */ + deleteUserInstanceConfig?: (google.spanner.executor.v1.IDeleteUserInstanceConfigAction|null); + + /** AdminAction getCloudInstanceConfig */ + getCloudInstanceConfig?: (google.spanner.executor.v1.IGetCloudInstanceConfigAction|null); + + /** AdminAction listInstanceConfigs */ + listInstanceConfigs?: (google.spanner.executor.v1.IListCloudInstanceConfigsAction|null); + + /** AdminAction createCloudInstance */ + createCloudInstance?: (google.spanner.executor.v1.ICreateCloudInstanceAction|null); + + /** AdminAction updateCloudInstance */ + updateCloudInstance?: (google.spanner.executor.v1.IUpdateCloudInstanceAction|null); + + /** AdminAction deleteCloudInstance */ + deleteCloudInstance?: (google.spanner.executor.v1.IDeleteCloudInstanceAction|null); + + /** AdminAction listCloudInstances */ + listCloudInstances?: (google.spanner.executor.v1.IListCloudInstancesAction|null); + + /** AdminAction getCloudInstance */ + getCloudInstance?: (google.spanner.executor.v1.IGetCloudInstanceAction|null); + + /** AdminAction createCloudDatabase */ + createCloudDatabase?: (google.spanner.executor.v1.ICreateCloudDatabaseAction|null); + + /** AdminAction updateCloudDatabaseDdl */ + updateCloudDatabaseDdl?: (google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction|null); + + /** AdminAction updateCloudDatabase */ + updateCloudDatabase?: (google.spanner.executor.v1.IUpdateCloudDatabaseAction|null); + + /** AdminAction dropCloudDatabase */ + dropCloudDatabase?: (google.spanner.executor.v1.IDropCloudDatabaseAction|null); + + /** AdminAction listCloudDatabases */ + listCloudDatabases?: (google.spanner.executor.v1.IListCloudDatabasesAction|null); + + /** AdminAction listCloudDatabaseOperations */ + listCloudDatabaseOperations?: (google.spanner.executor.v1.IListCloudDatabaseOperationsAction|null); + + /** AdminAction restoreCloudDatabase */ + restoreCloudDatabase?: (google.spanner.executor.v1.IRestoreCloudDatabaseAction|null); + + /** AdminAction getCloudDatabase */ + getCloudDatabase?: (google.spanner.executor.v1.IGetCloudDatabaseAction|null); + + /** AdminAction createCloudBackup */ + createCloudBackup?: (google.spanner.executor.v1.ICreateCloudBackupAction|null); + + /** AdminAction copyCloudBackup */ + copyCloudBackup?: (google.spanner.executor.v1.ICopyCloudBackupAction|null); + + /** AdminAction getCloudBackup */ + getCloudBackup?: (google.spanner.executor.v1.IGetCloudBackupAction|null); + + /** AdminAction updateCloudBackup */ + updateCloudBackup?: (google.spanner.executor.v1.IUpdateCloudBackupAction|null); + + /** AdminAction deleteCloudBackup */ + deleteCloudBackup?: (google.spanner.executor.v1.IDeleteCloudBackupAction|null); + + /** AdminAction listCloudBackups */ + listCloudBackups?: (google.spanner.executor.v1.IListCloudBackupsAction|null); + + /** AdminAction listCloudBackupOperations */ + listCloudBackupOperations?: (google.spanner.executor.v1.IListCloudBackupOperationsAction|null); + + /** AdminAction getOperation */ + getOperation?: (google.spanner.executor.v1.IGetOperationAction|null); + + /** AdminAction cancelOperation */ + cancelOperation?: (google.spanner.executor.v1.ICancelOperationAction|null); + + /** AdminAction changeQuorumCloudDatabase */ + changeQuorumCloudDatabase?: (google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction|null); + + /** AdminAction addSplitPoints */ + addSplitPoints?: (google.spanner.executor.v1.IAddSplitPointsAction|null); + } + + /** Represents an AdminAction. */ + class AdminAction implements IAdminAction { + + /** + * Constructs a new AdminAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IAdminAction); + + /** AdminAction createUserInstanceConfig. */ + public createUserInstanceConfig?: (google.spanner.executor.v1.ICreateUserInstanceConfigAction|null); + + /** AdminAction updateUserInstanceConfig. */ + public updateUserInstanceConfig?: (google.spanner.executor.v1.IUpdateUserInstanceConfigAction|null); + + /** AdminAction deleteUserInstanceConfig. */ + public deleteUserInstanceConfig?: (google.spanner.executor.v1.IDeleteUserInstanceConfigAction|null); + + /** AdminAction getCloudInstanceConfig. */ + public getCloudInstanceConfig?: (google.spanner.executor.v1.IGetCloudInstanceConfigAction|null); + + /** AdminAction listInstanceConfigs. */ + public listInstanceConfigs?: (google.spanner.executor.v1.IListCloudInstanceConfigsAction|null); + + /** AdminAction createCloudInstance. */ + public createCloudInstance?: (google.spanner.executor.v1.ICreateCloudInstanceAction|null); + + /** AdminAction updateCloudInstance. */ + public updateCloudInstance?: (google.spanner.executor.v1.IUpdateCloudInstanceAction|null); + + /** AdminAction deleteCloudInstance. */ + public deleteCloudInstance?: (google.spanner.executor.v1.IDeleteCloudInstanceAction|null); + + /** AdminAction listCloudInstances. */ + public listCloudInstances?: (google.spanner.executor.v1.IListCloudInstancesAction|null); + + /** AdminAction getCloudInstance. */ + public getCloudInstance?: (google.spanner.executor.v1.IGetCloudInstanceAction|null); + + /** AdminAction createCloudDatabase. */ + public createCloudDatabase?: (google.spanner.executor.v1.ICreateCloudDatabaseAction|null); + + /** AdminAction updateCloudDatabaseDdl. */ + public updateCloudDatabaseDdl?: (google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction|null); + + /** AdminAction updateCloudDatabase. */ + public updateCloudDatabase?: (google.spanner.executor.v1.IUpdateCloudDatabaseAction|null); + + /** AdminAction dropCloudDatabase. */ + public dropCloudDatabase?: (google.spanner.executor.v1.IDropCloudDatabaseAction|null); + + /** AdminAction listCloudDatabases. */ + public listCloudDatabases?: (google.spanner.executor.v1.IListCloudDatabasesAction|null); + + /** AdminAction listCloudDatabaseOperations. */ + public listCloudDatabaseOperations?: (google.spanner.executor.v1.IListCloudDatabaseOperationsAction|null); + + /** AdminAction restoreCloudDatabase. */ + public restoreCloudDatabase?: (google.spanner.executor.v1.IRestoreCloudDatabaseAction|null); + + /** AdminAction getCloudDatabase. */ + public getCloudDatabase?: (google.spanner.executor.v1.IGetCloudDatabaseAction|null); + + /** AdminAction createCloudBackup. */ + public createCloudBackup?: (google.spanner.executor.v1.ICreateCloudBackupAction|null); + + /** AdminAction copyCloudBackup. */ + public copyCloudBackup?: (google.spanner.executor.v1.ICopyCloudBackupAction|null); + + /** AdminAction getCloudBackup. */ + public getCloudBackup?: (google.spanner.executor.v1.IGetCloudBackupAction|null); + + /** AdminAction updateCloudBackup. */ + public updateCloudBackup?: (google.spanner.executor.v1.IUpdateCloudBackupAction|null); + + /** AdminAction deleteCloudBackup. */ + public deleteCloudBackup?: (google.spanner.executor.v1.IDeleteCloudBackupAction|null); + + /** AdminAction listCloudBackups. */ + public listCloudBackups?: (google.spanner.executor.v1.IListCloudBackupsAction|null); + + /** AdminAction listCloudBackupOperations. */ + public listCloudBackupOperations?: (google.spanner.executor.v1.IListCloudBackupOperationsAction|null); + + /** AdminAction getOperation. */ + public getOperation?: (google.spanner.executor.v1.IGetOperationAction|null); + + /** AdminAction cancelOperation. */ + public cancelOperation?: (google.spanner.executor.v1.ICancelOperationAction|null); + + /** AdminAction changeQuorumCloudDatabase. */ + public changeQuorumCloudDatabase?: (google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction|null); + + /** AdminAction addSplitPoints. */ + public addSplitPoints?: (google.spanner.executor.v1.IAddSplitPointsAction|null); + + /** AdminAction action. */ + public action?: ("createUserInstanceConfig"|"updateUserInstanceConfig"|"deleteUserInstanceConfig"|"getCloudInstanceConfig"|"listInstanceConfigs"|"createCloudInstance"|"updateCloudInstance"|"deleteCloudInstance"|"listCloudInstances"|"getCloudInstance"|"createCloudDatabase"|"updateCloudDatabaseDdl"|"updateCloudDatabase"|"dropCloudDatabase"|"listCloudDatabases"|"listCloudDatabaseOperations"|"restoreCloudDatabase"|"getCloudDatabase"|"createCloudBackup"|"copyCloudBackup"|"getCloudBackup"|"updateCloudBackup"|"deleteCloudBackup"|"listCloudBackups"|"listCloudBackupOperations"|"getOperation"|"cancelOperation"|"changeQuorumCloudDatabase"|"addSplitPoints"); + + /** + * Creates a new AdminAction instance using the specified properties. + * @param [properties] Properties to set + * @returns AdminAction instance + */ + public static create(properties?: google.spanner.executor.v1.IAdminAction): google.spanner.executor.v1.AdminAction; + + /** + * Encodes the specified AdminAction message. Does not implicitly {@link google.spanner.executor.v1.AdminAction.verify|verify} messages. + * @param message AdminAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IAdminAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AdminAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.AdminAction.verify|verify} messages. + * @param message AdminAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IAdminAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AdminAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AdminAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.AdminAction; + + /** + * Decodes an AdminAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AdminAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.AdminAction; + + /** + * Verifies an AdminAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AdminAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AdminAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.AdminAction; + + /** + * Creates a plain object from an AdminAction message. Also converts values to other types if specified. + * @param message AdminAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.AdminAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AdminAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AdminAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateUserInstanceConfigAction. */ + interface ICreateUserInstanceConfigAction { + + /** CreateUserInstanceConfigAction userConfigId */ + userConfigId?: (string|null); + + /** CreateUserInstanceConfigAction projectId */ + projectId?: (string|null); + + /** CreateUserInstanceConfigAction baseConfigId */ + baseConfigId?: (string|null); + + /** CreateUserInstanceConfigAction replicas */ + replicas?: (google.spanner.admin.instance.v1.IReplicaInfo[]|null); + } + + /** Represents a CreateUserInstanceConfigAction. */ + class CreateUserInstanceConfigAction implements ICreateUserInstanceConfigAction { + + /** + * Constructs a new CreateUserInstanceConfigAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICreateUserInstanceConfigAction); + + /** CreateUserInstanceConfigAction userConfigId. */ + public userConfigId: string; + + /** CreateUserInstanceConfigAction projectId. */ + public projectId: string; + + /** CreateUserInstanceConfigAction baseConfigId. */ + public baseConfigId: string; + + /** CreateUserInstanceConfigAction replicas. */ + public replicas: google.spanner.admin.instance.v1.IReplicaInfo[]; + + /** + * Creates a new CreateUserInstanceConfigAction instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateUserInstanceConfigAction instance + */ + public static create(properties?: google.spanner.executor.v1.ICreateUserInstanceConfigAction): google.spanner.executor.v1.CreateUserInstanceConfigAction; + + /** + * Encodes the specified CreateUserInstanceConfigAction message. Does not implicitly {@link google.spanner.executor.v1.CreateUserInstanceConfigAction.verify|verify} messages. + * @param message CreateUserInstanceConfigAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICreateUserInstanceConfigAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateUserInstanceConfigAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CreateUserInstanceConfigAction.verify|verify} messages. + * @param message CreateUserInstanceConfigAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICreateUserInstanceConfigAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateUserInstanceConfigAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CreateUserInstanceConfigAction; + + /** + * Decodes a CreateUserInstanceConfigAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CreateUserInstanceConfigAction; + + /** + * Verifies a CreateUserInstanceConfigAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateUserInstanceConfigAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateUserInstanceConfigAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CreateUserInstanceConfigAction; + + /** + * Creates a plain object from a CreateUserInstanceConfigAction message. Also converts values to other types if specified. + * @param message CreateUserInstanceConfigAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CreateUserInstanceConfigAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateUserInstanceConfigAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateUserInstanceConfigAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateUserInstanceConfigAction. */ + interface IUpdateUserInstanceConfigAction { + + /** UpdateUserInstanceConfigAction userConfigId */ + userConfigId?: (string|null); + + /** UpdateUserInstanceConfigAction projectId */ + projectId?: (string|null); + + /** UpdateUserInstanceConfigAction displayName */ + displayName?: (string|null); + + /** UpdateUserInstanceConfigAction labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents an UpdateUserInstanceConfigAction. */ + class UpdateUserInstanceConfigAction implements IUpdateUserInstanceConfigAction { + + /** + * Constructs a new UpdateUserInstanceConfigAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IUpdateUserInstanceConfigAction); + + /** UpdateUserInstanceConfigAction userConfigId. */ + public userConfigId: string; + + /** UpdateUserInstanceConfigAction projectId. */ + public projectId: string; + + /** UpdateUserInstanceConfigAction displayName. */ + public displayName?: (string|null); + + /** UpdateUserInstanceConfigAction labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a new UpdateUserInstanceConfigAction instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateUserInstanceConfigAction instance + */ + public static create(properties?: google.spanner.executor.v1.IUpdateUserInstanceConfigAction): google.spanner.executor.v1.UpdateUserInstanceConfigAction; + + /** + * Encodes the specified UpdateUserInstanceConfigAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateUserInstanceConfigAction.verify|verify} messages. + * @param message UpdateUserInstanceConfigAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IUpdateUserInstanceConfigAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateUserInstanceConfigAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateUserInstanceConfigAction.verify|verify} messages. + * @param message UpdateUserInstanceConfigAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IUpdateUserInstanceConfigAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateUserInstanceConfigAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.UpdateUserInstanceConfigAction; + + /** + * Decodes an UpdateUserInstanceConfigAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.UpdateUserInstanceConfigAction; + + /** + * Verifies an UpdateUserInstanceConfigAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateUserInstanceConfigAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateUserInstanceConfigAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.UpdateUserInstanceConfigAction; + + /** + * Creates a plain object from an UpdateUserInstanceConfigAction message. Also converts values to other types if specified. + * @param message UpdateUserInstanceConfigAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.UpdateUserInstanceConfigAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateUserInstanceConfigAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateUserInstanceConfigAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetCloudInstanceConfigAction. */ + interface IGetCloudInstanceConfigAction { + + /** GetCloudInstanceConfigAction instanceConfigId */ + instanceConfigId?: (string|null); + + /** GetCloudInstanceConfigAction projectId */ + projectId?: (string|null); + } + + /** Represents a GetCloudInstanceConfigAction. */ + class GetCloudInstanceConfigAction implements IGetCloudInstanceConfigAction { + + /** + * Constructs a new GetCloudInstanceConfigAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IGetCloudInstanceConfigAction); + + /** GetCloudInstanceConfigAction instanceConfigId. */ + public instanceConfigId: string; + + /** GetCloudInstanceConfigAction projectId. */ + public projectId: string; + + /** + * Creates a new GetCloudInstanceConfigAction instance using the specified properties. + * @param [properties] Properties to set + * @returns GetCloudInstanceConfigAction instance + */ + public static create(properties?: google.spanner.executor.v1.IGetCloudInstanceConfigAction): google.spanner.executor.v1.GetCloudInstanceConfigAction; + + /** + * Encodes the specified GetCloudInstanceConfigAction message. Does not implicitly {@link google.spanner.executor.v1.GetCloudInstanceConfigAction.verify|verify} messages. + * @param message GetCloudInstanceConfigAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IGetCloudInstanceConfigAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetCloudInstanceConfigAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetCloudInstanceConfigAction.verify|verify} messages. + * @param message GetCloudInstanceConfigAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IGetCloudInstanceConfigAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetCloudInstanceConfigAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetCloudInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.GetCloudInstanceConfigAction; + + /** + * Decodes a GetCloudInstanceConfigAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetCloudInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.GetCloudInstanceConfigAction; + + /** + * Verifies a GetCloudInstanceConfigAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetCloudInstanceConfigAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetCloudInstanceConfigAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.GetCloudInstanceConfigAction; + + /** + * Creates a plain object from a GetCloudInstanceConfigAction message. Also converts values to other types if specified. + * @param message GetCloudInstanceConfigAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.GetCloudInstanceConfigAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetCloudInstanceConfigAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetCloudInstanceConfigAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteUserInstanceConfigAction. */ + interface IDeleteUserInstanceConfigAction { + + /** DeleteUserInstanceConfigAction userConfigId */ + userConfigId?: (string|null); + + /** DeleteUserInstanceConfigAction projectId */ + projectId?: (string|null); + } + + /** Represents a DeleteUserInstanceConfigAction. */ + class DeleteUserInstanceConfigAction implements IDeleteUserInstanceConfigAction { + + /** + * Constructs a new DeleteUserInstanceConfigAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IDeleteUserInstanceConfigAction); + + /** DeleteUserInstanceConfigAction userConfigId. */ + public userConfigId: string; + + /** DeleteUserInstanceConfigAction projectId. */ + public projectId: string; + + /** + * Creates a new DeleteUserInstanceConfigAction instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteUserInstanceConfigAction instance + */ + public static create(properties?: google.spanner.executor.v1.IDeleteUserInstanceConfigAction): google.spanner.executor.v1.DeleteUserInstanceConfigAction; + + /** + * Encodes the specified DeleteUserInstanceConfigAction message. Does not implicitly {@link google.spanner.executor.v1.DeleteUserInstanceConfigAction.verify|verify} messages. + * @param message DeleteUserInstanceConfigAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IDeleteUserInstanceConfigAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteUserInstanceConfigAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DeleteUserInstanceConfigAction.verify|verify} messages. + * @param message DeleteUserInstanceConfigAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IDeleteUserInstanceConfigAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteUserInstanceConfigAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.DeleteUserInstanceConfigAction; + + /** + * Decodes a DeleteUserInstanceConfigAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.DeleteUserInstanceConfigAction; + + /** + * Verifies a DeleteUserInstanceConfigAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteUserInstanceConfigAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteUserInstanceConfigAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.DeleteUserInstanceConfigAction; + + /** + * Creates a plain object from a DeleteUserInstanceConfigAction message. Also converts values to other types if specified. + * @param message DeleteUserInstanceConfigAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.DeleteUserInstanceConfigAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteUserInstanceConfigAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteUserInstanceConfigAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCloudInstanceConfigsAction. */ + interface IListCloudInstanceConfigsAction { + + /** ListCloudInstanceConfigsAction projectId */ + projectId?: (string|null); + + /** ListCloudInstanceConfigsAction pageSize */ + pageSize?: (number|null); + + /** ListCloudInstanceConfigsAction pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCloudInstanceConfigsAction. */ + class ListCloudInstanceConfigsAction implements IListCloudInstanceConfigsAction { + + /** + * Constructs a new ListCloudInstanceConfigsAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IListCloudInstanceConfigsAction); + + /** ListCloudInstanceConfigsAction projectId. */ + public projectId: string; + + /** ListCloudInstanceConfigsAction pageSize. */ + public pageSize?: (number|null); + + /** ListCloudInstanceConfigsAction pageToken. */ + public pageToken?: (string|null); + + /** + * Creates a new ListCloudInstanceConfigsAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ListCloudInstanceConfigsAction instance + */ + public static create(properties?: google.spanner.executor.v1.IListCloudInstanceConfigsAction): google.spanner.executor.v1.ListCloudInstanceConfigsAction; + + /** + * Encodes the specified ListCloudInstanceConfigsAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudInstanceConfigsAction.verify|verify} messages. + * @param message ListCloudInstanceConfigsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IListCloudInstanceConfigsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListCloudInstanceConfigsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudInstanceConfigsAction.verify|verify} messages. + * @param message ListCloudInstanceConfigsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IListCloudInstanceConfigsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListCloudInstanceConfigsAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListCloudInstanceConfigsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ListCloudInstanceConfigsAction; + + /** + * Decodes a ListCloudInstanceConfigsAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListCloudInstanceConfigsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ListCloudInstanceConfigsAction; + + /** + * Verifies a ListCloudInstanceConfigsAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListCloudInstanceConfigsAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCloudInstanceConfigsAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ListCloudInstanceConfigsAction; + + /** + * Creates a plain object from a ListCloudInstanceConfigsAction message. Also converts values to other types if specified. + * @param message ListCloudInstanceConfigsAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ListCloudInstanceConfigsAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCloudInstanceConfigsAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCloudInstanceConfigsAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateCloudInstanceAction. */ + interface ICreateCloudInstanceAction { + + /** CreateCloudInstanceAction instanceId */ + instanceId?: (string|null); + + /** CreateCloudInstanceAction projectId */ + projectId?: (string|null); + + /** CreateCloudInstanceAction instanceConfigId */ + instanceConfigId?: (string|null); + + /** CreateCloudInstanceAction nodeCount */ + nodeCount?: (number|null); + + /** CreateCloudInstanceAction processingUnits */ + processingUnits?: (number|null); + + /** CreateCloudInstanceAction autoscalingConfig */ + autoscalingConfig?: (google.spanner.admin.instance.v1.IAutoscalingConfig|null); + + /** CreateCloudInstanceAction labels */ + labels?: ({ [k: string]: string }|null); + + /** CreateCloudInstanceAction edition */ + edition?: (google.spanner.admin.instance.v1.Instance.Edition|keyof typeof google.spanner.admin.instance.v1.Instance.Edition|null); + } + + /** Represents a CreateCloudInstanceAction. */ + class CreateCloudInstanceAction implements ICreateCloudInstanceAction { + + /** + * Constructs a new CreateCloudInstanceAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICreateCloudInstanceAction); + + /** CreateCloudInstanceAction instanceId. */ + public instanceId: string; + + /** CreateCloudInstanceAction projectId. */ + public projectId: string; + + /** CreateCloudInstanceAction instanceConfigId. */ + public instanceConfigId: string; + + /** CreateCloudInstanceAction nodeCount. */ + public nodeCount?: (number|null); + + /** CreateCloudInstanceAction processingUnits. */ + public processingUnits?: (number|null); + + /** CreateCloudInstanceAction autoscalingConfig. */ + public autoscalingConfig?: (google.spanner.admin.instance.v1.IAutoscalingConfig|null); + + /** CreateCloudInstanceAction labels. */ + public labels: { [k: string]: string }; + + /** CreateCloudInstanceAction edition. */ + public edition: (google.spanner.admin.instance.v1.Instance.Edition|keyof typeof google.spanner.admin.instance.v1.Instance.Edition); + + /** + * Creates a new CreateCloudInstanceAction instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateCloudInstanceAction instance + */ + public static create(properties?: google.spanner.executor.v1.ICreateCloudInstanceAction): google.spanner.executor.v1.CreateCloudInstanceAction; + + /** + * Encodes the specified CreateCloudInstanceAction message. Does not implicitly {@link google.spanner.executor.v1.CreateCloudInstanceAction.verify|verify} messages. + * @param message CreateCloudInstanceAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICreateCloudInstanceAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateCloudInstanceAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CreateCloudInstanceAction.verify|verify} messages. + * @param message CreateCloudInstanceAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICreateCloudInstanceAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateCloudInstanceAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CreateCloudInstanceAction; + + /** + * Decodes a CreateCloudInstanceAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CreateCloudInstanceAction; + + /** + * Verifies a CreateCloudInstanceAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateCloudInstanceAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateCloudInstanceAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CreateCloudInstanceAction; + + /** + * Creates a plain object from a CreateCloudInstanceAction message. Also converts values to other types if specified. + * @param message CreateCloudInstanceAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CreateCloudInstanceAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateCloudInstanceAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateCloudInstanceAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateCloudInstanceAction. */ + interface IUpdateCloudInstanceAction { + + /** UpdateCloudInstanceAction instanceId */ + instanceId?: (string|null); + + /** UpdateCloudInstanceAction projectId */ + projectId?: (string|null); + + /** UpdateCloudInstanceAction displayName */ + displayName?: (string|null); + + /** UpdateCloudInstanceAction nodeCount */ + nodeCount?: (number|null); + + /** UpdateCloudInstanceAction processingUnits */ + processingUnits?: (number|null); + + /** UpdateCloudInstanceAction autoscalingConfig */ + autoscalingConfig?: (google.spanner.admin.instance.v1.IAutoscalingConfig|null); + + /** UpdateCloudInstanceAction labels */ + labels?: ({ [k: string]: string }|null); + + /** UpdateCloudInstanceAction edition */ + edition?: (google.spanner.admin.instance.v1.Instance.Edition|keyof typeof google.spanner.admin.instance.v1.Instance.Edition|null); + } + + /** Represents an UpdateCloudInstanceAction. */ + class UpdateCloudInstanceAction implements IUpdateCloudInstanceAction { + + /** + * Constructs a new UpdateCloudInstanceAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IUpdateCloudInstanceAction); + + /** UpdateCloudInstanceAction instanceId. */ + public instanceId: string; + + /** UpdateCloudInstanceAction projectId. */ + public projectId: string; + + /** UpdateCloudInstanceAction displayName. */ + public displayName?: (string|null); + + /** UpdateCloudInstanceAction nodeCount. */ + public nodeCount?: (number|null); + + /** UpdateCloudInstanceAction processingUnits. */ + public processingUnits?: (number|null); + + /** UpdateCloudInstanceAction autoscalingConfig. */ + public autoscalingConfig?: (google.spanner.admin.instance.v1.IAutoscalingConfig|null); + + /** UpdateCloudInstanceAction labels. */ + public labels: { [k: string]: string }; + + /** UpdateCloudInstanceAction edition. */ + public edition: (google.spanner.admin.instance.v1.Instance.Edition|keyof typeof google.spanner.admin.instance.v1.Instance.Edition); + + /** + * Creates a new UpdateCloudInstanceAction instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateCloudInstanceAction instance + */ + public static create(properties?: google.spanner.executor.v1.IUpdateCloudInstanceAction): google.spanner.executor.v1.UpdateCloudInstanceAction; + + /** + * Encodes the specified UpdateCloudInstanceAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudInstanceAction.verify|verify} messages. + * @param message UpdateCloudInstanceAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IUpdateCloudInstanceAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateCloudInstanceAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudInstanceAction.verify|verify} messages. + * @param message UpdateCloudInstanceAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IUpdateCloudInstanceAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateCloudInstanceAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.UpdateCloudInstanceAction; + + /** + * Decodes an UpdateCloudInstanceAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.UpdateCloudInstanceAction; + + /** + * Verifies an UpdateCloudInstanceAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateCloudInstanceAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateCloudInstanceAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.UpdateCloudInstanceAction; + + /** + * Creates a plain object from an UpdateCloudInstanceAction message. Also converts values to other types if specified. + * @param message UpdateCloudInstanceAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.UpdateCloudInstanceAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateCloudInstanceAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateCloudInstanceAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteCloudInstanceAction. */ + interface IDeleteCloudInstanceAction { + + /** DeleteCloudInstanceAction instanceId */ + instanceId?: (string|null); + + /** DeleteCloudInstanceAction projectId */ + projectId?: (string|null); + } + + /** Represents a DeleteCloudInstanceAction. */ + class DeleteCloudInstanceAction implements IDeleteCloudInstanceAction { + + /** + * Constructs a new DeleteCloudInstanceAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IDeleteCloudInstanceAction); + + /** DeleteCloudInstanceAction instanceId. */ + public instanceId: string; + + /** DeleteCloudInstanceAction projectId. */ + public projectId: string; + + /** + * Creates a new DeleteCloudInstanceAction instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteCloudInstanceAction instance + */ + public static create(properties?: google.spanner.executor.v1.IDeleteCloudInstanceAction): google.spanner.executor.v1.DeleteCloudInstanceAction; + + /** + * Encodes the specified DeleteCloudInstanceAction message. Does not implicitly {@link google.spanner.executor.v1.DeleteCloudInstanceAction.verify|verify} messages. + * @param message DeleteCloudInstanceAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IDeleteCloudInstanceAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteCloudInstanceAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DeleteCloudInstanceAction.verify|verify} messages. + * @param message DeleteCloudInstanceAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IDeleteCloudInstanceAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteCloudInstanceAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.DeleteCloudInstanceAction; + + /** + * Decodes a DeleteCloudInstanceAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.DeleteCloudInstanceAction; + + /** + * Verifies a DeleteCloudInstanceAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteCloudInstanceAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteCloudInstanceAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.DeleteCloudInstanceAction; + + /** + * Creates a plain object from a DeleteCloudInstanceAction message. Also converts values to other types if specified. + * @param message DeleteCloudInstanceAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.DeleteCloudInstanceAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteCloudInstanceAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteCloudInstanceAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateCloudDatabaseAction. */ + interface ICreateCloudDatabaseAction { + + /** CreateCloudDatabaseAction instanceId */ + instanceId?: (string|null); + + /** CreateCloudDatabaseAction projectId */ + projectId?: (string|null); + + /** CreateCloudDatabaseAction databaseId */ + databaseId?: (string|null); + + /** CreateCloudDatabaseAction sdlStatement */ + sdlStatement?: (string[]|null); + + /** CreateCloudDatabaseAction encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + + /** CreateCloudDatabaseAction dialect */ + dialect?: (string|null); + + /** CreateCloudDatabaseAction protoDescriptors */ + protoDescriptors?: (Uint8Array|Buffer|string|null); + } + + /** Represents a CreateCloudDatabaseAction. */ + class CreateCloudDatabaseAction implements ICreateCloudDatabaseAction { + + /** + * Constructs a new CreateCloudDatabaseAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICreateCloudDatabaseAction); + + /** CreateCloudDatabaseAction instanceId. */ + public instanceId: string; + + /** CreateCloudDatabaseAction projectId. */ + public projectId: string; + + /** CreateCloudDatabaseAction databaseId. */ + public databaseId: string; + + /** CreateCloudDatabaseAction sdlStatement. */ + public sdlStatement: string[]; + + /** CreateCloudDatabaseAction encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + + /** CreateCloudDatabaseAction dialect. */ + public dialect?: (string|null); + + /** CreateCloudDatabaseAction protoDescriptors. */ + public protoDescriptors?: (Uint8Array|Buffer|string|null); + + /** + * Creates a new CreateCloudDatabaseAction instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateCloudDatabaseAction instance + */ + public static create(properties?: google.spanner.executor.v1.ICreateCloudDatabaseAction): google.spanner.executor.v1.CreateCloudDatabaseAction; + + /** + * Encodes the specified CreateCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.CreateCloudDatabaseAction.verify|verify} messages. + * @param message CreateCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICreateCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CreateCloudDatabaseAction.verify|verify} messages. + * @param message CreateCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICreateCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateCloudDatabaseAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CreateCloudDatabaseAction; + + /** + * Decodes a CreateCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CreateCloudDatabaseAction; + + /** + * Verifies a CreateCloudDatabaseAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateCloudDatabaseAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CreateCloudDatabaseAction; + + /** + * Creates a plain object from a CreateCloudDatabaseAction message. Also converts values to other types if specified. + * @param message CreateCloudDatabaseAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CreateCloudDatabaseAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateCloudDatabaseAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateCloudDatabaseAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateCloudDatabaseDdlAction. */ + interface IUpdateCloudDatabaseDdlAction { + + /** UpdateCloudDatabaseDdlAction instanceId */ + instanceId?: (string|null); + + /** UpdateCloudDatabaseDdlAction projectId */ + projectId?: (string|null); + + /** UpdateCloudDatabaseDdlAction databaseId */ + databaseId?: (string|null); + + /** UpdateCloudDatabaseDdlAction sdlStatement */ + sdlStatement?: (string[]|null); + + /** UpdateCloudDatabaseDdlAction operationId */ + operationId?: (string|null); + + /** UpdateCloudDatabaseDdlAction protoDescriptors */ + protoDescriptors?: (Uint8Array|Buffer|string|null); + } + + /** Represents an UpdateCloudDatabaseDdlAction. */ + class UpdateCloudDatabaseDdlAction implements IUpdateCloudDatabaseDdlAction { + + /** + * Constructs a new UpdateCloudDatabaseDdlAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction); + + /** UpdateCloudDatabaseDdlAction instanceId. */ + public instanceId: string; + + /** UpdateCloudDatabaseDdlAction projectId. */ + public projectId: string; + + /** UpdateCloudDatabaseDdlAction databaseId. */ + public databaseId: string; + + /** UpdateCloudDatabaseDdlAction sdlStatement. */ + public sdlStatement: string[]; + + /** UpdateCloudDatabaseDdlAction operationId. */ + public operationId: string; + + /** UpdateCloudDatabaseDdlAction protoDescriptors. */ + public protoDescriptors?: (Uint8Array|Buffer|string|null); + + /** + * Creates a new UpdateCloudDatabaseDdlAction instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateCloudDatabaseDdlAction instance + */ + public static create(properties?: google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction): google.spanner.executor.v1.UpdateCloudDatabaseDdlAction; + + /** + * Encodes the specified UpdateCloudDatabaseDdlAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.verify|verify} messages. + * @param message UpdateCloudDatabaseDdlAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateCloudDatabaseDdlAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.verify|verify} messages. + * @param message UpdateCloudDatabaseDdlAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateCloudDatabaseDdlAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateCloudDatabaseDdlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.UpdateCloudDatabaseDdlAction; + + /** + * Decodes an UpdateCloudDatabaseDdlAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateCloudDatabaseDdlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.UpdateCloudDatabaseDdlAction; + + /** + * Verifies an UpdateCloudDatabaseDdlAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateCloudDatabaseDdlAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateCloudDatabaseDdlAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.UpdateCloudDatabaseDdlAction; + + /** + * Creates a plain object from an UpdateCloudDatabaseDdlAction message. Also converts values to other types if specified. + * @param message UpdateCloudDatabaseDdlAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.UpdateCloudDatabaseDdlAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateCloudDatabaseDdlAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateCloudDatabaseDdlAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateCloudDatabaseAction. */ + interface IUpdateCloudDatabaseAction { + + /** UpdateCloudDatabaseAction instanceId */ + instanceId?: (string|null); + + /** UpdateCloudDatabaseAction projectId */ + projectId?: (string|null); + + /** UpdateCloudDatabaseAction databaseName */ + databaseName?: (string|null); + + /** UpdateCloudDatabaseAction enableDropProtection */ + enableDropProtection?: (boolean|null); + } + + /** Represents an UpdateCloudDatabaseAction. */ + class UpdateCloudDatabaseAction implements IUpdateCloudDatabaseAction { + + /** + * Constructs a new UpdateCloudDatabaseAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IUpdateCloudDatabaseAction); + + /** UpdateCloudDatabaseAction instanceId. */ + public instanceId: string; + + /** UpdateCloudDatabaseAction projectId. */ + public projectId: string; + + /** UpdateCloudDatabaseAction databaseName. */ + public databaseName: string; + + /** UpdateCloudDatabaseAction enableDropProtection. */ + public enableDropProtection: boolean; + + /** + * Creates a new UpdateCloudDatabaseAction instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateCloudDatabaseAction instance + */ + public static create(properties?: google.spanner.executor.v1.IUpdateCloudDatabaseAction): google.spanner.executor.v1.UpdateCloudDatabaseAction; + + /** + * Encodes the specified UpdateCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudDatabaseAction.verify|verify} messages. + * @param message UpdateCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IUpdateCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudDatabaseAction.verify|verify} messages. + * @param message UpdateCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IUpdateCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateCloudDatabaseAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.UpdateCloudDatabaseAction; + + /** + * Decodes an UpdateCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.UpdateCloudDatabaseAction; + + /** + * Verifies an UpdateCloudDatabaseAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateCloudDatabaseAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.UpdateCloudDatabaseAction; + + /** + * Creates a plain object from an UpdateCloudDatabaseAction message. Also converts values to other types if specified. + * @param message UpdateCloudDatabaseAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.UpdateCloudDatabaseAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateCloudDatabaseAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateCloudDatabaseAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DropCloudDatabaseAction. */ + interface IDropCloudDatabaseAction { + + /** DropCloudDatabaseAction instanceId */ + instanceId?: (string|null); + + /** DropCloudDatabaseAction projectId */ + projectId?: (string|null); + + /** DropCloudDatabaseAction databaseId */ + databaseId?: (string|null); + } + + /** Represents a DropCloudDatabaseAction. */ + class DropCloudDatabaseAction implements IDropCloudDatabaseAction { + + /** + * Constructs a new DropCloudDatabaseAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IDropCloudDatabaseAction); + + /** DropCloudDatabaseAction instanceId. */ + public instanceId: string; + + /** DropCloudDatabaseAction projectId. */ + public projectId: string; + + /** DropCloudDatabaseAction databaseId. */ + public databaseId: string; + + /** + * Creates a new DropCloudDatabaseAction instance using the specified properties. + * @param [properties] Properties to set + * @returns DropCloudDatabaseAction instance + */ + public static create(properties?: google.spanner.executor.v1.IDropCloudDatabaseAction): google.spanner.executor.v1.DropCloudDatabaseAction; + + /** + * Encodes the specified DropCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.DropCloudDatabaseAction.verify|verify} messages. + * @param message DropCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IDropCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DropCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DropCloudDatabaseAction.verify|verify} messages. + * @param message DropCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IDropCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DropCloudDatabaseAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DropCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.DropCloudDatabaseAction; + + /** + * Decodes a DropCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DropCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.DropCloudDatabaseAction; + + /** + * Verifies a DropCloudDatabaseAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DropCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DropCloudDatabaseAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.DropCloudDatabaseAction; + + /** + * Creates a plain object from a DropCloudDatabaseAction message. Also converts values to other types if specified. + * @param message DropCloudDatabaseAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.DropCloudDatabaseAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DropCloudDatabaseAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DropCloudDatabaseAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ChangeQuorumCloudDatabaseAction. */ + interface IChangeQuorumCloudDatabaseAction { + + /** ChangeQuorumCloudDatabaseAction databaseUri */ + databaseUri?: (string|null); + + /** ChangeQuorumCloudDatabaseAction servingLocations */ + servingLocations?: (string[]|null); + } + + /** Represents a ChangeQuorumCloudDatabaseAction. */ + class ChangeQuorumCloudDatabaseAction implements IChangeQuorumCloudDatabaseAction { + + /** + * Constructs a new ChangeQuorumCloudDatabaseAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction); + + /** ChangeQuorumCloudDatabaseAction databaseUri. */ + public databaseUri?: (string|null); + + /** ChangeQuorumCloudDatabaseAction servingLocations. */ + public servingLocations: string[]; + + /** + * Creates a new ChangeQuorumCloudDatabaseAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ChangeQuorumCloudDatabaseAction instance + */ + public static create(properties?: google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction): google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction; + + /** + * Encodes the specified ChangeQuorumCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.verify|verify} messages. + * @param message ChangeQuorumCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ChangeQuorumCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.verify|verify} messages. + * @param message ChangeQuorumCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ChangeQuorumCloudDatabaseAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ChangeQuorumCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction; + + /** + * Decodes a ChangeQuorumCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ChangeQuorumCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction; + + /** + * Verifies a ChangeQuorumCloudDatabaseAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ChangeQuorumCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ChangeQuorumCloudDatabaseAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction; + + /** + * Creates a plain object from a ChangeQuorumCloudDatabaseAction message. Also converts values to other types if specified. + * @param message ChangeQuorumCloudDatabaseAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ChangeQuorumCloudDatabaseAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ChangeQuorumCloudDatabaseAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AdaptMessageAction. */ + interface IAdaptMessageAction { + + /** AdaptMessageAction databaseUri */ + databaseUri?: (string|null); + + /** AdaptMessageAction protocol */ + protocol?: (string|null); + + /** AdaptMessageAction payload */ + payload?: (Uint8Array|Buffer|string|null); + + /** AdaptMessageAction attachments */ + attachments?: ({ [k: string]: string }|null); + + /** AdaptMessageAction query */ + query?: (string|null); + + /** AdaptMessageAction prepareThenExecute */ + prepareThenExecute?: (boolean|null); + } + + /** Represents an AdaptMessageAction. */ + class AdaptMessageAction implements IAdaptMessageAction { + + /** + * Constructs a new AdaptMessageAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IAdaptMessageAction); + + /** AdaptMessageAction databaseUri. */ + public databaseUri: string; + + /** AdaptMessageAction protocol. */ + public protocol: string; + + /** AdaptMessageAction payload. */ + public payload: (Uint8Array|Buffer|string); + + /** AdaptMessageAction attachments. */ + public attachments: { [k: string]: string }; + + /** AdaptMessageAction query. */ + public query: string; + + /** AdaptMessageAction prepareThenExecute. */ + public prepareThenExecute: boolean; + + /** + * Creates a new AdaptMessageAction instance using the specified properties. + * @param [properties] Properties to set + * @returns AdaptMessageAction instance + */ + public static create(properties?: google.spanner.executor.v1.IAdaptMessageAction): google.spanner.executor.v1.AdaptMessageAction; + + /** + * Encodes the specified AdaptMessageAction message. Does not implicitly {@link google.spanner.executor.v1.AdaptMessageAction.verify|verify} messages. + * @param message AdaptMessageAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IAdaptMessageAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AdaptMessageAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.AdaptMessageAction.verify|verify} messages. + * @param message AdaptMessageAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IAdaptMessageAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AdaptMessageAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AdaptMessageAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.AdaptMessageAction; + + /** + * Decodes an AdaptMessageAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AdaptMessageAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.AdaptMessageAction; + + /** + * Verifies an AdaptMessageAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AdaptMessageAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AdaptMessageAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.AdaptMessageAction; + + /** + * Creates a plain object from an AdaptMessageAction message. Also converts values to other types if specified. + * @param message AdaptMessageAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.AdaptMessageAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AdaptMessageAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AdaptMessageAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCloudDatabasesAction. */ + interface IListCloudDatabasesAction { + + /** ListCloudDatabasesAction projectId */ + projectId?: (string|null); + + /** ListCloudDatabasesAction instanceId */ + instanceId?: (string|null); + + /** ListCloudDatabasesAction pageSize */ + pageSize?: (number|null); + + /** ListCloudDatabasesAction pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCloudDatabasesAction. */ + class ListCloudDatabasesAction implements IListCloudDatabasesAction { + + /** + * Constructs a new ListCloudDatabasesAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IListCloudDatabasesAction); + + /** ListCloudDatabasesAction projectId. */ + public projectId: string; + + /** ListCloudDatabasesAction instanceId. */ + public instanceId: string; + + /** ListCloudDatabasesAction pageSize. */ + public pageSize: number; + + /** ListCloudDatabasesAction pageToken. */ + public pageToken: string; + + /** + * Creates a new ListCloudDatabasesAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ListCloudDatabasesAction instance + */ + public static create(properties?: google.spanner.executor.v1.IListCloudDatabasesAction): google.spanner.executor.v1.ListCloudDatabasesAction; + + /** + * Encodes the specified ListCloudDatabasesAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudDatabasesAction.verify|verify} messages. + * @param message ListCloudDatabasesAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IListCloudDatabasesAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListCloudDatabasesAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudDatabasesAction.verify|verify} messages. + * @param message ListCloudDatabasesAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IListCloudDatabasesAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListCloudDatabasesAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListCloudDatabasesAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ListCloudDatabasesAction; + + /** + * Decodes a ListCloudDatabasesAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListCloudDatabasesAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ListCloudDatabasesAction; + + /** + * Verifies a ListCloudDatabasesAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListCloudDatabasesAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCloudDatabasesAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ListCloudDatabasesAction; + + /** + * Creates a plain object from a ListCloudDatabasesAction message. Also converts values to other types if specified. + * @param message ListCloudDatabasesAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ListCloudDatabasesAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCloudDatabasesAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCloudDatabasesAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCloudInstancesAction. */ + interface IListCloudInstancesAction { + + /** ListCloudInstancesAction projectId */ + projectId?: (string|null); + + /** ListCloudInstancesAction filter */ + filter?: (string|null); + + /** ListCloudInstancesAction pageSize */ + pageSize?: (number|null); + + /** ListCloudInstancesAction pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCloudInstancesAction. */ + class ListCloudInstancesAction implements IListCloudInstancesAction { + + /** + * Constructs a new ListCloudInstancesAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IListCloudInstancesAction); + + /** ListCloudInstancesAction projectId. */ + public projectId: string; + + /** ListCloudInstancesAction filter. */ + public filter?: (string|null); + + /** ListCloudInstancesAction pageSize. */ + public pageSize?: (number|null); + + /** ListCloudInstancesAction pageToken. */ + public pageToken?: (string|null); + + /** + * Creates a new ListCloudInstancesAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ListCloudInstancesAction instance + */ + public static create(properties?: google.spanner.executor.v1.IListCloudInstancesAction): google.spanner.executor.v1.ListCloudInstancesAction; + + /** + * Encodes the specified ListCloudInstancesAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudInstancesAction.verify|verify} messages. + * @param message ListCloudInstancesAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IListCloudInstancesAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListCloudInstancesAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudInstancesAction.verify|verify} messages. + * @param message ListCloudInstancesAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IListCloudInstancesAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListCloudInstancesAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListCloudInstancesAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ListCloudInstancesAction; + + /** + * Decodes a ListCloudInstancesAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListCloudInstancesAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ListCloudInstancesAction; + + /** + * Verifies a ListCloudInstancesAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListCloudInstancesAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCloudInstancesAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ListCloudInstancesAction; + + /** + * Creates a plain object from a ListCloudInstancesAction message. Also converts values to other types if specified. + * @param message ListCloudInstancesAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ListCloudInstancesAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCloudInstancesAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCloudInstancesAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetCloudInstanceAction. */ + interface IGetCloudInstanceAction { + + /** GetCloudInstanceAction projectId */ + projectId?: (string|null); + + /** GetCloudInstanceAction instanceId */ + instanceId?: (string|null); + } + + /** Represents a GetCloudInstanceAction. */ + class GetCloudInstanceAction implements IGetCloudInstanceAction { + + /** + * Constructs a new GetCloudInstanceAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IGetCloudInstanceAction); + + /** GetCloudInstanceAction projectId. */ + public projectId: string; + + /** GetCloudInstanceAction instanceId. */ + public instanceId: string; + + /** + * Creates a new GetCloudInstanceAction instance using the specified properties. + * @param [properties] Properties to set + * @returns GetCloudInstanceAction instance + */ + public static create(properties?: google.spanner.executor.v1.IGetCloudInstanceAction): google.spanner.executor.v1.GetCloudInstanceAction; + + /** + * Encodes the specified GetCloudInstanceAction message. Does not implicitly {@link google.spanner.executor.v1.GetCloudInstanceAction.verify|verify} messages. + * @param message GetCloudInstanceAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IGetCloudInstanceAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetCloudInstanceAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetCloudInstanceAction.verify|verify} messages. + * @param message GetCloudInstanceAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IGetCloudInstanceAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetCloudInstanceAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.GetCloudInstanceAction; + + /** + * Decodes a GetCloudInstanceAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.GetCloudInstanceAction; + + /** + * Verifies a GetCloudInstanceAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetCloudInstanceAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetCloudInstanceAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.GetCloudInstanceAction; + + /** + * Creates a plain object from a GetCloudInstanceAction message. Also converts values to other types if specified. + * @param message GetCloudInstanceAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.GetCloudInstanceAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetCloudInstanceAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetCloudInstanceAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCloudDatabaseOperationsAction. */ + interface IListCloudDatabaseOperationsAction { + + /** ListCloudDatabaseOperationsAction projectId */ + projectId?: (string|null); + + /** ListCloudDatabaseOperationsAction instanceId */ + instanceId?: (string|null); + + /** ListCloudDatabaseOperationsAction filter */ + filter?: (string|null); + + /** ListCloudDatabaseOperationsAction pageSize */ + pageSize?: (number|null); + + /** ListCloudDatabaseOperationsAction pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCloudDatabaseOperationsAction. */ + class ListCloudDatabaseOperationsAction implements IListCloudDatabaseOperationsAction { + + /** + * Constructs a new ListCloudDatabaseOperationsAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IListCloudDatabaseOperationsAction); + + /** ListCloudDatabaseOperationsAction projectId. */ + public projectId: string; + + /** ListCloudDatabaseOperationsAction instanceId. */ + public instanceId: string; + + /** ListCloudDatabaseOperationsAction filter. */ + public filter: string; + + /** ListCloudDatabaseOperationsAction pageSize. */ + public pageSize: number; + + /** ListCloudDatabaseOperationsAction pageToken. */ + public pageToken: string; + + /** + * Creates a new ListCloudDatabaseOperationsAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ListCloudDatabaseOperationsAction instance + */ + public static create(properties?: google.spanner.executor.v1.IListCloudDatabaseOperationsAction): google.spanner.executor.v1.ListCloudDatabaseOperationsAction; + + /** + * Encodes the specified ListCloudDatabaseOperationsAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudDatabaseOperationsAction.verify|verify} messages. + * @param message ListCloudDatabaseOperationsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IListCloudDatabaseOperationsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListCloudDatabaseOperationsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudDatabaseOperationsAction.verify|verify} messages. + * @param message ListCloudDatabaseOperationsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IListCloudDatabaseOperationsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListCloudDatabaseOperationsAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListCloudDatabaseOperationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ListCloudDatabaseOperationsAction; + + /** + * Decodes a ListCloudDatabaseOperationsAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListCloudDatabaseOperationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ListCloudDatabaseOperationsAction; + + /** + * Verifies a ListCloudDatabaseOperationsAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListCloudDatabaseOperationsAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCloudDatabaseOperationsAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ListCloudDatabaseOperationsAction; + + /** + * Creates a plain object from a ListCloudDatabaseOperationsAction message. Also converts values to other types if specified. + * @param message ListCloudDatabaseOperationsAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ListCloudDatabaseOperationsAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCloudDatabaseOperationsAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCloudDatabaseOperationsAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RestoreCloudDatabaseAction. */ + interface IRestoreCloudDatabaseAction { + + /** RestoreCloudDatabaseAction projectId */ + projectId?: (string|null); + + /** RestoreCloudDatabaseAction backupInstanceId */ + backupInstanceId?: (string|null); + + /** RestoreCloudDatabaseAction backupId */ + backupId?: (string|null); + + /** RestoreCloudDatabaseAction databaseInstanceId */ + databaseInstanceId?: (string|null); + + /** RestoreCloudDatabaseAction databaseId */ + databaseId?: (string|null); + + /** RestoreCloudDatabaseAction encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + } + + /** Represents a RestoreCloudDatabaseAction. */ + class RestoreCloudDatabaseAction implements IRestoreCloudDatabaseAction { + + /** + * Constructs a new RestoreCloudDatabaseAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IRestoreCloudDatabaseAction); + + /** RestoreCloudDatabaseAction projectId. */ + public projectId: string; + + /** RestoreCloudDatabaseAction backupInstanceId. */ + public backupInstanceId: string; + + /** RestoreCloudDatabaseAction backupId. */ + public backupId: string; + + /** RestoreCloudDatabaseAction databaseInstanceId. */ + public databaseInstanceId: string; + + /** RestoreCloudDatabaseAction databaseId. */ + public databaseId: string; + + /** RestoreCloudDatabaseAction encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + + /** + * Creates a new RestoreCloudDatabaseAction instance using the specified properties. + * @param [properties] Properties to set + * @returns RestoreCloudDatabaseAction instance + */ + public static create(properties?: google.spanner.executor.v1.IRestoreCloudDatabaseAction): google.spanner.executor.v1.RestoreCloudDatabaseAction; + + /** + * Encodes the specified RestoreCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.RestoreCloudDatabaseAction.verify|verify} messages. + * @param message RestoreCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IRestoreCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RestoreCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.RestoreCloudDatabaseAction.verify|verify} messages. + * @param message RestoreCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IRestoreCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RestoreCloudDatabaseAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RestoreCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.RestoreCloudDatabaseAction; + + /** + * Decodes a RestoreCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RestoreCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.RestoreCloudDatabaseAction; + + /** + * Verifies a RestoreCloudDatabaseAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RestoreCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RestoreCloudDatabaseAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.RestoreCloudDatabaseAction; + + /** + * Creates a plain object from a RestoreCloudDatabaseAction message. Also converts values to other types if specified. + * @param message RestoreCloudDatabaseAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.RestoreCloudDatabaseAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RestoreCloudDatabaseAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreCloudDatabaseAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetCloudDatabaseAction. */ + interface IGetCloudDatabaseAction { + + /** GetCloudDatabaseAction projectId */ + projectId?: (string|null); + + /** GetCloudDatabaseAction instanceId */ + instanceId?: (string|null); + + /** GetCloudDatabaseAction databaseId */ + databaseId?: (string|null); + } + + /** Represents a GetCloudDatabaseAction. */ + class GetCloudDatabaseAction implements IGetCloudDatabaseAction { + + /** + * Constructs a new GetCloudDatabaseAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IGetCloudDatabaseAction); + + /** GetCloudDatabaseAction projectId. */ + public projectId: string; + + /** GetCloudDatabaseAction instanceId. */ + public instanceId: string; + + /** GetCloudDatabaseAction databaseId. */ + public databaseId: string; + + /** + * Creates a new GetCloudDatabaseAction instance using the specified properties. + * @param [properties] Properties to set + * @returns GetCloudDatabaseAction instance + */ + public static create(properties?: google.spanner.executor.v1.IGetCloudDatabaseAction): google.spanner.executor.v1.GetCloudDatabaseAction; + + /** + * Encodes the specified GetCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.GetCloudDatabaseAction.verify|verify} messages. + * @param message GetCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IGetCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetCloudDatabaseAction.verify|verify} messages. + * @param message GetCloudDatabaseAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IGetCloudDatabaseAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetCloudDatabaseAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.GetCloudDatabaseAction; + + /** + * Decodes a GetCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.GetCloudDatabaseAction; + + /** + * Verifies a GetCloudDatabaseAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetCloudDatabaseAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.GetCloudDatabaseAction; + + /** + * Creates a plain object from a GetCloudDatabaseAction message. Also converts values to other types if specified. + * @param message GetCloudDatabaseAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.GetCloudDatabaseAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetCloudDatabaseAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetCloudDatabaseAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateCloudBackupAction. */ + interface ICreateCloudBackupAction { + + /** CreateCloudBackupAction projectId */ + projectId?: (string|null); + + /** CreateCloudBackupAction instanceId */ + instanceId?: (string|null); + + /** CreateCloudBackupAction backupId */ + backupId?: (string|null); + + /** CreateCloudBackupAction databaseId */ + databaseId?: (string|null); + + /** CreateCloudBackupAction expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** CreateCloudBackupAction versionTime */ + versionTime?: (google.protobuf.ITimestamp|null); + + /** CreateCloudBackupAction encryptionConfig */ + encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + } + + /** Represents a CreateCloudBackupAction. */ + class CreateCloudBackupAction implements ICreateCloudBackupAction { + + /** + * Constructs a new CreateCloudBackupAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICreateCloudBackupAction); + + /** CreateCloudBackupAction projectId. */ + public projectId: string; + + /** CreateCloudBackupAction instanceId. */ + public instanceId: string; + + /** CreateCloudBackupAction backupId. */ + public backupId: string; + + /** CreateCloudBackupAction databaseId. */ + public databaseId: string; + + /** CreateCloudBackupAction expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** CreateCloudBackupAction versionTime. */ + public versionTime?: (google.protobuf.ITimestamp|null); + + /** CreateCloudBackupAction encryptionConfig. */ + public encryptionConfig?: (google.spanner.admin.database.v1.IEncryptionConfig|null); + + /** + * Creates a new CreateCloudBackupAction instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateCloudBackupAction instance + */ + public static create(properties?: google.spanner.executor.v1.ICreateCloudBackupAction): google.spanner.executor.v1.CreateCloudBackupAction; + + /** + * Encodes the specified CreateCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.CreateCloudBackupAction.verify|verify} messages. + * @param message CreateCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICreateCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CreateCloudBackupAction.verify|verify} messages. + * @param message CreateCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICreateCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateCloudBackupAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CreateCloudBackupAction; + + /** + * Decodes a CreateCloudBackupAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CreateCloudBackupAction; + + /** + * Verifies a CreateCloudBackupAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateCloudBackupAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CreateCloudBackupAction; + + /** + * Creates a plain object from a CreateCloudBackupAction message. Also converts values to other types if specified. + * @param message CreateCloudBackupAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CreateCloudBackupAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateCloudBackupAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateCloudBackupAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CopyCloudBackupAction. */ + interface ICopyCloudBackupAction { + + /** CopyCloudBackupAction projectId */ + projectId?: (string|null); + + /** CopyCloudBackupAction instanceId */ + instanceId?: (string|null); + + /** CopyCloudBackupAction backupId */ + backupId?: (string|null); + + /** CopyCloudBackupAction sourceBackup */ + sourceBackup?: (string|null); + + /** CopyCloudBackupAction expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CopyCloudBackupAction. */ + class CopyCloudBackupAction implements ICopyCloudBackupAction { + + /** + * Constructs a new CopyCloudBackupAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICopyCloudBackupAction); + + /** CopyCloudBackupAction projectId. */ + public projectId: string; + + /** CopyCloudBackupAction instanceId. */ + public instanceId: string; + + /** CopyCloudBackupAction backupId. */ + public backupId: string; + + /** CopyCloudBackupAction sourceBackup. */ + public sourceBackup: string; + + /** CopyCloudBackupAction expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new CopyCloudBackupAction instance using the specified properties. + * @param [properties] Properties to set + * @returns CopyCloudBackupAction instance + */ + public static create(properties?: google.spanner.executor.v1.ICopyCloudBackupAction): google.spanner.executor.v1.CopyCloudBackupAction; + + /** + * Encodes the specified CopyCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.CopyCloudBackupAction.verify|verify} messages. + * @param message CopyCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICopyCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CopyCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CopyCloudBackupAction.verify|verify} messages. + * @param message CopyCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICopyCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CopyCloudBackupAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CopyCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CopyCloudBackupAction; + + /** + * Decodes a CopyCloudBackupAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CopyCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CopyCloudBackupAction; + + /** + * Verifies a CopyCloudBackupAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CopyCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CopyCloudBackupAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CopyCloudBackupAction; + + /** + * Creates a plain object from a CopyCloudBackupAction message. Also converts values to other types if specified. + * @param message CopyCloudBackupAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CopyCloudBackupAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CopyCloudBackupAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CopyCloudBackupAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetCloudBackupAction. */ + interface IGetCloudBackupAction { + + /** GetCloudBackupAction projectId */ + projectId?: (string|null); + + /** GetCloudBackupAction instanceId */ + instanceId?: (string|null); + + /** GetCloudBackupAction backupId */ + backupId?: (string|null); + } + + /** Represents a GetCloudBackupAction. */ + class GetCloudBackupAction implements IGetCloudBackupAction { + + /** + * Constructs a new GetCloudBackupAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IGetCloudBackupAction); + + /** GetCloudBackupAction projectId. */ + public projectId: string; + + /** GetCloudBackupAction instanceId. */ + public instanceId: string; + + /** GetCloudBackupAction backupId. */ + public backupId: string; + + /** + * Creates a new GetCloudBackupAction instance using the specified properties. + * @param [properties] Properties to set + * @returns GetCloudBackupAction instance + */ + public static create(properties?: google.spanner.executor.v1.IGetCloudBackupAction): google.spanner.executor.v1.GetCloudBackupAction; + + /** + * Encodes the specified GetCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.GetCloudBackupAction.verify|verify} messages. + * @param message GetCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IGetCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetCloudBackupAction.verify|verify} messages. + * @param message GetCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IGetCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetCloudBackupAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.GetCloudBackupAction; + + /** + * Decodes a GetCloudBackupAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.GetCloudBackupAction; + + /** + * Verifies a GetCloudBackupAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetCloudBackupAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.GetCloudBackupAction; + + /** + * Creates a plain object from a GetCloudBackupAction message. Also converts values to other types if specified. + * @param message GetCloudBackupAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.GetCloudBackupAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetCloudBackupAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetCloudBackupAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateCloudBackupAction. */ + interface IUpdateCloudBackupAction { + + /** UpdateCloudBackupAction projectId */ + projectId?: (string|null); + + /** UpdateCloudBackupAction instanceId */ + instanceId?: (string|null); + + /** UpdateCloudBackupAction backupId */ + backupId?: (string|null); + + /** UpdateCloudBackupAction expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UpdateCloudBackupAction. */ + class UpdateCloudBackupAction implements IUpdateCloudBackupAction { + + /** + * Constructs a new UpdateCloudBackupAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IUpdateCloudBackupAction); + + /** UpdateCloudBackupAction projectId. */ + public projectId: string; + + /** UpdateCloudBackupAction instanceId. */ + public instanceId: string; + + /** UpdateCloudBackupAction backupId. */ + public backupId: string; + + /** UpdateCloudBackupAction expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new UpdateCloudBackupAction instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateCloudBackupAction instance + */ + public static create(properties?: google.spanner.executor.v1.IUpdateCloudBackupAction): google.spanner.executor.v1.UpdateCloudBackupAction; + + /** + * Encodes the specified UpdateCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudBackupAction.verify|verify} messages. + * @param message UpdateCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IUpdateCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudBackupAction.verify|verify} messages. + * @param message UpdateCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IUpdateCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateCloudBackupAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.UpdateCloudBackupAction; + + /** + * Decodes an UpdateCloudBackupAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.UpdateCloudBackupAction; + + /** + * Verifies an UpdateCloudBackupAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateCloudBackupAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.UpdateCloudBackupAction; + + /** + * Creates a plain object from an UpdateCloudBackupAction message. Also converts values to other types if specified. + * @param message UpdateCloudBackupAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.UpdateCloudBackupAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateCloudBackupAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateCloudBackupAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteCloudBackupAction. */ + interface IDeleteCloudBackupAction { + + /** DeleteCloudBackupAction projectId */ + projectId?: (string|null); + + /** DeleteCloudBackupAction instanceId */ + instanceId?: (string|null); + + /** DeleteCloudBackupAction backupId */ + backupId?: (string|null); + } + + /** Represents a DeleteCloudBackupAction. */ + class DeleteCloudBackupAction implements IDeleteCloudBackupAction { + + /** + * Constructs a new DeleteCloudBackupAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IDeleteCloudBackupAction); + + /** DeleteCloudBackupAction projectId. */ + public projectId: string; + + /** DeleteCloudBackupAction instanceId. */ + public instanceId: string; + + /** DeleteCloudBackupAction backupId. */ + public backupId: string; + + /** + * Creates a new DeleteCloudBackupAction instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteCloudBackupAction instance + */ + public static create(properties?: google.spanner.executor.v1.IDeleteCloudBackupAction): google.spanner.executor.v1.DeleteCloudBackupAction; + + /** + * Encodes the specified DeleteCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.DeleteCloudBackupAction.verify|verify} messages. + * @param message DeleteCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IDeleteCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DeleteCloudBackupAction.verify|verify} messages. + * @param message DeleteCloudBackupAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IDeleteCloudBackupAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteCloudBackupAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.DeleteCloudBackupAction; + + /** + * Decodes a DeleteCloudBackupAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.DeleteCloudBackupAction; + + /** + * Verifies a DeleteCloudBackupAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteCloudBackupAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.DeleteCloudBackupAction; + + /** + * Creates a plain object from a DeleteCloudBackupAction message. Also converts values to other types if specified. + * @param message DeleteCloudBackupAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.DeleteCloudBackupAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteCloudBackupAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteCloudBackupAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCloudBackupsAction. */ + interface IListCloudBackupsAction { + + /** ListCloudBackupsAction projectId */ + projectId?: (string|null); + + /** ListCloudBackupsAction instanceId */ + instanceId?: (string|null); + + /** ListCloudBackupsAction filter */ + filter?: (string|null); + + /** ListCloudBackupsAction pageSize */ + pageSize?: (number|null); + + /** ListCloudBackupsAction pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCloudBackupsAction. */ + class ListCloudBackupsAction implements IListCloudBackupsAction { + + /** + * Constructs a new ListCloudBackupsAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IListCloudBackupsAction); + + /** ListCloudBackupsAction projectId. */ + public projectId: string; + + /** ListCloudBackupsAction instanceId. */ + public instanceId: string; + + /** ListCloudBackupsAction filter. */ + public filter: string; + + /** ListCloudBackupsAction pageSize. */ + public pageSize: number; + + /** ListCloudBackupsAction pageToken. */ + public pageToken: string; + + /** + * Creates a new ListCloudBackupsAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ListCloudBackupsAction instance + */ + public static create(properties?: google.spanner.executor.v1.IListCloudBackupsAction): google.spanner.executor.v1.ListCloudBackupsAction; + + /** + * Encodes the specified ListCloudBackupsAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudBackupsAction.verify|verify} messages. + * @param message ListCloudBackupsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IListCloudBackupsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListCloudBackupsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudBackupsAction.verify|verify} messages. + * @param message ListCloudBackupsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IListCloudBackupsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListCloudBackupsAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListCloudBackupsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ListCloudBackupsAction; + + /** + * Decodes a ListCloudBackupsAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListCloudBackupsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ListCloudBackupsAction; + + /** + * Verifies a ListCloudBackupsAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListCloudBackupsAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCloudBackupsAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ListCloudBackupsAction; + + /** + * Creates a plain object from a ListCloudBackupsAction message. Also converts values to other types if specified. + * @param message ListCloudBackupsAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ListCloudBackupsAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCloudBackupsAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCloudBackupsAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCloudBackupOperationsAction. */ + interface IListCloudBackupOperationsAction { + + /** ListCloudBackupOperationsAction projectId */ + projectId?: (string|null); + + /** ListCloudBackupOperationsAction instanceId */ + instanceId?: (string|null); + + /** ListCloudBackupOperationsAction filter */ + filter?: (string|null); + + /** ListCloudBackupOperationsAction pageSize */ + pageSize?: (number|null); + + /** ListCloudBackupOperationsAction pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListCloudBackupOperationsAction. */ + class ListCloudBackupOperationsAction implements IListCloudBackupOperationsAction { + + /** + * Constructs a new ListCloudBackupOperationsAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IListCloudBackupOperationsAction); + + /** ListCloudBackupOperationsAction projectId. */ + public projectId: string; + + /** ListCloudBackupOperationsAction instanceId. */ + public instanceId: string; + + /** ListCloudBackupOperationsAction filter. */ + public filter: string; + + /** ListCloudBackupOperationsAction pageSize. */ + public pageSize: number; + + /** ListCloudBackupOperationsAction pageToken. */ + public pageToken: string; + + /** + * Creates a new ListCloudBackupOperationsAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ListCloudBackupOperationsAction instance + */ + public static create(properties?: google.spanner.executor.v1.IListCloudBackupOperationsAction): google.spanner.executor.v1.ListCloudBackupOperationsAction; + + /** + * Encodes the specified ListCloudBackupOperationsAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudBackupOperationsAction.verify|verify} messages. + * @param message ListCloudBackupOperationsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IListCloudBackupOperationsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListCloudBackupOperationsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudBackupOperationsAction.verify|verify} messages. + * @param message ListCloudBackupOperationsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IListCloudBackupOperationsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListCloudBackupOperationsAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListCloudBackupOperationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ListCloudBackupOperationsAction; + + /** + * Decodes a ListCloudBackupOperationsAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListCloudBackupOperationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ListCloudBackupOperationsAction; + + /** + * Verifies a ListCloudBackupOperationsAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListCloudBackupOperationsAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCloudBackupOperationsAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ListCloudBackupOperationsAction; + + /** + * Creates a plain object from a ListCloudBackupOperationsAction message. Also converts values to other types if specified. + * @param message ListCloudBackupOperationsAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ListCloudBackupOperationsAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCloudBackupOperationsAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCloudBackupOperationsAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationAction. */ + interface IGetOperationAction { + + /** GetOperationAction operation */ + operation?: (string|null); + } + + /** Represents a GetOperationAction. */ + class GetOperationAction implements IGetOperationAction { + + /** + * Constructs a new GetOperationAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IGetOperationAction); + + /** GetOperationAction operation. */ + public operation: string; + + /** + * Creates a new GetOperationAction instance using the specified properties. + * @param [properties] Properties to set + * @returns GetOperationAction instance + */ + public static create(properties?: google.spanner.executor.v1.IGetOperationAction): google.spanner.executor.v1.GetOperationAction; + + /** + * Encodes the specified GetOperationAction message. Does not implicitly {@link google.spanner.executor.v1.GetOperationAction.verify|verify} messages. + * @param message GetOperationAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IGetOperationAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetOperationAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetOperationAction.verify|verify} messages. + * @param message GetOperationAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IGetOperationAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetOperationAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetOperationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.GetOperationAction; + + /** + * Decodes a GetOperationAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetOperationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.GetOperationAction; + + /** + * Verifies a GetOperationAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetOperationAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.GetOperationAction; + + /** + * Creates a plain object from a GetOperationAction message. Also converts values to other types if specified. + * @param message GetOperationAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.GetOperationAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryCancellationAction. */ + interface IQueryCancellationAction { + + /** QueryCancellationAction longRunningSql */ + longRunningSql?: (string|null); + + /** QueryCancellationAction cancelQuery */ + cancelQuery?: (string|null); + } + + /** Represents a QueryCancellationAction. */ + class QueryCancellationAction implements IQueryCancellationAction { + + /** + * Constructs a new QueryCancellationAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IQueryCancellationAction); + + /** QueryCancellationAction longRunningSql. */ + public longRunningSql: string; + + /** QueryCancellationAction cancelQuery. */ + public cancelQuery: string; + + /** + * Creates a new QueryCancellationAction instance using the specified properties. + * @param [properties] Properties to set + * @returns QueryCancellationAction instance + */ + public static create(properties?: google.spanner.executor.v1.IQueryCancellationAction): google.spanner.executor.v1.QueryCancellationAction; + + /** + * Encodes the specified QueryCancellationAction message. Does not implicitly {@link google.spanner.executor.v1.QueryCancellationAction.verify|verify} messages. + * @param message QueryCancellationAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IQueryCancellationAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified QueryCancellationAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.QueryCancellationAction.verify|verify} messages. + * @param message QueryCancellationAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IQueryCancellationAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a QueryCancellationAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns QueryCancellationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.QueryCancellationAction; + + /** + * Decodes a QueryCancellationAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns QueryCancellationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.QueryCancellationAction; + + /** + * Verifies a QueryCancellationAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a QueryCancellationAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryCancellationAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.QueryCancellationAction; + + /** + * Creates a plain object from a QueryCancellationAction message. Also converts values to other types if specified. + * @param message QueryCancellationAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.QueryCancellationAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryCancellationAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryCancellationAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationAction. */ + interface ICancelOperationAction { + + /** CancelOperationAction operation */ + operation?: (string|null); + } + + /** Represents a CancelOperationAction. */ + class CancelOperationAction implements ICancelOperationAction { + + /** + * Constructs a new CancelOperationAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICancelOperationAction); + + /** CancelOperationAction operation. */ + public operation: string; + + /** + * Creates a new CancelOperationAction instance using the specified properties. + * @param [properties] Properties to set + * @returns CancelOperationAction instance + */ + public static create(properties?: google.spanner.executor.v1.ICancelOperationAction): google.spanner.executor.v1.CancelOperationAction; + + /** + * Encodes the specified CancelOperationAction message. Does not implicitly {@link google.spanner.executor.v1.CancelOperationAction.verify|verify} messages. + * @param message CancelOperationAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICancelOperationAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CancelOperationAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CancelOperationAction.verify|verify} messages. + * @param message CancelOperationAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICancelOperationAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CancelOperationAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CancelOperationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CancelOperationAction; + + /** + * Decodes a CancelOperationAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CancelOperationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CancelOperationAction; + + /** + * Verifies a CancelOperationAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CancelOperationAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CancelOperationAction; + + /** + * Creates a plain object from a CancelOperationAction message. Also converts values to other types if specified. + * @param message CancelOperationAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CancelOperationAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AddSplitPointsAction. */ + interface IAddSplitPointsAction { + + /** AddSplitPointsAction projectId */ + projectId?: (string|null); + + /** AddSplitPointsAction instanceId */ + instanceId?: (string|null); + + /** AddSplitPointsAction databaseId */ + databaseId?: (string|null); + + /** AddSplitPointsAction splitPoints */ + splitPoints?: (google.spanner.admin.database.v1.ISplitPoints[]|null); + } + + /** Represents an AddSplitPointsAction. */ + class AddSplitPointsAction implements IAddSplitPointsAction { + + /** + * Constructs a new AddSplitPointsAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IAddSplitPointsAction); + + /** AddSplitPointsAction projectId. */ + public projectId: string; + + /** AddSplitPointsAction instanceId. */ + public instanceId: string; + + /** AddSplitPointsAction databaseId. */ + public databaseId: string; + + /** AddSplitPointsAction splitPoints. */ + public splitPoints: google.spanner.admin.database.v1.ISplitPoints[]; + + /** + * Creates a new AddSplitPointsAction instance using the specified properties. + * @param [properties] Properties to set + * @returns AddSplitPointsAction instance + */ + public static create(properties?: google.spanner.executor.v1.IAddSplitPointsAction): google.spanner.executor.v1.AddSplitPointsAction; + + /** + * Encodes the specified AddSplitPointsAction message. Does not implicitly {@link google.spanner.executor.v1.AddSplitPointsAction.verify|verify} messages. + * @param message AddSplitPointsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IAddSplitPointsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AddSplitPointsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.AddSplitPointsAction.verify|verify} messages. + * @param message AddSplitPointsAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IAddSplitPointsAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AddSplitPointsAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AddSplitPointsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.AddSplitPointsAction; + + /** + * Decodes an AddSplitPointsAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AddSplitPointsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.AddSplitPointsAction; + + /** + * Verifies an AddSplitPointsAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AddSplitPointsAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AddSplitPointsAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.AddSplitPointsAction; + + /** + * Creates a plain object from an AddSplitPointsAction message. Also converts values to other types if specified. + * @param message AddSplitPointsAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.AddSplitPointsAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AddSplitPointsAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AddSplitPointsAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StartBatchTransactionAction. */ + interface IStartBatchTransactionAction { + + /** StartBatchTransactionAction batchTxnTime */ + batchTxnTime?: (google.protobuf.ITimestamp|null); + + /** StartBatchTransactionAction tid */ + tid?: (Uint8Array|Buffer|string|null); + + /** StartBatchTransactionAction cloudDatabaseRole */ + cloudDatabaseRole?: (string|null); + } + + /** Represents a StartBatchTransactionAction. */ + class StartBatchTransactionAction implements IStartBatchTransactionAction { + + /** + * Constructs a new StartBatchTransactionAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IStartBatchTransactionAction); + + /** StartBatchTransactionAction batchTxnTime. */ + public batchTxnTime?: (google.protobuf.ITimestamp|null); + + /** StartBatchTransactionAction tid. */ + public tid?: (Uint8Array|Buffer|string|null); + + /** StartBatchTransactionAction cloudDatabaseRole. */ + public cloudDatabaseRole: string; + + /** StartBatchTransactionAction param. */ + public param?: ("batchTxnTime"|"tid"); + + /** + * Creates a new StartBatchTransactionAction instance using the specified properties. + * @param [properties] Properties to set + * @returns StartBatchTransactionAction instance + */ + public static create(properties?: google.spanner.executor.v1.IStartBatchTransactionAction): google.spanner.executor.v1.StartBatchTransactionAction; + + /** + * Encodes the specified StartBatchTransactionAction message. Does not implicitly {@link google.spanner.executor.v1.StartBatchTransactionAction.verify|verify} messages. + * @param message StartBatchTransactionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IStartBatchTransactionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified StartBatchTransactionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.StartBatchTransactionAction.verify|verify} messages. + * @param message StartBatchTransactionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IStartBatchTransactionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a StartBatchTransactionAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns StartBatchTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.StartBatchTransactionAction; + + /** + * Decodes a StartBatchTransactionAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns StartBatchTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.StartBatchTransactionAction; + + /** + * Verifies a StartBatchTransactionAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a StartBatchTransactionAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StartBatchTransactionAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.StartBatchTransactionAction; + + /** + * Creates a plain object from a StartBatchTransactionAction message. Also converts values to other types if specified. + * @param message StartBatchTransactionAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.StartBatchTransactionAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StartBatchTransactionAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StartBatchTransactionAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloseBatchTransactionAction. */ + interface ICloseBatchTransactionAction { + + /** CloseBatchTransactionAction cleanup */ + cleanup?: (boolean|null); + } + + /** Represents a CloseBatchTransactionAction. */ + class CloseBatchTransactionAction implements ICloseBatchTransactionAction { + + /** + * Constructs a new CloseBatchTransactionAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICloseBatchTransactionAction); + + /** CloseBatchTransactionAction cleanup. */ + public cleanup: boolean; + + /** + * Creates a new CloseBatchTransactionAction instance using the specified properties. + * @param [properties] Properties to set + * @returns CloseBatchTransactionAction instance + */ + public static create(properties?: google.spanner.executor.v1.ICloseBatchTransactionAction): google.spanner.executor.v1.CloseBatchTransactionAction; + + /** + * Encodes the specified CloseBatchTransactionAction message. Does not implicitly {@link google.spanner.executor.v1.CloseBatchTransactionAction.verify|verify} messages. + * @param message CloseBatchTransactionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICloseBatchTransactionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CloseBatchTransactionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloseBatchTransactionAction.verify|verify} messages. + * @param message CloseBatchTransactionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICloseBatchTransactionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CloseBatchTransactionAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CloseBatchTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CloseBatchTransactionAction; + + /** + * Decodes a CloseBatchTransactionAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CloseBatchTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CloseBatchTransactionAction; + + /** + * Verifies a CloseBatchTransactionAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CloseBatchTransactionAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloseBatchTransactionAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CloseBatchTransactionAction; + + /** + * Creates a plain object from a CloseBatchTransactionAction message. Also converts values to other types if specified. + * @param message CloseBatchTransactionAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CloseBatchTransactionAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloseBatchTransactionAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloseBatchTransactionAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GenerateDbPartitionsForReadAction. */ + interface IGenerateDbPartitionsForReadAction { + + /** GenerateDbPartitionsForReadAction read */ + read?: (google.spanner.executor.v1.IReadAction|null); + + /** GenerateDbPartitionsForReadAction table */ + table?: (google.spanner.executor.v1.ITableMetadata[]|null); + + /** GenerateDbPartitionsForReadAction desiredBytesPerPartition */ + desiredBytesPerPartition?: (number|Long|string|null); + + /** GenerateDbPartitionsForReadAction maxPartitionCount */ + maxPartitionCount?: (number|Long|string|null); + } + + /** Represents a GenerateDbPartitionsForReadAction. */ + class GenerateDbPartitionsForReadAction implements IGenerateDbPartitionsForReadAction { + + /** + * Constructs a new GenerateDbPartitionsForReadAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IGenerateDbPartitionsForReadAction); + + /** GenerateDbPartitionsForReadAction read. */ + public read?: (google.spanner.executor.v1.IReadAction|null); + + /** GenerateDbPartitionsForReadAction table. */ + public table: google.spanner.executor.v1.ITableMetadata[]; + + /** GenerateDbPartitionsForReadAction desiredBytesPerPartition. */ + public desiredBytesPerPartition?: (number|Long|string|null); + + /** GenerateDbPartitionsForReadAction maxPartitionCount. */ + public maxPartitionCount?: (number|Long|string|null); + + /** + * Creates a new GenerateDbPartitionsForReadAction instance using the specified properties. + * @param [properties] Properties to set + * @returns GenerateDbPartitionsForReadAction instance + */ + public static create(properties?: google.spanner.executor.v1.IGenerateDbPartitionsForReadAction): google.spanner.executor.v1.GenerateDbPartitionsForReadAction; + + /** + * Encodes the specified GenerateDbPartitionsForReadAction message. Does not implicitly {@link google.spanner.executor.v1.GenerateDbPartitionsForReadAction.verify|verify} messages. + * @param message GenerateDbPartitionsForReadAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IGenerateDbPartitionsForReadAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GenerateDbPartitionsForReadAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GenerateDbPartitionsForReadAction.verify|verify} messages. + * @param message GenerateDbPartitionsForReadAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IGenerateDbPartitionsForReadAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GenerateDbPartitionsForReadAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GenerateDbPartitionsForReadAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.GenerateDbPartitionsForReadAction; + + /** + * Decodes a GenerateDbPartitionsForReadAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GenerateDbPartitionsForReadAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.GenerateDbPartitionsForReadAction; + + /** + * Verifies a GenerateDbPartitionsForReadAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GenerateDbPartitionsForReadAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GenerateDbPartitionsForReadAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.GenerateDbPartitionsForReadAction; + + /** + * Creates a plain object from a GenerateDbPartitionsForReadAction message. Also converts values to other types if specified. + * @param message GenerateDbPartitionsForReadAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.GenerateDbPartitionsForReadAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GenerateDbPartitionsForReadAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GenerateDbPartitionsForReadAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GenerateDbPartitionsForQueryAction. */ + interface IGenerateDbPartitionsForQueryAction { + + /** GenerateDbPartitionsForQueryAction query */ + query?: (google.spanner.executor.v1.IQueryAction|null); + + /** GenerateDbPartitionsForQueryAction desiredBytesPerPartition */ + desiredBytesPerPartition?: (number|Long|string|null); + } + + /** Represents a GenerateDbPartitionsForQueryAction. */ + class GenerateDbPartitionsForQueryAction implements IGenerateDbPartitionsForQueryAction { + + /** + * Constructs a new GenerateDbPartitionsForQueryAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction); + + /** GenerateDbPartitionsForQueryAction query. */ + public query?: (google.spanner.executor.v1.IQueryAction|null); + + /** GenerateDbPartitionsForQueryAction desiredBytesPerPartition. */ + public desiredBytesPerPartition?: (number|Long|string|null); + + /** + * Creates a new GenerateDbPartitionsForQueryAction instance using the specified properties. + * @param [properties] Properties to set + * @returns GenerateDbPartitionsForQueryAction instance + */ + public static create(properties?: google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction): google.spanner.executor.v1.GenerateDbPartitionsForQueryAction; + + /** + * Encodes the specified GenerateDbPartitionsForQueryAction message. Does not implicitly {@link google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.verify|verify} messages. + * @param message GenerateDbPartitionsForQueryAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GenerateDbPartitionsForQueryAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.verify|verify} messages. + * @param message GenerateDbPartitionsForQueryAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GenerateDbPartitionsForQueryAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GenerateDbPartitionsForQueryAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.GenerateDbPartitionsForQueryAction; + + /** + * Decodes a GenerateDbPartitionsForQueryAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GenerateDbPartitionsForQueryAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.GenerateDbPartitionsForQueryAction; + + /** + * Verifies a GenerateDbPartitionsForQueryAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GenerateDbPartitionsForQueryAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GenerateDbPartitionsForQueryAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.GenerateDbPartitionsForQueryAction; + + /** + * Creates a plain object from a GenerateDbPartitionsForQueryAction message. Also converts values to other types if specified. + * @param message GenerateDbPartitionsForQueryAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.GenerateDbPartitionsForQueryAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GenerateDbPartitionsForQueryAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GenerateDbPartitionsForQueryAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchPartition. */ + interface IBatchPartition { + + /** BatchPartition partition */ + partition?: (Uint8Array|Buffer|string|null); + + /** BatchPartition partitionToken */ + partitionToken?: (Uint8Array|Buffer|string|null); + + /** BatchPartition table */ + table?: (string|null); + + /** BatchPartition index */ + index?: (string|null); + } + + /** Represents a BatchPartition. */ + class BatchPartition implements IBatchPartition { + + /** + * Constructs a new BatchPartition. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IBatchPartition); + + /** BatchPartition partition. */ + public partition: (Uint8Array|Buffer|string); + + /** BatchPartition partitionToken. */ + public partitionToken: (Uint8Array|Buffer|string); + + /** BatchPartition table. */ + public table?: (string|null); + + /** BatchPartition index. */ + public index?: (string|null); + + /** + * Creates a new BatchPartition instance using the specified properties. + * @param [properties] Properties to set + * @returns BatchPartition instance + */ + public static create(properties?: google.spanner.executor.v1.IBatchPartition): google.spanner.executor.v1.BatchPartition; + + /** + * Encodes the specified BatchPartition message. Does not implicitly {@link google.spanner.executor.v1.BatchPartition.verify|verify} messages. + * @param message BatchPartition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IBatchPartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BatchPartition message, length delimited. Does not implicitly {@link google.spanner.executor.v1.BatchPartition.verify|verify} messages. + * @param message BatchPartition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IBatchPartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BatchPartition message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BatchPartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.BatchPartition; + + /** + * Decodes a BatchPartition message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BatchPartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.BatchPartition; + + /** + * Verifies a BatchPartition message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BatchPartition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchPartition + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.BatchPartition; + + /** + * Creates a plain object from a BatchPartition message. Also converts values to other types if specified. + * @param message BatchPartition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.BatchPartition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchPartition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchPartition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutePartitionAction. */ + interface IExecutePartitionAction { + + /** ExecutePartitionAction partition */ + partition?: (google.spanner.executor.v1.IBatchPartition|null); + } + + /** Represents an ExecutePartitionAction. */ + class ExecutePartitionAction implements IExecutePartitionAction { + + /** + * Constructs a new ExecutePartitionAction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IExecutePartitionAction); + + /** ExecutePartitionAction partition. */ + public partition?: (google.spanner.executor.v1.IBatchPartition|null); + + /** + * Creates a new ExecutePartitionAction instance using the specified properties. + * @param [properties] Properties to set + * @returns ExecutePartitionAction instance + */ + public static create(properties?: google.spanner.executor.v1.IExecutePartitionAction): google.spanner.executor.v1.ExecutePartitionAction; + + /** + * Encodes the specified ExecutePartitionAction message. Does not implicitly {@link google.spanner.executor.v1.ExecutePartitionAction.verify|verify} messages. + * @param message ExecutePartitionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IExecutePartitionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExecutePartitionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ExecutePartitionAction.verify|verify} messages. + * @param message ExecutePartitionAction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IExecutePartitionAction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExecutePartitionAction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExecutePartitionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ExecutePartitionAction; + + /** + * Decodes an ExecutePartitionAction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExecutePartitionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ExecutePartitionAction; + + /** + * Verifies an ExecutePartitionAction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExecutePartitionAction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePartitionAction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ExecutePartitionAction; + + /** + * Creates a plain object from an ExecutePartitionAction message. Also converts values to other types if specified. + * @param message ExecutePartitionAction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ExecutePartitionAction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutePartitionAction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutePartitionAction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecuteChangeStreamQuery. */ + interface IExecuteChangeStreamQuery { + + /** ExecuteChangeStreamQuery name */ + name?: (string|null); + + /** ExecuteChangeStreamQuery startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ExecuteChangeStreamQuery endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ExecuteChangeStreamQuery partitionToken */ + partitionToken?: (string|null); + + /** ExecuteChangeStreamQuery readOptions */ + readOptions?: (string[]|null); + + /** ExecuteChangeStreamQuery heartbeatMilliseconds */ + heartbeatMilliseconds?: (number|null); + + /** ExecuteChangeStreamQuery deadlineSeconds */ + deadlineSeconds?: (number|Long|string|null); + + /** ExecuteChangeStreamQuery cloudDatabaseRole */ + cloudDatabaseRole?: (string|null); + } + + /** Represents an ExecuteChangeStreamQuery. */ + class ExecuteChangeStreamQuery implements IExecuteChangeStreamQuery { + + /** + * Constructs a new ExecuteChangeStreamQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IExecuteChangeStreamQuery); + + /** ExecuteChangeStreamQuery name. */ + public name: string; + + /** ExecuteChangeStreamQuery startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ExecuteChangeStreamQuery endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ExecuteChangeStreamQuery partitionToken. */ + public partitionToken?: (string|null); + + /** ExecuteChangeStreamQuery readOptions. */ + public readOptions: string[]; + + /** ExecuteChangeStreamQuery heartbeatMilliseconds. */ + public heartbeatMilliseconds?: (number|null); + + /** ExecuteChangeStreamQuery deadlineSeconds. */ + public deadlineSeconds?: (number|Long|string|null); + + /** ExecuteChangeStreamQuery cloudDatabaseRole. */ + public cloudDatabaseRole?: (string|null); + + /** + * Creates a new ExecuteChangeStreamQuery instance using the specified properties. + * @param [properties] Properties to set + * @returns ExecuteChangeStreamQuery instance + */ + public static create(properties?: google.spanner.executor.v1.IExecuteChangeStreamQuery): google.spanner.executor.v1.ExecuteChangeStreamQuery; + + /** + * Encodes the specified ExecuteChangeStreamQuery message. Does not implicitly {@link google.spanner.executor.v1.ExecuteChangeStreamQuery.verify|verify} messages. + * @param message ExecuteChangeStreamQuery message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IExecuteChangeStreamQuery, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExecuteChangeStreamQuery message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ExecuteChangeStreamQuery.verify|verify} messages. + * @param message ExecuteChangeStreamQuery message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IExecuteChangeStreamQuery, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExecuteChangeStreamQuery message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExecuteChangeStreamQuery + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ExecuteChangeStreamQuery; + + /** + * Decodes an ExecuteChangeStreamQuery message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExecuteChangeStreamQuery + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ExecuteChangeStreamQuery; + + /** + * Verifies an ExecuteChangeStreamQuery message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExecuteChangeStreamQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecuteChangeStreamQuery + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ExecuteChangeStreamQuery; + + /** + * Creates a plain object from an ExecuteChangeStreamQuery message. Also converts values to other types if specified. + * @param message ExecuteChangeStreamQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ExecuteChangeStreamQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecuteChangeStreamQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecuteChangeStreamQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SpannerActionOutcome. */ + interface ISpannerActionOutcome { + + /** SpannerActionOutcome status */ + status?: (google.rpc.IStatus|null); + + /** SpannerActionOutcome commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + + /** SpannerActionOutcome readResult */ + readResult?: (google.spanner.executor.v1.IReadResult|null); + + /** SpannerActionOutcome queryResult */ + queryResult?: (google.spanner.executor.v1.IQueryResult|null); + + /** SpannerActionOutcome transactionRestarted */ + transactionRestarted?: (boolean|null); + + /** SpannerActionOutcome batchTxnId */ + batchTxnId?: (Uint8Array|Buffer|string|null); + + /** SpannerActionOutcome dbPartition */ + dbPartition?: (google.spanner.executor.v1.IBatchPartition[]|null); + + /** SpannerActionOutcome adminResult */ + adminResult?: (google.spanner.executor.v1.IAdminResult|null); + + /** SpannerActionOutcome dmlRowsModified */ + dmlRowsModified?: ((number|Long|string)[]|null); + + /** SpannerActionOutcome changeStreamRecords */ + changeStreamRecords?: (google.spanner.executor.v1.IChangeStreamRecord[]|null); + + /** SpannerActionOutcome snapshotIsolationTxnReadTimestamp */ + snapshotIsolationTxnReadTimestamp?: (number|Long|string|null); + } + + /** Represents a SpannerActionOutcome. */ + class SpannerActionOutcome implements ISpannerActionOutcome { + + /** + * Constructs a new SpannerActionOutcome. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ISpannerActionOutcome); + + /** SpannerActionOutcome status. */ + public status?: (google.rpc.IStatus|null); + + /** SpannerActionOutcome commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** SpannerActionOutcome readResult. */ + public readResult?: (google.spanner.executor.v1.IReadResult|null); + + /** SpannerActionOutcome queryResult. */ + public queryResult?: (google.spanner.executor.v1.IQueryResult|null); + + /** SpannerActionOutcome transactionRestarted. */ + public transactionRestarted?: (boolean|null); + + /** SpannerActionOutcome batchTxnId. */ + public batchTxnId?: (Uint8Array|Buffer|string|null); + + /** SpannerActionOutcome dbPartition. */ + public dbPartition: google.spanner.executor.v1.IBatchPartition[]; + + /** SpannerActionOutcome adminResult. */ + public adminResult?: (google.spanner.executor.v1.IAdminResult|null); + + /** SpannerActionOutcome dmlRowsModified. */ + public dmlRowsModified: (number|Long|string)[]; + + /** SpannerActionOutcome changeStreamRecords. */ + public changeStreamRecords: google.spanner.executor.v1.IChangeStreamRecord[]; + + /** SpannerActionOutcome snapshotIsolationTxnReadTimestamp. */ + public snapshotIsolationTxnReadTimestamp?: (number|Long|string|null); + + /** + * Creates a new SpannerActionOutcome instance using the specified properties. + * @param [properties] Properties to set + * @returns SpannerActionOutcome instance + */ + public static create(properties?: google.spanner.executor.v1.ISpannerActionOutcome): google.spanner.executor.v1.SpannerActionOutcome; + + /** + * Encodes the specified SpannerActionOutcome message. Does not implicitly {@link google.spanner.executor.v1.SpannerActionOutcome.verify|verify} messages. + * @param message SpannerActionOutcome message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ISpannerActionOutcome, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SpannerActionOutcome message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerActionOutcome.verify|verify} messages. + * @param message SpannerActionOutcome message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ISpannerActionOutcome, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SpannerActionOutcome message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SpannerActionOutcome + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.SpannerActionOutcome; + + /** + * Decodes a SpannerActionOutcome message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SpannerActionOutcome + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.SpannerActionOutcome; + + /** + * Verifies a SpannerActionOutcome message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SpannerActionOutcome message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SpannerActionOutcome + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.SpannerActionOutcome; + + /** + * Creates a plain object from a SpannerActionOutcome message. Also converts values to other types if specified. + * @param message SpannerActionOutcome + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.SpannerActionOutcome, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SpannerActionOutcome to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SpannerActionOutcome + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AdminResult. */ + interface IAdminResult { + + /** AdminResult backupResponse */ + backupResponse?: (google.spanner.executor.v1.ICloudBackupResponse|null); + + /** AdminResult operationResponse */ + operationResponse?: (google.spanner.executor.v1.IOperationResponse|null); + + /** AdminResult databaseResponse */ + databaseResponse?: (google.spanner.executor.v1.ICloudDatabaseResponse|null); + + /** AdminResult instanceResponse */ + instanceResponse?: (google.spanner.executor.v1.ICloudInstanceResponse|null); + + /** AdminResult instanceConfigResponse */ + instanceConfigResponse?: (google.spanner.executor.v1.ICloudInstanceConfigResponse|null); + } + + /** Represents an AdminResult. */ + class AdminResult implements IAdminResult { + + /** + * Constructs a new AdminResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IAdminResult); + + /** AdminResult backupResponse. */ + public backupResponse?: (google.spanner.executor.v1.ICloudBackupResponse|null); + + /** AdminResult operationResponse. */ + public operationResponse?: (google.spanner.executor.v1.IOperationResponse|null); + + /** AdminResult databaseResponse. */ + public databaseResponse?: (google.spanner.executor.v1.ICloudDatabaseResponse|null); + + /** AdminResult instanceResponse. */ + public instanceResponse?: (google.spanner.executor.v1.ICloudInstanceResponse|null); + + /** AdminResult instanceConfigResponse. */ + public instanceConfigResponse?: (google.spanner.executor.v1.ICloudInstanceConfigResponse|null); + + /** + * Creates a new AdminResult instance using the specified properties. + * @param [properties] Properties to set + * @returns AdminResult instance + */ + public static create(properties?: google.spanner.executor.v1.IAdminResult): google.spanner.executor.v1.AdminResult; + + /** + * Encodes the specified AdminResult message. Does not implicitly {@link google.spanner.executor.v1.AdminResult.verify|verify} messages. + * @param message AdminResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IAdminResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AdminResult message, length delimited. Does not implicitly {@link google.spanner.executor.v1.AdminResult.verify|verify} messages. + * @param message AdminResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IAdminResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AdminResult message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AdminResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.AdminResult; + + /** + * Decodes an AdminResult message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AdminResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.AdminResult; + + /** + * Verifies an AdminResult message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AdminResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AdminResult + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.AdminResult; + + /** + * Creates a plain object from an AdminResult message. Also converts values to other types if specified. + * @param message AdminResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.AdminResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AdminResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AdminResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloudBackupResponse. */ + interface ICloudBackupResponse { + + /** CloudBackupResponse listedBackups */ + listedBackups?: (google.spanner.admin.database.v1.IBackup[]|null); + + /** CloudBackupResponse listedBackupOperations */ + listedBackupOperations?: (google.longrunning.IOperation[]|null); + + /** CloudBackupResponse nextPageToken */ + nextPageToken?: (string|null); + + /** CloudBackupResponse backup */ + backup?: (google.spanner.admin.database.v1.IBackup|null); + } + + /** Represents a CloudBackupResponse. */ + class CloudBackupResponse implements ICloudBackupResponse { + + /** + * Constructs a new CloudBackupResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICloudBackupResponse); + + /** CloudBackupResponse listedBackups. */ + public listedBackups: google.spanner.admin.database.v1.IBackup[]; + + /** CloudBackupResponse listedBackupOperations. */ + public listedBackupOperations: google.longrunning.IOperation[]; + + /** CloudBackupResponse nextPageToken. */ + public nextPageToken: string; + + /** CloudBackupResponse backup. */ + public backup?: (google.spanner.admin.database.v1.IBackup|null); + + /** + * Creates a new CloudBackupResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns CloudBackupResponse instance + */ + public static create(properties?: google.spanner.executor.v1.ICloudBackupResponse): google.spanner.executor.v1.CloudBackupResponse; + + /** + * Encodes the specified CloudBackupResponse message. Does not implicitly {@link google.spanner.executor.v1.CloudBackupResponse.verify|verify} messages. + * @param message CloudBackupResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICloudBackupResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CloudBackupResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloudBackupResponse.verify|verify} messages. + * @param message CloudBackupResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICloudBackupResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CloudBackupResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CloudBackupResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CloudBackupResponse; + + /** + * Decodes a CloudBackupResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CloudBackupResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CloudBackupResponse; + + /** + * Verifies a CloudBackupResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CloudBackupResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloudBackupResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CloudBackupResponse; + + /** + * Creates a plain object from a CloudBackupResponse message. Also converts values to other types if specified. + * @param message CloudBackupResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CloudBackupResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloudBackupResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloudBackupResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationResponse. */ + interface IOperationResponse { + + /** OperationResponse listedOperations */ + listedOperations?: (google.longrunning.IOperation[]|null); + + /** OperationResponse nextPageToken */ + nextPageToken?: (string|null); + + /** OperationResponse operation */ + operation?: (google.longrunning.IOperation|null); + } + + /** Represents an OperationResponse. */ + class OperationResponse implements IOperationResponse { + + /** + * Constructs a new OperationResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IOperationResponse); + + /** OperationResponse listedOperations. */ + public listedOperations: google.longrunning.IOperation[]; + + /** OperationResponse nextPageToken. */ + public nextPageToken: string; + + /** OperationResponse operation. */ + public operation?: (google.longrunning.IOperation|null); + + /** + * Creates a new OperationResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns OperationResponse instance + */ + public static create(properties?: google.spanner.executor.v1.IOperationResponse): google.spanner.executor.v1.OperationResponse; + + /** + * Encodes the specified OperationResponse message. Does not implicitly {@link google.spanner.executor.v1.OperationResponse.verify|verify} messages. + * @param message OperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OperationResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.OperationResponse.verify|verify} messages. + * @param message OperationResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IOperationResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OperationResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.OperationResponse; + + /** + * Decodes an OperationResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.OperationResponse; + + /** + * Verifies an OperationResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OperationResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.OperationResponse; + + /** + * Creates a plain object from an OperationResponse message. Also converts values to other types if specified. + * @param message OperationResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.OperationResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloudInstanceResponse. */ + interface ICloudInstanceResponse { + + /** CloudInstanceResponse listedInstances */ + listedInstances?: (google.spanner.admin.instance.v1.IInstance[]|null); + + /** CloudInstanceResponse nextPageToken */ + nextPageToken?: (string|null); + + /** CloudInstanceResponse instance */ + instance?: (google.spanner.admin.instance.v1.IInstance|null); + } + + /** Represents a CloudInstanceResponse. */ + class CloudInstanceResponse implements ICloudInstanceResponse { + + /** + * Constructs a new CloudInstanceResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICloudInstanceResponse); + + /** CloudInstanceResponse listedInstances. */ + public listedInstances: google.spanner.admin.instance.v1.IInstance[]; + + /** CloudInstanceResponse nextPageToken. */ + public nextPageToken: string; + + /** CloudInstanceResponse instance. */ + public instance?: (google.spanner.admin.instance.v1.IInstance|null); + + /** + * Creates a new CloudInstanceResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns CloudInstanceResponse instance + */ + public static create(properties?: google.spanner.executor.v1.ICloudInstanceResponse): google.spanner.executor.v1.CloudInstanceResponse; + + /** + * Encodes the specified CloudInstanceResponse message. Does not implicitly {@link google.spanner.executor.v1.CloudInstanceResponse.verify|verify} messages. + * @param message CloudInstanceResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICloudInstanceResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CloudInstanceResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloudInstanceResponse.verify|verify} messages. + * @param message CloudInstanceResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICloudInstanceResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CloudInstanceResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CloudInstanceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CloudInstanceResponse; + + /** + * Decodes a CloudInstanceResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CloudInstanceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CloudInstanceResponse; + + /** + * Verifies a CloudInstanceResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CloudInstanceResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloudInstanceResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CloudInstanceResponse; + + /** + * Creates a plain object from a CloudInstanceResponse message. Also converts values to other types if specified. + * @param message CloudInstanceResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CloudInstanceResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloudInstanceResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloudInstanceResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloudInstanceConfigResponse. */ + interface ICloudInstanceConfigResponse { + + /** CloudInstanceConfigResponse listedInstanceConfigs */ + listedInstanceConfigs?: (google.spanner.admin.instance.v1.IInstanceConfig[]|null); + + /** CloudInstanceConfigResponse nextPageToken */ + nextPageToken?: (string|null); + + /** CloudInstanceConfigResponse instanceConfig */ + instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + } + + /** Represents a CloudInstanceConfigResponse. */ + class CloudInstanceConfigResponse implements ICloudInstanceConfigResponse { + + /** + * Constructs a new CloudInstanceConfigResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICloudInstanceConfigResponse); + + /** CloudInstanceConfigResponse listedInstanceConfigs. */ + public listedInstanceConfigs: google.spanner.admin.instance.v1.IInstanceConfig[]; + + /** CloudInstanceConfigResponse nextPageToken. */ + public nextPageToken: string; + + /** CloudInstanceConfigResponse instanceConfig. */ + public instanceConfig?: (google.spanner.admin.instance.v1.IInstanceConfig|null); + + /** + * Creates a new CloudInstanceConfigResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns CloudInstanceConfigResponse instance + */ + public static create(properties?: google.spanner.executor.v1.ICloudInstanceConfigResponse): google.spanner.executor.v1.CloudInstanceConfigResponse; + + /** + * Encodes the specified CloudInstanceConfigResponse message. Does not implicitly {@link google.spanner.executor.v1.CloudInstanceConfigResponse.verify|verify} messages. + * @param message CloudInstanceConfigResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICloudInstanceConfigResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CloudInstanceConfigResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloudInstanceConfigResponse.verify|verify} messages. + * @param message CloudInstanceConfigResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICloudInstanceConfigResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CloudInstanceConfigResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CloudInstanceConfigResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CloudInstanceConfigResponse; + + /** + * Decodes a CloudInstanceConfigResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CloudInstanceConfigResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CloudInstanceConfigResponse; + + /** + * Verifies a CloudInstanceConfigResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CloudInstanceConfigResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloudInstanceConfigResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CloudInstanceConfigResponse; + + /** + * Creates a plain object from a CloudInstanceConfigResponse message. Also converts values to other types if specified. + * @param message CloudInstanceConfigResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CloudInstanceConfigResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloudInstanceConfigResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloudInstanceConfigResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CloudDatabaseResponse. */ + interface ICloudDatabaseResponse { + + /** CloudDatabaseResponse listedDatabases */ + listedDatabases?: (google.spanner.admin.database.v1.IDatabase[]|null); + + /** CloudDatabaseResponse listedDatabaseOperations */ + listedDatabaseOperations?: (google.longrunning.IOperation[]|null); + + /** CloudDatabaseResponse nextPageToken */ + nextPageToken?: (string|null); + + /** CloudDatabaseResponse database */ + database?: (google.spanner.admin.database.v1.IDatabase|null); + } + + /** Represents a CloudDatabaseResponse. */ + class CloudDatabaseResponse implements ICloudDatabaseResponse { + + /** + * Constructs a new CloudDatabaseResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ICloudDatabaseResponse); + + /** CloudDatabaseResponse listedDatabases. */ + public listedDatabases: google.spanner.admin.database.v1.IDatabase[]; + + /** CloudDatabaseResponse listedDatabaseOperations. */ + public listedDatabaseOperations: google.longrunning.IOperation[]; + + /** CloudDatabaseResponse nextPageToken. */ + public nextPageToken: string; + + /** CloudDatabaseResponse database. */ + public database?: (google.spanner.admin.database.v1.IDatabase|null); + + /** + * Creates a new CloudDatabaseResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns CloudDatabaseResponse instance + */ + public static create(properties?: google.spanner.executor.v1.ICloudDatabaseResponse): google.spanner.executor.v1.CloudDatabaseResponse; + + /** + * Encodes the specified CloudDatabaseResponse message. Does not implicitly {@link google.spanner.executor.v1.CloudDatabaseResponse.verify|verify} messages. + * @param message CloudDatabaseResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ICloudDatabaseResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CloudDatabaseResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloudDatabaseResponse.verify|verify} messages. + * @param message CloudDatabaseResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ICloudDatabaseResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CloudDatabaseResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CloudDatabaseResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.CloudDatabaseResponse; + + /** + * Decodes a CloudDatabaseResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CloudDatabaseResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.CloudDatabaseResponse; + + /** + * Verifies a CloudDatabaseResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CloudDatabaseResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CloudDatabaseResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.CloudDatabaseResponse; + + /** + * Creates a plain object from a CloudDatabaseResponse message. Also converts values to other types if specified. + * @param message CloudDatabaseResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.CloudDatabaseResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CloudDatabaseResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CloudDatabaseResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadResult. */ + interface IReadResult { + + /** ReadResult table */ + table?: (string|null); + + /** ReadResult index */ + index?: (string|null); + + /** ReadResult requestIndex */ + requestIndex?: (number|null); + + /** ReadResult row */ + row?: (google.spanner.executor.v1.IValueList[]|null); + + /** ReadResult rowType */ + rowType?: (google.spanner.v1.IStructType|null); + } + + /** Represents a ReadResult. */ + class ReadResult implements IReadResult { + + /** + * Constructs a new ReadResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IReadResult); + + /** ReadResult table. */ + public table: string; + + /** ReadResult index. */ + public index?: (string|null); + + /** ReadResult requestIndex. */ + public requestIndex?: (number|null); + + /** ReadResult row. */ + public row: google.spanner.executor.v1.IValueList[]; + + /** ReadResult rowType. */ + public rowType?: (google.spanner.v1.IStructType|null); + + /** + * Creates a new ReadResult instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadResult instance + */ + public static create(properties?: google.spanner.executor.v1.IReadResult): google.spanner.executor.v1.ReadResult; + + /** + * Encodes the specified ReadResult message. Does not implicitly {@link google.spanner.executor.v1.ReadResult.verify|verify} messages. + * @param message ReadResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IReadResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadResult message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ReadResult.verify|verify} messages. + * @param message ReadResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IReadResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadResult message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ReadResult; + + /** + * Decodes a ReadResult message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ReadResult; + + /** + * Verifies a ReadResult message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadResult + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ReadResult; + + /** + * Creates a plain object from a ReadResult message. Also converts values to other types if specified. + * @param message ReadResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ReadResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryResult. */ + interface IQueryResult { + + /** QueryResult row */ + row?: (google.spanner.executor.v1.IValueList[]|null); + + /** QueryResult rowType */ + rowType?: (google.spanner.v1.IStructType|null); + } + + /** Represents a QueryResult. */ + class QueryResult implements IQueryResult { + + /** + * Constructs a new QueryResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IQueryResult); + + /** QueryResult row. */ + public row: google.spanner.executor.v1.IValueList[]; + + /** QueryResult rowType. */ + public rowType?: (google.spanner.v1.IStructType|null); + + /** + * Creates a new QueryResult instance using the specified properties. + * @param [properties] Properties to set + * @returns QueryResult instance + */ + public static create(properties?: google.spanner.executor.v1.IQueryResult): google.spanner.executor.v1.QueryResult; + + /** + * Encodes the specified QueryResult message. Does not implicitly {@link google.spanner.executor.v1.QueryResult.verify|verify} messages. + * @param message QueryResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IQueryResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified QueryResult message, length delimited. Does not implicitly {@link google.spanner.executor.v1.QueryResult.verify|verify} messages. + * @param message QueryResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IQueryResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a QueryResult message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns QueryResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.QueryResult; + + /** + * Decodes a QueryResult message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns QueryResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.QueryResult; + + /** + * Verifies a QueryResult message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a QueryResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryResult + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.QueryResult; + + /** + * Creates a plain object from a QueryResult message. Also converts values to other types if specified. + * @param message QueryResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.QueryResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ChangeStreamRecord. */ + interface IChangeStreamRecord { + + /** ChangeStreamRecord dataChange */ + dataChange?: (google.spanner.executor.v1.IDataChangeRecord|null); + + /** ChangeStreamRecord childPartition */ + childPartition?: (google.spanner.executor.v1.IChildPartitionsRecord|null); + + /** ChangeStreamRecord heartbeat */ + heartbeat?: (google.spanner.executor.v1.IHeartbeatRecord|null); + } + + /** Represents a ChangeStreamRecord. */ + class ChangeStreamRecord implements IChangeStreamRecord { + + /** + * Constructs a new ChangeStreamRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IChangeStreamRecord); + + /** ChangeStreamRecord dataChange. */ + public dataChange?: (google.spanner.executor.v1.IDataChangeRecord|null); + + /** ChangeStreamRecord childPartition. */ + public childPartition?: (google.spanner.executor.v1.IChildPartitionsRecord|null); + + /** ChangeStreamRecord heartbeat. */ + public heartbeat?: (google.spanner.executor.v1.IHeartbeatRecord|null); + + /** ChangeStreamRecord record. */ + public record?: ("dataChange"|"childPartition"|"heartbeat"); + + /** + * Creates a new ChangeStreamRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns ChangeStreamRecord instance + */ + public static create(properties?: google.spanner.executor.v1.IChangeStreamRecord): google.spanner.executor.v1.ChangeStreamRecord; + + /** + * Encodes the specified ChangeStreamRecord message. Does not implicitly {@link google.spanner.executor.v1.ChangeStreamRecord.verify|verify} messages. + * @param message ChangeStreamRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IChangeStreamRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ChangeStreamRecord message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ChangeStreamRecord.verify|verify} messages. + * @param message ChangeStreamRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IChangeStreamRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ChangeStreamRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ChangeStreamRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ChangeStreamRecord; + + /** + * Decodes a ChangeStreamRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ChangeStreamRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ChangeStreamRecord; + + /** + * Verifies a ChangeStreamRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ChangeStreamRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ChangeStreamRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ChangeStreamRecord; + + /** + * Creates a plain object from a ChangeStreamRecord message. Also converts values to other types if specified. + * @param message ChangeStreamRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ChangeStreamRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ChangeStreamRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ChangeStreamRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DataChangeRecord. */ + interface IDataChangeRecord { + + /** DataChangeRecord commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + + /** DataChangeRecord recordSequence */ + recordSequence?: (string|null); + + /** DataChangeRecord transactionId */ + transactionId?: (string|null); + + /** DataChangeRecord isLastRecord */ + isLastRecord?: (boolean|null); + + /** DataChangeRecord table */ + table?: (string|null); + + /** DataChangeRecord columnTypes */ + columnTypes?: (google.spanner.executor.v1.DataChangeRecord.IColumnType[]|null); + + /** DataChangeRecord mods */ + mods?: (google.spanner.executor.v1.DataChangeRecord.IMod[]|null); + + /** DataChangeRecord modType */ + modType?: (string|null); + + /** DataChangeRecord valueCaptureType */ + valueCaptureType?: (string|null); + + /** DataChangeRecord recordCount */ + recordCount?: (number|Long|string|null); + + /** DataChangeRecord partitionCount */ + partitionCount?: (number|Long|string|null); + + /** DataChangeRecord transactionTag */ + transactionTag?: (string|null); + + /** DataChangeRecord isSystemTransaction */ + isSystemTransaction?: (boolean|null); + } + + /** Represents a DataChangeRecord. */ + class DataChangeRecord implements IDataChangeRecord { + + /** + * Constructs a new DataChangeRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IDataChangeRecord); + + /** DataChangeRecord commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** DataChangeRecord recordSequence. */ + public recordSequence: string; + + /** DataChangeRecord transactionId. */ + public transactionId: string; + + /** DataChangeRecord isLastRecord. */ + public isLastRecord: boolean; + + /** DataChangeRecord table. */ + public table: string; + + /** DataChangeRecord columnTypes. */ + public columnTypes: google.spanner.executor.v1.DataChangeRecord.IColumnType[]; + + /** DataChangeRecord mods. */ + public mods: google.spanner.executor.v1.DataChangeRecord.IMod[]; + + /** DataChangeRecord modType. */ + public modType: string; + + /** DataChangeRecord valueCaptureType. */ + public valueCaptureType: string; + + /** DataChangeRecord recordCount. */ + public recordCount: (number|Long|string); + + /** DataChangeRecord partitionCount. */ + public partitionCount: (number|Long|string); + + /** DataChangeRecord transactionTag. */ + public transactionTag: string; + + /** DataChangeRecord isSystemTransaction. */ + public isSystemTransaction: boolean; + + /** + * Creates a new DataChangeRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns DataChangeRecord instance + */ + public static create(properties?: google.spanner.executor.v1.IDataChangeRecord): google.spanner.executor.v1.DataChangeRecord; + + /** + * Encodes the specified DataChangeRecord message. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.verify|verify} messages. + * @param message DataChangeRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IDataChangeRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DataChangeRecord message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.verify|verify} messages. + * @param message DataChangeRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IDataChangeRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DataChangeRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DataChangeRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.DataChangeRecord; + + /** + * Decodes a DataChangeRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DataChangeRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.DataChangeRecord; + + /** + * Verifies a DataChangeRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DataChangeRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DataChangeRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.DataChangeRecord; + + /** + * Creates a plain object from a DataChangeRecord message. Also converts values to other types if specified. + * @param message DataChangeRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.DataChangeRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DataChangeRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DataChangeRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DataChangeRecord { + + /** Properties of a ColumnType. */ + interface IColumnType { + + /** ColumnType name */ + name?: (string|null); + + /** ColumnType type */ + type?: (string|null); + + /** ColumnType isPrimaryKey */ + isPrimaryKey?: (boolean|null); + + /** ColumnType ordinalPosition */ + ordinalPosition?: (number|Long|string|null); + } + + /** Represents a ColumnType. */ + class ColumnType implements IColumnType { + + /** + * Constructs a new ColumnType. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.DataChangeRecord.IColumnType); + + /** ColumnType name. */ + public name: string; + + /** ColumnType type. */ + public type: string; + + /** ColumnType isPrimaryKey. */ + public isPrimaryKey: boolean; + + /** ColumnType ordinalPosition. */ + public ordinalPosition: (number|Long|string); + + /** + * Creates a new ColumnType instance using the specified properties. + * @param [properties] Properties to set + * @returns ColumnType instance + */ + public static create(properties?: google.spanner.executor.v1.DataChangeRecord.IColumnType): google.spanner.executor.v1.DataChangeRecord.ColumnType; + + /** + * Encodes the specified ColumnType message. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.ColumnType.verify|verify} messages. + * @param message ColumnType message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.DataChangeRecord.IColumnType, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ColumnType message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.ColumnType.verify|verify} messages. + * @param message ColumnType message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.DataChangeRecord.IColumnType, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ColumnType message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ColumnType + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.DataChangeRecord.ColumnType; + + /** + * Decodes a ColumnType message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ColumnType + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.DataChangeRecord.ColumnType; + + /** + * Verifies a ColumnType message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ColumnType message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ColumnType + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.DataChangeRecord.ColumnType; + + /** + * Creates a plain object from a ColumnType message. Also converts values to other types if specified. + * @param message ColumnType + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.DataChangeRecord.ColumnType, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ColumnType to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ColumnType + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Mod. */ + interface IMod { + + /** Mod keys */ + keys?: (string|null); + + /** Mod newValues */ + newValues?: (string|null); + + /** Mod oldValues */ + oldValues?: (string|null); + } + + /** Represents a Mod. */ + class Mod implements IMod { + + /** + * Constructs a new Mod. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.DataChangeRecord.IMod); + + /** Mod keys. */ + public keys: string; + + /** Mod newValues. */ + public newValues: string; + + /** Mod oldValues. */ + public oldValues: string; + + /** + * Creates a new Mod instance using the specified properties. + * @param [properties] Properties to set + * @returns Mod instance + */ + public static create(properties?: google.spanner.executor.v1.DataChangeRecord.IMod): google.spanner.executor.v1.DataChangeRecord.Mod; + + /** + * Encodes the specified Mod message. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.Mod.verify|verify} messages. + * @param message Mod message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.DataChangeRecord.IMod, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Mod message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.Mod.verify|verify} messages. + * @param message Mod message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.DataChangeRecord.IMod, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Mod message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.DataChangeRecord.Mod; + + /** + * Decodes a Mod message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.DataChangeRecord.Mod; + + /** + * Verifies a Mod message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Mod message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Mod + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.DataChangeRecord.Mod; + + /** + * Creates a plain object from a Mod message. Also converts values to other types if specified. + * @param message Mod + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.DataChangeRecord.Mod, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Mod to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Mod + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a ChildPartitionsRecord. */ + interface IChildPartitionsRecord { + + /** ChildPartitionsRecord startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ChildPartitionsRecord recordSequence */ + recordSequence?: (string|null); + + /** ChildPartitionsRecord childPartitions */ + childPartitions?: (google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition[]|null); + } + + /** Represents a ChildPartitionsRecord. */ + class ChildPartitionsRecord implements IChildPartitionsRecord { + + /** + * Constructs a new ChildPartitionsRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IChildPartitionsRecord); + + /** ChildPartitionsRecord startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ChildPartitionsRecord recordSequence. */ + public recordSequence: string; + + /** ChildPartitionsRecord childPartitions. */ + public childPartitions: google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition[]; + + /** + * Creates a new ChildPartitionsRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns ChildPartitionsRecord instance + */ + public static create(properties?: google.spanner.executor.v1.IChildPartitionsRecord): google.spanner.executor.v1.ChildPartitionsRecord; + + /** + * Encodes the specified ChildPartitionsRecord message. Does not implicitly {@link google.spanner.executor.v1.ChildPartitionsRecord.verify|verify} messages. + * @param message ChildPartitionsRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IChildPartitionsRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ChildPartitionsRecord message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ChildPartitionsRecord.verify|verify} messages. + * @param message ChildPartitionsRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IChildPartitionsRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ChildPartitionsRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ChildPartitionsRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ChildPartitionsRecord; + + /** + * Decodes a ChildPartitionsRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ChildPartitionsRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ChildPartitionsRecord; + + /** + * Verifies a ChildPartitionsRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ChildPartitionsRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ChildPartitionsRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ChildPartitionsRecord; + + /** + * Creates a plain object from a ChildPartitionsRecord message. Also converts values to other types if specified. + * @param message ChildPartitionsRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ChildPartitionsRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ChildPartitionsRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ChildPartitionsRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ChildPartitionsRecord { + + /** Properties of a ChildPartition. */ + interface IChildPartition { + + /** ChildPartition token */ + token?: (string|null); + + /** ChildPartition parentPartitionTokens */ + parentPartitionTokens?: (string[]|null); + } + + /** Represents a ChildPartition. */ + class ChildPartition implements IChildPartition { + + /** + * Constructs a new ChildPartition. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition); + + /** ChildPartition token. */ + public token: string; + + /** ChildPartition parentPartitionTokens. */ + public parentPartitionTokens: string[]; + + /** + * Creates a new ChildPartition instance using the specified properties. + * @param [properties] Properties to set + * @returns ChildPartition instance + */ + public static create(properties?: google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition): google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition; + + /** + * Encodes the specified ChildPartition message. Does not implicitly {@link google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.verify|verify} messages. + * @param message ChildPartition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ChildPartition message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.verify|verify} messages. + * @param message ChildPartition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ChildPartition message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ChildPartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition; + + /** + * Decodes a ChildPartition message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ChildPartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition; + + /** + * Verifies a ChildPartition message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ChildPartition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ChildPartition + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition; + + /** + * Creates a plain object from a ChildPartition message. Also converts values to other types if specified. + * @param message ChildPartition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ChildPartition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ChildPartition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a HeartbeatRecord. */ + interface IHeartbeatRecord { + + /** HeartbeatRecord heartbeatTime */ + heartbeatTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a HeartbeatRecord. */ + class HeartbeatRecord implements IHeartbeatRecord { + + /** + * Constructs a new HeartbeatRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.IHeartbeatRecord); + + /** HeartbeatRecord heartbeatTime. */ + public heartbeatTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new HeartbeatRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns HeartbeatRecord instance + */ + public static create(properties?: google.spanner.executor.v1.IHeartbeatRecord): google.spanner.executor.v1.HeartbeatRecord; + + /** + * Encodes the specified HeartbeatRecord message. Does not implicitly {@link google.spanner.executor.v1.HeartbeatRecord.verify|verify} messages. + * @param message HeartbeatRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.IHeartbeatRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified HeartbeatRecord message, length delimited. Does not implicitly {@link google.spanner.executor.v1.HeartbeatRecord.verify|verify} messages. + * @param message HeartbeatRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.IHeartbeatRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a HeartbeatRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns HeartbeatRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.HeartbeatRecord; + + /** + * Decodes a HeartbeatRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns HeartbeatRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.HeartbeatRecord; + + /** + * Verifies a HeartbeatRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a HeartbeatRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HeartbeatRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.HeartbeatRecord; + + /** + * Creates a plain object from a HeartbeatRecord message. Also converts values to other types if specified. + * @param message HeartbeatRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.HeartbeatRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HeartbeatRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HeartbeatRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SpannerOptions. */ + interface ISpannerOptions { + + /** SpannerOptions sessionPoolOptions */ + sessionPoolOptions?: (google.spanner.executor.v1.ISessionPoolOptions|null); + } + + /** Represents a SpannerOptions. */ + class SpannerOptions implements ISpannerOptions { + + /** + * Constructs a new SpannerOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ISpannerOptions); + + /** SpannerOptions sessionPoolOptions. */ + public sessionPoolOptions?: (google.spanner.executor.v1.ISessionPoolOptions|null); + + /** + * Creates a new SpannerOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns SpannerOptions instance + */ + public static create(properties?: google.spanner.executor.v1.ISpannerOptions): google.spanner.executor.v1.SpannerOptions; + + /** + * Encodes the specified SpannerOptions message. Does not implicitly {@link google.spanner.executor.v1.SpannerOptions.verify|verify} messages. + * @param message SpannerOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ISpannerOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SpannerOptions message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerOptions.verify|verify} messages. + * @param message SpannerOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ISpannerOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SpannerOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SpannerOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.SpannerOptions; + + /** + * Decodes a SpannerOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SpannerOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.SpannerOptions; + + /** + * Verifies a SpannerOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SpannerOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SpannerOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.SpannerOptions; + + /** + * Creates a plain object from a SpannerOptions message. Also converts values to other types if specified. + * @param message SpannerOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.SpannerOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SpannerOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SpannerOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SessionPoolOptions. */ + interface ISessionPoolOptions { + + /** SessionPoolOptions useMultiplexed */ + useMultiplexed?: (boolean|null); + } + + /** Represents a SessionPoolOptions. */ + class SessionPoolOptions implements ISessionPoolOptions { + + /** + * Constructs a new SessionPoolOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.executor.v1.ISessionPoolOptions); + + /** SessionPoolOptions useMultiplexed. */ + public useMultiplexed: boolean; + + /** + * Creates a new SessionPoolOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns SessionPoolOptions instance + */ + public static create(properties?: google.spanner.executor.v1.ISessionPoolOptions): google.spanner.executor.v1.SessionPoolOptions; + + /** + * Encodes the specified SessionPoolOptions message. Does not implicitly {@link google.spanner.executor.v1.SessionPoolOptions.verify|verify} messages. + * @param message SessionPoolOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.executor.v1.ISessionPoolOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SessionPoolOptions message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SessionPoolOptions.verify|verify} messages. + * @param message SessionPoolOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.executor.v1.ISessionPoolOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SessionPoolOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SessionPoolOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.executor.v1.SessionPoolOptions; + + /** + * Decodes a SessionPoolOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SessionPoolOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.executor.v1.SessionPoolOptions; + + /** + * Verifies a SessionPoolOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SessionPoolOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SessionPoolOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.executor.v1.SessionPoolOptions; + + /** + * Creates a plain object from a SessionPoolOptions message. Also converts values to other types if specified. + * @param message SessionPoolOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.executor.v1.SessionPoolOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SessionPoolOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SessionPoolOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Namespace v1. */ + namespace v1 { + + /** Represents a Spanner */ + class Spanner extends $protobuf.rpc.Service { + + /** + * Constructs a new Spanner service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new Spanner service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Spanner; + + /** + * Calls CreateSession. + * @param request CreateSessionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Session + */ + public createSession(request: google.spanner.v1.ICreateSessionRequest, callback: google.spanner.v1.Spanner.CreateSessionCallback): void; + + /** + * Calls CreateSession. + * @param request CreateSessionRequest message or plain object + * @returns Promise + */ + public createSession(request: google.spanner.v1.ICreateSessionRequest): Promise; + + /** + * Calls BatchCreateSessions. + * @param request BatchCreateSessionsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchCreateSessionsResponse + */ + public batchCreateSessions(request: google.spanner.v1.IBatchCreateSessionsRequest, callback: google.spanner.v1.Spanner.BatchCreateSessionsCallback): void; + + /** + * Calls BatchCreateSessions. + * @param request BatchCreateSessionsRequest message or plain object + * @returns Promise + */ + public batchCreateSessions(request: google.spanner.v1.IBatchCreateSessionsRequest): Promise; + + /** + * Calls GetSession. + * @param request GetSessionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Session + */ + public getSession(request: google.spanner.v1.IGetSessionRequest, callback: google.spanner.v1.Spanner.GetSessionCallback): void; + + /** + * Calls GetSession. + * @param request GetSessionRequest message or plain object + * @returns Promise + */ + public getSession(request: google.spanner.v1.IGetSessionRequest): Promise; + + /** + * Calls ListSessions. + * @param request ListSessionsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListSessionsResponse + */ + public listSessions(request: google.spanner.v1.IListSessionsRequest, callback: google.spanner.v1.Spanner.ListSessionsCallback): void; + + /** + * Calls ListSessions. + * @param request ListSessionsRequest message or plain object + * @returns Promise + */ + public listSessions(request: google.spanner.v1.IListSessionsRequest): Promise; + + /** + * Calls DeleteSession. + * @param request DeleteSessionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteSession(request: google.spanner.v1.IDeleteSessionRequest, callback: google.spanner.v1.Spanner.DeleteSessionCallback): void; + + /** + * Calls DeleteSession. + * @param request DeleteSessionRequest message or plain object + * @returns Promise + */ + public deleteSession(request: google.spanner.v1.IDeleteSessionRequest): Promise; + + /** + * Calls ExecuteSql. + * @param request ExecuteSqlRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ResultSet + */ + public executeSql(request: google.spanner.v1.IExecuteSqlRequest, callback: google.spanner.v1.Spanner.ExecuteSqlCallback): void; + + /** + * Calls ExecuteSql. + * @param request ExecuteSqlRequest message or plain object + * @returns Promise + */ + public executeSql(request: google.spanner.v1.IExecuteSqlRequest): Promise; + + /** + * Calls ExecuteStreamingSql. + * @param request ExecuteSqlRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartialResultSet + */ + public executeStreamingSql(request: google.spanner.v1.IExecuteSqlRequest, callback: google.spanner.v1.Spanner.ExecuteStreamingSqlCallback): void; + + /** + * Calls ExecuteStreamingSql. + * @param request ExecuteSqlRequest message or plain object + * @returns Promise + */ + public executeStreamingSql(request: google.spanner.v1.IExecuteSqlRequest): Promise; + + /** + * Calls ExecuteBatchDml. + * @param request ExecuteBatchDmlRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ExecuteBatchDmlResponse + */ + public executeBatchDml(request: google.spanner.v1.IExecuteBatchDmlRequest, callback: google.spanner.v1.Spanner.ExecuteBatchDmlCallback): void; + + /** + * Calls ExecuteBatchDml. + * @param request ExecuteBatchDmlRequest message or plain object + * @returns Promise + */ + public executeBatchDml(request: google.spanner.v1.IExecuteBatchDmlRequest): Promise; + + /** + * Calls Read. + * @param request ReadRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ResultSet + */ + public read(request: google.spanner.v1.IReadRequest, callback: google.spanner.v1.Spanner.ReadCallback): void; + + /** + * Calls Read. + * @param request ReadRequest message or plain object + * @returns Promise + */ + public read(request: google.spanner.v1.IReadRequest): Promise; + + /** + * Calls StreamingRead. + * @param request ReadRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartialResultSet + */ + public streamingRead(request: google.spanner.v1.IReadRequest, callback: google.spanner.v1.Spanner.StreamingReadCallback): void; + + /** + * Calls StreamingRead. + * @param request ReadRequest message or plain object + * @returns Promise + */ + public streamingRead(request: google.spanner.v1.IReadRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Transaction + */ + public beginTransaction(request: google.spanner.v1.IBeginTransactionRequest, callback: google.spanner.v1.Spanner.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.spanner.v1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.spanner.v1.ICommitRequest, callback: google.spanner.v1.Spanner.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.spanner.v1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.spanner.v1.IRollbackRequest, callback: google.spanner.v1.Spanner.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.spanner.v1.IRollbackRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionResponse + */ + public partitionQuery(request: google.spanner.v1.IPartitionQueryRequest, callback: google.spanner.v1.Spanner.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.spanner.v1.IPartitionQueryRequest): Promise; + + /** + * Calls PartitionRead. + * @param request PartitionReadRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionResponse + */ + public partitionRead(request: google.spanner.v1.IPartitionReadRequest, callback: google.spanner.v1.Spanner.PartitionReadCallback): void; + + /** + * Calls PartitionRead. + * @param request PartitionReadRequest message or plain object + * @returns Promise + */ + public partitionRead(request: google.spanner.v1.IPartitionReadRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.spanner.v1.IBatchWriteRequest, callback: google.spanner.v1.Spanner.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.spanner.v1.IBatchWriteRequest): Promise; + } + + namespace Spanner { + + /** + * Callback as used by {@link google.spanner.v1.Spanner|createSession}. + * @param error Error, if any + * @param [response] Session + */ + type CreateSessionCallback = (error: (Error|null), response?: google.spanner.v1.Session) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|batchCreateSessions}. + * @param error Error, if any + * @param [response] BatchCreateSessionsResponse + */ + type BatchCreateSessionsCallback = (error: (Error|null), response?: google.spanner.v1.BatchCreateSessionsResponse) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|getSession}. + * @param error Error, if any + * @param [response] Session + */ + type GetSessionCallback = (error: (Error|null), response?: google.spanner.v1.Session) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|listSessions}. + * @param error Error, if any + * @param [response] ListSessionsResponse + */ + type ListSessionsCallback = (error: (Error|null), response?: google.spanner.v1.ListSessionsResponse) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|deleteSession}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteSessionCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|executeSql}. + * @param error Error, if any + * @param [response] ResultSet + */ + type ExecuteSqlCallback = (error: (Error|null), response?: google.spanner.v1.ResultSet) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|executeStreamingSql}. + * @param error Error, if any + * @param [response] PartialResultSet + */ + type ExecuteStreamingSqlCallback = (error: (Error|null), response?: google.spanner.v1.PartialResultSet) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|executeBatchDml}. + * @param error Error, if any + * @param [response] ExecuteBatchDmlResponse + */ + type ExecuteBatchDmlCallback = (error: (Error|null), response?: google.spanner.v1.ExecuteBatchDmlResponse) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|read}. + * @param error Error, if any + * @param [response] ResultSet + */ + type ReadCallback = (error: (Error|null), response?: google.spanner.v1.ResultSet) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|streamingRead}. + * @param error Error, if any + * @param [response] PartialResultSet + */ + type StreamingReadCallback = (error: (Error|null), response?: google.spanner.v1.PartialResultSet) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|beginTransaction}. + * @param error Error, if any + * @param [response] Transaction + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.spanner.v1.Transaction) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.spanner.v1.CommitResponse) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|partitionQuery}. + * @param error Error, if any + * @param [response] PartitionResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.spanner.v1.PartitionResponse) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|partitionRead}. + * @param error Error, if any + * @param [response] PartitionResponse + */ + type PartitionReadCallback = (error: (Error|null), response?: google.spanner.v1.PartitionResponse) => void; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.spanner.v1.BatchWriteResponse) => void; + } + + /** Properties of a CreateSessionRequest. */ + interface ICreateSessionRequest { + + /** CreateSessionRequest database */ + database?: (string|null); + + /** CreateSessionRequest session */ + session?: (google.spanner.v1.ISession|null); + } + + /** Represents a CreateSessionRequest. */ + class CreateSessionRequest implements ICreateSessionRequest { + + /** + * Constructs a new CreateSessionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ICreateSessionRequest); + + /** CreateSessionRequest database. */ + public database: string; + + /** CreateSessionRequest session. */ + public session?: (google.spanner.v1.ISession|null); + + /** + * Creates a new CreateSessionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateSessionRequest instance + */ + public static create(properties?: google.spanner.v1.ICreateSessionRequest): google.spanner.v1.CreateSessionRequest; + + /** + * Encodes the specified CreateSessionRequest message. Does not implicitly {@link google.spanner.v1.CreateSessionRequest.verify|verify} messages. + * @param message CreateSessionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ICreateSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.CreateSessionRequest.verify|verify} messages. + * @param message CreateSessionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ICreateSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateSessionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.CreateSessionRequest; + + /** + * Decodes a CreateSessionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.CreateSessionRequest; + + /** + * Verifies a CreateSessionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateSessionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateSessionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.CreateSessionRequest; + + /** + * Creates a plain object from a CreateSessionRequest message. Also converts values to other types if specified. + * @param message CreateSessionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.CreateSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateSessionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateSessionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchCreateSessionsRequest. */ + interface IBatchCreateSessionsRequest { + + /** BatchCreateSessionsRequest database */ + database?: (string|null); + + /** BatchCreateSessionsRequest sessionTemplate */ + sessionTemplate?: (google.spanner.v1.ISession|null); + + /** BatchCreateSessionsRequest sessionCount */ + sessionCount?: (number|null); + } + + /** Represents a BatchCreateSessionsRequest. */ + class BatchCreateSessionsRequest implements IBatchCreateSessionsRequest { + + /** + * Constructs a new BatchCreateSessionsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IBatchCreateSessionsRequest); + + /** BatchCreateSessionsRequest database. */ + public database: string; + + /** BatchCreateSessionsRequest sessionTemplate. */ + public sessionTemplate?: (google.spanner.v1.ISession|null); + + /** BatchCreateSessionsRequest sessionCount. */ + public sessionCount: number; + + /** + * Creates a new BatchCreateSessionsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns BatchCreateSessionsRequest instance + */ + public static create(properties?: google.spanner.v1.IBatchCreateSessionsRequest): google.spanner.v1.BatchCreateSessionsRequest; + + /** + * Encodes the specified BatchCreateSessionsRequest message. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsRequest.verify|verify} messages. + * @param message BatchCreateSessionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IBatchCreateSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BatchCreateSessionsRequest message, length delimited. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsRequest.verify|verify} messages. + * @param message BatchCreateSessionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IBatchCreateSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BatchCreateSessionsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BatchCreateSessionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BatchCreateSessionsRequest; + + /** + * Decodes a BatchCreateSessionsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BatchCreateSessionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BatchCreateSessionsRequest; + + /** + * Verifies a BatchCreateSessionsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BatchCreateSessionsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchCreateSessionsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.BatchCreateSessionsRequest; + + /** + * Creates a plain object from a BatchCreateSessionsRequest message. Also converts values to other types if specified. + * @param message BatchCreateSessionsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.BatchCreateSessionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchCreateSessionsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchCreateSessionsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchCreateSessionsResponse. */ + interface IBatchCreateSessionsResponse { + + /** BatchCreateSessionsResponse session */ + session?: (google.spanner.v1.ISession[]|null); + } + + /** Represents a BatchCreateSessionsResponse. */ + class BatchCreateSessionsResponse implements IBatchCreateSessionsResponse { + + /** + * Constructs a new BatchCreateSessionsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IBatchCreateSessionsResponse); + + /** BatchCreateSessionsResponse session. */ + public session: google.spanner.v1.ISession[]; + + /** + * Creates a new BatchCreateSessionsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns BatchCreateSessionsResponse instance + */ + public static create(properties?: google.spanner.v1.IBatchCreateSessionsResponse): google.spanner.v1.BatchCreateSessionsResponse; + + /** + * Encodes the specified BatchCreateSessionsResponse message. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsResponse.verify|verify} messages. + * @param message BatchCreateSessionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IBatchCreateSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BatchCreateSessionsResponse message, length delimited. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsResponse.verify|verify} messages. + * @param message BatchCreateSessionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IBatchCreateSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BatchCreateSessionsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BatchCreateSessionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BatchCreateSessionsResponse; + + /** + * Decodes a BatchCreateSessionsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BatchCreateSessionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BatchCreateSessionsResponse; + + /** + * Verifies a BatchCreateSessionsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BatchCreateSessionsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchCreateSessionsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.BatchCreateSessionsResponse; + + /** + * Creates a plain object from a BatchCreateSessionsResponse message. Also converts values to other types if specified. + * @param message BatchCreateSessionsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.BatchCreateSessionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchCreateSessionsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchCreateSessionsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Session. */ + interface ISession { + + /** Session name */ + name?: (string|null); + + /** Session labels */ + labels?: ({ [k: string]: string }|null); + + /** Session createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Session approximateLastUseTime */ + approximateLastUseTime?: (google.protobuf.ITimestamp|null); + + /** Session creatorRole */ + creatorRole?: (string|null); + + /** Session multiplexed */ + multiplexed?: (boolean|null); + } + + /** Represents a Session. */ + class Session implements ISession { + + /** + * Constructs a new Session. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ISession); + + /** Session name. */ + public name: string; + + /** Session labels. */ + public labels: { [k: string]: string }; + + /** Session createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Session approximateLastUseTime. */ + public approximateLastUseTime?: (google.protobuf.ITimestamp|null); + + /** Session creatorRole. */ + public creatorRole: string; + + /** Session multiplexed. */ + public multiplexed: boolean; + + /** + * Creates a new Session instance using the specified properties. + * @param [properties] Properties to set + * @returns Session instance + */ + public static create(properties?: google.spanner.v1.ISession): google.spanner.v1.Session; + + /** + * Encodes the specified Session message. Does not implicitly {@link google.spanner.v1.Session.verify|verify} messages. + * @param message Session message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ISession, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Session message, length delimited. Does not implicitly {@link google.spanner.v1.Session.verify|verify} messages. + * @param message Session message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ISession, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Session message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Session + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Session; + + /** + * Decodes a Session message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Session + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Session; + + /** + * Verifies a Session message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Session message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Session + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Session; + + /** + * Creates a plain object from a Session message. Also converts values to other types if specified. + * @param message Session + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Session, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Session to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Session + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetSessionRequest. */ + interface IGetSessionRequest { + + /** GetSessionRequest name */ + name?: (string|null); + } + + /** Represents a GetSessionRequest. */ + class GetSessionRequest implements IGetSessionRequest { + + /** + * Constructs a new GetSessionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IGetSessionRequest); + + /** GetSessionRequest name. */ + public name: string; + + /** + * Creates a new GetSessionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetSessionRequest instance + */ + public static create(properties?: google.spanner.v1.IGetSessionRequest): google.spanner.v1.GetSessionRequest; + + /** + * Encodes the specified GetSessionRequest message. Does not implicitly {@link google.spanner.v1.GetSessionRequest.verify|verify} messages. + * @param message GetSessionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IGetSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.GetSessionRequest.verify|verify} messages. + * @param message GetSessionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IGetSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetSessionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.GetSessionRequest; + + /** + * Decodes a GetSessionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.GetSessionRequest; + + /** + * Verifies a GetSessionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetSessionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetSessionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.GetSessionRequest; + + /** + * Creates a plain object from a GetSessionRequest message. Also converts values to other types if specified. + * @param message GetSessionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.GetSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetSessionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetSessionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListSessionsRequest. */ + interface IListSessionsRequest { + + /** ListSessionsRequest database */ + database?: (string|null); + + /** ListSessionsRequest pageSize */ + pageSize?: (number|null); + + /** ListSessionsRequest pageToken */ + pageToken?: (string|null); + + /** ListSessionsRequest filter */ + filter?: (string|null); + } + + /** Represents a ListSessionsRequest. */ + class ListSessionsRequest implements IListSessionsRequest { + + /** + * Constructs a new ListSessionsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IListSessionsRequest); + + /** ListSessionsRequest database. */ + public database: string; + + /** ListSessionsRequest pageSize. */ + public pageSize: number; + + /** ListSessionsRequest pageToken. */ + public pageToken: string; + + /** ListSessionsRequest filter. */ + public filter: string; + + /** + * Creates a new ListSessionsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListSessionsRequest instance + */ + public static create(properties?: google.spanner.v1.IListSessionsRequest): google.spanner.v1.ListSessionsRequest; + + /** + * Encodes the specified ListSessionsRequest message. Does not implicitly {@link google.spanner.v1.ListSessionsRequest.verify|verify} messages. + * @param message ListSessionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IListSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListSessionsRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ListSessionsRequest.verify|verify} messages. + * @param message ListSessionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IListSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListSessionsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListSessionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ListSessionsRequest; + + /** + * Decodes a ListSessionsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListSessionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ListSessionsRequest; + + /** + * Verifies a ListSessionsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListSessionsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListSessionsRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ListSessionsRequest; + + /** + * Creates a plain object from a ListSessionsRequest message. Also converts values to other types if specified. + * @param message ListSessionsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ListSessionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListSessionsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListSessionsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListSessionsResponse. */ + interface IListSessionsResponse { + + /** ListSessionsResponse sessions */ + sessions?: (google.spanner.v1.ISession[]|null); + + /** ListSessionsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListSessionsResponse. */ + class ListSessionsResponse implements IListSessionsResponse { + + /** + * Constructs a new ListSessionsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IListSessionsResponse); + + /** ListSessionsResponse sessions. */ + public sessions: google.spanner.v1.ISession[]; + + /** ListSessionsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListSessionsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListSessionsResponse instance + */ + public static create(properties?: google.spanner.v1.IListSessionsResponse): google.spanner.v1.ListSessionsResponse; + + /** + * Encodes the specified ListSessionsResponse message. Does not implicitly {@link google.spanner.v1.ListSessionsResponse.verify|verify} messages. + * @param message ListSessionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IListSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListSessionsResponse message, length delimited. Does not implicitly {@link google.spanner.v1.ListSessionsResponse.verify|verify} messages. + * @param message ListSessionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IListSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListSessionsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListSessionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ListSessionsResponse; + + /** + * Decodes a ListSessionsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListSessionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ListSessionsResponse; + + /** + * Verifies a ListSessionsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListSessionsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListSessionsResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ListSessionsResponse; + + /** + * Creates a plain object from a ListSessionsResponse message. Also converts values to other types if specified. + * @param message ListSessionsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ListSessionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListSessionsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListSessionsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteSessionRequest. */ + interface IDeleteSessionRequest { + + /** DeleteSessionRequest name */ + name?: (string|null); + } + + /** Represents a DeleteSessionRequest. */ + class DeleteSessionRequest implements IDeleteSessionRequest { + + /** + * Constructs a new DeleteSessionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IDeleteSessionRequest); + + /** DeleteSessionRequest name. */ + public name: string; + + /** + * Creates a new DeleteSessionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteSessionRequest instance + */ + public static create(properties?: google.spanner.v1.IDeleteSessionRequest): google.spanner.v1.DeleteSessionRequest; + + /** + * Encodes the specified DeleteSessionRequest message. Does not implicitly {@link google.spanner.v1.DeleteSessionRequest.verify|verify} messages. + * @param message DeleteSessionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IDeleteSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.DeleteSessionRequest.verify|verify} messages. + * @param message DeleteSessionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IDeleteSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteSessionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.DeleteSessionRequest; + + /** + * Decodes a DeleteSessionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.DeleteSessionRequest; + + /** + * Verifies a DeleteSessionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteSessionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteSessionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.DeleteSessionRequest; + + /** + * Creates a plain object from a DeleteSessionRequest message. Also converts values to other types if specified. + * @param message DeleteSessionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.DeleteSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteSessionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteSessionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RequestOptions. */ + interface IRequestOptions { + + /** RequestOptions priority */ + priority?: (google.spanner.v1.RequestOptions.Priority|keyof typeof google.spanner.v1.RequestOptions.Priority|null); + + /** RequestOptions requestTag */ + requestTag?: (string|null); + + /** RequestOptions transactionTag */ + transactionTag?: (string|null); + + /** RequestOptions clientContext */ + clientContext?: (google.spanner.v1.RequestOptions.IClientContext|null); + } + + /** Represents a RequestOptions. */ + class RequestOptions implements IRequestOptions { + + /** + * Constructs a new RequestOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IRequestOptions); + + /** RequestOptions priority. */ + public priority: (google.spanner.v1.RequestOptions.Priority|keyof typeof google.spanner.v1.RequestOptions.Priority); + + /** RequestOptions requestTag. */ + public requestTag: string; + + /** RequestOptions transactionTag. */ + public transactionTag: string; + + /** RequestOptions clientContext. */ + public clientContext?: (google.spanner.v1.RequestOptions.IClientContext|null); + + /** + * Creates a new RequestOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns RequestOptions instance + */ + public static create(properties?: google.spanner.v1.IRequestOptions): google.spanner.v1.RequestOptions; + + /** + * Encodes the specified RequestOptions message. Does not implicitly {@link google.spanner.v1.RequestOptions.verify|verify} messages. + * @param message RequestOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IRequestOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RequestOptions message, length delimited. Does not implicitly {@link google.spanner.v1.RequestOptions.verify|verify} messages. + * @param message RequestOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IRequestOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RequestOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RequestOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.RequestOptions; + + /** + * Decodes a RequestOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RequestOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.RequestOptions; + + /** + * Verifies a RequestOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RequestOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RequestOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.RequestOptions; + + /** + * Creates a plain object from a RequestOptions message. Also converts values to other types if specified. + * @param message RequestOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.RequestOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RequestOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RequestOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace RequestOptions { + + /** Priority enum. */ + enum Priority { + PRIORITY_UNSPECIFIED = 0, + PRIORITY_LOW = 1, + PRIORITY_MEDIUM = 2, + PRIORITY_HIGH = 3 + } + + /** Properties of a ClientContext. */ + interface IClientContext { + + /** ClientContext secureContext */ + secureContext?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a ClientContext. */ + class ClientContext implements IClientContext { + + /** + * Constructs a new ClientContext. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.RequestOptions.IClientContext); + + /** ClientContext secureContext. */ + public secureContext: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a new ClientContext instance using the specified properties. + * @param [properties] Properties to set + * @returns ClientContext instance + */ + public static create(properties?: google.spanner.v1.RequestOptions.IClientContext): google.spanner.v1.RequestOptions.ClientContext; + + /** + * Encodes the specified ClientContext message. Does not implicitly {@link google.spanner.v1.RequestOptions.ClientContext.verify|verify} messages. + * @param message ClientContext message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.RequestOptions.IClientContext, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ClientContext message, length delimited. Does not implicitly {@link google.spanner.v1.RequestOptions.ClientContext.verify|verify} messages. + * @param message ClientContext message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.RequestOptions.IClientContext, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ClientContext message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ClientContext + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.RequestOptions.ClientContext; + + /** + * Decodes a ClientContext message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ClientContext + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.RequestOptions.ClientContext; + + /** + * Verifies a ClientContext message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ClientContext message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientContext + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.RequestOptions.ClientContext; + + /** + * Creates a plain object from a ClientContext message. Also converts values to other types if specified. + * @param message ClientContext + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.RequestOptions.ClientContext, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientContext to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientContext + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a DirectedReadOptions. */ + interface IDirectedReadOptions { + + /** DirectedReadOptions includeReplicas */ + includeReplicas?: (google.spanner.v1.DirectedReadOptions.IIncludeReplicas|null); + + /** DirectedReadOptions excludeReplicas */ + excludeReplicas?: (google.spanner.v1.DirectedReadOptions.IExcludeReplicas|null); + } + + /** Represents a DirectedReadOptions. */ + class DirectedReadOptions implements IDirectedReadOptions { + + /** + * Constructs a new DirectedReadOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IDirectedReadOptions); + + /** DirectedReadOptions includeReplicas. */ + public includeReplicas?: (google.spanner.v1.DirectedReadOptions.IIncludeReplicas|null); + + /** DirectedReadOptions excludeReplicas. */ + public excludeReplicas?: (google.spanner.v1.DirectedReadOptions.IExcludeReplicas|null); + + /** DirectedReadOptions replicas. */ + public replicas?: ("includeReplicas"|"excludeReplicas"); + + /** + * Creates a new DirectedReadOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns DirectedReadOptions instance + */ + public static create(properties?: google.spanner.v1.IDirectedReadOptions): google.spanner.v1.DirectedReadOptions; + + /** + * Encodes the specified DirectedReadOptions message. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.verify|verify} messages. + * @param message DirectedReadOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IDirectedReadOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DirectedReadOptions message, length delimited. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.verify|verify} messages. + * @param message DirectedReadOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IDirectedReadOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DirectedReadOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DirectedReadOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.DirectedReadOptions; + + /** + * Decodes a DirectedReadOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DirectedReadOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.DirectedReadOptions; + + /** + * Verifies a DirectedReadOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DirectedReadOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DirectedReadOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.DirectedReadOptions; + + /** + * Creates a plain object from a DirectedReadOptions message. Also converts values to other types if specified. + * @param message DirectedReadOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.DirectedReadOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DirectedReadOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DirectedReadOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DirectedReadOptions { + + /** Properties of a ReplicaSelection. */ + interface IReplicaSelection { + + /** ReplicaSelection location */ + location?: (string|null); + + /** ReplicaSelection type */ + type?: (google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type|keyof typeof google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type|null); + } + + /** Represents a ReplicaSelection. */ + class ReplicaSelection implements IReplicaSelection { + + /** + * Constructs a new ReplicaSelection. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.DirectedReadOptions.IReplicaSelection); + + /** ReplicaSelection location. */ + public location: string; + + /** ReplicaSelection type. */ + public type: (google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type|keyof typeof google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type); + + /** + * Creates a new ReplicaSelection instance using the specified properties. + * @param [properties] Properties to set + * @returns ReplicaSelection instance + */ + public static create(properties?: google.spanner.v1.DirectedReadOptions.IReplicaSelection): google.spanner.v1.DirectedReadOptions.ReplicaSelection; + + /** + * Encodes the specified ReplicaSelection message. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.ReplicaSelection.verify|verify} messages. + * @param message ReplicaSelection message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.DirectedReadOptions.IReplicaSelection, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReplicaSelection message, length delimited. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.ReplicaSelection.verify|verify} messages. + * @param message ReplicaSelection message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.DirectedReadOptions.IReplicaSelection, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReplicaSelection message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReplicaSelection + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.DirectedReadOptions.ReplicaSelection; + + /** + * Decodes a ReplicaSelection message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReplicaSelection + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.DirectedReadOptions.ReplicaSelection; + + /** + * Verifies a ReplicaSelection message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReplicaSelection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReplicaSelection + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.DirectedReadOptions.ReplicaSelection; + + /** + * Creates a plain object from a ReplicaSelection message. Also converts values to other types if specified. + * @param message ReplicaSelection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.DirectedReadOptions.ReplicaSelection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReplicaSelection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReplicaSelection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ReplicaSelection { + + /** Type enum. */ + enum Type { + TYPE_UNSPECIFIED = 0, + READ_WRITE = 1, + READ_ONLY = 2 + } + } + + /** Properties of an IncludeReplicas. */ + interface IIncludeReplicas { + + /** IncludeReplicas replicaSelections */ + replicaSelections?: (google.spanner.v1.DirectedReadOptions.IReplicaSelection[]|null); + + /** IncludeReplicas autoFailoverDisabled */ + autoFailoverDisabled?: (boolean|null); + } + + /** Represents an IncludeReplicas. */ + class IncludeReplicas implements IIncludeReplicas { + + /** + * Constructs a new IncludeReplicas. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.DirectedReadOptions.IIncludeReplicas); + + /** IncludeReplicas replicaSelections. */ + public replicaSelections: google.spanner.v1.DirectedReadOptions.IReplicaSelection[]; + + /** IncludeReplicas autoFailoverDisabled. */ + public autoFailoverDisabled: boolean; + + /** + * Creates a new IncludeReplicas instance using the specified properties. + * @param [properties] Properties to set + * @returns IncludeReplicas instance + */ + public static create(properties?: google.spanner.v1.DirectedReadOptions.IIncludeReplicas): google.spanner.v1.DirectedReadOptions.IncludeReplicas; + + /** + * Encodes the specified IncludeReplicas message. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.IncludeReplicas.verify|verify} messages. + * @param message IncludeReplicas message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.DirectedReadOptions.IIncludeReplicas, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified IncludeReplicas message, length delimited. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.IncludeReplicas.verify|verify} messages. + * @param message IncludeReplicas message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.DirectedReadOptions.IIncludeReplicas, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an IncludeReplicas message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns IncludeReplicas + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.DirectedReadOptions.IncludeReplicas; + + /** + * Decodes an IncludeReplicas message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns IncludeReplicas + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.DirectedReadOptions.IncludeReplicas; + + /** + * Verifies an IncludeReplicas message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an IncludeReplicas message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IncludeReplicas + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.DirectedReadOptions.IncludeReplicas; + + /** + * Creates a plain object from an IncludeReplicas message. Also converts values to other types if specified. + * @param message IncludeReplicas + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.DirectedReadOptions.IncludeReplicas, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IncludeReplicas to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IncludeReplicas + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExcludeReplicas. */ + interface IExcludeReplicas { + + /** ExcludeReplicas replicaSelections */ + replicaSelections?: (google.spanner.v1.DirectedReadOptions.IReplicaSelection[]|null); + } + + /** Represents an ExcludeReplicas. */ + class ExcludeReplicas implements IExcludeReplicas { + + /** + * Constructs a new ExcludeReplicas. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.DirectedReadOptions.IExcludeReplicas); + + /** ExcludeReplicas replicaSelections. */ + public replicaSelections: google.spanner.v1.DirectedReadOptions.IReplicaSelection[]; + + /** + * Creates a new ExcludeReplicas instance using the specified properties. + * @param [properties] Properties to set + * @returns ExcludeReplicas instance + */ + public static create(properties?: google.spanner.v1.DirectedReadOptions.IExcludeReplicas): google.spanner.v1.DirectedReadOptions.ExcludeReplicas; + + /** + * Encodes the specified ExcludeReplicas message. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.ExcludeReplicas.verify|verify} messages. + * @param message ExcludeReplicas message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.DirectedReadOptions.IExcludeReplicas, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExcludeReplicas message, length delimited. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.ExcludeReplicas.verify|verify} messages. + * @param message ExcludeReplicas message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.DirectedReadOptions.IExcludeReplicas, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExcludeReplicas message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExcludeReplicas + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.DirectedReadOptions.ExcludeReplicas; + + /** + * Decodes an ExcludeReplicas message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExcludeReplicas + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.DirectedReadOptions.ExcludeReplicas; + + /** + * Verifies an ExcludeReplicas message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExcludeReplicas message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExcludeReplicas + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.DirectedReadOptions.ExcludeReplicas; + + /** + * Creates a plain object from an ExcludeReplicas message. Also converts values to other types if specified. + * @param message ExcludeReplicas + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.DirectedReadOptions.ExcludeReplicas, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExcludeReplicas to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExcludeReplicas + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExecuteSqlRequest. */ + interface IExecuteSqlRequest { + + /** ExecuteSqlRequest session */ + session?: (string|null); + + /** ExecuteSqlRequest transaction */ + transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** ExecuteSqlRequest sql */ + sql?: (string|null); + + /** ExecuteSqlRequest params */ + params?: (google.protobuf.IStruct|null); + + /** ExecuteSqlRequest paramTypes */ + paramTypes?: ({ [k: string]: google.spanner.v1.IType }|null); + + /** ExecuteSqlRequest resumeToken */ + resumeToken?: (Uint8Array|Buffer|string|null); + + /** ExecuteSqlRequest queryMode */ + queryMode?: (google.spanner.v1.ExecuteSqlRequest.QueryMode|keyof typeof google.spanner.v1.ExecuteSqlRequest.QueryMode|null); + + /** ExecuteSqlRequest partitionToken */ + partitionToken?: (Uint8Array|Buffer|string|null); + + /** ExecuteSqlRequest seqno */ + seqno?: (number|Long|string|null); + + /** ExecuteSqlRequest queryOptions */ + queryOptions?: (google.spanner.v1.ExecuteSqlRequest.IQueryOptions|null); + + /** ExecuteSqlRequest requestOptions */ + requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** ExecuteSqlRequest directedReadOptions */ + directedReadOptions?: (google.spanner.v1.IDirectedReadOptions|null); + + /** ExecuteSqlRequest dataBoostEnabled */ + dataBoostEnabled?: (boolean|null); + + /** ExecuteSqlRequest lastStatement */ + lastStatement?: (boolean|null); + + /** ExecuteSqlRequest routingHint */ + routingHint?: (google.spanner.v1.IRoutingHint|null); + } + + /** Represents an ExecuteSqlRequest. */ + class ExecuteSqlRequest implements IExecuteSqlRequest { + + /** + * Constructs a new ExecuteSqlRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IExecuteSqlRequest); + + /** ExecuteSqlRequest session. */ + public session: string; + + /** ExecuteSqlRequest transaction. */ + public transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** ExecuteSqlRequest sql. */ + public sql: string; + + /** ExecuteSqlRequest params. */ + public params?: (google.protobuf.IStruct|null); + + /** ExecuteSqlRequest paramTypes. */ + public paramTypes: { [k: string]: google.spanner.v1.IType }; + + /** ExecuteSqlRequest resumeToken. */ + public resumeToken: (Uint8Array|Buffer|string); + + /** ExecuteSqlRequest queryMode. */ + public queryMode: (google.spanner.v1.ExecuteSqlRequest.QueryMode|keyof typeof google.spanner.v1.ExecuteSqlRequest.QueryMode); + + /** ExecuteSqlRequest partitionToken. */ + public partitionToken: (Uint8Array|Buffer|string); + + /** ExecuteSqlRequest seqno. */ + public seqno: (number|Long|string); + + /** ExecuteSqlRequest queryOptions. */ + public queryOptions?: (google.spanner.v1.ExecuteSqlRequest.IQueryOptions|null); + + /** ExecuteSqlRequest requestOptions. */ + public requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** ExecuteSqlRequest directedReadOptions. */ + public directedReadOptions?: (google.spanner.v1.IDirectedReadOptions|null); + + /** ExecuteSqlRequest dataBoostEnabled. */ + public dataBoostEnabled: boolean; + + /** ExecuteSqlRequest lastStatement. */ + public lastStatement: boolean; + + /** ExecuteSqlRequest routingHint. */ + public routingHint?: (google.spanner.v1.IRoutingHint|null); + + /** + * Creates a new ExecuteSqlRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ExecuteSqlRequest instance + */ + public static create(properties?: google.spanner.v1.IExecuteSqlRequest): google.spanner.v1.ExecuteSqlRequest; + + /** + * Encodes the specified ExecuteSqlRequest message. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.verify|verify} messages. + * @param message ExecuteSqlRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IExecuteSqlRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExecuteSqlRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.verify|verify} messages. + * @param message ExecuteSqlRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IExecuteSqlRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExecuteSqlRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExecuteSqlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteSqlRequest; + + /** + * Decodes an ExecuteSqlRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExecuteSqlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteSqlRequest; + + /** + * Verifies an ExecuteSqlRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExecuteSqlRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecuteSqlRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteSqlRequest; + + /** + * Creates a plain object from an ExecuteSqlRequest message. Also converts values to other types if specified. + * @param message ExecuteSqlRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ExecuteSqlRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecuteSqlRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecuteSqlRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExecuteSqlRequest { + + /** QueryMode enum. */ + enum QueryMode { + NORMAL = 0, + PLAN = 1, + PROFILE = 2, + WITH_STATS = 3, + WITH_PLAN_AND_STATS = 4 + } + + /** Properties of a QueryOptions. */ + interface IQueryOptions { + + /** QueryOptions optimizerVersion */ + optimizerVersion?: (string|null); + + /** QueryOptions optimizerStatisticsPackage */ + optimizerStatisticsPackage?: (string|null); + } + + /** Represents a QueryOptions. */ + class QueryOptions implements IQueryOptions { + + /** + * Constructs a new QueryOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ExecuteSqlRequest.IQueryOptions); + + /** QueryOptions optimizerVersion. */ + public optimizerVersion: string; + + /** QueryOptions optimizerStatisticsPackage. */ + public optimizerStatisticsPackage: string; + + /** + * Creates a new QueryOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns QueryOptions instance + */ + public static create(properties?: google.spanner.v1.ExecuteSqlRequest.IQueryOptions): google.spanner.v1.ExecuteSqlRequest.QueryOptions; + + /** + * Encodes the specified QueryOptions message. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.QueryOptions.verify|verify} messages. + * @param message QueryOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ExecuteSqlRequest.IQueryOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified QueryOptions message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.QueryOptions.verify|verify} messages. + * @param message QueryOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ExecuteSqlRequest.IQueryOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a QueryOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns QueryOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteSqlRequest.QueryOptions; + + /** + * Decodes a QueryOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns QueryOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteSqlRequest.QueryOptions; + + /** + * Verifies a QueryOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a QueryOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteSqlRequest.QueryOptions; + + /** + * Creates a plain object from a QueryOptions message. Also converts values to other types if specified. + * @param message QueryOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ExecuteSqlRequest.QueryOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExecuteBatchDmlRequest. */ + interface IExecuteBatchDmlRequest { + + /** ExecuteBatchDmlRequest session */ + session?: (string|null); + + /** ExecuteBatchDmlRequest transaction */ + transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** ExecuteBatchDmlRequest statements */ + statements?: (google.spanner.v1.ExecuteBatchDmlRequest.IStatement[]|null); + + /** ExecuteBatchDmlRequest seqno */ + seqno?: (number|Long|string|null); + + /** ExecuteBatchDmlRequest requestOptions */ + requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** ExecuteBatchDmlRequest lastStatements */ + lastStatements?: (boolean|null); + } + + /** Represents an ExecuteBatchDmlRequest. */ + class ExecuteBatchDmlRequest implements IExecuteBatchDmlRequest { + + /** + * Constructs a new ExecuteBatchDmlRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IExecuteBatchDmlRequest); + + /** ExecuteBatchDmlRequest session. */ + public session: string; + + /** ExecuteBatchDmlRequest transaction. */ + public transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** ExecuteBatchDmlRequest statements. */ + public statements: google.spanner.v1.ExecuteBatchDmlRequest.IStatement[]; + + /** ExecuteBatchDmlRequest seqno. */ + public seqno: (number|Long|string); + + /** ExecuteBatchDmlRequest requestOptions. */ + public requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** ExecuteBatchDmlRequest lastStatements. */ + public lastStatements: boolean; + + /** + * Creates a new ExecuteBatchDmlRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ExecuteBatchDmlRequest instance + */ + public static create(properties?: google.spanner.v1.IExecuteBatchDmlRequest): google.spanner.v1.ExecuteBatchDmlRequest; + + /** + * Encodes the specified ExecuteBatchDmlRequest message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.verify|verify} messages. + * @param message ExecuteBatchDmlRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IExecuteBatchDmlRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExecuteBatchDmlRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.verify|verify} messages. + * @param message ExecuteBatchDmlRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IExecuteBatchDmlRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExecuteBatchDmlRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExecuteBatchDmlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteBatchDmlRequest; + + /** + * Decodes an ExecuteBatchDmlRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExecuteBatchDmlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteBatchDmlRequest; + + /** + * Verifies an ExecuteBatchDmlRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExecuteBatchDmlRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecuteBatchDmlRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteBatchDmlRequest; + + /** + * Creates a plain object from an ExecuteBatchDmlRequest message. Also converts values to other types if specified. + * @param message ExecuteBatchDmlRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ExecuteBatchDmlRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecuteBatchDmlRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecuteBatchDmlRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExecuteBatchDmlRequest { + + /** Properties of a Statement. */ + interface IStatement { + + /** Statement sql */ + sql?: (string|null); + + /** Statement params */ + params?: (google.protobuf.IStruct|null); + + /** Statement paramTypes */ + paramTypes?: ({ [k: string]: google.spanner.v1.IType }|null); + } + + /** Represents a Statement. */ + class Statement implements IStatement { + + /** + * Constructs a new Statement. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ExecuteBatchDmlRequest.IStatement); + + /** Statement sql. */ + public sql: string; + + /** Statement params. */ + public params?: (google.protobuf.IStruct|null); + + /** Statement paramTypes. */ + public paramTypes: { [k: string]: google.spanner.v1.IType }; + + /** + * Creates a new Statement instance using the specified properties. + * @param [properties] Properties to set + * @returns Statement instance + */ + public static create(properties?: google.spanner.v1.ExecuteBatchDmlRequest.IStatement): google.spanner.v1.ExecuteBatchDmlRequest.Statement; + + /** + * Encodes the specified Statement message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.Statement.verify|verify} messages. + * @param message Statement message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ExecuteBatchDmlRequest.IStatement, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Statement message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.Statement.verify|verify} messages. + * @param message Statement message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ExecuteBatchDmlRequest.IStatement, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Statement message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Statement + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteBatchDmlRequest.Statement; + + /** + * Decodes a Statement message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Statement + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteBatchDmlRequest.Statement; + + /** + * Verifies a Statement message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Statement message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Statement + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteBatchDmlRequest.Statement; + + /** + * Creates a plain object from a Statement message. Also converts values to other types if specified. + * @param message Statement + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ExecuteBatchDmlRequest.Statement, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Statement to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Statement + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExecuteBatchDmlResponse. */ + interface IExecuteBatchDmlResponse { + + /** ExecuteBatchDmlResponse resultSets */ + resultSets?: (google.spanner.v1.IResultSet[]|null); + + /** ExecuteBatchDmlResponse status */ + status?: (google.rpc.IStatus|null); + + /** ExecuteBatchDmlResponse precommitToken */ + precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + } + + /** Represents an ExecuteBatchDmlResponse. */ + class ExecuteBatchDmlResponse implements IExecuteBatchDmlResponse { + + /** + * Constructs a new ExecuteBatchDmlResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IExecuteBatchDmlResponse); + + /** ExecuteBatchDmlResponse resultSets. */ + public resultSets: google.spanner.v1.IResultSet[]; + + /** ExecuteBatchDmlResponse status. */ + public status?: (google.rpc.IStatus|null); + + /** ExecuteBatchDmlResponse precommitToken. */ + public precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** + * Creates a new ExecuteBatchDmlResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ExecuteBatchDmlResponse instance + */ + public static create(properties?: google.spanner.v1.IExecuteBatchDmlResponse): google.spanner.v1.ExecuteBatchDmlResponse; + + /** + * Encodes the specified ExecuteBatchDmlResponse message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlResponse.verify|verify} messages. + * @param message ExecuteBatchDmlResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IExecuteBatchDmlResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExecuteBatchDmlResponse message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlResponse.verify|verify} messages. + * @param message ExecuteBatchDmlResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IExecuteBatchDmlResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExecuteBatchDmlResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExecuteBatchDmlResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteBatchDmlResponse; + + /** + * Decodes an ExecuteBatchDmlResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExecuteBatchDmlResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteBatchDmlResponse; + + /** + * Verifies an ExecuteBatchDmlResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExecuteBatchDmlResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecuteBatchDmlResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteBatchDmlResponse; + + /** + * Creates a plain object from an ExecuteBatchDmlResponse message. Also converts values to other types if specified. + * @param message ExecuteBatchDmlResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ExecuteBatchDmlResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecuteBatchDmlResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecuteBatchDmlResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionOptions. */ + interface IPartitionOptions { + + /** PartitionOptions partitionSizeBytes */ + partitionSizeBytes?: (number|Long|string|null); + + /** PartitionOptions maxPartitions */ + maxPartitions?: (number|Long|string|null); + } + + /** Represents a PartitionOptions. */ + class PartitionOptions implements IPartitionOptions { + + /** + * Constructs a new PartitionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IPartitionOptions); + + /** PartitionOptions partitionSizeBytes. */ + public partitionSizeBytes: (number|Long|string); + + /** PartitionOptions maxPartitions. */ + public maxPartitions: (number|Long|string); + + /** + * Creates a new PartitionOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionOptions instance + */ + public static create(properties?: google.spanner.v1.IPartitionOptions): google.spanner.v1.PartitionOptions; + + /** + * Encodes the specified PartitionOptions message. Does not implicitly {@link google.spanner.v1.PartitionOptions.verify|verify} messages. + * @param message PartitionOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IPartitionOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionOptions message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionOptions.verify|verify} messages. + * @param message PartitionOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IPartitionOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartitionOptions; + + /** + * Decodes a PartitionOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartitionOptions; + + /** + * Verifies a PartitionOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartitionOptions; + + /** + * Creates a plain object from a PartitionOptions message. Also converts values to other types if specified. + * @param message PartitionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.PartitionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest session */ + session?: (string|null); + + /** PartitionQueryRequest transaction */ + transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** PartitionQueryRequest sql */ + sql?: (string|null); + + /** PartitionQueryRequest params */ + params?: (google.protobuf.IStruct|null); + + /** PartitionQueryRequest paramTypes */ + paramTypes?: ({ [k: string]: google.spanner.v1.IType }|null); + + /** PartitionQueryRequest partitionOptions */ + partitionOptions?: (google.spanner.v1.IPartitionOptions|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IPartitionQueryRequest); + + /** PartitionQueryRequest session. */ + public session: string; + + /** PartitionQueryRequest transaction. */ + public transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** PartitionQueryRequest sql. */ + public sql: string; + + /** PartitionQueryRequest params. */ + public params?: (google.protobuf.IStruct|null); + + /** PartitionQueryRequest paramTypes. */ + public paramTypes: { [k: string]: google.spanner.v1.IType }; + + /** PartitionQueryRequest partitionOptions. */ + public partitionOptions?: (google.spanner.v1.IPartitionOptions|null); + + /** + * Creates a new PartitionQueryRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionQueryRequest instance + */ + public static create(properties?: google.spanner.v1.IPartitionQueryRequest): google.spanner.v1.PartitionQueryRequest; + + /** + * Encodes the specified PartitionQueryRequest message. Does not implicitly {@link google.spanner.v1.PartitionQueryRequest.verify|verify} messages. + * @param message PartitionQueryRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IPartitionQueryRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionQueryRequest message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionQueryRequest.verify|verify} messages. + * @param message PartitionQueryRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IPartitionQueryRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionQueryRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionQueryRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartitionQueryRequest; + + /** + * Decodes a PartitionQueryRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionQueryRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartitionQueryRequest; + + /** + * Verifies a PartitionQueryRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionReadRequest. */ + interface IPartitionReadRequest { + + /** PartitionReadRequest session */ + session?: (string|null); + + /** PartitionReadRequest transaction */ + transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** PartitionReadRequest table */ + table?: (string|null); + + /** PartitionReadRequest index */ + index?: (string|null); + + /** PartitionReadRequest columns */ + columns?: (string[]|null); + + /** PartitionReadRequest keySet */ + keySet?: (google.spanner.v1.IKeySet|null); + + /** PartitionReadRequest partitionOptions */ + partitionOptions?: (google.spanner.v1.IPartitionOptions|null); + } + + /** Represents a PartitionReadRequest. */ + class PartitionReadRequest implements IPartitionReadRequest { + + /** + * Constructs a new PartitionReadRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IPartitionReadRequest); + + /** PartitionReadRequest session. */ + public session: string; + + /** PartitionReadRequest transaction. */ + public transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** PartitionReadRequest table. */ + public table: string; + + /** PartitionReadRequest index. */ + public index: string; + + /** PartitionReadRequest columns. */ + public columns: string[]; + + /** PartitionReadRequest keySet. */ + public keySet?: (google.spanner.v1.IKeySet|null); + + /** PartitionReadRequest partitionOptions. */ + public partitionOptions?: (google.spanner.v1.IPartitionOptions|null); + + /** + * Creates a new PartitionReadRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionReadRequest instance + */ + public static create(properties?: google.spanner.v1.IPartitionReadRequest): google.spanner.v1.PartitionReadRequest; + + /** + * Encodes the specified PartitionReadRequest message. Does not implicitly {@link google.spanner.v1.PartitionReadRequest.verify|verify} messages. + * @param message PartitionReadRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IPartitionReadRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionReadRequest message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionReadRequest.verify|verify} messages. + * @param message PartitionReadRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IPartitionReadRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionReadRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionReadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartitionReadRequest; + + /** + * Decodes a PartitionReadRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionReadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartitionReadRequest; + + /** + * Verifies a PartitionReadRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionReadRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionReadRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartitionReadRequest; + + /** + * Creates a plain object from a PartitionReadRequest message. Also converts values to other types if specified. + * @param message PartitionReadRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.PartitionReadRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionReadRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionReadRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Partition. */ + interface IPartition { + + /** Partition partitionToken */ + partitionToken?: (Uint8Array|Buffer|string|null); + } + + /** Represents a Partition. */ + class Partition implements IPartition { + + /** + * Constructs a new Partition. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IPartition); + + /** Partition partitionToken. */ + public partitionToken: (Uint8Array|Buffer|string); + + /** + * Creates a new Partition instance using the specified properties. + * @param [properties] Properties to set + * @returns Partition instance + */ + public static create(properties?: google.spanner.v1.IPartition): google.spanner.v1.Partition; + + /** + * Encodes the specified Partition message. Does not implicitly {@link google.spanner.v1.Partition.verify|verify} messages. + * @param message Partition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IPartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Partition message, length delimited. Does not implicitly {@link google.spanner.v1.Partition.verify|verify} messages. + * @param message Partition message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IPartition, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Partition message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Partition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Partition; + + /** + * Decodes a Partition message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Partition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Partition; + + /** + * Verifies a Partition message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Partition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Partition + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Partition; + + /** + * Creates a plain object from a Partition message. Also converts values to other types if specified. + * @param message Partition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Partition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Partition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Partition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionResponse. */ + interface IPartitionResponse { + + /** PartitionResponse partitions */ + partitions?: (google.spanner.v1.IPartition[]|null); + + /** PartitionResponse transaction */ + transaction?: (google.spanner.v1.ITransaction|null); + } + + /** Represents a PartitionResponse. */ + class PartitionResponse implements IPartitionResponse { + + /** + * Constructs a new PartitionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IPartitionResponse); + + /** PartitionResponse partitions. */ + public partitions: google.spanner.v1.IPartition[]; + + /** PartitionResponse transaction. */ + public transaction?: (google.spanner.v1.ITransaction|null); + + /** + * Creates a new PartitionResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionResponse instance + */ + public static create(properties?: google.spanner.v1.IPartitionResponse): google.spanner.v1.PartitionResponse; + + /** + * Encodes the specified PartitionResponse message. Does not implicitly {@link google.spanner.v1.PartitionResponse.verify|verify} messages. + * @param message PartitionResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IPartitionResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionResponse message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionResponse.verify|verify} messages. + * @param message PartitionResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IPartitionResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartitionResponse; + + /** + * Decodes a PartitionResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartitionResponse; + + /** + * Verifies a PartitionResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartitionResponse; + + /** + * Creates a plain object from a PartitionResponse message. Also converts values to other types if specified. + * @param message PartitionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.PartitionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadRequest. */ + interface IReadRequest { + + /** ReadRequest session */ + session?: (string|null); + + /** ReadRequest transaction */ + transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** ReadRequest table */ + table?: (string|null); + + /** ReadRequest index */ + index?: (string|null); + + /** ReadRequest columns */ + columns?: (string[]|null); + + /** ReadRequest keySet */ + keySet?: (google.spanner.v1.IKeySet|null); + + /** ReadRequest limit */ + limit?: (number|Long|string|null); + + /** ReadRequest resumeToken */ + resumeToken?: (Uint8Array|Buffer|string|null); + + /** ReadRequest partitionToken */ + partitionToken?: (Uint8Array|Buffer|string|null); + + /** ReadRequest requestOptions */ + requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** ReadRequest directedReadOptions */ + directedReadOptions?: (google.spanner.v1.IDirectedReadOptions|null); + + /** ReadRequest dataBoostEnabled */ + dataBoostEnabled?: (boolean|null); + + /** ReadRequest orderBy */ + orderBy?: (google.spanner.v1.ReadRequest.OrderBy|keyof typeof google.spanner.v1.ReadRequest.OrderBy|null); + + /** ReadRequest lockHint */ + lockHint?: (google.spanner.v1.ReadRequest.LockHint|keyof typeof google.spanner.v1.ReadRequest.LockHint|null); + + /** ReadRequest routingHint */ + routingHint?: (google.spanner.v1.IRoutingHint|null); + } + + /** Represents a ReadRequest. */ + class ReadRequest implements IReadRequest { + + /** + * Constructs a new ReadRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IReadRequest); + + /** ReadRequest session. */ + public session: string; + + /** ReadRequest transaction. */ + public transaction?: (google.spanner.v1.ITransactionSelector|null); + + /** ReadRequest table. */ + public table: string; + + /** ReadRequest index. */ + public index: string; + + /** ReadRequest columns. */ + public columns: string[]; + + /** ReadRequest keySet. */ + public keySet?: (google.spanner.v1.IKeySet|null); + + /** ReadRequest limit. */ + public limit: (number|Long|string); + + /** ReadRequest resumeToken. */ + public resumeToken: (Uint8Array|Buffer|string); + + /** ReadRequest partitionToken. */ + public partitionToken: (Uint8Array|Buffer|string); + + /** ReadRequest requestOptions. */ + public requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** ReadRequest directedReadOptions. */ + public directedReadOptions?: (google.spanner.v1.IDirectedReadOptions|null); + + /** ReadRequest dataBoostEnabled. */ + public dataBoostEnabled: boolean; + + /** ReadRequest orderBy. */ + public orderBy: (google.spanner.v1.ReadRequest.OrderBy|keyof typeof google.spanner.v1.ReadRequest.OrderBy); + + /** ReadRequest lockHint. */ + public lockHint: (google.spanner.v1.ReadRequest.LockHint|keyof typeof google.spanner.v1.ReadRequest.LockHint); + + /** ReadRequest routingHint. */ + public routingHint?: (google.spanner.v1.IRoutingHint|null); + + /** + * Creates a new ReadRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadRequest instance + */ + public static create(properties?: google.spanner.v1.IReadRequest): google.spanner.v1.ReadRequest; + + /** + * Encodes the specified ReadRequest message. Does not implicitly {@link google.spanner.v1.ReadRequest.verify|verify} messages. + * @param message ReadRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IReadRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ReadRequest.verify|verify} messages. + * @param message ReadRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IReadRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ReadRequest; + + /** + * Decodes a ReadRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ReadRequest; + + /** + * Verifies a ReadRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ReadRequest; + + /** + * Creates a plain object from a ReadRequest message. Also converts values to other types if specified. + * @param message ReadRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ReadRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ReadRequest { + + /** OrderBy enum. */ + enum OrderBy { + ORDER_BY_UNSPECIFIED = 0, + ORDER_BY_PRIMARY_KEY = 1, + ORDER_BY_NO_ORDER = 2 + } + + /** LockHint enum. */ + enum LockHint { + LOCK_HINT_UNSPECIFIED = 0, + LOCK_HINT_SHARED = 1, + LOCK_HINT_EXCLUSIVE = 2 + } + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest session */ + session?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.spanner.v1.ITransactionOptions|null); + + /** BeginTransactionRequest requestOptions */ + requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** BeginTransactionRequest mutationKey */ + mutationKey?: (google.spanner.v1.IMutation|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IBeginTransactionRequest); + + /** BeginTransactionRequest session. */ + public session: string; + + /** BeginTransactionRequest options. */ + public options?: (google.spanner.v1.ITransactionOptions|null); + + /** BeginTransactionRequest requestOptions. */ + public requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** BeginTransactionRequest mutationKey. */ + public mutationKey?: (google.spanner.v1.IMutation|null); + + /** + * Creates a new BeginTransactionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns BeginTransactionRequest instance + */ + public static create(properties?: google.spanner.v1.IBeginTransactionRequest): google.spanner.v1.BeginTransactionRequest; + + /** + * Encodes the specified BeginTransactionRequest message. Does not implicitly {@link google.spanner.v1.BeginTransactionRequest.verify|verify} messages. + * @param message BeginTransactionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IBeginTransactionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BeginTransactionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.BeginTransactionRequest.verify|verify} messages. + * @param message BeginTransactionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IBeginTransactionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BeginTransactionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BeginTransactionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BeginTransactionRequest; + + /** + * Decodes a BeginTransactionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BeginTransactionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BeginTransactionRequest; + + /** + * Verifies a BeginTransactionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest session */ + session?: (string|null); + + /** CommitRequest transactionId */ + transactionId?: (Uint8Array|Buffer|string|null); + + /** CommitRequest singleUseTransaction */ + singleUseTransaction?: (google.spanner.v1.ITransactionOptions|null); + + /** CommitRequest mutations */ + mutations?: (google.spanner.v1.IMutation[]|null); + + /** CommitRequest returnCommitStats */ + returnCommitStats?: (boolean|null); + + /** CommitRequest maxCommitDelay */ + maxCommitDelay?: (google.protobuf.IDuration|null); + + /** CommitRequest requestOptions */ + requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** CommitRequest precommitToken */ + precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ICommitRequest); + + /** CommitRequest session. */ + public session: string; + + /** CommitRequest transactionId. */ + public transactionId?: (Uint8Array|Buffer|string|null); + + /** CommitRequest singleUseTransaction. */ + public singleUseTransaction?: (google.spanner.v1.ITransactionOptions|null); + + /** CommitRequest mutations. */ + public mutations: google.spanner.v1.IMutation[]; + + /** CommitRequest returnCommitStats. */ + public returnCommitStats: boolean; + + /** CommitRequest maxCommitDelay. */ + public maxCommitDelay?: (google.protobuf.IDuration|null); + + /** CommitRequest requestOptions. */ + public requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** CommitRequest precommitToken. */ + public precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** CommitRequest transaction. */ + public transaction?: ("transactionId"|"singleUseTransaction"); + + /** + * Creates a new CommitRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CommitRequest instance + */ + public static create(properties?: google.spanner.v1.ICommitRequest): google.spanner.v1.CommitRequest; + + /** + * Encodes the specified CommitRequest message. Does not implicitly {@link google.spanner.v1.CommitRequest.verify|verify} messages. + * @param message CommitRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ICommitRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CommitRequest message, length delimited. Does not implicitly {@link google.spanner.v1.CommitRequest.verify|verify} messages. + * @param message CommitRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ICommitRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CommitRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CommitRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.CommitRequest; + + /** + * Decodes a CommitRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CommitRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.CommitRequest; + + /** + * Verifies a CommitRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest session */ + session?: (string|null); + + /** RollbackRequest transactionId */ + transactionId?: (Uint8Array|Buffer|string|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IRollbackRequest); + + /** RollbackRequest session. */ + public session: string; + + /** RollbackRequest transactionId. */ + public transactionId: (Uint8Array|Buffer|string); + + /** + * Creates a new RollbackRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns RollbackRequest instance + */ + public static create(properties?: google.spanner.v1.IRollbackRequest): google.spanner.v1.RollbackRequest; + + /** + * Encodes the specified RollbackRequest message. Does not implicitly {@link google.spanner.v1.RollbackRequest.verify|verify} messages. + * @param message RollbackRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IRollbackRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RollbackRequest message, length delimited. Does not implicitly {@link google.spanner.v1.RollbackRequest.verify|verify} messages. + * @param message RollbackRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IRollbackRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RollbackRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RollbackRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.RollbackRequest; + + /** + * Decodes a RollbackRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RollbackRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.RollbackRequest; + + /** + * Verifies a RollbackRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest session */ + session?: (string|null); + + /** BatchWriteRequest requestOptions */ + requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** BatchWriteRequest mutationGroups */ + mutationGroups?: (google.spanner.v1.BatchWriteRequest.IMutationGroup[]|null); + + /** BatchWriteRequest excludeTxnFromChangeStreams */ + excludeTxnFromChangeStreams?: (boolean|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IBatchWriteRequest); + + /** BatchWriteRequest session. */ + public session: string; + + /** BatchWriteRequest requestOptions. */ + public requestOptions?: (google.spanner.v1.IRequestOptions|null); + + /** BatchWriteRequest mutationGroups. */ + public mutationGroups: google.spanner.v1.BatchWriteRequest.IMutationGroup[]; + + /** BatchWriteRequest excludeTxnFromChangeStreams. */ + public excludeTxnFromChangeStreams: boolean; + + /** + * Creates a new BatchWriteRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns BatchWriteRequest instance + */ + public static create(properties?: google.spanner.v1.IBatchWriteRequest): google.spanner.v1.BatchWriteRequest; + + /** + * Encodes the specified BatchWriteRequest message. Does not implicitly {@link google.spanner.v1.BatchWriteRequest.verify|verify} messages. + * @param message BatchWriteRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IBatchWriteRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BatchWriteRequest message, length delimited. Does not implicitly {@link google.spanner.v1.BatchWriteRequest.verify|verify} messages. + * @param message BatchWriteRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IBatchWriteRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BatchWriteRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BatchWriteRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BatchWriteRequest; + + /** + * Decodes a BatchWriteRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BatchWriteRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BatchWriteRequest; + + /** + * Verifies a BatchWriteRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace BatchWriteRequest { + + /** Properties of a MutationGroup. */ + interface IMutationGroup { + + /** MutationGroup mutations */ + mutations?: (google.spanner.v1.IMutation[]|null); + } + + /** Represents a MutationGroup. */ + class MutationGroup implements IMutationGroup { + + /** + * Constructs a new MutationGroup. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.BatchWriteRequest.IMutationGroup); + + /** MutationGroup mutations. */ + public mutations: google.spanner.v1.IMutation[]; + + /** + * Creates a new MutationGroup instance using the specified properties. + * @param [properties] Properties to set + * @returns MutationGroup instance + */ + public static create(properties?: google.spanner.v1.BatchWriteRequest.IMutationGroup): google.spanner.v1.BatchWriteRequest.MutationGroup; + + /** + * Encodes the specified MutationGroup message. Does not implicitly {@link google.spanner.v1.BatchWriteRequest.MutationGroup.verify|verify} messages. + * @param message MutationGroup message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.BatchWriteRequest.IMutationGroup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MutationGroup message, length delimited. Does not implicitly {@link google.spanner.v1.BatchWriteRequest.MutationGroup.verify|verify} messages. + * @param message MutationGroup message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.BatchWriteRequest.IMutationGroup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MutationGroup message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MutationGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BatchWriteRequest.MutationGroup; + + /** + * Decodes a MutationGroup message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MutationGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BatchWriteRequest.MutationGroup; + + /** + * Verifies a MutationGroup message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MutationGroup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MutationGroup + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.BatchWriteRequest.MutationGroup; + + /** + * Creates a plain object from a MutationGroup message. Also converts values to other types if specified. + * @param message MutationGroup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.BatchWriteRequest.MutationGroup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MutationGroup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MutationGroup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse indexes */ + indexes?: (number[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus|null); + + /** BatchWriteResponse commitTimestamp */ + commitTimestamp?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IBatchWriteResponse); + + /** BatchWriteResponse indexes. */ + public indexes: number[]; + + /** BatchWriteResponse status. */ + public status?: (google.rpc.IStatus|null); + + /** BatchWriteResponse commitTimestamp. */ + public commitTimestamp?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new BatchWriteResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns BatchWriteResponse instance + */ + public static create(properties?: google.spanner.v1.IBatchWriteResponse): google.spanner.v1.BatchWriteResponse; + + /** + * Encodes the specified BatchWriteResponse message. Does not implicitly {@link google.spanner.v1.BatchWriteResponse.verify|verify} messages. + * @param message BatchWriteResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IBatchWriteResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BatchWriteResponse message, length delimited. Does not implicitly {@link google.spanner.v1.BatchWriteResponse.verify|verify} messages. + * @param message BatchWriteResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IBatchWriteResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BatchWriteResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BatchWriteResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BatchWriteResponse; + + /** + * Decodes a BatchWriteResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BatchWriteResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BatchWriteResponse; + + /** + * Verifies a BatchWriteResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.BatchWriteResponse; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse commitTimestamp */ + commitTimestamp?: (google.protobuf.ITimestamp|null); + + /** CommitResponse commitStats */ + commitStats?: (google.spanner.v1.CommitResponse.ICommitStats|null); + + /** CommitResponse precommitToken */ + precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** CommitResponse snapshotTimestamp */ + snapshotTimestamp?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ICommitResponse); + + /** CommitResponse commitTimestamp. */ + public commitTimestamp?: (google.protobuf.ITimestamp|null); + + /** CommitResponse commitStats. */ + public commitStats?: (google.spanner.v1.CommitResponse.ICommitStats|null); + + /** CommitResponse precommitToken. */ + public precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** CommitResponse snapshotTimestamp. */ + public snapshotTimestamp?: (google.protobuf.ITimestamp|null); + + /** CommitResponse MultiplexedSessionRetry. */ + public MultiplexedSessionRetry?: "precommitToken"; + + /** + * Creates a new CommitResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns CommitResponse instance + */ + public static create(properties?: google.spanner.v1.ICommitResponse): google.spanner.v1.CommitResponse; + + /** + * Encodes the specified CommitResponse message. Does not implicitly {@link google.spanner.v1.CommitResponse.verify|verify} messages. + * @param message CommitResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ICommitResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CommitResponse message, length delimited. Does not implicitly {@link google.spanner.v1.CommitResponse.verify|verify} messages. + * @param message CommitResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ICommitResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CommitResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CommitResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.CommitResponse; + + /** + * Decodes a CommitResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CommitResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.CommitResponse; + + /** + * Verifies a CommitResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CommitResponse { + + /** Properties of a CommitStats. */ + interface ICommitStats { + + /** CommitStats mutationCount */ + mutationCount?: (number|Long|string|null); + } + + /** Represents a CommitStats. */ + class CommitStats implements ICommitStats { + + /** + * Constructs a new CommitStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.CommitResponse.ICommitStats); + + /** CommitStats mutationCount. */ + public mutationCount: (number|Long|string); + + /** + * Creates a new CommitStats instance using the specified properties. + * @param [properties] Properties to set + * @returns CommitStats instance + */ + public static create(properties?: google.spanner.v1.CommitResponse.ICommitStats): google.spanner.v1.CommitResponse.CommitStats; + + /** + * Encodes the specified CommitStats message. Does not implicitly {@link google.spanner.v1.CommitResponse.CommitStats.verify|verify} messages. + * @param message CommitStats message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.CommitResponse.ICommitStats, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CommitStats message, length delimited. Does not implicitly {@link google.spanner.v1.CommitResponse.CommitStats.verify|verify} messages. + * @param message CommitStats message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.CommitResponse.ICommitStats, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CommitStats message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CommitStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.CommitResponse.CommitStats; + + /** + * Decodes a CommitStats message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CommitStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.CommitResponse.CommitStats; + + /** + * Verifies a CommitStats message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CommitStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitStats + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.CommitResponse.CommitStats; + + /** + * Creates a plain object from a CommitStats message. Also converts values to other types if specified. + * @param message CommitStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.CommitResponse.CommitStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { + + /** TransactionOptions readWrite */ + readWrite?: (google.spanner.v1.TransactionOptions.IReadWrite|null); + + /** TransactionOptions partitionedDml */ + partitionedDml?: (google.spanner.v1.TransactionOptions.IPartitionedDml|null); + + /** TransactionOptions readOnly */ + readOnly?: (google.spanner.v1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions excludeTxnFromChangeStreams */ + excludeTxnFromChangeStreams?: (boolean|null); + + /** TransactionOptions isolationLevel */ + isolationLevel?: (google.spanner.v1.TransactionOptions.IsolationLevel|keyof typeof google.spanner.v1.TransactionOptions.IsolationLevel|null); + } + + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { + + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ITransactionOptions); + + /** TransactionOptions readWrite. */ + public readWrite?: (google.spanner.v1.TransactionOptions.IReadWrite|null); + + /** TransactionOptions partitionedDml. */ + public partitionedDml?: (google.spanner.v1.TransactionOptions.IPartitionedDml|null); + + /** TransactionOptions readOnly. */ + public readOnly?: (google.spanner.v1.TransactionOptions.IReadOnly|null); + + /** TransactionOptions excludeTxnFromChangeStreams. */ + public excludeTxnFromChangeStreams: boolean; + + /** TransactionOptions isolationLevel. */ + public isolationLevel: (google.spanner.v1.TransactionOptions.IsolationLevel|keyof typeof google.spanner.v1.TransactionOptions.IsolationLevel); + + /** TransactionOptions mode. */ + public mode?: ("readWrite"|"partitionedDml"|"readOnly"); + + /** + * Creates a new TransactionOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns TransactionOptions instance + */ + public static create(properties?: google.spanner.v1.ITransactionOptions): google.spanner.v1.TransactionOptions; + + /** + * Encodes the specified TransactionOptions message. Does not implicitly {@link google.spanner.v1.TransactionOptions.verify|verify} messages. + * @param message TransactionOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ITransactionOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TransactionOptions message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.verify|verify} messages. + * @param message TransactionOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ITransactionOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TransactionOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TransactionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionOptions; + + /** + * Decodes a TransactionOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TransactionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionOptions; + + /** + * Verifies a TransactionOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionOptions; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TransactionOptions { + + /** Properties of a ReadWrite. */ + interface IReadWrite { + + /** ReadWrite readLockMode */ + readLockMode?: (google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode|keyof typeof google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode|null); + + /** ReadWrite multiplexedSessionPreviousTransactionId */ + multiplexedSessionPreviousTransactionId?: (Uint8Array|Buffer|string|null); + } + + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { + + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.TransactionOptions.IReadWrite); + + /** ReadWrite readLockMode. */ + public readLockMode: (google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode|keyof typeof google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode); + + /** ReadWrite multiplexedSessionPreviousTransactionId. */ + public multiplexedSessionPreviousTransactionId: (Uint8Array|Buffer|string); + + /** + * Creates a new ReadWrite instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadWrite instance + */ + public static create(properties?: google.spanner.v1.TransactionOptions.IReadWrite): google.spanner.v1.TransactionOptions.ReadWrite; + + /** + * Encodes the specified ReadWrite message. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadWrite.verify|verify} messages. + * @param message ReadWrite message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.TransactionOptions.IReadWrite, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadWrite message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadWrite.verify|verify} messages. + * @param message ReadWrite message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.TransactionOptions.IReadWrite, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadWrite message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadWrite + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionOptions.ReadWrite; + + /** + * Decodes a ReadWrite message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadWrite + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionOptions.ReadWrite; + + /** + * Verifies a ReadWrite message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionOptions.ReadWrite; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ReadWrite { + + /** ReadLockMode enum. */ + enum ReadLockMode { + READ_LOCK_MODE_UNSPECIFIED = 0, + PESSIMISTIC = 1, + OPTIMISTIC = 2 + } + } + + /** Properties of a PartitionedDml. */ + interface IPartitionedDml { + } + + /** Represents a PartitionedDml. */ + class PartitionedDml implements IPartitionedDml { + + /** + * Constructs a new PartitionedDml. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.TransactionOptions.IPartitionedDml); + + /** + * Creates a new PartitionedDml instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionedDml instance + */ + public static create(properties?: google.spanner.v1.TransactionOptions.IPartitionedDml): google.spanner.v1.TransactionOptions.PartitionedDml; + + /** + * Encodes the specified PartitionedDml message. Does not implicitly {@link google.spanner.v1.TransactionOptions.PartitionedDml.verify|verify} messages. + * @param message PartitionedDml message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.TransactionOptions.IPartitionedDml, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionedDml message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.PartitionedDml.verify|verify} messages. + * @param message PartitionedDml message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.TransactionOptions.IPartitionedDml, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionedDml message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionedDml + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionOptions.PartitionedDml; + + /** + * Decodes a PartitionedDml message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionedDml + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionOptions.PartitionedDml; + + /** + * Verifies a PartitionedDml message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionedDml message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionedDml + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionOptions.PartitionedDml; + + /** + * Creates a plain object from a PartitionedDml message. Also converts values to other types if specified. + * @param message PartitionedDml + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.TransactionOptions.PartitionedDml, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionedDml to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionedDml + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadOnly. */ + interface IReadOnly { + + /** ReadOnly strong */ + strong?: (boolean|null); + + /** ReadOnly minReadTimestamp */ + minReadTimestamp?: (google.protobuf.ITimestamp|null); + + /** ReadOnly maxStaleness */ + maxStaleness?: (google.protobuf.IDuration|null); + + /** ReadOnly readTimestamp */ + readTimestamp?: (google.protobuf.ITimestamp|null); + + /** ReadOnly exactStaleness */ + exactStaleness?: (google.protobuf.IDuration|null); + + /** ReadOnly returnReadTimestamp */ + returnReadTimestamp?: (boolean|null); + } + + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { + + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.TransactionOptions.IReadOnly); + + /** ReadOnly strong. */ + public strong?: (boolean|null); + + /** ReadOnly minReadTimestamp. */ + public minReadTimestamp?: (google.protobuf.ITimestamp|null); + + /** ReadOnly maxStaleness. */ + public maxStaleness?: (google.protobuf.IDuration|null); + + /** ReadOnly readTimestamp. */ + public readTimestamp?: (google.protobuf.ITimestamp|null); + + /** ReadOnly exactStaleness. */ + public exactStaleness?: (google.protobuf.IDuration|null); + + /** ReadOnly returnReadTimestamp. */ + public returnReadTimestamp: boolean; + + /** ReadOnly timestampBound. */ + public timestampBound?: ("strong"|"minReadTimestamp"|"maxStaleness"|"readTimestamp"|"exactStaleness"); + + /** + * Creates a new ReadOnly instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadOnly instance + */ + public static create(properties?: google.spanner.v1.TransactionOptions.IReadOnly): google.spanner.v1.TransactionOptions.ReadOnly; + + /** + * Encodes the specified ReadOnly message. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadOnly.verify|verify} messages. + * @param message ReadOnly message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.TransactionOptions.IReadOnly, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadOnly message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadOnly.verify|verify} messages. + * @param message ReadOnly message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.TransactionOptions.IReadOnly, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadOnly message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadOnly + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionOptions.ReadOnly; + + /** + * Decodes a ReadOnly message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadOnly + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionOptions.ReadOnly; + + /** + * Verifies a ReadOnly message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionOptions.ReadOnly; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** IsolationLevel enum. */ + enum IsolationLevel { + ISOLATION_LEVEL_UNSPECIFIED = 0, + SERIALIZABLE = 1, + REPEATABLE_READ = 2 + } + } + + /** Properties of a Transaction. */ + interface ITransaction { + + /** Transaction id */ + id?: (Uint8Array|Buffer|string|null); + + /** Transaction readTimestamp */ + readTimestamp?: (google.protobuf.ITimestamp|null); + + /** Transaction precommitToken */ + precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + } + + /** Represents a Transaction. */ + class Transaction implements ITransaction { + + /** + * Constructs a new Transaction. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ITransaction); + + /** Transaction id. */ + public id: (Uint8Array|Buffer|string); + + /** Transaction readTimestamp. */ + public readTimestamp?: (google.protobuf.ITimestamp|null); + + /** Transaction precommitToken. */ + public precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** + * Creates a new Transaction instance using the specified properties. + * @param [properties] Properties to set + * @returns Transaction instance + */ + public static create(properties?: google.spanner.v1.ITransaction): google.spanner.v1.Transaction; + + /** + * Encodes the specified Transaction message. Does not implicitly {@link google.spanner.v1.Transaction.verify|verify} messages. + * @param message Transaction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ITransaction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Transaction message, length delimited. Does not implicitly {@link google.spanner.v1.Transaction.verify|verify} messages. + * @param message Transaction message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ITransaction, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Transaction message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Transaction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Transaction; + + /** + * Decodes a Transaction message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Transaction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Transaction; + + /** + * Verifies a Transaction message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Transaction message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Transaction + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Transaction; + + /** + * Creates a plain object from a Transaction message. Also converts values to other types if specified. + * @param message Transaction + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Transaction, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Transaction to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Transaction + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TransactionSelector. */ + interface ITransactionSelector { + + /** TransactionSelector singleUse */ + singleUse?: (google.spanner.v1.ITransactionOptions|null); + + /** TransactionSelector id */ + id?: (Uint8Array|Buffer|string|null); + + /** TransactionSelector begin */ + begin?: (google.spanner.v1.ITransactionOptions|null); + } + + /** Represents a TransactionSelector. */ + class TransactionSelector implements ITransactionSelector { + + /** + * Constructs a new TransactionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ITransactionSelector); + + /** TransactionSelector singleUse. */ + public singleUse?: (google.spanner.v1.ITransactionOptions|null); + + /** TransactionSelector id. */ + public id?: (Uint8Array|Buffer|string|null); + + /** TransactionSelector begin. */ + public begin?: (google.spanner.v1.ITransactionOptions|null); + + /** TransactionSelector selector. */ + public selector?: ("singleUse"|"id"|"begin"); + + /** + * Creates a new TransactionSelector instance using the specified properties. + * @param [properties] Properties to set + * @returns TransactionSelector instance + */ + public static create(properties?: google.spanner.v1.ITransactionSelector): google.spanner.v1.TransactionSelector; + + /** + * Encodes the specified TransactionSelector message. Does not implicitly {@link google.spanner.v1.TransactionSelector.verify|verify} messages. + * @param message TransactionSelector message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ITransactionSelector, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TransactionSelector message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionSelector.verify|verify} messages. + * @param message TransactionSelector message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ITransactionSelector, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TransactionSelector message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TransactionSelector + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionSelector; + + /** + * Decodes a TransactionSelector message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TransactionSelector + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionSelector; + + /** + * Verifies a TransactionSelector message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TransactionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionSelector + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionSelector; + + /** + * Creates a plain object from a TransactionSelector message. Also converts values to other types if specified. + * @param message TransactionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.TransactionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TransactionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MultiplexedSessionPrecommitToken. */ + interface IMultiplexedSessionPrecommitToken { + + /** MultiplexedSessionPrecommitToken precommitToken */ + precommitToken?: (Uint8Array|Buffer|string|null); + + /** MultiplexedSessionPrecommitToken seqNum */ + seqNum?: (number|null); + } + + /** Represents a MultiplexedSessionPrecommitToken. */ + class MultiplexedSessionPrecommitToken implements IMultiplexedSessionPrecommitToken { + + /** + * Constructs a new MultiplexedSessionPrecommitToken. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IMultiplexedSessionPrecommitToken); + + /** MultiplexedSessionPrecommitToken precommitToken. */ + public precommitToken: (Uint8Array|Buffer|string); + + /** MultiplexedSessionPrecommitToken seqNum. */ + public seqNum: number; + + /** + * Creates a new MultiplexedSessionPrecommitToken instance using the specified properties. + * @param [properties] Properties to set + * @returns MultiplexedSessionPrecommitToken instance + */ + public static create(properties?: google.spanner.v1.IMultiplexedSessionPrecommitToken): google.spanner.v1.MultiplexedSessionPrecommitToken; + + /** + * Encodes the specified MultiplexedSessionPrecommitToken message. Does not implicitly {@link google.spanner.v1.MultiplexedSessionPrecommitToken.verify|verify} messages. + * @param message MultiplexedSessionPrecommitToken message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IMultiplexedSessionPrecommitToken, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MultiplexedSessionPrecommitToken message, length delimited. Does not implicitly {@link google.spanner.v1.MultiplexedSessionPrecommitToken.verify|verify} messages. + * @param message MultiplexedSessionPrecommitToken message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IMultiplexedSessionPrecommitToken, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MultiplexedSessionPrecommitToken message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MultiplexedSessionPrecommitToken + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.MultiplexedSessionPrecommitToken; + + /** + * Decodes a MultiplexedSessionPrecommitToken message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MultiplexedSessionPrecommitToken + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.MultiplexedSessionPrecommitToken; + + /** + * Verifies a MultiplexedSessionPrecommitToken message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MultiplexedSessionPrecommitToken message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MultiplexedSessionPrecommitToken + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.MultiplexedSessionPrecommitToken; + + /** + * Creates a plain object from a MultiplexedSessionPrecommitToken message. Also converts values to other types if specified. + * @param message MultiplexedSessionPrecommitToken + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.MultiplexedSessionPrecommitToken, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MultiplexedSessionPrecommitToken to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MultiplexedSessionPrecommitToken + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a KeyRange. */ + interface IKeyRange { + + /** KeyRange startClosed */ + startClosed?: (google.protobuf.IListValue|null); + + /** KeyRange startOpen */ + startOpen?: (google.protobuf.IListValue|null); + + /** KeyRange endClosed */ + endClosed?: (google.protobuf.IListValue|null); + + /** KeyRange endOpen */ + endOpen?: (google.protobuf.IListValue|null); + } + + /** Represents a KeyRange. */ + class KeyRange implements IKeyRange { + + /** + * Constructs a new KeyRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IKeyRange); + + /** KeyRange startClosed. */ + public startClosed?: (google.protobuf.IListValue|null); + + /** KeyRange startOpen. */ + public startOpen?: (google.protobuf.IListValue|null); + + /** KeyRange endClosed. */ + public endClosed?: (google.protobuf.IListValue|null); + + /** KeyRange endOpen. */ + public endOpen?: (google.protobuf.IListValue|null); + + /** KeyRange startKeyType. */ + public startKeyType?: ("startClosed"|"startOpen"); + + /** KeyRange endKeyType. */ + public endKeyType?: ("endClosed"|"endOpen"); + + /** + * Creates a new KeyRange instance using the specified properties. + * @param [properties] Properties to set + * @returns KeyRange instance + */ + public static create(properties?: google.spanner.v1.IKeyRange): google.spanner.v1.KeyRange; + + /** + * Encodes the specified KeyRange message. Does not implicitly {@link google.spanner.v1.KeyRange.verify|verify} messages. + * @param message KeyRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IKeyRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified KeyRange message, length delimited. Does not implicitly {@link google.spanner.v1.KeyRange.verify|verify} messages. + * @param message KeyRange message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IKeyRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a KeyRange message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns KeyRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.KeyRange; + + /** + * Decodes a KeyRange message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns KeyRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.KeyRange; + + /** + * Verifies a KeyRange message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a KeyRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns KeyRange + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.KeyRange; + + /** + * Creates a plain object from a KeyRange message. Also converts values to other types if specified. + * @param message KeyRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.KeyRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this KeyRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for KeyRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a KeySet. */ + interface IKeySet { + + /** KeySet keys */ + keys?: (google.protobuf.IListValue[]|null); + + /** KeySet ranges */ + ranges?: (google.spanner.v1.IKeyRange[]|null); + + /** KeySet all */ + all?: (boolean|null); + } + + /** Represents a KeySet. */ + class KeySet implements IKeySet { + + /** + * Constructs a new KeySet. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IKeySet); + + /** KeySet keys. */ + public keys: google.protobuf.IListValue[]; + + /** KeySet ranges. */ + public ranges: google.spanner.v1.IKeyRange[]; + + /** KeySet all. */ + public all: boolean; + + /** + * Creates a new KeySet instance using the specified properties. + * @param [properties] Properties to set + * @returns KeySet instance + */ + public static create(properties?: google.spanner.v1.IKeySet): google.spanner.v1.KeySet; + + /** + * Encodes the specified KeySet message. Does not implicitly {@link google.spanner.v1.KeySet.verify|verify} messages. + * @param message KeySet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IKeySet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified KeySet message, length delimited. Does not implicitly {@link google.spanner.v1.KeySet.verify|verify} messages. + * @param message KeySet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IKeySet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a KeySet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns KeySet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.KeySet; + + /** + * Decodes a KeySet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns KeySet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.KeySet; + + /** + * Verifies a KeySet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a KeySet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns KeySet + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.KeySet; + + /** + * Creates a plain object from a KeySet message. Also converts values to other types if specified. + * @param message KeySet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.KeySet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this KeySet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for KeySet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Range. */ + interface IRange { + + /** Range startKey */ + startKey?: (Uint8Array|Buffer|string|null); + + /** Range limitKey */ + limitKey?: (Uint8Array|Buffer|string|null); + + /** Range groupUid */ + groupUid?: (number|Long|string|null); + + /** Range splitId */ + splitId?: (number|Long|string|null); + + /** Range generation */ + generation?: (Uint8Array|Buffer|string|null); + } + + /** Represents a Range. */ + class Range implements IRange { + + /** + * Constructs a new Range. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IRange); + + /** Range startKey. */ + public startKey: (Uint8Array|Buffer|string); + + /** Range limitKey. */ + public limitKey: (Uint8Array|Buffer|string); + + /** Range groupUid. */ + public groupUid: (number|Long|string); + + /** Range splitId. */ + public splitId: (number|Long|string); + + /** Range generation. */ + public generation: (Uint8Array|Buffer|string); + + /** + * Creates a new Range instance using the specified properties. + * @param [properties] Properties to set + * @returns Range instance + */ + public static create(properties?: google.spanner.v1.IRange): google.spanner.v1.Range; + + /** + * Encodes the specified Range message. Does not implicitly {@link google.spanner.v1.Range.verify|verify} messages. + * @param message Range message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Range message, length delimited. Does not implicitly {@link google.spanner.v1.Range.verify|verify} messages. + * @param message Range message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IRange, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Range message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Range + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Range; + + /** + * Decodes a Range message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Range + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Range; + + /** + * Verifies a Range message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Range message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Range + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Range; + + /** + * Creates a plain object from a Range message. Also converts values to other types if specified. + * @param message Range + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Range, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Range to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Range + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Tablet. */ + interface ITablet { + + /** Tablet tabletUid */ + tabletUid?: (number|Long|string|null); + + /** Tablet serverAddress */ + serverAddress?: (string|null); + + /** Tablet location */ + location?: (string|null); + + /** Tablet role */ + role?: (google.spanner.v1.Tablet.Role|keyof typeof google.spanner.v1.Tablet.Role|null); + + /** Tablet incarnation */ + incarnation?: (Uint8Array|Buffer|string|null); + + /** Tablet distance */ + distance?: (number|null); + + /** Tablet skip */ + skip?: (boolean|null); + } + + /** Represents a Tablet. */ + class Tablet implements ITablet { + + /** + * Constructs a new Tablet. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ITablet); + + /** Tablet tabletUid. */ + public tabletUid: (number|Long|string); + + /** Tablet serverAddress. */ + public serverAddress: string; + + /** Tablet location. */ + public location: string; + + /** Tablet role. */ + public role: (google.spanner.v1.Tablet.Role|keyof typeof google.spanner.v1.Tablet.Role); + + /** Tablet incarnation. */ + public incarnation: (Uint8Array|Buffer|string); + + /** Tablet distance. */ + public distance: number; + + /** Tablet skip. */ + public skip: boolean; + + /** + * Creates a new Tablet instance using the specified properties. + * @param [properties] Properties to set + * @returns Tablet instance + */ + public static create(properties?: google.spanner.v1.ITablet): google.spanner.v1.Tablet; + + /** + * Encodes the specified Tablet message. Does not implicitly {@link google.spanner.v1.Tablet.verify|verify} messages. + * @param message Tablet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ITablet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Tablet message, length delimited. Does not implicitly {@link google.spanner.v1.Tablet.verify|verify} messages. + * @param message Tablet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ITablet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Tablet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Tablet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Tablet; + + /** + * Decodes a Tablet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Tablet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Tablet; + + /** + * Verifies a Tablet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Tablet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Tablet + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Tablet; + + /** + * Creates a plain object from a Tablet message. Also converts values to other types if specified. + * @param message Tablet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Tablet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Tablet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Tablet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Tablet { + + /** Role enum. */ + enum Role { + ROLE_UNSPECIFIED = 0, + READ_WRITE = 1, + READ_ONLY = 2 + } + } + + /** Properties of a Group. */ + interface IGroup { + + /** Group groupUid */ + groupUid?: (number|Long|string|null); + + /** Group tablets */ + tablets?: (google.spanner.v1.ITablet[]|null); + + /** Group leaderIndex */ + leaderIndex?: (number|null); + + /** Group generation */ + generation?: (Uint8Array|Buffer|string|null); + } + + /** Represents a Group. */ + class Group implements IGroup { + + /** + * Constructs a new Group. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IGroup); + + /** Group groupUid. */ + public groupUid: (number|Long|string); + + /** Group tablets. */ + public tablets: google.spanner.v1.ITablet[]; + + /** Group leaderIndex. */ + public leaderIndex: number; + + /** Group generation. */ + public generation: (Uint8Array|Buffer|string); + + /** + * Creates a new Group instance using the specified properties. + * @param [properties] Properties to set + * @returns Group instance + */ + public static create(properties?: google.spanner.v1.IGroup): google.spanner.v1.Group; + + /** + * Encodes the specified Group message. Does not implicitly {@link google.spanner.v1.Group.verify|verify} messages. + * @param message Group message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IGroup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Group message, length delimited. Does not implicitly {@link google.spanner.v1.Group.verify|verify} messages. + * @param message Group message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IGroup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Group message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Group + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Group; + + /** + * Decodes a Group message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Group + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Group; + + /** + * Verifies a Group message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Group message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Group + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Group; + + /** + * Creates a plain object from a Group message. Also converts values to other types if specified. + * @param message Group + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Group, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Group to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Group + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a KeyRecipe. */ + interface IKeyRecipe { + + /** KeyRecipe tableName */ + tableName?: (string|null); + + /** KeyRecipe indexName */ + indexName?: (string|null); + + /** KeyRecipe operationUid */ + operationUid?: (number|Long|string|null); + + /** KeyRecipe part */ + part?: (google.spanner.v1.KeyRecipe.IPart[]|null); + } + + /** Represents a KeyRecipe. */ + class KeyRecipe implements IKeyRecipe { + + /** + * Constructs a new KeyRecipe. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IKeyRecipe); + + /** KeyRecipe tableName. */ + public tableName?: (string|null); + + /** KeyRecipe indexName. */ + public indexName?: (string|null); + + /** KeyRecipe operationUid. */ + public operationUid?: (number|Long|string|null); + + /** KeyRecipe part. */ + public part: google.spanner.v1.KeyRecipe.IPart[]; + + /** KeyRecipe target. */ + public target?: ("tableName"|"indexName"|"operationUid"); + + /** + * Creates a new KeyRecipe instance using the specified properties. + * @param [properties] Properties to set + * @returns KeyRecipe instance + */ + public static create(properties?: google.spanner.v1.IKeyRecipe): google.spanner.v1.KeyRecipe; + + /** + * Encodes the specified KeyRecipe message. Does not implicitly {@link google.spanner.v1.KeyRecipe.verify|verify} messages. + * @param message KeyRecipe message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IKeyRecipe, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified KeyRecipe message, length delimited. Does not implicitly {@link google.spanner.v1.KeyRecipe.verify|verify} messages. + * @param message KeyRecipe message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IKeyRecipe, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a KeyRecipe message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns KeyRecipe + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.KeyRecipe; + + /** + * Decodes a KeyRecipe message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns KeyRecipe + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.KeyRecipe; + + /** + * Verifies a KeyRecipe message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a KeyRecipe message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns KeyRecipe + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.KeyRecipe; + + /** + * Creates a plain object from a KeyRecipe message. Also converts values to other types if specified. + * @param message KeyRecipe + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.KeyRecipe, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this KeyRecipe to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for KeyRecipe + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace KeyRecipe { + + /** Properties of a Part. */ + interface IPart { + + /** Part tag */ + tag?: (number|null); + + /** Part order */ + order?: (google.spanner.v1.KeyRecipe.Part.Order|keyof typeof google.spanner.v1.KeyRecipe.Part.Order|null); + + /** Part nullOrder */ + nullOrder?: (google.spanner.v1.KeyRecipe.Part.NullOrder|keyof typeof google.spanner.v1.KeyRecipe.Part.NullOrder|null); + + /** Part type */ + type?: (google.spanner.v1.IType|null); + + /** Part identifier */ + identifier?: (string|null); + + /** Part value */ + value?: (google.protobuf.IValue|null); + + /** Part random */ + random?: (boolean|null); + + /** Part structIdentifiers */ + structIdentifiers?: (number[]|null); + } + + /** Represents a Part. */ + class Part implements IPart { + + /** + * Constructs a new Part. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.KeyRecipe.IPart); + + /** Part tag. */ + public tag: number; + + /** Part order. */ + public order: (google.spanner.v1.KeyRecipe.Part.Order|keyof typeof google.spanner.v1.KeyRecipe.Part.Order); + + /** Part nullOrder. */ + public nullOrder: (google.spanner.v1.KeyRecipe.Part.NullOrder|keyof typeof google.spanner.v1.KeyRecipe.Part.NullOrder); + + /** Part type. */ + public type?: (google.spanner.v1.IType|null); + + /** Part identifier. */ + public identifier?: (string|null); + + /** Part value. */ + public value?: (google.protobuf.IValue|null); + + /** Part random. */ + public random?: (boolean|null); + + /** Part structIdentifiers. */ + public structIdentifiers: number[]; + + /** Part valueType. */ + public valueType?: ("identifier"|"value"|"random"); + + /** + * Creates a new Part instance using the specified properties. + * @param [properties] Properties to set + * @returns Part instance + */ + public static create(properties?: google.spanner.v1.KeyRecipe.IPart): google.spanner.v1.KeyRecipe.Part; + + /** + * Encodes the specified Part message. Does not implicitly {@link google.spanner.v1.KeyRecipe.Part.verify|verify} messages. + * @param message Part message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.KeyRecipe.IPart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Part message, length delimited. Does not implicitly {@link google.spanner.v1.KeyRecipe.Part.verify|verify} messages. + * @param message Part message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.KeyRecipe.IPart, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Part message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Part + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.KeyRecipe.Part; + + /** + * Decodes a Part message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Part + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.KeyRecipe.Part; + + /** + * Verifies a Part message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Part message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Part + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.KeyRecipe.Part; + + /** + * Creates a plain object from a Part message. Also converts values to other types if specified. + * @param message Part + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.KeyRecipe.Part, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Part to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Part + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Part { + + /** Order enum. */ + enum Order { + ORDER_UNSPECIFIED = 0, + ASCENDING = 1, + DESCENDING = 2 + } + + /** NullOrder enum. */ + enum NullOrder { + NULL_ORDER_UNSPECIFIED = 0, + NULLS_FIRST = 1, + NULLS_LAST = 2, + NOT_NULL = 3 + } + } + } + + /** Properties of a RecipeList. */ + interface IRecipeList { + + /** RecipeList schemaGeneration */ + schemaGeneration?: (Uint8Array|Buffer|string|null); + + /** RecipeList recipe */ + recipe?: (google.spanner.v1.IKeyRecipe[]|null); + } + + /** Represents a RecipeList. */ + class RecipeList implements IRecipeList { + + /** + * Constructs a new RecipeList. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IRecipeList); + + /** RecipeList schemaGeneration. */ + public schemaGeneration: (Uint8Array|Buffer|string); + + /** RecipeList recipe. */ + public recipe: google.spanner.v1.IKeyRecipe[]; + + /** + * Creates a new RecipeList instance using the specified properties. + * @param [properties] Properties to set + * @returns RecipeList instance + */ + public static create(properties?: google.spanner.v1.IRecipeList): google.spanner.v1.RecipeList; + + /** + * Encodes the specified RecipeList message. Does not implicitly {@link google.spanner.v1.RecipeList.verify|verify} messages. + * @param message RecipeList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IRecipeList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RecipeList message, length delimited. Does not implicitly {@link google.spanner.v1.RecipeList.verify|verify} messages. + * @param message RecipeList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IRecipeList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RecipeList message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RecipeList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.RecipeList; + + /** + * Decodes a RecipeList message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RecipeList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.RecipeList; + + /** + * Verifies a RecipeList message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RecipeList message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RecipeList + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.RecipeList; + + /** + * Creates a plain object from a RecipeList message. Also converts values to other types if specified. + * @param message RecipeList + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.RecipeList, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RecipeList to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RecipeList + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CacheUpdate. */ + interface ICacheUpdate { + + /** CacheUpdate databaseId */ + databaseId?: (number|Long|string|null); + + /** CacheUpdate range */ + range?: (google.spanner.v1.IRange[]|null); + + /** CacheUpdate group */ + group?: (google.spanner.v1.IGroup[]|null); + + /** CacheUpdate keyRecipes */ + keyRecipes?: (google.spanner.v1.IRecipeList|null); + } + + /** Represents a CacheUpdate. */ + class CacheUpdate implements ICacheUpdate { + + /** + * Constructs a new CacheUpdate. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ICacheUpdate); + + /** CacheUpdate databaseId. */ + public databaseId: (number|Long|string); + + /** CacheUpdate range. */ + public range: google.spanner.v1.IRange[]; + + /** CacheUpdate group. */ + public group: google.spanner.v1.IGroup[]; + + /** CacheUpdate keyRecipes. */ + public keyRecipes?: (google.spanner.v1.IRecipeList|null); + + /** + * Creates a new CacheUpdate instance using the specified properties. + * @param [properties] Properties to set + * @returns CacheUpdate instance + */ + public static create(properties?: google.spanner.v1.ICacheUpdate): google.spanner.v1.CacheUpdate; + + /** + * Encodes the specified CacheUpdate message. Does not implicitly {@link google.spanner.v1.CacheUpdate.verify|verify} messages. + * @param message CacheUpdate message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ICacheUpdate, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CacheUpdate message, length delimited. Does not implicitly {@link google.spanner.v1.CacheUpdate.verify|verify} messages. + * @param message CacheUpdate message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ICacheUpdate, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CacheUpdate message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CacheUpdate + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.CacheUpdate; + + /** + * Decodes a CacheUpdate message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CacheUpdate + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.CacheUpdate; + + /** + * Verifies a CacheUpdate message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CacheUpdate message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CacheUpdate + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.CacheUpdate; + + /** + * Creates a plain object from a CacheUpdate message. Also converts values to other types if specified. + * @param message CacheUpdate + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.CacheUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CacheUpdate to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CacheUpdate + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingHint. */ + interface IRoutingHint { + + /** RoutingHint operationUid */ + operationUid?: (number|Long|string|null); + + /** RoutingHint databaseId */ + databaseId?: (number|Long|string|null); + + /** RoutingHint schemaGeneration */ + schemaGeneration?: (Uint8Array|Buffer|string|null); + + /** RoutingHint key */ + key?: (Uint8Array|Buffer|string|null); + + /** RoutingHint limitKey */ + limitKey?: (Uint8Array|Buffer|string|null); + + /** RoutingHint groupUid */ + groupUid?: (number|Long|string|null); + + /** RoutingHint splitId */ + splitId?: (number|Long|string|null); + + /** RoutingHint tabletUid */ + tabletUid?: (number|Long|string|null); + + /** RoutingHint skippedTabletUid */ + skippedTabletUid?: (google.spanner.v1.RoutingHint.ISkippedTablet[]|null); + + /** RoutingHint clientLocation */ + clientLocation?: (string|null); + } + + /** Represents a RoutingHint. */ + class RoutingHint implements IRoutingHint { + + /** + * Constructs a new RoutingHint. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IRoutingHint); + + /** RoutingHint operationUid. */ + public operationUid: (number|Long|string); + + /** RoutingHint databaseId. */ + public databaseId: (number|Long|string); + + /** RoutingHint schemaGeneration. */ + public schemaGeneration: (Uint8Array|Buffer|string); + + /** RoutingHint key. */ + public key: (Uint8Array|Buffer|string); + + /** RoutingHint limitKey. */ + public limitKey: (Uint8Array|Buffer|string); + + /** RoutingHint groupUid. */ + public groupUid: (number|Long|string); + + /** RoutingHint splitId. */ + public splitId: (number|Long|string); + + /** RoutingHint tabletUid. */ + public tabletUid: (number|Long|string); + + /** RoutingHint skippedTabletUid. */ + public skippedTabletUid: google.spanner.v1.RoutingHint.ISkippedTablet[]; + + /** RoutingHint clientLocation. */ + public clientLocation: string; + + /** + * Creates a new RoutingHint instance using the specified properties. + * @param [properties] Properties to set + * @returns RoutingHint instance + */ + public static create(properties?: google.spanner.v1.IRoutingHint): google.spanner.v1.RoutingHint; + + /** + * Encodes the specified RoutingHint message. Does not implicitly {@link google.spanner.v1.RoutingHint.verify|verify} messages. + * @param message RoutingHint message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IRoutingHint, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RoutingHint message, length delimited. Does not implicitly {@link google.spanner.v1.RoutingHint.verify|verify} messages. + * @param message RoutingHint message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IRoutingHint, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RoutingHint message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RoutingHint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.RoutingHint; + + /** + * Decodes a RoutingHint message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RoutingHint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.RoutingHint; + + /** + * Verifies a RoutingHint message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RoutingHint message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingHint + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.RoutingHint; + + /** + * Creates a plain object from a RoutingHint message. Also converts values to other types if specified. + * @param message RoutingHint + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.RoutingHint, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingHint to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingHint + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace RoutingHint { + + /** Properties of a SkippedTablet. */ + interface ISkippedTablet { + + /** SkippedTablet tabletUid */ + tabletUid?: (number|Long|string|null); + + /** SkippedTablet incarnation */ + incarnation?: (Uint8Array|Buffer|string|null); + } + + /** Represents a SkippedTablet. */ + class SkippedTablet implements ISkippedTablet { + + /** + * Constructs a new SkippedTablet. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.RoutingHint.ISkippedTablet); + + /** SkippedTablet tabletUid. */ + public tabletUid: (number|Long|string); + + /** SkippedTablet incarnation. */ + public incarnation: (Uint8Array|Buffer|string); + + /** + * Creates a new SkippedTablet instance using the specified properties. + * @param [properties] Properties to set + * @returns SkippedTablet instance + */ + public static create(properties?: google.spanner.v1.RoutingHint.ISkippedTablet): google.spanner.v1.RoutingHint.SkippedTablet; + + /** + * Encodes the specified SkippedTablet message. Does not implicitly {@link google.spanner.v1.RoutingHint.SkippedTablet.verify|verify} messages. + * @param message SkippedTablet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.RoutingHint.ISkippedTablet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SkippedTablet message, length delimited. Does not implicitly {@link google.spanner.v1.RoutingHint.SkippedTablet.verify|verify} messages. + * @param message SkippedTablet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.RoutingHint.ISkippedTablet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SkippedTablet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SkippedTablet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.RoutingHint.SkippedTablet; + + /** + * Decodes a SkippedTablet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SkippedTablet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.RoutingHint.SkippedTablet; + + /** + * Verifies a SkippedTablet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SkippedTablet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SkippedTablet + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.RoutingHint.SkippedTablet; + + /** + * Creates a plain object from a SkippedTablet message. Also converts values to other types if specified. + * @param message SkippedTablet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.RoutingHint.SkippedTablet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SkippedTablet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SkippedTablet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a Type. */ + interface IType { + + /** Type code */ + code?: (google.spanner.v1.TypeCode|keyof typeof google.spanner.v1.TypeCode|null); + + /** Type arrayElementType */ + arrayElementType?: (google.spanner.v1.IType|null); + + /** Type structType */ + structType?: (google.spanner.v1.IStructType|null); + + /** Type typeAnnotation */ + typeAnnotation?: (google.spanner.v1.TypeAnnotationCode|keyof typeof google.spanner.v1.TypeAnnotationCode|null); + + /** Type protoTypeFqn */ + protoTypeFqn?: (string|null); + } + + /** Represents a Type. */ + class Type implements IType { + + /** + * Constructs a new Type. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IType); + + /** Type code. */ + public code: (google.spanner.v1.TypeCode|keyof typeof google.spanner.v1.TypeCode); + + /** Type arrayElementType. */ + public arrayElementType?: (google.spanner.v1.IType|null); + + /** Type structType. */ + public structType?: (google.spanner.v1.IStructType|null); + + /** Type typeAnnotation. */ + public typeAnnotation: (google.spanner.v1.TypeAnnotationCode|keyof typeof google.spanner.v1.TypeAnnotationCode); + + /** Type protoTypeFqn. */ + public protoTypeFqn: string; + + /** + * Creates a new Type instance using the specified properties. + * @param [properties] Properties to set + * @returns Type instance + */ + public static create(properties?: google.spanner.v1.IType): google.spanner.v1.Type; + + /** + * Encodes the specified Type message. Does not implicitly {@link google.spanner.v1.Type.verify|verify} messages. + * @param message Type message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IType, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Type message, length delimited. Does not implicitly {@link google.spanner.v1.Type.verify|verify} messages. + * @param message Type message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IType, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Type message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Type + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Type; + + /** + * Decodes a Type message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Type + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Type; + + /** + * Verifies a Type message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Type message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Type + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Type; + + /** + * Creates a plain object from a Type message. Also converts values to other types if specified. + * @param message Type + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Type, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Type to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Type + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StructType. */ + interface IStructType { + + /** StructType fields */ + fields?: (google.spanner.v1.StructType.IField[]|null); + } + + /** Represents a StructType. */ + class StructType implements IStructType { + + /** + * Constructs a new StructType. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IStructType); + + /** StructType fields. */ + public fields: google.spanner.v1.StructType.IField[]; + + /** + * Creates a new StructType instance using the specified properties. + * @param [properties] Properties to set + * @returns StructType instance + */ + public static create(properties?: google.spanner.v1.IStructType): google.spanner.v1.StructType; + + /** + * Encodes the specified StructType message. Does not implicitly {@link google.spanner.v1.StructType.verify|verify} messages. + * @param message StructType message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IStructType, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified StructType message, length delimited. Does not implicitly {@link google.spanner.v1.StructType.verify|verify} messages. + * @param message StructType message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IStructType, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a StructType message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns StructType + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.StructType; + + /** + * Decodes a StructType message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns StructType + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.StructType; + + /** + * Verifies a StructType message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a StructType message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructType + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.StructType; + + /** + * Creates a plain object from a StructType message. Also converts values to other types if specified. + * @param message StructType + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.StructType, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructType to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructType + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructType { + + /** Properties of a Field. */ + interface IField { + + /** Field name */ + name?: (string|null); + + /** Field type */ + type?: (google.spanner.v1.IType|null); + } + + /** Represents a Field. */ + class Field implements IField { + + /** + * Constructs a new Field. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.StructType.IField); + + /** Field name. */ + public name: string; + + /** Field type. */ + public type?: (google.spanner.v1.IType|null); + + /** + * Creates a new Field instance using the specified properties. + * @param [properties] Properties to set + * @returns Field instance + */ + public static create(properties?: google.spanner.v1.StructType.IField): google.spanner.v1.StructType.Field; + + /** + * Encodes the specified Field message. Does not implicitly {@link google.spanner.v1.StructType.Field.verify|verify} messages. + * @param message Field message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.StructType.IField, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Field message, length delimited. Does not implicitly {@link google.spanner.v1.StructType.Field.verify|verify} messages. + * @param message Field message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.StructType.IField, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Field message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Field + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.StructType.Field; + + /** + * Decodes a Field message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Field + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.StructType.Field; + + /** + * Verifies a Field message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Field message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Field + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.StructType.Field; + + /** + * Creates a plain object from a Field message. Also converts values to other types if specified. + * @param message Field + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.StructType.Field, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Field to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Field + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** TypeCode enum. */ + enum TypeCode { + TYPE_CODE_UNSPECIFIED = 0, + BOOL = 1, + INT64 = 2, + FLOAT64 = 3, + FLOAT32 = 15, + TIMESTAMP = 4, + DATE = 5, + STRING = 6, + BYTES = 7, + ARRAY = 8, + STRUCT = 9, + NUMERIC = 10, + JSON = 11, + PROTO = 13, + ENUM = 14, + INTERVAL = 16, + UUID = 17 + } + + /** TypeAnnotationCode enum. */ + enum TypeAnnotationCode { + TYPE_ANNOTATION_CODE_UNSPECIFIED = 0, + PG_NUMERIC = 2, + PG_JSONB = 3, + PG_OID = 4 + } + + /** Properties of a Mutation. */ + interface IMutation { + + /** Mutation insert */ + insert?: (google.spanner.v1.Mutation.IWrite|null); + + /** Mutation update */ + update?: (google.spanner.v1.Mutation.IWrite|null); + + /** Mutation insertOrUpdate */ + insertOrUpdate?: (google.spanner.v1.Mutation.IWrite|null); + + /** Mutation replace */ + replace?: (google.spanner.v1.Mutation.IWrite|null); + + /** Mutation delete */ + "delete"?: (google.spanner.v1.Mutation.IDelete|null); + + /** Mutation send */ + send?: (google.spanner.v1.Mutation.ISend|null); + + /** Mutation ack */ + ack?: (google.spanner.v1.Mutation.IAck|null); + } + + /** Represents a Mutation. */ + class Mutation implements IMutation { + + /** + * Constructs a new Mutation. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IMutation); + + /** Mutation insert. */ + public insert?: (google.spanner.v1.Mutation.IWrite|null); + + /** Mutation update. */ + public update?: (google.spanner.v1.Mutation.IWrite|null); + + /** Mutation insertOrUpdate. */ + public insertOrUpdate?: (google.spanner.v1.Mutation.IWrite|null); + + /** Mutation replace. */ + public replace?: (google.spanner.v1.Mutation.IWrite|null); + + /** Mutation delete. */ + public delete?: (google.spanner.v1.Mutation.IDelete|null); + + /** Mutation send. */ + public send?: (google.spanner.v1.Mutation.ISend|null); + + /** Mutation ack. */ + public ack?: (google.spanner.v1.Mutation.IAck|null); + + /** Mutation operation. */ + public operation?: ("insert"|"update"|"insertOrUpdate"|"replace"|"delete"|"send"|"ack"); + + /** + * Creates a new Mutation instance using the specified properties. + * @param [properties] Properties to set + * @returns Mutation instance + */ + public static create(properties?: google.spanner.v1.IMutation): google.spanner.v1.Mutation; + + /** + * Encodes the specified Mutation message. Does not implicitly {@link google.spanner.v1.Mutation.verify|verify} messages. + * @param message Mutation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IMutation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Mutation message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.verify|verify} messages. + * @param message Mutation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IMutation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Mutation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Mutation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Mutation; + + /** + * Decodes a Mutation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Mutation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Mutation; + + /** + * Verifies a Mutation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Mutation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Mutation + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Mutation; + + /** + * Creates a plain object from a Mutation message. Also converts values to other types if specified. + * @param message Mutation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Mutation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Mutation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Mutation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Mutation { + + /** Properties of a Write. */ + interface IWrite { + + /** Write table */ + table?: (string|null); + + /** Write columns */ + columns?: (string[]|null); + + /** Write values */ + values?: (google.protobuf.IListValue[]|null); + } + + /** Represents a Write. */ + class Write implements IWrite { + + /** + * Constructs a new Write. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.Mutation.IWrite); + + /** Write table. */ + public table: string; + + /** Write columns. */ + public columns: string[]; + + /** Write values. */ + public values: google.protobuf.IListValue[]; + + /** + * Creates a new Write instance using the specified properties. + * @param [properties] Properties to set + * @returns Write instance + */ + public static create(properties?: google.spanner.v1.Mutation.IWrite): google.spanner.v1.Mutation.Write; + + /** + * Encodes the specified Write message. Does not implicitly {@link google.spanner.v1.Mutation.Write.verify|verify} messages. + * @param message Write message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.Mutation.IWrite, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Write message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Write.verify|verify} messages. + * @param message Write message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.Mutation.IWrite, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Write message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Write + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Mutation.Write; + + /** + * Decodes a Write message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Write + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Mutation.Write; + + /** + * Verifies a Write message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Write + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Mutation.Write; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Mutation.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Write to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Delete. */ + interface IDelete { + + /** Delete table */ + table?: (string|null); + + /** Delete keySet */ + keySet?: (google.spanner.v1.IKeySet|null); + } + + /** Represents a Delete. */ + class Delete implements IDelete { + + /** + * Constructs a new Delete. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.Mutation.IDelete); + + /** Delete table. */ + public table: string; + + /** Delete keySet. */ + public keySet?: (google.spanner.v1.IKeySet|null); + + /** + * Creates a new Delete instance using the specified properties. + * @param [properties] Properties to set + * @returns Delete instance + */ + public static create(properties?: google.spanner.v1.Mutation.IDelete): google.spanner.v1.Mutation.Delete; + + /** + * Encodes the specified Delete message. Does not implicitly {@link google.spanner.v1.Mutation.Delete.verify|verify} messages. + * @param message Delete message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.Mutation.IDelete, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Delete message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Delete.verify|verify} messages. + * @param message Delete message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.Mutation.IDelete, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Delete message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Delete + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Mutation.Delete; + + /** + * Decodes a Delete message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Delete + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Mutation.Delete; + + /** + * Verifies a Delete message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Delete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Delete + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Mutation.Delete; + + /** + * Creates a plain object from a Delete message. Also converts values to other types if specified. + * @param message Delete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Mutation.Delete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Delete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Delete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Send. */ + interface ISend { + + /** Send queue */ + queue?: (string|null); + + /** Send key */ + key?: (google.protobuf.IListValue|null); + + /** Send deliverTime */ + deliverTime?: (google.protobuf.ITimestamp|null); + + /** Send payload */ + payload?: (google.protobuf.IValue|null); + } + + /** Represents a Send. */ + class Send implements ISend { + + /** + * Constructs a new Send. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.Mutation.ISend); + + /** Send queue. */ + public queue: string; + + /** Send key. */ + public key?: (google.protobuf.IListValue|null); + + /** Send deliverTime. */ + public deliverTime?: (google.protobuf.ITimestamp|null); + + /** Send payload. */ + public payload?: (google.protobuf.IValue|null); + + /** + * Creates a new Send instance using the specified properties. + * @param [properties] Properties to set + * @returns Send instance + */ + public static create(properties?: google.spanner.v1.Mutation.ISend): google.spanner.v1.Mutation.Send; + + /** + * Encodes the specified Send message. Does not implicitly {@link google.spanner.v1.Mutation.Send.verify|verify} messages. + * @param message Send message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.Mutation.ISend, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Send message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Send.verify|verify} messages. + * @param message Send message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.Mutation.ISend, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Send message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Send + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Mutation.Send; + + /** + * Decodes a Send message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Send + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Mutation.Send; + + /** + * Verifies a Send message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Send message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Send + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Mutation.Send; + + /** + * Creates a plain object from a Send message. Also converts values to other types if specified. + * @param message Send + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Mutation.Send, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Send to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Send + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Ack. */ + interface IAck { + + /** Ack queue */ + queue?: (string|null); + + /** Ack key */ + key?: (google.protobuf.IListValue|null); + + /** Ack ignoreNotFound */ + ignoreNotFound?: (boolean|null); + } + + /** Represents an Ack. */ + class Ack implements IAck { + + /** + * Constructs a new Ack. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.Mutation.IAck); + + /** Ack queue. */ + public queue: string; + + /** Ack key. */ + public key?: (google.protobuf.IListValue|null); + + /** Ack ignoreNotFound. */ + public ignoreNotFound: boolean; + + /** + * Creates a new Ack instance using the specified properties. + * @param [properties] Properties to set + * @returns Ack instance + */ + public static create(properties?: google.spanner.v1.Mutation.IAck): google.spanner.v1.Mutation.Ack; + + /** + * Encodes the specified Ack message. Does not implicitly {@link google.spanner.v1.Mutation.Ack.verify|verify} messages. + * @param message Ack message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.Mutation.IAck, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Ack message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Ack.verify|verify} messages. + * @param message Ack message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.Mutation.IAck, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Ack message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Ack + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Mutation.Ack; + + /** + * Decodes an Ack message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Ack + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Mutation.Ack; + + /** + * Verifies an Ack message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Ack message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Ack + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.Mutation.Ack; + + /** + * Creates a plain object from an Ack message. Also converts values to other types if specified. + * @param message Ack + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.Mutation.Ack, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Ack to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Ack + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a ResultSet. */ + interface IResultSet { + + /** ResultSet metadata */ + metadata?: (google.spanner.v1.IResultSetMetadata|null); + + /** ResultSet rows */ + rows?: (google.protobuf.IListValue[]|null); + + /** ResultSet stats */ + stats?: (google.spanner.v1.IResultSetStats|null); + + /** ResultSet precommitToken */ + precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** ResultSet cacheUpdate */ + cacheUpdate?: (google.spanner.v1.ICacheUpdate|null); + } + + /** Represents a ResultSet. */ + class ResultSet implements IResultSet { + + /** + * Constructs a new ResultSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IResultSet); + + /** ResultSet metadata. */ + public metadata?: (google.spanner.v1.IResultSetMetadata|null); + + /** ResultSet rows. */ + public rows: google.protobuf.IListValue[]; + + /** ResultSet stats. */ + public stats?: (google.spanner.v1.IResultSetStats|null); + + /** ResultSet precommitToken. */ + public precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** ResultSet cacheUpdate. */ + public cacheUpdate?: (google.spanner.v1.ICacheUpdate|null); + + /** + * Creates a new ResultSet instance using the specified properties. + * @param [properties] Properties to set + * @returns ResultSet instance + */ + public static create(properties?: google.spanner.v1.IResultSet): google.spanner.v1.ResultSet; + + /** + * Encodes the specified ResultSet message. Does not implicitly {@link google.spanner.v1.ResultSet.verify|verify} messages. + * @param message ResultSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IResultSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResultSet message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSet.verify|verify} messages. + * @param message ResultSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IResultSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResultSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResultSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ResultSet; + + /** + * Decodes a ResultSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResultSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ResultSet; + + /** + * Verifies a ResultSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResultSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResultSet + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ResultSet; + + /** + * Creates a plain object from a ResultSet message. Also converts values to other types if specified. + * @param message ResultSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ResultSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResultSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResultSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartialResultSet. */ + interface IPartialResultSet { + + /** PartialResultSet metadata */ + metadata?: (google.spanner.v1.IResultSetMetadata|null); + + /** PartialResultSet values */ + values?: (google.protobuf.IValue[]|null); + + /** PartialResultSet chunkedValue */ + chunkedValue?: (boolean|null); + + /** PartialResultSet resumeToken */ + resumeToken?: (Uint8Array|Buffer|string|null); + + /** PartialResultSet stats */ + stats?: (google.spanner.v1.IResultSetStats|null); + + /** PartialResultSet precommitToken */ + precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** PartialResultSet last */ + last?: (boolean|null); + + /** PartialResultSet cacheUpdate */ + cacheUpdate?: (google.spanner.v1.ICacheUpdate|null); + } + + /** Represents a PartialResultSet. */ + class PartialResultSet implements IPartialResultSet { + + /** + * Constructs a new PartialResultSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IPartialResultSet); + + /** PartialResultSet metadata. */ + public metadata?: (google.spanner.v1.IResultSetMetadata|null); + + /** PartialResultSet values. */ + public values: google.protobuf.IValue[]; + + /** PartialResultSet chunkedValue. */ + public chunkedValue: boolean; + + /** PartialResultSet resumeToken. */ + public resumeToken: (Uint8Array|Buffer|string); + + /** PartialResultSet stats. */ + public stats?: (google.spanner.v1.IResultSetStats|null); + + /** PartialResultSet precommitToken. */ + public precommitToken?: (google.spanner.v1.IMultiplexedSessionPrecommitToken|null); + + /** PartialResultSet last. */ + public last: boolean; + + /** PartialResultSet cacheUpdate. */ + public cacheUpdate?: (google.spanner.v1.ICacheUpdate|null); + + /** + * Creates a new PartialResultSet instance using the specified properties. + * @param [properties] Properties to set + * @returns PartialResultSet instance + */ + public static create(properties?: google.spanner.v1.IPartialResultSet): google.spanner.v1.PartialResultSet; + + /** + * Encodes the specified PartialResultSet message. Does not implicitly {@link google.spanner.v1.PartialResultSet.verify|verify} messages. + * @param message PartialResultSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IPartialResultSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartialResultSet message, length delimited. Does not implicitly {@link google.spanner.v1.PartialResultSet.verify|verify} messages. + * @param message PartialResultSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IPartialResultSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartialResultSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartialResultSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartialResultSet; + + /** + * Decodes a PartialResultSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartialResultSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartialResultSet; + + /** + * Verifies a PartialResultSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartialResultSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartialResultSet + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartialResultSet; + + /** + * Creates a plain object from a PartialResultSet message. Also converts values to other types if specified. + * @param message PartialResultSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.PartialResultSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartialResultSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartialResultSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ResultSetMetadata. */ + interface IResultSetMetadata { + + /** ResultSetMetadata rowType */ + rowType?: (google.spanner.v1.IStructType|null); + + /** ResultSetMetadata transaction */ + transaction?: (google.spanner.v1.ITransaction|null); + + /** ResultSetMetadata undeclaredParameters */ + undeclaredParameters?: (google.spanner.v1.IStructType|null); + } + + /** Represents a ResultSetMetadata. */ + class ResultSetMetadata implements IResultSetMetadata { + + /** + * Constructs a new ResultSetMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IResultSetMetadata); + + /** ResultSetMetadata rowType. */ + public rowType?: (google.spanner.v1.IStructType|null); + + /** ResultSetMetadata transaction. */ + public transaction?: (google.spanner.v1.ITransaction|null); + + /** ResultSetMetadata undeclaredParameters. */ + public undeclaredParameters?: (google.spanner.v1.IStructType|null); + + /** + * Creates a new ResultSetMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns ResultSetMetadata instance + */ + public static create(properties?: google.spanner.v1.IResultSetMetadata): google.spanner.v1.ResultSetMetadata; + + /** + * Encodes the specified ResultSetMetadata message. Does not implicitly {@link google.spanner.v1.ResultSetMetadata.verify|verify} messages. + * @param message ResultSetMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IResultSetMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResultSetMetadata message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSetMetadata.verify|verify} messages. + * @param message ResultSetMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IResultSetMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResultSetMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResultSetMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ResultSetMetadata; + + /** + * Decodes a ResultSetMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResultSetMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ResultSetMetadata; + + /** + * Verifies a ResultSetMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResultSetMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResultSetMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ResultSetMetadata; + + /** + * Creates a plain object from a ResultSetMetadata message. Also converts values to other types if specified. + * @param message ResultSetMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ResultSetMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResultSetMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResultSetMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ResultSetStats. */ + interface IResultSetStats { + + /** ResultSetStats queryPlan */ + queryPlan?: (google.spanner.v1.IQueryPlan|null); + + /** ResultSetStats queryStats */ + queryStats?: (google.protobuf.IStruct|null); + + /** ResultSetStats rowCountExact */ + rowCountExact?: (number|Long|string|null); + + /** ResultSetStats rowCountLowerBound */ + rowCountLowerBound?: (number|Long|string|null); + } + + /** Represents a ResultSetStats. */ + class ResultSetStats implements IResultSetStats { + + /** + * Constructs a new ResultSetStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IResultSetStats); + + /** ResultSetStats queryPlan. */ + public queryPlan?: (google.spanner.v1.IQueryPlan|null); + + /** ResultSetStats queryStats. */ + public queryStats?: (google.protobuf.IStruct|null); + + /** ResultSetStats rowCountExact. */ + public rowCountExact?: (number|Long|string|null); + + /** ResultSetStats rowCountLowerBound. */ + public rowCountLowerBound?: (number|Long|string|null); + + /** ResultSetStats rowCount. */ + public rowCount?: ("rowCountExact"|"rowCountLowerBound"); + + /** + * Creates a new ResultSetStats instance using the specified properties. + * @param [properties] Properties to set + * @returns ResultSetStats instance + */ + public static create(properties?: google.spanner.v1.IResultSetStats): google.spanner.v1.ResultSetStats; + + /** + * Encodes the specified ResultSetStats message. Does not implicitly {@link google.spanner.v1.ResultSetStats.verify|verify} messages. + * @param message ResultSetStats message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IResultSetStats, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResultSetStats message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSetStats.verify|verify} messages. + * @param message ResultSetStats message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IResultSetStats, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResultSetStats message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResultSetStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ResultSetStats; + + /** + * Decodes a ResultSetStats message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResultSetStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ResultSetStats; + + /** + * Verifies a ResultSetStats message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResultSetStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResultSetStats + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ResultSetStats; + + /** + * Creates a plain object from a ResultSetStats message. Also converts values to other types if specified. + * @param message ResultSetStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ResultSetStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResultSetStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResultSetStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PlanNode. */ + interface IPlanNode { + + /** PlanNode index */ + index?: (number|null); + + /** PlanNode kind */ + kind?: (google.spanner.v1.PlanNode.Kind|keyof typeof google.spanner.v1.PlanNode.Kind|null); + + /** PlanNode displayName */ + displayName?: (string|null); + + /** PlanNode childLinks */ + childLinks?: (google.spanner.v1.PlanNode.IChildLink[]|null); + + /** PlanNode shortRepresentation */ + shortRepresentation?: (google.spanner.v1.PlanNode.IShortRepresentation|null); + + /** PlanNode metadata */ + metadata?: (google.protobuf.IStruct|null); + + /** PlanNode executionStats */ + executionStats?: (google.protobuf.IStruct|null); + } + + /** Represents a PlanNode. */ + class PlanNode implements IPlanNode { + + /** + * Constructs a new PlanNode. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IPlanNode); + + /** PlanNode index. */ + public index: number; + + /** PlanNode kind. */ + public kind: (google.spanner.v1.PlanNode.Kind|keyof typeof google.spanner.v1.PlanNode.Kind); + + /** PlanNode displayName. */ + public displayName: string; + + /** PlanNode childLinks. */ + public childLinks: google.spanner.v1.PlanNode.IChildLink[]; + + /** PlanNode shortRepresentation. */ + public shortRepresentation?: (google.spanner.v1.PlanNode.IShortRepresentation|null); + + /** PlanNode metadata. */ + public metadata?: (google.protobuf.IStruct|null); + + /** PlanNode executionStats. */ + public executionStats?: (google.protobuf.IStruct|null); + + /** + * Creates a new PlanNode instance using the specified properties. + * @param [properties] Properties to set + * @returns PlanNode instance + */ + public static create(properties?: google.spanner.v1.IPlanNode): google.spanner.v1.PlanNode; + + /** + * Encodes the specified PlanNode message. Does not implicitly {@link google.spanner.v1.PlanNode.verify|verify} messages. + * @param message PlanNode message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IPlanNode, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PlanNode message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.verify|verify} messages. + * @param message PlanNode message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IPlanNode, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PlanNode message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PlanNode + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PlanNode; + + /** + * Decodes a PlanNode message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PlanNode + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PlanNode; + + /** + * Verifies a PlanNode message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PlanNode message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PlanNode + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.PlanNode; + + /** + * Creates a plain object from a PlanNode message. Also converts values to other types if specified. + * @param message PlanNode + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.PlanNode, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PlanNode to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PlanNode + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PlanNode { + + /** Kind enum. */ + enum Kind { + KIND_UNSPECIFIED = 0, + RELATIONAL = 1, + SCALAR = 2 + } + + /** Properties of a ChildLink. */ + interface IChildLink { + + /** ChildLink childIndex */ + childIndex?: (number|null); + + /** ChildLink type */ + type?: (string|null); + + /** ChildLink variable */ + variable?: (string|null); + } + + /** Represents a ChildLink. */ + class ChildLink implements IChildLink { + + /** + * Constructs a new ChildLink. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.PlanNode.IChildLink); + + /** ChildLink childIndex. */ + public childIndex: number; + + /** ChildLink type. */ + public type: string; + + /** ChildLink variable. */ + public variable: string; + + /** + * Creates a new ChildLink instance using the specified properties. + * @param [properties] Properties to set + * @returns ChildLink instance + */ + public static create(properties?: google.spanner.v1.PlanNode.IChildLink): google.spanner.v1.PlanNode.ChildLink; + + /** + * Encodes the specified ChildLink message. Does not implicitly {@link google.spanner.v1.PlanNode.ChildLink.verify|verify} messages. + * @param message ChildLink message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.PlanNode.IChildLink, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ChildLink message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.ChildLink.verify|verify} messages. + * @param message ChildLink message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.PlanNode.IChildLink, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ChildLink message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ChildLink + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PlanNode.ChildLink; + + /** + * Decodes a ChildLink message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ChildLink + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PlanNode.ChildLink; + + /** + * Verifies a ChildLink message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ChildLink message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ChildLink + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.PlanNode.ChildLink; + + /** + * Creates a plain object from a ChildLink message. Also converts values to other types if specified. + * @param message ChildLink + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.PlanNode.ChildLink, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ChildLink to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ChildLink + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ShortRepresentation. */ + interface IShortRepresentation { + + /** ShortRepresentation description */ + description?: (string|null); + + /** ShortRepresentation subqueries */ + subqueries?: ({ [k: string]: number }|null); + } + + /** Represents a ShortRepresentation. */ + class ShortRepresentation implements IShortRepresentation { + + /** + * Constructs a new ShortRepresentation. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.PlanNode.IShortRepresentation); + + /** ShortRepresentation description. */ + public description: string; + + /** ShortRepresentation subqueries. */ + public subqueries: { [k: string]: number }; + + /** + * Creates a new ShortRepresentation instance using the specified properties. + * @param [properties] Properties to set + * @returns ShortRepresentation instance + */ + public static create(properties?: google.spanner.v1.PlanNode.IShortRepresentation): google.spanner.v1.PlanNode.ShortRepresentation; + + /** + * Encodes the specified ShortRepresentation message. Does not implicitly {@link google.spanner.v1.PlanNode.ShortRepresentation.verify|verify} messages. + * @param message ShortRepresentation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.PlanNode.IShortRepresentation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ShortRepresentation message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.ShortRepresentation.verify|verify} messages. + * @param message ShortRepresentation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.PlanNode.IShortRepresentation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ShortRepresentation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ShortRepresentation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PlanNode.ShortRepresentation; + + /** + * Decodes a ShortRepresentation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ShortRepresentation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PlanNode.ShortRepresentation; + + /** + * Verifies a ShortRepresentation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ShortRepresentation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ShortRepresentation + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.PlanNode.ShortRepresentation; + + /** + * Creates a plain object from a ShortRepresentation message. Also converts values to other types if specified. + * @param message ShortRepresentation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.PlanNode.ShortRepresentation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ShortRepresentation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ShortRepresentation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a QueryAdvisorResult. */ + interface IQueryAdvisorResult { + + /** QueryAdvisorResult indexAdvice */ + indexAdvice?: (google.spanner.v1.QueryAdvisorResult.IIndexAdvice[]|null); + } + + /** Represents a QueryAdvisorResult. */ + class QueryAdvisorResult implements IQueryAdvisorResult { + + /** + * Constructs a new QueryAdvisorResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IQueryAdvisorResult); + + /** QueryAdvisorResult indexAdvice. */ + public indexAdvice: google.spanner.v1.QueryAdvisorResult.IIndexAdvice[]; + + /** + * Creates a new QueryAdvisorResult instance using the specified properties. + * @param [properties] Properties to set + * @returns QueryAdvisorResult instance + */ + public static create(properties?: google.spanner.v1.IQueryAdvisorResult): google.spanner.v1.QueryAdvisorResult; + + /** + * Encodes the specified QueryAdvisorResult message. Does not implicitly {@link google.spanner.v1.QueryAdvisorResult.verify|verify} messages. + * @param message QueryAdvisorResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IQueryAdvisorResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified QueryAdvisorResult message, length delimited. Does not implicitly {@link google.spanner.v1.QueryAdvisorResult.verify|verify} messages. + * @param message QueryAdvisorResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IQueryAdvisorResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a QueryAdvisorResult message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns QueryAdvisorResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.QueryAdvisorResult; + + /** + * Decodes a QueryAdvisorResult message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns QueryAdvisorResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.QueryAdvisorResult; + + /** + * Verifies a QueryAdvisorResult message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a QueryAdvisorResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryAdvisorResult + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.QueryAdvisorResult; + + /** + * Creates a plain object from a QueryAdvisorResult message. Also converts values to other types if specified. + * @param message QueryAdvisorResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.QueryAdvisorResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryAdvisorResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryAdvisorResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace QueryAdvisorResult { + + /** Properties of an IndexAdvice. */ + interface IIndexAdvice { + + /** IndexAdvice ddl */ + ddl?: (string[]|null); + + /** IndexAdvice improvementFactor */ + improvementFactor?: (number|null); + } + + /** Represents an IndexAdvice. */ + class IndexAdvice implements IIndexAdvice { + + /** + * Constructs a new IndexAdvice. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.QueryAdvisorResult.IIndexAdvice); + + /** IndexAdvice ddl. */ + public ddl: string[]; + + /** IndexAdvice improvementFactor. */ + public improvementFactor: number; + + /** + * Creates a new IndexAdvice instance using the specified properties. + * @param [properties] Properties to set + * @returns IndexAdvice instance + */ + public static create(properties?: google.spanner.v1.QueryAdvisorResult.IIndexAdvice): google.spanner.v1.QueryAdvisorResult.IndexAdvice; + + /** + * Encodes the specified IndexAdvice message. Does not implicitly {@link google.spanner.v1.QueryAdvisorResult.IndexAdvice.verify|verify} messages. + * @param message IndexAdvice message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.QueryAdvisorResult.IIndexAdvice, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified IndexAdvice message, length delimited. Does not implicitly {@link google.spanner.v1.QueryAdvisorResult.IndexAdvice.verify|verify} messages. + * @param message IndexAdvice message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.QueryAdvisorResult.IIndexAdvice, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an IndexAdvice message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns IndexAdvice + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.QueryAdvisorResult.IndexAdvice; + + /** + * Decodes an IndexAdvice message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns IndexAdvice + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.QueryAdvisorResult.IndexAdvice; + + /** + * Verifies an IndexAdvice message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an IndexAdvice message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexAdvice + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.QueryAdvisorResult.IndexAdvice; + + /** + * Creates a plain object from an IndexAdvice message. Also converts values to other types if specified. + * @param message IndexAdvice + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.QueryAdvisorResult.IndexAdvice, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexAdvice to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexAdvice + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a QueryPlan. */ + interface IQueryPlan { + + /** QueryPlan planNodes */ + planNodes?: (google.spanner.v1.IPlanNode[]|null); + + /** QueryPlan queryAdvice */ + queryAdvice?: (google.spanner.v1.IQueryAdvisorResult|null); + } + + /** Represents a QueryPlan. */ + class QueryPlan implements IQueryPlan { + + /** + * Constructs a new QueryPlan. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IQueryPlan); + + /** QueryPlan planNodes. */ + public planNodes: google.spanner.v1.IPlanNode[]; + + /** QueryPlan queryAdvice. */ + public queryAdvice?: (google.spanner.v1.IQueryAdvisorResult|null); + + /** + * Creates a new QueryPlan instance using the specified properties. + * @param [properties] Properties to set + * @returns QueryPlan instance + */ + public static create(properties?: google.spanner.v1.IQueryPlan): google.spanner.v1.QueryPlan; + + /** + * Encodes the specified QueryPlan message. Does not implicitly {@link google.spanner.v1.QueryPlan.verify|verify} messages. + * @param message QueryPlan message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IQueryPlan, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified QueryPlan message, length delimited. Does not implicitly {@link google.spanner.v1.QueryPlan.verify|verify} messages. + * @param message QueryPlan message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IQueryPlan, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a QueryPlan message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns QueryPlan + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.QueryPlan; + + /** + * Decodes a QueryPlan message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns QueryPlan + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.QueryPlan; + + /** + * Verifies a QueryPlan message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a QueryPlan message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryPlan + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.QueryPlan; + + /** + * Creates a plain object from a QueryPlan message. Also converts values to other types if specified. + * @param message QueryPlan + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.QueryPlan, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryPlan to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryPlan + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ChangeStreamRecord. */ + interface IChangeStreamRecord { + + /** ChangeStreamRecord dataChangeRecord */ + dataChangeRecord?: (google.spanner.v1.ChangeStreamRecord.IDataChangeRecord|null); + + /** ChangeStreamRecord heartbeatRecord */ + heartbeatRecord?: (google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord|null); + + /** ChangeStreamRecord partitionStartRecord */ + partitionStartRecord?: (google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord|null); + + /** ChangeStreamRecord partitionEndRecord */ + partitionEndRecord?: (google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord|null); + + /** ChangeStreamRecord partitionEventRecord */ + partitionEventRecord?: (google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord|null); + } + + /** Represents a ChangeStreamRecord. */ + class ChangeStreamRecord implements IChangeStreamRecord { + + /** + * Constructs a new ChangeStreamRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.IChangeStreamRecord); + + /** ChangeStreamRecord dataChangeRecord. */ + public dataChangeRecord?: (google.spanner.v1.ChangeStreamRecord.IDataChangeRecord|null); + + /** ChangeStreamRecord heartbeatRecord. */ + public heartbeatRecord?: (google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord|null); + + /** ChangeStreamRecord partitionStartRecord. */ + public partitionStartRecord?: (google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord|null); + + /** ChangeStreamRecord partitionEndRecord. */ + public partitionEndRecord?: (google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord|null); + + /** ChangeStreamRecord partitionEventRecord. */ + public partitionEventRecord?: (google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord|null); + + /** ChangeStreamRecord record. */ + public record?: ("dataChangeRecord"|"heartbeatRecord"|"partitionStartRecord"|"partitionEndRecord"|"partitionEventRecord"); + + /** + * Creates a new ChangeStreamRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns ChangeStreamRecord instance + */ + public static create(properties?: google.spanner.v1.IChangeStreamRecord): google.spanner.v1.ChangeStreamRecord; + + /** + * Encodes the specified ChangeStreamRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.verify|verify} messages. + * @param message ChangeStreamRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.IChangeStreamRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ChangeStreamRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.verify|verify} messages. + * @param message ChangeStreamRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.IChangeStreamRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ChangeStreamRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ChangeStreamRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord; + + /** + * Decodes a ChangeStreamRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ChangeStreamRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord; + + /** + * Verifies a ChangeStreamRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ChangeStreamRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ChangeStreamRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord; + + /** + * Creates a plain object from a ChangeStreamRecord message. Also converts values to other types if specified. + * @param message ChangeStreamRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ChangeStreamRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ChangeStreamRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ChangeStreamRecord { + + /** Properties of a DataChangeRecord. */ + interface IDataChangeRecord { + + /** DataChangeRecord commitTimestamp */ + commitTimestamp?: (google.protobuf.ITimestamp|null); + + /** DataChangeRecord recordSequence */ + recordSequence?: (string|null); + + /** DataChangeRecord serverTransactionId */ + serverTransactionId?: (string|null); + + /** DataChangeRecord isLastRecordInTransactionInPartition */ + isLastRecordInTransactionInPartition?: (boolean|null); + + /** DataChangeRecord table */ + table?: (string|null); + + /** DataChangeRecord columnMetadata */ + columnMetadata?: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata[]|null); + + /** DataChangeRecord mods */ + mods?: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod[]|null); + + /** DataChangeRecord modType */ + modType?: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType|keyof typeof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType|null); + + /** DataChangeRecord valueCaptureType */ + valueCaptureType?: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType|keyof typeof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType|null); + + /** DataChangeRecord numberOfRecordsInTransaction */ + numberOfRecordsInTransaction?: (number|null); + + /** DataChangeRecord numberOfPartitionsInTransaction */ + numberOfPartitionsInTransaction?: (number|null); + + /** DataChangeRecord transactionTag */ + transactionTag?: (string|null); + + /** DataChangeRecord isSystemTransaction */ + isSystemTransaction?: (boolean|null); + } + + /** Represents a DataChangeRecord. */ + class DataChangeRecord implements IDataChangeRecord { + + /** + * Constructs a new DataChangeRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.IDataChangeRecord); + + /** DataChangeRecord commitTimestamp. */ + public commitTimestamp?: (google.protobuf.ITimestamp|null); + + /** DataChangeRecord recordSequence. */ + public recordSequence: string; + + /** DataChangeRecord serverTransactionId. */ + public serverTransactionId: string; + + /** DataChangeRecord isLastRecordInTransactionInPartition. */ + public isLastRecordInTransactionInPartition: boolean; + + /** DataChangeRecord table. */ + public table: string; + + /** DataChangeRecord columnMetadata. */ + public columnMetadata: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata[]; + + /** DataChangeRecord mods. */ + public mods: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod[]; + + /** DataChangeRecord modType. */ + public modType: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType|keyof typeof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType); + + /** DataChangeRecord valueCaptureType. */ + public valueCaptureType: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType|keyof typeof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType); + + /** DataChangeRecord numberOfRecordsInTransaction. */ + public numberOfRecordsInTransaction: number; + + /** DataChangeRecord numberOfPartitionsInTransaction. */ + public numberOfPartitionsInTransaction: number; + + /** DataChangeRecord transactionTag. */ + public transactionTag: string; + + /** DataChangeRecord isSystemTransaction. */ + public isSystemTransaction: boolean; + + /** + * Creates a new DataChangeRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns DataChangeRecord instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.IDataChangeRecord): google.spanner.v1.ChangeStreamRecord.DataChangeRecord; + + /** + * Encodes the specified DataChangeRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.verify|verify} messages. + * @param message DataChangeRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.IDataChangeRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DataChangeRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.verify|verify} messages. + * @param message DataChangeRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.IDataChangeRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DataChangeRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DataChangeRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.DataChangeRecord; + + /** + * Decodes a DataChangeRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DataChangeRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.DataChangeRecord; + + /** + * Verifies a DataChangeRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DataChangeRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DataChangeRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.DataChangeRecord; + + /** + * Creates a plain object from a DataChangeRecord message. Also converts values to other types if specified. + * @param message DataChangeRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DataChangeRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DataChangeRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace DataChangeRecord { + + /** Properties of a ColumnMetadata. */ + interface IColumnMetadata { + + /** ColumnMetadata name */ + name?: (string|null); + + /** ColumnMetadata type */ + type?: (google.spanner.v1.IType|null); + + /** ColumnMetadata isPrimaryKey */ + isPrimaryKey?: (boolean|null); + + /** ColumnMetadata ordinalPosition */ + ordinalPosition?: (number|Long|string|null); + } + + /** Represents a ColumnMetadata. */ + class ColumnMetadata implements IColumnMetadata { + + /** + * Constructs a new ColumnMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata); + + /** ColumnMetadata name. */ + public name: string; + + /** ColumnMetadata type. */ + public type?: (google.spanner.v1.IType|null); + + /** ColumnMetadata isPrimaryKey. */ + public isPrimaryKey: boolean; + + /** ColumnMetadata ordinalPosition. */ + public ordinalPosition: (number|Long|string); + + /** + * Creates a new ColumnMetadata instance using the specified properties. + * @param [properties] Properties to set + * @returns ColumnMetadata instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata; + + /** + * Encodes the specified ColumnMetadata message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.verify|verify} messages. + * @param message ColumnMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ColumnMetadata message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.verify|verify} messages. + * @param message ColumnMetadata message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ColumnMetadata message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ColumnMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata; + + /** + * Decodes a ColumnMetadata message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ColumnMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata; + + /** + * Verifies a ColumnMetadata message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ColumnMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ColumnMetadata + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata; + + /** + * Creates a plain object from a ColumnMetadata message. Also converts values to other types if specified. + * @param message ColumnMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ColumnMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ColumnMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ModValue. */ + interface IModValue { + + /** ModValue columnMetadataIndex */ + columnMetadataIndex?: (number|null); + + /** ModValue value */ + value?: (google.protobuf.IValue|null); + } + + /** Represents a ModValue. */ + class ModValue implements IModValue { + + /** + * Constructs a new ModValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue); + + /** ModValue columnMetadataIndex. */ + public columnMetadataIndex: number; + + /** ModValue value. */ + public value?: (google.protobuf.IValue|null); + + /** + * Creates a new ModValue instance using the specified properties. + * @param [properties] Properties to set + * @returns ModValue instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue; + + /** + * Encodes the specified ModValue message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.verify|verify} messages. + * @param message ModValue message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ModValue message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.verify|verify} messages. + * @param message ModValue message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ModValue message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ModValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue; + + /** + * Decodes a ModValue message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ModValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue; + + /** + * Verifies a ModValue message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ModValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ModValue + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue; + + /** + * Creates a plain object from a ModValue message. Also converts values to other types if specified. + * @param message ModValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ModValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ModValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Mod. */ + interface IMod { + + /** Mod keys */ + keys?: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue[]|null); + + /** Mod oldValues */ + oldValues?: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue[]|null); + + /** Mod newValues */ + newValues?: (google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue[]|null); + } + + /** Represents a Mod. */ + class Mod implements IMod { + + /** + * Constructs a new Mod. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod); + + /** Mod keys. */ + public keys: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue[]; + + /** Mod oldValues. */ + public oldValues: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue[]; + + /** Mod newValues. */ + public newValues: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue[]; + + /** + * Creates a new Mod instance using the specified properties. + * @param [properties] Properties to set + * @returns Mod instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod; + + /** + * Encodes the specified Mod message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.verify|verify} messages. + * @param message Mod message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Mod message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.verify|verify} messages. + * @param message Mod message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Mod message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod; + + /** + * Decodes a Mod message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod; + + /** + * Verifies a Mod message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Mod message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Mod + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod; + + /** + * Creates a plain object from a Mod message. Also converts values to other types if specified. + * @param message Mod + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Mod to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Mod + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** ModType enum. */ + enum ModType { + MOD_TYPE_UNSPECIFIED = 0, + INSERT = 10, + UPDATE = 20, + DELETE = 30 + } + + /** ValueCaptureType enum. */ + enum ValueCaptureType { + VALUE_CAPTURE_TYPE_UNSPECIFIED = 0, + OLD_AND_NEW_VALUES = 10, + NEW_VALUES = 20, + NEW_ROW = 30, + NEW_ROW_AND_OLD_VALUES = 40 + } + } + + /** Properties of a HeartbeatRecord. */ + interface IHeartbeatRecord { + + /** HeartbeatRecord timestamp */ + timestamp?: (google.protobuf.ITimestamp|null); + } + + /** Represents a HeartbeatRecord. */ + class HeartbeatRecord implements IHeartbeatRecord { + + /** + * Constructs a new HeartbeatRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord); + + /** HeartbeatRecord timestamp. */ + public timestamp?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new HeartbeatRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns HeartbeatRecord instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord): google.spanner.v1.ChangeStreamRecord.HeartbeatRecord; + + /** + * Encodes the specified HeartbeatRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.verify|verify} messages. + * @param message HeartbeatRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified HeartbeatRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.verify|verify} messages. + * @param message HeartbeatRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a HeartbeatRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns HeartbeatRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.HeartbeatRecord; + + /** + * Decodes a HeartbeatRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns HeartbeatRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.HeartbeatRecord; + + /** + * Verifies a HeartbeatRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a HeartbeatRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HeartbeatRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.HeartbeatRecord; + + /** + * Creates a plain object from a HeartbeatRecord message. Also converts values to other types if specified. + * @param message HeartbeatRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.HeartbeatRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HeartbeatRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HeartbeatRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionStartRecord. */ + interface IPartitionStartRecord { + + /** PartitionStartRecord startTimestamp */ + startTimestamp?: (google.protobuf.ITimestamp|null); + + /** PartitionStartRecord recordSequence */ + recordSequence?: (string|null); + + /** PartitionStartRecord partitionTokens */ + partitionTokens?: (string[]|null); + } + + /** Represents a PartitionStartRecord. */ + class PartitionStartRecord implements IPartitionStartRecord { + + /** + * Constructs a new PartitionStartRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord); + + /** PartitionStartRecord startTimestamp. */ + public startTimestamp?: (google.protobuf.ITimestamp|null); + + /** PartitionStartRecord recordSequence. */ + public recordSequence: string; + + /** PartitionStartRecord partitionTokens. */ + public partitionTokens: string[]; + + /** + * Creates a new PartitionStartRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionStartRecord instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord): google.spanner.v1.ChangeStreamRecord.PartitionStartRecord; + + /** + * Encodes the specified PartitionStartRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.verify|verify} messages. + * @param message PartitionStartRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionStartRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.verify|verify} messages. + * @param message PartitionStartRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionStartRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionStartRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.PartitionStartRecord; + + /** + * Decodes a PartitionStartRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionStartRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.PartitionStartRecord; + + /** + * Verifies a PartitionStartRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionStartRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionStartRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.PartitionStartRecord; + + /** + * Creates a plain object from a PartitionStartRecord message. Also converts values to other types if specified. + * @param message PartitionStartRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.PartitionStartRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionStartRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionStartRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionEndRecord. */ + interface IPartitionEndRecord { + + /** PartitionEndRecord endTimestamp */ + endTimestamp?: (google.protobuf.ITimestamp|null); + + /** PartitionEndRecord recordSequence */ + recordSequence?: (string|null); + + /** PartitionEndRecord partitionToken */ + partitionToken?: (string|null); + } + + /** Represents a PartitionEndRecord. */ + class PartitionEndRecord implements IPartitionEndRecord { + + /** + * Constructs a new PartitionEndRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord); + + /** PartitionEndRecord endTimestamp. */ + public endTimestamp?: (google.protobuf.ITimestamp|null); + + /** PartitionEndRecord recordSequence. */ + public recordSequence: string; + + /** PartitionEndRecord partitionToken. */ + public partitionToken: string; + + /** + * Creates a new PartitionEndRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionEndRecord instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord): google.spanner.v1.ChangeStreamRecord.PartitionEndRecord; + + /** + * Encodes the specified PartitionEndRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.verify|verify} messages. + * @param message PartitionEndRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionEndRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.verify|verify} messages. + * @param message PartitionEndRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionEndRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionEndRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.PartitionEndRecord; + + /** + * Decodes a PartitionEndRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionEndRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.PartitionEndRecord; + + /** + * Verifies a PartitionEndRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionEndRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionEndRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.PartitionEndRecord; + + /** + * Creates a plain object from a PartitionEndRecord message. Also converts values to other types if specified. + * @param message PartitionEndRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.PartitionEndRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionEndRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionEndRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionEventRecord. */ + interface IPartitionEventRecord { + + /** PartitionEventRecord commitTimestamp */ + commitTimestamp?: (google.protobuf.ITimestamp|null); + + /** PartitionEventRecord recordSequence */ + recordSequence?: (string|null); + + /** PartitionEventRecord partitionToken */ + partitionToken?: (string|null); + + /** PartitionEventRecord moveInEvents */ + moveInEvents?: (google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent[]|null); + + /** PartitionEventRecord moveOutEvents */ + moveOutEvents?: (google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent[]|null); + } + + /** Represents a PartitionEventRecord. */ + class PartitionEventRecord implements IPartitionEventRecord { + + /** + * Constructs a new PartitionEventRecord. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord); + + /** PartitionEventRecord commitTimestamp. */ + public commitTimestamp?: (google.protobuf.ITimestamp|null); + + /** PartitionEventRecord recordSequence. */ + public recordSequence: string; + + /** PartitionEventRecord partitionToken. */ + public partitionToken: string; + + /** PartitionEventRecord moveInEvents. */ + public moveInEvents: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent[]; + + /** PartitionEventRecord moveOutEvents. */ + public moveOutEvents: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent[]; + + /** + * Creates a new PartitionEventRecord instance using the specified properties. + * @param [properties] Properties to set + * @returns PartitionEventRecord instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord; + + /** + * Encodes the specified PartitionEventRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.verify|verify} messages. + * @param message PartitionEventRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartitionEventRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.verify|verify} messages. + * @param message PartitionEventRecord message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartitionEventRecord message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartitionEventRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord; + + /** + * Decodes a PartitionEventRecord message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartitionEventRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord; + + /** + * Verifies a PartitionEventRecord message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartitionEventRecord message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionEventRecord + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord; + + /** + * Creates a plain object from a PartitionEventRecord message. Also converts values to other types if specified. + * @param message PartitionEventRecord + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionEventRecord to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionEventRecord + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PartitionEventRecord { + + /** Properties of a MoveInEvent. */ + interface IMoveInEvent { + + /** MoveInEvent sourcePartitionToken */ + sourcePartitionToken?: (string|null); + } + + /** Represents a MoveInEvent. */ + class MoveInEvent implements IMoveInEvent { + + /** + * Constructs a new MoveInEvent. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent); + + /** MoveInEvent sourcePartitionToken. */ + public sourcePartitionToken: string; + + /** + * Creates a new MoveInEvent instance using the specified properties. + * @param [properties] Properties to set + * @returns MoveInEvent instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent; + + /** + * Encodes the specified MoveInEvent message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.verify|verify} messages. + * @param message MoveInEvent message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MoveInEvent message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.verify|verify} messages. + * @param message MoveInEvent message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MoveInEvent message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MoveInEvent + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent; + + /** + * Decodes a MoveInEvent message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MoveInEvent + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent; + + /** + * Verifies a MoveInEvent message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MoveInEvent message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MoveInEvent + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent; + + /** + * Creates a plain object from a MoveInEvent message. Also converts values to other types if specified. + * @param message MoveInEvent + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MoveInEvent to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MoveInEvent + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MoveOutEvent. */ + interface IMoveOutEvent { + + /** MoveOutEvent destinationPartitionToken */ + destinationPartitionToken?: (string|null); + } + + /** Represents a MoveOutEvent. */ + class MoveOutEvent implements IMoveOutEvent { + + /** + * Constructs a new MoveOutEvent. + * @param [properties] Properties to set + */ + constructor(properties?: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent); + + /** MoveOutEvent destinationPartitionToken. */ + public destinationPartitionToken: string; + + /** + * Creates a new MoveOutEvent instance using the specified properties. + * @param [properties] Properties to set + * @returns MoveOutEvent instance + */ + public static create(properties?: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent; + + /** + * Encodes the specified MoveOutEvent message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.verify|verify} messages. + * @param message MoveOutEvent message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MoveOutEvent message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.verify|verify} messages. + * @param message MoveOutEvent message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MoveOutEvent message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MoveOutEvent + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent; + + /** + * Decodes a MoveOutEvent message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MoveOutEvent + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent; + + /** + * Verifies a MoveOutEvent message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MoveOutEvent message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MoveOutEvent + */ + public static fromObject(object: { [k: string]: any }): google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent; + + /** + * Creates a plain object from a MoveOutEvent message. Also converts values to other types if specified. + * @param message MoveOutEvent + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MoveOutEvent to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MoveOutEvent + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + } + } + + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + enum FieldBehavior { + FIELD_BEHAVIOR_UNSPECIFIED = 0, + OPTIONAL = 1, + REQUIRED = 2, + OUTPUT_ONLY = 3, + INPUT_ONLY = 4, + IMMUTABLE = 5, + UNORDERED_LIST = 6, + NON_EMPTY_DEFAULT = 7, + IDENTIFIER = 8 + } + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); + + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); + + /** ResourceDescriptor nameField */ + nameField?: (string|null); + + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|keyof typeof google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: (google.api.ResourceDescriptor.History|keyof typeof google.api.ResourceDescriptor.History); + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a new ResourceDescriptor instance using the specified properties. + * @param [properties] Properties to set + * @returns ResourceDescriptor instance + */ + public static create(properties?: google.api.IResourceDescriptor): google.api.ResourceDescriptor; + + /** + * Encodes the specified ResourceDescriptor message. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @param message ResourceDescriptor message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResourceDescriptor message, length delimited. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @param message ResourceDescriptor message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResourceDescriptor + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceDescriptor; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResourceDescriptor + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceDescriptor; + + /** + * Verifies a ResourceDescriptor message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + enum History { + HISTORY_UNSPECIFIED = 0, + ORIGINALLY_SINGLE_PATTERN = 1, + FUTURE_MULTI_PATTERN = 2 + } + + /** Style enum. */ + enum Style { + STYLE_UNSPECIFIED = 0, + DECLARATIVE_FRIENDLY = 1 + } + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a new ResourceReference instance using the specified properties. + * @param [properties] Properties to set + * @returns ResourceReference instance + */ + public static create(properties?: google.api.IResourceReference): google.api.ResourceReference; + + /** + * Encodes the specified ResourceReference message. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @param message ResourceReference message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResourceReference message, length delimited. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @param message ResourceReference message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResourceReference message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResourceReference + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceReference; + + /** + * Decodes a ResourceReference message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResourceReference + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceReference; + + /** + * Verifies a ResourceReference message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a new Http instance using the specified properties. + * @param [properties] Properties to set + * @returns Http instance + */ + public static create(properties?: google.api.IHttp): google.api.Http; + + /** + * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @param message Http message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Http message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; + + /** + * Decodes a Http message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; + + /** + * Verifies a Http message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a new HttpRule instance using the specified properties. + * @param [properties] Properties to set + * @returns HttpRule instance + */ + public static create(properties?: google.api.IHttpRule): google.api.HttpRule; + + /** + * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @param message HttpRule message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a HttpRule message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; + + /** + * Decodes a HttpRule message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; + + /** + * Verifies a HttpRule message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a new CustomHttpPattern instance using the specified properties. + * @param [properties] Properties to set + * @returns CustomHttpPattern instance + */ + public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; + + /** + * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @param message CustomHttpPattern message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; + + /** + * Verifies a CustomHttpPattern message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + + /** + * Creates a new CommonLanguageSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns CommonLanguageSettings instance + */ + public static create(properties?: google.api.ICommonLanguageSettings): google.api.CommonLanguageSettings; + + /** + * Encodes the specified CommonLanguageSettings message. Does not implicitly {@link google.api.CommonLanguageSettings.verify|verify} messages. + * @param message CommonLanguageSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ICommonLanguageSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CommonLanguageSettings message, length delimited. Does not implicitly {@link google.api.CommonLanguageSettings.verify|verify} messages. + * @param message CommonLanguageSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ICommonLanguageSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CommonLanguageSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CommonLanguageSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CommonLanguageSettings; + + /** + * Decodes a CommonLanguageSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CommonLanguageSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CommonLanguageSettings; + + /** + * Verifies a CommonLanguageSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|keyof typeof google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: (google.api.LaunchStage|keyof typeof google.api.LaunchStage); + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a new ClientLibrarySettings instance using the specified properties. + * @param [properties] Properties to set + * @returns ClientLibrarySettings instance + */ + public static create(properties?: google.api.IClientLibrarySettings): google.api.ClientLibrarySettings; + + /** + * Encodes the specified ClientLibrarySettings message. Does not implicitly {@link google.api.ClientLibrarySettings.verify|verify} messages. + * @param message ClientLibrarySettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IClientLibrarySettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ClientLibrarySettings message, length delimited. Does not implicitly {@link google.api.ClientLibrarySettings.verify|verify} messages. + * @param message ClientLibrarySettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IClientLibrarySettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ClientLibrarySettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ClientLibrarySettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ClientLibrarySettings; + + /** + * Decodes a ClientLibrarySettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ClientLibrarySettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ClientLibrarySettings; + + /** + * Verifies a ClientLibrarySettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|keyof typeof google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: (google.api.ClientLibraryOrganization|keyof typeof google.api.ClientLibraryOrganization); + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a new Publishing instance using the specified properties. + * @param [properties] Properties to set + * @returns Publishing instance + */ + public static create(properties?: google.api.IPublishing): google.api.Publishing; + + /** + * Encodes the specified Publishing message. Does not implicitly {@link google.api.Publishing.verify|verify} messages. + * @param message Publishing message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IPublishing, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Publishing message, length delimited. Does not implicitly {@link google.api.Publishing.verify|verify} messages. + * @param message Publishing message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IPublishing, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Publishing message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Publishing + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Publishing; + + /** + * Decodes a Publishing message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Publishing + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Publishing; + + /** + * Verifies a Publishing message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a new JavaSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns JavaSettings instance + */ + public static create(properties?: google.api.IJavaSettings): google.api.JavaSettings; + + /** + * Encodes the specified JavaSettings message. Does not implicitly {@link google.api.JavaSettings.verify|verify} messages. + * @param message JavaSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IJavaSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified JavaSettings message, length delimited. Does not implicitly {@link google.api.JavaSettings.verify|verify} messages. + * @param message JavaSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IJavaSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a JavaSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns JavaSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.JavaSettings; + + /** + * Decodes a JavaSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns JavaSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.JavaSettings; + + /** + * Verifies a JavaSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a new CppSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns CppSettings instance + */ + public static create(properties?: google.api.ICppSettings): google.api.CppSettings; + + /** + * Encodes the specified CppSettings message. Does not implicitly {@link google.api.CppSettings.verify|verify} messages. + * @param message CppSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ICppSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CppSettings message, length delimited. Does not implicitly {@link google.api.CppSettings.verify|verify} messages. + * @param message CppSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ICppSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CppSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CppSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CppSettings; + + /** + * Decodes a CppSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CppSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CppSettings; + + /** + * Verifies a CppSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a new PhpSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns PhpSettings instance + */ + public static create(properties?: google.api.IPhpSettings): google.api.PhpSettings; + + /** + * Encodes the specified PhpSettings message. Does not implicitly {@link google.api.PhpSettings.verify|verify} messages. + * @param message PhpSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IPhpSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PhpSettings message, length delimited. Does not implicitly {@link google.api.PhpSettings.verify|verify} messages. + * @param message PhpSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IPhpSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PhpSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PhpSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PhpSettings; + + /** + * Decodes a PhpSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PhpSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PhpSettings; + + /** + * Verifies a PhpSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + + /** + * Creates a new PythonSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns PythonSettings instance + */ + public static create(properties?: google.api.IPythonSettings): google.api.PythonSettings; + + /** + * Encodes the specified PythonSettings message. Does not implicitly {@link google.api.PythonSettings.verify|verify} messages. + * @param message PythonSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IPythonSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PythonSettings message, length delimited. Does not implicitly {@link google.api.PythonSettings.verify|verify} messages. + * @param message PythonSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IPythonSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PythonSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PythonSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings; + + /** + * Decodes a PythonSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PythonSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings; + + /** + * Verifies a PythonSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PythonSettings { + + /** Properties of an ExperimentalFeatures. */ + interface IExperimentalFeatures { + + /** ExperimentalFeatures restAsyncIoEnabled */ + restAsyncIoEnabled?: (boolean|null); + + /** ExperimentalFeatures protobufPythonicTypesEnabled */ + protobufPythonicTypesEnabled?: (boolean|null); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (boolean|null); + } + + /** Represents an ExperimentalFeatures. */ + class ExperimentalFeatures implements IExperimentalFeatures { + + /** + * Constructs a new ExperimentalFeatures. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); + + /** ExperimentalFeatures restAsyncIoEnabled. */ + public restAsyncIoEnabled: boolean; + + /** ExperimentalFeatures protobufPythonicTypesEnabled. */ + public protobufPythonicTypesEnabled: boolean; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExperimentalFeatures + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @param message ExperimentalFeatures + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExperimentalFeatures + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a new NodeSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns NodeSettings instance + */ + public static create(properties?: google.api.INodeSettings): google.api.NodeSettings; + + /** + * Encodes the specified NodeSettings message. Does not implicitly {@link google.api.NodeSettings.verify|verify} messages. + * @param message NodeSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.INodeSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NodeSettings message, length delimited. Does not implicitly {@link google.api.NodeSettings.verify|verify} messages. + * @param message NodeSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.INodeSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NodeSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NodeSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.NodeSettings; + + /** + * Decodes a NodeSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NodeSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.NodeSettings; + + /** + * Verifies a NodeSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { + + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } + + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { + + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a new DotnetSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns DotnetSettings instance + */ + public static create(properties?: google.api.IDotnetSettings): google.api.DotnetSettings; + + /** + * Encodes the specified DotnetSettings message. Does not implicitly {@link google.api.DotnetSettings.verify|verify} messages. + * @param message DotnetSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IDotnetSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DotnetSettings message, length delimited. Does not implicitly {@link google.api.DotnetSettings.verify|verify} messages. + * @param message DotnetSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IDotnetSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DotnetSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DotnetSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.DotnetSettings; + + /** + * Decodes a DotnetSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DotnetSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.DotnetSettings; + + /** + * Verifies a DotnetSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { + + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); + + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a new RubySettings instance using the specified properties. + * @param [properties] Properties to set + * @returns RubySettings instance + */ + public static create(properties?: google.api.IRubySettings): google.api.RubySettings; + + /** + * Encodes the specified RubySettings message. Does not implicitly {@link google.api.RubySettings.verify|verify} messages. + * @param message RubySettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IRubySettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RubySettings message, length delimited. Does not implicitly {@link google.api.RubySettings.verify|verify} messages. + * @param message RubySettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IRubySettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RubySettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RubySettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.RubySettings; + + /** + * Decodes a RubySettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RubySettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.RubySettings; + + /** + * Verifies a RubySettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); + + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** + * Creates a new GoSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns GoSettings instance + */ + public static create(properties?: google.api.IGoSettings): google.api.GoSettings; + + /** + * Encodes the specified GoSettings message. Does not implicitly {@link google.api.GoSettings.verify|verify} messages. + * @param message GoSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IGoSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GoSettings message, length delimited. Does not implicitly {@link google.api.GoSettings.verify|verify} messages. + * @param message GoSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IGoSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GoSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GoSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.GoSettings; + + /** + * Decodes a GoSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GoSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.GoSettings; + + /** + * Verifies a GoSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodSettings. */ + interface IMethodSettings { + + /** MethodSettings selector */ + selector?: (string|null); + + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } + + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { + + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); + + /** MethodSettings selector. */ + public selector: string; + + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; + + /** + * Creates a new MethodSettings instance using the specified properties. + * @param [properties] Properties to set + * @returns MethodSettings instance + */ + public static create(properties?: google.api.IMethodSettings): google.api.MethodSettings; + + /** + * Encodes the specified MethodSettings message. Does not implicitly {@link google.api.MethodSettings.verify|verify} messages. + * @param message MethodSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IMethodSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MethodSettings message, length delimited. Does not implicitly {@link google.api.MethodSettings.verify|verify} messages. + * @param message MethodSettings message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IMethodSettings, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MethodSettings message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MethodSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.MethodSettings; + + /** + * Decodes a MethodSettings message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MethodSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.MethodSettings; + + /** + * Verifies a MethodSettings message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a new LongRunning instance using the specified properties. + * @param [properties] Properties to set + * @returns LongRunning instance + */ + public static create(properties?: google.api.MethodSettings.ILongRunning): google.api.MethodSettings.LongRunning; + + /** + * Encodes the specified LongRunning message. Does not implicitly {@link google.api.MethodSettings.LongRunning.verify|verify} messages. + * @param message LongRunning message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.MethodSettings.ILongRunning, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified LongRunning message, length delimited. Does not implicitly {@link google.api.MethodSettings.LongRunning.verify|verify} messages. + * @param message LongRunning message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.MethodSettings.ILongRunning, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a LongRunning message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns LongRunning + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.MethodSettings.LongRunning; + + /** + * Decodes a LongRunning message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns LongRunning + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.MethodSettings.LongRunning; + + /** + * Verifies a LongRunning message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** ClientLibraryOrganization enum. */ + enum ClientLibraryOrganization { + CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED = 0, + CLOUD = 1, + ADS = 2, + PHOTOS = 3, + STREET_VIEW = 4, + SHOPPING = 5, + GEO = 6, + GENERATIVE_AI = 7 + } + + /** ClientLibraryDestination enum. */ + enum ClientLibraryDestination { + CLIENT_LIBRARY_DESTINATION_UNSPECIFIED = 0, + GITHUB = 10, + PACKAGE_MANAGER = 20 + } + + /** Properties of a SelectiveGapicGeneration. */ + interface ISelectiveGapicGeneration { + + /** SelectiveGapicGeneration methods */ + methods?: (string[]|null); + + /** SelectiveGapicGeneration generateOmittedAsInternal */ + generateOmittedAsInternal?: (boolean|null); + } + + /** Represents a SelectiveGapicGeneration. */ + class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + + /** + * Constructs a new SelectiveGapicGeneration. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ISelectiveGapicGeneration); + + /** SelectiveGapicGeneration methods. */ + public methods: string[]; + + /** SelectiveGapicGeneration generateOmittedAsInternal. */ + public generateOmittedAsInternal: boolean; + + /** + * Creates a new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SelectiveGapicGeneration + */ + public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @param message SelectiveGapicGeneration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** LaunchStage enum. */ + enum LaunchStage { + LAUNCH_STAGE_UNSPECIFIED = 0, + UNIMPLEMENTED = 6, + PRELAUNCH = 7, + EARLY_ACCESS = 1, + ALPHA = 2, + BETA = 3, + GA = 4, + DEPRECATED = 5 + } + } + + /** Namespace longrunning. */ + namespace longrunning { + + /** Represents an Operations */ + class Operations extends $protobuf.rpc.Service { + + /** + * Constructs a new Operations service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new Operations service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Operations; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListOperationsResponse + */ + public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; + + /** + * Calls ListOperations. + * @param request ListOperationsRequest message or plain object + * @returns Promise + */ + public listOperations(request: google.longrunning.IListOperationsRequest): Promise; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; + + /** + * Calls GetOperation. + * @param request GetOperationRequest message or plain object + * @returns Promise + */ + public getOperation(request: google.longrunning.IGetOperationRequest): Promise; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; + + /** + * Calls DeleteOperation. + * @param request DeleteOperationRequest message or plain object + * @returns Promise + */ + public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; + + /** + * Calls CancelOperation. + * @param request CancelOperationRequest message or plain object + * @returns Promise + */ + public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; + + /** + * Calls WaitOperation. + * @param request WaitOperationRequest message or plain object + * @returns Promise + */ + public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise; + } + + namespace Operations { + + /** + * Callback as used by {@link google.longrunning.Operations|listOperations}. + * @param error Error, if any + * @param [response] ListOperationsResponse + */ + type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; + + /** + * Callback as used by {@link google.longrunning.Operations|getOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.longrunning.Operations|deleteOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations|cancelOperation}. + * @param error Error, if any + * @param [response] Empty + */ + type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.longrunning.Operations|waitOperation}. + * @param error Error, if any + * @param [response] Operation + */ + type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + } + + /** Properties of an Operation. */ + interface IOperation { + + /** Operation name */ + name?: (string|null); + + /** Operation metadata */ + metadata?: (google.protobuf.IAny|null); + + /** Operation done */ + done?: (boolean|null); + + /** Operation error */ + error?: (google.rpc.IStatus|null); + + /** Operation response */ + response?: (google.protobuf.IAny|null); + } + + /** Represents an Operation. */ + class Operation implements IOperation { + + /** + * Constructs a new Operation. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperation); + + /** Operation name. */ + public name: string; + + /** Operation metadata. */ + public metadata?: (google.protobuf.IAny|null); + + /** Operation done. */ + public done: boolean; + + /** Operation error. */ + public error?: (google.rpc.IStatus|null); + + /** Operation response. */ + public response?: (google.protobuf.IAny|null); + + /** Operation result. */ + public result?: ("error"|"response"); + + /** + * Creates a new Operation instance using the specified properties. + * @param [properties] Properties to set + * @returns Operation instance + */ + public static create(properties?: google.longrunning.IOperation): google.longrunning.Operation; + + /** + * Encodes the specified Operation message. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages. + * @param message Operation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Operation message, length delimited. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages. + * @param message Operation message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Operation message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Operation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.Operation; + + /** + * Decodes an Operation message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Operation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.Operation; + + /** + * Verifies an Operation message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Operation + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @param message Operation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Operation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetOperationRequest. */ + interface IGetOperationRequest { + + /** GetOperationRequest name */ + name?: (string|null); + } + + /** Represents a GetOperationRequest. */ + class GetOperationRequest implements IGetOperationRequest { + + /** + * Constructs a new GetOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IGetOperationRequest); + + /** GetOperationRequest name. */ + public name: string; + + /** + * Creates a new GetOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetOperationRequest instance + */ + public static create(properties?: google.longrunning.IGetOperationRequest): google.longrunning.GetOperationRequest; + + /** + * Encodes the specified GetOperationRequest message. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages. + * @param message GetOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages. + * @param message GetOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.GetOperationRequest; + + /** + * Decodes a GetOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.GetOperationRequest; + + /** + * Verifies a GetOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @param message GetOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsRequest. */ + interface IListOperationsRequest { + + /** ListOperationsRequest name */ + name?: (string|null); + + /** ListOperationsRequest filter */ + filter?: (string|null); + + /** ListOperationsRequest pageSize */ + pageSize?: (number|null); + + /** ListOperationsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListOperationsRequest. */ + class ListOperationsRequest implements IListOperationsRequest { + + /** + * Constructs a new ListOperationsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsRequest); + + /** ListOperationsRequest name. */ + public name: string; + + /** ListOperationsRequest filter. */ + public filter: string; + + /** ListOperationsRequest pageSize. */ + public pageSize: number; + + /** ListOperationsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListOperationsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListOperationsRequest instance + */ + public static create(properties?: google.longrunning.IListOperationsRequest): google.longrunning.ListOperationsRequest; + + /** + * Encodes the specified ListOperationsRequest message. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages. + * @param message ListOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListOperationsRequest message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages. + * @param message ListOperationsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListOperationsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsRequest; + + /** + * Decodes a ListOperationsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsRequest; + + /** + * Verifies a ListOperationsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @param message ListOperationsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListOperationsResponse. */ + interface IListOperationsResponse { + + /** ListOperationsResponse operations */ + operations?: (google.longrunning.IOperation[]|null); + + /** ListOperationsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListOperationsResponse. */ + class ListOperationsResponse implements IListOperationsResponse { + + /** + * Constructs a new ListOperationsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IListOperationsResponse); + + /** ListOperationsResponse operations. */ + public operations: google.longrunning.IOperation[]; + + /** ListOperationsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListOperationsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListOperationsResponse instance + */ + public static create(properties?: google.longrunning.IListOperationsResponse): google.longrunning.ListOperationsResponse; + + /** + * Encodes the specified ListOperationsResponse message. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages. + * @param message ListOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListOperationsResponse message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages. + * @param message ListOperationsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListOperationsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsResponse; + + /** + * Decodes a ListOperationsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsResponse; + + /** + * Verifies a ListOperationsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListOperationsResponse + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @param message ListOperationsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListOperationsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CancelOperationRequest. */ + interface ICancelOperationRequest { + + /** CancelOperationRequest name */ + name?: (string|null); + } + + /** Represents a CancelOperationRequest. */ + class CancelOperationRequest implements ICancelOperationRequest { + + /** + * Constructs a new CancelOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.ICancelOperationRequest); + + /** CancelOperationRequest name. */ + public name: string; + + /** + * Creates a new CancelOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CancelOperationRequest instance + */ + public static create(properties?: google.longrunning.ICancelOperationRequest): google.longrunning.CancelOperationRequest; + + /** + * Encodes the specified CancelOperationRequest message. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages. + * @param message CancelOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CancelOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages. + * @param message CancelOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CancelOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CancelOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.CancelOperationRequest; + + /** + * Decodes a CancelOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CancelOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.CancelOperationRequest; + + /** + * Verifies a CancelOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CancelOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @param message CancelOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CancelOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteOperationRequest. */ + interface IDeleteOperationRequest { + + /** DeleteOperationRequest name */ + name?: (string|null); + } + + /** Represents a DeleteOperationRequest. */ + class DeleteOperationRequest implements IDeleteOperationRequest { + + /** + * Constructs a new DeleteOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IDeleteOperationRequest); + + /** DeleteOperationRequest name. */ + public name: string; + + /** + * Creates a new DeleteOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteOperationRequest instance + */ + public static create(properties?: google.longrunning.IDeleteOperationRequest): google.longrunning.DeleteOperationRequest; + + /** + * Encodes the specified DeleteOperationRequest message. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages. + * @param message DeleteOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages. + * @param message DeleteOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.DeleteOperationRequest; + + /** + * Decodes a DeleteOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.DeleteOperationRequest; + + /** + * Verifies a DeleteOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @param message DeleteOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WaitOperationRequest. */ + interface IWaitOperationRequest { + + /** WaitOperationRequest name */ + name?: (string|null); + + /** WaitOperationRequest timeout */ + timeout?: (google.protobuf.IDuration|null); + } + + /** Represents a WaitOperationRequest. */ + class WaitOperationRequest implements IWaitOperationRequest { + + /** + * Constructs a new WaitOperationRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IWaitOperationRequest); + + /** WaitOperationRequest name. */ + public name: string; + + /** WaitOperationRequest timeout. */ + public timeout?: (google.protobuf.IDuration|null); + + /** + * Creates a new WaitOperationRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns WaitOperationRequest instance + */ + public static create(properties?: google.longrunning.IWaitOperationRequest): google.longrunning.WaitOperationRequest; + + /** + * Encodes the specified WaitOperationRequest message. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages. + * @param message WaitOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WaitOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages. + * @param message WaitOperationRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WaitOperationRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WaitOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.WaitOperationRequest; + + /** + * Decodes a WaitOperationRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WaitOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.WaitOperationRequest; + + /** + * Verifies a WaitOperationRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WaitOperationRequest + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @param message WaitOperationRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WaitOperationRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an OperationInfo. */ + interface IOperationInfo { + + /** OperationInfo responseType */ + responseType?: (string|null); + + /** OperationInfo metadataType */ + metadataType?: (string|null); + } + + /** Represents an OperationInfo. */ + class OperationInfo implements IOperationInfo { + + /** + * Constructs a new OperationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.longrunning.IOperationInfo); + + /** OperationInfo responseType. */ + public responseType: string; + + /** OperationInfo metadataType. */ + public metadataType: string; + + /** + * Creates a new OperationInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns OperationInfo instance + */ + public static create(properties?: google.longrunning.IOperationInfo): google.longrunning.OperationInfo; + + /** + * Encodes the specified OperationInfo message. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages. + * @param message OperationInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified OperationInfo message, length delimited. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages. + * @param message OperationInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an OperationInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns OperationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.OperationInfo; + + /** + * Decodes an OperationInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns OperationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.OperationInfo; + + /** + * Verifies an OperationInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OperationInfo + */ + public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @param message OperationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this OperationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace iam. */ + namespace iam { + + /** Namespace v1. */ + namespace v1 { + + /** Represents a IAMPolicy */ + class IAMPolicy extends $protobuf.rpc.Service { + + /** + * Constructs a new IAMPolicy service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new IAMPolicy service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): IAMPolicy; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest, callback: google.iam.v1.IAMPolicy.SetIamPolicyCallback): void; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRequest message or plain object + * @returns Promise + */ + public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest): Promise; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest, callback: google.iam.v1.IAMPolicy.GetIamPolicyCallback): void; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRequest message or plain object + * @returns Promise + */ + public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest): Promise; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and TestIamPermissionsResponse + */ + public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest, callback: google.iam.v1.IAMPolicy.TestIamPermissionsCallback): void; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRequest message or plain object + * @returns Promise + */ + public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest): Promise; + } + + namespace IAMPolicy { + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy|setIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type SetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy|getIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type GetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy|testIamPermissions}. + * @param error Error, if any + * @param [response] TestIamPermissionsResponse + */ + type TestIamPermissionsCallback = (error: (Error|null), response?: google.iam.v1.TestIamPermissionsResponse) => void; + } + + /** Properties of a SetIamPolicyRequest. */ + interface ISetIamPolicyRequest { + + /** SetIamPolicyRequest resource */ + resource?: (string|null); + + /** SetIamPolicyRequest policy */ + policy?: (google.iam.v1.IPolicy|null); + + /** SetIamPolicyRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents a SetIamPolicyRequest. */ + class SetIamPolicyRequest implements ISetIamPolicyRequest { + + /** + * Constructs a new SetIamPolicyRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.ISetIamPolicyRequest); + + /** SetIamPolicyRequest resource. */ + public resource: string; + + /** SetIamPolicyRequest policy. */ + public policy?: (google.iam.v1.IPolicy|null); + + /** SetIamPolicyRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new SetIamPolicyRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns SetIamPolicyRequest instance + */ + public static create(properties?: google.iam.v1.ISetIamPolicyRequest): google.iam.v1.SetIamPolicyRequest; + + /** + * Encodes the specified SetIamPolicyRequest message. Does not implicitly {@link google.iam.v1.SetIamPolicyRequest.verify|verify} messages. + * @param message SetIamPolicyRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.ISetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SetIamPolicyRequest message, length delimited. Does not implicitly {@link google.iam.v1.SetIamPolicyRequest.verify|verify} messages. + * @param message SetIamPolicyRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.ISetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SetIamPolicyRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.SetIamPolicyRequest; + + /** + * Decodes a SetIamPolicyRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.SetIamPolicyRequest; + + /** + * Verifies a SetIamPolicyRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SetIamPolicyRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SetIamPolicyRequest + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.SetIamPolicyRequest; + + /** + * Creates a plain object from a SetIamPolicyRequest message. Also converts values to other types if specified. + * @param message SetIamPolicyRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.SetIamPolicyRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SetIamPolicyRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SetIamPolicyRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetIamPolicyRequest. */ + interface IGetIamPolicyRequest { + + /** GetIamPolicyRequest resource */ + resource?: (string|null); + + /** GetIamPolicyRequest options */ + options?: (google.iam.v1.IGetPolicyOptions|null); + } + + /** Represents a GetIamPolicyRequest. */ + class GetIamPolicyRequest implements IGetIamPolicyRequest { + + /** + * Constructs a new GetIamPolicyRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IGetIamPolicyRequest); + + /** GetIamPolicyRequest resource. */ + public resource: string; + + /** GetIamPolicyRequest options. */ + public options?: (google.iam.v1.IGetPolicyOptions|null); + + /** + * Creates a new GetIamPolicyRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetIamPolicyRequest instance + */ + public static create(properties?: google.iam.v1.IGetIamPolicyRequest): google.iam.v1.GetIamPolicyRequest; + + /** + * Encodes the specified GetIamPolicyRequest message. Does not implicitly {@link google.iam.v1.GetIamPolicyRequest.verify|verify} messages. + * @param message GetIamPolicyRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IGetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetIamPolicyRequest message, length delimited. Does not implicitly {@link google.iam.v1.GetIamPolicyRequest.verify|verify} messages. + * @param message GetIamPolicyRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IGetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetIamPolicyRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.GetIamPolicyRequest; + + /** + * Decodes a GetIamPolicyRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.GetIamPolicyRequest; + + /** + * Verifies a GetIamPolicyRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetIamPolicyRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIamPolicyRequest + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.GetIamPolicyRequest; + + /** + * Creates a plain object from a GetIamPolicyRequest message. Also converts values to other types if specified. + * @param message GetIamPolicyRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.GetIamPolicyRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIamPolicyRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIamPolicyRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TestIamPermissionsRequest. */ + interface ITestIamPermissionsRequest { + + /** TestIamPermissionsRequest resource */ + resource?: (string|null); + + /** TestIamPermissionsRequest permissions */ + permissions?: (string[]|null); + } + + /** Represents a TestIamPermissionsRequest. */ + class TestIamPermissionsRequest implements ITestIamPermissionsRequest { + + /** + * Constructs a new TestIamPermissionsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.ITestIamPermissionsRequest); + + /** TestIamPermissionsRequest resource. */ + public resource: string; + + /** TestIamPermissionsRequest permissions. */ + public permissions: string[]; + + /** + * Creates a new TestIamPermissionsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns TestIamPermissionsRequest instance + */ + public static create(properties?: google.iam.v1.ITestIamPermissionsRequest): google.iam.v1.TestIamPermissionsRequest; + + /** + * Encodes the specified TestIamPermissionsRequest message. Does not implicitly {@link google.iam.v1.TestIamPermissionsRequest.verify|verify} messages. + * @param message TestIamPermissionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.ITestIamPermissionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TestIamPermissionsRequest message, length delimited. Does not implicitly {@link google.iam.v1.TestIamPermissionsRequest.verify|verify} messages. + * @param message TestIamPermissionsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.ITestIamPermissionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TestIamPermissionsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TestIamPermissionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.TestIamPermissionsRequest; + + /** + * Decodes a TestIamPermissionsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TestIamPermissionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.TestIamPermissionsRequest; + + /** + * Verifies a TestIamPermissionsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TestIamPermissionsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TestIamPermissionsRequest + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.TestIamPermissionsRequest; + + /** + * Creates a plain object from a TestIamPermissionsRequest message. Also converts values to other types if specified. + * @param message TestIamPermissionsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.TestIamPermissionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TestIamPermissionsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TestIamPermissionsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TestIamPermissionsResponse. */ + interface ITestIamPermissionsResponse { + + /** TestIamPermissionsResponse permissions */ + permissions?: (string[]|null); + } + + /** Represents a TestIamPermissionsResponse. */ + class TestIamPermissionsResponse implements ITestIamPermissionsResponse { + + /** + * Constructs a new TestIamPermissionsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.ITestIamPermissionsResponse); + + /** TestIamPermissionsResponse permissions. */ + public permissions: string[]; + + /** + * Creates a new TestIamPermissionsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns TestIamPermissionsResponse instance + */ + public static create(properties?: google.iam.v1.ITestIamPermissionsResponse): google.iam.v1.TestIamPermissionsResponse; + + /** + * Encodes the specified TestIamPermissionsResponse message. Does not implicitly {@link google.iam.v1.TestIamPermissionsResponse.verify|verify} messages. + * @param message TestIamPermissionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.ITestIamPermissionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TestIamPermissionsResponse message, length delimited. Does not implicitly {@link google.iam.v1.TestIamPermissionsResponse.verify|verify} messages. + * @param message TestIamPermissionsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.ITestIamPermissionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TestIamPermissionsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TestIamPermissionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.TestIamPermissionsResponse; + + /** + * Decodes a TestIamPermissionsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TestIamPermissionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.TestIamPermissionsResponse; + + /** + * Verifies a TestIamPermissionsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TestIamPermissionsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TestIamPermissionsResponse + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.TestIamPermissionsResponse; + + /** + * Creates a plain object from a TestIamPermissionsResponse message. Also converts values to other types if specified. + * @param message TestIamPermissionsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.TestIamPermissionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TestIamPermissionsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TestIamPermissionsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetPolicyOptions. */ + interface IGetPolicyOptions { + + /** GetPolicyOptions requestedPolicyVersion */ + requestedPolicyVersion?: (number|null); + } + + /** Represents a GetPolicyOptions. */ + class GetPolicyOptions implements IGetPolicyOptions { + + /** + * Constructs a new GetPolicyOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IGetPolicyOptions); + + /** GetPolicyOptions requestedPolicyVersion. */ + public requestedPolicyVersion: number; + + /** + * Creates a new GetPolicyOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns GetPolicyOptions instance + */ + public static create(properties?: google.iam.v1.IGetPolicyOptions): google.iam.v1.GetPolicyOptions; + + /** + * Encodes the specified GetPolicyOptions message. Does not implicitly {@link google.iam.v1.GetPolicyOptions.verify|verify} messages. + * @param message GetPolicyOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IGetPolicyOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetPolicyOptions message, length delimited. Does not implicitly {@link google.iam.v1.GetPolicyOptions.verify|verify} messages. + * @param message GetPolicyOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IGetPolicyOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetPolicyOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetPolicyOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.GetPolicyOptions; + + /** + * Decodes a GetPolicyOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetPolicyOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.GetPolicyOptions; + + /** + * Verifies a GetPolicyOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetPolicyOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetPolicyOptions + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.GetPolicyOptions; + + /** + * Creates a plain object from a GetPolicyOptions message. Also converts values to other types if specified. + * @param message GetPolicyOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.GetPolicyOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetPolicyOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetPolicyOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Policy. */ + interface IPolicy { + + /** Policy version */ + version?: (number|null); + + /** Policy bindings */ + bindings?: (google.iam.v1.IBinding[]|null); + + /** Policy auditConfigs */ + auditConfigs?: (google.iam.v1.IAuditConfig[]|null); + + /** Policy etag */ + etag?: (Uint8Array|Buffer|string|null); + } + + /** Represents a Policy. */ + class Policy implements IPolicy { + + /** + * Constructs a new Policy. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IPolicy); + + /** Policy version. */ + public version: number; + + /** Policy bindings. */ + public bindings: google.iam.v1.IBinding[]; + + /** Policy auditConfigs. */ + public auditConfigs: google.iam.v1.IAuditConfig[]; + + /** Policy etag. */ + public etag: (Uint8Array|Buffer|string); + + /** + * Creates a new Policy instance using the specified properties. + * @param [properties] Properties to set + * @returns Policy instance + */ + public static create(properties?: google.iam.v1.IPolicy): google.iam.v1.Policy; + + /** + * Encodes the specified Policy message. Does not implicitly {@link google.iam.v1.Policy.verify|verify} messages. + * @param message Policy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IPolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Policy message, length delimited. Does not implicitly {@link google.iam.v1.Policy.verify|verify} messages. + * @param message Policy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IPolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Policy message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Policy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.Policy; + + /** + * Decodes a Policy message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Policy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.Policy; + + /** + * Verifies a Policy message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Policy message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Policy + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.Policy; + + /** + * Creates a plain object from a Policy message. Also converts values to other types if specified. + * @param message Policy + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.Policy, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Policy to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Policy + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Binding. */ + interface IBinding { + + /** Binding role */ + role?: (string|null); + + /** Binding members */ + members?: (string[]|null); + + /** Binding condition */ + condition?: (google.type.IExpr|null); + } + + /** Represents a Binding. */ + class Binding implements IBinding { + + /** + * Constructs a new Binding. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IBinding); + + /** Binding role. */ + public role: string; + + /** Binding members. */ + public members: string[]; + + /** Binding condition. */ + public condition?: (google.type.IExpr|null); + + /** + * Creates a new Binding instance using the specified properties. + * @param [properties] Properties to set + * @returns Binding instance + */ + public static create(properties?: google.iam.v1.IBinding): google.iam.v1.Binding; + + /** + * Encodes the specified Binding message. Does not implicitly {@link google.iam.v1.Binding.verify|verify} messages. + * @param message Binding message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IBinding, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Binding message, length delimited. Does not implicitly {@link google.iam.v1.Binding.verify|verify} messages. + * @param message Binding message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IBinding, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Binding message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Binding + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.Binding; + + /** + * Decodes a Binding message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Binding + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.Binding; + + /** + * Verifies a Binding message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Binding message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Binding + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.Binding; + + /** + * Creates a plain object from a Binding message. Also converts values to other types if specified. + * @param message Binding + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.Binding, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Binding to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Binding + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AuditConfig. */ + interface IAuditConfig { + + /** AuditConfig service */ + service?: (string|null); + + /** AuditConfig auditLogConfigs */ + auditLogConfigs?: (google.iam.v1.IAuditLogConfig[]|null); + } + + /** Represents an AuditConfig. */ + class AuditConfig implements IAuditConfig { + + /** + * Constructs a new AuditConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IAuditConfig); + + /** AuditConfig service. */ + public service: string; + + /** AuditConfig auditLogConfigs. */ + public auditLogConfigs: google.iam.v1.IAuditLogConfig[]; + + /** + * Creates a new AuditConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns AuditConfig instance + */ + public static create(properties?: google.iam.v1.IAuditConfig): google.iam.v1.AuditConfig; + + /** + * Encodes the specified AuditConfig message. Does not implicitly {@link google.iam.v1.AuditConfig.verify|verify} messages. + * @param message AuditConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IAuditConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AuditConfig message, length delimited. Does not implicitly {@link google.iam.v1.AuditConfig.verify|verify} messages. + * @param message AuditConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IAuditConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AuditConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AuditConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.AuditConfig; + + /** + * Decodes an AuditConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AuditConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.AuditConfig; + + /** + * Verifies an AuditConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AuditConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AuditConfig + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.AuditConfig; + + /** + * Creates a plain object from an AuditConfig message. Also converts values to other types if specified. + * @param message AuditConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.AuditConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AuditConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AuditConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AuditLogConfig. */ + interface IAuditLogConfig { + + /** AuditLogConfig logType */ + logType?: (google.iam.v1.AuditLogConfig.LogType|keyof typeof google.iam.v1.AuditLogConfig.LogType|null); + + /** AuditLogConfig exemptedMembers */ + exemptedMembers?: (string[]|null); + } + + /** Represents an AuditLogConfig. */ + class AuditLogConfig implements IAuditLogConfig { + + /** + * Constructs a new AuditLogConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IAuditLogConfig); + + /** AuditLogConfig logType. */ + public logType: (google.iam.v1.AuditLogConfig.LogType|keyof typeof google.iam.v1.AuditLogConfig.LogType); + + /** AuditLogConfig exemptedMembers. */ + public exemptedMembers: string[]; + + /** + * Creates a new AuditLogConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns AuditLogConfig instance + */ + public static create(properties?: google.iam.v1.IAuditLogConfig): google.iam.v1.AuditLogConfig; + + /** + * Encodes the specified AuditLogConfig message. Does not implicitly {@link google.iam.v1.AuditLogConfig.verify|verify} messages. + * @param message AuditLogConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IAuditLogConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AuditLogConfig message, length delimited. Does not implicitly {@link google.iam.v1.AuditLogConfig.verify|verify} messages. + * @param message AuditLogConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IAuditLogConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AuditLogConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AuditLogConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.AuditLogConfig; + + /** + * Decodes an AuditLogConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AuditLogConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.AuditLogConfig; + + /** + * Verifies an AuditLogConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AuditLogConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AuditLogConfig + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.AuditLogConfig; + + /** + * Creates a plain object from an AuditLogConfig message. Also converts values to other types if specified. + * @param message AuditLogConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.AuditLogConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AuditLogConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AuditLogConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace AuditLogConfig { + + /** LogType enum. */ + enum LogType { + LOG_TYPE_UNSPECIFIED = 0, + ADMIN_READ = 1, + DATA_WRITE = 2, + DATA_READ = 3 + } + } + + /** Properties of a PolicyDelta. */ + interface IPolicyDelta { + + /** PolicyDelta bindingDeltas */ + bindingDeltas?: (google.iam.v1.IBindingDelta[]|null); + + /** PolicyDelta auditConfigDeltas */ + auditConfigDeltas?: (google.iam.v1.IAuditConfigDelta[]|null); + } + + /** Represents a PolicyDelta. */ + class PolicyDelta implements IPolicyDelta { + + /** + * Constructs a new PolicyDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IPolicyDelta); + + /** PolicyDelta bindingDeltas. */ + public bindingDeltas: google.iam.v1.IBindingDelta[]; + + /** PolicyDelta auditConfigDeltas. */ + public auditConfigDeltas: google.iam.v1.IAuditConfigDelta[]; + + /** + * Creates a new PolicyDelta instance using the specified properties. + * @param [properties] Properties to set + * @returns PolicyDelta instance + */ + public static create(properties?: google.iam.v1.IPolicyDelta): google.iam.v1.PolicyDelta; + + /** + * Encodes the specified PolicyDelta message. Does not implicitly {@link google.iam.v1.PolicyDelta.verify|verify} messages. + * @param message PolicyDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IPolicyDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PolicyDelta message, length delimited. Does not implicitly {@link google.iam.v1.PolicyDelta.verify|verify} messages. + * @param message PolicyDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IPolicyDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PolicyDelta message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PolicyDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.PolicyDelta; + + /** + * Decodes a PolicyDelta message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PolicyDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.PolicyDelta; + + /** + * Verifies a PolicyDelta message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PolicyDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PolicyDelta + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.PolicyDelta; + + /** + * Creates a plain object from a PolicyDelta message. Also converts values to other types if specified. + * @param message PolicyDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.PolicyDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PolicyDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PolicyDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BindingDelta. */ + interface IBindingDelta { + + /** BindingDelta action */ + action?: (google.iam.v1.BindingDelta.Action|keyof typeof google.iam.v1.BindingDelta.Action|null); + + /** BindingDelta role */ + role?: (string|null); + + /** BindingDelta member */ + member?: (string|null); + + /** BindingDelta condition */ + condition?: (google.type.IExpr|null); + } + + /** Represents a BindingDelta. */ + class BindingDelta implements IBindingDelta { + + /** + * Constructs a new BindingDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IBindingDelta); + + /** BindingDelta action. */ + public action: (google.iam.v1.BindingDelta.Action|keyof typeof google.iam.v1.BindingDelta.Action); + + /** BindingDelta role. */ + public role: string; + + /** BindingDelta member. */ + public member: string; + + /** BindingDelta condition. */ + public condition?: (google.type.IExpr|null); + + /** + * Creates a new BindingDelta instance using the specified properties. + * @param [properties] Properties to set + * @returns BindingDelta instance + */ + public static create(properties?: google.iam.v1.IBindingDelta): google.iam.v1.BindingDelta; + + /** + * Encodes the specified BindingDelta message. Does not implicitly {@link google.iam.v1.BindingDelta.verify|verify} messages. + * @param message BindingDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IBindingDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BindingDelta message, length delimited. Does not implicitly {@link google.iam.v1.BindingDelta.verify|verify} messages. + * @param message BindingDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IBindingDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BindingDelta message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BindingDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.BindingDelta; + + /** + * Decodes a BindingDelta message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BindingDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.BindingDelta; + + /** + * Verifies a BindingDelta message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BindingDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BindingDelta + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.BindingDelta; + + /** + * Creates a plain object from a BindingDelta message. Also converts values to other types if specified. + * @param message BindingDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.BindingDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BindingDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BindingDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace BindingDelta { + + /** Action enum. */ + enum Action { + ACTION_UNSPECIFIED = 0, + ADD = 1, + REMOVE = 2 + } + } + + /** Properties of an AuditConfigDelta. */ + interface IAuditConfigDelta { + + /** AuditConfigDelta action */ + action?: (google.iam.v1.AuditConfigDelta.Action|keyof typeof google.iam.v1.AuditConfigDelta.Action|null); + + /** AuditConfigDelta service */ + service?: (string|null); + + /** AuditConfigDelta exemptedMember */ + exemptedMember?: (string|null); + + /** AuditConfigDelta logType */ + logType?: (string|null); + } + + /** Represents an AuditConfigDelta. */ + class AuditConfigDelta implements IAuditConfigDelta { + + /** + * Constructs a new AuditConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.iam.v1.IAuditConfigDelta); + + /** AuditConfigDelta action. */ + public action: (google.iam.v1.AuditConfigDelta.Action|keyof typeof google.iam.v1.AuditConfigDelta.Action); + + /** AuditConfigDelta service. */ + public service: string; + + /** AuditConfigDelta exemptedMember. */ + public exemptedMember: string; + + /** AuditConfigDelta logType. */ + public logType: string; + + /** + * Creates a new AuditConfigDelta instance using the specified properties. + * @param [properties] Properties to set + * @returns AuditConfigDelta instance + */ + public static create(properties?: google.iam.v1.IAuditConfigDelta): google.iam.v1.AuditConfigDelta; + + /** + * Encodes the specified AuditConfigDelta message. Does not implicitly {@link google.iam.v1.AuditConfigDelta.verify|verify} messages. + * @param message AuditConfigDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.iam.v1.IAuditConfigDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AuditConfigDelta message, length delimited. Does not implicitly {@link google.iam.v1.AuditConfigDelta.verify|verify} messages. + * @param message AuditConfigDelta message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.iam.v1.IAuditConfigDelta, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AuditConfigDelta message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AuditConfigDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.AuditConfigDelta; + + /** + * Decodes an AuditConfigDelta message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AuditConfigDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.AuditConfigDelta; + + /** + * Verifies an AuditConfigDelta message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AuditConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AuditConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.iam.v1.AuditConfigDelta; + + /** + * Creates a plain object from an AuditConfigDelta message. Also converts values to other types if specified. + * @param message AuditConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.iam.v1.AuditConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AuditConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AuditConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace AuditConfigDelta { + + /** Action enum. */ + enum Action { + ACTION_UNSPECIFIED = 0, + ADD = 1, + REMOVE = 2 + } + } + } + } + + /** Namespace type. */ + namespace type { + + /** Properties of an Expr. */ + interface IExpr { + + /** Expr expression */ + expression?: (string|null); + + /** Expr title */ + title?: (string|null); + + /** Expr description */ + description?: (string|null); + + /** Expr location */ + location?: (string|null); + } + + /** Represents an Expr. */ + class Expr implements IExpr { + + /** + * Constructs a new Expr. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.IExpr); + + /** Expr expression. */ + public expression: string; + + /** Expr title. */ + public title: string; + + /** Expr description. */ + public description: string; + + /** Expr location. */ + public location: string; + + /** + * Creates a new Expr instance using the specified properties. + * @param [properties] Properties to set + * @returns Expr instance + */ + public static create(properties?: google.type.IExpr): google.type.Expr; + + /** + * Encodes the specified Expr message. Does not implicitly {@link google.type.Expr.verify|verify} messages. + * @param message Expr message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.type.IExpr, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Expr message, length delimited. Does not implicitly {@link google.type.Expr.verify|verify} messages. + * @param message Expr message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.type.IExpr, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Expr message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Expr + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.type.Expr; + + /** + * Decodes an Expr message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Expr + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.type.Expr; + + /** + * Verifies an Expr message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Expr message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Expr + */ + public static fromObject(object: { [k: string]: any }): google.type.Expr; + + /** + * Creates a plain object from an Expr message. Also converts values to other types if specified. + * @param message Expr + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.Expr, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Expr to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Expr + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } +} diff --git a/handwritten/spanner/protos/protos.js b/handwritten/spanner/protos/protos.js new file mode 100644 index 00000000000..837290eefd8 --- /dev/null +++ b/handwritten/spanner/protos/protos.js @@ -0,0 +1,113691 @@ +// Copyright 2026 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. + +/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ +(function(global, factory) { /* global define, require, module */ + + /* AMD */ if (typeof define === 'function' && define.amd) + define(["protobufjs/minimal"], factory); + + /* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports) + module.exports = factory(require("google-gax/build/src/protobuf").protobufMinimal); + +})(this, function($protobuf) { + "use strict"; + + // Common aliases + var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; + + // Exported root namespace + var $root = $protobuf.roots._google_cloud_spanner_protos || ($protobuf.roots._google_cloud_spanner_protos = {}); + + $root.google = (function() { + + /** + * Namespace google. + * @exports google + * @namespace + */ + var google = {}; + + google.protobuf = (function() { + + /** + * Namespace protobuf. + * @memberof google + * @namespace + */ + var protobuf = {}; + + protobuf.Duration = (function() { + + /** + * Properties of a Duration. + * @memberof google.protobuf + * @interface IDuration + * @property {number|Long|null} [seconds] Duration seconds + * @property {number|null} [nanos] Duration nanos + */ + + /** + * Constructs a new Duration. + * @memberof google.protobuf + * @classdesc Represents a Duration. + * @implements IDuration + * @constructor + * @param {google.protobuf.IDuration=} [properties] Properties to set + */ + function Duration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Duration seconds. + * @member {number|Long} seconds + * @memberof google.protobuf.Duration + * @instance + */ + Duration.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Duration nanos. + * @member {number} nanos + * @memberof google.protobuf.Duration + * @instance + */ + Duration.prototype.nanos = 0; + + /** + * Creates a new Duration instance using the specified properties. + * @function create + * @memberof google.protobuf.Duration + * @static + * @param {google.protobuf.IDuration=} [properties] Properties to set + * @returns {google.protobuf.Duration} Duration instance + */ + Duration.create = function create(properties) { + return new Duration(properties); + }; + + /** + * Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. + * @function encode + * @memberof google.protobuf.Duration + * @static + * @param {google.protobuf.IDuration} message Duration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Duration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.seconds != null && Object.hasOwnProperty.call(message, "seconds")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.seconds); + if (message.nanos != null && Object.hasOwnProperty.call(message, "nanos")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.nanos); + return writer; + }; + + /** + * Encodes the specified Duration message, length delimited. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.Duration + * @static + * @param {google.protobuf.IDuration} message Duration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Duration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Duration message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.Duration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.Duration} Duration + * @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, 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(); + break; + } + case 2: { + message.nanos = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Duration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.Duration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.Duration} Duration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Duration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Duration message. + * @function verify + * @memberof google.protobuf.Duration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Duration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (!$util.isInteger(message.seconds) && !(message.seconds && $util.isInteger(message.seconds.low) && $util.isInteger(message.seconds.high))) + return "seconds: integer|Long expected"; + if (message.nanos != null && message.hasOwnProperty("nanos")) + if (!$util.isInteger(message.nanos)) + return "nanos: integer expected"; + return null; + }; + + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Duration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Duration} Duration + */ + Duration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Duration) + return object; + var message = new $root.google.protobuf.Duration(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Duration + * @static + * @param {google.protobuf.Duration} message Duration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Duration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Duration to JSON. + * @function toJSON + * @memberof google.protobuf.Duration + * @instance + * @returns {Object.} JSON object + */ + Duration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Duration + * @function getTypeUrl + * @memberof google.protobuf.Duration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Duration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Duration"; + }; + + return Duration; + })(); + + protobuf.FileDescriptorSet = (function() { + + /** + * Properties of a FileDescriptorSet. + * @memberof google.protobuf + * @interface IFileDescriptorSet + * @property {Array.|null} [file] FileDescriptorSet file + */ + + /** + * Constructs a new FileDescriptorSet. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorSet. + * @implements IFileDescriptorSet + * @constructor + * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set + */ + function FileDescriptorSet(properties) { + this.file = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileDescriptorSet file. + * @member {Array.} file + * @memberof google.protobuf.FileDescriptorSet + * @instance + */ + FileDescriptorSet.prototype.file = $util.emptyArray; + + /** + * Creates a new FileDescriptorSet instance using the specified properties. + * @function create + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set + * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet instance + */ + FileDescriptorSet.create = function create(properties) { + return new FileDescriptorSet(properties); + }; + + /** + * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {google.protobuf.IFileDescriptorSet} message FileDescriptorSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FileDescriptorSet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.file != null && message.file.length) + for (var i = 0; i < message.file.length; ++i) + $root.google.protobuf.FileDescriptorProto.encode(message.file[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {google.protobuf.IFileDescriptorSet} message FileDescriptorSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FileDescriptorSet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet + * @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, 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)) + message.file = []; + message.file.push($root.google.protobuf.FileDescriptorProto.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FileDescriptorSet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FileDescriptorSet message. + * @function verify + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FileDescriptorSet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.file != null && message.hasOwnProperty("file")) { + if (!Array.isArray(message.file)) + return "file: array expected"; + for (var i = 0; i < message.file.length; ++i) { + var error = $root.google.protobuf.FileDescriptorProto.verify(message.file[i]); + if (error) + return "file." + error; + } + } + return null; + }; + + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet + */ + FileDescriptorSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorSet) + return object; + var message = new $root.google.protobuf.FileDescriptorSet(); + if (object.file) { + if (!Array.isArray(object.file)) + throw TypeError(".google.protobuf.FileDescriptorSet.file: array expected"); + message.file = []; + for (var i = 0; i < object.file.length; ++i) { + if (typeof object.file[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorSet.file: object expected"); + message.file[i] = $root.google.protobuf.FileDescriptorProto.fromObject(object.file[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {google.protobuf.FileDescriptorSet} message FileDescriptorSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.file = []; + if (message.file && message.file.length) { + object.file = []; + for (var j = 0; j < message.file.length; ++j) + object.file[j] = $root.google.protobuf.FileDescriptorProto.toObject(message.file[j], options); + } + return object; + }; + + /** + * Converts this FileDescriptorSet to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorSet + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileDescriptorSet + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorSet"; + }; + + return FileDescriptorSet; + })(); + + /** + * Edition enum. + * @name google.protobuf.Edition + * @enum {number} + * @property {number} EDITION_UNKNOWN=0 EDITION_UNKNOWN value + * @property {number} EDITION_LEGACY=900 EDITION_LEGACY value + * @property {number} EDITION_PROTO2=998 EDITION_PROTO2 value + * @property {number} EDITION_PROTO3=999 EDITION_PROTO3 value + * @property {number} EDITION_2023=1000 EDITION_2023 value + * @property {number} EDITION_2024=1001 EDITION_2024 value + * @property {number} EDITION_1_TEST_ONLY=1 EDITION_1_TEST_ONLY value + * @property {number} EDITION_2_TEST_ONLY=2 EDITION_2_TEST_ONLY value + * @property {number} EDITION_99997_TEST_ONLY=99997 EDITION_99997_TEST_ONLY value + * @property {number} EDITION_99998_TEST_ONLY=99998 EDITION_99998_TEST_ONLY value + * @property {number} EDITION_99999_TEST_ONLY=99999 EDITION_99999_TEST_ONLY value + * @property {number} EDITION_MAX=2147483647 EDITION_MAX value + */ + protobuf.Edition = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "EDITION_UNKNOWN"] = 0; + values[valuesById[900] = "EDITION_LEGACY"] = 900; + values[valuesById[998] = "EDITION_PROTO2"] = 998; + values[valuesById[999] = "EDITION_PROTO3"] = 999; + values[valuesById[1000] = "EDITION_2023"] = 1000; + values[valuesById[1001] = "EDITION_2024"] = 1001; + values[valuesById[1] = "EDITION_1_TEST_ONLY"] = 1; + values[valuesById[2] = "EDITION_2_TEST_ONLY"] = 2; + values[valuesById[99997] = "EDITION_99997_TEST_ONLY"] = 99997; + values[valuesById[99998] = "EDITION_99998_TEST_ONLY"] = 99998; + values[valuesById[99999] = "EDITION_99999_TEST_ONLY"] = 99999; + values[valuesById[2147483647] = "EDITION_MAX"] = 2147483647; + return values; + })(); + + protobuf.FileDescriptorProto = (function() { + + /** + * Properties of a FileDescriptorProto. + * @memberof google.protobuf + * @interface IFileDescriptorProto + * @property {string|null} [name] FileDescriptorProto name + * @property {string|null} ["package"] FileDescriptorProto package + * @property {Array.|null} [dependency] FileDescriptorProto dependency + * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency + * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [optionDependency] FileDescriptorProto optionDependency + * @property {Array.|null} [messageType] FileDescriptorProto messageType + * @property {Array.|null} [enumType] FileDescriptorProto enumType + * @property {Array.|null} [service] FileDescriptorProto service + * @property {Array.|null} [extension] FileDescriptorProto extension + * @property {google.protobuf.IFileOptions|null} [options] FileDescriptorProto options + * @property {google.protobuf.ISourceCodeInfo|null} [sourceCodeInfo] FileDescriptorProto sourceCodeInfo + * @property {string|null} [syntax] FileDescriptorProto syntax + * @property {google.protobuf.Edition|null} [edition] FileDescriptorProto edition + */ + + /** + * Constructs a new FileDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorProto. + * @implements IFileDescriptorProto + * @constructor + * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set + */ + function FileDescriptorProto(properties) { + this.dependency = []; + this.publicDependency = []; + this.weakDependency = []; + this.optionDependency = []; + this.messageType = []; + this.enumType = []; + this.service = []; + this.extension = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.name = ""; + + /** + * FileDescriptorProto package. + * @member {string} package + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype["package"] = ""; + + /** + * FileDescriptorProto dependency. + * @member {Array.} dependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.dependency = $util.emptyArray; + + /** + * FileDescriptorProto publicDependency. + * @member {Array.} publicDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.publicDependency = $util.emptyArray; + + /** + * FileDescriptorProto weakDependency. + * @member {Array.} weakDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + + /** + * FileDescriptorProto optionDependency. + * @member {Array.} optionDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.optionDependency = $util.emptyArray; + + /** + * FileDescriptorProto messageType. + * @member {Array.} messageType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.messageType = $util.emptyArray; + + /** + * FileDescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.enumType = $util.emptyArray; + + /** + * FileDescriptorProto service. + * @member {Array.} service + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.service = $util.emptyArray; + + /** + * FileDescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.extension = $util.emptyArray; + + /** + * FileDescriptorProto options. + * @member {google.protobuf.IFileOptions|null|undefined} options + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.options = null; + + /** + * FileDescriptorProto sourceCodeInfo. + * @member {google.protobuf.ISourceCodeInfo|null|undefined} sourceCodeInfo + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.sourceCodeInfo = null; + + /** + * FileDescriptorProto syntax. + * @member {string} syntax + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.syntax = ""; + + /** + * FileDescriptorProto edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.edition = 0; + + /** + * Creates a new FileDescriptorProto instance using the specified properties. + * @function create + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set + * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto instance + */ + FileDescriptorProto.create = function create(properties) { + return new FileDescriptorProto(properties); + }; + + /** + * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {google.protobuf.IFileDescriptorProto} message FileDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FileDescriptorProto.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message["package"] != null && Object.hasOwnProperty.call(message, "package")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message["package"]); + if (message.dependency != null && message.dependency.length) + for (var i = 0; i < message.dependency.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.dependency[i]); + if (message.messageType != null && message.messageType.length) + for (var i = 0; i < message.messageType.length; ++i) + $root.google.protobuf.DescriptorProto.encode(message.messageType[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.enumType != null && message.enumType.length) + for (var i = 0; i < message.enumType.length; ++i) + $root.google.protobuf.EnumDescriptorProto.encode(message.enumType[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.service != null && message.service.length) + for (var i = 0; i < message.service.length; ++i) + $root.google.protobuf.ServiceDescriptorProto.encode(message.service[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.extension != null && message.extension.length) + for (var i = 0; i < message.extension.length; ++i) + $root.google.protobuf.FieldDescriptorProto.encode(message.extension[i], writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.FileOptions.encode(message.options, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.sourceCodeInfo != null && Object.hasOwnProperty.call(message, "sourceCodeInfo")) + $root.google.protobuf.SourceCodeInfo.encode(message.sourceCodeInfo, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + if (message.publicDependency != null && message.publicDependency.length) + for (var i = 0; i < message.publicDependency.length; ++i) + writer.uint32(/* id 10, wireType 0 =*/80).int32(message.publicDependency[i]); + if (message.weakDependency != null && message.weakDependency.length) + for (var i = 0; i < message.weakDependency.length; ++i) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.weakDependency[i]); + if (message.syntax != null && Object.hasOwnProperty.call(message, "syntax")) + writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); + if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) + writer.uint32(/* id 14, wireType 0 =*/112).int32(message.edition); + if (message.optionDependency != null && message.optionDependency.length) + for (var i = 0; i < message.optionDependency.length; ++i) + writer.uint32(/* id 15, wireType 2 =*/122).string(message.optionDependency[i]); + return writer; + }; + + /** + * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {google.protobuf.IFileDescriptorProto} message FileDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FileDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto + * @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, 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(); + break; + } + case 2: { + message["package"] = reader.string(); + break; + } + case 3: { + if (!(message.dependency && message.dependency.length)) + message.dependency = []; + message.dependency.push(reader.string()); + break; + } + case 10: { + if (!(message.publicDependency && message.publicDependency.length)) + message.publicDependency = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.publicDependency.push(reader.int32()); + } else + message.publicDependency.push(reader.int32()); + break; + } + case 11: { + if (!(message.weakDependency && message.weakDependency.length)) + message.weakDependency = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.weakDependency.push(reader.int32()); + } else + message.weakDependency.push(reader.int32()); + break; + } + case 15: { + if (!(message.optionDependency && message.optionDependency.length)) + message.optionDependency = []; + message.optionDependency.push(reader.string()); + break; + } + case 4: { + if (!(message.messageType && message.messageType.length)) + message.messageType = []; + message.messageType.push($root.google.protobuf.DescriptorProto.decode(reader, reader.uint32())); + break; + } + case 5: { + if (!(message.enumType && message.enumType.length)) + message.enumType = []; + message.enumType.push($root.google.protobuf.EnumDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 6: { + if (!(message.service && message.service.length)) + message.service = []; + message.service.push($root.google.protobuf.ServiceDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 7: { + if (!(message.extension && message.extension.length)) + message.extension = []; + message.extension.push($root.google.protobuf.FieldDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 8: { + message.options = $root.google.protobuf.FileOptions.decode(reader, reader.uint32()); + break; + } + case 9: { + message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.decode(reader, reader.uint32()); + break; + } + case 12: { + message.syntax = reader.string(); + break; + } + case 14: { + message.edition = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FileDescriptorProto.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FileDescriptorProto message. + * @function verify + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FileDescriptorProto.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message["package"] != null && message.hasOwnProperty("package")) + if (!$util.isString(message["package"])) + return "package: string expected"; + if (message.dependency != null && message.hasOwnProperty("dependency")) { + if (!Array.isArray(message.dependency)) + return "dependency: array expected"; + for (var i = 0; i < message.dependency.length; ++i) + if (!$util.isString(message.dependency[i])) + return "dependency: string[] expected"; + } + if (message.publicDependency != null && message.hasOwnProperty("publicDependency")) { + if (!Array.isArray(message.publicDependency)) + return "publicDependency: array expected"; + for (var i = 0; i < message.publicDependency.length; ++i) + if (!$util.isInteger(message.publicDependency[i])) + return "publicDependency: integer[] expected"; + } + if (message.weakDependency != null && message.hasOwnProperty("weakDependency")) { + if (!Array.isArray(message.weakDependency)) + return "weakDependency: array expected"; + for (var i = 0; i < message.weakDependency.length; ++i) + if (!$util.isInteger(message.weakDependency[i])) + return "weakDependency: integer[] expected"; + } + if (message.optionDependency != null && message.hasOwnProperty("optionDependency")) { + if (!Array.isArray(message.optionDependency)) + return "optionDependency: array expected"; + for (var i = 0; i < message.optionDependency.length; ++i) + if (!$util.isString(message.optionDependency[i])) + return "optionDependency: string[] expected"; + } + if (message.messageType != null && message.hasOwnProperty("messageType")) { + if (!Array.isArray(message.messageType)) + return "messageType: array expected"; + for (var i = 0; i < message.messageType.length; ++i) { + var error = $root.google.protobuf.DescriptorProto.verify(message.messageType[i]); + if (error) + return "messageType." + error; + } + } + if (message.enumType != null && message.hasOwnProperty("enumType")) { + if (!Array.isArray(message.enumType)) + return "enumType: array expected"; + for (var i = 0; i < message.enumType.length; ++i) { + var error = $root.google.protobuf.EnumDescriptorProto.verify(message.enumType[i]); + if (error) + return "enumType." + error; + } + } + if (message.service != null && message.hasOwnProperty("service")) { + if (!Array.isArray(message.service)) + return "service: array expected"; + for (var i = 0; i < message.service.length; ++i) { + var error = $root.google.protobuf.ServiceDescriptorProto.verify(message.service[i]); + if (error) + return "service." + error; + } + } + if (message.extension != null && message.hasOwnProperty("extension")) { + if (!Array.isArray(message.extension)) + return "extension: array expected"; + for (var i = 0; i < message.extension.length; ++i) { + var error = $root.google.protobuf.FieldDescriptorProto.verify(message.extension[i]); + if (error) + return "extension." + error; + } + } + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.FileOptions.verify(message.options); + if (error) + return "options." + error; + } + if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) { + var error = $root.google.protobuf.SourceCodeInfo.verify(message.sourceCodeInfo); + if (error) + return "sourceCodeInfo." + error; + } + if (message.syntax != null && message.hasOwnProperty("syntax")) + if (!$util.isString(message.syntax)) + return "syntax: string expected"; + if (message.edition != null && message.hasOwnProperty("edition")) + switch (message.edition) { + default: + return "edition: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto + */ + FileDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorProto) + return object; + var message = new $root.google.protobuf.FileDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object["package"] != null) + message["package"] = String(object["package"]); + if (object.dependency) { + if (!Array.isArray(object.dependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.dependency: array expected"); + message.dependency = []; + for (var i = 0; i < object.dependency.length; ++i) + message.dependency[i] = String(object.dependency[i]); + } + if (object.publicDependency) { + if (!Array.isArray(object.publicDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.publicDependency: array expected"); + message.publicDependency = []; + for (var i = 0; i < object.publicDependency.length; ++i) + message.publicDependency[i] = object.publicDependency[i] | 0; + } + if (object.weakDependency) { + if (!Array.isArray(object.weakDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.weakDependency: array expected"); + message.weakDependency = []; + for (var i = 0; i < object.weakDependency.length; ++i) + message.weakDependency[i] = object.weakDependency[i] | 0; + } + if (object.optionDependency) { + if (!Array.isArray(object.optionDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.optionDependency: array expected"); + message.optionDependency = []; + for (var i = 0; i < object.optionDependency.length; ++i) + message.optionDependency[i] = String(object.optionDependency[i]); + } + if (object.messageType) { + if (!Array.isArray(object.messageType)) + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); + message.messageType = []; + for (var i = 0; i < object.messageType.length; ++i) { + if (typeof object.messageType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: object expected"); + message.messageType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.messageType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.service) { + if (!Array.isArray(object.service)) + throw TypeError(".google.protobuf.FileDescriptorProto.service: array expected"); + message.service = []; + for (var i = 0; i < object.service.length; ++i) { + if (typeof object.service[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.service: object expected"); + message.service[i] = $root.google.protobuf.ServiceDescriptorProto.fromObject(object.service[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.FileDescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FileOptions.fromObject(object.options); + } + if (object.sourceCodeInfo != null) { + if (typeof object.sourceCodeInfo !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.sourceCodeInfo: object expected"); + message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.fromObject(object.sourceCodeInfo); + } + if (object.syntax != null) + message.syntax = String(object.syntax); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {google.protobuf.FileDescriptorProto} message FileDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.dependency = []; + object.messageType = []; + object.enumType = []; + object.service = []; + object.extension = []; + object.publicDependency = []; + object.weakDependency = []; + object.optionDependency = []; + } + if (options.defaults) { + object.name = ""; + object["package"] = ""; + object.options = null; + object.sourceCodeInfo = null; + object.syntax = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message["package"] != null && message.hasOwnProperty("package")) + object["package"] = message["package"]; + if (message.dependency && message.dependency.length) { + object.dependency = []; + for (var j = 0; j < message.dependency.length; ++j) + object.dependency[j] = message.dependency[j]; + } + if (message.messageType && message.messageType.length) { + object.messageType = []; + for (var j = 0; j < message.messageType.length; ++j) + object.messageType[j] = $root.google.protobuf.DescriptorProto.toObject(message.messageType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.service && message.service.length) { + object.service = []; + for (var j = 0; j < message.service.length; ++j) + object.service[j] = $root.google.protobuf.ServiceDescriptorProto.toObject(message.service[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FileOptions.toObject(message.options, options); + if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) + object.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.toObject(message.sourceCodeInfo, options); + if (message.publicDependency && message.publicDependency.length) { + object.publicDependency = []; + for (var j = 0; j < message.publicDependency.length; ++j) + object.publicDependency[j] = message.publicDependency[j]; + } + if (message.weakDependency && message.weakDependency.length) { + object.weakDependency = []; + for (var j = 0; j < message.weakDependency.length; ++j) + object.weakDependency[j] = message.weakDependency[j]; + } + if (message.syntax != null && message.hasOwnProperty("syntax")) + object.syntax = message.syntax; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + if (message.optionDependency && message.optionDependency.length) { + object.optionDependency = []; + for (var j = 0; j < message.optionDependency.length; ++j) + object.optionDependency[j] = message.optionDependency[j]; + } + return object; + }; + + /** + * Converts this FileDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorProto"; + }; + + return FileDescriptorProto; + })(); + + protobuf.DescriptorProto = (function() { + + /** + * Properties of a DescriptorProto. + * @memberof google.protobuf + * @interface IDescriptorProto + * @property {string|null} [name] DescriptorProto name + * @property {Array.|null} [field] DescriptorProto field + * @property {Array.|null} [extension] DescriptorProto extension + * @property {Array.|null} [nestedType] DescriptorProto nestedType + * @property {Array.|null} [enumType] DescriptorProto enumType + * @property {Array.|null} [extensionRange] DescriptorProto extensionRange + * @property {Array.|null} [oneofDecl] DescriptorProto oneofDecl + * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options + * @property {Array.|null} [reservedRange] DescriptorProto reservedRange + * @property {Array.|null} [reservedName] DescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] DescriptorProto visibility + */ + + /** + * Constructs a new DescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a DescriptorProto. + * @implements IDescriptorProto + * @constructor + * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set + */ + function DescriptorProto(properties) { + this.field = []; + this.extension = []; + this.nestedType = []; + this.enumType = []; + this.extensionRange = []; + this.oneofDecl = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DescriptorProto name. + * @member {string} name + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.name = ""; + + /** + * DescriptorProto field. + * @member {Array.} field + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.field = $util.emptyArray; + + /** + * DescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extension = $util.emptyArray; + + /** + * DescriptorProto nestedType. + * @member {Array.} nestedType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.nestedType = $util.emptyArray; + + /** + * DescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.enumType = $util.emptyArray; + + /** + * DescriptorProto extensionRange. + * @member {Array.} extensionRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extensionRange = $util.emptyArray; + + /** + * DescriptorProto oneofDecl. + * @member {Array.} oneofDecl + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.oneofDecl = $util.emptyArray; + + /** + * DescriptorProto options. + * @member {google.protobuf.IMessageOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.options = null; + + /** + * DescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedRange = $util.emptyArray; + + /** + * DescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * DescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.visibility = 0; + + /** + * Creates a new DescriptorProto instance using the specified properties. + * @function create + * @memberof google.protobuf.DescriptorProto + * @static + * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set + * @returns {google.protobuf.DescriptorProto} DescriptorProto instance + */ + DescriptorProto.create = function create(properties) { + return new DescriptorProto(properties); + }; + + /** + * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @function encode + * @memberof google.protobuf.DescriptorProto + * @static + * @param {google.protobuf.IDescriptorProto} message DescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DescriptorProto.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.field != null && message.field.length) + for (var i = 0; i < message.field.length; ++i) + $root.google.protobuf.FieldDescriptorProto.encode(message.field[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.nestedType != null && message.nestedType.length) + for (var i = 0; i < message.nestedType.length; ++i) + $root.google.protobuf.DescriptorProto.encode(message.nestedType[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.enumType != null && message.enumType.length) + for (var i = 0; i < message.enumType.length; ++i) + $root.google.protobuf.EnumDescriptorProto.encode(message.enumType[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.extensionRange != null && message.extensionRange.length) + for (var i = 0; i < message.extensionRange.length; ++i) + $root.google.protobuf.DescriptorProto.ExtensionRange.encode(message.extensionRange[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.extension != null && message.extension.length) + for (var i = 0; i < message.extension.length; ++i) + $root.google.protobuf.FieldDescriptorProto.encode(message.extension[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.MessageOptions.encode(message.options, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.oneofDecl != null && message.oneofDecl.length) + for (var i = 0; i < message.oneofDecl.length; ++i) + $root.google.protobuf.OneofDescriptorProto.encode(message.oneofDecl[i], writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.reservedRange != null && message.reservedRange.length) + for (var i = 0; i < message.reservedRange.length; ++i) + $root.google.protobuf.DescriptorProto.ReservedRange.encode(message.reservedRange[i], writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + if (message.reservedName != null && message.reservedName.length) + for (var i = 0; i < message.reservedName.length; ++i) + writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.visibility); + return writer; + }; + + /** + * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.DescriptorProto + * @static + * @param {google.protobuf.IDescriptorProto} message DescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.DescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.DescriptorProto} DescriptorProto + * @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, 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(); + break; + } + case 2: { + if (!(message.field && message.field.length)) + message.field = []; + message.field.push($root.google.protobuf.FieldDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 6: { + if (!(message.extension && message.extension.length)) + message.extension = []; + message.extension.push($root.google.protobuf.FieldDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 3: { + if (!(message.nestedType && message.nestedType.length)) + message.nestedType = []; + message.nestedType.push($root.google.protobuf.DescriptorProto.decode(reader, reader.uint32())); + break; + } + case 4: { + if (!(message.enumType && message.enumType.length)) + message.enumType = []; + message.enumType.push($root.google.protobuf.EnumDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 5: { + if (!(message.extensionRange && message.extensionRange.length)) + message.extensionRange = []; + message.extensionRange.push($root.google.protobuf.DescriptorProto.ExtensionRange.decode(reader, reader.uint32())); + break; + } + case 8: { + if (!(message.oneofDecl && message.oneofDecl.length)) + message.oneofDecl = []; + message.oneofDecl.push($root.google.protobuf.OneofDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 7: { + message.options = $root.google.protobuf.MessageOptions.decode(reader, reader.uint32()); + break; + } + case 9: { + if (!(message.reservedRange && message.reservedRange.length)) + message.reservedRange = []; + message.reservedRange.push($root.google.protobuf.DescriptorProto.ReservedRange.decode(reader, reader.uint32())); + break; + } + case 10: { + if (!(message.reservedName && message.reservedName.length)) + message.reservedName = []; + message.reservedName.push(reader.string()); + break; + } + case 11: { + message.visibility = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.DescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.DescriptorProto} DescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DescriptorProto.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DescriptorProto message. + * @function verify + * @memberof google.protobuf.DescriptorProto + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DescriptorProto.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.field != null && message.hasOwnProperty("field")) { + if (!Array.isArray(message.field)) + return "field: array expected"; + for (var i = 0; i < message.field.length; ++i) { + var error = $root.google.protobuf.FieldDescriptorProto.verify(message.field[i]); + if (error) + return "field." + error; + } + } + if (message.extension != null && message.hasOwnProperty("extension")) { + if (!Array.isArray(message.extension)) + return "extension: array expected"; + for (var i = 0; i < message.extension.length; ++i) { + var error = $root.google.protobuf.FieldDescriptorProto.verify(message.extension[i]); + if (error) + return "extension." + error; + } + } + if (message.nestedType != null && message.hasOwnProperty("nestedType")) { + if (!Array.isArray(message.nestedType)) + return "nestedType: array expected"; + for (var i = 0; i < message.nestedType.length; ++i) { + var error = $root.google.protobuf.DescriptorProto.verify(message.nestedType[i]); + if (error) + return "nestedType." + error; + } + } + if (message.enumType != null && message.hasOwnProperty("enumType")) { + if (!Array.isArray(message.enumType)) + return "enumType: array expected"; + for (var i = 0; i < message.enumType.length; ++i) { + var error = $root.google.protobuf.EnumDescriptorProto.verify(message.enumType[i]); + if (error) + return "enumType." + error; + } + } + if (message.extensionRange != null && message.hasOwnProperty("extensionRange")) { + if (!Array.isArray(message.extensionRange)) + return "extensionRange: array expected"; + for (var i = 0; i < message.extensionRange.length; ++i) { + var error = $root.google.protobuf.DescriptorProto.ExtensionRange.verify(message.extensionRange[i]); + if (error) + return "extensionRange." + error; + } + } + if (message.oneofDecl != null && message.hasOwnProperty("oneofDecl")) { + if (!Array.isArray(message.oneofDecl)) + return "oneofDecl: array expected"; + for (var i = 0; i < message.oneofDecl.length; ++i) { + var error = $root.google.protobuf.OneofDescriptorProto.verify(message.oneofDecl[i]); + if (error) + return "oneofDecl." + error; + } + } + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.MessageOptions.verify(message.options); + if (error) + return "options." + error; + } + if (message.reservedRange != null && message.hasOwnProperty("reservedRange")) { + if (!Array.isArray(message.reservedRange)) + return "reservedRange: array expected"; + for (var i = 0; i < message.reservedRange.length; ++i) { + var error = $root.google.protobuf.DescriptorProto.ReservedRange.verify(message.reservedRange[i]); + if (error) + return "reservedRange." + error; + } + } + if (message.reservedName != null && message.hasOwnProperty("reservedName")) { + if (!Array.isArray(message.reservedName)) + return "reservedName: array expected"; + for (var i = 0; i < message.reservedName.length; ++i) + if (!$util.isString(message.reservedName[i])) + return "reservedName: string[] expected"; + } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto} DescriptorProto + */ + DescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto) + return object; + var message = new $root.google.protobuf.DescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.field) { + if (!Array.isArray(object.field)) + throw TypeError(".google.protobuf.DescriptorProto.field: array expected"); + message.field = []; + for (var i = 0; i < object.field.length; ++i) { + if (typeof object.field[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.field: object expected"); + message.field[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.field[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.DescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.nestedType) { + if (!Array.isArray(object.nestedType)) + throw TypeError(".google.protobuf.DescriptorProto.nestedType: array expected"); + message.nestedType = []; + for (var i = 0; i < object.nestedType.length; ++i) { + if (typeof object.nestedType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.nestedType: object expected"); + message.nestedType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.nestedType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.DescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.extensionRange) { + if (!Array.isArray(object.extensionRange)) + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: array expected"); + message.extensionRange = []; + for (var i = 0; i < object.extensionRange.length; ++i) { + if (typeof object.extensionRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: object expected"); + message.extensionRange[i] = $root.google.protobuf.DescriptorProto.ExtensionRange.fromObject(object.extensionRange[i]); + } + } + if (object.oneofDecl) { + if (!Array.isArray(object.oneofDecl)) + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: array expected"); + message.oneofDecl = []; + for (var i = 0; i < object.oneofDecl.length; ++i) { + if (typeof object.oneofDecl[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: object expected"); + message.oneofDecl[i] = $root.google.protobuf.OneofDescriptorProto.fromObject(object.oneofDecl[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MessageOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.DescriptorProto.ReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.DescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {google.protobuf.DescriptorProto} message DescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.field = []; + object.nestedType = []; + object.enumType = []; + object.extensionRange = []; + object.extension = []; + object.oneofDecl = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.field && message.field.length) { + object.field = []; + for (var j = 0; j < message.field.length; ++j) + object.field[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.field[j], options); + } + if (message.nestedType && message.nestedType.length) { + object.nestedType = []; + for (var j = 0; j < message.nestedType.length; ++j) + object.nestedType[j] = $root.google.protobuf.DescriptorProto.toObject(message.nestedType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.extensionRange && message.extensionRange.length) { + object.extensionRange = []; + for (var j = 0; j < message.extensionRange.length; ++j) + object.extensionRange[j] = $root.google.protobuf.DescriptorProto.ExtensionRange.toObject(message.extensionRange[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MessageOptions.toObject(message.options, options); + if (message.oneofDecl && message.oneofDecl.length) { + object.oneofDecl = []; + for (var j = 0; j < message.oneofDecl.length; ++j) + object.oneofDecl[j] = $root.google.protobuf.OneofDescriptorProto.toObject(message.oneofDecl[j], options); + } + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.DescriptorProto.ReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; + return object; + }; + + /** + * Converts this DescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto + * @instance + * @returns {Object.} JSON object + */ + DescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto"; + }; + + DescriptorProto.ExtensionRange = (function() { + + /** + * Properties of an ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @interface IExtensionRange + * @property {number|null} [start] ExtensionRange start + * @property {number|null} [end] ExtensionRange end + * @property {google.protobuf.IExtensionRangeOptions|null} [options] ExtensionRange options + */ + + /** + * Constructs a new ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents an ExtensionRange. + * @implements IExtensionRange + * @constructor + * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set + */ + function ExtensionRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExtensionRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.start = 0; + + /** + * ExtensionRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.end = 0; + + /** + * ExtensionRange options. + * @member {google.protobuf.IExtensionRangeOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + */ + ExtensionRange.prototype.options = null; + + /** + * Creates a new ExtensionRange instance using the specified properties. + * @function create + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set + * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange instance + */ + ExtensionRange.create = function create(properties) { + return new ExtensionRange(properties); + }; + + /** + * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @function encode + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {google.protobuf.DescriptorProto.IExtensionRange} message ExtensionRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExtensionRange.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.start != null && Object.hasOwnProperty.call(message, "start")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.start); + if (message.end != null && Object.hasOwnProperty.call(message, "end")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.end); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.ExtensionRangeOptions.encode(message.options, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {google.protobuf.DescriptorProto.IExtensionRange} message ExtensionRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExtensionRange.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange + * @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, 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(); + break; + } + case 2: { + message.end = reader.int32(); + break; + } + case 3: { + message.options = $root.google.protobuf.ExtensionRangeOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExtensionRange.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExtensionRange message. + * @function verify + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExtensionRange.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.start != null && message.hasOwnProperty("start")) + if (!$util.isInteger(message.start)) + return "start: integer expected"; + if (message.end != null && message.hasOwnProperty("end")) + if (!$util.isInteger(message.end)) + return "end: integer expected"; + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.ExtensionRangeOptions.verify(message.options); + if (error) + return "options." + error; + } + return null; + }; + + /** + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange + */ + ExtensionRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ExtensionRange) + return object; + var message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected"); + message.options = $root.google.protobuf.ExtensionRangeOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {google.protobuf.DescriptorProto.ExtensionRange} message ExtensionRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + object.options = null; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ExtensionRangeOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this ExtensionRange to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @instance + * @returns {Object.} JSON object + */ + ExtensionRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExtensionRange + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ExtensionRange"; + }; + + return ExtensionRange; + })(); + + DescriptorProto.ReservedRange = (function() { + + /** + * Properties of a ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @interface IReservedRange + * @property {number|null} [start] ReservedRange start + * @property {number|null} [end] ReservedRange end + */ + + /** + * Constructs a new ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents a ReservedRange. + * @implements IReservedRange + * @constructor + * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set + */ + function ReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservedRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + */ + ReservedRange.prototype.start = 0; + + /** + * ReservedRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + */ + ReservedRange.prototype.end = 0; + + /** + * Creates a new ReservedRange instance using the specified properties. + * @function create + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set + * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange instance + */ + ReservedRange.create = function create(properties) { + return new ReservedRange(properties); + }; + + /** + * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @function encode + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {google.protobuf.DescriptorProto.IReservedRange} message ReservedRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservedRange.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.start != null && Object.hasOwnProperty.call(message, "start")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.start); + if (message.end != null && Object.hasOwnProperty.call(message, "end")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.end); + return writer; + }; + + /** + * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {google.protobuf.DescriptorProto.IReservedRange} message ReservedRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservedRange.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReservedRange message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange + * @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, 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(); + break; + } + case 2: { + message.end = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReservedRange message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservedRange.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReservedRange message. + * @function verify + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReservedRange.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.start != null && message.hasOwnProperty("start")) + if (!$util.isInteger(message.start)) + return "start: integer expected"; + if (message.end != null && message.hasOwnProperty("end")) + if (!$util.isInteger(message.end)) + return "end: integer expected"; + return null; + }; + + /** + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange + */ + ReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ReservedRange) + return object; + var message = new $root.google.protobuf.DescriptorProto.ReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; + + /** + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {google.protobuf.DescriptorProto.ReservedRange} message ReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; + + /** + * Converts this ReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @instance + * @returns {Object.} JSON object + */ + ReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservedRange + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto.ReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ReservedRange"; + }; + + return ReservedRange; + })(); + + return DescriptorProto; + })(); + + protobuf.ExtensionRangeOptions = (function() { + + /** + * Properties of an ExtensionRangeOptions. + * @memberof google.protobuf + * @interface IExtensionRangeOptions + * @property {Array.|null} [uninterpretedOption] ExtensionRangeOptions uninterpretedOption + * @property {Array.|null} [declaration] ExtensionRangeOptions declaration + * @property {google.protobuf.IFeatureSet|null} [features] ExtensionRangeOptions features + * @property {google.protobuf.ExtensionRangeOptions.VerificationState|null} [verification] ExtensionRangeOptions verification + */ + + /** + * Constructs a new ExtensionRangeOptions. + * @memberof google.protobuf + * @classdesc Represents an ExtensionRangeOptions. + * @implements IExtensionRangeOptions + * @constructor + * @param {google.protobuf.IExtensionRangeOptions=} [properties] Properties to set + */ + function ExtensionRangeOptions(properties) { + this.uninterpretedOption = []; + this.declaration = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExtensionRangeOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * ExtensionRangeOptions declaration. + * @member {Array.} declaration + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.declaration = $util.emptyArray; + + /** + * ExtensionRangeOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.features = null; + + /** + * ExtensionRangeOptions verification. + * @member {google.protobuf.ExtensionRangeOptions.VerificationState} verification + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.verification = 1; + + /** + * Creates a new ExtensionRangeOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {google.protobuf.IExtensionRangeOptions=} [properties] Properties to set + * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions instance + */ + ExtensionRangeOptions.create = function create(properties) { + return new ExtensionRangeOptions(properties); + }; + + /** + * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {google.protobuf.IExtensionRangeOptions} message ExtensionRangeOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExtensionRangeOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.declaration != null && message.declaration.length) + for (var i = 0; i < message.declaration.length; ++i) + $root.google.protobuf.ExtensionRangeOptions.Declaration.encode(message.declaration[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.verification != null && Object.hasOwnProperty.call(message, "verification")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.verification); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 50, wireType 2 =*/402).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {google.protobuf.IExtensionRangeOptions} message ExtensionRangeOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExtensionRangeOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions + * @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, 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)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + case 2: { + if (!(message.declaration && message.declaration.length)) + message.declaration = []; + message.declaration.push($root.google.protobuf.ExtensionRangeOptions.Declaration.decode(reader, reader.uint32())); + break; + } + case 50: { + message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 3: { + message.verification = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExtensionRangeOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExtensionRangeOptions message. + * @function verify + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExtensionRangeOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + if (message.declaration != null && message.hasOwnProperty("declaration")) { + if (!Array.isArray(message.declaration)) + return "declaration: array expected"; + for (var i = 0; i < message.declaration.length; ++i) { + var error = $root.google.protobuf.ExtensionRangeOptions.Declaration.verify(message.declaration[i]); + if (error) + return "declaration." + error; + } + } + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.verification != null && message.hasOwnProperty("verification")) + switch (message.verification) { + default: + return "verification: enum value expected"; + case 0: + case 1: + break; + } + return null; + }; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions + */ + ExtensionRangeOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions(); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object.declaration) { + if (!Array.isArray(object.declaration)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: array expected"); + message.declaration = []; + for (var i = 0; i < object.declaration.length; ++i) { + if (typeof object.declaration[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: object expected"); + message.declaration[i] = $root.google.protobuf.ExtensionRangeOptions.Declaration.fromObject(object.declaration[i]); + } + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + switch (object.verification) { + case "DECLARATION": + case 0: + message.verification = 0; + break; + default: + if (typeof object.verification === "number") { + message.verification = object.verification; + break; + } + break; + case "UNVERIFIED": + case 1: + message.verification = 1; + break; + } + return message; + }; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {google.protobuf.ExtensionRangeOptions} message ExtensionRangeOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRangeOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.declaration = []; + object.uninterpretedOption = []; + } + if (options.defaults) { + object.verification = options.enums === String ? "UNVERIFIED" : 1; + object.features = null; + } + if (message.declaration && message.declaration.length) { + object.declaration = []; + for (var j = 0; j < message.declaration.length; ++j) + object.declaration[j] = $root.google.protobuf.ExtensionRangeOptions.Declaration.toObject(message.declaration[j], options); + } + if (message.verification != null && message.hasOwnProperty("verification")) + object.verification = options.enums === String ? $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] === undefined ? message.verification : $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] : message.verification; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + * @returns {Object.} JSON object + */ + ExtensionRangeOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRangeOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions"; + }; + + ExtensionRangeOptions.Declaration = (function() { + + /** + * Properties of a Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @interface IDeclaration + * @property {number|null} [number] Declaration number + * @property {string|null} [fullName] Declaration fullName + * @property {string|null} [type] Declaration type + * @property {boolean|null} [reserved] Declaration reserved + * @property {boolean|null} [repeated] Declaration repeated + */ + + /** + * Constructs a new Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @classdesc Represents a Declaration. + * @implements IDeclaration + * @constructor + * @param {google.protobuf.ExtensionRangeOptions.IDeclaration=} [properties] Properties to set + */ + function Declaration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Declaration number. + * @member {number} number + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.number = 0; + + /** + * Declaration fullName. + * @member {string} fullName + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.fullName = ""; + + /** + * Declaration type. + * @member {string} type + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.type = ""; + + /** + * Declaration reserved. + * @member {boolean} reserved + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.reserved = false; + + /** + * Declaration repeated. + * @member {boolean} repeated + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + */ + Declaration.prototype.repeated = false; + + /** + * Creates a new Declaration instance using the specified properties. + * @function create + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {google.protobuf.ExtensionRangeOptions.IDeclaration=} [properties] Properties to set + * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration instance + */ + Declaration.create = function create(properties) { + return new Declaration(properties); + }; + + /** + * Encodes the specified Declaration message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.Declaration.verify|verify} messages. + * @function encode + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {google.protobuf.ExtensionRangeOptions.IDeclaration} message Declaration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Declaration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.number != null && Object.hasOwnProperty.call(message, "number")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.number); + if (message.fullName != null && Object.hasOwnProperty.call(message, "fullName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.fullName); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.type); + if (message.reserved != null && Object.hasOwnProperty.call(message, "reserved")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.reserved); + if (message.repeated != null && Object.hasOwnProperty.call(message, "repeated")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.repeated); + return writer; + }; + + /** + * Encodes the specified Declaration message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.Declaration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {google.protobuf.ExtensionRangeOptions.IDeclaration} message Declaration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Declaration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Declaration message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration + * @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, 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(); + break; + } + case 2: { + message.fullName = reader.string(); + break; + } + case 3: { + message.type = reader.string(); + break; + } + case 5: { + message.reserved = reader.bool(); + break; + } + case 6: { + message.repeated = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Declaration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Declaration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Declaration message. + * @function verify + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Declaration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.number != null && message.hasOwnProperty("number")) + if (!$util.isInteger(message.number)) + return "number: integer expected"; + if (message.fullName != null && message.hasOwnProperty("fullName")) + if (!$util.isString(message.fullName)) + return "fullName: string expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.reserved != null && message.hasOwnProperty("reserved")) + if (typeof message.reserved !== "boolean") + return "reserved: boolean expected"; + if (message.repeated != null && message.hasOwnProperty("repeated")) + if (typeof message.repeated !== "boolean") + return "repeated: boolean expected"; + return null; + }; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration + */ + Declaration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions.Declaration) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions.Declaration(); + if (object.number != null) + message.number = object.number | 0; + if (object.fullName != null) + message.fullName = String(object.fullName); + if (object.type != null) + message.type = String(object.type); + if (object.reserved != null) + message.reserved = Boolean(object.reserved); + if (object.repeated != null) + message.repeated = Boolean(object.repeated); + return message; + }; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {google.protobuf.ExtensionRangeOptions.Declaration} message Declaration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Declaration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.number = 0; + object.fullName = ""; + object.type = ""; + object.reserved = false; + object.repeated = false; + } + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.fullName != null && message.hasOwnProperty("fullName")) + object.fullName = message.fullName; + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.reserved != null && message.hasOwnProperty("reserved")) + object.reserved = message.reserved; + if (message.repeated != null && message.hasOwnProperty("repeated")) + object.repeated = message.repeated; + return object; + }; + + /** + * Converts this Declaration to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @instance + * @returns {Object.} JSON object + */ + Declaration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Declaration + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Declaration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions.Declaration"; + }; + + return Declaration; + })(); + + /** + * VerificationState enum. + * @name google.protobuf.ExtensionRangeOptions.VerificationState + * @enum {number} + * @property {number} DECLARATION=0 DECLARATION value + * @property {number} UNVERIFIED=1 UNVERIFIED value + */ + ExtensionRangeOptions.VerificationState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DECLARATION"] = 0; + values[valuesById[1] = "UNVERIFIED"] = 1; + return values; + })(); + + return ExtensionRangeOptions; + })(); + + protobuf.FieldDescriptorProto = (function() { + + /** + * Properties of a FieldDescriptorProto. + * @memberof google.protobuf + * @interface IFieldDescriptorProto + * @property {string|null} [name] FieldDescriptorProto name + * @property {number|null} [number] FieldDescriptorProto number + * @property {google.protobuf.FieldDescriptorProto.Label|null} [label] FieldDescriptorProto label + * @property {google.protobuf.FieldDescriptorProto.Type|null} [type] FieldDescriptorProto type + * @property {string|null} [typeName] FieldDescriptorProto typeName + * @property {string|null} [extendee] FieldDescriptorProto extendee + * @property {string|null} [defaultValue] FieldDescriptorProto defaultValue + * @property {number|null} [oneofIndex] FieldDescriptorProto oneofIndex + * @property {string|null} [jsonName] FieldDescriptorProto jsonName + * @property {google.protobuf.IFieldOptions|null} [options] FieldDescriptorProto options + * @property {boolean|null} [proto3Optional] FieldDescriptorProto proto3Optional + */ + + /** + * Constructs a new FieldDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FieldDescriptorProto. + * @implements IFieldDescriptorProto + * @constructor + * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set + */ + function FieldDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.name = ""; + + /** + * FieldDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.number = 0; + + /** + * FieldDescriptorProto label. + * @member {google.protobuf.FieldDescriptorProto.Label} label + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.label = 1; + + /** + * FieldDescriptorProto type. + * @member {google.protobuf.FieldDescriptorProto.Type} type + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.type = 1; + + /** + * FieldDescriptorProto typeName. + * @member {string} typeName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.typeName = ""; + + /** + * FieldDescriptorProto extendee. + * @member {string} extendee + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.extendee = ""; + + /** + * FieldDescriptorProto defaultValue. + * @member {string} defaultValue + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.defaultValue = ""; + + /** + * FieldDescriptorProto oneofIndex. + * @member {number} oneofIndex + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.oneofIndex = 0; + + /** + * FieldDescriptorProto jsonName. + * @member {string} jsonName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.jsonName = ""; + + /** + * FieldDescriptorProto options. + * @member {google.protobuf.IFieldOptions|null|undefined} options + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.options = null; + + /** + * FieldDescriptorProto proto3Optional. + * @member {boolean} proto3Optional + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.proto3Optional = false; + + /** + * Creates a new FieldDescriptorProto instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set + * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto instance + */ + FieldDescriptorProto.create = function create(properties) { + return new FieldDescriptorProto(properties); + }; + + /** + * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {google.protobuf.IFieldDescriptorProto} message FieldDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldDescriptorProto.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.extendee != null && Object.hasOwnProperty.call(message, "extendee")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.extendee); + if (message.number != null && Object.hasOwnProperty.call(message, "number")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.number); + if (message.label != null && Object.hasOwnProperty.call(message, "label")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.label); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.type); + if (message.typeName != null && Object.hasOwnProperty.call(message, "typeName")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.typeName); + if (message.defaultValue != null && Object.hasOwnProperty.call(message, "defaultValue")) + writer.uint32(/* id 7, wireType 2 =*/58).string(message.defaultValue); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.FieldOptions.encode(message.options, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.oneofIndex != null && Object.hasOwnProperty.call(message, "oneofIndex")) + writer.uint32(/* id 9, wireType 0 =*/72).int32(message.oneofIndex); + if (message.jsonName != null && Object.hasOwnProperty.call(message, "jsonName")) + writer.uint32(/* id 10, wireType 2 =*/82).string(message.jsonName); + if (message.proto3Optional != null && Object.hasOwnProperty.call(message, "proto3Optional")) + writer.uint32(/* id 17, wireType 0 =*/136).bool(message.proto3Optional); + return writer; + }; + + /** + * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {google.protobuf.IFieldDescriptorProto} message FieldDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto + * @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, 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(); + break; + } + case 3: { + message.number = reader.int32(); + break; + } + case 4: { + message.label = reader.int32(); + break; + } + case 5: { + message.type = reader.int32(); + break; + } + case 6: { + message.typeName = reader.string(); + break; + } + case 2: { + message.extendee = reader.string(); + break; + } + case 7: { + message.defaultValue = reader.string(); + break; + } + case 9: { + message.oneofIndex = reader.int32(); + break; + } + case 10: { + message.jsonName = reader.string(); + break; + } + case 8: { + message.options = $root.google.protobuf.FieldOptions.decode(reader, reader.uint32()); + break; + } + case 17: { + message.proto3Optional = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FieldDescriptorProto.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FieldDescriptorProto message. + * @function verify + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FieldDescriptorProto.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.number != null && message.hasOwnProperty("number")) + if (!$util.isInteger(message.number)) + return "number: integer expected"; + if (message.label != null && message.hasOwnProperty("label")) + switch (message.label) { + default: + return "label: enum value expected"; + case 1: + case 3: + case 2: + break; + } + if (message.type != null && message.hasOwnProperty("type")) + switch (message.type) { + default: + return "type: enum value expected"; + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + break; + } + if (message.typeName != null && message.hasOwnProperty("typeName")) + if (!$util.isString(message.typeName)) + return "typeName: string expected"; + if (message.extendee != null && message.hasOwnProperty("extendee")) + if (!$util.isString(message.extendee)) + return "extendee: string expected"; + if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) + if (!$util.isString(message.defaultValue)) + return "defaultValue: string expected"; + if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) + if (!$util.isInteger(message.oneofIndex)) + return "oneofIndex: integer expected"; + if (message.jsonName != null && message.hasOwnProperty("jsonName")) + if (!$util.isString(message.jsonName)) + return "jsonName: string expected"; + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.FieldOptions.verify(message.options); + if (error) + return "options." + error; + } + if (message.proto3Optional != null && message.hasOwnProperty("proto3Optional")) + if (typeof message.proto3Optional !== "boolean") + return "proto3Optional: boolean expected"; + return null; + }; + + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto + */ + FieldDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldDescriptorProto) + return object; + var message = new $root.google.protobuf.FieldDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + switch (object.label) { + default: + if (typeof object.label === "number") { + message.label = object.label; + break; + } + break; + case "LABEL_OPTIONAL": + case 1: + message.label = 1; + break; + case "LABEL_REPEATED": + case 3: + message.label = 3; + break; + case "LABEL_REQUIRED": + case 2: + message.label = 2; + break; + } + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_DOUBLE": + case 1: + message.type = 1; + break; + case "TYPE_FLOAT": + case 2: + message.type = 2; + break; + case "TYPE_INT64": + case 3: + message.type = 3; + break; + case "TYPE_UINT64": + case 4: + message.type = 4; + break; + case "TYPE_INT32": + case 5: + message.type = 5; + break; + case "TYPE_FIXED64": + case 6: + message.type = 6; + break; + case "TYPE_FIXED32": + case 7: + message.type = 7; + break; + case "TYPE_BOOL": + case 8: + message.type = 8; + break; + case "TYPE_STRING": + case 9: + message.type = 9; + break; + case "TYPE_GROUP": + case 10: + message.type = 10; + break; + case "TYPE_MESSAGE": + case 11: + message.type = 11; + break; + case "TYPE_BYTES": + case 12: + message.type = 12; + break; + case "TYPE_UINT32": + case 13: + message.type = 13; + break; + case "TYPE_ENUM": + case 14: + message.type = 14; + break; + case "TYPE_SFIXED32": + case 15: + message.type = 15; + break; + case "TYPE_SFIXED64": + case 16: + message.type = 16; + break; + case "TYPE_SINT32": + case 17: + message.type = 17; + break; + case "TYPE_SINT64": + case 18: + message.type = 18; + break; + } + if (object.typeName != null) + message.typeName = String(object.typeName); + if (object.extendee != null) + message.extendee = String(object.extendee); + if (object.defaultValue != null) + message.defaultValue = String(object.defaultValue); + if (object.oneofIndex != null) + message.oneofIndex = object.oneofIndex | 0; + if (object.jsonName != null) + message.jsonName = String(object.jsonName); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FieldOptions.fromObject(object.options); + } + if (object.proto3Optional != null) + message.proto3Optional = Boolean(object.proto3Optional); + return message; + }; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {google.protobuf.FieldDescriptorProto} message FieldDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.extendee = ""; + object.number = 0; + object.label = options.enums === String ? "LABEL_OPTIONAL" : 1; + object.type = options.enums === String ? "TYPE_DOUBLE" : 1; + object.typeName = ""; + object.defaultValue = ""; + object.options = null; + object.oneofIndex = 0; + object.jsonName = ""; + object.proto3Optional = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.extendee != null && message.hasOwnProperty("extendee")) + object.extendee = message.extendee; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.label != null && message.hasOwnProperty("label")) + object.label = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Label[message.label] === undefined ? message.label : $root.google.protobuf.FieldDescriptorProto.Label[message.label] : message.label; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Type[message.type] === undefined ? message.type : $root.google.protobuf.FieldDescriptorProto.Type[message.type] : message.type; + if (message.typeName != null && message.hasOwnProperty("typeName")) + object.typeName = message.typeName; + if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) + object.defaultValue = message.defaultValue; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FieldOptions.toObject(message.options, options); + if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) + object.oneofIndex = message.oneofIndex; + if (message.jsonName != null && message.hasOwnProperty("jsonName")) + object.jsonName = message.jsonName; + if (message.proto3Optional != null && message.hasOwnProperty("proto3Optional")) + object.proto3Optional = message.proto3Optional; + return object; + }; + + /** + * Converts this FieldDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FieldDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FieldDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldDescriptorProto"; + }; + + /** + * Type enum. + * @name google.protobuf.FieldDescriptorProto.Type + * @enum {number} + * @property {number} TYPE_DOUBLE=1 TYPE_DOUBLE value + * @property {number} TYPE_FLOAT=2 TYPE_FLOAT value + * @property {number} TYPE_INT64=3 TYPE_INT64 value + * @property {number} TYPE_UINT64=4 TYPE_UINT64 value + * @property {number} TYPE_INT32=5 TYPE_INT32 value + * @property {number} TYPE_FIXED64=6 TYPE_FIXED64 value + * @property {number} TYPE_FIXED32=7 TYPE_FIXED32 value + * @property {number} TYPE_BOOL=8 TYPE_BOOL value + * @property {number} TYPE_STRING=9 TYPE_STRING value + * @property {number} TYPE_GROUP=10 TYPE_GROUP value + * @property {number} TYPE_MESSAGE=11 TYPE_MESSAGE value + * @property {number} TYPE_BYTES=12 TYPE_BYTES value + * @property {number} TYPE_UINT32=13 TYPE_UINT32 value + * @property {number} TYPE_ENUM=14 TYPE_ENUM value + * @property {number} TYPE_SFIXED32=15 TYPE_SFIXED32 value + * @property {number} TYPE_SFIXED64=16 TYPE_SFIXED64 value + * @property {number} TYPE_SINT32=17 TYPE_SINT32 value + * @property {number} TYPE_SINT64=18 TYPE_SINT64 value + */ + FieldDescriptorProto.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "TYPE_DOUBLE"] = 1; + values[valuesById[2] = "TYPE_FLOAT"] = 2; + values[valuesById[3] = "TYPE_INT64"] = 3; + values[valuesById[4] = "TYPE_UINT64"] = 4; + values[valuesById[5] = "TYPE_INT32"] = 5; + values[valuesById[6] = "TYPE_FIXED64"] = 6; + values[valuesById[7] = "TYPE_FIXED32"] = 7; + values[valuesById[8] = "TYPE_BOOL"] = 8; + values[valuesById[9] = "TYPE_STRING"] = 9; + values[valuesById[10] = "TYPE_GROUP"] = 10; + values[valuesById[11] = "TYPE_MESSAGE"] = 11; + values[valuesById[12] = "TYPE_BYTES"] = 12; + values[valuesById[13] = "TYPE_UINT32"] = 13; + values[valuesById[14] = "TYPE_ENUM"] = 14; + values[valuesById[15] = "TYPE_SFIXED32"] = 15; + values[valuesById[16] = "TYPE_SFIXED64"] = 16; + values[valuesById[17] = "TYPE_SINT32"] = 17; + values[valuesById[18] = "TYPE_SINT64"] = 18; + return values; + })(); + + /** + * Label enum. + * @name google.protobuf.FieldDescriptorProto.Label + * @enum {number} + * @property {number} LABEL_OPTIONAL=1 LABEL_OPTIONAL value + * @property {number} LABEL_REPEATED=3 LABEL_REPEATED value + * @property {number} LABEL_REQUIRED=2 LABEL_REQUIRED value + */ + FieldDescriptorProto.Label = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "LABEL_OPTIONAL"] = 1; + values[valuesById[3] = "LABEL_REPEATED"] = 3; + values[valuesById[2] = "LABEL_REQUIRED"] = 2; + return values; + })(); + + return FieldDescriptorProto; + })(); + + protobuf.OneofDescriptorProto = (function() { + + /** + * Properties of an OneofDescriptorProto. + * @memberof google.protobuf + * @interface IOneofDescriptorProto + * @property {string|null} [name] OneofDescriptorProto name + * @property {google.protobuf.IOneofOptions|null} [options] OneofDescriptorProto options + */ + + /** + * Constructs a new OneofDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an OneofDescriptorProto. + * @implements IOneofDescriptorProto + * @constructor + * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set + */ + function OneofDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.name = ""; + + /** + * OneofDescriptorProto options. + * @member {google.protobuf.IOneofOptions|null|undefined} options + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.options = null; + + /** + * Creates a new OneofDescriptorProto instance using the specified properties. + * @function create + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set + * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto instance + */ + OneofDescriptorProto.create = function create(properties) { + return new OneofDescriptorProto(properties); + }; + + /** + * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @function encode + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {google.protobuf.IOneofDescriptorProto} message OneofDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OneofDescriptorProto.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.OneofOptions.encode(message.options, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {google.protobuf.IOneofDescriptorProto} message OneofDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OneofDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto + * @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, 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(); + break; + } + case 2: { + message.options = $root.google.protobuf.OneofOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OneofDescriptorProto.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an OneofDescriptorProto message. + * @function verify + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + OneofDescriptorProto.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.OneofOptions.verify(message.options); + if (error) + return "options." + error; + } + return null; + }; + + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto + */ + OneofDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofDescriptorProto) + return object; + var message = new $root.google.protobuf.OneofDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.OneofOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {google.protobuf.OneofDescriptorProto} message OneofDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.OneofOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this OneofDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.OneofDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + OneofDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofDescriptorProto"; + }; + + return OneofDescriptorProto; + })(); + + protobuf.EnumDescriptorProto = (function() { + + /** + * Properties of an EnumDescriptorProto. + * @memberof google.protobuf + * @interface IEnumDescriptorProto + * @property {string|null} [name] EnumDescriptorProto name + * @property {Array.|null} [value] EnumDescriptorProto value + * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options + * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange + * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] EnumDescriptorProto visibility + */ + + /** + * Constructs a new EnumDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumDescriptorProto. + * @implements IEnumDescriptorProto + * @constructor + * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set + */ + function EnumDescriptorProto(properties) { + this.value = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.name = ""; + + /** + * EnumDescriptorProto value. + * @member {Array.} value + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.value = $util.emptyArray; + + /** + * EnumDescriptorProto options. + * @member {google.protobuf.IEnumOptions|null|undefined} options + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.options = null; + + /** + * EnumDescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedRange = $util.emptyArray; + + /** + * EnumDescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * EnumDescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.visibility = 0; + + /** + * Creates a new EnumDescriptorProto instance using the specified properties. + * @function create + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set + * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto instance + */ + EnumDescriptorProto.create = function create(properties) { + return new EnumDescriptorProto(properties); + }; + + /** + * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @function encode + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {google.protobuf.IEnumDescriptorProto} message EnumDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumDescriptorProto.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.value != null && message.value.length) + for (var i = 0; i < message.value.length; ++i) + $root.google.protobuf.EnumValueDescriptorProto.encode(message.value[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.EnumOptions.encode(message.options, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.reservedRange != null && message.reservedRange.length) + for (var i = 0; i < message.reservedRange.length; ++i) + $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.encode(message.reservedRange[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.reservedName != null && message.reservedName.length) + for (var i = 0; i < message.reservedName.length; ++i) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.visibility); + return writer; + }; + + /** + * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {google.protobuf.IEnumDescriptorProto} message EnumDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto + * @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, 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(); + break; + } + case 2: { + if (!(message.value && message.value.length)) + message.value = []; + message.value.push($root.google.protobuf.EnumValueDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 3: { + message.options = $root.google.protobuf.EnumOptions.decode(reader, reader.uint32()); + break; + } + case 4: { + if (!(message.reservedRange && message.reservedRange.length)) + message.reservedRange = []; + message.reservedRange.push($root.google.protobuf.EnumDescriptorProto.EnumReservedRange.decode(reader, reader.uint32())); + break; + } + case 5: { + if (!(message.reservedName && message.reservedName.length)) + message.reservedName = []; + message.reservedName.push(reader.string()); + break; + } + case 6: { + message.visibility = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EnumDescriptorProto.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an EnumDescriptorProto message. + * @function verify + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EnumDescriptorProto.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.value != null && message.hasOwnProperty("value")) { + if (!Array.isArray(message.value)) + return "value: array expected"; + for (var i = 0; i < message.value.length; ++i) { + var error = $root.google.protobuf.EnumValueDescriptorProto.verify(message.value[i]); + if (error) + return "value." + error; + } + } + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.EnumOptions.verify(message.options); + if (error) + return "options." + error; + } + if (message.reservedRange != null && message.hasOwnProperty("reservedRange")) { + if (!Array.isArray(message.reservedRange)) + return "reservedRange: array expected"; + for (var i = 0; i < message.reservedRange.length; ++i) { + var error = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.verify(message.reservedRange[i]); + if (error) + return "reservedRange." + error; + } + } + if (message.reservedName != null && message.hasOwnProperty("reservedName")) { + if (!Array.isArray(message.reservedName)) + return "reservedName: array expected"; + for (var i = 0; i < message.reservedName.length; ++i) + if (!$util.isString(message.reservedName[i])) + return "reservedName: string[] expected"; + } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto + */ + EnumDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.value) { + if (!Array.isArray(object.value)) + throw TypeError(".google.protobuf.EnumDescriptorProto.value: array expected"); + message.value = []; + for (var i = 0; i < object.value.length; ++i) { + if (typeof object.value[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.value: object expected"); + message.value[i] = $root.google.protobuf.EnumValueDescriptorProto.fromObject(object.value[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {google.protobuf.EnumDescriptorProto} message EnumDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.value = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.value && message.value.length) { + object.value = []; + for (var j = 0; j < message.value.length; ++j) + object.value[j] = $root.google.protobuf.EnumValueDescriptorProto.toObject(message.value[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumOptions.toObject(message.options, options); + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; + return object; + }; + + /** + * Converts this EnumDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto"; + }; + + EnumDescriptorProto.EnumReservedRange = (function() { + + /** + * Properties of an EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @interface IEnumReservedRange + * @property {number|null} [start] EnumReservedRange start + * @property {number|null} [end] EnumReservedRange end + */ + + /** + * Constructs a new EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @classdesc Represents an EnumReservedRange. + * @implements IEnumReservedRange + * @constructor + * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange=} [properties] Properties to set + */ + function EnumReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumReservedRange start. + * @member {number} start + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.start = 0; + + /** + * EnumReservedRange end. + * @member {number} end + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.end = 0; + + /** + * Creates a new EnumReservedRange instance using the specified properties. + * @function create + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange=} [properties] Properties to set + * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange instance + */ + EnumReservedRange.create = function create(properties) { + return new EnumReservedRange(properties); + }; + + /** + * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @function encode + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange} message EnumReservedRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumReservedRange.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.start != null && Object.hasOwnProperty.call(message, "start")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.start); + if (message.end != null && Object.hasOwnProperty.call(message, "end")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.end); + return writer; + }; + + /** + * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange} message EnumReservedRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumReservedRange.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange + * @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, 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(); + break; + } + case 2: { + message.end = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EnumReservedRange.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an EnumReservedRange message. + * @function verify + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EnumReservedRange.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.start != null && message.hasOwnProperty("start")) + if (!$util.isInteger(message.start)) + return "start: integer expected"; + if (message.end != null && message.hasOwnProperty("end")) + if (!$util.isInteger(message.end)) + return "end: integer expected"; + return null; + }; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange + */ + EnumReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto.EnumReservedRange) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto.EnumReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {google.protobuf.EnumDescriptorProto.EnumReservedRange} message EnumReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; + + /** + * Converts this EnumReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + * @returns {Object.} JSON object + */ + EnumReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumReservedRange + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto.EnumReservedRange"; + }; + + return EnumReservedRange; + })(); + + return EnumDescriptorProto; + })(); + + protobuf.EnumValueDescriptorProto = (function() { + + /** + * Properties of an EnumValueDescriptorProto. + * @memberof google.protobuf + * @interface IEnumValueDescriptorProto + * @property {string|null} [name] EnumValueDescriptorProto name + * @property {number|null} [number] EnumValueDescriptorProto number + * @property {google.protobuf.IEnumValueOptions|null} [options] EnumValueDescriptorProto options + */ + + /** + * Constructs a new EnumValueDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumValueDescriptorProto. + * @implements IEnumValueDescriptorProto + * @constructor + * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set + */ + function EnumValueDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.name = ""; + + /** + * EnumValueDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.number = 0; + + /** + * EnumValueDescriptorProto options. + * @member {google.protobuf.IEnumValueOptions|null|undefined} options + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.options = null; + + /** + * Creates a new EnumValueDescriptorProto instance using the specified properties. + * @function create + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set + * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto instance + */ + EnumValueDescriptorProto.create = function create(properties) { + return new EnumValueDescriptorProto(properties); + }; + + /** + * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @function encode + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {google.protobuf.IEnumValueDescriptorProto} message EnumValueDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumValueDescriptorProto.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.number != null && Object.hasOwnProperty.call(message, "number")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.number); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.EnumValueOptions.encode(message.options, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {google.protobuf.IEnumValueDescriptorProto} message EnumValueDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumValueDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto + * @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, 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(); + break; + } + case 2: { + message.number = reader.int32(); + break; + } + case 3: { + message.options = $root.google.protobuf.EnumValueOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EnumValueDescriptorProto.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an EnumValueDescriptorProto message. + * @function verify + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EnumValueDescriptorProto.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.number != null && message.hasOwnProperty("number")) + if (!$util.isInteger(message.number)) + return "number: integer expected"; + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.EnumValueOptions.verify(message.options); + if (error) + return "options." + error; + } + return null; + }; + + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto + */ + EnumValueDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumValueDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumValueOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {google.protobuf.EnumValueDescriptorProto} message EnumValueDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.number = 0; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumValueOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this EnumValueDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumValueDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueDescriptorProto"; + }; + + return EnumValueDescriptorProto; + })(); + + protobuf.ServiceDescriptorProto = (function() { + + /** + * Properties of a ServiceDescriptorProto. + * @memberof google.protobuf + * @interface IServiceDescriptorProto + * @property {string|null} [name] ServiceDescriptorProto name + * @property {Array.|null} [method] ServiceDescriptorProto method + * @property {google.protobuf.IServiceOptions|null} [options] ServiceDescriptorProto options + */ + + /** + * Constructs a new ServiceDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a ServiceDescriptorProto. + * @implements IServiceDescriptorProto + * @constructor + * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set + */ + function ServiceDescriptorProto(properties) { + this.method = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.name = ""; + + /** + * ServiceDescriptorProto method. + * @member {Array.} method + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.method = $util.emptyArray; + + /** + * ServiceDescriptorProto options. + * @member {google.protobuf.IServiceOptions|null|undefined} options + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.options = null; + + /** + * Creates a new ServiceDescriptorProto instance using the specified properties. + * @function create + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set + * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto instance + */ + ServiceDescriptorProto.create = function create(properties) { + return new ServiceDescriptorProto(properties); + }; + + /** + * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @function encode + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {google.protobuf.IServiceDescriptorProto} message ServiceDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ServiceDescriptorProto.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.method != null && message.method.length) + for (var i = 0; i < message.method.length; ++i) + $root.google.protobuf.MethodDescriptorProto.encode(message.method[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.ServiceOptions.encode(message.options, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {google.protobuf.IServiceDescriptorProto} message ServiceDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ServiceDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto + * @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, 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(); + break; + } + case 2: { + if (!(message.method && message.method.length)) + message.method = []; + message.method.push($root.google.protobuf.MethodDescriptorProto.decode(reader, reader.uint32())); + break; + } + case 3: { + message.options = $root.google.protobuf.ServiceOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ServiceDescriptorProto.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ServiceDescriptorProto message. + * @function verify + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ServiceDescriptorProto.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.method != null && message.hasOwnProperty("method")) { + if (!Array.isArray(message.method)) + return "method: array expected"; + for (var i = 0; i < message.method.length; ++i) { + var error = $root.google.protobuf.MethodDescriptorProto.verify(message.method[i]); + if (error) + return "method." + error; + } + } + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.ServiceOptions.verify(message.options); + if (error) + return "options." + error; + } + return null; + }; + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto + */ + ServiceDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceDescriptorProto) + return object; + var message = new $root.google.protobuf.ServiceDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.method) { + if (!Array.isArray(object.method)) + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: array expected"); + message.method = []; + for (var i = 0; i < object.method.length; ++i) { + if (typeof object.method[i] !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: object expected"); + message.method[i] = $root.google.protobuf.MethodDescriptorProto.fromObject(object.method[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.ServiceOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {google.protobuf.ServiceDescriptorProto} message ServiceDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.method = []; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.method && message.method.length) { + object.method = []; + for (var j = 0; j < message.method.length; ++j) + object.method[j] = $root.google.protobuf.MethodDescriptorProto.toObject(message.method[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ServiceOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + ServiceDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceDescriptorProto"; + }; + + return ServiceDescriptorProto; + })(); + + protobuf.MethodDescriptorProto = (function() { + + /** + * Properties of a MethodDescriptorProto. + * @memberof google.protobuf + * @interface IMethodDescriptorProto + * @property {string|null} [name] MethodDescriptorProto name + * @property {string|null} [inputType] MethodDescriptorProto inputType + * @property {string|null} [outputType] MethodDescriptorProto outputType + * @property {google.protobuf.IMethodOptions|null} [options] MethodDescriptorProto options + * @property {boolean|null} [clientStreaming] MethodDescriptorProto clientStreaming + * @property {boolean|null} [serverStreaming] MethodDescriptorProto serverStreaming + */ + + /** + * Constructs a new MethodDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a MethodDescriptorProto. + * @implements IMethodDescriptorProto + * @constructor + * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set + */ + function MethodDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.name = ""; + + /** + * MethodDescriptorProto inputType. + * @member {string} inputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.inputType = ""; + + /** + * MethodDescriptorProto outputType. + * @member {string} outputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.outputType = ""; + + /** + * MethodDescriptorProto options. + * @member {google.protobuf.IMethodOptions|null|undefined} options + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.options = null; + + /** + * MethodDescriptorProto clientStreaming. + * @member {boolean} clientStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.clientStreaming = false; + + /** + * MethodDescriptorProto serverStreaming. + * @member {boolean} serverStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.serverStreaming = false; + + /** + * Creates a new MethodDescriptorProto instance using the specified properties. + * @function create + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set + * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto instance + */ + MethodDescriptorProto.create = function create(properties) { + return new MethodDescriptorProto(properties); + }; + + /** + * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @function encode + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {google.protobuf.IMethodDescriptorProto} message MethodDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MethodDescriptorProto.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.inputType != null && Object.hasOwnProperty.call(message, "inputType")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.inputType); + if (message.outputType != null && Object.hasOwnProperty.call(message, "outputType")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.outputType); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.protobuf.MethodOptions.encode(message.options, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.clientStreaming != null && Object.hasOwnProperty.call(message, "clientStreaming")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.clientStreaming); + if (message.serverStreaming != null && Object.hasOwnProperty.call(message, "serverStreaming")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.serverStreaming); + return writer; + }; + + /** + * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {google.protobuf.IMethodDescriptorProto} message MethodDescriptorProto message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MethodDescriptorProto.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto + * @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, 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(); + break; + } + case 2: { + message.inputType = reader.string(); + break; + } + case 3: { + message.outputType = reader.string(); + break; + } + case 4: { + message.options = $root.google.protobuf.MethodOptions.decode(reader, reader.uint32()); + break; + } + case 5: { + message.clientStreaming = reader.bool(); + break; + } + case 6: { + message.serverStreaming = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MethodDescriptorProto.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MethodDescriptorProto message. + * @function verify + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MethodDescriptorProto.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.inputType != null && message.hasOwnProperty("inputType")) + if (!$util.isString(message.inputType)) + return "inputType: string expected"; + if (message.outputType != null && message.hasOwnProperty("outputType")) + if (!$util.isString(message.outputType)) + return "outputType: string expected"; + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.protobuf.MethodOptions.verify(message.options); + if (error) + return "options." + error; + } + if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) + if (typeof message.clientStreaming !== "boolean") + return "clientStreaming: boolean expected"; + if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) + if (typeof message.serverStreaming !== "boolean") + return "serverStreaming: boolean expected"; + return null; + }; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto + */ + MethodDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodDescriptorProto) + return object; + var message = new $root.google.protobuf.MethodDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.inputType != null) + message.inputType = String(object.inputType); + if (object.outputType != null) + message.outputType = String(object.outputType); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MethodOptions.fromObject(object.options); + } + if (object.clientStreaming != null) + message.clientStreaming = Boolean(object.clientStreaming); + if (object.serverStreaming != null) + message.serverStreaming = Boolean(object.serverStreaming); + return message; + }; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {google.protobuf.MethodDescriptorProto} message MethodDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.inputType = ""; + object.outputType = ""; + object.options = null; + object.clientStreaming = false; + object.serverStreaming = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.inputType != null && message.hasOwnProperty("inputType")) + object.inputType = message.inputType; + if (message.outputType != null && message.hasOwnProperty("outputType")) + object.outputType = message.outputType; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MethodOptions.toObject(message.options, options); + if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) + object.clientStreaming = message.clientStreaming; + if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) + object.serverStreaming = message.serverStreaming; + return object; + }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.MethodDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + MethodDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodDescriptorProto"; + }; + + return MethodDescriptorProto; + })(); + + protobuf.FileOptions = (function() { + + /** + * Properties of a FileOptions. + * @memberof google.protobuf + * @interface IFileOptions + * @property {string|null} [javaPackage] FileOptions javaPackage + * @property {string|null} [javaOuterClassname] FileOptions javaOuterClassname + * @property {boolean|null} [javaMultipleFiles] FileOptions javaMultipleFiles + * @property {boolean|null} [javaGenerateEqualsAndHash] FileOptions javaGenerateEqualsAndHash + * @property {boolean|null} [javaStringCheckUtf8] FileOptions javaStringCheckUtf8 + * @property {google.protobuf.FileOptions.OptimizeMode|null} [optimizeFor] FileOptions optimizeFor + * @property {string|null} [goPackage] FileOptions goPackage + * @property {boolean|null} [ccGenericServices] FileOptions ccGenericServices + * @property {boolean|null} [javaGenericServices] FileOptions javaGenericServices + * @property {boolean|null} [pyGenericServices] FileOptions pyGenericServices + * @property {boolean|null} [deprecated] FileOptions deprecated + * @property {boolean|null} [ccEnableArenas] FileOptions ccEnableArenas + * @property {string|null} [objcClassPrefix] FileOptions objcClassPrefix + * @property {string|null} [csharpNamespace] FileOptions csharpNamespace + * @property {string|null} [swiftPrefix] FileOptions swiftPrefix + * @property {string|null} [phpClassPrefix] FileOptions phpClassPrefix + * @property {string|null} [phpNamespace] FileOptions phpNamespace + * @property {string|null} [phpMetadataNamespace] FileOptions phpMetadataNamespace + * @property {string|null} [rubyPackage] FileOptions rubyPackage + * @property {google.protobuf.IFeatureSet|null} [features] FileOptions features + * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption + * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition + */ + + /** + * Constructs a new FileOptions. + * @memberof google.protobuf + * @classdesc Represents a FileOptions. + * @implements IFileOptions + * @constructor + * @param {google.protobuf.IFileOptions=} [properties] Properties to set + */ + function FileOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.resourceDefinition"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FileOptions javaPackage. + * @member {string} javaPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaPackage = ""; + + /** + * FileOptions javaOuterClassname. + * @member {string} javaOuterClassname + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaOuterClassname = ""; + + /** + * FileOptions javaMultipleFiles. + * @member {boolean} javaMultipleFiles + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaMultipleFiles = false; + + /** + * FileOptions javaGenerateEqualsAndHash. + * @member {boolean} javaGenerateEqualsAndHash + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenerateEqualsAndHash = false; + + /** + * FileOptions javaStringCheckUtf8. + * @member {boolean} javaStringCheckUtf8 + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaStringCheckUtf8 = false; + + /** + * FileOptions optimizeFor. + * @member {google.protobuf.FileOptions.OptimizeMode} optimizeFor + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.optimizeFor = 1; + + /** + * FileOptions goPackage. + * @member {string} goPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.goPackage = ""; + + /** + * FileOptions ccGenericServices. + * @member {boolean} ccGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccGenericServices = false; + + /** + * FileOptions javaGenericServices. + * @member {boolean} javaGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenericServices = false; + + /** + * FileOptions pyGenericServices. + * @member {boolean} pyGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.pyGenericServices = false; + + /** + * FileOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.deprecated = false; + + /** + * FileOptions ccEnableArenas. + * @member {boolean} ccEnableArenas + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccEnableArenas = true; + + /** + * FileOptions objcClassPrefix. + * @member {string} objcClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.objcClassPrefix = ""; + + /** + * FileOptions csharpNamespace. + * @member {string} csharpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.csharpNamespace = ""; + + /** + * FileOptions swiftPrefix. + * @member {string} swiftPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.swiftPrefix = ""; + + /** + * FileOptions phpClassPrefix. + * @member {string} phpClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpClassPrefix = ""; + + /** + * FileOptions phpNamespace. + * @member {string} phpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpNamespace = ""; + + /** + * FileOptions phpMetadataNamespace. + * @member {string} phpMetadataNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpMetadataNamespace = ""; + + /** + * FileOptions rubyPackage. + * @member {string} rubyPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.rubyPackage = ""; + + /** + * FileOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.features = null; + + /** + * FileOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * FileOptions .google.api.resourceDefinition. + * @member {Array.} .google.api.resourceDefinition + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; + + /** + * Creates a new FileOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.FileOptions + * @static + * @param {google.protobuf.IFileOptions=} [properties] Properties to set + * @returns {google.protobuf.FileOptions} FileOptions instance + */ + FileOptions.create = function create(properties) { + return new FileOptions(properties); + }; + + /** + * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FileOptions + * @static + * @param {google.protobuf.IFileOptions} message FileOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FileOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.javaPackage != null && Object.hasOwnProperty.call(message, "javaPackage")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.javaPackage); + if (message.javaOuterClassname != null && Object.hasOwnProperty.call(message, "javaOuterClassname")) + writer.uint32(/* id 8, wireType 2 =*/66).string(message.javaOuterClassname); + if (message.optimizeFor != null && Object.hasOwnProperty.call(message, "optimizeFor")) + writer.uint32(/* id 9, wireType 0 =*/72).int32(message.optimizeFor); + if (message.javaMultipleFiles != null && Object.hasOwnProperty.call(message, "javaMultipleFiles")) + writer.uint32(/* id 10, wireType 0 =*/80).bool(message.javaMultipleFiles); + if (message.goPackage != null && Object.hasOwnProperty.call(message, "goPackage")) + writer.uint32(/* id 11, wireType 2 =*/90).string(message.goPackage); + if (message.ccGenericServices != null && Object.hasOwnProperty.call(message, "ccGenericServices")) + writer.uint32(/* id 16, wireType 0 =*/128).bool(message.ccGenericServices); + if (message.javaGenericServices != null && Object.hasOwnProperty.call(message, "javaGenericServices")) + writer.uint32(/* id 17, wireType 0 =*/136).bool(message.javaGenericServices); + if (message.pyGenericServices != null && Object.hasOwnProperty.call(message, "pyGenericServices")) + writer.uint32(/* id 18, wireType 0 =*/144).bool(message.pyGenericServices); + if (message.javaGenerateEqualsAndHash != null && Object.hasOwnProperty.call(message, "javaGenerateEqualsAndHash")) + writer.uint32(/* id 20, wireType 0 =*/160).bool(message.javaGenerateEqualsAndHash); + if (message.deprecated != null && Object.hasOwnProperty.call(message, "deprecated")) + writer.uint32(/* id 23, wireType 0 =*/184).bool(message.deprecated); + if (message.javaStringCheckUtf8 != null && Object.hasOwnProperty.call(message, "javaStringCheckUtf8")) + writer.uint32(/* id 27, wireType 0 =*/216).bool(message.javaStringCheckUtf8); + if (message.ccEnableArenas != null && Object.hasOwnProperty.call(message, "ccEnableArenas")) + writer.uint32(/* id 31, wireType 0 =*/248).bool(message.ccEnableArenas); + if (message.objcClassPrefix != null && Object.hasOwnProperty.call(message, "objcClassPrefix")) + writer.uint32(/* id 36, wireType 2 =*/290).string(message.objcClassPrefix); + if (message.csharpNamespace != null && Object.hasOwnProperty.call(message, "csharpNamespace")) + writer.uint32(/* id 37, wireType 2 =*/298).string(message.csharpNamespace); + if (message.swiftPrefix != null && Object.hasOwnProperty.call(message, "swiftPrefix")) + writer.uint32(/* id 39, wireType 2 =*/314).string(message.swiftPrefix); + if (message.phpClassPrefix != null && Object.hasOwnProperty.call(message, "phpClassPrefix")) + writer.uint32(/* id 40, wireType 2 =*/322).string(message.phpClassPrefix); + if (message.phpNamespace != null && Object.hasOwnProperty.call(message, "phpNamespace")) + writer.uint32(/* id 41, wireType 2 =*/330).string(message.phpNamespace); + if (message.phpMetadataNamespace != null && Object.hasOwnProperty.call(message, "phpMetadataNamespace")) + writer.uint32(/* id 44, wireType 2 =*/354).string(message.phpMetadataNamespace); + if (message.rubyPackage != null && Object.hasOwnProperty.call(message, "rubyPackage")) + writer.uint32(/* id 45, wireType 2 =*/362).string(message.rubyPackage); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 50, wireType 2 =*/402).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + if (message[".google.api.resourceDefinition"] != null && message[".google.api.resourceDefinition"].length) + for (var i = 0; i < message[".google.api.resourceDefinition"].length; ++i) + $root.google.api.ResourceDescriptor.encode(message[".google.api.resourceDefinition"][i], writer.uint32(/* id 1053, wireType 2 =*/8426).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FileOptions + * @static + * @param {google.protobuf.IFileOptions} message FileOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FileOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FileOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FileOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FileOptions} FileOptions + * @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, 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(); + break; + } + case 8: { + message.javaOuterClassname = reader.string(); + break; + } + case 10: { + message.javaMultipleFiles = reader.bool(); + break; + } + case 20: { + message.javaGenerateEqualsAndHash = reader.bool(); + break; + } + case 27: { + message.javaStringCheckUtf8 = reader.bool(); + break; + } + case 9: { + message.optimizeFor = reader.int32(); + break; + } + case 11: { + message.goPackage = reader.string(); + break; + } + case 16: { + message.ccGenericServices = reader.bool(); + break; + } + case 17: { + message.javaGenericServices = reader.bool(); + break; + } + case 18: { + message.pyGenericServices = reader.bool(); + break; + } + case 23: { + message.deprecated = reader.bool(); + break; + } + case 31: { + message.ccEnableArenas = reader.bool(); + break; + } + case 36: { + message.objcClassPrefix = reader.string(); + break; + } + case 37: { + message.csharpNamespace = reader.string(); + break; + } + case 39: { + message.swiftPrefix = reader.string(); + break; + } + case 40: { + message.phpClassPrefix = reader.string(); + break; + } + case 41: { + message.phpNamespace = reader.string(); + break; + } + case 44: { + message.phpMetadataNamespace = reader.string(); + break; + } + case 45: { + message.rubyPackage = reader.string(); + break; + } + case 50: { + message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + case 1053: { + if (!(message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length)) + message[".google.api.resourceDefinition"] = []; + message[".google.api.resourceDefinition"].push($root.google.api.ResourceDescriptor.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FileOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FileOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FileOptions} FileOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FileOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FileOptions message. + * @function verify + * @memberof google.protobuf.FileOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FileOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) + if (!$util.isString(message.javaPackage)) + return "javaPackage: string expected"; + if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) + if (!$util.isString(message.javaOuterClassname)) + return "javaOuterClassname: string expected"; + if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) + if (typeof message.javaMultipleFiles !== "boolean") + return "javaMultipleFiles: boolean expected"; + if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) + if (typeof message.javaGenerateEqualsAndHash !== "boolean") + return "javaGenerateEqualsAndHash: boolean expected"; + if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) + if (typeof message.javaStringCheckUtf8 !== "boolean") + return "javaStringCheckUtf8: boolean expected"; + if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) + switch (message.optimizeFor) { + default: + return "optimizeFor: enum value expected"; + case 1: + case 2: + case 3: + break; + } + if (message.goPackage != null && message.hasOwnProperty("goPackage")) + if (!$util.isString(message.goPackage)) + return "goPackage: string expected"; + if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) + if (typeof message.ccGenericServices !== "boolean") + return "ccGenericServices: boolean expected"; + if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) + if (typeof message.javaGenericServices !== "boolean") + return "javaGenericServices: boolean expected"; + if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) + if (typeof message.pyGenericServices !== "boolean") + return "pyGenericServices: boolean expected"; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + if (typeof message.deprecated !== "boolean") + return "deprecated: boolean expected"; + if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) + if (typeof message.ccEnableArenas !== "boolean") + return "ccEnableArenas: boolean expected"; + if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) + if (!$util.isString(message.objcClassPrefix)) + return "objcClassPrefix: string expected"; + if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) + if (!$util.isString(message.csharpNamespace)) + return "csharpNamespace: string expected"; + if (message.swiftPrefix != null && message.hasOwnProperty("swiftPrefix")) + if (!$util.isString(message.swiftPrefix)) + return "swiftPrefix: string expected"; + if (message.phpClassPrefix != null && message.hasOwnProperty("phpClassPrefix")) + if (!$util.isString(message.phpClassPrefix)) + return "phpClassPrefix: string expected"; + if (message.phpNamespace != null && message.hasOwnProperty("phpNamespace")) + if (!$util.isString(message.phpNamespace)) + return "phpNamespace: string expected"; + if (message.phpMetadataNamespace != null && message.hasOwnProperty("phpMetadataNamespace")) + if (!$util.isString(message.phpMetadataNamespace)) + return "phpMetadataNamespace: string expected"; + if (message.rubyPackage != null && message.hasOwnProperty("rubyPackage")) + if (!$util.isString(message.rubyPackage)) + return "rubyPackage: string expected"; + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + if (message[".google.api.resourceDefinition"] != null && message.hasOwnProperty(".google.api.resourceDefinition")) { + if (!Array.isArray(message[".google.api.resourceDefinition"])) + return ".google.api.resourceDefinition: array expected"; + for (var i = 0; i < message[".google.api.resourceDefinition"].length; ++i) { + var error = $root.google.api.ResourceDescriptor.verify(message[".google.api.resourceDefinition"][i]); + if (error) + return ".google.api.resourceDefinition." + error; + } + } + return null; + }; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileOptions} FileOptions + */ + FileOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileOptions) + return object; + var message = new $root.google.protobuf.FileOptions(); + if (object.javaPackage != null) + message.javaPackage = String(object.javaPackage); + if (object.javaOuterClassname != null) + message.javaOuterClassname = String(object.javaOuterClassname); + if (object.javaMultipleFiles != null) + message.javaMultipleFiles = Boolean(object.javaMultipleFiles); + if (object.javaGenerateEqualsAndHash != null) + message.javaGenerateEqualsAndHash = Boolean(object.javaGenerateEqualsAndHash); + if (object.javaStringCheckUtf8 != null) + message.javaStringCheckUtf8 = Boolean(object.javaStringCheckUtf8); + switch (object.optimizeFor) { + default: + if (typeof object.optimizeFor === "number") { + message.optimizeFor = object.optimizeFor; + break; + } + break; + case "SPEED": + case 1: + message.optimizeFor = 1; + break; + case "CODE_SIZE": + case 2: + message.optimizeFor = 2; + break; + case "LITE_RUNTIME": + case 3: + message.optimizeFor = 3; + break; + } + if (object.goPackage != null) + message.goPackage = String(object.goPackage); + if (object.ccGenericServices != null) + message.ccGenericServices = Boolean(object.ccGenericServices); + if (object.javaGenericServices != null) + message.javaGenericServices = Boolean(object.javaGenericServices); + if (object.pyGenericServices != null) + message.pyGenericServices = Boolean(object.pyGenericServices); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.ccEnableArenas != null) + message.ccEnableArenas = Boolean(object.ccEnableArenas); + if (object.objcClassPrefix != null) + message.objcClassPrefix = String(object.objcClassPrefix); + if (object.csharpNamespace != null) + message.csharpNamespace = String(object.csharpNamespace); + if (object.swiftPrefix != null) + message.swiftPrefix = String(object.swiftPrefix); + if (object.phpClassPrefix != null) + message.phpClassPrefix = String(object.phpClassPrefix); + if (object.phpNamespace != null) + message.phpNamespace = String(object.phpNamespace); + if (object.phpMetadataNamespace != null) + message.phpMetadataNamespace = String(object.phpMetadataNamespace); + if (object.rubyPackage != null) + message.rubyPackage = String(object.rubyPackage); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FileOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resourceDefinition"]) { + if (!Array.isArray(object[".google.api.resourceDefinition"])) + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: array expected"); + message[".google.api.resourceDefinition"] = []; + for (var i = 0; i < object[".google.api.resourceDefinition"].length; ++i) { + if (typeof object[".google.api.resourceDefinition"][i] !== "object") + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: object expected"); + message[".google.api.resourceDefinition"][i] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resourceDefinition"][i]); + } + } + return message; + }; + + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileOptions + * @static + * @param {google.protobuf.FileOptions} message FileOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.resourceDefinition"] = []; + } + if (options.defaults) { + object.javaPackage = ""; + object.javaOuterClassname = ""; + object.optimizeFor = options.enums === String ? "SPEED" : 1; + object.javaMultipleFiles = false; + object.goPackage = ""; + object.ccGenericServices = false; + object.javaGenericServices = false; + object.pyGenericServices = false; + object.javaGenerateEqualsAndHash = false; + object.deprecated = false; + object.javaStringCheckUtf8 = false; + object.ccEnableArenas = true; + object.objcClassPrefix = ""; + object.csharpNamespace = ""; + object.swiftPrefix = ""; + object.phpClassPrefix = ""; + object.phpNamespace = ""; + object.phpMetadataNamespace = ""; + object.rubyPackage = ""; + object.features = null; + } + if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) + object.javaPackage = message.javaPackage; + if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) + object.javaOuterClassname = message.javaOuterClassname; + if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) + object.optimizeFor = options.enums === String ? $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] === undefined ? message.optimizeFor : $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] : message.optimizeFor; + if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) + object.javaMultipleFiles = message.javaMultipleFiles; + if (message.goPackage != null && message.hasOwnProperty("goPackage")) + object.goPackage = message.goPackage; + if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) + object.ccGenericServices = message.ccGenericServices; + if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) + object.javaGenericServices = message.javaGenericServices; + if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) + object.pyGenericServices = message.pyGenericServices; + if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) + object.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) + object.javaStringCheckUtf8 = message.javaStringCheckUtf8; + if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) + object.ccEnableArenas = message.ccEnableArenas; + if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) + object.objcClassPrefix = message.objcClassPrefix; + if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) + object.csharpNamespace = message.csharpNamespace; + if (message.swiftPrefix != null && message.hasOwnProperty("swiftPrefix")) + object.swiftPrefix = message.swiftPrefix; + if (message.phpClassPrefix != null && message.hasOwnProperty("phpClassPrefix")) + object.phpClassPrefix = message.phpClassPrefix; + if (message.phpNamespace != null && message.hasOwnProperty("phpNamespace")) + object.phpNamespace = message.phpNamespace; + if (message.phpMetadataNamespace != null && message.hasOwnProperty("phpMetadataNamespace")) + object.phpMetadataNamespace = message.phpMetadataNamespace; + if (message.rubyPackage != null && message.hasOwnProperty("rubyPackage")) + object.rubyPackage = message.rubyPackage; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length) { + object[".google.api.resourceDefinition"] = []; + for (var j = 0; j < message[".google.api.resourceDefinition"].length; ++j) + object[".google.api.resourceDefinition"][j] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resourceDefinition"][j], options); + } + return object; + }; + + /** + * Converts this FileOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FileOptions + * @instance + * @returns {Object.} JSON object + */ + FileOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FileOptions + * @function getTypeUrl + * @memberof google.protobuf.FileOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileOptions"; + }; + + /** + * OptimizeMode enum. + * @name google.protobuf.FileOptions.OptimizeMode + * @enum {number} + * @property {number} SPEED=1 SPEED value + * @property {number} CODE_SIZE=2 CODE_SIZE value + * @property {number} LITE_RUNTIME=3 LITE_RUNTIME value + */ + FileOptions.OptimizeMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "SPEED"] = 1; + values[valuesById[2] = "CODE_SIZE"] = 2; + values[valuesById[3] = "LITE_RUNTIME"] = 3; + return values; + })(); + + return FileOptions; + })(); + + protobuf.MessageOptions = (function() { + + /** + * Properties of a MessageOptions. + * @memberof google.protobuf + * @interface IMessageOptions + * @property {boolean|null} [messageSetWireFormat] MessageOptions messageSetWireFormat + * @property {boolean|null} [noStandardDescriptorAccessor] MessageOptions noStandardDescriptorAccessor + * @property {boolean|null} [deprecated] MessageOptions deprecated + * @property {boolean|null} [mapEntry] MessageOptions mapEntry + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] MessageOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] MessageOptions features + * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption + * @property {google.api.IResourceDescriptor|null} [".google.api.resource"] MessageOptions .google.api.resource + */ + + /** + * Constructs a new MessageOptions. + * @memberof google.protobuf + * @classdesc Represents a MessageOptions. + * @implements IMessageOptions + * @constructor + * @param {google.protobuf.IMessageOptions=} [properties] Properties to set + */ + function MessageOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MessageOptions messageSetWireFormat. + * @member {boolean} messageSetWireFormat + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.messageSetWireFormat = false; + + /** + * MessageOptions noStandardDescriptorAccessor. + * @member {boolean} noStandardDescriptorAccessor + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.noStandardDescriptorAccessor = false; + + /** + * MessageOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecated = false; + + /** + * MessageOptions mapEntry. + * @member {boolean} mapEntry + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.mapEntry = false; + + /** + * MessageOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + + /** + * MessageOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.features = null; + + /** + * MessageOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * MessageOptions .google.api.resource. + * @member {google.api.IResourceDescriptor|null|undefined} .google.api.resource + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype[".google.api.resource"] = null; + + /** + * Creates a new MessageOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.MessageOptions + * @static + * @param {google.protobuf.IMessageOptions=} [properties] Properties to set + * @returns {google.protobuf.MessageOptions} MessageOptions instance + */ + MessageOptions.create = function create(properties) { + return new MessageOptions(properties); + }; + + /** + * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.MessageOptions + * @static + * @param {google.protobuf.IMessageOptions} message MessageOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MessageOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.messageSetWireFormat != null && Object.hasOwnProperty.call(message, "messageSetWireFormat")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.messageSetWireFormat); + if (message.noStandardDescriptorAccessor != null && Object.hasOwnProperty.call(message, "noStandardDescriptorAccessor")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.noStandardDescriptorAccessor); + if (message.deprecated != null && Object.hasOwnProperty.call(message, "deprecated")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.deprecated); + if (message.mapEntry != null && Object.hasOwnProperty.call(message, "mapEntry")) + writer.uint32(/* id 7, wireType 0 =*/56).bool(message.mapEntry); + if (message.deprecatedLegacyJsonFieldConflicts != null && Object.hasOwnProperty.call(message, "deprecatedLegacyJsonFieldConflicts")) + writer.uint32(/* id 11, wireType 0 =*/88).bool(message.deprecatedLegacyJsonFieldConflicts); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + if (message[".google.api.resource"] != null && Object.hasOwnProperty.call(message, ".google.api.resource")) + $root.google.api.ResourceDescriptor.encode(message[".google.api.resource"], writer.uint32(/* id 1053, wireType 2 =*/8426).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.MessageOptions + * @static + * @param {google.protobuf.IMessageOptions} message MessageOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MessageOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MessageOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.MessageOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.MessageOptions} MessageOptions + * @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, 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(); + break; + } + case 2: { + message.noStandardDescriptorAccessor = reader.bool(); + break; + } + case 3: { + message.deprecated = reader.bool(); + break; + } + case 7: { + message.mapEntry = reader.bool(); + break; + } + case 11: { + message.deprecatedLegacyJsonFieldConflicts = reader.bool(); + break; + } + case 12: { + message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + case 1053: { + message[".google.api.resource"] = $root.google.api.ResourceDescriptor.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MessageOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.MessageOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.MessageOptions} MessageOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MessageOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MessageOptions message. + * @function verify + * @memberof google.protobuf.MessageOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MessageOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) + if (typeof message.messageSetWireFormat !== "boolean") + return "messageSetWireFormat: boolean expected"; + if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) + if (typeof message.noStandardDescriptorAccessor !== "boolean") + return "noStandardDescriptorAccessor: boolean expected"; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + if (typeof message.deprecated !== "boolean") + return "deprecated: boolean expected"; + if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) + if (typeof message.mapEntry !== "boolean") + return "mapEntry: boolean expected"; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + if (typeof message.deprecatedLegacyJsonFieldConflicts !== "boolean") + return "deprecatedLegacyJsonFieldConflicts: boolean expected"; + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) { + var error = $root.google.api.ResourceDescriptor.verify(message[".google.api.resource"]); + if (error) + return ".google.api.resource." + error; + } + return null; + }; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MessageOptions} MessageOptions + */ + MessageOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MessageOptions) + return object; + var message = new $root.google.protobuf.MessageOptions(); + if (object.messageSetWireFormat != null) + message.messageSetWireFormat = Boolean(object.messageSetWireFormat); + if (object.noStandardDescriptorAccessor != null) + message.noStandardDescriptorAccessor = Boolean(object.noStandardDescriptorAccessor); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.mapEntry != null) + message.mapEntry = Boolean(object.mapEntry); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MessageOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resource"] != null) { + if (typeof object[".google.api.resource"] !== "object") + throw TypeError(".google.protobuf.MessageOptions..google.api.resource: object expected"); + message[".google.api.resource"] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resource"]); + } + return message; + }; + + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {google.protobuf.MessageOptions} message MessageOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MessageOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.messageSetWireFormat = false; + object.noStandardDescriptorAccessor = false; + object.deprecated = false; + object.mapEntry = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + object[".google.api.resource"] = null; + } + if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) + object.messageSetWireFormat = message.messageSetWireFormat; + if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) + object.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) + object.mapEntry = message.mapEntry; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) + object[".google.api.resource"] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resource"], options); + return object; + }; + + /** + * Converts this MessageOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MessageOptions + * @instance + * @returns {Object.} JSON object + */ + MessageOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MessageOptions + * @function getTypeUrl + * @memberof google.protobuf.MessageOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MessageOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MessageOptions"; + }; + + return MessageOptions; + })(); + + protobuf.FieldOptions = (function() { + + /** + * Properties of a FieldOptions. + * @memberof google.protobuf + * @interface IFieldOptions + * @property {google.protobuf.FieldOptions.CType|null} [ctype] FieldOptions ctype + * @property {boolean|null} [packed] FieldOptions packed + * @property {google.protobuf.FieldOptions.JSType|null} [jstype] FieldOptions jstype + * @property {boolean|null} [lazy] FieldOptions lazy + * @property {boolean|null} [unverifiedLazy] FieldOptions unverifiedLazy + * @property {boolean|null} [deprecated] FieldOptions deprecated + * @property {boolean|null} [weak] FieldOptions weak + * @property {boolean|null} [debugRedact] FieldOptions debugRedact + * @property {google.protobuf.FieldOptions.OptionRetention|null} [retention] FieldOptions retention + * @property {Array.|null} [targets] FieldOptions targets + * @property {Array.|null} [editionDefaults] FieldOptions editionDefaults + * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] FieldOptions featureSupport + * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption + * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior + * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference + */ + + /** + * Constructs a new FieldOptions. + * @memberof google.protobuf + * @classdesc Represents a FieldOptions. + * @implements IFieldOptions + * @constructor + * @param {google.protobuf.IFieldOptions=} [properties] Properties to set + */ + function FieldOptions(properties) { + this.targets = []; + this.editionDefaults = []; + this.uninterpretedOption = []; + this[".google.api.fieldBehavior"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldOptions ctype. + * @member {google.protobuf.FieldOptions.CType} ctype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.ctype = 0; + + /** + * FieldOptions packed. + * @member {boolean} packed + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.packed = false; + + /** + * FieldOptions jstype. + * @member {google.protobuf.FieldOptions.JSType} jstype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.jstype = 0; + + /** + * FieldOptions lazy. + * @member {boolean} lazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.lazy = false; + + /** + * FieldOptions unverifiedLazy. + * @member {boolean} unverifiedLazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.unverifiedLazy = false; + + /** + * FieldOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.deprecated = false; + + /** + * FieldOptions weak. + * @member {boolean} weak + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.weak = false; + + /** + * FieldOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.debugRedact = false; + + /** + * FieldOptions retention. + * @member {google.protobuf.FieldOptions.OptionRetention} retention + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.retention = 0; + + /** + * FieldOptions targets. + * @member {Array.} targets + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.targets = $util.emptyArray; + + /** + * FieldOptions editionDefaults. + * @member {Array.} editionDefaults + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.editionDefaults = $util.emptyArray; + + /** + * FieldOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.features = null; + + /** + * FieldOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.featureSupport = null; + + /** + * FieldOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * FieldOptions .google.api.fieldBehavior. + * @member {Array.} .google.api.fieldBehavior + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.fieldBehavior"] = $util.emptyArray; + + /** + * FieldOptions .google.api.resourceReference. + * @member {google.api.IResourceReference|null|undefined} .google.api.resourceReference + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.resourceReference"] = null; + + /** + * Creates a new FieldOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions + * @static + * @param {google.protobuf.IFieldOptions=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions} FieldOptions instance + */ + FieldOptions.create = function create(properties) { + return new FieldOptions(properties); + }; + + /** + * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions + * @static + * @param {google.protobuf.IFieldOptions} message FieldOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.ctype != null && Object.hasOwnProperty.call(message, "ctype")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.ctype); + if (message.packed != null && Object.hasOwnProperty.call(message, "packed")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.packed); + if (message.deprecated != null && Object.hasOwnProperty.call(message, "deprecated")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.deprecated); + if (message.lazy != null && Object.hasOwnProperty.call(message, "lazy")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.lazy); + if (message.jstype != null && Object.hasOwnProperty.call(message, "jstype")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jstype); + if (message.weak != null && Object.hasOwnProperty.call(message, "weak")) + writer.uint32(/* id 10, wireType 0 =*/80).bool(message.weak); + if (message.unverifiedLazy != null && Object.hasOwnProperty.call(message, "unverifiedLazy")) + writer.uint32(/* id 15, wireType 0 =*/120).bool(message.unverifiedLazy); + if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) + writer.uint32(/* id 16, wireType 0 =*/128).bool(message.debugRedact); + if (message.retention != null && Object.hasOwnProperty.call(message, "retention")) + writer.uint32(/* id 17, wireType 0 =*/136).int32(message.retention); + if (message.targets != null && message.targets.length) + for (var i = 0; i < message.targets.length; ++i) + writer.uint32(/* id 19, wireType 0 =*/152).int32(message.targets[i]); + if (message.editionDefaults != null && message.editionDefaults.length) + for (var i = 0; i < message.editionDefaults.length; ++i) + $root.google.protobuf.FieldOptions.EditionDefault.encode(message.editionDefaults[i], writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + if (message[".google.api.fieldBehavior"] != null && message[".google.api.fieldBehavior"].length) + for (var i = 0; i < message[".google.api.fieldBehavior"].length; ++i) + writer.uint32(/* id 1052, wireType 0 =*/8416).int32(message[".google.api.fieldBehavior"][i]); + if (message[".google.api.resourceReference"] != null && Object.hasOwnProperty.call(message, ".google.api.resourceReference")) + $root.google.api.ResourceReference.encode(message[".google.api.resourceReference"], writer.uint32(/* id 1055, wireType 2 =*/8442).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions + * @static + * @param {google.protobuf.IFieldOptions} message FieldOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FieldOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions} FieldOptions + * @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, 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(); + break; + } + case 2: { + message.packed = reader.bool(); + break; + } + case 6: { + message.jstype = reader.int32(); + break; + } + case 5: { + message.lazy = reader.bool(); + break; + } + case 15: { + message.unverifiedLazy = reader.bool(); + break; + } + case 3: { + message.deprecated = reader.bool(); + break; + } + case 10: { + message.weak = reader.bool(); + break; + } + case 16: { + message.debugRedact = reader.bool(); + break; + } + case 17: { + message.retention = reader.int32(); + break; + } + case 19: { + if (!(message.targets && message.targets.length)) + message.targets = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.targets.push(reader.int32()); + } else + message.targets.push(reader.int32()); + break; + } + case 20: { + if (!(message.editionDefaults && message.editionDefaults.length)) + message.editionDefaults = []; + message.editionDefaults.push($root.google.protobuf.FieldOptions.EditionDefault.decode(reader, reader.uint32())); + break; + } + case 21: { + message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 22: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + case 1052: { + if (!(message[".google.api.fieldBehavior"] && message[".google.api.fieldBehavior"].length)) + message[".google.api.fieldBehavior"] = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message[".google.api.fieldBehavior"].push(reader.int32()); + } else + message[".google.api.fieldBehavior"].push(reader.int32()); + break; + } + case 1055: { + message[".google.api.resourceReference"] = $root.google.api.ResourceReference.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FieldOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions} FieldOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FieldOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FieldOptions message. + * @function verify + * @memberof google.protobuf.FieldOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FieldOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.ctype != null && message.hasOwnProperty("ctype")) + switch (message.ctype) { + default: + return "ctype: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.packed != null && message.hasOwnProperty("packed")) + if (typeof message.packed !== "boolean") + return "packed: boolean expected"; + if (message.jstype != null && message.hasOwnProperty("jstype")) + switch (message.jstype) { + default: + return "jstype: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.lazy != null && message.hasOwnProperty("lazy")) + if (typeof message.lazy !== "boolean") + return "lazy: boolean expected"; + if (message.unverifiedLazy != null && message.hasOwnProperty("unverifiedLazy")) + if (typeof message.unverifiedLazy !== "boolean") + return "unverifiedLazy: boolean expected"; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + if (typeof message.deprecated !== "boolean") + return "deprecated: boolean expected"; + if (message.weak != null && message.hasOwnProperty("weak")) + if (typeof message.weak !== "boolean") + return "weak: boolean expected"; + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + if (typeof message.debugRedact !== "boolean") + return "debugRedact: boolean expected"; + if (message.retention != null && message.hasOwnProperty("retention")) + switch (message.retention) { + default: + return "retention: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.targets != null && message.hasOwnProperty("targets")) { + if (!Array.isArray(message.targets)) + return "targets: array expected"; + for (var i = 0; i < message.targets.length; ++i) + switch (message.targets[i]) { + default: + return "targets: enum value[] expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + break; + } + } + if (message.editionDefaults != null && message.hasOwnProperty("editionDefaults")) { + if (!Array.isArray(message.editionDefaults)) + return "editionDefaults: array expected"; + for (var i = 0; i < message.editionDefaults.length; ++i) { + var error = $root.google.protobuf.FieldOptions.EditionDefault.verify(message.editionDefaults[i]); + if (error) + return "editionDefaults." + error; + } + } + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + if (message[".google.api.fieldBehavior"] != null && message.hasOwnProperty(".google.api.fieldBehavior")) { + if (!Array.isArray(message[".google.api.fieldBehavior"])) + return ".google.api.fieldBehavior: array expected"; + for (var i = 0; i < message[".google.api.fieldBehavior"].length; ++i) + switch (message[".google.api.fieldBehavior"][i]) { + default: + return ".google.api.fieldBehavior: enum value[] expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + break; + } + } + if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) { + var error = $root.google.api.ResourceReference.verify(message[".google.api.resourceReference"]); + if (error) + return ".google.api.resourceReference." + error; + } + return null; + }; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions} FieldOptions + */ + FieldOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions) + return object; + var message = new $root.google.protobuf.FieldOptions(); + switch (object.ctype) { + default: + if (typeof object.ctype === "number") { + message.ctype = object.ctype; + break; + } + break; + case "STRING": + case 0: + message.ctype = 0; + break; + case "CORD": + case 1: + message.ctype = 1; + break; + case "STRING_PIECE": + case 2: + message.ctype = 2; + break; + } + if (object.packed != null) + message.packed = Boolean(object.packed); + switch (object.jstype) { + default: + if (typeof object.jstype === "number") { + message.jstype = object.jstype; + break; + } + break; + case "JS_NORMAL": + case 0: + message.jstype = 0; + break; + case "JS_STRING": + case 1: + message.jstype = 1; + break; + case "JS_NUMBER": + case 2: + message.jstype = 2; + break; + } + if (object.lazy != null) + message.lazy = Boolean(object.lazy); + if (object.unverifiedLazy != null) + message.unverifiedLazy = Boolean(object.unverifiedLazy); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.weak != null) + message.weak = Boolean(object.weak); + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + switch (object.retention) { + default: + if (typeof object.retention === "number") { + message.retention = object.retention; + break; + } + break; + case "RETENTION_UNKNOWN": + case 0: + message.retention = 0; + break; + case "RETENTION_RUNTIME": + case 1: + message.retention = 1; + break; + case "RETENTION_SOURCE": + case 2: + message.retention = 2; + break; + } + if (object.targets) { + if (!Array.isArray(object.targets)) + throw TypeError(".google.protobuf.FieldOptions.targets: array expected"); + message.targets = []; + for (var i = 0; i < object.targets.length; ++i) + switch (object.targets[i]) { + default: + if (typeof object.targets[i] === "number") { + message.targets[i] = object.targets[i]; + break; + } + case "TARGET_TYPE_UNKNOWN": + case 0: + message.targets[i] = 0; + break; + case "TARGET_TYPE_FILE": + case 1: + message.targets[i] = 1; + break; + case "TARGET_TYPE_EXTENSION_RANGE": + case 2: + message.targets[i] = 2; + break; + case "TARGET_TYPE_MESSAGE": + case 3: + message.targets[i] = 3; + break; + case "TARGET_TYPE_FIELD": + case 4: + message.targets[i] = 4; + break; + case "TARGET_TYPE_ONEOF": + case 5: + message.targets[i] = 5; + break; + case "TARGET_TYPE_ENUM": + case 6: + message.targets[i] = 6; + break; + case "TARGET_TYPE_ENUM_ENTRY": + case 7: + message.targets[i] = 7; + break; + case "TARGET_TYPE_SERVICE": + case 8: + message.targets[i] = 8; + break; + case "TARGET_TYPE_METHOD": + case 9: + message.targets[i] = 9; + break; + } + } + if (object.editionDefaults) { + if (!Array.isArray(object.editionDefaults)) + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: array expected"); + message.editionDefaults = []; + for (var i = 0; i < object.editionDefaults.length; ++i) { + if (typeof object.editionDefaults[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: object expected"); + message.editionDefaults[i] = $root.google.protobuf.FieldOptions.EditionDefault.fromObject(object.editionDefaults[i]); + } + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FieldOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.FieldOptions.featureSupport: object expected"); + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.fromObject(object.featureSupport); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.fieldBehavior"]) { + if (!Array.isArray(object[".google.api.fieldBehavior"])) + throw TypeError(".google.protobuf.FieldOptions..google.api.fieldBehavior: array expected"); + message[".google.api.fieldBehavior"] = []; + for (var i = 0; i < object[".google.api.fieldBehavior"].length; ++i) + switch (object[".google.api.fieldBehavior"][i]) { + default: + if (typeof object[".google.api.fieldBehavior"][i] === "number") { + message[".google.api.fieldBehavior"][i] = object[".google.api.fieldBehavior"][i]; + break; + } + case "FIELD_BEHAVIOR_UNSPECIFIED": + case 0: + message[".google.api.fieldBehavior"][i] = 0; + break; + case "OPTIONAL": + case 1: + message[".google.api.fieldBehavior"][i] = 1; + break; + case "REQUIRED": + case 2: + message[".google.api.fieldBehavior"][i] = 2; + break; + case "OUTPUT_ONLY": + case 3: + message[".google.api.fieldBehavior"][i] = 3; + break; + case "INPUT_ONLY": + case 4: + message[".google.api.fieldBehavior"][i] = 4; + break; + case "IMMUTABLE": + case 5: + message[".google.api.fieldBehavior"][i] = 5; + break; + case "UNORDERED_LIST": + case 6: + message[".google.api.fieldBehavior"][i] = 6; + break; + case "NON_EMPTY_DEFAULT": + case 7: + message[".google.api.fieldBehavior"][i] = 7; + break; + case "IDENTIFIER": + case 8: + message[".google.api.fieldBehavior"][i] = 8; + break; + } + } + if (object[".google.api.resourceReference"] != null) { + if (typeof object[".google.api.resourceReference"] !== "object") + throw TypeError(".google.protobuf.FieldOptions..google.api.resourceReference: object expected"); + message[".google.api.resourceReference"] = $root.google.api.ResourceReference.fromObject(object[".google.api.resourceReference"]); + } + return message; + }; + + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {google.protobuf.FieldOptions} message FieldOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.targets = []; + object.editionDefaults = []; + object.uninterpretedOption = []; + object[".google.api.fieldBehavior"] = []; + } + if (options.defaults) { + object.ctype = options.enums === String ? "STRING" : 0; + object.packed = false; + object.deprecated = false; + object.lazy = false; + object.jstype = options.enums === String ? "JS_NORMAL" : 0; + object.weak = false; + object.unverifiedLazy = false; + object.debugRedact = false; + object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; + object.features = null; + object.featureSupport = null; + object[".google.api.resourceReference"] = null; + } + if (message.ctype != null && message.hasOwnProperty("ctype")) + object.ctype = options.enums === String ? $root.google.protobuf.FieldOptions.CType[message.ctype] === undefined ? message.ctype : $root.google.protobuf.FieldOptions.CType[message.ctype] : message.ctype; + if (message.packed != null && message.hasOwnProperty("packed")) + object.packed = message.packed; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.lazy != null && message.hasOwnProperty("lazy")) + object.lazy = message.lazy; + if (message.jstype != null && message.hasOwnProperty("jstype")) + object.jstype = options.enums === String ? $root.google.protobuf.FieldOptions.JSType[message.jstype] === undefined ? message.jstype : $root.google.protobuf.FieldOptions.JSType[message.jstype] : message.jstype; + if (message.weak != null && message.hasOwnProperty("weak")) + object.weak = message.weak; + if (message.unverifiedLazy != null && message.hasOwnProperty("unverifiedLazy")) + object.unverifiedLazy = message.unverifiedLazy; + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.retention != null && message.hasOwnProperty("retention")) + object.retention = options.enums === String ? $root.google.protobuf.FieldOptions.OptionRetention[message.retention] === undefined ? message.retention : $root.google.protobuf.FieldOptions.OptionRetention[message.retention] : message.retention; + if (message.targets && message.targets.length) { + object.targets = []; + for (var j = 0; j < message.targets.length; ++j) + object.targets[j] = options.enums === String ? $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] === undefined ? message.targets[j] : $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] : message.targets[j]; + } + if (message.editionDefaults && message.editionDefaults.length) { + object.editionDefaults = []; + for (var j = 0; j < message.editionDefaults.length; ++j) + object.editionDefaults[j] = $root.google.protobuf.FieldOptions.EditionDefault.toObject(message.editionDefaults[j], options); + } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) + object.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.toObject(message.featureSupport, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.fieldBehavior"] && message[".google.api.fieldBehavior"].length) { + object[".google.api.fieldBehavior"] = []; + for (var j = 0; j < message[".google.api.fieldBehavior"].length; ++j) + object[".google.api.fieldBehavior"][j] = options.enums === String ? $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] === undefined ? message[".google.api.fieldBehavior"][j] : $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] : message[".google.api.fieldBehavior"][j]; + } + if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) + object[".google.api.resourceReference"] = $root.google.api.ResourceReference.toObject(message[".google.api.resourceReference"], options); + return object; + }; + + /** + * Converts this FieldOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions + * @instance + * @returns {Object.} JSON object + */ + FieldOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldOptions + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions"; + }; + + /** + * CType enum. + * @name google.protobuf.FieldOptions.CType + * @enum {number} + * @property {number} STRING=0 STRING value + * @property {number} CORD=1 CORD value + * @property {number} STRING_PIECE=2 STRING_PIECE value + */ + FieldOptions.CType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STRING"] = 0; + values[valuesById[1] = "CORD"] = 1; + values[valuesById[2] = "STRING_PIECE"] = 2; + return values; + })(); + + /** + * JSType enum. + * @name google.protobuf.FieldOptions.JSType + * @enum {number} + * @property {number} JS_NORMAL=0 JS_NORMAL value + * @property {number} JS_STRING=1 JS_STRING value + * @property {number} JS_NUMBER=2 JS_NUMBER value + */ + FieldOptions.JSType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JS_NORMAL"] = 0; + values[valuesById[1] = "JS_STRING"] = 1; + values[valuesById[2] = "JS_NUMBER"] = 2; + return values; + })(); + + /** + * OptionRetention enum. + * @name google.protobuf.FieldOptions.OptionRetention + * @enum {number} + * @property {number} RETENTION_UNKNOWN=0 RETENTION_UNKNOWN value + * @property {number} RETENTION_RUNTIME=1 RETENTION_RUNTIME value + * @property {number} RETENTION_SOURCE=2 RETENTION_SOURCE value + */ + FieldOptions.OptionRetention = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "RETENTION_UNKNOWN"] = 0; + values[valuesById[1] = "RETENTION_RUNTIME"] = 1; + values[valuesById[2] = "RETENTION_SOURCE"] = 2; + return values; + })(); + + /** + * OptionTargetType enum. + * @name google.protobuf.FieldOptions.OptionTargetType + * @enum {number} + * @property {number} TARGET_TYPE_UNKNOWN=0 TARGET_TYPE_UNKNOWN value + * @property {number} TARGET_TYPE_FILE=1 TARGET_TYPE_FILE value + * @property {number} TARGET_TYPE_EXTENSION_RANGE=2 TARGET_TYPE_EXTENSION_RANGE value + * @property {number} TARGET_TYPE_MESSAGE=3 TARGET_TYPE_MESSAGE value + * @property {number} TARGET_TYPE_FIELD=4 TARGET_TYPE_FIELD value + * @property {number} TARGET_TYPE_ONEOF=5 TARGET_TYPE_ONEOF value + * @property {number} TARGET_TYPE_ENUM=6 TARGET_TYPE_ENUM value + * @property {number} TARGET_TYPE_ENUM_ENTRY=7 TARGET_TYPE_ENUM_ENTRY value + * @property {number} TARGET_TYPE_SERVICE=8 TARGET_TYPE_SERVICE value + * @property {number} TARGET_TYPE_METHOD=9 TARGET_TYPE_METHOD value + */ + FieldOptions.OptionTargetType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TARGET_TYPE_UNKNOWN"] = 0; + values[valuesById[1] = "TARGET_TYPE_FILE"] = 1; + values[valuesById[2] = "TARGET_TYPE_EXTENSION_RANGE"] = 2; + values[valuesById[3] = "TARGET_TYPE_MESSAGE"] = 3; + values[valuesById[4] = "TARGET_TYPE_FIELD"] = 4; + values[valuesById[5] = "TARGET_TYPE_ONEOF"] = 5; + values[valuesById[6] = "TARGET_TYPE_ENUM"] = 6; + values[valuesById[7] = "TARGET_TYPE_ENUM_ENTRY"] = 7; + values[valuesById[8] = "TARGET_TYPE_SERVICE"] = 8; + values[valuesById[9] = "TARGET_TYPE_METHOD"] = 9; + return values; + })(); + + FieldOptions.EditionDefault = (function() { + + /** + * Properties of an EditionDefault. + * @memberof google.protobuf.FieldOptions + * @interface IEditionDefault + * @property {google.protobuf.Edition|null} [edition] EditionDefault edition + * @property {string|null} [value] EditionDefault value + */ + + /** + * Constructs a new EditionDefault. + * @memberof google.protobuf.FieldOptions + * @classdesc Represents an EditionDefault. + * @implements IEditionDefault + * @constructor + * @param {google.protobuf.FieldOptions.IEditionDefault=} [properties] Properties to set + */ + function EditionDefault(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + */ + EditionDefault.prototype.edition = 0; + + /** + * EditionDefault value. + * @member {string} value + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + */ + EditionDefault.prototype.value = ""; + + /** + * Creates a new EditionDefault instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.IEditionDefault=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault instance + */ + EditionDefault.create = function create(properties) { + return new EditionDefault(properties); + }; + + /** + * Encodes the specified EditionDefault message. Does not implicitly {@link google.protobuf.FieldOptions.EditionDefault.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.IEditionDefault} message EditionDefault message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EditionDefault.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.value != null && Object.hasOwnProperty.call(message, "value")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.value); + if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + return writer; + }; + + /** + * Encodes the specified EditionDefault message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.EditionDefault.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.IEditionDefault} message EditionDefault message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EditionDefault.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an EditionDefault message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault + * @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, 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(); + break; + } + case 2: { + message.value = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an EditionDefault message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EditionDefault.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an EditionDefault message. + * @function verify + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EditionDefault.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.edition != null && message.hasOwnProperty("edition")) + switch (message.edition) { + default: + return "edition: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.value != null && message.hasOwnProperty("value")) + if (!$util.isString(message.value)) + return "value: string expected"; + return null; + }; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault + */ + EditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions.EditionDefault) + return object; + var message = new $root.google.protobuf.FieldOptions.EditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + if (object.value != null) + message.value = String(object.value); + return message; + }; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + }; + + return EditionDefault; + })(); + + FieldOptions.FeatureSupport = (function() { + + /** + * Properties of a FeatureSupport. + * @memberof google.protobuf.FieldOptions + * @interface IFeatureSupport + * @property {google.protobuf.Edition|null} [editionIntroduced] FeatureSupport editionIntroduced + * @property {google.protobuf.Edition|null} [editionDeprecated] FeatureSupport editionDeprecated + * @property {string|null} [deprecationWarning] FeatureSupport deprecationWarning + * @property {google.protobuf.Edition|null} [editionRemoved] FeatureSupport editionRemoved + */ + + /** + * Constructs a new FeatureSupport. + * @memberof google.protobuf.FieldOptions + * @classdesc Represents a FeatureSupport. + * @implements IFeatureSupport + * @constructor + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + */ + function FeatureSupport(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSupport editionIntroduced. + * @member {google.protobuf.Edition} editionIntroduced + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + */ + FeatureSupport.prototype.editionIntroduced = 0; + + /** + * FeatureSupport editionDeprecated. + * @member {google.protobuf.Edition} editionDeprecated + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + */ + FeatureSupport.prototype.editionDeprecated = 0; + + /** + * FeatureSupport deprecationWarning. + * @member {string} deprecationWarning + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + */ + FeatureSupport.prototype.deprecationWarning = ""; + + /** + * FeatureSupport editionRemoved. + * @member {google.protobuf.Edition} editionRemoved + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + */ + FeatureSupport.prototype.editionRemoved = 0; + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport instance + */ + FeatureSupport.create = function create(properties) { + return new FeatureSupport(properties); + }; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.editionIntroduced != null && Object.hasOwnProperty.call(message, "editionIntroduced")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.editionIntroduced); + if (message.editionDeprecated != null && Object.hasOwnProperty.call(message, "editionDeprecated")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.editionDeprecated); + if (message.deprecationWarning != null && Object.hasOwnProperty.call(message, "deprecationWarning")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.deprecationWarning); + if (message.editionRemoved != null && Object.hasOwnProperty.call(message, "editionRemoved")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.editionRemoved); + return writer; + }; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.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.FeatureSupport(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.editionIntroduced = reader.int32(); + break; + } + case 2: { + message.editionDeprecated = reader.int32(); + break; + } + case 3: { + message.deprecationWarning = reader.string(); + break; + } + case 4: { + message.editionRemoved = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSupport message. + * @function verify + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSupport.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + switch (message.editionIntroduced) { + default: + return "editionIntroduced: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + switch (message.editionDeprecated) { + default: + return "editionDeprecated: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + if (!$util.isString(message.deprecationWarning)) + return "deprecationWarning: string expected"; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + switch (message.editionRemoved) { + default: + return "editionRemoved: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * Creates a FeatureSupport message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + */ + FeatureSupport.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions.FeatureSupport) + return object; + var message = new $root.google.protobuf.FieldOptions.FeatureSupport(); + switch (object.editionIntroduced) { + default: + if (typeof object.editionIntroduced === "number") { + message.editionIntroduced = object.editionIntroduced; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.editionIntroduced = 0; + break; + case "EDITION_LEGACY": + case 900: + message.editionIntroduced = 900; + break; + case "EDITION_PROTO2": + case 998: + message.editionIntroduced = 998; + break; + case "EDITION_PROTO3": + case 999: + message.editionIntroduced = 999; + break; + case "EDITION_2023": + case 1000: + message.editionIntroduced = 1000; + break; + case "EDITION_2024": + case 1001: + message.editionIntroduced = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.editionIntroduced = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.editionIntroduced = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.editionIntroduced = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.editionIntroduced = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.editionIntroduced = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.editionIntroduced = 2147483647; + break; + } + switch (object.editionDeprecated) { + default: + if (typeof object.editionDeprecated === "number") { + message.editionDeprecated = object.editionDeprecated; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.editionDeprecated = 0; + break; + case "EDITION_LEGACY": + case 900: + message.editionDeprecated = 900; + break; + case "EDITION_PROTO2": + case 998: + message.editionDeprecated = 998; + break; + case "EDITION_PROTO3": + case 999: + message.editionDeprecated = 999; + break; + case "EDITION_2023": + case 1000: + message.editionDeprecated = 1000; + break; + case "EDITION_2024": + case 1001: + message.editionDeprecated = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.editionDeprecated = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.editionDeprecated = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.editionDeprecated = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.editionDeprecated = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.editionDeprecated = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.editionDeprecated = 2147483647; + break; + } + if (object.deprecationWarning != null) + message.deprecationWarning = String(object.deprecationWarning); + switch (object.editionRemoved) { + default: + if (typeof object.editionRemoved === "number") { + message.editionRemoved = object.editionRemoved; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.editionRemoved = 0; + break; + case "EDITION_LEGACY": + case 900: + message.editionRemoved = 900; + break; + case "EDITION_PROTO2": + case 998: + message.editionRemoved = 998; + break; + case "EDITION_PROTO3": + case 999: + message.editionRemoved = 999; + break; + case "EDITION_2023": + case 1000: + message.editionRemoved = 1000; + break; + case "EDITION_2024": + case 1001: + message.editionRemoved = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.editionRemoved = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.editionRemoved = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.editionRemoved = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.editionRemoved = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.editionRemoved = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.editionRemoved = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSupport message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSupport.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.editionIntroduced = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.editionDeprecated = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.deprecationWarning = ""; + object.editionRemoved = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + object.editionIntroduced = options.enums === String ? $root.google.protobuf.Edition[message.editionIntroduced] === undefined ? message.editionIntroduced : $root.google.protobuf.Edition[message.editionIntroduced] : message.editionIntroduced; + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + object.editionDeprecated = options.enums === String ? $root.google.protobuf.Edition[message.editionDeprecated] === undefined ? message.editionDeprecated : $root.google.protobuf.Edition[message.editionDeprecated] : message.editionDeprecated; + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + object.deprecationWarning = message.deprecationWarning; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + object.editionRemoved = options.enums === String ? $root.google.protobuf.Edition[message.editionRemoved] === undefined ? message.editionRemoved : $root.google.protobuf.Edition[message.editionRemoved] : message.editionRemoved; + return object; + }; + + /** + * Converts this FeatureSupport to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + * @returns {Object.} JSON object + */ + FeatureSupport.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSupport + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; + }; + + return FeatureSupport; + })(); + + return FieldOptions; + })(); + + protobuf.OneofOptions = (function() { + + /** + * Properties of an OneofOptions. + * @memberof google.protobuf + * @interface IOneofOptions + * @property {google.protobuf.IFeatureSet|null} [features] OneofOptions features + * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption + */ + + /** + * Constructs a new OneofOptions. + * @memberof google.protobuf + * @classdesc Represents an OneofOptions. + * @implements IOneofOptions + * @constructor + * @param {google.protobuf.IOneofOptions=} [properties] Properties to set + */ + function OneofOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.features = null; + + /** + * OneofOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates a new OneofOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.IOneofOptions=} [properties] Properties to set + * @returns {google.protobuf.OneofOptions} OneofOptions instance + */ + OneofOptions.create = function create(properties) { + return new OneofOptions(properties); + }; + + /** + * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.IOneofOptions} message OneofOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OneofOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.IOneofOptions} message OneofOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OneofOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an OneofOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.OneofOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.OneofOptions} OneofOptions + * @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, 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()); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an OneofOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.OneofOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.OneofOptions} OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OneofOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an OneofOptions message. + * @function verify + * @memberof google.protobuf.OneofOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + OneofOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + return null; + }; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofOptions} OneofOptions + */ + OneofOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofOptions) + return object; + var message = new $root.google.protobuf.OneofOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.OneofOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.OneofOptions} message OneofOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) + object.features = null; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this OneofOptions to JSON. + * @function toJSON + * @memberof google.protobuf.OneofOptions + * @instance + * @returns {Object.} JSON object + */ + OneofOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofOptions + * @function getTypeUrl + * @memberof google.protobuf.OneofOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofOptions"; + }; + + return OneofOptions; + })(); + + protobuf.EnumOptions = (function() { + + /** + * Properties of an EnumOptions. + * @memberof google.protobuf + * @interface IEnumOptions + * @property {boolean|null} [allowAlias] EnumOptions allowAlias + * @property {boolean|null} [deprecated] EnumOptions deprecated + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] EnumOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] EnumOptions features + * @property {Array.|null} [uninterpretedOption] EnumOptions uninterpretedOption + */ + + /** + * Constructs a new EnumOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumOptions. + * @implements IEnumOptions + * @constructor + * @param {google.protobuf.IEnumOptions=} [properties] Properties to set + */ + function EnumOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumOptions allowAlias. + * @member {boolean} allowAlias + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.allowAlias = false; + + /** + * EnumOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecated = false; + + /** + * EnumOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + + /** + * EnumOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.features = null; + + /** + * EnumOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates a new EnumOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.EnumOptions + * @static + * @param {google.protobuf.IEnumOptions=} [properties] Properties to set + * @returns {google.protobuf.EnumOptions} EnumOptions instance + */ + EnumOptions.create = function create(properties) { + return new EnumOptions(properties); + }; + + /** + * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.EnumOptions + * @static + * @param {google.protobuf.IEnumOptions} message EnumOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.allowAlias != null && Object.hasOwnProperty.call(message, "allowAlias")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.allowAlias); + if (message.deprecated != null && Object.hasOwnProperty.call(message, "deprecated")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.deprecated); + if (message.deprecatedLegacyJsonFieldConflicts != null && Object.hasOwnProperty.call(message, "deprecatedLegacyJsonFieldConflicts")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.deprecatedLegacyJsonFieldConflicts); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.EnumOptions + * @static + * @param {google.protobuf.IEnumOptions} message EnumOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an EnumOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.EnumOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.EnumOptions} EnumOptions + * @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, 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(); + break; + } + case 3: { + message.deprecated = reader.bool(); + break; + } + case 6: { + message.deprecatedLegacyJsonFieldConflicts = reader.bool(); + break; + } + case 7: { + message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an EnumOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.EnumOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.EnumOptions} EnumOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EnumOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an EnumOptions message. + * @function verify + * @memberof google.protobuf.EnumOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EnumOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) + if (typeof message.allowAlias !== "boolean") + return "allowAlias: boolean expected"; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + if (typeof message.deprecated !== "boolean") + return "deprecated: boolean expected"; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + if (typeof message.deprecatedLegacyJsonFieldConflicts !== "boolean") + return "deprecatedLegacyJsonFieldConflicts: boolean expected"; + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + return null; + }; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumOptions} EnumOptions + */ + EnumOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumOptions) + return object; + var message = new $root.google.protobuf.EnumOptions(); + if (object.allowAlias != null) + message.allowAlias = Boolean(object.allowAlias); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {google.protobuf.EnumOptions} message EnumOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.allowAlias = false; + object.deprecated = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + } + if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) + object.allowAlias = message.allowAlias; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this EnumOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumOptions + * @instance + * @returns {Object.} JSON object + */ + EnumOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumOptions"; + }; + + return EnumOptions; + })(); + + protobuf.EnumValueOptions = (function() { + + /** + * Properties of an EnumValueOptions. + * @memberof google.protobuf + * @interface IEnumValueOptions + * @property {boolean|null} [deprecated] EnumValueOptions deprecated + * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features + * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] EnumValueOptions featureSupport + * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption + */ + + /** + * Constructs a new EnumValueOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumValueOptions. + * @implements IEnumValueOptions + * @constructor + * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set + */ + function EnumValueOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.deprecated = false; + + /** + * EnumValueOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.features = null; + + /** + * EnumValueOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.debugRedact = false; + + /** + * EnumValueOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.featureSupport = null; + + /** + * EnumValueOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates a new EnumValueOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set + * @returns {google.protobuf.EnumValueOptions} EnumValueOptions instance + */ + EnumValueOptions.create = function create(properties) { + return new EnumValueOptions(properties); + }; + + /** + * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {google.protobuf.IEnumValueOptions} message EnumValueOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumValueOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.deprecated != null && Object.hasOwnProperty.call(message, "deprecated")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.deprecated); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.debugRedact); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {google.protobuf.IEnumValueOptions} message EnumValueOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EnumValueOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.EnumValueOptions} EnumValueOptions + * @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, 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(); + break; + } + case 2: { + message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 3: { + message.debugRedact = reader.bool(); + break; + } + case 4: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.EnumValueOptions} EnumValueOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EnumValueOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an EnumValueOptions message. + * @function verify + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EnumValueOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + if (typeof message.deprecated !== "boolean") + return "deprecated: boolean expected"; + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + if (typeof message.debugRedact !== "boolean") + return "debugRedact: boolean expected"; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + return null; + }; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueOptions} EnumValueOptions + */ + EnumValueOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueOptions) + return object; + var message = new $root.google.protobuf.EnumValueOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.featureSupport: object expected"); + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.fromObject(object.featureSupport); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {google.protobuf.EnumValueOptions} message EnumValueOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object.debugRedact = false; + object.featureSupport = null; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) + object.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.toObject(message.featureSupport, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this EnumValueOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueOptions + * @instance + * @returns {Object.} JSON object + */ + EnumValueOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnumValueOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueOptions"; + }; + + return EnumValueOptions; + })(); + + protobuf.ServiceOptions = (function() { + + /** + * Properties of a ServiceOptions. + * @memberof google.protobuf + * @interface IServiceOptions + * @property {google.protobuf.IFeatureSet|null} [features] ServiceOptions features + * @property {boolean|null} [deprecated] ServiceOptions deprecated + * @property {Array.|null} [uninterpretedOption] ServiceOptions uninterpretedOption + * @property {string|null} [".google.api.defaultHost"] ServiceOptions .google.api.defaultHost + * @property {string|null} [".google.api.oauthScopes"] ServiceOptions .google.api.oauthScopes + * @property {string|null} [".google.api.apiVersion"] ServiceOptions .google.api.apiVersion + */ + + /** + * Constructs a new ServiceOptions. + * @memberof google.protobuf + * @classdesc Represents a ServiceOptions. + * @implements IServiceOptions + * @constructor + * @param {google.protobuf.IServiceOptions=} [properties] Properties to set + */ + function ServiceOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.features = null; + + /** + * ServiceOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.deprecated = false; + + /** + * ServiceOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * ServiceOptions .google.api.defaultHost. + * @member {string} .google.api.defaultHost + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.defaultHost"] = ""; + + /** + * ServiceOptions .google.api.oauthScopes. + * @member {string} .google.api.oauthScopes + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.oauthScopes"] = ""; + + /** + * ServiceOptions .google.api.apiVersion. + * @member {string} .google.api.apiVersion + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.apiVersion"] = ""; + + /** + * Creates a new ServiceOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.ServiceOptions + * @static + * @param {google.protobuf.IServiceOptions=} [properties] Properties to set + * @returns {google.protobuf.ServiceOptions} ServiceOptions instance + */ + ServiceOptions.create = function create(properties) { + return new ServiceOptions(properties); + }; + + /** + * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.ServiceOptions + * @static + * @param {google.protobuf.IServiceOptions} message ServiceOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ServiceOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.deprecated != null && Object.hasOwnProperty.call(message, "deprecated")) + writer.uint32(/* id 33, wireType 0 =*/264).bool(message.deprecated); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 34, wireType 2 =*/274).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + if (message[".google.api.defaultHost"] != null && Object.hasOwnProperty.call(message, ".google.api.defaultHost")) + writer.uint32(/* id 1049, wireType 2 =*/8394).string(message[".google.api.defaultHost"]); + if (message[".google.api.oauthScopes"] != null && Object.hasOwnProperty.call(message, ".google.api.oauthScopes")) + writer.uint32(/* id 1050, wireType 2 =*/8402).string(message[".google.api.oauthScopes"]); + if (message[".google.api.apiVersion"] != null && Object.hasOwnProperty.call(message, ".google.api.apiVersion")) + writer.uint32(/* id 525000001, wireType 2 =*/4200000010).string(message[".google.api.apiVersion"]); + return writer; + }; + + /** + * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.ServiceOptions + * @static + * @param {google.protobuf.IServiceOptions} message ServiceOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ServiceOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.ServiceOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.ServiceOptions} ServiceOptions + * @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, 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()); + break; + } + case 33: { + message.deprecated = reader.bool(); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + case 1049: { + message[".google.api.defaultHost"] = reader.string(); + break; + } + case 1050: { + message[".google.api.oauthScopes"] = reader.string(); + break; + } + case 525000001: { + message[".google.api.apiVersion"] = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.ServiceOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.ServiceOptions} ServiceOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ServiceOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ServiceOptions message. + * @function verify + * @memberof google.protobuf.ServiceOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ServiceOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + if (typeof message.deprecated !== "boolean") + return "deprecated: boolean expected"; + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + if (message[".google.api.defaultHost"] != null && message.hasOwnProperty(".google.api.defaultHost")) + if (!$util.isString(message[".google.api.defaultHost"])) + return ".google.api.defaultHost: string expected"; + if (message[".google.api.oauthScopes"] != null && message.hasOwnProperty(".google.api.oauthScopes")) + if (!$util.isString(message[".google.api.oauthScopes"])) + return ".google.api.oauthScopes: string expected"; + if (message[".google.api.apiVersion"] != null && message.hasOwnProperty(".google.api.apiVersion")) + if (!$util.isString(message[".google.api.apiVersion"])) + return ".google.api.apiVersion: string expected"; + return null; + }; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceOptions} ServiceOptions + */ + ServiceOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceOptions) + return object; + var message = new $root.google.protobuf.ServiceOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ServiceOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.defaultHost"] != null) + message[".google.api.defaultHost"] = String(object[".google.api.defaultHost"]); + if (object[".google.api.oauthScopes"] != null) + message[".google.api.oauthScopes"] = String(object[".google.api.oauthScopes"]); + if (object[".google.api.apiVersion"] != null) + message[".google.api.apiVersion"] = String(object[".google.api.apiVersion"]); + return message; + }; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {google.protobuf.ServiceOptions} message ServiceOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object[".google.api.defaultHost"] = ""; + object[".google.api.oauthScopes"] = ""; + object[".google.api.apiVersion"] = ""; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.defaultHost"] != null && message.hasOwnProperty(".google.api.defaultHost")) + object[".google.api.defaultHost"] = message[".google.api.defaultHost"]; + if (message[".google.api.oauthScopes"] != null && message.hasOwnProperty(".google.api.oauthScopes")) + object[".google.api.oauthScopes"] = message[".google.api.oauthScopes"]; + if (message[".google.api.apiVersion"] != null && message.hasOwnProperty(".google.api.apiVersion")) + object[".google.api.apiVersion"] = message[".google.api.apiVersion"]; + return object; + }; + + /** + * Converts this ServiceOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceOptions + * @instance + * @returns {Object.} JSON object + */ + ServiceOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ServiceOptions + * @function getTypeUrl + * @memberof google.protobuf.ServiceOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceOptions"; + }; + + return ServiceOptions; + })(); + + protobuf.MethodOptions = (function() { + + /** + * Properties of a MethodOptions. + * @memberof google.protobuf + * @interface IMethodOptions + * @property {boolean|null} [deprecated] MethodOptions deprecated + * @property {google.protobuf.MethodOptions.IdempotencyLevel|null} [idempotencyLevel] MethodOptions idempotencyLevel + * @property {google.protobuf.IFeatureSet|null} [features] MethodOptions features + * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption + * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http + * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature + * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo + */ + + /** + * Constructs a new MethodOptions. + * @memberof google.protobuf + * @classdesc Represents a MethodOptions. + * @implements IMethodOptions + * @constructor + * @param {google.protobuf.IMethodOptions=} [properties] Properties to set + */ + function MethodOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.methodSignature"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.deprecated = false; + + /** + * MethodOptions idempotencyLevel. + * @member {google.protobuf.MethodOptions.IdempotencyLevel} idempotencyLevel + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.idempotencyLevel = 0; + + /** + * MethodOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.features = null; + + /** + * MethodOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * MethodOptions .google.api.http. + * @member {google.api.IHttpRule|null|undefined} .google.api.http + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.http"] = null; + + /** + * MethodOptions .google.api.methodSignature. + * @member {Array.} .google.api.methodSignature + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.methodSignature"] = $util.emptyArray; + + /** + * MethodOptions .google.longrunning.operationInfo. + * @member {google.longrunning.IOperationInfo|null|undefined} .google.longrunning.operationInfo + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.longrunning.operationInfo"] = null; + + /** + * Creates a new MethodOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.MethodOptions + * @static + * @param {google.protobuf.IMethodOptions=} [properties] Properties to set + * @returns {google.protobuf.MethodOptions} MethodOptions instance + */ + MethodOptions.create = function create(properties) { + return new MethodOptions(properties); + }; + + /** + * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.MethodOptions + * @static + * @param {google.protobuf.IMethodOptions} message MethodOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MethodOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.deprecated != null && Object.hasOwnProperty.call(message, "deprecated")) + writer.uint32(/* id 33, wireType 0 =*/264).bool(message.deprecated); + if (message.idempotencyLevel != null && Object.hasOwnProperty.call(message, "idempotencyLevel")) + writer.uint32(/* id 34, wireType 0 =*/272).int32(message.idempotencyLevel); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 35, wireType 2 =*/282).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + if (message[".google.longrunning.operationInfo"] != null && Object.hasOwnProperty.call(message, ".google.longrunning.operationInfo")) + $root.google.longrunning.OperationInfo.encode(message[".google.longrunning.operationInfo"], writer.uint32(/* id 1049, wireType 2 =*/8394).fork()).ldelim(); + if (message[".google.api.methodSignature"] != null && message[".google.api.methodSignature"].length) + for (var i = 0; i < message[".google.api.methodSignature"].length; ++i) + writer.uint32(/* id 1051, wireType 2 =*/8410).string(message[".google.api.methodSignature"][i]); + if (message[".google.api.http"] != null && Object.hasOwnProperty.call(message, ".google.api.http")) + $root.google.api.HttpRule.encode(message[".google.api.http"], writer.uint32(/* id 72295728, wireType 2 =*/578365826).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.MethodOptions + * @static + * @param {google.protobuf.IMethodOptions} message MethodOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MethodOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MethodOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.MethodOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.MethodOptions} MethodOptions + * @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, 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(); + break; + } + case 34: { + message.idempotencyLevel = reader.int32(); + break; + } + case 35: { + message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + message.uninterpretedOption = []; + message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); + break; + } + case 72295728: { + message[".google.api.http"] = $root.google.api.HttpRule.decode(reader, reader.uint32()); + break; + } + case 1051: { + if (!(message[".google.api.methodSignature"] && message[".google.api.methodSignature"].length)) + message[".google.api.methodSignature"] = []; + message[".google.api.methodSignature"].push(reader.string()); + break; + } + case 1049: { + message[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MethodOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.MethodOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.MethodOptions} MethodOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MethodOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MethodOptions message. + * @function verify + * @memberof google.protobuf.MethodOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MethodOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + if (typeof message.deprecated !== "boolean") + return "deprecated: boolean expected"; + if (message.idempotencyLevel != null && message.hasOwnProperty("idempotencyLevel")) + switch (message.idempotencyLevel) { + default: + return "idempotencyLevel: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.features != null && message.hasOwnProperty("features")) { + var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (error) + return "features." + error; + } + if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { + if (!Array.isArray(message.uninterpretedOption)) + return "uninterpretedOption: array expected"; + for (var i = 0; i < message.uninterpretedOption.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.verify(message.uninterpretedOption[i]); + if (error) + return "uninterpretedOption." + error; + } + } + if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) { + var error = $root.google.api.HttpRule.verify(message[".google.api.http"]); + if (error) + return ".google.api.http." + error; + } + if (message[".google.api.methodSignature"] != null && message.hasOwnProperty(".google.api.methodSignature")) { + if (!Array.isArray(message[".google.api.methodSignature"])) + return ".google.api.methodSignature: array expected"; + for (var i = 0; i < message[".google.api.methodSignature"].length; ++i) + if (!$util.isString(message[".google.api.methodSignature"][i])) + return ".google.api.methodSignature: string[] expected"; + } + if (message[".google.longrunning.operationInfo"] != null && message.hasOwnProperty(".google.longrunning.operationInfo")) { + var error = $root.google.longrunning.OperationInfo.verify(message[".google.longrunning.operationInfo"]); + if (error) + return ".google.longrunning.operationInfo." + error; + } + return null; + }; + + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodOptions} MethodOptions + */ + MethodOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodOptions) + return object; + var message = new $root.google.protobuf.MethodOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + switch (object.idempotencyLevel) { + default: + if (typeof object.idempotencyLevel === "number") { + message.idempotencyLevel = object.idempotencyLevel; + break; + } + break; + case "IDEMPOTENCY_UNKNOWN": + case 0: + message.idempotencyLevel = 0; + break; + case "NO_SIDE_EFFECTS": + case 1: + message.idempotencyLevel = 1; + break; + case "IDEMPOTENT": + case 2: + message.idempotencyLevel = 2; + break; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MethodOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.http"] != null) { + if (typeof object[".google.api.http"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.http: object expected"); + message[".google.api.http"] = $root.google.api.HttpRule.fromObject(object[".google.api.http"]); + } + if (object[".google.api.methodSignature"]) { + if (!Array.isArray(object[".google.api.methodSignature"])) + throw TypeError(".google.protobuf.MethodOptions..google.api.methodSignature: array expected"); + message[".google.api.methodSignature"] = []; + for (var i = 0; i < object[".google.api.methodSignature"].length; ++i) + message[".google.api.methodSignature"][i] = String(object[".google.api.methodSignature"][i]); + } + if (object[".google.longrunning.operationInfo"] != null) { + if (typeof object[".google.longrunning.operationInfo"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); + message[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.fromObject(object[".google.longrunning.operationInfo"]); + } + return message; + }; + + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {google.protobuf.MethodOptions} message MethodOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.methodSignature"] = []; + } + if (options.defaults) { + object.deprecated = false; + object.idempotencyLevel = options.enums === String ? "IDEMPOTENCY_UNKNOWN" : 0; + object.features = null; + object[".google.longrunning.operationInfo"] = null; + object[".google.api.http"] = null; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.idempotencyLevel != null && message.hasOwnProperty("idempotencyLevel")) + object.idempotencyLevel = options.enums === String ? $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] === undefined ? message.idempotencyLevel : $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] : message.idempotencyLevel; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.longrunning.operationInfo"] != null && message.hasOwnProperty(".google.longrunning.operationInfo")) + object[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.toObject(message[".google.longrunning.operationInfo"], options); + if (message[".google.api.methodSignature"] && message[".google.api.methodSignature"].length) { + object[".google.api.methodSignature"] = []; + for (var j = 0; j < message[".google.api.methodSignature"].length; ++j) + object[".google.api.methodSignature"][j] = message[".google.api.methodSignature"][j]; + } + if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) + object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); + return object; + }; + + /** + * Converts this MethodOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MethodOptions + * @instance + * @returns {Object.} JSON object + */ + MethodOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodOptions + * @function getTypeUrl + * @memberof google.protobuf.MethodOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodOptions"; + }; + + /** + * IdempotencyLevel enum. + * @name google.protobuf.MethodOptions.IdempotencyLevel + * @enum {number} + * @property {number} IDEMPOTENCY_UNKNOWN=0 IDEMPOTENCY_UNKNOWN value + * @property {number} NO_SIDE_EFFECTS=1 NO_SIDE_EFFECTS value + * @property {number} IDEMPOTENT=2 IDEMPOTENT value + */ + MethodOptions.IdempotencyLevel = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "IDEMPOTENCY_UNKNOWN"] = 0; + values[valuesById[1] = "NO_SIDE_EFFECTS"] = 1; + values[valuesById[2] = "IDEMPOTENT"] = 2; + return values; + })(); + + return MethodOptions; + })(); + + protobuf.UninterpretedOption = (function() { + + /** + * Properties of an UninterpretedOption. + * @memberof google.protobuf + * @interface IUninterpretedOption + * @property {Array.|null} [name] UninterpretedOption name + * @property {string|null} [identifierValue] UninterpretedOption identifierValue + * @property {number|Long|null} [positiveIntValue] UninterpretedOption positiveIntValue + * @property {number|Long|null} [negativeIntValue] UninterpretedOption negativeIntValue + * @property {number|null} [doubleValue] UninterpretedOption doubleValue + * @property {Uint8Array|null} [stringValue] UninterpretedOption stringValue + * @property {string|null} [aggregateValue] UninterpretedOption aggregateValue + */ + + /** + * Constructs a new UninterpretedOption. + * @memberof google.protobuf + * @classdesc Represents an UninterpretedOption. + * @implements IUninterpretedOption + * @constructor + * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set + */ + function UninterpretedOption(properties) { + this.name = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UninterpretedOption name. + * @member {Array.} name + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.name = $util.emptyArray; + + /** + * UninterpretedOption identifierValue. + * @member {string} identifierValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.identifierValue = ""; + + /** + * UninterpretedOption positiveIntValue. + * @member {number|Long} positiveIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.positiveIntValue = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * UninterpretedOption negativeIntValue. + * @member {number|Long} negativeIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.negativeIntValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UninterpretedOption doubleValue. + * @member {number} doubleValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.doubleValue = 0; + + /** + * UninterpretedOption stringValue. + * @member {Uint8Array} stringValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.stringValue = $util.newBuffer([]); + + /** + * UninterpretedOption aggregateValue. + * @member {string} aggregateValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.aggregateValue = ""; + + /** + * Creates a new UninterpretedOption instance using the specified properties. + * @function create + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set + * @returns {google.protobuf.UninterpretedOption} UninterpretedOption instance + */ + UninterpretedOption.create = function create(properties) { + return new UninterpretedOption(properties); + }; + + /** + * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @function encode + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {google.protobuf.IUninterpretedOption} message UninterpretedOption message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UninterpretedOption.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && message.name.length) + for (var i = 0; i < message.name.length; ++i) + $root.google.protobuf.UninterpretedOption.NamePart.encode(message.name[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.identifierValue != null && Object.hasOwnProperty.call(message, "identifierValue")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.identifierValue); + if (message.positiveIntValue != null && Object.hasOwnProperty.call(message, "positiveIntValue")) + writer.uint32(/* id 4, wireType 0 =*/32).uint64(message.positiveIntValue); + if (message.negativeIntValue != null && Object.hasOwnProperty.call(message, "negativeIntValue")) + writer.uint32(/* id 5, wireType 0 =*/40).int64(message.negativeIntValue); + if (message.doubleValue != null && Object.hasOwnProperty.call(message, "doubleValue")) + writer.uint32(/* id 6, wireType 1 =*/49).double(message.doubleValue); + if (message.stringValue != null && Object.hasOwnProperty.call(message, "stringValue")) + writer.uint32(/* id 7, wireType 2 =*/58).bytes(message.stringValue); + if (message.aggregateValue != null && Object.hasOwnProperty.call(message, "aggregateValue")) + writer.uint32(/* id 8, wireType 2 =*/66).string(message.aggregateValue); + return writer; + }; + + /** + * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {google.protobuf.IUninterpretedOption} message UninterpretedOption message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UninterpretedOption.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.UninterpretedOption} UninterpretedOption + * @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, 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)) + message.name = []; + message.name.push($root.google.protobuf.UninterpretedOption.NamePart.decode(reader, reader.uint32())); + break; + } + case 3: { + message.identifierValue = reader.string(); + break; + } + case 4: { + message.positiveIntValue = reader.uint64(); + break; + } + case 5: { + message.negativeIntValue = reader.int64(); + break; + } + case 6: { + message.doubleValue = reader.double(); + break; + } + case 7: { + message.stringValue = reader.bytes(); + break; + } + case 8: { + message.aggregateValue = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.UninterpretedOption} UninterpretedOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UninterpretedOption.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UninterpretedOption message. + * @function verify + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UninterpretedOption.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) { + if (!Array.isArray(message.name)) + return "name: array expected"; + for (var i = 0; i < message.name.length; ++i) { + var error = $root.google.protobuf.UninterpretedOption.NamePart.verify(message.name[i]); + if (error) + return "name." + error; + } + } + if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) + if (!$util.isString(message.identifierValue)) + return "identifierValue: string expected"; + if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) + if (!$util.isInteger(message.positiveIntValue) && !(message.positiveIntValue && $util.isInteger(message.positiveIntValue.low) && $util.isInteger(message.positiveIntValue.high))) + return "positiveIntValue: integer|Long expected"; + if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) + if (!$util.isInteger(message.negativeIntValue) && !(message.negativeIntValue && $util.isInteger(message.negativeIntValue.low) && $util.isInteger(message.negativeIntValue.high))) + return "negativeIntValue: integer|Long expected"; + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) + if (typeof message.doubleValue !== "number") + return "doubleValue: number expected"; + if (message.stringValue != null && message.hasOwnProperty("stringValue")) + if (!(message.stringValue && typeof message.stringValue.length === "number" || $util.isString(message.stringValue))) + return "stringValue: buffer expected"; + if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) + if (!$util.isString(message.aggregateValue)) + return "aggregateValue: string expected"; + return null; + }; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption} UninterpretedOption + */ + UninterpretedOption.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption) + return object; + var message = new $root.google.protobuf.UninterpretedOption(); + if (object.name) { + if (!Array.isArray(object.name)) + throw TypeError(".google.protobuf.UninterpretedOption.name: array expected"); + message.name = []; + for (var i = 0; i < object.name.length; ++i) { + if (typeof object.name[i] !== "object") + throw TypeError(".google.protobuf.UninterpretedOption.name: object expected"); + message.name[i] = $root.google.protobuf.UninterpretedOption.NamePart.fromObject(object.name[i]); + } + } + if (object.identifierValue != null) + message.identifierValue = String(object.identifierValue); + if (object.positiveIntValue != null) + if ($util.Long) + (message.positiveIntValue = $util.Long.fromValue(object.positiveIntValue)).unsigned = true; + else if (typeof object.positiveIntValue === "string") + message.positiveIntValue = parseInt(object.positiveIntValue, 10); + else if (typeof object.positiveIntValue === "number") + message.positiveIntValue = object.positiveIntValue; + else if (typeof object.positiveIntValue === "object") + message.positiveIntValue = new $util.LongBits(object.positiveIntValue.low >>> 0, object.positiveIntValue.high >>> 0).toNumber(true); + if (object.negativeIntValue != null) + if ($util.Long) + (message.negativeIntValue = $util.Long.fromValue(object.negativeIntValue)).unsigned = false; + else if (typeof object.negativeIntValue === "string") + message.negativeIntValue = parseInt(object.negativeIntValue, 10); + else if (typeof object.negativeIntValue === "number") + message.negativeIntValue = object.negativeIntValue; + else if (typeof object.negativeIntValue === "object") + message.negativeIntValue = new $util.LongBits(object.negativeIntValue.low >>> 0, object.negativeIntValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.stringValue != null) + if (typeof object.stringValue === "string") + $util.base64.decode(object.stringValue, message.stringValue = $util.newBuffer($util.base64.length(object.stringValue)), 0); + else if (object.stringValue.length >= 0) + message.stringValue = object.stringValue; + if (object.aggregateValue != null) + message.aggregateValue = String(object.aggregateValue); + return message; + }; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {google.protobuf.UninterpretedOption} message UninterpretedOption + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UninterpretedOption.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.name = []; + if (options.defaults) { + object.identifierValue = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.positiveIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.positiveIntValue = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.negativeIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.negativeIntValue = options.longs === String ? "0" : 0; + object.doubleValue = 0; + if (options.bytes === String) + object.stringValue = ""; + else { + object.stringValue = []; + if (options.bytes !== Array) + object.stringValue = $util.newBuffer(object.stringValue); + } + object.aggregateValue = ""; + } + if (message.name && message.name.length) { + object.name = []; + for (var j = 0; j < message.name.length; ++j) + object.name[j] = $root.google.protobuf.UninterpretedOption.NamePart.toObject(message.name[j], options); + } + if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) + object.identifierValue = message.identifierValue; + if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) + if (typeof message.positiveIntValue === "number") + object.positiveIntValue = options.longs === String ? String(message.positiveIntValue) : message.positiveIntValue; + else + object.positiveIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.positiveIntValue) : options.longs === Number ? new $util.LongBits(message.positiveIntValue.low >>> 0, message.positiveIntValue.high >>> 0).toNumber(true) : message.positiveIntValue; + if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) + if (typeof message.negativeIntValue === "number") + object.negativeIntValue = options.longs === String ? String(message.negativeIntValue) : message.negativeIntValue; + else + object.negativeIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.negativeIntValue) : options.longs === Number ? new $util.LongBits(message.negativeIntValue.low >>> 0, message.negativeIntValue.high >>> 0).toNumber() : message.negativeIntValue; + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (message.stringValue != null && message.hasOwnProperty("stringValue")) + object.stringValue = options.bytes === String ? $util.base64.encode(message.stringValue, 0, message.stringValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.stringValue) : message.stringValue; + if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) + object.aggregateValue = message.aggregateValue; + return object; + }; + + /** + * Converts this UninterpretedOption to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption + * @instance + * @returns {Object.} JSON object + */ + UninterpretedOption.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UninterpretedOption + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UninterpretedOption.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption"; + }; + + UninterpretedOption.NamePart = (function() { + + /** + * Properties of a NamePart. + * @memberof google.protobuf.UninterpretedOption + * @interface INamePart + * @property {string} namePart NamePart namePart + * @property {boolean} isExtension NamePart isExtension + */ + + /** + * Constructs a new NamePart. + * @memberof google.protobuf.UninterpretedOption + * @classdesc Represents a NamePart. + * @implements INamePart + * @constructor + * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set + */ + function NamePart(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NamePart namePart. + * @member {string} namePart + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + */ + NamePart.prototype.namePart = ""; + + /** + * NamePart isExtension. + * @member {boolean} isExtension + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + */ + NamePart.prototype.isExtension = false; + + /** + * Creates a new NamePart instance using the specified properties. + * @function create + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set + * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart instance + */ + NamePart.create = function create(properties) { + return new NamePart(properties); + }; + + /** + * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @function encode + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {google.protobuf.UninterpretedOption.INamePart} message NamePart message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NamePart.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + writer.uint32(/* id 1, wireType 2 =*/10).string(message.namePart); + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.isExtension); + return writer; + }; + + /** + * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {google.protobuf.UninterpretedOption.INamePart} message NamePart message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NamePart.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a NamePart message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart + * @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, 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(); + break; + } + case 2: { + message.isExtension = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + if (!message.hasOwnProperty("namePart")) + throw $util.ProtocolError("missing required 'namePart'", { instance: message }); + if (!message.hasOwnProperty("isExtension")) + throw $util.ProtocolError("missing required 'isExtension'", { instance: message }); + return message; + }; + + /** + * Decodes a NamePart message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NamePart.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a NamePart message. + * @function verify + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + NamePart.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (!$util.isString(message.namePart)) + return "namePart: string expected"; + if (typeof message.isExtension !== "boolean") + return "isExtension: boolean expected"; + return null; + }; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart + */ + NamePart.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption.NamePart) + return object; + var message = new $root.google.protobuf.UninterpretedOption.NamePart(); + if (object.namePart != null) + message.namePart = String(object.namePart); + if (object.isExtension != null) + message.isExtension = Boolean(object.isExtension); + return message; + }; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {google.protobuf.UninterpretedOption.NamePart} message NamePart + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NamePart.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.namePart = ""; + object.isExtension = false; + } + if (message.namePart != null && message.hasOwnProperty("namePart")) + object.namePart = message.namePart; + if (message.isExtension != null && message.hasOwnProperty("isExtension")) + object.isExtension = message.isExtension; + return object; + }; + + /** + * Converts this NamePart to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + * @returns {Object.} JSON object + */ + NamePart.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NamePart + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NamePart.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption.NamePart"; + }; + + return NamePart; + })(); + + return UninterpretedOption; + })(); + + protobuf.FeatureSet = (function() { + + /** + * Properties of a FeatureSet. + * @memberof google.protobuf + * @interface IFeatureSet + * @property {google.protobuf.FeatureSet.FieldPresence|null} [fieldPresence] FeatureSet fieldPresence + * @property {google.protobuf.FeatureSet.EnumType|null} [enumType] FeatureSet enumType + * @property {google.protobuf.FeatureSet.RepeatedFieldEncoding|null} [repeatedFieldEncoding] FeatureSet repeatedFieldEncoding + * @property {google.protobuf.FeatureSet.Utf8Validation|null} [utf8Validation] FeatureSet utf8Validation + * @property {google.protobuf.FeatureSet.MessageEncoding|null} [messageEncoding] FeatureSet messageEncoding + * @property {google.protobuf.FeatureSet.JsonFormat|null} [jsonFormat] FeatureSet jsonFormat + * @property {google.protobuf.FeatureSet.EnforceNamingStyle|null} [enforceNamingStyle] FeatureSet enforceNamingStyle + * @property {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null} [defaultSymbolVisibility] FeatureSet defaultSymbolVisibility + */ + + /** + * Constructs a new FeatureSet. + * @memberof google.protobuf + * @classdesc Represents a FeatureSet. + * @implements IFeatureSet + * @constructor + * @param {google.protobuf.IFeatureSet=} [properties] Properties to set + */ + function FeatureSet(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSet fieldPresence. + * @member {google.protobuf.FeatureSet.FieldPresence} fieldPresence + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.fieldPresence = 0; + + /** + * FeatureSet enumType. + * @member {google.protobuf.FeatureSet.EnumType} enumType + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enumType = 0; + + /** + * FeatureSet repeatedFieldEncoding. + * @member {google.protobuf.FeatureSet.RepeatedFieldEncoding} repeatedFieldEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.repeatedFieldEncoding = 0; + + /** + * FeatureSet utf8Validation. + * @member {google.protobuf.FeatureSet.Utf8Validation} utf8Validation + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.utf8Validation = 0; + + /** + * FeatureSet messageEncoding. + * @member {google.protobuf.FeatureSet.MessageEncoding} messageEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.messageEncoding = 0; + + /** + * FeatureSet jsonFormat. + * @member {google.protobuf.FeatureSet.JsonFormat} jsonFormat + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.jsonFormat = 0; + + /** + * FeatureSet enforceNamingStyle. + * @member {google.protobuf.FeatureSet.EnforceNamingStyle} enforceNamingStyle + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enforceNamingStyle = 0; + + /** + * FeatureSet defaultSymbolVisibility. + * @member {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility} defaultSymbolVisibility + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.defaultSymbolVisibility = 0; + + /** + * Creates a new FeatureSet instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet + * @static + * @param {google.protobuf.IFeatureSet=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet} FeatureSet instance + */ + FeatureSet.create = function create(properties) { + return new FeatureSet(properties); + }; + + /** + * Encodes the specified FeatureSet message. Does not implicitly {@link google.protobuf.FeatureSet.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet + * @static + * @param {google.protobuf.IFeatureSet} message FeatureSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.fieldPresence != null && Object.hasOwnProperty.call(message, "fieldPresence")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.fieldPresence); + if (message.enumType != null && Object.hasOwnProperty.call(message, "enumType")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.enumType); + if (message.repeatedFieldEncoding != null && Object.hasOwnProperty.call(message, "repeatedFieldEncoding")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.repeatedFieldEncoding); + if (message.utf8Validation != null && Object.hasOwnProperty.call(message, "utf8Validation")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.utf8Validation); + if (message.messageEncoding != null && Object.hasOwnProperty.call(message, "messageEncoding")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.messageEncoding); + if (message.jsonFormat != null && Object.hasOwnProperty.call(message, "jsonFormat")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jsonFormat); + if (message.enforceNamingStyle != null && Object.hasOwnProperty.call(message, "enforceNamingStyle")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.enforceNamingStyle); + if (message.defaultSymbolVisibility != null && Object.hasOwnProperty.call(message, "defaultSymbolVisibility")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.defaultSymbolVisibility); + return writer; + }; + + /** + * Encodes the specified FeatureSet message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet + * @static + * @param {google.protobuf.IFeatureSet} message FeatureSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSet message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet} FeatureSet + * @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, 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(); + break; + } + case 2: { + message.enumType = reader.int32(); + break; + } + case 3: { + message.repeatedFieldEncoding = reader.int32(); + break; + } + case 4: { + message.utf8Validation = reader.int32(); + break; + } + case 5: { + message.messageEncoding = reader.int32(); + break; + } + case 6: { + message.jsonFormat = reader.int32(); + break; + } + case 7: { + message.enforceNamingStyle = reader.int32(); + break; + } + case 8: { + message.defaultSymbolVisibility = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet} FeatureSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSet message. + * @function verify + * @memberof google.protobuf.FeatureSet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.fieldPresence != null && message.hasOwnProperty("fieldPresence")) + switch (message.fieldPresence) { + default: + return "fieldPresence: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.enumType != null && message.hasOwnProperty("enumType")) + switch (message.enumType) { + default: + return "enumType: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.repeatedFieldEncoding != null && message.hasOwnProperty("repeatedFieldEncoding")) + switch (message.repeatedFieldEncoding) { + default: + return "repeatedFieldEncoding: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.utf8Validation != null && message.hasOwnProperty("utf8Validation")) + switch (message.utf8Validation) { + default: + return "utf8Validation: enum value expected"; + case 0: + case 2: + case 3: + break; + } + if (message.messageEncoding != null && message.hasOwnProperty("messageEncoding")) + switch (message.messageEncoding) { + default: + return "messageEncoding: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.jsonFormat != null && message.hasOwnProperty("jsonFormat")) + switch (message.jsonFormat) { + default: + return "jsonFormat: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + switch (message.enforceNamingStyle) { + default: + return "enforceNamingStyle: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + switch (message.defaultSymbolVisibility) { + default: + return "defaultSymbolVisibility: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + return null; + }; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet} FeatureSet + */ + FeatureSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet) + return object; + var message = new $root.google.protobuf.FeatureSet(); + switch (object.fieldPresence) { + default: + if (typeof object.fieldPresence === "number") { + message.fieldPresence = object.fieldPresence; + break; + } + break; + case "FIELD_PRESENCE_UNKNOWN": + case 0: + message.fieldPresence = 0; + break; + case "EXPLICIT": + case 1: + message.fieldPresence = 1; + break; + case "IMPLICIT": + case 2: + message.fieldPresence = 2; + break; + case "LEGACY_REQUIRED": + case 3: + message.fieldPresence = 3; + break; + } + switch (object.enumType) { + default: + if (typeof object.enumType === "number") { + message.enumType = object.enumType; + break; + } + break; + case "ENUM_TYPE_UNKNOWN": + case 0: + message.enumType = 0; + break; + case "OPEN": + case 1: + message.enumType = 1; + break; + case "CLOSED": + case 2: + message.enumType = 2; + break; + } + switch (object.repeatedFieldEncoding) { + default: + if (typeof object.repeatedFieldEncoding === "number") { + message.repeatedFieldEncoding = object.repeatedFieldEncoding; + break; + } + break; + case "REPEATED_FIELD_ENCODING_UNKNOWN": + case 0: + message.repeatedFieldEncoding = 0; + break; + case "PACKED": + case 1: + message.repeatedFieldEncoding = 1; + break; + case "EXPANDED": + case 2: + message.repeatedFieldEncoding = 2; + break; + } + switch (object.utf8Validation) { + default: + if (typeof object.utf8Validation === "number") { + message.utf8Validation = object.utf8Validation; + break; + } + break; + case "UTF8_VALIDATION_UNKNOWN": + case 0: + message.utf8Validation = 0; + break; + case "VERIFY": + case 2: + message.utf8Validation = 2; + break; + case "NONE": + case 3: + message.utf8Validation = 3; + break; + } + switch (object.messageEncoding) { + default: + if (typeof object.messageEncoding === "number") { + message.messageEncoding = object.messageEncoding; + break; + } + break; + case "MESSAGE_ENCODING_UNKNOWN": + case 0: + message.messageEncoding = 0; + break; + case "LENGTH_PREFIXED": + case 1: + message.messageEncoding = 1; + break; + case "DELIMITED": + case 2: + message.messageEncoding = 2; + break; + } + switch (object.jsonFormat) { + default: + if (typeof object.jsonFormat === "number") { + message.jsonFormat = object.jsonFormat; + break; + } + break; + case "JSON_FORMAT_UNKNOWN": + case 0: + message.jsonFormat = 0; + break; + case "ALLOW": + case 1: + message.jsonFormat = 1; + break; + case "LEGACY_BEST_EFFORT": + case 2: + message.jsonFormat = 2; + break; + } + switch (object.enforceNamingStyle) { + default: + if (typeof object.enforceNamingStyle === "number") { + message.enforceNamingStyle = object.enforceNamingStyle; + break; + } + break; + case "ENFORCE_NAMING_STYLE_UNKNOWN": + case 0: + message.enforceNamingStyle = 0; + break; + case "STYLE2024": + case 1: + message.enforceNamingStyle = 1; + break; + case "STYLE_LEGACY": + case 2: + message.enforceNamingStyle = 2; + break; + } + switch (object.defaultSymbolVisibility) { + default: + if (typeof object.defaultSymbolVisibility === "number") { + message.defaultSymbolVisibility = object.defaultSymbolVisibility; + break; + } + break; + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + case 0: + message.defaultSymbolVisibility = 0; + break; + case "EXPORT_ALL": + case 1: + message.defaultSymbolVisibility = 1; + break; + case "EXPORT_TOP_LEVEL": + case 2: + message.defaultSymbolVisibility = 2; + break; + case "LOCAL_ALL": + case 3: + message.defaultSymbolVisibility = 3; + break; + case "STRICT": + case 4: + message.defaultSymbolVisibility = 4; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {google.protobuf.FeatureSet} message FeatureSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.fieldPresence = options.enums === String ? "FIELD_PRESENCE_UNKNOWN" : 0; + object.enumType = options.enums === String ? "ENUM_TYPE_UNKNOWN" : 0; + object.repeatedFieldEncoding = options.enums === String ? "REPEATED_FIELD_ENCODING_UNKNOWN" : 0; + object.utf8Validation = options.enums === String ? "UTF8_VALIDATION_UNKNOWN" : 0; + object.messageEncoding = options.enums === String ? "MESSAGE_ENCODING_UNKNOWN" : 0; + object.jsonFormat = options.enums === String ? "JSON_FORMAT_UNKNOWN" : 0; + object.enforceNamingStyle = options.enums === String ? "ENFORCE_NAMING_STYLE_UNKNOWN" : 0; + object.defaultSymbolVisibility = options.enums === String ? "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN" : 0; + } + if (message.fieldPresence != null && message.hasOwnProperty("fieldPresence")) + object.fieldPresence = options.enums === String ? $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] === undefined ? message.fieldPresence : $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] : message.fieldPresence; + if (message.enumType != null && message.hasOwnProperty("enumType")) + object.enumType = options.enums === String ? $root.google.protobuf.FeatureSet.EnumType[message.enumType] === undefined ? message.enumType : $root.google.protobuf.FeatureSet.EnumType[message.enumType] : message.enumType; + if (message.repeatedFieldEncoding != null && message.hasOwnProperty("repeatedFieldEncoding")) + object.repeatedFieldEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] === undefined ? message.repeatedFieldEncoding : $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] : message.repeatedFieldEncoding; + if (message.utf8Validation != null && message.hasOwnProperty("utf8Validation")) + object.utf8Validation = options.enums === String ? $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] === undefined ? message.utf8Validation : $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] : message.utf8Validation; + if (message.messageEncoding != null && message.hasOwnProperty("messageEncoding")) + object.messageEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] === undefined ? message.messageEncoding : $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] : message.messageEncoding; + if (message.jsonFormat != null && message.hasOwnProperty("jsonFormat")) + object.jsonFormat = options.enums === String ? $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] === undefined ? message.jsonFormat : $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] : message.jsonFormat; + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + object.enforceNamingStyle = options.enums === String ? $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] === undefined ? message.enforceNamingStyle : $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] : message.enforceNamingStyle; + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + object.defaultSymbolVisibility = options.enums === String ? $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] === undefined ? message.defaultSymbolVisibility : $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] : message.defaultSymbolVisibility; + return object; + }; + + /** + * Converts this FeatureSet to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet + * @instance + * @returns {Object.} JSON object + */ + FeatureSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSet + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet"; + }; + + /** + * FieldPresence enum. + * @name google.protobuf.FeatureSet.FieldPresence + * @enum {number} + * @property {number} FIELD_PRESENCE_UNKNOWN=0 FIELD_PRESENCE_UNKNOWN value + * @property {number} EXPLICIT=1 EXPLICIT value + * @property {number} IMPLICIT=2 IMPLICIT value + * @property {number} LEGACY_REQUIRED=3 LEGACY_REQUIRED value + */ + FeatureSet.FieldPresence = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_PRESENCE_UNKNOWN"] = 0; + values[valuesById[1] = "EXPLICIT"] = 1; + values[valuesById[2] = "IMPLICIT"] = 2; + values[valuesById[3] = "LEGACY_REQUIRED"] = 3; + return values; + })(); + + /** + * EnumType enum. + * @name google.protobuf.FeatureSet.EnumType + * @enum {number} + * @property {number} ENUM_TYPE_UNKNOWN=0 ENUM_TYPE_UNKNOWN value + * @property {number} OPEN=1 OPEN value + * @property {number} CLOSED=2 CLOSED value + */ + FeatureSet.EnumType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENUM_TYPE_UNKNOWN"] = 0; + values[valuesById[1] = "OPEN"] = 1; + values[valuesById[2] = "CLOSED"] = 2; + return values; + })(); + + /** + * RepeatedFieldEncoding enum. + * @name google.protobuf.FeatureSet.RepeatedFieldEncoding + * @enum {number} + * @property {number} REPEATED_FIELD_ENCODING_UNKNOWN=0 REPEATED_FIELD_ENCODING_UNKNOWN value + * @property {number} PACKED=1 PACKED value + * @property {number} EXPANDED=2 EXPANDED value + */ + FeatureSet.RepeatedFieldEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "REPEATED_FIELD_ENCODING_UNKNOWN"] = 0; + values[valuesById[1] = "PACKED"] = 1; + values[valuesById[2] = "EXPANDED"] = 2; + return values; + })(); + + /** + * Utf8Validation enum. + * @name google.protobuf.FeatureSet.Utf8Validation + * @enum {number} + * @property {number} UTF8_VALIDATION_UNKNOWN=0 UTF8_VALIDATION_UNKNOWN value + * @property {number} VERIFY=2 VERIFY value + * @property {number} NONE=3 NONE value + */ + FeatureSet.Utf8Validation = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UTF8_VALIDATION_UNKNOWN"] = 0; + values[valuesById[2] = "VERIFY"] = 2; + values[valuesById[3] = "NONE"] = 3; + return values; + })(); + + /** + * MessageEncoding enum. + * @name google.protobuf.FeatureSet.MessageEncoding + * @enum {number} + * @property {number} MESSAGE_ENCODING_UNKNOWN=0 MESSAGE_ENCODING_UNKNOWN value + * @property {number} LENGTH_PREFIXED=1 LENGTH_PREFIXED value + * @property {number} DELIMITED=2 DELIMITED value + */ + FeatureSet.MessageEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MESSAGE_ENCODING_UNKNOWN"] = 0; + values[valuesById[1] = "LENGTH_PREFIXED"] = 1; + values[valuesById[2] = "DELIMITED"] = 2; + return values; + })(); + + /** + * JsonFormat enum. + * @name google.protobuf.FeatureSet.JsonFormat + * @enum {number} + * @property {number} JSON_FORMAT_UNKNOWN=0 JSON_FORMAT_UNKNOWN value + * @property {number} ALLOW=1 ALLOW value + * @property {number} LEGACY_BEST_EFFORT=2 LEGACY_BEST_EFFORT value + */ + FeatureSet.JsonFormat = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JSON_FORMAT_UNKNOWN"] = 0; + values[valuesById[1] = "ALLOW"] = 1; + values[valuesById[2] = "LEGACY_BEST_EFFORT"] = 2; + return values; + })(); + + /** + * EnforceNamingStyle enum. + * @name google.protobuf.FeatureSet.EnforceNamingStyle + * @enum {number} + * @property {number} ENFORCE_NAMING_STYLE_UNKNOWN=0 ENFORCE_NAMING_STYLE_UNKNOWN value + * @property {number} STYLE2024=1 STYLE2024 value + * @property {number} STYLE_LEGACY=2 STYLE_LEGACY value + */ + FeatureSet.EnforceNamingStyle = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENFORCE_NAMING_STYLE_UNKNOWN"] = 0; + values[valuesById[1] = "STYLE2024"] = 1; + values[valuesById[2] = "STYLE_LEGACY"] = 2; + return values; + })(); + + FeatureSet.VisibilityFeature = (function() { + + /** + * Properties of a VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @interface IVisibilityFeature + */ + + /** + * Constructs a new VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @classdesc Represents a VisibilityFeature. + * @implements IVisibilityFeature + * @constructor + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + */ + function VisibilityFeature(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature instance + */ + VisibilityFeature.create = function create(properties) { + return new VisibilityFeature(properties); + }; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.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.VisibilityFeature(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VisibilityFeature message. + * @function verify + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VisibilityFeature.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + */ + VisibilityFeature.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet.VisibilityFeature) + return object; + return new $root.google.protobuf.FeatureSet.VisibilityFeature(); + }; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.VisibilityFeature} message VisibilityFeature + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VisibilityFeature.toObject = function toObject() { + return {}; + }; + + /** + * Converts this VisibilityFeature to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @instance + * @returns {Object.} JSON object + */ + VisibilityFeature.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VisibilityFeature + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VisibilityFeature.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet.VisibilityFeature"; + }; + + /** + * DefaultSymbolVisibility enum. + * @name google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility + * @enum {number} + * @property {number} DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0 DEFAULT_SYMBOL_VISIBILITY_UNKNOWN value + * @property {number} EXPORT_ALL=1 EXPORT_ALL value + * @property {number} EXPORT_TOP_LEVEL=2 EXPORT_TOP_LEVEL value + * @property {number} LOCAL_ALL=3 LOCAL_ALL value + * @property {number} STRICT=4 STRICT value + */ + VisibilityFeature.DefaultSymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0; + values[valuesById[1] = "EXPORT_ALL"] = 1; + values[valuesById[2] = "EXPORT_TOP_LEVEL"] = 2; + values[valuesById[3] = "LOCAL_ALL"] = 3; + values[valuesById[4] = "STRICT"] = 4; + return values; + })(); + + return VisibilityFeature; + })(); + + return FeatureSet; + })(); + + protobuf.FeatureSetDefaults = (function() { + + /** + * Properties of a FeatureSetDefaults. + * @memberof google.protobuf + * @interface IFeatureSetDefaults + * @property {Array.|null} [defaults] FeatureSetDefaults defaults + * @property {google.protobuf.Edition|null} [minimumEdition] FeatureSetDefaults minimumEdition + * @property {google.protobuf.Edition|null} [maximumEdition] FeatureSetDefaults maximumEdition + */ + + /** + * Constructs a new FeatureSetDefaults. + * @memberof google.protobuf + * @classdesc Represents a FeatureSetDefaults. + * @implements IFeatureSetDefaults + * @constructor + * @param {google.protobuf.IFeatureSetDefaults=} [properties] Properties to set + */ + function FeatureSetDefaults(properties) { + this.defaults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSetDefaults defaults. + * @member {Array.} defaults + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.defaults = $util.emptyArray; + + /** + * FeatureSetDefaults minimumEdition. + * @member {google.protobuf.Edition} minimumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.minimumEdition = 0; + + /** + * FeatureSetDefaults maximumEdition. + * @member {google.protobuf.Edition} maximumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.maximumEdition = 0; + + /** + * Creates a new FeatureSetDefaults instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {google.protobuf.IFeatureSetDefaults=} [properties] Properties to set + * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults instance + */ + FeatureSetDefaults.create = function create(properties) { + return new FeatureSetDefaults(properties); + }; + + /** + * Encodes the specified FeatureSetDefaults message. Does not implicitly {@link google.protobuf.FeatureSetDefaults.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {google.protobuf.IFeatureSetDefaults} message FeatureSetDefaults message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSetDefaults.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.defaults != null && message.defaults.length) + for (var i = 0; i < message.defaults.length; ++i) + $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.encode(message.defaults[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.minimumEdition != null && Object.hasOwnProperty.call(message, "minimumEdition")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.minimumEdition); + if (message.maximumEdition != null && Object.hasOwnProperty.call(message, "maximumEdition")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.maximumEdition); + return writer; + }; + + /** + * Encodes the specified FeatureSetDefaults message, length delimited. Does not implicitly {@link google.protobuf.FeatureSetDefaults.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {google.protobuf.IFeatureSetDefaults} message FeatureSetDefaults message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSetDefaults.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSetDefaults message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults + * @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, 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)) + message.defaults = []; + message.defaults.push($root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.decode(reader, reader.uint32())); + break; + } + case 4: { + message.minimumEdition = reader.int32(); + break; + } + case 5: { + message.maximumEdition = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSetDefaults message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSetDefaults.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSetDefaults message. + * @function verify + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSetDefaults.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.defaults != null && message.hasOwnProperty("defaults")) { + if (!Array.isArray(message.defaults)) + return "defaults: array expected"; + for (var i = 0; i < message.defaults.length; ++i) { + var error = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.verify(message.defaults[i]); + if (error) + return "defaults." + error; + } + } + if (message.minimumEdition != null && message.hasOwnProperty("minimumEdition")) + switch (message.minimumEdition) { + default: + return "minimumEdition: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.maximumEdition != null && message.hasOwnProperty("maximumEdition")) + switch (message.maximumEdition) { + default: + return "maximumEdition: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults + */ + FeatureSetDefaults.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults(); + if (object.defaults) { + if (!Array.isArray(object.defaults)) + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected"); + message.defaults = []; + for (var i = 0; i < object.defaults.length; ++i) { + if (typeof object.defaults[i] !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: object expected"); + message.defaults[i] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fromObject(object.defaults[i]); + } + } + switch (object.minimumEdition) { + default: + if (typeof object.minimumEdition === "number") { + message.minimumEdition = object.minimumEdition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.minimumEdition = 0; + break; + case "EDITION_LEGACY": + case 900: + message.minimumEdition = 900; + break; + case "EDITION_PROTO2": + case 998: + message.minimumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.minimumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.minimumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.minimumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.minimumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.minimumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.minimumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.minimumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.minimumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.minimumEdition = 2147483647; + break; + } + switch (object.maximumEdition) { + default: + if (typeof object.maximumEdition === "number") { + message.maximumEdition = object.maximumEdition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.maximumEdition = 0; + break; + case "EDITION_LEGACY": + case 900: + message.maximumEdition = 900; + break; + case "EDITION_PROTO2": + case 998: + message.maximumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.maximumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.maximumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.maximumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.maximumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.maximumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.maximumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.maximumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.maximumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.maximumEdition = 2147483647; + break; + } + return message; + }; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {google.protobuf.FeatureSetDefaults} message FeatureSetDefaults + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetDefaults.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.defaults = []; + if (options.defaults) { + object.minimumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.maximumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.defaults && message.defaults.length) { + object.defaults = []; + for (var j = 0; j < message.defaults.length; ++j) + object.defaults[j] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.toObject(message.defaults[j], options); + } + if (message.minimumEdition != null && message.hasOwnProperty("minimumEdition")) + object.minimumEdition = options.enums === String ? $root.google.protobuf.Edition[message.minimumEdition] === undefined ? message.minimumEdition : $root.google.protobuf.Edition[message.minimumEdition] : message.minimumEdition; + if (message.maximumEdition != null && message.hasOwnProperty("maximumEdition")) + object.maximumEdition = options.enums === String ? $root.google.protobuf.Edition[message.maximumEdition] === undefined ? message.maximumEdition : $root.google.protobuf.Edition[message.maximumEdition] : message.maximumEdition; + return object; + }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults + * @instance + * @returns {Object.} JSON object + */ + FeatureSetDefaults.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSetDefaults + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetDefaults.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults"; + }; + + FeatureSetDefaults.FeatureSetEditionDefault = (function() { + + /** + * Properties of a FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @interface IFeatureSetEditionDefault + * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition + * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures + * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures + */ + + /** + * Constructs a new FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @classdesc Represents a FeatureSetEditionDefault. + * @implements IFeatureSetEditionDefault + * @constructor + * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault=} [properties] Properties to set + */ + function FeatureSetEditionDefault(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSetEditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.edition = 0; + + /** + * FeatureSetEditionDefault overridableFeatures. + * @member {google.protobuf.IFeatureSet|null|undefined} overridableFeatures + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.overridableFeatures = null; + + /** + * FeatureSetEditionDefault fixedFeatures. + * @member {google.protobuf.IFeatureSet|null|undefined} fixedFeatures + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + */ + FeatureSetEditionDefault.prototype.fixedFeatures = null; + + /** + * Creates a new FeatureSetEditionDefault instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault=} [properties] Properties to set + * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault instance + */ + FeatureSetEditionDefault.create = function create(properties) { + return new FeatureSetEditionDefault(properties); + }; + + /** + * Encodes the specified FeatureSetEditionDefault message. Does not implicitly {@link google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault} message FeatureSetEditionDefault message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSetEditionDefault.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + if (message.overridableFeatures != null && Object.hasOwnProperty.call(message, "overridableFeatures")) + $root.google.protobuf.FeatureSet.encode(message.overridableFeatures, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.fixedFeatures != null && Object.hasOwnProperty.call(message, "fixedFeatures")) + $root.google.protobuf.FeatureSet.encode(message.fixedFeatures, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified FeatureSetEditionDefault message, length delimited. Does not implicitly {@link google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault} message FeatureSetEditionDefault message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSetEditionDefault.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSetEditionDefault message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault + * @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, 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(); + break; + } + case 4: { + message.overridableFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.fixedFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSetEditionDefault message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSetEditionDefault.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSetEditionDefault message. + * @function verify + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSetEditionDefault.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.edition != null && message.hasOwnProperty("edition")) + switch (message.edition) { + default: + return "edition: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.overridableFeatures); + if (error) + return "overridableFeatures." + error; + } + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.fixedFeatures); + if (error) + return "fixedFeatures." + error; + } + return null; + }; + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault + */ + FeatureSetEditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + if (object.overridableFeatures != null) { + if (typeof object.overridableFeatures !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.overridableFeatures: object expected"); + message.overridableFeatures = $root.google.protobuf.FeatureSet.fromObject(object.overridableFeatures); + } + if (object.fixedFeatures != null) { + if (typeof object.fixedFeatures !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fixedFeatures: object expected"); + message.fixedFeatures = $root.google.protobuf.FeatureSet.fromObject(object.fixedFeatures); + } + return message; + }; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} message FeatureSetEditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetEditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.overridableFeatures = null; + object.fixedFeatures = null; + } + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) + object.overridableFeatures = $root.google.protobuf.FeatureSet.toObject(message.overridableFeatures, options); + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) + object.fixedFeatures = $root.google.protobuf.FeatureSet.toObject(message.fixedFeatures, options); + return object; + }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @instance + * @returns {Object.} JSON object + */ + FeatureSetEditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetEditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"; + }; + + return FeatureSetEditionDefault; + })(); + + return FeatureSetDefaults; + })(); + + protobuf.SourceCodeInfo = (function() { + + /** + * Properties of a SourceCodeInfo. + * @memberof google.protobuf + * @interface ISourceCodeInfo + * @property {Array.|null} [location] SourceCodeInfo location + */ + + /** + * Constructs a new SourceCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a SourceCodeInfo. + * @implements ISourceCodeInfo + * @constructor + * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set + */ + function SourceCodeInfo(properties) { + this.location = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SourceCodeInfo location. + * @member {Array.} location + * @memberof google.protobuf.SourceCodeInfo + * @instance + */ + SourceCodeInfo.prototype.location = $util.emptyArray; + + /** + * Creates a new SourceCodeInfo instance using the specified properties. + * @function create + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set + * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo instance + */ + SourceCodeInfo.create = function create(properties) { + return new SourceCodeInfo(properties); + }; + + /** + * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @function encode + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {google.protobuf.ISourceCodeInfo} message SourceCodeInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SourceCodeInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.location != null && message.location.length) + for (var i = 0; i < message.location.length; ++i) + $root.google.protobuf.SourceCodeInfo.Location.encode(message.location[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {google.protobuf.ISourceCodeInfo} message SourceCodeInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SourceCodeInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo + * @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, 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)) + message.location = []; + message.location.push($root.google.protobuf.SourceCodeInfo.Location.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SourceCodeInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SourceCodeInfo message. + * @function verify + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SourceCodeInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.location != null && message.hasOwnProperty("location")) { + if (!Array.isArray(message.location)) + return "location: array expected"; + for (var i = 0; i < message.location.length; ++i) { + var error = $root.google.protobuf.SourceCodeInfo.Location.verify(message.location[i]); + if (error) + return "location." + error; + } + } + return null; + }; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo + */ + SourceCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo) + return object; + var message = new $root.google.protobuf.SourceCodeInfo(); + if (object.location) { + if (!Array.isArray(object.location)) + throw TypeError(".google.protobuf.SourceCodeInfo.location: array expected"); + message.location = []; + for (var i = 0; i < object.location.length; ++i) { + if (typeof object.location[i] !== "object") + throw TypeError(".google.protobuf.SourceCodeInfo.location: object expected"); + message.location[i] = $root.google.protobuf.SourceCodeInfo.Location.fromObject(object.location[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {google.protobuf.SourceCodeInfo} message SourceCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SourceCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.location = []; + if (message.location && message.location.length) { + object.location = []; + for (var j = 0; j < message.location.length; ++j) + object.location[j] = $root.google.protobuf.SourceCodeInfo.Location.toObject(message.location[j], options); + } + return object; + }; + + /** + * Converts this SourceCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo + * @instance + * @returns {Object.} JSON object + */ + SourceCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SourceCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SourceCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo"; + }; + + SourceCodeInfo.Location = (function() { + + /** + * Properties of a Location. + * @memberof google.protobuf.SourceCodeInfo + * @interface ILocation + * @property {Array.|null} [path] Location path + * @property {Array.|null} [span] Location span + * @property {string|null} [leadingComments] Location leadingComments + * @property {string|null} [trailingComments] Location trailingComments + * @property {Array.|null} [leadingDetachedComments] Location leadingDetachedComments + */ + + /** + * Constructs a new Location. + * @memberof google.protobuf.SourceCodeInfo + * @classdesc Represents a Location. + * @implements ILocation + * @constructor + * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set + */ + function Location(properties) { + this.path = []; + this.span = []; + this.leadingDetachedComments = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Location path. + * @member {Array.} path + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.path = $util.emptyArray; + + /** + * Location span. + * @member {Array.} span + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.span = $util.emptyArray; + + /** + * Location leadingComments. + * @member {string} leadingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingComments = ""; + + /** + * Location trailingComments. + * @member {string} trailingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.trailingComments = ""; + + /** + * Location leadingDetachedComments. + * @member {Array.} leadingDetachedComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingDetachedComments = $util.emptyArray; + + /** + * Creates a new Location instance using the specified properties. + * @function create + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set + * @returns {google.protobuf.SourceCodeInfo.Location} Location instance + */ + Location.create = function create(properties) { + return new Location(properties); + }; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @function encode + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {google.protobuf.SourceCodeInfo.ILocation} message Location message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Location.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.path != null && message.path.length) { + writer.uint32(/* id 1, wireType 2 =*/10).fork(); + for (var i = 0; i < message.path.length; ++i) + writer.int32(message.path[i]); + writer.ldelim(); + } + if (message.span != null && message.span.length) { + writer.uint32(/* id 2, wireType 2 =*/18).fork(); + for (var i = 0; i < message.span.length; ++i) + writer.int32(message.span[i]); + writer.ldelim(); + } + if (message.leadingComments != null && Object.hasOwnProperty.call(message, "leadingComments")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.leadingComments); + if (message.trailingComments != null && Object.hasOwnProperty.call(message, "trailingComments")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.trailingComments); + if (message.leadingDetachedComments != null && message.leadingDetachedComments.length) + for (var i = 0; i < message.leadingDetachedComments.length; ++i) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.leadingDetachedComments[i]); + return writer; + }; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {google.protobuf.SourceCodeInfo.ILocation} message Location message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Location.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Location message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.SourceCodeInfo.Location} Location + * @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, 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)) + message.path = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.path.push(reader.int32()); + } else + message.path.push(reader.int32()); + break; + } + case 2: { + if (!(message.span && message.span.length)) + message.span = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.span.push(reader.int32()); + } else + message.span.push(reader.int32()); + break; + } + case 3: { + message.leadingComments = reader.string(); + break; + } + case 4: { + message.trailingComments = reader.string(); + break; + } + case 6: { + if (!(message.leadingDetachedComments && message.leadingDetachedComments.length)) + message.leadingDetachedComments = []; + message.leadingDetachedComments.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.SourceCodeInfo.Location} Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Location.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Location message. + * @function verify + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Location.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.path != null && message.hasOwnProperty("path")) { + if (!Array.isArray(message.path)) + return "path: array expected"; + for (var i = 0; i < message.path.length; ++i) + if (!$util.isInteger(message.path[i])) + return "path: integer[] expected"; + } + if (message.span != null && message.hasOwnProperty("span")) { + if (!Array.isArray(message.span)) + return "span: array expected"; + for (var i = 0; i < message.span.length; ++i) + if (!$util.isInteger(message.span[i])) + return "span: integer[] expected"; + } + if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) + if (!$util.isString(message.leadingComments)) + return "leadingComments: string expected"; + if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) + if (!$util.isString(message.trailingComments)) + return "trailingComments: string expected"; + if (message.leadingDetachedComments != null && message.hasOwnProperty("leadingDetachedComments")) { + if (!Array.isArray(message.leadingDetachedComments)) + return "leadingDetachedComments: array expected"; + for (var i = 0; i < message.leadingDetachedComments.length; ++i) + if (!$util.isString(message.leadingDetachedComments[i])) + return "leadingDetachedComments: string[] expected"; + } + return null; + }; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo.Location} Location + */ + Location.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo.Location) + return object; + var message = new $root.google.protobuf.SourceCodeInfo.Location(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.span) { + if (!Array.isArray(object.span)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.span: array expected"); + message.span = []; + for (var i = 0; i < object.span.length; ++i) + message.span[i] = object.span[i] | 0; + } + if (object.leadingComments != null) + message.leadingComments = String(object.leadingComments); + if (object.trailingComments != null) + message.trailingComments = String(object.trailingComments); + if (object.leadingDetachedComments) { + if (!Array.isArray(object.leadingDetachedComments)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.leadingDetachedComments: array expected"); + message.leadingDetachedComments = []; + for (var i = 0; i < object.leadingDetachedComments.length; ++i) + message.leadingDetachedComments[i] = String(object.leadingDetachedComments[i]); + } + return message; + }; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {google.protobuf.SourceCodeInfo.Location} message Location + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Location.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.path = []; + object.span = []; + object.leadingDetachedComments = []; + } + if (options.defaults) { + object.leadingComments = ""; + object.trailingComments = ""; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.span && message.span.length) { + object.span = []; + for (var j = 0; j < message.span.length; ++j) + object.span[j] = message.span[j]; + } + if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) + object.leadingComments = message.leadingComments; + if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) + object.trailingComments = message.trailingComments; + if (message.leadingDetachedComments && message.leadingDetachedComments.length) { + object.leadingDetachedComments = []; + for (var j = 0; j < message.leadingDetachedComments.length; ++j) + object.leadingDetachedComments[j] = message.leadingDetachedComments[j]; + } + return object; + }; + + /** + * Converts this Location to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + * @returns {Object.} JSON object + */ + Location.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Location + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo.Location + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Location.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo.Location"; + }; + + return Location; + })(); + + return SourceCodeInfo; + })(); + + protobuf.GeneratedCodeInfo = (function() { + + /** + * Properties of a GeneratedCodeInfo. + * @memberof google.protobuf + * @interface IGeneratedCodeInfo + * @property {Array.|null} [annotation] GeneratedCodeInfo annotation + */ + + /** + * Constructs a new GeneratedCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a GeneratedCodeInfo. + * @implements IGeneratedCodeInfo + * @constructor + * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set + */ + function GeneratedCodeInfo(properties) { + this.annotation = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GeneratedCodeInfo annotation. + * @member {Array.} annotation + * @memberof google.protobuf.GeneratedCodeInfo + * @instance + */ + GeneratedCodeInfo.prototype.annotation = $util.emptyArray; + + /** + * Creates a new GeneratedCodeInfo instance using the specified properties. + * @function create + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set + * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo instance + */ + GeneratedCodeInfo.create = function create(properties) { + return new GeneratedCodeInfo(properties); + }; + + /** + * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @function encode + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {google.protobuf.IGeneratedCodeInfo} message GeneratedCodeInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GeneratedCodeInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.annotation != null && message.annotation.length) + for (var i = 0; i < message.annotation.length; ++i) + $root.google.protobuf.GeneratedCodeInfo.Annotation.encode(message.annotation[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {google.protobuf.IGeneratedCodeInfo} message GeneratedCodeInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GeneratedCodeInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo + * @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, 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)) + message.annotation = []; + message.annotation.push($root.google.protobuf.GeneratedCodeInfo.Annotation.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GeneratedCodeInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GeneratedCodeInfo message. + * @function verify + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GeneratedCodeInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.annotation != null && message.hasOwnProperty("annotation")) { + if (!Array.isArray(message.annotation)) + return "annotation: array expected"; + for (var i = 0; i < message.annotation.length; ++i) { + var error = $root.google.protobuf.GeneratedCodeInfo.Annotation.verify(message.annotation[i]); + if (error) + return "annotation." + error; + } + } + return null; + }; + + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo + */ + GeneratedCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo(); + if (object.annotation) { + if (!Array.isArray(object.annotation)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: array expected"); + message.annotation = []; + for (var i = 0; i < object.annotation.length; ++i) { + if (typeof object.annotation[i] !== "object") + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: object expected"); + message.annotation[i] = $root.google.protobuf.GeneratedCodeInfo.Annotation.fromObject(object.annotation[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {google.protobuf.GeneratedCodeInfo} message GeneratedCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GeneratedCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.annotation = []; + if (message.annotation && message.annotation.length) { + object.annotation = []; + for (var j = 0; j < message.annotation.length; ++j) + object.annotation[j] = $root.google.protobuf.GeneratedCodeInfo.Annotation.toObject(message.annotation[j], options); + } + return object; + }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo + * @instance + * @returns {Object.} JSON object + */ + GeneratedCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GeneratedCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo"; + }; + + GeneratedCodeInfo.Annotation = (function() { + + /** + * Properties of an Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @interface IAnnotation + * @property {Array.|null} [path] Annotation path + * @property {string|null} [sourceFile] Annotation sourceFile + * @property {number|null} [begin] Annotation begin + * @property {number|null} [end] Annotation end + * @property {google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null} [semantic] Annotation semantic + */ + + /** + * Constructs a new Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @classdesc Represents an Annotation. + * @implements IAnnotation + * @constructor + * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set + */ + function Annotation(properties) { + this.path = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Annotation path. + * @member {Array.} path + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.path = $util.emptyArray; + + /** + * Annotation sourceFile. + * @member {string} sourceFile + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.sourceFile = ""; + + /** + * Annotation begin. + * @member {number} begin + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.begin = 0; + + /** + * Annotation end. + * @member {number} end + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.end = 0; + + /** + * Annotation semantic. + * @member {google.protobuf.GeneratedCodeInfo.Annotation.Semantic} semantic + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.semantic = 0; + + /** + * Creates a new Annotation instance using the specified properties. + * @function create + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set + * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation instance + */ + Annotation.create = function create(properties) { + return new Annotation(properties); + }; + + /** + * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @function encode + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {google.protobuf.GeneratedCodeInfo.IAnnotation} message Annotation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Annotation.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.path != null && message.path.length) { + writer.uint32(/* id 1, wireType 2 =*/10).fork(); + for (var i = 0; i < message.path.length; ++i) + writer.int32(message.path[i]); + writer.ldelim(); + } + if (message.sourceFile != null && Object.hasOwnProperty.call(message, "sourceFile")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.sourceFile); + if (message.begin != null && Object.hasOwnProperty.call(message, "begin")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.begin); + if (message.end != null && Object.hasOwnProperty.call(message, "end")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.end); + if (message.semantic != null && Object.hasOwnProperty.call(message, "semantic")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.semantic); + return writer; + }; + + /** + * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {google.protobuf.GeneratedCodeInfo.IAnnotation} message Annotation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Annotation.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an Annotation message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation + * @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, 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)) + message.path = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.path.push(reader.int32()); + } else + message.path.push(reader.int32()); + break; + } + case 2: { + message.sourceFile = reader.string(); + break; + } + case 3: { + message.begin = reader.int32(); + break; + } + case 4: { + message.end = reader.int32(); + break; + } + case 5: { + message.semantic = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an Annotation message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Annotation.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an Annotation message. + * @function verify + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Annotation.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.path != null && message.hasOwnProperty("path")) { + if (!Array.isArray(message.path)) + return "path: array expected"; + for (var i = 0; i < message.path.length; ++i) + if (!$util.isInteger(message.path[i])) + return "path: integer[] expected"; + } + if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) + if (!$util.isString(message.sourceFile)) + return "sourceFile: string expected"; + if (message.begin != null && message.hasOwnProperty("begin")) + if (!$util.isInteger(message.begin)) + return "begin: integer expected"; + if (message.end != null && message.hasOwnProperty("end")) + if (!$util.isInteger(message.end)) + return "end: integer expected"; + if (message.semantic != null && message.hasOwnProperty("semantic")) + switch (message.semantic) { + default: + return "semantic: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation + */ + Annotation.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo.Annotation) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.Annotation.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.sourceFile != null) + message.sourceFile = String(object.sourceFile); + if (object.begin != null) + message.begin = object.begin | 0; + if (object.end != null) + message.end = object.end | 0; + switch (object.semantic) { + default: + if (typeof object.semantic === "number") { + message.semantic = object.semantic; + break; + } + break; + case "NONE": + case 0: + message.semantic = 0; + break; + case "SET": + case 1: + message.semantic = 1; + break; + case "ALIAS": + case 2: + message.semantic = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {google.protobuf.GeneratedCodeInfo.Annotation} message Annotation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Annotation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.path = []; + if (options.defaults) { + object.sourceFile = ""; + object.begin = 0; + object.end = 0; + object.semantic = options.enums === String ? "NONE" : 0; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) + object.sourceFile = message.sourceFile; + if (message.begin != null && message.hasOwnProperty("begin")) + object.begin = message.begin; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.semantic != null && message.hasOwnProperty("semantic")) + object.semantic = options.enums === String ? $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] === undefined ? message.semantic : $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] : message.semantic; + return object; + }; + + /** + * Converts this Annotation to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + * @returns {Object.} JSON object + */ + Annotation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Annotation + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Annotation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo.Annotation"; + }; + + /** + * Semantic enum. + * @name google.protobuf.GeneratedCodeInfo.Annotation.Semantic + * @enum {number} + * @property {number} NONE=0 NONE value + * @property {number} SET=1 SET value + * @property {number} ALIAS=2 ALIAS value + */ + Annotation.Semantic = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NONE"] = 0; + values[valuesById[1] = "SET"] = 1; + values[valuesById[2] = "ALIAS"] = 2; + return values; + })(); + + return Annotation; + })(); + + return GeneratedCodeInfo; + })(); + + /** + * SymbolVisibility enum. + * @name google.protobuf.SymbolVisibility + * @enum {number} + * @property {number} VISIBILITY_UNSET=0 VISIBILITY_UNSET value + * @property {number} VISIBILITY_LOCAL=1 VISIBILITY_LOCAL value + * @property {number} VISIBILITY_EXPORT=2 VISIBILITY_EXPORT value + */ + protobuf.SymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VISIBILITY_UNSET"] = 0; + values[valuesById[1] = "VISIBILITY_LOCAL"] = 1; + values[valuesById[2] = "VISIBILITY_EXPORT"] = 2; + return values; + })(); + + protobuf.Any = (function() { + + /** + * Properties of an Any. + * @memberof google.protobuf + * @interface IAny + * @property {string|null} [type_url] Any type_url + * @property {Uint8Array|null} [value] Any value + */ + + /** + * Constructs a new Any. + * @memberof google.protobuf + * @classdesc Represents an Any. + * @implements IAny + * @constructor + * @param {google.protobuf.IAny=} [properties] Properties to set + */ + function Any(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Any type_url. + * @member {string} type_url + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.type_url = ""; + + /** + * Any value. + * @member {Uint8Array} value + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.value = $util.newBuffer([]); + + /** + * Creates a new Any instance using the specified properties. + * @function create + * @memberof google.protobuf.Any + * @static + * @param {google.protobuf.IAny=} [properties] Properties to set + * @returns {google.protobuf.Any} Any instance + */ + Any.create = function create(properties) { + return new Any(properties); + }; + + /** + * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. + * @function encode + * @memberof google.protobuf.Any + * @static + * @param {google.protobuf.IAny} message Any message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Any.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.type_url != null && Object.hasOwnProperty.call(message, "type_url")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.type_url); + if (message.value != null && Object.hasOwnProperty.call(message, "value")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.value); + return writer; + }; + + /** + * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.Any + * @static + * @param {google.protobuf.IAny} message Any message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Any.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an Any message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.Any + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.Any} Any + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Any.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.Any(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.type_url = reader.string(); + break; + } + case 2: { + message.value = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an Any message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.Any + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.Any} Any + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Any.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an Any message. + * @function verify + * @memberof google.protobuf.Any + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Any.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.type_url != null && message.hasOwnProperty("type_url")) + if (!$util.isString(message.type_url)) + return "type_url: string expected"; + if (message.value != null && message.hasOwnProperty("value")) + if (!(message.value && typeof message.value.length === "number" || $util.isString(message.value))) + return "value: buffer expected"; + return null; + }; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Any + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Any} Any + */ + Any.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Any) + return object; + var message = new $root.google.protobuf.Any(); + if (object.type_url != null) + message.type_url = String(object.type_url); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; + return message; + }; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Any + * @static + * @param {google.protobuf.Any} message Any + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Any.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type_url = ""; + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + } + if (message.type_url != null && message.hasOwnProperty("type_url")) + object.type_url = message.type_url; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; + return object; + }; + + /** + * Converts this Any to JSON. + * @function toJSON + * @memberof google.protobuf.Any + * @instance + * @returns {Object.} JSON object + */ + Any.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Any + * @function getTypeUrl + * @memberof google.protobuf.Any + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Any.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Any"; + }; + + return Any; + })(); + + protobuf.Empty = (function() { + + /** + * Properties of an Empty. + * @memberof google.protobuf + * @interface IEmpty + */ + + /** + * Constructs a new Empty. + * @memberof google.protobuf + * @classdesc Represents an Empty. + * @implements IEmpty + * @constructor + * @param {google.protobuf.IEmpty=} [properties] Properties to set + */ + function Empty(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new Empty instance using the specified properties. + * @function create + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.IEmpty=} [properties] Properties to set + * @returns {google.protobuf.Empty} Empty instance + */ + Empty.create = function create(properties) { + return new Empty(properties); + }; + + /** + * Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @function encode + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.IEmpty} message Empty message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Empty.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.IEmpty} message Empty message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Empty.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an Empty message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.Empty + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.Empty} Empty + * @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, 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); + break; + } + } + return message; + }; + + /** + * Decodes an Empty message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.Empty + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.Empty} Empty + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Empty.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an Empty message. + * @function verify + * @memberof google.protobuf.Empty + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Empty.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Empty + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Empty} Empty + */ + Empty.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Empty) + return object; + return new $root.google.protobuf.Empty(); + }; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.Empty} message Empty + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Empty.toObject = function toObject() { + return {}; + }; + + /** + * Converts this Empty to JSON. + * @function toJSON + * @memberof google.protobuf.Empty + * @instance + * @returns {Object.} JSON object + */ + Empty.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Empty + * @function getTypeUrl + * @memberof google.protobuf.Empty + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Empty"; + }; + + return Empty; + })(); + + protobuf.FieldMask = (function() { + + /** + * Properties of a FieldMask. + * @memberof google.protobuf + * @interface IFieldMask + * @property {Array.|null} [paths] FieldMask paths + */ + + /** + * Constructs a new FieldMask. + * @memberof google.protobuf + * @classdesc Represents a FieldMask. + * @implements IFieldMask + * @constructor + * @param {google.protobuf.IFieldMask=} [properties] Properties to set + */ + function FieldMask(properties) { + this.paths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldMask paths. + * @member {Array.} paths + * @memberof google.protobuf.FieldMask + * @instance + */ + FieldMask.prototype.paths = $util.emptyArray; + + /** + * Creates a new FieldMask instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.IFieldMask=} [properties] Properties to set + * @returns {google.protobuf.FieldMask} FieldMask instance + */ + FieldMask.create = function create(properties) { + return new FieldMask(properties); + }; + + /** + * Encodes the specified FieldMask message. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.IFieldMask} message FieldMask message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldMask.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.paths != null && message.paths.length) + for (var i = 0; i < message.paths.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.paths[i]); + return writer; + }; + + /** + * Encodes the specified FieldMask message, length delimited. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.IFieldMask} message FieldMask message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldMask.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FieldMask message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldMask + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldMask} FieldMask + * @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, 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)) + message.paths = []; + message.paths.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FieldMask message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldMask + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldMask} FieldMask + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FieldMask.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FieldMask message. + * @function verify + * @memberof google.protobuf.FieldMask + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FieldMask.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.paths != null && message.hasOwnProperty("paths")) { + if (!Array.isArray(message.paths)) + return "paths: array expected"; + for (var i = 0; i < message.paths.length; ++i) + if (!$util.isString(message.paths[i])) + return "paths: string[] expected"; + } + return null; + }; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldMask + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldMask} FieldMask + */ + FieldMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldMask) + return object; + var message = new $root.google.protobuf.FieldMask(); + if (object.paths) { + if (!Array.isArray(object.paths)) + throw TypeError(".google.protobuf.FieldMask.paths: array expected"); + message.paths = []; + for (var i = 0; i < object.paths.length; ++i) + message.paths[i] = String(object.paths[i]); + } + return message; + }; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.FieldMask} message FieldMask + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldMask.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.paths = []; + if (message.paths && message.paths.length) { + object.paths = []; + for (var j = 0; j < message.paths.length; ++j) + object.paths[j] = message.paths[j]; + } + return object; + }; + + /** + * Converts this FieldMask to JSON. + * @function toJSON + * @memberof google.protobuf.FieldMask + * @instance + * @returns {Object.} JSON object + */ + FieldMask.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldMask + * @function getTypeUrl + * @memberof google.protobuf.FieldMask + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldMask"; + }; + + return FieldMask; + })(); + + protobuf.Timestamp = (function() { + + /** + * Properties of a Timestamp. + * @memberof google.protobuf + * @interface ITimestamp + * @property {number|Long|null} [seconds] Timestamp seconds + * @property {number|null} [nanos] Timestamp nanos + */ + + /** + * Constructs a new Timestamp. + * @memberof google.protobuf + * @classdesc Represents a Timestamp. + * @implements ITimestamp + * @constructor + * @param {google.protobuf.ITimestamp=} [properties] Properties to set + */ + function Timestamp(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Timestamp seconds. + * @member {number|Long} seconds + * @memberof google.protobuf.Timestamp + * @instance + */ + Timestamp.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Timestamp nanos. + * @member {number} nanos + * @memberof google.protobuf.Timestamp + * @instance + */ + Timestamp.prototype.nanos = 0; + + /** + * Creates a new Timestamp instance using the specified properties. + * @function create + * @memberof google.protobuf.Timestamp + * @static + * @param {google.protobuf.ITimestamp=} [properties] Properties to set + * @returns {google.protobuf.Timestamp} Timestamp instance + */ + Timestamp.create = function create(properties) { + return new Timestamp(properties); + }; + + /** + * Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. + * @function encode + * @memberof google.protobuf.Timestamp + * @static + * @param {google.protobuf.ITimestamp} message Timestamp message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Timestamp.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.seconds != null && Object.hasOwnProperty.call(message, "seconds")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.seconds); + if (message.nanos != null && Object.hasOwnProperty.call(message, "nanos")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.nanos); + return writer; + }; + + /** + * Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.Timestamp + * @static + * @param {google.protobuf.ITimestamp} message Timestamp message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Timestamp.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Timestamp message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.Timestamp + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.Timestamp} Timestamp + * @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, 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(); + break; + } + case 2: { + message.nanos = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Timestamp message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.Timestamp + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.Timestamp} Timestamp + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Timestamp.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Timestamp message. + * @function verify + * @memberof google.protobuf.Timestamp + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Timestamp.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (!$util.isInteger(message.seconds) && !(message.seconds && $util.isInteger(message.seconds.low) && $util.isInteger(message.seconds.high))) + return "seconds: integer|Long expected"; + if (message.nanos != null && message.hasOwnProperty("nanos")) + if (!$util.isInteger(message.nanos)) + return "nanos: integer expected"; + return null; + }; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Timestamp + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Timestamp} Timestamp + */ + Timestamp.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Timestamp) + return object; + var message = new $root.google.protobuf.Timestamp(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Timestamp + * @static + * @param {google.protobuf.Timestamp} message Timestamp + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Timestamp.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Timestamp to JSON. + * @function toJSON + * @memberof google.protobuf.Timestamp + * @instance + * @returns {Object.} JSON object + */ + Timestamp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Timestamp + * @function getTypeUrl + * @memberof google.protobuf.Timestamp + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Timestamp.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Timestamp"; + }; + + return Timestamp; + })(); + + protobuf.Struct = (function() { + + /** + * Properties of a Struct. + * @memberof google.protobuf + * @interface IStruct + * @property {Object.|null} [fields] Struct fields + */ + + /** + * Constructs a new Struct. + * @memberof google.protobuf + * @classdesc Represents a Struct. + * @implements IStruct + * @constructor + * @param {google.protobuf.IStruct=} [properties] Properties to set + */ + function Struct(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Struct fields. + * @member {Object.} fields + * @memberof google.protobuf.Struct + * @instance + */ + Struct.prototype.fields = $util.emptyObject; + + /** + * Creates a new Struct instance using the specified properties. + * @function create + * @memberof google.protobuf.Struct + * @static + * @param {google.protobuf.IStruct=} [properties] Properties to set + * @returns {google.protobuf.Struct} Struct instance + */ + Struct.create = function create(properties) { + return new Struct(properties); + }; + + /** + * Encodes the specified Struct message. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. + * @function encode + * @memberof google.protobuf.Struct + * @static + * @param {google.protobuf.IStruct} message Struct message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Struct.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.fields != null && Object.hasOwnProperty.call(message, "fields")) + for (var keys = Object.keys(message.fields), i = 0; i < keys.length; ++i) { + writer.uint32(/* id 1, wireType 2 =*/10).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); + $root.google.protobuf.Value.encode(message.fields[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); + } + return writer; + }; + + /** + * Encodes the specified Struct message, length delimited. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.Struct + * @static + * @param {google.protobuf.IStruct} message Struct message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Struct.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Struct message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.Struct + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.Struct} Struct + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Struct.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.Struct(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (message.fields === $util.emptyObject) + message.fields = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = null; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = $root.google.protobuf.Value.decode(reader, reader.uint32()); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.fields[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Struct message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.Struct + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.Struct} Struct + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Struct.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Struct message. + * @function verify + * @memberof google.protobuf.Struct + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Struct.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.fields != null && message.hasOwnProperty("fields")) { + if (!$util.isObject(message.fields)) + return "fields: object expected"; + var key = Object.keys(message.fields); + for (var i = 0; i < key.length; ++i) { + var error = $root.google.protobuf.Value.verify(message.fields[key[i]]); + if (error) + return "fields." + error; + } + } + return null; + }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Struct + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Struct} Struct + */ + Struct.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Struct) + return object; + var message = new $root.google.protobuf.Struct(); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields[keys[i]] = $root.google.protobuf.Value.fromObject(object.fields[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Struct + * @static + * @param {google.protobuf.Struct} message Struct + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Struct.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.protobuf.Value.toObject(message.fields[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Struct to JSON. + * @function toJSON + * @memberof google.protobuf.Struct + * @instance + * @returns {Object.} JSON object + */ + Struct.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Struct + * @function getTypeUrl + * @memberof google.protobuf.Struct + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Struct.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Struct"; + }; + + return Struct; + })(); + + protobuf.Value = (function() { + + /** + * Properties of a Value. + * @memberof google.protobuf + * @interface IValue + * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue + * @property {number|null} [numberValue] Value numberValue + * @property {string|null} [stringValue] Value stringValue + * @property {boolean|null} [boolValue] Value boolValue + * @property {google.protobuf.IStruct|null} [structValue] Value structValue + * @property {google.protobuf.IListValue|null} [listValue] Value listValue + */ + + /** + * Constructs a new Value. + * @memberof google.protobuf + * @classdesc Represents a Value. + * @implements IValue + * @constructor + * @param {google.protobuf.IValue=} [properties] Properties to set + */ + function Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Value nullValue. + * @member {google.protobuf.NullValue|null|undefined} nullValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.nullValue = null; + + /** + * Value numberValue. + * @member {number|null|undefined} numberValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.numberValue = null; + + /** + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.stringValue = null; + + /** + * Value boolValue. + * @member {boolean|null|undefined} boolValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.boolValue = null; + + /** + * Value structValue. + * @member {google.protobuf.IStruct|null|undefined} structValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.structValue = null; + + /** + * Value listValue. + * @member {google.protobuf.IListValue|null|undefined} listValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.listValue = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Value kind. + * @member {"nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"|undefined} kind + * @memberof google.protobuf.Value + * @instance + */ + Object.defineProperty(Value.prototype, "kind", { + get: $util.oneOfGetter($oneOfFields = ["nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new Value instance using the specified properties. + * @function create + * @memberof google.protobuf.Value + * @static + * @param {google.protobuf.IValue=} [properties] Properties to set + * @returns {google.protobuf.Value} Value instance + */ + Value.create = function create(properties) { + return new Value(properties); + }; + + /** + * Encodes the specified Value message. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. + * @function encode + * @memberof google.protobuf.Value + * @static + * @param {google.protobuf.IValue} message Value message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Value.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.nullValue != null && Object.hasOwnProperty.call(message, "nullValue")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.nullValue); + if (message.numberValue != null && Object.hasOwnProperty.call(message, "numberValue")) + writer.uint32(/* id 2, wireType 1 =*/17).double(message.numberValue); + if (message.stringValue != null && Object.hasOwnProperty.call(message, "stringValue")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.stringValue); + if (message.boolValue != null && Object.hasOwnProperty.call(message, "boolValue")) + writer.uint32(/* id 4, wireType 0 =*/32).bool(message.boolValue); + if (message.structValue != null && Object.hasOwnProperty.call(message, "structValue")) + $root.google.protobuf.Struct.encode(message.structValue, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.listValue != null && Object.hasOwnProperty.call(message, "listValue")) + $root.google.protobuf.ListValue.encode(message.listValue, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Value message, length delimited. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.Value + * @static + * @param {google.protobuf.IValue} message Value message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Value.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Value message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.Value + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.Value} Value + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Value.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.Value(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.nullValue = reader.int32(); + break; + } + case 2: { + message.numberValue = reader.double(); + break; + } + case 3: { + message.stringValue = reader.string(); + break; + } + case 4: { + message.boolValue = reader.bool(); + break; + } + case 5: { + message.structValue = $root.google.protobuf.Struct.decode(reader, reader.uint32()); + break; + } + case 6: { + message.listValue = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Value message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.Value + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.Value} Value + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Value.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Value message. + * @function verify + * @memberof google.protobuf.Value + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Value.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + properties.kind = 1; + switch (message.nullValue) { + default: + return "nullValue: enum value expected"; + case 0: + break; + } + } + if (message.numberValue != null && message.hasOwnProperty("numberValue")) { + if (properties.kind === 1) + return "kind: multiple values"; + properties.kind = 1; + if (typeof message.numberValue !== "number") + return "numberValue: number expected"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + if (properties.kind === 1) + return "kind: multiple values"; + properties.kind = 1; + if (!$util.isString(message.stringValue)) + return "stringValue: string expected"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + if (properties.kind === 1) + return "kind: multiple values"; + properties.kind = 1; + if (typeof message.boolValue !== "boolean") + return "boolValue: boolean expected"; + } + if (message.structValue != null && message.hasOwnProperty("structValue")) { + if (properties.kind === 1) + return "kind: multiple values"; + properties.kind = 1; + { + var error = $root.google.protobuf.Struct.verify(message.structValue); + if (error) + return "structValue." + error; + } + } + if (message.listValue != null && message.hasOwnProperty("listValue")) { + if (properties.kind === 1) + return "kind: multiple values"; + properties.kind = 1; + { + var error = $root.google.protobuf.ListValue.verify(message.listValue); + if (error) + return "listValue." + error; + } + } + return null; + }; + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Value + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Value} Value + */ + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Value) + return object; + var message = new $root.google.protobuf.Value(); + switch (object.nullValue) { + default: + if (typeof object.nullValue === "number") { + message.nullValue = object.nullValue; + break; + } + break; + case "NULL_VALUE": + case 0: + message.nullValue = 0; + break; + } + if (object.numberValue != null) + message.numberValue = Number(object.numberValue); + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.boolValue != null) + message.boolValue = Boolean(object.boolValue); + if (object.structValue != null) { + if (typeof object.structValue !== "object") + throw TypeError(".google.protobuf.Value.structValue: object expected"); + message.structValue = $root.google.protobuf.Struct.fromObject(object.structValue); + } + if (object.listValue != null) { + if (typeof object.listValue !== "object") + throw TypeError(".google.protobuf.Value.listValue: object expected"); + message.listValue = $root.google.protobuf.ListValue.fromObject(object.listValue); + } + return message; + }; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Value + * @static + * @param {google.protobuf.Value} message Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; + if (options.oneofs) + object.kind = "nullValue"; + } + if (message.numberValue != null && message.hasOwnProperty("numberValue")) { + object.numberValue = options.json && !isFinite(message.numberValue) ? String(message.numberValue) : message.numberValue; + if (options.oneofs) + object.kind = "numberValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.kind = "stringValue"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + object.boolValue = message.boolValue; + if (options.oneofs) + object.kind = "boolValue"; + } + if (message.structValue != null && message.hasOwnProperty("structValue")) { + object.structValue = $root.google.protobuf.Struct.toObject(message.structValue, options); + if (options.oneofs) + object.kind = "structValue"; + } + if (message.listValue != null && message.hasOwnProperty("listValue")) { + object.listValue = $root.google.protobuf.ListValue.toObject(message.listValue, options); + if (options.oneofs) + object.kind = "listValue"; + } + return object; + }; + + /** + * Converts this Value to JSON. + * @function toJSON + * @memberof google.protobuf.Value + * @instance + * @returns {Object.} JSON object + */ + Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Value + * @function getTypeUrl + * @memberof google.protobuf.Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Value"; + }; + + return Value; + })(); + + /** + * NullValue enum. + * @name google.protobuf.NullValue + * @enum {number} + * @property {number} NULL_VALUE=0 NULL_VALUE value + */ + protobuf.NullValue = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NULL_VALUE"] = 0; + return values; + })(); + + protobuf.ListValue = (function() { + + /** + * Properties of a ListValue. + * @memberof google.protobuf + * @interface IListValue + * @property {Array.|null} [values] ListValue values + */ + + /** + * Constructs a new ListValue. + * @memberof google.protobuf + * @classdesc Represents a ListValue. + * @implements IListValue + * @constructor + * @param {google.protobuf.IListValue=} [properties] Properties to set + */ + function ListValue(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListValue values. + * @member {Array.} values + * @memberof google.protobuf.ListValue + * @instance + */ + ListValue.prototype.values = $util.emptyArray; + + /** + * Creates a new ListValue instance using the specified properties. + * @function create + * @memberof google.protobuf.ListValue + * @static + * @param {google.protobuf.IListValue=} [properties] Properties to set + * @returns {google.protobuf.ListValue} ListValue instance + */ + ListValue.create = function create(properties) { + return new ListValue(properties); + }; + + /** + * Encodes the specified ListValue message. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. + * @function encode + * @memberof google.protobuf.ListValue + * @static + * @param {google.protobuf.IListValue} message ListValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListValue.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.values != null && message.values.length) + for (var i = 0; i < message.values.length; ++i) + $root.google.protobuf.Value.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ListValue message, length delimited. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.ListValue + * @static + * @param {google.protobuf.IListValue} message ListValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListValue.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListValue message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.ListValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.ListValue} ListValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListValue.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.ListValue(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.values && message.values.length)) + message.values = []; + message.values.push($root.google.protobuf.Value.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListValue message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.ListValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.ListValue} ListValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListValue.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListValue message. + * @function verify + * @memberof google.protobuf.ListValue + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListValue.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.values != null && message.hasOwnProperty("values")) { + if (!Array.isArray(message.values)) + return "values: array expected"; + for (var i = 0; i < message.values.length; ++i) { + var error = $root.google.protobuf.Value.verify(message.values[i]); + if (error) + return "values." + error; + } + } + return null; + }; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ListValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ListValue} ListValue + */ + ListValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ListValue) + return object; + var message = new $root.google.protobuf.ListValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.protobuf.ListValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.protobuf.ListValue.values: object expected"); + message.values[i] = $root.google.protobuf.Value.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ListValue + * @static + * @param {google.protobuf.ListValue} message ListValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.protobuf.Value.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this ListValue to JSON. + * @function toJSON + * @memberof google.protobuf.ListValue + * @instance + * @returns {Object.} JSON object + */ + ListValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListValue + * @function getTypeUrl + * @memberof google.protobuf.ListValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ListValue"; + }; + + return ListValue; + })(); + + return protobuf; + })(); + + google.rpc = (function() { + + /** + * Namespace rpc. + * @memberof google + * @namespace + */ + var rpc = {}; + + rpc.ErrorInfo = (function() { + + /** + * Properties of an ErrorInfo. + * @memberof google.rpc + * @interface IErrorInfo + * @property {string|null} [reason] ErrorInfo reason + * @property {string|null} [domain] ErrorInfo domain + * @property {Object.|null} [metadata] ErrorInfo metadata + */ + + /** + * Constructs a new ErrorInfo. + * @memberof google.rpc + * @classdesc Represents an ErrorInfo. + * @implements IErrorInfo + * @constructor + * @param {google.rpc.IErrorInfo=} [properties] Properties to set + */ + function ErrorInfo(properties) { + this.metadata = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ErrorInfo reason. + * @member {string} reason + * @memberof google.rpc.ErrorInfo + * @instance + */ + ErrorInfo.prototype.reason = ""; + + /** + * ErrorInfo domain. + * @member {string} domain + * @memberof google.rpc.ErrorInfo + * @instance + */ + ErrorInfo.prototype.domain = ""; + + /** + * ErrorInfo metadata. + * @member {Object.} metadata + * @memberof google.rpc.ErrorInfo + * @instance + */ + ErrorInfo.prototype.metadata = $util.emptyObject; + + /** + * Creates a new ErrorInfo instance using the specified properties. + * @function create + * @memberof google.rpc.ErrorInfo + * @static + * @param {google.rpc.IErrorInfo=} [properties] Properties to set + * @returns {google.rpc.ErrorInfo} ErrorInfo instance + */ + ErrorInfo.create = function create(properties) { + return new ErrorInfo(properties); + }; + + /** + * Encodes the specified ErrorInfo message. Does not implicitly {@link google.rpc.ErrorInfo.verify|verify} messages. + * @function encode + * @memberof google.rpc.ErrorInfo + * @static + * @param {google.rpc.IErrorInfo} message ErrorInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ErrorInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.reason != null && Object.hasOwnProperty.call(message, "reason")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.reason); + if (message.domain != null && Object.hasOwnProperty.call(message, "domain")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.domain); + if (message.metadata != null && Object.hasOwnProperty.call(message, "metadata")) + for (var keys = Object.keys(message.metadata), i = 0; i < keys.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.metadata[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified ErrorInfo message, length delimited. Does not implicitly {@link google.rpc.ErrorInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.ErrorInfo + * @static + * @param {google.rpc.IErrorInfo} message ErrorInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ErrorInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ErrorInfo message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.ErrorInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.ErrorInfo} ErrorInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ErrorInfo.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.rpc.ErrorInfo(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.reason = reader.string(); + break; + } + case 2: { + message.domain = reader.string(); + break; + } + case 3: { + if (message.metadata === $util.emptyObject) + message.metadata = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.metadata[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ErrorInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.ErrorInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.ErrorInfo} ErrorInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ErrorInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ErrorInfo message. + * @function verify + * @memberof google.rpc.ErrorInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ErrorInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.reason != null && message.hasOwnProperty("reason")) + if (!$util.isString(message.reason)) + return "reason: string expected"; + if (message.domain != null && message.hasOwnProperty("domain")) + if (!$util.isString(message.domain)) + return "domain: string expected"; + if (message.metadata != null && message.hasOwnProperty("metadata")) { + if (!$util.isObject(message.metadata)) + return "metadata: object expected"; + var key = Object.keys(message.metadata); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.metadata[key[i]])) + return "metadata: string{k:string} expected"; + } + return null; + }; + + /** + * Creates an ErrorInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.ErrorInfo + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.ErrorInfo} ErrorInfo + */ + ErrorInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.ErrorInfo) + return object; + var message = new $root.google.rpc.ErrorInfo(); + if (object.reason != null) + message.reason = String(object.reason); + if (object.domain != null) + message.domain = String(object.domain); + if (object.metadata) { + if (typeof object.metadata !== "object") + throw TypeError(".google.rpc.ErrorInfo.metadata: object expected"); + message.metadata = {}; + for (var keys = Object.keys(object.metadata), i = 0; i < keys.length; ++i) + message.metadata[keys[i]] = String(object.metadata[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from an ErrorInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.ErrorInfo + * @static + * @param {google.rpc.ErrorInfo} message ErrorInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ErrorInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.metadata = {}; + if (options.defaults) { + object.reason = ""; + object.domain = ""; + } + if (message.reason != null && message.hasOwnProperty("reason")) + object.reason = message.reason; + if (message.domain != null && message.hasOwnProperty("domain")) + object.domain = message.domain; + var keys2; + if (message.metadata && (keys2 = Object.keys(message.metadata)).length) { + object.metadata = {}; + for (var j = 0; j < keys2.length; ++j) + object.metadata[keys2[j]] = message.metadata[keys2[j]]; + } + return object; + }; + + /** + * Converts this ErrorInfo to JSON. + * @function toJSON + * @memberof google.rpc.ErrorInfo + * @instance + * @returns {Object.} JSON object + */ + ErrorInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ErrorInfo + * @function getTypeUrl + * @memberof google.rpc.ErrorInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ErrorInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.ErrorInfo"; + }; + + return ErrorInfo; + })(); + + rpc.RetryInfo = (function() { + + /** + * Properties of a RetryInfo. + * @memberof google.rpc + * @interface IRetryInfo + * @property {google.protobuf.IDuration|null} [retryDelay] RetryInfo retryDelay + */ + + /** + * Constructs a new RetryInfo. + * @memberof google.rpc + * @classdesc Represents a RetryInfo. + * @implements IRetryInfo + * @constructor + * @param {google.rpc.IRetryInfo=} [properties] Properties to set + */ + function RetryInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RetryInfo retryDelay. + * @member {google.protobuf.IDuration|null|undefined} retryDelay + * @memberof google.rpc.RetryInfo + * @instance + */ + RetryInfo.prototype.retryDelay = null; + + /** + * Creates a new RetryInfo instance using the specified properties. + * @function create + * @memberof google.rpc.RetryInfo + * @static + * @param {google.rpc.IRetryInfo=} [properties] Properties to set + * @returns {google.rpc.RetryInfo} RetryInfo instance + */ + RetryInfo.create = function create(properties) { + return new RetryInfo(properties); + }; + + /** + * Encodes the specified RetryInfo message. Does not implicitly {@link google.rpc.RetryInfo.verify|verify} messages. + * @function encode + * @memberof google.rpc.RetryInfo + * @static + * @param {google.rpc.IRetryInfo} message RetryInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RetryInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.retryDelay != null && Object.hasOwnProperty.call(message, "retryDelay")) + $root.google.protobuf.Duration.encode(message.retryDelay, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RetryInfo message, length delimited. Does not implicitly {@link google.rpc.RetryInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.RetryInfo + * @static + * @param {google.rpc.IRetryInfo} message RetryInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RetryInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RetryInfo message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.RetryInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.RetryInfo} RetryInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RetryInfo.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.rpc.RetryInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.retryDelay = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RetryInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.RetryInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.RetryInfo} RetryInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RetryInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RetryInfo message. + * @function verify + * @memberof google.rpc.RetryInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RetryInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.retryDelay != null && message.hasOwnProperty("retryDelay")) { + var error = $root.google.protobuf.Duration.verify(message.retryDelay); + if (error) + return "retryDelay." + error; + } + return null; + }; + + /** + * Creates a RetryInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.RetryInfo + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.RetryInfo} RetryInfo + */ + RetryInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.RetryInfo) + return object; + var message = new $root.google.rpc.RetryInfo(); + if (object.retryDelay != null) { + if (typeof object.retryDelay !== "object") + throw TypeError(".google.rpc.RetryInfo.retryDelay: object expected"); + message.retryDelay = $root.google.protobuf.Duration.fromObject(object.retryDelay); + } + return message; + }; + + /** + * Creates a plain object from a RetryInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.RetryInfo + * @static + * @param {google.rpc.RetryInfo} message RetryInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RetryInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.retryDelay = null; + if (message.retryDelay != null && message.hasOwnProperty("retryDelay")) + object.retryDelay = $root.google.protobuf.Duration.toObject(message.retryDelay, options); + return object; + }; + + /** + * Converts this RetryInfo to JSON. + * @function toJSON + * @memberof google.rpc.RetryInfo + * @instance + * @returns {Object.} JSON object + */ + RetryInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RetryInfo + * @function getTypeUrl + * @memberof google.rpc.RetryInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RetryInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.RetryInfo"; + }; + + return RetryInfo; + })(); + + rpc.DebugInfo = (function() { + + /** + * Properties of a DebugInfo. + * @memberof google.rpc + * @interface IDebugInfo + * @property {Array.|null} [stackEntries] DebugInfo stackEntries + * @property {string|null} [detail] DebugInfo detail + */ + + /** + * Constructs a new DebugInfo. + * @memberof google.rpc + * @classdesc Represents a DebugInfo. + * @implements IDebugInfo + * @constructor + * @param {google.rpc.IDebugInfo=} [properties] Properties to set + */ + function DebugInfo(properties) { + this.stackEntries = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DebugInfo stackEntries. + * @member {Array.} stackEntries + * @memberof google.rpc.DebugInfo + * @instance + */ + DebugInfo.prototype.stackEntries = $util.emptyArray; + + /** + * DebugInfo detail. + * @member {string} detail + * @memberof google.rpc.DebugInfo + * @instance + */ + DebugInfo.prototype.detail = ""; + + /** + * Creates a new DebugInfo instance using the specified properties. + * @function create + * @memberof google.rpc.DebugInfo + * @static + * @param {google.rpc.IDebugInfo=} [properties] Properties to set + * @returns {google.rpc.DebugInfo} DebugInfo instance + */ + DebugInfo.create = function create(properties) { + return new DebugInfo(properties); + }; + + /** + * Encodes the specified DebugInfo message. Does not implicitly {@link google.rpc.DebugInfo.verify|verify} messages. + * @function encode + * @memberof google.rpc.DebugInfo + * @static + * @param {google.rpc.IDebugInfo} message DebugInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DebugInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.stackEntries != null && message.stackEntries.length) + for (var i = 0; i < message.stackEntries.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.stackEntries[i]); + if (message.detail != null && Object.hasOwnProperty.call(message, "detail")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.detail); + return writer; + }; + + /** + * Encodes the specified DebugInfo message, length delimited. Does not implicitly {@link google.rpc.DebugInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.DebugInfo + * @static + * @param {google.rpc.IDebugInfo} message DebugInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DebugInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DebugInfo message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.DebugInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.DebugInfo} DebugInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DebugInfo.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.rpc.DebugInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.stackEntries && message.stackEntries.length)) + message.stackEntries = []; + message.stackEntries.push(reader.string()); + break; + } + case 2: { + message.detail = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DebugInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.DebugInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.DebugInfo} DebugInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DebugInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DebugInfo message. + * @function verify + * @memberof google.rpc.DebugInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DebugInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.stackEntries != null && message.hasOwnProperty("stackEntries")) { + if (!Array.isArray(message.stackEntries)) + return "stackEntries: array expected"; + for (var i = 0; i < message.stackEntries.length; ++i) + if (!$util.isString(message.stackEntries[i])) + return "stackEntries: string[] expected"; + } + if (message.detail != null && message.hasOwnProperty("detail")) + if (!$util.isString(message.detail)) + return "detail: string expected"; + return null; + }; + + /** + * Creates a DebugInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.DebugInfo + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.DebugInfo} DebugInfo + */ + DebugInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.DebugInfo) + return object; + var message = new $root.google.rpc.DebugInfo(); + if (object.stackEntries) { + if (!Array.isArray(object.stackEntries)) + throw TypeError(".google.rpc.DebugInfo.stackEntries: array expected"); + message.stackEntries = []; + for (var i = 0; i < object.stackEntries.length; ++i) + message.stackEntries[i] = String(object.stackEntries[i]); + } + if (object.detail != null) + message.detail = String(object.detail); + return message; + }; + + /** + * Creates a plain object from a DebugInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.DebugInfo + * @static + * @param {google.rpc.DebugInfo} message DebugInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DebugInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.stackEntries = []; + if (options.defaults) + object.detail = ""; + if (message.stackEntries && message.stackEntries.length) { + object.stackEntries = []; + for (var j = 0; j < message.stackEntries.length; ++j) + object.stackEntries[j] = message.stackEntries[j]; + } + if (message.detail != null && message.hasOwnProperty("detail")) + object.detail = message.detail; + return object; + }; + + /** + * Converts this DebugInfo to JSON. + * @function toJSON + * @memberof google.rpc.DebugInfo + * @instance + * @returns {Object.} JSON object + */ + DebugInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DebugInfo + * @function getTypeUrl + * @memberof google.rpc.DebugInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DebugInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.DebugInfo"; + }; + + return DebugInfo; + })(); + + rpc.QuotaFailure = (function() { + + /** + * Properties of a QuotaFailure. + * @memberof google.rpc + * @interface IQuotaFailure + * @property {Array.|null} [violations] QuotaFailure violations + */ + + /** + * Constructs a new QuotaFailure. + * @memberof google.rpc + * @classdesc Represents a QuotaFailure. + * @implements IQuotaFailure + * @constructor + * @param {google.rpc.IQuotaFailure=} [properties] Properties to set + */ + function QuotaFailure(properties) { + this.violations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QuotaFailure violations. + * @member {Array.} violations + * @memberof google.rpc.QuotaFailure + * @instance + */ + QuotaFailure.prototype.violations = $util.emptyArray; + + /** + * Creates a new QuotaFailure instance using the specified properties. + * @function create + * @memberof google.rpc.QuotaFailure + * @static + * @param {google.rpc.IQuotaFailure=} [properties] Properties to set + * @returns {google.rpc.QuotaFailure} QuotaFailure instance + */ + QuotaFailure.create = function create(properties) { + return new QuotaFailure(properties); + }; + + /** + * Encodes the specified QuotaFailure message. Does not implicitly {@link google.rpc.QuotaFailure.verify|verify} messages. + * @function encode + * @memberof google.rpc.QuotaFailure + * @static + * @param {google.rpc.IQuotaFailure} message QuotaFailure message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QuotaFailure.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.violations != null && message.violations.length) + for (var i = 0; i < message.violations.length; ++i) + $root.google.rpc.QuotaFailure.Violation.encode(message.violations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified QuotaFailure message, length delimited. Does not implicitly {@link google.rpc.QuotaFailure.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.QuotaFailure + * @static + * @param {google.rpc.IQuotaFailure} message QuotaFailure message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QuotaFailure.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a QuotaFailure message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.QuotaFailure + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.QuotaFailure} QuotaFailure + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QuotaFailure.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.rpc.QuotaFailure(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.violations && message.violations.length)) + message.violations = []; + message.violations.push($root.google.rpc.QuotaFailure.Violation.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a QuotaFailure message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.QuotaFailure + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.QuotaFailure} QuotaFailure + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QuotaFailure.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a QuotaFailure message. + * @function verify + * @memberof google.rpc.QuotaFailure + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + QuotaFailure.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.violations != null && message.hasOwnProperty("violations")) { + if (!Array.isArray(message.violations)) + return "violations: array expected"; + for (var i = 0; i < message.violations.length; ++i) { + var error = $root.google.rpc.QuotaFailure.Violation.verify(message.violations[i]); + if (error) + return "violations." + error; + } + } + return null; + }; + + /** + * Creates a QuotaFailure message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.QuotaFailure + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.QuotaFailure} QuotaFailure + */ + QuotaFailure.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.QuotaFailure) + return object; + var message = new $root.google.rpc.QuotaFailure(); + if (object.violations) { + if (!Array.isArray(object.violations)) + throw TypeError(".google.rpc.QuotaFailure.violations: array expected"); + message.violations = []; + for (var i = 0; i < object.violations.length; ++i) { + if (typeof object.violations[i] !== "object") + throw TypeError(".google.rpc.QuotaFailure.violations: object expected"); + message.violations[i] = $root.google.rpc.QuotaFailure.Violation.fromObject(object.violations[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a QuotaFailure message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.QuotaFailure + * @static + * @param {google.rpc.QuotaFailure} message QuotaFailure + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QuotaFailure.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.violations = []; + if (message.violations && message.violations.length) { + object.violations = []; + for (var j = 0; j < message.violations.length; ++j) + object.violations[j] = $root.google.rpc.QuotaFailure.Violation.toObject(message.violations[j], options); + } + return object; + }; + + /** + * Converts this QuotaFailure to JSON. + * @function toJSON + * @memberof google.rpc.QuotaFailure + * @instance + * @returns {Object.} JSON object + */ + QuotaFailure.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QuotaFailure + * @function getTypeUrl + * @memberof google.rpc.QuotaFailure + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QuotaFailure.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.QuotaFailure"; + }; + + QuotaFailure.Violation = (function() { + + /** + * Properties of a Violation. + * @memberof google.rpc.QuotaFailure + * @interface IViolation + * @property {string|null} [subject] Violation subject + * @property {string|null} [description] Violation description + */ + + /** + * Constructs a new Violation. + * @memberof google.rpc.QuotaFailure + * @classdesc Represents a Violation. + * @implements IViolation + * @constructor + * @param {google.rpc.QuotaFailure.IViolation=} [properties] Properties to set + */ + function Violation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Violation subject. + * @member {string} subject + * @memberof google.rpc.QuotaFailure.Violation + * @instance + */ + Violation.prototype.subject = ""; + + /** + * Violation description. + * @member {string} description + * @memberof google.rpc.QuotaFailure.Violation + * @instance + */ + Violation.prototype.description = ""; + + /** + * Creates a new Violation instance using the specified properties. + * @function create + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {google.rpc.QuotaFailure.IViolation=} [properties] Properties to set + * @returns {google.rpc.QuotaFailure.Violation} Violation instance + */ + Violation.create = function create(properties) { + return new Violation(properties); + }; + + /** + * Encodes the specified Violation message. Does not implicitly {@link google.rpc.QuotaFailure.Violation.verify|verify} messages. + * @function encode + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {google.rpc.QuotaFailure.IViolation} message Violation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Violation.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.subject != null && Object.hasOwnProperty.call(message, "subject")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.subject); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.description); + return writer; + }; + + /** + * Encodes the specified Violation message, length delimited. Does not implicitly {@link google.rpc.QuotaFailure.Violation.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {google.rpc.QuotaFailure.IViolation} message Violation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Violation.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Violation message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.QuotaFailure.Violation} Violation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Violation.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.rpc.QuotaFailure.Violation(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.subject = reader.string(); + break; + } + case 2: { + message.description = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Violation message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.QuotaFailure.Violation} Violation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Violation.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Violation message. + * @function verify + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Violation.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.subject != null && message.hasOwnProperty("subject")) + if (!$util.isString(message.subject)) + return "subject: string expected"; + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + return null; + }; + + /** + * Creates a Violation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.QuotaFailure.Violation} Violation + */ + Violation.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.QuotaFailure.Violation) + return object; + var message = new $root.google.rpc.QuotaFailure.Violation(); + if (object.subject != null) + message.subject = String(object.subject); + if (object.description != null) + message.description = String(object.description); + return message; + }; + + /** + * Creates a plain object from a Violation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {google.rpc.QuotaFailure.Violation} message Violation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Violation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.subject = ""; + object.description = ""; + } + if (message.subject != null && message.hasOwnProperty("subject")) + object.subject = message.subject; + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + return object; + }; + + /** + * Converts this Violation to JSON. + * @function toJSON + * @memberof google.rpc.QuotaFailure.Violation + * @instance + * @returns {Object.} JSON object + */ + Violation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Violation + * @function getTypeUrl + * @memberof google.rpc.QuotaFailure.Violation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Violation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.QuotaFailure.Violation"; + }; + + return Violation; + })(); + + return QuotaFailure; + })(); + + rpc.PreconditionFailure = (function() { + + /** + * Properties of a PreconditionFailure. + * @memberof google.rpc + * @interface IPreconditionFailure + * @property {Array.|null} [violations] PreconditionFailure violations + */ + + /** + * Constructs a new PreconditionFailure. + * @memberof google.rpc + * @classdesc Represents a PreconditionFailure. + * @implements IPreconditionFailure + * @constructor + * @param {google.rpc.IPreconditionFailure=} [properties] Properties to set + */ + function PreconditionFailure(properties) { + this.violations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PreconditionFailure violations. + * @member {Array.} violations + * @memberof google.rpc.PreconditionFailure + * @instance + */ + PreconditionFailure.prototype.violations = $util.emptyArray; + + /** + * Creates a new PreconditionFailure instance using the specified properties. + * @function create + * @memberof google.rpc.PreconditionFailure + * @static + * @param {google.rpc.IPreconditionFailure=} [properties] Properties to set + * @returns {google.rpc.PreconditionFailure} PreconditionFailure instance + */ + PreconditionFailure.create = function create(properties) { + return new PreconditionFailure(properties); + }; + + /** + * Encodes the specified PreconditionFailure message. Does not implicitly {@link google.rpc.PreconditionFailure.verify|verify} messages. + * @function encode + * @memberof google.rpc.PreconditionFailure + * @static + * @param {google.rpc.IPreconditionFailure} message PreconditionFailure message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PreconditionFailure.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.violations != null && message.violations.length) + for (var i = 0; i < message.violations.length; ++i) + $root.google.rpc.PreconditionFailure.Violation.encode(message.violations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PreconditionFailure message, length delimited. Does not implicitly {@link google.rpc.PreconditionFailure.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.PreconditionFailure + * @static + * @param {google.rpc.IPreconditionFailure} message PreconditionFailure message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PreconditionFailure.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PreconditionFailure message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.PreconditionFailure + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.PreconditionFailure} PreconditionFailure + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PreconditionFailure.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.rpc.PreconditionFailure(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.violations && message.violations.length)) + message.violations = []; + message.violations.push($root.google.rpc.PreconditionFailure.Violation.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PreconditionFailure message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.PreconditionFailure + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.PreconditionFailure} PreconditionFailure + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PreconditionFailure.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PreconditionFailure message. + * @function verify + * @memberof google.rpc.PreconditionFailure + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PreconditionFailure.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.violations != null && message.hasOwnProperty("violations")) { + if (!Array.isArray(message.violations)) + return "violations: array expected"; + for (var i = 0; i < message.violations.length; ++i) { + var error = $root.google.rpc.PreconditionFailure.Violation.verify(message.violations[i]); + if (error) + return "violations." + error; + } + } + return null; + }; + + /** + * Creates a PreconditionFailure message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.PreconditionFailure + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.PreconditionFailure} PreconditionFailure + */ + PreconditionFailure.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.PreconditionFailure) + return object; + var message = new $root.google.rpc.PreconditionFailure(); + if (object.violations) { + if (!Array.isArray(object.violations)) + throw TypeError(".google.rpc.PreconditionFailure.violations: array expected"); + message.violations = []; + for (var i = 0; i < object.violations.length; ++i) { + if (typeof object.violations[i] !== "object") + throw TypeError(".google.rpc.PreconditionFailure.violations: object expected"); + message.violations[i] = $root.google.rpc.PreconditionFailure.Violation.fromObject(object.violations[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a PreconditionFailure message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.PreconditionFailure + * @static + * @param {google.rpc.PreconditionFailure} message PreconditionFailure + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PreconditionFailure.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.violations = []; + if (message.violations && message.violations.length) { + object.violations = []; + for (var j = 0; j < message.violations.length; ++j) + object.violations[j] = $root.google.rpc.PreconditionFailure.Violation.toObject(message.violations[j], options); + } + return object; + }; + + /** + * Converts this PreconditionFailure to JSON. + * @function toJSON + * @memberof google.rpc.PreconditionFailure + * @instance + * @returns {Object.} JSON object + */ + PreconditionFailure.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PreconditionFailure + * @function getTypeUrl + * @memberof google.rpc.PreconditionFailure + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PreconditionFailure.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.PreconditionFailure"; + }; + + PreconditionFailure.Violation = (function() { + + /** + * Properties of a Violation. + * @memberof google.rpc.PreconditionFailure + * @interface IViolation + * @property {string|null} [type] Violation type + * @property {string|null} [subject] Violation subject + * @property {string|null} [description] Violation description + */ + + /** + * Constructs a new Violation. + * @memberof google.rpc.PreconditionFailure + * @classdesc Represents a Violation. + * @implements IViolation + * @constructor + * @param {google.rpc.PreconditionFailure.IViolation=} [properties] Properties to set + */ + function Violation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Violation type. + * @member {string} type + * @memberof google.rpc.PreconditionFailure.Violation + * @instance + */ + Violation.prototype.type = ""; + + /** + * Violation subject. + * @member {string} subject + * @memberof google.rpc.PreconditionFailure.Violation + * @instance + */ + Violation.prototype.subject = ""; + + /** + * Violation description. + * @member {string} description + * @memberof google.rpc.PreconditionFailure.Violation + * @instance + */ + Violation.prototype.description = ""; + + /** + * Creates a new Violation instance using the specified properties. + * @function create + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {google.rpc.PreconditionFailure.IViolation=} [properties] Properties to set + * @returns {google.rpc.PreconditionFailure.Violation} Violation instance + */ + Violation.create = function create(properties) { + return new Violation(properties); + }; + + /** + * Encodes the specified Violation message. Does not implicitly {@link google.rpc.PreconditionFailure.Violation.verify|verify} messages. + * @function encode + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {google.rpc.PreconditionFailure.IViolation} message Violation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Violation.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.type); + if (message.subject != null && Object.hasOwnProperty.call(message, "subject")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.subject); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.description); + return writer; + }; + + /** + * Encodes the specified Violation message, length delimited. Does not implicitly {@link google.rpc.PreconditionFailure.Violation.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {google.rpc.PreconditionFailure.IViolation} message Violation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Violation.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Violation message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.PreconditionFailure.Violation} Violation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Violation.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.rpc.PreconditionFailure.Violation(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.type = reader.string(); + break; + } + case 2: { + message.subject = reader.string(); + break; + } + case 3: { + message.description = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Violation message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.PreconditionFailure.Violation} Violation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Violation.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Violation message. + * @function verify + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Violation.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.subject != null && message.hasOwnProperty("subject")) + if (!$util.isString(message.subject)) + return "subject: string expected"; + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + return null; + }; + + /** + * Creates a Violation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.PreconditionFailure.Violation} Violation + */ + Violation.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.PreconditionFailure.Violation) + return object; + var message = new $root.google.rpc.PreconditionFailure.Violation(); + if (object.type != null) + message.type = String(object.type); + if (object.subject != null) + message.subject = String(object.subject); + if (object.description != null) + message.description = String(object.description); + return message; + }; + + /** + * Creates a plain object from a Violation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {google.rpc.PreconditionFailure.Violation} message Violation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Violation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type = ""; + object.subject = ""; + object.description = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.subject != null && message.hasOwnProperty("subject")) + object.subject = message.subject; + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + return object; + }; + + /** + * Converts this Violation to JSON. + * @function toJSON + * @memberof google.rpc.PreconditionFailure.Violation + * @instance + * @returns {Object.} JSON object + */ + Violation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Violation + * @function getTypeUrl + * @memberof google.rpc.PreconditionFailure.Violation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Violation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.PreconditionFailure.Violation"; + }; + + return Violation; + })(); + + return PreconditionFailure; + })(); + + rpc.BadRequest = (function() { + + /** + * Properties of a BadRequest. + * @memberof google.rpc + * @interface IBadRequest + * @property {Array.|null} [fieldViolations] BadRequest fieldViolations + */ + + /** + * Constructs a new BadRequest. + * @memberof google.rpc + * @classdesc Represents a BadRequest. + * @implements IBadRequest + * @constructor + * @param {google.rpc.IBadRequest=} [properties] Properties to set + */ + function BadRequest(properties) { + this.fieldViolations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BadRequest fieldViolations. + * @member {Array.} fieldViolations + * @memberof google.rpc.BadRequest + * @instance + */ + BadRequest.prototype.fieldViolations = $util.emptyArray; + + /** + * Creates a new BadRequest instance using the specified properties. + * @function create + * @memberof google.rpc.BadRequest + * @static + * @param {google.rpc.IBadRequest=} [properties] Properties to set + * @returns {google.rpc.BadRequest} BadRequest instance + */ + BadRequest.create = function create(properties) { + return new BadRequest(properties); + }; + + /** + * Encodes the specified BadRequest message. Does not implicitly {@link google.rpc.BadRequest.verify|verify} messages. + * @function encode + * @memberof google.rpc.BadRequest + * @static + * @param {google.rpc.IBadRequest} message BadRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BadRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.fieldViolations != null && message.fieldViolations.length) + for (var i = 0; i < message.fieldViolations.length; ++i) + $root.google.rpc.BadRequest.FieldViolation.encode(message.fieldViolations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BadRequest message, length delimited. Does not implicitly {@link google.rpc.BadRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.BadRequest + * @static + * @param {google.rpc.IBadRequest} message BadRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BadRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BadRequest message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.BadRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.BadRequest} BadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BadRequest.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.rpc.BadRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.fieldViolations && message.fieldViolations.length)) + message.fieldViolations = []; + message.fieldViolations.push($root.google.rpc.BadRequest.FieldViolation.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BadRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.BadRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.BadRequest} BadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BadRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BadRequest message. + * @function verify + * @memberof google.rpc.BadRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BadRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.fieldViolations != null && message.hasOwnProperty("fieldViolations")) { + if (!Array.isArray(message.fieldViolations)) + return "fieldViolations: array expected"; + for (var i = 0; i < message.fieldViolations.length; ++i) { + var error = $root.google.rpc.BadRequest.FieldViolation.verify(message.fieldViolations[i]); + if (error) + return "fieldViolations." + error; + } + } + return null; + }; + + /** + * Creates a BadRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.BadRequest + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.BadRequest} BadRequest + */ + BadRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.BadRequest) + return object; + var message = new $root.google.rpc.BadRequest(); + if (object.fieldViolations) { + if (!Array.isArray(object.fieldViolations)) + throw TypeError(".google.rpc.BadRequest.fieldViolations: array expected"); + message.fieldViolations = []; + for (var i = 0; i < object.fieldViolations.length; ++i) { + if (typeof object.fieldViolations[i] !== "object") + throw TypeError(".google.rpc.BadRequest.fieldViolations: object expected"); + message.fieldViolations[i] = $root.google.rpc.BadRequest.FieldViolation.fromObject(object.fieldViolations[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a BadRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.BadRequest + * @static + * @param {google.rpc.BadRequest} message BadRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BadRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fieldViolations = []; + if (message.fieldViolations && message.fieldViolations.length) { + object.fieldViolations = []; + for (var j = 0; j < message.fieldViolations.length; ++j) + object.fieldViolations[j] = $root.google.rpc.BadRequest.FieldViolation.toObject(message.fieldViolations[j], options); + } + return object; + }; + + /** + * Converts this BadRequest to JSON. + * @function toJSON + * @memberof google.rpc.BadRequest + * @instance + * @returns {Object.} JSON object + */ + BadRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BadRequest + * @function getTypeUrl + * @memberof google.rpc.BadRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BadRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.BadRequest"; + }; + + BadRequest.FieldViolation = (function() { + + /** + * Properties of a FieldViolation. + * @memberof google.rpc.BadRequest + * @interface IFieldViolation + * @property {string|null} [field] FieldViolation field + * @property {string|null} [description] FieldViolation description + */ + + /** + * Constructs a new FieldViolation. + * @memberof google.rpc.BadRequest + * @classdesc Represents a FieldViolation. + * @implements IFieldViolation + * @constructor + * @param {google.rpc.BadRequest.IFieldViolation=} [properties] Properties to set + */ + function FieldViolation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldViolation field. + * @member {string} field + * @memberof google.rpc.BadRequest.FieldViolation + * @instance + */ + FieldViolation.prototype.field = ""; + + /** + * FieldViolation description. + * @member {string} description + * @memberof google.rpc.BadRequest.FieldViolation + * @instance + */ + FieldViolation.prototype.description = ""; + + /** + * Creates a new FieldViolation instance using the specified properties. + * @function create + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {google.rpc.BadRequest.IFieldViolation=} [properties] Properties to set + * @returns {google.rpc.BadRequest.FieldViolation} FieldViolation instance + */ + FieldViolation.create = function create(properties) { + return new FieldViolation(properties); + }; + + /** + * Encodes the specified FieldViolation message. Does not implicitly {@link google.rpc.BadRequest.FieldViolation.verify|verify} messages. + * @function encode + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {google.rpc.BadRequest.IFieldViolation} message FieldViolation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldViolation.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.field != null && Object.hasOwnProperty.call(message, "field")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.field); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.description); + return writer; + }; + + /** + * Encodes the specified FieldViolation message, length delimited. Does not implicitly {@link google.rpc.BadRequest.FieldViolation.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {google.rpc.BadRequest.IFieldViolation} message FieldViolation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldViolation.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FieldViolation message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.BadRequest.FieldViolation} FieldViolation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FieldViolation.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.rpc.BadRequest.FieldViolation(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.field = reader.string(); + break; + } + case 2: { + message.description = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FieldViolation message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.BadRequest.FieldViolation} FieldViolation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FieldViolation.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FieldViolation message. + * @function verify + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FieldViolation.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.field != null && message.hasOwnProperty("field")) + if (!$util.isString(message.field)) + return "field: string expected"; + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + return null; + }; + + /** + * Creates a FieldViolation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.BadRequest.FieldViolation} FieldViolation + */ + FieldViolation.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.BadRequest.FieldViolation) + return object; + var message = new $root.google.rpc.BadRequest.FieldViolation(); + if (object.field != null) + message.field = String(object.field); + if (object.description != null) + message.description = String(object.description); + return message; + }; + + /** + * Creates a plain object from a FieldViolation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {google.rpc.BadRequest.FieldViolation} message FieldViolation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldViolation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = ""; + object.description = ""; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = message.field; + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + return object; + }; + + /** + * Converts this FieldViolation to JSON. + * @function toJSON + * @memberof google.rpc.BadRequest.FieldViolation + * @instance + * @returns {Object.} JSON object + */ + FieldViolation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldViolation + * @function getTypeUrl + * @memberof google.rpc.BadRequest.FieldViolation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldViolation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.BadRequest.FieldViolation"; + }; + + return FieldViolation; + })(); + + return BadRequest; + })(); + + rpc.RequestInfo = (function() { + + /** + * Properties of a RequestInfo. + * @memberof google.rpc + * @interface IRequestInfo + * @property {string|null} [requestId] RequestInfo requestId + * @property {string|null} [servingData] RequestInfo servingData + */ + + /** + * Constructs a new RequestInfo. + * @memberof google.rpc + * @classdesc Represents a RequestInfo. + * @implements IRequestInfo + * @constructor + * @param {google.rpc.IRequestInfo=} [properties] Properties to set + */ + function RequestInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RequestInfo requestId. + * @member {string} requestId + * @memberof google.rpc.RequestInfo + * @instance + */ + RequestInfo.prototype.requestId = ""; + + /** + * RequestInfo servingData. + * @member {string} servingData + * @memberof google.rpc.RequestInfo + * @instance + */ + RequestInfo.prototype.servingData = ""; + + /** + * Creates a new RequestInfo instance using the specified properties. + * @function create + * @memberof google.rpc.RequestInfo + * @static + * @param {google.rpc.IRequestInfo=} [properties] Properties to set + * @returns {google.rpc.RequestInfo} RequestInfo instance + */ + RequestInfo.create = function create(properties) { + return new RequestInfo(properties); + }; + + /** + * Encodes the specified RequestInfo message. Does not implicitly {@link google.rpc.RequestInfo.verify|verify} messages. + * @function encode + * @memberof google.rpc.RequestInfo + * @static + * @param {google.rpc.IRequestInfo} message RequestInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RequestInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.requestId); + if (message.servingData != null && Object.hasOwnProperty.call(message, "servingData")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.servingData); + return writer; + }; + + /** + * Encodes the specified RequestInfo message, length delimited. Does not implicitly {@link google.rpc.RequestInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.RequestInfo + * @static + * @param {google.rpc.IRequestInfo} message RequestInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RequestInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RequestInfo message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.RequestInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.RequestInfo} RequestInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RequestInfo.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.rpc.RequestInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.requestId = reader.string(); + break; + } + case 2: { + message.servingData = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RequestInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.RequestInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.RequestInfo} RequestInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RequestInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RequestInfo message. + * @function verify + * @memberof google.rpc.RequestInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RequestInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + if (message.servingData != null && message.hasOwnProperty("servingData")) + if (!$util.isString(message.servingData)) + return "servingData: string expected"; + return null; + }; + + /** + * Creates a RequestInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.RequestInfo + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.RequestInfo} RequestInfo + */ + RequestInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.RequestInfo) + return object; + var message = new $root.google.rpc.RequestInfo(); + if (object.requestId != null) + message.requestId = String(object.requestId); + if (object.servingData != null) + message.servingData = String(object.servingData); + return message; + }; + + /** + * Creates a plain object from a RequestInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.RequestInfo + * @static + * @param {google.rpc.RequestInfo} message RequestInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RequestInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.requestId = ""; + object.servingData = ""; + } + if (message.requestId != null && message.hasOwnProperty("requestId")) + object.requestId = message.requestId; + if (message.servingData != null && message.hasOwnProperty("servingData")) + object.servingData = message.servingData; + return object; + }; + + /** + * Converts this RequestInfo to JSON. + * @function toJSON + * @memberof google.rpc.RequestInfo + * @instance + * @returns {Object.} JSON object + */ + RequestInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RequestInfo + * @function getTypeUrl + * @memberof google.rpc.RequestInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RequestInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.RequestInfo"; + }; + + return RequestInfo; + })(); + + rpc.ResourceInfo = (function() { + + /** + * Properties of a ResourceInfo. + * @memberof google.rpc + * @interface IResourceInfo + * @property {string|null} [resourceType] ResourceInfo resourceType + * @property {string|null} [resourceName] ResourceInfo resourceName + * @property {string|null} [owner] ResourceInfo owner + * @property {string|null} [description] ResourceInfo description + */ + + /** + * Constructs a new ResourceInfo. + * @memberof google.rpc + * @classdesc Represents a ResourceInfo. + * @implements IResourceInfo + * @constructor + * @param {google.rpc.IResourceInfo=} [properties] Properties to set + */ + function ResourceInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceInfo resourceType. + * @member {string} resourceType + * @memberof google.rpc.ResourceInfo + * @instance + */ + ResourceInfo.prototype.resourceType = ""; + + /** + * ResourceInfo resourceName. + * @member {string} resourceName + * @memberof google.rpc.ResourceInfo + * @instance + */ + ResourceInfo.prototype.resourceName = ""; + + /** + * ResourceInfo owner. + * @member {string} owner + * @memberof google.rpc.ResourceInfo + * @instance + */ + ResourceInfo.prototype.owner = ""; + + /** + * ResourceInfo description. + * @member {string} description + * @memberof google.rpc.ResourceInfo + * @instance + */ + ResourceInfo.prototype.description = ""; + + /** + * Creates a new ResourceInfo instance using the specified properties. + * @function create + * @memberof google.rpc.ResourceInfo + * @static + * @param {google.rpc.IResourceInfo=} [properties] Properties to set + * @returns {google.rpc.ResourceInfo} ResourceInfo instance + */ + ResourceInfo.create = function create(properties) { + return new ResourceInfo(properties); + }; + + /** + * Encodes the specified ResourceInfo message. Does not implicitly {@link google.rpc.ResourceInfo.verify|verify} messages. + * @function encode + * @memberof google.rpc.ResourceInfo + * @static + * @param {google.rpc.IResourceInfo} message ResourceInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceType != null && Object.hasOwnProperty.call(message, "resourceType")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.resourceType); + if (message.resourceName != null && Object.hasOwnProperty.call(message, "resourceName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.resourceName); + if (message.owner != null && Object.hasOwnProperty.call(message, "owner")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.owner); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.description); + return writer; + }; + + /** + * Encodes the specified ResourceInfo message, length delimited. Does not implicitly {@link google.rpc.ResourceInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.ResourceInfo + * @static + * @param {google.rpc.IResourceInfo} message ResourceInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ResourceInfo message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.ResourceInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.ResourceInfo} ResourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceInfo.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.rpc.ResourceInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.resourceType = reader.string(); + break; + } + case 2: { + message.resourceName = reader.string(); + break; + } + case 3: { + message.owner = reader.string(); + break; + } + case 4: { + message.description = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ResourceInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.ResourceInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.ResourceInfo} ResourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ResourceInfo message. + * @function verify + * @memberof google.rpc.ResourceInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResourceInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceType != null && message.hasOwnProperty("resourceType")) + if (!$util.isString(message.resourceType)) + return "resourceType: string expected"; + if (message.resourceName != null && message.hasOwnProperty("resourceName")) + if (!$util.isString(message.resourceName)) + return "resourceName: string expected"; + if (message.owner != null && message.hasOwnProperty("owner")) + if (!$util.isString(message.owner)) + return "owner: string expected"; + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + return null; + }; + + /** + * Creates a ResourceInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.ResourceInfo + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.ResourceInfo} ResourceInfo + */ + ResourceInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.ResourceInfo) + return object; + var message = new $root.google.rpc.ResourceInfo(); + if (object.resourceType != null) + message.resourceType = String(object.resourceType); + if (object.resourceName != null) + message.resourceName = String(object.resourceName); + if (object.owner != null) + message.owner = String(object.owner); + if (object.description != null) + message.description = String(object.description); + return message; + }; + + /** + * Creates a plain object from a ResourceInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.ResourceInfo + * @static + * @param {google.rpc.ResourceInfo} message ResourceInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.resourceType = ""; + object.resourceName = ""; + object.owner = ""; + object.description = ""; + } + if (message.resourceType != null && message.hasOwnProperty("resourceType")) + object.resourceType = message.resourceType; + if (message.resourceName != null && message.hasOwnProperty("resourceName")) + object.resourceName = message.resourceName; + if (message.owner != null && message.hasOwnProperty("owner")) + object.owner = message.owner; + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + return object; + }; + + /** + * Converts this ResourceInfo to JSON. + * @function toJSON + * @memberof google.rpc.ResourceInfo + * @instance + * @returns {Object.} JSON object + */ + ResourceInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceInfo + * @function getTypeUrl + * @memberof google.rpc.ResourceInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.ResourceInfo"; + }; + + return ResourceInfo; + })(); + + rpc.Help = (function() { + + /** + * Properties of a Help. + * @memberof google.rpc + * @interface IHelp + * @property {Array.|null} [links] Help links + */ + + /** + * Constructs a new Help. + * @memberof google.rpc + * @classdesc Represents a Help. + * @implements IHelp + * @constructor + * @param {google.rpc.IHelp=} [properties] Properties to set + */ + function Help(properties) { + this.links = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Help links. + * @member {Array.} links + * @memberof google.rpc.Help + * @instance + */ + Help.prototype.links = $util.emptyArray; + + /** + * Creates a new Help instance using the specified properties. + * @function create + * @memberof google.rpc.Help + * @static + * @param {google.rpc.IHelp=} [properties] Properties to set + * @returns {google.rpc.Help} Help instance + */ + Help.create = function create(properties) { + return new Help(properties); + }; + + /** + * Encodes the specified Help message. Does not implicitly {@link google.rpc.Help.verify|verify} messages. + * @function encode + * @memberof google.rpc.Help + * @static + * @param {google.rpc.IHelp} message Help message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Help.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.links != null && message.links.length) + for (var i = 0; i < message.links.length; ++i) + $root.google.rpc.Help.Link.encode(message.links[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Help message, length delimited. Does not implicitly {@link google.rpc.Help.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.Help + * @static + * @param {google.rpc.IHelp} message Help message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Help.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Help message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.Help + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.Help} Help + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Help.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.rpc.Help(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.links && message.links.length)) + message.links = []; + message.links.push($root.google.rpc.Help.Link.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Help message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.Help + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.Help} Help + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Help.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Help message. + * @function verify + * @memberof google.rpc.Help + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Help.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.links != null && message.hasOwnProperty("links")) { + if (!Array.isArray(message.links)) + return "links: array expected"; + for (var i = 0; i < message.links.length; ++i) { + var error = $root.google.rpc.Help.Link.verify(message.links[i]); + if (error) + return "links." + error; + } + } + return null; + }; + + /** + * Creates a Help message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.Help + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.Help} Help + */ + Help.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.Help) + return object; + var message = new $root.google.rpc.Help(); + if (object.links) { + if (!Array.isArray(object.links)) + throw TypeError(".google.rpc.Help.links: array expected"); + message.links = []; + for (var i = 0; i < object.links.length; ++i) { + if (typeof object.links[i] !== "object") + throw TypeError(".google.rpc.Help.links: object expected"); + message.links[i] = $root.google.rpc.Help.Link.fromObject(object.links[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Help message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.Help + * @static + * @param {google.rpc.Help} message Help + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Help.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.links = []; + if (message.links && message.links.length) { + object.links = []; + for (var j = 0; j < message.links.length; ++j) + object.links[j] = $root.google.rpc.Help.Link.toObject(message.links[j], options); + } + return object; + }; + + /** + * Converts this Help to JSON. + * @function toJSON + * @memberof google.rpc.Help + * @instance + * @returns {Object.} JSON object + */ + Help.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Help + * @function getTypeUrl + * @memberof google.rpc.Help + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Help.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.Help"; + }; + + Help.Link = (function() { + + /** + * Properties of a Link. + * @memberof google.rpc.Help + * @interface ILink + * @property {string|null} [description] Link description + * @property {string|null} [url] Link url + */ + + /** + * Constructs a new Link. + * @memberof google.rpc.Help + * @classdesc Represents a Link. + * @implements ILink + * @constructor + * @param {google.rpc.Help.ILink=} [properties] Properties to set + */ + function Link(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Link description. + * @member {string} description + * @memberof google.rpc.Help.Link + * @instance + */ + Link.prototype.description = ""; + + /** + * Link url. + * @member {string} url + * @memberof google.rpc.Help.Link + * @instance + */ + Link.prototype.url = ""; + + /** + * Creates a new Link instance using the specified properties. + * @function create + * @memberof google.rpc.Help.Link + * @static + * @param {google.rpc.Help.ILink=} [properties] Properties to set + * @returns {google.rpc.Help.Link} Link instance + */ + Link.create = function create(properties) { + return new Link(properties); + }; + + /** + * Encodes the specified Link message. Does not implicitly {@link google.rpc.Help.Link.verify|verify} messages. + * @function encode + * @memberof google.rpc.Help.Link + * @static + * @param {google.rpc.Help.ILink} message Link message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Link.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.description); + if (message.url != null && Object.hasOwnProperty.call(message, "url")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.url); + return writer; + }; + + /** + * Encodes the specified Link message, length delimited. Does not implicitly {@link google.rpc.Help.Link.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.Help.Link + * @static + * @param {google.rpc.Help.ILink} message Link message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Link.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Link message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.Help.Link + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.Help.Link} Link + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Link.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.rpc.Help.Link(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.description = reader.string(); + break; + } + case 2: { + message.url = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Link message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.Help.Link + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.Help.Link} Link + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Link.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Link message. + * @function verify + * @memberof google.rpc.Help.Link + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Link.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + if (message.url != null && message.hasOwnProperty("url")) + if (!$util.isString(message.url)) + return "url: string expected"; + return null; + }; + + /** + * Creates a Link message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.Help.Link + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.Help.Link} Link + */ + Link.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.Help.Link) + return object; + var message = new $root.google.rpc.Help.Link(); + if (object.description != null) + message.description = String(object.description); + if (object.url != null) + message.url = String(object.url); + return message; + }; + + /** + * Creates a plain object from a Link message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.Help.Link + * @static + * @param {google.rpc.Help.Link} message Link + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Link.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.description = ""; + object.url = ""; + } + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + if (message.url != null && message.hasOwnProperty("url")) + object.url = message.url; + return object; + }; + + /** + * Converts this Link to JSON. + * @function toJSON + * @memberof google.rpc.Help.Link + * @instance + * @returns {Object.} JSON object + */ + Link.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Link + * @function getTypeUrl + * @memberof google.rpc.Help.Link + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Link.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.Help.Link"; + }; + + return Link; + })(); + + return Help; + })(); + + rpc.LocalizedMessage = (function() { + + /** + * Properties of a LocalizedMessage. + * @memberof google.rpc + * @interface ILocalizedMessage + * @property {string|null} [locale] LocalizedMessage locale + * @property {string|null} [message] LocalizedMessage message + */ + + /** + * Constructs a new LocalizedMessage. + * @memberof google.rpc + * @classdesc Represents a LocalizedMessage. + * @implements ILocalizedMessage + * @constructor + * @param {google.rpc.ILocalizedMessage=} [properties] Properties to set + */ + function LocalizedMessage(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LocalizedMessage locale. + * @member {string} locale + * @memberof google.rpc.LocalizedMessage + * @instance + */ + LocalizedMessage.prototype.locale = ""; + + /** + * LocalizedMessage message. + * @member {string} message + * @memberof google.rpc.LocalizedMessage + * @instance + */ + LocalizedMessage.prototype.message = ""; + + /** + * Creates a new LocalizedMessage instance using the specified properties. + * @function create + * @memberof google.rpc.LocalizedMessage + * @static + * @param {google.rpc.ILocalizedMessage=} [properties] Properties to set + * @returns {google.rpc.LocalizedMessage} LocalizedMessage instance + */ + LocalizedMessage.create = function create(properties) { + return new LocalizedMessage(properties); + }; + + /** + * Encodes the specified LocalizedMessage message. Does not implicitly {@link google.rpc.LocalizedMessage.verify|verify} messages. + * @function encode + * @memberof google.rpc.LocalizedMessage + * @static + * @param {google.rpc.ILocalizedMessage} message LocalizedMessage message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LocalizedMessage.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.locale != null && Object.hasOwnProperty.call(message, "locale")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.locale); + if (message.message != null && Object.hasOwnProperty.call(message, "message")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.message); + return writer; + }; + + /** + * Encodes the specified LocalizedMessage message, length delimited. Does not implicitly {@link google.rpc.LocalizedMessage.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.LocalizedMessage + * @static + * @param {google.rpc.ILocalizedMessage} message LocalizedMessage message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LocalizedMessage.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a LocalizedMessage message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.LocalizedMessage + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.LocalizedMessage} LocalizedMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LocalizedMessage.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.rpc.LocalizedMessage(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.locale = reader.string(); + break; + } + case 2: { + message.message = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a LocalizedMessage message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.LocalizedMessage + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.LocalizedMessage} LocalizedMessage + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LocalizedMessage.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a LocalizedMessage message. + * @function verify + * @memberof google.rpc.LocalizedMessage + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + LocalizedMessage.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.locale != null && message.hasOwnProperty("locale")) + if (!$util.isString(message.locale)) + return "locale: string expected"; + if (message.message != null && message.hasOwnProperty("message")) + if (!$util.isString(message.message)) + return "message: string expected"; + return null; + }; + + /** + * Creates a LocalizedMessage message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.LocalizedMessage + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.LocalizedMessage} LocalizedMessage + */ + LocalizedMessage.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.LocalizedMessage) + return object; + var message = new $root.google.rpc.LocalizedMessage(); + if (object.locale != null) + message.locale = String(object.locale); + if (object.message != null) + message.message = String(object.message); + return message; + }; + + /** + * Creates a plain object from a LocalizedMessage message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.LocalizedMessage + * @static + * @param {google.rpc.LocalizedMessage} message LocalizedMessage + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LocalizedMessage.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.locale = ""; + object.message = ""; + } + if (message.locale != null && message.hasOwnProperty("locale")) + object.locale = message.locale; + if (message.message != null && message.hasOwnProperty("message")) + object.message = message.message; + return object; + }; + + /** + * Converts this LocalizedMessage to JSON. + * @function toJSON + * @memberof google.rpc.LocalizedMessage + * @instance + * @returns {Object.} JSON object + */ + LocalizedMessage.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LocalizedMessage + * @function getTypeUrl + * @memberof google.rpc.LocalizedMessage + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LocalizedMessage.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.LocalizedMessage"; + }; + + return LocalizedMessage; + })(); + + rpc.Status = (function() { + + /** + * Properties of a Status. + * @memberof google.rpc + * @interface IStatus + * @property {number|null} [code] Status code + * @property {string|null} [message] Status message + * @property {Array.|null} [details] Status details + */ + + /** + * Constructs a new Status. + * @memberof google.rpc + * @classdesc Represents a Status. + * @implements IStatus + * @constructor + * @param {google.rpc.IStatus=} [properties] Properties to set + */ + function Status(properties) { + this.details = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Status code. + * @member {number} code + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.code = 0; + + /** + * Status message. + * @member {string} message + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.message = ""; + + /** + * Status details. + * @member {Array.} details + * @memberof google.rpc.Status + * @instance + */ + Status.prototype.details = $util.emptyArray; + + /** + * Creates a new Status instance using the specified properties. + * @function create + * @memberof google.rpc.Status + * @static + * @param {google.rpc.IStatus=} [properties] Properties to set + * @returns {google.rpc.Status} Status instance + */ + Status.create = function create(properties) { + return new Status(properties); + }; + + /** + * Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages. + * @function encode + * @memberof google.rpc.Status + * @static + * @param {google.rpc.IStatus} message Status message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Status.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.code != null && Object.hasOwnProperty.call(message, "code")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.code); + if (message.message != null && Object.hasOwnProperty.call(message, "message")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.message); + if (message.details != null && message.details.length) + for (var i = 0; i < message.details.length; ++i) + $root.google.protobuf.Any.encode(message.details[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages. + * @function encodeDelimited + * @memberof google.rpc.Status + * @static + * @param {google.rpc.IStatus} message Status message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Status.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Status message from the specified reader or buffer. + * @function decode + * @memberof google.rpc.Status + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.rpc.Status} Status + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Status.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.rpc.Status(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.code = reader.int32(); + break; + } + case 2: { + message.message = reader.string(); + break; + } + case 3: { + if (!(message.details && message.details.length)) + message.details = []; + message.details.push($root.google.protobuf.Any.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Status message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.rpc.Status + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.rpc.Status} Status + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Status.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Status message. + * @function verify + * @memberof google.rpc.Status + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Status.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.code != null && message.hasOwnProperty("code")) + if (!$util.isInteger(message.code)) + return "code: integer expected"; + if (message.message != null && message.hasOwnProperty("message")) + if (!$util.isString(message.message)) + return "message: string expected"; + if (message.details != null && message.hasOwnProperty("details")) { + if (!Array.isArray(message.details)) + return "details: array expected"; + for (var i = 0; i < message.details.length; ++i) { + var error = $root.google.protobuf.Any.verify(message.details[i]); + if (error) + return "details." + error; + } + } + return null; + }; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.rpc.Status + * @static + * @param {Object.} object Plain object + * @returns {google.rpc.Status} Status + */ + Status.fromObject = function fromObject(object) { + if (object instanceof $root.google.rpc.Status) + return object; + var message = new $root.google.rpc.Status(); + if (object.code != null) + message.code = object.code | 0; + if (object.message != null) + message.message = String(object.message); + if (object.details) { + if (!Array.isArray(object.details)) + throw TypeError(".google.rpc.Status.details: array expected"); + message.details = []; + for (var i = 0; i < object.details.length; ++i) { + if (typeof object.details[i] !== "object") + throw TypeError(".google.rpc.Status.details: object expected"); + message.details[i] = $root.google.protobuf.Any.fromObject(object.details[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @function toObject + * @memberof google.rpc.Status + * @static + * @param {google.rpc.Status} message Status + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Status.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.details = []; + if (options.defaults) { + object.code = 0; + object.message = ""; + } + if (message.code != null && message.hasOwnProperty("code")) + object.code = message.code; + if (message.message != null && message.hasOwnProperty("message")) + object.message = message.message; + if (message.details && message.details.length) { + object.details = []; + for (var j = 0; j < message.details.length; ++j) + object.details[j] = $root.google.protobuf.Any.toObject(message.details[j], options); + } + return object; + }; + + /** + * Converts this Status to JSON. + * @function toJSON + * @memberof google.rpc.Status + * @instance + * @returns {Object.} JSON object + */ + Status.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Status + * @function getTypeUrl + * @memberof google.rpc.Status + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Status.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.rpc.Status"; + }; + + return Status; + })(); + + return rpc; + })(); + + google.spanner = (function() { + + /** + * Namespace spanner. + * @memberof google + * @namespace + */ + var spanner = {}; + + spanner.admin = (function() { + + /** + * Namespace admin. + * @memberof google.spanner + * @namespace + */ + var admin = {}; + + admin.database = (function() { + + /** + * Namespace database. + * @memberof google.spanner.admin + * @namespace + */ + var database = {}; + + database.v1 = (function() { + + /** + * Namespace v1. + * @memberof google.spanner.admin.database + * @namespace + */ + var v1 = {}; + + v1.Backup = (function() { + + /** + * Properties of a Backup. + * @memberof google.spanner.admin.database.v1 + * @interface IBackup + * @property {string|null} [database] Backup database + * @property {google.protobuf.ITimestamp|null} [versionTime] Backup versionTime + * @property {google.protobuf.ITimestamp|null} [expireTime] Backup expireTime + * @property {string|null} [name] Backup name + * @property {google.protobuf.ITimestamp|null} [createTime] Backup createTime + * @property {number|Long|null} [sizeBytes] Backup sizeBytes + * @property {number|Long|null} [freeableSizeBytes] Backup freeableSizeBytes + * @property {number|Long|null} [exclusiveSizeBytes] Backup exclusiveSizeBytes + * @property {google.spanner.admin.database.v1.Backup.State|null} [state] Backup state + * @property {Array.|null} [referencingDatabases] Backup referencingDatabases + * @property {google.spanner.admin.database.v1.IEncryptionInfo|null} [encryptionInfo] Backup encryptionInfo + * @property {Array.|null} [encryptionInformation] Backup encryptionInformation + * @property {google.spanner.admin.database.v1.DatabaseDialect|null} [databaseDialect] Backup databaseDialect + * @property {Array.|null} [referencingBackups] Backup referencingBackups + * @property {google.protobuf.ITimestamp|null} [maxExpireTime] Backup maxExpireTime + * @property {Array.|null} [backupSchedules] Backup backupSchedules + * @property {string|null} [incrementalBackupChainId] Backup incrementalBackupChainId + * @property {google.protobuf.ITimestamp|null} [oldestVersionTime] Backup oldestVersionTime + * @property {Array.|null} [instancePartitions] Backup instancePartitions + */ + + /** + * Constructs a new Backup. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a Backup. + * @implements IBackup + * @constructor + * @param {google.spanner.admin.database.v1.IBackup=} [properties] Properties to set + */ + function Backup(properties) { + this.referencingDatabases = []; + this.encryptionInformation = []; + this.referencingBackups = []; + this.backupSchedules = []; + this.instancePartitions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Backup database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.database = ""; + + /** + * Backup versionTime. + * @member {google.protobuf.ITimestamp|null|undefined} versionTime + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.versionTime = null; + + /** + * Backup expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.expireTime = null; + + /** + * Backup name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.name = ""; + + /** + * Backup createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.createTime = null; + + /** + * Backup sizeBytes. + * @member {number|Long} sizeBytes + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.sizeBytes = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Backup freeableSizeBytes. + * @member {number|Long} freeableSizeBytes + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.freeableSizeBytes = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Backup exclusiveSizeBytes. + * @member {number|Long} exclusiveSizeBytes + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.exclusiveSizeBytes = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Backup state. + * @member {google.spanner.admin.database.v1.Backup.State} state + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.state = 0; + + /** + * Backup referencingDatabases. + * @member {Array.} referencingDatabases + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.referencingDatabases = $util.emptyArray; + + /** + * Backup encryptionInfo. + * @member {google.spanner.admin.database.v1.IEncryptionInfo|null|undefined} encryptionInfo + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.encryptionInfo = null; + + /** + * Backup encryptionInformation. + * @member {Array.} encryptionInformation + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.encryptionInformation = $util.emptyArray; + + /** + * Backup databaseDialect. + * @member {google.spanner.admin.database.v1.DatabaseDialect} databaseDialect + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.databaseDialect = 0; + + /** + * Backup referencingBackups. + * @member {Array.} referencingBackups + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.referencingBackups = $util.emptyArray; + + /** + * Backup maxExpireTime. + * @member {google.protobuf.ITimestamp|null|undefined} maxExpireTime + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.maxExpireTime = null; + + /** + * Backup backupSchedules. + * @member {Array.} backupSchedules + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.backupSchedules = $util.emptyArray; + + /** + * Backup incrementalBackupChainId. + * @member {string} incrementalBackupChainId + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.incrementalBackupChainId = ""; + + /** + * Backup oldestVersionTime. + * @member {google.protobuf.ITimestamp|null|undefined} oldestVersionTime + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.oldestVersionTime = null; + + /** + * Backup instancePartitions. + * @member {Array.} instancePartitions + * @memberof google.spanner.admin.database.v1.Backup + * @instance + */ + Backup.prototype.instancePartitions = $util.emptyArray; + + /** + * Creates a new Backup instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {google.spanner.admin.database.v1.IBackup=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.Backup} Backup instance + */ + Backup.create = function create(properties) { + return new Backup(properties); + }; + + /** + * Encodes the specified Backup message. Does not implicitly {@link google.spanner.admin.database.v1.Backup.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {google.spanner.admin.database.v1.IBackup} message Backup message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Backup.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.database); + if (message.expireTime != null && Object.hasOwnProperty.call(message, "expireTime")) + $root.google.protobuf.Timestamp.encode(message.expireTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.createTime != null && Object.hasOwnProperty.call(message, "createTime")) + $root.google.protobuf.Timestamp.encode(message.createTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.sizeBytes != null && Object.hasOwnProperty.call(message, "sizeBytes")) + writer.uint32(/* id 5, wireType 0 =*/40).int64(message.sizeBytes); + if (message.state != null && Object.hasOwnProperty.call(message, "state")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.state); + if (message.referencingDatabases != null && message.referencingDatabases.length) + for (var i = 0; i < message.referencingDatabases.length; ++i) + writer.uint32(/* id 7, wireType 2 =*/58).string(message.referencingDatabases[i]); + if (message.encryptionInfo != null && Object.hasOwnProperty.call(message, "encryptionInfo")) + $root.google.spanner.admin.database.v1.EncryptionInfo.encode(message.encryptionInfo, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.versionTime != null && Object.hasOwnProperty.call(message, "versionTime")) + $root.google.protobuf.Timestamp.encode(message.versionTime, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + if (message.databaseDialect != null && Object.hasOwnProperty.call(message, "databaseDialect")) + writer.uint32(/* id 10, wireType 0 =*/80).int32(message.databaseDialect); + if (message.referencingBackups != null && message.referencingBackups.length) + for (var i = 0; i < message.referencingBackups.length; ++i) + writer.uint32(/* id 11, wireType 2 =*/90).string(message.referencingBackups[i]); + if (message.maxExpireTime != null && Object.hasOwnProperty.call(message, "maxExpireTime")) + $root.google.protobuf.Timestamp.encode(message.maxExpireTime, writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim(); + if (message.encryptionInformation != null && message.encryptionInformation.length) + for (var i = 0; i < message.encryptionInformation.length; ++i) + $root.google.spanner.admin.database.v1.EncryptionInfo.encode(message.encryptionInformation[i], writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim(); + if (message.backupSchedules != null && message.backupSchedules.length) + for (var i = 0; i < message.backupSchedules.length; ++i) + writer.uint32(/* id 14, wireType 2 =*/114).string(message.backupSchedules[i]); + if (message.freeableSizeBytes != null && Object.hasOwnProperty.call(message, "freeableSizeBytes")) + writer.uint32(/* id 15, wireType 0 =*/120).int64(message.freeableSizeBytes); + if (message.exclusiveSizeBytes != null && Object.hasOwnProperty.call(message, "exclusiveSizeBytes")) + writer.uint32(/* id 16, wireType 0 =*/128).int64(message.exclusiveSizeBytes); + if (message.incrementalBackupChainId != null && Object.hasOwnProperty.call(message, "incrementalBackupChainId")) + writer.uint32(/* id 17, wireType 2 =*/138).string(message.incrementalBackupChainId); + if (message.oldestVersionTime != null && Object.hasOwnProperty.call(message, "oldestVersionTime")) + $root.google.protobuf.Timestamp.encode(message.oldestVersionTime, writer.uint32(/* id 18, wireType 2 =*/146).fork()).ldelim(); + if (message.instancePartitions != null && message.instancePartitions.length) + for (var i = 0; i < message.instancePartitions.length; ++i) + $root.google.spanner.admin.database.v1.BackupInstancePartition.encode(message.instancePartitions[i], writer.uint32(/* id 19, wireType 2 =*/154).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Backup message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.Backup.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {google.spanner.admin.database.v1.IBackup} message Backup message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Backup.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Backup message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.Backup} Backup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Backup.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.spanner.admin.database.v1.Backup(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 2: { + message.database = reader.string(); + break; + } + case 9: { + message.versionTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.expireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 1: { + message.name = reader.string(); + break; + } + case 4: { + message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 5: { + message.sizeBytes = reader.int64(); + break; + } + case 15: { + message.freeableSizeBytes = reader.int64(); + break; + } + case 16: { + message.exclusiveSizeBytes = reader.int64(); + break; + } + case 6: { + message.state = reader.int32(); + break; + } + case 7: { + if (!(message.referencingDatabases && message.referencingDatabases.length)) + message.referencingDatabases = []; + message.referencingDatabases.push(reader.string()); + break; + } + case 8: { + message.encryptionInfo = $root.google.spanner.admin.database.v1.EncryptionInfo.decode(reader, reader.uint32()); + break; + } + case 13: { + if (!(message.encryptionInformation && message.encryptionInformation.length)) + message.encryptionInformation = []; + message.encryptionInformation.push($root.google.spanner.admin.database.v1.EncryptionInfo.decode(reader, reader.uint32())); + break; + } + case 10: { + message.databaseDialect = reader.int32(); + break; + } + case 11: { + if (!(message.referencingBackups && message.referencingBackups.length)) + message.referencingBackups = []; + message.referencingBackups.push(reader.string()); + break; + } + case 12: { + message.maxExpireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 14: { + if (!(message.backupSchedules && message.backupSchedules.length)) + message.backupSchedules = []; + message.backupSchedules.push(reader.string()); + break; + } + case 17: { + message.incrementalBackupChainId = reader.string(); + break; + } + case 18: { + message.oldestVersionTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 19: { + if (!(message.instancePartitions && message.instancePartitions.length)) + message.instancePartitions = []; + message.instancePartitions.push($root.google.spanner.admin.database.v1.BackupInstancePartition.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Backup message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.Backup} Backup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Backup.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Backup message. + * @function verify + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Backup.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.versionTime != null && message.hasOwnProperty("versionTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.versionTime); + if (error) + return "versionTime." + error; + } + if (message.expireTime != null && message.hasOwnProperty("expireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.expireTime); + if (error) + return "expireTime." + error; + } + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.createTime != null && message.hasOwnProperty("createTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.createTime); + if (error) + return "createTime." + error; + } + if (message.sizeBytes != null && message.hasOwnProperty("sizeBytes")) + if (!$util.isInteger(message.sizeBytes) && !(message.sizeBytes && $util.isInteger(message.sizeBytes.low) && $util.isInteger(message.sizeBytes.high))) + return "sizeBytes: integer|Long expected"; + if (message.freeableSizeBytes != null && message.hasOwnProperty("freeableSizeBytes")) + if (!$util.isInteger(message.freeableSizeBytes) && !(message.freeableSizeBytes && $util.isInteger(message.freeableSizeBytes.low) && $util.isInteger(message.freeableSizeBytes.high))) + return "freeableSizeBytes: integer|Long expected"; + if (message.exclusiveSizeBytes != null && message.hasOwnProperty("exclusiveSizeBytes")) + if (!$util.isInteger(message.exclusiveSizeBytes) && !(message.exclusiveSizeBytes && $util.isInteger(message.exclusiveSizeBytes.low) && $util.isInteger(message.exclusiveSizeBytes.high))) + return "exclusiveSizeBytes: integer|Long expected"; + if (message.state != null && message.hasOwnProperty("state")) + switch (message.state) { + default: + return "state: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.referencingDatabases != null && message.hasOwnProperty("referencingDatabases")) { + if (!Array.isArray(message.referencingDatabases)) + return "referencingDatabases: array expected"; + for (var i = 0; i < message.referencingDatabases.length; ++i) + if (!$util.isString(message.referencingDatabases[i])) + return "referencingDatabases: string[] expected"; + } + if (message.encryptionInfo != null && message.hasOwnProperty("encryptionInfo")) { + var error = $root.google.spanner.admin.database.v1.EncryptionInfo.verify(message.encryptionInfo); + if (error) + return "encryptionInfo." + error; + } + if (message.encryptionInformation != null && message.hasOwnProperty("encryptionInformation")) { + if (!Array.isArray(message.encryptionInformation)) + return "encryptionInformation: array expected"; + for (var i = 0; i < message.encryptionInformation.length; ++i) { + var error = $root.google.spanner.admin.database.v1.EncryptionInfo.verify(message.encryptionInformation[i]); + if (error) + return "encryptionInformation." + error; + } + } + if (message.databaseDialect != null && message.hasOwnProperty("databaseDialect")) + switch (message.databaseDialect) { + default: + return "databaseDialect: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.referencingBackups != null && message.hasOwnProperty("referencingBackups")) { + if (!Array.isArray(message.referencingBackups)) + return "referencingBackups: array expected"; + for (var i = 0; i < message.referencingBackups.length; ++i) + if (!$util.isString(message.referencingBackups[i])) + return "referencingBackups: string[] expected"; + } + if (message.maxExpireTime != null && message.hasOwnProperty("maxExpireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.maxExpireTime); + if (error) + return "maxExpireTime." + error; + } + if (message.backupSchedules != null && message.hasOwnProperty("backupSchedules")) { + if (!Array.isArray(message.backupSchedules)) + return "backupSchedules: array expected"; + for (var i = 0; i < message.backupSchedules.length; ++i) + if (!$util.isString(message.backupSchedules[i])) + return "backupSchedules: string[] expected"; + } + if (message.incrementalBackupChainId != null && message.hasOwnProperty("incrementalBackupChainId")) + if (!$util.isString(message.incrementalBackupChainId)) + return "incrementalBackupChainId: string expected"; + if (message.oldestVersionTime != null && message.hasOwnProperty("oldestVersionTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.oldestVersionTime); + if (error) + return "oldestVersionTime." + error; + } + if (message.instancePartitions != null && message.hasOwnProperty("instancePartitions")) { + if (!Array.isArray(message.instancePartitions)) + return "instancePartitions: array expected"; + for (var i = 0; i < message.instancePartitions.length; ++i) { + var error = $root.google.spanner.admin.database.v1.BackupInstancePartition.verify(message.instancePartitions[i]); + if (error) + return "instancePartitions." + error; + } + } + return null; + }; + + /** + * Creates a Backup message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.Backup} Backup + */ + Backup.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.Backup) + return object; + var message = new $root.google.spanner.admin.database.v1.Backup(); + if (object.database != null) + message.database = String(object.database); + if (object.versionTime != null) { + if (typeof object.versionTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.Backup.versionTime: object expected"); + message.versionTime = $root.google.protobuf.Timestamp.fromObject(object.versionTime); + } + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.Backup.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime); + } + if (object.name != null) + message.name = String(object.name); + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.Backup.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.sizeBytes != null) + if ($util.Long) + (message.sizeBytes = $util.Long.fromValue(object.sizeBytes)).unsigned = false; + else if (typeof object.sizeBytes === "string") + message.sizeBytes = parseInt(object.sizeBytes, 10); + else if (typeof object.sizeBytes === "number") + message.sizeBytes = object.sizeBytes; + else if (typeof object.sizeBytes === "object") + message.sizeBytes = new $util.LongBits(object.sizeBytes.low >>> 0, object.sizeBytes.high >>> 0).toNumber(); + if (object.freeableSizeBytes != null) + if ($util.Long) + (message.freeableSizeBytes = $util.Long.fromValue(object.freeableSizeBytes)).unsigned = false; + else if (typeof object.freeableSizeBytes === "string") + message.freeableSizeBytes = parseInt(object.freeableSizeBytes, 10); + else if (typeof object.freeableSizeBytes === "number") + message.freeableSizeBytes = object.freeableSizeBytes; + else if (typeof object.freeableSizeBytes === "object") + message.freeableSizeBytes = new $util.LongBits(object.freeableSizeBytes.low >>> 0, object.freeableSizeBytes.high >>> 0).toNumber(); + if (object.exclusiveSizeBytes != null) + if ($util.Long) + (message.exclusiveSizeBytes = $util.Long.fromValue(object.exclusiveSizeBytes)).unsigned = false; + else if (typeof object.exclusiveSizeBytes === "string") + message.exclusiveSizeBytes = parseInt(object.exclusiveSizeBytes, 10); + else if (typeof object.exclusiveSizeBytes === "number") + message.exclusiveSizeBytes = object.exclusiveSizeBytes; + else if (typeof object.exclusiveSizeBytes === "object") + message.exclusiveSizeBytes = new $util.LongBits(object.exclusiveSizeBytes.low >>> 0, object.exclusiveSizeBytes.high >>> 0).toNumber(); + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "CREATING": + case 1: + message.state = 1; + break; + case "READY": + case 2: + message.state = 2; + break; + } + if (object.referencingDatabases) { + if (!Array.isArray(object.referencingDatabases)) + throw TypeError(".google.spanner.admin.database.v1.Backup.referencingDatabases: array expected"); + message.referencingDatabases = []; + for (var i = 0; i < object.referencingDatabases.length; ++i) + message.referencingDatabases[i] = String(object.referencingDatabases[i]); + } + if (object.encryptionInfo != null) { + if (typeof object.encryptionInfo !== "object") + throw TypeError(".google.spanner.admin.database.v1.Backup.encryptionInfo: object expected"); + message.encryptionInfo = $root.google.spanner.admin.database.v1.EncryptionInfo.fromObject(object.encryptionInfo); + } + if (object.encryptionInformation) { + if (!Array.isArray(object.encryptionInformation)) + throw TypeError(".google.spanner.admin.database.v1.Backup.encryptionInformation: array expected"); + message.encryptionInformation = []; + for (var i = 0; i < object.encryptionInformation.length; ++i) { + if (typeof object.encryptionInformation[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.Backup.encryptionInformation: object expected"); + message.encryptionInformation[i] = $root.google.spanner.admin.database.v1.EncryptionInfo.fromObject(object.encryptionInformation[i]); + } + } + switch (object.databaseDialect) { + default: + if (typeof object.databaseDialect === "number") { + message.databaseDialect = object.databaseDialect; + break; + } + break; + case "DATABASE_DIALECT_UNSPECIFIED": + case 0: + message.databaseDialect = 0; + break; + case "GOOGLE_STANDARD_SQL": + case 1: + message.databaseDialect = 1; + break; + case "POSTGRESQL": + case 2: + message.databaseDialect = 2; + break; + } + if (object.referencingBackups) { + if (!Array.isArray(object.referencingBackups)) + throw TypeError(".google.spanner.admin.database.v1.Backup.referencingBackups: array expected"); + message.referencingBackups = []; + for (var i = 0; i < object.referencingBackups.length; ++i) + message.referencingBackups[i] = String(object.referencingBackups[i]); + } + if (object.maxExpireTime != null) { + if (typeof object.maxExpireTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.Backup.maxExpireTime: object expected"); + message.maxExpireTime = $root.google.protobuf.Timestamp.fromObject(object.maxExpireTime); + } + if (object.backupSchedules) { + if (!Array.isArray(object.backupSchedules)) + throw TypeError(".google.spanner.admin.database.v1.Backup.backupSchedules: array expected"); + message.backupSchedules = []; + for (var i = 0; i < object.backupSchedules.length; ++i) + message.backupSchedules[i] = String(object.backupSchedules[i]); + } + if (object.incrementalBackupChainId != null) + message.incrementalBackupChainId = String(object.incrementalBackupChainId); + if (object.oldestVersionTime != null) { + if (typeof object.oldestVersionTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.Backup.oldestVersionTime: object expected"); + message.oldestVersionTime = $root.google.protobuf.Timestamp.fromObject(object.oldestVersionTime); + } + if (object.instancePartitions) { + if (!Array.isArray(object.instancePartitions)) + throw TypeError(".google.spanner.admin.database.v1.Backup.instancePartitions: array expected"); + message.instancePartitions = []; + for (var i = 0; i < object.instancePartitions.length; ++i) { + if (typeof object.instancePartitions[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.Backup.instancePartitions: object expected"); + message.instancePartitions[i] = $root.google.spanner.admin.database.v1.BackupInstancePartition.fromObject(object.instancePartitions[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Backup message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {google.spanner.admin.database.v1.Backup} message Backup + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Backup.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.referencingDatabases = []; + object.referencingBackups = []; + object.encryptionInformation = []; + object.backupSchedules = []; + object.instancePartitions = []; + } + if (options.defaults) { + object.name = ""; + object.database = ""; + object.expireTime = null; + object.createTime = null; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.sizeBytes = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.sizeBytes = options.longs === String ? "0" : 0; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + object.encryptionInfo = null; + object.versionTime = null; + object.databaseDialect = options.enums === String ? "DATABASE_DIALECT_UNSPECIFIED" : 0; + object.maxExpireTime = null; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.freeableSizeBytes = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.freeableSizeBytes = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.exclusiveSizeBytes = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.exclusiveSizeBytes = options.longs === String ? "0" : 0; + object.incrementalBackupChainId = ""; + object.oldestVersionTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.sizeBytes != null && message.hasOwnProperty("sizeBytes")) + if (typeof message.sizeBytes === "number") + object.sizeBytes = options.longs === String ? String(message.sizeBytes) : message.sizeBytes; + else + object.sizeBytes = options.longs === String ? $util.Long.prototype.toString.call(message.sizeBytes) : options.longs === Number ? new $util.LongBits(message.sizeBytes.low >>> 0, message.sizeBytes.high >>> 0).toNumber() : message.sizeBytes; + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.spanner.admin.database.v1.Backup.State[message.state] === undefined ? message.state : $root.google.spanner.admin.database.v1.Backup.State[message.state] : message.state; + if (message.referencingDatabases && message.referencingDatabases.length) { + object.referencingDatabases = []; + for (var j = 0; j < message.referencingDatabases.length; ++j) + object.referencingDatabases[j] = message.referencingDatabases[j]; + } + if (message.encryptionInfo != null && message.hasOwnProperty("encryptionInfo")) + object.encryptionInfo = $root.google.spanner.admin.database.v1.EncryptionInfo.toObject(message.encryptionInfo, options); + if (message.versionTime != null && message.hasOwnProperty("versionTime")) + object.versionTime = $root.google.protobuf.Timestamp.toObject(message.versionTime, options); + if (message.databaseDialect != null && message.hasOwnProperty("databaseDialect")) + object.databaseDialect = options.enums === String ? $root.google.spanner.admin.database.v1.DatabaseDialect[message.databaseDialect] === undefined ? message.databaseDialect : $root.google.spanner.admin.database.v1.DatabaseDialect[message.databaseDialect] : message.databaseDialect; + if (message.referencingBackups && message.referencingBackups.length) { + object.referencingBackups = []; + for (var j = 0; j < message.referencingBackups.length; ++j) + object.referencingBackups[j] = message.referencingBackups[j]; + } + if (message.maxExpireTime != null && message.hasOwnProperty("maxExpireTime")) + object.maxExpireTime = $root.google.protobuf.Timestamp.toObject(message.maxExpireTime, options); + if (message.encryptionInformation && message.encryptionInformation.length) { + object.encryptionInformation = []; + for (var j = 0; j < message.encryptionInformation.length; ++j) + object.encryptionInformation[j] = $root.google.spanner.admin.database.v1.EncryptionInfo.toObject(message.encryptionInformation[j], options); + } + if (message.backupSchedules && message.backupSchedules.length) { + object.backupSchedules = []; + for (var j = 0; j < message.backupSchedules.length; ++j) + object.backupSchedules[j] = message.backupSchedules[j]; + } + if (message.freeableSizeBytes != null && message.hasOwnProperty("freeableSizeBytes")) + if (typeof message.freeableSizeBytes === "number") + object.freeableSizeBytes = options.longs === String ? String(message.freeableSizeBytes) : message.freeableSizeBytes; + else + object.freeableSizeBytes = options.longs === String ? $util.Long.prototype.toString.call(message.freeableSizeBytes) : options.longs === Number ? new $util.LongBits(message.freeableSizeBytes.low >>> 0, message.freeableSizeBytes.high >>> 0).toNumber() : message.freeableSizeBytes; + if (message.exclusiveSizeBytes != null && message.hasOwnProperty("exclusiveSizeBytes")) + if (typeof message.exclusiveSizeBytes === "number") + object.exclusiveSizeBytes = options.longs === String ? String(message.exclusiveSizeBytes) : message.exclusiveSizeBytes; + else + object.exclusiveSizeBytes = options.longs === String ? $util.Long.prototype.toString.call(message.exclusiveSizeBytes) : options.longs === Number ? new $util.LongBits(message.exclusiveSizeBytes.low >>> 0, message.exclusiveSizeBytes.high >>> 0).toNumber() : message.exclusiveSizeBytes; + if (message.incrementalBackupChainId != null && message.hasOwnProperty("incrementalBackupChainId")) + object.incrementalBackupChainId = message.incrementalBackupChainId; + if (message.oldestVersionTime != null && message.hasOwnProperty("oldestVersionTime")) + object.oldestVersionTime = $root.google.protobuf.Timestamp.toObject(message.oldestVersionTime, options); + if (message.instancePartitions && message.instancePartitions.length) { + object.instancePartitions = []; + for (var j = 0; j < message.instancePartitions.length; ++j) + object.instancePartitions[j] = $root.google.spanner.admin.database.v1.BackupInstancePartition.toObject(message.instancePartitions[j], options); + } + return object; + }; + + /** + * Converts this Backup to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.Backup + * @instance + * @returns {Object.} JSON object + */ + Backup.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Backup + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.Backup + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Backup.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.Backup"; + }; + + /** + * State enum. + * @name google.spanner.admin.database.v1.Backup.State + * @enum {number} + * @property {number} STATE_UNSPECIFIED=0 STATE_UNSPECIFIED value + * @property {number} CREATING=1 CREATING value + * @property {number} READY=2 READY value + */ + Backup.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = 0; + values[valuesById[1] = "CREATING"] = 1; + values[valuesById[2] = "READY"] = 2; + return values; + })(); + + return Backup; + })(); + + v1.CreateBackupRequest = (function() { + + /** + * Properties of a CreateBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @interface ICreateBackupRequest + * @property {string|null} [parent] CreateBackupRequest parent + * @property {string|null} [backupId] CreateBackupRequest backupId + * @property {google.spanner.admin.database.v1.IBackup|null} [backup] CreateBackupRequest backup + * @property {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig|null} [encryptionConfig] CreateBackupRequest encryptionConfig + */ + + /** + * Constructs a new CreateBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CreateBackupRequest. + * @implements ICreateBackupRequest + * @constructor + * @param {google.spanner.admin.database.v1.ICreateBackupRequest=} [properties] Properties to set + */ + function CreateBackupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateBackupRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @instance + */ + CreateBackupRequest.prototype.parent = ""; + + /** + * CreateBackupRequest backupId. + * @member {string} backupId + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @instance + */ + CreateBackupRequest.prototype.backupId = ""; + + /** + * CreateBackupRequest backup. + * @member {google.spanner.admin.database.v1.IBackup|null|undefined} backup + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @instance + */ + CreateBackupRequest.prototype.backup = null; + + /** + * CreateBackupRequest encryptionConfig. + * @member {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @instance + */ + CreateBackupRequest.prototype.encryptionConfig = null; + + /** + * Creates a new CreateBackupRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CreateBackupRequest} CreateBackupRequest instance + */ + CreateBackupRequest.create = function create(properties) { + return new CreateBackupRequest(properties); + }; + + /** + * Encodes the specified CreateBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupRequest} message CreateBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateBackupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.backupId != null && Object.hasOwnProperty.call(message, "backupId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.backupId); + if (message.backup != null && Object.hasOwnProperty.call(message, "backup")) + $root.google.spanner.admin.database.v1.Backup.encode(message.backup, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupRequest} message CreateBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateBackupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateBackupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CreateBackupRequest} CreateBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateBackupRequest.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.spanner.admin.database.v1.CreateBackupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.backupId = reader.string(); + break; + } + case 3: { + message.backup = $root.google.spanner.admin.database.v1.Backup.decode(reader, reader.uint32()); + break; + } + case 4: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateBackupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CreateBackupRequest} CreateBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateBackupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateBackupRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateBackupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.backupId != null && message.hasOwnProperty("backupId")) + if (!$util.isString(message.backupId)) + return "backupId: string expected"; + if (message.backup != null && message.hasOwnProperty("backup")) { + var error = $root.google.spanner.admin.database.v1.Backup.verify(message.backup); + if (error) + return "backup." + error; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + return null; + }; + + /** + * Creates a CreateBackupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CreateBackupRequest} CreateBackupRequest + */ + CreateBackupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CreateBackupRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.CreateBackupRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.backupId != null) + message.backupId = String(object.backupId); + if (object.backup != null) { + if (typeof object.backup !== "object") + throw TypeError(".google.spanner.admin.database.v1.CreateBackupRequest.backup: object expected"); + message.backup = $root.google.spanner.admin.database.v1.Backup.fromObject(object.backup); + } + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.admin.database.v1.CreateBackupRequest.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.fromObject(object.encryptionConfig); + } + return message; + }; + + /** + * Creates a plain object from a CreateBackupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {google.spanner.admin.database.v1.CreateBackupRequest} message CreateBackupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateBackupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.backupId = ""; + object.backup = null; + object.encryptionConfig = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.backupId != null && message.hasOwnProperty("backupId")) + object.backupId = message.backupId; + if (message.backup != null && message.hasOwnProperty("backup")) + object.backup = $root.google.spanner.admin.database.v1.Backup.toObject(message.backup, options); + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.toObject(message.encryptionConfig, options); + return object; + }; + + /** + * Converts this CreateBackupRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @instance + * @returns {Object.} JSON object + */ + CreateBackupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateBackupRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CreateBackupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateBackupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CreateBackupRequest"; + }; + + return CreateBackupRequest; + })(); + + v1.CreateBackupMetadata = (function() { + + /** + * Properties of a CreateBackupMetadata. + * @memberof google.spanner.admin.database.v1 + * @interface ICreateBackupMetadata + * @property {string|null} [name] CreateBackupMetadata name + * @property {string|null} [database] CreateBackupMetadata database + * @property {google.spanner.admin.database.v1.IOperationProgress|null} [progress] CreateBackupMetadata progress + * @property {google.protobuf.ITimestamp|null} [cancelTime] CreateBackupMetadata cancelTime + */ + + /** + * Constructs a new CreateBackupMetadata. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CreateBackupMetadata. + * @implements ICreateBackupMetadata + * @constructor + * @param {google.spanner.admin.database.v1.ICreateBackupMetadata=} [properties] Properties to set + */ + function CreateBackupMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateBackupMetadata name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @instance + */ + CreateBackupMetadata.prototype.name = ""; + + /** + * CreateBackupMetadata database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @instance + */ + CreateBackupMetadata.prototype.database = ""; + + /** + * CreateBackupMetadata progress. + * @member {google.spanner.admin.database.v1.IOperationProgress|null|undefined} progress + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @instance + */ + CreateBackupMetadata.prototype.progress = null; + + /** + * CreateBackupMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @instance + */ + CreateBackupMetadata.prototype.cancelTime = null; + + /** + * Creates a new CreateBackupMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CreateBackupMetadata} CreateBackupMetadata instance + */ + CreateBackupMetadata.create = function create(properties) { + return new CreateBackupMetadata(properties); + }; + + /** + * Encodes the specified CreateBackupMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupMetadata} message CreateBackupMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateBackupMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.database); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.spanner.admin.database.v1.OperationProgress.encode(message.progress, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateBackupMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupMetadata} message CreateBackupMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateBackupMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateBackupMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CreateBackupMetadata} CreateBackupMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateBackupMetadata.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.spanner.admin.database.v1.CreateBackupMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.database = reader.string(); + break; + } + case 3: { + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.decode(reader, reader.uint32()); + break; + } + case 4: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateBackupMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CreateBackupMetadata} CreateBackupMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateBackupMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateBackupMetadata message. + * @function verify + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateBackupMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.spanner.admin.database.v1.OperationProgress.verify(message.progress); + if (error) + return "progress." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + return null; + }; + + /** + * Creates a CreateBackupMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CreateBackupMetadata} CreateBackupMetadata + */ + CreateBackupMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CreateBackupMetadata) + return object; + var message = new $root.google.spanner.admin.database.v1.CreateBackupMetadata(); + if (object.name != null) + message.name = String(object.name); + if (object.database != null) + message.database = String(object.database); + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.spanner.admin.database.v1.CreateBackupMetadata.progress: object expected"); + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.fromObject(object.progress); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.CreateBackupMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + return message; + }; + + /** + * Creates a plain object from a CreateBackupMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {google.spanner.admin.database.v1.CreateBackupMetadata} message CreateBackupMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateBackupMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.database = ""; + object.progress = null; + object.cancelTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.spanner.admin.database.v1.OperationProgress.toObject(message.progress, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + return object; + }; + + /** + * Converts this CreateBackupMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @instance + * @returns {Object.} JSON object + */ + CreateBackupMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateBackupMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CreateBackupMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateBackupMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CreateBackupMetadata"; + }; + + return CreateBackupMetadata; + })(); + + v1.CopyBackupRequest = (function() { + + /** + * Properties of a CopyBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @interface ICopyBackupRequest + * @property {string|null} [parent] CopyBackupRequest parent + * @property {string|null} [backupId] CopyBackupRequest backupId + * @property {string|null} [sourceBackup] CopyBackupRequest sourceBackup + * @property {google.protobuf.ITimestamp|null} [expireTime] CopyBackupRequest expireTime + * @property {google.spanner.admin.database.v1.ICopyBackupEncryptionConfig|null} [encryptionConfig] CopyBackupRequest encryptionConfig + */ + + /** + * Constructs a new CopyBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CopyBackupRequest. + * @implements ICopyBackupRequest + * @constructor + * @param {google.spanner.admin.database.v1.ICopyBackupRequest=} [properties] Properties to set + */ + function CopyBackupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CopyBackupRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @instance + */ + CopyBackupRequest.prototype.parent = ""; + + /** + * CopyBackupRequest backupId. + * @member {string} backupId + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @instance + */ + CopyBackupRequest.prototype.backupId = ""; + + /** + * CopyBackupRequest sourceBackup. + * @member {string} sourceBackup + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @instance + */ + CopyBackupRequest.prototype.sourceBackup = ""; + + /** + * CopyBackupRequest expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @instance + */ + CopyBackupRequest.prototype.expireTime = null; + + /** + * CopyBackupRequest encryptionConfig. + * @member {google.spanner.admin.database.v1.ICopyBackupEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @instance + */ + CopyBackupRequest.prototype.encryptionConfig = null; + + /** + * Creates a new CopyBackupRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CopyBackupRequest} CopyBackupRequest instance + */ + CopyBackupRequest.create = function create(properties) { + return new CopyBackupRequest(properties); + }; + + /** + * Encodes the specified CopyBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupRequest} message CopyBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CopyBackupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.backupId != null && Object.hasOwnProperty.call(message, "backupId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.backupId); + if (message.sourceBackup != null && Object.hasOwnProperty.call(message, "sourceBackup")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.sourceBackup); + if (message.expireTime != null && Object.hasOwnProperty.call(message, "expireTime")) + $root.google.protobuf.Timestamp.encode(message.expireTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CopyBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupRequest} message CopyBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CopyBackupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CopyBackupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CopyBackupRequest} CopyBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CopyBackupRequest.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.spanner.admin.database.v1.CopyBackupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.backupId = reader.string(); + break; + } + case 3: { + message.sourceBackup = reader.string(); + break; + } + case 4: { + message.expireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 5: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CopyBackupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CopyBackupRequest} CopyBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CopyBackupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CopyBackupRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CopyBackupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.backupId != null && message.hasOwnProperty("backupId")) + if (!$util.isString(message.backupId)) + return "backupId: string expected"; + if (message.sourceBackup != null && message.hasOwnProperty("sourceBackup")) + if (!$util.isString(message.sourceBackup)) + return "sourceBackup: string expected"; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.expireTime); + if (error) + return "expireTime." + error; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + return null; + }; + + /** + * Creates a CopyBackupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CopyBackupRequest} CopyBackupRequest + */ + CopyBackupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CopyBackupRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.CopyBackupRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.backupId != null) + message.backupId = String(object.backupId); + if (object.sourceBackup != null) + message.sourceBackup = String(object.sourceBackup); + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.CopyBackupRequest.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime); + } + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.admin.database.v1.CopyBackupRequest.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig.fromObject(object.encryptionConfig); + } + return message; + }; + + /** + * Creates a plain object from a CopyBackupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {google.spanner.admin.database.v1.CopyBackupRequest} message CopyBackupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CopyBackupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.backupId = ""; + object.sourceBackup = ""; + object.expireTime = null; + object.encryptionConfig = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.backupId != null && message.hasOwnProperty("backupId")) + object.backupId = message.backupId; + if (message.sourceBackup != null && message.hasOwnProperty("sourceBackup")) + object.sourceBackup = message.sourceBackup; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig.toObject(message.encryptionConfig, options); + return object; + }; + + /** + * Converts this CopyBackupRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @instance + * @returns {Object.} JSON object + */ + CopyBackupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CopyBackupRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CopyBackupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CopyBackupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CopyBackupRequest"; + }; + + return CopyBackupRequest; + })(); + + v1.CopyBackupMetadata = (function() { + + /** + * Properties of a CopyBackupMetadata. + * @memberof google.spanner.admin.database.v1 + * @interface ICopyBackupMetadata + * @property {string|null} [name] CopyBackupMetadata name + * @property {string|null} [sourceBackup] CopyBackupMetadata sourceBackup + * @property {google.spanner.admin.database.v1.IOperationProgress|null} [progress] CopyBackupMetadata progress + * @property {google.protobuf.ITimestamp|null} [cancelTime] CopyBackupMetadata cancelTime + */ + + /** + * Constructs a new CopyBackupMetadata. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CopyBackupMetadata. + * @implements ICopyBackupMetadata + * @constructor + * @param {google.spanner.admin.database.v1.ICopyBackupMetadata=} [properties] Properties to set + */ + function CopyBackupMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CopyBackupMetadata name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @instance + */ + CopyBackupMetadata.prototype.name = ""; + + /** + * CopyBackupMetadata sourceBackup. + * @member {string} sourceBackup + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @instance + */ + CopyBackupMetadata.prototype.sourceBackup = ""; + + /** + * CopyBackupMetadata progress. + * @member {google.spanner.admin.database.v1.IOperationProgress|null|undefined} progress + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @instance + */ + CopyBackupMetadata.prototype.progress = null; + + /** + * CopyBackupMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @instance + */ + CopyBackupMetadata.prototype.cancelTime = null; + + /** + * Creates a new CopyBackupMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CopyBackupMetadata} CopyBackupMetadata instance + */ + CopyBackupMetadata.create = function create(properties) { + return new CopyBackupMetadata(properties); + }; + + /** + * Encodes the specified CopyBackupMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupMetadata} message CopyBackupMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CopyBackupMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.sourceBackup != null && Object.hasOwnProperty.call(message, "sourceBackup")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.sourceBackup); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.spanner.admin.database.v1.OperationProgress.encode(message.progress, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CopyBackupMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupMetadata} message CopyBackupMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CopyBackupMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CopyBackupMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CopyBackupMetadata} CopyBackupMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CopyBackupMetadata.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.spanner.admin.database.v1.CopyBackupMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.sourceBackup = reader.string(); + break; + } + case 3: { + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.decode(reader, reader.uint32()); + break; + } + case 4: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CopyBackupMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CopyBackupMetadata} CopyBackupMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CopyBackupMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CopyBackupMetadata message. + * @function verify + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CopyBackupMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.sourceBackup != null && message.hasOwnProperty("sourceBackup")) + if (!$util.isString(message.sourceBackup)) + return "sourceBackup: string expected"; + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.spanner.admin.database.v1.OperationProgress.verify(message.progress); + if (error) + return "progress." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + return null; + }; + + /** + * Creates a CopyBackupMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CopyBackupMetadata} CopyBackupMetadata + */ + CopyBackupMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CopyBackupMetadata) + return object; + var message = new $root.google.spanner.admin.database.v1.CopyBackupMetadata(); + if (object.name != null) + message.name = String(object.name); + if (object.sourceBackup != null) + message.sourceBackup = String(object.sourceBackup); + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.spanner.admin.database.v1.CopyBackupMetadata.progress: object expected"); + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.fromObject(object.progress); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.CopyBackupMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + return message; + }; + + /** + * Creates a plain object from a CopyBackupMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {google.spanner.admin.database.v1.CopyBackupMetadata} message CopyBackupMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CopyBackupMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.sourceBackup = ""; + object.progress = null; + object.cancelTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.sourceBackup != null && message.hasOwnProperty("sourceBackup")) + object.sourceBackup = message.sourceBackup; + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.spanner.admin.database.v1.OperationProgress.toObject(message.progress, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + return object; + }; + + /** + * Converts this CopyBackupMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @instance + * @returns {Object.} JSON object + */ + CopyBackupMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CopyBackupMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CopyBackupMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CopyBackupMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CopyBackupMetadata"; + }; + + return CopyBackupMetadata; + })(); + + v1.UpdateBackupRequest = (function() { + + /** + * Properties of an UpdateBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IUpdateBackupRequest + * @property {google.spanner.admin.database.v1.IBackup|null} [backup] UpdateBackupRequest backup + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateBackupRequest updateMask + */ + + /** + * Constructs a new UpdateBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an UpdateBackupRequest. + * @implements IUpdateBackupRequest + * @constructor + * @param {google.spanner.admin.database.v1.IUpdateBackupRequest=} [properties] Properties to set + */ + function UpdateBackupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateBackupRequest backup. + * @member {google.spanner.admin.database.v1.IBackup|null|undefined} backup + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @instance + */ + UpdateBackupRequest.prototype.backup = null; + + /** + * UpdateBackupRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @instance + */ + UpdateBackupRequest.prototype.updateMask = null; + + /** + * Creates a new UpdateBackupRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateBackupRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.UpdateBackupRequest} UpdateBackupRequest instance + */ + UpdateBackupRequest.create = function create(properties) { + return new UpdateBackupRequest(properties); + }; + + /** + * Encodes the specified UpdateBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateBackupRequest} message UpdateBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateBackupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.backup != null && Object.hasOwnProperty.call(message, "backup")) + $root.google.spanner.admin.database.v1.Backup.encode(message.backup, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + $root.google.protobuf.FieldMask.encode(message.updateMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateBackupRequest} message UpdateBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateBackupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateBackupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.UpdateBackupRequest} UpdateBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateBackupRequest.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.spanner.admin.database.v1.UpdateBackupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.backup = $root.google.spanner.admin.database.v1.Backup.decode(reader, reader.uint32()); + break; + } + case 2: { + message.updateMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateBackupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.UpdateBackupRequest} UpdateBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateBackupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateBackupRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateBackupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.backup != null && message.hasOwnProperty("backup")) { + var error = $root.google.spanner.admin.database.v1.Backup.verify(message.backup); + if (error) + return "backup." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.updateMask); + if (error) + return "updateMask." + error; + } + return null; + }; + + /** + * Creates an UpdateBackupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.UpdateBackupRequest} UpdateBackupRequest + */ + UpdateBackupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.UpdateBackupRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.UpdateBackupRequest(); + if (object.backup != null) { + if (typeof object.backup !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateBackupRequest.backup: object expected"); + message.backup = $root.google.spanner.admin.database.v1.Backup.fromObject(object.backup); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateBackupRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateBackupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {google.spanner.admin.database.v1.UpdateBackupRequest} message UpdateBackupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateBackupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.backup = null; + object.updateMask = null; + } + if (message.backup != null && message.hasOwnProperty("backup")) + object.backup = $root.google.spanner.admin.database.v1.Backup.toObject(message.backup, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this UpdateBackupRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateBackupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateBackupRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.UpdateBackupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateBackupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.UpdateBackupRequest"; + }; + + return UpdateBackupRequest; + })(); + + v1.GetBackupRequest = (function() { + + /** + * Properties of a GetBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IGetBackupRequest + * @property {string|null} [name] GetBackupRequest name + */ + + /** + * Constructs a new GetBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a GetBackupRequest. + * @implements IGetBackupRequest + * @constructor + * @param {google.spanner.admin.database.v1.IGetBackupRequest=} [properties] Properties to set + */ + function GetBackupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetBackupRequest name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @instance + */ + GetBackupRequest.prototype.name = ""; + + /** + * Creates a new GetBackupRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IGetBackupRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.GetBackupRequest} GetBackupRequest instance + */ + GetBackupRequest.create = function create(properties) { + return new GetBackupRequest(properties); + }; + + /** + * Encodes the specified GetBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IGetBackupRequest} message GetBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetBackupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IGetBackupRequest} message GetBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetBackupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetBackupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.GetBackupRequest} GetBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetBackupRequest.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.spanner.admin.database.v1.GetBackupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetBackupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.GetBackupRequest} GetBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetBackupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetBackupRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetBackupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.GetBackupRequest} GetBackupRequest + */ + GetBackupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.GetBackupRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.GetBackupRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {google.spanner.admin.database.v1.GetBackupRequest} message GetBackupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetBackupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetBackupRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @instance + * @returns {Object.} JSON object + */ + GetBackupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetBackupRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.GetBackupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetBackupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.GetBackupRequest"; + }; + + return GetBackupRequest; + })(); + + v1.DeleteBackupRequest = (function() { + + /** + * Properties of a DeleteBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IDeleteBackupRequest + * @property {string|null} [name] DeleteBackupRequest name + */ + + /** + * Constructs a new DeleteBackupRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a DeleteBackupRequest. + * @implements IDeleteBackupRequest + * @constructor + * @param {google.spanner.admin.database.v1.IDeleteBackupRequest=} [properties] Properties to set + */ + function DeleteBackupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteBackupRequest name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @instance + */ + DeleteBackupRequest.prototype.name = ""; + + /** + * Creates a new DeleteBackupRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IDeleteBackupRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.DeleteBackupRequest} DeleteBackupRequest instance + */ + DeleteBackupRequest.create = function create(properties) { + return new DeleteBackupRequest(properties); + }; + + /** + * Encodes the specified DeleteBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IDeleteBackupRequest} message DeleteBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteBackupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified DeleteBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {google.spanner.admin.database.v1.IDeleteBackupRequest} message DeleteBackupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteBackupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteBackupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.DeleteBackupRequest} DeleteBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteBackupRequest.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.spanner.admin.database.v1.DeleteBackupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteBackupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.DeleteBackupRequest} DeleteBackupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteBackupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteBackupRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteBackupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.DeleteBackupRequest} DeleteBackupRequest + */ + DeleteBackupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.DeleteBackupRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.DeleteBackupRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {google.spanner.admin.database.v1.DeleteBackupRequest} message DeleteBackupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteBackupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteBackupRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteBackupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteBackupRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.DeleteBackupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteBackupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.DeleteBackupRequest"; + }; + + return DeleteBackupRequest; + })(); + + v1.ListBackupsRequest = (function() { + + /** + * Properties of a ListBackupsRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IListBackupsRequest + * @property {string|null} [parent] ListBackupsRequest parent + * @property {string|null} [filter] ListBackupsRequest filter + * @property {number|null} [pageSize] ListBackupsRequest pageSize + * @property {string|null} [pageToken] ListBackupsRequest pageToken + */ + + /** + * Constructs a new ListBackupsRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListBackupsRequest. + * @implements IListBackupsRequest + * @constructor + * @param {google.spanner.admin.database.v1.IListBackupsRequest=} [properties] Properties to set + */ + function ListBackupsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupsRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @instance + */ + ListBackupsRequest.prototype.parent = ""; + + /** + * ListBackupsRequest filter. + * @member {string} filter + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @instance + */ + ListBackupsRequest.prototype.filter = ""; + + /** + * ListBackupsRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @instance + */ + ListBackupsRequest.prototype.pageSize = 0; + + /** + * ListBackupsRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @instance + */ + ListBackupsRequest.prototype.pageToken = ""; + + /** + * Creates a new ListBackupsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupsRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListBackupsRequest} ListBackupsRequest instance + */ + ListBackupsRequest.create = function create(properties) { + return new ListBackupsRequest(properties); + }; + + /** + * Encodes the specified ListBackupsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupsRequest} message ListBackupsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListBackupsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupsRequest} message ListBackupsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListBackupsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListBackupsRequest} ListBackupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupsRequest.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.spanner.admin.database.v1.ListBackupsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListBackupsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListBackupsRequest} ListBackupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListBackupsRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListBackupsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListBackupsRequest} ListBackupsRequest + */ + ListBackupsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListBackupsRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.ListBackupsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {google.spanner.admin.database.v1.ListBackupsRequest} message ListBackupsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListBackupsRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @instance + * @returns {Object.} JSON object + */ + ListBackupsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupsRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListBackupsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListBackupsRequest"; + }; + + return ListBackupsRequest; + })(); + + v1.ListBackupsResponse = (function() { + + /** + * Properties of a ListBackupsResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IListBackupsResponse + * @property {Array.|null} [backups] ListBackupsResponse backups + * @property {string|null} [nextPageToken] ListBackupsResponse nextPageToken + */ + + /** + * Constructs a new ListBackupsResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListBackupsResponse. + * @implements IListBackupsResponse + * @constructor + * @param {google.spanner.admin.database.v1.IListBackupsResponse=} [properties] Properties to set + */ + function ListBackupsResponse(properties) { + this.backups = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupsResponse backups. + * @member {Array.} backups + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @instance + */ + ListBackupsResponse.prototype.backups = $util.emptyArray; + + /** + * ListBackupsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @instance + */ + ListBackupsResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListBackupsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupsResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListBackupsResponse} ListBackupsResponse instance + */ + ListBackupsResponse.create = function create(properties) { + return new ListBackupsResponse(properties); + }; + + /** + * Encodes the specified ListBackupsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupsResponse} message ListBackupsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.backups != null && message.backups.length) + for (var i = 0; i < message.backups.length; ++i) + $root.google.spanner.admin.database.v1.Backup.encode(message.backups[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListBackupsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupsResponse} message ListBackupsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListBackupsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListBackupsResponse} ListBackupsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupsResponse.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.spanner.admin.database.v1.ListBackupsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.backups && message.backups.length)) + message.backups = []; + message.backups.push($root.google.spanner.admin.database.v1.Backup.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListBackupsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListBackupsResponse} ListBackupsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListBackupsResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListBackupsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.backups != null && message.hasOwnProperty("backups")) { + if (!Array.isArray(message.backups)) + return "backups: array expected"; + for (var i = 0; i < message.backups.length; ++i) { + var error = $root.google.spanner.admin.database.v1.Backup.verify(message.backups[i]); + if (error) + return "backups." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListBackupsResponse} ListBackupsResponse + */ + ListBackupsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListBackupsResponse) + return object; + var message = new $root.google.spanner.admin.database.v1.ListBackupsResponse(); + if (object.backups) { + if (!Array.isArray(object.backups)) + throw TypeError(".google.spanner.admin.database.v1.ListBackupsResponse.backups: array expected"); + message.backups = []; + for (var i = 0; i < object.backups.length; ++i) { + if (typeof object.backups[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.ListBackupsResponse.backups: object expected"); + message.backups[i] = $root.google.spanner.admin.database.v1.Backup.fromObject(object.backups[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {google.spanner.admin.database.v1.ListBackupsResponse} message ListBackupsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.backups = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.backups && message.backups.length) { + object.backups = []; + for (var j = 0; j < message.backups.length; ++j) + object.backups[j] = $root.google.spanner.admin.database.v1.Backup.toObject(message.backups[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListBackupsResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @instance + * @returns {Object.} JSON object + */ + ListBackupsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupsResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListBackupsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListBackupsResponse"; + }; + + return ListBackupsResponse; + })(); + + v1.ListBackupOperationsRequest = (function() { + + /** + * Properties of a ListBackupOperationsRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IListBackupOperationsRequest + * @property {string|null} [parent] ListBackupOperationsRequest parent + * @property {string|null} [filter] ListBackupOperationsRequest filter + * @property {number|null} [pageSize] ListBackupOperationsRequest pageSize + * @property {string|null} [pageToken] ListBackupOperationsRequest pageToken + */ + + /** + * Constructs a new ListBackupOperationsRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListBackupOperationsRequest. + * @implements IListBackupOperationsRequest + * @constructor + * @param {google.spanner.admin.database.v1.IListBackupOperationsRequest=} [properties] Properties to set + */ + function ListBackupOperationsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupOperationsRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @instance + */ + ListBackupOperationsRequest.prototype.parent = ""; + + /** + * ListBackupOperationsRequest filter. + * @member {string} filter + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @instance + */ + ListBackupOperationsRequest.prototype.filter = ""; + + /** + * ListBackupOperationsRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @instance + */ + ListBackupOperationsRequest.prototype.pageSize = 0; + + /** + * ListBackupOperationsRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @instance + */ + ListBackupOperationsRequest.prototype.pageToken = ""; + + /** + * Creates a new ListBackupOperationsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupOperationsRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListBackupOperationsRequest} ListBackupOperationsRequest instance + */ + ListBackupOperationsRequest.create = function create(properties) { + return new ListBackupOperationsRequest(properties); + }; + + /** + * Encodes the specified ListBackupOperationsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupOperationsRequest} message ListBackupOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupOperationsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListBackupOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupOperationsRequest} message ListBackupOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupOperationsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListBackupOperationsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListBackupOperationsRequest} ListBackupOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupOperationsRequest.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.spanner.admin.database.v1.ListBackupOperationsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListBackupOperationsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListBackupOperationsRequest} ListBackupOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupOperationsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListBackupOperationsRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListBackupOperationsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListBackupOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListBackupOperationsRequest} ListBackupOperationsRequest + */ + ListBackupOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListBackupOperationsRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.ListBackupOperationsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListBackupOperationsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {google.spanner.admin.database.v1.ListBackupOperationsRequest} message ListBackupOperationsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupOperationsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListBackupOperationsRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @instance + * @returns {Object.} JSON object + */ + ListBackupOperationsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupOperationsRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListBackupOperationsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListBackupOperationsRequest"; + }; + + return ListBackupOperationsRequest; + })(); + + v1.ListBackupOperationsResponse = (function() { + + /** + * Properties of a ListBackupOperationsResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IListBackupOperationsResponse + * @property {Array.|null} [operations] ListBackupOperationsResponse operations + * @property {string|null} [nextPageToken] ListBackupOperationsResponse nextPageToken + */ + + /** + * Constructs a new ListBackupOperationsResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListBackupOperationsResponse. + * @implements IListBackupOperationsResponse + * @constructor + * @param {google.spanner.admin.database.v1.IListBackupOperationsResponse=} [properties] Properties to set + */ + function ListBackupOperationsResponse(properties) { + this.operations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupOperationsResponse operations. + * @member {Array.} operations + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @instance + */ + ListBackupOperationsResponse.prototype.operations = $util.emptyArray; + + /** + * ListBackupOperationsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @instance + */ + ListBackupOperationsResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListBackupOperationsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupOperationsResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListBackupOperationsResponse} ListBackupOperationsResponse instance + */ + ListBackupOperationsResponse.create = function create(properties) { + return new ListBackupOperationsResponse(properties); + }; + + /** + * Encodes the specified ListBackupOperationsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupOperationsResponse} message ListBackupOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupOperationsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.operations != null && message.operations.length) + for (var i = 0; i < message.operations.length; ++i) + $root.google.longrunning.Operation.encode(message.operations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListBackupOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupOperationsResponse} message ListBackupOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupOperationsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListBackupOperationsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListBackupOperationsResponse} ListBackupOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupOperationsResponse.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.spanner.admin.database.v1.ListBackupOperationsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.operations && message.operations.length)) + message.operations = []; + message.operations.push($root.google.longrunning.Operation.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListBackupOperationsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListBackupOperationsResponse} ListBackupOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupOperationsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListBackupOperationsResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListBackupOperationsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.operations != null && message.hasOwnProperty("operations")) { + if (!Array.isArray(message.operations)) + return "operations: array expected"; + for (var i = 0; i < message.operations.length; ++i) { + var error = $root.google.longrunning.Operation.verify(message.operations[i]); + if (error) + return "operations." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListBackupOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListBackupOperationsResponse} ListBackupOperationsResponse + */ + ListBackupOperationsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListBackupOperationsResponse) + return object; + var message = new $root.google.spanner.admin.database.v1.ListBackupOperationsResponse(); + if (object.operations) { + if (!Array.isArray(object.operations)) + throw TypeError(".google.spanner.admin.database.v1.ListBackupOperationsResponse.operations: array expected"); + message.operations = []; + for (var i = 0; i < object.operations.length; ++i) { + if (typeof object.operations[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.ListBackupOperationsResponse.operations: object expected"); + message.operations[i] = $root.google.longrunning.Operation.fromObject(object.operations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListBackupOperationsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {google.spanner.admin.database.v1.ListBackupOperationsResponse} message ListBackupOperationsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupOperationsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.operations = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.operations && message.operations.length) { + object.operations = []; + for (var j = 0; j < message.operations.length; ++j) + object.operations[j] = $root.google.longrunning.Operation.toObject(message.operations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListBackupOperationsResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @instance + * @returns {Object.} JSON object + */ + ListBackupOperationsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupOperationsResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListBackupOperationsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupOperationsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListBackupOperationsResponse"; + }; + + return ListBackupOperationsResponse; + })(); + + v1.BackupInfo = (function() { + + /** + * Properties of a BackupInfo. + * @memberof google.spanner.admin.database.v1 + * @interface IBackupInfo + * @property {string|null} [backup] BackupInfo backup + * @property {google.protobuf.ITimestamp|null} [versionTime] BackupInfo versionTime + * @property {google.protobuf.ITimestamp|null} [createTime] BackupInfo createTime + * @property {string|null} [sourceDatabase] BackupInfo sourceDatabase + */ + + /** + * Constructs a new BackupInfo. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a BackupInfo. + * @implements IBackupInfo + * @constructor + * @param {google.spanner.admin.database.v1.IBackupInfo=} [properties] Properties to set + */ + function BackupInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BackupInfo backup. + * @member {string} backup + * @memberof google.spanner.admin.database.v1.BackupInfo + * @instance + */ + BackupInfo.prototype.backup = ""; + + /** + * BackupInfo versionTime. + * @member {google.protobuf.ITimestamp|null|undefined} versionTime + * @memberof google.spanner.admin.database.v1.BackupInfo + * @instance + */ + BackupInfo.prototype.versionTime = null; + + /** + * BackupInfo createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.spanner.admin.database.v1.BackupInfo + * @instance + */ + BackupInfo.prototype.createTime = null; + + /** + * BackupInfo sourceDatabase. + * @member {string} sourceDatabase + * @memberof google.spanner.admin.database.v1.BackupInfo + * @instance + */ + BackupInfo.prototype.sourceDatabase = ""; + + /** + * Creates a new BackupInfo instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {google.spanner.admin.database.v1.IBackupInfo=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.BackupInfo} BackupInfo instance + */ + BackupInfo.create = function create(properties) { + return new BackupInfo(properties); + }; + + /** + * Encodes the specified BackupInfo message. Does not implicitly {@link google.spanner.admin.database.v1.BackupInfo.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {google.spanner.admin.database.v1.IBackupInfo} message BackupInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackupInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.backup != null && Object.hasOwnProperty.call(message, "backup")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.backup); + if (message.createTime != null && Object.hasOwnProperty.call(message, "createTime")) + $root.google.protobuf.Timestamp.encode(message.createTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.sourceDatabase != null && Object.hasOwnProperty.call(message, "sourceDatabase")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.sourceDatabase); + if (message.versionTime != null && Object.hasOwnProperty.call(message, "versionTime")) + $root.google.protobuf.Timestamp.encode(message.versionTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BackupInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {google.spanner.admin.database.v1.IBackupInfo} message BackupInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackupInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BackupInfo message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.BackupInfo} BackupInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackupInfo.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.spanner.admin.database.v1.BackupInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.backup = reader.string(); + break; + } + case 4: { + message.versionTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.sourceDatabase = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BackupInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.BackupInfo} BackupInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackupInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BackupInfo message. + * @function verify + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BackupInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.backup != null && message.hasOwnProperty("backup")) + if (!$util.isString(message.backup)) + return "backup: string expected"; + if (message.versionTime != null && message.hasOwnProperty("versionTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.versionTime); + if (error) + return "versionTime." + error; + } + if (message.createTime != null && message.hasOwnProperty("createTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.createTime); + if (error) + return "createTime." + error; + } + if (message.sourceDatabase != null && message.hasOwnProperty("sourceDatabase")) + if (!$util.isString(message.sourceDatabase)) + return "sourceDatabase: string expected"; + return null; + }; + + /** + * Creates a BackupInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.BackupInfo} BackupInfo + */ + BackupInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.BackupInfo) + return object; + var message = new $root.google.spanner.admin.database.v1.BackupInfo(); + if (object.backup != null) + message.backup = String(object.backup); + if (object.versionTime != null) { + if (typeof object.versionTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupInfo.versionTime: object expected"); + message.versionTime = $root.google.protobuf.Timestamp.fromObject(object.versionTime); + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupInfo.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.sourceDatabase != null) + message.sourceDatabase = String(object.sourceDatabase); + return message; + }; + + /** + * Creates a plain object from a BackupInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {google.spanner.admin.database.v1.BackupInfo} message BackupInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BackupInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.backup = ""; + object.createTime = null; + object.sourceDatabase = ""; + object.versionTime = null; + } + if (message.backup != null && message.hasOwnProperty("backup")) + object.backup = message.backup; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.sourceDatabase != null && message.hasOwnProperty("sourceDatabase")) + object.sourceDatabase = message.sourceDatabase; + if (message.versionTime != null && message.hasOwnProperty("versionTime")) + object.versionTime = $root.google.protobuf.Timestamp.toObject(message.versionTime, options); + return object; + }; + + /** + * Converts this BackupInfo to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.BackupInfo + * @instance + * @returns {Object.} JSON object + */ + BackupInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BackupInfo + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.BackupInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BackupInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.BackupInfo"; + }; + + return BackupInfo; + })(); + + v1.CreateBackupEncryptionConfig = (function() { + + /** + * Properties of a CreateBackupEncryptionConfig. + * @memberof google.spanner.admin.database.v1 + * @interface ICreateBackupEncryptionConfig + * @property {google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType|null} [encryptionType] CreateBackupEncryptionConfig encryptionType + * @property {string|null} [kmsKeyName] CreateBackupEncryptionConfig kmsKeyName + * @property {Array.|null} [kmsKeyNames] CreateBackupEncryptionConfig kmsKeyNames + */ + + /** + * Constructs a new CreateBackupEncryptionConfig. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CreateBackupEncryptionConfig. + * @implements ICreateBackupEncryptionConfig + * @constructor + * @param {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig=} [properties] Properties to set + */ + function CreateBackupEncryptionConfig(properties) { + this.kmsKeyNames = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateBackupEncryptionConfig encryptionType. + * @member {google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType} encryptionType + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @instance + */ + CreateBackupEncryptionConfig.prototype.encryptionType = 0; + + /** + * CreateBackupEncryptionConfig kmsKeyName. + * @member {string} kmsKeyName + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @instance + */ + CreateBackupEncryptionConfig.prototype.kmsKeyName = ""; + + /** + * CreateBackupEncryptionConfig kmsKeyNames. + * @member {Array.} kmsKeyNames + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @instance + */ + CreateBackupEncryptionConfig.prototype.kmsKeyNames = $util.emptyArray; + + /** + * Creates a new CreateBackupEncryptionConfig instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CreateBackupEncryptionConfig} CreateBackupEncryptionConfig instance + */ + CreateBackupEncryptionConfig.create = function create(properties) { + return new CreateBackupEncryptionConfig(properties); + }; + + /** + * Encodes the specified CreateBackupEncryptionConfig message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupEncryptionConfig.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig} message CreateBackupEncryptionConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateBackupEncryptionConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.encryptionType != null && Object.hasOwnProperty.call(message, "encryptionType")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.encryptionType); + if (message.kmsKeyName != null && Object.hasOwnProperty.call(message, "kmsKeyName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.kmsKeyName); + if (message.kmsKeyNames != null && message.kmsKeyNames.length) + for (var i = 0; i < message.kmsKeyNames.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.kmsKeyNames[i]); + return writer; + }; + + /** + * Encodes the specified CreateBackupEncryptionConfig message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupEncryptionConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig} message CreateBackupEncryptionConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateBackupEncryptionConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateBackupEncryptionConfig message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CreateBackupEncryptionConfig} CreateBackupEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateBackupEncryptionConfig.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.spanner.admin.database.v1.CreateBackupEncryptionConfig(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.encryptionType = reader.int32(); + break; + } + case 2: { + message.kmsKeyName = reader.string(); + break; + } + case 3: { + if (!(message.kmsKeyNames && message.kmsKeyNames.length)) + message.kmsKeyNames = []; + message.kmsKeyNames.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateBackupEncryptionConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CreateBackupEncryptionConfig} CreateBackupEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateBackupEncryptionConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateBackupEncryptionConfig message. + * @function verify + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateBackupEncryptionConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.encryptionType != null && message.hasOwnProperty("encryptionType")) + switch (message.encryptionType) { + default: + return "encryptionType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + if (!$util.isString(message.kmsKeyName)) + return "kmsKeyName: string expected"; + if (message.kmsKeyNames != null && message.hasOwnProperty("kmsKeyNames")) { + if (!Array.isArray(message.kmsKeyNames)) + return "kmsKeyNames: array expected"; + for (var i = 0; i < message.kmsKeyNames.length; ++i) + if (!$util.isString(message.kmsKeyNames[i])) + return "kmsKeyNames: string[] expected"; + } + return null; + }; + + /** + * Creates a CreateBackupEncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CreateBackupEncryptionConfig} CreateBackupEncryptionConfig + */ + CreateBackupEncryptionConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig) + return object; + var message = new $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig(); + switch (object.encryptionType) { + default: + if (typeof object.encryptionType === "number") { + message.encryptionType = object.encryptionType; + break; + } + break; + case "ENCRYPTION_TYPE_UNSPECIFIED": + case 0: + message.encryptionType = 0; + break; + case "USE_DATABASE_ENCRYPTION": + case 1: + message.encryptionType = 1; + break; + case "GOOGLE_DEFAULT_ENCRYPTION": + case 2: + message.encryptionType = 2; + break; + case "CUSTOMER_MANAGED_ENCRYPTION": + case 3: + message.encryptionType = 3; + break; + } + if (object.kmsKeyName != null) + message.kmsKeyName = String(object.kmsKeyName); + if (object.kmsKeyNames) { + if (!Array.isArray(object.kmsKeyNames)) + throw TypeError(".google.spanner.admin.database.v1.CreateBackupEncryptionConfig.kmsKeyNames: array expected"); + message.kmsKeyNames = []; + for (var i = 0; i < object.kmsKeyNames.length; ++i) + message.kmsKeyNames[i] = String(object.kmsKeyNames[i]); + } + return message; + }; + + /** + * Creates a plain object from a CreateBackupEncryptionConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.CreateBackupEncryptionConfig} message CreateBackupEncryptionConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateBackupEncryptionConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.kmsKeyNames = []; + if (options.defaults) { + object.encryptionType = options.enums === String ? "ENCRYPTION_TYPE_UNSPECIFIED" : 0; + object.kmsKeyName = ""; + } + if (message.encryptionType != null && message.hasOwnProperty("encryptionType")) + object.encryptionType = options.enums === String ? $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType[message.encryptionType] === undefined ? message.encryptionType : $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType[message.encryptionType] : message.encryptionType; + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + object.kmsKeyName = message.kmsKeyName; + if (message.kmsKeyNames && message.kmsKeyNames.length) { + object.kmsKeyNames = []; + for (var j = 0; j < message.kmsKeyNames.length; ++j) + object.kmsKeyNames[j] = message.kmsKeyNames[j]; + } + return object; + }; + + /** + * Converts this CreateBackupEncryptionConfig to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @instance + * @returns {Object.} JSON object + */ + CreateBackupEncryptionConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateBackupEncryptionConfig + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CreateBackupEncryptionConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateBackupEncryptionConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CreateBackupEncryptionConfig"; + }; + + /** + * EncryptionType enum. + * @name google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType + * @enum {number} + * @property {number} ENCRYPTION_TYPE_UNSPECIFIED=0 ENCRYPTION_TYPE_UNSPECIFIED value + * @property {number} USE_DATABASE_ENCRYPTION=1 USE_DATABASE_ENCRYPTION value + * @property {number} GOOGLE_DEFAULT_ENCRYPTION=2 GOOGLE_DEFAULT_ENCRYPTION value + * @property {number} CUSTOMER_MANAGED_ENCRYPTION=3 CUSTOMER_MANAGED_ENCRYPTION value + */ + CreateBackupEncryptionConfig.EncryptionType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENCRYPTION_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "USE_DATABASE_ENCRYPTION"] = 1; + values[valuesById[2] = "GOOGLE_DEFAULT_ENCRYPTION"] = 2; + values[valuesById[3] = "CUSTOMER_MANAGED_ENCRYPTION"] = 3; + return values; + })(); + + return CreateBackupEncryptionConfig; + })(); + + v1.CopyBackupEncryptionConfig = (function() { + + /** + * Properties of a CopyBackupEncryptionConfig. + * @memberof google.spanner.admin.database.v1 + * @interface ICopyBackupEncryptionConfig + * @property {google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType|null} [encryptionType] CopyBackupEncryptionConfig encryptionType + * @property {string|null} [kmsKeyName] CopyBackupEncryptionConfig kmsKeyName + * @property {Array.|null} [kmsKeyNames] CopyBackupEncryptionConfig kmsKeyNames + */ + + /** + * Constructs a new CopyBackupEncryptionConfig. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CopyBackupEncryptionConfig. + * @implements ICopyBackupEncryptionConfig + * @constructor + * @param {google.spanner.admin.database.v1.ICopyBackupEncryptionConfig=} [properties] Properties to set + */ + function CopyBackupEncryptionConfig(properties) { + this.kmsKeyNames = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CopyBackupEncryptionConfig encryptionType. + * @member {google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType} encryptionType + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @instance + */ + CopyBackupEncryptionConfig.prototype.encryptionType = 0; + + /** + * CopyBackupEncryptionConfig kmsKeyName. + * @member {string} kmsKeyName + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @instance + */ + CopyBackupEncryptionConfig.prototype.kmsKeyName = ""; + + /** + * CopyBackupEncryptionConfig kmsKeyNames. + * @member {Array.} kmsKeyNames + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @instance + */ + CopyBackupEncryptionConfig.prototype.kmsKeyNames = $util.emptyArray; + + /** + * Creates a new CopyBackupEncryptionConfig instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupEncryptionConfig=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CopyBackupEncryptionConfig} CopyBackupEncryptionConfig instance + */ + CopyBackupEncryptionConfig.create = function create(properties) { + return new CopyBackupEncryptionConfig(properties); + }; + + /** + * Encodes the specified CopyBackupEncryptionConfig message. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupEncryptionConfig.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupEncryptionConfig} message CopyBackupEncryptionConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CopyBackupEncryptionConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.encryptionType != null && Object.hasOwnProperty.call(message, "encryptionType")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.encryptionType); + if (message.kmsKeyName != null && Object.hasOwnProperty.call(message, "kmsKeyName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.kmsKeyName); + if (message.kmsKeyNames != null && message.kmsKeyNames.length) + for (var i = 0; i < message.kmsKeyNames.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.kmsKeyNames[i]); + return writer; + }; + + /** + * Encodes the specified CopyBackupEncryptionConfig message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CopyBackupEncryptionConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.ICopyBackupEncryptionConfig} message CopyBackupEncryptionConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CopyBackupEncryptionConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CopyBackupEncryptionConfig message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CopyBackupEncryptionConfig} CopyBackupEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CopyBackupEncryptionConfig.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.spanner.admin.database.v1.CopyBackupEncryptionConfig(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.encryptionType = reader.int32(); + break; + } + case 2: { + message.kmsKeyName = reader.string(); + break; + } + case 3: { + if (!(message.kmsKeyNames && message.kmsKeyNames.length)) + message.kmsKeyNames = []; + message.kmsKeyNames.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CopyBackupEncryptionConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CopyBackupEncryptionConfig} CopyBackupEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CopyBackupEncryptionConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CopyBackupEncryptionConfig message. + * @function verify + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CopyBackupEncryptionConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.encryptionType != null && message.hasOwnProperty("encryptionType")) + switch (message.encryptionType) { + default: + return "encryptionType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + if (!$util.isString(message.kmsKeyName)) + return "kmsKeyName: string expected"; + if (message.kmsKeyNames != null && message.hasOwnProperty("kmsKeyNames")) { + if (!Array.isArray(message.kmsKeyNames)) + return "kmsKeyNames: array expected"; + for (var i = 0; i < message.kmsKeyNames.length; ++i) + if (!$util.isString(message.kmsKeyNames[i])) + return "kmsKeyNames: string[] expected"; + } + return null; + }; + + /** + * Creates a CopyBackupEncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CopyBackupEncryptionConfig} CopyBackupEncryptionConfig + */ + CopyBackupEncryptionConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig) + return object; + var message = new $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig(); + switch (object.encryptionType) { + default: + if (typeof object.encryptionType === "number") { + message.encryptionType = object.encryptionType; + break; + } + break; + case "ENCRYPTION_TYPE_UNSPECIFIED": + case 0: + message.encryptionType = 0; + break; + case "USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION": + case 1: + message.encryptionType = 1; + break; + case "GOOGLE_DEFAULT_ENCRYPTION": + case 2: + message.encryptionType = 2; + break; + case "CUSTOMER_MANAGED_ENCRYPTION": + case 3: + message.encryptionType = 3; + break; + } + if (object.kmsKeyName != null) + message.kmsKeyName = String(object.kmsKeyName); + if (object.kmsKeyNames) { + if (!Array.isArray(object.kmsKeyNames)) + throw TypeError(".google.spanner.admin.database.v1.CopyBackupEncryptionConfig.kmsKeyNames: array expected"); + message.kmsKeyNames = []; + for (var i = 0; i < object.kmsKeyNames.length; ++i) + message.kmsKeyNames[i] = String(object.kmsKeyNames[i]); + } + return message; + }; + + /** + * Creates a plain object from a CopyBackupEncryptionConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.CopyBackupEncryptionConfig} message CopyBackupEncryptionConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CopyBackupEncryptionConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.kmsKeyNames = []; + if (options.defaults) { + object.encryptionType = options.enums === String ? "ENCRYPTION_TYPE_UNSPECIFIED" : 0; + object.kmsKeyName = ""; + } + if (message.encryptionType != null && message.hasOwnProperty("encryptionType")) + object.encryptionType = options.enums === String ? $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType[message.encryptionType] === undefined ? message.encryptionType : $root.google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType[message.encryptionType] : message.encryptionType; + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + object.kmsKeyName = message.kmsKeyName; + if (message.kmsKeyNames && message.kmsKeyNames.length) { + object.kmsKeyNames = []; + for (var j = 0; j < message.kmsKeyNames.length; ++j) + object.kmsKeyNames[j] = message.kmsKeyNames[j]; + } + return object; + }; + + /** + * Converts this CopyBackupEncryptionConfig to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @instance + * @returns {Object.} JSON object + */ + CopyBackupEncryptionConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CopyBackupEncryptionConfig + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CopyBackupEncryptionConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CopyBackupEncryptionConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CopyBackupEncryptionConfig"; + }; + + /** + * EncryptionType enum. + * @name google.spanner.admin.database.v1.CopyBackupEncryptionConfig.EncryptionType + * @enum {number} + * @property {number} ENCRYPTION_TYPE_UNSPECIFIED=0 ENCRYPTION_TYPE_UNSPECIFIED value + * @property {number} USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION=1 USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION value + * @property {number} GOOGLE_DEFAULT_ENCRYPTION=2 GOOGLE_DEFAULT_ENCRYPTION value + * @property {number} CUSTOMER_MANAGED_ENCRYPTION=3 CUSTOMER_MANAGED_ENCRYPTION value + */ + CopyBackupEncryptionConfig.EncryptionType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENCRYPTION_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION"] = 1; + values[valuesById[2] = "GOOGLE_DEFAULT_ENCRYPTION"] = 2; + values[valuesById[3] = "CUSTOMER_MANAGED_ENCRYPTION"] = 3; + return values; + })(); + + return CopyBackupEncryptionConfig; + })(); + + v1.FullBackupSpec = (function() { + + /** + * Properties of a FullBackupSpec. + * @memberof google.spanner.admin.database.v1 + * @interface IFullBackupSpec + */ + + /** + * Constructs a new FullBackupSpec. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a FullBackupSpec. + * @implements IFullBackupSpec + * @constructor + * @param {google.spanner.admin.database.v1.IFullBackupSpec=} [properties] Properties to set + */ + function FullBackupSpec(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new FullBackupSpec instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {google.spanner.admin.database.v1.IFullBackupSpec=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.FullBackupSpec} FullBackupSpec instance + */ + FullBackupSpec.create = function create(properties) { + return new FullBackupSpec(properties); + }; + + /** + * Encodes the specified FullBackupSpec message. Does not implicitly {@link google.spanner.admin.database.v1.FullBackupSpec.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {google.spanner.admin.database.v1.IFullBackupSpec} message FullBackupSpec message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FullBackupSpec.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified FullBackupSpec message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.FullBackupSpec.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {google.spanner.admin.database.v1.IFullBackupSpec} message FullBackupSpec message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FullBackupSpec.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FullBackupSpec message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.FullBackupSpec} FullBackupSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FullBackupSpec.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.spanner.admin.database.v1.FullBackupSpec(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FullBackupSpec message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.FullBackupSpec} FullBackupSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FullBackupSpec.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FullBackupSpec message. + * @function verify + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FullBackupSpec.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a FullBackupSpec message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.FullBackupSpec} FullBackupSpec + */ + FullBackupSpec.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.FullBackupSpec) + return object; + return new $root.google.spanner.admin.database.v1.FullBackupSpec(); + }; + + /** + * Creates a plain object from a FullBackupSpec message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {google.spanner.admin.database.v1.FullBackupSpec} message FullBackupSpec + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FullBackupSpec.toObject = function toObject() { + return {}; + }; + + /** + * Converts this FullBackupSpec to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @instance + * @returns {Object.} JSON object + */ + FullBackupSpec.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FullBackupSpec + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.FullBackupSpec + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FullBackupSpec.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.FullBackupSpec"; + }; + + return FullBackupSpec; + })(); + + v1.IncrementalBackupSpec = (function() { + + /** + * Properties of an IncrementalBackupSpec. + * @memberof google.spanner.admin.database.v1 + * @interface IIncrementalBackupSpec + */ + + /** + * Constructs a new IncrementalBackupSpec. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an IncrementalBackupSpec. + * @implements IIncrementalBackupSpec + * @constructor + * @param {google.spanner.admin.database.v1.IIncrementalBackupSpec=} [properties] Properties to set + */ + function IncrementalBackupSpec(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new IncrementalBackupSpec instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {google.spanner.admin.database.v1.IIncrementalBackupSpec=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.IncrementalBackupSpec} IncrementalBackupSpec instance + */ + IncrementalBackupSpec.create = function create(properties) { + return new IncrementalBackupSpec(properties); + }; + + /** + * Encodes the specified IncrementalBackupSpec message. Does not implicitly {@link google.spanner.admin.database.v1.IncrementalBackupSpec.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {google.spanner.admin.database.v1.IIncrementalBackupSpec} message IncrementalBackupSpec message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IncrementalBackupSpec.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified IncrementalBackupSpec message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.IncrementalBackupSpec.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {google.spanner.admin.database.v1.IIncrementalBackupSpec} message IncrementalBackupSpec message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IncrementalBackupSpec.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an IncrementalBackupSpec message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.IncrementalBackupSpec} IncrementalBackupSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IncrementalBackupSpec.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.spanner.admin.database.v1.IncrementalBackupSpec(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an IncrementalBackupSpec message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.IncrementalBackupSpec} IncrementalBackupSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IncrementalBackupSpec.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an IncrementalBackupSpec message. + * @function verify + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + IncrementalBackupSpec.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates an IncrementalBackupSpec message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.IncrementalBackupSpec} IncrementalBackupSpec + */ + IncrementalBackupSpec.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.IncrementalBackupSpec) + return object; + return new $root.google.spanner.admin.database.v1.IncrementalBackupSpec(); + }; + + /** + * Creates a plain object from an IncrementalBackupSpec message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {google.spanner.admin.database.v1.IncrementalBackupSpec} message IncrementalBackupSpec + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IncrementalBackupSpec.toObject = function toObject() { + return {}; + }; + + /** + * Converts this IncrementalBackupSpec to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @instance + * @returns {Object.} JSON object + */ + IncrementalBackupSpec.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IncrementalBackupSpec + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.IncrementalBackupSpec + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IncrementalBackupSpec.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.IncrementalBackupSpec"; + }; + + return IncrementalBackupSpec; + })(); + + v1.BackupInstancePartition = (function() { + + /** + * Properties of a BackupInstancePartition. + * @memberof google.spanner.admin.database.v1 + * @interface IBackupInstancePartition + * @property {string|null} [instancePartition] BackupInstancePartition instancePartition + */ + + /** + * Constructs a new BackupInstancePartition. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a BackupInstancePartition. + * @implements IBackupInstancePartition + * @constructor + * @param {google.spanner.admin.database.v1.IBackupInstancePartition=} [properties] Properties to set + */ + function BackupInstancePartition(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BackupInstancePartition instancePartition. + * @member {string} instancePartition + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @instance + */ + BackupInstancePartition.prototype.instancePartition = ""; + + /** + * Creates a new BackupInstancePartition instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {google.spanner.admin.database.v1.IBackupInstancePartition=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.BackupInstancePartition} BackupInstancePartition instance + */ + BackupInstancePartition.create = function create(properties) { + return new BackupInstancePartition(properties); + }; + + /** + * Encodes the specified BackupInstancePartition message. Does not implicitly {@link google.spanner.admin.database.v1.BackupInstancePartition.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {google.spanner.admin.database.v1.IBackupInstancePartition} message BackupInstancePartition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackupInstancePartition.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instancePartition != null && Object.hasOwnProperty.call(message, "instancePartition")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instancePartition); + return writer; + }; + + /** + * Encodes the specified BackupInstancePartition message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupInstancePartition.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {google.spanner.admin.database.v1.IBackupInstancePartition} message BackupInstancePartition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackupInstancePartition.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BackupInstancePartition message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.BackupInstancePartition} BackupInstancePartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackupInstancePartition.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.spanner.admin.database.v1.BackupInstancePartition(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instancePartition = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BackupInstancePartition message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.BackupInstancePartition} BackupInstancePartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackupInstancePartition.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BackupInstancePartition message. + * @function verify + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BackupInstancePartition.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) + if (!$util.isString(message.instancePartition)) + return "instancePartition: string expected"; + return null; + }; + + /** + * Creates a BackupInstancePartition message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.BackupInstancePartition} BackupInstancePartition + */ + BackupInstancePartition.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.BackupInstancePartition) + return object; + var message = new $root.google.spanner.admin.database.v1.BackupInstancePartition(); + if (object.instancePartition != null) + message.instancePartition = String(object.instancePartition); + return message; + }; + + /** + * Creates a plain object from a BackupInstancePartition message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {google.spanner.admin.database.v1.BackupInstancePartition} message BackupInstancePartition + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BackupInstancePartition.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.instancePartition = ""; + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) + object.instancePartition = message.instancePartition; + return object; + }; + + /** + * Converts this BackupInstancePartition to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @instance + * @returns {Object.} JSON object + */ + BackupInstancePartition.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BackupInstancePartition + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.BackupInstancePartition + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BackupInstancePartition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.BackupInstancePartition"; + }; + + return BackupInstancePartition; + })(); + + v1.OperationProgress = (function() { + + /** + * Properties of an OperationProgress. + * @memberof google.spanner.admin.database.v1 + * @interface IOperationProgress + * @property {number|null} [progressPercent] OperationProgress progressPercent + * @property {google.protobuf.ITimestamp|null} [startTime] OperationProgress startTime + * @property {google.protobuf.ITimestamp|null} [endTime] OperationProgress endTime + */ + + /** + * Constructs a new OperationProgress. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an OperationProgress. + * @implements IOperationProgress + * @constructor + * @param {google.spanner.admin.database.v1.IOperationProgress=} [properties] Properties to set + */ + function OperationProgress(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OperationProgress progressPercent. + * @member {number} progressPercent + * @memberof google.spanner.admin.database.v1.OperationProgress + * @instance + */ + OperationProgress.prototype.progressPercent = 0; + + /** + * OperationProgress startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.spanner.admin.database.v1.OperationProgress + * @instance + */ + OperationProgress.prototype.startTime = null; + + /** + * OperationProgress endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.spanner.admin.database.v1.OperationProgress + * @instance + */ + OperationProgress.prototype.endTime = null; + + /** + * Creates a new OperationProgress instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {google.spanner.admin.database.v1.IOperationProgress=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.OperationProgress} OperationProgress instance + */ + OperationProgress.create = function create(properties) { + return new OperationProgress(properties); + }; + + /** + * Encodes the specified OperationProgress message. Does not implicitly {@link google.spanner.admin.database.v1.OperationProgress.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {google.spanner.admin.database.v1.IOperationProgress} message OperationProgress message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OperationProgress.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.progressPercent != null && Object.hasOwnProperty.call(message, "progressPercent")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.progressPercent); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) + $root.google.protobuf.Timestamp.encode(message.endTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified OperationProgress message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.OperationProgress.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {google.spanner.admin.database.v1.IOperationProgress} message OperationProgress message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OperationProgress.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an OperationProgress message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.OperationProgress} OperationProgress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OperationProgress.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.spanner.admin.database.v1.OperationProgress(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.progressPercent = reader.int32(); + break; + } + case 2: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.endTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an OperationProgress message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.OperationProgress} OperationProgress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OperationProgress.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an OperationProgress message. + * @function verify + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + OperationProgress.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.progressPercent != null && message.hasOwnProperty("progressPercent")) + if (!$util.isInteger(message.progressPercent)) + return "progressPercent: integer expected"; + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.endTime != null && message.hasOwnProperty("endTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.endTime); + if (error) + return "endTime." + error; + } + return null; + }; + + /** + * Creates an OperationProgress message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.OperationProgress} OperationProgress + */ + OperationProgress.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.OperationProgress) + return object; + var message = new $root.google.spanner.admin.database.v1.OperationProgress(); + if (object.progressPercent != null) + message.progressPercent = object.progressPercent | 0; + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.OperationProgress.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.OperationProgress.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + return message; + }; + + /** + * Creates a plain object from an OperationProgress message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {google.spanner.admin.database.v1.OperationProgress} message OperationProgress + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OperationProgress.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.progressPercent = 0; + object.startTime = null; + object.endTime = null; + } + if (message.progressPercent != null && message.hasOwnProperty("progressPercent")) + object.progressPercent = message.progressPercent; + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + return object; + }; + + /** + * Converts this OperationProgress to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.OperationProgress + * @instance + * @returns {Object.} JSON object + */ + OperationProgress.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OperationProgress + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.OperationProgress + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OperationProgress.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.OperationProgress"; + }; + + return OperationProgress; + })(); + + v1.EncryptionConfig = (function() { + + /** + * Properties of an EncryptionConfig. + * @memberof google.spanner.admin.database.v1 + * @interface IEncryptionConfig + * @property {string|null} [kmsKeyName] EncryptionConfig kmsKeyName + * @property {Array.|null} [kmsKeyNames] EncryptionConfig kmsKeyNames + */ + + /** + * Constructs a new EncryptionConfig. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an EncryptionConfig. + * @implements IEncryptionConfig + * @constructor + * @param {google.spanner.admin.database.v1.IEncryptionConfig=} [properties] Properties to set + */ + function EncryptionConfig(properties) { + this.kmsKeyNames = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EncryptionConfig kmsKeyName. + * @member {string} kmsKeyName + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @instance + */ + EncryptionConfig.prototype.kmsKeyName = ""; + + /** + * EncryptionConfig kmsKeyNames. + * @member {Array.} kmsKeyNames + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @instance + */ + EncryptionConfig.prototype.kmsKeyNames = $util.emptyArray; + + /** + * Creates a new EncryptionConfig instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.IEncryptionConfig=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.EncryptionConfig} EncryptionConfig instance + */ + EncryptionConfig.create = function create(properties) { + return new EncryptionConfig(properties); + }; + + /** + * Encodes the specified EncryptionConfig message. Does not implicitly {@link google.spanner.admin.database.v1.EncryptionConfig.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.IEncryptionConfig} message EncryptionConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EncryptionConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.kmsKeyName != null && Object.hasOwnProperty.call(message, "kmsKeyName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.kmsKeyName); + if (message.kmsKeyNames != null && message.kmsKeyNames.length) + for (var i = 0; i < message.kmsKeyNames.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.kmsKeyNames[i]); + return writer; + }; + + /** + * Encodes the specified EncryptionConfig message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.EncryptionConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.IEncryptionConfig} message EncryptionConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EncryptionConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an EncryptionConfig message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.EncryptionConfig} EncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EncryptionConfig.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.spanner.admin.database.v1.EncryptionConfig(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 2: { + message.kmsKeyName = reader.string(); + break; + } + case 3: { + if (!(message.kmsKeyNames && message.kmsKeyNames.length)) + message.kmsKeyNames = []; + message.kmsKeyNames.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an EncryptionConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.EncryptionConfig} EncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EncryptionConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an EncryptionConfig message. + * @function verify + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EncryptionConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + if (!$util.isString(message.kmsKeyName)) + return "kmsKeyName: string expected"; + if (message.kmsKeyNames != null && message.hasOwnProperty("kmsKeyNames")) { + if (!Array.isArray(message.kmsKeyNames)) + return "kmsKeyNames: array expected"; + for (var i = 0; i < message.kmsKeyNames.length; ++i) + if (!$util.isString(message.kmsKeyNames[i])) + return "kmsKeyNames: string[] expected"; + } + return null; + }; + + /** + * Creates an EncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.EncryptionConfig} EncryptionConfig + */ + EncryptionConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.EncryptionConfig) + return object; + var message = new $root.google.spanner.admin.database.v1.EncryptionConfig(); + if (object.kmsKeyName != null) + message.kmsKeyName = String(object.kmsKeyName); + if (object.kmsKeyNames) { + if (!Array.isArray(object.kmsKeyNames)) + throw TypeError(".google.spanner.admin.database.v1.EncryptionConfig.kmsKeyNames: array expected"); + message.kmsKeyNames = []; + for (var i = 0; i < object.kmsKeyNames.length; ++i) + message.kmsKeyNames[i] = String(object.kmsKeyNames[i]); + } + return message; + }; + + /** + * Creates a plain object from an EncryptionConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.EncryptionConfig} message EncryptionConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EncryptionConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.kmsKeyNames = []; + if (options.defaults) + object.kmsKeyName = ""; + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + object.kmsKeyName = message.kmsKeyName; + if (message.kmsKeyNames && message.kmsKeyNames.length) { + object.kmsKeyNames = []; + for (var j = 0; j < message.kmsKeyNames.length; ++j) + object.kmsKeyNames[j] = message.kmsKeyNames[j]; + } + return object; + }; + + /** + * Converts this EncryptionConfig to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @instance + * @returns {Object.} JSON object + */ + EncryptionConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EncryptionConfig + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.EncryptionConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EncryptionConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.EncryptionConfig"; + }; + + return EncryptionConfig; + })(); + + v1.EncryptionInfo = (function() { + + /** + * Properties of an EncryptionInfo. + * @memberof google.spanner.admin.database.v1 + * @interface IEncryptionInfo + * @property {google.spanner.admin.database.v1.EncryptionInfo.Type|null} [encryptionType] EncryptionInfo encryptionType + * @property {google.rpc.IStatus|null} [encryptionStatus] EncryptionInfo encryptionStatus + * @property {string|null} [kmsKeyVersion] EncryptionInfo kmsKeyVersion + */ + + /** + * Constructs a new EncryptionInfo. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an EncryptionInfo. + * @implements IEncryptionInfo + * @constructor + * @param {google.spanner.admin.database.v1.IEncryptionInfo=} [properties] Properties to set + */ + function EncryptionInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EncryptionInfo encryptionType. + * @member {google.spanner.admin.database.v1.EncryptionInfo.Type} encryptionType + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @instance + */ + EncryptionInfo.prototype.encryptionType = 0; + + /** + * EncryptionInfo encryptionStatus. + * @member {google.rpc.IStatus|null|undefined} encryptionStatus + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @instance + */ + EncryptionInfo.prototype.encryptionStatus = null; + + /** + * EncryptionInfo kmsKeyVersion. + * @member {string} kmsKeyVersion + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @instance + */ + EncryptionInfo.prototype.kmsKeyVersion = ""; + + /** + * Creates a new EncryptionInfo instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {google.spanner.admin.database.v1.IEncryptionInfo=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.EncryptionInfo} EncryptionInfo instance + */ + EncryptionInfo.create = function create(properties) { + return new EncryptionInfo(properties); + }; + + /** + * Encodes the specified EncryptionInfo message. Does not implicitly {@link google.spanner.admin.database.v1.EncryptionInfo.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {google.spanner.admin.database.v1.IEncryptionInfo} message EncryptionInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EncryptionInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.kmsKeyVersion != null && Object.hasOwnProperty.call(message, "kmsKeyVersion")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.kmsKeyVersion); + if (message.encryptionType != null && Object.hasOwnProperty.call(message, "encryptionType")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.encryptionType); + if (message.encryptionStatus != null && Object.hasOwnProperty.call(message, "encryptionStatus")) + $root.google.rpc.Status.encode(message.encryptionStatus, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified EncryptionInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.EncryptionInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {google.spanner.admin.database.v1.IEncryptionInfo} message EncryptionInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + EncryptionInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an EncryptionInfo message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.EncryptionInfo} EncryptionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EncryptionInfo.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.spanner.admin.database.v1.EncryptionInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3: { + message.encryptionType = reader.int32(); + break; + } + case 4: { + message.encryptionStatus = $root.google.rpc.Status.decode(reader, reader.uint32()); + break; + } + case 2: { + message.kmsKeyVersion = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an EncryptionInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.EncryptionInfo} EncryptionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + EncryptionInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an EncryptionInfo message. + * @function verify + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + EncryptionInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.encryptionType != null && message.hasOwnProperty("encryptionType")) + switch (message.encryptionType) { + default: + return "encryptionType: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.encryptionStatus != null && message.hasOwnProperty("encryptionStatus")) { + var error = $root.google.rpc.Status.verify(message.encryptionStatus); + if (error) + return "encryptionStatus." + error; + } + if (message.kmsKeyVersion != null && message.hasOwnProperty("kmsKeyVersion")) + if (!$util.isString(message.kmsKeyVersion)) + return "kmsKeyVersion: string expected"; + return null; + }; + + /** + * Creates an EncryptionInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.EncryptionInfo} EncryptionInfo + */ + EncryptionInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.EncryptionInfo) + return object; + var message = new $root.google.spanner.admin.database.v1.EncryptionInfo(); + switch (object.encryptionType) { + default: + if (typeof object.encryptionType === "number") { + message.encryptionType = object.encryptionType; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.encryptionType = 0; + break; + case "GOOGLE_DEFAULT_ENCRYPTION": + case 1: + message.encryptionType = 1; + break; + case "CUSTOMER_MANAGED_ENCRYPTION": + case 2: + message.encryptionType = 2; + break; + } + if (object.encryptionStatus != null) { + if (typeof object.encryptionStatus !== "object") + throw TypeError(".google.spanner.admin.database.v1.EncryptionInfo.encryptionStatus: object expected"); + message.encryptionStatus = $root.google.rpc.Status.fromObject(object.encryptionStatus); + } + if (object.kmsKeyVersion != null) + message.kmsKeyVersion = String(object.kmsKeyVersion); + return message; + }; + + /** + * Creates a plain object from an EncryptionInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {google.spanner.admin.database.v1.EncryptionInfo} message EncryptionInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EncryptionInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.kmsKeyVersion = ""; + object.encryptionType = options.enums === String ? "TYPE_UNSPECIFIED" : 0; + object.encryptionStatus = null; + } + if (message.kmsKeyVersion != null && message.hasOwnProperty("kmsKeyVersion")) + object.kmsKeyVersion = message.kmsKeyVersion; + if (message.encryptionType != null && message.hasOwnProperty("encryptionType")) + object.encryptionType = options.enums === String ? $root.google.spanner.admin.database.v1.EncryptionInfo.Type[message.encryptionType] === undefined ? message.encryptionType : $root.google.spanner.admin.database.v1.EncryptionInfo.Type[message.encryptionType] : message.encryptionType; + if (message.encryptionStatus != null && message.hasOwnProperty("encryptionStatus")) + object.encryptionStatus = $root.google.rpc.Status.toObject(message.encryptionStatus, options); + return object; + }; + + /** + * Converts this EncryptionInfo to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @instance + * @returns {Object.} JSON object + */ + EncryptionInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EncryptionInfo + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.EncryptionInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EncryptionInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.EncryptionInfo"; + }; + + /** + * Type enum. + * @name google.spanner.admin.database.v1.EncryptionInfo.Type + * @enum {number} + * @property {number} TYPE_UNSPECIFIED=0 TYPE_UNSPECIFIED value + * @property {number} GOOGLE_DEFAULT_ENCRYPTION=1 GOOGLE_DEFAULT_ENCRYPTION value + * @property {number} CUSTOMER_MANAGED_ENCRYPTION=2 CUSTOMER_MANAGED_ENCRYPTION value + */ + EncryptionInfo.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "GOOGLE_DEFAULT_ENCRYPTION"] = 1; + values[valuesById[2] = "CUSTOMER_MANAGED_ENCRYPTION"] = 2; + return values; + })(); + + return EncryptionInfo; + })(); + + /** + * DatabaseDialect enum. + * @name google.spanner.admin.database.v1.DatabaseDialect + * @enum {number} + * @property {number} DATABASE_DIALECT_UNSPECIFIED=0 DATABASE_DIALECT_UNSPECIFIED value + * @property {number} GOOGLE_STANDARD_SQL=1 GOOGLE_STANDARD_SQL value + * @property {number} POSTGRESQL=2 POSTGRESQL value + */ + v1.DatabaseDialect = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DATABASE_DIALECT_UNSPECIFIED"] = 0; + values[valuesById[1] = "GOOGLE_STANDARD_SQL"] = 1; + values[valuesById[2] = "POSTGRESQL"] = 2; + return values; + })(); + + v1.BackupScheduleSpec = (function() { + + /** + * Properties of a BackupScheduleSpec. + * @memberof google.spanner.admin.database.v1 + * @interface IBackupScheduleSpec + * @property {google.spanner.admin.database.v1.ICrontabSpec|null} [cronSpec] BackupScheduleSpec cronSpec + */ + + /** + * Constructs a new BackupScheduleSpec. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a BackupScheduleSpec. + * @implements IBackupScheduleSpec + * @constructor + * @param {google.spanner.admin.database.v1.IBackupScheduleSpec=} [properties] Properties to set + */ + function BackupScheduleSpec(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BackupScheduleSpec cronSpec. + * @member {google.spanner.admin.database.v1.ICrontabSpec|null|undefined} cronSpec + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @instance + */ + BackupScheduleSpec.prototype.cronSpec = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BackupScheduleSpec scheduleSpec. + * @member {"cronSpec"|undefined} scheduleSpec + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @instance + */ + Object.defineProperty(BackupScheduleSpec.prototype, "scheduleSpec", { + get: $util.oneOfGetter($oneOfFields = ["cronSpec"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new BackupScheduleSpec instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {google.spanner.admin.database.v1.IBackupScheduleSpec=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.BackupScheduleSpec} BackupScheduleSpec instance + */ + BackupScheduleSpec.create = function create(properties) { + return new BackupScheduleSpec(properties); + }; + + /** + * Encodes the specified BackupScheduleSpec message. Does not implicitly {@link google.spanner.admin.database.v1.BackupScheduleSpec.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {google.spanner.admin.database.v1.IBackupScheduleSpec} message BackupScheduleSpec message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackupScheduleSpec.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.cronSpec != null && Object.hasOwnProperty.call(message, "cronSpec")) + $root.google.spanner.admin.database.v1.CrontabSpec.encode(message.cronSpec, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BackupScheduleSpec message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupScheduleSpec.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {google.spanner.admin.database.v1.IBackupScheduleSpec} message BackupScheduleSpec message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackupScheduleSpec.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BackupScheduleSpec message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.BackupScheduleSpec} BackupScheduleSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackupScheduleSpec.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.spanner.admin.database.v1.BackupScheduleSpec(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.cronSpec = $root.google.spanner.admin.database.v1.CrontabSpec.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BackupScheduleSpec message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.BackupScheduleSpec} BackupScheduleSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackupScheduleSpec.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BackupScheduleSpec message. + * @function verify + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BackupScheduleSpec.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.cronSpec != null && message.hasOwnProperty("cronSpec")) { + properties.scheduleSpec = 1; + { + var error = $root.google.spanner.admin.database.v1.CrontabSpec.verify(message.cronSpec); + if (error) + return "cronSpec." + error; + } + } + return null; + }; + + /** + * Creates a BackupScheduleSpec message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.BackupScheduleSpec} BackupScheduleSpec + */ + BackupScheduleSpec.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.BackupScheduleSpec) + return object; + var message = new $root.google.spanner.admin.database.v1.BackupScheduleSpec(); + if (object.cronSpec != null) { + if (typeof object.cronSpec !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupScheduleSpec.cronSpec: object expected"); + message.cronSpec = $root.google.spanner.admin.database.v1.CrontabSpec.fromObject(object.cronSpec); + } + return message; + }; + + /** + * Creates a plain object from a BackupScheduleSpec message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {google.spanner.admin.database.v1.BackupScheduleSpec} message BackupScheduleSpec + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BackupScheduleSpec.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.cronSpec != null && message.hasOwnProperty("cronSpec")) { + object.cronSpec = $root.google.spanner.admin.database.v1.CrontabSpec.toObject(message.cronSpec, options); + if (options.oneofs) + object.scheduleSpec = "cronSpec"; + } + return object; + }; + + /** + * Converts this BackupScheduleSpec to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @instance + * @returns {Object.} JSON object + */ + BackupScheduleSpec.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BackupScheduleSpec + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.BackupScheduleSpec + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BackupScheduleSpec.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.BackupScheduleSpec"; + }; + + return BackupScheduleSpec; + })(); + + v1.BackupSchedule = (function() { + + /** + * Properties of a BackupSchedule. + * @memberof google.spanner.admin.database.v1 + * @interface IBackupSchedule + * @property {string|null} [name] BackupSchedule name + * @property {google.spanner.admin.database.v1.IBackupScheduleSpec|null} [spec] BackupSchedule spec + * @property {google.protobuf.IDuration|null} [retentionDuration] BackupSchedule retentionDuration + * @property {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig|null} [encryptionConfig] BackupSchedule encryptionConfig + * @property {google.spanner.admin.database.v1.IFullBackupSpec|null} [fullBackupSpec] BackupSchedule fullBackupSpec + * @property {google.spanner.admin.database.v1.IIncrementalBackupSpec|null} [incrementalBackupSpec] BackupSchedule incrementalBackupSpec + * @property {google.protobuf.ITimestamp|null} [updateTime] BackupSchedule updateTime + */ + + /** + * Constructs a new BackupSchedule. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a BackupSchedule. + * @implements IBackupSchedule + * @constructor + * @param {google.spanner.admin.database.v1.IBackupSchedule=} [properties] Properties to set + */ + function BackupSchedule(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BackupSchedule name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.name = ""; + + /** + * BackupSchedule spec. + * @member {google.spanner.admin.database.v1.IBackupScheduleSpec|null|undefined} spec + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.spec = null; + + /** + * BackupSchedule retentionDuration. + * @member {google.protobuf.IDuration|null|undefined} retentionDuration + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.retentionDuration = null; + + /** + * BackupSchedule encryptionConfig. + * @member {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.encryptionConfig = null; + + /** + * BackupSchedule fullBackupSpec. + * @member {google.spanner.admin.database.v1.IFullBackupSpec|null|undefined} fullBackupSpec + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.fullBackupSpec = null; + + /** + * BackupSchedule incrementalBackupSpec. + * @member {google.spanner.admin.database.v1.IIncrementalBackupSpec|null|undefined} incrementalBackupSpec + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.incrementalBackupSpec = null; + + /** + * BackupSchedule updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + */ + BackupSchedule.prototype.updateTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * BackupSchedule backupTypeSpec. + * @member {"fullBackupSpec"|"incrementalBackupSpec"|undefined} backupTypeSpec + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + */ + Object.defineProperty(BackupSchedule.prototype, "backupTypeSpec", { + get: $util.oneOfGetter($oneOfFields = ["fullBackupSpec", "incrementalBackupSpec"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new BackupSchedule instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {google.spanner.admin.database.v1.IBackupSchedule=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.BackupSchedule} BackupSchedule instance + */ + BackupSchedule.create = function create(properties) { + return new BackupSchedule(properties); + }; + + /** + * Encodes the specified BackupSchedule message. Does not implicitly {@link google.spanner.admin.database.v1.BackupSchedule.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {google.spanner.admin.database.v1.IBackupSchedule} message BackupSchedule message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackupSchedule.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.retentionDuration != null && Object.hasOwnProperty.call(message, "retentionDuration")) + $root.google.protobuf.Duration.encode(message.retentionDuration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.spec != null && Object.hasOwnProperty.call(message, "spec")) + $root.google.spanner.admin.database.v1.BackupScheduleSpec.encode(message.spec, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.fullBackupSpec != null && Object.hasOwnProperty.call(message, "fullBackupSpec")) + $root.google.spanner.admin.database.v1.FullBackupSpec.encode(message.fullBackupSpec, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.incrementalBackupSpec != null && Object.hasOwnProperty.call(message, "incrementalBackupSpec")) + $root.google.spanner.admin.database.v1.IncrementalBackupSpec.encode(message.incrementalBackupSpec, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.updateTime != null && Object.hasOwnProperty.call(message, "updateTime")) + $root.google.protobuf.Timestamp.encode(message.updateTime, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BackupSchedule message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupSchedule.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {google.spanner.admin.database.v1.IBackupSchedule} message BackupSchedule message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackupSchedule.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BackupSchedule message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.BackupSchedule} BackupSchedule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackupSchedule.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.spanner.admin.database.v1.BackupSchedule(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 6: { + message.spec = $root.google.spanner.admin.database.v1.BackupScheduleSpec.decode(reader, reader.uint32()); + break; + } + case 3: { + message.retentionDuration = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + case 4: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.decode(reader, reader.uint32()); + break; + } + case 7: { + message.fullBackupSpec = $root.google.spanner.admin.database.v1.FullBackupSpec.decode(reader, reader.uint32()); + break; + } + case 8: { + message.incrementalBackupSpec = $root.google.spanner.admin.database.v1.IncrementalBackupSpec.decode(reader, reader.uint32()); + break; + } + case 9: { + message.updateTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BackupSchedule message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.BackupSchedule} BackupSchedule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackupSchedule.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BackupSchedule message. + * @function verify + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BackupSchedule.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.spec != null && message.hasOwnProperty("spec")) { + var error = $root.google.spanner.admin.database.v1.BackupScheduleSpec.verify(message.spec); + if (error) + return "spec." + error; + } + if (message.retentionDuration != null && message.hasOwnProperty("retentionDuration")) { + var error = $root.google.protobuf.Duration.verify(message.retentionDuration); + if (error) + return "retentionDuration." + error; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + if (message.fullBackupSpec != null && message.hasOwnProperty("fullBackupSpec")) { + properties.backupTypeSpec = 1; + { + var error = $root.google.spanner.admin.database.v1.FullBackupSpec.verify(message.fullBackupSpec); + if (error) + return "fullBackupSpec." + error; + } + } + if (message.incrementalBackupSpec != null && message.hasOwnProperty("incrementalBackupSpec")) { + if (properties.backupTypeSpec === 1) + return "backupTypeSpec: multiple values"; + properties.backupTypeSpec = 1; + { + var error = $root.google.spanner.admin.database.v1.IncrementalBackupSpec.verify(message.incrementalBackupSpec); + if (error) + return "incrementalBackupSpec." + error; + } + } + if (message.updateTime != null && message.hasOwnProperty("updateTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.updateTime); + if (error) + return "updateTime." + error; + } + return null; + }; + + /** + * Creates a BackupSchedule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.BackupSchedule} BackupSchedule + */ + BackupSchedule.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.BackupSchedule) + return object; + var message = new $root.google.spanner.admin.database.v1.BackupSchedule(); + if (object.name != null) + message.name = String(object.name); + if (object.spec != null) { + if (typeof object.spec !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupSchedule.spec: object expected"); + message.spec = $root.google.spanner.admin.database.v1.BackupScheduleSpec.fromObject(object.spec); + } + if (object.retentionDuration != null) { + if (typeof object.retentionDuration !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupSchedule.retentionDuration: object expected"); + message.retentionDuration = $root.google.protobuf.Duration.fromObject(object.retentionDuration); + } + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupSchedule.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.fromObject(object.encryptionConfig); + } + if (object.fullBackupSpec != null) { + if (typeof object.fullBackupSpec !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupSchedule.fullBackupSpec: object expected"); + message.fullBackupSpec = $root.google.spanner.admin.database.v1.FullBackupSpec.fromObject(object.fullBackupSpec); + } + if (object.incrementalBackupSpec != null) { + if (typeof object.incrementalBackupSpec !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupSchedule.incrementalBackupSpec: object expected"); + message.incrementalBackupSpec = $root.google.spanner.admin.database.v1.IncrementalBackupSpec.fromObject(object.incrementalBackupSpec); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.BackupSchedule.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + return message; + }; + + /** + * Creates a plain object from a BackupSchedule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {google.spanner.admin.database.v1.BackupSchedule} message BackupSchedule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BackupSchedule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.retentionDuration = null; + object.encryptionConfig = null; + object.spec = null; + object.updateTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.retentionDuration != null && message.hasOwnProperty("retentionDuration")) + object.retentionDuration = $root.google.protobuf.Duration.toObject(message.retentionDuration, options); + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.toObject(message.encryptionConfig, options); + if (message.spec != null && message.hasOwnProperty("spec")) + object.spec = $root.google.spanner.admin.database.v1.BackupScheduleSpec.toObject(message.spec, options); + if (message.fullBackupSpec != null && message.hasOwnProperty("fullBackupSpec")) { + object.fullBackupSpec = $root.google.spanner.admin.database.v1.FullBackupSpec.toObject(message.fullBackupSpec, options); + if (options.oneofs) + object.backupTypeSpec = "fullBackupSpec"; + } + if (message.incrementalBackupSpec != null && message.hasOwnProperty("incrementalBackupSpec")) { + object.incrementalBackupSpec = $root.google.spanner.admin.database.v1.IncrementalBackupSpec.toObject(message.incrementalBackupSpec, options); + if (options.oneofs) + object.backupTypeSpec = "incrementalBackupSpec"; + } + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + return object; + }; + + /** + * Converts this BackupSchedule to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @instance + * @returns {Object.} JSON object + */ + BackupSchedule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BackupSchedule + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.BackupSchedule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BackupSchedule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.BackupSchedule"; + }; + + return BackupSchedule; + })(); + + v1.CrontabSpec = (function() { + + /** + * Properties of a CrontabSpec. + * @memberof google.spanner.admin.database.v1 + * @interface ICrontabSpec + * @property {string|null} [text] CrontabSpec text + * @property {string|null} [timeZone] CrontabSpec timeZone + * @property {google.protobuf.IDuration|null} [creationWindow] CrontabSpec creationWindow + */ + + /** + * Constructs a new CrontabSpec. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CrontabSpec. + * @implements ICrontabSpec + * @constructor + * @param {google.spanner.admin.database.v1.ICrontabSpec=} [properties] Properties to set + */ + function CrontabSpec(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CrontabSpec text. + * @member {string} text + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @instance + */ + CrontabSpec.prototype.text = ""; + + /** + * CrontabSpec timeZone. + * @member {string} timeZone + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @instance + */ + CrontabSpec.prototype.timeZone = ""; + + /** + * CrontabSpec creationWindow. + * @member {google.protobuf.IDuration|null|undefined} creationWindow + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @instance + */ + CrontabSpec.prototype.creationWindow = null; + + /** + * Creates a new CrontabSpec instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {google.spanner.admin.database.v1.ICrontabSpec=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CrontabSpec} CrontabSpec instance + */ + CrontabSpec.create = function create(properties) { + return new CrontabSpec(properties); + }; + + /** + * Encodes the specified CrontabSpec message. Does not implicitly {@link google.spanner.admin.database.v1.CrontabSpec.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {google.spanner.admin.database.v1.ICrontabSpec} message CrontabSpec message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CrontabSpec.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.text != null && Object.hasOwnProperty.call(message, "text")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.text); + if (message.timeZone != null && Object.hasOwnProperty.call(message, "timeZone")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.timeZone); + if (message.creationWindow != null && Object.hasOwnProperty.call(message, "creationWindow")) + $root.google.protobuf.Duration.encode(message.creationWindow, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CrontabSpec message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CrontabSpec.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {google.spanner.admin.database.v1.ICrontabSpec} message CrontabSpec message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CrontabSpec.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CrontabSpec message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CrontabSpec} CrontabSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CrontabSpec.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.spanner.admin.database.v1.CrontabSpec(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.text = reader.string(); + break; + } + case 2: { + message.timeZone = reader.string(); + break; + } + case 3: { + message.creationWindow = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CrontabSpec message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CrontabSpec} CrontabSpec + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CrontabSpec.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CrontabSpec message. + * @function verify + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CrontabSpec.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.text != null && message.hasOwnProperty("text")) + if (!$util.isString(message.text)) + return "text: string expected"; + if (message.timeZone != null && message.hasOwnProperty("timeZone")) + if (!$util.isString(message.timeZone)) + return "timeZone: string expected"; + if (message.creationWindow != null && message.hasOwnProperty("creationWindow")) { + var error = $root.google.protobuf.Duration.verify(message.creationWindow); + if (error) + return "creationWindow." + error; + } + return null; + }; + + /** + * Creates a CrontabSpec message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CrontabSpec} CrontabSpec + */ + CrontabSpec.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CrontabSpec) + return object; + var message = new $root.google.spanner.admin.database.v1.CrontabSpec(); + if (object.text != null) + message.text = String(object.text); + if (object.timeZone != null) + message.timeZone = String(object.timeZone); + if (object.creationWindow != null) { + if (typeof object.creationWindow !== "object") + throw TypeError(".google.spanner.admin.database.v1.CrontabSpec.creationWindow: object expected"); + message.creationWindow = $root.google.protobuf.Duration.fromObject(object.creationWindow); + } + return message; + }; + + /** + * Creates a plain object from a CrontabSpec message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {google.spanner.admin.database.v1.CrontabSpec} message CrontabSpec + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CrontabSpec.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.text = ""; + object.timeZone = ""; + object.creationWindow = null; + } + if (message.text != null && message.hasOwnProperty("text")) + object.text = message.text; + if (message.timeZone != null && message.hasOwnProperty("timeZone")) + object.timeZone = message.timeZone; + if (message.creationWindow != null && message.hasOwnProperty("creationWindow")) + object.creationWindow = $root.google.protobuf.Duration.toObject(message.creationWindow, options); + return object; + }; + + /** + * Converts this CrontabSpec to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @instance + * @returns {Object.} JSON object + */ + CrontabSpec.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CrontabSpec + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CrontabSpec + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CrontabSpec.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CrontabSpec"; + }; + + return CrontabSpec; + })(); + + v1.CreateBackupScheduleRequest = (function() { + + /** + * Properties of a CreateBackupScheduleRequest. + * @memberof google.spanner.admin.database.v1 + * @interface ICreateBackupScheduleRequest + * @property {string|null} [parent] CreateBackupScheduleRequest parent + * @property {string|null} [backupScheduleId] CreateBackupScheduleRequest backupScheduleId + * @property {google.spanner.admin.database.v1.IBackupSchedule|null} [backupSchedule] CreateBackupScheduleRequest backupSchedule + */ + + /** + * Constructs a new CreateBackupScheduleRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CreateBackupScheduleRequest. + * @implements ICreateBackupScheduleRequest + * @constructor + * @param {google.spanner.admin.database.v1.ICreateBackupScheduleRequest=} [properties] Properties to set + */ + function CreateBackupScheduleRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateBackupScheduleRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @instance + */ + CreateBackupScheduleRequest.prototype.parent = ""; + + /** + * CreateBackupScheduleRequest backupScheduleId. + * @member {string} backupScheduleId + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @instance + */ + CreateBackupScheduleRequest.prototype.backupScheduleId = ""; + + /** + * CreateBackupScheduleRequest backupSchedule. + * @member {google.spanner.admin.database.v1.IBackupSchedule|null|undefined} backupSchedule + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @instance + */ + CreateBackupScheduleRequest.prototype.backupSchedule = null; + + /** + * Creates a new CreateBackupScheduleRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupScheduleRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CreateBackupScheduleRequest} CreateBackupScheduleRequest instance + */ + CreateBackupScheduleRequest.create = function create(properties) { + return new CreateBackupScheduleRequest(properties); + }; + + /** + * Encodes the specified CreateBackupScheduleRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupScheduleRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupScheduleRequest} message CreateBackupScheduleRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateBackupScheduleRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.backupScheduleId != null && Object.hasOwnProperty.call(message, "backupScheduleId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.backupScheduleId); + if (message.backupSchedule != null && Object.hasOwnProperty.call(message, "backupSchedule")) + $root.google.spanner.admin.database.v1.BackupSchedule.encode(message.backupSchedule, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateBackupScheduleRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupScheduleRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateBackupScheduleRequest} message CreateBackupScheduleRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateBackupScheduleRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateBackupScheduleRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CreateBackupScheduleRequest} CreateBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateBackupScheduleRequest.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.spanner.admin.database.v1.CreateBackupScheduleRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.backupScheduleId = reader.string(); + break; + } + case 3: { + message.backupSchedule = $root.google.spanner.admin.database.v1.BackupSchedule.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateBackupScheduleRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CreateBackupScheduleRequest} CreateBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateBackupScheduleRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateBackupScheduleRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateBackupScheduleRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.backupScheduleId != null && message.hasOwnProperty("backupScheduleId")) + if (!$util.isString(message.backupScheduleId)) + return "backupScheduleId: string expected"; + if (message.backupSchedule != null && message.hasOwnProperty("backupSchedule")) { + var error = $root.google.spanner.admin.database.v1.BackupSchedule.verify(message.backupSchedule); + if (error) + return "backupSchedule." + error; + } + return null; + }; + + /** + * Creates a CreateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CreateBackupScheduleRequest} CreateBackupScheduleRequest + */ + CreateBackupScheduleRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CreateBackupScheduleRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.CreateBackupScheduleRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.backupScheduleId != null) + message.backupScheduleId = String(object.backupScheduleId); + if (object.backupSchedule != null) { + if (typeof object.backupSchedule !== "object") + throw TypeError(".google.spanner.admin.database.v1.CreateBackupScheduleRequest.backupSchedule: object expected"); + message.backupSchedule = $root.google.spanner.admin.database.v1.BackupSchedule.fromObject(object.backupSchedule); + } + return message; + }; + + /** + * Creates a plain object from a CreateBackupScheduleRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.CreateBackupScheduleRequest} message CreateBackupScheduleRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateBackupScheduleRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.backupScheduleId = ""; + object.backupSchedule = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.backupScheduleId != null && message.hasOwnProperty("backupScheduleId")) + object.backupScheduleId = message.backupScheduleId; + if (message.backupSchedule != null && message.hasOwnProperty("backupSchedule")) + object.backupSchedule = $root.google.spanner.admin.database.v1.BackupSchedule.toObject(message.backupSchedule, options); + return object; + }; + + /** + * Converts this CreateBackupScheduleRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @instance + * @returns {Object.} JSON object + */ + CreateBackupScheduleRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateBackupScheduleRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CreateBackupScheduleRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateBackupScheduleRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CreateBackupScheduleRequest"; + }; + + return CreateBackupScheduleRequest; + })(); + + v1.GetBackupScheduleRequest = (function() { + + /** + * Properties of a GetBackupScheduleRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IGetBackupScheduleRequest + * @property {string|null} [name] GetBackupScheduleRequest name + */ + + /** + * Constructs a new GetBackupScheduleRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a GetBackupScheduleRequest. + * @implements IGetBackupScheduleRequest + * @constructor + * @param {google.spanner.admin.database.v1.IGetBackupScheduleRequest=} [properties] Properties to set + */ + function GetBackupScheduleRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetBackupScheduleRequest name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @instance + */ + GetBackupScheduleRequest.prototype.name = ""; + + /** + * Creates a new GetBackupScheduleRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IGetBackupScheduleRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.GetBackupScheduleRequest} GetBackupScheduleRequest instance + */ + GetBackupScheduleRequest.create = function create(properties) { + return new GetBackupScheduleRequest(properties); + }; + + /** + * Encodes the specified GetBackupScheduleRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupScheduleRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IGetBackupScheduleRequest} message GetBackupScheduleRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetBackupScheduleRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetBackupScheduleRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupScheduleRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IGetBackupScheduleRequest} message GetBackupScheduleRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetBackupScheduleRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetBackupScheduleRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.GetBackupScheduleRequest} GetBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetBackupScheduleRequest.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.spanner.admin.database.v1.GetBackupScheduleRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetBackupScheduleRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.GetBackupScheduleRequest} GetBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetBackupScheduleRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetBackupScheduleRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetBackupScheduleRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.GetBackupScheduleRequest} GetBackupScheduleRequest + */ + GetBackupScheduleRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.GetBackupScheduleRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.GetBackupScheduleRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetBackupScheduleRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.GetBackupScheduleRequest} message GetBackupScheduleRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetBackupScheduleRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetBackupScheduleRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @instance + * @returns {Object.} JSON object + */ + GetBackupScheduleRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetBackupScheduleRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.GetBackupScheduleRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetBackupScheduleRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.GetBackupScheduleRequest"; + }; + + return GetBackupScheduleRequest; + })(); + + v1.DeleteBackupScheduleRequest = (function() { + + /** + * Properties of a DeleteBackupScheduleRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IDeleteBackupScheduleRequest + * @property {string|null} [name] DeleteBackupScheduleRequest name + */ + + /** + * Constructs a new DeleteBackupScheduleRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a DeleteBackupScheduleRequest. + * @implements IDeleteBackupScheduleRequest + * @constructor + * @param {google.spanner.admin.database.v1.IDeleteBackupScheduleRequest=} [properties] Properties to set + */ + function DeleteBackupScheduleRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteBackupScheduleRequest name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @instance + */ + DeleteBackupScheduleRequest.prototype.name = ""; + + /** + * Creates a new DeleteBackupScheduleRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IDeleteBackupScheduleRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.DeleteBackupScheduleRequest} DeleteBackupScheduleRequest instance + */ + DeleteBackupScheduleRequest.create = function create(properties) { + return new DeleteBackupScheduleRequest(properties); + }; + + /** + * Encodes the specified DeleteBackupScheduleRequest message. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupScheduleRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IDeleteBackupScheduleRequest} message DeleteBackupScheduleRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteBackupScheduleRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified DeleteBackupScheduleRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupScheduleRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IDeleteBackupScheduleRequest} message DeleteBackupScheduleRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteBackupScheduleRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteBackupScheduleRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.DeleteBackupScheduleRequest} DeleteBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteBackupScheduleRequest.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.spanner.admin.database.v1.DeleteBackupScheduleRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteBackupScheduleRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.DeleteBackupScheduleRequest} DeleteBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteBackupScheduleRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteBackupScheduleRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteBackupScheduleRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a DeleteBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.DeleteBackupScheduleRequest} DeleteBackupScheduleRequest + */ + DeleteBackupScheduleRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.DeleteBackupScheduleRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.DeleteBackupScheduleRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteBackupScheduleRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.DeleteBackupScheduleRequest} message DeleteBackupScheduleRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteBackupScheduleRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteBackupScheduleRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteBackupScheduleRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteBackupScheduleRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.DeleteBackupScheduleRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteBackupScheduleRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.DeleteBackupScheduleRequest"; + }; + + return DeleteBackupScheduleRequest; + })(); + + v1.ListBackupSchedulesRequest = (function() { + + /** + * Properties of a ListBackupSchedulesRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IListBackupSchedulesRequest + * @property {string|null} [parent] ListBackupSchedulesRequest parent + * @property {number|null} [pageSize] ListBackupSchedulesRequest pageSize + * @property {string|null} [pageToken] ListBackupSchedulesRequest pageToken + */ + + /** + * Constructs a new ListBackupSchedulesRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListBackupSchedulesRequest. + * @implements IListBackupSchedulesRequest + * @constructor + * @param {google.spanner.admin.database.v1.IListBackupSchedulesRequest=} [properties] Properties to set + */ + function ListBackupSchedulesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupSchedulesRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @instance + */ + ListBackupSchedulesRequest.prototype.parent = ""; + + /** + * ListBackupSchedulesRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @instance + */ + ListBackupSchedulesRequest.prototype.pageSize = 0; + + /** + * ListBackupSchedulesRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @instance + */ + ListBackupSchedulesRequest.prototype.pageToken = ""; + + /** + * Creates a new ListBackupSchedulesRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupSchedulesRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListBackupSchedulesRequest} ListBackupSchedulesRequest instance + */ + ListBackupSchedulesRequest.create = function create(properties) { + return new ListBackupSchedulesRequest(properties); + }; + + /** + * Encodes the specified ListBackupSchedulesRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupSchedulesRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupSchedulesRequest} message ListBackupSchedulesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupSchedulesRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListBackupSchedulesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupSchedulesRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {google.spanner.admin.database.v1.IListBackupSchedulesRequest} message ListBackupSchedulesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupSchedulesRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListBackupSchedulesRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListBackupSchedulesRequest} ListBackupSchedulesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupSchedulesRequest.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.spanner.admin.database.v1.ListBackupSchedulesRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListBackupSchedulesRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListBackupSchedulesRequest} ListBackupSchedulesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupSchedulesRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListBackupSchedulesRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListBackupSchedulesRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListBackupSchedulesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListBackupSchedulesRequest} ListBackupSchedulesRequest + */ + ListBackupSchedulesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListBackupSchedulesRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.ListBackupSchedulesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListBackupSchedulesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {google.spanner.admin.database.v1.ListBackupSchedulesRequest} message ListBackupSchedulesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupSchedulesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListBackupSchedulesRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @instance + * @returns {Object.} JSON object + */ + ListBackupSchedulesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupSchedulesRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupSchedulesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListBackupSchedulesRequest"; + }; + + return ListBackupSchedulesRequest; + })(); + + v1.ListBackupSchedulesResponse = (function() { + + /** + * Properties of a ListBackupSchedulesResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IListBackupSchedulesResponse + * @property {Array.|null} [backupSchedules] ListBackupSchedulesResponse backupSchedules + * @property {string|null} [nextPageToken] ListBackupSchedulesResponse nextPageToken + */ + + /** + * Constructs a new ListBackupSchedulesResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListBackupSchedulesResponse. + * @implements IListBackupSchedulesResponse + * @constructor + * @param {google.spanner.admin.database.v1.IListBackupSchedulesResponse=} [properties] Properties to set + */ + function ListBackupSchedulesResponse(properties) { + this.backupSchedules = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListBackupSchedulesResponse backupSchedules. + * @member {Array.} backupSchedules + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @instance + */ + ListBackupSchedulesResponse.prototype.backupSchedules = $util.emptyArray; + + /** + * ListBackupSchedulesResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @instance + */ + ListBackupSchedulesResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListBackupSchedulesResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupSchedulesResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListBackupSchedulesResponse} ListBackupSchedulesResponse instance + */ + ListBackupSchedulesResponse.create = function create(properties) { + return new ListBackupSchedulesResponse(properties); + }; + + /** + * Encodes the specified ListBackupSchedulesResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupSchedulesResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupSchedulesResponse} message ListBackupSchedulesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupSchedulesResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.backupSchedules != null && message.backupSchedules.length) + for (var i = 0; i < message.backupSchedules.length; ++i) + $root.google.spanner.admin.database.v1.BackupSchedule.encode(message.backupSchedules[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListBackupSchedulesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupSchedulesResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {google.spanner.admin.database.v1.IListBackupSchedulesResponse} message ListBackupSchedulesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListBackupSchedulesResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListBackupSchedulesResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListBackupSchedulesResponse} ListBackupSchedulesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupSchedulesResponse.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.spanner.admin.database.v1.ListBackupSchedulesResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.backupSchedules && message.backupSchedules.length)) + message.backupSchedules = []; + message.backupSchedules.push($root.google.spanner.admin.database.v1.BackupSchedule.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListBackupSchedulesResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListBackupSchedulesResponse} ListBackupSchedulesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListBackupSchedulesResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListBackupSchedulesResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListBackupSchedulesResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.backupSchedules != null && message.hasOwnProperty("backupSchedules")) { + if (!Array.isArray(message.backupSchedules)) + return "backupSchedules: array expected"; + for (var i = 0; i < message.backupSchedules.length; ++i) { + var error = $root.google.spanner.admin.database.v1.BackupSchedule.verify(message.backupSchedules[i]); + if (error) + return "backupSchedules." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListBackupSchedulesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListBackupSchedulesResponse} ListBackupSchedulesResponse + */ + ListBackupSchedulesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListBackupSchedulesResponse) + return object; + var message = new $root.google.spanner.admin.database.v1.ListBackupSchedulesResponse(); + if (object.backupSchedules) { + if (!Array.isArray(object.backupSchedules)) + throw TypeError(".google.spanner.admin.database.v1.ListBackupSchedulesResponse.backupSchedules: array expected"); + message.backupSchedules = []; + for (var i = 0; i < object.backupSchedules.length; ++i) { + if (typeof object.backupSchedules[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.ListBackupSchedulesResponse.backupSchedules: object expected"); + message.backupSchedules[i] = $root.google.spanner.admin.database.v1.BackupSchedule.fromObject(object.backupSchedules[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListBackupSchedulesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {google.spanner.admin.database.v1.ListBackupSchedulesResponse} message ListBackupSchedulesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListBackupSchedulesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.backupSchedules = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.backupSchedules && message.backupSchedules.length) { + object.backupSchedules = []; + for (var j = 0; j < message.backupSchedules.length; ++j) + object.backupSchedules[j] = $root.google.spanner.admin.database.v1.BackupSchedule.toObject(message.backupSchedules[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListBackupSchedulesResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @instance + * @returns {Object.} JSON object + */ + ListBackupSchedulesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListBackupSchedulesResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListBackupSchedulesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListBackupSchedulesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListBackupSchedulesResponse"; + }; + + return ListBackupSchedulesResponse; + })(); + + v1.UpdateBackupScheduleRequest = (function() { + + /** + * Properties of an UpdateBackupScheduleRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IUpdateBackupScheduleRequest + * @property {google.spanner.admin.database.v1.IBackupSchedule|null} [backupSchedule] UpdateBackupScheduleRequest backupSchedule + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateBackupScheduleRequest updateMask + */ + + /** + * Constructs a new UpdateBackupScheduleRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an UpdateBackupScheduleRequest. + * @implements IUpdateBackupScheduleRequest + * @constructor + * @param {google.spanner.admin.database.v1.IUpdateBackupScheduleRequest=} [properties] Properties to set + */ + function UpdateBackupScheduleRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateBackupScheduleRequest backupSchedule. + * @member {google.spanner.admin.database.v1.IBackupSchedule|null|undefined} backupSchedule + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @instance + */ + UpdateBackupScheduleRequest.prototype.backupSchedule = null; + + /** + * UpdateBackupScheduleRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @instance + */ + UpdateBackupScheduleRequest.prototype.updateMask = null; + + /** + * Creates a new UpdateBackupScheduleRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateBackupScheduleRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.UpdateBackupScheduleRequest} UpdateBackupScheduleRequest instance + */ + UpdateBackupScheduleRequest.create = function create(properties) { + return new UpdateBackupScheduleRequest(properties); + }; + + /** + * Encodes the specified UpdateBackupScheduleRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupScheduleRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateBackupScheduleRequest} message UpdateBackupScheduleRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateBackupScheduleRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.backupSchedule != null && Object.hasOwnProperty.call(message, "backupSchedule")) + $root.google.spanner.admin.database.v1.BackupSchedule.encode(message.backupSchedule, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + $root.google.protobuf.FieldMask.encode(message.updateMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateBackupScheduleRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupScheduleRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateBackupScheduleRequest} message UpdateBackupScheduleRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateBackupScheduleRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateBackupScheduleRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.UpdateBackupScheduleRequest} UpdateBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateBackupScheduleRequest.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.spanner.admin.database.v1.UpdateBackupScheduleRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.backupSchedule = $root.google.spanner.admin.database.v1.BackupSchedule.decode(reader, reader.uint32()); + break; + } + case 2: { + message.updateMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateBackupScheduleRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.UpdateBackupScheduleRequest} UpdateBackupScheduleRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateBackupScheduleRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateBackupScheduleRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateBackupScheduleRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.backupSchedule != null && message.hasOwnProperty("backupSchedule")) { + var error = $root.google.spanner.admin.database.v1.BackupSchedule.verify(message.backupSchedule); + if (error) + return "backupSchedule." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.updateMask); + if (error) + return "updateMask." + error; + } + return null; + }; + + /** + * Creates an UpdateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.UpdateBackupScheduleRequest} UpdateBackupScheduleRequest + */ + UpdateBackupScheduleRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.UpdateBackupScheduleRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.UpdateBackupScheduleRequest(); + if (object.backupSchedule != null) { + if (typeof object.backupSchedule !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateBackupScheduleRequest.backupSchedule: object expected"); + message.backupSchedule = $root.google.spanner.admin.database.v1.BackupSchedule.fromObject(object.backupSchedule); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateBackupScheduleRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateBackupScheduleRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {google.spanner.admin.database.v1.UpdateBackupScheduleRequest} message UpdateBackupScheduleRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateBackupScheduleRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.backupSchedule = null; + object.updateMask = null; + } + if (message.backupSchedule != null && message.hasOwnProperty("backupSchedule")) + object.backupSchedule = $root.google.spanner.admin.database.v1.BackupSchedule.toObject(message.backupSchedule, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this UpdateBackupScheduleRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateBackupScheduleRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateBackupScheduleRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.UpdateBackupScheduleRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateBackupScheduleRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.UpdateBackupScheduleRequest"; + }; + + return UpdateBackupScheduleRequest; + })(); + + v1.DatabaseAdmin = (function() { + + /** + * Constructs a new DatabaseAdmin service. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a DatabaseAdmin + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function DatabaseAdmin(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (DatabaseAdmin.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = DatabaseAdmin; + + /** + * Creates new DatabaseAdmin service using the specified rpc implementation. + * @function create + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {DatabaseAdmin} RPC service. Useful where requests and/or responses are streamed. + */ + DatabaseAdmin.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listDatabases}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef ListDatabasesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.ListDatabasesResponse} [response] ListDatabasesResponse + */ + + /** + * Calls ListDatabases. + * @function listDatabases + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListDatabasesRequest} request ListDatabasesRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.ListDatabasesCallback} callback Node-style callback called with the error, if any, and ListDatabasesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.listDatabases = function listDatabases(request, callback) { + return this.rpcCall(listDatabases, $root.google.spanner.admin.database.v1.ListDatabasesRequest, $root.google.spanner.admin.database.v1.ListDatabasesResponse, request, callback); + }, "name", { value: "ListDatabases" }); + + /** + * Calls ListDatabases. + * @function listDatabases + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListDatabasesRequest} request ListDatabasesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|createDatabase}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef CreateDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CreateDatabase. + * @function createDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.ICreateDatabaseRequest} request CreateDatabaseRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabaseCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.createDatabase = function createDatabase(request, callback) { + return this.rpcCall(createDatabase, $root.google.spanner.admin.database.v1.CreateDatabaseRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CreateDatabase" }); + + /** + * Calls CreateDatabase. + * @function createDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.ICreateDatabaseRequest} request CreateDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getDatabase}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef GetDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.Database} [response] Database + */ + + /** + * Calls GetDatabase. + * @function getDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IGetDatabaseRequest} request GetDatabaseRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseCallback} callback Node-style callback called with the error, if any, and Database + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.getDatabase = function getDatabase(request, callback) { + return this.rpcCall(getDatabase, $root.google.spanner.admin.database.v1.GetDatabaseRequest, $root.google.spanner.admin.database.v1.Database, request, callback); + }, "name", { value: "GetDatabase" }); + + /** + * Calls GetDatabase. + * @function getDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IGetDatabaseRequest} request GetDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|updateDatabase}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef UpdateDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls UpdateDatabase. + * @function updateDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IUpdateDatabaseRequest} request UpdateDatabaseRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.updateDatabase = function updateDatabase(request, callback) { + return this.rpcCall(updateDatabase, $root.google.spanner.admin.database.v1.UpdateDatabaseRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "UpdateDatabase" }); + + /** + * Calls UpdateDatabase. + * @function updateDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IUpdateDatabaseRequest} request UpdateDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|updateDatabaseDdl}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef UpdateDatabaseDdlCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls UpdateDatabaseDdl. + * @function updateDatabaseDdl + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest} request UpdateDatabaseDdlRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdlCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.updateDatabaseDdl = function updateDatabaseDdl(request, callback) { + return this.rpcCall(updateDatabaseDdl, $root.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "UpdateDatabaseDdl" }); + + /** + * Calls UpdateDatabaseDdl. + * @function updateDatabaseDdl + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest} request UpdateDatabaseDdlRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|dropDatabase}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef DropDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DropDatabase. + * @function dropDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IDropDatabaseRequest} request DropDatabaseRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.DropDatabaseCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.dropDatabase = function dropDatabase(request, callback) { + return this.rpcCall(dropDatabase, $root.google.spanner.admin.database.v1.DropDatabaseRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DropDatabase" }); + + /** + * Calls DropDatabase. + * @function dropDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IDropDatabaseRequest} request DropDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getDatabaseDdl}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef GetDatabaseDdlCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.GetDatabaseDdlResponse} [response] GetDatabaseDdlResponse + */ + + /** + * Calls GetDatabaseDdl. + * @function getDatabaseDdl + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlRequest} request GetDatabaseDdlRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdlCallback} callback Node-style callback called with the error, if any, and GetDatabaseDdlResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.getDatabaseDdl = function getDatabaseDdl(request, callback) { + return this.rpcCall(getDatabaseDdl, $root.google.spanner.admin.database.v1.GetDatabaseDdlRequest, $root.google.spanner.admin.database.v1.GetDatabaseDdlResponse, request, callback); + }, "name", { value: "GetDatabaseDdl" }); + + /** + * Calls GetDatabaseDdl. + * @function getDatabaseDdl + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlRequest} request GetDatabaseDdlRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|setIamPolicy}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef SetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.Policy} [response] Policy + */ + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.iam.v1.ISetIamPolicyRequest} request SetIamPolicyRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.SetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.setIamPolicy = function setIamPolicy(request, callback) { + return this.rpcCall(setIamPolicy, $root.google.iam.v1.SetIamPolicyRequest, $root.google.iam.v1.Policy, request, callback); + }, "name", { value: "SetIamPolicy" }); + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.iam.v1.ISetIamPolicyRequest} request SetIamPolicyRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getIamPolicy}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef GetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.Policy} [response] Policy + */ + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.iam.v1.IGetIamPolicyRequest} request GetIamPolicyRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.GetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.getIamPolicy = function getIamPolicy(request, callback) { + return this.rpcCall(getIamPolicy, $root.google.iam.v1.GetIamPolicyRequest, $root.google.iam.v1.Policy, request, callback); + }, "name", { value: "GetIamPolicy" }); + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.iam.v1.IGetIamPolicyRequest} request GetIamPolicyRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|testIamPermissions}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef TestIamPermissionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.TestIamPermissionsResponse} [response] TestIamPermissionsResponse + */ + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.iam.v1.ITestIamPermissionsRequest} request TestIamPermissionsRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.TestIamPermissionsCallback} callback Node-style callback called with the error, if any, and TestIamPermissionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.testIamPermissions = function testIamPermissions(request, callback) { + return this.rpcCall(testIamPermissions, $root.google.iam.v1.TestIamPermissionsRequest, $root.google.iam.v1.TestIamPermissionsResponse, request, callback); + }, "name", { value: "TestIamPermissions" }); + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.iam.v1.ITestIamPermissionsRequest} request TestIamPermissionsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|createBackup}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef CreateBackupCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CreateBackup. + * @function createBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.ICreateBackupRequest} request CreateBackupRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.CreateBackupCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.createBackup = function createBackup(request, callback) { + return this.rpcCall(createBackup, $root.google.spanner.admin.database.v1.CreateBackupRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CreateBackup" }); + + /** + * Calls CreateBackup. + * @function createBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.ICreateBackupRequest} request CreateBackupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|copyBackup}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef CopyBackupCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CopyBackup. + * @function copyBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.ICopyBackupRequest} request CopyBackupRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.CopyBackupCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.copyBackup = function copyBackup(request, callback) { + return this.rpcCall(copyBackup, $root.google.spanner.admin.database.v1.CopyBackupRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CopyBackup" }); + + /** + * Calls CopyBackup. + * @function copyBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.ICopyBackupRequest} request CopyBackupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getBackup}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef GetBackupCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.Backup} [response] Backup + */ + + /** + * Calls GetBackup. + * @function getBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IGetBackupRequest} request GetBackupRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.GetBackupCallback} callback Node-style callback called with the error, if any, and Backup + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.getBackup = function getBackup(request, callback) { + return this.rpcCall(getBackup, $root.google.spanner.admin.database.v1.GetBackupRequest, $root.google.spanner.admin.database.v1.Backup, request, callback); + }, "name", { value: "GetBackup" }); + + /** + * Calls GetBackup. + * @function getBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IGetBackupRequest} request GetBackupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|updateBackup}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef UpdateBackupCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.Backup} [response] Backup + */ + + /** + * Calls UpdateBackup. + * @function updateBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IUpdateBackupRequest} request UpdateBackupRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackupCallback} callback Node-style callback called with the error, if any, and Backup + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.updateBackup = function updateBackup(request, callback) { + return this.rpcCall(updateBackup, $root.google.spanner.admin.database.v1.UpdateBackupRequest, $root.google.spanner.admin.database.v1.Backup, request, callback); + }, "name", { value: "UpdateBackup" }); + + /** + * Calls UpdateBackup. + * @function updateBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IUpdateBackupRequest} request UpdateBackupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|deleteBackup}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef DeleteBackupCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteBackup. + * @function deleteBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IDeleteBackupRequest} request DeleteBackupRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.DeleteBackupCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.deleteBackup = function deleteBackup(request, callback) { + return this.rpcCall(deleteBackup, $root.google.spanner.admin.database.v1.DeleteBackupRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteBackup" }); + + /** + * Calls DeleteBackup. + * @function deleteBackup + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IDeleteBackupRequest} request DeleteBackupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listBackups}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef ListBackupsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.ListBackupsResponse} [response] ListBackupsResponse + */ + + /** + * Calls ListBackups. + * @function listBackups + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListBackupsRequest} request ListBackupsRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.ListBackupsCallback} callback Node-style callback called with the error, if any, and ListBackupsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.listBackups = function listBackups(request, callback) { + return this.rpcCall(listBackups, $root.google.spanner.admin.database.v1.ListBackupsRequest, $root.google.spanner.admin.database.v1.ListBackupsResponse, request, callback); + }, "name", { value: "ListBackups" }); + + /** + * Calls ListBackups. + * @function listBackups + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListBackupsRequest} request ListBackupsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|restoreDatabase}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef RestoreDatabaseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls RestoreDatabase. + * @function restoreDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IRestoreDatabaseRequest} request RestoreDatabaseRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.RestoreDatabaseCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.restoreDatabase = function restoreDatabase(request, callback) { + return this.rpcCall(restoreDatabase, $root.google.spanner.admin.database.v1.RestoreDatabaseRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "RestoreDatabase" }); + + /** + * Calls RestoreDatabase. + * @function restoreDatabase + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IRestoreDatabaseRequest} request RestoreDatabaseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listDatabaseOperations}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef ListDatabaseOperationsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.ListDatabaseOperationsResponse} [response] ListDatabaseOperationsResponse + */ + + /** + * Calls ListDatabaseOperations. + * @function listDatabaseOperations + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsRequest} request ListDatabaseOperationsRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseOperationsCallback} callback Node-style callback called with the error, if any, and ListDatabaseOperationsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.listDatabaseOperations = function listDatabaseOperations(request, callback) { + return this.rpcCall(listDatabaseOperations, $root.google.spanner.admin.database.v1.ListDatabaseOperationsRequest, $root.google.spanner.admin.database.v1.ListDatabaseOperationsResponse, request, callback); + }, "name", { value: "ListDatabaseOperations" }); + + /** + * Calls ListDatabaseOperations. + * @function listDatabaseOperations + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsRequest} request ListDatabaseOperationsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listBackupOperations}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef ListBackupOperationsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.ListBackupOperationsResponse} [response] ListBackupOperationsResponse + */ + + /** + * Calls ListBackupOperations. + * @function listBackupOperations + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListBackupOperationsRequest} request ListBackupOperationsRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.ListBackupOperationsCallback} callback Node-style callback called with the error, if any, and ListBackupOperationsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.listBackupOperations = function listBackupOperations(request, callback) { + return this.rpcCall(listBackupOperations, $root.google.spanner.admin.database.v1.ListBackupOperationsRequest, $root.google.spanner.admin.database.v1.ListBackupOperationsResponse, request, callback); + }, "name", { value: "ListBackupOperations" }); + + /** + * Calls ListBackupOperations. + * @function listBackupOperations + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListBackupOperationsRequest} request ListBackupOperationsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listDatabaseRoles}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef ListDatabaseRolesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.ListDatabaseRolesResponse} [response] ListDatabaseRolesResponse + */ + + /** + * Calls ListDatabaseRoles. + * @function listDatabaseRoles + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListDatabaseRolesRequest} request ListDatabaseRolesRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseRolesCallback} callback Node-style callback called with the error, if any, and ListDatabaseRolesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.listDatabaseRoles = function listDatabaseRoles(request, callback) { + return this.rpcCall(listDatabaseRoles, $root.google.spanner.admin.database.v1.ListDatabaseRolesRequest, $root.google.spanner.admin.database.v1.ListDatabaseRolesResponse, request, callback); + }, "name", { value: "ListDatabaseRoles" }); + + /** + * Calls ListDatabaseRoles. + * @function listDatabaseRoles + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListDatabaseRolesRequest} request ListDatabaseRolesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|addSplitPoints}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef AddSplitPointsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.AddSplitPointsResponse} [response] AddSplitPointsResponse + */ + + /** + * Calls AddSplitPoints. + * @function addSplitPoints + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IAddSplitPointsRequest} request AddSplitPointsRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.AddSplitPointsCallback} callback Node-style callback called with the error, if any, and AddSplitPointsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.addSplitPoints = function addSplitPoints(request, callback) { + return this.rpcCall(addSplitPoints, $root.google.spanner.admin.database.v1.AddSplitPointsRequest, $root.google.spanner.admin.database.v1.AddSplitPointsResponse, request, callback); + }, "name", { value: "AddSplitPoints" }); + + /** + * Calls AddSplitPoints. + * @function addSplitPoints + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IAddSplitPointsRequest} request AddSplitPointsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|createBackupSchedule}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef CreateBackupScheduleCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.BackupSchedule} [response] BackupSchedule + */ + + /** + * Calls CreateBackupSchedule. + * @function createBackupSchedule + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.ICreateBackupScheduleRequest} request CreateBackupScheduleRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.CreateBackupScheduleCallback} callback Node-style callback called with the error, if any, and BackupSchedule + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.createBackupSchedule = function createBackupSchedule(request, callback) { + return this.rpcCall(createBackupSchedule, $root.google.spanner.admin.database.v1.CreateBackupScheduleRequest, $root.google.spanner.admin.database.v1.BackupSchedule, request, callback); + }, "name", { value: "CreateBackupSchedule" }); + + /** + * Calls CreateBackupSchedule. + * @function createBackupSchedule + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.ICreateBackupScheduleRequest} request CreateBackupScheduleRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|getBackupSchedule}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef GetBackupScheduleCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.BackupSchedule} [response] BackupSchedule + */ + + /** + * Calls GetBackupSchedule. + * @function getBackupSchedule + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IGetBackupScheduleRequest} request GetBackupScheduleRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.GetBackupScheduleCallback} callback Node-style callback called with the error, if any, and BackupSchedule + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.getBackupSchedule = function getBackupSchedule(request, callback) { + return this.rpcCall(getBackupSchedule, $root.google.spanner.admin.database.v1.GetBackupScheduleRequest, $root.google.spanner.admin.database.v1.BackupSchedule, request, callback); + }, "name", { value: "GetBackupSchedule" }); + + /** + * Calls GetBackupSchedule. + * @function getBackupSchedule + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IGetBackupScheduleRequest} request GetBackupScheduleRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|updateBackupSchedule}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef UpdateBackupScheduleCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.BackupSchedule} [response] BackupSchedule + */ + + /** + * Calls UpdateBackupSchedule. + * @function updateBackupSchedule + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IUpdateBackupScheduleRequest} request UpdateBackupScheduleRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackupScheduleCallback} callback Node-style callback called with the error, if any, and BackupSchedule + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.updateBackupSchedule = function updateBackupSchedule(request, callback) { + return this.rpcCall(updateBackupSchedule, $root.google.spanner.admin.database.v1.UpdateBackupScheduleRequest, $root.google.spanner.admin.database.v1.BackupSchedule, request, callback); + }, "name", { value: "UpdateBackupSchedule" }); + + /** + * Calls UpdateBackupSchedule. + * @function updateBackupSchedule + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IUpdateBackupScheduleRequest} request UpdateBackupScheduleRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|deleteBackupSchedule}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef DeleteBackupScheduleCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteBackupSchedule. + * @function deleteBackupSchedule + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IDeleteBackupScheduleRequest} request DeleteBackupScheduleRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.DeleteBackupScheduleCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.deleteBackupSchedule = function deleteBackupSchedule(request, callback) { + return this.rpcCall(deleteBackupSchedule, $root.google.spanner.admin.database.v1.DeleteBackupScheduleRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteBackupSchedule" }); + + /** + * Calls DeleteBackupSchedule. + * @function deleteBackupSchedule + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IDeleteBackupScheduleRequest} request DeleteBackupScheduleRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|listBackupSchedules}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef ListBackupSchedulesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.ListBackupSchedulesResponse} [response] ListBackupSchedulesResponse + */ + + /** + * Calls ListBackupSchedules. + * @function listBackupSchedules + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListBackupSchedulesRequest} request ListBackupSchedulesRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.ListBackupSchedulesCallback} callback Node-style callback called with the error, if any, and ListBackupSchedulesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.listBackupSchedules = function listBackupSchedules(request, callback) { + return this.rpcCall(listBackupSchedules, $root.google.spanner.admin.database.v1.ListBackupSchedulesRequest, $root.google.spanner.admin.database.v1.ListBackupSchedulesResponse, request, callback); + }, "name", { value: "ListBackupSchedules" }); + + /** + * Calls ListBackupSchedules. + * @function listBackupSchedules + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IListBackupSchedulesRequest} request ListBackupSchedulesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin|internalUpdateGraphOperation}. + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @typedef InternalUpdateGraphOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse} [response] InternalUpdateGraphOperationResponse + */ + + /** + * Calls InternalUpdateGraphOperation. + * @function internalUpdateGraphOperation + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest} request InternalUpdateGraphOperationRequest message or plain object + * @param {google.spanner.admin.database.v1.DatabaseAdmin.InternalUpdateGraphOperationCallback} callback Node-style callback called with the error, if any, and InternalUpdateGraphOperationResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(DatabaseAdmin.prototype.internalUpdateGraphOperation = function internalUpdateGraphOperation(request, callback) { + return this.rpcCall(internalUpdateGraphOperation, $root.google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest, $root.google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse, request, callback); + }, "name", { value: "InternalUpdateGraphOperation" }); + + /** + * Calls InternalUpdateGraphOperation. + * @function internalUpdateGraphOperation + * @memberof google.spanner.admin.database.v1.DatabaseAdmin + * @instance + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest} request InternalUpdateGraphOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return DatabaseAdmin; + })(); + + v1.RestoreInfo = (function() { + + /** + * Properties of a RestoreInfo. + * @memberof google.spanner.admin.database.v1 + * @interface IRestoreInfo + * @property {google.spanner.admin.database.v1.RestoreSourceType|null} [sourceType] RestoreInfo sourceType + * @property {google.spanner.admin.database.v1.IBackupInfo|null} [backupInfo] RestoreInfo backupInfo + */ + + /** + * Constructs a new RestoreInfo. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a RestoreInfo. + * @implements IRestoreInfo + * @constructor + * @param {google.spanner.admin.database.v1.IRestoreInfo=} [properties] Properties to set + */ + function RestoreInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RestoreInfo sourceType. + * @member {google.spanner.admin.database.v1.RestoreSourceType} sourceType + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @instance + */ + RestoreInfo.prototype.sourceType = 0; + + /** + * RestoreInfo backupInfo. + * @member {google.spanner.admin.database.v1.IBackupInfo|null|undefined} backupInfo + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @instance + */ + RestoreInfo.prototype.backupInfo = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RestoreInfo sourceInfo. + * @member {"backupInfo"|undefined} sourceInfo + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @instance + */ + Object.defineProperty(RestoreInfo.prototype, "sourceInfo", { + get: $util.oneOfGetter($oneOfFields = ["backupInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new RestoreInfo instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {google.spanner.admin.database.v1.IRestoreInfo=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.RestoreInfo} RestoreInfo instance + */ + RestoreInfo.create = function create(properties) { + return new RestoreInfo(properties); + }; + + /** + * Encodes the specified RestoreInfo message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreInfo.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {google.spanner.admin.database.v1.IRestoreInfo} message RestoreInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.sourceType != null && Object.hasOwnProperty.call(message, "sourceType")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.sourceType); + if (message.backupInfo != null && Object.hasOwnProperty.call(message, "backupInfo")) + $root.google.spanner.admin.database.v1.BackupInfo.encode(message.backupInfo, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RestoreInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {google.spanner.admin.database.v1.IRestoreInfo} message RestoreInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RestoreInfo message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.RestoreInfo} RestoreInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreInfo.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.spanner.admin.database.v1.RestoreInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.sourceType = reader.int32(); + break; + } + case 2: { + message.backupInfo = $root.google.spanner.admin.database.v1.BackupInfo.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RestoreInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.RestoreInfo} RestoreInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RestoreInfo message. + * @function verify + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RestoreInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.sourceType != null && message.hasOwnProperty("sourceType")) + switch (message.sourceType) { + default: + return "sourceType: enum value expected"; + case 0: + case 1: + break; + } + if (message.backupInfo != null && message.hasOwnProperty("backupInfo")) { + properties.sourceInfo = 1; + { + var error = $root.google.spanner.admin.database.v1.BackupInfo.verify(message.backupInfo); + if (error) + return "backupInfo." + error; + } + } + return null; + }; + + /** + * Creates a RestoreInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.RestoreInfo} RestoreInfo + */ + RestoreInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.RestoreInfo) + return object; + var message = new $root.google.spanner.admin.database.v1.RestoreInfo(); + switch (object.sourceType) { + default: + if (typeof object.sourceType === "number") { + message.sourceType = object.sourceType; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.sourceType = 0; + break; + case "BACKUP": + case 1: + message.sourceType = 1; + break; + } + if (object.backupInfo != null) { + if (typeof object.backupInfo !== "object") + throw TypeError(".google.spanner.admin.database.v1.RestoreInfo.backupInfo: object expected"); + message.backupInfo = $root.google.spanner.admin.database.v1.BackupInfo.fromObject(object.backupInfo); + } + return message; + }; + + /** + * Creates a plain object from a RestoreInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {google.spanner.admin.database.v1.RestoreInfo} message RestoreInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RestoreInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.sourceType = options.enums === String ? "TYPE_UNSPECIFIED" : 0; + if (message.sourceType != null && message.hasOwnProperty("sourceType")) + object.sourceType = options.enums === String ? $root.google.spanner.admin.database.v1.RestoreSourceType[message.sourceType] === undefined ? message.sourceType : $root.google.spanner.admin.database.v1.RestoreSourceType[message.sourceType] : message.sourceType; + if (message.backupInfo != null && message.hasOwnProperty("backupInfo")) { + object.backupInfo = $root.google.spanner.admin.database.v1.BackupInfo.toObject(message.backupInfo, options); + if (options.oneofs) + object.sourceInfo = "backupInfo"; + } + return object; + }; + + /** + * Converts this RestoreInfo to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @instance + * @returns {Object.} JSON object + */ + RestoreInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RestoreInfo + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.RestoreInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RestoreInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.RestoreInfo"; + }; + + return RestoreInfo; + })(); + + v1.Database = (function() { + + /** + * Properties of a Database. + * @memberof google.spanner.admin.database.v1 + * @interface IDatabase + * @property {string|null} [name] Database name + * @property {google.spanner.admin.database.v1.Database.State|null} [state] Database state + * @property {google.protobuf.ITimestamp|null} [createTime] Database createTime + * @property {google.spanner.admin.database.v1.IRestoreInfo|null} [restoreInfo] Database restoreInfo + * @property {google.spanner.admin.database.v1.IEncryptionConfig|null} [encryptionConfig] Database encryptionConfig + * @property {Array.|null} [encryptionInfo] Database encryptionInfo + * @property {string|null} [versionRetentionPeriod] Database versionRetentionPeriod + * @property {google.protobuf.ITimestamp|null} [earliestVersionTime] Database earliestVersionTime + * @property {string|null} [defaultLeader] Database defaultLeader + * @property {google.spanner.admin.database.v1.DatabaseDialect|null} [databaseDialect] Database databaseDialect + * @property {boolean|null} [enableDropProtection] Database enableDropProtection + * @property {boolean|null} [reconciling] Database reconciling + */ + + /** + * Constructs a new Database. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a Database. + * @implements IDatabase + * @constructor + * @param {google.spanner.admin.database.v1.IDatabase=} [properties] Properties to set + */ + function Database(properties) { + this.encryptionInfo = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Database name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.name = ""; + + /** + * Database state. + * @member {google.spanner.admin.database.v1.Database.State} state + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.state = 0; + + /** + * Database createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.createTime = null; + + /** + * Database restoreInfo. + * @member {google.spanner.admin.database.v1.IRestoreInfo|null|undefined} restoreInfo + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.restoreInfo = null; + + /** + * Database encryptionConfig. + * @member {google.spanner.admin.database.v1.IEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.encryptionConfig = null; + + /** + * Database encryptionInfo. + * @member {Array.} encryptionInfo + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.encryptionInfo = $util.emptyArray; + + /** + * Database versionRetentionPeriod. + * @member {string} versionRetentionPeriod + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.versionRetentionPeriod = ""; + + /** + * Database earliestVersionTime. + * @member {google.protobuf.ITimestamp|null|undefined} earliestVersionTime + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.earliestVersionTime = null; + + /** + * Database defaultLeader. + * @member {string} defaultLeader + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.defaultLeader = ""; + + /** + * Database databaseDialect. + * @member {google.spanner.admin.database.v1.DatabaseDialect} databaseDialect + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.databaseDialect = 0; + + /** + * Database enableDropProtection. + * @member {boolean} enableDropProtection + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.enableDropProtection = false; + + /** + * Database reconciling. + * @member {boolean} reconciling + * @memberof google.spanner.admin.database.v1.Database + * @instance + */ + Database.prototype.reconciling = false; + + /** + * Creates a new Database instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {google.spanner.admin.database.v1.IDatabase=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.Database} Database instance + */ + Database.create = function create(properties) { + return new Database(properties); + }; + + /** + * Encodes the specified Database message. Does not implicitly {@link google.spanner.admin.database.v1.Database.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {google.spanner.admin.database.v1.IDatabase} message Database message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Database.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.state != null && Object.hasOwnProperty.call(message, "state")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.state); + if (message.createTime != null && Object.hasOwnProperty.call(message, "createTime")) + $root.google.protobuf.Timestamp.encode(message.createTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.restoreInfo != null && Object.hasOwnProperty.call(message, "restoreInfo")) + $root.google.spanner.admin.database.v1.RestoreInfo.encode(message.restoreInfo, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.EncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.versionRetentionPeriod != null && Object.hasOwnProperty.call(message, "versionRetentionPeriod")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.versionRetentionPeriod); + if (message.earliestVersionTime != null && Object.hasOwnProperty.call(message, "earliestVersionTime")) + $root.google.protobuf.Timestamp.encode(message.earliestVersionTime, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.encryptionInfo != null && message.encryptionInfo.length) + for (var i = 0; i < message.encryptionInfo.length; ++i) + $root.google.spanner.admin.database.v1.EncryptionInfo.encode(message.encryptionInfo[i], writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.defaultLeader != null && Object.hasOwnProperty.call(message, "defaultLeader")) + writer.uint32(/* id 9, wireType 2 =*/74).string(message.defaultLeader); + if (message.databaseDialect != null && Object.hasOwnProperty.call(message, "databaseDialect")) + writer.uint32(/* id 10, wireType 0 =*/80).int32(message.databaseDialect); + if (message.enableDropProtection != null && Object.hasOwnProperty.call(message, "enableDropProtection")) + writer.uint32(/* id 11, wireType 0 =*/88).bool(message.enableDropProtection); + if (message.reconciling != null && Object.hasOwnProperty.call(message, "reconciling")) + writer.uint32(/* id 12, wireType 0 =*/96).bool(message.reconciling); + return writer; + }; + + /** + * Encodes the specified Database message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.Database.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {google.spanner.admin.database.v1.IDatabase} message Database message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Database.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Database message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.Database} Database + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Database.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.spanner.admin.database.v1.Database(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.state = reader.int32(); + break; + } + case 3: { + message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.restoreInfo = $root.google.spanner.admin.database.v1.RestoreInfo.decode(reader, reader.uint32()); + break; + } + case 5: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.decode(reader, reader.uint32()); + break; + } + case 8: { + if (!(message.encryptionInfo && message.encryptionInfo.length)) + message.encryptionInfo = []; + message.encryptionInfo.push($root.google.spanner.admin.database.v1.EncryptionInfo.decode(reader, reader.uint32())); + break; + } + case 6: { + message.versionRetentionPeriod = reader.string(); + break; + } + case 7: { + message.earliestVersionTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 9: { + message.defaultLeader = reader.string(); + break; + } + case 10: { + message.databaseDialect = reader.int32(); + break; + } + case 11: { + message.enableDropProtection = reader.bool(); + break; + } + case 12: { + message.reconciling = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Database message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.Database} Database + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Database.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Database message. + * @function verify + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Database.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.state != null && message.hasOwnProperty("state")) + switch (message.state) { + default: + return "state: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.createTime != null && message.hasOwnProperty("createTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.createTime); + if (error) + return "createTime." + error; + } + if (message.restoreInfo != null && message.hasOwnProperty("restoreInfo")) { + var error = $root.google.spanner.admin.database.v1.RestoreInfo.verify(message.restoreInfo); + if (error) + return "restoreInfo." + error; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.EncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + if (message.encryptionInfo != null && message.hasOwnProperty("encryptionInfo")) { + if (!Array.isArray(message.encryptionInfo)) + return "encryptionInfo: array expected"; + for (var i = 0; i < message.encryptionInfo.length; ++i) { + var error = $root.google.spanner.admin.database.v1.EncryptionInfo.verify(message.encryptionInfo[i]); + if (error) + return "encryptionInfo." + error; + } + } + if (message.versionRetentionPeriod != null && message.hasOwnProperty("versionRetentionPeriod")) + if (!$util.isString(message.versionRetentionPeriod)) + return "versionRetentionPeriod: string expected"; + if (message.earliestVersionTime != null && message.hasOwnProperty("earliestVersionTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.earliestVersionTime); + if (error) + return "earliestVersionTime." + error; + } + if (message.defaultLeader != null && message.hasOwnProperty("defaultLeader")) + if (!$util.isString(message.defaultLeader)) + return "defaultLeader: string expected"; + if (message.databaseDialect != null && message.hasOwnProperty("databaseDialect")) + switch (message.databaseDialect) { + default: + return "databaseDialect: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.enableDropProtection != null && message.hasOwnProperty("enableDropProtection")) + if (typeof message.enableDropProtection !== "boolean") + return "enableDropProtection: boolean expected"; + if (message.reconciling != null && message.hasOwnProperty("reconciling")) + if (typeof message.reconciling !== "boolean") + return "reconciling: boolean expected"; + return null; + }; + + /** + * Creates a Database message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.Database} Database + */ + Database.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.Database) + return object; + var message = new $root.google.spanner.admin.database.v1.Database(); + if (object.name != null) + message.name = String(object.name); + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "CREATING": + case 1: + message.state = 1; + break; + case "READY": + case 2: + message.state = 2; + break; + case "READY_OPTIMIZING": + case 3: + message.state = 3; + break; + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.Database.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.restoreInfo != null) { + if (typeof object.restoreInfo !== "object") + throw TypeError(".google.spanner.admin.database.v1.Database.restoreInfo: object expected"); + message.restoreInfo = $root.google.spanner.admin.database.v1.RestoreInfo.fromObject(object.restoreInfo); + } + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.admin.database.v1.Database.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.fromObject(object.encryptionConfig); + } + if (object.encryptionInfo) { + if (!Array.isArray(object.encryptionInfo)) + throw TypeError(".google.spanner.admin.database.v1.Database.encryptionInfo: array expected"); + message.encryptionInfo = []; + for (var i = 0; i < object.encryptionInfo.length; ++i) { + if (typeof object.encryptionInfo[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.Database.encryptionInfo: object expected"); + message.encryptionInfo[i] = $root.google.spanner.admin.database.v1.EncryptionInfo.fromObject(object.encryptionInfo[i]); + } + } + if (object.versionRetentionPeriod != null) + message.versionRetentionPeriod = String(object.versionRetentionPeriod); + if (object.earliestVersionTime != null) { + if (typeof object.earliestVersionTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.Database.earliestVersionTime: object expected"); + message.earliestVersionTime = $root.google.protobuf.Timestamp.fromObject(object.earliestVersionTime); + } + if (object.defaultLeader != null) + message.defaultLeader = String(object.defaultLeader); + switch (object.databaseDialect) { + default: + if (typeof object.databaseDialect === "number") { + message.databaseDialect = object.databaseDialect; + break; + } + break; + case "DATABASE_DIALECT_UNSPECIFIED": + case 0: + message.databaseDialect = 0; + break; + case "GOOGLE_STANDARD_SQL": + case 1: + message.databaseDialect = 1; + break; + case "POSTGRESQL": + case 2: + message.databaseDialect = 2; + break; + } + if (object.enableDropProtection != null) + message.enableDropProtection = Boolean(object.enableDropProtection); + if (object.reconciling != null) + message.reconciling = Boolean(object.reconciling); + return message; + }; + + /** + * Creates a plain object from a Database message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {google.spanner.admin.database.v1.Database} message Database + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Database.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.encryptionInfo = []; + if (options.defaults) { + object.name = ""; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + object.createTime = null; + object.restoreInfo = null; + object.encryptionConfig = null; + object.versionRetentionPeriod = ""; + object.earliestVersionTime = null; + object.defaultLeader = ""; + object.databaseDialect = options.enums === String ? "DATABASE_DIALECT_UNSPECIFIED" : 0; + object.enableDropProtection = false; + object.reconciling = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.spanner.admin.database.v1.Database.State[message.state] === undefined ? message.state : $root.google.spanner.admin.database.v1.Database.State[message.state] : message.state; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.restoreInfo != null && message.hasOwnProperty("restoreInfo")) + object.restoreInfo = $root.google.spanner.admin.database.v1.RestoreInfo.toObject(message.restoreInfo, options); + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.toObject(message.encryptionConfig, options); + if (message.versionRetentionPeriod != null && message.hasOwnProperty("versionRetentionPeriod")) + object.versionRetentionPeriod = message.versionRetentionPeriod; + if (message.earliestVersionTime != null && message.hasOwnProperty("earliestVersionTime")) + object.earliestVersionTime = $root.google.protobuf.Timestamp.toObject(message.earliestVersionTime, options); + if (message.encryptionInfo && message.encryptionInfo.length) { + object.encryptionInfo = []; + for (var j = 0; j < message.encryptionInfo.length; ++j) + object.encryptionInfo[j] = $root.google.spanner.admin.database.v1.EncryptionInfo.toObject(message.encryptionInfo[j], options); + } + if (message.defaultLeader != null && message.hasOwnProperty("defaultLeader")) + object.defaultLeader = message.defaultLeader; + if (message.databaseDialect != null && message.hasOwnProperty("databaseDialect")) + object.databaseDialect = options.enums === String ? $root.google.spanner.admin.database.v1.DatabaseDialect[message.databaseDialect] === undefined ? message.databaseDialect : $root.google.spanner.admin.database.v1.DatabaseDialect[message.databaseDialect] : message.databaseDialect; + if (message.enableDropProtection != null && message.hasOwnProperty("enableDropProtection")) + object.enableDropProtection = message.enableDropProtection; + if (message.reconciling != null && message.hasOwnProperty("reconciling")) + object.reconciling = message.reconciling; + return object; + }; + + /** + * Converts this Database to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.Database + * @instance + * @returns {Object.} JSON object + */ + Database.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Database + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.Database + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Database.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.Database"; + }; + + /** + * State enum. + * @name google.spanner.admin.database.v1.Database.State + * @enum {number} + * @property {number} STATE_UNSPECIFIED=0 STATE_UNSPECIFIED value + * @property {number} CREATING=1 CREATING value + * @property {number} READY=2 READY value + * @property {number} READY_OPTIMIZING=3 READY_OPTIMIZING value + */ + Database.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = 0; + values[valuesById[1] = "CREATING"] = 1; + values[valuesById[2] = "READY"] = 2; + values[valuesById[3] = "READY_OPTIMIZING"] = 3; + return values; + })(); + + return Database; + })(); + + v1.ListDatabasesRequest = (function() { + + /** + * Properties of a ListDatabasesRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IListDatabasesRequest + * @property {string|null} [parent] ListDatabasesRequest parent + * @property {number|null} [pageSize] ListDatabasesRequest pageSize + * @property {string|null} [pageToken] ListDatabasesRequest pageToken + */ + + /** + * Constructs a new ListDatabasesRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListDatabasesRequest. + * @implements IListDatabasesRequest + * @constructor + * @param {google.spanner.admin.database.v1.IListDatabasesRequest=} [properties] Properties to set + */ + function ListDatabasesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDatabasesRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @instance + */ + ListDatabasesRequest.prototype.parent = ""; + + /** + * ListDatabasesRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @instance + */ + ListDatabasesRequest.prototype.pageSize = 0; + + /** + * ListDatabasesRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @instance + */ + ListDatabasesRequest.prototype.pageToken = ""; + + /** + * Creates a new ListDatabasesRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabasesRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListDatabasesRequest} ListDatabasesRequest instance + */ + ListDatabasesRequest.create = function create(properties) { + return new ListDatabasesRequest(properties); + }; + + /** + * Encodes the specified ListDatabasesRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabasesRequest} message ListDatabasesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabasesRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListDatabasesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabasesRequest} message ListDatabasesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabasesRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListDatabasesRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListDatabasesRequest} ListDatabasesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabasesRequest.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.spanner.admin.database.v1.ListDatabasesRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListDatabasesRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListDatabasesRequest} ListDatabasesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabasesRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListDatabasesRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListDatabasesRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListDatabasesRequest} ListDatabasesRequest + */ + ListDatabasesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListDatabasesRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.ListDatabasesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {google.spanner.admin.database.v1.ListDatabasesRequest} message ListDatabasesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDatabasesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListDatabasesRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @instance + * @returns {Object.} JSON object + */ + ListDatabasesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDatabasesRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListDatabasesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDatabasesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListDatabasesRequest"; + }; + + return ListDatabasesRequest; + })(); + + v1.ListDatabasesResponse = (function() { + + /** + * Properties of a ListDatabasesResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IListDatabasesResponse + * @property {Array.|null} [databases] ListDatabasesResponse databases + * @property {string|null} [nextPageToken] ListDatabasesResponse nextPageToken + */ + + /** + * Constructs a new ListDatabasesResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListDatabasesResponse. + * @implements IListDatabasesResponse + * @constructor + * @param {google.spanner.admin.database.v1.IListDatabasesResponse=} [properties] Properties to set + */ + function ListDatabasesResponse(properties) { + this.databases = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDatabasesResponse databases. + * @member {Array.} databases + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @instance + */ + ListDatabasesResponse.prototype.databases = $util.emptyArray; + + /** + * ListDatabasesResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @instance + */ + ListDatabasesResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListDatabasesResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabasesResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListDatabasesResponse} ListDatabasesResponse instance + */ + ListDatabasesResponse.create = function create(properties) { + return new ListDatabasesResponse(properties); + }; + + /** + * Encodes the specified ListDatabasesResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabasesResponse} message ListDatabasesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabasesResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.databases != null && message.databases.length) + for (var i = 0; i < message.databases.length; ++i) + $root.google.spanner.admin.database.v1.Database.encode(message.databases[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListDatabasesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabasesResponse} message ListDatabasesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabasesResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListDatabasesResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListDatabasesResponse} ListDatabasesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabasesResponse.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.spanner.admin.database.v1.ListDatabasesResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.databases && message.databases.length)) + message.databases = []; + message.databases.push($root.google.spanner.admin.database.v1.Database.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListDatabasesResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListDatabasesResponse} ListDatabasesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabasesResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListDatabasesResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListDatabasesResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.databases != null && message.hasOwnProperty("databases")) { + if (!Array.isArray(message.databases)) + return "databases: array expected"; + for (var i = 0; i < message.databases.length; ++i) { + var error = $root.google.spanner.admin.database.v1.Database.verify(message.databases[i]); + if (error) + return "databases." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListDatabasesResponse} ListDatabasesResponse + */ + ListDatabasesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListDatabasesResponse) + return object; + var message = new $root.google.spanner.admin.database.v1.ListDatabasesResponse(); + if (object.databases) { + if (!Array.isArray(object.databases)) + throw TypeError(".google.spanner.admin.database.v1.ListDatabasesResponse.databases: array expected"); + message.databases = []; + for (var i = 0; i < object.databases.length; ++i) { + if (typeof object.databases[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.ListDatabasesResponse.databases: object expected"); + message.databases[i] = $root.google.spanner.admin.database.v1.Database.fromObject(object.databases[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {google.spanner.admin.database.v1.ListDatabasesResponse} message ListDatabasesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDatabasesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.databases = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.databases && message.databases.length) { + object.databases = []; + for (var j = 0; j < message.databases.length; ++j) + object.databases[j] = $root.google.spanner.admin.database.v1.Database.toObject(message.databases[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListDatabasesResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @instance + * @returns {Object.} JSON object + */ + ListDatabasesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDatabasesResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListDatabasesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDatabasesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListDatabasesResponse"; + }; + + return ListDatabasesResponse; + })(); + + v1.CreateDatabaseRequest = (function() { + + /** + * Properties of a CreateDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @interface ICreateDatabaseRequest + * @property {string|null} [parent] CreateDatabaseRequest parent + * @property {string|null} [createStatement] CreateDatabaseRequest createStatement + * @property {Array.|null} [extraStatements] CreateDatabaseRequest extraStatements + * @property {google.spanner.admin.database.v1.IEncryptionConfig|null} [encryptionConfig] CreateDatabaseRequest encryptionConfig + * @property {google.spanner.admin.database.v1.DatabaseDialect|null} [databaseDialect] CreateDatabaseRequest databaseDialect + * @property {Uint8Array|null} [protoDescriptors] CreateDatabaseRequest protoDescriptors + */ + + /** + * Constructs a new CreateDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CreateDatabaseRequest. + * @implements ICreateDatabaseRequest + * @constructor + * @param {google.spanner.admin.database.v1.ICreateDatabaseRequest=} [properties] Properties to set + */ + function CreateDatabaseRequest(properties) { + this.extraStatements = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateDatabaseRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.parent = ""; + + /** + * CreateDatabaseRequest createStatement. + * @member {string} createStatement + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.createStatement = ""; + + /** + * CreateDatabaseRequest extraStatements. + * @member {Array.} extraStatements + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.extraStatements = $util.emptyArray; + + /** + * CreateDatabaseRequest encryptionConfig. + * @member {google.spanner.admin.database.v1.IEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.encryptionConfig = null; + + /** + * CreateDatabaseRequest databaseDialect. + * @member {google.spanner.admin.database.v1.DatabaseDialect} databaseDialect + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.databaseDialect = 0; + + /** + * CreateDatabaseRequest protoDescriptors. + * @member {Uint8Array} protoDescriptors + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @instance + */ + CreateDatabaseRequest.prototype.protoDescriptors = $util.newBuffer([]); + + /** + * Creates a new CreateDatabaseRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateDatabaseRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CreateDatabaseRequest} CreateDatabaseRequest instance + */ + CreateDatabaseRequest.create = function create(properties) { + return new CreateDatabaseRequest(properties); + }; + + /** + * Encodes the specified CreateDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateDatabaseRequest} message CreateDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateDatabaseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.createStatement != null && Object.hasOwnProperty.call(message, "createStatement")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.createStatement); + if (message.extraStatements != null && message.extraStatements.length) + for (var i = 0; i < message.extraStatements.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.extraStatements[i]); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.EncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.databaseDialect != null && Object.hasOwnProperty.call(message, "databaseDialect")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.databaseDialect); + if (message.protoDescriptors != null && Object.hasOwnProperty.call(message, "protoDescriptors")) + writer.uint32(/* id 6, wireType 2 =*/50).bytes(message.protoDescriptors); + return writer; + }; + + /** + * Encodes the specified CreateDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.ICreateDatabaseRequest} message CreateDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateDatabaseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateDatabaseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CreateDatabaseRequest} CreateDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateDatabaseRequest.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.spanner.admin.database.v1.CreateDatabaseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.createStatement = reader.string(); + break; + } + case 3: { + if (!(message.extraStatements && message.extraStatements.length)) + message.extraStatements = []; + message.extraStatements.push(reader.string()); + break; + } + case 4: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.decode(reader, reader.uint32()); + break; + } + case 5: { + message.databaseDialect = reader.int32(); + break; + } + case 6: { + message.protoDescriptors = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateDatabaseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CreateDatabaseRequest} CreateDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateDatabaseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateDatabaseRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateDatabaseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.createStatement != null && message.hasOwnProperty("createStatement")) + if (!$util.isString(message.createStatement)) + return "createStatement: string expected"; + if (message.extraStatements != null && message.hasOwnProperty("extraStatements")) { + if (!Array.isArray(message.extraStatements)) + return "extraStatements: array expected"; + for (var i = 0; i < message.extraStatements.length; ++i) + if (!$util.isString(message.extraStatements[i])) + return "extraStatements: string[] expected"; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.EncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + if (message.databaseDialect != null && message.hasOwnProperty("databaseDialect")) + switch (message.databaseDialect) { + default: + return "databaseDialect: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) + if (!(message.protoDescriptors && typeof message.protoDescriptors.length === "number" || $util.isString(message.protoDescriptors))) + return "protoDescriptors: buffer expected"; + return null; + }; + + /** + * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CreateDatabaseRequest} CreateDatabaseRequest + */ + CreateDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CreateDatabaseRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.CreateDatabaseRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.createStatement != null) + message.createStatement = String(object.createStatement); + if (object.extraStatements) { + if (!Array.isArray(object.extraStatements)) + throw TypeError(".google.spanner.admin.database.v1.CreateDatabaseRequest.extraStatements: array expected"); + message.extraStatements = []; + for (var i = 0; i < object.extraStatements.length; ++i) + message.extraStatements[i] = String(object.extraStatements[i]); + } + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.admin.database.v1.CreateDatabaseRequest.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.fromObject(object.encryptionConfig); + } + switch (object.databaseDialect) { + default: + if (typeof object.databaseDialect === "number") { + message.databaseDialect = object.databaseDialect; + break; + } + break; + case "DATABASE_DIALECT_UNSPECIFIED": + case 0: + message.databaseDialect = 0; + break; + case "GOOGLE_STANDARD_SQL": + case 1: + message.databaseDialect = 1; + break; + case "POSTGRESQL": + case 2: + message.databaseDialect = 2; + break; + } + if (object.protoDescriptors != null) + if (typeof object.protoDescriptors === "string") + $util.base64.decode(object.protoDescriptors, message.protoDescriptors = $util.newBuffer($util.base64.length(object.protoDescriptors)), 0); + else if (object.protoDescriptors.length >= 0) + message.protoDescriptors = object.protoDescriptors; + return message; + }; + + /** + * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.CreateDatabaseRequest} message CreateDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.extraStatements = []; + if (options.defaults) { + object.parent = ""; + object.createStatement = ""; + object.encryptionConfig = null; + object.databaseDialect = options.enums === String ? "DATABASE_DIALECT_UNSPECIFIED" : 0; + if (options.bytes === String) + object.protoDescriptors = ""; + else { + object.protoDescriptors = []; + if (options.bytes !== Array) + object.protoDescriptors = $util.newBuffer(object.protoDescriptors); + } + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.createStatement != null && message.hasOwnProperty("createStatement")) + object.createStatement = message.createStatement; + if (message.extraStatements && message.extraStatements.length) { + object.extraStatements = []; + for (var j = 0; j < message.extraStatements.length; ++j) + object.extraStatements[j] = message.extraStatements[j]; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.toObject(message.encryptionConfig, options); + if (message.databaseDialect != null && message.hasOwnProperty("databaseDialect")) + object.databaseDialect = options.enums === String ? $root.google.spanner.admin.database.v1.DatabaseDialect[message.databaseDialect] === undefined ? message.databaseDialect : $root.google.spanner.admin.database.v1.DatabaseDialect[message.databaseDialect] : message.databaseDialect; + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) + object.protoDescriptors = options.bytes === String ? $util.base64.encode(message.protoDescriptors, 0, message.protoDescriptors.length) : options.bytes === Array ? Array.prototype.slice.call(message.protoDescriptors) : message.protoDescriptors; + return object; + }; + + /** + * Converts this CreateDatabaseRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + CreateDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateDatabaseRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CreateDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CreateDatabaseRequest"; + }; + + return CreateDatabaseRequest; + })(); + + v1.CreateDatabaseMetadata = (function() { + + /** + * Properties of a CreateDatabaseMetadata. + * @memberof google.spanner.admin.database.v1 + * @interface ICreateDatabaseMetadata + * @property {string|null} [database] CreateDatabaseMetadata database + */ + + /** + * Constructs a new CreateDatabaseMetadata. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a CreateDatabaseMetadata. + * @implements ICreateDatabaseMetadata + * @constructor + * @param {google.spanner.admin.database.v1.ICreateDatabaseMetadata=} [properties] Properties to set + */ + function CreateDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateDatabaseMetadata database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @instance + */ + CreateDatabaseMetadata.prototype.database = ""; + + /** + * Creates a new CreateDatabaseMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.ICreateDatabaseMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.CreateDatabaseMetadata} CreateDatabaseMetadata instance + */ + CreateDatabaseMetadata.create = function create(properties) { + return new CreateDatabaseMetadata(properties); + }; + + /** + * Encodes the specified CreateDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.ICreateDatabaseMetadata} message CreateDatabaseMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateDatabaseMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + return writer; + }; + + /** + * Encodes the specified CreateDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.ICreateDatabaseMetadata} message CreateDatabaseMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateDatabaseMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateDatabaseMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.CreateDatabaseMetadata} CreateDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateDatabaseMetadata.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.spanner.admin.database.v1.CreateDatabaseMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateDatabaseMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.CreateDatabaseMetadata} CreateDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateDatabaseMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateDatabaseMetadata message. + * @function verify + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateDatabaseMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + return null; + }; + + /** + * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.CreateDatabaseMetadata} CreateDatabaseMetadata + */ + CreateDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.CreateDatabaseMetadata) + return object; + var message = new $root.google.spanner.admin.database.v1.CreateDatabaseMetadata(); + if (object.database != null) + message.database = String(object.database); + return message; + }; + + /** + * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.CreateDatabaseMetadata} message CreateDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateDatabaseMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + return object; + }; + + /** + * Converts this CreateDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + CreateDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateDatabaseMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.CreateDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.CreateDatabaseMetadata"; + }; + + return CreateDatabaseMetadata; + })(); + + v1.GetDatabaseRequest = (function() { + + /** + * Properties of a GetDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IGetDatabaseRequest + * @property {string|null} [name] GetDatabaseRequest name + */ + + /** + * Constructs a new GetDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a GetDatabaseRequest. + * @implements IGetDatabaseRequest + * @constructor + * @param {google.spanner.admin.database.v1.IGetDatabaseRequest=} [properties] Properties to set + */ + function GetDatabaseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetDatabaseRequest name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @instance + */ + GetDatabaseRequest.prototype.name = ""; + + /** + * Creates a new GetDatabaseRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.GetDatabaseRequest} GetDatabaseRequest instance + */ + GetDatabaseRequest.create = function create(properties) { + return new GetDatabaseRequest(properties); + }; + + /** + * Encodes the specified GetDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseRequest} message GetDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetDatabaseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseRequest} message GetDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetDatabaseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetDatabaseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.GetDatabaseRequest} GetDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetDatabaseRequest.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.spanner.admin.database.v1.GetDatabaseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetDatabaseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.GetDatabaseRequest} GetDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetDatabaseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetDatabaseRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetDatabaseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.GetDatabaseRequest} GetDatabaseRequest + */ + GetDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.GetDatabaseRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.GetDatabaseRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.GetDatabaseRequest} message GetDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + GetDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetDatabaseRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.GetDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.GetDatabaseRequest"; + }; + + return GetDatabaseRequest; + })(); + + v1.UpdateDatabaseRequest = (function() { + + /** + * Properties of an UpdateDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IUpdateDatabaseRequest + * @property {google.spanner.admin.database.v1.IDatabase|null} [database] UpdateDatabaseRequest database + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateDatabaseRequest updateMask + */ + + /** + * Constructs a new UpdateDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an UpdateDatabaseRequest. + * @implements IUpdateDatabaseRequest + * @constructor + * @param {google.spanner.admin.database.v1.IUpdateDatabaseRequest=} [properties] Properties to set + */ + function UpdateDatabaseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateDatabaseRequest database. + * @member {google.spanner.admin.database.v1.IDatabase|null|undefined} database + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @instance + */ + UpdateDatabaseRequest.prototype.database = null; + + /** + * UpdateDatabaseRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @instance + */ + UpdateDatabaseRequest.prototype.updateMask = null; + + /** + * Creates a new UpdateDatabaseRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.UpdateDatabaseRequest} UpdateDatabaseRequest instance + */ + UpdateDatabaseRequest.create = function create(properties) { + return new UpdateDatabaseRequest(properties); + }; + + /** + * Encodes the specified UpdateDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseRequest} message UpdateDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateDatabaseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + $root.google.spanner.admin.database.v1.Database.encode(message.database, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + $root.google.protobuf.FieldMask.encode(message.updateMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseRequest} message UpdateDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateDatabaseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateDatabaseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.UpdateDatabaseRequest} UpdateDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateDatabaseRequest.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.spanner.admin.database.v1.UpdateDatabaseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = $root.google.spanner.admin.database.v1.Database.decode(reader, reader.uint32()); + break; + } + case 2: { + message.updateMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateDatabaseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.UpdateDatabaseRequest} UpdateDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateDatabaseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateDatabaseRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateDatabaseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) { + var error = $root.google.spanner.admin.database.v1.Database.verify(message.database); + if (error) + return "database." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.updateMask); + if (error) + return "updateMask." + error; + } + return null; + }; + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.UpdateDatabaseRequest} UpdateDatabaseRequest + */ + UpdateDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.UpdateDatabaseRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.UpdateDatabaseRequest(); + if (object.database != null) { + if (typeof object.database !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseRequest.database: object expected"); + message.database = $root.google.spanner.admin.database.v1.Database.fromObject(object.database); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.UpdateDatabaseRequest} message UpdateDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = null; + object.updateMask = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = $root.google.spanner.admin.database.v1.Database.toObject(message.database, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.UpdateDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.UpdateDatabaseRequest"; + }; + + return UpdateDatabaseRequest; + })(); + + v1.UpdateDatabaseMetadata = (function() { + + /** + * Properties of an UpdateDatabaseMetadata. + * @memberof google.spanner.admin.database.v1 + * @interface IUpdateDatabaseMetadata + * @property {google.spanner.admin.database.v1.IUpdateDatabaseRequest|null} [request] UpdateDatabaseMetadata request + * @property {google.spanner.admin.database.v1.IOperationProgress|null} [progress] UpdateDatabaseMetadata progress + * @property {google.protobuf.ITimestamp|null} [cancelTime] UpdateDatabaseMetadata cancelTime + */ + + /** + * Constructs a new UpdateDatabaseMetadata. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an UpdateDatabaseMetadata. + * @implements IUpdateDatabaseMetadata + * @constructor + * @param {google.spanner.admin.database.v1.IUpdateDatabaseMetadata=} [properties] Properties to set + */ + function UpdateDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateDatabaseMetadata request. + * @member {google.spanner.admin.database.v1.IUpdateDatabaseRequest|null|undefined} request + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @instance + */ + UpdateDatabaseMetadata.prototype.request = null; + + /** + * UpdateDatabaseMetadata progress. + * @member {google.spanner.admin.database.v1.IOperationProgress|null|undefined} progress + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @instance + */ + UpdateDatabaseMetadata.prototype.progress = null; + + /** + * UpdateDatabaseMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @instance + */ + UpdateDatabaseMetadata.prototype.cancelTime = null; + + /** + * Creates a new UpdateDatabaseMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.UpdateDatabaseMetadata} UpdateDatabaseMetadata instance + */ + UpdateDatabaseMetadata.create = function create(properties) { + return new UpdateDatabaseMetadata(properties); + }; + + /** + * Encodes the specified UpdateDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseMetadata} message UpdateDatabaseMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateDatabaseMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.request != null && Object.hasOwnProperty.call(message, "request")) + $root.google.spanner.admin.database.v1.UpdateDatabaseRequest.encode(message.request, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.spanner.admin.database.v1.OperationProgress.encode(message.progress, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseMetadata} message UpdateDatabaseMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateDatabaseMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateDatabaseMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.UpdateDatabaseMetadata} UpdateDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateDatabaseMetadata.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.spanner.admin.database.v1.UpdateDatabaseMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.request = $root.google.spanner.admin.database.v1.UpdateDatabaseRequest.decode(reader, reader.uint32()); + break; + } + case 2: { + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.decode(reader, reader.uint32()); + break; + } + case 3: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateDatabaseMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.UpdateDatabaseMetadata} UpdateDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateDatabaseMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateDatabaseMetadata message. + * @function verify + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateDatabaseMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.request != null && message.hasOwnProperty("request")) { + var error = $root.google.spanner.admin.database.v1.UpdateDatabaseRequest.verify(message.request); + if (error) + return "request." + error; + } + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.spanner.admin.database.v1.OperationProgress.verify(message.progress); + if (error) + return "progress." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + return null; + }; + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.UpdateDatabaseMetadata} UpdateDatabaseMetadata + */ + UpdateDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.UpdateDatabaseMetadata) + return object; + var message = new $root.google.spanner.admin.database.v1.UpdateDatabaseMetadata(); + if (object.request != null) { + if (typeof object.request !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseMetadata.request: object expected"); + message.request = $root.google.spanner.admin.database.v1.UpdateDatabaseRequest.fromObject(object.request); + } + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseMetadata.progress: object expected"); + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.fromObject(object.progress); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + return message; + }; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.UpdateDatabaseMetadata} message UpdateDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateDatabaseMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.request = null; + object.progress = null; + object.cancelTime = null; + } + if (message.request != null && message.hasOwnProperty("request")) + object.request = $root.google.spanner.admin.database.v1.UpdateDatabaseRequest.toObject(message.request, options); + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.spanner.admin.database.v1.OperationProgress.toObject(message.progress, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + return object; + }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + UpdateDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.UpdateDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.UpdateDatabaseMetadata"; + }; + + return UpdateDatabaseMetadata; + })(); + + v1.UpdateDatabaseDdlRequest = (function() { + + /** + * Properties of an UpdateDatabaseDdlRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IUpdateDatabaseDdlRequest + * @property {string|null} [database] UpdateDatabaseDdlRequest database + * @property {Array.|null} [statements] UpdateDatabaseDdlRequest statements + * @property {string|null} [operationId] UpdateDatabaseDdlRequest operationId + * @property {Uint8Array|null} [protoDescriptors] UpdateDatabaseDdlRequest protoDescriptors + * @property {boolean|null} [throughputMode] UpdateDatabaseDdlRequest throughputMode + */ + + /** + * Constructs a new UpdateDatabaseDdlRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an UpdateDatabaseDdlRequest. + * @implements IUpdateDatabaseDdlRequest + * @constructor + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest=} [properties] Properties to set + */ + function UpdateDatabaseDdlRequest(properties) { + this.statements = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateDatabaseDdlRequest database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @instance + */ + UpdateDatabaseDdlRequest.prototype.database = ""; + + /** + * UpdateDatabaseDdlRequest statements. + * @member {Array.} statements + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @instance + */ + UpdateDatabaseDdlRequest.prototype.statements = $util.emptyArray; + + /** + * UpdateDatabaseDdlRequest operationId. + * @member {string} operationId + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @instance + */ + UpdateDatabaseDdlRequest.prototype.operationId = ""; + + /** + * UpdateDatabaseDdlRequest protoDescriptors. + * @member {Uint8Array} protoDescriptors + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @instance + */ + UpdateDatabaseDdlRequest.prototype.protoDescriptors = $util.newBuffer([]); + + /** + * UpdateDatabaseDdlRequest throughputMode. + * @member {boolean} throughputMode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @instance + */ + UpdateDatabaseDdlRequest.prototype.throughputMode = false; + + /** + * Creates a new UpdateDatabaseDdlRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.UpdateDatabaseDdlRequest} UpdateDatabaseDdlRequest instance + */ + UpdateDatabaseDdlRequest.create = function create(properties) { + return new UpdateDatabaseDdlRequest(properties); + }; + + /** + * Encodes the specified UpdateDatabaseDdlRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest} message UpdateDatabaseDdlRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateDatabaseDdlRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + if (message.statements != null && message.statements.length) + for (var i = 0; i < message.statements.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.statements[i]); + if (message.operationId != null && Object.hasOwnProperty.call(message, "operationId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.operationId); + if (message.protoDescriptors != null && Object.hasOwnProperty.call(message, "protoDescriptors")) + writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.protoDescriptors); + if (message.throughputMode != null && Object.hasOwnProperty.call(message, "throughputMode")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.throughputMode); + return writer; + }; + + /** + * Encodes the specified UpdateDatabaseDdlRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest} message UpdateDatabaseDdlRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateDatabaseDdlRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateDatabaseDdlRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.UpdateDatabaseDdlRequest} UpdateDatabaseDdlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateDatabaseDdlRequest.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.spanner.admin.database.v1.UpdateDatabaseDdlRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + case 2: { + if (!(message.statements && message.statements.length)) + message.statements = []; + message.statements.push(reader.string()); + break; + } + case 3: { + message.operationId = reader.string(); + break; + } + case 4: { + message.protoDescriptors = reader.bytes(); + break; + } + case 5: { + message.throughputMode = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateDatabaseDdlRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.UpdateDatabaseDdlRequest} UpdateDatabaseDdlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateDatabaseDdlRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateDatabaseDdlRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateDatabaseDdlRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.statements != null && message.hasOwnProperty("statements")) { + if (!Array.isArray(message.statements)) + return "statements: array expected"; + for (var i = 0; i < message.statements.length; ++i) + if (!$util.isString(message.statements[i])) + return "statements: string[] expected"; + } + if (message.operationId != null && message.hasOwnProperty("operationId")) + if (!$util.isString(message.operationId)) + return "operationId: string expected"; + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) + if (!(message.protoDescriptors && typeof message.protoDescriptors.length === "number" || $util.isString(message.protoDescriptors))) + return "protoDescriptors: buffer expected"; + if (message.throughputMode != null && message.hasOwnProperty("throughputMode")) + if (typeof message.throughputMode !== "boolean") + return "throughputMode: boolean expected"; + return null; + }; + + /** + * Creates an UpdateDatabaseDdlRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.UpdateDatabaseDdlRequest} UpdateDatabaseDdlRequest + */ + UpdateDatabaseDdlRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.statements) { + if (!Array.isArray(object.statements)) + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.statements: array expected"); + message.statements = []; + for (var i = 0; i < object.statements.length; ++i) + message.statements[i] = String(object.statements[i]); + } + if (object.operationId != null) + message.operationId = String(object.operationId); + if (object.protoDescriptors != null) + if (typeof object.protoDescriptors === "string") + $util.base64.decode(object.protoDescriptors, message.protoDescriptors = $util.newBuffer($util.base64.length(object.protoDescriptors)), 0); + else if (object.protoDescriptors.length >= 0) + message.protoDescriptors = object.protoDescriptors; + if (object.throughputMode != null) + message.throughputMode = Boolean(object.throughputMode); + return message; + }; + + /** + * Creates a plain object from an UpdateDatabaseDdlRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {google.spanner.admin.database.v1.UpdateDatabaseDdlRequest} message UpdateDatabaseDdlRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateDatabaseDdlRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.statements = []; + if (options.defaults) { + object.database = ""; + object.operationId = ""; + if (options.bytes === String) + object.protoDescriptors = ""; + else { + object.protoDescriptors = []; + if (options.bytes !== Array) + object.protoDescriptors = $util.newBuffer(object.protoDescriptors); + } + object.throughputMode = false; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.statements && message.statements.length) { + object.statements = []; + for (var j = 0; j < message.statements.length; ++j) + object.statements[j] = message.statements[j]; + } + if (message.operationId != null && message.hasOwnProperty("operationId")) + object.operationId = message.operationId; + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) + object.protoDescriptors = options.bytes === String ? $util.base64.encode(message.protoDescriptors, 0, message.protoDescriptors.length) : options.bytes === Array ? Array.prototype.slice.call(message.protoDescriptors) : message.protoDescriptors; + if (message.throughputMode != null && message.hasOwnProperty("throughputMode")) + object.throughputMode = message.throughputMode; + return object; + }; + + /** + * Converts this UpdateDatabaseDdlRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateDatabaseDdlRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateDatabaseDdlRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateDatabaseDdlRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.UpdateDatabaseDdlRequest"; + }; + + return UpdateDatabaseDdlRequest; + })(); + + v1.DdlStatementActionInfo = (function() { + + /** + * Properties of a DdlStatementActionInfo. + * @memberof google.spanner.admin.database.v1 + * @interface IDdlStatementActionInfo + * @property {string|null} [action] DdlStatementActionInfo action + * @property {string|null} [entityType] DdlStatementActionInfo entityType + * @property {Array.|null} [entityNames] DdlStatementActionInfo entityNames + */ + + /** + * Constructs a new DdlStatementActionInfo. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a DdlStatementActionInfo. + * @implements IDdlStatementActionInfo + * @constructor + * @param {google.spanner.admin.database.v1.IDdlStatementActionInfo=} [properties] Properties to set + */ + function DdlStatementActionInfo(properties) { + this.entityNames = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DdlStatementActionInfo action. + * @member {string} action + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @instance + */ + DdlStatementActionInfo.prototype.action = ""; + + /** + * DdlStatementActionInfo entityType. + * @member {string} entityType + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @instance + */ + DdlStatementActionInfo.prototype.entityType = ""; + + /** + * DdlStatementActionInfo entityNames. + * @member {Array.} entityNames + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @instance + */ + DdlStatementActionInfo.prototype.entityNames = $util.emptyArray; + + /** + * Creates a new DdlStatementActionInfo instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {google.spanner.admin.database.v1.IDdlStatementActionInfo=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.DdlStatementActionInfo} DdlStatementActionInfo instance + */ + DdlStatementActionInfo.create = function create(properties) { + return new DdlStatementActionInfo(properties); + }; + + /** + * Encodes the specified DdlStatementActionInfo message. Does not implicitly {@link google.spanner.admin.database.v1.DdlStatementActionInfo.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {google.spanner.admin.database.v1.IDdlStatementActionInfo} message DdlStatementActionInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DdlStatementActionInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.action != null && Object.hasOwnProperty.call(message, "action")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.action); + if (message.entityType != null && Object.hasOwnProperty.call(message, "entityType")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.entityType); + if (message.entityNames != null && message.entityNames.length) + for (var i = 0; i < message.entityNames.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.entityNames[i]); + return writer; + }; + + /** + * Encodes the specified DdlStatementActionInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DdlStatementActionInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {google.spanner.admin.database.v1.IDdlStatementActionInfo} message DdlStatementActionInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DdlStatementActionInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DdlStatementActionInfo message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.DdlStatementActionInfo} DdlStatementActionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DdlStatementActionInfo.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.spanner.admin.database.v1.DdlStatementActionInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.action = reader.string(); + break; + } + case 2: { + message.entityType = reader.string(); + break; + } + case 3: { + if (!(message.entityNames && message.entityNames.length)) + message.entityNames = []; + message.entityNames.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DdlStatementActionInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.DdlStatementActionInfo} DdlStatementActionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DdlStatementActionInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DdlStatementActionInfo message. + * @function verify + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DdlStatementActionInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.action != null && message.hasOwnProperty("action")) + if (!$util.isString(message.action)) + return "action: string expected"; + if (message.entityType != null && message.hasOwnProperty("entityType")) + if (!$util.isString(message.entityType)) + return "entityType: string expected"; + if (message.entityNames != null && message.hasOwnProperty("entityNames")) { + if (!Array.isArray(message.entityNames)) + return "entityNames: array expected"; + for (var i = 0; i < message.entityNames.length; ++i) + if (!$util.isString(message.entityNames[i])) + return "entityNames: string[] expected"; + } + return null; + }; + + /** + * Creates a DdlStatementActionInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.DdlStatementActionInfo} DdlStatementActionInfo + */ + DdlStatementActionInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.DdlStatementActionInfo) + return object; + var message = new $root.google.spanner.admin.database.v1.DdlStatementActionInfo(); + if (object.action != null) + message.action = String(object.action); + if (object.entityType != null) + message.entityType = String(object.entityType); + if (object.entityNames) { + if (!Array.isArray(object.entityNames)) + throw TypeError(".google.spanner.admin.database.v1.DdlStatementActionInfo.entityNames: array expected"); + message.entityNames = []; + for (var i = 0; i < object.entityNames.length; ++i) + message.entityNames[i] = String(object.entityNames[i]); + } + return message; + }; + + /** + * Creates a plain object from a DdlStatementActionInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {google.spanner.admin.database.v1.DdlStatementActionInfo} message DdlStatementActionInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DdlStatementActionInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.entityNames = []; + if (options.defaults) { + object.action = ""; + object.entityType = ""; + } + if (message.action != null && message.hasOwnProperty("action")) + object.action = message.action; + if (message.entityType != null && message.hasOwnProperty("entityType")) + object.entityType = message.entityType; + if (message.entityNames && message.entityNames.length) { + object.entityNames = []; + for (var j = 0; j < message.entityNames.length; ++j) + object.entityNames[j] = message.entityNames[j]; + } + return object; + }; + + /** + * Converts this DdlStatementActionInfo to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @instance + * @returns {Object.} JSON object + */ + DdlStatementActionInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DdlStatementActionInfo + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.DdlStatementActionInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DdlStatementActionInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.DdlStatementActionInfo"; + }; + + return DdlStatementActionInfo; + })(); + + v1.UpdateDatabaseDdlMetadata = (function() { + + /** + * Properties of an UpdateDatabaseDdlMetadata. + * @memberof google.spanner.admin.database.v1 + * @interface IUpdateDatabaseDdlMetadata + * @property {string|null} [database] UpdateDatabaseDdlMetadata database + * @property {Array.|null} [statements] UpdateDatabaseDdlMetadata statements + * @property {Array.|null} [commitTimestamps] UpdateDatabaseDdlMetadata commitTimestamps + * @property {boolean|null} [throttled] UpdateDatabaseDdlMetadata throttled + * @property {Array.|null} [progress] UpdateDatabaseDdlMetadata progress + * @property {Array.|null} [actions] UpdateDatabaseDdlMetadata actions + */ + + /** + * Constructs a new UpdateDatabaseDdlMetadata. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an UpdateDatabaseDdlMetadata. + * @implements IUpdateDatabaseDdlMetadata + * @constructor + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata=} [properties] Properties to set + */ + function UpdateDatabaseDdlMetadata(properties) { + this.statements = []; + this.commitTimestamps = []; + this.progress = []; + this.actions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateDatabaseDdlMetadata database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @instance + */ + UpdateDatabaseDdlMetadata.prototype.database = ""; + + /** + * UpdateDatabaseDdlMetadata statements. + * @member {Array.} statements + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @instance + */ + UpdateDatabaseDdlMetadata.prototype.statements = $util.emptyArray; + + /** + * UpdateDatabaseDdlMetadata commitTimestamps. + * @member {Array.} commitTimestamps + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @instance + */ + UpdateDatabaseDdlMetadata.prototype.commitTimestamps = $util.emptyArray; + + /** + * UpdateDatabaseDdlMetadata throttled. + * @member {boolean} throttled + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @instance + */ + UpdateDatabaseDdlMetadata.prototype.throttled = false; + + /** + * UpdateDatabaseDdlMetadata progress. + * @member {Array.} progress + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @instance + */ + UpdateDatabaseDdlMetadata.prototype.progress = $util.emptyArray; + + /** + * UpdateDatabaseDdlMetadata actions. + * @member {Array.} actions + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @instance + */ + UpdateDatabaseDdlMetadata.prototype.actions = $util.emptyArray; + + /** + * Creates a new UpdateDatabaseDdlMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata} UpdateDatabaseDdlMetadata instance + */ + UpdateDatabaseDdlMetadata.create = function create(properties) { + return new UpdateDatabaseDdlMetadata(properties); + }; + + /** + * Encodes the specified UpdateDatabaseDdlMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata} message UpdateDatabaseDdlMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateDatabaseDdlMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + if (message.statements != null && message.statements.length) + for (var i = 0; i < message.statements.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.statements[i]); + if (message.commitTimestamps != null && message.commitTimestamps.length) + for (var i = 0; i < message.commitTimestamps.length; ++i) + $root.google.protobuf.Timestamp.encode(message.commitTimestamps[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.throttled != null && Object.hasOwnProperty.call(message, "throttled")) + writer.uint32(/* id 4, wireType 0 =*/32).bool(message.throttled); + if (message.progress != null && message.progress.length) + for (var i = 0; i < message.progress.length; ++i) + $root.google.spanner.admin.database.v1.OperationProgress.encode(message.progress[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.actions != null && message.actions.length) + for (var i = 0; i < message.actions.length; ++i) + $root.google.spanner.admin.database.v1.DdlStatementActionInfo.encode(message.actions[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateDatabaseDdlMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata} message UpdateDatabaseDdlMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateDatabaseDdlMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateDatabaseDdlMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata} UpdateDatabaseDdlMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateDatabaseDdlMetadata.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.spanner.admin.database.v1.UpdateDatabaseDdlMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + case 2: { + if (!(message.statements && message.statements.length)) + message.statements = []; + message.statements.push(reader.string()); + break; + } + case 3: { + if (!(message.commitTimestamps && message.commitTimestamps.length)) + message.commitTimestamps = []; + message.commitTimestamps.push($root.google.protobuf.Timestamp.decode(reader, reader.uint32())); + break; + } + case 4: { + message.throttled = reader.bool(); + break; + } + case 5: { + if (!(message.progress && message.progress.length)) + message.progress = []; + message.progress.push($root.google.spanner.admin.database.v1.OperationProgress.decode(reader, reader.uint32())); + break; + } + case 6: { + if (!(message.actions && message.actions.length)) + message.actions = []; + message.actions.push($root.google.spanner.admin.database.v1.DdlStatementActionInfo.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateDatabaseDdlMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata} UpdateDatabaseDdlMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateDatabaseDdlMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateDatabaseDdlMetadata message. + * @function verify + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateDatabaseDdlMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.statements != null && message.hasOwnProperty("statements")) { + if (!Array.isArray(message.statements)) + return "statements: array expected"; + for (var i = 0; i < message.statements.length; ++i) + if (!$util.isString(message.statements[i])) + return "statements: string[] expected"; + } + if (message.commitTimestamps != null && message.hasOwnProperty("commitTimestamps")) { + if (!Array.isArray(message.commitTimestamps)) + return "commitTimestamps: array expected"; + for (var i = 0; i < message.commitTimestamps.length; ++i) { + var error = $root.google.protobuf.Timestamp.verify(message.commitTimestamps[i]); + if (error) + return "commitTimestamps." + error; + } + } + if (message.throttled != null && message.hasOwnProperty("throttled")) + if (typeof message.throttled !== "boolean") + return "throttled: boolean expected"; + if (message.progress != null && message.hasOwnProperty("progress")) { + if (!Array.isArray(message.progress)) + return "progress: array expected"; + for (var i = 0; i < message.progress.length; ++i) { + var error = $root.google.spanner.admin.database.v1.OperationProgress.verify(message.progress[i]); + if (error) + return "progress." + error; + } + } + if (message.actions != null && message.hasOwnProperty("actions")) { + if (!Array.isArray(message.actions)) + return "actions: array expected"; + for (var i = 0; i < message.actions.length; ++i) { + var error = $root.google.spanner.admin.database.v1.DdlStatementActionInfo.verify(message.actions[i]); + if (error) + return "actions." + error; + } + } + return null; + }; + + /** + * Creates an UpdateDatabaseDdlMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata} UpdateDatabaseDdlMetadata + */ + UpdateDatabaseDdlMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata) + return object; + var message = new $root.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata(); + if (object.database != null) + message.database = String(object.database); + if (object.statements) { + if (!Array.isArray(object.statements)) + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.statements: array expected"); + message.statements = []; + for (var i = 0; i < object.statements.length; ++i) + message.statements[i] = String(object.statements[i]); + } + if (object.commitTimestamps) { + if (!Array.isArray(object.commitTimestamps)) + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.commitTimestamps: array expected"); + message.commitTimestamps = []; + for (var i = 0; i < object.commitTimestamps.length; ++i) { + if (typeof object.commitTimestamps[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.commitTimestamps: object expected"); + message.commitTimestamps[i] = $root.google.protobuf.Timestamp.fromObject(object.commitTimestamps[i]); + } + } + if (object.throttled != null) + message.throttled = Boolean(object.throttled); + if (object.progress) { + if (!Array.isArray(object.progress)) + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.progress: array expected"); + message.progress = []; + for (var i = 0; i < object.progress.length; ++i) { + if (typeof object.progress[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.progress: object expected"); + message.progress[i] = $root.google.spanner.admin.database.v1.OperationProgress.fromObject(object.progress[i]); + } + } + if (object.actions) { + if (!Array.isArray(object.actions)) + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.actions: array expected"); + message.actions = []; + for (var i = 0; i < object.actions.length; ++i) { + if (typeof object.actions[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.actions: object expected"); + message.actions[i] = $root.google.spanner.admin.database.v1.DdlStatementActionInfo.fromObject(object.actions[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an UpdateDatabaseDdlMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata} message UpdateDatabaseDdlMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateDatabaseDdlMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.statements = []; + object.commitTimestamps = []; + object.progress = []; + object.actions = []; + } + if (options.defaults) { + object.database = ""; + object.throttled = false; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.statements && message.statements.length) { + object.statements = []; + for (var j = 0; j < message.statements.length; ++j) + object.statements[j] = message.statements[j]; + } + if (message.commitTimestamps && message.commitTimestamps.length) { + object.commitTimestamps = []; + for (var j = 0; j < message.commitTimestamps.length; ++j) + object.commitTimestamps[j] = $root.google.protobuf.Timestamp.toObject(message.commitTimestamps[j], options); + } + if (message.throttled != null && message.hasOwnProperty("throttled")) + object.throttled = message.throttled; + if (message.progress && message.progress.length) { + object.progress = []; + for (var j = 0; j < message.progress.length; ++j) + object.progress[j] = $root.google.spanner.admin.database.v1.OperationProgress.toObject(message.progress[j], options); + } + if (message.actions && message.actions.length) { + object.actions = []; + for (var j = 0; j < message.actions.length; ++j) + object.actions[j] = $root.google.spanner.admin.database.v1.DdlStatementActionInfo.toObject(message.actions[j], options); + } + return object; + }; + + /** + * Converts this UpdateDatabaseDdlMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @instance + * @returns {Object.} JSON object + */ + UpdateDatabaseDdlMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateDatabaseDdlMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateDatabaseDdlMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata"; + }; + + return UpdateDatabaseDdlMetadata; + })(); + + v1.DropDatabaseRequest = (function() { + + /** + * Properties of a DropDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IDropDatabaseRequest + * @property {string|null} [database] DropDatabaseRequest database + */ + + /** + * Constructs a new DropDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a DropDatabaseRequest. + * @implements IDropDatabaseRequest + * @constructor + * @param {google.spanner.admin.database.v1.IDropDatabaseRequest=} [properties] Properties to set + */ + function DropDatabaseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DropDatabaseRequest database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @instance + */ + DropDatabaseRequest.prototype.database = ""; + + /** + * Creates a new DropDatabaseRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IDropDatabaseRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.DropDatabaseRequest} DropDatabaseRequest instance + */ + DropDatabaseRequest.create = function create(properties) { + return new DropDatabaseRequest(properties); + }; + + /** + * Encodes the specified DropDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.DropDatabaseRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IDropDatabaseRequest} message DropDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DropDatabaseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + return writer; + }; + + /** + * Encodes the specified DropDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DropDatabaseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IDropDatabaseRequest} message DropDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DropDatabaseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DropDatabaseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.DropDatabaseRequest} DropDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DropDatabaseRequest.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.spanner.admin.database.v1.DropDatabaseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DropDatabaseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.DropDatabaseRequest} DropDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DropDatabaseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DropDatabaseRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DropDatabaseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + return null; + }; + + /** + * Creates a DropDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.DropDatabaseRequest} DropDatabaseRequest + */ + DropDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.DropDatabaseRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.DropDatabaseRequest(); + if (object.database != null) + message.database = String(object.database); + return message; + }; + + /** + * Creates a plain object from a DropDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.DropDatabaseRequest} message DropDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DropDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + return object; + }; + + /** + * Converts this DropDatabaseRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + DropDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DropDatabaseRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.DropDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DropDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.DropDatabaseRequest"; + }; + + return DropDatabaseRequest; + })(); + + v1.GetDatabaseDdlRequest = (function() { + + /** + * Properties of a GetDatabaseDdlRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IGetDatabaseDdlRequest + * @property {string|null} [database] GetDatabaseDdlRequest database + */ + + /** + * Constructs a new GetDatabaseDdlRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a GetDatabaseDdlRequest. + * @implements IGetDatabaseDdlRequest + * @constructor + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlRequest=} [properties] Properties to set + */ + function GetDatabaseDdlRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetDatabaseDdlRequest database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @instance + */ + GetDatabaseDdlRequest.prototype.database = ""; + + /** + * Creates a new GetDatabaseDdlRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.GetDatabaseDdlRequest} GetDatabaseDdlRequest instance + */ + GetDatabaseDdlRequest.create = function create(properties) { + return new GetDatabaseDdlRequest(properties); + }; + + /** + * Encodes the specified GetDatabaseDdlRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlRequest} message GetDatabaseDdlRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetDatabaseDdlRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + return writer; + }; + + /** + * Encodes the specified GetDatabaseDdlRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlRequest} message GetDatabaseDdlRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetDatabaseDdlRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetDatabaseDdlRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.GetDatabaseDdlRequest} GetDatabaseDdlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetDatabaseDdlRequest.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.spanner.admin.database.v1.GetDatabaseDdlRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetDatabaseDdlRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.GetDatabaseDdlRequest} GetDatabaseDdlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetDatabaseDdlRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetDatabaseDdlRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetDatabaseDdlRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + return null; + }; + + /** + * Creates a GetDatabaseDdlRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.GetDatabaseDdlRequest} GetDatabaseDdlRequest + */ + GetDatabaseDdlRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.GetDatabaseDdlRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.GetDatabaseDdlRequest(); + if (object.database != null) + message.database = String(object.database); + return message; + }; + + /** + * Creates a plain object from a GetDatabaseDdlRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {google.spanner.admin.database.v1.GetDatabaseDdlRequest} message GetDatabaseDdlRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetDatabaseDdlRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + return object; + }; + + /** + * Converts this GetDatabaseDdlRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @instance + * @returns {Object.} JSON object + */ + GetDatabaseDdlRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetDatabaseDdlRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetDatabaseDdlRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.GetDatabaseDdlRequest"; + }; + + return GetDatabaseDdlRequest; + })(); + + v1.GetDatabaseDdlResponse = (function() { + + /** + * Properties of a GetDatabaseDdlResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IGetDatabaseDdlResponse + * @property {Array.|null} [statements] GetDatabaseDdlResponse statements + * @property {Uint8Array|null} [protoDescriptors] GetDatabaseDdlResponse protoDescriptors + */ + + /** + * Constructs a new GetDatabaseDdlResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a GetDatabaseDdlResponse. + * @implements IGetDatabaseDdlResponse + * @constructor + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlResponse=} [properties] Properties to set + */ + function GetDatabaseDdlResponse(properties) { + this.statements = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetDatabaseDdlResponse statements. + * @member {Array.} statements + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @instance + */ + GetDatabaseDdlResponse.prototype.statements = $util.emptyArray; + + /** + * GetDatabaseDdlResponse protoDescriptors. + * @member {Uint8Array} protoDescriptors + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @instance + */ + GetDatabaseDdlResponse.prototype.protoDescriptors = $util.newBuffer([]); + + /** + * Creates a new GetDatabaseDdlResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.GetDatabaseDdlResponse} GetDatabaseDdlResponse instance + */ + GetDatabaseDdlResponse.create = function create(properties) { + return new GetDatabaseDdlResponse(properties); + }; + + /** + * Encodes the specified GetDatabaseDdlResponse message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlResponse} message GetDatabaseDdlResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetDatabaseDdlResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.statements != null && message.statements.length) + for (var i = 0; i < message.statements.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.statements[i]); + if (message.protoDescriptors != null && Object.hasOwnProperty.call(message, "protoDescriptors")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.protoDescriptors); + return writer; + }; + + /** + * Encodes the specified GetDatabaseDdlResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {google.spanner.admin.database.v1.IGetDatabaseDdlResponse} message GetDatabaseDdlResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetDatabaseDdlResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetDatabaseDdlResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.GetDatabaseDdlResponse} GetDatabaseDdlResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetDatabaseDdlResponse.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.spanner.admin.database.v1.GetDatabaseDdlResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.statements && message.statements.length)) + message.statements = []; + message.statements.push(reader.string()); + break; + } + case 2: { + message.protoDescriptors = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetDatabaseDdlResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.GetDatabaseDdlResponse} GetDatabaseDdlResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetDatabaseDdlResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetDatabaseDdlResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetDatabaseDdlResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.statements != null && message.hasOwnProperty("statements")) { + if (!Array.isArray(message.statements)) + return "statements: array expected"; + for (var i = 0; i < message.statements.length; ++i) + if (!$util.isString(message.statements[i])) + return "statements: string[] expected"; + } + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) + if (!(message.protoDescriptors && typeof message.protoDescriptors.length === "number" || $util.isString(message.protoDescriptors))) + return "protoDescriptors: buffer expected"; + return null; + }; + + /** + * Creates a GetDatabaseDdlResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.GetDatabaseDdlResponse} GetDatabaseDdlResponse + */ + GetDatabaseDdlResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.GetDatabaseDdlResponse) + return object; + var message = new $root.google.spanner.admin.database.v1.GetDatabaseDdlResponse(); + if (object.statements) { + if (!Array.isArray(object.statements)) + throw TypeError(".google.spanner.admin.database.v1.GetDatabaseDdlResponse.statements: array expected"); + message.statements = []; + for (var i = 0; i < object.statements.length; ++i) + message.statements[i] = String(object.statements[i]); + } + if (object.protoDescriptors != null) + if (typeof object.protoDescriptors === "string") + $util.base64.decode(object.protoDescriptors, message.protoDescriptors = $util.newBuffer($util.base64.length(object.protoDescriptors)), 0); + else if (object.protoDescriptors.length >= 0) + message.protoDescriptors = object.protoDescriptors; + return message; + }; + + /** + * Creates a plain object from a GetDatabaseDdlResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {google.spanner.admin.database.v1.GetDatabaseDdlResponse} message GetDatabaseDdlResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetDatabaseDdlResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.statements = []; + if (options.defaults) + if (options.bytes === String) + object.protoDescriptors = ""; + else { + object.protoDescriptors = []; + if (options.bytes !== Array) + object.protoDescriptors = $util.newBuffer(object.protoDescriptors); + } + if (message.statements && message.statements.length) { + object.statements = []; + for (var j = 0; j < message.statements.length; ++j) + object.statements[j] = message.statements[j]; + } + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) + object.protoDescriptors = options.bytes === String ? $util.base64.encode(message.protoDescriptors, 0, message.protoDescriptors.length) : options.bytes === Array ? Array.prototype.slice.call(message.protoDescriptors) : message.protoDescriptors; + return object; + }; + + /** + * Converts this GetDatabaseDdlResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @instance + * @returns {Object.} JSON object + */ + GetDatabaseDdlResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetDatabaseDdlResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.GetDatabaseDdlResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetDatabaseDdlResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.GetDatabaseDdlResponse"; + }; + + return GetDatabaseDdlResponse; + })(); + + v1.ListDatabaseOperationsRequest = (function() { + + /** + * Properties of a ListDatabaseOperationsRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IListDatabaseOperationsRequest + * @property {string|null} [parent] ListDatabaseOperationsRequest parent + * @property {string|null} [filter] ListDatabaseOperationsRequest filter + * @property {number|null} [pageSize] ListDatabaseOperationsRequest pageSize + * @property {string|null} [pageToken] ListDatabaseOperationsRequest pageToken + */ + + /** + * Constructs a new ListDatabaseOperationsRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListDatabaseOperationsRequest. + * @implements IListDatabaseOperationsRequest + * @constructor + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsRequest=} [properties] Properties to set + */ + function ListDatabaseOperationsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDatabaseOperationsRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @instance + */ + ListDatabaseOperationsRequest.prototype.parent = ""; + + /** + * ListDatabaseOperationsRequest filter. + * @member {string} filter + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @instance + */ + ListDatabaseOperationsRequest.prototype.filter = ""; + + /** + * ListDatabaseOperationsRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @instance + */ + ListDatabaseOperationsRequest.prototype.pageSize = 0; + + /** + * ListDatabaseOperationsRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @instance + */ + ListDatabaseOperationsRequest.prototype.pageToken = ""; + + /** + * Creates a new ListDatabaseOperationsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListDatabaseOperationsRequest} ListDatabaseOperationsRequest instance + */ + ListDatabaseOperationsRequest.create = function create(properties) { + return new ListDatabaseOperationsRequest(properties); + }; + + /** + * Encodes the specified ListDatabaseOperationsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsRequest} message ListDatabaseOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabaseOperationsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListDatabaseOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsRequest} message ListDatabaseOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabaseOperationsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListDatabaseOperationsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListDatabaseOperationsRequest} ListDatabaseOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabaseOperationsRequest.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.spanner.admin.database.v1.ListDatabaseOperationsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListDatabaseOperationsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListDatabaseOperationsRequest} ListDatabaseOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabaseOperationsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListDatabaseOperationsRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListDatabaseOperationsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListDatabaseOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListDatabaseOperationsRequest} ListDatabaseOperationsRequest + */ + ListDatabaseOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListDatabaseOperationsRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.ListDatabaseOperationsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListDatabaseOperationsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {google.spanner.admin.database.v1.ListDatabaseOperationsRequest} message ListDatabaseOperationsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDatabaseOperationsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListDatabaseOperationsRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @instance + * @returns {Object.} JSON object + */ + ListDatabaseOperationsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDatabaseOperationsRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDatabaseOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListDatabaseOperationsRequest"; + }; + + return ListDatabaseOperationsRequest; + })(); + + v1.ListDatabaseOperationsResponse = (function() { + + /** + * Properties of a ListDatabaseOperationsResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IListDatabaseOperationsResponse + * @property {Array.|null} [operations] ListDatabaseOperationsResponse operations + * @property {string|null} [nextPageToken] ListDatabaseOperationsResponse nextPageToken + */ + + /** + * Constructs a new ListDatabaseOperationsResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListDatabaseOperationsResponse. + * @implements IListDatabaseOperationsResponse + * @constructor + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsResponse=} [properties] Properties to set + */ + function ListDatabaseOperationsResponse(properties) { + this.operations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDatabaseOperationsResponse operations. + * @member {Array.} operations + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @instance + */ + ListDatabaseOperationsResponse.prototype.operations = $util.emptyArray; + + /** + * ListDatabaseOperationsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @instance + */ + ListDatabaseOperationsResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListDatabaseOperationsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListDatabaseOperationsResponse} ListDatabaseOperationsResponse instance + */ + ListDatabaseOperationsResponse.create = function create(properties) { + return new ListDatabaseOperationsResponse(properties); + }; + + /** + * Encodes the specified ListDatabaseOperationsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsResponse} message ListDatabaseOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabaseOperationsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.operations != null && message.operations.length) + for (var i = 0; i < message.operations.length; ++i) + $root.google.longrunning.Operation.encode(message.operations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListDatabaseOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseOperationsResponse} message ListDatabaseOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabaseOperationsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListDatabaseOperationsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListDatabaseOperationsResponse} ListDatabaseOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabaseOperationsResponse.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.spanner.admin.database.v1.ListDatabaseOperationsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.operations && message.operations.length)) + message.operations = []; + message.operations.push($root.google.longrunning.Operation.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListDatabaseOperationsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListDatabaseOperationsResponse} ListDatabaseOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabaseOperationsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListDatabaseOperationsResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListDatabaseOperationsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.operations != null && message.hasOwnProperty("operations")) { + if (!Array.isArray(message.operations)) + return "operations: array expected"; + for (var i = 0; i < message.operations.length; ++i) { + var error = $root.google.longrunning.Operation.verify(message.operations[i]); + if (error) + return "operations." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListDatabaseOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListDatabaseOperationsResponse} ListDatabaseOperationsResponse + */ + ListDatabaseOperationsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListDatabaseOperationsResponse) + return object; + var message = new $root.google.spanner.admin.database.v1.ListDatabaseOperationsResponse(); + if (object.operations) { + if (!Array.isArray(object.operations)) + throw TypeError(".google.spanner.admin.database.v1.ListDatabaseOperationsResponse.operations: array expected"); + message.operations = []; + for (var i = 0; i < object.operations.length; ++i) { + if (typeof object.operations[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.ListDatabaseOperationsResponse.operations: object expected"); + message.operations[i] = $root.google.longrunning.Operation.fromObject(object.operations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListDatabaseOperationsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {google.spanner.admin.database.v1.ListDatabaseOperationsResponse} message ListDatabaseOperationsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDatabaseOperationsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.operations = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.operations && message.operations.length) { + object.operations = []; + for (var j = 0; j < message.operations.length; ++j) + object.operations[j] = $root.google.longrunning.Operation.toObject(message.operations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListDatabaseOperationsResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @instance + * @returns {Object.} JSON object + */ + ListDatabaseOperationsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDatabaseOperationsResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListDatabaseOperationsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDatabaseOperationsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListDatabaseOperationsResponse"; + }; + + return ListDatabaseOperationsResponse; + })(); + + v1.RestoreDatabaseRequest = (function() { + + /** + * Properties of a RestoreDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IRestoreDatabaseRequest + * @property {string|null} [parent] RestoreDatabaseRequest parent + * @property {string|null} [databaseId] RestoreDatabaseRequest databaseId + * @property {string|null} [backup] RestoreDatabaseRequest backup + * @property {google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig|null} [encryptionConfig] RestoreDatabaseRequest encryptionConfig + */ + + /** + * Constructs a new RestoreDatabaseRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a RestoreDatabaseRequest. + * @implements IRestoreDatabaseRequest + * @constructor + * @param {google.spanner.admin.database.v1.IRestoreDatabaseRequest=} [properties] Properties to set + */ + function RestoreDatabaseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RestoreDatabaseRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.parent = ""; + + /** + * RestoreDatabaseRequest databaseId. + * @member {string} databaseId + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.databaseId = ""; + + /** + * RestoreDatabaseRequest backup. + * @member {string|null|undefined} backup + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.backup = null; + + /** + * RestoreDatabaseRequest encryptionConfig. + * @member {google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @instance + */ + RestoreDatabaseRequest.prototype.encryptionConfig = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RestoreDatabaseRequest source. + * @member {"backup"|undefined} source + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @instance + */ + Object.defineProperty(RestoreDatabaseRequest.prototype, "source", { + get: $util.oneOfGetter($oneOfFields = ["backup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new RestoreDatabaseRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.RestoreDatabaseRequest} RestoreDatabaseRequest instance + */ + RestoreDatabaseRequest.create = function create(properties) { + return new RestoreDatabaseRequest(properties); + }; + + /** + * Encodes the specified RestoreDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseRequest} message RestoreDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreDatabaseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.databaseId); + if (message.backup != null && Object.hasOwnProperty.call(message, "backup")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.backup); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RestoreDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseRequest} message RestoreDatabaseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreDatabaseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RestoreDatabaseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.RestoreDatabaseRequest} RestoreDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreDatabaseRequest.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.spanner.admin.database.v1.RestoreDatabaseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.databaseId = reader.string(); + break; + } + case 3: { + message.backup = reader.string(); + break; + } + case 4: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RestoreDatabaseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.RestoreDatabaseRequest} RestoreDatabaseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreDatabaseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RestoreDatabaseRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RestoreDatabaseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isString(message.databaseId)) + return "databaseId: string expected"; + if (message.backup != null && message.hasOwnProperty("backup")) { + properties.source = 1; + if (!$util.isString(message.backup)) + return "backup: string expected"; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + return null; + }; + + /** + * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.RestoreDatabaseRequest} RestoreDatabaseRequest + */ + RestoreDatabaseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.RestoreDatabaseRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.RestoreDatabaseRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + if (object.backup != null) + message.backup = String(object.backup); + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.admin.database.v1.RestoreDatabaseRequest.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.fromObject(object.encryptionConfig); + } + return message; + }; + + /** + * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {google.spanner.admin.database.v1.RestoreDatabaseRequest} message RestoreDatabaseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RestoreDatabaseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.databaseId = ""; + object.encryptionConfig = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + if (message.backup != null && message.hasOwnProperty("backup")) { + object.backup = message.backup; + if (options.oneofs) + object.source = "backup"; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.toObject(message.encryptionConfig, options); + return object; + }; + + /** + * Converts this RestoreDatabaseRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @instance + * @returns {Object.} JSON object + */ + RestoreDatabaseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RestoreDatabaseRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.RestoreDatabaseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RestoreDatabaseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.RestoreDatabaseRequest"; + }; + + return RestoreDatabaseRequest; + })(); + + v1.RestoreDatabaseEncryptionConfig = (function() { + + /** + * Properties of a RestoreDatabaseEncryptionConfig. + * @memberof google.spanner.admin.database.v1 + * @interface IRestoreDatabaseEncryptionConfig + * @property {google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType|null} [encryptionType] RestoreDatabaseEncryptionConfig encryptionType + * @property {string|null} [kmsKeyName] RestoreDatabaseEncryptionConfig kmsKeyName + * @property {Array.|null} [kmsKeyNames] RestoreDatabaseEncryptionConfig kmsKeyNames + */ + + /** + * Constructs a new RestoreDatabaseEncryptionConfig. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a RestoreDatabaseEncryptionConfig. + * @implements IRestoreDatabaseEncryptionConfig + * @constructor + * @param {google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig=} [properties] Properties to set + */ + function RestoreDatabaseEncryptionConfig(properties) { + this.kmsKeyNames = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RestoreDatabaseEncryptionConfig encryptionType. + * @member {google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType} encryptionType + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @instance + */ + RestoreDatabaseEncryptionConfig.prototype.encryptionType = 0; + + /** + * RestoreDatabaseEncryptionConfig kmsKeyName. + * @member {string} kmsKeyName + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @instance + */ + RestoreDatabaseEncryptionConfig.prototype.kmsKeyName = ""; + + /** + * RestoreDatabaseEncryptionConfig kmsKeyNames. + * @member {Array.} kmsKeyNames + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @instance + */ + RestoreDatabaseEncryptionConfig.prototype.kmsKeyNames = $util.emptyArray; + + /** + * Creates a new RestoreDatabaseEncryptionConfig instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig} RestoreDatabaseEncryptionConfig instance + */ + RestoreDatabaseEncryptionConfig.create = function create(properties) { + return new RestoreDatabaseEncryptionConfig(properties); + }; + + /** + * Encodes the specified RestoreDatabaseEncryptionConfig message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig} message RestoreDatabaseEncryptionConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreDatabaseEncryptionConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.encryptionType != null && Object.hasOwnProperty.call(message, "encryptionType")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.encryptionType); + if (message.kmsKeyName != null && Object.hasOwnProperty.call(message, "kmsKeyName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.kmsKeyName); + if (message.kmsKeyNames != null && message.kmsKeyNames.length) + for (var i = 0; i < message.kmsKeyNames.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.kmsKeyNames[i]); + return writer; + }; + + /** + * Encodes the specified RestoreDatabaseEncryptionConfig message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig} message RestoreDatabaseEncryptionConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreDatabaseEncryptionConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RestoreDatabaseEncryptionConfig message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig} RestoreDatabaseEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreDatabaseEncryptionConfig.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.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.encryptionType = reader.int32(); + break; + } + case 2: { + message.kmsKeyName = reader.string(); + break; + } + case 3: { + if (!(message.kmsKeyNames && message.kmsKeyNames.length)) + message.kmsKeyNames = []; + message.kmsKeyNames.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RestoreDatabaseEncryptionConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig} RestoreDatabaseEncryptionConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreDatabaseEncryptionConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RestoreDatabaseEncryptionConfig message. + * @function verify + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RestoreDatabaseEncryptionConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.encryptionType != null && message.hasOwnProperty("encryptionType")) + switch (message.encryptionType) { + default: + return "encryptionType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + if (!$util.isString(message.kmsKeyName)) + return "kmsKeyName: string expected"; + if (message.kmsKeyNames != null && message.hasOwnProperty("kmsKeyNames")) { + if (!Array.isArray(message.kmsKeyNames)) + return "kmsKeyNames: array expected"; + for (var i = 0; i < message.kmsKeyNames.length; ++i) + if (!$util.isString(message.kmsKeyNames[i])) + return "kmsKeyNames: string[] expected"; + } + return null; + }; + + /** + * Creates a RestoreDatabaseEncryptionConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig} RestoreDatabaseEncryptionConfig + */ + RestoreDatabaseEncryptionConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig) + return object; + var message = new $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig(); + switch (object.encryptionType) { + default: + if (typeof object.encryptionType === "number") { + message.encryptionType = object.encryptionType; + break; + } + break; + case "ENCRYPTION_TYPE_UNSPECIFIED": + case 0: + message.encryptionType = 0; + break; + case "USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION": + case 1: + message.encryptionType = 1; + break; + case "GOOGLE_DEFAULT_ENCRYPTION": + case 2: + message.encryptionType = 2; + break; + case "CUSTOMER_MANAGED_ENCRYPTION": + case 3: + message.encryptionType = 3; + break; + } + if (object.kmsKeyName != null) + message.kmsKeyName = String(object.kmsKeyName); + if (object.kmsKeyNames) { + if (!Array.isArray(object.kmsKeyNames)) + throw TypeError(".google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.kmsKeyNames: array expected"); + message.kmsKeyNames = []; + for (var i = 0; i < object.kmsKeyNames.length; ++i) + message.kmsKeyNames[i] = String(object.kmsKeyNames[i]); + } + return message; + }; + + /** + * Creates a plain object from a RestoreDatabaseEncryptionConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig} message RestoreDatabaseEncryptionConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RestoreDatabaseEncryptionConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.kmsKeyNames = []; + if (options.defaults) { + object.encryptionType = options.enums === String ? "ENCRYPTION_TYPE_UNSPECIFIED" : 0; + object.kmsKeyName = ""; + } + if (message.encryptionType != null && message.hasOwnProperty("encryptionType")) + object.encryptionType = options.enums === String ? $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType[message.encryptionType] === undefined ? message.encryptionType : $root.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType[message.encryptionType] : message.encryptionType; + if (message.kmsKeyName != null && message.hasOwnProperty("kmsKeyName")) + object.kmsKeyName = message.kmsKeyName; + if (message.kmsKeyNames && message.kmsKeyNames.length) { + object.kmsKeyNames = []; + for (var j = 0; j < message.kmsKeyNames.length; ++j) + object.kmsKeyNames[j] = message.kmsKeyNames[j]; + } + return object; + }; + + /** + * Converts this RestoreDatabaseEncryptionConfig to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @instance + * @returns {Object.} JSON object + */ + RestoreDatabaseEncryptionConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RestoreDatabaseEncryptionConfig + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RestoreDatabaseEncryptionConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig"; + }; + + /** + * EncryptionType enum. + * @name google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType + * @enum {number} + * @property {number} ENCRYPTION_TYPE_UNSPECIFIED=0 ENCRYPTION_TYPE_UNSPECIFIED value + * @property {number} USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION=1 USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION value + * @property {number} GOOGLE_DEFAULT_ENCRYPTION=2 GOOGLE_DEFAULT_ENCRYPTION value + * @property {number} CUSTOMER_MANAGED_ENCRYPTION=3 CUSTOMER_MANAGED_ENCRYPTION value + */ + RestoreDatabaseEncryptionConfig.EncryptionType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENCRYPTION_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION"] = 1; + values[valuesById[2] = "GOOGLE_DEFAULT_ENCRYPTION"] = 2; + values[valuesById[3] = "CUSTOMER_MANAGED_ENCRYPTION"] = 3; + return values; + })(); + + return RestoreDatabaseEncryptionConfig; + })(); + + v1.RestoreDatabaseMetadata = (function() { + + /** + * Properties of a RestoreDatabaseMetadata. + * @memberof google.spanner.admin.database.v1 + * @interface IRestoreDatabaseMetadata + * @property {string|null} [name] RestoreDatabaseMetadata name + * @property {google.spanner.admin.database.v1.RestoreSourceType|null} [sourceType] RestoreDatabaseMetadata sourceType + * @property {google.spanner.admin.database.v1.IBackupInfo|null} [backupInfo] RestoreDatabaseMetadata backupInfo + * @property {google.spanner.admin.database.v1.IOperationProgress|null} [progress] RestoreDatabaseMetadata progress + * @property {google.protobuf.ITimestamp|null} [cancelTime] RestoreDatabaseMetadata cancelTime + * @property {string|null} [optimizeDatabaseOperationName] RestoreDatabaseMetadata optimizeDatabaseOperationName + */ + + /** + * Constructs a new RestoreDatabaseMetadata. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a RestoreDatabaseMetadata. + * @implements IRestoreDatabaseMetadata + * @constructor + * @param {google.spanner.admin.database.v1.IRestoreDatabaseMetadata=} [properties] Properties to set + */ + function RestoreDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RestoreDatabaseMetadata name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.name = ""; + + /** + * RestoreDatabaseMetadata sourceType. + * @member {google.spanner.admin.database.v1.RestoreSourceType} sourceType + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.sourceType = 0; + + /** + * RestoreDatabaseMetadata backupInfo. + * @member {google.spanner.admin.database.v1.IBackupInfo|null|undefined} backupInfo + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.backupInfo = null; + + /** + * RestoreDatabaseMetadata progress. + * @member {google.spanner.admin.database.v1.IOperationProgress|null|undefined} progress + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.progress = null; + + /** + * RestoreDatabaseMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.cancelTime = null; + + /** + * RestoreDatabaseMetadata optimizeDatabaseOperationName. + * @member {string} optimizeDatabaseOperationName + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @instance + */ + RestoreDatabaseMetadata.prototype.optimizeDatabaseOperationName = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RestoreDatabaseMetadata sourceInfo. + * @member {"backupInfo"|undefined} sourceInfo + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @instance + */ + Object.defineProperty(RestoreDatabaseMetadata.prototype, "sourceInfo", { + get: $util.oneOfGetter($oneOfFields = ["backupInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new RestoreDatabaseMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.RestoreDatabaseMetadata} RestoreDatabaseMetadata instance + */ + RestoreDatabaseMetadata.create = function create(properties) { + return new RestoreDatabaseMetadata(properties); + }; + + /** + * Encodes the specified RestoreDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseMetadata} message RestoreDatabaseMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreDatabaseMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.sourceType != null && Object.hasOwnProperty.call(message, "sourceType")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.sourceType); + if (message.backupInfo != null && Object.hasOwnProperty.call(message, "backupInfo")) + $root.google.spanner.admin.database.v1.BackupInfo.encode(message.backupInfo, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.spanner.admin.database.v1.OperationProgress.encode(message.progress, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.optimizeDatabaseOperationName != null && Object.hasOwnProperty.call(message, "optimizeDatabaseOperationName")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.optimizeDatabaseOperationName); + return writer; + }; + + /** + * Encodes the specified RestoreDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IRestoreDatabaseMetadata} message RestoreDatabaseMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreDatabaseMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RestoreDatabaseMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.RestoreDatabaseMetadata} RestoreDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreDatabaseMetadata.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.spanner.admin.database.v1.RestoreDatabaseMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.sourceType = reader.int32(); + break; + } + case 3: { + message.backupInfo = $root.google.spanner.admin.database.v1.BackupInfo.decode(reader, reader.uint32()); + break; + } + case 4: { + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.decode(reader, reader.uint32()); + break; + } + case 5: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 6: { + message.optimizeDatabaseOperationName = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RestoreDatabaseMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.RestoreDatabaseMetadata} RestoreDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreDatabaseMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RestoreDatabaseMetadata message. + * @function verify + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RestoreDatabaseMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.sourceType != null && message.hasOwnProperty("sourceType")) + switch (message.sourceType) { + default: + return "sourceType: enum value expected"; + case 0: + case 1: + break; + } + if (message.backupInfo != null && message.hasOwnProperty("backupInfo")) { + properties.sourceInfo = 1; + { + var error = $root.google.spanner.admin.database.v1.BackupInfo.verify(message.backupInfo); + if (error) + return "backupInfo." + error; + } + } + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.spanner.admin.database.v1.OperationProgress.verify(message.progress); + if (error) + return "progress." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + if (message.optimizeDatabaseOperationName != null && message.hasOwnProperty("optimizeDatabaseOperationName")) + if (!$util.isString(message.optimizeDatabaseOperationName)) + return "optimizeDatabaseOperationName: string expected"; + return null; + }; + + /** + * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.RestoreDatabaseMetadata} RestoreDatabaseMetadata + */ + RestoreDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.RestoreDatabaseMetadata) + return object; + var message = new $root.google.spanner.admin.database.v1.RestoreDatabaseMetadata(); + if (object.name != null) + message.name = String(object.name); + switch (object.sourceType) { + default: + if (typeof object.sourceType === "number") { + message.sourceType = object.sourceType; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.sourceType = 0; + break; + case "BACKUP": + case 1: + message.sourceType = 1; + break; + } + if (object.backupInfo != null) { + if (typeof object.backupInfo !== "object") + throw TypeError(".google.spanner.admin.database.v1.RestoreDatabaseMetadata.backupInfo: object expected"); + message.backupInfo = $root.google.spanner.admin.database.v1.BackupInfo.fromObject(object.backupInfo); + } + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.spanner.admin.database.v1.RestoreDatabaseMetadata.progress: object expected"); + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.fromObject(object.progress); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.RestoreDatabaseMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + if (object.optimizeDatabaseOperationName != null) + message.optimizeDatabaseOperationName = String(object.optimizeDatabaseOperationName); + return message; + }; + + /** + * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.RestoreDatabaseMetadata} message RestoreDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RestoreDatabaseMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.sourceType = options.enums === String ? "TYPE_UNSPECIFIED" : 0; + object.progress = null; + object.cancelTime = null; + object.optimizeDatabaseOperationName = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.sourceType != null && message.hasOwnProperty("sourceType")) + object.sourceType = options.enums === String ? $root.google.spanner.admin.database.v1.RestoreSourceType[message.sourceType] === undefined ? message.sourceType : $root.google.spanner.admin.database.v1.RestoreSourceType[message.sourceType] : message.sourceType; + if (message.backupInfo != null && message.hasOwnProperty("backupInfo")) { + object.backupInfo = $root.google.spanner.admin.database.v1.BackupInfo.toObject(message.backupInfo, options); + if (options.oneofs) + object.sourceInfo = "backupInfo"; + } + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.spanner.admin.database.v1.OperationProgress.toObject(message.progress, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + if (message.optimizeDatabaseOperationName != null && message.hasOwnProperty("optimizeDatabaseOperationName")) + object.optimizeDatabaseOperationName = message.optimizeDatabaseOperationName; + return object; + }; + + /** + * Converts this RestoreDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + RestoreDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RestoreDatabaseMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.RestoreDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RestoreDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.RestoreDatabaseMetadata"; + }; + + return RestoreDatabaseMetadata; + })(); + + v1.OptimizeRestoredDatabaseMetadata = (function() { + + /** + * Properties of an OptimizeRestoredDatabaseMetadata. + * @memberof google.spanner.admin.database.v1 + * @interface IOptimizeRestoredDatabaseMetadata + * @property {string|null} [name] OptimizeRestoredDatabaseMetadata name + * @property {google.spanner.admin.database.v1.IOperationProgress|null} [progress] OptimizeRestoredDatabaseMetadata progress + */ + + /** + * Constructs a new OptimizeRestoredDatabaseMetadata. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an OptimizeRestoredDatabaseMetadata. + * @implements IOptimizeRestoredDatabaseMetadata + * @constructor + * @param {google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata=} [properties] Properties to set + */ + function OptimizeRestoredDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OptimizeRestoredDatabaseMetadata name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @instance + */ + OptimizeRestoredDatabaseMetadata.prototype.name = ""; + + /** + * OptimizeRestoredDatabaseMetadata progress. + * @member {google.spanner.admin.database.v1.IOperationProgress|null|undefined} progress + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @instance + */ + OptimizeRestoredDatabaseMetadata.prototype.progress = null; + + /** + * Creates a new OptimizeRestoredDatabaseMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata} OptimizeRestoredDatabaseMetadata instance + */ + OptimizeRestoredDatabaseMetadata.create = function create(properties) { + return new OptimizeRestoredDatabaseMetadata(properties); + }; + + /** + * Encodes the specified OptimizeRestoredDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata} message OptimizeRestoredDatabaseMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OptimizeRestoredDatabaseMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.spanner.admin.database.v1.OperationProgress.encode(message.progress, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified OptimizeRestoredDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata} message OptimizeRestoredDatabaseMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OptimizeRestoredDatabaseMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an OptimizeRestoredDatabaseMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata} OptimizeRestoredDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OptimizeRestoredDatabaseMetadata.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.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an OptimizeRestoredDatabaseMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata} OptimizeRestoredDatabaseMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OptimizeRestoredDatabaseMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an OptimizeRestoredDatabaseMetadata message. + * @function verify + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + OptimizeRestoredDatabaseMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.spanner.admin.database.v1.OperationProgress.verify(message.progress); + if (error) + return "progress." + error; + } + return null; + }; + + /** + * Creates an OptimizeRestoredDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata} OptimizeRestoredDatabaseMetadata + */ + OptimizeRestoredDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata) + return object; + var message = new $root.google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata(); + if (object.name != null) + message.name = String(object.name); + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata.progress: object expected"); + message.progress = $root.google.spanner.admin.database.v1.OperationProgress.fromObject(object.progress); + } + return message; + }; + + /** + * Creates a plain object from an OptimizeRestoredDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata} message OptimizeRestoredDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OptimizeRestoredDatabaseMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.progress = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.spanner.admin.database.v1.OperationProgress.toObject(message.progress, options); + return object; + }; + + /** + * Converts this OptimizeRestoredDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + OptimizeRestoredDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OptimizeRestoredDatabaseMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OptimizeRestoredDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata"; + }; + + return OptimizeRestoredDatabaseMetadata; + })(); + + /** + * RestoreSourceType enum. + * @name google.spanner.admin.database.v1.RestoreSourceType + * @enum {number} + * @property {number} TYPE_UNSPECIFIED=0 TYPE_UNSPECIFIED value + * @property {number} BACKUP=1 BACKUP value + */ + v1.RestoreSourceType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "BACKUP"] = 1; + return values; + })(); + + v1.DatabaseRole = (function() { + + /** + * Properties of a DatabaseRole. + * @memberof google.spanner.admin.database.v1 + * @interface IDatabaseRole + * @property {string|null} [name] DatabaseRole name + */ + + /** + * Constructs a new DatabaseRole. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a DatabaseRole. + * @implements IDatabaseRole + * @constructor + * @param {google.spanner.admin.database.v1.IDatabaseRole=} [properties] Properties to set + */ + function DatabaseRole(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DatabaseRole name. + * @member {string} name + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @instance + */ + DatabaseRole.prototype.name = ""; + + /** + * Creates a new DatabaseRole instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {google.spanner.admin.database.v1.IDatabaseRole=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.DatabaseRole} DatabaseRole instance + */ + DatabaseRole.create = function create(properties) { + return new DatabaseRole(properties); + }; + + /** + * Encodes the specified DatabaseRole message. Does not implicitly {@link google.spanner.admin.database.v1.DatabaseRole.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {google.spanner.admin.database.v1.IDatabaseRole} message DatabaseRole message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DatabaseRole.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified DatabaseRole message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DatabaseRole.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {google.spanner.admin.database.v1.IDatabaseRole} message DatabaseRole message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DatabaseRole.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DatabaseRole message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.DatabaseRole} DatabaseRole + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DatabaseRole.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.spanner.admin.database.v1.DatabaseRole(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DatabaseRole message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.DatabaseRole} DatabaseRole + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DatabaseRole.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DatabaseRole message. + * @function verify + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DatabaseRole.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a DatabaseRole message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.DatabaseRole} DatabaseRole + */ + DatabaseRole.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.DatabaseRole) + return object; + var message = new $root.google.spanner.admin.database.v1.DatabaseRole(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DatabaseRole message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {google.spanner.admin.database.v1.DatabaseRole} message DatabaseRole + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DatabaseRole.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DatabaseRole to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @instance + * @returns {Object.} JSON object + */ + DatabaseRole.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DatabaseRole + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.DatabaseRole + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DatabaseRole.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.DatabaseRole"; + }; + + return DatabaseRole; + })(); + + v1.ListDatabaseRolesRequest = (function() { + + /** + * Properties of a ListDatabaseRolesRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IListDatabaseRolesRequest + * @property {string|null} [parent] ListDatabaseRolesRequest parent + * @property {number|null} [pageSize] ListDatabaseRolesRequest pageSize + * @property {string|null} [pageToken] ListDatabaseRolesRequest pageToken + */ + + /** + * Constructs a new ListDatabaseRolesRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListDatabaseRolesRequest. + * @implements IListDatabaseRolesRequest + * @constructor + * @param {google.spanner.admin.database.v1.IListDatabaseRolesRequest=} [properties] Properties to set + */ + function ListDatabaseRolesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDatabaseRolesRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @instance + */ + ListDatabaseRolesRequest.prototype.parent = ""; + + /** + * ListDatabaseRolesRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @instance + */ + ListDatabaseRolesRequest.prototype.pageSize = 0; + + /** + * ListDatabaseRolesRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @instance + */ + ListDatabaseRolesRequest.prototype.pageToken = ""; + + /** + * Creates a new ListDatabaseRolesRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseRolesRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListDatabaseRolesRequest} ListDatabaseRolesRequest instance + */ + ListDatabaseRolesRequest.create = function create(properties) { + return new ListDatabaseRolesRequest(properties); + }; + + /** + * Encodes the specified ListDatabaseRolesRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseRolesRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseRolesRequest} message ListDatabaseRolesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabaseRolesRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListDatabaseRolesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseRolesRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseRolesRequest} message ListDatabaseRolesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabaseRolesRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListDatabaseRolesRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListDatabaseRolesRequest} ListDatabaseRolesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabaseRolesRequest.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.spanner.admin.database.v1.ListDatabaseRolesRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListDatabaseRolesRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListDatabaseRolesRequest} ListDatabaseRolesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabaseRolesRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListDatabaseRolesRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListDatabaseRolesRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListDatabaseRolesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListDatabaseRolesRequest} ListDatabaseRolesRequest + */ + ListDatabaseRolesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListDatabaseRolesRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.ListDatabaseRolesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListDatabaseRolesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {google.spanner.admin.database.v1.ListDatabaseRolesRequest} message ListDatabaseRolesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDatabaseRolesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListDatabaseRolesRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @instance + * @returns {Object.} JSON object + */ + ListDatabaseRolesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDatabaseRolesRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDatabaseRolesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListDatabaseRolesRequest"; + }; + + return ListDatabaseRolesRequest; + })(); + + v1.ListDatabaseRolesResponse = (function() { + + /** + * Properties of a ListDatabaseRolesResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IListDatabaseRolesResponse + * @property {Array.|null} [databaseRoles] ListDatabaseRolesResponse databaseRoles + * @property {string|null} [nextPageToken] ListDatabaseRolesResponse nextPageToken + */ + + /** + * Constructs a new ListDatabaseRolesResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a ListDatabaseRolesResponse. + * @implements IListDatabaseRolesResponse + * @constructor + * @param {google.spanner.admin.database.v1.IListDatabaseRolesResponse=} [properties] Properties to set + */ + function ListDatabaseRolesResponse(properties) { + this.databaseRoles = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDatabaseRolesResponse databaseRoles. + * @member {Array.} databaseRoles + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @instance + */ + ListDatabaseRolesResponse.prototype.databaseRoles = $util.emptyArray; + + /** + * ListDatabaseRolesResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @instance + */ + ListDatabaseRolesResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListDatabaseRolesResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseRolesResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.ListDatabaseRolesResponse} ListDatabaseRolesResponse instance + */ + ListDatabaseRolesResponse.create = function create(properties) { + return new ListDatabaseRolesResponse(properties); + }; + + /** + * Encodes the specified ListDatabaseRolesResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseRolesResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseRolesResponse} message ListDatabaseRolesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabaseRolesResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.databaseRoles != null && message.databaseRoles.length) + for (var i = 0; i < message.databaseRoles.length; ++i) + $root.google.spanner.admin.database.v1.DatabaseRole.encode(message.databaseRoles[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListDatabaseRolesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseRolesResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {google.spanner.admin.database.v1.IListDatabaseRolesResponse} message ListDatabaseRolesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListDatabaseRolesResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListDatabaseRolesResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.ListDatabaseRolesResponse} ListDatabaseRolesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabaseRolesResponse.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.spanner.admin.database.v1.ListDatabaseRolesResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.databaseRoles && message.databaseRoles.length)) + message.databaseRoles = []; + message.databaseRoles.push($root.google.spanner.admin.database.v1.DatabaseRole.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListDatabaseRolesResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.ListDatabaseRolesResponse} ListDatabaseRolesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListDatabaseRolesResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListDatabaseRolesResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListDatabaseRolesResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.databaseRoles != null && message.hasOwnProperty("databaseRoles")) { + if (!Array.isArray(message.databaseRoles)) + return "databaseRoles: array expected"; + for (var i = 0; i < message.databaseRoles.length; ++i) { + var error = $root.google.spanner.admin.database.v1.DatabaseRole.verify(message.databaseRoles[i]); + if (error) + return "databaseRoles." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListDatabaseRolesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.ListDatabaseRolesResponse} ListDatabaseRolesResponse + */ + ListDatabaseRolesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.ListDatabaseRolesResponse) + return object; + var message = new $root.google.spanner.admin.database.v1.ListDatabaseRolesResponse(); + if (object.databaseRoles) { + if (!Array.isArray(object.databaseRoles)) + throw TypeError(".google.spanner.admin.database.v1.ListDatabaseRolesResponse.databaseRoles: array expected"); + message.databaseRoles = []; + for (var i = 0; i < object.databaseRoles.length; ++i) { + if (typeof object.databaseRoles[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.ListDatabaseRolesResponse.databaseRoles: object expected"); + message.databaseRoles[i] = $root.google.spanner.admin.database.v1.DatabaseRole.fromObject(object.databaseRoles[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListDatabaseRolesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {google.spanner.admin.database.v1.ListDatabaseRolesResponse} message ListDatabaseRolesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDatabaseRolesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.databaseRoles = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.databaseRoles && message.databaseRoles.length) { + object.databaseRoles = []; + for (var j = 0; j < message.databaseRoles.length; ++j) + object.databaseRoles[j] = $root.google.spanner.admin.database.v1.DatabaseRole.toObject(message.databaseRoles[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListDatabaseRolesResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @instance + * @returns {Object.} JSON object + */ + ListDatabaseRolesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDatabaseRolesResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.ListDatabaseRolesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDatabaseRolesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.ListDatabaseRolesResponse"; + }; + + return ListDatabaseRolesResponse; + })(); + + v1.AddSplitPointsRequest = (function() { + + /** + * Properties of an AddSplitPointsRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IAddSplitPointsRequest + * @property {string|null} [database] AddSplitPointsRequest database + * @property {Array.|null} [splitPoints] AddSplitPointsRequest splitPoints + * @property {string|null} [initiator] AddSplitPointsRequest initiator + */ + + /** + * Constructs a new AddSplitPointsRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an AddSplitPointsRequest. + * @implements IAddSplitPointsRequest + * @constructor + * @param {google.spanner.admin.database.v1.IAddSplitPointsRequest=} [properties] Properties to set + */ + function AddSplitPointsRequest(properties) { + this.splitPoints = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AddSplitPointsRequest database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @instance + */ + AddSplitPointsRequest.prototype.database = ""; + + /** + * AddSplitPointsRequest splitPoints. + * @member {Array.} splitPoints + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @instance + */ + AddSplitPointsRequest.prototype.splitPoints = $util.emptyArray; + + /** + * AddSplitPointsRequest initiator. + * @member {string} initiator + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @instance + */ + AddSplitPointsRequest.prototype.initiator = ""; + + /** + * Creates a new AddSplitPointsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {google.spanner.admin.database.v1.IAddSplitPointsRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.AddSplitPointsRequest} AddSplitPointsRequest instance + */ + AddSplitPointsRequest.create = function create(properties) { + return new AddSplitPointsRequest(properties); + }; + + /** + * Encodes the specified AddSplitPointsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.AddSplitPointsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {google.spanner.admin.database.v1.IAddSplitPointsRequest} message AddSplitPointsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AddSplitPointsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + if (message.splitPoints != null && message.splitPoints.length) + for (var i = 0; i < message.splitPoints.length; ++i) + $root.google.spanner.admin.database.v1.SplitPoints.encode(message.splitPoints[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.initiator != null && Object.hasOwnProperty.call(message, "initiator")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.initiator); + return writer; + }; + + /** + * Encodes the specified AddSplitPointsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.AddSplitPointsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {google.spanner.admin.database.v1.IAddSplitPointsRequest} message AddSplitPointsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AddSplitPointsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AddSplitPointsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.AddSplitPointsRequest} AddSplitPointsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AddSplitPointsRequest.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.spanner.admin.database.v1.AddSplitPointsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + case 2: { + if (!(message.splitPoints && message.splitPoints.length)) + message.splitPoints = []; + message.splitPoints.push($root.google.spanner.admin.database.v1.SplitPoints.decode(reader, reader.uint32())); + break; + } + case 3: { + message.initiator = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AddSplitPointsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.AddSplitPointsRequest} AddSplitPointsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AddSplitPointsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AddSplitPointsRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AddSplitPointsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.splitPoints != null && message.hasOwnProperty("splitPoints")) { + if (!Array.isArray(message.splitPoints)) + return "splitPoints: array expected"; + for (var i = 0; i < message.splitPoints.length; ++i) { + var error = $root.google.spanner.admin.database.v1.SplitPoints.verify(message.splitPoints[i]); + if (error) + return "splitPoints." + error; + } + } + if (message.initiator != null && message.hasOwnProperty("initiator")) + if (!$util.isString(message.initiator)) + return "initiator: string expected"; + return null; + }; + + /** + * Creates an AddSplitPointsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.AddSplitPointsRequest} AddSplitPointsRequest + */ + AddSplitPointsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.AddSplitPointsRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.AddSplitPointsRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.splitPoints) { + if (!Array.isArray(object.splitPoints)) + throw TypeError(".google.spanner.admin.database.v1.AddSplitPointsRequest.splitPoints: array expected"); + message.splitPoints = []; + for (var i = 0; i < object.splitPoints.length; ++i) { + if (typeof object.splitPoints[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.AddSplitPointsRequest.splitPoints: object expected"); + message.splitPoints[i] = $root.google.spanner.admin.database.v1.SplitPoints.fromObject(object.splitPoints[i]); + } + } + if (object.initiator != null) + message.initiator = String(object.initiator); + return message; + }; + + /** + * Creates a plain object from an AddSplitPointsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {google.spanner.admin.database.v1.AddSplitPointsRequest} message AddSplitPointsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AddSplitPointsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.splitPoints = []; + if (options.defaults) { + object.database = ""; + object.initiator = ""; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.splitPoints && message.splitPoints.length) { + object.splitPoints = []; + for (var j = 0; j < message.splitPoints.length; ++j) + object.splitPoints[j] = $root.google.spanner.admin.database.v1.SplitPoints.toObject(message.splitPoints[j], options); + } + if (message.initiator != null && message.hasOwnProperty("initiator")) + object.initiator = message.initiator; + return object; + }; + + /** + * Converts this AddSplitPointsRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @instance + * @returns {Object.} JSON object + */ + AddSplitPointsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AddSplitPointsRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.AddSplitPointsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AddSplitPointsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.AddSplitPointsRequest"; + }; + + return AddSplitPointsRequest; + })(); + + v1.AddSplitPointsResponse = (function() { + + /** + * Properties of an AddSplitPointsResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IAddSplitPointsResponse + */ + + /** + * Constructs a new AddSplitPointsResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an AddSplitPointsResponse. + * @implements IAddSplitPointsResponse + * @constructor + * @param {google.spanner.admin.database.v1.IAddSplitPointsResponse=} [properties] Properties to set + */ + function AddSplitPointsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new AddSplitPointsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {google.spanner.admin.database.v1.IAddSplitPointsResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.AddSplitPointsResponse} AddSplitPointsResponse instance + */ + AddSplitPointsResponse.create = function create(properties) { + return new AddSplitPointsResponse(properties); + }; + + /** + * Encodes the specified AddSplitPointsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.AddSplitPointsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {google.spanner.admin.database.v1.IAddSplitPointsResponse} message AddSplitPointsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AddSplitPointsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified AddSplitPointsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.AddSplitPointsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {google.spanner.admin.database.v1.IAddSplitPointsResponse} message AddSplitPointsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AddSplitPointsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AddSplitPointsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.AddSplitPointsResponse} AddSplitPointsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AddSplitPointsResponse.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.spanner.admin.database.v1.AddSplitPointsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AddSplitPointsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.AddSplitPointsResponse} AddSplitPointsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AddSplitPointsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AddSplitPointsResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AddSplitPointsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates an AddSplitPointsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.AddSplitPointsResponse} AddSplitPointsResponse + */ + AddSplitPointsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.AddSplitPointsResponse) + return object; + return new $root.google.spanner.admin.database.v1.AddSplitPointsResponse(); + }; + + /** + * Creates a plain object from an AddSplitPointsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {google.spanner.admin.database.v1.AddSplitPointsResponse} message AddSplitPointsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AddSplitPointsResponse.toObject = function toObject() { + return {}; + }; + + /** + * Converts this AddSplitPointsResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @instance + * @returns {Object.} JSON object + */ + AddSplitPointsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AddSplitPointsResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.AddSplitPointsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AddSplitPointsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.AddSplitPointsResponse"; + }; + + return AddSplitPointsResponse; + })(); + + v1.SplitPoints = (function() { + + /** + * Properties of a SplitPoints. + * @memberof google.spanner.admin.database.v1 + * @interface ISplitPoints + * @property {string|null} [table] SplitPoints table + * @property {string|null} [index] SplitPoints index + * @property {Array.|null} [keys] SplitPoints keys + * @property {google.protobuf.ITimestamp|null} [expireTime] SplitPoints expireTime + */ + + /** + * Constructs a new SplitPoints. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents a SplitPoints. + * @implements ISplitPoints + * @constructor + * @param {google.spanner.admin.database.v1.ISplitPoints=} [properties] Properties to set + */ + function SplitPoints(properties) { + this.keys = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SplitPoints table. + * @member {string} table + * @memberof google.spanner.admin.database.v1.SplitPoints + * @instance + */ + SplitPoints.prototype.table = ""; + + /** + * SplitPoints index. + * @member {string} index + * @memberof google.spanner.admin.database.v1.SplitPoints + * @instance + */ + SplitPoints.prototype.index = ""; + + /** + * SplitPoints keys. + * @member {Array.} keys + * @memberof google.spanner.admin.database.v1.SplitPoints + * @instance + */ + SplitPoints.prototype.keys = $util.emptyArray; + + /** + * SplitPoints expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.spanner.admin.database.v1.SplitPoints + * @instance + */ + SplitPoints.prototype.expireTime = null; + + /** + * Creates a new SplitPoints instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {google.spanner.admin.database.v1.ISplitPoints=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.SplitPoints} SplitPoints instance + */ + SplitPoints.create = function create(properties) { + return new SplitPoints(properties); + }; + + /** + * Encodes the specified SplitPoints message. Does not implicitly {@link google.spanner.admin.database.v1.SplitPoints.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {google.spanner.admin.database.v1.ISplitPoints} message SplitPoints message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SplitPoints.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.table); + if (message.index != null && Object.hasOwnProperty.call(message, "index")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.index); + if (message.keys != null && message.keys.length) + for (var i = 0; i < message.keys.length; ++i) + $root.google.spanner.admin.database.v1.SplitPoints.Key.encode(message.keys[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.expireTime != null && Object.hasOwnProperty.call(message, "expireTime")) + $root.google.protobuf.Timestamp.encode(message.expireTime, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SplitPoints message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.SplitPoints.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {google.spanner.admin.database.v1.ISplitPoints} message SplitPoints message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SplitPoints.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SplitPoints message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.SplitPoints} SplitPoints + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SplitPoints.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.spanner.admin.database.v1.SplitPoints(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.table = reader.string(); + break; + } + case 2: { + message.index = reader.string(); + break; + } + case 3: { + if (!(message.keys && message.keys.length)) + message.keys = []; + message.keys.push($root.google.spanner.admin.database.v1.SplitPoints.Key.decode(reader, reader.uint32())); + break; + } + case 5: { + message.expireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SplitPoints message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.SplitPoints} SplitPoints + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SplitPoints.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SplitPoints message. + * @function verify + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SplitPoints.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.index != null && message.hasOwnProperty("index")) + if (!$util.isString(message.index)) + return "index: string expected"; + if (message.keys != null && message.hasOwnProperty("keys")) { + if (!Array.isArray(message.keys)) + return "keys: array expected"; + for (var i = 0; i < message.keys.length; ++i) { + var error = $root.google.spanner.admin.database.v1.SplitPoints.Key.verify(message.keys[i]); + if (error) + return "keys." + error; + } + } + if (message.expireTime != null && message.hasOwnProperty("expireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.expireTime); + if (error) + return "expireTime." + error; + } + return null; + }; + + /** + * Creates a SplitPoints message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.SplitPoints} SplitPoints + */ + SplitPoints.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.SplitPoints) + return object; + var message = new $root.google.spanner.admin.database.v1.SplitPoints(); + if (object.table != null) + message.table = String(object.table); + if (object.index != null) + message.index = String(object.index); + if (object.keys) { + if (!Array.isArray(object.keys)) + throw TypeError(".google.spanner.admin.database.v1.SplitPoints.keys: array expected"); + message.keys = []; + for (var i = 0; i < object.keys.length; ++i) { + if (typeof object.keys[i] !== "object") + throw TypeError(".google.spanner.admin.database.v1.SplitPoints.keys: object expected"); + message.keys[i] = $root.google.spanner.admin.database.v1.SplitPoints.Key.fromObject(object.keys[i]); + } + } + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.spanner.admin.database.v1.SplitPoints.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime); + } + return message; + }; + + /** + * Creates a plain object from a SplitPoints message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {google.spanner.admin.database.v1.SplitPoints} message SplitPoints + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SplitPoints.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.keys = []; + if (options.defaults) { + object.table = ""; + object.index = ""; + object.expireTime = null; + } + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.index != null && message.hasOwnProperty("index")) + object.index = message.index; + if (message.keys && message.keys.length) { + object.keys = []; + for (var j = 0; j < message.keys.length; ++j) + object.keys[j] = $root.google.spanner.admin.database.v1.SplitPoints.Key.toObject(message.keys[j], options); + } + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + return object; + }; + + /** + * Converts this SplitPoints to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.SplitPoints + * @instance + * @returns {Object.} JSON object + */ + SplitPoints.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SplitPoints + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.SplitPoints + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SplitPoints.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.SplitPoints"; + }; + + SplitPoints.Key = (function() { + + /** + * Properties of a Key. + * @memberof google.spanner.admin.database.v1.SplitPoints + * @interface IKey + * @property {google.protobuf.IListValue|null} [keyParts] Key keyParts + */ + + /** + * Constructs a new Key. + * @memberof google.spanner.admin.database.v1.SplitPoints + * @classdesc Represents a Key. + * @implements IKey + * @constructor + * @param {google.spanner.admin.database.v1.SplitPoints.IKey=} [properties] Properties to set + */ + function Key(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Key keyParts. + * @member {google.protobuf.IListValue|null|undefined} keyParts + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @instance + */ + Key.prototype.keyParts = null; + + /** + * Creates a new Key instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {google.spanner.admin.database.v1.SplitPoints.IKey=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.SplitPoints.Key} Key instance + */ + Key.create = function create(properties) { + return new Key(properties); + }; + + /** + * Encodes the specified Key message. Does not implicitly {@link google.spanner.admin.database.v1.SplitPoints.Key.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {google.spanner.admin.database.v1.SplitPoints.IKey} message Key message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Key.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.keyParts != null && Object.hasOwnProperty.call(message, "keyParts")) + $root.google.protobuf.ListValue.encode(message.keyParts, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Key message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.SplitPoints.Key.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {google.spanner.admin.database.v1.SplitPoints.IKey} message Key message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Key.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Key message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.SplitPoints.Key} Key + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Key.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.spanner.admin.database.v1.SplitPoints.Key(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.keyParts = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Key message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.SplitPoints.Key} Key + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Key.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Key message. + * @function verify + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Key.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.keyParts != null && message.hasOwnProperty("keyParts")) { + var error = $root.google.protobuf.ListValue.verify(message.keyParts); + if (error) + return "keyParts." + error; + } + return null; + }; + + /** + * Creates a Key message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.SplitPoints.Key} Key + */ + Key.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.SplitPoints.Key) + return object; + var message = new $root.google.spanner.admin.database.v1.SplitPoints.Key(); + if (object.keyParts != null) { + if (typeof object.keyParts !== "object") + throw TypeError(".google.spanner.admin.database.v1.SplitPoints.Key.keyParts: object expected"); + message.keyParts = $root.google.protobuf.ListValue.fromObject(object.keyParts); + } + return message; + }; + + /** + * Creates a plain object from a Key message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {google.spanner.admin.database.v1.SplitPoints.Key} message Key + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Key.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.keyParts = null; + if (message.keyParts != null && message.hasOwnProperty("keyParts")) + object.keyParts = $root.google.protobuf.ListValue.toObject(message.keyParts, options); + return object; + }; + + /** + * Converts this Key to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @instance + * @returns {Object.} JSON object + */ + Key.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Key + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.SplitPoints.Key + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Key.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.SplitPoints.Key"; + }; + + return Key; + })(); + + return SplitPoints; + })(); + + v1.InternalUpdateGraphOperationRequest = (function() { + + /** + * Properties of an InternalUpdateGraphOperationRequest. + * @memberof google.spanner.admin.database.v1 + * @interface IInternalUpdateGraphOperationRequest + * @property {string|null} [database] InternalUpdateGraphOperationRequest database + * @property {string|null} [operationId] InternalUpdateGraphOperationRequest operationId + * @property {string|null} [vmIdentityToken] InternalUpdateGraphOperationRequest vmIdentityToken + * @property {number|null} [progress] InternalUpdateGraphOperationRequest progress + * @property {google.rpc.IStatus|null} [status] InternalUpdateGraphOperationRequest status + */ + + /** + * Constructs a new InternalUpdateGraphOperationRequest. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an InternalUpdateGraphOperationRequest. + * @implements IInternalUpdateGraphOperationRequest + * @constructor + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest=} [properties] Properties to set + */ + function InternalUpdateGraphOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InternalUpdateGraphOperationRequest database. + * @member {string} database + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @instance + */ + InternalUpdateGraphOperationRequest.prototype.database = ""; + + /** + * InternalUpdateGraphOperationRequest operationId. + * @member {string} operationId + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @instance + */ + InternalUpdateGraphOperationRequest.prototype.operationId = ""; + + /** + * InternalUpdateGraphOperationRequest vmIdentityToken. + * @member {string} vmIdentityToken + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @instance + */ + InternalUpdateGraphOperationRequest.prototype.vmIdentityToken = ""; + + /** + * InternalUpdateGraphOperationRequest progress. + * @member {number} progress + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @instance + */ + InternalUpdateGraphOperationRequest.prototype.progress = 0; + + /** + * InternalUpdateGraphOperationRequest status. + * @member {google.rpc.IStatus|null|undefined} status + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @instance + */ + InternalUpdateGraphOperationRequest.prototype.status = null; + + /** + * Creates a new InternalUpdateGraphOperationRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest} InternalUpdateGraphOperationRequest instance + */ + InternalUpdateGraphOperationRequest.create = function create(properties) { + return new InternalUpdateGraphOperationRequest(properties); + }; + + /** + * Encodes the specified InternalUpdateGraphOperationRequest message. Does not implicitly {@link google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest} message InternalUpdateGraphOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InternalUpdateGraphOperationRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + if (message.operationId != null && Object.hasOwnProperty.call(message, "operationId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.operationId); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + writer.uint32(/* id 3, wireType 1 =*/25).double(message.progress); + if (message.vmIdentityToken != null && Object.hasOwnProperty.call(message, "vmIdentityToken")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.vmIdentityToken); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + $root.google.rpc.Status.encode(message.status, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified InternalUpdateGraphOperationRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest} message InternalUpdateGraphOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InternalUpdateGraphOperationRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InternalUpdateGraphOperationRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest} InternalUpdateGraphOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InternalUpdateGraphOperationRequest.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.spanner.admin.database.v1.InternalUpdateGraphOperationRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + case 2: { + message.operationId = reader.string(); + break; + } + case 5: { + message.vmIdentityToken = reader.string(); + break; + } + case 3: { + message.progress = reader.double(); + break; + } + case 6: { + message.status = $root.google.rpc.Status.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InternalUpdateGraphOperationRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest} InternalUpdateGraphOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InternalUpdateGraphOperationRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InternalUpdateGraphOperationRequest message. + * @function verify + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InternalUpdateGraphOperationRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.operationId != null && message.hasOwnProperty("operationId")) + if (!$util.isString(message.operationId)) + return "operationId: string expected"; + if (message.vmIdentityToken != null && message.hasOwnProperty("vmIdentityToken")) + if (!$util.isString(message.vmIdentityToken)) + return "vmIdentityToken: string expected"; + if (message.progress != null && message.hasOwnProperty("progress")) + if (typeof message.progress !== "number") + return "progress: number expected"; + if (message.status != null && message.hasOwnProperty("status")) { + var error = $root.google.rpc.Status.verify(message.status); + if (error) + return "status." + error; + } + return null; + }; + + /** + * Creates an InternalUpdateGraphOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest} InternalUpdateGraphOperationRequest + */ + InternalUpdateGraphOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest) + return object; + var message = new $root.google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.operationId != null) + message.operationId = String(object.operationId); + if (object.vmIdentityToken != null) + message.vmIdentityToken = String(object.vmIdentityToken); + if (object.progress != null) + message.progress = Number(object.progress); + if (object.status != null) { + if (typeof object.status !== "object") + throw TypeError(".google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest.status: object expected"); + message.status = $root.google.rpc.Status.fromObject(object.status); + } + return message; + }; + + /** + * Creates a plain object from an InternalUpdateGraphOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest} message InternalUpdateGraphOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InternalUpdateGraphOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + object.operationId = ""; + object.progress = 0; + object.vmIdentityToken = ""; + object.status = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.operationId != null && message.hasOwnProperty("operationId")) + object.operationId = message.operationId; + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = options.json && !isFinite(message.progress) ? String(message.progress) : message.progress; + if (message.vmIdentityToken != null && message.hasOwnProperty("vmIdentityToken")) + object.vmIdentityToken = message.vmIdentityToken; + if (message.status != null && message.hasOwnProperty("status")) + object.status = $root.google.rpc.Status.toObject(message.status, options); + return object; + }; + + /** + * Converts this InternalUpdateGraphOperationRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @instance + * @returns {Object.} JSON object + */ + InternalUpdateGraphOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InternalUpdateGraphOperationRequest + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InternalUpdateGraphOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest"; + }; + + return InternalUpdateGraphOperationRequest; + })(); + + v1.InternalUpdateGraphOperationResponse = (function() { + + /** + * Properties of an InternalUpdateGraphOperationResponse. + * @memberof google.spanner.admin.database.v1 + * @interface IInternalUpdateGraphOperationResponse + */ + + /** + * Constructs a new InternalUpdateGraphOperationResponse. + * @memberof google.spanner.admin.database.v1 + * @classdesc Represents an InternalUpdateGraphOperationResponse. + * @implements IInternalUpdateGraphOperationResponse + * @constructor + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse=} [properties] Properties to set + */ + function InternalUpdateGraphOperationResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new InternalUpdateGraphOperationResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse=} [properties] Properties to set + * @returns {google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse} InternalUpdateGraphOperationResponse instance + */ + InternalUpdateGraphOperationResponse.create = function create(properties) { + return new InternalUpdateGraphOperationResponse(properties); + }; + + /** + * Encodes the specified InternalUpdateGraphOperationResponse message. Does not implicitly {@link google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse} message InternalUpdateGraphOperationResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InternalUpdateGraphOperationResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified InternalUpdateGraphOperationResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse} message InternalUpdateGraphOperationResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InternalUpdateGraphOperationResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InternalUpdateGraphOperationResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse} InternalUpdateGraphOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InternalUpdateGraphOperationResponse.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.spanner.admin.database.v1.InternalUpdateGraphOperationResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InternalUpdateGraphOperationResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse} InternalUpdateGraphOperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InternalUpdateGraphOperationResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InternalUpdateGraphOperationResponse message. + * @function verify + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InternalUpdateGraphOperationResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates an InternalUpdateGraphOperationResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse} InternalUpdateGraphOperationResponse + */ + InternalUpdateGraphOperationResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse) + return object; + return new $root.google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse(); + }; + + /** + * Creates a plain object from an InternalUpdateGraphOperationResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse} message InternalUpdateGraphOperationResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InternalUpdateGraphOperationResponse.toObject = function toObject() { + return {}; + }; + + /** + * Converts this InternalUpdateGraphOperationResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @instance + * @returns {Object.} JSON object + */ + InternalUpdateGraphOperationResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InternalUpdateGraphOperationResponse + * @function getTypeUrl + * @memberof google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InternalUpdateGraphOperationResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse"; + }; + + return InternalUpdateGraphOperationResponse; + })(); + + return v1; + })(); + + return database; + })(); + + admin.instance = (function() { + + /** + * Namespace instance. + * @memberof google.spanner.admin + * @namespace + */ + var instance = {}; + + instance.v1 = (function() { + + /** + * Namespace v1. + * @memberof google.spanner.admin.instance + * @namespace + */ + var v1 = {}; + + v1.OperationProgress = (function() { + + /** + * Properties of an OperationProgress. + * @memberof google.spanner.admin.instance.v1 + * @interface IOperationProgress + * @property {number|null} [progressPercent] OperationProgress progressPercent + * @property {google.protobuf.ITimestamp|null} [startTime] OperationProgress startTime + * @property {google.protobuf.ITimestamp|null} [endTime] OperationProgress endTime + */ + + /** + * Constructs a new OperationProgress. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an OperationProgress. + * @implements IOperationProgress + * @constructor + * @param {google.spanner.admin.instance.v1.IOperationProgress=} [properties] Properties to set + */ + function OperationProgress(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OperationProgress progressPercent. + * @member {number} progressPercent + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @instance + */ + OperationProgress.prototype.progressPercent = 0; + + /** + * OperationProgress startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @instance + */ + OperationProgress.prototype.startTime = null; + + /** + * OperationProgress endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @instance + */ + OperationProgress.prototype.endTime = null; + + /** + * Creates a new OperationProgress instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {google.spanner.admin.instance.v1.IOperationProgress=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.OperationProgress} OperationProgress instance + */ + OperationProgress.create = function create(properties) { + return new OperationProgress(properties); + }; + + /** + * Encodes the specified OperationProgress message. Does not implicitly {@link google.spanner.admin.instance.v1.OperationProgress.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {google.spanner.admin.instance.v1.IOperationProgress} message OperationProgress message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OperationProgress.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.progressPercent != null && Object.hasOwnProperty.call(message, "progressPercent")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.progressPercent); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) + $root.google.protobuf.Timestamp.encode(message.endTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified OperationProgress message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.OperationProgress.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {google.spanner.admin.instance.v1.IOperationProgress} message OperationProgress message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OperationProgress.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an OperationProgress message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.OperationProgress} OperationProgress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OperationProgress.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.spanner.admin.instance.v1.OperationProgress(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.progressPercent = reader.int32(); + break; + } + case 2: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.endTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an OperationProgress message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.OperationProgress} OperationProgress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OperationProgress.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an OperationProgress message. + * @function verify + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + OperationProgress.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.progressPercent != null && message.hasOwnProperty("progressPercent")) + if (!$util.isInteger(message.progressPercent)) + return "progressPercent: integer expected"; + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.endTime != null && message.hasOwnProperty("endTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.endTime); + if (error) + return "endTime." + error; + } + return null; + }; + + /** + * Creates an OperationProgress message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.OperationProgress} OperationProgress + */ + OperationProgress.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.OperationProgress) + return object; + var message = new $root.google.spanner.admin.instance.v1.OperationProgress(); + if (object.progressPercent != null) + message.progressPercent = object.progressPercent | 0; + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.OperationProgress.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.OperationProgress.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + return message; + }; + + /** + * Creates a plain object from an OperationProgress message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {google.spanner.admin.instance.v1.OperationProgress} message OperationProgress + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OperationProgress.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.progressPercent = 0; + object.startTime = null; + object.endTime = null; + } + if (message.progressPercent != null && message.hasOwnProperty("progressPercent")) + object.progressPercent = message.progressPercent; + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + return object; + }; + + /** + * Converts this OperationProgress to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @instance + * @returns {Object.} JSON object + */ + OperationProgress.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OperationProgress + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.OperationProgress + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OperationProgress.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.OperationProgress"; + }; + + return OperationProgress; + })(); + + /** + * FulfillmentPeriod enum. + * @name google.spanner.admin.instance.v1.FulfillmentPeriod + * @enum {number} + * @property {number} FULFILLMENT_PERIOD_UNSPECIFIED=0 FULFILLMENT_PERIOD_UNSPECIFIED value + * @property {number} FULFILLMENT_PERIOD_NORMAL=1 FULFILLMENT_PERIOD_NORMAL value + * @property {number} FULFILLMENT_PERIOD_EXTENDED=2 FULFILLMENT_PERIOD_EXTENDED value + */ + v1.FulfillmentPeriod = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FULFILLMENT_PERIOD_UNSPECIFIED"] = 0; + values[valuesById[1] = "FULFILLMENT_PERIOD_NORMAL"] = 1; + values[valuesById[2] = "FULFILLMENT_PERIOD_EXTENDED"] = 2; + return values; + })(); + + v1.ReplicaSelection = (function() { + + /** + * Properties of a ReplicaSelection. + * @memberof google.spanner.admin.instance.v1 + * @interface IReplicaSelection + * @property {string|null} [location] ReplicaSelection location + */ + + /** + * Constructs a new ReplicaSelection. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ReplicaSelection. + * @implements IReplicaSelection + * @constructor + * @param {google.spanner.admin.instance.v1.IReplicaSelection=} [properties] Properties to set + */ + function ReplicaSelection(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReplicaSelection location. + * @member {string} location + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @instance + */ + ReplicaSelection.prototype.location = ""; + + /** + * Creates a new ReplicaSelection instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {google.spanner.admin.instance.v1.IReplicaSelection=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ReplicaSelection} ReplicaSelection instance + */ + ReplicaSelection.create = function create(properties) { + return new ReplicaSelection(properties); + }; + + /** + * Encodes the specified ReplicaSelection message. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaSelection.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {google.spanner.admin.instance.v1.IReplicaSelection} message ReplicaSelection message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReplicaSelection.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.location != null && Object.hasOwnProperty.call(message, "location")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.location); + return writer; + }; + + /** + * Encodes the specified ReplicaSelection message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaSelection.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {google.spanner.admin.instance.v1.IReplicaSelection} message ReplicaSelection message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReplicaSelection.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReplicaSelection message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ReplicaSelection} ReplicaSelection + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReplicaSelection.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.spanner.admin.instance.v1.ReplicaSelection(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.location = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReplicaSelection message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ReplicaSelection} ReplicaSelection + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReplicaSelection.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReplicaSelection message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReplicaSelection.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.location != null && message.hasOwnProperty("location")) + if (!$util.isString(message.location)) + return "location: string expected"; + return null; + }; + + /** + * Creates a ReplicaSelection message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ReplicaSelection} ReplicaSelection + */ + ReplicaSelection.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ReplicaSelection) + return object; + var message = new $root.google.spanner.admin.instance.v1.ReplicaSelection(); + if (object.location != null) + message.location = String(object.location); + return message; + }; + + /** + * Creates a plain object from a ReplicaSelection message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {google.spanner.admin.instance.v1.ReplicaSelection} message ReplicaSelection + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReplicaSelection.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.location = ""; + if (message.location != null && message.hasOwnProperty("location")) + object.location = message.location; + return object; + }; + + /** + * Converts this ReplicaSelection to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @instance + * @returns {Object.} JSON object + */ + ReplicaSelection.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReplicaSelection + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ReplicaSelection + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReplicaSelection.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ReplicaSelection"; + }; + + return ReplicaSelection; + })(); + + v1.InstanceAdmin = (function() { + + /** + * Constructs a new InstanceAdmin service. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an InstanceAdmin + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function InstanceAdmin(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (InstanceAdmin.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = InstanceAdmin; + + /** + * Creates new InstanceAdmin service using the specified rpc implementation. + * @function create + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {InstanceAdmin} RPC service. Useful where requests and/or responses are streamed. + */ + InstanceAdmin.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstanceConfigs}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef ListInstanceConfigsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.instance.v1.ListInstanceConfigsResponse} [response] ListInstanceConfigsResponse + */ + + /** + * Calls ListInstanceConfigs. + * @function listInstanceConfigs + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsRequest} request ListInstanceConfigsRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigsCallback} callback Node-style callback called with the error, if any, and ListInstanceConfigsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.listInstanceConfigs = function listInstanceConfigs(request, callback) { + return this.rpcCall(listInstanceConfigs, $root.google.spanner.admin.instance.v1.ListInstanceConfigsRequest, $root.google.spanner.admin.instance.v1.ListInstanceConfigsResponse, request, callback); + }, "name", { value: "ListInstanceConfigs" }); + + /** + * Calls ListInstanceConfigs. + * @function listInstanceConfigs + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsRequest} request ListInstanceConfigsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|getInstanceConfig}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef GetInstanceConfigCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.instance.v1.InstanceConfig} [response] InstanceConfig + */ + + /** + * Calls GetInstanceConfig. + * @function getInstanceConfig + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IGetInstanceConfigRequest} request GetInstanceConfigRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfigCallback} callback Node-style callback called with the error, if any, and InstanceConfig + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.getInstanceConfig = function getInstanceConfig(request, callback) { + return this.rpcCall(getInstanceConfig, $root.google.spanner.admin.instance.v1.GetInstanceConfigRequest, $root.google.spanner.admin.instance.v1.InstanceConfig, request, callback); + }, "name", { value: "GetInstanceConfig" }); + + /** + * Calls GetInstanceConfig. + * @function getInstanceConfig + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IGetInstanceConfigRequest} request GetInstanceConfigRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|createInstanceConfig}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef CreateInstanceConfigCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CreateInstanceConfig. + * @function createInstanceConfig + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigRequest} request CreateInstanceConfigRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceConfigCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.createInstanceConfig = function createInstanceConfig(request, callback) { + return this.rpcCall(createInstanceConfig, $root.google.spanner.admin.instance.v1.CreateInstanceConfigRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CreateInstanceConfig" }); + + /** + * Calls CreateInstanceConfig. + * @function createInstanceConfig + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigRequest} request CreateInstanceConfigRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|updateInstanceConfig}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef UpdateInstanceConfigCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls UpdateInstanceConfig. + * @function updateInstanceConfig + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest} request UpdateInstanceConfigRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceConfigCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.updateInstanceConfig = function updateInstanceConfig(request, callback) { + return this.rpcCall(updateInstanceConfig, $root.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "UpdateInstanceConfig" }); + + /** + * Calls UpdateInstanceConfig. + * @function updateInstanceConfig + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest} request UpdateInstanceConfigRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|deleteInstanceConfig}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef DeleteInstanceConfigCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteInstanceConfig. + * @function deleteInstanceConfig + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest} request DeleteInstanceConfigRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstanceConfigCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.deleteInstanceConfig = function deleteInstanceConfig(request, callback) { + return this.rpcCall(deleteInstanceConfig, $root.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteInstanceConfig" }); + + /** + * Calls DeleteInstanceConfig. + * @function deleteInstanceConfig + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest} request DeleteInstanceConfigRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstanceConfigOperations}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef ListInstanceConfigOperationsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse} [response] ListInstanceConfigOperationsResponse + */ + + /** + * Calls ListInstanceConfigOperations. + * @function listInstanceConfigOperations + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest} request ListInstanceConfigOperationsRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigOperationsCallback} callback Node-style callback called with the error, if any, and ListInstanceConfigOperationsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.listInstanceConfigOperations = function listInstanceConfigOperations(request, callback) { + return this.rpcCall(listInstanceConfigOperations, $root.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest, $root.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse, request, callback); + }, "name", { value: "ListInstanceConfigOperations" }); + + /** + * Calls ListInstanceConfigOperations. + * @function listInstanceConfigOperations + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest} request ListInstanceConfigOperationsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstances}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef ListInstancesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.instance.v1.ListInstancesResponse} [response] ListInstancesResponse + */ + + /** + * Calls ListInstances. + * @function listInstances + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstancesRequest} request ListInstancesRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.ListInstancesCallback} callback Node-style callback called with the error, if any, and ListInstancesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.listInstances = function listInstances(request, callback) { + return this.rpcCall(listInstances, $root.google.spanner.admin.instance.v1.ListInstancesRequest, $root.google.spanner.admin.instance.v1.ListInstancesResponse, request, callback); + }, "name", { value: "ListInstances" }); + + /** + * Calls ListInstances. + * @function listInstances + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstancesRequest} request ListInstancesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstancePartitions}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef ListInstancePartitionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.instance.v1.ListInstancePartitionsResponse} [response] ListInstancePartitionsResponse + */ + + /** + * Calls ListInstancePartitions. + * @function listInstancePartitions + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsRequest} request ListInstancePartitionsRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitionsCallback} callback Node-style callback called with the error, if any, and ListInstancePartitionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.listInstancePartitions = function listInstancePartitions(request, callback) { + return this.rpcCall(listInstancePartitions, $root.google.spanner.admin.instance.v1.ListInstancePartitionsRequest, $root.google.spanner.admin.instance.v1.ListInstancePartitionsResponse, request, callback); + }, "name", { value: "ListInstancePartitions" }); + + /** + * Calls ListInstancePartitions. + * @function listInstancePartitions + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsRequest} request ListInstancePartitionsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|getInstance}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef GetInstanceCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.instance.v1.Instance} [response] Instance + */ + + /** + * Calls GetInstance. + * @function getInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IGetInstanceRequest} request GetInstanceRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceCallback} callback Node-style callback called with the error, if any, and Instance + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.getInstance = function getInstance(request, callback) { + return this.rpcCall(getInstance, $root.google.spanner.admin.instance.v1.GetInstanceRequest, $root.google.spanner.admin.instance.v1.Instance, request, callback); + }, "name", { value: "GetInstance" }); + + /** + * Calls GetInstance. + * @function getInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IGetInstanceRequest} request GetInstanceRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|createInstance}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef CreateInstanceCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CreateInstance. + * @function createInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.ICreateInstanceRequest} request CreateInstanceRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.createInstance = function createInstance(request, callback) { + return this.rpcCall(createInstance, $root.google.spanner.admin.instance.v1.CreateInstanceRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CreateInstance" }); + + /** + * Calls CreateInstance. + * @function createInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.ICreateInstanceRequest} request CreateInstanceRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|updateInstance}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef UpdateInstanceCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls UpdateInstance. + * @function updateInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IUpdateInstanceRequest} request UpdateInstanceRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.updateInstance = function updateInstance(request, callback) { + return this.rpcCall(updateInstance, $root.google.spanner.admin.instance.v1.UpdateInstanceRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "UpdateInstance" }); + + /** + * Calls UpdateInstance. + * @function updateInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IUpdateInstanceRequest} request UpdateInstanceRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|deleteInstance}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef DeleteInstanceCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteInstance. + * @function deleteInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IDeleteInstanceRequest} request DeleteInstanceRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstanceCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.deleteInstance = function deleteInstance(request, callback) { + return this.rpcCall(deleteInstance, $root.google.spanner.admin.instance.v1.DeleteInstanceRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteInstance" }); + + /** + * Calls DeleteInstance. + * @function deleteInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IDeleteInstanceRequest} request DeleteInstanceRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|setIamPolicy}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef SetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.Policy} [response] Policy + */ + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.iam.v1.ISetIamPolicyRequest} request SetIamPolicyRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.SetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.setIamPolicy = function setIamPolicy(request, callback) { + return this.rpcCall(setIamPolicy, $root.google.iam.v1.SetIamPolicyRequest, $root.google.iam.v1.Policy, request, callback); + }, "name", { value: "SetIamPolicy" }); + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.iam.v1.ISetIamPolicyRequest} request SetIamPolicyRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|getIamPolicy}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef GetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.Policy} [response] Policy + */ + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.iam.v1.IGetIamPolicyRequest} request GetIamPolicyRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.GetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.getIamPolicy = function getIamPolicy(request, callback) { + return this.rpcCall(getIamPolicy, $root.google.iam.v1.GetIamPolicyRequest, $root.google.iam.v1.Policy, request, callback); + }, "name", { value: "GetIamPolicy" }); + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.iam.v1.IGetIamPolicyRequest} request GetIamPolicyRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|testIamPermissions}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef TestIamPermissionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.TestIamPermissionsResponse} [response] TestIamPermissionsResponse + */ + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.iam.v1.ITestIamPermissionsRequest} request TestIamPermissionsRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.TestIamPermissionsCallback} callback Node-style callback called with the error, if any, and TestIamPermissionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.testIamPermissions = function testIamPermissions(request, callback) { + return this.rpcCall(testIamPermissions, $root.google.iam.v1.TestIamPermissionsRequest, $root.google.iam.v1.TestIamPermissionsResponse, request, callback); + }, "name", { value: "TestIamPermissions" }); + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.iam.v1.ITestIamPermissionsRequest} request TestIamPermissionsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|getInstancePartition}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef GetInstancePartitionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.instance.v1.InstancePartition} [response] InstancePartition + */ + + /** + * Calls GetInstancePartition. + * @function getInstancePartition + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IGetInstancePartitionRequest} request GetInstancePartitionRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.GetInstancePartitionCallback} callback Node-style callback called with the error, if any, and InstancePartition + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.getInstancePartition = function getInstancePartition(request, callback) { + return this.rpcCall(getInstancePartition, $root.google.spanner.admin.instance.v1.GetInstancePartitionRequest, $root.google.spanner.admin.instance.v1.InstancePartition, request, callback); + }, "name", { value: "GetInstancePartition" }); + + /** + * Calls GetInstancePartition. + * @function getInstancePartition + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IGetInstancePartitionRequest} request GetInstancePartitionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|createInstancePartition}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef CreateInstancePartitionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls CreateInstancePartition. + * @function createInstancePartition + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionRequest} request CreateInstancePartitionRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.CreateInstancePartitionCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.createInstancePartition = function createInstancePartition(request, callback) { + return this.rpcCall(createInstancePartition, $root.google.spanner.admin.instance.v1.CreateInstancePartitionRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "CreateInstancePartition" }); + + /** + * Calls CreateInstancePartition. + * @function createInstancePartition + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionRequest} request CreateInstancePartitionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|deleteInstancePartition}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef DeleteInstancePartitionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteInstancePartition. + * @function deleteInstancePartition + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest} request DeleteInstancePartitionRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstancePartitionCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.deleteInstancePartition = function deleteInstancePartition(request, callback) { + return this.rpcCall(deleteInstancePartition, $root.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteInstancePartition" }); + + /** + * Calls DeleteInstancePartition. + * @function deleteInstancePartition + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest} request DeleteInstancePartitionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|updateInstancePartition}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef UpdateInstancePartitionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls UpdateInstancePartition. + * @function updateInstancePartition + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest} request UpdateInstancePartitionRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstancePartitionCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.updateInstancePartition = function updateInstancePartition(request, callback) { + return this.rpcCall(updateInstancePartition, $root.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "UpdateInstancePartition" }); + + /** + * Calls UpdateInstancePartition. + * @function updateInstancePartition + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest} request UpdateInstancePartitionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|listInstancePartitionOperations}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef ListInstancePartitionOperationsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse} [response] ListInstancePartitionOperationsResponse + */ + + /** + * Calls ListInstancePartitionOperations. + * @function listInstancePartitionOperations + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest} request ListInstancePartitionOperationsRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.ListInstancePartitionOperationsCallback} callback Node-style callback called with the error, if any, and ListInstancePartitionOperationsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.listInstancePartitionOperations = function listInstancePartitionOperations(request, callback) { + return this.rpcCall(listInstancePartitionOperations, $root.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest, $root.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse, request, callback); + }, "name", { value: "ListInstancePartitionOperations" }); + + /** + * Calls ListInstancePartitionOperations. + * @function listInstancePartitionOperations + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest} request ListInstancePartitionOperationsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin|moveInstance}. + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @typedef MoveInstanceCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls MoveInstance. + * @function moveInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IMoveInstanceRequest} request MoveInstanceRequest message or plain object + * @param {google.spanner.admin.instance.v1.InstanceAdmin.MoveInstanceCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceAdmin.prototype.moveInstance = function moveInstance(request, callback) { + return this.rpcCall(moveInstance, $root.google.spanner.admin.instance.v1.MoveInstanceRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "MoveInstance" }); + + /** + * Calls MoveInstance. + * @function moveInstance + * @memberof google.spanner.admin.instance.v1.InstanceAdmin + * @instance + * @param {google.spanner.admin.instance.v1.IMoveInstanceRequest} request MoveInstanceRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return InstanceAdmin; + })(); + + v1.ReplicaInfo = (function() { + + /** + * Properties of a ReplicaInfo. + * @memberof google.spanner.admin.instance.v1 + * @interface IReplicaInfo + * @property {string|null} [location] ReplicaInfo location + * @property {google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType|null} [type] ReplicaInfo type + * @property {boolean|null} [defaultLeaderLocation] ReplicaInfo defaultLeaderLocation + */ + + /** + * Constructs a new ReplicaInfo. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ReplicaInfo. + * @implements IReplicaInfo + * @constructor + * @param {google.spanner.admin.instance.v1.IReplicaInfo=} [properties] Properties to set + */ + function ReplicaInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReplicaInfo location. + * @member {string} location + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @instance + */ + ReplicaInfo.prototype.location = ""; + + /** + * ReplicaInfo type. + * @member {google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType} type + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @instance + */ + ReplicaInfo.prototype.type = 0; + + /** + * ReplicaInfo defaultLeaderLocation. + * @member {boolean} defaultLeaderLocation + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @instance + */ + ReplicaInfo.prototype.defaultLeaderLocation = false; + + /** + * Creates a new ReplicaInfo instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {google.spanner.admin.instance.v1.IReplicaInfo=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ReplicaInfo} ReplicaInfo instance + */ + ReplicaInfo.create = function create(properties) { + return new ReplicaInfo(properties); + }; + + /** + * Encodes the specified ReplicaInfo message. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaInfo.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {google.spanner.admin.instance.v1.IReplicaInfo} message ReplicaInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReplicaInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.location != null && Object.hasOwnProperty.call(message, "location")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.location); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.type); + if (message.defaultLeaderLocation != null && Object.hasOwnProperty.call(message, "defaultLeaderLocation")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.defaultLeaderLocation); + return writer; + }; + + /** + * Encodes the specified ReplicaInfo message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {google.spanner.admin.instance.v1.IReplicaInfo} message ReplicaInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReplicaInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReplicaInfo message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ReplicaInfo} ReplicaInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReplicaInfo.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.spanner.admin.instance.v1.ReplicaInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.location = reader.string(); + break; + } + case 2: { + message.type = reader.int32(); + break; + } + case 3: { + message.defaultLeaderLocation = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReplicaInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ReplicaInfo} ReplicaInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReplicaInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReplicaInfo message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReplicaInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.location != null && message.hasOwnProperty("location")) + if (!$util.isString(message.location)) + return "location: string expected"; + if (message.type != null && message.hasOwnProperty("type")) + switch (message.type) { + default: + return "type: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.defaultLeaderLocation != null && message.hasOwnProperty("defaultLeaderLocation")) + if (typeof message.defaultLeaderLocation !== "boolean") + return "defaultLeaderLocation: boolean expected"; + return null; + }; + + /** + * Creates a ReplicaInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ReplicaInfo} ReplicaInfo + */ + ReplicaInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ReplicaInfo) + return object; + var message = new $root.google.spanner.admin.instance.v1.ReplicaInfo(); + if (object.location != null) + message.location = String(object.location); + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.type = 0; + break; + case "READ_WRITE": + case 1: + message.type = 1; + break; + case "READ_ONLY": + case 2: + message.type = 2; + break; + case "WITNESS": + case 3: + message.type = 3; + break; + } + if (object.defaultLeaderLocation != null) + message.defaultLeaderLocation = Boolean(object.defaultLeaderLocation); + return message; + }; + + /** + * Creates a plain object from a ReplicaInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {google.spanner.admin.instance.v1.ReplicaInfo} message ReplicaInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReplicaInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.location = ""; + object.type = options.enums === String ? "TYPE_UNSPECIFIED" : 0; + object.defaultLeaderLocation = false; + } + if (message.location != null && message.hasOwnProperty("location")) + object.location = message.location; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType[message.type] === undefined ? message.type : $root.google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType[message.type] : message.type; + if (message.defaultLeaderLocation != null && message.hasOwnProperty("defaultLeaderLocation")) + object.defaultLeaderLocation = message.defaultLeaderLocation; + return object; + }; + + /** + * Converts this ReplicaInfo to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @instance + * @returns {Object.} JSON object + */ + ReplicaInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReplicaInfo + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ReplicaInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReplicaInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ReplicaInfo"; + }; + + /** + * ReplicaType enum. + * @name google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType + * @enum {number} + * @property {number} TYPE_UNSPECIFIED=0 TYPE_UNSPECIFIED value + * @property {number} READ_WRITE=1 READ_WRITE value + * @property {number} READ_ONLY=2 READ_ONLY value + * @property {number} WITNESS=3 WITNESS value + */ + ReplicaInfo.ReplicaType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "READ_WRITE"] = 1; + values[valuesById[2] = "READ_ONLY"] = 2; + values[valuesById[3] = "WITNESS"] = 3; + return values; + })(); + + return ReplicaInfo; + })(); + + v1.InstanceConfig = (function() { + + /** + * Properties of an InstanceConfig. + * @memberof google.spanner.admin.instance.v1 + * @interface IInstanceConfig + * @property {string|null} [name] InstanceConfig name + * @property {string|null} [displayName] InstanceConfig displayName + * @property {google.spanner.admin.instance.v1.InstanceConfig.Type|null} [configType] InstanceConfig configType + * @property {Array.|null} [replicas] InstanceConfig replicas + * @property {Array.|null} [optionalReplicas] InstanceConfig optionalReplicas + * @property {string|null} [baseConfig] InstanceConfig baseConfig + * @property {Object.|null} [labels] InstanceConfig labels + * @property {string|null} [etag] InstanceConfig etag + * @property {Array.|null} [leaderOptions] InstanceConfig leaderOptions + * @property {boolean|null} [reconciling] InstanceConfig reconciling + * @property {google.spanner.admin.instance.v1.InstanceConfig.State|null} [state] InstanceConfig state + * @property {google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability|null} [freeInstanceAvailability] InstanceConfig freeInstanceAvailability + * @property {google.spanner.admin.instance.v1.InstanceConfig.QuorumType|null} [quorumType] InstanceConfig quorumType + * @property {number|Long|null} [storageLimitPerProcessingUnit] InstanceConfig storageLimitPerProcessingUnit + */ + + /** + * Constructs a new InstanceConfig. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an InstanceConfig. + * @implements IInstanceConfig + * @constructor + * @param {google.spanner.admin.instance.v1.IInstanceConfig=} [properties] Properties to set + */ + function InstanceConfig(properties) { + this.replicas = []; + this.optionalReplicas = []; + this.labels = {}; + this.leaderOptions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstanceConfig name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.name = ""; + + /** + * InstanceConfig displayName. + * @member {string} displayName + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.displayName = ""; + + /** + * InstanceConfig configType. + * @member {google.spanner.admin.instance.v1.InstanceConfig.Type} configType + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.configType = 0; + + /** + * InstanceConfig replicas. + * @member {Array.} replicas + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.replicas = $util.emptyArray; + + /** + * InstanceConfig optionalReplicas. + * @member {Array.} optionalReplicas + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.optionalReplicas = $util.emptyArray; + + /** + * InstanceConfig baseConfig. + * @member {string} baseConfig + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.baseConfig = ""; + + /** + * InstanceConfig labels. + * @member {Object.} labels + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.labels = $util.emptyObject; + + /** + * InstanceConfig etag. + * @member {string} etag + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.etag = ""; + + /** + * InstanceConfig leaderOptions. + * @member {Array.} leaderOptions + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.leaderOptions = $util.emptyArray; + + /** + * InstanceConfig reconciling. + * @member {boolean} reconciling + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.reconciling = false; + + /** + * InstanceConfig state. + * @member {google.spanner.admin.instance.v1.InstanceConfig.State} state + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.state = 0; + + /** + * InstanceConfig freeInstanceAvailability. + * @member {google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability} freeInstanceAvailability + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.freeInstanceAvailability = 0; + + /** + * InstanceConfig quorumType. + * @member {google.spanner.admin.instance.v1.InstanceConfig.QuorumType} quorumType + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.quorumType = 0; + + /** + * InstanceConfig storageLimitPerProcessingUnit. + * @member {number|Long} storageLimitPerProcessingUnit + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + */ + InstanceConfig.prototype.storageLimitPerProcessingUnit = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new InstanceConfig instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {google.spanner.admin.instance.v1.IInstanceConfig=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.InstanceConfig} InstanceConfig instance + */ + InstanceConfig.create = function create(properties) { + return new InstanceConfig(properties); + }; + + /** + * Encodes the specified InstanceConfig message. Does not implicitly {@link google.spanner.admin.instance.v1.InstanceConfig.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {google.spanner.admin.instance.v1.IInstanceConfig} message InstanceConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstanceConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.displayName); + if (message.replicas != null && message.replicas.length) + for (var i = 0; i < message.replicas.length; ++i) + $root.google.spanner.admin.instance.v1.ReplicaInfo.encode(message.replicas[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.leaderOptions != null && message.leaderOptions.length) + for (var i = 0; i < message.leaderOptions.length; ++i) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.leaderOptions[i]); + if (message.configType != null && Object.hasOwnProperty.call(message, "configType")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.configType); + if (message.optionalReplicas != null && message.optionalReplicas.length) + for (var i = 0; i < message.optionalReplicas.length; ++i) + $root.google.spanner.admin.instance.v1.ReplicaInfo.encode(message.optionalReplicas[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.baseConfig != null && Object.hasOwnProperty.call(message, "baseConfig")) + writer.uint32(/* id 7, wireType 2 =*/58).string(message.baseConfig); + if (message.labels != null && Object.hasOwnProperty.call(message, "labels")) + for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) + writer.uint32(/* id 8, wireType 2 =*/66).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 9, wireType 2 =*/74).string(message.etag); + if (message.reconciling != null && Object.hasOwnProperty.call(message, "reconciling")) + writer.uint32(/* id 10, wireType 0 =*/80).bool(message.reconciling); + if (message.state != null && Object.hasOwnProperty.call(message, "state")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.state); + if (message.freeInstanceAvailability != null && Object.hasOwnProperty.call(message, "freeInstanceAvailability")) + writer.uint32(/* id 12, wireType 0 =*/96).int32(message.freeInstanceAvailability); + if (message.quorumType != null && Object.hasOwnProperty.call(message, "quorumType")) + writer.uint32(/* id 18, wireType 0 =*/144).int32(message.quorumType); + if (message.storageLimitPerProcessingUnit != null && Object.hasOwnProperty.call(message, "storageLimitPerProcessingUnit")) + writer.uint32(/* id 19, wireType 0 =*/152).int64(message.storageLimitPerProcessingUnit); + return writer; + }; + + /** + * Encodes the specified InstanceConfig message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.InstanceConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {google.spanner.admin.instance.v1.IInstanceConfig} message InstanceConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstanceConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstanceConfig message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.InstanceConfig} InstanceConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstanceConfig.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.spanner.admin.instance.v1.InstanceConfig(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.displayName = reader.string(); + break; + } + case 5: { + message.configType = reader.int32(); + break; + } + case 3: { + if (!(message.replicas && message.replicas.length)) + message.replicas = []; + message.replicas.push($root.google.spanner.admin.instance.v1.ReplicaInfo.decode(reader, reader.uint32())); + break; + } + case 6: { + if (!(message.optionalReplicas && message.optionalReplicas.length)) + message.optionalReplicas = []; + message.optionalReplicas.push($root.google.spanner.admin.instance.v1.ReplicaInfo.decode(reader, reader.uint32())); + break; + } + case 7: { + message.baseConfig = reader.string(); + break; + } + case 8: { + if (message.labels === $util.emptyObject) + message.labels = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.labels[key] = value; + break; + } + case 9: { + message.etag = reader.string(); + break; + } + case 4: { + if (!(message.leaderOptions && message.leaderOptions.length)) + message.leaderOptions = []; + message.leaderOptions.push(reader.string()); + break; + } + case 10: { + message.reconciling = reader.bool(); + break; + } + case 11: { + message.state = reader.int32(); + break; + } + case 12: { + message.freeInstanceAvailability = reader.int32(); + break; + } + case 18: { + message.quorumType = reader.int32(); + break; + } + case 19: { + message.storageLimitPerProcessingUnit = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstanceConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.InstanceConfig} InstanceConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstanceConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstanceConfig message. + * @function verify + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstanceConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.displayName != null && message.hasOwnProperty("displayName")) + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + if (message.configType != null && message.hasOwnProperty("configType")) + switch (message.configType) { + default: + return "configType: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.replicas != null && message.hasOwnProperty("replicas")) { + if (!Array.isArray(message.replicas)) + return "replicas: array expected"; + for (var i = 0; i < message.replicas.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.ReplicaInfo.verify(message.replicas[i]); + if (error) + return "replicas." + error; + } + } + if (message.optionalReplicas != null && message.hasOwnProperty("optionalReplicas")) { + if (!Array.isArray(message.optionalReplicas)) + return "optionalReplicas: array expected"; + for (var i = 0; i < message.optionalReplicas.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.ReplicaInfo.verify(message.optionalReplicas[i]); + if (error) + return "optionalReplicas." + error; + } + } + if (message.baseConfig != null && message.hasOwnProperty("baseConfig")) + if (!$util.isString(message.baseConfig)) + return "baseConfig: string expected"; + if (message.labels != null && message.hasOwnProperty("labels")) { + if (!$util.isObject(message.labels)) + return "labels: object expected"; + var key = Object.keys(message.labels); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.labels[key[i]])) + return "labels: string{k:string} expected"; + } + if (message.etag != null && message.hasOwnProperty("etag")) + if (!$util.isString(message.etag)) + return "etag: string expected"; + if (message.leaderOptions != null && message.hasOwnProperty("leaderOptions")) { + if (!Array.isArray(message.leaderOptions)) + return "leaderOptions: array expected"; + for (var i = 0; i < message.leaderOptions.length; ++i) + if (!$util.isString(message.leaderOptions[i])) + return "leaderOptions: string[] expected"; + } + if (message.reconciling != null && message.hasOwnProperty("reconciling")) + if (typeof message.reconciling !== "boolean") + return "reconciling: boolean expected"; + if (message.state != null && message.hasOwnProperty("state")) + switch (message.state) { + default: + return "state: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.freeInstanceAvailability != null && message.hasOwnProperty("freeInstanceAvailability")) + switch (message.freeInstanceAvailability) { + default: + return "freeInstanceAvailability: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + if (message.quorumType != null && message.hasOwnProperty("quorumType")) + switch (message.quorumType) { + default: + return "quorumType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.storageLimitPerProcessingUnit != null && message.hasOwnProperty("storageLimitPerProcessingUnit")) + if (!$util.isInteger(message.storageLimitPerProcessingUnit) && !(message.storageLimitPerProcessingUnit && $util.isInteger(message.storageLimitPerProcessingUnit.low) && $util.isInteger(message.storageLimitPerProcessingUnit.high))) + return "storageLimitPerProcessingUnit: integer|Long expected"; + return null; + }; + + /** + * Creates an InstanceConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.InstanceConfig} InstanceConfig + */ + InstanceConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.InstanceConfig) + return object; + var message = new $root.google.spanner.admin.instance.v1.InstanceConfig(); + if (object.name != null) + message.name = String(object.name); + if (object.displayName != null) + message.displayName = String(object.displayName); + switch (object.configType) { + default: + if (typeof object.configType === "number") { + message.configType = object.configType; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.configType = 0; + break; + case "GOOGLE_MANAGED": + case 1: + message.configType = 1; + break; + case "USER_MANAGED": + case 2: + message.configType = 2; + break; + } + if (object.replicas) { + if (!Array.isArray(object.replicas)) + throw TypeError(".google.spanner.admin.instance.v1.InstanceConfig.replicas: array expected"); + message.replicas = []; + for (var i = 0; i < object.replicas.length; ++i) { + if (typeof object.replicas[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.InstanceConfig.replicas: object expected"); + message.replicas[i] = $root.google.spanner.admin.instance.v1.ReplicaInfo.fromObject(object.replicas[i]); + } + } + if (object.optionalReplicas) { + if (!Array.isArray(object.optionalReplicas)) + throw TypeError(".google.spanner.admin.instance.v1.InstanceConfig.optionalReplicas: array expected"); + message.optionalReplicas = []; + for (var i = 0; i < object.optionalReplicas.length; ++i) { + if (typeof object.optionalReplicas[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.InstanceConfig.optionalReplicas: object expected"); + message.optionalReplicas[i] = $root.google.spanner.admin.instance.v1.ReplicaInfo.fromObject(object.optionalReplicas[i]); + } + } + if (object.baseConfig != null) + message.baseConfig = String(object.baseConfig); + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.spanner.admin.instance.v1.InstanceConfig.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + if (object.etag != null) + message.etag = String(object.etag); + if (object.leaderOptions) { + if (!Array.isArray(object.leaderOptions)) + throw TypeError(".google.spanner.admin.instance.v1.InstanceConfig.leaderOptions: array expected"); + message.leaderOptions = []; + for (var i = 0; i < object.leaderOptions.length; ++i) + message.leaderOptions[i] = String(object.leaderOptions[i]); + } + if (object.reconciling != null) + message.reconciling = Boolean(object.reconciling); + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "CREATING": + case 1: + message.state = 1; + break; + case "READY": + case 2: + message.state = 2; + break; + } + switch (object.freeInstanceAvailability) { + default: + if (typeof object.freeInstanceAvailability === "number") { + message.freeInstanceAvailability = object.freeInstanceAvailability; + break; + } + break; + case "FREE_INSTANCE_AVAILABILITY_UNSPECIFIED": + case 0: + message.freeInstanceAvailability = 0; + break; + case "AVAILABLE": + case 1: + message.freeInstanceAvailability = 1; + break; + case "UNSUPPORTED": + case 2: + message.freeInstanceAvailability = 2; + break; + case "DISABLED": + case 3: + message.freeInstanceAvailability = 3; + break; + case "QUOTA_EXCEEDED": + case 4: + message.freeInstanceAvailability = 4; + break; + } + switch (object.quorumType) { + default: + if (typeof object.quorumType === "number") { + message.quorumType = object.quorumType; + break; + } + break; + case "QUORUM_TYPE_UNSPECIFIED": + case 0: + message.quorumType = 0; + break; + case "REGION": + case 1: + message.quorumType = 1; + break; + case "DUAL_REGION": + case 2: + message.quorumType = 2; + break; + case "MULTI_REGION": + case 3: + message.quorumType = 3; + break; + } + if (object.storageLimitPerProcessingUnit != null) + if ($util.Long) + (message.storageLimitPerProcessingUnit = $util.Long.fromValue(object.storageLimitPerProcessingUnit)).unsigned = false; + else if (typeof object.storageLimitPerProcessingUnit === "string") + message.storageLimitPerProcessingUnit = parseInt(object.storageLimitPerProcessingUnit, 10); + else if (typeof object.storageLimitPerProcessingUnit === "number") + message.storageLimitPerProcessingUnit = object.storageLimitPerProcessingUnit; + else if (typeof object.storageLimitPerProcessingUnit === "object") + message.storageLimitPerProcessingUnit = new $util.LongBits(object.storageLimitPerProcessingUnit.low >>> 0, object.storageLimitPerProcessingUnit.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from an InstanceConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {google.spanner.admin.instance.v1.InstanceConfig} message InstanceConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstanceConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.replicas = []; + object.leaderOptions = []; + object.optionalReplicas = []; + } + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.name = ""; + object.displayName = ""; + object.configType = options.enums === String ? "TYPE_UNSPECIFIED" : 0; + object.baseConfig = ""; + object.etag = ""; + object.reconciling = false; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + object.freeInstanceAvailability = options.enums === String ? "FREE_INSTANCE_AVAILABILITY_UNSPECIFIED" : 0; + object.quorumType = options.enums === String ? "QUORUM_TYPE_UNSPECIFIED" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.storageLimitPerProcessingUnit = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.storageLimitPerProcessingUnit = options.longs === String ? "0" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.displayName != null && message.hasOwnProperty("displayName")) + object.displayName = message.displayName; + if (message.replicas && message.replicas.length) { + object.replicas = []; + for (var j = 0; j < message.replicas.length; ++j) + object.replicas[j] = $root.google.spanner.admin.instance.v1.ReplicaInfo.toObject(message.replicas[j], options); + } + if (message.leaderOptions && message.leaderOptions.length) { + object.leaderOptions = []; + for (var j = 0; j < message.leaderOptions.length; ++j) + object.leaderOptions[j] = message.leaderOptions[j]; + } + if (message.configType != null && message.hasOwnProperty("configType")) + object.configType = options.enums === String ? $root.google.spanner.admin.instance.v1.InstanceConfig.Type[message.configType] === undefined ? message.configType : $root.google.spanner.admin.instance.v1.InstanceConfig.Type[message.configType] : message.configType; + if (message.optionalReplicas && message.optionalReplicas.length) { + object.optionalReplicas = []; + for (var j = 0; j < message.optionalReplicas.length; ++j) + object.optionalReplicas[j] = $root.google.spanner.admin.instance.v1.ReplicaInfo.toObject(message.optionalReplicas[j], options); + } + if (message.baseConfig != null && message.hasOwnProperty("baseConfig")) + object.baseConfig = message.baseConfig; + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + if (message.etag != null && message.hasOwnProperty("etag")) + object.etag = message.etag; + if (message.reconciling != null && message.hasOwnProperty("reconciling")) + object.reconciling = message.reconciling; + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.spanner.admin.instance.v1.InstanceConfig.State[message.state] === undefined ? message.state : $root.google.spanner.admin.instance.v1.InstanceConfig.State[message.state] : message.state; + if (message.freeInstanceAvailability != null && message.hasOwnProperty("freeInstanceAvailability")) + object.freeInstanceAvailability = options.enums === String ? $root.google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability[message.freeInstanceAvailability] === undefined ? message.freeInstanceAvailability : $root.google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability[message.freeInstanceAvailability] : message.freeInstanceAvailability; + if (message.quorumType != null && message.hasOwnProperty("quorumType")) + object.quorumType = options.enums === String ? $root.google.spanner.admin.instance.v1.InstanceConfig.QuorumType[message.quorumType] === undefined ? message.quorumType : $root.google.spanner.admin.instance.v1.InstanceConfig.QuorumType[message.quorumType] : message.quorumType; + if (message.storageLimitPerProcessingUnit != null && message.hasOwnProperty("storageLimitPerProcessingUnit")) + if (typeof message.storageLimitPerProcessingUnit === "number") + object.storageLimitPerProcessingUnit = options.longs === String ? String(message.storageLimitPerProcessingUnit) : message.storageLimitPerProcessingUnit; + else + object.storageLimitPerProcessingUnit = options.longs === String ? $util.Long.prototype.toString.call(message.storageLimitPerProcessingUnit) : options.longs === Number ? new $util.LongBits(message.storageLimitPerProcessingUnit.low >>> 0, message.storageLimitPerProcessingUnit.high >>> 0).toNumber() : message.storageLimitPerProcessingUnit; + return object; + }; + + /** + * Converts this InstanceConfig to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @instance + * @returns {Object.} JSON object + */ + InstanceConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstanceConfig + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.InstanceConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstanceConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.InstanceConfig"; + }; + + /** + * Type enum. + * @name google.spanner.admin.instance.v1.InstanceConfig.Type + * @enum {number} + * @property {number} TYPE_UNSPECIFIED=0 TYPE_UNSPECIFIED value + * @property {number} GOOGLE_MANAGED=1 GOOGLE_MANAGED value + * @property {number} USER_MANAGED=2 USER_MANAGED value + */ + InstanceConfig.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "GOOGLE_MANAGED"] = 1; + values[valuesById[2] = "USER_MANAGED"] = 2; + return values; + })(); + + /** + * State enum. + * @name google.spanner.admin.instance.v1.InstanceConfig.State + * @enum {number} + * @property {number} STATE_UNSPECIFIED=0 STATE_UNSPECIFIED value + * @property {number} CREATING=1 CREATING value + * @property {number} READY=2 READY value + */ + InstanceConfig.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = 0; + values[valuesById[1] = "CREATING"] = 1; + values[valuesById[2] = "READY"] = 2; + return values; + })(); + + /** + * FreeInstanceAvailability enum. + * @name google.spanner.admin.instance.v1.InstanceConfig.FreeInstanceAvailability + * @enum {number} + * @property {number} FREE_INSTANCE_AVAILABILITY_UNSPECIFIED=0 FREE_INSTANCE_AVAILABILITY_UNSPECIFIED value + * @property {number} AVAILABLE=1 AVAILABLE value + * @property {number} UNSUPPORTED=2 UNSUPPORTED value + * @property {number} DISABLED=3 DISABLED value + * @property {number} QUOTA_EXCEEDED=4 QUOTA_EXCEEDED value + */ + InstanceConfig.FreeInstanceAvailability = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FREE_INSTANCE_AVAILABILITY_UNSPECIFIED"] = 0; + values[valuesById[1] = "AVAILABLE"] = 1; + values[valuesById[2] = "UNSUPPORTED"] = 2; + values[valuesById[3] = "DISABLED"] = 3; + values[valuesById[4] = "QUOTA_EXCEEDED"] = 4; + return values; + })(); + + /** + * QuorumType enum. + * @name google.spanner.admin.instance.v1.InstanceConfig.QuorumType + * @enum {number} + * @property {number} QUORUM_TYPE_UNSPECIFIED=0 QUORUM_TYPE_UNSPECIFIED value + * @property {number} REGION=1 REGION value + * @property {number} DUAL_REGION=2 DUAL_REGION value + * @property {number} MULTI_REGION=3 MULTI_REGION value + */ + InstanceConfig.QuorumType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "QUORUM_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "REGION"] = 1; + values[valuesById[2] = "DUAL_REGION"] = 2; + values[valuesById[3] = "MULTI_REGION"] = 3; + return values; + })(); + + return InstanceConfig; + })(); + + v1.ReplicaComputeCapacity = (function() { + + /** + * Properties of a ReplicaComputeCapacity. + * @memberof google.spanner.admin.instance.v1 + * @interface IReplicaComputeCapacity + * @property {google.spanner.admin.instance.v1.IReplicaSelection|null} [replicaSelection] ReplicaComputeCapacity replicaSelection + * @property {number|null} [nodeCount] ReplicaComputeCapacity nodeCount + * @property {number|null} [processingUnits] ReplicaComputeCapacity processingUnits + */ + + /** + * Constructs a new ReplicaComputeCapacity. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ReplicaComputeCapacity. + * @implements IReplicaComputeCapacity + * @constructor + * @param {google.spanner.admin.instance.v1.IReplicaComputeCapacity=} [properties] Properties to set + */ + function ReplicaComputeCapacity(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReplicaComputeCapacity replicaSelection. + * @member {google.spanner.admin.instance.v1.IReplicaSelection|null|undefined} replicaSelection + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @instance + */ + ReplicaComputeCapacity.prototype.replicaSelection = null; + + /** + * ReplicaComputeCapacity nodeCount. + * @member {number|null|undefined} nodeCount + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @instance + */ + ReplicaComputeCapacity.prototype.nodeCount = null; + + /** + * ReplicaComputeCapacity processingUnits. + * @member {number|null|undefined} processingUnits + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @instance + */ + ReplicaComputeCapacity.prototype.processingUnits = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ReplicaComputeCapacity computeCapacity. + * @member {"nodeCount"|"processingUnits"|undefined} computeCapacity + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @instance + */ + Object.defineProperty(ReplicaComputeCapacity.prototype, "computeCapacity", { + get: $util.oneOfGetter($oneOfFields = ["nodeCount", "processingUnits"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReplicaComputeCapacity instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {google.spanner.admin.instance.v1.IReplicaComputeCapacity=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ReplicaComputeCapacity} ReplicaComputeCapacity instance + */ + ReplicaComputeCapacity.create = function create(properties) { + return new ReplicaComputeCapacity(properties); + }; + + /** + * Encodes the specified ReplicaComputeCapacity message. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaComputeCapacity.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {google.spanner.admin.instance.v1.IReplicaComputeCapacity} message ReplicaComputeCapacity message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReplicaComputeCapacity.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.replicaSelection != null && Object.hasOwnProperty.call(message, "replicaSelection")) + $root.google.spanner.admin.instance.v1.ReplicaSelection.encode(message.replicaSelection, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nodeCount != null && Object.hasOwnProperty.call(message, "nodeCount")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.nodeCount); + if (message.processingUnits != null && Object.hasOwnProperty.call(message, "processingUnits")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.processingUnits); + return writer; + }; + + /** + * Encodes the specified ReplicaComputeCapacity message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaComputeCapacity.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {google.spanner.admin.instance.v1.IReplicaComputeCapacity} message ReplicaComputeCapacity message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReplicaComputeCapacity.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReplicaComputeCapacity message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ReplicaComputeCapacity} ReplicaComputeCapacity + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReplicaComputeCapacity.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.spanner.admin.instance.v1.ReplicaComputeCapacity(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.replicaSelection = $root.google.spanner.admin.instance.v1.ReplicaSelection.decode(reader, reader.uint32()); + break; + } + case 2: { + message.nodeCount = reader.int32(); + break; + } + case 3: { + message.processingUnits = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReplicaComputeCapacity message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ReplicaComputeCapacity} ReplicaComputeCapacity + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReplicaComputeCapacity.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReplicaComputeCapacity message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReplicaComputeCapacity.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.replicaSelection != null && message.hasOwnProperty("replicaSelection")) { + var error = $root.google.spanner.admin.instance.v1.ReplicaSelection.verify(message.replicaSelection); + if (error) + return "replicaSelection." + error; + } + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) { + properties.computeCapacity = 1; + if (!$util.isInteger(message.nodeCount)) + return "nodeCount: integer expected"; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) { + if (properties.computeCapacity === 1) + return "computeCapacity: multiple values"; + properties.computeCapacity = 1; + if (!$util.isInteger(message.processingUnits)) + return "processingUnits: integer expected"; + } + return null; + }; + + /** + * Creates a ReplicaComputeCapacity message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ReplicaComputeCapacity} ReplicaComputeCapacity + */ + ReplicaComputeCapacity.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ReplicaComputeCapacity) + return object; + var message = new $root.google.spanner.admin.instance.v1.ReplicaComputeCapacity(); + if (object.replicaSelection != null) { + if (typeof object.replicaSelection !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ReplicaComputeCapacity.replicaSelection: object expected"); + message.replicaSelection = $root.google.spanner.admin.instance.v1.ReplicaSelection.fromObject(object.replicaSelection); + } + if (object.nodeCount != null) + message.nodeCount = object.nodeCount | 0; + if (object.processingUnits != null) + message.processingUnits = object.processingUnits | 0; + return message; + }; + + /** + * Creates a plain object from a ReplicaComputeCapacity message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {google.spanner.admin.instance.v1.ReplicaComputeCapacity} message ReplicaComputeCapacity + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReplicaComputeCapacity.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.replicaSelection = null; + if (message.replicaSelection != null && message.hasOwnProperty("replicaSelection")) + object.replicaSelection = $root.google.spanner.admin.instance.v1.ReplicaSelection.toObject(message.replicaSelection, options); + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) { + object.nodeCount = message.nodeCount; + if (options.oneofs) + object.computeCapacity = "nodeCount"; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) { + object.processingUnits = message.processingUnits; + if (options.oneofs) + object.computeCapacity = "processingUnits"; + } + return object; + }; + + /** + * Converts this ReplicaComputeCapacity to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @instance + * @returns {Object.} JSON object + */ + ReplicaComputeCapacity.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReplicaComputeCapacity + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ReplicaComputeCapacity + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReplicaComputeCapacity.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ReplicaComputeCapacity"; + }; + + return ReplicaComputeCapacity; + })(); + + v1.AutoscalingConfig = (function() { + + /** + * Properties of an AutoscalingConfig. + * @memberof google.spanner.admin.instance.v1 + * @interface IAutoscalingConfig + * @property {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits|null} [autoscalingLimits] AutoscalingConfig autoscalingLimits + * @property {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets|null} [autoscalingTargets] AutoscalingConfig autoscalingTargets + * @property {Array.|null} [asymmetricAutoscalingOptions] AutoscalingConfig asymmetricAutoscalingOptions + */ + + /** + * Constructs a new AutoscalingConfig. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an AutoscalingConfig. + * @implements IAutoscalingConfig + * @constructor + * @param {google.spanner.admin.instance.v1.IAutoscalingConfig=} [properties] Properties to set + */ + function AutoscalingConfig(properties) { + this.asymmetricAutoscalingOptions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AutoscalingConfig autoscalingLimits. + * @member {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits|null|undefined} autoscalingLimits + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @instance + */ + AutoscalingConfig.prototype.autoscalingLimits = null; + + /** + * AutoscalingConfig autoscalingTargets. + * @member {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets|null|undefined} autoscalingTargets + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @instance + */ + AutoscalingConfig.prototype.autoscalingTargets = null; + + /** + * AutoscalingConfig asymmetricAutoscalingOptions. + * @member {Array.} asymmetricAutoscalingOptions + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @instance + */ + AutoscalingConfig.prototype.asymmetricAutoscalingOptions = $util.emptyArray; + + /** + * Creates a new AutoscalingConfig instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {google.spanner.admin.instance.v1.IAutoscalingConfig=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig} AutoscalingConfig instance + */ + AutoscalingConfig.create = function create(properties) { + return new AutoscalingConfig(properties); + }; + + /** + * Encodes the specified AutoscalingConfig message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {google.spanner.admin.instance.v1.IAutoscalingConfig} message AutoscalingConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AutoscalingConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.autoscalingLimits != null && Object.hasOwnProperty.call(message, "autoscalingLimits")) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.encode(message.autoscalingLimits, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.autoscalingTargets != null && Object.hasOwnProperty.call(message, "autoscalingTargets")) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.encode(message.autoscalingTargets, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.asymmetricAutoscalingOptions != null && message.asymmetricAutoscalingOptions.length) + for (var i = 0; i < message.asymmetricAutoscalingOptions.length; ++i) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.encode(message.asymmetricAutoscalingOptions[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified AutoscalingConfig message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {google.spanner.admin.instance.v1.IAutoscalingConfig} message AutoscalingConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AutoscalingConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AutoscalingConfig message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig} AutoscalingConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AutoscalingConfig.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.spanner.admin.instance.v1.AutoscalingConfig(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.autoscalingLimits = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.decode(reader, reader.uint32()); + break; + } + case 2: { + message.autoscalingTargets = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.decode(reader, reader.uint32()); + break; + } + case 3: { + if (!(message.asymmetricAutoscalingOptions && message.asymmetricAutoscalingOptions.length)) + message.asymmetricAutoscalingOptions = []; + message.asymmetricAutoscalingOptions.push($root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AutoscalingConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig} AutoscalingConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AutoscalingConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AutoscalingConfig message. + * @function verify + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AutoscalingConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.autoscalingLimits != null && message.hasOwnProperty("autoscalingLimits")) { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.verify(message.autoscalingLimits); + if (error) + return "autoscalingLimits." + error; + } + if (message.autoscalingTargets != null && message.hasOwnProperty("autoscalingTargets")) { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.verify(message.autoscalingTargets); + if (error) + return "autoscalingTargets." + error; + } + if (message.asymmetricAutoscalingOptions != null && message.hasOwnProperty("asymmetricAutoscalingOptions")) { + if (!Array.isArray(message.asymmetricAutoscalingOptions)) + return "asymmetricAutoscalingOptions: array expected"; + for (var i = 0; i < message.asymmetricAutoscalingOptions.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.verify(message.asymmetricAutoscalingOptions[i]); + if (error) + return "asymmetricAutoscalingOptions." + error; + } + } + return null; + }; + + /** + * Creates an AutoscalingConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig} AutoscalingConfig + */ + AutoscalingConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.AutoscalingConfig) + return object; + var message = new $root.google.spanner.admin.instance.v1.AutoscalingConfig(); + if (object.autoscalingLimits != null) { + if (typeof object.autoscalingLimits !== "object") + throw TypeError(".google.spanner.admin.instance.v1.AutoscalingConfig.autoscalingLimits: object expected"); + message.autoscalingLimits = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.fromObject(object.autoscalingLimits); + } + if (object.autoscalingTargets != null) { + if (typeof object.autoscalingTargets !== "object") + throw TypeError(".google.spanner.admin.instance.v1.AutoscalingConfig.autoscalingTargets: object expected"); + message.autoscalingTargets = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.fromObject(object.autoscalingTargets); + } + if (object.asymmetricAutoscalingOptions) { + if (!Array.isArray(object.asymmetricAutoscalingOptions)) + throw TypeError(".google.spanner.admin.instance.v1.AutoscalingConfig.asymmetricAutoscalingOptions: array expected"); + message.asymmetricAutoscalingOptions = []; + for (var i = 0; i < object.asymmetricAutoscalingOptions.length; ++i) { + if (typeof object.asymmetricAutoscalingOptions[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.AutoscalingConfig.asymmetricAutoscalingOptions: object expected"); + message.asymmetricAutoscalingOptions[i] = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.fromObject(object.asymmetricAutoscalingOptions[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an AutoscalingConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig} message AutoscalingConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AutoscalingConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.asymmetricAutoscalingOptions = []; + if (options.defaults) { + object.autoscalingLimits = null; + object.autoscalingTargets = null; + } + if (message.autoscalingLimits != null && message.hasOwnProperty("autoscalingLimits")) + object.autoscalingLimits = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.toObject(message.autoscalingLimits, options); + if (message.autoscalingTargets != null && message.hasOwnProperty("autoscalingTargets")) + object.autoscalingTargets = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.toObject(message.autoscalingTargets, options); + if (message.asymmetricAutoscalingOptions && message.asymmetricAutoscalingOptions.length) { + object.asymmetricAutoscalingOptions = []; + for (var j = 0; j < message.asymmetricAutoscalingOptions.length; ++j) + object.asymmetricAutoscalingOptions[j] = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.toObject(message.asymmetricAutoscalingOptions[j], options); + } + return object; + }; + + /** + * Converts this AutoscalingConfig to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @instance + * @returns {Object.} JSON object + */ + AutoscalingConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AutoscalingConfig + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AutoscalingConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.AutoscalingConfig"; + }; + + AutoscalingConfig.AutoscalingLimits = (function() { + + /** + * Properties of an AutoscalingLimits. + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @interface IAutoscalingLimits + * @property {number|null} [minNodes] AutoscalingLimits minNodes + * @property {number|null} [minProcessingUnits] AutoscalingLimits minProcessingUnits + * @property {number|null} [maxNodes] AutoscalingLimits maxNodes + * @property {number|null} [maxProcessingUnits] AutoscalingLimits maxProcessingUnits + */ + + /** + * Constructs a new AutoscalingLimits. + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @classdesc Represents an AutoscalingLimits. + * @implements IAutoscalingLimits + * @constructor + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits=} [properties] Properties to set + */ + function AutoscalingLimits(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AutoscalingLimits minNodes. + * @member {number|null|undefined} minNodes + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @instance + */ + AutoscalingLimits.prototype.minNodes = null; + + /** + * AutoscalingLimits minProcessingUnits. + * @member {number|null|undefined} minProcessingUnits + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @instance + */ + AutoscalingLimits.prototype.minProcessingUnits = null; + + /** + * AutoscalingLimits maxNodes. + * @member {number|null|undefined} maxNodes + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @instance + */ + AutoscalingLimits.prototype.maxNodes = null; + + /** + * AutoscalingLimits maxProcessingUnits. + * @member {number|null|undefined} maxProcessingUnits + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @instance + */ + AutoscalingLimits.prototype.maxProcessingUnits = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * AutoscalingLimits minLimit. + * @member {"minNodes"|"minProcessingUnits"|undefined} minLimit + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @instance + */ + Object.defineProperty(AutoscalingLimits.prototype, "minLimit", { + get: $util.oneOfGetter($oneOfFields = ["minNodes", "minProcessingUnits"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * AutoscalingLimits maxLimit. + * @member {"maxNodes"|"maxProcessingUnits"|undefined} maxLimit + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @instance + */ + Object.defineProperty(AutoscalingLimits.prototype, "maxLimit", { + get: $util.oneOfGetter($oneOfFields = ["maxNodes", "maxProcessingUnits"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new AutoscalingLimits instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits} AutoscalingLimits instance + */ + AutoscalingLimits.create = function create(properties) { + return new AutoscalingLimits(properties); + }; + + /** + * Encodes the specified AutoscalingLimits message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits} message AutoscalingLimits message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AutoscalingLimits.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.minNodes != null && Object.hasOwnProperty.call(message, "minNodes")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.minNodes); + if (message.minProcessingUnits != null && Object.hasOwnProperty.call(message, "minProcessingUnits")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.minProcessingUnits); + if (message.maxNodes != null && Object.hasOwnProperty.call(message, "maxNodes")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.maxNodes); + if (message.maxProcessingUnits != null && Object.hasOwnProperty.call(message, "maxProcessingUnits")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.maxProcessingUnits); + return writer; + }; + + /** + * Encodes the specified AutoscalingLimits message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits} message AutoscalingLimits message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AutoscalingLimits.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AutoscalingLimits message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits} AutoscalingLimits + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AutoscalingLimits.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.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.minNodes = reader.int32(); + break; + } + case 2: { + message.minProcessingUnits = reader.int32(); + break; + } + case 3: { + message.maxNodes = reader.int32(); + break; + } + case 4: { + message.maxProcessingUnits = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AutoscalingLimits message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits} AutoscalingLimits + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AutoscalingLimits.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AutoscalingLimits message. + * @function verify + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AutoscalingLimits.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.minNodes != null && message.hasOwnProperty("minNodes")) { + properties.minLimit = 1; + if (!$util.isInteger(message.minNodes)) + return "minNodes: integer expected"; + } + if (message.minProcessingUnits != null && message.hasOwnProperty("minProcessingUnits")) { + if (properties.minLimit === 1) + return "minLimit: multiple values"; + properties.minLimit = 1; + if (!$util.isInteger(message.minProcessingUnits)) + return "minProcessingUnits: integer expected"; + } + if (message.maxNodes != null && message.hasOwnProperty("maxNodes")) { + properties.maxLimit = 1; + if (!$util.isInteger(message.maxNodes)) + return "maxNodes: integer expected"; + } + if (message.maxProcessingUnits != null && message.hasOwnProperty("maxProcessingUnits")) { + if (properties.maxLimit === 1) + return "maxLimit: multiple values"; + properties.maxLimit = 1; + if (!$util.isInteger(message.maxProcessingUnits)) + return "maxProcessingUnits: integer expected"; + } + return null; + }; + + /** + * Creates an AutoscalingLimits message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits} AutoscalingLimits + */ + AutoscalingLimits.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits) + return object; + var message = new $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits(); + if (object.minNodes != null) + message.minNodes = object.minNodes | 0; + if (object.minProcessingUnits != null) + message.minProcessingUnits = object.minProcessingUnits | 0; + if (object.maxNodes != null) + message.maxNodes = object.maxNodes | 0; + if (object.maxProcessingUnits != null) + message.maxProcessingUnits = object.maxProcessingUnits | 0; + return message; + }; + + /** + * Creates a plain object from an AutoscalingLimits message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits} message AutoscalingLimits + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AutoscalingLimits.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.minNodes != null && message.hasOwnProperty("minNodes")) { + object.minNodes = message.minNodes; + if (options.oneofs) + object.minLimit = "minNodes"; + } + if (message.minProcessingUnits != null && message.hasOwnProperty("minProcessingUnits")) { + object.minProcessingUnits = message.minProcessingUnits; + if (options.oneofs) + object.minLimit = "minProcessingUnits"; + } + if (message.maxNodes != null && message.hasOwnProperty("maxNodes")) { + object.maxNodes = message.maxNodes; + if (options.oneofs) + object.maxLimit = "maxNodes"; + } + if (message.maxProcessingUnits != null && message.hasOwnProperty("maxProcessingUnits")) { + object.maxProcessingUnits = message.maxProcessingUnits; + if (options.oneofs) + object.maxLimit = "maxProcessingUnits"; + } + return object; + }; + + /** + * Converts this AutoscalingLimits to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @instance + * @returns {Object.} JSON object + */ + AutoscalingLimits.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AutoscalingLimits + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AutoscalingLimits.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits"; + }; + + return AutoscalingLimits; + })(); + + AutoscalingConfig.AutoscalingTargets = (function() { + + /** + * Properties of an AutoscalingTargets. + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @interface IAutoscalingTargets + * @property {number|null} [highPriorityCpuUtilizationPercent] AutoscalingTargets highPriorityCpuUtilizationPercent + * @property {number|null} [totalCpuUtilizationPercent] AutoscalingTargets totalCpuUtilizationPercent + * @property {number|null} [storageUtilizationPercent] AutoscalingTargets storageUtilizationPercent + */ + + /** + * Constructs a new AutoscalingTargets. + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @classdesc Represents an AutoscalingTargets. + * @implements IAutoscalingTargets + * @constructor + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets=} [properties] Properties to set + */ + function AutoscalingTargets(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AutoscalingTargets highPriorityCpuUtilizationPercent. + * @member {number} highPriorityCpuUtilizationPercent + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @instance + */ + AutoscalingTargets.prototype.highPriorityCpuUtilizationPercent = 0; + + /** + * AutoscalingTargets totalCpuUtilizationPercent. + * @member {number} totalCpuUtilizationPercent + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @instance + */ + AutoscalingTargets.prototype.totalCpuUtilizationPercent = 0; + + /** + * AutoscalingTargets storageUtilizationPercent. + * @member {number} storageUtilizationPercent + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @instance + */ + AutoscalingTargets.prototype.storageUtilizationPercent = 0; + + /** + * Creates a new AutoscalingTargets instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets} AutoscalingTargets instance + */ + AutoscalingTargets.create = function create(properties) { + return new AutoscalingTargets(properties); + }; + + /** + * Encodes the specified AutoscalingTargets message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets} message AutoscalingTargets message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AutoscalingTargets.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.highPriorityCpuUtilizationPercent != null && Object.hasOwnProperty.call(message, "highPriorityCpuUtilizationPercent")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.highPriorityCpuUtilizationPercent); + if (message.storageUtilizationPercent != null && Object.hasOwnProperty.call(message, "storageUtilizationPercent")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.storageUtilizationPercent); + if (message.totalCpuUtilizationPercent != null && Object.hasOwnProperty.call(message, "totalCpuUtilizationPercent")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.totalCpuUtilizationPercent); + return writer; + }; + + /** + * Encodes the specified AutoscalingTargets message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingTargets} message AutoscalingTargets message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AutoscalingTargets.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AutoscalingTargets message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets} AutoscalingTargets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AutoscalingTargets.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.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.highPriorityCpuUtilizationPercent = reader.int32(); + break; + } + case 4: { + message.totalCpuUtilizationPercent = reader.int32(); + break; + } + case 2: { + message.storageUtilizationPercent = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AutoscalingTargets message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets} AutoscalingTargets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AutoscalingTargets.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AutoscalingTargets message. + * @function verify + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AutoscalingTargets.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.highPriorityCpuUtilizationPercent != null && message.hasOwnProperty("highPriorityCpuUtilizationPercent")) + if (!$util.isInteger(message.highPriorityCpuUtilizationPercent)) + return "highPriorityCpuUtilizationPercent: integer expected"; + if (message.totalCpuUtilizationPercent != null && message.hasOwnProperty("totalCpuUtilizationPercent")) + if (!$util.isInteger(message.totalCpuUtilizationPercent)) + return "totalCpuUtilizationPercent: integer expected"; + if (message.storageUtilizationPercent != null && message.hasOwnProperty("storageUtilizationPercent")) + if (!$util.isInteger(message.storageUtilizationPercent)) + return "storageUtilizationPercent: integer expected"; + return null; + }; + + /** + * Creates an AutoscalingTargets message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets} AutoscalingTargets + */ + AutoscalingTargets.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets) + return object; + var message = new $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets(); + if (object.highPriorityCpuUtilizationPercent != null) + message.highPriorityCpuUtilizationPercent = object.highPriorityCpuUtilizationPercent | 0; + if (object.totalCpuUtilizationPercent != null) + message.totalCpuUtilizationPercent = object.totalCpuUtilizationPercent | 0; + if (object.storageUtilizationPercent != null) + message.storageUtilizationPercent = object.storageUtilizationPercent | 0; + return message; + }; + + /** + * Creates a plain object from an AutoscalingTargets message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets} message AutoscalingTargets + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AutoscalingTargets.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.highPriorityCpuUtilizationPercent = 0; + object.storageUtilizationPercent = 0; + object.totalCpuUtilizationPercent = 0; + } + if (message.highPriorityCpuUtilizationPercent != null && message.hasOwnProperty("highPriorityCpuUtilizationPercent")) + object.highPriorityCpuUtilizationPercent = message.highPriorityCpuUtilizationPercent; + if (message.storageUtilizationPercent != null && message.hasOwnProperty("storageUtilizationPercent")) + object.storageUtilizationPercent = message.storageUtilizationPercent; + if (message.totalCpuUtilizationPercent != null && message.hasOwnProperty("totalCpuUtilizationPercent")) + object.totalCpuUtilizationPercent = message.totalCpuUtilizationPercent; + return object; + }; + + /** + * Converts this AutoscalingTargets to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @instance + * @returns {Object.} JSON object + */ + AutoscalingTargets.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AutoscalingTargets + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AutoscalingTargets.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingTargets"; + }; + + return AutoscalingTargets; + })(); + + AutoscalingConfig.AsymmetricAutoscalingOption = (function() { + + /** + * Properties of an AsymmetricAutoscalingOption. + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @interface IAsymmetricAutoscalingOption + * @property {google.spanner.admin.instance.v1.IReplicaSelection|null} [replicaSelection] AsymmetricAutoscalingOption replicaSelection + * @property {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides|null} [overrides] AsymmetricAutoscalingOption overrides + */ + + /** + * Constructs a new AsymmetricAutoscalingOption. + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig + * @classdesc Represents an AsymmetricAutoscalingOption. + * @implements IAsymmetricAutoscalingOption + * @constructor + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption=} [properties] Properties to set + */ + function AsymmetricAutoscalingOption(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AsymmetricAutoscalingOption replicaSelection. + * @member {google.spanner.admin.instance.v1.IReplicaSelection|null|undefined} replicaSelection + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @instance + */ + AsymmetricAutoscalingOption.prototype.replicaSelection = null; + + /** + * AsymmetricAutoscalingOption overrides. + * @member {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides|null|undefined} overrides + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @instance + */ + AsymmetricAutoscalingOption.prototype.overrides = null; + + /** + * Creates a new AsymmetricAutoscalingOption instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption} AsymmetricAutoscalingOption instance + */ + AsymmetricAutoscalingOption.create = function create(properties) { + return new AsymmetricAutoscalingOption(properties); + }; + + /** + * Encodes the specified AsymmetricAutoscalingOption message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption} message AsymmetricAutoscalingOption message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AsymmetricAutoscalingOption.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.replicaSelection != null && Object.hasOwnProperty.call(message, "replicaSelection")) + $root.google.spanner.admin.instance.v1.ReplicaSelection.encode(message.replicaSelection, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.overrides != null && Object.hasOwnProperty.call(message, "overrides")) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.encode(message.overrides, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified AsymmetricAutoscalingOption message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.IAsymmetricAutoscalingOption} message AsymmetricAutoscalingOption message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AsymmetricAutoscalingOption.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AsymmetricAutoscalingOption message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption} AsymmetricAutoscalingOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AsymmetricAutoscalingOption.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.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.replicaSelection = $root.google.spanner.admin.instance.v1.ReplicaSelection.decode(reader, reader.uint32()); + break; + } + case 2: { + message.overrides = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AsymmetricAutoscalingOption message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption} AsymmetricAutoscalingOption + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AsymmetricAutoscalingOption.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AsymmetricAutoscalingOption message. + * @function verify + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AsymmetricAutoscalingOption.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.replicaSelection != null && message.hasOwnProperty("replicaSelection")) { + var error = $root.google.spanner.admin.instance.v1.ReplicaSelection.verify(message.replicaSelection); + if (error) + return "replicaSelection." + error; + } + if (message.overrides != null && message.hasOwnProperty("overrides")) { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.verify(message.overrides); + if (error) + return "overrides." + error; + } + return null; + }; + + /** + * Creates an AsymmetricAutoscalingOption message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption} AsymmetricAutoscalingOption + */ + AsymmetricAutoscalingOption.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption) + return object; + var message = new $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption(); + if (object.replicaSelection != null) { + if (typeof object.replicaSelection !== "object") + throw TypeError(".google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.replicaSelection: object expected"); + message.replicaSelection = $root.google.spanner.admin.instance.v1.ReplicaSelection.fromObject(object.replicaSelection); + } + if (object.overrides != null) { + if (typeof object.overrides !== "object") + throw TypeError(".google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.overrides: object expected"); + message.overrides = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.fromObject(object.overrides); + } + return message; + }; + + /** + * Creates a plain object from an AsymmetricAutoscalingOption message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption} message AsymmetricAutoscalingOption + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AsymmetricAutoscalingOption.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.replicaSelection = null; + object.overrides = null; + } + if (message.replicaSelection != null && message.hasOwnProperty("replicaSelection")) + object.replicaSelection = $root.google.spanner.admin.instance.v1.ReplicaSelection.toObject(message.replicaSelection, options); + if (message.overrides != null && message.hasOwnProperty("overrides")) + object.overrides = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.toObject(message.overrides, options); + return object; + }; + + /** + * Converts this AsymmetricAutoscalingOption to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @instance + * @returns {Object.} JSON object + */ + AsymmetricAutoscalingOption.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AsymmetricAutoscalingOption + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AsymmetricAutoscalingOption.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption"; + }; + + AsymmetricAutoscalingOption.AutoscalingConfigOverrides = (function() { + + /** + * Properties of an AutoscalingConfigOverrides. + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @interface IAutoscalingConfigOverrides + * @property {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits|null} [autoscalingLimits] AutoscalingConfigOverrides autoscalingLimits + * @property {number|null} [autoscalingTargetHighPriorityCpuUtilizationPercent] AutoscalingConfigOverrides autoscalingTargetHighPriorityCpuUtilizationPercent + * @property {number|null} [autoscalingTargetTotalCpuUtilizationPercent] AutoscalingConfigOverrides autoscalingTargetTotalCpuUtilizationPercent + * @property {boolean|null} [disableHighPriorityCpuAutoscaling] AutoscalingConfigOverrides disableHighPriorityCpuAutoscaling + * @property {boolean|null} [disableTotalCpuAutoscaling] AutoscalingConfigOverrides disableTotalCpuAutoscaling + */ + + /** + * Constructs a new AutoscalingConfigOverrides. + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption + * @classdesc Represents an AutoscalingConfigOverrides. + * @implements IAutoscalingConfigOverrides + * @constructor + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides=} [properties] Properties to set + */ + function AutoscalingConfigOverrides(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AutoscalingConfigOverrides autoscalingLimits. + * @member {google.spanner.admin.instance.v1.AutoscalingConfig.IAutoscalingLimits|null|undefined} autoscalingLimits + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @instance + */ + AutoscalingConfigOverrides.prototype.autoscalingLimits = null; + + /** + * AutoscalingConfigOverrides autoscalingTargetHighPriorityCpuUtilizationPercent. + * @member {number} autoscalingTargetHighPriorityCpuUtilizationPercent + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @instance + */ + AutoscalingConfigOverrides.prototype.autoscalingTargetHighPriorityCpuUtilizationPercent = 0; + + /** + * AutoscalingConfigOverrides autoscalingTargetTotalCpuUtilizationPercent. + * @member {number} autoscalingTargetTotalCpuUtilizationPercent + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @instance + */ + AutoscalingConfigOverrides.prototype.autoscalingTargetTotalCpuUtilizationPercent = 0; + + /** + * AutoscalingConfigOverrides disableHighPriorityCpuAutoscaling. + * @member {boolean} disableHighPriorityCpuAutoscaling + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @instance + */ + AutoscalingConfigOverrides.prototype.disableHighPriorityCpuAutoscaling = false; + + /** + * AutoscalingConfigOverrides disableTotalCpuAutoscaling. + * @member {boolean} disableTotalCpuAutoscaling + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @instance + */ + AutoscalingConfigOverrides.prototype.disableTotalCpuAutoscaling = false; + + /** + * Creates a new AutoscalingConfigOverrides instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides} AutoscalingConfigOverrides instance + */ + AutoscalingConfigOverrides.create = function create(properties) { + return new AutoscalingConfigOverrides(properties); + }; + + /** + * Encodes the specified AutoscalingConfigOverrides message. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides} message AutoscalingConfigOverrides message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AutoscalingConfigOverrides.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.autoscalingLimits != null && Object.hasOwnProperty.call(message, "autoscalingLimits")) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.encode(message.autoscalingLimits, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.autoscalingTargetHighPriorityCpuUtilizationPercent != null && Object.hasOwnProperty.call(message, "autoscalingTargetHighPriorityCpuUtilizationPercent")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.autoscalingTargetHighPriorityCpuUtilizationPercent); + if (message.autoscalingTargetTotalCpuUtilizationPercent != null && Object.hasOwnProperty.call(message, "autoscalingTargetTotalCpuUtilizationPercent")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.autoscalingTargetTotalCpuUtilizationPercent); + if (message.disableHighPriorityCpuAutoscaling != null && Object.hasOwnProperty.call(message, "disableHighPriorityCpuAutoscaling")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.disableHighPriorityCpuAutoscaling); + if (message.disableTotalCpuAutoscaling != null && Object.hasOwnProperty.call(message, "disableTotalCpuAutoscaling")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.disableTotalCpuAutoscaling); + return writer; + }; + + /** + * Encodes the specified AutoscalingConfigOverrides message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.IAutoscalingConfigOverrides} message AutoscalingConfigOverrides message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AutoscalingConfigOverrides.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AutoscalingConfigOverrides message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides} AutoscalingConfigOverrides + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AutoscalingConfigOverrides.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.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.autoscalingLimits = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.decode(reader, reader.uint32()); + break; + } + case 2: { + message.autoscalingTargetHighPriorityCpuUtilizationPercent = reader.int32(); + break; + } + case 4: { + message.autoscalingTargetTotalCpuUtilizationPercent = reader.int32(); + break; + } + case 5: { + message.disableHighPriorityCpuAutoscaling = reader.bool(); + break; + } + case 6: { + message.disableTotalCpuAutoscaling = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AutoscalingConfigOverrides message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides} AutoscalingConfigOverrides + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AutoscalingConfigOverrides.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AutoscalingConfigOverrides message. + * @function verify + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AutoscalingConfigOverrides.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.autoscalingLimits != null && message.hasOwnProperty("autoscalingLimits")) { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.verify(message.autoscalingLimits); + if (error) + return "autoscalingLimits." + error; + } + if (message.autoscalingTargetHighPriorityCpuUtilizationPercent != null && message.hasOwnProperty("autoscalingTargetHighPriorityCpuUtilizationPercent")) + if (!$util.isInteger(message.autoscalingTargetHighPriorityCpuUtilizationPercent)) + return "autoscalingTargetHighPriorityCpuUtilizationPercent: integer expected"; + if (message.autoscalingTargetTotalCpuUtilizationPercent != null && message.hasOwnProperty("autoscalingTargetTotalCpuUtilizationPercent")) + if (!$util.isInteger(message.autoscalingTargetTotalCpuUtilizationPercent)) + return "autoscalingTargetTotalCpuUtilizationPercent: integer expected"; + if (message.disableHighPriorityCpuAutoscaling != null && message.hasOwnProperty("disableHighPriorityCpuAutoscaling")) + if (typeof message.disableHighPriorityCpuAutoscaling !== "boolean") + return "disableHighPriorityCpuAutoscaling: boolean expected"; + if (message.disableTotalCpuAutoscaling != null && message.hasOwnProperty("disableTotalCpuAutoscaling")) + if (typeof message.disableTotalCpuAutoscaling !== "boolean") + return "disableTotalCpuAutoscaling: boolean expected"; + return null; + }; + + /** + * Creates an AutoscalingConfigOverrides message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides} AutoscalingConfigOverrides + */ + AutoscalingConfigOverrides.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides) + return object; + var message = new $root.google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides(); + if (object.autoscalingLimits != null) { + if (typeof object.autoscalingLimits !== "object") + throw TypeError(".google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides.autoscalingLimits: object expected"); + message.autoscalingLimits = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.fromObject(object.autoscalingLimits); + } + if (object.autoscalingTargetHighPriorityCpuUtilizationPercent != null) + message.autoscalingTargetHighPriorityCpuUtilizationPercent = object.autoscalingTargetHighPriorityCpuUtilizationPercent | 0; + if (object.autoscalingTargetTotalCpuUtilizationPercent != null) + message.autoscalingTargetTotalCpuUtilizationPercent = object.autoscalingTargetTotalCpuUtilizationPercent | 0; + if (object.disableHighPriorityCpuAutoscaling != null) + message.disableHighPriorityCpuAutoscaling = Boolean(object.disableHighPriorityCpuAutoscaling); + if (object.disableTotalCpuAutoscaling != null) + message.disableTotalCpuAutoscaling = Boolean(object.disableTotalCpuAutoscaling); + return message; + }; + + /** + * Creates a plain object from an AutoscalingConfigOverrides message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides} message AutoscalingConfigOverrides + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AutoscalingConfigOverrides.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.autoscalingLimits = null; + object.autoscalingTargetHighPriorityCpuUtilizationPercent = 0; + object.autoscalingTargetTotalCpuUtilizationPercent = 0; + object.disableHighPriorityCpuAutoscaling = false; + object.disableTotalCpuAutoscaling = false; + } + if (message.autoscalingLimits != null && message.hasOwnProperty("autoscalingLimits")) + object.autoscalingLimits = $root.google.spanner.admin.instance.v1.AutoscalingConfig.AutoscalingLimits.toObject(message.autoscalingLimits, options); + if (message.autoscalingTargetHighPriorityCpuUtilizationPercent != null && message.hasOwnProperty("autoscalingTargetHighPriorityCpuUtilizationPercent")) + object.autoscalingTargetHighPriorityCpuUtilizationPercent = message.autoscalingTargetHighPriorityCpuUtilizationPercent; + if (message.autoscalingTargetTotalCpuUtilizationPercent != null && message.hasOwnProperty("autoscalingTargetTotalCpuUtilizationPercent")) + object.autoscalingTargetTotalCpuUtilizationPercent = message.autoscalingTargetTotalCpuUtilizationPercent; + if (message.disableHighPriorityCpuAutoscaling != null && message.hasOwnProperty("disableHighPriorityCpuAutoscaling")) + object.disableHighPriorityCpuAutoscaling = message.disableHighPriorityCpuAutoscaling; + if (message.disableTotalCpuAutoscaling != null && message.hasOwnProperty("disableTotalCpuAutoscaling")) + object.disableTotalCpuAutoscaling = message.disableTotalCpuAutoscaling; + return object; + }; + + /** + * Converts this AutoscalingConfigOverrides to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @instance + * @returns {Object.} JSON object + */ + AutoscalingConfigOverrides.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AutoscalingConfigOverrides + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AutoscalingConfigOverrides.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.AutoscalingConfig.AsymmetricAutoscalingOption.AutoscalingConfigOverrides"; + }; + + return AutoscalingConfigOverrides; + })(); + + return AsymmetricAutoscalingOption; + })(); + + return AutoscalingConfig; + })(); + + v1.Instance = (function() { + + /** + * Properties of an Instance. + * @memberof google.spanner.admin.instance.v1 + * @interface IInstance + * @property {string|null} [name] Instance name + * @property {string|null} [config] Instance config + * @property {string|null} [displayName] Instance displayName + * @property {number|null} [nodeCount] Instance nodeCount + * @property {number|null} [processingUnits] Instance processingUnits + * @property {Array.|null} [replicaComputeCapacity] Instance replicaComputeCapacity + * @property {google.spanner.admin.instance.v1.IAutoscalingConfig|null} [autoscalingConfig] Instance autoscalingConfig + * @property {google.spanner.admin.instance.v1.Instance.State|null} [state] Instance state + * @property {Object.|null} [labels] Instance labels + * @property {google.spanner.admin.instance.v1.Instance.InstanceType|null} [instanceType] Instance instanceType + * @property {Array.|null} [endpointUris] Instance endpointUris + * @property {google.protobuf.ITimestamp|null} [createTime] Instance createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] Instance updateTime + * @property {google.spanner.admin.instance.v1.IFreeInstanceMetadata|null} [freeInstanceMetadata] Instance freeInstanceMetadata + * @property {google.spanner.admin.instance.v1.Instance.Edition|null} [edition] Instance edition + * @property {google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType|null} [defaultBackupScheduleType] Instance defaultBackupScheduleType + */ + + /** + * Constructs a new Instance. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an Instance. + * @implements IInstance + * @constructor + * @param {google.spanner.admin.instance.v1.IInstance=} [properties] Properties to set + */ + function Instance(properties) { + this.replicaComputeCapacity = []; + this.labels = {}; + this.endpointUris = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Instance name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.name = ""; + + /** + * Instance config. + * @member {string} config + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.config = ""; + + /** + * Instance displayName. + * @member {string} displayName + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.displayName = ""; + + /** + * Instance nodeCount. + * @member {number} nodeCount + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.nodeCount = 0; + + /** + * Instance processingUnits. + * @member {number} processingUnits + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.processingUnits = 0; + + /** + * Instance replicaComputeCapacity. + * @member {Array.} replicaComputeCapacity + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.replicaComputeCapacity = $util.emptyArray; + + /** + * Instance autoscalingConfig. + * @member {google.spanner.admin.instance.v1.IAutoscalingConfig|null|undefined} autoscalingConfig + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.autoscalingConfig = null; + + /** + * Instance state. + * @member {google.spanner.admin.instance.v1.Instance.State} state + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.state = 0; + + /** + * Instance labels. + * @member {Object.} labels + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.labels = $util.emptyObject; + + /** + * Instance instanceType. + * @member {google.spanner.admin.instance.v1.Instance.InstanceType} instanceType + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.instanceType = 0; + + /** + * Instance endpointUris. + * @member {Array.} endpointUris + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.endpointUris = $util.emptyArray; + + /** + * Instance createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.createTime = null; + + /** + * Instance updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.updateTime = null; + + /** + * Instance freeInstanceMetadata. + * @member {google.spanner.admin.instance.v1.IFreeInstanceMetadata|null|undefined} freeInstanceMetadata + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.freeInstanceMetadata = null; + + /** + * Instance edition. + * @member {google.spanner.admin.instance.v1.Instance.Edition} edition + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.edition = 0; + + /** + * Instance defaultBackupScheduleType. + * @member {google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType} defaultBackupScheduleType + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + */ + Instance.prototype.defaultBackupScheduleType = 0; + + /** + * Creates a new Instance instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {google.spanner.admin.instance.v1.IInstance=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.Instance} Instance instance + */ + Instance.create = function create(properties) { + return new Instance(properties); + }; + + /** + * Encodes the specified Instance message. Does not implicitly {@link google.spanner.admin.instance.v1.Instance.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {google.spanner.admin.instance.v1.IInstance} message Instance message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Instance.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.config != null && Object.hasOwnProperty.call(message, "config")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.config); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.displayName); + if (message.nodeCount != null && Object.hasOwnProperty.call(message, "nodeCount")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.nodeCount); + if (message.state != null && Object.hasOwnProperty.call(message, "state")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.state); + if (message.labels != null && Object.hasOwnProperty.call(message, "labels")) + for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) + writer.uint32(/* id 7, wireType 2 =*/58).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); + if (message.endpointUris != null && message.endpointUris.length) + for (var i = 0; i < message.endpointUris.length; ++i) + writer.uint32(/* id 8, wireType 2 =*/66).string(message.endpointUris[i]); + if (message.processingUnits != null && Object.hasOwnProperty.call(message, "processingUnits")) + writer.uint32(/* id 9, wireType 0 =*/72).int32(message.processingUnits); + if (message.instanceType != null && Object.hasOwnProperty.call(message, "instanceType")) + writer.uint32(/* id 10, wireType 0 =*/80).int32(message.instanceType); + if (message.createTime != null && Object.hasOwnProperty.call(message, "createTime")) + $root.google.protobuf.Timestamp.encode(message.createTime, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); + if (message.updateTime != null && Object.hasOwnProperty.call(message, "updateTime")) + $root.google.protobuf.Timestamp.encode(message.updateTime, writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim(); + if (message.freeInstanceMetadata != null && Object.hasOwnProperty.call(message, "freeInstanceMetadata")) + $root.google.spanner.admin.instance.v1.FreeInstanceMetadata.encode(message.freeInstanceMetadata, writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim(); + if (message.autoscalingConfig != null && Object.hasOwnProperty.call(message, "autoscalingConfig")) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.encode(message.autoscalingConfig, writer.uint32(/* id 17, wireType 2 =*/138).fork()).ldelim(); + if (message.replicaComputeCapacity != null && message.replicaComputeCapacity.length) + for (var i = 0; i < message.replicaComputeCapacity.length; ++i) + $root.google.spanner.admin.instance.v1.ReplicaComputeCapacity.encode(message.replicaComputeCapacity[i], writer.uint32(/* id 19, wireType 2 =*/154).fork()).ldelim(); + if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) + writer.uint32(/* id 20, wireType 0 =*/160).int32(message.edition); + if (message.defaultBackupScheduleType != null && Object.hasOwnProperty.call(message, "defaultBackupScheduleType")) + writer.uint32(/* id 23, wireType 0 =*/184).int32(message.defaultBackupScheduleType); + return writer; + }; + + /** + * Encodes the specified Instance message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.Instance.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {google.spanner.admin.instance.v1.IInstance} message Instance message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Instance.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an Instance message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.Instance} Instance + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Instance.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.spanner.admin.instance.v1.Instance(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.config = reader.string(); + break; + } + case 3: { + message.displayName = reader.string(); + break; + } + case 5: { + message.nodeCount = reader.int32(); + break; + } + case 9: { + message.processingUnits = reader.int32(); + break; + } + case 19: { + if (!(message.replicaComputeCapacity && message.replicaComputeCapacity.length)) + message.replicaComputeCapacity = []; + message.replicaComputeCapacity.push($root.google.spanner.admin.instance.v1.ReplicaComputeCapacity.decode(reader, reader.uint32())); + break; + } + case 17: { + message.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.decode(reader, reader.uint32()); + break; + } + case 6: { + message.state = reader.int32(); + break; + } + case 7: { + if (message.labels === $util.emptyObject) + message.labels = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.labels[key] = value; + break; + } + case 10: { + message.instanceType = reader.int32(); + break; + } + case 8: { + if (!(message.endpointUris && message.endpointUris.length)) + message.endpointUris = []; + message.endpointUris.push(reader.string()); + break; + } + case 11: { + message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 12: { + message.updateTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 13: { + message.freeInstanceMetadata = $root.google.spanner.admin.instance.v1.FreeInstanceMetadata.decode(reader, reader.uint32()); + break; + } + case 20: { + message.edition = reader.int32(); + break; + } + case 23: { + message.defaultBackupScheduleType = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an Instance message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.Instance} Instance + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Instance.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an Instance message. + * @function verify + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Instance.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.config != null && message.hasOwnProperty("config")) + if (!$util.isString(message.config)) + return "config: string expected"; + if (message.displayName != null && message.hasOwnProperty("displayName")) + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) + if (!$util.isInteger(message.nodeCount)) + return "nodeCount: integer expected"; + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) + if (!$util.isInteger(message.processingUnits)) + return "processingUnits: integer expected"; + if (message.replicaComputeCapacity != null && message.hasOwnProperty("replicaComputeCapacity")) { + if (!Array.isArray(message.replicaComputeCapacity)) + return "replicaComputeCapacity: array expected"; + for (var i = 0; i < message.replicaComputeCapacity.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.ReplicaComputeCapacity.verify(message.replicaComputeCapacity[i]); + if (error) + return "replicaComputeCapacity." + error; + } + } + if (message.autoscalingConfig != null && message.hasOwnProperty("autoscalingConfig")) { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.verify(message.autoscalingConfig); + if (error) + return "autoscalingConfig." + error; + } + if (message.state != null && message.hasOwnProperty("state")) + switch (message.state) { + default: + return "state: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.labels != null && message.hasOwnProperty("labels")) { + if (!$util.isObject(message.labels)) + return "labels: object expected"; + var key = Object.keys(message.labels); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.labels[key[i]])) + return "labels: string{k:string} expected"; + } + if (message.instanceType != null && message.hasOwnProperty("instanceType")) + switch (message.instanceType) { + default: + return "instanceType: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.endpointUris != null && message.hasOwnProperty("endpointUris")) { + if (!Array.isArray(message.endpointUris)) + return "endpointUris: array expected"; + for (var i = 0; i < message.endpointUris.length; ++i) + if (!$util.isString(message.endpointUris[i])) + return "endpointUris: string[] expected"; + } + if (message.createTime != null && message.hasOwnProperty("createTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.createTime); + if (error) + return "createTime." + error; + } + if (message.updateTime != null && message.hasOwnProperty("updateTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.updateTime); + if (error) + return "updateTime." + error; + } + if (message.freeInstanceMetadata != null && message.hasOwnProperty("freeInstanceMetadata")) { + var error = $root.google.spanner.admin.instance.v1.FreeInstanceMetadata.verify(message.freeInstanceMetadata); + if (error) + return "freeInstanceMetadata." + error; + } + if (message.edition != null && message.hasOwnProperty("edition")) + switch (message.edition) { + default: + return "edition: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.defaultBackupScheduleType != null && message.hasOwnProperty("defaultBackupScheduleType")) + switch (message.defaultBackupScheduleType) { + default: + return "defaultBackupScheduleType: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates an Instance message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.Instance} Instance + */ + Instance.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.Instance) + return object; + var message = new $root.google.spanner.admin.instance.v1.Instance(); + if (object.name != null) + message.name = String(object.name); + if (object.config != null) + message.config = String(object.config); + if (object.displayName != null) + message.displayName = String(object.displayName); + if (object.nodeCount != null) + message.nodeCount = object.nodeCount | 0; + if (object.processingUnits != null) + message.processingUnits = object.processingUnits | 0; + if (object.replicaComputeCapacity) { + if (!Array.isArray(object.replicaComputeCapacity)) + throw TypeError(".google.spanner.admin.instance.v1.Instance.replicaComputeCapacity: array expected"); + message.replicaComputeCapacity = []; + for (var i = 0; i < object.replicaComputeCapacity.length; ++i) { + if (typeof object.replicaComputeCapacity[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.Instance.replicaComputeCapacity: object expected"); + message.replicaComputeCapacity[i] = $root.google.spanner.admin.instance.v1.ReplicaComputeCapacity.fromObject(object.replicaComputeCapacity[i]); + } + } + if (object.autoscalingConfig != null) { + if (typeof object.autoscalingConfig !== "object") + throw TypeError(".google.spanner.admin.instance.v1.Instance.autoscalingConfig: object expected"); + message.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.fromObject(object.autoscalingConfig); + } + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "CREATING": + case 1: + message.state = 1; + break; + case "READY": + case 2: + message.state = 2; + break; + } + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.spanner.admin.instance.v1.Instance.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + switch (object.instanceType) { + default: + if (typeof object.instanceType === "number") { + message.instanceType = object.instanceType; + break; + } + break; + case "INSTANCE_TYPE_UNSPECIFIED": + case 0: + message.instanceType = 0; + break; + case "PROVISIONED": + case 1: + message.instanceType = 1; + break; + case "FREE_INSTANCE": + case 2: + message.instanceType = 2; + break; + } + if (object.endpointUris) { + if (!Array.isArray(object.endpointUris)) + throw TypeError(".google.spanner.admin.instance.v1.Instance.endpointUris: array expected"); + message.endpointUris = []; + for (var i = 0; i < object.endpointUris.length; ++i) + message.endpointUris[i] = String(object.endpointUris[i]); + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.Instance.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.Instance.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + if (object.freeInstanceMetadata != null) { + if (typeof object.freeInstanceMetadata !== "object") + throw TypeError(".google.spanner.admin.instance.v1.Instance.freeInstanceMetadata: object expected"); + message.freeInstanceMetadata = $root.google.spanner.admin.instance.v1.FreeInstanceMetadata.fromObject(object.freeInstanceMetadata); + } + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNSPECIFIED": + case 0: + message.edition = 0; + break; + case "STANDARD": + case 1: + message.edition = 1; + break; + case "ENTERPRISE": + case 2: + message.edition = 2; + break; + case "ENTERPRISE_PLUS": + case 3: + message.edition = 3; + break; + } + switch (object.defaultBackupScheduleType) { + default: + if (typeof object.defaultBackupScheduleType === "number") { + message.defaultBackupScheduleType = object.defaultBackupScheduleType; + break; + } + break; + case "DEFAULT_BACKUP_SCHEDULE_TYPE_UNSPECIFIED": + case 0: + message.defaultBackupScheduleType = 0; + break; + case "NONE": + case 1: + message.defaultBackupScheduleType = 1; + break; + case "AUTOMATIC": + case 2: + message.defaultBackupScheduleType = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an Instance message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {google.spanner.admin.instance.v1.Instance} message Instance + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Instance.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.endpointUris = []; + object.replicaComputeCapacity = []; + } + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.name = ""; + object.config = ""; + object.displayName = ""; + object.nodeCount = 0; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + object.processingUnits = 0; + object.instanceType = options.enums === String ? "INSTANCE_TYPE_UNSPECIFIED" : 0; + object.createTime = null; + object.updateTime = null; + object.freeInstanceMetadata = null; + object.autoscalingConfig = null; + object.edition = options.enums === String ? "EDITION_UNSPECIFIED" : 0; + object.defaultBackupScheduleType = options.enums === String ? "DEFAULT_BACKUP_SCHEDULE_TYPE_UNSPECIFIED" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.config != null && message.hasOwnProperty("config")) + object.config = message.config; + if (message.displayName != null && message.hasOwnProperty("displayName")) + object.displayName = message.displayName; + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) + object.nodeCount = message.nodeCount; + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.spanner.admin.instance.v1.Instance.State[message.state] === undefined ? message.state : $root.google.spanner.admin.instance.v1.Instance.State[message.state] : message.state; + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + if (message.endpointUris && message.endpointUris.length) { + object.endpointUris = []; + for (var j = 0; j < message.endpointUris.length; ++j) + object.endpointUris[j] = message.endpointUris[j]; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) + object.processingUnits = message.processingUnits; + if (message.instanceType != null && message.hasOwnProperty("instanceType")) + object.instanceType = options.enums === String ? $root.google.spanner.admin.instance.v1.Instance.InstanceType[message.instanceType] === undefined ? message.instanceType : $root.google.spanner.admin.instance.v1.Instance.InstanceType[message.instanceType] : message.instanceType; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.freeInstanceMetadata != null && message.hasOwnProperty("freeInstanceMetadata")) + object.freeInstanceMetadata = $root.google.spanner.admin.instance.v1.FreeInstanceMetadata.toObject(message.freeInstanceMetadata, options); + if (message.autoscalingConfig != null && message.hasOwnProperty("autoscalingConfig")) + object.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.toObject(message.autoscalingConfig, options); + if (message.replicaComputeCapacity && message.replicaComputeCapacity.length) { + object.replicaComputeCapacity = []; + for (var j = 0; j < message.replicaComputeCapacity.length; ++j) + object.replicaComputeCapacity[j] = $root.google.spanner.admin.instance.v1.ReplicaComputeCapacity.toObject(message.replicaComputeCapacity[j], options); + } + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.spanner.admin.instance.v1.Instance.Edition[message.edition] === undefined ? message.edition : $root.google.spanner.admin.instance.v1.Instance.Edition[message.edition] : message.edition; + if (message.defaultBackupScheduleType != null && message.hasOwnProperty("defaultBackupScheduleType")) + object.defaultBackupScheduleType = options.enums === String ? $root.google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType[message.defaultBackupScheduleType] === undefined ? message.defaultBackupScheduleType : $root.google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType[message.defaultBackupScheduleType] : message.defaultBackupScheduleType; + return object; + }; + + /** + * Converts this Instance to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.Instance + * @instance + * @returns {Object.} JSON object + */ + Instance.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Instance + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.Instance + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Instance.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.Instance"; + }; + + /** + * State enum. + * @name google.spanner.admin.instance.v1.Instance.State + * @enum {number} + * @property {number} STATE_UNSPECIFIED=0 STATE_UNSPECIFIED value + * @property {number} CREATING=1 CREATING value + * @property {number} READY=2 READY value + */ + Instance.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = 0; + values[valuesById[1] = "CREATING"] = 1; + values[valuesById[2] = "READY"] = 2; + return values; + })(); + + /** + * InstanceType enum. + * @name google.spanner.admin.instance.v1.Instance.InstanceType + * @enum {number} + * @property {number} INSTANCE_TYPE_UNSPECIFIED=0 INSTANCE_TYPE_UNSPECIFIED value + * @property {number} PROVISIONED=1 PROVISIONED value + * @property {number} FREE_INSTANCE=2 FREE_INSTANCE value + */ + Instance.InstanceType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "INSTANCE_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "PROVISIONED"] = 1; + values[valuesById[2] = "FREE_INSTANCE"] = 2; + return values; + })(); + + /** + * Edition enum. + * @name google.spanner.admin.instance.v1.Instance.Edition + * @enum {number} + * @property {number} EDITION_UNSPECIFIED=0 EDITION_UNSPECIFIED value + * @property {number} STANDARD=1 STANDARD value + * @property {number} ENTERPRISE=2 ENTERPRISE value + * @property {number} ENTERPRISE_PLUS=3 ENTERPRISE_PLUS value + */ + Instance.Edition = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "EDITION_UNSPECIFIED"] = 0; + values[valuesById[1] = "STANDARD"] = 1; + values[valuesById[2] = "ENTERPRISE"] = 2; + values[valuesById[3] = "ENTERPRISE_PLUS"] = 3; + return values; + })(); + + /** + * DefaultBackupScheduleType enum. + * @name google.spanner.admin.instance.v1.Instance.DefaultBackupScheduleType + * @enum {number} + * @property {number} DEFAULT_BACKUP_SCHEDULE_TYPE_UNSPECIFIED=0 DEFAULT_BACKUP_SCHEDULE_TYPE_UNSPECIFIED value + * @property {number} NONE=1 NONE value + * @property {number} AUTOMATIC=2 AUTOMATIC value + */ + Instance.DefaultBackupScheduleType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_BACKUP_SCHEDULE_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "NONE"] = 1; + values[valuesById[2] = "AUTOMATIC"] = 2; + return values; + })(); + + return Instance; + })(); + + v1.ListInstanceConfigsRequest = (function() { + + /** + * Properties of a ListInstanceConfigsRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstanceConfigsRequest + * @property {string|null} [parent] ListInstanceConfigsRequest parent + * @property {number|null} [pageSize] ListInstanceConfigsRequest pageSize + * @property {string|null} [pageToken] ListInstanceConfigsRequest pageToken + */ + + /** + * Constructs a new ListInstanceConfigsRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstanceConfigsRequest. + * @implements IListInstanceConfigsRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsRequest=} [properties] Properties to set + */ + function ListInstanceConfigsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstanceConfigsRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @instance + */ + ListInstanceConfigsRequest.prototype.parent = ""; + + /** + * ListInstanceConfigsRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @instance + */ + ListInstanceConfigsRequest.prototype.pageSize = 0; + + /** + * ListInstanceConfigsRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @instance + */ + ListInstanceConfigsRequest.prototype.pageToken = ""; + + /** + * Creates a new ListInstanceConfigsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigsRequest} ListInstanceConfigsRequest instance + */ + ListInstanceConfigsRequest.create = function create(properties) { + return new ListInstanceConfigsRequest(properties); + }; + + /** + * Encodes the specified ListInstanceConfigsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsRequest} message ListInstanceConfigsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstanceConfigsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListInstanceConfigsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsRequest} message ListInstanceConfigsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstanceConfigsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstanceConfigsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigsRequest} ListInstanceConfigsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstanceConfigsRequest.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.spanner.admin.instance.v1.ListInstanceConfigsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstanceConfigsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigsRequest} ListInstanceConfigsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstanceConfigsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstanceConfigsRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstanceConfigsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListInstanceConfigsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigsRequest} ListInstanceConfigsRequest + */ + ListInstanceConfigsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstanceConfigsRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstanceConfigsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListInstanceConfigsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {google.spanner.admin.instance.v1.ListInstanceConfigsRequest} message ListInstanceConfigsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstanceConfigsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListInstanceConfigsRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @instance + * @returns {Object.} JSON object + */ + ListInstanceConfigsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstanceConfigsRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstanceConfigsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstanceConfigsRequest"; + }; + + return ListInstanceConfigsRequest; + })(); + + v1.ListInstanceConfigsResponse = (function() { + + /** + * Properties of a ListInstanceConfigsResponse. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstanceConfigsResponse + * @property {Array.|null} [instanceConfigs] ListInstanceConfigsResponse instanceConfigs + * @property {string|null} [nextPageToken] ListInstanceConfigsResponse nextPageToken + */ + + /** + * Constructs a new ListInstanceConfigsResponse. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstanceConfigsResponse. + * @implements IListInstanceConfigsResponse + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsResponse=} [properties] Properties to set + */ + function ListInstanceConfigsResponse(properties) { + this.instanceConfigs = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstanceConfigsResponse instanceConfigs. + * @member {Array.} instanceConfigs + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @instance + */ + ListInstanceConfigsResponse.prototype.instanceConfigs = $util.emptyArray; + + /** + * ListInstanceConfigsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @instance + */ + ListInstanceConfigsResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListInstanceConfigsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsResponse=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigsResponse} ListInstanceConfigsResponse instance + */ + ListInstanceConfigsResponse.create = function create(properties) { + return new ListInstanceConfigsResponse(properties); + }; + + /** + * Encodes the specified ListInstanceConfigsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsResponse} message ListInstanceConfigsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstanceConfigsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceConfigs != null && message.instanceConfigs.length) + for (var i = 0; i < message.instanceConfigs.length; ++i) + $root.google.spanner.admin.instance.v1.InstanceConfig.encode(message.instanceConfigs[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListInstanceConfigsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigsResponse} message ListInstanceConfigsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstanceConfigsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstanceConfigsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigsResponse} ListInstanceConfigsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstanceConfigsResponse.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.spanner.admin.instance.v1.ListInstanceConfigsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.instanceConfigs && message.instanceConfigs.length)) + message.instanceConfigs = []; + message.instanceConfigs.push($root.google.spanner.admin.instance.v1.InstanceConfig.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstanceConfigsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigsResponse} ListInstanceConfigsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstanceConfigsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstanceConfigsResponse message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstanceConfigsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instanceConfigs != null && message.hasOwnProperty("instanceConfigs")) { + if (!Array.isArray(message.instanceConfigs)) + return "instanceConfigs: array expected"; + for (var i = 0; i < message.instanceConfigs.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.InstanceConfig.verify(message.instanceConfigs[i]); + if (error) + return "instanceConfigs." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListInstanceConfigsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigsResponse} ListInstanceConfigsResponse + */ + ListInstanceConfigsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstanceConfigsResponse) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstanceConfigsResponse(); + if (object.instanceConfigs) { + if (!Array.isArray(object.instanceConfigs)) + throw TypeError(".google.spanner.admin.instance.v1.ListInstanceConfigsResponse.instanceConfigs: array expected"); + message.instanceConfigs = []; + for (var i = 0; i < object.instanceConfigs.length; ++i) { + if (typeof object.instanceConfigs[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ListInstanceConfigsResponse.instanceConfigs: object expected"); + message.instanceConfigs[i] = $root.google.spanner.admin.instance.v1.InstanceConfig.fromObject(object.instanceConfigs[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListInstanceConfigsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {google.spanner.admin.instance.v1.ListInstanceConfigsResponse} message ListInstanceConfigsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstanceConfigsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.instanceConfigs = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.instanceConfigs && message.instanceConfigs.length) { + object.instanceConfigs = []; + for (var j = 0; j < message.instanceConfigs.length; ++j) + object.instanceConfigs[j] = $root.google.spanner.admin.instance.v1.InstanceConfig.toObject(message.instanceConfigs[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListInstanceConfigsResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @instance + * @returns {Object.} JSON object + */ + ListInstanceConfigsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstanceConfigsResponse + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstanceConfigsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstanceConfigsResponse"; + }; + + return ListInstanceConfigsResponse; + })(); + + v1.GetInstanceConfigRequest = (function() { + + /** + * Properties of a GetInstanceConfigRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IGetInstanceConfigRequest + * @property {string|null} [name] GetInstanceConfigRequest name + */ + + /** + * Constructs a new GetInstanceConfigRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a GetInstanceConfigRequest. + * @implements IGetInstanceConfigRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IGetInstanceConfigRequest=} [properties] Properties to set + */ + function GetInstanceConfigRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetInstanceConfigRequest name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @instance + */ + GetInstanceConfigRequest.prototype.name = ""; + + /** + * Creates a new GetInstanceConfigRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstanceConfigRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.GetInstanceConfigRequest} GetInstanceConfigRequest instance + */ + GetInstanceConfigRequest.create = function create(properties) { + return new GetInstanceConfigRequest(properties); + }; + + /** + * Encodes the specified GetInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceConfigRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstanceConfigRequest} message GetInstanceConfigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetInstanceConfigRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceConfigRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstanceConfigRequest} message GetInstanceConfigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetInstanceConfigRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetInstanceConfigRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.GetInstanceConfigRequest} GetInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetInstanceConfigRequest.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.spanner.admin.instance.v1.GetInstanceConfigRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetInstanceConfigRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.GetInstanceConfigRequest} GetInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetInstanceConfigRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetInstanceConfigRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetInstanceConfigRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.GetInstanceConfigRequest} GetInstanceConfigRequest + */ + GetInstanceConfigRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.GetInstanceConfigRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.GetInstanceConfigRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetInstanceConfigRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.GetInstanceConfigRequest} message GetInstanceConfigRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetInstanceConfigRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetInstanceConfigRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @instance + * @returns {Object.} JSON object + */ + GetInstanceConfigRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetInstanceConfigRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.GetInstanceConfigRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetInstanceConfigRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.GetInstanceConfigRequest"; + }; + + return GetInstanceConfigRequest; + })(); + + v1.CreateInstanceConfigRequest = (function() { + + /** + * Properties of a CreateInstanceConfigRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface ICreateInstanceConfigRequest + * @property {string|null} [parent] CreateInstanceConfigRequest parent + * @property {string|null} [instanceConfigId] CreateInstanceConfigRequest instanceConfigId + * @property {google.spanner.admin.instance.v1.IInstanceConfig|null} [instanceConfig] CreateInstanceConfigRequest instanceConfig + * @property {boolean|null} [validateOnly] CreateInstanceConfigRequest validateOnly + */ + + /** + * Constructs a new CreateInstanceConfigRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a CreateInstanceConfigRequest. + * @implements ICreateInstanceConfigRequest + * @constructor + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigRequest=} [properties] Properties to set + */ + function CreateInstanceConfigRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateInstanceConfigRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @instance + */ + CreateInstanceConfigRequest.prototype.parent = ""; + + /** + * CreateInstanceConfigRequest instanceConfigId. + * @member {string} instanceConfigId + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @instance + */ + CreateInstanceConfigRequest.prototype.instanceConfigId = ""; + + /** + * CreateInstanceConfigRequest instanceConfig. + * @member {google.spanner.admin.instance.v1.IInstanceConfig|null|undefined} instanceConfig + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @instance + */ + CreateInstanceConfigRequest.prototype.instanceConfig = null; + + /** + * CreateInstanceConfigRequest validateOnly. + * @member {boolean} validateOnly + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @instance + */ + CreateInstanceConfigRequest.prototype.validateOnly = false; + + /** + * Creates a new CreateInstanceConfigRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.CreateInstanceConfigRequest} CreateInstanceConfigRequest instance + */ + CreateInstanceConfigRequest.create = function create(properties) { + return new CreateInstanceConfigRequest(properties); + }; + + /** + * Encodes the specified CreateInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceConfigRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigRequest} message CreateInstanceConfigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstanceConfigRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.instanceConfigId != null && Object.hasOwnProperty.call(message, "instanceConfigId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceConfigId); + if (message.instanceConfig != null && Object.hasOwnProperty.call(message, "instanceConfig")) + $root.google.spanner.admin.instance.v1.InstanceConfig.encode(message.instanceConfig, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.validateOnly != null && Object.hasOwnProperty.call(message, "validateOnly")) + writer.uint32(/* id 4, wireType 0 =*/32).bool(message.validateOnly); + return writer; + }; + + /** + * Encodes the specified CreateInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceConfigRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigRequest} message CreateInstanceConfigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstanceConfigRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateInstanceConfigRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.CreateInstanceConfigRequest} CreateInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstanceConfigRequest.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.spanner.admin.instance.v1.CreateInstanceConfigRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.instanceConfigId = reader.string(); + break; + } + case 3: { + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.decode(reader, reader.uint32()); + break; + } + case 4: { + message.validateOnly = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateInstanceConfigRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.CreateInstanceConfigRequest} CreateInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstanceConfigRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateInstanceConfigRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateInstanceConfigRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.instanceConfigId != null && message.hasOwnProperty("instanceConfigId")) + if (!$util.isString(message.instanceConfigId)) + return "instanceConfigId: string expected"; + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) { + var error = $root.google.spanner.admin.instance.v1.InstanceConfig.verify(message.instanceConfig); + if (error) + return "instanceConfig." + error; + } + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + if (typeof message.validateOnly !== "boolean") + return "validateOnly: boolean expected"; + return null; + }; + + /** + * Creates a CreateInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.CreateInstanceConfigRequest} CreateInstanceConfigRequest + */ + CreateInstanceConfigRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.CreateInstanceConfigRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.CreateInstanceConfigRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.instanceConfigId != null) + message.instanceConfigId = String(object.instanceConfigId); + if (object.instanceConfig != null) { + if (typeof object.instanceConfig !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceConfigRequest.instanceConfig: object expected"); + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.fromObject(object.instanceConfig); + } + if (object.validateOnly != null) + message.validateOnly = Boolean(object.validateOnly); + return message; + }; + + /** + * Creates a plain object from a CreateInstanceConfigRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.CreateInstanceConfigRequest} message CreateInstanceConfigRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateInstanceConfigRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.instanceConfigId = ""; + object.instanceConfig = null; + object.validateOnly = false; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.instanceConfigId != null && message.hasOwnProperty("instanceConfigId")) + object.instanceConfigId = message.instanceConfigId; + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) + object.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.toObject(message.instanceConfig, options); + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + object.validateOnly = message.validateOnly; + return object; + }; + + /** + * Converts this CreateInstanceConfigRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @instance + * @returns {Object.} JSON object + */ + CreateInstanceConfigRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateInstanceConfigRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateInstanceConfigRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.CreateInstanceConfigRequest"; + }; + + return CreateInstanceConfigRequest; + })(); + + v1.UpdateInstanceConfigRequest = (function() { + + /** + * Properties of an UpdateInstanceConfigRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IUpdateInstanceConfigRequest + * @property {google.spanner.admin.instance.v1.IInstanceConfig|null} [instanceConfig] UpdateInstanceConfigRequest instanceConfig + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateInstanceConfigRequest updateMask + * @property {boolean|null} [validateOnly] UpdateInstanceConfigRequest validateOnly + */ + + /** + * Constructs a new UpdateInstanceConfigRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an UpdateInstanceConfigRequest. + * @implements IUpdateInstanceConfigRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest=} [properties] Properties to set + */ + function UpdateInstanceConfigRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateInstanceConfigRequest instanceConfig. + * @member {google.spanner.admin.instance.v1.IInstanceConfig|null|undefined} instanceConfig + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @instance + */ + UpdateInstanceConfigRequest.prototype.instanceConfig = null; + + /** + * UpdateInstanceConfigRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @instance + */ + UpdateInstanceConfigRequest.prototype.updateMask = null; + + /** + * UpdateInstanceConfigRequest validateOnly. + * @member {boolean} validateOnly + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @instance + */ + UpdateInstanceConfigRequest.prototype.validateOnly = false; + + /** + * Creates a new UpdateInstanceConfigRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.UpdateInstanceConfigRequest} UpdateInstanceConfigRequest instance + */ + UpdateInstanceConfigRequest.create = function create(properties) { + return new UpdateInstanceConfigRequest(properties); + }; + + /** + * Encodes the specified UpdateInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceConfigRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest} message UpdateInstanceConfigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstanceConfigRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceConfig != null && Object.hasOwnProperty.call(message, "instanceConfig")) + $root.google.spanner.admin.instance.v1.InstanceConfig.encode(message.instanceConfig, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + $root.google.protobuf.FieldMask.encode(message.updateMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.validateOnly != null && Object.hasOwnProperty.call(message, "validateOnly")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.validateOnly); + return writer; + }; + + /** + * Encodes the specified UpdateInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceConfigRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest} message UpdateInstanceConfigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstanceConfigRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateInstanceConfigRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.UpdateInstanceConfigRequest} UpdateInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstanceConfigRequest.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.spanner.admin.instance.v1.UpdateInstanceConfigRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.decode(reader, reader.uint32()); + break; + } + case 2: { + message.updateMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + case 3: { + message.validateOnly = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateInstanceConfigRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.UpdateInstanceConfigRequest} UpdateInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstanceConfigRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateInstanceConfigRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateInstanceConfigRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) { + var error = $root.google.spanner.admin.instance.v1.InstanceConfig.verify(message.instanceConfig); + if (error) + return "instanceConfig." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.updateMask); + if (error) + return "updateMask." + error; + } + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + if (typeof message.validateOnly !== "boolean") + return "validateOnly: boolean expected"; + return null; + }; + + /** + * Creates an UpdateInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.UpdateInstanceConfigRequest} UpdateInstanceConfigRequest + */ + UpdateInstanceConfigRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest(); + if (object.instanceConfig != null) { + if (typeof object.instanceConfig !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceConfigRequest.instanceConfig: object expected"); + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.fromObject(object.instanceConfig); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceConfigRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + if (object.validateOnly != null) + message.validateOnly = Boolean(object.validateOnly); + return message; + }; + + /** + * Creates a plain object from an UpdateInstanceConfigRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.UpdateInstanceConfigRequest} message UpdateInstanceConfigRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateInstanceConfigRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instanceConfig = null; + object.updateMask = null; + object.validateOnly = false; + } + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) + object.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.toObject(message.instanceConfig, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + object.validateOnly = message.validateOnly; + return object; + }; + + /** + * Converts this UpdateInstanceConfigRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateInstanceConfigRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateInstanceConfigRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateInstanceConfigRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.UpdateInstanceConfigRequest"; + }; + + return UpdateInstanceConfigRequest; + })(); + + v1.DeleteInstanceConfigRequest = (function() { + + /** + * Properties of a DeleteInstanceConfigRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IDeleteInstanceConfigRequest + * @property {string|null} [name] DeleteInstanceConfigRequest name + * @property {string|null} [etag] DeleteInstanceConfigRequest etag + * @property {boolean|null} [validateOnly] DeleteInstanceConfigRequest validateOnly + */ + + /** + * Constructs a new DeleteInstanceConfigRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a DeleteInstanceConfigRequest. + * @implements IDeleteInstanceConfigRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest=} [properties] Properties to set + */ + function DeleteInstanceConfigRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteInstanceConfigRequest name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @instance + */ + DeleteInstanceConfigRequest.prototype.name = ""; + + /** + * DeleteInstanceConfigRequest etag. + * @member {string} etag + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @instance + */ + DeleteInstanceConfigRequest.prototype.etag = ""; + + /** + * DeleteInstanceConfigRequest validateOnly. + * @member {boolean} validateOnly + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @instance + */ + DeleteInstanceConfigRequest.prototype.validateOnly = false; + + /** + * Creates a new DeleteInstanceConfigRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.DeleteInstanceConfigRequest} DeleteInstanceConfigRequest instance + */ + DeleteInstanceConfigRequest.create = function create(properties) { + return new DeleteInstanceConfigRequest(properties); + }; + + /** + * Encodes the specified DeleteInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceConfigRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest} message DeleteInstanceConfigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteInstanceConfigRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.etag); + if (message.validateOnly != null && Object.hasOwnProperty.call(message, "validateOnly")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.validateOnly); + return writer; + }; + + /** + * Encodes the specified DeleteInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceConfigRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest} message DeleteInstanceConfigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteInstanceConfigRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteInstanceConfigRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.DeleteInstanceConfigRequest} DeleteInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteInstanceConfigRequest.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.spanner.admin.instance.v1.DeleteInstanceConfigRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.etag = reader.string(); + break; + } + case 3: { + message.validateOnly = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteInstanceConfigRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.DeleteInstanceConfigRequest} DeleteInstanceConfigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteInstanceConfigRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteInstanceConfigRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteInstanceConfigRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.etag != null && message.hasOwnProperty("etag")) + if (!$util.isString(message.etag)) + return "etag: string expected"; + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + if (typeof message.validateOnly !== "boolean") + return "validateOnly: boolean expected"; + return null; + }; + + /** + * Creates a DeleteInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.DeleteInstanceConfigRequest} DeleteInstanceConfigRequest + */ + DeleteInstanceConfigRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.etag != null) + message.etag = String(object.etag); + if (object.validateOnly != null) + message.validateOnly = Boolean(object.validateOnly); + return message; + }; + + /** + * Creates a plain object from a DeleteInstanceConfigRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {google.spanner.admin.instance.v1.DeleteInstanceConfigRequest} message DeleteInstanceConfigRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteInstanceConfigRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.etag = ""; + object.validateOnly = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.etag != null && message.hasOwnProperty("etag")) + object.etag = message.etag; + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + object.validateOnly = message.validateOnly; + return object; + }; + + /** + * Converts this DeleteInstanceConfigRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteInstanceConfigRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteInstanceConfigRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.DeleteInstanceConfigRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteInstanceConfigRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.DeleteInstanceConfigRequest"; + }; + + return DeleteInstanceConfigRequest; + })(); + + v1.ListInstanceConfigOperationsRequest = (function() { + + /** + * Properties of a ListInstanceConfigOperationsRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstanceConfigOperationsRequest + * @property {string|null} [parent] ListInstanceConfigOperationsRequest parent + * @property {string|null} [filter] ListInstanceConfigOperationsRequest filter + * @property {number|null} [pageSize] ListInstanceConfigOperationsRequest pageSize + * @property {string|null} [pageToken] ListInstanceConfigOperationsRequest pageToken + */ + + /** + * Constructs a new ListInstanceConfigOperationsRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstanceConfigOperationsRequest. + * @implements IListInstanceConfigOperationsRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest=} [properties] Properties to set + */ + function ListInstanceConfigOperationsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstanceConfigOperationsRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @instance + */ + ListInstanceConfigOperationsRequest.prototype.parent = ""; + + /** + * ListInstanceConfigOperationsRequest filter. + * @member {string} filter + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @instance + */ + ListInstanceConfigOperationsRequest.prototype.filter = ""; + + /** + * ListInstanceConfigOperationsRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @instance + */ + ListInstanceConfigOperationsRequest.prototype.pageSize = 0; + + /** + * ListInstanceConfigOperationsRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @instance + */ + ListInstanceConfigOperationsRequest.prototype.pageToken = ""; + + /** + * Creates a new ListInstanceConfigOperationsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest} ListInstanceConfigOperationsRequest instance + */ + ListInstanceConfigOperationsRequest.create = function create(properties) { + return new ListInstanceConfigOperationsRequest(properties); + }; + + /** + * Encodes the specified ListInstanceConfigOperationsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest} message ListInstanceConfigOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstanceConfigOperationsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListInstanceConfigOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest} message ListInstanceConfigOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstanceConfigOperationsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstanceConfigOperationsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest} ListInstanceConfigOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstanceConfigOperationsRequest.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.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstanceConfigOperationsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest} ListInstanceConfigOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstanceConfigOperationsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstanceConfigOperationsRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstanceConfigOperationsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListInstanceConfigOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest} ListInstanceConfigOperationsRequest + */ + ListInstanceConfigOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListInstanceConfigOperationsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest} message ListInstanceConfigOperationsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstanceConfigOperationsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListInstanceConfigOperationsRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @instance + * @returns {Object.} JSON object + */ + ListInstanceConfigOperationsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstanceConfigOperationsRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstanceConfigOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest"; + }; + + return ListInstanceConfigOperationsRequest; + })(); + + v1.ListInstanceConfigOperationsResponse = (function() { + + /** + * Properties of a ListInstanceConfigOperationsResponse. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstanceConfigOperationsResponse + * @property {Array.|null} [operations] ListInstanceConfigOperationsResponse operations + * @property {string|null} [nextPageToken] ListInstanceConfigOperationsResponse nextPageToken + */ + + /** + * Constructs a new ListInstanceConfigOperationsResponse. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstanceConfigOperationsResponse. + * @implements IListInstanceConfigOperationsResponse + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse=} [properties] Properties to set + */ + function ListInstanceConfigOperationsResponse(properties) { + this.operations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstanceConfigOperationsResponse operations. + * @member {Array.} operations + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @instance + */ + ListInstanceConfigOperationsResponse.prototype.operations = $util.emptyArray; + + /** + * ListInstanceConfigOperationsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @instance + */ + ListInstanceConfigOperationsResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListInstanceConfigOperationsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse} ListInstanceConfigOperationsResponse instance + */ + ListInstanceConfigOperationsResponse.create = function create(properties) { + return new ListInstanceConfigOperationsResponse(properties); + }; + + /** + * Encodes the specified ListInstanceConfigOperationsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse} message ListInstanceConfigOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstanceConfigOperationsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.operations != null && message.operations.length) + for (var i = 0; i < message.operations.length; ++i) + $root.google.longrunning.Operation.encode(message.operations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListInstanceConfigOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse} message ListInstanceConfigOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstanceConfigOperationsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstanceConfigOperationsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse} ListInstanceConfigOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstanceConfigOperationsResponse.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.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.operations && message.operations.length)) + message.operations = []; + message.operations.push($root.google.longrunning.Operation.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstanceConfigOperationsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse} ListInstanceConfigOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstanceConfigOperationsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstanceConfigOperationsResponse message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstanceConfigOperationsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.operations != null && message.hasOwnProperty("operations")) { + if (!Array.isArray(message.operations)) + return "operations: array expected"; + for (var i = 0; i < message.operations.length; ++i) { + var error = $root.google.longrunning.Operation.verify(message.operations[i]); + if (error) + return "operations." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListInstanceConfigOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse} ListInstanceConfigOperationsResponse + */ + ListInstanceConfigOperationsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse(); + if (object.operations) { + if (!Array.isArray(object.operations)) + throw TypeError(".google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.operations: array expected"); + message.operations = []; + for (var i = 0; i < object.operations.length; ++i) { + if (typeof object.operations[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.operations: object expected"); + message.operations[i] = $root.google.longrunning.Operation.fromObject(object.operations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListInstanceConfigOperationsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse} message ListInstanceConfigOperationsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstanceConfigOperationsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.operations = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.operations && message.operations.length) { + object.operations = []; + for (var j = 0; j < message.operations.length; ++j) + object.operations[j] = $root.google.longrunning.Operation.toObject(message.operations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListInstanceConfigOperationsResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @instance + * @returns {Object.} JSON object + */ + ListInstanceConfigOperationsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstanceConfigOperationsResponse + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstanceConfigOperationsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse"; + }; + + return ListInstanceConfigOperationsResponse; + })(); + + v1.GetInstanceRequest = (function() { + + /** + * Properties of a GetInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IGetInstanceRequest + * @property {string|null} [name] GetInstanceRequest name + * @property {google.protobuf.IFieldMask|null} [fieldMask] GetInstanceRequest fieldMask + */ + + /** + * Constructs a new GetInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a GetInstanceRequest. + * @implements IGetInstanceRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IGetInstanceRequest=} [properties] Properties to set + */ + function GetInstanceRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetInstanceRequest name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @instance + */ + GetInstanceRequest.prototype.name = ""; + + /** + * GetInstanceRequest fieldMask. + * @member {google.protobuf.IFieldMask|null|undefined} fieldMask + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @instance + */ + GetInstanceRequest.prototype.fieldMask = null; + + /** + * Creates a new GetInstanceRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstanceRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.GetInstanceRequest} GetInstanceRequest instance + */ + GetInstanceRequest.create = function create(properties) { + return new GetInstanceRequest(properties); + }; + + /** + * Encodes the specified GetInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstanceRequest} message GetInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetInstanceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.fieldMask != null && Object.hasOwnProperty.call(message, "fieldMask")) + $root.google.protobuf.FieldMask.encode(message.fieldMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified GetInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstanceRequest} message GetInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetInstanceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetInstanceRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.GetInstanceRequest} GetInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetInstanceRequest.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.spanner.admin.instance.v1.GetInstanceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.fieldMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetInstanceRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.GetInstanceRequest} GetInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetInstanceRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetInstanceRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetInstanceRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.fieldMask != null && message.hasOwnProperty("fieldMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.fieldMask); + if (error) + return "fieldMask." + error; + } + return null; + }; + + /** + * Creates a GetInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.GetInstanceRequest} GetInstanceRequest + */ + GetInstanceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.GetInstanceRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.GetInstanceRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.fieldMask != null) { + if (typeof object.fieldMask !== "object") + throw TypeError(".google.spanner.admin.instance.v1.GetInstanceRequest.fieldMask: object expected"); + message.fieldMask = $root.google.protobuf.FieldMask.fromObject(object.fieldMask); + } + return message; + }; + + /** + * Creates a plain object from a GetInstanceRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.GetInstanceRequest} message GetInstanceRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetInstanceRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.fieldMask = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.fieldMask != null && message.hasOwnProperty("fieldMask")) + object.fieldMask = $root.google.protobuf.FieldMask.toObject(message.fieldMask, options); + return object; + }; + + /** + * Converts this GetInstanceRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @instance + * @returns {Object.} JSON object + */ + GetInstanceRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetInstanceRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.GetInstanceRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetInstanceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.GetInstanceRequest"; + }; + + return GetInstanceRequest; + })(); + + v1.CreateInstanceRequest = (function() { + + /** + * Properties of a CreateInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface ICreateInstanceRequest + * @property {string|null} [parent] CreateInstanceRequest parent + * @property {string|null} [instanceId] CreateInstanceRequest instanceId + * @property {google.spanner.admin.instance.v1.IInstance|null} [instance] CreateInstanceRequest instance + */ + + /** + * Constructs a new CreateInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a CreateInstanceRequest. + * @implements ICreateInstanceRequest + * @constructor + * @param {google.spanner.admin.instance.v1.ICreateInstanceRequest=} [properties] Properties to set + */ + function CreateInstanceRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateInstanceRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @instance + */ + CreateInstanceRequest.prototype.parent = ""; + + /** + * CreateInstanceRequest instanceId. + * @member {string} instanceId + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @instance + */ + CreateInstanceRequest.prototype.instanceId = ""; + + /** + * CreateInstanceRequest instance. + * @member {google.spanner.admin.instance.v1.IInstance|null|undefined} instance + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @instance + */ + CreateInstanceRequest.prototype.instance = null; + + /** + * Creates a new CreateInstanceRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.CreateInstanceRequest} CreateInstanceRequest instance + */ + CreateInstanceRequest.create = function create(properties) { + return new CreateInstanceRequest(properties); + }; + + /** + * Encodes the specified CreateInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceRequest} message CreateInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstanceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.instance != null && Object.hasOwnProperty.call(message, "instance")) + $root.google.spanner.admin.instance.v1.Instance.encode(message.instance, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceRequest} message CreateInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstanceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateInstanceRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.CreateInstanceRequest} CreateInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstanceRequest.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.spanner.admin.instance.v1.CreateInstanceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.instance = $root.google.spanner.admin.instance.v1.Instance.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateInstanceRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.CreateInstanceRequest} CreateInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstanceRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateInstanceRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateInstanceRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.instance != null && message.hasOwnProperty("instance")) { + var error = $root.google.spanner.admin.instance.v1.Instance.verify(message.instance); + if (error) + return "instance." + error; + } + return null; + }; + + /** + * Creates a CreateInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.CreateInstanceRequest} CreateInstanceRequest + */ + CreateInstanceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.CreateInstanceRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.CreateInstanceRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.instance != null) { + if (typeof object.instance !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceRequest.instance: object expected"); + message.instance = $root.google.spanner.admin.instance.v1.Instance.fromObject(object.instance); + } + return message; + }; + + /** + * Creates a plain object from a CreateInstanceRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.CreateInstanceRequest} message CreateInstanceRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateInstanceRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.instanceId = ""; + object.instance = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.instance != null && message.hasOwnProperty("instance")) + object.instance = $root.google.spanner.admin.instance.v1.Instance.toObject(message.instance, options); + return object; + }; + + /** + * Converts this CreateInstanceRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @instance + * @returns {Object.} JSON object + */ + CreateInstanceRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateInstanceRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.CreateInstanceRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateInstanceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.CreateInstanceRequest"; + }; + + return CreateInstanceRequest; + })(); + + v1.ListInstancesRequest = (function() { + + /** + * Properties of a ListInstancesRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstancesRequest + * @property {string|null} [parent] ListInstancesRequest parent + * @property {number|null} [pageSize] ListInstancesRequest pageSize + * @property {string|null} [pageToken] ListInstancesRequest pageToken + * @property {string|null} [filter] ListInstancesRequest filter + * @property {google.protobuf.ITimestamp|null} [instanceDeadline] ListInstancesRequest instanceDeadline + */ + + /** + * Constructs a new ListInstancesRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstancesRequest. + * @implements IListInstancesRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstancesRequest=} [properties] Properties to set + */ + function ListInstancesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstancesRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @instance + */ + ListInstancesRequest.prototype.parent = ""; + + /** + * ListInstancesRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @instance + */ + ListInstancesRequest.prototype.pageSize = 0; + + /** + * ListInstancesRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @instance + */ + ListInstancesRequest.prototype.pageToken = ""; + + /** + * ListInstancesRequest filter. + * @member {string} filter + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @instance + */ + ListInstancesRequest.prototype.filter = ""; + + /** + * ListInstancesRequest instanceDeadline. + * @member {google.protobuf.ITimestamp|null|undefined} instanceDeadline + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @instance + */ + ListInstancesRequest.prototype.instanceDeadline = null; + + /** + * Creates a new ListInstancesRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancesRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstancesRequest} ListInstancesRequest instance + */ + ListInstancesRequest.create = function create(properties) { + return new ListInstancesRequest(properties); + }; + + /** + * Encodes the specified ListInstancesRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancesRequest} message ListInstancesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancesRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.filter); + if (message.instanceDeadline != null && Object.hasOwnProperty.call(message, "instanceDeadline")) + $root.google.protobuf.Timestamp.encode(message.instanceDeadline, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ListInstancesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancesRequest} message ListInstancesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancesRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstancesRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstancesRequest} ListInstancesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancesRequest.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.spanner.admin.instance.v1.ListInstancesRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + case 4: { + message.filter = reader.string(); + break; + } + case 5: { + message.instanceDeadline = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstancesRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstancesRequest} ListInstancesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancesRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstancesRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstancesRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.instanceDeadline != null && message.hasOwnProperty("instanceDeadline")) { + var error = $root.google.protobuf.Timestamp.verify(message.instanceDeadline); + if (error) + return "instanceDeadline." + error; + } + return null; + }; + + /** + * Creates a ListInstancesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstancesRequest} ListInstancesRequest + */ + ListInstancesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstancesRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstancesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.filter != null) + message.filter = String(object.filter); + if (object.instanceDeadline != null) { + if (typeof object.instanceDeadline !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ListInstancesRequest.instanceDeadline: object expected"); + message.instanceDeadline = $root.google.protobuf.Timestamp.fromObject(object.instanceDeadline); + } + return message; + }; + + /** + * Creates a plain object from a ListInstancesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {google.spanner.admin.instance.v1.ListInstancesRequest} message ListInstancesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstancesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + object.filter = ""; + object.instanceDeadline = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.instanceDeadline != null && message.hasOwnProperty("instanceDeadline")) + object.instanceDeadline = $root.google.protobuf.Timestamp.toObject(message.instanceDeadline, options); + return object; + }; + + /** + * Converts this ListInstancesRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @instance + * @returns {Object.} JSON object + */ + ListInstancesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstancesRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstancesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstancesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstancesRequest"; + }; + + return ListInstancesRequest; + })(); + + v1.ListInstancesResponse = (function() { + + /** + * Properties of a ListInstancesResponse. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstancesResponse + * @property {Array.|null} [instances] ListInstancesResponse instances + * @property {string|null} [nextPageToken] ListInstancesResponse nextPageToken + * @property {Array.|null} [unreachable] ListInstancesResponse unreachable + */ + + /** + * Constructs a new ListInstancesResponse. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstancesResponse. + * @implements IListInstancesResponse + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstancesResponse=} [properties] Properties to set + */ + function ListInstancesResponse(properties) { + this.instances = []; + this.unreachable = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstancesResponse instances. + * @member {Array.} instances + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @instance + */ + ListInstancesResponse.prototype.instances = $util.emptyArray; + + /** + * ListInstancesResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @instance + */ + ListInstancesResponse.prototype.nextPageToken = ""; + + /** + * ListInstancesResponse unreachable. + * @member {Array.} unreachable + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @instance + */ + ListInstancesResponse.prototype.unreachable = $util.emptyArray; + + /** + * Creates a new ListInstancesResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancesResponse=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstancesResponse} ListInstancesResponse instance + */ + ListInstancesResponse.create = function create(properties) { + return new ListInstancesResponse(properties); + }; + + /** + * Encodes the specified ListInstancesResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancesResponse} message ListInstancesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancesResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instances != null && message.instances.length) + for (var i = 0; i < message.instances.length; ++i) + $root.google.spanner.admin.instance.v1.Instance.encode(message.instances[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + if (message.unreachable != null && message.unreachable.length) + for (var i = 0; i < message.unreachable.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.unreachable[i]); + return writer; + }; + + /** + * Encodes the specified ListInstancesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancesResponse} message ListInstancesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancesResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstancesResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstancesResponse} ListInstancesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancesResponse.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.spanner.admin.instance.v1.ListInstancesResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.instances && message.instances.length)) + message.instances = []; + message.instances.push($root.google.spanner.admin.instance.v1.Instance.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + case 3: { + if (!(message.unreachable && message.unreachable.length)) + message.unreachable = []; + message.unreachable.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstancesResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstancesResponse} ListInstancesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancesResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstancesResponse message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstancesResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instances != null && message.hasOwnProperty("instances")) { + if (!Array.isArray(message.instances)) + return "instances: array expected"; + for (var i = 0; i < message.instances.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.Instance.verify(message.instances[i]); + if (error) + return "instances." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + if (message.unreachable != null && message.hasOwnProperty("unreachable")) { + if (!Array.isArray(message.unreachable)) + return "unreachable: array expected"; + for (var i = 0; i < message.unreachable.length; ++i) + if (!$util.isString(message.unreachable[i])) + return "unreachable: string[] expected"; + } + return null; + }; + + /** + * Creates a ListInstancesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstancesResponse} ListInstancesResponse + */ + ListInstancesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstancesResponse) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstancesResponse(); + if (object.instances) { + if (!Array.isArray(object.instances)) + throw TypeError(".google.spanner.admin.instance.v1.ListInstancesResponse.instances: array expected"); + message.instances = []; + for (var i = 0; i < object.instances.length; ++i) { + if (typeof object.instances[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ListInstancesResponse.instances: object expected"); + message.instances[i] = $root.google.spanner.admin.instance.v1.Instance.fromObject(object.instances[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.unreachable) { + if (!Array.isArray(object.unreachable)) + throw TypeError(".google.spanner.admin.instance.v1.ListInstancesResponse.unreachable: array expected"); + message.unreachable = []; + for (var i = 0; i < object.unreachable.length; ++i) + message.unreachable[i] = String(object.unreachable[i]); + } + return message; + }; + + /** + * Creates a plain object from a ListInstancesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {google.spanner.admin.instance.v1.ListInstancesResponse} message ListInstancesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstancesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.instances = []; + object.unreachable = []; + } + if (options.defaults) + object.nextPageToken = ""; + if (message.instances && message.instances.length) { + object.instances = []; + for (var j = 0; j < message.instances.length; ++j) + object.instances[j] = $root.google.spanner.admin.instance.v1.Instance.toObject(message.instances[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.unreachable && message.unreachable.length) { + object.unreachable = []; + for (var j = 0; j < message.unreachable.length; ++j) + object.unreachable[j] = message.unreachable[j]; + } + return object; + }; + + /** + * Converts this ListInstancesResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @instance + * @returns {Object.} JSON object + */ + ListInstancesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstancesResponse + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstancesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstancesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstancesResponse"; + }; + + return ListInstancesResponse; + })(); + + v1.UpdateInstanceRequest = (function() { + + /** + * Properties of an UpdateInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IUpdateInstanceRequest + * @property {google.spanner.admin.instance.v1.IInstance|null} [instance] UpdateInstanceRequest instance + * @property {google.protobuf.IFieldMask|null} [fieldMask] UpdateInstanceRequest fieldMask + */ + + /** + * Constructs a new UpdateInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an UpdateInstanceRequest. + * @implements IUpdateInstanceRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IUpdateInstanceRequest=} [properties] Properties to set + */ + function UpdateInstanceRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateInstanceRequest instance. + * @member {google.spanner.admin.instance.v1.IInstance|null|undefined} instance + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @instance + */ + UpdateInstanceRequest.prototype.instance = null; + + /** + * UpdateInstanceRequest fieldMask. + * @member {google.protobuf.IFieldMask|null|undefined} fieldMask + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @instance + */ + UpdateInstanceRequest.prototype.fieldMask = null; + + /** + * Creates a new UpdateInstanceRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.UpdateInstanceRequest} UpdateInstanceRequest instance + */ + UpdateInstanceRequest.create = function create(properties) { + return new UpdateInstanceRequest(properties); + }; + + /** + * Encodes the specified UpdateInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceRequest} message UpdateInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstanceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instance != null && Object.hasOwnProperty.call(message, "instance")) + $root.google.spanner.admin.instance.v1.Instance.encode(message.instance, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.fieldMask != null && Object.hasOwnProperty.call(message, "fieldMask")) + $root.google.protobuf.FieldMask.encode(message.fieldMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceRequest} message UpdateInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstanceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateInstanceRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.UpdateInstanceRequest} UpdateInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstanceRequest.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.spanner.admin.instance.v1.UpdateInstanceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instance = $root.google.spanner.admin.instance.v1.Instance.decode(reader, reader.uint32()); + break; + } + case 2: { + message.fieldMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateInstanceRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.UpdateInstanceRequest} UpdateInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstanceRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateInstanceRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateInstanceRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instance != null && message.hasOwnProperty("instance")) { + var error = $root.google.spanner.admin.instance.v1.Instance.verify(message.instance); + if (error) + return "instance." + error; + } + if (message.fieldMask != null && message.hasOwnProperty("fieldMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.fieldMask); + if (error) + return "fieldMask." + error; + } + return null; + }; + + /** + * Creates an UpdateInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.UpdateInstanceRequest} UpdateInstanceRequest + */ + UpdateInstanceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.UpdateInstanceRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.UpdateInstanceRequest(); + if (object.instance != null) { + if (typeof object.instance !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceRequest.instance: object expected"); + message.instance = $root.google.spanner.admin.instance.v1.Instance.fromObject(object.instance); + } + if (object.fieldMask != null) { + if (typeof object.fieldMask !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceRequest.fieldMask: object expected"); + message.fieldMask = $root.google.protobuf.FieldMask.fromObject(object.fieldMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateInstanceRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.UpdateInstanceRequest} message UpdateInstanceRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateInstanceRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instance = null; + object.fieldMask = null; + } + if (message.instance != null && message.hasOwnProperty("instance")) + object.instance = $root.google.spanner.admin.instance.v1.Instance.toObject(message.instance, options); + if (message.fieldMask != null && message.hasOwnProperty("fieldMask")) + object.fieldMask = $root.google.protobuf.FieldMask.toObject(message.fieldMask, options); + return object; + }; + + /** + * Converts this UpdateInstanceRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateInstanceRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateInstanceRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.UpdateInstanceRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateInstanceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.UpdateInstanceRequest"; + }; + + return UpdateInstanceRequest; + })(); + + v1.DeleteInstanceRequest = (function() { + + /** + * Properties of a DeleteInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IDeleteInstanceRequest + * @property {string|null} [name] DeleteInstanceRequest name + */ + + /** + * Constructs a new DeleteInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a DeleteInstanceRequest. + * @implements IDeleteInstanceRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IDeleteInstanceRequest=} [properties] Properties to set + */ + function DeleteInstanceRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteInstanceRequest name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @instance + */ + DeleteInstanceRequest.prototype.name = ""; + + /** + * Creates a new DeleteInstanceRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstanceRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.DeleteInstanceRequest} DeleteInstanceRequest instance + */ + DeleteInstanceRequest.create = function create(properties) { + return new DeleteInstanceRequest(properties); + }; + + /** + * Encodes the specified DeleteInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstanceRequest} message DeleteInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteInstanceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified DeleteInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstanceRequest} message DeleteInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteInstanceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteInstanceRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.DeleteInstanceRequest} DeleteInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteInstanceRequest.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.spanner.admin.instance.v1.DeleteInstanceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteInstanceRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.DeleteInstanceRequest} DeleteInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteInstanceRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteInstanceRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteInstanceRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a DeleteInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.DeleteInstanceRequest} DeleteInstanceRequest + */ + DeleteInstanceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.DeleteInstanceRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.DeleteInstanceRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteInstanceRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.DeleteInstanceRequest} message DeleteInstanceRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteInstanceRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteInstanceRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteInstanceRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteInstanceRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.DeleteInstanceRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteInstanceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.DeleteInstanceRequest"; + }; + + return DeleteInstanceRequest; + })(); + + v1.CreateInstanceMetadata = (function() { + + /** + * Properties of a CreateInstanceMetadata. + * @memberof google.spanner.admin.instance.v1 + * @interface ICreateInstanceMetadata + * @property {google.spanner.admin.instance.v1.IInstance|null} [instance] CreateInstanceMetadata instance + * @property {google.protobuf.ITimestamp|null} [startTime] CreateInstanceMetadata startTime + * @property {google.protobuf.ITimestamp|null} [cancelTime] CreateInstanceMetadata cancelTime + * @property {google.protobuf.ITimestamp|null} [endTime] CreateInstanceMetadata endTime + * @property {google.spanner.admin.instance.v1.FulfillmentPeriod|null} [expectedFulfillmentPeriod] CreateInstanceMetadata expectedFulfillmentPeriod + */ + + /** + * Constructs a new CreateInstanceMetadata. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a CreateInstanceMetadata. + * @implements ICreateInstanceMetadata + * @constructor + * @param {google.spanner.admin.instance.v1.ICreateInstanceMetadata=} [properties] Properties to set + */ + function CreateInstanceMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateInstanceMetadata instance. + * @member {google.spanner.admin.instance.v1.IInstance|null|undefined} instance + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @instance + */ + CreateInstanceMetadata.prototype.instance = null; + + /** + * CreateInstanceMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @instance + */ + CreateInstanceMetadata.prototype.startTime = null; + + /** + * CreateInstanceMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @instance + */ + CreateInstanceMetadata.prototype.cancelTime = null; + + /** + * CreateInstanceMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @instance + */ + CreateInstanceMetadata.prototype.endTime = null; + + /** + * CreateInstanceMetadata expectedFulfillmentPeriod. + * @member {google.spanner.admin.instance.v1.FulfillmentPeriod} expectedFulfillmentPeriod + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @instance + */ + CreateInstanceMetadata.prototype.expectedFulfillmentPeriod = 0; + + /** + * Creates a new CreateInstanceMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.CreateInstanceMetadata} CreateInstanceMetadata instance + */ + CreateInstanceMetadata.create = function create(properties) { + return new CreateInstanceMetadata(properties); + }; + + /** + * Encodes the specified CreateInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceMetadata} message CreateInstanceMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstanceMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instance != null && Object.hasOwnProperty.call(message, "instance")) + $root.google.spanner.admin.instance.v1.Instance.encode(message.instance, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) + $root.google.protobuf.Timestamp.encode(message.endTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.expectedFulfillmentPeriod != null && Object.hasOwnProperty.call(message, "expectedFulfillmentPeriod")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.expectedFulfillmentPeriod); + return writer; + }; + + /** + * Encodes the specified CreateInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceMetadata} message CreateInstanceMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstanceMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateInstanceMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.CreateInstanceMetadata} CreateInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstanceMetadata.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.spanner.admin.instance.v1.CreateInstanceMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instance = $root.google.spanner.admin.instance.v1.Instance.decode(reader, reader.uint32()); + break; + } + case 2: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.endTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 5: { + message.expectedFulfillmentPeriod = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateInstanceMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.CreateInstanceMetadata} CreateInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstanceMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateInstanceMetadata message. + * @function verify + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateInstanceMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instance != null && message.hasOwnProperty("instance")) { + var error = $root.google.spanner.admin.instance.v1.Instance.verify(message.instance); + if (error) + return "instance." + error; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + if (message.endTime != null && message.hasOwnProperty("endTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.endTime); + if (error) + return "endTime." + error; + } + if (message.expectedFulfillmentPeriod != null && message.hasOwnProperty("expectedFulfillmentPeriod")) + switch (message.expectedFulfillmentPeriod) { + default: + return "expectedFulfillmentPeriod: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates a CreateInstanceMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.CreateInstanceMetadata} CreateInstanceMetadata + */ + CreateInstanceMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.CreateInstanceMetadata) + return object; + var message = new $root.google.spanner.admin.instance.v1.CreateInstanceMetadata(); + if (object.instance != null) { + if (typeof object.instance !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceMetadata.instance: object expected"); + message.instance = $root.google.spanner.admin.instance.v1.Instance.fromObject(object.instance); + } + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + switch (object.expectedFulfillmentPeriod) { + default: + if (typeof object.expectedFulfillmentPeriod === "number") { + message.expectedFulfillmentPeriod = object.expectedFulfillmentPeriod; + break; + } + break; + case "FULFILLMENT_PERIOD_UNSPECIFIED": + case 0: + message.expectedFulfillmentPeriod = 0; + break; + case "FULFILLMENT_PERIOD_NORMAL": + case 1: + message.expectedFulfillmentPeriod = 1; + break; + case "FULFILLMENT_PERIOD_EXTENDED": + case 2: + message.expectedFulfillmentPeriod = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a CreateInstanceMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.CreateInstanceMetadata} message CreateInstanceMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateInstanceMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instance = null; + object.startTime = null; + object.cancelTime = null; + object.endTime = null; + object.expectedFulfillmentPeriod = options.enums === String ? "FULFILLMENT_PERIOD_UNSPECIFIED" : 0; + } + if (message.instance != null && message.hasOwnProperty("instance")) + object.instance = $root.google.spanner.admin.instance.v1.Instance.toObject(message.instance, options); + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.expectedFulfillmentPeriod != null && message.hasOwnProperty("expectedFulfillmentPeriod")) + object.expectedFulfillmentPeriod = options.enums === String ? $root.google.spanner.admin.instance.v1.FulfillmentPeriod[message.expectedFulfillmentPeriod] === undefined ? message.expectedFulfillmentPeriod : $root.google.spanner.admin.instance.v1.FulfillmentPeriod[message.expectedFulfillmentPeriod] : message.expectedFulfillmentPeriod; + return object; + }; + + /** + * Converts this CreateInstanceMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @instance + * @returns {Object.} JSON object + */ + CreateInstanceMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateInstanceMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.CreateInstanceMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateInstanceMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.CreateInstanceMetadata"; + }; + + return CreateInstanceMetadata; + })(); + + v1.UpdateInstanceMetadata = (function() { + + /** + * Properties of an UpdateInstanceMetadata. + * @memberof google.spanner.admin.instance.v1 + * @interface IUpdateInstanceMetadata + * @property {google.spanner.admin.instance.v1.IInstance|null} [instance] UpdateInstanceMetadata instance + * @property {google.protobuf.ITimestamp|null} [startTime] UpdateInstanceMetadata startTime + * @property {google.protobuf.ITimestamp|null} [cancelTime] UpdateInstanceMetadata cancelTime + * @property {google.protobuf.ITimestamp|null} [endTime] UpdateInstanceMetadata endTime + * @property {google.spanner.admin.instance.v1.FulfillmentPeriod|null} [expectedFulfillmentPeriod] UpdateInstanceMetadata expectedFulfillmentPeriod + */ + + /** + * Constructs a new UpdateInstanceMetadata. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an UpdateInstanceMetadata. + * @implements IUpdateInstanceMetadata + * @constructor + * @param {google.spanner.admin.instance.v1.IUpdateInstanceMetadata=} [properties] Properties to set + */ + function UpdateInstanceMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateInstanceMetadata instance. + * @member {google.spanner.admin.instance.v1.IInstance|null|undefined} instance + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @instance + */ + UpdateInstanceMetadata.prototype.instance = null; + + /** + * UpdateInstanceMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @instance + */ + UpdateInstanceMetadata.prototype.startTime = null; + + /** + * UpdateInstanceMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @instance + */ + UpdateInstanceMetadata.prototype.cancelTime = null; + + /** + * UpdateInstanceMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @instance + */ + UpdateInstanceMetadata.prototype.endTime = null; + + /** + * UpdateInstanceMetadata expectedFulfillmentPeriod. + * @member {google.spanner.admin.instance.v1.FulfillmentPeriod} expectedFulfillmentPeriod + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @instance + */ + UpdateInstanceMetadata.prototype.expectedFulfillmentPeriod = 0; + + /** + * Creates a new UpdateInstanceMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.UpdateInstanceMetadata} UpdateInstanceMetadata instance + */ + UpdateInstanceMetadata.create = function create(properties) { + return new UpdateInstanceMetadata(properties); + }; + + /** + * Encodes the specified UpdateInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceMetadata} message UpdateInstanceMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstanceMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instance != null && Object.hasOwnProperty.call(message, "instance")) + $root.google.spanner.admin.instance.v1.Instance.encode(message.instance, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) + $root.google.protobuf.Timestamp.encode(message.endTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.expectedFulfillmentPeriod != null && Object.hasOwnProperty.call(message, "expectedFulfillmentPeriod")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.expectedFulfillmentPeriod); + return writer; + }; + + /** + * Encodes the specified UpdateInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceMetadata} message UpdateInstanceMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstanceMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateInstanceMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.UpdateInstanceMetadata} UpdateInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstanceMetadata.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.spanner.admin.instance.v1.UpdateInstanceMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instance = $root.google.spanner.admin.instance.v1.Instance.decode(reader, reader.uint32()); + break; + } + case 2: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.endTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 5: { + message.expectedFulfillmentPeriod = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateInstanceMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.UpdateInstanceMetadata} UpdateInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstanceMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateInstanceMetadata message. + * @function verify + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateInstanceMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instance != null && message.hasOwnProperty("instance")) { + var error = $root.google.spanner.admin.instance.v1.Instance.verify(message.instance); + if (error) + return "instance." + error; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + if (message.endTime != null && message.hasOwnProperty("endTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.endTime); + if (error) + return "endTime." + error; + } + if (message.expectedFulfillmentPeriod != null && message.hasOwnProperty("expectedFulfillmentPeriod")) + switch (message.expectedFulfillmentPeriod) { + default: + return "expectedFulfillmentPeriod: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates an UpdateInstanceMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.UpdateInstanceMetadata} UpdateInstanceMetadata + */ + UpdateInstanceMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.UpdateInstanceMetadata) + return object; + var message = new $root.google.spanner.admin.instance.v1.UpdateInstanceMetadata(); + if (object.instance != null) { + if (typeof object.instance !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceMetadata.instance: object expected"); + message.instance = $root.google.spanner.admin.instance.v1.Instance.fromObject(object.instance); + } + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + switch (object.expectedFulfillmentPeriod) { + default: + if (typeof object.expectedFulfillmentPeriod === "number") { + message.expectedFulfillmentPeriod = object.expectedFulfillmentPeriod; + break; + } + break; + case "FULFILLMENT_PERIOD_UNSPECIFIED": + case 0: + message.expectedFulfillmentPeriod = 0; + break; + case "FULFILLMENT_PERIOD_NORMAL": + case 1: + message.expectedFulfillmentPeriod = 1; + break; + case "FULFILLMENT_PERIOD_EXTENDED": + case 2: + message.expectedFulfillmentPeriod = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an UpdateInstanceMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.UpdateInstanceMetadata} message UpdateInstanceMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateInstanceMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instance = null; + object.startTime = null; + object.cancelTime = null; + object.endTime = null; + object.expectedFulfillmentPeriod = options.enums === String ? "FULFILLMENT_PERIOD_UNSPECIFIED" : 0; + } + if (message.instance != null && message.hasOwnProperty("instance")) + object.instance = $root.google.spanner.admin.instance.v1.Instance.toObject(message.instance, options); + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.expectedFulfillmentPeriod != null && message.hasOwnProperty("expectedFulfillmentPeriod")) + object.expectedFulfillmentPeriod = options.enums === String ? $root.google.spanner.admin.instance.v1.FulfillmentPeriod[message.expectedFulfillmentPeriod] === undefined ? message.expectedFulfillmentPeriod : $root.google.spanner.admin.instance.v1.FulfillmentPeriod[message.expectedFulfillmentPeriod] : message.expectedFulfillmentPeriod; + return object; + }; + + /** + * Converts this UpdateInstanceMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @instance + * @returns {Object.} JSON object + */ + UpdateInstanceMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateInstanceMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.UpdateInstanceMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateInstanceMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.UpdateInstanceMetadata"; + }; + + return UpdateInstanceMetadata; + })(); + + v1.FreeInstanceMetadata = (function() { + + /** + * Properties of a FreeInstanceMetadata. + * @memberof google.spanner.admin.instance.v1 + * @interface IFreeInstanceMetadata + * @property {google.protobuf.ITimestamp|null} [expireTime] FreeInstanceMetadata expireTime + * @property {google.protobuf.ITimestamp|null} [upgradeTime] FreeInstanceMetadata upgradeTime + * @property {google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior|null} [expireBehavior] FreeInstanceMetadata expireBehavior + */ + + /** + * Constructs a new FreeInstanceMetadata. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a FreeInstanceMetadata. + * @implements IFreeInstanceMetadata + * @constructor + * @param {google.spanner.admin.instance.v1.IFreeInstanceMetadata=} [properties] Properties to set + */ + function FreeInstanceMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FreeInstanceMetadata expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @instance + */ + FreeInstanceMetadata.prototype.expireTime = null; + + /** + * FreeInstanceMetadata upgradeTime. + * @member {google.protobuf.ITimestamp|null|undefined} upgradeTime + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @instance + */ + FreeInstanceMetadata.prototype.upgradeTime = null; + + /** + * FreeInstanceMetadata expireBehavior. + * @member {google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior} expireBehavior + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @instance + */ + FreeInstanceMetadata.prototype.expireBehavior = 0; + + /** + * Creates a new FreeInstanceMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IFreeInstanceMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.FreeInstanceMetadata} FreeInstanceMetadata instance + */ + FreeInstanceMetadata.create = function create(properties) { + return new FreeInstanceMetadata(properties); + }; + + /** + * Encodes the specified FreeInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.FreeInstanceMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IFreeInstanceMetadata} message FreeInstanceMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FreeInstanceMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.expireTime != null && Object.hasOwnProperty.call(message, "expireTime")) + $root.google.protobuf.Timestamp.encode(message.expireTime, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.upgradeTime != null && Object.hasOwnProperty.call(message, "upgradeTime")) + $root.google.protobuf.Timestamp.encode(message.upgradeTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.expireBehavior != null && Object.hasOwnProperty.call(message, "expireBehavior")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.expireBehavior); + return writer; + }; + + /** + * Encodes the specified FreeInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.FreeInstanceMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IFreeInstanceMetadata} message FreeInstanceMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FreeInstanceMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FreeInstanceMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.FreeInstanceMetadata} FreeInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FreeInstanceMetadata.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.spanner.admin.instance.v1.FreeInstanceMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.expireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.upgradeTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.expireBehavior = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FreeInstanceMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.FreeInstanceMetadata} FreeInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FreeInstanceMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FreeInstanceMetadata message. + * @function verify + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FreeInstanceMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.expireTime); + if (error) + return "expireTime." + error; + } + if (message.upgradeTime != null && message.hasOwnProperty("upgradeTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.upgradeTime); + if (error) + return "upgradeTime." + error; + } + if (message.expireBehavior != null && message.hasOwnProperty("expireBehavior")) + switch (message.expireBehavior) { + default: + return "expireBehavior: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates a FreeInstanceMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.FreeInstanceMetadata} FreeInstanceMetadata + */ + FreeInstanceMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.FreeInstanceMetadata) + return object; + var message = new $root.google.spanner.admin.instance.v1.FreeInstanceMetadata(); + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.FreeInstanceMetadata.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime); + } + if (object.upgradeTime != null) { + if (typeof object.upgradeTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.FreeInstanceMetadata.upgradeTime: object expected"); + message.upgradeTime = $root.google.protobuf.Timestamp.fromObject(object.upgradeTime); + } + switch (object.expireBehavior) { + default: + if (typeof object.expireBehavior === "number") { + message.expireBehavior = object.expireBehavior; + break; + } + break; + case "EXPIRE_BEHAVIOR_UNSPECIFIED": + case 0: + message.expireBehavior = 0; + break; + case "FREE_TO_PROVISIONED": + case 1: + message.expireBehavior = 1; + break; + case "REMOVE_AFTER_GRACE_PERIOD": + case 2: + message.expireBehavior = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a FreeInstanceMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.FreeInstanceMetadata} message FreeInstanceMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FreeInstanceMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.expireTime = null; + object.upgradeTime = null; + object.expireBehavior = options.enums === String ? "EXPIRE_BEHAVIOR_UNSPECIFIED" : 0; + } + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + if (message.upgradeTime != null && message.hasOwnProperty("upgradeTime")) + object.upgradeTime = $root.google.protobuf.Timestamp.toObject(message.upgradeTime, options); + if (message.expireBehavior != null && message.hasOwnProperty("expireBehavior")) + object.expireBehavior = options.enums === String ? $root.google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior[message.expireBehavior] === undefined ? message.expireBehavior : $root.google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior[message.expireBehavior] : message.expireBehavior; + return object; + }; + + /** + * Converts this FreeInstanceMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @instance + * @returns {Object.} JSON object + */ + FreeInstanceMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FreeInstanceMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.FreeInstanceMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FreeInstanceMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.FreeInstanceMetadata"; + }; + + /** + * ExpireBehavior enum. + * @name google.spanner.admin.instance.v1.FreeInstanceMetadata.ExpireBehavior + * @enum {number} + * @property {number} EXPIRE_BEHAVIOR_UNSPECIFIED=0 EXPIRE_BEHAVIOR_UNSPECIFIED value + * @property {number} FREE_TO_PROVISIONED=1 FREE_TO_PROVISIONED value + * @property {number} REMOVE_AFTER_GRACE_PERIOD=2 REMOVE_AFTER_GRACE_PERIOD value + */ + FreeInstanceMetadata.ExpireBehavior = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "EXPIRE_BEHAVIOR_UNSPECIFIED"] = 0; + values[valuesById[1] = "FREE_TO_PROVISIONED"] = 1; + values[valuesById[2] = "REMOVE_AFTER_GRACE_PERIOD"] = 2; + return values; + })(); + + return FreeInstanceMetadata; + })(); + + v1.CreateInstanceConfigMetadata = (function() { + + /** + * Properties of a CreateInstanceConfigMetadata. + * @memberof google.spanner.admin.instance.v1 + * @interface ICreateInstanceConfigMetadata + * @property {google.spanner.admin.instance.v1.IInstanceConfig|null} [instanceConfig] CreateInstanceConfigMetadata instanceConfig + * @property {google.spanner.admin.instance.v1.IOperationProgress|null} [progress] CreateInstanceConfigMetadata progress + * @property {google.protobuf.ITimestamp|null} [cancelTime] CreateInstanceConfigMetadata cancelTime + */ + + /** + * Constructs a new CreateInstanceConfigMetadata. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a CreateInstanceConfigMetadata. + * @implements ICreateInstanceConfigMetadata + * @constructor + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata=} [properties] Properties to set + */ + function CreateInstanceConfigMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateInstanceConfigMetadata instanceConfig. + * @member {google.spanner.admin.instance.v1.IInstanceConfig|null|undefined} instanceConfig + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @instance + */ + CreateInstanceConfigMetadata.prototype.instanceConfig = null; + + /** + * CreateInstanceConfigMetadata progress. + * @member {google.spanner.admin.instance.v1.IOperationProgress|null|undefined} progress + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @instance + */ + CreateInstanceConfigMetadata.prototype.progress = null; + + /** + * CreateInstanceConfigMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @instance + */ + CreateInstanceConfigMetadata.prototype.cancelTime = null; + + /** + * Creates a new CreateInstanceConfigMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.CreateInstanceConfigMetadata} CreateInstanceConfigMetadata instance + */ + CreateInstanceConfigMetadata.create = function create(properties) { + return new CreateInstanceConfigMetadata(properties); + }; + + /** + * Encodes the specified CreateInstanceConfigMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceConfigMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata} message CreateInstanceConfigMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstanceConfigMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceConfig != null && Object.hasOwnProperty.call(message, "instanceConfig")) + $root.google.spanner.admin.instance.v1.InstanceConfig.encode(message.instanceConfig, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.spanner.admin.instance.v1.OperationProgress.encode(message.progress, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateInstanceConfigMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceConfigMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata} message CreateInstanceConfigMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstanceConfigMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateInstanceConfigMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.CreateInstanceConfigMetadata} CreateInstanceConfigMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstanceConfigMetadata.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.spanner.admin.instance.v1.CreateInstanceConfigMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.decode(reader, reader.uint32()); + break; + } + case 2: { + message.progress = $root.google.spanner.admin.instance.v1.OperationProgress.decode(reader, reader.uint32()); + break; + } + case 3: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateInstanceConfigMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.CreateInstanceConfigMetadata} CreateInstanceConfigMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstanceConfigMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateInstanceConfigMetadata message. + * @function verify + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateInstanceConfigMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) { + var error = $root.google.spanner.admin.instance.v1.InstanceConfig.verify(message.instanceConfig); + if (error) + return "instanceConfig." + error; + } + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.spanner.admin.instance.v1.OperationProgress.verify(message.progress); + if (error) + return "progress." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + return null; + }; + + /** + * Creates a CreateInstanceConfigMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.CreateInstanceConfigMetadata} CreateInstanceConfigMetadata + */ + CreateInstanceConfigMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata) + return object; + var message = new $root.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata(); + if (object.instanceConfig != null) { + if (typeof object.instanceConfig !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceConfigMetadata.instanceConfig: object expected"); + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.fromObject(object.instanceConfig); + } + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceConfigMetadata.progress: object expected"); + message.progress = $root.google.spanner.admin.instance.v1.OperationProgress.fromObject(object.progress); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstanceConfigMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + return message; + }; + + /** + * Creates a plain object from a CreateInstanceConfigMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {google.spanner.admin.instance.v1.CreateInstanceConfigMetadata} message CreateInstanceConfigMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateInstanceConfigMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instanceConfig = null; + object.progress = null; + object.cancelTime = null; + } + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) + object.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.toObject(message.instanceConfig, options); + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.spanner.admin.instance.v1.OperationProgress.toObject(message.progress, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + return object; + }; + + /** + * Converts this CreateInstanceConfigMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @instance + * @returns {Object.} JSON object + */ + CreateInstanceConfigMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateInstanceConfigMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateInstanceConfigMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata"; + }; + + return CreateInstanceConfigMetadata; + })(); + + v1.UpdateInstanceConfigMetadata = (function() { + + /** + * Properties of an UpdateInstanceConfigMetadata. + * @memberof google.spanner.admin.instance.v1 + * @interface IUpdateInstanceConfigMetadata + * @property {google.spanner.admin.instance.v1.IInstanceConfig|null} [instanceConfig] UpdateInstanceConfigMetadata instanceConfig + * @property {google.spanner.admin.instance.v1.IOperationProgress|null} [progress] UpdateInstanceConfigMetadata progress + * @property {google.protobuf.ITimestamp|null} [cancelTime] UpdateInstanceConfigMetadata cancelTime + */ + + /** + * Constructs a new UpdateInstanceConfigMetadata. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an UpdateInstanceConfigMetadata. + * @implements IUpdateInstanceConfigMetadata + * @constructor + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata=} [properties] Properties to set + */ + function UpdateInstanceConfigMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateInstanceConfigMetadata instanceConfig. + * @member {google.spanner.admin.instance.v1.IInstanceConfig|null|undefined} instanceConfig + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @instance + */ + UpdateInstanceConfigMetadata.prototype.instanceConfig = null; + + /** + * UpdateInstanceConfigMetadata progress. + * @member {google.spanner.admin.instance.v1.IOperationProgress|null|undefined} progress + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @instance + */ + UpdateInstanceConfigMetadata.prototype.progress = null; + + /** + * UpdateInstanceConfigMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @instance + */ + UpdateInstanceConfigMetadata.prototype.cancelTime = null; + + /** + * Creates a new UpdateInstanceConfigMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata} UpdateInstanceConfigMetadata instance + */ + UpdateInstanceConfigMetadata.create = function create(properties) { + return new UpdateInstanceConfigMetadata(properties); + }; + + /** + * Encodes the specified UpdateInstanceConfigMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata} message UpdateInstanceConfigMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstanceConfigMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceConfig != null && Object.hasOwnProperty.call(message, "instanceConfig")) + $root.google.spanner.admin.instance.v1.InstanceConfig.encode(message.instanceConfig, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.spanner.admin.instance.v1.OperationProgress.encode(message.progress, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateInstanceConfigMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata} message UpdateInstanceConfigMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstanceConfigMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateInstanceConfigMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata} UpdateInstanceConfigMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstanceConfigMetadata.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.spanner.admin.instance.v1.UpdateInstanceConfigMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.decode(reader, reader.uint32()); + break; + } + case 2: { + message.progress = $root.google.spanner.admin.instance.v1.OperationProgress.decode(reader, reader.uint32()); + break; + } + case 3: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateInstanceConfigMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata} UpdateInstanceConfigMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstanceConfigMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateInstanceConfigMetadata message. + * @function verify + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateInstanceConfigMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) { + var error = $root.google.spanner.admin.instance.v1.InstanceConfig.verify(message.instanceConfig); + if (error) + return "instanceConfig." + error; + } + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.spanner.admin.instance.v1.OperationProgress.verify(message.progress); + if (error) + return "progress." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + return null; + }; + + /** + * Creates an UpdateInstanceConfigMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata} UpdateInstanceConfigMetadata + */ + UpdateInstanceConfigMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata) + return object; + var message = new $root.google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata(); + if (object.instanceConfig != null) { + if (typeof object.instanceConfig !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.instanceConfig: object expected"); + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.fromObject(object.instanceConfig); + } + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.progress: object expected"); + message.progress = $root.google.spanner.admin.instance.v1.OperationProgress.fromObject(object.progress); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + return message; + }; + + /** + * Creates a plain object from an UpdateInstanceConfigMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata} message UpdateInstanceConfigMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateInstanceConfigMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instanceConfig = null; + object.progress = null; + object.cancelTime = null; + } + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) + object.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.toObject(message.instanceConfig, options); + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.spanner.admin.instance.v1.OperationProgress.toObject(message.progress, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + return object; + }; + + /** + * Converts this UpdateInstanceConfigMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @instance + * @returns {Object.} JSON object + */ + UpdateInstanceConfigMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateInstanceConfigMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateInstanceConfigMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata"; + }; + + return UpdateInstanceConfigMetadata; + })(); + + v1.InstancePartition = (function() { + + /** + * Properties of an InstancePartition. + * @memberof google.spanner.admin.instance.v1 + * @interface IInstancePartition + * @property {string|null} [name] InstancePartition name + * @property {string|null} [config] InstancePartition config + * @property {string|null} [displayName] InstancePartition displayName + * @property {number|null} [nodeCount] InstancePartition nodeCount + * @property {number|null} [processingUnits] InstancePartition processingUnits + * @property {google.spanner.admin.instance.v1.IAutoscalingConfig|null} [autoscalingConfig] InstancePartition autoscalingConfig + * @property {google.spanner.admin.instance.v1.InstancePartition.State|null} [state] InstancePartition state + * @property {google.protobuf.ITimestamp|null} [createTime] InstancePartition createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] InstancePartition updateTime + * @property {Array.|null} [referencingDatabases] InstancePartition referencingDatabases + * @property {Array.|null} [referencingBackups] InstancePartition referencingBackups + * @property {string|null} [etag] InstancePartition etag + */ + + /** + * Constructs a new InstancePartition. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an InstancePartition. + * @implements IInstancePartition + * @constructor + * @param {google.spanner.admin.instance.v1.IInstancePartition=} [properties] Properties to set + */ + function InstancePartition(properties) { + this.referencingDatabases = []; + this.referencingBackups = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstancePartition name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.name = ""; + + /** + * InstancePartition config. + * @member {string} config + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.config = ""; + + /** + * InstancePartition displayName. + * @member {string} displayName + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.displayName = ""; + + /** + * InstancePartition nodeCount. + * @member {number|null|undefined} nodeCount + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.nodeCount = null; + + /** + * InstancePartition processingUnits. + * @member {number|null|undefined} processingUnits + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.processingUnits = null; + + /** + * InstancePartition autoscalingConfig. + * @member {google.spanner.admin.instance.v1.IAutoscalingConfig|null|undefined} autoscalingConfig + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.autoscalingConfig = null; + + /** + * InstancePartition state. + * @member {google.spanner.admin.instance.v1.InstancePartition.State} state + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.state = 0; + + /** + * InstancePartition createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.createTime = null; + + /** + * InstancePartition updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.updateTime = null; + + /** + * InstancePartition referencingDatabases. + * @member {Array.} referencingDatabases + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.referencingDatabases = $util.emptyArray; + + /** + * InstancePartition referencingBackups. + * @member {Array.} referencingBackups + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.referencingBackups = $util.emptyArray; + + /** + * InstancePartition etag. + * @member {string} etag + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + InstancePartition.prototype.etag = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * InstancePartition computeCapacity. + * @member {"nodeCount"|"processingUnits"|undefined} computeCapacity + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + */ + Object.defineProperty(InstancePartition.prototype, "computeCapacity", { + get: $util.oneOfGetter($oneOfFields = ["nodeCount", "processingUnits"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InstancePartition instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {google.spanner.admin.instance.v1.IInstancePartition=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.InstancePartition} InstancePartition instance + */ + InstancePartition.create = function create(properties) { + return new InstancePartition(properties); + }; + + /** + * Encodes the specified InstancePartition message. Does not implicitly {@link google.spanner.admin.instance.v1.InstancePartition.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {google.spanner.admin.instance.v1.IInstancePartition} message InstancePartition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstancePartition.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.config != null && Object.hasOwnProperty.call(message, "config")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.config); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.displayName); + if (message.nodeCount != null && Object.hasOwnProperty.call(message, "nodeCount")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.nodeCount); + if (message.processingUnits != null && Object.hasOwnProperty.call(message, "processingUnits")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.processingUnits); + if (message.state != null && Object.hasOwnProperty.call(message, "state")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.state); + if (message.createTime != null && Object.hasOwnProperty.call(message, "createTime")) + $root.google.protobuf.Timestamp.encode(message.createTime, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.updateTime != null && Object.hasOwnProperty.call(message, "updateTime")) + $root.google.protobuf.Timestamp.encode(message.updateTime, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + if (message.referencingDatabases != null && message.referencingDatabases.length) + for (var i = 0; i < message.referencingDatabases.length; ++i) + writer.uint32(/* id 10, wireType 2 =*/82).string(message.referencingDatabases[i]); + if (message.referencingBackups != null && message.referencingBackups.length) + for (var i = 0; i < message.referencingBackups.length; ++i) + writer.uint32(/* id 11, wireType 2 =*/90).string(message.referencingBackups[i]); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 12, wireType 2 =*/98).string(message.etag); + if (message.autoscalingConfig != null && Object.hasOwnProperty.call(message, "autoscalingConfig")) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.encode(message.autoscalingConfig, writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified InstancePartition message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.InstancePartition.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {google.spanner.admin.instance.v1.IInstancePartition} message InstancePartition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstancePartition.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstancePartition message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.InstancePartition} InstancePartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstancePartition.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.spanner.admin.instance.v1.InstancePartition(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.config = reader.string(); + break; + } + case 3: { + message.displayName = reader.string(); + break; + } + case 5: { + message.nodeCount = reader.int32(); + break; + } + case 6: { + message.processingUnits = reader.int32(); + break; + } + case 13: { + message.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.decode(reader, reader.uint32()); + break; + } + case 7: { + message.state = reader.int32(); + break; + } + case 8: { + message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 9: { + message.updateTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 10: { + if (!(message.referencingDatabases && message.referencingDatabases.length)) + message.referencingDatabases = []; + message.referencingDatabases.push(reader.string()); + break; + } + case 11: { + if (!(message.referencingBackups && message.referencingBackups.length)) + message.referencingBackups = []; + message.referencingBackups.push(reader.string()); + break; + } + case 12: { + message.etag = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstancePartition message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.InstancePartition} InstancePartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstancePartition.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstancePartition message. + * @function verify + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstancePartition.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.config != null && message.hasOwnProperty("config")) + if (!$util.isString(message.config)) + return "config: string expected"; + if (message.displayName != null && message.hasOwnProperty("displayName")) + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) { + properties.computeCapacity = 1; + if (!$util.isInteger(message.nodeCount)) + return "nodeCount: integer expected"; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) { + if (properties.computeCapacity === 1) + return "computeCapacity: multiple values"; + properties.computeCapacity = 1; + if (!$util.isInteger(message.processingUnits)) + return "processingUnits: integer expected"; + } + if (message.autoscalingConfig != null && message.hasOwnProperty("autoscalingConfig")) { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.verify(message.autoscalingConfig); + if (error) + return "autoscalingConfig." + error; + } + if (message.state != null && message.hasOwnProperty("state")) + switch (message.state) { + default: + return "state: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.createTime != null && message.hasOwnProperty("createTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.createTime); + if (error) + return "createTime." + error; + } + if (message.updateTime != null && message.hasOwnProperty("updateTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.updateTime); + if (error) + return "updateTime." + error; + } + if (message.referencingDatabases != null && message.hasOwnProperty("referencingDatabases")) { + if (!Array.isArray(message.referencingDatabases)) + return "referencingDatabases: array expected"; + for (var i = 0; i < message.referencingDatabases.length; ++i) + if (!$util.isString(message.referencingDatabases[i])) + return "referencingDatabases: string[] expected"; + } + if (message.referencingBackups != null && message.hasOwnProperty("referencingBackups")) { + if (!Array.isArray(message.referencingBackups)) + return "referencingBackups: array expected"; + for (var i = 0; i < message.referencingBackups.length; ++i) + if (!$util.isString(message.referencingBackups[i])) + return "referencingBackups: string[] expected"; + } + if (message.etag != null && message.hasOwnProperty("etag")) + if (!$util.isString(message.etag)) + return "etag: string expected"; + return null; + }; + + /** + * Creates an InstancePartition message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.InstancePartition} InstancePartition + */ + InstancePartition.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.InstancePartition) + return object; + var message = new $root.google.spanner.admin.instance.v1.InstancePartition(); + if (object.name != null) + message.name = String(object.name); + if (object.config != null) + message.config = String(object.config); + if (object.displayName != null) + message.displayName = String(object.displayName); + if (object.nodeCount != null) + message.nodeCount = object.nodeCount | 0; + if (object.processingUnits != null) + message.processingUnits = object.processingUnits | 0; + if (object.autoscalingConfig != null) { + if (typeof object.autoscalingConfig !== "object") + throw TypeError(".google.spanner.admin.instance.v1.InstancePartition.autoscalingConfig: object expected"); + message.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.fromObject(object.autoscalingConfig); + } + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "CREATING": + case 1: + message.state = 1; + break; + case "READY": + case 2: + message.state = 2; + break; + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.InstancePartition.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.InstancePartition.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + if (object.referencingDatabases) { + if (!Array.isArray(object.referencingDatabases)) + throw TypeError(".google.spanner.admin.instance.v1.InstancePartition.referencingDatabases: array expected"); + message.referencingDatabases = []; + for (var i = 0; i < object.referencingDatabases.length; ++i) + message.referencingDatabases[i] = String(object.referencingDatabases[i]); + } + if (object.referencingBackups) { + if (!Array.isArray(object.referencingBackups)) + throw TypeError(".google.spanner.admin.instance.v1.InstancePartition.referencingBackups: array expected"); + message.referencingBackups = []; + for (var i = 0; i < object.referencingBackups.length; ++i) + message.referencingBackups[i] = String(object.referencingBackups[i]); + } + if (object.etag != null) + message.etag = String(object.etag); + return message; + }; + + /** + * Creates a plain object from an InstancePartition message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {google.spanner.admin.instance.v1.InstancePartition} message InstancePartition + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstancePartition.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.referencingDatabases = []; + object.referencingBackups = []; + } + if (options.defaults) { + object.name = ""; + object.config = ""; + object.displayName = ""; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + object.createTime = null; + object.updateTime = null; + object.etag = ""; + object.autoscalingConfig = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.config != null && message.hasOwnProperty("config")) + object.config = message.config; + if (message.displayName != null && message.hasOwnProperty("displayName")) + object.displayName = message.displayName; + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) { + object.nodeCount = message.nodeCount; + if (options.oneofs) + object.computeCapacity = "nodeCount"; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) { + object.processingUnits = message.processingUnits; + if (options.oneofs) + object.computeCapacity = "processingUnits"; + } + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.spanner.admin.instance.v1.InstancePartition.State[message.state] === undefined ? message.state : $root.google.spanner.admin.instance.v1.InstancePartition.State[message.state] : message.state; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.referencingDatabases && message.referencingDatabases.length) { + object.referencingDatabases = []; + for (var j = 0; j < message.referencingDatabases.length; ++j) + object.referencingDatabases[j] = message.referencingDatabases[j]; + } + if (message.referencingBackups && message.referencingBackups.length) { + object.referencingBackups = []; + for (var j = 0; j < message.referencingBackups.length; ++j) + object.referencingBackups[j] = message.referencingBackups[j]; + } + if (message.etag != null && message.hasOwnProperty("etag")) + object.etag = message.etag; + if (message.autoscalingConfig != null && message.hasOwnProperty("autoscalingConfig")) + object.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.toObject(message.autoscalingConfig, options); + return object; + }; + + /** + * Converts this InstancePartition to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @instance + * @returns {Object.} JSON object + */ + InstancePartition.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstancePartition + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.InstancePartition + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstancePartition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.InstancePartition"; + }; + + /** + * State enum. + * @name google.spanner.admin.instance.v1.InstancePartition.State + * @enum {number} + * @property {number} STATE_UNSPECIFIED=0 STATE_UNSPECIFIED value + * @property {number} CREATING=1 CREATING value + * @property {number} READY=2 READY value + */ + InstancePartition.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = 0; + values[valuesById[1] = "CREATING"] = 1; + values[valuesById[2] = "READY"] = 2; + return values; + })(); + + return InstancePartition; + })(); + + v1.CreateInstancePartitionMetadata = (function() { + + /** + * Properties of a CreateInstancePartitionMetadata. + * @memberof google.spanner.admin.instance.v1 + * @interface ICreateInstancePartitionMetadata + * @property {google.spanner.admin.instance.v1.IInstancePartition|null} [instancePartition] CreateInstancePartitionMetadata instancePartition + * @property {google.protobuf.ITimestamp|null} [startTime] CreateInstancePartitionMetadata startTime + * @property {google.protobuf.ITimestamp|null} [cancelTime] CreateInstancePartitionMetadata cancelTime + * @property {google.protobuf.ITimestamp|null} [endTime] CreateInstancePartitionMetadata endTime + */ + + /** + * Constructs a new CreateInstancePartitionMetadata. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a CreateInstancePartitionMetadata. + * @implements ICreateInstancePartitionMetadata + * @constructor + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata=} [properties] Properties to set + */ + function CreateInstancePartitionMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateInstancePartitionMetadata instancePartition. + * @member {google.spanner.admin.instance.v1.IInstancePartition|null|undefined} instancePartition + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @instance + */ + CreateInstancePartitionMetadata.prototype.instancePartition = null; + + /** + * CreateInstancePartitionMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @instance + */ + CreateInstancePartitionMetadata.prototype.startTime = null; + + /** + * CreateInstancePartitionMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @instance + */ + CreateInstancePartitionMetadata.prototype.cancelTime = null; + + /** + * CreateInstancePartitionMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @instance + */ + CreateInstancePartitionMetadata.prototype.endTime = null; + + /** + * Creates a new CreateInstancePartitionMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.CreateInstancePartitionMetadata} CreateInstancePartitionMetadata instance + */ + CreateInstancePartitionMetadata.create = function create(properties) { + return new CreateInstancePartitionMetadata(properties); + }; + + /** + * Encodes the specified CreateInstancePartitionMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstancePartitionMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata} message CreateInstancePartitionMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstancePartitionMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instancePartition != null && Object.hasOwnProperty.call(message, "instancePartition")) + $root.google.spanner.admin.instance.v1.InstancePartition.encode(message.instancePartition, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) + $root.google.protobuf.Timestamp.encode(message.endTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateInstancePartitionMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstancePartitionMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata} message CreateInstancePartitionMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstancePartitionMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateInstancePartitionMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.CreateInstancePartitionMetadata} CreateInstancePartitionMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstancePartitionMetadata.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.spanner.admin.instance.v1.CreateInstancePartitionMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.decode(reader, reader.uint32()); + break; + } + case 2: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.endTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateInstancePartitionMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.CreateInstancePartitionMetadata} CreateInstancePartitionMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstancePartitionMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateInstancePartitionMetadata message. + * @function verify + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateInstancePartitionMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) { + var error = $root.google.spanner.admin.instance.v1.InstancePartition.verify(message.instancePartition); + if (error) + return "instancePartition." + error; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + if (message.endTime != null && message.hasOwnProperty("endTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.endTime); + if (error) + return "endTime." + error; + } + return null; + }; + + /** + * Creates a CreateInstancePartitionMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.CreateInstancePartitionMetadata} CreateInstancePartitionMetadata + */ + CreateInstancePartitionMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata) + return object; + var message = new $root.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata(); + if (object.instancePartition != null) { + if (typeof object.instancePartition !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstancePartitionMetadata.instancePartition: object expected"); + message.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.fromObject(object.instancePartition); + } + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstancePartitionMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstancePartitionMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstancePartitionMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + return message; + }; + + /** + * Creates a plain object from a CreateInstancePartitionMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {google.spanner.admin.instance.v1.CreateInstancePartitionMetadata} message CreateInstancePartitionMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateInstancePartitionMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instancePartition = null; + object.startTime = null; + object.cancelTime = null; + object.endTime = null; + } + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) + object.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.toObject(message.instancePartition, options); + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + return object; + }; + + /** + * Converts this CreateInstancePartitionMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @instance + * @returns {Object.} JSON object + */ + CreateInstancePartitionMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateInstancePartitionMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateInstancePartitionMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata"; + }; + + return CreateInstancePartitionMetadata; + })(); + + v1.CreateInstancePartitionRequest = (function() { + + /** + * Properties of a CreateInstancePartitionRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface ICreateInstancePartitionRequest + * @property {string|null} [parent] CreateInstancePartitionRequest parent + * @property {string|null} [instancePartitionId] CreateInstancePartitionRequest instancePartitionId + * @property {google.spanner.admin.instance.v1.IInstancePartition|null} [instancePartition] CreateInstancePartitionRequest instancePartition + */ + + /** + * Constructs a new CreateInstancePartitionRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a CreateInstancePartitionRequest. + * @implements ICreateInstancePartitionRequest + * @constructor + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionRequest=} [properties] Properties to set + */ + function CreateInstancePartitionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateInstancePartitionRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @instance + */ + CreateInstancePartitionRequest.prototype.parent = ""; + + /** + * CreateInstancePartitionRequest instancePartitionId. + * @member {string} instancePartitionId + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @instance + */ + CreateInstancePartitionRequest.prototype.instancePartitionId = ""; + + /** + * CreateInstancePartitionRequest instancePartition. + * @member {google.spanner.admin.instance.v1.IInstancePartition|null|undefined} instancePartition + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @instance + */ + CreateInstancePartitionRequest.prototype.instancePartition = null; + + /** + * Creates a new CreateInstancePartitionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.CreateInstancePartitionRequest} CreateInstancePartitionRequest instance + */ + CreateInstancePartitionRequest.create = function create(properties) { + return new CreateInstancePartitionRequest(properties); + }; + + /** + * Encodes the specified CreateInstancePartitionRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstancePartitionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionRequest} message CreateInstancePartitionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstancePartitionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.instancePartitionId != null && Object.hasOwnProperty.call(message, "instancePartitionId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instancePartitionId); + if (message.instancePartition != null && Object.hasOwnProperty.call(message, "instancePartition")) + $root.google.spanner.admin.instance.v1.InstancePartition.encode(message.instancePartition, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateInstancePartitionRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstancePartitionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.ICreateInstancePartitionRequest} message CreateInstancePartitionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateInstancePartitionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateInstancePartitionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.CreateInstancePartitionRequest} CreateInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstancePartitionRequest.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.spanner.admin.instance.v1.CreateInstancePartitionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.instancePartitionId = reader.string(); + break; + } + case 3: { + message.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateInstancePartitionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.CreateInstancePartitionRequest} CreateInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateInstancePartitionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateInstancePartitionRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateInstancePartitionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.instancePartitionId != null && message.hasOwnProperty("instancePartitionId")) + if (!$util.isString(message.instancePartitionId)) + return "instancePartitionId: string expected"; + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) { + var error = $root.google.spanner.admin.instance.v1.InstancePartition.verify(message.instancePartition); + if (error) + return "instancePartition." + error; + } + return null; + }; + + /** + * Creates a CreateInstancePartitionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.CreateInstancePartitionRequest} CreateInstancePartitionRequest + */ + CreateInstancePartitionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.CreateInstancePartitionRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.CreateInstancePartitionRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.instancePartitionId != null) + message.instancePartitionId = String(object.instancePartitionId); + if (object.instancePartition != null) { + if (typeof object.instancePartition !== "object") + throw TypeError(".google.spanner.admin.instance.v1.CreateInstancePartitionRequest.instancePartition: object expected"); + message.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.fromObject(object.instancePartition); + } + return message; + }; + + /** + * Creates a plain object from a CreateInstancePartitionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.CreateInstancePartitionRequest} message CreateInstancePartitionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateInstancePartitionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.instancePartitionId = ""; + object.instancePartition = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.instancePartitionId != null && message.hasOwnProperty("instancePartitionId")) + object.instancePartitionId = message.instancePartitionId; + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) + object.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.toObject(message.instancePartition, options); + return object; + }; + + /** + * Converts this CreateInstancePartitionRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @instance + * @returns {Object.} JSON object + */ + CreateInstancePartitionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateInstancePartitionRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.CreateInstancePartitionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateInstancePartitionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.CreateInstancePartitionRequest"; + }; + + return CreateInstancePartitionRequest; + })(); + + v1.DeleteInstancePartitionRequest = (function() { + + /** + * Properties of a DeleteInstancePartitionRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IDeleteInstancePartitionRequest + * @property {string|null} [name] DeleteInstancePartitionRequest name + * @property {string|null} [etag] DeleteInstancePartitionRequest etag + */ + + /** + * Constructs a new DeleteInstancePartitionRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a DeleteInstancePartitionRequest. + * @implements IDeleteInstancePartitionRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest=} [properties] Properties to set + */ + function DeleteInstancePartitionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteInstancePartitionRequest name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @instance + */ + DeleteInstancePartitionRequest.prototype.name = ""; + + /** + * DeleteInstancePartitionRequest etag. + * @member {string} etag + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @instance + */ + DeleteInstancePartitionRequest.prototype.etag = ""; + + /** + * Creates a new DeleteInstancePartitionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.DeleteInstancePartitionRequest} DeleteInstancePartitionRequest instance + */ + DeleteInstancePartitionRequest.create = function create(properties) { + return new DeleteInstancePartitionRequest(properties); + }; + + /** + * Encodes the specified DeleteInstancePartitionRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstancePartitionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest} message DeleteInstancePartitionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteInstancePartitionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.etag); + return writer; + }; + + /** + * Encodes the specified DeleteInstancePartitionRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstancePartitionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest} message DeleteInstancePartitionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteInstancePartitionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteInstancePartitionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.DeleteInstancePartitionRequest} DeleteInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteInstancePartitionRequest.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.spanner.admin.instance.v1.DeleteInstancePartitionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.etag = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteInstancePartitionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.DeleteInstancePartitionRequest} DeleteInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteInstancePartitionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteInstancePartitionRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteInstancePartitionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.etag != null && message.hasOwnProperty("etag")) + if (!$util.isString(message.etag)) + return "etag: string expected"; + return null; + }; + + /** + * Creates a DeleteInstancePartitionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.DeleteInstancePartitionRequest} DeleteInstancePartitionRequest + */ + DeleteInstancePartitionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.etag != null) + message.etag = String(object.etag); + return message; + }; + + /** + * Creates a plain object from a DeleteInstancePartitionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.DeleteInstancePartitionRequest} message DeleteInstancePartitionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteInstancePartitionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.etag = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.etag != null && message.hasOwnProperty("etag")) + object.etag = message.etag; + return object; + }; + + /** + * Converts this DeleteInstancePartitionRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteInstancePartitionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteInstancePartitionRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.DeleteInstancePartitionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteInstancePartitionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.DeleteInstancePartitionRequest"; + }; + + return DeleteInstancePartitionRequest; + })(); + + v1.GetInstancePartitionRequest = (function() { + + /** + * Properties of a GetInstancePartitionRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IGetInstancePartitionRequest + * @property {string|null} [name] GetInstancePartitionRequest name + */ + + /** + * Constructs a new GetInstancePartitionRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a GetInstancePartitionRequest. + * @implements IGetInstancePartitionRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IGetInstancePartitionRequest=} [properties] Properties to set + */ + function GetInstancePartitionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetInstancePartitionRequest name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @instance + */ + GetInstancePartitionRequest.prototype.name = ""; + + /** + * Creates a new GetInstancePartitionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstancePartitionRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.GetInstancePartitionRequest} GetInstancePartitionRequest instance + */ + GetInstancePartitionRequest.create = function create(properties) { + return new GetInstancePartitionRequest(properties); + }; + + /** + * Encodes the specified GetInstancePartitionRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstancePartitionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstancePartitionRequest} message GetInstancePartitionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetInstancePartitionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetInstancePartitionRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstancePartitionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IGetInstancePartitionRequest} message GetInstancePartitionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetInstancePartitionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetInstancePartitionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.GetInstancePartitionRequest} GetInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetInstancePartitionRequest.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.spanner.admin.instance.v1.GetInstancePartitionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetInstancePartitionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.GetInstancePartitionRequest} GetInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetInstancePartitionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetInstancePartitionRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetInstancePartitionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetInstancePartitionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.GetInstancePartitionRequest} GetInstancePartitionRequest + */ + GetInstancePartitionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.GetInstancePartitionRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.GetInstancePartitionRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetInstancePartitionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.GetInstancePartitionRequest} message GetInstancePartitionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetInstancePartitionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetInstancePartitionRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @instance + * @returns {Object.} JSON object + */ + GetInstancePartitionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetInstancePartitionRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.GetInstancePartitionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetInstancePartitionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.GetInstancePartitionRequest"; + }; + + return GetInstancePartitionRequest; + })(); + + v1.UpdateInstancePartitionRequest = (function() { + + /** + * Properties of an UpdateInstancePartitionRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IUpdateInstancePartitionRequest + * @property {google.spanner.admin.instance.v1.IInstancePartition|null} [instancePartition] UpdateInstancePartitionRequest instancePartition + * @property {google.protobuf.IFieldMask|null} [fieldMask] UpdateInstancePartitionRequest fieldMask + */ + + /** + * Constructs a new UpdateInstancePartitionRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an UpdateInstancePartitionRequest. + * @implements IUpdateInstancePartitionRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest=} [properties] Properties to set + */ + function UpdateInstancePartitionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateInstancePartitionRequest instancePartition. + * @member {google.spanner.admin.instance.v1.IInstancePartition|null|undefined} instancePartition + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @instance + */ + UpdateInstancePartitionRequest.prototype.instancePartition = null; + + /** + * UpdateInstancePartitionRequest fieldMask. + * @member {google.protobuf.IFieldMask|null|undefined} fieldMask + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @instance + */ + UpdateInstancePartitionRequest.prototype.fieldMask = null; + + /** + * Creates a new UpdateInstancePartitionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.UpdateInstancePartitionRequest} UpdateInstancePartitionRequest instance + */ + UpdateInstancePartitionRequest.create = function create(properties) { + return new UpdateInstancePartitionRequest(properties); + }; + + /** + * Encodes the specified UpdateInstancePartitionRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstancePartitionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest} message UpdateInstancePartitionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstancePartitionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instancePartition != null && Object.hasOwnProperty.call(message, "instancePartition")) + $root.google.spanner.admin.instance.v1.InstancePartition.encode(message.instancePartition, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.fieldMask != null && Object.hasOwnProperty.call(message, "fieldMask")) + $root.google.protobuf.FieldMask.encode(message.fieldMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateInstancePartitionRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstancePartitionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest} message UpdateInstancePartitionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstancePartitionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateInstancePartitionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.UpdateInstancePartitionRequest} UpdateInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstancePartitionRequest.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.spanner.admin.instance.v1.UpdateInstancePartitionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.decode(reader, reader.uint32()); + break; + } + case 2: { + message.fieldMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateInstancePartitionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.UpdateInstancePartitionRequest} UpdateInstancePartitionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstancePartitionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateInstancePartitionRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateInstancePartitionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) { + var error = $root.google.spanner.admin.instance.v1.InstancePartition.verify(message.instancePartition); + if (error) + return "instancePartition." + error; + } + if (message.fieldMask != null && message.hasOwnProperty("fieldMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.fieldMask); + if (error) + return "fieldMask." + error; + } + return null; + }; + + /** + * Creates an UpdateInstancePartitionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.UpdateInstancePartitionRequest} UpdateInstancePartitionRequest + */ + UpdateInstancePartitionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest(); + if (object.instancePartition != null) { + if (typeof object.instancePartition !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstancePartitionRequest.instancePartition: object expected"); + message.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.fromObject(object.instancePartition); + } + if (object.fieldMask != null) { + if (typeof object.fieldMask !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstancePartitionRequest.fieldMask: object expected"); + message.fieldMask = $root.google.protobuf.FieldMask.fromObject(object.fieldMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateInstancePartitionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {google.spanner.admin.instance.v1.UpdateInstancePartitionRequest} message UpdateInstancePartitionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateInstancePartitionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instancePartition = null; + object.fieldMask = null; + } + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) + object.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.toObject(message.instancePartition, options); + if (message.fieldMask != null && message.hasOwnProperty("fieldMask")) + object.fieldMask = $root.google.protobuf.FieldMask.toObject(message.fieldMask, options); + return object; + }; + + /** + * Converts this UpdateInstancePartitionRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateInstancePartitionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateInstancePartitionRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateInstancePartitionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.UpdateInstancePartitionRequest"; + }; + + return UpdateInstancePartitionRequest; + })(); + + v1.UpdateInstancePartitionMetadata = (function() { + + /** + * Properties of an UpdateInstancePartitionMetadata. + * @memberof google.spanner.admin.instance.v1 + * @interface IUpdateInstancePartitionMetadata + * @property {google.spanner.admin.instance.v1.IInstancePartition|null} [instancePartition] UpdateInstancePartitionMetadata instancePartition + * @property {google.protobuf.ITimestamp|null} [startTime] UpdateInstancePartitionMetadata startTime + * @property {google.protobuf.ITimestamp|null} [cancelTime] UpdateInstancePartitionMetadata cancelTime + * @property {google.protobuf.ITimestamp|null} [endTime] UpdateInstancePartitionMetadata endTime + */ + + /** + * Constructs a new UpdateInstancePartitionMetadata. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents an UpdateInstancePartitionMetadata. + * @implements IUpdateInstancePartitionMetadata + * @constructor + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata=} [properties] Properties to set + */ + function UpdateInstancePartitionMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateInstancePartitionMetadata instancePartition. + * @member {google.spanner.admin.instance.v1.IInstancePartition|null|undefined} instancePartition + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @instance + */ + UpdateInstancePartitionMetadata.prototype.instancePartition = null; + + /** + * UpdateInstancePartitionMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @instance + */ + UpdateInstancePartitionMetadata.prototype.startTime = null; + + /** + * UpdateInstancePartitionMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @instance + */ + UpdateInstancePartitionMetadata.prototype.cancelTime = null; + + /** + * UpdateInstancePartitionMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @instance + */ + UpdateInstancePartitionMetadata.prototype.endTime = null; + + /** + * Creates a new UpdateInstancePartitionMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata} UpdateInstancePartitionMetadata instance + */ + UpdateInstancePartitionMetadata.create = function create(properties) { + return new UpdateInstancePartitionMetadata(properties); + }; + + /** + * Encodes the specified UpdateInstancePartitionMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata} message UpdateInstancePartitionMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstancePartitionMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instancePartition != null && Object.hasOwnProperty.call(message, "instancePartition")) + $root.google.spanner.admin.instance.v1.InstancePartition.encode(message.instancePartition, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) + $root.google.protobuf.Timestamp.encode(message.endTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateInstancePartitionMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata} message UpdateInstancePartitionMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateInstancePartitionMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateInstancePartitionMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata} UpdateInstancePartitionMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstancePartitionMetadata.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.spanner.admin.instance.v1.UpdateInstancePartitionMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.decode(reader, reader.uint32()); + break; + } + case 2: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.endTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateInstancePartitionMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata} UpdateInstancePartitionMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateInstancePartitionMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateInstancePartitionMetadata message. + * @function verify + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateInstancePartitionMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) { + var error = $root.google.spanner.admin.instance.v1.InstancePartition.verify(message.instancePartition); + if (error) + return "instancePartition." + error; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + if (message.endTime != null && message.hasOwnProperty("endTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.endTime); + if (error) + return "endTime." + error; + } + return null; + }; + + /** + * Creates an UpdateInstancePartitionMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata} UpdateInstancePartitionMetadata + */ + UpdateInstancePartitionMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata) + return object; + var message = new $root.google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata(); + if (object.instancePartition != null) { + if (typeof object.instancePartition !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.instancePartition: object expected"); + message.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.fromObject(object.instancePartition); + } + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + return message; + }; + + /** + * Creates a plain object from an UpdateInstancePartitionMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata} message UpdateInstancePartitionMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateInstancePartitionMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instancePartition = null; + object.startTime = null; + object.cancelTime = null; + object.endTime = null; + } + if (message.instancePartition != null && message.hasOwnProperty("instancePartition")) + object.instancePartition = $root.google.spanner.admin.instance.v1.InstancePartition.toObject(message.instancePartition, options); + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + return object; + }; + + /** + * Converts this UpdateInstancePartitionMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @instance + * @returns {Object.} JSON object + */ + UpdateInstancePartitionMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateInstancePartitionMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateInstancePartitionMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata"; + }; + + return UpdateInstancePartitionMetadata; + })(); + + v1.ListInstancePartitionsRequest = (function() { + + /** + * Properties of a ListInstancePartitionsRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstancePartitionsRequest + * @property {string|null} [parent] ListInstancePartitionsRequest parent + * @property {number|null} [pageSize] ListInstancePartitionsRequest pageSize + * @property {string|null} [pageToken] ListInstancePartitionsRequest pageToken + * @property {google.protobuf.ITimestamp|null} [instancePartitionDeadline] ListInstancePartitionsRequest instancePartitionDeadline + */ + + /** + * Constructs a new ListInstancePartitionsRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstancePartitionsRequest. + * @implements IListInstancePartitionsRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsRequest=} [properties] Properties to set + */ + function ListInstancePartitionsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstancePartitionsRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @instance + */ + ListInstancePartitionsRequest.prototype.parent = ""; + + /** + * ListInstancePartitionsRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @instance + */ + ListInstancePartitionsRequest.prototype.pageSize = 0; + + /** + * ListInstancePartitionsRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @instance + */ + ListInstancePartitionsRequest.prototype.pageToken = ""; + + /** + * ListInstancePartitionsRequest instancePartitionDeadline. + * @member {google.protobuf.ITimestamp|null|undefined} instancePartitionDeadline + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @instance + */ + ListInstancePartitionsRequest.prototype.instancePartitionDeadline = null; + + /** + * Creates a new ListInstancePartitionsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionsRequest} ListInstancePartitionsRequest instance + */ + ListInstancePartitionsRequest.create = function create(properties) { + return new ListInstancePartitionsRequest(properties); + }; + + /** + * Encodes the specified ListInstancePartitionsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsRequest} message ListInstancePartitionsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancePartitionsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + if (message.instancePartitionDeadline != null && Object.hasOwnProperty.call(message, "instancePartitionDeadline")) + $root.google.protobuf.Timestamp.encode(message.instancePartitionDeadline, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ListInstancePartitionsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsRequest} message ListInstancePartitionsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancePartitionsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstancePartitionsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionsRequest} ListInstancePartitionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancePartitionsRequest.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.spanner.admin.instance.v1.ListInstancePartitionsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + case 4: { + message.instancePartitionDeadline = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstancePartitionsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionsRequest} ListInstancePartitionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancePartitionsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstancePartitionsRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstancePartitionsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + if (message.instancePartitionDeadline != null && message.hasOwnProperty("instancePartitionDeadline")) { + var error = $root.google.protobuf.Timestamp.verify(message.instancePartitionDeadline); + if (error) + return "instancePartitionDeadline." + error; + } + return null; + }; + + /** + * Creates a ListInstancePartitionsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionsRequest} ListInstancePartitionsRequest + */ + ListInstancePartitionsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstancePartitionsRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstancePartitionsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.instancePartitionDeadline != null) { + if (typeof object.instancePartitionDeadline !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ListInstancePartitionsRequest.instancePartitionDeadline: object expected"); + message.instancePartitionDeadline = $root.google.protobuf.Timestamp.fromObject(object.instancePartitionDeadline); + } + return message; + }; + + /** + * Creates a plain object from a ListInstancePartitionsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {google.spanner.admin.instance.v1.ListInstancePartitionsRequest} message ListInstancePartitionsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstancePartitionsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + object.instancePartitionDeadline = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.instancePartitionDeadline != null && message.hasOwnProperty("instancePartitionDeadline")) + object.instancePartitionDeadline = $root.google.protobuf.Timestamp.toObject(message.instancePartitionDeadline, options); + return object; + }; + + /** + * Converts this ListInstancePartitionsRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @instance + * @returns {Object.} JSON object + */ + ListInstancePartitionsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstancePartitionsRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstancePartitionsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstancePartitionsRequest"; + }; + + return ListInstancePartitionsRequest; + })(); + + v1.ListInstancePartitionsResponse = (function() { + + /** + * Properties of a ListInstancePartitionsResponse. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstancePartitionsResponse + * @property {Array.|null} [instancePartitions] ListInstancePartitionsResponse instancePartitions + * @property {string|null} [nextPageToken] ListInstancePartitionsResponse nextPageToken + * @property {Array.|null} [unreachable] ListInstancePartitionsResponse unreachable + */ + + /** + * Constructs a new ListInstancePartitionsResponse. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstancePartitionsResponse. + * @implements IListInstancePartitionsResponse + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsResponse=} [properties] Properties to set + */ + function ListInstancePartitionsResponse(properties) { + this.instancePartitions = []; + this.unreachable = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstancePartitionsResponse instancePartitions. + * @member {Array.} instancePartitions + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @instance + */ + ListInstancePartitionsResponse.prototype.instancePartitions = $util.emptyArray; + + /** + * ListInstancePartitionsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @instance + */ + ListInstancePartitionsResponse.prototype.nextPageToken = ""; + + /** + * ListInstancePartitionsResponse unreachable. + * @member {Array.} unreachable + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @instance + */ + ListInstancePartitionsResponse.prototype.unreachable = $util.emptyArray; + + /** + * Creates a new ListInstancePartitionsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsResponse=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionsResponse} ListInstancePartitionsResponse instance + */ + ListInstancePartitionsResponse.create = function create(properties) { + return new ListInstancePartitionsResponse(properties); + }; + + /** + * Encodes the specified ListInstancePartitionsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsResponse} message ListInstancePartitionsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancePartitionsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instancePartitions != null && message.instancePartitions.length) + for (var i = 0; i < message.instancePartitions.length; ++i) + $root.google.spanner.admin.instance.v1.InstancePartition.encode(message.instancePartitions[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + if (message.unreachable != null && message.unreachable.length) + for (var i = 0; i < message.unreachable.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.unreachable[i]); + return writer; + }; + + /** + * Encodes the specified ListInstancePartitionsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionsResponse} message ListInstancePartitionsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancePartitionsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstancePartitionsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionsResponse} ListInstancePartitionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancePartitionsResponse.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.spanner.admin.instance.v1.ListInstancePartitionsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.instancePartitions && message.instancePartitions.length)) + message.instancePartitions = []; + message.instancePartitions.push($root.google.spanner.admin.instance.v1.InstancePartition.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + case 3: { + if (!(message.unreachable && message.unreachable.length)) + message.unreachable = []; + message.unreachable.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstancePartitionsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionsResponse} ListInstancePartitionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancePartitionsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstancePartitionsResponse message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstancePartitionsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instancePartitions != null && message.hasOwnProperty("instancePartitions")) { + if (!Array.isArray(message.instancePartitions)) + return "instancePartitions: array expected"; + for (var i = 0; i < message.instancePartitions.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.InstancePartition.verify(message.instancePartitions[i]); + if (error) + return "instancePartitions." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + if (message.unreachable != null && message.hasOwnProperty("unreachable")) { + if (!Array.isArray(message.unreachable)) + return "unreachable: array expected"; + for (var i = 0; i < message.unreachable.length; ++i) + if (!$util.isString(message.unreachable[i])) + return "unreachable: string[] expected"; + } + return null; + }; + + /** + * Creates a ListInstancePartitionsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionsResponse} ListInstancePartitionsResponse + */ + ListInstancePartitionsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstancePartitionsResponse) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstancePartitionsResponse(); + if (object.instancePartitions) { + if (!Array.isArray(object.instancePartitions)) + throw TypeError(".google.spanner.admin.instance.v1.ListInstancePartitionsResponse.instancePartitions: array expected"); + message.instancePartitions = []; + for (var i = 0; i < object.instancePartitions.length; ++i) { + if (typeof object.instancePartitions[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ListInstancePartitionsResponse.instancePartitions: object expected"); + message.instancePartitions[i] = $root.google.spanner.admin.instance.v1.InstancePartition.fromObject(object.instancePartitions[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.unreachable) { + if (!Array.isArray(object.unreachable)) + throw TypeError(".google.spanner.admin.instance.v1.ListInstancePartitionsResponse.unreachable: array expected"); + message.unreachable = []; + for (var i = 0; i < object.unreachable.length; ++i) + message.unreachable[i] = String(object.unreachable[i]); + } + return message; + }; + + /** + * Creates a plain object from a ListInstancePartitionsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {google.spanner.admin.instance.v1.ListInstancePartitionsResponse} message ListInstancePartitionsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstancePartitionsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.instancePartitions = []; + object.unreachable = []; + } + if (options.defaults) + object.nextPageToken = ""; + if (message.instancePartitions && message.instancePartitions.length) { + object.instancePartitions = []; + for (var j = 0; j < message.instancePartitions.length; ++j) + object.instancePartitions[j] = $root.google.spanner.admin.instance.v1.InstancePartition.toObject(message.instancePartitions[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.unreachable && message.unreachable.length) { + object.unreachable = []; + for (var j = 0; j < message.unreachable.length; ++j) + object.unreachable[j] = message.unreachable[j]; + } + return object; + }; + + /** + * Converts this ListInstancePartitionsResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @instance + * @returns {Object.} JSON object + */ + ListInstancePartitionsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstancePartitionsResponse + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstancePartitionsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstancePartitionsResponse"; + }; + + return ListInstancePartitionsResponse; + })(); + + v1.ListInstancePartitionOperationsRequest = (function() { + + /** + * Properties of a ListInstancePartitionOperationsRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstancePartitionOperationsRequest + * @property {string|null} [parent] ListInstancePartitionOperationsRequest parent + * @property {string|null} [filter] ListInstancePartitionOperationsRequest filter + * @property {number|null} [pageSize] ListInstancePartitionOperationsRequest pageSize + * @property {string|null} [pageToken] ListInstancePartitionOperationsRequest pageToken + * @property {google.protobuf.ITimestamp|null} [instancePartitionDeadline] ListInstancePartitionOperationsRequest instancePartitionDeadline + */ + + /** + * Constructs a new ListInstancePartitionOperationsRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstancePartitionOperationsRequest. + * @implements IListInstancePartitionOperationsRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest=} [properties] Properties to set + */ + function ListInstancePartitionOperationsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstancePartitionOperationsRequest parent. + * @member {string} parent + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @instance + */ + ListInstancePartitionOperationsRequest.prototype.parent = ""; + + /** + * ListInstancePartitionOperationsRequest filter. + * @member {string} filter + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @instance + */ + ListInstancePartitionOperationsRequest.prototype.filter = ""; + + /** + * ListInstancePartitionOperationsRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @instance + */ + ListInstancePartitionOperationsRequest.prototype.pageSize = 0; + + /** + * ListInstancePartitionOperationsRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @instance + */ + ListInstancePartitionOperationsRequest.prototype.pageToken = ""; + + /** + * ListInstancePartitionOperationsRequest instancePartitionDeadline. + * @member {google.protobuf.ITimestamp|null|undefined} instancePartitionDeadline + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @instance + */ + ListInstancePartitionOperationsRequest.prototype.instancePartitionDeadline = null; + + /** + * Creates a new ListInstancePartitionOperationsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest} ListInstancePartitionOperationsRequest instance + */ + ListInstancePartitionOperationsRequest.create = function create(properties) { + return new ListInstancePartitionOperationsRequest(properties); + }; + + /** + * Encodes the specified ListInstancePartitionOperationsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest} message ListInstancePartitionOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancePartitionOperationsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + if (message.instancePartitionDeadline != null && Object.hasOwnProperty.call(message, "instancePartitionDeadline")) + $root.google.protobuf.Timestamp.encode(message.instancePartitionDeadline, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ListInstancePartitionOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest} message ListInstancePartitionOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancePartitionOperationsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstancePartitionOperationsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest} ListInstancePartitionOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancePartitionOperationsRequest.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.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + case 5: { + message.instancePartitionDeadline = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstancePartitionOperationsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest} ListInstancePartitionOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancePartitionOperationsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstancePartitionOperationsRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstancePartitionOperationsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + if (message.instancePartitionDeadline != null && message.hasOwnProperty("instancePartitionDeadline")) { + var error = $root.google.protobuf.Timestamp.verify(message.instancePartitionDeadline); + if (error) + return "instancePartitionDeadline." + error; + } + return null; + }; + + /** + * Creates a ListInstancePartitionOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest} ListInstancePartitionOperationsRequest + */ + ListInstancePartitionOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.instancePartitionDeadline != null) { + if (typeof object.instancePartitionDeadline !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest.instancePartitionDeadline: object expected"); + message.instancePartitionDeadline = $root.google.protobuf.Timestamp.fromObject(object.instancePartitionDeadline); + } + return message; + }; + + /** + * Creates a plain object from a ListInstancePartitionOperationsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest} message ListInstancePartitionOperationsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstancePartitionOperationsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + object.instancePartitionDeadline = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.instancePartitionDeadline != null && message.hasOwnProperty("instancePartitionDeadline")) + object.instancePartitionDeadline = $root.google.protobuf.Timestamp.toObject(message.instancePartitionDeadline, options); + return object; + }; + + /** + * Converts this ListInstancePartitionOperationsRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @instance + * @returns {Object.} JSON object + */ + ListInstancePartitionOperationsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstancePartitionOperationsRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstancePartitionOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest"; + }; + + return ListInstancePartitionOperationsRequest; + })(); + + v1.ListInstancePartitionOperationsResponse = (function() { + + /** + * Properties of a ListInstancePartitionOperationsResponse. + * @memberof google.spanner.admin.instance.v1 + * @interface IListInstancePartitionOperationsResponse + * @property {Array.|null} [operations] ListInstancePartitionOperationsResponse operations + * @property {string|null} [nextPageToken] ListInstancePartitionOperationsResponse nextPageToken + * @property {Array.|null} [unreachableInstancePartitions] ListInstancePartitionOperationsResponse unreachableInstancePartitions + */ + + /** + * Constructs a new ListInstancePartitionOperationsResponse. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a ListInstancePartitionOperationsResponse. + * @implements IListInstancePartitionOperationsResponse + * @constructor + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse=} [properties] Properties to set + */ + function ListInstancePartitionOperationsResponse(properties) { + this.operations = []; + this.unreachableInstancePartitions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstancePartitionOperationsResponse operations. + * @member {Array.} operations + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @instance + */ + ListInstancePartitionOperationsResponse.prototype.operations = $util.emptyArray; + + /** + * ListInstancePartitionOperationsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @instance + */ + ListInstancePartitionOperationsResponse.prototype.nextPageToken = ""; + + /** + * ListInstancePartitionOperationsResponse unreachableInstancePartitions. + * @member {Array.} unreachableInstancePartitions + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @instance + */ + ListInstancePartitionOperationsResponse.prototype.unreachableInstancePartitions = $util.emptyArray; + + /** + * Creates a new ListInstancePartitionOperationsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse} ListInstancePartitionOperationsResponse instance + */ + ListInstancePartitionOperationsResponse.create = function create(properties) { + return new ListInstancePartitionOperationsResponse(properties); + }; + + /** + * Encodes the specified ListInstancePartitionOperationsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse} message ListInstancePartitionOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancePartitionOperationsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.operations != null && message.operations.length) + for (var i = 0; i < message.operations.length; ++i) + $root.google.longrunning.Operation.encode(message.operations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + if (message.unreachableInstancePartitions != null && message.unreachableInstancePartitions.length) + for (var i = 0; i < message.unreachableInstancePartitions.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.unreachableInstancePartitions[i]); + return writer; + }; + + /** + * Encodes the specified ListInstancePartitionOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse} message ListInstancePartitionOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstancePartitionOperationsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstancePartitionOperationsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse} ListInstancePartitionOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancePartitionOperationsResponse.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.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.operations && message.operations.length)) + message.operations = []; + message.operations.push($root.google.longrunning.Operation.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + case 3: { + if (!(message.unreachableInstancePartitions && message.unreachableInstancePartitions.length)) + message.unreachableInstancePartitions = []; + message.unreachableInstancePartitions.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstancePartitionOperationsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse} ListInstancePartitionOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstancePartitionOperationsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstancePartitionOperationsResponse message. + * @function verify + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstancePartitionOperationsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.operations != null && message.hasOwnProperty("operations")) { + if (!Array.isArray(message.operations)) + return "operations: array expected"; + for (var i = 0; i < message.operations.length; ++i) { + var error = $root.google.longrunning.Operation.verify(message.operations[i]); + if (error) + return "operations." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + if (message.unreachableInstancePartitions != null && message.hasOwnProperty("unreachableInstancePartitions")) { + if (!Array.isArray(message.unreachableInstancePartitions)) + return "unreachableInstancePartitions: array expected"; + for (var i = 0; i < message.unreachableInstancePartitions.length; ++i) + if (!$util.isString(message.unreachableInstancePartitions[i])) + return "unreachableInstancePartitions: string[] expected"; + } + return null; + }; + + /** + * Creates a ListInstancePartitionOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse} ListInstancePartitionOperationsResponse + */ + ListInstancePartitionOperationsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse) + return object; + var message = new $root.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse(); + if (object.operations) { + if (!Array.isArray(object.operations)) + throw TypeError(".google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.operations: array expected"); + message.operations = []; + for (var i = 0; i < object.operations.length; ++i) { + if (typeof object.operations[i] !== "object") + throw TypeError(".google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.operations: object expected"); + message.operations[i] = $root.google.longrunning.Operation.fromObject(object.operations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.unreachableInstancePartitions) { + if (!Array.isArray(object.unreachableInstancePartitions)) + throw TypeError(".google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.unreachableInstancePartitions: array expected"); + message.unreachableInstancePartitions = []; + for (var i = 0; i < object.unreachableInstancePartitions.length; ++i) + message.unreachableInstancePartitions[i] = String(object.unreachableInstancePartitions[i]); + } + return message; + }; + + /** + * Creates a plain object from a ListInstancePartitionOperationsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse} message ListInstancePartitionOperationsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstancePartitionOperationsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.operations = []; + object.unreachableInstancePartitions = []; + } + if (options.defaults) + object.nextPageToken = ""; + if (message.operations && message.operations.length) { + object.operations = []; + for (var j = 0; j < message.operations.length; ++j) + object.operations[j] = $root.google.longrunning.Operation.toObject(message.operations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.unreachableInstancePartitions && message.unreachableInstancePartitions.length) { + object.unreachableInstancePartitions = []; + for (var j = 0; j < message.unreachableInstancePartitions.length; ++j) + object.unreachableInstancePartitions[j] = message.unreachableInstancePartitions[j]; + } + return object; + }; + + /** + * Converts this ListInstancePartitionOperationsResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @instance + * @returns {Object.} JSON object + */ + ListInstancePartitionOperationsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstancePartitionOperationsResponse + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstancePartitionOperationsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse"; + }; + + return ListInstancePartitionOperationsResponse; + })(); + + v1.MoveInstanceRequest = (function() { + + /** + * Properties of a MoveInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @interface IMoveInstanceRequest + * @property {string|null} [name] MoveInstanceRequest name + * @property {string|null} [targetConfig] MoveInstanceRequest targetConfig + */ + + /** + * Constructs a new MoveInstanceRequest. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a MoveInstanceRequest. + * @implements IMoveInstanceRequest + * @constructor + * @param {google.spanner.admin.instance.v1.IMoveInstanceRequest=} [properties] Properties to set + */ + function MoveInstanceRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MoveInstanceRequest name. + * @member {string} name + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @instance + */ + MoveInstanceRequest.prototype.name = ""; + + /** + * MoveInstanceRequest targetConfig. + * @member {string} targetConfig + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @instance + */ + MoveInstanceRequest.prototype.targetConfig = ""; + + /** + * Creates a new MoveInstanceRequest instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceRequest=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.MoveInstanceRequest} MoveInstanceRequest instance + */ + MoveInstanceRequest.create = function create(properties) { + return new MoveInstanceRequest(properties); + }; + + /** + * Encodes the specified MoveInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceRequest} message MoveInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveInstanceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.targetConfig != null && Object.hasOwnProperty.call(message, "targetConfig")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.targetConfig); + return writer; + }; + + /** + * Encodes the specified MoveInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceRequest} message MoveInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveInstanceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MoveInstanceRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.MoveInstanceRequest} MoveInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveInstanceRequest.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.spanner.admin.instance.v1.MoveInstanceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.targetConfig = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MoveInstanceRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.MoveInstanceRequest} MoveInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveInstanceRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MoveInstanceRequest message. + * @function verify + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MoveInstanceRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.targetConfig != null && message.hasOwnProperty("targetConfig")) + if (!$util.isString(message.targetConfig)) + return "targetConfig: string expected"; + return null; + }; + + /** + * Creates a MoveInstanceRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.MoveInstanceRequest} MoveInstanceRequest + */ + MoveInstanceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.MoveInstanceRequest) + return object; + var message = new $root.google.spanner.admin.instance.v1.MoveInstanceRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.targetConfig != null) + message.targetConfig = String(object.targetConfig); + return message; + }; + + /** + * Creates a plain object from a MoveInstanceRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {google.spanner.admin.instance.v1.MoveInstanceRequest} message MoveInstanceRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MoveInstanceRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.targetConfig = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.targetConfig != null && message.hasOwnProperty("targetConfig")) + object.targetConfig = message.targetConfig; + return object; + }; + + /** + * Converts this MoveInstanceRequest to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @instance + * @returns {Object.} JSON object + */ + MoveInstanceRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MoveInstanceRequest + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.MoveInstanceRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MoveInstanceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.MoveInstanceRequest"; + }; + + return MoveInstanceRequest; + })(); + + v1.MoveInstanceResponse = (function() { + + /** + * Properties of a MoveInstanceResponse. + * @memberof google.spanner.admin.instance.v1 + * @interface IMoveInstanceResponse + */ + + /** + * Constructs a new MoveInstanceResponse. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a MoveInstanceResponse. + * @implements IMoveInstanceResponse + * @constructor + * @param {google.spanner.admin.instance.v1.IMoveInstanceResponse=} [properties] Properties to set + */ + function MoveInstanceResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new MoveInstanceResponse instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceResponse=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.MoveInstanceResponse} MoveInstanceResponse instance + */ + MoveInstanceResponse.create = function create(properties) { + return new MoveInstanceResponse(properties); + }; + + /** + * Encodes the specified MoveInstanceResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceResponse} message MoveInstanceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveInstanceResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified MoveInstanceResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceResponse} message MoveInstanceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveInstanceResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MoveInstanceResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.MoveInstanceResponse} MoveInstanceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveInstanceResponse.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.spanner.admin.instance.v1.MoveInstanceResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MoveInstanceResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.MoveInstanceResponse} MoveInstanceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveInstanceResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MoveInstanceResponse message. + * @function verify + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MoveInstanceResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a MoveInstanceResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.MoveInstanceResponse} MoveInstanceResponse + */ + MoveInstanceResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.MoveInstanceResponse) + return object; + return new $root.google.spanner.admin.instance.v1.MoveInstanceResponse(); + }; + + /** + * Creates a plain object from a MoveInstanceResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {google.spanner.admin.instance.v1.MoveInstanceResponse} message MoveInstanceResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MoveInstanceResponse.toObject = function toObject() { + return {}; + }; + + /** + * Converts this MoveInstanceResponse to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @instance + * @returns {Object.} JSON object + */ + MoveInstanceResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MoveInstanceResponse + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.MoveInstanceResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MoveInstanceResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.MoveInstanceResponse"; + }; + + return MoveInstanceResponse; + })(); + + v1.MoveInstanceMetadata = (function() { + + /** + * Properties of a MoveInstanceMetadata. + * @memberof google.spanner.admin.instance.v1 + * @interface IMoveInstanceMetadata + * @property {string|null} [targetConfig] MoveInstanceMetadata targetConfig + * @property {google.spanner.admin.instance.v1.IOperationProgress|null} [progress] MoveInstanceMetadata progress + * @property {google.protobuf.ITimestamp|null} [cancelTime] MoveInstanceMetadata cancelTime + */ + + /** + * Constructs a new MoveInstanceMetadata. + * @memberof google.spanner.admin.instance.v1 + * @classdesc Represents a MoveInstanceMetadata. + * @implements IMoveInstanceMetadata + * @constructor + * @param {google.spanner.admin.instance.v1.IMoveInstanceMetadata=} [properties] Properties to set + */ + function MoveInstanceMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MoveInstanceMetadata targetConfig. + * @member {string} targetConfig + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @instance + */ + MoveInstanceMetadata.prototype.targetConfig = ""; + + /** + * MoveInstanceMetadata progress. + * @member {google.spanner.admin.instance.v1.IOperationProgress|null|undefined} progress + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @instance + */ + MoveInstanceMetadata.prototype.progress = null; + + /** + * MoveInstanceMetadata cancelTime. + * @member {google.protobuf.ITimestamp|null|undefined} cancelTime + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @instance + */ + MoveInstanceMetadata.prototype.cancelTime = null; + + /** + * Creates a new MoveInstanceMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceMetadata=} [properties] Properties to set + * @returns {google.spanner.admin.instance.v1.MoveInstanceMetadata} MoveInstanceMetadata instance + */ + MoveInstanceMetadata.create = function create(properties) { + return new MoveInstanceMetadata(properties); + }; + + /** + * Encodes the specified MoveInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceMetadata} message MoveInstanceMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveInstanceMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.targetConfig != null && Object.hasOwnProperty.call(message, "targetConfig")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.targetConfig); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.spanner.admin.instance.v1.OperationProgress.encode(message.progress, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.cancelTime != null && Object.hasOwnProperty.call(message, "cancelTime")) + $root.google.protobuf.Timestamp.encode(message.cancelTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified MoveInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.MoveInstanceMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.IMoveInstanceMetadata} message MoveInstanceMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveInstanceMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MoveInstanceMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.admin.instance.v1.MoveInstanceMetadata} MoveInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveInstanceMetadata.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.spanner.admin.instance.v1.MoveInstanceMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.targetConfig = reader.string(); + break; + } + case 2: { + message.progress = $root.google.spanner.admin.instance.v1.OperationProgress.decode(reader, reader.uint32()); + break; + } + case 3: { + message.cancelTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MoveInstanceMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.admin.instance.v1.MoveInstanceMetadata} MoveInstanceMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveInstanceMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MoveInstanceMetadata message. + * @function verify + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MoveInstanceMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.targetConfig != null && message.hasOwnProperty("targetConfig")) + if (!$util.isString(message.targetConfig)) + return "targetConfig: string expected"; + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.spanner.admin.instance.v1.OperationProgress.verify(message.progress); + if (error) + return "progress." + error; + } + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.cancelTime); + if (error) + return "cancelTime." + error; + } + return null; + }; + + /** + * Creates a MoveInstanceMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.admin.instance.v1.MoveInstanceMetadata} MoveInstanceMetadata + */ + MoveInstanceMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.admin.instance.v1.MoveInstanceMetadata) + return object; + var message = new $root.google.spanner.admin.instance.v1.MoveInstanceMetadata(); + if (object.targetConfig != null) + message.targetConfig = String(object.targetConfig); + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.spanner.admin.instance.v1.MoveInstanceMetadata.progress: object expected"); + message.progress = $root.google.spanner.admin.instance.v1.OperationProgress.fromObject(object.progress); + } + if (object.cancelTime != null) { + if (typeof object.cancelTime !== "object") + throw TypeError(".google.spanner.admin.instance.v1.MoveInstanceMetadata.cancelTime: object expected"); + message.cancelTime = $root.google.protobuf.Timestamp.fromObject(object.cancelTime); + } + return message; + }; + + /** + * Creates a plain object from a MoveInstanceMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {google.spanner.admin.instance.v1.MoveInstanceMetadata} message MoveInstanceMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MoveInstanceMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.targetConfig = ""; + object.progress = null; + object.cancelTime = null; + } + if (message.targetConfig != null && message.hasOwnProperty("targetConfig")) + object.targetConfig = message.targetConfig; + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.spanner.admin.instance.v1.OperationProgress.toObject(message.progress, options); + if (message.cancelTime != null && message.hasOwnProperty("cancelTime")) + object.cancelTime = $root.google.protobuf.Timestamp.toObject(message.cancelTime, options); + return object; + }; + + /** + * Converts this MoveInstanceMetadata to JSON. + * @function toJSON + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @instance + * @returns {Object.} JSON object + */ + MoveInstanceMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MoveInstanceMetadata + * @function getTypeUrl + * @memberof google.spanner.admin.instance.v1.MoveInstanceMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MoveInstanceMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.admin.instance.v1.MoveInstanceMetadata"; + }; + + return MoveInstanceMetadata; + })(); + + return v1; + })(); + + return instance; + })(); + + return admin; + })(); + + spanner.executor = (function() { + + /** + * Namespace executor. + * @memberof google.spanner + * @namespace + */ + var executor = {}; + + executor.v1 = (function() { + + /** + * Namespace v1. + * @memberof google.spanner.executor + * @namespace + */ + var v1 = {}; + + v1.SpannerExecutorProxy = (function() { + + /** + * Constructs a new SpannerExecutorProxy service. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a SpannerExecutorProxy + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function SpannerExecutorProxy(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (SpannerExecutorProxy.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = SpannerExecutorProxy; + + /** + * Creates new SpannerExecutorProxy service using the specified rpc implementation. + * @function create + * @memberof google.spanner.executor.v1.SpannerExecutorProxy + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {SpannerExecutorProxy} RPC service. Useful where requests and/or responses are streamed. + */ + SpannerExecutorProxy.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.spanner.executor.v1.SpannerExecutorProxy|executeActionAsync}. + * @memberof google.spanner.executor.v1.SpannerExecutorProxy + * @typedef ExecuteActionAsyncCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.executor.v1.SpannerAsyncActionResponse} [response] SpannerAsyncActionResponse + */ + + /** + * Calls ExecuteActionAsync. + * @function executeActionAsync + * @memberof google.spanner.executor.v1.SpannerExecutorProxy + * @instance + * @param {google.spanner.executor.v1.ISpannerAsyncActionRequest} request SpannerAsyncActionRequest message or plain object + * @param {google.spanner.executor.v1.SpannerExecutorProxy.ExecuteActionAsyncCallback} callback Node-style callback called with the error, if any, and SpannerAsyncActionResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(SpannerExecutorProxy.prototype.executeActionAsync = function executeActionAsync(request, callback) { + return this.rpcCall(executeActionAsync, $root.google.spanner.executor.v1.SpannerAsyncActionRequest, $root.google.spanner.executor.v1.SpannerAsyncActionResponse, request, callback); + }, "name", { value: "ExecuteActionAsync" }); + + /** + * Calls ExecuteActionAsync. + * @function executeActionAsync + * @memberof google.spanner.executor.v1.SpannerExecutorProxy + * @instance + * @param {google.spanner.executor.v1.ISpannerAsyncActionRequest} request SpannerAsyncActionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return SpannerExecutorProxy; + })(); + + v1.SpannerAsyncActionRequest = (function() { + + /** + * Properties of a SpannerAsyncActionRequest. + * @memberof google.spanner.executor.v1 + * @interface ISpannerAsyncActionRequest + * @property {number|null} [actionId] SpannerAsyncActionRequest actionId + * @property {google.spanner.executor.v1.ISpannerAction|null} [action] SpannerAsyncActionRequest action + */ + + /** + * Constructs a new SpannerAsyncActionRequest. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a SpannerAsyncActionRequest. + * @implements ISpannerAsyncActionRequest + * @constructor + * @param {google.spanner.executor.v1.ISpannerAsyncActionRequest=} [properties] Properties to set + */ + function SpannerAsyncActionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SpannerAsyncActionRequest actionId. + * @member {number} actionId + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @instance + */ + SpannerAsyncActionRequest.prototype.actionId = 0; + + /** + * SpannerAsyncActionRequest action. + * @member {google.spanner.executor.v1.ISpannerAction|null|undefined} action + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @instance + */ + SpannerAsyncActionRequest.prototype.action = null; + + /** + * Creates a new SpannerAsyncActionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {google.spanner.executor.v1.ISpannerAsyncActionRequest=} [properties] Properties to set + * @returns {google.spanner.executor.v1.SpannerAsyncActionRequest} SpannerAsyncActionRequest instance + */ + SpannerAsyncActionRequest.create = function create(properties) { + return new SpannerAsyncActionRequest(properties); + }; + + /** + * Encodes the specified SpannerAsyncActionRequest message. Does not implicitly {@link google.spanner.executor.v1.SpannerAsyncActionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {google.spanner.executor.v1.ISpannerAsyncActionRequest} message SpannerAsyncActionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerAsyncActionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.actionId != null && Object.hasOwnProperty.call(message, "actionId")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.actionId); + if (message.action != null && Object.hasOwnProperty.call(message, "action")) + $root.google.spanner.executor.v1.SpannerAction.encode(message.action, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SpannerAsyncActionRequest message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerAsyncActionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {google.spanner.executor.v1.ISpannerAsyncActionRequest} message SpannerAsyncActionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerAsyncActionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SpannerAsyncActionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.SpannerAsyncActionRequest} SpannerAsyncActionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerAsyncActionRequest.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.spanner.executor.v1.SpannerAsyncActionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.actionId = reader.int32(); + break; + } + case 2: { + message.action = $root.google.spanner.executor.v1.SpannerAction.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SpannerAsyncActionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.SpannerAsyncActionRequest} SpannerAsyncActionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerAsyncActionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SpannerAsyncActionRequest message. + * @function verify + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SpannerAsyncActionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.actionId != null && message.hasOwnProperty("actionId")) + if (!$util.isInteger(message.actionId)) + return "actionId: integer expected"; + if (message.action != null && message.hasOwnProperty("action")) { + var error = $root.google.spanner.executor.v1.SpannerAction.verify(message.action); + if (error) + return "action." + error; + } + return null; + }; + + /** + * Creates a SpannerAsyncActionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.SpannerAsyncActionRequest} SpannerAsyncActionRequest + */ + SpannerAsyncActionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.SpannerAsyncActionRequest) + return object; + var message = new $root.google.spanner.executor.v1.SpannerAsyncActionRequest(); + if (object.actionId != null) + message.actionId = object.actionId | 0; + if (object.action != null) { + if (typeof object.action !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAsyncActionRequest.action: object expected"); + message.action = $root.google.spanner.executor.v1.SpannerAction.fromObject(object.action); + } + return message; + }; + + /** + * Creates a plain object from a SpannerAsyncActionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {google.spanner.executor.v1.SpannerAsyncActionRequest} message SpannerAsyncActionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SpannerAsyncActionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.actionId = 0; + object.action = null; + } + if (message.actionId != null && message.hasOwnProperty("actionId")) + object.actionId = message.actionId; + if (message.action != null && message.hasOwnProperty("action")) + object.action = $root.google.spanner.executor.v1.SpannerAction.toObject(message.action, options); + return object; + }; + + /** + * Converts this SpannerAsyncActionRequest to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @instance + * @returns {Object.} JSON object + */ + SpannerAsyncActionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SpannerAsyncActionRequest + * @function getTypeUrl + * @memberof google.spanner.executor.v1.SpannerAsyncActionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SpannerAsyncActionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.SpannerAsyncActionRequest"; + }; + + return SpannerAsyncActionRequest; + })(); + + v1.SpannerAsyncActionResponse = (function() { + + /** + * Properties of a SpannerAsyncActionResponse. + * @memberof google.spanner.executor.v1 + * @interface ISpannerAsyncActionResponse + * @property {number|null} [actionId] SpannerAsyncActionResponse actionId + * @property {google.spanner.executor.v1.ISpannerActionOutcome|null} [outcome] SpannerAsyncActionResponse outcome + */ + + /** + * Constructs a new SpannerAsyncActionResponse. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a SpannerAsyncActionResponse. + * @implements ISpannerAsyncActionResponse + * @constructor + * @param {google.spanner.executor.v1.ISpannerAsyncActionResponse=} [properties] Properties to set + */ + function SpannerAsyncActionResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SpannerAsyncActionResponse actionId. + * @member {number} actionId + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @instance + */ + SpannerAsyncActionResponse.prototype.actionId = 0; + + /** + * SpannerAsyncActionResponse outcome. + * @member {google.spanner.executor.v1.ISpannerActionOutcome|null|undefined} outcome + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @instance + */ + SpannerAsyncActionResponse.prototype.outcome = null; + + /** + * Creates a new SpannerAsyncActionResponse instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {google.spanner.executor.v1.ISpannerAsyncActionResponse=} [properties] Properties to set + * @returns {google.spanner.executor.v1.SpannerAsyncActionResponse} SpannerAsyncActionResponse instance + */ + SpannerAsyncActionResponse.create = function create(properties) { + return new SpannerAsyncActionResponse(properties); + }; + + /** + * Encodes the specified SpannerAsyncActionResponse message. Does not implicitly {@link google.spanner.executor.v1.SpannerAsyncActionResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {google.spanner.executor.v1.ISpannerAsyncActionResponse} message SpannerAsyncActionResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerAsyncActionResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.actionId != null && Object.hasOwnProperty.call(message, "actionId")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.actionId); + if (message.outcome != null && Object.hasOwnProperty.call(message, "outcome")) + $root.google.spanner.executor.v1.SpannerActionOutcome.encode(message.outcome, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SpannerAsyncActionResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerAsyncActionResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {google.spanner.executor.v1.ISpannerAsyncActionResponse} message SpannerAsyncActionResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerAsyncActionResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SpannerAsyncActionResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.SpannerAsyncActionResponse} SpannerAsyncActionResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerAsyncActionResponse.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.spanner.executor.v1.SpannerAsyncActionResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.actionId = reader.int32(); + break; + } + case 2: { + message.outcome = $root.google.spanner.executor.v1.SpannerActionOutcome.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SpannerAsyncActionResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.SpannerAsyncActionResponse} SpannerAsyncActionResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerAsyncActionResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SpannerAsyncActionResponse message. + * @function verify + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SpannerAsyncActionResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.actionId != null && message.hasOwnProperty("actionId")) + if (!$util.isInteger(message.actionId)) + return "actionId: integer expected"; + if (message.outcome != null && message.hasOwnProperty("outcome")) { + var error = $root.google.spanner.executor.v1.SpannerActionOutcome.verify(message.outcome); + if (error) + return "outcome." + error; + } + return null; + }; + + /** + * Creates a SpannerAsyncActionResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.SpannerAsyncActionResponse} SpannerAsyncActionResponse + */ + SpannerAsyncActionResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.SpannerAsyncActionResponse) + return object; + var message = new $root.google.spanner.executor.v1.SpannerAsyncActionResponse(); + if (object.actionId != null) + message.actionId = object.actionId | 0; + if (object.outcome != null) { + if (typeof object.outcome !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAsyncActionResponse.outcome: object expected"); + message.outcome = $root.google.spanner.executor.v1.SpannerActionOutcome.fromObject(object.outcome); + } + return message; + }; + + /** + * Creates a plain object from a SpannerAsyncActionResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {google.spanner.executor.v1.SpannerAsyncActionResponse} message SpannerAsyncActionResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SpannerAsyncActionResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.actionId = 0; + object.outcome = null; + } + if (message.actionId != null && message.hasOwnProperty("actionId")) + object.actionId = message.actionId; + if (message.outcome != null && message.hasOwnProperty("outcome")) + object.outcome = $root.google.spanner.executor.v1.SpannerActionOutcome.toObject(message.outcome, options); + return object; + }; + + /** + * Converts this SpannerAsyncActionResponse to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @instance + * @returns {Object.} JSON object + */ + SpannerAsyncActionResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SpannerAsyncActionResponse + * @function getTypeUrl + * @memberof google.spanner.executor.v1.SpannerAsyncActionResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SpannerAsyncActionResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.SpannerAsyncActionResponse"; + }; + + return SpannerAsyncActionResponse; + })(); + + v1.SpannerAction = (function() { + + /** + * Properties of a SpannerAction. + * @memberof google.spanner.executor.v1 + * @interface ISpannerAction + * @property {string|null} [databasePath] SpannerAction databasePath + * @property {google.spanner.executor.v1.ISpannerOptions|null} [spannerOptions] SpannerAction spannerOptions + * @property {google.spanner.executor.v1.IStartTransactionAction|null} [start] SpannerAction start + * @property {google.spanner.executor.v1.IFinishTransactionAction|null} [finish] SpannerAction finish + * @property {google.spanner.executor.v1.IReadAction|null} [read] SpannerAction read + * @property {google.spanner.executor.v1.IQueryAction|null} [query] SpannerAction query + * @property {google.spanner.executor.v1.IMutationAction|null} [mutation] SpannerAction mutation + * @property {google.spanner.executor.v1.IDmlAction|null} [dml] SpannerAction dml + * @property {google.spanner.executor.v1.IBatchDmlAction|null} [batchDml] SpannerAction batchDml + * @property {google.spanner.executor.v1.IWriteMutationsAction|null} [write] SpannerAction write + * @property {google.spanner.executor.v1.IPartitionedUpdateAction|null} [partitionedUpdate] SpannerAction partitionedUpdate + * @property {google.spanner.executor.v1.IAdminAction|null} [admin] SpannerAction admin + * @property {google.spanner.executor.v1.IStartBatchTransactionAction|null} [startBatchTxn] SpannerAction startBatchTxn + * @property {google.spanner.executor.v1.ICloseBatchTransactionAction|null} [closeBatchTxn] SpannerAction closeBatchTxn + * @property {google.spanner.executor.v1.IGenerateDbPartitionsForReadAction|null} [generateDbPartitionsRead] SpannerAction generateDbPartitionsRead + * @property {google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction|null} [generateDbPartitionsQuery] SpannerAction generateDbPartitionsQuery + * @property {google.spanner.executor.v1.IExecutePartitionAction|null} [executePartition] SpannerAction executePartition + * @property {google.spanner.executor.v1.IExecuteChangeStreamQuery|null} [executeChangeStreamQuery] SpannerAction executeChangeStreamQuery + * @property {google.spanner.executor.v1.IQueryCancellationAction|null} [queryCancellation] SpannerAction queryCancellation + * @property {google.spanner.executor.v1.IAdaptMessageAction|null} [adaptMessage] SpannerAction adaptMessage + */ + + /** + * Constructs a new SpannerAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a SpannerAction. + * @implements ISpannerAction + * @constructor + * @param {google.spanner.executor.v1.ISpannerAction=} [properties] Properties to set + */ + function SpannerAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SpannerAction databasePath. + * @member {string} databasePath + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.databasePath = ""; + + /** + * SpannerAction spannerOptions. + * @member {google.spanner.executor.v1.ISpannerOptions|null|undefined} spannerOptions + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.spannerOptions = null; + + /** + * SpannerAction start. + * @member {google.spanner.executor.v1.IStartTransactionAction|null|undefined} start + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.start = null; + + /** + * SpannerAction finish. + * @member {google.spanner.executor.v1.IFinishTransactionAction|null|undefined} finish + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.finish = null; + + /** + * SpannerAction read. + * @member {google.spanner.executor.v1.IReadAction|null|undefined} read + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.read = null; + + /** + * SpannerAction query. + * @member {google.spanner.executor.v1.IQueryAction|null|undefined} query + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.query = null; + + /** + * SpannerAction mutation. + * @member {google.spanner.executor.v1.IMutationAction|null|undefined} mutation + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.mutation = null; + + /** + * SpannerAction dml. + * @member {google.spanner.executor.v1.IDmlAction|null|undefined} dml + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.dml = null; + + /** + * SpannerAction batchDml. + * @member {google.spanner.executor.v1.IBatchDmlAction|null|undefined} batchDml + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.batchDml = null; + + /** + * SpannerAction write. + * @member {google.spanner.executor.v1.IWriteMutationsAction|null|undefined} write + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.write = null; + + /** + * SpannerAction partitionedUpdate. + * @member {google.spanner.executor.v1.IPartitionedUpdateAction|null|undefined} partitionedUpdate + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.partitionedUpdate = null; + + /** + * SpannerAction admin. + * @member {google.spanner.executor.v1.IAdminAction|null|undefined} admin + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.admin = null; + + /** + * SpannerAction startBatchTxn. + * @member {google.spanner.executor.v1.IStartBatchTransactionAction|null|undefined} startBatchTxn + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.startBatchTxn = null; + + /** + * SpannerAction closeBatchTxn. + * @member {google.spanner.executor.v1.ICloseBatchTransactionAction|null|undefined} closeBatchTxn + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.closeBatchTxn = null; + + /** + * SpannerAction generateDbPartitionsRead. + * @member {google.spanner.executor.v1.IGenerateDbPartitionsForReadAction|null|undefined} generateDbPartitionsRead + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.generateDbPartitionsRead = null; + + /** + * SpannerAction generateDbPartitionsQuery. + * @member {google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction|null|undefined} generateDbPartitionsQuery + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.generateDbPartitionsQuery = null; + + /** + * SpannerAction executePartition. + * @member {google.spanner.executor.v1.IExecutePartitionAction|null|undefined} executePartition + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.executePartition = null; + + /** + * SpannerAction executeChangeStreamQuery. + * @member {google.spanner.executor.v1.IExecuteChangeStreamQuery|null|undefined} executeChangeStreamQuery + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.executeChangeStreamQuery = null; + + /** + * SpannerAction queryCancellation. + * @member {google.spanner.executor.v1.IQueryCancellationAction|null|undefined} queryCancellation + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.queryCancellation = null; + + /** + * SpannerAction adaptMessage. + * @member {google.spanner.executor.v1.IAdaptMessageAction|null|undefined} adaptMessage + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + SpannerAction.prototype.adaptMessage = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * SpannerAction action. + * @member {"start"|"finish"|"read"|"query"|"mutation"|"dml"|"batchDml"|"write"|"partitionedUpdate"|"admin"|"startBatchTxn"|"closeBatchTxn"|"generateDbPartitionsRead"|"generateDbPartitionsQuery"|"executePartition"|"executeChangeStreamQuery"|"queryCancellation"|"adaptMessage"|undefined} action + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + */ + Object.defineProperty(SpannerAction.prototype, "action", { + get: $util.oneOfGetter($oneOfFields = ["start", "finish", "read", "query", "mutation", "dml", "batchDml", "write", "partitionedUpdate", "admin", "startBatchTxn", "closeBatchTxn", "generateDbPartitionsRead", "generateDbPartitionsQuery", "executePartition", "executeChangeStreamQuery", "queryCancellation", "adaptMessage"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new SpannerAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {google.spanner.executor.v1.ISpannerAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.SpannerAction} SpannerAction instance + */ + SpannerAction.create = function create(properties) { + return new SpannerAction(properties); + }; + + /** + * Encodes the specified SpannerAction message. Does not implicitly {@link google.spanner.executor.v1.SpannerAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {google.spanner.executor.v1.ISpannerAction} message SpannerAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.databasePath != null && Object.hasOwnProperty.call(message, "databasePath")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.databasePath); + if (message.spannerOptions != null && Object.hasOwnProperty.call(message, "spannerOptions")) + $root.google.spanner.executor.v1.SpannerOptions.encode(message.spannerOptions, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.start != null && Object.hasOwnProperty.call(message, "start")) + $root.google.spanner.executor.v1.StartTransactionAction.encode(message.start, writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); + if (message.finish != null && Object.hasOwnProperty.call(message, "finish")) + $root.google.spanner.executor.v1.FinishTransactionAction.encode(message.finish, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); + if (message.read != null && Object.hasOwnProperty.call(message, "read")) + $root.google.spanner.executor.v1.ReadAction.encode(message.read, writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); + if (message.query != null && Object.hasOwnProperty.call(message, "query")) + $root.google.spanner.executor.v1.QueryAction.encode(message.query, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.mutation != null && Object.hasOwnProperty.call(message, "mutation")) + $root.google.spanner.executor.v1.MutationAction.encode(message.mutation, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); + if (message.dml != null && Object.hasOwnProperty.call(message, "dml")) + $root.google.spanner.executor.v1.DmlAction.encode(message.dml, writer.uint32(/* id 23, wireType 2 =*/186).fork()).ldelim(); + if (message.batchDml != null && Object.hasOwnProperty.call(message, "batchDml")) + $root.google.spanner.executor.v1.BatchDmlAction.encode(message.batchDml, writer.uint32(/* id 24, wireType 2 =*/194).fork()).ldelim(); + if (message.write != null && Object.hasOwnProperty.call(message, "write")) + $root.google.spanner.executor.v1.WriteMutationsAction.encode(message.write, writer.uint32(/* id 25, wireType 2 =*/202).fork()).ldelim(); + if (message.partitionedUpdate != null && Object.hasOwnProperty.call(message, "partitionedUpdate")) + $root.google.spanner.executor.v1.PartitionedUpdateAction.encode(message.partitionedUpdate, writer.uint32(/* id 27, wireType 2 =*/218).fork()).ldelim(); + if (message.admin != null && Object.hasOwnProperty.call(message, "admin")) + $root.google.spanner.executor.v1.AdminAction.encode(message.admin, writer.uint32(/* id 30, wireType 2 =*/242).fork()).ldelim(); + if (message.startBatchTxn != null && Object.hasOwnProperty.call(message, "startBatchTxn")) + $root.google.spanner.executor.v1.StartBatchTransactionAction.encode(message.startBatchTxn, writer.uint32(/* id 40, wireType 2 =*/322).fork()).ldelim(); + if (message.closeBatchTxn != null && Object.hasOwnProperty.call(message, "closeBatchTxn")) + $root.google.spanner.executor.v1.CloseBatchTransactionAction.encode(message.closeBatchTxn, writer.uint32(/* id 41, wireType 2 =*/330).fork()).ldelim(); + if (message.generateDbPartitionsRead != null && Object.hasOwnProperty.call(message, "generateDbPartitionsRead")) + $root.google.spanner.executor.v1.GenerateDbPartitionsForReadAction.encode(message.generateDbPartitionsRead, writer.uint32(/* id 42, wireType 2 =*/338).fork()).ldelim(); + if (message.generateDbPartitionsQuery != null && Object.hasOwnProperty.call(message, "generateDbPartitionsQuery")) + $root.google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.encode(message.generateDbPartitionsQuery, writer.uint32(/* id 43, wireType 2 =*/346).fork()).ldelim(); + if (message.executePartition != null && Object.hasOwnProperty.call(message, "executePartition")) + $root.google.spanner.executor.v1.ExecutePartitionAction.encode(message.executePartition, writer.uint32(/* id 44, wireType 2 =*/354).fork()).ldelim(); + if (message.executeChangeStreamQuery != null && Object.hasOwnProperty.call(message, "executeChangeStreamQuery")) + $root.google.spanner.executor.v1.ExecuteChangeStreamQuery.encode(message.executeChangeStreamQuery, writer.uint32(/* id 50, wireType 2 =*/402).fork()).ldelim(); + if (message.queryCancellation != null && Object.hasOwnProperty.call(message, "queryCancellation")) + $root.google.spanner.executor.v1.QueryCancellationAction.encode(message.queryCancellation, writer.uint32(/* id 51, wireType 2 =*/410).fork()).ldelim(); + if (message.adaptMessage != null && Object.hasOwnProperty.call(message, "adaptMessage")) + $root.google.spanner.executor.v1.AdaptMessageAction.encode(message.adaptMessage, writer.uint32(/* id 52, wireType 2 =*/418).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SpannerAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {google.spanner.executor.v1.ISpannerAction} message SpannerAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SpannerAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.SpannerAction} SpannerAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerAction.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.spanner.executor.v1.SpannerAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.databasePath = reader.string(); + break; + } + case 2: { + message.spannerOptions = $root.google.spanner.executor.v1.SpannerOptions.decode(reader, reader.uint32()); + break; + } + case 10: { + message.start = $root.google.spanner.executor.v1.StartTransactionAction.decode(reader, reader.uint32()); + break; + } + case 11: { + message.finish = $root.google.spanner.executor.v1.FinishTransactionAction.decode(reader, reader.uint32()); + break; + } + case 20: { + message.read = $root.google.spanner.executor.v1.ReadAction.decode(reader, reader.uint32()); + break; + } + case 21: { + message.query = $root.google.spanner.executor.v1.QueryAction.decode(reader, reader.uint32()); + break; + } + case 22: { + message.mutation = $root.google.spanner.executor.v1.MutationAction.decode(reader, reader.uint32()); + break; + } + case 23: { + message.dml = $root.google.spanner.executor.v1.DmlAction.decode(reader, reader.uint32()); + break; + } + case 24: { + message.batchDml = $root.google.spanner.executor.v1.BatchDmlAction.decode(reader, reader.uint32()); + break; + } + case 25: { + message.write = $root.google.spanner.executor.v1.WriteMutationsAction.decode(reader, reader.uint32()); + break; + } + case 27: { + message.partitionedUpdate = $root.google.spanner.executor.v1.PartitionedUpdateAction.decode(reader, reader.uint32()); + break; + } + case 30: { + message.admin = $root.google.spanner.executor.v1.AdminAction.decode(reader, reader.uint32()); + break; + } + case 40: { + message.startBatchTxn = $root.google.spanner.executor.v1.StartBatchTransactionAction.decode(reader, reader.uint32()); + break; + } + case 41: { + message.closeBatchTxn = $root.google.spanner.executor.v1.CloseBatchTransactionAction.decode(reader, reader.uint32()); + break; + } + case 42: { + message.generateDbPartitionsRead = $root.google.spanner.executor.v1.GenerateDbPartitionsForReadAction.decode(reader, reader.uint32()); + break; + } + case 43: { + message.generateDbPartitionsQuery = $root.google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.decode(reader, reader.uint32()); + break; + } + case 44: { + message.executePartition = $root.google.spanner.executor.v1.ExecutePartitionAction.decode(reader, reader.uint32()); + break; + } + case 50: { + message.executeChangeStreamQuery = $root.google.spanner.executor.v1.ExecuteChangeStreamQuery.decode(reader, reader.uint32()); + break; + } + case 51: { + message.queryCancellation = $root.google.spanner.executor.v1.QueryCancellationAction.decode(reader, reader.uint32()); + break; + } + case 52: { + message.adaptMessage = $root.google.spanner.executor.v1.AdaptMessageAction.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SpannerAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.SpannerAction} SpannerAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SpannerAction message. + * @function verify + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SpannerAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.databasePath != null && message.hasOwnProperty("databasePath")) + if (!$util.isString(message.databasePath)) + return "databasePath: string expected"; + if (message.spannerOptions != null && message.hasOwnProperty("spannerOptions")) { + var error = $root.google.spanner.executor.v1.SpannerOptions.verify(message.spannerOptions); + if (error) + return "spannerOptions." + error; + } + if (message.start != null && message.hasOwnProperty("start")) { + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.StartTransactionAction.verify(message.start); + if (error) + return "start." + error; + } + } + if (message.finish != null && message.hasOwnProperty("finish")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.FinishTransactionAction.verify(message.finish); + if (error) + return "finish." + error; + } + } + if (message.read != null && message.hasOwnProperty("read")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ReadAction.verify(message.read); + if (error) + return "read." + error; + } + } + if (message.query != null && message.hasOwnProperty("query")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.QueryAction.verify(message.query); + if (error) + return "query." + error; + } + } + if (message.mutation != null && message.hasOwnProperty("mutation")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.MutationAction.verify(message.mutation); + if (error) + return "mutation." + error; + } + } + if (message.dml != null && message.hasOwnProperty("dml")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.DmlAction.verify(message.dml); + if (error) + return "dml." + error; + } + } + if (message.batchDml != null && message.hasOwnProperty("batchDml")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.BatchDmlAction.verify(message.batchDml); + if (error) + return "batchDml." + error; + } + } + if (message.write != null && message.hasOwnProperty("write")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.WriteMutationsAction.verify(message.write); + if (error) + return "write." + error; + } + } + if (message.partitionedUpdate != null && message.hasOwnProperty("partitionedUpdate")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.PartitionedUpdateAction.verify(message.partitionedUpdate); + if (error) + return "partitionedUpdate." + error; + } + } + if (message.admin != null && message.hasOwnProperty("admin")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.AdminAction.verify(message.admin); + if (error) + return "admin." + error; + } + } + if (message.startBatchTxn != null && message.hasOwnProperty("startBatchTxn")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.StartBatchTransactionAction.verify(message.startBatchTxn); + if (error) + return "startBatchTxn." + error; + } + } + if (message.closeBatchTxn != null && message.hasOwnProperty("closeBatchTxn")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.CloseBatchTransactionAction.verify(message.closeBatchTxn); + if (error) + return "closeBatchTxn." + error; + } + } + if (message.generateDbPartitionsRead != null && message.hasOwnProperty("generateDbPartitionsRead")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.GenerateDbPartitionsForReadAction.verify(message.generateDbPartitionsRead); + if (error) + return "generateDbPartitionsRead." + error; + } + } + if (message.generateDbPartitionsQuery != null && message.hasOwnProperty("generateDbPartitionsQuery")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.verify(message.generateDbPartitionsQuery); + if (error) + return "generateDbPartitionsQuery." + error; + } + } + if (message.executePartition != null && message.hasOwnProperty("executePartition")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ExecutePartitionAction.verify(message.executePartition); + if (error) + return "executePartition." + error; + } + } + if (message.executeChangeStreamQuery != null && message.hasOwnProperty("executeChangeStreamQuery")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ExecuteChangeStreamQuery.verify(message.executeChangeStreamQuery); + if (error) + return "executeChangeStreamQuery." + error; + } + } + if (message.queryCancellation != null && message.hasOwnProperty("queryCancellation")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.QueryCancellationAction.verify(message.queryCancellation); + if (error) + return "queryCancellation." + error; + } + } + if (message.adaptMessage != null && message.hasOwnProperty("adaptMessage")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.AdaptMessageAction.verify(message.adaptMessage); + if (error) + return "adaptMessage." + error; + } + } + return null; + }; + + /** + * Creates a SpannerAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.SpannerAction} SpannerAction + */ + SpannerAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.SpannerAction) + return object; + var message = new $root.google.spanner.executor.v1.SpannerAction(); + if (object.databasePath != null) + message.databasePath = String(object.databasePath); + if (object.spannerOptions != null) { + if (typeof object.spannerOptions !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.spannerOptions: object expected"); + message.spannerOptions = $root.google.spanner.executor.v1.SpannerOptions.fromObject(object.spannerOptions); + } + if (object.start != null) { + if (typeof object.start !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.start: object expected"); + message.start = $root.google.spanner.executor.v1.StartTransactionAction.fromObject(object.start); + } + if (object.finish != null) { + if (typeof object.finish !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.finish: object expected"); + message.finish = $root.google.spanner.executor.v1.FinishTransactionAction.fromObject(object.finish); + } + if (object.read != null) { + if (typeof object.read !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.read: object expected"); + message.read = $root.google.spanner.executor.v1.ReadAction.fromObject(object.read); + } + if (object.query != null) { + if (typeof object.query !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.query: object expected"); + message.query = $root.google.spanner.executor.v1.QueryAction.fromObject(object.query); + } + if (object.mutation != null) { + if (typeof object.mutation !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.mutation: object expected"); + message.mutation = $root.google.spanner.executor.v1.MutationAction.fromObject(object.mutation); + } + if (object.dml != null) { + if (typeof object.dml !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.dml: object expected"); + message.dml = $root.google.spanner.executor.v1.DmlAction.fromObject(object.dml); + } + if (object.batchDml != null) { + if (typeof object.batchDml !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.batchDml: object expected"); + message.batchDml = $root.google.spanner.executor.v1.BatchDmlAction.fromObject(object.batchDml); + } + if (object.write != null) { + if (typeof object.write !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.write: object expected"); + message.write = $root.google.spanner.executor.v1.WriteMutationsAction.fromObject(object.write); + } + if (object.partitionedUpdate != null) { + if (typeof object.partitionedUpdate !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.partitionedUpdate: object expected"); + message.partitionedUpdate = $root.google.spanner.executor.v1.PartitionedUpdateAction.fromObject(object.partitionedUpdate); + } + if (object.admin != null) { + if (typeof object.admin !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.admin: object expected"); + message.admin = $root.google.spanner.executor.v1.AdminAction.fromObject(object.admin); + } + if (object.startBatchTxn != null) { + if (typeof object.startBatchTxn !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.startBatchTxn: object expected"); + message.startBatchTxn = $root.google.spanner.executor.v1.StartBatchTransactionAction.fromObject(object.startBatchTxn); + } + if (object.closeBatchTxn != null) { + if (typeof object.closeBatchTxn !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.closeBatchTxn: object expected"); + message.closeBatchTxn = $root.google.spanner.executor.v1.CloseBatchTransactionAction.fromObject(object.closeBatchTxn); + } + if (object.generateDbPartitionsRead != null) { + if (typeof object.generateDbPartitionsRead !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.generateDbPartitionsRead: object expected"); + message.generateDbPartitionsRead = $root.google.spanner.executor.v1.GenerateDbPartitionsForReadAction.fromObject(object.generateDbPartitionsRead); + } + if (object.generateDbPartitionsQuery != null) { + if (typeof object.generateDbPartitionsQuery !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.generateDbPartitionsQuery: object expected"); + message.generateDbPartitionsQuery = $root.google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.fromObject(object.generateDbPartitionsQuery); + } + if (object.executePartition != null) { + if (typeof object.executePartition !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.executePartition: object expected"); + message.executePartition = $root.google.spanner.executor.v1.ExecutePartitionAction.fromObject(object.executePartition); + } + if (object.executeChangeStreamQuery != null) { + if (typeof object.executeChangeStreamQuery !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.executeChangeStreamQuery: object expected"); + message.executeChangeStreamQuery = $root.google.spanner.executor.v1.ExecuteChangeStreamQuery.fromObject(object.executeChangeStreamQuery); + } + if (object.queryCancellation != null) { + if (typeof object.queryCancellation !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.queryCancellation: object expected"); + message.queryCancellation = $root.google.spanner.executor.v1.QueryCancellationAction.fromObject(object.queryCancellation); + } + if (object.adaptMessage != null) { + if (typeof object.adaptMessage !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerAction.adaptMessage: object expected"); + message.adaptMessage = $root.google.spanner.executor.v1.AdaptMessageAction.fromObject(object.adaptMessage); + } + return message; + }; + + /** + * Creates a plain object from a SpannerAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {google.spanner.executor.v1.SpannerAction} message SpannerAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SpannerAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.databasePath = ""; + object.spannerOptions = null; + } + if (message.databasePath != null && message.hasOwnProperty("databasePath")) + object.databasePath = message.databasePath; + if (message.spannerOptions != null && message.hasOwnProperty("spannerOptions")) + object.spannerOptions = $root.google.spanner.executor.v1.SpannerOptions.toObject(message.spannerOptions, options); + if (message.start != null && message.hasOwnProperty("start")) { + object.start = $root.google.spanner.executor.v1.StartTransactionAction.toObject(message.start, options); + if (options.oneofs) + object.action = "start"; + } + if (message.finish != null && message.hasOwnProperty("finish")) { + object.finish = $root.google.spanner.executor.v1.FinishTransactionAction.toObject(message.finish, options); + if (options.oneofs) + object.action = "finish"; + } + if (message.read != null && message.hasOwnProperty("read")) { + object.read = $root.google.spanner.executor.v1.ReadAction.toObject(message.read, options); + if (options.oneofs) + object.action = "read"; + } + if (message.query != null && message.hasOwnProperty("query")) { + object.query = $root.google.spanner.executor.v1.QueryAction.toObject(message.query, options); + if (options.oneofs) + object.action = "query"; + } + if (message.mutation != null && message.hasOwnProperty("mutation")) { + object.mutation = $root.google.spanner.executor.v1.MutationAction.toObject(message.mutation, options); + if (options.oneofs) + object.action = "mutation"; + } + if (message.dml != null && message.hasOwnProperty("dml")) { + object.dml = $root.google.spanner.executor.v1.DmlAction.toObject(message.dml, options); + if (options.oneofs) + object.action = "dml"; + } + if (message.batchDml != null && message.hasOwnProperty("batchDml")) { + object.batchDml = $root.google.spanner.executor.v1.BatchDmlAction.toObject(message.batchDml, options); + if (options.oneofs) + object.action = "batchDml"; + } + if (message.write != null && message.hasOwnProperty("write")) { + object.write = $root.google.spanner.executor.v1.WriteMutationsAction.toObject(message.write, options); + if (options.oneofs) + object.action = "write"; + } + if (message.partitionedUpdate != null && message.hasOwnProperty("partitionedUpdate")) { + object.partitionedUpdate = $root.google.spanner.executor.v1.PartitionedUpdateAction.toObject(message.partitionedUpdate, options); + if (options.oneofs) + object.action = "partitionedUpdate"; + } + if (message.admin != null && message.hasOwnProperty("admin")) { + object.admin = $root.google.spanner.executor.v1.AdminAction.toObject(message.admin, options); + if (options.oneofs) + object.action = "admin"; + } + if (message.startBatchTxn != null && message.hasOwnProperty("startBatchTxn")) { + object.startBatchTxn = $root.google.spanner.executor.v1.StartBatchTransactionAction.toObject(message.startBatchTxn, options); + if (options.oneofs) + object.action = "startBatchTxn"; + } + if (message.closeBatchTxn != null && message.hasOwnProperty("closeBatchTxn")) { + object.closeBatchTxn = $root.google.spanner.executor.v1.CloseBatchTransactionAction.toObject(message.closeBatchTxn, options); + if (options.oneofs) + object.action = "closeBatchTxn"; + } + if (message.generateDbPartitionsRead != null && message.hasOwnProperty("generateDbPartitionsRead")) { + object.generateDbPartitionsRead = $root.google.spanner.executor.v1.GenerateDbPartitionsForReadAction.toObject(message.generateDbPartitionsRead, options); + if (options.oneofs) + object.action = "generateDbPartitionsRead"; + } + if (message.generateDbPartitionsQuery != null && message.hasOwnProperty("generateDbPartitionsQuery")) { + object.generateDbPartitionsQuery = $root.google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.toObject(message.generateDbPartitionsQuery, options); + if (options.oneofs) + object.action = "generateDbPartitionsQuery"; + } + if (message.executePartition != null && message.hasOwnProperty("executePartition")) { + object.executePartition = $root.google.spanner.executor.v1.ExecutePartitionAction.toObject(message.executePartition, options); + if (options.oneofs) + object.action = "executePartition"; + } + if (message.executeChangeStreamQuery != null && message.hasOwnProperty("executeChangeStreamQuery")) { + object.executeChangeStreamQuery = $root.google.spanner.executor.v1.ExecuteChangeStreamQuery.toObject(message.executeChangeStreamQuery, options); + if (options.oneofs) + object.action = "executeChangeStreamQuery"; + } + if (message.queryCancellation != null && message.hasOwnProperty("queryCancellation")) { + object.queryCancellation = $root.google.spanner.executor.v1.QueryCancellationAction.toObject(message.queryCancellation, options); + if (options.oneofs) + object.action = "queryCancellation"; + } + if (message.adaptMessage != null && message.hasOwnProperty("adaptMessage")) { + object.adaptMessage = $root.google.spanner.executor.v1.AdaptMessageAction.toObject(message.adaptMessage, options); + if (options.oneofs) + object.action = "adaptMessage"; + } + return object; + }; + + /** + * Converts this SpannerAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.SpannerAction + * @instance + * @returns {Object.} JSON object + */ + SpannerAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SpannerAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.SpannerAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SpannerAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.SpannerAction"; + }; + + return SpannerAction; + })(); + + v1.ReadAction = (function() { + + /** + * Properties of a ReadAction. + * @memberof google.spanner.executor.v1 + * @interface IReadAction + * @property {string|null} [table] ReadAction table + * @property {string|null} [index] ReadAction index + * @property {Array.|null} [column] ReadAction column + * @property {google.spanner.executor.v1.IKeySet|null} [keys] ReadAction keys + * @property {number|null} [limit] ReadAction limit + */ + + /** + * Constructs a new ReadAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ReadAction. + * @implements IReadAction + * @constructor + * @param {google.spanner.executor.v1.IReadAction=} [properties] Properties to set + */ + function ReadAction(properties) { + this.column = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadAction table. + * @member {string} table + * @memberof google.spanner.executor.v1.ReadAction + * @instance + */ + ReadAction.prototype.table = ""; + + /** + * ReadAction index. + * @member {string|null|undefined} index + * @memberof google.spanner.executor.v1.ReadAction + * @instance + */ + ReadAction.prototype.index = null; + + /** + * ReadAction column. + * @member {Array.} column + * @memberof google.spanner.executor.v1.ReadAction + * @instance + */ + ReadAction.prototype.column = $util.emptyArray; + + /** + * ReadAction keys. + * @member {google.spanner.executor.v1.IKeySet|null|undefined} keys + * @memberof google.spanner.executor.v1.ReadAction + * @instance + */ + ReadAction.prototype.keys = null; + + /** + * ReadAction limit. + * @member {number} limit + * @memberof google.spanner.executor.v1.ReadAction + * @instance + */ + ReadAction.prototype.limit = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReadAction.prototype, "_index", { + get: $util.oneOfGetter($oneOfFields = ["index"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReadAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {google.spanner.executor.v1.IReadAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ReadAction} ReadAction instance + */ + ReadAction.create = function create(properties) { + return new ReadAction(properties); + }; + + /** + * Encodes the specified ReadAction message. Does not implicitly {@link google.spanner.executor.v1.ReadAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {google.spanner.executor.v1.IReadAction} message ReadAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.table); + if (message.index != null && Object.hasOwnProperty.call(message, "index")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.index); + if (message.column != null && message.column.length) + for (var i = 0; i < message.column.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.column[i]); + if (message.keys != null && Object.hasOwnProperty.call(message, "keys")) + $root.google.spanner.executor.v1.KeySet.encode(message.keys, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.limit != null && Object.hasOwnProperty.call(message, "limit")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.limit); + return writer; + }; + + /** + * Encodes the specified ReadAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ReadAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {google.spanner.executor.v1.IReadAction} message ReadAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ReadAction} ReadAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadAction.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.spanner.executor.v1.ReadAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.table = reader.string(); + break; + } + case 2: { + message.index = reader.string(); + break; + } + case 3: { + if (!(message.column && message.column.length)) + message.column = []; + message.column.push(reader.string()); + break; + } + case 4: { + message.keys = $root.google.spanner.executor.v1.KeySet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.limit = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReadAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ReadAction} ReadAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadAction message. + * @function verify + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.index != null && message.hasOwnProperty("index")) { + properties._index = 1; + if (!$util.isString(message.index)) + return "index: string expected"; + } + if (message.column != null && message.hasOwnProperty("column")) { + if (!Array.isArray(message.column)) + return "column: array expected"; + for (var i = 0; i < message.column.length; ++i) + if (!$util.isString(message.column[i])) + return "column: string[] expected"; + } + if (message.keys != null && message.hasOwnProperty("keys")) { + var error = $root.google.spanner.executor.v1.KeySet.verify(message.keys); + if (error) + return "keys." + error; + } + if (message.limit != null && message.hasOwnProperty("limit")) + if (!$util.isInteger(message.limit)) + return "limit: integer expected"; + return null; + }; + + /** + * Creates a ReadAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ReadAction} ReadAction + */ + ReadAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ReadAction) + return object; + var message = new $root.google.spanner.executor.v1.ReadAction(); + if (object.table != null) + message.table = String(object.table); + if (object.index != null) + message.index = String(object.index); + if (object.column) { + if (!Array.isArray(object.column)) + throw TypeError(".google.spanner.executor.v1.ReadAction.column: array expected"); + message.column = []; + for (var i = 0; i < object.column.length; ++i) + message.column[i] = String(object.column[i]); + } + if (object.keys != null) { + if (typeof object.keys !== "object") + throw TypeError(".google.spanner.executor.v1.ReadAction.keys: object expected"); + message.keys = $root.google.spanner.executor.v1.KeySet.fromObject(object.keys); + } + if (object.limit != null) + message.limit = object.limit | 0; + return message; + }; + + /** + * Creates a plain object from a ReadAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {google.spanner.executor.v1.ReadAction} message ReadAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.column = []; + if (options.defaults) { + object.table = ""; + object.keys = null; + object.limit = 0; + } + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.index != null && message.hasOwnProperty("index")) { + object.index = message.index; + if (options.oneofs) + object._index = "index"; + } + if (message.column && message.column.length) { + object.column = []; + for (var j = 0; j < message.column.length; ++j) + object.column[j] = message.column[j]; + } + if (message.keys != null && message.hasOwnProperty("keys")) + object.keys = $root.google.spanner.executor.v1.KeySet.toObject(message.keys, options); + if (message.limit != null && message.hasOwnProperty("limit")) + object.limit = message.limit; + return object; + }; + + /** + * Converts this ReadAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ReadAction + * @instance + * @returns {Object.} JSON object + */ + ReadAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ReadAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ReadAction"; + }; + + return ReadAction; + })(); + + v1.QueryAction = (function() { + + /** + * Properties of a QueryAction. + * @memberof google.spanner.executor.v1 + * @interface IQueryAction + * @property {string|null} [sql] QueryAction sql + * @property {Array.|null} [params] QueryAction params + */ + + /** + * Constructs a new QueryAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a QueryAction. + * @implements IQueryAction + * @constructor + * @param {google.spanner.executor.v1.IQueryAction=} [properties] Properties to set + */ + function QueryAction(properties) { + this.params = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QueryAction sql. + * @member {string} sql + * @memberof google.spanner.executor.v1.QueryAction + * @instance + */ + QueryAction.prototype.sql = ""; + + /** + * QueryAction params. + * @member {Array.} params + * @memberof google.spanner.executor.v1.QueryAction + * @instance + */ + QueryAction.prototype.params = $util.emptyArray; + + /** + * Creates a new QueryAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {google.spanner.executor.v1.IQueryAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.QueryAction} QueryAction instance + */ + QueryAction.create = function create(properties) { + return new QueryAction(properties); + }; + + /** + * Encodes the specified QueryAction message. Does not implicitly {@link google.spanner.executor.v1.QueryAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {google.spanner.executor.v1.IQueryAction} message QueryAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.sql != null && Object.hasOwnProperty.call(message, "sql")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.sql); + if (message.params != null && message.params.length) + for (var i = 0; i < message.params.length; ++i) + $root.google.spanner.executor.v1.QueryAction.Parameter.encode(message.params[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified QueryAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.QueryAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {google.spanner.executor.v1.IQueryAction} message QueryAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a QueryAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.QueryAction} QueryAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryAction.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.spanner.executor.v1.QueryAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.sql = reader.string(); + break; + } + case 2: { + if (!(message.params && message.params.length)) + message.params = []; + message.params.push($root.google.spanner.executor.v1.QueryAction.Parameter.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a QueryAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.QueryAction} QueryAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a QueryAction message. + * @function verify + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + QueryAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.sql != null && message.hasOwnProperty("sql")) + if (!$util.isString(message.sql)) + return "sql: string expected"; + if (message.params != null && message.hasOwnProperty("params")) { + if (!Array.isArray(message.params)) + return "params: array expected"; + for (var i = 0; i < message.params.length; ++i) { + var error = $root.google.spanner.executor.v1.QueryAction.Parameter.verify(message.params[i]); + if (error) + return "params." + error; + } + } + return null; + }; + + /** + * Creates a QueryAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.QueryAction} QueryAction + */ + QueryAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.QueryAction) + return object; + var message = new $root.google.spanner.executor.v1.QueryAction(); + if (object.sql != null) + message.sql = String(object.sql); + if (object.params) { + if (!Array.isArray(object.params)) + throw TypeError(".google.spanner.executor.v1.QueryAction.params: array expected"); + message.params = []; + for (var i = 0; i < object.params.length; ++i) { + if (typeof object.params[i] !== "object") + throw TypeError(".google.spanner.executor.v1.QueryAction.params: object expected"); + message.params[i] = $root.google.spanner.executor.v1.QueryAction.Parameter.fromObject(object.params[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a QueryAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {google.spanner.executor.v1.QueryAction} message QueryAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.params = []; + if (options.defaults) + object.sql = ""; + if (message.sql != null && message.hasOwnProperty("sql")) + object.sql = message.sql; + if (message.params && message.params.length) { + object.params = []; + for (var j = 0; j < message.params.length; ++j) + object.params[j] = $root.google.spanner.executor.v1.QueryAction.Parameter.toObject(message.params[j], options); + } + return object; + }; + + /** + * Converts this QueryAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.QueryAction + * @instance + * @returns {Object.} JSON object + */ + QueryAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QueryAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.QueryAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.QueryAction"; + }; + + QueryAction.Parameter = (function() { + + /** + * Properties of a Parameter. + * @memberof google.spanner.executor.v1.QueryAction + * @interface IParameter + * @property {string|null} [name] Parameter name + * @property {google.spanner.v1.IType|null} [type] Parameter type + * @property {google.spanner.executor.v1.IValue|null} [value] Parameter value + */ + + /** + * Constructs a new Parameter. + * @memberof google.spanner.executor.v1.QueryAction + * @classdesc Represents a Parameter. + * @implements IParameter + * @constructor + * @param {google.spanner.executor.v1.QueryAction.IParameter=} [properties] Properties to set + */ + function Parameter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Parameter name. + * @member {string} name + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @instance + */ + Parameter.prototype.name = ""; + + /** + * Parameter type. + * @member {google.spanner.v1.IType|null|undefined} type + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @instance + */ + Parameter.prototype.type = null; + + /** + * Parameter value. + * @member {google.spanner.executor.v1.IValue|null|undefined} value + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @instance + */ + Parameter.prototype.value = null; + + /** + * Creates a new Parameter instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {google.spanner.executor.v1.QueryAction.IParameter=} [properties] Properties to set + * @returns {google.spanner.executor.v1.QueryAction.Parameter} Parameter instance + */ + Parameter.create = function create(properties) { + return new Parameter(properties); + }; + + /** + * Encodes the specified Parameter message. Does not implicitly {@link google.spanner.executor.v1.QueryAction.Parameter.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {google.spanner.executor.v1.QueryAction.IParameter} message Parameter message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Parameter.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + $root.google.spanner.v1.Type.encode(message.type, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.value != null && Object.hasOwnProperty.call(message, "value")) + $root.google.spanner.executor.v1.Value.encode(message.value, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Parameter message, length delimited. Does not implicitly {@link google.spanner.executor.v1.QueryAction.Parameter.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {google.spanner.executor.v1.QueryAction.IParameter} message Parameter message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Parameter.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Parameter message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.QueryAction.Parameter} Parameter + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Parameter.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.spanner.executor.v1.QueryAction.Parameter(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.type = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + } + case 3: { + message.value = $root.google.spanner.executor.v1.Value.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Parameter message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.QueryAction.Parameter} Parameter + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Parameter.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Parameter message. + * @function verify + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Parameter.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.type != null && message.hasOwnProperty("type")) { + var error = $root.google.spanner.v1.Type.verify(message.type); + if (error) + return "type." + error; + } + if (message.value != null && message.hasOwnProperty("value")) { + var error = $root.google.spanner.executor.v1.Value.verify(message.value); + if (error) + return "value." + error; + } + return null; + }; + + /** + * Creates a Parameter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.QueryAction.Parameter} Parameter + */ + Parameter.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.QueryAction.Parameter) + return object; + var message = new $root.google.spanner.executor.v1.QueryAction.Parameter(); + if (object.name != null) + message.name = String(object.name); + if (object.type != null) { + if (typeof object.type !== "object") + throw TypeError(".google.spanner.executor.v1.QueryAction.Parameter.type: object expected"); + message.type = $root.google.spanner.v1.Type.fromObject(object.type); + } + if (object.value != null) { + if (typeof object.value !== "object") + throw TypeError(".google.spanner.executor.v1.QueryAction.Parameter.value: object expected"); + message.value = $root.google.spanner.executor.v1.Value.fromObject(object.value); + } + return message; + }; + + /** + * Creates a plain object from a Parameter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {google.spanner.executor.v1.QueryAction.Parameter} message Parameter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Parameter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.type = null; + object.value = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.type != null && message.hasOwnProperty("type")) + object.type = $root.google.spanner.v1.Type.toObject(message.type, options); + if (message.value != null && message.hasOwnProperty("value")) + object.value = $root.google.spanner.executor.v1.Value.toObject(message.value, options); + return object; + }; + + /** + * Converts this Parameter to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @instance + * @returns {Object.} JSON object + */ + Parameter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Parameter + * @function getTypeUrl + * @memberof google.spanner.executor.v1.QueryAction.Parameter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Parameter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.QueryAction.Parameter"; + }; + + return Parameter; + })(); + + return QueryAction; + })(); + + v1.DmlAction = (function() { + + /** + * Properties of a DmlAction. + * @memberof google.spanner.executor.v1 + * @interface IDmlAction + * @property {google.spanner.executor.v1.IQueryAction|null} [update] DmlAction update + * @property {boolean|null} [autocommitIfSupported] DmlAction autocommitIfSupported + * @property {boolean|null} [lastStatement] DmlAction lastStatement + */ + + /** + * Constructs a new DmlAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a DmlAction. + * @implements IDmlAction + * @constructor + * @param {google.spanner.executor.v1.IDmlAction=} [properties] Properties to set + */ + function DmlAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DmlAction update. + * @member {google.spanner.executor.v1.IQueryAction|null|undefined} update + * @memberof google.spanner.executor.v1.DmlAction + * @instance + */ + DmlAction.prototype.update = null; + + /** + * DmlAction autocommitIfSupported. + * @member {boolean|null|undefined} autocommitIfSupported + * @memberof google.spanner.executor.v1.DmlAction + * @instance + */ + DmlAction.prototype.autocommitIfSupported = null; + + /** + * DmlAction lastStatement. + * @member {boolean|null|undefined} lastStatement + * @memberof google.spanner.executor.v1.DmlAction + * @instance + */ + DmlAction.prototype.lastStatement = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(DmlAction.prototype, "_autocommitIfSupported", { + get: $util.oneOfGetter($oneOfFields = ["autocommitIfSupported"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(DmlAction.prototype, "_lastStatement", { + get: $util.oneOfGetter($oneOfFields = ["lastStatement"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new DmlAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {google.spanner.executor.v1.IDmlAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.DmlAction} DmlAction instance + */ + DmlAction.create = function create(properties) { + return new DmlAction(properties); + }; + + /** + * Encodes the specified DmlAction message. Does not implicitly {@link google.spanner.executor.v1.DmlAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {google.spanner.executor.v1.IDmlAction} message DmlAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DmlAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.update != null && Object.hasOwnProperty.call(message, "update")) + $root.google.spanner.executor.v1.QueryAction.encode(message.update, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.autocommitIfSupported != null && Object.hasOwnProperty.call(message, "autocommitIfSupported")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.autocommitIfSupported); + if (message.lastStatement != null && Object.hasOwnProperty.call(message, "lastStatement")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.lastStatement); + return writer; + }; + + /** + * Encodes the specified DmlAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DmlAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {google.spanner.executor.v1.IDmlAction} message DmlAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DmlAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DmlAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.DmlAction} DmlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DmlAction.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.spanner.executor.v1.DmlAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.update = $root.google.spanner.executor.v1.QueryAction.decode(reader, reader.uint32()); + break; + } + case 2: { + message.autocommitIfSupported = reader.bool(); + break; + } + case 3: { + message.lastStatement = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DmlAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.DmlAction} DmlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DmlAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DmlAction message. + * @function verify + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DmlAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.update != null && message.hasOwnProperty("update")) { + var error = $root.google.spanner.executor.v1.QueryAction.verify(message.update); + if (error) + return "update." + error; + } + if (message.autocommitIfSupported != null && message.hasOwnProperty("autocommitIfSupported")) { + properties._autocommitIfSupported = 1; + if (typeof message.autocommitIfSupported !== "boolean") + return "autocommitIfSupported: boolean expected"; + } + if (message.lastStatement != null && message.hasOwnProperty("lastStatement")) { + properties._lastStatement = 1; + if (typeof message.lastStatement !== "boolean") + return "lastStatement: boolean expected"; + } + return null; + }; + + /** + * Creates a DmlAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.DmlAction} DmlAction + */ + DmlAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.DmlAction) + return object; + var message = new $root.google.spanner.executor.v1.DmlAction(); + if (object.update != null) { + if (typeof object.update !== "object") + throw TypeError(".google.spanner.executor.v1.DmlAction.update: object expected"); + message.update = $root.google.spanner.executor.v1.QueryAction.fromObject(object.update); + } + if (object.autocommitIfSupported != null) + message.autocommitIfSupported = Boolean(object.autocommitIfSupported); + if (object.lastStatement != null) + message.lastStatement = Boolean(object.lastStatement); + return message; + }; + + /** + * Creates a plain object from a DmlAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {google.spanner.executor.v1.DmlAction} message DmlAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DmlAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.update = null; + if (message.update != null && message.hasOwnProperty("update")) + object.update = $root.google.spanner.executor.v1.QueryAction.toObject(message.update, options); + if (message.autocommitIfSupported != null && message.hasOwnProperty("autocommitIfSupported")) { + object.autocommitIfSupported = message.autocommitIfSupported; + if (options.oneofs) + object._autocommitIfSupported = "autocommitIfSupported"; + } + if (message.lastStatement != null && message.hasOwnProperty("lastStatement")) { + object.lastStatement = message.lastStatement; + if (options.oneofs) + object._lastStatement = "lastStatement"; + } + return object; + }; + + /** + * Converts this DmlAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.DmlAction + * @instance + * @returns {Object.} JSON object + */ + DmlAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DmlAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.DmlAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DmlAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.DmlAction"; + }; + + return DmlAction; + })(); + + v1.BatchDmlAction = (function() { + + /** + * Properties of a BatchDmlAction. + * @memberof google.spanner.executor.v1 + * @interface IBatchDmlAction + * @property {Array.|null} [updates] BatchDmlAction updates + * @property {boolean|null} [lastStatements] BatchDmlAction lastStatements + */ + + /** + * Constructs a new BatchDmlAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a BatchDmlAction. + * @implements IBatchDmlAction + * @constructor + * @param {google.spanner.executor.v1.IBatchDmlAction=} [properties] Properties to set + */ + function BatchDmlAction(properties) { + this.updates = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchDmlAction updates. + * @member {Array.} updates + * @memberof google.spanner.executor.v1.BatchDmlAction + * @instance + */ + BatchDmlAction.prototype.updates = $util.emptyArray; + + /** + * BatchDmlAction lastStatements. + * @member {boolean|null|undefined} lastStatements + * @memberof google.spanner.executor.v1.BatchDmlAction + * @instance + */ + BatchDmlAction.prototype.lastStatements = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(BatchDmlAction.prototype, "_lastStatements", { + get: $util.oneOfGetter($oneOfFields = ["lastStatements"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new BatchDmlAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {google.spanner.executor.v1.IBatchDmlAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.BatchDmlAction} BatchDmlAction instance + */ + BatchDmlAction.create = function create(properties) { + return new BatchDmlAction(properties); + }; + + /** + * Encodes the specified BatchDmlAction message. Does not implicitly {@link google.spanner.executor.v1.BatchDmlAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {google.spanner.executor.v1.IBatchDmlAction} message BatchDmlAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchDmlAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.updates != null && message.updates.length) + for (var i = 0; i < message.updates.length; ++i) + $root.google.spanner.executor.v1.QueryAction.encode(message.updates[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.lastStatements != null && Object.hasOwnProperty.call(message, "lastStatements")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.lastStatements); + return writer; + }; + + /** + * Encodes the specified BatchDmlAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.BatchDmlAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {google.spanner.executor.v1.IBatchDmlAction} message BatchDmlAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchDmlAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BatchDmlAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.BatchDmlAction} BatchDmlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchDmlAction.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.spanner.executor.v1.BatchDmlAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.updates && message.updates.length)) + message.updates = []; + message.updates.push($root.google.spanner.executor.v1.QueryAction.decode(reader, reader.uint32())); + break; + } + case 2: { + message.lastStatements = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BatchDmlAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.BatchDmlAction} BatchDmlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchDmlAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BatchDmlAction message. + * @function verify + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BatchDmlAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.updates != null && message.hasOwnProperty("updates")) { + if (!Array.isArray(message.updates)) + return "updates: array expected"; + for (var i = 0; i < message.updates.length; ++i) { + var error = $root.google.spanner.executor.v1.QueryAction.verify(message.updates[i]); + if (error) + return "updates." + error; + } + } + if (message.lastStatements != null && message.hasOwnProperty("lastStatements")) { + properties._lastStatements = 1; + if (typeof message.lastStatements !== "boolean") + return "lastStatements: boolean expected"; + } + return null; + }; + + /** + * Creates a BatchDmlAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.BatchDmlAction} BatchDmlAction + */ + BatchDmlAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.BatchDmlAction) + return object; + var message = new $root.google.spanner.executor.v1.BatchDmlAction(); + if (object.updates) { + if (!Array.isArray(object.updates)) + throw TypeError(".google.spanner.executor.v1.BatchDmlAction.updates: array expected"); + message.updates = []; + for (var i = 0; i < object.updates.length; ++i) { + if (typeof object.updates[i] !== "object") + throw TypeError(".google.spanner.executor.v1.BatchDmlAction.updates: object expected"); + message.updates[i] = $root.google.spanner.executor.v1.QueryAction.fromObject(object.updates[i]); + } + } + if (object.lastStatements != null) + message.lastStatements = Boolean(object.lastStatements); + return message; + }; + + /** + * Creates a plain object from a BatchDmlAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {google.spanner.executor.v1.BatchDmlAction} message BatchDmlAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchDmlAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.updates = []; + if (message.updates && message.updates.length) { + object.updates = []; + for (var j = 0; j < message.updates.length; ++j) + object.updates[j] = $root.google.spanner.executor.v1.QueryAction.toObject(message.updates[j], options); + } + if (message.lastStatements != null && message.hasOwnProperty("lastStatements")) { + object.lastStatements = message.lastStatements; + if (options.oneofs) + object._lastStatements = "lastStatements"; + } + return object; + }; + + /** + * Converts this BatchDmlAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.BatchDmlAction + * @instance + * @returns {Object.} JSON object + */ + BatchDmlAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchDmlAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.BatchDmlAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchDmlAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.BatchDmlAction"; + }; + + return BatchDmlAction; + })(); + + v1.Value = (function() { + + /** + * Properties of a Value. + * @memberof google.spanner.executor.v1 + * @interface IValue + * @property {boolean|null} [isNull] Value isNull + * @property {number|Long|null} [intValue] Value intValue + * @property {boolean|null} [boolValue] Value boolValue + * @property {number|null} [doubleValue] Value doubleValue + * @property {Uint8Array|null} [bytesValue] Value bytesValue + * @property {string|null} [stringValue] Value stringValue + * @property {google.spanner.executor.v1.IValueList|null} [structValue] Value structValue + * @property {google.protobuf.ITimestamp|null} [timestampValue] Value timestampValue + * @property {number|null} [dateDaysValue] Value dateDaysValue + * @property {boolean|null} [isCommitTimestamp] Value isCommitTimestamp + * @property {google.spanner.executor.v1.IValueList|null} [arrayValue] Value arrayValue + * @property {google.spanner.v1.IType|null} [arrayType] Value arrayType + */ + + /** + * Constructs a new Value. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a Value. + * @implements IValue + * @constructor + * @param {google.spanner.executor.v1.IValue=} [properties] Properties to set + */ + function Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Value isNull. + * @member {boolean|null|undefined} isNull + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.isNull = null; + + /** + * Value intValue. + * @member {number|Long|null|undefined} intValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.intValue = null; + + /** + * Value boolValue. + * @member {boolean|null|undefined} boolValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.boolValue = null; + + /** + * Value doubleValue. + * @member {number|null|undefined} doubleValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.doubleValue = null; + + /** + * Value bytesValue. + * @member {Uint8Array|null|undefined} bytesValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.bytesValue = null; + + /** + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.stringValue = null; + + /** + * Value structValue. + * @member {google.spanner.executor.v1.IValueList|null|undefined} structValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.structValue = null; + + /** + * Value timestampValue. + * @member {google.protobuf.ITimestamp|null|undefined} timestampValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.timestampValue = null; + + /** + * Value dateDaysValue. + * @member {number|null|undefined} dateDaysValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.dateDaysValue = null; + + /** + * Value isCommitTimestamp. + * @member {boolean|null|undefined} isCommitTimestamp + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.isCommitTimestamp = null; + + /** + * Value arrayValue. + * @member {google.spanner.executor.v1.IValueList|null|undefined} arrayValue + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.arrayValue = null; + + /** + * Value arrayType. + * @member {google.spanner.v1.IType|null|undefined} arrayType + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Value.prototype.arrayType = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Value valueType. + * @member {"isNull"|"intValue"|"boolValue"|"doubleValue"|"bytesValue"|"stringValue"|"structValue"|"timestampValue"|"dateDaysValue"|"isCommitTimestamp"|"arrayValue"|undefined} valueType + * @memberof google.spanner.executor.v1.Value + * @instance + */ + Object.defineProperty(Value.prototype, "valueType", { + get: $util.oneOfGetter($oneOfFields = ["isNull", "intValue", "boolValue", "doubleValue", "bytesValue", "stringValue", "structValue", "timestampValue", "dateDaysValue", "isCommitTimestamp", "arrayValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(Value.prototype, "_arrayType", { + get: $util.oneOfGetter($oneOfFields = ["arrayType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new Value instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.Value + * @static + * @param {google.spanner.executor.v1.IValue=} [properties] Properties to set + * @returns {google.spanner.executor.v1.Value} Value instance + */ + Value.create = function create(properties) { + return new Value(properties); + }; + + /** + * Encodes the specified Value message. Does not implicitly {@link google.spanner.executor.v1.Value.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.Value + * @static + * @param {google.spanner.executor.v1.IValue} message Value message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Value.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.isNull != null && Object.hasOwnProperty.call(message, "isNull")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.isNull); + if (message.intValue != null && Object.hasOwnProperty.call(message, "intValue")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.intValue); + if (message.boolValue != null && Object.hasOwnProperty.call(message, "boolValue")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.boolValue); + if (message.doubleValue != null && Object.hasOwnProperty.call(message, "doubleValue")) + writer.uint32(/* id 4, wireType 1 =*/33).double(message.doubleValue); + if (message.bytesValue != null && Object.hasOwnProperty.call(message, "bytesValue")) + writer.uint32(/* id 5, wireType 2 =*/42).bytes(message.bytesValue); + if (message.stringValue != null && Object.hasOwnProperty.call(message, "stringValue")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.stringValue); + if (message.structValue != null && Object.hasOwnProperty.call(message, "structValue")) + $root.google.spanner.executor.v1.ValueList.encode(message.structValue, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.timestampValue != null && Object.hasOwnProperty.call(message, "timestampValue")) + $root.google.protobuf.Timestamp.encode(message.timestampValue, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.dateDaysValue != null && Object.hasOwnProperty.call(message, "dateDaysValue")) + writer.uint32(/* id 9, wireType 0 =*/72).int32(message.dateDaysValue); + if (message.isCommitTimestamp != null && Object.hasOwnProperty.call(message, "isCommitTimestamp")) + writer.uint32(/* id 10, wireType 0 =*/80).bool(message.isCommitTimestamp); + if (message.arrayValue != null && Object.hasOwnProperty.call(message, "arrayValue")) + $root.google.spanner.executor.v1.ValueList.encode(message.arrayValue, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); + if (message.arrayType != null && Object.hasOwnProperty.call(message, "arrayType")) + $root.google.spanner.v1.Type.encode(message.arrayType, writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Value message, length delimited. Does not implicitly {@link google.spanner.executor.v1.Value.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.Value + * @static + * @param {google.spanner.executor.v1.IValue} message Value message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Value.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Value message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.Value + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.Value} Value + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Value.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.spanner.executor.v1.Value(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.isNull = reader.bool(); + break; + } + case 2: { + message.intValue = reader.int64(); + break; + } + case 3: { + message.boolValue = reader.bool(); + break; + } + case 4: { + message.doubleValue = reader.double(); + break; + } + case 5: { + message.bytesValue = reader.bytes(); + break; + } + case 6: { + message.stringValue = reader.string(); + break; + } + case 7: { + message.structValue = $root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32()); + break; + } + case 8: { + message.timestampValue = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 9: { + message.dateDaysValue = reader.int32(); + break; + } + case 10: { + message.isCommitTimestamp = reader.bool(); + break; + } + case 11: { + message.arrayValue = $root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32()); + break; + } + case 12: { + message.arrayType = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Value message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.Value + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.Value} Value + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Value.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Value message. + * @function verify + * @memberof google.spanner.executor.v1.Value + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Value.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.isNull != null && message.hasOwnProperty("isNull")) { + properties.valueType = 1; + if (typeof message.isNull !== "boolean") + return "isNull: boolean expected"; + } + if (message.intValue != null && message.hasOwnProperty("intValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + if (!$util.isInteger(message.intValue) && !(message.intValue && $util.isInteger(message.intValue.low) && $util.isInteger(message.intValue.high))) + return "intValue: integer|Long expected"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + if (typeof message.boolValue !== "boolean") + return "boolValue: boolean expected"; + } + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + if (typeof message.doubleValue !== "number") + return "doubleValue: number expected"; + } + if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + if (!(message.bytesValue && typeof message.bytesValue.length === "number" || $util.isString(message.bytesValue))) + return "bytesValue: buffer expected"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + if (!$util.isString(message.stringValue)) + return "stringValue: string expected"; + } + if (message.structValue != null && message.hasOwnProperty("structValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.structValue); + if (error) + return "structValue." + error; + } + } + if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + { + var error = $root.google.protobuf.Timestamp.verify(message.timestampValue); + if (error) + return "timestampValue." + error; + } + } + if (message.dateDaysValue != null && message.hasOwnProperty("dateDaysValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + if (!$util.isInteger(message.dateDaysValue)) + return "dateDaysValue: integer expected"; + } + if (message.isCommitTimestamp != null && message.hasOwnProperty("isCommitTimestamp")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + if (typeof message.isCommitTimestamp !== "boolean") + return "isCommitTimestamp: boolean expected"; + } + if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.arrayValue); + if (error) + return "arrayValue." + error; + } + } + if (message.arrayType != null && message.hasOwnProperty("arrayType")) { + properties._arrayType = 1; + { + var error = $root.google.spanner.v1.Type.verify(message.arrayType); + if (error) + return "arrayType." + error; + } + } + return null; + }; + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.Value + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.Value} Value + */ + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.Value) + return object; + var message = new $root.google.spanner.executor.v1.Value(); + if (object.isNull != null) + message.isNull = Boolean(object.isNull); + if (object.intValue != null) + if ($util.Long) + (message.intValue = $util.Long.fromValue(object.intValue)).unsigned = false; + else if (typeof object.intValue === "string") + message.intValue = parseInt(object.intValue, 10); + else if (typeof object.intValue === "number") + message.intValue = object.intValue; + else if (typeof object.intValue === "object") + message.intValue = new $util.LongBits(object.intValue.low >>> 0, object.intValue.high >>> 0).toNumber(); + if (object.boolValue != null) + message.boolValue = Boolean(object.boolValue); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.bytesValue != null) + if (typeof object.bytesValue === "string") + $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0); + else if (object.bytesValue.length >= 0) + message.bytesValue = object.bytesValue; + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.structValue != null) { + if (typeof object.structValue !== "object") + throw TypeError(".google.spanner.executor.v1.Value.structValue: object expected"); + message.structValue = $root.google.spanner.executor.v1.ValueList.fromObject(object.structValue); + } + if (object.timestampValue != null) { + if (typeof object.timestampValue !== "object") + throw TypeError(".google.spanner.executor.v1.Value.timestampValue: object expected"); + message.timestampValue = $root.google.protobuf.Timestamp.fromObject(object.timestampValue); + } + if (object.dateDaysValue != null) + message.dateDaysValue = object.dateDaysValue | 0; + if (object.isCommitTimestamp != null) + message.isCommitTimestamp = Boolean(object.isCommitTimestamp); + if (object.arrayValue != null) { + if (typeof object.arrayValue !== "object") + throw TypeError(".google.spanner.executor.v1.Value.arrayValue: object expected"); + message.arrayValue = $root.google.spanner.executor.v1.ValueList.fromObject(object.arrayValue); + } + if (object.arrayType != null) { + if (typeof object.arrayType !== "object") + throw TypeError(".google.spanner.executor.v1.Value.arrayType: object expected"); + message.arrayType = $root.google.spanner.v1.Type.fromObject(object.arrayType); + } + return message; + }; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.Value + * @static + * @param {google.spanner.executor.v1.Value} message Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.isNull != null && message.hasOwnProperty("isNull")) { + object.isNull = message.isNull; + if (options.oneofs) + object.valueType = "isNull"; + } + if (message.intValue != null && message.hasOwnProperty("intValue")) { + if (typeof message.intValue === "number") + object.intValue = options.longs === String ? String(message.intValue) : message.intValue; + else + object.intValue = options.longs === String ? $util.Long.prototype.toString.call(message.intValue) : options.longs === Number ? new $util.LongBits(message.intValue.low >>> 0, message.intValue.high >>> 0).toNumber() : message.intValue; + if (options.oneofs) + object.valueType = "intValue"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + object.boolValue = message.boolValue; + if (options.oneofs) + object.valueType = "boolValue"; + } + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (options.oneofs) + object.valueType = "doubleValue"; + } + if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { + object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue; + if (options.oneofs) + object.valueType = "bytesValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.valueType = "stringValue"; + } + if (message.structValue != null && message.hasOwnProperty("structValue")) { + object.structValue = $root.google.spanner.executor.v1.ValueList.toObject(message.structValue, options); + if (options.oneofs) + object.valueType = "structValue"; + } + if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) { + object.timestampValue = $root.google.protobuf.Timestamp.toObject(message.timestampValue, options); + if (options.oneofs) + object.valueType = "timestampValue"; + } + if (message.dateDaysValue != null && message.hasOwnProperty("dateDaysValue")) { + object.dateDaysValue = message.dateDaysValue; + if (options.oneofs) + object.valueType = "dateDaysValue"; + } + if (message.isCommitTimestamp != null && message.hasOwnProperty("isCommitTimestamp")) { + object.isCommitTimestamp = message.isCommitTimestamp; + if (options.oneofs) + object.valueType = "isCommitTimestamp"; + } + if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { + object.arrayValue = $root.google.spanner.executor.v1.ValueList.toObject(message.arrayValue, options); + if (options.oneofs) + object.valueType = "arrayValue"; + } + if (message.arrayType != null && message.hasOwnProperty("arrayType")) { + object.arrayType = $root.google.spanner.v1.Type.toObject(message.arrayType, options); + if (options.oneofs) + object._arrayType = "arrayType"; + } + return object; + }; + + /** + * Converts this Value to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.Value + * @instance + * @returns {Object.} JSON object + */ + Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Value + * @function getTypeUrl + * @memberof google.spanner.executor.v1.Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.Value"; + }; + + return Value; + })(); + + v1.KeyRange = (function() { + + /** + * Properties of a KeyRange. + * @memberof google.spanner.executor.v1 + * @interface IKeyRange + * @property {google.spanner.executor.v1.IValueList|null} [start] KeyRange start + * @property {google.spanner.executor.v1.IValueList|null} [limit] KeyRange limit + * @property {google.spanner.executor.v1.KeyRange.Type|null} [type] KeyRange type + */ + + /** + * Constructs a new KeyRange. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a KeyRange. + * @implements IKeyRange + * @constructor + * @param {google.spanner.executor.v1.IKeyRange=} [properties] Properties to set + */ + function KeyRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * KeyRange start. + * @member {google.spanner.executor.v1.IValueList|null|undefined} start + * @memberof google.spanner.executor.v1.KeyRange + * @instance + */ + KeyRange.prototype.start = null; + + /** + * KeyRange limit. + * @member {google.spanner.executor.v1.IValueList|null|undefined} limit + * @memberof google.spanner.executor.v1.KeyRange + * @instance + */ + KeyRange.prototype.limit = null; + + /** + * KeyRange type. + * @member {google.spanner.executor.v1.KeyRange.Type|null|undefined} type + * @memberof google.spanner.executor.v1.KeyRange + * @instance + */ + KeyRange.prototype.type = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(KeyRange.prototype, "_type", { + get: $util.oneOfGetter($oneOfFields = ["type"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new KeyRange instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {google.spanner.executor.v1.IKeyRange=} [properties] Properties to set + * @returns {google.spanner.executor.v1.KeyRange} KeyRange instance + */ + KeyRange.create = function create(properties) { + return new KeyRange(properties); + }; + + /** + * Encodes the specified KeyRange message. Does not implicitly {@link google.spanner.executor.v1.KeyRange.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {google.spanner.executor.v1.IKeyRange} message KeyRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyRange.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.start != null && Object.hasOwnProperty.call(message, "start")) + $root.google.spanner.executor.v1.ValueList.encode(message.start, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.limit != null && Object.hasOwnProperty.call(message, "limit")) + $root.google.spanner.executor.v1.ValueList.encode(message.limit, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.type); + return writer; + }; + + /** + * Encodes the specified KeyRange message, length delimited. Does not implicitly {@link google.spanner.executor.v1.KeyRange.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {google.spanner.executor.v1.IKeyRange} message KeyRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyRange.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a KeyRange message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.KeyRange} KeyRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyRange.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.spanner.executor.v1.KeyRange(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.start = $root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32()); + break; + } + case 2: { + message.limit = $root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32()); + break; + } + case 3: { + message.type = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a KeyRange message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.KeyRange} KeyRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyRange.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a KeyRange message. + * @function verify + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + KeyRange.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.start != null && message.hasOwnProperty("start")) { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.start); + if (error) + return "start." + error; + } + if (message.limit != null && message.hasOwnProperty("limit")) { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.limit); + if (error) + return "limit." + error; + } + if (message.type != null && message.hasOwnProperty("type")) { + properties._type = 1; + switch (message.type) { + default: + return "type: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + } + return null; + }; + + /** + * Creates a KeyRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.KeyRange} KeyRange + */ + KeyRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.KeyRange) + return object; + var message = new $root.google.spanner.executor.v1.KeyRange(); + if (object.start != null) { + if (typeof object.start !== "object") + throw TypeError(".google.spanner.executor.v1.KeyRange.start: object expected"); + message.start = $root.google.spanner.executor.v1.ValueList.fromObject(object.start); + } + if (object.limit != null) { + if (typeof object.limit !== "object") + throw TypeError(".google.spanner.executor.v1.KeyRange.limit: object expected"); + message.limit = $root.google.spanner.executor.v1.ValueList.fromObject(object.limit); + } + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.type = 0; + break; + case "CLOSED_CLOSED": + case 1: + message.type = 1; + break; + case "CLOSED_OPEN": + case 2: + message.type = 2; + break; + case "OPEN_CLOSED": + case 3: + message.type = 3; + break; + case "OPEN_OPEN": + case 4: + message.type = 4; + break; + } + return message; + }; + + /** + * Creates a plain object from a KeyRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {google.spanner.executor.v1.KeyRange} message KeyRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + KeyRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = null; + object.limit = null; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = $root.google.spanner.executor.v1.ValueList.toObject(message.start, options); + if (message.limit != null && message.hasOwnProperty("limit")) + object.limit = $root.google.spanner.executor.v1.ValueList.toObject(message.limit, options); + if (message.type != null && message.hasOwnProperty("type")) { + object.type = options.enums === String ? $root.google.spanner.executor.v1.KeyRange.Type[message.type] === undefined ? message.type : $root.google.spanner.executor.v1.KeyRange.Type[message.type] : message.type; + if (options.oneofs) + object._type = "type"; + } + return object; + }; + + /** + * Converts this KeyRange to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.KeyRange + * @instance + * @returns {Object.} JSON object + */ + KeyRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for KeyRange + * @function getTypeUrl + * @memberof google.spanner.executor.v1.KeyRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + KeyRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.KeyRange"; + }; + + /** + * Type enum. + * @name google.spanner.executor.v1.KeyRange.Type + * @enum {number} + * @property {number} TYPE_UNSPECIFIED=0 TYPE_UNSPECIFIED value + * @property {number} CLOSED_CLOSED=1 CLOSED_CLOSED value + * @property {number} CLOSED_OPEN=2 CLOSED_OPEN value + * @property {number} OPEN_CLOSED=3 OPEN_CLOSED value + * @property {number} OPEN_OPEN=4 OPEN_OPEN value + */ + KeyRange.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "CLOSED_CLOSED"] = 1; + values[valuesById[2] = "CLOSED_OPEN"] = 2; + values[valuesById[3] = "OPEN_CLOSED"] = 3; + values[valuesById[4] = "OPEN_OPEN"] = 4; + return values; + })(); + + return KeyRange; + })(); + + v1.KeySet = (function() { + + /** + * Properties of a KeySet. + * @memberof google.spanner.executor.v1 + * @interface IKeySet + * @property {Array.|null} [point] KeySet point + * @property {Array.|null} [range] KeySet range + * @property {boolean|null} [all] KeySet all + */ + + /** + * Constructs a new KeySet. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a KeySet. + * @implements IKeySet + * @constructor + * @param {google.spanner.executor.v1.IKeySet=} [properties] Properties to set + */ + function KeySet(properties) { + this.point = []; + this.range = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * KeySet point. + * @member {Array.} point + * @memberof google.spanner.executor.v1.KeySet + * @instance + */ + KeySet.prototype.point = $util.emptyArray; + + /** + * KeySet range. + * @member {Array.} range + * @memberof google.spanner.executor.v1.KeySet + * @instance + */ + KeySet.prototype.range = $util.emptyArray; + + /** + * KeySet all. + * @member {boolean} all + * @memberof google.spanner.executor.v1.KeySet + * @instance + */ + KeySet.prototype.all = false; + + /** + * Creates a new KeySet instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {google.spanner.executor.v1.IKeySet=} [properties] Properties to set + * @returns {google.spanner.executor.v1.KeySet} KeySet instance + */ + KeySet.create = function create(properties) { + return new KeySet(properties); + }; + + /** + * Encodes the specified KeySet message. Does not implicitly {@link google.spanner.executor.v1.KeySet.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {google.spanner.executor.v1.IKeySet} message KeySet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeySet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.point != null && message.point.length) + for (var i = 0; i < message.point.length; ++i) + $root.google.spanner.executor.v1.ValueList.encode(message.point[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.range != null && message.range.length) + for (var i = 0; i < message.range.length; ++i) + $root.google.spanner.executor.v1.KeyRange.encode(message.range[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.all != null && Object.hasOwnProperty.call(message, "all")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.all); + return writer; + }; + + /** + * Encodes the specified KeySet message, length delimited. Does not implicitly {@link google.spanner.executor.v1.KeySet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {google.spanner.executor.v1.IKeySet} message KeySet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeySet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a KeySet message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.KeySet} KeySet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeySet.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.spanner.executor.v1.KeySet(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.point && message.point.length)) + message.point = []; + message.point.push($root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32())); + break; + } + case 2: { + if (!(message.range && message.range.length)) + message.range = []; + message.range.push($root.google.spanner.executor.v1.KeyRange.decode(reader, reader.uint32())); + break; + } + case 3: { + message.all = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a KeySet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.KeySet} KeySet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeySet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a KeySet message. + * @function verify + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + KeySet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.point != null && message.hasOwnProperty("point")) { + if (!Array.isArray(message.point)) + return "point: array expected"; + for (var i = 0; i < message.point.length; ++i) { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.point[i]); + if (error) + return "point." + error; + } + } + if (message.range != null && message.hasOwnProperty("range")) { + if (!Array.isArray(message.range)) + return "range: array expected"; + for (var i = 0; i < message.range.length; ++i) { + var error = $root.google.spanner.executor.v1.KeyRange.verify(message.range[i]); + if (error) + return "range." + error; + } + } + if (message.all != null && message.hasOwnProperty("all")) + if (typeof message.all !== "boolean") + return "all: boolean expected"; + return null; + }; + + /** + * Creates a KeySet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.KeySet} KeySet + */ + KeySet.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.KeySet) + return object; + var message = new $root.google.spanner.executor.v1.KeySet(); + if (object.point) { + if (!Array.isArray(object.point)) + throw TypeError(".google.spanner.executor.v1.KeySet.point: array expected"); + message.point = []; + for (var i = 0; i < object.point.length; ++i) { + if (typeof object.point[i] !== "object") + throw TypeError(".google.spanner.executor.v1.KeySet.point: object expected"); + message.point[i] = $root.google.spanner.executor.v1.ValueList.fromObject(object.point[i]); + } + } + if (object.range) { + if (!Array.isArray(object.range)) + throw TypeError(".google.spanner.executor.v1.KeySet.range: array expected"); + message.range = []; + for (var i = 0; i < object.range.length; ++i) { + if (typeof object.range[i] !== "object") + throw TypeError(".google.spanner.executor.v1.KeySet.range: object expected"); + message.range[i] = $root.google.spanner.executor.v1.KeyRange.fromObject(object.range[i]); + } + } + if (object.all != null) + message.all = Boolean(object.all); + return message; + }; + + /** + * Creates a plain object from a KeySet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {google.spanner.executor.v1.KeySet} message KeySet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + KeySet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.point = []; + object.range = []; + } + if (options.defaults) + object.all = false; + if (message.point && message.point.length) { + object.point = []; + for (var j = 0; j < message.point.length; ++j) + object.point[j] = $root.google.spanner.executor.v1.ValueList.toObject(message.point[j], options); + } + if (message.range && message.range.length) { + object.range = []; + for (var j = 0; j < message.range.length; ++j) + object.range[j] = $root.google.spanner.executor.v1.KeyRange.toObject(message.range[j], options); + } + if (message.all != null && message.hasOwnProperty("all")) + object.all = message.all; + return object; + }; + + /** + * Converts this KeySet to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.KeySet + * @instance + * @returns {Object.} JSON object + */ + KeySet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for KeySet + * @function getTypeUrl + * @memberof google.spanner.executor.v1.KeySet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + KeySet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.KeySet"; + }; + + return KeySet; + })(); + + v1.ValueList = (function() { + + /** + * Properties of a ValueList. + * @memberof google.spanner.executor.v1 + * @interface IValueList + * @property {Array.|null} [value] ValueList value + */ + + /** + * Constructs a new ValueList. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ValueList. + * @implements IValueList + * @constructor + * @param {google.spanner.executor.v1.IValueList=} [properties] Properties to set + */ + function ValueList(properties) { + this.value = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ValueList value. + * @member {Array.} value + * @memberof google.spanner.executor.v1.ValueList + * @instance + */ + ValueList.prototype.value = $util.emptyArray; + + /** + * Creates a new ValueList instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {google.spanner.executor.v1.IValueList=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ValueList} ValueList instance + */ + ValueList.create = function create(properties) { + return new ValueList(properties); + }; + + /** + * Encodes the specified ValueList message. Does not implicitly {@link google.spanner.executor.v1.ValueList.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {google.spanner.executor.v1.IValueList} message ValueList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ValueList.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.value != null && message.value.length) + for (var i = 0; i < message.value.length; ++i) + $root.google.spanner.executor.v1.Value.encode(message.value[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ValueList message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ValueList.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {google.spanner.executor.v1.IValueList} message ValueList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ValueList.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ValueList message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ValueList} ValueList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ValueList.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.spanner.executor.v1.ValueList(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.value && message.value.length)) + message.value = []; + message.value.push($root.google.spanner.executor.v1.Value.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ValueList message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ValueList} ValueList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ValueList.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ValueList message. + * @function verify + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ValueList.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.value != null && message.hasOwnProperty("value")) { + if (!Array.isArray(message.value)) + return "value: array expected"; + for (var i = 0; i < message.value.length; ++i) { + var error = $root.google.spanner.executor.v1.Value.verify(message.value[i]); + if (error) + return "value." + error; + } + } + return null; + }; + + /** + * Creates a ValueList message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ValueList} ValueList + */ + ValueList.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ValueList) + return object; + var message = new $root.google.spanner.executor.v1.ValueList(); + if (object.value) { + if (!Array.isArray(object.value)) + throw TypeError(".google.spanner.executor.v1.ValueList.value: array expected"); + message.value = []; + for (var i = 0; i < object.value.length; ++i) { + if (typeof object.value[i] !== "object") + throw TypeError(".google.spanner.executor.v1.ValueList.value: object expected"); + message.value[i] = $root.google.spanner.executor.v1.Value.fromObject(object.value[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ValueList message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {google.spanner.executor.v1.ValueList} message ValueList + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ValueList.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.value = []; + if (message.value && message.value.length) { + object.value = []; + for (var j = 0; j < message.value.length; ++j) + object.value[j] = $root.google.spanner.executor.v1.Value.toObject(message.value[j], options); + } + return object; + }; + + /** + * Converts this ValueList to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ValueList + * @instance + * @returns {Object.} JSON object + */ + ValueList.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ValueList + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ValueList + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ValueList.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ValueList"; + }; + + return ValueList; + })(); + + v1.MutationAction = (function() { + + /** + * Properties of a MutationAction. + * @memberof google.spanner.executor.v1 + * @interface IMutationAction + * @property {Array.|null} [mod] MutationAction mod + */ + + /** + * Constructs a new MutationAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a MutationAction. + * @implements IMutationAction + * @constructor + * @param {google.spanner.executor.v1.IMutationAction=} [properties] Properties to set + */ + function MutationAction(properties) { + this.mod = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MutationAction mod. + * @member {Array.} mod + * @memberof google.spanner.executor.v1.MutationAction + * @instance + */ + MutationAction.prototype.mod = $util.emptyArray; + + /** + * Creates a new MutationAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {google.spanner.executor.v1.IMutationAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.MutationAction} MutationAction instance + */ + MutationAction.create = function create(properties) { + return new MutationAction(properties); + }; + + /** + * Encodes the specified MutationAction message. Does not implicitly {@link google.spanner.executor.v1.MutationAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {google.spanner.executor.v1.IMutationAction} message MutationAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MutationAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.mod != null && message.mod.length) + for (var i = 0; i < message.mod.length; ++i) + $root.google.spanner.executor.v1.MutationAction.Mod.encode(message.mod[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified MutationAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.MutationAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {google.spanner.executor.v1.IMutationAction} message MutationAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MutationAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MutationAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.MutationAction} MutationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MutationAction.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.spanner.executor.v1.MutationAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.mod && message.mod.length)) + message.mod = []; + message.mod.push($root.google.spanner.executor.v1.MutationAction.Mod.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MutationAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.MutationAction} MutationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MutationAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MutationAction message. + * @function verify + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MutationAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.mod != null && message.hasOwnProperty("mod")) { + if (!Array.isArray(message.mod)) + return "mod: array expected"; + for (var i = 0; i < message.mod.length; ++i) { + var error = $root.google.spanner.executor.v1.MutationAction.Mod.verify(message.mod[i]); + if (error) + return "mod." + error; + } + } + return null; + }; + + /** + * Creates a MutationAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.MutationAction} MutationAction + */ + MutationAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.MutationAction) + return object; + var message = new $root.google.spanner.executor.v1.MutationAction(); + if (object.mod) { + if (!Array.isArray(object.mod)) + throw TypeError(".google.spanner.executor.v1.MutationAction.mod: array expected"); + message.mod = []; + for (var i = 0; i < object.mod.length; ++i) { + if (typeof object.mod[i] !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.mod: object expected"); + message.mod[i] = $root.google.spanner.executor.v1.MutationAction.Mod.fromObject(object.mod[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a MutationAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {google.spanner.executor.v1.MutationAction} message MutationAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MutationAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.mod = []; + if (message.mod && message.mod.length) { + object.mod = []; + for (var j = 0; j < message.mod.length; ++j) + object.mod[j] = $root.google.spanner.executor.v1.MutationAction.Mod.toObject(message.mod[j], options); + } + return object; + }; + + /** + * Converts this MutationAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.MutationAction + * @instance + * @returns {Object.} JSON object + */ + MutationAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MutationAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.MutationAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MutationAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.MutationAction"; + }; + + MutationAction.InsertArgs = (function() { + + /** + * Properties of an InsertArgs. + * @memberof google.spanner.executor.v1.MutationAction + * @interface IInsertArgs + * @property {Array.|null} [column] InsertArgs column + * @property {Array.|null} [type] InsertArgs type + * @property {Array.|null} [values] InsertArgs values + */ + + /** + * Constructs a new InsertArgs. + * @memberof google.spanner.executor.v1.MutationAction + * @classdesc Represents an InsertArgs. + * @implements IInsertArgs + * @constructor + * @param {google.spanner.executor.v1.MutationAction.IInsertArgs=} [properties] Properties to set + */ + function InsertArgs(properties) { + this.column = []; + this.type = []; + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InsertArgs column. + * @member {Array.} column + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @instance + */ + InsertArgs.prototype.column = $util.emptyArray; + + /** + * InsertArgs type. + * @member {Array.} type + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @instance + */ + InsertArgs.prototype.type = $util.emptyArray; + + /** + * InsertArgs values. + * @member {Array.} values + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @instance + */ + InsertArgs.prototype.values = $util.emptyArray; + + /** + * Creates a new InsertArgs instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {google.spanner.executor.v1.MutationAction.IInsertArgs=} [properties] Properties to set + * @returns {google.spanner.executor.v1.MutationAction.InsertArgs} InsertArgs instance + */ + InsertArgs.create = function create(properties) { + return new InsertArgs(properties); + }; + + /** + * Encodes the specified InsertArgs message. Does not implicitly {@link google.spanner.executor.v1.MutationAction.InsertArgs.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {google.spanner.executor.v1.MutationAction.IInsertArgs} message InsertArgs message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InsertArgs.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.column != null && message.column.length) + for (var i = 0; i < message.column.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.column[i]); + if (message.type != null && message.type.length) + for (var i = 0; i < message.type.length; ++i) + $root.google.spanner.v1.Type.encode(message.type[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.values != null && message.values.length) + for (var i = 0; i < message.values.length; ++i) + $root.google.spanner.executor.v1.ValueList.encode(message.values[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified InsertArgs message, length delimited. Does not implicitly {@link google.spanner.executor.v1.MutationAction.InsertArgs.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {google.spanner.executor.v1.MutationAction.IInsertArgs} message InsertArgs message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InsertArgs.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InsertArgs message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.MutationAction.InsertArgs} InsertArgs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InsertArgs.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.spanner.executor.v1.MutationAction.InsertArgs(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.column && message.column.length)) + message.column = []; + message.column.push(reader.string()); + break; + } + case 2: { + if (!(message.type && message.type.length)) + message.type = []; + message.type.push($root.google.spanner.v1.Type.decode(reader, reader.uint32())); + break; + } + case 3: { + if (!(message.values && message.values.length)) + message.values = []; + message.values.push($root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InsertArgs message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.MutationAction.InsertArgs} InsertArgs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InsertArgs.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InsertArgs message. + * @function verify + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InsertArgs.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.column != null && message.hasOwnProperty("column")) { + if (!Array.isArray(message.column)) + return "column: array expected"; + for (var i = 0; i < message.column.length; ++i) + if (!$util.isString(message.column[i])) + return "column: string[] expected"; + } + if (message.type != null && message.hasOwnProperty("type")) { + if (!Array.isArray(message.type)) + return "type: array expected"; + for (var i = 0; i < message.type.length; ++i) { + var error = $root.google.spanner.v1.Type.verify(message.type[i]); + if (error) + return "type." + error; + } + } + if (message.values != null && message.hasOwnProperty("values")) { + if (!Array.isArray(message.values)) + return "values: array expected"; + for (var i = 0; i < message.values.length; ++i) { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.values[i]); + if (error) + return "values." + error; + } + } + return null; + }; + + /** + * Creates an InsertArgs message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.MutationAction.InsertArgs} InsertArgs + */ + InsertArgs.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.MutationAction.InsertArgs) + return object; + var message = new $root.google.spanner.executor.v1.MutationAction.InsertArgs(); + if (object.column) { + if (!Array.isArray(object.column)) + throw TypeError(".google.spanner.executor.v1.MutationAction.InsertArgs.column: array expected"); + message.column = []; + for (var i = 0; i < object.column.length; ++i) + message.column[i] = String(object.column[i]); + } + if (object.type) { + if (!Array.isArray(object.type)) + throw TypeError(".google.spanner.executor.v1.MutationAction.InsertArgs.type: array expected"); + message.type = []; + for (var i = 0; i < object.type.length; ++i) { + if (typeof object.type[i] !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.InsertArgs.type: object expected"); + message.type[i] = $root.google.spanner.v1.Type.fromObject(object.type[i]); + } + } + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.spanner.executor.v1.MutationAction.InsertArgs.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.InsertArgs.values: object expected"); + message.values[i] = $root.google.spanner.executor.v1.ValueList.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an InsertArgs message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {google.spanner.executor.v1.MutationAction.InsertArgs} message InsertArgs + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InsertArgs.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.column = []; + object.type = []; + object.values = []; + } + if (message.column && message.column.length) { + object.column = []; + for (var j = 0; j < message.column.length; ++j) + object.column[j] = message.column[j]; + } + if (message.type && message.type.length) { + object.type = []; + for (var j = 0; j < message.type.length; ++j) + object.type[j] = $root.google.spanner.v1.Type.toObject(message.type[j], options); + } + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.spanner.executor.v1.ValueList.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this InsertArgs to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @instance + * @returns {Object.} JSON object + */ + InsertArgs.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InsertArgs + * @function getTypeUrl + * @memberof google.spanner.executor.v1.MutationAction.InsertArgs + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InsertArgs.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.MutationAction.InsertArgs"; + }; + + return InsertArgs; + })(); + + MutationAction.UpdateArgs = (function() { + + /** + * Properties of an UpdateArgs. + * @memberof google.spanner.executor.v1.MutationAction + * @interface IUpdateArgs + * @property {Array.|null} [column] UpdateArgs column + * @property {Array.|null} [type] UpdateArgs type + * @property {Array.|null} [values] UpdateArgs values + */ + + /** + * Constructs a new UpdateArgs. + * @memberof google.spanner.executor.v1.MutationAction + * @classdesc Represents an UpdateArgs. + * @implements IUpdateArgs + * @constructor + * @param {google.spanner.executor.v1.MutationAction.IUpdateArgs=} [properties] Properties to set + */ + function UpdateArgs(properties) { + this.column = []; + this.type = []; + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateArgs column. + * @member {Array.} column + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @instance + */ + UpdateArgs.prototype.column = $util.emptyArray; + + /** + * UpdateArgs type. + * @member {Array.} type + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @instance + */ + UpdateArgs.prototype.type = $util.emptyArray; + + /** + * UpdateArgs values. + * @member {Array.} values + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @instance + */ + UpdateArgs.prototype.values = $util.emptyArray; + + /** + * Creates a new UpdateArgs instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {google.spanner.executor.v1.MutationAction.IUpdateArgs=} [properties] Properties to set + * @returns {google.spanner.executor.v1.MutationAction.UpdateArgs} UpdateArgs instance + */ + UpdateArgs.create = function create(properties) { + return new UpdateArgs(properties); + }; + + /** + * Encodes the specified UpdateArgs message. Does not implicitly {@link google.spanner.executor.v1.MutationAction.UpdateArgs.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {google.spanner.executor.v1.MutationAction.IUpdateArgs} message UpdateArgs message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateArgs.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.column != null && message.column.length) + for (var i = 0; i < message.column.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.column[i]); + if (message.type != null && message.type.length) + for (var i = 0; i < message.type.length; ++i) + $root.google.spanner.v1.Type.encode(message.type[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.values != null && message.values.length) + for (var i = 0; i < message.values.length; ++i) + $root.google.spanner.executor.v1.ValueList.encode(message.values[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateArgs message, length delimited. Does not implicitly {@link google.spanner.executor.v1.MutationAction.UpdateArgs.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {google.spanner.executor.v1.MutationAction.IUpdateArgs} message UpdateArgs message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateArgs.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateArgs message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.MutationAction.UpdateArgs} UpdateArgs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateArgs.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.spanner.executor.v1.MutationAction.UpdateArgs(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.column && message.column.length)) + message.column = []; + message.column.push(reader.string()); + break; + } + case 2: { + if (!(message.type && message.type.length)) + message.type = []; + message.type.push($root.google.spanner.v1.Type.decode(reader, reader.uint32())); + break; + } + case 3: { + if (!(message.values && message.values.length)) + message.values = []; + message.values.push($root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateArgs message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.MutationAction.UpdateArgs} UpdateArgs + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateArgs.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateArgs message. + * @function verify + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateArgs.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.column != null && message.hasOwnProperty("column")) { + if (!Array.isArray(message.column)) + return "column: array expected"; + for (var i = 0; i < message.column.length; ++i) + if (!$util.isString(message.column[i])) + return "column: string[] expected"; + } + if (message.type != null && message.hasOwnProperty("type")) { + if (!Array.isArray(message.type)) + return "type: array expected"; + for (var i = 0; i < message.type.length; ++i) { + var error = $root.google.spanner.v1.Type.verify(message.type[i]); + if (error) + return "type." + error; + } + } + if (message.values != null && message.hasOwnProperty("values")) { + if (!Array.isArray(message.values)) + return "values: array expected"; + for (var i = 0; i < message.values.length; ++i) { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.values[i]); + if (error) + return "values." + error; + } + } + return null; + }; + + /** + * Creates an UpdateArgs message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.MutationAction.UpdateArgs} UpdateArgs + */ + UpdateArgs.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.MutationAction.UpdateArgs) + return object; + var message = new $root.google.spanner.executor.v1.MutationAction.UpdateArgs(); + if (object.column) { + if (!Array.isArray(object.column)) + throw TypeError(".google.spanner.executor.v1.MutationAction.UpdateArgs.column: array expected"); + message.column = []; + for (var i = 0; i < object.column.length; ++i) + message.column[i] = String(object.column[i]); + } + if (object.type) { + if (!Array.isArray(object.type)) + throw TypeError(".google.spanner.executor.v1.MutationAction.UpdateArgs.type: array expected"); + message.type = []; + for (var i = 0; i < object.type.length; ++i) { + if (typeof object.type[i] !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.UpdateArgs.type: object expected"); + message.type[i] = $root.google.spanner.v1.Type.fromObject(object.type[i]); + } + } + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.spanner.executor.v1.MutationAction.UpdateArgs.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.UpdateArgs.values: object expected"); + message.values[i] = $root.google.spanner.executor.v1.ValueList.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an UpdateArgs message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {google.spanner.executor.v1.MutationAction.UpdateArgs} message UpdateArgs + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateArgs.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.column = []; + object.type = []; + object.values = []; + } + if (message.column && message.column.length) { + object.column = []; + for (var j = 0; j < message.column.length; ++j) + object.column[j] = message.column[j]; + } + if (message.type && message.type.length) { + object.type = []; + for (var j = 0; j < message.type.length; ++j) + object.type[j] = $root.google.spanner.v1.Type.toObject(message.type[j], options); + } + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.spanner.executor.v1.ValueList.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this UpdateArgs to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @instance + * @returns {Object.} JSON object + */ + UpdateArgs.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateArgs + * @function getTypeUrl + * @memberof google.spanner.executor.v1.MutationAction.UpdateArgs + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateArgs.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.MutationAction.UpdateArgs"; + }; + + return UpdateArgs; + })(); + + MutationAction.Mod = (function() { + + /** + * Properties of a Mod. + * @memberof google.spanner.executor.v1.MutationAction + * @interface IMod + * @property {string|null} [table] Mod table + * @property {google.spanner.executor.v1.MutationAction.IInsertArgs|null} [insert] Mod insert + * @property {google.spanner.executor.v1.MutationAction.IUpdateArgs|null} [update] Mod update + * @property {google.spanner.executor.v1.MutationAction.IInsertArgs|null} [insertOrUpdate] Mod insertOrUpdate + * @property {google.spanner.executor.v1.MutationAction.IInsertArgs|null} [replace] Mod replace + * @property {google.spanner.executor.v1.IKeySet|null} [deleteKeys] Mod deleteKeys + */ + + /** + * Constructs a new Mod. + * @memberof google.spanner.executor.v1.MutationAction + * @classdesc Represents a Mod. + * @implements IMod + * @constructor + * @param {google.spanner.executor.v1.MutationAction.IMod=} [properties] Properties to set + */ + function Mod(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Mod table. + * @member {string} table + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @instance + */ + Mod.prototype.table = ""; + + /** + * Mod insert. + * @member {google.spanner.executor.v1.MutationAction.IInsertArgs|null|undefined} insert + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @instance + */ + Mod.prototype.insert = null; + + /** + * Mod update. + * @member {google.spanner.executor.v1.MutationAction.IUpdateArgs|null|undefined} update + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @instance + */ + Mod.prototype.update = null; + + /** + * Mod insertOrUpdate. + * @member {google.spanner.executor.v1.MutationAction.IInsertArgs|null|undefined} insertOrUpdate + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @instance + */ + Mod.prototype.insertOrUpdate = null; + + /** + * Mod replace. + * @member {google.spanner.executor.v1.MutationAction.IInsertArgs|null|undefined} replace + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @instance + */ + Mod.prototype.replace = null; + + /** + * Mod deleteKeys. + * @member {google.spanner.executor.v1.IKeySet|null|undefined} deleteKeys + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @instance + */ + Mod.prototype.deleteKeys = null; + + /** + * Creates a new Mod instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {google.spanner.executor.v1.MutationAction.IMod=} [properties] Properties to set + * @returns {google.spanner.executor.v1.MutationAction.Mod} Mod instance + */ + Mod.create = function create(properties) { + return new Mod(properties); + }; + + /** + * Encodes the specified Mod message. Does not implicitly {@link google.spanner.executor.v1.MutationAction.Mod.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {google.spanner.executor.v1.MutationAction.IMod} message Mod message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Mod.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.table); + if (message.insert != null && Object.hasOwnProperty.call(message, "insert")) + $root.google.spanner.executor.v1.MutationAction.InsertArgs.encode(message.insert, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.update != null && Object.hasOwnProperty.call(message, "update")) + $root.google.spanner.executor.v1.MutationAction.UpdateArgs.encode(message.update, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.insertOrUpdate != null && Object.hasOwnProperty.call(message, "insertOrUpdate")) + $root.google.spanner.executor.v1.MutationAction.InsertArgs.encode(message.insertOrUpdate, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.replace != null && Object.hasOwnProperty.call(message, "replace")) + $root.google.spanner.executor.v1.MutationAction.InsertArgs.encode(message.replace, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.deleteKeys != null && Object.hasOwnProperty.call(message, "deleteKeys")) + $root.google.spanner.executor.v1.KeySet.encode(message.deleteKeys, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Mod message, length delimited. Does not implicitly {@link google.spanner.executor.v1.MutationAction.Mod.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {google.spanner.executor.v1.MutationAction.IMod} message Mod message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Mod.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Mod message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.MutationAction.Mod} Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Mod.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.spanner.executor.v1.MutationAction.Mod(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.table = reader.string(); + break; + } + case 2: { + message.insert = $root.google.spanner.executor.v1.MutationAction.InsertArgs.decode(reader, reader.uint32()); + break; + } + case 3: { + message.update = $root.google.spanner.executor.v1.MutationAction.UpdateArgs.decode(reader, reader.uint32()); + break; + } + case 4: { + message.insertOrUpdate = $root.google.spanner.executor.v1.MutationAction.InsertArgs.decode(reader, reader.uint32()); + break; + } + case 5: { + message.replace = $root.google.spanner.executor.v1.MutationAction.InsertArgs.decode(reader, reader.uint32()); + break; + } + case 6: { + message.deleteKeys = $root.google.spanner.executor.v1.KeySet.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Mod message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.MutationAction.Mod} Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Mod.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Mod message. + * @function verify + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Mod.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.insert != null && message.hasOwnProperty("insert")) { + var error = $root.google.spanner.executor.v1.MutationAction.InsertArgs.verify(message.insert); + if (error) + return "insert." + error; + } + if (message.update != null && message.hasOwnProperty("update")) { + var error = $root.google.spanner.executor.v1.MutationAction.UpdateArgs.verify(message.update); + if (error) + return "update." + error; + } + if (message.insertOrUpdate != null && message.hasOwnProperty("insertOrUpdate")) { + var error = $root.google.spanner.executor.v1.MutationAction.InsertArgs.verify(message.insertOrUpdate); + if (error) + return "insertOrUpdate." + error; + } + if (message.replace != null && message.hasOwnProperty("replace")) { + var error = $root.google.spanner.executor.v1.MutationAction.InsertArgs.verify(message.replace); + if (error) + return "replace." + error; + } + if (message.deleteKeys != null && message.hasOwnProperty("deleteKeys")) { + var error = $root.google.spanner.executor.v1.KeySet.verify(message.deleteKeys); + if (error) + return "deleteKeys." + error; + } + return null; + }; + + /** + * Creates a Mod message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.MutationAction.Mod} Mod + */ + Mod.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.MutationAction.Mod) + return object; + var message = new $root.google.spanner.executor.v1.MutationAction.Mod(); + if (object.table != null) + message.table = String(object.table); + if (object.insert != null) { + if (typeof object.insert !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.Mod.insert: object expected"); + message.insert = $root.google.spanner.executor.v1.MutationAction.InsertArgs.fromObject(object.insert); + } + if (object.update != null) { + if (typeof object.update !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.Mod.update: object expected"); + message.update = $root.google.spanner.executor.v1.MutationAction.UpdateArgs.fromObject(object.update); + } + if (object.insertOrUpdate != null) { + if (typeof object.insertOrUpdate !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.Mod.insertOrUpdate: object expected"); + message.insertOrUpdate = $root.google.spanner.executor.v1.MutationAction.InsertArgs.fromObject(object.insertOrUpdate); + } + if (object.replace != null) { + if (typeof object.replace !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.Mod.replace: object expected"); + message.replace = $root.google.spanner.executor.v1.MutationAction.InsertArgs.fromObject(object.replace); + } + if (object.deleteKeys != null) { + if (typeof object.deleteKeys !== "object") + throw TypeError(".google.spanner.executor.v1.MutationAction.Mod.deleteKeys: object expected"); + message.deleteKeys = $root.google.spanner.executor.v1.KeySet.fromObject(object.deleteKeys); + } + return message; + }; + + /** + * Creates a plain object from a Mod message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {google.spanner.executor.v1.MutationAction.Mod} message Mod + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Mod.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.table = ""; + object.insert = null; + object.update = null; + object.insertOrUpdate = null; + object.replace = null; + object.deleteKeys = null; + } + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.insert != null && message.hasOwnProperty("insert")) + object.insert = $root.google.spanner.executor.v1.MutationAction.InsertArgs.toObject(message.insert, options); + if (message.update != null && message.hasOwnProperty("update")) + object.update = $root.google.spanner.executor.v1.MutationAction.UpdateArgs.toObject(message.update, options); + if (message.insertOrUpdate != null && message.hasOwnProperty("insertOrUpdate")) + object.insertOrUpdate = $root.google.spanner.executor.v1.MutationAction.InsertArgs.toObject(message.insertOrUpdate, options); + if (message.replace != null && message.hasOwnProperty("replace")) + object.replace = $root.google.spanner.executor.v1.MutationAction.InsertArgs.toObject(message.replace, options); + if (message.deleteKeys != null && message.hasOwnProperty("deleteKeys")) + object.deleteKeys = $root.google.spanner.executor.v1.KeySet.toObject(message.deleteKeys, options); + return object; + }; + + /** + * Converts this Mod to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @instance + * @returns {Object.} JSON object + */ + Mod.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Mod + * @function getTypeUrl + * @memberof google.spanner.executor.v1.MutationAction.Mod + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Mod.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.MutationAction.Mod"; + }; + + return Mod; + })(); + + return MutationAction; + })(); + + v1.WriteMutationsAction = (function() { + + /** + * Properties of a WriteMutationsAction. + * @memberof google.spanner.executor.v1 + * @interface IWriteMutationsAction + * @property {google.spanner.executor.v1.IMutationAction|null} [mutation] WriteMutationsAction mutation + */ + + /** + * Constructs a new WriteMutationsAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a WriteMutationsAction. + * @implements IWriteMutationsAction + * @constructor + * @param {google.spanner.executor.v1.IWriteMutationsAction=} [properties] Properties to set + */ + function WriteMutationsAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WriteMutationsAction mutation. + * @member {google.spanner.executor.v1.IMutationAction|null|undefined} mutation + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @instance + */ + WriteMutationsAction.prototype.mutation = null; + + /** + * Creates a new WriteMutationsAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {google.spanner.executor.v1.IWriteMutationsAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.WriteMutationsAction} WriteMutationsAction instance + */ + WriteMutationsAction.create = function create(properties) { + return new WriteMutationsAction(properties); + }; + + /** + * Encodes the specified WriteMutationsAction message. Does not implicitly {@link google.spanner.executor.v1.WriteMutationsAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {google.spanner.executor.v1.IWriteMutationsAction} message WriteMutationsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WriteMutationsAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.mutation != null && Object.hasOwnProperty.call(message, "mutation")) + $root.google.spanner.executor.v1.MutationAction.encode(message.mutation, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified WriteMutationsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.WriteMutationsAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {google.spanner.executor.v1.IWriteMutationsAction} message WriteMutationsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WriteMutationsAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a WriteMutationsAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.WriteMutationsAction} WriteMutationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WriteMutationsAction.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.spanner.executor.v1.WriteMutationsAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.mutation = $root.google.spanner.executor.v1.MutationAction.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a WriteMutationsAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.WriteMutationsAction} WriteMutationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WriteMutationsAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a WriteMutationsAction message. + * @function verify + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + WriteMutationsAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.mutation != null && message.hasOwnProperty("mutation")) { + var error = $root.google.spanner.executor.v1.MutationAction.verify(message.mutation); + if (error) + return "mutation." + error; + } + return null; + }; + + /** + * Creates a WriteMutationsAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.WriteMutationsAction} WriteMutationsAction + */ + WriteMutationsAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.WriteMutationsAction) + return object; + var message = new $root.google.spanner.executor.v1.WriteMutationsAction(); + if (object.mutation != null) { + if (typeof object.mutation !== "object") + throw TypeError(".google.spanner.executor.v1.WriteMutationsAction.mutation: object expected"); + message.mutation = $root.google.spanner.executor.v1.MutationAction.fromObject(object.mutation); + } + return message; + }; + + /** + * Creates a plain object from a WriteMutationsAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {google.spanner.executor.v1.WriteMutationsAction} message WriteMutationsAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteMutationsAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.mutation = null; + if (message.mutation != null && message.hasOwnProperty("mutation")) + object.mutation = $root.google.spanner.executor.v1.MutationAction.toObject(message.mutation, options); + return object; + }; + + /** + * Converts this WriteMutationsAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @instance + * @returns {Object.} JSON object + */ + WriteMutationsAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WriteMutationsAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.WriteMutationsAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteMutationsAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.WriteMutationsAction"; + }; + + return WriteMutationsAction; + })(); + + v1.PartitionedUpdateAction = (function() { + + /** + * Properties of a PartitionedUpdateAction. + * @memberof google.spanner.executor.v1 + * @interface IPartitionedUpdateAction + * @property {google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions|null} [options] PartitionedUpdateAction options + * @property {google.spanner.executor.v1.IQueryAction|null} [update] PartitionedUpdateAction update + */ + + /** + * Constructs a new PartitionedUpdateAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a PartitionedUpdateAction. + * @implements IPartitionedUpdateAction + * @constructor + * @param {google.spanner.executor.v1.IPartitionedUpdateAction=} [properties] Properties to set + */ + function PartitionedUpdateAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionedUpdateAction options. + * @member {google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions|null|undefined} options + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @instance + */ + PartitionedUpdateAction.prototype.options = null; + + /** + * PartitionedUpdateAction update. + * @member {google.spanner.executor.v1.IQueryAction|null|undefined} update + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @instance + */ + PartitionedUpdateAction.prototype.update = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PartitionedUpdateAction.prototype, "_options", { + get: $util.oneOfGetter($oneOfFields = ["options"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new PartitionedUpdateAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {google.spanner.executor.v1.IPartitionedUpdateAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.PartitionedUpdateAction} PartitionedUpdateAction instance + */ + PartitionedUpdateAction.create = function create(properties) { + return new PartitionedUpdateAction(properties); + }; + + /** + * Encodes the specified PartitionedUpdateAction message. Does not implicitly {@link google.spanner.executor.v1.PartitionedUpdateAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {google.spanner.executor.v1.IPartitionedUpdateAction} message PartitionedUpdateAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionedUpdateAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.encode(message.options, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.update != null && Object.hasOwnProperty.call(message, "update")) + $root.google.spanner.executor.v1.QueryAction.encode(message.update, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PartitionedUpdateAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.PartitionedUpdateAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {google.spanner.executor.v1.IPartitionedUpdateAction} message PartitionedUpdateAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionedUpdateAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionedUpdateAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.PartitionedUpdateAction} PartitionedUpdateAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionedUpdateAction.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.spanner.executor.v1.PartitionedUpdateAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.options = $root.google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.decode(reader, reader.uint32()); + break; + } + case 2: { + message.update = $root.google.spanner.executor.v1.QueryAction.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionedUpdateAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.PartitionedUpdateAction} PartitionedUpdateAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionedUpdateAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionedUpdateAction message. + * @function verify + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionedUpdateAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.options != null && message.hasOwnProperty("options")) { + properties._options = 1; + { + var error = $root.google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.verify(message.options); + if (error) + return "options." + error; + } + } + if (message.update != null && message.hasOwnProperty("update")) { + var error = $root.google.spanner.executor.v1.QueryAction.verify(message.update); + if (error) + return "update." + error; + } + return null; + }; + + /** + * Creates a PartitionedUpdateAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.PartitionedUpdateAction} PartitionedUpdateAction + */ + PartitionedUpdateAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.PartitionedUpdateAction) + return object; + var message = new $root.google.spanner.executor.v1.PartitionedUpdateAction(); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.spanner.executor.v1.PartitionedUpdateAction.options: object expected"); + message.options = $root.google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.fromObject(object.options); + } + if (object.update != null) { + if (typeof object.update !== "object") + throw TypeError(".google.spanner.executor.v1.PartitionedUpdateAction.update: object expected"); + message.update = $root.google.spanner.executor.v1.QueryAction.fromObject(object.update); + } + return message; + }; + + /** + * Creates a plain object from a PartitionedUpdateAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {google.spanner.executor.v1.PartitionedUpdateAction} message PartitionedUpdateAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionedUpdateAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.update = null; + if (message.options != null && message.hasOwnProperty("options")) { + object.options = $root.google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.toObject(message.options, options); + if (options.oneofs) + object._options = "options"; + } + if (message.update != null && message.hasOwnProperty("update")) + object.update = $root.google.spanner.executor.v1.QueryAction.toObject(message.update, options); + return object; + }; + + /** + * Converts this PartitionedUpdateAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @instance + * @returns {Object.} JSON object + */ + PartitionedUpdateAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionedUpdateAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionedUpdateAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.PartitionedUpdateAction"; + }; + + PartitionedUpdateAction.ExecutePartitionedUpdateOptions = (function() { + + /** + * Properties of an ExecutePartitionedUpdateOptions. + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @interface IExecutePartitionedUpdateOptions + * @property {google.spanner.v1.RequestOptions.Priority|null} [rpcPriority] ExecutePartitionedUpdateOptions rpcPriority + * @property {string|null} [tag] ExecutePartitionedUpdateOptions tag + */ + + /** + * Constructs a new ExecutePartitionedUpdateOptions. + * @memberof google.spanner.executor.v1.PartitionedUpdateAction + * @classdesc Represents an ExecutePartitionedUpdateOptions. + * @implements IExecutePartitionedUpdateOptions + * @constructor + * @param {google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions=} [properties] Properties to set + */ + function ExecutePartitionedUpdateOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecutePartitionedUpdateOptions rpcPriority. + * @member {google.spanner.v1.RequestOptions.Priority|null|undefined} rpcPriority + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @instance + */ + ExecutePartitionedUpdateOptions.prototype.rpcPriority = null; + + /** + * ExecutePartitionedUpdateOptions tag. + * @member {string|null|undefined} tag + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @instance + */ + ExecutePartitionedUpdateOptions.prototype.tag = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ExecutePartitionedUpdateOptions.prototype, "_rpcPriority", { + get: $util.oneOfGetter($oneOfFields = ["rpcPriority"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ExecutePartitionedUpdateOptions.prototype, "_tag", { + get: $util.oneOfGetter($oneOfFields = ["tag"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ExecutePartitionedUpdateOptions instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions=} [properties] Properties to set + * @returns {google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions} ExecutePartitionedUpdateOptions instance + */ + ExecutePartitionedUpdateOptions.create = function create(properties) { + return new ExecutePartitionedUpdateOptions(properties); + }; + + /** + * Encodes the specified ExecutePartitionedUpdateOptions message. Does not implicitly {@link google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions} message ExecutePartitionedUpdateOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecutePartitionedUpdateOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.rpcPriority != null && Object.hasOwnProperty.call(message, "rpcPriority")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.rpcPriority); + if (message.tag != null && Object.hasOwnProperty.call(message, "tag")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.tag); + return writer; + }; + + /** + * Encodes the specified ExecutePartitionedUpdateOptions message, length delimited. Does not implicitly {@link google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {google.spanner.executor.v1.PartitionedUpdateAction.IExecutePartitionedUpdateOptions} message ExecutePartitionedUpdateOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecutePartitionedUpdateOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExecutePartitionedUpdateOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions} ExecutePartitionedUpdateOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecutePartitionedUpdateOptions.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.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.rpcPriority = reader.int32(); + break; + } + case 2: { + message.tag = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExecutePartitionedUpdateOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions} ExecutePartitionedUpdateOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecutePartitionedUpdateOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExecutePartitionedUpdateOptions message. + * @function verify + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExecutePartitionedUpdateOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.rpcPriority != null && message.hasOwnProperty("rpcPriority")) { + properties._rpcPriority = 1; + switch (message.rpcPriority) { + default: + return "rpcPriority: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + } + if (message.tag != null && message.hasOwnProperty("tag")) { + properties._tag = 1; + if (!$util.isString(message.tag)) + return "tag: string expected"; + } + return null; + }; + + /** + * Creates an ExecutePartitionedUpdateOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions} ExecutePartitionedUpdateOptions + */ + ExecutePartitionedUpdateOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions) + return object; + var message = new $root.google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions(); + switch (object.rpcPriority) { + default: + if (typeof object.rpcPriority === "number") { + message.rpcPriority = object.rpcPriority; + break; + } + break; + case "PRIORITY_UNSPECIFIED": + case 0: + message.rpcPriority = 0; + break; + case "PRIORITY_LOW": + case 1: + message.rpcPriority = 1; + break; + case "PRIORITY_MEDIUM": + case 2: + message.rpcPriority = 2; + break; + case "PRIORITY_HIGH": + case 3: + message.rpcPriority = 3; + break; + } + if (object.tag != null) + message.tag = String(object.tag); + return message; + }; + + /** + * Creates a plain object from an ExecutePartitionedUpdateOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions} message ExecutePartitionedUpdateOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecutePartitionedUpdateOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.rpcPriority != null && message.hasOwnProperty("rpcPriority")) { + object.rpcPriority = options.enums === String ? $root.google.spanner.v1.RequestOptions.Priority[message.rpcPriority] === undefined ? message.rpcPriority : $root.google.spanner.v1.RequestOptions.Priority[message.rpcPriority] : message.rpcPriority; + if (options.oneofs) + object._rpcPriority = "rpcPriority"; + } + if (message.tag != null && message.hasOwnProperty("tag")) { + object.tag = message.tag; + if (options.oneofs) + object._tag = "tag"; + } + return object; + }; + + /** + * Converts this ExecutePartitionedUpdateOptions to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @instance + * @returns {Object.} JSON object + */ + ExecutePartitionedUpdateOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecutePartitionedUpdateOptions + * @function getTypeUrl + * @memberof google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecutePartitionedUpdateOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.PartitionedUpdateAction.ExecutePartitionedUpdateOptions"; + }; + + return ExecutePartitionedUpdateOptions; + })(); + + return PartitionedUpdateAction; + })(); + + v1.StartTransactionAction = (function() { + + /** + * Properties of a StartTransactionAction. + * @memberof google.spanner.executor.v1 + * @interface IStartTransactionAction + * @property {google.spanner.executor.v1.IConcurrency|null} [concurrency] StartTransactionAction concurrency + * @property {Array.|null} [table] StartTransactionAction table + * @property {string|null} [transactionSeed] StartTransactionAction transactionSeed + * @property {google.spanner.executor.v1.ITransactionExecutionOptions|null} [executionOptions] StartTransactionAction executionOptions + */ + + /** + * Constructs a new StartTransactionAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a StartTransactionAction. + * @implements IStartTransactionAction + * @constructor + * @param {google.spanner.executor.v1.IStartTransactionAction=} [properties] Properties to set + */ + function StartTransactionAction(properties) { + this.table = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StartTransactionAction concurrency. + * @member {google.spanner.executor.v1.IConcurrency|null|undefined} concurrency + * @memberof google.spanner.executor.v1.StartTransactionAction + * @instance + */ + StartTransactionAction.prototype.concurrency = null; + + /** + * StartTransactionAction table. + * @member {Array.} table + * @memberof google.spanner.executor.v1.StartTransactionAction + * @instance + */ + StartTransactionAction.prototype.table = $util.emptyArray; + + /** + * StartTransactionAction transactionSeed. + * @member {string} transactionSeed + * @memberof google.spanner.executor.v1.StartTransactionAction + * @instance + */ + StartTransactionAction.prototype.transactionSeed = ""; + + /** + * StartTransactionAction executionOptions. + * @member {google.spanner.executor.v1.ITransactionExecutionOptions|null|undefined} executionOptions + * @memberof google.spanner.executor.v1.StartTransactionAction + * @instance + */ + StartTransactionAction.prototype.executionOptions = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(StartTransactionAction.prototype, "_concurrency", { + get: $util.oneOfGetter($oneOfFields = ["concurrency"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(StartTransactionAction.prototype, "_executionOptions", { + get: $util.oneOfGetter($oneOfFields = ["executionOptions"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new StartTransactionAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {google.spanner.executor.v1.IStartTransactionAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.StartTransactionAction} StartTransactionAction instance + */ + StartTransactionAction.create = function create(properties) { + return new StartTransactionAction(properties); + }; + + /** + * Encodes the specified StartTransactionAction message. Does not implicitly {@link google.spanner.executor.v1.StartTransactionAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {google.spanner.executor.v1.IStartTransactionAction} message StartTransactionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StartTransactionAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.concurrency != null && Object.hasOwnProperty.call(message, "concurrency")) + $root.google.spanner.executor.v1.Concurrency.encode(message.concurrency, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.table != null && message.table.length) + for (var i = 0; i < message.table.length; ++i) + $root.google.spanner.executor.v1.TableMetadata.encode(message.table[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.transactionSeed != null && Object.hasOwnProperty.call(message, "transactionSeed")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.transactionSeed); + if (message.executionOptions != null && Object.hasOwnProperty.call(message, "executionOptions")) + $root.google.spanner.executor.v1.TransactionExecutionOptions.encode(message.executionOptions, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified StartTransactionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.StartTransactionAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {google.spanner.executor.v1.IStartTransactionAction} message StartTransactionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StartTransactionAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a StartTransactionAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.StartTransactionAction} StartTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StartTransactionAction.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.spanner.executor.v1.StartTransactionAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.concurrency = $root.google.spanner.executor.v1.Concurrency.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.table && message.table.length)) + message.table = []; + message.table.push($root.google.spanner.executor.v1.TableMetadata.decode(reader, reader.uint32())); + break; + } + case 3: { + message.transactionSeed = reader.string(); + break; + } + case 4: { + message.executionOptions = $root.google.spanner.executor.v1.TransactionExecutionOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a StartTransactionAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.StartTransactionAction} StartTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StartTransactionAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a StartTransactionAction message. + * @function verify + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + StartTransactionAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.concurrency != null && message.hasOwnProperty("concurrency")) { + properties._concurrency = 1; + { + var error = $root.google.spanner.executor.v1.Concurrency.verify(message.concurrency); + if (error) + return "concurrency." + error; + } + } + if (message.table != null && message.hasOwnProperty("table")) { + if (!Array.isArray(message.table)) + return "table: array expected"; + for (var i = 0; i < message.table.length; ++i) { + var error = $root.google.spanner.executor.v1.TableMetadata.verify(message.table[i]); + if (error) + return "table." + error; + } + } + if (message.transactionSeed != null && message.hasOwnProperty("transactionSeed")) + if (!$util.isString(message.transactionSeed)) + return "transactionSeed: string expected"; + if (message.executionOptions != null && message.hasOwnProperty("executionOptions")) { + properties._executionOptions = 1; + { + var error = $root.google.spanner.executor.v1.TransactionExecutionOptions.verify(message.executionOptions); + if (error) + return "executionOptions." + error; + } + } + return null; + }; + + /** + * Creates a StartTransactionAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.StartTransactionAction} StartTransactionAction + */ + StartTransactionAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.StartTransactionAction) + return object; + var message = new $root.google.spanner.executor.v1.StartTransactionAction(); + if (object.concurrency != null) { + if (typeof object.concurrency !== "object") + throw TypeError(".google.spanner.executor.v1.StartTransactionAction.concurrency: object expected"); + message.concurrency = $root.google.spanner.executor.v1.Concurrency.fromObject(object.concurrency); + } + if (object.table) { + if (!Array.isArray(object.table)) + throw TypeError(".google.spanner.executor.v1.StartTransactionAction.table: array expected"); + message.table = []; + for (var i = 0; i < object.table.length; ++i) { + if (typeof object.table[i] !== "object") + throw TypeError(".google.spanner.executor.v1.StartTransactionAction.table: object expected"); + message.table[i] = $root.google.spanner.executor.v1.TableMetadata.fromObject(object.table[i]); + } + } + if (object.transactionSeed != null) + message.transactionSeed = String(object.transactionSeed); + if (object.executionOptions != null) { + if (typeof object.executionOptions !== "object") + throw TypeError(".google.spanner.executor.v1.StartTransactionAction.executionOptions: object expected"); + message.executionOptions = $root.google.spanner.executor.v1.TransactionExecutionOptions.fromObject(object.executionOptions); + } + return message; + }; + + /** + * Creates a plain object from a StartTransactionAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {google.spanner.executor.v1.StartTransactionAction} message StartTransactionAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StartTransactionAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.table = []; + if (options.defaults) + object.transactionSeed = ""; + if (message.concurrency != null && message.hasOwnProperty("concurrency")) { + object.concurrency = $root.google.spanner.executor.v1.Concurrency.toObject(message.concurrency, options); + if (options.oneofs) + object._concurrency = "concurrency"; + } + if (message.table && message.table.length) { + object.table = []; + for (var j = 0; j < message.table.length; ++j) + object.table[j] = $root.google.spanner.executor.v1.TableMetadata.toObject(message.table[j], options); + } + if (message.transactionSeed != null && message.hasOwnProperty("transactionSeed")) + object.transactionSeed = message.transactionSeed; + if (message.executionOptions != null && message.hasOwnProperty("executionOptions")) { + object.executionOptions = $root.google.spanner.executor.v1.TransactionExecutionOptions.toObject(message.executionOptions, options); + if (options.oneofs) + object._executionOptions = "executionOptions"; + } + return object; + }; + + /** + * Converts this StartTransactionAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.StartTransactionAction + * @instance + * @returns {Object.} JSON object + */ + StartTransactionAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StartTransactionAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.StartTransactionAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StartTransactionAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.StartTransactionAction"; + }; + + return StartTransactionAction; + })(); + + v1.Concurrency = (function() { + + /** + * Properties of a Concurrency. + * @memberof google.spanner.executor.v1 + * @interface IConcurrency + * @property {number|null} [stalenessSeconds] Concurrency stalenessSeconds + * @property {number|Long|null} [minReadTimestampMicros] Concurrency minReadTimestampMicros + * @property {number|null} [maxStalenessSeconds] Concurrency maxStalenessSeconds + * @property {number|Long|null} [exactTimestampMicros] Concurrency exactTimestampMicros + * @property {boolean|null} [strong] Concurrency strong + * @property {boolean|null} [batch] Concurrency batch + * @property {boolean|null} [snapshotEpochRead] Concurrency snapshotEpochRead + * @property {string|null} [snapshotEpochRootTable] Concurrency snapshotEpochRootTable + * @property {number|Long|null} [batchReadTimestampMicros] Concurrency batchReadTimestampMicros + */ + + /** + * Constructs a new Concurrency. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a Concurrency. + * @implements IConcurrency + * @constructor + * @param {google.spanner.executor.v1.IConcurrency=} [properties] Properties to set + */ + function Concurrency(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Concurrency stalenessSeconds. + * @member {number|null|undefined} stalenessSeconds + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.stalenessSeconds = null; + + /** + * Concurrency minReadTimestampMicros. + * @member {number|Long|null|undefined} minReadTimestampMicros + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.minReadTimestampMicros = null; + + /** + * Concurrency maxStalenessSeconds. + * @member {number|null|undefined} maxStalenessSeconds + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.maxStalenessSeconds = null; + + /** + * Concurrency exactTimestampMicros. + * @member {number|Long|null|undefined} exactTimestampMicros + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.exactTimestampMicros = null; + + /** + * Concurrency strong. + * @member {boolean|null|undefined} strong + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.strong = null; + + /** + * Concurrency batch. + * @member {boolean|null|undefined} batch + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.batch = null; + + /** + * Concurrency snapshotEpochRead. + * @member {boolean} snapshotEpochRead + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.snapshotEpochRead = false; + + /** + * Concurrency snapshotEpochRootTable. + * @member {string} snapshotEpochRootTable + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.snapshotEpochRootTable = ""; + + /** + * Concurrency batchReadTimestampMicros. + * @member {number|Long} batchReadTimestampMicros + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Concurrency.prototype.batchReadTimestampMicros = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Concurrency concurrencyMode. + * @member {"stalenessSeconds"|"minReadTimestampMicros"|"maxStalenessSeconds"|"exactTimestampMicros"|"strong"|"batch"|undefined} concurrencyMode + * @memberof google.spanner.executor.v1.Concurrency + * @instance + */ + Object.defineProperty(Concurrency.prototype, "concurrencyMode", { + get: $util.oneOfGetter($oneOfFields = ["stalenessSeconds", "minReadTimestampMicros", "maxStalenessSeconds", "exactTimestampMicros", "strong", "batch"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new Concurrency instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {google.spanner.executor.v1.IConcurrency=} [properties] Properties to set + * @returns {google.spanner.executor.v1.Concurrency} Concurrency instance + */ + Concurrency.create = function create(properties) { + return new Concurrency(properties); + }; + + /** + * Encodes the specified Concurrency message. Does not implicitly {@link google.spanner.executor.v1.Concurrency.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {google.spanner.executor.v1.IConcurrency} message Concurrency message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Concurrency.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.stalenessSeconds != null && Object.hasOwnProperty.call(message, "stalenessSeconds")) + writer.uint32(/* id 1, wireType 1 =*/9).double(message.stalenessSeconds); + if (message.minReadTimestampMicros != null && Object.hasOwnProperty.call(message, "minReadTimestampMicros")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.minReadTimestampMicros); + if (message.maxStalenessSeconds != null && Object.hasOwnProperty.call(message, "maxStalenessSeconds")) + writer.uint32(/* id 3, wireType 1 =*/25).double(message.maxStalenessSeconds); + if (message.exactTimestampMicros != null && Object.hasOwnProperty.call(message, "exactTimestampMicros")) + writer.uint32(/* id 4, wireType 0 =*/32).int64(message.exactTimestampMicros); + if (message.strong != null && Object.hasOwnProperty.call(message, "strong")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.strong); + if (message.batch != null && Object.hasOwnProperty.call(message, "batch")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.batch); + if (message.snapshotEpochRead != null && Object.hasOwnProperty.call(message, "snapshotEpochRead")) + writer.uint32(/* id 7, wireType 0 =*/56).bool(message.snapshotEpochRead); + if (message.snapshotEpochRootTable != null && Object.hasOwnProperty.call(message, "snapshotEpochRootTable")) + writer.uint32(/* id 8, wireType 2 =*/66).string(message.snapshotEpochRootTable); + if (message.batchReadTimestampMicros != null && Object.hasOwnProperty.call(message, "batchReadTimestampMicros")) + writer.uint32(/* id 9, wireType 0 =*/72).int64(message.batchReadTimestampMicros); + return writer; + }; + + /** + * Encodes the specified Concurrency message, length delimited. Does not implicitly {@link google.spanner.executor.v1.Concurrency.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {google.spanner.executor.v1.IConcurrency} message Concurrency message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Concurrency.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Concurrency message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.Concurrency} Concurrency + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Concurrency.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.spanner.executor.v1.Concurrency(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.stalenessSeconds = reader.double(); + break; + } + case 2: { + message.minReadTimestampMicros = reader.int64(); + break; + } + case 3: { + message.maxStalenessSeconds = reader.double(); + break; + } + case 4: { + message.exactTimestampMicros = reader.int64(); + break; + } + case 5: { + message.strong = reader.bool(); + break; + } + case 6: { + message.batch = reader.bool(); + break; + } + case 7: { + message.snapshotEpochRead = reader.bool(); + break; + } + case 8: { + message.snapshotEpochRootTable = reader.string(); + break; + } + case 9: { + message.batchReadTimestampMicros = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Concurrency message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.Concurrency} Concurrency + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Concurrency.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Concurrency message. + * @function verify + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Concurrency.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.stalenessSeconds != null && message.hasOwnProperty("stalenessSeconds")) { + properties.concurrencyMode = 1; + if (typeof message.stalenessSeconds !== "number") + return "stalenessSeconds: number expected"; + } + if (message.minReadTimestampMicros != null && message.hasOwnProperty("minReadTimestampMicros")) { + if (properties.concurrencyMode === 1) + return "concurrencyMode: multiple values"; + properties.concurrencyMode = 1; + if (!$util.isInteger(message.minReadTimestampMicros) && !(message.minReadTimestampMicros && $util.isInteger(message.minReadTimestampMicros.low) && $util.isInteger(message.minReadTimestampMicros.high))) + return "minReadTimestampMicros: integer|Long expected"; + } + if (message.maxStalenessSeconds != null && message.hasOwnProperty("maxStalenessSeconds")) { + if (properties.concurrencyMode === 1) + return "concurrencyMode: multiple values"; + properties.concurrencyMode = 1; + if (typeof message.maxStalenessSeconds !== "number") + return "maxStalenessSeconds: number expected"; + } + if (message.exactTimestampMicros != null && message.hasOwnProperty("exactTimestampMicros")) { + if (properties.concurrencyMode === 1) + return "concurrencyMode: multiple values"; + properties.concurrencyMode = 1; + if (!$util.isInteger(message.exactTimestampMicros) && !(message.exactTimestampMicros && $util.isInteger(message.exactTimestampMicros.low) && $util.isInteger(message.exactTimestampMicros.high))) + return "exactTimestampMicros: integer|Long expected"; + } + if (message.strong != null && message.hasOwnProperty("strong")) { + if (properties.concurrencyMode === 1) + return "concurrencyMode: multiple values"; + properties.concurrencyMode = 1; + if (typeof message.strong !== "boolean") + return "strong: boolean expected"; + } + if (message.batch != null && message.hasOwnProperty("batch")) { + if (properties.concurrencyMode === 1) + return "concurrencyMode: multiple values"; + properties.concurrencyMode = 1; + if (typeof message.batch !== "boolean") + return "batch: boolean expected"; + } + if (message.snapshotEpochRead != null && message.hasOwnProperty("snapshotEpochRead")) + if (typeof message.snapshotEpochRead !== "boolean") + return "snapshotEpochRead: boolean expected"; + if (message.snapshotEpochRootTable != null && message.hasOwnProperty("snapshotEpochRootTable")) + if (!$util.isString(message.snapshotEpochRootTable)) + return "snapshotEpochRootTable: string expected"; + if (message.batchReadTimestampMicros != null && message.hasOwnProperty("batchReadTimestampMicros")) + if (!$util.isInteger(message.batchReadTimestampMicros) && !(message.batchReadTimestampMicros && $util.isInteger(message.batchReadTimestampMicros.low) && $util.isInteger(message.batchReadTimestampMicros.high))) + return "batchReadTimestampMicros: integer|Long expected"; + return null; + }; + + /** + * Creates a Concurrency message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.Concurrency} Concurrency + */ + Concurrency.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.Concurrency) + return object; + var message = new $root.google.spanner.executor.v1.Concurrency(); + if (object.stalenessSeconds != null) + message.stalenessSeconds = Number(object.stalenessSeconds); + if (object.minReadTimestampMicros != null) + if ($util.Long) + (message.minReadTimestampMicros = $util.Long.fromValue(object.minReadTimestampMicros)).unsigned = false; + else if (typeof object.minReadTimestampMicros === "string") + message.minReadTimestampMicros = parseInt(object.minReadTimestampMicros, 10); + else if (typeof object.minReadTimestampMicros === "number") + message.minReadTimestampMicros = object.minReadTimestampMicros; + else if (typeof object.minReadTimestampMicros === "object") + message.minReadTimestampMicros = new $util.LongBits(object.minReadTimestampMicros.low >>> 0, object.minReadTimestampMicros.high >>> 0).toNumber(); + if (object.maxStalenessSeconds != null) + message.maxStalenessSeconds = Number(object.maxStalenessSeconds); + if (object.exactTimestampMicros != null) + if ($util.Long) + (message.exactTimestampMicros = $util.Long.fromValue(object.exactTimestampMicros)).unsigned = false; + else if (typeof object.exactTimestampMicros === "string") + message.exactTimestampMicros = parseInt(object.exactTimestampMicros, 10); + else if (typeof object.exactTimestampMicros === "number") + message.exactTimestampMicros = object.exactTimestampMicros; + else if (typeof object.exactTimestampMicros === "object") + message.exactTimestampMicros = new $util.LongBits(object.exactTimestampMicros.low >>> 0, object.exactTimestampMicros.high >>> 0).toNumber(); + if (object.strong != null) + message.strong = Boolean(object.strong); + if (object.batch != null) + message.batch = Boolean(object.batch); + if (object.snapshotEpochRead != null) + message.snapshotEpochRead = Boolean(object.snapshotEpochRead); + if (object.snapshotEpochRootTable != null) + message.snapshotEpochRootTable = String(object.snapshotEpochRootTable); + if (object.batchReadTimestampMicros != null) + if ($util.Long) + (message.batchReadTimestampMicros = $util.Long.fromValue(object.batchReadTimestampMicros)).unsigned = false; + else if (typeof object.batchReadTimestampMicros === "string") + message.batchReadTimestampMicros = parseInt(object.batchReadTimestampMicros, 10); + else if (typeof object.batchReadTimestampMicros === "number") + message.batchReadTimestampMicros = object.batchReadTimestampMicros; + else if (typeof object.batchReadTimestampMicros === "object") + message.batchReadTimestampMicros = new $util.LongBits(object.batchReadTimestampMicros.low >>> 0, object.batchReadTimestampMicros.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a Concurrency message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {google.spanner.executor.v1.Concurrency} message Concurrency + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Concurrency.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.snapshotEpochRead = false; + object.snapshotEpochRootTable = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.batchReadTimestampMicros = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.batchReadTimestampMicros = options.longs === String ? "0" : 0; + } + if (message.stalenessSeconds != null && message.hasOwnProperty("stalenessSeconds")) { + object.stalenessSeconds = options.json && !isFinite(message.stalenessSeconds) ? String(message.stalenessSeconds) : message.stalenessSeconds; + if (options.oneofs) + object.concurrencyMode = "stalenessSeconds"; + } + if (message.minReadTimestampMicros != null && message.hasOwnProperty("minReadTimestampMicros")) { + if (typeof message.minReadTimestampMicros === "number") + object.minReadTimestampMicros = options.longs === String ? String(message.minReadTimestampMicros) : message.minReadTimestampMicros; + else + object.minReadTimestampMicros = options.longs === String ? $util.Long.prototype.toString.call(message.minReadTimestampMicros) : options.longs === Number ? new $util.LongBits(message.minReadTimestampMicros.low >>> 0, message.minReadTimestampMicros.high >>> 0).toNumber() : message.minReadTimestampMicros; + if (options.oneofs) + object.concurrencyMode = "minReadTimestampMicros"; + } + if (message.maxStalenessSeconds != null && message.hasOwnProperty("maxStalenessSeconds")) { + object.maxStalenessSeconds = options.json && !isFinite(message.maxStalenessSeconds) ? String(message.maxStalenessSeconds) : message.maxStalenessSeconds; + if (options.oneofs) + object.concurrencyMode = "maxStalenessSeconds"; + } + if (message.exactTimestampMicros != null && message.hasOwnProperty("exactTimestampMicros")) { + if (typeof message.exactTimestampMicros === "number") + object.exactTimestampMicros = options.longs === String ? String(message.exactTimestampMicros) : message.exactTimestampMicros; + else + object.exactTimestampMicros = options.longs === String ? $util.Long.prototype.toString.call(message.exactTimestampMicros) : options.longs === Number ? new $util.LongBits(message.exactTimestampMicros.low >>> 0, message.exactTimestampMicros.high >>> 0).toNumber() : message.exactTimestampMicros; + if (options.oneofs) + object.concurrencyMode = "exactTimestampMicros"; + } + if (message.strong != null && message.hasOwnProperty("strong")) { + object.strong = message.strong; + if (options.oneofs) + object.concurrencyMode = "strong"; + } + if (message.batch != null && message.hasOwnProperty("batch")) { + object.batch = message.batch; + if (options.oneofs) + object.concurrencyMode = "batch"; + } + if (message.snapshotEpochRead != null && message.hasOwnProperty("snapshotEpochRead")) + object.snapshotEpochRead = message.snapshotEpochRead; + if (message.snapshotEpochRootTable != null && message.hasOwnProperty("snapshotEpochRootTable")) + object.snapshotEpochRootTable = message.snapshotEpochRootTable; + if (message.batchReadTimestampMicros != null && message.hasOwnProperty("batchReadTimestampMicros")) + if (typeof message.batchReadTimestampMicros === "number") + object.batchReadTimestampMicros = options.longs === String ? String(message.batchReadTimestampMicros) : message.batchReadTimestampMicros; + else + object.batchReadTimestampMicros = options.longs === String ? $util.Long.prototype.toString.call(message.batchReadTimestampMicros) : options.longs === Number ? new $util.LongBits(message.batchReadTimestampMicros.low >>> 0, message.batchReadTimestampMicros.high >>> 0).toNumber() : message.batchReadTimestampMicros; + return object; + }; + + /** + * Converts this Concurrency to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.Concurrency + * @instance + * @returns {Object.} JSON object + */ + Concurrency.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Concurrency + * @function getTypeUrl + * @memberof google.spanner.executor.v1.Concurrency + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Concurrency.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.Concurrency"; + }; + + return Concurrency; + })(); + + v1.TableMetadata = (function() { + + /** + * Properties of a TableMetadata. + * @memberof google.spanner.executor.v1 + * @interface ITableMetadata + * @property {string|null} [name] TableMetadata name + * @property {Array.|null} [column] TableMetadata column + * @property {Array.|null} [keyColumn] TableMetadata keyColumn + */ + + /** + * Constructs a new TableMetadata. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a TableMetadata. + * @implements ITableMetadata + * @constructor + * @param {google.spanner.executor.v1.ITableMetadata=} [properties] Properties to set + */ + function TableMetadata(properties) { + this.column = []; + this.keyColumn = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TableMetadata name. + * @member {string} name + * @memberof google.spanner.executor.v1.TableMetadata + * @instance + */ + TableMetadata.prototype.name = ""; + + /** + * TableMetadata column. + * @member {Array.} column + * @memberof google.spanner.executor.v1.TableMetadata + * @instance + */ + TableMetadata.prototype.column = $util.emptyArray; + + /** + * TableMetadata keyColumn. + * @member {Array.} keyColumn + * @memberof google.spanner.executor.v1.TableMetadata + * @instance + */ + TableMetadata.prototype.keyColumn = $util.emptyArray; + + /** + * Creates a new TableMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {google.spanner.executor.v1.ITableMetadata=} [properties] Properties to set + * @returns {google.spanner.executor.v1.TableMetadata} TableMetadata instance + */ + TableMetadata.create = function create(properties) { + return new TableMetadata(properties); + }; + + /** + * Encodes the specified TableMetadata message. Does not implicitly {@link google.spanner.executor.v1.TableMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {google.spanner.executor.v1.ITableMetadata} message TableMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.column != null && message.column.length) + for (var i = 0; i < message.column.length; ++i) + $root.google.spanner.executor.v1.ColumnMetadata.encode(message.column[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.keyColumn != null && message.keyColumn.length) + for (var i = 0; i < message.keyColumn.length; ++i) + $root.google.spanner.executor.v1.ColumnMetadata.encode(message.keyColumn[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified TableMetadata message, length delimited. Does not implicitly {@link google.spanner.executor.v1.TableMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {google.spanner.executor.v1.ITableMetadata} message TableMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TableMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.TableMetadata} TableMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableMetadata.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.spanner.executor.v1.TableMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + if (!(message.column && message.column.length)) + message.column = []; + message.column.push($root.google.spanner.executor.v1.ColumnMetadata.decode(reader, reader.uint32())); + break; + } + case 3: { + if (!(message.keyColumn && message.keyColumn.length)) + message.keyColumn = []; + message.keyColumn.push($root.google.spanner.executor.v1.ColumnMetadata.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TableMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.TableMetadata} TableMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TableMetadata message. + * @function verify + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TableMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.column != null && message.hasOwnProperty("column")) { + if (!Array.isArray(message.column)) + return "column: array expected"; + for (var i = 0; i < message.column.length; ++i) { + var error = $root.google.spanner.executor.v1.ColumnMetadata.verify(message.column[i]); + if (error) + return "column." + error; + } + } + if (message.keyColumn != null && message.hasOwnProperty("keyColumn")) { + if (!Array.isArray(message.keyColumn)) + return "keyColumn: array expected"; + for (var i = 0; i < message.keyColumn.length; ++i) { + var error = $root.google.spanner.executor.v1.ColumnMetadata.verify(message.keyColumn[i]); + if (error) + return "keyColumn." + error; + } + } + return null; + }; + + /** + * Creates a TableMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.TableMetadata} TableMetadata + */ + TableMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.TableMetadata) + return object; + var message = new $root.google.spanner.executor.v1.TableMetadata(); + if (object.name != null) + message.name = String(object.name); + if (object.column) { + if (!Array.isArray(object.column)) + throw TypeError(".google.spanner.executor.v1.TableMetadata.column: array expected"); + message.column = []; + for (var i = 0; i < object.column.length; ++i) { + if (typeof object.column[i] !== "object") + throw TypeError(".google.spanner.executor.v1.TableMetadata.column: object expected"); + message.column[i] = $root.google.spanner.executor.v1.ColumnMetadata.fromObject(object.column[i]); + } + } + if (object.keyColumn) { + if (!Array.isArray(object.keyColumn)) + throw TypeError(".google.spanner.executor.v1.TableMetadata.keyColumn: array expected"); + message.keyColumn = []; + for (var i = 0; i < object.keyColumn.length; ++i) { + if (typeof object.keyColumn[i] !== "object") + throw TypeError(".google.spanner.executor.v1.TableMetadata.keyColumn: object expected"); + message.keyColumn[i] = $root.google.spanner.executor.v1.ColumnMetadata.fromObject(object.keyColumn[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a TableMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {google.spanner.executor.v1.TableMetadata} message TableMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TableMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.column = []; + object.keyColumn = []; + } + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.column && message.column.length) { + object.column = []; + for (var j = 0; j < message.column.length; ++j) + object.column[j] = $root.google.spanner.executor.v1.ColumnMetadata.toObject(message.column[j], options); + } + if (message.keyColumn && message.keyColumn.length) { + object.keyColumn = []; + for (var j = 0; j < message.keyColumn.length; ++j) + object.keyColumn[j] = $root.google.spanner.executor.v1.ColumnMetadata.toObject(message.keyColumn[j], options); + } + return object; + }; + + /** + * Converts this TableMetadata to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.TableMetadata + * @instance + * @returns {Object.} JSON object + */ + TableMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TableMetadata + * @function getTypeUrl + * @memberof google.spanner.executor.v1.TableMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TableMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.TableMetadata"; + }; + + return TableMetadata; + })(); + + v1.ColumnMetadata = (function() { + + /** + * Properties of a ColumnMetadata. + * @memberof google.spanner.executor.v1 + * @interface IColumnMetadata + * @property {string|null} [name] ColumnMetadata name + * @property {google.spanner.v1.IType|null} [type] ColumnMetadata type + */ + + /** + * Constructs a new ColumnMetadata. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ColumnMetadata. + * @implements IColumnMetadata + * @constructor + * @param {google.spanner.executor.v1.IColumnMetadata=} [properties] Properties to set + */ + function ColumnMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ColumnMetadata name. + * @member {string} name + * @memberof google.spanner.executor.v1.ColumnMetadata + * @instance + */ + ColumnMetadata.prototype.name = ""; + + /** + * ColumnMetadata type. + * @member {google.spanner.v1.IType|null|undefined} type + * @memberof google.spanner.executor.v1.ColumnMetadata + * @instance + */ + ColumnMetadata.prototype.type = null; + + /** + * Creates a new ColumnMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {google.spanner.executor.v1.IColumnMetadata=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ColumnMetadata} ColumnMetadata instance + */ + ColumnMetadata.create = function create(properties) { + return new ColumnMetadata(properties); + }; + + /** + * Encodes the specified ColumnMetadata message. Does not implicitly {@link google.spanner.executor.v1.ColumnMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {google.spanner.executor.v1.IColumnMetadata} message ColumnMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ColumnMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + $root.google.spanner.v1.Type.encode(message.type, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ColumnMetadata message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ColumnMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {google.spanner.executor.v1.IColumnMetadata} message ColumnMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ColumnMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ColumnMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ColumnMetadata} ColumnMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ColumnMetadata.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.spanner.executor.v1.ColumnMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.type = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ColumnMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ColumnMetadata} ColumnMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ColumnMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ColumnMetadata message. + * @function verify + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ColumnMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.type != null && message.hasOwnProperty("type")) { + var error = $root.google.spanner.v1.Type.verify(message.type); + if (error) + return "type." + error; + } + return null; + }; + + /** + * Creates a ColumnMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ColumnMetadata} ColumnMetadata + */ + ColumnMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ColumnMetadata) + return object; + var message = new $root.google.spanner.executor.v1.ColumnMetadata(); + if (object.name != null) + message.name = String(object.name); + if (object.type != null) { + if (typeof object.type !== "object") + throw TypeError(".google.spanner.executor.v1.ColumnMetadata.type: object expected"); + message.type = $root.google.spanner.v1.Type.fromObject(object.type); + } + return message; + }; + + /** + * Creates a plain object from a ColumnMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {google.spanner.executor.v1.ColumnMetadata} message ColumnMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ColumnMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.type = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.type != null && message.hasOwnProperty("type")) + object.type = $root.google.spanner.v1.Type.toObject(message.type, options); + return object; + }; + + /** + * Converts this ColumnMetadata to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ColumnMetadata + * @instance + * @returns {Object.} JSON object + */ + ColumnMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ColumnMetadata + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ColumnMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ColumnMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ColumnMetadata"; + }; + + return ColumnMetadata; + })(); + + v1.TransactionExecutionOptions = (function() { + + /** + * Properties of a TransactionExecutionOptions. + * @memberof google.spanner.executor.v1 + * @interface ITransactionExecutionOptions + * @property {boolean|null} [optimistic] TransactionExecutionOptions optimistic + * @property {boolean|null} [excludeFromChangeStreams] TransactionExecutionOptions excludeFromChangeStreams + * @property {boolean|null} [serializableOptimistic] TransactionExecutionOptions serializableOptimistic + * @property {boolean|null} [snapshotIsolationOptimistic] TransactionExecutionOptions snapshotIsolationOptimistic + * @property {boolean|null} [snapshotIsolationPessimistic] TransactionExecutionOptions snapshotIsolationPessimistic + * @property {boolean|null} [excludeTxnFromChangeStreams] TransactionExecutionOptions excludeTxnFromChangeStreams + */ + + /** + * Constructs a new TransactionExecutionOptions. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a TransactionExecutionOptions. + * @implements ITransactionExecutionOptions + * @constructor + * @param {google.spanner.executor.v1.ITransactionExecutionOptions=} [properties] Properties to set + */ + function TransactionExecutionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TransactionExecutionOptions optimistic. + * @member {boolean} optimistic + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @instance + */ + TransactionExecutionOptions.prototype.optimistic = false; + + /** + * TransactionExecutionOptions excludeFromChangeStreams. + * @member {boolean} excludeFromChangeStreams + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @instance + */ + TransactionExecutionOptions.prototype.excludeFromChangeStreams = false; + + /** + * TransactionExecutionOptions serializableOptimistic. + * @member {boolean} serializableOptimistic + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @instance + */ + TransactionExecutionOptions.prototype.serializableOptimistic = false; + + /** + * TransactionExecutionOptions snapshotIsolationOptimistic. + * @member {boolean} snapshotIsolationOptimistic + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @instance + */ + TransactionExecutionOptions.prototype.snapshotIsolationOptimistic = false; + + /** + * TransactionExecutionOptions snapshotIsolationPessimistic. + * @member {boolean} snapshotIsolationPessimistic + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @instance + */ + TransactionExecutionOptions.prototype.snapshotIsolationPessimistic = false; + + /** + * TransactionExecutionOptions excludeTxnFromChangeStreams. + * @member {boolean} excludeTxnFromChangeStreams + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @instance + */ + TransactionExecutionOptions.prototype.excludeTxnFromChangeStreams = false; + + /** + * Creates a new TransactionExecutionOptions instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {google.spanner.executor.v1.ITransactionExecutionOptions=} [properties] Properties to set + * @returns {google.spanner.executor.v1.TransactionExecutionOptions} TransactionExecutionOptions instance + */ + TransactionExecutionOptions.create = function create(properties) { + return new TransactionExecutionOptions(properties); + }; + + /** + * Encodes the specified TransactionExecutionOptions message. Does not implicitly {@link google.spanner.executor.v1.TransactionExecutionOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {google.spanner.executor.v1.ITransactionExecutionOptions} message TransactionExecutionOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TransactionExecutionOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.optimistic != null && Object.hasOwnProperty.call(message, "optimistic")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.optimistic); + if (message.excludeFromChangeStreams != null && Object.hasOwnProperty.call(message, "excludeFromChangeStreams")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.excludeFromChangeStreams); + if (message.serializableOptimistic != null && Object.hasOwnProperty.call(message, "serializableOptimistic")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.serializableOptimistic); + if (message.snapshotIsolationOptimistic != null && Object.hasOwnProperty.call(message, "snapshotIsolationOptimistic")) + writer.uint32(/* id 4, wireType 0 =*/32).bool(message.snapshotIsolationOptimistic); + if (message.snapshotIsolationPessimistic != null && Object.hasOwnProperty.call(message, "snapshotIsolationPessimistic")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.snapshotIsolationPessimistic); + if (message.excludeTxnFromChangeStreams != null && Object.hasOwnProperty.call(message, "excludeTxnFromChangeStreams")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.excludeTxnFromChangeStreams); + return writer; + }; + + /** + * Encodes the specified TransactionExecutionOptions message, length delimited. Does not implicitly {@link google.spanner.executor.v1.TransactionExecutionOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {google.spanner.executor.v1.ITransactionExecutionOptions} message TransactionExecutionOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TransactionExecutionOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TransactionExecutionOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.TransactionExecutionOptions} TransactionExecutionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TransactionExecutionOptions.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.spanner.executor.v1.TransactionExecutionOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.optimistic = reader.bool(); + break; + } + case 2: { + message.excludeFromChangeStreams = reader.bool(); + break; + } + case 3: { + message.serializableOptimistic = reader.bool(); + break; + } + case 4: { + message.snapshotIsolationOptimistic = reader.bool(); + break; + } + case 5: { + message.snapshotIsolationPessimistic = reader.bool(); + break; + } + case 6: { + message.excludeTxnFromChangeStreams = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TransactionExecutionOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.TransactionExecutionOptions} TransactionExecutionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TransactionExecutionOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TransactionExecutionOptions message. + * @function verify + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TransactionExecutionOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.optimistic != null && message.hasOwnProperty("optimistic")) + if (typeof message.optimistic !== "boolean") + return "optimistic: boolean expected"; + if (message.excludeFromChangeStreams != null && message.hasOwnProperty("excludeFromChangeStreams")) + if (typeof message.excludeFromChangeStreams !== "boolean") + return "excludeFromChangeStreams: boolean expected"; + if (message.serializableOptimistic != null && message.hasOwnProperty("serializableOptimistic")) + if (typeof message.serializableOptimistic !== "boolean") + return "serializableOptimistic: boolean expected"; + if (message.snapshotIsolationOptimistic != null && message.hasOwnProperty("snapshotIsolationOptimistic")) + if (typeof message.snapshotIsolationOptimistic !== "boolean") + return "snapshotIsolationOptimistic: boolean expected"; + if (message.snapshotIsolationPessimistic != null && message.hasOwnProperty("snapshotIsolationPessimistic")) + if (typeof message.snapshotIsolationPessimistic !== "boolean") + return "snapshotIsolationPessimistic: boolean expected"; + if (message.excludeTxnFromChangeStreams != null && message.hasOwnProperty("excludeTxnFromChangeStreams")) + if (typeof message.excludeTxnFromChangeStreams !== "boolean") + return "excludeTxnFromChangeStreams: boolean expected"; + return null; + }; + + /** + * Creates a TransactionExecutionOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.TransactionExecutionOptions} TransactionExecutionOptions + */ + TransactionExecutionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.TransactionExecutionOptions) + return object; + var message = new $root.google.spanner.executor.v1.TransactionExecutionOptions(); + if (object.optimistic != null) + message.optimistic = Boolean(object.optimistic); + if (object.excludeFromChangeStreams != null) + message.excludeFromChangeStreams = Boolean(object.excludeFromChangeStreams); + if (object.serializableOptimistic != null) + message.serializableOptimistic = Boolean(object.serializableOptimistic); + if (object.snapshotIsolationOptimistic != null) + message.snapshotIsolationOptimistic = Boolean(object.snapshotIsolationOptimistic); + if (object.snapshotIsolationPessimistic != null) + message.snapshotIsolationPessimistic = Boolean(object.snapshotIsolationPessimistic); + if (object.excludeTxnFromChangeStreams != null) + message.excludeTxnFromChangeStreams = Boolean(object.excludeTxnFromChangeStreams); + return message; + }; + + /** + * Creates a plain object from a TransactionExecutionOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {google.spanner.executor.v1.TransactionExecutionOptions} message TransactionExecutionOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TransactionExecutionOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.optimistic = false; + object.excludeFromChangeStreams = false; + object.serializableOptimistic = false; + object.snapshotIsolationOptimistic = false; + object.snapshotIsolationPessimistic = false; + object.excludeTxnFromChangeStreams = false; + } + if (message.optimistic != null && message.hasOwnProperty("optimistic")) + object.optimistic = message.optimistic; + if (message.excludeFromChangeStreams != null && message.hasOwnProperty("excludeFromChangeStreams")) + object.excludeFromChangeStreams = message.excludeFromChangeStreams; + if (message.serializableOptimistic != null && message.hasOwnProperty("serializableOptimistic")) + object.serializableOptimistic = message.serializableOptimistic; + if (message.snapshotIsolationOptimistic != null && message.hasOwnProperty("snapshotIsolationOptimistic")) + object.snapshotIsolationOptimistic = message.snapshotIsolationOptimistic; + if (message.snapshotIsolationPessimistic != null && message.hasOwnProperty("snapshotIsolationPessimistic")) + object.snapshotIsolationPessimistic = message.snapshotIsolationPessimistic; + if (message.excludeTxnFromChangeStreams != null && message.hasOwnProperty("excludeTxnFromChangeStreams")) + object.excludeTxnFromChangeStreams = message.excludeTxnFromChangeStreams; + return object; + }; + + /** + * Converts this TransactionExecutionOptions to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @instance + * @returns {Object.} JSON object + */ + TransactionExecutionOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TransactionExecutionOptions + * @function getTypeUrl + * @memberof google.spanner.executor.v1.TransactionExecutionOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TransactionExecutionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.TransactionExecutionOptions"; + }; + + return TransactionExecutionOptions; + })(); + + v1.FinishTransactionAction = (function() { + + /** + * Properties of a FinishTransactionAction. + * @memberof google.spanner.executor.v1 + * @interface IFinishTransactionAction + * @property {google.spanner.executor.v1.FinishTransactionAction.Mode|null} [mode] FinishTransactionAction mode + */ + + /** + * Constructs a new FinishTransactionAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a FinishTransactionAction. + * @implements IFinishTransactionAction + * @constructor + * @param {google.spanner.executor.v1.IFinishTransactionAction=} [properties] Properties to set + */ + function FinishTransactionAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FinishTransactionAction mode. + * @member {google.spanner.executor.v1.FinishTransactionAction.Mode} mode + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @instance + */ + FinishTransactionAction.prototype.mode = 0; + + /** + * Creates a new FinishTransactionAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {google.spanner.executor.v1.IFinishTransactionAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.FinishTransactionAction} FinishTransactionAction instance + */ + FinishTransactionAction.create = function create(properties) { + return new FinishTransactionAction(properties); + }; + + /** + * Encodes the specified FinishTransactionAction message. Does not implicitly {@link google.spanner.executor.v1.FinishTransactionAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {google.spanner.executor.v1.IFinishTransactionAction} message FinishTransactionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FinishTransactionAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.mode != null && Object.hasOwnProperty.call(message, "mode")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.mode); + return writer; + }; + + /** + * Encodes the specified FinishTransactionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.FinishTransactionAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {google.spanner.executor.v1.IFinishTransactionAction} message FinishTransactionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FinishTransactionAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FinishTransactionAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.FinishTransactionAction} FinishTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FinishTransactionAction.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.spanner.executor.v1.FinishTransactionAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.mode = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FinishTransactionAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.FinishTransactionAction} FinishTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FinishTransactionAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FinishTransactionAction message. + * @function verify + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FinishTransactionAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.mode != null && message.hasOwnProperty("mode")) + switch (message.mode) { + default: + return "mode: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates a FinishTransactionAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.FinishTransactionAction} FinishTransactionAction + */ + FinishTransactionAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.FinishTransactionAction) + return object; + var message = new $root.google.spanner.executor.v1.FinishTransactionAction(); + switch (object.mode) { + default: + if (typeof object.mode === "number") { + message.mode = object.mode; + break; + } + break; + case "MODE_UNSPECIFIED": + case 0: + message.mode = 0; + break; + case "COMMIT": + case 1: + message.mode = 1; + break; + case "ABANDON": + case 2: + message.mode = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a FinishTransactionAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {google.spanner.executor.v1.FinishTransactionAction} message FinishTransactionAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FinishTransactionAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.mode = options.enums === String ? "MODE_UNSPECIFIED" : 0; + if (message.mode != null && message.hasOwnProperty("mode")) + object.mode = options.enums === String ? $root.google.spanner.executor.v1.FinishTransactionAction.Mode[message.mode] === undefined ? message.mode : $root.google.spanner.executor.v1.FinishTransactionAction.Mode[message.mode] : message.mode; + return object; + }; + + /** + * Converts this FinishTransactionAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @instance + * @returns {Object.} JSON object + */ + FinishTransactionAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FinishTransactionAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.FinishTransactionAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FinishTransactionAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.FinishTransactionAction"; + }; + + /** + * Mode enum. + * @name google.spanner.executor.v1.FinishTransactionAction.Mode + * @enum {number} + * @property {number} MODE_UNSPECIFIED=0 MODE_UNSPECIFIED value + * @property {number} COMMIT=1 COMMIT value + * @property {number} ABANDON=2 ABANDON value + */ + FinishTransactionAction.Mode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MODE_UNSPECIFIED"] = 0; + values[valuesById[1] = "COMMIT"] = 1; + values[valuesById[2] = "ABANDON"] = 2; + return values; + })(); + + return FinishTransactionAction; + })(); + + v1.AdminAction = (function() { + + /** + * Properties of an AdminAction. + * @memberof google.spanner.executor.v1 + * @interface IAdminAction + * @property {google.spanner.executor.v1.ICreateUserInstanceConfigAction|null} [createUserInstanceConfig] AdminAction createUserInstanceConfig + * @property {google.spanner.executor.v1.IUpdateUserInstanceConfigAction|null} [updateUserInstanceConfig] AdminAction updateUserInstanceConfig + * @property {google.spanner.executor.v1.IDeleteUserInstanceConfigAction|null} [deleteUserInstanceConfig] AdminAction deleteUserInstanceConfig + * @property {google.spanner.executor.v1.IGetCloudInstanceConfigAction|null} [getCloudInstanceConfig] AdminAction getCloudInstanceConfig + * @property {google.spanner.executor.v1.IListCloudInstanceConfigsAction|null} [listInstanceConfigs] AdminAction listInstanceConfigs + * @property {google.spanner.executor.v1.ICreateCloudInstanceAction|null} [createCloudInstance] AdminAction createCloudInstance + * @property {google.spanner.executor.v1.IUpdateCloudInstanceAction|null} [updateCloudInstance] AdminAction updateCloudInstance + * @property {google.spanner.executor.v1.IDeleteCloudInstanceAction|null} [deleteCloudInstance] AdminAction deleteCloudInstance + * @property {google.spanner.executor.v1.IListCloudInstancesAction|null} [listCloudInstances] AdminAction listCloudInstances + * @property {google.spanner.executor.v1.IGetCloudInstanceAction|null} [getCloudInstance] AdminAction getCloudInstance + * @property {google.spanner.executor.v1.ICreateCloudDatabaseAction|null} [createCloudDatabase] AdminAction createCloudDatabase + * @property {google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction|null} [updateCloudDatabaseDdl] AdminAction updateCloudDatabaseDdl + * @property {google.spanner.executor.v1.IUpdateCloudDatabaseAction|null} [updateCloudDatabase] AdminAction updateCloudDatabase + * @property {google.spanner.executor.v1.IDropCloudDatabaseAction|null} [dropCloudDatabase] AdminAction dropCloudDatabase + * @property {google.spanner.executor.v1.IListCloudDatabasesAction|null} [listCloudDatabases] AdminAction listCloudDatabases + * @property {google.spanner.executor.v1.IListCloudDatabaseOperationsAction|null} [listCloudDatabaseOperations] AdminAction listCloudDatabaseOperations + * @property {google.spanner.executor.v1.IRestoreCloudDatabaseAction|null} [restoreCloudDatabase] AdminAction restoreCloudDatabase + * @property {google.spanner.executor.v1.IGetCloudDatabaseAction|null} [getCloudDatabase] AdminAction getCloudDatabase + * @property {google.spanner.executor.v1.ICreateCloudBackupAction|null} [createCloudBackup] AdminAction createCloudBackup + * @property {google.spanner.executor.v1.ICopyCloudBackupAction|null} [copyCloudBackup] AdminAction copyCloudBackup + * @property {google.spanner.executor.v1.IGetCloudBackupAction|null} [getCloudBackup] AdminAction getCloudBackup + * @property {google.spanner.executor.v1.IUpdateCloudBackupAction|null} [updateCloudBackup] AdminAction updateCloudBackup + * @property {google.spanner.executor.v1.IDeleteCloudBackupAction|null} [deleteCloudBackup] AdminAction deleteCloudBackup + * @property {google.spanner.executor.v1.IListCloudBackupsAction|null} [listCloudBackups] AdminAction listCloudBackups + * @property {google.spanner.executor.v1.IListCloudBackupOperationsAction|null} [listCloudBackupOperations] AdminAction listCloudBackupOperations + * @property {google.spanner.executor.v1.IGetOperationAction|null} [getOperation] AdminAction getOperation + * @property {google.spanner.executor.v1.ICancelOperationAction|null} [cancelOperation] AdminAction cancelOperation + * @property {google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction|null} [changeQuorumCloudDatabase] AdminAction changeQuorumCloudDatabase + * @property {google.spanner.executor.v1.IAddSplitPointsAction|null} [addSplitPoints] AdminAction addSplitPoints + */ + + /** + * Constructs a new AdminAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an AdminAction. + * @implements IAdminAction + * @constructor + * @param {google.spanner.executor.v1.IAdminAction=} [properties] Properties to set + */ + function AdminAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AdminAction createUserInstanceConfig. + * @member {google.spanner.executor.v1.ICreateUserInstanceConfigAction|null|undefined} createUserInstanceConfig + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.createUserInstanceConfig = null; + + /** + * AdminAction updateUserInstanceConfig. + * @member {google.spanner.executor.v1.IUpdateUserInstanceConfigAction|null|undefined} updateUserInstanceConfig + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.updateUserInstanceConfig = null; + + /** + * AdminAction deleteUserInstanceConfig. + * @member {google.spanner.executor.v1.IDeleteUserInstanceConfigAction|null|undefined} deleteUserInstanceConfig + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.deleteUserInstanceConfig = null; + + /** + * AdminAction getCloudInstanceConfig. + * @member {google.spanner.executor.v1.IGetCloudInstanceConfigAction|null|undefined} getCloudInstanceConfig + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.getCloudInstanceConfig = null; + + /** + * AdminAction listInstanceConfigs. + * @member {google.spanner.executor.v1.IListCloudInstanceConfigsAction|null|undefined} listInstanceConfigs + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.listInstanceConfigs = null; + + /** + * AdminAction createCloudInstance. + * @member {google.spanner.executor.v1.ICreateCloudInstanceAction|null|undefined} createCloudInstance + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.createCloudInstance = null; + + /** + * AdminAction updateCloudInstance. + * @member {google.spanner.executor.v1.IUpdateCloudInstanceAction|null|undefined} updateCloudInstance + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.updateCloudInstance = null; + + /** + * AdminAction deleteCloudInstance. + * @member {google.spanner.executor.v1.IDeleteCloudInstanceAction|null|undefined} deleteCloudInstance + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.deleteCloudInstance = null; + + /** + * AdminAction listCloudInstances. + * @member {google.spanner.executor.v1.IListCloudInstancesAction|null|undefined} listCloudInstances + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.listCloudInstances = null; + + /** + * AdminAction getCloudInstance. + * @member {google.spanner.executor.v1.IGetCloudInstanceAction|null|undefined} getCloudInstance + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.getCloudInstance = null; + + /** + * AdminAction createCloudDatabase. + * @member {google.spanner.executor.v1.ICreateCloudDatabaseAction|null|undefined} createCloudDatabase + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.createCloudDatabase = null; + + /** + * AdminAction updateCloudDatabaseDdl. + * @member {google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction|null|undefined} updateCloudDatabaseDdl + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.updateCloudDatabaseDdl = null; + + /** + * AdminAction updateCloudDatabase. + * @member {google.spanner.executor.v1.IUpdateCloudDatabaseAction|null|undefined} updateCloudDatabase + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.updateCloudDatabase = null; + + /** + * AdminAction dropCloudDatabase. + * @member {google.spanner.executor.v1.IDropCloudDatabaseAction|null|undefined} dropCloudDatabase + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.dropCloudDatabase = null; + + /** + * AdminAction listCloudDatabases. + * @member {google.spanner.executor.v1.IListCloudDatabasesAction|null|undefined} listCloudDatabases + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.listCloudDatabases = null; + + /** + * AdminAction listCloudDatabaseOperations. + * @member {google.spanner.executor.v1.IListCloudDatabaseOperationsAction|null|undefined} listCloudDatabaseOperations + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.listCloudDatabaseOperations = null; + + /** + * AdminAction restoreCloudDatabase. + * @member {google.spanner.executor.v1.IRestoreCloudDatabaseAction|null|undefined} restoreCloudDatabase + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.restoreCloudDatabase = null; + + /** + * AdminAction getCloudDatabase. + * @member {google.spanner.executor.v1.IGetCloudDatabaseAction|null|undefined} getCloudDatabase + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.getCloudDatabase = null; + + /** + * AdminAction createCloudBackup. + * @member {google.spanner.executor.v1.ICreateCloudBackupAction|null|undefined} createCloudBackup + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.createCloudBackup = null; + + /** + * AdminAction copyCloudBackup. + * @member {google.spanner.executor.v1.ICopyCloudBackupAction|null|undefined} copyCloudBackup + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.copyCloudBackup = null; + + /** + * AdminAction getCloudBackup. + * @member {google.spanner.executor.v1.IGetCloudBackupAction|null|undefined} getCloudBackup + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.getCloudBackup = null; + + /** + * AdminAction updateCloudBackup. + * @member {google.spanner.executor.v1.IUpdateCloudBackupAction|null|undefined} updateCloudBackup + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.updateCloudBackup = null; + + /** + * AdminAction deleteCloudBackup. + * @member {google.spanner.executor.v1.IDeleteCloudBackupAction|null|undefined} deleteCloudBackup + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.deleteCloudBackup = null; + + /** + * AdminAction listCloudBackups. + * @member {google.spanner.executor.v1.IListCloudBackupsAction|null|undefined} listCloudBackups + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.listCloudBackups = null; + + /** + * AdminAction listCloudBackupOperations. + * @member {google.spanner.executor.v1.IListCloudBackupOperationsAction|null|undefined} listCloudBackupOperations + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.listCloudBackupOperations = null; + + /** + * AdminAction getOperation. + * @member {google.spanner.executor.v1.IGetOperationAction|null|undefined} getOperation + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.getOperation = null; + + /** + * AdminAction cancelOperation. + * @member {google.spanner.executor.v1.ICancelOperationAction|null|undefined} cancelOperation + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.cancelOperation = null; + + /** + * AdminAction changeQuorumCloudDatabase. + * @member {google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction|null|undefined} changeQuorumCloudDatabase + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.changeQuorumCloudDatabase = null; + + /** + * AdminAction addSplitPoints. + * @member {google.spanner.executor.v1.IAddSplitPointsAction|null|undefined} addSplitPoints + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + AdminAction.prototype.addSplitPoints = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * AdminAction action. + * @member {"createUserInstanceConfig"|"updateUserInstanceConfig"|"deleteUserInstanceConfig"|"getCloudInstanceConfig"|"listInstanceConfigs"|"createCloudInstance"|"updateCloudInstance"|"deleteCloudInstance"|"listCloudInstances"|"getCloudInstance"|"createCloudDatabase"|"updateCloudDatabaseDdl"|"updateCloudDatabase"|"dropCloudDatabase"|"listCloudDatabases"|"listCloudDatabaseOperations"|"restoreCloudDatabase"|"getCloudDatabase"|"createCloudBackup"|"copyCloudBackup"|"getCloudBackup"|"updateCloudBackup"|"deleteCloudBackup"|"listCloudBackups"|"listCloudBackupOperations"|"getOperation"|"cancelOperation"|"changeQuorumCloudDatabase"|"addSplitPoints"|undefined} action + * @memberof google.spanner.executor.v1.AdminAction + * @instance + */ + Object.defineProperty(AdminAction.prototype, "action", { + get: $util.oneOfGetter($oneOfFields = ["createUserInstanceConfig", "updateUserInstanceConfig", "deleteUserInstanceConfig", "getCloudInstanceConfig", "listInstanceConfigs", "createCloudInstance", "updateCloudInstance", "deleteCloudInstance", "listCloudInstances", "getCloudInstance", "createCloudDatabase", "updateCloudDatabaseDdl", "updateCloudDatabase", "dropCloudDatabase", "listCloudDatabases", "listCloudDatabaseOperations", "restoreCloudDatabase", "getCloudDatabase", "createCloudBackup", "copyCloudBackup", "getCloudBackup", "updateCloudBackup", "deleteCloudBackup", "listCloudBackups", "listCloudBackupOperations", "getOperation", "cancelOperation", "changeQuorumCloudDatabase", "addSplitPoints"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new AdminAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {google.spanner.executor.v1.IAdminAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.AdminAction} AdminAction instance + */ + AdminAction.create = function create(properties) { + return new AdminAction(properties); + }; + + /** + * Encodes the specified AdminAction message. Does not implicitly {@link google.spanner.executor.v1.AdminAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {google.spanner.executor.v1.IAdminAction} message AdminAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AdminAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.createUserInstanceConfig != null && Object.hasOwnProperty.call(message, "createUserInstanceConfig")) + $root.google.spanner.executor.v1.CreateUserInstanceConfigAction.encode(message.createUserInstanceConfig, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.updateUserInstanceConfig != null && Object.hasOwnProperty.call(message, "updateUserInstanceConfig")) + $root.google.spanner.executor.v1.UpdateUserInstanceConfigAction.encode(message.updateUserInstanceConfig, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.deleteUserInstanceConfig != null && Object.hasOwnProperty.call(message, "deleteUserInstanceConfig")) + $root.google.spanner.executor.v1.DeleteUserInstanceConfigAction.encode(message.deleteUserInstanceConfig, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.getCloudInstanceConfig != null && Object.hasOwnProperty.call(message, "getCloudInstanceConfig")) + $root.google.spanner.executor.v1.GetCloudInstanceConfigAction.encode(message.getCloudInstanceConfig, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.listInstanceConfigs != null && Object.hasOwnProperty.call(message, "listInstanceConfigs")) + $root.google.spanner.executor.v1.ListCloudInstanceConfigsAction.encode(message.listInstanceConfigs, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.createCloudInstance != null && Object.hasOwnProperty.call(message, "createCloudInstance")) + $root.google.spanner.executor.v1.CreateCloudInstanceAction.encode(message.createCloudInstance, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.updateCloudInstance != null && Object.hasOwnProperty.call(message, "updateCloudInstance")) + $root.google.spanner.executor.v1.UpdateCloudInstanceAction.encode(message.updateCloudInstance, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.deleteCloudInstance != null && Object.hasOwnProperty.call(message, "deleteCloudInstance")) + $root.google.spanner.executor.v1.DeleteCloudInstanceAction.encode(message.deleteCloudInstance, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.listCloudInstances != null && Object.hasOwnProperty.call(message, "listCloudInstances")) + $root.google.spanner.executor.v1.ListCloudInstancesAction.encode(message.listCloudInstances, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + if (message.getCloudInstance != null && Object.hasOwnProperty.call(message, "getCloudInstance")) + $root.google.spanner.executor.v1.GetCloudInstanceAction.encode(message.getCloudInstance, writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); + if (message.createCloudDatabase != null && Object.hasOwnProperty.call(message, "createCloudDatabase")) + $root.google.spanner.executor.v1.CreateCloudDatabaseAction.encode(message.createCloudDatabase, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); + if (message.updateCloudDatabaseDdl != null && Object.hasOwnProperty.call(message, "updateCloudDatabaseDdl")) + $root.google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.encode(message.updateCloudDatabaseDdl, writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim(); + if (message.dropCloudDatabase != null && Object.hasOwnProperty.call(message, "dropCloudDatabase")) + $root.google.spanner.executor.v1.DropCloudDatabaseAction.encode(message.dropCloudDatabase, writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim(); + if (message.listCloudDatabases != null && Object.hasOwnProperty.call(message, "listCloudDatabases")) + $root.google.spanner.executor.v1.ListCloudDatabasesAction.encode(message.listCloudDatabases, writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim(); + if (message.listCloudDatabaseOperations != null && Object.hasOwnProperty.call(message, "listCloudDatabaseOperations")) + $root.google.spanner.executor.v1.ListCloudDatabaseOperationsAction.encode(message.listCloudDatabaseOperations, writer.uint32(/* id 15, wireType 2 =*/122).fork()).ldelim(); + if (message.restoreCloudDatabase != null && Object.hasOwnProperty.call(message, "restoreCloudDatabase")) + $root.google.spanner.executor.v1.RestoreCloudDatabaseAction.encode(message.restoreCloudDatabase, writer.uint32(/* id 16, wireType 2 =*/130).fork()).ldelim(); + if (message.getCloudDatabase != null && Object.hasOwnProperty.call(message, "getCloudDatabase")) + $root.google.spanner.executor.v1.GetCloudDatabaseAction.encode(message.getCloudDatabase, writer.uint32(/* id 17, wireType 2 =*/138).fork()).ldelim(); + if (message.createCloudBackup != null && Object.hasOwnProperty.call(message, "createCloudBackup")) + $root.google.spanner.executor.v1.CreateCloudBackupAction.encode(message.createCloudBackup, writer.uint32(/* id 18, wireType 2 =*/146).fork()).ldelim(); + if (message.copyCloudBackup != null && Object.hasOwnProperty.call(message, "copyCloudBackup")) + $root.google.spanner.executor.v1.CopyCloudBackupAction.encode(message.copyCloudBackup, writer.uint32(/* id 19, wireType 2 =*/154).fork()).ldelim(); + if (message.getCloudBackup != null && Object.hasOwnProperty.call(message, "getCloudBackup")) + $root.google.spanner.executor.v1.GetCloudBackupAction.encode(message.getCloudBackup, writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); + if (message.updateCloudBackup != null && Object.hasOwnProperty.call(message, "updateCloudBackup")) + $root.google.spanner.executor.v1.UpdateCloudBackupAction.encode(message.updateCloudBackup, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.deleteCloudBackup != null && Object.hasOwnProperty.call(message, "deleteCloudBackup")) + $root.google.spanner.executor.v1.DeleteCloudBackupAction.encode(message.deleteCloudBackup, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); + if (message.listCloudBackups != null && Object.hasOwnProperty.call(message, "listCloudBackups")) + $root.google.spanner.executor.v1.ListCloudBackupsAction.encode(message.listCloudBackups, writer.uint32(/* id 23, wireType 2 =*/186).fork()).ldelim(); + if (message.listCloudBackupOperations != null && Object.hasOwnProperty.call(message, "listCloudBackupOperations")) + $root.google.spanner.executor.v1.ListCloudBackupOperationsAction.encode(message.listCloudBackupOperations, writer.uint32(/* id 24, wireType 2 =*/194).fork()).ldelim(); + if (message.getOperation != null && Object.hasOwnProperty.call(message, "getOperation")) + $root.google.spanner.executor.v1.GetOperationAction.encode(message.getOperation, writer.uint32(/* id 25, wireType 2 =*/202).fork()).ldelim(); + if (message.cancelOperation != null && Object.hasOwnProperty.call(message, "cancelOperation")) + $root.google.spanner.executor.v1.CancelOperationAction.encode(message.cancelOperation, writer.uint32(/* id 26, wireType 2 =*/210).fork()).ldelim(); + if (message.updateCloudDatabase != null && Object.hasOwnProperty.call(message, "updateCloudDatabase")) + $root.google.spanner.executor.v1.UpdateCloudDatabaseAction.encode(message.updateCloudDatabase, writer.uint32(/* id 27, wireType 2 =*/218).fork()).ldelim(); + if (message.changeQuorumCloudDatabase != null && Object.hasOwnProperty.call(message, "changeQuorumCloudDatabase")) + $root.google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.encode(message.changeQuorumCloudDatabase, writer.uint32(/* id 28, wireType 2 =*/226).fork()).ldelim(); + if (message.addSplitPoints != null && Object.hasOwnProperty.call(message, "addSplitPoints")) + $root.google.spanner.executor.v1.AddSplitPointsAction.encode(message.addSplitPoints, writer.uint32(/* id 29, wireType 2 =*/234).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified AdminAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.AdminAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {google.spanner.executor.v1.IAdminAction} message AdminAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AdminAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AdminAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.AdminAction} AdminAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AdminAction.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.spanner.executor.v1.AdminAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.createUserInstanceConfig = $root.google.spanner.executor.v1.CreateUserInstanceConfigAction.decode(reader, reader.uint32()); + break; + } + case 2: { + message.updateUserInstanceConfig = $root.google.spanner.executor.v1.UpdateUserInstanceConfigAction.decode(reader, reader.uint32()); + break; + } + case 3: { + message.deleteUserInstanceConfig = $root.google.spanner.executor.v1.DeleteUserInstanceConfigAction.decode(reader, reader.uint32()); + break; + } + case 4: { + message.getCloudInstanceConfig = $root.google.spanner.executor.v1.GetCloudInstanceConfigAction.decode(reader, reader.uint32()); + break; + } + case 5: { + message.listInstanceConfigs = $root.google.spanner.executor.v1.ListCloudInstanceConfigsAction.decode(reader, reader.uint32()); + break; + } + case 6: { + message.createCloudInstance = $root.google.spanner.executor.v1.CreateCloudInstanceAction.decode(reader, reader.uint32()); + break; + } + case 7: { + message.updateCloudInstance = $root.google.spanner.executor.v1.UpdateCloudInstanceAction.decode(reader, reader.uint32()); + break; + } + case 8: { + message.deleteCloudInstance = $root.google.spanner.executor.v1.DeleteCloudInstanceAction.decode(reader, reader.uint32()); + break; + } + case 9: { + message.listCloudInstances = $root.google.spanner.executor.v1.ListCloudInstancesAction.decode(reader, reader.uint32()); + break; + } + case 10: { + message.getCloudInstance = $root.google.spanner.executor.v1.GetCloudInstanceAction.decode(reader, reader.uint32()); + break; + } + case 11: { + message.createCloudDatabase = $root.google.spanner.executor.v1.CreateCloudDatabaseAction.decode(reader, reader.uint32()); + break; + } + case 12: { + message.updateCloudDatabaseDdl = $root.google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.decode(reader, reader.uint32()); + break; + } + case 27: { + message.updateCloudDatabase = $root.google.spanner.executor.v1.UpdateCloudDatabaseAction.decode(reader, reader.uint32()); + break; + } + case 13: { + message.dropCloudDatabase = $root.google.spanner.executor.v1.DropCloudDatabaseAction.decode(reader, reader.uint32()); + break; + } + case 14: { + message.listCloudDatabases = $root.google.spanner.executor.v1.ListCloudDatabasesAction.decode(reader, reader.uint32()); + break; + } + case 15: { + message.listCloudDatabaseOperations = $root.google.spanner.executor.v1.ListCloudDatabaseOperationsAction.decode(reader, reader.uint32()); + break; + } + case 16: { + message.restoreCloudDatabase = $root.google.spanner.executor.v1.RestoreCloudDatabaseAction.decode(reader, reader.uint32()); + break; + } + case 17: { + message.getCloudDatabase = $root.google.spanner.executor.v1.GetCloudDatabaseAction.decode(reader, reader.uint32()); + break; + } + case 18: { + message.createCloudBackup = $root.google.spanner.executor.v1.CreateCloudBackupAction.decode(reader, reader.uint32()); + break; + } + case 19: { + message.copyCloudBackup = $root.google.spanner.executor.v1.CopyCloudBackupAction.decode(reader, reader.uint32()); + break; + } + case 20: { + message.getCloudBackup = $root.google.spanner.executor.v1.GetCloudBackupAction.decode(reader, reader.uint32()); + break; + } + case 21: { + message.updateCloudBackup = $root.google.spanner.executor.v1.UpdateCloudBackupAction.decode(reader, reader.uint32()); + break; + } + case 22: { + message.deleteCloudBackup = $root.google.spanner.executor.v1.DeleteCloudBackupAction.decode(reader, reader.uint32()); + break; + } + case 23: { + message.listCloudBackups = $root.google.spanner.executor.v1.ListCloudBackupsAction.decode(reader, reader.uint32()); + break; + } + case 24: { + message.listCloudBackupOperations = $root.google.spanner.executor.v1.ListCloudBackupOperationsAction.decode(reader, reader.uint32()); + break; + } + case 25: { + message.getOperation = $root.google.spanner.executor.v1.GetOperationAction.decode(reader, reader.uint32()); + break; + } + case 26: { + message.cancelOperation = $root.google.spanner.executor.v1.CancelOperationAction.decode(reader, reader.uint32()); + break; + } + case 28: { + message.changeQuorumCloudDatabase = $root.google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.decode(reader, reader.uint32()); + break; + } + case 29: { + message.addSplitPoints = $root.google.spanner.executor.v1.AddSplitPointsAction.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AdminAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.AdminAction} AdminAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AdminAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AdminAction message. + * @function verify + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AdminAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.createUserInstanceConfig != null && message.hasOwnProperty("createUserInstanceConfig")) { + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.CreateUserInstanceConfigAction.verify(message.createUserInstanceConfig); + if (error) + return "createUserInstanceConfig." + error; + } + } + if (message.updateUserInstanceConfig != null && message.hasOwnProperty("updateUserInstanceConfig")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.UpdateUserInstanceConfigAction.verify(message.updateUserInstanceConfig); + if (error) + return "updateUserInstanceConfig." + error; + } + } + if (message.deleteUserInstanceConfig != null && message.hasOwnProperty("deleteUserInstanceConfig")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.DeleteUserInstanceConfigAction.verify(message.deleteUserInstanceConfig); + if (error) + return "deleteUserInstanceConfig." + error; + } + } + if (message.getCloudInstanceConfig != null && message.hasOwnProperty("getCloudInstanceConfig")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.GetCloudInstanceConfigAction.verify(message.getCloudInstanceConfig); + if (error) + return "getCloudInstanceConfig." + error; + } + } + if (message.listInstanceConfigs != null && message.hasOwnProperty("listInstanceConfigs")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ListCloudInstanceConfigsAction.verify(message.listInstanceConfigs); + if (error) + return "listInstanceConfigs." + error; + } + } + if (message.createCloudInstance != null && message.hasOwnProperty("createCloudInstance")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.CreateCloudInstanceAction.verify(message.createCloudInstance); + if (error) + return "createCloudInstance." + error; + } + } + if (message.updateCloudInstance != null && message.hasOwnProperty("updateCloudInstance")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.UpdateCloudInstanceAction.verify(message.updateCloudInstance); + if (error) + return "updateCloudInstance." + error; + } + } + if (message.deleteCloudInstance != null && message.hasOwnProperty("deleteCloudInstance")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.DeleteCloudInstanceAction.verify(message.deleteCloudInstance); + if (error) + return "deleteCloudInstance." + error; + } + } + if (message.listCloudInstances != null && message.hasOwnProperty("listCloudInstances")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ListCloudInstancesAction.verify(message.listCloudInstances); + if (error) + return "listCloudInstances." + error; + } + } + if (message.getCloudInstance != null && message.hasOwnProperty("getCloudInstance")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.GetCloudInstanceAction.verify(message.getCloudInstance); + if (error) + return "getCloudInstance." + error; + } + } + if (message.createCloudDatabase != null && message.hasOwnProperty("createCloudDatabase")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.CreateCloudDatabaseAction.verify(message.createCloudDatabase); + if (error) + return "createCloudDatabase." + error; + } + } + if (message.updateCloudDatabaseDdl != null && message.hasOwnProperty("updateCloudDatabaseDdl")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.verify(message.updateCloudDatabaseDdl); + if (error) + return "updateCloudDatabaseDdl." + error; + } + } + if (message.updateCloudDatabase != null && message.hasOwnProperty("updateCloudDatabase")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.UpdateCloudDatabaseAction.verify(message.updateCloudDatabase); + if (error) + return "updateCloudDatabase." + error; + } + } + if (message.dropCloudDatabase != null && message.hasOwnProperty("dropCloudDatabase")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.DropCloudDatabaseAction.verify(message.dropCloudDatabase); + if (error) + return "dropCloudDatabase." + error; + } + } + if (message.listCloudDatabases != null && message.hasOwnProperty("listCloudDatabases")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ListCloudDatabasesAction.verify(message.listCloudDatabases); + if (error) + return "listCloudDatabases." + error; + } + } + if (message.listCloudDatabaseOperations != null && message.hasOwnProperty("listCloudDatabaseOperations")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ListCloudDatabaseOperationsAction.verify(message.listCloudDatabaseOperations); + if (error) + return "listCloudDatabaseOperations." + error; + } + } + if (message.restoreCloudDatabase != null && message.hasOwnProperty("restoreCloudDatabase")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.RestoreCloudDatabaseAction.verify(message.restoreCloudDatabase); + if (error) + return "restoreCloudDatabase." + error; + } + } + if (message.getCloudDatabase != null && message.hasOwnProperty("getCloudDatabase")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.GetCloudDatabaseAction.verify(message.getCloudDatabase); + if (error) + return "getCloudDatabase." + error; + } + } + if (message.createCloudBackup != null && message.hasOwnProperty("createCloudBackup")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.CreateCloudBackupAction.verify(message.createCloudBackup); + if (error) + return "createCloudBackup." + error; + } + } + if (message.copyCloudBackup != null && message.hasOwnProperty("copyCloudBackup")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.CopyCloudBackupAction.verify(message.copyCloudBackup); + if (error) + return "copyCloudBackup." + error; + } + } + if (message.getCloudBackup != null && message.hasOwnProperty("getCloudBackup")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.GetCloudBackupAction.verify(message.getCloudBackup); + if (error) + return "getCloudBackup." + error; + } + } + if (message.updateCloudBackup != null && message.hasOwnProperty("updateCloudBackup")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.UpdateCloudBackupAction.verify(message.updateCloudBackup); + if (error) + return "updateCloudBackup." + error; + } + } + if (message.deleteCloudBackup != null && message.hasOwnProperty("deleteCloudBackup")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.DeleteCloudBackupAction.verify(message.deleteCloudBackup); + if (error) + return "deleteCloudBackup." + error; + } + } + if (message.listCloudBackups != null && message.hasOwnProperty("listCloudBackups")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ListCloudBackupsAction.verify(message.listCloudBackups); + if (error) + return "listCloudBackups." + error; + } + } + if (message.listCloudBackupOperations != null && message.hasOwnProperty("listCloudBackupOperations")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ListCloudBackupOperationsAction.verify(message.listCloudBackupOperations); + if (error) + return "listCloudBackupOperations." + error; + } + } + if (message.getOperation != null && message.hasOwnProperty("getOperation")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.GetOperationAction.verify(message.getOperation); + if (error) + return "getOperation." + error; + } + } + if (message.cancelOperation != null && message.hasOwnProperty("cancelOperation")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.CancelOperationAction.verify(message.cancelOperation); + if (error) + return "cancelOperation." + error; + } + } + if (message.changeQuorumCloudDatabase != null && message.hasOwnProperty("changeQuorumCloudDatabase")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.verify(message.changeQuorumCloudDatabase); + if (error) + return "changeQuorumCloudDatabase." + error; + } + } + if (message.addSplitPoints != null && message.hasOwnProperty("addSplitPoints")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + { + var error = $root.google.spanner.executor.v1.AddSplitPointsAction.verify(message.addSplitPoints); + if (error) + return "addSplitPoints." + error; + } + } + return null; + }; + + /** + * Creates an AdminAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.AdminAction} AdminAction + */ + AdminAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.AdminAction) + return object; + var message = new $root.google.spanner.executor.v1.AdminAction(); + if (object.createUserInstanceConfig != null) { + if (typeof object.createUserInstanceConfig !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.createUserInstanceConfig: object expected"); + message.createUserInstanceConfig = $root.google.spanner.executor.v1.CreateUserInstanceConfigAction.fromObject(object.createUserInstanceConfig); + } + if (object.updateUserInstanceConfig != null) { + if (typeof object.updateUserInstanceConfig !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.updateUserInstanceConfig: object expected"); + message.updateUserInstanceConfig = $root.google.spanner.executor.v1.UpdateUserInstanceConfigAction.fromObject(object.updateUserInstanceConfig); + } + if (object.deleteUserInstanceConfig != null) { + if (typeof object.deleteUserInstanceConfig !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.deleteUserInstanceConfig: object expected"); + message.deleteUserInstanceConfig = $root.google.spanner.executor.v1.DeleteUserInstanceConfigAction.fromObject(object.deleteUserInstanceConfig); + } + if (object.getCloudInstanceConfig != null) { + if (typeof object.getCloudInstanceConfig !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.getCloudInstanceConfig: object expected"); + message.getCloudInstanceConfig = $root.google.spanner.executor.v1.GetCloudInstanceConfigAction.fromObject(object.getCloudInstanceConfig); + } + if (object.listInstanceConfigs != null) { + if (typeof object.listInstanceConfigs !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.listInstanceConfigs: object expected"); + message.listInstanceConfigs = $root.google.spanner.executor.v1.ListCloudInstanceConfigsAction.fromObject(object.listInstanceConfigs); + } + if (object.createCloudInstance != null) { + if (typeof object.createCloudInstance !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.createCloudInstance: object expected"); + message.createCloudInstance = $root.google.spanner.executor.v1.CreateCloudInstanceAction.fromObject(object.createCloudInstance); + } + if (object.updateCloudInstance != null) { + if (typeof object.updateCloudInstance !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.updateCloudInstance: object expected"); + message.updateCloudInstance = $root.google.spanner.executor.v1.UpdateCloudInstanceAction.fromObject(object.updateCloudInstance); + } + if (object.deleteCloudInstance != null) { + if (typeof object.deleteCloudInstance !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.deleteCloudInstance: object expected"); + message.deleteCloudInstance = $root.google.spanner.executor.v1.DeleteCloudInstanceAction.fromObject(object.deleteCloudInstance); + } + if (object.listCloudInstances != null) { + if (typeof object.listCloudInstances !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.listCloudInstances: object expected"); + message.listCloudInstances = $root.google.spanner.executor.v1.ListCloudInstancesAction.fromObject(object.listCloudInstances); + } + if (object.getCloudInstance != null) { + if (typeof object.getCloudInstance !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.getCloudInstance: object expected"); + message.getCloudInstance = $root.google.spanner.executor.v1.GetCloudInstanceAction.fromObject(object.getCloudInstance); + } + if (object.createCloudDatabase != null) { + if (typeof object.createCloudDatabase !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.createCloudDatabase: object expected"); + message.createCloudDatabase = $root.google.spanner.executor.v1.CreateCloudDatabaseAction.fromObject(object.createCloudDatabase); + } + if (object.updateCloudDatabaseDdl != null) { + if (typeof object.updateCloudDatabaseDdl !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.updateCloudDatabaseDdl: object expected"); + message.updateCloudDatabaseDdl = $root.google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.fromObject(object.updateCloudDatabaseDdl); + } + if (object.updateCloudDatabase != null) { + if (typeof object.updateCloudDatabase !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.updateCloudDatabase: object expected"); + message.updateCloudDatabase = $root.google.spanner.executor.v1.UpdateCloudDatabaseAction.fromObject(object.updateCloudDatabase); + } + if (object.dropCloudDatabase != null) { + if (typeof object.dropCloudDatabase !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.dropCloudDatabase: object expected"); + message.dropCloudDatabase = $root.google.spanner.executor.v1.DropCloudDatabaseAction.fromObject(object.dropCloudDatabase); + } + if (object.listCloudDatabases != null) { + if (typeof object.listCloudDatabases !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.listCloudDatabases: object expected"); + message.listCloudDatabases = $root.google.spanner.executor.v1.ListCloudDatabasesAction.fromObject(object.listCloudDatabases); + } + if (object.listCloudDatabaseOperations != null) { + if (typeof object.listCloudDatabaseOperations !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.listCloudDatabaseOperations: object expected"); + message.listCloudDatabaseOperations = $root.google.spanner.executor.v1.ListCloudDatabaseOperationsAction.fromObject(object.listCloudDatabaseOperations); + } + if (object.restoreCloudDatabase != null) { + if (typeof object.restoreCloudDatabase !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.restoreCloudDatabase: object expected"); + message.restoreCloudDatabase = $root.google.spanner.executor.v1.RestoreCloudDatabaseAction.fromObject(object.restoreCloudDatabase); + } + if (object.getCloudDatabase != null) { + if (typeof object.getCloudDatabase !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.getCloudDatabase: object expected"); + message.getCloudDatabase = $root.google.spanner.executor.v1.GetCloudDatabaseAction.fromObject(object.getCloudDatabase); + } + if (object.createCloudBackup != null) { + if (typeof object.createCloudBackup !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.createCloudBackup: object expected"); + message.createCloudBackup = $root.google.spanner.executor.v1.CreateCloudBackupAction.fromObject(object.createCloudBackup); + } + if (object.copyCloudBackup != null) { + if (typeof object.copyCloudBackup !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.copyCloudBackup: object expected"); + message.copyCloudBackup = $root.google.spanner.executor.v1.CopyCloudBackupAction.fromObject(object.copyCloudBackup); + } + if (object.getCloudBackup != null) { + if (typeof object.getCloudBackup !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.getCloudBackup: object expected"); + message.getCloudBackup = $root.google.spanner.executor.v1.GetCloudBackupAction.fromObject(object.getCloudBackup); + } + if (object.updateCloudBackup != null) { + if (typeof object.updateCloudBackup !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.updateCloudBackup: object expected"); + message.updateCloudBackup = $root.google.spanner.executor.v1.UpdateCloudBackupAction.fromObject(object.updateCloudBackup); + } + if (object.deleteCloudBackup != null) { + if (typeof object.deleteCloudBackup !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.deleteCloudBackup: object expected"); + message.deleteCloudBackup = $root.google.spanner.executor.v1.DeleteCloudBackupAction.fromObject(object.deleteCloudBackup); + } + if (object.listCloudBackups != null) { + if (typeof object.listCloudBackups !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.listCloudBackups: object expected"); + message.listCloudBackups = $root.google.spanner.executor.v1.ListCloudBackupsAction.fromObject(object.listCloudBackups); + } + if (object.listCloudBackupOperations != null) { + if (typeof object.listCloudBackupOperations !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.listCloudBackupOperations: object expected"); + message.listCloudBackupOperations = $root.google.spanner.executor.v1.ListCloudBackupOperationsAction.fromObject(object.listCloudBackupOperations); + } + if (object.getOperation != null) { + if (typeof object.getOperation !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.getOperation: object expected"); + message.getOperation = $root.google.spanner.executor.v1.GetOperationAction.fromObject(object.getOperation); + } + if (object.cancelOperation != null) { + if (typeof object.cancelOperation !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.cancelOperation: object expected"); + message.cancelOperation = $root.google.spanner.executor.v1.CancelOperationAction.fromObject(object.cancelOperation); + } + if (object.changeQuorumCloudDatabase != null) { + if (typeof object.changeQuorumCloudDatabase !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.changeQuorumCloudDatabase: object expected"); + message.changeQuorumCloudDatabase = $root.google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.fromObject(object.changeQuorumCloudDatabase); + } + if (object.addSplitPoints != null) { + if (typeof object.addSplitPoints !== "object") + throw TypeError(".google.spanner.executor.v1.AdminAction.addSplitPoints: object expected"); + message.addSplitPoints = $root.google.spanner.executor.v1.AddSplitPointsAction.fromObject(object.addSplitPoints); + } + return message; + }; + + /** + * Creates a plain object from an AdminAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {google.spanner.executor.v1.AdminAction} message AdminAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AdminAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.createUserInstanceConfig != null && message.hasOwnProperty("createUserInstanceConfig")) { + object.createUserInstanceConfig = $root.google.spanner.executor.v1.CreateUserInstanceConfigAction.toObject(message.createUserInstanceConfig, options); + if (options.oneofs) + object.action = "createUserInstanceConfig"; + } + if (message.updateUserInstanceConfig != null && message.hasOwnProperty("updateUserInstanceConfig")) { + object.updateUserInstanceConfig = $root.google.spanner.executor.v1.UpdateUserInstanceConfigAction.toObject(message.updateUserInstanceConfig, options); + if (options.oneofs) + object.action = "updateUserInstanceConfig"; + } + if (message.deleteUserInstanceConfig != null && message.hasOwnProperty("deleteUserInstanceConfig")) { + object.deleteUserInstanceConfig = $root.google.spanner.executor.v1.DeleteUserInstanceConfigAction.toObject(message.deleteUserInstanceConfig, options); + if (options.oneofs) + object.action = "deleteUserInstanceConfig"; + } + if (message.getCloudInstanceConfig != null && message.hasOwnProperty("getCloudInstanceConfig")) { + object.getCloudInstanceConfig = $root.google.spanner.executor.v1.GetCloudInstanceConfigAction.toObject(message.getCloudInstanceConfig, options); + if (options.oneofs) + object.action = "getCloudInstanceConfig"; + } + if (message.listInstanceConfigs != null && message.hasOwnProperty("listInstanceConfigs")) { + object.listInstanceConfigs = $root.google.spanner.executor.v1.ListCloudInstanceConfigsAction.toObject(message.listInstanceConfigs, options); + if (options.oneofs) + object.action = "listInstanceConfigs"; + } + if (message.createCloudInstance != null && message.hasOwnProperty("createCloudInstance")) { + object.createCloudInstance = $root.google.spanner.executor.v1.CreateCloudInstanceAction.toObject(message.createCloudInstance, options); + if (options.oneofs) + object.action = "createCloudInstance"; + } + if (message.updateCloudInstance != null && message.hasOwnProperty("updateCloudInstance")) { + object.updateCloudInstance = $root.google.spanner.executor.v1.UpdateCloudInstanceAction.toObject(message.updateCloudInstance, options); + if (options.oneofs) + object.action = "updateCloudInstance"; + } + if (message.deleteCloudInstance != null && message.hasOwnProperty("deleteCloudInstance")) { + object.deleteCloudInstance = $root.google.spanner.executor.v1.DeleteCloudInstanceAction.toObject(message.deleteCloudInstance, options); + if (options.oneofs) + object.action = "deleteCloudInstance"; + } + if (message.listCloudInstances != null && message.hasOwnProperty("listCloudInstances")) { + object.listCloudInstances = $root.google.spanner.executor.v1.ListCloudInstancesAction.toObject(message.listCloudInstances, options); + if (options.oneofs) + object.action = "listCloudInstances"; + } + if (message.getCloudInstance != null && message.hasOwnProperty("getCloudInstance")) { + object.getCloudInstance = $root.google.spanner.executor.v1.GetCloudInstanceAction.toObject(message.getCloudInstance, options); + if (options.oneofs) + object.action = "getCloudInstance"; + } + if (message.createCloudDatabase != null && message.hasOwnProperty("createCloudDatabase")) { + object.createCloudDatabase = $root.google.spanner.executor.v1.CreateCloudDatabaseAction.toObject(message.createCloudDatabase, options); + if (options.oneofs) + object.action = "createCloudDatabase"; + } + if (message.updateCloudDatabaseDdl != null && message.hasOwnProperty("updateCloudDatabaseDdl")) { + object.updateCloudDatabaseDdl = $root.google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.toObject(message.updateCloudDatabaseDdl, options); + if (options.oneofs) + object.action = "updateCloudDatabaseDdl"; + } + if (message.dropCloudDatabase != null && message.hasOwnProperty("dropCloudDatabase")) { + object.dropCloudDatabase = $root.google.spanner.executor.v1.DropCloudDatabaseAction.toObject(message.dropCloudDatabase, options); + if (options.oneofs) + object.action = "dropCloudDatabase"; + } + if (message.listCloudDatabases != null && message.hasOwnProperty("listCloudDatabases")) { + object.listCloudDatabases = $root.google.spanner.executor.v1.ListCloudDatabasesAction.toObject(message.listCloudDatabases, options); + if (options.oneofs) + object.action = "listCloudDatabases"; + } + if (message.listCloudDatabaseOperations != null && message.hasOwnProperty("listCloudDatabaseOperations")) { + object.listCloudDatabaseOperations = $root.google.spanner.executor.v1.ListCloudDatabaseOperationsAction.toObject(message.listCloudDatabaseOperations, options); + if (options.oneofs) + object.action = "listCloudDatabaseOperations"; + } + if (message.restoreCloudDatabase != null && message.hasOwnProperty("restoreCloudDatabase")) { + object.restoreCloudDatabase = $root.google.spanner.executor.v1.RestoreCloudDatabaseAction.toObject(message.restoreCloudDatabase, options); + if (options.oneofs) + object.action = "restoreCloudDatabase"; + } + if (message.getCloudDatabase != null && message.hasOwnProperty("getCloudDatabase")) { + object.getCloudDatabase = $root.google.spanner.executor.v1.GetCloudDatabaseAction.toObject(message.getCloudDatabase, options); + if (options.oneofs) + object.action = "getCloudDatabase"; + } + if (message.createCloudBackup != null && message.hasOwnProperty("createCloudBackup")) { + object.createCloudBackup = $root.google.spanner.executor.v1.CreateCloudBackupAction.toObject(message.createCloudBackup, options); + if (options.oneofs) + object.action = "createCloudBackup"; + } + if (message.copyCloudBackup != null && message.hasOwnProperty("copyCloudBackup")) { + object.copyCloudBackup = $root.google.spanner.executor.v1.CopyCloudBackupAction.toObject(message.copyCloudBackup, options); + if (options.oneofs) + object.action = "copyCloudBackup"; + } + if (message.getCloudBackup != null && message.hasOwnProperty("getCloudBackup")) { + object.getCloudBackup = $root.google.spanner.executor.v1.GetCloudBackupAction.toObject(message.getCloudBackup, options); + if (options.oneofs) + object.action = "getCloudBackup"; + } + if (message.updateCloudBackup != null && message.hasOwnProperty("updateCloudBackup")) { + object.updateCloudBackup = $root.google.spanner.executor.v1.UpdateCloudBackupAction.toObject(message.updateCloudBackup, options); + if (options.oneofs) + object.action = "updateCloudBackup"; + } + if (message.deleteCloudBackup != null && message.hasOwnProperty("deleteCloudBackup")) { + object.deleteCloudBackup = $root.google.spanner.executor.v1.DeleteCloudBackupAction.toObject(message.deleteCloudBackup, options); + if (options.oneofs) + object.action = "deleteCloudBackup"; + } + if (message.listCloudBackups != null && message.hasOwnProperty("listCloudBackups")) { + object.listCloudBackups = $root.google.spanner.executor.v1.ListCloudBackupsAction.toObject(message.listCloudBackups, options); + if (options.oneofs) + object.action = "listCloudBackups"; + } + if (message.listCloudBackupOperations != null && message.hasOwnProperty("listCloudBackupOperations")) { + object.listCloudBackupOperations = $root.google.spanner.executor.v1.ListCloudBackupOperationsAction.toObject(message.listCloudBackupOperations, options); + if (options.oneofs) + object.action = "listCloudBackupOperations"; + } + if (message.getOperation != null && message.hasOwnProperty("getOperation")) { + object.getOperation = $root.google.spanner.executor.v1.GetOperationAction.toObject(message.getOperation, options); + if (options.oneofs) + object.action = "getOperation"; + } + if (message.cancelOperation != null && message.hasOwnProperty("cancelOperation")) { + object.cancelOperation = $root.google.spanner.executor.v1.CancelOperationAction.toObject(message.cancelOperation, options); + if (options.oneofs) + object.action = "cancelOperation"; + } + if (message.updateCloudDatabase != null && message.hasOwnProperty("updateCloudDatabase")) { + object.updateCloudDatabase = $root.google.spanner.executor.v1.UpdateCloudDatabaseAction.toObject(message.updateCloudDatabase, options); + if (options.oneofs) + object.action = "updateCloudDatabase"; + } + if (message.changeQuorumCloudDatabase != null && message.hasOwnProperty("changeQuorumCloudDatabase")) { + object.changeQuorumCloudDatabase = $root.google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.toObject(message.changeQuorumCloudDatabase, options); + if (options.oneofs) + object.action = "changeQuorumCloudDatabase"; + } + if (message.addSplitPoints != null && message.hasOwnProperty("addSplitPoints")) { + object.addSplitPoints = $root.google.spanner.executor.v1.AddSplitPointsAction.toObject(message.addSplitPoints, options); + if (options.oneofs) + object.action = "addSplitPoints"; + } + return object; + }; + + /** + * Converts this AdminAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.AdminAction + * @instance + * @returns {Object.} JSON object + */ + AdminAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AdminAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.AdminAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AdminAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.AdminAction"; + }; + + return AdminAction; + })(); + + v1.CreateUserInstanceConfigAction = (function() { + + /** + * Properties of a CreateUserInstanceConfigAction. + * @memberof google.spanner.executor.v1 + * @interface ICreateUserInstanceConfigAction + * @property {string|null} [userConfigId] CreateUserInstanceConfigAction userConfigId + * @property {string|null} [projectId] CreateUserInstanceConfigAction projectId + * @property {string|null} [baseConfigId] CreateUserInstanceConfigAction baseConfigId + * @property {Array.|null} [replicas] CreateUserInstanceConfigAction replicas + */ + + /** + * Constructs a new CreateUserInstanceConfigAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CreateUserInstanceConfigAction. + * @implements ICreateUserInstanceConfigAction + * @constructor + * @param {google.spanner.executor.v1.ICreateUserInstanceConfigAction=} [properties] Properties to set + */ + function CreateUserInstanceConfigAction(properties) { + this.replicas = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateUserInstanceConfigAction userConfigId. + * @member {string} userConfigId + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @instance + */ + CreateUserInstanceConfigAction.prototype.userConfigId = ""; + + /** + * CreateUserInstanceConfigAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @instance + */ + CreateUserInstanceConfigAction.prototype.projectId = ""; + + /** + * CreateUserInstanceConfigAction baseConfigId. + * @member {string} baseConfigId + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @instance + */ + CreateUserInstanceConfigAction.prototype.baseConfigId = ""; + + /** + * CreateUserInstanceConfigAction replicas. + * @member {Array.} replicas + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @instance + */ + CreateUserInstanceConfigAction.prototype.replicas = $util.emptyArray; + + /** + * Creates a new CreateUserInstanceConfigAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.ICreateUserInstanceConfigAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CreateUserInstanceConfigAction} CreateUserInstanceConfigAction instance + */ + CreateUserInstanceConfigAction.create = function create(properties) { + return new CreateUserInstanceConfigAction(properties); + }; + + /** + * Encodes the specified CreateUserInstanceConfigAction message. Does not implicitly {@link google.spanner.executor.v1.CreateUserInstanceConfigAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.ICreateUserInstanceConfigAction} message CreateUserInstanceConfigAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateUserInstanceConfigAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userConfigId != null && Object.hasOwnProperty.call(message, "userConfigId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.userConfigId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + if (message.baseConfigId != null && Object.hasOwnProperty.call(message, "baseConfigId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.baseConfigId); + if (message.replicas != null && message.replicas.length) + for (var i = 0; i < message.replicas.length; ++i) + $root.google.spanner.admin.instance.v1.ReplicaInfo.encode(message.replicas[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateUserInstanceConfigAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CreateUserInstanceConfigAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.ICreateUserInstanceConfigAction} message CreateUserInstanceConfigAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateUserInstanceConfigAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateUserInstanceConfigAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CreateUserInstanceConfigAction} CreateUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateUserInstanceConfigAction.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.spanner.executor.v1.CreateUserInstanceConfigAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.userConfigId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + case 3: { + message.baseConfigId = reader.string(); + break; + } + case 4: { + if (!(message.replicas && message.replicas.length)) + message.replicas = []; + message.replicas.push($root.google.spanner.admin.instance.v1.ReplicaInfo.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateUserInstanceConfigAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CreateUserInstanceConfigAction} CreateUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateUserInstanceConfigAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateUserInstanceConfigAction message. + * @function verify + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateUserInstanceConfigAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userConfigId != null && message.hasOwnProperty("userConfigId")) + if (!$util.isString(message.userConfigId)) + return "userConfigId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.baseConfigId != null && message.hasOwnProperty("baseConfigId")) + if (!$util.isString(message.baseConfigId)) + return "baseConfigId: string expected"; + if (message.replicas != null && message.hasOwnProperty("replicas")) { + if (!Array.isArray(message.replicas)) + return "replicas: array expected"; + for (var i = 0; i < message.replicas.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.ReplicaInfo.verify(message.replicas[i]); + if (error) + return "replicas." + error; + } + } + return null; + }; + + /** + * Creates a CreateUserInstanceConfigAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CreateUserInstanceConfigAction} CreateUserInstanceConfigAction + */ + CreateUserInstanceConfigAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CreateUserInstanceConfigAction) + return object; + var message = new $root.google.spanner.executor.v1.CreateUserInstanceConfigAction(); + if (object.userConfigId != null) + message.userConfigId = String(object.userConfigId); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.baseConfigId != null) + message.baseConfigId = String(object.baseConfigId); + if (object.replicas) { + if (!Array.isArray(object.replicas)) + throw TypeError(".google.spanner.executor.v1.CreateUserInstanceConfigAction.replicas: array expected"); + message.replicas = []; + for (var i = 0; i < object.replicas.length; ++i) { + if (typeof object.replicas[i] !== "object") + throw TypeError(".google.spanner.executor.v1.CreateUserInstanceConfigAction.replicas: object expected"); + message.replicas[i] = $root.google.spanner.admin.instance.v1.ReplicaInfo.fromObject(object.replicas[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a CreateUserInstanceConfigAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.CreateUserInstanceConfigAction} message CreateUserInstanceConfigAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateUserInstanceConfigAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.replicas = []; + if (options.defaults) { + object.userConfigId = ""; + object.projectId = ""; + object.baseConfigId = ""; + } + if (message.userConfigId != null && message.hasOwnProperty("userConfigId")) + object.userConfigId = message.userConfigId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.baseConfigId != null && message.hasOwnProperty("baseConfigId")) + object.baseConfigId = message.baseConfigId; + if (message.replicas && message.replicas.length) { + object.replicas = []; + for (var j = 0; j < message.replicas.length; ++j) + object.replicas[j] = $root.google.spanner.admin.instance.v1.ReplicaInfo.toObject(message.replicas[j], options); + } + return object; + }; + + /** + * Converts this CreateUserInstanceConfigAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @instance + * @returns {Object.} JSON object + */ + CreateUserInstanceConfigAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateUserInstanceConfigAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CreateUserInstanceConfigAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateUserInstanceConfigAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CreateUserInstanceConfigAction"; + }; + + return CreateUserInstanceConfigAction; + })(); + + v1.UpdateUserInstanceConfigAction = (function() { + + /** + * Properties of an UpdateUserInstanceConfigAction. + * @memberof google.spanner.executor.v1 + * @interface IUpdateUserInstanceConfigAction + * @property {string|null} [userConfigId] UpdateUserInstanceConfigAction userConfigId + * @property {string|null} [projectId] UpdateUserInstanceConfigAction projectId + * @property {string|null} [displayName] UpdateUserInstanceConfigAction displayName + * @property {Object.|null} [labels] UpdateUserInstanceConfigAction labels + */ + + /** + * Constructs a new UpdateUserInstanceConfigAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an UpdateUserInstanceConfigAction. + * @implements IUpdateUserInstanceConfigAction + * @constructor + * @param {google.spanner.executor.v1.IUpdateUserInstanceConfigAction=} [properties] Properties to set + */ + function UpdateUserInstanceConfigAction(properties) { + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateUserInstanceConfigAction userConfigId. + * @member {string} userConfigId + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @instance + */ + UpdateUserInstanceConfigAction.prototype.userConfigId = ""; + + /** + * UpdateUserInstanceConfigAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @instance + */ + UpdateUserInstanceConfigAction.prototype.projectId = ""; + + /** + * UpdateUserInstanceConfigAction displayName. + * @member {string|null|undefined} displayName + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @instance + */ + UpdateUserInstanceConfigAction.prototype.displayName = null; + + /** + * UpdateUserInstanceConfigAction labels. + * @member {Object.} labels + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @instance + */ + UpdateUserInstanceConfigAction.prototype.labels = $util.emptyObject; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UpdateUserInstanceConfigAction.prototype, "_displayName", { + get: $util.oneOfGetter($oneOfFields = ["displayName"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UpdateUserInstanceConfigAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IUpdateUserInstanceConfigAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.UpdateUserInstanceConfigAction} UpdateUserInstanceConfigAction instance + */ + UpdateUserInstanceConfigAction.create = function create(properties) { + return new UpdateUserInstanceConfigAction(properties); + }; + + /** + * Encodes the specified UpdateUserInstanceConfigAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateUserInstanceConfigAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IUpdateUserInstanceConfigAction} message UpdateUserInstanceConfigAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateUserInstanceConfigAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userConfigId != null && Object.hasOwnProperty.call(message, "userConfigId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.userConfigId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.displayName); + if (message.labels != null && Object.hasOwnProperty.call(message, "labels")) + for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) + writer.uint32(/* id 4, wireType 2 =*/34).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateUserInstanceConfigAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateUserInstanceConfigAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IUpdateUserInstanceConfigAction} message UpdateUserInstanceConfigAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateUserInstanceConfigAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateUserInstanceConfigAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.UpdateUserInstanceConfigAction} UpdateUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateUserInstanceConfigAction.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.spanner.executor.v1.UpdateUserInstanceConfigAction(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.userConfigId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + case 3: { + message.displayName = reader.string(); + break; + } + case 4: { + if (message.labels === $util.emptyObject) + message.labels = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.labels[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateUserInstanceConfigAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.UpdateUserInstanceConfigAction} UpdateUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateUserInstanceConfigAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateUserInstanceConfigAction message. + * @function verify + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateUserInstanceConfigAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.userConfigId != null && message.hasOwnProperty("userConfigId")) + if (!$util.isString(message.userConfigId)) + return "userConfigId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.displayName != null && message.hasOwnProperty("displayName")) { + properties._displayName = 1; + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + } + if (message.labels != null && message.hasOwnProperty("labels")) { + if (!$util.isObject(message.labels)) + return "labels: object expected"; + var key = Object.keys(message.labels); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.labels[key[i]])) + return "labels: string{k:string} expected"; + } + return null; + }; + + /** + * Creates an UpdateUserInstanceConfigAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.UpdateUserInstanceConfigAction} UpdateUserInstanceConfigAction + */ + UpdateUserInstanceConfigAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.UpdateUserInstanceConfigAction) + return object; + var message = new $root.google.spanner.executor.v1.UpdateUserInstanceConfigAction(); + if (object.userConfigId != null) + message.userConfigId = String(object.userConfigId); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.displayName != null) + message.displayName = String(object.displayName); + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.spanner.executor.v1.UpdateUserInstanceConfigAction.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from an UpdateUserInstanceConfigAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.UpdateUserInstanceConfigAction} message UpdateUserInstanceConfigAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateUserInstanceConfigAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.userConfigId = ""; + object.projectId = ""; + } + if (message.userConfigId != null && message.hasOwnProperty("userConfigId")) + object.userConfigId = message.userConfigId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.displayName != null && message.hasOwnProperty("displayName")) { + object.displayName = message.displayName; + if (options.oneofs) + object._displayName = "displayName"; + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + return object; + }; + + /** + * Converts this UpdateUserInstanceConfigAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @instance + * @returns {Object.} JSON object + */ + UpdateUserInstanceConfigAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateUserInstanceConfigAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.UpdateUserInstanceConfigAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateUserInstanceConfigAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.UpdateUserInstanceConfigAction"; + }; + + return UpdateUserInstanceConfigAction; + })(); + + v1.GetCloudInstanceConfigAction = (function() { + + /** + * Properties of a GetCloudInstanceConfigAction. + * @memberof google.spanner.executor.v1 + * @interface IGetCloudInstanceConfigAction + * @property {string|null} [instanceConfigId] GetCloudInstanceConfigAction instanceConfigId + * @property {string|null} [projectId] GetCloudInstanceConfigAction projectId + */ + + /** + * Constructs a new GetCloudInstanceConfigAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a GetCloudInstanceConfigAction. + * @implements IGetCloudInstanceConfigAction + * @constructor + * @param {google.spanner.executor.v1.IGetCloudInstanceConfigAction=} [properties] Properties to set + */ + function GetCloudInstanceConfigAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetCloudInstanceConfigAction instanceConfigId. + * @member {string} instanceConfigId + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @instance + */ + GetCloudInstanceConfigAction.prototype.instanceConfigId = ""; + + /** + * GetCloudInstanceConfigAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @instance + */ + GetCloudInstanceConfigAction.prototype.projectId = ""; + + /** + * Creates a new GetCloudInstanceConfigAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IGetCloudInstanceConfigAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.GetCloudInstanceConfigAction} GetCloudInstanceConfigAction instance + */ + GetCloudInstanceConfigAction.create = function create(properties) { + return new GetCloudInstanceConfigAction(properties); + }; + + /** + * Encodes the specified GetCloudInstanceConfigAction message. Does not implicitly {@link google.spanner.executor.v1.GetCloudInstanceConfigAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IGetCloudInstanceConfigAction} message GetCloudInstanceConfigAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetCloudInstanceConfigAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceConfigId != null && Object.hasOwnProperty.call(message, "instanceConfigId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instanceConfigId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + return writer; + }; + + /** + * Encodes the specified GetCloudInstanceConfigAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetCloudInstanceConfigAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IGetCloudInstanceConfigAction} message GetCloudInstanceConfigAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetCloudInstanceConfigAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetCloudInstanceConfigAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.GetCloudInstanceConfigAction} GetCloudInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetCloudInstanceConfigAction.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.spanner.executor.v1.GetCloudInstanceConfigAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceConfigId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetCloudInstanceConfigAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.GetCloudInstanceConfigAction} GetCloudInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetCloudInstanceConfigAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetCloudInstanceConfigAction message. + * @function verify + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetCloudInstanceConfigAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instanceConfigId != null && message.hasOwnProperty("instanceConfigId")) + if (!$util.isString(message.instanceConfigId)) + return "instanceConfigId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + return null; + }; + + /** + * Creates a GetCloudInstanceConfigAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.GetCloudInstanceConfigAction} GetCloudInstanceConfigAction + */ + GetCloudInstanceConfigAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.GetCloudInstanceConfigAction) + return object; + var message = new $root.google.spanner.executor.v1.GetCloudInstanceConfigAction(); + if (object.instanceConfigId != null) + message.instanceConfigId = String(object.instanceConfigId); + if (object.projectId != null) + message.projectId = String(object.projectId); + return message; + }; + + /** + * Creates a plain object from a GetCloudInstanceConfigAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.GetCloudInstanceConfigAction} message GetCloudInstanceConfigAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetCloudInstanceConfigAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instanceConfigId = ""; + object.projectId = ""; + } + if (message.instanceConfigId != null && message.hasOwnProperty("instanceConfigId")) + object.instanceConfigId = message.instanceConfigId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + return object; + }; + + /** + * Converts this GetCloudInstanceConfigAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @instance + * @returns {Object.} JSON object + */ + GetCloudInstanceConfigAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetCloudInstanceConfigAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.GetCloudInstanceConfigAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetCloudInstanceConfigAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.GetCloudInstanceConfigAction"; + }; + + return GetCloudInstanceConfigAction; + })(); + + v1.DeleteUserInstanceConfigAction = (function() { + + /** + * Properties of a DeleteUserInstanceConfigAction. + * @memberof google.spanner.executor.v1 + * @interface IDeleteUserInstanceConfigAction + * @property {string|null} [userConfigId] DeleteUserInstanceConfigAction userConfigId + * @property {string|null} [projectId] DeleteUserInstanceConfigAction projectId + */ + + /** + * Constructs a new DeleteUserInstanceConfigAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a DeleteUserInstanceConfigAction. + * @implements IDeleteUserInstanceConfigAction + * @constructor + * @param {google.spanner.executor.v1.IDeleteUserInstanceConfigAction=} [properties] Properties to set + */ + function DeleteUserInstanceConfigAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteUserInstanceConfigAction userConfigId. + * @member {string} userConfigId + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @instance + */ + DeleteUserInstanceConfigAction.prototype.userConfigId = ""; + + /** + * DeleteUserInstanceConfigAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @instance + */ + DeleteUserInstanceConfigAction.prototype.projectId = ""; + + /** + * Creates a new DeleteUserInstanceConfigAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IDeleteUserInstanceConfigAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.DeleteUserInstanceConfigAction} DeleteUserInstanceConfigAction instance + */ + DeleteUserInstanceConfigAction.create = function create(properties) { + return new DeleteUserInstanceConfigAction(properties); + }; + + /** + * Encodes the specified DeleteUserInstanceConfigAction message. Does not implicitly {@link google.spanner.executor.v1.DeleteUserInstanceConfigAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IDeleteUserInstanceConfigAction} message DeleteUserInstanceConfigAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteUserInstanceConfigAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userConfigId != null && Object.hasOwnProperty.call(message, "userConfigId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.userConfigId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + return writer; + }; + + /** + * Encodes the specified DeleteUserInstanceConfigAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DeleteUserInstanceConfigAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.IDeleteUserInstanceConfigAction} message DeleteUserInstanceConfigAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteUserInstanceConfigAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteUserInstanceConfigAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.DeleteUserInstanceConfigAction} DeleteUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteUserInstanceConfigAction.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.spanner.executor.v1.DeleteUserInstanceConfigAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.userConfigId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteUserInstanceConfigAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.DeleteUserInstanceConfigAction} DeleteUserInstanceConfigAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteUserInstanceConfigAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteUserInstanceConfigAction message. + * @function verify + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteUserInstanceConfigAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userConfigId != null && message.hasOwnProperty("userConfigId")) + if (!$util.isString(message.userConfigId)) + return "userConfigId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + return null; + }; + + /** + * Creates a DeleteUserInstanceConfigAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.DeleteUserInstanceConfigAction} DeleteUserInstanceConfigAction + */ + DeleteUserInstanceConfigAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.DeleteUserInstanceConfigAction) + return object; + var message = new $root.google.spanner.executor.v1.DeleteUserInstanceConfigAction(); + if (object.userConfigId != null) + message.userConfigId = String(object.userConfigId); + if (object.projectId != null) + message.projectId = String(object.projectId); + return message; + }; + + /** + * Creates a plain object from a DeleteUserInstanceConfigAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {google.spanner.executor.v1.DeleteUserInstanceConfigAction} message DeleteUserInstanceConfigAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteUserInstanceConfigAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.userConfigId = ""; + object.projectId = ""; + } + if (message.userConfigId != null && message.hasOwnProperty("userConfigId")) + object.userConfigId = message.userConfigId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + return object; + }; + + /** + * Converts this DeleteUserInstanceConfigAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @instance + * @returns {Object.} JSON object + */ + DeleteUserInstanceConfigAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteUserInstanceConfigAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.DeleteUserInstanceConfigAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteUserInstanceConfigAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.DeleteUserInstanceConfigAction"; + }; + + return DeleteUserInstanceConfigAction; + })(); + + v1.ListCloudInstanceConfigsAction = (function() { + + /** + * Properties of a ListCloudInstanceConfigsAction. + * @memberof google.spanner.executor.v1 + * @interface IListCloudInstanceConfigsAction + * @property {string|null} [projectId] ListCloudInstanceConfigsAction projectId + * @property {number|null} [pageSize] ListCloudInstanceConfigsAction pageSize + * @property {string|null} [pageToken] ListCloudInstanceConfigsAction pageToken + */ + + /** + * Constructs a new ListCloudInstanceConfigsAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ListCloudInstanceConfigsAction. + * @implements IListCloudInstanceConfigsAction + * @constructor + * @param {google.spanner.executor.v1.IListCloudInstanceConfigsAction=} [properties] Properties to set + */ + function ListCloudInstanceConfigsAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCloudInstanceConfigsAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @instance + */ + ListCloudInstanceConfigsAction.prototype.projectId = ""; + + /** + * ListCloudInstanceConfigsAction pageSize. + * @member {number|null|undefined} pageSize + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @instance + */ + ListCloudInstanceConfigsAction.prototype.pageSize = null; + + /** + * ListCloudInstanceConfigsAction pageToken. + * @member {string|null|undefined} pageToken + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @instance + */ + ListCloudInstanceConfigsAction.prototype.pageToken = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListCloudInstanceConfigsAction.prototype, "_pageSize", { + get: $util.oneOfGetter($oneOfFields = ["pageSize"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListCloudInstanceConfigsAction.prototype, "_pageToken", { + get: $util.oneOfGetter($oneOfFields = ["pageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListCloudInstanceConfigsAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {google.spanner.executor.v1.IListCloudInstanceConfigsAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ListCloudInstanceConfigsAction} ListCloudInstanceConfigsAction instance + */ + ListCloudInstanceConfigsAction.create = function create(properties) { + return new ListCloudInstanceConfigsAction(properties); + }; + + /** + * Encodes the specified ListCloudInstanceConfigsAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudInstanceConfigsAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {google.spanner.executor.v1.IListCloudInstanceConfigsAction} message ListCloudInstanceConfigsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudInstanceConfigsAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListCloudInstanceConfigsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudInstanceConfigsAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {google.spanner.executor.v1.IListCloudInstanceConfigsAction} message ListCloudInstanceConfigsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudInstanceConfigsAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListCloudInstanceConfigsAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ListCloudInstanceConfigsAction} ListCloudInstanceConfigsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudInstanceConfigsAction.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.spanner.executor.v1.ListCloudInstanceConfigsAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListCloudInstanceConfigsAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ListCloudInstanceConfigsAction} ListCloudInstanceConfigsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudInstanceConfigsAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListCloudInstanceConfigsAction message. + * @function verify + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListCloudInstanceConfigsAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) { + properties._pageSize = 1; + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + properties._pageToken = 1; + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + } + return null; + }; + + /** + * Creates a ListCloudInstanceConfigsAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ListCloudInstanceConfigsAction} ListCloudInstanceConfigsAction + */ + ListCloudInstanceConfigsAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ListCloudInstanceConfigsAction) + return object; + var message = new $root.google.spanner.executor.v1.ListCloudInstanceConfigsAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListCloudInstanceConfigsAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {google.spanner.executor.v1.ListCloudInstanceConfigsAction} message ListCloudInstanceConfigsAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCloudInstanceConfigsAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.projectId = ""; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) { + object.pageSize = message.pageSize; + if (options.oneofs) + object._pageSize = "pageSize"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + object.pageToken = message.pageToken; + if (options.oneofs) + object._pageToken = "pageToken"; + } + return object; + }; + + /** + * Converts this ListCloudInstanceConfigsAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @instance + * @returns {Object.} JSON object + */ + ListCloudInstanceConfigsAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCloudInstanceConfigsAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ListCloudInstanceConfigsAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCloudInstanceConfigsAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ListCloudInstanceConfigsAction"; + }; + + return ListCloudInstanceConfigsAction; + })(); + + v1.CreateCloudInstanceAction = (function() { + + /** + * Properties of a CreateCloudInstanceAction. + * @memberof google.spanner.executor.v1 + * @interface ICreateCloudInstanceAction + * @property {string|null} [instanceId] CreateCloudInstanceAction instanceId + * @property {string|null} [projectId] CreateCloudInstanceAction projectId + * @property {string|null} [instanceConfigId] CreateCloudInstanceAction instanceConfigId + * @property {number|null} [nodeCount] CreateCloudInstanceAction nodeCount + * @property {number|null} [processingUnits] CreateCloudInstanceAction processingUnits + * @property {google.spanner.admin.instance.v1.IAutoscalingConfig|null} [autoscalingConfig] CreateCloudInstanceAction autoscalingConfig + * @property {Object.|null} [labels] CreateCloudInstanceAction labels + * @property {google.spanner.admin.instance.v1.Instance.Edition|null} [edition] CreateCloudInstanceAction edition + */ + + /** + * Constructs a new CreateCloudInstanceAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CreateCloudInstanceAction. + * @implements ICreateCloudInstanceAction + * @constructor + * @param {google.spanner.executor.v1.ICreateCloudInstanceAction=} [properties] Properties to set + */ + function CreateCloudInstanceAction(properties) { + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateCloudInstanceAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + */ + CreateCloudInstanceAction.prototype.instanceId = ""; + + /** + * CreateCloudInstanceAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + */ + CreateCloudInstanceAction.prototype.projectId = ""; + + /** + * CreateCloudInstanceAction instanceConfigId. + * @member {string} instanceConfigId + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + */ + CreateCloudInstanceAction.prototype.instanceConfigId = ""; + + /** + * CreateCloudInstanceAction nodeCount. + * @member {number|null|undefined} nodeCount + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + */ + CreateCloudInstanceAction.prototype.nodeCount = null; + + /** + * CreateCloudInstanceAction processingUnits. + * @member {number|null|undefined} processingUnits + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + */ + CreateCloudInstanceAction.prototype.processingUnits = null; + + /** + * CreateCloudInstanceAction autoscalingConfig. + * @member {google.spanner.admin.instance.v1.IAutoscalingConfig|null|undefined} autoscalingConfig + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + */ + CreateCloudInstanceAction.prototype.autoscalingConfig = null; + + /** + * CreateCloudInstanceAction labels. + * @member {Object.} labels + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + */ + CreateCloudInstanceAction.prototype.labels = $util.emptyObject; + + /** + * CreateCloudInstanceAction edition. + * @member {google.spanner.admin.instance.v1.Instance.Edition} edition + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + */ + CreateCloudInstanceAction.prototype.edition = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CreateCloudInstanceAction.prototype, "_nodeCount", { + get: $util.oneOfGetter($oneOfFields = ["nodeCount"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CreateCloudInstanceAction.prototype, "_processingUnits", { + get: $util.oneOfGetter($oneOfFields = ["processingUnits"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CreateCloudInstanceAction.prototype, "_autoscalingConfig", { + get: $util.oneOfGetter($oneOfFields = ["autoscalingConfig"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new CreateCloudInstanceAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudInstanceAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CreateCloudInstanceAction} CreateCloudInstanceAction instance + */ + CreateCloudInstanceAction.create = function create(properties) { + return new CreateCloudInstanceAction(properties); + }; + + /** + * Encodes the specified CreateCloudInstanceAction message. Does not implicitly {@link google.spanner.executor.v1.CreateCloudInstanceAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudInstanceAction} message CreateCloudInstanceAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateCloudInstanceAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instanceId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + if (message.instanceConfigId != null && Object.hasOwnProperty.call(message, "instanceConfigId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.instanceConfigId); + if (message.nodeCount != null && Object.hasOwnProperty.call(message, "nodeCount")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.nodeCount); + if (message.labels != null && Object.hasOwnProperty.call(message, "labels")) + for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) + writer.uint32(/* id 5, wireType 2 =*/42).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); + if (message.processingUnits != null && Object.hasOwnProperty.call(message, "processingUnits")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.processingUnits); + if (message.autoscalingConfig != null && Object.hasOwnProperty.call(message, "autoscalingConfig")) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.encode(message.autoscalingConfig, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.edition); + return writer; + }; + + /** + * Encodes the specified CreateCloudInstanceAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CreateCloudInstanceAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudInstanceAction} message CreateCloudInstanceAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateCloudInstanceAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateCloudInstanceAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CreateCloudInstanceAction} CreateCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateCloudInstanceAction.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.spanner.executor.v1.CreateCloudInstanceAction(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + case 3: { + message.instanceConfigId = reader.string(); + break; + } + case 4: { + message.nodeCount = reader.int32(); + break; + } + case 6: { + message.processingUnits = reader.int32(); + break; + } + case 7: { + message.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.decode(reader, reader.uint32()); + break; + } + case 5: { + if (message.labels === $util.emptyObject) + message.labels = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.labels[key] = value; + break; + } + case 8: { + message.edition = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateCloudInstanceAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CreateCloudInstanceAction} CreateCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateCloudInstanceAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateCloudInstanceAction message. + * @function verify + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateCloudInstanceAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceConfigId != null && message.hasOwnProperty("instanceConfigId")) + if (!$util.isString(message.instanceConfigId)) + return "instanceConfigId: string expected"; + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) { + properties._nodeCount = 1; + if (!$util.isInteger(message.nodeCount)) + return "nodeCount: integer expected"; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) { + properties._processingUnits = 1; + if (!$util.isInteger(message.processingUnits)) + return "processingUnits: integer expected"; + } + if (message.autoscalingConfig != null && message.hasOwnProperty("autoscalingConfig")) { + properties._autoscalingConfig = 1; + { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.verify(message.autoscalingConfig); + if (error) + return "autoscalingConfig." + error; + } + } + if (message.labels != null && message.hasOwnProperty("labels")) { + if (!$util.isObject(message.labels)) + return "labels: object expected"; + var key = Object.keys(message.labels); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.labels[key[i]])) + return "labels: string{k:string} expected"; + } + if (message.edition != null && message.hasOwnProperty("edition")) + switch (message.edition) { + default: + return "edition: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + return null; + }; + + /** + * Creates a CreateCloudInstanceAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CreateCloudInstanceAction} CreateCloudInstanceAction + */ + CreateCloudInstanceAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CreateCloudInstanceAction) + return object; + var message = new $root.google.spanner.executor.v1.CreateCloudInstanceAction(); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceConfigId != null) + message.instanceConfigId = String(object.instanceConfigId); + if (object.nodeCount != null) + message.nodeCount = object.nodeCount | 0; + if (object.processingUnits != null) + message.processingUnits = object.processingUnits | 0; + if (object.autoscalingConfig != null) { + if (typeof object.autoscalingConfig !== "object") + throw TypeError(".google.spanner.executor.v1.CreateCloudInstanceAction.autoscalingConfig: object expected"); + message.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.fromObject(object.autoscalingConfig); + } + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.spanner.executor.v1.CreateCloudInstanceAction.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNSPECIFIED": + case 0: + message.edition = 0; + break; + case "STANDARD": + case 1: + message.edition = 1; + break; + case "ENTERPRISE": + case 2: + message.edition = 2; + break; + case "ENTERPRISE_PLUS": + case 3: + message.edition = 3; + break; + } + return message; + }; + + /** + * Creates a plain object from a CreateCloudInstanceAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.CreateCloudInstanceAction} message CreateCloudInstanceAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateCloudInstanceAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.instanceId = ""; + object.projectId = ""; + object.instanceConfigId = ""; + object.edition = options.enums === String ? "EDITION_UNSPECIFIED" : 0; + } + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceConfigId != null && message.hasOwnProperty("instanceConfigId")) + object.instanceConfigId = message.instanceConfigId; + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) { + object.nodeCount = message.nodeCount; + if (options.oneofs) + object._nodeCount = "nodeCount"; + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) { + object.processingUnits = message.processingUnits; + if (options.oneofs) + object._processingUnits = "processingUnits"; + } + if (message.autoscalingConfig != null && message.hasOwnProperty("autoscalingConfig")) { + object.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.toObject(message.autoscalingConfig, options); + if (options.oneofs) + object._autoscalingConfig = "autoscalingConfig"; + } + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.spanner.admin.instance.v1.Instance.Edition[message.edition] === undefined ? message.edition : $root.google.spanner.admin.instance.v1.Instance.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this CreateCloudInstanceAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @instance + * @returns {Object.} JSON object + */ + CreateCloudInstanceAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateCloudInstanceAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CreateCloudInstanceAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateCloudInstanceAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CreateCloudInstanceAction"; + }; + + return CreateCloudInstanceAction; + })(); + + v1.UpdateCloudInstanceAction = (function() { + + /** + * Properties of an UpdateCloudInstanceAction. + * @memberof google.spanner.executor.v1 + * @interface IUpdateCloudInstanceAction + * @property {string|null} [instanceId] UpdateCloudInstanceAction instanceId + * @property {string|null} [projectId] UpdateCloudInstanceAction projectId + * @property {string|null} [displayName] UpdateCloudInstanceAction displayName + * @property {number|null} [nodeCount] UpdateCloudInstanceAction nodeCount + * @property {number|null} [processingUnits] UpdateCloudInstanceAction processingUnits + * @property {google.spanner.admin.instance.v1.IAutoscalingConfig|null} [autoscalingConfig] UpdateCloudInstanceAction autoscalingConfig + * @property {Object.|null} [labels] UpdateCloudInstanceAction labels + * @property {google.spanner.admin.instance.v1.Instance.Edition|null} [edition] UpdateCloudInstanceAction edition + */ + + /** + * Constructs a new UpdateCloudInstanceAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an UpdateCloudInstanceAction. + * @implements IUpdateCloudInstanceAction + * @constructor + * @param {google.spanner.executor.v1.IUpdateCloudInstanceAction=} [properties] Properties to set + */ + function UpdateCloudInstanceAction(properties) { + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateCloudInstanceAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + */ + UpdateCloudInstanceAction.prototype.instanceId = ""; + + /** + * UpdateCloudInstanceAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + */ + UpdateCloudInstanceAction.prototype.projectId = ""; + + /** + * UpdateCloudInstanceAction displayName. + * @member {string|null|undefined} displayName + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + */ + UpdateCloudInstanceAction.prototype.displayName = null; + + /** + * UpdateCloudInstanceAction nodeCount. + * @member {number|null|undefined} nodeCount + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + */ + UpdateCloudInstanceAction.prototype.nodeCount = null; + + /** + * UpdateCloudInstanceAction processingUnits. + * @member {number|null|undefined} processingUnits + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + */ + UpdateCloudInstanceAction.prototype.processingUnits = null; + + /** + * UpdateCloudInstanceAction autoscalingConfig. + * @member {google.spanner.admin.instance.v1.IAutoscalingConfig|null|undefined} autoscalingConfig + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + */ + UpdateCloudInstanceAction.prototype.autoscalingConfig = null; + + /** + * UpdateCloudInstanceAction labels. + * @member {Object.} labels + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + */ + UpdateCloudInstanceAction.prototype.labels = $util.emptyObject; + + /** + * UpdateCloudInstanceAction edition. + * @member {google.spanner.admin.instance.v1.Instance.Edition} edition + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + */ + UpdateCloudInstanceAction.prototype.edition = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UpdateCloudInstanceAction.prototype, "_displayName", { + get: $util.oneOfGetter($oneOfFields = ["displayName"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UpdateCloudInstanceAction.prototype, "_nodeCount", { + get: $util.oneOfGetter($oneOfFields = ["nodeCount"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UpdateCloudInstanceAction.prototype, "_processingUnits", { + get: $util.oneOfGetter($oneOfFields = ["processingUnits"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UpdateCloudInstanceAction.prototype, "_autoscalingConfig", { + get: $util.oneOfGetter($oneOfFields = ["autoscalingConfig"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UpdateCloudInstanceAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudInstanceAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.UpdateCloudInstanceAction} UpdateCloudInstanceAction instance + */ + UpdateCloudInstanceAction.create = function create(properties) { + return new UpdateCloudInstanceAction(properties); + }; + + /** + * Encodes the specified UpdateCloudInstanceAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudInstanceAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudInstanceAction} message UpdateCloudInstanceAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateCloudInstanceAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instanceId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.displayName); + if (message.nodeCount != null && Object.hasOwnProperty.call(message, "nodeCount")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.nodeCount); + if (message.processingUnits != null && Object.hasOwnProperty.call(message, "processingUnits")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.processingUnits); + if (message.labels != null && Object.hasOwnProperty.call(message, "labels")) + for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) + writer.uint32(/* id 6, wireType 2 =*/50).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); + if (message.autoscalingConfig != null && Object.hasOwnProperty.call(message, "autoscalingConfig")) + $root.google.spanner.admin.instance.v1.AutoscalingConfig.encode(message.autoscalingConfig, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.edition); + return writer; + }; + + /** + * Encodes the specified UpdateCloudInstanceAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudInstanceAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudInstanceAction} message UpdateCloudInstanceAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateCloudInstanceAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateCloudInstanceAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.UpdateCloudInstanceAction} UpdateCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateCloudInstanceAction.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.spanner.executor.v1.UpdateCloudInstanceAction(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + case 3: { + message.displayName = reader.string(); + break; + } + case 4: { + message.nodeCount = reader.int32(); + break; + } + case 5: { + message.processingUnits = reader.int32(); + break; + } + case 7: { + message.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.decode(reader, reader.uint32()); + break; + } + case 6: { + if (message.labels === $util.emptyObject) + message.labels = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.labels[key] = value; + break; + } + case 8: { + message.edition = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateCloudInstanceAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.UpdateCloudInstanceAction} UpdateCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateCloudInstanceAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateCloudInstanceAction message. + * @function verify + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateCloudInstanceAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.displayName != null && message.hasOwnProperty("displayName")) { + properties._displayName = 1; + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + } + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) { + properties._nodeCount = 1; + if (!$util.isInteger(message.nodeCount)) + return "nodeCount: integer expected"; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) { + properties._processingUnits = 1; + if (!$util.isInteger(message.processingUnits)) + return "processingUnits: integer expected"; + } + if (message.autoscalingConfig != null && message.hasOwnProperty("autoscalingConfig")) { + properties._autoscalingConfig = 1; + { + var error = $root.google.spanner.admin.instance.v1.AutoscalingConfig.verify(message.autoscalingConfig); + if (error) + return "autoscalingConfig." + error; + } + } + if (message.labels != null && message.hasOwnProperty("labels")) { + if (!$util.isObject(message.labels)) + return "labels: object expected"; + var key = Object.keys(message.labels); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.labels[key[i]])) + return "labels: string{k:string} expected"; + } + if (message.edition != null && message.hasOwnProperty("edition")) + switch (message.edition) { + default: + return "edition: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + return null; + }; + + /** + * Creates an UpdateCloudInstanceAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.UpdateCloudInstanceAction} UpdateCloudInstanceAction + */ + UpdateCloudInstanceAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.UpdateCloudInstanceAction) + return object; + var message = new $root.google.spanner.executor.v1.UpdateCloudInstanceAction(); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.displayName != null) + message.displayName = String(object.displayName); + if (object.nodeCount != null) + message.nodeCount = object.nodeCount | 0; + if (object.processingUnits != null) + message.processingUnits = object.processingUnits | 0; + if (object.autoscalingConfig != null) { + if (typeof object.autoscalingConfig !== "object") + throw TypeError(".google.spanner.executor.v1.UpdateCloudInstanceAction.autoscalingConfig: object expected"); + message.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.fromObject(object.autoscalingConfig); + } + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.spanner.executor.v1.UpdateCloudInstanceAction.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNSPECIFIED": + case 0: + message.edition = 0; + break; + case "STANDARD": + case 1: + message.edition = 1; + break; + case "ENTERPRISE": + case 2: + message.edition = 2; + break; + case "ENTERPRISE_PLUS": + case 3: + message.edition = 3; + break; + } + return message; + }; + + /** + * Creates a plain object from an UpdateCloudInstanceAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.UpdateCloudInstanceAction} message UpdateCloudInstanceAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateCloudInstanceAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.instanceId = ""; + object.projectId = ""; + object.edition = options.enums === String ? "EDITION_UNSPECIFIED" : 0; + } + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.displayName != null && message.hasOwnProperty("displayName")) { + object.displayName = message.displayName; + if (options.oneofs) + object._displayName = "displayName"; + } + if (message.nodeCount != null && message.hasOwnProperty("nodeCount")) { + object.nodeCount = message.nodeCount; + if (options.oneofs) + object._nodeCount = "nodeCount"; + } + if (message.processingUnits != null && message.hasOwnProperty("processingUnits")) { + object.processingUnits = message.processingUnits; + if (options.oneofs) + object._processingUnits = "processingUnits"; + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + if (message.autoscalingConfig != null && message.hasOwnProperty("autoscalingConfig")) { + object.autoscalingConfig = $root.google.spanner.admin.instance.v1.AutoscalingConfig.toObject(message.autoscalingConfig, options); + if (options.oneofs) + object._autoscalingConfig = "autoscalingConfig"; + } + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.spanner.admin.instance.v1.Instance.Edition[message.edition] === undefined ? message.edition : $root.google.spanner.admin.instance.v1.Instance.Edition[message.edition] : message.edition; + return object; + }; + + /** + * Converts this UpdateCloudInstanceAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @instance + * @returns {Object.} JSON object + */ + UpdateCloudInstanceAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateCloudInstanceAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.UpdateCloudInstanceAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateCloudInstanceAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.UpdateCloudInstanceAction"; + }; + + return UpdateCloudInstanceAction; + })(); + + v1.DeleteCloudInstanceAction = (function() { + + /** + * Properties of a DeleteCloudInstanceAction. + * @memberof google.spanner.executor.v1 + * @interface IDeleteCloudInstanceAction + * @property {string|null} [instanceId] DeleteCloudInstanceAction instanceId + * @property {string|null} [projectId] DeleteCloudInstanceAction projectId + */ + + /** + * Constructs a new DeleteCloudInstanceAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a DeleteCloudInstanceAction. + * @implements IDeleteCloudInstanceAction + * @constructor + * @param {google.spanner.executor.v1.IDeleteCloudInstanceAction=} [properties] Properties to set + */ + function DeleteCloudInstanceAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteCloudInstanceAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @instance + */ + DeleteCloudInstanceAction.prototype.instanceId = ""; + + /** + * DeleteCloudInstanceAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @instance + */ + DeleteCloudInstanceAction.prototype.projectId = ""; + + /** + * Creates a new DeleteCloudInstanceAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IDeleteCloudInstanceAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.DeleteCloudInstanceAction} DeleteCloudInstanceAction instance + */ + DeleteCloudInstanceAction.create = function create(properties) { + return new DeleteCloudInstanceAction(properties); + }; + + /** + * Encodes the specified DeleteCloudInstanceAction message. Does not implicitly {@link google.spanner.executor.v1.DeleteCloudInstanceAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IDeleteCloudInstanceAction} message DeleteCloudInstanceAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteCloudInstanceAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instanceId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + return writer; + }; + + /** + * Encodes the specified DeleteCloudInstanceAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DeleteCloudInstanceAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IDeleteCloudInstanceAction} message DeleteCloudInstanceAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteCloudInstanceAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteCloudInstanceAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.DeleteCloudInstanceAction} DeleteCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteCloudInstanceAction.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.spanner.executor.v1.DeleteCloudInstanceAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteCloudInstanceAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.DeleteCloudInstanceAction} DeleteCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteCloudInstanceAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteCloudInstanceAction message. + * @function verify + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteCloudInstanceAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + return null; + }; + + /** + * Creates a DeleteCloudInstanceAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.DeleteCloudInstanceAction} DeleteCloudInstanceAction + */ + DeleteCloudInstanceAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.DeleteCloudInstanceAction) + return object; + var message = new $root.google.spanner.executor.v1.DeleteCloudInstanceAction(); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.projectId != null) + message.projectId = String(object.projectId); + return message; + }; + + /** + * Creates a plain object from a DeleteCloudInstanceAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.DeleteCloudInstanceAction} message DeleteCloudInstanceAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteCloudInstanceAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instanceId = ""; + object.projectId = ""; + } + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + return object; + }; + + /** + * Converts this DeleteCloudInstanceAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @instance + * @returns {Object.} JSON object + */ + DeleteCloudInstanceAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteCloudInstanceAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.DeleteCloudInstanceAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteCloudInstanceAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.DeleteCloudInstanceAction"; + }; + + return DeleteCloudInstanceAction; + })(); + + v1.CreateCloudDatabaseAction = (function() { + + /** + * Properties of a CreateCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @interface ICreateCloudDatabaseAction + * @property {string|null} [instanceId] CreateCloudDatabaseAction instanceId + * @property {string|null} [projectId] CreateCloudDatabaseAction projectId + * @property {string|null} [databaseId] CreateCloudDatabaseAction databaseId + * @property {Array.|null} [sdlStatement] CreateCloudDatabaseAction sdlStatement + * @property {google.spanner.admin.database.v1.IEncryptionConfig|null} [encryptionConfig] CreateCloudDatabaseAction encryptionConfig + * @property {string|null} [dialect] CreateCloudDatabaseAction dialect + * @property {Uint8Array|null} [protoDescriptors] CreateCloudDatabaseAction protoDescriptors + */ + + /** + * Constructs a new CreateCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CreateCloudDatabaseAction. + * @implements ICreateCloudDatabaseAction + * @constructor + * @param {google.spanner.executor.v1.ICreateCloudDatabaseAction=} [properties] Properties to set + */ + function CreateCloudDatabaseAction(properties) { + this.sdlStatement = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateCloudDatabaseAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @instance + */ + CreateCloudDatabaseAction.prototype.instanceId = ""; + + /** + * CreateCloudDatabaseAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @instance + */ + CreateCloudDatabaseAction.prototype.projectId = ""; + + /** + * CreateCloudDatabaseAction databaseId. + * @member {string} databaseId + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @instance + */ + CreateCloudDatabaseAction.prototype.databaseId = ""; + + /** + * CreateCloudDatabaseAction sdlStatement. + * @member {Array.} sdlStatement + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @instance + */ + CreateCloudDatabaseAction.prototype.sdlStatement = $util.emptyArray; + + /** + * CreateCloudDatabaseAction encryptionConfig. + * @member {google.spanner.admin.database.v1.IEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @instance + */ + CreateCloudDatabaseAction.prototype.encryptionConfig = null; + + /** + * CreateCloudDatabaseAction dialect. + * @member {string|null|undefined} dialect + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @instance + */ + CreateCloudDatabaseAction.prototype.dialect = null; + + /** + * CreateCloudDatabaseAction protoDescriptors. + * @member {Uint8Array|null|undefined} protoDescriptors + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @instance + */ + CreateCloudDatabaseAction.prototype.protoDescriptors = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CreateCloudDatabaseAction.prototype, "_dialect", { + get: $util.oneOfGetter($oneOfFields = ["dialect"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CreateCloudDatabaseAction.prototype, "_protoDescriptors", { + get: $util.oneOfGetter($oneOfFields = ["protoDescriptors"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new CreateCloudDatabaseAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudDatabaseAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CreateCloudDatabaseAction} CreateCloudDatabaseAction instance + */ + CreateCloudDatabaseAction.create = function create(properties) { + return new CreateCloudDatabaseAction(properties); + }; + + /** + * Encodes the specified CreateCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.CreateCloudDatabaseAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudDatabaseAction} message CreateCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateCloudDatabaseAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instanceId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.databaseId); + if (message.sdlStatement != null && message.sdlStatement.length) + for (var i = 0; i < message.sdlStatement.length; ++i) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.sdlStatement[i]); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.EncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.dialect != null && Object.hasOwnProperty.call(message, "dialect")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.dialect); + if (message.protoDescriptors != null && Object.hasOwnProperty.call(message, "protoDescriptors")) + writer.uint32(/* id 7, wireType 2 =*/58).bytes(message.protoDescriptors); + return writer; + }; + + /** + * Encodes the specified CreateCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CreateCloudDatabaseAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudDatabaseAction} message CreateCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateCloudDatabaseAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateCloudDatabaseAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CreateCloudDatabaseAction} CreateCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateCloudDatabaseAction.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.spanner.executor.v1.CreateCloudDatabaseAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + case 3: { + message.databaseId = reader.string(); + break; + } + case 4: { + if (!(message.sdlStatement && message.sdlStatement.length)) + message.sdlStatement = []; + message.sdlStatement.push(reader.string()); + break; + } + case 5: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.decode(reader, reader.uint32()); + break; + } + case 6: { + message.dialect = reader.string(); + break; + } + case 7: { + message.protoDescriptors = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CreateCloudDatabaseAction} CreateCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateCloudDatabaseAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateCloudDatabaseAction message. + * @function verify + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateCloudDatabaseAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isString(message.databaseId)) + return "databaseId: string expected"; + if (message.sdlStatement != null && message.hasOwnProperty("sdlStatement")) { + if (!Array.isArray(message.sdlStatement)) + return "sdlStatement: array expected"; + for (var i = 0; i < message.sdlStatement.length; ++i) + if (!$util.isString(message.sdlStatement[i])) + return "sdlStatement: string[] expected"; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.EncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + if (message.dialect != null && message.hasOwnProperty("dialect")) { + properties._dialect = 1; + if (!$util.isString(message.dialect)) + return "dialect: string expected"; + } + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) { + properties._protoDescriptors = 1; + if (!(message.protoDescriptors && typeof message.protoDescriptors.length === "number" || $util.isString(message.protoDescriptors))) + return "protoDescriptors: buffer expected"; + } + return null; + }; + + /** + * Creates a CreateCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CreateCloudDatabaseAction} CreateCloudDatabaseAction + */ + CreateCloudDatabaseAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CreateCloudDatabaseAction) + return object; + var message = new $root.google.spanner.executor.v1.CreateCloudDatabaseAction(); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + if (object.sdlStatement) { + if (!Array.isArray(object.sdlStatement)) + throw TypeError(".google.spanner.executor.v1.CreateCloudDatabaseAction.sdlStatement: array expected"); + message.sdlStatement = []; + for (var i = 0; i < object.sdlStatement.length; ++i) + message.sdlStatement[i] = String(object.sdlStatement[i]); + } + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.executor.v1.CreateCloudDatabaseAction.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.fromObject(object.encryptionConfig); + } + if (object.dialect != null) + message.dialect = String(object.dialect); + if (object.protoDescriptors != null) + if (typeof object.protoDescriptors === "string") + $util.base64.decode(object.protoDescriptors, message.protoDescriptors = $util.newBuffer($util.base64.length(object.protoDescriptors)), 0); + else if (object.protoDescriptors.length >= 0) + message.protoDescriptors = object.protoDescriptors; + return message; + }; + + /** + * Creates a plain object from a CreateCloudDatabaseAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.CreateCloudDatabaseAction} message CreateCloudDatabaseAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateCloudDatabaseAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.sdlStatement = []; + if (options.defaults) { + object.instanceId = ""; + object.projectId = ""; + object.databaseId = ""; + object.encryptionConfig = null; + } + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + if (message.sdlStatement && message.sdlStatement.length) { + object.sdlStatement = []; + for (var j = 0; j < message.sdlStatement.length; ++j) + object.sdlStatement[j] = message.sdlStatement[j]; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.toObject(message.encryptionConfig, options); + if (message.dialect != null && message.hasOwnProperty("dialect")) { + object.dialect = message.dialect; + if (options.oneofs) + object._dialect = "dialect"; + } + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) { + object.protoDescriptors = options.bytes === String ? $util.base64.encode(message.protoDescriptors, 0, message.protoDescriptors.length) : options.bytes === Array ? Array.prototype.slice.call(message.protoDescriptors) : message.protoDescriptors; + if (options.oneofs) + object._protoDescriptors = "protoDescriptors"; + } + return object; + }; + + /** + * Converts this CreateCloudDatabaseAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @instance + * @returns {Object.} JSON object + */ + CreateCloudDatabaseAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateCloudDatabaseAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CreateCloudDatabaseAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateCloudDatabaseAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CreateCloudDatabaseAction"; + }; + + return CreateCloudDatabaseAction; + })(); + + v1.UpdateCloudDatabaseDdlAction = (function() { + + /** + * Properties of an UpdateCloudDatabaseDdlAction. + * @memberof google.spanner.executor.v1 + * @interface IUpdateCloudDatabaseDdlAction + * @property {string|null} [instanceId] UpdateCloudDatabaseDdlAction instanceId + * @property {string|null} [projectId] UpdateCloudDatabaseDdlAction projectId + * @property {string|null} [databaseId] UpdateCloudDatabaseDdlAction databaseId + * @property {Array.|null} [sdlStatement] UpdateCloudDatabaseDdlAction sdlStatement + * @property {string|null} [operationId] UpdateCloudDatabaseDdlAction operationId + * @property {Uint8Array|null} [protoDescriptors] UpdateCloudDatabaseDdlAction protoDescriptors + */ + + /** + * Constructs a new UpdateCloudDatabaseDdlAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an UpdateCloudDatabaseDdlAction. + * @implements IUpdateCloudDatabaseDdlAction + * @constructor + * @param {google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction=} [properties] Properties to set + */ + function UpdateCloudDatabaseDdlAction(properties) { + this.sdlStatement = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateCloudDatabaseDdlAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @instance + */ + UpdateCloudDatabaseDdlAction.prototype.instanceId = ""; + + /** + * UpdateCloudDatabaseDdlAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @instance + */ + UpdateCloudDatabaseDdlAction.prototype.projectId = ""; + + /** + * UpdateCloudDatabaseDdlAction databaseId. + * @member {string} databaseId + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @instance + */ + UpdateCloudDatabaseDdlAction.prototype.databaseId = ""; + + /** + * UpdateCloudDatabaseDdlAction sdlStatement. + * @member {Array.} sdlStatement + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @instance + */ + UpdateCloudDatabaseDdlAction.prototype.sdlStatement = $util.emptyArray; + + /** + * UpdateCloudDatabaseDdlAction operationId. + * @member {string} operationId + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @instance + */ + UpdateCloudDatabaseDdlAction.prototype.operationId = ""; + + /** + * UpdateCloudDatabaseDdlAction protoDescriptors. + * @member {Uint8Array|null|undefined} protoDescriptors + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @instance + */ + UpdateCloudDatabaseDdlAction.prototype.protoDescriptors = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UpdateCloudDatabaseDdlAction.prototype, "_protoDescriptors", { + get: $util.oneOfGetter($oneOfFields = ["protoDescriptors"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UpdateCloudDatabaseDdlAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.UpdateCloudDatabaseDdlAction} UpdateCloudDatabaseDdlAction instance + */ + UpdateCloudDatabaseDdlAction.create = function create(properties) { + return new UpdateCloudDatabaseDdlAction(properties); + }; + + /** + * Encodes the specified UpdateCloudDatabaseDdlAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction} message UpdateCloudDatabaseDdlAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateCloudDatabaseDdlAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instanceId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.databaseId); + if (message.sdlStatement != null && message.sdlStatement.length) + for (var i = 0; i < message.sdlStatement.length; ++i) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.sdlStatement[i]); + if (message.operationId != null && Object.hasOwnProperty.call(message, "operationId")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.operationId); + if (message.protoDescriptors != null && Object.hasOwnProperty.call(message, "protoDescriptors")) + writer.uint32(/* id 6, wireType 2 =*/50).bytes(message.protoDescriptors); + return writer; + }; + + /** + * Encodes the specified UpdateCloudDatabaseDdlAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudDatabaseDdlAction} message UpdateCloudDatabaseDdlAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateCloudDatabaseDdlAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateCloudDatabaseDdlAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.UpdateCloudDatabaseDdlAction} UpdateCloudDatabaseDdlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateCloudDatabaseDdlAction.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.spanner.executor.v1.UpdateCloudDatabaseDdlAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + case 3: { + message.databaseId = reader.string(); + break; + } + case 4: { + if (!(message.sdlStatement && message.sdlStatement.length)) + message.sdlStatement = []; + message.sdlStatement.push(reader.string()); + break; + } + case 5: { + message.operationId = reader.string(); + break; + } + case 6: { + message.protoDescriptors = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateCloudDatabaseDdlAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.UpdateCloudDatabaseDdlAction} UpdateCloudDatabaseDdlAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateCloudDatabaseDdlAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateCloudDatabaseDdlAction message. + * @function verify + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateCloudDatabaseDdlAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isString(message.databaseId)) + return "databaseId: string expected"; + if (message.sdlStatement != null && message.hasOwnProperty("sdlStatement")) { + if (!Array.isArray(message.sdlStatement)) + return "sdlStatement: array expected"; + for (var i = 0; i < message.sdlStatement.length; ++i) + if (!$util.isString(message.sdlStatement[i])) + return "sdlStatement: string[] expected"; + } + if (message.operationId != null && message.hasOwnProperty("operationId")) + if (!$util.isString(message.operationId)) + return "operationId: string expected"; + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) { + properties._protoDescriptors = 1; + if (!(message.protoDescriptors && typeof message.protoDescriptors.length === "number" || $util.isString(message.protoDescriptors))) + return "protoDescriptors: buffer expected"; + } + return null; + }; + + /** + * Creates an UpdateCloudDatabaseDdlAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.UpdateCloudDatabaseDdlAction} UpdateCloudDatabaseDdlAction + */ + UpdateCloudDatabaseDdlAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.UpdateCloudDatabaseDdlAction) + return object; + var message = new $root.google.spanner.executor.v1.UpdateCloudDatabaseDdlAction(); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + if (object.sdlStatement) { + if (!Array.isArray(object.sdlStatement)) + throw TypeError(".google.spanner.executor.v1.UpdateCloudDatabaseDdlAction.sdlStatement: array expected"); + message.sdlStatement = []; + for (var i = 0; i < object.sdlStatement.length; ++i) + message.sdlStatement[i] = String(object.sdlStatement[i]); + } + if (object.operationId != null) + message.operationId = String(object.operationId); + if (object.protoDescriptors != null) + if (typeof object.protoDescriptors === "string") + $util.base64.decode(object.protoDescriptors, message.protoDescriptors = $util.newBuffer($util.base64.length(object.protoDescriptors)), 0); + else if (object.protoDescriptors.length >= 0) + message.protoDescriptors = object.protoDescriptors; + return message; + }; + + /** + * Creates a plain object from an UpdateCloudDatabaseDdlAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {google.spanner.executor.v1.UpdateCloudDatabaseDdlAction} message UpdateCloudDatabaseDdlAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateCloudDatabaseDdlAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.sdlStatement = []; + if (options.defaults) { + object.instanceId = ""; + object.projectId = ""; + object.databaseId = ""; + object.operationId = ""; + } + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + if (message.sdlStatement && message.sdlStatement.length) { + object.sdlStatement = []; + for (var j = 0; j < message.sdlStatement.length; ++j) + object.sdlStatement[j] = message.sdlStatement[j]; + } + if (message.operationId != null && message.hasOwnProperty("operationId")) + object.operationId = message.operationId; + if (message.protoDescriptors != null && message.hasOwnProperty("protoDescriptors")) { + object.protoDescriptors = options.bytes === String ? $util.base64.encode(message.protoDescriptors, 0, message.protoDescriptors.length) : options.bytes === Array ? Array.prototype.slice.call(message.protoDescriptors) : message.protoDescriptors; + if (options.oneofs) + object._protoDescriptors = "protoDescriptors"; + } + return object; + }; + + /** + * Converts this UpdateCloudDatabaseDdlAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @instance + * @returns {Object.} JSON object + */ + UpdateCloudDatabaseDdlAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateCloudDatabaseDdlAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseDdlAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateCloudDatabaseDdlAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.UpdateCloudDatabaseDdlAction"; + }; + + return UpdateCloudDatabaseDdlAction; + })(); + + v1.UpdateCloudDatabaseAction = (function() { + + /** + * Properties of an UpdateCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @interface IUpdateCloudDatabaseAction + * @property {string|null} [instanceId] UpdateCloudDatabaseAction instanceId + * @property {string|null} [projectId] UpdateCloudDatabaseAction projectId + * @property {string|null} [databaseName] UpdateCloudDatabaseAction databaseName + * @property {boolean|null} [enableDropProtection] UpdateCloudDatabaseAction enableDropProtection + */ + + /** + * Constructs a new UpdateCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an UpdateCloudDatabaseAction. + * @implements IUpdateCloudDatabaseAction + * @constructor + * @param {google.spanner.executor.v1.IUpdateCloudDatabaseAction=} [properties] Properties to set + */ + function UpdateCloudDatabaseAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateCloudDatabaseAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @instance + */ + UpdateCloudDatabaseAction.prototype.instanceId = ""; + + /** + * UpdateCloudDatabaseAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @instance + */ + UpdateCloudDatabaseAction.prototype.projectId = ""; + + /** + * UpdateCloudDatabaseAction databaseName. + * @member {string} databaseName + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @instance + */ + UpdateCloudDatabaseAction.prototype.databaseName = ""; + + /** + * UpdateCloudDatabaseAction enableDropProtection. + * @member {boolean} enableDropProtection + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @instance + */ + UpdateCloudDatabaseAction.prototype.enableDropProtection = false; + + /** + * Creates a new UpdateCloudDatabaseAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudDatabaseAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.UpdateCloudDatabaseAction} UpdateCloudDatabaseAction instance + */ + UpdateCloudDatabaseAction.create = function create(properties) { + return new UpdateCloudDatabaseAction(properties); + }; + + /** + * Encodes the specified UpdateCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudDatabaseAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudDatabaseAction} message UpdateCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateCloudDatabaseAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instanceId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + if (message.databaseName != null && Object.hasOwnProperty.call(message, "databaseName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.databaseName); + if (message.enableDropProtection != null && Object.hasOwnProperty.call(message, "enableDropProtection")) + writer.uint32(/* id 4, wireType 0 =*/32).bool(message.enableDropProtection); + return writer; + }; + + /** + * Encodes the specified UpdateCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudDatabaseAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudDatabaseAction} message UpdateCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateCloudDatabaseAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateCloudDatabaseAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.UpdateCloudDatabaseAction} UpdateCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateCloudDatabaseAction.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.spanner.executor.v1.UpdateCloudDatabaseAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + case 3: { + message.databaseName = reader.string(); + break; + } + case 4: { + message.enableDropProtection = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.UpdateCloudDatabaseAction} UpdateCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateCloudDatabaseAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateCloudDatabaseAction message. + * @function verify + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateCloudDatabaseAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.databaseName != null && message.hasOwnProperty("databaseName")) + if (!$util.isString(message.databaseName)) + return "databaseName: string expected"; + if (message.enableDropProtection != null && message.hasOwnProperty("enableDropProtection")) + if (typeof message.enableDropProtection !== "boolean") + return "enableDropProtection: boolean expected"; + return null; + }; + + /** + * Creates an UpdateCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.UpdateCloudDatabaseAction} UpdateCloudDatabaseAction + */ + UpdateCloudDatabaseAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.UpdateCloudDatabaseAction) + return object; + var message = new $root.google.spanner.executor.v1.UpdateCloudDatabaseAction(); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.databaseName != null) + message.databaseName = String(object.databaseName); + if (object.enableDropProtection != null) + message.enableDropProtection = Boolean(object.enableDropProtection); + return message; + }; + + /** + * Creates a plain object from an UpdateCloudDatabaseAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.UpdateCloudDatabaseAction} message UpdateCloudDatabaseAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateCloudDatabaseAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instanceId = ""; + object.projectId = ""; + object.databaseName = ""; + object.enableDropProtection = false; + } + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.databaseName != null && message.hasOwnProperty("databaseName")) + object.databaseName = message.databaseName; + if (message.enableDropProtection != null && message.hasOwnProperty("enableDropProtection")) + object.enableDropProtection = message.enableDropProtection; + return object; + }; + + /** + * Converts this UpdateCloudDatabaseAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @instance + * @returns {Object.} JSON object + */ + UpdateCloudDatabaseAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateCloudDatabaseAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.UpdateCloudDatabaseAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateCloudDatabaseAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.UpdateCloudDatabaseAction"; + }; + + return UpdateCloudDatabaseAction; + })(); + + v1.DropCloudDatabaseAction = (function() { + + /** + * Properties of a DropCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @interface IDropCloudDatabaseAction + * @property {string|null} [instanceId] DropCloudDatabaseAction instanceId + * @property {string|null} [projectId] DropCloudDatabaseAction projectId + * @property {string|null} [databaseId] DropCloudDatabaseAction databaseId + */ + + /** + * Constructs a new DropCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a DropCloudDatabaseAction. + * @implements IDropCloudDatabaseAction + * @constructor + * @param {google.spanner.executor.v1.IDropCloudDatabaseAction=} [properties] Properties to set + */ + function DropCloudDatabaseAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DropCloudDatabaseAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @instance + */ + DropCloudDatabaseAction.prototype.instanceId = ""; + + /** + * DropCloudDatabaseAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @instance + */ + DropCloudDatabaseAction.prototype.projectId = ""; + + /** + * DropCloudDatabaseAction databaseId. + * @member {string} databaseId + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @instance + */ + DropCloudDatabaseAction.prototype.databaseId = ""; + + /** + * Creates a new DropCloudDatabaseAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IDropCloudDatabaseAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.DropCloudDatabaseAction} DropCloudDatabaseAction instance + */ + DropCloudDatabaseAction.create = function create(properties) { + return new DropCloudDatabaseAction(properties); + }; + + /** + * Encodes the specified DropCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.DropCloudDatabaseAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IDropCloudDatabaseAction} message DropCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DropCloudDatabaseAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.instanceId); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.projectId); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.databaseId); + return writer; + }; + + /** + * Encodes the specified DropCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DropCloudDatabaseAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IDropCloudDatabaseAction} message DropCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DropCloudDatabaseAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DropCloudDatabaseAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.DropCloudDatabaseAction} DropCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DropCloudDatabaseAction.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.spanner.executor.v1.DropCloudDatabaseAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.instanceId = reader.string(); + break; + } + case 2: { + message.projectId = reader.string(); + break; + } + case 3: { + message.databaseId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DropCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.DropCloudDatabaseAction} DropCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DropCloudDatabaseAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DropCloudDatabaseAction message. + * @function verify + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DropCloudDatabaseAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isString(message.databaseId)) + return "databaseId: string expected"; + return null; + }; + + /** + * Creates a DropCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.DropCloudDatabaseAction} DropCloudDatabaseAction + */ + DropCloudDatabaseAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.DropCloudDatabaseAction) + return object; + var message = new $root.google.spanner.executor.v1.DropCloudDatabaseAction(); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + return message; + }; + + /** + * Creates a plain object from a DropCloudDatabaseAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.DropCloudDatabaseAction} message DropCloudDatabaseAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DropCloudDatabaseAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.instanceId = ""; + object.projectId = ""; + object.databaseId = ""; + } + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + return object; + }; + + /** + * Converts this DropCloudDatabaseAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @instance + * @returns {Object.} JSON object + */ + DropCloudDatabaseAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DropCloudDatabaseAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.DropCloudDatabaseAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DropCloudDatabaseAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.DropCloudDatabaseAction"; + }; + + return DropCloudDatabaseAction; + })(); + + v1.ChangeQuorumCloudDatabaseAction = (function() { + + /** + * Properties of a ChangeQuorumCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @interface IChangeQuorumCloudDatabaseAction + * @property {string|null} [databaseUri] ChangeQuorumCloudDatabaseAction databaseUri + * @property {Array.|null} [servingLocations] ChangeQuorumCloudDatabaseAction servingLocations + */ + + /** + * Constructs a new ChangeQuorumCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ChangeQuorumCloudDatabaseAction. + * @implements IChangeQuorumCloudDatabaseAction + * @constructor + * @param {google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction=} [properties] Properties to set + */ + function ChangeQuorumCloudDatabaseAction(properties) { + this.servingLocations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ChangeQuorumCloudDatabaseAction databaseUri. + * @member {string|null|undefined} databaseUri + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @instance + */ + ChangeQuorumCloudDatabaseAction.prototype.databaseUri = null; + + /** + * ChangeQuorumCloudDatabaseAction servingLocations. + * @member {Array.} servingLocations + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @instance + */ + ChangeQuorumCloudDatabaseAction.prototype.servingLocations = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ChangeQuorumCloudDatabaseAction.prototype, "_databaseUri", { + get: $util.oneOfGetter($oneOfFields = ["databaseUri"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ChangeQuorumCloudDatabaseAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction} ChangeQuorumCloudDatabaseAction instance + */ + ChangeQuorumCloudDatabaseAction.create = function create(properties) { + return new ChangeQuorumCloudDatabaseAction(properties); + }; + + /** + * Encodes the specified ChangeQuorumCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction} message ChangeQuorumCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChangeQuorumCloudDatabaseAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.databaseUri != null && Object.hasOwnProperty.call(message, "databaseUri")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.databaseUri); + if (message.servingLocations != null && message.servingLocations.length) + for (var i = 0; i < message.servingLocations.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.servingLocations[i]); + return writer; + }; + + /** + * Encodes the specified ChangeQuorumCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IChangeQuorumCloudDatabaseAction} message ChangeQuorumCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChangeQuorumCloudDatabaseAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ChangeQuorumCloudDatabaseAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction} ChangeQuorumCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChangeQuorumCloudDatabaseAction.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.spanner.executor.v1.ChangeQuorumCloudDatabaseAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.databaseUri = reader.string(); + break; + } + case 2: { + if (!(message.servingLocations && message.servingLocations.length)) + message.servingLocations = []; + message.servingLocations.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ChangeQuorumCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction} ChangeQuorumCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChangeQuorumCloudDatabaseAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ChangeQuorumCloudDatabaseAction message. + * @function verify + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ChangeQuorumCloudDatabaseAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.databaseUri != null && message.hasOwnProperty("databaseUri")) { + properties._databaseUri = 1; + if (!$util.isString(message.databaseUri)) + return "databaseUri: string expected"; + } + if (message.servingLocations != null && message.hasOwnProperty("servingLocations")) { + if (!Array.isArray(message.servingLocations)) + return "servingLocations: array expected"; + for (var i = 0; i < message.servingLocations.length; ++i) + if (!$util.isString(message.servingLocations[i])) + return "servingLocations: string[] expected"; + } + return null; + }; + + /** + * Creates a ChangeQuorumCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction} ChangeQuorumCloudDatabaseAction + */ + ChangeQuorumCloudDatabaseAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction) + return object; + var message = new $root.google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction(); + if (object.databaseUri != null) + message.databaseUri = String(object.databaseUri); + if (object.servingLocations) { + if (!Array.isArray(object.servingLocations)) + throw TypeError(".google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction.servingLocations: array expected"); + message.servingLocations = []; + for (var i = 0; i < object.servingLocations.length; ++i) + message.servingLocations[i] = String(object.servingLocations[i]); + } + return message; + }; + + /** + * Creates a plain object from a ChangeQuorumCloudDatabaseAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction} message ChangeQuorumCloudDatabaseAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ChangeQuorumCloudDatabaseAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.servingLocations = []; + if (message.databaseUri != null && message.hasOwnProperty("databaseUri")) { + object.databaseUri = message.databaseUri; + if (options.oneofs) + object._databaseUri = "databaseUri"; + } + if (message.servingLocations && message.servingLocations.length) { + object.servingLocations = []; + for (var j = 0; j < message.servingLocations.length; ++j) + object.servingLocations[j] = message.servingLocations[j]; + } + return object; + }; + + /** + * Converts this ChangeQuorumCloudDatabaseAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @instance + * @returns {Object.} JSON object + */ + ChangeQuorumCloudDatabaseAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ChangeQuorumCloudDatabaseAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ChangeQuorumCloudDatabaseAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ChangeQuorumCloudDatabaseAction"; + }; + + return ChangeQuorumCloudDatabaseAction; + })(); + + v1.AdaptMessageAction = (function() { + + /** + * Properties of an AdaptMessageAction. + * @memberof google.spanner.executor.v1 + * @interface IAdaptMessageAction + * @property {string|null} [databaseUri] AdaptMessageAction databaseUri + * @property {string|null} [protocol] AdaptMessageAction protocol + * @property {Uint8Array|null} [payload] AdaptMessageAction payload + * @property {Object.|null} [attachments] AdaptMessageAction attachments + * @property {string|null} [query] AdaptMessageAction query + * @property {boolean|null} [prepareThenExecute] AdaptMessageAction prepareThenExecute + */ + + /** + * Constructs a new AdaptMessageAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an AdaptMessageAction. + * @implements IAdaptMessageAction + * @constructor + * @param {google.spanner.executor.v1.IAdaptMessageAction=} [properties] Properties to set + */ + function AdaptMessageAction(properties) { + this.attachments = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AdaptMessageAction databaseUri. + * @member {string} databaseUri + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @instance + */ + AdaptMessageAction.prototype.databaseUri = ""; + + /** + * AdaptMessageAction protocol. + * @member {string} protocol + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @instance + */ + AdaptMessageAction.prototype.protocol = ""; + + /** + * AdaptMessageAction payload. + * @member {Uint8Array} payload + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @instance + */ + AdaptMessageAction.prototype.payload = $util.newBuffer([]); + + /** + * AdaptMessageAction attachments. + * @member {Object.} attachments + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @instance + */ + AdaptMessageAction.prototype.attachments = $util.emptyObject; + + /** + * AdaptMessageAction query. + * @member {string} query + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @instance + */ + AdaptMessageAction.prototype.query = ""; + + /** + * AdaptMessageAction prepareThenExecute. + * @member {boolean} prepareThenExecute + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @instance + */ + AdaptMessageAction.prototype.prepareThenExecute = false; + + /** + * Creates a new AdaptMessageAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {google.spanner.executor.v1.IAdaptMessageAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.AdaptMessageAction} AdaptMessageAction instance + */ + AdaptMessageAction.create = function create(properties) { + return new AdaptMessageAction(properties); + }; + + /** + * Encodes the specified AdaptMessageAction message. Does not implicitly {@link google.spanner.executor.v1.AdaptMessageAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {google.spanner.executor.v1.IAdaptMessageAction} message AdaptMessageAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AdaptMessageAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.databaseUri != null && Object.hasOwnProperty.call(message, "databaseUri")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.databaseUri); + if (message.protocol != null && Object.hasOwnProperty.call(message, "protocol")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.protocol); + if (message.payload != null && Object.hasOwnProperty.call(message, "payload")) + writer.uint32(/* id 3, wireType 2 =*/26).bytes(message.payload); + if (message.attachments != null && Object.hasOwnProperty.call(message, "attachments")) + for (var keys = Object.keys(message.attachments), i = 0; i < keys.length; ++i) + writer.uint32(/* id 4, wireType 2 =*/34).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.attachments[keys[i]]).ldelim(); + if (message.query != null && Object.hasOwnProperty.call(message, "query")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.query); + if (message.prepareThenExecute != null && Object.hasOwnProperty.call(message, "prepareThenExecute")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.prepareThenExecute); + return writer; + }; + + /** + * Encodes the specified AdaptMessageAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.AdaptMessageAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {google.spanner.executor.v1.IAdaptMessageAction} message AdaptMessageAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AdaptMessageAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AdaptMessageAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.AdaptMessageAction} AdaptMessageAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AdaptMessageAction.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.spanner.executor.v1.AdaptMessageAction(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.databaseUri = reader.string(); + break; + } + case 2: { + message.protocol = reader.string(); + break; + } + case 3: { + message.payload = reader.bytes(); + break; + } + case 4: { + if (message.attachments === $util.emptyObject) + message.attachments = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.attachments[key] = value; + break; + } + case 5: { + message.query = reader.string(); + break; + } + case 6: { + message.prepareThenExecute = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AdaptMessageAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.AdaptMessageAction} AdaptMessageAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AdaptMessageAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AdaptMessageAction message. + * @function verify + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AdaptMessageAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.databaseUri != null && message.hasOwnProperty("databaseUri")) + if (!$util.isString(message.databaseUri)) + return "databaseUri: string expected"; + if (message.protocol != null && message.hasOwnProperty("protocol")) + if (!$util.isString(message.protocol)) + return "protocol: string expected"; + if (message.payload != null && message.hasOwnProperty("payload")) + if (!(message.payload && typeof message.payload.length === "number" || $util.isString(message.payload))) + return "payload: buffer expected"; + if (message.attachments != null && message.hasOwnProperty("attachments")) { + if (!$util.isObject(message.attachments)) + return "attachments: object expected"; + var key = Object.keys(message.attachments); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.attachments[key[i]])) + return "attachments: string{k:string} expected"; + } + if (message.query != null && message.hasOwnProperty("query")) + if (!$util.isString(message.query)) + return "query: string expected"; + if (message.prepareThenExecute != null && message.hasOwnProperty("prepareThenExecute")) + if (typeof message.prepareThenExecute !== "boolean") + return "prepareThenExecute: boolean expected"; + return null; + }; + + /** + * Creates an AdaptMessageAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.AdaptMessageAction} AdaptMessageAction + */ + AdaptMessageAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.AdaptMessageAction) + return object; + var message = new $root.google.spanner.executor.v1.AdaptMessageAction(); + if (object.databaseUri != null) + message.databaseUri = String(object.databaseUri); + if (object.protocol != null) + message.protocol = String(object.protocol); + if (object.payload != null) + if (typeof object.payload === "string") + $util.base64.decode(object.payload, message.payload = $util.newBuffer($util.base64.length(object.payload)), 0); + else if (object.payload.length >= 0) + message.payload = object.payload; + if (object.attachments) { + if (typeof object.attachments !== "object") + throw TypeError(".google.spanner.executor.v1.AdaptMessageAction.attachments: object expected"); + message.attachments = {}; + for (var keys = Object.keys(object.attachments), i = 0; i < keys.length; ++i) + message.attachments[keys[i]] = String(object.attachments[keys[i]]); + } + if (object.query != null) + message.query = String(object.query); + if (object.prepareThenExecute != null) + message.prepareThenExecute = Boolean(object.prepareThenExecute); + return message; + }; + + /** + * Creates a plain object from an AdaptMessageAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {google.spanner.executor.v1.AdaptMessageAction} message AdaptMessageAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AdaptMessageAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.attachments = {}; + if (options.defaults) { + object.databaseUri = ""; + object.protocol = ""; + if (options.bytes === String) + object.payload = ""; + else { + object.payload = []; + if (options.bytes !== Array) + object.payload = $util.newBuffer(object.payload); + } + object.query = ""; + object.prepareThenExecute = false; + } + if (message.databaseUri != null && message.hasOwnProperty("databaseUri")) + object.databaseUri = message.databaseUri; + if (message.protocol != null && message.hasOwnProperty("protocol")) + object.protocol = message.protocol; + if (message.payload != null && message.hasOwnProperty("payload")) + object.payload = options.bytes === String ? $util.base64.encode(message.payload, 0, message.payload.length) : options.bytes === Array ? Array.prototype.slice.call(message.payload) : message.payload; + var keys2; + if (message.attachments && (keys2 = Object.keys(message.attachments)).length) { + object.attachments = {}; + for (var j = 0; j < keys2.length; ++j) + object.attachments[keys2[j]] = message.attachments[keys2[j]]; + } + if (message.query != null && message.hasOwnProperty("query")) + object.query = message.query; + if (message.prepareThenExecute != null && message.hasOwnProperty("prepareThenExecute")) + object.prepareThenExecute = message.prepareThenExecute; + return object; + }; + + /** + * Converts this AdaptMessageAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @instance + * @returns {Object.} JSON object + */ + AdaptMessageAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AdaptMessageAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.AdaptMessageAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AdaptMessageAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.AdaptMessageAction"; + }; + + return AdaptMessageAction; + })(); + + v1.ListCloudDatabasesAction = (function() { + + /** + * Properties of a ListCloudDatabasesAction. + * @memberof google.spanner.executor.v1 + * @interface IListCloudDatabasesAction + * @property {string|null} [projectId] ListCloudDatabasesAction projectId + * @property {string|null} [instanceId] ListCloudDatabasesAction instanceId + * @property {number|null} [pageSize] ListCloudDatabasesAction pageSize + * @property {string|null} [pageToken] ListCloudDatabasesAction pageToken + */ + + /** + * Constructs a new ListCloudDatabasesAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ListCloudDatabasesAction. + * @implements IListCloudDatabasesAction + * @constructor + * @param {google.spanner.executor.v1.IListCloudDatabasesAction=} [properties] Properties to set + */ + function ListCloudDatabasesAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCloudDatabasesAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @instance + */ + ListCloudDatabasesAction.prototype.projectId = ""; + + /** + * ListCloudDatabasesAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @instance + */ + ListCloudDatabasesAction.prototype.instanceId = ""; + + /** + * ListCloudDatabasesAction pageSize. + * @member {number} pageSize + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @instance + */ + ListCloudDatabasesAction.prototype.pageSize = 0; + + /** + * ListCloudDatabasesAction pageToken. + * @member {string} pageToken + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @instance + */ + ListCloudDatabasesAction.prototype.pageToken = ""; + + /** + * Creates a new ListCloudDatabasesAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {google.spanner.executor.v1.IListCloudDatabasesAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ListCloudDatabasesAction} ListCloudDatabasesAction instance + */ + ListCloudDatabasesAction.create = function create(properties) { + return new ListCloudDatabasesAction(properties); + }; + + /** + * Encodes the specified ListCloudDatabasesAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudDatabasesAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {google.spanner.executor.v1.IListCloudDatabasesAction} message ListCloudDatabasesAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudDatabasesAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListCloudDatabasesAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudDatabasesAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {google.spanner.executor.v1.IListCloudDatabasesAction} message ListCloudDatabasesAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudDatabasesAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListCloudDatabasesAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ListCloudDatabasesAction} ListCloudDatabasesAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudDatabasesAction.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.spanner.executor.v1.ListCloudDatabasesAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListCloudDatabasesAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ListCloudDatabasesAction} ListCloudDatabasesAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudDatabasesAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListCloudDatabasesAction message. + * @function verify + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListCloudDatabasesAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListCloudDatabasesAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ListCloudDatabasesAction} ListCloudDatabasesAction + */ + ListCloudDatabasesAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ListCloudDatabasesAction) + return object; + var message = new $root.google.spanner.executor.v1.ListCloudDatabasesAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListCloudDatabasesAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {google.spanner.executor.v1.ListCloudDatabasesAction} message ListCloudDatabasesAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCloudDatabasesAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListCloudDatabasesAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @instance + * @returns {Object.} JSON object + */ + ListCloudDatabasesAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCloudDatabasesAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ListCloudDatabasesAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCloudDatabasesAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ListCloudDatabasesAction"; + }; + + return ListCloudDatabasesAction; + })(); + + v1.ListCloudInstancesAction = (function() { + + /** + * Properties of a ListCloudInstancesAction. + * @memberof google.spanner.executor.v1 + * @interface IListCloudInstancesAction + * @property {string|null} [projectId] ListCloudInstancesAction projectId + * @property {string|null} [filter] ListCloudInstancesAction filter + * @property {number|null} [pageSize] ListCloudInstancesAction pageSize + * @property {string|null} [pageToken] ListCloudInstancesAction pageToken + */ + + /** + * Constructs a new ListCloudInstancesAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ListCloudInstancesAction. + * @implements IListCloudInstancesAction + * @constructor + * @param {google.spanner.executor.v1.IListCloudInstancesAction=} [properties] Properties to set + */ + function ListCloudInstancesAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCloudInstancesAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @instance + */ + ListCloudInstancesAction.prototype.projectId = ""; + + /** + * ListCloudInstancesAction filter. + * @member {string|null|undefined} filter + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @instance + */ + ListCloudInstancesAction.prototype.filter = null; + + /** + * ListCloudInstancesAction pageSize. + * @member {number|null|undefined} pageSize + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @instance + */ + ListCloudInstancesAction.prototype.pageSize = null; + + /** + * ListCloudInstancesAction pageToken. + * @member {string|null|undefined} pageToken + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @instance + */ + ListCloudInstancesAction.prototype.pageToken = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListCloudInstancesAction.prototype, "_filter", { + get: $util.oneOfGetter($oneOfFields = ["filter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListCloudInstancesAction.prototype, "_pageSize", { + get: $util.oneOfGetter($oneOfFields = ["pageSize"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListCloudInstancesAction.prototype, "_pageToken", { + get: $util.oneOfGetter($oneOfFields = ["pageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListCloudInstancesAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {google.spanner.executor.v1.IListCloudInstancesAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ListCloudInstancesAction} ListCloudInstancesAction instance + */ + ListCloudInstancesAction.create = function create(properties) { + return new ListCloudInstancesAction(properties); + }; + + /** + * Encodes the specified ListCloudInstancesAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudInstancesAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {google.spanner.executor.v1.IListCloudInstancesAction} message ListCloudInstancesAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudInstancesAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListCloudInstancesAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudInstancesAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {google.spanner.executor.v1.IListCloudInstancesAction} message ListCloudInstancesAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudInstancesAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListCloudInstancesAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ListCloudInstancesAction} ListCloudInstancesAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudInstancesAction.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.spanner.executor.v1.ListCloudInstancesAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListCloudInstancesAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ListCloudInstancesAction} ListCloudInstancesAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudInstancesAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListCloudInstancesAction message. + * @function verify + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListCloudInstancesAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) { + properties._filter = 1; + if (!$util.isString(message.filter)) + return "filter: string expected"; + } + if (message.pageSize != null && message.hasOwnProperty("pageSize")) { + properties._pageSize = 1; + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + properties._pageToken = 1; + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + } + return null; + }; + + /** + * Creates a ListCloudInstancesAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ListCloudInstancesAction} ListCloudInstancesAction + */ + ListCloudInstancesAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ListCloudInstancesAction) + return object; + var message = new $root.google.spanner.executor.v1.ListCloudInstancesAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListCloudInstancesAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {google.spanner.executor.v1.ListCloudInstancesAction} message ListCloudInstancesAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCloudInstancesAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.projectId = ""; + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = message.filter; + if (options.oneofs) + object._filter = "filter"; + } + if (message.pageSize != null && message.hasOwnProperty("pageSize")) { + object.pageSize = message.pageSize; + if (options.oneofs) + object._pageSize = "pageSize"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + object.pageToken = message.pageToken; + if (options.oneofs) + object._pageToken = "pageToken"; + } + return object; + }; + + /** + * Converts this ListCloudInstancesAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @instance + * @returns {Object.} JSON object + */ + ListCloudInstancesAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCloudInstancesAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ListCloudInstancesAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCloudInstancesAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ListCloudInstancesAction"; + }; + + return ListCloudInstancesAction; + })(); + + v1.GetCloudInstanceAction = (function() { + + /** + * Properties of a GetCloudInstanceAction. + * @memberof google.spanner.executor.v1 + * @interface IGetCloudInstanceAction + * @property {string|null} [projectId] GetCloudInstanceAction projectId + * @property {string|null} [instanceId] GetCloudInstanceAction instanceId + */ + + /** + * Constructs a new GetCloudInstanceAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a GetCloudInstanceAction. + * @implements IGetCloudInstanceAction + * @constructor + * @param {google.spanner.executor.v1.IGetCloudInstanceAction=} [properties] Properties to set + */ + function GetCloudInstanceAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetCloudInstanceAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @instance + */ + GetCloudInstanceAction.prototype.projectId = ""; + + /** + * GetCloudInstanceAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @instance + */ + GetCloudInstanceAction.prototype.instanceId = ""; + + /** + * Creates a new GetCloudInstanceAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IGetCloudInstanceAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.GetCloudInstanceAction} GetCloudInstanceAction instance + */ + GetCloudInstanceAction.create = function create(properties) { + return new GetCloudInstanceAction(properties); + }; + + /** + * Encodes the specified GetCloudInstanceAction message. Does not implicitly {@link google.spanner.executor.v1.GetCloudInstanceAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IGetCloudInstanceAction} message GetCloudInstanceAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetCloudInstanceAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + return writer; + }; + + /** + * Encodes the specified GetCloudInstanceAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetCloudInstanceAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.IGetCloudInstanceAction} message GetCloudInstanceAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetCloudInstanceAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetCloudInstanceAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.GetCloudInstanceAction} GetCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetCloudInstanceAction.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.spanner.executor.v1.GetCloudInstanceAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetCloudInstanceAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.GetCloudInstanceAction} GetCloudInstanceAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetCloudInstanceAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetCloudInstanceAction message. + * @function verify + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetCloudInstanceAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + return null; + }; + + /** + * Creates a GetCloudInstanceAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.GetCloudInstanceAction} GetCloudInstanceAction + */ + GetCloudInstanceAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.GetCloudInstanceAction) + return object; + var message = new $root.google.spanner.executor.v1.GetCloudInstanceAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + return message; + }; + + /** + * Creates a plain object from a GetCloudInstanceAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {google.spanner.executor.v1.GetCloudInstanceAction} message GetCloudInstanceAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetCloudInstanceAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + return object; + }; + + /** + * Converts this GetCloudInstanceAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @instance + * @returns {Object.} JSON object + */ + GetCloudInstanceAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetCloudInstanceAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.GetCloudInstanceAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetCloudInstanceAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.GetCloudInstanceAction"; + }; + + return GetCloudInstanceAction; + })(); + + v1.ListCloudDatabaseOperationsAction = (function() { + + /** + * Properties of a ListCloudDatabaseOperationsAction. + * @memberof google.spanner.executor.v1 + * @interface IListCloudDatabaseOperationsAction + * @property {string|null} [projectId] ListCloudDatabaseOperationsAction projectId + * @property {string|null} [instanceId] ListCloudDatabaseOperationsAction instanceId + * @property {string|null} [filter] ListCloudDatabaseOperationsAction filter + * @property {number|null} [pageSize] ListCloudDatabaseOperationsAction pageSize + * @property {string|null} [pageToken] ListCloudDatabaseOperationsAction pageToken + */ + + /** + * Constructs a new ListCloudDatabaseOperationsAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ListCloudDatabaseOperationsAction. + * @implements IListCloudDatabaseOperationsAction + * @constructor + * @param {google.spanner.executor.v1.IListCloudDatabaseOperationsAction=} [properties] Properties to set + */ + function ListCloudDatabaseOperationsAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCloudDatabaseOperationsAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @instance + */ + ListCloudDatabaseOperationsAction.prototype.projectId = ""; + + /** + * ListCloudDatabaseOperationsAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @instance + */ + ListCloudDatabaseOperationsAction.prototype.instanceId = ""; + + /** + * ListCloudDatabaseOperationsAction filter. + * @member {string} filter + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @instance + */ + ListCloudDatabaseOperationsAction.prototype.filter = ""; + + /** + * ListCloudDatabaseOperationsAction pageSize. + * @member {number} pageSize + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @instance + */ + ListCloudDatabaseOperationsAction.prototype.pageSize = 0; + + /** + * ListCloudDatabaseOperationsAction pageToken. + * @member {string} pageToken + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @instance + */ + ListCloudDatabaseOperationsAction.prototype.pageToken = ""; + + /** + * Creates a new ListCloudDatabaseOperationsAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {google.spanner.executor.v1.IListCloudDatabaseOperationsAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ListCloudDatabaseOperationsAction} ListCloudDatabaseOperationsAction instance + */ + ListCloudDatabaseOperationsAction.create = function create(properties) { + return new ListCloudDatabaseOperationsAction(properties); + }; + + /** + * Encodes the specified ListCloudDatabaseOperationsAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudDatabaseOperationsAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {google.spanner.executor.v1.IListCloudDatabaseOperationsAction} message ListCloudDatabaseOperationsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudDatabaseOperationsAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListCloudDatabaseOperationsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudDatabaseOperationsAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {google.spanner.executor.v1.IListCloudDatabaseOperationsAction} message ListCloudDatabaseOperationsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudDatabaseOperationsAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListCloudDatabaseOperationsAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ListCloudDatabaseOperationsAction} ListCloudDatabaseOperationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudDatabaseOperationsAction.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.spanner.executor.v1.ListCloudDatabaseOperationsAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.filter = reader.string(); + break; + } + case 4: { + message.pageSize = reader.int32(); + break; + } + case 5: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListCloudDatabaseOperationsAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ListCloudDatabaseOperationsAction} ListCloudDatabaseOperationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudDatabaseOperationsAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListCloudDatabaseOperationsAction message. + * @function verify + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListCloudDatabaseOperationsAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListCloudDatabaseOperationsAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ListCloudDatabaseOperationsAction} ListCloudDatabaseOperationsAction + */ + ListCloudDatabaseOperationsAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ListCloudDatabaseOperationsAction) + return object; + var message = new $root.google.spanner.executor.v1.ListCloudDatabaseOperationsAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListCloudDatabaseOperationsAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {google.spanner.executor.v1.ListCloudDatabaseOperationsAction} message ListCloudDatabaseOperationsAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCloudDatabaseOperationsAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListCloudDatabaseOperationsAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @instance + * @returns {Object.} JSON object + */ + ListCloudDatabaseOperationsAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCloudDatabaseOperationsAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ListCloudDatabaseOperationsAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCloudDatabaseOperationsAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ListCloudDatabaseOperationsAction"; + }; + + return ListCloudDatabaseOperationsAction; + })(); + + v1.RestoreCloudDatabaseAction = (function() { + + /** + * Properties of a RestoreCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @interface IRestoreCloudDatabaseAction + * @property {string|null} [projectId] RestoreCloudDatabaseAction projectId + * @property {string|null} [backupInstanceId] RestoreCloudDatabaseAction backupInstanceId + * @property {string|null} [backupId] RestoreCloudDatabaseAction backupId + * @property {string|null} [databaseInstanceId] RestoreCloudDatabaseAction databaseInstanceId + * @property {string|null} [databaseId] RestoreCloudDatabaseAction databaseId + * @property {google.spanner.admin.database.v1.IEncryptionConfig|null} [encryptionConfig] RestoreCloudDatabaseAction encryptionConfig + */ + + /** + * Constructs a new RestoreCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a RestoreCloudDatabaseAction. + * @implements IRestoreCloudDatabaseAction + * @constructor + * @param {google.spanner.executor.v1.IRestoreCloudDatabaseAction=} [properties] Properties to set + */ + function RestoreCloudDatabaseAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RestoreCloudDatabaseAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @instance + */ + RestoreCloudDatabaseAction.prototype.projectId = ""; + + /** + * RestoreCloudDatabaseAction backupInstanceId. + * @member {string} backupInstanceId + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @instance + */ + RestoreCloudDatabaseAction.prototype.backupInstanceId = ""; + + /** + * RestoreCloudDatabaseAction backupId. + * @member {string} backupId + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @instance + */ + RestoreCloudDatabaseAction.prototype.backupId = ""; + + /** + * RestoreCloudDatabaseAction databaseInstanceId. + * @member {string} databaseInstanceId + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @instance + */ + RestoreCloudDatabaseAction.prototype.databaseInstanceId = ""; + + /** + * RestoreCloudDatabaseAction databaseId. + * @member {string} databaseId + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @instance + */ + RestoreCloudDatabaseAction.prototype.databaseId = ""; + + /** + * RestoreCloudDatabaseAction encryptionConfig. + * @member {google.spanner.admin.database.v1.IEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @instance + */ + RestoreCloudDatabaseAction.prototype.encryptionConfig = null; + + /** + * Creates a new RestoreCloudDatabaseAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IRestoreCloudDatabaseAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.RestoreCloudDatabaseAction} RestoreCloudDatabaseAction instance + */ + RestoreCloudDatabaseAction.create = function create(properties) { + return new RestoreCloudDatabaseAction(properties); + }; + + /** + * Encodes the specified RestoreCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.RestoreCloudDatabaseAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IRestoreCloudDatabaseAction} message RestoreCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreCloudDatabaseAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.backupInstanceId != null && Object.hasOwnProperty.call(message, "backupInstanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.backupInstanceId); + if (message.backupId != null && Object.hasOwnProperty.call(message, "backupId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.backupId); + if (message.databaseInstanceId != null && Object.hasOwnProperty.call(message, "databaseInstanceId")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.databaseInstanceId); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.databaseId); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.EncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RestoreCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.RestoreCloudDatabaseAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IRestoreCloudDatabaseAction} message RestoreCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RestoreCloudDatabaseAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RestoreCloudDatabaseAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.RestoreCloudDatabaseAction} RestoreCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreCloudDatabaseAction.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.spanner.executor.v1.RestoreCloudDatabaseAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.backupInstanceId = reader.string(); + break; + } + case 3: { + message.backupId = reader.string(); + break; + } + case 4: { + message.databaseInstanceId = reader.string(); + break; + } + case 5: { + message.databaseId = reader.string(); + break; + } + case 7: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RestoreCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.RestoreCloudDatabaseAction} RestoreCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RestoreCloudDatabaseAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RestoreCloudDatabaseAction message. + * @function verify + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RestoreCloudDatabaseAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.backupInstanceId != null && message.hasOwnProperty("backupInstanceId")) + if (!$util.isString(message.backupInstanceId)) + return "backupInstanceId: string expected"; + if (message.backupId != null && message.hasOwnProperty("backupId")) + if (!$util.isString(message.backupId)) + return "backupId: string expected"; + if (message.databaseInstanceId != null && message.hasOwnProperty("databaseInstanceId")) + if (!$util.isString(message.databaseInstanceId)) + return "databaseInstanceId: string expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isString(message.databaseId)) + return "databaseId: string expected"; + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.EncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + return null; + }; + + /** + * Creates a RestoreCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.RestoreCloudDatabaseAction} RestoreCloudDatabaseAction + */ + RestoreCloudDatabaseAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.RestoreCloudDatabaseAction) + return object; + var message = new $root.google.spanner.executor.v1.RestoreCloudDatabaseAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.backupInstanceId != null) + message.backupInstanceId = String(object.backupInstanceId); + if (object.backupId != null) + message.backupId = String(object.backupId); + if (object.databaseInstanceId != null) + message.databaseInstanceId = String(object.databaseInstanceId); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.executor.v1.RestoreCloudDatabaseAction.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.fromObject(object.encryptionConfig); + } + return message; + }; + + /** + * Creates a plain object from a RestoreCloudDatabaseAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.RestoreCloudDatabaseAction} message RestoreCloudDatabaseAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RestoreCloudDatabaseAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.backupInstanceId = ""; + object.backupId = ""; + object.databaseInstanceId = ""; + object.databaseId = ""; + object.encryptionConfig = null; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.backupInstanceId != null && message.hasOwnProperty("backupInstanceId")) + object.backupInstanceId = message.backupInstanceId; + if (message.backupId != null && message.hasOwnProperty("backupId")) + object.backupId = message.backupId; + if (message.databaseInstanceId != null && message.hasOwnProperty("databaseInstanceId")) + object.databaseInstanceId = message.databaseInstanceId; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.toObject(message.encryptionConfig, options); + return object; + }; + + /** + * Converts this RestoreCloudDatabaseAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @instance + * @returns {Object.} JSON object + */ + RestoreCloudDatabaseAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RestoreCloudDatabaseAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.RestoreCloudDatabaseAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RestoreCloudDatabaseAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.RestoreCloudDatabaseAction"; + }; + + return RestoreCloudDatabaseAction; + })(); + + v1.GetCloudDatabaseAction = (function() { + + /** + * Properties of a GetCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @interface IGetCloudDatabaseAction + * @property {string|null} [projectId] GetCloudDatabaseAction projectId + * @property {string|null} [instanceId] GetCloudDatabaseAction instanceId + * @property {string|null} [databaseId] GetCloudDatabaseAction databaseId + */ + + /** + * Constructs a new GetCloudDatabaseAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a GetCloudDatabaseAction. + * @implements IGetCloudDatabaseAction + * @constructor + * @param {google.spanner.executor.v1.IGetCloudDatabaseAction=} [properties] Properties to set + */ + function GetCloudDatabaseAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetCloudDatabaseAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @instance + */ + GetCloudDatabaseAction.prototype.projectId = ""; + + /** + * GetCloudDatabaseAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @instance + */ + GetCloudDatabaseAction.prototype.instanceId = ""; + + /** + * GetCloudDatabaseAction databaseId. + * @member {string} databaseId + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @instance + */ + GetCloudDatabaseAction.prototype.databaseId = ""; + + /** + * Creates a new GetCloudDatabaseAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IGetCloudDatabaseAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.GetCloudDatabaseAction} GetCloudDatabaseAction instance + */ + GetCloudDatabaseAction.create = function create(properties) { + return new GetCloudDatabaseAction(properties); + }; + + /** + * Encodes the specified GetCloudDatabaseAction message. Does not implicitly {@link google.spanner.executor.v1.GetCloudDatabaseAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IGetCloudDatabaseAction} message GetCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetCloudDatabaseAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.databaseId); + return writer; + }; + + /** + * Encodes the specified GetCloudDatabaseAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetCloudDatabaseAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.IGetCloudDatabaseAction} message GetCloudDatabaseAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetCloudDatabaseAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetCloudDatabaseAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.GetCloudDatabaseAction} GetCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetCloudDatabaseAction.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.spanner.executor.v1.GetCloudDatabaseAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.databaseId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetCloudDatabaseAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.GetCloudDatabaseAction} GetCloudDatabaseAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetCloudDatabaseAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetCloudDatabaseAction message. + * @function verify + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetCloudDatabaseAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isString(message.databaseId)) + return "databaseId: string expected"; + return null; + }; + + /** + * Creates a GetCloudDatabaseAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.GetCloudDatabaseAction} GetCloudDatabaseAction + */ + GetCloudDatabaseAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.GetCloudDatabaseAction) + return object; + var message = new $root.google.spanner.executor.v1.GetCloudDatabaseAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + return message; + }; + + /** + * Creates a plain object from a GetCloudDatabaseAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {google.spanner.executor.v1.GetCloudDatabaseAction} message GetCloudDatabaseAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetCloudDatabaseAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.databaseId = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + return object; + }; + + /** + * Converts this GetCloudDatabaseAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @instance + * @returns {Object.} JSON object + */ + GetCloudDatabaseAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetCloudDatabaseAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.GetCloudDatabaseAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetCloudDatabaseAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.GetCloudDatabaseAction"; + }; + + return GetCloudDatabaseAction; + })(); + + v1.CreateCloudBackupAction = (function() { + + /** + * Properties of a CreateCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @interface ICreateCloudBackupAction + * @property {string|null} [projectId] CreateCloudBackupAction projectId + * @property {string|null} [instanceId] CreateCloudBackupAction instanceId + * @property {string|null} [backupId] CreateCloudBackupAction backupId + * @property {string|null} [databaseId] CreateCloudBackupAction databaseId + * @property {google.protobuf.ITimestamp|null} [expireTime] CreateCloudBackupAction expireTime + * @property {google.protobuf.ITimestamp|null} [versionTime] CreateCloudBackupAction versionTime + * @property {google.spanner.admin.database.v1.IEncryptionConfig|null} [encryptionConfig] CreateCloudBackupAction encryptionConfig + */ + + /** + * Constructs a new CreateCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CreateCloudBackupAction. + * @implements ICreateCloudBackupAction + * @constructor + * @param {google.spanner.executor.v1.ICreateCloudBackupAction=} [properties] Properties to set + */ + function CreateCloudBackupAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateCloudBackupAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @instance + */ + CreateCloudBackupAction.prototype.projectId = ""; + + /** + * CreateCloudBackupAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @instance + */ + CreateCloudBackupAction.prototype.instanceId = ""; + + /** + * CreateCloudBackupAction backupId. + * @member {string} backupId + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @instance + */ + CreateCloudBackupAction.prototype.backupId = ""; + + /** + * CreateCloudBackupAction databaseId. + * @member {string} databaseId + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @instance + */ + CreateCloudBackupAction.prototype.databaseId = ""; + + /** + * CreateCloudBackupAction expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @instance + */ + CreateCloudBackupAction.prototype.expireTime = null; + + /** + * CreateCloudBackupAction versionTime. + * @member {google.protobuf.ITimestamp|null|undefined} versionTime + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @instance + */ + CreateCloudBackupAction.prototype.versionTime = null; + + /** + * CreateCloudBackupAction encryptionConfig. + * @member {google.spanner.admin.database.v1.IEncryptionConfig|null|undefined} encryptionConfig + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @instance + */ + CreateCloudBackupAction.prototype.encryptionConfig = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CreateCloudBackupAction.prototype, "_versionTime", { + get: $util.oneOfGetter($oneOfFields = ["versionTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new CreateCloudBackupAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudBackupAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CreateCloudBackupAction} CreateCloudBackupAction instance + */ + CreateCloudBackupAction.create = function create(properties) { + return new CreateCloudBackupAction(properties); + }; + + /** + * Encodes the specified CreateCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.CreateCloudBackupAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudBackupAction} message CreateCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateCloudBackupAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.backupId != null && Object.hasOwnProperty.call(message, "backupId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.backupId); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.databaseId); + if (message.expireTime != null && Object.hasOwnProperty.call(message, "expireTime")) + $root.google.protobuf.Timestamp.encode(message.expireTime, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.versionTime != null && Object.hasOwnProperty.call(message, "versionTime")) + $root.google.protobuf.Timestamp.encode(message.versionTime, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.encryptionConfig != null && Object.hasOwnProperty.call(message, "encryptionConfig")) + $root.google.spanner.admin.database.v1.EncryptionConfig.encode(message.encryptionConfig, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CreateCloudBackupAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {google.spanner.executor.v1.ICreateCloudBackupAction} message CreateCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateCloudBackupAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateCloudBackupAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CreateCloudBackupAction} CreateCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateCloudBackupAction.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.spanner.executor.v1.CreateCloudBackupAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.backupId = reader.string(); + break; + } + case 4: { + message.databaseId = reader.string(); + break; + } + case 5: { + message.expireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 6: { + message.versionTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 7: { + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateCloudBackupAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CreateCloudBackupAction} CreateCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateCloudBackupAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateCloudBackupAction message. + * @function verify + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateCloudBackupAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.backupId != null && message.hasOwnProperty("backupId")) + if (!$util.isString(message.backupId)) + return "backupId: string expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isString(message.databaseId)) + return "databaseId: string expected"; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.expireTime); + if (error) + return "expireTime." + error; + } + if (message.versionTime != null && message.hasOwnProperty("versionTime")) { + properties._versionTime = 1; + { + var error = $root.google.protobuf.Timestamp.verify(message.versionTime); + if (error) + return "versionTime." + error; + } + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) { + var error = $root.google.spanner.admin.database.v1.EncryptionConfig.verify(message.encryptionConfig); + if (error) + return "encryptionConfig." + error; + } + return null; + }; + + /** + * Creates a CreateCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CreateCloudBackupAction} CreateCloudBackupAction + */ + CreateCloudBackupAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CreateCloudBackupAction) + return object; + var message = new $root.google.spanner.executor.v1.CreateCloudBackupAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.backupId != null) + message.backupId = String(object.backupId); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.spanner.executor.v1.CreateCloudBackupAction.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime); + } + if (object.versionTime != null) { + if (typeof object.versionTime !== "object") + throw TypeError(".google.spanner.executor.v1.CreateCloudBackupAction.versionTime: object expected"); + message.versionTime = $root.google.protobuf.Timestamp.fromObject(object.versionTime); + } + if (object.encryptionConfig != null) { + if (typeof object.encryptionConfig !== "object") + throw TypeError(".google.spanner.executor.v1.CreateCloudBackupAction.encryptionConfig: object expected"); + message.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.fromObject(object.encryptionConfig); + } + return message; + }; + + /** + * Creates a plain object from a CreateCloudBackupAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {google.spanner.executor.v1.CreateCloudBackupAction} message CreateCloudBackupAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateCloudBackupAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.backupId = ""; + object.databaseId = ""; + object.expireTime = null; + object.encryptionConfig = null; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.backupId != null && message.hasOwnProperty("backupId")) + object.backupId = message.backupId; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + if (message.versionTime != null && message.hasOwnProperty("versionTime")) { + object.versionTime = $root.google.protobuf.Timestamp.toObject(message.versionTime, options); + if (options.oneofs) + object._versionTime = "versionTime"; + } + if (message.encryptionConfig != null && message.hasOwnProperty("encryptionConfig")) + object.encryptionConfig = $root.google.spanner.admin.database.v1.EncryptionConfig.toObject(message.encryptionConfig, options); + return object; + }; + + /** + * Converts this CreateCloudBackupAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @instance + * @returns {Object.} JSON object + */ + CreateCloudBackupAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateCloudBackupAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CreateCloudBackupAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateCloudBackupAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CreateCloudBackupAction"; + }; + + return CreateCloudBackupAction; + })(); + + v1.CopyCloudBackupAction = (function() { + + /** + * Properties of a CopyCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @interface ICopyCloudBackupAction + * @property {string|null} [projectId] CopyCloudBackupAction projectId + * @property {string|null} [instanceId] CopyCloudBackupAction instanceId + * @property {string|null} [backupId] CopyCloudBackupAction backupId + * @property {string|null} [sourceBackup] CopyCloudBackupAction sourceBackup + * @property {google.protobuf.ITimestamp|null} [expireTime] CopyCloudBackupAction expireTime + */ + + /** + * Constructs a new CopyCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CopyCloudBackupAction. + * @implements ICopyCloudBackupAction + * @constructor + * @param {google.spanner.executor.v1.ICopyCloudBackupAction=} [properties] Properties to set + */ + function CopyCloudBackupAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CopyCloudBackupAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @instance + */ + CopyCloudBackupAction.prototype.projectId = ""; + + /** + * CopyCloudBackupAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @instance + */ + CopyCloudBackupAction.prototype.instanceId = ""; + + /** + * CopyCloudBackupAction backupId. + * @member {string} backupId + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @instance + */ + CopyCloudBackupAction.prototype.backupId = ""; + + /** + * CopyCloudBackupAction sourceBackup. + * @member {string} sourceBackup + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @instance + */ + CopyCloudBackupAction.prototype.sourceBackup = ""; + + /** + * CopyCloudBackupAction expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @instance + */ + CopyCloudBackupAction.prototype.expireTime = null; + + /** + * Creates a new CopyCloudBackupAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {google.spanner.executor.v1.ICopyCloudBackupAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CopyCloudBackupAction} CopyCloudBackupAction instance + */ + CopyCloudBackupAction.create = function create(properties) { + return new CopyCloudBackupAction(properties); + }; + + /** + * Encodes the specified CopyCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.CopyCloudBackupAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {google.spanner.executor.v1.ICopyCloudBackupAction} message CopyCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CopyCloudBackupAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.backupId != null && Object.hasOwnProperty.call(message, "backupId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.backupId); + if (message.sourceBackup != null && Object.hasOwnProperty.call(message, "sourceBackup")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.sourceBackup); + if (message.expireTime != null && Object.hasOwnProperty.call(message, "expireTime")) + $root.google.protobuf.Timestamp.encode(message.expireTime, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CopyCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CopyCloudBackupAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {google.spanner.executor.v1.ICopyCloudBackupAction} message CopyCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CopyCloudBackupAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CopyCloudBackupAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CopyCloudBackupAction} CopyCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CopyCloudBackupAction.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.spanner.executor.v1.CopyCloudBackupAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.backupId = reader.string(); + break; + } + case 4: { + message.sourceBackup = reader.string(); + break; + } + case 5: { + message.expireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CopyCloudBackupAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CopyCloudBackupAction} CopyCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CopyCloudBackupAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CopyCloudBackupAction message. + * @function verify + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CopyCloudBackupAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.backupId != null && message.hasOwnProperty("backupId")) + if (!$util.isString(message.backupId)) + return "backupId: string expected"; + if (message.sourceBackup != null && message.hasOwnProperty("sourceBackup")) + if (!$util.isString(message.sourceBackup)) + return "sourceBackup: string expected"; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.expireTime); + if (error) + return "expireTime." + error; + } + return null; + }; + + /** + * Creates a CopyCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CopyCloudBackupAction} CopyCloudBackupAction + */ + CopyCloudBackupAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CopyCloudBackupAction) + return object; + var message = new $root.google.spanner.executor.v1.CopyCloudBackupAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.backupId != null) + message.backupId = String(object.backupId); + if (object.sourceBackup != null) + message.sourceBackup = String(object.sourceBackup); + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.spanner.executor.v1.CopyCloudBackupAction.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime); + } + return message; + }; + + /** + * Creates a plain object from a CopyCloudBackupAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {google.spanner.executor.v1.CopyCloudBackupAction} message CopyCloudBackupAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CopyCloudBackupAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.backupId = ""; + object.sourceBackup = ""; + object.expireTime = null; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.backupId != null && message.hasOwnProperty("backupId")) + object.backupId = message.backupId; + if (message.sourceBackup != null && message.hasOwnProperty("sourceBackup")) + object.sourceBackup = message.sourceBackup; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + return object; + }; + + /** + * Converts this CopyCloudBackupAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @instance + * @returns {Object.} JSON object + */ + CopyCloudBackupAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CopyCloudBackupAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CopyCloudBackupAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CopyCloudBackupAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CopyCloudBackupAction"; + }; + + return CopyCloudBackupAction; + })(); + + v1.GetCloudBackupAction = (function() { + + /** + * Properties of a GetCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @interface IGetCloudBackupAction + * @property {string|null} [projectId] GetCloudBackupAction projectId + * @property {string|null} [instanceId] GetCloudBackupAction instanceId + * @property {string|null} [backupId] GetCloudBackupAction backupId + */ + + /** + * Constructs a new GetCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a GetCloudBackupAction. + * @implements IGetCloudBackupAction + * @constructor + * @param {google.spanner.executor.v1.IGetCloudBackupAction=} [properties] Properties to set + */ + function GetCloudBackupAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetCloudBackupAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @instance + */ + GetCloudBackupAction.prototype.projectId = ""; + + /** + * GetCloudBackupAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @instance + */ + GetCloudBackupAction.prototype.instanceId = ""; + + /** + * GetCloudBackupAction backupId. + * @member {string} backupId + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @instance + */ + GetCloudBackupAction.prototype.backupId = ""; + + /** + * Creates a new GetCloudBackupAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IGetCloudBackupAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.GetCloudBackupAction} GetCloudBackupAction instance + */ + GetCloudBackupAction.create = function create(properties) { + return new GetCloudBackupAction(properties); + }; + + /** + * Encodes the specified GetCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.GetCloudBackupAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IGetCloudBackupAction} message GetCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetCloudBackupAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.backupId != null && Object.hasOwnProperty.call(message, "backupId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.backupId); + return writer; + }; + + /** + * Encodes the specified GetCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetCloudBackupAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IGetCloudBackupAction} message GetCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetCloudBackupAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetCloudBackupAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.GetCloudBackupAction} GetCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetCloudBackupAction.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.spanner.executor.v1.GetCloudBackupAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.backupId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetCloudBackupAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.GetCloudBackupAction} GetCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetCloudBackupAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetCloudBackupAction message. + * @function verify + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetCloudBackupAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.backupId != null && message.hasOwnProperty("backupId")) + if (!$util.isString(message.backupId)) + return "backupId: string expected"; + return null; + }; + + /** + * Creates a GetCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.GetCloudBackupAction} GetCloudBackupAction + */ + GetCloudBackupAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.GetCloudBackupAction) + return object; + var message = new $root.google.spanner.executor.v1.GetCloudBackupAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.backupId != null) + message.backupId = String(object.backupId); + return message; + }; + + /** + * Creates a plain object from a GetCloudBackupAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {google.spanner.executor.v1.GetCloudBackupAction} message GetCloudBackupAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetCloudBackupAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.backupId = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.backupId != null && message.hasOwnProperty("backupId")) + object.backupId = message.backupId; + return object; + }; + + /** + * Converts this GetCloudBackupAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @instance + * @returns {Object.} JSON object + */ + GetCloudBackupAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetCloudBackupAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.GetCloudBackupAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetCloudBackupAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.GetCloudBackupAction"; + }; + + return GetCloudBackupAction; + })(); + + v1.UpdateCloudBackupAction = (function() { + + /** + * Properties of an UpdateCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @interface IUpdateCloudBackupAction + * @property {string|null} [projectId] UpdateCloudBackupAction projectId + * @property {string|null} [instanceId] UpdateCloudBackupAction instanceId + * @property {string|null} [backupId] UpdateCloudBackupAction backupId + * @property {google.protobuf.ITimestamp|null} [expireTime] UpdateCloudBackupAction expireTime + */ + + /** + * Constructs a new UpdateCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an UpdateCloudBackupAction. + * @implements IUpdateCloudBackupAction + * @constructor + * @param {google.spanner.executor.v1.IUpdateCloudBackupAction=} [properties] Properties to set + */ + function UpdateCloudBackupAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateCloudBackupAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @instance + */ + UpdateCloudBackupAction.prototype.projectId = ""; + + /** + * UpdateCloudBackupAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @instance + */ + UpdateCloudBackupAction.prototype.instanceId = ""; + + /** + * UpdateCloudBackupAction backupId. + * @member {string} backupId + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @instance + */ + UpdateCloudBackupAction.prototype.backupId = ""; + + /** + * UpdateCloudBackupAction expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @instance + */ + UpdateCloudBackupAction.prototype.expireTime = null; + + /** + * Creates a new UpdateCloudBackupAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudBackupAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.UpdateCloudBackupAction} UpdateCloudBackupAction instance + */ + UpdateCloudBackupAction.create = function create(properties) { + return new UpdateCloudBackupAction(properties); + }; + + /** + * Encodes the specified UpdateCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudBackupAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudBackupAction} message UpdateCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateCloudBackupAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.backupId != null && Object.hasOwnProperty.call(message, "backupId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.backupId); + if (message.expireTime != null && Object.hasOwnProperty.call(message, "expireTime")) + $root.google.protobuf.Timestamp.encode(message.expireTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.UpdateCloudBackupAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IUpdateCloudBackupAction} message UpdateCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateCloudBackupAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateCloudBackupAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.UpdateCloudBackupAction} UpdateCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateCloudBackupAction.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.spanner.executor.v1.UpdateCloudBackupAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.backupId = reader.string(); + break; + } + case 4: { + message.expireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateCloudBackupAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.UpdateCloudBackupAction} UpdateCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateCloudBackupAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateCloudBackupAction message. + * @function verify + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateCloudBackupAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.backupId != null && message.hasOwnProperty("backupId")) + if (!$util.isString(message.backupId)) + return "backupId: string expected"; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.expireTime); + if (error) + return "expireTime." + error; + } + return null; + }; + + /** + * Creates an UpdateCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.UpdateCloudBackupAction} UpdateCloudBackupAction + */ + UpdateCloudBackupAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.UpdateCloudBackupAction) + return object; + var message = new $root.google.spanner.executor.v1.UpdateCloudBackupAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.backupId != null) + message.backupId = String(object.backupId); + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.spanner.executor.v1.UpdateCloudBackupAction.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime); + } + return message; + }; + + /** + * Creates a plain object from an UpdateCloudBackupAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {google.spanner.executor.v1.UpdateCloudBackupAction} message UpdateCloudBackupAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateCloudBackupAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.backupId = ""; + object.expireTime = null; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.backupId != null && message.hasOwnProperty("backupId")) + object.backupId = message.backupId; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + return object; + }; + + /** + * Converts this UpdateCloudBackupAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @instance + * @returns {Object.} JSON object + */ + UpdateCloudBackupAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateCloudBackupAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.UpdateCloudBackupAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateCloudBackupAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.UpdateCloudBackupAction"; + }; + + return UpdateCloudBackupAction; + })(); + + v1.DeleteCloudBackupAction = (function() { + + /** + * Properties of a DeleteCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @interface IDeleteCloudBackupAction + * @property {string|null} [projectId] DeleteCloudBackupAction projectId + * @property {string|null} [instanceId] DeleteCloudBackupAction instanceId + * @property {string|null} [backupId] DeleteCloudBackupAction backupId + */ + + /** + * Constructs a new DeleteCloudBackupAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a DeleteCloudBackupAction. + * @implements IDeleteCloudBackupAction + * @constructor + * @param {google.spanner.executor.v1.IDeleteCloudBackupAction=} [properties] Properties to set + */ + function DeleteCloudBackupAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteCloudBackupAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @instance + */ + DeleteCloudBackupAction.prototype.projectId = ""; + + /** + * DeleteCloudBackupAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @instance + */ + DeleteCloudBackupAction.prototype.instanceId = ""; + + /** + * DeleteCloudBackupAction backupId. + * @member {string} backupId + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @instance + */ + DeleteCloudBackupAction.prototype.backupId = ""; + + /** + * Creates a new DeleteCloudBackupAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IDeleteCloudBackupAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.DeleteCloudBackupAction} DeleteCloudBackupAction instance + */ + DeleteCloudBackupAction.create = function create(properties) { + return new DeleteCloudBackupAction(properties); + }; + + /** + * Encodes the specified DeleteCloudBackupAction message. Does not implicitly {@link google.spanner.executor.v1.DeleteCloudBackupAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IDeleteCloudBackupAction} message DeleteCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteCloudBackupAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.backupId != null && Object.hasOwnProperty.call(message, "backupId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.backupId); + return writer; + }; + + /** + * Encodes the specified DeleteCloudBackupAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DeleteCloudBackupAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {google.spanner.executor.v1.IDeleteCloudBackupAction} message DeleteCloudBackupAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteCloudBackupAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteCloudBackupAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.DeleteCloudBackupAction} DeleteCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteCloudBackupAction.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.spanner.executor.v1.DeleteCloudBackupAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.backupId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteCloudBackupAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.DeleteCloudBackupAction} DeleteCloudBackupAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteCloudBackupAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteCloudBackupAction message. + * @function verify + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteCloudBackupAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.backupId != null && message.hasOwnProperty("backupId")) + if (!$util.isString(message.backupId)) + return "backupId: string expected"; + return null; + }; + + /** + * Creates a DeleteCloudBackupAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.DeleteCloudBackupAction} DeleteCloudBackupAction + */ + DeleteCloudBackupAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.DeleteCloudBackupAction) + return object; + var message = new $root.google.spanner.executor.v1.DeleteCloudBackupAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.backupId != null) + message.backupId = String(object.backupId); + return message; + }; + + /** + * Creates a plain object from a DeleteCloudBackupAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {google.spanner.executor.v1.DeleteCloudBackupAction} message DeleteCloudBackupAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteCloudBackupAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.backupId = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.backupId != null && message.hasOwnProperty("backupId")) + object.backupId = message.backupId; + return object; + }; + + /** + * Converts this DeleteCloudBackupAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @instance + * @returns {Object.} JSON object + */ + DeleteCloudBackupAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteCloudBackupAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.DeleteCloudBackupAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteCloudBackupAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.DeleteCloudBackupAction"; + }; + + return DeleteCloudBackupAction; + })(); + + v1.ListCloudBackupsAction = (function() { + + /** + * Properties of a ListCloudBackupsAction. + * @memberof google.spanner.executor.v1 + * @interface IListCloudBackupsAction + * @property {string|null} [projectId] ListCloudBackupsAction projectId + * @property {string|null} [instanceId] ListCloudBackupsAction instanceId + * @property {string|null} [filter] ListCloudBackupsAction filter + * @property {number|null} [pageSize] ListCloudBackupsAction pageSize + * @property {string|null} [pageToken] ListCloudBackupsAction pageToken + */ + + /** + * Constructs a new ListCloudBackupsAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ListCloudBackupsAction. + * @implements IListCloudBackupsAction + * @constructor + * @param {google.spanner.executor.v1.IListCloudBackupsAction=} [properties] Properties to set + */ + function ListCloudBackupsAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCloudBackupsAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @instance + */ + ListCloudBackupsAction.prototype.projectId = ""; + + /** + * ListCloudBackupsAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @instance + */ + ListCloudBackupsAction.prototype.instanceId = ""; + + /** + * ListCloudBackupsAction filter. + * @member {string} filter + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @instance + */ + ListCloudBackupsAction.prototype.filter = ""; + + /** + * ListCloudBackupsAction pageSize. + * @member {number} pageSize + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @instance + */ + ListCloudBackupsAction.prototype.pageSize = 0; + + /** + * ListCloudBackupsAction pageToken. + * @member {string} pageToken + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @instance + */ + ListCloudBackupsAction.prototype.pageToken = ""; + + /** + * Creates a new ListCloudBackupsAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {google.spanner.executor.v1.IListCloudBackupsAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ListCloudBackupsAction} ListCloudBackupsAction instance + */ + ListCloudBackupsAction.create = function create(properties) { + return new ListCloudBackupsAction(properties); + }; + + /** + * Encodes the specified ListCloudBackupsAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudBackupsAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {google.spanner.executor.v1.IListCloudBackupsAction} message ListCloudBackupsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudBackupsAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListCloudBackupsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudBackupsAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {google.spanner.executor.v1.IListCloudBackupsAction} message ListCloudBackupsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudBackupsAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListCloudBackupsAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ListCloudBackupsAction} ListCloudBackupsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudBackupsAction.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.spanner.executor.v1.ListCloudBackupsAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.filter = reader.string(); + break; + } + case 4: { + message.pageSize = reader.int32(); + break; + } + case 5: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListCloudBackupsAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ListCloudBackupsAction} ListCloudBackupsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudBackupsAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListCloudBackupsAction message. + * @function verify + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListCloudBackupsAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListCloudBackupsAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ListCloudBackupsAction} ListCloudBackupsAction + */ + ListCloudBackupsAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ListCloudBackupsAction) + return object; + var message = new $root.google.spanner.executor.v1.ListCloudBackupsAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListCloudBackupsAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {google.spanner.executor.v1.ListCloudBackupsAction} message ListCloudBackupsAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCloudBackupsAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListCloudBackupsAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @instance + * @returns {Object.} JSON object + */ + ListCloudBackupsAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCloudBackupsAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ListCloudBackupsAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCloudBackupsAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ListCloudBackupsAction"; + }; + + return ListCloudBackupsAction; + })(); + + v1.ListCloudBackupOperationsAction = (function() { + + /** + * Properties of a ListCloudBackupOperationsAction. + * @memberof google.spanner.executor.v1 + * @interface IListCloudBackupOperationsAction + * @property {string|null} [projectId] ListCloudBackupOperationsAction projectId + * @property {string|null} [instanceId] ListCloudBackupOperationsAction instanceId + * @property {string|null} [filter] ListCloudBackupOperationsAction filter + * @property {number|null} [pageSize] ListCloudBackupOperationsAction pageSize + * @property {string|null} [pageToken] ListCloudBackupOperationsAction pageToken + */ + + /** + * Constructs a new ListCloudBackupOperationsAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ListCloudBackupOperationsAction. + * @implements IListCloudBackupOperationsAction + * @constructor + * @param {google.spanner.executor.v1.IListCloudBackupOperationsAction=} [properties] Properties to set + */ + function ListCloudBackupOperationsAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListCloudBackupOperationsAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @instance + */ + ListCloudBackupOperationsAction.prototype.projectId = ""; + + /** + * ListCloudBackupOperationsAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @instance + */ + ListCloudBackupOperationsAction.prototype.instanceId = ""; + + /** + * ListCloudBackupOperationsAction filter. + * @member {string} filter + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @instance + */ + ListCloudBackupOperationsAction.prototype.filter = ""; + + /** + * ListCloudBackupOperationsAction pageSize. + * @member {number} pageSize + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @instance + */ + ListCloudBackupOperationsAction.prototype.pageSize = 0; + + /** + * ListCloudBackupOperationsAction pageToken. + * @member {string} pageToken + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @instance + */ + ListCloudBackupOperationsAction.prototype.pageToken = ""; + + /** + * Creates a new ListCloudBackupOperationsAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {google.spanner.executor.v1.IListCloudBackupOperationsAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ListCloudBackupOperationsAction} ListCloudBackupOperationsAction instance + */ + ListCloudBackupOperationsAction.create = function create(properties) { + return new ListCloudBackupOperationsAction(properties); + }; + + /** + * Encodes the specified ListCloudBackupOperationsAction message. Does not implicitly {@link google.spanner.executor.v1.ListCloudBackupOperationsAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {google.spanner.executor.v1.IListCloudBackupOperationsAction} message ListCloudBackupOperationsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudBackupOperationsAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListCloudBackupOperationsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ListCloudBackupOperationsAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {google.spanner.executor.v1.IListCloudBackupOperationsAction} message ListCloudBackupOperationsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListCloudBackupOperationsAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListCloudBackupOperationsAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ListCloudBackupOperationsAction} ListCloudBackupOperationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudBackupOperationsAction.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.spanner.executor.v1.ListCloudBackupOperationsAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.filter = reader.string(); + break; + } + case 4: { + message.pageSize = reader.int32(); + break; + } + case 5: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListCloudBackupOperationsAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ListCloudBackupOperationsAction} ListCloudBackupOperationsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListCloudBackupOperationsAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListCloudBackupOperationsAction message. + * @function verify + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListCloudBackupOperationsAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListCloudBackupOperationsAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ListCloudBackupOperationsAction} ListCloudBackupOperationsAction + */ + ListCloudBackupOperationsAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ListCloudBackupOperationsAction) + return object; + var message = new $root.google.spanner.executor.v1.ListCloudBackupOperationsAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListCloudBackupOperationsAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {google.spanner.executor.v1.ListCloudBackupOperationsAction} message ListCloudBackupOperationsAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListCloudBackupOperationsAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListCloudBackupOperationsAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @instance + * @returns {Object.} JSON object + */ + ListCloudBackupOperationsAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListCloudBackupOperationsAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ListCloudBackupOperationsAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListCloudBackupOperationsAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ListCloudBackupOperationsAction"; + }; + + return ListCloudBackupOperationsAction; + })(); + + v1.GetOperationAction = (function() { + + /** + * Properties of a GetOperationAction. + * @memberof google.spanner.executor.v1 + * @interface IGetOperationAction + * @property {string|null} [operation] GetOperationAction operation + */ + + /** + * Constructs a new GetOperationAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a GetOperationAction. + * @implements IGetOperationAction + * @constructor + * @param {google.spanner.executor.v1.IGetOperationAction=} [properties] Properties to set + */ + function GetOperationAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetOperationAction operation. + * @member {string} operation + * @memberof google.spanner.executor.v1.GetOperationAction + * @instance + */ + GetOperationAction.prototype.operation = ""; + + /** + * Creates a new GetOperationAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {google.spanner.executor.v1.IGetOperationAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.GetOperationAction} GetOperationAction instance + */ + GetOperationAction.create = function create(properties) { + return new GetOperationAction(properties); + }; + + /** + * Encodes the specified GetOperationAction message. Does not implicitly {@link google.spanner.executor.v1.GetOperationAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {google.spanner.executor.v1.IGetOperationAction} message GetOperationAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetOperationAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.operation != null && Object.hasOwnProperty.call(message, "operation")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.operation); + return writer; + }; + + /** + * Encodes the specified GetOperationAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GetOperationAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {google.spanner.executor.v1.IGetOperationAction} message GetOperationAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetOperationAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetOperationAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.GetOperationAction} GetOperationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetOperationAction.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.spanner.executor.v1.GetOperationAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.operation = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetOperationAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.GetOperationAction} GetOperationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetOperationAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetOperationAction message. + * @function verify + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetOperationAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.operation != null && message.hasOwnProperty("operation")) + if (!$util.isString(message.operation)) + return "operation: string expected"; + return null; + }; + + /** + * Creates a GetOperationAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.GetOperationAction} GetOperationAction + */ + GetOperationAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.GetOperationAction) + return object; + var message = new $root.google.spanner.executor.v1.GetOperationAction(); + if (object.operation != null) + message.operation = String(object.operation); + return message; + }; + + /** + * Creates a plain object from a GetOperationAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {google.spanner.executor.v1.GetOperationAction} message GetOperationAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetOperationAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.operation = ""; + if (message.operation != null && message.hasOwnProperty("operation")) + object.operation = message.operation; + return object; + }; + + /** + * Converts this GetOperationAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.GetOperationAction + * @instance + * @returns {Object.} JSON object + */ + GetOperationAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetOperationAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.GetOperationAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetOperationAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.GetOperationAction"; + }; + + return GetOperationAction; + })(); + + v1.QueryCancellationAction = (function() { + + /** + * Properties of a QueryCancellationAction. + * @memberof google.spanner.executor.v1 + * @interface IQueryCancellationAction + * @property {string|null} [longRunningSql] QueryCancellationAction longRunningSql + * @property {string|null} [cancelQuery] QueryCancellationAction cancelQuery + */ + + /** + * Constructs a new QueryCancellationAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a QueryCancellationAction. + * @implements IQueryCancellationAction + * @constructor + * @param {google.spanner.executor.v1.IQueryCancellationAction=} [properties] Properties to set + */ + function QueryCancellationAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QueryCancellationAction longRunningSql. + * @member {string} longRunningSql + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @instance + */ + QueryCancellationAction.prototype.longRunningSql = ""; + + /** + * QueryCancellationAction cancelQuery. + * @member {string} cancelQuery + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @instance + */ + QueryCancellationAction.prototype.cancelQuery = ""; + + /** + * Creates a new QueryCancellationAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {google.spanner.executor.v1.IQueryCancellationAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.QueryCancellationAction} QueryCancellationAction instance + */ + QueryCancellationAction.create = function create(properties) { + return new QueryCancellationAction(properties); + }; + + /** + * Encodes the specified QueryCancellationAction message. Does not implicitly {@link google.spanner.executor.v1.QueryCancellationAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {google.spanner.executor.v1.IQueryCancellationAction} message QueryCancellationAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryCancellationAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.longRunningSql != null && Object.hasOwnProperty.call(message, "longRunningSql")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.longRunningSql); + if (message.cancelQuery != null && Object.hasOwnProperty.call(message, "cancelQuery")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.cancelQuery); + return writer; + }; + + /** + * Encodes the specified QueryCancellationAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.QueryCancellationAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {google.spanner.executor.v1.IQueryCancellationAction} message QueryCancellationAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryCancellationAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a QueryCancellationAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.QueryCancellationAction} QueryCancellationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryCancellationAction.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.spanner.executor.v1.QueryCancellationAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.longRunningSql = reader.string(); + break; + } + case 2: { + message.cancelQuery = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a QueryCancellationAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.QueryCancellationAction} QueryCancellationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryCancellationAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a QueryCancellationAction message. + * @function verify + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + QueryCancellationAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.longRunningSql != null && message.hasOwnProperty("longRunningSql")) + if (!$util.isString(message.longRunningSql)) + return "longRunningSql: string expected"; + if (message.cancelQuery != null && message.hasOwnProperty("cancelQuery")) + if (!$util.isString(message.cancelQuery)) + return "cancelQuery: string expected"; + return null; + }; + + /** + * Creates a QueryCancellationAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.QueryCancellationAction} QueryCancellationAction + */ + QueryCancellationAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.QueryCancellationAction) + return object; + var message = new $root.google.spanner.executor.v1.QueryCancellationAction(); + if (object.longRunningSql != null) + message.longRunningSql = String(object.longRunningSql); + if (object.cancelQuery != null) + message.cancelQuery = String(object.cancelQuery); + return message; + }; + + /** + * Creates a plain object from a QueryCancellationAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {google.spanner.executor.v1.QueryCancellationAction} message QueryCancellationAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryCancellationAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.longRunningSql = ""; + object.cancelQuery = ""; + } + if (message.longRunningSql != null && message.hasOwnProperty("longRunningSql")) + object.longRunningSql = message.longRunningSql; + if (message.cancelQuery != null && message.hasOwnProperty("cancelQuery")) + object.cancelQuery = message.cancelQuery; + return object; + }; + + /** + * Converts this QueryCancellationAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @instance + * @returns {Object.} JSON object + */ + QueryCancellationAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QueryCancellationAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.QueryCancellationAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryCancellationAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.QueryCancellationAction"; + }; + + return QueryCancellationAction; + })(); + + v1.CancelOperationAction = (function() { + + /** + * Properties of a CancelOperationAction. + * @memberof google.spanner.executor.v1 + * @interface ICancelOperationAction + * @property {string|null} [operation] CancelOperationAction operation + */ + + /** + * Constructs a new CancelOperationAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CancelOperationAction. + * @implements ICancelOperationAction + * @constructor + * @param {google.spanner.executor.v1.ICancelOperationAction=} [properties] Properties to set + */ + function CancelOperationAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CancelOperationAction operation. + * @member {string} operation + * @memberof google.spanner.executor.v1.CancelOperationAction + * @instance + */ + CancelOperationAction.prototype.operation = ""; + + /** + * Creates a new CancelOperationAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {google.spanner.executor.v1.ICancelOperationAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CancelOperationAction} CancelOperationAction instance + */ + CancelOperationAction.create = function create(properties) { + return new CancelOperationAction(properties); + }; + + /** + * Encodes the specified CancelOperationAction message. Does not implicitly {@link google.spanner.executor.v1.CancelOperationAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {google.spanner.executor.v1.ICancelOperationAction} message CancelOperationAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CancelOperationAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.operation != null && Object.hasOwnProperty.call(message, "operation")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.operation); + return writer; + }; + + /** + * Encodes the specified CancelOperationAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CancelOperationAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {google.spanner.executor.v1.ICancelOperationAction} message CancelOperationAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CancelOperationAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CancelOperationAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CancelOperationAction} CancelOperationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CancelOperationAction.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.spanner.executor.v1.CancelOperationAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.operation = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CancelOperationAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CancelOperationAction} CancelOperationAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CancelOperationAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CancelOperationAction message. + * @function verify + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CancelOperationAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.operation != null && message.hasOwnProperty("operation")) + if (!$util.isString(message.operation)) + return "operation: string expected"; + return null; + }; + + /** + * Creates a CancelOperationAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CancelOperationAction} CancelOperationAction + */ + CancelOperationAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CancelOperationAction) + return object; + var message = new $root.google.spanner.executor.v1.CancelOperationAction(); + if (object.operation != null) + message.operation = String(object.operation); + return message; + }; + + /** + * Creates a plain object from a CancelOperationAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {google.spanner.executor.v1.CancelOperationAction} message CancelOperationAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CancelOperationAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.operation = ""; + if (message.operation != null && message.hasOwnProperty("operation")) + object.operation = message.operation; + return object; + }; + + /** + * Converts this CancelOperationAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CancelOperationAction + * @instance + * @returns {Object.} JSON object + */ + CancelOperationAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CancelOperationAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CancelOperationAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CancelOperationAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CancelOperationAction"; + }; + + return CancelOperationAction; + })(); + + v1.AddSplitPointsAction = (function() { + + /** + * Properties of an AddSplitPointsAction. + * @memberof google.spanner.executor.v1 + * @interface IAddSplitPointsAction + * @property {string|null} [projectId] AddSplitPointsAction projectId + * @property {string|null} [instanceId] AddSplitPointsAction instanceId + * @property {string|null} [databaseId] AddSplitPointsAction databaseId + * @property {Array.|null} [splitPoints] AddSplitPointsAction splitPoints + */ + + /** + * Constructs a new AddSplitPointsAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an AddSplitPointsAction. + * @implements IAddSplitPointsAction + * @constructor + * @param {google.spanner.executor.v1.IAddSplitPointsAction=} [properties] Properties to set + */ + function AddSplitPointsAction(properties) { + this.splitPoints = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AddSplitPointsAction projectId. + * @member {string} projectId + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @instance + */ + AddSplitPointsAction.prototype.projectId = ""; + + /** + * AddSplitPointsAction instanceId. + * @member {string} instanceId + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @instance + */ + AddSplitPointsAction.prototype.instanceId = ""; + + /** + * AddSplitPointsAction databaseId. + * @member {string} databaseId + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @instance + */ + AddSplitPointsAction.prototype.databaseId = ""; + + /** + * AddSplitPointsAction splitPoints. + * @member {Array.} splitPoints + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @instance + */ + AddSplitPointsAction.prototype.splitPoints = $util.emptyArray; + + /** + * Creates a new AddSplitPointsAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {google.spanner.executor.v1.IAddSplitPointsAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.AddSplitPointsAction} AddSplitPointsAction instance + */ + AddSplitPointsAction.create = function create(properties) { + return new AddSplitPointsAction(properties); + }; + + /** + * Encodes the specified AddSplitPointsAction message. Does not implicitly {@link google.spanner.executor.v1.AddSplitPointsAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {google.spanner.executor.v1.IAddSplitPointsAction} message AddSplitPointsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AddSplitPointsAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.projectId != null && Object.hasOwnProperty.call(message, "projectId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.projectId); + if (message.instanceId != null && Object.hasOwnProperty.call(message, "instanceId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.instanceId); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.databaseId); + if (message.splitPoints != null && message.splitPoints.length) + for (var i = 0; i < message.splitPoints.length; ++i) + $root.google.spanner.admin.database.v1.SplitPoints.encode(message.splitPoints[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified AddSplitPointsAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.AddSplitPointsAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {google.spanner.executor.v1.IAddSplitPointsAction} message AddSplitPointsAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AddSplitPointsAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AddSplitPointsAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.AddSplitPointsAction} AddSplitPointsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AddSplitPointsAction.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.spanner.executor.v1.AddSplitPointsAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.projectId = reader.string(); + break; + } + case 2: { + message.instanceId = reader.string(); + break; + } + case 3: { + message.databaseId = reader.string(); + break; + } + case 4: { + if (!(message.splitPoints && message.splitPoints.length)) + message.splitPoints = []; + message.splitPoints.push($root.google.spanner.admin.database.v1.SplitPoints.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AddSplitPointsAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.AddSplitPointsAction} AddSplitPointsAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AddSplitPointsAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AddSplitPointsAction message. + * @function verify + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AddSplitPointsAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.projectId != null && message.hasOwnProperty("projectId")) + if (!$util.isString(message.projectId)) + return "projectId: string expected"; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + if (!$util.isString(message.instanceId)) + return "instanceId: string expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isString(message.databaseId)) + return "databaseId: string expected"; + if (message.splitPoints != null && message.hasOwnProperty("splitPoints")) { + if (!Array.isArray(message.splitPoints)) + return "splitPoints: array expected"; + for (var i = 0; i < message.splitPoints.length; ++i) { + var error = $root.google.spanner.admin.database.v1.SplitPoints.verify(message.splitPoints[i]); + if (error) + return "splitPoints." + error; + } + } + return null; + }; + + /** + * Creates an AddSplitPointsAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.AddSplitPointsAction} AddSplitPointsAction + */ + AddSplitPointsAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.AddSplitPointsAction) + return object; + var message = new $root.google.spanner.executor.v1.AddSplitPointsAction(); + if (object.projectId != null) + message.projectId = String(object.projectId); + if (object.instanceId != null) + message.instanceId = String(object.instanceId); + if (object.databaseId != null) + message.databaseId = String(object.databaseId); + if (object.splitPoints) { + if (!Array.isArray(object.splitPoints)) + throw TypeError(".google.spanner.executor.v1.AddSplitPointsAction.splitPoints: array expected"); + message.splitPoints = []; + for (var i = 0; i < object.splitPoints.length; ++i) { + if (typeof object.splitPoints[i] !== "object") + throw TypeError(".google.spanner.executor.v1.AddSplitPointsAction.splitPoints: object expected"); + message.splitPoints[i] = $root.google.spanner.admin.database.v1.SplitPoints.fromObject(object.splitPoints[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an AddSplitPointsAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {google.spanner.executor.v1.AddSplitPointsAction} message AddSplitPointsAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AddSplitPointsAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.splitPoints = []; + if (options.defaults) { + object.projectId = ""; + object.instanceId = ""; + object.databaseId = ""; + } + if (message.projectId != null && message.hasOwnProperty("projectId")) + object.projectId = message.projectId; + if (message.instanceId != null && message.hasOwnProperty("instanceId")) + object.instanceId = message.instanceId; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + object.databaseId = message.databaseId; + if (message.splitPoints && message.splitPoints.length) { + object.splitPoints = []; + for (var j = 0; j < message.splitPoints.length; ++j) + object.splitPoints[j] = $root.google.spanner.admin.database.v1.SplitPoints.toObject(message.splitPoints[j], options); + } + return object; + }; + + /** + * Converts this AddSplitPointsAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @instance + * @returns {Object.} JSON object + */ + AddSplitPointsAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AddSplitPointsAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.AddSplitPointsAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AddSplitPointsAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.AddSplitPointsAction"; + }; + + return AddSplitPointsAction; + })(); + + v1.StartBatchTransactionAction = (function() { + + /** + * Properties of a StartBatchTransactionAction. + * @memberof google.spanner.executor.v1 + * @interface IStartBatchTransactionAction + * @property {google.protobuf.ITimestamp|null} [batchTxnTime] StartBatchTransactionAction batchTxnTime + * @property {Uint8Array|null} [tid] StartBatchTransactionAction tid + * @property {string|null} [cloudDatabaseRole] StartBatchTransactionAction cloudDatabaseRole + */ + + /** + * Constructs a new StartBatchTransactionAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a StartBatchTransactionAction. + * @implements IStartBatchTransactionAction + * @constructor + * @param {google.spanner.executor.v1.IStartBatchTransactionAction=} [properties] Properties to set + */ + function StartBatchTransactionAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StartBatchTransactionAction batchTxnTime. + * @member {google.protobuf.ITimestamp|null|undefined} batchTxnTime + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @instance + */ + StartBatchTransactionAction.prototype.batchTxnTime = null; + + /** + * StartBatchTransactionAction tid. + * @member {Uint8Array|null|undefined} tid + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @instance + */ + StartBatchTransactionAction.prototype.tid = null; + + /** + * StartBatchTransactionAction cloudDatabaseRole. + * @member {string} cloudDatabaseRole + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @instance + */ + StartBatchTransactionAction.prototype.cloudDatabaseRole = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * StartBatchTransactionAction param. + * @member {"batchTxnTime"|"tid"|undefined} param + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @instance + */ + Object.defineProperty(StartBatchTransactionAction.prototype, "param", { + get: $util.oneOfGetter($oneOfFields = ["batchTxnTime", "tid"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new StartBatchTransactionAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {google.spanner.executor.v1.IStartBatchTransactionAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.StartBatchTransactionAction} StartBatchTransactionAction instance + */ + StartBatchTransactionAction.create = function create(properties) { + return new StartBatchTransactionAction(properties); + }; + + /** + * Encodes the specified StartBatchTransactionAction message. Does not implicitly {@link google.spanner.executor.v1.StartBatchTransactionAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {google.spanner.executor.v1.IStartBatchTransactionAction} message StartBatchTransactionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StartBatchTransactionAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.batchTxnTime != null && Object.hasOwnProperty.call(message, "batchTxnTime")) + $root.google.protobuf.Timestamp.encode(message.batchTxnTime, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.tid != null && Object.hasOwnProperty.call(message, "tid")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.tid); + if (message.cloudDatabaseRole != null && Object.hasOwnProperty.call(message, "cloudDatabaseRole")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.cloudDatabaseRole); + return writer; + }; + + /** + * Encodes the specified StartBatchTransactionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.StartBatchTransactionAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {google.spanner.executor.v1.IStartBatchTransactionAction} message StartBatchTransactionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StartBatchTransactionAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a StartBatchTransactionAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.StartBatchTransactionAction} StartBatchTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StartBatchTransactionAction.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.spanner.executor.v1.StartBatchTransactionAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.batchTxnTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.tid = reader.bytes(); + break; + } + case 3: { + message.cloudDatabaseRole = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a StartBatchTransactionAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.StartBatchTransactionAction} StartBatchTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StartBatchTransactionAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a StartBatchTransactionAction message. + * @function verify + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + StartBatchTransactionAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.batchTxnTime != null && message.hasOwnProperty("batchTxnTime")) { + properties.param = 1; + { + var error = $root.google.protobuf.Timestamp.verify(message.batchTxnTime); + if (error) + return "batchTxnTime." + error; + } + } + if (message.tid != null && message.hasOwnProperty("tid")) { + if (properties.param === 1) + return "param: multiple values"; + properties.param = 1; + if (!(message.tid && typeof message.tid.length === "number" || $util.isString(message.tid))) + return "tid: buffer expected"; + } + if (message.cloudDatabaseRole != null && message.hasOwnProperty("cloudDatabaseRole")) + if (!$util.isString(message.cloudDatabaseRole)) + return "cloudDatabaseRole: string expected"; + return null; + }; + + /** + * Creates a StartBatchTransactionAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.StartBatchTransactionAction} StartBatchTransactionAction + */ + StartBatchTransactionAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.StartBatchTransactionAction) + return object; + var message = new $root.google.spanner.executor.v1.StartBatchTransactionAction(); + if (object.batchTxnTime != null) { + if (typeof object.batchTxnTime !== "object") + throw TypeError(".google.spanner.executor.v1.StartBatchTransactionAction.batchTxnTime: object expected"); + message.batchTxnTime = $root.google.protobuf.Timestamp.fromObject(object.batchTxnTime); + } + if (object.tid != null) + if (typeof object.tid === "string") + $util.base64.decode(object.tid, message.tid = $util.newBuffer($util.base64.length(object.tid)), 0); + else if (object.tid.length >= 0) + message.tid = object.tid; + if (object.cloudDatabaseRole != null) + message.cloudDatabaseRole = String(object.cloudDatabaseRole); + return message; + }; + + /** + * Creates a plain object from a StartBatchTransactionAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {google.spanner.executor.v1.StartBatchTransactionAction} message StartBatchTransactionAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StartBatchTransactionAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.cloudDatabaseRole = ""; + if (message.batchTxnTime != null && message.hasOwnProperty("batchTxnTime")) { + object.batchTxnTime = $root.google.protobuf.Timestamp.toObject(message.batchTxnTime, options); + if (options.oneofs) + object.param = "batchTxnTime"; + } + if (message.tid != null && message.hasOwnProperty("tid")) { + object.tid = options.bytes === String ? $util.base64.encode(message.tid, 0, message.tid.length) : options.bytes === Array ? Array.prototype.slice.call(message.tid) : message.tid; + if (options.oneofs) + object.param = "tid"; + } + if (message.cloudDatabaseRole != null && message.hasOwnProperty("cloudDatabaseRole")) + object.cloudDatabaseRole = message.cloudDatabaseRole; + return object; + }; + + /** + * Converts this StartBatchTransactionAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @instance + * @returns {Object.} JSON object + */ + StartBatchTransactionAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StartBatchTransactionAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.StartBatchTransactionAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StartBatchTransactionAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.StartBatchTransactionAction"; + }; + + return StartBatchTransactionAction; + })(); + + v1.CloseBatchTransactionAction = (function() { + + /** + * Properties of a CloseBatchTransactionAction. + * @memberof google.spanner.executor.v1 + * @interface ICloseBatchTransactionAction + * @property {boolean|null} [cleanup] CloseBatchTransactionAction cleanup + */ + + /** + * Constructs a new CloseBatchTransactionAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CloseBatchTransactionAction. + * @implements ICloseBatchTransactionAction + * @constructor + * @param {google.spanner.executor.v1.ICloseBatchTransactionAction=} [properties] Properties to set + */ + function CloseBatchTransactionAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CloseBatchTransactionAction cleanup. + * @member {boolean} cleanup + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @instance + */ + CloseBatchTransactionAction.prototype.cleanup = false; + + /** + * Creates a new CloseBatchTransactionAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {google.spanner.executor.v1.ICloseBatchTransactionAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CloseBatchTransactionAction} CloseBatchTransactionAction instance + */ + CloseBatchTransactionAction.create = function create(properties) { + return new CloseBatchTransactionAction(properties); + }; + + /** + * Encodes the specified CloseBatchTransactionAction message. Does not implicitly {@link google.spanner.executor.v1.CloseBatchTransactionAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {google.spanner.executor.v1.ICloseBatchTransactionAction} message CloseBatchTransactionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloseBatchTransactionAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.cleanup != null && Object.hasOwnProperty.call(message, "cleanup")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.cleanup); + return writer; + }; + + /** + * Encodes the specified CloseBatchTransactionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloseBatchTransactionAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {google.spanner.executor.v1.ICloseBatchTransactionAction} message CloseBatchTransactionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloseBatchTransactionAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CloseBatchTransactionAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CloseBatchTransactionAction} CloseBatchTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloseBatchTransactionAction.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.spanner.executor.v1.CloseBatchTransactionAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.cleanup = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CloseBatchTransactionAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CloseBatchTransactionAction} CloseBatchTransactionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloseBatchTransactionAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CloseBatchTransactionAction message. + * @function verify + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CloseBatchTransactionAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.cleanup != null && message.hasOwnProperty("cleanup")) + if (typeof message.cleanup !== "boolean") + return "cleanup: boolean expected"; + return null; + }; + + /** + * Creates a CloseBatchTransactionAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CloseBatchTransactionAction} CloseBatchTransactionAction + */ + CloseBatchTransactionAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CloseBatchTransactionAction) + return object; + var message = new $root.google.spanner.executor.v1.CloseBatchTransactionAction(); + if (object.cleanup != null) + message.cleanup = Boolean(object.cleanup); + return message; + }; + + /** + * Creates a plain object from a CloseBatchTransactionAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {google.spanner.executor.v1.CloseBatchTransactionAction} message CloseBatchTransactionAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CloseBatchTransactionAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.cleanup = false; + if (message.cleanup != null && message.hasOwnProperty("cleanup")) + object.cleanup = message.cleanup; + return object; + }; + + /** + * Converts this CloseBatchTransactionAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @instance + * @returns {Object.} JSON object + */ + CloseBatchTransactionAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CloseBatchTransactionAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CloseBatchTransactionAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CloseBatchTransactionAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CloseBatchTransactionAction"; + }; + + return CloseBatchTransactionAction; + })(); + + v1.GenerateDbPartitionsForReadAction = (function() { + + /** + * Properties of a GenerateDbPartitionsForReadAction. + * @memberof google.spanner.executor.v1 + * @interface IGenerateDbPartitionsForReadAction + * @property {google.spanner.executor.v1.IReadAction|null} [read] GenerateDbPartitionsForReadAction read + * @property {Array.|null} [table] GenerateDbPartitionsForReadAction table + * @property {number|Long|null} [desiredBytesPerPartition] GenerateDbPartitionsForReadAction desiredBytesPerPartition + * @property {number|Long|null} [maxPartitionCount] GenerateDbPartitionsForReadAction maxPartitionCount + */ + + /** + * Constructs a new GenerateDbPartitionsForReadAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a GenerateDbPartitionsForReadAction. + * @implements IGenerateDbPartitionsForReadAction + * @constructor + * @param {google.spanner.executor.v1.IGenerateDbPartitionsForReadAction=} [properties] Properties to set + */ + function GenerateDbPartitionsForReadAction(properties) { + this.table = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GenerateDbPartitionsForReadAction read. + * @member {google.spanner.executor.v1.IReadAction|null|undefined} read + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @instance + */ + GenerateDbPartitionsForReadAction.prototype.read = null; + + /** + * GenerateDbPartitionsForReadAction table. + * @member {Array.} table + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @instance + */ + GenerateDbPartitionsForReadAction.prototype.table = $util.emptyArray; + + /** + * GenerateDbPartitionsForReadAction desiredBytesPerPartition. + * @member {number|Long|null|undefined} desiredBytesPerPartition + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @instance + */ + GenerateDbPartitionsForReadAction.prototype.desiredBytesPerPartition = null; + + /** + * GenerateDbPartitionsForReadAction maxPartitionCount. + * @member {number|Long|null|undefined} maxPartitionCount + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @instance + */ + GenerateDbPartitionsForReadAction.prototype.maxPartitionCount = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(GenerateDbPartitionsForReadAction.prototype, "_desiredBytesPerPartition", { + get: $util.oneOfGetter($oneOfFields = ["desiredBytesPerPartition"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(GenerateDbPartitionsForReadAction.prototype, "_maxPartitionCount", { + get: $util.oneOfGetter($oneOfFields = ["maxPartitionCount"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new GenerateDbPartitionsForReadAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {google.spanner.executor.v1.IGenerateDbPartitionsForReadAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.GenerateDbPartitionsForReadAction} GenerateDbPartitionsForReadAction instance + */ + GenerateDbPartitionsForReadAction.create = function create(properties) { + return new GenerateDbPartitionsForReadAction(properties); + }; + + /** + * Encodes the specified GenerateDbPartitionsForReadAction message. Does not implicitly {@link google.spanner.executor.v1.GenerateDbPartitionsForReadAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {google.spanner.executor.v1.IGenerateDbPartitionsForReadAction} message GenerateDbPartitionsForReadAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GenerateDbPartitionsForReadAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.read != null && Object.hasOwnProperty.call(message, "read")) + $root.google.spanner.executor.v1.ReadAction.encode(message.read, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.table != null && message.table.length) + for (var i = 0; i < message.table.length; ++i) + $root.google.spanner.executor.v1.TableMetadata.encode(message.table[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.desiredBytesPerPartition != null && Object.hasOwnProperty.call(message, "desiredBytesPerPartition")) + writer.uint32(/* id 3, wireType 0 =*/24).int64(message.desiredBytesPerPartition); + if (message.maxPartitionCount != null && Object.hasOwnProperty.call(message, "maxPartitionCount")) + writer.uint32(/* id 4, wireType 0 =*/32).int64(message.maxPartitionCount); + return writer; + }; + + /** + * Encodes the specified GenerateDbPartitionsForReadAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GenerateDbPartitionsForReadAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {google.spanner.executor.v1.IGenerateDbPartitionsForReadAction} message GenerateDbPartitionsForReadAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GenerateDbPartitionsForReadAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GenerateDbPartitionsForReadAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.GenerateDbPartitionsForReadAction} GenerateDbPartitionsForReadAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GenerateDbPartitionsForReadAction.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.spanner.executor.v1.GenerateDbPartitionsForReadAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.read = $root.google.spanner.executor.v1.ReadAction.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.table && message.table.length)) + message.table = []; + message.table.push($root.google.spanner.executor.v1.TableMetadata.decode(reader, reader.uint32())); + break; + } + case 3: { + message.desiredBytesPerPartition = reader.int64(); + break; + } + case 4: { + message.maxPartitionCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GenerateDbPartitionsForReadAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.GenerateDbPartitionsForReadAction} GenerateDbPartitionsForReadAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GenerateDbPartitionsForReadAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GenerateDbPartitionsForReadAction message. + * @function verify + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GenerateDbPartitionsForReadAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.read != null && message.hasOwnProperty("read")) { + var error = $root.google.spanner.executor.v1.ReadAction.verify(message.read); + if (error) + return "read." + error; + } + if (message.table != null && message.hasOwnProperty("table")) { + if (!Array.isArray(message.table)) + return "table: array expected"; + for (var i = 0; i < message.table.length; ++i) { + var error = $root.google.spanner.executor.v1.TableMetadata.verify(message.table[i]); + if (error) + return "table." + error; + } + } + if (message.desiredBytesPerPartition != null && message.hasOwnProperty("desiredBytesPerPartition")) { + properties._desiredBytesPerPartition = 1; + if (!$util.isInteger(message.desiredBytesPerPartition) && !(message.desiredBytesPerPartition && $util.isInteger(message.desiredBytesPerPartition.low) && $util.isInteger(message.desiredBytesPerPartition.high))) + return "desiredBytesPerPartition: integer|Long expected"; + } + if (message.maxPartitionCount != null && message.hasOwnProperty("maxPartitionCount")) { + properties._maxPartitionCount = 1; + if (!$util.isInteger(message.maxPartitionCount) && !(message.maxPartitionCount && $util.isInteger(message.maxPartitionCount.low) && $util.isInteger(message.maxPartitionCount.high))) + return "maxPartitionCount: integer|Long expected"; + } + return null; + }; + + /** + * Creates a GenerateDbPartitionsForReadAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.GenerateDbPartitionsForReadAction} GenerateDbPartitionsForReadAction + */ + GenerateDbPartitionsForReadAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.GenerateDbPartitionsForReadAction) + return object; + var message = new $root.google.spanner.executor.v1.GenerateDbPartitionsForReadAction(); + if (object.read != null) { + if (typeof object.read !== "object") + throw TypeError(".google.spanner.executor.v1.GenerateDbPartitionsForReadAction.read: object expected"); + message.read = $root.google.spanner.executor.v1.ReadAction.fromObject(object.read); + } + if (object.table) { + if (!Array.isArray(object.table)) + throw TypeError(".google.spanner.executor.v1.GenerateDbPartitionsForReadAction.table: array expected"); + message.table = []; + for (var i = 0; i < object.table.length; ++i) { + if (typeof object.table[i] !== "object") + throw TypeError(".google.spanner.executor.v1.GenerateDbPartitionsForReadAction.table: object expected"); + message.table[i] = $root.google.spanner.executor.v1.TableMetadata.fromObject(object.table[i]); + } + } + if (object.desiredBytesPerPartition != null) + if ($util.Long) + (message.desiredBytesPerPartition = $util.Long.fromValue(object.desiredBytesPerPartition)).unsigned = false; + else if (typeof object.desiredBytesPerPartition === "string") + message.desiredBytesPerPartition = parseInt(object.desiredBytesPerPartition, 10); + else if (typeof object.desiredBytesPerPartition === "number") + message.desiredBytesPerPartition = object.desiredBytesPerPartition; + else if (typeof object.desiredBytesPerPartition === "object") + message.desiredBytesPerPartition = new $util.LongBits(object.desiredBytesPerPartition.low >>> 0, object.desiredBytesPerPartition.high >>> 0).toNumber(); + if (object.maxPartitionCount != null) + if ($util.Long) + (message.maxPartitionCount = $util.Long.fromValue(object.maxPartitionCount)).unsigned = false; + else if (typeof object.maxPartitionCount === "string") + message.maxPartitionCount = parseInt(object.maxPartitionCount, 10); + else if (typeof object.maxPartitionCount === "number") + message.maxPartitionCount = object.maxPartitionCount; + else if (typeof object.maxPartitionCount === "object") + message.maxPartitionCount = new $util.LongBits(object.maxPartitionCount.low >>> 0, object.maxPartitionCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a GenerateDbPartitionsForReadAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {google.spanner.executor.v1.GenerateDbPartitionsForReadAction} message GenerateDbPartitionsForReadAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GenerateDbPartitionsForReadAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.table = []; + if (options.defaults) + object.read = null; + if (message.read != null && message.hasOwnProperty("read")) + object.read = $root.google.spanner.executor.v1.ReadAction.toObject(message.read, options); + if (message.table && message.table.length) { + object.table = []; + for (var j = 0; j < message.table.length; ++j) + object.table[j] = $root.google.spanner.executor.v1.TableMetadata.toObject(message.table[j], options); + } + if (message.desiredBytesPerPartition != null && message.hasOwnProperty("desiredBytesPerPartition")) { + if (typeof message.desiredBytesPerPartition === "number") + object.desiredBytesPerPartition = options.longs === String ? String(message.desiredBytesPerPartition) : message.desiredBytesPerPartition; + else + object.desiredBytesPerPartition = options.longs === String ? $util.Long.prototype.toString.call(message.desiredBytesPerPartition) : options.longs === Number ? new $util.LongBits(message.desiredBytesPerPartition.low >>> 0, message.desiredBytesPerPartition.high >>> 0).toNumber() : message.desiredBytesPerPartition; + if (options.oneofs) + object._desiredBytesPerPartition = "desiredBytesPerPartition"; + } + if (message.maxPartitionCount != null && message.hasOwnProperty("maxPartitionCount")) { + if (typeof message.maxPartitionCount === "number") + object.maxPartitionCount = options.longs === String ? String(message.maxPartitionCount) : message.maxPartitionCount; + else + object.maxPartitionCount = options.longs === String ? $util.Long.prototype.toString.call(message.maxPartitionCount) : options.longs === Number ? new $util.LongBits(message.maxPartitionCount.low >>> 0, message.maxPartitionCount.high >>> 0).toNumber() : message.maxPartitionCount; + if (options.oneofs) + object._maxPartitionCount = "maxPartitionCount"; + } + return object; + }; + + /** + * Converts this GenerateDbPartitionsForReadAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @instance + * @returns {Object.} JSON object + */ + GenerateDbPartitionsForReadAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GenerateDbPartitionsForReadAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForReadAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GenerateDbPartitionsForReadAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.GenerateDbPartitionsForReadAction"; + }; + + return GenerateDbPartitionsForReadAction; + })(); + + v1.GenerateDbPartitionsForQueryAction = (function() { + + /** + * Properties of a GenerateDbPartitionsForQueryAction. + * @memberof google.spanner.executor.v1 + * @interface IGenerateDbPartitionsForQueryAction + * @property {google.spanner.executor.v1.IQueryAction|null} [query] GenerateDbPartitionsForQueryAction query + * @property {number|Long|null} [desiredBytesPerPartition] GenerateDbPartitionsForQueryAction desiredBytesPerPartition + */ + + /** + * Constructs a new GenerateDbPartitionsForQueryAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a GenerateDbPartitionsForQueryAction. + * @implements IGenerateDbPartitionsForQueryAction + * @constructor + * @param {google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction=} [properties] Properties to set + */ + function GenerateDbPartitionsForQueryAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GenerateDbPartitionsForQueryAction query. + * @member {google.spanner.executor.v1.IQueryAction|null|undefined} query + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @instance + */ + GenerateDbPartitionsForQueryAction.prototype.query = null; + + /** + * GenerateDbPartitionsForQueryAction desiredBytesPerPartition. + * @member {number|Long|null|undefined} desiredBytesPerPartition + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @instance + */ + GenerateDbPartitionsForQueryAction.prototype.desiredBytesPerPartition = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(GenerateDbPartitionsForQueryAction.prototype, "_desiredBytesPerPartition", { + get: $util.oneOfGetter($oneOfFields = ["desiredBytesPerPartition"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new GenerateDbPartitionsForQueryAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.GenerateDbPartitionsForQueryAction} GenerateDbPartitionsForQueryAction instance + */ + GenerateDbPartitionsForQueryAction.create = function create(properties) { + return new GenerateDbPartitionsForQueryAction(properties); + }; + + /** + * Encodes the specified GenerateDbPartitionsForQueryAction message. Does not implicitly {@link google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction} message GenerateDbPartitionsForQueryAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GenerateDbPartitionsForQueryAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.query != null && Object.hasOwnProperty.call(message, "query")) + $root.google.spanner.executor.v1.QueryAction.encode(message.query, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.desiredBytesPerPartition != null && Object.hasOwnProperty.call(message, "desiredBytesPerPartition")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.desiredBytesPerPartition); + return writer; + }; + + /** + * Encodes the specified GenerateDbPartitionsForQueryAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {google.spanner.executor.v1.IGenerateDbPartitionsForQueryAction} message GenerateDbPartitionsForQueryAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GenerateDbPartitionsForQueryAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GenerateDbPartitionsForQueryAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.GenerateDbPartitionsForQueryAction} GenerateDbPartitionsForQueryAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GenerateDbPartitionsForQueryAction.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.spanner.executor.v1.GenerateDbPartitionsForQueryAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.query = $root.google.spanner.executor.v1.QueryAction.decode(reader, reader.uint32()); + break; + } + case 2: { + message.desiredBytesPerPartition = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GenerateDbPartitionsForQueryAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.GenerateDbPartitionsForQueryAction} GenerateDbPartitionsForQueryAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GenerateDbPartitionsForQueryAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GenerateDbPartitionsForQueryAction message. + * @function verify + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GenerateDbPartitionsForQueryAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.query != null && message.hasOwnProperty("query")) { + var error = $root.google.spanner.executor.v1.QueryAction.verify(message.query); + if (error) + return "query." + error; + } + if (message.desiredBytesPerPartition != null && message.hasOwnProperty("desiredBytesPerPartition")) { + properties._desiredBytesPerPartition = 1; + if (!$util.isInteger(message.desiredBytesPerPartition) && !(message.desiredBytesPerPartition && $util.isInteger(message.desiredBytesPerPartition.low) && $util.isInteger(message.desiredBytesPerPartition.high))) + return "desiredBytesPerPartition: integer|Long expected"; + } + return null; + }; + + /** + * Creates a GenerateDbPartitionsForQueryAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.GenerateDbPartitionsForQueryAction} GenerateDbPartitionsForQueryAction + */ + GenerateDbPartitionsForQueryAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.GenerateDbPartitionsForQueryAction) + return object; + var message = new $root.google.spanner.executor.v1.GenerateDbPartitionsForQueryAction(); + if (object.query != null) { + if (typeof object.query !== "object") + throw TypeError(".google.spanner.executor.v1.GenerateDbPartitionsForQueryAction.query: object expected"); + message.query = $root.google.spanner.executor.v1.QueryAction.fromObject(object.query); + } + if (object.desiredBytesPerPartition != null) + if ($util.Long) + (message.desiredBytesPerPartition = $util.Long.fromValue(object.desiredBytesPerPartition)).unsigned = false; + else if (typeof object.desiredBytesPerPartition === "string") + message.desiredBytesPerPartition = parseInt(object.desiredBytesPerPartition, 10); + else if (typeof object.desiredBytesPerPartition === "number") + message.desiredBytesPerPartition = object.desiredBytesPerPartition; + else if (typeof object.desiredBytesPerPartition === "object") + message.desiredBytesPerPartition = new $util.LongBits(object.desiredBytesPerPartition.low >>> 0, object.desiredBytesPerPartition.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a GenerateDbPartitionsForQueryAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {google.spanner.executor.v1.GenerateDbPartitionsForQueryAction} message GenerateDbPartitionsForQueryAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GenerateDbPartitionsForQueryAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.query = null; + if (message.query != null && message.hasOwnProperty("query")) + object.query = $root.google.spanner.executor.v1.QueryAction.toObject(message.query, options); + if (message.desiredBytesPerPartition != null && message.hasOwnProperty("desiredBytesPerPartition")) { + if (typeof message.desiredBytesPerPartition === "number") + object.desiredBytesPerPartition = options.longs === String ? String(message.desiredBytesPerPartition) : message.desiredBytesPerPartition; + else + object.desiredBytesPerPartition = options.longs === String ? $util.Long.prototype.toString.call(message.desiredBytesPerPartition) : options.longs === Number ? new $util.LongBits(message.desiredBytesPerPartition.low >>> 0, message.desiredBytesPerPartition.high >>> 0).toNumber() : message.desiredBytesPerPartition; + if (options.oneofs) + object._desiredBytesPerPartition = "desiredBytesPerPartition"; + } + return object; + }; + + /** + * Converts this GenerateDbPartitionsForQueryAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @instance + * @returns {Object.} JSON object + */ + GenerateDbPartitionsForQueryAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GenerateDbPartitionsForQueryAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.GenerateDbPartitionsForQueryAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GenerateDbPartitionsForQueryAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.GenerateDbPartitionsForQueryAction"; + }; + + return GenerateDbPartitionsForQueryAction; + })(); + + v1.BatchPartition = (function() { + + /** + * Properties of a BatchPartition. + * @memberof google.spanner.executor.v1 + * @interface IBatchPartition + * @property {Uint8Array|null} [partition] BatchPartition partition + * @property {Uint8Array|null} [partitionToken] BatchPartition partitionToken + * @property {string|null} [table] BatchPartition table + * @property {string|null} [index] BatchPartition index + */ + + /** + * Constructs a new BatchPartition. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a BatchPartition. + * @implements IBatchPartition + * @constructor + * @param {google.spanner.executor.v1.IBatchPartition=} [properties] Properties to set + */ + function BatchPartition(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchPartition partition. + * @member {Uint8Array} partition + * @memberof google.spanner.executor.v1.BatchPartition + * @instance + */ + BatchPartition.prototype.partition = $util.newBuffer([]); + + /** + * BatchPartition partitionToken. + * @member {Uint8Array} partitionToken + * @memberof google.spanner.executor.v1.BatchPartition + * @instance + */ + BatchPartition.prototype.partitionToken = $util.newBuffer([]); + + /** + * BatchPartition table. + * @member {string|null|undefined} table + * @memberof google.spanner.executor.v1.BatchPartition + * @instance + */ + BatchPartition.prototype.table = null; + + /** + * BatchPartition index. + * @member {string|null|undefined} index + * @memberof google.spanner.executor.v1.BatchPartition + * @instance + */ + BatchPartition.prototype.index = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(BatchPartition.prototype, "_table", { + get: $util.oneOfGetter($oneOfFields = ["table"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(BatchPartition.prototype, "_index", { + get: $util.oneOfGetter($oneOfFields = ["index"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new BatchPartition instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {google.spanner.executor.v1.IBatchPartition=} [properties] Properties to set + * @returns {google.spanner.executor.v1.BatchPartition} BatchPartition instance + */ + BatchPartition.create = function create(properties) { + return new BatchPartition(properties); + }; + + /** + * Encodes the specified BatchPartition message. Does not implicitly {@link google.spanner.executor.v1.BatchPartition.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {google.spanner.executor.v1.IBatchPartition} message BatchPartition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchPartition.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partition != null && Object.hasOwnProperty.call(message, "partition")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.partition); + if (message.partitionToken != null && Object.hasOwnProperty.call(message, "partitionToken")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.partitionToken); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.table); + if (message.index != null && Object.hasOwnProperty.call(message, "index")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.index); + return writer; + }; + + /** + * Encodes the specified BatchPartition message, length delimited. Does not implicitly {@link google.spanner.executor.v1.BatchPartition.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {google.spanner.executor.v1.IBatchPartition} message BatchPartition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchPartition.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BatchPartition message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.BatchPartition} BatchPartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchPartition.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.spanner.executor.v1.BatchPartition(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.partition = reader.bytes(); + break; + } + case 2: { + message.partitionToken = reader.bytes(); + break; + } + case 3: { + message.table = reader.string(); + break; + } + case 4: { + message.index = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BatchPartition message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.BatchPartition} BatchPartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchPartition.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BatchPartition message. + * @function verify + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BatchPartition.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.partition != null && message.hasOwnProperty("partition")) + if (!(message.partition && typeof message.partition.length === "number" || $util.isString(message.partition))) + return "partition: buffer expected"; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + if (!(message.partitionToken && typeof message.partitionToken.length === "number" || $util.isString(message.partitionToken))) + return "partitionToken: buffer expected"; + if (message.table != null && message.hasOwnProperty("table")) { + properties._table = 1; + if (!$util.isString(message.table)) + return "table: string expected"; + } + if (message.index != null && message.hasOwnProperty("index")) { + properties._index = 1; + if (!$util.isString(message.index)) + return "index: string expected"; + } + return null; + }; + + /** + * Creates a BatchPartition message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.BatchPartition} BatchPartition + */ + BatchPartition.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.BatchPartition) + return object; + var message = new $root.google.spanner.executor.v1.BatchPartition(); + if (object.partition != null) + if (typeof object.partition === "string") + $util.base64.decode(object.partition, message.partition = $util.newBuffer($util.base64.length(object.partition)), 0); + else if (object.partition.length >= 0) + message.partition = object.partition; + if (object.partitionToken != null) + if (typeof object.partitionToken === "string") + $util.base64.decode(object.partitionToken, message.partitionToken = $util.newBuffer($util.base64.length(object.partitionToken)), 0); + else if (object.partitionToken.length >= 0) + message.partitionToken = object.partitionToken; + if (object.table != null) + message.table = String(object.table); + if (object.index != null) + message.index = String(object.index); + return message; + }; + + /** + * Creates a plain object from a BatchPartition message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {google.spanner.executor.v1.BatchPartition} message BatchPartition + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchPartition.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if (options.bytes === String) + object.partition = ""; + else { + object.partition = []; + if (options.bytes !== Array) + object.partition = $util.newBuffer(object.partition); + } + if (options.bytes === String) + object.partitionToken = ""; + else { + object.partitionToken = []; + if (options.bytes !== Array) + object.partitionToken = $util.newBuffer(object.partitionToken); + } + } + if (message.partition != null && message.hasOwnProperty("partition")) + object.partition = options.bytes === String ? $util.base64.encode(message.partition, 0, message.partition.length) : options.bytes === Array ? Array.prototype.slice.call(message.partition) : message.partition; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + object.partitionToken = options.bytes === String ? $util.base64.encode(message.partitionToken, 0, message.partitionToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.partitionToken) : message.partitionToken; + if (message.table != null && message.hasOwnProperty("table")) { + object.table = message.table; + if (options.oneofs) + object._table = "table"; + } + if (message.index != null && message.hasOwnProperty("index")) { + object.index = message.index; + if (options.oneofs) + object._index = "index"; + } + return object; + }; + + /** + * Converts this BatchPartition to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.BatchPartition + * @instance + * @returns {Object.} JSON object + */ + BatchPartition.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchPartition + * @function getTypeUrl + * @memberof google.spanner.executor.v1.BatchPartition + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchPartition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.BatchPartition"; + }; + + return BatchPartition; + })(); + + v1.ExecutePartitionAction = (function() { + + /** + * Properties of an ExecutePartitionAction. + * @memberof google.spanner.executor.v1 + * @interface IExecutePartitionAction + * @property {google.spanner.executor.v1.IBatchPartition|null} [partition] ExecutePartitionAction partition + */ + + /** + * Constructs a new ExecutePartitionAction. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an ExecutePartitionAction. + * @implements IExecutePartitionAction + * @constructor + * @param {google.spanner.executor.v1.IExecutePartitionAction=} [properties] Properties to set + */ + function ExecutePartitionAction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecutePartitionAction partition. + * @member {google.spanner.executor.v1.IBatchPartition|null|undefined} partition + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @instance + */ + ExecutePartitionAction.prototype.partition = null; + + /** + * Creates a new ExecutePartitionAction instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {google.spanner.executor.v1.IExecutePartitionAction=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ExecutePartitionAction} ExecutePartitionAction instance + */ + ExecutePartitionAction.create = function create(properties) { + return new ExecutePartitionAction(properties); + }; + + /** + * Encodes the specified ExecutePartitionAction message. Does not implicitly {@link google.spanner.executor.v1.ExecutePartitionAction.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {google.spanner.executor.v1.IExecutePartitionAction} message ExecutePartitionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecutePartitionAction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partition != null && Object.hasOwnProperty.call(message, "partition")) + $root.google.spanner.executor.v1.BatchPartition.encode(message.partition, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ExecutePartitionAction message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ExecutePartitionAction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {google.spanner.executor.v1.IExecutePartitionAction} message ExecutePartitionAction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecutePartitionAction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExecutePartitionAction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ExecutePartitionAction} ExecutePartitionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecutePartitionAction.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.spanner.executor.v1.ExecutePartitionAction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.partition = $root.google.spanner.executor.v1.BatchPartition.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExecutePartitionAction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ExecutePartitionAction} ExecutePartitionAction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecutePartitionAction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExecutePartitionAction message. + * @function verify + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExecutePartitionAction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.partition != null && message.hasOwnProperty("partition")) { + var error = $root.google.spanner.executor.v1.BatchPartition.verify(message.partition); + if (error) + return "partition." + error; + } + return null; + }; + + /** + * Creates an ExecutePartitionAction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ExecutePartitionAction} ExecutePartitionAction + */ + ExecutePartitionAction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ExecutePartitionAction) + return object; + var message = new $root.google.spanner.executor.v1.ExecutePartitionAction(); + if (object.partition != null) { + if (typeof object.partition !== "object") + throw TypeError(".google.spanner.executor.v1.ExecutePartitionAction.partition: object expected"); + message.partition = $root.google.spanner.executor.v1.BatchPartition.fromObject(object.partition); + } + return message; + }; + + /** + * Creates a plain object from an ExecutePartitionAction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {google.spanner.executor.v1.ExecutePartitionAction} message ExecutePartitionAction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecutePartitionAction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.partition = null; + if (message.partition != null && message.hasOwnProperty("partition")) + object.partition = $root.google.spanner.executor.v1.BatchPartition.toObject(message.partition, options); + return object; + }; + + /** + * Converts this ExecutePartitionAction to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @instance + * @returns {Object.} JSON object + */ + ExecutePartitionAction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecutePartitionAction + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ExecutePartitionAction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecutePartitionAction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ExecutePartitionAction"; + }; + + return ExecutePartitionAction; + })(); + + v1.ExecuteChangeStreamQuery = (function() { + + /** + * Properties of an ExecuteChangeStreamQuery. + * @memberof google.spanner.executor.v1 + * @interface IExecuteChangeStreamQuery + * @property {string|null} [name] ExecuteChangeStreamQuery name + * @property {google.protobuf.ITimestamp|null} [startTime] ExecuteChangeStreamQuery startTime + * @property {google.protobuf.ITimestamp|null} [endTime] ExecuteChangeStreamQuery endTime + * @property {string|null} [partitionToken] ExecuteChangeStreamQuery partitionToken + * @property {Array.|null} [readOptions] ExecuteChangeStreamQuery readOptions + * @property {number|null} [heartbeatMilliseconds] ExecuteChangeStreamQuery heartbeatMilliseconds + * @property {number|Long|null} [deadlineSeconds] ExecuteChangeStreamQuery deadlineSeconds + * @property {string|null} [cloudDatabaseRole] ExecuteChangeStreamQuery cloudDatabaseRole + */ + + /** + * Constructs a new ExecuteChangeStreamQuery. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an ExecuteChangeStreamQuery. + * @implements IExecuteChangeStreamQuery + * @constructor + * @param {google.spanner.executor.v1.IExecuteChangeStreamQuery=} [properties] Properties to set + */ + function ExecuteChangeStreamQuery(properties) { + this.readOptions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecuteChangeStreamQuery name. + * @member {string} name + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + */ + ExecuteChangeStreamQuery.prototype.name = ""; + + /** + * ExecuteChangeStreamQuery startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + */ + ExecuteChangeStreamQuery.prototype.startTime = null; + + /** + * ExecuteChangeStreamQuery endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + */ + ExecuteChangeStreamQuery.prototype.endTime = null; + + /** + * ExecuteChangeStreamQuery partitionToken. + * @member {string|null|undefined} partitionToken + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + */ + ExecuteChangeStreamQuery.prototype.partitionToken = null; + + /** + * ExecuteChangeStreamQuery readOptions. + * @member {Array.} readOptions + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + */ + ExecuteChangeStreamQuery.prototype.readOptions = $util.emptyArray; + + /** + * ExecuteChangeStreamQuery heartbeatMilliseconds. + * @member {number|null|undefined} heartbeatMilliseconds + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + */ + ExecuteChangeStreamQuery.prototype.heartbeatMilliseconds = null; + + /** + * ExecuteChangeStreamQuery deadlineSeconds. + * @member {number|Long|null|undefined} deadlineSeconds + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + */ + ExecuteChangeStreamQuery.prototype.deadlineSeconds = null; + + /** + * ExecuteChangeStreamQuery cloudDatabaseRole. + * @member {string|null|undefined} cloudDatabaseRole + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + */ + ExecuteChangeStreamQuery.prototype.cloudDatabaseRole = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ExecuteChangeStreamQuery.prototype, "_endTime", { + get: $util.oneOfGetter($oneOfFields = ["endTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ExecuteChangeStreamQuery.prototype, "_partitionToken", { + get: $util.oneOfGetter($oneOfFields = ["partitionToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ExecuteChangeStreamQuery.prototype, "_heartbeatMilliseconds", { + get: $util.oneOfGetter($oneOfFields = ["heartbeatMilliseconds"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ExecuteChangeStreamQuery.prototype, "_deadlineSeconds", { + get: $util.oneOfGetter($oneOfFields = ["deadlineSeconds"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ExecuteChangeStreamQuery.prototype, "_cloudDatabaseRole", { + get: $util.oneOfGetter($oneOfFields = ["cloudDatabaseRole"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ExecuteChangeStreamQuery instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {google.spanner.executor.v1.IExecuteChangeStreamQuery=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ExecuteChangeStreamQuery} ExecuteChangeStreamQuery instance + */ + ExecuteChangeStreamQuery.create = function create(properties) { + return new ExecuteChangeStreamQuery(properties); + }; + + /** + * Encodes the specified ExecuteChangeStreamQuery message. Does not implicitly {@link google.spanner.executor.v1.ExecuteChangeStreamQuery.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {google.spanner.executor.v1.IExecuteChangeStreamQuery} message ExecuteChangeStreamQuery message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecuteChangeStreamQuery.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) + $root.google.protobuf.Timestamp.encode(message.endTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.partitionToken != null && Object.hasOwnProperty.call(message, "partitionToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.partitionToken); + if (message.readOptions != null && message.readOptions.length) + for (var i = 0; i < message.readOptions.length; ++i) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.readOptions[i]); + if (message.heartbeatMilliseconds != null && Object.hasOwnProperty.call(message, "heartbeatMilliseconds")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.heartbeatMilliseconds); + if (message.deadlineSeconds != null && Object.hasOwnProperty.call(message, "deadlineSeconds")) + writer.uint32(/* id 7, wireType 0 =*/56).int64(message.deadlineSeconds); + if (message.cloudDatabaseRole != null && Object.hasOwnProperty.call(message, "cloudDatabaseRole")) + writer.uint32(/* id 8, wireType 2 =*/66).string(message.cloudDatabaseRole); + return writer; + }; + + /** + * Encodes the specified ExecuteChangeStreamQuery message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ExecuteChangeStreamQuery.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {google.spanner.executor.v1.IExecuteChangeStreamQuery} message ExecuteChangeStreamQuery message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecuteChangeStreamQuery.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExecuteChangeStreamQuery message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ExecuteChangeStreamQuery} ExecuteChangeStreamQuery + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecuteChangeStreamQuery.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.spanner.executor.v1.ExecuteChangeStreamQuery(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.endTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.partitionToken = reader.string(); + break; + } + case 5: { + if (!(message.readOptions && message.readOptions.length)) + message.readOptions = []; + message.readOptions.push(reader.string()); + break; + } + case 6: { + message.heartbeatMilliseconds = reader.int32(); + break; + } + case 7: { + message.deadlineSeconds = reader.int64(); + break; + } + case 8: { + message.cloudDatabaseRole = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExecuteChangeStreamQuery message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ExecuteChangeStreamQuery} ExecuteChangeStreamQuery + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecuteChangeStreamQuery.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExecuteChangeStreamQuery message. + * @function verify + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExecuteChangeStreamQuery.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.endTime != null && message.hasOwnProperty("endTime")) { + properties._endTime = 1; + { + var error = $root.google.protobuf.Timestamp.verify(message.endTime); + if (error) + return "endTime." + error; + } + } + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) { + properties._partitionToken = 1; + if (!$util.isString(message.partitionToken)) + return "partitionToken: string expected"; + } + if (message.readOptions != null && message.hasOwnProperty("readOptions")) { + if (!Array.isArray(message.readOptions)) + return "readOptions: array expected"; + for (var i = 0; i < message.readOptions.length; ++i) + if (!$util.isString(message.readOptions[i])) + return "readOptions: string[] expected"; + } + if (message.heartbeatMilliseconds != null && message.hasOwnProperty("heartbeatMilliseconds")) { + properties._heartbeatMilliseconds = 1; + if (!$util.isInteger(message.heartbeatMilliseconds)) + return "heartbeatMilliseconds: integer expected"; + } + if (message.deadlineSeconds != null && message.hasOwnProperty("deadlineSeconds")) { + properties._deadlineSeconds = 1; + if (!$util.isInteger(message.deadlineSeconds) && !(message.deadlineSeconds && $util.isInteger(message.deadlineSeconds.low) && $util.isInteger(message.deadlineSeconds.high))) + return "deadlineSeconds: integer|Long expected"; + } + if (message.cloudDatabaseRole != null && message.hasOwnProperty("cloudDatabaseRole")) { + properties._cloudDatabaseRole = 1; + if (!$util.isString(message.cloudDatabaseRole)) + return "cloudDatabaseRole: string expected"; + } + return null; + }; + + /** + * Creates an ExecuteChangeStreamQuery message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ExecuteChangeStreamQuery} ExecuteChangeStreamQuery + */ + ExecuteChangeStreamQuery.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ExecuteChangeStreamQuery) + return object; + var message = new $root.google.spanner.executor.v1.ExecuteChangeStreamQuery(); + if (object.name != null) + message.name = String(object.name); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.spanner.executor.v1.ExecuteChangeStreamQuery.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.spanner.executor.v1.ExecuteChangeStreamQuery.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + if (object.partitionToken != null) + message.partitionToken = String(object.partitionToken); + if (object.readOptions) { + if (!Array.isArray(object.readOptions)) + throw TypeError(".google.spanner.executor.v1.ExecuteChangeStreamQuery.readOptions: array expected"); + message.readOptions = []; + for (var i = 0; i < object.readOptions.length; ++i) + message.readOptions[i] = String(object.readOptions[i]); + } + if (object.heartbeatMilliseconds != null) + message.heartbeatMilliseconds = object.heartbeatMilliseconds | 0; + if (object.deadlineSeconds != null) + if ($util.Long) + (message.deadlineSeconds = $util.Long.fromValue(object.deadlineSeconds)).unsigned = false; + else if (typeof object.deadlineSeconds === "string") + message.deadlineSeconds = parseInt(object.deadlineSeconds, 10); + else if (typeof object.deadlineSeconds === "number") + message.deadlineSeconds = object.deadlineSeconds; + else if (typeof object.deadlineSeconds === "object") + message.deadlineSeconds = new $util.LongBits(object.deadlineSeconds.low >>> 0, object.deadlineSeconds.high >>> 0).toNumber(); + if (object.cloudDatabaseRole != null) + message.cloudDatabaseRole = String(object.cloudDatabaseRole); + return message; + }; + + /** + * Creates a plain object from an ExecuteChangeStreamQuery message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {google.spanner.executor.v1.ExecuteChangeStreamQuery} message ExecuteChangeStreamQuery + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecuteChangeStreamQuery.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.readOptions = []; + if (options.defaults) { + object.name = ""; + object.startTime = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) { + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (options.oneofs) + object._endTime = "endTime"; + } + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) { + object.partitionToken = message.partitionToken; + if (options.oneofs) + object._partitionToken = "partitionToken"; + } + if (message.readOptions && message.readOptions.length) { + object.readOptions = []; + for (var j = 0; j < message.readOptions.length; ++j) + object.readOptions[j] = message.readOptions[j]; + } + if (message.heartbeatMilliseconds != null && message.hasOwnProperty("heartbeatMilliseconds")) { + object.heartbeatMilliseconds = message.heartbeatMilliseconds; + if (options.oneofs) + object._heartbeatMilliseconds = "heartbeatMilliseconds"; + } + if (message.deadlineSeconds != null && message.hasOwnProperty("deadlineSeconds")) { + if (typeof message.deadlineSeconds === "number") + object.deadlineSeconds = options.longs === String ? String(message.deadlineSeconds) : message.deadlineSeconds; + else + object.deadlineSeconds = options.longs === String ? $util.Long.prototype.toString.call(message.deadlineSeconds) : options.longs === Number ? new $util.LongBits(message.deadlineSeconds.low >>> 0, message.deadlineSeconds.high >>> 0).toNumber() : message.deadlineSeconds; + if (options.oneofs) + object._deadlineSeconds = "deadlineSeconds"; + } + if (message.cloudDatabaseRole != null && message.hasOwnProperty("cloudDatabaseRole")) { + object.cloudDatabaseRole = message.cloudDatabaseRole; + if (options.oneofs) + object._cloudDatabaseRole = "cloudDatabaseRole"; + } + return object; + }; + + /** + * Converts this ExecuteChangeStreamQuery to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @instance + * @returns {Object.} JSON object + */ + ExecuteChangeStreamQuery.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecuteChangeStreamQuery + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ExecuteChangeStreamQuery + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecuteChangeStreamQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ExecuteChangeStreamQuery"; + }; + + return ExecuteChangeStreamQuery; + })(); + + v1.SpannerActionOutcome = (function() { + + /** + * Properties of a SpannerActionOutcome. + * @memberof google.spanner.executor.v1 + * @interface ISpannerActionOutcome + * @property {google.rpc.IStatus|null} [status] SpannerActionOutcome status + * @property {google.protobuf.ITimestamp|null} [commitTime] SpannerActionOutcome commitTime + * @property {google.spanner.executor.v1.IReadResult|null} [readResult] SpannerActionOutcome readResult + * @property {google.spanner.executor.v1.IQueryResult|null} [queryResult] SpannerActionOutcome queryResult + * @property {boolean|null} [transactionRestarted] SpannerActionOutcome transactionRestarted + * @property {Uint8Array|null} [batchTxnId] SpannerActionOutcome batchTxnId + * @property {Array.|null} [dbPartition] SpannerActionOutcome dbPartition + * @property {google.spanner.executor.v1.IAdminResult|null} [adminResult] SpannerActionOutcome adminResult + * @property {Array.|null} [dmlRowsModified] SpannerActionOutcome dmlRowsModified + * @property {Array.|null} [changeStreamRecords] SpannerActionOutcome changeStreamRecords + * @property {number|Long|null} [snapshotIsolationTxnReadTimestamp] SpannerActionOutcome snapshotIsolationTxnReadTimestamp + */ + + /** + * Constructs a new SpannerActionOutcome. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a SpannerActionOutcome. + * @implements ISpannerActionOutcome + * @constructor + * @param {google.spanner.executor.v1.ISpannerActionOutcome=} [properties] Properties to set + */ + function SpannerActionOutcome(properties) { + this.dbPartition = []; + this.dmlRowsModified = []; + this.changeStreamRecords = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SpannerActionOutcome status. + * @member {google.rpc.IStatus|null|undefined} status + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.status = null; + + /** + * SpannerActionOutcome commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.commitTime = null; + + /** + * SpannerActionOutcome readResult. + * @member {google.spanner.executor.v1.IReadResult|null|undefined} readResult + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.readResult = null; + + /** + * SpannerActionOutcome queryResult. + * @member {google.spanner.executor.v1.IQueryResult|null|undefined} queryResult + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.queryResult = null; + + /** + * SpannerActionOutcome transactionRestarted. + * @member {boolean|null|undefined} transactionRestarted + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.transactionRestarted = null; + + /** + * SpannerActionOutcome batchTxnId. + * @member {Uint8Array|null|undefined} batchTxnId + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.batchTxnId = null; + + /** + * SpannerActionOutcome dbPartition. + * @member {Array.} dbPartition + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.dbPartition = $util.emptyArray; + + /** + * SpannerActionOutcome adminResult. + * @member {google.spanner.executor.v1.IAdminResult|null|undefined} adminResult + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.adminResult = null; + + /** + * SpannerActionOutcome dmlRowsModified. + * @member {Array.} dmlRowsModified + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.dmlRowsModified = $util.emptyArray; + + /** + * SpannerActionOutcome changeStreamRecords. + * @member {Array.} changeStreamRecords + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.changeStreamRecords = $util.emptyArray; + + /** + * SpannerActionOutcome snapshotIsolationTxnReadTimestamp. + * @member {number|Long|null|undefined} snapshotIsolationTxnReadTimestamp + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + */ + SpannerActionOutcome.prototype.snapshotIsolationTxnReadTimestamp = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SpannerActionOutcome.prototype, "_status", { + get: $util.oneOfGetter($oneOfFields = ["status"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SpannerActionOutcome.prototype, "_commitTime", { + get: $util.oneOfGetter($oneOfFields = ["commitTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SpannerActionOutcome.prototype, "_readResult", { + get: $util.oneOfGetter($oneOfFields = ["readResult"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SpannerActionOutcome.prototype, "_queryResult", { + get: $util.oneOfGetter($oneOfFields = ["queryResult"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SpannerActionOutcome.prototype, "_transactionRestarted", { + get: $util.oneOfGetter($oneOfFields = ["transactionRestarted"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SpannerActionOutcome.prototype, "_batchTxnId", { + get: $util.oneOfGetter($oneOfFields = ["batchTxnId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SpannerActionOutcome.prototype, "_adminResult", { + get: $util.oneOfGetter($oneOfFields = ["adminResult"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SpannerActionOutcome.prototype, "_snapshotIsolationTxnReadTimestamp", { + get: $util.oneOfGetter($oneOfFields = ["snapshotIsolationTxnReadTimestamp"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new SpannerActionOutcome instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {google.spanner.executor.v1.ISpannerActionOutcome=} [properties] Properties to set + * @returns {google.spanner.executor.v1.SpannerActionOutcome} SpannerActionOutcome instance + */ + SpannerActionOutcome.create = function create(properties) { + return new SpannerActionOutcome(properties); + }; + + /** + * Encodes the specified SpannerActionOutcome message. Does not implicitly {@link google.spanner.executor.v1.SpannerActionOutcome.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {google.spanner.executor.v1.ISpannerActionOutcome} message SpannerActionOutcome message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerActionOutcome.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + $root.google.rpc.Status.encode(message.status, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.commitTime != null && Object.hasOwnProperty.call(message, "commitTime")) + $root.google.protobuf.Timestamp.encode(message.commitTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.readResult != null && Object.hasOwnProperty.call(message, "readResult")) + $root.google.spanner.executor.v1.ReadResult.encode(message.readResult, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.queryResult != null && Object.hasOwnProperty.call(message, "queryResult")) + $root.google.spanner.executor.v1.QueryResult.encode(message.queryResult, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.transactionRestarted != null && Object.hasOwnProperty.call(message, "transactionRestarted")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.transactionRestarted); + if (message.batchTxnId != null && Object.hasOwnProperty.call(message, "batchTxnId")) + writer.uint32(/* id 6, wireType 2 =*/50).bytes(message.batchTxnId); + if (message.dbPartition != null && message.dbPartition.length) + for (var i = 0; i < message.dbPartition.length; ++i) + $root.google.spanner.executor.v1.BatchPartition.encode(message.dbPartition[i], writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.adminResult != null && Object.hasOwnProperty.call(message, "adminResult")) + $root.google.spanner.executor.v1.AdminResult.encode(message.adminResult, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.dmlRowsModified != null && message.dmlRowsModified.length) { + writer.uint32(/* id 9, wireType 2 =*/74).fork(); + for (var i = 0; i < message.dmlRowsModified.length; ++i) + writer.int64(message.dmlRowsModified[i]); + writer.ldelim(); + } + if (message.changeStreamRecords != null && message.changeStreamRecords.length) + for (var i = 0; i < message.changeStreamRecords.length; ++i) + $root.google.spanner.executor.v1.ChangeStreamRecord.encode(message.changeStreamRecords[i], writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); + if (message.snapshotIsolationTxnReadTimestamp != null && Object.hasOwnProperty.call(message, "snapshotIsolationTxnReadTimestamp")) + writer.uint32(/* id 11, wireType 0 =*/88).int64(message.snapshotIsolationTxnReadTimestamp); + return writer; + }; + + /** + * Encodes the specified SpannerActionOutcome message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerActionOutcome.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {google.spanner.executor.v1.ISpannerActionOutcome} message SpannerActionOutcome message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerActionOutcome.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SpannerActionOutcome message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.SpannerActionOutcome} SpannerActionOutcome + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerActionOutcome.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.spanner.executor.v1.SpannerActionOutcome(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.status = $root.google.rpc.Status.decode(reader, reader.uint32()); + break; + } + case 2: { + message.commitTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.readResult = $root.google.spanner.executor.v1.ReadResult.decode(reader, reader.uint32()); + break; + } + case 4: { + message.queryResult = $root.google.spanner.executor.v1.QueryResult.decode(reader, reader.uint32()); + break; + } + case 5: { + message.transactionRestarted = reader.bool(); + break; + } + case 6: { + message.batchTxnId = reader.bytes(); + break; + } + case 7: { + if (!(message.dbPartition && message.dbPartition.length)) + message.dbPartition = []; + message.dbPartition.push($root.google.spanner.executor.v1.BatchPartition.decode(reader, reader.uint32())); + break; + } + case 8: { + message.adminResult = $root.google.spanner.executor.v1.AdminResult.decode(reader, reader.uint32()); + break; + } + case 9: { + if (!(message.dmlRowsModified && message.dmlRowsModified.length)) + message.dmlRowsModified = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.dmlRowsModified.push(reader.int64()); + } else + message.dmlRowsModified.push(reader.int64()); + break; + } + case 10: { + if (!(message.changeStreamRecords && message.changeStreamRecords.length)) + message.changeStreamRecords = []; + message.changeStreamRecords.push($root.google.spanner.executor.v1.ChangeStreamRecord.decode(reader, reader.uint32())); + break; + } + case 11: { + message.snapshotIsolationTxnReadTimestamp = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SpannerActionOutcome message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.SpannerActionOutcome} SpannerActionOutcome + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerActionOutcome.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SpannerActionOutcome message. + * @function verify + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SpannerActionOutcome.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.status != null && message.hasOwnProperty("status")) { + properties._status = 1; + { + var error = $root.google.rpc.Status.verify(message.status); + if (error) + return "status." + error; + } + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) { + properties._commitTime = 1; + { + var error = $root.google.protobuf.Timestamp.verify(message.commitTime); + if (error) + return "commitTime." + error; + } + } + if (message.readResult != null && message.hasOwnProperty("readResult")) { + properties._readResult = 1; + { + var error = $root.google.spanner.executor.v1.ReadResult.verify(message.readResult); + if (error) + return "readResult." + error; + } + } + if (message.queryResult != null && message.hasOwnProperty("queryResult")) { + properties._queryResult = 1; + { + var error = $root.google.spanner.executor.v1.QueryResult.verify(message.queryResult); + if (error) + return "queryResult." + error; + } + } + if (message.transactionRestarted != null && message.hasOwnProperty("transactionRestarted")) { + properties._transactionRestarted = 1; + if (typeof message.transactionRestarted !== "boolean") + return "transactionRestarted: boolean expected"; + } + if (message.batchTxnId != null && message.hasOwnProperty("batchTxnId")) { + properties._batchTxnId = 1; + if (!(message.batchTxnId && typeof message.batchTxnId.length === "number" || $util.isString(message.batchTxnId))) + return "batchTxnId: buffer expected"; + } + if (message.dbPartition != null && message.hasOwnProperty("dbPartition")) { + if (!Array.isArray(message.dbPartition)) + return "dbPartition: array expected"; + for (var i = 0; i < message.dbPartition.length; ++i) { + var error = $root.google.spanner.executor.v1.BatchPartition.verify(message.dbPartition[i]); + if (error) + return "dbPartition." + error; + } + } + if (message.adminResult != null && message.hasOwnProperty("adminResult")) { + properties._adminResult = 1; + { + var error = $root.google.spanner.executor.v1.AdminResult.verify(message.adminResult); + if (error) + return "adminResult." + error; + } + } + if (message.dmlRowsModified != null && message.hasOwnProperty("dmlRowsModified")) { + if (!Array.isArray(message.dmlRowsModified)) + return "dmlRowsModified: array expected"; + for (var i = 0; i < message.dmlRowsModified.length; ++i) + if (!$util.isInteger(message.dmlRowsModified[i]) && !(message.dmlRowsModified[i] && $util.isInteger(message.dmlRowsModified[i].low) && $util.isInteger(message.dmlRowsModified[i].high))) + return "dmlRowsModified: integer|Long[] expected"; + } + if (message.changeStreamRecords != null && message.hasOwnProperty("changeStreamRecords")) { + if (!Array.isArray(message.changeStreamRecords)) + return "changeStreamRecords: array expected"; + for (var i = 0; i < message.changeStreamRecords.length; ++i) { + var error = $root.google.spanner.executor.v1.ChangeStreamRecord.verify(message.changeStreamRecords[i]); + if (error) + return "changeStreamRecords." + error; + } + } + if (message.snapshotIsolationTxnReadTimestamp != null && message.hasOwnProperty("snapshotIsolationTxnReadTimestamp")) { + properties._snapshotIsolationTxnReadTimestamp = 1; + if (!$util.isInteger(message.snapshotIsolationTxnReadTimestamp) && !(message.snapshotIsolationTxnReadTimestamp && $util.isInteger(message.snapshotIsolationTxnReadTimestamp.low) && $util.isInteger(message.snapshotIsolationTxnReadTimestamp.high))) + return "snapshotIsolationTxnReadTimestamp: integer|Long expected"; + } + return null; + }; + + /** + * Creates a SpannerActionOutcome message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.SpannerActionOutcome} SpannerActionOutcome + */ + SpannerActionOutcome.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.SpannerActionOutcome) + return object; + var message = new $root.google.spanner.executor.v1.SpannerActionOutcome(); + if (object.status != null) { + if (typeof object.status !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.status: object expected"); + message.status = $root.google.rpc.Status.fromObject(object.status); + } + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + } + if (object.readResult != null) { + if (typeof object.readResult !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.readResult: object expected"); + message.readResult = $root.google.spanner.executor.v1.ReadResult.fromObject(object.readResult); + } + if (object.queryResult != null) { + if (typeof object.queryResult !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.queryResult: object expected"); + message.queryResult = $root.google.spanner.executor.v1.QueryResult.fromObject(object.queryResult); + } + if (object.transactionRestarted != null) + message.transactionRestarted = Boolean(object.transactionRestarted); + if (object.batchTxnId != null) + if (typeof object.batchTxnId === "string") + $util.base64.decode(object.batchTxnId, message.batchTxnId = $util.newBuffer($util.base64.length(object.batchTxnId)), 0); + else if (object.batchTxnId.length >= 0) + message.batchTxnId = object.batchTxnId; + if (object.dbPartition) { + if (!Array.isArray(object.dbPartition)) + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.dbPartition: array expected"); + message.dbPartition = []; + for (var i = 0; i < object.dbPartition.length; ++i) { + if (typeof object.dbPartition[i] !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.dbPartition: object expected"); + message.dbPartition[i] = $root.google.spanner.executor.v1.BatchPartition.fromObject(object.dbPartition[i]); + } + } + if (object.adminResult != null) { + if (typeof object.adminResult !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.adminResult: object expected"); + message.adminResult = $root.google.spanner.executor.v1.AdminResult.fromObject(object.adminResult); + } + if (object.dmlRowsModified) { + if (!Array.isArray(object.dmlRowsModified)) + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.dmlRowsModified: array expected"); + message.dmlRowsModified = []; + for (var i = 0; i < object.dmlRowsModified.length; ++i) + if ($util.Long) + (message.dmlRowsModified[i] = $util.Long.fromValue(object.dmlRowsModified[i])).unsigned = false; + else if (typeof object.dmlRowsModified[i] === "string") + message.dmlRowsModified[i] = parseInt(object.dmlRowsModified[i], 10); + else if (typeof object.dmlRowsModified[i] === "number") + message.dmlRowsModified[i] = object.dmlRowsModified[i]; + else if (typeof object.dmlRowsModified[i] === "object") + message.dmlRowsModified[i] = new $util.LongBits(object.dmlRowsModified[i].low >>> 0, object.dmlRowsModified[i].high >>> 0).toNumber(); + } + if (object.changeStreamRecords) { + if (!Array.isArray(object.changeStreamRecords)) + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.changeStreamRecords: array expected"); + message.changeStreamRecords = []; + for (var i = 0; i < object.changeStreamRecords.length; ++i) { + if (typeof object.changeStreamRecords[i] !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerActionOutcome.changeStreamRecords: object expected"); + message.changeStreamRecords[i] = $root.google.spanner.executor.v1.ChangeStreamRecord.fromObject(object.changeStreamRecords[i]); + } + } + if (object.snapshotIsolationTxnReadTimestamp != null) + if ($util.Long) + (message.snapshotIsolationTxnReadTimestamp = $util.Long.fromValue(object.snapshotIsolationTxnReadTimestamp)).unsigned = false; + else if (typeof object.snapshotIsolationTxnReadTimestamp === "string") + message.snapshotIsolationTxnReadTimestamp = parseInt(object.snapshotIsolationTxnReadTimestamp, 10); + else if (typeof object.snapshotIsolationTxnReadTimestamp === "number") + message.snapshotIsolationTxnReadTimestamp = object.snapshotIsolationTxnReadTimestamp; + else if (typeof object.snapshotIsolationTxnReadTimestamp === "object") + message.snapshotIsolationTxnReadTimestamp = new $util.LongBits(object.snapshotIsolationTxnReadTimestamp.low >>> 0, object.snapshotIsolationTxnReadTimestamp.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a SpannerActionOutcome message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {google.spanner.executor.v1.SpannerActionOutcome} message SpannerActionOutcome + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SpannerActionOutcome.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.dbPartition = []; + object.dmlRowsModified = []; + object.changeStreamRecords = []; + } + if (message.status != null && message.hasOwnProperty("status")) { + object.status = $root.google.rpc.Status.toObject(message.status, options); + if (options.oneofs) + object._status = "status"; + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) { + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + if (options.oneofs) + object._commitTime = "commitTime"; + } + if (message.readResult != null && message.hasOwnProperty("readResult")) { + object.readResult = $root.google.spanner.executor.v1.ReadResult.toObject(message.readResult, options); + if (options.oneofs) + object._readResult = "readResult"; + } + if (message.queryResult != null && message.hasOwnProperty("queryResult")) { + object.queryResult = $root.google.spanner.executor.v1.QueryResult.toObject(message.queryResult, options); + if (options.oneofs) + object._queryResult = "queryResult"; + } + if (message.transactionRestarted != null && message.hasOwnProperty("transactionRestarted")) { + object.transactionRestarted = message.transactionRestarted; + if (options.oneofs) + object._transactionRestarted = "transactionRestarted"; + } + if (message.batchTxnId != null && message.hasOwnProperty("batchTxnId")) { + object.batchTxnId = options.bytes === String ? $util.base64.encode(message.batchTxnId, 0, message.batchTxnId.length) : options.bytes === Array ? Array.prototype.slice.call(message.batchTxnId) : message.batchTxnId; + if (options.oneofs) + object._batchTxnId = "batchTxnId"; + } + if (message.dbPartition && message.dbPartition.length) { + object.dbPartition = []; + for (var j = 0; j < message.dbPartition.length; ++j) + object.dbPartition[j] = $root.google.spanner.executor.v1.BatchPartition.toObject(message.dbPartition[j], options); + } + if (message.adminResult != null && message.hasOwnProperty("adminResult")) { + object.adminResult = $root.google.spanner.executor.v1.AdminResult.toObject(message.adminResult, options); + if (options.oneofs) + object._adminResult = "adminResult"; + } + if (message.dmlRowsModified && message.dmlRowsModified.length) { + object.dmlRowsModified = []; + for (var j = 0; j < message.dmlRowsModified.length; ++j) + if (typeof message.dmlRowsModified[j] === "number") + object.dmlRowsModified[j] = options.longs === String ? String(message.dmlRowsModified[j]) : message.dmlRowsModified[j]; + else + object.dmlRowsModified[j] = options.longs === String ? $util.Long.prototype.toString.call(message.dmlRowsModified[j]) : options.longs === Number ? new $util.LongBits(message.dmlRowsModified[j].low >>> 0, message.dmlRowsModified[j].high >>> 0).toNumber() : message.dmlRowsModified[j]; + } + if (message.changeStreamRecords && message.changeStreamRecords.length) { + object.changeStreamRecords = []; + for (var j = 0; j < message.changeStreamRecords.length; ++j) + object.changeStreamRecords[j] = $root.google.spanner.executor.v1.ChangeStreamRecord.toObject(message.changeStreamRecords[j], options); + } + if (message.snapshotIsolationTxnReadTimestamp != null && message.hasOwnProperty("snapshotIsolationTxnReadTimestamp")) { + if (typeof message.snapshotIsolationTxnReadTimestamp === "number") + object.snapshotIsolationTxnReadTimestamp = options.longs === String ? String(message.snapshotIsolationTxnReadTimestamp) : message.snapshotIsolationTxnReadTimestamp; + else + object.snapshotIsolationTxnReadTimestamp = options.longs === String ? $util.Long.prototype.toString.call(message.snapshotIsolationTxnReadTimestamp) : options.longs === Number ? new $util.LongBits(message.snapshotIsolationTxnReadTimestamp.low >>> 0, message.snapshotIsolationTxnReadTimestamp.high >>> 0).toNumber() : message.snapshotIsolationTxnReadTimestamp; + if (options.oneofs) + object._snapshotIsolationTxnReadTimestamp = "snapshotIsolationTxnReadTimestamp"; + } + return object; + }; + + /** + * Converts this SpannerActionOutcome to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @instance + * @returns {Object.} JSON object + */ + SpannerActionOutcome.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SpannerActionOutcome + * @function getTypeUrl + * @memberof google.spanner.executor.v1.SpannerActionOutcome + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SpannerActionOutcome.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.SpannerActionOutcome"; + }; + + return SpannerActionOutcome; + })(); + + v1.AdminResult = (function() { + + /** + * Properties of an AdminResult. + * @memberof google.spanner.executor.v1 + * @interface IAdminResult + * @property {google.spanner.executor.v1.ICloudBackupResponse|null} [backupResponse] AdminResult backupResponse + * @property {google.spanner.executor.v1.IOperationResponse|null} [operationResponse] AdminResult operationResponse + * @property {google.spanner.executor.v1.ICloudDatabaseResponse|null} [databaseResponse] AdminResult databaseResponse + * @property {google.spanner.executor.v1.ICloudInstanceResponse|null} [instanceResponse] AdminResult instanceResponse + * @property {google.spanner.executor.v1.ICloudInstanceConfigResponse|null} [instanceConfigResponse] AdminResult instanceConfigResponse + */ + + /** + * Constructs a new AdminResult. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an AdminResult. + * @implements IAdminResult + * @constructor + * @param {google.spanner.executor.v1.IAdminResult=} [properties] Properties to set + */ + function AdminResult(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AdminResult backupResponse. + * @member {google.spanner.executor.v1.ICloudBackupResponse|null|undefined} backupResponse + * @memberof google.spanner.executor.v1.AdminResult + * @instance + */ + AdminResult.prototype.backupResponse = null; + + /** + * AdminResult operationResponse. + * @member {google.spanner.executor.v1.IOperationResponse|null|undefined} operationResponse + * @memberof google.spanner.executor.v1.AdminResult + * @instance + */ + AdminResult.prototype.operationResponse = null; + + /** + * AdminResult databaseResponse. + * @member {google.spanner.executor.v1.ICloudDatabaseResponse|null|undefined} databaseResponse + * @memberof google.spanner.executor.v1.AdminResult + * @instance + */ + AdminResult.prototype.databaseResponse = null; + + /** + * AdminResult instanceResponse. + * @member {google.spanner.executor.v1.ICloudInstanceResponse|null|undefined} instanceResponse + * @memberof google.spanner.executor.v1.AdminResult + * @instance + */ + AdminResult.prototype.instanceResponse = null; + + /** + * AdminResult instanceConfigResponse. + * @member {google.spanner.executor.v1.ICloudInstanceConfigResponse|null|undefined} instanceConfigResponse + * @memberof google.spanner.executor.v1.AdminResult + * @instance + */ + AdminResult.prototype.instanceConfigResponse = null; + + /** + * Creates a new AdminResult instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {google.spanner.executor.v1.IAdminResult=} [properties] Properties to set + * @returns {google.spanner.executor.v1.AdminResult} AdminResult instance + */ + AdminResult.create = function create(properties) { + return new AdminResult(properties); + }; + + /** + * Encodes the specified AdminResult message. Does not implicitly {@link google.spanner.executor.v1.AdminResult.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {google.spanner.executor.v1.IAdminResult} message AdminResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AdminResult.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.backupResponse != null && Object.hasOwnProperty.call(message, "backupResponse")) + $root.google.spanner.executor.v1.CloudBackupResponse.encode(message.backupResponse, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.operationResponse != null && Object.hasOwnProperty.call(message, "operationResponse")) + $root.google.spanner.executor.v1.OperationResponse.encode(message.operationResponse, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.databaseResponse != null && Object.hasOwnProperty.call(message, "databaseResponse")) + $root.google.spanner.executor.v1.CloudDatabaseResponse.encode(message.databaseResponse, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.instanceResponse != null && Object.hasOwnProperty.call(message, "instanceResponse")) + $root.google.spanner.executor.v1.CloudInstanceResponse.encode(message.instanceResponse, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.instanceConfigResponse != null && Object.hasOwnProperty.call(message, "instanceConfigResponse")) + $root.google.spanner.executor.v1.CloudInstanceConfigResponse.encode(message.instanceConfigResponse, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified AdminResult message, length delimited. Does not implicitly {@link google.spanner.executor.v1.AdminResult.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {google.spanner.executor.v1.IAdminResult} message AdminResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AdminResult.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AdminResult message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.AdminResult} AdminResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AdminResult.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.spanner.executor.v1.AdminResult(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.backupResponse = $root.google.spanner.executor.v1.CloudBackupResponse.decode(reader, reader.uint32()); + break; + } + case 2: { + message.operationResponse = $root.google.spanner.executor.v1.OperationResponse.decode(reader, reader.uint32()); + break; + } + case 3: { + message.databaseResponse = $root.google.spanner.executor.v1.CloudDatabaseResponse.decode(reader, reader.uint32()); + break; + } + case 4: { + message.instanceResponse = $root.google.spanner.executor.v1.CloudInstanceResponse.decode(reader, reader.uint32()); + break; + } + case 5: { + message.instanceConfigResponse = $root.google.spanner.executor.v1.CloudInstanceConfigResponse.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AdminResult message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.AdminResult} AdminResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AdminResult.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AdminResult message. + * @function verify + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AdminResult.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.backupResponse != null && message.hasOwnProperty("backupResponse")) { + var error = $root.google.spanner.executor.v1.CloudBackupResponse.verify(message.backupResponse); + if (error) + return "backupResponse." + error; + } + if (message.operationResponse != null && message.hasOwnProperty("operationResponse")) { + var error = $root.google.spanner.executor.v1.OperationResponse.verify(message.operationResponse); + if (error) + return "operationResponse." + error; + } + if (message.databaseResponse != null && message.hasOwnProperty("databaseResponse")) { + var error = $root.google.spanner.executor.v1.CloudDatabaseResponse.verify(message.databaseResponse); + if (error) + return "databaseResponse." + error; + } + if (message.instanceResponse != null && message.hasOwnProperty("instanceResponse")) { + var error = $root.google.spanner.executor.v1.CloudInstanceResponse.verify(message.instanceResponse); + if (error) + return "instanceResponse." + error; + } + if (message.instanceConfigResponse != null && message.hasOwnProperty("instanceConfigResponse")) { + var error = $root.google.spanner.executor.v1.CloudInstanceConfigResponse.verify(message.instanceConfigResponse); + if (error) + return "instanceConfigResponse." + error; + } + return null; + }; + + /** + * Creates an AdminResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.AdminResult} AdminResult + */ + AdminResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.AdminResult) + return object; + var message = new $root.google.spanner.executor.v1.AdminResult(); + if (object.backupResponse != null) { + if (typeof object.backupResponse !== "object") + throw TypeError(".google.spanner.executor.v1.AdminResult.backupResponse: object expected"); + message.backupResponse = $root.google.spanner.executor.v1.CloudBackupResponse.fromObject(object.backupResponse); + } + if (object.operationResponse != null) { + if (typeof object.operationResponse !== "object") + throw TypeError(".google.spanner.executor.v1.AdminResult.operationResponse: object expected"); + message.operationResponse = $root.google.spanner.executor.v1.OperationResponse.fromObject(object.operationResponse); + } + if (object.databaseResponse != null) { + if (typeof object.databaseResponse !== "object") + throw TypeError(".google.spanner.executor.v1.AdminResult.databaseResponse: object expected"); + message.databaseResponse = $root.google.spanner.executor.v1.CloudDatabaseResponse.fromObject(object.databaseResponse); + } + if (object.instanceResponse != null) { + if (typeof object.instanceResponse !== "object") + throw TypeError(".google.spanner.executor.v1.AdminResult.instanceResponse: object expected"); + message.instanceResponse = $root.google.spanner.executor.v1.CloudInstanceResponse.fromObject(object.instanceResponse); + } + if (object.instanceConfigResponse != null) { + if (typeof object.instanceConfigResponse !== "object") + throw TypeError(".google.spanner.executor.v1.AdminResult.instanceConfigResponse: object expected"); + message.instanceConfigResponse = $root.google.spanner.executor.v1.CloudInstanceConfigResponse.fromObject(object.instanceConfigResponse); + } + return message; + }; + + /** + * Creates a plain object from an AdminResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {google.spanner.executor.v1.AdminResult} message AdminResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AdminResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.backupResponse = null; + object.operationResponse = null; + object.databaseResponse = null; + object.instanceResponse = null; + object.instanceConfigResponse = null; + } + if (message.backupResponse != null && message.hasOwnProperty("backupResponse")) + object.backupResponse = $root.google.spanner.executor.v1.CloudBackupResponse.toObject(message.backupResponse, options); + if (message.operationResponse != null && message.hasOwnProperty("operationResponse")) + object.operationResponse = $root.google.spanner.executor.v1.OperationResponse.toObject(message.operationResponse, options); + if (message.databaseResponse != null && message.hasOwnProperty("databaseResponse")) + object.databaseResponse = $root.google.spanner.executor.v1.CloudDatabaseResponse.toObject(message.databaseResponse, options); + if (message.instanceResponse != null && message.hasOwnProperty("instanceResponse")) + object.instanceResponse = $root.google.spanner.executor.v1.CloudInstanceResponse.toObject(message.instanceResponse, options); + if (message.instanceConfigResponse != null && message.hasOwnProperty("instanceConfigResponse")) + object.instanceConfigResponse = $root.google.spanner.executor.v1.CloudInstanceConfigResponse.toObject(message.instanceConfigResponse, options); + return object; + }; + + /** + * Converts this AdminResult to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.AdminResult + * @instance + * @returns {Object.} JSON object + */ + AdminResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AdminResult + * @function getTypeUrl + * @memberof google.spanner.executor.v1.AdminResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AdminResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.AdminResult"; + }; + + return AdminResult; + })(); + + v1.CloudBackupResponse = (function() { + + /** + * Properties of a CloudBackupResponse. + * @memberof google.spanner.executor.v1 + * @interface ICloudBackupResponse + * @property {Array.|null} [listedBackups] CloudBackupResponse listedBackups + * @property {Array.|null} [listedBackupOperations] CloudBackupResponse listedBackupOperations + * @property {string|null} [nextPageToken] CloudBackupResponse nextPageToken + * @property {google.spanner.admin.database.v1.IBackup|null} [backup] CloudBackupResponse backup + */ + + /** + * Constructs a new CloudBackupResponse. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CloudBackupResponse. + * @implements ICloudBackupResponse + * @constructor + * @param {google.spanner.executor.v1.ICloudBackupResponse=} [properties] Properties to set + */ + function CloudBackupResponse(properties) { + this.listedBackups = []; + this.listedBackupOperations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CloudBackupResponse listedBackups. + * @member {Array.} listedBackups + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @instance + */ + CloudBackupResponse.prototype.listedBackups = $util.emptyArray; + + /** + * CloudBackupResponse listedBackupOperations. + * @member {Array.} listedBackupOperations + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @instance + */ + CloudBackupResponse.prototype.listedBackupOperations = $util.emptyArray; + + /** + * CloudBackupResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @instance + */ + CloudBackupResponse.prototype.nextPageToken = ""; + + /** + * CloudBackupResponse backup. + * @member {google.spanner.admin.database.v1.IBackup|null|undefined} backup + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @instance + */ + CloudBackupResponse.prototype.backup = null; + + /** + * Creates a new CloudBackupResponse instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {google.spanner.executor.v1.ICloudBackupResponse=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CloudBackupResponse} CloudBackupResponse instance + */ + CloudBackupResponse.create = function create(properties) { + return new CloudBackupResponse(properties); + }; + + /** + * Encodes the specified CloudBackupResponse message. Does not implicitly {@link google.spanner.executor.v1.CloudBackupResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {google.spanner.executor.v1.ICloudBackupResponse} message CloudBackupResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloudBackupResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.listedBackups != null && message.listedBackups.length) + for (var i = 0; i < message.listedBackups.length; ++i) + $root.google.spanner.admin.database.v1.Backup.encode(message.listedBackups[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.listedBackupOperations != null && message.listedBackupOperations.length) + for (var i = 0; i < message.listedBackupOperations.length; ++i) + $root.google.longrunning.Operation.encode(message.listedBackupOperations[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.nextPageToken); + if (message.backup != null && Object.hasOwnProperty.call(message, "backup")) + $root.google.spanner.admin.database.v1.Backup.encode(message.backup, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CloudBackupResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloudBackupResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {google.spanner.executor.v1.ICloudBackupResponse} message CloudBackupResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloudBackupResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CloudBackupResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CloudBackupResponse} CloudBackupResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloudBackupResponse.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.spanner.executor.v1.CloudBackupResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.listedBackups && message.listedBackups.length)) + message.listedBackups = []; + message.listedBackups.push($root.google.spanner.admin.database.v1.Backup.decode(reader, reader.uint32())); + break; + } + case 2: { + if (!(message.listedBackupOperations && message.listedBackupOperations.length)) + message.listedBackupOperations = []; + message.listedBackupOperations.push($root.google.longrunning.Operation.decode(reader, reader.uint32())); + break; + } + case 3: { + message.nextPageToken = reader.string(); + break; + } + case 4: { + message.backup = $root.google.spanner.admin.database.v1.Backup.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CloudBackupResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CloudBackupResponse} CloudBackupResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloudBackupResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CloudBackupResponse message. + * @function verify + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CloudBackupResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.listedBackups != null && message.hasOwnProperty("listedBackups")) { + if (!Array.isArray(message.listedBackups)) + return "listedBackups: array expected"; + for (var i = 0; i < message.listedBackups.length; ++i) { + var error = $root.google.spanner.admin.database.v1.Backup.verify(message.listedBackups[i]); + if (error) + return "listedBackups." + error; + } + } + if (message.listedBackupOperations != null && message.hasOwnProperty("listedBackupOperations")) { + if (!Array.isArray(message.listedBackupOperations)) + return "listedBackupOperations: array expected"; + for (var i = 0; i < message.listedBackupOperations.length; ++i) { + var error = $root.google.longrunning.Operation.verify(message.listedBackupOperations[i]); + if (error) + return "listedBackupOperations." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + if (message.backup != null && message.hasOwnProperty("backup")) { + var error = $root.google.spanner.admin.database.v1.Backup.verify(message.backup); + if (error) + return "backup." + error; + } + return null; + }; + + /** + * Creates a CloudBackupResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CloudBackupResponse} CloudBackupResponse + */ + CloudBackupResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CloudBackupResponse) + return object; + var message = new $root.google.spanner.executor.v1.CloudBackupResponse(); + if (object.listedBackups) { + if (!Array.isArray(object.listedBackups)) + throw TypeError(".google.spanner.executor.v1.CloudBackupResponse.listedBackups: array expected"); + message.listedBackups = []; + for (var i = 0; i < object.listedBackups.length; ++i) { + if (typeof object.listedBackups[i] !== "object") + throw TypeError(".google.spanner.executor.v1.CloudBackupResponse.listedBackups: object expected"); + message.listedBackups[i] = $root.google.spanner.admin.database.v1.Backup.fromObject(object.listedBackups[i]); + } + } + if (object.listedBackupOperations) { + if (!Array.isArray(object.listedBackupOperations)) + throw TypeError(".google.spanner.executor.v1.CloudBackupResponse.listedBackupOperations: array expected"); + message.listedBackupOperations = []; + for (var i = 0; i < object.listedBackupOperations.length; ++i) { + if (typeof object.listedBackupOperations[i] !== "object") + throw TypeError(".google.spanner.executor.v1.CloudBackupResponse.listedBackupOperations: object expected"); + message.listedBackupOperations[i] = $root.google.longrunning.Operation.fromObject(object.listedBackupOperations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.backup != null) { + if (typeof object.backup !== "object") + throw TypeError(".google.spanner.executor.v1.CloudBackupResponse.backup: object expected"); + message.backup = $root.google.spanner.admin.database.v1.Backup.fromObject(object.backup); + } + return message; + }; + + /** + * Creates a plain object from a CloudBackupResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {google.spanner.executor.v1.CloudBackupResponse} message CloudBackupResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CloudBackupResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.listedBackups = []; + object.listedBackupOperations = []; + } + if (options.defaults) { + object.nextPageToken = ""; + object.backup = null; + } + if (message.listedBackups && message.listedBackups.length) { + object.listedBackups = []; + for (var j = 0; j < message.listedBackups.length; ++j) + object.listedBackups[j] = $root.google.spanner.admin.database.v1.Backup.toObject(message.listedBackups[j], options); + } + if (message.listedBackupOperations && message.listedBackupOperations.length) { + object.listedBackupOperations = []; + for (var j = 0; j < message.listedBackupOperations.length; ++j) + object.listedBackupOperations[j] = $root.google.longrunning.Operation.toObject(message.listedBackupOperations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.backup != null && message.hasOwnProperty("backup")) + object.backup = $root.google.spanner.admin.database.v1.Backup.toObject(message.backup, options); + return object; + }; + + /** + * Converts this CloudBackupResponse to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @instance + * @returns {Object.} JSON object + */ + CloudBackupResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CloudBackupResponse + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CloudBackupResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CloudBackupResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CloudBackupResponse"; + }; + + return CloudBackupResponse; + })(); + + v1.OperationResponse = (function() { + + /** + * Properties of an OperationResponse. + * @memberof google.spanner.executor.v1 + * @interface IOperationResponse + * @property {Array.|null} [listedOperations] OperationResponse listedOperations + * @property {string|null} [nextPageToken] OperationResponse nextPageToken + * @property {google.longrunning.IOperation|null} [operation] OperationResponse operation + */ + + /** + * Constructs a new OperationResponse. + * @memberof google.spanner.executor.v1 + * @classdesc Represents an OperationResponse. + * @implements IOperationResponse + * @constructor + * @param {google.spanner.executor.v1.IOperationResponse=} [properties] Properties to set + */ + function OperationResponse(properties) { + this.listedOperations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OperationResponse listedOperations. + * @member {Array.} listedOperations + * @memberof google.spanner.executor.v1.OperationResponse + * @instance + */ + OperationResponse.prototype.listedOperations = $util.emptyArray; + + /** + * OperationResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.executor.v1.OperationResponse + * @instance + */ + OperationResponse.prototype.nextPageToken = ""; + + /** + * OperationResponse operation. + * @member {google.longrunning.IOperation|null|undefined} operation + * @memberof google.spanner.executor.v1.OperationResponse + * @instance + */ + OperationResponse.prototype.operation = null; + + /** + * Creates a new OperationResponse instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {google.spanner.executor.v1.IOperationResponse=} [properties] Properties to set + * @returns {google.spanner.executor.v1.OperationResponse} OperationResponse instance + */ + OperationResponse.create = function create(properties) { + return new OperationResponse(properties); + }; + + /** + * Encodes the specified OperationResponse message. Does not implicitly {@link google.spanner.executor.v1.OperationResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {google.spanner.executor.v1.IOperationResponse} message OperationResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OperationResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.listedOperations != null && message.listedOperations.length) + for (var i = 0; i < message.listedOperations.length; ++i) + $root.google.longrunning.Operation.encode(message.listedOperations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + if (message.operation != null && Object.hasOwnProperty.call(message, "operation")) + $root.google.longrunning.Operation.encode(message.operation, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified OperationResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.OperationResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {google.spanner.executor.v1.IOperationResponse} message OperationResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OperationResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an OperationResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.OperationResponse} OperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OperationResponse.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.spanner.executor.v1.OperationResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.listedOperations && message.listedOperations.length)) + message.listedOperations = []; + message.listedOperations.push($root.google.longrunning.Operation.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + case 3: { + message.operation = $root.google.longrunning.Operation.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an OperationResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.OperationResponse} OperationResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OperationResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an OperationResponse message. + * @function verify + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + OperationResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.listedOperations != null && message.hasOwnProperty("listedOperations")) { + if (!Array.isArray(message.listedOperations)) + return "listedOperations: array expected"; + for (var i = 0; i < message.listedOperations.length; ++i) { + var error = $root.google.longrunning.Operation.verify(message.listedOperations[i]); + if (error) + return "listedOperations." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + if (message.operation != null && message.hasOwnProperty("operation")) { + var error = $root.google.longrunning.Operation.verify(message.operation); + if (error) + return "operation." + error; + } + return null; + }; + + /** + * Creates an OperationResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.OperationResponse} OperationResponse + */ + OperationResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.OperationResponse) + return object; + var message = new $root.google.spanner.executor.v1.OperationResponse(); + if (object.listedOperations) { + if (!Array.isArray(object.listedOperations)) + throw TypeError(".google.spanner.executor.v1.OperationResponse.listedOperations: array expected"); + message.listedOperations = []; + for (var i = 0; i < object.listedOperations.length; ++i) { + if (typeof object.listedOperations[i] !== "object") + throw TypeError(".google.spanner.executor.v1.OperationResponse.listedOperations: object expected"); + message.listedOperations[i] = $root.google.longrunning.Operation.fromObject(object.listedOperations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.operation != null) { + if (typeof object.operation !== "object") + throw TypeError(".google.spanner.executor.v1.OperationResponse.operation: object expected"); + message.operation = $root.google.longrunning.Operation.fromObject(object.operation); + } + return message; + }; + + /** + * Creates a plain object from an OperationResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {google.spanner.executor.v1.OperationResponse} message OperationResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OperationResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.listedOperations = []; + if (options.defaults) { + object.nextPageToken = ""; + object.operation = null; + } + if (message.listedOperations && message.listedOperations.length) { + object.listedOperations = []; + for (var j = 0; j < message.listedOperations.length; ++j) + object.listedOperations[j] = $root.google.longrunning.Operation.toObject(message.listedOperations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.operation != null && message.hasOwnProperty("operation")) + object.operation = $root.google.longrunning.Operation.toObject(message.operation, options); + return object; + }; + + /** + * Converts this OperationResponse to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.OperationResponse + * @instance + * @returns {Object.} JSON object + */ + OperationResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OperationResponse + * @function getTypeUrl + * @memberof google.spanner.executor.v1.OperationResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OperationResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.OperationResponse"; + }; + + return OperationResponse; + })(); + + v1.CloudInstanceResponse = (function() { + + /** + * Properties of a CloudInstanceResponse. + * @memberof google.spanner.executor.v1 + * @interface ICloudInstanceResponse + * @property {Array.|null} [listedInstances] CloudInstanceResponse listedInstances + * @property {string|null} [nextPageToken] CloudInstanceResponse nextPageToken + * @property {google.spanner.admin.instance.v1.IInstance|null} [instance] CloudInstanceResponse instance + */ + + /** + * Constructs a new CloudInstanceResponse. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CloudInstanceResponse. + * @implements ICloudInstanceResponse + * @constructor + * @param {google.spanner.executor.v1.ICloudInstanceResponse=} [properties] Properties to set + */ + function CloudInstanceResponse(properties) { + this.listedInstances = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CloudInstanceResponse listedInstances. + * @member {Array.} listedInstances + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @instance + */ + CloudInstanceResponse.prototype.listedInstances = $util.emptyArray; + + /** + * CloudInstanceResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @instance + */ + CloudInstanceResponse.prototype.nextPageToken = ""; + + /** + * CloudInstanceResponse instance. + * @member {google.spanner.admin.instance.v1.IInstance|null|undefined} instance + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @instance + */ + CloudInstanceResponse.prototype.instance = null; + + /** + * Creates a new CloudInstanceResponse instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {google.spanner.executor.v1.ICloudInstanceResponse=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CloudInstanceResponse} CloudInstanceResponse instance + */ + CloudInstanceResponse.create = function create(properties) { + return new CloudInstanceResponse(properties); + }; + + /** + * Encodes the specified CloudInstanceResponse message. Does not implicitly {@link google.spanner.executor.v1.CloudInstanceResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {google.spanner.executor.v1.ICloudInstanceResponse} message CloudInstanceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloudInstanceResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.listedInstances != null && message.listedInstances.length) + for (var i = 0; i < message.listedInstances.length; ++i) + $root.google.spanner.admin.instance.v1.Instance.encode(message.listedInstances[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + if (message.instance != null && Object.hasOwnProperty.call(message, "instance")) + $root.google.spanner.admin.instance.v1.Instance.encode(message.instance, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CloudInstanceResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloudInstanceResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {google.spanner.executor.v1.ICloudInstanceResponse} message CloudInstanceResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloudInstanceResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CloudInstanceResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CloudInstanceResponse} CloudInstanceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloudInstanceResponse.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.spanner.executor.v1.CloudInstanceResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.listedInstances && message.listedInstances.length)) + message.listedInstances = []; + message.listedInstances.push($root.google.spanner.admin.instance.v1.Instance.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + case 3: { + message.instance = $root.google.spanner.admin.instance.v1.Instance.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CloudInstanceResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CloudInstanceResponse} CloudInstanceResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloudInstanceResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CloudInstanceResponse message. + * @function verify + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CloudInstanceResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.listedInstances != null && message.hasOwnProperty("listedInstances")) { + if (!Array.isArray(message.listedInstances)) + return "listedInstances: array expected"; + for (var i = 0; i < message.listedInstances.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.Instance.verify(message.listedInstances[i]); + if (error) + return "listedInstances." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + if (message.instance != null && message.hasOwnProperty("instance")) { + var error = $root.google.spanner.admin.instance.v1.Instance.verify(message.instance); + if (error) + return "instance." + error; + } + return null; + }; + + /** + * Creates a CloudInstanceResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CloudInstanceResponse} CloudInstanceResponse + */ + CloudInstanceResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CloudInstanceResponse) + return object; + var message = new $root.google.spanner.executor.v1.CloudInstanceResponse(); + if (object.listedInstances) { + if (!Array.isArray(object.listedInstances)) + throw TypeError(".google.spanner.executor.v1.CloudInstanceResponse.listedInstances: array expected"); + message.listedInstances = []; + for (var i = 0; i < object.listedInstances.length; ++i) { + if (typeof object.listedInstances[i] !== "object") + throw TypeError(".google.spanner.executor.v1.CloudInstanceResponse.listedInstances: object expected"); + message.listedInstances[i] = $root.google.spanner.admin.instance.v1.Instance.fromObject(object.listedInstances[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.instance != null) { + if (typeof object.instance !== "object") + throw TypeError(".google.spanner.executor.v1.CloudInstanceResponse.instance: object expected"); + message.instance = $root.google.spanner.admin.instance.v1.Instance.fromObject(object.instance); + } + return message; + }; + + /** + * Creates a plain object from a CloudInstanceResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {google.spanner.executor.v1.CloudInstanceResponse} message CloudInstanceResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CloudInstanceResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.listedInstances = []; + if (options.defaults) { + object.nextPageToken = ""; + object.instance = null; + } + if (message.listedInstances && message.listedInstances.length) { + object.listedInstances = []; + for (var j = 0; j < message.listedInstances.length; ++j) + object.listedInstances[j] = $root.google.spanner.admin.instance.v1.Instance.toObject(message.listedInstances[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.instance != null && message.hasOwnProperty("instance")) + object.instance = $root.google.spanner.admin.instance.v1.Instance.toObject(message.instance, options); + return object; + }; + + /** + * Converts this CloudInstanceResponse to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @instance + * @returns {Object.} JSON object + */ + CloudInstanceResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CloudInstanceResponse + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CloudInstanceResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CloudInstanceResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CloudInstanceResponse"; + }; + + return CloudInstanceResponse; + })(); + + v1.CloudInstanceConfigResponse = (function() { + + /** + * Properties of a CloudInstanceConfigResponse. + * @memberof google.spanner.executor.v1 + * @interface ICloudInstanceConfigResponse + * @property {Array.|null} [listedInstanceConfigs] CloudInstanceConfigResponse listedInstanceConfigs + * @property {string|null} [nextPageToken] CloudInstanceConfigResponse nextPageToken + * @property {google.spanner.admin.instance.v1.IInstanceConfig|null} [instanceConfig] CloudInstanceConfigResponse instanceConfig + */ + + /** + * Constructs a new CloudInstanceConfigResponse. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CloudInstanceConfigResponse. + * @implements ICloudInstanceConfigResponse + * @constructor + * @param {google.spanner.executor.v1.ICloudInstanceConfigResponse=} [properties] Properties to set + */ + function CloudInstanceConfigResponse(properties) { + this.listedInstanceConfigs = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CloudInstanceConfigResponse listedInstanceConfigs. + * @member {Array.} listedInstanceConfigs + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @instance + */ + CloudInstanceConfigResponse.prototype.listedInstanceConfigs = $util.emptyArray; + + /** + * CloudInstanceConfigResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @instance + */ + CloudInstanceConfigResponse.prototype.nextPageToken = ""; + + /** + * CloudInstanceConfigResponse instanceConfig. + * @member {google.spanner.admin.instance.v1.IInstanceConfig|null|undefined} instanceConfig + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @instance + */ + CloudInstanceConfigResponse.prototype.instanceConfig = null; + + /** + * Creates a new CloudInstanceConfigResponse instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {google.spanner.executor.v1.ICloudInstanceConfigResponse=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CloudInstanceConfigResponse} CloudInstanceConfigResponse instance + */ + CloudInstanceConfigResponse.create = function create(properties) { + return new CloudInstanceConfigResponse(properties); + }; + + /** + * Encodes the specified CloudInstanceConfigResponse message. Does not implicitly {@link google.spanner.executor.v1.CloudInstanceConfigResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {google.spanner.executor.v1.ICloudInstanceConfigResponse} message CloudInstanceConfigResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloudInstanceConfigResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.listedInstanceConfigs != null && message.listedInstanceConfigs.length) + for (var i = 0; i < message.listedInstanceConfigs.length; ++i) + $root.google.spanner.admin.instance.v1.InstanceConfig.encode(message.listedInstanceConfigs[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + if (message.instanceConfig != null && Object.hasOwnProperty.call(message, "instanceConfig")) + $root.google.spanner.admin.instance.v1.InstanceConfig.encode(message.instanceConfig, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CloudInstanceConfigResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloudInstanceConfigResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {google.spanner.executor.v1.ICloudInstanceConfigResponse} message CloudInstanceConfigResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloudInstanceConfigResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CloudInstanceConfigResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CloudInstanceConfigResponse} CloudInstanceConfigResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloudInstanceConfigResponse.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.spanner.executor.v1.CloudInstanceConfigResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.listedInstanceConfigs && message.listedInstanceConfigs.length)) + message.listedInstanceConfigs = []; + message.listedInstanceConfigs.push($root.google.spanner.admin.instance.v1.InstanceConfig.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + case 3: { + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CloudInstanceConfigResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CloudInstanceConfigResponse} CloudInstanceConfigResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloudInstanceConfigResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CloudInstanceConfigResponse message. + * @function verify + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CloudInstanceConfigResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.listedInstanceConfigs != null && message.hasOwnProperty("listedInstanceConfigs")) { + if (!Array.isArray(message.listedInstanceConfigs)) + return "listedInstanceConfigs: array expected"; + for (var i = 0; i < message.listedInstanceConfigs.length; ++i) { + var error = $root.google.spanner.admin.instance.v1.InstanceConfig.verify(message.listedInstanceConfigs[i]); + if (error) + return "listedInstanceConfigs." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) { + var error = $root.google.spanner.admin.instance.v1.InstanceConfig.verify(message.instanceConfig); + if (error) + return "instanceConfig." + error; + } + return null; + }; + + /** + * Creates a CloudInstanceConfigResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CloudInstanceConfigResponse} CloudInstanceConfigResponse + */ + CloudInstanceConfigResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CloudInstanceConfigResponse) + return object; + var message = new $root.google.spanner.executor.v1.CloudInstanceConfigResponse(); + if (object.listedInstanceConfigs) { + if (!Array.isArray(object.listedInstanceConfigs)) + throw TypeError(".google.spanner.executor.v1.CloudInstanceConfigResponse.listedInstanceConfigs: array expected"); + message.listedInstanceConfigs = []; + for (var i = 0; i < object.listedInstanceConfigs.length; ++i) { + if (typeof object.listedInstanceConfigs[i] !== "object") + throw TypeError(".google.spanner.executor.v1.CloudInstanceConfigResponse.listedInstanceConfigs: object expected"); + message.listedInstanceConfigs[i] = $root.google.spanner.admin.instance.v1.InstanceConfig.fromObject(object.listedInstanceConfigs[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.instanceConfig != null) { + if (typeof object.instanceConfig !== "object") + throw TypeError(".google.spanner.executor.v1.CloudInstanceConfigResponse.instanceConfig: object expected"); + message.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.fromObject(object.instanceConfig); + } + return message; + }; + + /** + * Creates a plain object from a CloudInstanceConfigResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {google.spanner.executor.v1.CloudInstanceConfigResponse} message CloudInstanceConfigResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CloudInstanceConfigResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.listedInstanceConfigs = []; + if (options.defaults) { + object.nextPageToken = ""; + object.instanceConfig = null; + } + if (message.listedInstanceConfigs && message.listedInstanceConfigs.length) { + object.listedInstanceConfigs = []; + for (var j = 0; j < message.listedInstanceConfigs.length; ++j) + object.listedInstanceConfigs[j] = $root.google.spanner.admin.instance.v1.InstanceConfig.toObject(message.listedInstanceConfigs[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.instanceConfig != null && message.hasOwnProperty("instanceConfig")) + object.instanceConfig = $root.google.spanner.admin.instance.v1.InstanceConfig.toObject(message.instanceConfig, options); + return object; + }; + + /** + * Converts this CloudInstanceConfigResponse to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @instance + * @returns {Object.} JSON object + */ + CloudInstanceConfigResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CloudInstanceConfigResponse + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CloudInstanceConfigResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CloudInstanceConfigResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CloudInstanceConfigResponse"; + }; + + return CloudInstanceConfigResponse; + })(); + + v1.CloudDatabaseResponse = (function() { + + /** + * Properties of a CloudDatabaseResponse. + * @memberof google.spanner.executor.v1 + * @interface ICloudDatabaseResponse + * @property {Array.|null} [listedDatabases] CloudDatabaseResponse listedDatabases + * @property {Array.|null} [listedDatabaseOperations] CloudDatabaseResponse listedDatabaseOperations + * @property {string|null} [nextPageToken] CloudDatabaseResponse nextPageToken + * @property {google.spanner.admin.database.v1.IDatabase|null} [database] CloudDatabaseResponse database + */ + + /** + * Constructs a new CloudDatabaseResponse. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a CloudDatabaseResponse. + * @implements ICloudDatabaseResponse + * @constructor + * @param {google.spanner.executor.v1.ICloudDatabaseResponse=} [properties] Properties to set + */ + function CloudDatabaseResponse(properties) { + this.listedDatabases = []; + this.listedDatabaseOperations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CloudDatabaseResponse listedDatabases. + * @member {Array.} listedDatabases + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @instance + */ + CloudDatabaseResponse.prototype.listedDatabases = $util.emptyArray; + + /** + * CloudDatabaseResponse listedDatabaseOperations. + * @member {Array.} listedDatabaseOperations + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @instance + */ + CloudDatabaseResponse.prototype.listedDatabaseOperations = $util.emptyArray; + + /** + * CloudDatabaseResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @instance + */ + CloudDatabaseResponse.prototype.nextPageToken = ""; + + /** + * CloudDatabaseResponse database. + * @member {google.spanner.admin.database.v1.IDatabase|null|undefined} database + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @instance + */ + CloudDatabaseResponse.prototype.database = null; + + /** + * Creates a new CloudDatabaseResponse instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {google.spanner.executor.v1.ICloudDatabaseResponse=} [properties] Properties to set + * @returns {google.spanner.executor.v1.CloudDatabaseResponse} CloudDatabaseResponse instance + */ + CloudDatabaseResponse.create = function create(properties) { + return new CloudDatabaseResponse(properties); + }; + + /** + * Encodes the specified CloudDatabaseResponse message. Does not implicitly {@link google.spanner.executor.v1.CloudDatabaseResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {google.spanner.executor.v1.ICloudDatabaseResponse} message CloudDatabaseResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloudDatabaseResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.listedDatabases != null && message.listedDatabases.length) + for (var i = 0; i < message.listedDatabases.length; ++i) + $root.google.spanner.admin.database.v1.Database.encode(message.listedDatabases[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.listedDatabaseOperations != null && message.listedDatabaseOperations.length) + for (var i = 0; i < message.listedDatabaseOperations.length; ++i) + $root.google.longrunning.Operation.encode(message.listedDatabaseOperations[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.nextPageToken); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + $root.google.spanner.admin.database.v1.Database.encode(message.database, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CloudDatabaseResponse message, length delimited. Does not implicitly {@link google.spanner.executor.v1.CloudDatabaseResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {google.spanner.executor.v1.ICloudDatabaseResponse} message CloudDatabaseResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CloudDatabaseResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CloudDatabaseResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.CloudDatabaseResponse} CloudDatabaseResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloudDatabaseResponse.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.spanner.executor.v1.CloudDatabaseResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.listedDatabases && message.listedDatabases.length)) + message.listedDatabases = []; + message.listedDatabases.push($root.google.spanner.admin.database.v1.Database.decode(reader, reader.uint32())); + break; + } + case 2: { + if (!(message.listedDatabaseOperations && message.listedDatabaseOperations.length)) + message.listedDatabaseOperations = []; + message.listedDatabaseOperations.push($root.google.longrunning.Operation.decode(reader, reader.uint32())); + break; + } + case 3: { + message.nextPageToken = reader.string(); + break; + } + case 4: { + message.database = $root.google.spanner.admin.database.v1.Database.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CloudDatabaseResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.CloudDatabaseResponse} CloudDatabaseResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CloudDatabaseResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CloudDatabaseResponse message. + * @function verify + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CloudDatabaseResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.listedDatabases != null && message.hasOwnProperty("listedDatabases")) { + if (!Array.isArray(message.listedDatabases)) + return "listedDatabases: array expected"; + for (var i = 0; i < message.listedDatabases.length; ++i) { + var error = $root.google.spanner.admin.database.v1.Database.verify(message.listedDatabases[i]); + if (error) + return "listedDatabases." + error; + } + } + if (message.listedDatabaseOperations != null && message.hasOwnProperty("listedDatabaseOperations")) { + if (!Array.isArray(message.listedDatabaseOperations)) + return "listedDatabaseOperations: array expected"; + for (var i = 0; i < message.listedDatabaseOperations.length; ++i) { + var error = $root.google.longrunning.Operation.verify(message.listedDatabaseOperations[i]); + if (error) + return "listedDatabaseOperations." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + if (message.database != null && message.hasOwnProperty("database")) { + var error = $root.google.spanner.admin.database.v1.Database.verify(message.database); + if (error) + return "database." + error; + } + return null; + }; + + /** + * Creates a CloudDatabaseResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.CloudDatabaseResponse} CloudDatabaseResponse + */ + CloudDatabaseResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.CloudDatabaseResponse) + return object; + var message = new $root.google.spanner.executor.v1.CloudDatabaseResponse(); + if (object.listedDatabases) { + if (!Array.isArray(object.listedDatabases)) + throw TypeError(".google.spanner.executor.v1.CloudDatabaseResponse.listedDatabases: array expected"); + message.listedDatabases = []; + for (var i = 0; i < object.listedDatabases.length; ++i) { + if (typeof object.listedDatabases[i] !== "object") + throw TypeError(".google.spanner.executor.v1.CloudDatabaseResponse.listedDatabases: object expected"); + message.listedDatabases[i] = $root.google.spanner.admin.database.v1.Database.fromObject(object.listedDatabases[i]); + } + } + if (object.listedDatabaseOperations) { + if (!Array.isArray(object.listedDatabaseOperations)) + throw TypeError(".google.spanner.executor.v1.CloudDatabaseResponse.listedDatabaseOperations: array expected"); + message.listedDatabaseOperations = []; + for (var i = 0; i < object.listedDatabaseOperations.length; ++i) { + if (typeof object.listedDatabaseOperations[i] !== "object") + throw TypeError(".google.spanner.executor.v1.CloudDatabaseResponse.listedDatabaseOperations: object expected"); + message.listedDatabaseOperations[i] = $root.google.longrunning.Operation.fromObject(object.listedDatabaseOperations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.database != null) { + if (typeof object.database !== "object") + throw TypeError(".google.spanner.executor.v1.CloudDatabaseResponse.database: object expected"); + message.database = $root.google.spanner.admin.database.v1.Database.fromObject(object.database); + } + return message; + }; + + /** + * Creates a plain object from a CloudDatabaseResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {google.spanner.executor.v1.CloudDatabaseResponse} message CloudDatabaseResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CloudDatabaseResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.listedDatabases = []; + object.listedDatabaseOperations = []; + } + if (options.defaults) { + object.nextPageToken = ""; + object.database = null; + } + if (message.listedDatabases && message.listedDatabases.length) { + object.listedDatabases = []; + for (var j = 0; j < message.listedDatabases.length; ++j) + object.listedDatabases[j] = $root.google.spanner.admin.database.v1.Database.toObject(message.listedDatabases[j], options); + } + if (message.listedDatabaseOperations && message.listedDatabaseOperations.length) { + object.listedDatabaseOperations = []; + for (var j = 0; j < message.listedDatabaseOperations.length; ++j) + object.listedDatabaseOperations[j] = $root.google.longrunning.Operation.toObject(message.listedDatabaseOperations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + if (message.database != null && message.hasOwnProperty("database")) + object.database = $root.google.spanner.admin.database.v1.Database.toObject(message.database, options); + return object; + }; + + /** + * Converts this CloudDatabaseResponse to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @instance + * @returns {Object.} JSON object + */ + CloudDatabaseResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CloudDatabaseResponse + * @function getTypeUrl + * @memberof google.spanner.executor.v1.CloudDatabaseResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CloudDatabaseResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.CloudDatabaseResponse"; + }; + + return CloudDatabaseResponse; + })(); + + v1.ReadResult = (function() { + + /** + * Properties of a ReadResult. + * @memberof google.spanner.executor.v1 + * @interface IReadResult + * @property {string|null} [table] ReadResult table + * @property {string|null} [index] ReadResult index + * @property {number|null} [requestIndex] ReadResult requestIndex + * @property {Array.|null} [row] ReadResult row + * @property {google.spanner.v1.IStructType|null} [rowType] ReadResult rowType + */ + + /** + * Constructs a new ReadResult. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ReadResult. + * @implements IReadResult + * @constructor + * @param {google.spanner.executor.v1.IReadResult=} [properties] Properties to set + */ + function ReadResult(properties) { + this.row = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadResult table. + * @member {string} table + * @memberof google.spanner.executor.v1.ReadResult + * @instance + */ + ReadResult.prototype.table = ""; + + /** + * ReadResult index. + * @member {string|null|undefined} index + * @memberof google.spanner.executor.v1.ReadResult + * @instance + */ + ReadResult.prototype.index = null; + + /** + * ReadResult requestIndex. + * @member {number|null|undefined} requestIndex + * @memberof google.spanner.executor.v1.ReadResult + * @instance + */ + ReadResult.prototype.requestIndex = null; + + /** + * ReadResult row. + * @member {Array.} row + * @memberof google.spanner.executor.v1.ReadResult + * @instance + */ + ReadResult.prototype.row = $util.emptyArray; + + /** + * ReadResult rowType. + * @member {google.spanner.v1.IStructType|null|undefined} rowType + * @memberof google.spanner.executor.v1.ReadResult + * @instance + */ + ReadResult.prototype.rowType = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReadResult.prototype, "_index", { + get: $util.oneOfGetter($oneOfFields = ["index"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReadResult.prototype, "_requestIndex", { + get: $util.oneOfGetter($oneOfFields = ["requestIndex"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReadResult.prototype, "_rowType", { + get: $util.oneOfGetter($oneOfFields = ["rowType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReadResult instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {google.spanner.executor.v1.IReadResult=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ReadResult} ReadResult instance + */ + ReadResult.create = function create(properties) { + return new ReadResult(properties); + }; + + /** + * Encodes the specified ReadResult message. Does not implicitly {@link google.spanner.executor.v1.ReadResult.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {google.spanner.executor.v1.IReadResult} message ReadResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadResult.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.table); + if (message.index != null && Object.hasOwnProperty.call(message, "index")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.index); + if (message.requestIndex != null && Object.hasOwnProperty.call(message, "requestIndex")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.requestIndex); + if (message.row != null && message.row.length) + for (var i = 0; i < message.row.length; ++i) + $root.google.spanner.executor.v1.ValueList.encode(message.row[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.rowType != null && Object.hasOwnProperty.call(message, "rowType")) + $root.google.spanner.v1.StructType.encode(message.rowType, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ReadResult message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ReadResult.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {google.spanner.executor.v1.IReadResult} message ReadResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadResult.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadResult message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ReadResult} ReadResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadResult.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.spanner.executor.v1.ReadResult(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.table = reader.string(); + break; + } + case 2: { + message.index = reader.string(); + break; + } + case 3: { + message.requestIndex = reader.int32(); + break; + } + case 4: { + if (!(message.row && message.row.length)) + message.row = []; + message.row.push($root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32())); + break; + } + case 5: { + message.rowType = $root.google.spanner.v1.StructType.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReadResult message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ReadResult} ReadResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadResult.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadResult message. + * @function verify + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadResult.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.index != null && message.hasOwnProperty("index")) { + properties._index = 1; + if (!$util.isString(message.index)) + return "index: string expected"; + } + if (message.requestIndex != null && message.hasOwnProperty("requestIndex")) { + properties._requestIndex = 1; + if (!$util.isInteger(message.requestIndex)) + return "requestIndex: integer expected"; + } + if (message.row != null && message.hasOwnProperty("row")) { + if (!Array.isArray(message.row)) + return "row: array expected"; + for (var i = 0; i < message.row.length; ++i) { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.row[i]); + if (error) + return "row." + error; + } + } + if (message.rowType != null && message.hasOwnProperty("rowType")) { + properties._rowType = 1; + { + var error = $root.google.spanner.v1.StructType.verify(message.rowType); + if (error) + return "rowType." + error; + } + } + return null; + }; + + /** + * Creates a ReadResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ReadResult} ReadResult + */ + ReadResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ReadResult) + return object; + var message = new $root.google.spanner.executor.v1.ReadResult(); + if (object.table != null) + message.table = String(object.table); + if (object.index != null) + message.index = String(object.index); + if (object.requestIndex != null) + message.requestIndex = object.requestIndex | 0; + if (object.row) { + if (!Array.isArray(object.row)) + throw TypeError(".google.spanner.executor.v1.ReadResult.row: array expected"); + message.row = []; + for (var i = 0; i < object.row.length; ++i) { + if (typeof object.row[i] !== "object") + throw TypeError(".google.spanner.executor.v1.ReadResult.row: object expected"); + message.row[i] = $root.google.spanner.executor.v1.ValueList.fromObject(object.row[i]); + } + } + if (object.rowType != null) { + if (typeof object.rowType !== "object") + throw TypeError(".google.spanner.executor.v1.ReadResult.rowType: object expected"); + message.rowType = $root.google.spanner.v1.StructType.fromObject(object.rowType); + } + return message; + }; + + /** + * Creates a plain object from a ReadResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {google.spanner.executor.v1.ReadResult} message ReadResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.row = []; + if (options.defaults) + object.table = ""; + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.index != null && message.hasOwnProperty("index")) { + object.index = message.index; + if (options.oneofs) + object._index = "index"; + } + if (message.requestIndex != null && message.hasOwnProperty("requestIndex")) { + object.requestIndex = message.requestIndex; + if (options.oneofs) + object._requestIndex = "requestIndex"; + } + if (message.row && message.row.length) { + object.row = []; + for (var j = 0; j < message.row.length; ++j) + object.row[j] = $root.google.spanner.executor.v1.ValueList.toObject(message.row[j], options); + } + if (message.rowType != null && message.hasOwnProperty("rowType")) { + object.rowType = $root.google.spanner.v1.StructType.toObject(message.rowType, options); + if (options.oneofs) + object._rowType = "rowType"; + } + return object; + }; + + /** + * Converts this ReadResult to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ReadResult + * @instance + * @returns {Object.} JSON object + */ + ReadResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadResult + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ReadResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ReadResult"; + }; + + return ReadResult; + })(); + + v1.QueryResult = (function() { + + /** + * Properties of a QueryResult. + * @memberof google.spanner.executor.v1 + * @interface IQueryResult + * @property {Array.|null} [row] QueryResult row + * @property {google.spanner.v1.IStructType|null} [rowType] QueryResult rowType + */ + + /** + * Constructs a new QueryResult. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a QueryResult. + * @implements IQueryResult + * @constructor + * @param {google.spanner.executor.v1.IQueryResult=} [properties] Properties to set + */ + function QueryResult(properties) { + this.row = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QueryResult row. + * @member {Array.} row + * @memberof google.spanner.executor.v1.QueryResult + * @instance + */ + QueryResult.prototype.row = $util.emptyArray; + + /** + * QueryResult rowType. + * @member {google.spanner.v1.IStructType|null|undefined} rowType + * @memberof google.spanner.executor.v1.QueryResult + * @instance + */ + QueryResult.prototype.rowType = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(QueryResult.prototype, "_rowType", { + get: $util.oneOfGetter($oneOfFields = ["rowType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new QueryResult instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {google.spanner.executor.v1.IQueryResult=} [properties] Properties to set + * @returns {google.spanner.executor.v1.QueryResult} QueryResult instance + */ + QueryResult.create = function create(properties) { + return new QueryResult(properties); + }; + + /** + * Encodes the specified QueryResult message. Does not implicitly {@link google.spanner.executor.v1.QueryResult.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {google.spanner.executor.v1.IQueryResult} message QueryResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryResult.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.row != null && message.row.length) + for (var i = 0; i < message.row.length; ++i) + $root.google.spanner.executor.v1.ValueList.encode(message.row[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.rowType != null && Object.hasOwnProperty.call(message, "rowType")) + $root.google.spanner.v1.StructType.encode(message.rowType, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified QueryResult message, length delimited. Does not implicitly {@link google.spanner.executor.v1.QueryResult.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {google.spanner.executor.v1.IQueryResult} message QueryResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryResult.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a QueryResult message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.QueryResult} QueryResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryResult.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.spanner.executor.v1.QueryResult(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.row && message.row.length)) + message.row = []; + message.row.push($root.google.spanner.executor.v1.ValueList.decode(reader, reader.uint32())); + break; + } + case 2: { + message.rowType = $root.google.spanner.v1.StructType.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a QueryResult message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.QueryResult} QueryResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryResult.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a QueryResult message. + * @function verify + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + QueryResult.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.row != null && message.hasOwnProperty("row")) { + if (!Array.isArray(message.row)) + return "row: array expected"; + for (var i = 0; i < message.row.length; ++i) { + var error = $root.google.spanner.executor.v1.ValueList.verify(message.row[i]); + if (error) + return "row." + error; + } + } + if (message.rowType != null && message.hasOwnProperty("rowType")) { + properties._rowType = 1; + { + var error = $root.google.spanner.v1.StructType.verify(message.rowType); + if (error) + return "rowType." + error; + } + } + return null; + }; + + /** + * Creates a QueryResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.QueryResult} QueryResult + */ + QueryResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.QueryResult) + return object; + var message = new $root.google.spanner.executor.v1.QueryResult(); + if (object.row) { + if (!Array.isArray(object.row)) + throw TypeError(".google.spanner.executor.v1.QueryResult.row: array expected"); + message.row = []; + for (var i = 0; i < object.row.length; ++i) { + if (typeof object.row[i] !== "object") + throw TypeError(".google.spanner.executor.v1.QueryResult.row: object expected"); + message.row[i] = $root.google.spanner.executor.v1.ValueList.fromObject(object.row[i]); + } + } + if (object.rowType != null) { + if (typeof object.rowType !== "object") + throw TypeError(".google.spanner.executor.v1.QueryResult.rowType: object expected"); + message.rowType = $root.google.spanner.v1.StructType.fromObject(object.rowType); + } + return message; + }; + + /** + * Creates a plain object from a QueryResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {google.spanner.executor.v1.QueryResult} message QueryResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.row = []; + if (message.row && message.row.length) { + object.row = []; + for (var j = 0; j < message.row.length; ++j) + object.row[j] = $root.google.spanner.executor.v1.ValueList.toObject(message.row[j], options); + } + if (message.rowType != null && message.hasOwnProperty("rowType")) { + object.rowType = $root.google.spanner.v1.StructType.toObject(message.rowType, options); + if (options.oneofs) + object._rowType = "rowType"; + } + return object; + }; + + /** + * Converts this QueryResult to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.QueryResult + * @instance + * @returns {Object.} JSON object + */ + QueryResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QueryResult + * @function getTypeUrl + * @memberof google.spanner.executor.v1.QueryResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.QueryResult"; + }; + + return QueryResult; + })(); + + v1.ChangeStreamRecord = (function() { + + /** + * Properties of a ChangeStreamRecord. + * @memberof google.spanner.executor.v1 + * @interface IChangeStreamRecord + * @property {google.spanner.executor.v1.IDataChangeRecord|null} [dataChange] ChangeStreamRecord dataChange + * @property {google.spanner.executor.v1.IChildPartitionsRecord|null} [childPartition] ChangeStreamRecord childPartition + * @property {google.spanner.executor.v1.IHeartbeatRecord|null} [heartbeat] ChangeStreamRecord heartbeat + */ + + /** + * Constructs a new ChangeStreamRecord. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ChangeStreamRecord. + * @implements IChangeStreamRecord + * @constructor + * @param {google.spanner.executor.v1.IChangeStreamRecord=} [properties] Properties to set + */ + function ChangeStreamRecord(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ChangeStreamRecord dataChange. + * @member {google.spanner.executor.v1.IDataChangeRecord|null|undefined} dataChange + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @instance + */ + ChangeStreamRecord.prototype.dataChange = null; + + /** + * ChangeStreamRecord childPartition. + * @member {google.spanner.executor.v1.IChildPartitionsRecord|null|undefined} childPartition + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @instance + */ + ChangeStreamRecord.prototype.childPartition = null; + + /** + * ChangeStreamRecord heartbeat. + * @member {google.spanner.executor.v1.IHeartbeatRecord|null|undefined} heartbeat + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @instance + */ + ChangeStreamRecord.prototype.heartbeat = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ChangeStreamRecord record. + * @member {"dataChange"|"childPartition"|"heartbeat"|undefined} record + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @instance + */ + Object.defineProperty(ChangeStreamRecord.prototype, "record", { + get: $util.oneOfGetter($oneOfFields = ["dataChange", "childPartition", "heartbeat"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ChangeStreamRecord instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {google.spanner.executor.v1.IChangeStreamRecord=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ChangeStreamRecord} ChangeStreamRecord instance + */ + ChangeStreamRecord.create = function create(properties) { + return new ChangeStreamRecord(properties); + }; + + /** + * Encodes the specified ChangeStreamRecord message. Does not implicitly {@link google.spanner.executor.v1.ChangeStreamRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {google.spanner.executor.v1.IChangeStreamRecord} message ChangeStreamRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChangeStreamRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataChange != null && Object.hasOwnProperty.call(message, "dataChange")) + $root.google.spanner.executor.v1.DataChangeRecord.encode(message.dataChange, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.childPartition != null && Object.hasOwnProperty.call(message, "childPartition")) + $root.google.spanner.executor.v1.ChildPartitionsRecord.encode(message.childPartition, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.heartbeat != null && Object.hasOwnProperty.call(message, "heartbeat")) + $root.google.spanner.executor.v1.HeartbeatRecord.encode(message.heartbeat, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ChangeStreamRecord message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ChangeStreamRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {google.spanner.executor.v1.IChangeStreamRecord} message ChangeStreamRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChangeStreamRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ChangeStreamRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ChangeStreamRecord} ChangeStreamRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChangeStreamRecord.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.spanner.executor.v1.ChangeStreamRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.dataChange = $root.google.spanner.executor.v1.DataChangeRecord.decode(reader, reader.uint32()); + break; + } + case 2: { + message.childPartition = $root.google.spanner.executor.v1.ChildPartitionsRecord.decode(reader, reader.uint32()); + break; + } + case 3: { + message.heartbeat = $root.google.spanner.executor.v1.HeartbeatRecord.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ChangeStreamRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ChangeStreamRecord} ChangeStreamRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChangeStreamRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ChangeStreamRecord message. + * @function verify + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ChangeStreamRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.dataChange != null && message.hasOwnProperty("dataChange")) { + properties.record = 1; + { + var error = $root.google.spanner.executor.v1.DataChangeRecord.verify(message.dataChange); + if (error) + return "dataChange." + error; + } + } + if (message.childPartition != null && message.hasOwnProperty("childPartition")) { + if (properties.record === 1) + return "record: multiple values"; + properties.record = 1; + { + var error = $root.google.spanner.executor.v1.ChildPartitionsRecord.verify(message.childPartition); + if (error) + return "childPartition." + error; + } + } + if (message.heartbeat != null && message.hasOwnProperty("heartbeat")) { + if (properties.record === 1) + return "record: multiple values"; + properties.record = 1; + { + var error = $root.google.spanner.executor.v1.HeartbeatRecord.verify(message.heartbeat); + if (error) + return "heartbeat." + error; + } + } + return null; + }; + + /** + * Creates a ChangeStreamRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ChangeStreamRecord} ChangeStreamRecord + */ + ChangeStreamRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ChangeStreamRecord) + return object; + var message = new $root.google.spanner.executor.v1.ChangeStreamRecord(); + if (object.dataChange != null) { + if (typeof object.dataChange !== "object") + throw TypeError(".google.spanner.executor.v1.ChangeStreamRecord.dataChange: object expected"); + message.dataChange = $root.google.spanner.executor.v1.DataChangeRecord.fromObject(object.dataChange); + } + if (object.childPartition != null) { + if (typeof object.childPartition !== "object") + throw TypeError(".google.spanner.executor.v1.ChangeStreamRecord.childPartition: object expected"); + message.childPartition = $root.google.spanner.executor.v1.ChildPartitionsRecord.fromObject(object.childPartition); + } + if (object.heartbeat != null) { + if (typeof object.heartbeat !== "object") + throw TypeError(".google.spanner.executor.v1.ChangeStreamRecord.heartbeat: object expected"); + message.heartbeat = $root.google.spanner.executor.v1.HeartbeatRecord.fromObject(object.heartbeat); + } + return message; + }; + + /** + * Creates a plain object from a ChangeStreamRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {google.spanner.executor.v1.ChangeStreamRecord} message ChangeStreamRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ChangeStreamRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.dataChange != null && message.hasOwnProperty("dataChange")) { + object.dataChange = $root.google.spanner.executor.v1.DataChangeRecord.toObject(message.dataChange, options); + if (options.oneofs) + object.record = "dataChange"; + } + if (message.childPartition != null && message.hasOwnProperty("childPartition")) { + object.childPartition = $root.google.spanner.executor.v1.ChildPartitionsRecord.toObject(message.childPartition, options); + if (options.oneofs) + object.record = "childPartition"; + } + if (message.heartbeat != null && message.hasOwnProperty("heartbeat")) { + object.heartbeat = $root.google.spanner.executor.v1.HeartbeatRecord.toObject(message.heartbeat, options); + if (options.oneofs) + object.record = "heartbeat"; + } + return object; + }; + + /** + * Converts this ChangeStreamRecord to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @instance + * @returns {Object.} JSON object + */ + ChangeStreamRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ChangeStreamRecord + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ChangeStreamRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ChangeStreamRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ChangeStreamRecord"; + }; + + return ChangeStreamRecord; + })(); + + v1.DataChangeRecord = (function() { + + /** + * Properties of a DataChangeRecord. + * @memberof google.spanner.executor.v1 + * @interface IDataChangeRecord + * @property {google.protobuf.ITimestamp|null} [commitTime] DataChangeRecord commitTime + * @property {string|null} [recordSequence] DataChangeRecord recordSequence + * @property {string|null} [transactionId] DataChangeRecord transactionId + * @property {boolean|null} [isLastRecord] DataChangeRecord isLastRecord + * @property {string|null} [table] DataChangeRecord table + * @property {Array.|null} [columnTypes] DataChangeRecord columnTypes + * @property {Array.|null} [mods] DataChangeRecord mods + * @property {string|null} [modType] DataChangeRecord modType + * @property {string|null} [valueCaptureType] DataChangeRecord valueCaptureType + * @property {number|Long|null} [recordCount] DataChangeRecord recordCount + * @property {number|Long|null} [partitionCount] DataChangeRecord partitionCount + * @property {string|null} [transactionTag] DataChangeRecord transactionTag + * @property {boolean|null} [isSystemTransaction] DataChangeRecord isSystemTransaction + */ + + /** + * Constructs a new DataChangeRecord. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a DataChangeRecord. + * @implements IDataChangeRecord + * @constructor + * @param {google.spanner.executor.v1.IDataChangeRecord=} [properties] Properties to set + */ + function DataChangeRecord(properties) { + this.columnTypes = []; + this.mods = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DataChangeRecord commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.commitTime = null; + + /** + * DataChangeRecord recordSequence. + * @member {string} recordSequence + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.recordSequence = ""; + + /** + * DataChangeRecord transactionId. + * @member {string} transactionId + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.transactionId = ""; + + /** + * DataChangeRecord isLastRecord. + * @member {boolean} isLastRecord + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.isLastRecord = false; + + /** + * DataChangeRecord table. + * @member {string} table + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.table = ""; + + /** + * DataChangeRecord columnTypes. + * @member {Array.} columnTypes + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.columnTypes = $util.emptyArray; + + /** + * DataChangeRecord mods. + * @member {Array.} mods + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.mods = $util.emptyArray; + + /** + * DataChangeRecord modType. + * @member {string} modType + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.modType = ""; + + /** + * DataChangeRecord valueCaptureType. + * @member {string} valueCaptureType + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.valueCaptureType = ""; + + /** + * DataChangeRecord recordCount. + * @member {number|Long} recordCount + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * DataChangeRecord partitionCount. + * @member {number|Long} partitionCount + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.partitionCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * DataChangeRecord transactionTag. + * @member {string} transactionTag + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.transactionTag = ""; + + /** + * DataChangeRecord isSystemTransaction. + * @member {boolean} isSystemTransaction + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.isSystemTransaction = false; + + /** + * Creates a new DataChangeRecord instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {google.spanner.executor.v1.IDataChangeRecord=} [properties] Properties to set + * @returns {google.spanner.executor.v1.DataChangeRecord} DataChangeRecord instance + */ + DataChangeRecord.create = function create(properties) { + return new DataChangeRecord(properties); + }; + + /** + * Encodes the specified DataChangeRecord message. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {google.spanner.executor.v1.IDataChangeRecord} message DataChangeRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DataChangeRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.commitTime != null && Object.hasOwnProperty.call(message, "commitTime")) + $root.google.protobuf.Timestamp.encode(message.commitTime, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.recordSequence != null && Object.hasOwnProperty.call(message, "recordSequence")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.recordSequence); + if (message.transactionId != null && Object.hasOwnProperty.call(message, "transactionId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.transactionId); + if (message.isLastRecord != null && Object.hasOwnProperty.call(message, "isLastRecord")) + writer.uint32(/* id 4, wireType 0 =*/32).bool(message.isLastRecord); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.table); + if (message.columnTypes != null && message.columnTypes.length) + for (var i = 0; i < message.columnTypes.length; ++i) + $root.google.spanner.executor.v1.DataChangeRecord.ColumnType.encode(message.columnTypes[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.mods != null && message.mods.length) + for (var i = 0; i < message.mods.length; ++i) + $root.google.spanner.executor.v1.DataChangeRecord.Mod.encode(message.mods[i], writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.modType != null && Object.hasOwnProperty.call(message, "modType")) + writer.uint32(/* id 8, wireType 2 =*/66).string(message.modType); + if (message.valueCaptureType != null && Object.hasOwnProperty.call(message, "valueCaptureType")) + writer.uint32(/* id 9, wireType 2 =*/74).string(message.valueCaptureType); + if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) + writer.uint32(/* id 10, wireType 0 =*/80).int64(message.recordCount); + if (message.partitionCount != null && Object.hasOwnProperty.call(message, "partitionCount")) + writer.uint32(/* id 11, wireType 0 =*/88).int64(message.partitionCount); + if (message.transactionTag != null && Object.hasOwnProperty.call(message, "transactionTag")) + writer.uint32(/* id 12, wireType 2 =*/98).string(message.transactionTag); + if (message.isSystemTransaction != null && Object.hasOwnProperty.call(message, "isSystemTransaction")) + writer.uint32(/* id 13, wireType 0 =*/104).bool(message.isSystemTransaction); + return writer; + }; + + /** + * Encodes the specified DataChangeRecord message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {google.spanner.executor.v1.IDataChangeRecord} message DataChangeRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DataChangeRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DataChangeRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.DataChangeRecord} DataChangeRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DataChangeRecord.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.spanner.executor.v1.DataChangeRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.commitTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.recordSequence = reader.string(); + break; + } + case 3: { + message.transactionId = reader.string(); + break; + } + case 4: { + message.isLastRecord = reader.bool(); + break; + } + case 5: { + message.table = reader.string(); + break; + } + case 6: { + if (!(message.columnTypes && message.columnTypes.length)) + message.columnTypes = []; + message.columnTypes.push($root.google.spanner.executor.v1.DataChangeRecord.ColumnType.decode(reader, reader.uint32())); + break; + } + case 7: { + if (!(message.mods && message.mods.length)) + message.mods = []; + message.mods.push($root.google.spanner.executor.v1.DataChangeRecord.Mod.decode(reader, reader.uint32())); + break; + } + case 8: { + message.modType = reader.string(); + break; + } + case 9: { + message.valueCaptureType = reader.string(); + break; + } + case 10: { + message.recordCount = reader.int64(); + break; + } + case 11: { + message.partitionCount = reader.int64(); + break; + } + case 12: { + message.transactionTag = reader.string(); + break; + } + case 13: { + message.isSystemTransaction = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DataChangeRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.DataChangeRecord} DataChangeRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DataChangeRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DataChangeRecord message. + * @function verify + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DataChangeRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.commitTime != null && message.hasOwnProperty("commitTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.commitTime); + if (error) + return "commitTime." + error; + } + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + if (!$util.isString(message.recordSequence)) + return "recordSequence: string expected"; + if (message.transactionId != null && message.hasOwnProperty("transactionId")) + if (!$util.isString(message.transactionId)) + return "transactionId: string expected"; + if (message.isLastRecord != null && message.hasOwnProperty("isLastRecord")) + if (typeof message.isLastRecord !== "boolean") + return "isLastRecord: boolean expected"; + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.columnTypes != null && message.hasOwnProperty("columnTypes")) { + if (!Array.isArray(message.columnTypes)) + return "columnTypes: array expected"; + for (var i = 0; i < message.columnTypes.length; ++i) { + var error = $root.google.spanner.executor.v1.DataChangeRecord.ColumnType.verify(message.columnTypes[i]); + if (error) + return "columnTypes." + error; + } + } + if (message.mods != null && message.hasOwnProperty("mods")) { + if (!Array.isArray(message.mods)) + return "mods: array expected"; + for (var i = 0; i < message.mods.length; ++i) { + var error = $root.google.spanner.executor.v1.DataChangeRecord.Mod.verify(message.mods[i]); + if (error) + return "mods." + error; + } + } + if (message.modType != null && message.hasOwnProperty("modType")) + if (!$util.isString(message.modType)) + return "modType: string expected"; + if (message.valueCaptureType != null && message.hasOwnProperty("valueCaptureType")) + if (!$util.isString(message.valueCaptureType)) + return "valueCaptureType: string expected"; + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) + return "recordCount: integer|Long expected"; + if (message.partitionCount != null && message.hasOwnProperty("partitionCount")) + if (!$util.isInteger(message.partitionCount) && !(message.partitionCount && $util.isInteger(message.partitionCount.low) && $util.isInteger(message.partitionCount.high))) + return "partitionCount: integer|Long expected"; + if (message.transactionTag != null && message.hasOwnProperty("transactionTag")) + if (!$util.isString(message.transactionTag)) + return "transactionTag: string expected"; + if (message.isSystemTransaction != null && message.hasOwnProperty("isSystemTransaction")) + if (typeof message.isSystemTransaction !== "boolean") + return "isSystemTransaction: boolean expected"; + return null; + }; + + /** + * Creates a DataChangeRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.DataChangeRecord} DataChangeRecord + */ + DataChangeRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.DataChangeRecord) + return object; + var message = new $root.google.spanner.executor.v1.DataChangeRecord(); + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.spanner.executor.v1.DataChangeRecord.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + } + if (object.recordSequence != null) + message.recordSequence = String(object.recordSequence); + if (object.transactionId != null) + message.transactionId = String(object.transactionId); + if (object.isLastRecord != null) + message.isLastRecord = Boolean(object.isLastRecord); + if (object.table != null) + message.table = String(object.table); + if (object.columnTypes) { + if (!Array.isArray(object.columnTypes)) + throw TypeError(".google.spanner.executor.v1.DataChangeRecord.columnTypes: array expected"); + message.columnTypes = []; + for (var i = 0; i < object.columnTypes.length; ++i) { + if (typeof object.columnTypes[i] !== "object") + throw TypeError(".google.spanner.executor.v1.DataChangeRecord.columnTypes: object expected"); + message.columnTypes[i] = $root.google.spanner.executor.v1.DataChangeRecord.ColumnType.fromObject(object.columnTypes[i]); + } + } + if (object.mods) { + if (!Array.isArray(object.mods)) + throw TypeError(".google.spanner.executor.v1.DataChangeRecord.mods: array expected"); + message.mods = []; + for (var i = 0; i < object.mods.length; ++i) { + if (typeof object.mods[i] !== "object") + throw TypeError(".google.spanner.executor.v1.DataChangeRecord.mods: object expected"); + message.mods[i] = $root.google.spanner.executor.v1.DataChangeRecord.Mod.fromObject(object.mods[i]); + } + } + if (object.modType != null) + message.modType = String(object.modType); + if (object.valueCaptureType != null) + message.valueCaptureType = String(object.valueCaptureType); + if (object.recordCount != null) + if ($util.Long) + (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; + else if (typeof object.recordCount === "string") + message.recordCount = parseInt(object.recordCount, 10); + else if (typeof object.recordCount === "number") + message.recordCount = object.recordCount; + else if (typeof object.recordCount === "object") + message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); + if (object.partitionCount != null) + if ($util.Long) + (message.partitionCount = $util.Long.fromValue(object.partitionCount)).unsigned = false; + else if (typeof object.partitionCount === "string") + message.partitionCount = parseInt(object.partitionCount, 10); + else if (typeof object.partitionCount === "number") + message.partitionCount = object.partitionCount; + else if (typeof object.partitionCount === "object") + message.partitionCount = new $util.LongBits(object.partitionCount.low >>> 0, object.partitionCount.high >>> 0).toNumber(); + if (object.transactionTag != null) + message.transactionTag = String(object.transactionTag); + if (object.isSystemTransaction != null) + message.isSystemTransaction = Boolean(object.isSystemTransaction); + return message; + }; + + /** + * Creates a plain object from a DataChangeRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {google.spanner.executor.v1.DataChangeRecord} message DataChangeRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DataChangeRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.columnTypes = []; + object.mods = []; + } + if (options.defaults) { + object.commitTime = null; + object.recordSequence = ""; + object.transactionId = ""; + object.isLastRecord = false; + object.table = ""; + object.modType = ""; + object.valueCaptureType = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.recordCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.partitionCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.partitionCount = options.longs === String ? "0" : 0; + object.transactionTag = ""; + object.isSystemTransaction = false; + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + object.recordSequence = message.recordSequence; + if (message.transactionId != null && message.hasOwnProperty("transactionId")) + object.transactionId = message.transactionId; + if (message.isLastRecord != null && message.hasOwnProperty("isLastRecord")) + object.isLastRecord = message.isLastRecord; + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.columnTypes && message.columnTypes.length) { + object.columnTypes = []; + for (var j = 0; j < message.columnTypes.length; ++j) + object.columnTypes[j] = $root.google.spanner.executor.v1.DataChangeRecord.ColumnType.toObject(message.columnTypes[j], options); + } + if (message.mods && message.mods.length) { + object.mods = []; + for (var j = 0; j < message.mods.length; ++j) + object.mods[j] = $root.google.spanner.executor.v1.DataChangeRecord.Mod.toObject(message.mods[j], options); + } + if (message.modType != null && message.hasOwnProperty("modType")) + object.modType = message.modType; + if (message.valueCaptureType != null && message.hasOwnProperty("valueCaptureType")) + object.valueCaptureType = message.valueCaptureType; + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (typeof message.recordCount === "number") + object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; + else + object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; + if (message.partitionCount != null && message.hasOwnProperty("partitionCount")) + if (typeof message.partitionCount === "number") + object.partitionCount = options.longs === String ? String(message.partitionCount) : message.partitionCount; + else + object.partitionCount = options.longs === String ? $util.Long.prototype.toString.call(message.partitionCount) : options.longs === Number ? new $util.LongBits(message.partitionCount.low >>> 0, message.partitionCount.high >>> 0).toNumber() : message.partitionCount; + if (message.transactionTag != null && message.hasOwnProperty("transactionTag")) + object.transactionTag = message.transactionTag; + if (message.isSystemTransaction != null && message.hasOwnProperty("isSystemTransaction")) + object.isSystemTransaction = message.isSystemTransaction; + return object; + }; + + /** + * Converts this DataChangeRecord to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.DataChangeRecord + * @instance + * @returns {Object.} JSON object + */ + DataChangeRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DataChangeRecord + * @function getTypeUrl + * @memberof google.spanner.executor.v1.DataChangeRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DataChangeRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.DataChangeRecord"; + }; + + DataChangeRecord.ColumnType = (function() { + + /** + * Properties of a ColumnType. + * @memberof google.spanner.executor.v1.DataChangeRecord + * @interface IColumnType + * @property {string|null} [name] ColumnType name + * @property {string|null} [type] ColumnType type + * @property {boolean|null} [isPrimaryKey] ColumnType isPrimaryKey + * @property {number|Long|null} [ordinalPosition] ColumnType ordinalPosition + */ + + /** + * Constructs a new ColumnType. + * @memberof google.spanner.executor.v1.DataChangeRecord + * @classdesc Represents a ColumnType. + * @implements IColumnType + * @constructor + * @param {google.spanner.executor.v1.DataChangeRecord.IColumnType=} [properties] Properties to set + */ + function ColumnType(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ColumnType name. + * @member {string} name + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @instance + */ + ColumnType.prototype.name = ""; + + /** + * ColumnType type. + * @member {string} type + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @instance + */ + ColumnType.prototype.type = ""; + + /** + * ColumnType isPrimaryKey. + * @member {boolean} isPrimaryKey + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @instance + */ + ColumnType.prototype.isPrimaryKey = false; + + /** + * ColumnType ordinalPosition. + * @member {number|Long} ordinalPosition + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @instance + */ + ColumnType.prototype.ordinalPosition = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new ColumnType instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {google.spanner.executor.v1.DataChangeRecord.IColumnType=} [properties] Properties to set + * @returns {google.spanner.executor.v1.DataChangeRecord.ColumnType} ColumnType instance + */ + ColumnType.create = function create(properties) { + return new ColumnType(properties); + }; + + /** + * Encodes the specified ColumnType message. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.ColumnType.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {google.spanner.executor.v1.DataChangeRecord.IColumnType} message ColumnType message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ColumnType.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.type); + if (message.isPrimaryKey != null && Object.hasOwnProperty.call(message, "isPrimaryKey")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.isPrimaryKey); + if (message.ordinalPosition != null && Object.hasOwnProperty.call(message, "ordinalPosition")) + writer.uint32(/* id 4, wireType 0 =*/32).int64(message.ordinalPosition); + return writer; + }; + + /** + * Encodes the specified ColumnType message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.ColumnType.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {google.spanner.executor.v1.DataChangeRecord.IColumnType} message ColumnType message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ColumnType.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ColumnType message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.DataChangeRecord.ColumnType} ColumnType + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ColumnType.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.spanner.executor.v1.DataChangeRecord.ColumnType(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.type = reader.string(); + break; + } + case 3: { + message.isPrimaryKey = reader.bool(); + break; + } + case 4: { + message.ordinalPosition = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ColumnType message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.DataChangeRecord.ColumnType} ColumnType + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ColumnType.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ColumnType message. + * @function verify + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ColumnType.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.isPrimaryKey != null && message.hasOwnProperty("isPrimaryKey")) + if (typeof message.isPrimaryKey !== "boolean") + return "isPrimaryKey: boolean expected"; + if (message.ordinalPosition != null && message.hasOwnProperty("ordinalPosition")) + if (!$util.isInteger(message.ordinalPosition) && !(message.ordinalPosition && $util.isInteger(message.ordinalPosition.low) && $util.isInteger(message.ordinalPosition.high))) + return "ordinalPosition: integer|Long expected"; + return null; + }; + + /** + * Creates a ColumnType message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.DataChangeRecord.ColumnType} ColumnType + */ + ColumnType.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.DataChangeRecord.ColumnType) + return object; + var message = new $root.google.spanner.executor.v1.DataChangeRecord.ColumnType(); + if (object.name != null) + message.name = String(object.name); + if (object.type != null) + message.type = String(object.type); + if (object.isPrimaryKey != null) + message.isPrimaryKey = Boolean(object.isPrimaryKey); + if (object.ordinalPosition != null) + if ($util.Long) + (message.ordinalPosition = $util.Long.fromValue(object.ordinalPosition)).unsigned = false; + else if (typeof object.ordinalPosition === "string") + message.ordinalPosition = parseInt(object.ordinalPosition, 10); + else if (typeof object.ordinalPosition === "number") + message.ordinalPosition = object.ordinalPosition; + else if (typeof object.ordinalPosition === "object") + message.ordinalPosition = new $util.LongBits(object.ordinalPosition.low >>> 0, object.ordinalPosition.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a ColumnType message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {google.spanner.executor.v1.DataChangeRecord.ColumnType} message ColumnType + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ColumnType.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.type = ""; + object.isPrimaryKey = false; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.ordinalPosition = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.ordinalPosition = options.longs === String ? "0" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.isPrimaryKey != null && message.hasOwnProperty("isPrimaryKey")) + object.isPrimaryKey = message.isPrimaryKey; + if (message.ordinalPosition != null && message.hasOwnProperty("ordinalPosition")) + if (typeof message.ordinalPosition === "number") + object.ordinalPosition = options.longs === String ? String(message.ordinalPosition) : message.ordinalPosition; + else + object.ordinalPosition = options.longs === String ? $util.Long.prototype.toString.call(message.ordinalPosition) : options.longs === Number ? new $util.LongBits(message.ordinalPosition.low >>> 0, message.ordinalPosition.high >>> 0).toNumber() : message.ordinalPosition; + return object; + }; + + /** + * Converts this ColumnType to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @instance + * @returns {Object.} JSON object + */ + ColumnType.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ColumnType + * @function getTypeUrl + * @memberof google.spanner.executor.v1.DataChangeRecord.ColumnType + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ColumnType.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.DataChangeRecord.ColumnType"; + }; + + return ColumnType; + })(); + + DataChangeRecord.Mod = (function() { + + /** + * Properties of a Mod. + * @memberof google.spanner.executor.v1.DataChangeRecord + * @interface IMod + * @property {string|null} [keys] Mod keys + * @property {string|null} [newValues] Mod newValues + * @property {string|null} [oldValues] Mod oldValues + */ + + /** + * Constructs a new Mod. + * @memberof google.spanner.executor.v1.DataChangeRecord + * @classdesc Represents a Mod. + * @implements IMod + * @constructor + * @param {google.spanner.executor.v1.DataChangeRecord.IMod=} [properties] Properties to set + */ + function Mod(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Mod keys. + * @member {string} keys + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @instance + */ + Mod.prototype.keys = ""; + + /** + * Mod newValues. + * @member {string} newValues + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @instance + */ + Mod.prototype.newValues = ""; + + /** + * Mod oldValues. + * @member {string} oldValues + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @instance + */ + Mod.prototype.oldValues = ""; + + /** + * Creates a new Mod instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {google.spanner.executor.v1.DataChangeRecord.IMod=} [properties] Properties to set + * @returns {google.spanner.executor.v1.DataChangeRecord.Mod} Mod instance + */ + Mod.create = function create(properties) { + return new Mod(properties); + }; + + /** + * Encodes the specified Mod message. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.Mod.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {google.spanner.executor.v1.DataChangeRecord.IMod} message Mod message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Mod.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.keys != null && Object.hasOwnProperty.call(message, "keys")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.keys); + if (message.newValues != null && Object.hasOwnProperty.call(message, "newValues")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.newValues); + if (message.oldValues != null && Object.hasOwnProperty.call(message, "oldValues")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.oldValues); + return writer; + }; + + /** + * Encodes the specified Mod message, length delimited. Does not implicitly {@link google.spanner.executor.v1.DataChangeRecord.Mod.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {google.spanner.executor.v1.DataChangeRecord.IMod} message Mod message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Mod.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Mod message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.DataChangeRecord.Mod} Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Mod.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.spanner.executor.v1.DataChangeRecord.Mod(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.keys = reader.string(); + break; + } + case 2: { + message.newValues = reader.string(); + break; + } + case 3: { + message.oldValues = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Mod message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.DataChangeRecord.Mod} Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Mod.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Mod message. + * @function verify + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Mod.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.keys != null && message.hasOwnProperty("keys")) + if (!$util.isString(message.keys)) + return "keys: string expected"; + if (message.newValues != null && message.hasOwnProperty("newValues")) + if (!$util.isString(message.newValues)) + return "newValues: string expected"; + if (message.oldValues != null && message.hasOwnProperty("oldValues")) + if (!$util.isString(message.oldValues)) + return "oldValues: string expected"; + return null; + }; + + /** + * Creates a Mod message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.DataChangeRecord.Mod} Mod + */ + Mod.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.DataChangeRecord.Mod) + return object; + var message = new $root.google.spanner.executor.v1.DataChangeRecord.Mod(); + if (object.keys != null) + message.keys = String(object.keys); + if (object.newValues != null) + message.newValues = String(object.newValues); + if (object.oldValues != null) + message.oldValues = String(object.oldValues); + return message; + }; + + /** + * Creates a plain object from a Mod message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {google.spanner.executor.v1.DataChangeRecord.Mod} message Mod + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Mod.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.keys = ""; + object.newValues = ""; + object.oldValues = ""; + } + if (message.keys != null && message.hasOwnProperty("keys")) + object.keys = message.keys; + if (message.newValues != null && message.hasOwnProperty("newValues")) + object.newValues = message.newValues; + if (message.oldValues != null && message.hasOwnProperty("oldValues")) + object.oldValues = message.oldValues; + return object; + }; + + /** + * Converts this Mod to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @instance + * @returns {Object.} JSON object + */ + Mod.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Mod + * @function getTypeUrl + * @memberof google.spanner.executor.v1.DataChangeRecord.Mod + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Mod.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.DataChangeRecord.Mod"; + }; + + return Mod; + })(); + + return DataChangeRecord; + })(); + + v1.ChildPartitionsRecord = (function() { + + /** + * Properties of a ChildPartitionsRecord. + * @memberof google.spanner.executor.v1 + * @interface IChildPartitionsRecord + * @property {google.protobuf.ITimestamp|null} [startTime] ChildPartitionsRecord startTime + * @property {string|null} [recordSequence] ChildPartitionsRecord recordSequence + * @property {Array.|null} [childPartitions] ChildPartitionsRecord childPartitions + */ + + /** + * Constructs a new ChildPartitionsRecord. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a ChildPartitionsRecord. + * @implements IChildPartitionsRecord + * @constructor + * @param {google.spanner.executor.v1.IChildPartitionsRecord=} [properties] Properties to set + */ + function ChildPartitionsRecord(properties) { + this.childPartitions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ChildPartitionsRecord startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @instance + */ + ChildPartitionsRecord.prototype.startTime = null; + + /** + * ChildPartitionsRecord recordSequence. + * @member {string} recordSequence + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @instance + */ + ChildPartitionsRecord.prototype.recordSequence = ""; + + /** + * ChildPartitionsRecord childPartitions. + * @member {Array.} childPartitions + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @instance + */ + ChildPartitionsRecord.prototype.childPartitions = $util.emptyArray; + + /** + * Creates a new ChildPartitionsRecord instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {google.spanner.executor.v1.IChildPartitionsRecord=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ChildPartitionsRecord} ChildPartitionsRecord instance + */ + ChildPartitionsRecord.create = function create(properties) { + return new ChildPartitionsRecord(properties); + }; + + /** + * Encodes the specified ChildPartitionsRecord message. Does not implicitly {@link google.spanner.executor.v1.ChildPartitionsRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {google.spanner.executor.v1.IChildPartitionsRecord} message ChildPartitionsRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChildPartitionsRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.recordSequence != null && Object.hasOwnProperty.call(message, "recordSequence")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.recordSequence); + if (message.childPartitions != null && message.childPartitions.length) + for (var i = 0; i < message.childPartitions.length; ++i) + $root.google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.encode(message.childPartitions[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ChildPartitionsRecord message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ChildPartitionsRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {google.spanner.executor.v1.IChildPartitionsRecord} message ChildPartitionsRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChildPartitionsRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ChildPartitionsRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ChildPartitionsRecord} ChildPartitionsRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChildPartitionsRecord.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.spanner.executor.v1.ChildPartitionsRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.recordSequence = reader.string(); + break; + } + case 3: { + if (!(message.childPartitions && message.childPartitions.length)) + message.childPartitions = []; + message.childPartitions.push($root.google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ChildPartitionsRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ChildPartitionsRecord} ChildPartitionsRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChildPartitionsRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ChildPartitionsRecord message. + * @function verify + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ChildPartitionsRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + if (!$util.isString(message.recordSequence)) + return "recordSequence: string expected"; + if (message.childPartitions != null && message.hasOwnProperty("childPartitions")) { + if (!Array.isArray(message.childPartitions)) + return "childPartitions: array expected"; + for (var i = 0; i < message.childPartitions.length; ++i) { + var error = $root.google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.verify(message.childPartitions[i]); + if (error) + return "childPartitions." + error; + } + } + return null; + }; + + /** + * Creates a ChildPartitionsRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ChildPartitionsRecord} ChildPartitionsRecord + */ + ChildPartitionsRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ChildPartitionsRecord) + return object; + var message = new $root.google.spanner.executor.v1.ChildPartitionsRecord(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.spanner.executor.v1.ChildPartitionsRecord.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.recordSequence != null) + message.recordSequence = String(object.recordSequence); + if (object.childPartitions) { + if (!Array.isArray(object.childPartitions)) + throw TypeError(".google.spanner.executor.v1.ChildPartitionsRecord.childPartitions: array expected"); + message.childPartitions = []; + for (var i = 0; i < object.childPartitions.length; ++i) { + if (typeof object.childPartitions[i] !== "object") + throw TypeError(".google.spanner.executor.v1.ChildPartitionsRecord.childPartitions: object expected"); + message.childPartitions[i] = $root.google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.fromObject(object.childPartitions[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ChildPartitionsRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {google.spanner.executor.v1.ChildPartitionsRecord} message ChildPartitionsRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ChildPartitionsRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.childPartitions = []; + if (options.defaults) { + object.startTime = null; + object.recordSequence = ""; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + object.recordSequence = message.recordSequence; + if (message.childPartitions && message.childPartitions.length) { + object.childPartitions = []; + for (var j = 0; j < message.childPartitions.length; ++j) + object.childPartitions[j] = $root.google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.toObject(message.childPartitions[j], options); + } + return object; + }; + + /** + * Converts this ChildPartitionsRecord to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @instance + * @returns {Object.} JSON object + */ + ChildPartitionsRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ChildPartitionsRecord + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ChildPartitionsRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ChildPartitionsRecord"; + }; + + ChildPartitionsRecord.ChildPartition = (function() { + + /** + * Properties of a ChildPartition. + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @interface IChildPartition + * @property {string|null} [token] ChildPartition token + * @property {Array.|null} [parentPartitionTokens] ChildPartition parentPartitionTokens + */ + + /** + * Constructs a new ChildPartition. + * @memberof google.spanner.executor.v1.ChildPartitionsRecord + * @classdesc Represents a ChildPartition. + * @implements IChildPartition + * @constructor + * @param {google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition=} [properties] Properties to set + */ + function ChildPartition(properties) { + this.parentPartitionTokens = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ChildPartition token. + * @member {string} token + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @instance + */ + ChildPartition.prototype.token = ""; + + /** + * ChildPartition parentPartitionTokens. + * @member {Array.} parentPartitionTokens + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @instance + */ + ChildPartition.prototype.parentPartitionTokens = $util.emptyArray; + + /** + * Creates a new ChildPartition instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition=} [properties] Properties to set + * @returns {google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition} ChildPartition instance + */ + ChildPartition.create = function create(properties) { + return new ChildPartition(properties); + }; + + /** + * Encodes the specified ChildPartition message. Does not implicitly {@link google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition} message ChildPartition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChildPartition.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.token != null && Object.hasOwnProperty.call(message, "token")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.token); + if (message.parentPartitionTokens != null && message.parentPartitionTokens.length) + for (var i = 0; i < message.parentPartitionTokens.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.parentPartitionTokens[i]); + return writer; + }; + + /** + * Encodes the specified ChildPartition message, length delimited. Does not implicitly {@link google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {google.spanner.executor.v1.ChildPartitionsRecord.IChildPartition} message ChildPartition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChildPartition.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ChildPartition message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition} ChildPartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChildPartition.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.spanner.executor.v1.ChildPartitionsRecord.ChildPartition(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.token = reader.string(); + break; + } + case 2: { + if (!(message.parentPartitionTokens && message.parentPartitionTokens.length)) + message.parentPartitionTokens = []; + message.parentPartitionTokens.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ChildPartition message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition} ChildPartition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChildPartition.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ChildPartition message. + * @function verify + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ChildPartition.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.token != null && message.hasOwnProperty("token")) + if (!$util.isString(message.token)) + return "token: string expected"; + if (message.parentPartitionTokens != null && message.hasOwnProperty("parentPartitionTokens")) { + if (!Array.isArray(message.parentPartitionTokens)) + return "parentPartitionTokens: array expected"; + for (var i = 0; i < message.parentPartitionTokens.length; ++i) + if (!$util.isString(message.parentPartitionTokens[i])) + return "parentPartitionTokens: string[] expected"; + } + return null; + }; + + /** + * Creates a ChildPartition message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition} ChildPartition + */ + ChildPartition.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition) + return object; + var message = new $root.google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition(); + if (object.token != null) + message.token = String(object.token); + if (object.parentPartitionTokens) { + if (!Array.isArray(object.parentPartitionTokens)) + throw TypeError(".google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition.parentPartitionTokens: array expected"); + message.parentPartitionTokens = []; + for (var i = 0; i < object.parentPartitionTokens.length; ++i) + message.parentPartitionTokens[i] = String(object.parentPartitionTokens[i]); + } + return message; + }; + + /** + * Creates a plain object from a ChildPartition message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition} message ChildPartition + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ChildPartition.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.parentPartitionTokens = []; + if (options.defaults) + object.token = ""; + if (message.token != null && message.hasOwnProperty("token")) + object.token = message.token; + if (message.parentPartitionTokens && message.parentPartitionTokens.length) { + object.parentPartitionTokens = []; + for (var j = 0; j < message.parentPartitionTokens.length; ++j) + object.parentPartitionTokens[j] = message.parentPartitionTokens[j]; + } + return object; + }; + + /** + * Converts this ChildPartition to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @instance + * @returns {Object.} JSON object + */ + ChildPartition.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ChildPartition + * @function getTypeUrl + * @memberof google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ChildPartition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.ChildPartitionsRecord.ChildPartition"; + }; + + return ChildPartition; + })(); + + return ChildPartitionsRecord; + })(); + + v1.HeartbeatRecord = (function() { + + /** + * Properties of a HeartbeatRecord. + * @memberof google.spanner.executor.v1 + * @interface IHeartbeatRecord + * @property {google.protobuf.ITimestamp|null} [heartbeatTime] HeartbeatRecord heartbeatTime + */ + + /** + * Constructs a new HeartbeatRecord. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a HeartbeatRecord. + * @implements IHeartbeatRecord + * @constructor + * @param {google.spanner.executor.v1.IHeartbeatRecord=} [properties] Properties to set + */ + function HeartbeatRecord(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * HeartbeatRecord heartbeatTime. + * @member {google.protobuf.ITimestamp|null|undefined} heartbeatTime + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @instance + */ + HeartbeatRecord.prototype.heartbeatTime = null; + + /** + * Creates a new HeartbeatRecord instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {google.spanner.executor.v1.IHeartbeatRecord=} [properties] Properties to set + * @returns {google.spanner.executor.v1.HeartbeatRecord} HeartbeatRecord instance + */ + HeartbeatRecord.create = function create(properties) { + return new HeartbeatRecord(properties); + }; + + /** + * Encodes the specified HeartbeatRecord message. Does not implicitly {@link google.spanner.executor.v1.HeartbeatRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {google.spanner.executor.v1.IHeartbeatRecord} message HeartbeatRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + HeartbeatRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.heartbeatTime != null && Object.hasOwnProperty.call(message, "heartbeatTime")) + $root.google.protobuf.Timestamp.encode(message.heartbeatTime, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified HeartbeatRecord message, length delimited. Does not implicitly {@link google.spanner.executor.v1.HeartbeatRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {google.spanner.executor.v1.IHeartbeatRecord} message HeartbeatRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + HeartbeatRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a HeartbeatRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.HeartbeatRecord} HeartbeatRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + HeartbeatRecord.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.spanner.executor.v1.HeartbeatRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.heartbeatTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a HeartbeatRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.HeartbeatRecord} HeartbeatRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + HeartbeatRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a HeartbeatRecord message. + * @function verify + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + HeartbeatRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.heartbeatTime != null && message.hasOwnProperty("heartbeatTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.heartbeatTime); + if (error) + return "heartbeatTime." + error; + } + return null; + }; + + /** + * Creates a HeartbeatRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.HeartbeatRecord} HeartbeatRecord + */ + HeartbeatRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.HeartbeatRecord) + return object; + var message = new $root.google.spanner.executor.v1.HeartbeatRecord(); + if (object.heartbeatTime != null) { + if (typeof object.heartbeatTime !== "object") + throw TypeError(".google.spanner.executor.v1.HeartbeatRecord.heartbeatTime: object expected"); + message.heartbeatTime = $root.google.protobuf.Timestamp.fromObject(object.heartbeatTime); + } + return message; + }; + + /** + * Creates a plain object from a HeartbeatRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {google.spanner.executor.v1.HeartbeatRecord} message HeartbeatRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + HeartbeatRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.heartbeatTime = null; + if (message.heartbeatTime != null && message.hasOwnProperty("heartbeatTime")) + object.heartbeatTime = $root.google.protobuf.Timestamp.toObject(message.heartbeatTime, options); + return object; + }; + + /** + * Converts this HeartbeatRecord to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @instance + * @returns {Object.} JSON object + */ + HeartbeatRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for HeartbeatRecord + * @function getTypeUrl + * @memberof google.spanner.executor.v1.HeartbeatRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + HeartbeatRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.HeartbeatRecord"; + }; + + return HeartbeatRecord; + })(); + + v1.SpannerOptions = (function() { + + /** + * Properties of a SpannerOptions. + * @memberof google.spanner.executor.v1 + * @interface ISpannerOptions + * @property {google.spanner.executor.v1.ISessionPoolOptions|null} [sessionPoolOptions] SpannerOptions sessionPoolOptions + */ + + /** + * Constructs a new SpannerOptions. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a SpannerOptions. + * @implements ISpannerOptions + * @constructor + * @param {google.spanner.executor.v1.ISpannerOptions=} [properties] Properties to set + */ + function SpannerOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SpannerOptions sessionPoolOptions. + * @member {google.spanner.executor.v1.ISessionPoolOptions|null|undefined} sessionPoolOptions + * @memberof google.spanner.executor.v1.SpannerOptions + * @instance + */ + SpannerOptions.prototype.sessionPoolOptions = null; + + /** + * Creates a new SpannerOptions instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {google.spanner.executor.v1.ISpannerOptions=} [properties] Properties to set + * @returns {google.spanner.executor.v1.SpannerOptions} SpannerOptions instance + */ + SpannerOptions.create = function create(properties) { + return new SpannerOptions(properties); + }; + + /** + * Encodes the specified SpannerOptions message. Does not implicitly {@link google.spanner.executor.v1.SpannerOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {google.spanner.executor.v1.ISpannerOptions} message SpannerOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.sessionPoolOptions != null && Object.hasOwnProperty.call(message, "sessionPoolOptions")) + $root.google.spanner.executor.v1.SessionPoolOptions.encode(message.sessionPoolOptions, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SpannerOptions message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SpannerOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {google.spanner.executor.v1.ISpannerOptions} message SpannerOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SpannerOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SpannerOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.SpannerOptions} SpannerOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerOptions.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.spanner.executor.v1.SpannerOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.sessionPoolOptions = $root.google.spanner.executor.v1.SessionPoolOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SpannerOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.SpannerOptions} SpannerOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SpannerOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SpannerOptions message. + * @function verify + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SpannerOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.sessionPoolOptions != null && message.hasOwnProperty("sessionPoolOptions")) { + var error = $root.google.spanner.executor.v1.SessionPoolOptions.verify(message.sessionPoolOptions); + if (error) + return "sessionPoolOptions." + error; + } + return null; + }; + + /** + * Creates a SpannerOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.SpannerOptions} SpannerOptions + */ + SpannerOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.SpannerOptions) + return object; + var message = new $root.google.spanner.executor.v1.SpannerOptions(); + if (object.sessionPoolOptions != null) { + if (typeof object.sessionPoolOptions !== "object") + throw TypeError(".google.spanner.executor.v1.SpannerOptions.sessionPoolOptions: object expected"); + message.sessionPoolOptions = $root.google.spanner.executor.v1.SessionPoolOptions.fromObject(object.sessionPoolOptions); + } + return message; + }; + + /** + * Creates a plain object from a SpannerOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {google.spanner.executor.v1.SpannerOptions} message SpannerOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SpannerOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.sessionPoolOptions = null; + if (message.sessionPoolOptions != null && message.hasOwnProperty("sessionPoolOptions")) + object.sessionPoolOptions = $root.google.spanner.executor.v1.SessionPoolOptions.toObject(message.sessionPoolOptions, options); + return object; + }; + + /** + * Converts this SpannerOptions to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.SpannerOptions + * @instance + * @returns {Object.} JSON object + */ + SpannerOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SpannerOptions + * @function getTypeUrl + * @memberof google.spanner.executor.v1.SpannerOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SpannerOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.SpannerOptions"; + }; + + return SpannerOptions; + })(); + + v1.SessionPoolOptions = (function() { + + /** + * Properties of a SessionPoolOptions. + * @memberof google.spanner.executor.v1 + * @interface ISessionPoolOptions + * @property {boolean|null} [useMultiplexed] SessionPoolOptions useMultiplexed + */ + + /** + * Constructs a new SessionPoolOptions. + * @memberof google.spanner.executor.v1 + * @classdesc Represents a SessionPoolOptions. + * @implements ISessionPoolOptions + * @constructor + * @param {google.spanner.executor.v1.ISessionPoolOptions=} [properties] Properties to set + */ + function SessionPoolOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SessionPoolOptions useMultiplexed. + * @member {boolean} useMultiplexed + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @instance + */ + SessionPoolOptions.prototype.useMultiplexed = false; + + /** + * Creates a new SessionPoolOptions instance using the specified properties. + * @function create + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {google.spanner.executor.v1.ISessionPoolOptions=} [properties] Properties to set + * @returns {google.spanner.executor.v1.SessionPoolOptions} SessionPoolOptions instance + */ + SessionPoolOptions.create = function create(properties) { + return new SessionPoolOptions(properties); + }; + + /** + * Encodes the specified SessionPoolOptions message. Does not implicitly {@link google.spanner.executor.v1.SessionPoolOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {google.spanner.executor.v1.ISessionPoolOptions} message SessionPoolOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SessionPoolOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.useMultiplexed != null && Object.hasOwnProperty.call(message, "useMultiplexed")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.useMultiplexed); + return writer; + }; + + /** + * Encodes the specified SessionPoolOptions message, length delimited. Does not implicitly {@link google.spanner.executor.v1.SessionPoolOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {google.spanner.executor.v1.ISessionPoolOptions} message SessionPoolOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SessionPoolOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SessionPoolOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.executor.v1.SessionPoolOptions} SessionPoolOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SessionPoolOptions.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.spanner.executor.v1.SessionPoolOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.useMultiplexed = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SessionPoolOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.executor.v1.SessionPoolOptions} SessionPoolOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SessionPoolOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SessionPoolOptions message. + * @function verify + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SessionPoolOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.useMultiplexed != null && message.hasOwnProperty("useMultiplexed")) + if (typeof message.useMultiplexed !== "boolean") + return "useMultiplexed: boolean expected"; + return null; + }; + + /** + * Creates a SessionPoolOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.executor.v1.SessionPoolOptions} SessionPoolOptions + */ + SessionPoolOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.executor.v1.SessionPoolOptions) + return object; + var message = new $root.google.spanner.executor.v1.SessionPoolOptions(); + if (object.useMultiplexed != null) + message.useMultiplexed = Boolean(object.useMultiplexed); + return message; + }; + + /** + * Creates a plain object from a SessionPoolOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {google.spanner.executor.v1.SessionPoolOptions} message SessionPoolOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SessionPoolOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.useMultiplexed = false; + if (message.useMultiplexed != null && message.hasOwnProperty("useMultiplexed")) + object.useMultiplexed = message.useMultiplexed; + return object; + }; + + /** + * Converts this SessionPoolOptions to JSON. + * @function toJSON + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @instance + * @returns {Object.} JSON object + */ + SessionPoolOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SessionPoolOptions + * @function getTypeUrl + * @memberof google.spanner.executor.v1.SessionPoolOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SessionPoolOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.executor.v1.SessionPoolOptions"; + }; + + return SessionPoolOptions; + })(); + + return v1; + })(); + + return executor; + })(); + + spanner.v1 = (function() { + + /** + * Namespace v1. + * @memberof google.spanner + * @namespace + */ + var v1 = {}; + + v1.Spanner = (function() { + + /** + * Constructs a new Spanner service. + * @memberof google.spanner.v1 + * @classdesc Represents a Spanner + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Spanner(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (Spanner.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Spanner; + + /** + * Creates new Spanner service using the specified rpc implementation. + * @function create + * @memberof google.spanner.v1.Spanner + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {Spanner} RPC service. Useful where requests and/or responses are streamed. + */ + Spanner.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.spanner.v1.Spanner|createSession}. + * @memberof google.spanner.v1.Spanner + * @typedef CreateSessionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.Session} [response] Session + */ + + /** + * Calls CreateSession. + * @function createSession + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.ICreateSessionRequest} request CreateSessionRequest message or plain object + * @param {google.spanner.v1.Spanner.CreateSessionCallback} callback Node-style callback called with the error, if any, and Session + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.createSession = function createSession(request, callback) { + return this.rpcCall(createSession, $root.google.spanner.v1.CreateSessionRequest, $root.google.spanner.v1.Session, request, callback); + }, "name", { value: "CreateSession" }); + + /** + * Calls CreateSession. + * @function createSession + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.ICreateSessionRequest} request CreateSessionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|batchCreateSessions}. + * @memberof google.spanner.v1.Spanner + * @typedef BatchCreateSessionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.BatchCreateSessionsResponse} [response] BatchCreateSessionsResponse + */ + + /** + * Calls BatchCreateSessions. + * @function batchCreateSessions + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IBatchCreateSessionsRequest} request BatchCreateSessionsRequest message or plain object + * @param {google.spanner.v1.Spanner.BatchCreateSessionsCallback} callback Node-style callback called with the error, if any, and BatchCreateSessionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.batchCreateSessions = function batchCreateSessions(request, callback) { + return this.rpcCall(batchCreateSessions, $root.google.spanner.v1.BatchCreateSessionsRequest, $root.google.spanner.v1.BatchCreateSessionsResponse, request, callback); + }, "name", { value: "BatchCreateSessions" }); + + /** + * Calls BatchCreateSessions. + * @function batchCreateSessions + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IBatchCreateSessionsRequest} request BatchCreateSessionsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|getSession}. + * @memberof google.spanner.v1.Spanner + * @typedef GetSessionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.Session} [response] Session + */ + + /** + * Calls GetSession. + * @function getSession + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IGetSessionRequest} request GetSessionRequest message or plain object + * @param {google.spanner.v1.Spanner.GetSessionCallback} callback Node-style callback called with the error, if any, and Session + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.getSession = function getSession(request, callback) { + return this.rpcCall(getSession, $root.google.spanner.v1.GetSessionRequest, $root.google.spanner.v1.Session, request, callback); + }, "name", { value: "GetSession" }); + + /** + * Calls GetSession. + * @function getSession + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IGetSessionRequest} request GetSessionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|listSessions}. + * @memberof google.spanner.v1.Spanner + * @typedef ListSessionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.ListSessionsResponse} [response] ListSessionsResponse + */ + + /** + * Calls ListSessions. + * @function listSessions + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IListSessionsRequest} request ListSessionsRequest message or plain object + * @param {google.spanner.v1.Spanner.ListSessionsCallback} callback Node-style callback called with the error, if any, and ListSessionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.listSessions = function listSessions(request, callback) { + return this.rpcCall(listSessions, $root.google.spanner.v1.ListSessionsRequest, $root.google.spanner.v1.ListSessionsResponse, request, callback); + }, "name", { value: "ListSessions" }); + + /** + * Calls ListSessions. + * @function listSessions + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IListSessionsRequest} request ListSessionsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|deleteSession}. + * @memberof google.spanner.v1.Spanner + * @typedef DeleteSessionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteSession. + * @function deleteSession + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IDeleteSessionRequest} request DeleteSessionRequest message or plain object + * @param {google.spanner.v1.Spanner.DeleteSessionCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.deleteSession = function deleteSession(request, callback) { + return this.rpcCall(deleteSession, $root.google.spanner.v1.DeleteSessionRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteSession" }); + + /** + * Calls DeleteSession. + * @function deleteSession + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IDeleteSessionRequest} request DeleteSessionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|executeSql}. + * @memberof google.spanner.v1.Spanner + * @typedef ExecuteSqlCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.ResultSet} [response] ResultSet + */ + + /** + * Calls ExecuteSql. + * @function executeSql + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IExecuteSqlRequest} request ExecuteSqlRequest message or plain object + * @param {google.spanner.v1.Spanner.ExecuteSqlCallback} callback Node-style callback called with the error, if any, and ResultSet + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.executeSql = function executeSql(request, callback) { + return this.rpcCall(executeSql, $root.google.spanner.v1.ExecuteSqlRequest, $root.google.spanner.v1.ResultSet, request, callback); + }, "name", { value: "ExecuteSql" }); + + /** + * Calls ExecuteSql. + * @function executeSql + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IExecuteSqlRequest} request ExecuteSqlRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|executeStreamingSql}. + * @memberof google.spanner.v1.Spanner + * @typedef ExecuteStreamingSqlCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.PartialResultSet} [response] PartialResultSet + */ + + /** + * Calls ExecuteStreamingSql. + * @function executeStreamingSql + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IExecuteSqlRequest} request ExecuteSqlRequest message or plain object + * @param {google.spanner.v1.Spanner.ExecuteStreamingSqlCallback} callback Node-style callback called with the error, if any, and PartialResultSet + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.executeStreamingSql = function executeStreamingSql(request, callback) { + return this.rpcCall(executeStreamingSql, $root.google.spanner.v1.ExecuteSqlRequest, $root.google.spanner.v1.PartialResultSet, request, callback); + }, "name", { value: "ExecuteStreamingSql" }); + + /** + * Calls ExecuteStreamingSql. + * @function executeStreamingSql + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IExecuteSqlRequest} request ExecuteSqlRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|executeBatchDml}. + * @memberof google.spanner.v1.Spanner + * @typedef ExecuteBatchDmlCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.ExecuteBatchDmlResponse} [response] ExecuteBatchDmlResponse + */ + + /** + * Calls ExecuteBatchDml. + * @function executeBatchDml + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IExecuteBatchDmlRequest} request ExecuteBatchDmlRequest message or plain object + * @param {google.spanner.v1.Spanner.ExecuteBatchDmlCallback} callback Node-style callback called with the error, if any, and ExecuteBatchDmlResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.executeBatchDml = function executeBatchDml(request, callback) { + return this.rpcCall(executeBatchDml, $root.google.spanner.v1.ExecuteBatchDmlRequest, $root.google.spanner.v1.ExecuteBatchDmlResponse, request, callback); + }, "name", { value: "ExecuteBatchDml" }); + + /** + * Calls ExecuteBatchDml. + * @function executeBatchDml + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IExecuteBatchDmlRequest} request ExecuteBatchDmlRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|read}. + * @memberof google.spanner.v1.Spanner + * @typedef ReadCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.ResultSet} [response] ResultSet + */ + + /** + * Calls Read. + * @function read + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IReadRequest} request ReadRequest message or plain object + * @param {google.spanner.v1.Spanner.ReadCallback} callback Node-style callback called with the error, if any, and ResultSet + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.read = function read(request, callback) { + return this.rpcCall(read, $root.google.spanner.v1.ReadRequest, $root.google.spanner.v1.ResultSet, request, callback); + }, "name", { value: "Read" }); + + /** + * Calls Read. + * @function read + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IReadRequest} request ReadRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|streamingRead}. + * @memberof google.spanner.v1.Spanner + * @typedef StreamingReadCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.PartialResultSet} [response] PartialResultSet + */ + + /** + * Calls StreamingRead. + * @function streamingRead + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IReadRequest} request ReadRequest message or plain object + * @param {google.spanner.v1.Spanner.StreamingReadCallback} callback Node-style callback called with the error, if any, and PartialResultSet + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.streamingRead = function streamingRead(request, callback) { + return this.rpcCall(streamingRead, $root.google.spanner.v1.ReadRequest, $root.google.spanner.v1.PartialResultSet, request, callback); + }, "name", { value: "StreamingRead" }); + + /** + * Calls StreamingRead. + * @function streamingRead + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IReadRequest} request ReadRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|beginTransaction}. + * @memberof google.spanner.v1.Spanner + * @typedef BeginTransactionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.Transaction} [response] Transaction + */ + + /** + * Calls BeginTransaction. + * @function beginTransaction + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object + * @param {google.spanner.v1.Spanner.BeginTransactionCallback} callback Node-style callback called with the error, if any, and Transaction + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.beginTransaction = function beginTransaction(request, callback) { + return this.rpcCall(beginTransaction, $root.google.spanner.v1.BeginTransactionRequest, $root.google.spanner.v1.Transaction, request, callback); + }, "name", { value: "BeginTransaction" }); + + /** + * Calls BeginTransaction. + * @function beginTransaction + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|commit}. + * @memberof google.spanner.v1.Spanner + * @typedef CommitCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.CommitResponse} [response] CommitResponse + */ + + /** + * Calls Commit. + * @function commit + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.ICommitRequest} request CommitRequest message or plain object + * @param {google.spanner.v1.Spanner.CommitCallback} callback Node-style callback called with the error, if any, and CommitResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.commit = function commit(request, callback) { + return this.rpcCall(commit, $root.google.spanner.v1.CommitRequest, $root.google.spanner.v1.CommitResponse, request, callback); + }, "name", { value: "Commit" }); + + /** + * Calls Commit. + * @function commit + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.ICommitRequest} request CommitRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|rollback}. + * @memberof google.spanner.v1.Spanner + * @typedef RollbackCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls Rollback. + * @function rollback + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IRollbackRequest} request RollbackRequest message or plain object + * @param {google.spanner.v1.Spanner.RollbackCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.rollback = function rollback(request, callback) { + return this.rpcCall(rollback, $root.google.spanner.v1.RollbackRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "Rollback" }); + + /** + * Calls Rollback. + * @function rollback + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IRollbackRequest} request RollbackRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|partitionQuery}. + * @memberof google.spanner.v1.Spanner + * @typedef PartitionQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.PartitionResponse} [response] PartitionResponse + */ + + /** + * Calls PartitionQuery. + * @function partitionQuery + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object + * @param {google.spanner.v1.Spanner.PartitionQueryCallback} callback Node-style callback called with the error, if any, and PartitionResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.partitionQuery = function partitionQuery(request, callback) { + return this.rpcCall(partitionQuery, $root.google.spanner.v1.PartitionQueryRequest, $root.google.spanner.v1.PartitionResponse, request, callback); + }, "name", { value: "PartitionQuery" }); + + /** + * Calls PartitionQuery. + * @function partitionQuery + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|partitionRead}. + * @memberof google.spanner.v1.Spanner + * @typedef PartitionReadCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.PartitionResponse} [response] PartitionResponse + */ + + /** + * Calls PartitionRead. + * @function partitionRead + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IPartitionReadRequest} request PartitionReadRequest message or plain object + * @param {google.spanner.v1.Spanner.PartitionReadCallback} callback Node-style callback called with the error, if any, and PartitionResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.partitionRead = function partitionRead(request, callback) { + return this.rpcCall(partitionRead, $root.google.spanner.v1.PartitionReadRequest, $root.google.spanner.v1.PartitionResponse, request, callback); + }, "name", { value: "PartitionRead" }); + + /** + * Calls PartitionRead. + * @function partitionRead + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IPartitionReadRequest} request PartitionReadRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.spanner.v1.Spanner|batchWrite}. + * @memberof google.spanner.v1.Spanner + * @typedef BatchWriteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.spanner.v1.BatchWriteResponse} [response] BatchWriteResponse + */ + + /** + * Calls BatchWrite. + * @function batchWrite + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IBatchWriteRequest} request BatchWriteRequest message or plain object + * @param {google.spanner.v1.Spanner.BatchWriteCallback} callback Node-style callback called with the error, if any, and BatchWriteResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Spanner.prototype.batchWrite = function batchWrite(request, callback) { + return this.rpcCall(batchWrite, $root.google.spanner.v1.BatchWriteRequest, $root.google.spanner.v1.BatchWriteResponse, request, callback); + }, "name", { value: "BatchWrite" }); + + /** + * Calls BatchWrite. + * @function batchWrite + * @memberof google.spanner.v1.Spanner + * @instance + * @param {google.spanner.v1.IBatchWriteRequest} request BatchWriteRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return Spanner; + })(); + + v1.CreateSessionRequest = (function() { + + /** + * Properties of a CreateSessionRequest. + * @memberof google.spanner.v1 + * @interface ICreateSessionRequest + * @property {string|null} [database] CreateSessionRequest database + * @property {google.spanner.v1.ISession|null} [session] CreateSessionRequest session + */ + + /** + * Constructs a new CreateSessionRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a CreateSessionRequest. + * @implements ICreateSessionRequest + * @constructor + * @param {google.spanner.v1.ICreateSessionRequest=} [properties] Properties to set + */ + function CreateSessionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateSessionRequest database. + * @member {string} database + * @memberof google.spanner.v1.CreateSessionRequest + * @instance + */ + CreateSessionRequest.prototype.database = ""; + + /** + * CreateSessionRequest session. + * @member {google.spanner.v1.ISession|null|undefined} session + * @memberof google.spanner.v1.CreateSessionRequest + * @instance + */ + CreateSessionRequest.prototype.session = null; + + /** + * Creates a new CreateSessionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {google.spanner.v1.ICreateSessionRequest=} [properties] Properties to set + * @returns {google.spanner.v1.CreateSessionRequest} CreateSessionRequest instance + */ + CreateSessionRequest.create = function create(properties) { + return new CreateSessionRequest(properties); + }; + + /** + * Encodes the specified CreateSessionRequest message. Does not implicitly {@link google.spanner.v1.CreateSessionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {google.spanner.v1.ICreateSessionRequest} message CreateSessionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateSessionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + $root.google.spanner.v1.Session.encode(message.session, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.CreateSessionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {google.spanner.v1.ICreateSessionRequest} message CreateSessionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateSessionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateSessionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.CreateSessionRequest} CreateSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateSessionRequest.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.spanner.v1.CreateSessionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + case 2: { + message.session = $root.google.spanner.v1.Session.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateSessionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.CreateSessionRequest} CreateSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateSessionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateSessionRequest message. + * @function verify + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateSessionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.session != null && message.hasOwnProperty("session")) { + var error = $root.google.spanner.v1.Session.verify(message.session); + if (error) + return "session." + error; + } + return null; + }; + + /** + * Creates a CreateSessionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.CreateSessionRequest} CreateSessionRequest + */ + CreateSessionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.CreateSessionRequest) + return object; + var message = new $root.google.spanner.v1.CreateSessionRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.session != null) { + if (typeof object.session !== "object") + throw TypeError(".google.spanner.v1.CreateSessionRequest.session: object expected"); + message.session = $root.google.spanner.v1.Session.fromObject(object.session); + } + return message; + }; + + /** + * Creates a plain object from a CreateSessionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {google.spanner.v1.CreateSessionRequest} message CreateSessionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateSessionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + object.session = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.session != null && message.hasOwnProperty("session")) + object.session = $root.google.spanner.v1.Session.toObject(message.session, options); + return object; + }; + + /** + * Converts this CreateSessionRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.CreateSessionRequest + * @instance + * @returns {Object.} JSON object + */ + CreateSessionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateSessionRequest + * @function getTypeUrl + * @memberof google.spanner.v1.CreateSessionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateSessionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.CreateSessionRequest"; + }; + + return CreateSessionRequest; + })(); + + v1.BatchCreateSessionsRequest = (function() { + + /** + * Properties of a BatchCreateSessionsRequest. + * @memberof google.spanner.v1 + * @interface IBatchCreateSessionsRequest + * @property {string|null} [database] BatchCreateSessionsRequest database + * @property {google.spanner.v1.ISession|null} [sessionTemplate] BatchCreateSessionsRequest sessionTemplate + * @property {number|null} [sessionCount] BatchCreateSessionsRequest sessionCount + */ + + /** + * Constructs a new BatchCreateSessionsRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a BatchCreateSessionsRequest. + * @implements IBatchCreateSessionsRequest + * @constructor + * @param {google.spanner.v1.IBatchCreateSessionsRequest=} [properties] Properties to set + */ + function BatchCreateSessionsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchCreateSessionsRequest database. + * @member {string} database + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @instance + */ + BatchCreateSessionsRequest.prototype.database = ""; + + /** + * BatchCreateSessionsRequest sessionTemplate. + * @member {google.spanner.v1.ISession|null|undefined} sessionTemplate + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @instance + */ + BatchCreateSessionsRequest.prototype.sessionTemplate = null; + + /** + * BatchCreateSessionsRequest sessionCount. + * @member {number} sessionCount + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @instance + */ + BatchCreateSessionsRequest.prototype.sessionCount = 0; + + /** + * Creates a new BatchCreateSessionsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {google.spanner.v1.IBatchCreateSessionsRequest=} [properties] Properties to set + * @returns {google.spanner.v1.BatchCreateSessionsRequest} BatchCreateSessionsRequest instance + */ + BatchCreateSessionsRequest.create = function create(properties) { + return new BatchCreateSessionsRequest(properties); + }; + + /** + * Encodes the specified BatchCreateSessionsRequest message. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {google.spanner.v1.IBatchCreateSessionsRequest} message BatchCreateSessionsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchCreateSessionsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + if (message.sessionTemplate != null && Object.hasOwnProperty.call(message, "sessionTemplate")) + $root.google.spanner.v1.Session.encode(message.sessionTemplate, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.sessionCount != null && Object.hasOwnProperty.call(message, "sessionCount")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.sessionCount); + return writer; + }; + + /** + * Encodes the specified BatchCreateSessionsRequest message, length delimited. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {google.spanner.v1.IBatchCreateSessionsRequest} message BatchCreateSessionsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchCreateSessionsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BatchCreateSessionsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.BatchCreateSessionsRequest} BatchCreateSessionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchCreateSessionsRequest.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.spanner.v1.BatchCreateSessionsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + case 2: { + message.sessionTemplate = $root.google.spanner.v1.Session.decode(reader, reader.uint32()); + break; + } + case 3: { + message.sessionCount = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BatchCreateSessionsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.BatchCreateSessionsRequest} BatchCreateSessionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchCreateSessionsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BatchCreateSessionsRequest message. + * @function verify + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BatchCreateSessionsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.sessionTemplate != null && message.hasOwnProperty("sessionTemplate")) { + var error = $root.google.spanner.v1.Session.verify(message.sessionTemplate); + if (error) + return "sessionTemplate." + error; + } + if (message.sessionCount != null && message.hasOwnProperty("sessionCount")) + if (!$util.isInteger(message.sessionCount)) + return "sessionCount: integer expected"; + return null; + }; + + /** + * Creates a BatchCreateSessionsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.BatchCreateSessionsRequest} BatchCreateSessionsRequest + */ + BatchCreateSessionsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.BatchCreateSessionsRequest) + return object; + var message = new $root.google.spanner.v1.BatchCreateSessionsRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.sessionTemplate != null) { + if (typeof object.sessionTemplate !== "object") + throw TypeError(".google.spanner.v1.BatchCreateSessionsRequest.sessionTemplate: object expected"); + message.sessionTemplate = $root.google.spanner.v1.Session.fromObject(object.sessionTemplate); + } + if (object.sessionCount != null) + message.sessionCount = object.sessionCount | 0; + return message; + }; + + /** + * Creates a plain object from a BatchCreateSessionsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {google.spanner.v1.BatchCreateSessionsRequest} message BatchCreateSessionsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchCreateSessionsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + object.sessionTemplate = null; + object.sessionCount = 0; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.sessionTemplate != null && message.hasOwnProperty("sessionTemplate")) + object.sessionTemplate = $root.google.spanner.v1.Session.toObject(message.sessionTemplate, options); + if (message.sessionCount != null && message.hasOwnProperty("sessionCount")) + object.sessionCount = message.sessionCount; + return object; + }; + + /** + * Converts this BatchCreateSessionsRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @instance + * @returns {Object.} JSON object + */ + BatchCreateSessionsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchCreateSessionsRequest + * @function getTypeUrl + * @memberof google.spanner.v1.BatchCreateSessionsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchCreateSessionsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.BatchCreateSessionsRequest"; + }; + + return BatchCreateSessionsRequest; + })(); + + v1.BatchCreateSessionsResponse = (function() { + + /** + * Properties of a BatchCreateSessionsResponse. + * @memberof google.spanner.v1 + * @interface IBatchCreateSessionsResponse + * @property {Array.|null} [session] BatchCreateSessionsResponse session + */ + + /** + * Constructs a new BatchCreateSessionsResponse. + * @memberof google.spanner.v1 + * @classdesc Represents a BatchCreateSessionsResponse. + * @implements IBatchCreateSessionsResponse + * @constructor + * @param {google.spanner.v1.IBatchCreateSessionsResponse=} [properties] Properties to set + */ + function BatchCreateSessionsResponse(properties) { + this.session = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchCreateSessionsResponse session. + * @member {Array.} session + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @instance + */ + BatchCreateSessionsResponse.prototype.session = $util.emptyArray; + + /** + * Creates a new BatchCreateSessionsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {google.spanner.v1.IBatchCreateSessionsResponse=} [properties] Properties to set + * @returns {google.spanner.v1.BatchCreateSessionsResponse} BatchCreateSessionsResponse instance + */ + BatchCreateSessionsResponse.create = function create(properties) { + return new BatchCreateSessionsResponse(properties); + }; + + /** + * Encodes the specified BatchCreateSessionsResponse message. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {google.spanner.v1.IBatchCreateSessionsResponse} message BatchCreateSessionsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchCreateSessionsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && message.session.length) + for (var i = 0; i < message.session.length; ++i) + $root.google.spanner.v1.Session.encode(message.session[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BatchCreateSessionsResponse message, length delimited. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {google.spanner.v1.IBatchCreateSessionsResponse} message BatchCreateSessionsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchCreateSessionsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BatchCreateSessionsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.BatchCreateSessionsResponse} BatchCreateSessionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchCreateSessionsResponse.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.spanner.v1.BatchCreateSessionsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.session && message.session.length)) + message.session = []; + message.session.push($root.google.spanner.v1.Session.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BatchCreateSessionsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.BatchCreateSessionsResponse} BatchCreateSessionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchCreateSessionsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BatchCreateSessionsResponse message. + * @function verify + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BatchCreateSessionsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) { + if (!Array.isArray(message.session)) + return "session: array expected"; + for (var i = 0; i < message.session.length; ++i) { + var error = $root.google.spanner.v1.Session.verify(message.session[i]); + if (error) + return "session." + error; + } + } + return null; + }; + + /** + * Creates a BatchCreateSessionsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.BatchCreateSessionsResponse} BatchCreateSessionsResponse + */ + BatchCreateSessionsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.BatchCreateSessionsResponse) + return object; + var message = new $root.google.spanner.v1.BatchCreateSessionsResponse(); + if (object.session) { + if (!Array.isArray(object.session)) + throw TypeError(".google.spanner.v1.BatchCreateSessionsResponse.session: array expected"); + message.session = []; + for (var i = 0; i < object.session.length; ++i) { + if (typeof object.session[i] !== "object") + throw TypeError(".google.spanner.v1.BatchCreateSessionsResponse.session: object expected"); + message.session[i] = $root.google.spanner.v1.Session.fromObject(object.session[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a BatchCreateSessionsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {google.spanner.v1.BatchCreateSessionsResponse} message BatchCreateSessionsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchCreateSessionsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.session = []; + if (message.session && message.session.length) { + object.session = []; + for (var j = 0; j < message.session.length; ++j) + object.session[j] = $root.google.spanner.v1.Session.toObject(message.session[j], options); + } + return object; + }; + + /** + * Converts this BatchCreateSessionsResponse to JSON. + * @function toJSON + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @instance + * @returns {Object.} JSON object + */ + BatchCreateSessionsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchCreateSessionsResponse + * @function getTypeUrl + * @memberof google.spanner.v1.BatchCreateSessionsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchCreateSessionsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.BatchCreateSessionsResponse"; + }; + + return BatchCreateSessionsResponse; + })(); + + v1.Session = (function() { + + /** + * Properties of a Session. + * @memberof google.spanner.v1 + * @interface ISession + * @property {string|null} [name] Session name + * @property {Object.|null} [labels] Session labels + * @property {google.protobuf.ITimestamp|null} [createTime] Session createTime + * @property {google.protobuf.ITimestamp|null} [approximateLastUseTime] Session approximateLastUseTime + * @property {string|null} [creatorRole] Session creatorRole + * @property {boolean|null} [multiplexed] Session multiplexed + */ + + /** + * Constructs a new Session. + * @memberof google.spanner.v1 + * @classdesc Represents a Session. + * @implements ISession + * @constructor + * @param {google.spanner.v1.ISession=} [properties] Properties to set + */ + function Session(properties) { + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Session name. + * @member {string} name + * @memberof google.spanner.v1.Session + * @instance + */ + Session.prototype.name = ""; + + /** + * Session labels. + * @member {Object.} labels + * @memberof google.spanner.v1.Session + * @instance + */ + Session.prototype.labels = $util.emptyObject; + + /** + * Session createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.spanner.v1.Session + * @instance + */ + Session.prototype.createTime = null; + + /** + * Session approximateLastUseTime. + * @member {google.protobuf.ITimestamp|null|undefined} approximateLastUseTime + * @memberof google.spanner.v1.Session + * @instance + */ + Session.prototype.approximateLastUseTime = null; + + /** + * Session creatorRole. + * @member {string} creatorRole + * @memberof google.spanner.v1.Session + * @instance + */ + Session.prototype.creatorRole = ""; + + /** + * Session multiplexed. + * @member {boolean} multiplexed + * @memberof google.spanner.v1.Session + * @instance + */ + Session.prototype.multiplexed = false; + + /** + * Creates a new Session instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Session + * @static + * @param {google.spanner.v1.ISession=} [properties] Properties to set + * @returns {google.spanner.v1.Session} Session instance + */ + Session.create = function create(properties) { + return new Session(properties); + }; + + /** + * Encodes the specified Session message. Does not implicitly {@link google.spanner.v1.Session.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Session + * @static + * @param {google.spanner.v1.ISession} message Session message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Session.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.labels != null && Object.hasOwnProperty.call(message, "labels")) + for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); + if (message.createTime != null && Object.hasOwnProperty.call(message, "createTime")) + $root.google.protobuf.Timestamp.encode(message.createTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.approximateLastUseTime != null && Object.hasOwnProperty.call(message, "approximateLastUseTime")) + $root.google.protobuf.Timestamp.encode(message.approximateLastUseTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.creatorRole != null && Object.hasOwnProperty.call(message, "creatorRole")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.creatorRole); + if (message.multiplexed != null && Object.hasOwnProperty.call(message, "multiplexed")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.multiplexed); + return writer; + }; + + /** + * Encodes the specified Session message, length delimited. Does not implicitly {@link google.spanner.v1.Session.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Session + * @static + * @param {google.spanner.v1.ISession} message Session message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Session.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Session message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Session + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Session} Session + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Session.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.spanner.v1.Session(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + if (message.labels === $util.emptyObject) + message.labels = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.labels[key] = value; + break; + } + case 3: { + message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.approximateLastUseTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 5: { + message.creatorRole = reader.string(); + break; + } + case 6: { + message.multiplexed = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Session message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Session + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Session} Session + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Session.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Session message. + * @function verify + * @memberof google.spanner.v1.Session + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Session.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.labels != null && message.hasOwnProperty("labels")) { + if (!$util.isObject(message.labels)) + return "labels: object expected"; + var key = Object.keys(message.labels); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.labels[key[i]])) + return "labels: string{k:string} expected"; + } + if (message.createTime != null && message.hasOwnProperty("createTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.createTime); + if (error) + return "createTime." + error; + } + if (message.approximateLastUseTime != null && message.hasOwnProperty("approximateLastUseTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.approximateLastUseTime); + if (error) + return "approximateLastUseTime." + error; + } + if (message.creatorRole != null && message.hasOwnProperty("creatorRole")) + if (!$util.isString(message.creatorRole)) + return "creatorRole: string expected"; + if (message.multiplexed != null && message.hasOwnProperty("multiplexed")) + if (typeof message.multiplexed !== "boolean") + return "multiplexed: boolean expected"; + return null; + }; + + /** + * Creates a Session message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Session + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Session} Session + */ + Session.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Session) + return object; + var message = new $root.google.spanner.v1.Session(); + if (object.name != null) + message.name = String(object.name); + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.spanner.v1.Session.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.spanner.v1.Session.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.approximateLastUseTime != null) { + if (typeof object.approximateLastUseTime !== "object") + throw TypeError(".google.spanner.v1.Session.approximateLastUseTime: object expected"); + message.approximateLastUseTime = $root.google.protobuf.Timestamp.fromObject(object.approximateLastUseTime); + } + if (object.creatorRole != null) + message.creatorRole = String(object.creatorRole); + if (object.multiplexed != null) + message.multiplexed = Boolean(object.multiplexed); + return message; + }; + + /** + * Creates a plain object from a Session message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Session + * @static + * @param {google.spanner.v1.Session} message Session + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Session.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.name = ""; + object.createTime = null; + object.approximateLastUseTime = null; + object.creatorRole = ""; + object.multiplexed = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.approximateLastUseTime != null && message.hasOwnProperty("approximateLastUseTime")) + object.approximateLastUseTime = $root.google.protobuf.Timestamp.toObject(message.approximateLastUseTime, options); + if (message.creatorRole != null && message.hasOwnProperty("creatorRole")) + object.creatorRole = message.creatorRole; + if (message.multiplexed != null && message.hasOwnProperty("multiplexed")) + object.multiplexed = message.multiplexed; + return object; + }; + + /** + * Converts this Session to JSON. + * @function toJSON + * @memberof google.spanner.v1.Session + * @instance + * @returns {Object.} JSON object + */ + Session.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Session + * @function getTypeUrl + * @memberof google.spanner.v1.Session + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Session.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Session"; + }; + + return Session; + })(); + + v1.GetSessionRequest = (function() { + + /** + * Properties of a GetSessionRequest. + * @memberof google.spanner.v1 + * @interface IGetSessionRequest + * @property {string|null} [name] GetSessionRequest name + */ + + /** + * Constructs a new GetSessionRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a GetSessionRequest. + * @implements IGetSessionRequest + * @constructor + * @param {google.spanner.v1.IGetSessionRequest=} [properties] Properties to set + */ + function GetSessionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetSessionRequest name. + * @member {string} name + * @memberof google.spanner.v1.GetSessionRequest + * @instance + */ + GetSessionRequest.prototype.name = ""; + + /** + * Creates a new GetSessionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {google.spanner.v1.IGetSessionRequest=} [properties] Properties to set + * @returns {google.spanner.v1.GetSessionRequest} GetSessionRequest instance + */ + GetSessionRequest.create = function create(properties) { + return new GetSessionRequest(properties); + }; + + /** + * Encodes the specified GetSessionRequest message. Does not implicitly {@link google.spanner.v1.GetSessionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {google.spanner.v1.IGetSessionRequest} message GetSessionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetSessionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.GetSessionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {google.spanner.v1.IGetSessionRequest} message GetSessionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetSessionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetSessionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.GetSessionRequest} GetSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetSessionRequest.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.spanner.v1.GetSessionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetSessionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.GetSessionRequest} GetSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetSessionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetSessionRequest message. + * @function verify + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetSessionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetSessionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.GetSessionRequest} GetSessionRequest + */ + GetSessionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.GetSessionRequest) + return object; + var message = new $root.google.spanner.v1.GetSessionRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetSessionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {google.spanner.v1.GetSessionRequest} message GetSessionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetSessionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetSessionRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.GetSessionRequest + * @instance + * @returns {Object.} JSON object + */ + GetSessionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetSessionRequest + * @function getTypeUrl + * @memberof google.spanner.v1.GetSessionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetSessionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.GetSessionRequest"; + }; + + return GetSessionRequest; + })(); + + v1.ListSessionsRequest = (function() { + + /** + * Properties of a ListSessionsRequest. + * @memberof google.spanner.v1 + * @interface IListSessionsRequest + * @property {string|null} [database] ListSessionsRequest database + * @property {number|null} [pageSize] ListSessionsRequest pageSize + * @property {string|null} [pageToken] ListSessionsRequest pageToken + * @property {string|null} [filter] ListSessionsRequest filter + */ + + /** + * Constructs a new ListSessionsRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a ListSessionsRequest. + * @implements IListSessionsRequest + * @constructor + * @param {google.spanner.v1.IListSessionsRequest=} [properties] Properties to set + */ + function ListSessionsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListSessionsRequest database. + * @member {string} database + * @memberof google.spanner.v1.ListSessionsRequest + * @instance + */ + ListSessionsRequest.prototype.database = ""; + + /** + * ListSessionsRequest pageSize. + * @member {number} pageSize + * @memberof google.spanner.v1.ListSessionsRequest + * @instance + */ + ListSessionsRequest.prototype.pageSize = 0; + + /** + * ListSessionsRequest pageToken. + * @member {string} pageToken + * @memberof google.spanner.v1.ListSessionsRequest + * @instance + */ + ListSessionsRequest.prototype.pageToken = ""; + + /** + * ListSessionsRequest filter. + * @member {string} filter + * @memberof google.spanner.v1.ListSessionsRequest + * @instance + */ + ListSessionsRequest.prototype.filter = ""; + + /** + * Creates a new ListSessionsRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {google.spanner.v1.IListSessionsRequest=} [properties] Properties to set + * @returns {google.spanner.v1.ListSessionsRequest} ListSessionsRequest instance + */ + ListSessionsRequest.create = function create(properties) { + return new ListSessionsRequest(properties); + }; + + /** + * Encodes the specified ListSessionsRequest message. Does not implicitly {@link google.spanner.v1.ListSessionsRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {google.spanner.v1.IListSessionsRequest} message ListSessionsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSessionsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.database != null && Object.hasOwnProperty.call(message, "database")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.database); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.filter); + return writer; + }; + + /** + * Encodes the specified ListSessionsRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ListSessionsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {google.spanner.v1.IListSessionsRequest} message ListSessionsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSessionsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListSessionsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ListSessionsRequest} ListSessionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSessionsRequest.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.spanner.v1.ListSessionsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.database = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + case 4: { + message.filter = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListSessionsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ListSessionsRequest} ListSessionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSessionsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListSessionsRequest message. + * @function verify + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListSessionsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.database != null && message.hasOwnProperty("database")) + if (!$util.isString(message.database)) + return "database: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + return null; + }; + + /** + * Creates a ListSessionsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ListSessionsRequest} ListSessionsRequest + */ + ListSessionsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ListSessionsRequest) + return object; + var message = new $root.google.spanner.v1.ListSessionsRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.filter != null) + message.filter = String(object.filter); + return message; + }; + + /** + * Creates a plain object from a ListSessionsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {google.spanner.v1.ListSessionsRequest} message ListSessionsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListSessionsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + object.pageSize = 0; + object.pageToken = ""; + object.filter = ""; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + return object; + }; + + /** + * Converts this ListSessionsRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.ListSessionsRequest + * @instance + * @returns {Object.} JSON object + */ + ListSessionsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListSessionsRequest + * @function getTypeUrl + * @memberof google.spanner.v1.ListSessionsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListSessionsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ListSessionsRequest"; + }; + + return ListSessionsRequest; + })(); + + v1.ListSessionsResponse = (function() { + + /** + * Properties of a ListSessionsResponse. + * @memberof google.spanner.v1 + * @interface IListSessionsResponse + * @property {Array.|null} [sessions] ListSessionsResponse sessions + * @property {string|null} [nextPageToken] ListSessionsResponse nextPageToken + */ + + /** + * Constructs a new ListSessionsResponse. + * @memberof google.spanner.v1 + * @classdesc Represents a ListSessionsResponse. + * @implements IListSessionsResponse + * @constructor + * @param {google.spanner.v1.IListSessionsResponse=} [properties] Properties to set + */ + function ListSessionsResponse(properties) { + this.sessions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListSessionsResponse sessions. + * @member {Array.} sessions + * @memberof google.spanner.v1.ListSessionsResponse + * @instance + */ + ListSessionsResponse.prototype.sessions = $util.emptyArray; + + /** + * ListSessionsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.spanner.v1.ListSessionsResponse + * @instance + */ + ListSessionsResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListSessionsResponse instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {google.spanner.v1.IListSessionsResponse=} [properties] Properties to set + * @returns {google.spanner.v1.ListSessionsResponse} ListSessionsResponse instance + */ + ListSessionsResponse.create = function create(properties) { + return new ListSessionsResponse(properties); + }; + + /** + * Encodes the specified ListSessionsResponse message. Does not implicitly {@link google.spanner.v1.ListSessionsResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {google.spanner.v1.IListSessionsResponse} message ListSessionsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSessionsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.sessions != null && message.sessions.length) + for (var i = 0; i < message.sessions.length; ++i) + $root.google.spanner.v1.Session.encode(message.sessions[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListSessionsResponse message, length delimited. Does not implicitly {@link google.spanner.v1.ListSessionsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {google.spanner.v1.IListSessionsResponse} message ListSessionsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSessionsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListSessionsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ListSessionsResponse} ListSessionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSessionsResponse.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.spanner.v1.ListSessionsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.sessions && message.sessions.length)) + message.sessions = []; + message.sessions.push($root.google.spanner.v1.Session.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListSessionsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ListSessionsResponse} ListSessionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSessionsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListSessionsResponse message. + * @function verify + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListSessionsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.sessions != null && message.hasOwnProperty("sessions")) { + if (!Array.isArray(message.sessions)) + return "sessions: array expected"; + for (var i = 0; i < message.sessions.length; ++i) { + var error = $root.google.spanner.v1.Session.verify(message.sessions[i]); + if (error) + return "sessions." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListSessionsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ListSessionsResponse} ListSessionsResponse + */ + ListSessionsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ListSessionsResponse) + return object; + var message = new $root.google.spanner.v1.ListSessionsResponse(); + if (object.sessions) { + if (!Array.isArray(object.sessions)) + throw TypeError(".google.spanner.v1.ListSessionsResponse.sessions: array expected"); + message.sessions = []; + for (var i = 0; i < object.sessions.length; ++i) { + if (typeof object.sessions[i] !== "object") + throw TypeError(".google.spanner.v1.ListSessionsResponse.sessions: object expected"); + message.sessions[i] = $root.google.spanner.v1.Session.fromObject(object.sessions[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListSessionsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {google.spanner.v1.ListSessionsResponse} message ListSessionsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListSessionsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.sessions = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.sessions && message.sessions.length) { + object.sessions = []; + for (var j = 0; j < message.sessions.length; ++j) + object.sessions[j] = $root.google.spanner.v1.Session.toObject(message.sessions[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListSessionsResponse to JSON. + * @function toJSON + * @memberof google.spanner.v1.ListSessionsResponse + * @instance + * @returns {Object.} JSON object + */ + ListSessionsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListSessionsResponse + * @function getTypeUrl + * @memberof google.spanner.v1.ListSessionsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListSessionsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ListSessionsResponse"; + }; + + return ListSessionsResponse; + })(); + + v1.DeleteSessionRequest = (function() { + + /** + * Properties of a DeleteSessionRequest. + * @memberof google.spanner.v1 + * @interface IDeleteSessionRequest + * @property {string|null} [name] DeleteSessionRequest name + */ + + /** + * Constructs a new DeleteSessionRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a DeleteSessionRequest. + * @implements IDeleteSessionRequest + * @constructor + * @param {google.spanner.v1.IDeleteSessionRequest=} [properties] Properties to set + */ + function DeleteSessionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteSessionRequest name. + * @member {string} name + * @memberof google.spanner.v1.DeleteSessionRequest + * @instance + */ + DeleteSessionRequest.prototype.name = ""; + + /** + * Creates a new DeleteSessionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {google.spanner.v1.IDeleteSessionRequest=} [properties] Properties to set + * @returns {google.spanner.v1.DeleteSessionRequest} DeleteSessionRequest instance + */ + DeleteSessionRequest.create = function create(properties) { + return new DeleteSessionRequest(properties); + }; + + /** + * Encodes the specified DeleteSessionRequest message. Does not implicitly {@link google.spanner.v1.DeleteSessionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {google.spanner.v1.IDeleteSessionRequest} message DeleteSessionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteSessionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified DeleteSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.DeleteSessionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {google.spanner.v1.IDeleteSessionRequest} message DeleteSessionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteSessionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteSessionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.DeleteSessionRequest} DeleteSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteSessionRequest.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.spanner.v1.DeleteSessionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteSessionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.DeleteSessionRequest} DeleteSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteSessionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteSessionRequest message. + * @function verify + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteSessionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a DeleteSessionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.DeleteSessionRequest} DeleteSessionRequest + */ + DeleteSessionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.DeleteSessionRequest) + return object; + var message = new $root.google.spanner.v1.DeleteSessionRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteSessionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {google.spanner.v1.DeleteSessionRequest} message DeleteSessionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteSessionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteSessionRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.DeleteSessionRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteSessionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteSessionRequest + * @function getTypeUrl + * @memberof google.spanner.v1.DeleteSessionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteSessionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.DeleteSessionRequest"; + }; + + return DeleteSessionRequest; + })(); + + v1.RequestOptions = (function() { + + /** + * Properties of a RequestOptions. + * @memberof google.spanner.v1 + * @interface IRequestOptions + * @property {google.spanner.v1.RequestOptions.Priority|null} [priority] RequestOptions priority + * @property {string|null} [requestTag] RequestOptions requestTag + * @property {string|null} [transactionTag] RequestOptions transactionTag + * @property {google.spanner.v1.RequestOptions.IClientContext|null} [clientContext] RequestOptions clientContext + */ + + /** + * Constructs a new RequestOptions. + * @memberof google.spanner.v1 + * @classdesc Represents a RequestOptions. + * @implements IRequestOptions + * @constructor + * @param {google.spanner.v1.IRequestOptions=} [properties] Properties to set + */ + function RequestOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RequestOptions priority. + * @member {google.spanner.v1.RequestOptions.Priority} priority + * @memberof google.spanner.v1.RequestOptions + * @instance + */ + RequestOptions.prototype.priority = 0; + + /** + * RequestOptions requestTag. + * @member {string} requestTag + * @memberof google.spanner.v1.RequestOptions + * @instance + */ + RequestOptions.prototype.requestTag = ""; + + /** + * RequestOptions transactionTag. + * @member {string} transactionTag + * @memberof google.spanner.v1.RequestOptions + * @instance + */ + RequestOptions.prototype.transactionTag = ""; + + /** + * RequestOptions clientContext. + * @member {google.spanner.v1.RequestOptions.IClientContext|null|undefined} clientContext + * @memberof google.spanner.v1.RequestOptions + * @instance + */ + RequestOptions.prototype.clientContext = null; + + /** + * Creates a new RequestOptions instance using the specified properties. + * @function create + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {google.spanner.v1.IRequestOptions=} [properties] Properties to set + * @returns {google.spanner.v1.RequestOptions} RequestOptions instance + */ + RequestOptions.create = function create(properties) { + return new RequestOptions(properties); + }; + + /** + * Encodes the specified RequestOptions message. Does not implicitly {@link google.spanner.v1.RequestOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {google.spanner.v1.IRequestOptions} message RequestOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RequestOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.priority != null && Object.hasOwnProperty.call(message, "priority")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.priority); + if (message.requestTag != null && Object.hasOwnProperty.call(message, "requestTag")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.requestTag); + if (message.transactionTag != null && Object.hasOwnProperty.call(message, "transactionTag")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.transactionTag); + if (message.clientContext != null && Object.hasOwnProperty.call(message, "clientContext")) + $root.google.spanner.v1.RequestOptions.ClientContext.encode(message.clientContext, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RequestOptions message, length delimited. Does not implicitly {@link google.spanner.v1.RequestOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {google.spanner.v1.IRequestOptions} message RequestOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RequestOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RequestOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.RequestOptions} RequestOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RequestOptions.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.spanner.v1.RequestOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.priority = reader.int32(); + break; + } + case 2: { + message.requestTag = reader.string(); + break; + } + case 3: { + message.transactionTag = reader.string(); + break; + } + case 4: { + message.clientContext = $root.google.spanner.v1.RequestOptions.ClientContext.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RequestOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.RequestOptions} RequestOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RequestOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RequestOptions message. + * @function verify + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RequestOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.priority != null && message.hasOwnProperty("priority")) + switch (message.priority) { + default: + return "priority: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.requestTag != null && message.hasOwnProperty("requestTag")) + if (!$util.isString(message.requestTag)) + return "requestTag: string expected"; + if (message.transactionTag != null && message.hasOwnProperty("transactionTag")) + if (!$util.isString(message.transactionTag)) + return "transactionTag: string expected"; + if (message.clientContext != null && message.hasOwnProperty("clientContext")) { + var error = $root.google.spanner.v1.RequestOptions.ClientContext.verify(message.clientContext); + if (error) + return "clientContext." + error; + } + return null; + }; + + /** + * Creates a RequestOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.RequestOptions} RequestOptions + */ + RequestOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.RequestOptions) + return object; + var message = new $root.google.spanner.v1.RequestOptions(); + switch (object.priority) { + default: + if (typeof object.priority === "number") { + message.priority = object.priority; + break; + } + break; + case "PRIORITY_UNSPECIFIED": + case 0: + message.priority = 0; + break; + case "PRIORITY_LOW": + case 1: + message.priority = 1; + break; + case "PRIORITY_MEDIUM": + case 2: + message.priority = 2; + break; + case "PRIORITY_HIGH": + case 3: + message.priority = 3; + break; + } + if (object.requestTag != null) + message.requestTag = String(object.requestTag); + if (object.transactionTag != null) + message.transactionTag = String(object.transactionTag); + if (object.clientContext != null) { + if (typeof object.clientContext !== "object") + throw TypeError(".google.spanner.v1.RequestOptions.clientContext: object expected"); + message.clientContext = $root.google.spanner.v1.RequestOptions.ClientContext.fromObject(object.clientContext); + } + return message; + }; + + /** + * Creates a plain object from a RequestOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {google.spanner.v1.RequestOptions} message RequestOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RequestOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.priority = options.enums === String ? "PRIORITY_UNSPECIFIED" : 0; + object.requestTag = ""; + object.transactionTag = ""; + object.clientContext = null; + } + if (message.priority != null && message.hasOwnProperty("priority")) + object.priority = options.enums === String ? $root.google.spanner.v1.RequestOptions.Priority[message.priority] === undefined ? message.priority : $root.google.spanner.v1.RequestOptions.Priority[message.priority] : message.priority; + if (message.requestTag != null && message.hasOwnProperty("requestTag")) + object.requestTag = message.requestTag; + if (message.transactionTag != null && message.hasOwnProperty("transactionTag")) + object.transactionTag = message.transactionTag; + if (message.clientContext != null && message.hasOwnProperty("clientContext")) + object.clientContext = $root.google.spanner.v1.RequestOptions.ClientContext.toObject(message.clientContext, options); + return object; + }; + + /** + * Converts this RequestOptions to JSON. + * @function toJSON + * @memberof google.spanner.v1.RequestOptions + * @instance + * @returns {Object.} JSON object + */ + RequestOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RequestOptions + * @function getTypeUrl + * @memberof google.spanner.v1.RequestOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RequestOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.RequestOptions"; + }; + + /** + * Priority enum. + * @name google.spanner.v1.RequestOptions.Priority + * @enum {number} + * @property {number} PRIORITY_UNSPECIFIED=0 PRIORITY_UNSPECIFIED value + * @property {number} PRIORITY_LOW=1 PRIORITY_LOW value + * @property {number} PRIORITY_MEDIUM=2 PRIORITY_MEDIUM value + * @property {number} PRIORITY_HIGH=3 PRIORITY_HIGH value + */ + RequestOptions.Priority = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "PRIORITY_UNSPECIFIED"] = 0; + values[valuesById[1] = "PRIORITY_LOW"] = 1; + values[valuesById[2] = "PRIORITY_MEDIUM"] = 2; + values[valuesById[3] = "PRIORITY_HIGH"] = 3; + return values; + })(); + + RequestOptions.ClientContext = (function() { + + /** + * Properties of a ClientContext. + * @memberof google.spanner.v1.RequestOptions + * @interface IClientContext + * @property {Object.|null} [secureContext] ClientContext secureContext + */ + + /** + * Constructs a new ClientContext. + * @memberof google.spanner.v1.RequestOptions + * @classdesc Represents a ClientContext. + * @implements IClientContext + * @constructor + * @param {google.spanner.v1.RequestOptions.IClientContext=} [properties] Properties to set + */ + function ClientContext(properties) { + this.secureContext = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ClientContext secureContext. + * @member {Object.} secureContext + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @instance + */ + ClientContext.prototype.secureContext = $util.emptyObject; + + /** + * Creates a new ClientContext instance using the specified properties. + * @function create + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {google.spanner.v1.RequestOptions.IClientContext=} [properties] Properties to set + * @returns {google.spanner.v1.RequestOptions.ClientContext} ClientContext instance + */ + ClientContext.create = function create(properties) { + return new ClientContext(properties); + }; + + /** + * Encodes the specified ClientContext message. Does not implicitly {@link google.spanner.v1.RequestOptions.ClientContext.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {google.spanner.v1.RequestOptions.IClientContext} message ClientContext message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ClientContext.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.secureContext != null && Object.hasOwnProperty.call(message, "secureContext")) + for (var keys = Object.keys(message.secureContext), i = 0; i < keys.length; ++i) { + writer.uint32(/* id 1, wireType 2 =*/10).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); + $root.google.protobuf.Value.encode(message.secureContext[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); + } + return writer; + }; + + /** + * Encodes the specified ClientContext message, length delimited. Does not implicitly {@link google.spanner.v1.RequestOptions.ClientContext.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {google.spanner.v1.RequestOptions.IClientContext} message ClientContext message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ClientContext.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ClientContext message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.RequestOptions.ClientContext} ClientContext + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ClientContext.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.spanner.v1.RequestOptions.ClientContext(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (message.secureContext === $util.emptyObject) + message.secureContext = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = null; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = $root.google.protobuf.Value.decode(reader, reader.uint32()); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.secureContext[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ClientContext message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.RequestOptions.ClientContext} ClientContext + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ClientContext.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ClientContext message. + * @function verify + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ClientContext.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.secureContext != null && message.hasOwnProperty("secureContext")) { + if (!$util.isObject(message.secureContext)) + return "secureContext: object expected"; + var key = Object.keys(message.secureContext); + for (var i = 0; i < key.length; ++i) { + var error = $root.google.protobuf.Value.verify(message.secureContext[key[i]]); + if (error) + return "secureContext." + error; + } + } + return null; + }; + + /** + * Creates a ClientContext message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.RequestOptions.ClientContext} ClientContext + */ + ClientContext.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.RequestOptions.ClientContext) + return object; + var message = new $root.google.spanner.v1.RequestOptions.ClientContext(); + if (object.secureContext) { + if (typeof object.secureContext !== "object") + throw TypeError(".google.spanner.v1.RequestOptions.ClientContext.secureContext: object expected"); + message.secureContext = {}; + for (var keys = Object.keys(object.secureContext), i = 0; i < keys.length; ++i) { + if (typeof object.secureContext[keys[i]] !== "object") + throw TypeError(".google.spanner.v1.RequestOptions.ClientContext.secureContext: object expected"); + message.secureContext[keys[i]] = $root.google.protobuf.Value.fromObject(object.secureContext[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a ClientContext message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {google.spanner.v1.RequestOptions.ClientContext} message ClientContext + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ClientContext.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.secureContext = {}; + var keys2; + if (message.secureContext && (keys2 = Object.keys(message.secureContext)).length) { + object.secureContext = {}; + for (var j = 0; j < keys2.length; ++j) + object.secureContext[keys2[j]] = $root.google.protobuf.Value.toObject(message.secureContext[keys2[j]], options); + } + return object; + }; + + /** + * Converts this ClientContext to JSON. + * @function toJSON + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @instance + * @returns {Object.} JSON object + */ + ClientContext.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ClientContext + * @function getTypeUrl + * @memberof google.spanner.v1.RequestOptions.ClientContext + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ClientContext.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.RequestOptions.ClientContext"; + }; + + return ClientContext; + })(); + + return RequestOptions; + })(); + + v1.DirectedReadOptions = (function() { + + /** + * Properties of a DirectedReadOptions. + * @memberof google.spanner.v1 + * @interface IDirectedReadOptions + * @property {google.spanner.v1.DirectedReadOptions.IIncludeReplicas|null} [includeReplicas] DirectedReadOptions includeReplicas + * @property {google.spanner.v1.DirectedReadOptions.IExcludeReplicas|null} [excludeReplicas] DirectedReadOptions excludeReplicas + */ + + /** + * Constructs a new DirectedReadOptions. + * @memberof google.spanner.v1 + * @classdesc Represents a DirectedReadOptions. + * @implements IDirectedReadOptions + * @constructor + * @param {google.spanner.v1.IDirectedReadOptions=} [properties] Properties to set + */ + function DirectedReadOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DirectedReadOptions includeReplicas. + * @member {google.spanner.v1.DirectedReadOptions.IIncludeReplicas|null|undefined} includeReplicas + * @memberof google.spanner.v1.DirectedReadOptions + * @instance + */ + DirectedReadOptions.prototype.includeReplicas = null; + + /** + * DirectedReadOptions excludeReplicas. + * @member {google.spanner.v1.DirectedReadOptions.IExcludeReplicas|null|undefined} excludeReplicas + * @memberof google.spanner.v1.DirectedReadOptions + * @instance + */ + DirectedReadOptions.prototype.excludeReplicas = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * DirectedReadOptions replicas. + * @member {"includeReplicas"|"excludeReplicas"|undefined} replicas + * @memberof google.spanner.v1.DirectedReadOptions + * @instance + */ + Object.defineProperty(DirectedReadOptions.prototype, "replicas", { + get: $util.oneOfGetter($oneOfFields = ["includeReplicas", "excludeReplicas"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new DirectedReadOptions instance using the specified properties. + * @function create + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {google.spanner.v1.IDirectedReadOptions=} [properties] Properties to set + * @returns {google.spanner.v1.DirectedReadOptions} DirectedReadOptions instance + */ + DirectedReadOptions.create = function create(properties) { + return new DirectedReadOptions(properties); + }; + + /** + * Encodes the specified DirectedReadOptions message. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {google.spanner.v1.IDirectedReadOptions} message DirectedReadOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DirectedReadOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.includeReplicas != null && Object.hasOwnProperty.call(message, "includeReplicas")) + $root.google.spanner.v1.DirectedReadOptions.IncludeReplicas.encode(message.includeReplicas, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.excludeReplicas != null && Object.hasOwnProperty.call(message, "excludeReplicas")) + $root.google.spanner.v1.DirectedReadOptions.ExcludeReplicas.encode(message.excludeReplicas, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified DirectedReadOptions message, length delimited. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {google.spanner.v1.IDirectedReadOptions} message DirectedReadOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DirectedReadOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DirectedReadOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.DirectedReadOptions} DirectedReadOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DirectedReadOptions.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.spanner.v1.DirectedReadOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.includeReplicas = $root.google.spanner.v1.DirectedReadOptions.IncludeReplicas.decode(reader, reader.uint32()); + break; + } + case 2: { + message.excludeReplicas = $root.google.spanner.v1.DirectedReadOptions.ExcludeReplicas.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DirectedReadOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.DirectedReadOptions} DirectedReadOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DirectedReadOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DirectedReadOptions message. + * @function verify + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DirectedReadOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.includeReplicas != null && message.hasOwnProperty("includeReplicas")) { + properties.replicas = 1; + { + var error = $root.google.spanner.v1.DirectedReadOptions.IncludeReplicas.verify(message.includeReplicas); + if (error) + return "includeReplicas." + error; + } + } + if (message.excludeReplicas != null && message.hasOwnProperty("excludeReplicas")) { + if (properties.replicas === 1) + return "replicas: multiple values"; + properties.replicas = 1; + { + var error = $root.google.spanner.v1.DirectedReadOptions.ExcludeReplicas.verify(message.excludeReplicas); + if (error) + return "excludeReplicas." + error; + } + } + return null; + }; + + /** + * Creates a DirectedReadOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.DirectedReadOptions} DirectedReadOptions + */ + DirectedReadOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.DirectedReadOptions) + return object; + var message = new $root.google.spanner.v1.DirectedReadOptions(); + if (object.includeReplicas != null) { + if (typeof object.includeReplicas !== "object") + throw TypeError(".google.spanner.v1.DirectedReadOptions.includeReplicas: object expected"); + message.includeReplicas = $root.google.spanner.v1.DirectedReadOptions.IncludeReplicas.fromObject(object.includeReplicas); + } + if (object.excludeReplicas != null) { + if (typeof object.excludeReplicas !== "object") + throw TypeError(".google.spanner.v1.DirectedReadOptions.excludeReplicas: object expected"); + message.excludeReplicas = $root.google.spanner.v1.DirectedReadOptions.ExcludeReplicas.fromObject(object.excludeReplicas); + } + return message; + }; + + /** + * Creates a plain object from a DirectedReadOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {google.spanner.v1.DirectedReadOptions} message DirectedReadOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DirectedReadOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.includeReplicas != null && message.hasOwnProperty("includeReplicas")) { + object.includeReplicas = $root.google.spanner.v1.DirectedReadOptions.IncludeReplicas.toObject(message.includeReplicas, options); + if (options.oneofs) + object.replicas = "includeReplicas"; + } + if (message.excludeReplicas != null && message.hasOwnProperty("excludeReplicas")) { + object.excludeReplicas = $root.google.spanner.v1.DirectedReadOptions.ExcludeReplicas.toObject(message.excludeReplicas, options); + if (options.oneofs) + object.replicas = "excludeReplicas"; + } + return object; + }; + + /** + * Converts this DirectedReadOptions to JSON. + * @function toJSON + * @memberof google.spanner.v1.DirectedReadOptions + * @instance + * @returns {Object.} JSON object + */ + DirectedReadOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DirectedReadOptions + * @function getTypeUrl + * @memberof google.spanner.v1.DirectedReadOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DirectedReadOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.DirectedReadOptions"; + }; + + DirectedReadOptions.ReplicaSelection = (function() { + + /** + * Properties of a ReplicaSelection. + * @memberof google.spanner.v1.DirectedReadOptions + * @interface IReplicaSelection + * @property {string|null} [location] ReplicaSelection location + * @property {google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type|null} [type] ReplicaSelection type + */ + + /** + * Constructs a new ReplicaSelection. + * @memberof google.spanner.v1.DirectedReadOptions + * @classdesc Represents a ReplicaSelection. + * @implements IReplicaSelection + * @constructor + * @param {google.spanner.v1.DirectedReadOptions.IReplicaSelection=} [properties] Properties to set + */ + function ReplicaSelection(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReplicaSelection location. + * @member {string} location + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @instance + */ + ReplicaSelection.prototype.location = ""; + + /** + * ReplicaSelection type. + * @member {google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type} type + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @instance + */ + ReplicaSelection.prototype.type = 0; + + /** + * Creates a new ReplicaSelection instance using the specified properties. + * @function create + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {google.spanner.v1.DirectedReadOptions.IReplicaSelection=} [properties] Properties to set + * @returns {google.spanner.v1.DirectedReadOptions.ReplicaSelection} ReplicaSelection instance + */ + ReplicaSelection.create = function create(properties) { + return new ReplicaSelection(properties); + }; + + /** + * Encodes the specified ReplicaSelection message. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.ReplicaSelection.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {google.spanner.v1.DirectedReadOptions.IReplicaSelection} message ReplicaSelection message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReplicaSelection.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.location != null && Object.hasOwnProperty.call(message, "location")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.location); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.type); + return writer; + }; + + /** + * Encodes the specified ReplicaSelection message, length delimited. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.ReplicaSelection.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {google.spanner.v1.DirectedReadOptions.IReplicaSelection} message ReplicaSelection message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReplicaSelection.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReplicaSelection message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.DirectedReadOptions.ReplicaSelection} ReplicaSelection + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReplicaSelection.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.spanner.v1.DirectedReadOptions.ReplicaSelection(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.location = reader.string(); + break; + } + case 2: { + message.type = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReplicaSelection message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.DirectedReadOptions.ReplicaSelection} ReplicaSelection + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReplicaSelection.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReplicaSelection message. + * @function verify + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReplicaSelection.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.location != null && message.hasOwnProperty("location")) + if (!$util.isString(message.location)) + return "location: string expected"; + if (message.type != null && message.hasOwnProperty("type")) + switch (message.type) { + default: + return "type: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates a ReplicaSelection message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.DirectedReadOptions.ReplicaSelection} ReplicaSelection + */ + ReplicaSelection.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection) + return object; + var message = new $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection(); + if (object.location != null) + message.location = String(object.location); + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.type = 0; + break; + case "READ_WRITE": + case 1: + message.type = 1; + break; + case "READ_ONLY": + case 2: + message.type = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a ReplicaSelection message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {google.spanner.v1.DirectedReadOptions.ReplicaSelection} message ReplicaSelection + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReplicaSelection.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.location = ""; + object.type = options.enums === String ? "TYPE_UNSPECIFIED" : 0; + } + if (message.location != null && message.hasOwnProperty("location")) + object.location = message.location; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type[message.type] === undefined ? message.type : $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type[message.type] : message.type; + return object; + }; + + /** + * Converts this ReplicaSelection to JSON. + * @function toJSON + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @instance + * @returns {Object.} JSON object + */ + ReplicaSelection.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReplicaSelection + * @function getTypeUrl + * @memberof google.spanner.v1.DirectedReadOptions.ReplicaSelection + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReplicaSelection.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.DirectedReadOptions.ReplicaSelection"; + }; + + /** + * Type enum. + * @name google.spanner.v1.DirectedReadOptions.ReplicaSelection.Type + * @enum {number} + * @property {number} TYPE_UNSPECIFIED=0 TYPE_UNSPECIFIED value + * @property {number} READ_WRITE=1 READ_WRITE value + * @property {number} READ_ONLY=2 READ_ONLY value + */ + ReplicaSelection.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "READ_WRITE"] = 1; + values[valuesById[2] = "READ_ONLY"] = 2; + return values; + })(); + + return ReplicaSelection; + })(); + + DirectedReadOptions.IncludeReplicas = (function() { + + /** + * Properties of an IncludeReplicas. + * @memberof google.spanner.v1.DirectedReadOptions + * @interface IIncludeReplicas + * @property {Array.|null} [replicaSelections] IncludeReplicas replicaSelections + * @property {boolean|null} [autoFailoverDisabled] IncludeReplicas autoFailoverDisabled + */ + + /** + * Constructs a new IncludeReplicas. + * @memberof google.spanner.v1.DirectedReadOptions + * @classdesc Represents an IncludeReplicas. + * @implements IIncludeReplicas + * @constructor + * @param {google.spanner.v1.DirectedReadOptions.IIncludeReplicas=} [properties] Properties to set + */ + function IncludeReplicas(properties) { + this.replicaSelections = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * IncludeReplicas replicaSelections. + * @member {Array.} replicaSelections + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @instance + */ + IncludeReplicas.prototype.replicaSelections = $util.emptyArray; + + /** + * IncludeReplicas autoFailoverDisabled. + * @member {boolean} autoFailoverDisabled + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @instance + */ + IncludeReplicas.prototype.autoFailoverDisabled = false; + + /** + * Creates a new IncludeReplicas instance using the specified properties. + * @function create + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {google.spanner.v1.DirectedReadOptions.IIncludeReplicas=} [properties] Properties to set + * @returns {google.spanner.v1.DirectedReadOptions.IncludeReplicas} IncludeReplicas instance + */ + IncludeReplicas.create = function create(properties) { + return new IncludeReplicas(properties); + }; + + /** + * Encodes the specified IncludeReplicas message. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.IncludeReplicas.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {google.spanner.v1.DirectedReadOptions.IIncludeReplicas} message IncludeReplicas message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IncludeReplicas.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.replicaSelections != null && message.replicaSelections.length) + for (var i = 0; i < message.replicaSelections.length; ++i) + $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.encode(message.replicaSelections[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.autoFailoverDisabled != null && Object.hasOwnProperty.call(message, "autoFailoverDisabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.autoFailoverDisabled); + return writer; + }; + + /** + * Encodes the specified IncludeReplicas message, length delimited. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.IncludeReplicas.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {google.spanner.v1.DirectedReadOptions.IIncludeReplicas} message IncludeReplicas message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IncludeReplicas.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an IncludeReplicas message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.DirectedReadOptions.IncludeReplicas} IncludeReplicas + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IncludeReplicas.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.spanner.v1.DirectedReadOptions.IncludeReplicas(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.replicaSelections && message.replicaSelections.length)) + message.replicaSelections = []; + message.replicaSelections.push($root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.decode(reader, reader.uint32())); + break; + } + case 2: { + message.autoFailoverDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an IncludeReplicas message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.DirectedReadOptions.IncludeReplicas} IncludeReplicas + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IncludeReplicas.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an IncludeReplicas message. + * @function verify + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + IncludeReplicas.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.replicaSelections != null && message.hasOwnProperty("replicaSelections")) { + if (!Array.isArray(message.replicaSelections)) + return "replicaSelections: array expected"; + for (var i = 0; i < message.replicaSelections.length; ++i) { + var error = $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.verify(message.replicaSelections[i]); + if (error) + return "replicaSelections." + error; + } + } + if (message.autoFailoverDisabled != null && message.hasOwnProperty("autoFailoverDisabled")) + if (typeof message.autoFailoverDisabled !== "boolean") + return "autoFailoverDisabled: boolean expected"; + return null; + }; + + /** + * Creates an IncludeReplicas message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.DirectedReadOptions.IncludeReplicas} IncludeReplicas + */ + IncludeReplicas.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.DirectedReadOptions.IncludeReplicas) + return object; + var message = new $root.google.spanner.v1.DirectedReadOptions.IncludeReplicas(); + if (object.replicaSelections) { + if (!Array.isArray(object.replicaSelections)) + throw TypeError(".google.spanner.v1.DirectedReadOptions.IncludeReplicas.replicaSelections: array expected"); + message.replicaSelections = []; + for (var i = 0; i < object.replicaSelections.length; ++i) { + if (typeof object.replicaSelections[i] !== "object") + throw TypeError(".google.spanner.v1.DirectedReadOptions.IncludeReplicas.replicaSelections: object expected"); + message.replicaSelections[i] = $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.fromObject(object.replicaSelections[i]); + } + } + if (object.autoFailoverDisabled != null) + message.autoFailoverDisabled = Boolean(object.autoFailoverDisabled); + return message; + }; + + /** + * Creates a plain object from an IncludeReplicas message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {google.spanner.v1.DirectedReadOptions.IncludeReplicas} message IncludeReplicas + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IncludeReplicas.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.replicaSelections = []; + if (options.defaults) + object.autoFailoverDisabled = false; + if (message.replicaSelections && message.replicaSelections.length) { + object.replicaSelections = []; + for (var j = 0; j < message.replicaSelections.length; ++j) + object.replicaSelections[j] = $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.toObject(message.replicaSelections[j], options); + } + if (message.autoFailoverDisabled != null && message.hasOwnProperty("autoFailoverDisabled")) + object.autoFailoverDisabled = message.autoFailoverDisabled; + return object; + }; + + /** + * Converts this IncludeReplicas to JSON. + * @function toJSON + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @instance + * @returns {Object.} JSON object + */ + IncludeReplicas.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IncludeReplicas + * @function getTypeUrl + * @memberof google.spanner.v1.DirectedReadOptions.IncludeReplicas + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IncludeReplicas.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.DirectedReadOptions.IncludeReplicas"; + }; + + return IncludeReplicas; + })(); + + DirectedReadOptions.ExcludeReplicas = (function() { + + /** + * Properties of an ExcludeReplicas. + * @memberof google.spanner.v1.DirectedReadOptions + * @interface IExcludeReplicas + * @property {Array.|null} [replicaSelections] ExcludeReplicas replicaSelections + */ + + /** + * Constructs a new ExcludeReplicas. + * @memberof google.spanner.v1.DirectedReadOptions + * @classdesc Represents an ExcludeReplicas. + * @implements IExcludeReplicas + * @constructor + * @param {google.spanner.v1.DirectedReadOptions.IExcludeReplicas=} [properties] Properties to set + */ + function ExcludeReplicas(properties) { + this.replicaSelections = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExcludeReplicas replicaSelections. + * @member {Array.} replicaSelections + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @instance + */ + ExcludeReplicas.prototype.replicaSelections = $util.emptyArray; + + /** + * Creates a new ExcludeReplicas instance using the specified properties. + * @function create + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {google.spanner.v1.DirectedReadOptions.IExcludeReplicas=} [properties] Properties to set + * @returns {google.spanner.v1.DirectedReadOptions.ExcludeReplicas} ExcludeReplicas instance + */ + ExcludeReplicas.create = function create(properties) { + return new ExcludeReplicas(properties); + }; + + /** + * Encodes the specified ExcludeReplicas message. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.ExcludeReplicas.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {google.spanner.v1.DirectedReadOptions.IExcludeReplicas} message ExcludeReplicas message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExcludeReplicas.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.replicaSelections != null && message.replicaSelections.length) + for (var i = 0; i < message.replicaSelections.length; ++i) + $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.encode(message.replicaSelections[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ExcludeReplicas message, length delimited. Does not implicitly {@link google.spanner.v1.DirectedReadOptions.ExcludeReplicas.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {google.spanner.v1.DirectedReadOptions.IExcludeReplicas} message ExcludeReplicas message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExcludeReplicas.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExcludeReplicas message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.DirectedReadOptions.ExcludeReplicas} ExcludeReplicas + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExcludeReplicas.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.spanner.v1.DirectedReadOptions.ExcludeReplicas(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.replicaSelections && message.replicaSelections.length)) + message.replicaSelections = []; + message.replicaSelections.push($root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExcludeReplicas message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.DirectedReadOptions.ExcludeReplicas} ExcludeReplicas + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExcludeReplicas.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExcludeReplicas message. + * @function verify + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExcludeReplicas.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.replicaSelections != null && message.hasOwnProperty("replicaSelections")) { + if (!Array.isArray(message.replicaSelections)) + return "replicaSelections: array expected"; + for (var i = 0; i < message.replicaSelections.length; ++i) { + var error = $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.verify(message.replicaSelections[i]); + if (error) + return "replicaSelections." + error; + } + } + return null; + }; + + /** + * Creates an ExcludeReplicas message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.DirectedReadOptions.ExcludeReplicas} ExcludeReplicas + */ + ExcludeReplicas.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.DirectedReadOptions.ExcludeReplicas) + return object; + var message = new $root.google.spanner.v1.DirectedReadOptions.ExcludeReplicas(); + if (object.replicaSelections) { + if (!Array.isArray(object.replicaSelections)) + throw TypeError(".google.spanner.v1.DirectedReadOptions.ExcludeReplicas.replicaSelections: array expected"); + message.replicaSelections = []; + for (var i = 0; i < object.replicaSelections.length; ++i) { + if (typeof object.replicaSelections[i] !== "object") + throw TypeError(".google.spanner.v1.DirectedReadOptions.ExcludeReplicas.replicaSelections: object expected"); + message.replicaSelections[i] = $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.fromObject(object.replicaSelections[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an ExcludeReplicas message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {google.spanner.v1.DirectedReadOptions.ExcludeReplicas} message ExcludeReplicas + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExcludeReplicas.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.replicaSelections = []; + if (message.replicaSelections && message.replicaSelections.length) { + object.replicaSelections = []; + for (var j = 0; j < message.replicaSelections.length; ++j) + object.replicaSelections[j] = $root.google.spanner.v1.DirectedReadOptions.ReplicaSelection.toObject(message.replicaSelections[j], options); + } + return object; + }; + + /** + * Converts this ExcludeReplicas to JSON. + * @function toJSON + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @instance + * @returns {Object.} JSON object + */ + ExcludeReplicas.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExcludeReplicas + * @function getTypeUrl + * @memberof google.spanner.v1.DirectedReadOptions.ExcludeReplicas + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExcludeReplicas.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.DirectedReadOptions.ExcludeReplicas"; + }; + + return ExcludeReplicas; + })(); + + return DirectedReadOptions; + })(); + + v1.ExecuteSqlRequest = (function() { + + /** + * Properties of an ExecuteSqlRequest. + * @memberof google.spanner.v1 + * @interface IExecuteSqlRequest + * @property {string|null} [session] ExecuteSqlRequest session + * @property {google.spanner.v1.ITransactionSelector|null} [transaction] ExecuteSqlRequest transaction + * @property {string|null} [sql] ExecuteSqlRequest sql + * @property {google.protobuf.IStruct|null} [params] ExecuteSqlRequest params + * @property {Object.|null} [paramTypes] ExecuteSqlRequest paramTypes + * @property {Uint8Array|null} [resumeToken] ExecuteSqlRequest resumeToken + * @property {google.spanner.v1.ExecuteSqlRequest.QueryMode|null} [queryMode] ExecuteSqlRequest queryMode + * @property {Uint8Array|null} [partitionToken] ExecuteSqlRequest partitionToken + * @property {number|Long|null} [seqno] ExecuteSqlRequest seqno + * @property {google.spanner.v1.ExecuteSqlRequest.IQueryOptions|null} [queryOptions] ExecuteSqlRequest queryOptions + * @property {google.spanner.v1.IRequestOptions|null} [requestOptions] ExecuteSqlRequest requestOptions + * @property {google.spanner.v1.IDirectedReadOptions|null} [directedReadOptions] ExecuteSqlRequest directedReadOptions + * @property {boolean|null} [dataBoostEnabled] ExecuteSqlRequest dataBoostEnabled + * @property {boolean|null} [lastStatement] ExecuteSqlRequest lastStatement + * @property {google.spanner.v1.IRoutingHint|null} [routingHint] ExecuteSqlRequest routingHint + */ + + /** + * Constructs a new ExecuteSqlRequest. + * @memberof google.spanner.v1 + * @classdesc Represents an ExecuteSqlRequest. + * @implements IExecuteSqlRequest + * @constructor + * @param {google.spanner.v1.IExecuteSqlRequest=} [properties] Properties to set + */ + function ExecuteSqlRequest(properties) { + this.paramTypes = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecuteSqlRequest session. + * @member {string} session + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.session = ""; + + /** + * ExecuteSqlRequest transaction. + * @member {google.spanner.v1.ITransactionSelector|null|undefined} transaction + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.transaction = null; + + /** + * ExecuteSqlRequest sql. + * @member {string} sql + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.sql = ""; + + /** + * ExecuteSqlRequest params. + * @member {google.protobuf.IStruct|null|undefined} params + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.params = null; + + /** + * ExecuteSqlRequest paramTypes. + * @member {Object.} paramTypes + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.paramTypes = $util.emptyObject; + + /** + * ExecuteSqlRequest resumeToken. + * @member {Uint8Array} resumeToken + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.resumeToken = $util.newBuffer([]); + + /** + * ExecuteSqlRequest queryMode. + * @member {google.spanner.v1.ExecuteSqlRequest.QueryMode} queryMode + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.queryMode = 0; + + /** + * ExecuteSqlRequest partitionToken. + * @member {Uint8Array} partitionToken + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.partitionToken = $util.newBuffer([]); + + /** + * ExecuteSqlRequest seqno. + * @member {number|Long} seqno + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.seqno = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * ExecuteSqlRequest queryOptions. + * @member {google.spanner.v1.ExecuteSqlRequest.IQueryOptions|null|undefined} queryOptions + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.queryOptions = null; + + /** + * ExecuteSqlRequest requestOptions. + * @member {google.spanner.v1.IRequestOptions|null|undefined} requestOptions + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.requestOptions = null; + + /** + * ExecuteSqlRequest directedReadOptions. + * @member {google.spanner.v1.IDirectedReadOptions|null|undefined} directedReadOptions + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.directedReadOptions = null; + + /** + * ExecuteSqlRequest dataBoostEnabled. + * @member {boolean} dataBoostEnabled + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.dataBoostEnabled = false; + + /** + * ExecuteSqlRequest lastStatement. + * @member {boolean} lastStatement + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.lastStatement = false; + + /** + * ExecuteSqlRequest routingHint. + * @member {google.spanner.v1.IRoutingHint|null|undefined} routingHint + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + */ + ExecuteSqlRequest.prototype.routingHint = null; + + /** + * Creates a new ExecuteSqlRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {google.spanner.v1.IExecuteSqlRequest=} [properties] Properties to set + * @returns {google.spanner.v1.ExecuteSqlRequest} ExecuteSqlRequest instance + */ + ExecuteSqlRequest.create = function create(properties) { + return new ExecuteSqlRequest(properties); + }; + + /** + * Encodes the specified ExecuteSqlRequest message. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {google.spanner.v1.IExecuteSqlRequest} message ExecuteSqlRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecuteSqlRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.transaction != null && Object.hasOwnProperty.call(message, "transaction")) + $root.google.spanner.v1.TransactionSelector.encode(message.transaction, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.sql != null && Object.hasOwnProperty.call(message, "sql")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.sql); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.protobuf.Struct.encode(message.params, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.paramTypes != null && Object.hasOwnProperty.call(message, "paramTypes")) + for (var keys = Object.keys(message.paramTypes), i = 0; i < keys.length; ++i) { + writer.uint32(/* id 5, wireType 2 =*/42).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); + $root.google.spanner.v1.Type.encode(message.paramTypes[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); + } + if (message.resumeToken != null && Object.hasOwnProperty.call(message, "resumeToken")) + writer.uint32(/* id 6, wireType 2 =*/50).bytes(message.resumeToken); + if (message.queryMode != null && Object.hasOwnProperty.call(message, "queryMode")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.queryMode); + if (message.partitionToken != null && Object.hasOwnProperty.call(message, "partitionToken")) + writer.uint32(/* id 8, wireType 2 =*/66).bytes(message.partitionToken); + if (message.seqno != null && Object.hasOwnProperty.call(message, "seqno")) + writer.uint32(/* id 9, wireType 0 =*/72).int64(message.seqno); + if (message.queryOptions != null && Object.hasOwnProperty.call(message, "queryOptions")) + $root.google.spanner.v1.ExecuteSqlRequest.QueryOptions.encode(message.queryOptions, writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); + if (message.requestOptions != null && Object.hasOwnProperty.call(message, "requestOptions")) + $root.google.spanner.v1.RequestOptions.encode(message.requestOptions, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); + if (message.directedReadOptions != null && Object.hasOwnProperty.call(message, "directedReadOptions")) + $root.google.spanner.v1.DirectedReadOptions.encode(message.directedReadOptions, writer.uint32(/* id 15, wireType 2 =*/122).fork()).ldelim(); + if (message.dataBoostEnabled != null && Object.hasOwnProperty.call(message, "dataBoostEnabled")) + writer.uint32(/* id 16, wireType 0 =*/128).bool(message.dataBoostEnabled); + if (message.lastStatement != null && Object.hasOwnProperty.call(message, "lastStatement")) + writer.uint32(/* id 17, wireType 0 =*/136).bool(message.lastStatement); + if (message.routingHint != null && Object.hasOwnProperty.call(message, "routingHint")) + $root.google.spanner.v1.RoutingHint.encode(message.routingHint, writer.uint32(/* id 18, wireType 2 =*/146).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ExecuteSqlRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {google.spanner.v1.IExecuteSqlRequest} message ExecuteSqlRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecuteSqlRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExecuteSqlRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ExecuteSqlRequest} ExecuteSqlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecuteSqlRequest.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.spanner.v1.ExecuteSqlRequest(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 2: { + message.transaction = $root.google.spanner.v1.TransactionSelector.decode(reader, reader.uint32()); + break; + } + case 3: { + message.sql = reader.string(); + break; + } + case 4: { + message.params = $root.google.protobuf.Struct.decode(reader, reader.uint32()); + break; + } + case 5: { + if (message.paramTypes === $util.emptyObject) + message.paramTypes = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = null; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.paramTypes[key] = value; + break; + } + case 6: { + message.resumeToken = reader.bytes(); + break; + } + case 7: { + message.queryMode = reader.int32(); + break; + } + case 8: { + message.partitionToken = reader.bytes(); + break; + } + case 9: { + message.seqno = reader.int64(); + break; + } + case 10: { + message.queryOptions = $root.google.spanner.v1.ExecuteSqlRequest.QueryOptions.decode(reader, reader.uint32()); + break; + } + case 11: { + message.requestOptions = $root.google.spanner.v1.RequestOptions.decode(reader, reader.uint32()); + break; + } + case 15: { + message.directedReadOptions = $root.google.spanner.v1.DirectedReadOptions.decode(reader, reader.uint32()); + break; + } + case 16: { + message.dataBoostEnabled = reader.bool(); + break; + } + case 17: { + message.lastStatement = reader.bool(); + break; + } + case 18: { + message.routingHint = $root.google.spanner.v1.RoutingHint.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExecuteSqlRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ExecuteSqlRequest} ExecuteSqlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecuteSqlRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExecuteSqlRequest message. + * @function verify + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExecuteSqlRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.transaction != null && message.hasOwnProperty("transaction")) { + var error = $root.google.spanner.v1.TransactionSelector.verify(message.transaction); + if (error) + return "transaction." + error; + } + if (message.sql != null && message.hasOwnProperty("sql")) + if (!$util.isString(message.sql)) + return "sql: string expected"; + if (message.params != null && message.hasOwnProperty("params")) { + var error = $root.google.protobuf.Struct.verify(message.params); + if (error) + return "params." + error; + } + if (message.paramTypes != null && message.hasOwnProperty("paramTypes")) { + if (!$util.isObject(message.paramTypes)) + return "paramTypes: object expected"; + var key = Object.keys(message.paramTypes); + for (var i = 0; i < key.length; ++i) { + var error = $root.google.spanner.v1.Type.verify(message.paramTypes[key[i]]); + if (error) + return "paramTypes." + error; + } + } + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + if (!(message.resumeToken && typeof message.resumeToken.length === "number" || $util.isString(message.resumeToken))) + return "resumeToken: buffer expected"; + if (message.queryMode != null && message.hasOwnProperty("queryMode")) + switch (message.queryMode) { + default: + return "queryMode: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + if (!(message.partitionToken && typeof message.partitionToken.length === "number" || $util.isString(message.partitionToken))) + return "partitionToken: buffer expected"; + if (message.seqno != null && message.hasOwnProperty("seqno")) + if (!$util.isInteger(message.seqno) && !(message.seqno && $util.isInteger(message.seqno.low) && $util.isInteger(message.seqno.high))) + return "seqno: integer|Long expected"; + if (message.queryOptions != null && message.hasOwnProperty("queryOptions")) { + var error = $root.google.spanner.v1.ExecuteSqlRequest.QueryOptions.verify(message.queryOptions); + if (error) + return "queryOptions." + error; + } + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) { + var error = $root.google.spanner.v1.RequestOptions.verify(message.requestOptions); + if (error) + return "requestOptions." + error; + } + if (message.directedReadOptions != null && message.hasOwnProperty("directedReadOptions")) { + var error = $root.google.spanner.v1.DirectedReadOptions.verify(message.directedReadOptions); + if (error) + return "directedReadOptions." + error; + } + if (message.dataBoostEnabled != null && message.hasOwnProperty("dataBoostEnabled")) + if (typeof message.dataBoostEnabled !== "boolean") + return "dataBoostEnabled: boolean expected"; + if (message.lastStatement != null && message.hasOwnProperty("lastStatement")) + if (typeof message.lastStatement !== "boolean") + return "lastStatement: boolean expected"; + if (message.routingHint != null && message.hasOwnProperty("routingHint")) { + var error = $root.google.spanner.v1.RoutingHint.verify(message.routingHint); + if (error) + return "routingHint." + error; + } + return null; + }; + + /** + * Creates an ExecuteSqlRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ExecuteSqlRequest} ExecuteSqlRequest + */ + ExecuteSqlRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ExecuteSqlRequest) + return object; + var message = new $root.google.spanner.v1.ExecuteSqlRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.transaction != null) { + if (typeof object.transaction !== "object") + throw TypeError(".google.spanner.v1.ExecuteSqlRequest.transaction: object expected"); + message.transaction = $root.google.spanner.v1.TransactionSelector.fromObject(object.transaction); + } + if (object.sql != null) + message.sql = String(object.sql); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.spanner.v1.ExecuteSqlRequest.params: object expected"); + message.params = $root.google.protobuf.Struct.fromObject(object.params); + } + if (object.paramTypes) { + if (typeof object.paramTypes !== "object") + throw TypeError(".google.spanner.v1.ExecuteSqlRequest.paramTypes: object expected"); + message.paramTypes = {}; + for (var keys = Object.keys(object.paramTypes), i = 0; i < keys.length; ++i) { + if (typeof object.paramTypes[keys[i]] !== "object") + throw TypeError(".google.spanner.v1.ExecuteSqlRequest.paramTypes: object expected"); + message.paramTypes[keys[i]] = $root.google.spanner.v1.Type.fromObject(object.paramTypes[keys[i]]); + } + } + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + switch (object.queryMode) { + default: + if (typeof object.queryMode === "number") { + message.queryMode = object.queryMode; + break; + } + break; + case "NORMAL": + case 0: + message.queryMode = 0; + break; + case "PLAN": + case 1: + message.queryMode = 1; + break; + case "PROFILE": + case 2: + message.queryMode = 2; + break; + case "WITH_STATS": + case 3: + message.queryMode = 3; + break; + case "WITH_PLAN_AND_STATS": + case 4: + message.queryMode = 4; + break; + } + if (object.partitionToken != null) + if (typeof object.partitionToken === "string") + $util.base64.decode(object.partitionToken, message.partitionToken = $util.newBuffer($util.base64.length(object.partitionToken)), 0); + else if (object.partitionToken.length >= 0) + message.partitionToken = object.partitionToken; + if (object.seqno != null) + if ($util.Long) + (message.seqno = $util.Long.fromValue(object.seqno)).unsigned = false; + else if (typeof object.seqno === "string") + message.seqno = parseInt(object.seqno, 10); + else if (typeof object.seqno === "number") + message.seqno = object.seqno; + else if (typeof object.seqno === "object") + message.seqno = new $util.LongBits(object.seqno.low >>> 0, object.seqno.high >>> 0).toNumber(); + if (object.queryOptions != null) { + if (typeof object.queryOptions !== "object") + throw TypeError(".google.spanner.v1.ExecuteSqlRequest.queryOptions: object expected"); + message.queryOptions = $root.google.spanner.v1.ExecuteSqlRequest.QueryOptions.fromObject(object.queryOptions); + } + if (object.requestOptions != null) { + if (typeof object.requestOptions !== "object") + throw TypeError(".google.spanner.v1.ExecuteSqlRequest.requestOptions: object expected"); + message.requestOptions = $root.google.spanner.v1.RequestOptions.fromObject(object.requestOptions); + } + if (object.directedReadOptions != null) { + if (typeof object.directedReadOptions !== "object") + throw TypeError(".google.spanner.v1.ExecuteSqlRequest.directedReadOptions: object expected"); + message.directedReadOptions = $root.google.spanner.v1.DirectedReadOptions.fromObject(object.directedReadOptions); + } + if (object.dataBoostEnabled != null) + message.dataBoostEnabled = Boolean(object.dataBoostEnabled); + if (object.lastStatement != null) + message.lastStatement = Boolean(object.lastStatement); + if (object.routingHint != null) { + if (typeof object.routingHint !== "object") + throw TypeError(".google.spanner.v1.ExecuteSqlRequest.routingHint: object expected"); + message.routingHint = $root.google.spanner.v1.RoutingHint.fromObject(object.routingHint); + } + return message; + }; + + /** + * Creates a plain object from an ExecuteSqlRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {google.spanner.v1.ExecuteSqlRequest} message ExecuteSqlRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecuteSqlRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.paramTypes = {}; + if (options.defaults) { + object.session = ""; + object.transaction = null; + object.sql = ""; + object.params = null; + if (options.bytes === String) + object.resumeToken = ""; + else { + object.resumeToken = []; + if (options.bytes !== Array) + object.resumeToken = $util.newBuffer(object.resumeToken); + } + object.queryMode = options.enums === String ? "NORMAL" : 0; + if (options.bytes === String) + object.partitionToken = ""; + else { + object.partitionToken = []; + if (options.bytes !== Array) + object.partitionToken = $util.newBuffer(object.partitionToken); + } + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seqno = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seqno = options.longs === String ? "0" : 0; + object.queryOptions = null; + object.requestOptions = null; + object.directedReadOptions = null; + object.dataBoostEnabled = false; + object.lastStatement = false; + object.routingHint = null; + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = $root.google.spanner.v1.TransactionSelector.toObject(message.transaction, options); + if (message.sql != null && message.hasOwnProperty("sql")) + object.sql = message.sql; + if (message.params != null && message.hasOwnProperty("params")) + object.params = $root.google.protobuf.Struct.toObject(message.params, options); + var keys2; + if (message.paramTypes && (keys2 = Object.keys(message.paramTypes)).length) { + object.paramTypes = {}; + for (var j = 0; j < keys2.length; ++j) + object.paramTypes[keys2[j]] = $root.google.spanner.v1.Type.toObject(message.paramTypes[keys2[j]], options); + } + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (message.queryMode != null && message.hasOwnProperty("queryMode")) + object.queryMode = options.enums === String ? $root.google.spanner.v1.ExecuteSqlRequest.QueryMode[message.queryMode] === undefined ? message.queryMode : $root.google.spanner.v1.ExecuteSqlRequest.QueryMode[message.queryMode] : message.queryMode; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + object.partitionToken = options.bytes === String ? $util.base64.encode(message.partitionToken, 0, message.partitionToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.partitionToken) : message.partitionToken; + if (message.seqno != null && message.hasOwnProperty("seqno")) + if (typeof message.seqno === "number") + object.seqno = options.longs === String ? String(message.seqno) : message.seqno; + else + object.seqno = options.longs === String ? $util.Long.prototype.toString.call(message.seqno) : options.longs === Number ? new $util.LongBits(message.seqno.low >>> 0, message.seqno.high >>> 0).toNumber() : message.seqno; + if (message.queryOptions != null && message.hasOwnProperty("queryOptions")) + object.queryOptions = $root.google.spanner.v1.ExecuteSqlRequest.QueryOptions.toObject(message.queryOptions, options); + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) + object.requestOptions = $root.google.spanner.v1.RequestOptions.toObject(message.requestOptions, options); + if (message.directedReadOptions != null && message.hasOwnProperty("directedReadOptions")) + object.directedReadOptions = $root.google.spanner.v1.DirectedReadOptions.toObject(message.directedReadOptions, options); + if (message.dataBoostEnabled != null && message.hasOwnProperty("dataBoostEnabled")) + object.dataBoostEnabled = message.dataBoostEnabled; + if (message.lastStatement != null && message.hasOwnProperty("lastStatement")) + object.lastStatement = message.lastStatement; + if (message.routingHint != null && message.hasOwnProperty("routingHint")) + object.routingHint = $root.google.spanner.v1.RoutingHint.toObject(message.routingHint, options); + return object; + }; + + /** + * Converts this ExecuteSqlRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.ExecuteSqlRequest + * @instance + * @returns {Object.} JSON object + */ + ExecuteSqlRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecuteSqlRequest + * @function getTypeUrl + * @memberof google.spanner.v1.ExecuteSqlRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecuteSqlRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ExecuteSqlRequest"; + }; + + /** + * QueryMode enum. + * @name google.spanner.v1.ExecuteSqlRequest.QueryMode + * @enum {number} + * @property {number} NORMAL=0 NORMAL value + * @property {number} PLAN=1 PLAN value + * @property {number} PROFILE=2 PROFILE value + * @property {number} WITH_STATS=3 WITH_STATS value + * @property {number} WITH_PLAN_AND_STATS=4 WITH_PLAN_AND_STATS value + */ + ExecuteSqlRequest.QueryMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NORMAL"] = 0; + values[valuesById[1] = "PLAN"] = 1; + values[valuesById[2] = "PROFILE"] = 2; + values[valuesById[3] = "WITH_STATS"] = 3; + values[valuesById[4] = "WITH_PLAN_AND_STATS"] = 4; + return values; + })(); + + ExecuteSqlRequest.QueryOptions = (function() { + + /** + * Properties of a QueryOptions. + * @memberof google.spanner.v1.ExecuteSqlRequest + * @interface IQueryOptions + * @property {string|null} [optimizerVersion] QueryOptions optimizerVersion + * @property {string|null} [optimizerStatisticsPackage] QueryOptions optimizerStatisticsPackage + */ + + /** + * Constructs a new QueryOptions. + * @memberof google.spanner.v1.ExecuteSqlRequest + * @classdesc Represents a QueryOptions. + * @implements IQueryOptions + * @constructor + * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions=} [properties] Properties to set + */ + function QueryOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QueryOptions optimizerVersion. + * @member {string} optimizerVersion + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @instance + */ + QueryOptions.prototype.optimizerVersion = ""; + + /** + * QueryOptions optimizerStatisticsPackage. + * @member {string} optimizerStatisticsPackage + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @instance + */ + QueryOptions.prototype.optimizerStatisticsPackage = ""; + + /** + * Creates a new QueryOptions instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions=} [properties] Properties to set + * @returns {google.spanner.v1.ExecuteSqlRequest.QueryOptions} QueryOptions instance + */ + QueryOptions.create = function create(properties) { + return new QueryOptions(properties); + }; + + /** + * Encodes the specified QueryOptions message. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.QueryOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} message QueryOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.optimizerVersion != null && Object.hasOwnProperty.call(message, "optimizerVersion")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.optimizerVersion); + if (message.optimizerStatisticsPackage != null && Object.hasOwnProperty.call(message, "optimizerStatisticsPackage")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.optimizerStatisticsPackage); + return writer; + }; + + /** + * Encodes the specified QueryOptions message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.QueryOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} message QueryOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a QueryOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ExecuteSqlRequest.QueryOptions} QueryOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryOptions.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.spanner.v1.ExecuteSqlRequest.QueryOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.optimizerVersion = reader.string(); + break; + } + case 2: { + message.optimizerStatisticsPackage = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a QueryOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ExecuteSqlRequest.QueryOptions} QueryOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a QueryOptions message. + * @function verify + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + QueryOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.optimizerVersion != null && message.hasOwnProperty("optimizerVersion")) + if (!$util.isString(message.optimizerVersion)) + return "optimizerVersion: string expected"; + if (message.optimizerStatisticsPackage != null && message.hasOwnProperty("optimizerStatisticsPackage")) + if (!$util.isString(message.optimizerStatisticsPackage)) + return "optimizerStatisticsPackage: string expected"; + return null; + }; + + /** + * Creates a QueryOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ExecuteSqlRequest.QueryOptions} QueryOptions + */ + QueryOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ExecuteSqlRequest.QueryOptions) + return object; + var message = new $root.google.spanner.v1.ExecuteSqlRequest.QueryOptions(); + if (object.optimizerVersion != null) + message.optimizerVersion = String(object.optimizerVersion); + if (object.optimizerStatisticsPackage != null) + message.optimizerStatisticsPackage = String(object.optimizerStatisticsPackage); + return message; + }; + + /** + * Creates a plain object from a QueryOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {google.spanner.v1.ExecuteSqlRequest.QueryOptions} message QueryOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.optimizerVersion = ""; + object.optimizerStatisticsPackage = ""; + } + if (message.optimizerVersion != null && message.hasOwnProperty("optimizerVersion")) + object.optimizerVersion = message.optimizerVersion; + if (message.optimizerStatisticsPackage != null && message.hasOwnProperty("optimizerStatisticsPackage")) + object.optimizerStatisticsPackage = message.optimizerStatisticsPackage; + return object; + }; + + /** + * Converts this QueryOptions to JSON. + * @function toJSON + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @instance + * @returns {Object.} JSON object + */ + QueryOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QueryOptions + * @function getTypeUrl + * @memberof google.spanner.v1.ExecuteSqlRequest.QueryOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ExecuteSqlRequest.QueryOptions"; + }; + + return QueryOptions; + })(); + + return ExecuteSqlRequest; + })(); + + v1.ExecuteBatchDmlRequest = (function() { + + /** + * Properties of an ExecuteBatchDmlRequest. + * @memberof google.spanner.v1 + * @interface IExecuteBatchDmlRequest + * @property {string|null} [session] ExecuteBatchDmlRequest session + * @property {google.spanner.v1.ITransactionSelector|null} [transaction] ExecuteBatchDmlRequest transaction + * @property {Array.|null} [statements] ExecuteBatchDmlRequest statements + * @property {number|Long|null} [seqno] ExecuteBatchDmlRequest seqno + * @property {google.spanner.v1.IRequestOptions|null} [requestOptions] ExecuteBatchDmlRequest requestOptions + * @property {boolean|null} [lastStatements] ExecuteBatchDmlRequest lastStatements + */ + + /** + * Constructs a new ExecuteBatchDmlRequest. + * @memberof google.spanner.v1 + * @classdesc Represents an ExecuteBatchDmlRequest. + * @implements IExecuteBatchDmlRequest + * @constructor + * @param {google.spanner.v1.IExecuteBatchDmlRequest=} [properties] Properties to set + */ + function ExecuteBatchDmlRequest(properties) { + this.statements = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecuteBatchDmlRequest session. + * @member {string} session + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @instance + */ + ExecuteBatchDmlRequest.prototype.session = ""; + + /** + * ExecuteBatchDmlRequest transaction. + * @member {google.spanner.v1.ITransactionSelector|null|undefined} transaction + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @instance + */ + ExecuteBatchDmlRequest.prototype.transaction = null; + + /** + * ExecuteBatchDmlRequest statements. + * @member {Array.} statements + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @instance + */ + ExecuteBatchDmlRequest.prototype.statements = $util.emptyArray; + + /** + * ExecuteBatchDmlRequest seqno. + * @member {number|Long} seqno + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @instance + */ + ExecuteBatchDmlRequest.prototype.seqno = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * ExecuteBatchDmlRequest requestOptions. + * @member {google.spanner.v1.IRequestOptions|null|undefined} requestOptions + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @instance + */ + ExecuteBatchDmlRequest.prototype.requestOptions = null; + + /** + * ExecuteBatchDmlRequest lastStatements. + * @member {boolean} lastStatements + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @instance + */ + ExecuteBatchDmlRequest.prototype.lastStatements = false; + + /** + * Creates a new ExecuteBatchDmlRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {google.spanner.v1.IExecuteBatchDmlRequest=} [properties] Properties to set + * @returns {google.spanner.v1.ExecuteBatchDmlRequest} ExecuteBatchDmlRequest instance + */ + ExecuteBatchDmlRequest.create = function create(properties) { + return new ExecuteBatchDmlRequest(properties); + }; + + /** + * Encodes the specified ExecuteBatchDmlRequest message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {google.spanner.v1.IExecuteBatchDmlRequest} message ExecuteBatchDmlRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecuteBatchDmlRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.transaction != null && Object.hasOwnProperty.call(message, "transaction")) + $root.google.spanner.v1.TransactionSelector.encode(message.transaction, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.statements != null && message.statements.length) + for (var i = 0; i < message.statements.length; ++i) + $root.google.spanner.v1.ExecuteBatchDmlRequest.Statement.encode(message.statements[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.seqno != null && Object.hasOwnProperty.call(message, "seqno")) + writer.uint32(/* id 4, wireType 0 =*/32).int64(message.seqno); + if (message.requestOptions != null && Object.hasOwnProperty.call(message, "requestOptions")) + $root.google.spanner.v1.RequestOptions.encode(message.requestOptions, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.lastStatements != null && Object.hasOwnProperty.call(message, "lastStatements")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.lastStatements); + return writer; + }; + + /** + * Encodes the specified ExecuteBatchDmlRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {google.spanner.v1.IExecuteBatchDmlRequest} message ExecuteBatchDmlRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecuteBatchDmlRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExecuteBatchDmlRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ExecuteBatchDmlRequest} ExecuteBatchDmlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecuteBatchDmlRequest.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.spanner.v1.ExecuteBatchDmlRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 2: { + message.transaction = $root.google.spanner.v1.TransactionSelector.decode(reader, reader.uint32()); + break; + } + case 3: { + if (!(message.statements && message.statements.length)) + message.statements = []; + message.statements.push($root.google.spanner.v1.ExecuteBatchDmlRequest.Statement.decode(reader, reader.uint32())); + break; + } + case 4: { + message.seqno = reader.int64(); + break; + } + case 5: { + message.requestOptions = $root.google.spanner.v1.RequestOptions.decode(reader, reader.uint32()); + break; + } + case 6: { + message.lastStatements = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExecuteBatchDmlRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ExecuteBatchDmlRequest} ExecuteBatchDmlRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecuteBatchDmlRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExecuteBatchDmlRequest message. + * @function verify + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExecuteBatchDmlRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.transaction != null && message.hasOwnProperty("transaction")) { + var error = $root.google.spanner.v1.TransactionSelector.verify(message.transaction); + if (error) + return "transaction." + error; + } + if (message.statements != null && message.hasOwnProperty("statements")) { + if (!Array.isArray(message.statements)) + return "statements: array expected"; + for (var i = 0; i < message.statements.length; ++i) { + var error = $root.google.spanner.v1.ExecuteBatchDmlRequest.Statement.verify(message.statements[i]); + if (error) + return "statements." + error; + } + } + if (message.seqno != null && message.hasOwnProperty("seqno")) + if (!$util.isInteger(message.seqno) && !(message.seqno && $util.isInteger(message.seqno.low) && $util.isInteger(message.seqno.high))) + return "seqno: integer|Long expected"; + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) { + var error = $root.google.spanner.v1.RequestOptions.verify(message.requestOptions); + if (error) + return "requestOptions." + error; + } + if (message.lastStatements != null && message.hasOwnProperty("lastStatements")) + if (typeof message.lastStatements !== "boolean") + return "lastStatements: boolean expected"; + return null; + }; + + /** + * Creates an ExecuteBatchDmlRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ExecuteBatchDmlRequest} ExecuteBatchDmlRequest + */ + ExecuteBatchDmlRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ExecuteBatchDmlRequest) + return object; + var message = new $root.google.spanner.v1.ExecuteBatchDmlRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.transaction != null) { + if (typeof object.transaction !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlRequest.transaction: object expected"); + message.transaction = $root.google.spanner.v1.TransactionSelector.fromObject(object.transaction); + } + if (object.statements) { + if (!Array.isArray(object.statements)) + throw TypeError(".google.spanner.v1.ExecuteBatchDmlRequest.statements: array expected"); + message.statements = []; + for (var i = 0; i < object.statements.length; ++i) { + if (typeof object.statements[i] !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlRequest.statements: object expected"); + message.statements[i] = $root.google.spanner.v1.ExecuteBatchDmlRequest.Statement.fromObject(object.statements[i]); + } + } + if (object.seqno != null) + if ($util.Long) + (message.seqno = $util.Long.fromValue(object.seqno)).unsigned = false; + else if (typeof object.seqno === "string") + message.seqno = parseInt(object.seqno, 10); + else if (typeof object.seqno === "number") + message.seqno = object.seqno; + else if (typeof object.seqno === "object") + message.seqno = new $util.LongBits(object.seqno.low >>> 0, object.seqno.high >>> 0).toNumber(); + if (object.requestOptions != null) { + if (typeof object.requestOptions !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlRequest.requestOptions: object expected"); + message.requestOptions = $root.google.spanner.v1.RequestOptions.fromObject(object.requestOptions); + } + if (object.lastStatements != null) + message.lastStatements = Boolean(object.lastStatements); + return message; + }; + + /** + * Creates a plain object from an ExecuteBatchDmlRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {google.spanner.v1.ExecuteBatchDmlRequest} message ExecuteBatchDmlRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecuteBatchDmlRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.statements = []; + if (options.defaults) { + object.session = ""; + object.transaction = null; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seqno = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seqno = options.longs === String ? "0" : 0; + object.requestOptions = null; + object.lastStatements = false; + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = $root.google.spanner.v1.TransactionSelector.toObject(message.transaction, options); + if (message.statements && message.statements.length) { + object.statements = []; + for (var j = 0; j < message.statements.length; ++j) + object.statements[j] = $root.google.spanner.v1.ExecuteBatchDmlRequest.Statement.toObject(message.statements[j], options); + } + if (message.seqno != null && message.hasOwnProperty("seqno")) + if (typeof message.seqno === "number") + object.seqno = options.longs === String ? String(message.seqno) : message.seqno; + else + object.seqno = options.longs === String ? $util.Long.prototype.toString.call(message.seqno) : options.longs === Number ? new $util.LongBits(message.seqno.low >>> 0, message.seqno.high >>> 0).toNumber() : message.seqno; + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) + object.requestOptions = $root.google.spanner.v1.RequestOptions.toObject(message.requestOptions, options); + if (message.lastStatements != null && message.hasOwnProperty("lastStatements")) + object.lastStatements = message.lastStatements; + return object; + }; + + /** + * Converts this ExecuteBatchDmlRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @instance + * @returns {Object.} JSON object + */ + ExecuteBatchDmlRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecuteBatchDmlRequest + * @function getTypeUrl + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecuteBatchDmlRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ExecuteBatchDmlRequest"; + }; + + ExecuteBatchDmlRequest.Statement = (function() { + + /** + * Properties of a Statement. + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @interface IStatement + * @property {string|null} [sql] Statement sql + * @property {google.protobuf.IStruct|null} [params] Statement params + * @property {Object.|null} [paramTypes] Statement paramTypes + */ + + /** + * Constructs a new Statement. + * @memberof google.spanner.v1.ExecuteBatchDmlRequest + * @classdesc Represents a Statement. + * @implements IStatement + * @constructor + * @param {google.spanner.v1.ExecuteBatchDmlRequest.IStatement=} [properties] Properties to set + */ + function Statement(properties) { + this.paramTypes = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Statement sql. + * @member {string} sql + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @instance + */ + Statement.prototype.sql = ""; + + /** + * Statement params. + * @member {google.protobuf.IStruct|null|undefined} params + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @instance + */ + Statement.prototype.params = null; + + /** + * Statement paramTypes. + * @member {Object.} paramTypes + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @instance + */ + Statement.prototype.paramTypes = $util.emptyObject; + + /** + * Creates a new Statement instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {google.spanner.v1.ExecuteBatchDmlRequest.IStatement=} [properties] Properties to set + * @returns {google.spanner.v1.ExecuteBatchDmlRequest.Statement} Statement instance + */ + Statement.create = function create(properties) { + return new Statement(properties); + }; + + /** + * Encodes the specified Statement message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.Statement.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {google.spanner.v1.ExecuteBatchDmlRequest.IStatement} message Statement message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Statement.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.sql != null && Object.hasOwnProperty.call(message, "sql")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.sql); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.protobuf.Struct.encode(message.params, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.paramTypes != null && Object.hasOwnProperty.call(message, "paramTypes")) + for (var keys = Object.keys(message.paramTypes), i = 0; i < keys.length; ++i) { + writer.uint32(/* id 3, wireType 2 =*/26).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); + $root.google.spanner.v1.Type.encode(message.paramTypes[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); + } + return writer; + }; + + /** + * Encodes the specified Statement message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.Statement.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {google.spanner.v1.ExecuteBatchDmlRequest.IStatement} message Statement message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Statement.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Statement message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ExecuteBatchDmlRequest.Statement} Statement + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Statement.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.spanner.v1.ExecuteBatchDmlRequest.Statement(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.sql = reader.string(); + break; + } + case 2: { + message.params = $root.google.protobuf.Struct.decode(reader, reader.uint32()); + break; + } + case 3: { + if (message.paramTypes === $util.emptyObject) + message.paramTypes = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = null; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.paramTypes[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Statement message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ExecuteBatchDmlRequest.Statement} Statement + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Statement.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Statement message. + * @function verify + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Statement.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.sql != null && message.hasOwnProperty("sql")) + if (!$util.isString(message.sql)) + return "sql: string expected"; + if (message.params != null && message.hasOwnProperty("params")) { + var error = $root.google.protobuf.Struct.verify(message.params); + if (error) + return "params." + error; + } + if (message.paramTypes != null && message.hasOwnProperty("paramTypes")) { + if (!$util.isObject(message.paramTypes)) + return "paramTypes: object expected"; + var key = Object.keys(message.paramTypes); + for (var i = 0; i < key.length; ++i) { + var error = $root.google.spanner.v1.Type.verify(message.paramTypes[key[i]]); + if (error) + return "paramTypes." + error; + } + } + return null; + }; + + /** + * Creates a Statement message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ExecuteBatchDmlRequest.Statement} Statement + */ + Statement.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ExecuteBatchDmlRequest.Statement) + return object; + var message = new $root.google.spanner.v1.ExecuteBatchDmlRequest.Statement(); + if (object.sql != null) + message.sql = String(object.sql); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlRequest.Statement.params: object expected"); + message.params = $root.google.protobuf.Struct.fromObject(object.params); + } + if (object.paramTypes) { + if (typeof object.paramTypes !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlRequest.Statement.paramTypes: object expected"); + message.paramTypes = {}; + for (var keys = Object.keys(object.paramTypes), i = 0; i < keys.length; ++i) { + if (typeof object.paramTypes[keys[i]] !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlRequest.Statement.paramTypes: object expected"); + message.paramTypes[keys[i]] = $root.google.spanner.v1.Type.fromObject(object.paramTypes[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Statement message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {google.spanner.v1.ExecuteBatchDmlRequest.Statement} message Statement + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Statement.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.paramTypes = {}; + if (options.defaults) { + object.sql = ""; + object.params = null; + } + if (message.sql != null && message.hasOwnProperty("sql")) + object.sql = message.sql; + if (message.params != null && message.hasOwnProperty("params")) + object.params = $root.google.protobuf.Struct.toObject(message.params, options); + var keys2; + if (message.paramTypes && (keys2 = Object.keys(message.paramTypes)).length) { + object.paramTypes = {}; + for (var j = 0; j < keys2.length; ++j) + object.paramTypes[keys2[j]] = $root.google.spanner.v1.Type.toObject(message.paramTypes[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Statement to JSON. + * @function toJSON + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @instance + * @returns {Object.} JSON object + */ + Statement.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Statement + * @function getTypeUrl + * @memberof google.spanner.v1.ExecuteBatchDmlRequest.Statement + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Statement.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ExecuteBatchDmlRequest.Statement"; + }; + + return Statement; + })(); + + return ExecuteBatchDmlRequest; + })(); + + v1.ExecuteBatchDmlResponse = (function() { + + /** + * Properties of an ExecuteBatchDmlResponse. + * @memberof google.spanner.v1 + * @interface IExecuteBatchDmlResponse + * @property {Array.|null} [resultSets] ExecuteBatchDmlResponse resultSets + * @property {google.rpc.IStatus|null} [status] ExecuteBatchDmlResponse status + * @property {google.spanner.v1.IMultiplexedSessionPrecommitToken|null} [precommitToken] ExecuteBatchDmlResponse precommitToken + */ + + /** + * Constructs a new ExecuteBatchDmlResponse. + * @memberof google.spanner.v1 + * @classdesc Represents an ExecuteBatchDmlResponse. + * @implements IExecuteBatchDmlResponse + * @constructor + * @param {google.spanner.v1.IExecuteBatchDmlResponse=} [properties] Properties to set + */ + function ExecuteBatchDmlResponse(properties) { + this.resultSets = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecuteBatchDmlResponse resultSets. + * @member {Array.} resultSets + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @instance + */ + ExecuteBatchDmlResponse.prototype.resultSets = $util.emptyArray; + + /** + * ExecuteBatchDmlResponse status. + * @member {google.rpc.IStatus|null|undefined} status + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @instance + */ + ExecuteBatchDmlResponse.prototype.status = null; + + /** + * ExecuteBatchDmlResponse precommitToken. + * @member {google.spanner.v1.IMultiplexedSessionPrecommitToken|null|undefined} precommitToken + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @instance + */ + ExecuteBatchDmlResponse.prototype.precommitToken = null; + + /** + * Creates a new ExecuteBatchDmlResponse instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {google.spanner.v1.IExecuteBatchDmlResponse=} [properties] Properties to set + * @returns {google.spanner.v1.ExecuteBatchDmlResponse} ExecuteBatchDmlResponse instance + */ + ExecuteBatchDmlResponse.create = function create(properties) { + return new ExecuteBatchDmlResponse(properties); + }; + + /** + * Encodes the specified ExecuteBatchDmlResponse message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {google.spanner.v1.IExecuteBatchDmlResponse} message ExecuteBatchDmlResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecuteBatchDmlResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resultSets != null && message.resultSets.length) + for (var i = 0; i < message.resultSets.length; ++i) + $root.google.spanner.v1.ResultSet.encode(message.resultSets[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + $root.google.rpc.Status.encode(message.status, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.precommitToken != null && Object.hasOwnProperty.call(message, "precommitToken")) + $root.google.spanner.v1.MultiplexedSessionPrecommitToken.encode(message.precommitToken, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ExecuteBatchDmlResponse message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {google.spanner.v1.IExecuteBatchDmlResponse} message ExecuteBatchDmlResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExecuteBatchDmlResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExecuteBatchDmlResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ExecuteBatchDmlResponse} ExecuteBatchDmlResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecuteBatchDmlResponse.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.spanner.v1.ExecuteBatchDmlResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.resultSets && message.resultSets.length)) + message.resultSets = []; + message.resultSets.push($root.google.spanner.v1.ResultSet.decode(reader, reader.uint32())); + break; + } + case 2: { + message.status = $root.google.rpc.Status.decode(reader, reader.uint32()); + break; + } + case 3: { + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExecuteBatchDmlResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ExecuteBatchDmlResponse} ExecuteBatchDmlResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExecuteBatchDmlResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExecuteBatchDmlResponse message. + * @function verify + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExecuteBatchDmlResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resultSets != null && message.hasOwnProperty("resultSets")) { + if (!Array.isArray(message.resultSets)) + return "resultSets: array expected"; + for (var i = 0; i < message.resultSets.length; ++i) { + var error = $root.google.spanner.v1.ResultSet.verify(message.resultSets[i]); + if (error) + return "resultSets." + error; + } + } + if (message.status != null && message.hasOwnProperty("status")) { + var error = $root.google.rpc.Status.verify(message.status); + if (error) + return "status." + error; + } + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) { + var error = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.verify(message.precommitToken); + if (error) + return "precommitToken." + error; + } + return null; + }; + + /** + * Creates an ExecuteBatchDmlResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ExecuteBatchDmlResponse} ExecuteBatchDmlResponse + */ + ExecuteBatchDmlResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ExecuteBatchDmlResponse) + return object; + var message = new $root.google.spanner.v1.ExecuteBatchDmlResponse(); + if (object.resultSets) { + if (!Array.isArray(object.resultSets)) + throw TypeError(".google.spanner.v1.ExecuteBatchDmlResponse.resultSets: array expected"); + message.resultSets = []; + for (var i = 0; i < object.resultSets.length; ++i) { + if (typeof object.resultSets[i] !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlResponse.resultSets: object expected"); + message.resultSets[i] = $root.google.spanner.v1.ResultSet.fromObject(object.resultSets[i]); + } + } + if (object.status != null) { + if (typeof object.status !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlResponse.status: object expected"); + message.status = $root.google.rpc.Status.fromObject(object.status); + } + if (object.precommitToken != null) { + if (typeof object.precommitToken !== "object") + throw TypeError(".google.spanner.v1.ExecuteBatchDmlResponse.precommitToken: object expected"); + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.fromObject(object.precommitToken); + } + return message; + }; + + /** + * Creates a plain object from an ExecuteBatchDmlResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {google.spanner.v1.ExecuteBatchDmlResponse} message ExecuteBatchDmlResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecuteBatchDmlResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.resultSets = []; + if (options.defaults) { + object.status = null; + object.precommitToken = null; + } + if (message.resultSets && message.resultSets.length) { + object.resultSets = []; + for (var j = 0; j < message.resultSets.length; ++j) + object.resultSets[j] = $root.google.spanner.v1.ResultSet.toObject(message.resultSets[j], options); + } + if (message.status != null && message.hasOwnProperty("status")) + object.status = $root.google.rpc.Status.toObject(message.status, options); + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) + object.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.toObject(message.precommitToken, options); + return object; + }; + + /** + * Converts this ExecuteBatchDmlResponse to JSON. + * @function toJSON + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @instance + * @returns {Object.} JSON object + */ + ExecuteBatchDmlResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExecuteBatchDmlResponse + * @function getTypeUrl + * @memberof google.spanner.v1.ExecuteBatchDmlResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecuteBatchDmlResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ExecuteBatchDmlResponse"; + }; + + return ExecuteBatchDmlResponse; + })(); + + v1.PartitionOptions = (function() { + + /** + * Properties of a PartitionOptions. + * @memberof google.spanner.v1 + * @interface IPartitionOptions + * @property {number|Long|null} [partitionSizeBytes] PartitionOptions partitionSizeBytes + * @property {number|Long|null} [maxPartitions] PartitionOptions maxPartitions + */ + + /** + * Constructs a new PartitionOptions. + * @memberof google.spanner.v1 + * @classdesc Represents a PartitionOptions. + * @implements IPartitionOptions + * @constructor + * @param {google.spanner.v1.IPartitionOptions=} [properties] Properties to set + */ + function PartitionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionOptions partitionSizeBytes. + * @member {number|Long} partitionSizeBytes + * @memberof google.spanner.v1.PartitionOptions + * @instance + */ + PartitionOptions.prototype.partitionSizeBytes = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * PartitionOptions maxPartitions. + * @member {number|Long} maxPartitions + * @memberof google.spanner.v1.PartitionOptions + * @instance + */ + PartitionOptions.prototype.maxPartitions = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new PartitionOptions instance using the specified properties. + * @function create + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {google.spanner.v1.IPartitionOptions=} [properties] Properties to set + * @returns {google.spanner.v1.PartitionOptions} PartitionOptions instance + */ + PartitionOptions.create = function create(properties) { + return new PartitionOptions(properties); + }; + + /** + * Encodes the specified PartitionOptions message. Does not implicitly {@link google.spanner.v1.PartitionOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {google.spanner.v1.IPartitionOptions} message PartitionOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partitionSizeBytes != null && Object.hasOwnProperty.call(message, "partitionSizeBytes")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.partitionSizeBytes); + if (message.maxPartitions != null && Object.hasOwnProperty.call(message, "maxPartitions")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.maxPartitions); + return writer; + }; + + /** + * Encodes the specified PartitionOptions message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {google.spanner.v1.IPartitionOptions} message PartitionOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.PartitionOptions} PartitionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionOptions.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.spanner.v1.PartitionOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.partitionSizeBytes = reader.int64(); + break; + } + case 2: { + message.maxPartitions = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.PartitionOptions} PartitionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionOptions message. + * @function verify + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.partitionSizeBytes != null && message.hasOwnProperty("partitionSizeBytes")) + if (!$util.isInteger(message.partitionSizeBytes) && !(message.partitionSizeBytes && $util.isInteger(message.partitionSizeBytes.low) && $util.isInteger(message.partitionSizeBytes.high))) + return "partitionSizeBytes: integer|Long expected"; + if (message.maxPartitions != null && message.hasOwnProperty("maxPartitions")) + if (!$util.isInteger(message.maxPartitions) && !(message.maxPartitions && $util.isInteger(message.maxPartitions.low) && $util.isInteger(message.maxPartitions.high))) + return "maxPartitions: integer|Long expected"; + return null; + }; + + /** + * Creates a PartitionOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.PartitionOptions} PartitionOptions + */ + PartitionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.PartitionOptions) + return object; + var message = new $root.google.spanner.v1.PartitionOptions(); + if (object.partitionSizeBytes != null) + if ($util.Long) + (message.partitionSizeBytes = $util.Long.fromValue(object.partitionSizeBytes)).unsigned = false; + else if (typeof object.partitionSizeBytes === "string") + message.partitionSizeBytes = parseInt(object.partitionSizeBytes, 10); + else if (typeof object.partitionSizeBytes === "number") + message.partitionSizeBytes = object.partitionSizeBytes; + else if (typeof object.partitionSizeBytes === "object") + message.partitionSizeBytes = new $util.LongBits(object.partitionSizeBytes.low >>> 0, object.partitionSizeBytes.high >>> 0).toNumber(); + if (object.maxPartitions != null) + if ($util.Long) + (message.maxPartitions = $util.Long.fromValue(object.maxPartitions)).unsigned = false; + else if (typeof object.maxPartitions === "string") + message.maxPartitions = parseInt(object.maxPartitions, 10); + else if (typeof object.maxPartitions === "number") + message.maxPartitions = object.maxPartitions; + else if (typeof object.maxPartitions === "object") + message.maxPartitions = new $util.LongBits(object.maxPartitions.low >>> 0, object.maxPartitions.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a PartitionOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {google.spanner.v1.PartitionOptions} message PartitionOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.partitionSizeBytes = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.partitionSizeBytes = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.maxPartitions = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.maxPartitions = options.longs === String ? "0" : 0; + } + if (message.partitionSizeBytes != null && message.hasOwnProperty("partitionSizeBytes")) + if (typeof message.partitionSizeBytes === "number") + object.partitionSizeBytes = options.longs === String ? String(message.partitionSizeBytes) : message.partitionSizeBytes; + else + object.partitionSizeBytes = options.longs === String ? $util.Long.prototype.toString.call(message.partitionSizeBytes) : options.longs === Number ? new $util.LongBits(message.partitionSizeBytes.low >>> 0, message.partitionSizeBytes.high >>> 0).toNumber() : message.partitionSizeBytes; + if (message.maxPartitions != null && message.hasOwnProperty("maxPartitions")) + if (typeof message.maxPartitions === "number") + object.maxPartitions = options.longs === String ? String(message.maxPartitions) : message.maxPartitions; + else + object.maxPartitions = options.longs === String ? $util.Long.prototype.toString.call(message.maxPartitions) : options.longs === Number ? new $util.LongBits(message.maxPartitions.low >>> 0, message.maxPartitions.high >>> 0).toNumber() : message.maxPartitions; + return object; + }; + + /** + * Converts this PartitionOptions to JSON. + * @function toJSON + * @memberof google.spanner.v1.PartitionOptions + * @instance + * @returns {Object.} JSON object + */ + PartitionOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionOptions + * @function getTypeUrl + * @memberof google.spanner.v1.PartitionOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.PartitionOptions"; + }; + + return PartitionOptions; + })(); + + v1.PartitionQueryRequest = (function() { + + /** + * Properties of a PartitionQueryRequest. + * @memberof google.spanner.v1 + * @interface IPartitionQueryRequest + * @property {string|null} [session] PartitionQueryRequest session + * @property {google.spanner.v1.ITransactionSelector|null} [transaction] PartitionQueryRequest transaction + * @property {string|null} [sql] PartitionQueryRequest sql + * @property {google.protobuf.IStruct|null} [params] PartitionQueryRequest params + * @property {Object.|null} [paramTypes] PartitionQueryRequest paramTypes + * @property {google.spanner.v1.IPartitionOptions|null} [partitionOptions] PartitionQueryRequest partitionOptions + */ + + /** + * Constructs a new PartitionQueryRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a PartitionQueryRequest. + * @implements IPartitionQueryRequest + * @constructor + * @param {google.spanner.v1.IPartitionQueryRequest=} [properties] Properties to set + */ + function PartitionQueryRequest(properties) { + this.paramTypes = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionQueryRequest session. + * @member {string} session + * @memberof google.spanner.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.session = ""; + + /** + * PartitionQueryRequest transaction. + * @member {google.spanner.v1.ITransactionSelector|null|undefined} transaction + * @memberof google.spanner.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.transaction = null; + + /** + * PartitionQueryRequest sql. + * @member {string} sql + * @memberof google.spanner.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.sql = ""; + + /** + * PartitionQueryRequest params. + * @member {google.protobuf.IStruct|null|undefined} params + * @memberof google.spanner.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.params = null; + + /** + * PartitionQueryRequest paramTypes. + * @member {Object.} paramTypes + * @memberof google.spanner.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.paramTypes = $util.emptyObject; + + /** + * PartitionQueryRequest partitionOptions. + * @member {google.spanner.v1.IPartitionOptions|null|undefined} partitionOptions + * @memberof google.spanner.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.partitionOptions = null; + + /** + * Creates a new PartitionQueryRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {google.spanner.v1.IPartitionQueryRequest=} [properties] Properties to set + * @returns {google.spanner.v1.PartitionQueryRequest} PartitionQueryRequest instance + */ + PartitionQueryRequest.create = function create(properties) { + return new PartitionQueryRequest(properties); + }; + + /** + * Encodes the specified PartitionQueryRequest message. Does not implicitly {@link google.spanner.v1.PartitionQueryRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {google.spanner.v1.IPartitionQueryRequest} message PartitionQueryRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionQueryRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.transaction != null && Object.hasOwnProperty.call(message, "transaction")) + $root.google.spanner.v1.TransactionSelector.encode(message.transaction, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.sql != null && Object.hasOwnProperty.call(message, "sql")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.sql); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.protobuf.Struct.encode(message.params, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.paramTypes != null && Object.hasOwnProperty.call(message, "paramTypes")) + for (var keys = Object.keys(message.paramTypes), i = 0; i < keys.length; ++i) { + writer.uint32(/* id 5, wireType 2 =*/42).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); + $root.google.spanner.v1.Type.encode(message.paramTypes[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); + } + if (message.partitionOptions != null && Object.hasOwnProperty.call(message, "partitionOptions")) + $root.google.spanner.v1.PartitionOptions.encode(message.partitionOptions, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PartitionQueryRequest message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionQueryRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {google.spanner.v1.IPartitionQueryRequest} message PartitionQueryRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionQueryRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionQueryRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.PartitionQueryRequest} PartitionQueryRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionQueryRequest.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.spanner.v1.PartitionQueryRequest(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 2: { + message.transaction = $root.google.spanner.v1.TransactionSelector.decode(reader, reader.uint32()); + break; + } + case 3: { + message.sql = reader.string(); + break; + } + case 4: { + message.params = $root.google.protobuf.Struct.decode(reader, reader.uint32()); + break; + } + case 5: { + if (message.paramTypes === $util.emptyObject) + message.paramTypes = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = null; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.paramTypes[key] = value; + break; + } + case 6: { + message.partitionOptions = $root.google.spanner.v1.PartitionOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionQueryRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.PartitionQueryRequest} PartitionQueryRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionQueryRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionQueryRequest message. + * @function verify + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionQueryRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.transaction != null && message.hasOwnProperty("transaction")) { + var error = $root.google.spanner.v1.TransactionSelector.verify(message.transaction); + if (error) + return "transaction." + error; + } + if (message.sql != null && message.hasOwnProperty("sql")) + if (!$util.isString(message.sql)) + return "sql: string expected"; + if (message.params != null && message.hasOwnProperty("params")) { + var error = $root.google.protobuf.Struct.verify(message.params); + if (error) + return "params." + error; + } + if (message.paramTypes != null && message.hasOwnProperty("paramTypes")) { + if (!$util.isObject(message.paramTypes)) + return "paramTypes: object expected"; + var key = Object.keys(message.paramTypes); + for (var i = 0; i < key.length; ++i) { + var error = $root.google.spanner.v1.Type.verify(message.paramTypes[key[i]]); + if (error) + return "paramTypes." + error; + } + } + if (message.partitionOptions != null && message.hasOwnProperty("partitionOptions")) { + var error = $root.google.spanner.v1.PartitionOptions.verify(message.partitionOptions); + if (error) + return "partitionOptions." + error; + } + return null; + }; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.PartitionQueryRequest} PartitionQueryRequest + */ + PartitionQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.PartitionQueryRequest) + return object; + var message = new $root.google.spanner.v1.PartitionQueryRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.transaction != null) { + if (typeof object.transaction !== "object") + throw TypeError(".google.spanner.v1.PartitionQueryRequest.transaction: object expected"); + message.transaction = $root.google.spanner.v1.TransactionSelector.fromObject(object.transaction); + } + if (object.sql != null) + message.sql = String(object.sql); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.spanner.v1.PartitionQueryRequest.params: object expected"); + message.params = $root.google.protobuf.Struct.fromObject(object.params); + } + if (object.paramTypes) { + if (typeof object.paramTypes !== "object") + throw TypeError(".google.spanner.v1.PartitionQueryRequest.paramTypes: object expected"); + message.paramTypes = {}; + for (var keys = Object.keys(object.paramTypes), i = 0; i < keys.length; ++i) { + if (typeof object.paramTypes[keys[i]] !== "object") + throw TypeError(".google.spanner.v1.PartitionQueryRequest.paramTypes: object expected"); + message.paramTypes[keys[i]] = $root.google.spanner.v1.Type.fromObject(object.paramTypes[keys[i]]); + } + } + if (object.partitionOptions != null) { + if (typeof object.partitionOptions !== "object") + throw TypeError(".google.spanner.v1.PartitionQueryRequest.partitionOptions: object expected"); + message.partitionOptions = $root.google.spanner.v1.PartitionOptions.fromObject(object.partitionOptions); + } + return message; + }; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {google.spanner.v1.PartitionQueryRequest} message PartitionQueryRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionQueryRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.paramTypes = {}; + if (options.defaults) { + object.session = ""; + object.transaction = null; + object.sql = ""; + object.params = null; + object.partitionOptions = null; + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = $root.google.spanner.v1.TransactionSelector.toObject(message.transaction, options); + if (message.sql != null && message.hasOwnProperty("sql")) + object.sql = message.sql; + if (message.params != null && message.hasOwnProperty("params")) + object.params = $root.google.protobuf.Struct.toObject(message.params, options); + var keys2; + if (message.paramTypes && (keys2 = Object.keys(message.paramTypes)).length) { + object.paramTypes = {}; + for (var j = 0; j < keys2.length; ++j) + object.paramTypes[keys2[j]] = $root.google.spanner.v1.Type.toObject(message.paramTypes[keys2[j]], options); + } + if (message.partitionOptions != null && message.hasOwnProperty("partitionOptions")) + object.partitionOptions = $root.google.spanner.v1.PartitionOptions.toObject(message.partitionOptions, options); + return object; + }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.PartitionQueryRequest + * @instance + * @returns {Object.} JSON object + */ + PartitionQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionQueryRequest + * @function getTypeUrl + * @memberof google.spanner.v1.PartitionQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.PartitionQueryRequest"; + }; + + return PartitionQueryRequest; + })(); + + v1.PartitionReadRequest = (function() { + + /** + * Properties of a PartitionReadRequest. + * @memberof google.spanner.v1 + * @interface IPartitionReadRequest + * @property {string|null} [session] PartitionReadRequest session + * @property {google.spanner.v1.ITransactionSelector|null} [transaction] PartitionReadRequest transaction + * @property {string|null} [table] PartitionReadRequest table + * @property {string|null} [index] PartitionReadRequest index + * @property {Array.|null} [columns] PartitionReadRequest columns + * @property {google.spanner.v1.IKeySet|null} [keySet] PartitionReadRequest keySet + * @property {google.spanner.v1.IPartitionOptions|null} [partitionOptions] PartitionReadRequest partitionOptions + */ + + /** + * Constructs a new PartitionReadRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a PartitionReadRequest. + * @implements IPartitionReadRequest + * @constructor + * @param {google.spanner.v1.IPartitionReadRequest=} [properties] Properties to set + */ + function PartitionReadRequest(properties) { + this.columns = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionReadRequest session. + * @member {string} session + * @memberof google.spanner.v1.PartitionReadRequest + * @instance + */ + PartitionReadRequest.prototype.session = ""; + + /** + * PartitionReadRequest transaction. + * @member {google.spanner.v1.ITransactionSelector|null|undefined} transaction + * @memberof google.spanner.v1.PartitionReadRequest + * @instance + */ + PartitionReadRequest.prototype.transaction = null; + + /** + * PartitionReadRequest table. + * @member {string} table + * @memberof google.spanner.v1.PartitionReadRequest + * @instance + */ + PartitionReadRequest.prototype.table = ""; + + /** + * PartitionReadRequest index. + * @member {string} index + * @memberof google.spanner.v1.PartitionReadRequest + * @instance + */ + PartitionReadRequest.prototype.index = ""; + + /** + * PartitionReadRequest columns. + * @member {Array.} columns + * @memberof google.spanner.v1.PartitionReadRequest + * @instance + */ + PartitionReadRequest.prototype.columns = $util.emptyArray; + + /** + * PartitionReadRequest keySet. + * @member {google.spanner.v1.IKeySet|null|undefined} keySet + * @memberof google.spanner.v1.PartitionReadRequest + * @instance + */ + PartitionReadRequest.prototype.keySet = null; + + /** + * PartitionReadRequest partitionOptions. + * @member {google.spanner.v1.IPartitionOptions|null|undefined} partitionOptions + * @memberof google.spanner.v1.PartitionReadRequest + * @instance + */ + PartitionReadRequest.prototype.partitionOptions = null; + + /** + * Creates a new PartitionReadRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {google.spanner.v1.IPartitionReadRequest=} [properties] Properties to set + * @returns {google.spanner.v1.PartitionReadRequest} PartitionReadRequest instance + */ + PartitionReadRequest.create = function create(properties) { + return new PartitionReadRequest(properties); + }; + + /** + * Encodes the specified PartitionReadRequest message. Does not implicitly {@link google.spanner.v1.PartitionReadRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {google.spanner.v1.IPartitionReadRequest} message PartitionReadRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionReadRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.transaction != null && Object.hasOwnProperty.call(message, "transaction")) + $root.google.spanner.v1.TransactionSelector.encode(message.transaction, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.table); + if (message.index != null && Object.hasOwnProperty.call(message, "index")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.index); + if (message.columns != null && message.columns.length) + for (var i = 0; i < message.columns.length; ++i) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.columns[i]); + if (message.keySet != null && Object.hasOwnProperty.call(message, "keySet")) + $root.google.spanner.v1.KeySet.encode(message.keySet, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.partitionOptions != null && Object.hasOwnProperty.call(message, "partitionOptions")) + $root.google.spanner.v1.PartitionOptions.encode(message.partitionOptions, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PartitionReadRequest message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionReadRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {google.spanner.v1.IPartitionReadRequest} message PartitionReadRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionReadRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionReadRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.PartitionReadRequest} PartitionReadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionReadRequest.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.spanner.v1.PartitionReadRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 2: { + message.transaction = $root.google.spanner.v1.TransactionSelector.decode(reader, reader.uint32()); + break; + } + case 3: { + message.table = reader.string(); + break; + } + case 4: { + message.index = reader.string(); + break; + } + case 5: { + if (!(message.columns && message.columns.length)) + message.columns = []; + message.columns.push(reader.string()); + break; + } + case 6: { + message.keySet = $root.google.spanner.v1.KeySet.decode(reader, reader.uint32()); + break; + } + case 9: { + message.partitionOptions = $root.google.spanner.v1.PartitionOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionReadRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.PartitionReadRequest} PartitionReadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionReadRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionReadRequest message. + * @function verify + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionReadRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.transaction != null && message.hasOwnProperty("transaction")) { + var error = $root.google.spanner.v1.TransactionSelector.verify(message.transaction); + if (error) + return "transaction." + error; + } + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.index != null && message.hasOwnProperty("index")) + if (!$util.isString(message.index)) + return "index: string expected"; + if (message.columns != null && message.hasOwnProperty("columns")) { + if (!Array.isArray(message.columns)) + return "columns: array expected"; + for (var i = 0; i < message.columns.length; ++i) + if (!$util.isString(message.columns[i])) + return "columns: string[] expected"; + } + if (message.keySet != null && message.hasOwnProperty("keySet")) { + var error = $root.google.spanner.v1.KeySet.verify(message.keySet); + if (error) + return "keySet." + error; + } + if (message.partitionOptions != null && message.hasOwnProperty("partitionOptions")) { + var error = $root.google.spanner.v1.PartitionOptions.verify(message.partitionOptions); + if (error) + return "partitionOptions." + error; + } + return null; + }; + + /** + * Creates a PartitionReadRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.PartitionReadRequest} PartitionReadRequest + */ + PartitionReadRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.PartitionReadRequest) + return object; + var message = new $root.google.spanner.v1.PartitionReadRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.transaction != null) { + if (typeof object.transaction !== "object") + throw TypeError(".google.spanner.v1.PartitionReadRequest.transaction: object expected"); + message.transaction = $root.google.spanner.v1.TransactionSelector.fromObject(object.transaction); + } + if (object.table != null) + message.table = String(object.table); + if (object.index != null) + message.index = String(object.index); + if (object.columns) { + if (!Array.isArray(object.columns)) + throw TypeError(".google.spanner.v1.PartitionReadRequest.columns: array expected"); + message.columns = []; + for (var i = 0; i < object.columns.length; ++i) + message.columns[i] = String(object.columns[i]); + } + if (object.keySet != null) { + if (typeof object.keySet !== "object") + throw TypeError(".google.spanner.v1.PartitionReadRequest.keySet: object expected"); + message.keySet = $root.google.spanner.v1.KeySet.fromObject(object.keySet); + } + if (object.partitionOptions != null) { + if (typeof object.partitionOptions !== "object") + throw TypeError(".google.spanner.v1.PartitionReadRequest.partitionOptions: object expected"); + message.partitionOptions = $root.google.spanner.v1.PartitionOptions.fromObject(object.partitionOptions); + } + return message; + }; + + /** + * Creates a plain object from a PartitionReadRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {google.spanner.v1.PartitionReadRequest} message PartitionReadRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionReadRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.columns = []; + if (options.defaults) { + object.session = ""; + object.transaction = null; + object.table = ""; + object.index = ""; + object.keySet = null; + object.partitionOptions = null; + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = $root.google.spanner.v1.TransactionSelector.toObject(message.transaction, options); + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.index != null && message.hasOwnProperty("index")) + object.index = message.index; + if (message.columns && message.columns.length) { + object.columns = []; + for (var j = 0; j < message.columns.length; ++j) + object.columns[j] = message.columns[j]; + } + if (message.keySet != null && message.hasOwnProperty("keySet")) + object.keySet = $root.google.spanner.v1.KeySet.toObject(message.keySet, options); + if (message.partitionOptions != null && message.hasOwnProperty("partitionOptions")) + object.partitionOptions = $root.google.spanner.v1.PartitionOptions.toObject(message.partitionOptions, options); + return object; + }; + + /** + * Converts this PartitionReadRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.PartitionReadRequest + * @instance + * @returns {Object.} JSON object + */ + PartitionReadRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionReadRequest + * @function getTypeUrl + * @memberof google.spanner.v1.PartitionReadRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionReadRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.PartitionReadRequest"; + }; + + return PartitionReadRequest; + })(); + + v1.Partition = (function() { + + /** + * Properties of a Partition. + * @memberof google.spanner.v1 + * @interface IPartition + * @property {Uint8Array|null} [partitionToken] Partition partitionToken + */ + + /** + * Constructs a new Partition. + * @memberof google.spanner.v1 + * @classdesc Represents a Partition. + * @implements IPartition + * @constructor + * @param {google.spanner.v1.IPartition=} [properties] Properties to set + */ + function Partition(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Partition partitionToken. + * @member {Uint8Array} partitionToken + * @memberof google.spanner.v1.Partition + * @instance + */ + Partition.prototype.partitionToken = $util.newBuffer([]); + + /** + * Creates a new Partition instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Partition + * @static + * @param {google.spanner.v1.IPartition=} [properties] Properties to set + * @returns {google.spanner.v1.Partition} Partition instance + */ + Partition.create = function create(properties) { + return new Partition(properties); + }; + + /** + * Encodes the specified Partition message. Does not implicitly {@link google.spanner.v1.Partition.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Partition + * @static + * @param {google.spanner.v1.IPartition} message Partition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Partition.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partitionToken != null && Object.hasOwnProperty.call(message, "partitionToken")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.partitionToken); + return writer; + }; + + /** + * Encodes the specified Partition message, length delimited. Does not implicitly {@link google.spanner.v1.Partition.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Partition + * @static + * @param {google.spanner.v1.IPartition} message Partition message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Partition.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Partition message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Partition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Partition} Partition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Partition.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.spanner.v1.Partition(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.partitionToken = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Partition message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Partition + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Partition} Partition + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Partition.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Partition message. + * @function verify + * @memberof google.spanner.v1.Partition + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Partition.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + if (!(message.partitionToken && typeof message.partitionToken.length === "number" || $util.isString(message.partitionToken))) + return "partitionToken: buffer expected"; + return null; + }; + + /** + * Creates a Partition message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Partition + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Partition} Partition + */ + Partition.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Partition) + return object; + var message = new $root.google.spanner.v1.Partition(); + if (object.partitionToken != null) + if (typeof object.partitionToken === "string") + $util.base64.decode(object.partitionToken, message.partitionToken = $util.newBuffer($util.base64.length(object.partitionToken)), 0); + else if (object.partitionToken.length >= 0) + message.partitionToken = object.partitionToken; + return message; + }; + + /** + * Creates a plain object from a Partition message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Partition + * @static + * @param {google.spanner.v1.Partition} message Partition + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Partition.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.partitionToken = ""; + else { + object.partitionToken = []; + if (options.bytes !== Array) + object.partitionToken = $util.newBuffer(object.partitionToken); + } + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + object.partitionToken = options.bytes === String ? $util.base64.encode(message.partitionToken, 0, message.partitionToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.partitionToken) : message.partitionToken; + return object; + }; + + /** + * Converts this Partition to JSON. + * @function toJSON + * @memberof google.spanner.v1.Partition + * @instance + * @returns {Object.} JSON object + */ + Partition.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Partition + * @function getTypeUrl + * @memberof google.spanner.v1.Partition + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Partition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Partition"; + }; + + return Partition; + })(); + + v1.PartitionResponse = (function() { + + /** + * Properties of a PartitionResponse. + * @memberof google.spanner.v1 + * @interface IPartitionResponse + * @property {Array.|null} [partitions] PartitionResponse partitions + * @property {google.spanner.v1.ITransaction|null} [transaction] PartitionResponse transaction + */ + + /** + * Constructs a new PartitionResponse. + * @memberof google.spanner.v1 + * @classdesc Represents a PartitionResponse. + * @implements IPartitionResponse + * @constructor + * @param {google.spanner.v1.IPartitionResponse=} [properties] Properties to set + */ + function PartitionResponse(properties) { + this.partitions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionResponse partitions. + * @member {Array.} partitions + * @memberof google.spanner.v1.PartitionResponse + * @instance + */ + PartitionResponse.prototype.partitions = $util.emptyArray; + + /** + * PartitionResponse transaction. + * @member {google.spanner.v1.ITransaction|null|undefined} transaction + * @memberof google.spanner.v1.PartitionResponse + * @instance + */ + PartitionResponse.prototype.transaction = null; + + /** + * Creates a new PartitionResponse instance using the specified properties. + * @function create + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {google.spanner.v1.IPartitionResponse=} [properties] Properties to set + * @returns {google.spanner.v1.PartitionResponse} PartitionResponse instance + */ + PartitionResponse.create = function create(properties) { + return new PartitionResponse(properties); + }; + + /** + * Encodes the specified PartitionResponse message. Does not implicitly {@link google.spanner.v1.PartitionResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {google.spanner.v1.IPartitionResponse} message PartitionResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partitions != null && message.partitions.length) + for (var i = 0; i < message.partitions.length; ++i) + $root.google.spanner.v1.Partition.encode(message.partitions[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.transaction != null && Object.hasOwnProperty.call(message, "transaction")) + $root.google.spanner.v1.Transaction.encode(message.transaction, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PartitionResponse message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {google.spanner.v1.IPartitionResponse} message PartitionResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.PartitionResponse} PartitionResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionResponse.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.spanner.v1.PartitionResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.partitions && message.partitions.length)) + message.partitions = []; + message.partitions.push($root.google.spanner.v1.Partition.decode(reader, reader.uint32())); + break; + } + case 2: { + message.transaction = $root.google.spanner.v1.Transaction.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.PartitionResponse} PartitionResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionResponse message. + * @function verify + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.partitions != null && message.hasOwnProperty("partitions")) { + if (!Array.isArray(message.partitions)) + return "partitions: array expected"; + for (var i = 0; i < message.partitions.length; ++i) { + var error = $root.google.spanner.v1.Partition.verify(message.partitions[i]); + if (error) + return "partitions." + error; + } + } + if (message.transaction != null && message.hasOwnProperty("transaction")) { + var error = $root.google.spanner.v1.Transaction.verify(message.transaction); + if (error) + return "transaction." + error; + } + return null; + }; + + /** + * Creates a PartitionResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.PartitionResponse} PartitionResponse + */ + PartitionResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.PartitionResponse) + return object; + var message = new $root.google.spanner.v1.PartitionResponse(); + if (object.partitions) { + if (!Array.isArray(object.partitions)) + throw TypeError(".google.spanner.v1.PartitionResponse.partitions: array expected"); + message.partitions = []; + for (var i = 0; i < object.partitions.length; ++i) { + if (typeof object.partitions[i] !== "object") + throw TypeError(".google.spanner.v1.PartitionResponse.partitions: object expected"); + message.partitions[i] = $root.google.spanner.v1.Partition.fromObject(object.partitions[i]); + } + } + if (object.transaction != null) { + if (typeof object.transaction !== "object") + throw TypeError(".google.spanner.v1.PartitionResponse.transaction: object expected"); + message.transaction = $root.google.spanner.v1.Transaction.fromObject(object.transaction); + } + return message; + }; + + /** + * Creates a plain object from a PartitionResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {google.spanner.v1.PartitionResponse} message PartitionResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.partitions = []; + if (options.defaults) + object.transaction = null; + if (message.partitions && message.partitions.length) { + object.partitions = []; + for (var j = 0; j < message.partitions.length; ++j) + object.partitions[j] = $root.google.spanner.v1.Partition.toObject(message.partitions[j], options); + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = $root.google.spanner.v1.Transaction.toObject(message.transaction, options); + return object; + }; + + /** + * Converts this PartitionResponse to JSON. + * @function toJSON + * @memberof google.spanner.v1.PartitionResponse + * @instance + * @returns {Object.} JSON object + */ + PartitionResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionResponse + * @function getTypeUrl + * @memberof google.spanner.v1.PartitionResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.PartitionResponse"; + }; + + return PartitionResponse; + })(); + + v1.ReadRequest = (function() { + + /** + * Properties of a ReadRequest. + * @memberof google.spanner.v1 + * @interface IReadRequest + * @property {string|null} [session] ReadRequest session + * @property {google.spanner.v1.ITransactionSelector|null} [transaction] ReadRequest transaction + * @property {string|null} [table] ReadRequest table + * @property {string|null} [index] ReadRequest index + * @property {Array.|null} [columns] ReadRequest columns + * @property {google.spanner.v1.IKeySet|null} [keySet] ReadRequest keySet + * @property {number|Long|null} [limit] ReadRequest limit + * @property {Uint8Array|null} [resumeToken] ReadRequest resumeToken + * @property {Uint8Array|null} [partitionToken] ReadRequest partitionToken + * @property {google.spanner.v1.IRequestOptions|null} [requestOptions] ReadRequest requestOptions + * @property {google.spanner.v1.IDirectedReadOptions|null} [directedReadOptions] ReadRequest directedReadOptions + * @property {boolean|null} [dataBoostEnabled] ReadRequest dataBoostEnabled + * @property {google.spanner.v1.ReadRequest.OrderBy|null} [orderBy] ReadRequest orderBy + * @property {google.spanner.v1.ReadRequest.LockHint|null} [lockHint] ReadRequest lockHint + * @property {google.spanner.v1.IRoutingHint|null} [routingHint] ReadRequest routingHint + */ + + /** + * Constructs a new ReadRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a ReadRequest. + * @implements IReadRequest + * @constructor + * @param {google.spanner.v1.IReadRequest=} [properties] Properties to set + */ + function ReadRequest(properties) { + this.columns = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadRequest session. + * @member {string} session + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.session = ""; + + /** + * ReadRequest transaction. + * @member {google.spanner.v1.ITransactionSelector|null|undefined} transaction + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.transaction = null; + + /** + * ReadRequest table. + * @member {string} table + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.table = ""; + + /** + * ReadRequest index. + * @member {string} index + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.index = ""; + + /** + * ReadRequest columns. + * @member {Array.} columns + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.columns = $util.emptyArray; + + /** + * ReadRequest keySet. + * @member {google.spanner.v1.IKeySet|null|undefined} keySet + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.keySet = null; + + /** + * ReadRequest limit. + * @member {number|Long} limit + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.limit = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * ReadRequest resumeToken. + * @member {Uint8Array} resumeToken + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.resumeToken = $util.newBuffer([]); + + /** + * ReadRequest partitionToken. + * @member {Uint8Array} partitionToken + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.partitionToken = $util.newBuffer([]); + + /** + * ReadRequest requestOptions. + * @member {google.spanner.v1.IRequestOptions|null|undefined} requestOptions + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.requestOptions = null; + + /** + * ReadRequest directedReadOptions. + * @member {google.spanner.v1.IDirectedReadOptions|null|undefined} directedReadOptions + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.directedReadOptions = null; + + /** + * ReadRequest dataBoostEnabled. + * @member {boolean} dataBoostEnabled + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.dataBoostEnabled = false; + + /** + * ReadRequest orderBy. + * @member {google.spanner.v1.ReadRequest.OrderBy} orderBy + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.orderBy = 0; + + /** + * ReadRequest lockHint. + * @member {google.spanner.v1.ReadRequest.LockHint} lockHint + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.lockHint = 0; + + /** + * ReadRequest routingHint. + * @member {google.spanner.v1.IRoutingHint|null|undefined} routingHint + * @memberof google.spanner.v1.ReadRequest + * @instance + */ + ReadRequest.prototype.routingHint = null; + + /** + * Creates a new ReadRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {google.spanner.v1.IReadRequest=} [properties] Properties to set + * @returns {google.spanner.v1.ReadRequest} ReadRequest instance + */ + ReadRequest.create = function create(properties) { + return new ReadRequest(properties); + }; + + /** + * Encodes the specified ReadRequest message. Does not implicitly {@link google.spanner.v1.ReadRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {google.spanner.v1.IReadRequest} message ReadRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.transaction != null && Object.hasOwnProperty.call(message, "transaction")) + $root.google.spanner.v1.TransactionSelector.encode(message.transaction, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.table); + if (message.index != null && Object.hasOwnProperty.call(message, "index")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.index); + if (message.columns != null && message.columns.length) + for (var i = 0; i < message.columns.length; ++i) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.columns[i]); + if (message.keySet != null && Object.hasOwnProperty.call(message, "keySet")) + $root.google.spanner.v1.KeySet.encode(message.keySet, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.limit != null && Object.hasOwnProperty.call(message, "limit")) + writer.uint32(/* id 8, wireType 0 =*/64).int64(message.limit); + if (message.resumeToken != null && Object.hasOwnProperty.call(message, "resumeToken")) + writer.uint32(/* id 9, wireType 2 =*/74).bytes(message.resumeToken); + if (message.partitionToken != null && Object.hasOwnProperty.call(message, "partitionToken")) + writer.uint32(/* id 10, wireType 2 =*/82).bytes(message.partitionToken); + if (message.requestOptions != null && Object.hasOwnProperty.call(message, "requestOptions")) + $root.google.spanner.v1.RequestOptions.encode(message.requestOptions, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); + if (message.directedReadOptions != null && Object.hasOwnProperty.call(message, "directedReadOptions")) + $root.google.spanner.v1.DirectedReadOptions.encode(message.directedReadOptions, writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim(); + if (message.dataBoostEnabled != null && Object.hasOwnProperty.call(message, "dataBoostEnabled")) + writer.uint32(/* id 15, wireType 0 =*/120).bool(message.dataBoostEnabled); + if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) + writer.uint32(/* id 16, wireType 0 =*/128).int32(message.orderBy); + if (message.lockHint != null && Object.hasOwnProperty.call(message, "lockHint")) + writer.uint32(/* id 17, wireType 0 =*/136).int32(message.lockHint); + if (message.routingHint != null && Object.hasOwnProperty.call(message, "routingHint")) + $root.google.spanner.v1.RoutingHint.encode(message.routingHint, writer.uint32(/* id 18, wireType 2 =*/146).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ReadRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ReadRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {google.spanner.v1.IReadRequest} message ReadRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ReadRequest} ReadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadRequest.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.spanner.v1.ReadRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 2: { + message.transaction = $root.google.spanner.v1.TransactionSelector.decode(reader, reader.uint32()); + break; + } + case 3: { + message.table = reader.string(); + break; + } + case 4: { + message.index = reader.string(); + break; + } + case 5: { + if (!(message.columns && message.columns.length)) + message.columns = []; + message.columns.push(reader.string()); + break; + } + case 6: { + message.keySet = $root.google.spanner.v1.KeySet.decode(reader, reader.uint32()); + break; + } + case 8: { + message.limit = reader.int64(); + break; + } + case 9: { + message.resumeToken = reader.bytes(); + break; + } + case 10: { + message.partitionToken = reader.bytes(); + break; + } + case 11: { + message.requestOptions = $root.google.spanner.v1.RequestOptions.decode(reader, reader.uint32()); + break; + } + case 14: { + message.directedReadOptions = $root.google.spanner.v1.DirectedReadOptions.decode(reader, reader.uint32()); + break; + } + case 15: { + message.dataBoostEnabled = reader.bool(); + break; + } + case 16: { + message.orderBy = reader.int32(); + break; + } + case 17: { + message.lockHint = reader.int32(); + break; + } + case 18: { + message.routingHint = $root.google.spanner.v1.RoutingHint.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReadRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ReadRequest} ReadRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadRequest message. + * @function verify + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.transaction != null && message.hasOwnProperty("transaction")) { + var error = $root.google.spanner.v1.TransactionSelector.verify(message.transaction); + if (error) + return "transaction." + error; + } + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.index != null && message.hasOwnProperty("index")) + if (!$util.isString(message.index)) + return "index: string expected"; + if (message.columns != null && message.hasOwnProperty("columns")) { + if (!Array.isArray(message.columns)) + return "columns: array expected"; + for (var i = 0; i < message.columns.length; ++i) + if (!$util.isString(message.columns[i])) + return "columns: string[] expected"; + } + if (message.keySet != null && message.hasOwnProperty("keySet")) { + var error = $root.google.spanner.v1.KeySet.verify(message.keySet); + if (error) + return "keySet." + error; + } + if (message.limit != null && message.hasOwnProperty("limit")) + if (!$util.isInteger(message.limit) && !(message.limit && $util.isInteger(message.limit.low) && $util.isInteger(message.limit.high))) + return "limit: integer|Long expected"; + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + if (!(message.resumeToken && typeof message.resumeToken.length === "number" || $util.isString(message.resumeToken))) + return "resumeToken: buffer expected"; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + if (!(message.partitionToken && typeof message.partitionToken.length === "number" || $util.isString(message.partitionToken))) + return "partitionToken: buffer expected"; + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) { + var error = $root.google.spanner.v1.RequestOptions.verify(message.requestOptions); + if (error) + return "requestOptions." + error; + } + if (message.directedReadOptions != null && message.hasOwnProperty("directedReadOptions")) { + var error = $root.google.spanner.v1.DirectedReadOptions.verify(message.directedReadOptions); + if (error) + return "directedReadOptions." + error; + } + if (message.dataBoostEnabled != null && message.hasOwnProperty("dataBoostEnabled")) + if (typeof message.dataBoostEnabled !== "boolean") + return "dataBoostEnabled: boolean expected"; + if (message.orderBy != null && message.hasOwnProperty("orderBy")) + switch (message.orderBy) { + default: + return "orderBy: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.lockHint != null && message.hasOwnProperty("lockHint")) + switch (message.lockHint) { + default: + return "lockHint: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.routingHint != null && message.hasOwnProperty("routingHint")) { + var error = $root.google.spanner.v1.RoutingHint.verify(message.routingHint); + if (error) + return "routingHint." + error; + } + return null; + }; + + /** + * Creates a ReadRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ReadRequest} ReadRequest + */ + ReadRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ReadRequest) + return object; + var message = new $root.google.spanner.v1.ReadRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.transaction != null) { + if (typeof object.transaction !== "object") + throw TypeError(".google.spanner.v1.ReadRequest.transaction: object expected"); + message.transaction = $root.google.spanner.v1.TransactionSelector.fromObject(object.transaction); + } + if (object.table != null) + message.table = String(object.table); + if (object.index != null) + message.index = String(object.index); + if (object.columns) { + if (!Array.isArray(object.columns)) + throw TypeError(".google.spanner.v1.ReadRequest.columns: array expected"); + message.columns = []; + for (var i = 0; i < object.columns.length; ++i) + message.columns[i] = String(object.columns[i]); + } + if (object.keySet != null) { + if (typeof object.keySet !== "object") + throw TypeError(".google.spanner.v1.ReadRequest.keySet: object expected"); + message.keySet = $root.google.spanner.v1.KeySet.fromObject(object.keySet); + } + if (object.limit != null) + if ($util.Long) + (message.limit = $util.Long.fromValue(object.limit)).unsigned = false; + else if (typeof object.limit === "string") + message.limit = parseInt(object.limit, 10); + else if (typeof object.limit === "number") + message.limit = object.limit; + else if (typeof object.limit === "object") + message.limit = new $util.LongBits(object.limit.low >>> 0, object.limit.high >>> 0).toNumber(); + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + if (object.partitionToken != null) + if (typeof object.partitionToken === "string") + $util.base64.decode(object.partitionToken, message.partitionToken = $util.newBuffer($util.base64.length(object.partitionToken)), 0); + else if (object.partitionToken.length >= 0) + message.partitionToken = object.partitionToken; + if (object.requestOptions != null) { + if (typeof object.requestOptions !== "object") + throw TypeError(".google.spanner.v1.ReadRequest.requestOptions: object expected"); + message.requestOptions = $root.google.spanner.v1.RequestOptions.fromObject(object.requestOptions); + } + if (object.directedReadOptions != null) { + if (typeof object.directedReadOptions !== "object") + throw TypeError(".google.spanner.v1.ReadRequest.directedReadOptions: object expected"); + message.directedReadOptions = $root.google.spanner.v1.DirectedReadOptions.fromObject(object.directedReadOptions); + } + if (object.dataBoostEnabled != null) + message.dataBoostEnabled = Boolean(object.dataBoostEnabled); + switch (object.orderBy) { + default: + if (typeof object.orderBy === "number") { + message.orderBy = object.orderBy; + break; + } + break; + case "ORDER_BY_UNSPECIFIED": + case 0: + message.orderBy = 0; + break; + case "ORDER_BY_PRIMARY_KEY": + case 1: + message.orderBy = 1; + break; + case "ORDER_BY_NO_ORDER": + case 2: + message.orderBy = 2; + break; + } + switch (object.lockHint) { + default: + if (typeof object.lockHint === "number") { + message.lockHint = object.lockHint; + break; + } + break; + case "LOCK_HINT_UNSPECIFIED": + case 0: + message.lockHint = 0; + break; + case "LOCK_HINT_SHARED": + case 1: + message.lockHint = 1; + break; + case "LOCK_HINT_EXCLUSIVE": + case 2: + message.lockHint = 2; + break; + } + if (object.routingHint != null) { + if (typeof object.routingHint !== "object") + throw TypeError(".google.spanner.v1.ReadRequest.routingHint: object expected"); + message.routingHint = $root.google.spanner.v1.RoutingHint.fromObject(object.routingHint); + } + return message; + }; + + /** + * Creates a plain object from a ReadRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {google.spanner.v1.ReadRequest} message ReadRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.columns = []; + if (options.defaults) { + object.session = ""; + object.transaction = null; + object.table = ""; + object.index = ""; + object.keySet = null; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.limit = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.limit = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.resumeToken = ""; + else { + object.resumeToken = []; + if (options.bytes !== Array) + object.resumeToken = $util.newBuffer(object.resumeToken); + } + if (options.bytes === String) + object.partitionToken = ""; + else { + object.partitionToken = []; + if (options.bytes !== Array) + object.partitionToken = $util.newBuffer(object.partitionToken); + } + object.requestOptions = null; + object.directedReadOptions = null; + object.dataBoostEnabled = false; + object.orderBy = options.enums === String ? "ORDER_BY_UNSPECIFIED" : 0; + object.lockHint = options.enums === String ? "LOCK_HINT_UNSPECIFIED" : 0; + object.routingHint = null; + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = $root.google.spanner.v1.TransactionSelector.toObject(message.transaction, options); + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.index != null && message.hasOwnProperty("index")) + object.index = message.index; + if (message.columns && message.columns.length) { + object.columns = []; + for (var j = 0; j < message.columns.length; ++j) + object.columns[j] = message.columns[j]; + } + if (message.keySet != null && message.hasOwnProperty("keySet")) + object.keySet = $root.google.spanner.v1.KeySet.toObject(message.keySet, options); + if (message.limit != null && message.hasOwnProperty("limit")) + if (typeof message.limit === "number") + object.limit = options.longs === String ? String(message.limit) : message.limit; + else + object.limit = options.longs === String ? $util.Long.prototype.toString.call(message.limit) : options.longs === Number ? new $util.LongBits(message.limit.low >>> 0, message.limit.high >>> 0).toNumber() : message.limit; + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + object.partitionToken = options.bytes === String ? $util.base64.encode(message.partitionToken, 0, message.partitionToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.partitionToken) : message.partitionToken; + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) + object.requestOptions = $root.google.spanner.v1.RequestOptions.toObject(message.requestOptions, options); + if (message.directedReadOptions != null && message.hasOwnProperty("directedReadOptions")) + object.directedReadOptions = $root.google.spanner.v1.DirectedReadOptions.toObject(message.directedReadOptions, options); + if (message.dataBoostEnabled != null && message.hasOwnProperty("dataBoostEnabled")) + object.dataBoostEnabled = message.dataBoostEnabled; + if (message.orderBy != null && message.hasOwnProperty("orderBy")) + object.orderBy = options.enums === String ? $root.google.spanner.v1.ReadRequest.OrderBy[message.orderBy] === undefined ? message.orderBy : $root.google.spanner.v1.ReadRequest.OrderBy[message.orderBy] : message.orderBy; + if (message.lockHint != null && message.hasOwnProperty("lockHint")) + object.lockHint = options.enums === String ? $root.google.spanner.v1.ReadRequest.LockHint[message.lockHint] === undefined ? message.lockHint : $root.google.spanner.v1.ReadRequest.LockHint[message.lockHint] : message.lockHint; + if (message.routingHint != null && message.hasOwnProperty("routingHint")) + object.routingHint = $root.google.spanner.v1.RoutingHint.toObject(message.routingHint, options); + return object; + }; + + /** + * Converts this ReadRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.ReadRequest + * @instance + * @returns {Object.} JSON object + */ + ReadRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadRequest + * @function getTypeUrl + * @memberof google.spanner.v1.ReadRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ReadRequest"; + }; + + /** + * OrderBy enum. + * @name google.spanner.v1.ReadRequest.OrderBy + * @enum {number} + * @property {number} ORDER_BY_UNSPECIFIED=0 ORDER_BY_UNSPECIFIED value + * @property {number} ORDER_BY_PRIMARY_KEY=1 ORDER_BY_PRIMARY_KEY value + * @property {number} ORDER_BY_NO_ORDER=2 ORDER_BY_NO_ORDER value + */ + ReadRequest.OrderBy = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ORDER_BY_UNSPECIFIED"] = 0; + values[valuesById[1] = "ORDER_BY_PRIMARY_KEY"] = 1; + values[valuesById[2] = "ORDER_BY_NO_ORDER"] = 2; + return values; + })(); + + /** + * LockHint enum. + * @name google.spanner.v1.ReadRequest.LockHint + * @enum {number} + * @property {number} LOCK_HINT_UNSPECIFIED=0 LOCK_HINT_UNSPECIFIED value + * @property {number} LOCK_HINT_SHARED=1 LOCK_HINT_SHARED value + * @property {number} LOCK_HINT_EXCLUSIVE=2 LOCK_HINT_EXCLUSIVE value + */ + ReadRequest.LockHint = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LOCK_HINT_UNSPECIFIED"] = 0; + values[valuesById[1] = "LOCK_HINT_SHARED"] = 1; + values[valuesById[2] = "LOCK_HINT_EXCLUSIVE"] = 2; + return values; + })(); + + return ReadRequest; + })(); + + v1.BeginTransactionRequest = (function() { + + /** + * Properties of a BeginTransactionRequest. + * @memberof google.spanner.v1 + * @interface IBeginTransactionRequest + * @property {string|null} [session] BeginTransactionRequest session + * @property {google.spanner.v1.ITransactionOptions|null} [options] BeginTransactionRequest options + * @property {google.spanner.v1.IRequestOptions|null} [requestOptions] BeginTransactionRequest requestOptions + * @property {google.spanner.v1.IMutation|null} [mutationKey] BeginTransactionRequest mutationKey + */ + + /** + * Constructs a new BeginTransactionRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a BeginTransactionRequest. + * @implements IBeginTransactionRequest + * @constructor + * @param {google.spanner.v1.IBeginTransactionRequest=} [properties] Properties to set + */ + function BeginTransactionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BeginTransactionRequest session. + * @member {string} session + * @memberof google.spanner.v1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.session = ""; + + /** + * BeginTransactionRequest options. + * @member {google.spanner.v1.ITransactionOptions|null|undefined} options + * @memberof google.spanner.v1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.options = null; + + /** + * BeginTransactionRequest requestOptions. + * @member {google.spanner.v1.IRequestOptions|null|undefined} requestOptions + * @memberof google.spanner.v1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.requestOptions = null; + + /** + * BeginTransactionRequest mutationKey. + * @member {google.spanner.v1.IMutation|null|undefined} mutationKey + * @memberof google.spanner.v1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.mutationKey = null; + + /** + * Creates a new BeginTransactionRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {google.spanner.v1.IBeginTransactionRequest=} [properties] Properties to set + * @returns {google.spanner.v1.BeginTransactionRequest} BeginTransactionRequest instance + */ + BeginTransactionRequest.create = function create(properties) { + return new BeginTransactionRequest(properties); + }; + + /** + * Encodes the specified BeginTransactionRequest message. Does not implicitly {@link google.spanner.v1.BeginTransactionRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {google.spanner.v1.IBeginTransactionRequest} message BeginTransactionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BeginTransactionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.spanner.v1.TransactionOptions.encode(message.options, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.requestOptions != null && Object.hasOwnProperty.call(message, "requestOptions")) + $root.google.spanner.v1.RequestOptions.encode(message.requestOptions, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.mutationKey != null && Object.hasOwnProperty.call(message, "mutationKey")) + $root.google.spanner.v1.Mutation.encode(message.mutationKey, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BeginTransactionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.BeginTransactionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {google.spanner.v1.IBeginTransactionRequest} message BeginTransactionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BeginTransactionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BeginTransactionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.BeginTransactionRequest} BeginTransactionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BeginTransactionRequest.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.spanner.v1.BeginTransactionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 2: { + message.options = $root.google.spanner.v1.TransactionOptions.decode(reader, reader.uint32()); + break; + } + case 3: { + message.requestOptions = $root.google.spanner.v1.RequestOptions.decode(reader, reader.uint32()); + break; + } + case 4: { + message.mutationKey = $root.google.spanner.v1.Mutation.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BeginTransactionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.BeginTransactionRequest} BeginTransactionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BeginTransactionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BeginTransactionRequest message. + * @function verify + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BeginTransactionRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.spanner.v1.TransactionOptions.verify(message.options); + if (error) + return "options." + error; + } + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) { + var error = $root.google.spanner.v1.RequestOptions.verify(message.requestOptions); + if (error) + return "requestOptions." + error; + } + if (message.mutationKey != null && message.hasOwnProperty("mutationKey")) { + var error = $root.google.spanner.v1.Mutation.verify(message.mutationKey); + if (error) + return "mutationKey." + error; + } + return null; + }; + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.BeginTransactionRequest} BeginTransactionRequest + */ + BeginTransactionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.BeginTransactionRequest) + return object; + var message = new $root.google.spanner.v1.BeginTransactionRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.spanner.v1.BeginTransactionRequest.options: object expected"); + message.options = $root.google.spanner.v1.TransactionOptions.fromObject(object.options); + } + if (object.requestOptions != null) { + if (typeof object.requestOptions !== "object") + throw TypeError(".google.spanner.v1.BeginTransactionRequest.requestOptions: object expected"); + message.requestOptions = $root.google.spanner.v1.RequestOptions.fromObject(object.requestOptions); + } + if (object.mutationKey != null) { + if (typeof object.mutationKey !== "object") + throw TypeError(".google.spanner.v1.BeginTransactionRequest.mutationKey: object expected"); + message.mutationKey = $root.google.spanner.v1.Mutation.fromObject(object.mutationKey); + } + return message; + }; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {google.spanner.v1.BeginTransactionRequest} message BeginTransactionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BeginTransactionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.session = ""; + object.options = null; + object.requestOptions = null; + object.mutationKey = null; + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.spanner.v1.TransactionOptions.toObject(message.options, options); + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) + object.requestOptions = $root.google.spanner.v1.RequestOptions.toObject(message.requestOptions, options); + if (message.mutationKey != null && message.hasOwnProperty("mutationKey")) + object.mutationKey = $root.google.spanner.v1.Mutation.toObject(message.mutationKey, options); + return object; + }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.BeginTransactionRequest + * @instance + * @returns {Object.} JSON object + */ + BeginTransactionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BeginTransactionRequest + * @function getTypeUrl + * @memberof google.spanner.v1.BeginTransactionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BeginTransactionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.BeginTransactionRequest"; + }; + + return BeginTransactionRequest; + })(); + + v1.CommitRequest = (function() { + + /** + * Properties of a CommitRequest. + * @memberof google.spanner.v1 + * @interface ICommitRequest + * @property {string|null} [session] CommitRequest session + * @property {Uint8Array|null} [transactionId] CommitRequest transactionId + * @property {google.spanner.v1.ITransactionOptions|null} [singleUseTransaction] CommitRequest singleUseTransaction + * @property {Array.|null} [mutations] CommitRequest mutations + * @property {boolean|null} [returnCommitStats] CommitRequest returnCommitStats + * @property {google.protobuf.IDuration|null} [maxCommitDelay] CommitRequest maxCommitDelay + * @property {google.spanner.v1.IRequestOptions|null} [requestOptions] CommitRequest requestOptions + * @property {google.spanner.v1.IMultiplexedSessionPrecommitToken|null} [precommitToken] CommitRequest precommitToken + */ + + /** + * Constructs a new CommitRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a CommitRequest. + * @implements ICommitRequest + * @constructor + * @param {google.spanner.v1.ICommitRequest=} [properties] Properties to set + */ + function CommitRequest(properties) { + this.mutations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommitRequest session. + * @member {string} session + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.session = ""; + + /** + * CommitRequest transactionId. + * @member {Uint8Array|null|undefined} transactionId + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.transactionId = null; + + /** + * CommitRequest singleUseTransaction. + * @member {google.spanner.v1.ITransactionOptions|null|undefined} singleUseTransaction + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.singleUseTransaction = null; + + /** + * CommitRequest mutations. + * @member {Array.} mutations + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.mutations = $util.emptyArray; + + /** + * CommitRequest returnCommitStats. + * @member {boolean} returnCommitStats + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.returnCommitStats = false; + + /** + * CommitRequest maxCommitDelay. + * @member {google.protobuf.IDuration|null|undefined} maxCommitDelay + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.maxCommitDelay = null; + + /** + * CommitRequest requestOptions. + * @member {google.spanner.v1.IRequestOptions|null|undefined} requestOptions + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.requestOptions = null; + + /** + * CommitRequest precommitToken. + * @member {google.spanner.v1.IMultiplexedSessionPrecommitToken|null|undefined} precommitToken + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.precommitToken = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * CommitRequest transaction. + * @member {"transactionId"|"singleUseTransaction"|undefined} transaction + * @memberof google.spanner.v1.CommitRequest + * @instance + */ + Object.defineProperty(CommitRequest.prototype, "transaction", { + get: $util.oneOfGetter($oneOfFields = ["transactionId", "singleUseTransaction"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new CommitRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {google.spanner.v1.ICommitRequest=} [properties] Properties to set + * @returns {google.spanner.v1.CommitRequest} CommitRequest instance + */ + CommitRequest.create = function create(properties) { + return new CommitRequest(properties); + }; + + /** + * Encodes the specified CommitRequest message. Does not implicitly {@link google.spanner.v1.CommitRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {google.spanner.v1.ICommitRequest} message CommitRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CommitRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.transactionId != null && Object.hasOwnProperty.call(message, "transactionId")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.transactionId); + if (message.singleUseTransaction != null && Object.hasOwnProperty.call(message, "singleUseTransaction")) + $root.google.spanner.v1.TransactionOptions.encode(message.singleUseTransaction, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.mutations != null && message.mutations.length) + for (var i = 0; i < message.mutations.length; ++i) + $root.google.spanner.v1.Mutation.encode(message.mutations[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.returnCommitStats != null && Object.hasOwnProperty.call(message, "returnCommitStats")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.returnCommitStats); + if (message.requestOptions != null && Object.hasOwnProperty.call(message, "requestOptions")) + $root.google.spanner.v1.RequestOptions.encode(message.requestOptions, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.maxCommitDelay != null && Object.hasOwnProperty.call(message, "maxCommitDelay")) + $root.google.protobuf.Duration.encode(message.maxCommitDelay, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.precommitToken != null && Object.hasOwnProperty.call(message, "precommitToken")) + $root.google.spanner.v1.MultiplexedSessionPrecommitToken.encode(message.precommitToken, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CommitRequest message, length delimited. Does not implicitly {@link google.spanner.v1.CommitRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {google.spanner.v1.ICommitRequest} message CommitRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CommitRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CommitRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.CommitRequest} CommitRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CommitRequest.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.spanner.v1.CommitRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 2: { + message.transactionId = reader.bytes(); + break; + } + case 3: { + message.singleUseTransaction = $root.google.spanner.v1.TransactionOptions.decode(reader, reader.uint32()); + break; + } + case 4: { + if (!(message.mutations && message.mutations.length)) + message.mutations = []; + message.mutations.push($root.google.spanner.v1.Mutation.decode(reader, reader.uint32())); + break; + } + case 5: { + message.returnCommitStats = reader.bool(); + break; + } + case 8: { + message.maxCommitDelay = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + case 6: { + message.requestOptions = $root.google.spanner.v1.RequestOptions.decode(reader, reader.uint32()); + break; + } + case 9: { + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CommitRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.CommitRequest} CommitRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CommitRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CommitRequest message. + * @function verify + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CommitRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.transactionId != null && message.hasOwnProperty("transactionId")) { + properties.transaction = 1; + if (!(message.transactionId && typeof message.transactionId.length === "number" || $util.isString(message.transactionId))) + return "transactionId: buffer expected"; + } + if (message.singleUseTransaction != null && message.hasOwnProperty("singleUseTransaction")) { + if (properties.transaction === 1) + return "transaction: multiple values"; + properties.transaction = 1; + { + var error = $root.google.spanner.v1.TransactionOptions.verify(message.singleUseTransaction); + if (error) + return "singleUseTransaction." + error; + } + } + if (message.mutations != null && message.hasOwnProperty("mutations")) { + if (!Array.isArray(message.mutations)) + return "mutations: array expected"; + for (var i = 0; i < message.mutations.length; ++i) { + var error = $root.google.spanner.v1.Mutation.verify(message.mutations[i]); + if (error) + return "mutations." + error; + } + } + if (message.returnCommitStats != null && message.hasOwnProperty("returnCommitStats")) + if (typeof message.returnCommitStats !== "boolean") + return "returnCommitStats: boolean expected"; + if (message.maxCommitDelay != null && message.hasOwnProperty("maxCommitDelay")) { + var error = $root.google.protobuf.Duration.verify(message.maxCommitDelay); + if (error) + return "maxCommitDelay." + error; + } + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) { + var error = $root.google.spanner.v1.RequestOptions.verify(message.requestOptions); + if (error) + return "requestOptions." + error; + } + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) { + var error = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.verify(message.precommitToken); + if (error) + return "precommitToken." + error; + } + return null; + }; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.CommitRequest} CommitRequest + */ + CommitRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.CommitRequest) + return object; + var message = new $root.google.spanner.v1.CommitRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.transactionId != null) + if (typeof object.transactionId === "string") + $util.base64.decode(object.transactionId, message.transactionId = $util.newBuffer($util.base64.length(object.transactionId)), 0); + else if (object.transactionId.length >= 0) + message.transactionId = object.transactionId; + if (object.singleUseTransaction != null) { + if (typeof object.singleUseTransaction !== "object") + throw TypeError(".google.spanner.v1.CommitRequest.singleUseTransaction: object expected"); + message.singleUseTransaction = $root.google.spanner.v1.TransactionOptions.fromObject(object.singleUseTransaction); + } + if (object.mutations) { + if (!Array.isArray(object.mutations)) + throw TypeError(".google.spanner.v1.CommitRequest.mutations: array expected"); + message.mutations = []; + for (var i = 0; i < object.mutations.length; ++i) { + if (typeof object.mutations[i] !== "object") + throw TypeError(".google.spanner.v1.CommitRequest.mutations: object expected"); + message.mutations[i] = $root.google.spanner.v1.Mutation.fromObject(object.mutations[i]); + } + } + if (object.returnCommitStats != null) + message.returnCommitStats = Boolean(object.returnCommitStats); + if (object.maxCommitDelay != null) { + if (typeof object.maxCommitDelay !== "object") + throw TypeError(".google.spanner.v1.CommitRequest.maxCommitDelay: object expected"); + message.maxCommitDelay = $root.google.protobuf.Duration.fromObject(object.maxCommitDelay); + } + if (object.requestOptions != null) { + if (typeof object.requestOptions !== "object") + throw TypeError(".google.spanner.v1.CommitRequest.requestOptions: object expected"); + message.requestOptions = $root.google.spanner.v1.RequestOptions.fromObject(object.requestOptions); + } + if (object.precommitToken != null) { + if (typeof object.precommitToken !== "object") + throw TypeError(".google.spanner.v1.CommitRequest.precommitToken: object expected"); + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.fromObject(object.precommitToken); + } + return message; + }; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {google.spanner.v1.CommitRequest} message CommitRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.mutations = []; + if (options.defaults) { + object.session = ""; + object.returnCommitStats = false; + object.requestOptions = null; + object.maxCommitDelay = null; + object.precommitToken = null; + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.transactionId != null && message.hasOwnProperty("transactionId")) { + object.transactionId = options.bytes === String ? $util.base64.encode(message.transactionId, 0, message.transactionId.length) : options.bytes === Array ? Array.prototype.slice.call(message.transactionId) : message.transactionId; + if (options.oneofs) + object.transaction = "transactionId"; + } + if (message.singleUseTransaction != null && message.hasOwnProperty("singleUseTransaction")) { + object.singleUseTransaction = $root.google.spanner.v1.TransactionOptions.toObject(message.singleUseTransaction, options); + if (options.oneofs) + object.transaction = "singleUseTransaction"; + } + if (message.mutations && message.mutations.length) { + object.mutations = []; + for (var j = 0; j < message.mutations.length; ++j) + object.mutations[j] = $root.google.spanner.v1.Mutation.toObject(message.mutations[j], options); + } + if (message.returnCommitStats != null && message.hasOwnProperty("returnCommitStats")) + object.returnCommitStats = message.returnCommitStats; + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) + object.requestOptions = $root.google.spanner.v1.RequestOptions.toObject(message.requestOptions, options); + if (message.maxCommitDelay != null && message.hasOwnProperty("maxCommitDelay")) + object.maxCommitDelay = $root.google.protobuf.Duration.toObject(message.maxCommitDelay, options); + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) + object.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.toObject(message.precommitToken, options); + return object; + }; + + /** + * Converts this CommitRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.CommitRequest + * @instance + * @returns {Object.} JSON object + */ + CommitRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitRequest + * @function getTypeUrl + * @memberof google.spanner.v1.CommitRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.CommitRequest"; + }; + + return CommitRequest; + })(); + + v1.RollbackRequest = (function() { + + /** + * Properties of a RollbackRequest. + * @memberof google.spanner.v1 + * @interface IRollbackRequest + * @property {string|null} [session] RollbackRequest session + * @property {Uint8Array|null} [transactionId] RollbackRequest transactionId + */ + + /** + * Constructs a new RollbackRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a RollbackRequest. + * @implements IRollbackRequest + * @constructor + * @param {google.spanner.v1.IRollbackRequest=} [properties] Properties to set + */ + function RollbackRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RollbackRequest session. + * @member {string} session + * @memberof google.spanner.v1.RollbackRequest + * @instance + */ + RollbackRequest.prototype.session = ""; + + /** + * RollbackRequest transactionId. + * @member {Uint8Array} transactionId + * @memberof google.spanner.v1.RollbackRequest + * @instance + */ + RollbackRequest.prototype.transactionId = $util.newBuffer([]); + + /** + * Creates a new RollbackRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {google.spanner.v1.IRollbackRequest=} [properties] Properties to set + * @returns {google.spanner.v1.RollbackRequest} RollbackRequest instance + */ + RollbackRequest.create = function create(properties) { + return new RollbackRequest(properties); + }; + + /** + * Encodes the specified RollbackRequest message. Does not implicitly {@link google.spanner.v1.RollbackRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {google.spanner.v1.IRollbackRequest} message RollbackRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RollbackRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.transactionId != null && Object.hasOwnProperty.call(message, "transactionId")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.transactionId); + return writer; + }; + + /** + * Encodes the specified RollbackRequest message, length delimited. Does not implicitly {@link google.spanner.v1.RollbackRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {google.spanner.v1.IRollbackRequest} message RollbackRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RollbackRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RollbackRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.RollbackRequest} RollbackRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RollbackRequest.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.spanner.v1.RollbackRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 2: { + message.transactionId = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RollbackRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.RollbackRequest} RollbackRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RollbackRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RollbackRequest message. + * @function verify + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RollbackRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.transactionId != null && message.hasOwnProperty("transactionId")) + if (!(message.transactionId && typeof message.transactionId.length === "number" || $util.isString(message.transactionId))) + return "transactionId: buffer expected"; + return null; + }; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.RollbackRequest} RollbackRequest + */ + RollbackRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.RollbackRequest) + return object; + var message = new $root.google.spanner.v1.RollbackRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.transactionId != null) + if (typeof object.transactionId === "string") + $util.base64.decode(object.transactionId, message.transactionId = $util.newBuffer($util.base64.length(object.transactionId)), 0); + else if (object.transactionId.length >= 0) + message.transactionId = object.transactionId; + return message; + }; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {google.spanner.v1.RollbackRequest} message RollbackRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RollbackRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.session = ""; + if (options.bytes === String) + object.transactionId = ""; + else { + object.transactionId = []; + if (options.bytes !== Array) + object.transactionId = $util.newBuffer(object.transactionId); + } + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.transactionId != null && message.hasOwnProperty("transactionId")) + object.transactionId = options.bytes === String ? $util.base64.encode(message.transactionId, 0, message.transactionId.length) : options.bytes === Array ? Array.prototype.slice.call(message.transactionId) : message.transactionId; + return object; + }; + + /** + * Converts this RollbackRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.RollbackRequest + * @instance + * @returns {Object.} JSON object + */ + RollbackRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RollbackRequest + * @function getTypeUrl + * @memberof google.spanner.v1.RollbackRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RollbackRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.RollbackRequest"; + }; + + return RollbackRequest; + })(); + + v1.BatchWriteRequest = (function() { + + /** + * Properties of a BatchWriteRequest. + * @memberof google.spanner.v1 + * @interface IBatchWriteRequest + * @property {string|null} [session] BatchWriteRequest session + * @property {google.spanner.v1.IRequestOptions|null} [requestOptions] BatchWriteRequest requestOptions + * @property {Array.|null} [mutationGroups] BatchWriteRequest mutationGroups + * @property {boolean|null} [excludeTxnFromChangeStreams] BatchWriteRequest excludeTxnFromChangeStreams + */ + + /** + * Constructs a new BatchWriteRequest. + * @memberof google.spanner.v1 + * @classdesc Represents a BatchWriteRequest. + * @implements IBatchWriteRequest + * @constructor + * @param {google.spanner.v1.IBatchWriteRequest=} [properties] Properties to set + */ + function BatchWriteRequest(properties) { + this.mutationGroups = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchWriteRequest session. + * @member {string} session + * @memberof google.spanner.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.session = ""; + + /** + * BatchWriteRequest requestOptions. + * @member {google.spanner.v1.IRequestOptions|null|undefined} requestOptions + * @memberof google.spanner.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.requestOptions = null; + + /** + * BatchWriteRequest mutationGroups. + * @member {Array.} mutationGroups + * @memberof google.spanner.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.mutationGroups = $util.emptyArray; + + /** + * BatchWriteRequest excludeTxnFromChangeStreams. + * @member {boolean} excludeTxnFromChangeStreams + * @memberof google.spanner.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.excludeTxnFromChangeStreams = false; + + /** + * Creates a new BatchWriteRequest instance using the specified properties. + * @function create + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {google.spanner.v1.IBatchWriteRequest=} [properties] Properties to set + * @returns {google.spanner.v1.BatchWriteRequest} BatchWriteRequest instance + */ + BatchWriteRequest.create = function create(properties) { + return new BatchWriteRequest(properties); + }; + + /** + * Encodes the specified BatchWriteRequest message. Does not implicitly {@link google.spanner.v1.BatchWriteRequest.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {google.spanner.v1.IBatchWriteRequest} message BatchWriteRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchWriteRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.session != null && Object.hasOwnProperty.call(message, "session")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.session); + if (message.requestOptions != null && Object.hasOwnProperty.call(message, "requestOptions")) + $root.google.spanner.v1.RequestOptions.encode(message.requestOptions, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.mutationGroups != null && message.mutationGroups.length) + for (var i = 0; i < message.mutationGroups.length; ++i) + $root.google.spanner.v1.BatchWriteRequest.MutationGroup.encode(message.mutationGroups[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.excludeTxnFromChangeStreams != null && Object.hasOwnProperty.call(message, "excludeTxnFromChangeStreams")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.excludeTxnFromChangeStreams); + return writer; + }; + + /** + * Encodes the specified BatchWriteRequest message, length delimited. Does not implicitly {@link google.spanner.v1.BatchWriteRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {google.spanner.v1.IBatchWriteRequest} message BatchWriteRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchWriteRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BatchWriteRequest message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.BatchWriteRequest} BatchWriteRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchWriteRequest.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.spanner.v1.BatchWriteRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.session = reader.string(); + break; + } + case 3: { + message.requestOptions = $root.google.spanner.v1.RequestOptions.decode(reader, reader.uint32()); + break; + } + case 4: { + if (!(message.mutationGroups && message.mutationGroups.length)) + message.mutationGroups = []; + message.mutationGroups.push($root.google.spanner.v1.BatchWriteRequest.MutationGroup.decode(reader, reader.uint32())); + break; + } + case 5: { + message.excludeTxnFromChangeStreams = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BatchWriteRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.BatchWriteRequest} BatchWriteRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchWriteRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BatchWriteRequest message. + * @function verify + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BatchWriteRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.session != null && message.hasOwnProperty("session")) + if (!$util.isString(message.session)) + return "session: string expected"; + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) { + var error = $root.google.spanner.v1.RequestOptions.verify(message.requestOptions); + if (error) + return "requestOptions." + error; + } + if (message.mutationGroups != null && message.hasOwnProperty("mutationGroups")) { + if (!Array.isArray(message.mutationGroups)) + return "mutationGroups: array expected"; + for (var i = 0; i < message.mutationGroups.length; ++i) { + var error = $root.google.spanner.v1.BatchWriteRequest.MutationGroup.verify(message.mutationGroups[i]); + if (error) + return "mutationGroups." + error; + } + } + if (message.excludeTxnFromChangeStreams != null && message.hasOwnProperty("excludeTxnFromChangeStreams")) + if (typeof message.excludeTxnFromChangeStreams !== "boolean") + return "excludeTxnFromChangeStreams: boolean expected"; + return null; + }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.BatchWriteRequest} BatchWriteRequest + */ + BatchWriteRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.BatchWriteRequest) + return object; + var message = new $root.google.spanner.v1.BatchWriteRequest(); + if (object.session != null) + message.session = String(object.session); + if (object.requestOptions != null) { + if (typeof object.requestOptions !== "object") + throw TypeError(".google.spanner.v1.BatchWriteRequest.requestOptions: object expected"); + message.requestOptions = $root.google.spanner.v1.RequestOptions.fromObject(object.requestOptions); + } + if (object.mutationGroups) { + if (!Array.isArray(object.mutationGroups)) + throw TypeError(".google.spanner.v1.BatchWriteRequest.mutationGroups: array expected"); + message.mutationGroups = []; + for (var i = 0; i < object.mutationGroups.length; ++i) { + if (typeof object.mutationGroups[i] !== "object") + throw TypeError(".google.spanner.v1.BatchWriteRequest.mutationGroups: object expected"); + message.mutationGroups[i] = $root.google.spanner.v1.BatchWriteRequest.MutationGroup.fromObject(object.mutationGroups[i]); + } + } + if (object.excludeTxnFromChangeStreams != null) + message.excludeTxnFromChangeStreams = Boolean(object.excludeTxnFromChangeStreams); + return message; + }; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {google.spanner.v1.BatchWriteRequest} message BatchWriteRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchWriteRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.mutationGroups = []; + if (options.defaults) { + object.session = ""; + object.requestOptions = null; + object.excludeTxnFromChangeStreams = false; + } + if (message.session != null && message.hasOwnProperty("session")) + object.session = message.session; + if (message.requestOptions != null && message.hasOwnProperty("requestOptions")) + object.requestOptions = $root.google.spanner.v1.RequestOptions.toObject(message.requestOptions, options); + if (message.mutationGroups && message.mutationGroups.length) { + object.mutationGroups = []; + for (var j = 0; j < message.mutationGroups.length; ++j) + object.mutationGroups[j] = $root.google.spanner.v1.BatchWriteRequest.MutationGroup.toObject(message.mutationGroups[j], options); + } + if (message.excludeTxnFromChangeStreams != null && message.hasOwnProperty("excludeTxnFromChangeStreams")) + object.excludeTxnFromChangeStreams = message.excludeTxnFromChangeStreams; + return object; + }; + + /** + * Converts this BatchWriteRequest to JSON. + * @function toJSON + * @memberof google.spanner.v1.BatchWriteRequest + * @instance + * @returns {Object.} JSON object + */ + BatchWriteRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchWriteRequest + * @function getTypeUrl + * @memberof google.spanner.v1.BatchWriteRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchWriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.BatchWriteRequest"; + }; + + BatchWriteRequest.MutationGroup = (function() { + + /** + * Properties of a MutationGroup. + * @memberof google.spanner.v1.BatchWriteRequest + * @interface IMutationGroup + * @property {Array.|null} [mutations] MutationGroup mutations + */ + + /** + * Constructs a new MutationGroup. + * @memberof google.spanner.v1.BatchWriteRequest + * @classdesc Represents a MutationGroup. + * @implements IMutationGroup + * @constructor + * @param {google.spanner.v1.BatchWriteRequest.IMutationGroup=} [properties] Properties to set + */ + function MutationGroup(properties) { + this.mutations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MutationGroup mutations. + * @member {Array.} mutations + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @instance + */ + MutationGroup.prototype.mutations = $util.emptyArray; + + /** + * Creates a new MutationGroup instance using the specified properties. + * @function create + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {google.spanner.v1.BatchWriteRequest.IMutationGroup=} [properties] Properties to set + * @returns {google.spanner.v1.BatchWriteRequest.MutationGroup} MutationGroup instance + */ + MutationGroup.create = function create(properties) { + return new MutationGroup(properties); + }; + + /** + * Encodes the specified MutationGroup message. Does not implicitly {@link google.spanner.v1.BatchWriteRequest.MutationGroup.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {google.spanner.v1.BatchWriteRequest.IMutationGroup} message MutationGroup message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MutationGroup.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.mutations != null && message.mutations.length) + for (var i = 0; i < message.mutations.length; ++i) + $root.google.spanner.v1.Mutation.encode(message.mutations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified MutationGroup message, length delimited. Does not implicitly {@link google.spanner.v1.BatchWriteRequest.MutationGroup.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {google.spanner.v1.BatchWriteRequest.IMutationGroup} message MutationGroup message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MutationGroup.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MutationGroup message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.BatchWriteRequest.MutationGroup} MutationGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MutationGroup.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.spanner.v1.BatchWriteRequest.MutationGroup(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.mutations && message.mutations.length)) + message.mutations = []; + message.mutations.push($root.google.spanner.v1.Mutation.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MutationGroup message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.BatchWriteRequest.MutationGroup} MutationGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MutationGroup.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MutationGroup message. + * @function verify + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MutationGroup.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.mutations != null && message.hasOwnProperty("mutations")) { + if (!Array.isArray(message.mutations)) + return "mutations: array expected"; + for (var i = 0; i < message.mutations.length; ++i) { + var error = $root.google.spanner.v1.Mutation.verify(message.mutations[i]); + if (error) + return "mutations." + error; + } + } + return null; + }; + + /** + * Creates a MutationGroup message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.BatchWriteRequest.MutationGroup} MutationGroup + */ + MutationGroup.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.BatchWriteRequest.MutationGroup) + return object; + var message = new $root.google.spanner.v1.BatchWriteRequest.MutationGroup(); + if (object.mutations) { + if (!Array.isArray(object.mutations)) + throw TypeError(".google.spanner.v1.BatchWriteRequest.MutationGroup.mutations: array expected"); + message.mutations = []; + for (var i = 0; i < object.mutations.length; ++i) { + if (typeof object.mutations[i] !== "object") + throw TypeError(".google.spanner.v1.BatchWriteRequest.MutationGroup.mutations: object expected"); + message.mutations[i] = $root.google.spanner.v1.Mutation.fromObject(object.mutations[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a MutationGroup message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {google.spanner.v1.BatchWriteRequest.MutationGroup} message MutationGroup + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MutationGroup.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.mutations = []; + if (message.mutations && message.mutations.length) { + object.mutations = []; + for (var j = 0; j < message.mutations.length; ++j) + object.mutations[j] = $root.google.spanner.v1.Mutation.toObject(message.mutations[j], options); + } + return object; + }; + + /** + * Converts this MutationGroup to JSON. + * @function toJSON + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @instance + * @returns {Object.} JSON object + */ + MutationGroup.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MutationGroup + * @function getTypeUrl + * @memberof google.spanner.v1.BatchWriteRequest.MutationGroup + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MutationGroup.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.BatchWriteRequest.MutationGroup"; + }; + + return MutationGroup; + })(); + + return BatchWriteRequest; + })(); + + v1.BatchWriteResponse = (function() { + + /** + * Properties of a BatchWriteResponse. + * @memberof google.spanner.v1 + * @interface IBatchWriteResponse + * @property {Array.|null} [indexes] BatchWriteResponse indexes + * @property {google.rpc.IStatus|null} [status] BatchWriteResponse status + * @property {google.protobuf.ITimestamp|null} [commitTimestamp] BatchWriteResponse commitTimestamp + */ + + /** + * Constructs a new BatchWriteResponse. + * @memberof google.spanner.v1 + * @classdesc Represents a BatchWriteResponse. + * @implements IBatchWriteResponse + * @constructor + * @param {google.spanner.v1.IBatchWriteResponse=} [properties] Properties to set + */ + function BatchWriteResponse(properties) { + this.indexes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchWriteResponse indexes. + * @member {Array.} indexes + * @memberof google.spanner.v1.BatchWriteResponse + * @instance + */ + BatchWriteResponse.prototype.indexes = $util.emptyArray; + + /** + * BatchWriteResponse status. + * @member {google.rpc.IStatus|null|undefined} status + * @memberof google.spanner.v1.BatchWriteResponse + * @instance + */ + BatchWriteResponse.prototype.status = null; + + /** + * BatchWriteResponse commitTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} commitTimestamp + * @memberof google.spanner.v1.BatchWriteResponse + * @instance + */ + BatchWriteResponse.prototype.commitTimestamp = null; + + /** + * Creates a new BatchWriteResponse instance using the specified properties. + * @function create + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {google.spanner.v1.IBatchWriteResponse=} [properties] Properties to set + * @returns {google.spanner.v1.BatchWriteResponse} BatchWriteResponse instance + */ + BatchWriteResponse.create = function create(properties) { + return new BatchWriteResponse(properties); + }; + + /** + * Encodes the specified BatchWriteResponse message. Does not implicitly {@link google.spanner.v1.BatchWriteResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {google.spanner.v1.IBatchWriteResponse} message BatchWriteResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchWriteResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.indexes != null && message.indexes.length) { + writer.uint32(/* id 1, wireType 2 =*/10).fork(); + for (var i = 0; i < message.indexes.length; ++i) + writer.int32(message.indexes[i]); + writer.ldelim(); + } + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + $root.google.rpc.Status.encode(message.status, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.commitTimestamp != null && Object.hasOwnProperty.call(message, "commitTimestamp")) + $root.google.protobuf.Timestamp.encode(message.commitTimestamp, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BatchWriteResponse message, length delimited. Does not implicitly {@link google.spanner.v1.BatchWriteResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {google.spanner.v1.IBatchWriteResponse} message BatchWriteResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchWriteResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BatchWriteResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.BatchWriteResponse} BatchWriteResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchWriteResponse.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.spanner.v1.BatchWriteResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.indexes && message.indexes.length)) + message.indexes = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.indexes.push(reader.int32()); + } else + message.indexes.push(reader.int32()); + break; + } + case 2: { + message.status = $root.google.rpc.Status.decode(reader, reader.uint32()); + break; + } + case 3: { + message.commitTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BatchWriteResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.BatchWriteResponse} BatchWriteResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchWriteResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BatchWriteResponse message. + * @function verify + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BatchWriteResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.indexes != null && message.hasOwnProperty("indexes")) { + if (!Array.isArray(message.indexes)) + return "indexes: array expected"; + for (var i = 0; i < message.indexes.length; ++i) + if (!$util.isInteger(message.indexes[i])) + return "indexes: integer[] expected"; + } + if (message.status != null && message.hasOwnProperty("status")) { + var error = $root.google.rpc.Status.verify(message.status); + if (error) + return "status." + error; + } + if (message.commitTimestamp != null && message.hasOwnProperty("commitTimestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.commitTimestamp); + if (error) + return "commitTimestamp." + error; + } + return null; + }; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.BatchWriteResponse} BatchWriteResponse + */ + BatchWriteResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.BatchWriteResponse) + return object; + var message = new $root.google.spanner.v1.BatchWriteResponse(); + if (object.indexes) { + if (!Array.isArray(object.indexes)) + throw TypeError(".google.spanner.v1.BatchWriteResponse.indexes: array expected"); + message.indexes = []; + for (var i = 0; i < object.indexes.length; ++i) + message.indexes[i] = object.indexes[i] | 0; + } + if (object.status != null) { + if (typeof object.status !== "object") + throw TypeError(".google.spanner.v1.BatchWriteResponse.status: object expected"); + message.status = $root.google.rpc.Status.fromObject(object.status); + } + if (object.commitTimestamp != null) { + if (typeof object.commitTimestamp !== "object") + throw TypeError(".google.spanner.v1.BatchWriteResponse.commitTimestamp: object expected"); + message.commitTimestamp = $root.google.protobuf.Timestamp.fromObject(object.commitTimestamp); + } + return message; + }; + + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {google.spanner.v1.BatchWriteResponse} message BatchWriteResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchWriteResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.indexes = []; + if (options.defaults) { + object.status = null; + object.commitTimestamp = null; + } + if (message.indexes && message.indexes.length) { + object.indexes = []; + for (var j = 0; j < message.indexes.length; ++j) + object.indexes[j] = message.indexes[j]; + } + if (message.status != null && message.hasOwnProperty("status")) + object.status = $root.google.rpc.Status.toObject(message.status, options); + if (message.commitTimestamp != null && message.hasOwnProperty("commitTimestamp")) + object.commitTimestamp = $root.google.protobuf.Timestamp.toObject(message.commitTimestamp, options); + return object; + }; + + /** + * Converts this BatchWriteResponse to JSON. + * @function toJSON + * @memberof google.spanner.v1.BatchWriteResponse + * @instance + * @returns {Object.} JSON object + */ + BatchWriteResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchWriteResponse + * @function getTypeUrl + * @memberof google.spanner.v1.BatchWriteResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchWriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.BatchWriteResponse"; + }; + + return BatchWriteResponse; + })(); + + v1.CommitResponse = (function() { + + /** + * Properties of a CommitResponse. + * @memberof google.spanner.v1 + * @interface ICommitResponse + * @property {google.protobuf.ITimestamp|null} [commitTimestamp] CommitResponse commitTimestamp + * @property {google.spanner.v1.CommitResponse.ICommitStats|null} [commitStats] CommitResponse commitStats + * @property {google.spanner.v1.IMultiplexedSessionPrecommitToken|null} [precommitToken] CommitResponse precommitToken + * @property {google.protobuf.ITimestamp|null} [snapshotTimestamp] CommitResponse snapshotTimestamp + */ + + /** + * Constructs a new CommitResponse. + * @memberof google.spanner.v1 + * @classdesc Represents a CommitResponse. + * @implements ICommitResponse + * @constructor + * @param {google.spanner.v1.ICommitResponse=} [properties] Properties to set + */ + function CommitResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommitResponse commitTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} commitTimestamp + * @memberof google.spanner.v1.CommitResponse + * @instance + */ + CommitResponse.prototype.commitTimestamp = null; + + /** + * CommitResponse commitStats. + * @member {google.spanner.v1.CommitResponse.ICommitStats|null|undefined} commitStats + * @memberof google.spanner.v1.CommitResponse + * @instance + */ + CommitResponse.prototype.commitStats = null; + + /** + * CommitResponse precommitToken. + * @member {google.spanner.v1.IMultiplexedSessionPrecommitToken|null|undefined} precommitToken + * @memberof google.spanner.v1.CommitResponse + * @instance + */ + CommitResponse.prototype.precommitToken = null; + + /** + * CommitResponse snapshotTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} snapshotTimestamp + * @memberof google.spanner.v1.CommitResponse + * @instance + */ + CommitResponse.prototype.snapshotTimestamp = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * CommitResponse MultiplexedSessionRetry. + * @member {"precommitToken"|undefined} MultiplexedSessionRetry + * @memberof google.spanner.v1.CommitResponse + * @instance + */ + Object.defineProperty(CommitResponse.prototype, "MultiplexedSessionRetry", { + get: $util.oneOfGetter($oneOfFields = ["precommitToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new CommitResponse instance using the specified properties. + * @function create + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {google.spanner.v1.ICommitResponse=} [properties] Properties to set + * @returns {google.spanner.v1.CommitResponse} CommitResponse instance + */ + CommitResponse.create = function create(properties) { + return new CommitResponse(properties); + }; + + /** + * Encodes the specified CommitResponse message. Does not implicitly {@link google.spanner.v1.CommitResponse.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {google.spanner.v1.ICommitResponse} message CommitResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CommitResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.commitTimestamp != null && Object.hasOwnProperty.call(message, "commitTimestamp")) + $root.google.protobuf.Timestamp.encode(message.commitTimestamp, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.commitStats != null && Object.hasOwnProperty.call(message, "commitStats")) + $root.google.spanner.v1.CommitResponse.CommitStats.encode(message.commitStats, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.precommitToken != null && Object.hasOwnProperty.call(message, "precommitToken")) + $root.google.spanner.v1.MultiplexedSessionPrecommitToken.encode(message.precommitToken, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.snapshotTimestamp != null && Object.hasOwnProperty.call(message, "snapshotTimestamp")) + $root.google.protobuf.Timestamp.encode(message.snapshotTimestamp, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CommitResponse message, length delimited. Does not implicitly {@link google.spanner.v1.CommitResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {google.spanner.v1.ICommitResponse} message CommitResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CommitResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CommitResponse message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.CommitResponse} CommitResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CommitResponse.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.spanner.v1.CommitResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.commitTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.commitStats = $root.google.spanner.v1.CommitResponse.CommitStats.decode(reader, reader.uint32()); + break; + } + case 4: { + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.decode(reader, reader.uint32()); + break; + } + case 5: { + message.snapshotTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CommitResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.CommitResponse} CommitResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CommitResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CommitResponse message. + * @function verify + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CommitResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.commitTimestamp != null && message.hasOwnProperty("commitTimestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.commitTimestamp); + if (error) + return "commitTimestamp." + error; + } + if (message.commitStats != null && message.hasOwnProperty("commitStats")) { + var error = $root.google.spanner.v1.CommitResponse.CommitStats.verify(message.commitStats); + if (error) + return "commitStats." + error; + } + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) { + properties.MultiplexedSessionRetry = 1; + { + var error = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.verify(message.precommitToken); + if (error) + return "precommitToken." + error; + } + } + if (message.snapshotTimestamp != null && message.hasOwnProperty("snapshotTimestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.snapshotTimestamp); + if (error) + return "snapshotTimestamp." + error; + } + return null; + }; + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.CommitResponse} CommitResponse + */ + CommitResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.CommitResponse) + return object; + var message = new $root.google.spanner.v1.CommitResponse(); + if (object.commitTimestamp != null) { + if (typeof object.commitTimestamp !== "object") + throw TypeError(".google.spanner.v1.CommitResponse.commitTimestamp: object expected"); + message.commitTimestamp = $root.google.protobuf.Timestamp.fromObject(object.commitTimestamp); + } + if (object.commitStats != null) { + if (typeof object.commitStats !== "object") + throw TypeError(".google.spanner.v1.CommitResponse.commitStats: object expected"); + message.commitStats = $root.google.spanner.v1.CommitResponse.CommitStats.fromObject(object.commitStats); + } + if (object.precommitToken != null) { + if (typeof object.precommitToken !== "object") + throw TypeError(".google.spanner.v1.CommitResponse.precommitToken: object expected"); + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.fromObject(object.precommitToken); + } + if (object.snapshotTimestamp != null) { + if (typeof object.snapshotTimestamp !== "object") + throw TypeError(".google.spanner.v1.CommitResponse.snapshotTimestamp: object expected"); + message.snapshotTimestamp = $root.google.protobuf.Timestamp.fromObject(object.snapshotTimestamp); + } + return message; + }; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {google.spanner.v1.CommitResponse} message CommitResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.commitTimestamp = null; + object.commitStats = null; + object.snapshotTimestamp = null; + } + if (message.commitTimestamp != null && message.hasOwnProperty("commitTimestamp")) + object.commitTimestamp = $root.google.protobuf.Timestamp.toObject(message.commitTimestamp, options); + if (message.commitStats != null && message.hasOwnProperty("commitStats")) + object.commitStats = $root.google.spanner.v1.CommitResponse.CommitStats.toObject(message.commitStats, options); + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) { + object.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.toObject(message.precommitToken, options); + if (options.oneofs) + object.MultiplexedSessionRetry = "precommitToken"; + } + if (message.snapshotTimestamp != null && message.hasOwnProperty("snapshotTimestamp")) + object.snapshotTimestamp = $root.google.protobuf.Timestamp.toObject(message.snapshotTimestamp, options); + return object; + }; + + /** + * Converts this CommitResponse to JSON. + * @function toJSON + * @memberof google.spanner.v1.CommitResponse + * @instance + * @returns {Object.} JSON object + */ + CommitResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitResponse + * @function getTypeUrl + * @memberof google.spanner.v1.CommitResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.CommitResponse"; + }; + + CommitResponse.CommitStats = (function() { + + /** + * Properties of a CommitStats. + * @memberof google.spanner.v1.CommitResponse + * @interface ICommitStats + * @property {number|Long|null} [mutationCount] CommitStats mutationCount + */ + + /** + * Constructs a new CommitStats. + * @memberof google.spanner.v1.CommitResponse + * @classdesc Represents a CommitStats. + * @implements ICommitStats + * @constructor + * @param {google.spanner.v1.CommitResponse.ICommitStats=} [properties] Properties to set + */ + function CommitStats(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommitStats mutationCount. + * @member {number|Long} mutationCount + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @instance + */ + CommitStats.prototype.mutationCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new CommitStats instance using the specified properties. + * @function create + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {google.spanner.v1.CommitResponse.ICommitStats=} [properties] Properties to set + * @returns {google.spanner.v1.CommitResponse.CommitStats} CommitStats instance + */ + CommitStats.create = function create(properties) { + return new CommitStats(properties); + }; + + /** + * Encodes the specified CommitStats message. Does not implicitly {@link google.spanner.v1.CommitResponse.CommitStats.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {google.spanner.v1.CommitResponse.ICommitStats} message CommitStats message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CommitStats.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.mutationCount != null && Object.hasOwnProperty.call(message, "mutationCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.mutationCount); + return writer; + }; + + /** + * Encodes the specified CommitStats message, length delimited. Does not implicitly {@link google.spanner.v1.CommitResponse.CommitStats.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {google.spanner.v1.CommitResponse.ICommitStats} message CommitStats message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CommitStats.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CommitStats message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.CommitResponse.CommitStats} CommitStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CommitStats.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.spanner.v1.CommitResponse.CommitStats(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.mutationCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CommitStats message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.CommitResponse.CommitStats} CommitStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CommitStats.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CommitStats message. + * @function verify + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CommitStats.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.mutationCount != null && message.hasOwnProperty("mutationCount")) + if (!$util.isInteger(message.mutationCount) && !(message.mutationCount && $util.isInteger(message.mutationCount.low) && $util.isInteger(message.mutationCount.high))) + return "mutationCount: integer|Long expected"; + return null; + }; + + /** + * Creates a CommitStats message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.CommitResponse.CommitStats} CommitStats + */ + CommitStats.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.CommitResponse.CommitStats) + return object; + var message = new $root.google.spanner.v1.CommitResponse.CommitStats(); + if (object.mutationCount != null) + if ($util.Long) + (message.mutationCount = $util.Long.fromValue(object.mutationCount)).unsigned = false; + else if (typeof object.mutationCount === "string") + message.mutationCount = parseInt(object.mutationCount, 10); + else if (typeof object.mutationCount === "number") + message.mutationCount = object.mutationCount; + else if (typeof object.mutationCount === "object") + message.mutationCount = new $util.LongBits(object.mutationCount.low >>> 0, object.mutationCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a CommitStats message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {google.spanner.v1.CommitResponse.CommitStats} message CommitStats + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitStats.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.mutationCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.mutationCount = options.longs === String ? "0" : 0; + if (message.mutationCount != null && message.hasOwnProperty("mutationCount")) + if (typeof message.mutationCount === "number") + object.mutationCount = options.longs === String ? String(message.mutationCount) : message.mutationCount; + else + object.mutationCount = options.longs === String ? $util.Long.prototype.toString.call(message.mutationCount) : options.longs === Number ? new $util.LongBits(message.mutationCount.low >>> 0, message.mutationCount.high >>> 0).toNumber() : message.mutationCount; + return object; + }; + + /** + * Converts this CommitStats to JSON. + * @function toJSON + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @instance + * @returns {Object.} JSON object + */ + CommitStats.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitStats + * @function getTypeUrl + * @memberof google.spanner.v1.CommitResponse.CommitStats + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitStats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.CommitResponse.CommitStats"; + }; + + return CommitStats; + })(); + + return CommitResponse; + })(); + + v1.TransactionOptions = (function() { + + /** + * Properties of a TransactionOptions. + * @memberof google.spanner.v1 + * @interface ITransactionOptions + * @property {google.spanner.v1.TransactionOptions.IReadWrite|null} [readWrite] TransactionOptions readWrite + * @property {google.spanner.v1.TransactionOptions.IPartitionedDml|null} [partitionedDml] TransactionOptions partitionedDml + * @property {google.spanner.v1.TransactionOptions.IReadOnly|null} [readOnly] TransactionOptions readOnly + * @property {boolean|null} [excludeTxnFromChangeStreams] TransactionOptions excludeTxnFromChangeStreams + * @property {google.spanner.v1.TransactionOptions.IsolationLevel|null} [isolationLevel] TransactionOptions isolationLevel + */ + + /** + * Constructs a new TransactionOptions. + * @memberof google.spanner.v1 + * @classdesc Represents a TransactionOptions. + * @implements ITransactionOptions + * @constructor + * @param {google.spanner.v1.ITransactionOptions=} [properties] Properties to set + */ + function TransactionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TransactionOptions readWrite. + * @member {google.spanner.v1.TransactionOptions.IReadWrite|null|undefined} readWrite + * @memberof google.spanner.v1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.readWrite = null; + + /** + * TransactionOptions partitionedDml. + * @member {google.spanner.v1.TransactionOptions.IPartitionedDml|null|undefined} partitionedDml + * @memberof google.spanner.v1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.partitionedDml = null; + + /** + * TransactionOptions readOnly. + * @member {google.spanner.v1.TransactionOptions.IReadOnly|null|undefined} readOnly + * @memberof google.spanner.v1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.readOnly = null; + + /** + * TransactionOptions excludeTxnFromChangeStreams. + * @member {boolean} excludeTxnFromChangeStreams + * @memberof google.spanner.v1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.excludeTxnFromChangeStreams = false; + + /** + * TransactionOptions isolationLevel. + * @member {google.spanner.v1.TransactionOptions.IsolationLevel} isolationLevel + * @memberof google.spanner.v1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.isolationLevel = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * TransactionOptions mode. + * @member {"readWrite"|"partitionedDml"|"readOnly"|undefined} mode + * @memberof google.spanner.v1.TransactionOptions + * @instance + */ + Object.defineProperty(TransactionOptions.prototype, "mode", { + get: $util.oneOfGetter($oneOfFields = ["readWrite", "partitionedDml", "readOnly"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new TransactionOptions instance using the specified properties. + * @function create + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {google.spanner.v1.ITransactionOptions=} [properties] Properties to set + * @returns {google.spanner.v1.TransactionOptions} TransactionOptions instance + */ + TransactionOptions.create = function create(properties) { + return new TransactionOptions(properties); + }; + + /** + * Encodes the specified TransactionOptions message. Does not implicitly {@link google.spanner.v1.TransactionOptions.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {google.spanner.v1.ITransactionOptions} message TransactionOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TransactionOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.readWrite != null && Object.hasOwnProperty.call(message, "readWrite")) + $root.google.spanner.v1.TransactionOptions.ReadWrite.encode(message.readWrite, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.readOnly != null && Object.hasOwnProperty.call(message, "readOnly")) + $root.google.spanner.v1.TransactionOptions.ReadOnly.encode(message.readOnly, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.partitionedDml != null && Object.hasOwnProperty.call(message, "partitionedDml")) + $root.google.spanner.v1.TransactionOptions.PartitionedDml.encode(message.partitionedDml, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.excludeTxnFromChangeStreams != null && Object.hasOwnProperty.call(message, "excludeTxnFromChangeStreams")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.excludeTxnFromChangeStreams); + if (message.isolationLevel != null && Object.hasOwnProperty.call(message, "isolationLevel")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.isolationLevel); + return writer; + }; + + /** + * Encodes the specified TransactionOptions message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {google.spanner.v1.ITransactionOptions} message TransactionOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TransactionOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TransactionOptions message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.TransactionOptions} TransactionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TransactionOptions.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.spanner.v1.TransactionOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.readWrite = $root.google.spanner.v1.TransactionOptions.ReadWrite.decode(reader, reader.uint32()); + break; + } + case 3: { + message.partitionedDml = $root.google.spanner.v1.TransactionOptions.PartitionedDml.decode(reader, reader.uint32()); + break; + } + case 2: { + message.readOnly = $root.google.spanner.v1.TransactionOptions.ReadOnly.decode(reader, reader.uint32()); + break; + } + case 5: { + message.excludeTxnFromChangeStreams = reader.bool(); + break; + } + case 6: { + message.isolationLevel = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TransactionOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.TransactionOptions} TransactionOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TransactionOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TransactionOptions message. + * @function verify + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TransactionOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.readWrite != null && message.hasOwnProperty("readWrite")) { + properties.mode = 1; + { + var error = $root.google.spanner.v1.TransactionOptions.ReadWrite.verify(message.readWrite); + if (error) + return "readWrite." + error; + } + } + if (message.partitionedDml != null && message.hasOwnProperty("partitionedDml")) { + if (properties.mode === 1) + return "mode: multiple values"; + properties.mode = 1; + { + var error = $root.google.spanner.v1.TransactionOptions.PartitionedDml.verify(message.partitionedDml); + if (error) + return "partitionedDml." + error; + } + } + if (message.readOnly != null && message.hasOwnProperty("readOnly")) { + if (properties.mode === 1) + return "mode: multiple values"; + properties.mode = 1; + { + var error = $root.google.spanner.v1.TransactionOptions.ReadOnly.verify(message.readOnly); + if (error) + return "readOnly." + error; + } + } + if (message.excludeTxnFromChangeStreams != null && message.hasOwnProperty("excludeTxnFromChangeStreams")) + if (typeof message.excludeTxnFromChangeStreams !== "boolean") + return "excludeTxnFromChangeStreams: boolean expected"; + if (message.isolationLevel != null && message.hasOwnProperty("isolationLevel")) + switch (message.isolationLevel) { + default: + return "isolationLevel: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.TransactionOptions} TransactionOptions + */ + TransactionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.TransactionOptions) + return object; + var message = new $root.google.spanner.v1.TransactionOptions(); + if (object.readWrite != null) { + if (typeof object.readWrite !== "object") + throw TypeError(".google.spanner.v1.TransactionOptions.readWrite: object expected"); + message.readWrite = $root.google.spanner.v1.TransactionOptions.ReadWrite.fromObject(object.readWrite); + } + if (object.partitionedDml != null) { + if (typeof object.partitionedDml !== "object") + throw TypeError(".google.spanner.v1.TransactionOptions.partitionedDml: object expected"); + message.partitionedDml = $root.google.spanner.v1.TransactionOptions.PartitionedDml.fromObject(object.partitionedDml); + } + if (object.readOnly != null) { + if (typeof object.readOnly !== "object") + throw TypeError(".google.spanner.v1.TransactionOptions.readOnly: object expected"); + message.readOnly = $root.google.spanner.v1.TransactionOptions.ReadOnly.fromObject(object.readOnly); + } + if (object.excludeTxnFromChangeStreams != null) + message.excludeTxnFromChangeStreams = Boolean(object.excludeTxnFromChangeStreams); + switch (object.isolationLevel) { + default: + if (typeof object.isolationLevel === "number") { + message.isolationLevel = object.isolationLevel; + break; + } + break; + case "ISOLATION_LEVEL_UNSPECIFIED": + case 0: + message.isolationLevel = 0; + break; + case "SERIALIZABLE": + case 1: + message.isolationLevel = 1; + break; + case "REPEATABLE_READ": + case 2: + message.isolationLevel = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {google.spanner.v1.TransactionOptions} message TransactionOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TransactionOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.excludeTxnFromChangeStreams = false; + object.isolationLevel = options.enums === String ? "ISOLATION_LEVEL_UNSPECIFIED" : 0; + } + if (message.readWrite != null && message.hasOwnProperty("readWrite")) { + object.readWrite = $root.google.spanner.v1.TransactionOptions.ReadWrite.toObject(message.readWrite, options); + if (options.oneofs) + object.mode = "readWrite"; + } + if (message.readOnly != null && message.hasOwnProperty("readOnly")) { + object.readOnly = $root.google.spanner.v1.TransactionOptions.ReadOnly.toObject(message.readOnly, options); + if (options.oneofs) + object.mode = "readOnly"; + } + if (message.partitionedDml != null && message.hasOwnProperty("partitionedDml")) { + object.partitionedDml = $root.google.spanner.v1.TransactionOptions.PartitionedDml.toObject(message.partitionedDml, options); + if (options.oneofs) + object.mode = "partitionedDml"; + } + if (message.excludeTxnFromChangeStreams != null && message.hasOwnProperty("excludeTxnFromChangeStreams")) + object.excludeTxnFromChangeStreams = message.excludeTxnFromChangeStreams; + if (message.isolationLevel != null && message.hasOwnProperty("isolationLevel")) + object.isolationLevel = options.enums === String ? $root.google.spanner.v1.TransactionOptions.IsolationLevel[message.isolationLevel] === undefined ? message.isolationLevel : $root.google.spanner.v1.TransactionOptions.IsolationLevel[message.isolationLevel] : message.isolationLevel; + return object; + }; + + /** + * Converts this TransactionOptions to JSON. + * @function toJSON + * @memberof google.spanner.v1.TransactionOptions + * @instance + * @returns {Object.} JSON object + */ + TransactionOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TransactionOptions + * @function getTypeUrl + * @memberof google.spanner.v1.TransactionOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TransactionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.TransactionOptions"; + }; + + TransactionOptions.ReadWrite = (function() { + + /** + * Properties of a ReadWrite. + * @memberof google.spanner.v1.TransactionOptions + * @interface IReadWrite + * @property {google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode|null} [readLockMode] ReadWrite readLockMode + * @property {Uint8Array|null} [multiplexedSessionPreviousTransactionId] ReadWrite multiplexedSessionPreviousTransactionId + */ + + /** + * Constructs a new ReadWrite. + * @memberof google.spanner.v1.TransactionOptions + * @classdesc Represents a ReadWrite. + * @implements IReadWrite + * @constructor + * @param {google.spanner.v1.TransactionOptions.IReadWrite=} [properties] Properties to set + */ + function ReadWrite(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadWrite readLockMode. + * @member {google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode} readLockMode + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @instance + */ + ReadWrite.prototype.readLockMode = 0; + + /** + * ReadWrite multiplexedSessionPreviousTransactionId. + * @member {Uint8Array} multiplexedSessionPreviousTransactionId + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @instance + */ + ReadWrite.prototype.multiplexedSessionPreviousTransactionId = $util.newBuffer([]); + + /** + * Creates a new ReadWrite instance using the specified properties. + * @function create + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {google.spanner.v1.TransactionOptions.IReadWrite=} [properties] Properties to set + * @returns {google.spanner.v1.TransactionOptions.ReadWrite} ReadWrite instance + */ + ReadWrite.create = function create(properties) { + return new ReadWrite(properties); + }; + + /** + * Encodes the specified ReadWrite message. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadWrite.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {google.spanner.v1.TransactionOptions.IReadWrite} message ReadWrite message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadWrite.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.readLockMode != null && Object.hasOwnProperty.call(message, "readLockMode")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.readLockMode); + if (message.multiplexedSessionPreviousTransactionId != null && Object.hasOwnProperty.call(message, "multiplexedSessionPreviousTransactionId")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.multiplexedSessionPreviousTransactionId); + return writer; + }; + + /** + * Encodes the specified ReadWrite message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadWrite.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {google.spanner.v1.TransactionOptions.IReadWrite} message ReadWrite message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadWrite.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadWrite message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.TransactionOptions.ReadWrite} ReadWrite + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadWrite.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.spanner.v1.TransactionOptions.ReadWrite(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.readLockMode = reader.int32(); + break; + } + case 2: { + message.multiplexedSessionPreviousTransactionId = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReadWrite message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.TransactionOptions.ReadWrite} ReadWrite + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadWrite.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadWrite message. + * @function verify + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadWrite.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.readLockMode != null && message.hasOwnProperty("readLockMode")) + switch (message.readLockMode) { + default: + return "readLockMode: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.multiplexedSessionPreviousTransactionId != null && message.hasOwnProperty("multiplexedSessionPreviousTransactionId")) + if (!(message.multiplexedSessionPreviousTransactionId && typeof message.multiplexedSessionPreviousTransactionId.length === "number" || $util.isString(message.multiplexedSessionPreviousTransactionId))) + return "multiplexedSessionPreviousTransactionId: buffer expected"; + return null; + }; + + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.TransactionOptions.ReadWrite} ReadWrite + */ + ReadWrite.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.TransactionOptions.ReadWrite) + return object; + var message = new $root.google.spanner.v1.TransactionOptions.ReadWrite(); + switch (object.readLockMode) { + default: + if (typeof object.readLockMode === "number") { + message.readLockMode = object.readLockMode; + break; + } + break; + case "READ_LOCK_MODE_UNSPECIFIED": + case 0: + message.readLockMode = 0; + break; + case "PESSIMISTIC": + case 1: + message.readLockMode = 1; + break; + case "OPTIMISTIC": + case 2: + message.readLockMode = 2; + break; + } + if (object.multiplexedSessionPreviousTransactionId != null) + if (typeof object.multiplexedSessionPreviousTransactionId === "string") + $util.base64.decode(object.multiplexedSessionPreviousTransactionId, message.multiplexedSessionPreviousTransactionId = $util.newBuffer($util.base64.length(object.multiplexedSessionPreviousTransactionId)), 0); + else if (object.multiplexedSessionPreviousTransactionId.length >= 0) + message.multiplexedSessionPreviousTransactionId = object.multiplexedSessionPreviousTransactionId; + return message; + }; + + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {google.spanner.v1.TransactionOptions.ReadWrite} message ReadWrite + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadWrite.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.readLockMode = options.enums === String ? "READ_LOCK_MODE_UNSPECIFIED" : 0; + if (options.bytes === String) + object.multiplexedSessionPreviousTransactionId = ""; + else { + object.multiplexedSessionPreviousTransactionId = []; + if (options.bytes !== Array) + object.multiplexedSessionPreviousTransactionId = $util.newBuffer(object.multiplexedSessionPreviousTransactionId); + } + } + if (message.readLockMode != null && message.hasOwnProperty("readLockMode")) + object.readLockMode = options.enums === String ? $root.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode[message.readLockMode] === undefined ? message.readLockMode : $root.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode[message.readLockMode] : message.readLockMode; + if (message.multiplexedSessionPreviousTransactionId != null && message.hasOwnProperty("multiplexedSessionPreviousTransactionId")) + object.multiplexedSessionPreviousTransactionId = options.bytes === String ? $util.base64.encode(message.multiplexedSessionPreviousTransactionId, 0, message.multiplexedSessionPreviousTransactionId.length) : options.bytes === Array ? Array.prototype.slice.call(message.multiplexedSessionPreviousTransactionId) : message.multiplexedSessionPreviousTransactionId; + return object; + }; + + /** + * Converts this ReadWrite to JSON. + * @function toJSON + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @instance + * @returns {Object.} JSON object + */ + ReadWrite.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadWrite + * @function getTypeUrl + * @memberof google.spanner.v1.TransactionOptions.ReadWrite + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadWrite.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.TransactionOptions.ReadWrite"; + }; + + /** + * ReadLockMode enum. + * @name google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode + * @enum {number} + * @property {number} READ_LOCK_MODE_UNSPECIFIED=0 READ_LOCK_MODE_UNSPECIFIED value + * @property {number} PESSIMISTIC=1 PESSIMISTIC value + * @property {number} OPTIMISTIC=2 OPTIMISTIC value + */ + ReadWrite.ReadLockMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "READ_LOCK_MODE_UNSPECIFIED"] = 0; + values[valuesById[1] = "PESSIMISTIC"] = 1; + values[valuesById[2] = "OPTIMISTIC"] = 2; + return values; + })(); + + return ReadWrite; + })(); + + TransactionOptions.PartitionedDml = (function() { + + /** + * Properties of a PartitionedDml. + * @memberof google.spanner.v1.TransactionOptions + * @interface IPartitionedDml + */ + + /** + * Constructs a new PartitionedDml. + * @memberof google.spanner.v1.TransactionOptions + * @classdesc Represents a PartitionedDml. + * @implements IPartitionedDml + * @constructor + * @param {google.spanner.v1.TransactionOptions.IPartitionedDml=} [properties] Properties to set + */ + function PartitionedDml(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new PartitionedDml instance using the specified properties. + * @function create + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {google.spanner.v1.TransactionOptions.IPartitionedDml=} [properties] Properties to set + * @returns {google.spanner.v1.TransactionOptions.PartitionedDml} PartitionedDml instance + */ + PartitionedDml.create = function create(properties) { + return new PartitionedDml(properties); + }; + + /** + * Encodes the specified PartitionedDml message. Does not implicitly {@link google.spanner.v1.TransactionOptions.PartitionedDml.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {google.spanner.v1.TransactionOptions.IPartitionedDml} message PartitionedDml message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionedDml.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified PartitionedDml message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.PartitionedDml.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {google.spanner.v1.TransactionOptions.IPartitionedDml} message PartitionedDml message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionedDml.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionedDml message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.TransactionOptions.PartitionedDml} PartitionedDml + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionedDml.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.spanner.v1.TransactionOptions.PartitionedDml(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionedDml message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.TransactionOptions.PartitionedDml} PartitionedDml + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionedDml.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionedDml message. + * @function verify + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionedDml.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a PartitionedDml message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.TransactionOptions.PartitionedDml} PartitionedDml + */ + PartitionedDml.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.TransactionOptions.PartitionedDml) + return object; + return new $root.google.spanner.v1.TransactionOptions.PartitionedDml(); + }; + + /** + * Creates a plain object from a PartitionedDml message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {google.spanner.v1.TransactionOptions.PartitionedDml} message PartitionedDml + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionedDml.toObject = function toObject() { + return {}; + }; + + /** + * Converts this PartitionedDml to JSON. + * @function toJSON + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @instance + * @returns {Object.} JSON object + */ + PartitionedDml.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionedDml + * @function getTypeUrl + * @memberof google.spanner.v1.TransactionOptions.PartitionedDml + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionedDml.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.TransactionOptions.PartitionedDml"; + }; + + return PartitionedDml; + })(); + + TransactionOptions.ReadOnly = (function() { + + /** + * Properties of a ReadOnly. + * @memberof google.spanner.v1.TransactionOptions + * @interface IReadOnly + * @property {boolean|null} [strong] ReadOnly strong + * @property {google.protobuf.ITimestamp|null} [minReadTimestamp] ReadOnly minReadTimestamp + * @property {google.protobuf.IDuration|null} [maxStaleness] ReadOnly maxStaleness + * @property {google.protobuf.ITimestamp|null} [readTimestamp] ReadOnly readTimestamp + * @property {google.protobuf.IDuration|null} [exactStaleness] ReadOnly exactStaleness + * @property {boolean|null} [returnReadTimestamp] ReadOnly returnReadTimestamp + */ + + /** + * Constructs a new ReadOnly. + * @memberof google.spanner.v1.TransactionOptions + * @classdesc Represents a ReadOnly. + * @implements IReadOnly + * @constructor + * @param {google.spanner.v1.TransactionOptions.IReadOnly=} [properties] Properties to set + */ + function ReadOnly(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadOnly strong. + * @member {boolean|null|undefined} strong + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.strong = null; + + /** + * ReadOnly minReadTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} minReadTimestamp + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.minReadTimestamp = null; + + /** + * ReadOnly maxStaleness. + * @member {google.protobuf.IDuration|null|undefined} maxStaleness + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.maxStaleness = null; + + /** + * ReadOnly readTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} readTimestamp + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.readTimestamp = null; + + /** + * ReadOnly exactStaleness. + * @member {google.protobuf.IDuration|null|undefined} exactStaleness + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.exactStaleness = null; + + /** + * ReadOnly returnReadTimestamp. + * @member {boolean} returnReadTimestamp + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.returnReadTimestamp = false; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ReadOnly timestampBound. + * @member {"strong"|"minReadTimestamp"|"maxStaleness"|"readTimestamp"|"exactStaleness"|undefined} timestampBound + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @instance + */ + Object.defineProperty(ReadOnly.prototype, "timestampBound", { + get: $util.oneOfGetter($oneOfFields = ["strong", "minReadTimestamp", "maxStaleness", "readTimestamp", "exactStaleness"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReadOnly instance using the specified properties. + * @function create + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {google.spanner.v1.TransactionOptions.IReadOnly=} [properties] Properties to set + * @returns {google.spanner.v1.TransactionOptions.ReadOnly} ReadOnly instance + */ + ReadOnly.create = function create(properties) { + return new ReadOnly(properties); + }; + + /** + * Encodes the specified ReadOnly message. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadOnly.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {google.spanner.v1.TransactionOptions.IReadOnly} message ReadOnly message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadOnly.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.strong != null && Object.hasOwnProperty.call(message, "strong")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.strong); + if (message.minReadTimestamp != null && Object.hasOwnProperty.call(message, "minReadTimestamp")) + $root.google.protobuf.Timestamp.encode(message.minReadTimestamp, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.maxStaleness != null && Object.hasOwnProperty.call(message, "maxStaleness")) + $root.google.protobuf.Duration.encode(message.maxStaleness, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.readTimestamp != null && Object.hasOwnProperty.call(message, "readTimestamp")) + $root.google.protobuf.Timestamp.encode(message.readTimestamp, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.exactStaleness != null && Object.hasOwnProperty.call(message, "exactStaleness")) + $root.google.protobuf.Duration.encode(message.exactStaleness, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.returnReadTimestamp != null && Object.hasOwnProperty.call(message, "returnReadTimestamp")) + writer.uint32(/* id 6, wireType 0 =*/48).bool(message.returnReadTimestamp); + return writer; + }; + + /** + * Encodes the specified ReadOnly message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadOnly.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {google.spanner.v1.TransactionOptions.IReadOnly} message ReadOnly message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadOnly.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadOnly message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.TransactionOptions.ReadOnly} ReadOnly + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadOnly.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.spanner.v1.TransactionOptions.ReadOnly(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.strong = reader.bool(); + break; + } + case 2: { + message.minReadTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.maxStaleness = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + case 4: { + message.readTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 5: { + message.exactStaleness = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + case 6: { + message.returnReadTimestamp = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReadOnly message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.TransactionOptions.ReadOnly} ReadOnly + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadOnly.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadOnly message. + * @function verify + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadOnly.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.strong != null && message.hasOwnProperty("strong")) { + properties.timestampBound = 1; + if (typeof message.strong !== "boolean") + return "strong: boolean expected"; + } + if (message.minReadTimestamp != null && message.hasOwnProperty("minReadTimestamp")) { + if (properties.timestampBound === 1) + return "timestampBound: multiple values"; + properties.timestampBound = 1; + { + var error = $root.google.protobuf.Timestamp.verify(message.minReadTimestamp); + if (error) + return "minReadTimestamp." + error; + } + } + if (message.maxStaleness != null && message.hasOwnProperty("maxStaleness")) { + if (properties.timestampBound === 1) + return "timestampBound: multiple values"; + properties.timestampBound = 1; + { + var error = $root.google.protobuf.Duration.verify(message.maxStaleness); + if (error) + return "maxStaleness." + error; + } + } + if (message.readTimestamp != null && message.hasOwnProperty("readTimestamp")) { + if (properties.timestampBound === 1) + return "timestampBound: multiple values"; + properties.timestampBound = 1; + { + var error = $root.google.protobuf.Timestamp.verify(message.readTimestamp); + if (error) + return "readTimestamp." + error; + } + } + if (message.exactStaleness != null && message.hasOwnProperty("exactStaleness")) { + if (properties.timestampBound === 1) + return "timestampBound: multiple values"; + properties.timestampBound = 1; + { + var error = $root.google.protobuf.Duration.verify(message.exactStaleness); + if (error) + return "exactStaleness." + error; + } + } + if (message.returnReadTimestamp != null && message.hasOwnProperty("returnReadTimestamp")) + if (typeof message.returnReadTimestamp !== "boolean") + return "returnReadTimestamp: boolean expected"; + return null; + }; + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.TransactionOptions.ReadOnly} ReadOnly + */ + ReadOnly.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.TransactionOptions.ReadOnly) + return object; + var message = new $root.google.spanner.v1.TransactionOptions.ReadOnly(); + if (object.strong != null) + message.strong = Boolean(object.strong); + if (object.minReadTimestamp != null) { + if (typeof object.minReadTimestamp !== "object") + throw TypeError(".google.spanner.v1.TransactionOptions.ReadOnly.minReadTimestamp: object expected"); + message.minReadTimestamp = $root.google.protobuf.Timestamp.fromObject(object.minReadTimestamp); + } + if (object.maxStaleness != null) { + if (typeof object.maxStaleness !== "object") + throw TypeError(".google.spanner.v1.TransactionOptions.ReadOnly.maxStaleness: object expected"); + message.maxStaleness = $root.google.protobuf.Duration.fromObject(object.maxStaleness); + } + if (object.readTimestamp != null) { + if (typeof object.readTimestamp !== "object") + throw TypeError(".google.spanner.v1.TransactionOptions.ReadOnly.readTimestamp: object expected"); + message.readTimestamp = $root.google.protobuf.Timestamp.fromObject(object.readTimestamp); + } + if (object.exactStaleness != null) { + if (typeof object.exactStaleness !== "object") + throw TypeError(".google.spanner.v1.TransactionOptions.ReadOnly.exactStaleness: object expected"); + message.exactStaleness = $root.google.protobuf.Duration.fromObject(object.exactStaleness); + } + if (object.returnReadTimestamp != null) + message.returnReadTimestamp = Boolean(object.returnReadTimestamp); + return message; + }; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {google.spanner.v1.TransactionOptions.ReadOnly} message ReadOnly + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadOnly.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.returnReadTimestamp = false; + if (message.strong != null && message.hasOwnProperty("strong")) { + object.strong = message.strong; + if (options.oneofs) + object.timestampBound = "strong"; + } + if (message.minReadTimestamp != null && message.hasOwnProperty("minReadTimestamp")) { + object.minReadTimestamp = $root.google.protobuf.Timestamp.toObject(message.minReadTimestamp, options); + if (options.oneofs) + object.timestampBound = "minReadTimestamp"; + } + if (message.maxStaleness != null && message.hasOwnProperty("maxStaleness")) { + object.maxStaleness = $root.google.protobuf.Duration.toObject(message.maxStaleness, options); + if (options.oneofs) + object.timestampBound = "maxStaleness"; + } + if (message.readTimestamp != null && message.hasOwnProperty("readTimestamp")) { + object.readTimestamp = $root.google.protobuf.Timestamp.toObject(message.readTimestamp, options); + if (options.oneofs) + object.timestampBound = "readTimestamp"; + } + if (message.exactStaleness != null && message.hasOwnProperty("exactStaleness")) { + object.exactStaleness = $root.google.protobuf.Duration.toObject(message.exactStaleness, options); + if (options.oneofs) + object.timestampBound = "exactStaleness"; + } + if (message.returnReadTimestamp != null && message.hasOwnProperty("returnReadTimestamp")) + object.returnReadTimestamp = message.returnReadTimestamp; + return object; + }; + + /** + * Converts this ReadOnly to JSON. + * @function toJSON + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @instance + * @returns {Object.} JSON object + */ + ReadOnly.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadOnly + * @function getTypeUrl + * @memberof google.spanner.v1.TransactionOptions.ReadOnly + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadOnly.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.TransactionOptions.ReadOnly"; + }; + + return ReadOnly; + })(); + + /** + * IsolationLevel enum. + * @name google.spanner.v1.TransactionOptions.IsolationLevel + * @enum {number} + * @property {number} ISOLATION_LEVEL_UNSPECIFIED=0 ISOLATION_LEVEL_UNSPECIFIED value + * @property {number} SERIALIZABLE=1 SERIALIZABLE value + * @property {number} REPEATABLE_READ=2 REPEATABLE_READ value + */ + TransactionOptions.IsolationLevel = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ISOLATION_LEVEL_UNSPECIFIED"] = 0; + values[valuesById[1] = "SERIALIZABLE"] = 1; + values[valuesById[2] = "REPEATABLE_READ"] = 2; + return values; + })(); + + return TransactionOptions; + })(); + + v1.Transaction = (function() { + + /** + * Properties of a Transaction. + * @memberof google.spanner.v1 + * @interface ITransaction + * @property {Uint8Array|null} [id] Transaction id + * @property {google.protobuf.ITimestamp|null} [readTimestamp] Transaction readTimestamp + * @property {google.spanner.v1.IMultiplexedSessionPrecommitToken|null} [precommitToken] Transaction precommitToken + */ + + /** + * Constructs a new Transaction. + * @memberof google.spanner.v1 + * @classdesc Represents a Transaction. + * @implements ITransaction + * @constructor + * @param {google.spanner.v1.ITransaction=} [properties] Properties to set + */ + function Transaction(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Transaction id. + * @member {Uint8Array} id + * @memberof google.spanner.v1.Transaction + * @instance + */ + Transaction.prototype.id = $util.newBuffer([]); + + /** + * Transaction readTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} readTimestamp + * @memberof google.spanner.v1.Transaction + * @instance + */ + Transaction.prototype.readTimestamp = null; + + /** + * Transaction precommitToken. + * @member {google.spanner.v1.IMultiplexedSessionPrecommitToken|null|undefined} precommitToken + * @memberof google.spanner.v1.Transaction + * @instance + */ + Transaction.prototype.precommitToken = null; + + /** + * Creates a new Transaction instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Transaction + * @static + * @param {google.spanner.v1.ITransaction=} [properties] Properties to set + * @returns {google.spanner.v1.Transaction} Transaction instance + */ + Transaction.create = function create(properties) { + return new Transaction(properties); + }; + + /** + * Encodes the specified Transaction message. Does not implicitly {@link google.spanner.v1.Transaction.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Transaction + * @static + * @param {google.spanner.v1.ITransaction} message Transaction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Transaction.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.id); + if (message.readTimestamp != null && Object.hasOwnProperty.call(message, "readTimestamp")) + $root.google.protobuf.Timestamp.encode(message.readTimestamp, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.precommitToken != null && Object.hasOwnProperty.call(message, "precommitToken")) + $root.google.spanner.v1.MultiplexedSessionPrecommitToken.encode(message.precommitToken, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Transaction message, length delimited. Does not implicitly {@link google.spanner.v1.Transaction.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Transaction + * @static + * @param {google.spanner.v1.ITransaction} message Transaction message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Transaction.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Transaction message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Transaction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Transaction} Transaction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Transaction.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.spanner.v1.Transaction(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.id = reader.bytes(); + break; + } + case 2: { + message.readTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 3: { + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Transaction message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Transaction + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Transaction} Transaction + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Transaction.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Transaction message. + * @function verify + * @memberof google.spanner.v1.Transaction + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Transaction.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.id != null && message.hasOwnProperty("id")) + if (!(message.id && typeof message.id.length === "number" || $util.isString(message.id))) + return "id: buffer expected"; + if (message.readTimestamp != null && message.hasOwnProperty("readTimestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.readTimestamp); + if (error) + return "readTimestamp." + error; + } + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) { + var error = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.verify(message.precommitToken); + if (error) + return "precommitToken." + error; + } + return null; + }; + + /** + * Creates a Transaction message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Transaction + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Transaction} Transaction + */ + Transaction.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Transaction) + return object; + var message = new $root.google.spanner.v1.Transaction(); + if (object.id != null) + if (typeof object.id === "string") + $util.base64.decode(object.id, message.id = $util.newBuffer($util.base64.length(object.id)), 0); + else if (object.id.length >= 0) + message.id = object.id; + if (object.readTimestamp != null) { + if (typeof object.readTimestamp !== "object") + throw TypeError(".google.spanner.v1.Transaction.readTimestamp: object expected"); + message.readTimestamp = $root.google.protobuf.Timestamp.fromObject(object.readTimestamp); + } + if (object.precommitToken != null) { + if (typeof object.precommitToken !== "object") + throw TypeError(".google.spanner.v1.Transaction.precommitToken: object expected"); + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.fromObject(object.precommitToken); + } + return message; + }; + + /** + * Creates a plain object from a Transaction message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Transaction + * @static + * @param {google.spanner.v1.Transaction} message Transaction + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Transaction.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if (options.bytes === String) + object.id = ""; + else { + object.id = []; + if (options.bytes !== Array) + object.id = $util.newBuffer(object.id); + } + object.readTimestamp = null; + object.precommitToken = null; + } + if (message.id != null && message.hasOwnProperty("id")) + object.id = options.bytes === String ? $util.base64.encode(message.id, 0, message.id.length) : options.bytes === Array ? Array.prototype.slice.call(message.id) : message.id; + if (message.readTimestamp != null && message.hasOwnProperty("readTimestamp")) + object.readTimestamp = $root.google.protobuf.Timestamp.toObject(message.readTimestamp, options); + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) + object.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.toObject(message.precommitToken, options); + return object; + }; + + /** + * Converts this Transaction to JSON. + * @function toJSON + * @memberof google.spanner.v1.Transaction + * @instance + * @returns {Object.} JSON object + */ + Transaction.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Transaction + * @function getTypeUrl + * @memberof google.spanner.v1.Transaction + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Transaction.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Transaction"; + }; + + return Transaction; + })(); + + v1.TransactionSelector = (function() { + + /** + * Properties of a TransactionSelector. + * @memberof google.spanner.v1 + * @interface ITransactionSelector + * @property {google.spanner.v1.ITransactionOptions|null} [singleUse] TransactionSelector singleUse + * @property {Uint8Array|null} [id] TransactionSelector id + * @property {google.spanner.v1.ITransactionOptions|null} [begin] TransactionSelector begin + */ + + /** + * Constructs a new TransactionSelector. + * @memberof google.spanner.v1 + * @classdesc Represents a TransactionSelector. + * @implements ITransactionSelector + * @constructor + * @param {google.spanner.v1.ITransactionSelector=} [properties] Properties to set + */ + function TransactionSelector(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TransactionSelector singleUse. + * @member {google.spanner.v1.ITransactionOptions|null|undefined} singleUse + * @memberof google.spanner.v1.TransactionSelector + * @instance + */ + TransactionSelector.prototype.singleUse = null; + + /** + * TransactionSelector id. + * @member {Uint8Array|null|undefined} id + * @memberof google.spanner.v1.TransactionSelector + * @instance + */ + TransactionSelector.prototype.id = null; + + /** + * TransactionSelector begin. + * @member {google.spanner.v1.ITransactionOptions|null|undefined} begin + * @memberof google.spanner.v1.TransactionSelector + * @instance + */ + TransactionSelector.prototype.begin = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * TransactionSelector selector. + * @member {"singleUse"|"id"|"begin"|undefined} selector + * @memberof google.spanner.v1.TransactionSelector + * @instance + */ + Object.defineProperty(TransactionSelector.prototype, "selector", { + get: $util.oneOfGetter($oneOfFields = ["singleUse", "id", "begin"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new TransactionSelector instance using the specified properties. + * @function create + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {google.spanner.v1.ITransactionSelector=} [properties] Properties to set + * @returns {google.spanner.v1.TransactionSelector} TransactionSelector instance + */ + TransactionSelector.create = function create(properties) { + return new TransactionSelector(properties); + }; + + /** + * Encodes the specified TransactionSelector message. Does not implicitly {@link google.spanner.v1.TransactionSelector.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {google.spanner.v1.ITransactionSelector} message TransactionSelector message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TransactionSelector.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.singleUse != null && Object.hasOwnProperty.call(message, "singleUse")) + $root.google.spanner.v1.TransactionOptions.encode(message.singleUse, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.id); + if (message.begin != null && Object.hasOwnProperty.call(message, "begin")) + $root.google.spanner.v1.TransactionOptions.encode(message.begin, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified TransactionSelector message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionSelector.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {google.spanner.v1.ITransactionSelector} message TransactionSelector message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TransactionSelector.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TransactionSelector message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.TransactionSelector} TransactionSelector + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TransactionSelector.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.spanner.v1.TransactionSelector(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.singleUse = $root.google.spanner.v1.TransactionOptions.decode(reader, reader.uint32()); + break; + } + case 2: { + message.id = reader.bytes(); + break; + } + case 3: { + message.begin = $root.google.spanner.v1.TransactionOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TransactionSelector message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.TransactionSelector} TransactionSelector + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TransactionSelector.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TransactionSelector message. + * @function verify + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TransactionSelector.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.singleUse != null && message.hasOwnProperty("singleUse")) { + properties.selector = 1; + { + var error = $root.google.spanner.v1.TransactionOptions.verify(message.singleUse); + if (error) + return "singleUse." + error; + } + } + if (message.id != null && message.hasOwnProperty("id")) { + if (properties.selector === 1) + return "selector: multiple values"; + properties.selector = 1; + if (!(message.id && typeof message.id.length === "number" || $util.isString(message.id))) + return "id: buffer expected"; + } + if (message.begin != null && message.hasOwnProperty("begin")) { + if (properties.selector === 1) + return "selector: multiple values"; + properties.selector = 1; + { + var error = $root.google.spanner.v1.TransactionOptions.verify(message.begin); + if (error) + return "begin." + error; + } + } + return null; + }; + + /** + * Creates a TransactionSelector message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.TransactionSelector} TransactionSelector + */ + TransactionSelector.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.TransactionSelector) + return object; + var message = new $root.google.spanner.v1.TransactionSelector(); + if (object.singleUse != null) { + if (typeof object.singleUse !== "object") + throw TypeError(".google.spanner.v1.TransactionSelector.singleUse: object expected"); + message.singleUse = $root.google.spanner.v1.TransactionOptions.fromObject(object.singleUse); + } + if (object.id != null) + if (typeof object.id === "string") + $util.base64.decode(object.id, message.id = $util.newBuffer($util.base64.length(object.id)), 0); + else if (object.id.length >= 0) + message.id = object.id; + if (object.begin != null) { + if (typeof object.begin !== "object") + throw TypeError(".google.spanner.v1.TransactionSelector.begin: object expected"); + message.begin = $root.google.spanner.v1.TransactionOptions.fromObject(object.begin); + } + return message; + }; + + /** + * Creates a plain object from a TransactionSelector message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {google.spanner.v1.TransactionSelector} message TransactionSelector + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TransactionSelector.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.singleUse != null && message.hasOwnProperty("singleUse")) { + object.singleUse = $root.google.spanner.v1.TransactionOptions.toObject(message.singleUse, options); + if (options.oneofs) + object.selector = "singleUse"; + } + if (message.id != null && message.hasOwnProperty("id")) { + object.id = options.bytes === String ? $util.base64.encode(message.id, 0, message.id.length) : options.bytes === Array ? Array.prototype.slice.call(message.id) : message.id; + if (options.oneofs) + object.selector = "id"; + } + if (message.begin != null && message.hasOwnProperty("begin")) { + object.begin = $root.google.spanner.v1.TransactionOptions.toObject(message.begin, options); + if (options.oneofs) + object.selector = "begin"; + } + return object; + }; + + /** + * Converts this TransactionSelector to JSON. + * @function toJSON + * @memberof google.spanner.v1.TransactionSelector + * @instance + * @returns {Object.} JSON object + */ + TransactionSelector.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TransactionSelector + * @function getTypeUrl + * @memberof google.spanner.v1.TransactionSelector + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TransactionSelector.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.TransactionSelector"; + }; + + return TransactionSelector; + })(); + + v1.MultiplexedSessionPrecommitToken = (function() { + + /** + * Properties of a MultiplexedSessionPrecommitToken. + * @memberof google.spanner.v1 + * @interface IMultiplexedSessionPrecommitToken + * @property {Uint8Array|null} [precommitToken] MultiplexedSessionPrecommitToken precommitToken + * @property {number|null} [seqNum] MultiplexedSessionPrecommitToken seqNum + */ + + /** + * Constructs a new MultiplexedSessionPrecommitToken. + * @memberof google.spanner.v1 + * @classdesc Represents a MultiplexedSessionPrecommitToken. + * @implements IMultiplexedSessionPrecommitToken + * @constructor + * @param {google.spanner.v1.IMultiplexedSessionPrecommitToken=} [properties] Properties to set + */ + function MultiplexedSessionPrecommitToken(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MultiplexedSessionPrecommitToken precommitToken. + * @member {Uint8Array} precommitToken + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @instance + */ + MultiplexedSessionPrecommitToken.prototype.precommitToken = $util.newBuffer([]); + + /** + * MultiplexedSessionPrecommitToken seqNum. + * @member {number} seqNum + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @instance + */ + MultiplexedSessionPrecommitToken.prototype.seqNum = 0; + + /** + * Creates a new MultiplexedSessionPrecommitToken instance using the specified properties. + * @function create + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {google.spanner.v1.IMultiplexedSessionPrecommitToken=} [properties] Properties to set + * @returns {google.spanner.v1.MultiplexedSessionPrecommitToken} MultiplexedSessionPrecommitToken instance + */ + MultiplexedSessionPrecommitToken.create = function create(properties) { + return new MultiplexedSessionPrecommitToken(properties); + }; + + /** + * Encodes the specified MultiplexedSessionPrecommitToken message. Does not implicitly {@link google.spanner.v1.MultiplexedSessionPrecommitToken.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {google.spanner.v1.IMultiplexedSessionPrecommitToken} message MultiplexedSessionPrecommitToken message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MultiplexedSessionPrecommitToken.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.precommitToken != null && Object.hasOwnProperty.call(message, "precommitToken")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.precommitToken); + if (message.seqNum != null && Object.hasOwnProperty.call(message, "seqNum")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.seqNum); + return writer; + }; + + /** + * Encodes the specified MultiplexedSessionPrecommitToken message, length delimited. Does not implicitly {@link google.spanner.v1.MultiplexedSessionPrecommitToken.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {google.spanner.v1.IMultiplexedSessionPrecommitToken} message MultiplexedSessionPrecommitToken message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MultiplexedSessionPrecommitToken.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MultiplexedSessionPrecommitToken message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.MultiplexedSessionPrecommitToken} MultiplexedSessionPrecommitToken + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MultiplexedSessionPrecommitToken.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.spanner.v1.MultiplexedSessionPrecommitToken(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.precommitToken = reader.bytes(); + break; + } + case 2: { + message.seqNum = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MultiplexedSessionPrecommitToken message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.MultiplexedSessionPrecommitToken} MultiplexedSessionPrecommitToken + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MultiplexedSessionPrecommitToken.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MultiplexedSessionPrecommitToken message. + * @function verify + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MultiplexedSessionPrecommitToken.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) + if (!(message.precommitToken && typeof message.precommitToken.length === "number" || $util.isString(message.precommitToken))) + return "precommitToken: buffer expected"; + if (message.seqNum != null && message.hasOwnProperty("seqNum")) + if (!$util.isInteger(message.seqNum)) + return "seqNum: integer expected"; + return null; + }; + + /** + * Creates a MultiplexedSessionPrecommitToken message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.MultiplexedSessionPrecommitToken} MultiplexedSessionPrecommitToken + */ + MultiplexedSessionPrecommitToken.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.MultiplexedSessionPrecommitToken) + return object; + var message = new $root.google.spanner.v1.MultiplexedSessionPrecommitToken(); + if (object.precommitToken != null) + if (typeof object.precommitToken === "string") + $util.base64.decode(object.precommitToken, message.precommitToken = $util.newBuffer($util.base64.length(object.precommitToken)), 0); + else if (object.precommitToken.length >= 0) + message.precommitToken = object.precommitToken; + if (object.seqNum != null) + message.seqNum = object.seqNum | 0; + return message; + }; + + /** + * Creates a plain object from a MultiplexedSessionPrecommitToken message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {google.spanner.v1.MultiplexedSessionPrecommitToken} message MultiplexedSessionPrecommitToken + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MultiplexedSessionPrecommitToken.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if (options.bytes === String) + object.precommitToken = ""; + else { + object.precommitToken = []; + if (options.bytes !== Array) + object.precommitToken = $util.newBuffer(object.precommitToken); + } + object.seqNum = 0; + } + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) + object.precommitToken = options.bytes === String ? $util.base64.encode(message.precommitToken, 0, message.precommitToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.precommitToken) : message.precommitToken; + if (message.seqNum != null && message.hasOwnProperty("seqNum")) + object.seqNum = message.seqNum; + return object; + }; + + /** + * Converts this MultiplexedSessionPrecommitToken to JSON. + * @function toJSON + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @instance + * @returns {Object.} JSON object + */ + MultiplexedSessionPrecommitToken.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MultiplexedSessionPrecommitToken + * @function getTypeUrl + * @memberof google.spanner.v1.MultiplexedSessionPrecommitToken + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MultiplexedSessionPrecommitToken.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.MultiplexedSessionPrecommitToken"; + }; + + return MultiplexedSessionPrecommitToken; + })(); + + v1.KeyRange = (function() { + + /** + * Properties of a KeyRange. + * @memberof google.spanner.v1 + * @interface IKeyRange + * @property {google.protobuf.IListValue|null} [startClosed] KeyRange startClosed + * @property {google.protobuf.IListValue|null} [startOpen] KeyRange startOpen + * @property {google.protobuf.IListValue|null} [endClosed] KeyRange endClosed + * @property {google.protobuf.IListValue|null} [endOpen] KeyRange endOpen + */ + + /** + * Constructs a new KeyRange. + * @memberof google.spanner.v1 + * @classdesc Represents a KeyRange. + * @implements IKeyRange + * @constructor + * @param {google.spanner.v1.IKeyRange=} [properties] Properties to set + */ + function KeyRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * KeyRange startClosed. + * @member {google.protobuf.IListValue|null|undefined} startClosed + * @memberof google.spanner.v1.KeyRange + * @instance + */ + KeyRange.prototype.startClosed = null; + + /** + * KeyRange startOpen. + * @member {google.protobuf.IListValue|null|undefined} startOpen + * @memberof google.spanner.v1.KeyRange + * @instance + */ + KeyRange.prototype.startOpen = null; + + /** + * KeyRange endClosed. + * @member {google.protobuf.IListValue|null|undefined} endClosed + * @memberof google.spanner.v1.KeyRange + * @instance + */ + KeyRange.prototype.endClosed = null; + + /** + * KeyRange endOpen. + * @member {google.protobuf.IListValue|null|undefined} endOpen + * @memberof google.spanner.v1.KeyRange + * @instance + */ + KeyRange.prototype.endOpen = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * KeyRange startKeyType. + * @member {"startClosed"|"startOpen"|undefined} startKeyType + * @memberof google.spanner.v1.KeyRange + * @instance + */ + Object.defineProperty(KeyRange.prototype, "startKeyType", { + get: $util.oneOfGetter($oneOfFields = ["startClosed", "startOpen"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * KeyRange endKeyType. + * @member {"endClosed"|"endOpen"|undefined} endKeyType + * @memberof google.spanner.v1.KeyRange + * @instance + */ + Object.defineProperty(KeyRange.prototype, "endKeyType", { + get: $util.oneOfGetter($oneOfFields = ["endClosed", "endOpen"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new KeyRange instance using the specified properties. + * @function create + * @memberof google.spanner.v1.KeyRange + * @static + * @param {google.spanner.v1.IKeyRange=} [properties] Properties to set + * @returns {google.spanner.v1.KeyRange} KeyRange instance + */ + KeyRange.create = function create(properties) { + return new KeyRange(properties); + }; + + /** + * Encodes the specified KeyRange message. Does not implicitly {@link google.spanner.v1.KeyRange.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.KeyRange + * @static + * @param {google.spanner.v1.IKeyRange} message KeyRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyRange.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.startClosed != null && Object.hasOwnProperty.call(message, "startClosed")) + $root.google.protobuf.ListValue.encode(message.startClosed, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.startOpen != null && Object.hasOwnProperty.call(message, "startOpen")) + $root.google.protobuf.ListValue.encode(message.startOpen, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.endClosed != null && Object.hasOwnProperty.call(message, "endClosed")) + $root.google.protobuf.ListValue.encode(message.endClosed, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.endOpen != null && Object.hasOwnProperty.call(message, "endOpen")) + $root.google.protobuf.ListValue.encode(message.endOpen, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified KeyRange message, length delimited. Does not implicitly {@link google.spanner.v1.KeyRange.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.KeyRange + * @static + * @param {google.spanner.v1.IKeyRange} message KeyRange message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyRange.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a KeyRange message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.KeyRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.KeyRange} KeyRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyRange.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.spanner.v1.KeyRange(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.startClosed = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); + break; + } + case 2: { + message.startOpen = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); + break; + } + case 3: { + message.endClosed = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); + break; + } + case 4: { + message.endOpen = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a KeyRange message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.KeyRange + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.KeyRange} KeyRange + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyRange.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a KeyRange message. + * @function verify + * @memberof google.spanner.v1.KeyRange + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + KeyRange.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.startClosed != null && message.hasOwnProperty("startClosed")) { + properties.startKeyType = 1; + { + var error = $root.google.protobuf.ListValue.verify(message.startClosed); + if (error) + return "startClosed." + error; + } + } + if (message.startOpen != null && message.hasOwnProperty("startOpen")) { + if (properties.startKeyType === 1) + return "startKeyType: multiple values"; + properties.startKeyType = 1; + { + var error = $root.google.protobuf.ListValue.verify(message.startOpen); + if (error) + return "startOpen." + error; + } + } + if (message.endClosed != null && message.hasOwnProperty("endClosed")) { + properties.endKeyType = 1; + { + var error = $root.google.protobuf.ListValue.verify(message.endClosed); + if (error) + return "endClosed." + error; + } + } + if (message.endOpen != null && message.hasOwnProperty("endOpen")) { + if (properties.endKeyType === 1) + return "endKeyType: multiple values"; + properties.endKeyType = 1; + { + var error = $root.google.protobuf.ListValue.verify(message.endOpen); + if (error) + return "endOpen." + error; + } + } + return null; + }; + + /** + * Creates a KeyRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.KeyRange + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.KeyRange} KeyRange + */ + KeyRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.KeyRange) + return object; + var message = new $root.google.spanner.v1.KeyRange(); + if (object.startClosed != null) { + if (typeof object.startClosed !== "object") + throw TypeError(".google.spanner.v1.KeyRange.startClosed: object expected"); + message.startClosed = $root.google.protobuf.ListValue.fromObject(object.startClosed); + } + if (object.startOpen != null) { + if (typeof object.startOpen !== "object") + throw TypeError(".google.spanner.v1.KeyRange.startOpen: object expected"); + message.startOpen = $root.google.protobuf.ListValue.fromObject(object.startOpen); + } + if (object.endClosed != null) { + if (typeof object.endClosed !== "object") + throw TypeError(".google.spanner.v1.KeyRange.endClosed: object expected"); + message.endClosed = $root.google.protobuf.ListValue.fromObject(object.endClosed); + } + if (object.endOpen != null) { + if (typeof object.endOpen !== "object") + throw TypeError(".google.spanner.v1.KeyRange.endOpen: object expected"); + message.endOpen = $root.google.protobuf.ListValue.fromObject(object.endOpen); + } + return message; + }; + + /** + * Creates a plain object from a KeyRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.KeyRange + * @static + * @param {google.spanner.v1.KeyRange} message KeyRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + KeyRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.startClosed != null && message.hasOwnProperty("startClosed")) { + object.startClosed = $root.google.protobuf.ListValue.toObject(message.startClosed, options); + if (options.oneofs) + object.startKeyType = "startClosed"; + } + if (message.startOpen != null && message.hasOwnProperty("startOpen")) { + object.startOpen = $root.google.protobuf.ListValue.toObject(message.startOpen, options); + if (options.oneofs) + object.startKeyType = "startOpen"; + } + if (message.endClosed != null && message.hasOwnProperty("endClosed")) { + object.endClosed = $root.google.protobuf.ListValue.toObject(message.endClosed, options); + if (options.oneofs) + object.endKeyType = "endClosed"; + } + if (message.endOpen != null && message.hasOwnProperty("endOpen")) { + object.endOpen = $root.google.protobuf.ListValue.toObject(message.endOpen, options); + if (options.oneofs) + object.endKeyType = "endOpen"; + } + return object; + }; + + /** + * Converts this KeyRange to JSON. + * @function toJSON + * @memberof google.spanner.v1.KeyRange + * @instance + * @returns {Object.} JSON object + */ + KeyRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for KeyRange + * @function getTypeUrl + * @memberof google.spanner.v1.KeyRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + KeyRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.KeyRange"; + }; + + return KeyRange; + })(); + + v1.KeySet = (function() { + + /** + * Properties of a KeySet. + * @memberof google.spanner.v1 + * @interface IKeySet + * @property {Array.|null} [keys] KeySet keys + * @property {Array.|null} [ranges] KeySet ranges + * @property {boolean|null} [all] KeySet all + */ + + /** + * Constructs a new KeySet. + * @memberof google.spanner.v1 + * @classdesc Represents a KeySet. + * @implements IKeySet + * @constructor + * @param {google.spanner.v1.IKeySet=} [properties] Properties to set + */ + function KeySet(properties) { + this.keys = []; + this.ranges = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * KeySet keys. + * @member {Array.} keys + * @memberof google.spanner.v1.KeySet + * @instance + */ + KeySet.prototype.keys = $util.emptyArray; + + /** + * KeySet ranges. + * @member {Array.} ranges + * @memberof google.spanner.v1.KeySet + * @instance + */ + KeySet.prototype.ranges = $util.emptyArray; + + /** + * KeySet all. + * @member {boolean} all + * @memberof google.spanner.v1.KeySet + * @instance + */ + KeySet.prototype.all = false; + + /** + * Creates a new KeySet instance using the specified properties. + * @function create + * @memberof google.spanner.v1.KeySet + * @static + * @param {google.spanner.v1.IKeySet=} [properties] Properties to set + * @returns {google.spanner.v1.KeySet} KeySet instance + */ + KeySet.create = function create(properties) { + return new KeySet(properties); + }; + + /** + * Encodes the specified KeySet message. Does not implicitly {@link google.spanner.v1.KeySet.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.KeySet + * @static + * @param {google.spanner.v1.IKeySet} message KeySet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeySet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.keys != null && message.keys.length) + for (var i = 0; i < message.keys.length; ++i) + $root.google.protobuf.ListValue.encode(message.keys[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.ranges != null && message.ranges.length) + for (var i = 0; i < message.ranges.length; ++i) + $root.google.spanner.v1.KeyRange.encode(message.ranges[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.all != null && Object.hasOwnProperty.call(message, "all")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.all); + return writer; + }; + + /** + * Encodes the specified KeySet message, length delimited. Does not implicitly {@link google.spanner.v1.KeySet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.KeySet + * @static + * @param {google.spanner.v1.IKeySet} message KeySet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeySet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a KeySet message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.KeySet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.KeySet} KeySet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeySet.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.spanner.v1.KeySet(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.keys && message.keys.length)) + message.keys = []; + message.keys.push($root.google.protobuf.ListValue.decode(reader, reader.uint32())); + break; + } + case 2: { + if (!(message.ranges && message.ranges.length)) + message.ranges = []; + message.ranges.push($root.google.spanner.v1.KeyRange.decode(reader, reader.uint32())); + break; + } + case 3: { + message.all = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a KeySet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.KeySet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.KeySet} KeySet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeySet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a KeySet message. + * @function verify + * @memberof google.spanner.v1.KeySet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + KeySet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.keys != null && message.hasOwnProperty("keys")) { + if (!Array.isArray(message.keys)) + return "keys: array expected"; + for (var i = 0; i < message.keys.length; ++i) { + var error = $root.google.protobuf.ListValue.verify(message.keys[i]); + if (error) + return "keys." + error; + } + } + if (message.ranges != null && message.hasOwnProperty("ranges")) { + if (!Array.isArray(message.ranges)) + return "ranges: array expected"; + for (var i = 0; i < message.ranges.length; ++i) { + var error = $root.google.spanner.v1.KeyRange.verify(message.ranges[i]); + if (error) + return "ranges." + error; + } + } + if (message.all != null && message.hasOwnProperty("all")) + if (typeof message.all !== "boolean") + return "all: boolean expected"; + return null; + }; + + /** + * Creates a KeySet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.KeySet + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.KeySet} KeySet + */ + KeySet.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.KeySet) + return object; + var message = new $root.google.spanner.v1.KeySet(); + if (object.keys) { + if (!Array.isArray(object.keys)) + throw TypeError(".google.spanner.v1.KeySet.keys: array expected"); + message.keys = []; + for (var i = 0; i < object.keys.length; ++i) { + if (typeof object.keys[i] !== "object") + throw TypeError(".google.spanner.v1.KeySet.keys: object expected"); + message.keys[i] = $root.google.protobuf.ListValue.fromObject(object.keys[i]); + } + } + if (object.ranges) { + if (!Array.isArray(object.ranges)) + throw TypeError(".google.spanner.v1.KeySet.ranges: array expected"); + message.ranges = []; + for (var i = 0; i < object.ranges.length; ++i) { + if (typeof object.ranges[i] !== "object") + throw TypeError(".google.spanner.v1.KeySet.ranges: object expected"); + message.ranges[i] = $root.google.spanner.v1.KeyRange.fromObject(object.ranges[i]); + } + } + if (object.all != null) + message.all = Boolean(object.all); + return message; + }; + + /** + * Creates a plain object from a KeySet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.KeySet + * @static + * @param {google.spanner.v1.KeySet} message KeySet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + KeySet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.keys = []; + object.ranges = []; + } + if (options.defaults) + object.all = false; + if (message.keys && message.keys.length) { + object.keys = []; + for (var j = 0; j < message.keys.length; ++j) + object.keys[j] = $root.google.protobuf.ListValue.toObject(message.keys[j], options); + } + if (message.ranges && message.ranges.length) { + object.ranges = []; + for (var j = 0; j < message.ranges.length; ++j) + object.ranges[j] = $root.google.spanner.v1.KeyRange.toObject(message.ranges[j], options); + } + if (message.all != null && message.hasOwnProperty("all")) + object.all = message.all; + return object; + }; + + /** + * Converts this KeySet to JSON. + * @function toJSON + * @memberof google.spanner.v1.KeySet + * @instance + * @returns {Object.} JSON object + */ + KeySet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for KeySet + * @function getTypeUrl + * @memberof google.spanner.v1.KeySet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + KeySet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.KeySet"; + }; + + return KeySet; + })(); + + v1.Range = (function() { + + /** + * Properties of a Range. + * @memberof google.spanner.v1 + * @interface IRange + * @property {Uint8Array|null} [startKey] Range startKey + * @property {Uint8Array|null} [limitKey] Range limitKey + * @property {number|Long|null} [groupUid] Range groupUid + * @property {number|Long|null} [splitId] Range splitId + * @property {Uint8Array|null} [generation] Range generation + */ + + /** + * Constructs a new Range. + * @memberof google.spanner.v1 + * @classdesc Represents a Range. + * @implements IRange + * @constructor + * @param {google.spanner.v1.IRange=} [properties] Properties to set + */ + function Range(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Range startKey. + * @member {Uint8Array} startKey + * @memberof google.spanner.v1.Range + * @instance + */ + Range.prototype.startKey = $util.newBuffer([]); + + /** + * Range limitKey. + * @member {Uint8Array} limitKey + * @memberof google.spanner.v1.Range + * @instance + */ + Range.prototype.limitKey = $util.newBuffer([]); + + /** + * Range groupUid. + * @member {number|Long} groupUid + * @memberof google.spanner.v1.Range + * @instance + */ + Range.prototype.groupUid = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * Range splitId. + * @member {number|Long} splitId + * @memberof google.spanner.v1.Range + * @instance + */ + Range.prototype.splitId = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * Range generation. + * @member {Uint8Array} generation + * @memberof google.spanner.v1.Range + * @instance + */ + Range.prototype.generation = $util.newBuffer([]); + + /** + * Creates a new Range instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Range + * @static + * @param {google.spanner.v1.IRange=} [properties] Properties to set + * @returns {google.spanner.v1.Range} Range instance + */ + Range.create = function create(properties) { + return new Range(properties); + }; + + /** + * Encodes the specified Range message. Does not implicitly {@link google.spanner.v1.Range.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Range + * @static + * @param {google.spanner.v1.IRange} message Range message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Range.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.startKey != null && Object.hasOwnProperty.call(message, "startKey")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.startKey); + if (message.limitKey != null && Object.hasOwnProperty.call(message, "limitKey")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.limitKey); + if (message.groupUid != null && Object.hasOwnProperty.call(message, "groupUid")) + writer.uint32(/* id 3, wireType 0 =*/24).uint64(message.groupUid); + if (message.splitId != null && Object.hasOwnProperty.call(message, "splitId")) + writer.uint32(/* id 4, wireType 0 =*/32).uint64(message.splitId); + if (message.generation != null && Object.hasOwnProperty.call(message, "generation")) + writer.uint32(/* id 5, wireType 2 =*/42).bytes(message.generation); + return writer; + }; + + /** + * Encodes the specified Range message, length delimited. Does not implicitly {@link google.spanner.v1.Range.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Range + * @static + * @param {google.spanner.v1.IRange} message Range message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Range.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Range message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Range + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Range} Range + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Range.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.spanner.v1.Range(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.startKey = reader.bytes(); + break; + } + case 2: { + message.limitKey = reader.bytes(); + break; + } + case 3: { + message.groupUid = reader.uint64(); + break; + } + case 4: { + message.splitId = reader.uint64(); + break; + } + case 5: { + message.generation = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Range message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Range + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Range} Range + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Range.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Range message. + * @function verify + * @memberof google.spanner.v1.Range + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Range.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.startKey != null && message.hasOwnProperty("startKey")) + if (!(message.startKey && typeof message.startKey.length === "number" || $util.isString(message.startKey))) + return "startKey: buffer expected"; + if (message.limitKey != null && message.hasOwnProperty("limitKey")) + if (!(message.limitKey && typeof message.limitKey.length === "number" || $util.isString(message.limitKey))) + return "limitKey: buffer expected"; + if (message.groupUid != null && message.hasOwnProperty("groupUid")) + if (!$util.isInteger(message.groupUid) && !(message.groupUid && $util.isInteger(message.groupUid.low) && $util.isInteger(message.groupUid.high))) + return "groupUid: integer|Long expected"; + if (message.splitId != null && message.hasOwnProperty("splitId")) + if (!$util.isInteger(message.splitId) && !(message.splitId && $util.isInteger(message.splitId.low) && $util.isInteger(message.splitId.high))) + return "splitId: integer|Long expected"; + if (message.generation != null && message.hasOwnProperty("generation")) + if (!(message.generation && typeof message.generation.length === "number" || $util.isString(message.generation))) + return "generation: buffer expected"; + return null; + }; + + /** + * Creates a Range message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Range + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Range} Range + */ + Range.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Range) + return object; + var message = new $root.google.spanner.v1.Range(); + if (object.startKey != null) + if (typeof object.startKey === "string") + $util.base64.decode(object.startKey, message.startKey = $util.newBuffer($util.base64.length(object.startKey)), 0); + else if (object.startKey.length >= 0) + message.startKey = object.startKey; + if (object.limitKey != null) + if (typeof object.limitKey === "string") + $util.base64.decode(object.limitKey, message.limitKey = $util.newBuffer($util.base64.length(object.limitKey)), 0); + else if (object.limitKey.length >= 0) + message.limitKey = object.limitKey; + if (object.groupUid != null) + if ($util.Long) + (message.groupUid = $util.Long.fromValue(object.groupUid)).unsigned = true; + else if (typeof object.groupUid === "string") + message.groupUid = parseInt(object.groupUid, 10); + else if (typeof object.groupUid === "number") + message.groupUid = object.groupUid; + else if (typeof object.groupUid === "object") + message.groupUid = new $util.LongBits(object.groupUid.low >>> 0, object.groupUid.high >>> 0).toNumber(true); + if (object.splitId != null) + if ($util.Long) + (message.splitId = $util.Long.fromValue(object.splitId)).unsigned = true; + else if (typeof object.splitId === "string") + message.splitId = parseInt(object.splitId, 10); + else if (typeof object.splitId === "number") + message.splitId = object.splitId; + else if (typeof object.splitId === "object") + message.splitId = new $util.LongBits(object.splitId.low >>> 0, object.splitId.high >>> 0).toNumber(true); + if (object.generation != null) + if (typeof object.generation === "string") + $util.base64.decode(object.generation, message.generation = $util.newBuffer($util.base64.length(object.generation)), 0); + else if (object.generation.length >= 0) + message.generation = object.generation; + return message; + }; + + /** + * Creates a plain object from a Range message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Range + * @static + * @param {google.spanner.v1.Range} message Range + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Range.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if (options.bytes === String) + object.startKey = ""; + else { + object.startKey = []; + if (options.bytes !== Array) + object.startKey = $util.newBuffer(object.startKey); + } + if (options.bytes === String) + object.limitKey = ""; + else { + object.limitKey = []; + if (options.bytes !== Array) + object.limitKey = $util.newBuffer(object.limitKey); + } + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.groupUid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.groupUid = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.splitId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.splitId = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.generation = ""; + else { + object.generation = []; + if (options.bytes !== Array) + object.generation = $util.newBuffer(object.generation); + } + } + if (message.startKey != null && message.hasOwnProperty("startKey")) + object.startKey = options.bytes === String ? $util.base64.encode(message.startKey, 0, message.startKey.length) : options.bytes === Array ? Array.prototype.slice.call(message.startKey) : message.startKey; + if (message.limitKey != null && message.hasOwnProperty("limitKey")) + object.limitKey = options.bytes === String ? $util.base64.encode(message.limitKey, 0, message.limitKey.length) : options.bytes === Array ? Array.prototype.slice.call(message.limitKey) : message.limitKey; + if (message.groupUid != null && message.hasOwnProperty("groupUid")) + if (typeof message.groupUid === "number") + object.groupUid = options.longs === String ? String(message.groupUid) : message.groupUid; + else + object.groupUid = options.longs === String ? $util.Long.prototype.toString.call(message.groupUid) : options.longs === Number ? new $util.LongBits(message.groupUid.low >>> 0, message.groupUid.high >>> 0).toNumber(true) : message.groupUid; + if (message.splitId != null && message.hasOwnProperty("splitId")) + if (typeof message.splitId === "number") + object.splitId = options.longs === String ? String(message.splitId) : message.splitId; + else + object.splitId = options.longs === String ? $util.Long.prototype.toString.call(message.splitId) : options.longs === Number ? new $util.LongBits(message.splitId.low >>> 0, message.splitId.high >>> 0).toNumber(true) : message.splitId; + if (message.generation != null && message.hasOwnProperty("generation")) + object.generation = options.bytes === String ? $util.base64.encode(message.generation, 0, message.generation.length) : options.bytes === Array ? Array.prototype.slice.call(message.generation) : message.generation; + return object; + }; + + /** + * Converts this Range to JSON. + * @function toJSON + * @memberof google.spanner.v1.Range + * @instance + * @returns {Object.} JSON object + */ + Range.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Range + * @function getTypeUrl + * @memberof google.spanner.v1.Range + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Range.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Range"; + }; + + return Range; + })(); + + v1.Tablet = (function() { + + /** + * Properties of a Tablet. + * @memberof google.spanner.v1 + * @interface ITablet + * @property {number|Long|null} [tabletUid] Tablet tabletUid + * @property {string|null} [serverAddress] Tablet serverAddress + * @property {string|null} [location] Tablet location + * @property {google.spanner.v1.Tablet.Role|null} [role] Tablet role + * @property {Uint8Array|null} [incarnation] Tablet incarnation + * @property {number|null} [distance] Tablet distance + * @property {boolean|null} [skip] Tablet skip + */ + + /** + * Constructs a new Tablet. + * @memberof google.spanner.v1 + * @classdesc Represents a Tablet. + * @implements ITablet + * @constructor + * @param {google.spanner.v1.ITablet=} [properties] Properties to set + */ + function Tablet(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Tablet tabletUid. + * @member {number|Long} tabletUid + * @memberof google.spanner.v1.Tablet + * @instance + */ + Tablet.prototype.tabletUid = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * Tablet serverAddress. + * @member {string} serverAddress + * @memberof google.spanner.v1.Tablet + * @instance + */ + Tablet.prototype.serverAddress = ""; + + /** + * Tablet location. + * @member {string} location + * @memberof google.spanner.v1.Tablet + * @instance + */ + Tablet.prototype.location = ""; + + /** + * Tablet role. + * @member {google.spanner.v1.Tablet.Role} role + * @memberof google.spanner.v1.Tablet + * @instance + */ + Tablet.prototype.role = 0; + + /** + * Tablet incarnation. + * @member {Uint8Array} incarnation + * @memberof google.spanner.v1.Tablet + * @instance + */ + Tablet.prototype.incarnation = $util.newBuffer([]); + + /** + * Tablet distance. + * @member {number} distance + * @memberof google.spanner.v1.Tablet + * @instance + */ + Tablet.prototype.distance = 0; + + /** + * Tablet skip. + * @member {boolean} skip + * @memberof google.spanner.v1.Tablet + * @instance + */ + Tablet.prototype.skip = false; + + /** + * Creates a new Tablet instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Tablet + * @static + * @param {google.spanner.v1.ITablet=} [properties] Properties to set + * @returns {google.spanner.v1.Tablet} Tablet instance + */ + Tablet.create = function create(properties) { + return new Tablet(properties); + }; + + /** + * Encodes the specified Tablet message. Does not implicitly {@link google.spanner.v1.Tablet.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Tablet + * @static + * @param {google.spanner.v1.ITablet} message Tablet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Tablet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.tabletUid != null && Object.hasOwnProperty.call(message, "tabletUid")) + writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.tabletUid); + if (message.serverAddress != null && Object.hasOwnProperty.call(message, "serverAddress")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.serverAddress); + if (message.location != null && Object.hasOwnProperty.call(message, "location")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.location); + if (message.role != null && Object.hasOwnProperty.call(message, "role")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.role); + if (message.incarnation != null && Object.hasOwnProperty.call(message, "incarnation")) + writer.uint32(/* id 5, wireType 2 =*/42).bytes(message.incarnation); + if (message.distance != null && Object.hasOwnProperty.call(message, "distance")) + writer.uint32(/* id 6, wireType 0 =*/48).uint32(message.distance); + if (message.skip != null && Object.hasOwnProperty.call(message, "skip")) + writer.uint32(/* id 7, wireType 0 =*/56).bool(message.skip); + return writer; + }; + + /** + * Encodes the specified Tablet message, length delimited. Does not implicitly {@link google.spanner.v1.Tablet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Tablet + * @static + * @param {google.spanner.v1.ITablet} message Tablet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Tablet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Tablet message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Tablet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Tablet} Tablet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Tablet.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.spanner.v1.Tablet(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.tabletUid = reader.uint64(); + break; + } + case 2: { + message.serverAddress = reader.string(); + break; + } + case 3: { + message.location = reader.string(); + break; + } + case 4: { + message.role = reader.int32(); + break; + } + case 5: { + message.incarnation = reader.bytes(); + break; + } + case 6: { + message.distance = reader.uint32(); + break; + } + case 7: { + message.skip = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Tablet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Tablet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Tablet} Tablet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Tablet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Tablet message. + * @function verify + * @memberof google.spanner.v1.Tablet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Tablet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.tabletUid != null && message.hasOwnProperty("tabletUid")) + if (!$util.isInteger(message.tabletUid) && !(message.tabletUid && $util.isInteger(message.tabletUid.low) && $util.isInteger(message.tabletUid.high))) + return "tabletUid: integer|Long expected"; + if (message.serverAddress != null && message.hasOwnProperty("serverAddress")) + if (!$util.isString(message.serverAddress)) + return "serverAddress: string expected"; + if (message.location != null && message.hasOwnProperty("location")) + if (!$util.isString(message.location)) + return "location: string expected"; + if (message.role != null && message.hasOwnProperty("role")) + switch (message.role) { + default: + return "role: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.incarnation != null && message.hasOwnProperty("incarnation")) + if (!(message.incarnation && typeof message.incarnation.length === "number" || $util.isString(message.incarnation))) + return "incarnation: buffer expected"; + if (message.distance != null && message.hasOwnProperty("distance")) + if (!$util.isInteger(message.distance)) + return "distance: integer expected"; + if (message.skip != null && message.hasOwnProperty("skip")) + if (typeof message.skip !== "boolean") + return "skip: boolean expected"; + return null; + }; + + /** + * Creates a Tablet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Tablet + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Tablet} Tablet + */ + Tablet.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Tablet) + return object; + var message = new $root.google.spanner.v1.Tablet(); + if (object.tabletUid != null) + if ($util.Long) + (message.tabletUid = $util.Long.fromValue(object.tabletUid)).unsigned = true; + else if (typeof object.tabletUid === "string") + message.tabletUid = parseInt(object.tabletUid, 10); + else if (typeof object.tabletUid === "number") + message.tabletUid = object.tabletUid; + else if (typeof object.tabletUid === "object") + message.tabletUid = new $util.LongBits(object.tabletUid.low >>> 0, object.tabletUid.high >>> 0).toNumber(true); + if (object.serverAddress != null) + message.serverAddress = String(object.serverAddress); + if (object.location != null) + message.location = String(object.location); + switch (object.role) { + default: + if (typeof object.role === "number") { + message.role = object.role; + break; + } + break; + case "ROLE_UNSPECIFIED": + case 0: + message.role = 0; + break; + case "READ_WRITE": + case 1: + message.role = 1; + break; + case "READ_ONLY": + case 2: + message.role = 2; + break; + } + if (object.incarnation != null) + if (typeof object.incarnation === "string") + $util.base64.decode(object.incarnation, message.incarnation = $util.newBuffer($util.base64.length(object.incarnation)), 0); + else if (object.incarnation.length >= 0) + message.incarnation = object.incarnation; + if (object.distance != null) + message.distance = object.distance >>> 0; + if (object.skip != null) + message.skip = Boolean(object.skip); + return message; + }; + + /** + * Creates a plain object from a Tablet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Tablet + * @static + * @param {google.spanner.v1.Tablet} message Tablet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Tablet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.tabletUid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.tabletUid = options.longs === String ? "0" : 0; + object.serverAddress = ""; + object.location = ""; + object.role = options.enums === String ? "ROLE_UNSPECIFIED" : 0; + if (options.bytes === String) + object.incarnation = ""; + else { + object.incarnation = []; + if (options.bytes !== Array) + object.incarnation = $util.newBuffer(object.incarnation); + } + object.distance = 0; + object.skip = false; + } + if (message.tabletUid != null && message.hasOwnProperty("tabletUid")) + if (typeof message.tabletUid === "number") + object.tabletUid = options.longs === String ? String(message.tabletUid) : message.tabletUid; + else + object.tabletUid = options.longs === String ? $util.Long.prototype.toString.call(message.tabletUid) : options.longs === Number ? new $util.LongBits(message.tabletUid.low >>> 0, message.tabletUid.high >>> 0).toNumber(true) : message.tabletUid; + if (message.serverAddress != null && message.hasOwnProperty("serverAddress")) + object.serverAddress = message.serverAddress; + if (message.location != null && message.hasOwnProperty("location")) + object.location = message.location; + if (message.role != null && message.hasOwnProperty("role")) + object.role = options.enums === String ? $root.google.spanner.v1.Tablet.Role[message.role] === undefined ? message.role : $root.google.spanner.v1.Tablet.Role[message.role] : message.role; + if (message.incarnation != null && message.hasOwnProperty("incarnation")) + object.incarnation = options.bytes === String ? $util.base64.encode(message.incarnation, 0, message.incarnation.length) : options.bytes === Array ? Array.prototype.slice.call(message.incarnation) : message.incarnation; + if (message.distance != null && message.hasOwnProperty("distance")) + object.distance = message.distance; + if (message.skip != null && message.hasOwnProperty("skip")) + object.skip = message.skip; + return object; + }; + + /** + * Converts this Tablet to JSON. + * @function toJSON + * @memberof google.spanner.v1.Tablet + * @instance + * @returns {Object.} JSON object + */ + Tablet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Tablet + * @function getTypeUrl + * @memberof google.spanner.v1.Tablet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Tablet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Tablet"; + }; + + /** + * Role enum. + * @name google.spanner.v1.Tablet.Role + * @enum {number} + * @property {number} ROLE_UNSPECIFIED=0 ROLE_UNSPECIFIED value + * @property {number} READ_WRITE=1 READ_WRITE value + * @property {number} READ_ONLY=2 READ_ONLY value + */ + Tablet.Role = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ROLE_UNSPECIFIED"] = 0; + values[valuesById[1] = "READ_WRITE"] = 1; + values[valuesById[2] = "READ_ONLY"] = 2; + return values; + })(); + + return Tablet; + })(); + + v1.Group = (function() { + + /** + * Properties of a Group. + * @memberof google.spanner.v1 + * @interface IGroup + * @property {number|Long|null} [groupUid] Group groupUid + * @property {Array.|null} [tablets] Group tablets + * @property {number|null} [leaderIndex] Group leaderIndex + * @property {Uint8Array|null} [generation] Group generation + */ + + /** + * Constructs a new Group. + * @memberof google.spanner.v1 + * @classdesc Represents a Group. + * @implements IGroup + * @constructor + * @param {google.spanner.v1.IGroup=} [properties] Properties to set + */ + function Group(properties) { + this.tablets = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Group groupUid. + * @member {number|Long} groupUid + * @memberof google.spanner.v1.Group + * @instance + */ + Group.prototype.groupUid = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * Group tablets. + * @member {Array.} tablets + * @memberof google.spanner.v1.Group + * @instance + */ + Group.prototype.tablets = $util.emptyArray; + + /** + * Group leaderIndex. + * @member {number} leaderIndex + * @memberof google.spanner.v1.Group + * @instance + */ + Group.prototype.leaderIndex = 0; + + /** + * Group generation. + * @member {Uint8Array} generation + * @memberof google.spanner.v1.Group + * @instance + */ + Group.prototype.generation = $util.newBuffer([]); + + /** + * Creates a new Group instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Group + * @static + * @param {google.spanner.v1.IGroup=} [properties] Properties to set + * @returns {google.spanner.v1.Group} Group instance + */ + Group.create = function create(properties) { + return new Group(properties); + }; + + /** + * Encodes the specified Group message. Does not implicitly {@link google.spanner.v1.Group.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Group + * @static + * @param {google.spanner.v1.IGroup} message Group message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Group.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.groupUid != null && Object.hasOwnProperty.call(message, "groupUid")) + writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.groupUid); + if (message.tablets != null && message.tablets.length) + for (var i = 0; i < message.tablets.length; ++i) + $root.google.spanner.v1.Tablet.encode(message.tablets[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.leaderIndex != null && Object.hasOwnProperty.call(message, "leaderIndex")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.leaderIndex); + if (message.generation != null && Object.hasOwnProperty.call(message, "generation")) + writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.generation); + return writer; + }; + + /** + * Encodes the specified Group message, length delimited. Does not implicitly {@link google.spanner.v1.Group.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Group + * @static + * @param {google.spanner.v1.IGroup} message Group message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Group.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Group message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Group + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Group} Group + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Group.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.spanner.v1.Group(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.groupUid = reader.uint64(); + break; + } + case 2: { + if (!(message.tablets && message.tablets.length)) + message.tablets = []; + message.tablets.push($root.google.spanner.v1.Tablet.decode(reader, reader.uint32())); + break; + } + case 3: { + message.leaderIndex = reader.int32(); + break; + } + case 4: { + message.generation = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Group message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Group + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Group} Group + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Group.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Group message. + * @function verify + * @memberof google.spanner.v1.Group + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Group.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.groupUid != null && message.hasOwnProperty("groupUid")) + if (!$util.isInteger(message.groupUid) && !(message.groupUid && $util.isInteger(message.groupUid.low) && $util.isInteger(message.groupUid.high))) + return "groupUid: integer|Long expected"; + if (message.tablets != null && message.hasOwnProperty("tablets")) { + if (!Array.isArray(message.tablets)) + return "tablets: array expected"; + for (var i = 0; i < message.tablets.length; ++i) { + var error = $root.google.spanner.v1.Tablet.verify(message.tablets[i]); + if (error) + return "tablets." + error; + } + } + if (message.leaderIndex != null && message.hasOwnProperty("leaderIndex")) + if (!$util.isInteger(message.leaderIndex)) + return "leaderIndex: integer expected"; + if (message.generation != null && message.hasOwnProperty("generation")) + if (!(message.generation && typeof message.generation.length === "number" || $util.isString(message.generation))) + return "generation: buffer expected"; + return null; + }; + + /** + * Creates a Group message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Group + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Group} Group + */ + Group.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Group) + return object; + var message = new $root.google.spanner.v1.Group(); + if (object.groupUid != null) + if ($util.Long) + (message.groupUid = $util.Long.fromValue(object.groupUid)).unsigned = true; + else if (typeof object.groupUid === "string") + message.groupUid = parseInt(object.groupUid, 10); + else if (typeof object.groupUid === "number") + message.groupUid = object.groupUid; + else if (typeof object.groupUid === "object") + message.groupUid = new $util.LongBits(object.groupUid.low >>> 0, object.groupUid.high >>> 0).toNumber(true); + if (object.tablets) { + if (!Array.isArray(object.tablets)) + throw TypeError(".google.spanner.v1.Group.tablets: array expected"); + message.tablets = []; + for (var i = 0; i < object.tablets.length; ++i) { + if (typeof object.tablets[i] !== "object") + throw TypeError(".google.spanner.v1.Group.tablets: object expected"); + message.tablets[i] = $root.google.spanner.v1.Tablet.fromObject(object.tablets[i]); + } + } + if (object.leaderIndex != null) + message.leaderIndex = object.leaderIndex | 0; + if (object.generation != null) + if (typeof object.generation === "string") + $util.base64.decode(object.generation, message.generation = $util.newBuffer($util.base64.length(object.generation)), 0); + else if (object.generation.length >= 0) + message.generation = object.generation; + return message; + }; + + /** + * Creates a plain object from a Group message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Group + * @static + * @param {google.spanner.v1.Group} message Group + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Group.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.tablets = []; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.groupUid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.groupUid = options.longs === String ? "0" : 0; + object.leaderIndex = 0; + if (options.bytes === String) + object.generation = ""; + else { + object.generation = []; + if (options.bytes !== Array) + object.generation = $util.newBuffer(object.generation); + } + } + if (message.groupUid != null && message.hasOwnProperty("groupUid")) + if (typeof message.groupUid === "number") + object.groupUid = options.longs === String ? String(message.groupUid) : message.groupUid; + else + object.groupUid = options.longs === String ? $util.Long.prototype.toString.call(message.groupUid) : options.longs === Number ? new $util.LongBits(message.groupUid.low >>> 0, message.groupUid.high >>> 0).toNumber(true) : message.groupUid; + if (message.tablets && message.tablets.length) { + object.tablets = []; + for (var j = 0; j < message.tablets.length; ++j) + object.tablets[j] = $root.google.spanner.v1.Tablet.toObject(message.tablets[j], options); + } + if (message.leaderIndex != null && message.hasOwnProperty("leaderIndex")) + object.leaderIndex = message.leaderIndex; + if (message.generation != null && message.hasOwnProperty("generation")) + object.generation = options.bytes === String ? $util.base64.encode(message.generation, 0, message.generation.length) : options.bytes === Array ? Array.prototype.slice.call(message.generation) : message.generation; + return object; + }; + + /** + * Converts this Group to JSON. + * @function toJSON + * @memberof google.spanner.v1.Group + * @instance + * @returns {Object.} JSON object + */ + Group.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Group + * @function getTypeUrl + * @memberof google.spanner.v1.Group + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Group.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Group"; + }; + + return Group; + })(); + + v1.KeyRecipe = (function() { + + /** + * Properties of a KeyRecipe. + * @memberof google.spanner.v1 + * @interface IKeyRecipe + * @property {string|null} [tableName] KeyRecipe tableName + * @property {string|null} [indexName] KeyRecipe indexName + * @property {number|Long|null} [operationUid] KeyRecipe operationUid + * @property {Array.|null} [part] KeyRecipe part + */ + + /** + * Constructs a new KeyRecipe. + * @memberof google.spanner.v1 + * @classdesc Represents a KeyRecipe. + * @implements IKeyRecipe + * @constructor + * @param {google.spanner.v1.IKeyRecipe=} [properties] Properties to set + */ + function KeyRecipe(properties) { + this.part = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * KeyRecipe tableName. + * @member {string|null|undefined} tableName + * @memberof google.spanner.v1.KeyRecipe + * @instance + */ + KeyRecipe.prototype.tableName = null; + + /** + * KeyRecipe indexName. + * @member {string|null|undefined} indexName + * @memberof google.spanner.v1.KeyRecipe + * @instance + */ + KeyRecipe.prototype.indexName = null; + + /** + * KeyRecipe operationUid. + * @member {number|Long|null|undefined} operationUid + * @memberof google.spanner.v1.KeyRecipe + * @instance + */ + KeyRecipe.prototype.operationUid = null; + + /** + * KeyRecipe part. + * @member {Array.} part + * @memberof google.spanner.v1.KeyRecipe + * @instance + */ + KeyRecipe.prototype.part = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * KeyRecipe target. + * @member {"tableName"|"indexName"|"operationUid"|undefined} target + * @memberof google.spanner.v1.KeyRecipe + * @instance + */ + Object.defineProperty(KeyRecipe.prototype, "target", { + get: $util.oneOfGetter($oneOfFields = ["tableName", "indexName", "operationUid"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new KeyRecipe instance using the specified properties. + * @function create + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {google.spanner.v1.IKeyRecipe=} [properties] Properties to set + * @returns {google.spanner.v1.KeyRecipe} KeyRecipe instance + */ + KeyRecipe.create = function create(properties) { + return new KeyRecipe(properties); + }; + + /** + * Encodes the specified KeyRecipe message. Does not implicitly {@link google.spanner.v1.KeyRecipe.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {google.spanner.v1.IKeyRecipe} message KeyRecipe message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyRecipe.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.tableName != null && Object.hasOwnProperty.call(message, "tableName")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.tableName); + if (message.indexName != null && Object.hasOwnProperty.call(message, "indexName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.indexName); + if (message.operationUid != null && Object.hasOwnProperty.call(message, "operationUid")) + writer.uint32(/* id 3, wireType 0 =*/24).uint64(message.operationUid); + if (message.part != null && message.part.length) + for (var i = 0; i < message.part.length; ++i) + $root.google.spanner.v1.KeyRecipe.Part.encode(message.part[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified KeyRecipe message, length delimited. Does not implicitly {@link google.spanner.v1.KeyRecipe.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {google.spanner.v1.IKeyRecipe} message KeyRecipe message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + KeyRecipe.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a KeyRecipe message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.KeyRecipe} KeyRecipe + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyRecipe.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.spanner.v1.KeyRecipe(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.tableName = reader.string(); + break; + } + case 2: { + message.indexName = reader.string(); + break; + } + case 3: { + message.operationUid = reader.uint64(); + break; + } + case 4: { + if (!(message.part && message.part.length)) + message.part = []; + message.part.push($root.google.spanner.v1.KeyRecipe.Part.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a KeyRecipe message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.KeyRecipe} KeyRecipe + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + KeyRecipe.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a KeyRecipe message. + * @function verify + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + KeyRecipe.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.tableName != null && message.hasOwnProperty("tableName")) { + properties.target = 1; + if (!$util.isString(message.tableName)) + return "tableName: string expected"; + } + if (message.indexName != null && message.hasOwnProperty("indexName")) { + if (properties.target === 1) + return "target: multiple values"; + properties.target = 1; + if (!$util.isString(message.indexName)) + return "indexName: string expected"; + } + if (message.operationUid != null && message.hasOwnProperty("operationUid")) { + if (properties.target === 1) + return "target: multiple values"; + properties.target = 1; + if (!$util.isInteger(message.operationUid) && !(message.operationUid && $util.isInteger(message.operationUid.low) && $util.isInteger(message.operationUid.high))) + return "operationUid: integer|Long expected"; + } + if (message.part != null && message.hasOwnProperty("part")) { + if (!Array.isArray(message.part)) + return "part: array expected"; + for (var i = 0; i < message.part.length; ++i) { + var error = $root.google.spanner.v1.KeyRecipe.Part.verify(message.part[i]); + if (error) + return "part." + error; + } + } + return null; + }; + + /** + * Creates a KeyRecipe message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.KeyRecipe} KeyRecipe + */ + KeyRecipe.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.KeyRecipe) + return object; + var message = new $root.google.spanner.v1.KeyRecipe(); + if (object.tableName != null) + message.tableName = String(object.tableName); + if (object.indexName != null) + message.indexName = String(object.indexName); + if (object.operationUid != null) + if ($util.Long) + (message.operationUid = $util.Long.fromValue(object.operationUid)).unsigned = true; + else if (typeof object.operationUid === "string") + message.operationUid = parseInt(object.operationUid, 10); + else if (typeof object.operationUid === "number") + message.operationUid = object.operationUid; + else if (typeof object.operationUid === "object") + message.operationUid = new $util.LongBits(object.operationUid.low >>> 0, object.operationUid.high >>> 0).toNumber(true); + if (object.part) { + if (!Array.isArray(object.part)) + throw TypeError(".google.spanner.v1.KeyRecipe.part: array expected"); + message.part = []; + for (var i = 0; i < object.part.length; ++i) { + if (typeof object.part[i] !== "object") + throw TypeError(".google.spanner.v1.KeyRecipe.part: object expected"); + message.part[i] = $root.google.spanner.v1.KeyRecipe.Part.fromObject(object.part[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a KeyRecipe message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {google.spanner.v1.KeyRecipe} message KeyRecipe + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + KeyRecipe.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.part = []; + if (message.tableName != null && message.hasOwnProperty("tableName")) { + object.tableName = message.tableName; + if (options.oneofs) + object.target = "tableName"; + } + if (message.indexName != null && message.hasOwnProperty("indexName")) { + object.indexName = message.indexName; + if (options.oneofs) + object.target = "indexName"; + } + if (message.operationUid != null && message.hasOwnProperty("operationUid")) { + if (typeof message.operationUid === "number") + object.operationUid = options.longs === String ? String(message.operationUid) : message.operationUid; + else + object.operationUid = options.longs === String ? $util.Long.prototype.toString.call(message.operationUid) : options.longs === Number ? new $util.LongBits(message.operationUid.low >>> 0, message.operationUid.high >>> 0).toNumber(true) : message.operationUid; + if (options.oneofs) + object.target = "operationUid"; + } + if (message.part && message.part.length) { + object.part = []; + for (var j = 0; j < message.part.length; ++j) + object.part[j] = $root.google.spanner.v1.KeyRecipe.Part.toObject(message.part[j], options); + } + return object; + }; + + /** + * Converts this KeyRecipe to JSON. + * @function toJSON + * @memberof google.spanner.v1.KeyRecipe + * @instance + * @returns {Object.} JSON object + */ + KeyRecipe.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for KeyRecipe + * @function getTypeUrl + * @memberof google.spanner.v1.KeyRecipe + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + KeyRecipe.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.KeyRecipe"; + }; + + KeyRecipe.Part = (function() { + + /** + * Properties of a Part. + * @memberof google.spanner.v1.KeyRecipe + * @interface IPart + * @property {number|null} [tag] Part tag + * @property {google.spanner.v1.KeyRecipe.Part.Order|null} [order] Part order + * @property {google.spanner.v1.KeyRecipe.Part.NullOrder|null} [nullOrder] Part nullOrder + * @property {google.spanner.v1.IType|null} [type] Part type + * @property {string|null} [identifier] Part identifier + * @property {google.protobuf.IValue|null} [value] Part value + * @property {boolean|null} [random] Part random + * @property {Array.|null} [structIdentifiers] Part structIdentifiers + */ + + /** + * Constructs a new Part. + * @memberof google.spanner.v1.KeyRecipe + * @classdesc Represents a Part. + * @implements IPart + * @constructor + * @param {google.spanner.v1.KeyRecipe.IPart=} [properties] Properties to set + */ + function Part(properties) { + this.structIdentifiers = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Part tag. + * @member {number} tag + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Part.prototype.tag = 0; + + /** + * Part order. + * @member {google.spanner.v1.KeyRecipe.Part.Order} order + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Part.prototype.order = 0; + + /** + * Part nullOrder. + * @member {google.spanner.v1.KeyRecipe.Part.NullOrder} nullOrder + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Part.prototype.nullOrder = 0; + + /** + * Part type. + * @member {google.spanner.v1.IType|null|undefined} type + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Part.prototype.type = null; + + /** + * Part identifier. + * @member {string|null|undefined} identifier + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Part.prototype.identifier = null; + + /** + * Part value. + * @member {google.protobuf.IValue|null|undefined} value + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Part.prototype.value = null; + + /** + * Part random. + * @member {boolean|null|undefined} random + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Part.prototype.random = null; + + /** + * Part structIdentifiers. + * @member {Array.} structIdentifiers + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Part.prototype.structIdentifiers = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Part valueType. + * @member {"identifier"|"value"|"random"|undefined} valueType + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + */ + Object.defineProperty(Part.prototype, "valueType", { + get: $util.oneOfGetter($oneOfFields = ["identifier", "value", "random"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new Part instance using the specified properties. + * @function create + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {google.spanner.v1.KeyRecipe.IPart=} [properties] Properties to set + * @returns {google.spanner.v1.KeyRecipe.Part} Part instance + */ + Part.create = function create(properties) { + return new Part(properties); + }; + + /** + * Encodes the specified Part message. Does not implicitly {@link google.spanner.v1.KeyRecipe.Part.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {google.spanner.v1.KeyRecipe.IPart} message Part message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Part.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.tag != null && Object.hasOwnProperty.call(message, "tag")) + writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.tag); + if (message.order != null && Object.hasOwnProperty.call(message, "order")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.order); + if (message.nullOrder != null && Object.hasOwnProperty.call(message, "nullOrder")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.nullOrder); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + $root.google.spanner.v1.Type.encode(message.type, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.identifier != null && Object.hasOwnProperty.call(message, "identifier")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.identifier); + if (message.value != null && Object.hasOwnProperty.call(message, "value")) + $root.google.protobuf.Value.encode(message.value, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.structIdentifiers != null && message.structIdentifiers.length) { + writer.uint32(/* id 7, wireType 2 =*/58).fork(); + for (var i = 0; i < message.structIdentifiers.length; ++i) + writer.int32(message.structIdentifiers[i]); + writer.ldelim(); + } + if (message.random != null && Object.hasOwnProperty.call(message, "random")) + writer.uint32(/* id 8, wireType 0 =*/64).bool(message.random); + return writer; + }; + + /** + * Encodes the specified Part message, length delimited. Does not implicitly {@link google.spanner.v1.KeyRecipe.Part.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {google.spanner.v1.KeyRecipe.IPart} message Part message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Part.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Part message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.KeyRecipe.Part} Part + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Part.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.spanner.v1.KeyRecipe.Part(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.tag = reader.uint32(); + break; + } + case 2: { + message.order = reader.int32(); + break; + } + case 3: { + message.nullOrder = reader.int32(); + break; + } + case 4: { + message.type = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + } + case 5: { + message.identifier = reader.string(); + break; + } + case 6: { + message.value = $root.google.protobuf.Value.decode(reader, reader.uint32()); + break; + } + case 8: { + message.random = reader.bool(); + break; + } + case 7: { + if (!(message.structIdentifiers && message.structIdentifiers.length)) + message.structIdentifiers = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.structIdentifiers.push(reader.int32()); + } else + message.structIdentifiers.push(reader.int32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Part message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.KeyRecipe.Part} Part + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Part.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Part message. + * @function verify + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Part.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.tag != null && message.hasOwnProperty("tag")) + if (!$util.isInteger(message.tag)) + return "tag: integer expected"; + if (message.order != null && message.hasOwnProperty("order")) + switch (message.order) { + default: + return "order: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.nullOrder != null && message.hasOwnProperty("nullOrder")) + switch (message.nullOrder) { + default: + return "nullOrder: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.type != null && message.hasOwnProperty("type")) { + var error = $root.google.spanner.v1.Type.verify(message.type); + if (error) + return "type." + error; + } + if (message.identifier != null && message.hasOwnProperty("identifier")) { + properties.valueType = 1; + if (!$util.isString(message.identifier)) + return "identifier: string expected"; + } + if (message.value != null && message.hasOwnProperty("value")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + { + var error = $root.google.protobuf.Value.verify(message.value); + if (error) + return "value." + error; + } + } + if (message.random != null && message.hasOwnProperty("random")) { + if (properties.valueType === 1) + return "valueType: multiple values"; + properties.valueType = 1; + if (typeof message.random !== "boolean") + return "random: boolean expected"; + } + if (message.structIdentifiers != null && message.hasOwnProperty("structIdentifiers")) { + if (!Array.isArray(message.structIdentifiers)) + return "structIdentifiers: array expected"; + for (var i = 0; i < message.structIdentifiers.length; ++i) + if (!$util.isInteger(message.structIdentifiers[i])) + return "structIdentifiers: integer[] expected"; + } + return null; + }; + + /** + * Creates a Part message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.KeyRecipe.Part} Part + */ + Part.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.KeyRecipe.Part) + return object; + var message = new $root.google.spanner.v1.KeyRecipe.Part(); + if (object.tag != null) + message.tag = object.tag >>> 0; + switch (object.order) { + default: + if (typeof object.order === "number") { + message.order = object.order; + break; + } + break; + case "ORDER_UNSPECIFIED": + case 0: + message.order = 0; + break; + case "ASCENDING": + case 1: + message.order = 1; + break; + case "DESCENDING": + case 2: + message.order = 2; + break; + } + switch (object.nullOrder) { + default: + if (typeof object.nullOrder === "number") { + message.nullOrder = object.nullOrder; + break; + } + break; + case "NULL_ORDER_UNSPECIFIED": + case 0: + message.nullOrder = 0; + break; + case "NULLS_FIRST": + case 1: + message.nullOrder = 1; + break; + case "NULLS_LAST": + case 2: + message.nullOrder = 2; + break; + case "NOT_NULL": + case 3: + message.nullOrder = 3; + break; + } + if (object.type != null) { + if (typeof object.type !== "object") + throw TypeError(".google.spanner.v1.KeyRecipe.Part.type: object expected"); + message.type = $root.google.spanner.v1.Type.fromObject(object.type); + } + if (object.identifier != null) + message.identifier = String(object.identifier); + if (object.value != null) { + if (typeof object.value !== "object") + throw TypeError(".google.spanner.v1.KeyRecipe.Part.value: object expected"); + message.value = $root.google.protobuf.Value.fromObject(object.value); + } + if (object.random != null) + message.random = Boolean(object.random); + if (object.structIdentifiers) { + if (!Array.isArray(object.structIdentifiers)) + throw TypeError(".google.spanner.v1.KeyRecipe.Part.structIdentifiers: array expected"); + message.structIdentifiers = []; + for (var i = 0; i < object.structIdentifiers.length; ++i) + message.structIdentifiers[i] = object.structIdentifiers[i] | 0; + } + return message; + }; + + /** + * Creates a plain object from a Part message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {google.spanner.v1.KeyRecipe.Part} message Part + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Part.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.structIdentifiers = []; + if (options.defaults) { + object.tag = 0; + object.order = options.enums === String ? "ORDER_UNSPECIFIED" : 0; + object.nullOrder = options.enums === String ? "NULL_ORDER_UNSPECIFIED" : 0; + object.type = null; + } + if (message.tag != null && message.hasOwnProperty("tag")) + object.tag = message.tag; + if (message.order != null && message.hasOwnProperty("order")) + object.order = options.enums === String ? $root.google.spanner.v1.KeyRecipe.Part.Order[message.order] === undefined ? message.order : $root.google.spanner.v1.KeyRecipe.Part.Order[message.order] : message.order; + if (message.nullOrder != null && message.hasOwnProperty("nullOrder")) + object.nullOrder = options.enums === String ? $root.google.spanner.v1.KeyRecipe.Part.NullOrder[message.nullOrder] === undefined ? message.nullOrder : $root.google.spanner.v1.KeyRecipe.Part.NullOrder[message.nullOrder] : message.nullOrder; + if (message.type != null && message.hasOwnProperty("type")) + object.type = $root.google.spanner.v1.Type.toObject(message.type, options); + if (message.identifier != null && message.hasOwnProperty("identifier")) { + object.identifier = message.identifier; + if (options.oneofs) + object.valueType = "identifier"; + } + if (message.value != null && message.hasOwnProperty("value")) { + object.value = $root.google.protobuf.Value.toObject(message.value, options); + if (options.oneofs) + object.valueType = "value"; + } + if (message.structIdentifiers && message.structIdentifiers.length) { + object.structIdentifiers = []; + for (var j = 0; j < message.structIdentifiers.length; ++j) + object.structIdentifiers[j] = message.structIdentifiers[j]; + } + if (message.random != null && message.hasOwnProperty("random")) { + object.random = message.random; + if (options.oneofs) + object.valueType = "random"; + } + return object; + }; + + /** + * Converts this Part to JSON. + * @function toJSON + * @memberof google.spanner.v1.KeyRecipe.Part + * @instance + * @returns {Object.} JSON object + */ + Part.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Part + * @function getTypeUrl + * @memberof google.spanner.v1.KeyRecipe.Part + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Part.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.KeyRecipe.Part"; + }; + + /** + * Order enum. + * @name google.spanner.v1.KeyRecipe.Part.Order + * @enum {number} + * @property {number} ORDER_UNSPECIFIED=0 ORDER_UNSPECIFIED value + * @property {number} ASCENDING=1 ASCENDING value + * @property {number} DESCENDING=2 DESCENDING value + */ + Part.Order = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ORDER_UNSPECIFIED"] = 0; + values[valuesById[1] = "ASCENDING"] = 1; + values[valuesById[2] = "DESCENDING"] = 2; + return values; + })(); + + /** + * NullOrder enum. + * @name google.spanner.v1.KeyRecipe.Part.NullOrder + * @enum {number} + * @property {number} NULL_ORDER_UNSPECIFIED=0 NULL_ORDER_UNSPECIFIED value + * @property {number} NULLS_FIRST=1 NULLS_FIRST value + * @property {number} NULLS_LAST=2 NULLS_LAST value + * @property {number} NOT_NULL=3 NOT_NULL value + */ + Part.NullOrder = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NULL_ORDER_UNSPECIFIED"] = 0; + values[valuesById[1] = "NULLS_FIRST"] = 1; + values[valuesById[2] = "NULLS_LAST"] = 2; + values[valuesById[3] = "NOT_NULL"] = 3; + return values; + })(); + + return Part; + })(); + + return KeyRecipe; + })(); + + v1.RecipeList = (function() { + + /** + * Properties of a RecipeList. + * @memberof google.spanner.v1 + * @interface IRecipeList + * @property {Uint8Array|null} [schemaGeneration] RecipeList schemaGeneration + * @property {Array.|null} [recipe] RecipeList recipe + */ + + /** + * Constructs a new RecipeList. + * @memberof google.spanner.v1 + * @classdesc Represents a RecipeList. + * @implements IRecipeList + * @constructor + * @param {google.spanner.v1.IRecipeList=} [properties] Properties to set + */ + function RecipeList(properties) { + this.recipe = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RecipeList schemaGeneration. + * @member {Uint8Array} schemaGeneration + * @memberof google.spanner.v1.RecipeList + * @instance + */ + RecipeList.prototype.schemaGeneration = $util.newBuffer([]); + + /** + * RecipeList recipe. + * @member {Array.} recipe + * @memberof google.spanner.v1.RecipeList + * @instance + */ + RecipeList.prototype.recipe = $util.emptyArray; + + /** + * Creates a new RecipeList instance using the specified properties. + * @function create + * @memberof google.spanner.v1.RecipeList + * @static + * @param {google.spanner.v1.IRecipeList=} [properties] Properties to set + * @returns {google.spanner.v1.RecipeList} RecipeList instance + */ + RecipeList.create = function create(properties) { + return new RecipeList(properties); + }; + + /** + * Encodes the specified RecipeList message. Does not implicitly {@link google.spanner.v1.RecipeList.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.RecipeList + * @static + * @param {google.spanner.v1.IRecipeList} message RecipeList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RecipeList.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.schemaGeneration != null && Object.hasOwnProperty.call(message, "schemaGeneration")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.schemaGeneration); + if (message.recipe != null && message.recipe.length) + for (var i = 0; i < message.recipe.length; ++i) + $root.google.spanner.v1.KeyRecipe.encode(message.recipe[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RecipeList message, length delimited. Does not implicitly {@link google.spanner.v1.RecipeList.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.RecipeList + * @static + * @param {google.spanner.v1.IRecipeList} message RecipeList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RecipeList.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RecipeList message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.RecipeList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.RecipeList} RecipeList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RecipeList.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.spanner.v1.RecipeList(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.schemaGeneration = reader.bytes(); + break; + } + case 3: { + if (!(message.recipe && message.recipe.length)) + message.recipe = []; + message.recipe.push($root.google.spanner.v1.KeyRecipe.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RecipeList message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.RecipeList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.RecipeList} RecipeList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RecipeList.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RecipeList message. + * @function verify + * @memberof google.spanner.v1.RecipeList + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RecipeList.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.schemaGeneration != null && message.hasOwnProperty("schemaGeneration")) + if (!(message.schemaGeneration && typeof message.schemaGeneration.length === "number" || $util.isString(message.schemaGeneration))) + return "schemaGeneration: buffer expected"; + if (message.recipe != null && message.hasOwnProperty("recipe")) { + if (!Array.isArray(message.recipe)) + return "recipe: array expected"; + for (var i = 0; i < message.recipe.length; ++i) { + var error = $root.google.spanner.v1.KeyRecipe.verify(message.recipe[i]); + if (error) + return "recipe." + error; + } + } + return null; + }; + + /** + * Creates a RecipeList message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.RecipeList + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.RecipeList} RecipeList + */ + RecipeList.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.RecipeList) + return object; + var message = new $root.google.spanner.v1.RecipeList(); + if (object.schemaGeneration != null) + if (typeof object.schemaGeneration === "string") + $util.base64.decode(object.schemaGeneration, message.schemaGeneration = $util.newBuffer($util.base64.length(object.schemaGeneration)), 0); + else if (object.schemaGeneration.length >= 0) + message.schemaGeneration = object.schemaGeneration; + if (object.recipe) { + if (!Array.isArray(object.recipe)) + throw TypeError(".google.spanner.v1.RecipeList.recipe: array expected"); + message.recipe = []; + for (var i = 0; i < object.recipe.length; ++i) { + if (typeof object.recipe[i] !== "object") + throw TypeError(".google.spanner.v1.RecipeList.recipe: object expected"); + message.recipe[i] = $root.google.spanner.v1.KeyRecipe.fromObject(object.recipe[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a RecipeList message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.RecipeList + * @static + * @param {google.spanner.v1.RecipeList} message RecipeList + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RecipeList.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.recipe = []; + if (options.defaults) + if (options.bytes === String) + object.schemaGeneration = ""; + else { + object.schemaGeneration = []; + if (options.bytes !== Array) + object.schemaGeneration = $util.newBuffer(object.schemaGeneration); + } + if (message.schemaGeneration != null && message.hasOwnProperty("schemaGeneration")) + object.schemaGeneration = options.bytes === String ? $util.base64.encode(message.schemaGeneration, 0, message.schemaGeneration.length) : options.bytes === Array ? Array.prototype.slice.call(message.schemaGeneration) : message.schemaGeneration; + if (message.recipe && message.recipe.length) { + object.recipe = []; + for (var j = 0; j < message.recipe.length; ++j) + object.recipe[j] = $root.google.spanner.v1.KeyRecipe.toObject(message.recipe[j], options); + } + return object; + }; + + /** + * Converts this RecipeList to JSON. + * @function toJSON + * @memberof google.spanner.v1.RecipeList + * @instance + * @returns {Object.} JSON object + */ + RecipeList.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RecipeList + * @function getTypeUrl + * @memberof google.spanner.v1.RecipeList + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RecipeList.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.RecipeList"; + }; + + return RecipeList; + })(); + + v1.CacheUpdate = (function() { + + /** + * Properties of a CacheUpdate. + * @memberof google.spanner.v1 + * @interface ICacheUpdate + * @property {number|Long|null} [databaseId] CacheUpdate databaseId + * @property {Array.|null} [range] CacheUpdate range + * @property {Array.|null} [group] CacheUpdate group + * @property {google.spanner.v1.IRecipeList|null} [keyRecipes] CacheUpdate keyRecipes + */ + + /** + * Constructs a new CacheUpdate. + * @memberof google.spanner.v1 + * @classdesc Represents a CacheUpdate. + * @implements ICacheUpdate + * @constructor + * @param {google.spanner.v1.ICacheUpdate=} [properties] Properties to set + */ + function CacheUpdate(properties) { + this.range = []; + this.group = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CacheUpdate databaseId. + * @member {number|Long} databaseId + * @memberof google.spanner.v1.CacheUpdate + * @instance + */ + CacheUpdate.prototype.databaseId = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * CacheUpdate range. + * @member {Array.} range + * @memberof google.spanner.v1.CacheUpdate + * @instance + */ + CacheUpdate.prototype.range = $util.emptyArray; + + /** + * CacheUpdate group. + * @member {Array.} group + * @memberof google.spanner.v1.CacheUpdate + * @instance + */ + CacheUpdate.prototype.group = $util.emptyArray; + + /** + * CacheUpdate keyRecipes. + * @member {google.spanner.v1.IRecipeList|null|undefined} keyRecipes + * @memberof google.spanner.v1.CacheUpdate + * @instance + */ + CacheUpdate.prototype.keyRecipes = null; + + /** + * Creates a new CacheUpdate instance using the specified properties. + * @function create + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {google.spanner.v1.ICacheUpdate=} [properties] Properties to set + * @returns {google.spanner.v1.CacheUpdate} CacheUpdate instance + */ + CacheUpdate.create = function create(properties) { + return new CacheUpdate(properties); + }; + + /** + * Encodes the specified CacheUpdate message. Does not implicitly {@link google.spanner.v1.CacheUpdate.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {google.spanner.v1.ICacheUpdate} message CacheUpdate message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CacheUpdate.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.databaseId); + if (message.range != null && message.range.length) + for (var i = 0; i < message.range.length; ++i) + $root.google.spanner.v1.Range.encode(message.range[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.group != null && message.group.length) + for (var i = 0; i < message.group.length; ++i) + $root.google.spanner.v1.Group.encode(message.group[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.keyRecipes != null && Object.hasOwnProperty.call(message, "keyRecipes")) + $root.google.spanner.v1.RecipeList.encode(message.keyRecipes, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CacheUpdate message, length delimited. Does not implicitly {@link google.spanner.v1.CacheUpdate.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {google.spanner.v1.ICacheUpdate} message CacheUpdate message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CacheUpdate.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CacheUpdate message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.CacheUpdate} CacheUpdate + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CacheUpdate.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.spanner.v1.CacheUpdate(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.databaseId = reader.uint64(); + break; + } + case 2: { + if (!(message.range && message.range.length)) + message.range = []; + message.range.push($root.google.spanner.v1.Range.decode(reader, reader.uint32())); + break; + } + case 3: { + if (!(message.group && message.group.length)) + message.group = []; + message.group.push($root.google.spanner.v1.Group.decode(reader, reader.uint32())); + break; + } + case 5: { + message.keyRecipes = $root.google.spanner.v1.RecipeList.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CacheUpdate message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.CacheUpdate} CacheUpdate + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CacheUpdate.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CacheUpdate message. + * @function verify + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CacheUpdate.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isInteger(message.databaseId) && !(message.databaseId && $util.isInteger(message.databaseId.low) && $util.isInteger(message.databaseId.high))) + return "databaseId: integer|Long expected"; + if (message.range != null && message.hasOwnProperty("range")) { + if (!Array.isArray(message.range)) + return "range: array expected"; + for (var i = 0; i < message.range.length; ++i) { + var error = $root.google.spanner.v1.Range.verify(message.range[i]); + if (error) + return "range." + error; + } + } + if (message.group != null && message.hasOwnProperty("group")) { + if (!Array.isArray(message.group)) + return "group: array expected"; + for (var i = 0; i < message.group.length; ++i) { + var error = $root.google.spanner.v1.Group.verify(message.group[i]); + if (error) + return "group." + error; + } + } + if (message.keyRecipes != null && message.hasOwnProperty("keyRecipes")) { + var error = $root.google.spanner.v1.RecipeList.verify(message.keyRecipes); + if (error) + return "keyRecipes." + error; + } + return null; + }; + + /** + * Creates a CacheUpdate message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.CacheUpdate} CacheUpdate + */ + CacheUpdate.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.CacheUpdate) + return object; + var message = new $root.google.spanner.v1.CacheUpdate(); + if (object.databaseId != null) + if ($util.Long) + (message.databaseId = $util.Long.fromValue(object.databaseId)).unsigned = true; + else if (typeof object.databaseId === "string") + message.databaseId = parseInt(object.databaseId, 10); + else if (typeof object.databaseId === "number") + message.databaseId = object.databaseId; + else if (typeof object.databaseId === "object") + message.databaseId = new $util.LongBits(object.databaseId.low >>> 0, object.databaseId.high >>> 0).toNumber(true); + if (object.range) { + if (!Array.isArray(object.range)) + throw TypeError(".google.spanner.v1.CacheUpdate.range: array expected"); + message.range = []; + for (var i = 0; i < object.range.length; ++i) { + if (typeof object.range[i] !== "object") + throw TypeError(".google.spanner.v1.CacheUpdate.range: object expected"); + message.range[i] = $root.google.spanner.v1.Range.fromObject(object.range[i]); + } + } + if (object.group) { + if (!Array.isArray(object.group)) + throw TypeError(".google.spanner.v1.CacheUpdate.group: array expected"); + message.group = []; + for (var i = 0; i < object.group.length; ++i) { + if (typeof object.group[i] !== "object") + throw TypeError(".google.spanner.v1.CacheUpdate.group: object expected"); + message.group[i] = $root.google.spanner.v1.Group.fromObject(object.group[i]); + } + } + if (object.keyRecipes != null) { + if (typeof object.keyRecipes !== "object") + throw TypeError(".google.spanner.v1.CacheUpdate.keyRecipes: object expected"); + message.keyRecipes = $root.google.spanner.v1.RecipeList.fromObject(object.keyRecipes); + } + return message; + }; + + /** + * Creates a plain object from a CacheUpdate message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {google.spanner.v1.CacheUpdate} message CacheUpdate + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CacheUpdate.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.range = []; + object.group = []; + } + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.databaseId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.databaseId = options.longs === String ? "0" : 0; + object.keyRecipes = null; + } + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (typeof message.databaseId === "number") + object.databaseId = options.longs === String ? String(message.databaseId) : message.databaseId; + else + object.databaseId = options.longs === String ? $util.Long.prototype.toString.call(message.databaseId) : options.longs === Number ? new $util.LongBits(message.databaseId.low >>> 0, message.databaseId.high >>> 0).toNumber(true) : message.databaseId; + if (message.range && message.range.length) { + object.range = []; + for (var j = 0; j < message.range.length; ++j) + object.range[j] = $root.google.spanner.v1.Range.toObject(message.range[j], options); + } + if (message.group && message.group.length) { + object.group = []; + for (var j = 0; j < message.group.length; ++j) + object.group[j] = $root.google.spanner.v1.Group.toObject(message.group[j], options); + } + if (message.keyRecipes != null && message.hasOwnProperty("keyRecipes")) + object.keyRecipes = $root.google.spanner.v1.RecipeList.toObject(message.keyRecipes, options); + return object; + }; + + /** + * Converts this CacheUpdate to JSON. + * @function toJSON + * @memberof google.spanner.v1.CacheUpdate + * @instance + * @returns {Object.} JSON object + */ + CacheUpdate.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CacheUpdate + * @function getTypeUrl + * @memberof google.spanner.v1.CacheUpdate + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CacheUpdate.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.CacheUpdate"; + }; + + return CacheUpdate; + })(); + + v1.RoutingHint = (function() { + + /** + * Properties of a RoutingHint. + * @memberof google.spanner.v1 + * @interface IRoutingHint + * @property {number|Long|null} [operationUid] RoutingHint operationUid + * @property {number|Long|null} [databaseId] RoutingHint databaseId + * @property {Uint8Array|null} [schemaGeneration] RoutingHint schemaGeneration + * @property {Uint8Array|null} [key] RoutingHint key + * @property {Uint8Array|null} [limitKey] RoutingHint limitKey + * @property {number|Long|null} [groupUid] RoutingHint groupUid + * @property {number|Long|null} [splitId] RoutingHint splitId + * @property {number|Long|null} [tabletUid] RoutingHint tabletUid + * @property {Array.|null} [skippedTabletUid] RoutingHint skippedTabletUid + * @property {string|null} [clientLocation] RoutingHint clientLocation + */ + + /** + * Constructs a new RoutingHint. + * @memberof google.spanner.v1 + * @classdesc Represents a RoutingHint. + * @implements IRoutingHint + * @constructor + * @param {google.spanner.v1.IRoutingHint=} [properties] Properties to set + */ + function RoutingHint(properties) { + this.skippedTabletUid = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingHint operationUid. + * @member {number|Long} operationUid + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.operationUid = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * RoutingHint databaseId. + * @member {number|Long} databaseId + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.databaseId = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * RoutingHint schemaGeneration. + * @member {Uint8Array} schemaGeneration + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.schemaGeneration = $util.newBuffer([]); + + /** + * RoutingHint key. + * @member {Uint8Array} key + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.key = $util.newBuffer([]); + + /** + * RoutingHint limitKey. + * @member {Uint8Array} limitKey + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.limitKey = $util.newBuffer([]); + + /** + * RoutingHint groupUid. + * @member {number|Long} groupUid + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.groupUid = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * RoutingHint splitId. + * @member {number|Long} splitId + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.splitId = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * RoutingHint tabletUid. + * @member {number|Long} tabletUid + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.tabletUid = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * RoutingHint skippedTabletUid. + * @member {Array.} skippedTabletUid + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.skippedTabletUid = $util.emptyArray; + + /** + * RoutingHint clientLocation. + * @member {string} clientLocation + * @memberof google.spanner.v1.RoutingHint + * @instance + */ + RoutingHint.prototype.clientLocation = ""; + + /** + * Creates a new RoutingHint instance using the specified properties. + * @function create + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {google.spanner.v1.IRoutingHint=} [properties] Properties to set + * @returns {google.spanner.v1.RoutingHint} RoutingHint instance + */ + RoutingHint.create = function create(properties) { + return new RoutingHint(properties); + }; + + /** + * Encodes the specified RoutingHint message. Does not implicitly {@link google.spanner.v1.RoutingHint.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {google.spanner.v1.IRoutingHint} message RoutingHint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RoutingHint.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.operationUid != null && Object.hasOwnProperty.call(message, "operationUid")) + writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.operationUid); + if (message.databaseId != null && Object.hasOwnProperty.call(message, "databaseId")) + writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.databaseId); + if (message.schemaGeneration != null && Object.hasOwnProperty.call(message, "schemaGeneration")) + writer.uint32(/* id 3, wireType 2 =*/26).bytes(message.schemaGeneration); + if (message.key != null && Object.hasOwnProperty.call(message, "key")) + writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.key); + if (message.limitKey != null && Object.hasOwnProperty.call(message, "limitKey")) + writer.uint32(/* id 5, wireType 2 =*/42).bytes(message.limitKey); + if (message.groupUid != null && Object.hasOwnProperty.call(message, "groupUid")) + writer.uint32(/* id 6, wireType 0 =*/48).uint64(message.groupUid); + if (message.splitId != null && Object.hasOwnProperty.call(message, "splitId")) + writer.uint32(/* id 7, wireType 0 =*/56).uint64(message.splitId); + if (message.tabletUid != null && Object.hasOwnProperty.call(message, "tabletUid")) + writer.uint32(/* id 8, wireType 0 =*/64).uint64(message.tabletUid); + if (message.skippedTabletUid != null && message.skippedTabletUid.length) + for (var i = 0; i < message.skippedTabletUid.length; ++i) + $root.google.spanner.v1.RoutingHint.SkippedTablet.encode(message.skippedTabletUid[i], writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + if (message.clientLocation != null && Object.hasOwnProperty.call(message, "clientLocation")) + writer.uint32(/* id 10, wireType 2 =*/82).string(message.clientLocation); + return writer; + }; + + /** + * Encodes the specified RoutingHint message, length delimited. Does not implicitly {@link google.spanner.v1.RoutingHint.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {google.spanner.v1.IRoutingHint} message RoutingHint message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RoutingHint.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RoutingHint message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.RoutingHint} RoutingHint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RoutingHint.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.spanner.v1.RoutingHint(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.operationUid = reader.uint64(); + break; + } + case 2: { + message.databaseId = reader.uint64(); + break; + } + case 3: { + message.schemaGeneration = reader.bytes(); + break; + } + case 4: { + message.key = reader.bytes(); + break; + } + case 5: { + message.limitKey = reader.bytes(); + break; + } + case 6: { + message.groupUid = reader.uint64(); + break; + } + case 7: { + message.splitId = reader.uint64(); + break; + } + case 8: { + message.tabletUid = reader.uint64(); + break; + } + case 9: { + if (!(message.skippedTabletUid && message.skippedTabletUid.length)) + message.skippedTabletUid = []; + message.skippedTabletUid.push($root.google.spanner.v1.RoutingHint.SkippedTablet.decode(reader, reader.uint32())); + break; + } + case 10: { + message.clientLocation = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RoutingHint message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.RoutingHint} RoutingHint + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RoutingHint.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RoutingHint message. + * @function verify + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RoutingHint.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.operationUid != null && message.hasOwnProperty("operationUid")) + if (!$util.isInteger(message.operationUid) && !(message.operationUid && $util.isInteger(message.operationUid.low) && $util.isInteger(message.operationUid.high))) + return "operationUid: integer|Long expected"; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (!$util.isInteger(message.databaseId) && !(message.databaseId && $util.isInteger(message.databaseId.low) && $util.isInteger(message.databaseId.high))) + return "databaseId: integer|Long expected"; + if (message.schemaGeneration != null && message.hasOwnProperty("schemaGeneration")) + if (!(message.schemaGeneration && typeof message.schemaGeneration.length === "number" || $util.isString(message.schemaGeneration))) + return "schemaGeneration: buffer expected"; + if (message.key != null && message.hasOwnProperty("key")) + if (!(message.key && typeof message.key.length === "number" || $util.isString(message.key))) + return "key: buffer expected"; + if (message.limitKey != null && message.hasOwnProperty("limitKey")) + if (!(message.limitKey && typeof message.limitKey.length === "number" || $util.isString(message.limitKey))) + return "limitKey: buffer expected"; + if (message.groupUid != null && message.hasOwnProperty("groupUid")) + if (!$util.isInteger(message.groupUid) && !(message.groupUid && $util.isInteger(message.groupUid.low) && $util.isInteger(message.groupUid.high))) + return "groupUid: integer|Long expected"; + if (message.splitId != null && message.hasOwnProperty("splitId")) + if (!$util.isInteger(message.splitId) && !(message.splitId && $util.isInteger(message.splitId.low) && $util.isInteger(message.splitId.high))) + return "splitId: integer|Long expected"; + if (message.tabletUid != null && message.hasOwnProperty("tabletUid")) + if (!$util.isInteger(message.tabletUid) && !(message.tabletUid && $util.isInteger(message.tabletUid.low) && $util.isInteger(message.tabletUid.high))) + return "tabletUid: integer|Long expected"; + if (message.skippedTabletUid != null && message.hasOwnProperty("skippedTabletUid")) { + if (!Array.isArray(message.skippedTabletUid)) + return "skippedTabletUid: array expected"; + for (var i = 0; i < message.skippedTabletUid.length; ++i) { + var error = $root.google.spanner.v1.RoutingHint.SkippedTablet.verify(message.skippedTabletUid[i]); + if (error) + return "skippedTabletUid." + error; + } + } + if (message.clientLocation != null && message.hasOwnProperty("clientLocation")) + if (!$util.isString(message.clientLocation)) + return "clientLocation: string expected"; + return null; + }; + + /** + * Creates a RoutingHint message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.RoutingHint} RoutingHint + */ + RoutingHint.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.RoutingHint) + return object; + var message = new $root.google.spanner.v1.RoutingHint(); + if (object.operationUid != null) + if ($util.Long) + (message.operationUid = $util.Long.fromValue(object.operationUid)).unsigned = true; + else if (typeof object.operationUid === "string") + message.operationUid = parseInt(object.operationUid, 10); + else if (typeof object.operationUid === "number") + message.operationUid = object.operationUid; + else if (typeof object.operationUid === "object") + message.operationUid = new $util.LongBits(object.operationUid.low >>> 0, object.operationUid.high >>> 0).toNumber(true); + if (object.databaseId != null) + if ($util.Long) + (message.databaseId = $util.Long.fromValue(object.databaseId)).unsigned = true; + else if (typeof object.databaseId === "string") + message.databaseId = parseInt(object.databaseId, 10); + else if (typeof object.databaseId === "number") + message.databaseId = object.databaseId; + else if (typeof object.databaseId === "object") + message.databaseId = new $util.LongBits(object.databaseId.low >>> 0, object.databaseId.high >>> 0).toNumber(true); + if (object.schemaGeneration != null) + if (typeof object.schemaGeneration === "string") + $util.base64.decode(object.schemaGeneration, message.schemaGeneration = $util.newBuffer($util.base64.length(object.schemaGeneration)), 0); + else if (object.schemaGeneration.length >= 0) + message.schemaGeneration = object.schemaGeneration; + if (object.key != null) + if (typeof object.key === "string") + $util.base64.decode(object.key, message.key = $util.newBuffer($util.base64.length(object.key)), 0); + else if (object.key.length >= 0) + message.key = object.key; + if (object.limitKey != null) + if (typeof object.limitKey === "string") + $util.base64.decode(object.limitKey, message.limitKey = $util.newBuffer($util.base64.length(object.limitKey)), 0); + else if (object.limitKey.length >= 0) + message.limitKey = object.limitKey; + if (object.groupUid != null) + if ($util.Long) + (message.groupUid = $util.Long.fromValue(object.groupUid)).unsigned = true; + else if (typeof object.groupUid === "string") + message.groupUid = parseInt(object.groupUid, 10); + else if (typeof object.groupUid === "number") + message.groupUid = object.groupUid; + else if (typeof object.groupUid === "object") + message.groupUid = new $util.LongBits(object.groupUid.low >>> 0, object.groupUid.high >>> 0).toNumber(true); + if (object.splitId != null) + if ($util.Long) + (message.splitId = $util.Long.fromValue(object.splitId)).unsigned = true; + else if (typeof object.splitId === "string") + message.splitId = parseInt(object.splitId, 10); + else if (typeof object.splitId === "number") + message.splitId = object.splitId; + else if (typeof object.splitId === "object") + message.splitId = new $util.LongBits(object.splitId.low >>> 0, object.splitId.high >>> 0).toNumber(true); + if (object.tabletUid != null) + if ($util.Long) + (message.tabletUid = $util.Long.fromValue(object.tabletUid)).unsigned = true; + else if (typeof object.tabletUid === "string") + message.tabletUid = parseInt(object.tabletUid, 10); + else if (typeof object.tabletUid === "number") + message.tabletUid = object.tabletUid; + else if (typeof object.tabletUid === "object") + message.tabletUid = new $util.LongBits(object.tabletUid.low >>> 0, object.tabletUid.high >>> 0).toNumber(true); + if (object.skippedTabletUid) { + if (!Array.isArray(object.skippedTabletUid)) + throw TypeError(".google.spanner.v1.RoutingHint.skippedTabletUid: array expected"); + message.skippedTabletUid = []; + for (var i = 0; i < object.skippedTabletUid.length; ++i) { + if (typeof object.skippedTabletUid[i] !== "object") + throw TypeError(".google.spanner.v1.RoutingHint.skippedTabletUid: object expected"); + message.skippedTabletUid[i] = $root.google.spanner.v1.RoutingHint.SkippedTablet.fromObject(object.skippedTabletUid[i]); + } + } + if (object.clientLocation != null) + message.clientLocation = String(object.clientLocation); + return message; + }; + + /** + * Creates a plain object from a RoutingHint message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {google.spanner.v1.RoutingHint} message RoutingHint + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingHint.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.skippedTabletUid = []; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.operationUid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.operationUid = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.databaseId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.databaseId = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.schemaGeneration = ""; + else { + object.schemaGeneration = []; + if (options.bytes !== Array) + object.schemaGeneration = $util.newBuffer(object.schemaGeneration); + } + if (options.bytes === String) + object.key = ""; + else { + object.key = []; + if (options.bytes !== Array) + object.key = $util.newBuffer(object.key); + } + if (options.bytes === String) + object.limitKey = ""; + else { + object.limitKey = []; + if (options.bytes !== Array) + object.limitKey = $util.newBuffer(object.limitKey); + } + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.groupUid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.groupUid = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.splitId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.splitId = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.tabletUid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.tabletUid = options.longs === String ? "0" : 0; + object.clientLocation = ""; + } + if (message.operationUid != null && message.hasOwnProperty("operationUid")) + if (typeof message.operationUid === "number") + object.operationUid = options.longs === String ? String(message.operationUid) : message.operationUid; + else + object.operationUid = options.longs === String ? $util.Long.prototype.toString.call(message.operationUid) : options.longs === Number ? new $util.LongBits(message.operationUid.low >>> 0, message.operationUid.high >>> 0).toNumber(true) : message.operationUid; + if (message.databaseId != null && message.hasOwnProperty("databaseId")) + if (typeof message.databaseId === "number") + object.databaseId = options.longs === String ? String(message.databaseId) : message.databaseId; + else + object.databaseId = options.longs === String ? $util.Long.prototype.toString.call(message.databaseId) : options.longs === Number ? new $util.LongBits(message.databaseId.low >>> 0, message.databaseId.high >>> 0).toNumber(true) : message.databaseId; + if (message.schemaGeneration != null && message.hasOwnProperty("schemaGeneration")) + object.schemaGeneration = options.bytes === String ? $util.base64.encode(message.schemaGeneration, 0, message.schemaGeneration.length) : options.bytes === Array ? Array.prototype.slice.call(message.schemaGeneration) : message.schemaGeneration; + if (message.key != null && message.hasOwnProperty("key")) + object.key = options.bytes === String ? $util.base64.encode(message.key, 0, message.key.length) : options.bytes === Array ? Array.prototype.slice.call(message.key) : message.key; + if (message.limitKey != null && message.hasOwnProperty("limitKey")) + object.limitKey = options.bytes === String ? $util.base64.encode(message.limitKey, 0, message.limitKey.length) : options.bytes === Array ? Array.prototype.slice.call(message.limitKey) : message.limitKey; + if (message.groupUid != null && message.hasOwnProperty("groupUid")) + if (typeof message.groupUid === "number") + object.groupUid = options.longs === String ? String(message.groupUid) : message.groupUid; + else + object.groupUid = options.longs === String ? $util.Long.prototype.toString.call(message.groupUid) : options.longs === Number ? new $util.LongBits(message.groupUid.low >>> 0, message.groupUid.high >>> 0).toNumber(true) : message.groupUid; + if (message.splitId != null && message.hasOwnProperty("splitId")) + if (typeof message.splitId === "number") + object.splitId = options.longs === String ? String(message.splitId) : message.splitId; + else + object.splitId = options.longs === String ? $util.Long.prototype.toString.call(message.splitId) : options.longs === Number ? new $util.LongBits(message.splitId.low >>> 0, message.splitId.high >>> 0).toNumber(true) : message.splitId; + if (message.tabletUid != null && message.hasOwnProperty("tabletUid")) + if (typeof message.tabletUid === "number") + object.tabletUid = options.longs === String ? String(message.tabletUid) : message.tabletUid; + else + object.tabletUid = options.longs === String ? $util.Long.prototype.toString.call(message.tabletUid) : options.longs === Number ? new $util.LongBits(message.tabletUid.low >>> 0, message.tabletUid.high >>> 0).toNumber(true) : message.tabletUid; + if (message.skippedTabletUid && message.skippedTabletUid.length) { + object.skippedTabletUid = []; + for (var j = 0; j < message.skippedTabletUid.length; ++j) + object.skippedTabletUid[j] = $root.google.spanner.v1.RoutingHint.SkippedTablet.toObject(message.skippedTabletUid[j], options); + } + if (message.clientLocation != null && message.hasOwnProperty("clientLocation")) + object.clientLocation = message.clientLocation; + return object; + }; + + /** + * Converts this RoutingHint to JSON. + * @function toJSON + * @memberof google.spanner.v1.RoutingHint + * @instance + * @returns {Object.} JSON object + */ + RoutingHint.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingHint + * @function getTypeUrl + * @memberof google.spanner.v1.RoutingHint + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingHint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.RoutingHint"; + }; + + RoutingHint.SkippedTablet = (function() { + + /** + * Properties of a SkippedTablet. + * @memberof google.spanner.v1.RoutingHint + * @interface ISkippedTablet + * @property {number|Long|null} [tabletUid] SkippedTablet tabletUid + * @property {Uint8Array|null} [incarnation] SkippedTablet incarnation + */ + + /** + * Constructs a new SkippedTablet. + * @memberof google.spanner.v1.RoutingHint + * @classdesc Represents a SkippedTablet. + * @implements ISkippedTablet + * @constructor + * @param {google.spanner.v1.RoutingHint.ISkippedTablet=} [properties] Properties to set + */ + function SkippedTablet(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SkippedTablet tabletUid. + * @member {number|Long} tabletUid + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @instance + */ + SkippedTablet.prototype.tabletUid = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + + /** + * SkippedTablet incarnation. + * @member {Uint8Array} incarnation + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @instance + */ + SkippedTablet.prototype.incarnation = $util.newBuffer([]); + + /** + * Creates a new SkippedTablet instance using the specified properties. + * @function create + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {google.spanner.v1.RoutingHint.ISkippedTablet=} [properties] Properties to set + * @returns {google.spanner.v1.RoutingHint.SkippedTablet} SkippedTablet instance + */ + SkippedTablet.create = function create(properties) { + return new SkippedTablet(properties); + }; + + /** + * Encodes the specified SkippedTablet message. Does not implicitly {@link google.spanner.v1.RoutingHint.SkippedTablet.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {google.spanner.v1.RoutingHint.ISkippedTablet} message SkippedTablet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SkippedTablet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.tabletUid != null && Object.hasOwnProperty.call(message, "tabletUid")) + writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.tabletUid); + if (message.incarnation != null && Object.hasOwnProperty.call(message, "incarnation")) + writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.incarnation); + return writer; + }; + + /** + * Encodes the specified SkippedTablet message, length delimited. Does not implicitly {@link google.spanner.v1.RoutingHint.SkippedTablet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {google.spanner.v1.RoutingHint.ISkippedTablet} message SkippedTablet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SkippedTablet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SkippedTablet message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.RoutingHint.SkippedTablet} SkippedTablet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SkippedTablet.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.spanner.v1.RoutingHint.SkippedTablet(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.tabletUid = reader.uint64(); + break; + } + case 2: { + message.incarnation = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SkippedTablet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.RoutingHint.SkippedTablet} SkippedTablet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SkippedTablet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SkippedTablet message. + * @function verify + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SkippedTablet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.tabletUid != null && message.hasOwnProperty("tabletUid")) + if (!$util.isInteger(message.tabletUid) && !(message.tabletUid && $util.isInteger(message.tabletUid.low) && $util.isInteger(message.tabletUid.high))) + return "tabletUid: integer|Long expected"; + if (message.incarnation != null && message.hasOwnProperty("incarnation")) + if (!(message.incarnation && typeof message.incarnation.length === "number" || $util.isString(message.incarnation))) + return "incarnation: buffer expected"; + return null; + }; + + /** + * Creates a SkippedTablet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.RoutingHint.SkippedTablet} SkippedTablet + */ + SkippedTablet.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.RoutingHint.SkippedTablet) + return object; + var message = new $root.google.spanner.v1.RoutingHint.SkippedTablet(); + if (object.tabletUid != null) + if ($util.Long) + (message.tabletUid = $util.Long.fromValue(object.tabletUid)).unsigned = true; + else if (typeof object.tabletUid === "string") + message.tabletUid = parseInt(object.tabletUid, 10); + else if (typeof object.tabletUid === "number") + message.tabletUid = object.tabletUid; + else if (typeof object.tabletUid === "object") + message.tabletUid = new $util.LongBits(object.tabletUid.low >>> 0, object.tabletUid.high >>> 0).toNumber(true); + if (object.incarnation != null) + if (typeof object.incarnation === "string") + $util.base64.decode(object.incarnation, message.incarnation = $util.newBuffer($util.base64.length(object.incarnation)), 0); + else if (object.incarnation.length >= 0) + message.incarnation = object.incarnation; + return message; + }; + + /** + * Creates a plain object from a SkippedTablet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {google.spanner.v1.RoutingHint.SkippedTablet} message SkippedTablet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SkippedTablet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.tabletUid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.tabletUid = options.longs === String ? "0" : 0; + if (options.bytes === String) + object.incarnation = ""; + else { + object.incarnation = []; + if (options.bytes !== Array) + object.incarnation = $util.newBuffer(object.incarnation); + } + } + if (message.tabletUid != null && message.hasOwnProperty("tabletUid")) + if (typeof message.tabletUid === "number") + object.tabletUid = options.longs === String ? String(message.tabletUid) : message.tabletUid; + else + object.tabletUid = options.longs === String ? $util.Long.prototype.toString.call(message.tabletUid) : options.longs === Number ? new $util.LongBits(message.tabletUid.low >>> 0, message.tabletUid.high >>> 0).toNumber(true) : message.tabletUid; + if (message.incarnation != null && message.hasOwnProperty("incarnation")) + object.incarnation = options.bytes === String ? $util.base64.encode(message.incarnation, 0, message.incarnation.length) : options.bytes === Array ? Array.prototype.slice.call(message.incarnation) : message.incarnation; + return object; + }; + + /** + * Converts this SkippedTablet to JSON. + * @function toJSON + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @instance + * @returns {Object.} JSON object + */ + SkippedTablet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SkippedTablet + * @function getTypeUrl + * @memberof google.spanner.v1.RoutingHint.SkippedTablet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SkippedTablet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.RoutingHint.SkippedTablet"; + }; + + return SkippedTablet; + })(); + + return RoutingHint; + })(); + + v1.Type = (function() { + + /** + * Properties of a Type. + * @memberof google.spanner.v1 + * @interface IType + * @property {google.spanner.v1.TypeCode|null} [code] Type code + * @property {google.spanner.v1.IType|null} [arrayElementType] Type arrayElementType + * @property {google.spanner.v1.IStructType|null} [structType] Type structType + * @property {google.spanner.v1.TypeAnnotationCode|null} [typeAnnotation] Type typeAnnotation + * @property {string|null} [protoTypeFqn] Type protoTypeFqn + */ + + /** + * Constructs a new Type. + * @memberof google.spanner.v1 + * @classdesc Represents a Type. + * @implements IType + * @constructor + * @param {google.spanner.v1.IType=} [properties] Properties to set + */ + function Type(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Type code. + * @member {google.spanner.v1.TypeCode} code + * @memberof google.spanner.v1.Type + * @instance + */ + Type.prototype.code = 0; + + /** + * Type arrayElementType. + * @member {google.spanner.v1.IType|null|undefined} arrayElementType + * @memberof google.spanner.v1.Type + * @instance + */ + Type.prototype.arrayElementType = null; + + /** + * Type structType. + * @member {google.spanner.v1.IStructType|null|undefined} structType + * @memberof google.spanner.v1.Type + * @instance + */ + Type.prototype.structType = null; + + /** + * Type typeAnnotation. + * @member {google.spanner.v1.TypeAnnotationCode} typeAnnotation + * @memberof google.spanner.v1.Type + * @instance + */ + Type.prototype.typeAnnotation = 0; + + /** + * Type protoTypeFqn. + * @member {string} protoTypeFqn + * @memberof google.spanner.v1.Type + * @instance + */ + Type.prototype.protoTypeFqn = ""; + + /** + * Creates a new Type instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Type + * @static + * @param {google.spanner.v1.IType=} [properties] Properties to set + * @returns {google.spanner.v1.Type} Type instance + */ + Type.create = function create(properties) { + return new Type(properties); + }; + + /** + * Encodes the specified Type message. Does not implicitly {@link google.spanner.v1.Type.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Type + * @static + * @param {google.spanner.v1.IType} message Type message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Type.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.code != null && Object.hasOwnProperty.call(message, "code")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.code); + if (message.arrayElementType != null && Object.hasOwnProperty.call(message, "arrayElementType")) + $root.google.spanner.v1.Type.encode(message.arrayElementType, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.structType != null && Object.hasOwnProperty.call(message, "structType")) + $root.google.spanner.v1.StructType.encode(message.structType, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.typeAnnotation != null && Object.hasOwnProperty.call(message, "typeAnnotation")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.typeAnnotation); + if (message.protoTypeFqn != null && Object.hasOwnProperty.call(message, "protoTypeFqn")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.protoTypeFqn); + return writer; + }; + + /** + * Encodes the specified Type message, length delimited. Does not implicitly {@link google.spanner.v1.Type.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Type + * @static + * @param {google.spanner.v1.IType} message Type message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Type.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Type message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Type + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Type} Type + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Type.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.spanner.v1.Type(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.code = reader.int32(); + break; + } + case 2: { + message.arrayElementType = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + } + case 3: { + message.structType = $root.google.spanner.v1.StructType.decode(reader, reader.uint32()); + break; + } + case 4: { + message.typeAnnotation = reader.int32(); + break; + } + case 5: { + message.protoTypeFqn = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Type message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Type + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Type} Type + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Type.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Type message. + * @function verify + * @memberof google.spanner.v1.Type + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Type.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.code != null && message.hasOwnProperty("code")) + switch (message.code) { + default: + return "code: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 15: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 13: + case 14: + case 16: + case 17: + break; + } + if (message.arrayElementType != null && message.hasOwnProperty("arrayElementType")) { + var error = $root.google.spanner.v1.Type.verify(message.arrayElementType); + if (error) + return "arrayElementType." + error; + } + if (message.structType != null && message.hasOwnProperty("structType")) { + var error = $root.google.spanner.v1.StructType.verify(message.structType); + if (error) + return "structType." + error; + } + if (message.typeAnnotation != null && message.hasOwnProperty("typeAnnotation")) + switch (message.typeAnnotation) { + default: + return "typeAnnotation: enum value expected"; + case 0: + case 2: + case 3: + case 4: + break; + } + if (message.protoTypeFqn != null && message.hasOwnProperty("protoTypeFqn")) + if (!$util.isString(message.protoTypeFqn)) + return "protoTypeFqn: string expected"; + return null; + }; + + /** + * Creates a Type message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Type + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Type} Type + */ + Type.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Type) + return object; + var message = new $root.google.spanner.v1.Type(); + switch (object.code) { + default: + if (typeof object.code === "number") { + message.code = object.code; + break; + } + break; + case "TYPE_CODE_UNSPECIFIED": + case 0: + message.code = 0; + break; + case "BOOL": + case 1: + message.code = 1; + break; + case "INT64": + case 2: + message.code = 2; + break; + case "FLOAT64": + case 3: + message.code = 3; + break; + case "FLOAT32": + case 15: + message.code = 15; + break; + case "TIMESTAMP": + case 4: + message.code = 4; + break; + case "DATE": + case 5: + message.code = 5; + break; + case "STRING": + case 6: + message.code = 6; + break; + case "BYTES": + case 7: + message.code = 7; + break; + case "ARRAY": + case 8: + message.code = 8; + break; + case "STRUCT": + case 9: + message.code = 9; + break; + case "NUMERIC": + case 10: + message.code = 10; + break; + case "JSON": + case 11: + message.code = 11; + break; + case "PROTO": + case 13: + message.code = 13; + break; + case "ENUM": + case 14: + message.code = 14; + break; + case "INTERVAL": + case 16: + message.code = 16; + break; + case "UUID": + case 17: + message.code = 17; + break; + } + if (object.arrayElementType != null) { + if (typeof object.arrayElementType !== "object") + throw TypeError(".google.spanner.v1.Type.arrayElementType: object expected"); + message.arrayElementType = $root.google.spanner.v1.Type.fromObject(object.arrayElementType); + } + if (object.structType != null) { + if (typeof object.structType !== "object") + throw TypeError(".google.spanner.v1.Type.structType: object expected"); + message.structType = $root.google.spanner.v1.StructType.fromObject(object.structType); + } + switch (object.typeAnnotation) { + default: + if (typeof object.typeAnnotation === "number") { + message.typeAnnotation = object.typeAnnotation; + break; + } + break; + case "TYPE_ANNOTATION_CODE_UNSPECIFIED": + case 0: + message.typeAnnotation = 0; + break; + case "PG_NUMERIC": + case 2: + message.typeAnnotation = 2; + break; + case "PG_JSONB": + case 3: + message.typeAnnotation = 3; + break; + case "PG_OID": + case 4: + message.typeAnnotation = 4; + break; + } + if (object.protoTypeFqn != null) + message.protoTypeFqn = String(object.protoTypeFqn); + return message; + }; + + /** + * Creates a plain object from a Type message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Type + * @static + * @param {google.spanner.v1.Type} message Type + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Type.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.code = options.enums === String ? "TYPE_CODE_UNSPECIFIED" : 0; + object.arrayElementType = null; + object.structType = null; + object.typeAnnotation = options.enums === String ? "TYPE_ANNOTATION_CODE_UNSPECIFIED" : 0; + object.protoTypeFqn = ""; + } + if (message.code != null && message.hasOwnProperty("code")) + object.code = options.enums === String ? $root.google.spanner.v1.TypeCode[message.code] === undefined ? message.code : $root.google.spanner.v1.TypeCode[message.code] : message.code; + if (message.arrayElementType != null && message.hasOwnProperty("arrayElementType")) + object.arrayElementType = $root.google.spanner.v1.Type.toObject(message.arrayElementType, options); + if (message.structType != null && message.hasOwnProperty("structType")) + object.structType = $root.google.spanner.v1.StructType.toObject(message.structType, options); + if (message.typeAnnotation != null && message.hasOwnProperty("typeAnnotation")) + object.typeAnnotation = options.enums === String ? $root.google.spanner.v1.TypeAnnotationCode[message.typeAnnotation] === undefined ? message.typeAnnotation : $root.google.spanner.v1.TypeAnnotationCode[message.typeAnnotation] : message.typeAnnotation; + if (message.protoTypeFqn != null && message.hasOwnProperty("protoTypeFqn")) + object.protoTypeFqn = message.protoTypeFqn; + return object; + }; + + /** + * Converts this Type to JSON. + * @function toJSON + * @memberof google.spanner.v1.Type + * @instance + * @returns {Object.} JSON object + */ + Type.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Type + * @function getTypeUrl + * @memberof google.spanner.v1.Type + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Type.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Type"; + }; + + return Type; + })(); + + v1.StructType = (function() { + + /** + * Properties of a StructType. + * @memberof google.spanner.v1 + * @interface IStructType + * @property {Array.|null} [fields] StructType fields + */ + + /** + * Constructs a new StructType. + * @memberof google.spanner.v1 + * @classdesc Represents a StructType. + * @implements IStructType + * @constructor + * @param {google.spanner.v1.IStructType=} [properties] Properties to set + */ + function StructType(properties) { + this.fields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StructType fields. + * @member {Array.} fields + * @memberof google.spanner.v1.StructType + * @instance + */ + StructType.prototype.fields = $util.emptyArray; + + /** + * Creates a new StructType instance using the specified properties. + * @function create + * @memberof google.spanner.v1.StructType + * @static + * @param {google.spanner.v1.IStructType=} [properties] Properties to set + * @returns {google.spanner.v1.StructType} StructType instance + */ + StructType.create = function create(properties) { + return new StructType(properties); + }; + + /** + * Encodes the specified StructType message. Does not implicitly {@link google.spanner.v1.StructType.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.StructType + * @static + * @param {google.spanner.v1.IStructType} message StructType message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StructType.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.fields != null && message.fields.length) + for (var i = 0; i < message.fields.length; ++i) + $root.google.spanner.v1.StructType.Field.encode(message.fields[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified StructType message, length delimited. Does not implicitly {@link google.spanner.v1.StructType.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.StructType + * @static + * @param {google.spanner.v1.IStructType} message StructType message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StructType.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a StructType message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.StructType + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.StructType} StructType + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StructType.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.spanner.v1.StructType(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.fields && message.fields.length)) + message.fields = []; + message.fields.push($root.google.spanner.v1.StructType.Field.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a StructType message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.StructType + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.StructType} StructType + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StructType.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a StructType message. + * @function verify + * @memberof google.spanner.v1.StructType + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + StructType.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.fields != null && message.hasOwnProperty("fields")) { + if (!Array.isArray(message.fields)) + return "fields: array expected"; + for (var i = 0; i < message.fields.length; ++i) { + var error = $root.google.spanner.v1.StructType.Field.verify(message.fields[i]); + if (error) + return "fields." + error; + } + } + return null; + }; + + /** + * Creates a StructType message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.StructType + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.StructType} StructType + */ + StructType.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.StructType) + return object; + var message = new $root.google.spanner.v1.StructType(); + if (object.fields) { + if (!Array.isArray(object.fields)) + throw TypeError(".google.spanner.v1.StructType.fields: array expected"); + message.fields = []; + for (var i = 0; i < object.fields.length; ++i) { + if (typeof object.fields[i] !== "object") + throw TypeError(".google.spanner.v1.StructType.fields: object expected"); + message.fields[i] = $root.google.spanner.v1.StructType.Field.fromObject(object.fields[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a StructType message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.StructType + * @static + * @param {google.spanner.v1.StructType} message StructType + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StructType.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fields = []; + if (message.fields && message.fields.length) { + object.fields = []; + for (var j = 0; j < message.fields.length; ++j) + object.fields[j] = $root.google.spanner.v1.StructType.Field.toObject(message.fields[j], options); + } + return object; + }; + + /** + * Converts this StructType to JSON. + * @function toJSON + * @memberof google.spanner.v1.StructType + * @instance + * @returns {Object.} JSON object + */ + StructType.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StructType + * @function getTypeUrl + * @memberof google.spanner.v1.StructType + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StructType.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.StructType"; + }; + + StructType.Field = (function() { + + /** + * Properties of a Field. + * @memberof google.spanner.v1.StructType + * @interface IField + * @property {string|null} [name] Field name + * @property {google.spanner.v1.IType|null} [type] Field type + */ + + /** + * Constructs a new Field. + * @memberof google.spanner.v1.StructType + * @classdesc Represents a Field. + * @implements IField + * @constructor + * @param {google.spanner.v1.StructType.IField=} [properties] Properties to set + */ + function Field(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Field name. + * @member {string} name + * @memberof google.spanner.v1.StructType.Field + * @instance + */ + Field.prototype.name = ""; + + /** + * Field type. + * @member {google.spanner.v1.IType|null|undefined} type + * @memberof google.spanner.v1.StructType.Field + * @instance + */ + Field.prototype.type = null; + + /** + * Creates a new Field instance using the specified properties. + * @function create + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {google.spanner.v1.StructType.IField=} [properties] Properties to set + * @returns {google.spanner.v1.StructType.Field} Field instance + */ + Field.create = function create(properties) { + return new Field(properties); + }; + + /** + * Encodes the specified Field message. Does not implicitly {@link google.spanner.v1.StructType.Field.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {google.spanner.v1.StructType.IField} message Field message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Field.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + $root.google.spanner.v1.Type.encode(message.type, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Field message, length delimited. Does not implicitly {@link google.spanner.v1.StructType.Field.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {google.spanner.v1.StructType.IField} message Field message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Field.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Field message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.StructType.Field} Field + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Field.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.spanner.v1.StructType.Field(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.type = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Field message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.StructType.Field} Field + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Field.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Field message. + * @function verify + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Field.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.type != null && message.hasOwnProperty("type")) { + var error = $root.google.spanner.v1.Type.verify(message.type); + if (error) + return "type." + error; + } + return null; + }; + + /** + * Creates a Field message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.StructType.Field} Field + */ + Field.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.StructType.Field) + return object; + var message = new $root.google.spanner.v1.StructType.Field(); + if (object.name != null) + message.name = String(object.name); + if (object.type != null) { + if (typeof object.type !== "object") + throw TypeError(".google.spanner.v1.StructType.Field.type: object expected"); + message.type = $root.google.spanner.v1.Type.fromObject(object.type); + } + return message; + }; + + /** + * Creates a plain object from a Field message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {google.spanner.v1.StructType.Field} message Field + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Field.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.type = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.type != null && message.hasOwnProperty("type")) + object.type = $root.google.spanner.v1.Type.toObject(message.type, options); + return object; + }; + + /** + * Converts this Field to JSON. + * @function toJSON + * @memberof google.spanner.v1.StructType.Field + * @instance + * @returns {Object.} JSON object + */ + Field.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Field + * @function getTypeUrl + * @memberof google.spanner.v1.StructType.Field + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Field.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.StructType.Field"; + }; + + return Field; + })(); + + return StructType; + })(); + + /** + * TypeCode enum. + * @name google.spanner.v1.TypeCode + * @enum {number} + * @property {number} TYPE_CODE_UNSPECIFIED=0 TYPE_CODE_UNSPECIFIED value + * @property {number} BOOL=1 BOOL value + * @property {number} INT64=2 INT64 value + * @property {number} FLOAT64=3 FLOAT64 value + * @property {number} FLOAT32=15 FLOAT32 value + * @property {number} TIMESTAMP=4 TIMESTAMP value + * @property {number} DATE=5 DATE value + * @property {number} STRING=6 STRING value + * @property {number} BYTES=7 BYTES value + * @property {number} ARRAY=8 ARRAY value + * @property {number} STRUCT=9 STRUCT value + * @property {number} NUMERIC=10 NUMERIC value + * @property {number} JSON=11 JSON value + * @property {number} PROTO=13 PROTO value + * @property {number} ENUM=14 ENUM value + * @property {number} INTERVAL=16 INTERVAL value + * @property {number} UUID=17 UUID value + */ + v1.TypeCode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_CODE_UNSPECIFIED"] = 0; + values[valuesById[1] = "BOOL"] = 1; + values[valuesById[2] = "INT64"] = 2; + values[valuesById[3] = "FLOAT64"] = 3; + values[valuesById[15] = "FLOAT32"] = 15; + values[valuesById[4] = "TIMESTAMP"] = 4; + values[valuesById[5] = "DATE"] = 5; + values[valuesById[6] = "STRING"] = 6; + values[valuesById[7] = "BYTES"] = 7; + values[valuesById[8] = "ARRAY"] = 8; + values[valuesById[9] = "STRUCT"] = 9; + values[valuesById[10] = "NUMERIC"] = 10; + values[valuesById[11] = "JSON"] = 11; + values[valuesById[13] = "PROTO"] = 13; + values[valuesById[14] = "ENUM"] = 14; + values[valuesById[16] = "INTERVAL"] = 16; + values[valuesById[17] = "UUID"] = 17; + return values; + })(); + + /** + * TypeAnnotationCode enum. + * @name google.spanner.v1.TypeAnnotationCode + * @enum {number} + * @property {number} TYPE_ANNOTATION_CODE_UNSPECIFIED=0 TYPE_ANNOTATION_CODE_UNSPECIFIED value + * @property {number} PG_NUMERIC=2 PG_NUMERIC value + * @property {number} PG_JSONB=3 PG_JSONB value + * @property {number} PG_OID=4 PG_OID value + */ + v1.TypeAnnotationCode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_ANNOTATION_CODE_UNSPECIFIED"] = 0; + values[valuesById[2] = "PG_NUMERIC"] = 2; + values[valuesById[3] = "PG_JSONB"] = 3; + values[valuesById[4] = "PG_OID"] = 4; + return values; + })(); + + v1.Mutation = (function() { + + /** + * Properties of a Mutation. + * @memberof google.spanner.v1 + * @interface IMutation + * @property {google.spanner.v1.Mutation.IWrite|null} [insert] Mutation insert + * @property {google.spanner.v1.Mutation.IWrite|null} [update] Mutation update + * @property {google.spanner.v1.Mutation.IWrite|null} [insertOrUpdate] Mutation insertOrUpdate + * @property {google.spanner.v1.Mutation.IWrite|null} [replace] Mutation replace + * @property {google.spanner.v1.Mutation.IDelete|null} ["delete"] Mutation delete + * @property {google.spanner.v1.Mutation.ISend|null} [send] Mutation send + * @property {google.spanner.v1.Mutation.IAck|null} [ack] Mutation ack + */ + + /** + * Constructs a new Mutation. + * @memberof google.spanner.v1 + * @classdesc Represents a Mutation. + * @implements IMutation + * @constructor + * @param {google.spanner.v1.IMutation=} [properties] Properties to set + */ + function Mutation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Mutation insert. + * @member {google.spanner.v1.Mutation.IWrite|null|undefined} insert + * @memberof google.spanner.v1.Mutation + * @instance + */ + Mutation.prototype.insert = null; + + /** + * Mutation update. + * @member {google.spanner.v1.Mutation.IWrite|null|undefined} update + * @memberof google.spanner.v1.Mutation + * @instance + */ + Mutation.prototype.update = null; + + /** + * Mutation insertOrUpdate. + * @member {google.spanner.v1.Mutation.IWrite|null|undefined} insertOrUpdate + * @memberof google.spanner.v1.Mutation + * @instance + */ + Mutation.prototype.insertOrUpdate = null; + + /** + * Mutation replace. + * @member {google.spanner.v1.Mutation.IWrite|null|undefined} replace + * @memberof google.spanner.v1.Mutation + * @instance + */ + Mutation.prototype.replace = null; + + /** + * Mutation delete. + * @member {google.spanner.v1.Mutation.IDelete|null|undefined} delete + * @memberof google.spanner.v1.Mutation + * @instance + */ + Mutation.prototype["delete"] = null; + + /** + * Mutation send. + * @member {google.spanner.v1.Mutation.ISend|null|undefined} send + * @memberof google.spanner.v1.Mutation + * @instance + */ + Mutation.prototype.send = null; + + /** + * Mutation ack. + * @member {google.spanner.v1.Mutation.IAck|null|undefined} ack + * @memberof google.spanner.v1.Mutation + * @instance + */ + Mutation.prototype.ack = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Mutation operation. + * @member {"insert"|"update"|"insertOrUpdate"|"replace"|"delete"|"send"|"ack"|undefined} operation + * @memberof google.spanner.v1.Mutation + * @instance + */ + Object.defineProperty(Mutation.prototype, "operation", { + get: $util.oneOfGetter($oneOfFields = ["insert", "update", "insertOrUpdate", "replace", "delete", "send", "ack"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new Mutation instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Mutation + * @static + * @param {google.spanner.v1.IMutation=} [properties] Properties to set + * @returns {google.spanner.v1.Mutation} Mutation instance + */ + Mutation.create = function create(properties) { + return new Mutation(properties); + }; + + /** + * Encodes the specified Mutation message. Does not implicitly {@link google.spanner.v1.Mutation.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Mutation + * @static + * @param {google.spanner.v1.IMutation} message Mutation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Mutation.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.insert != null && Object.hasOwnProperty.call(message, "insert")) + $root.google.spanner.v1.Mutation.Write.encode(message.insert, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.update != null && Object.hasOwnProperty.call(message, "update")) + $root.google.spanner.v1.Mutation.Write.encode(message.update, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.insertOrUpdate != null && Object.hasOwnProperty.call(message, "insertOrUpdate")) + $root.google.spanner.v1.Mutation.Write.encode(message.insertOrUpdate, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.replace != null && Object.hasOwnProperty.call(message, "replace")) + $root.google.spanner.v1.Mutation.Write.encode(message.replace, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message["delete"] != null && Object.hasOwnProperty.call(message, "delete")) + $root.google.spanner.v1.Mutation.Delete.encode(message["delete"], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.send != null && Object.hasOwnProperty.call(message, "send")) + $root.google.spanner.v1.Mutation.Send.encode(message.send, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.ack != null && Object.hasOwnProperty.call(message, "ack")) + $root.google.spanner.v1.Mutation.Ack.encode(message.ack, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Mutation message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Mutation + * @static + * @param {google.spanner.v1.IMutation} message Mutation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Mutation.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Mutation message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Mutation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Mutation} Mutation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Mutation.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.spanner.v1.Mutation(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.insert = $root.google.spanner.v1.Mutation.Write.decode(reader, reader.uint32()); + break; + } + case 2: { + message.update = $root.google.spanner.v1.Mutation.Write.decode(reader, reader.uint32()); + break; + } + case 3: { + message.insertOrUpdate = $root.google.spanner.v1.Mutation.Write.decode(reader, reader.uint32()); + break; + } + case 4: { + message.replace = $root.google.spanner.v1.Mutation.Write.decode(reader, reader.uint32()); + break; + } + case 5: { + message["delete"] = $root.google.spanner.v1.Mutation.Delete.decode(reader, reader.uint32()); + break; + } + case 6: { + message.send = $root.google.spanner.v1.Mutation.Send.decode(reader, reader.uint32()); + break; + } + case 7: { + message.ack = $root.google.spanner.v1.Mutation.Ack.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Mutation message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Mutation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Mutation} Mutation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Mutation.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Mutation message. + * @function verify + * @memberof google.spanner.v1.Mutation + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Mutation.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.insert != null && message.hasOwnProperty("insert")) { + properties.operation = 1; + { + var error = $root.google.spanner.v1.Mutation.Write.verify(message.insert); + if (error) + return "insert." + error; + } + } + if (message.update != null && message.hasOwnProperty("update")) { + if (properties.operation === 1) + return "operation: multiple values"; + properties.operation = 1; + { + var error = $root.google.spanner.v1.Mutation.Write.verify(message.update); + if (error) + return "update." + error; + } + } + if (message.insertOrUpdate != null && message.hasOwnProperty("insertOrUpdate")) { + if (properties.operation === 1) + return "operation: multiple values"; + properties.operation = 1; + { + var error = $root.google.spanner.v1.Mutation.Write.verify(message.insertOrUpdate); + if (error) + return "insertOrUpdate." + error; + } + } + if (message.replace != null && message.hasOwnProperty("replace")) { + if (properties.operation === 1) + return "operation: multiple values"; + properties.operation = 1; + { + var error = $root.google.spanner.v1.Mutation.Write.verify(message.replace); + if (error) + return "replace." + error; + } + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + if (properties.operation === 1) + return "operation: multiple values"; + properties.operation = 1; + { + var error = $root.google.spanner.v1.Mutation.Delete.verify(message["delete"]); + if (error) + return "delete." + error; + } + } + if (message.send != null && message.hasOwnProperty("send")) { + if (properties.operation === 1) + return "operation: multiple values"; + properties.operation = 1; + { + var error = $root.google.spanner.v1.Mutation.Send.verify(message.send); + if (error) + return "send." + error; + } + } + if (message.ack != null && message.hasOwnProperty("ack")) { + if (properties.operation === 1) + return "operation: multiple values"; + properties.operation = 1; + { + var error = $root.google.spanner.v1.Mutation.Ack.verify(message.ack); + if (error) + return "ack." + error; + } + } + return null; + }; + + /** + * Creates a Mutation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Mutation + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Mutation} Mutation + */ + Mutation.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Mutation) + return object; + var message = new $root.google.spanner.v1.Mutation(); + if (object.insert != null) { + if (typeof object.insert !== "object") + throw TypeError(".google.spanner.v1.Mutation.insert: object expected"); + message.insert = $root.google.spanner.v1.Mutation.Write.fromObject(object.insert); + } + if (object.update != null) { + if (typeof object.update !== "object") + throw TypeError(".google.spanner.v1.Mutation.update: object expected"); + message.update = $root.google.spanner.v1.Mutation.Write.fromObject(object.update); + } + if (object.insertOrUpdate != null) { + if (typeof object.insertOrUpdate !== "object") + throw TypeError(".google.spanner.v1.Mutation.insertOrUpdate: object expected"); + message.insertOrUpdate = $root.google.spanner.v1.Mutation.Write.fromObject(object.insertOrUpdate); + } + if (object.replace != null) { + if (typeof object.replace !== "object") + throw TypeError(".google.spanner.v1.Mutation.replace: object expected"); + message.replace = $root.google.spanner.v1.Mutation.Write.fromObject(object.replace); + } + if (object["delete"] != null) { + if (typeof object["delete"] !== "object") + throw TypeError(".google.spanner.v1.Mutation.delete: object expected"); + message["delete"] = $root.google.spanner.v1.Mutation.Delete.fromObject(object["delete"]); + } + if (object.send != null) { + if (typeof object.send !== "object") + throw TypeError(".google.spanner.v1.Mutation.send: object expected"); + message.send = $root.google.spanner.v1.Mutation.Send.fromObject(object.send); + } + if (object.ack != null) { + if (typeof object.ack !== "object") + throw TypeError(".google.spanner.v1.Mutation.ack: object expected"); + message.ack = $root.google.spanner.v1.Mutation.Ack.fromObject(object.ack); + } + return message; + }; + + /** + * Creates a plain object from a Mutation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Mutation + * @static + * @param {google.spanner.v1.Mutation} message Mutation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Mutation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.insert != null && message.hasOwnProperty("insert")) { + object.insert = $root.google.spanner.v1.Mutation.Write.toObject(message.insert, options); + if (options.oneofs) + object.operation = "insert"; + } + if (message.update != null && message.hasOwnProperty("update")) { + object.update = $root.google.spanner.v1.Mutation.Write.toObject(message.update, options); + if (options.oneofs) + object.operation = "update"; + } + if (message.insertOrUpdate != null && message.hasOwnProperty("insertOrUpdate")) { + object.insertOrUpdate = $root.google.spanner.v1.Mutation.Write.toObject(message.insertOrUpdate, options); + if (options.oneofs) + object.operation = "insertOrUpdate"; + } + if (message.replace != null && message.hasOwnProperty("replace")) { + object.replace = $root.google.spanner.v1.Mutation.Write.toObject(message.replace, options); + if (options.oneofs) + object.operation = "replace"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = $root.google.spanner.v1.Mutation.Delete.toObject(message["delete"], options); + if (options.oneofs) + object.operation = "delete"; + } + if (message.send != null && message.hasOwnProperty("send")) { + object.send = $root.google.spanner.v1.Mutation.Send.toObject(message.send, options); + if (options.oneofs) + object.operation = "send"; + } + if (message.ack != null && message.hasOwnProperty("ack")) { + object.ack = $root.google.spanner.v1.Mutation.Ack.toObject(message.ack, options); + if (options.oneofs) + object.operation = "ack"; + } + return object; + }; + + /** + * Converts this Mutation to JSON. + * @function toJSON + * @memberof google.spanner.v1.Mutation + * @instance + * @returns {Object.} JSON object + */ + Mutation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Mutation + * @function getTypeUrl + * @memberof google.spanner.v1.Mutation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Mutation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Mutation"; + }; + + Mutation.Write = (function() { + + /** + * Properties of a Write. + * @memberof google.spanner.v1.Mutation + * @interface IWrite + * @property {string|null} [table] Write table + * @property {Array.|null} [columns] Write columns + * @property {Array.|null} [values] Write values + */ + + /** + * Constructs a new Write. + * @memberof google.spanner.v1.Mutation + * @classdesc Represents a Write. + * @implements IWrite + * @constructor + * @param {google.spanner.v1.Mutation.IWrite=} [properties] Properties to set + */ + function Write(properties) { + this.columns = []; + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Write table. + * @member {string} table + * @memberof google.spanner.v1.Mutation.Write + * @instance + */ + Write.prototype.table = ""; + + /** + * Write columns. + * @member {Array.} columns + * @memberof google.spanner.v1.Mutation.Write + * @instance + */ + Write.prototype.columns = $util.emptyArray; + + /** + * Write values. + * @member {Array.} values + * @memberof google.spanner.v1.Mutation.Write + * @instance + */ + Write.prototype.values = $util.emptyArray; + + /** + * Creates a new Write instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {google.spanner.v1.Mutation.IWrite=} [properties] Properties to set + * @returns {google.spanner.v1.Mutation.Write} Write instance + */ + Write.create = function create(properties) { + return new Write(properties); + }; + + /** + * Encodes the specified Write message. Does not implicitly {@link google.spanner.v1.Mutation.Write.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {google.spanner.v1.Mutation.IWrite} message Write message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Write.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.table); + if (message.columns != null && message.columns.length) + for (var i = 0; i < message.columns.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.columns[i]); + if (message.values != null && message.values.length) + for (var i = 0; i < message.values.length; ++i) + $root.google.protobuf.ListValue.encode(message.values[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Write message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Write.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {google.spanner.v1.Mutation.IWrite} message Write message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Write.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Write message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Mutation.Write} Write + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Write.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.spanner.v1.Mutation.Write(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.table = reader.string(); + break; + } + case 2: { + if (!(message.columns && message.columns.length)) + message.columns = []; + message.columns.push(reader.string()); + break; + } + case 3: { + if (!(message.values && message.values.length)) + message.values = []; + message.values.push($root.google.protobuf.ListValue.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Write message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Mutation.Write} Write + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Write.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Write message. + * @function verify + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Write.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.columns != null && message.hasOwnProperty("columns")) { + if (!Array.isArray(message.columns)) + return "columns: array expected"; + for (var i = 0; i < message.columns.length; ++i) + if (!$util.isString(message.columns[i])) + return "columns: string[] expected"; + } + if (message.values != null && message.hasOwnProperty("values")) { + if (!Array.isArray(message.values)) + return "values: array expected"; + for (var i = 0; i < message.values.length; ++i) { + var error = $root.google.protobuf.ListValue.verify(message.values[i]); + if (error) + return "values." + error; + } + } + return null; + }; + + /** + * Creates a Write message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Mutation.Write} Write + */ + Write.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Mutation.Write) + return object; + var message = new $root.google.spanner.v1.Mutation.Write(); + if (object.table != null) + message.table = String(object.table); + if (object.columns) { + if (!Array.isArray(object.columns)) + throw TypeError(".google.spanner.v1.Mutation.Write.columns: array expected"); + message.columns = []; + for (var i = 0; i < object.columns.length; ++i) + message.columns[i] = String(object.columns[i]); + } + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.spanner.v1.Mutation.Write.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.spanner.v1.Mutation.Write.values: object expected"); + message.values[i] = $root.google.protobuf.ListValue.fromObject(object.values[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {google.spanner.v1.Mutation.Write} message Write + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Write.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.columns = []; + object.values = []; + } + if (options.defaults) + object.table = ""; + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.columns && message.columns.length) { + object.columns = []; + for (var j = 0; j < message.columns.length; ++j) + object.columns[j] = message.columns[j]; + } + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.protobuf.ListValue.toObject(message.values[j], options); + } + return object; + }; + + /** + * Converts this Write to JSON. + * @function toJSON + * @memberof google.spanner.v1.Mutation.Write + * @instance + * @returns {Object.} JSON object + */ + Write.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Write + * @function getTypeUrl + * @memberof google.spanner.v1.Mutation.Write + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Write.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Mutation.Write"; + }; + + return Write; + })(); + + Mutation.Delete = (function() { + + /** + * Properties of a Delete. + * @memberof google.spanner.v1.Mutation + * @interface IDelete + * @property {string|null} [table] Delete table + * @property {google.spanner.v1.IKeySet|null} [keySet] Delete keySet + */ + + /** + * Constructs a new Delete. + * @memberof google.spanner.v1.Mutation + * @classdesc Represents a Delete. + * @implements IDelete + * @constructor + * @param {google.spanner.v1.Mutation.IDelete=} [properties] Properties to set + */ + function Delete(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Delete table. + * @member {string} table + * @memberof google.spanner.v1.Mutation.Delete + * @instance + */ + Delete.prototype.table = ""; + + /** + * Delete keySet. + * @member {google.spanner.v1.IKeySet|null|undefined} keySet + * @memberof google.spanner.v1.Mutation.Delete + * @instance + */ + Delete.prototype.keySet = null; + + /** + * Creates a new Delete instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {google.spanner.v1.Mutation.IDelete=} [properties] Properties to set + * @returns {google.spanner.v1.Mutation.Delete} Delete instance + */ + Delete.create = function create(properties) { + return new Delete(properties); + }; + + /** + * Encodes the specified Delete message. Does not implicitly {@link google.spanner.v1.Mutation.Delete.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {google.spanner.v1.Mutation.IDelete} message Delete message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Delete.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.table); + if (message.keySet != null && Object.hasOwnProperty.call(message, "keySet")) + $root.google.spanner.v1.KeySet.encode(message.keySet, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Delete message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Delete.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {google.spanner.v1.Mutation.IDelete} message Delete message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Delete.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Delete message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Mutation.Delete} Delete + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Delete.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.spanner.v1.Mutation.Delete(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.table = reader.string(); + break; + } + case 2: { + message.keySet = $root.google.spanner.v1.KeySet.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Delete message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Mutation.Delete} Delete + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Delete.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Delete message. + * @function verify + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Delete.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.keySet != null && message.hasOwnProperty("keySet")) { + var error = $root.google.spanner.v1.KeySet.verify(message.keySet); + if (error) + return "keySet." + error; + } + return null; + }; + + /** + * Creates a Delete message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Mutation.Delete} Delete + */ + Delete.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Mutation.Delete) + return object; + var message = new $root.google.spanner.v1.Mutation.Delete(); + if (object.table != null) + message.table = String(object.table); + if (object.keySet != null) { + if (typeof object.keySet !== "object") + throw TypeError(".google.spanner.v1.Mutation.Delete.keySet: object expected"); + message.keySet = $root.google.spanner.v1.KeySet.fromObject(object.keySet); + } + return message; + }; + + /** + * Creates a plain object from a Delete message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {google.spanner.v1.Mutation.Delete} message Delete + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Delete.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.table = ""; + object.keySet = null; + } + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.keySet != null && message.hasOwnProperty("keySet")) + object.keySet = $root.google.spanner.v1.KeySet.toObject(message.keySet, options); + return object; + }; + + /** + * Converts this Delete to JSON. + * @function toJSON + * @memberof google.spanner.v1.Mutation.Delete + * @instance + * @returns {Object.} JSON object + */ + Delete.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Delete + * @function getTypeUrl + * @memberof google.spanner.v1.Mutation.Delete + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Delete.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Mutation.Delete"; + }; + + return Delete; + })(); + + Mutation.Send = (function() { + + /** + * Properties of a Send. + * @memberof google.spanner.v1.Mutation + * @interface ISend + * @property {string|null} [queue] Send queue + * @property {google.protobuf.IListValue|null} [key] Send key + * @property {google.protobuf.ITimestamp|null} [deliverTime] Send deliverTime + * @property {google.protobuf.IValue|null} [payload] Send payload + */ + + /** + * Constructs a new Send. + * @memberof google.spanner.v1.Mutation + * @classdesc Represents a Send. + * @implements ISend + * @constructor + * @param {google.spanner.v1.Mutation.ISend=} [properties] Properties to set + */ + function Send(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Send queue. + * @member {string} queue + * @memberof google.spanner.v1.Mutation.Send + * @instance + */ + Send.prototype.queue = ""; + + /** + * Send key. + * @member {google.protobuf.IListValue|null|undefined} key + * @memberof google.spanner.v1.Mutation.Send + * @instance + */ + Send.prototype.key = null; + + /** + * Send deliverTime. + * @member {google.protobuf.ITimestamp|null|undefined} deliverTime + * @memberof google.spanner.v1.Mutation.Send + * @instance + */ + Send.prototype.deliverTime = null; + + /** + * Send payload. + * @member {google.protobuf.IValue|null|undefined} payload + * @memberof google.spanner.v1.Mutation.Send + * @instance + */ + Send.prototype.payload = null; + + /** + * Creates a new Send instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {google.spanner.v1.Mutation.ISend=} [properties] Properties to set + * @returns {google.spanner.v1.Mutation.Send} Send instance + */ + Send.create = function create(properties) { + return new Send(properties); + }; + + /** + * Encodes the specified Send message. Does not implicitly {@link google.spanner.v1.Mutation.Send.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {google.spanner.v1.Mutation.ISend} message Send message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Send.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.queue != null && Object.hasOwnProperty.call(message, "queue")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.queue); + if (message.key != null && Object.hasOwnProperty.call(message, "key")) + $root.google.protobuf.ListValue.encode(message.key, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.deliverTime != null && Object.hasOwnProperty.call(message, "deliverTime")) + $root.google.protobuf.Timestamp.encode(message.deliverTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.payload != null && Object.hasOwnProperty.call(message, "payload")) + $root.google.protobuf.Value.encode(message.payload, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Send message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Send.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {google.spanner.v1.Mutation.ISend} message Send message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Send.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Send message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Mutation.Send} Send + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Send.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.spanner.v1.Mutation.Send(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.queue = reader.string(); + break; + } + case 2: { + message.key = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); + break; + } + case 3: { + message.deliverTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.payload = $root.google.protobuf.Value.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Send message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Mutation.Send} Send + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Send.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Send message. + * @function verify + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Send.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.queue != null && message.hasOwnProperty("queue")) + if (!$util.isString(message.queue)) + return "queue: string expected"; + if (message.key != null && message.hasOwnProperty("key")) { + var error = $root.google.protobuf.ListValue.verify(message.key); + if (error) + return "key." + error; + } + if (message.deliverTime != null && message.hasOwnProperty("deliverTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.deliverTime); + if (error) + return "deliverTime." + error; + } + if (message.payload != null && message.hasOwnProperty("payload")) { + var error = $root.google.protobuf.Value.verify(message.payload); + if (error) + return "payload." + error; + } + return null; + }; + + /** + * Creates a Send message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Mutation.Send} Send + */ + Send.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Mutation.Send) + return object; + var message = new $root.google.spanner.v1.Mutation.Send(); + if (object.queue != null) + message.queue = String(object.queue); + if (object.key != null) { + if (typeof object.key !== "object") + throw TypeError(".google.spanner.v1.Mutation.Send.key: object expected"); + message.key = $root.google.protobuf.ListValue.fromObject(object.key); + } + if (object.deliverTime != null) { + if (typeof object.deliverTime !== "object") + throw TypeError(".google.spanner.v1.Mutation.Send.deliverTime: object expected"); + message.deliverTime = $root.google.protobuf.Timestamp.fromObject(object.deliverTime); + } + if (object.payload != null) { + if (typeof object.payload !== "object") + throw TypeError(".google.spanner.v1.Mutation.Send.payload: object expected"); + message.payload = $root.google.protobuf.Value.fromObject(object.payload); + } + return message; + }; + + /** + * Creates a plain object from a Send message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {google.spanner.v1.Mutation.Send} message Send + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Send.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.queue = ""; + object.key = null; + object.deliverTime = null; + object.payload = null; + } + if (message.queue != null && message.hasOwnProperty("queue")) + object.queue = message.queue; + if (message.key != null && message.hasOwnProperty("key")) + object.key = $root.google.protobuf.ListValue.toObject(message.key, options); + if (message.deliverTime != null && message.hasOwnProperty("deliverTime")) + object.deliverTime = $root.google.protobuf.Timestamp.toObject(message.deliverTime, options); + if (message.payload != null && message.hasOwnProperty("payload")) + object.payload = $root.google.protobuf.Value.toObject(message.payload, options); + return object; + }; + + /** + * Converts this Send to JSON. + * @function toJSON + * @memberof google.spanner.v1.Mutation.Send + * @instance + * @returns {Object.} JSON object + */ + Send.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Send + * @function getTypeUrl + * @memberof google.spanner.v1.Mutation.Send + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Send.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Mutation.Send"; + }; + + return Send; + })(); + + Mutation.Ack = (function() { + + /** + * Properties of an Ack. + * @memberof google.spanner.v1.Mutation + * @interface IAck + * @property {string|null} [queue] Ack queue + * @property {google.protobuf.IListValue|null} [key] Ack key + * @property {boolean|null} [ignoreNotFound] Ack ignoreNotFound + */ + + /** + * Constructs a new Ack. + * @memberof google.spanner.v1.Mutation + * @classdesc Represents an Ack. + * @implements IAck + * @constructor + * @param {google.spanner.v1.Mutation.IAck=} [properties] Properties to set + */ + function Ack(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Ack queue. + * @member {string} queue + * @memberof google.spanner.v1.Mutation.Ack + * @instance + */ + Ack.prototype.queue = ""; + + /** + * Ack key. + * @member {google.protobuf.IListValue|null|undefined} key + * @memberof google.spanner.v1.Mutation.Ack + * @instance + */ + Ack.prototype.key = null; + + /** + * Ack ignoreNotFound. + * @member {boolean} ignoreNotFound + * @memberof google.spanner.v1.Mutation.Ack + * @instance + */ + Ack.prototype.ignoreNotFound = false; + + /** + * Creates a new Ack instance using the specified properties. + * @function create + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {google.spanner.v1.Mutation.IAck=} [properties] Properties to set + * @returns {google.spanner.v1.Mutation.Ack} Ack instance + */ + Ack.create = function create(properties) { + return new Ack(properties); + }; + + /** + * Encodes the specified Ack message. Does not implicitly {@link google.spanner.v1.Mutation.Ack.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {google.spanner.v1.Mutation.IAck} message Ack message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Ack.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.queue != null && Object.hasOwnProperty.call(message, "queue")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.queue); + if (message.key != null && Object.hasOwnProperty.call(message, "key")) + $root.google.protobuf.ListValue.encode(message.key, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.ignoreNotFound != null && Object.hasOwnProperty.call(message, "ignoreNotFound")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.ignoreNotFound); + return writer; + }; + + /** + * Encodes the specified Ack message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Ack.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {google.spanner.v1.Mutation.IAck} message Ack message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Ack.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an Ack message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.Mutation.Ack} Ack + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Ack.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.spanner.v1.Mutation.Ack(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.queue = reader.string(); + break; + } + case 2: { + message.key = $root.google.protobuf.ListValue.decode(reader, reader.uint32()); + break; + } + case 3: { + message.ignoreNotFound = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an Ack message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.Mutation.Ack} Ack + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Ack.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an Ack message. + * @function verify + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Ack.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.queue != null && message.hasOwnProperty("queue")) + if (!$util.isString(message.queue)) + return "queue: string expected"; + if (message.key != null && message.hasOwnProperty("key")) { + var error = $root.google.protobuf.ListValue.verify(message.key); + if (error) + return "key." + error; + } + if (message.ignoreNotFound != null && message.hasOwnProperty("ignoreNotFound")) + if (typeof message.ignoreNotFound !== "boolean") + return "ignoreNotFound: boolean expected"; + return null; + }; + + /** + * Creates an Ack message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.Mutation.Ack} Ack + */ + Ack.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.Mutation.Ack) + return object; + var message = new $root.google.spanner.v1.Mutation.Ack(); + if (object.queue != null) + message.queue = String(object.queue); + if (object.key != null) { + if (typeof object.key !== "object") + throw TypeError(".google.spanner.v1.Mutation.Ack.key: object expected"); + message.key = $root.google.protobuf.ListValue.fromObject(object.key); + } + if (object.ignoreNotFound != null) + message.ignoreNotFound = Boolean(object.ignoreNotFound); + return message; + }; + + /** + * Creates a plain object from an Ack message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {google.spanner.v1.Mutation.Ack} message Ack + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Ack.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.queue = ""; + object.key = null; + object.ignoreNotFound = false; + } + if (message.queue != null && message.hasOwnProperty("queue")) + object.queue = message.queue; + if (message.key != null && message.hasOwnProperty("key")) + object.key = $root.google.protobuf.ListValue.toObject(message.key, options); + if (message.ignoreNotFound != null && message.hasOwnProperty("ignoreNotFound")) + object.ignoreNotFound = message.ignoreNotFound; + return object; + }; + + /** + * Converts this Ack to JSON. + * @function toJSON + * @memberof google.spanner.v1.Mutation.Ack + * @instance + * @returns {Object.} JSON object + */ + Ack.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Ack + * @function getTypeUrl + * @memberof google.spanner.v1.Mutation.Ack + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Ack.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.Mutation.Ack"; + }; + + return Ack; + })(); + + return Mutation; + })(); + + v1.ResultSet = (function() { + + /** + * Properties of a ResultSet. + * @memberof google.spanner.v1 + * @interface IResultSet + * @property {google.spanner.v1.IResultSetMetadata|null} [metadata] ResultSet metadata + * @property {Array.|null} [rows] ResultSet rows + * @property {google.spanner.v1.IResultSetStats|null} [stats] ResultSet stats + * @property {google.spanner.v1.IMultiplexedSessionPrecommitToken|null} [precommitToken] ResultSet precommitToken + * @property {google.spanner.v1.ICacheUpdate|null} [cacheUpdate] ResultSet cacheUpdate + */ + + /** + * Constructs a new ResultSet. + * @memberof google.spanner.v1 + * @classdesc Represents a ResultSet. + * @implements IResultSet + * @constructor + * @param {google.spanner.v1.IResultSet=} [properties] Properties to set + */ + function ResultSet(properties) { + this.rows = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResultSet metadata. + * @member {google.spanner.v1.IResultSetMetadata|null|undefined} metadata + * @memberof google.spanner.v1.ResultSet + * @instance + */ + ResultSet.prototype.metadata = null; + + /** + * ResultSet rows. + * @member {Array.} rows + * @memberof google.spanner.v1.ResultSet + * @instance + */ + ResultSet.prototype.rows = $util.emptyArray; + + /** + * ResultSet stats. + * @member {google.spanner.v1.IResultSetStats|null|undefined} stats + * @memberof google.spanner.v1.ResultSet + * @instance + */ + ResultSet.prototype.stats = null; + + /** + * ResultSet precommitToken. + * @member {google.spanner.v1.IMultiplexedSessionPrecommitToken|null|undefined} precommitToken + * @memberof google.spanner.v1.ResultSet + * @instance + */ + ResultSet.prototype.precommitToken = null; + + /** + * ResultSet cacheUpdate. + * @member {google.spanner.v1.ICacheUpdate|null|undefined} cacheUpdate + * @memberof google.spanner.v1.ResultSet + * @instance + */ + ResultSet.prototype.cacheUpdate = null; + + /** + * Creates a new ResultSet instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ResultSet + * @static + * @param {google.spanner.v1.IResultSet=} [properties] Properties to set + * @returns {google.spanner.v1.ResultSet} ResultSet instance + */ + ResultSet.create = function create(properties) { + return new ResultSet(properties); + }; + + /** + * Encodes the specified ResultSet message. Does not implicitly {@link google.spanner.v1.ResultSet.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ResultSet + * @static + * @param {google.spanner.v1.IResultSet} message ResultSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResultSet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.metadata != null && Object.hasOwnProperty.call(message, "metadata")) + $root.google.spanner.v1.ResultSetMetadata.encode(message.metadata, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.rows != null && message.rows.length) + for (var i = 0; i < message.rows.length; ++i) + $root.google.protobuf.ListValue.encode(message.rows[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.stats != null && Object.hasOwnProperty.call(message, "stats")) + $root.google.spanner.v1.ResultSetStats.encode(message.stats, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.precommitToken != null && Object.hasOwnProperty.call(message, "precommitToken")) + $root.google.spanner.v1.MultiplexedSessionPrecommitToken.encode(message.precommitToken, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.cacheUpdate != null && Object.hasOwnProperty.call(message, "cacheUpdate")) + $root.google.spanner.v1.CacheUpdate.encode(message.cacheUpdate, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ResultSet message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ResultSet + * @static + * @param {google.spanner.v1.IResultSet} message ResultSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResultSet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ResultSet message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ResultSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ResultSet} ResultSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResultSet.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.spanner.v1.ResultSet(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.metadata = $root.google.spanner.v1.ResultSetMetadata.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.rows && message.rows.length)) + message.rows = []; + message.rows.push($root.google.protobuf.ListValue.decode(reader, reader.uint32())); + break; + } + case 3: { + message.stats = $root.google.spanner.v1.ResultSetStats.decode(reader, reader.uint32()); + break; + } + case 5: { + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.decode(reader, reader.uint32()); + break; + } + case 6: { + message.cacheUpdate = $root.google.spanner.v1.CacheUpdate.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ResultSet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ResultSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ResultSet} ResultSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResultSet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ResultSet message. + * @function verify + * @memberof google.spanner.v1.ResultSet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResultSet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.metadata != null && message.hasOwnProperty("metadata")) { + var error = $root.google.spanner.v1.ResultSetMetadata.verify(message.metadata); + if (error) + return "metadata." + error; + } + if (message.rows != null && message.hasOwnProperty("rows")) { + if (!Array.isArray(message.rows)) + return "rows: array expected"; + for (var i = 0; i < message.rows.length; ++i) { + var error = $root.google.protobuf.ListValue.verify(message.rows[i]); + if (error) + return "rows." + error; + } + } + if (message.stats != null && message.hasOwnProperty("stats")) { + var error = $root.google.spanner.v1.ResultSetStats.verify(message.stats); + if (error) + return "stats." + error; + } + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) { + var error = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.verify(message.precommitToken); + if (error) + return "precommitToken." + error; + } + if (message.cacheUpdate != null && message.hasOwnProperty("cacheUpdate")) { + var error = $root.google.spanner.v1.CacheUpdate.verify(message.cacheUpdate); + if (error) + return "cacheUpdate." + error; + } + return null; + }; + + /** + * Creates a ResultSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ResultSet + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ResultSet} ResultSet + */ + ResultSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ResultSet) + return object; + var message = new $root.google.spanner.v1.ResultSet(); + if (object.metadata != null) { + if (typeof object.metadata !== "object") + throw TypeError(".google.spanner.v1.ResultSet.metadata: object expected"); + message.metadata = $root.google.spanner.v1.ResultSetMetadata.fromObject(object.metadata); + } + if (object.rows) { + if (!Array.isArray(object.rows)) + throw TypeError(".google.spanner.v1.ResultSet.rows: array expected"); + message.rows = []; + for (var i = 0; i < object.rows.length; ++i) { + if (typeof object.rows[i] !== "object") + throw TypeError(".google.spanner.v1.ResultSet.rows: object expected"); + message.rows[i] = $root.google.protobuf.ListValue.fromObject(object.rows[i]); + } + } + if (object.stats != null) { + if (typeof object.stats !== "object") + throw TypeError(".google.spanner.v1.ResultSet.stats: object expected"); + message.stats = $root.google.spanner.v1.ResultSetStats.fromObject(object.stats); + } + if (object.precommitToken != null) { + if (typeof object.precommitToken !== "object") + throw TypeError(".google.spanner.v1.ResultSet.precommitToken: object expected"); + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.fromObject(object.precommitToken); + } + if (object.cacheUpdate != null) { + if (typeof object.cacheUpdate !== "object") + throw TypeError(".google.spanner.v1.ResultSet.cacheUpdate: object expected"); + message.cacheUpdate = $root.google.spanner.v1.CacheUpdate.fromObject(object.cacheUpdate); + } + return message; + }; + + /** + * Creates a plain object from a ResultSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ResultSet + * @static + * @param {google.spanner.v1.ResultSet} message ResultSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResultSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.rows = []; + if (options.defaults) { + object.metadata = null; + object.stats = null; + object.precommitToken = null; + object.cacheUpdate = null; + } + if (message.metadata != null && message.hasOwnProperty("metadata")) + object.metadata = $root.google.spanner.v1.ResultSetMetadata.toObject(message.metadata, options); + if (message.rows && message.rows.length) { + object.rows = []; + for (var j = 0; j < message.rows.length; ++j) + object.rows[j] = $root.google.protobuf.ListValue.toObject(message.rows[j], options); + } + if (message.stats != null && message.hasOwnProperty("stats")) + object.stats = $root.google.spanner.v1.ResultSetStats.toObject(message.stats, options); + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) + object.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.toObject(message.precommitToken, options); + if (message.cacheUpdate != null && message.hasOwnProperty("cacheUpdate")) + object.cacheUpdate = $root.google.spanner.v1.CacheUpdate.toObject(message.cacheUpdate, options); + return object; + }; + + /** + * Converts this ResultSet to JSON. + * @function toJSON + * @memberof google.spanner.v1.ResultSet + * @instance + * @returns {Object.} JSON object + */ + ResultSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResultSet + * @function getTypeUrl + * @memberof google.spanner.v1.ResultSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResultSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ResultSet"; + }; + + return ResultSet; + })(); + + v1.PartialResultSet = (function() { + + /** + * Properties of a PartialResultSet. + * @memberof google.spanner.v1 + * @interface IPartialResultSet + * @property {google.spanner.v1.IResultSetMetadata|null} [metadata] PartialResultSet metadata + * @property {Array.|null} [values] PartialResultSet values + * @property {boolean|null} [chunkedValue] PartialResultSet chunkedValue + * @property {Uint8Array|null} [resumeToken] PartialResultSet resumeToken + * @property {google.spanner.v1.IResultSetStats|null} [stats] PartialResultSet stats + * @property {google.spanner.v1.IMultiplexedSessionPrecommitToken|null} [precommitToken] PartialResultSet precommitToken + * @property {boolean|null} [last] PartialResultSet last + * @property {google.spanner.v1.ICacheUpdate|null} [cacheUpdate] PartialResultSet cacheUpdate + */ + + /** + * Constructs a new PartialResultSet. + * @memberof google.spanner.v1 + * @classdesc Represents a PartialResultSet. + * @implements IPartialResultSet + * @constructor + * @param {google.spanner.v1.IPartialResultSet=} [properties] Properties to set + */ + function PartialResultSet(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartialResultSet metadata. + * @member {google.spanner.v1.IResultSetMetadata|null|undefined} metadata + * @memberof google.spanner.v1.PartialResultSet + * @instance + */ + PartialResultSet.prototype.metadata = null; + + /** + * PartialResultSet values. + * @member {Array.} values + * @memberof google.spanner.v1.PartialResultSet + * @instance + */ + PartialResultSet.prototype.values = $util.emptyArray; + + /** + * PartialResultSet chunkedValue. + * @member {boolean} chunkedValue + * @memberof google.spanner.v1.PartialResultSet + * @instance + */ + PartialResultSet.prototype.chunkedValue = false; + + /** + * PartialResultSet resumeToken. + * @member {Uint8Array} resumeToken + * @memberof google.spanner.v1.PartialResultSet + * @instance + */ + PartialResultSet.prototype.resumeToken = $util.newBuffer([]); + + /** + * PartialResultSet stats. + * @member {google.spanner.v1.IResultSetStats|null|undefined} stats + * @memberof google.spanner.v1.PartialResultSet + * @instance + */ + PartialResultSet.prototype.stats = null; + + /** + * PartialResultSet precommitToken. + * @member {google.spanner.v1.IMultiplexedSessionPrecommitToken|null|undefined} precommitToken + * @memberof google.spanner.v1.PartialResultSet + * @instance + */ + PartialResultSet.prototype.precommitToken = null; + + /** + * PartialResultSet last. + * @member {boolean} last + * @memberof google.spanner.v1.PartialResultSet + * @instance + */ + PartialResultSet.prototype.last = false; + + /** + * PartialResultSet cacheUpdate. + * @member {google.spanner.v1.ICacheUpdate|null|undefined} cacheUpdate + * @memberof google.spanner.v1.PartialResultSet + * @instance + */ + PartialResultSet.prototype.cacheUpdate = null; + + /** + * Creates a new PartialResultSet instance using the specified properties. + * @function create + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {google.spanner.v1.IPartialResultSet=} [properties] Properties to set + * @returns {google.spanner.v1.PartialResultSet} PartialResultSet instance + */ + PartialResultSet.create = function create(properties) { + return new PartialResultSet(properties); + }; + + /** + * Encodes the specified PartialResultSet message. Does not implicitly {@link google.spanner.v1.PartialResultSet.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {google.spanner.v1.IPartialResultSet} message PartialResultSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartialResultSet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.metadata != null && Object.hasOwnProperty.call(message, "metadata")) + $root.google.spanner.v1.ResultSetMetadata.encode(message.metadata, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.values != null && message.values.length) + for (var i = 0; i < message.values.length; ++i) + $root.google.protobuf.Value.encode(message.values[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.chunkedValue != null && Object.hasOwnProperty.call(message, "chunkedValue")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.chunkedValue); + if (message.resumeToken != null && Object.hasOwnProperty.call(message, "resumeToken")) + writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.resumeToken); + if (message.stats != null && Object.hasOwnProperty.call(message, "stats")) + $root.google.spanner.v1.ResultSetStats.encode(message.stats, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.precommitToken != null && Object.hasOwnProperty.call(message, "precommitToken")) + $root.google.spanner.v1.MultiplexedSessionPrecommitToken.encode(message.precommitToken, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.last != null && Object.hasOwnProperty.call(message, "last")) + writer.uint32(/* id 9, wireType 0 =*/72).bool(message.last); + if (message.cacheUpdate != null && Object.hasOwnProperty.call(message, "cacheUpdate")) + $root.google.spanner.v1.CacheUpdate.encode(message.cacheUpdate, writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PartialResultSet message, length delimited. Does not implicitly {@link google.spanner.v1.PartialResultSet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {google.spanner.v1.IPartialResultSet} message PartialResultSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartialResultSet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartialResultSet message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.PartialResultSet} PartialResultSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartialResultSet.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.spanner.v1.PartialResultSet(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.metadata = $root.google.spanner.v1.ResultSetMetadata.decode(reader, reader.uint32()); + break; + } + case 2: { + if (!(message.values && message.values.length)) + message.values = []; + message.values.push($root.google.protobuf.Value.decode(reader, reader.uint32())); + break; + } + case 3: { + message.chunkedValue = reader.bool(); + break; + } + case 4: { + message.resumeToken = reader.bytes(); + break; + } + case 5: { + message.stats = $root.google.spanner.v1.ResultSetStats.decode(reader, reader.uint32()); + break; + } + case 8: { + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.decode(reader, reader.uint32()); + break; + } + case 9: { + message.last = reader.bool(); + break; + } + case 10: { + message.cacheUpdate = $root.google.spanner.v1.CacheUpdate.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartialResultSet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.PartialResultSet} PartialResultSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartialResultSet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartialResultSet message. + * @function verify + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartialResultSet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.metadata != null && message.hasOwnProperty("metadata")) { + var error = $root.google.spanner.v1.ResultSetMetadata.verify(message.metadata); + if (error) + return "metadata." + error; + } + if (message.values != null && message.hasOwnProperty("values")) { + if (!Array.isArray(message.values)) + return "values: array expected"; + for (var i = 0; i < message.values.length; ++i) { + var error = $root.google.protobuf.Value.verify(message.values[i]); + if (error) + return "values." + error; + } + } + if (message.chunkedValue != null && message.hasOwnProperty("chunkedValue")) + if (typeof message.chunkedValue !== "boolean") + return "chunkedValue: boolean expected"; + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + if (!(message.resumeToken && typeof message.resumeToken.length === "number" || $util.isString(message.resumeToken))) + return "resumeToken: buffer expected"; + if (message.stats != null && message.hasOwnProperty("stats")) { + var error = $root.google.spanner.v1.ResultSetStats.verify(message.stats); + if (error) + return "stats." + error; + } + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) { + var error = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.verify(message.precommitToken); + if (error) + return "precommitToken." + error; + } + if (message.last != null && message.hasOwnProperty("last")) + if (typeof message.last !== "boolean") + return "last: boolean expected"; + if (message.cacheUpdate != null && message.hasOwnProperty("cacheUpdate")) { + var error = $root.google.spanner.v1.CacheUpdate.verify(message.cacheUpdate); + if (error) + return "cacheUpdate." + error; + } + return null; + }; + + /** + * Creates a PartialResultSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.PartialResultSet} PartialResultSet + */ + PartialResultSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.PartialResultSet) + return object; + var message = new $root.google.spanner.v1.PartialResultSet(); + if (object.metadata != null) { + if (typeof object.metadata !== "object") + throw TypeError(".google.spanner.v1.PartialResultSet.metadata: object expected"); + message.metadata = $root.google.spanner.v1.ResultSetMetadata.fromObject(object.metadata); + } + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.spanner.v1.PartialResultSet.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.spanner.v1.PartialResultSet.values: object expected"); + message.values[i] = $root.google.protobuf.Value.fromObject(object.values[i]); + } + } + if (object.chunkedValue != null) + message.chunkedValue = Boolean(object.chunkedValue); + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + if (object.stats != null) { + if (typeof object.stats !== "object") + throw TypeError(".google.spanner.v1.PartialResultSet.stats: object expected"); + message.stats = $root.google.spanner.v1.ResultSetStats.fromObject(object.stats); + } + if (object.precommitToken != null) { + if (typeof object.precommitToken !== "object") + throw TypeError(".google.spanner.v1.PartialResultSet.precommitToken: object expected"); + message.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.fromObject(object.precommitToken); + } + if (object.last != null) + message.last = Boolean(object.last); + if (object.cacheUpdate != null) { + if (typeof object.cacheUpdate !== "object") + throw TypeError(".google.spanner.v1.PartialResultSet.cacheUpdate: object expected"); + message.cacheUpdate = $root.google.spanner.v1.CacheUpdate.fromObject(object.cacheUpdate); + } + return message; + }; + + /** + * Creates a plain object from a PartialResultSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {google.spanner.v1.PartialResultSet} message PartialResultSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartialResultSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (options.defaults) { + object.metadata = null; + object.chunkedValue = false; + if (options.bytes === String) + object.resumeToken = ""; + else { + object.resumeToken = []; + if (options.bytes !== Array) + object.resumeToken = $util.newBuffer(object.resumeToken); + } + object.stats = null; + object.precommitToken = null; + object.last = false; + object.cacheUpdate = null; + } + if (message.metadata != null && message.hasOwnProperty("metadata")) + object.metadata = $root.google.spanner.v1.ResultSetMetadata.toObject(message.metadata, options); + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.protobuf.Value.toObject(message.values[j], options); + } + if (message.chunkedValue != null && message.hasOwnProperty("chunkedValue")) + object.chunkedValue = message.chunkedValue; + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (message.stats != null && message.hasOwnProperty("stats")) + object.stats = $root.google.spanner.v1.ResultSetStats.toObject(message.stats, options); + if (message.precommitToken != null && message.hasOwnProperty("precommitToken")) + object.precommitToken = $root.google.spanner.v1.MultiplexedSessionPrecommitToken.toObject(message.precommitToken, options); + if (message.last != null && message.hasOwnProperty("last")) + object.last = message.last; + if (message.cacheUpdate != null && message.hasOwnProperty("cacheUpdate")) + object.cacheUpdate = $root.google.spanner.v1.CacheUpdate.toObject(message.cacheUpdate, options); + return object; + }; + + /** + * Converts this PartialResultSet to JSON. + * @function toJSON + * @memberof google.spanner.v1.PartialResultSet + * @instance + * @returns {Object.} JSON object + */ + PartialResultSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartialResultSet + * @function getTypeUrl + * @memberof google.spanner.v1.PartialResultSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartialResultSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.PartialResultSet"; + }; + + return PartialResultSet; + })(); + + v1.ResultSetMetadata = (function() { + + /** + * Properties of a ResultSetMetadata. + * @memberof google.spanner.v1 + * @interface IResultSetMetadata + * @property {google.spanner.v1.IStructType|null} [rowType] ResultSetMetadata rowType + * @property {google.spanner.v1.ITransaction|null} [transaction] ResultSetMetadata transaction + * @property {google.spanner.v1.IStructType|null} [undeclaredParameters] ResultSetMetadata undeclaredParameters + */ + + /** + * Constructs a new ResultSetMetadata. + * @memberof google.spanner.v1 + * @classdesc Represents a ResultSetMetadata. + * @implements IResultSetMetadata + * @constructor + * @param {google.spanner.v1.IResultSetMetadata=} [properties] Properties to set + */ + function ResultSetMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResultSetMetadata rowType. + * @member {google.spanner.v1.IStructType|null|undefined} rowType + * @memberof google.spanner.v1.ResultSetMetadata + * @instance + */ + ResultSetMetadata.prototype.rowType = null; + + /** + * ResultSetMetadata transaction. + * @member {google.spanner.v1.ITransaction|null|undefined} transaction + * @memberof google.spanner.v1.ResultSetMetadata + * @instance + */ + ResultSetMetadata.prototype.transaction = null; + + /** + * ResultSetMetadata undeclaredParameters. + * @member {google.spanner.v1.IStructType|null|undefined} undeclaredParameters + * @memberof google.spanner.v1.ResultSetMetadata + * @instance + */ + ResultSetMetadata.prototype.undeclaredParameters = null; + + /** + * Creates a new ResultSetMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {google.spanner.v1.IResultSetMetadata=} [properties] Properties to set + * @returns {google.spanner.v1.ResultSetMetadata} ResultSetMetadata instance + */ + ResultSetMetadata.create = function create(properties) { + return new ResultSetMetadata(properties); + }; + + /** + * Encodes the specified ResultSetMetadata message. Does not implicitly {@link google.spanner.v1.ResultSetMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {google.spanner.v1.IResultSetMetadata} message ResultSetMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResultSetMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.rowType != null && Object.hasOwnProperty.call(message, "rowType")) + $root.google.spanner.v1.StructType.encode(message.rowType, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.transaction != null && Object.hasOwnProperty.call(message, "transaction")) + $root.google.spanner.v1.Transaction.encode(message.transaction, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.undeclaredParameters != null && Object.hasOwnProperty.call(message, "undeclaredParameters")) + $root.google.spanner.v1.StructType.encode(message.undeclaredParameters, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ResultSetMetadata message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSetMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {google.spanner.v1.IResultSetMetadata} message ResultSetMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResultSetMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ResultSetMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ResultSetMetadata} ResultSetMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResultSetMetadata.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.spanner.v1.ResultSetMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.rowType = $root.google.spanner.v1.StructType.decode(reader, reader.uint32()); + break; + } + case 2: { + message.transaction = $root.google.spanner.v1.Transaction.decode(reader, reader.uint32()); + break; + } + case 3: { + message.undeclaredParameters = $root.google.spanner.v1.StructType.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ResultSetMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ResultSetMetadata} ResultSetMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResultSetMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ResultSetMetadata message. + * @function verify + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResultSetMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.rowType != null && message.hasOwnProperty("rowType")) { + var error = $root.google.spanner.v1.StructType.verify(message.rowType); + if (error) + return "rowType." + error; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) { + var error = $root.google.spanner.v1.Transaction.verify(message.transaction); + if (error) + return "transaction." + error; + } + if (message.undeclaredParameters != null && message.hasOwnProperty("undeclaredParameters")) { + var error = $root.google.spanner.v1.StructType.verify(message.undeclaredParameters); + if (error) + return "undeclaredParameters." + error; + } + return null; + }; + + /** + * Creates a ResultSetMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ResultSetMetadata} ResultSetMetadata + */ + ResultSetMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ResultSetMetadata) + return object; + var message = new $root.google.spanner.v1.ResultSetMetadata(); + if (object.rowType != null) { + if (typeof object.rowType !== "object") + throw TypeError(".google.spanner.v1.ResultSetMetadata.rowType: object expected"); + message.rowType = $root.google.spanner.v1.StructType.fromObject(object.rowType); + } + if (object.transaction != null) { + if (typeof object.transaction !== "object") + throw TypeError(".google.spanner.v1.ResultSetMetadata.transaction: object expected"); + message.transaction = $root.google.spanner.v1.Transaction.fromObject(object.transaction); + } + if (object.undeclaredParameters != null) { + if (typeof object.undeclaredParameters !== "object") + throw TypeError(".google.spanner.v1.ResultSetMetadata.undeclaredParameters: object expected"); + message.undeclaredParameters = $root.google.spanner.v1.StructType.fromObject(object.undeclaredParameters); + } + return message; + }; + + /** + * Creates a plain object from a ResultSetMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {google.spanner.v1.ResultSetMetadata} message ResultSetMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResultSetMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.rowType = null; + object.transaction = null; + object.undeclaredParameters = null; + } + if (message.rowType != null && message.hasOwnProperty("rowType")) + object.rowType = $root.google.spanner.v1.StructType.toObject(message.rowType, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = $root.google.spanner.v1.Transaction.toObject(message.transaction, options); + if (message.undeclaredParameters != null && message.hasOwnProperty("undeclaredParameters")) + object.undeclaredParameters = $root.google.spanner.v1.StructType.toObject(message.undeclaredParameters, options); + return object; + }; + + /** + * Converts this ResultSetMetadata to JSON. + * @function toJSON + * @memberof google.spanner.v1.ResultSetMetadata + * @instance + * @returns {Object.} JSON object + */ + ResultSetMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResultSetMetadata + * @function getTypeUrl + * @memberof google.spanner.v1.ResultSetMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResultSetMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ResultSetMetadata"; + }; + + return ResultSetMetadata; + })(); + + v1.ResultSetStats = (function() { + + /** + * Properties of a ResultSetStats. + * @memberof google.spanner.v1 + * @interface IResultSetStats + * @property {google.spanner.v1.IQueryPlan|null} [queryPlan] ResultSetStats queryPlan + * @property {google.protobuf.IStruct|null} [queryStats] ResultSetStats queryStats + * @property {number|Long|null} [rowCountExact] ResultSetStats rowCountExact + * @property {number|Long|null} [rowCountLowerBound] ResultSetStats rowCountLowerBound + */ + + /** + * Constructs a new ResultSetStats. + * @memberof google.spanner.v1 + * @classdesc Represents a ResultSetStats. + * @implements IResultSetStats + * @constructor + * @param {google.spanner.v1.IResultSetStats=} [properties] Properties to set + */ + function ResultSetStats(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResultSetStats queryPlan. + * @member {google.spanner.v1.IQueryPlan|null|undefined} queryPlan + * @memberof google.spanner.v1.ResultSetStats + * @instance + */ + ResultSetStats.prototype.queryPlan = null; + + /** + * ResultSetStats queryStats. + * @member {google.protobuf.IStruct|null|undefined} queryStats + * @memberof google.spanner.v1.ResultSetStats + * @instance + */ + ResultSetStats.prototype.queryStats = null; + + /** + * ResultSetStats rowCountExact. + * @member {number|Long|null|undefined} rowCountExact + * @memberof google.spanner.v1.ResultSetStats + * @instance + */ + ResultSetStats.prototype.rowCountExact = null; + + /** + * ResultSetStats rowCountLowerBound. + * @member {number|Long|null|undefined} rowCountLowerBound + * @memberof google.spanner.v1.ResultSetStats + * @instance + */ + ResultSetStats.prototype.rowCountLowerBound = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ResultSetStats rowCount. + * @member {"rowCountExact"|"rowCountLowerBound"|undefined} rowCount + * @memberof google.spanner.v1.ResultSetStats + * @instance + */ + Object.defineProperty(ResultSetStats.prototype, "rowCount", { + get: $util.oneOfGetter($oneOfFields = ["rowCountExact", "rowCountLowerBound"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ResultSetStats instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {google.spanner.v1.IResultSetStats=} [properties] Properties to set + * @returns {google.spanner.v1.ResultSetStats} ResultSetStats instance + */ + ResultSetStats.create = function create(properties) { + return new ResultSetStats(properties); + }; + + /** + * Encodes the specified ResultSetStats message. Does not implicitly {@link google.spanner.v1.ResultSetStats.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {google.spanner.v1.IResultSetStats} message ResultSetStats message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResultSetStats.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.queryPlan != null && Object.hasOwnProperty.call(message, "queryPlan")) + $root.google.spanner.v1.QueryPlan.encode(message.queryPlan, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.queryStats != null && Object.hasOwnProperty.call(message, "queryStats")) + $root.google.protobuf.Struct.encode(message.queryStats, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.rowCountExact != null && Object.hasOwnProperty.call(message, "rowCountExact")) + writer.uint32(/* id 3, wireType 0 =*/24).int64(message.rowCountExact); + if (message.rowCountLowerBound != null && Object.hasOwnProperty.call(message, "rowCountLowerBound")) + writer.uint32(/* id 4, wireType 0 =*/32).int64(message.rowCountLowerBound); + return writer; + }; + + /** + * Encodes the specified ResultSetStats message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSetStats.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {google.spanner.v1.IResultSetStats} message ResultSetStats message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResultSetStats.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ResultSetStats message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ResultSetStats} ResultSetStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResultSetStats.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.spanner.v1.ResultSetStats(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.queryPlan = $root.google.spanner.v1.QueryPlan.decode(reader, reader.uint32()); + break; + } + case 2: { + message.queryStats = $root.google.protobuf.Struct.decode(reader, reader.uint32()); + break; + } + case 3: { + message.rowCountExact = reader.int64(); + break; + } + case 4: { + message.rowCountLowerBound = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ResultSetStats message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ResultSetStats} ResultSetStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResultSetStats.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ResultSetStats message. + * @function verify + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResultSetStats.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.queryPlan != null && message.hasOwnProperty("queryPlan")) { + var error = $root.google.spanner.v1.QueryPlan.verify(message.queryPlan); + if (error) + return "queryPlan." + error; + } + if (message.queryStats != null && message.hasOwnProperty("queryStats")) { + var error = $root.google.protobuf.Struct.verify(message.queryStats); + if (error) + return "queryStats." + error; + } + if (message.rowCountExact != null && message.hasOwnProperty("rowCountExact")) { + properties.rowCount = 1; + if (!$util.isInteger(message.rowCountExact) && !(message.rowCountExact && $util.isInteger(message.rowCountExact.low) && $util.isInteger(message.rowCountExact.high))) + return "rowCountExact: integer|Long expected"; + } + if (message.rowCountLowerBound != null && message.hasOwnProperty("rowCountLowerBound")) { + if (properties.rowCount === 1) + return "rowCount: multiple values"; + properties.rowCount = 1; + if (!$util.isInteger(message.rowCountLowerBound) && !(message.rowCountLowerBound && $util.isInteger(message.rowCountLowerBound.low) && $util.isInteger(message.rowCountLowerBound.high))) + return "rowCountLowerBound: integer|Long expected"; + } + return null; + }; + + /** + * Creates a ResultSetStats message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ResultSetStats} ResultSetStats + */ + ResultSetStats.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ResultSetStats) + return object; + var message = new $root.google.spanner.v1.ResultSetStats(); + if (object.queryPlan != null) { + if (typeof object.queryPlan !== "object") + throw TypeError(".google.spanner.v1.ResultSetStats.queryPlan: object expected"); + message.queryPlan = $root.google.spanner.v1.QueryPlan.fromObject(object.queryPlan); + } + if (object.queryStats != null) { + if (typeof object.queryStats !== "object") + throw TypeError(".google.spanner.v1.ResultSetStats.queryStats: object expected"); + message.queryStats = $root.google.protobuf.Struct.fromObject(object.queryStats); + } + if (object.rowCountExact != null) + if ($util.Long) + (message.rowCountExact = $util.Long.fromValue(object.rowCountExact)).unsigned = false; + else if (typeof object.rowCountExact === "string") + message.rowCountExact = parseInt(object.rowCountExact, 10); + else if (typeof object.rowCountExact === "number") + message.rowCountExact = object.rowCountExact; + else if (typeof object.rowCountExact === "object") + message.rowCountExact = new $util.LongBits(object.rowCountExact.low >>> 0, object.rowCountExact.high >>> 0).toNumber(); + if (object.rowCountLowerBound != null) + if ($util.Long) + (message.rowCountLowerBound = $util.Long.fromValue(object.rowCountLowerBound)).unsigned = false; + else if (typeof object.rowCountLowerBound === "string") + message.rowCountLowerBound = parseInt(object.rowCountLowerBound, 10); + else if (typeof object.rowCountLowerBound === "number") + message.rowCountLowerBound = object.rowCountLowerBound; + else if (typeof object.rowCountLowerBound === "object") + message.rowCountLowerBound = new $util.LongBits(object.rowCountLowerBound.low >>> 0, object.rowCountLowerBound.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a ResultSetStats message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {google.spanner.v1.ResultSetStats} message ResultSetStats + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResultSetStats.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.queryPlan = null; + object.queryStats = null; + } + if (message.queryPlan != null && message.hasOwnProperty("queryPlan")) + object.queryPlan = $root.google.spanner.v1.QueryPlan.toObject(message.queryPlan, options); + if (message.queryStats != null && message.hasOwnProperty("queryStats")) + object.queryStats = $root.google.protobuf.Struct.toObject(message.queryStats, options); + if (message.rowCountExact != null && message.hasOwnProperty("rowCountExact")) { + if (typeof message.rowCountExact === "number") + object.rowCountExact = options.longs === String ? String(message.rowCountExact) : message.rowCountExact; + else + object.rowCountExact = options.longs === String ? $util.Long.prototype.toString.call(message.rowCountExact) : options.longs === Number ? new $util.LongBits(message.rowCountExact.low >>> 0, message.rowCountExact.high >>> 0).toNumber() : message.rowCountExact; + if (options.oneofs) + object.rowCount = "rowCountExact"; + } + if (message.rowCountLowerBound != null && message.hasOwnProperty("rowCountLowerBound")) { + if (typeof message.rowCountLowerBound === "number") + object.rowCountLowerBound = options.longs === String ? String(message.rowCountLowerBound) : message.rowCountLowerBound; + else + object.rowCountLowerBound = options.longs === String ? $util.Long.prototype.toString.call(message.rowCountLowerBound) : options.longs === Number ? new $util.LongBits(message.rowCountLowerBound.low >>> 0, message.rowCountLowerBound.high >>> 0).toNumber() : message.rowCountLowerBound; + if (options.oneofs) + object.rowCount = "rowCountLowerBound"; + } + return object; + }; + + /** + * Converts this ResultSetStats to JSON. + * @function toJSON + * @memberof google.spanner.v1.ResultSetStats + * @instance + * @returns {Object.} JSON object + */ + ResultSetStats.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResultSetStats + * @function getTypeUrl + * @memberof google.spanner.v1.ResultSetStats + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResultSetStats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ResultSetStats"; + }; + + return ResultSetStats; + })(); + + v1.PlanNode = (function() { + + /** + * Properties of a PlanNode. + * @memberof google.spanner.v1 + * @interface IPlanNode + * @property {number|null} [index] PlanNode index + * @property {google.spanner.v1.PlanNode.Kind|null} [kind] PlanNode kind + * @property {string|null} [displayName] PlanNode displayName + * @property {Array.|null} [childLinks] PlanNode childLinks + * @property {google.spanner.v1.PlanNode.IShortRepresentation|null} [shortRepresentation] PlanNode shortRepresentation + * @property {google.protobuf.IStruct|null} [metadata] PlanNode metadata + * @property {google.protobuf.IStruct|null} [executionStats] PlanNode executionStats + */ + + /** + * Constructs a new PlanNode. + * @memberof google.spanner.v1 + * @classdesc Represents a PlanNode. + * @implements IPlanNode + * @constructor + * @param {google.spanner.v1.IPlanNode=} [properties] Properties to set + */ + function PlanNode(properties) { + this.childLinks = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PlanNode index. + * @member {number} index + * @memberof google.spanner.v1.PlanNode + * @instance + */ + PlanNode.prototype.index = 0; + + /** + * PlanNode kind. + * @member {google.spanner.v1.PlanNode.Kind} kind + * @memberof google.spanner.v1.PlanNode + * @instance + */ + PlanNode.prototype.kind = 0; + + /** + * PlanNode displayName. + * @member {string} displayName + * @memberof google.spanner.v1.PlanNode + * @instance + */ + PlanNode.prototype.displayName = ""; + + /** + * PlanNode childLinks. + * @member {Array.} childLinks + * @memberof google.spanner.v1.PlanNode + * @instance + */ + PlanNode.prototype.childLinks = $util.emptyArray; + + /** + * PlanNode shortRepresentation. + * @member {google.spanner.v1.PlanNode.IShortRepresentation|null|undefined} shortRepresentation + * @memberof google.spanner.v1.PlanNode + * @instance + */ + PlanNode.prototype.shortRepresentation = null; + + /** + * PlanNode metadata. + * @member {google.protobuf.IStruct|null|undefined} metadata + * @memberof google.spanner.v1.PlanNode + * @instance + */ + PlanNode.prototype.metadata = null; + + /** + * PlanNode executionStats. + * @member {google.protobuf.IStruct|null|undefined} executionStats + * @memberof google.spanner.v1.PlanNode + * @instance + */ + PlanNode.prototype.executionStats = null; + + /** + * Creates a new PlanNode instance using the specified properties. + * @function create + * @memberof google.spanner.v1.PlanNode + * @static + * @param {google.spanner.v1.IPlanNode=} [properties] Properties to set + * @returns {google.spanner.v1.PlanNode} PlanNode instance + */ + PlanNode.create = function create(properties) { + return new PlanNode(properties); + }; + + /** + * Encodes the specified PlanNode message. Does not implicitly {@link google.spanner.v1.PlanNode.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.PlanNode + * @static + * @param {google.spanner.v1.IPlanNode} message PlanNode message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PlanNode.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.index != null && Object.hasOwnProperty.call(message, "index")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.index); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.kind); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.displayName); + if (message.childLinks != null && message.childLinks.length) + for (var i = 0; i < message.childLinks.length; ++i) + $root.google.spanner.v1.PlanNode.ChildLink.encode(message.childLinks[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.shortRepresentation != null && Object.hasOwnProperty.call(message, "shortRepresentation")) + $root.google.spanner.v1.PlanNode.ShortRepresentation.encode(message.shortRepresentation, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.metadata != null && Object.hasOwnProperty.call(message, "metadata")) + $root.google.protobuf.Struct.encode(message.metadata, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.executionStats != null && Object.hasOwnProperty.call(message, "executionStats")) + $root.google.protobuf.Struct.encode(message.executionStats, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PlanNode message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.PlanNode + * @static + * @param {google.spanner.v1.IPlanNode} message PlanNode message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PlanNode.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PlanNode message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.PlanNode + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.PlanNode} PlanNode + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PlanNode.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.spanner.v1.PlanNode(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.index = reader.int32(); + break; + } + case 2: { + message.kind = reader.int32(); + break; + } + case 3: { + message.displayName = reader.string(); + break; + } + case 4: { + if (!(message.childLinks && message.childLinks.length)) + message.childLinks = []; + message.childLinks.push($root.google.spanner.v1.PlanNode.ChildLink.decode(reader, reader.uint32())); + break; + } + case 5: { + message.shortRepresentation = $root.google.spanner.v1.PlanNode.ShortRepresentation.decode(reader, reader.uint32()); + break; + } + case 6: { + message.metadata = $root.google.protobuf.Struct.decode(reader, reader.uint32()); + break; + } + case 7: { + message.executionStats = $root.google.protobuf.Struct.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PlanNode message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.PlanNode + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.PlanNode} PlanNode + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PlanNode.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PlanNode message. + * @function verify + * @memberof google.spanner.v1.PlanNode + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PlanNode.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.index != null && message.hasOwnProperty("index")) + if (!$util.isInteger(message.index)) + return "index: integer expected"; + if (message.kind != null && message.hasOwnProperty("kind")) + switch (message.kind) { + default: + return "kind: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.displayName != null && message.hasOwnProperty("displayName")) + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + if (message.childLinks != null && message.hasOwnProperty("childLinks")) { + if (!Array.isArray(message.childLinks)) + return "childLinks: array expected"; + for (var i = 0; i < message.childLinks.length; ++i) { + var error = $root.google.spanner.v1.PlanNode.ChildLink.verify(message.childLinks[i]); + if (error) + return "childLinks." + error; + } + } + if (message.shortRepresentation != null && message.hasOwnProperty("shortRepresentation")) { + var error = $root.google.spanner.v1.PlanNode.ShortRepresentation.verify(message.shortRepresentation); + if (error) + return "shortRepresentation." + error; + } + if (message.metadata != null && message.hasOwnProperty("metadata")) { + var error = $root.google.protobuf.Struct.verify(message.metadata); + if (error) + return "metadata." + error; + } + if (message.executionStats != null && message.hasOwnProperty("executionStats")) { + var error = $root.google.protobuf.Struct.verify(message.executionStats); + if (error) + return "executionStats." + error; + } + return null; + }; + + /** + * Creates a PlanNode message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.PlanNode + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.PlanNode} PlanNode + */ + PlanNode.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.PlanNode) + return object; + var message = new $root.google.spanner.v1.PlanNode(); + if (object.index != null) + message.index = object.index | 0; + switch (object.kind) { + default: + if (typeof object.kind === "number") { + message.kind = object.kind; + break; + } + break; + case "KIND_UNSPECIFIED": + case 0: + message.kind = 0; + break; + case "RELATIONAL": + case 1: + message.kind = 1; + break; + case "SCALAR": + case 2: + message.kind = 2; + break; + } + if (object.displayName != null) + message.displayName = String(object.displayName); + if (object.childLinks) { + if (!Array.isArray(object.childLinks)) + throw TypeError(".google.spanner.v1.PlanNode.childLinks: array expected"); + message.childLinks = []; + for (var i = 0; i < object.childLinks.length; ++i) { + if (typeof object.childLinks[i] !== "object") + throw TypeError(".google.spanner.v1.PlanNode.childLinks: object expected"); + message.childLinks[i] = $root.google.spanner.v1.PlanNode.ChildLink.fromObject(object.childLinks[i]); + } + } + if (object.shortRepresentation != null) { + if (typeof object.shortRepresentation !== "object") + throw TypeError(".google.spanner.v1.PlanNode.shortRepresentation: object expected"); + message.shortRepresentation = $root.google.spanner.v1.PlanNode.ShortRepresentation.fromObject(object.shortRepresentation); + } + if (object.metadata != null) { + if (typeof object.metadata !== "object") + throw TypeError(".google.spanner.v1.PlanNode.metadata: object expected"); + message.metadata = $root.google.protobuf.Struct.fromObject(object.metadata); + } + if (object.executionStats != null) { + if (typeof object.executionStats !== "object") + throw TypeError(".google.spanner.v1.PlanNode.executionStats: object expected"); + message.executionStats = $root.google.protobuf.Struct.fromObject(object.executionStats); + } + return message; + }; + + /** + * Creates a plain object from a PlanNode message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.PlanNode + * @static + * @param {google.spanner.v1.PlanNode} message PlanNode + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PlanNode.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.childLinks = []; + if (options.defaults) { + object.index = 0; + object.kind = options.enums === String ? "KIND_UNSPECIFIED" : 0; + object.displayName = ""; + object.shortRepresentation = null; + object.metadata = null; + object.executionStats = null; + } + if (message.index != null && message.hasOwnProperty("index")) + object.index = message.index; + if (message.kind != null && message.hasOwnProperty("kind")) + object.kind = options.enums === String ? $root.google.spanner.v1.PlanNode.Kind[message.kind] === undefined ? message.kind : $root.google.spanner.v1.PlanNode.Kind[message.kind] : message.kind; + if (message.displayName != null && message.hasOwnProperty("displayName")) + object.displayName = message.displayName; + if (message.childLinks && message.childLinks.length) { + object.childLinks = []; + for (var j = 0; j < message.childLinks.length; ++j) + object.childLinks[j] = $root.google.spanner.v1.PlanNode.ChildLink.toObject(message.childLinks[j], options); + } + if (message.shortRepresentation != null && message.hasOwnProperty("shortRepresentation")) + object.shortRepresentation = $root.google.spanner.v1.PlanNode.ShortRepresentation.toObject(message.shortRepresentation, options); + if (message.metadata != null && message.hasOwnProperty("metadata")) + object.metadata = $root.google.protobuf.Struct.toObject(message.metadata, options); + if (message.executionStats != null && message.hasOwnProperty("executionStats")) + object.executionStats = $root.google.protobuf.Struct.toObject(message.executionStats, options); + return object; + }; + + /** + * Converts this PlanNode to JSON. + * @function toJSON + * @memberof google.spanner.v1.PlanNode + * @instance + * @returns {Object.} JSON object + */ + PlanNode.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PlanNode + * @function getTypeUrl + * @memberof google.spanner.v1.PlanNode + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PlanNode.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.PlanNode"; + }; + + /** + * Kind enum. + * @name google.spanner.v1.PlanNode.Kind + * @enum {number} + * @property {number} KIND_UNSPECIFIED=0 KIND_UNSPECIFIED value + * @property {number} RELATIONAL=1 RELATIONAL value + * @property {number} SCALAR=2 SCALAR value + */ + PlanNode.Kind = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "KIND_UNSPECIFIED"] = 0; + values[valuesById[1] = "RELATIONAL"] = 1; + values[valuesById[2] = "SCALAR"] = 2; + return values; + })(); + + PlanNode.ChildLink = (function() { + + /** + * Properties of a ChildLink. + * @memberof google.spanner.v1.PlanNode + * @interface IChildLink + * @property {number|null} [childIndex] ChildLink childIndex + * @property {string|null} [type] ChildLink type + * @property {string|null} [variable] ChildLink variable + */ + + /** + * Constructs a new ChildLink. + * @memberof google.spanner.v1.PlanNode + * @classdesc Represents a ChildLink. + * @implements IChildLink + * @constructor + * @param {google.spanner.v1.PlanNode.IChildLink=} [properties] Properties to set + */ + function ChildLink(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ChildLink childIndex. + * @member {number} childIndex + * @memberof google.spanner.v1.PlanNode.ChildLink + * @instance + */ + ChildLink.prototype.childIndex = 0; + + /** + * ChildLink type. + * @member {string} type + * @memberof google.spanner.v1.PlanNode.ChildLink + * @instance + */ + ChildLink.prototype.type = ""; + + /** + * ChildLink variable. + * @member {string} variable + * @memberof google.spanner.v1.PlanNode.ChildLink + * @instance + */ + ChildLink.prototype.variable = ""; + + /** + * Creates a new ChildLink instance using the specified properties. + * @function create + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {google.spanner.v1.PlanNode.IChildLink=} [properties] Properties to set + * @returns {google.spanner.v1.PlanNode.ChildLink} ChildLink instance + */ + ChildLink.create = function create(properties) { + return new ChildLink(properties); + }; + + /** + * Encodes the specified ChildLink message. Does not implicitly {@link google.spanner.v1.PlanNode.ChildLink.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {google.spanner.v1.PlanNode.IChildLink} message ChildLink message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChildLink.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.childIndex != null && Object.hasOwnProperty.call(message, "childIndex")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.childIndex); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.type); + if (message.variable != null && Object.hasOwnProperty.call(message, "variable")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.variable); + return writer; + }; + + /** + * Encodes the specified ChildLink message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.ChildLink.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {google.spanner.v1.PlanNode.IChildLink} message ChildLink message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChildLink.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ChildLink message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.PlanNode.ChildLink} ChildLink + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChildLink.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.spanner.v1.PlanNode.ChildLink(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.childIndex = reader.int32(); + break; + } + case 2: { + message.type = reader.string(); + break; + } + case 3: { + message.variable = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ChildLink message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.PlanNode.ChildLink} ChildLink + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChildLink.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ChildLink message. + * @function verify + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ChildLink.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.childIndex != null && message.hasOwnProperty("childIndex")) + if (!$util.isInteger(message.childIndex)) + return "childIndex: integer expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.variable != null && message.hasOwnProperty("variable")) + if (!$util.isString(message.variable)) + return "variable: string expected"; + return null; + }; + + /** + * Creates a ChildLink message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.PlanNode.ChildLink} ChildLink + */ + ChildLink.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.PlanNode.ChildLink) + return object; + var message = new $root.google.spanner.v1.PlanNode.ChildLink(); + if (object.childIndex != null) + message.childIndex = object.childIndex | 0; + if (object.type != null) + message.type = String(object.type); + if (object.variable != null) + message.variable = String(object.variable); + return message; + }; + + /** + * Creates a plain object from a ChildLink message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {google.spanner.v1.PlanNode.ChildLink} message ChildLink + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ChildLink.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.childIndex = 0; + object.type = ""; + object.variable = ""; + } + if (message.childIndex != null && message.hasOwnProperty("childIndex")) + object.childIndex = message.childIndex; + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.variable != null && message.hasOwnProperty("variable")) + object.variable = message.variable; + return object; + }; + + /** + * Converts this ChildLink to JSON. + * @function toJSON + * @memberof google.spanner.v1.PlanNode.ChildLink + * @instance + * @returns {Object.} JSON object + */ + ChildLink.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ChildLink + * @function getTypeUrl + * @memberof google.spanner.v1.PlanNode.ChildLink + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ChildLink.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.PlanNode.ChildLink"; + }; + + return ChildLink; + })(); + + PlanNode.ShortRepresentation = (function() { + + /** + * Properties of a ShortRepresentation. + * @memberof google.spanner.v1.PlanNode + * @interface IShortRepresentation + * @property {string|null} [description] ShortRepresentation description + * @property {Object.|null} [subqueries] ShortRepresentation subqueries + */ + + /** + * Constructs a new ShortRepresentation. + * @memberof google.spanner.v1.PlanNode + * @classdesc Represents a ShortRepresentation. + * @implements IShortRepresentation + * @constructor + * @param {google.spanner.v1.PlanNode.IShortRepresentation=} [properties] Properties to set + */ + function ShortRepresentation(properties) { + this.subqueries = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ShortRepresentation description. + * @member {string} description + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @instance + */ + ShortRepresentation.prototype.description = ""; + + /** + * ShortRepresentation subqueries. + * @member {Object.} subqueries + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @instance + */ + ShortRepresentation.prototype.subqueries = $util.emptyObject; + + /** + * Creates a new ShortRepresentation instance using the specified properties. + * @function create + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {google.spanner.v1.PlanNode.IShortRepresentation=} [properties] Properties to set + * @returns {google.spanner.v1.PlanNode.ShortRepresentation} ShortRepresentation instance + */ + ShortRepresentation.create = function create(properties) { + return new ShortRepresentation(properties); + }; + + /** + * Encodes the specified ShortRepresentation message. Does not implicitly {@link google.spanner.v1.PlanNode.ShortRepresentation.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {google.spanner.v1.PlanNode.IShortRepresentation} message ShortRepresentation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ShortRepresentation.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.description); + if (message.subqueries != null && Object.hasOwnProperty.call(message, "subqueries")) + for (var keys = Object.keys(message.subqueries), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 0 =*/16).int32(message.subqueries[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified ShortRepresentation message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.ShortRepresentation.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {google.spanner.v1.PlanNode.IShortRepresentation} message ShortRepresentation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ShortRepresentation.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ShortRepresentation message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.PlanNode.ShortRepresentation} ShortRepresentation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ShortRepresentation.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.spanner.v1.PlanNode.ShortRepresentation(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.description = reader.string(); + break; + } + case 2: { + if (message.subqueries === $util.emptyObject) + message.subqueries = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = 0; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.int32(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.subqueries[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ShortRepresentation message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.PlanNode.ShortRepresentation} ShortRepresentation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ShortRepresentation.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ShortRepresentation message. + * @function verify + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ShortRepresentation.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + if (message.subqueries != null && message.hasOwnProperty("subqueries")) { + if (!$util.isObject(message.subqueries)) + return "subqueries: object expected"; + var key = Object.keys(message.subqueries); + for (var i = 0; i < key.length; ++i) + if (!$util.isInteger(message.subqueries[key[i]])) + return "subqueries: integer{k:string} expected"; + } + return null; + }; + + /** + * Creates a ShortRepresentation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.PlanNode.ShortRepresentation} ShortRepresentation + */ + ShortRepresentation.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.PlanNode.ShortRepresentation) + return object; + var message = new $root.google.spanner.v1.PlanNode.ShortRepresentation(); + if (object.description != null) + message.description = String(object.description); + if (object.subqueries) { + if (typeof object.subqueries !== "object") + throw TypeError(".google.spanner.v1.PlanNode.ShortRepresentation.subqueries: object expected"); + message.subqueries = {}; + for (var keys = Object.keys(object.subqueries), i = 0; i < keys.length; ++i) + message.subqueries[keys[i]] = object.subqueries[keys[i]] | 0; + } + return message; + }; + + /** + * Creates a plain object from a ShortRepresentation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {google.spanner.v1.PlanNode.ShortRepresentation} message ShortRepresentation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ShortRepresentation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.subqueries = {}; + if (options.defaults) + object.description = ""; + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + var keys2; + if (message.subqueries && (keys2 = Object.keys(message.subqueries)).length) { + object.subqueries = {}; + for (var j = 0; j < keys2.length; ++j) + object.subqueries[keys2[j]] = message.subqueries[keys2[j]]; + } + return object; + }; + + /** + * Converts this ShortRepresentation to JSON. + * @function toJSON + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @instance + * @returns {Object.} JSON object + */ + ShortRepresentation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ShortRepresentation + * @function getTypeUrl + * @memberof google.spanner.v1.PlanNode.ShortRepresentation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ShortRepresentation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.PlanNode.ShortRepresentation"; + }; + + return ShortRepresentation; + })(); + + return PlanNode; + })(); + + v1.QueryAdvisorResult = (function() { + + /** + * Properties of a QueryAdvisorResult. + * @memberof google.spanner.v1 + * @interface IQueryAdvisorResult + * @property {Array.|null} [indexAdvice] QueryAdvisorResult indexAdvice + */ + + /** + * Constructs a new QueryAdvisorResult. + * @memberof google.spanner.v1 + * @classdesc Represents a QueryAdvisorResult. + * @implements IQueryAdvisorResult + * @constructor + * @param {google.spanner.v1.IQueryAdvisorResult=} [properties] Properties to set + */ + function QueryAdvisorResult(properties) { + this.indexAdvice = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QueryAdvisorResult indexAdvice. + * @member {Array.} indexAdvice + * @memberof google.spanner.v1.QueryAdvisorResult + * @instance + */ + QueryAdvisorResult.prototype.indexAdvice = $util.emptyArray; + + /** + * Creates a new QueryAdvisorResult instance using the specified properties. + * @function create + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {google.spanner.v1.IQueryAdvisorResult=} [properties] Properties to set + * @returns {google.spanner.v1.QueryAdvisorResult} QueryAdvisorResult instance + */ + QueryAdvisorResult.create = function create(properties) { + return new QueryAdvisorResult(properties); + }; + + /** + * Encodes the specified QueryAdvisorResult message. Does not implicitly {@link google.spanner.v1.QueryAdvisorResult.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {google.spanner.v1.IQueryAdvisorResult} message QueryAdvisorResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryAdvisorResult.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.indexAdvice != null && message.indexAdvice.length) + for (var i = 0; i < message.indexAdvice.length; ++i) + $root.google.spanner.v1.QueryAdvisorResult.IndexAdvice.encode(message.indexAdvice[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified QueryAdvisorResult message, length delimited. Does not implicitly {@link google.spanner.v1.QueryAdvisorResult.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {google.spanner.v1.IQueryAdvisorResult} message QueryAdvisorResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryAdvisorResult.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a QueryAdvisorResult message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.QueryAdvisorResult} QueryAdvisorResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryAdvisorResult.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.spanner.v1.QueryAdvisorResult(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.indexAdvice && message.indexAdvice.length)) + message.indexAdvice = []; + message.indexAdvice.push($root.google.spanner.v1.QueryAdvisorResult.IndexAdvice.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a QueryAdvisorResult message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.QueryAdvisorResult} QueryAdvisorResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryAdvisorResult.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a QueryAdvisorResult message. + * @function verify + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + QueryAdvisorResult.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.indexAdvice != null && message.hasOwnProperty("indexAdvice")) { + if (!Array.isArray(message.indexAdvice)) + return "indexAdvice: array expected"; + for (var i = 0; i < message.indexAdvice.length; ++i) { + var error = $root.google.spanner.v1.QueryAdvisorResult.IndexAdvice.verify(message.indexAdvice[i]); + if (error) + return "indexAdvice." + error; + } + } + return null; + }; + + /** + * Creates a QueryAdvisorResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.QueryAdvisorResult} QueryAdvisorResult + */ + QueryAdvisorResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.QueryAdvisorResult) + return object; + var message = new $root.google.spanner.v1.QueryAdvisorResult(); + if (object.indexAdvice) { + if (!Array.isArray(object.indexAdvice)) + throw TypeError(".google.spanner.v1.QueryAdvisorResult.indexAdvice: array expected"); + message.indexAdvice = []; + for (var i = 0; i < object.indexAdvice.length; ++i) { + if (typeof object.indexAdvice[i] !== "object") + throw TypeError(".google.spanner.v1.QueryAdvisorResult.indexAdvice: object expected"); + message.indexAdvice[i] = $root.google.spanner.v1.QueryAdvisorResult.IndexAdvice.fromObject(object.indexAdvice[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a QueryAdvisorResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {google.spanner.v1.QueryAdvisorResult} message QueryAdvisorResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryAdvisorResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.indexAdvice = []; + if (message.indexAdvice && message.indexAdvice.length) { + object.indexAdvice = []; + for (var j = 0; j < message.indexAdvice.length; ++j) + object.indexAdvice[j] = $root.google.spanner.v1.QueryAdvisorResult.IndexAdvice.toObject(message.indexAdvice[j], options); + } + return object; + }; + + /** + * Converts this QueryAdvisorResult to JSON. + * @function toJSON + * @memberof google.spanner.v1.QueryAdvisorResult + * @instance + * @returns {Object.} JSON object + */ + QueryAdvisorResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QueryAdvisorResult + * @function getTypeUrl + * @memberof google.spanner.v1.QueryAdvisorResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryAdvisorResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.QueryAdvisorResult"; + }; + + QueryAdvisorResult.IndexAdvice = (function() { + + /** + * Properties of an IndexAdvice. + * @memberof google.spanner.v1.QueryAdvisorResult + * @interface IIndexAdvice + * @property {Array.|null} [ddl] IndexAdvice ddl + * @property {number|null} [improvementFactor] IndexAdvice improvementFactor + */ + + /** + * Constructs a new IndexAdvice. + * @memberof google.spanner.v1.QueryAdvisorResult + * @classdesc Represents an IndexAdvice. + * @implements IIndexAdvice + * @constructor + * @param {google.spanner.v1.QueryAdvisorResult.IIndexAdvice=} [properties] Properties to set + */ + function IndexAdvice(properties) { + this.ddl = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * IndexAdvice ddl. + * @member {Array.} ddl + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @instance + */ + IndexAdvice.prototype.ddl = $util.emptyArray; + + /** + * IndexAdvice improvementFactor. + * @member {number} improvementFactor + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @instance + */ + IndexAdvice.prototype.improvementFactor = 0; + + /** + * Creates a new IndexAdvice instance using the specified properties. + * @function create + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {google.spanner.v1.QueryAdvisorResult.IIndexAdvice=} [properties] Properties to set + * @returns {google.spanner.v1.QueryAdvisorResult.IndexAdvice} IndexAdvice instance + */ + IndexAdvice.create = function create(properties) { + return new IndexAdvice(properties); + }; + + /** + * Encodes the specified IndexAdvice message. Does not implicitly {@link google.spanner.v1.QueryAdvisorResult.IndexAdvice.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {google.spanner.v1.QueryAdvisorResult.IIndexAdvice} message IndexAdvice message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IndexAdvice.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.ddl != null && message.ddl.length) + for (var i = 0; i < message.ddl.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.ddl[i]); + if (message.improvementFactor != null && Object.hasOwnProperty.call(message, "improvementFactor")) + writer.uint32(/* id 2, wireType 1 =*/17).double(message.improvementFactor); + return writer; + }; + + /** + * Encodes the specified IndexAdvice message, length delimited. Does not implicitly {@link google.spanner.v1.QueryAdvisorResult.IndexAdvice.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {google.spanner.v1.QueryAdvisorResult.IIndexAdvice} message IndexAdvice message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IndexAdvice.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an IndexAdvice message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.QueryAdvisorResult.IndexAdvice} IndexAdvice + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IndexAdvice.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.spanner.v1.QueryAdvisorResult.IndexAdvice(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.ddl && message.ddl.length)) + message.ddl = []; + message.ddl.push(reader.string()); + break; + } + case 2: { + message.improvementFactor = reader.double(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an IndexAdvice message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.QueryAdvisorResult.IndexAdvice} IndexAdvice + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IndexAdvice.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an IndexAdvice message. + * @function verify + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + IndexAdvice.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.ddl != null && message.hasOwnProperty("ddl")) { + if (!Array.isArray(message.ddl)) + return "ddl: array expected"; + for (var i = 0; i < message.ddl.length; ++i) + if (!$util.isString(message.ddl[i])) + return "ddl: string[] expected"; + } + if (message.improvementFactor != null && message.hasOwnProperty("improvementFactor")) + if (typeof message.improvementFactor !== "number") + return "improvementFactor: number expected"; + return null; + }; + + /** + * Creates an IndexAdvice message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.QueryAdvisorResult.IndexAdvice} IndexAdvice + */ + IndexAdvice.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.QueryAdvisorResult.IndexAdvice) + return object; + var message = new $root.google.spanner.v1.QueryAdvisorResult.IndexAdvice(); + if (object.ddl) { + if (!Array.isArray(object.ddl)) + throw TypeError(".google.spanner.v1.QueryAdvisorResult.IndexAdvice.ddl: array expected"); + message.ddl = []; + for (var i = 0; i < object.ddl.length; ++i) + message.ddl[i] = String(object.ddl[i]); + } + if (object.improvementFactor != null) + message.improvementFactor = Number(object.improvementFactor); + return message; + }; + + /** + * Creates a plain object from an IndexAdvice message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {google.spanner.v1.QueryAdvisorResult.IndexAdvice} message IndexAdvice + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IndexAdvice.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.ddl = []; + if (options.defaults) + object.improvementFactor = 0; + if (message.ddl && message.ddl.length) { + object.ddl = []; + for (var j = 0; j < message.ddl.length; ++j) + object.ddl[j] = message.ddl[j]; + } + if (message.improvementFactor != null && message.hasOwnProperty("improvementFactor")) + object.improvementFactor = options.json && !isFinite(message.improvementFactor) ? String(message.improvementFactor) : message.improvementFactor; + return object; + }; + + /** + * Converts this IndexAdvice to JSON. + * @function toJSON + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @instance + * @returns {Object.} JSON object + */ + IndexAdvice.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IndexAdvice + * @function getTypeUrl + * @memberof google.spanner.v1.QueryAdvisorResult.IndexAdvice + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IndexAdvice.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.QueryAdvisorResult.IndexAdvice"; + }; + + return IndexAdvice; + })(); + + return QueryAdvisorResult; + })(); + + v1.QueryPlan = (function() { + + /** + * Properties of a QueryPlan. + * @memberof google.spanner.v1 + * @interface IQueryPlan + * @property {Array.|null} [planNodes] QueryPlan planNodes + * @property {google.spanner.v1.IQueryAdvisorResult|null} [queryAdvice] QueryPlan queryAdvice + */ + + /** + * Constructs a new QueryPlan. + * @memberof google.spanner.v1 + * @classdesc Represents a QueryPlan. + * @implements IQueryPlan + * @constructor + * @param {google.spanner.v1.IQueryPlan=} [properties] Properties to set + */ + function QueryPlan(properties) { + this.planNodes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * QueryPlan planNodes. + * @member {Array.} planNodes + * @memberof google.spanner.v1.QueryPlan + * @instance + */ + QueryPlan.prototype.planNodes = $util.emptyArray; + + /** + * QueryPlan queryAdvice. + * @member {google.spanner.v1.IQueryAdvisorResult|null|undefined} queryAdvice + * @memberof google.spanner.v1.QueryPlan + * @instance + */ + QueryPlan.prototype.queryAdvice = null; + + /** + * Creates a new QueryPlan instance using the specified properties. + * @function create + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {google.spanner.v1.IQueryPlan=} [properties] Properties to set + * @returns {google.spanner.v1.QueryPlan} QueryPlan instance + */ + QueryPlan.create = function create(properties) { + return new QueryPlan(properties); + }; + + /** + * Encodes the specified QueryPlan message. Does not implicitly {@link google.spanner.v1.QueryPlan.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {google.spanner.v1.IQueryPlan} message QueryPlan message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryPlan.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.planNodes != null && message.planNodes.length) + for (var i = 0; i < message.planNodes.length; ++i) + $root.google.spanner.v1.PlanNode.encode(message.planNodes[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.queryAdvice != null && Object.hasOwnProperty.call(message, "queryAdvice")) + $root.google.spanner.v1.QueryAdvisorResult.encode(message.queryAdvice, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified QueryPlan message, length delimited. Does not implicitly {@link google.spanner.v1.QueryPlan.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {google.spanner.v1.IQueryPlan} message QueryPlan message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + QueryPlan.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a QueryPlan message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.QueryPlan} QueryPlan + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryPlan.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.spanner.v1.QueryPlan(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.planNodes && message.planNodes.length)) + message.planNodes = []; + message.planNodes.push($root.google.spanner.v1.PlanNode.decode(reader, reader.uint32())); + break; + } + case 2: { + message.queryAdvice = $root.google.spanner.v1.QueryAdvisorResult.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a QueryPlan message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.QueryPlan} QueryPlan + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + QueryPlan.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a QueryPlan message. + * @function verify + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + QueryPlan.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.planNodes != null && message.hasOwnProperty("planNodes")) { + if (!Array.isArray(message.planNodes)) + return "planNodes: array expected"; + for (var i = 0; i < message.planNodes.length; ++i) { + var error = $root.google.spanner.v1.PlanNode.verify(message.planNodes[i]); + if (error) + return "planNodes." + error; + } + } + if (message.queryAdvice != null && message.hasOwnProperty("queryAdvice")) { + var error = $root.google.spanner.v1.QueryAdvisorResult.verify(message.queryAdvice); + if (error) + return "queryAdvice." + error; + } + return null; + }; + + /** + * Creates a QueryPlan message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.QueryPlan} QueryPlan + */ + QueryPlan.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.QueryPlan) + return object; + var message = new $root.google.spanner.v1.QueryPlan(); + if (object.planNodes) { + if (!Array.isArray(object.planNodes)) + throw TypeError(".google.spanner.v1.QueryPlan.planNodes: array expected"); + message.planNodes = []; + for (var i = 0; i < object.planNodes.length; ++i) { + if (typeof object.planNodes[i] !== "object") + throw TypeError(".google.spanner.v1.QueryPlan.planNodes: object expected"); + message.planNodes[i] = $root.google.spanner.v1.PlanNode.fromObject(object.planNodes[i]); + } + } + if (object.queryAdvice != null) { + if (typeof object.queryAdvice !== "object") + throw TypeError(".google.spanner.v1.QueryPlan.queryAdvice: object expected"); + message.queryAdvice = $root.google.spanner.v1.QueryAdvisorResult.fromObject(object.queryAdvice); + } + return message; + }; + + /** + * Creates a plain object from a QueryPlan message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {google.spanner.v1.QueryPlan} message QueryPlan + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryPlan.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.planNodes = []; + if (options.defaults) + object.queryAdvice = null; + if (message.planNodes && message.planNodes.length) { + object.planNodes = []; + for (var j = 0; j < message.planNodes.length; ++j) + object.planNodes[j] = $root.google.spanner.v1.PlanNode.toObject(message.planNodes[j], options); + } + if (message.queryAdvice != null && message.hasOwnProperty("queryAdvice")) + object.queryAdvice = $root.google.spanner.v1.QueryAdvisorResult.toObject(message.queryAdvice, options); + return object; + }; + + /** + * Converts this QueryPlan to JSON. + * @function toJSON + * @memberof google.spanner.v1.QueryPlan + * @instance + * @returns {Object.} JSON object + */ + QueryPlan.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for QueryPlan + * @function getTypeUrl + * @memberof google.spanner.v1.QueryPlan + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryPlan.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.QueryPlan"; + }; + + return QueryPlan; + })(); + + v1.ChangeStreamRecord = (function() { + + /** + * Properties of a ChangeStreamRecord. + * @memberof google.spanner.v1 + * @interface IChangeStreamRecord + * @property {google.spanner.v1.ChangeStreamRecord.IDataChangeRecord|null} [dataChangeRecord] ChangeStreamRecord dataChangeRecord + * @property {google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord|null} [heartbeatRecord] ChangeStreamRecord heartbeatRecord + * @property {google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord|null} [partitionStartRecord] ChangeStreamRecord partitionStartRecord + * @property {google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord|null} [partitionEndRecord] ChangeStreamRecord partitionEndRecord + * @property {google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord|null} [partitionEventRecord] ChangeStreamRecord partitionEventRecord + */ + + /** + * Constructs a new ChangeStreamRecord. + * @memberof google.spanner.v1 + * @classdesc Represents a ChangeStreamRecord. + * @implements IChangeStreamRecord + * @constructor + * @param {google.spanner.v1.IChangeStreamRecord=} [properties] Properties to set + */ + function ChangeStreamRecord(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ChangeStreamRecord dataChangeRecord. + * @member {google.spanner.v1.ChangeStreamRecord.IDataChangeRecord|null|undefined} dataChangeRecord + * @memberof google.spanner.v1.ChangeStreamRecord + * @instance + */ + ChangeStreamRecord.prototype.dataChangeRecord = null; + + /** + * ChangeStreamRecord heartbeatRecord. + * @member {google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord|null|undefined} heartbeatRecord + * @memberof google.spanner.v1.ChangeStreamRecord + * @instance + */ + ChangeStreamRecord.prototype.heartbeatRecord = null; + + /** + * ChangeStreamRecord partitionStartRecord. + * @member {google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord|null|undefined} partitionStartRecord + * @memberof google.spanner.v1.ChangeStreamRecord + * @instance + */ + ChangeStreamRecord.prototype.partitionStartRecord = null; + + /** + * ChangeStreamRecord partitionEndRecord. + * @member {google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord|null|undefined} partitionEndRecord + * @memberof google.spanner.v1.ChangeStreamRecord + * @instance + */ + ChangeStreamRecord.prototype.partitionEndRecord = null; + + /** + * ChangeStreamRecord partitionEventRecord. + * @member {google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord|null|undefined} partitionEventRecord + * @memberof google.spanner.v1.ChangeStreamRecord + * @instance + */ + ChangeStreamRecord.prototype.partitionEventRecord = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ChangeStreamRecord record. + * @member {"dataChangeRecord"|"heartbeatRecord"|"partitionStartRecord"|"partitionEndRecord"|"partitionEventRecord"|undefined} record + * @memberof google.spanner.v1.ChangeStreamRecord + * @instance + */ + Object.defineProperty(ChangeStreamRecord.prototype, "record", { + get: $util.oneOfGetter($oneOfFields = ["dataChangeRecord", "heartbeatRecord", "partitionStartRecord", "partitionEndRecord", "partitionEventRecord"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ChangeStreamRecord instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {google.spanner.v1.IChangeStreamRecord=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord} ChangeStreamRecord instance + */ + ChangeStreamRecord.create = function create(properties) { + return new ChangeStreamRecord(properties); + }; + + /** + * Encodes the specified ChangeStreamRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {google.spanner.v1.IChangeStreamRecord} message ChangeStreamRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChangeStreamRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataChangeRecord != null && Object.hasOwnProperty.call(message, "dataChangeRecord")) + $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.encode(message.dataChangeRecord, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.heartbeatRecord != null && Object.hasOwnProperty.call(message, "heartbeatRecord")) + $root.google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.encode(message.heartbeatRecord, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.partitionStartRecord != null && Object.hasOwnProperty.call(message, "partitionStartRecord")) + $root.google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.encode(message.partitionStartRecord, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.partitionEndRecord != null && Object.hasOwnProperty.call(message, "partitionEndRecord")) + $root.google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.encode(message.partitionEndRecord, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.partitionEventRecord != null && Object.hasOwnProperty.call(message, "partitionEventRecord")) + $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.encode(message.partitionEventRecord, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ChangeStreamRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {google.spanner.v1.IChangeStreamRecord} message ChangeStreamRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ChangeStreamRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ChangeStreamRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord} ChangeStreamRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChangeStreamRecord.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.spanner.v1.ChangeStreamRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.dataChangeRecord = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.decode(reader, reader.uint32()); + break; + } + case 2: { + message.heartbeatRecord = $root.google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.decode(reader, reader.uint32()); + break; + } + case 3: { + message.partitionStartRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.decode(reader, reader.uint32()); + break; + } + case 4: { + message.partitionEndRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.decode(reader, reader.uint32()); + break; + } + case 5: { + message.partitionEventRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ChangeStreamRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord} ChangeStreamRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ChangeStreamRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ChangeStreamRecord message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ChangeStreamRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.dataChangeRecord != null && message.hasOwnProperty("dataChangeRecord")) { + properties.record = 1; + { + var error = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.verify(message.dataChangeRecord); + if (error) + return "dataChangeRecord." + error; + } + } + if (message.heartbeatRecord != null && message.hasOwnProperty("heartbeatRecord")) { + if (properties.record === 1) + return "record: multiple values"; + properties.record = 1; + { + var error = $root.google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.verify(message.heartbeatRecord); + if (error) + return "heartbeatRecord." + error; + } + } + if (message.partitionStartRecord != null && message.hasOwnProperty("partitionStartRecord")) { + if (properties.record === 1) + return "record: multiple values"; + properties.record = 1; + { + var error = $root.google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.verify(message.partitionStartRecord); + if (error) + return "partitionStartRecord." + error; + } + } + if (message.partitionEndRecord != null && message.hasOwnProperty("partitionEndRecord")) { + if (properties.record === 1) + return "record: multiple values"; + properties.record = 1; + { + var error = $root.google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.verify(message.partitionEndRecord); + if (error) + return "partitionEndRecord." + error; + } + } + if (message.partitionEventRecord != null && message.hasOwnProperty("partitionEventRecord")) { + if (properties.record === 1) + return "record: multiple values"; + properties.record = 1; + { + var error = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.verify(message.partitionEventRecord); + if (error) + return "partitionEventRecord." + error; + } + } + return null; + }; + + /** + * Creates a ChangeStreamRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord} ChangeStreamRecord + */ + ChangeStreamRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord(); + if (object.dataChangeRecord != null) { + if (typeof object.dataChangeRecord !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.dataChangeRecord: object expected"); + message.dataChangeRecord = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.fromObject(object.dataChangeRecord); + } + if (object.heartbeatRecord != null) { + if (typeof object.heartbeatRecord !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.heartbeatRecord: object expected"); + message.heartbeatRecord = $root.google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.fromObject(object.heartbeatRecord); + } + if (object.partitionStartRecord != null) { + if (typeof object.partitionStartRecord !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.partitionStartRecord: object expected"); + message.partitionStartRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.fromObject(object.partitionStartRecord); + } + if (object.partitionEndRecord != null) { + if (typeof object.partitionEndRecord !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.partitionEndRecord: object expected"); + message.partitionEndRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.fromObject(object.partitionEndRecord); + } + if (object.partitionEventRecord != null) { + if (typeof object.partitionEventRecord !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.partitionEventRecord: object expected"); + message.partitionEventRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.fromObject(object.partitionEventRecord); + } + return message; + }; + + /** + * Creates a plain object from a ChangeStreamRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord} message ChangeStreamRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ChangeStreamRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.dataChangeRecord != null && message.hasOwnProperty("dataChangeRecord")) { + object.dataChangeRecord = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.toObject(message.dataChangeRecord, options); + if (options.oneofs) + object.record = "dataChangeRecord"; + } + if (message.heartbeatRecord != null && message.hasOwnProperty("heartbeatRecord")) { + object.heartbeatRecord = $root.google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.toObject(message.heartbeatRecord, options); + if (options.oneofs) + object.record = "heartbeatRecord"; + } + if (message.partitionStartRecord != null && message.hasOwnProperty("partitionStartRecord")) { + object.partitionStartRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.toObject(message.partitionStartRecord, options); + if (options.oneofs) + object.record = "partitionStartRecord"; + } + if (message.partitionEndRecord != null && message.hasOwnProperty("partitionEndRecord")) { + object.partitionEndRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.toObject(message.partitionEndRecord, options); + if (options.oneofs) + object.record = "partitionEndRecord"; + } + if (message.partitionEventRecord != null && message.hasOwnProperty("partitionEventRecord")) { + object.partitionEventRecord = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.toObject(message.partitionEventRecord, options); + if (options.oneofs) + object.record = "partitionEventRecord"; + } + return object; + }; + + /** + * Converts this ChangeStreamRecord to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord + * @instance + * @returns {Object.} JSON object + */ + ChangeStreamRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ChangeStreamRecord + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ChangeStreamRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord"; + }; + + ChangeStreamRecord.DataChangeRecord = (function() { + + /** + * Properties of a DataChangeRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @interface IDataChangeRecord + * @property {google.protobuf.ITimestamp|null} [commitTimestamp] DataChangeRecord commitTimestamp + * @property {string|null} [recordSequence] DataChangeRecord recordSequence + * @property {string|null} [serverTransactionId] DataChangeRecord serverTransactionId + * @property {boolean|null} [isLastRecordInTransactionInPartition] DataChangeRecord isLastRecordInTransactionInPartition + * @property {string|null} [table] DataChangeRecord table + * @property {Array.|null} [columnMetadata] DataChangeRecord columnMetadata + * @property {Array.|null} [mods] DataChangeRecord mods + * @property {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType|null} [modType] DataChangeRecord modType + * @property {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType|null} [valueCaptureType] DataChangeRecord valueCaptureType + * @property {number|null} [numberOfRecordsInTransaction] DataChangeRecord numberOfRecordsInTransaction + * @property {number|null} [numberOfPartitionsInTransaction] DataChangeRecord numberOfPartitionsInTransaction + * @property {string|null} [transactionTag] DataChangeRecord transactionTag + * @property {boolean|null} [isSystemTransaction] DataChangeRecord isSystemTransaction + */ + + /** + * Constructs a new DataChangeRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @classdesc Represents a DataChangeRecord. + * @implements IDataChangeRecord + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.IDataChangeRecord=} [properties] Properties to set + */ + function DataChangeRecord(properties) { + this.columnMetadata = []; + this.mods = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DataChangeRecord commitTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} commitTimestamp + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.commitTimestamp = null; + + /** + * DataChangeRecord recordSequence. + * @member {string} recordSequence + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.recordSequence = ""; + + /** + * DataChangeRecord serverTransactionId. + * @member {string} serverTransactionId + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.serverTransactionId = ""; + + /** + * DataChangeRecord isLastRecordInTransactionInPartition. + * @member {boolean} isLastRecordInTransactionInPartition + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.isLastRecordInTransactionInPartition = false; + + /** + * DataChangeRecord table. + * @member {string} table + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.table = ""; + + /** + * DataChangeRecord columnMetadata. + * @member {Array.} columnMetadata + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.columnMetadata = $util.emptyArray; + + /** + * DataChangeRecord mods. + * @member {Array.} mods + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.mods = $util.emptyArray; + + /** + * DataChangeRecord modType. + * @member {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType} modType + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.modType = 0; + + /** + * DataChangeRecord valueCaptureType. + * @member {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType} valueCaptureType + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.valueCaptureType = 0; + + /** + * DataChangeRecord numberOfRecordsInTransaction. + * @member {number} numberOfRecordsInTransaction + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.numberOfRecordsInTransaction = 0; + + /** + * DataChangeRecord numberOfPartitionsInTransaction. + * @member {number} numberOfPartitionsInTransaction + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.numberOfPartitionsInTransaction = 0; + + /** + * DataChangeRecord transactionTag. + * @member {string} transactionTag + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.transactionTag = ""; + + /** + * DataChangeRecord isSystemTransaction. + * @member {boolean} isSystemTransaction + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + */ + DataChangeRecord.prototype.isSystemTransaction = false; + + /** + * Creates a new DataChangeRecord instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IDataChangeRecord=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord} DataChangeRecord instance + */ + DataChangeRecord.create = function create(properties) { + return new DataChangeRecord(properties); + }; + + /** + * Encodes the specified DataChangeRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IDataChangeRecord} message DataChangeRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DataChangeRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.commitTimestamp != null && Object.hasOwnProperty.call(message, "commitTimestamp")) + $root.google.protobuf.Timestamp.encode(message.commitTimestamp, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.recordSequence != null && Object.hasOwnProperty.call(message, "recordSequence")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.recordSequence); + if (message.serverTransactionId != null && Object.hasOwnProperty.call(message, "serverTransactionId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.serverTransactionId); + if (message.isLastRecordInTransactionInPartition != null && Object.hasOwnProperty.call(message, "isLastRecordInTransactionInPartition")) + writer.uint32(/* id 4, wireType 0 =*/32).bool(message.isLastRecordInTransactionInPartition); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.table); + if (message.columnMetadata != null && message.columnMetadata.length) + for (var i = 0; i < message.columnMetadata.length; ++i) + $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.encode(message.columnMetadata[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.mods != null && message.mods.length) + for (var i = 0; i < message.mods.length; ++i) + $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.encode(message.mods[i], writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.modType != null && Object.hasOwnProperty.call(message, "modType")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.modType); + if (message.valueCaptureType != null && Object.hasOwnProperty.call(message, "valueCaptureType")) + writer.uint32(/* id 9, wireType 0 =*/72).int32(message.valueCaptureType); + if (message.numberOfRecordsInTransaction != null && Object.hasOwnProperty.call(message, "numberOfRecordsInTransaction")) + writer.uint32(/* id 10, wireType 0 =*/80).int32(message.numberOfRecordsInTransaction); + if (message.numberOfPartitionsInTransaction != null && Object.hasOwnProperty.call(message, "numberOfPartitionsInTransaction")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.numberOfPartitionsInTransaction); + if (message.transactionTag != null && Object.hasOwnProperty.call(message, "transactionTag")) + writer.uint32(/* id 12, wireType 2 =*/98).string(message.transactionTag); + if (message.isSystemTransaction != null && Object.hasOwnProperty.call(message, "isSystemTransaction")) + writer.uint32(/* id 13, wireType 0 =*/104).bool(message.isSystemTransaction); + return writer; + }; + + /** + * Encodes the specified DataChangeRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IDataChangeRecord} message DataChangeRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DataChangeRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DataChangeRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord} DataChangeRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DataChangeRecord.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.spanner.v1.ChangeStreamRecord.DataChangeRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.commitTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.recordSequence = reader.string(); + break; + } + case 3: { + message.serverTransactionId = reader.string(); + break; + } + case 4: { + message.isLastRecordInTransactionInPartition = reader.bool(); + break; + } + case 5: { + message.table = reader.string(); + break; + } + case 6: { + if (!(message.columnMetadata && message.columnMetadata.length)) + message.columnMetadata = []; + message.columnMetadata.push($root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.decode(reader, reader.uint32())); + break; + } + case 7: { + if (!(message.mods && message.mods.length)) + message.mods = []; + message.mods.push($root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.decode(reader, reader.uint32())); + break; + } + case 8: { + message.modType = reader.int32(); + break; + } + case 9: { + message.valueCaptureType = reader.int32(); + break; + } + case 10: { + message.numberOfRecordsInTransaction = reader.int32(); + break; + } + case 11: { + message.numberOfPartitionsInTransaction = reader.int32(); + break; + } + case 12: { + message.transactionTag = reader.string(); + break; + } + case 13: { + message.isSystemTransaction = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DataChangeRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord} DataChangeRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DataChangeRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DataChangeRecord message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DataChangeRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.commitTimestamp != null && message.hasOwnProperty("commitTimestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.commitTimestamp); + if (error) + return "commitTimestamp." + error; + } + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + if (!$util.isString(message.recordSequence)) + return "recordSequence: string expected"; + if (message.serverTransactionId != null && message.hasOwnProperty("serverTransactionId")) + if (!$util.isString(message.serverTransactionId)) + return "serverTransactionId: string expected"; + if (message.isLastRecordInTransactionInPartition != null && message.hasOwnProperty("isLastRecordInTransactionInPartition")) + if (typeof message.isLastRecordInTransactionInPartition !== "boolean") + return "isLastRecordInTransactionInPartition: boolean expected"; + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.columnMetadata != null && message.hasOwnProperty("columnMetadata")) { + if (!Array.isArray(message.columnMetadata)) + return "columnMetadata: array expected"; + for (var i = 0; i < message.columnMetadata.length; ++i) { + var error = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.verify(message.columnMetadata[i]); + if (error) + return "columnMetadata." + error; + } + } + if (message.mods != null && message.hasOwnProperty("mods")) { + if (!Array.isArray(message.mods)) + return "mods: array expected"; + for (var i = 0; i < message.mods.length; ++i) { + var error = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.verify(message.mods[i]); + if (error) + return "mods." + error; + } + } + if (message.modType != null && message.hasOwnProperty("modType")) + switch (message.modType) { + default: + return "modType: enum value expected"; + case 0: + case 10: + case 20: + case 30: + break; + } + if (message.valueCaptureType != null && message.hasOwnProperty("valueCaptureType")) + switch (message.valueCaptureType) { + default: + return "valueCaptureType: enum value expected"; + case 0: + case 10: + case 20: + case 30: + case 40: + break; + } + if (message.numberOfRecordsInTransaction != null && message.hasOwnProperty("numberOfRecordsInTransaction")) + if (!$util.isInteger(message.numberOfRecordsInTransaction)) + return "numberOfRecordsInTransaction: integer expected"; + if (message.numberOfPartitionsInTransaction != null && message.hasOwnProperty("numberOfPartitionsInTransaction")) + if (!$util.isInteger(message.numberOfPartitionsInTransaction)) + return "numberOfPartitionsInTransaction: integer expected"; + if (message.transactionTag != null && message.hasOwnProperty("transactionTag")) + if (!$util.isString(message.transactionTag)) + return "transactionTag: string expected"; + if (message.isSystemTransaction != null && message.hasOwnProperty("isSystemTransaction")) + if (typeof message.isSystemTransaction !== "boolean") + return "isSystemTransaction: boolean expected"; + return null; + }; + + /** + * Creates a DataChangeRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord} DataChangeRecord + */ + DataChangeRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord(); + if (object.commitTimestamp != null) { + if (typeof object.commitTimestamp !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.commitTimestamp: object expected"); + message.commitTimestamp = $root.google.protobuf.Timestamp.fromObject(object.commitTimestamp); + } + if (object.recordSequence != null) + message.recordSequence = String(object.recordSequence); + if (object.serverTransactionId != null) + message.serverTransactionId = String(object.serverTransactionId); + if (object.isLastRecordInTransactionInPartition != null) + message.isLastRecordInTransactionInPartition = Boolean(object.isLastRecordInTransactionInPartition); + if (object.table != null) + message.table = String(object.table); + if (object.columnMetadata) { + if (!Array.isArray(object.columnMetadata)) + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.columnMetadata: array expected"); + message.columnMetadata = []; + for (var i = 0; i < object.columnMetadata.length; ++i) { + if (typeof object.columnMetadata[i] !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.columnMetadata: object expected"); + message.columnMetadata[i] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.fromObject(object.columnMetadata[i]); + } + } + if (object.mods) { + if (!Array.isArray(object.mods)) + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.mods: array expected"); + message.mods = []; + for (var i = 0; i < object.mods.length; ++i) { + if (typeof object.mods[i] !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.mods: object expected"); + message.mods[i] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.fromObject(object.mods[i]); + } + } + switch (object.modType) { + default: + if (typeof object.modType === "number") { + message.modType = object.modType; + break; + } + break; + case "MOD_TYPE_UNSPECIFIED": + case 0: + message.modType = 0; + break; + case "INSERT": + case 10: + message.modType = 10; + break; + case "UPDATE": + case 20: + message.modType = 20; + break; + case "DELETE": + case 30: + message.modType = 30; + break; + } + switch (object.valueCaptureType) { + default: + if (typeof object.valueCaptureType === "number") { + message.valueCaptureType = object.valueCaptureType; + break; + } + break; + case "VALUE_CAPTURE_TYPE_UNSPECIFIED": + case 0: + message.valueCaptureType = 0; + break; + case "OLD_AND_NEW_VALUES": + case 10: + message.valueCaptureType = 10; + break; + case "NEW_VALUES": + case 20: + message.valueCaptureType = 20; + break; + case "NEW_ROW": + case 30: + message.valueCaptureType = 30; + break; + case "NEW_ROW_AND_OLD_VALUES": + case 40: + message.valueCaptureType = 40; + break; + } + if (object.numberOfRecordsInTransaction != null) + message.numberOfRecordsInTransaction = object.numberOfRecordsInTransaction | 0; + if (object.numberOfPartitionsInTransaction != null) + message.numberOfPartitionsInTransaction = object.numberOfPartitionsInTransaction | 0; + if (object.transactionTag != null) + message.transactionTag = String(object.transactionTag); + if (object.isSystemTransaction != null) + message.isSystemTransaction = Boolean(object.isSystemTransaction); + return message; + }; + + /** + * Creates a plain object from a DataChangeRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord} message DataChangeRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DataChangeRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.columnMetadata = []; + object.mods = []; + } + if (options.defaults) { + object.commitTimestamp = null; + object.recordSequence = ""; + object.serverTransactionId = ""; + object.isLastRecordInTransactionInPartition = false; + object.table = ""; + object.modType = options.enums === String ? "MOD_TYPE_UNSPECIFIED" : 0; + object.valueCaptureType = options.enums === String ? "VALUE_CAPTURE_TYPE_UNSPECIFIED" : 0; + object.numberOfRecordsInTransaction = 0; + object.numberOfPartitionsInTransaction = 0; + object.transactionTag = ""; + object.isSystemTransaction = false; + } + if (message.commitTimestamp != null && message.hasOwnProperty("commitTimestamp")) + object.commitTimestamp = $root.google.protobuf.Timestamp.toObject(message.commitTimestamp, options); + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + object.recordSequence = message.recordSequence; + if (message.serverTransactionId != null && message.hasOwnProperty("serverTransactionId")) + object.serverTransactionId = message.serverTransactionId; + if (message.isLastRecordInTransactionInPartition != null && message.hasOwnProperty("isLastRecordInTransactionInPartition")) + object.isLastRecordInTransactionInPartition = message.isLastRecordInTransactionInPartition; + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.columnMetadata && message.columnMetadata.length) { + object.columnMetadata = []; + for (var j = 0; j < message.columnMetadata.length; ++j) + object.columnMetadata[j] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.toObject(message.columnMetadata[j], options); + } + if (message.mods && message.mods.length) { + object.mods = []; + for (var j = 0; j < message.mods.length; ++j) + object.mods[j] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.toObject(message.mods[j], options); + } + if (message.modType != null && message.hasOwnProperty("modType")) + object.modType = options.enums === String ? $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType[message.modType] === undefined ? message.modType : $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType[message.modType] : message.modType; + if (message.valueCaptureType != null && message.hasOwnProperty("valueCaptureType")) + object.valueCaptureType = options.enums === String ? $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType[message.valueCaptureType] === undefined ? message.valueCaptureType : $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType[message.valueCaptureType] : message.valueCaptureType; + if (message.numberOfRecordsInTransaction != null && message.hasOwnProperty("numberOfRecordsInTransaction")) + object.numberOfRecordsInTransaction = message.numberOfRecordsInTransaction; + if (message.numberOfPartitionsInTransaction != null && message.hasOwnProperty("numberOfPartitionsInTransaction")) + object.numberOfPartitionsInTransaction = message.numberOfPartitionsInTransaction; + if (message.transactionTag != null && message.hasOwnProperty("transactionTag")) + object.transactionTag = message.transactionTag; + if (message.isSystemTransaction != null && message.hasOwnProperty("isSystemTransaction")) + object.isSystemTransaction = message.isSystemTransaction; + return object; + }; + + /** + * Converts this DataChangeRecord to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @instance + * @returns {Object.} JSON object + */ + DataChangeRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DataChangeRecord + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DataChangeRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.DataChangeRecord"; + }; + + DataChangeRecord.ColumnMetadata = (function() { + + /** + * Properties of a ColumnMetadata. + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @interface IColumnMetadata + * @property {string|null} [name] ColumnMetadata name + * @property {google.spanner.v1.IType|null} [type] ColumnMetadata type + * @property {boolean|null} [isPrimaryKey] ColumnMetadata isPrimaryKey + * @property {number|Long|null} [ordinalPosition] ColumnMetadata ordinalPosition + */ + + /** + * Constructs a new ColumnMetadata. + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @classdesc Represents a ColumnMetadata. + * @implements IColumnMetadata + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata=} [properties] Properties to set + */ + function ColumnMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ColumnMetadata name. + * @member {string} name + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @instance + */ + ColumnMetadata.prototype.name = ""; + + /** + * ColumnMetadata type. + * @member {google.spanner.v1.IType|null|undefined} type + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @instance + */ + ColumnMetadata.prototype.type = null; + + /** + * ColumnMetadata isPrimaryKey. + * @member {boolean} isPrimaryKey + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @instance + */ + ColumnMetadata.prototype.isPrimaryKey = false; + + /** + * ColumnMetadata ordinalPosition. + * @member {number|Long} ordinalPosition + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @instance + */ + ColumnMetadata.prototype.ordinalPosition = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new ColumnMetadata instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata} ColumnMetadata instance + */ + ColumnMetadata.create = function create(properties) { + return new ColumnMetadata(properties); + }; + + /** + * Encodes the specified ColumnMetadata message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata} message ColumnMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ColumnMetadata.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + $root.google.spanner.v1.Type.encode(message.type, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.isPrimaryKey != null && Object.hasOwnProperty.call(message, "isPrimaryKey")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.isPrimaryKey); + if (message.ordinalPosition != null && Object.hasOwnProperty.call(message, "ordinalPosition")) + writer.uint32(/* id 4, wireType 0 =*/32).int64(message.ordinalPosition); + return writer; + }; + + /** + * Encodes the specified ColumnMetadata message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IColumnMetadata} message ColumnMetadata message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ColumnMetadata.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ColumnMetadata message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata} ColumnMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ColumnMetadata.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.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.type = $root.google.spanner.v1.Type.decode(reader, reader.uint32()); + break; + } + case 3: { + message.isPrimaryKey = reader.bool(); + break; + } + case 4: { + message.ordinalPosition = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ColumnMetadata message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata} ColumnMetadata + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ColumnMetadata.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ColumnMetadata message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ColumnMetadata.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.type != null && message.hasOwnProperty("type")) { + var error = $root.google.spanner.v1.Type.verify(message.type); + if (error) + return "type." + error; + } + if (message.isPrimaryKey != null && message.hasOwnProperty("isPrimaryKey")) + if (typeof message.isPrimaryKey !== "boolean") + return "isPrimaryKey: boolean expected"; + if (message.ordinalPosition != null && message.hasOwnProperty("ordinalPosition")) + if (!$util.isInteger(message.ordinalPosition) && !(message.ordinalPosition && $util.isInteger(message.ordinalPosition.low) && $util.isInteger(message.ordinalPosition.high))) + return "ordinalPosition: integer|Long expected"; + return null; + }; + + /** + * Creates a ColumnMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata} ColumnMetadata + */ + ColumnMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata(); + if (object.name != null) + message.name = String(object.name); + if (object.type != null) { + if (typeof object.type !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata.type: object expected"); + message.type = $root.google.spanner.v1.Type.fromObject(object.type); + } + if (object.isPrimaryKey != null) + message.isPrimaryKey = Boolean(object.isPrimaryKey); + if (object.ordinalPosition != null) + if ($util.Long) + (message.ordinalPosition = $util.Long.fromValue(object.ordinalPosition)).unsigned = false; + else if (typeof object.ordinalPosition === "string") + message.ordinalPosition = parseInt(object.ordinalPosition, 10); + else if (typeof object.ordinalPosition === "number") + message.ordinalPosition = object.ordinalPosition; + else if (typeof object.ordinalPosition === "object") + message.ordinalPosition = new $util.LongBits(object.ordinalPosition.low >>> 0, object.ordinalPosition.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a ColumnMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata} message ColumnMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ColumnMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.type = null; + object.isPrimaryKey = false; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.ordinalPosition = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.ordinalPosition = options.longs === String ? "0" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.type != null && message.hasOwnProperty("type")) + object.type = $root.google.spanner.v1.Type.toObject(message.type, options); + if (message.isPrimaryKey != null && message.hasOwnProperty("isPrimaryKey")) + object.isPrimaryKey = message.isPrimaryKey; + if (message.ordinalPosition != null && message.hasOwnProperty("ordinalPosition")) + if (typeof message.ordinalPosition === "number") + object.ordinalPosition = options.longs === String ? String(message.ordinalPosition) : message.ordinalPosition; + else + object.ordinalPosition = options.longs === String ? $util.Long.prototype.toString.call(message.ordinalPosition) : options.longs === Number ? new $util.LongBits(message.ordinalPosition.low >>> 0, message.ordinalPosition.high >>> 0).toNumber() : message.ordinalPosition; + return object; + }; + + /** + * Converts this ColumnMetadata to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @instance + * @returns {Object.} JSON object + */ + ColumnMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ColumnMetadata + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ColumnMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ColumnMetadata"; + }; + + return ColumnMetadata; + })(); + + DataChangeRecord.ModValue = (function() { + + /** + * Properties of a ModValue. + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @interface IModValue + * @property {number|null} [columnMetadataIndex] ModValue columnMetadataIndex + * @property {google.protobuf.IValue|null} [value] ModValue value + */ + + /** + * Constructs a new ModValue. + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @classdesc Represents a ModValue. + * @implements IModValue + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue=} [properties] Properties to set + */ + function ModValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ModValue columnMetadataIndex. + * @member {number} columnMetadataIndex + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @instance + */ + ModValue.prototype.columnMetadataIndex = 0; + + /** + * ModValue value. + * @member {google.protobuf.IValue|null|undefined} value + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @instance + */ + ModValue.prototype.value = null; + + /** + * Creates a new ModValue instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue} ModValue instance + */ + ModValue.create = function create(properties) { + return new ModValue(properties); + }; + + /** + * Encodes the specified ModValue message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue} message ModValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ModValue.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.columnMetadataIndex != null && Object.hasOwnProperty.call(message, "columnMetadataIndex")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.columnMetadataIndex); + if (message.value != null && Object.hasOwnProperty.call(message, "value")) + $root.google.protobuf.Value.encode(message.value, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ModValue message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IModValue} message ModValue message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ModValue.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ModValue message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue} ModValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ModValue.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.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.columnMetadataIndex = reader.int32(); + break; + } + case 2: { + message.value = $root.google.protobuf.Value.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ModValue message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue} ModValue + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ModValue.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ModValue message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ModValue.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.columnMetadataIndex != null && message.hasOwnProperty("columnMetadataIndex")) + if (!$util.isInteger(message.columnMetadataIndex)) + return "columnMetadataIndex: integer expected"; + if (message.value != null && message.hasOwnProperty("value")) { + var error = $root.google.protobuf.Value.verify(message.value); + if (error) + return "value." + error; + } + return null; + }; + + /** + * Creates a ModValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue} ModValue + */ + ModValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue(); + if (object.columnMetadataIndex != null) + message.columnMetadataIndex = object.columnMetadataIndex | 0; + if (object.value != null) { + if (typeof object.value !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.value: object expected"); + message.value = $root.google.protobuf.Value.fromObject(object.value); + } + return message; + }; + + /** + * Creates a plain object from a ModValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue} message ModValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ModValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.columnMetadataIndex = 0; + object.value = null; + } + if (message.columnMetadataIndex != null && message.hasOwnProperty("columnMetadataIndex")) + object.columnMetadataIndex = message.columnMetadataIndex; + if (message.value != null && message.hasOwnProperty("value")) + object.value = $root.google.protobuf.Value.toObject(message.value, options); + return object; + }; + + /** + * Converts this ModValue to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @instance + * @returns {Object.} JSON object + */ + ModValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ModValue + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ModValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue"; + }; + + return ModValue; + })(); + + DataChangeRecord.Mod = (function() { + + /** + * Properties of a Mod. + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @interface IMod + * @property {Array.|null} [keys] Mod keys + * @property {Array.|null} [oldValues] Mod oldValues + * @property {Array.|null} [newValues] Mod newValues + */ + + /** + * Constructs a new Mod. + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord + * @classdesc Represents a Mod. + * @implements IMod + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod=} [properties] Properties to set + */ + function Mod(properties) { + this.keys = []; + this.oldValues = []; + this.newValues = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Mod keys. + * @member {Array.} keys + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @instance + */ + Mod.prototype.keys = $util.emptyArray; + + /** + * Mod oldValues. + * @member {Array.} oldValues + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @instance + */ + Mod.prototype.oldValues = $util.emptyArray; + + /** + * Mod newValues. + * @member {Array.} newValues + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @instance + */ + Mod.prototype.newValues = $util.emptyArray; + + /** + * Creates a new Mod instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod} Mod instance + */ + Mod.create = function create(properties) { + return new Mod(properties); + }; + + /** + * Encodes the specified Mod message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod} message Mod message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Mod.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.keys != null && message.keys.length) + for (var i = 0; i < message.keys.length; ++i) + $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.encode(message.keys[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.oldValues != null && message.oldValues.length) + for (var i = 0; i < message.oldValues.length; ++i) + $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.encode(message.oldValues[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.newValues != null && message.newValues.length) + for (var i = 0; i < message.newValues.length; ++i) + $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.encode(message.newValues[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Mod message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.IMod} message Mod message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Mod.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Mod message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod} Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Mod.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.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.keys && message.keys.length)) + message.keys = []; + message.keys.push($root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.decode(reader, reader.uint32())); + break; + } + case 2: { + if (!(message.oldValues && message.oldValues.length)) + message.oldValues = []; + message.oldValues.push($root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.decode(reader, reader.uint32())); + break; + } + case 3: { + if (!(message.newValues && message.newValues.length)) + message.newValues = []; + message.newValues.push($root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Mod message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod} Mod + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Mod.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Mod message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Mod.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.keys != null && message.hasOwnProperty("keys")) { + if (!Array.isArray(message.keys)) + return "keys: array expected"; + for (var i = 0; i < message.keys.length; ++i) { + var error = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.verify(message.keys[i]); + if (error) + return "keys." + error; + } + } + if (message.oldValues != null && message.hasOwnProperty("oldValues")) { + if (!Array.isArray(message.oldValues)) + return "oldValues: array expected"; + for (var i = 0; i < message.oldValues.length; ++i) { + var error = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.verify(message.oldValues[i]); + if (error) + return "oldValues." + error; + } + } + if (message.newValues != null && message.hasOwnProperty("newValues")) { + if (!Array.isArray(message.newValues)) + return "newValues: array expected"; + for (var i = 0; i < message.newValues.length; ++i) { + var error = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.verify(message.newValues[i]); + if (error) + return "newValues." + error; + } + } + return null; + }; + + /** + * Creates a Mod message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod} Mod + */ + Mod.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod(); + if (object.keys) { + if (!Array.isArray(object.keys)) + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.keys: array expected"); + message.keys = []; + for (var i = 0; i < object.keys.length; ++i) { + if (typeof object.keys[i] !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.keys: object expected"); + message.keys[i] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.fromObject(object.keys[i]); + } + } + if (object.oldValues) { + if (!Array.isArray(object.oldValues)) + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.oldValues: array expected"); + message.oldValues = []; + for (var i = 0; i < object.oldValues.length; ++i) { + if (typeof object.oldValues[i] !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.oldValues: object expected"); + message.oldValues[i] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.fromObject(object.oldValues[i]); + } + } + if (object.newValues) { + if (!Array.isArray(object.newValues)) + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.newValues: array expected"); + message.newValues = []; + for (var i = 0; i < object.newValues.length; ++i) { + if (typeof object.newValues[i] !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod.newValues: object expected"); + message.newValues[i] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.fromObject(object.newValues[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Mod message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod} message Mod + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Mod.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.keys = []; + object.oldValues = []; + object.newValues = []; + } + if (message.keys && message.keys.length) { + object.keys = []; + for (var j = 0; j < message.keys.length; ++j) + object.keys[j] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.toObject(message.keys[j], options); + } + if (message.oldValues && message.oldValues.length) { + object.oldValues = []; + for (var j = 0; j < message.oldValues.length; ++j) + object.oldValues[j] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.toObject(message.oldValues[j], options); + } + if (message.newValues && message.newValues.length) { + object.newValues = []; + for (var j = 0; j < message.newValues.length; ++j) + object.newValues[j] = $root.google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModValue.toObject(message.newValues[j], options); + } + return object; + }; + + /** + * Converts this Mod to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @instance + * @returns {Object.} JSON object + */ + Mod.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Mod + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Mod.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.DataChangeRecord.Mod"; + }; + + return Mod; + })(); + + /** + * ModType enum. + * @name google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ModType + * @enum {number} + * @property {number} MOD_TYPE_UNSPECIFIED=0 MOD_TYPE_UNSPECIFIED value + * @property {number} INSERT=10 INSERT value + * @property {number} UPDATE=20 UPDATE value + * @property {number} DELETE=30 DELETE value + */ + DataChangeRecord.ModType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MOD_TYPE_UNSPECIFIED"] = 0; + values[valuesById[10] = "INSERT"] = 10; + values[valuesById[20] = "UPDATE"] = 20; + values[valuesById[30] = "DELETE"] = 30; + return values; + })(); + + /** + * ValueCaptureType enum. + * @name google.spanner.v1.ChangeStreamRecord.DataChangeRecord.ValueCaptureType + * @enum {number} + * @property {number} VALUE_CAPTURE_TYPE_UNSPECIFIED=0 VALUE_CAPTURE_TYPE_UNSPECIFIED value + * @property {number} OLD_AND_NEW_VALUES=10 OLD_AND_NEW_VALUES value + * @property {number} NEW_VALUES=20 NEW_VALUES value + * @property {number} NEW_ROW=30 NEW_ROW value + * @property {number} NEW_ROW_AND_OLD_VALUES=40 NEW_ROW_AND_OLD_VALUES value + */ + DataChangeRecord.ValueCaptureType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VALUE_CAPTURE_TYPE_UNSPECIFIED"] = 0; + values[valuesById[10] = "OLD_AND_NEW_VALUES"] = 10; + values[valuesById[20] = "NEW_VALUES"] = 20; + values[valuesById[30] = "NEW_ROW"] = 30; + values[valuesById[40] = "NEW_ROW_AND_OLD_VALUES"] = 40; + return values; + })(); + + return DataChangeRecord; + })(); + + ChangeStreamRecord.HeartbeatRecord = (function() { + + /** + * Properties of a HeartbeatRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @interface IHeartbeatRecord + * @property {google.protobuf.ITimestamp|null} [timestamp] HeartbeatRecord timestamp + */ + + /** + * Constructs a new HeartbeatRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @classdesc Represents a HeartbeatRecord. + * @implements IHeartbeatRecord + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord=} [properties] Properties to set + */ + function HeartbeatRecord(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * HeartbeatRecord timestamp. + * @member {google.protobuf.ITimestamp|null|undefined} timestamp + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @instance + */ + HeartbeatRecord.prototype.timestamp = null; + + /** + * Creates a new HeartbeatRecord instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.HeartbeatRecord} HeartbeatRecord instance + */ + HeartbeatRecord.create = function create(properties) { + return new HeartbeatRecord(properties); + }; + + /** + * Encodes the specified HeartbeatRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord} message HeartbeatRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + HeartbeatRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.timestamp != null && Object.hasOwnProperty.call(message, "timestamp")) + $root.google.protobuf.Timestamp.encode(message.timestamp, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified HeartbeatRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IHeartbeatRecord} message HeartbeatRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + HeartbeatRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a HeartbeatRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.HeartbeatRecord} HeartbeatRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + HeartbeatRecord.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.spanner.v1.ChangeStreamRecord.HeartbeatRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.timestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a HeartbeatRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.HeartbeatRecord} HeartbeatRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + HeartbeatRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a HeartbeatRecord message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + HeartbeatRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.timestamp != null && message.hasOwnProperty("timestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.timestamp); + if (error) + return "timestamp." + error; + } + return null; + }; + + /** + * Creates a HeartbeatRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.HeartbeatRecord} HeartbeatRecord + */ + HeartbeatRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.HeartbeatRecord) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.HeartbeatRecord(); + if (object.timestamp != null) { + if (typeof object.timestamp !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.HeartbeatRecord.timestamp: object expected"); + message.timestamp = $root.google.protobuf.Timestamp.fromObject(object.timestamp); + } + return message; + }; + + /** + * Creates a plain object from a HeartbeatRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.HeartbeatRecord} message HeartbeatRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + HeartbeatRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.timestamp = null; + if (message.timestamp != null && message.hasOwnProperty("timestamp")) + object.timestamp = $root.google.protobuf.Timestamp.toObject(message.timestamp, options); + return object; + }; + + /** + * Converts this HeartbeatRecord to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @instance + * @returns {Object.} JSON object + */ + HeartbeatRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for HeartbeatRecord + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.HeartbeatRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + HeartbeatRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.HeartbeatRecord"; + }; + + return HeartbeatRecord; + })(); + + ChangeStreamRecord.PartitionStartRecord = (function() { + + /** + * Properties of a PartitionStartRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @interface IPartitionStartRecord + * @property {google.protobuf.ITimestamp|null} [startTimestamp] PartitionStartRecord startTimestamp + * @property {string|null} [recordSequence] PartitionStartRecord recordSequence + * @property {Array.|null} [partitionTokens] PartitionStartRecord partitionTokens + */ + + /** + * Constructs a new PartitionStartRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @classdesc Represents a PartitionStartRecord. + * @implements IPartitionStartRecord + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord=} [properties] Properties to set + */ + function PartitionStartRecord(properties) { + this.partitionTokens = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionStartRecord startTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} startTimestamp + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @instance + */ + PartitionStartRecord.prototype.startTimestamp = null; + + /** + * PartitionStartRecord recordSequence. + * @member {string} recordSequence + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @instance + */ + PartitionStartRecord.prototype.recordSequence = ""; + + /** + * PartitionStartRecord partitionTokens. + * @member {Array.} partitionTokens + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @instance + */ + PartitionStartRecord.prototype.partitionTokens = $util.emptyArray; + + /** + * Creates a new PartitionStartRecord instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionStartRecord} PartitionStartRecord instance + */ + PartitionStartRecord.create = function create(properties) { + return new PartitionStartRecord(properties); + }; + + /** + * Encodes the specified PartitionStartRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord} message PartitionStartRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionStartRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.startTimestamp != null && Object.hasOwnProperty.call(message, "startTimestamp")) + $root.google.protobuf.Timestamp.encode(message.startTimestamp, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.recordSequence != null && Object.hasOwnProperty.call(message, "recordSequence")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.recordSequence); + if (message.partitionTokens != null && message.partitionTokens.length) + for (var i = 0; i < message.partitionTokens.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.partitionTokens[i]); + return writer; + }; + + /** + * Encodes the specified PartitionStartRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionStartRecord} message PartitionStartRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionStartRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionStartRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionStartRecord} PartitionStartRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionStartRecord.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.spanner.v1.ChangeStreamRecord.PartitionStartRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.startTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.recordSequence = reader.string(); + break; + } + case 3: { + if (!(message.partitionTokens && message.partitionTokens.length)) + message.partitionTokens = []; + message.partitionTokens.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionStartRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionStartRecord} PartitionStartRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionStartRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionStartRecord message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionStartRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.startTimestamp != null && message.hasOwnProperty("startTimestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTimestamp); + if (error) + return "startTimestamp." + error; + } + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + if (!$util.isString(message.recordSequence)) + return "recordSequence: string expected"; + if (message.partitionTokens != null && message.hasOwnProperty("partitionTokens")) { + if (!Array.isArray(message.partitionTokens)) + return "partitionTokens: array expected"; + for (var i = 0; i < message.partitionTokens.length; ++i) + if (!$util.isString(message.partitionTokens[i])) + return "partitionTokens: string[] expected"; + } + return null; + }; + + /** + * Creates a PartitionStartRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionStartRecord} PartitionStartRecord + */ + PartitionStartRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.PartitionStartRecord) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.PartitionStartRecord(); + if (object.startTimestamp != null) { + if (typeof object.startTimestamp !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.startTimestamp: object expected"); + message.startTimestamp = $root.google.protobuf.Timestamp.fromObject(object.startTimestamp); + } + if (object.recordSequence != null) + message.recordSequence = String(object.recordSequence); + if (object.partitionTokens) { + if (!Array.isArray(object.partitionTokens)) + throw TypeError(".google.spanner.v1.ChangeStreamRecord.PartitionStartRecord.partitionTokens: array expected"); + message.partitionTokens = []; + for (var i = 0; i < object.partitionTokens.length; ++i) + message.partitionTokens[i] = String(object.partitionTokens[i]); + } + return message; + }; + + /** + * Creates a plain object from a PartitionStartRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionStartRecord} message PartitionStartRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionStartRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.partitionTokens = []; + if (options.defaults) { + object.startTimestamp = null; + object.recordSequence = ""; + } + if (message.startTimestamp != null && message.hasOwnProperty("startTimestamp")) + object.startTimestamp = $root.google.protobuf.Timestamp.toObject(message.startTimestamp, options); + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + object.recordSequence = message.recordSequence; + if (message.partitionTokens && message.partitionTokens.length) { + object.partitionTokens = []; + for (var j = 0; j < message.partitionTokens.length; ++j) + object.partitionTokens[j] = message.partitionTokens[j]; + } + return object; + }; + + /** + * Converts this PartitionStartRecord to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @instance + * @returns {Object.} JSON object + */ + PartitionStartRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionStartRecord + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionStartRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionStartRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.PartitionStartRecord"; + }; + + return PartitionStartRecord; + })(); + + ChangeStreamRecord.PartitionEndRecord = (function() { + + /** + * Properties of a PartitionEndRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @interface IPartitionEndRecord + * @property {google.protobuf.ITimestamp|null} [endTimestamp] PartitionEndRecord endTimestamp + * @property {string|null} [recordSequence] PartitionEndRecord recordSequence + * @property {string|null} [partitionToken] PartitionEndRecord partitionToken + */ + + /** + * Constructs a new PartitionEndRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @classdesc Represents a PartitionEndRecord. + * @implements IPartitionEndRecord + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord=} [properties] Properties to set + */ + function PartitionEndRecord(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionEndRecord endTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} endTimestamp + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @instance + */ + PartitionEndRecord.prototype.endTimestamp = null; + + /** + * PartitionEndRecord recordSequence. + * @member {string} recordSequence + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @instance + */ + PartitionEndRecord.prototype.recordSequence = ""; + + /** + * PartitionEndRecord partitionToken. + * @member {string} partitionToken + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @instance + */ + PartitionEndRecord.prototype.partitionToken = ""; + + /** + * Creates a new PartitionEndRecord instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEndRecord} PartitionEndRecord instance + */ + PartitionEndRecord.create = function create(properties) { + return new PartitionEndRecord(properties); + }; + + /** + * Encodes the specified PartitionEndRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord} message PartitionEndRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionEndRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.endTimestamp != null && Object.hasOwnProperty.call(message, "endTimestamp")) + $root.google.protobuf.Timestamp.encode(message.endTimestamp, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.recordSequence != null && Object.hasOwnProperty.call(message, "recordSequence")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.recordSequence); + if (message.partitionToken != null && Object.hasOwnProperty.call(message, "partitionToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.partitionToken); + return writer; + }; + + /** + * Encodes the specified PartitionEndRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionEndRecord} message PartitionEndRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionEndRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionEndRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEndRecord} PartitionEndRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionEndRecord.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.spanner.v1.ChangeStreamRecord.PartitionEndRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.endTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.recordSequence = reader.string(); + break; + } + case 3: { + message.partitionToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionEndRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEndRecord} PartitionEndRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionEndRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionEndRecord message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionEndRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.endTimestamp != null && message.hasOwnProperty("endTimestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.endTimestamp); + if (error) + return "endTimestamp." + error; + } + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + if (!$util.isString(message.recordSequence)) + return "recordSequence: string expected"; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + if (!$util.isString(message.partitionToken)) + return "partitionToken: string expected"; + return null; + }; + + /** + * Creates a PartitionEndRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEndRecord} PartitionEndRecord + */ + PartitionEndRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.PartitionEndRecord) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.PartitionEndRecord(); + if (object.endTimestamp != null) { + if (typeof object.endTimestamp !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.PartitionEndRecord.endTimestamp: object expected"); + message.endTimestamp = $root.google.protobuf.Timestamp.fromObject(object.endTimestamp); + } + if (object.recordSequence != null) + message.recordSequence = String(object.recordSequence); + if (object.partitionToken != null) + message.partitionToken = String(object.partitionToken); + return message; + }; + + /** + * Creates a plain object from a PartitionEndRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEndRecord} message PartitionEndRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionEndRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.endTimestamp = null; + object.recordSequence = ""; + object.partitionToken = ""; + } + if (message.endTimestamp != null && message.hasOwnProperty("endTimestamp")) + object.endTimestamp = $root.google.protobuf.Timestamp.toObject(message.endTimestamp, options); + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + object.recordSequence = message.recordSequence; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + object.partitionToken = message.partitionToken; + return object; + }; + + /** + * Converts this PartitionEndRecord to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @instance + * @returns {Object.} JSON object + */ + PartitionEndRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionEndRecord + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEndRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionEndRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.PartitionEndRecord"; + }; + + return PartitionEndRecord; + })(); + + ChangeStreamRecord.PartitionEventRecord = (function() { + + /** + * Properties of a PartitionEventRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @interface IPartitionEventRecord + * @property {google.protobuf.ITimestamp|null} [commitTimestamp] PartitionEventRecord commitTimestamp + * @property {string|null} [recordSequence] PartitionEventRecord recordSequence + * @property {string|null} [partitionToken] PartitionEventRecord partitionToken + * @property {Array.|null} [moveInEvents] PartitionEventRecord moveInEvents + * @property {Array.|null} [moveOutEvents] PartitionEventRecord moveOutEvents + */ + + /** + * Constructs a new PartitionEventRecord. + * @memberof google.spanner.v1.ChangeStreamRecord + * @classdesc Represents a PartitionEventRecord. + * @implements IPartitionEventRecord + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord=} [properties] Properties to set + */ + function PartitionEventRecord(properties) { + this.moveInEvents = []; + this.moveOutEvents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartitionEventRecord commitTimestamp. + * @member {google.protobuf.ITimestamp|null|undefined} commitTimestamp + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @instance + */ + PartitionEventRecord.prototype.commitTimestamp = null; + + /** + * PartitionEventRecord recordSequence. + * @member {string} recordSequence + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @instance + */ + PartitionEventRecord.prototype.recordSequence = ""; + + /** + * PartitionEventRecord partitionToken. + * @member {string} partitionToken + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @instance + */ + PartitionEventRecord.prototype.partitionToken = ""; + + /** + * PartitionEventRecord moveInEvents. + * @member {Array.} moveInEvents + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @instance + */ + PartitionEventRecord.prototype.moveInEvents = $util.emptyArray; + + /** + * PartitionEventRecord moveOutEvents. + * @member {Array.} moveOutEvents + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @instance + */ + PartitionEventRecord.prototype.moveOutEvents = $util.emptyArray; + + /** + * Creates a new PartitionEventRecord instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord} PartitionEventRecord instance + */ + PartitionEventRecord.create = function create(properties) { + return new PartitionEventRecord(properties); + }; + + /** + * Encodes the specified PartitionEventRecord message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord} message PartitionEventRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionEventRecord.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.commitTimestamp != null && Object.hasOwnProperty.call(message, "commitTimestamp")) + $root.google.protobuf.Timestamp.encode(message.commitTimestamp, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.recordSequence != null && Object.hasOwnProperty.call(message, "recordSequence")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.recordSequence); + if (message.partitionToken != null && Object.hasOwnProperty.call(message, "partitionToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.partitionToken); + if (message.moveInEvents != null && message.moveInEvents.length) + for (var i = 0; i < message.moveInEvents.length; ++i) + $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.encode(message.moveInEvents[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.moveOutEvents != null && message.moveOutEvents.length) + for (var i = 0; i < message.moveOutEvents.length; ++i) + $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.encode(message.moveOutEvents[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PartitionEventRecord message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.IPartitionEventRecord} message PartitionEventRecord message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartitionEventRecord.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartitionEventRecord message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord} PartitionEventRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionEventRecord.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.spanner.v1.ChangeStreamRecord.PartitionEventRecord(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.commitTimestamp = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 2: { + message.recordSequence = reader.string(); + break; + } + case 3: { + message.partitionToken = reader.string(); + break; + } + case 4: { + if (!(message.moveInEvents && message.moveInEvents.length)) + message.moveInEvents = []; + message.moveInEvents.push($root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.decode(reader, reader.uint32())); + break; + } + case 5: { + if (!(message.moveOutEvents && message.moveOutEvents.length)) + message.moveOutEvents = []; + message.moveOutEvents.push($root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartitionEventRecord message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord} PartitionEventRecord + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartitionEventRecord.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartitionEventRecord message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartitionEventRecord.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.commitTimestamp != null && message.hasOwnProperty("commitTimestamp")) { + var error = $root.google.protobuf.Timestamp.verify(message.commitTimestamp); + if (error) + return "commitTimestamp." + error; + } + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + if (!$util.isString(message.recordSequence)) + return "recordSequence: string expected"; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + if (!$util.isString(message.partitionToken)) + return "partitionToken: string expected"; + if (message.moveInEvents != null && message.hasOwnProperty("moveInEvents")) { + if (!Array.isArray(message.moveInEvents)) + return "moveInEvents: array expected"; + for (var i = 0; i < message.moveInEvents.length; ++i) { + var error = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.verify(message.moveInEvents[i]); + if (error) + return "moveInEvents." + error; + } + } + if (message.moveOutEvents != null && message.hasOwnProperty("moveOutEvents")) { + if (!Array.isArray(message.moveOutEvents)) + return "moveOutEvents: array expected"; + for (var i = 0; i < message.moveOutEvents.length; ++i) { + var error = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.verify(message.moveOutEvents[i]); + if (error) + return "moveOutEvents." + error; + } + } + return null; + }; + + /** + * Creates a PartitionEventRecord message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord} PartitionEventRecord + */ + PartitionEventRecord.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord(); + if (object.commitTimestamp != null) { + if (typeof object.commitTimestamp !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.commitTimestamp: object expected"); + message.commitTimestamp = $root.google.protobuf.Timestamp.fromObject(object.commitTimestamp); + } + if (object.recordSequence != null) + message.recordSequence = String(object.recordSequence); + if (object.partitionToken != null) + message.partitionToken = String(object.partitionToken); + if (object.moveInEvents) { + if (!Array.isArray(object.moveInEvents)) + throw TypeError(".google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.moveInEvents: array expected"); + message.moveInEvents = []; + for (var i = 0; i < object.moveInEvents.length; ++i) { + if (typeof object.moveInEvents[i] !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.moveInEvents: object expected"); + message.moveInEvents[i] = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.fromObject(object.moveInEvents[i]); + } + } + if (object.moveOutEvents) { + if (!Array.isArray(object.moveOutEvents)) + throw TypeError(".google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.moveOutEvents: array expected"); + message.moveOutEvents = []; + for (var i = 0; i < object.moveOutEvents.length; ++i) { + if (typeof object.moveOutEvents[i] !== "object") + throw TypeError(".google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.moveOutEvents: object expected"); + message.moveOutEvents[i] = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.fromObject(object.moveOutEvents[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a PartitionEventRecord message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord} message PartitionEventRecord + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionEventRecord.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.moveInEvents = []; + object.moveOutEvents = []; + } + if (options.defaults) { + object.commitTimestamp = null; + object.recordSequence = ""; + object.partitionToken = ""; + } + if (message.commitTimestamp != null && message.hasOwnProperty("commitTimestamp")) + object.commitTimestamp = $root.google.protobuf.Timestamp.toObject(message.commitTimestamp, options); + if (message.recordSequence != null && message.hasOwnProperty("recordSequence")) + object.recordSequence = message.recordSequence; + if (message.partitionToken != null && message.hasOwnProperty("partitionToken")) + object.partitionToken = message.partitionToken; + if (message.moveInEvents && message.moveInEvents.length) { + object.moveInEvents = []; + for (var j = 0; j < message.moveInEvents.length; ++j) + object.moveInEvents[j] = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.toObject(message.moveInEvents[j], options); + } + if (message.moveOutEvents && message.moveOutEvents.length) { + object.moveOutEvents = []; + for (var j = 0; j < message.moveOutEvents.length; ++j) + object.moveOutEvents[j] = $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.toObject(message.moveOutEvents[j], options); + } + return object; + }; + + /** + * Converts this PartitionEventRecord to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @instance + * @returns {Object.} JSON object + */ + PartitionEventRecord.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionEventRecord + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionEventRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.PartitionEventRecord"; + }; + + PartitionEventRecord.MoveInEvent = (function() { + + /** + * Properties of a MoveInEvent. + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @interface IMoveInEvent + * @property {string|null} [sourcePartitionToken] MoveInEvent sourcePartitionToken + */ + + /** + * Constructs a new MoveInEvent. + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @classdesc Represents a MoveInEvent. + * @implements IMoveInEvent + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent=} [properties] Properties to set + */ + function MoveInEvent(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MoveInEvent sourcePartitionToken. + * @member {string} sourcePartitionToken + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @instance + */ + MoveInEvent.prototype.sourcePartitionToken = ""; + + /** + * Creates a new MoveInEvent instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent} MoveInEvent instance + */ + MoveInEvent.create = function create(properties) { + return new MoveInEvent(properties); + }; + + /** + * Encodes the specified MoveInEvent message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent} message MoveInEvent message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveInEvent.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.sourcePartitionToken != null && Object.hasOwnProperty.call(message, "sourcePartitionToken")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.sourcePartitionToken); + return writer; + }; + + /** + * Encodes the specified MoveInEvent message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveInEvent} message MoveInEvent message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveInEvent.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MoveInEvent message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent} MoveInEvent + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveInEvent.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.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.sourcePartitionToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MoveInEvent message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent} MoveInEvent + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveInEvent.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MoveInEvent message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MoveInEvent.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.sourcePartitionToken != null && message.hasOwnProperty("sourcePartitionToken")) + if (!$util.isString(message.sourcePartitionToken)) + return "sourcePartitionToken: string expected"; + return null; + }; + + /** + * Creates a MoveInEvent message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent} MoveInEvent + */ + MoveInEvent.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent(); + if (object.sourcePartitionToken != null) + message.sourcePartitionToken = String(object.sourcePartitionToken); + return message; + }; + + /** + * Creates a plain object from a MoveInEvent message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent} message MoveInEvent + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MoveInEvent.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.sourcePartitionToken = ""; + if (message.sourcePartitionToken != null && message.hasOwnProperty("sourcePartitionToken")) + object.sourcePartitionToken = message.sourcePartitionToken; + return object; + }; + + /** + * Converts this MoveInEvent to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @instance + * @returns {Object.} JSON object + */ + MoveInEvent.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MoveInEvent + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MoveInEvent.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveInEvent"; + }; + + return MoveInEvent; + })(); + + PartitionEventRecord.MoveOutEvent = (function() { + + /** + * Properties of a MoveOutEvent. + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @interface IMoveOutEvent + * @property {string|null} [destinationPartitionToken] MoveOutEvent destinationPartitionToken + */ + + /** + * Constructs a new MoveOutEvent. + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord + * @classdesc Represents a MoveOutEvent. + * @implements IMoveOutEvent + * @constructor + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent=} [properties] Properties to set + */ + function MoveOutEvent(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MoveOutEvent destinationPartitionToken. + * @member {string} destinationPartitionToken + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @instance + */ + MoveOutEvent.prototype.destinationPartitionToken = ""; + + /** + * Creates a new MoveOutEvent instance using the specified properties. + * @function create + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent=} [properties] Properties to set + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent} MoveOutEvent instance + */ + MoveOutEvent.create = function create(properties) { + return new MoveOutEvent(properties); + }; + + /** + * Encodes the specified MoveOutEvent message. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.verify|verify} messages. + * @function encode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent} message MoveOutEvent message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveOutEvent.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.destinationPartitionToken != null && Object.hasOwnProperty.call(message, "destinationPartitionToken")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.destinationPartitionToken); + return writer; + }; + + /** + * Encodes the specified MoveOutEvent message, length delimited. Does not implicitly {@link google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent.verify|verify} messages. + * @function encodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.IMoveOutEvent} message MoveOutEvent message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MoveOutEvent.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MoveOutEvent message from the specified reader or buffer. + * @function decode + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent} MoveOutEvent + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveOutEvent.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.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.destinationPartitionToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MoveOutEvent message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent} MoveOutEvent + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MoveOutEvent.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MoveOutEvent message. + * @function verify + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MoveOutEvent.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.destinationPartitionToken != null && message.hasOwnProperty("destinationPartitionToken")) + if (!$util.isString(message.destinationPartitionToken)) + return "destinationPartitionToken: string expected"; + return null; + }; + + /** + * Creates a MoveOutEvent message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {Object.} object Plain object + * @returns {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent} MoveOutEvent + */ + MoveOutEvent.fromObject = function fromObject(object) { + if (object instanceof $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent) + return object; + var message = new $root.google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent(); + if (object.destinationPartitionToken != null) + message.destinationPartitionToken = String(object.destinationPartitionToken); + return message; + }; + + /** + * Creates a plain object from a MoveOutEvent message. Also converts values to other types if specified. + * @function toObject + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent} message MoveOutEvent + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MoveOutEvent.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.destinationPartitionToken = ""; + if (message.destinationPartitionToken != null && message.hasOwnProperty("destinationPartitionToken")) + object.destinationPartitionToken = message.destinationPartitionToken; + return object; + }; + + /** + * Converts this MoveOutEvent to JSON. + * @function toJSON + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @instance + * @returns {Object.} JSON object + */ + MoveOutEvent.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MoveOutEvent + * @function getTypeUrl + * @memberof google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MoveOutEvent.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.spanner.v1.ChangeStreamRecord.PartitionEventRecord.MoveOutEvent"; + }; + + return MoveOutEvent; + })(); + + return PartitionEventRecord; + })(); + + return ChangeStreamRecord; + })(); + + return v1; + })(); + + return spanner; + })(); + + google.api = (function() { + + /** + * Namespace api. + * @memberof google + * @namespace + */ + var api = {}; + + /** + * FieldBehavior enum. + * @name google.api.FieldBehavior + * @enum {number} + * @property {number} FIELD_BEHAVIOR_UNSPECIFIED=0 FIELD_BEHAVIOR_UNSPECIFIED value + * @property {number} OPTIONAL=1 OPTIONAL value + * @property {number} REQUIRED=2 REQUIRED value + * @property {number} OUTPUT_ONLY=3 OUTPUT_ONLY value + * @property {number} INPUT_ONLY=4 INPUT_ONLY value + * @property {number} IMMUTABLE=5 IMMUTABLE value + * @property {number} UNORDERED_LIST=6 UNORDERED_LIST value + * @property {number} NON_EMPTY_DEFAULT=7 NON_EMPTY_DEFAULT value + * @property {number} IDENTIFIER=8 IDENTIFIER value + */ + api.FieldBehavior = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_BEHAVIOR_UNSPECIFIED"] = 0; + values[valuesById[1] = "OPTIONAL"] = 1; + values[valuesById[2] = "REQUIRED"] = 2; + values[valuesById[3] = "OUTPUT_ONLY"] = 3; + values[valuesById[4] = "INPUT_ONLY"] = 4; + values[valuesById[5] = "IMMUTABLE"] = 5; + values[valuesById[6] = "UNORDERED_LIST"] = 6; + values[valuesById[7] = "NON_EMPTY_DEFAULT"] = 7; + values[valuesById[8] = "IDENTIFIER"] = 8; + return values; + })(); + + api.ResourceDescriptor = (function() { + + /** + * Properties of a ResourceDescriptor. + * @memberof google.api + * @interface IResourceDescriptor + * @property {string|null} [type] ResourceDescriptor type + * @property {Array.|null} [pattern] ResourceDescriptor pattern + * @property {string|null} [nameField] ResourceDescriptor nameField + * @property {google.api.ResourceDescriptor.History|null} [history] ResourceDescriptor history + * @property {string|null} [plural] ResourceDescriptor plural + * @property {string|null} [singular] ResourceDescriptor singular + * @property {Array.|null} [style] ResourceDescriptor style + */ + + /** + * Constructs a new ResourceDescriptor. + * @memberof google.api + * @classdesc Represents a ResourceDescriptor. + * @implements IResourceDescriptor + * @constructor + * @param {google.api.IResourceDescriptor=} [properties] Properties to set + */ + function ResourceDescriptor(properties) { + this.pattern = []; + this.style = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceDescriptor type. + * @member {string} type + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.type = ""; + + /** + * ResourceDescriptor pattern. + * @member {Array.} pattern + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.pattern = $util.emptyArray; + + /** + * ResourceDescriptor nameField. + * @member {string} nameField + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.nameField = ""; + + /** + * ResourceDescriptor history. + * @member {google.api.ResourceDescriptor.History} history + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.history = 0; + + /** + * ResourceDescriptor plural. + * @member {string} plural + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.plural = ""; + + /** + * ResourceDescriptor singular. + * @member {string} singular + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.singular = ""; + + /** + * ResourceDescriptor style. + * @member {Array.} style + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.style = $util.emptyArray; + + /** + * Creates a new ResourceDescriptor instance using the specified properties. + * @function create + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.IResourceDescriptor=} [properties] Properties to set + * @returns {google.api.ResourceDescriptor} ResourceDescriptor instance + */ + ResourceDescriptor.create = function create(properties) { + return new ResourceDescriptor(properties); + }; + + /** + * Encodes the specified ResourceDescriptor message. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @function encode + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.IResourceDescriptor} message ResourceDescriptor message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceDescriptor.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.type); + if (message.pattern != null && message.pattern.length) + for (var i = 0; i < message.pattern.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.pattern[i]); + if (message.nameField != null && Object.hasOwnProperty.call(message, "nameField")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.nameField); + if (message.history != null && Object.hasOwnProperty.call(message, "history")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.history); + if (message.plural != null && Object.hasOwnProperty.call(message, "plural")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.plural); + if (message.singular != null && Object.hasOwnProperty.call(message, "singular")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.singular); + if (message.style != null && message.style.length) { + writer.uint32(/* id 10, wireType 2 =*/82).fork(); + for (var i = 0; i < message.style.length; ++i) + writer.int32(message.style[i]); + writer.ldelim(); + } + return writer; + }; + + /** + * Encodes the specified ResourceDescriptor message, length delimited. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.IResourceDescriptor} message ResourceDescriptor message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceDescriptor.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer. + * @function decode + * @memberof google.api.ResourceDescriptor + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + * @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, 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(); + break; + } + case 2: { + if (!(message.pattern && message.pattern.length)) + message.pattern = []; + message.pattern.push(reader.string()); + break; + } + case 3: { + message.nameField = reader.string(); + break; + } + case 4: { + message.history = reader.int32(); + break; + } + case 5: { + message.plural = reader.string(); + break; + } + case 6: { + message.singular = reader.string(); + break; + } + case 10: { + if (!(message.style && message.style.length)) + message.style = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.style.push(reader.int32()); + } else + message.style.push(reader.int32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.ResourceDescriptor + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceDescriptor.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ResourceDescriptor message. + * @function verify + * @memberof google.api.ResourceDescriptor + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResourceDescriptor.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.pattern != null && message.hasOwnProperty("pattern")) { + if (!Array.isArray(message.pattern)) + return "pattern: array expected"; + for (var i = 0; i < message.pattern.length; ++i) + if (!$util.isString(message.pattern[i])) + return "pattern: string[] expected"; + } + if (message.nameField != null && message.hasOwnProperty("nameField")) + if (!$util.isString(message.nameField)) + return "nameField: string expected"; + if (message.history != null && message.hasOwnProperty("history")) + switch (message.history) { + default: + return "history: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.plural != null && message.hasOwnProperty("plural")) + if (!$util.isString(message.plural)) + return "plural: string expected"; + if (message.singular != null && message.hasOwnProperty("singular")) + if (!$util.isString(message.singular)) + return "singular: string expected"; + if (message.style != null && message.hasOwnProperty("style")) { + if (!Array.isArray(message.style)) + return "style: array expected"; + for (var i = 0; i < message.style.length; ++i) + switch (message.style[i]) { + default: + return "style: enum value[] expected"; + case 0: + case 1: + break; + } + } + return null; + }; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + */ + ResourceDescriptor.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceDescriptor) + return object; + var message = new $root.google.api.ResourceDescriptor(); + if (object.type != null) + message.type = String(object.type); + if (object.pattern) { + if (!Array.isArray(object.pattern)) + throw TypeError(".google.api.ResourceDescriptor.pattern: array expected"); + message.pattern = []; + for (var i = 0; i < object.pattern.length; ++i) + message.pattern[i] = String(object.pattern[i]); + } + if (object.nameField != null) + message.nameField = String(object.nameField); + switch (object.history) { + default: + if (typeof object.history === "number") { + message.history = object.history; + break; + } + break; + case "HISTORY_UNSPECIFIED": + case 0: + message.history = 0; + break; + case "ORIGINALLY_SINGLE_PATTERN": + case 1: + message.history = 1; + break; + case "FUTURE_MULTI_PATTERN": + case 2: + message.history = 2; + break; + } + if (object.plural != null) + message.plural = String(object.plural); + if (object.singular != null) + message.singular = String(object.singular); + if (object.style) { + if (!Array.isArray(object.style)) + throw TypeError(".google.api.ResourceDescriptor.style: array expected"); + message.style = []; + for (var i = 0; i < object.style.length; ++i) + switch (object.style[i]) { + default: + if (typeof object.style[i] === "number") { + message.style[i] = object.style[i]; + break; + } + case "STYLE_UNSPECIFIED": + case 0: + message.style[i] = 0; + break; + case "DECLARATIVE_FRIENDLY": + case 1: + message.style[i] = 1; + break; + } + } + return message; + }; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.ResourceDescriptor} message ResourceDescriptor + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceDescriptor.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.pattern = []; + object.style = []; + } + if (options.defaults) { + object.type = ""; + object.nameField = ""; + object.history = options.enums === String ? "HISTORY_UNSPECIFIED" : 0; + object.plural = ""; + object.singular = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.pattern && message.pattern.length) { + object.pattern = []; + for (var j = 0; j < message.pattern.length; ++j) + object.pattern[j] = message.pattern[j]; + } + if (message.nameField != null && message.hasOwnProperty("nameField")) + object.nameField = message.nameField; + if (message.history != null && message.hasOwnProperty("history")) + object.history = options.enums === String ? $root.google.api.ResourceDescriptor.History[message.history] === undefined ? message.history : $root.google.api.ResourceDescriptor.History[message.history] : message.history; + if (message.plural != null && message.hasOwnProperty("plural")) + object.plural = message.plural; + if (message.singular != null && message.hasOwnProperty("singular")) + object.singular = message.singular; + if (message.style && message.style.length) { + object.style = []; + for (var j = 0; j < message.style.length; ++j) + object.style[j] = options.enums === String ? $root.google.api.ResourceDescriptor.Style[message.style[j]] === undefined ? message.style[j] : $root.google.api.ResourceDescriptor.Style[message.style[j]] : message.style[j]; + } + return object; + }; + + /** + * Converts this ResourceDescriptor to JSON. + * @function toJSON + * @memberof google.api.ResourceDescriptor + * @instance + * @returns {Object.} JSON object + */ + ResourceDescriptor.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceDescriptor + * @function getTypeUrl + * @memberof google.api.ResourceDescriptor + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceDescriptor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceDescriptor"; + }; + + /** + * History enum. + * @name google.api.ResourceDescriptor.History + * @enum {number} + * @property {number} HISTORY_UNSPECIFIED=0 HISTORY_UNSPECIFIED value + * @property {number} ORIGINALLY_SINGLE_PATTERN=1 ORIGINALLY_SINGLE_PATTERN value + * @property {number} FUTURE_MULTI_PATTERN=2 FUTURE_MULTI_PATTERN value + */ + ResourceDescriptor.History = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "HISTORY_UNSPECIFIED"] = 0; + values[valuesById[1] = "ORIGINALLY_SINGLE_PATTERN"] = 1; + values[valuesById[2] = "FUTURE_MULTI_PATTERN"] = 2; + return values; + })(); + + /** + * Style enum. + * @name google.api.ResourceDescriptor.Style + * @enum {number} + * @property {number} STYLE_UNSPECIFIED=0 STYLE_UNSPECIFIED value + * @property {number} DECLARATIVE_FRIENDLY=1 DECLARATIVE_FRIENDLY value + */ + ResourceDescriptor.Style = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STYLE_UNSPECIFIED"] = 0; + values[valuesById[1] = "DECLARATIVE_FRIENDLY"] = 1; + return values; + })(); + + return ResourceDescriptor; + })(); + + api.ResourceReference = (function() { + + /** + * Properties of a ResourceReference. + * @memberof google.api + * @interface IResourceReference + * @property {string|null} [type] ResourceReference type + * @property {string|null} [childType] ResourceReference childType + */ + + /** + * Constructs a new ResourceReference. + * @memberof google.api + * @classdesc Represents a ResourceReference. + * @implements IResourceReference + * @constructor + * @param {google.api.IResourceReference=} [properties] Properties to set + */ + function ResourceReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceReference type. + * @member {string} type + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.type = ""; + + /** + * ResourceReference childType. + * @member {string} childType + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.childType = ""; + + /** + * Creates a new ResourceReference instance using the specified properties. + * @function create + * @memberof google.api.ResourceReference + * @static + * @param {google.api.IResourceReference=} [properties] Properties to set + * @returns {google.api.ResourceReference} ResourceReference instance + */ + ResourceReference.create = function create(properties) { + return new ResourceReference(properties); + }; + + /** + * Encodes the specified ResourceReference message. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @function encode + * @memberof google.api.ResourceReference + * @static + * @param {google.api.IResourceReference} message ResourceReference message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceReference.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.type); + if (message.childType != null && Object.hasOwnProperty.call(message, "childType")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.childType); + return writer; + }; + + /** + * Encodes the specified ResourceReference message, length delimited. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.ResourceReference + * @static + * @param {google.api.IResourceReference} message ResourceReference message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceReference.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ResourceReference message from the specified reader or buffer. + * @function decode + * @memberof google.api.ResourceReference + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.ResourceReference} ResourceReference + * @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, 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(); + break; + } + case 2: { + message.childType = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ResourceReference message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.ResourceReference + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.ResourceReference} ResourceReference + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceReference.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ResourceReference message. + * @function verify + * @memberof google.api.ResourceReference + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResourceReference.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.childType != null && message.hasOwnProperty("childType")) + if (!$util.isString(message.childType)) + return "childType: string expected"; + return null; + }; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceReference + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceReference} ResourceReference + */ + ResourceReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceReference) + return object; + var message = new $root.google.api.ResourceReference(); + if (object.type != null) + message.type = String(object.type); + if (object.childType != null) + message.childType = String(object.childType); + return message; + }; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceReference + * @static + * @param {google.api.ResourceReference} message ResourceReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type = ""; + object.childType = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.childType != null && message.hasOwnProperty("childType")) + object.childType = message.childType; + return object; + }; + + /** + * Converts this ResourceReference to JSON. + * @function toJSON + * @memberof google.api.ResourceReference + * @instance + * @returns {Object.} JSON object + */ + ResourceReference.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceReference + * @function getTypeUrl + * @memberof google.api.ResourceReference + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceReference"; + }; + + return ResourceReference; + })(); + + api.Http = (function() { + + /** + * Properties of a Http. + * @memberof google.api + * @interface IHttp + * @property {Array.|null} [rules] Http rules + * @property {boolean|null} [fullyDecodeReservedExpansion] Http fullyDecodeReservedExpansion + */ + + /** + * Constructs a new Http. + * @memberof google.api + * @classdesc Represents a Http. + * @implements IHttp + * @constructor + * @param {google.api.IHttp=} [properties] Properties to set + */ + function Http(properties) { + this.rules = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Http rules. + * @member {Array.} rules + * @memberof google.api.Http + * @instance + */ + Http.prototype.rules = $util.emptyArray; + + /** + * Http fullyDecodeReservedExpansion. + * @member {boolean} fullyDecodeReservedExpansion + * @memberof google.api.Http + * @instance + */ + Http.prototype.fullyDecodeReservedExpansion = false; + + /** + * Creates a new Http instance using the specified properties. + * @function create + * @memberof google.api.Http + * @static + * @param {google.api.IHttp=} [properties] Properties to set + * @returns {google.api.Http} Http instance + */ + Http.create = function create(properties) { + return new Http(properties); + }; + + /** + * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @function encode + * @memberof google.api.Http + * @static + * @param {google.api.IHttp} message Http message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Http.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.rules != null && message.rules.length) + for (var i = 0; i < message.rules.length; ++i) + $root.google.api.HttpRule.encode(message.rules[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.fullyDecodeReservedExpansion != null && Object.hasOwnProperty.call(message, "fullyDecodeReservedExpansion")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.fullyDecodeReservedExpansion); + return writer; + }; + + /** + * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.Http + * @static + * @param {google.api.IHttp} message Http message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Http.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Http message from the specified reader or buffer. + * @function decode + * @memberof google.api.Http + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.Http} Http + * @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, 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)) + message.rules = []; + message.rules.push($root.google.api.HttpRule.decode(reader, reader.uint32())); + break; + } + case 2: { + message.fullyDecodeReservedExpansion = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Http message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.Http + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.Http} Http + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Http.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Http message. + * @function verify + * @memberof google.api.Http + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Http.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.rules != null && message.hasOwnProperty("rules")) { + if (!Array.isArray(message.rules)) + return "rules: array expected"; + for (var i = 0; i < message.rules.length; ++i) { + var error = $root.google.api.HttpRule.verify(message.rules[i]); + if (error) + return "rules." + error; + } + } + if (message.fullyDecodeReservedExpansion != null && message.hasOwnProperty("fullyDecodeReservedExpansion")) + if (typeof message.fullyDecodeReservedExpansion !== "boolean") + return "fullyDecodeReservedExpansion: boolean expected"; + return null; + }; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Http + * @static + * @param {Object.} object Plain object + * @returns {google.api.Http} Http + */ + Http.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Http) + return object; + var message = new $root.google.api.Http(); + if (object.rules) { + if (!Array.isArray(object.rules)) + throw TypeError(".google.api.Http.rules: array expected"); + message.rules = []; + for (var i = 0; i < object.rules.length; ++i) { + if (typeof object.rules[i] !== "object") + throw TypeError(".google.api.Http.rules: object expected"); + message.rules[i] = $root.google.api.HttpRule.fromObject(object.rules[i]); + } + } + if (object.fullyDecodeReservedExpansion != null) + message.fullyDecodeReservedExpansion = Boolean(object.fullyDecodeReservedExpansion); + return message; + }; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Http + * @static + * @param {google.api.Http} message Http + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Http.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.rules = []; + if (options.defaults) + object.fullyDecodeReservedExpansion = false; + if (message.rules && message.rules.length) { + object.rules = []; + for (var j = 0; j < message.rules.length; ++j) + object.rules[j] = $root.google.api.HttpRule.toObject(message.rules[j], options); + } + if (message.fullyDecodeReservedExpansion != null && message.hasOwnProperty("fullyDecodeReservedExpansion")) + object.fullyDecodeReservedExpansion = message.fullyDecodeReservedExpansion; + return object; + }; + + /** + * Converts this Http to JSON. + * @function toJSON + * @memberof google.api.Http + * @instance + * @returns {Object.} JSON object + */ + Http.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Http + * @function getTypeUrl + * @memberof google.api.Http + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Http.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.Http"; + }; + + return Http; + })(); + + api.HttpRule = (function() { + + /** + * Properties of a HttpRule. + * @memberof google.api + * @interface IHttpRule + * @property {string|null} [selector] HttpRule selector + * @property {string|null} [get] HttpRule get + * @property {string|null} [put] HttpRule put + * @property {string|null} [post] HttpRule post + * @property {string|null} ["delete"] HttpRule delete + * @property {string|null} [patch] HttpRule patch + * @property {google.api.ICustomHttpPattern|null} [custom] HttpRule custom + * @property {string|null} [body] HttpRule body + * @property {string|null} [responseBody] HttpRule responseBody + * @property {Array.|null} [additionalBindings] HttpRule additionalBindings + */ + + /** + * Constructs a new HttpRule. + * @memberof google.api + * @classdesc Represents a HttpRule. + * @implements IHttpRule + * @constructor + * @param {google.api.IHttpRule=} [properties] Properties to set + */ + function HttpRule(properties) { + this.additionalBindings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * HttpRule selector. + * @member {string} selector + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.selector = ""; + + /** + * HttpRule get. + * @member {string|null|undefined} get + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.get = null; + + /** + * HttpRule put. + * @member {string|null|undefined} put + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.put = null; + + /** + * HttpRule post. + * @member {string|null|undefined} post + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.post = null; + + /** + * HttpRule delete. + * @member {string|null|undefined} delete + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype["delete"] = null; + + /** + * HttpRule patch. + * @member {string|null|undefined} patch + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.patch = null; + + /** + * HttpRule custom. + * @member {google.api.ICustomHttpPattern|null|undefined} custom + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.custom = null; + + /** + * HttpRule body. + * @member {string} body + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.body = ""; + + /** + * HttpRule responseBody. + * @member {string} responseBody + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.responseBody = ""; + + /** + * HttpRule additionalBindings. + * @member {Array.} additionalBindings + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.additionalBindings = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * HttpRule pattern. + * @member {"get"|"put"|"post"|"delete"|"patch"|"custom"|undefined} pattern + * @memberof google.api.HttpRule + * @instance + */ + Object.defineProperty(HttpRule.prototype, "pattern", { + get: $util.oneOfGetter($oneOfFields = ["get", "put", "post", "delete", "patch", "custom"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new HttpRule instance using the specified properties. + * @function create + * @memberof google.api.HttpRule + * @static + * @param {google.api.IHttpRule=} [properties] Properties to set + * @returns {google.api.HttpRule} HttpRule instance + */ + HttpRule.create = function create(properties) { + return new HttpRule(properties); + }; + + /** + * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @function encode + * @memberof google.api.HttpRule + * @static + * @param {google.api.IHttpRule} message HttpRule message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + HttpRule.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.selector != null && Object.hasOwnProperty.call(message, "selector")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.selector); + if (message.get != null && Object.hasOwnProperty.call(message, "get")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.get); + if (message.put != null && Object.hasOwnProperty.call(message, "put")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.put); + if (message.post != null && Object.hasOwnProperty.call(message, "post")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.post); + if (message["delete"] != null && Object.hasOwnProperty.call(message, "delete")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message["delete"]); + if (message.patch != null && Object.hasOwnProperty.call(message, "patch")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.patch); + if (message.body != null && Object.hasOwnProperty.call(message, "body")) + writer.uint32(/* id 7, wireType 2 =*/58).string(message.body); + if (message.custom != null && Object.hasOwnProperty.call(message, "custom")) + $root.google.api.CustomHttpPattern.encode(message.custom, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.additionalBindings != null && message.additionalBindings.length) + for (var i = 0; i < message.additionalBindings.length; ++i) + $root.google.api.HttpRule.encode(message.additionalBindings[i], writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); + if (message.responseBody != null && Object.hasOwnProperty.call(message, "responseBody")) + writer.uint32(/* id 12, wireType 2 =*/98).string(message.responseBody); + return writer; + }; + + /** + * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.HttpRule + * @static + * @param {google.api.IHttpRule} message HttpRule message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + HttpRule.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a HttpRule message from the specified reader or buffer. + * @function decode + * @memberof google.api.HttpRule + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.HttpRule} HttpRule + * @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, 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(); + break; + } + case 2: { + message.get = reader.string(); + break; + } + case 3: { + message.put = reader.string(); + break; + } + case 4: { + message.post = reader.string(); + break; + } + case 5: { + message["delete"] = reader.string(); + break; + } + case 6: { + message.patch = reader.string(); + break; + } + case 8: { + message.custom = $root.google.api.CustomHttpPattern.decode(reader, reader.uint32()); + break; + } + case 7: { + message.body = reader.string(); + break; + } + case 12: { + message.responseBody = reader.string(); + break; + } + case 11: { + if (!(message.additionalBindings && message.additionalBindings.length)) + message.additionalBindings = []; + message.additionalBindings.push($root.google.api.HttpRule.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a HttpRule message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.HttpRule + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.HttpRule} HttpRule + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + HttpRule.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a HttpRule message. + * @function verify + * @memberof google.api.HttpRule + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + HttpRule.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.selector != null && message.hasOwnProperty("selector")) + if (!$util.isString(message.selector)) + return "selector: string expected"; + if (message.get != null && message.hasOwnProperty("get")) { + properties.pattern = 1; + if (!$util.isString(message.get)) + return "get: string expected"; + } + if (message.put != null && message.hasOwnProperty("put")) { + if (properties.pattern === 1) + return "pattern: multiple values"; + properties.pattern = 1; + if (!$util.isString(message.put)) + return "put: string expected"; + } + if (message.post != null && message.hasOwnProperty("post")) { + if (properties.pattern === 1) + return "pattern: multiple values"; + properties.pattern = 1; + if (!$util.isString(message.post)) + return "post: string expected"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + if (properties.pattern === 1) + return "pattern: multiple values"; + properties.pattern = 1; + if (!$util.isString(message["delete"])) + return "delete: string expected"; + } + if (message.patch != null && message.hasOwnProperty("patch")) { + if (properties.pattern === 1) + return "pattern: multiple values"; + properties.pattern = 1; + if (!$util.isString(message.patch)) + return "patch: string expected"; + } + if (message.custom != null && message.hasOwnProperty("custom")) { + if (properties.pattern === 1) + return "pattern: multiple values"; + properties.pattern = 1; + { + var error = $root.google.api.CustomHttpPattern.verify(message.custom); + if (error) + return "custom." + error; + } + } + if (message.body != null && message.hasOwnProperty("body")) + if (!$util.isString(message.body)) + return "body: string expected"; + if (message.responseBody != null && message.hasOwnProperty("responseBody")) + if (!$util.isString(message.responseBody)) + return "responseBody: string expected"; + if (message.additionalBindings != null && message.hasOwnProperty("additionalBindings")) { + if (!Array.isArray(message.additionalBindings)) + return "additionalBindings: array expected"; + for (var i = 0; i < message.additionalBindings.length; ++i) { + var error = $root.google.api.HttpRule.verify(message.additionalBindings[i]); + if (error) + return "additionalBindings." + error; + } + } + return null; + }; + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.HttpRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.HttpRule} HttpRule + */ + HttpRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.HttpRule) + return object; + var message = new $root.google.api.HttpRule(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.get != null) + message.get = String(object.get); + if (object.put != null) + message.put = String(object.put); + if (object.post != null) + message.post = String(object.post); + if (object["delete"] != null) + message["delete"] = String(object["delete"]); + if (object.patch != null) + message.patch = String(object.patch); + if (object.custom != null) { + if (typeof object.custom !== "object") + throw TypeError(".google.api.HttpRule.custom: object expected"); + message.custom = $root.google.api.CustomHttpPattern.fromObject(object.custom); + } + if (object.body != null) + message.body = String(object.body); + if (object.responseBody != null) + message.responseBody = String(object.responseBody); + if (object.additionalBindings) { + if (!Array.isArray(object.additionalBindings)) + throw TypeError(".google.api.HttpRule.additionalBindings: array expected"); + message.additionalBindings = []; + for (var i = 0; i < object.additionalBindings.length; ++i) { + if (typeof object.additionalBindings[i] !== "object") + throw TypeError(".google.api.HttpRule.additionalBindings: object expected"); + message.additionalBindings[i] = $root.google.api.HttpRule.fromObject(object.additionalBindings[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.HttpRule + * @static + * @param {google.api.HttpRule} message HttpRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + HttpRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.additionalBindings = []; + if (options.defaults) { + object.selector = ""; + object.body = ""; + object.responseBody = ""; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.get != null && message.hasOwnProperty("get")) { + object.get = message.get; + if (options.oneofs) + object.pattern = "get"; + } + if (message.put != null && message.hasOwnProperty("put")) { + object.put = message.put; + if (options.oneofs) + object.pattern = "put"; + } + if (message.post != null && message.hasOwnProperty("post")) { + object.post = message.post; + if (options.oneofs) + object.pattern = "post"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = message["delete"]; + if (options.oneofs) + object.pattern = "delete"; + } + if (message.patch != null && message.hasOwnProperty("patch")) { + object.patch = message.patch; + if (options.oneofs) + object.pattern = "patch"; + } + if (message.body != null && message.hasOwnProperty("body")) + object.body = message.body; + if (message.custom != null && message.hasOwnProperty("custom")) { + object.custom = $root.google.api.CustomHttpPattern.toObject(message.custom, options); + if (options.oneofs) + object.pattern = "custom"; + } + if (message.additionalBindings && message.additionalBindings.length) { + object.additionalBindings = []; + for (var j = 0; j < message.additionalBindings.length; ++j) + object.additionalBindings[j] = $root.google.api.HttpRule.toObject(message.additionalBindings[j], options); + } + if (message.responseBody != null && message.hasOwnProperty("responseBody")) + object.responseBody = message.responseBody; + return object; + }; + + /** + * Converts this HttpRule to JSON. + * @function toJSON + * @memberof google.api.HttpRule + * @instance + * @returns {Object.} JSON object + */ + HttpRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for HttpRule + * @function getTypeUrl + * @memberof google.api.HttpRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + HttpRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.HttpRule"; + }; + + return HttpRule; + })(); + + api.CustomHttpPattern = (function() { + + /** + * Properties of a CustomHttpPattern. + * @memberof google.api + * @interface ICustomHttpPattern + * @property {string|null} [kind] CustomHttpPattern kind + * @property {string|null} [path] CustomHttpPattern path + */ + + /** + * Constructs a new CustomHttpPattern. + * @memberof google.api + * @classdesc Represents a CustomHttpPattern. + * @implements ICustomHttpPattern + * @constructor + * @param {google.api.ICustomHttpPattern=} [properties] Properties to set + */ + function CustomHttpPattern(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CustomHttpPattern kind. + * @member {string} kind + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.kind = ""; + + /** + * CustomHttpPattern path. + * @member {string} path + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.path = ""; + + /** + * Creates a new CustomHttpPattern instance using the specified properties. + * @function create + * @memberof google.api.CustomHttpPattern + * @static + * @param {google.api.ICustomHttpPattern=} [properties] Properties to set + * @returns {google.api.CustomHttpPattern} CustomHttpPattern instance + */ + CustomHttpPattern.create = function create(properties) { + return new CustomHttpPattern(properties); + }; + + /** + * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @function encode + * @memberof google.api.CustomHttpPattern + * @static + * @param {google.api.ICustomHttpPattern} message CustomHttpPattern message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CustomHttpPattern.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.kind); + if (message.path != null && Object.hasOwnProperty.call(message, "path")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.path); + return writer; + }; + + /** + * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.CustomHttpPattern + * @static + * @param {google.api.ICustomHttpPattern} message CustomHttpPattern message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CustomHttpPattern.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer. + * @function decode + * @memberof google.api.CustomHttpPattern + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.CustomHttpPattern} CustomHttpPattern + * @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, 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(); + break; + } + case 2: { + message.path = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.CustomHttpPattern + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.CustomHttpPattern} CustomHttpPattern + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CustomHttpPattern.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CustomHttpPattern message. + * @function verify + * @memberof google.api.CustomHttpPattern + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CustomHttpPattern.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.kind != null && message.hasOwnProperty("kind")) + if (!$util.isString(message.kind)) + return "kind: string expected"; + if (message.path != null && message.hasOwnProperty("path")) + if (!$util.isString(message.path)) + return "path: string expected"; + return null; + }; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {Object.} object Plain object + * @returns {google.api.CustomHttpPattern} CustomHttpPattern + */ + CustomHttpPattern.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CustomHttpPattern) + return object; + var message = new $root.google.api.CustomHttpPattern(); + if (object.kind != null) + message.kind = String(object.kind); + if (object.path != null) + message.path = String(object.path); + return message; + }; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {google.api.CustomHttpPattern} message CustomHttpPattern + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CustomHttpPattern.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.kind = ""; + object.path = ""; + } + if (message.kind != null && message.hasOwnProperty("kind")) + object.kind = message.kind; + if (message.path != null && message.hasOwnProperty("path")) + object.path = message.path; + return object; + }; + + /** + * Converts this CustomHttpPattern to JSON. + * @function toJSON + * @memberof google.api.CustomHttpPattern + * @instance + * @returns {Object.} JSON object + */ + CustomHttpPattern.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CustomHttpPattern + * @function getTypeUrl + * @memberof google.api.CustomHttpPattern + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CustomHttpPattern.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CustomHttpPattern"; + }; + + return CustomHttpPattern; + })(); + + api.CommonLanguageSettings = (function() { + + /** + * Properties of a CommonLanguageSettings. + * @memberof google.api + * @interface ICommonLanguageSettings + * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri + * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration + */ + + /** + * Constructs a new CommonLanguageSettings. + * @memberof google.api + * @classdesc Represents a CommonLanguageSettings. + * @implements ICommonLanguageSettings + * @constructor + * @param {google.api.ICommonLanguageSettings=} [properties] Properties to set + */ + function CommonLanguageSettings(properties) { + this.destinations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CommonLanguageSettings referenceDocsUri. + * @member {string} referenceDocsUri + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.referenceDocsUri = ""; + + /** + * CommonLanguageSettings destinations. + * @member {Array.} destinations + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.destinations = $util.emptyArray; + + /** + * CommonLanguageSettings selectiveGapicGeneration. + * @member {google.api.ISelectiveGapicGeneration|null|undefined} selectiveGapicGeneration + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.selectiveGapicGeneration = null; + + /** + * Creates a new CommonLanguageSettings instance using the specified properties. + * @function create + * @memberof google.api.CommonLanguageSettings + * @static + * @param {google.api.ICommonLanguageSettings=} [properties] Properties to set + * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings instance + */ + CommonLanguageSettings.create = function create(properties) { + return new CommonLanguageSettings(properties); + }; + + /** + * Encodes the specified CommonLanguageSettings message. Does not implicitly {@link google.api.CommonLanguageSettings.verify|verify} messages. + * @function encode + * @memberof google.api.CommonLanguageSettings + * @static + * @param {google.api.ICommonLanguageSettings} message CommonLanguageSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CommonLanguageSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.referenceDocsUri != null && Object.hasOwnProperty.call(message, "referenceDocsUri")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.referenceDocsUri); + if (message.destinations != null && message.destinations.length) { + writer.uint32(/* id 2, wireType 2 =*/18).fork(); + for (var i = 0; i < message.destinations.length; ++i) + writer.int32(message.destinations[i]); + writer.ldelim(); + } + if (message.selectiveGapicGeneration != null && Object.hasOwnProperty.call(message, "selectiveGapicGeneration")) + $root.google.api.SelectiveGapicGeneration.encode(message.selectiveGapicGeneration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CommonLanguageSettings message, length delimited. Does not implicitly {@link google.api.CommonLanguageSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.CommonLanguageSettings + * @static + * @param {google.api.ICommonLanguageSettings} message CommonLanguageSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CommonLanguageSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CommonLanguageSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.CommonLanguageSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings + * @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, 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(); + break; + } + case 2: { + if (!(message.destinations && message.destinations.length)) + message.destinations = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.destinations.push(reader.int32()); + } else + message.destinations.push(reader.int32()); + break; + } + case 3: { + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CommonLanguageSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.CommonLanguageSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CommonLanguageSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CommonLanguageSettings message. + * @function verify + * @memberof google.api.CommonLanguageSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CommonLanguageSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) + if (!$util.isString(message.referenceDocsUri)) + return "referenceDocsUri: string expected"; + if (message.destinations != null && message.hasOwnProperty("destinations")) { + if (!Array.isArray(message.destinations)) + return "destinations: array expected"; + for (var i = 0; i < message.destinations.length; ++i) + switch (message.destinations[i]) { + default: + return "destinations: enum value[] expected"; + case 0: + case 10: + case 20: + break; + } + } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) { + var error = $root.google.api.SelectiveGapicGeneration.verify(message.selectiveGapicGeneration); + if (error) + return "selectiveGapicGeneration." + error; + } + return null; + }; + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings + */ + CommonLanguageSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CommonLanguageSettings) + return object; + var message = new $root.google.api.CommonLanguageSettings(); + if (object.referenceDocsUri != null) + message.referenceDocsUri = String(object.referenceDocsUri); + if (object.destinations) { + if (!Array.isArray(object.destinations)) + throw TypeError(".google.api.CommonLanguageSettings.destinations: array expected"); + message.destinations = []; + for (var i = 0; i < object.destinations.length; ++i) + switch (object.destinations[i]) { + default: + if (typeof object.destinations[i] === "number") { + message.destinations[i] = object.destinations[i]; + break; + } + case "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": + case 0: + message.destinations[i] = 0; + break; + case "GITHUB": + case 10: + message.destinations[i] = 10; + break; + case "PACKAGE_MANAGER": + case 20: + message.destinations[i] = 20; + break; + } + } + if (object.selectiveGapicGeneration != null) { + if (typeof object.selectiveGapicGeneration !== "object") + throw TypeError(".google.api.CommonLanguageSettings.selectiveGapicGeneration: object expected"); + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.fromObject(object.selectiveGapicGeneration); + } + return message; + }; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {google.api.CommonLanguageSettings} message CommonLanguageSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommonLanguageSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.destinations = []; + if (options.defaults) { + object.referenceDocsUri = ""; + object.selectiveGapicGeneration = null; + } + if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) + object.referenceDocsUri = message.referenceDocsUri; + if (message.destinations && message.destinations.length) { + object.destinations = []; + for (var j = 0; j < message.destinations.length; ++j) + object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; + } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) + object.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.toObject(message.selectiveGapicGeneration, options); + return object; + }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @function toJSON + * @memberof google.api.CommonLanguageSettings + * @instance + * @returns {Object.} JSON object + */ + CommonLanguageSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommonLanguageSettings + * @function getTypeUrl + * @memberof google.api.CommonLanguageSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommonLanguageSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CommonLanguageSettings"; + }; + + return CommonLanguageSettings; + })(); + + api.ClientLibrarySettings = (function() { + + /** + * Properties of a ClientLibrarySettings. + * @memberof google.api + * @interface IClientLibrarySettings + * @property {string|null} [version] ClientLibrarySettings version + * @property {google.api.LaunchStage|null} [launchStage] ClientLibrarySettings launchStage + * @property {boolean|null} [restNumericEnums] ClientLibrarySettings restNumericEnums + * @property {google.api.IJavaSettings|null} [javaSettings] ClientLibrarySettings javaSettings + * @property {google.api.ICppSettings|null} [cppSettings] ClientLibrarySettings cppSettings + * @property {google.api.IPhpSettings|null} [phpSettings] ClientLibrarySettings phpSettings + * @property {google.api.IPythonSettings|null} [pythonSettings] ClientLibrarySettings pythonSettings + * @property {google.api.INodeSettings|null} [nodeSettings] ClientLibrarySettings nodeSettings + * @property {google.api.IDotnetSettings|null} [dotnetSettings] ClientLibrarySettings dotnetSettings + * @property {google.api.IRubySettings|null} [rubySettings] ClientLibrarySettings rubySettings + * @property {google.api.IGoSettings|null} [goSettings] ClientLibrarySettings goSettings + */ + + /** + * Constructs a new ClientLibrarySettings. + * @memberof google.api + * @classdesc Represents a ClientLibrarySettings. + * @implements IClientLibrarySettings + * @constructor + * @param {google.api.IClientLibrarySettings=} [properties] Properties to set + */ + function ClientLibrarySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ClientLibrarySettings version. + * @member {string} version + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.version = ""; + + /** + * ClientLibrarySettings launchStage. + * @member {google.api.LaunchStage} launchStage + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.launchStage = 0; + + /** + * ClientLibrarySettings restNumericEnums. + * @member {boolean} restNumericEnums + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.restNumericEnums = false; + + /** + * ClientLibrarySettings javaSettings. + * @member {google.api.IJavaSettings|null|undefined} javaSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.javaSettings = null; + + /** + * ClientLibrarySettings cppSettings. + * @member {google.api.ICppSettings|null|undefined} cppSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.cppSettings = null; + + /** + * ClientLibrarySettings phpSettings. + * @member {google.api.IPhpSettings|null|undefined} phpSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.phpSettings = null; + + /** + * ClientLibrarySettings pythonSettings. + * @member {google.api.IPythonSettings|null|undefined} pythonSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.pythonSettings = null; + + /** + * ClientLibrarySettings nodeSettings. + * @member {google.api.INodeSettings|null|undefined} nodeSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.nodeSettings = null; + + /** + * ClientLibrarySettings dotnetSettings. + * @member {google.api.IDotnetSettings|null|undefined} dotnetSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.dotnetSettings = null; + + /** + * ClientLibrarySettings rubySettings. + * @member {google.api.IRubySettings|null|undefined} rubySettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.rubySettings = null; + + /** + * ClientLibrarySettings goSettings. + * @member {google.api.IGoSettings|null|undefined} goSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.goSettings = null; + + /** + * Creates a new ClientLibrarySettings instance using the specified properties. + * @function create + * @memberof google.api.ClientLibrarySettings + * @static + * @param {google.api.IClientLibrarySettings=} [properties] Properties to set + * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings instance + */ + ClientLibrarySettings.create = function create(properties) { + return new ClientLibrarySettings(properties); + }; + + /** + * Encodes the specified ClientLibrarySettings message. Does not implicitly {@link google.api.ClientLibrarySettings.verify|verify} messages. + * @function encode + * @memberof google.api.ClientLibrarySettings + * @static + * @param {google.api.IClientLibrarySettings} message ClientLibrarySettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ClientLibrarySettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.version != null && Object.hasOwnProperty.call(message, "version")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.version); + if (message.launchStage != null && Object.hasOwnProperty.call(message, "launchStage")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.launchStage); + if (message.restNumericEnums != null && Object.hasOwnProperty.call(message, "restNumericEnums")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.restNumericEnums); + if (message.javaSettings != null && Object.hasOwnProperty.call(message, "javaSettings")) + $root.google.api.JavaSettings.encode(message.javaSettings, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.cppSettings != null && Object.hasOwnProperty.call(message, "cppSettings")) + $root.google.api.CppSettings.encode(message.cppSettings, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); + if (message.phpSettings != null && Object.hasOwnProperty.call(message, "phpSettings")) + $root.google.api.PhpSettings.encode(message.phpSettings, writer.uint32(/* id 23, wireType 2 =*/186).fork()).ldelim(); + if (message.pythonSettings != null && Object.hasOwnProperty.call(message, "pythonSettings")) + $root.google.api.PythonSettings.encode(message.pythonSettings, writer.uint32(/* id 24, wireType 2 =*/194).fork()).ldelim(); + if (message.nodeSettings != null && Object.hasOwnProperty.call(message, "nodeSettings")) + $root.google.api.NodeSettings.encode(message.nodeSettings, writer.uint32(/* id 25, wireType 2 =*/202).fork()).ldelim(); + if (message.dotnetSettings != null && Object.hasOwnProperty.call(message, "dotnetSettings")) + $root.google.api.DotnetSettings.encode(message.dotnetSettings, writer.uint32(/* id 26, wireType 2 =*/210).fork()).ldelim(); + if (message.rubySettings != null && Object.hasOwnProperty.call(message, "rubySettings")) + $root.google.api.RubySettings.encode(message.rubySettings, writer.uint32(/* id 27, wireType 2 =*/218).fork()).ldelim(); + if (message.goSettings != null && Object.hasOwnProperty.call(message, "goSettings")) + $root.google.api.GoSettings.encode(message.goSettings, writer.uint32(/* id 28, wireType 2 =*/226).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ClientLibrarySettings message, length delimited. Does not implicitly {@link google.api.ClientLibrarySettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.ClientLibrarySettings + * @static + * @param {google.api.IClientLibrarySettings} message ClientLibrarySettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ClientLibrarySettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ClientLibrarySettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.ClientLibrarySettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings + * @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, 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(); + break; + } + case 2: { + message.launchStage = reader.int32(); + break; + } + case 3: { + message.restNumericEnums = reader.bool(); + break; + } + case 21: { + message.javaSettings = $root.google.api.JavaSettings.decode(reader, reader.uint32()); + break; + } + case 22: { + message.cppSettings = $root.google.api.CppSettings.decode(reader, reader.uint32()); + break; + } + case 23: { + message.phpSettings = $root.google.api.PhpSettings.decode(reader, reader.uint32()); + break; + } + case 24: { + message.pythonSettings = $root.google.api.PythonSettings.decode(reader, reader.uint32()); + break; + } + case 25: { + message.nodeSettings = $root.google.api.NodeSettings.decode(reader, reader.uint32()); + break; + } + case 26: { + message.dotnetSettings = $root.google.api.DotnetSettings.decode(reader, reader.uint32()); + break; + } + case 27: { + message.rubySettings = $root.google.api.RubySettings.decode(reader, reader.uint32()); + break; + } + case 28: { + message.goSettings = $root.google.api.GoSettings.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ClientLibrarySettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.ClientLibrarySettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ClientLibrarySettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ClientLibrarySettings message. + * @function verify + * @memberof google.api.ClientLibrarySettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ClientLibrarySettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.version != null && message.hasOwnProperty("version")) + if (!$util.isString(message.version)) + return "version: string expected"; + if (message.launchStage != null && message.hasOwnProperty("launchStage")) + switch (message.launchStage) { + default: + return "launchStage: enum value expected"; + case 0: + case 6: + case 7: + case 1: + case 2: + case 3: + case 4: + case 5: + break; + } + if (message.restNumericEnums != null && message.hasOwnProperty("restNumericEnums")) + if (typeof message.restNumericEnums !== "boolean") + return "restNumericEnums: boolean expected"; + if (message.javaSettings != null && message.hasOwnProperty("javaSettings")) { + var error = $root.google.api.JavaSettings.verify(message.javaSettings); + if (error) + return "javaSettings." + error; + } + if (message.cppSettings != null && message.hasOwnProperty("cppSettings")) { + var error = $root.google.api.CppSettings.verify(message.cppSettings); + if (error) + return "cppSettings." + error; + } + if (message.phpSettings != null && message.hasOwnProperty("phpSettings")) { + var error = $root.google.api.PhpSettings.verify(message.phpSettings); + if (error) + return "phpSettings." + error; + } + if (message.pythonSettings != null && message.hasOwnProperty("pythonSettings")) { + var error = $root.google.api.PythonSettings.verify(message.pythonSettings); + if (error) + return "pythonSettings." + error; + } + if (message.nodeSettings != null && message.hasOwnProperty("nodeSettings")) { + var error = $root.google.api.NodeSettings.verify(message.nodeSettings); + if (error) + return "nodeSettings." + error; + } + if (message.dotnetSettings != null && message.hasOwnProperty("dotnetSettings")) { + var error = $root.google.api.DotnetSettings.verify(message.dotnetSettings); + if (error) + return "dotnetSettings." + error; + } + if (message.rubySettings != null && message.hasOwnProperty("rubySettings")) { + var error = $root.google.api.RubySettings.verify(message.rubySettings); + if (error) + return "rubySettings." + error; + } + if (message.goSettings != null && message.hasOwnProperty("goSettings")) { + var error = $root.google.api.GoSettings.verify(message.goSettings); + if (error) + return "goSettings." + error; + } + return null; + }; + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings + */ + ClientLibrarySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ClientLibrarySettings) + return object; + var message = new $root.google.api.ClientLibrarySettings(); + if (object.version != null) + message.version = String(object.version); + switch (object.launchStage) { + default: + if (typeof object.launchStage === "number") { + message.launchStage = object.launchStage; + break; + } + break; + case "LAUNCH_STAGE_UNSPECIFIED": + case 0: + message.launchStage = 0; + break; + case "UNIMPLEMENTED": + case 6: + message.launchStage = 6; + break; + case "PRELAUNCH": + case 7: + message.launchStage = 7; + break; + case "EARLY_ACCESS": + case 1: + message.launchStage = 1; + break; + case "ALPHA": + case 2: + message.launchStage = 2; + break; + case "BETA": + case 3: + message.launchStage = 3; + break; + case "GA": + case 4: + message.launchStage = 4; + break; + case "DEPRECATED": + case 5: + message.launchStage = 5; + break; + } + if (object.restNumericEnums != null) + message.restNumericEnums = Boolean(object.restNumericEnums); + if (object.javaSettings != null) { + if (typeof object.javaSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.javaSettings: object expected"); + message.javaSettings = $root.google.api.JavaSettings.fromObject(object.javaSettings); + } + if (object.cppSettings != null) { + if (typeof object.cppSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.cppSettings: object expected"); + message.cppSettings = $root.google.api.CppSettings.fromObject(object.cppSettings); + } + if (object.phpSettings != null) { + if (typeof object.phpSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.phpSettings: object expected"); + message.phpSettings = $root.google.api.PhpSettings.fromObject(object.phpSettings); + } + if (object.pythonSettings != null) { + if (typeof object.pythonSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.pythonSettings: object expected"); + message.pythonSettings = $root.google.api.PythonSettings.fromObject(object.pythonSettings); + } + if (object.nodeSettings != null) { + if (typeof object.nodeSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.nodeSettings: object expected"); + message.nodeSettings = $root.google.api.NodeSettings.fromObject(object.nodeSettings); + } + if (object.dotnetSettings != null) { + if (typeof object.dotnetSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.dotnetSettings: object expected"); + message.dotnetSettings = $root.google.api.DotnetSettings.fromObject(object.dotnetSettings); + } + if (object.rubySettings != null) { + if (typeof object.rubySettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.rubySettings: object expected"); + message.rubySettings = $root.google.api.RubySettings.fromObject(object.rubySettings); + } + if (object.goSettings != null) { + if (typeof object.goSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.goSettings: object expected"); + message.goSettings = $root.google.api.GoSettings.fromObject(object.goSettings); + } + return message; + }; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {google.api.ClientLibrarySettings} message ClientLibrarySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ClientLibrarySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.version = ""; + object.launchStage = options.enums === String ? "LAUNCH_STAGE_UNSPECIFIED" : 0; + object.restNumericEnums = false; + object.javaSettings = null; + object.cppSettings = null; + object.phpSettings = null; + object.pythonSettings = null; + object.nodeSettings = null; + object.dotnetSettings = null; + object.rubySettings = null; + object.goSettings = null; + } + if (message.version != null && message.hasOwnProperty("version")) + object.version = message.version; + if (message.launchStage != null && message.hasOwnProperty("launchStage")) + object.launchStage = options.enums === String ? $root.google.api.LaunchStage[message.launchStage] === undefined ? message.launchStage : $root.google.api.LaunchStage[message.launchStage] : message.launchStage; + if (message.restNumericEnums != null && message.hasOwnProperty("restNumericEnums")) + object.restNumericEnums = message.restNumericEnums; + if (message.javaSettings != null && message.hasOwnProperty("javaSettings")) + object.javaSettings = $root.google.api.JavaSettings.toObject(message.javaSettings, options); + if (message.cppSettings != null && message.hasOwnProperty("cppSettings")) + object.cppSettings = $root.google.api.CppSettings.toObject(message.cppSettings, options); + if (message.phpSettings != null && message.hasOwnProperty("phpSettings")) + object.phpSettings = $root.google.api.PhpSettings.toObject(message.phpSettings, options); + if (message.pythonSettings != null && message.hasOwnProperty("pythonSettings")) + object.pythonSettings = $root.google.api.PythonSettings.toObject(message.pythonSettings, options); + if (message.nodeSettings != null && message.hasOwnProperty("nodeSettings")) + object.nodeSettings = $root.google.api.NodeSettings.toObject(message.nodeSettings, options); + if (message.dotnetSettings != null && message.hasOwnProperty("dotnetSettings")) + object.dotnetSettings = $root.google.api.DotnetSettings.toObject(message.dotnetSettings, options); + if (message.rubySettings != null && message.hasOwnProperty("rubySettings")) + object.rubySettings = $root.google.api.RubySettings.toObject(message.rubySettings, options); + if (message.goSettings != null && message.hasOwnProperty("goSettings")) + object.goSettings = $root.google.api.GoSettings.toObject(message.goSettings, options); + return object; + }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @function toJSON + * @memberof google.api.ClientLibrarySettings + * @instance + * @returns {Object.} JSON object + */ + ClientLibrarySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ClientLibrarySettings + * @function getTypeUrl + * @memberof google.api.ClientLibrarySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ClientLibrarySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ClientLibrarySettings"; + }; + + return ClientLibrarySettings; + })(); + + api.Publishing = (function() { + + /** + * Properties of a Publishing. + * @memberof google.api + * @interface IPublishing + * @property {Array.|null} [methodSettings] Publishing methodSettings + * @property {string|null} [newIssueUri] Publishing newIssueUri + * @property {string|null} [documentationUri] Publishing documentationUri + * @property {string|null} [apiShortName] Publishing apiShortName + * @property {string|null} [githubLabel] Publishing githubLabel + * @property {Array.|null} [codeownerGithubTeams] Publishing codeownerGithubTeams + * @property {string|null} [docTagPrefix] Publishing docTagPrefix + * @property {google.api.ClientLibraryOrganization|null} [organization] Publishing organization + * @property {Array.|null} [librarySettings] Publishing librarySettings + * @property {string|null} [protoReferenceDocumentationUri] Publishing protoReferenceDocumentationUri + * @property {string|null} [restReferenceDocumentationUri] Publishing restReferenceDocumentationUri + */ + + /** + * Constructs a new Publishing. + * @memberof google.api + * @classdesc Represents a Publishing. + * @implements IPublishing + * @constructor + * @param {google.api.IPublishing=} [properties] Properties to set + */ + function Publishing(properties) { + this.methodSettings = []; + this.codeownerGithubTeams = []; + this.librarySettings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Publishing methodSettings. + * @member {Array.} methodSettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.methodSettings = $util.emptyArray; + + /** + * Publishing newIssueUri. + * @member {string} newIssueUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.newIssueUri = ""; + + /** + * Publishing documentationUri. + * @member {string} documentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.documentationUri = ""; + + /** + * Publishing apiShortName. + * @member {string} apiShortName + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.apiShortName = ""; + + /** + * Publishing githubLabel. + * @member {string} githubLabel + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.githubLabel = ""; + + /** + * Publishing codeownerGithubTeams. + * @member {Array.} codeownerGithubTeams + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.codeownerGithubTeams = $util.emptyArray; + + /** + * Publishing docTagPrefix. + * @member {string} docTagPrefix + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.docTagPrefix = ""; + + /** + * Publishing organization. + * @member {google.api.ClientLibraryOrganization} organization + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.organization = 0; + + /** + * Publishing librarySettings. + * @member {Array.} librarySettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.librarySettings = $util.emptyArray; + + /** + * Publishing protoReferenceDocumentationUri. + * @member {string} protoReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.protoReferenceDocumentationUri = ""; + + /** + * Publishing restReferenceDocumentationUri. + * @member {string} restReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.restReferenceDocumentationUri = ""; + + /** + * Creates a new Publishing instance using the specified properties. + * @function create + * @memberof google.api.Publishing + * @static + * @param {google.api.IPublishing=} [properties] Properties to set + * @returns {google.api.Publishing} Publishing instance + */ + Publishing.create = function create(properties) { + return new Publishing(properties); + }; + + /** + * Encodes the specified Publishing message. Does not implicitly {@link google.api.Publishing.verify|verify} messages. + * @function encode + * @memberof google.api.Publishing + * @static + * @param {google.api.IPublishing} message Publishing message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Publishing.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methodSettings != null && message.methodSettings.length) + for (var i = 0; i < message.methodSettings.length; ++i) + $root.google.api.MethodSettings.encode(message.methodSettings[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.newIssueUri != null && Object.hasOwnProperty.call(message, "newIssueUri")) + writer.uint32(/* id 101, wireType 2 =*/810).string(message.newIssueUri); + if (message.documentationUri != null && Object.hasOwnProperty.call(message, "documentationUri")) + writer.uint32(/* id 102, wireType 2 =*/818).string(message.documentationUri); + if (message.apiShortName != null && Object.hasOwnProperty.call(message, "apiShortName")) + writer.uint32(/* id 103, wireType 2 =*/826).string(message.apiShortName); + if (message.githubLabel != null && Object.hasOwnProperty.call(message, "githubLabel")) + writer.uint32(/* id 104, wireType 2 =*/834).string(message.githubLabel); + if (message.codeownerGithubTeams != null && message.codeownerGithubTeams.length) + for (var i = 0; i < message.codeownerGithubTeams.length; ++i) + writer.uint32(/* id 105, wireType 2 =*/842).string(message.codeownerGithubTeams[i]); + if (message.docTagPrefix != null && Object.hasOwnProperty.call(message, "docTagPrefix")) + writer.uint32(/* id 106, wireType 2 =*/850).string(message.docTagPrefix); + if (message.organization != null && Object.hasOwnProperty.call(message, "organization")) + writer.uint32(/* id 107, wireType 0 =*/856).int32(message.organization); + if (message.librarySettings != null && message.librarySettings.length) + for (var i = 0; i < message.librarySettings.length; ++i) + $root.google.api.ClientLibrarySettings.encode(message.librarySettings[i], writer.uint32(/* id 109, wireType 2 =*/874).fork()).ldelim(); + if (message.protoReferenceDocumentationUri != null && Object.hasOwnProperty.call(message, "protoReferenceDocumentationUri")) + writer.uint32(/* id 110, wireType 2 =*/882).string(message.protoReferenceDocumentationUri); + if (message.restReferenceDocumentationUri != null && Object.hasOwnProperty.call(message, "restReferenceDocumentationUri")) + writer.uint32(/* id 111, wireType 2 =*/890).string(message.restReferenceDocumentationUri); + return writer; + }; + + /** + * Encodes the specified Publishing message, length delimited. Does not implicitly {@link google.api.Publishing.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.Publishing + * @static + * @param {google.api.IPublishing} message Publishing message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Publishing.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Publishing message from the specified reader or buffer. + * @function decode + * @memberof google.api.Publishing + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.Publishing} Publishing + * @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, 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)) + message.methodSettings = []; + message.methodSettings.push($root.google.api.MethodSettings.decode(reader, reader.uint32())); + break; + } + case 101: { + message.newIssueUri = reader.string(); + break; + } + case 102: { + message.documentationUri = reader.string(); + break; + } + case 103: { + message.apiShortName = reader.string(); + break; + } + case 104: { + message.githubLabel = reader.string(); + break; + } + case 105: { + if (!(message.codeownerGithubTeams && message.codeownerGithubTeams.length)) + message.codeownerGithubTeams = []; + message.codeownerGithubTeams.push(reader.string()); + break; + } + case 106: { + message.docTagPrefix = reader.string(); + break; + } + case 107: { + message.organization = reader.int32(); + break; + } + case 109: { + if (!(message.librarySettings && message.librarySettings.length)) + message.librarySettings = []; + message.librarySettings.push($root.google.api.ClientLibrarySettings.decode(reader, reader.uint32())); + break; + } + case 110: { + message.protoReferenceDocumentationUri = reader.string(); + break; + } + case 111: { + message.restReferenceDocumentationUri = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Publishing message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.Publishing + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.Publishing} Publishing + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Publishing.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Publishing message. + * @function verify + * @memberof google.api.Publishing + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Publishing.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methodSettings != null && message.hasOwnProperty("methodSettings")) { + if (!Array.isArray(message.methodSettings)) + return "methodSettings: array expected"; + for (var i = 0; i < message.methodSettings.length; ++i) { + var error = $root.google.api.MethodSettings.verify(message.methodSettings[i]); + if (error) + return "methodSettings." + error; + } + } + if (message.newIssueUri != null && message.hasOwnProperty("newIssueUri")) + if (!$util.isString(message.newIssueUri)) + return "newIssueUri: string expected"; + if (message.documentationUri != null && message.hasOwnProperty("documentationUri")) + if (!$util.isString(message.documentationUri)) + return "documentationUri: string expected"; + if (message.apiShortName != null && message.hasOwnProperty("apiShortName")) + if (!$util.isString(message.apiShortName)) + return "apiShortName: string expected"; + if (message.githubLabel != null && message.hasOwnProperty("githubLabel")) + if (!$util.isString(message.githubLabel)) + return "githubLabel: string expected"; + if (message.codeownerGithubTeams != null && message.hasOwnProperty("codeownerGithubTeams")) { + if (!Array.isArray(message.codeownerGithubTeams)) + return "codeownerGithubTeams: array expected"; + for (var i = 0; i < message.codeownerGithubTeams.length; ++i) + if (!$util.isString(message.codeownerGithubTeams[i])) + return "codeownerGithubTeams: string[] expected"; + } + if (message.docTagPrefix != null && message.hasOwnProperty("docTagPrefix")) + if (!$util.isString(message.docTagPrefix)) + return "docTagPrefix: string expected"; + if (message.organization != null && message.hasOwnProperty("organization")) + switch (message.organization) { + default: + return "organization: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + break; + } + if (message.librarySettings != null && message.hasOwnProperty("librarySettings")) { + if (!Array.isArray(message.librarySettings)) + return "librarySettings: array expected"; + for (var i = 0; i < message.librarySettings.length; ++i) { + var error = $root.google.api.ClientLibrarySettings.verify(message.librarySettings[i]); + if (error) + return "librarySettings." + error; + } + } + if (message.protoReferenceDocumentationUri != null && message.hasOwnProperty("protoReferenceDocumentationUri")) + if (!$util.isString(message.protoReferenceDocumentationUri)) + return "protoReferenceDocumentationUri: string expected"; + if (message.restReferenceDocumentationUri != null && message.hasOwnProperty("restReferenceDocumentationUri")) + if (!$util.isString(message.restReferenceDocumentationUri)) + return "restReferenceDocumentationUri: string expected"; + return null; + }; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Publishing + * @static + * @param {Object.} object Plain object + * @returns {google.api.Publishing} Publishing + */ + Publishing.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Publishing) + return object; + var message = new $root.google.api.Publishing(); + if (object.methodSettings) { + if (!Array.isArray(object.methodSettings)) + throw TypeError(".google.api.Publishing.methodSettings: array expected"); + message.methodSettings = []; + for (var i = 0; i < object.methodSettings.length; ++i) { + if (typeof object.methodSettings[i] !== "object") + throw TypeError(".google.api.Publishing.methodSettings: object expected"); + message.methodSettings[i] = $root.google.api.MethodSettings.fromObject(object.methodSettings[i]); + } + } + if (object.newIssueUri != null) + message.newIssueUri = String(object.newIssueUri); + if (object.documentationUri != null) + message.documentationUri = String(object.documentationUri); + if (object.apiShortName != null) + message.apiShortName = String(object.apiShortName); + if (object.githubLabel != null) + message.githubLabel = String(object.githubLabel); + if (object.codeownerGithubTeams) { + if (!Array.isArray(object.codeownerGithubTeams)) + throw TypeError(".google.api.Publishing.codeownerGithubTeams: array expected"); + message.codeownerGithubTeams = []; + for (var i = 0; i < object.codeownerGithubTeams.length; ++i) + message.codeownerGithubTeams[i] = String(object.codeownerGithubTeams[i]); + } + if (object.docTagPrefix != null) + message.docTagPrefix = String(object.docTagPrefix); + switch (object.organization) { + default: + if (typeof object.organization === "number") { + message.organization = object.organization; + break; + } + break; + case "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": + case 0: + message.organization = 0; + break; + case "CLOUD": + case 1: + message.organization = 1; + break; + case "ADS": + case 2: + message.organization = 2; + break; + case "PHOTOS": + case 3: + message.organization = 3; + break; + case "STREET_VIEW": + case 4: + message.organization = 4; + break; + case "SHOPPING": + case 5: + message.organization = 5; + break; + case "GEO": + case 6: + message.organization = 6; + break; + case "GENERATIVE_AI": + case 7: + message.organization = 7; + break; + } + if (object.librarySettings) { + if (!Array.isArray(object.librarySettings)) + throw TypeError(".google.api.Publishing.librarySettings: array expected"); + message.librarySettings = []; + for (var i = 0; i < object.librarySettings.length; ++i) { + if (typeof object.librarySettings[i] !== "object") + throw TypeError(".google.api.Publishing.librarySettings: object expected"); + message.librarySettings[i] = $root.google.api.ClientLibrarySettings.fromObject(object.librarySettings[i]); + } + } + if (object.protoReferenceDocumentationUri != null) + message.protoReferenceDocumentationUri = String(object.protoReferenceDocumentationUri); + if (object.restReferenceDocumentationUri != null) + message.restReferenceDocumentationUri = String(object.restReferenceDocumentationUri); + return message; + }; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Publishing + * @static + * @param {google.api.Publishing} message Publishing + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Publishing.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.methodSettings = []; + object.codeownerGithubTeams = []; + object.librarySettings = []; + } + if (options.defaults) { + object.newIssueUri = ""; + object.documentationUri = ""; + object.apiShortName = ""; + object.githubLabel = ""; + object.docTagPrefix = ""; + object.organization = options.enums === String ? "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED" : 0; + object.protoReferenceDocumentationUri = ""; + object.restReferenceDocumentationUri = ""; + } + if (message.methodSettings && message.methodSettings.length) { + object.methodSettings = []; + for (var j = 0; j < message.methodSettings.length; ++j) + object.methodSettings[j] = $root.google.api.MethodSettings.toObject(message.methodSettings[j], options); + } + if (message.newIssueUri != null && message.hasOwnProperty("newIssueUri")) + object.newIssueUri = message.newIssueUri; + if (message.documentationUri != null && message.hasOwnProperty("documentationUri")) + object.documentationUri = message.documentationUri; + if (message.apiShortName != null && message.hasOwnProperty("apiShortName")) + object.apiShortName = message.apiShortName; + if (message.githubLabel != null && message.hasOwnProperty("githubLabel")) + object.githubLabel = message.githubLabel; + if (message.codeownerGithubTeams && message.codeownerGithubTeams.length) { + object.codeownerGithubTeams = []; + for (var j = 0; j < message.codeownerGithubTeams.length; ++j) + object.codeownerGithubTeams[j] = message.codeownerGithubTeams[j]; + } + if (message.docTagPrefix != null && message.hasOwnProperty("docTagPrefix")) + object.docTagPrefix = message.docTagPrefix; + if (message.organization != null && message.hasOwnProperty("organization")) + object.organization = options.enums === String ? $root.google.api.ClientLibraryOrganization[message.organization] === undefined ? message.organization : $root.google.api.ClientLibraryOrganization[message.organization] : message.organization; + if (message.librarySettings && message.librarySettings.length) { + object.librarySettings = []; + for (var j = 0; j < message.librarySettings.length; ++j) + object.librarySettings[j] = $root.google.api.ClientLibrarySettings.toObject(message.librarySettings[j], options); + } + if (message.protoReferenceDocumentationUri != null && message.hasOwnProperty("protoReferenceDocumentationUri")) + object.protoReferenceDocumentationUri = message.protoReferenceDocumentationUri; + if (message.restReferenceDocumentationUri != null && message.hasOwnProperty("restReferenceDocumentationUri")) + object.restReferenceDocumentationUri = message.restReferenceDocumentationUri; + return object; + }; + + /** + * Converts this Publishing to JSON. + * @function toJSON + * @memberof google.api.Publishing + * @instance + * @returns {Object.} JSON object + */ + Publishing.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Publishing + * @function getTypeUrl + * @memberof google.api.Publishing + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Publishing.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.Publishing"; + }; + + return Publishing; + })(); + + api.JavaSettings = (function() { + + /** + * Properties of a JavaSettings. + * @memberof google.api + * @interface IJavaSettings + * @property {string|null} [libraryPackage] JavaSettings libraryPackage + * @property {Object.|null} [serviceClassNames] JavaSettings serviceClassNames + * @property {google.api.ICommonLanguageSettings|null} [common] JavaSettings common + */ + + /** + * Constructs a new JavaSettings. + * @memberof google.api + * @classdesc Represents a JavaSettings. + * @implements IJavaSettings + * @constructor + * @param {google.api.IJavaSettings=} [properties] Properties to set + */ + function JavaSettings(properties) { + this.serviceClassNames = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * JavaSettings libraryPackage. + * @member {string} libraryPackage + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.libraryPackage = ""; + + /** + * JavaSettings serviceClassNames. + * @member {Object.} serviceClassNames + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.serviceClassNames = $util.emptyObject; + + /** + * JavaSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.common = null; + + /** + * Creates a new JavaSettings instance using the specified properties. + * @function create + * @memberof google.api.JavaSettings + * @static + * @param {google.api.IJavaSettings=} [properties] Properties to set + * @returns {google.api.JavaSettings} JavaSettings instance + */ + JavaSettings.create = function create(properties) { + return new JavaSettings(properties); + }; + + /** + * Encodes the specified JavaSettings message. Does not implicitly {@link google.api.JavaSettings.verify|verify} messages. + * @function encode + * @memberof google.api.JavaSettings + * @static + * @param {google.api.IJavaSettings} message JavaSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + JavaSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.libraryPackage != null && Object.hasOwnProperty.call(message, "libraryPackage")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.libraryPackage); + if (message.serviceClassNames != null && Object.hasOwnProperty.call(message, "serviceClassNames")) + for (var keys = Object.keys(message.serviceClassNames), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.serviceClassNames[keys[i]]).ldelim(); + if (message.common != null && Object.hasOwnProperty.call(message, "common")) + $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified JavaSettings message, length delimited. Does not implicitly {@link google.api.JavaSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.JavaSettings + * @static + * @param {google.api.IJavaSettings} message JavaSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + JavaSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a JavaSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.JavaSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.JavaSettings} JavaSettings + * @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, 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(); + break; + } + case 2: { + if (message.serviceClassNames === $util.emptyObject) + message.serviceClassNames = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.serviceClassNames[key] = value; + break; + } + case 3: { + message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a JavaSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.JavaSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.JavaSettings} JavaSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + JavaSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a JavaSettings message. + * @function verify + * @memberof google.api.JavaSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + JavaSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.libraryPackage != null && message.hasOwnProperty("libraryPackage")) + if (!$util.isString(message.libraryPackage)) + return "libraryPackage: string expected"; + if (message.serviceClassNames != null && message.hasOwnProperty("serviceClassNames")) { + if (!$util.isObject(message.serviceClassNames)) + return "serviceClassNames: object expected"; + var key = Object.keys(message.serviceClassNames); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.serviceClassNames[key[i]])) + return "serviceClassNames: string{k:string} expected"; + } + if (message.common != null && message.hasOwnProperty("common")) { + var error = $root.google.api.CommonLanguageSettings.verify(message.common); + if (error) + return "common." + error; + } + return null; + }; + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.JavaSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.JavaSettings} JavaSettings + */ + JavaSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.JavaSettings) + return object; + var message = new $root.google.api.JavaSettings(); + if (object.libraryPackage != null) + message.libraryPackage = String(object.libraryPackage); + if (object.serviceClassNames) { + if (typeof object.serviceClassNames !== "object") + throw TypeError(".google.api.JavaSettings.serviceClassNames: object expected"); + message.serviceClassNames = {}; + for (var keys = Object.keys(object.serviceClassNames), i = 0; i < keys.length; ++i) + message.serviceClassNames[keys[i]] = String(object.serviceClassNames[keys[i]]); + } + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.JavaSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.JavaSettings + * @static + * @param {google.api.JavaSettings} message JavaSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + JavaSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.serviceClassNames = {}; + if (options.defaults) { + object.libraryPackage = ""; + object.common = null; + } + if (message.libraryPackage != null && message.hasOwnProperty("libraryPackage")) + object.libraryPackage = message.libraryPackage; + var keys2; + if (message.serviceClassNames && (keys2 = Object.keys(message.serviceClassNames)).length) { + object.serviceClassNames = {}; + for (var j = 0; j < keys2.length; ++j) + object.serviceClassNames[keys2[j]] = message.serviceClassNames[keys2[j]]; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this JavaSettings to JSON. + * @function toJSON + * @memberof google.api.JavaSettings + * @instance + * @returns {Object.} JSON object + */ + JavaSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for JavaSettings + * @function getTypeUrl + * @memberof google.api.JavaSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + JavaSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.JavaSettings"; + }; + + return JavaSettings; + })(); + + api.CppSettings = (function() { + + /** + * Properties of a CppSettings. + * @memberof google.api + * @interface ICppSettings + * @property {google.api.ICommonLanguageSettings|null} [common] CppSettings common + */ + + /** + * Constructs a new CppSettings. + * @memberof google.api + * @classdesc Represents a CppSettings. + * @implements ICppSettings + * @constructor + * @param {google.api.ICppSettings=} [properties] Properties to set + */ + function CppSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CppSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.CppSettings + * @instance + */ + CppSettings.prototype.common = null; + + /** + * Creates a new CppSettings instance using the specified properties. + * @function create + * @memberof google.api.CppSettings + * @static + * @param {google.api.ICppSettings=} [properties] Properties to set + * @returns {google.api.CppSettings} CppSettings instance + */ + CppSettings.create = function create(properties) { + return new CppSettings(properties); + }; + + /** + * Encodes the specified CppSettings message. Does not implicitly {@link google.api.CppSettings.verify|verify} messages. + * @function encode + * @memberof google.api.CppSettings + * @static + * @param {google.api.ICppSettings} message CppSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CppSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.common != null && Object.hasOwnProperty.call(message, "common")) + $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CppSettings message, length delimited. Does not implicitly {@link google.api.CppSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.CppSettings + * @static + * @param {google.api.ICppSettings} message CppSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CppSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CppSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.CppSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.CppSettings} CppSettings + * @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, 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()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CppSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.CppSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.CppSettings} CppSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CppSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CppSettings message. + * @function verify + * @memberof google.api.CppSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CppSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.common != null && message.hasOwnProperty("common")) { + var error = $root.google.api.CommonLanguageSettings.verify(message.common); + if (error) + return "common." + error; + } + return null; + }; + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CppSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CppSettings} CppSettings + */ + CppSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CppSettings) + return object; + var message = new $root.google.api.CppSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.CppSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CppSettings + * @static + * @param {google.api.CppSettings} message CppSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CppSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this CppSettings to JSON. + * @function toJSON + * @memberof google.api.CppSettings + * @instance + * @returns {Object.} JSON object + */ + CppSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CppSettings + * @function getTypeUrl + * @memberof google.api.CppSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CppSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CppSettings"; + }; + + return CppSettings; + })(); + + api.PhpSettings = (function() { + + /** + * Properties of a PhpSettings. + * @memberof google.api + * @interface IPhpSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PhpSettings common + */ + + /** + * Constructs a new PhpSettings. + * @memberof google.api + * @classdesc Represents a PhpSettings. + * @implements IPhpSettings + * @constructor + * @param {google.api.IPhpSettings=} [properties] Properties to set + */ + function PhpSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PhpSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PhpSettings + * @instance + */ + PhpSettings.prototype.common = null; + + /** + * Creates a new PhpSettings instance using the specified properties. + * @function create + * @memberof google.api.PhpSettings + * @static + * @param {google.api.IPhpSettings=} [properties] Properties to set + * @returns {google.api.PhpSettings} PhpSettings instance + */ + PhpSettings.create = function create(properties) { + return new PhpSettings(properties); + }; + + /** + * Encodes the specified PhpSettings message. Does not implicitly {@link google.api.PhpSettings.verify|verify} messages. + * @function encode + * @memberof google.api.PhpSettings + * @static + * @param {google.api.IPhpSettings} message PhpSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PhpSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.common != null && Object.hasOwnProperty.call(message, "common")) + $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PhpSettings message, length delimited. Does not implicitly {@link google.api.PhpSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PhpSettings + * @static + * @param {google.api.IPhpSettings} message PhpSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PhpSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PhpSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.PhpSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PhpSettings} PhpSettings + * @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, 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()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PhpSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PhpSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PhpSettings} PhpSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PhpSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PhpSettings message. + * @function verify + * @memberof google.api.PhpSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PhpSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.common != null && message.hasOwnProperty("common")) { + var error = $root.google.api.CommonLanguageSettings.verify(message.common); + if (error) + return "common." + error; + } + return null; + }; + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PhpSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PhpSettings} PhpSettings + */ + PhpSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PhpSettings) + return object; + var message = new $root.google.api.PhpSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PhpSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PhpSettings + * @static + * @param {google.api.PhpSettings} message PhpSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PhpSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this PhpSettings to JSON. + * @function toJSON + * @memberof google.api.PhpSettings + * @instance + * @returns {Object.} JSON object + */ + PhpSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PhpSettings + * @function getTypeUrl + * @memberof google.api.PhpSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PhpSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PhpSettings"; + }; + + return PhpSettings; + })(); + + api.PythonSettings = (function() { + + /** + * Properties of a PythonSettings. + * @memberof google.api + * @interface IPythonSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures + */ + + /** + * Constructs a new PythonSettings. + * @memberof google.api + * @classdesc Represents a PythonSettings. + * @implements IPythonSettings + * @constructor + * @param {google.api.IPythonSettings=} [properties] Properties to set + */ + function PythonSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PythonSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.common = null; + + /** + * PythonSettings experimentalFeatures. + * @member {google.api.PythonSettings.IExperimentalFeatures|null|undefined} experimentalFeatures + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.experimentalFeatures = null; + + /** + * Creates a new PythonSettings instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings + * @static + * @param {google.api.IPythonSettings=} [properties] Properties to set + * @returns {google.api.PythonSettings} PythonSettings instance + */ + PythonSettings.create = function create(properties) { + return new PythonSettings(properties); + }; + + /** + * Encodes the specified PythonSettings message. Does not implicitly {@link google.api.PythonSettings.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings + * @static + * @param {google.api.IPythonSettings} message PythonSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PythonSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.common != null && Object.hasOwnProperty.call(message, "common")) + $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.experimentalFeatures != null && Object.hasOwnProperty.call(message, "experimentalFeatures")) + $root.google.api.PythonSettings.ExperimentalFeatures.encode(message.experimentalFeatures, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PythonSettings message, length delimited. Does not implicitly {@link google.api.PythonSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings + * @static + * @param {google.api.IPythonSettings} message PythonSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PythonSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PythonSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings} PythonSettings + * @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, 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()); + break; + } + case 2: { + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PythonSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings} PythonSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PythonSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PythonSettings message. + * @function verify + * @memberof google.api.PythonSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PythonSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.common != null && message.hasOwnProperty("common")) { + var error = $root.google.api.CommonLanguageSettings.verify(message.common); + if (error) + return "common." + error; + } + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) { + var error = $root.google.api.PythonSettings.ExperimentalFeatures.verify(message.experimentalFeatures); + if (error) + return "experimentalFeatures." + error; + } + return null; + }; + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings} PythonSettings + */ + PythonSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings) + return object; + var message = new $root.google.api.PythonSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PythonSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.experimentalFeatures != null) { + if (typeof object.experimentalFeatures !== "object") + throw TypeError(".google.api.PythonSettings.experimentalFeatures: object expected"); + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.fromObject(object.experimentalFeatures); + } + return message; + }; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings + * @static + * @param {google.api.PythonSettings} message PythonSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PythonSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.common = null; + object.experimentalFeatures = null; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) + object.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.toObject(message.experimentalFeatures, options); + return object; + }; + + /** + * Converts this PythonSettings to JSON. + * @function toJSON + * @memberof google.api.PythonSettings + * @instance + * @returns {Object.} JSON object + */ + PythonSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PythonSettings + * @function getTypeUrl + * @memberof google.api.PythonSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PythonSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings"; + }; + + PythonSettings.ExperimentalFeatures = (function() { + + /** + * Properties of an ExperimentalFeatures. + * @memberof google.api.PythonSettings + * @interface IExperimentalFeatures + * @property {boolean|null} [restAsyncIoEnabled] ExperimentalFeatures restAsyncIoEnabled + * @property {boolean|null} [protobufPythonicTypesEnabled] ExperimentalFeatures protobufPythonicTypesEnabled + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * Constructs a new ExperimentalFeatures. + * @memberof google.api.PythonSettings + * @classdesc Represents an ExperimentalFeatures. + * @implements IExperimentalFeatures + * @constructor + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + */ + function ExperimentalFeatures(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExperimentalFeatures restAsyncIoEnabled. + * @member {boolean} restAsyncIoEnabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.restAsyncIoEnabled = false; + + /** + * ExperimentalFeatures protobufPythonicTypesEnabled. + * @member {boolean} protobufPythonicTypesEnabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.protobufPythonicTypesEnabled = false; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures instance + */ + ExperimentalFeatures.create = function create(properties) { + return new ExperimentalFeatures(properties); + }; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.restAsyncIoEnabled != null && Object.hasOwnProperty.call(message, "restAsyncIoEnabled")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.restAsyncIoEnabled); + if (message.protobufPythonicTypesEnabled != null && Object.hasOwnProperty.call(message, "protobufPythonicTypesEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.protobufPythonicTypesEnabled); + if (message.unversionedPackageDisabled != null && Object.hasOwnProperty.call(message, "unversionedPackageDisabled")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.unversionedPackageDisabled); + return writer; + }; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.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.ExperimentalFeatures(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.restAsyncIoEnabled = reader.bool(); + break; + } + case 2: { + message.protobufPythonicTypesEnabled = reader.bool(); + break; + } + case 3: { + message.unversionedPackageDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExperimentalFeatures message. + * @function verify + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExperimentalFeatures.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + if (typeof message.restAsyncIoEnabled !== "boolean") + return "restAsyncIoEnabled: boolean expected"; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + if (typeof message.protobufPythonicTypesEnabled !== "boolean") + return "protobufPythonicTypesEnabled: boolean expected"; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + if (typeof message.unversionedPackageDisabled !== "boolean") + return "unversionedPackageDisabled: boolean expected"; + return null; + }; + + /** + * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + */ + ExperimentalFeatures.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings.ExperimentalFeatures) + return object; + var message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + if (object.restAsyncIoEnabled != null) + message.restAsyncIoEnabled = Boolean(object.restAsyncIoEnabled); + if (object.protobufPythonicTypesEnabled != null) + message.protobufPythonicTypesEnabled = Boolean(object.protobufPythonicTypesEnabled); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + return message; + }; + + /** + * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.ExperimentalFeatures} message ExperimentalFeatures + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExperimentalFeatures.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.restAsyncIoEnabled = false; + object.protobufPythonicTypesEnabled = false; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + return object; + }; + + /** + * Converts this ExperimentalFeatures to JSON. + * @function toJSON + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + * @returns {Object.} JSON object + */ + ExperimentalFeatures.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExperimentalFeatures + * @function getTypeUrl + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExperimentalFeatures.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings.ExperimentalFeatures"; + }; + + return ExperimentalFeatures; + })(); + + return PythonSettings; + })(); + + api.NodeSettings = (function() { + + /** + * Properties of a NodeSettings. + * @memberof google.api + * @interface INodeSettings + * @property {google.api.ICommonLanguageSettings|null} [common] NodeSettings common + */ + + /** + * Constructs a new NodeSettings. + * @memberof google.api + * @classdesc Represents a NodeSettings. + * @implements INodeSettings + * @constructor + * @param {google.api.INodeSettings=} [properties] Properties to set + */ + function NodeSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NodeSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.NodeSettings + * @instance + */ + NodeSettings.prototype.common = null; + + /** + * Creates a new NodeSettings instance using the specified properties. + * @function create + * @memberof google.api.NodeSettings + * @static + * @param {google.api.INodeSettings=} [properties] Properties to set + * @returns {google.api.NodeSettings} NodeSettings instance + */ + NodeSettings.create = function create(properties) { + return new NodeSettings(properties); + }; + + /** + * Encodes the specified NodeSettings message. Does not implicitly {@link google.api.NodeSettings.verify|verify} messages. + * @function encode + * @memberof google.api.NodeSettings + * @static + * @param {google.api.INodeSettings} message NodeSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NodeSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.common != null && Object.hasOwnProperty.call(message, "common")) + $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified NodeSettings message, length delimited. Does not implicitly {@link google.api.NodeSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.NodeSettings + * @static + * @param {google.api.INodeSettings} message NodeSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NodeSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a NodeSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.NodeSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.NodeSettings} NodeSettings + * @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, 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()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a NodeSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.NodeSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.NodeSettings} NodeSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NodeSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a NodeSettings message. + * @function verify + * @memberof google.api.NodeSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + NodeSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.common != null && message.hasOwnProperty("common")) { + var error = $root.google.api.CommonLanguageSettings.verify(message.common); + if (error) + return "common." + error; + } + return null; + }; + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.NodeSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.NodeSettings} NodeSettings + */ + NodeSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.NodeSettings) + return object; + var message = new $root.google.api.NodeSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.NodeSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.NodeSettings + * @static + * @param {google.api.NodeSettings} message NodeSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NodeSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this NodeSettings to JSON. + * @function toJSON + * @memberof google.api.NodeSettings + * @instance + * @returns {Object.} JSON object + */ + NodeSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NodeSettings + * @function getTypeUrl + * @memberof google.api.NodeSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NodeSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.NodeSettings"; + }; + + return NodeSettings; + })(); + + api.DotnetSettings = (function() { + + /** + * Properties of a DotnetSettings. + * @memberof google.api + * @interface IDotnetSettings + * @property {google.api.ICommonLanguageSettings|null} [common] DotnetSettings common + * @property {Object.|null} [renamedServices] DotnetSettings renamedServices + * @property {Object.|null} [renamedResources] DotnetSettings renamedResources + * @property {Array.|null} [ignoredResources] DotnetSettings ignoredResources + * @property {Array.|null} [forcedNamespaceAliases] DotnetSettings forcedNamespaceAliases + * @property {Array.|null} [handwrittenSignatures] DotnetSettings handwrittenSignatures + */ + + /** + * Constructs a new DotnetSettings. + * @memberof google.api + * @classdesc Represents a DotnetSettings. + * @implements IDotnetSettings + * @constructor + * @param {google.api.IDotnetSettings=} [properties] Properties to set + */ + function DotnetSettings(properties) { + this.renamedServices = {}; + this.renamedResources = {}; + this.ignoredResources = []; + this.forcedNamespaceAliases = []; + this.handwrittenSignatures = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DotnetSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.common = null; + + /** + * DotnetSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedServices = $util.emptyObject; + + /** + * DotnetSettings renamedResources. + * @member {Object.} renamedResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedResources = $util.emptyObject; + + /** + * DotnetSettings ignoredResources. + * @member {Array.} ignoredResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.ignoredResources = $util.emptyArray; + + /** + * DotnetSettings forcedNamespaceAliases. + * @member {Array.} forcedNamespaceAliases + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.forcedNamespaceAliases = $util.emptyArray; + + /** + * DotnetSettings handwrittenSignatures. + * @member {Array.} handwrittenSignatures + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.handwrittenSignatures = $util.emptyArray; + + /** + * Creates a new DotnetSettings instance using the specified properties. + * @function create + * @memberof google.api.DotnetSettings + * @static + * @param {google.api.IDotnetSettings=} [properties] Properties to set + * @returns {google.api.DotnetSettings} DotnetSettings instance + */ + DotnetSettings.create = function create(properties) { + return new DotnetSettings(properties); + }; + + /** + * Encodes the specified DotnetSettings message. Does not implicitly {@link google.api.DotnetSettings.verify|verify} messages. + * @function encode + * @memberof google.api.DotnetSettings + * @static + * @param {google.api.IDotnetSettings} message DotnetSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DotnetSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.common != null && Object.hasOwnProperty.call(message, "common")) + $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); + if (message.renamedResources != null && Object.hasOwnProperty.call(message, "renamedResources")) + for (var keys = Object.keys(message.renamedResources), i = 0; i < keys.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedResources[keys[i]]).ldelim(); + if (message.ignoredResources != null && message.ignoredResources.length) + for (var i = 0; i < message.ignoredResources.length; ++i) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.ignoredResources[i]); + if (message.forcedNamespaceAliases != null && message.forcedNamespaceAliases.length) + for (var i = 0; i < message.forcedNamespaceAliases.length; ++i) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.forcedNamespaceAliases[i]); + if (message.handwrittenSignatures != null && message.handwrittenSignatures.length) + for (var i = 0; i < message.handwrittenSignatures.length; ++i) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.handwrittenSignatures[i]); + return writer; + }; + + /** + * Encodes the specified DotnetSettings message, length delimited. Does not implicitly {@link google.api.DotnetSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.DotnetSettings + * @static + * @param {google.api.IDotnetSettings} message DotnetSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DotnetSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DotnetSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.DotnetSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.DotnetSettings} DotnetSettings + * @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, 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()); + break; + } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } + case 3: { + if (message.renamedResources === $util.emptyObject) + message.renamedResources = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedResources[key] = value; + break; + } + case 4: { + if (!(message.ignoredResources && message.ignoredResources.length)) + message.ignoredResources = []; + message.ignoredResources.push(reader.string()); + break; + } + case 5: { + if (!(message.forcedNamespaceAliases && message.forcedNamespaceAliases.length)) + message.forcedNamespaceAliases = []; + message.forcedNamespaceAliases.push(reader.string()); + break; + } + case 6: { + if (!(message.handwrittenSignatures && message.handwrittenSignatures.length)) + message.handwrittenSignatures = []; + message.handwrittenSignatures.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DotnetSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.DotnetSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.DotnetSettings} DotnetSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DotnetSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DotnetSettings message. + * @function verify + * @memberof google.api.DotnetSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DotnetSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.common != null && message.hasOwnProperty("common")) { + var error = $root.google.api.CommonLanguageSettings.verify(message.common); + if (error) + return "common." + error; + } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } + if (message.renamedResources != null && message.hasOwnProperty("renamedResources")) { + if (!$util.isObject(message.renamedResources)) + return "renamedResources: object expected"; + var key = Object.keys(message.renamedResources); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedResources[key[i]])) + return "renamedResources: string{k:string} expected"; + } + if (message.ignoredResources != null && message.hasOwnProperty("ignoredResources")) { + if (!Array.isArray(message.ignoredResources)) + return "ignoredResources: array expected"; + for (var i = 0; i < message.ignoredResources.length; ++i) + if (!$util.isString(message.ignoredResources[i])) + return "ignoredResources: string[] expected"; + } + if (message.forcedNamespaceAliases != null && message.hasOwnProperty("forcedNamespaceAliases")) { + if (!Array.isArray(message.forcedNamespaceAliases)) + return "forcedNamespaceAliases: array expected"; + for (var i = 0; i < message.forcedNamespaceAliases.length; ++i) + if (!$util.isString(message.forcedNamespaceAliases[i])) + return "forcedNamespaceAliases: string[] expected"; + } + if (message.handwrittenSignatures != null && message.hasOwnProperty("handwrittenSignatures")) { + if (!Array.isArray(message.handwrittenSignatures)) + return "handwrittenSignatures: array expected"; + for (var i = 0; i < message.handwrittenSignatures.length; ++i) + if (!$util.isString(message.handwrittenSignatures[i])) + return "handwrittenSignatures: string[] expected"; + } + return null; + }; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.DotnetSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.DotnetSettings} DotnetSettings + */ + DotnetSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.DotnetSettings) + return object; + var message = new $root.google.api.DotnetSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.DotnetSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.DotnetSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + if (object.renamedResources) { + if (typeof object.renamedResources !== "object") + throw TypeError(".google.api.DotnetSettings.renamedResources: object expected"); + message.renamedResources = {}; + for (var keys = Object.keys(object.renamedResources), i = 0; i < keys.length; ++i) + message.renamedResources[keys[i]] = String(object.renamedResources[keys[i]]); + } + if (object.ignoredResources) { + if (!Array.isArray(object.ignoredResources)) + throw TypeError(".google.api.DotnetSettings.ignoredResources: array expected"); + message.ignoredResources = []; + for (var i = 0; i < object.ignoredResources.length; ++i) + message.ignoredResources[i] = String(object.ignoredResources[i]); + } + if (object.forcedNamespaceAliases) { + if (!Array.isArray(object.forcedNamespaceAliases)) + throw TypeError(".google.api.DotnetSettings.forcedNamespaceAliases: array expected"); + message.forcedNamespaceAliases = []; + for (var i = 0; i < object.forcedNamespaceAliases.length; ++i) + message.forcedNamespaceAliases[i] = String(object.forcedNamespaceAliases[i]); + } + if (object.handwrittenSignatures) { + if (!Array.isArray(object.handwrittenSignatures)) + throw TypeError(".google.api.DotnetSettings.handwrittenSignatures: array expected"); + message.handwrittenSignatures = []; + for (var i = 0; i < object.handwrittenSignatures.length; ++i) + message.handwrittenSignatures[i] = String(object.handwrittenSignatures[i]); + } + return message; + }; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.DotnetSettings + * @static + * @param {google.api.DotnetSettings} message DotnetSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DotnetSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.ignoredResources = []; + object.forcedNamespaceAliases = []; + object.handwrittenSignatures = []; + } + if (options.objects || options.defaults) { + object.renamedServices = {}; + object.renamedResources = {}; + } + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + if (message.renamedResources && (keys2 = Object.keys(message.renamedResources)).length) { + object.renamedResources = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedResources[keys2[j]] = message.renamedResources[keys2[j]]; + } + if (message.ignoredResources && message.ignoredResources.length) { + object.ignoredResources = []; + for (var j = 0; j < message.ignoredResources.length; ++j) + object.ignoredResources[j] = message.ignoredResources[j]; + } + if (message.forcedNamespaceAliases && message.forcedNamespaceAliases.length) { + object.forcedNamespaceAliases = []; + for (var j = 0; j < message.forcedNamespaceAliases.length; ++j) + object.forcedNamespaceAliases[j] = message.forcedNamespaceAliases[j]; + } + if (message.handwrittenSignatures && message.handwrittenSignatures.length) { + object.handwrittenSignatures = []; + for (var j = 0; j < message.handwrittenSignatures.length; ++j) + object.handwrittenSignatures[j] = message.handwrittenSignatures[j]; + } + return object; + }; + + /** + * Converts this DotnetSettings to JSON. + * @function toJSON + * @memberof google.api.DotnetSettings + * @instance + * @returns {Object.} JSON object + */ + DotnetSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DotnetSettings + * @function getTypeUrl + * @memberof google.api.DotnetSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DotnetSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.DotnetSettings"; + }; + + return DotnetSettings; + })(); + + api.RubySettings = (function() { + + /** + * Properties of a RubySettings. + * @memberof google.api + * @interface IRubySettings + * @property {google.api.ICommonLanguageSettings|null} [common] RubySettings common + */ + + /** + * Constructs a new RubySettings. + * @memberof google.api + * @classdesc Represents a RubySettings. + * @implements IRubySettings + * @constructor + * @param {google.api.IRubySettings=} [properties] Properties to set + */ + function RubySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RubySettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.RubySettings + * @instance + */ + RubySettings.prototype.common = null; + + /** + * Creates a new RubySettings instance using the specified properties. + * @function create + * @memberof google.api.RubySettings + * @static + * @param {google.api.IRubySettings=} [properties] Properties to set + * @returns {google.api.RubySettings} RubySettings instance + */ + RubySettings.create = function create(properties) { + return new RubySettings(properties); + }; + + /** + * Encodes the specified RubySettings message. Does not implicitly {@link google.api.RubySettings.verify|verify} messages. + * @function encode + * @memberof google.api.RubySettings + * @static + * @param {google.api.IRubySettings} message RubySettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RubySettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.common != null && Object.hasOwnProperty.call(message, "common")) + $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RubySettings message, length delimited. Does not implicitly {@link google.api.RubySettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.RubySettings + * @static + * @param {google.api.IRubySettings} message RubySettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RubySettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RubySettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.RubySettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.RubySettings} RubySettings + * @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, 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()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RubySettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.RubySettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.RubySettings} RubySettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RubySettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RubySettings message. + * @function verify + * @memberof google.api.RubySettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RubySettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.common != null && message.hasOwnProperty("common")) { + var error = $root.google.api.CommonLanguageSettings.verify(message.common); + if (error) + return "common." + error; + } + return null; + }; + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RubySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.RubySettings} RubySettings + */ + RubySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RubySettings) + return object; + var message = new $root.google.api.RubySettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.RubySettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RubySettings + * @static + * @param {google.api.RubySettings} message RubySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RubySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; + + /** + * Converts this RubySettings to JSON. + * @function toJSON + * @memberof google.api.RubySettings + * @instance + * @returns {Object.} JSON object + */ + RubySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RubySettings + * @function getTypeUrl + * @memberof google.api.RubySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RubySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RubySettings"; + }; + + return RubySettings; + })(); + + api.GoSettings = (function() { + + /** + * Properties of a GoSettings. + * @memberof google.api + * @interface IGoSettings + * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices + */ + + /** + * Constructs a new GoSettings. + * @memberof google.api + * @classdesc Represents a GoSettings. + * @implements IGoSettings + * @constructor + * @param {google.api.IGoSettings=} [properties] Properties to set + */ + function GoSettings(properties) { + this.renamedServices = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GoSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.common = null; + + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + + /** + * Creates a new GoSettings instance using the specified properties. + * @function create + * @memberof google.api.GoSettings + * @static + * @param {google.api.IGoSettings=} [properties] Properties to set + * @returns {google.api.GoSettings} GoSettings instance + */ + GoSettings.create = function create(properties) { + return new GoSettings(properties); + }; + + /** + * Encodes the specified GoSettings message. Does not implicitly {@link google.api.GoSettings.verify|verify} messages. + * @function encode + * @memberof google.api.GoSettings + * @static + * @param {google.api.IGoSettings} message GoSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GoSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.common != null && Object.hasOwnProperty.call(message, "common")) + $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified GoSettings message, length delimited. Does not implicitly {@link google.api.GoSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.GoSettings + * @static + * @param {google.api.IGoSettings} message GoSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GoSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GoSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.GoSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.GoSettings} GoSettings + * @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, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(), 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()); + break; + } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GoSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.GoSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.GoSettings} GoSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GoSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GoSettings message. + * @function verify + * @memberof google.api.GoSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GoSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.common != null && message.hasOwnProperty("common")) { + var error = $root.google.api.CommonLanguageSettings.verify(message.common); + if (error) + return "common." + error; + } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } + return null; + }; + + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.GoSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.GoSettings} GoSettings + */ + GoSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.GoSettings) + return object; + var message = new $root.google.api.GoSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.GoSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.GoSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.GoSettings + * @static + * @param {google.api.GoSettings} message GoSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GoSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.renamedServices = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + return object; + }; + + /** + * Converts this GoSettings to JSON. + * @function toJSON + * @memberof google.api.GoSettings + * @instance + * @returns {Object.} JSON object + */ + GoSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GoSettings + * @function getTypeUrl + * @memberof google.api.GoSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GoSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.GoSettings"; + }; + + return GoSettings; + })(); + + api.MethodSettings = (function() { + + /** + * Properties of a MethodSettings. + * @memberof google.api + * @interface IMethodSettings + * @property {string|null} [selector] MethodSettings selector + * @property {google.api.MethodSettings.ILongRunning|null} [longRunning] MethodSettings longRunning + * @property {Array.|null} [autoPopulatedFields] MethodSettings autoPopulatedFields + */ + + /** + * Constructs a new MethodSettings. + * @memberof google.api + * @classdesc Represents a MethodSettings. + * @implements IMethodSettings + * @constructor + * @param {google.api.IMethodSettings=} [properties] Properties to set + */ + function MethodSettings(properties) { + this.autoPopulatedFields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MethodSettings selector. + * @member {string} selector + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.selector = ""; + + /** + * MethodSettings longRunning. + * @member {google.api.MethodSettings.ILongRunning|null|undefined} longRunning + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.longRunning = null; + + /** + * MethodSettings autoPopulatedFields. + * @member {Array.} autoPopulatedFields + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.autoPopulatedFields = $util.emptyArray; + + /** + * Creates a new MethodSettings instance using the specified properties. + * @function create + * @memberof google.api.MethodSettings + * @static + * @param {google.api.IMethodSettings=} [properties] Properties to set + * @returns {google.api.MethodSettings} MethodSettings instance + */ + MethodSettings.create = function create(properties) { + return new MethodSettings(properties); + }; + + /** + * Encodes the specified MethodSettings message. Does not implicitly {@link google.api.MethodSettings.verify|verify} messages. + * @function encode + * @memberof google.api.MethodSettings + * @static + * @param {google.api.IMethodSettings} message MethodSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MethodSettings.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.selector != null && Object.hasOwnProperty.call(message, "selector")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.selector); + if (message.longRunning != null && Object.hasOwnProperty.call(message, "longRunning")) + $root.google.api.MethodSettings.LongRunning.encode(message.longRunning, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.autoPopulatedFields != null && message.autoPopulatedFields.length) + for (var i = 0; i < message.autoPopulatedFields.length; ++i) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.autoPopulatedFields[i]); + return writer; + }; + + /** + * Encodes the specified MethodSettings message, length delimited. Does not implicitly {@link google.api.MethodSettings.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.MethodSettings + * @static + * @param {google.api.IMethodSettings} message MethodSettings message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MethodSettings.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MethodSettings message from the specified reader or buffer. + * @function decode + * @memberof google.api.MethodSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.MethodSettings} MethodSettings + * @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, 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(); + break; + } + case 2: { + message.longRunning = $root.google.api.MethodSettings.LongRunning.decode(reader, reader.uint32()); + break; + } + case 3: { + if (!(message.autoPopulatedFields && message.autoPopulatedFields.length)) + message.autoPopulatedFields = []; + message.autoPopulatedFields.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MethodSettings message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.MethodSettings + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.MethodSettings} MethodSettings + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MethodSettings.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MethodSettings message. + * @function verify + * @memberof google.api.MethodSettings + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MethodSettings.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.selector != null && message.hasOwnProperty("selector")) + if (!$util.isString(message.selector)) + return "selector: string expected"; + if (message.longRunning != null && message.hasOwnProperty("longRunning")) { + var error = $root.google.api.MethodSettings.LongRunning.verify(message.longRunning); + if (error) + return "longRunning." + error; + } + if (message.autoPopulatedFields != null && message.hasOwnProperty("autoPopulatedFields")) { + if (!Array.isArray(message.autoPopulatedFields)) + return "autoPopulatedFields: array expected"; + for (var i = 0; i < message.autoPopulatedFields.length; ++i) + if (!$util.isString(message.autoPopulatedFields[i])) + return "autoPopulatedFields: string[] expected"; + } + return null; + }; + + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings} MethodSettings + */ + MethodSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings) + return object; + var message = new $root.google.api.MethodSettings(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.longRunning != null) { + if (typeof object.longRunning !== "object") + throw TypeError(".google.api.MethodSettings.longRunning: object expected"); + message.longRunning = $root.google.api.MethodSettings.LongRunning.fromObject(object.longRunning); + } + if (object.autoPopulatedFields) { + if (!Array.isArray(object.autoPopulatedFields)) + throw TypeError(".google.api.MethodSettings.autoPopulatedFields: array expected"); + message.autoPopulatedFields = []; + for (var i = 0; i < object.autoPopulatedFields.length; ++i) + message.autoPopulatedFields[i] = String(object.autoPopulatedFields[i]); + } + return message; + }; + + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings + * @static + * @param {google.api.MethodSettings} message MethodSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.autoPopulatedFields = []; + if (options.defaults) { + object.selector = ""; + object.longRunning = null; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.longRunning != null && message.hasOwnProperty("longRunning")) + object.longRunning = $root.google.api.MethodSettings.LongRunning.toObject(message.longRunning, options); + if (message.autoPopulatedFields && message.autoPopulatedFields.length) { + object.autoPopulatedFields = []; + for (var j = 0; j < message.autoPopulatedFields.length; ++j) + object.autoPopulatedFields[j] = message.autoPopulatedFields[j]; + } + return object; + }; + + /** + * Converts this MethodSettings to JSON. + * @function toJSON + * @memberof google.api.MethodSettings + * @instance + * @returns {Object.} JSON object + */ + MethodSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MethodSettings + * @function getTypeUrl + * @memberof google.api.MethodSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings"; + }; + + MethodSettings.LongRunning = (function() { + + /** + * Properties of a LongRunning. + * @memberof google.api.MethodSettings + * @interface ILongRunning + * @property {google.protobuf.IDuration|null} [initialPollDelay] LongRunning initialPollDelay + * @property {number|null} [pollDelayMultiplier] LongRunning pollDelayMultiplier + * @property {google.protobuf.IDuration|null} [maxPollDelay] LongRunning maxPollDelay + * @property {google.protobuf.IDuration|null} [totalPollTimeout] LongRunning totalPollTimeout + */ + + /** + * Constructs a new LongRunning. + * @memberof google.api.MethodSettings + * @classdesc Represents a LongRunning. + * @implements ILongRunning + * @constructor + * @param {google.api.MethodSettings.ILongRunning=} [properties] Properties to set + */ + function LongRunning(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LongRunning initialPollDelay. + * @member {google.protobuf.IDuration|null|undefined} initialPollDelay + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.initialPollDelay = null; + + /** + * LongRunning pollDelayMultiplier. + * @member {number} pollDelayMultiplier + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.pollDelayMultiplier = 0; + + /** + * LongRunning maxPollDelay. + * @member {google.protobuf.IDuration|null|undefined} maxPollDelay + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.maxPollDelay = null; + + /** + * LongRunning totalPollTimeout. + * @member {google.protobuf.IDuration|null|undefined} totalPollTimeout + * @memberof google.api.MethodSettings.LongRunning + * @instance + */ + LongRunning.prototype.totalPollTimeout = null; + + /** + * Creates a new LongRunning instance using the specified properties. + * @function create + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {google.api.MethodSettings.ILongRunning=} [properties] Properties to set + * @returns {google.api.MethodSettings.LongRunning} LongRunning instance + */ + LongRunning.create = function create(properties) { + return new LongRunning(properties); + }; + + /** + * Encodes the specified LongRunning message. Does not implicitly {@link google.api.MethodSettings.LongRunning.verify|verify} messages. + * @function encode + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {google.api.MethodSettings.ILongRunning} message LongRunning message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LongRunning.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.initialPollDelay != null && Object.hasOwnProperty.call(message, "initialPollDelay")) + $root.google.protobuf.Duration.encode(message.initialPollDelay, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.pollDelayMultiplier != null && Object.hasOwnProperty.call(message, "pollDelayMultiplier")) + writer.uint32(/* id 2, wireType 5 =*/21).float(message.pollDelayMultiplier); + if (message.maxPollDelay != null && Object.hasOwnProperty.call(message, "maxPollDelay")) + $root.google.protobuf.Duration.encode(message.maxPollDelay, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.totalPollTimeout != null && Object.hasOwnProperty.call(message, "totalPollTimeout")) + $root.google.protobuf.Duration.encode(message.totalPollTimeout, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified LongRunning message, length delimited. Does not implicitly {@link google.api.MethodSettings.LongRunning.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {google.api.MethodSettings.ILongRunning} message LongRunning message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LongRunning.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a LongRunning message from the specified reader or buffer. + * @function decode + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.MethodSettings.LongRunning} LongRunning + * @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, 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()); + break; + } + case 2: { + message.pollDelayMultiplier = reader.float(); + break; + } + case 3: { + message.maxPollDelay = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + case 4: { + message.totalPollTimeout = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a LongRunning message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.MethodSettings.LongRunning} LongRunning + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LongRunning.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a LongRunning message. + * @function verify + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + LongRunning.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.initialPollDelay != null && message.hasOwnProperty("initialPollDelay")) { + var error = $root.google.protobuf.Duration.verify(message.initialPollDelay); + if (error) + return "initialPollDelay." + error; + } + if (message.pollDelayMultiplier != null && message.hasOwnProperty("pollDelayMultiplier")) + if (typeof message.pollDelayMultiplier !== "number") + return "pollDelayMultiplier: number expected"; + if (message.maxPollDelay != null && message.hasOwnProperty("maxPollDelay")) { + var error = $root.google.protobuf.Duration.verify(message.maxPollDelay); + if (error) + return "maxPollDelay." + error; + } + if (message.totalPollTimeout != null && message.hasOwnProperty("totalPollTimeout")) { + var error = $root.google.protobuf.Duration.verify(message.totalPollTimeout); + if (error) + return "totalPollTimeout." + error; + } + return null; + }; + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings.LongRunning} LongRunning + */ + LongRunning.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings.LongRunning) + return object; + var message = new $root.google.api.MethodSettings.LongRunning(); + if (object.initialPollDelay != null) { + if (typeof object.initialPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.initialPollDelay: object expected"); + message.initialPollDelay = $root.google.protobuf.Duration.fromObject(object.initialPollDelay); + } + if (object.pollDelayMultiplier != null) + message.pollDelayMultiplier = Number(object.pollDelayMultiplier); + if (object.maxPollDelay != null) { + if (typeof object.maxPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.maxPollDelay: object expected"); + message.maxPollDelay = $root.google.protobuf.Duration.fromObject(object.maxPollDelay); + } + if (object.totalPollTimeout != null) { + if (typeof object.totalPollTimeout !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.totalPollTimeout: object expected"); + message.totalPollTimeout = $root.google.protobuf.Duration.fromObject(object.totalPollTimeout); + } + return message; + }; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {google.api.MethodSettings.LongRunning} message LongRunning + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LongRunning.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.initialPollDelay = null; + object.pollDelayMultiplier = 0; + object.maxPollDelay = null; + object.totalPollTimeout = null; + } + if (message.initialPollDelay != null && message.hasOwnProperty("initialPollDelay")) + object.initialPollDelay = $root.google.protobuf.Duration.toObject(message.initialPollDelay, options); + if (message.pollDelayMultiplier != null && message.hasOwnProperty("pollDelayMultiplier")) + object.pollDelayMultiplier = options.json && !isFinite(message.pollDelayMultiplier) ? String(message.pollDelayMultiplier) : message.pollDelayMultiplier; + if (message.maxPollDelay != null && message.hasOwnProperty("maxPollDelay")) + object.maxPollDelay = $root.google.protobuf.Duration.toObject(message.maxPollDelay, options); + if (message.totalPollTimeout != null && message.hasOwnProperty("totalPollTimeout")) + object.totalPollTimeout = $root.google.protobuf.Duration.toObject(message.totalPollTimeout, options); + return object; + }; + + /** + * Converts this LongRunning to JSON. + * @function toJSON + * @memberof google.api.MethodSettings.LongRunning + * @instance + * @returns {Object.} JSON object + */ + LongRunning.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LongRunning + * @function getTypeUrl + * @memberof google.api.MethodSettings.LongRunning + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LongRunning.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings.LongRunning"; + }; + + return LongRunning; + })(); + + return MethodSettings; + })(); + + /** + * ClientLibraryOrganization enum. + * @name google.api.ClientLibraryOrganization + * @enum {number} + * @property {number} CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED=0 CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED value + * @property {number} CLOUD=1 CLOUD value + * @property {number} ADS=2 ADS value + * @property {number} PHOTOS=3 PHOTOS value + * @property {number} STREET_VIEW=4 STREET_VIEW value + * @property {number} SHOPPING=5 SHOPPING value + * @property {number} GEO=6 GEO value + * @property {number} GENERATIVE_AI=7 GENERATIVE_AI value + */ + api.ClientLibraryOrganization = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"] = 0; + values[valuesById[1] = "CLOUD"] = 1; + values[valuesById[2] = "ADS"] = 2; + values[valuesById[3] = "PHOTOS"] = 3; + values[valuesById[4] = "STREET_VIEW"] = 4; + values[valuesById[5] = "SHOPPING"] = 5; + values[valuesById[6] = "GEO"] = 6; + values[valuesById[7] = "GENERATIVE_AI"] = 7; + return values; + })(); + + /** + * ClientLibraryDestination enum. + * @name google.api.ClientLibraryDestination + * @enum {number} + * @property {number} CLIENT_LIBRARY_DESTINATION_UNSPECIFIED=0 CLIENT_LIBRARY_DESTINATION_UNSPECIFIED value + * @property {number} GITHUB=10 GITHUB value + * @property {number} PACKAGE_MANAGER=20 PACKAGE_MANAGER value + */ + api.ClientLibraryDestination = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"] = 0; + values[valuesById[10] = "GITHUB"] = 10; + values[valuesById[20] = "PACKAGE_MANAGER"] = 20; + return values; + })(); + + api.SelectiveGapicGeneration = (function() { + + /** + * Properties of a SelectiveGapicGeneration. + * @memberof google.api + * @interface ISelectiveGapicGeneration + * @property {Array.|null} [methods] SelectiveGapicGeneration methods + * @property {boolean|null} [generateOmittedAsInternal] SelectiveGapicGeneration generateOmittedAsInternal + */ + + /** + * Constructs a new SelectiveGapicGeneration. + * @memberof google.api + * @classdesc Represents a SelectiveGapicGeneration. + * @implements ISelectiveGapicGeneration + * @constructor + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + */ + function SelectiveGapicGeneration(properties) { + this.methods = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SelectiveGapicGeneration methods. + * @member {Array.} methods + * @memberof google.api.SelectiveGapicGeneration + * @instance + */ + SelectiveGapicGeneration.prototype.methods = $util.emptyArray; + + /** + * SelectiveGapicGeneration generateOmittedAsInternal. + * @member {boolean} generateOmittedAsInternal + * @memberof google.api.SelectiveGapicGeneration + * @instance + */ + SelectiveGapicGeneration.prototype.generateOmittedAsInternal = false; + + /** + * Creates a new SelectiveGapicGeneration instance using the specified properties. + * @function create + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration instance + */ + SelectiveGapicGeneration.create = function create(properties) { + return new SelectiveGapicGeneration(properties); + }; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methods != null && message.methods.length) + for (var i = 0; i < message.methods.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.methods[i]); + if (message.generateOmittedAsInternal != null && Object.hasOwnProperty.call(message, "generateOmittedAsInternal")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.generateOmittedAsInternal); + return writer; + }; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @function decode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.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.SelectiveGapicGeneration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.methods && message.methods.length)) + message.methods = []; + message.methods.push(reader.string()); + break; + } + case 2: { + message.generateOmittedAsInternal = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SelectiveGapicGeneration message. + * @function verify + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SelectiveGapicGeneration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methods != null && message.hasOwnProperty("methods")) { + if (!Array.isArray(message.methods)) + return "methods: array expected"; + for (var i = 0; i < message.methods.length; ++i) + if (!$util.isString(message.methods[i])) + return "methods: string[] expected"; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + if (typeof message.generateOmittedAsInternal !== "boolean") + return "generateOmittedAsInternal: boolean expected"; + return null; + }; + + /** + * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} object Plain object + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + */ + SelectiveGapicGeneration.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.SelectiveGapicGeneration) + return object; + var message = new $root.google.api.SelectiveGapicGeneration(); + if (object.methods) { + if (!Array.isArray(object.methods)) + throw TypeError(".google.api.SelectiveGapicGeneration.methods: array expected"); + message.methods = []; + for (var i = 0; i < object.methods.length; ++i) + message.methods[i] = String(object.methods[i]); + } + if (object.generateOmittedAsInternal != null) + message.generateOmittedAsInternal = Boolean(object.generateOmittedAsInternal); + return message; + }; + + /** + * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.SelectiveGapicGeneration} message SelectiveGapicGeneration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SelectiveGapicGeneration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.methods = []; + if (options.defaults) + object.generateOmittedAsInternal = false; + if (message.methods && message.methods.length) { + object.methods = []; + for (var j = 0; j < message.methods.length; ++j) + object.methods[j] = message.methods[j]; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + object.generateOmittedAsInternal = message.generateOmittedAsInternal; + return object; + }; + + /** + * Converts this SelectiveGapicGeneration to JSON. + * @function toJSON + * @memberof google.api.SelectiveGapicGeneration + * @instance + * @returns {Object.} JSON object + */ + SelectiveGapicGeneration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SelectiveGapicGeneration + * @function getTypeUrl + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SelectiveGapicGeneration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.SelectiveGapicGeneration"; + }; + + return SelectiveGapicGeneration; + })(); + + /** + * LaunchStage enum. + * @name google.api.LaunchStage + * @enum {number} + * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value + * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value + * @property {number} PRELAUNCH=7 PRELAUNCH value + * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value + * @property {number} ALPHA=2 ALPHA value + * @property {number} BETA=3 BETA value + * @property {number} GA=4 GA value + * @property {number} DEPRECATED=5 DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; + values[valuesById[6] = "UNIMPLEMENTED"] = 6; + values[valuesById[7] = "PRELAUNCH"] = 7; + values[valuesById[1] = "EARLY_ACCESS"] = 1; + values[valuesById[2] = "ALPHA"] = 2; + values[valuesById[3] = "BETA"] = 3; + values[valuesById[4] = "GA"] = 4; + values[valuesById[5] = "DEPRECATED"] = 5; + return values; + })(); + + return api; + })(); + + google.longrunning = (function() { + + /** + * Namespace longrunning. + * @memberof google + * @namespace + */ + var longrunning = {}; + + longrunning.Operations = (function() { + + /** + * Constructs a new Operations service. + * @memberof google.longrunning + * @classdesc Represents an Operations + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Operations(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (Operations.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Operations; + + /** + * Creates new Operations service using the specified rpc implementation. + * @function create + * @memberof google.longrunning.Operations + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {Operations} RPC service. Useful where requests and/or responses are streamed. + */ + Operations.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.longrunning.Operations|listOperations}. + * @memberof google.longrunning.Operations + * @typedef ListOperationsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.ListOperationsResponse} [response] ListOperationsResponse + */ + + /** + * Calls ListOperations. + * @function listOperations + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IListOperationsRequest} request ListOperationsRequest message or plain object + * @param {google.longrunning.Operations.ListOperationsCallback} callback Node-style callback called with the error, if any, and ListOperationsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.listOperations = function listOperations(request, callback) { + return this.rpcCall(listOperations, $root.google.longrunning.ListOperationsRequest, $root.google.longrunning.ListOperationsResponse, request, callback); + }, "name", { value: "ListOperations" }); + + /** + * Calls ListOperations. + * @function listOperations + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IListOperationsRequest} request ListOperationsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations|getOperation}. + * @memberof google.longrunning.Operations + * @typedef GetOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls GetOperation. + * @function getOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IGetOperationRequest} request GetOperationRequest message or plain object + * @param {google.longrunning.Operations.GetOperationCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.getOperation = function getOperation(request, callback) { + return this.rpcCall(getOperation, $root.google.longrunning.GetOperationRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "GetOperation" }); + + /** + * Calls GetOperation. + * @function getOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IGetOperationRequest} request GetOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations|deleteOperation}. + * @memberof google.longrunning.Operations + * @typedef DeleteOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteOperation. + * @function deleteOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IDeleteOperationRequest} request DeleteOperationRequest message or plain object + * @param {google.longrunning.Operations.DeleteOperationCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.deleteOperation = function deleteOperation(request, callback) { + return this.rpcCall(deleteOperation, $root.google.longrunning.DeleteOperationRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteOperation" }); + + /** + * Calls DeleteOperation. + * @function deleteOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IDeleteOperationRequest} request DeleteOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations|cancelOperation}. + * @memberof google.longrunning.Operations + * @typedef CancelOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls CancelOperation. + * @function cancelOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.ICancelOperationRequest} request CancelOperationRequest message or plain object + * @param {google.longrunning.Operations.CancelOperationCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.cancelOperation = function cancelOperation(request, callback) { + return this.rpcCall(cancelOperation, $root.google.longrunning.CancelOperationRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "CancelOperation" }); + + /** + * Calls CancelOperation. + * @function cancelOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.ICancelOperationRequest} request CancelOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.longrunning.Operations|waitOperation}. + * @memberof google.longrunning.Operations + * @typedef WaitOperationCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls WaitOperation. + * @function waitOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IWaitOperationRequest} request WaitOperationRequest message or plain object + * @param {google.longrunning.Operations.WaitOperationCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Operations.prototype.waitOperation = function waitOperation(request, callback) { + return this.rpcCall(waitOperation, $root.google.longrunning.WaitOperationRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "WaitOperation" }); + + /** + * Calls WaitOperation. + * @function waitOperation + * @memberof google.longrunning.Operations + * @instance + * @param {google.longrunning.IWaitOperationRequest} request WaitOperationRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return Operations; + })(); + + longrunning.Operation = (function() { + + /** + * Properties of an Operation. + * @memberof google.longrunning + * @interface IOperation + * @property {string|null} [name] Operation name + * @property {google.protobuf.IAny|null} [metadata] Operation metadata + * @property {boolean|null} [done] Operation done + * @property {google.rpc.IStatus|null} [error] Operation error + * @property {google.protobuf.IAny|null} [response] Operation response + */ + + /** + * Constructs a new Operation. + * @memberof google.longrunning + * @classdesc Represents an Operation. + * @implements IOperation + * @constructor + * @param {google.longrunning.IOperation=} [properties] Properties to set + */ + function Operation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Operation name. + * @member {string} name + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.name = ""; + + /** + * Operation metadata. + * @member {google.protobuf.IAny|null|undefined} metadata + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.metadata = null; + + /** + * Operation done. + * @member {boolean} done + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.done = false; + + /** + * Operation error. + * @member {google.rpc.IStatus|null|undefined} error + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.error = null; + + /** + * Operation response. + * @member {google.protobuf.IAny|null|undefined} response + * @memberof google.longrunning.Operation + * @instance + */ + Operation.prototype.response = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Operation result. + * @member {"error"|"response"|undefined} result + * @memberof google.longrunning.Operation + * @instance + */ + Object.defineProperty(Operation.prototype, "result", { + get: $util.oneOfGetter($oneOfFields = ["error", "response"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new Operation instance using the specified properties. + * @function create + * @memberof google.longrunning.Operation + * @static + * @param {google.longrunning.IOperation=} [properties] Properties to set + * @returns {google.longrunning.Operation} Operation instance + */ + Operation.create = function create(properties) { + return new Operation(properties); + }; + + /** + * Encodes the specified Operation message. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages. + * @function encode + * @memberof google.longrunning.Operation + * @static + * @param {google.longrunning.IOperation} message Operation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Operation.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.metadata != null && Object.hasOwnProperty.call(message, "metadata")) + $root.google.protobuf.Any.encode(message.metadata, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.done != null && Object.hasOwnProperty.call(message, "done")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.done); + if (message.error != null && Object.hasOwnProperty.call(message, "error")) + $root.google.rpc.Status.encode(message.error, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.response != null && Object.hasOwnProperty.call(message, "response")) + $root.google.protobuf.Any.encode(message.response, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Operation message, length delimited. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages. + * @function encodeDelimited + * @memberof google.longrunning.Operation + * @static + * @param {google.longrunning.IOperation} message Operation message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Operation.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an Operation message from the specified reader or buffer. + * @function decode + * @memberof google.longrunning.Operation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.longrunning.Operation} Operation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Operation.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.longrunning.Operation(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.metadata = $root.google.protobuf.Any.decode(reader, reader.uint32()); + break; + } + case 3: { + message.done = reader.bool(); + break; + } + case 4: { + message.error = $root.google.rpc.Status.decode(reader, reader.uint32()); + break; + } + case 5: { + message.response = $root.google.protobuf.Any.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an Operation message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.longrunning.Operation + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.longrunning.Operation} Operation + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Operation.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an Operation message. + * @function verify + * @memberof google.longrunning.Operation + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Operation.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.metadata != null && message.hasOwnProperty("metadata")) { + var error = $root.google.protobuf.Any.verify(message.metadata); + if (error) + return "metadata." + error; + } + if (message.done != null && message.hasOwnProperty("done")) + if (typeof message.done !== "boolean") + return "done: boolean expected"; + if (message.error != null && message.hasOwnProperty("error")) { + properties.result = 1; + { + var error = $root.google.rpc.Status.verify(message.error); + if (error) + return "error." + error; + } + } + if (message.response != null && message.hasOwnProperty("response")) { + if (properties.result === 1) + return "result: multiple values"; + properties.result = 1; + { + var error = $root.google.protobuf.Any.verify(message.response); + if (error) + return "response." + error; + } + } + return null; + }; + + /** + * Creates an Operation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.Operation + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.Operation} Operation + */ + Operation.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.Operation) + return object; + var message = new $root.google.longrunning.Operation(); + if (object.name != null) + message.name = String(object.name); + if (object.metadata != null) { + if (typeof object.metadata !== "object") + throw TypeError(".google.longrunning.Operation.metadata: object expected"); + message.metadata = $root.google.protobuf.Any.fromObject(object.metadata); + } + if (object.done != null) + message.done = Boolean(object.done); + if (object.error != null) { + if (typeof object.error !== "object") + throw TypeError(".google.longrunning.Operation.error: object expected"); + message.error = $root.google.rpc.Status.fromObject(object.error); + } + if (object.response != null) { + if (typeof object.response !== "object") + throw TypeError(".google.longrunning.Operation.response: object expected"); + message.response = $root.google.protobuf.Any.fromObject(object.response); + } + return message; + }; + + /** + * Creates a plain object from an Operation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.Operation + * @static + * @param {google.longrunning.Operation} message Operation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Operation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.metadata = null; + object.done = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.metadata != null && message.hasOwnProperty("metadata")) + object.metadata = $root.google.protobuf.Any.toObject(message.metadata, options); + if (message.done != null && message.hasOwnProperty("done")) + object.done = message.done; + if (message.error != null && message.hasOwnProperty("error")) { + object.error = $root.google.rpc.Status.toObject(message.error, options); + if (options.oneofs) + object.result = "error"; + } + if (message.response != null && message.hasOwnProperty("response")) { + object.response = $root.google.protobuf.Any.toObject(message.response, options); + if (options.oneofs) + object.result = "response"; + } + return object; + }; + + /** + * Converts this Operation to JSON. + * @function toJSON + * @memberof google.longrunning.Operation + * @instance + * @returns {Object.} JSON object + */ + Operation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Operation + * @function getTypeUrl + * @memberof google.longrunning.Operation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Operation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.Operation"; + }; + + return Operation; + })(); + + longrunning.GetOperationRequest = (function() { + + /** + * Properties of a GetOperationRequest. + * @memberof google.longrunning + * @interface IGetOperationRequest + * @property {string|null} [name] GetOperationRequest name + */ + + /** + * Constructs a new GetOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a GetOperationRequest. + * @implements IGetOperationRequest + * @constructor + * @param {google.longrunning.IGetOperationRequest=} [properties] Properties to set + */ + function GetOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetOperationRequest name. + * @member {string} name + * @memberof google.longrunning.GetOperationRequest + * @instance + */ + GetOperationRequest.prototype.name = ""; + + /** + * Creates a new GetOperationRequest instance using the specified properties. + * @function create + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {google.longrunning.IGetOperationRequest=} [properties] Properties to set + * @returns {google.longrunning.GetOperationRequest} GetOperationRequest instance + */ + GetOperationRequest.create = function create(properties) { + return new GetOperationRequest(properties); + }; + + /** + * Encodes the specified GetOperationRequest message. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages. + * @function encode + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {google.longrunning.IGetOperationRequest} message GetOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetOperationRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {google.longrunning.IGetOperationRequest} message GetOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetOperationRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetOperationRequest message from the specified reader or buffer. + * @function decode + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.longrunning.GetOperationRequest} GetOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetOperationRequest.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.longrunning.GetOperationRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetOperationRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.longrunning.GetOperationRequest} GetOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetOperationRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetOperationRequest message. + * @function verify + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetOperationRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.GetOperationRequest} GetOperationRequest + */ + GetOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.GetOperationRequest) + return object; + var message = new $root.google.longrunning.GetOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {google.longrunning.GetOperationRequest} message GetOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.GetOperationRequest + * @instance + * @returns {Object.} JSON object + */ + GetOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.GetOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.GetOperationRequest"; + }; + + return GetOperationRequest; + })(); + + longrunning.ListOperationsRequest = (function() { + + /** + * Properties of a ListOperationsRequest. + * @memberof google.longrunning + * @interface IListOperationsRequest + * @property {string|null} [name] ListOperationsRequest name + * @property {string|null} [filter] ListOperationsRequest filter + * @property {number|null} [pageSize] ListOperationsRequest pageSize + * @property {string|null} [pageToken] ListOperationsRequest pageToken + */ + + /** + * Constructs a new ListOperationsRequest. + * @memberof google.longrunning + * @classdesc Represents a ListOperationsRequest. + * @implements IListOperationsRequest + * @constructor + * @param {google.longrunning.IListOperationsRequest=} [properties] Properties to set + */ + function ListOperationsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListOperationsRequest name. + * @member {string} name + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.name = ""; + + /** + * ListOperationsRequest filter. + * @member {string} filter + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.filter = ""; + + /** + * ListOperationsRequest pageSize. + * @member {number} pageSize + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.pageSize = 0; + + /** + * ListOperationsRequest pageToken. + * @member {string} pageToken + * @memberof google.longrunning.ListOperationsRequest + * @instance + */ + ListOperationsRequest.prototype.pageToken = ""; + + /** + * Creates a new ListOperationsRequest instance using the specified properties. + * @function create + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {google.longrunning.IListOperationsRequest=} [properties] Properties to set + * @returns {google.longrunning.ListOperationsRequest} ListOperationsRequest instance + */ + ListOperationsRequest.create = function create(properties) { + return new ListOperationsRequest(properties); + }; + + /** + * Encodes the specified ListOperationsRequest message. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages. + * @function encode + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {google.longrunning.IListOperationsRequest} message ListOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListOperationsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.name); + return writer; + }; + + /** + * Encodes the specified ListOperationsRequest message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {google.longrunning.IListOperationsRequest} message ListOperationsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListOperationsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListOperationsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.longrunning.ListOperationsRequest} ListOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListOperationsRequest.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.longrunning.ListOperationsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 4: { + message.name = reader.string(); + break; + } + case 1: { + message.filter = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListOperationsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.longrunning.ListOperationsRequest} ListOperationsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListOperationsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListOperationsRequest message. + * @function verify + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListOperationsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.ListOperationsRequest} ListOperationsRequest + */ + ListOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.ListOperationsRequest) + return object; + var message = new $root.google.longrunning.ListOperationsRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {google.longrunning.ListOperationsRequest} message ListOperationsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListOperationsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + object.name = ""; + } + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this ListOperationsRequest to JSON. + * @function toJSON + * @memberof google.longrunning.ListOperationsRequest + * @instance + * @returns {Object.} JSON object + */ + ListOperationsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListOperationsRequest + * @function getTypeUrl + * @memberof google.longrunning.ListOperationsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.ListOperationsRequest"; + }; + + return ListOperationsRequest; + })(); + + longrunning.ListOperationsResponse = (function() { + + /** + * Properties of a ListOperationsResponse. + * @memberof google.longrunning + * @interface IListOperationsResponse + * @property {Array.|null} [operations] ListOperationsResponse operations + * @property {string|null} [nextPageToken] ListOperationsResponse nextPageToken + */ + + /** + * Constructs a new ListOperationsResponse. + * @memberof google.longrunning + * @classdesc Represents a ListOperationsResponse. + * @implements IListOperationsResponse + * @constructor + * @param {google.longrunning.IListOperationsResponse=} [properties] Properties to set + */ + function ListOperationsResponse(properties) { + this.operations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListOperationsResponse operations. + * @member {Array.} operations + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.operations = $util.emptyArray; + + /** + * ListOperationsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.longrunning.ListOperationsResponse + * @instance + */ + ListOperationsResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListOperationsResponse instance using the specified properties. + * @function create + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {google.longrunning.IListOperationsResponse=} [properties] Properties to set + * @returns {google.longrunning.ListOperationsResponse} ListOperationsResponse instance + */ + ListOperationsResponse.create = function create(properties) { + return new ListOperationsResponse(properties); + }; + + /** + * Encodes the specified ListOperationsResponse message. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages. + * @function encode + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {google.longrunning.IListOperationsResponse} message ListOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListOperationsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.operations != null && message.operations.length) + for (var i = 0; i < message.operations.length; ++i) + $root.google.longrunning.Operation.encode(message.operations[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListOperationsResponse message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {google.longrunning.IListOperationsResponse} message ListOperationsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListOperationsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListOperationsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.longrunning.ListOperationsResponse} ListOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListOperationsResponse.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.longrunning.ListOperationsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.operations && message.operations.length)) + message.operations = []; + message.operations.push($root.google.longrunning.Operation.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListOperationsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.longrunning.ListOperationsResponse} ListOperationsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListOperationsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListOperationsResponse message. + * @function verify + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListOperationsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.operations != null && message.hasOwnProperty("operations")) { + if (!Array.isArray(message.operations)) + return "operations: array expected"; + for (var i = 0; i < message.operations.length; ++i) { + var error = $root.google.longrunning.Operation.verify(message.operations[i]); + if (error) + return "operations." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.ListOperationsResponse} ListOperationsResponse + */ + ListOperationsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.ListOperationsResponse) + return object; + var message = new $root.google.longrunning.ListOperationsResponse(); + if (object.operations) { + if (!Array.isArray(object.operations)) + throw TypeError(".google.longrunning.ListOperationsResponse.operations: array expected"); + message.operations = []; + for (var i = 0; i < object.operations.length; ++i) { + if (typeof object.operations[i] !== "object") + throw TypeError(".google.longrunning.ListOperationsResponse.operations: object expected"); + message.operations[i] = $root.google.longrunning.Operation.fromObject(object.operations[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {google.longrunning.ListOperationsResponse} message ListOperationsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListOperationsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.operations = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.operations && message.operations.length) { + object.operations = []; + for (var j = 0; j < message.operations.length; ++j) + object.operations[j] = $root.google.longrunning.Operation.toObject(message.operations[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListOperationsResponse to JSON. + * @function toJSON + * @memberof google.longrunning.ListOperationsResponse + * @instance + * @returns {Object.} JSON object + */ + ListOperationsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListOperationsResponse + * @function getTypeUrl + * @memberof google.longrunning.ListOperationsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListOperationsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.ListOperationsResponse"; + }; + + return ListOperationsResponse; + })(); + + longrunning.CancelOperationRequest = (function() { + + /** + * Properties of a CancelOperationRequest. + * @memberof google.longrunning + * @interface ICancelOperationRequest + * @property {string|null} [name] CancelOperationRequest name + */ + + /** + * Constructs a new CancelOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a CancelOperationRequest. + * @implements ICancelOperationRequest + * @constructor + * @param {google.longrunning.ICancelOperationRequest=} [properties] Properties to set + */ + function CancelOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CancelOperationRequest name. + * @member {string} name + * @memberof google.longrunning.CancelOperationRequest + * @instance + */ + CancelOperationRequest.prototype.name = ""; + + /** + * Creates a new CancelOperationRequest instance using the specified properties. + * @function create + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {google.longrunning.ICancelOperationRequest=} [properties] Properties to set + * @returns {google.longrunning.CancelOperationRequest} CancelOperationRequest instance + */ + CancelOperationRequest.create = function create(properties) { + return new CancelOperationRequest(properties); + }; + + /** + * Encodes the specified CancelOperationRequest message. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages. + * @function encode + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {google.longrunning.ICancelOperationRequest} message CancelOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CancelOperationRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified CancelOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {google.longrunning.ICancelOperationRequest} message CancelOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CancelOperationRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CancelOperationRequest message from the specified reader or buffer. + * @function decode + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.longrunning.CancelOperationRequest} CancelOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CancelOperationRequest.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.longrunning.CancelOperationRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CancelOperationRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.longrunning.CancelOperationRequest} CancelOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CancelOperationRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CancelOperationRequest message. + * @function verify + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CancelOperationRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.CancelOperationRequest} CancelOperationRequest + */ + CancelOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.CancelOperationRequest) + return object; + var message = new $root.google.longrunning.CancelOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {google.longrunning.CancelOperationRequest} message CancelOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CancelOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this CancelOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.CancelOperationRequest + * @instance + * @returns {Object.} JSON object + */ + CancelOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CancelOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.CancelOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CancelOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.CancelOperationRequest"; + }; + + return CancelOperationRequest; + })(); + + longrunning.DeleteOperationRequest = (function() { + + /** + * Properties of a DeleteOperationRequest. + * @memberof google.longrunning + * @interface IDeleteOperationRequest + * @property {string|null} [name] DeleteOperationRequest name + */ + + /** + * Constructs a new DeleteOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a DeleteOperationRequest. + * @implements IDeleteOperationRequest + * @constructor + * @param {google.longrunning.IDeleteOperationRequest=} [properties] Properties to set + */ + function DeleteOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteOperationRequest name. + * @member {string} name + * @memberof google.longrunning.DeleteOperationRequest + * @instance + */ + DeleteOperationRequest.prototype.name = ""; + + /** + * Creates a new DeleteOperationRequest instance using the specified properties. + * @function create + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {google.longrunning.IDeleteOperationRequest=} [properties] Properties to set + * @returns {google.longrunning.DeleteOperationRequest} DeleteOperationRequest instance + */ + DeleteOperationRequest.create = function create(properties) { + return new DeleteOperationRequest(properties); + }; + + /** + * Encodes the specified DeleteOperationRequest message. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages. + * @function encode + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {google.longrunning.IDeleteOperationRequest} message DeleteOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteOperationRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified DeleteOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {google.longrunning.IDeleteOperationRequest} message DeleteOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteOperationRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteOperationRequest message from the specified reader or buffer. + * @function decode + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.longrunning.DeleteOperationRequest} DeleteOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteOperationRequest.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.longrunning.DeleteOperationRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteOperationRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.longrunning.DeleteOperationRequest} DeleteOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteOperationRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteOperationRequest message. + * @function verify + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteOperationRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.DeleteOperationRequest} DeleteOperationRequest + */ + DeleteOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.DeleteOperationRequest) + return object; + var message = new $root.google.longrunning.DeleteOperationRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {google.longrunning.DeleteOperationRequest} message DeleteOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeleteOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.DeleteOperationRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.DeleteOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.DeleteOperationRequest"; + }; + + return DeleteOperationRequest; + })(); + + longrunning.WaitOperationRequest = (function() { + + /** + * Properties of a WaitOperationRequest. + * @memberof google.longrunning + * @interface IWaitOperationRequest + * @property {string|null} [name] WaitOperationRequest name + * @property {google.protobuf.IDuration|null} [timeout] WaitOperationRequest timeout + */ + + /** + * Constructs a new WaitOperationRequest. + * @memberof google.longrunning + * @classdesc Represents a WaitOperationRequest. + * @implements IWaitOperationRequest + * @constructor + * @param {google.longrunning.IWaitOperationRequest=} [properties] Properties to set + */ + function WaitOperationRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WaitOperationRequest name. + * @member {string} name + * @memberof google.longrunning.WaitOperationRequest + * @instance + */ + WaitOperationRequest.prototype.name = ""; + + /** + * WaitOperationRequest timeout. + * @member {google.protobuf.IDuration|null|undefined} timeout + * @memberof google.longrunning.WaitOperationRequest + * @instance + */ + WaitOperationRequest.prototype.timeout = null; + + /** + * Creates a new WaitOperationRequest instance using the specified properties. + * @function create + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {google.longrunning.IWaitOperationRequest=} [properties] Properties to set + * @returns {google.longrunning.WaitOperationRequest} WaitOperationRequest instance + */ + WaitOperationRequest.create = function create(properties) { + return new WaitOperationRequest(properties); + }; + + /** + * Encodes the specified WaitOperationRequest message. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages. + * @function encode + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {google.longrunning.IWaitOperationRequest} message WaitOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WaitOperationRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.timeout != null && Object.hasOwnProperty.call(message, "timeout")) + $root.google.protobuf.Duration.encode(message.timeout, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified WaitOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {google.longrunning.IWaitOperationRequest} message WaitOperationRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WaitOperationRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a WaitOperationRequest message from the specified reader or buffer. + * @function decode + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.longrunning.WaitOperationRequest} WaitOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WaitOperationRequest.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.longrunning.WaitOperationRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.timeout = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a WaitOperationRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.longrunning.WaitOperationRequest} WaitOperationRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WaitOperationRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a WaitOperationRequest message. + * @function verify + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + WaitOperationRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.timeout != null && message.hasOwnProperty("timeout")) { + var error = $root.google.protobuf.Duration.verify(message.timeout); + if (error) + return "timeout." + error; + } + return null; + }; + + /** + * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.WaitOperationRequest} WaitOperationRequest + */ + WaitOperationRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.WaitOperationRequest) + return object; + var message = new $root.google.longrunning.WaitOperationRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.timeout != null) { + if (typeof object.timeout !== "object") + throw TypeError(".google.longrunning.WaitOperationRequest.timeout: object expected"); + message.timeout = $root.google.protobuf.Duration.fromObject(object.timeout); + } + return message; + }; + + /** + * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {google.longrunning.WaitOperationRequest} message WaitOperationRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WaitOperationRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.timeout = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.timeout != null && message.hasOwnProperty("timeout")) + object.timeout = $root.google.protobuf.Duration.toObject(message.timeout, options); + return object; + }; + + /** + * Converts this WaitOperationRequest to JSON. + * @function toJSON + * @memberof google.longrunning.WaitOperationRequest + * @instance + * @returns {Object.} JSON object + */ + WaitOperationRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WaitOperationRequest + * @function getTypeUrl + * @memberof google.longrunning.WaitOperationRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WaitOperationRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.WaitOperationRequest"; + }; + + return WaitOperationRequest; + })(); + + longrunning.OperationInfo = (function() { + + /** + * Properties of an OperationInfo. + * @memberof google.longrunning + * @interface IOperationInfo + * @property {string|null} [responseType] OperationInfo responseType + * @property {string|null} [metadataType] OperationInfo metadataType + */ + + /** + * Constructs a new OperationInfo. + * @memberof google.longrunning + * @classdesc Represents an OperationInfo. + * @implements IOperationInfo + * @constructor + * @param {google.longrunning.IOperationInfo=} [properties] Properties to set + */ + function OperationInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OperationInfo responseType. + * @member {string} responseType + * @memberof google.longrunning.OperationInfo + * @instance + */ + OperationInfo.prototype.responseType = ""; + + /** + * OperationInfo metadataType. + * @member {string} metadataType + * @memberof google.longrunning.OperationInfo + * @instance + */ + OperationInfo.prototype.metadataType = ""; + + /** + * Creates a new OperationInfo instance using the specified properties. + * @function create + * @memberof google.longrunning.OperationInfo + * @static + * @param {google.longrunning.IOperationInfo=} [properties] Properties to set + * @returns {google.longrunning.OperationInfo} OperationInfo instance + */ + OperationInfo.create = function create(properties) { + return new OperationInfo(properties); + }; + + /** + * Encodes the specified OperationInfo message. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages. + * @function encode + * @memberof google.longrunning.OperationInfo + * @static + * @param {google.longrunning.IOperationInfo} message OperationInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OperationInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.responseType != null && Object.hasOwnProperty.call(message, "responseType")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.responseType); + if (message.metadataType != null && Object.hasOwnProperty.call(message, "metadataType")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.metadataType); + return writer; + }; + + /** + * Encodes the specified OperationInfo message, length delimited. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.longrunning.OperationInfo + * @static + * @param {google.longrunning.IOperationInfo} message OperationInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OperationInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an OperationInfo message from the specified reader or buffer. + * @function decode + * @memberof google.longrunning.OperationInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.longrunning.OperationInfo} OperationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OperationInfo.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.longrunning.OperationInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.responseType = reader.string(); + break; + } + case 2: { + message.metadataType = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an OperationInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.longrunning.OperationInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.longrunning.OperationInfo} OperationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OperationInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an OperationInfo message. + * @function verify + * @memberof google.longrunning.OperationInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + OperationInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.responseType != null && message.hasOwnProperty("responseType")) + if (!$util.isString(message.responseType)) + return "responseType: string expected"; + if (message.metadataType != null && message.hasOwnProperty("metadataType")) + if (!$util.isString(message.metadataType)) + return "metadataType: string expected"; + return null; + }; + + /** + * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.longrunning.OperationInfo + * @static + * @param {Object.} object Plain object + * @returns {google.longrunning.OperationInfo} OperationInfo + */ + OperationInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.longrunning.OperationInfo) + return object; + var message = new $root.google.longrunning.OperationInfo(); + if (object.responseType != null) + message.responseType = String(object.responseType); + if (object.metadataType != null) + message.metadataType = String(object.metadataType); + return message; + }; + + /** + * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.longrunning.OperationInfo + * @static + * @param {google.longrunning.OperationInfo} message OperationInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OperationInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.responseType = ""; + object.metadataType = ""; + } + if (message.responseType != null && message.hasOwnProperty("responseType")) + object.responseType = message.responseType; + if (message.metadataType != null && message.hasOwnProperty("metadataType")) + object.metadataType = message.metadataType; + return object; + }; + + /** + * Converts this OperationInfo to JSON. + * @function toJSON + * @memberof google.longrunning.OperationInfo + * @instance + * @returns {Object.} JSON object + */ + OperationInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OperationInfo + * @function getTypeUrl + * @memberof google.longrunning.OperationInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OperationInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.longrunning.OperationInfo"; + }; + + return OperationInfo; + })(); + + return longrunning; + })(); + + google.iam = (function() { + + /** + * Namespace iam. + * @memberof google + * @namespace + */ + var iam = {}; + + iam.v1 = (function() { + + /** + * Namespace v1. + * @memberof google.iam + * @namespace + */ + var v1 = {}; + + v1.IAMPolicy = (function() { + + /** + * Constructs a new IAMPolicy service. + * @memberof google.iam.v1 + * @classdesc Represents a IAMPolicy + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function IAMPolicy(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (IAMPolicy.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = IAMPolicy; + + /** + * Creates new IAMPolicy service using the specified rpc implementation. + * @function create + * @memberof google.iam.v1.IAMPolicy + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {IAMPolicy} RPC service. Useful where requests and/or responses are streamed. + */ + IAMPolicy.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy|setIamPolicy}. + * @memberof google.iam.v1.IAMPolicy + * @typedef SetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.Policy} [response] Policy + */ + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.iam.v1.IAMPolicy + * @instance + * @param {google.iam.v1.ISetIamPolicyRequest} request SetIamPolicyRequest message or plain object + * @param {google.iam.v1.IAMPolicy.SetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(IAMPolicy.prototype.setIamPolicy = function setIamPolicy(request, callback) { + return this.rpcCall(setIamPolicy, $root.google.iam.v1.SetIamPolicyRequest, $root.google.iam.v1.Policy, request, callback); + }, "name", { value: "SetIamPolicy" }); + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.iam.v1.IAMPolicy + * @instance + * @param {google.iam.v1.ISetIamPolicyRequest} request SetIamPolicyRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy|getIamPolicy}. + * @memberof google.iam.v1.IAMPolicy + * @typedef GetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.Policy} [response] Policy + */ + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.iam.v1.IAMPolicy + * @instance + * @param {google.iam.v1.IGetIamPolicyRequest} request GetIamPolicyRequest message or plain object + * @param {google.iam.v1.IAMPolicy.GetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(IAMPolicy.prototype.getIamPolicy = function getIamPolicy(request, callback) { + return this.rpcCall(getIamPolicy, $root.google.iam.v1.GetIamPolicyRequest, $root.google.iam.v1.Policy, request, callback); + }, "name", { value: "GetIamPolicy" }); + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.iam.v1.IAMPolicy + * @instance + * @param {google.iam.v1.IGetIamPolicyRequest} request GetIamPolicyRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.iam.v1.IAMPolicy|testIamPermissions}. + * @memberof google.iam.v1.IAMPolicy + * @typedef TestIamPermissionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.iam.v1.TestIamPermissionsResponse} [response] TestIamPermissionsResponse + */ + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.iam.v1.IAMPolicy + * @instance + * @param {google.iam.v1.ITestIamPermissionsRequest} request TestIamPermissionsRequest message or plain object + * @param {google.iam.v1.IAMPolicy.TestIamPermissionsCallback} callback Node-style callback called with the error, if any, and TestIamPermissionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(IAMPolicy.prototype.testIamPermissions = function testIamPermissions(request, callback) { + return this.rpcCall(testIamPermissions, $root.google.iam.v1.TestIamPermissionsRequest, $root.google.iam.v1.TestIamPermissionsResponse, request, callback); + }, "name", { value: "TestIamPermissions" }); + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.iam.v1.IAMPolicy + * @instance + * @param {google.iam.v1.ITestIamPermissionsRequest} request TestIamPermissionsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return IAMPolicy; + })(); + + v1.SetIamPolicyRequest = (function() { + + /** + * Properties of a SetIamPolicyRequest. + * @memberof google.iam.v1 + * @interface ISetIamPolicyRequest + * @property {string|null} [resource] SetIamPolicyRequest resource + * @property {google.iam.v1.IPolicy|null} [policy] SetIamPolicyRequest policy + * @property {google.protobuf.IFieldMask|null} [updateMask] SetIamPolicyRequest updateMask + */ + + /** + * Constructs a new SetIamPolicyRequest. + * @memberof google.iam.v1 + * @classdesc Represents a SetIamPolicyRequest. + * @implements ISetIamPolicyRequest + * @constructor + * @param {google.iam.v1.ISetIamPolicyRequest=} [properties] Properties to set + */ + function SetIamPolicyRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SetIamPolicyRequest resource. + * @member {string} resource + * @memberof google.iam.v1.SetIamPolicyRequest + * @instance + */ + SetIamPolicyRequest.prototype.resource = ""; + + /** + * SetIamPolicyRequest policy. + * @member {google.iam.v1.IPolicy|null|undefined} policy + * @memberof google.iam.v1.SetIamPolicyRequest + * @instance + */ + SetIamPolicyRequest.prototype.policy = null; + + /** + * SetIamPolicyRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.iam.v1.SetIamPolicyRequest + * @instance + */ + SetIamPolicyRequest.prototype.updateMask = null; + + /** + * Creates a new SetIamPolicyRequest instance using the specified properties. + * @function create + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {google.iam.v1.ISetIamPolicyRequest=} [properties] Properties to set + * @returns {google.iam.v1.SetIamPolicyRequest} SetIamPolicyRequest instance + */ + SetIamPolicyRequest.create = function create(properties) { + return new SetIamPolicyRequest(properties); + }; + + /** + * Encodes the specified SetIamPolicyRequest message. Does not implicitly {@link google.iam.v1.SetIamPolicyRequest.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {google.iam.v1.ISetIamPolicyRequest} message SetIamPolicyRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SetIamPolicyRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.resource); + if (message.policy != null && Object.hasOwnProperty.call(message, "policy")) + $root.google.iam.v1.Policy.encode(message.policy, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + $root.google.protobuf.FieldMask.encode(message.updateMask, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SetIamPolicyRequest message, length delimited. Does not implicitly {@link google.iam.v1.SetIamPolicyRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {google.iam.v1.ISetIamPolicyRequest} message SetIamPolicyRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SetIamPolicyRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SetIamPolicyRequest message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.SetIamPolicyRequest} SetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SetIamPolicyRequest.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.iam.v1.SetIamPolicyRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.resource = reader.string(); + break; + } + case 2: { + message.policy = $root.google.iam.v1.Policy.decode(reader, reader.uint32()); + break; + } + case 3: { + message.updateMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SetIamPolicyRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.SetIamPolicyRequest} SetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SetIamPolicyRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SetIamPolicyRequest message. + * @function verify + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SetIamPolicyRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + if (message.policy != null && message.hasOwnProperty("policy")) { + var error = $root.google.iam.v1.Policy.verify(message.policy); + if (error) + return "policy." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.updateMask); + if (error) + return "updateMask." + error; + } + return null; + }; + + /** + * Creates a SetIamPolicyRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.SetIamPolicyRequest} SetIamPolicyRequest + */ + SetIamPolicyRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.SetIamPolicyRequest) + return object; + var message = new $root.google.iam.v1.SetIamPolicyRequest(); + if (object.resource != null) + message.resource = String(object.resource); + if (object.policy != null) { + if (typeof object.policy !== "object") + throw TypeError(".google.iam.v1.SetIamPolicyRequest.policy: object expected"); + message.policy = $root.google.iam.v1.Policy.fromObject(object.policy); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.iam.v1.SetIamPolicyRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from a SetIamPolicyRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {google.iam.v1.SetIamPolicyRequest} message SetIamPolicyRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SetIamPolicyRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.resource = ""; + object.policy = null; + object.updateMask = null; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.policy != null && message.hasOwnProperty("policy")) + object.policy = $root.google.iam.v1.Policy.toObject(message.policy, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this SetIamPolicyRequest to JSON. + * @function toJSON + * @memberof google.iam.v1.SetIamPolicyRequest + * @instance + * @returns {Object.} JSON object + */ + SetIamPolicyRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SetIamPolicyRequest + * @function getTypeUrl + * @memberof google.iam.v1.SetIamPolicyRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SetIamPolicyRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.SetIamPolicyRequest"; + }; + + return SetIamPolicyRequest; + })(); + + v1.GetIamPolicyRequest = (function() { + + /** + * Properties of a GetIamPolicyRequest. + * @memberof google.iam.v1 + * @interface IGetIamPolicyRequest + * @property {string|null} [resource] GetIamPolicyRequest resource + * @property {google.iam.v1.IGetPolicyOptions|null} [options] GetIamPolicyRequest options + */ + + /** + * Constructs a new GetIamPolicyRequest. + * @memberof google.iam.v1 + * @classdesc Represents a GetIamPolicyRequest. + * @implements IGetIamPolicyRequest + * @constructor + * @param {google.iam.v1.IGetIamPolicyRequest=} [properties] Properties to set + */ + function GetIamPolicyRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetIamPolicyRequest resource. + * @member {string} resource + * @memberof google.iam.v1.GetIamPolicyRequest + * @instance + */ + GetIamPolicyRequest.prototype.resource = ""; + + /** + * GetIamPolicyRequest options. + * @member {google.iam.v1.IGetPolicyOptions|null|undefined} options + * @memberof google.iam.v1.GetIamPolicyRequest + * @instance + */ + GetIamPolicyRequest.prototype.options = null; + + /** + * Creates a new GetIamPolicyRequest instance using the specified properties. + * @function create + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {google.iam.v1.IGetIamPolicyRequest=} [properties] Properties to set + * @returns {google.iam.v1.GetIamPolicyRequest} GetIamPolicyRequest instance + */ + GetIamPolicyRequest.create = function create(properties) { + return new GetIamPolicyRequest(properties); + }; + + /** + * Encodes the specified GetIamPolicyRequest message. Does not implicitly {@link google.iam.v1.GetIamPolicyRequest.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {google.iam.v1.IGetIamPolicyRequest} message GetIamPolicyRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetIamPolicyRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.resource); + if (message.options != null && Object.hasOwnProperty.call(message, "options")) + $root.google.iam.v1.GetPolicyOptions.encode(message.options, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified GetIamPolicyRequest message, length delimited. Does not implicitly {@link google.iam.v1.GetIamPolicyRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {google.iam.v1.IGetIamPolicyRequest} message GetIamPolicyRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetIamPolicyRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetIamPolicyRequest message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.GetIamPolicyRequest} GetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetIamPolicyRequest.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.iam.v1.GetIamPolicyRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.resource = reader.string(); + break; + } + case 2: { + message.options = $root.google.iam.v1.GetPolicyOptions.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetIamPolicyRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.GetIamPolicyRequest} GetIamPolicyRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetIamPolicyRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetIamPolicyRequest message. + * @function verify + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetIamPolicyRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + if (message.options != null && message.hasOwnProperty("options")) { + var error = $root.google.iam.v1.GetPolicyOptions.verify(message.options); + if (error) + return "options." + error; + } + return null; + }; + + /** + * Creates a GetIamPolicyRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.GetIamPolicyRequest} GetIamPolicyRequest + */ + GetIamPolicyRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.GetIamPolicyRequest) + return object; + var message = new $root.google.iam.v1.GetIamPolicyRequest(); + if (object.resource != null) + message.resource = String(object.resource); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.iam.v1.GetIamPolicyRequest.options: object expected"); + message.options = $root.google.iam.v1.GetPolicyOptions.fromObject(object.options); + } + return message; + }; + + /** + * Creates a plain object from a GetIamPolicyRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {google.iam.v1.GetIamPolicyRequest} message GetIamPolicyRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetIamPolicyRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.resource = ""; + object.options = null; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.iam.v1.GetPolicyOptions.toObject(message.options, options); + return object; + }; + + /** + * Converts this GetIamPolicyRequest to JSON. + * @function toJSON + * @memberof google.iam.v1.GetIamPolicyRequest + * @instance + * @returns {Object.} JSON object + */ + GetIamPolicyRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetIamPolicyRequest + * @function getTypeUrl + * @memberof google.iam.v1.GetIamPolicyRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetIamPolicyRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.GetIamPolicyRequest"; + }; + + return GetIamPolicyRequest; + })(); + + v1.TestIamPermissionsRequest = (function() { + + /** + * Properties of a TestIamPermissionsRequest. + * @memberof google.iam.v1 + * @interface ITestIamPermissionsRequest + * @property {string|null} [resource] TestIamPermissionsRequest resource + * @property {Array.|null} [permissions] TestIamPermissionsRequest permissions + */ + + /** + * Constructs a new TestIamPermissionsRequest. + * @memberof google.iam.v1 + * @classdesc Represents a TestIamPermissionsRequest. + * @implements ITestIamPermissionsRequest + * @constructor + * @param {google.iam.v1.ITestIamPermissionsRequest=} [properties] Properties to set + */ + function TestIamPermissionsRequest(properties) { + this.permissions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TestIamPermissionsRequest resource. + * @member {string} resource + * @memberof google.iam.v1.TestIamPermissionsRequest + * @instance + */ + TestIamPermissionsRequest.prototype.resource = ""; + + /** + * TestIamPermissionsRequest permissions. + * @member {Array.} permissions + * @memberof google.iam.v1.TestIamPermissionsRequest + * @instance + */ + TestIamPermissionsRequest.prototype.permissions = $util.emptyArray; + + /** + * Creates a new TestIamPermissionsRequest instance using the specified properties. + * @function create + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {google.iam.v1.ITestIamPermissionsRequest=} [properties] Properties to set + * @returns {google.iam.v1.TestIamPermissionsRequest} TestIamPermissionsRequest instance + */ + TestIamPermissionsRequest.create = function create(properties) { + return new TestIamPermissionsRequest(properties); + }; + + /** + * Encodes the specified TestIamPermissionsRequest message. Does not implicitly {@link google.iam.v1.TestIamPermissionsRequest.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {google.iam.v1.ITestIamPermissionsRequest} message TestIamPermissionsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.resource); + if (message.permissions != null && message.permissions.length) + for (var i = 0; i < message.permissions.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.permissions[i]); + return writer; + }; + + /** + * Encodes the specified TestIamPermissionsRequest message, length delimited. Does not implicitly {@link google.iam.v1.TestIamPermissionsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {google.iam.v1.ITestIamPermissionsRequest} message TestIamPermissionsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TestIamPermissionsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.TestIamPermissionsRequest} TestIamPermissionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsRequest.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.iam.v1.TestIamPermissionsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.resource = reader.string(); + break; + } + case 2: { + if (!(message.permissions && message.permissions.length)) + message.permissions = []; + message.permissions.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TestIamPermissionsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.TestIamPermissionsRequest} TestIamPermissionsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TestIamPermissionsRequest message. + * @function verify + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TestIamPermissionsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + if (message.permissions != null && message.hasOwnProperty("permissions")) { + if (!Array.isArray(message.permissions)) + return "permissions: array expected"; + for (var i = 0; i < message.permissions.length; ++i) + if (!$util.isString(message.permissions[i])) + return "permissions: string[] expected"; + } + return null; + }; + + /** + * Creates a TestIamPermissionsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.TestIamPermissionsRequest} TestIamPermissionsRequest + */ + TestIamPermissionsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.TestIamPermissionsRequest) + return object; + var message = new $root.google.iam.v1.TestIamPermissionsRequest(); + if (object.resource != null) + message.resource = String(object.resource); + if (object.permissions) { + if (!Array.isArray(object.permissions)) + throw TypeError(".google.iam.v1.TestIamPermissionsRequest.permissions: array expected"); + message.permissions = []; + for (var i = 0; i < object.permissions.length; ++i) + message.permissions[i] = String(object.permissions[i]); + } + return message; + }; + + /** + * Creates a plain object from a TestIamPermissionsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {google.iam.v1.TestIamPermissionsRequest} message TestIamPermissionsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TestIamPermissionsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.permissions = []; + if (options.defaults) + object.resource = ""; + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.permissions && message.permissions.length) { + object.permissions = []; + for (var j = 0; j < message.permissions.length; ++j) + object.permissions[j] = message.permissions[j]; + } + return object; + }; + + /** + * Converts this TestIamPermissionsRequest to JSON. + * @function toJSON + * @memberof google.iam.v1.TestIamPermissionsRequest + * @instance + * @returns {Object.} JSON object + */ + TestIamPermissionsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TestIamPermissionsRequest + * @function getTypeUrl + * @memberof google.iam.v1.TestIamPermissionsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TestIamPermissionsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.TestIamPermissionsRequest"; + }; + + return TestIamPermissionsRequest; + })(); + + v1.TestIamPermissionsResponse = (function() { + + /** + * Properties of a TestIamPermissionsResponse. + * @memberof google.iam.v1 + * @interface ITestIamPermissionsResponse + * @property {Array.|null} [permissions] TestIamPermissionsResponse permissions + */ + + /** + * Constructs a new TestIamPermissionsResponse. + * @memberof google.iam.v1 + * @classdesc Represents a TestIamPermissionsResponse. + * @implements ITestIamPermissionsResponse + * @constructor + * @param {google.iam.v1.ITestIamPermissionsResponse=} [properties] Properties to set + */ + function TestIamPermissionsResponse(properties) { + this.permissions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TestIamPermissionsResponse permissions. + * @member {Array.} permissions + * @memberof google.iam.v1.TestIamPermissionsResponse + * @instance + */ + TestIamPermissionsResponse.prototype.permissions = $util.emptyArray; + + /** + * Creates a new TestIamPermissionsResponse instance using the specified properties. + * @function create + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {google.iam.v1.ITestIamPermissionsResponse=} [properties] Properties to set + * @returns {google.iam.v1.TestIamPermissionsResponse} TestIamPermissionsResponse instance + */ + TestIamPermissionsResponse.create = function create(properties) { + return new TestIamPermissionsResponse(properties); + }; + + /** + * Encodes the specified TestIamPermissionsResponse message. Does not implicitly {@link google.iam.v1.TestIamPermissionsResponse.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {google.iam.v1.ITestIamPermissionsResponse} message TestIamPermissionsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.permissions != null && message.permissions.length) + for (var i = 0; i < message.permissions.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.permissions[i]); + return writer; + }; + + /** + * Encodes the specified TestIamPermissionsResponse message, length delimited. Does not implicitly {@link google.iam.v1.TestIamPermissionsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {google.iam.v1.ITestIamPermissionsResponse} message TestIamPermissionsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TestIamPermissionsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.TestIamPermissionsResponse} TestIamPermissionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsResponse.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.iam.v1.TestIamPermissionsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.permissions && message.permissions.length)) + message.permissions = []; + message.permissions.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TestIamPermissionsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.TestIamPermissionsResponse} TestIamPermissionsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TestIamPermissionsResponse message. + * @function verify + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TestIamPermissionsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.permissions != null && message.hasOwnProperty("permissions")) { + if (!Array.isArray(message.permissions)) + return "permissions: array expected"; + for (var i = 0; i < message.permissions.length; ++i) + if (!$util.isString(message.permissions[i])) + return "permissions: string[] expected"; + } + return null; + }; + + /** + * Creates a TestIamPermissionsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.TestIamPermissionsResponse} TestIamPermissionsResponse + */ + TestIamPermissionsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.TestIamPermissionsResponse) + return object; + var message = new $root.google.iam.v1.TestIamPermissionsResponse(); + if (object.permissions) { + if (!Array.isArray(object.permissions)) + throw TypeError(".google.iam.v1.TestIamPermissionsResponse.permissions: array expected"); + message.permissions = []; + for (var i = 0; i < object.permissions.length; ++i) + message.permissions[i] = String(object.permissions[i]); + } + return message; + }; + + /** + * Creates a plain object from a TestIamPermissionsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {google.iam.v1.TestIamPermissionsResponse} message TestIamPermissionsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TestIamPermissionsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.permissions = []; + if (message.permissions && message.permissions.length) { + object.permissions = []; + for (var j = 0; j < message.permissions.length; ++j) + object.permissions[j] = message.permissions[j]; + } + return object; + }; + + /** + * Converts this TestIamPermissionsResponse to JSON. + * @function toJSON + * @memberof google.iam.v1.TestIamPermissionsResponse + * @instance + * @returns {Object.} JSON object + */ + TestIamPermissionsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TestIamPermissionsResponse + * @function getTypeUrl + * @memberof google.iam.v1.TestIamPermissionsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TestIamPermissionsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.TestIamPermissionsResponse"; + }; + + return TestIamPermissionsResponse; + })(); + + v1.GetPolicyOptions = (function() { + + /** + * Properties of a GetPolicyOptions. + * @memberof google.iam.v1 + * @interface IGetPolicyOptions + * @property {number|null} [requestedPolicyVersion] GetPolicyOptions requestedPolicyVersion + */ + + /** + * Constructs a new GetPolicyOptions. + * @memberof google.iam.v1 + * @classdesc Represents a GetPolicyOptions. + * @implements IGetPolicyOptions + * @constructor + * @param {google.iam.v1.IGetPolicyOptions=} [properties] Properties to set + */ + function GetPolicyOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetPolicyOptions requestedPolicyVersion. + * @member {number} requestedPolicyVersion + * @memberof google.iam.v1.GetPolicyOptions + * @instance + */ + GetPolicyOptions.prototype.requestedPolicyVersion = 0; + + /** + * Creates a new GetPolicyOptions instance using the specified properties. + * @function create + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {google.iam.v1.IGetPolicyOptions=} [properties] Properties to set + * @returns {google.iam.v1.GetPolicyOptions} GetPolicyOptions instance + */ + GetPolicyOptions.create = function create(properties) { + return new GetPolicyOptions(properties); + }; + + /** + * Encodes the specified GetPolicyOptions message. Does not implicitly {@link google.iam.v1.GetPolicyOptions.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {google.iam.v1.IGetPolicyOptions} message GetPolicyOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetPolicyOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestedPolicyVersion != null && Object.hasOwnProperty.call(message, "requestedPolicyVersion")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.requestedPolicyVersion); + return writer; + }; + + /** + * Encodes the specified GetPolicyOptions message, length delimited. Does not implicitly {@link google.iam.v1.GetPolicyOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {google.iam.v1.IGetPolicyOptions} message GetPolicyOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetPolicyOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetPolicyOptions message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.GetPolicyOptions} GetPolicyOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetPolicyOptions.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.iam.v1.GetPolicyOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.requestedPolicyVersion = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetPolicyOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.GetPolicyOptions} GetPolicyOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetPolicyOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetPolicyOptions message. + * @function verify + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetPolicyOptions.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.requestedPolicyVersion != null && message.hasOwnProperty("requestedPolicyVersion")) + if (!$util.isInteger(message.requestedPolicyVersion)) + return "requestedPolicyVersion: integer expected"; + return null; + }; + + /** + * Creates a GetPolicyOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.GetPolicyOptions} GetPolicyOptions + */ + GetPolicyOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.GetPolicyOptions) + return object; + var message = new $root.google.iam.v1.GetPolicyOptions(); + if (object.requestedPolicyVersion != null) + message.requestedPolicyVersion = object.requestedPolicyVersion | 0; + return message; + }; + + /** + * Creates a plain object from a GetPolicyOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {google.iam.v1.GetPolicyOptions} message GetPolicyOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetPolicyOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.requestedPolicyVersion = 0; + if (message.requestedPolicyVersion != null && message.hasOwnProperty("requestedPolicyVersion")) + object.requestedPolicyVersion = message.requestedPolicyVersion; + return object; + }; + + /** + * Converts this GetPolicyOptions to JSON. + * @function toJSON + * @memberof google.iam.v1.GetPolicyOptions + * @instance + * @returns {Object.} JSON object + */ + GetPolicyOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetPolicyOptions + * @function getTypeUrl + * @memberof google.iam.v1.GetPolicyOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetPolicyOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.GetPolicyOptions"; + }; + + return GetPolicyOptions; + })(); + + v1.Policy = (function() { + + /** + * Properties of a Policy. + * @memberof google.iam.v1 + * @interface IPolicy + * @property {number|null} [version] Policy version + * @property {Array.|null} [bindings] Policy bindings + * @property {Array.|null} [auditConfigs] Policy auditConfigs + * @property {Uint8Array|null} [etag] Policy etag + */ + + /** + * Constructs a new Policy. + * @memberof google.iam.v1 + * @classdesc Represents a Policy. + * @implements IPolicy + * @constructor + * @param {google.iam.v1.IPolicy=} [properties] Properties to set + */ + function Policy(properties) { + this.bindings = []; + this.auditConfigs = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Policy version. + * @member {number} version + * @memberof google.iam.v1.Policy + * @instance + */ + Policy.prototype.version = 0; + + /** + * Policy bindings. + * @member {Array.} bindings + * @memberof google.iam.v1.Policy + * @instance + */ + Policy.prototype.bindings = $util.emptyArray; + + /** + * Policy auditConfigs. + * @member {Array.} auditConfigs + * @memberof google.iam.v1.Policy + * @instance + */ + Policy.prototype.auditConfigs = $util.emptyArray; + + /** + * Policy etag. + * @member {Uint8Array} etag + * @memberof google.iam.v1.Policy + * @instance + */ + Policy.prototype.etag = $util.newBuffer([]); + + /** + * Creates a new Policy instance using the specified properties. + * @function create + * @memberof google.iam.v1.Policy + * @static + * @param {google.iam.v1.IPolicy=} [properties] Properties to set + * @returns {google.iam.v1.Policy} Policy instance + */ + Policy.create = function create(properties) { + return new Policy(properties); + }; + + /** + * Encodes the specified Policy message. Does not implicitly {@link google.iam.v1.Policy.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.Policy + * @static + * @param {google.iam.v1.IPolicy} message Policy message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Policy.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.version != null && Object.hasOwnProperty.call(message, "version")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.version); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 3, wireType 2 =*/26).bytes(message.etag); + if (message.bindings != null && message.bindings.length) + for (var i = 0; i < message.bindings.length; ++i) + $root.google.iam.v1.Binding.encode(message.bindings[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.auditConfigs != null && message.auditConfigs.length) + for (var i = 0; i < message.auditConfigs.length; ++i) + $root.google.iam.v1.AuditConfig.encode(message.auditConfigs[i], writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Policy message, length delimited. Does not implicitly {@link google.iam.v1.Policy.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.Policy + * @static + * @param {google.iam.v1.IPolicy} message Policy message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Policy.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Policy message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.Policy + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.Policy} Policy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Policy.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.iam.v1.Policy(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.version = reader.int32(); + break; + } + case 4: { + if (!(message.bindings && message.bindings.length)) + message.bindings = []; + message.bindings.push($root.google.iam.v1.Binding.decode(reader, reader.uint32())); + break; + } + case 6: { + if (!(message.auditConfigs && message.auditConfigs.length)) + message.auditConfigs = []; + message.auditConfigs.push($root.google.iam.v1.AuditConfig.decode(reader, reader.uint32())); + break; + } + case 3: { + message.etag = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Policy message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.Policy + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.Policy} Policy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Policy.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Policy message. + * @function verify + * @memberof google.iam.v1.Policy + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Policy.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.version != null && message.hasOwnProperty("version")) + if (!$util.isInteger(message.version)) + return "version: integer expected"; + if (message.bindings != null && message.hasOwnProperty("bindings")) { + if (!Array.isArray(message.bindings)) + return "bindings: array expected"; + for (var i = 0; i < message.bindings.length; ++i) { + var error = $root.google.iam.v1.Binding.verify(message.bindings[i]); + if (error) + return "bindings." + error; + } + } + if (message.auditConfigs != null && message.hasOwnProperty("auditConfigs")) { + if (!Array.isArray(message.auditConfigs)) + return "auditConfigs: array expected"; + for (var i = 0; i < message.auditConfigs.length; ++i) { + var error = $root.google.iam.v1.AuditConfig.verify(message.auditConfigs[i]); + if (error) + return "auditConfigs." + error; + } + } + if (message.etag != null && message.hasOwnProperty("etag")) + if (!(message.etag && typeof message.etag.length === "number" || $util.isString(message.etag))) + return "etag: buffer expected"; + return null; + }; + + /** + * Creates a Policy message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.Policy + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.Policy} Policy + */ + Policy.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.Policy) + return object; + var message = new $root.google.iam.v1.Policy(); + if (object.version != null) + message.version = object.version | 0; + if (object.bindings) { + if (!Array.isArray(object.bindings)) + throw TypeError(".google.iam.v1.Policy.bindings: array expected"); + message.bindings = []; + for (var i = 0; i < object.bindings.length; ++i) { + if (typeof object.bindings[i] !== "object") + throw TypeError(".google.iam.v1.Policy.bindings: object expected"); + message.bindings[i] = $root.google.iam.v1.Binding.fromObject(object.bindings[i]); + } + } + if (object.auditConfigs) { + if (!Array.isArray(object.auditConfigs)) + throw TypeError(".google.iam.v1.Policy.auditConfigs: array expected"); + message.auditConfigs = []; + for (var i = 0; i < object.auditConfigs.length; ++i) { + if (typeof object.auditConfigs[i] !== "object") + throw TypeError(".google.iam.v1.Policy.auditConfigs: object expected"); + message.auditConfigs[i] = $root.google.iam.v1.AuditConfig.fromObject(object.auditConfigs[i]); + } + } + if (object.etag != null) + if (typeof object.etag === "string") + $util.base64.decode(object.etag, message.etag = $util.newBuffer($util.base64.length(object.etag)), 0); + else if (object.etag.length >= 0) + message.etag = object.etag; + return message; + }; + + /** + * Creates a plain object from a Policy message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.Policy + * @static + * @param {google.iam.v1.Policy} message Policy + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Policy.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.bindings = []; + object.auditConfigs = []; + } + if (options.defaults) { + object.version = 0; + if (options.bytes === String) + object.etag = ""; + else { + object.etag = []; + if (options.bytes !== Array) + object.etag = $util.newBuffer(object.etag); + } + } + if (message.version != null && message.hasOwnProperty("version")) + object.version = message.version; + if (message.etag != null && message.hasOwnProperty("etag")) + object.etag = options.bytes === String ? $util.base64.encode(message.etag, 0, message.etag.length) : options.bytes === Array ? Array.prototype.slice.call(message.etag) : message.etag; + if (message.bindings && message.bindings.length) { + object.bindings = []; + for (var j = 0; j < message.bindings.length; ++j) + object.bindings[j] = $root.google.iam.v1.Binding.toObject(message.bindings[j], options); + } + if (message.auditConfigs && message.auditConfigs.length) { + object.auditConfigs = []; + for (var j = 0; j < message.auditConfigs.length; ++j) + object.auditConfigs[j] = $root.google.iam.v1.AuditConfig.toObject(message.auditConfigs[j], options); + } + return object; + }; + + /** + * Converts this Policy to JSON. + * @function toJSON + * @memberof google.iam.v1.Policy + * @instance + * @returns {Object.} JSON object + */ + Policy.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Policy + * @function getTypeUrl + * @memberof google.iam.v1.Policy + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Policy.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.Policy"; + }; + + return Policy; + })(); + + v1.Binding = (function() { + + /** + * Properties of a Binding. + * @memberof google.iam.v1 + * @interface IBinding + * @property {string|null} [role] Binding role + * @property {Array.|null} [members] Binding members + * @property {google.type.IExpr|null} [condition] Binding condition + */ + + /** + * Constructs a new Binding. + * @memberof google.iam.v1 + * @classdesc Represents a Binding. + * @implements IBinding + * @constructor + * @param {google.iam.v1.IBinding=} [properties] Properties to set + */ + function Binding(properties) { + this.members = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Binding role. + * @member {string} role + * @memberof google.iam.v1.Binding + * @instance + */ + Binding.prototype.role = ""; + + /** + * Binding members. + * @member {Array.} members + * @memberof google.iam.v1.Binding + * @instance + */ + Binding.prototype.members = $util.emptyArray; + + /** + * Binding condition. + * @member {google.type.IExpr|null|undefined} condition + * @memberof google.iam.v1.Binding + * @instance + */ + Binding.prototype.condition = null; + + /** + * Creates a new Binding instance using the specified properties. + * @function create + * @memberof google.iam.v1.Binding + * @static + * @param {google.iam.v1.IBinding=} [properties] Properties to set + * @returns {google.iam.v1.Binding} Binding instance + */ + Binding.create = function create(properties) { + return new Binding(properties); + }; + + /** + * Encodes the specified Binding message. Does not implicitly {@link google.iam.v1.Binding.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.Binding + * @static + * @param {google.iam.v1.IBinding} message Binding message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Binding.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.role != null && Object.hasOwnProperty.call(message, "role")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.role); + if (message.members != null && message.members.length) + for (var i = 0; i < message.members.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.members[i]); + if (message.condition != null && Object.hasOwnProperty.call(message, "condition")) + $root.google.type.Expr.encode(message.condition, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified Binding message, length delimited. Does not implicitly {@link google.iam.v1.Binding.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.Binding + * @static + * @param {google.iam.v1.IBinding} message Binding message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Binding.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Binding message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.Binding + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.Binding} Binding + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Binding.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.iam.v1.Binding(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.role = reader.string(); + break; + } + case 2: { + if (!(message.members && message.members.length)) + message.members = []; + message.members.push(reader.string()); + break; + } + case 3: { + message.condition = $root.google.type.Expr.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Binding message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.Binding + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.Binding} Binding + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Binding.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Binding message. + * @function verify + * @memberof google.iam.v1.Binding + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Binding.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.role != null && message.hasOwnProperty("role")) + if (!$util.isString(message.role)) + return "role: string expected"; + if (message.members != null && message.hasOwnProperty("members")) { + if (!Array.isArray(message.members)) + return "members: array expected"; + for (var i = 0; i < message.members.length; ++i) + if (!$util.isString(message.members[i])) + return "members: string[] expected"; + } + if (message.condition != null && message.hasOwnProperty("condition")) { + var error = $root.google.type.Expr.verify(message.condition); + if (error) + return "condition." + error; + } + return null; + }; + + /** + * Creates a Binding message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.Binding + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.Binding} Binding + */ + Binding.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.Binding) + return object; + var message = new $root.google.iam.v1.Binding(); + if (object.role != null) + message.role = String(object.role); + if (object.members) { + if (!Array.isArray(object.members)) + throw TypeError(".google.iam.v1.Binding.members: array expected"); + message.members = []; + for (var i = 0; i < object.members.length; ++i) + message.members[i] = String(object.members[i]); + } + if (object.condition != null) { + if (typeof object.condition !== "object") + throw TypeError(".google.iam.v1.Binding.condition: object expected"); + message.condition = $root.google.type.Expr.fromObject(object.condition); + } + return message; + }; + + /** + * Creates a plain object from a Binding message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.Binding + * @static + * @param {google.iam.v1.Binding} message Binding + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Binding.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.members = []; + if (options.defaults) { + object.role = ""; + object.condition = null; + } + if (message.role != null && message.hasOwnProperty("role")) + object.role = message.role; + if (message.members && message.members.length) { + object.members = []; + for (var j = 0; j < message.members.length; ++j) + object.members[j] = message.members[j]; + } + if (message.condition != null && message.hasOwnProperty("condition")) + object.condition = $root.google.type.Expr.toObject(message.condition, options); + return object; + }; + + /** + * Converts this Binding to JSON. + * @function toJSON + * @memberof google.iam.v1.Binding + * @instance + * @returns {Object.} JSON object + */ + Binding.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Binding + * @function getTypeUrl + * @memberof google.iam.v1.Binding + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Binding.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.Binding"; + }; + + return Binding; + })(); + + v1.AuditConfig = (function() { + + /** + * Properties of an AuditConfig. + * @memberof google.iam.v1 + * @interface IAuditConfig + * @property {string|null} [service] AuditConfig service + * @property {Array.|null} [auditLogConfigs] AuditConfig auditLogConfigs + */ + + /** + * Constructs a new AuditConfig. + * @memberof google.iam.v1 + * @classdesc Represents an AuditConfig. + * @implements IAuditConfig + * @constructor + * @param {google.iam.v1.IAuditConfig=} [properties] Properties to set + */ + function AuditConfig(properties) { + this.auditLogConfigs = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AuditConfig service. + * @member {string} service + * @memberof google.iam.v1.AuditConfig + * @instance + */ + AuditConfig.prototype.service = ""; + + /** + * AuditConfig auditLogConfigs. + * @member {Array.} auditLogConfigs + * @memberof google.iam.v1.AuditConfig + * @instance + */ + AuditConfig.prototype.auditLogConfigs = $util.emptyArray; + + /** + * Creates a new AuditConfig instance using the specified properties. + * @function create + * @memberof google.iam.v1.AuditConfig + * @static + * @param {google.iam.v1.IAuditConfig=} [properties] Properties to set + * @returns {google.iam.v1.AuditConfig} AuditConfig instance + */ + AuditConfig.create = function create(properties) { + return new AuditConfig(properties); + }; + + /** + * Encodes the specified AuditConfig message. Does not implicitly {@link google.iam.v1.AuditConfig.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.AuditConfig + * @static + * @param {google.iam.v1.IAuditConfig} message AuditConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AuditConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.service != null && Object.hasOwnProperty.call(message, "service")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.service); + if (message.auditLogConfigs != null && message.auditLogConfigs.length) + for (var i = 0; i < message.auditLogConfigs.length; ++i) + $root.google.iam.v1.AuditLogConfig.encode(message.auditLogConfigs[i], writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified AuditConfig message, length delimited. Does not implicitly {@link google.iam.v1.AuditConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.AuditConfig + * @static + * @param {google.iam.v1.IAuditConfig} message AuditConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AuditConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AuditConfig message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.AuditConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.AuditConfig} AuditConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AuditConfig.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.iam.v1.AuditConfig(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.service = reader.string(); + break; + } + case 3: { + if (!(message.auditLogConfigs && message.auditLogConfigs.length)) + message.auditLogConfigs = []; + message.auditLogConfigs.push($root.google.iam.v1.AuditLogConfig.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AuditConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.AuditConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.AuditConfig} AuditConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AuditConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AuditConfig message. + * @function verify + * @memberof google.iam.v1.AuditConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AuditConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.service != null && message.hasOwnProperty("service")) + if (!$util.isString(message.service)) + return "service: string expected"; + if (message.auditLogConfigs != null && message.hasOwnProperty("auditLogConfigs")) { + if (!Array.isArray(message.auditLogConfigs)) + return "auditLogConfigs: array expected"; + for (var i = 0; i < message.auditLogConfigs.length; ++i) { + var error = $root.google.iam.v1.AuditLogConfig.verify(message.auditLogConfigs[i]); + if (error) + return "auditLogConfigs." + error; + } + } + return null; + }; + + /** + * Creates an AuditConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.AuditConfig + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.AuditConfig} AuditConfig + */ + AuditConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.AuditConfig) + return object; + var message = new $root.google.iam.v1.AuditConfig(); + if (object.service != null) + message.service = String(object.service); + if (object.auditLogConfigs) { + if (!Array.isArray(object.auditLogConfigs)) + throw TypeError(".google.iam.v1.AuditConfig.auditLogConfigs: array expected"); + message.auditLogConfigs = []; + for (var i = 0; i < object.auditLogConfigs.length; ++i) { + if (typeof object.auditLogConfigs[i] !== "object") + throw TypeError(".google.iam.v1.AuditConfig.auditLogConfigs: object expected"); + message.auditLogConfigs[i] = $root.google.iam.v1.AuditLogConfig.fromObject(object.auditLogConfigs[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an AuditConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.AuditConfig + * @static + * @param {google.iam.v1.AuditConfig} message AuditConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AuditConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.auditLogConfigs = []; + if (options.defaults) + object.service = ""; + if (message.service != null && message.hasOwnProperty("service")) + object.service = message.service; + if (message.auditLogConfigs && message.auditLogConfigs.length) { + object.auditLogConfigs = []; + for (var j = 0; j < message.auditLogConfigs.length; ++j) + object.auditLogConfigs[j] = $root.google.iam.v1.AuditLogConfig.toObject(message.auditLogConfigs[j], options); + } + return object; + }; + + /** + * Converts this AuditConfig to JSON. + * @function toJSON + * @memberof google.iam.v1.AuditConfig + * @instance + * @returns {Object.} JSON object + */ + AuditConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AuditConfig + * @function getTypeUrl + * @memberof google.iam.v1.AuditConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AuditConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.AuditConfig"; + }; + + return AuditConfig; + })(); + + v1.AuditLogConfig = (function() { + + /** + * Properties of an AuditLogConfig. + * @memberof google.iam.v1 + * @interface IAuditLogConfig + * @property {google.iam.v1.AuditLogConfig.LogType|null} [logType] AuditLogConfig logType + * @property {Array.|null} [exemptedMembers] AuditLogConfig exemptedMembers + */ + + /** + * Constructs a new AuditLogConfig. + * @memberof google.iam.v1 + * @classdesc Represents an AuditLogConfig. + * @implements IAuditLogConfig + * @constructor + * @param {google.iam.v1.IAuditLogConfig=} [properties] Properties to set + */ + function AuditLogConfig(properties) { + this.exemptedMembers = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AuditLogConfig logType. + * @member {google.iam.v1.AuditLogConfig.LogType} logType + * @memberof google.iam.v1.AuditLogConfig + * @instance + */ + AuditLogConfig.prototype.logType = 0; + + /** + * AuditLogConfig exemptedMembers. + * @member {Array.} exemptedMembers + * @memberof google.iam.v1.AuditLogConfig + * @instance + */ + AuditLogConfig.prototype.exemptedMembers = $util.emptyArray; + + /** + * Creates a new AuditLogConfig instance using the specified properties. + * @function create + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {google.iam.v1.IAuditLogConfig=} [properties] Properties to set + * @returns {google.iam.v1.AuditLogConfig} AuditLogConfig instance + */ + AuditLogConfig.create = function create(properties) { + return new AuditLogConfig(properties); + }; + + /** + * Encodes the specified AuditLogConfig message. Does not implicitly {@link google.iam.v1.AuditLogConfig.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {google.iam.v1.IAuditLogConfig} message AuditLogConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AuditLogConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.logType != null && Object.hasOwnProperty.call(message, "logType")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.logType); + if (message.exemptedMembers != null && message.exemptedMembers.length) + for (var i = 0; i < message.exemptedMembers.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.exemptedMembers[i]); + return writer; + }; + + /** + * Encodes the specified AuditLogConfig message, length delimited. Does not implicitly {@link google.iam.v1.AuditLogConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {google.iam.v1.IAuditLogConfig} message AuditLogConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AuditLogConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AuditLogConfig message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.AuditLogConfig} AuditLogConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AuditLogConfig.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.iam.v1.AuditLogConfig(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.logType = reader.int32(); + break; + } + case 2: { + if (!(message.exemptedMembers && message.exemptedMembers.length)) + message.exemptedMembers = []; + message.exemptedMembers.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AuditLogConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.AuditLogConfig} AuditLogConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AuditLogConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AuditLogConfig message. + * @function verify + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AuditLogConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.logType != null && message.hasOwnProperty("logType")) + switch (message.logType) { + default: + return "logType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.exemptedMembers != null && message.hasOwnProperty("exemptedMembers")) { + if (!Array.isArray(message.exemptedMembers)) + return "exemptedMembers: array expected"; + for (var i = 0; i < message.exemptedMembers.length; ++i) + if (!$util.isString(message.exemptedMembers[i])) + return "exemptedMembers: string[] expected"; + } + return null; + }; + + /** + * Creates an AuditLogConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.AuditLogConfig} AuditLogConfig + */ + AuditLogConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.AuditLogConfig) + return object; + var message = new $root.google.iam.v1.AuditLogConfig(); + switch (object.logType) { + default: + if (typeof object.logType === "number") { + message.logType = object.logType; + break; + } + break; + case "LOG_TYPE_UNSPECIFIED": + case 0: + message.logType = 0; + break; + case "ADMIN_READ": + case 1: + message.logType = 1; + break; + case "DATA_WRITE": + case 2: + message.logType = 2; + break; + case "DATA_READ": + case 3: + message.logType = 3; + break; + } + if (object.exemptedMembers) { + if (!Array.isArray(object.exemptedMembers)) + throw TypeError(".google.iam.v1.AuditLogConfig.exemptedMembers: array expected"); + message.exemptedMembers = []; + for (var i = 0; i < object.exemptedMembers.length; ++i) + message.exemptedMembers[i] = String(object.exemptedMembers[i]); + } + return message; + }; + + /** + * Creates a plain object from an AuditLogConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {google.iam.v1.AuditLogConfig} message AuditLogConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AuditLogConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.exemptedMembers = []; + if (options.defaults) + object.logType = options.enums === String ? "LOG_TYPE_UNSPECIFIED" : 0; + if (message.logType != null && message.hasOwnProperty("logType")) + object.logType = options.enums === String ? $root.google.iam.v1.AuditLogConfig.LogType[message.logType] === undefined ? message.logType : $root.google.iam.v1.AuditLogConfig.LogType[message.logType] : message.logType; + if (message.exemptedMembers && message.exemptedMembers.length) { + object.exemptedMembers = []; + for (var j = 0; j < message.exemptedMembers.length; ++j) + object.exemptedMembers[j] = message.exemptedMembers[j]; + } + return object; + }; + + /** + * Converts this AuditLogConfig to JSON. + * @function toJSON + * @memberof google.iam.v1.AuditLogConfig + * @instance + * @returns {Object.} JSON object + */ + AuditLogConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AuditLogConfig + * @function getTypeUrl + * @memberof google.iam.v1.AuditLogConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AuditLogConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.AuditLogConfig"; + }; + + /** + * LogType enum. + * @name google.iam.v1.AuditLogConfig.LogType + * @enum {number} + * @property {number} LOG_TYPE_UNSPECIFIED=0 LOG_TYPE_UNSPECIFIED value + * @property {number} ADMIN_READ=1 ADMIN_READ value + * @property {number} DATA_WRITE=2 DATA_WRITE value + * @property {number} DATA_READ=3 DATA_READ value + */ + AuditLogConfig.LogType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LOG_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "ADMIN_READ"] = 1; + values[valuesById[2] = "DATA_WRITE"] = 2; + values[valuesById[3] = "DATA_READ"] = 3; + return values; + })(); + + return AuditLogConfig; + })(); + + v1.PolicyDelta = (function() { + + /** + * Properties of a PolicyDelta. + * @memberof google.iam.v1 + * @interface IPolicyDelta + * @property {Array.|null} [bindingDeltas] PolicyDelta bindingDeltas + * @property {Array.|null} [auditConfigDeltas] PolicyDelta auditConfigDeltas + */ + + /** + * Constructs a new PolicyDelta. + * @memberof google.iam.v1 + * @classdesc Represents a PolicyDelta. + * @implements IPolicyDelta + * @constructor + * @param {google.iam.v1.IPolicyDelta=} [properties] Properties to set + */ + function PolicyDelta(properties) { + this.bindingDeltas = []; + this.auditConfigDeltas = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PolicyDelta bindingDeltas. + * @member {Array.} bindingDeltas + * @memberof google.iam.v1.PolicyDelta + * @instance + */ + PolicyDelta.prototype.bindingDeltas = $util.emptyArray; + + /** + * PolicyDelta auditConfigDeltas. + * @member {Array.} auditConfigDeltas + * @memberof google.iam.v1.PolicyDelta + * @instance + */ + PolicyDelta.prototype.auditConfigDeltas = $util.emptyArray; + + /** + * Creates a new PolicyDelta instance using the specified properties. + * @function create + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {google.iam.v1.IPolicyDelta=} [properties] Properties to set + * @returns {google.iam.v1.PolicyDelta} PolicyDelta instance + */ + PolicyDelta.create = function create(properties) { + return new PolicyDelta(properties); + }; + + /** + * Encodes the specified PolicyDelta message. Does not implicitly {@link google.iam.v1.PolicyDelta.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {google.iam.v1.IPolicyDelta} message PolicyDelta message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PolicyDelta.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.bindingDeltas != null && message.bindingDeltas.length) + for (var i = 0; i < message.bindingDeltas.length; ++i) + $root.google.iam.v1.BindingDelta.encode(message.bindingDeltas[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.auditConfigDeltas != null && message.auditConfigDeltas.length) + for (var i = 0; i < message.auditConfigDeltas.length; ++i) + $root.google.iam.v1.AuditConfigDelta.encode(message.auditConfigDeltas[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PolicyDelta message, length delimited. Does not implicitly {@link google.iam.v1.PolicyDelta.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {google.iam.v1.IPolicyDelta} message PolicyDelta message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PolicyDelta.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PolicyDelta message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.PolicyDelta} PolicyDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PolicyDelta.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.iam.v1.PolicyDelta(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.bindingDeltas && message.bindingDeltas.length)) + message.bindingDeltas = []; + message.bindingDeltas.push($root.google.iam.v1.BindingDelta.decode(reader, reader.uint32())); + break; + } + case 2: { + if (!(message.auditConfigDeltas && message.auditConfigDeltas.length)) + message.auditConfigDeltas = []; + message.auditConfigDeltas.push($root.google.iam.v1.AuditConfigDelta.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PolicyDelta message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.PolicyDelta} PolicyDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PolicyDelta.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PolicyDelta message. + * @function verify + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PolicyDelta.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.bindingDeltas != null && message.hasOwnProperty("bindingDeltas")) { + if (!Array.isArray(message.bindingDeltas)) + return "bindingDeltas: array expected"; + for (var i = 0; i < message.bindingDeltas.length; ++i) { + var error = $root.google.iam.v1.BindingDelta.verify(message.bindingDeltas[i]); + if (error) + return "bindingDeltas." + error; + } + } + if (message.auditConfigDeltas != null && message.hasOwnProperty("auditConfigDeltas")) { + if (!Array.isArray(message.auditConfigDeltas)) + return "auditConfigDeltas: array expected"; + for (var i = 0; i < message.auditConfigDeltas.length; ++i) { + var error = $root.google.iam.v1.AuditConfigDelta.verify(message.auditConfigDeltas[i]); + if (error) + return "auditConfigDeltas." + error; + } + } + return null; + }; + + /** + * Creates a PolicyDelta message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.PolicyDelta} PolicyDelta + */ + PolicyDelta.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.PolicyDelta) + return object; + var message = new $root.google.iam.v1.PolicyDelta(); + if (object.bindingDeltas) { + if (!Array.isArray(object.bindingDeltas)) + throw TypeError(".google.iam.v1.PolicyDelta.bindingDeltas: array expected"); + message.bindingDeltas = []; + for (var i = 0; i < object.bindingDeltas.length; ++i) { + if (typeof object.bindingDeltas[i] !== "object") + throw TypeError(".google.iam.v1.PolicyDelta.bindingDeltas: object expected"); + message.bindingDeltas[i] = $root.google.iam.v1.BindingDelta.fromObject(object.bindingDeltas[i]); + } + } + if (object.auditConfigDeltas) { + if (!Array.isArray(object.auditConfigDeltas)) + throw TypeError(".google.iam.v1.PolicyDelta.auditConfigDeltas: array expected"); + message.auditConfigDeltas = []; + for (var i = 0; i < object.auditConfigDeltas.length; ++i) { + if (typeof object.auditConfigDeltas[i] !== "object") + throw TypeError(".google.iam.v1.PolicyDelta.auditConfigDeltas: object expected"); + message.auditConfigDeltas[i] = $root.google.iam.v1.AuditConfigDelta.fromObject(object.auditConfigDeltas[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a PolicyDelta message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {google.iam.v1.PolicyDelta} message PolicyDelta + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PolicyDelta.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.bindingDeltas = []; + object.auditConfigDeltas = []; + } + if (message.bindingDeltas && message.bindingDeltas.length) { + object.bindingDeltas = []; + for (var j = 0; j < message.bindingDeltas.length; ++j) + object.bindingDeltas[j] = $root.google.iam.v1.BindingDelta.toObject(message.bindingDeltas[j], options); + } + if (message.auditConfigDeltas && message.auditConfigDeltas.length) { + object.auditConfigDeltas = []; + for (var j = 0; j < message.auditConfigDeltas.length; ++j) + object.auditConfigDeltas[j] = $root.google.iam.v1.AuditConfigDelta.toObject(message.auditConfigDeltas[j], options); + } + return object; + }; + + /** + * Converts this PolicyDelta to JSON. + * @function toJSON + * @memberof google.iam.v1.PolicyDelta + * @instance + * @returns {Object.} JSON object + */ + PolicyDelta.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PolicyDelta + * @function getTypeUrl + * @memberof google.iam.v1.PolicyDelta + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PolicyDelta.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.PolicyDelta"; + }; + + return PolicyDelta; + })(); + + v1.BindingDelta = (function() { + + /** + * Properties of a BindingDelta. + * @memberof google.iam.v1 + * @interface IBindingDelta + * @property {google.iam.v1.BindingDelta.Action|null} [action] BindingDelta action + * @property {string|null} [role] BindingDelta role + * @property {string|null} [member] BindingDelta member + * @property {google.type.IExpr|null} [condition] BindingDelta condition + */ + + /** + * Constructs a new BindingDelta. + * @memberof google.iam.v1 + * @classdesc Represents a BindingDelta. + * @implements IBindingDelta + * @constructor + * @param {google.iam.v1.IBindingDelta=} [properties] Properties to set + */ + function BindingDelta(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BindingDelta action. + * @member {google.iam.v1.BindingDelta.Action} action + * @memberof google.iam.v1.BindingDelta + * @instance + */ + BindingDelta.prototype.action = 0; + + /** + * BindingDelta role. + * @member {string} role + * @memberof google.iam.v1.BindingDelta + * @instance + */ + BindingDelta.prototype.role = ""; + + /** + * BindingDelta member. + * @member {string} member + * @memberof google.iam.v1.BindingDelta + * @instance + */ + BindingDelta.prototype.member = ""; + + /** + * BindingDelta condition. + * @member {google.type.IExpr|null|undefined} condition + * @memberof google.iam.v1.BindingDelta + * @instance + */ + BindingDelta.prototype.condition = null; + + /** + * Creates a new BindingDelta instance using the specified properties. + * @function create + * @memberof google.iam.v1.BindingDelta + * @static + * @param {google.iam.v1.IBindingDelta=} [properties] Properties to set + * @returns {google.iam.v1.BindingDelta} BindingDelta instance + */ + BindingDelta.create = function create(properties) { + return new BindingDelta(properties); + }; + + /** + * Encodes the specified BindingDelta message. Does not implicitly {@link google.iam.v1.BindingDelta.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.BindingDelta + * @static + * @param {google.iam.v1.IBindingDelta} message BindingDelta message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BindingDelta.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.action != null && Object.hasOwnProperty.call(message, "action")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.action); + if (message.role != null && Object.hasOwnProperty.call(message, "role")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.role); + if (message.member != null && Object.hasOwnProperty.call(message, "member")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.member); + if (message.condition != null && Object.hasOwnProperty.call(message, "condition")) + $root.google.type.Expr.encode(message.condition, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BindingDelta message, length delimited. Does not implicitly {@link google.iam.v1.BindingDelta.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.BindingDelta + * @static + * @param {google.iam.v1.IBindingDelta} message BindingDelta message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BindingDelta.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BindingDelta message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.BindingDelta + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.BindingDelta} BindingDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BindingDelta.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.iam.v1.BindingDelta(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.action = reader.int32(); + break; + } + case 2: { + message.role = reader.string(); + break; + } + case 3: { + message.member = reader.string(); + break; + } + case 4: { + message.condition = $root.google.type.Expr.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BindingDelta message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.BindingDelta + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.BindingDelta} BindingDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BindingDelta.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BindingDelta message. + * @function verify + * @memberof google.iam.v1.BindingDelta + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BindingDelta.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.action != null && message.hasOwnProperty("action")) + switch (message.action) { + default: + return "action: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.role != null && message.hasOwnProperty("role")) + if (!$util.isString(message.role)) + return "role: string expected"; + if (message.member != null && message.hasOwnProperty("member")) + if (!$util.isString(message.member)) + return "member: string expected"; + if (message.condition != null && message.hasOwnProperty("condition")) { + var error = $root.google.type.Expr.verify(message.condition); + if (error) + return "condition." + error; + } + return null; + }; + + /** + * Creates a BindingDelta message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.BindingDelta + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.BindingDelta} BindingDelta + */ + BindingDelta.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.BindingDelta) + return object; + var message = new $root.google.iam.v1.BindingDelta(); + switch (object.action) { + default: + if (typeof object.action === "number") { + message.action = object.action; + break; + } + break; + case "ACTION_UNSPECIFIED": + case 0: + message.action = 0; + break; + case "ADD": + case 1: + message.action = 1; + break; + case "REMOVE": + case 2: + message.action = 2; + break; + } + if (object.role != null) + message.role = String(object.role); + if (object.member != null) + message.member = String(object.member); + if (object.condition != null) { + if (typeof object.condition !== "object") + throw TypeError(".google.iam.v1.BindingDelta.condition: object expected"); + message.condition = $root.google.type.Expr.fromObject(object.condition); + } + return message; + }; + + /** + * Creates a plain object from a BindingDelta message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.BindingDelta + * @static + * @param {google.iam.v1.BindingDelta} message BindingDelta + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BindingDelta.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.action = options.enums === String ? "ACTION_UNSPECIFIED" : 0; + object.role = ""; + object.member = ""; + object.condition = null; + } + if (message.action != null && message.hasOwnProperty("action")) + object.action = options.enums === String ? $root.google.iam.v1.BindingDelta.Action[message.action] === undefined ? message.action : $root.google.iam.v1.BindingDelta.Action[message.action] : message.action; + if (message.role != null && message.hasOwnProperty("role")) + object.role = message.role; + if (message.member != null && message.hasOwnProperty("member")) + object.member = message.member; + if (message.condition != null && message.hasOwnProperty("condition")) + object.condition = $root.google.type.Expr.toObject(message.condition, options); + return object; + }; + + /** + * Converts this BindingDelta to JSON. + * @function toJSON + * @memberof google.iam.v1.BindingDelta + * @instance + * @returns {Object.} JSON object + */ + BindingDelta.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BindingDelta + * @function getTypeUrl + * @memberof google.iam.v1.BindingDelta + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BindingDelta.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.BindingDelta"; + }; + + /** + * Action enum. + * @name google.iam.v1.BindingDelta.Action + * @enum {number} + * @property {number} ACTION_UNSPECIFIED=0 ACTION_UNSPECIFIED value + * @property {number} ADD=1 ADD value + * @property {number} REMOVE=2 REMOVE value + */ + BindingDelta.Action = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ACTION_UNSPECIFIED"] = 0; + values[valuesById[1] = "ADD"] = 1; + values[valuesById[2] = "REMOVE"] = 2; + return values; + })(); + + return BindingDelta; + })(); + + v1.AuditConfigDelta = (function() { + + /** + * Properties of an AuditConfigDelta. + * @memberof google.iam.v1 + * @interface IAuditConfigDelta + * @property {google.iam.v1.AuditConfigDelta.Action|null} [action] AuditConfigDelta action + * @property {string|null} [service] AuditConfigDelta service + * @property {string|null} [exemptedMember] AuditConfigDelta exemptedMember + * @property {string|null} [logType] AuditConfigDelta logType + */ + + /** + * Constructs a new AuditConfigDelta. + * @memberof google.iam.v1 + * @classdesc Represents an AuditConfigDelta. + * @implements IAuditConfigDelta + * @constructor + * @param {google.iam.v1.IAuditConfigDelta=} [properties] Properties to set + */ + function AuditConfigDelta(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * AuditConfigDelta action. + * @member {google.iam.v1.AuditConfigDelta.Action} action + * @memberof google.iam.v1.AuditConfigDelta + * @instance + */ + AuditConfigDelta.prototype.action = 0; + + /** + * AuditConfigDelta service. + * @member {string} service + * @memberof google.iam.v1.AuditConfigDelta + * @instance + */ + AuditConfigDelta.prototype.service = ""; + + /** + * AuditConfigDelta exemptedMember. + * @member {string} exemptedMember + * @memberof google.iam.v1.AuditConfigDelta + * @instance + */ + AuditConfigDelta.prototype.exemptedMember = ""; + + /** + * AuditConfigDelta logType. + * @member {string} logType + * @memberof google.iam.v1.AuditConfigDelta + * @instance + */ + AuditConfigDelta.prototype.logType = ""; + + /** + * Creates a new AuditConfigDelta instance using the specified properties. + * @function create + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {google.iam.v1.IAuditConfigDelta=} [properties] Properties to set + * @returns {google.iam.v1.AuditConfigDelta} AuditConfigDelta instance + */ + AuditConfigDelta.create = function create(properties) { + return new AuditConfigDelta(properties); + }; + + /** + * Encodes the specified AuditConfigDelta message. Does not implicitly {@link google.iam.v1.AuditConfigDelta.verify|verify} messages. + * @function encode + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {google.iam.v1.IAuditConfigDelta} message AuditConfigDelta message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AuditConfigDelta.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.action != null && Object.hasOwnProperty.call(message, "action")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.action); + if (message.service != null && Object.hasOwnProperty.call(message, "service")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.service); + if (message.exemptedMember != null && Object.hasOwnProperty.call(message, "exemptedMember")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.exemptedMember); + if (message.logType != null && Object.hasOwnProperty.call(message, "logType")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.logType); + return writer; + }; + + /** + * Encodes the specified AuditConfigDelta message, length delimited. Does not implicitly {@link google.iam.v1.AuditConfigDelta.verify|verify} messages. + * @function encodeDelimited + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {google.iam.v1.IAuditConfigDelta} message AuditConfigDelta message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AuditConfigDelta.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AuditConfigDelta message from the specified reader or buffer. + * @function decode + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.iam.v1.AuditConfigDelta} AuditConfigDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AuditConfigDelta.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.iam.v1.AuditConfigDelta(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.action = reader.int32(); + break; + } + case 2: { + message.service = reader.string(); + break; + } + case 3: { + message.exemptedMember = reader.string(); + break; + } + case 4: { + message.logType = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an AuditConfigDelta message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.iam.v1.AuditConfigDelta} AuditConfigDelta + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AuditConfigDelta.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AuditConfigDelta message. + * @function verify + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AuditConfigDelta.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.action != null && message.hasOwnProperty("action")) + switch (message.action) { + default: + return "action: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.service != null && message.hasOwnProperty("service")) + if (!$util.isString(message.service)) + return "service: string expected"; + if (message.exemptedMember != null && message.hasOwnProperty("exemptedMember")) + if (!$util.isString(message.exemptedMember)) + return "exemptedMember: string expected"; + if (message.logType != null && message.hasOwnProperty("logType")) + if (!$util.isString(message.logType)) + return "logType: string expected"; + return null; + }; + + /** + * Creates an AuditConfigDelta message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {Object.} object Plain object + * @returns {google.iam.v1.AuditConfigDelta} AuditConfigDelta + */ + AuditConfigDelta.fromObject = function fromObject(object) { + if (object instanceof $root.google.iam.v1.AuditConfigDelta) + return object; + var message = new $root.google.iam.v1.AuditConfigDelta(); + switch (object.action) { + default: + if (typeof object.action === "number") { + message.action = object.action; + break; + } + break; + case "ACTION_UNSPECIFIED": + case 0: + message.action = 0; + break; + case "ADD": + case 1: + message.action = 1; + break; + case "REMOVE": + case 2: + message.action = 2; + break; + } + if (object.service != null) + message.service = String(object.service); + if (object.exemptedMember != null) + message.exemptedMember = String(object.exemptedMember); + if (object.logType != null) + message.logType = String(object.logType); + return message; + }; + + /** + * Creates a plain object from an AuditConfigDelta message. Also converts values to other types if specified. + * @function toObject + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {google.iam.v1.AuditConfigDelta} message AuditConfigDelta + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AuditConfigDelta.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.action = options.enums === String ? "ACTION_UNSPECIFIED" : 0; + object.service = ""; + object.exemptedMember = ""; + object.logType = ""; + } + if (message.action != null && message.hasOwnProperty("action")) + object.action = options.enums === String ? $root.google.iam.v1.AuditConfigDelta.Action[message.action] === undefined ? message.action : $root.google.iam.v1.AuditConfigDelta.Action[message.action] : message.action; + if (message.service != null && message.hasOwnProperty("service")) + object.service = message.service; + if (message.exemptedMember != null && message.hasOwnProperty("exemptedMember")) + object.exemptedMember = message.exemptedMember; + if (message.logType != null && message.hasOwnProperty("logType")) + object.logType = message.logType; + return object; + }; + + /** + * Converts this AuditConfigDelta to JSON. + * @function toJSON + * @memberof google.iam.v1.AuditConfigDelta + * @instance + * @returns {Object.} JSON object + */ + AuditConfigDelta.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AuditConfigDelta + * @function getTypeUrl + * @memberof google.iam.v1.AuditConfigDelta + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AuditConfigDelta.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.iam.v1.AuditConfigDelta"; + }; + + /** + * Action enum. + * @name google.iam.v1.AuditConfigDelta.Action + * @enum {number} + * @property {number} ACTION_UNSPECIFIED=0 ACTION_UNSPECIFIED value + * @property {number} ADD=1 ADD value + * @property {number} REMOVE=2 REMOVE value + */ + AuditConfigDelta.Action = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ACTION_UNSPECIFIED"] = 0; + values[valuesById[1] = "ADD"] = 1; + values[valuesById[2] = "REMOVE"] = 2; + return values; + })(); + + return AuditConfigDelta; + })(); + + return v1; + })(); + + return iam; + })(); + + google.type = (function() { + + /** + * Namespace type. + * @memberof google + * @namespace + */ + var type = {}; + + type.Expr = (function() { + + /** + * Properties of an Expr. + * @memberof google.type + * @interface IExpr + * @property {string|null} [expression] Expr expression + * @property {string|null} [title] Expr title + * @property {string|null} [description] Expr description + * @property {string|null} [location] Expr location + */ + + /** + * Constructs a new Expr. + * @memberof google.type + * @classdesc Represents an Expr. + * @implements IExpr + * @constructor + * @param {google.type.IExpr=} [properties] Properties to set + */ + function Expr(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Expr expression. + * @member {string} expression + * @memberof google.type.Expr + * @instance + */ + Expr.prototype.expression = ""; + + /** + * Expr title. + * @member {string} title + * @memberof google.type.Expr + * @instance + */ + Expr.prototype.title = ""; + + /** + * Expr description. + * @member {string} description + * @memberof google.type.Expr + * @instance + */ + Expr.prototype.description = ""; + + /** + * Expr location. + * @member {string} location + * @memberof google.type.Expr + * @instance + */ + Expr.prototype.location = ""; + + /** + * Creates a new Expr instance using the specified properties. + * @function create + * @memberof google.type.Expr + * @static + * @param {google.type.IExpr=} [properties] Properties to set + * @returns {google.type.Expr} Expr instance + */ + Expr.create = function create(properties) { + return new Expr(properties); + }; + + /** + * Encodes the specified Expr message. Does not implicitly {@link google.type.Expr.verify|verify} messages. + * @function encode + * @memberof google.type.Expr + * @static + * @param {google.type.IExpr} message Expr message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Expr.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.expression != null && Object.hasOwnProperty.call(message, "expression")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.expression); + if (message.title != null && Object.hasOwnProperty.call(message, "title")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.title); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.description); + if (message.location != null && Object.hasOwnProperty.call(message, "location")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.location); + return writer; + }; + + /** + * Encodes the specified Expr message, length delimited. Does not implicitly {@link google.type.Expr.verify|verify} messages. + * @function encodeDelimited + * @memberof google.type.Expr + * @static + * @param {google.type.IExpr} message Expr message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Expr.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an Expr message from the specified reader or buffer. + * @function decode + * @memberof google.type.Expr + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.type.Expr} Expr + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Expr.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.type.Expr(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.expression = reader.string(); + break; + } + case 2: { + message.title = reader.string(); + break; + } + case 3: { + message.description = reader.string(); + break; + } + case 4: { + message.location = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an Expr message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.type.Expr + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.type.Expr} Expr + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Expr.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an Expr message. + * @function verify + * @memberof google.type.Expr + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Expr.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.expression != null && message.hasOwnProperty("expression")) + if (!$util.isString(message.expression)) + return "expression: string expected"; + if (message.title != null && message.hasOwnProperty("title")) + if (!$util.isString(message.title)) + return "title: string expected"; + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + if (message.location != null && message.hasOwnProperty("location")) + if (!$util.isString(message.location)) + return "location: string expected"; + return null; + }; + + /** + * Creates an Expr message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.type.Expr + * @static + * @param {Object.} object Plain object + * @returns {google.type.Expr} Expr + */ + Expr.fromObject = function fromObject(object) { + if (object instanceof $root.google.type.Expr) + return object; + var message = new $root.google.type.Expr(); + if (object.expression != null) + message.expression = String(object.expression); + if (object.title != null) + message.title = String(object.title); + if (object.description != null) + message.description = String(object.description); + if (object.location != null) + message.location = String(object.location); + return message; + }; + + /** + * Creates a plain object from an Expr message. Also converts values to other types if specified. + * @function toObject + * @memberof google.type.Expr + * @static + * @param {google.type.Expr} message Expr + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Expr.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.expression = ""; + object.title = ""; + object.description = ""; + object.location = ""; + } + if (message.expression != null && message.hasOwnProperty("expression")) + object.expression = message.expression; + if (message.title != null && message.hasOwnProperty("title")) + object.title = message.title; + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + if (message.location != null && message.hasOwnProperty("location")) + object.location = message.location; + return object; + }; + + /** + * Converts this Expr to JSON. + * @function toJSON + * @memberof google.type.Expr + * @instance + * @returns {Object.} JSON object + */ + Expr.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Expr + * @function getTypeUrl + * @memberof google.type.Expr + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Expr.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.type.Expr"; + }; + + return Expr; + })(); + + return type; + })(); + + return google; + })(); + + return $root; +}); diff --git a/handwritten/spanner/protos/protos.json b/handwritten/spanner/protos/protos.json new file mode 100644 index 00000000000..99fcec0aa89 --- /dev/null +++ b/handwritten/spanner/protos/protos.json @@ -0,0 +1,11505 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "options": { + "go_package": "google.golang.org/protobuf/types/descriptorpb", + "java_package": "com.google.protobuf", + "java_outer_classname": "DescriptorProtos", + "csharp_namespace": "Google.Protobuf.Reflection", + "objc_class_prefix": "GPB", + "cc_enable_arenas": true, + "optimize_for": "SPEED" + }, + "nested": { + "Duration": { + "fields": { + "seconds": { + "type": "int64", + "id": 1 + }, + "nanos": { + "type": "int32", + "id": 2 + } + } + }, + "FileDescriptorSet": { + "edition": "proto2", + "fields": { + "file": { + "rule": "repeated", + "type": "FileDescriptorProto", + "id": 1 + } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] + }, + "Edition": { + "edition": "proto2", + "values": { + "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, + "EDITION_PROTO2": 998, + "EDITION_PROTO3": 999, + "EDITION_2023": 1000, + "EDITION_2024": 1001, + "EDITION_1_TEST_ONLY": 1, + "EDITION_2_TEST_ONLY": 2, + "EDITION_99997_TEST_ONLY": 99997, + "EDITION_99998_TEST_ONLY": 99998, + "EDITION_99999_TEST_ONLY": 99999, + "EDITION_MAX": 2147483647 + } + }, + "FileDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "package": { + "type": "string", + "id": 2 + }, + "dependency": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "publicDependency": { + "rule": "repeated", + "type": "int32", + "id": 10 + }, + "weakDependency": { + "rule": "repeated", + "type": "int32", + "id": 11 + }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, + "messageType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 4 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 5 + }, + "service": { + "rule": "repeated", + "type": "ServiceDescriptorProto", + "id": 6 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 7 + }, + "options": { + "type": "FileOptions", + "id": 8 + }, + "sourceCodeInfo": { + "type": "SourceCodeInfo", + "id": 9 + }, + "syntax": { + "type": "string", + "id": 12 + }, + "edition": { + "type": "Edition", + "id": 14 + } + } + }, + "DescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "field": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 2 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 6 + }, + "nestedType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 3 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 4 + }, + "extensionRange": { + "rule": "repeated", + "type": "ExtensionRange", + "id": 5 + }, + "oneofDecl": { + "rule": "repeated", + "type": "OneofDescriptorProto", + "id": 8 + }, + "options": { + "type": "MessageOptions", + "id": 7 + }, + "reservedRange": { + "rule": "repeated", + "type": "ReservedRange", + "id": 9 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 + } + }, + "nested": { + "ExtensionRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "ExtensionRangeOptions", + "id": 3 + } + } + }, + "ReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "ExtensionRangeOptions": { + "edition": "proto2", + "fields": { + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + }, + "declaration": { + "rule": "repeated", + "type": "Declaration", + "id": 2, + "options": { + "retention": "RETENTION_SOURCE" + } + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "verification": { + "type": "VerificationState", + "id": 3, + "options": { + "default": "UNVERIFIED", + "retention": "RETENTION_SOURCE" + } + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "Declaration": { + "fields": { + "number": { + "type": "int32", + "id": 1 + }, + "fullName": { + "type": "string", + "id": 2 + }, + "type": { + "type": "string", + "id": 3 + }, + "reserved": { + "type": "bool", + "id": 5 + }, + "repeated": { + "type": "bool", + "id": 6 + } + }, + "reserved": [ + [ + 4, + 4 + ] + ] + }, + "VerificationState": { + "values": { + "DECLARATION": 0, + "UNVERIFIED": 1 + } + } + } + }, + "FieldDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 3 + }, + "label": { + "type": "Label", + "id": 4 + }, + "type": { + "type": "Type", + "id": 5 + }, + "typeName": { + "type": "string", + "id": 6 + }, + "extendee": { + "type": "string", + "id": 2 + }, + "defaultValue": { + "type": "string", + "id": 7 + }, + "oneofIndex": { + "type": "int32", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "options": { + "type": "FieldOptions", + "id": 8 + }, + "proto3Optional": { + "type": "bool", + "id": 17 + } + }, + "nested": { + "Type": { + "values": { + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Label": { + "values": { + "LABEL_OPTIONAL": 1, + "LABEL_REPEATED": 3, + "LABEL_REQUIRED": 2 + } + } + } + }, + "OneofDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "options": { + "type": "OneofOptions", + "id": 2 + } + } + }, + "EnumDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "rule": "repeated", + "type": "EnumValueDescriptorProto", + "id": 2 + }, + "options": { + "type": "EnumOptions", + "id": 3 + }, + "reservedRange": { + "rule": "repeated", + "type": "EnumReservedRange", + "id": 4 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 + } + }, + "nested": { + "EnumReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "EnumValueDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "EnumValueOptions", + "id": 3 + } + } + }, + "ServiceDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "method": { + "rule": "repeated", + "type": "MethodDescriptorProto", + "id": 2 + }, + "options": { + "type": "ServiceOptions", + "id": 3 + } + }, + "reserved": [ + [ + 4, + 4 + ], + "stream" + ] + }, + "MethodDescriptorProto": { + "edition": "proto2", + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "inputType": { + "type": "string", + "id": 2 + }, + "outputType": { + "type": "string", + "id": 3 + }, + "options": { + "type": "MethodOptions", + "id": 4 + }, + "clientStreaming": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "serverStreaming": { + "type": "bool", + "id": 6, + "options": { + "default": false + } + } + } + }, + "FileOptions": { + "edition": "proto2", + "fields": { + "javaPackage": { + "type": "string", + "id": 1 + }, + "javaOuterClassname": { + "type": "string", + "id": 8 + }, + "javaMultipleFiles": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "javaGenerateEqualsAndHash": { + "type": "bool", + "id": 20, + "options": { + "deprecated": true + } + }, + "javaStringCheckUtf8": { + "type": "bool", + "id": 27, + "options": { + "default": false + } + }, + "optimizeFor": { + "type": "OptimizeMode", + "id": 9, + "options": { + "default": "SPEED" + } + }, + "goPackage": { + "type": "string", + "id": 11 + }, + "ccGenericServices": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "javaGenericServices": { + "type": "bool", + "id": 17, + "options": { + "default": false + } + }, + "pyGenericServices": { + "type": "bool", + "id": 18, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 23, + "options": { + "default": false + } + }, + "ccEnableArenas": { + "type": "bool", + "id": 31, + "options": { + "default": true + } + }, + "objcClassPrefix": { + "type": "string", + "id": 36 + }, + "csharpNamespace": { + "type": "string", + "id": 37 + }, + "swiftPrefix": { + "type": "string", + "id": 39 + }, + "phpClassPrefix": { + "type": "string", + "id": 40 + }, + "phpNamespace": { + "type": "string", + "id": 41 + }, + "phpMetadataNamespace": { + "type": "string", + "id": 44 + }, + "rubyPackage": { + "type": "string", + "id": 45 + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 42, + 42 + ], + "php_generic_services", + [ + 38, + 38 + ] + ], + "nested": { + "OptimizeMode": { + "values": { + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3 + } + } + } + }, + "MessageOptions": { + "edition": "proto2", + "fields": { + "messageSetWireFormat": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "noStandardDescriptorAccessor": { + "type": "bool", + "id": 2, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "mapEntry": { + "type": "bool", + "id": 7 + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 11, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 12 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 5, + 5 + ], + [ + 6, + 6 + ], + [ + 8, + 8 + ], + [ + 9, + 9 + ] + ] + }, + "FieldOptions": { + "edition": "proto2", + "fields": { + "ctype": { + "type": "CType", + "id": 1, + "options": { + "default": "STRING" + } + }, + "packed": { + "type": "bool", + "id": 2 + }, + "jstype": { + "type": "JSType", + "id": 6, + "options": { + "default": "JS_NORMAL" + } + }, + "lazy": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "unverifiedLazy": { + "type": "bool", + "id": 15, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "weak": { + "type": "bool", + "id": 10, + "options": { + "default": false, + "deprecated": true + } + }, + "debugRedact": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "retention": { + "type": "OptionRetention", + "id": 17 + }, + "targets": { + "rule": "repeated", + "type": "OptionTargetType", + "id": 19 + }, + "editionDefaults": { + "rule": "repeated", + "type": "EditionDefault", + "id": 20 + }, + "features": { + "type": "FeatureSet", + "id": 21 + }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 18, + 18 + ] + ], + "nested": { + "CType": { + "values": { + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2 + } + }, + "JSType": { + "values": { + "JS_NORMAL": 0, + "JS_STRING": 1, + "JS_NUMBER": 2 + } + }, + "OptionRetention": { + "values": { + "RETENTION_UNKNOWN": 0, + "RETENTION_RUNTIME": 1, + "RETENTION_SOURCE": 2 + } + }, + "OptionTargetType": { + "values": { + "TARGET_TYPE_UNKNOWN": 0, + "TARGET_TYPE_FILE": 1, + "TARGET_TYPE_EXTENSION_RANGE": 2, + "TARGET_TYPE_MESSAGE": 3, + "TARGET_TYPE_FIELD": 4, + "TARGET_TYPE_ONEOF": 5, + "TARGET_TYPE_ENUM": 6, + "TARGET_TYPE_ENUM_ENTRY": 7, + "TARGET_TYPE_SERVICE": 8, + "TARGET_TYPE_METHOD": 9 + } + }, + "EditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "value": { + "type": "string", + "id": 2 + } + } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } + } + } + }, + "OneofOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 1 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "EnumOptions": { + "edition": "proto2", + "fields": { + "allowAlias": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 6, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 7 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 5, + 5 + ] + ] + }, + "EnumValueOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "features": { + "type": "FeatureSet", + "id": 2 + }, + "debugRedact": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "ServiceOptions": { + "edition": "proto2", + "fields": { + "features": { + "type": "FeatureSet", + "id": 34 + }, + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "MethodOptions": { + "edition": "proto2", + "fields": { + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "idempotencyLevel": { + "type": "IdempotencyLevel", + "id": 34, + "options": { + "default": "IDEMPOTENCY_UNKNOWN" + } + }, + "features": { + "type": "FeatureSet", + "id": 35 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "IdempotencyLevel": { + "values": { + "IDEMPOTENCY_UNKNOWN": 0, + "NO_SIDE_EFFECTS": 1, + "IDEMPOTENT": 2 + } + } + } + }, + "UninterpretedOption": { + "edition": "proto2", + "fields": { + "name": { + "rule": "repeated", + "type": "NamePart", + "id": 2 + }, + "identifierValue": { + "type": "string", + "id": 3 + }, + "positiveIntValue": { + "type": "uint64", + "id": 4 + }, + "negativeIntValue": { + "type": "int64", + "id": 5 + }, + "doubleValue": { + "type": "double", + "id": 6 + }, + "stringValue": { + "type": "bytes", + "id": 7 + }, + "aggregateValue": { + "type": "string", + "id": 8 + } + }, + "nested": { + "NamePart": { + "fields": { + "namePart": { + "rule": "required", + "type": "string", + "id": 1 + }, + "isExtension": { + "rule": "required", + "type": "bool", + "id": 2 + } + } + } + } + }, + "FeatureSet": { + "edition": "proto2", + "fields": { + "fieldPresence": { + "type": "FieldPresence", + "id": 1, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_2023", + "edition_defaults.value": "EXPLICIT" + } + }, + "enumType": { + "type": "EnumType", + "id": 2, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "OPEN" + } + }, + "repeatedFieldEncoding": { + "type": "RepeatedFieldEncoding", + "id": 3, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "PACKED" + } + }, + "utf8Validation": { + "type": "Utf8Validation", + "id": 4, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "VERIFY" + } + }, + "messageEncoding": { + "type": "MessageEncoding", + "id": 5, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", + "edition_defaults.value": "LENGTH_PREFIXED" + } + }, + "jsonFormat": { + "type": "JsonFormat", + "id": 6, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "ALLOW" + } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } + } + }, + "extensions": [ + [ + 1000, + 9994 + ], + [ + 9995, + 9999 + ], + [ + 10000, + 10000 + ] + ], + "reserved": [ + [ + 999, + 999 + ] + ], + "nested": { + "FieldPresence": { + "values": { + "FIELD_PRESENCE_UNKNOWN": 0, + "EXPLICIT": 1, + "IMPLICIT": 2, + "LEGACY_REQUIRED": 3 + } + }, + "EnumType": { + "values": { + "ENUM_TYPE_UNKNOWN": 0, + "OPEN": 1, + "CLOSED": 2 + } + }, + "RepeatedFieldEncoding": { + "values": { + "REPEATED_FIELD_ENCODING_UNKNOWN": 0, + "PACKED": 1, + "EXPANDED": 2 + } + }, + "Utf8Validation": { + "values": { + "UTF8_VALIDATION_UNKNOWN": 0, + "VERIFY": 2, + "NONE": 3 + }, + "reserved": [ + [ + 1, + 1 + ] + ] + }, + "MessageEncoding": { + "values": { + "MESSAGE_ENCODING_UNKNOWN": 0, + "LENGTH_PREFIXED": 1, + "DELIMITED": 2 + } + }, + "JsonFormat": { + "values": { + "JSON_FORMAT_UNKNOWN": 0, + "ALLOW": 1, + "LEGACY_BEST_EFFORT": 2 + } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } + } + } + }, + "FeatureSetDefaults": { + "edition": "proto2", + "fields": { + "defaults": { + "rule": "repeated", + "type": "FeatureSetEditionDefault", + "id": 1 + }, + "minimumEdition": { + "type": "Edition", + "id": 4 + }, + "maximumEdition": { + "type": "Edition", + "id": 5 + } + }, + "nested": { + "FeatureSetEditionDefault": { + "fields": { + "edition": { + "type": "Edition", + "id": 3 + }, + "overridableFeatures": { + "type": "FeatureSet", + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 + } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] + } + } + }, + "SourceCodeInfo": { + "edition": "proto2", + "fields": { + "location": { + "rule": "repeated", + "type": "Location", + "id": 1 + } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], + "nested": { + "Location": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "span": { + "rule": "repeated", + "type": "int32", + "id": 2, + "options": { + "packed": true + } + }, + "leadingComments": { + "type": "string", + "id": 3 + }, + "trailingComments": { + "type": "string", + "id": 4 + }, + "leadingDetachedComments": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + } + } + }, + "GeneratedCodeInfo": { + "edition": "proto2", + "fields": { + "annotation": { + "rule": "repeated", + "type": "Annotation", + "id": 1 + } + }, + "nested": { + "Annotation": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1, + "options": { + "packed": true + } + }, + "sourceFile": { + "type": "string", + "id": 2 + }, + "begin": { + "type": "int32", + "id": 3 + }, + "end": { + "type": "int32", + "id": 4 + }, + "semantic": { + "type": "Semantic", + "id": 5 + } + }, + "nested": { + "Semantic": { + "values": { + "NONE": 0, + "SET": 1, + "ALIAS": 2 + } + } + } + } + } + }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } + }, + "Any": { + "fields": { + "type_url": { + "type": "string", + "id": 1 + }, + "value": { + "type": "bytes", + "id": 2 + } + } + }, + "Empty": { + "fields": {} + }, + "FieldMask": { + "fields": { + "paths": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } + }, + "Timestamp": { + "fields": { + "seconds": { + "type": "int64", + "id": 1 + }, + "nanos": { + "type": "int32", + "id": 2 + } + } + }, + "Struct": { + "fields": { + "fields": { + "keyType": "string", + "type": "Value", + "id": 1 + } + } + }, + "Value": { + "oneofs": { + "kind": { + "oneof": [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + "fields": { + "nullValue": { + "type": "NullValue", + "id": 1 + }, + "numberValue": { + "type": "double", + "id": 2 + }, + "stringValue": { + "type": "string", + "id": 3 + }, + "boolValue": { + "type": "bool", + "id": 4 + }, + "structValue": { + "type": "Struct", + "id": 5 + }, + "listValue": { + "type": "ListValue", + "id": 6 + } + } + }, + "NullValue": { + "values": { + "NULL_VALUE": 0 + } + }, + "ListValue": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + } + } + } + } + }, + "rpc": { + "options": { + "go_package": "google.golang.org/genproto/googleapis/rpc/status;status", + "java_multiple_files": true, + "java_outer_classname": "StatusProto", + "java_package": "com.google.rpc", + "objc_class_prefix": "RPC", + "cc_enable_arenas": true + }, + "nested": { + "ErrorInfo": { + "fields": { + "reason": { + "type": "string", + "id": 1 + }, + "domain": { + "type": "string", + "id": 2 + }, + "metadata": { + "keyType": "string", + "type": "string", + "id": 3 + } + } + }, + "RetryInfo": { + "fields": { + "retryDelay": { + "type": "google.protobuf.Duration", + "id": 1 + } + } + }, + "DebugInfo": { + "fields": { + "stackEntries": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "detail": { + "type": "string", + "id": 2 + } + } + }, + "QuotaFailure": { + "fields": { + "violations": { + "rule": "repeated", + "type": "Violation", + "id": 1 + } + }, + "nested": { + "Violation": { + "fields": { + "subject": { + "type": "string", + "id": 1 + }, + "description": { + "type": "string", + "id": 2 + } + } + } + } + }, + "PreconditionFailure": { + "fields": { + "violations": { + "rule": "repeated", + "type": "Violation", + "id": 1 + } + }, + "nested": { + "Violation": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "subject": { + "type": "string", + "id": 2 + }, + "description": { + "type": "string", + "id": 3 + } + } + } + } + }, + "BadRequest": { + "fields": { + "fieldViolations": { + "rule": "repeated", + "type": "FieldViolation", + "id": 1 + } + }, + "nested": { + "FieldViolation": { + "fields": { + "field": { + "type": "string", + "id": 1 + }, + "description": { + "type": "string", + "id": 2 + } + } + } + } + }, + "RequestInfo": { + "fields": { + "requestId": { + "type": "string", + "id": 1 + }, + "servingData": { + "type": "string", + "id": 2 + } + } + }, + "ResourceInfo": { + "fields": { + "resourceType": { + "type": "string", + "id": 1 + }, + "resourceName": { + "type": "string", + "id": 2 + }, + "owner": { + "type": "string", + "id": 3 + }, + "description": { + "type": "string", + "id": 4 + } + } + }, + "Help": { + "fields": { + "links": { + "rule": "repeated", + "type": "Link", + "id": 1 + } + }, + "nested": { + "Link": { + "fields": { + "description": { + "type": "string", + "id": 1 + }, + "url": { + "type": "string", + "id": 2 + } + } + } + } + }, + "LocalizedMessage": { + "fields": { + "locale": { + "type": "string", + "id": 1 + }, + "message": { + "type": "string", + "id": 2 + } + } + }, + "Status": { + "fields": { + "code": { + "type": "int32", + "id": 1 + }, + "message": { + "type": "string", + "id": 2 + }, + "details": { + "rule": "repeated", + "type": "google.protobuf.Any", + "id": 3 + } + } + } + } + }, + "spanner": { + "nested": { + "admin": { + "nested": { + "database": { + "nested": { + "v1": { + "options": { + "csharp_namespace": "Google.Cloud.Spanner.Admin.Database.V1", + "go_package": "cloud.google.com/go/spanner/admin/database/apiv1/databasepb;databasepb", + "java_multiple_files": true, + "java_outer_classname": "SpannerDatabaseAdminProto", + "java_package": "com.google.spanner.admin.database.v1", + "php_namespace": "Google\\Cloud\\Spanner\\Admin\\Database\\V1", + "ruby_package": "Google::Cloud::Spanner::Admin::Database::V1", + "(google.api.resource_definition).type": "spanner.googleapis.com/InstancePartition", + "(google.api.resource_definition).pattern": "projects/{project}/instances/{instance}/instancePartitions/{instance_partition}" + }, + "nested": { + "Backup": { + "options": { + "(google.api.resource).type": "spanner.googleapis.com/Backup", + "(google.api.resource).pattern": "projects/{project}/instances/{instance}/backups/{backup}" + }, + "fields": { + "database": { + "type": "string", + "id": 2, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "versionTime": { + "type": "google.protobuf.Timestamp", + "id": 9 + }, + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "name": { + "type": "string", + "id": 1 + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "sizeBytes": { + "type": "int64", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "freeableSizeBytes": { + "type": "int64", + "id": 15, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "exclusiveSizeBytes": { + "type": "int64", + "id": 16, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "state": { + "type": "State", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "referencingDatabases": { + "rule": "repeated", + "type": "string", + "id": 7, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "encryptionInfo": { + "type": "EncryptionInfo", + "id": 8, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "encryptionInformation": { + "rule": "repeated", + "type": "EncryptionInfo", + "id": 13, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "databaseDialect": { + "type": "DatabaseDialect", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "referencingBackups": { + "rule": "repeated", + "type": "string", + "id": 11, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + }, + "maxExpireTime": { + "type": "google.protobuf.Timestamp", + "id": 12, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "backupSchedules": { + "rule": "repeated", + "type": "string", + "id": 14, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "(google.api.resource_reference).type": "spanner.googleapis.com/BackupSchedule" + } + }, + "incrementalBackupChainId": { + "type": "string", + "id": 17, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "oldestVersionTime": { + "type": "google.protobuf.Timestamp", + "id": 18, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "instancePartitions": { + "rule": "repeated", + "type": "BackupInstancePartition", + "id": 19, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + }, + "nested": { + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "CREATING": 1, + "READY": 2 + } + } + } + }, + "CreateBackupRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "backupId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "backup": { + "type": "Backup", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "encryptionConfig": { + "type": "CreateBackupEncryptionConfig", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "CreateBackupMetadata": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + }, + "database": { + "type": "string", + "id": 2, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "progress": { + "type": "OperationProgress", + "id": 3 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "CopyBackupRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "backupId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "sourceBackup": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + }, + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "encryptionConfig": { + "type": "CopyBackupEncryptionConfig", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "CopyBackupMetadata": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + }, + "sourceBackup": { + "type": "string", + "id": 2, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + }, + "progress": { + "type": "OperationProgress", + "id": 3 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "UpdateBackupRequest": { + "fields": { + "backup": { + "type": "Backup", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "GetBackupRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + } + } + }, + "DeleteBackupRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + } + } + }, + "ListBackupsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "filter": { + "type": "string", + "id": 2 + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + } + } + }, + "ListBackupsResponse": { + "fields": { + "backups": { + "rule": "repeated", + "type": "Backup", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "ListBackupOperationsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "filter": { + "type": "string", + "id": 2 + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + } + } + }, + "ListBackupOperationsResponse": { + "fields": { + "operations": { + "rule": "repeated", + "type": "google.longrunning.Operation", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "BackupInfo": { + "fields": { + "backup": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + }, + "versionTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "sourceDatabase": { + "type": "string", + "id": 3, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + } + } + }, + "CreateBackupEncryptionConfig": { + "fields": { + "encryptionType": { + "type": "EncryptionType", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "kmsKeyName": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKey" + } + }, + "kmsKeyNames": { + "rule": "repeated", + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKey" + } + } + }, + "nested": { + "EncryptionType": { + "values": { + "ENCRYPTION_TYPE_UNSPECIFIED": 0, + "USE_DATABASE_ENCRYPTION": 1, + "GOOGLE_DEFAULT_ENCRYPTION": 2, + "CUSTOMER_MANAGED_ENCRYPTION": 3 + } + } + } + }, + "CopyBackupEncryptionConfig": { + "fields": { + "encryptionType": { + "type": "EncryptionType", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "kmsKeyName": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKey" + } + }, + "kmsKeyNames": { + "rule": "repeated", + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKey" + } + } + }, + "nested": { + "EncryptionType": { + "values": { + "ENCRYPTION_TYPE_UNSPECIFIED": 0, + "USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION": 1, + "GOOGLE_DEFAULT_ENCRYPTION": 2, + "CUSTOMER_MANAGED_ENCRYPTION": 3 + } + } + } + }, + "FullBackupSpec": { + "fields": {} + }, + "IncrementalBackupSpec": { + "fields": {} + }, + "BackupInstancePartition": { + "fields": { + "instancePartition": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/InstancePartition" + } + } + } + }, + "OperationProgress": { + "fields": { + "progressPercent": { + "type": "int32", + "id": 1 + }, + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + } + } + }, + "EncryptionConfig": { + "fields": { + "kmsKeyName": { + "type": "string", + "id": 2, + "options": { + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKey" + } + }, + "kmsKeyNames": { + "rule": "repeated", + "type": "string", + "id": 3, + "options": { + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKey" + } + } + } + }, + "EncryptionInfo": { + "fields": { + "encryptionType": { + "type": "Type", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "encryptionStatus": { + "type": "google.rpc.Status", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "kmsKeyVersion": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKeyVersion" + } + } + }, + "nested": { + "Type": { + "values": { + "TYPE_UNSPECIFIED": 0, + "GOOGLE_DEFAULT_ENCRYPTION": 1, + "CUSTOMER_MANAGED_ENCRYPTION": 2 + } + } + } + }, + "DatabaseDialect": { + "values": { + "DATABASE_DIALECT_UNSPECIFIED": 0, + "GOOGLE_STANDARD_SQL": 1, + "POSTGRESQL": 2 + } + }, + "BackupScheduleSpec": { + "oneofs": { + "scheduleSpec": { + "oneof": [ + "cronSpec" + ] + } + }, + "fields": { + "cronSpec": { + "type": "CrontabSpec", + "id": 1 + } + } + }, + "BackupSchedule": { + "options": { + "(google.api.resource).type": "spanner.googleapis.com/BackupSchedule", + "(google.api.resource).pattern": "projects/{project}/instances/{instance}/databases/{database}/backupSchedules/{schedule}", + "(google.api.resource).plural": "backupSchedules", + "(google.api.resource).singular": "backupSchedule" + }, + "oneofs": { + "backupTypeSpec": { + "oneof": [ + "fullBackupSpec", + "incrementalBackupSpec" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "IDENTIFIER" + } + }, + "spec": { + "type": "BackupScheduleSpec", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "retentionDuration": { + "type": "google.protobuf.Duration", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "encryptionConfig": { + "type": "CreateBackupEncryptionConfig", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "fullBackupSpec": { + "type": "FullBackupSpec", + "id": 7 + }, + "incrementalBackupSpec": { + "type": "IncrementalBackupSpec", + "id": 8 + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 9, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "CrontabSpec": { + "fields": { + "text": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "timeZone": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "creationWindow": { + "type": "google.protobuf.Duration", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "CreateBackupScheduleRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "backupScheduleId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "backupSchedule": { + "type": "BackupSchedule", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "GetBackupScheduleRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/BackupSchedule" + } + } + } + }, + "DeleteBackupScheduleRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/BackupSchedule" + } + } + } + }, + "ListBackupSchedulesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "pageSize": { + "type": "int32", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageToken": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ListBackupSchedulesResponse": { + "fields": { + "backupSchedules": { + "rule": "repeated", + "type": "BackupSchedule", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "UpdateBackupScheduleRequest": { + "fields": { + "backupSchedule": { + "type": "BackupSchedule", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "DatabaseAdmin": { + "options": { + "(google.api.default_host)": "spanner.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/spanner.admin" + }, + "methods": { + "ListDatabases": { + "requestType": "ListDatabasesRequest", + "responseType": "ListDatabasesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/instances/*}/databases", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/instances/*}/databases" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "CreateDatabase": { + "requestType": "CreateDatabaseRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/instances/*}/databases", + "(google.api.http).body": "*", + "(google.api.method_signature)": "parent,create_statement", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.database.v1.Database", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.database.v1.CreateDatabaseMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/instances/*}/databases", + "body": "*" + } + }, + { + "(google.api.method_signature)": "parent,create_statement" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.database.v1.Database", + "metadata_type": "google.spanner.admin.database.v1.CreateDatabaseMetadata" + } + } + ] + }, + "GetDatabase": { + "requestType": "GetDatabaseRequest", + "responseType": "Database", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/instances/*/databases/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/instances/*/databases/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "UpdateDatabase": { + "requestType": "UpdateDatabaseRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).patch": "/v1/{database.name=projects/*/instances/*/databases/*}", + "(google.api.http).body": "database", + "(google.api.method_signature)": "database,update_mask", + "(google.longrunning.operation_info).response_type": "Database", + "(google.longrunning.operation_info).metadata_type": "UpdateDatabaseMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{database.name=projects/*/instances/*/databases/*}", + "body": "database" + } + }, + { + "(google.api.method_signature)": "database,update_mask" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "Database", + "metadata_type": "UpdateDatabaseMetadata" + } + } + ] + }, + "UpdateDatabaseDdl": { + "requestType": "UpdateDatabaseDdlRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).patch": "/v1/{database=projects/*/instances/*/databases/*}/ddl", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,statements", + "(google.longrunning.operation_info).response_type": "google.protobuf.Empty", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{database=projects/*/instances/*/databases/*}/ddl", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,statements" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.protobuf.Empty", + "metadata_type": "google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata" + } + } + ] + }, + "DropDatabase": { + "requestType": "DropDatabaseRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{database=projects/*/instances/*/databases/*}", + "(google.api.method_signature)": "database" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{database=projects/*/instances/*/databases/*}" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + "GetDatabaseDdl": { + "requestType": "GetDatabaseDdlRequest", + "responseType": "GetDatabaseDdlResponse", + "options": { + "(google.api.http).get": "/v1/{database=projects/*/instances/*/databases/*}/ddl", + "(google.api.method_signature)": "database" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{database=projects/*/instances/*/databases/*}/ddl" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + "SetIamPolicy": { + "requestType": "google.iam.v1.SetIamPolicyRequest", + "responseType": "google.iam.v1.Policy", + "options": { + "(google.api.http).post": "/v1/{resource=projects/*/instances/*/databases/*}:setIamPolicy", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{resource=projects/*/instances/*/databases/*/backupSchedules/*}:setIamPolicy", + "(google.api.http).additional_bindings.body": "*", + "(google.api.method_signature)": "resource,policy" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=projects/*/instances/*/databases/*}:setIamPolicy", + "body": "*", + "additional_bindings": [ + { + "post": "/v1/{resource=projects/*/instances/*/backups/*}:setIamPolicy", + "body": "*" + }, + { + "post": "/v1/{resource=projects/*/instances/*/databases/*/backupSchedules/*}:setIamPolicy", + "body": "*" + } + ] + } + }, + { + "(google.api.method_signature)": "resource,policy" + } + ] + }, + "GetIamPolicy": { + "requestType": "google.iam.v1.GetIamPolicyRequest", + "responseType": "google.iam.v1.Policy", + "options": { + "(google.api.http).post": "/v1/{resource=projects/*/instances/*/databases/*}:getIamPolicy", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{resource=projects/*/instances/*/databases/*/backupSchedules/*}:getIamPolicy", + "(google.api.http).additional_bindings.body": "*", + "(google.api.method_signature)": "resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=projects/*/instances/*/databases/*}:getIamPolicy", + "body": "*", + "additional_bindings": [ + { + "post": "/v1/{resource=projects/*/instances/*/backups/*}:getIamPolicy", + "body": "*" + }, + { + "post": "/v1/{resource=projects/*/instances/*/databases/*/backupSchedules/*}:getIamPolicy", + "body": "*" + } + ] + } + }, + { + "(google.api.method_signature)": "resource" + } + ] + }, + "TestIamPermissions": { + "requestType": "google.iam.v1.TestIamPermissionsRequest", + "responseType": "google.iam.v1.TestIamPermissionsResponse", + "options": { + "(google.api.http).post": "/v1/{resource=projects/*/instances/*/databases/*}:testIamPermissions", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{resource=projects/*/instances/*/databases/*/databaseRoles/*}:testIamPermissions", + "(google.api.http).additional_bindings.body": "*", + "(google.api.method_signature)": "resource,permissions" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=projects/*/instances/*/databases/*}:testIamPermissions", + "body": "*", + "additional_bindings": [ + { + "post": "/v1/{resource=projects/*/instances/*/backups/*}:testIamPermissions", + "body": "*" + }, + { + "post": "/v1/{resource=projects/*/instances/*/databases/*/backupSchedules/*}:testIamPermissions", + "body": "*" + }, + { + "post": "/v1/{resource=projects/*/instances/*/databases/*/databaseRoles/*}:testIamPermissions", + "body": "*" + } + ] + } + }, + { + "(google.api.method_signature)": "resource,permissions" + } + ] + }, + "CreateBackup": { + "requestType": "CreateBackupRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/instances/*}/backups", + "(google.api.http).body": "backup", + "(google.api.method_signature)": "parent,backup,backup_id", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.database.v1.Backup", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.database.v1.CreateBackupMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/instances/*}/backups", + "body": "backup" + } + }, + { + "(google.api.method_signature)": "parent,backup,backup_id" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.database.v1.Backup", + "metadata_type": "google.spanner.admin.database.v1.CreateBackupMetadata" + } + } + ] + }, + "CopyBackup": { + "requestType": "CopyBackupRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/instances/*}/backups:copy", + "(google.api.http).body": "*", + "(google.api.method_signature)": "parent,backup_id,source_backup,expire_time", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.database.v1.Backup", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.database.v1.CopyBackupMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/instances/*}/backups:copy", + "body": "*" + } + }, + { + "(google.api.method_signature)": "parent,backup_id,source_backup,expire_time" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.database.v1.Backup", + "metadata_type": "google.spanner.admin.database.v1.CopyBackupMetadata" + } + } + ] + }, + "GetBackup": { + "requestType": "GetBackupRequest", + "responseType": "Backup", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/instances/*/backups/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/instances/*/backups/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "UpdateBackup": { + "requestType": "UpdateBackupRequest", + "responseType": "Backup", + "options": { + "(google.api.http).patch": "/v1/{backup.name=projects/*/instances/*/backups/*}", + "(google.api.http).body": "backup", + "(google.api.method_signature)": "backup,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{backup.name=projects/*/instances/*/backups/*}", + "body": "backup" + } + }, + { + "(google.api.method_signature)": "backup,update_mask" + } + ] + }, + "DeleteBackup": { + "requestType": "DeleteBackupRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/instances/*/backups/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/instances/*/backups/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListBackups": { + "requestType": "ListBackupsRequest", + "responseType": "ListBackupsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/instances/*}/backups", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/instances/*}/backups" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "RestoreDatabase": { + "requestType": "RestoreDatabaseRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/instances/*}/databases:restore", + "(google.api.http).body": "*", + "(google.api.method_signature)": "parent,database_id,backup", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.database.v1.Database", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.database.v1.RestoreDatabaseMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/instances/*}/databases:restore", + "body": "*" + } + }, + { + "(google.api.method_signature)": "parent,database_id,backup" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.database.v1.Database", + "metadata_type": "google.spanner.admin.database.v1.RestoreDatabaseMetadata" + } + } + ] + }, + "ListDatabaseOperations": { + "requestType": "ListDatabaseOperationsRequest", + "responseType": "ListDatabaseOperationsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/instances/*}/databaseOperations", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/instances/*}/databaseOperations" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "ListBackupOperations": { + "requestType": "ListBackupOperationsRequest", + "responseType": "ListBackupOperationsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/instances/*}/backupOperations", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/instances/*}/backupOperations" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "ListDatabaseRoles": { + "requestType": "ListDatabaseRolesRequest", + "responseType": "ListDatabaseRolesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/instances/*/databases/*}/databaseRoles", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/instances/*/databases/*}/databaseRoles" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "AddSplitPoints": { + "requestType": "AddSplitPointsRequest", + "responseType": "AddSplitPointsResponse", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/instances/*/databases/*}:addSplitPoints", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,split_points" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/instances/*/databases/*}:addSplitPoints", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,split_points" + } + ] + }, + "CreateBackupSchedule": { + "requestType": "CreateBackupScheduleRequest", + "responseType": "BackupSchedule", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/instances/*/databases/*}/backupSchedules", + "(google.api.http).body": "backup_schedule", + "(google.api.method_signature)": "parent,backup_schedule,backup_schedule_id" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/instances/*/databases/*}/backupSchedules", + "body": "backup_schedule" + } + }, + { + "(google.api.method_signature)": "parent,backup_schedule,backup_schedule_id" + } + ] + }, + "GetBackupSchedule": { + "requestType": "GetBackupScheduleRequest", + "responseType": "BackupSchedule", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/instances/*/databases/*/backupSchedules/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/instances/*/databases/*/backupSchedules/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "UpdateBackupSchedule": { + "requestType": "UpdateBackupScheduleRequest", + "responseType": "BackupSchedule", + "options": { + "(google.api.http).patch": "/v1/{backup_schedule.name=projects/*/instances/*/databases/*/backupSchedules/*}", + "(google.api.http).body": "backup_schedule", + "(google.api.method_signature)": "backup_schedule,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{backup_schedule.name=projects/*/instances/*/databases/*/backupSchedules/*}", + "body": "backup_schedule" + } + }, + { + "(google.api.method_signature)": "backup_schedule,update_mask" + } + ] + }, + "DeleteBackupSchedule": { + "requestType": "DeleteBackupScheduleRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/instances/*/databases/*/backupSchedules/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/instances/*/databases/*/backupSchedules/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListBackupSchedules": { + "requestType": "ListBackupSchedulesRequest", + "responseType": "ListBackupSchedulesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/instances/*/databases/*}/backupSchedules", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/instances/*/databases/*}/backupSchedules" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "InternalUpdateGraphOperation": { + "requestType": "InternalUpdateGraphOperationRequest", + "responseType": "InternalUpdateGraphOperationResponse", + "options": { + "(google.api.method_signature)": "database,operation_id" + }, + "parsedOptions": [ + { + "(google.api.method_signature)": "database,operation_id" + } + ] + } + } + }, + "RestoreInfo": { + "oneofs": { + "sourceInfo": { + "oneof": [ + "backupInfo" + ] + } + }, + "fields": { + "sourceType": { + "type": "RestoreSourceType", + "id": 1 + }, + "backupInfo": { + "type": "BackupInfo", + "id": 2 + } + } + }, + "Database": { + "options": { + "(google.api.resource).type": "spanner.googleapis.com/Database", + "(google.api.resource).pattern": "projects/{project}/instances/{instance}/databases/{database}" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "state": { + "type": "State", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "restoreInfo": { + "type": "RestoreInfo", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "encryptionConfig": { + "type": "EncryptionConfig", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "encryptionInfo": { + "rule": "repeated", + "type": "EncryptionInfo", + "id": 8, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "versionRetentionPeriod": { + "type": "string", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "earliestVersionTime": { + "type": "google.protobuf.Timestamp", + "id": 7, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "defaultLeader": { + "type": "string", + "id": 9, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "databaseDialect": { + "type": "DatabaseDialect", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "enableDropProtection": { + "type": "bool", + "id": 11 + }, + "reconciling": { + "type": "bool", + "id": 12, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + }, + "nested": { + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "CREATING": 1, + "READY": 2, + "READY_OPTIMIZING": 3 + } + } + } + }, + "ListDatabasesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + } + } + }, + "ListDatabasesResponse": { + "fields": { + "databases": { + "rule": "repeated", + "type": "Database", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "CreateDatabaseRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "createStatement": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "extraStatements": { + "rule": "repeated", + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "encryptionConfig": { + "type": "EncryptionConfig", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "databaseDialect": { + "type": "DatabaseDialect", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "protoDescriptors": { + "type": "bytes", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "CreateDatabaseMetadata": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + } + } + }, + "GetDatabaseRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + } + } + }, + "UpdateDatabaseRequest": { + "fields": { + "database": { + "type": "Database", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "UpdateDatabaseMetadata": { + "fields": { + "request": { + "type": "UpdateDatabaseRequest", + "id": 1 + }, + "progress": { + "type": "OperationProgress", + "id": 2 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + } + } + }, + "UpdateDatabaseDdlRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "statements": { + "rule": "repeated", + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "operationId": { + "type": "string", + "id": 3 + }, + "protoDescriptors": { + "type": "bytes", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "throughputMode": { + "type": "bool", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "DdlStatementActionInfo": { + "fields": { + "action": { + "type": "string", + "id": 1 + }, + "entityType": { + "type": "string", + "id": 2 + }, + "entityNames": { + "rule": "repeated", + "type": "string", + "id": 3 + } + } + }, + "UpdateDatabaseDdlMetadata": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "statements": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "commitTimestamps": { + "rule": "repeated", + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "throttled": { + "type": "bool", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "progress": { + "rule": "repeated", + "type": "OperationProgress", + "id": 5 + }, + "actions": { + "rule": "repeated", + "type": "DdlStatementActionInfo", + "id": 6 + } + } + }, + "DropDatabaseRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + } + } + }, + "GetDatabaseDdlRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + } + } + }, + "GetDatabaseDdlResponse": { + "fields": { + "statements": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "protoDescriptors": { + "type": "bytes", + "id": 2 + } + } + }, + "ListDatabaseOperationsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "filter": { + "type": "string", + "id": 2 + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + } + } + }, + "ListDatabaseOperationsResponse": { + "fields": { + "operations": { + "rule": "repeated", + "type": "google.longrunning.Operation", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "RestoreDatabaseRequest": { + "oneofs": { + "source": { + "oneof": [ + "backup" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "databaseId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "backup": { + "type": "string", + "id": 3, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Backup" + } + }, + "encryptionConfig": { + "type": "RestoreDatabaseEncryptionConfig", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "RestoreDatabaseEncryptionConfig": { + "fields": { + "encryptionType": { + "type": "EncryptionType", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "kmsKeyName": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKey" + } + }, + "kmsKeyNames": { + "rule": "repeated", + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "(google.api.resource_reference).type": "cloudkms.googleapis.com/CryptoKey" + } + } + }, + "nested": { + "EncryptionType": { + "values": { + "ENCRYPTION_TYPE_UNSPECIFIED": 0, + "USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION": 1, + "GOOGLE_DEFAULT_ENCRYPTION": 2, + "CUSTOMER_MANAGED_ENCRYPTION": 3 + } + } + } + }, + "RestoreDatabaseMetadata": { + "oneofs": { + "sourceInfo": { + "oneof": [ + "backupInfo" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "sourceType": { + "type": "RestoreSourceType", + "id": 2 + }, + "backupInfo": { + "type": "BackupInfo", + "id": 3 + }, + "progress": { + "type": "OperationProgress", + "id": 4 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 5 + }, + "optimizeDatabaseOperationName": { + "type": "string", + "id": 6 + } + } + }, + "OptimizeRestoredDatabaseMetadata": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "progress": { + "type": "OperationProgress", + "id": 2 + } + } + }, + "RestoreSourceType": { + "values": { + "TYPE_UNSPECIFIED": 0, + "BACKUP": 1 + } + }, + "DatabaseRole": { + "options": { + "(google.api.resource).type": "spanner.googleapis.com/DatabaseRole", + "(google.api.resource).pattern": "projects/{project}/instances/{instance}/databases/{database}/databaseRoles/{role}" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "ListDatabaseRolesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + } + } + }, + "ListDatabaseRolesResponse": { + "fields": { + "databaseRoles": { + "rule": "repeated", + "type": "DatabaseRole", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "AddSplitPointsRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "splitPoints": { + "rule": "repeated", + "type": "SplitPoints", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "initiator": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "AddSplitPointsResponse": { + "fields": {} + }, + "SplitPoints": { + "fields": { + "table": { + "type": "string", + "id": 1 + }, + "index": { + "type": "string", + "id": 2 + }, + "keys": { + "rule": "repeated", + "type": "Key", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "Key": { + "fields": { + "keyParts": { + "type": "google.protobuf.ListValue", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + } + } + }, + "InternalUpdateGraphOperationRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "operationId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "vmIdentityToken": { + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "progress": { + "type": "double", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "status": { + "type": "google.rpc.Status", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "InternalUpdateGraphOperationResponse": { + "fields": {} + } + } + } + } + }, + "instance": { + "nested": { + "v1": { + "options": { + "csharp_namespace": "Google.Cloud.Spanner.Admin.Instance.V1", + "go_package": "cloud.google.com/go/spanner/admin/instance/apiv1/instancepb;instancepb", + "java_multiple_files": true, + "java_outer_classname": "SpannerInstanceAdminProto", + "java_package": "com.google.spanner.admin.instance.v1", + "php_namespace": "Google\\Cloud\\Spanner\\Admin\\Instance\\V1", + "ruby_package": "Google::Cloud::Spanner::Admin::Instance::V1" + }, + "nested": { + "OperationProgress": { + "fields": { + "progressPercent": { + "type": "int32", + "id": 1 + }, + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + } + } + }, + "FulfillmentPeriod": { + "values": { + "FULFILLMENT_PERIOD_UNSPECIFIED": 0, + "FULFILLMENT_PERIOD_NORMAL": 1, + "FULFILLMENT_PERIOD_EXTENDED": 2 + } + }, + "ReplicaSelection": { + "fields": { + "location": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "InstanceAdmin": { + "options": { + "(google.api.default_host)": "spanner.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/spanner.admin" + }, + "methods": { + "ListInstanceConfigs": { + "requestType": "ListInstanceConfigsRequest", + "responseType": "ListInstanceConfigsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*}/instanceConfigs", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*}/instanceConfigs" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "GetInstanceConfig": { + "requestType": "GetInstanceConfigRequest", + "responseType": "InstanceConfig", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/instanceConfigs/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/instanceConfigs/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "CreateInstanceConfig": { + "requestType": "CreateInstanceConfigRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*}/instanceConfigs", + "(google.api.http).body": "*", + "(google.api.method_signature)": "parent,instance_config,instance_config_id", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.instance.v1.InstanceConfig", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.instance.v1.CreateInstanceConfigMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*}/instanceConfigs", + "body": "*" + } + }, + { + "(google.api.method_signature)": "parent,instance_config,instance_config_id" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.instance.v1.InstanceConfig", + "metadata_type": "google.spanner.admin.instance.v1.CreateInstanceConfigMetadata" + } + } + ] + }, + "UpdateInstanceConfig": { + "requestType": "UpdateInstanceConfigRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).patch": "/v1/{instance_config.name=projects/*/instanceConfigs/*}", + "(google.api.http).body": "*", + "(google.api.method_signature)": "instance_config,update_mask", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.instance.v1.InstanceConfig", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{instance_config.name=projects/*/instanceConfigs/*}", + "body": "*" + } + }, + { + "(google.api.method_signature)": "instance_config,update_mask" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.instance.v1.InstanceConfig", + "metadata_type": "google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata" + } + } + ] + }, + "DeleteInstanceConfig": { + "requestType": "DeleteInstanceConfigRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/instanceConfigs/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/instanceConfigs/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListInstanceConfigOperations": { + "requestType": "ListInstanceConfigOperationsRequest", + "responseType": "ListInstanceConfigOperationsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*}/instanceConfigOperations", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*}/instanceConfigOperations" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "ListInstances": { + "requestType": "ListInstancesRequest", + "responseType": "ListInstancesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*}/instances", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*}/instances" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "ListInstancePartitions": { + "requestType": "ListInstancePartitionsRequest", + "responseType": "ListInstancePartitionsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/instances/*}/instancePartitions", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/instances/*}/instancePartitions" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "GetInstance": { + "requestType": "GetInstanceRequest", + "responseType": "Instance", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/instances/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/instances/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "CreateInstance": { + "requestType": "CreateInstanceRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*}/instances", + "(google.api.http).body": "*", + "(google.api.method_signature)": "parent,instance_id,instance", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.instance.v1.Instance", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.instance.v1.CreateInstanceMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*}/instances", + "body": "*" + } + }, + { + "(google.api.method_signature)": "parent,instance_id,instance" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.instance.v1.Instance", + "metadata_type": "google.spanner.admin.instance.v1.CreateInstanceMetadata" + } + } + ] + }, + "UpdateInstance": { + "requestType": "UpdateInstanceRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).patch": "/v1/{instance.name=projects/*/instances/*}", + "(google.api.http).body": "*", + "(google.api.method_signature)": "instance,field_mask", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.instance.v1.Instance", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.instance.v1.UpdateInstanceMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{instance.name=projects/*/instances/*}", + "body": "*" + } + }, + { + "(google.api.method_signature)": "instance,field_mask" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.instance.v1.Instance", + "metadata_type": "google.spanner.admin.instance.v1.UpdateInstanceMetadata" + } + } + ] + }, + "DeleteInstance": { + "requestType": "DeleteInstanceRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/instances/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/instances/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "SetIamPolicy": { + "requestType": "google.iam.v1.SetIamPolicyRequest", + "responseType": "google.iam.v1.Policy", + "options": { + "(google.api.http).post": "/v1/{resource=projects/*/instances/*}:setIamPolicy", + "(google.api.http).body": "*", + "(google.api.method_signature)": "resource,policy" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=projects/*/instances/*}:setIamPolicy", + "body": "*" + } + }, + { + "(google.api.method_signature)": "resource,policy" + } + ] + }, + "GetIamPolicy": { + "requestType": "google.iam.v1.GetIamPolicyRequest", + "responseType": "google.iam.v1.Policy", + "options": { + "(google.api.http).post": "/v1/{resource=projects/*/instances/*}:getIamPolicy", + "(google.api.http).body": "*", + "(google.api.method_signature)": "resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=projects/*/instances/*}:getIamPolicy", + "body": "*" + } + }, + { + "(google.api.method_signature)": "resource" + } + ] + }, + "TestIamPermissions": { + "requestType": "google.iam.v1.TestIamPermissionsRequest", + "responseType": "google.iam.v1.TestIamPermissionsResponse", + "options": { + "(google.api.http).post": "/v1/{resource=projects/*/instances/*}:testIamPermissions", + "(google.api.http).body": "*", + "(google.api.method_signature)": "resource,permissions" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=projects/*/instances/*}:testIamPermissions", + "body": "*" + } + }, + { + "(google.api.method_signature)": "resource,permissions" + } + ] + }, + "GetInstancePartition": { + "requestType": "GetInstancePartitionRequest", + "responseType": "InstancePartition", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/instances/*/instancePartitions/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/instances/*/instancePartitions/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "CreateInstancePartition": { + "requestType": "CreateInstancePartitionRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/instances/*}/instancePartitions", + "(google.api.http).body": "*", + "(google.api.method_signature)": "parent,instance_partition,instance_partition_id", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.instance.v1.InstancePartition", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.instance.v1.CreateInstancePartitionMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/instances/*}/instancePartitions", + "body": "*" + } + }, + { + "(google.api.method_signature)": "parent,instance_partition,instance_partition_id" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.instance.v1.InstancePartition", + "metadata_type": "google.spanner.admin.instance.v1.CreateInstancePartitionMetadata" + } + } + ] + }, + "DeleteInstancePartition": { + "requestType": "DeleteInstancePartitionRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/instances/*/instancePartitions/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/instances/*/instancePartitions/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "UpdateInstancePartition": { + "requestType": "UpdateInstancePartitionRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).patch": "/v1/{instance_partition.name=projects/*/instances/*/instancePartitions/*}", + "(google.api.http).body": "*", + "(google.api.method_signature)": "instance_partition,field_mask", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.instance.v1.InstancePartition", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{instance_partition.name=projects/*/instances/*/instancePartitions/*}", + "body": "*" + } + }, + { + "(google.api.method_signature)": "instance_partition,field_mask" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.instance.v1.InstancePartition", + "metadata_type": "google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata" + } + } + ] + }, + "ListInstancePartitionOperations": { + "requestType": "ListInstancePartitionOperationsRequest", + "responseType": "ListInstancePartitionOperationsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/instances/*}/instancePartitionOperations", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/instances/*}/instancePartitionOperations" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "MoveInstance": { + "requestType": "MoveInstanceRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/instances/*}:move", + "(google.api.http).body": "*", + "(google.longrunning.operation_info).response_type": "google.spanner.admin.instance.v1.MoveInstanceResponse", + "(google.longrunning.operation_info).metadata_type": "google.spanner.admin.instance.v1.MoveInstanceMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/instances/*}:move", + "body": "*" + } + }, + { + "(google.longrunning.operation_info)": { + "response_type": "google.spanner.admin.instance.v1.MoveInstanceResponse", + "metadata_type": "google.spanner.admin.instance.v1.MoveInstanceMetadata" + } + } + ] + } + } + }, + "ReplicaInfo": { + "fields": { + "location": { + "type": "string", + "id": 1 + }, + "type": { + "type": "ReplicaType", + "id": 2 + }, + "defaultLeaderLocation": { + "type": "bool", + "id": 3 + } + }, + "nested": { + "ReplicaType": { + "values": { + "TYPE_UNSPECIFIED": 0, + "READ_WRITE": 1, + "READ_ONLY": 2, + "WITNESS": 3 + } + } + } + }, + "InstanceConfig": { + "options": { + "(google.api.resource).type": "spanner.googleapis.com/InstanceConfig", + "(google.api.resource).pattern": "projects/{project}/instanceConfigs/{instance_config}", + "(google.api.resource).plural": "instanceConfigs", + "(google.api.resource).singular": "instanceConfig" + }, + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "displayName": { + "type": "string", + "id": 2 + }, + "configType": { + "type": "Type", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "replicas": { + "rule": "repeated", + "type": "ReplicaInfo", + "id": 3 + }, + "optionalReplicas": { + "rule": "repeated", + "type": "ReplicaInfo", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "baseConfig": { + "type": "string", + "id": 7, + "options": { + "(google.api.resource_reference).type": "spanner.googleapis.com/InstanceConfig" + } + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 8 + }, + "etag": { + "type": "string", + "id": 9 + }, + "leaderOptions": { + "rule": "repeated", + "type": "string", + "id": 4 + }, + "reconciling": { + "type": "bool", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "state": { + "type": "State", + "id": 11, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "freeInstanceAvailability": { + "type": "FreeInstanceAvailability", + "id": 12, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "quorumType": { + "type": "QuorumType", + "id": 18, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "storageLimitPerProcessingUnit": { + "type": "int64", + "id": 19, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + }, + "nested": { + "Type": { + "values": { + "TYPE_UNSPECIFIED": 0, + "GOOGLE_MANAGED": 1, + "USER_MANAGED": 2 + } + }, + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "CREATING": 1, + "READY": 2 + } + }, + "FreeInstanceAvailability": { + "values": { + "FREE_INSTANCE_AVAILABILITY_UNSPECIFIED": 0, + "AVAILABLE": 1, + "UNSUPPORTED": 2, + "DISABLED": 3, + "QUOTA_EXCEEDED": 4 + } + }, + "QuorumType": { + "values": { + "QUORUM_TYPE_UNSPECIFIED": 0, + "REGION": 1, + "DUAL_REGION": 2, + "MULTI_REGION": 3 + } + } + } + }, + "ReplicaComputeCapacity": { + "oneofs": { + "computeCapacity": { + "oneof": [ + "nodeCount", + "processingUnits" + ] + } + }, + "fields": { + "replicaSelection": { + "type": "ReplicaSelection", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "nodeCount": { + "type": "int32", + "id": 2 + }, + "processingUnits": { + "type": "int32", + "id": 3 + } + } + }, + "AutoscalingConfig": { + "fields": { + "autoscalingLimits": { + "type": "AutoscalingLimits", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "autoscalingTargets": { + "type": "AutoscalingTargets", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "asymmetricAutoscalingOptions": { + "rule": "repeated", + "type": "AsymmetricAutoscalingOption", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "AutoscalingLimits": { + "oneofs": { + "minLimit": { + "oneof": [ + "minNodes", + "minProcessingUnits" + ] + }, + "maxLimit": { + "oneof": [ + "maxNodes", + "maxProcessingUnits" + ] + } + }, + "fields": { + "minNodes": { + "type": "int32", + "id": 1 + }, + "minProcessingUnits": { + "type": "int32", + "id": 2 + }, + "maxNodes": { + "type": "int32", + "id": 3 + }, + "maxProcessingUnits": { + "type": "int32", + "id": 4 + } + } + }, + "AutoscalingTargets": { + "fields": { + "highPriorityCpuUtilizationPercent": { + "type": "int32", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "totalCpuUtilizationPercent": { + "type": "int32", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "storageUtilizationPercent": { + "type": "int32", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "AsymmetricAutoscalingOption": { + "fields": { + "replicaSelection": { + "type": "ReplicaSelection", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "overrides": { + "type": "AutoscalingConfigOverrides", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "AutoscalingConfigOverrides": { + "fields": { + "autoscalingLimits": { + "type": "AutoscalingLimits", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "autoscalingTargetHighPriorityCpuUtilizationPercent": { + "type": "int32", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "autoscalingTargetTotalCpuUtilizationPercent": { + "type": "int32", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "disableHighPriorityCpuAutoscaling": { + "type": "bool", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "disableTotalCpuAutoscaling": { + "type": "bool", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + } + } + } + } + }, + "Instance": { + "options": { + "(google.api.resource).type": "spanner.googleapis.com/Instance", + "(google.api.resource).pattern": "projects/{project}/instances/{instance}", + "(google.api.resource).plural": "instances", + "(google.api.resource).singular": "instance" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "config": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/InstanceConfig" + } + }, + "displayName": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "nodeCount": { + "type": "int32", + "id": 5 + }, + "processingUnits": { + "type": "int32", + "id": 9 + }, + "replicaComputeCapacity": { + "rule": "repeated", + "type": "ReplicaComputeCapacity", + "id": 19, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "autoscalingConfig": { + "type": "AutoscalingConfig", + "id": 17, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "state": { + "type": "State", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 7 + }, + "instanceType": { + "type": "InstanceType", + "id": 10 + }, + "endpointUris": { + "rule": "repeated", + "type": "string", + "id": 8 + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 11, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 12, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "freeInstanceMetadata": { + "type": "FreeInstanceMetadata", + "id": 13 + }, + "edition": { + "type": "Edition", + "id": 20, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "defaultBackupScheduleType": { + "type": "DefaultBackupScheduleType", + "id": 23, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "CREATING": 1, + "READY": 2 + } + }, + "InstanceType": { + "values": { + "INSTANCE_TYPE_UNSPECIFIED": 0, + "PROVISIONED": 1, + "FREE_INSTANCE": 2 + } + }, + "Edition": { + "values": { + "EDITION_UNSPECIFIED": 0, + "STANDARD": 1, + "ENTERPRISE": 2, + "ENTERPRISE_PLUS": 3 + } + }, + "DefaultBackupScheduleType": { + "values": { + "DEFAULT_BACKUP_SCHEDULE_TYPE_UNSPECIFIED": 0, + "NONE": 1, + "AUTOMATIC": 2 + } + } + } + }, + "ListInstanceConfigsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "cloudresourcemanager.googleapis.com/Project" + } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + } + } + }, + "ListInstanceConfigsResponse": { + "fields": { + "instanceConfigs": { + "rule": "repeated", + "type": "InstanceConfig", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "GetInstanceConfigRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/InstanceConfig" + } + } + } + }, + "CreateInstanceConfigRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "cloudresourcemanager.googleapis.com/Project" + } + }, + "instanceConfigId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "instanceConfig": { + "type": "InstanceConfig", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "validateOnly": { + "type": "bool", + "id": 4 + } + } + }, + "UpdateInstanceConfigRequest": { + "fields": { + "instanceConfig": { + "type": "InstanceConfig", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "validateOnly": { + "type": "bool", + "id": 3 + } + } + }, + "DeleteInstanceConfigRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/InstanceConfig" + } + }, + "etag": { + "type": "string", + "id": 2 + }, + "validateOnly": { + "type": "bool", + "id": 3 + } + } + }, + "ListInstanceConfigOperationsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "cloudresourcemanager.googleapis.com/Project" + } + }, + "filter": { + "type": "string", + "id": 2 + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + } + } + }, + "ListInstanceConfigOperationsResponse": { + "fields": { + "operations": { + "rule": "repeated", + "type": "google.longrunning.Operation", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "GetInstanceRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "fieldMask": { + "type": "google.protobuf.FieldMask", + "id": 2 + } + } + }, + "CreateInstanceRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "cloudresourcemanager.googleapis.com/Project" + } + }, + "instanceId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "instance": { + "type": "Instance", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "ListInstancesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "cloudresourcemanager.googleapis.com/Project" + } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + }, + "filter": { + "type": "string", + "id": 4 + }, + "instanceDeadline": { + "type": "google.protobuf.Timestamp", + "id": 5 + } + } + }, + "ListInstancesResponse": { + "fields": { + "instances": { + "rule": "repeated", + "type": "Instance", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + }, + "unreachable": { + "rule": "repeated", + "type": "string", + "id": 3 + } + } + }, + "UpdateInstanceRequest": { + "fields": { + "instance": { + "type": "Instance", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "fieldMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "DeleteInstanceRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + } + } + }, + "CreateInstanceMetadata": { + "fields": { + "instance": { + "type": "Instance", + "id": 1 + }, + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + }, + "expectedFulfillmentPeriod": { + "type": "FulfillmentPeriod", + "id": 5 + } + } + }, + "UpdateInstanceMetadata": { + "fields": { + "instance": { + "type": "Instance", + "id": 1 + }, + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + }, + "expectedFulfillmentPeriod": { + "type": "FulfillmentPeriod", + "id": 5 + } + } + }, + "FreeInstanceMetadata": { + "fields": { + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "upgradeTime": { + "type": "google.protobuf.Timestamp", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "expireBehavior": { + "type": "ExpireBehavior", + "id": 3 + } + }, + "nested": { + "ExpireBehavior": { + "values": { + "EXPIRE_BEHAVIOR_UNSPECIFIED": 0, + "FREE_TO_PROVISIONED": 1, + "REMOVE_AFTER_GRACE_PERIOD": 2 + } + } + } + }, + "CreateInstanceConfigMetadata": { + "fields": { + "instanceConfig": { + "type": "InstanceConfig", + "id": 1 + }, + "progress": { + "type": "OperationProgress", + "id": 2 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + } + } + }, + "UpdateInstanceConfigMetadata": { + "fields": { + "instanceConfig": { + "type": "InstanceConfig", + "id": 1 + }, + "progress": { + "type": "OperationProgress", + "id": 2 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + } + } + }, + "InstancePartition": { + "options": { + "(google.api.resource).type": "spanner.googleapis.com/InstancePartition", + "(google.api.resource).pattern": "projects/{project}/instances/{instance}/instancePartitions/{instance_partition}", + "(google.api.resource).plural": "instancePartitions", + "(google.api.resource).singular": "instancePartition" + }, + "oneofs": { + "computeCapacity": { + "oneof": [ + "nodeCount", + "processingUnits" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "config": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/InstanceConfig" + } + }, + "displayName": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "nodeCount": { + "type": "int32", + "id": 5 + }, + "processingUnits": { + "type": "int32", + "id": 6 + }, + "autoscalingConfig": { + "type": "AutoscalingConfig", + "id": 13, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "state": { + "type": "State", + "id": 7, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 8, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 9, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "referencingDatabases": { + "rule": "repeated", + "type": "string", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "referencingBackups": { + "rule": "repeated", + "type": "string", + "id": 11, + "options": { + "deprecated": true, + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "etag": { + "type": "string", + "id": 12 + } + }, + "nested": { + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "CREATING": 1, + "READY": 2 + } + } + } + }, + "CreateInstancePartitionMetadata": { + "fields": { + "instancePartition": { + "type": "InstancePartition", + "id": 1 + }, + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "CreateInstancePartitionRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "instancePartitionId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "instancePartition": { + "type": "InstancePartition", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "DeleteInstancePartitionRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/InstancePartition" + } + }, + "etag": { + "type": "string", + "id": 2 + } + } + }, + "GetInstancePartitionRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/InstancePartition" + } + } + } + }, + "UpdateInstancePartitionRequest": { + "fields": { + "instancePartition": { + "type": "InstancePartition", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "fieldMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "UpdateInstancePartitionMetadata": { + "fields": { + "instancePartition": { + "type": "InstancePartition", + "id": 1 + }, + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } + } + }, + "ListInstancePartitionsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + }, + "instancePartitionDeadline": { + "type": "google.protobuf.Timestamp", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ListInstancePartitionsResponse": { + "fields": { + "instancePartitions": { + "rule": "repeated", + "type": "InstancePartition", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + }, + "unreachable": { + "rule": "repeated", + "type": "string", + "id": 3 + } + } + }, + "ListInstancePartitionOperationsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "filter": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageSize": { + "type": "int32", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageToken": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "instancePartitionDeadline": { + "type": "google.protobuf.Timestamp", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ListInstancePartitionOperationsResponse": { + "fields": { + "operations": { + "rule": "repeated", + "type": "google.longrunning.Operation", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + }, + "unreachableInstancePartitions": { + "rule": "repeated", + "type": "string", + "id": 3 + } + } + }, + "MoveInstanceRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Instance" + } + }, + "targetConfig": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/InstanceConfig" + } + } + } + }, + "MoveInstanceResponse": { + "fields": {} + }, + "MoveInstanceMetadata": { + "fields": { + "targetConfig": { + "type": "string", + "id": 1 + }, + "progress": { + "type": "OperationProgress", + "id": 2 + }, + "cancelTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + } + } + } + } + } + } + } + } + }, + "executor": { + "nested": { + "v1": { + "options": { + "go_package": "cloud.google.com/go/spanner/executor/apiv1/executorpb;executorpb", + "java_multiple_files": true, + "java_outer_classname": "CloudExecutorProto", + "java_package": "com.google.spanner.executor.v1" + }, + "nested": { + "SpannerExecutorProxy": { + "options": { + "(google.api.default_host)": "spanner-cloud-executor.googleapis.com" + }, + "methods": { + "ExecuteActionAsync": { + "requestType": "SpannerAsyncActionRequest", + "requestStream": true, + "responseType": "SpannerAsyncActionResponse", + "responseStream": true + } + } + }, + "SpannerAsyncActionRequest": { + "fields": { + "actionId": { + "type": "int32", + "id": 1 + }, + "action": { + "type": "SpannerAction", + "id": 2 + } + } + }, + "SpannerAsyncActionResponse": { + "fields": { + "actionId": { + "type": "int32", + "id": 1 + }, + "outcome": { + "type": "SpannerActionOutcome", + "id": 2 + } + } + }, + "SpannerAction": { + "oneofs": { + "action": { + "oneof": [ + "start", + "finish", + "read", + "query", + "mutation", + "dml", + "batchDml", + "write", + "partitionedUpdate", + "admin", + "startBatchTxn", + "closeBatchTxn", + "generateDbPartitionsRead", + "generateDbPartitionsQuery", + "executePartition", + "executeChangeStreamQuery", + "queryCancellation", + "adaptMessage" + ] + } + }, + "fields": { + "databasePath": { + "type": "string", + "id": 1 + }, + "spannerOptions": { + "type": "SpannerOptions", + "id": 2 + }, + "start": { + "type": "StartTransactionAction", + "id": 10 + }, + "finish": { + "type": "FinishTransactionAction", + "id": 11 + }, + "read": { + "type": "ReadAction", + "id": 20 + }, + "query": { + "type": "QueryAction", + "id": 21 + }, + "mutation": { + "type": "MutationAction", + "id": 22 + }, + "dml": { + "type": "DmlAction", + "id": 23 + }, + "batchDml": { + "type": "BatchDmlAction", + "id": 24 + }, + "write": { + "type": "WriteMutationsAction", + "id": 25 + }, + "partitionedUpdate": { + "type": "PartitionedUpdateAction", + "id": 27 + }, + "admin": { + "type": "AdminAction", + "id": 30 + }, + "startBatchTxn": { + "type": "StartBatchTransactionAction", + "id": 40 + }, + "closeBatchTxn": { + "type": "CloseBatchTransactionAction", + "id": 41 + }, + "generateDbPartitionsRead": { + "type": "GenerateDbPartitionsForReadAction", + "id": 42 + }, + "generateDbPartitionsQuery": { + "type": "GenerateDbPartitionsForQueryAction", + "id": 43 + }, + "executePartition": { + "type": "ExecutePartitionAction", + "id": 44 + }, + "executeChangeStreamQuery": { + "type": "ExecuteChangeStreamQuery", + "id": 50 + }, + "queryCancellation": { + "type": "QueryCancellationAction", + "id": 51 + }, + "adaptMessage": { + "type": "AdaptMessageAction", + "id": 52 + } + } + }, + "ReadAction": { + "oneofs": { + "_index": { + "oneof": [ + "index" + ] + } + }, + "fields": { + "table": { + "type": "string", + "id": 1 + }, + "index": { + "type": "string", + "id": 2, + "options": { + "proto3_optional": true + } + }, + "column": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "keys": { + "type": "KeySet", + "id": 4 + }, + "limit": { + "type": "int32", + "id": 5 + } + } + }, + "QueryAction": { + "fields": { + "sql": { + "type": "string", + "id": 1 + }, + "params": { + "rule": "repeated", + "type": "Parameter", + "id": 2 + } + }, + "nested": { + "Parameter": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "type": { + "type": "google.spanner.v1.Type", + "id": 2 + }, + "value": { + "type": "Value", + "id": 3 + } + } + } + } + }, + "DmlAction": { + "oneofs": { + "_autocommitIfSupported": { + "oneof": [ + "autocommitIfSupported" + ] + }, + "_lastStatement": { + "oneof": [ + "lastStatement" + ] + } + }, + "fields": { + "update": { + "type": "QueryAction", + "id": 1 + }, + "autocommitIfSupported": { + "type": "bool", + "id": 2, + "options": { + "proto3_optional": true + } + }, + "lastStatement": { + "type": "bool", + "id": 3, + "options": { + "proto3_optional": true + } + } + } + }, + "BatchDmlAction": { + "oneofs": { + "_lastStatements": { + "oneof": [ + "lastStatements" + ] + } + }, + "fields": { + "updates": { + "rule": "repeated", + "type": "QueryAction", + "id": 1 + }, + "lastStatements": { + "type": "bool", + "id": 2, + "options": { + "proto3_optional": true + } + } + } + }, + "Value": { + "oneofs": { + "valueType": { + "oneof": [ + "isNull", + "intValue", + "boolValue", + "doubleValue", + "bytesValue", + "stringValue", + "structValue", + "timestampValue", + "dateDaysValue", + "isCommitTimestamp", + "arrayValue" + ] + }, + "_arrayType": { + "oneof": [ + "arrayType" + ] + } + }, + "fields": { + "isNull": { + "type": "bool", + "id": 1 + }, + "intValue": { + "type": "int64", + "id": 2 + }, + "boolValue": { + "type": "bool", + "id": 3 + }, + "doubleValue": { + "type": "double", + "id": 4 + }, + "bytesValue": { + "type": "bytes", + "id": 5 + }, + "stringValue": { + "type": "string", + "id": 6 + }, + "structValue": { + "type": "ValueList", + "id": 7 + }, + "timestampValue": { + "type": "google.protobuf.Timestamp", + "id": 8 + }, + "dateDaysValue": { + "type": "int32", + "id": 9 + }, + "isCommitTimestamp": { + "type": "bool", + "id": 10 + }, + "arrayValue": { + "type": "ValueList", + "id": 11 + }, + "arrayType": { + "type": "google.spanner.v1.Type", + "id": 12, + "options": { + "proto3_optional": true + } + } + } + }, + "KeyRange": { + "oneofs": { + "_type": { + "oneof": [ + "type" + ] + } + }, + "fields": { + "start": { + "type": "ValueList", + "id": 1 + }, + "limit": { + "type": "ValueList", + "id": 2 + }, + "type": { + "type": "Type", + "id": 3, + "options": { + "proto3_optional": true + } + } + }, + "nested": { + "Type": { + "values": { + "TYPE_UNSPECIFIED": 0, + "CLOSED_CLOSED": 1, + "CLOSED_OPEN": 2, + "OPEN_CLOSED": 3, + "OPEN_OPEN": 4 + } + } + } + }, + "KeySet": { + "fields": { + "point": { + "rule": "repeated", + "type": "ValueList", + "id": 1 + }, + "range": { + "rule": "repeated", + "type": "KeyRange", + "id": 2 + }, + "all": { + "type": "bool", + "id": 3 + } + } + }, + "ValueList": { + "fields": { + "value": { + "rule": "repeated", + "type": "Value", + "id": 1 + } + } + }, + "MutationAction": { + "fields": { + "mod": { + "rule": "repeated", + "type": "Mod", + "id": 1 + } + }, + "nested": { + "InsertArgs": { + "fields": { + "column": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "type": { + "rule": "repeated", + "type": "google.spanner.v1.Type", + "id": 2 + }, + "values": { + "rule": "repeated", + "type": "ValueList", + "id": 3 + } + } + }, + "UpdateArgs": { + "fields": { + "column": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "type": { + "rule": "repeated", + "type": "google.spanner.v1.Type", + "id": 2 + }, + "values": { + "rule": "repeated", + "type": "ValueList", + "id": 3 + } + } + }, + "Mod": { + "fields": { + "table": { + "type": "string", + "id": 1 + }, + "insert": { + "type": "InsertArgs", + "id": 2 + }, + "update": { + "type": "UpdateArgs", + "id": 3 + }, + "insertOrUpdate": { + "type": "InsertArgs", + "id": 4 + }, + "replace": { + "type": "InsertArgs", + "id": 5 + }, + "deleteKeys": { + "type": "KeySet", + "id": 6 + } + } + } + } + }, + "WriteMutationsAction": { + "fields": { + "mutation": { + "type": "MutationAction", + "id": 1 + } + } + }, + "PartitionedUpdateAction": { + "oneofs": { + "_options": { + "oneof": [ + "options" + ] + } + }, + "fields": { + "options": { + "type": "ExecutePartitionedUpdateOptions", + "id": 1, + "options": { + "proto3_optional": true + } + }, + "update": { + "type": "QueryAction", + "id": 2 + } + }, + "nested": { + "ExecutePartitionedUpdateOptions": { + "oneofs": { + "_rpcPriority": { + "oneof": [ + "rpcPriority" + ] + }, + "_tag": { + "oneof": [ + "tag" + ] + } + }, + "fields": { + "rpcPriority": { + "type": "google.spanner.v1.RequestOptions.Priority", + "id": 1, + "options": { + "proto3_optional": true + } + }, + "tag": { + "type": "string", + "id": 2, + "options": { + "proto3_optional": true + } + } + } + } + } + }, + "StartTransactionAction": { + "oneofs": { + "_concurrency": { + "oneof": [ + "concurrency" + ] + }, + "_executionOptions": { + "oneof": [ + "executionOptions" + ] + } + }, + "fields": { + "concurrency": { + "type": "Concurrency", + "id": 1, + "options": { + "proto3_optional": true + } + }, + "table": { + "rule": "repeated", + "type": "TableMetadata", + "id": 2 + }, + "transactionSeed": { + "type": "string", + "id": 3 + }, + "executionOptions": { + "type": "TransactionExecutionOptions", + "id": 4, + "options": { + "proto3_optional": true + } + } + } + }, + "Concurrency": { + "oneofs": { + "concurrencyMode": { + "oneof": [ + "stalenessSeconds", + "minReadTimestampMicros", + "maxStalenessSeconds", + "exactTimestampMicros", + "strong", + "batch" + ] + } + }, + "fields": { + "stalenessSeconds": { + "type": "double", + "id": 1 + }, + "minReadTimestampMicros": { + "type": "int64", + "id": 2 + }, + "maxStalenessSeconds": { + "type": "double", + "id": 3 + }, + "exactTimestampMicros": { + "type": "int64", + "id": 4 + }, + "strong": { + "type": "bool", + "id": 5 + }, + "batch": { + "type": "bool", + "id": 6 + }, + "snapshotEpochRead": { + "type": "bool", + "id": 7 + }, + "snapshotEpochRootTable": { + "type": "string", + "id": 8 + }, + "batchReadTimestampMicros": { + "type": "int64", + "id": 9 + } + } + }, + "TableMetadata": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "column": { + "rule": "repeated", + "type": "ColumnMetadata", + "id": 2 + }, + "keyColumn": { + "rule": "repeated", + "type": "ColumnMetadata", + "id": 3 + } + } + }, + "ColumnMetadata": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "type": { + "type": "google.spanner.v1.Type", + "id": 2 + } + } + }, + "TransactionExecutionOptions": { + "fields": { + "optimistic": { + "type": "bool", + "id": 1 + }, + "excludeFromChangeStreams": { + "type": "bool", + "id": 2 + }, + "serializableOptimistic": { + "type": "bool", + "id": 3 + }, + "snapshotIsolationOptimistic": { + "type": "bool", + "id": 4 + }, + "snapshotIsolationPessimistic": { + "type": "bool", + "id": 5 + }, + "excludeTxnFromChangeStreams": { + "type": "bool", + "id": 6 + } + } + }, + "FinishTransactionAction": { + "fields": { + "mode": { + "type": "Mode", + "id": 1 + } + }, + "nested": { + "Mode": { + "values": { + "MODE_UNSPECIFIED": 0, + "COMMIT": 1, + "ABANDON": 2 + } + } + } + }, + "AdminAction": { + "oneofs": { + "action": { + "oneof": [ + "createUserInstanceConfig", + "updateUserInstanceConfig", + "deleteUserInstanceConfig", + "getCloudInstanceConfig", + "listInstanceConfigs", + "createCloudInstance", + "updateCloudInstance", + "deleteCloudInstance", + "listCloudInstances", + "getCloudInstance", + "createCloudDatabase", + "updateCloudDatabaseDdl", + "updateCloudDatabase", + "dropCloudDatabase", + "listCloudDatabases", + "listCloudDatabaseOperations", + "restoreCloudDatabase", + "getCloudDatabase", + "createCloudBackup", + "copyCloudBackup", + "getCloudBackup", + "updateCloudBackup", + "deleteCloudBackup", + "listCloudBackups", + "listCloudBackupOperations", + "getOperation", + "cancelOperation", + "changeQuorumCloudDatabase", + "addSplitPoints" + ] + } + }, + "fields": { + "createUserInstanceConfig": { + "type": "CreateUserInstanceConfigAction", + "id": 1 + }, + "updateUserInstanceConfig": { + "type": "UpdateUserInstanceConfigAction", + "id": 2 + }, + "deleteUserInstanceConfig": { + "type": "DeleteUserInstanceConfigAction", + "id": 3 + }, + "getCloudInstanceConfig": { + "type": "GetCloudInstanceConfigAction", + "id": 4 + }, + "listInstanceConfigs": { + "type": "ListCloudInstanceConfigsAction", + "id": 5 + }, + "createCloudInstance": { + "type": "CreateCloudInstanceAction", + "id": 6 + }, + "updateCloudInstance": { + "type": "UpdateCloudInstanceAction", + "id": 7 + }, + "deleteCloudInstance": { + "type": "DeleteCloudInstanceAction", + "id": 8 + }, + "listCloudInstances": { + "type": "ListCloudInstancesAction", + "id": 9 + }, + "getCloudInstance": { + "type": "GetCloudInstanceAction", + "id": 10 + }, + "createCloudDatabase": { + "type": "CreateCloudDatabaseAction", + "id": 11 + }, + "updateCloudDatabaseDdl": { + "type": "UpdateCloudDatabaseDdlAction", + "id": 12 + }, + "updateCloudDatabase": { + "type": "UpdateCloudDatabaseAction", + "id": 27 + }, + "dropCloudDatabase": { + "type": "DropCloudDatabaseAction", + "id": 13 + }, + "listCloudDatabases": { + "type": "ListCloudDatabasesAction", + "id": 14 + }, + "listCloudDatabaseOperations": { + "type": "ListCloudDatabaseOperationsAction", + "id": 15 + }, + "restoreCloudDatabase": { + "type": "RestoreCloudDatabaseAction", + "id": 16 + }, + "getCloudDatabase": { + "type": "GetCloudDatabaseAction", + "id": 17 + }, + "createCloudBackup": { + "type": "CreateCloudBackupAction", + "id": 18 + }, + "copyCloudBackup": { + "type": "CopyCloudBackupAction", + "id": 19 + }, + "getCloudBackup": { + "type": "GetCloudBackupAction", + "id": 20 + }, + "updateCloudBackup": { + "type": "UpdateCloudBackupAction", + "id": 21 + }, + "deleteCloudBackup": { + "type": "DeleteCloudBackupAction", + "id": 22 + }, + "listCloudBackups": { + "type": "ListCloudBackupsAction", + "id": 23 + }, + "listCloudBackupOperations": { + "type": "ListCloudBackupOperationsAction", + "id": 24 + }, + "getOperation": { + "type": "GetOperationAction", + "id": 25 + }, + "cancelOperation": { + "type": "CancelOperationAction", + "id": 26 + }, + "changeQuorumCloudDatabase": { + "type": "ChangeQuorumCloudDatabaseAction", + "id": 28 + }, + "addSplitPoints": { + "type": "AddSplitPointsAction", + "id": 29 + } + } + }, + "CreateUserInstanceConfigAction": { + "fields": { + "userConfigId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + }, + "baseConfigId": { + "type": "string", + "id": 3 + }, + "replicas": { + "rule": "repeated", + "type": "google.spanner.admin.instance.v1.ReplicaInfo", + "id": 4 + } + } + }, + "UpdateUserInstanceConfigAction": { + "oneofs": { + "_displayName": { + "oneof": [ + "displayName" + ] + } + }, + "fields": { + "userConfigId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + }, + "displayName": { + "type": "string", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 4 + } + } + }, + "GetCloudInstanceConfigAction": { + "fields": { + "instanceConfigId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + } + } + }, + "DeleteUserInstanceConfigAction": { + "fields": { + "userConfigId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + } + } + }, + "ListCloudInstanceConfigsAction": { + "oneofs": { + "_pageSize": { + "oneof": [ + "pageSize" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + } + }, + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "pageSize": { + "type": "int32", + "id": 2, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 3, + "options": { + "proto3_optional": true + } + } + } + }, + "CreateCloudInstanceAction": { + "oneofs": { + "_nodeCount": { + "oneof": [ + "nodeCount" + ] + }, + "_processingUnits": { + "oneof": [ + "processingUnits" + ] + }, + "_autoscalingConfig": { + "oneof": [ + "autoscalingConfig" + ] + } + }, + "fields": { + "instanceId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + }, + "instanceConfigId": { + "type": "string", + "id": 3 + }, + "nodeCount": { + "type": "int32", + "id": 4, + "options": { + "proto3_optional": true + } + }, + "processingUnits": { + "type": "int32", + "id": 6, + "options": { + "proto3_optional": true + } + }, + "autoscalingConfig": { + "type": "google.spanner.admin.instance.v1.AutoscalingConfig", + "id": 7, + "options": { + "proto3_optional": true + } + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 5 + }, + "edition": { + "type": "google.spanner.admin.instance.v1.Instance.Edition", + "id": 8 + } + } + }, + "UpdateCloudInstanceAction": { + "oneofs": { + "_displayName": { + "oneof": [ + "displayName" + ] + }, + "_nodeCount": { + "oneof": [ + "nodeCount" + ] + }, + "_processingUnits": { + "oneof": [ + "processingUnits" + ] + }, + "_autoscalingConfig": { + "oneof": [ + "autoscalingConfig" + ] + } + }, + "fields": { + "instanceId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + }, + "displayName": { + "type": "string", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "nodeCount": { + "type": "int32", + "id": 4, + "options": { + "proto3_optional": true + } + }, + "processingUnits": { + "type": "int32", + "id": 5, + "options": { + "proto3_optional": true + } + }, + "autoscalingConfig": { + "type": "google.spanner.admin.instance.v1.AutoscalingConfig", + "id": 7, + "options": { + "proto3_optional": true + } + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 6 + }, + "edition": { + "type": "google.spanner.admin.instance.v1.Instance.Edition", + "id": 8 + } + } + }, + "DeleteCloudInstanceAction": { + "fields": { + "instanceId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + } + } + }, + "CreateCloudDatabaseAction": { + "oneofs": { + "_dialect": { + "oneof": [ + "dialect" + ] + }, + "_protoDescriptors": { + "oneof": [ + "protoDescriptors" + ] + } + }, + "fields": { + "instanceId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + }, + "databaseId": { + "type": "string", + "id": 3 + }, + "sdlStatement": { + "rule": "repeated", + "type": "string", + "id": 4 + }, + "encryptionConfig": { + "type": "google.spanner.admin.database.v1.EncryptionConfig", + "id": 5 + }, + "dialect": { + "type": "string", + "id": 6, + "options": { + "proto3_optional": true + } + }, + "protoDescriptors": { + "type": "bytes", + "id": 7, + "options": { + "proto3_optional": true + } + } + } + }, + "UpdateCloudDatabaseDdlAction": { + "oneofs": { + "_protoDescriptors": { + "oneof": [ + "protoDescriptors" + ] + } + }, + "fields": { + "instanceId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + }, + "databaseId": { + "type": "string", + "id": 3 + }, + "sdlStatement": { + "rule": "repeated", + "type": "string", + "id": 4 + }, + "operationId": { + "type": "string", + "id": 5 + }, + "protoDescriptors": { + "type": "bytes", + "id": 6, + "options": { + "proto3_optional": true + } + } + } + }, + "UpdateCloudDatabaseAction": { + "fields": { + "instanceId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + }, + "databaseName": { + "type": "string", + "id": 3 + }, + "enableDropProtection": { + "type": "bool", + "id": 4 + } + } + }, + "DropCloudDatabaseAction": { + "fields": { + "instanceId": { + "type": "string", + "id": 1 + }, + "projectId": { + "type": "string", + "id": 2 + }, + "databaseId": { + "type": "string", + "id": 3 + } + } + }, + "ChangeQuorumCloudDatabaseAction": { + "oneofs": { + "_databaseUri": { + "oneof": [ + "databaseUri" + ] + } + }, + "fields": { + "databaseUri": { + "type": "string", + "id": 1, + "options": { + "proto3_optional": true + } + }, + "servingLocations": { + "rule": "repeated", + "type": "string", + "id": 2 + } + } + }, + "AdaptMessageAction": { + "fields": { + "databaseUri": { + "type": "string", + "id": 1 + }, + "protocol": { + "type": "string", + "id": 2 + }, + "payload": { + "type": "bytes", + "id": 3 + }, + "attachments": { + "keyType": "string", + "type": "string", + "id": 4 + }, + "query": { + "type": "string", + "id": 5 + }, + "prepareThenExecute": { + "type": "bool", + "id": 6 + } + } + }, + "ListCloudDatabasesAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "pageSize": { + "type": "int32", + "id": 3 + }, + "pageToken": { + "type": "string", + "id": 4 + } + } + }, + "ListCloudInstancesAction": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_pageSize": { + "oneof": [ + "pageSize" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + } + }, + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "filter": { + "type": "string", + "id": 2, + "options": { + "proto3_optional": true + } + }, + "pageSize": { + "type": "int32", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 4, + "options": { + "proto3_optional": true + } + } + } + }, + "GetCloudInstanceAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + } + } + }, + "ListCloudDatabaseOperationsAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "filter": { + "type": "string", + "id": 3 + }, + "pageSize": { + "type": "int32", + "id": 4 + }, + "pageToken": { + "type": "string", + "id": 5 + } + } + }, + "RestoreCloudDatabaseAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "backupInstanceId": { + "type": "string", + "id": 2 + }, + "backupId": { + "type": "string", + "id": 3 + }, + "databaseInstanceId": { + "type": "string", + "id": 4 + }, + "databaseId": { + "type": "string", + "id": 5 + }, + "encryptionConfig": { + "type": "google.spanner.admin.database.v1.EncryptionConfig", + "id": 7 + } + } + }, + "GetCloudDatabaseAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "databaseId": { + "type": "string", + "id": 3 + } + } + }, + "CreateCloudBackupAction": { + "oneofs": { + "_versionTime": { + "oneof": [ + "versionTime" + ] + } + }, + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "backupId": { + "type": "string", + "id": 3 + }, + "databaseId": { + "type": "string", + "id": 4 + }, + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "versionTime": { + "type": "google.protobuf.Timestamp", + "id": 6, + "options": { + "proto3_optional": true + } + }, + "encryptionConfig": { + "type": "google.spanner.admin.database.v1.EncryptionConfig", + "id": 7 + } + } + }, + "CopyCloudBackupAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "backupId": { + "type": "string", + "id": 3 + }, + "sourceBackup": { + "type": "string", + "id": 4 + }, + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "GetCloudBackupAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "backupId": { + "type": "string", + "id": 3 + } + } + }, + "UpdateCloudBackupAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "backupId": { + "type": "string", + "id": 3 + }, + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "DeleteCloudBackupAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "backupId": { + "type": "string", + "id": 3 + } + } + }, + "ListCloudBackupsAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "filter": { + "type": "string", + "id": 3 + }, + "pageSize": { + "type": "int32", + "id": 4 + }, + "pageToken": { + "type": "string", + "id": 5 + } + } + }, + "ListCloudBackupOperationsAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "filter": { + "type": "string", + "id": 3 + }, + "pageSize": { + "type": "int32", + "id": 4 + }, + "pageToken": { + "type": "string", + "id": 5 + } + } + }, + "GetOperationAction": { + "fields": { + "operation": { + "type": "string", + "id": 1 + } + } + }, + "QueryCancellationAction": { + "fields": { + "longRunningSql": { + "type": "string", + "id": 1 + }, + "cancelQuery": { + "type": "string", + "id": 2 + } + } + }, + "CancelOperationAction": { + "fields": { + "operation": { + "type": "string", + "id": 1 + } + } + }, + "AddSplitPointsAction": { + "fields": { + "projectId": { + "type": "string", + "id": 1 + }, + "instanceId": { + "type": "string", + "id": 2 + }, + "databaseId": { + "type": "string", + "id": 3 + }, + "splitPoints": { + "rule": "repeated", + "type": "google.spanner.admin.database.v1.SplitPoints", + "id": 4 + } + } + }, + "StartBatchTransactionAction": { + "oneofs": { + "param": { + "oneof": [ + "batchTxnTime", + "tid" + ] + } + }, + "fields": { + "batchTxnTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "tid": { + "type": "bytes", + "id": 2 + }, + "cloudDatabaseRole": { + "type": "string", + "id": 3 + } + } + }, + "CloseBatchTransactionAction": { + "fields": { + "cleanup": { + "type": "bool", + "id": 1 + } + } + }, + "GenerateDbPartitionsForReadAction": { + "oneofs": { + "_desiredBytesPerPartition": { + "oneof": [ + "desiredBytesPerPartition" + ] + }, + "_maxPartitionCount": { + "oneof": [ + "maxPartitionCount" + ] + } + }, + "fields": { + "read": { + "type": "ReadAction", + "id": 1 + }, + "table": { + "rule": "repeated", + "type": "TableMetadata", + "id": 2 + }, + "desiredBytesPerPartition": { + "type": "int64", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "maxPartitionCount": { + "type": "int64", + "id": 4, + "options": { + "proto3_optional": true + } + } + } + }, + "GenerateDbPartitionsForQueryAction": { + "oneofs": { + "_desiredBytesPerPartition": { + "oneof": [ + "desiredBytesPerPartition" + ] + } + }, + "fields": { + "query": { + "type": "QueryAction", + "id": 1 + }, + "desiredBytesPerPartition": { + "type": "int64", + "id": 2, + "options": { + "proto3_optional": true + } + } + } + }, + "BatchPartition": { + "oneofs": { + "_table": { + "oneof": [ + "table" + ] + }, + "_index": { + "oneof": [ + "index" + ] + } + }, + "fields": { + "partition": { + "type": "bytes", + "id": 1 + }, + "partitionToken": { + "type": "bytes", + "id": 2 + }, + "table": { + "type": "string", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "index": { + "type": "string", + "id": 4, + "options": { + "proto3_optional": true + } + } + } + }, + "ExecutePartitionAction": { + "fields": { + "partition": { + "type": "BatchPartition", + "id": 1 + } + } + }, + "ExecuteChangeStreamQuery": { + "oneofs": { + "_endTime": { + "oneof": [ + "endTime" + ] + }, + "_partitionToken": { + "oneof": [ + "partitionToken" + ] + }, + "_heartbeatMilliseconds": { + "oneof": [ + "heartbeatMilliseconds" + ] + }, + "_deadlineSeconds": { + "oneof": [ + "deadlineSeconds" + ] + }, + "_cloudDatabaseRole": { + "oneof": [ + "cloudDatabaseRole" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "partitionToken": { + "type": "string", + "id": 4, + "options": { + "proto3_optional": true + } + }, + "readOptions": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "heartbeatMilliseconds": { + "type": "int32", + "id": 6, + "options": { + "proto3_optional": true + } + }, + "deadlineSeconds": { + "type": "int64", + "id": 7, + "options": { + "proto3_optional": true + } + }, + "cloudDatabaseRole": { + "type": "string", + "id": 8, + "options": { + "proto3_optional": true + } + } + } + }, + "SpannerActionOutcome": { + "oneofs": { + "_status": { + "oneof": [ + "status" + ] + }, + "_commitTime": { + "oneof": [ + "commitTime" + ] + }, + "_readResult": { + "oneof": [ + "readResult" + ] + }, + "_queryResult": { + "oneof": [ + "queryResult" + ] + }, + "_transactionRestarted": { + "oneof": [ + "transactionRestarted" + ] + }, + "_batchTxnId": { + "oneof": [ + "batchTxnId" + ] + }, + "_adminResult": { + "oneof": [ + "adminResult" + ] + }, + "_snapshotIsolationTxnReadTimestamp": { + "oneof": [ + "snapshotIsolationTxnReadTimestamp" + ] + } + }, + "fields": { + "status": { + "type": "google.rpc.Status", + "id": 1, + "options": { + "proto3_optional": true + } + }, + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 2, + "options": { + "proto3_optional": true + } + }, + "readResult": { + "type": "ReadResult", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "queryResult": { + "type": "QueryResult", + "id": 4, + "options": { + "proto3_optional": true + } + }, + "transactionRestarted": { + "type": "bool", + "id": 5, + "options": { + "proto3_optional": true + } + }, + "batchTxnId": { + "type": "bytes", + "id": 6, + "options": { + "proto3_optional": true + } + }, + "dbPartition": { + "rule": "repeated", + "type": "BatchPartition", + "id": 7 + }, + "adminResult": { + "type": "AdminResult", + "id": 8, + "options": { + "proto3_optional": true + } + }, + "dmlRowsModified": { + "rule": "repeated", + "type": "int64", + "id": 9 + }, + "changeStreamRecords": { + "rule": "repeated", + "type": "ChangeStreamRecord", + "id": 10 + }, + "snapshotIsolationTxnReadTimestamp": { + "type": "int64", + "id": 11, + "options": { + "proto3_optional": true + } + } + } + }, + "AdminResult": { + "fields": { + "backupResponse": { + "type": "CloudBackupResponse", + "id": 1 + }, + "operationResponse": { + "type": "OperationResponse", + "id": 2 + }, + "databaseResponse": { + "type": "CloudDatabaseResponse", + "id": 3 + }, + "instanceResponse": { + "type": "CloudInstanceResponse", + "id": 4 + }, + "instanceConfigResponse": { + "type": "CloudInstanceConfigResponse", + "id": 5 + } + } + }, + "CloudBackupResponse": { + "fields": { + "listedBackups": { + "rule": "repeated", + "type": "google.spanner.admin.database.v1.Backup", + "id": 1 + }, + "listedBackupOperations": { + "rule": "repeated", + "type": "google.longrunning.Operation", + "id": 2 + }, + "nextPageToken": { + "type": "string", + "id": 3 + }, + "backup": { + "type": "google.spanner.admin.database.v1.Backup", + "id": 4 + } + } + }, + "OperationResponse": { + "fields": { + "listedOperations": { + "rule": "repeated", + "type": "google.longrunning.Operation", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + }, + "operation": { + "type": "google.longrunning.Operation", + "id": 3 + } + } + }, + "CloudInstanceResponse": { + "fields": { + "listedInstances": { + "rule": "repeated", + "type": "google.spanner.admin.instance.v1.Instance", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + }, + "instance": { + "type": "google.spanner.admin.instance.v1.Instance", + "id": 3 + } + } + }, + "CloudInstanceConfigResponse": { + "fields": { + "listedInstanceConfigs": { + "rule": "repeated", + "type": "google.spanner.admin.instance.v1.InstanceConfig", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + }, + "instanceConfig": { + "type": "google.spanner.admin.instance.v1.InstanceConfig", + "id": 3 + } + } + }, + "CloudDatabaseResponse": { + "fields": { + "listedDatabases": { + "rule": "repeated", + "type": "google.spanner.admin.database.v1.Database", + "id": 1 + }, + "listedDatabaseOperations": { + "rule": "repeated", + "type": "google.longrunning.Operation", + "id": 2 + }, + "nextPageToken": { + "type": "string", + "id": 3 + }, + "database": { + "type": "google.spanner.admin.database.v1.Database", + "id": 4 + } + } + }, + "ReadResult": { + "oneofs": { + "_index": { + "oneof": [ + "index" + ] + }, + "_requestIndex": { + "oneof": [ + "requestIndex" + ] + }, + "_rowType": { + "oneof": [ + "rowType" + ] + } + }, + "fields": { + "table": { + "type": "string", + "id": 1 + }, + "index": { + "type": "string", + "id": 2, + "options": { + "proto3_optional": true + } + }, + "requestIndex": { + "type": "int32", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "row": { + "rule": "repeated", + "type": "ValueList", + "id": 4 + }, + "rowType": { + "type": "google.spanner.v1.StructType", + "id": 5, + "options": { + "proto3_optional": true + } + } + } + }, + "QueryResult": { + "oneofs": { + "_rowType": { + "oneof": [ + "rowType" + ] + } + }, + "fields": { + "row": { + "rule": "repeated", + "type": "ValueList", + "id": 1 + }, + "rowType": { + "type": "google.spanner.v1.StructType", + "id": 2, + "options": { + "proto3_optional": true + } + } + } + }, + "ChangeStreamRecord": { + "oneofs": { + "record": { + "oneof": [ + "dataChange", + "childPartition", + "heartbeat" + ] + } + }, + "fields": { + "dataChange": { + "type": "DataChangeRecord", + "id": 1 + }, + "childPartition": { + "type": "ChildPartitionsRecord", + "id": 2 + }, + "heartbeat": { + "type": "HeartbeatRecord", + "id": 3 + } + } + }, + "DataChangeRecord": { + "fields": { + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "recordSequence": { + "type": "string", + "id": 2 + }, + "transactionId": { + "type": "string", + "id": 3 + }, + "isLastRecord": { + "type": "bool", + "id": 4 + }, + "table": { + "type": "string", + "id": 5 + }, + "columnTypes": { + "rule": "repeated", + "type": "ColumnType", + "id": 6 + }, + "mods": { + "rule": "repeated", + "type": "Mod", + "id": 7 + }, + "modType": { + "type": "string", + "id": 8 + }, + "valueCaptureType": { + "type": "string", + "id": 9 + }, + "recordCount": { + "type": "int64", + "id": 10 + }, + "partitionCount": { + "type": "int64", + "id": 11 + }, + "transactionTag": { + "type": "string", + "id": 12 + }, + "isSystemTransaction": { + "type": "bool", + "id": 13 + } + }, + "nested": { + "ColumnType": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "type": { + "type": "string", + "id": 2 + }, + "isPrimaryKey": { + "type": "bool", + "id": 3 + }, + "ordinalPosition": { + "type": "int64", + "id": 4 + } + } + }, + "Mod": { + "fields": { + "keys": { + "type": "string", + "id": 1 + }, + "newValues": { + "type": "string", + "id": 2 + }, + "oldValues": { + "type": "string", + "id": 3 + } + } + } + } + }, + "ChildPartitionsRecord": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "recordSequence": { + "type": "string", + "id": 2 + }, + "childPartitions": { + "rule": "repeated", + "type": "ChildPartition", + "id": 3 + } + }, + "nested": { + "ChildPartition": { + "fields": { + "token": { + "type": "string", + "id": 1 + }, + "parentPartitionTokens": { + "rule": "repeated", + "type": "string", + "id": 2 + } + } + } + } + }, + "HeartbeatRecord": { + "fields": { + "heartbeatTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + } + } + }, + "SpannerOptions": { + "fields": { + "sessionPoolOptions": { + "type": "SessionPoolOptions", + "id": 1 + } + } + }, + "SessionPoolOptions": { + "fields": { + "useMultiplexed": { + "type": "bool", + "id": 1 + } + } + } + } + } + } + }, + "v1": { + "options": { + "csharp_namespace": "Google.Cloud.Spanner.V1", + "go_package": "cloud.google.com/go/spanner/apiv1/spannerpb;spannerpb", + "java_multiple_files": true, + "java_outer_classname": "ChangeStreamProto", + "java_package": "com.google.spanner.v1", + "php_namespace": "Google\\Cloud\\Spanner\\V1", + "ruby_package": "Google::Cloud::Spanner::V1", + "(google.api.resource_definition).type": "spanner.googleapis.com/Database", + "(google.api.resource_definition).pattern": "projects/{project}/instances/{instance}/databases/{database}" + }, + "nested": { + "Spanner": { + "options": { + "(google.api.default_host)": "spanner.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/spanner.data" + }, + "methods": { + "CreateSession": { + "requestType": "CreateSessionRequest", + "responseType": "Session", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/instances/*/databases/*}/sessions", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/instances/*/databases/*}/sessions", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + "BatchCreateSessions": { + "requestType": "BatchCreateSessionsRequest", + "responseType": "BatchCreateSessionsResponse", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/instances/*/databases/*}/sessions:batchCreate", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,session_count" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/instances/*/databases/*}/sessions:batchCreate", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,session_count" + } + ] + }, + "GetSession": { + "requestType": "GetSessionRequest", + "responseType": "Session", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/instances/*/databases/*/sessions/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/instances/*/databases/*/sessions/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListSessions": { + "requestType": "ListSessionsRequest", + "responseType": "ListSessionsResponse", + "options": { + "(google.api.http).get": "/v1/{database=projects/*/instances/*/databases/*}/sessions", + "(google.api.method_signature)": "database" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{database=projects/*/instances/*/databases/*}/sessions" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + "DeleteSession": { + "requestType": "DeleteSessionRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/instances/*/databases/*/sessions/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/instances/*/databases/*/sessions/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ExecuteSql": { + "requestType": "ExecuteSqlRequest", + "responseType": "ResultSet", + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeSql", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeSql", + "body": "*" + } + } + ] + }, + "ExecuteStreamingSql": { + "requestType": "ExecuteSqlRequest", + "responseType": "PartialResultSet", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeStreamingSql", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeStreamingSql", + "body": "*" + } + } + ] + }, + "ExecuteBatchDml": { + "requestType": "ExecuteBatchDmlRequest", + "responseType": "ExecuteBatchDmlResponse", + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeBatchDml", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeBatchDml", + "body": "*" + } + } + ] + }, + "Read": { + "requestType": "ReadRequest", + "responseType": "ResultSet", + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:read", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:read", + "body": "*" + } + } + ] + }, + "StreamingRead": { + "requestType": "ReadRequest", + "responseType": "PartialResultSet", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:streamingRead", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:streamingRead", + "body": "*" + } + } + ] + }, + "BeginTransaction": { + "requestType": "BeginTransactionRequest", + "responseType": "Transaction", + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:beginTransaction", + "(google.api.http).body": "*", + "(google.api.method_signature)": "session,options" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:beginTransaction", + "body": "*" + } + }, + { + "(google.api.method_signature)": "session,options" + } + ] + }, + "Commit": { + "requestType": "CommitRequest", + "responseType": "CommitResponse", + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:commit", + "(google.api.http).body": "*", + "(google.api.method_signature)": "session,single_use_transaction,mutations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:commit", + "body": "*" + } + }, + { + "(google.api.method_signature)": "session,transaction_id,mutations" + }, + { + "(google.api.method_signature)": "session,single_use_transaction,mutations" + } + ] + }, + "Rollback": { + "requestType": "RollbackRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:rollback", + "(google.api.http).body": "*", + "(google.api.method_signature)": "session,transaction_id" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:rollback", + "body": "*" + } + }, + { + "(google.api.method_signature)": "session,transaction_id" + } + ] + }, + "PartitionQuery": { + "requestType": "PartitionQueryRequest", + "responseType": "PartitionResponse", + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:partitionQuery", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:partitionQuery", + "body": "*" + } + } + ] + }, + "PartitionRead": { + "requestType": "PartitionReadRequest", + "responseType": "PartitionResponse", + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:partitionRead", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:partitionRead", + "body": "*" + } + } + ] + }, + "BatchWrite": { + "requestType": "BatchWriteRequest", + "responseType": "BatchWriteResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:batchWrite", + "(google.api.http).body": "*", + "(google.api.method_signature)": "session,mutation_groups" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{session=projects/*/instances/*/databases/*/sessions/*}:batchWrite", + "body": "*" + } + }, + { + "(google.api.method_signature)": "session,mutation_groups" + } + ] + } + } + }, + "CreateSessionRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "session": { + "type": "Session", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "BatchCreateSessionsRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "sessionTemplate": { + "type": "Session", + "id": 2 + }, + "sessionCount": { + "type": "int32", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "BatchCreateSessionsResponse": { + "fields": { + "session": { + "rule": "repeated", + "type": "Session", + "id": 1 + } + } + }, + "Session": { + "options": { + "(google.api.resource).type": "spanner.googleapis.com/Session", + "(google.api.resource).pattern": "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}", + "(google.api.resource).plural": "sessions", + "(google.api.resource).singular": "session" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "approximateLastUseTime": { + "type": "google.protobuf.Timestamp", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "creatorRole": { + "type": "string", + "id": 5 + }, + "multiplexed": { + "type": "bool", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "GetSessionRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + } + } + }, + "ListSessionsRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Database" + } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + }, + "filter": { + "type": "string", + "id": 4 + } + } + }, + "ListSessionsResponse": { + "fields": { + "sessions": { + "rule": "repeated", + "type": "Session", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "DeleteSessionRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + } + } + }, + "RequestOptions": { + "fields": { + "priority": { + "type": "Priority", + "id": 1 + }, + "requestTag": { + "type": "string", + "id": 2 + }, + "transactionTag": { + "type": "string", + "id": 3 + }, + "clientContext": { + "type": "ClientContext", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "Priority": { + "values": { + "PRIORITY_UNSPECIFIED": 0, + "PRIORITY_LOW": 1, + "PRIORITY_MEDIUM": 2, + "PRIORITY_HIGH": 3 + } + }, + "ClientContext": { + "fields": { + "secureContext": { + "keyType": "string", + "type": "google.protobuf.Value", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + } + } + }, + "DirectedReadOptions": { + "oneofs": { + "replicas": { + "oneof": [ + "includeReplicas", + "excludeReplicas" + ] + } + }, + "fields": { + "includeReplicas": { + "type": "IncludeReplicas", + "id": 1 + }, + "excludeReplicas": { + "type": "ExcludeReplicas", + "id": 2 + } + }, + "nested": { + "ReplicaSelection": { + "fields": { + "location": { + "type": "string", + "id": 1 + }, + "type": { + "type": "Type", + "id": 2 + } + }, + "nested": { + "Type": { + "values": { + "TYPE_UNSPECIFIED": 0, + "READ_WRITE": 1, + "READ_ONLY": 2 + } + } + } + }, + "IncludeReplicas": { + "fields": { + "replicaSelections": { + "rule": "repeated", + "type": "ReplicaSelection", + "id": 1 + }, + "autoFailoverDisabled": { + "type": "bool", + "id": 2 + } + } + }, + "ExcludeReplicas": { + "fields": { + "replicaSelections": { + "rule": "repeated", + "type": "ReplicaSelection", + "id": 1 + } + } + } + } + }, + "ExecuteSqlRequest": { + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "transaction": { + "type": "TransactionSelector", + "id": 2 + }, + "sql": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "params": { + "type": "google.protobuf.Struct", + "id": 4 + }, + "paramTypes": { + "keyType": "string", + "type": "Type", + "id": 5 + }, + "resumeToken": { + "type": "bytes", + "id": 6 + }, + "queryMode": { + "type": "QueryMode", + "id": 7 + }, + "partitionToken": { + "type": "bytes", + "id": 8 + }, + "seqno": { + "type": "int64", + "id": 9 + }, + "queryOptions": { + "type": "QueryOptions", + "id": 10 + }, + "requestOptions": { + "type": "RequestOptions", + "id": 11 + }, + "directedReadOptions": { + "type": "DirectedReadOptions", + "id": 15 + }, + "dataBoostEnabled": { + "type": "bool", + "id": 16 + }, + "lastStatement": { + "type": "bool", + "id": 17, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "routingHint": { + "type": "RoutingHint", + "id": 18, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "QueryMode": { + "values": { + "NORMAL": 0, + "PLAN": 1, + "PROFILE": 2, + "WITH_STATS": 3, + "WITH_PLAN_AND_STATS": 4 + } + }, + "QueryOptions": { + "fields": { + "optimizerVersion": { + "type": "string", + "id": 1 + }, + "optimizerStatisticsPackage": { + "type": "string", + "id": 2 + } + } + } + } + }, + "ExecuteBatchDmlRequest": { + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "transaction": { + "type": "TransactionSelector", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "statements": { + "rule": "repeated", + "type": "Statement", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "seqno": { + "type": "int64", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "requestOptions": { + "type": "RequestOptions", + "id": 5 + }, + "lastStatements": { + "type": "bool", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "Statement": { + "fields": { + "sql": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "params": { + "type": "google.protobuf.Struct", + "id": 2 + }, + "paramTypes": { + "keyType": "string", + "type": "Type", + "id": 3 + } + } + } + } + }, + "ExecuteBatchDmlResponse": { + "fields": { + "resultSets": { + "rule": "repeated", + "type": "ResultSet", + "id": 1 + }, + "status": { + "type": "google.rpc.Status", + "id": 2 + }, + "precommitToken": { + "type": "MultiplexedSessionPrecommitToken", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "PartitionOptions": { + "fields": { + "partitionSizeBytes": { + "type": "int64", + "id": 1 + }, + "maxPartitions": { + "type": "int64", + "id": 2 + } + } + }, + "PartitionQueryRequest": { + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "transaction": { + "type": "TransactionSelector", + "id": 2 + }, + "sql": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "params": { + "type": "google.protobuf.Struct", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "paramTypes": { + "keyType": "string", + "type": "Type", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "partitionOptions": { + "type": "PartitionOptions", + "id": 6 + } + } + }, + "PartitionReadRequest": { + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "transaction": { + "type": "TransactionSelector", + "id": 2 + }, + "table": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "index": { + "type": "string", + "id": 4 + }, + "columns": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "keySet": { + "type": "KeySet", + "id": 6, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "partitionOptions": { + "type": "PartitionOptions", + "id": 9 + } + } + }, + "Partition": { + "fields": { + "partitionToken": { + "type": "bytes", + "id": 1 + } + } + }, + "PartitionResponse": { + "fields": { + "partitions": { + "rule": "repeated", + "type": "Partition", + "id": 1 + }, + "transaction": { + "type": "Transaction", + "id": 2 + } + } + }, + "ReadRequest": { + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "transaction": { + "type": "TransactionSelector", + "id": 2 + }, + "table": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "index": { + "type": "string", + "id": 4 + }, + "columns": { + "rule": "repeated", + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "keySet": { + "type": "KeySet", + "id": 6, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "limit": { + "type": "int64", + "id": 8 + }, + "resumeToken": { + "type": "bytes", + "id": 9 + }, + "partitionToken": { + "type": "bytes", + "id": 10 + }, + "requestOptions": { + "type": "RequestOptions", + "id": 11 + }, + "directedReadOptions": { + "type": "DirectedReadOptions", + "id": 14 + }, + "dataBoostEnabled": { + "type": "bool", + "id": 15 + }, + "orderBy": { + "type": "OrderBy", + "id": 16, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "lockHint": { + "type": "LockHint", + "id": 17, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "routingHint": { + "type": "RoutingHint", + "id": 18, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "OrderBy": { + "values": { + "ORDER_BY_UNSPECIFIED": 0, + "ORDER_BY_PRIMARY_KEY": 1, + "ORDER_BY_NO_ORDER": 2 + } + }, + "LockHint": { + "values": { + "LOCK_HINT_UNSPECIFIED": 0, + "LOCK_HINT_SHARED": 1, + "LOCK_HINT_EXCLUSIVE": 2 + } + } + } + }, + "BeginTransactionRequest": { + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "options": { + "type": "TransactionOptions", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "requestOptions": { + "type": "RequestOptions", + "id": 3 + }, + "mutationKey": { + "type": "Mutation", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "CommitRequest": { + "oneofs": { + "transaction": { + "oneof": [ + "transactionId", + "singleUseTransaction" + ] + } + }, + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "transactionId": { + "type": "bytes", + "id": 2 + }, + "singleUseTransaction": { + "type": "TransactionOptions", + "id": 3 + }, + "mutations": { + "rule": "repeated", + "type": "Mutation", + "id": 4 + }, + "returnCommitStats": { + "type": "bool", + "id": 5 + }, + "maxCommitDelay": { + "type": "google.protobuf.Duration", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "requestOptions": { + "type": "RequestOptions", + "id": 6 + }, + "precommitToken": { + "type": "MultiplexedSessionPrecommitToken", + "id": 9, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "RollbackRequest": { + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "transactionId": { + "type": "bytes", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "BatchWriteRequest": { + "fields": { + "session": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "spanner.googleapis.com/Session" + } + }, + "requestOptions": { + "type": "RequestOptions", + "id": 3 + }, + "mutationGroups": { + "rule": "repeated", + "type": "MutationGroup", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "excludeTxnFromChangeStreams": { + "type": "bool", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "MutationGroup": { + "fields": { + "mutations": { + "rule": "repeated", + "type": "Mutation", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + } + } + }, + "BatchWriteResponse": { + "fields": { + "indexes": { + "rule": "repeated", + "type": "int32", + "id": 1 + }, + "status": { + "type": "google.rpc.Status", + "id": 2 + }, + "commitTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 3 + } + } + }, + "CommitResponse": { + "oneofs": { + "MultiplexedSessionRetry": { + "oneof": [ + "precommitToken" + ] + } + }, + "fields": { + "commitTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "commitStats": { + "type": "CommitStats", + "id": 2 + }, + "precommitToken": { + "type": "MultiplexedSessionPrecommitToken", + "id": 4 + }, + "snapshotTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 5 + } + }, + "nested": { + "CommitStats": { + "fields": { + "mutationCount": { + "type": "int64", + "id": 1 + } + } + } + } + }, + "TransactionOptions": { + "oneofs": { + "mode": { + "oneof": [ + "readWrite", + "partitionedDml", + "readOnly" + ] + } + }, + "fields": { + "readWrite": { + "type": "ReadWrite", + "id": 1 + }, + "partitionedDml": { + "type": "PartitionedDml", + "id": 3 + }, + "readOnly": { + "type": "ReadOnly", + "id": 2 + }, + "excludeTxnFromChangeStreams": { + "type": "bool", + "id": 5 + }, + "isolationLevel": { + "type": "IsolationLevel", + "id": 6 + } + }, + "nested": { + "ReadWrite": { + "fields": { + "readLockMode": { + "type": "ReadLockMode", + "id": 1 + }, + "multiplexedSessionPreviousTransactionId": { + "type": "bytes", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "ReadLockMode": { + "values": { + "READ_LOCK_MODE_UNSPECIFIED": 0, + "PESSIMISTIC": 1, + "OPTIMISTIC": 2 + } + } + } + }, + "PartitionedDml": { + "fields": {} + }, + "ReadOnly": { + "oneofs": { + "timestampBound": { + "oneof": [ + "strong", + "minReadTimestamp", + "maxStaleness", + "readTimestamp", + "exactStaleness" + ] + } + }, + "fields": { + "strong": { + "type": "bool", + "id": 1 + }, + "minReadTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "maxStaleness": { + "type": "google.protobuf.Duration", + "id": 3 + }, + "readTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 4 + }, + "exactStaleness": { + "type": "google.protobuf.Duration", + "id": 5 + }, + "returnReadTimestamp": { + "type": "bool", + "id": 6 + } + } + }, + "IsolationLevel": { + "values": { + "ISOLATION_LEVEL_UNSPECIFIED": 0, + "SERIALIZABLE": 1, + "REPEATABLE_READ": 2 + } + } + } + }, + "Transaction": { + "fields": { + "id": { + "type": "bytes", + "id": 1 + }, + "readTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "precommitToken": { + "type": "MultiplexedSessionPrecommitToken", + "id": 3 + } + } + }, + "TransactionSelector": { + "oneofs": { + "selector": { + "oneof": [ + "singleUse", + "id", + "begin" + ] + } + }, + "fields": { + "singleUse": { + "type": "TransactionOptions", + "id": 1 + }, + "id": { + "type": "bytes", + "id": 2 + }, + "begin": { + "type": "TransactionOptions", + "id": 3 + } + } + }, + "MultiplexedSessionPrecommitToken": { + "fields": { + "precommitToken": { + "type": "bytes", + "id": 1 + }, + "seqNum": { + "type": "int32", + "id": 2 + } + } + }, + "KeyRange": { + "oneofs": { + "startKeyType": { + "oneof": [ + "startClosed", + "startOpen" + ] + }, + "endKeyType": { + "oneof": [ + "endClosed", + "endOpen" + ] + } + }, + "fields": { + "startClosed": { + "type": "google.protobuf.ListValue", + "id": 1 + }, + "startOpen": { + "type": "google.protobuf.ListValue", + "id": 2 + }, + "endClosed": { + "type": "google.protobuf.ListValue", + "id": 3 + }, + "endOpen": { + "type": "google.protobuf.ListValue", + "id": 4 + } + } + }, + "KeySet": { + "fields": { + "keys": { + "rule": "repeated", + "type": "google.protobuf.ListValue", + "id": 1 + }, + "ranges": { + "rule": "repeated", + "type": "KeyRange", + "id": 2 + }, + "all": { + "type": "bool", + "id": 3 + } + } + }, + "Range": { + "fields": { + "startKey": { + "type": "bytes", + "id": 1 + }, + "limitKey": { + "type": "bytes", + "id": 2 + }, + "groupUid": { + "type": "uint64", + "id": 3 + }, + "splitId": { + "type": "uint64", + "id": 4 + }, + "generation": { + "type": "bytes", + "id": 5 + } + } + }, + "Tablet": { + "fields": { + "tabletUid": { + "type": "uint64", + "id": 1 + }, + "serverAddress": { + "type": "string", + "id": 2 + }, + "location": { + "type": "string", + "id": 3 + }, + "role": { + "type": "Role", + "id": 4 + }, + "incarnation": { + "type": "bytes", + "id": 5 + }, + "distance": { + "type": "uint32", + "id": 6 + }, + "skip": { + "type": "bool", + "id": 7 + } + }, + "nested": { + "Role": { + "values": { + "ROLE_UNSPECIFIED": 0, + "READ_WRITE": 1, + "READ_ONLY": 2 + } + } + } + }, + "Group": { + "fields": { + "groupUid": { + "type": "uint64", + "id": 1 + }, + "tablets": { + "rule": "repeated", + "type": "Tablet", + "id": 2 + }, + "leaderIndex": { + "type": "int32", + "id": 3 + }, + "generation": { + "type": "bytes", + "id": 4 + } + } + }, + "KeyRecipe": { + "oneofs": { + "target": { + "oneof": [ + "tableName", + "indexName", + "operationUid" + ] + } + }, + "fields": { + "tableName": { + "type": "string", + "id": 1 + }, + "indexName": { + "type": "string", + "id": 2 + }, + "operationUid": { + "type": "uint64", + "id": 3 + }, + "part": { + "rule": "repeated", + "type": "Part", + "id": 4 + } + }, + "nested": { + "Part": { + "oneofs": { + "valueType": { + "oneof": [ + "identifier", + "value", + "random" + ] + } + }, + "fields": { + "tag": { + "type": "uint32", + "id": 1 + }, + "order": { + "type": "Order", + "id": 2 + }, + "nullOrder": { + "type": "NullOrder", + "id": 3 + }, + "type": { + "type": "Type", + "id": 4 + }, + "identifier": { + "type": "string", + "id": 5 + }, + "value": { + "type": "google.protobuf.Value", + "id": 6 + }, + "random": { + "type": "bool", + "id": 8 + }, + "structIdentifiers": { + "rule": "repeated", + "type": "int32", + "id": 7 + } + }, + "nested": { + "Order": { + "values": { + "ORDER_UNSPECIFIED": 0, + "ASCENDING": 1, + "DESCENDING": 2 + } + }, + "NullOrder": { + "values": { + "NULL_ORDER_UNSPECIFIED": 0, + "NULLS_FIRST": 1, + "NULLS_LAST": 2, + "NOT_NULL": 3 + } + } + } + } + } + }, + "RecipeList": { + "fields": { + "schemaGeneration": { + "type": "bytes", + "id": 1 + }, + "recipe": { + "rule": "repeated", + "type": "KeyRecipe", + "id": 3 + } + } + }, + "CacheUpdate": { + "fields": { + "databaseId": { + "type": "uint64", + "id": 1 + }, + "range": { + "rule": "repeated", + "type": "Range", + "id": 2 + }, + "group": { + "rule": "repeated", + "type": "Group", + "id": 3 + }, + "keyRecipes": { + "type": "RecipeList", + "id": 5 + } + } + }, + "RoutingHint": { + "fields": { + "operationUid": { + "type": "uint64", + "id": 1 + }, + "databaseId": { + "type": "uint64", + "id": 2 + }, + "schemaGeneration": { + "type": "bytes", + "id": 3 + }, + "key": { + "type": "bytes", + "id": 4 + }, + "limitKey": { + "type": "bytes", + "id": 5 + }, + "groupUid": { + "type": "uint64", + "id": 6 + }, + "splitId": { + "type": "uint64", + "id": 7 + }, + "tabletUid": { + "type": "uint64", + "id": 8 + }, + "skippedTabletUid": { + "rule": "repeated", + "type": "SkippedTablet", + "id": 9 + }, + "clientLocation": { + "type": "string", + "id": 10 + } + }, + "nested": { + "SkippedTablet": { + "fields": { + "tabletUid": { + "type": "uint64", + "id": 1 + }, + "incarnation": { + "type": "bytes", + "id": 2 + } + } + } + } + }, + "Type": { + "fields": { + "code": { + "type": "TypeCode", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "arrayElementType": { + "type": "Type", + "id": 2 + }, + "structType": { + "type": "StructType", + "id": 3 + }, + "typeAnnotation": { + "type": "TypeAnnotationCode", + "id": 4 + }, + "protoTypeFqn": { + "type": "string", + "id": 5 + } + } + }, + "StructType": { + "fields": { + "fields": { + "rule": "repeated", + "type": "Field", + "id": 1 + } + }, + "nested": { + "Field": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "type": { + "type": "Type", + "id": 2 + } + } + } + } + }, + "TypeCode": { + "values": { + "TYPE_CODE_UNSPECIFIED": 0, + "BOOL": 1, + "INT64": 2, + "FLOAT64": 3, + "FLOAT32": 15, + "TIMESTAMP": 4, + "DATE": 5, + "STRING": 6, + "BYTES": 7, + "ARRAY": 8, + "STRUCT": 9, + "NUMERIC": 10, + "JSON": 11, + "PROTO": 13, + "ENUM": 14, + "INTERVAL": 16, + "UUID": 17 + } + }, + "TypeAnnotationCode": { + "values": { + "TYPE_ANNOTATION_CODE_UNSPECIFIED": 0, + "PG_NUMERIC": 2, + "PG_JSONB": 3, + "PG_OID": 4 + } + }, + "Mutation": { + "oneofs": { + "operation": { + "oneof": [ + "insert", + "update", + "insertOrUpdate", + "replace", + "delete", + "send", + "ack" + ] + } + }, + "fields": { + "insert": { + "type": "Write", + "id": 1 + }, + "update": { + "type": "Write", + "id": 2 + }, + "insertOrUpdate": { + "type": "Write", + "id": 3 + }, + "replace": { + "type": "Write", + "id": 4 + }, + "delete": { + "type": "Delete", + "id": 5 + }, + "send": { + "type": "Send", + "id": 6 + }, + "ack": { + "type": "Ack", + "id": 7 + } + }, + "nested": { + "Write": { + "fields": { + "table": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "columns": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "values": { + "rule": "repeated", + "type": "google.protobuf.ListValue", + "id": 3 + } + } + }, + "Delete": { + "fields": { + "table": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "keySet": { + "type": "KeySet", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "Send": { + "fields": { + "queue": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "key": { + "type": "google.protobuf.ListValue", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "deliverTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "payload": { + "type": "google.protobuf.Value", + "id": 4 + } + } + }, + "Ack": { + "fields": { + "queue": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "key": { + "type": "google.protobuf.ListValue", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "ignoreNotFound": { + "type": "bool", + "id": 3 + } + } + } + } + }, + "ResultSet": { + "fields": { + "metadata": { + "type": "ResultSetMetadata", + "id": 1 + }, + "rows": { + "rule": "repeated", + "type": "google.protobuf.ListValue", + "id": 2 + }, + "stats": { + "type": "ResultSetStats", + "id": 3 + }, + "precommitToken": { + "type": "MultiplexedSessionPrecommitToken", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "cacheUpdate": { + "type": "CacheUpdate", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "PartialResultSet": { + "fields": { + "metadata": { + "type": "ResultSetMetadata", + "id": 1 + }, + "values": { + "rule": "repeated", + "type": "google.protobuf.Value", + "id": 2 + }, + "chunkedValue": { + "type": "bool", + "id": 3 + }, + "resumeToken": { + "type": "bytes", + "id": 4 + }, + "stats": { + "type": "ResultSetStats", + "id": 5 + }, + "precommitToken": { + "type": "MultiplexedSessionPrecommitToken", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "last": { + "type": "bool", + "id": 9, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "cacheUpdate": { + "type": "CacheUpdate", + "id": 10, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ResultSetMetadata": { + "fields": { + "rowType": { + "type": "StructType", + "id": 1 + }, + "transaction": { + "type": "Transaction", + "id": 2 + }, + "undeclaredParameters": { + "type": "StructType", + "id": 3 + } + } + }, + "ResultSetStats": { + "oneofs": { + "rowCount": { + "oneof": [ + "rowCountExact", + "rowCountLowerBound" + ] + } + }, + "fields": { + "queryPlan": { + "type": "QueryPlan", + "id": 1 + }, + "queryStats": { + "type": "google.protobuf.Struct", + "id": 2 + }, + "rowCountExact": { + "type": "int64", + "id": 3 + }, + "rowCountLowerBound": { + "type": "int64", + "id": 4 + } + } + }, + "PlanNode": { + "fields": { + "index": { + "type": "int32", + "id": 1 + }, + "kind": { + "type": "Kind", + "id": 2 + }, + "displayName": { + "type": "string", + "id": 3 + }, + "childLinks": { + "rule": "repeated", + "type": "ChildLink", + "id": 4 + }, + "shortRepresentation": { + "type": "ShortRepresentation", + "id": 5 + }, + "metadata": { + "type": "google.protobuf.Struct", + "id": 6 + }, + "executionStats": { + "type": "google.protobuf.Struct", + "id": 7 + } + }, + "nested": { + "Kind": { + "values": { + "KIND_UNSPECIFIED": 0, + "RELATIONAL": 1, + "SCALAR": 2 + } + }, + "ChildLink": { + "fields": { + "childIndex": { + "type": "int32", + "id": 1 + }, + "type": { + "type": "string", + "id": 2 + }, + "variable": { + "type": "string", + "id": 3 + } + } + }, + "ShortRepresentation": { + "fields": { + "description": { + "type": "string", + "id": 1 + }, + "subqueries": { + "keyType": "string", + "type": "int32", + "id": 2 + } + } + } + } + }, + "QueryAdvisorResult": { + "fields": { + "indexAdvice": { + "rule": "repeated", + "type": "IndexAdvice", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "IndexAdvice": { + "fields": { + "ddl": { + "rule": "repeated", + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "improvementFactor": { + "type": "double", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + } + } + }, + "QueryPlan": { + "fields": { + "planNodes": { + "rule": "repeated", + "type": "PlanNode", + "id": 1 + }, + "queryAdvice": { + "type": "QueryAdvisorResult", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ChangeStreamRecord": { + "oneofs": { + "record": { + "oneof": [ + "dataChangeRecord", + "heartbeatRecord", + "partitionStartRecord", + "partitionEndRecord", + "partitionEventRecord" + ] + } + }, + "fields": { + "dataChangeRecord": { + "type": "DataChangeRecord", + "id": 1 + }, + "heartbeatRecord": { + "type": "HeartbeatRecord", + "id": 2 + }, + "partitionStartRecord": { + "type": "PartitionStartRecord", + "id": 3 + }, + "partitionEndRecord": { + "type": "PartitionEndRecord", + "id": 4 + }, + "partitionEventRecord": { + "type": "PartitionEventRecord", + "id": 5 + } + }, + "nested": { + "DataChangeRecord": { + "fields": { + "commitTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "recordSequence": { + "type": "string", + "id": 2 + }, + "serverTransactionId": { + "type": "string", + "id": 3 + }, + "isLastRecordInTransactionInPartition": { + "type": "bool", + "id": 4 + }, + "table": { + "type": "string", + "id": 5 + }, + "columnMetadata": { + "rule": "repeated", + "type": "ColumnMetadata", + "id": 6 + }, + "mods": { + "rule": "repeated", + "type": "Mod", + "id": 7 + }, + "modType": { + "type": "ModType", + "id": 8 + }, + "valueCaptureType": { + "type": "ValueCaptureType", + "id": 9 + }, + "numberOfRecordsInTransaction": { + "type": "int32", + "id": 10 + }, + "numberOfPartitionsInTransaction": { + "type": "int32", + "id": 11 + }, + "transactionTag": { + "type": "string", + "id": 12 + }, + "isSystemTransaction": { + "type": "bool", + "id": 13 + } + }, + "nested": { + "ColumnMetadata": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "type": { + "type": "Type", + "id": 2 + }, + "isPrimaryKey": { + "type": "bool", + "id": 3 + }, + "ordinalPosition": { + "type": "int64", + "id": 4 + } + } + }, + "ModValue": { + "fields": { + "columnMetadataIndex": { + "type": "int32", + "id": 1 + }, + "value": { + "type": "google.protobuf.Value", + "id": 2 + } + } + }, + "Mod": { + "fields": { + "keys": { + "rule": "repeated", + "type": "ModValue", + "id": 1 + }, + "oldValues": { + "rule": "repeated", + "type": "ModValue", + "id": 2 + }, + "newValues": { + "rule": "repeated", + "type": "ModValue", + "id": 3 + } + } + }, + "ModType": { + "values": { + "MOD_TYPE_UNSPECIFIED": 0, + "INSERT": 10, + "UPDATE": 20, + "DELETE": 30 + } + }, + "ValueCaptureType": { + "values": { + "VALUE_CAPTURE_TYPE_UNSPECIFIED": 0, + "OLD_AND_NEW_VALUES": 10, + "NEW_VALUES": 20, + "NEW_ROW": 30, + "NEW_ROW_AND_OLD_VALUES": 40 + } + } + } + }, + "HeartbeatRecord": { + "fields": { + "timestamp": { + "type": "google.protobuf.Timestamp", + "id": 1 + } + } + }, + "PartitionStartRecord": { + "fields": { + "startTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "recordSequence": { + "type": "string", + "id": 2 + }, + "partitionTokens": { + "rule": "repeated", + "type": "string", + "id": 3 + } + } + }, + "PartitionEndRecord": { + "fields": { + "endTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "recordSequence": { + "type": "string", + "id": 2 + }, + "partitionToken": { + "type": "string", + "id": 3 + } + } + }, + "PartitionEventRecord": { + "fields": { + "commitTimestamp": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "recordSequence": { + "type": "string", + "id": 2 + }, + "partitionToken": { + "type": "string", + "id": 3 + }, + "moveInEvents": { + "rule": "repeated", + "type": "MoveInEvent", + "id": 4 + }, + "moveOutEvents": { + "rule": "repeated", + "type": "MoveOutEvent", + "id": 5 + } + }, + "nested": { + "MoveInEvent": { + "fields": { + "sourcePartitionToken": { + "type": "string", + "id": 1 + } + } + }, + "MoveOutEvent": { + "fields": { + "destinationPartitionToken": { + "type": "string", + "id": 1 + } + } + } + } + } + } + } + } + } + } + }, + "api": { + "options": { + "go_package": "google.golang.org/genproto/googleapis/api;api", + "java_multiple_files": true, + "java_outer_classname": "LaunchStageProto", + "java_package": "com.google.api", + "objc_class_prefix": "GAPI" + }, + "nested": { + "fieldBehavior": { + "rule": "repeated", + "type": "google.api.FieldBehavior", + "id": 1052, + "extend": "google.protobuf.FieldOptions", + "options": { + "packed": false + } + }, + "FieldBehavior": { + "values": { + "FIELD_BEHAVIOR_UNSPECIFIED": 0, + "OPTIONAL": 1, + "REQUIRED": 2, + "OUTPUT_ONLY": 3, + "INPUT_ONLY": 4, + "IMMUTABLE": 5, + "UNORDERED_LIST": 6, + "NON_EMPTY_DEFAULT": 7, + "IDENTIFIER": 8 + } + }, + "resourceReference": { + "type": "google.api.ResourceReference", + "id": 1055, + "extend": "google.protobuf.FieldOptions" + }, + "resourceDefinition": { + "rule": "repeated", + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.FileOptions" + }, + "resource": { + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.MessageOptions" + }, + "ResourceDescriptor": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "pattern": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "nameField": { + "type": "string", + "id": 3 + }, + "history": { + "type": "History", + "id": 4 + }, + "plural": { + "type": "string", + "id": 5 + }, + "singular": { + "type": "string", + "id": 6 + }, + "style": { + "rule": "repeated", + "type": "Style", + "id": 10 + } + }, + "nested": { + "History": { + "values": { + "HISTORY_UNSPECIFIED": 0, + "ORIGINALLY_SINGLE_PATTERN": 1, + "FUTURE_MULTI_PATTERN": 2 + } + }, + "Style": { + "values": { + "STYLE_UNSPECIFIED": 0, + "DECLARATIVE_FRIENDLY": 1 + } + } + } + }, + "ResourceReference": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "childType": { + "type": "string", + "id": 2 + } + } + }, + "http": { + "type": "HttpRule", + "id": 72295728, + "extend": "google.protobuf.MethodOptions" + }, + "Http": { + "fields": { + "rules": { + "rule": "repeated", + "type": "HttpRule", + "id": 1 + }, + "fullyDecodeReservedExpansion": { + "type": "bool", + "id": 2 + } + } + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "body": { + "type": "string", + "id": 7 + }, + "responseBody": { + "type": "string", + "id": 12 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + }, + "CustomHttpPattern": { + "fields": { + "kind": { + "type": "string", + "id": 1 + }, + "path": { + "type": "string", + "id": 2 + } + } + }, + "methodSignature": { + "rule": "repeated", + "type": "string", + "id": 1051, + "extend": "google.protobuf.MethodOptions" + }, + "defaultHost": { + "type": "string", + "id": 1049, + "extend": "google.protobuf.ServiceOptions" + }, + "oauthScopes": { + "type": "string", + "id": 1050, + "extend": "google.protobuf.ServiceOptions" + }, + "apiVersion": { + "type": "string", + "id": 525000001, + "extend": "google.protobuf.ServiceOptions" + }, + "CommonLanguageSettings": { + "fields": { + "referenceDocsUri": { + "type": "string", + "id": 1, + "options": { + "deprecated": true + } + }, + "destinations": { + "rule": "repeated", + "type": "ClientLibraryDestination", + "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 + } + } + }, + "ClientLibrarySettings": { + "fields": { + "version": { + "type": "string", + "id": 1 + }, + "launchStage": { + "type": "LaunchStage", + "id": 2 + }, + "restNumericEnums": { + "type": "bool", + "id": 3 + }, + "javaSettings": { + "type": "JavaSettings", + "id": 21 + }, + "cppSettings": { + "type": "CppSettings", + "id": 22 + }, + "phpSettings": { + "type": "PhpSettings", + "id": 23 + }, + "pythonSettings": { + "type": "PythonSettings", + "id": 24 + }, + "nodeSettings": { + "type": "NodeSettings", + "id": 25 + }, + "dotnetSettings": { + "type": "DotnetSettings", + "id": 26 + }, + "rubySettings": { + "type": "RubySettings", + "id": 27 + }, + "goSettings": { + "type": "GoSettings", + "id": 28 + } + } + }, + "Publishing": { + "fields": { + "methodSettings": { + "rule": "repeated", + "type": "MethodSettings", + "id": 2 + }, + "newIssueUri": { + "type": "string", + "id": 101 + }, + "documentationUri": { + "type": "string", + "id": 102 + }, + "apiShortName": { + "type": "string", + "id": 103 + }, + "githubLabel": { + "type": "string", + "id": 104 + }, + "codeownerGithubTeams": { + "rule": "repeated", + "type": "string", + "id": 105 + }, + "docTagPrefix": { + "type": "string", + "id": 106 + }, + "organization": { + "type": "ClientLibraryOrganization", + "id": 107 + }, + "librarySettings": { + "rule": "repeated", + "type": "ClientLibrarySettings", + "id": 109 + }, + "protoReferenceDocumentationUri": { + "type": "string", + "id": 110 + }, + "restReferenceDocumentationUri": { + "type": "string", + "id": 111 + } + } + }, + "JavaSettings": { + "fields": { + "libraryPackage": { + "type": "string", + "id": 1 + }, + "serviceClassNames": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "common": { + "type": "CommonLanguageSettings", + "id": 3 + } + } + }, + "CppSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PhpSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PythonSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } + } + } + }, + "NodeSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "DotnetSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "renamedResources": { + "keyType": "string", + "type": "string", + "id": 3 + }, + "ignoredResources": { + "rule": "repeated", + "type": "string", + "id": 4 + }, + "forcedNamespaceAliases": { + "rule": "repeated", + "type": "string", + "id": 5 + }, + "handwrittenSignatures": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + }, + "RubySettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "GoSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 + } + } + }, + "MethodSettings": { + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "longRunning": { + "type": "LongRunning", + "id": 2 + }, + "autoPopulatedFields": { + "rule": "repeated", + "type": "string", + "id": 3 + } + }, + "nested": { + "LongRunning": { + "fields": { + "initialPollDelay": { + "type": "google.protobuf.Duration", + "id": 1 + }, + "pollDelayMultiplier": { + "type": "float", + "id": 2 + }, + "maxPollDelay": { + "type": "google.protobuf.Duration", + "id": 3 + }, + "totalPollTimeout": { + "type": "google.protobuf.Duration", + "id": 4 + } + } + } + } + }, + "ClientLibraryOrganization": { + "values": { + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": 0, + "CLOUD": 1, + "ADS": 2, + "PHOTOS": 3, + "STREET_VIEW": 4, + "SHOPPING": 5, + "GEO": 6, + "GENERATIVE_AI": 7 + } + }, + "ClientLibraryDestination": { + "values": { + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": 0, + "GITHUB": 10, + "PACKAGE_MANAGER": 20 + } + }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, + "LaunchStage": { + "values": { + "LAUNCH_STAGE_UNSPECIFIED": 0, + "UNIMPLEMENTED": 6, + "PRELAUNCH": 7, + "EARLY_ACCESS": 1, + "ALPHA": 2, + "BETA": 3, + "GA": 4, + "DEPRECATED": 5 + } + } + } + }, + "longrunning": { + "options": { + "cc_enable_arenas": true, + "csharp_namespace": "Google.LongRunning", + "go_package": "cloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb", + "java_multiple_files": true, + "java_outer_classname": "OperationsProto", + "java_package": "com.google.longrunning", + "objc_class_prefix": "GLRUN", + "php_namespace": "Google\\LongRunning" + }, + "nested": { + "operationInfo": { + "type": "google.longrunning.OperationInfo", + "id": 1049, + "extend": "google.protobuf.MethodOptions" + }, + "Operations": { + "options": { + "(google.api.default_host)": "longrunning.googleapis.com" + }, + "methods": { + "ListOperations": { + "requestType": "ListOperationsRequest", + "responseType": "ListOperationsResponse", + "options": { + "(google.api.http).get": "/v1/{name=operations}", + "(google.api.method_signature)": "name,filter" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=operations}" + } + }, + { + "(google.api.method_signature)": "name,filter" + } + ] + }, + "GetOperation": { + "requestType": "GetOperationRequest", + "responseType": "Operation", + "options": { + "(google.api.http).get": "/v1/{name=operations/**}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=operations/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "DeleteOperation": { + "requestType": "DeleteOperationRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=operations/**}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=operations/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "CancelOperation": { + "requestType": "CancelOperationRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).post": "/v1/{name=operations/**}:cancel", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=operations/**}:cancel", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "WaitOperation": { + "requestType": "WaitOperationRequest", + "responseType": "Operation" + } + } + }, + "Operation": { + "oneofs": { + "result": { + "oneof": [ + "error", + "response" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "metadata": { + "type": "google.protobuf.Any", + "id": 2 + }, + "done": { + "type": "bool", + "id": 3 + }, + "error": { + "type": "google.rpc.Status", + "id": 4 + }, + "response": { + "type": "google.protobuf.Any", + "id": 5 + } + } + }, + "GetOperationRequest": { + "fields": { + "name": { + "type": "string", + "id": 1 + } + } + }, + "ListOperationsRequest": { + "fields": { + "name": { + "type": "string", + "id": 4 + }, + "filter": { + "type": "string", + "id": 1 + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + } + } + }, + "ListOperationsResponse": { + "fields": { + "operations": { + "rule": "repeated", + "type": "Operation", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "CancelOperationRequest": { + "fields": { + "name": { + "type": "string", + "id": 1 + } + } + }, + "DeleteOperationRequest": { + "fields": { + "name": { + "type": "string", + "id": 1 + } + } + }, + "WaitOperationRequest": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "timeout": { + "type": "google.protobuf.Duration", + "id": 2 + } + } + }, + "OperationInfo": { + "fields": { + "responseType": { + "type": "string", + "id": 1 + }, + "metadataType": { + "type": "string", + "id": 2 + } + } + } + } + }, + "iam": { + "nested": { + "v1": { + "options": { + "csharp_namespace": "Google.Cloud.Iam.V1", + "go_package": "cloud.google.com/go/iam/apiv1/iampb;iampb", + "java_multiple_files": true, + "java_outer_classname": "PolicyProto", + "java_package": "com.google.iam.v1", + "php_namespace": "Google\\Cloud\\Iam\\V1", + "cc_enable_arenas": true + }, + "nested": { + "IAMPolicy": { + "options": { + "(google.api.default_host)": "iam-meta-api.googleapis.com" + }, + "methods": { + "SetIamPolicy": { + "requestType": "SetIamPolicyRequest", + "responseType": "Policy", + "options": { + "(google.api.http).post": "/v1/{resource=**}:setIamPolicy", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=**}:setIamPolicy", + "body": "*" + } + } + ] + }, + "GetIamPolicy": { + "requestType": "GetIamPolicyRequest", + "responseType": "Policy", + "options": { + "(google.api.http).post": "/v1/{resource=**}:getIamPolicy", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=**}:getIamPolicy", + "body": "*" + } + } + ] + }, + "TestIamPermissions": { + "requestType": "TestIamPermissionsRequest", + "responseType": "TestIamPermissionsResponse", + "options": { + "(google.api.http).post": "/v1/{resource=**}:testIamPermissions", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{resource=**}:testIamPermissions", + "body": "*" + } + } + ] + } + } + }, + "SetIamPolicyRequest": { + "fields": { + "resource": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "*" + } + }, + "policy": { + "type": "Policy", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 3 + } + } + }, + "GetIamPolicyRequest": { + "fields": { + "resource": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "*" + } + }, + "options": { + "type": "GetPolicyOptions", + "id": 2 + } + } + }, + "TestIamPermissionsRequest": { + "fields": { + "resource": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "*" + } + }, + "permissions": { + "rule": "repeated", + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsResponse": { + "fields": { + "permissions": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } + }, + "GetPolicyOptions": { + "fields": { + "requestedPolicyVersion": { + "type": "int32", + "id": 1 + } + } + }, + "Policy": { + "fields": { + "version": { + "type": "int32", + "id": 1 + }, + "bindings": { + "rule": "repeated", + "type": "Binding", + "id": 4 + }, + "auditConfigs": { + "rule": "repeated", + "type": "AuditConfig", + "id": 6 + }, + "etag": { + "type": "bytes", + "id": 3 + } + } + }, + "Binding": { + "fields": { + "role": { + "type": "string", + "id": 1 + }, + "members": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "condition": { + "type": "google.type.Expr", + "id": 3 + } + } + }, + "AuditConfig": { + "fields": { + "service": { + "type": "string", + "id": 1 + }, + "auditLogConfigs": { + "rule": "repeated", + "type": "AuditLogConfig", + "id": 3 + } + } + }, + "AuditLogConfig": { + "fields": { + "logType": { + "type": "LogType", + "id": 1 + }, + "exemptedMembers": { + "rule": "repeated", + "type": "string", + "id": 2 + } + }, + "nested": { + "LogType": { + "values": { + "LOG_TYPE_UNSPECIFIED": 0, + "ADMIN_READ": 1, + "DATA_WRITE": 2, + "DATA_READ": 3 + } + } + } + }, + "PolicyDelta": { + "fields": { + "bindingDeltas": { + "rule": "repeated", + "type": "BindingDelta", + "id": 1 + }, + "auditConfigDeltas": { + "rule": "repeated", + "type": "AuditConfigDelta", + "id": 2 + } + } + }, + "BindingDelta": { + "fields": { + "action": { + "type": "Action", + "id": 1 + }, + "role": { + "type": "string", + "id": 2 + }, + "member": { + "type": "string", + "id": 3 + }, + "condition": { + "type": "google.type.Expr", + "id": 4 + } + }, + "nested": { + "Action": { + "values": { + "ACTION_UNSPECIFIED": 0, + "ADD": 1, + "REMOVE": 2 + } + } + } + }, + "AuditConfigDelta": { + "fields": { + "action": { + "type": "Action", + "id": 1 + }, + "service": { + "type": "string", + "id": 2 + }, + "exemptedMember": { + "type": "string", + "id": 3 + }, + "logType": { + "type": "string", + "id": 4 + } + }, + "nested": { + "Action": { + "values": { + "ACTION_UNSPECIFIED": 0, + "ADD": 1, + "REMOVE": 2 + } + } + } + } + } + } + } + }, + "type": { + "options": { + "go_package": "google.golang.org/genproto/googleapis/type/expr;expr", + "java_multiple_files": true, + "java_outer_classname": "ExprProto", + "java_package": "com.google.type", + "objc_class_prefix": "GTP" + }, + "nested": { + "Expr": { + "fields": { + "expression": { + "type": "string", + "id": 1 + }, + "title": { + "type": "string", + "id": 2 + }, + "description": { + "type": "string", + "id": 3 + }, + "location": { + "type": "string", + "id": 4 + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/handwritten/spanner/scripts/cleanup.js b/handwritten/spanner/scripts/cleanup.js new file mode 100644 index 00000000000..88f306a0f81 --- /dev/null +++ b/handwritten/spanner/scripts/cleanup.js @@ -0,0 +1,62 @@ +/*! + * Copyright 2018 Google LLC. All Rights Reserved. + * + * 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. + */ + +const {Spanner} = require('../'); +const pLimit = require('p-limit'); +const {describe, it} = require('mocha'); +const spanner = new Spanner({projectId: process.env.GCLOUD_PROJECT}); + +// Delete instances that are 1 hour old. +const STALE_THRESHOLD = 60 * 60; + +const CURRENT_DATE = new Date(); + +async function deleteStaleInstances(labelFilter) { + const [instances] = await spanner.getInstances({}); + + const filtered = instances.filter(instance => { + return labelFilter(instance.metadata.labels); + }); + + const limit = pLimit(5); + await Promise.all( + filtered.map(instance => + limit(() => + setTimeout(() => { + instance.delete(); + }, 500), + ), + ), + ); +} + +describe('Clean up', () => { + it('should clean up stale instances', async () => { + // Remove instances with label { created: Date } that's older than STALE_THRESHOLD + const labelFilter = labels => { + if (labels.created) { + const creationDate = new Date(labels.created * 1000); + return ( + CURRENT_DATE.valueOf() - creationDate.valueOf() > + STALE_THRESHOLD * 1000 + ); + } + return false; + }; + + await deleteStaleInstances(labelFilter); + }); +}); diff --git a/handwritten/spanner/src/backup.ts b/handwritten/spanner/src/backup.ts new file mode 100644 index 00000000000..ece00c33eb0 --- /dev/null +++ b/handwritten/spanner/src/backup.ts @@ -0,0 +1,642 @@ +/** + * Copyright 2020 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 {promisifyAll, callbackifyAll} from '@google-cloud/promisify'; +import {Instance} from './instance'; +import { + IOperation, + LongRunningCallback, + RequestCallback, + ResourceCallback, + NormalCallback, + CLOUD_RESOURCE_HEADER, +} from './common'; +import {EnumKey, Spanner, RequestConfig, TranslateEnumKeys} from '.'; +import { + grpc, + CallOptions, + Metadata, + Operation as GaxOperation, +} from 'google-gax'; +import {DateStruct, PreciseDate} from '@google-cloud/precise-date'; +import {google as databaseAdmin} from '../protos/protos'; +import {common as p} from 'protobufjs'; + +export type CreateBackupCallback = LongRunningCallback; +export type CopyBackupCallback = LongRunningCallback; + +export interface CreateBackupGaxOperation extends GaxOperation { + // Overridden with more specific type for CreateBackup operation + metadata: Metadata & + databaseAdmin.spanner.admin.database.v1.ICreateBackupMetadata; +} + +export type CreateBackupResponse = [ + Backup, + CreateBackupGaxOperation, + IOperation, +]; + +export interface CreateBackupOptions { + databasePath: string; + expireTime: string | number | p.ITimestamp | PreciseDate; + versionTime?: string | number | p.ITimestamp | PreciseDate; + encryptionConfig?: databaseAdmin.spanner.admin.database.v1.ICreateBackupEncryptionConfig; + gaxOptions?: CallOptions; +} + +export interface CopyBackupGaxOperation extends GaxOperation { + // Overridden with more specific type for CopyBackup operation + metadata: Metadata & + databaseAdmin.spanner.admin.database.v1.ICopyBackupMetadata; +} + +export type CopyBackupResponse = [Backup, CopyBackupGaxOperation, IOperation]; + +export interface CopyBackupOptions + extends databaseAdmin.spanner.admin.database.v1.ICopyBackupRequest { + gaxOptions?: CallOptions; +} + +/** + * IBackup structure with backup state enum translated to string form. + */ +type IBackupTranslatedEnum = TranslateEnumKeys< + databaseAdmin.spanner.admin.database.v1.IBackup, + 'state', + typeof databaseAdmin.spanner.admin.database.v1.Backup.State +>; + +export type GetMetadataResponse = [IBackupTranslatedEnum]; +type GetMetadataCallback = RequestCallback; + +type UpdateExpireTimeCallback = + RequestCallback; + +type DeleteCallback = RequestCallback; + +interface BackupRequest { + ( + config: RequestConfig, + callback: ResourceCallback, + ): void; + (config: RequestConfig, callback: RequestCallback): void; +} +export type GetStateCallback = NormalCallback< + EnumKey +>; +export type GetExpireTimeCallback = NormalCallback; +export type ExistsCallback = NormalCallback; +/** + * The {@link Backup} class represents a Cloud Spanner backup. + * + * Create a `Backup` object to interact with or create a Cloud Spanner backup or copy a backup. + * + * @class + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.backup('my-backup'); + * ``` + * + * ``` + * * @example + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const sourceBackup = instance.backup('my-source-backup'); + * const copyBackup = instance.copyBackup('my-copy-backup', 'my-source-backup'); + * ``` + */ +class Backup { + id: string; + formattedName_: string; + instanceFormattedName_: string; + resourceHeader_: {[k: string]: string}; + request: BackupRequest; + metadata?: databaseAdmin.spanner.admin.database.v1.IBackup; + sourceName: string | undefined; + constructor(instance: Instance, name: string, sourceName?: string) { + this.request = instance.request; + this.instanceFormattedName_ = instance.formattedName_; + this.formattedName_ = Backup.formatName_(instance.formattedName_, name); + this.id = this.formattedName_.split('/').pop() || ''; + this.sourceName = sourceName; + this.resourceHeader_ = { + [CLOUD_RESOURCE_HEADER]: this.instanceFormattedName_, + }; + } + + /** + * @typedef {object} CreateBackupOptions + * @property {string} databasePath The database path. + * @property {string|number|google.protobuf.Timestamp|external:PreciseDate} + * expireTime The expire time of the backup. + * @property {string|number|google.protobuf.Timestamp|external:PreciseDate} + * versionTime Take a backup of the state of the database at this time. + * @property {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig} + * encryptionConfig An encryption configuration describing the + * encryption type and key resources in Cloud KMS to be used to encrypt + * the backup. + * @property {object} [gaxOptions] The request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} CreateBackupResponse + * @property {Backup} 0 The new {@link Backup}. + * @property {google.longrunning.Operation} 1 An {@link Operation} object that can be used to check + * the status of the request. + * @property {object} 2 The full API response. + */ + /** + * @callback CreateBackupCallback + * @param {?Error} err Request error, if any. + * @param {Backup} backup The new {@link Backup}. + * @param {google.longrunning.Operation} operation An {@link Operation} object that can be used to + * check the status of the request. + * @param {object} apiResponse The full API response. + */ + /** + * Create a backup. + * + * @method Backup#create + * @param {CreateBackupOptions} options Parameters for creating a backup. + * @param {CallOptions} [options.gaxOptions] The request configuration + * options, See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {CreateBackupCallback} [callback] Callback function. + * @returns {Promise} When resolved, the backup + * operation will have started, but will not have necessarily completed. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const oneDay = 1000 * 60 * 60 * 24; + * const expireTime = Date.now() + oneDay; + * const versionTime = Date.now() - oneDay; + * const backup = instance.backup('my-backup'); + * const [, backupOperation] = await backup.create({ + * databasePath: 'projects/my-project/instances/my-instance/databases/my-database', + * expireTime: expireTime, + * versionTime: versionTime, + * encryptionConfig: { + * encryptionType: 'CUSTOMER_MANAGED_ENCRYPTION', + * kmsKeyName: 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key', + * }, + * }); + * // Await completion of the backup operation. + * await backupOperation.promise(); + * ``` + */ + create( + options: CreateBackupOptions | CopyBackupOptions, + ): Promise | Promise; + create( + options: CreateBackupOptions | CopyBackupOptions, + callback: CreateBackupCallback | CopyBackupCallback, + ): void; + create( + options: CreateBackupOptions | CopyBackupOptions, + callback?: CreateBackupCallback | CopyBackupCallback, + ): Promise | Promise | void { + const gaxOpts = options.gaxOptions; + if ('databasePath' in options) { + const reqOpts: databaseAdmin.spanner.admin.database.v1.ICreateBackupRequest = + { + parent: this.instanceFormattedName_, + backupId: this.id, + backup: { + database: options.databasePath, + expireTime: Spanner.timestamp(options.expireTime).toStruct(), + name: this.formattedName_, + }, + }; + if ('versionTime' in options) { + reqOpts.backup!.versionTime = Spanner.timestamp( + options.versionTime, + ).toStruct(); + } + if ( + 'encryptionConfig' in options && + (options as CreateBackupOptions).encryptionConfig + ) { + reqOpts.encryptionConfig = ( + options as CreateBackupOptions + ).encryptionConfig; + } + this.request( + { + client: 'DatabaseAdminClient', + method: 'createBackup', + reqOpts, + gaxOpts, + headers: this.resourceHeader_, + }, + (err, operation, resp) => { + if (err) { + callback!(err, null, null, resp); + return; + } + callback!(null, this, operation, resp); + }, + ); + } else if (this.sourceName) { + delete options.gaxOptions; + options.backupId = this.id; + options.parent = this.instanceFormattedName_; + options.sourceBackup = this.sourceName; + this.request( + { + client: 'DatabaseAdminClient', + method: 'copyBackup', + reqOpts: + options as databaseAdmin.spanner.admin.database.v1.ICopyBackupRequest, + gaxOpts, + headers: this.resourceHeader_, + }, + (err, operation, resp) => { + if (err) { + callback!(err, null, null, resp); + return; + } + callback!(null, this, operation, resp); + }, + ); + } + } + + /** + * @typedef {array} GetMetadataResponse + * @property {object} 0 The {@link Backup} metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The {@link Backup} metadata. + * @param {object} apiResponse The full API response. + */ + /** + * Retrieves backup's metadata. + * + * @see {@link #getState} + * @see {@link #getExpireTime} + * + * @method Backup#getMetadata + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.backup('my-backup'); + * const [backupInfo] = await backup.getMetadata(); + * console.log(`${backupInfo.name}: size=${backupInfo.sizeBytes}`); + * ``` + */ + getMetadata(gaxOptions?: CallOptions): Promise; + getMetadata(callback: GetMetadataCallback): void; + getMetadata(gaxOptions: CallOptions, callback: GetMetadataCallback): void; + getMetadata( + gaxOptionsOrCallback?: CallOptions | GetMetadataCallback, + cb?: GetMetadataCallback, + ): void | Promise { + const callback = + typeof gaxOptionsOrCallback === 'function' + ? (gaxOptionsOrCallback as GetMetadataCallback) + : cb; + const gaxOpts = + typeof gaxOptionsOrCallback === 'object' + ? (gaxOptionsOrCallback as CallOptions) + : {}; + const reqOpts: databaseAdmin.spanner.admin.database.v1.IGetBackupRequest = { + name: this.formattedName_, + }; + this.request( + { + client: 'DatabaseAdminClient', + method: 'getBackup', + reqOpts, + gaxOpts, + headers: this.resourceHeader_, + }, + (err, response) => { + if (response) { + this.metadata = response; + } + callback!(err, response); + }, + ); + } + + /** + * Retrieves the state of the backup. + * + * The backup state indicates if the backup has completed. + * + * @see {@link #getMetadata} + * + * @method Backup#getState + * @param {GetStateCallback} [callback] Callback function. + * @returns {Promise | undefined>} + * When resolved, contains the current state of the backup if it exists. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.backup('my-backup'); + * const state = await backup.getState(); + * const backupCompleted = (state === 'READY'); + * ``` + */ + getState(): Promise< + | EnumKey + | undefined + | null + >; + getState(callback: GetStateCallback): void; + async getState(): Promise< + | EnumKey + | undefined + | null + > { + const [backupInfo] = await this.getMetadata(); + return backupInfo.state; + } + + /** + * Retrieves the expiry time of the backup. + * + * @see {@link #updateExpireTime} + * @see {@link #getMetadata} + * + * @method Backup#getExpireTime + * @returns {Promise} When resolved, contains the + * current expire time of the backup if it exists. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.backup('my-backup'); + * const expireTime = await backup.getExpireTime(); + * console.log(`Backup expires on ${expireTime.toISOString()}`); + * ``` + */ + getExpireTime(): Promise; + getExpireTime(callback: GetExpireTimeCallback): void; + async getExpireTime(): Promise { + const [backupInfo] = await this.getMetadata(); + return new PreciseDate(backupInfo.expireTime as DateStruct); + } + + /** + * Checks whether the backup exists. + * + * @see {@link #getMetadata} + * + * @method Backup#exists + * @returns {Promise} When resolved, contains true if the backup + * exists and false if it does not exist. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.backup('my-backup'); + * const alreadyExists = await backup.exists(); + * console.log(`Does backup exist? ${alreadyExists}`); + * ``` + */ + exists(): Promise; + exists(callback: ExistsCallback): void; + async exists(): Promise { + try { + // Attempt to read metadata to determine whether backup exists + await this.getMetadata(); + // Found therefore it exists + return true; + } catch (err) { + if ((err as grpc.ServerErrorResponse).code === grpc.status.NOT_FOUND) { + return false; + } + // Some other error occurred, rethrow + throw err; + } + } + + /** + * @callback UpdateExpireTimeCallback + * @param {?Error} err Request error, if any. + * @param {google.spanner.admin.database.v1.IBackup} backup The updated + * backup. + */ + /** + * Sets the expiry time of a backup. + * + * @see {@link #getExpireTime} + * + * @method Backup#updateExpireTime + * @param {string|number|google.protobuf.Timestamp|external:PreciseDate} + * expireTime The expiry time to update with. + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {UpdateExpireTimeCallback} [callback] Callback function. + * @returns {Promise} When resolved, + * the backup's expire time will have been updated. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.backup('my-backup'); + * const oneDay = 1000 * 60 * 60 * 24; + * const newExpireTime = Spanner.timestamp(Date.now() + oneDay); + * await backup.updateExpireTime(newExpireTime); + * ``` + */ + updateExpireTime( + expireTime: string | number | p.ITimestamp | PreciseDate, + ): Promise; + updateExpireTime( + expireTime: string | number | p.ITimestamp | PreciseDate, + gaxOptions?: CallOptions, + ): Promise; + updateExpireTime( + expireTime: string | number | p.ITimestamp | PreciseDate, + callback: UpdateExpireTimeCallback, + ): void; + updateExpireTime( + expireTime: string | number | p.ITimestamp | PreciseDate, + gaxOptions: CallOptions, + callback: UpdateExpireTimeCallback, + ): void; + updateExpireTime( + expireTime: string | number | p.ITimestamp | PreciseDate, + gaxOptionsOrCallback?: CallOptions | UpdateExpireTimeCallback, + cb?: UpdateExpireTimeCallback, + ): void | Promise { + const callback = + typeof gaxOptionsOrCallback === 'function' + ? (gaxOptionsOrCallback as UpdateExpireTimeCallback) + : cb; + const gaxOpts = + typeof gaxOptionsOrCallback === 'object' + ? (gaxOptionsOrCallback as CallOptions) + : {}; + const reqOpts: databaseAdmin.spanner.admin.database.v1.IUpdateBackupRequest = + { + backup: { + name: this.formattedName_, + expireTime: Spanner.timestamp(expireTime).toStruct(), + }, + updateMask: { + paths: ['expire_time'], + }, + }; + this.request( + { + client: 'DatabaseAdminClient', + method: 'updateBackup', + reqOpts, + gaxOpts, + headers: this.resourceHeader_, + }, + (err, response) => { + callback!(err, response); + }, + ); + } + + /** + * Deletes a backup. + * + * @method Backup#delete + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DeleteBackupCallback} [callback] Callback function. + * @returns {Promise} When resolved, the backup will have been deleted. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.backup('my-backup'); + * await backup.delete(); + * ``` + */ + delete(gaxOptions?: CallOptions): Promise; + delete(callback: DeleteCallback): void; + delete(gaxOptions: CallOptions, callback: DeleteCallback): void; + delete( + gaxOptionsOrCallback?: CallOptions | DeleteCallback, + cb?: DeleteCallback, + ): void | Promise { + const callback = + typeof gaxOptionsOrCallback === 'function' + ? (gaxOptionsOrCallback as DeleteCallback) + : cb; + const gaxOpts = + typeof gaxOptionsOrCallback === 'object' + ? (gaxOptionsOrCallback as CallOptions) + : {}; + const reqOpts: databaseAdmin.spanner.admin.database.v1.IDeleteBackupRequest = + { + name: this.formattedName_, + }; + this.request( + { + client: 'DatabaseAdminClient', + method: 'deleteBackup', + reqOpts, + gaxOpts, + headers: this.resourceHeader_, + }, + err => { + callback!(err); + }, + ); + } + + /** + * Format the backup name to include the instance name. + * + * @private + * + * @param {string} instanceName The formatted instance name. + * @param {string} name The table name. + * @returns {string} + * + * @example + * ``` + * Backup.formatName_( + * 'projects/grape-spaceship-123/instances/my-instance', + * 'my-backup' + * ); + * // 'projects/grape-spaceship-123/instances/my-instance/backups/my-backup' + * ``` + */ + static formatName_(instanceName: string, name: string) { + if (name.indexOf('/') > -1) { + return name; + } + const backupName = name.split('/').pop(); + return instanceName + '/backups/' + backupName; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Backup, { + exclude: ['getState', 'getExpireTime', 'exists'], +}); + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +callbackifyAll(Backup, { + exclude: ['create', 'getMetadata', 'updateExpireTime', 'delete'], +}); + +/** + * Reference to the {@link Backup} class. + * @name module:@google-cloud/spanner.Backup + * @see Backup + */ +export {Backup}; diff --git a/handwritten/spanner/src/batch-transaction.ts b/handwritten/spanner/src/batch-transaction.ts new file mode 100644 index 00000000000..4f88d9a6594 --- /dev/null +++ b/handwritten/spanner/src/batch-transaction.ts @@ -0,0 +1,501 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * 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 {PreciseDate} from '@google-cloud/precise-date'; +import {promisifyAll} from '@google-cloud/promisify'; +import * as extend from 'extend'; +import { + ExecuteSqlRequest, + ReadCallback, + ReadRequest, + ReadResponse, + RunCallback, + RunResponse, + Snapshot, +} from './transaction'; +import {google} from '../protos/protos'; +import {Session, Database} from '.'; +import { + CLOUD_RESOURCE_HEADER, + ResourceCallback, + addLeaderAwareRoutingHeader, +} from '../src/common'; +import {startTrace, setSpanError, traceConfig} from './instrument'; +import {injectRequestIDIntoHeaders} from './request_id_header'; +import {isString} from './helper'; + +export interface TransactionIdentifier { + session: string | Session; + transaction?: string; + timestamp?: google.protobuf.ITimestamp; +} + +export type CreateReadPartitionsResponse = [ + ReadRequest[], + google.spanner.v1.IPartitionResponse, +]; + +export type CreateReadPartitionsCallback = ResourceCallback< + ReadRequest[], + google.spanner.v1.IPartitionResponse +>; + +export type CreateQueryPartitionsResponse = [ + ExecuteSqlRequest[], + google.spanner.v1.IPartitionResponse, +]; + +export type CreateQueryPartitionsCallback = ResourceCallback< + ExecuteSqlRequest[], + google.spanner.v1.IPartitionResponse +>; + +/** + * Use a BatchTransaction object to create partitions and read/query against + * your Cloud Spanner database. + * + * @class + * @extends Snapshot + * + * @param {TimestampBounds} [options] [Timestamp Bounds](https://cloud.google.com/spanner/docs/timestamp-bounds). + */ +class BatchTransaction extends Snapshot { + /** + * Closes all open resources. + * + * When the transaction is no longer needed, you should call this method to + * free up resources allocated by the Batch client. + * + * Calling this method would render the transaction unusable everywhere. In + * particular if this transaction object was being used across multiple + * machines, calling this method on any of the machine would make the + * transaction unusable on all the machines. This should only be called when + * the transaction is no longer needed anywhere + * + * @param {BasicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.createBatchTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * transaction.close(function(err, apiResponse) {}); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.createBatchTransaction().then(function(data) { + * const transaction = data[0]; + * return transaction.close(); + * }); + * ``` + */ + close(callback?) { + this.end(); + if (callback) { + callback(); + } + } + /** + * @see [`ExecuteSqlRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest) + * @typedef {object} QueryPartition + * @property {string} partitionToken A token representing the partition, used to identify and execute the partition at a later time. + */ + /** + * @typedef {array} CreateQueryPartitionsResponse + * @property {ExecuteSqlRequest[]} 0 Array of ExecuteSqlRequest partitions. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateQueryPartitionsCallback + * @param {?Error} err Request error, if any. + * @param {ExecuteSqlRequest[]} partitions Array of ExecuteSqlRequest partitions. + * @param {object} apiResponse The full API response. + */ + /** + * Creates a set of query partitions that can be used to execute a query + * operation in parallel. Partitions become invalid when the transaction used + * to create them is closed. + * + * @param {string|ExecuteSqlRequest} query - A SQL query string or an {@link ExecuteSqlRequest} object. + * If a string is provided, it will be wrapped into an `ExecuteSqlRequest`. + * @param {object} [query.gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {object} [query.params] A map of parameter name to values. + * @param {object} [query.partitionOptions] A map of partition options. + * @param {object} [query.types] A map of parameter types. + * @param {CreateQueryPartitionsCallback} [callback] - Optional Callback function. If not provided, a promise is returned. + * @returns {Promise|void} A promise resolving to an array of + * `ExecuteSqlRequest' partitions and `IPartitionResponse` , or void if a callback is provided. + * + * @example include:samples/batch.js + * region_tag:spanner_batch_client + */ + createQueryPartitions( + query: string | ExecuteSqlRequest, + ): Promise; + createQueryPartitions( + query: string | ExecuteSqlRequest, + callback: CreateQueryPartitionsCallback, + ): void; + createQueryPartitions( + query: string | ExecuteSqlRequest, + cb?: CreateQueryPartitionsCallback, + ): void | Promise { + const request: ExecuteSqlRequest = + typeof query === 'string' ? {sql: query} : query; + + const reqOpts = Object.assign({}, request, Snapshot.encodeParams(request)); + + delete (reqOpts as any).gaxOptions; + delete (reqOpts as any).types; + + const traceConfig: traceConfig = { + sql: request.sql, + opts: this._observabilityOptions, + dbName: this.getDBName(), + }; + return startTrace( + 'BatchTransaction.createQueryPartitions', + traceConfig, + span => { + const headers: {[k: string]: string} = {}; + if (this._getSpanner().routeToLeaderEnabled) { + addLeaderAwareRoutingHeader(headers); + } + + this.createPartitions_( + { + client: 'SpannerClient', + method: 'partitionQuery', + reqOpts, + gaxOpts: request.gaxOptions, + headers: injectRequestIDIntoHeaders(headers, this.session), + }, + (err, partitions, resp) => { + if (err) { + setSpanError(span, err); + } + + span.end(); + cb!(err, partitions, resp); + }, + ); + }, + ); + } + + protected getDBName(): string { + return (this.session.parent as Database).formattedName_; + } + + /** + * Generic create partition method. Handles common parameters used in both + * {@link BatchTransaction#createQueryPartitions} and {@link + * BatchTransaction#createReadPartitions} + * + * @private + * + * @param {object} config The request config. + * @param {function} callback Callback function. + */ + createPartitions_(config, callback) { + const traceConfig: traceConfig = { + opts: this._observabilityOptions, + dbName: this.getDBName(), + }; + + return startTrace( + 'BatchTransaction.createPartitions_', + traceConfig, + span => { + const query = extend({}, config.reqOpts, { + session: this.session.formattedName_, + transaction: {id: this.id}, + }); + config.reqOpts = extend({}, query); + const headers = { + [CLOUD_RESOURCE_HEADER]: (this.session.parent as Database) + .formattedName_, + }; + config.headers = injectRequestIDIntoHeaders(headers, this.session); + delete query.partitionOptions; + this.session.request(config, (err, resp) => { + if (err) { + setSpanError(span, err); + span.end(); + callback(err, null, resp); + return; + } + + const partitions = resp.partitions.map(partition => { + return extend({}, query, partition); + }); + + if (resp.transaction) { + const {id, readTimestamp} = resp.transaction; + + this.id = id; + + if (readTimestamp) { + this.readTimestampProto = readTimestamp; + this.readTimestamp = new PreciseDate(readTimestamp); + } + } + + span.end(); + callback(null, partitions, resp); + }); + }, + ); + } + /** + * @typedef {object} ReadPartition + * @mixes ReadRequestOptions + * @property {string} partitionToken partitionToken A token representing the partition, used to identify and execute the partition at a later time. + * @property {object} [gaxOptions] optional request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} CreateReadPartitionsResponse + * @property {ReadPartition[]} 0 Array of read partitions. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateReadPartitionsCallback + * @param {?Error} err Request error, if any. + * @param {ReadPartition[]} partitions Array of read partitions. + * @param {object} apiResponse The full API response. + */ + /** + * Creates a set of read partitions that can be used to execute a read + * operation in parallel. Partitions become invalid when the transaction used + * to create them is closed. + * + * @param {ReadRequest} options Configuration object, describing what to + * read from. + * @param {CreateReadPartitionsCallback} [callback] Callback function. + * @returns {Promise|void} A promise that resolves + * to an array containing the read partitions and the full API response, or `void` if a callback is provided. + */ + createReadPartitions( + options: ReadRequest, + ): Promise; + createReadPartitions( + options: ReadRequest, + callback: CreateReadPartitionsCallback, + ): void; + createReadPartitions( + options: ReadRequest, + cb?: CreateReadPartitionsCallback, + ): void | Promise { + const traceConfig: traceConfig = { + opts: this._observabilityOptions, + dbName: this.getDBName(), + }; + + return startTrace( + 'BatchTransaction.createReadPartitions', + traceConfig, + span => { + const reqOpts = Object.assign({}, options, { + keySet: Snapshot.encodeKeySet(options), + }); + + delete reqOpts.gaxOptions; + delete reqOpts.keys; + delete reqOpts.ranges; + + const headers: {[k: string]: string} = {}; + if (this._getSpanner().routeToLeaderEnabled) { + addLeaderAwareRoutingHeader(headers); + } + + this.createPartitions_( + { + client: 'SpannerClient', + method: 'partitionRead', + reqOpts, + gaxOpts: options.gaxOptions, + headers: injectRequestIDIntoHeaders(headers, this.session), + }, + (err, partitions, resp) => { + if (err) { + setSpanError(span, err); + } + + span.end(); + cb!(err, partitions, resp); + }, + ); + }, + ); + } + /** + * Executes partition using either a read or a SQL query, depending on the type of partition provided. + * + * @param {ReadRequest|ExecuteSqlRequest} partition The partition object to execute. + * This can either be a `ReadPartition` or a `QueryPartition`. + * + * @param {ReadCallback|RunCallback} [callback] Optional Callback function. If not provided, + * a promise will be returned. + * + * If the partition is a read partition, it will execute a read using {@link Transaction#read} + * @see {@link Transaction#read} when using {@link ReadRequest}. + * + * If the partition is query partition, it will execute a SQL query using {@link Transaction#run} + * @see {@link Transaction#run} when using {@link ExecuteSqlRequest}. + * + * @returns {Promise|void} Returns a promise when no callback is provided, + * or void when a callback is used. + * + * @example include:samples/batch.js + * region_tag:spanner_batch_execute_partitions + */ + execute( + partition: ReadRequest | ExecuteSqlRequest, + ): Promise; + execute( + partition: ReadRequest | ExecuteSqlRequest, + callback: ReadCallback | RunCallback, + ): void; + execute( + partition: ReadRequest | ExecuteSqlRequest, + cb?: ReadCallback | RunCallback, + ): void | Promise { + const isRead = typeof (partition as ReadRequest).table === 'string'; + + if (isRead) { + this.read( + (partition as ReadRequest).table!, + partition as ReadRequest, + cb as ReadCallback, + ); + return; + } + + this.run(partition as ExecuteSqlRequest, cb as RunCallback); + } + /** + * Executes partition in streaming mode. + * + * @see {@link Transaction#createReadStream} when using {@link ReadPartition}. + * @see {@link Transaction#runStream} when using {@link QueryPartition}. + * + * @param {ReadPartition|QueryPartition} partition The partition object. + * @returns {ReadableStream} A readable stream that emits rows. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.createBatchTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * transaction.createReadPartitions(options, function(err, partitions) { + * const partition = partitions[0]; + * + * transaction + * .executeStream(partition) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row = [ + * // { + * // name: 'SingerId', + * // value: '1' + * // }, + * // { + * // name: 'Name', + * // value: 'Eddie Wilson' + * // } + * // ] + * }) + * .on('end', function() { + * // All results retrieved + * }); + * }); + * }); + * ``` + */ + executeStream(partition) { + // TODO: Instrument the streams with Otel. + if (isString(partition.table)) { + return this.createReadStream(partition.table, partition); + } + return this.runStream(partition); + } + /** + * @typedef {object} TransactionIdentifier + * @property {string|Session} session The full session name. + * @property {string} transaction The transaction ID. + * @property {string|Date} readTimestamp The transaction read timestamp. + */ + /** + * Creates a transaction identifier used to reference the transaction in + * workers. + * + * @returns {TransactionIdentifier} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.createBatchTransaction(function(err, transaction) { + * const identifier = transaction.identifier(); + * }); + * ``` + */ + identifier(): TransactionIdentifier { + return { + transaction: (this.id! as Buffer).toString('base64'), + session: this.session.id, + timestamp: this.readTimestampProto, + }; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(BatchTransaction, { + exclude: ['identifier'], +}); + +export {BatchTransaction}; diff --git a/handwritten/spanner/src/codec.ts b/handwritten/spanner/src/codec.ts new file mode 100644 index 00000000000..0d4aaecc6d0 --- /dev/null +++ b/handwritten/spanner/src/codec.ts @@ -0,0 +1,1348 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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 {GrpcService} from './common-grpc/service'; +import {PreciseDate} from '@google-cloud/precise-date'; +import { + isArray, + isBoolean, + isDate, + isDecimal, + isInfinite, + isInteger, + isNull, + isNumber, + isObject, + isString, + isUndefined, + toArray, +} from './helper'; +import {Big} from 'big.js'; +import {common as p} from 'protobufjs'; +import {google as spannerClient} from '../protos/protos'; +import {GoogleError} from 'google-gax'; +import * as uuid from 'uuid'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type Value = any; + +let uuidUntypedFlagWarned = false; + +export interface Field { + name: string; + value: Value; +} + +export interface IProtoMessageParams { + // Supports proto message serialized binary data as a `Buffer` or pass a + // message object created using the functions generated by protobufjs-cli. + value: object; + // Fully qualified name of the proto representing the message definition + fullName: string; + /** + * Provide a First Class function that includes nested functions named + * "encode" for serialization and "decode" for deserialization of the proto + * message. The function should be sourced from the JS file generated by + * protobufjs-cli for the proto message. + */ + messageFunction?: Function; +} + +export interface IProtoEnumParams { + // Supports proto enum integer constant or pass the enum string + // the functions generated by protobufjs-cli. + value: string | number; + // Fully qualified name of the proto representing the enum definition + fullName: string; + /** + * An object containing enum string to id mapping. + * @example: { POP: 0, JAZZ: 1, FOLK: 2, ROCK: 3 } + * + * The object should be sourced from the JS file generated by + * protobufjs-cli for the proto message. Additionally, please review the + * sample at {@link www.samples.com} for guidance. + * + * ToDo: Update the link + */ + enumObject?: object; +} + +export interface Json { + [field: string]: Value; +} + +export interface JSONOptions { + wrapNumbers?: boolean; + wrapStructs?: boolean; + includeNameless?: boolean; +} + +// https://github.com/Microsoft/TypeScript/issues/27920 +type DateFields = [number, number, number]; + +/** + * Date-like object used to represent Cloud Spanner Dates. DATE types represent + * a logical calendar date, independent of time zone. DATE values do not + * represent a specific 24-hour period. Rather, a given DATE value represents a + * different 24-hour period when interpreted in a different time zone. Because + * of this, all values passed to {@link Spanner.date} will be interpreted as + * local time. + * + * To represent an absolute point in time, use {@link Spanner.timestamp}. + * + * @see Spanner.date + * @see https://cloud.google.com/spanner/docs/data-types#date-type + * + * @class + * @extends Date + * + * @param {string|number} [date] String representing the date or number + * representing the year. If year is a number between 0 and 99, then year is + * assumed to be 1900 + year. + * @param {number} [month] Number representing the month (0 = January). + * @param {number} [date] Number representing the date. + * + * @example + * ``` + * Spanner.date('3-3-1933'); + * ``` + */ +export class SpannerDate extends Date { + constructor(dateString?: string); + constructor(year: number, month: number, date: number); + constructor(...dateFields: Array) { + const yearOrDateString = dateFields[0]; + + // yearOrDateString could be 0 (number). + if (yearOrDateString === null || yearOrDateString === undefined) { + dateFields[0] = new Date().toDateString(); + } + + // JavaScript Date objects will interpret ISO date strings as Zulu time, + // but by formatting it, we can infer local time. + if (/^\d{4}-\d{1,2}-\d{1,2}/.test(yearOrDateString as string)) { + const [year, month, date] = (yearOrDateString as string).split(/-|T/); + dateFields = [`${month}-${date}-${year}`]; + } + + super(...(dateFields.slice(0, 3) as DateFields)); + } + /** + * Returns the date in ISO date format. + * `YYYY-MM-DD` + * + * @returns {string} + */ + toJSON(): string { + const year = this.getFullYear().toString(); + const month = (this.getMonth() + 1).toString(); + const date = this.getDate().toString(); + + return `${year.padStart(4, '0')}-${month.padStart(2, '0')}-${date.padStart( + 2, + '0', + )}`; + } +} + +/** + * Using an abstract class to simplify checking for wrapped numbers. + * + * @private + */ +abstract class WrappedNumber { + value!: string | number; + abstract valueOf(): number; +} + +/** + * @typedef Float32 + * @see Spanner.float32 + */ +export class Float32 extends WrappedNumber { + value: number; + constructor(value: number) { + super(); + this.value = value; + } + valueOf(): number { + return Number(this.value); + } +} + +/** + * @typedef Float + * @see Spanner.float + */ +export class Float extends WrappedNumber { + value: number; + constructor(value: number) { + super(); + this.value = value; + } + valueOf(): number { + return Number(this.value); + } +} + +/** + * @typedef Int + * @see Spanner.int + */ +export class Int extends WrappedNumber { + value: string; + constructor(value: string) { + super(); + this.value = value.toString(); + } + valueOf(): number { + const num = Number(this.value); + if (num > Number.MAX_SAFE_INTEGER) { + throw new GoogleError(`Integer ${this.value} is out of bounds.`); + } + return num; + } +} + +/** + * @typedef Struct + * @see Spanner.struct + */ +export class Struct extends Array { + /** + * Converts struct into a pojo (plain old JavaScript object). + * + * @param {JSONOptions} [options] JSON options. + * @returns {object} + */ + toJSON(options?: JSONOptions): Json { + return codec.convertFieldsToJson(this, options); + } + /** + * Converts an array of fields to a struct. + * + * @private + * + * @param {object[]} fields List of struct fields. + * @return {Struct} + */ + static fromArray(fields: Field[]): Struct { + return new Struct(...fields); + } + /** + * Converts a JSON object to a struct. + * + * @private + * + * @param {object} json Struct JSON. + * @return {Struct} + */ + static fromJSON(json: Json): Struct { + const fields = Object.keys(json || {}).map(name => { + const value = json[name]; + return {name, value}; + }); + return Struct.fromArray(fields); + } +} + +/** + * @typedef Numeric + * @see Spanner.numeric + */ +export class Numeric { + value: string; + constructor(value: string) { + this.value = value; + } + valueOf(): Big { + return new Big(this.value); + } + toJSON(): string { + return this.valueOf().toJSON(); + } +} + +/** + * @typedef PGNumeric + * @see Spanner.pgNumeric + */ +export class PGNumeric { + value: string; + constructor(pgValue: string | number) { + this.value = pgValue.toString(); + } + valueOf(): Big { + if (this.value.toLowerCase() === 'nan') { + throw new Error(`${this.value} cannot be converted to a numeric value`); + } + return new Big(this.value); + } + toJSON(): string { + return this.valueOf().toJSON(); + } +} + +/** + * @typedef ProtoMessage + * @see Spanner.protoMessage + */ +export class ProtoMessage { + value: Buffer; + fullName: string; + messageFunction?: Function; + + constructor(protoMessageParams: IProtoMessageParams) { + this.fullName = protoMessageParams.fullName; + this.messageFunction = protoMessageParams.messageFunction; + + if (protoMessageParams.value instanceof Buffer) { + this.value = protoMessageParams.value; + } else if (protoMessageParams.messageFunction) { + this.value = protoMessageParams.messageFunction['encode']( + protoMessageParams.value, + ).finish(); + } else { + throw new GoogleError(`protoMessageParams cannot be used to construct + the ProtoMessage. Pass the serialized buffer of the + proto message as the value or provide the message object along with the + corresponding messageFunction generated by protobufjs-cli.`); + } + } + + toJSON(): string { + if (this.messageFunction) { + return this.messageFunction['toObject']( + this.messageFunction['decode'](this.value), + ); + } + return this.value.toString(); + } +} + +/** + * @typedef ProtoEnum + * @see Spanner.protoEnum + */ +export class ProtoEnum { + value: string; + fullName: string; + enumObject?: object; + + constructor(protoEnumParams: IProtoEnumParams) { + this.fullName = protoEnumParams.fullName; + this.enumObject = protoEnumParams.enumObject; + + /** + * @code{IProtoEnumParams} can accept either a number or a string as a value so + * converting to string and checking whether it's numeric using regex. + */ + if (/^\d+$/.test(protoEnumParams.value.toString())) { + this.value = protoEnumParams.value.toString(); + } else if ( + protoEnumParams.enumObject && + protoEnumParams.enumObject[protoEnumParams.value] + ) { + this.value = protoEnumParams.enumObject[protoEnumParams.value]; + } else { + throw new GoogleError(`protoEnumParams cannot be used for constructing the + ProtoEnum. Pass the number as the value or provide the enum string + constant as the value along with the corresponding enumObject generated + by protobufjs-cli.`); + } + } + + toJSON(): string { + if (this.enumObject) { + return Object.getPrototypeOf(this.enumObject)[this.value]; + } + return this.value.toString(); + } +} + +/** + * @typedef PGJsonb + * @see Spanner.pgJsonb + */ +export class PGJsonb { + value: object; + constructor(pgValue: object | string) { + if (typeof pgValue === 'string') { + pgValue = JSON.parse(pgValue) as object; + } + this.value = pgValue; + } + + toString(): string { + return JSON.stringify(this.value); + } +} + +/** + * @typedef PGOid + * @see Spanner.pgOid + */ +export class PGOid extends WrappedNumber { + value: string; + constructor(value: string) { + super(); + this.value = value.toString(); + } + valueOf(): number { + const num = Number(this.value); + if (num > Number.MAX_SAFE_INTEGER) { + throw new GoogleError(`PG.OID ${this.value} is out of bounds.`); + } + return num; + } +} + +/** + * @typedef Interval + * @see Spanner.interval + */ +export class Interval { + private months: number; + private days: number; + private nanoseconds: bigint; + + // Regex to parse ISO8601 duration format: P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S + // Only seconds can be fractional, and can have at most 9 digits after decimal point. + // Both '.' and ',' are considered valid decimal point. + private static readonly ISO8601_PATTERN: RegExp = + /^P(?!$)(-?\d+Y)?(-?\d+M)?(-?\d+D)?(T(?=-?[.,]?\d)(-?\d+H)?(-?\d+M)?(-?(((\d+)([.,]\d{1,9})?)|([.,]\d{1,9}))S)?)?$/; + + static readonly MONTHS_PER_YEAR: number = 12; + static readonly DAYS_PER_MONTH: number = 30; + static readonly HOURS_PER_DAY: number = 24; + static readonly MINUTES_PER_HOUR: number = 60; + static readonly SECONDS_PER_MINUTE: number = 60; + static readonly SECONDS_PER_HOUR: number = + Interval.MINUTES_PER_HOUR * Interval.SECONDS_PER_MINUTE; + static readonly MILLISECONDS_PER_SECOND: number = 1000; + static readonly MICROSECONDS_PER_MILLISECOND: number = 1000; + static readonly NANOSECONDS_PER_MICROSECOND: number = 1000; + static readonly NANOSECONDS_PER_MILLISECOND: number = + Interval.MICROSECONDS_PER_MILLISECOND * + Interval.NANOSECONDS_PER_MICROSECOND; + static readonly NANOSECONDS_PER_SECOND: number = + Interval.MILLISECONDS_PER_SECOND * + Interval.MICROSECONDS_PER_MILLISECOND * + Interval.NANOSECONDS_PER_MICROSECOND; + static readonly NANOSECONDS_PER_DAY: bigint = + BigInt(Interval.HOURS_PER_DAY) * + BigInt(Interval.SECONDS_PER_HOUR) * + BigInt(Interval.NANOSECONDS_PER_SECOND); + static readonly NANOSECONDS_PER_MONTH: bigint = + BigInt(Interval.DAYS_PER_MONTH) * Interval.NANOSECONDS_PER_DAY; + static readonly ZERO: Interval = new Interval(0, 0, BigInt(0)); + + /** + * @param months months part of the `Interval` + * @param days days part of the `Interval` + * @param nanoseconds nanoseconds part of the `Interval` + */ + constructor(months: number, days: number, nanoseconds: bigint) { + if (!isInteger(months)) { + throw new GoogleError( + `Invalid months: ${months}, months should be an integral value`, + ); + } + + if (!isInteger(days)) { + throw new GoogleError( + `Invalid days: ${days}, days should be an integral value`, + ); + } + + if (isNull(nanoseconds) || isUndefined(nanoseconds)) { + throw new GoogleError( + `Invalid nanoseconds: ${nanoseconds}, nanoseconds should be a valid bigint value`, + ); + } + + this.months = months; + this.days = days; + this.nanoseconds = nanoseconds; + } + + /** + * @returns months part of the `Interval`. + */ + getMonths(): number { + return this.months; + } + + /** + * @returns days part of the `Interval`. + */ + getDays(): number { + return this.days; + } + + /** + * @returns nanoseconds part of the `Interval`. + */ + getNanoseconds(): bigint { + return this.nanoseconds; + } + + /** + * Constructs an `Interval` with specified months. + */ + static fromMonths(months: number): Interval { + return new Interval(months, 0, BigInt(0)); + } + + /** + * Constructs an `Interval` with specified days. + */ + static fromDays(days: number): Interval { + return new Interval(0, days, BigInt(0)); + } + + /** + * Constructs an `Interval` with specified seconds. + */ + static fromSeconds(seconds: number): Interval { + if (!isInteger(seconds)) { + throw new GoogleError( + `Invalid seconds: ${seconds}, seconds should be an integral value`, + ); + } + return new Interval( + 0, + 0, + BigInt(Interval.NANOSECONDS_PER_SECOND) * BigInt(seconds), + ); + } + + /** + * Constructs an `Interval` with specified milliseconds. + */ + static fromMilliseconds(milliseconds: number): Interval { + if (!isInteger(milliseconds)) { + throw new GoogleError( + `Invalid milliseconds: ${milliseconds}, milliseconds should be an integral value`, + ); + } + return new Interval( + 0, + 0, + BigInt(Interval.NANOSECONDS_PER_MILLISECOND) * BigInt(milliseconds), + ); + } + + /** + * Constructs an `Interval` with specified microseconds. + */ + static fromMicroseconds(microseconds: number): Interval { + if (!isInteger(microseconds)) { + throw new GoogleError( + `Invalid microseconds: ${microseconds}, microseconds should be an integral value`, + ); + } + return new Interval( + 0, + 0, + BigInt(Interval.NANOSECONDS_PER_MICROSECOND) * BigInt(microseconds), + ); + } + + /** + * Constructs an `Interval` with specified nanoseconds. + */ + static fromNanoseconds(nanoseconds: bigint): Interval { + return new Interval(0, 0, nanoseconds); + } + + /** + * Constructs an Interval from ISO8601 duration format: `P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S`. + * Only seconds can be fractional, and can have at most 9 digits after decimal point. + * Both '.' and ',' are considered valid decimal point. + */ + static fromISO8601(isoString: string): Interval { + const matcher = Interval.ISO8601_PATTERN.exec(isoString); + if (!matcher) { + throw new GoogleError(`Invalid ISO8601 duration string: ${isoString}`); + } + + const getNullOrDefault = (groupIdx: number): string => + matcher[groupIdx] === undefined ? '0' : matcher[groupIdx]; + const years: number = parseInt(getNullOrDefault(1).replace('Y', '')); + const months: number = parseInt(getNullOrDefault(2).replace('M', '')); + const days: number = parseInt(getNullOrDefault(3).replace('D', '')); + const hours: number = parseInt(getNullOrDefault(5).replace('H', '')); + const minutes: number = parseInt(getNullOrDefault(6).replace('M', '')); + const seconds: Big = Big( + getNullOrDefault(7).replace('S', '').replace(',', '.'), + ); + + const totalMonths: number = Big(years) + .mul(Big(Interval.MONTHS_PER_YEAR)) + .add(Big(months)) + .toNumber(); + if (!Number.isSafeInteger(totalMonths)) { + throw new GoogleError( + 'Total months is outside of the range of safe integer', + ); + } + + const totalNanoseconds = BigInt( + seconds + .add( + Big((BigInt(hours) * BigInt(Interval.SECONDS_PER_HOUR)).toString()), + ) + .add( + Big( + (BigInt(minutes) * BigInt(Interval.SECONDS_PER_MINUTE)).toString(), + ), + ) + .mul(Big(this.NANOSECONDS_PER_SECOND)) + .toString(), + ); + + return new Interval(totalMonths, days, totalNanoseconds); + } + + /** + * @returns string representation of Interval in ISO8601 duration format: `P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S` + */ + toISO8601(): string { + if (this.equals(Interval.ZERO)) { + return 'P0Y'; + } + + // months part is normalized to years and months. + let result = 'P'; + if (this.months !== 0) { + const years_part: number = Math.trunc( + this.months / Interval.MONTHS_PER_YEAR, + ); + const months_part: number = + this.months - years_part * Interval.MONTHS_PER_YEAR; + if (years_part !== 0) { + result += `${years_part}Y`; + } + if (months_part !== 0) { + result += `${months_part}M`; + } + } + + if (this.days !== 0) { + result += `${this.days}D`; + } + + // Nanoseconds part is normalized to hours, minutes and nanoseconds. + if (this.nanoseconds !== BigInt(0)) { + result += 'T'; + let nanoseconds: bigint = this.nanoseconds; + const hours_part: bigint = + nanoseconds / + BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_HOUR); + nanoseconds = + nanoseconds - + hours_part * + BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_HOUR); + + const minutes_part: bigint = + nanoseconds / + BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_MINUTE); + nanoseconds = + nanoseconds - + minutes_part * + BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_MINUTE); + const zero_bigint = BigInt(0); + if (hours_part !== zero_bigint) { + result += `${hours_part}H`; + } + + if (minutes_part !== zero_bigint) { + result += `${minutes_part}M`; + } + + let sign = ''; + if (nanoseconds < zero_bigint) { + sign = '-'; + nanoseconds = -nanoseconds; + } + + // Nanoseconds are converted to seconds and fractional part. + const seconds_part: bigint = + nanoseconds / BigInt(Interval.NANOSECONDS_PER_SECOND); + nanoseconds = + nanoseconds - seconds_part * BigInt(Interval.NANOSECONDS_PER_SECOND); + if (seconds_part !== zero_bigint || nanoseconds !== zero_bigint) { + result += `${sign}${seconds_part}`; + if (nanoseconds !== zero_bigint) { + // Fractional part is kept in a group of 3 + // For e.g.: PT0.5S will be normalized to PT0.500S + result += `.${nanoseconds + .toString() + .padStart(9, '0') + .replace(/(0{3})+$/, '')}`; + } + result += 'S'; + } + } + + return result; + } + + equals(other: Interval): boolean { + if (!other) { + return false; + } + + return ( + this.months === other.months && + this.days === other.days && + this.nanoseconds === other.nanoseconds + ); + } + + valueOf(): Interval { + return this; + } + + /** + * @returns JSON representation for Interval. + * Interval is represented in ISO8601 duration format string in JSON. + */ + toJSON(): string { + return this.toISO8601().toString(); + } +} + +/** + * @typedef JSONOptions + * @property {boolean} [wrapNumbers=false] Indicates if the numbers should be + * wrapped in Int/Float wrappers. + * @property {boolean} [wrapStructs=false] Indicates if the structs should be + * wrapped in Struct wrapper. + * @property {boolean} [includeNameless=false] Indicates if nameless columns + * should be included in the result. If true, nameless columns will be + * assigned the name '_{column_index}'. + */ +/** + * Wherever a row or struct object is returned, it is assigned a "toJSON" + * function. This function will generate the JSON for that row. + * + * @private + * + * @param {array} row The row to generate JSON for. + * @param {JSONOptions} [options] JSON options. + * @returns {object} + */ +function convertFieldsToJson(fields: Field[], options?: JSONOptions): Json { + const json: Json = {}; + + const defaultOptions = { + wrapNumbers: false, + wrapStructs: false, + includeNameless: false, + }; + + options = Object.assign(defaultOptions, options); + + let index = 0; + for (const {name, value} of fields) { + if (!name && !options.includeNameless) { + continue; + } + const fieldName = name ? name : `_${index}`; + + try { + json[fieldName] = convertValueToJson(value, options); + } catch (e) { + (e as Error).message = [ + `Serializing column "${fieldName}" encountered an error: ${ + (e as Error).message + }`, + 'Call row.toJSON({ wrapNumbers: true }) to receive a custom type.', + ].join(' '); + throw e; + } + index++; + } + + return json; +} + +/** + * Attempts to convert a wrapped or nested value into a native JavaScript type. + * + * @private + * + * @param {*} value The value to convert. + * @param {JSONOptions} options JSON options. + * @return {*} + */ +function convertValueToJson(value: Value, options: JSONOptions): Value { + if (!options.wrapNumbers && value instanceof WrappedNumber) { + return value.valueOf(); + } + + if (value instanceof Struct) { + if (!options.wrapStructs) { + return value.toJSON(options); + } + + return value.map(({name, value}) => { + value = convertValueToJson(value, options); + return {name, value}; + }); + } + + if (Array.isArray(value)) { + return value.map(child => convertValueToJson(child, options)); + } + + if (value instanceof ProtoMessage || value instanceof ProtoEnum) { + return value.toJSON(); + } + + return value; +} + +/** + * Re-decode after the generic gRPC decoding step. + * + * @private + * + * @param {*} value Value to decode + * @param {object[]} type Value type object. + * @param columnMetadata Optional parameter to deserialize data + * @returns {*} + */ +function decode( + value: Value, + type: spannerClient.spanner.v1.Type, + columnMetadata?: object, +): Value { + if (isNull(value)) { + return null; + } + + let decoded = value; + let fields; + + switch (type.code) { + case spannerClient.spanner.v1.TypeCode.BYTES: + case 'BYTES': + decoded = Buffer.from(decoded, 'base64'); + break; + case spannerClient.spanner.v1.TypeCode.PROTO: + case 'PROTO': + decoded = Buffer.from(decoded, 'base64'); + decoded = new ProtoMessage({ + value: decoded, + fullName: type.protoTypeFqn, + messageFunction: columnMetadata as Function, + }); + break; + case spannerClient.spanner.v1.TypeCode.ENUM: + case 'ENUM': + decoded = new ProtoEnum({ + value: decoded, + fullName: type.protoTypeFqn, + enumObject: columnMetadata as object, + }); + break; + case spannerClient.spanner.v1.TypeCode.FLOAT32: + case 'FLOAT32': + decoded = new Float32(decoded); + break; + case spannerClient.spanner.v1.TypeCode.FLOAT64: + case 'FLOAT64': + decoded = new Float(decoded); + break; + case spannerClient.spanner.v1.TypeCode.INT64: + case 'INT64': + if ( + type.typeAnnotation === + spannerClient.spanner.v1.TypeAnnotationCode.PG_OID || + type.typeAnnotation === 'PG_OID' + ) { + decoded = new PGOid(decoded); + break; + } + decoded = new Int(decoded); + break; + case spannerClient.spanner.v1.TypeCode.NUMERIC: + case 'NUMERIC': + if ( + type.typeAnnotation === + spannerClient.spanner.v1.TypeAnnotationCode.PG_NUMERIC || + type.typeAnnotation === 'PG_NUMERIC' + ) { + decoded = new PGNumeric(decoded); + break; + } + decoded = new Numeric(decoded); + break; + case spannerClient.spanner.v1.TypeCode.TIMESTAMP: + case 'TIMESTAMP': + decoded = new PreciseDate(decoded); + break; + case spannerClient.spanner.v1.TypeCode.DATE: + case 'DATE': + decoded = new SpannerDate(decoded); + break; + case spannerClient.spanner.v1.TypeCode.JSON: + case 'JSON': + if ( + type.typeAnnotation === + spannerClient.spanner.v1.TypeAnnotationCode.PG_JSONB || + type.typeAnnotation === 'PG_JSONB' + ) { + decoded = new PGJsonb(decoded); + break; + } + decoded = JSON.parse(decoded); + break; + case spannerClient.spanner.v1.TypeCode.INTERVAL: + case 'INTERVAL': + decoded = Interval.fromISO8601(decoded); + break; + case spannerClient.spanner.v1.TypeCode.ARRAY: + case 'ARRAY': + decoded = decoded.map(value => { + return decode( + value, + type.arrayElementType! as spannerClient.spanner.v1.Type, + columnMetadata, + ); + }); + break; + case spannerClient.spanner.v1.TypeCode.STRUCT: + case 'STRUCT': + fields = type.structType!.fields!.map(({name, type}, index) => { + const value = decode( + (!Array.isArray(decoded) && decoded[name!]) || decoded[index], + type as spannerClient.spanner.v1.Type, + columnMetadata, + ); + return {name, value}; + }); + decoded = Struct.fromArray(fields as Field[]); + break; + default: + break; + } + + return decoded; +} + +/** + * Encode a value in the format the API expects. + * + * @private + * + * @param {*} value The value to be encoded. + * @returns {object} google.protobuf.Value + */ +function encode(value: Value): p.IValue { + return GrpcService.encodeValue_(encodeValue(value)); +} + +/** + * Formats values into expected format of google.protobuf.Value. The actual + * conversion to a google.protobuf.Value object happens via + * `Service.encodeValue_` + * + * @private + * + * @param {*} value The value to be encoded. + * @returns {*} + */ +function encodeValue(value: Value): Value { + if (isNumber(value) && !isDecimal(value)) { + return value.toString(); + } + + if (isDate(value)) { + return value.toJSON(); + } + + if (value instanceof WrappedNumber) { + return value.value; + } + + if (value instanceof Numeric) { + return value.value; + } + + if (value instanceof PGNumeric) { + return value.value; + } + + if (Buffer.isBuffer(value)) { + return value.toString('base64'); + } + + if (value instanceof ProtoMessage) { + return value.value.toString('base64'); + } + + if (value instanceof ProtoEnum) { + return value.value; + } + + if (value instanceof Struct) { + return Array.from(value).map(field => encodeValue(field.value)); + } + + if (isArray(value)) { + return value.map(encodeValue); + } + + if (value instanceof PGJsonb) { + return value.toString(); + } + + if (value instanceof Interval) { + return value.toISO8601(); + } + + if (isObject(value)) { + return JSON.stringify(value); + } + + return value; +} + +/** + * Just a map with friendlier names for the types. + * + * @private + * @enum {string} + */ +const TypeCode: { + [name: string]: keyof typeof spannerClient.spanner.v1.TypeCode; +} = { + unspecified: 'TYPE_CODE_UNSPECIFIED', + bool: 'BOOL', + int64: 'INT64', + pgOid: 'INT64', + uuid: 'UUID', + float32: 'FLOAT32', + float64: 'FLOAT64', + numeric: 'NUMERIC', + pgNumeric: 'NUMERIC', + timestamp: 'TIMESTAMP', + date: 'DATE', + string: 'STRING', + bytes: 'BYTES', + json: 'JSON', + jsonb: 'JSON', + interval: 'INTERVAL', + proto: 'PROTO', + enum: 'ENUM', + array: 'ARRAY', + struct: 'STRUCT', +}; + +/** + * Conveniece Type object that simplifies specifying the data type, the array + * child type and/or struct fields. + * + * @private + */ +export interface Type { + type: string; + fields?: FieldType[]; + child?: Type; + fullName?: string; +} + +interface FieldType extends Type { + name: string; +} + +/** + * @typedef {ParamType} StructField + * @property {string} name The name of the field. + */ +/** + * @typedef {object} ParamType + * @property {string} type The param type. Must be one of the following: + * - uuid + * - float32 + * - float64 + * - int64 + * - numeric + * - bool + * - string + * - bytes + * - json + * - interval + * - proto + * - enum + * - timestamp + * - date + * - struct + * - array + * @property {StructField[]} [fields] **For struct types only**. Type + * definitions for the individual fields. + * @property {string|ParamType} [child] **For array types only**. The array + * element type. + */ +/** + * Get the corresponding Spanner data type for the provided value. + * + * @private + * + * @param {*} value - The value. + * @returns {object} + * + * @example + * ``` + * codec.getType(NaN); + * // {type: 'float64'} + * ``` + */ +function getType(value: Value): Type { + const isSpecialNumber = + isInfinite(value) || (isNumber(value) && isNaN(value)); + + if (value instanceof Float32) { + return {type: 'float32'}; + } + + if (isDecimal(value) || isSpecialNumber || value instanceof Float) { + return {type: 'float64'}; + } + + if (isNumber(value) || value instanceof Int) { + return {type: 'int64'}; + } + + if (value instanceof Numeric) { + return {type: 'numeric'}; + } + + if (value instanceof PGNumeric) { + return {type: 'pgNumeric'}; + } + + if (value instanceof PGJsonb) { + return {type: 'pgJsonb'}; + } + + if (value instanceof PGOid) { + return {type: 'pgOid'}; + } + + if (value instanceof Interval) { + return {type: 'interval'}; + } + + if (value instanceof ProtoMessage) { + return {type: 'proto', fullName: value.fullName}; + } + + if (value instanceof ProtoEnum) { + return {type: 'enum', fullName: value.fullName}; + } + + if (isBoolean(value)) { + return {type: 'bool'}; + } + + if (process.env['SPANNER_ENABLE_UUID_AS_UNTYPED'] === 'true') { + if (!uuidUntypedFlagWarned) { + process.emitWarning( + 'SPANNER_ENABLE_UUID_AS_UNTYPED environment variable is deprecated and will be removed in a future release.', + 'DeprecationWarning', + ); + uuidUntypedFlagWarned = true; + } + if (uuid.validate(value)) { + return {type: 'unspecified'}; + } + } + + if (isString(value)) { + return {type: 'string'}; + } + + if (Buffer.isBuffer(value)) { + return {type: 'bytes'}; + } + + if (value instanceof SpannerDate) { + return {type: 'date'}; + } + + if (isDate(value)) { + return {type: 'timestamp'}; + } + + if (value instanceof Struct) { + return { + type: 'struct', + fields: Array.from(value).map(({name, value}) => { + return Object.assign({name}, getType(value)); + }), + }; + } + + if (isArray(value)) { + let child; + + for (let i = 0; i < value.length; i++) { + child = value[i]; + + if (!isNull(child)) { + break; + } + } + + return { + type: 'array', + child: getType(child), + }; + } + + if (isObject(value)) { + return {type: 'json'}; + } + + return {type: 'unspecified'}; +} + +/** + * Converts a value to google.protobuf.ListValue + * + * @private + * + * @param {*} value The value to convert. + * @returns {object} + */ +function convertToListValue(value: T): p.IListValue { + const values = (toArray(value) as T[]).map(codec.encode); + return {values}; +} + +/** + * Converts milliseconds to google.protobuf.Timestamp + * + * @private + * + * @param {number} ms The milliseconds to convert. + * @returns {object} + */ +function convertMsToProtoTimestamp( + ms: number, +): spannerClient.protobuf.ITimestamp { + const rawSeconds = ms / 1000; + const seconds = Math.floor(rawSeconds); + const nanos = Math.round((rawSeconds - seconds) * 1e9); + return {seconds, nanos}; +} + +/** + * Converts google.protobuf.Timestamp to Date object. + * + * @private + * + * @param {object} timestamp The protobuf timestamp. + * @returns {Date} + */ +function convertProtoTimestampToDate({ + nanos = 0, + seconds = 0, +}: p.ITimestamp): Date { + const ms = Math.floor(nanos) / 1e6; + const s = Math.floor(seconds as number); + return new Date(s * 1000 + ms); +} + +/** + * Encodes paramTypes into correct structure. + * + * @private + * + * @param {object|string} [config='unspecified'] Type config. + * @return {object} + */ +function createTypeObject( + friendlyType?: string | Type, +): spannerClient.spanner.v1.Type { + if (!friendlyType) { + friendlyType = 'unspecified'; + } + + if (typeof friendlyType === 'string') { + friendlyType = {type: friendlyType} as Type; + } + + const config: Type = friendlyType as Type; + const code: keyof typeof spannerClient.spanner.v1.TypeCode = + TypeCode[config.type] || TypeCode.unspecified; + const type: spannerClient.spanner.v1.Type = { + code, + } as spannerClient.spanner.v1.Type; + + if (code === 'PROTO' || code === 'ENUM') { + type.protoTypeFqn = config.fullName || ''; + } + + if (code === 'ARRAY') { + type.arrayElementType = codec.createTypeObject(config.child); + } + + if (code === 'STRUCT') { + type.structType = { + fields: toArray(config.fields!).map(field => { + return {name: field.name, type: codec.createTypeObject(field)}; + }), + }; + } + + if (friendlyType.type === 'pgNumeric') { + type.typeAnnotation = + spannerClient.spanner.v1.TypeAnnotationCode.PG_NUMERIC; + } else if (friendlyType.type === 'jsonb') { + type.typeAnnotation = spannerClient.spanner.v1.TypeAnnotationCode.PG_JSONB; + } else if (friendlyType.type === 'pgOid') { + type.typeAnnotation = spannerClient.spanner.v1.TypeAnnotationCode.PG_OID; + } + return type; +} + +export const codec = { + convertToListValue, + convertMsToProtoTimestamp, + convertProtoTimestampToDate, + createTypeObject, + SpannerDate, + Float32, + Float, + Int, + Numeric, + PGNumeric, + PGJsonb, + ProtoMessage, + ProtoEnum, + PGOid, + Interval, + convertFieldsToJson, + decode, + encode, + getType, + Struct, +}; diff --git a/handwritten/spanner/src/common-grpc/service-object.ts b/handwritten/spanner/src/common-grpc/service-object.ts new file mode 100644 index 00000000000..d071bb0104e --- /dev/null +++ b/handwritten/spanner/src/common-grpc/service-object.ts @@ -0,0 +1,153 @@ +/*! + * Copyright 2019 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. + */ + +/*! + * @module commonGrpc/serviceObject + */ + +import { + Metadata, + MetadataCallback, + ResponseCallback, + ServiceObject, + ServiceObjectConfig, + SetMetadataResponse, + util, +} from '@google-cloud/common'; +import {promisifyAll} from '@google-cloud/promisify'; +import * as extend from 'extend'; +import {CoreOptions, RequestCallback, Response} from 'teeny-request'; + +export class GrpcServiceObject extends ServiceObject { + declare parent: GrpcServiceObject; + + /** + * GrpcServiceObject is a base class, meant to be inherited from by a service + * object that uses the gRPC protobuf API. + * + * @constructor + * @alias module:common/grpc-service-object + * + * @private + * + * @param {object} config - Configuration object. + */ + constructor(config: ServiceObjectConfig) { + super(config); + this.parent = config.parent as GrpcServiceObject; + } + + /** + * Delete the object. + * + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + */ + delete(): Promise<[Response]>; + delete(callback: RequestCallback): void; + delete(callback?: RequestCallback): void | Promise<[Response]> { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const protoOpts = (this.methods.delete as any).protoOpts; + const reqOpts = this.getOpts(this.methods.delete); + this.request(protoOpts, reqOpts, callback || util.noop); + } + + /** + * Get the metadata of this object. + * + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.metadata - The metadata for this object. + */ + getMetadata(): Promise; + getMetadata(callback: MetadataCallback): void; + getMetadata(callback?: MetadataCallback): void | Promise { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const protoOpts = (this.methods.getMetadata as any).protoOpts; + const reqOpts = this.getOpts(this.methods.getMetadata); + this.request(protoOpts, reqOpts, (err: Error, resp: Response) => { + if (err) { + callback!(err, null, resp); + return; + } + this.metadata = resp; + callback!(null, this.metadata, resp); + }); + } + + /** + * Set the metadata for this object. + * + * @param {object} metadata - The metadata to set on this object. + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + */ + setMetadata(metadata: Metadata): Promise; + setMetadata(metadata: Metadata, callback: ResponseCallback): void; + setMetadata( + metadata: Metadata, + callback?: ResponseCallback, + ): void | Promise { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const protoOpts = (this.methods.setMetadata as any).protoOpts; + const reqOpts = extend( + true, + {}, + this.getOpts(this.methods.setMetadata), + metadata, + ); + this.request(protoOpts, reqOpts, callback || util.noop); + } + + /** + * Patch a request to the GrpcService object. + * + * @private + */ + request(...args: Array<{}>) { + return this.parent.request(...args); + } + + /** + * Patch a streaming request to the GrpcService object. + * + * @private + */ + requestStream(...args: Array<{}>) { + return this.parent.requestStream(...args); + } + + /** + * Patch a writable streaming request to the GrpcService object. + * + * @private + */ + requestWritableStream(...args: Array<{}>) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return (this.parent as any).requestWritableStream.apply(this.parent, args); + } + + private getOpts(metadata: boolean | {reqOpts?: CoreOptions}) { + return typeof metadata === 'boolean' ? {} : metadata.reqOpts || {}; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(GrpcServiceObject); diff --git a/handwritten/spanner/src/common-grpc/service.ts b/handwritten/spanner/src/common-grpc/service.ts new file mode 100644 index 00000000000..ba7691ce5b1 --- /dev/null +++ b/handwritten/spanner/src/common-grpc/service.ts @@ -0,0 +1,1093 @@ +/*! + * Copyright 2019 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. + */ + +/*! + * @module commonGrpc/service + */ + +import * as path from 'path'; +import { + Abortable, + BodyResponseCallback, + DecorateRequestOptions, + Service, + ServiceConfig, + util, +} from '@google-cloud/common'; +import {replaceProjectIdToken} from '@google-cloud/projectify'; +import { + loadSync, + PackageDefinition, + ServiceDefinition, +} from '@grpc/proto-loader'; +import * as duplexify from 'duplexify'; +import {EventEmitter} from 'events'; +import * as extend from 'extend'; +import {grpc, GrpcClient} from 'google-gax'; +import {Request, Response} from 'teeny-request'; +import * as retryRequest from 'retry-request'; +import {Duplex, PassThrough} from 'stream'; +import { + isArray, + isBoolean, + isError, + isNull, + isNumber, + isObject, + isString, + isUndefined, +} from '../helper'; + +const gaxProtoPath = path.join( + path.dirname(require.resolve('google-gax')), + '..', + 'protos', +); + +export interface ServiceRequestCallback { + (err: Error | null, apiResponse?: Response): void; +} + +interface RetryOptions { + objectMode?: boolean; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + request?: any; + retries?: number; + noResponseRetries?: number; + currentRetryAttempt?: number; + shouldRetryFn?: (response: Response) => boolean; +} + +export interface ProtoOpts { + service: string; + method: string; + timeout?: number; + retryOpts?: RetryOptions; + stream?: Duplex; +} + +interface GrpcOptions { + deadline?: Date; +} + +/** + * Configuration object for GrpcService. + */ +export interface GrpcServiceConfig extends ServiceConfig { + /** gRPC implementation to use. By default, uses `@grpc/grpc-js`. */ + grpc?: typeof grpc; + /** gRPC version, to send in headers */ + grpcVersion?: string; + /** Metadata to send with every request. */ + grpcMetadata: grpc.Metadata; + /** The root directory where proto files live. */ + protosDir: string; + /** + * Directly provide the required proto files. This is useful when a single + * class requires multiple services. + */ + protoServices: { + [serviceName: string]: {path: string; service: string; baseUrl: string}; + }; + customEndpoint: boolean; +} + +// TODO: convert this object to an array + +/** + * @const {object} - A map of protobuf codes to HTTP status codes. + * @private + */ +const GRPC_ERROR_CODE_TO_HTTP = { + 0: { + code: 200, + message: 'OK', + }, + + 1: { + code: 499, + message: 'Client Closed Request', + }, + + 2: { + code: 500, + message: 'Internal Server Error', + }, + + 3: { + code: 400, + message: 'Bad Request', + }, + + 4: { + code: 504, + message: 'Gateway Timeout', + }, + + 5: { + code: 404, + message: 'Not Found', + }, + + 6: { + code: 409, + message: 'Conflict', + }, + + 7: { + code: 403, + message: 'Forbidden', + }, + + 8: { + code: 429, + message: 'Too Many Requests', + }, + + 9: { + code: 412, + message: 'Precondition Failed', + }, + + 10: { + code: 409, + message: 'Conflict', + }, + + 11: { + code: 400, + message: 'Bad Request', + }, + + 12: { + code: 501, + message: 'Not Implemented', + }, + + 13: { + code: 500, + message: 'Internal Server Error', + }, + + 14: { + code: 503, + message: 'Service Unavailable', + }, + + 15: { + code: 500, + message: 'Internal Server Error', + }, + + 16: { + code: 401, + message: 'Unauthorized', + }, +}; + +/** + * The default configuration for all gRPC Service instantions. + * + * @resource [All options]{@link + * https://github.com/grpc/grpc/blob/13e185419cd177b7fb552601665e43820321a96b/include/grpc/impl/codegen/grpc_types.h#L148} + * + * @private + * + * @type {object} + */ +const GRPC_SERVICE_OPTIONS = { + // RE: https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1991 + 'grpc.max_send_message_length': -1, // unlimited + 'grpc.max_receive_message_length': -1, // unlimited + + // RE: https://github.com/grpc/grpc/issues/8839 + // RE: https://github.com/grpc/grpc/issues/8382 + // RE: https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1991 + 'grpc.initial_reconnect_backoff_ms': 5000, +}; + +export interface ObjectToStructConverterConfig { + removeCircular?: boolean; + stringify?: boolean; +} + +export class ObjectToStructConverter { + seenObjects: Set<{}>; + removeCircular: boolean; + stringify?: boolean; + /** + * A class that can be used to convert an object to a struct. Optionally this + * class can be used to erase/throw on circular references during conversion. + * + * @private + * + * @param {object=} options - Configuration object. + * @param {boolean} options.removeCircular - Remove circular references in the + * object with a placeholder string. (Default: `false`) + * @param {boolean} options.stringify - Stringify un-recognized types. (Default: + * `false`) + */ + constructor(options?: ObjectToStructConverterConfig) { + options = options || {}; + this.seenObjects = new Set(); + this.removeCircular = options.removeCircular === true; + this.stringify = options.stringify === true; + } + + /** + * Begin the conversion process from a JS object to an encoded gRPC Value + * message. + * + * @param {*} value - The input value. + * @return {object} - The encoded value. + * + * @example + * ObjectToStructConverter.convert({ + * aString: 'Hi' + * }); + * // { + * // fields: { + * // aString: { + * // stringValue: 'Hello!' + * // } + * // } + * // } + */ + convert(obj: {}) { + const convertedObject = { + fields: {}, + }; + this.seenObjects.add(obj); + for (const prop in obj) { + if (Object.prototype.hasOwnProperty.call(obj, prop)) { + const value = obj[prop]; + if (isUndefined(value)) { + continue; + } + convertedObject.fields[prop] = this.encodeValue_(value); + } + } + this.seenObjects.delete(obj); + return convertedObject; + } + + /** + * Convert a raw value to a type-denoted protobuf message-friendly object. + * + * @private + * + * @param {*} value - The input value. + * @return {*} - The encoded value. + * + * @example + * ObjectToStructConverter.encodeValue('Hi'); + * // { + * // stringValue: 'Hello!' + * // } + */ + encodeValue_(value: {}) { + let convertedValue; + + if (isNull(value)) { + convertedValue = { + nullValue: 0, + }; + } else if (isNumber(value)) { + convertedValue = { + numberValue: value, + }; + } else if (isString(value)) { + convertedValue = { + stringValue: value, + }; + } else if (isBoolean(value)) { + convertedValue = { + boolValue: value, + }; + } else if (Buffer.isBuffer(value)) { + convertedValue = { + blobValue: value, + }; + } else if (isObject(value)) { + if (this.seenObjects.has(value)) { + // Circular reference. + if (!this.removeCircular) { + throw new Error( + [ + 'This object contains a circular reference. To automatically', + 'remove it, set the `removeCircular` option to true.', + ].join(' '), + ); + } + convertedValue = { + stringValue: '[Circular]', + }; + } else { + convertedValue = { + structValue: this.convert(value), + }; + } + } else if (isArray(value)) { + convertedValue = { + listValue: { + values: (value as Array<{}>).map(this.encodeValue_.bind(this)), + }, + }; + } else { + if (!this.stringify) { + throw new Error('Value of type ' + typeof value + ' not recognized.'); + } + convertedValue = { + stringValue: String(value), + }; + } + return convertedValue; + } +} + +export class GrpcService extends Service { + grpc?: typeof grpc; + grpcVersion?: string; + grpcCredentials?: {}; + grpcMetadata?: {add: Function}; + maxRetries?: number; + userAgent?: string; + activeServiceMap_ = new Map(); + protos = {}; + + /** A cache for proto objects. */ + private static protoObjectCache: {[name: string]: PackageDefinition} = {}; + + static readonly GRPC_SERVICE_OPTIONS = GRPC_SERVICE_OPTIONS; + static readonly GRPC_ERROR_CODE_TO_HTTP = GRPC_ERROR_CODE_TO_HTTP; + static readonly ObjectToStructConverter = ObjectToStructConverter; + + /** + * Service is a base class, meant to be inherited from by a "service," like + * BigQuery or Storage. + * + * This handles making authenticated requests by exposing a `makeReq_` + * function. + * + * @constructor + * @alias module:common/grpc-service + * + * @param config - Configuration object. + * @param {object} options - [Configuration object](#/docs/?method=gcloud). + */ + constructor(config: GrpcServiceConfig, options) { + super(config, options); + + if (global['GCLOUD_SANDBOX_ENV']) { + // gRPC has a tendency to cause our doc unit tests to fail, so we prevent + // any calls to that library from going through. + // Reference: + // https://github.com/GoogleCloudPlatform/google-cloud-node/pull/1137#issuecomment-193315047 + return global['GCLOUD_SANDBOX_ENV']; + } + if (config.grpc) { + this.grpc = config.grpc; + this.grpcVersion = config.grpcVersion || 'grpc/unknown'; + } else { + this.grpc = grpc; + this.grpcVersion = 'grpc/' + new GrpcClient().grpcVersion; + } + if (config.customEndpoint) { + this.grpcCredentials = this.grpc.credentials.createInsecure(); + } + + this.grpcMetadata = new this.grpc.Metadata(); + this.grpcMetadata!.add( + 'x-goog-api-client', + [ + 'gl-node/' + process.versions.node, + 'gccl/' + config.packageJson.version, + this.grpcVersion, + ].join(' '), + ); + if (config.grpcMetadata) { + for (const prop in config.grpcMetadata) { + this.grpcMetadata!.add(prop, config.grpcMetadata[prop]); + } + } + + this.maxRetries = options.maxRetries; + this.userAgent = util.getUserAgentFromPackageJson(config.packageJson); + + if (this.providedUserAgent) { + this.userAgent = `${this.providedUserAgent} ${this.userAgent}`; + } + options['grpc.primary_user_agent'] = this.userAgent; + + this.activeServiceMap_ = new Map(); + this.protos = {}; + const protoServices = config.protoServices; + + Object.keys(protoServices).forEach(name => { + const protoConfig = protoServices[name]; + const services = this.loadProtoFile(protoConfig.path, config); + const serviceKey = ['google', protoConfig.service, name] + .filter(x => x) + .join('.'); + const service = services[serviceKey] as ServiceDefinition & { + baseUrl?: string; + }; + + this.protos[name] = service; + + if (protoConfig.baseUrl) { + service.baseUrl = protoConfig.baseUrl; + } + }); + } + + /** + * Make an authenticated request with gRPC. + * + * @param {object} protoOpts - The proto options. + * @param {string} protoOpts.service - The service name. + * @param {string} protoOpts.method - The method name. + * @param {number=} protoOpts.timeout - After how many milliseconds should the + * request cancel. + * @param {object} reqOpts - The request options. + * @param {function=} callback - The callback function. + */ + request(reqOpts: DecorateRequestOptions): Promise; + request( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void; + request( + reqOpts: DecorateRequestOptions, + callback?: BodyResponseCallback, + ): void | Promise; + request( + protoOpts: ProtoOpts, + reqOpts: DecorateRequestOptions, + callback: ServiceRequestCallback, + ): Abortable | void; + request( + pOpts: ProtoOpts | DecorateRequestOptions, + rOpts?: DecorateRequestOptions | BodyResponseCallback, + callback?: ServiceRequestCallback, + ): Abortable | void | Promise { + /** + * The function signature above is a little funky. This is due to the way + * method overloading in TypeScript operates. Since this class extends + * Service, the signatures for `request` need to have + * *something* in common. The only signature actually used here is: + * + * request(protoOpts: ProtoOpts, reqOpts: DecorateRequestOptions, callback: + * ServiceRequestCallback): Abortable|void; + * + * Hence the weird casting below. + */ + const protoOpts = pOpts as ProtoOpts; + let reqOpts = rOpts as DecorateRequestOptions; + + if (global['GCLOUD_SANDBOX_ENV']) { + return global['GCLOUD_SANDBOX_ENV']; + } + + if (!this.grpcCredentials) { + // We must establish an authClient to give to grpc. + this.getGrpcCredentials_((err, credentials) => { + if (err) { + callback!(err); + return; + } + + this.grpcCredentials = credentials; + this.request(protoOpts, reqOpts, callback!); + }); + + return; + } + + const service = this.getService_(protoOpts); + const metadata = this.grpcMetadata; + const grpcOpts: GrpcOptions = {}; + + if (typeof protoOpts.timeout === 'number') { + grpcOpts.deadline = GrpcService.createDeadline_(protoOpts.timeout); + } + + try { + reqOpts = this.decorateRequest_(reqOpts); + } catch (e) { + callback!(e as Error); + return; + } + + // Retains a reference to an error from the response. If the final callback + // is executed with this as the "response", we return it to the user as an + // error. + let respError; + + const retryOpts = Object.assign( + { + retries: this.maxRetries, + currentRetryAttempt: 0, + shouldRetryFn: GrpcService.shouldRetryRequest_, + + // retry-request determines if it should retry from the incoming HTTP + // response status. gRPC always returns an error proto message. We + // pass that "error" into retry-request to act as the HTTP response, + // so it can use the status code to determine if it should retry. + request(_, onResponse) { + respError = null; + return service[protoOpts.method]( + reqOpts, + metadata, + grpcOpts, + (err, resp) => { + if (err) { + respError = GrpcService.decorateError_(err); + + if (respError) { + onResponse(null, respError); + return; + } + onResponse(err, resp); + return; + } + + onResponse(null, resp); + }, + ); + }, + }, + protoOpts.retryOpts, + ); + + return retryRequest(null!, retryOpts, (err, resp: object) => { + if (!err && resp === respError) { + err = respError; + resp = null!; + } + callback!(err, resp as Response); + }); + } + + /** + * Make an authenticated streaming request with gRPC. + * + * @param {object} protoOpts - The proto options. + * @param {string} protoOpts.service - The service. + * @param {string} protoOpts.method - The method name. + * @param {number=} protoOpts.timeout - After how many milliseconds should the + * request cancel. + * @param {object} reqOpts - The request options. + */ + requestStream(reqOpts: DecorateRequestOptions): Request; + requestStream(protoOpts: ProtoOpts, reqOpts: DecorateRequestOptions): Duplex; + requestStream( + pOpts: ProtoOpts | DecorateRequestOptions, + rOpts?: DecorateRequestOptions, + ): Duplex | Request { + /** + * The function signature above is a little funky. This is due to the way + * method overloading in TypeScript operates. Since this class extends + * Service, the signatures for `requestStream` need to have + * *something* in common. The only signature actually used here is: + * + * requestStream(protoOpts: ProtoOpts, reqOpts: DecorateRequestOptions): + * Duplex; + * + * Hence the weird casting below. + */ + if (global['GCLOUD_SANDBOX_ENV']) { + return new PassThrough({objectMode: true}); + } + const protoOpts = pOpts as ProtoOpts; + let reqOpts = rOpts as DecorateRequestOptions; + + if (!protoOpts.stream) { + protoOpts.stream = new PassThrough({objectMode: true}); + } + + const stream = protoOpts.stream; + + if (!this.grpcCredentials) { + // We must establish an authClient to give to grpc. + this.getGrpcCredentials_((err, credentials) => { + if (err) { + stream.destroy(err); + return; + } + this.grpcCredentials = credentials; + this.requestStream(protoOpts, reqOpts); + }); + return stream; + } + + const objectMode = !!reqOpts.objectMode; + const service = this.getService_(protoOpts); + const grpcMetadata = this.grpcMetadata; + const grpcOpts: GrpcOptions = {}; + + if (typeof protoOpts.timeout === 'number') { + grpcOpts.deadline = GrpcService.createDeadline_(protoOpts.timeout); + } + + try { + reqOpts = this.decorateRequest_(reqOpts); + } catch (e) { + setImmediate(() => { + stream.destroy(e as Error); + }); + return stream; + } + + const retryOpts = Object.assign( + { + retries: this.maxRetries, + currentRetryAttempt: 0, + objectMode, + shouldRetryFn: GrpcService.shouldRetryRequest_, + + request() { + const ee: EventEmitter = service[protoOpts.method]( + reqOpts, + grpcMetadata, + grpcOpts, + ).on('metadata', () => { + // retry-request requires a server response before it + // starts emitting data. The closest mechanism grpc + // provides is a metadata event, but this does not provide + // any kind of response status. So we're faking it here + // with code `0` which translates to HTTP 200. + // + // https://github.com/GoogleCloudPlatform/google-cloud-node/pull/1444#discussion_r71812636 + const grcpStatus = GrpcService.decorateStatus_({code: 0}); + ee.emit('response', grcpStatus); + }); + return ee; + }, + }, + protoOpts.retryOpts, + ); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return (retryRequest(null!, retryOpts) as any) + .on('error', err => { + const grpcError = GrpcService.decorateError_(err); + stream.destroy(grpcError || err); + }) + .on('request', stream.emit.bind(stream, 'request')) + .pipe(stream); + } + + /** + * Make an authenticated writable streaming request with gRPC. + * + * @param {object} protoOpts - The proto options. + * @param {string} protoOpts.service - The service. + * @param {string} protoOpts.method - The method name. + * @param {number=} protoOpts.timeout - After how many milliseconds should the + * request cancel. + * @param {object} reqOpts - The request options. + */ + requestWritableStream(protoOpts, reqOpts) { + const stream = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (protoOpts.stream = protoOpts.stream || (duplexify as any).obj()); + + if (global['GCLOUD_SANDBOX_ENV']) { + return stream; + } + + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + + if (!this.grpcCredentials) { + // We must establish an authClient to give to grpc. + this.getGrpcCredentials_((err, credentials) => { + if (err) { + stream.destroy(err); + return; + } + + self.grpcCredentials = credentials; + self.requestWritableStream(protoOpts, reqOpts); + }); + + return stream; + } + + const service = this.getService_(protoOpts); + const grpcMetadata = this.grpcMetadata; + const grpcOpts: GrpcOptions = {}; + + if (isNumber(protoOpts.timeout)) { + grpcOpts.deadline = GrpcService.createDeadline_(protoOpts.timeout); + } + + try { + reqOpts = this.decorateRequest_(reqOpts); + } catch (e) { + setImmediate(() => { + stream.destroy(e); + }); + return stream; + } + + const grpcStream = service[protoOpts.method]( + reqOpts, + grpcMetadata, + grpcOpts, + ) + .on('status', status => { + const grcpStatus = GrpcService.decorateStatus_(status); + stream.emit('response', grcpStatus || status); + }) + .on('error', err => { + const grpcError = GrpcService.decorateError_(err); + stream.destroy(grpcError || err); + }); + + stream.setReadable(grpcStream); + stream.setWritable(grpcStream); + + return stream; + } + + /** + * Decode a protobuf Struct's value. + * + * @param {object} value - A Struct's Field message. + * @return {*} - The decoded value. + */ + static decodeValue_(value) { + switch (value.kind) { + case 'structValue': { + return GrpcService.structToObj_(value.structValue); + } + + case 'nullValue': { + return null; + } + + case 'listValue': { + return value.listValue.values.map(GrpcService.decodeValue_); + } + + default: { + return value[value.kind]; + } + } + } + + /** + * Convert a raw value to a type-denoted protobuf message-friendly object. + * + * + * @param {*} value - The input value. + * @return {*} - The encoded value. + * + * @example + * ObjectToStructConverter.encodeValue('Hi'); + * // { + * // stringValue: 'Hello!' + * // } + */ + static encodeValue_(value) { + return new GrpcService.ObjectToStructConverter().encodeValue_(value); + } + + /** + * Creates a deadline. + * + * @private + * + * @param {number} timeout - Timeout in miliseconds. + * @return {date} deadline - The deadline in Date object form. + */ + private static createDeadline_(timeout: number) { + return new Date(Date.now() + timeout); + } + + /** + * Checks for a grpc status code and extends the error object with additional + * information. + * + * @private + * + * @param {error|object} err - The grpc error. + * @return {error|null} + */ + static decorateError_(err: Error): Error | null { + const errorObj = isError(err) ? err : {}; + return GrpcService.decorateGrpcResponse_(errorObj, err); + } + + /** + * Checks for a grpc status code and extends the supplied object with + * additional information. + * + * @private + * + * @param {object} obj - The object to be extended. + * @param {object} response - The grpc response. + * @return {object|null} + */ + private static decorateGrpcResponse_(obj, response) { + if (response && GRPC_ERROR_CODE_TO_HTTP[response.code]) { + const defaultResponseDetails = GRPC_ERROR_CODE_TO_HTTP[response.code]; + let message = defaultResponseDetails.message; + + if (response.message) { + // gRPC error messages can be either stringified JSON or strings. + try { + message = JSON.parse(response.message).description; + } catch (e) { + message = response.message; + } + } + + return extend(true, obj, response, { + code: defaultResponseDetails.code, + message, + }); + } + + return null; + } + + /** + * Checks for grpc status code and extends the status object with additional + * information + * + * @private + * @param {object} status - The grpc status. + * @return {object|null} + */ + private static decorateStatus_(status) { + return GrpcService.decorateGrpcResponse_({}, status); + } + + /** + * Function to decide whether or not a request retry could occur. + * + * @private + * + * @param {object} response - The request response. + * @return {boolean} shouldRetry + */ + private static shouldRetryRequest_(response) { + return [429, 500, 502, 503].indexOf(response.code) > -1; + } + + /** + * Convert an object to a struct. + * + * @private + * + * @param {object} obj - An object to convert. + * @param {object=} options - Configuration object. + * @param {boolean} options.removeCircular - Remove circular references in the + * object with a placeholder string. + * @param {boolean} options.stringify - Stringify un-recognized types. + * @return {array} - The converted object. + * + * @example + * GrpcService.objToStruct_({ + * greeting: 'Hello!', + * favNumber: 7, + * friendIds: [ + * 1004, + * 1006 + * ], + * userDetails: { + * termsSigned: true + * } + * }); + * // { + * // fields: { + * // greeting: { + * // stringValue: 'Hello!' + * // }, + * // favNumber: { + * // numberValue: 7 + * // }, + * // friendIds: { + * // listValue: [ + * // { + * // numberValue: 1004 + * // }, + * // { + * // numberValue: 1006 + * // } + * // ] + * // }, + * // userDetails: { + * // fields: { + * // termsSigned: { + * // booleanValue: true + * // } + * // } + * // } + * // } + * // } + */ + private static objToStruct_(obj, options) { + return new GrpcService.ObjectToStructConverter(options).convert(obj); + } + + /** + * Condense a protobuf Struct into an object of only its values. + * + * @private + * + * @param {object} struct - A protobuf Struct message. + * @return {object} - The simplified object. + * + * @example + * GrpcService.structToObj_({ + * fields: { + * name: { + * kind: 'stringValue', + * stringValue: 'Stephen' + * } + * } + * }); + * // { + * // name: 'Stephen' + * // } + */ + private static structToObj_(struct) { + const convertedObject = {}; + + for (const prop in struct.fields) { + const value = struct.fields[prop]; + convertedObject[prop] = GrpcService.decodeValue_(value); + } + + return convertedObject; + } + + /** + * Assign a projectId if one is specified to all request options. + * + * @param {object} reqOpts - The request options. + * @return {object} - The decorated request object. + */ + decorateRequest_(reqOpts) { + reqOpts = Object.assign({}, reqOpts); + + delete reqOpts.autoPaginate; + delete reqOpts.autoPaginateVal; + delete reqOpts.objectMode; + + return replaceProjectIdToken(reqOpts, this.projectId); + } + + /** + * To authorize requests through gRPC, we must get the raw google-auth-library + * auth client object. + * + * @private + * + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error getting an auth client. + */ + private getGrpcCredentials_(callback) { + this.authClient.getClient().then(client => { + const credentials = this.grpc!.credentials.combineChannelCredentials( + this.grpc!.credentials.createSsl(), + grpc.credentials.createFromGoogleCredential({ + // the `grpc` package does not support the `Headers` object yet + getRequestHeaders: async (url?: string | URL) => { + const headers = await client.getRequestHeaders(url); + const genericHeadersObject: Record = {}; + + headers.forEach( + (value, key) => (genericHeadersObject[key] = value), + ); + + return genericHeadersObject; + }, + }), + ); + if (!this.projectId || this.projectId === '{{projectId}}') { + this.projectId = client.projectId!; + } + callback(null, credentials); + }, callback); + } + + /** + * Loads a proto file, useful when handling multiple proto files/services + * within a single instance of GrpcService. + * + * @private + * + * @param protoConfig - The proto specific configs for this file. + * @param config - The base config for the GrpcService. + * @return protoObject - The loaded proto object. + */ + private loadProtoFile( + protoPath: string, + config: GrpcServiceConfig, + ): PackageDefinition { + const protoObjectCacheKey = [config.protosDir, protoPath].join('$'); + + if (!GrpcService.protoObjectCache[protoObjectCacheKey]) { + const services = loadSync(protoPath, { + keepCase: false, + defaults: true, + bytes: String, + longs: String, + enums: String, + oneofs: true, + includeDirs: [config.protosDir, gaxProtoPath], + }); + GrpcService.protoObjectCache[protoObjectCacheKey] = services; + } + + return GrpcService.protoObjectCache[protoObjectCacheKey]; + } + + /** + * Retrieves the service object used to make the grpc requests. + * + * @private + * + * @param {object} protoOpts - The proto options. + * @return {object} service - The proto service. + */ + private getService_(protoOpts) { + const proto = this.protos[protoOpts.service]; + let service = this.activeServiceMap_.get(protoOpts.service); + + if (!service) { + service = new proto[protoOpts.service]( + proto.baseUrl || this.baseUrl, + this.grpcCredentials, + Object.assign( + { + 'grpc.primary_user_agent': this.userAgent, + }, + GRPC_SERVICE_OPTIONS, + ), + ); + + this.activeServiceMap_.set(protoOpts.service, service); + } + + return service; + } +} diff --git a/handwritten/spanner/src/common.ts b/handwritten/spanner/src/common.ts new file mode 100644 index 00000000000..81d13fdcf78 --- /dev/null +++ b/handwritten/spanner/src/common.ts @@ -0,0 +1,128 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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 {grpc, CallOptions, Operation as GaxOperation} from 'google-gax'; +import {google as instanceAdmin} from '../protos/protos'; +import {google as databaseAdmin} from '../protos/protos'; +import {Spanner} from '.'; + +export type IOperation = instanceAdmin.longrunning.IOperation; + +export type Schema = + | string + | string[] + | databaseAdmin.spanner.admin.database.v1.IUpdateDatabaseDdlRequest; + +export interface ResourceCallback { + ( + err: grpc.ServiceError | null, + resource?: Resource | null, + response?: Response, + ): void; +} +export type PagedResponse = [Item[], {} | null, Response]; + +export type RequestCallback = R extends void + ? NormalCallback + : PagedCallback; + +export interface NormalCallback { + (err: grpc.ServiceError | null, res?: TResponse | null): void; +} + +export interface PagedCallback { + ( + err: grpc.ServiceError | null, + results?: Item[] | null, + nextQuery?: {} | null, + response?: Response | null, + ): void; +} + +export interface LongRunningCallback { + ( + err: grpc.ServiceError | null, + resource?: Resource | null, + operation?: GaxOperation | null, + apiResponse?: IOperation, + ): void; +} + +export interface PagedOptions { + pageSize?: number; + pageToken?: string; + gaxOptions?: CallOptions; +} + +export interface PagedOptionsWithFilter extends PagedOptions { + filter?: string; +} + +/*! + * HTTP header for the resource prefix to improve routing + * by the backend. + */ +export const CLOUD_RESOURCE_HEADER = 'google-cloud-resource-prefix'; + +/*! + * HTTP header to route the requests at Leader + */ +export const LEADER_AWARE_ROUTING_HEADER = 'x-goog-spanner-route-to-leader'; + +/* + * END TO END TRACING header. + */ +export const END_TO_END_TRACING_HEADER = 'x-goog-spanner-end-to-end-tracing'; + +/* + * AFE SERVER TIMING header. + */ +export const AFE_SERVER_TIMING_HEADER = + 'x-goog-spanner-enable-afe-server-timing'; + +/** + * Add Leader aware routing header to existing header list. + * @param headers Existing header list. + */ +export function addLeaderAwareRoutingHeader(headers: {[k: string]: string}) { + headers[LEADER_AWARE_ROUTING_HEADER] = 'true'; +} + +/** + * Returns common headers to add. + * @param headers Common header list. + */ +export function getCommonHeaders( + resourceName: string, + enableTracing?: boolean, +) { + const headers: {[k: string]: string} = {}; + + if ( + process.env.SPANNER_ENABLE_END_TO_END_TRACING === 'true' || + enableTracing + ) { + headers[END_TO_END_TRACING_HEADER] = 'true'; + } + + if (Spanner.isAFEServerTimingEnabled()) { + headers[AFE_SERVER_TIMING_HEADER] = 'true'; + } + + headers[CLOUD_RESOURCE_HEADER] = resourceName; + + return headers; +} diff --git a/handwritten/spanner/src/database.ts b/handwritten/spanner/src/database.ts new file mode 100644 index 00000000000..2c8d2cdf295 --- /dev/null +++ b/handwritten/spanner/src/database.ts @@ -0,0 +1,4168 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 { + ApiError, + ExistsCallback, + GetConfig, + Metadata, + ServiceObjectConfig, +} from '@google-cloud/common'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common-grpc/service-object'); +import {promisify, promisifyAll, callbackifyAll} from '@google-cloud/promisify'; +import * as extend from 'extend'; +import * as r from 'teeny-request'; +import * as streamEvents from 'stream-events'; +import * as through from 'through2'; +import { + CallOptions, + GoogleError, + grpc, + Operation as GaxOperation, +} from 'google-gax'; +import {Backup} from './backup'; +import {BatchTransaction, TransactionIdentifier} from './batch-transaction'; +import {SessionFactory, SessionFactoryInterface} from './session-factory'; +import { + google as databaseAdmin, + google, + google as spannerClient, +} from '../protos/protos'; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import { + CreateDatabaseCallback, + CreateDatabaseOptions, + GetDatabaseOperationsOptions, + GetDatabaseOperationsResponse, + Instance, + GetDatabaseOperationsCallback, +} from './instance'; +import {PartialResultStream, Row} from './partial-result-stream'; +import {Session} from './session'; +import { + isSessionNotFoundError, + SessionPool, + SessionPoolCloseCallback, + SessionPoolInterface, + SessionPoolOptions, +} from './session-pool'; +import {CreateTableCallback, CreateTableResponse, Table} from './table'; +import { + BatchWriteOptions, + CommitCallback, + CommitResponse, + ExecuteSqlRequest, + MutationGroup, + MutationSet, + RunCallback, + RunResponse, + RunUpdateCallback, + Snapshot, + TimestampBounds, + Transaction, +} from './transaction'; +import { + AsyncRunTransactionCallback, + AsyncTransactionRunner, + RunTransactionCallback, + RunTransactionOptions, + TransactionRunner, +} from './transaction-runner'; +import { + IOperation, + LongRunningCallback, + NormalCallback, + PagedOptionsWithFilter, + PagedResponse, + RequestCallback, + ResourceCallback, + Schema, + addLeaderAwareRoutingHeader, + getCommonHeaders, +} from './common'; +import {finished, Duplex, Readable, Transform} from 'stream'; +import {PreciseDate} from '@google-cloud/precise-date'; +import {EnumKey, RequestConfig, TranslateEnumKeys, Spanner} from '.'; +import {toArray} from './helper'; +import {ServiceError} from 'google-gax'; +import IPolicy = google.iam.v1.IPolicy; +import Policy = google.iam.v1.Policy; +import FieldMask = google.protobuf.FieldMask; +import IDatabase = google.spanner.admin.database.v1.IDatabase; +import snakeCase = require('lodash.snakecase'); +import { + ObservabilityOptions, + Span, + getActiveOrNoopSpan, + startTrace, + setSpanError, + setSpanErrorAndException, + traceConfig, +} from './instrument'; +import { + AtomicCounter, + X_GOOG_SPANNER_REQUEST_ID_HEADER, + craftRequestId, + newAtomicCounter, +} from './request_id_header'; + +export type GetDatabaseRolesCallback = RequestCallback< + IDatabaseRole, + databaseAdmin.spanner.admin.database.v1.IListDatabaseRolesResponse +>; +export type GetDatabaseRolesResponse = PagedResponse< + IDatabaseRole, + databaseAdmin.spanner.admin.database.v1.IListDatabaseRolesResponse +>; +type SetDatabaseMetadataCallback = ResourceCallback; +type SetDatabaseMetadataResponse = [GaxOperation, IOperation]; +type IDatabaseRole = databaseAdmin.spanner.admin.database.v1.IDatabaseRole; + +type CreateBatchTransactionCallback = ResourceCallback< + BatchTransaction, + google.spanner.v1.ITransaction | google.spanner.v1.ISession +>; + +type CreateBatchTransactionResponse = [ + BatchTransaction, + google.spanner.v1.ITransaction | google.spanner.v1.ISession, +]; +type DatabaseResponse = [Database, r.Response]; +type DatabaseCallback = ResourceCallback; + +type GetSnapshotCallback = NormalCallback; + +type GetTransactionCallback = NormalCallback; + +export interface SessionPoolConstructor { + new ( + database: Database, + options?: SessionPoolOptions | null, + ): SessionPoolInterface; +} + +export type GetDatabaseDialectCallback = NormalCallback< + EnumKey +>; + +export interface SetIamPolicyRequest { + policy: Policy | null; + updateMask?: FieldMask | null; +} + +export interface RunPartitionedUpdateOptions extends ExecuteSqlRequest { + excludeTxnFromChangeStreams?: boolean; +} + +export type UpdateSchemaCallback = ResourceCallback< + GaxOperation, + databaseAdmin.longrunning.IOperation +>; + +export type UpdateSchemaResponse = [ + GaxOperation, + databaseAdmin.longrunning.IOperation, +]; + +type PoolRequestCallback = RequestCallback; + +type ResultSetStats = spannerClient.spanner.v1.ResultSetStats; +type ResultSetMetadata = spannerClient.spanner.v1.ResultSetMetadata; + +export type GetSessionsOptions = PagedOptionsWithFilter; +export type GetDatabaseRolesOptions = PagedOptionsWithFilter; + +/** + * IDatabase structure with database state enum translated to string form. + */ +type IDatabaseTranslatedEnum = Omit< + TranslateEnumKeys< + databaseAdmin.spanner.admin.database.v1.IDatabase, + 'state', + typeof databaseAdmin.spanner.admin.database.v1.Database.State + >, + 'restoreInfo' +> & + Omit< + TranslateEnumKeys< + databaseAdmin.spanner.admin.database.v1.IDatabase, + 'databaseDialect', + typeof databaseAdmin.spanner.admin.database.v1.DatabaseDialect + >, + 'restoreInfo' + > & {restoreInfo?: IRestoreInfoTranslatedEnum | null}; + +/** + * IRestoreInfo structure with restore source type enum translated to string form. + */ +type IRestoreInfoTranslatedEnum = TranslateEnumKeys< + databaseAdmin.spanner.admin.database.v1.IRestoreInfo, + 'sourceType', + typeof databaseAdmin.spanner.admin.database.v1.RestoreSourceType +>; + +type GetDatabaseMetadataResponse = [IDatabaseTranslatedEnum]; +type GetDatabaseMetadataCallback = RequestCallback; + +type GetSchemaCallback = RequestCallback< + string, + databaseAdmin.spanner.admin.database.v1.IGetDatabaseDdlResponse +>; +type GetSchemaResponse = [ + string[], + databaseAdmin.spanner.admin.database.v1.IGetDatabaseDdlResponse, +]; +type GetIamPolicyResponse = IPolicy; +type GetIamPolicyCallback = RequestCallback; +type SetIamPolicyResponse = IPolicy; +type SetIamPolicyCallback = RequestCallback; +type GetSessionsCallback = RequestCallback< + Session, + google.spanner.v1.IListSessionsResponse +>; + +type GetSessionsResponse = PagedResponse< + Session, + google.spanner.v1.IListSessionsResponse +>; + +export type GetDatabaseConfig = GetConfig & + databaseAdmin.spanner.admin.database.v1.IGetDatabaseRequest & { + gaxOptions?: CallOptions; + }; +type DatabaseCloseResponse = [google.protobuf.IEmpty]; + +export type CreateSessionResponse = [ + Session, + spannerClient.spanner.v1.ISession, +]; + +export interface CreateSessionOptions { + labels?: {[k: string]: string} | null; + databaseRole?: string | null; + gaxOptions?: CallOptions; + multiplexed?: boolean; +} + +export interface GetIamPolicyOptions { + requestedPolicyVersion?: number | null; + gaxOptions?: CallOptions; +} + +/** + * @typedef {object} GetTransactionOptions + */ +export type GetTransactionOptions = Omit; + +export type CreateSessionCallback = ResourceCallback< + Session, + spannerClient.spanner.v1.ISession +>; + +export interface BatchCreateSessionsOptions extends CreateSessionOptions { + count: number; +} + +export type BatchCreateSessionsResponse = [ + Session[], + spannerClient.spanner.v1.IBatchCreateSessionsResponse, +]; + +export type BatchCreateSessionsCallback = ResourceCallback< + Session[], + spannerClient.spanner.v1.IBatchCreateSessionsResponse +>; + +export type DatabaseDeleteResponse = [databaseAdmin.protobuf.IEmpty]; +export type DatabaseDeleteCallback = + NormalCallback; + +export interface CancelableDuplex extends Duplex { + cancel(): void; +} + +export type RestoreDatabaseCallback = LongRunningCallback; + +export type RestoreDatabaseResponse = [ + Database, + GaxOperation, + databaseAdmin.longrunning.IOperation, +]; + +export type GetRestoreInfoCallback = NormalCallback; +export type GetStateCallback = NormalCallback< + EnumKey +>; + +interface DatabaseRequest { + ( + config: RequestConfig, + callback: ResourceCallback, + ): void; + (config: RequestConfig, callback: RequestCallback): void; + (config: RequestConfig, callback: RequestCallback): void; +} + +export interface RestoreOptions { + encryptionConfig?: databaseAdmin.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig; + gaxOptions?: CallOptions; +} + +export interface WriteAtLeastOnceOptions extends CallOptions { + readLockMode?: ReadLockMode; + isolationLevel?: IsolationLevel; +} + +/** + * Create a Database object to interact with a Cloud Spanner database. + * + * @class + * + * @param {string} name Name of the database. + * @param {SessionPoolOptions|SessionPoolInterface} options Session pool + * configuration options or custom pool interface. + * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} queryOptions + * The default query options to use for queries on the database. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * ``` + */ +class Database extends common.GrpcServiceObject { + private instance: Instance; + formattedName_: string; + pool_: SessionPoolInterface; + sessionFactory_: SessionFactoryInterface; + queryOptions_?: spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions; + isMuxEnabledForRW_?: boolean; + commonHeaders_: {[k: string]: string}; + request: DatabaseRequest; + databaseRole?: string | null; + labels?: {[k: string]: string} | null; + databaseDialect?: EnumKey< + typeof databaseAdmin.spanner.admin.database.v1.DatabaseDialect + > | null; + _observabilityOptions?: ObservabilityOptions; // TODO: exmaine if we can remove it + private _traceConfig: traceConfig; + private _nthRequest: AtomicCounter; + public _clientId: number; + constructor( + instance: Instance, + name: string, + poolOptions?: SessionPoolConstructor | SessionPoolOptions, + queryOptions?: spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions, + databaseRole?: string | null, + ) { + const methods = { + /** + * Create a database. + * + * @method Database#create + * @param {CreateDatabaseRequest} [options] Configuration object. + * @param {CreateDatabaseCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.create(function(err, database, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Database created successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.create() + * .then(function(data) { + * const operation = data[0]; + * const apiResponse = data[1]; + * + * return operation.promise(); + * }) + * .then(function() { + * // Database created successfully. + * }); + * ``` + */ + create: true, + }; + + const formattedName_ = Database.formatName_(instance.formattedName_, name); + + super({ + parent: instance, + id: name, + methods, + createMethod: ( + _: {}, + options: CreateDatabaseOptions, + callback: CreateDatabaseCallback, + ) => { + const pool = this.pool_ as SessionPool; + if (pool._pending > 0) { + // If there are BatchCreateSessions requests pending, then we should + // wait until these have finished before we try to create the database. + // Otherwise the results of these requests might be propagated to + // client requests that are submitted after the database has been + // created. If the pending requests have not finished within 10 seconds, + // they will be ignored and the database creation will proceed. + let timeout; + const promises = [ + new Promise( + resolve => (timeout = setTimeout(resolve, 10000)), + ), + new Promise(resolve => { + pool + .on('available', () => { + if (pool._pending === 0) { + clearTimeout(timeout); + resolve(); + } + }) + .on('createError', () => { + if (pool._pending === 0) { + clearTimeout(timeout); + resolve(); + } + }); + }), + ]; + Promise.race(promises) + .then(() => + instance.createDatabase(formattedName_, options, callback), + ) + .catch(() => {}); + } else { + return instance.createDatabase(formattedName_, options, callback); + } + }, + } as {} as ServiceObjectConfig); + + this.formattedName_ = formattedName_; + this.instance = instance; + + const poolOpts = typeof poolOptions === 'object' ? poolOptions : null; + this.databaseRole = databaseRole || poolOpts?.databaseRole || null; + this.labels = this._getSpanner().sessionLabels || poolOpts?.labels || null; + + this._observabilityOptions = instance._observabilityOptions; + this._traceConfig = { + opts: this._observabilityOptions, + dbName: this.formattedName_, + }; + + this.request = instance.request; + this._nthRequest = newAtomicCounter(0); + if (this.parent && this.parent.parent) { + this._clientId = (this.parent.parent as Spanner)._nthClientId; + } else { + this._clientId = instance._nthClientId; + } + this._observabilityOptions = instance._observabilityOptions; + this.commonHeaders_ = getCommonHeaders( + this.formattedName_, + this._observabilityOptions?.enableEndToEndTracing, + ); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.requestStream = instance.requestStream as any; + this.sessionFactory_ = new SessionFactory(this, name, poolOptions); + this.pool_ = this.sessionFactory_.getPool(); + this.isMuxEnabledForRW_ = this.sessionFactory_.isMultiplexedEnabledForRW(); + const sessionPoolInstance = this.pool_ as SessionPool; + if (sessionPoolInstance) { + sessionPoolInstance._observabilityOptions = + instance._observabilityOptions; + } + this.queryOptions_ = Object.assign( + Object.assign({}, queryOptions), + Database.getEnvironmentQueryOptions(), + ); + } + + _nextNthRequest(): number { + return this._nthRequest.increment(); + } + + /** + * @typedef {array} SetDatabaseMetadataResponse + * @property {object} 0 The {@link Database} metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback SetDatabaseMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The {@link Database} metadata. + * @param {object} apiResponse The full API response. + */ + /** + * Update the metadata for this database. Note that this method follows PATCH + * semantics, so previously-configured settings will persist. + * + * Wrapper around {@link v1.DatabaseAdminClient#updateDatabase}. + * + * @see {@link v1.DatabaseAdminClient#updateDatabase} + * @see [UpdateDatabase API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase) + * + * @param {object} metadata The metadata you wish to set. + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {SetDatabaseMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const metadata = { + * enableDropProtection: true + * }; + * + * database.setMetadata(metadata, function(err, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Metadata updated successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.setMetadata(metadata).then(function(data) { + * const operation = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + setMetadata( + metadata: IDatabase, + gaxOptions?: CallOptions, + ): Promise; + setMetadata(metadata: IDatabase, callback: SetDatabaseMetadataCallback): void; + setMetadata( + metadata: IDatabase, + gaxOptions: CallOptions, + callback: SetDatabaseMetadataCallback, + ): void; + setMetadata( + metadata: IDatabase, + optionsOrCallback?: CallOptions | SetDatabaseMetadataCallback, + cb?: SetDatabaseMetadataCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts = { + database: extend( + { + name: this.formattedName_, + }, + metadata, + ), + updateMask: { + paths: Object.keys(metadata).map(snakeCase), + }, + }; + return this.request( + { + client: 'DatabaseAdminClient', + method: 'updateDatabase', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + callback!, + ); + } + + static getEnvironmentQueryOptions() { + const options = + {} as spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions; + if (process.env.SPANNER_OPTIMIZER_VERSION) { + options.optimizerVersion = process.env.SPANNER_OPTIMIZER_VERSION; + } + if (process.env.SPANNER_OPTIMIZER_STATISTICS_PACKAGE) { + options.optimizerStatisticsPackage = + process.env.SPANNER_OPTIMIZER_STATISTICS_PACKAGE; + } + return options; + } + + /** + * @typedef {object} BatchCreateSessionsOptions + * @property {number} count The number of sessions to create. + * @property {object.} [labels] Labels to apply to each + * session. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} BatchCreateSessionsResponse + * @property {Session[]} 0 The newly created sessions. + * @property {object} 1 The full API response. + */ + /** + * @callback BatchCreateSessionsCallback + * @param {?Error} err Request error, if any. + * @param {Session[]} sessions The newly created sessions. + * @param {object} apiResponse The full API response. + */ + /** + * Create a batch of sessions, which can be used to perform transactions that + * read and/or modify data. + * + * **It is unlikely you will need to interact with sessions directly. By + * default, sessions are created and utilized for maximum performance + * automatically.** + * + * Wrapper around {@link v1.SpannerClient#batchCreateSessions}. + * + * @see {@link v1.SpannerClient#batchCreateSessions} + * @see [BatchCreateSessions API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.BatchCreateSessions) + * + * @param {number|BatchCreateSessionsOptions} options Desired session count or + * a configuration object. + * @param {BatchCreateSessionsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const count = 5; + * + * database.batchCreateSession(count, (err, sessions, response) => { + * if (err) { + * // Error handling omitted. + * } + * + * // `sessions` is an array of Session objects. + * }); + * + * ``` + * @example If the callback is omitted, we'll return a Promise. + * ``` + * const [sessions, response] = await database.batchCreateSessions(count); + * ``` + */ + batchCreateSessions( + options: number | BatchCreateSessionsOptions, + ): Promise; + batchCreateSessions( + options: number | BatchCreateSessionsOptions, + callback: BatchCreateSessionsCallback, + ): void; + batchCreateSessions( + options: number | BatchCreateSessionsOptions, + callback?: BatchCreateSessionsCallback, + ): void | Promise { + if (typeof options === 'number') { + options = {count: options}; + } + + const count = options.count; + const labels = options.labels || this.labels || null; + const databaseRole = options.databaseRole || this.databaseRole || null; + + const reqOpts: google.spanner.v1.IBatchCreateSessionsRequest = { + database: this.formattedName_, + sessionTemplate: {labels: labels, creatorRole: databaseRole}, + sessionCount: count, + }; + + const headers = this.commonHeaders_; + if (this._getSpanner().routeToLeaderEnabled) { + addLeaderAwareRoutingHeader(headers); + } + + const allHeaders = this._metadataWithRequestId( + this._nextNthRequest(), + 1, + headers, + ); + + startTrace('Database.batchCreateSessions', this._traceConfig, span => { + this.request( + { + client: 'SpannerClient', + method: 'batchCreateSessions', + reqOpts, + gaxOpts: options.gaxOptions, + headers: allHeaders, + }, + (err, resp) => { + if (err) { + setSpanError(span, err); + span.end(); + callback!(err, null, resp!); + return; + } + + const sessions = (resp!.session || []).map(metadata => { + const session = this.session(metadata.name!); + session._observabilityOptions = this._traceConfig!.opts; + session.metadata = metadata; + return session; + }); + + span.end(); + callback!(null, sessions, resp!); + }, + ); + }); + } + + public _metadataWithRequestId( + nthRequest: number, + attempt: number, + priorMetadata?: {[k: string]: string}, + ): {[k: string]: string} { + if (!priorMetadata) { + priorMetadata = {}; + } + const withReqId = { + ...priorMetadata, + }; + withReqId[X_GOOG_SPANNER_REQUEST_ID_HEADER] = craftRequestId( + this._clientId || 1, + 1, // TODO: Properly infer the channelId + nthRequest, + attempt, + ); + return withReqId; + } + + /** + * Get a reference to a {@link BatchTransaction} object. + * + * @see {@link BatchTransaction#identifier} to generate an identifier. + * + * @param {TransactionIdentifier} identifier The transaction identifier. + * @param {object} [options] [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds). + * @returns {BatchTransaction} A batch transaction object. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const transaction = database.batchTransaction({ + * session: 'my-session', + * transaction: 'my-transaction', + * readTimestamp: 1518464696657 + * }); + * ``` + */ + batchTransaction( + identifier: TransactionIdentifier, + options?: TimestampBounds, + ): BatchTransaction { + const session = + typeof identifier.session === 'string' + ? this.session(identifier.session) + : identifier.session; + const id = identifier.transaction; + const transaction = new BatchTransaction(session, options); + transaction.id = id; + transaction._observabilityOptions = this._traceConfig!.opts; + transaction.readTimestamp = identifier.timestamp as PreciseDate; + return transaction; + } + /** + * @callback CloseDatabaseCallback + * @param {?Error} err Request error, if any. + */ + /** + * Close the database connection and destroy all sessions associated with it. + * + * @param {CloseDatabaseCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.close(function(err) { + * if (err) { + * // Error handling omitted. + * } + * }); + * + * //- + * // In the event of a session leak, the error object will contain a + * // `messages` field. + * //- + * database.close(function(err) { + * if (err && err.messages) { + * err.messages.forEach(function(message) { + * console.error(message); + * }); + * } + * }); + * ``` + */ + close(callback: SessionPoolCloseCallback): void; + close(): Promise; + close( + callback?: SessionPoolCloseCallback, + ): void | Promise { + const key = this.id!.split('/').pop(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this.parent as any).databases_.delete(key); + this.pool_.close(callback!); + } + /** + * @typedef {array} CreateTransactionResponse + * @property {BatchTransaction} 0 The {@link BatchTransaction}. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateTransactionCallback + * @param {?Error} err Request error, if any. + * @param {BatchTransaction} transaction The {@link BatchTransaction}. + * @param {object} apiResponse The full API response. + */ + /** + * Create a transaction that can be used for batch querying. + * + * @param {object} [options] [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds). + * @param {CreateTransactionCallback} [callback] Callback function. + * @returns {Promise} + */ + createBatchTransaction( + options?: TimestampBounds, + ): Promise; + createBatchTransaction(callback: CreateBatchTransactionCallback): void; + createBatchTransaction( + options: TimestampBounds, + callback: CreateBatchTransactionCallback, + ): void; + createBatchTransaction( + optionsOrCallback?: TimestampBounds | CreateBatchTransactionCallback, + cb?: CreateBatchTransactionCallback, + ): void | Promise { + const callback = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as CreateBatchTransactionCallback) + : cb; + const options = + typeof optionsOrCallback === 'object' + ? (optionsOrCallback as TimestampBounds) + : {}; + return startTrace( + 'Database.createBatchTransaction', + this._traceConfig, + span => { + this.sessionFactory_.getSession((err, session) => { + if (err) { + setSpanError(span, err); + span.end(); + callback!(err as ServiceError, null, undefined); + return; + } + const transaction = this.batchTransaction( + {session: session!}, + options, + ); + this._releaseOnEnd(session!, transaction, span); + transaction.begin((err, resp) => { + if (err) { + setSpanError(span, err); + if (isSessionNotFoundError(err)) { + span.addEvent('No session available', { + 'session.id': session?.id, + }); + } + span.end(); + callback!(err, null, resp!); + return; + } + span.addEvent('Using Session', {'session.id': session?.id}); + span.end(); + callback!(null, transaction, resp!); + }); + }); + }, + ); + } + /** + * Create a new session. + * + * @typedef {object} CreateSessionOptions + * @property {Object.} [labels] The labels for the session. + * + * * Label keys must be between 1 and 63 characters long and must conform to + * the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`. + * * Label values must be between 0 and 63 characters long and must conform + * to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`. + * * No more than 64 labels can be associated with a given session. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} CreateSessionResponse + * @property {Session} 0 The newly created session. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateSessionCallback + * @param {?Error} err Request error, if any. + * @param {Session} session The newly created session. + * @param {object} apiResponse The full API response. + */ + /** + * Create a new session, which can be used to perform transactions that read + * and/or modify data. + * + * Sessions can only execute one transaction at a time. To execute multiple + * concurrent read-write/write-only transactions, create multiple sessions. + * Note that standalone reads and queries use a transaction internally, and + * count toward the one transaction limit. + * + * **It is unlikely you will need to interact with sessions directly. By + * default, sessions are created and utilized for maximum performance + * automatically.** + * + * Wrapper around {@link v1.SpannerClient#createSession}. + * + * @see {@link v1.SpannerClient#createSession} + * @see [CreateSession API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.CreateSession) + * + * @param {CreateSessionOptions} [options] Configuration object. + * @param {CreateSessionCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.createSession(function(err, session, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // `session` is a Session object. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.createSession().then(function(data) { + * const session = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + createSession(options: CreateSessionOptions): Promise; + createSession(callback: CreateSessionCallback): void; + createSession( + options: CreateSessionOptions, + callback: CreateSessionCallback, + ): void; + createSession( + optionsOrCallback: CreateSessionOptions | CreateSessionCallback, + cb?: CreateSessionCallback, + ): void | Promise { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' && optionsOrCallback + ? extend({}, optionsOrCallback) + : ({} as CreateSessionOptions); + + const reqOpts: google.spanner.v1.ICreateSessionRequest = { + database: this.formattedName_, + }; + + reqOpts.session = {}; + + if (options.multiplexed) { + reqOpts.session.multiplexed = options.multiplexed; + } + + reqOpts.session.labels = options.labels || this.labels || null; + + reqOpts.session.creatorRole = + options.databaseRole || this.databaseRole || null; + + const headers = this._metadataWithRequestId( + this._nextNthRequest(), + 1, + this.commonHeaders_, + ); + if (this._getSpanner().routeToLeaderEnabled) { + addLeaderAwareRoutingHeader(headers); + } + + startTrace('Database.createSession', this._traceConfig, span => { + this.request( + { + client: 'SpannerClient', + method: 'createSession', + reqOpts, + gaxOpts: options.gaxOptions, + headers: headers, + }, + (err, resp) => { + if (err) { + setSpanError(span, err); + span.end(); + callback(err, null, resp!); + return; + } + const session = this.session(resp!.name!); + session.metadata = resp; + session._observabilityOptions = this._traceConfig!.opts; + span.end(); + callback(null, session, resp!); + }, + ); + }); + } + /** + * @typedef {array} CreateTableResponse + * @property {Table} 0 The new {@link Table}. + * @property {google.longrunning.Operation} 1 An {@link Operation} object that can be used to check + * the status of the request. + * @property {object} 2 The full API response. + */ + /** + * @callback CreateTableCallback + * @param {?Error} err Request error, if any. + * @param {Table} table The new {@link Table}. + * @param {google.longrunning.Operation} operation An {@link Operation} object that can be used to + * check the status of the request. + * @param {object} apiResponse The full API response. + */ + /** + * Create a table. + * + * Wrapper around {@link Database#updateSchema}. + * + * @see {@link Database#updateSchema} + * + * @param {string} schema A DDL CREATE statement describing the table. + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {CreateTableCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const schema = + * 'CREATE TABLE Singers (' + + * ' SingerId INT64 NOT NULL,' + + * ' FirstName STRING(1024),' + + * ' LastName STRING(1024),' + + * ' SingerInfo BYTES(MAX),' + + * ') PRIMARY KEY(SingerId)'; + * + * database.createTable(schema, function(err, table, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Table created successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.createTable(schema) + * .then(function(data) { + * const table = data[0]; + * const operation = data[1]; + * + * return operation.promise(); + * }) + * .then(function() { + * // Table created successfully. + * }); + * ``` + */ + createTable( + schema: Schema, + gaxOptions?: CallOptions, + ): Promise; + createTable(schema: Schema, callback: CreateTableCallback): void; + createTable( + schema: Schema, + gaxOptions: CallOptions, + callback: CreateTableCallback, + ): void; + createTable( + schema: Schema, + gaxOptionsOrCallback?: CallOptions | CreateTableCallback, + cb?: CreateTableCallback, + ): void | Promise { + const gaxOptions = + typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; + const callback = + typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; + + this.updateSchema(schema, gaxOptions, (err, operation, resp) => { + if (err) { + callback!(err, null, null, resp!); + return; + } + const tableName = (schema as string).match( + /CREATE TABLE `*([^\s`(]+)/, + )![1]; + const table = this.table(tableName!); + table._observabilityOptions = this._traceConfig!.opts; + callback!(null, table, operation!, resp!); + }); + } + /** + * Decorates transaction so that when end() is called it will return the session + * back into the pool. + * + * @private + * + * @param {Session} session The session to release. + * @param {Transaction} transaction The transaction to observe. + * @returns {Transaction} + */ + private _releaseOnEnd(session: Session, transaction: Snapshot, span: Span) { + transaction.once('end', () => { + try { + this.sessionFactory_.release(session); + } catch (e) { + setSpanErrorAndException(span, e as Error); + this.emit('error', e); + } finally { + span.end(); + } + }); + } + /** + * @typedef {array} DatabaseDeleteResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DatabaseDeleteCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the database. + * + * Wrapper around {@link v1.DatabaseAdminClient#dropDatabase}. + * + * @see {@link v1.DatabaseAdminClient#dropDatabase} + * @see [DropDatabase API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DatabaseDeleteCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.delete(function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Database was deleted successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + delete(gaxOptions?: CallOptions): Promise; + delete(callback: DatabaseDeleteCallback): void; + delete(gaxOptions: CallOptions, callback: DatabaseDeleteCallback): void; + delete( + optionsOrCallback?: CallOptions | DatabaseDeleteCallback, + cb?: DatabaseDeleteCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts: databaseAdmin.spanner.admin.database.v1.IDropDatabaseRequest = + { + database: this.formattedName_, + }; + this.close(() => { + this.request( + { + client: 'DatabaseAdminClient', + method: 'dropDatabase', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + callback!, + ); + }); + } + /** + * @typedef {array} DatabaseExistsResponse + * @property {boolean} 0 Whether the {@link Database} exists. + */ + /** + * @callback DatabaseExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link Database} exists. + */ + /** + * Check if a database exists. + * + * @method Database#exists + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DatabaseExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists(gaxOptions?: CallOptions): Promise<[boolean]>; + exists(callback: ExistsCallback): void; + exists(gaxOptions: CallOptions, callback: ExistsCallback): void; + exists( + gaxOptionsOrCallback?: CallOptions | ExistsCallback, + cb?: ExistsCallback, + ): void | Promise<[boolean]> { + const gaxOptions = + typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; + const callback = + typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; + + const NOT_FOUND = 5; + + this.getMetadata(gaxOptions, err => { + if (err && (err as ApiError).code !== NOT_FOUND) { + callback!(err); + return; + } + const exists = !err || (err as ApiError).code !== NOT_FOUND; + callback!(null, exists); + }); + } + /** + * @typedef {array} GetDatabaseResponse + * @property {Database} 0 The {@link Database}. + * @property {object} 1 The full API response. + */ + /** + * @callback GetDatabaseCallback + * @param {?Error} err Request error, if any. + * @param {Database} database The {@link Database}. + * @param {object} apiResponse The full API response. + */ + /** + * Get a database if it exists. + * + * You may optionally use this to "get or create" an object by providing an + * object with `autoCreate` set to `true`. Any extra configuration that is + * normally required for the `create` method must be contained within this + * object as well. + * + * @param {options} [options] Configuration object. + * @param {boolean} [options.autoCreate=false] Automatically create the + * object if it does not exist. + * @param {object} [options.gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetDatabaseCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.get(function(err, database, apiResponse) { + * // `database.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.get().then(function(data) { + * const database = data[0]; + * const apiResponse = data[0]; + * }); + * ``` + */ + get(options?: GetDatabaseConfig): Promise; + get(callback: DatabaseCallback): void; + get(options: GetDatabaseConfig, callback: DatabaseCallback): void; + get( + optionsOrCallback?: GetDatabaseConfig | DatabaseCallback, + cb?: DatabaseCallback, + ): void | Promise { + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetDatabaseConfig); + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + this.getMetadata(options.gaxOptions!, (err, metadata) => { + if (err) { + if (options.autoCreate && (err as ApiError).code === 5) { + this.create( + options, + (err, database: Database, operation: GaxOperation) => { + if (err) { + callback!(err as grpc.ServiceError); + return; + } + operation + .on('error', callback!) + .on('complete', (metadata: Metadata) => { + this.metadata = metadata; + callback!(null, this, metadata as r.Response); + }); + }, + ); + return; + } + callback!(err); + return; + } + callback!(null, this, metadata as r.Response); + }); + } + /** + * @typedef {array} GetDatabaseMetadataResponse + * @property {object} 0 The {@link Database} metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetDatabaseMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The {@link Database} metadata. + * @param {object} apiResponse The full API response. + */ + /** + * Get the database's metadata. + * + * Wrapper around {@link v1.DatabaseAdminClient#getDatabase}. + * + * @see {@link v1.DatabaseAdminClient#getDatabase} + * @see [GetDatabase API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabase) + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetDatabaseMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.getMetadata(function(err, metadata) { + * if (err) { + * // Error handling omitted. + * } + * + * // Database was deleted successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + getMetadata(gaxOptions?: CallOptions): Promise; + getMetadata(callback: GetDatabaseMetadataCallback): void; + getMetadata( + gaxOptions: CallOptions, + callback: GetDatabaseMetadataCallback, + ): void; + getMetadata( + gaxOptionsOrCallback?: CallOptions | GetDatabaseMetadataCallback, + cb?: GetDatabaseMetadataCallback, + ): void | Promise { + const callback = + typeof gaxOptionsOrCallback === 'function' + ? (gaxOptionsOrCallback as GetDatabaseMetadataCallback) + : cb; + const gaxOpts = + typeof gaxOptionsOrCallback === 'object' + ? (gaxOptionsOrCallback as CallOptions) + : {}; + + const reqOpts: databaseAdmin.spanner.admin.database.v1.IGetDatabaseRequest = + { + name: this.formattedName_, + }; + return this.request( + { + client: 'DatabaseAdminClient', + method: 'getDatabase', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, resp) => { + if (resp) { + this.metadata = resp; + } + callback!(err, resp); + }, + ); + } + + /** + * {@link google.spanner.admin.database.v1#RestoreInfo} structure with restore + * source type enum translated to string form. + * + * @typedef {object} IRestoreInfoTranslatedEnum + */ + /** + * @callback GetRestoreInfoCallback + * @param {?Error} err Request error, if any. + * @param {IRestoreInfoTranslatedEnum | undefined} restoreInfo Contains the restore + * information for the database if it was restored from a backup. + */ + /** + * Retrieves the restore information of the database. + * + * @see {@link #getMetadata} + * + * @method Database#getRestoreInfo + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetRestoreInfoCallback} [callback] Callback function. + * @returns {Promise} When resolved, + * contains the restore information for the database if it was restored + * from a backup. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const restoreInfo = await database.getRestoreInfo(); + * console.log(`Database restored from ${restoreInfo.backupInfo.backup}`); + * ``` + */ + getRestoreInfo( + options?: CallOptions, + ): Promise; + getRestoreInfo(callback: GetRestoreInfoCallback): void; + getRestoreInfo(options: CallOptions, callback: GetRestoreInfoCallback): void; + async getRestoreInfo( + optionsOrCallback?: CallOptions | GetRestoreInfoCallback, + ): Promise { + const gaxOptions = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + + const [metadata] = await this.getMetadata(gaxOptions); + return metadata.restoreInfo ? metadata.restoreInfo : undefined; + } + + /** + * @callback GetStateCallback + * @param {?Error} err Request error, if any. + * @param {EnumKey | undefined} state + * Contains the current state of the database if the state is defined. + */ + /** + * Retrieves the state of the database. + * + * The database state indicates if the database is ready after creation or + * after being restored from a backup. + * + * @see {@link #getMetadata} + * + * @method Database#getState + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetStateCallback} [callback] Callback function. + * @returns {Promise | undefined>} + * When resolved, contains the current state of the database if the state + * is defined. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const state = await database.getState(); + * const isReady = (state === 'READY'); + * ``` + */ + getState( + options?: CallOptions, + ): Promise< + | EnumKey + | undefined + >; + getState(callback: GetStateCallback): void; + getState(options: CallOptions, callback: GetStateCallback): void; + async getState( + optionsOrCallback?: CallOptions | GetStateCallback, + ): Promise< + | EnumKey + | undefined + > { + const gaxOptions = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + + const [metadata] = await this.getMetadata(gaxOptions); + return metadata.state || undefined; + } + + /** + * Retrieves the dialect of the database + * + * @see {@link #getMetadata} + * + * @method Database#getDatabaseDialect + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetDatabaseDialectCallback} [callback] Callback function. + * @returns {Promise | undefined>} + * When resolved, contains the database dialect of the database if the dialect is defined. + * @example + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const dialect = await database.getDatabaseDialect(); + * const isGoogleSQL = (dialect === 'GOOGLE_STANDARD_SQL'); + * const isPostgreSQL = (dialect === 'POSTGRESQL'); + */ + + getDatabaseDialect( + options?: CallOptions, + ): Promise< + | EnumKey + | undefined + >; + getDatabaseDialect(callback: GetDatabaseDialectCallback): void; + getDatabaseDialect( + options: CallOptions, + callback: GetDatabaseDialectCallback, + ): void; + async getDatabaseDialect( + optionsOrCallback?: CallOptions | GetDatabaseDialectCallback, + callback?: GetDatabaseDialectCallback, + ): Promise< + | EnumKey + | undefined + > { + const gaxOptions = + typeof optionsOrCallback === 'object' + ? (optionsOrCallback as CallOptions) + : {}; + + const cb = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as GetDatabaseDialectCallback) + : callback; + + try { + if ( + this.databaseDialect === 'DATABASE_DIALECT_UNSPECIFIED' || + this.databaseDialect === null || + this.databaseDialect === undefined + ) { + const [metadata] = await this.getMetadata(gaxOptions); + this.databaseDialect = metadata.databaseDialect; + } + if (cb) { + cb(null, this.databaseDialect); + return; + } + return this.databaseDialect || undefined; + } catch (err) { + cb!(err as grpc.ServiceError); + return; + } + } + + /** + * @typedef {array} GetSchemaResponse + * @property {string[]} 0 An array of database DDL statements. + * @property {object} 1 The full API response. + */ + /** + * @callback GetSchemaCallback + * @param {?Error} err Request error, if any. + * @param {string[]} statements An array of database DDL statements. + * @param {object} apiResponse The full API response. + */ + /** + * Get this database's schema as a list of formatted DDL statements. + * + * Wrapper around {@link v1.DatabaseAdminClient#getDatabaseDdl}. + * + * @see {@link v1.DatabaseAdminClient#getDatabaseDdl} + * @see [Data Definition Language (DDL)](https://cloud.google.com/spanner/docs/data-definition-language) + * @see [GetDatabaseDdl API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetSchemaCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.getSchema(function(err, statements, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.getSchema().then(function(data) { + * const statements = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + getSchema(options?: CallOptions): Promise; + getSchema(callback: GetSchemaCallback): void; + getSchema(options: CallOptions, callback: GetSchemaCallback): void; + getSchema( + optionsOrCallback?: CallOptions | GetSchemaCallback, + cb?: GetSchemaCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts: databaseAdmin.spanner.admin.database.v1.IGetDatabaseDdlRequest = + { + database: this.formattedName_, + }; + this.request( + { + client: 'DatabaseAdminClient', + method: 'getDatabaseDdl', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (err, statements, ...args: any[]) => { + callback!(err, statements ? statements.statements : null, ...args); + }, + ); + } + + /** + * Options object for requested policy version. + * + * @typedef {object} GetIamPolicyOptions + * @property {number|null} [requestedPolicyVersion] policy version requested, possible values are 0, 1 and 3, + * See {@link https://cloud.google.com/iam/docs/policies#versions} for more details + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @callback GetIamPolicyCallback + * @param {?Error} err Request error, if any. + * @param {google.iam.v1.Policy| undefined} policy Returns policy for the give database + */ + /** + * Retrieves the policy of the database. + * + * A Policy is a collection of bindings. A binding binds one or more members, or principals, + * to a single role. Principals can be user accounts, service accounts, Google groups, and + * domains (such as G Suite). A role is a named list of permissions; each role can be an IAM + * predefined role or a user-created custom role. + * + * @see {@link #getIamPolicy} + * + * @method Database#getIamPolicy + * @param {object} [options] requestedPolicyVersion and gax options(configuration options) + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html} + * for more details on gax options. + * @param {GetIamPolicyCallback} [callback] Callback function. + * @returns {Promise} + * When resolved, contains the current policy of the database. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const policy = await database.getIamPolicy(); + * console.log(policy.bindings, policy.version, policy.etag, policy.auditConfigs) + * const policyWithVersion specified = await database.getIamPolicy({requestedPolicyVersion: 3}); + * ``` + */ + getIamPolicy(options?: GetIamPolicyOptions): Promise; + getIamPolicy(callback: GetIamPolicyCallback): void; + getIamPolicy( + options: GetIamPolicyOptions, + callback: GetIamPolicyCallback, + ): void; + getIamPolicy( + optionsOrCallback?: GetIamPolicyOptions | GetIamPolicyCallback, + cb?: GetIamPolicyCallback, + ): void | Promise { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts: databaseAdmin.iam.v1.IGetIamPolicyRequest = { + resource: this.formattedName_, + options: { + requestedPolicyVersion: options.requestedPolicyVersion || null, + }, + }; + this.request( + { + client: 'DatabaseAdminClient', + method: 'getIamPolicy', + reqOpts, + gaxOpts: options.gaxOptions, + headers: this.commonHeaders_, + }, + (err, resp) => { + callback!(err, resp); + }, + ); + } + + /** + * Options object for listing sessions. + * + * @typedef {object} GetSessionsOptions + * @property {string} [filter] An expression for filtering the results of the + * request. Filter rules are case insensitive. The fields eligible for + * filtering are: + * - **`name`** + * - **`display_name`** + * - **`labels.key`** where key is the name of a label + * + * Some examples of using filters are: + * - **`name:*`** The instance has a name. + * - **`name:Howl`** The instance's name is howl. + * - **`labels.env:*`** The instance has the label env. + * - **`labels.env:dev`** The instance's label env has the value dev. + * - **`name:howl labels.env:dev`** The instance's name is howl and it has + * the label env with value dev. + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} GetSessionsResponse + * @property {Session[]} 0 Array of {@link Session} instances. + * @property {object} 1 A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetSessionsCallback + * @param {?Error} err Request error, if any. + * @param {Session[]} instances Array of {@link Session} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Gets a list of sessions. + * + * Wrapper around {@link v1.SpannerClient#listSessions} + * + * @see {@link v1.SpannerClient#listSessions} + * @see [ListSessions API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ListSessions) + * + * @param {GetSessionsOptions} [options] Options object for listing sessions. + * @param {GetSessionsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.getSessions(function(err, sessions) { + * // `sessions` is an array of `Session` objects. + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * function callback(err, sessions, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * database.getSessions(nextQuery, callback); + * } + * } + * + * database.getInstances({ + * gaxOptions: {autoPaginate: false} + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.getInstances().then(function(data) { + * const sessions = data[0]; + * }); + * ``` + */ + getSessions(options?: GetSessionsOptions): Promise; + getSessions(callback: GetSessionsCallback): void; + getSessions(options: GetSessionsOptions, callback: GetSessionsCallback): void; + getSessions( + optionsOrCallback?: GetSessionsOptions | GetSessionsCallback, + cb?: GetSessionsCallback, + ): void | Promise { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetSessionsOptions); + const gaxOpts = extend(true, {}, options.gaxOptions); + let reqOpts = extend({}, options, { + database: this.formattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetSessionsOptions).pageSize, + pageToken: (gaxOpts as GetSessionsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetSessionsOptions).pageSize; + delete (gaxOpts as GetSessionsOptions).pageToken; + } + + const headers = this._metadataWithRequestId( + this._nextNthRequest(), + 1, + this.commonHeaders_, + ); + + return startTrace('Database.getSessions', this._traceConfig, span => { + this.request< + google.spanner.v1.ISession, + google.spanner.v1.IListSessionsResponse + >( + { + client: 'SpannerClient', + method: 'listSessions', + reqOpts, + gaxOpts, + headers: headers, + }, + (err, sessions, nextPageRequest, ...args) => { + if (err) { + setSpanError(span, err); + } + let sessionInstances: Session[] | null = null; + if (sessions) { + sessionInstances = sessions.map(metadata => { + const session = self.session(metadata.name!); + session.metadata = metadata; + session._observabilityOptions = this._traceConfig!.opts; + return session; + }); + } + span.end(); + const nextQuery = nextPageRequest! + ? extend({}, options, nextPageRequest!) + : null; + callback!(err, sessionInstances!, nextQuery, ...args); + }, + ); + }); + } + + /** + * Get a list of sessions as a readable object stream. + * + * Wrapper around {@link v1.SpannerClient#listSessions} + * + * @see {@link v1.SpannerClient#listSessions} + * @see [ListSessions API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ListSessions) + * + * @method Spanner#getSessionsStream + * @param {GetSessionsOptions} [options] Options object for listing sessions. + * @returns {ReadableStream} A readable stream that emits {@link Session} + * instances. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.getSessionsStream() + * .on('error', console.error) + * .on('data', function(database) { + * // `sessions` is a `Session` object. + * }) + * .on('end', function() { + * // All sessions retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * database.getSessionsStream() + * .on('data', function(session) { + * this.end(); + * }); + * ``` + */ + getSessionsStream(options: GetSessionsOptions = {}): NodeJS.ReadableStream { + const gaxOpts = extend(true, {}, options.gaxOptions); + + let reqOpts = extend({}, options, { + database: this.formattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetSessionsOptions).pageSize, + pageToken: (gaxOpts as GetSessionsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetSessionsOptions).pageSize; + delete (gaxOpts as GetSessionsOptions).pageToken; + } + + return this.requestStream({ + client: 'SpannerClient', + method: 'listSessionsStream', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }); + } + + /** + * @typedef {array} GetSnapshotResponse + * @property {Snapshot} 0 The snapshot object. + */ + /** + * @callback GetSnapshotCallback + * @param {?Error} err Request error, if any. + * @param {Snapshot} snapshot The snapshot object. + */ + /** + * Get a read only {@link Snapshot} transaction. + * + * Wrapper around {@link v1.SpannerClient#beginTransaction}. + * + * **NOTE:** When finished with the Snapshot, {@link Snapshot#end} should be + * called to release the underlying {@link Session}. **Failure to do could + * result in a Session leak.** + * + * **NOTE:** Since the returned {@link Snapshot} transaction is not a + * single-use transaction, it is invalid to set the `minReadTimestamp` and + * `maxStaleness` parameters in {@link TimestampBounds} as those parameters + * can only be set for single-use transactions. + * https://cloud.google.com/spanner/docs/reference/rest/v1/TransactionOptions#bounded-staleness + * + * @see {@link v1.SpannerClient#beginTransaction} + * + * @param {TimestampBounds} [options] Timestamp bounds. + * @param {GetSnapshotCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.getSnapshot(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Should be called when finished with Snapshot. + * transaction.end(); + * }); + * ``` + * + * @example If the callback is omitted, we'll return a Promise. + * ``` + * database.getSnapshot().then(function(data) { + * const transaction = data[0]; + * }); + * ``` + * + * @example include:samples/transaction.js + * region_tag:spanner_read_only_transaction + * Read-only transaction: + */ + getSnapshot(options?: TimestampBounds): Promise<[Snapshot]>; + getSnapshot(callback: GetSnapshotCallback): void; + getSnapshot(options: TimestampBounds, callback: GetSnapshotCallback): void; + getSnapshot( + optionsOrCallback?: TimestampBounds | GetSnapshotCallback, + cb?: GetSnapshotCallback, + ): void | Promise<[Snapshot]> { + const callback = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as GetSnapshotCallback) + : cb; + const options = + typeof optionsOrCallback === 'object' + ? (optionsOrCallback as TimestampBounds) + : {}; + + if ( + ('maxStaleness' in options && + options.maxStaleness !== null && + options.maxStaleness !== undefined) || + ('minReadTimestamp' in options && + options.minReadTimestamp !== null && + options.minReadTimestamp !== undefined) + ) { + const error = Object.assign( + new Error( + 'maxStaleness / minReadTimestamp is not supported for multi-use read-only transactions.', + ), + { + code: 3, // invalid argument + }, + ) as ServiceError; + callback!(error); + return; + } + + return startTrace('Database.getSnapshot', this._traceConfig, span => { + this.sessionFactory_.getSession((err, session) => { + if (err) { + setSpanError(span, err); + span.end(); + callback!(err as ServiceError); + return; + } + + const snapshot = session!.snapshot(options, this.queryOptions_); + + snapshot.begin(err => { + if (err) { + setSpanError(span, err); + if ( + isSessionNotFoundError(err) && + !this.sessionFactory_.isMultiplexedEnabled() + ) { + span.addEvent('No session available', { + 'session.id': session?.id, + }); + session!.lastError = err; + this.sessionFactory_.release(session!); + span.end(); + this.getSnapshot(options, callback!); + } else { + span.addEvent('Using Session', {'session.id': session?.id}); + this.sessionFactory_.release(session!); + span.end(); + callback!(err); + } + return; + } + + this._releaseOnEnd(session!, snapshot, span); + span.end(); + callback!(err, snapshot); + }); + }); + }); + } + /** + * @typedef {array} GetTransactionResponse + * @property {Transaction} 0 The transaction object. + */ + /** + * @callback GetTransactionCallback + * @param {?Error} err Request error, if any. + * @param {Transaction} transaction The transaction object. + */ + /** + * Get a read/write ready {@link Transaction} object. + * + * **NOTE:** In the event that you encounter an error while reading/writing, + * if you decide to forgo calling {@link Transaction#commit} or + * {@link Transaction#rollback}, then you need to call + * {@link Transaction#end} to release the underlying {@link Session} object. + * **Failure to do could result in a Session leak.** + * + * Wrapper around {@link v1.SpannerClient#beginTransaction}. + * + * @see {@link v1.SpannerClient#beginTransaction} + * + * @param {GetTransactionCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.getTransaction(function(err, transaction) {}); + * + * ``` + * @example If the callback is omitted, we'll return a Promise. + * ``` + * database.getTransaction().then(function(data) { + * const transaction = data[0]; + * }); + * ``` + */ + getTransaction( + optionsOrCallback?: GetTransactionOptions, + ): Promise<[Transaction]>; + getTransaction(callback: GetTransactionCallback): void; + getTransaction( + optionsOrCallback?: GetTransactionOptions | GetTransactionCallback, + callback?: GetTransactionCallback, + ): void | Promise<[Transaction]> { + const cb = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as GetTransactionCallback) + : callback; + const options = + typeof optionsOrCallback === 'object' && optionsOrCallback + ? (optionsOrCallback as GetTransactionOptions) + : {}; + + return startTrace( + 'Database.getTransaction', + { + ...this._traceConfig, + transactionTag: options.requestOptions?.transactionTag, + }, + span => { + this.sessionFactory_.getSessionForReadWrite( + (err, session, transaction) => { + if (!err) { + if (options.requestOptions) { + transaction!.requestOptions = Object.assign( + transaction!.requestOptions || {}, + options.requestOptions, + ); + } + transaction?.setReadWriteTransactionOptions( + options as RunTransactionOptions, + ); + span.addEvent('Using Session', {'session.id': session?.id}); + transaction!._observabilityOptions = this._observabilityOptions; + this._releaseOnEnd(session!, transaction!, span); + } else { + setSpanError(span, err); + } + span.end(); + cb!(err as grpc.ServiceError | null, transaction); + }, + ); + }, + ); + } + + /** + * Query object for listing database operations. + * + * @typedef {object} GetDatabaseOperationsOptions + * @property {string} [filter] An expression for filtering the results of the + * request. Filter can be configured as outlined in + * {@link v1.DatabaseAdminClient#listDatabaseOperations}. + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetDatabaseOperationsCallback} [callback] Callback function. + */ + /** + * @typedef {array} GetDatabaseOperationsResponse + * @property {IOperation[]} 0 Array of {@link IOperation} instances. + * @property {object} 1 The full API response. + */ + /** + * List pending and completed operations for the database. + * + * @see {@link Instance.getDatabaseOperations} + * + * @param {GetDatabaseOperationsOptions} [options] Contains query object for + * listing database operations and request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @returns {Promise} When resolved, contains + * a paged list of database operations. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const [operations] = await database.getOperations(); + * + * //- + * // To manually handle pagination, set autoPaginate:false in gaxOptions. + * //- + * let pageToken = undefined; + * do { + * const [operations, , response] = await database.getOperations({ + * pageSize: 3, + * pageToken, + * gaxOptions: {autoPaginate: false}, + * }); + * operations.forEach(operation => { + * // Do something with operation + * }); + * pageToken = response.nextPageToken; + * } while (pageToken); + * ``` + */ + getOperations( + options?: GetDatabaseOperationsOptions, + ): Promise; + getOperations(callback: GetDatabaseOperationsCallback): void; + getOperations( + options: GetDatabaseOperationsOptions, + callback: GetDatabaseOperationsCallback, + ): void; + async getOperations( + optionsOrCallback?: + | GetDatabaseOperationsOptions + | GetDatabaseOperationsCallback, + ): Promise { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + // Create a query that lists database operations only on this database from + // the instance. Operation name will be prefixed with the database path for + // all operations on this database + let dbSpecificFilter = `name:${this.formattedName_}`; + if (options && options.filter) { + dbSpecificFilter = `(${dbSpecificFilter}) AND (${options.filter})`; + } + const dbSpecificQuery: GetDatabaseOperationsOptions = { + ...options, + filter: dbSpecificFilter, + }; + + return this.instance.getDatabaseOperations(dbSpecificQuery); + } + + /** + * @typedef {array} GetDatabaseRolesResponse + * @property {IDatabaseRolees[]} 0 Array of list of database roles. + * @property {object} 1 A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetDatabaseRolesCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Gets a list of database roles + * + * @see {@link v1.DatabaseAdminClient#getDatabaseRoles} + * @see [GetDatabaseRoles API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseRoles) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetDatabaseRolesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.getDatabaseRoles(function(err, roles) { + * // `roles` is an array of `DatabaseRoles` objects. + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * function callback(err, roles, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * database.getDatabaseRoles(nextQuery, callback); + * } + * } + * + * database.getInstances({ + * gaxOptions: {autoPaginate: false} + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.getInstances().then(function(data) { + * const roles = data[0]; + * }); + * ``` + */ + getDatabaseRoles(gaxOptions?: CallOptions): Promise; + getDatabaseRoles(callback: GetDatabaseRolesCallback): void; + getDatabaseRoles( + gaxOptions: CallOptions, + callback: GetDatabaseRolesCallback, + ): void; + getDatabaseRoles( + optionsOrCallback?: CallOptions | GetDatabaseRolesCallback, + cb?: GetDatabaseRolesCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + let reqOpts = { + parent: this.formattedName_, + }; + + // Copy over pageSize and pageToken values from gaxOptions. + // However, values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetDatabaseRolesOptions).pageSize, + pageToken: (gaxOpts as GetDatabaseRolesOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetDatabaseRolesOptions).pageSize; + delete (gaxOpts as GetDatabaseRolesOptions).pageToken; + } + + this.request< + IDatabaseRole, + databaseAdmin.spanner.admin.database.v1.ListDatabaseRolesResponse + >( + { + client: 'DatabaseAdminClient', + method: 'listDatabaseRoles', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, roles, nextPageRequest, ...args) => { + const nextQuery = nextPageRequest! + ? extend({}, gaxOpts, nextPageRequest!) + : null; + + callback!(err, roles, nextQuery, ...args); + }, + ); + } + + /** + * Make an API request, first assuring an active session is used. + * + * @private + * + * @param {object} config Request config + * @param {function} callback Callback function + */ + makePooledRequest_(config: RequestConfig): Promise; + makePooledRequest_( + config: RequestConfig, + callback: PoolRequestCallback, + ): void; + makePooledRequest_( + config: RequestConfig, + callback?: PoolRequestCallback, + ): void | Promise { + const sessionFactory_ = this.sessionFactory_; + sessionFactory_.getSessionForReadWrite((err, session) => { + if (err) { + callback!(err as ServiceError, null); + return; + } + + const span = getActiveOrNoopSpan(); + span.addEvent('Using Session', {'session.id': session?.id}); + config.reqOpts.session = session!.formattedName_; + this.request(config, (err, ...args) => { + sessionFactory_.release(session!); + callback!(err, ...args); + }); + }); + } + + /** + * Make an API request as a stream, first assuring an active session is used. + * + * @private + * + * @param {object} config Request config + * @returns {Stream} + */ + makePooledStreamingRequest_(config: RequestConfig): Readable { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const sessionFactory_ = this.sessionFactory_; + let requestStream: CancelableDuplex; + let session: Session | null; + const waitForSessionStream = streamEvents(through.obj()); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (waitForSessionStream as any).abort = () => { + releaseSession(); + if (requestStream) { + requestStream.cancel(); + } + }; + function destroyStream(err: grpc.ServiceError) { + waitForSessionStream.destroy(err); + } + function releaseSession() { + if (session) { + sessionFactory_.release(session); + session = null; + } + } + waitForSessionStream.on('reading', () => { + sessionFactory_.getSession((err, session_) => { + const span = getActiveOrNoopSpan(); + if (err) { + setSpanError(span, err as ServiceError); + destroyStream(err as ServiceError); + return; + } + span.addEvent('Using Session', {'session.id': session_?.id}); + session = session_!; + config.reqOpts.session = session!.formattedName_; + requestStream = self.requestStream(config); + requestStream + .on('error', releaseSession) + .on('error', destroyStream) + .on('end', releaseSession) + .pipe(waitForSessionStream); + }); + }); + return waitForSessionStream; + } + + /** + * @typedef {object} RestoreOptions + * @property {google.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig} + * encryptionConfig An encryption configuration describing + * the encryption type and key resources in Cloud KMS used to + * encrypt/decrypt the database to restore to. + * @property {CallOptions} [gaxOptions] The request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} RestoreDatabaseResponse + * @property {Database} 0 The new {@link Database}. + * @property {google.longrunning.Operation} 1 An {@link Operation} object that can be used to check + * the status of the request. + * @property {object} 2 The full API response. + */ + /** + * @callback RestoreDatabaseCallback + * @param {?Error} err Request error, if any. + * @param {Database} database The new {@link Database}. + * @param {google.longrunning.Operation} operation An {@link Operation} object that can be used to + * check the status of the request. + * @param {object} apiResponse The full API response. + */ + /** + * Restore a backup into this database. + * + * When this call completes, the restore will have commenced but will not + * necessarily have completed. + * + * @param {string} backupPath The path of the backup to restore. + * @param {RestoreOptions} [options] Request configuration options. + * @param {RestoreDatabaseCallback} [callback] Callback function. + * @returns {Promise} When resolved, contains the restore operation. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const backupName = 'projects/my-project/instances/my-instance/backups/my-backup'; + * const [, restoreOperation] = await database.restore(backupName); + * // Wait for restore to complete + * await restoreOperation.promise(); + * + * //- + * // Restore database with a different encryption key to the one used by the + * // backup. + * //- + * const [, restoreWithKeyOperation] = await database.restore( + * backupName, + * { + * encryptionConfig: { + * encryptionType: 'CUSTOMER_MANAGED_ENCRYPTION', + * kmsKeyName: 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key', + * } + * }, + * ); + * // Wait for restore to complete + * await restoreWithKeyOperation.promise(); + * ``` + */ + restore(backupPath: string): Promise; + restore( + backupPath: string, + options?: RestoreOptions | CallOptions, + ): Promise; + restore(backupPath: string, callback: RestoreDatabaseCallback): void; + restore( + backupPath: string, + options: RestoreOptions | CallOptions, + callback: RestoreDatabaseCallback, + ): void; + restore( + backupName: string, + optionsOrCallback?: RestoreOptions | CallOptions | RestoreDatabaseCallback, + cb?: RestoreDatabaseCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as RestoreDatabaseCallback) + : cb; + const gaxOpts = + 'gaxOptions' in options + ? (options as RestoreOptions).gaxOptions + : (options as CallOptions); + + const reqOpts: databaseAdmin.spanner.admin.database.v1.IRestoreDatabaseRequest = + { + parent: this.instance.formattedName_, + databaseId: this.id, + backup: Backup.formatName_(this.instance.formattedName_, backupName), + }; + + if ( + 'encryptionConfig' in options && + (options as RestoreOptions).encryptionConfig + ) { + reqOpts.encryptionConfig = (options as RestoreOptions).encryptionConfig; + } + + return this.request( + { + client: 'DatabaseAdminClient', + method: 'restoreDatabase', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, operation, resp) => { + if (err) { + callback!(err, null, null, resp); + return; + } + callback!(null, this, operation, resp); + }, + ); + } + + /** + * Transaction options. + * + * @typedef {object} DatabaseRunRequest + * @property {number} [exactStaleness] Executes all reads at the timestamp + * that is `exactStaleness` old. + * @property {date} [readTimestamp] Execute all reads at the given + * timestamp. + * @property {boolean} [strong] Read at the timestamp where all previously + * committed transactions are visible. + */ + /** + * @typedef {array} RunResponse + * @property {Array} 0 Rows are returned as an array objects. Each + * object has a `name` and `value` property. To get a serialized object, + * call `toJSON()`. + * @property {?google.spanner.v1.IResultSetStats} 1 Query statistics, if the query is executed in + * PLAN or PROFILE mode. + */ + /** + * @callback RunCallback + * @param {?Error} err Request error, if any. + * @param {Array} rows Rows are returned as an array of objects. + * Each object has a `name` and `value` property. To get a serialized + * object, call `toJSON()`. + * @param {?google.spanner.v1.IResultSetStats} stats Query statistics, if the query is executed + * in PLAN or PROFILE mode. + */ + /** + * Execute a SQL statement on this database. + * + * Wrapper around {@link v1.SpannerClient#executeStreamingSql}. + * + * @see {@link v1.SpannerClient#executeStreamingSql} + * @see [Query Syntax](https://cloud.google.com/spanner/docs/query-syntax) + * @see [ExecuteSql API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ExecuteSql) + * + * @param {string|ExecuteSqlRequest} query A SQL query or + * {@link ExecuteSqlRequest} object. + * @param {TimestampBounds} [options] Snapshot timestamp bounds. + * @param {RunCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const query = 'SELECT * FROM Singers'; + * + * database.run(query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * const firstRow = rows[0]; + * + * // firstRow = [ + * // { + * // name: 'SingerId', + * // value: '1' + * // }, + * // { + * // name: 'Name', + * // value: 'Eddie Wilson' + * // } + * // ] + * }); + * + * //- + * // Rows are returned as an array of object arrays. Each object has a `name` + * // and `value` property. To get a serialized object, call `toJSON()`. + * //- + * database.run(query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * const firstRow = rows[0]; + * + * // firstRow.toJSON() = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }); + * + * //- + * // Alternatively, set `query.json` to `true`, and this step will be performed + * // automatically. + * //- + * database.run(query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * const firstRow = rows[0]; + * + * // firstRow = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }); + * + * //- + * // The SQL query string can contain parameter placeholders. A parameter + * // placeholder consists of '@' followed by the parameter name. + * //- + * const query = { + * sql: 'SELECT * FROM Singers WHERE name = @name', + * params: { + * name: 'Eddie Wilson' + * } + * }; + * + * database.run(query, function(err, rows) {}); + * + * //- + * // If you need to enforce a specific param type, a types map can be provided. + * // This is typically useful if your param value can be null. + * //- + * const query = { + * sql: 'SELECT * FROM Singers WHERE name = @name AND id = @id', + * params: { + * id: spanner.int(8), + * name: null + * }, + * types: { + * id: 'int64', + * name: 'string' + * } + * }; + * + * database.run(query, function(err, rows) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.run(query).then(function(data) { + * const rows = data[0]; + * }); + * + * ``` + * @example include:samples/crud.js + * region_tag:spanner_query_data + * Full example: + * + * @example include:samples/index-query-data.js + * region_tag:spanner_query_data_with_index + * Querying data with an index: + */ + run(query: string | ExecuteSqlRequest): Promise; + run( + query: string | ExecuteSqlRequest, + options?: TimestampBounds, + ): Promise; + run(query: string | ExecuteSqlRequest, callback: RunCallback): void; + run( + query: string | ExecuteSqlRequest, + options: TimestampBounds, + callback: RunCallback, + ): void; + run( + query: string | ExecuteSqlRequest, + optionsOrCallback?: TimestampBounds | RunCallback, + cb?: RunCallback, + ): void | Promise { + let stats: ResultSetStats; + let metadata: ResultSetMetadata; + const rows: Row[] = []; + const callback = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as RunCallback) + : cb; + const options = + typeof optionsOrCallback === 'object' + ? (optionsOrCallback as TimestampBounds) + : {}; + + return startTrace( + 'Database.run', + { + ...(query as ExecuteSqlRequest), + ...this._traceConfig, + }, + span => { + this.runStream(query, options) + .on('error', err => { + setSpanError(span, err); + span.end(); + callback!(err as grpc.ServiceError, rows, stats, metadata); + }) + .on('response', response => { + if (response.metadata) { + metadata = response.metadata; + } + }) + .on('stats', _stats => (stats = _stats)) + .on('data', row => { + rows.push(row); + }) + .on('end', () => { + span.end(); + callback!(null, rows, stats, metadata); + }); + }, + ); + } + /** + * Partitioned DML transactions are used to execute DML statements with a + * different execution strategy that provides different, and often better, + * scalability properties for large, table-wide operations than DML in a + * Transaction transaction. Smaller scoped statements, such as an OLTP workload, + * should prefer using Transaction transactions. + * + * @see {@link Transaction#runUpdate} + * + * @param {string|ExecuteSqlRequest} query A DML statement or + * {@link ExecuteSqlRequest} object. + * @param {RunUpdateCallback} [callback] Callback function. + * @returns {Promise} + */ + runPartitionedUpdate( + query: string | RunPartitionedUpdateOptions, + ): Promise<[number]>; + runPartitionedUpdate( + query: string | RunPartitionedUpdateOptions, + callback?: RunUpdateCallback, + ): void; + runPartitionedUpdate( + query: string | RunPartitionedUpdateOptions, + callback?: RunUpdateCallback, + ): void | Promise<[number]> { + return startTrace( + 'Database.runPartitionedUpdate', + { + ...(query as RunPartitionedUpdateOptions), + ...this._traceConfig, + requestTag: (query as RunPartitionedUpdateOptions)?.requestOptions + ?.requestTag, + }, + span => { + this.sessionFactory_.getSessionForPartitionedOps((err, session) => { + if (err) { + setSpanError(span, err); + span.end(); + callback!(err as ServiceError, 0); + return; + } + + void this._runPartitionedUpdate(session!, query, (err, count) => { + if (err) { + setSpanError(span, err); + } + span.end(); + callback!(err, count); + }); + }); + }, + ); + } + + _runPartitionedUpdate( + session: Session, + query: string | RunPartitionedUpdateOptions, + callback?: RunUpdateCallback, + ): void | Promise { + const transaction = session.partitionedDml(); + + if (typeof query !== 'string' && query.excludeTxnFromChangeStreams) { + transaction.excludeTxnFromChangeStreams(); + } + transaction.begin(err => { + if (err) { + this.sessionFactory_.release(session!); + callback!(err, 0); + return; + } + + transaction.runUpdate(query, async (err, updateCount) => { + if (err) { + if (err.code !== grpc.status.ABORTED) { + this.sessionFactory_.release(session!); + callback!(err, 0); + return; + } + void this._runPartitionedUpdate(session, query, callback); + } else { + this.sessionFactory_.release(session!); + callback!(null, updateCount); + return; + } + }); + }); + } + + /** + * Create a readable object stream to receive resulting rows from a SQL + * statement. + * + * Wrapper around {@link v1.SpannerClient#executeStreamingSql}. + * + * @see {@link v1.SpannerClient#executeStreamingSql} + * @see [Query Syntax](https://cloud.google.com/spanner/docs/query-syntax) + * @see [ExecuteSql API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ExecuteSql) + * + * @fires PartialResultStream#response + * + * @param {string|ExecuteSqlRequest} query A SQL query or + * {@link ExecuteSqlRequest} object. + * @param {TimestampBounds} [options] Snapshot timestamp bounds. + * @returns {PartialResultStream} A readable stream that emits rows. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const query = 'SELECT * FROM Singers'; + * + * database.runStream(query) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row = [ + * // { + * // name: 'SingerId', + * // value: '1' + * // }, + * // { + * // name: 'Name', + * // value: 'Eddie Wilson' + * // } + * // ] + * // ] + * }) + * .on('end', function() { + * // All results retrieved. + * }); + * + * //- + * // Rows are returned as an array of objects. Each object has a `name` and + * // `value` property. To get a serialized object, call `toJSON()`. + * //- + * database.runStream(query) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row.toJSON() = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }) + * .on('end', function() { + * // All results retrieved. + * }); + * + * //- + * // Alternatively, set `query.json` to `true`, and this step will be performed + * // automatically. + * //- + * query.json = true; + * + * database.runStream(query) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }) + * .on('end', function() { + * // All results retrieved. + * }); + * + * //- + * // The SQL query string can contain parameter placeholders. A parameter + * // placeholder consists of '@' followed by the parameter name. + * //- + * const query = { + * sql: 'SELECT * FROM Singers WHERE name = @name', + * params: { + * name: 'Eddie Wilson' + * } + * }; + * + * database.runStream(query) + * .on('error', function(err) {}) + * .on('data', function(row) {}) + * .on('end', function() {}); + * + * //- + * // If you need to enforce a specific param type, a types map can be provided. + * // This is typically useful if your param value can be null. + * //- + * const query = { + * sql: 'SELECT * FROM Singers WHERE name = @name', + * params: { + * name: 'Eddie Wilson' + * }, + * types: { + * name: 'string' + * } + * }; + * + * database.runStream(query) + * .on('error', function(err) {}) + * .on('data', function(row) {}) + * .on('end', function() {}); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * database.runStream(query) + * .on('data', function(row) { + * this.end(); + * }); + * ``` + */ + runStream( + query: string | ExecuteSqlRequest, + options?: TimestampBounds, + ): PartialResultStream { + const proxyStream: Transform = through.obj(); + return startTrace( + 'Database.runStream', + { + ...(query as ExecuteSqlRequest), + ...this._traceConfig, + requestTag: (query as ExecuteSqlRequest)?.requestOptions?.requestTag, + }, + span => { + this.sessionFactory_.getSession((err, session) => { + if (err) { + setSpanError(span, err); + proxyStream.destroy(err); + span.end(); + return; + } + + span.addEvent('Using Session', {'session.id': session?.id}); + + const snapshot = session!.snapshot(options, this.queryOptions_); + + this._releaseOnEnd(session!, snapshot, span); + + let dataReceived = false; + let dataStream = snapshot.runStream(query); + + const endListener = () => { + snapshot.end(); + }; + dataStream + .once('data', () => (dataReceived = true)) + .once('error', err => { + setSpanError(span, err); + + if ( + !dataReceived && + isSessionNotFoundError(err as grpc.ServiceError) && + !this.sessionFactory_.isMultiplexedEnabled() + ) { + // If it is a 'Session not found' error and we have not yet received + // any data, we can safely retry the query on a new session. + // Register the error on the session so the pool can discard it. + if (session) { + session.lastError = err as grpc.ServiceError; + } + span.addEvent('No session available', { + 'session.id': session?.id, + }); + // Remove the current data stream from the end user stream. + dataStream.unpipe(proxyStream); + dataStream.removeListener('end', endListener); + dataStream.end(); + snapshot.end(); + span.end(); + // Create a new data stream and add it to the end user stream. + dataStream = this.runStream(query, options); + dataStream.pipe(proxyStream); + } else { + proxyStream.destroy(err); + snapshot.end(); + } + }) + .on('stats', stats => proxyStream.emit('stats', stats)) + .on('response', response => proxyStream.emit('response', response)) + .once('end', endListener) + .pipe(proxyStream); + }); + + finished(proxyStream, err => { + if (err) { + setSpanError(span, err); + } + span.end(); + }); + + return proxyStream as PartialResultStream; + }, + ); + } + + /** + * @typedef {object} RunTransactionOptions + * @property {number} [timeout] The maximum amount of time (in ms) that a + * {@link Transaction} should be ran for. + */ + /** + * @callback RunTransactionCallback + * @param {?Error} err An error returned while making this request. + * @param {Transaction} transaction The transaction object. The transaction has + * already been created, and is ready to be queried and committed against. + */ + /** + * A transaction in Cloud Spanner is a set of reads and writes that execute + * atomically at a single logical point in time across columns, rows, and tables + * in a database. + * + * Note that Cloud Spanner does not support nested transactions. If a new + * transaction is started inside of the run function, it will be an independent + * transaction. + * + * The callback you provide to this function will become the "run function". It + * will be executed with either an error or a {@link Transaction} + * object. The Transaction object will let you run queries and queue mutations + * until you are ready to {@link Transaction#commit}. + * + * In the event that an aborted error occurs, we will re-run the `runFn` in its + * entirety. If you prefer to handle aborted errors for yourself please refer to + * {@link Database#getTransaction}. + * + * **NOTE:** In the event that you encounter an error while reading/writing, + * if you decide to forgo calling {@link Transaction#commit} or + * {@link Transaction#rollback}, then you need to call + * {@link Transaction#end} to release the underlying {@link Session} object. + * **Failure to do could result in a Session leak.** + * + * For a more complete listing of functionality available to a Transaction, see + * the {@link Transaction} API documentation. For a general overview of + * transactions within Cloud Spanner, see + * [Transactions](https://cloud.google.com/spanner/docs/transactions) from the + * official Cloud Spanner documentation. + * + * If you would like to run a transaction and receive a promise or use + * async/await, use {@link Database#runTransactionAsync}. + * + * @see [Transactions](https://cloud.google.com/spanner/docs/transactions) + * + * @param {RunTransactionOptions} [options] Transaction runner options. + * @param {RunTransactionCallback} callback A function to execute in the context + * of a transaction. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Run a transactional query. + * transaction.run('SELECT * FROM Singers', function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * // Queue a mutation (note that there is no callback passed to `insert`). + * transaction.insert('Singers', { + * SingerId: 'Id3b', + * Name: 'Joe West' + * }); + * + * // Commit the transaction. + * transaction.commit(function(err) { + * if (!err) { + * // Transaction committed successfully. + * } + * }); + * }); + * }); + * + * ``` + * @example include:samples/transaction.js + * region_tag:spanner_read_write_transaction + * Read-write transaction: + */ + runTransaction(runFn: RunTransactionCallback): void; + runTransaction( + options: RunTransactionOptions, + runFn: RunTransactionCallback, + ): void; + runTransaction( + optionsOrRunFn: RunTransactionOptions | RunTransactionCallback, + fn?: RunTransactionCallback, + ): void { + const runFn = + typeof optionsOrRunFn === 'function' + ? (optionsOrRunFn as RunTransactionCallback) + : fn; + const options = + typeof optionsOrRunFn === 'object' && optionsOrRunFn + ? (optionsOrRunFn as RunTransactionOptions) + : {}; + + startTrace( + 'Database.runTransaction', + { + ...this._traceConfig, + transactionTag: options.requestOptions?.transactionTag, + }, + span => { + this.sessionFactory_.getSessionForReadWrite( + (err, session?, transaction?) => { + if (err) { + setSpanError(span, err); + } + + if (err && isSessionNotFoundError(err as grpc.ServiceError)) { + span.addEvent('No session available', { + 'session.id': session?.id, + }); + span.end(); + this.runTransaction(options, runFn!); + return; + } + + if (err) { + span.end(); + runFn!(err as grpc.ServiceError); + return; + } + + transaction!._observabilityOptions = this._observabilityOptions; + + transaction!.requestOptions = Object.assign( + transaction!.requestOptions || {}, + options.requestOptions, + ); + + transaction!.setReadWriteTransactionOptions( + options as RunTransactionOptions, + ); + + const release = () => { + this.sessionFactory_.release(session!); + span.end(); + }; + + const runner = new TransactionRunner( + session!, + transaction!, + runFn!, + options, + ); + + runner.run().then(release, err => { + setSpanError(span, err!); + + if (isSessionNotFoundError(err)) { + span.addEvent('No session available', { + 'session.id': session?.id, + }); + release(); + this.runTransaction(options, runFn!); + } else { + setImmediate(runFn!, err); + release(); + } + }); + }, + ); + }, + ); + } + + runTransactionAsync( + runFn: AsyncRunTransactionCallback, + ): Promise; + runTransactionAsync( + options: RunTransactionOptions, + runFn: AsyncRunTransactionCallback, + ): Promise; + /** + * @callback AsyncRunTransactionCallback + * @param {Transaction} transaction The transaction object. The transaction has + * already been created, and is ready to be queried and committed against. + */ + /** + * A transaction in Cloud Spanner is a set of reads and writes that execute + * atomically at a single logical point in time across columns, rows, and tables + * in a database. + * + * Note that Cloud Spanner does not support nested transactions. If a new + * transaction is started inside of the run function, it will be an independent + * transaction. + * + * The async function you provide will become the "run function". It + * will be executed with a {@link Transaction} + * object. The Transaction object will let you run queries and queue mutations + * until you are ready to {@link Transaction#commit}. + * + * In the event that an aborted error occurs, we will re-run the `runFn` in its + * entirety. If you prefer to handle aborted errors for yourself please refer to + * {@link Database#getTransaction}. + * + * **NOTE:** In the event that you encounter an error while reading/writing, + * if you decide to forgo calling {@link Transaction#commit} or + * {@link Transaction#rollback}, then you need to call + * {@link Transaction#end} to release the underlying {@link Session} object. + * **Failure to do could result in a Session leak.** + * + * For a more complete listing of functionality available to a Transaction, see + * the {@link Transaction} API documentation. For a general overview of + * transactions within Cloud Spanner, see + * [Transactions](https://cloud.google.com/spanner/docs/transactions) from the + * official Cloud Spanner documentation. + * + * @see [Transactions](https://cloud.google.com/spanner/docs/transactions) + * + * @param {RunTransactionOptions} [options] Transaction runner options. + * @param {AsyncRunTransactionCallback} callback A function to execute in the + * context of a transaction. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const data = await database.runTransactionAsync(async (transaction) => { + * const [rows] = await transaction.run('SELECT * FROM MyTable'); + * const data = rows.map(row => row.thing); + * + * await transaction.commit(); + * return data; + * }); + * ``` + */ + async runTransactionAsync( + optionsOrRunFn: RunTransactionOptions | AsyncRunTransactionCallback, + fn?: AsyncRunTransactionCallback, + ): Promise { + const runFn = + typeof optionsOrRunFn === 'function' + ? (optionsOrRunFn as AsyncRunTransactionCallback) + : fn!; + const options = + typeof optionsOrRunFn === 'object' + ? (optionsOrRunFn as RunTransactionOptions) + : {}; + + let sessionId = ''; + const getSession = this.sessionFactory_.getSessionForReadWrite.bind( + this.sessionFactory_, + ); + + return startTrace( + 'Database.runTransactionAsync', + { + ...this._traceConfig, + transactionTag: options?.requestOptions?.transactionTag, + }, + async span => { + // Loop to retry 'Session not found' errors. + // (and yes, we like while (true) more than for (;;) here) + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const [session, transaction] = await promisify(getSession)(); + transaction.requestOptions = Object.assign( + transaction.requestOptions || {}, + options.requestOptions, + ); + transaction!.setReadWriteTransactionOptions( + options as RunTransactionOptions, + ); + sessionId = session?.id; + span.addEvent('Using Session', {'session.id': sessionId}); + const runner = new AsyncTransactionRunner( + session, + transaction, + runFn, + options, + ); + + try { + return await runner.run(); + } catch (e) { + setSpanErrorAndException(span, e as Error); + throw e; + } finally { + span.end(); + this.sessionFactory_.release(session); + } + } catch (e) { + if (isSessionNotFoundError(e as ServiceError)) { + span.addEvent('No session available', { + 'session.id': sessionId, + }); + } else { + span.end(); + throw e; + } + } + } + }, + ); + } + + /** + * Write a batch of mutations to Spanner. + * + * All mutations in a group are committed atomically. However, mutations across + * groups can be committed non-atomically in an unspecified order and thus, they + * must be independent of each other. Partial failure is possible, i.e., some groups + * may have been committed successfully, while some may have failed. The results of + * individual batches are streamed into the response as the batches are applied. + * + * batchWriteAtLeastOnce requests are not replay protected, meaning that each mutation group may + * be applied more than once. Replays of non-idempotent mutations may have undesirable + * effects. For example, replays of an insert mutation may produce an already exists + * error or if you use generated or commit timestamp-based keys, it may result in additional + * rows being added to the mutation's table. We recommend structuring your mutation groups to + * be idempotent to avoid this issue. + * + * @method Spanner#batchWriteAtLeastOnce + * + * @param {MutationGroup[]} [mutationGroups] The group of mutations to be applied. + * @param {BatchWriteOptions} [options] Options object for batch write request. + * + * @returns {ReadableStream} An object stream which emits + * {@link protos.google.spanner.v1.BatchWriteResponse|BatchWriteResponse} + * on 'data' event. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const mutationGroup = new MutationGroup(); + * mutationGroup.insert('Singers', { + * SingerId: '1', + * FirstName: 'Marc', + * LastName: 'Richards', + * }); + * + * database.batchWriteAtLeastOnce([mutationGroup]) + * .on('error', console.error) + * .on('data', response => { + * console.log('response: ', response); + * }) + * .on('end', () => { + * console.log('Request completed successfully'); + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * database.batchWriteAtLeastOnce() + * .on('data', response => { + * this.end(); + * }); + * ``` + */ + batchWriteAtLeastOnce( + mutationGroups: MutationGroup[], + options?: BatchWriteOptions, + ): NodeJS.ReadableStream { + const proxyStream: Transform = through.obj(); + + return startTrace( + 'Database.batchWriteAtLeastOnce', + { + ...this._traceConfig, + transactionTag: options?.requestOptions?.transactionTag, + }, + span => { + this.sessionFactory_.getSessionForReadWrite((err, session) => { + if (err) { + proxyStream.destroy(err); + setSpanError(span, err); + span.end(); + return; + } + + span.addEvent('Using Session', {'session.id': session?.id}); + const gaxOpts = extend(true, {}, options?.gaxOptions); + const reqOpts = Object.assign( + {} as spannerClient.spanner.v1.BatchWriteRequest, + { + session: session!.formattedName_!, + mutationGroups: mutationGroups.map(mg => mg.proto()), + requestOptions: options?.requestOptions, + excludeTxnFromChangeStream: options?.excludeTxnFromChangeStreams, + }, + ); + let dataReceived = false; + let dataStream = this.requestStream({ + client: 'SpannerClient', + method: 'batchWrite', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }); + dataStream + .once('data', () => (dataReceived = true)) + .once('error', err => { + setSpanError(span, err); + + if ( + !dataReceived && + isSessionNotFoundError(err as grpc.ServiceError) + ) { + // If there's a 'Session not found' error and we have not yet received + // any data, we can safely retry the writes on a new session. + // Register the error on the session so the pool can discard it. + if (session) { + session.lastError = err as grpc.ServiceError; + } + span.addEvent('No session available', { + 'session.id': session?.id, + }); + // Remove the current data stream from the end user stream. + dataStream.unpipe(proxyStream); + dataStream.end(); + span.end(); + // Create a new stream and add it to the end user stream. + dataStream = this.batchWriteAtLeastOnce( + mutationGroups, + options, + ); + dataStream.pipe(proxyStream); + } else { + span.end(); + proxyStream.destroy(err); + } + }) + .once('end', () => { + span.end(); + this.sessionFactory_.release(session!); + }) + .pipe(proxyStream); + }); + + return proxyStream as NodeJS.ReadableStream; + }, + ); + } + + /** + * Write mutations using a single RPC invocation without replay protection. + * + * writeAtLeastOnce writes mutations to Spanner using a single Commit RPC. + * These requests are not replay protected, meaning that it may apply mutations more + * than once, if the mutations are not idempotent, this may lead to a failure being + * reported when the mutation was applied once. Replays non-idempotent mutations may + * have undesirable effects. For example, replays of an insert mutation may produce an + * already exists error. For this reason, most users of the library will prefer to use + * {@link runTransaction} instead. + * + * However, {@link writeAtLeastOnce()} requires only a single RPC, whereas {@link runTransaction()} + * requires two RPCs (one of which may be performed in advance), and so this method may be + * appropriate for latency sensitive and/or high throughput blind writing. + * + * We recommend structuring your mutation set to be idempotent to avoid this issue. + * + * @param {MutationSet} [mutations] Set of Mutations to be applied. + * @param {CallOptions} [options] Options object for blind write request. + * @param {CommitCallback} [callback] Callback function for blind write request. + * + * @returns {Promise} + * + * @example + * ``` + * const {Spanner, MutationSet} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const mutations = new MutationSet(); + * mutations.upsert('Singers', { + * SingerId: 1, + * FirstName: 'Scarlet', + * LastName: 'Terry', + * }); + * mutations.upsert('Singers', { + * SingerId: 2, + * FirstName: 'Marc', + * LastName: 'Richards', + * }); + * + * try { + * const [response] = await database.writeAtLeastOnce(mutations, {}); + * console.log(response.commitTimestamp); + * } catch(err) { + * console.log("Error: ", err); + * } + * ``` + */ + writeAtLeastOnce(mutations: MutationSet): Promise; + writeAtLeastOnce( + mutations: MutationSet, + options: WriteAtLeastOnceOptions, + ): Promise; + writeAtLeastOnce(mutations: MutationSet, callback: CommitCallback): void; + writeAtLeastOnce( + mutations: MutationSet, + options: WriteAtLeastOnceOptions, + callback: CommitCallback, + ): void; + writeAtLeastOnce( + mutations: MutationSet, + optionsOrCallback?: WriteAtLeastOnceOptions | CommitCallback, + callback?: CommitCallback, + ): void | Promise { + const cb = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as CommitCallback) + : callback; + const options = + typeof optionsOrCallback === 'object' && optionsOrCallback + ? (optionsOrCallback as WriteAtLeastOnceOptions) + : {}; + + return startTrace('Database.writeAtLeastOnce', this._traceConfig, span => { + this.sessionFactory_.getSession((err, session?, transaction?) => { + if ( + err && + isSessionNotFoundError(err as grpc.ServiceError) && + !this.sessionFactory_.isMultiplexedEnabled() + ) { + span.addEvent('No session available', { + 'session.id': session?.id, + }); + span.end(); + this.writeAtLeastOnce(mutations, options, cb!); + return; + } + if (err) { + setSpanError(span, err); + span.end(); + cb!(err as grpc.ServiceError); + return; + } + span.addEvent('Using Session', {'session.id': session?.id}); + this._releaseOnEnd(session!, transaction!, span); + try { + transaction!.setReadWriteTransactionOptions( + options as RunTransactionOptions, + ); + transaction?.setQueuedMutations(mutations.proto()); + return transaction?.commit(options, (err, resp) => { + if (err) { + setSpanError(span, err); + } + span.end(); + cb!(err, resp); + }); + } catch (e) { + setSpanErrorAndException(span, e as Error); + span.end(); + throw e; + } + }); + }); + } + + /** + * Create a Session object. + * + * It is unlikely you will need to interact with sessions directly. By default, + * sessions are created and utilized for maximum performance automatically. + * + * @param {string} [name] The name of the session. If not provided, it is + * assumed you are going to create it. + * @returns {Session} A Session object. + * + * @example + * ``` + * var session = database.session('session-name'); + * ``` + */ + session(name?: string) { + return new Session(this, name); + } + /** + * Get a reference to a Table object. + * + * @throws {GoogleError} If a name is not provided. + * + * @param {string} name The name of the table. + * @return {Table} A Table object. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const table = database.table('Singers'); + * ``` + */ + + /** + * @callback SetIamPolicyCallback + * @param {?Error} err Request error, if any. + * @param {google.iam.v1.Policy| undefined} policy Returns policy for the give database + */ + /** + * Sets the policy for the database. + * + * A Policy is a collection of bindings. A binding binds one or more members, or principals, + * to a single role. Principals can be user accounts, service accounts, Google groups, and + * domains (such as G Suite). A role is a named list of permissions; each role can be an IAM + * predefined role or a user-created custom role. + * + * @see {@link #setIamPolicy} + * + * @method Database#setIamPolicy + * @param {object} [policy] requestedPolicyVersion and gax options(configuration options) + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html} + * for more details on gax options. + * @param {object} [options] Requested configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html} + * for more details on Call Options. + * @param {SetIamPolicyCallback} [callback] Callback function. + * @returns {Promise} + * When resolved, contains the current policy of the database. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const binding = { + * role: 'roles/spanner.fineGrainedAccessUser', + * members: ['user:asthamohta@google.com'], + * condition: { + * title: 'new condition', + * expression: 'resource.name.endsWith("/databaseRoles/parent")', + * }, + * }; + * const policy = { + * bindings: [newBinding], + * version: 3, + *}; + * const policy = await database.setIamPolicy({policy: policy}); + * ``` + */ + setIamPolicy(policy: SetIamPolicyRequest): Promise; + setIamPolicy( + policy: SetIamPolicyRequest, + options?: CallOptions, + ): Promise; + setIamPolicy( + policy: SetIamPolicyRequest, + callback: SetIamPolicyCallback, + ): void; + setIamPolicy( + policy: SetIamPolicyRequest, + options: CallOptions, + callback: SetIamPolicyCallback, + ): void; + setIamPolicy( + policy: SetIamPolicyRequest, + optionsOrCallback?: CallOptions | SetIamPolicyCallback, + cb?: SetIamPolicyCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as SetIamPolicyCallback) + : cb; + const gaxOpts = options as CallOptions; + + const reqOpts: databaseAdmin.iam.v1.ISetIamPolicyRequest = { + resource: this.formattedName_, + policy: policy.policy, + updateMask: policy.updateMask || null, + }; + + this.request( + { + client: 'DatabaseAdminClient', + method: 'setIamPolicy', + reqOpts, + gaxOpts: gaxOpts, + headers: this.commonHeaders_, + }, + (err, resp) => { + callback!(err, resp); + }, + ); + } + + table(name: string) { + if (!name) { + throw new GoogleError('A name is required to access a Table object.'); + } + return new Table(this, name); + } + /** + * Update the schema of the database by creating/altering/dropping tables, + * columns, indexes, etc. + * + * This method immediately responds with an Operation object. Register event + * handlers for the "error" and "complete" events to see how the operation + * finishes. Follow along with the examples below. + * + * Wrapper around {@link v1.DatabaseAdminClient#updateDatabaseDdl}. + * + * @see {@link v1.DatabaseAdminClient#updateDatabaseDdl} + * @see [Data Definition Language (DDL)](https://cloud.google.com/spanner/docs/data-definition-language) + * @see [Schema and Data Model](https://cloud.google.com/spanner/docs/schema-and-data-model) + * @see [UpdateDatabaseDdl API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) + * + * @param {string|string[]|object} statements An array of database DDL + * statements, or an + * [`UpdateDatabaseDdlRequest` object](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.UpdateDatabaseDdlRequest). + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {LongRunningOperationCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const statements = [ + * 'CREATE TABLE Singers (' + + * ' SingerId INT64 NOT NULL,' + + * ' FirstName STRING(1024),' + + * ' LastName STRING(1024),' + + * ' SingerInfo BYTES(MAX),' + + * ') PRIMARY KEY(SingerId)' + * ]; + * + * database.updateSchema(statements, function(err, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Database schema updated successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * database.updateSchema(statements) + * .then(function(data) { + * const operation = data[0]; + * return operation.promise(); + * }) + * .then(function() { + * // Database schema updated successfully. + * }); + * + * ``` + * @example include:samples/schema.js + * region_tag:spanner_add_column + * Adding a column: + * + * @example include:samples/index-create.js + * region_tag:spanner_create_index + * Creating an index: + * + * @example include:samples/index-create-stroing.js + * region_tag:spanner_create_storing_index + * Creating a storing index: + */ + updateSchema( + statements: Schema, + gaxOptions?: CallOptions, + ): Promise; + updateSchema(statements: Schema, callback: UpdateSchemaCallback): void; + updateSchema( + statements: Schema, + gaxOptions: CallOptions, + callback: UpdateSchemaCallback, + ): void; + updateSchema( + statements: Schema, + optionsOrCallback?: CallOptions | UpdateSchemaCallback, + cb?: UpdateSchemaCallback, + ): Promise | void { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + if (typeof statements === 'string' || Array.isArray(statements)) { + statements = { + statements: toArray(statements) as string[], + }; + } + const reqOpts: databaseAdmin.spanner.admin.database.v1.IUpdateDatabaseDdlRequest = + extend( + { + database: this.formattedName_, + }, + statements, + ); + return this.request( + { + client: 'DatabaseAdminClient', + method: 'updateDatabaseDdl', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + callback!, + ); + } + /** + * Format the database name to include the instance name. + * + * @private + * + * @param {string} instanceName The formatted instance name. + * @param {string} name The table name. + * @returns {string} + * + * @example + * ``` + * Database.formatName_( + * 'projects/grape-spaceship-123/instances/my-instance', + * 'my-database' + * ); + * // 'projects/grape-spaceship-123/instances/my-instance/databases/my-database' + * ``` + */ + static formatName_(instanceName: string, name: string) { + if (name.indexOf('/') > -1) { + return name; + } + const databaseName = name.split('/').pop(); + return instanceName + '/databases/' + databaseName; + } + + /** + * Gets the Spanner object + * + * @private + * + * @returns {Spanner} + */ + private _getSpanner(): Spanner { + return this.instance.parent as Spanner; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Database, { + exclude: [ + 'batchTransaction', + 'batchWriteAtLeastOnce', + 'getRestoreInfo', + 'getState', + 'getDatabaseDialect', + 'getOperations', + 'runTransaction', + 'runTransactionAsync', + 'table', + 'session', + ], +}); + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +callbackifyAll(Database, { + exclude: [ + 'create', + 'batchCreateSessions', + 'batchTransaction', + 'batchWriteAtLeastOnce', + 'writeAtLeastOnce', + 'close', + 'createBatchTransaction', + 'createSession', + 'createTable', + 'delete', + 'exists', + 'get', + 'getDatabaseDialect', + 'getMetadata', + 'getSchema', + 'getSessions', + 'getSnapshot', + 'getTransaction', + 'getIamPolicy', + 'restore', + 'run', + 'runPartitionedUpdate', + 'runTransaction', + 'runTransactionAsync', + 'session', + 'setMetadata', + 'table', + 'updateSchema', + ], +}); + +/** + * Reference to the {@link Database} class. + * @name module:@google-cloud/spanner.Database + * @see Database + */ +export {Database}; diff --git a/handwritten/spanner/src/extra_proto_list.json b/handwritten/spanner/src/extra_proto_list.json new file mode 100644 index 00000000000..2999217b1c1 --- /dev/null +++ b/handwritten/spanner/src/extra_proto_list.json @@ -0,0 +1 @@ +["../node_modules/google-gax/build/protos/google/rpc/error_details.proto"] diff --git a/handwritten/spanner/src/helper.ts b/handwritten/spanner/src/helper.ts new file mode 100644 index 00000000000..30692c13c79 --- /dev/null +++ b/handwritten/spanner/src/helper.ts @@ -0,0 +1,278 @@ +/** + * 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 + * + * 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 {grpc} from 'google-gax'; +/** + * Checks whether the given error is a 'Database not found' error. + * @param {Error} error The error to check. + * @return {boolean} True if the error is a 'Database not found' error, and otherwise false. + */ +export function isDatabaseNotFoundError( + error: grpc.ServiceError | undefined, +): boolean { + return ( + error !== undefined && + error.code === grpc.status.NOT_FOUND && + error.message.includes('Database not found') + ); +} + +/** + * Checks whether the given error is an 'Instance not found' error. + * @param {Error} error The error to check. + * @return {boolean} True if the error is an 'Instance not found' error, and otherwise false. + */ +export function isInstanceNotFoundError( + error: grpc.ServiceError | undefined, +): boolean { + return ( + error !== undefined && + error.code === grpc.status.NOT_FOUND && + error.message.includes('Instance not found') + ); +} + +/** + * Checks whether the given error is a 'Could not load the default credentials' error. + * @param {Error} error The error to check. + * @return {boolean} True if the error is a 'Could not load the default credentials' error, and otherwise false. + */ +export function isDefaultCredentialsNotSetError( + error: grpc.ServiceError | undefined, +): boolean { + return ( + error !== undefined && + error.message.includes('Could not load the default credentials') + ); +} + +/** + * Checks whether the given error is an 'Unable to detect a Project Id in the current environment' error. + * @param {Error} error The error to check. + * @return {boolean} True if the error is an 'Unable to detect a Project Id in the current environment' error, and otherwise false. + */ +export function isProjectIdNotSetInEnvironmentError( + error: grpc.ServiceError | undefined, +): boolean { + return ( + error !== undefined && + error.message.includes( + 'Unable to detect a Project Id in the current environment', + ) + ); +} + +/** + * Checks whether the given error is a 'Create session permission' error. + * @param {Error} error The error to check. + * @return {boolean} True if the error is a 'Create session permission' error, and otherwise false. + */ +export function isCreateSessionPermissionError( + error: grpc.ServiceError | undefined, +): boolean { + return ( + error !== undefined && + error.code === grpc.status.PERMISSION_DENIED && + error.message.includes('spanner.sessions.create') + ); +} + +/** + * Converts any value into an array. Acts as a replacement for `arrify`. + * If the value is null or undefined, returns an empty array. + * If the value is already an array, returns is unchanges. + * Otherwise, wraps the value in a new array. + * @param value The value to convert into an array. + * @returns An array containing the value, or an empty array. + */ +export function toArray(value: any) { + if (value === null || value === undefined) { + return []; + } + + if (Array.isArray(value)) { + return value; + } + + if (typeof value === 'string') { + return [value]; + } + + if (typeof value[Symbol.iterator] === 'function') { + return [...value]; + } + + return [value]; +} + +/** + * Checks if a value is defined. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is NOT `undefined`, otherwise `false`. + */ +export function isDefined(value: any): boolean { + return typeof value !== 'undefined'; +} + +/** + * Checks if a value is null. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is null, otherwise `false`. + */ +export function isNull(value: any): boolean { + return value === null; +} + +/** + * Checks if a value is undefined. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is `undefined`, otherwise `false`. + */ +export function isUndefined(value: any): boolean { + return typeof value === 'undefined'; +} + +/** + * Checks if a value is empty. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is empty, otherwise `false`. + */ +export function isEmpty(value: any): boolean { + const type = Object.prototype.toString.call(value); + if ( + type === '[object Array]' || + type === '[object Arguments]' || + type === '[object String]' + ) { + return value.length === 0; + } + if (type === '[object Object]') { + for (const key in value) { + if (Object.prototype.hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + return !value; +} + +/** + * Checks if a value is a plain javascript object. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is an object, otherwise `false`. + */ +export function isObject(value: any): boolean { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * Checks if a value is a string. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is string, otherwise `false`. + */ +export function isString(value: any): boolean { + return Object.prototype.toString.call(value) === '[object String]'; +} + +/** + * Checks if a value is an array. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is an array, otherwise `false`. + */ +export function isArray(value: any): boolean { + return Array.isArray(value); +} + +/** + * Checks if a value is a Date object. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is a `Date` object, otherwise `false`. + */ +export function isDate(value: any): boolean { + return Object.prototype.toString.call(value) === '[object Date]'; +} + +/** + * Checks if a value is a boolean. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is boolean, otherwise `false`. + */ +export function isBoolean(value: any): boolean { + return Object.prototype.toString.call(value) === '[object Boolean]'; +} + +/** + * Checks if a value is a number. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is a number, otherwise `false`. + */ +export function isNumber(value: any): boolean { + return Object.prototype.toString.call(value) === '[object Number]'; +} + +/** + * Checks if a value is an integer. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is an integer, otherwise `false`. + */ +export function isInteger(value: any): boolean { + return Number.isInteger(value); +} + +/** + * Checks if a value is `NaN`. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is `NaN`, otherwise `false`. + */ +export function isActualNaN(value: any): boolean { + return value !== value; +} + +/** + * Checks if a value is a non-integer (decimal) number. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is a decimal number, otherwise `false`. + */ +export function isDecimal(value: any): boolean { + // A number is a decimal if it's a number but not an integer. + return ( + isNumber(value) && + !isInfinite(value) && + !isActualNaN(value) && + value % 1 !== 0 + ); +} + +/** + * Checks if a value is `Infinity` or `-Infinity`. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is infinite, otherwise `false`. + */ +export function isInfinite(value: any): boolean { + return value === Infinity || value === -Infinity; +} + +/** + * Checks if a value is an `Error` object. + * @param {*} value The value to check. + * @returns {Boolean} `true` if the value is an `Error` object, otherwise `false`. + */ +export function isError(value: any): boolean { + return ( + value instanceof Error || + Object.prototype.toString.call(value) === '[object Error]' + ); +} diff --git a/handwritten/spanner/src/index.ts b/handwritten/spanner/src/index.ts new file mode 100644 index 00000000000..e46f34d109a --- /dev/null +++ b/handwritten/spanner/src/index.ts @@ -0,0 +1,2408 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 {GrpcService, GrpcServiceConfig} from './common-grpc/service'; +import {PreciseDate} from '@google-cloud/precise-date'; +import {replaceProjectIdToken} from '@google-cloud/projectify'; +import {promisifyAll} from '@google-cloud/promisify'; +import * as extend from 'extend'; +import {GoogleAuth, GoogleAuthOptions} from 'google-auth-library'; +import * as path from 'path'; +import {common as p} from 'protobufjs'; +import * as streamEvents from 'stream-events'; +import {EventEmitter} from 'events'; +import * as through from 'through2'; +import { + codec, + Float32, + Float, + Int, + Numeric, + PGNumeric, + PGJsonb, + SpannerDate, + Interval, + Struct, + ProtoMessage, + ProtoEnum, + IProtoMessageParams, + IProtoEnumParams, +} from './codec'; +import {context, propagation} from '@opentelemetry/api'; +import {Backup} from './backup'; +import {Database} from './database'; +import { + Instance, + CreateInstanceCallback, + CreateInstanceResponse, +} from './instance'; +import { + InstanceConfig, + CreateInstanceConfigCallback, + CreateInstanceConfigResponse, +} from './instance-config'; +import { + grpc, + GrpcClientOptions, + CallOptions, + GoogleError, + ClientOptions, +} from 'google-gax'; +import {google, google as instanceAdmin} from '../protos/protos'; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import { + PagedOptions, + PagedResponse, + PagedCallback, + PagedOptionsWithFilter, + CLOUD_RESOURCE_HEADER, + NormalCallback, + getCommonHeaders, +} from './common'; +import {Session} from './session'; +import {SessionPool} from './session-pool'; +import {Table} from './table'; +import { + MutationGroup, + MutationSet, + PartitionedDml, + Snapshot, + Transaction, +} from './transaction'; +import grpcGcpModule = require('grpc-gcp'); +const grpcGcp = grpcGcpModule(grpc); +import * as v1 from './v1'; +import { + ObservabilityOptions, + ensureInitialContextManagerSet, +} from './instrument'; +import { + attributeXGoogSpannerRequestIdToActiveSpan, + injectRequestIDIntoError, + nextSpannerClientId, +} from './request_id_header'; +import {PeriodicExportingMetricReader} from '@opentelemetry/sdk-metrics'; +import {MetricInterceptor} from './metrics/interceptor'; +import {CloudMonitoringMetricsExporter} from './metrics/spanner-metrics-exporter'; +import {MetricsTracerFactory} from './metrics/metrics-tracer-factory'; +import {MetricsTracer} from './metrics/metrics-tracer'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const gcpApiConfig = require('./spanner_grpc_config.json'); + +export type IOperation = instanceAdmin.longrunning.IOperation; + +export type GetInstancesOptions = PagedOptionsWithFilter; + +export type GetInstancesResponse = PagedResponse< + Instance, + instanceAdmin.spanner.admin.instance.v1.IListInstancesResponse +>; +export type GetInstancesCallback = PagedCallback< + Instance, + instanceAdmin.spanner.admin.instance.v1.IListInstancesResponse +>; + +export type GetInstanceConfigsOptions = PagedOptions; +export type GetInstanceConfigsResponse = PagedResponse< + instanceAdmin.spanner.admin.instance.v1.IInstanceConfig, + instanceAdmin.spanner.admin.instance.v1.IListInstanceConfigsResponse +>; +export type GetInstanceConfigsCallback = PagedCallback< + instanceAdmin.spanner.admin.instance.v1.IInstanceConfig, + instanceAdmin.spanner.admin.instance.v1.IListInstanceConfigsResponse +>; + +export interface GetInstanceConfigOptions { + gaxOptions?: CallOptions; +} +export type GetInstanceConfigResponse = [IInstanceConfig]; +export type GetInstanceConfigCallback = NormalCallback; + +export type GetInstanceConfigOperationsOptions = PagedOptionsWithFilter; +export type GetInstanceConfigOperationsResponse = PagedResponse< + IOperation, + instanceAdmin.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse +>; +export type GetInstanceConfigOperationsCallback = PagedCallback< + IOperation, + instanceAdmin.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse +>; + +/** + * Session pool configuration options. + * @property {boolean} [routeToLeaderEnabled=True] If set to false leader aware routing will be disabled. + * Disabling leader aware routing would route all requests in RW/PDML transactions to any region. + * @property {google.spanner.v1.IDirectedReadOptions} [directedReadOptions] Sets the DirectedReadOptions for all ReadRequests and ExecuteSqlRequests for the Client. + * Indicates which replicas or regions should be used for non-transactional reads or queries. + * DirectedReadOptions won't be set for readWrite transactions" + * @property {ObservabilityOptions} [observabilityOptions] Sets the observability options to be used for OpenTelemetry tracing + * @property {boolean} [disableBuiltInMetrics=True] If set to true, built-in metrics will be disabled. + */ +export interface SpannerOptions extends GrpcClientOptions { + apiEndpoint?: string; + servicePath?: string; + port?: number; + sslCreds?: grpc.ChannelCredentials; + routeToLeaderEnabled?: boolean; + directedReadOptions?: google.spanner.v1.IDirectedReadOptions | null; + defaultTransactionOptions?: Pick< + RunTransactionOptions, + 'isolationLevel' | 'readLockMode' + >; + observabilityOptions?: ObservabilityOptions; + disableBuiltInMetrics?: boolean; + interceptors?: any[]; + sessionLabels?: {[key: string]: string}; + /** + * The Trusted Cloud Domain (TPC) DNS of the service used to make requests. + * Defaults to `googleapis.com`. + * We support both camelCase and snake_case for the universe domain. + * Customer may set any of these as both the options are same, + * they both points to universe endpoint. + * There is no preference for any of these option; however exception will be + * thrown if both are set to different values. + */ + universe_domain?: string; + universeDomain?: string; +} +export interface RequestConfig { + client: string; + method: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + reqOpts: any; + gaxOpts?: CallOptions; + headers: {[k: string]: string}; +} +export interface CreateInstanceRequest { + config?: string; + nodes?: number; + processingUnits?: number; + displayName?: string; + labels?: {[k: string]: string} | null; + gaxOptions?: CallOptions; +} +export interface CreateInstanceConfigRequest { + displayName?: string; + replicas?: google.spanner.admin.instance.v1.IReplicaInfo[]; + baseConfig?: string; + labels?: {[k: string]: string} | null; + etag?: string; + validateOnly?: boolean; + gaxOptions?: CallOptions; +} + +/** + * Translates enum values to string keys. + * + * @param E enum type. + */ +export type EnumKey = keyof E; + +/** + * Translates an enum property of an object from enum value to enum key, leaving + * all other properties as-is. + * + * @param T type containing properties to translate. + * @param U name of the enum property. + * @param E enum type to translate. + */ +export type TranslateEnumKeys< + T, + U extends keyof T, + E extends {[index: string]: unknown}, +> = { + [P in keyof T]: P extends U ? EnumKey | null | undefined : T[P]; +}; + +/** + * Retrieves the universe domain. + * + * This function checks for a universe domain in the following order: + * 1. The `universeDomain` property within the provided spanner options. + * 2. The `universe_domain` property within the provided spanner options. + * 3. The `GOOGLE_CLOUD_UNIVERSE_DOMAIN` environment variable. + * 4. If none of the above properties will be set, it will fallback to `googleapis.com`. + * + * For consistency with the Auth client, if the `universe_domain` option or the + * `GOOGLE_CLOUD_UNIVERSE_DOMAIN` env variable is used, this function will also set the + * `universeDomain` property within the provided `SpannerOptions` object. This ensures the + * Spanner client's universe domain aligns with the universe configured for authentication. + * + * @param {SpannerOptions} options - The Spanner client options. + * @returns {string} The universe domain. + */ +function getUniverseDomain(options: SpannerOptions): string { + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + const universeDomain = + options?.universeDomain ?? + options?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; + // if the options.universe_domain/GOOGLE_CLOUD_UNIVERSE_DOMAIN env variable is set, + // set its value to the Spanner `universeDomain` options + // to match it with the universe from Auth Client + if ( + !options?.universeDomain && + (options?.universe_domain || process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN) + ) { + options.universeDomain = universeDomain; + } + return universeDomain; +} + +/** + * [Cloud Spanner](https://cloud.google.com/spanner) is a highly scalable, + * transactional, managed, NewSQL database service. Cloud Spanner solves the + * need for a horizontally-scaling database with consistent global transaction + * and SQL semantics. With Cloud Spanner you don't need to choose between + * consistency and horizontal scaling — you get both. + * + * @class + * + * @see [Cloud Spanner Documentation](https://cloud.google.com/spanner/docs) + * @see [Cloud Spanner Concepts](https://cloud.google.com/spanner/docs/concepts) + * + * @example Install the client library with npm: + * ``` + * npm install --save @google-cloud/spanner + * ``` + * + * @example Create a client that uses Application + * Default Credentials (ADC): + * ``` + * const client = new Spanner(); + * ``` + * + * @example Create a client with explicit + * credentials: + * ``` + * const client = new Spanner({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example include:samples/quickstart.js + * region_tag:spanner_quickstart + * Full quickstart example: + * + * @param {ClientConfig} [options] Configuration options. + */ +class Spanner extends GrpcService { + options: GoogleAuthOptions; + auth: GoogleAuth; + clients_: Map; + instances_: Map; + instanceConfigs_: Map; + projectIdReplaced_: boolean; + projectId_?: string; + projectFormattedName_: string; + commonHeaders_: {[k: string]: string}; + routeToLeaderEnabled = true; + directedReadOptions: google.spanner.v1.IDirectedReadOptions | null; + defaultTransactionOptions: RunTransactionOptions; + _observabilityOptions: ObservabilityOptions | undefined; + sessionLabels: {[key: string]: string} | null; + private _universeDomain: string; + private _isInSecureCredentials: boolean; + private static _isAFEServerTimingEnabled: boolean | undefined; + readonly _nthClientId: number; + + /** + * Placeholder used to auto populate a column with the commit timestamp. + * This can only be used for timestamp columns that have set the option + * "(allow_commit_timestamp=true)" in the schema. + * + * @type {string} + */ + static COMMIT_TIMESTAMP = 'spanner.commit_timestamp()'; + static POSTGRESQL = + google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL; + static GOOGLE_STANDARD_SQL = + google.spanner.admin.database.v1.DatabaseDialect.GOOGLE_STANDARD_SQL; + + /** + * Returns whether AFE (Application Frontend Extension) server timing is enabled. + * + * This method checks the value of the environment variable + * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to the + * string `'true'`, then AFE server timing is considered disabled, and this method + * returns `false`. For all other values (including if the variable is unset), + * the method returns `true`. + * + * @returns {boolean} `true` if AFE server timing is enabled; otherwise, `false`. + */ + public static isAFEServerTimingEnabled = (): boolean => { + if (this._isAFEServerTimingEnabled === undefined) { + this._isAFEServerTimingEnabled = + process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] !== 'true'; + } + return this._isAFEServerTimingEnabled; + }; + + /** Resets the cached value (use in tests if env changes). */ + public static _resetAFEServerTimingForTest(): void { + this._isAFEServerTimingEnabled = undefined; + } + + /** + * Gets the configured Spanner emulator host from an environment variable. + */ + static getSpannerEmulatorHost(): + | {endpoint: string; port?: number} + | undefined { + const endpointWithPort = process.env.SPANNER_EMULATOR_HOST; + if (endpointWithPort) { + if ( + endpointWithPort.startsWith('http:') || + endpointWithPort.startsWith('https:') + ) { + throw new GoogleError( + 'SPANNER_EMULATOR_HOST must not start with a protocol specification (http/https)', + ); + } + const index = endpointWithPort.indexOf(':'); + if (index > -1) { + const portName = endpointWithPort.substring(index + 1); + const port = +portName; + if (!port || port < 1 || port > 65535) { + throw new GoogleError(`Invalid port number: ${portName}`); + } + return { + endpoint: endpointWithPort.substring(0, index), + port: +endpointWithPort.substring(index + 1), + }; + } + return {endpoint: endpointWithPort}; + } + return undefined; + } + + constructor(options?: SpannerOptions) { + const scopes: Array<{}> = []; + const clientClasses = [ + v1.DatabaseAdminClient, + v1.InstanceAdminClient, + v1.SpannerClient, + ]; + for (const clientClass of clientClasses) { + for (const scope of clientClass.scopes) { + if (scopes.indexOf(scope) === -1) { + scopes.push(scope); + } + } + } + + options = Object.assign( + { + libName: 'gccl', + libVersion: require('../../package.json').version, + scopes, + // Add grpc keep alive setting + 'grpc.keepalive_time_ms': 120000, + // Enable grpc-gcp support + 'grpc.callInvocationTransformer': grpcGcp.gcpCallInvocationTransformer, + 'grpc.channelFactoryOverride': grpcGcp.gcpChannelFactoryOverride, + 'grpc.gcpApiConfig': grpcGcp.createGcpApiConfig(gcpApiConfig), + grpc, + }, + options || {}, + ) as {} as SpannerOptions; + + const directedReadOptions = options.directedReadOptions + ? options.directedReadOptions + : null; + delete options.directedReadOptions; + + const defaultTransactionOptions = options.defaultTransactionOptions + ? options.defaultTransactionOptions + : { + isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED, + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }; + delete options.defaultTransactionOptions; + + if ( + options?.universe_domain && + options?.universeDomain && + options?.universe_domain !== options?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + + const emulatorHost = Spanner.getSpannerEmulatorHost(); + if ( + emulatorHost && + emulatorHost.endpoint && + emulatorHost.endpoint.length > 0 + ) { + options.servicePath = emulatorHost.endpoint; + options.port = emulatorHost.port; + options.sslCreds = grpc.credentials.createInsecure(); + } + + const universeEndpoint = getUniverseDomain(options); + const spannerUniverseEndpoint = 'spanner.' + universeEndpoint; + const config = { + baseUrl: + options.apiEndpoint || options.servicePath || spannerUniverseEndpoint, + protosDir: path.resolve(__dirname, '../protos'), + protoServices: { + Operations: { + path: 'google/longrunning/operations.proto', + service: 'longrunning', + }, + }, + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + packageJson: require('../../package.json'), + } as {} as GrpcServiceConfig; + super(config, options); + + if (options.routeToLeaderEnabled === false) { + this.routeToLeaderEnabled = false; + } + + this._isInSecureCredentials = options.sslCreds?._isSecure() === false; + this.options = options; + this.auth = new GoogleAuth(this.options); + this.clients_ = new Map(); + this.instances_ = new Map(); + this.instanceConfigs_ = new Map(); + this.projectIdReplaced_ = false; + this.projectFormattedName_ = 'projects/' + this.projectId; + this.directedReadOptions = directedReadOptions; + this.defaultTransactionOptions = defaultTransactionOptions; + this._observabilityOptions = options.observabilityOptions; + this.sessionLabels = options.sessionLabels || null; + this.commonHeaders_ = getCommonHeaders( + this.projectFormattedName_, + this._observabilityOptions?.enableEndToEndTracing, + ); + ensureInitialContextManagerSet(); + this._nthClientId = nextSpannerClientId(); + this._universeDomain = universeEndpoint; + this.projectId_ = options.projectId; + this.configureMetrics_(options.disableBuiltInMetrics); + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * Gets the InstanceAdminClient object. + * The returned InstanceAdminClient object is a shared, managed instance and should not be manually closed. + * @returns {v1.InstanceAdminClient} The InstanceAdminClient object + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner({ + * projectId: projectId, + * }); + * const instanceAdminClient = spanner.getInstanceAdminClient(); + * ``` + */ + getInstanceAdminClient(): v1.InstanceAdminClient { + const clientName = 'InstanceAdminClient'; + if (!this.clients_.has(clientName)) { + this.clients_.set( + clientName, + new v1[clientName](this.options as ClientOptions), + ); + } + return this.clients_.get(clientName)! as v1.InstanceAdminClient; + } + + /** + * Gets the DatabaseAdminClient object. + * The returned DatabaseAdminClient object is a managed, shared instance and should not be manually closed. + * @returns {v1.DatabaseAdminClient} The DatabaseAdminClient object. + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner({ + * projectId: projectId, + * }); + * const databaseAdminClient = spanner.getDatabaseAdminClient(); + * ``` + */ + getDatabaseAdminClient(): v1.DatabaseAdminClient { + const clientName = 'DatabaseAdminClient'; + if (!this.clients_.has(clientName)) { + this.clients_.set( + clientName, + new v1[clientName](this.options as ClientOptions), + ); + } + return this.clients_.get(clientName)! as v1.DatabaseAdminClient; + } + + /** Closes this Spanner client and cleans up all resources used by it. */ + close(): void { + this.clients_.forEach(c => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const client = c as any; + if (client.operationsClient && client.operationsClient.close) { + client.operationsClient.close(); + } + client.close(); + }); + cleanup().catch(err => { + console.error('Error occured during cleanup: ', err); + }); + } + + /** + * Config for the new instance. + * + * @typedef {object} CreateInstanceRequest + * @property {string} config The name of the instance's configuration. + * @property {number} [nodes=1] The number of nodes allocated to this instance. + * Defaults to 1. + * @property {Object.} [labels] Labels are a flexible and + * lightweight mechanism for organizing cloud resources into groups that + * reflect a customer's organizational needs and deployment strategies. + * Cloud Labels can be used to filter collections of resources. They can + * be used to control how resource metrics are aggregated. And they can + * be used as arguments to policy management rules (e.g. route, + * firewall, load balancing, etc.). + * @property {string} [displayName] The descriptive name for this instance + * as it appears in UIs. Must be unique per project and between 4 and 30 + * characters in length. + * Defaults to the instance unique identifier '' of the full + * instance name of the form 'projects//instances/'. + */ + /** + * @typedef {array} CreateInstanceResponse + * @property {Instance} 0 The new {@link Instance}. + * @property {google.longrunning.Operation} 1 An operation object that can be used to check + * the status of the request. + * @property {google.longrunning.IOperation} 2 The full API response. + */ + /** + * @callback CreateInstanceCallback + * @param {?Error} err Request error, if any. + * @param {Instance} instance The new {@link Instance}. + * @param {google.longrunning.Operation} operation An operation object that can be used to + * check the status of the request. + * @param {google.longrunning.IOperation} apiResponse The full API response. + */ + /** + * Create an instance. + * + * Wrapper around {@link v1.InstanceAdminClient#createInstance}. + * + * @see {@link v1.InstanceAdminClient#createInstance} + * @see [CreateInstance API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance) + * + * @throws {GoogleError} If a name is not provided. + * @throws {GoogleError} If a configuration object is not provided. + * + * @param {string} name The name of the instance to be created. + * @param {CreateInstanceRequest} config Configuration object. + * @param {CreateInstanceCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const config = { + * config: 'regional-us-central1', + * nodes: 1 + * }; + * + * function callback(err, instance, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Instance created successfully. + * }); + * } + * + * spanner.createInstance('new-instance-name', config, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * spanner.createInstance('new-instance-name', config) + * .then(function(data) { + * const instance = data[0]; + * const operation = data[1]; + * return operation.promise(); + * }) + * .then(function() { + * // Instance created successfully. + * }); + * ``` + */ + createInstance( + name: string, + config: CreateInstanceRequest, + ): Promise; + createInstance( + name: string, + config: CreateInstanceRequest, + callback: CreateInstanceCallback, + ): void; + createInstance( + name: string, + config: CreateInstanceRequest, + callback?: CreateInstanceCallback, + ): void | Promise { + if (!name) { + throw new GoogleError('A name is required to create an instance.'); + } + if (!config) { + throw new GoogleError( + ['A configuration object is required to create an instance.'].join(''), + ); + } + const formattedName = Instance.formatName_(this.projectId, name); + const displayName = config.displayName || formattedName.split('/').pop(); + const reqOpts = { + parent: this.projectFormattedName_, + instanceId: formattedName.split('/').pop(), + instance: extend( + { + name: formattedName, + displayName, + nodeCount: config.nodes, + processingUnits: config.processingUnits, + }, + config, + ), + }; + + if (reqOpts.instance.nodeCount && reqOpts.instance.processingUnits) { + throw new GoogleError( + ['Only one of nodeCount or processingUnits can be specified.'].join(''), + ); + } + if (!reqOpts.instance.nodeCount && !reqOpts.instance.processingUnits) { + // If neither nodes nor processingUnits are specified, default to a + // nodeCount of 1. + reqOpts.instance.nodeCount = 1; + } + + delete reqOpts.instance.nodes; + delete reqOpts.instance.gaxOptions; + + if (config.config!.indexOf('/') === -1) { + reqOpts.instance.config = `projects/${this.projectId}/instanceConfigs/${config.config}`; + } + this.request( + { + client: 'InstanceAdminClient', + method: 'createInstance', + reqOpts, + gaxOpts: config.gaxOptions, + headers: this.commonHeaders_, + }, + (err, operation, resp) => { + if (err) { + callback!(err, null, null, resp); + return; + } + const instance = this.instance(formattedName); + instance._observabilityOptions = this._observabilityOptions; + callback!(null, instance, operation, resp); + }, + ); + } + + /** + * Query object for listing instances. + * + * @typedef {object} GetInstancesOptions + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @property {string} [filter] An expression for filtering the results of the + * request. Filter rules are case insensitive. The fields eligible for + * filtering are: + * - **`name`** + * - **`display_name`** + * - **`labels.key`** where key is the name of a label + * + * Some examples of using filters are: + * - **`name:*`** The instance has a name. + * - **`name:Howl`** The instance's name is howl. + * - **`labels.env:*`** The instance has the label env. + * - **`labels.env:dev`** The instance's label env has the value dev. + * - **`name:howl labels.env:dev`** The instance's name is howl and it has + * the label env with value dev. + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + */ + /** + * @typedef {array} GetInstancesResponse + * @property {Instance[]} 0 Array of {@link Instance} instances. + * @property {object} 1 A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetInstancesCallback + * @param {?Error} err Request error, if any. + * @param {Instance[]} instances Array of {@link Instance} instances. + * @param {string} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Get a list of instances. + * + * Wrapper around {@link v1.InstanceAdminClient#listInstances}. + * + * @see {@link v1.InstanceAdminClient#listInstances} + * @see [ListInstances API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.ListInstances) + * + * @param {GetInstancesOptions} [options] Query object for listing instances. + * @param {GetInstancesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * spanner.getInstances(function(err, instances) { + * // `instances` is an array of `Instance` objects. + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * function callback(err, instances, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * spanner.getInstances(nextQuery, callback); + * } + * } + * + * spanner.getInstances({ + * gaxOptions: { + * autoPaginate: false, + * } + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * spanner.getInstances().then(function(data) { + * const instances = data[0]; + * }); + * ``` + */ + getInstances(options?: GetInstancesOptions): Promise; + getInstances(callback: GetInstancesCallback): void; + getInstances( + query: GetInstancesOptions, + callback: GetInstancesCallback, + ): void; + getInstances( + optionsOrCallback?: GetInstancesOptions | GetInstancesCallback, + cb?: GetInstancesCallback, + ): Promise | void { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetInstancesOptions); + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const gaxOpts = extend(true, {}, options.gaxOptions); + + let reqOpts = extend({}, options, { + parent: 'projects/' + this.projectId, + }); + + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetInstancesOptions).pageSize, + pageToken: (gaxOpts as GetInstancesOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetInstancesOptions).pageToken; + delete (gaxOpts as GetInstancesOptions).pageSize; + } + + this.request( + { + client: 'InstanceAdminClient', + method: 'listInstances', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, instances, nextPageRequest, ...args) => { + let instanceInstances: Instance[] | null = null; + if (instances) { + instanceInstances = instances.map(instance => { + const instanceInstance = self.instance(instance.name); + instanceInstance.metadata = instance; + return instanceInstance; + }); + } + const nextQuery = nextPageRequest! + ? extend({}, options, nextPageRequest!) + : null; + callback!(err, instanceInstances, nextQuery, ...args); + }, + ); + } + + /** + * Get a list of {@link Instance} objects as a readable object stream. + * + * Wrapper around {@link v1.InstanceAdminClient#listInstances}. + * + * @see {@link v1.InstanceAdminClient#listInstances} + * @see [ListInstances API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.ListInstances) + * + * @method Spanner#getInstancesStream + * @param {GetInstancesOptions} [options] Query object for listing instances. + * @returns {ReadableStream} A readable stream that emits {@link Instance} + * instances. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * spanner.getInstancesStream() + * .on('error', console.error) + * .on('data', function(instance) { + * // `instance` is an `Instance` object. + * }) + * .on('end', function() { + * // All instances retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * spanner.getInstancesStream() + * .on('data', function(instance) { + * this.end(); + * }); + * ``` + */ + getInstancesStream(options: GetInstancesOptions = {}): NodeJS.ReadableStream { + const gaxOpts = extend(true, {}, options.gaxOptions); + + let reqOpts = extend({}, options, { + parent: 'projects/' + this.projectId, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetInstancesOptions).pageSize, + pageToken: (gaxOpts as GetInstancesOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetInstancesOptions).pageSize; + delete (gaxOpts as GetInstancesOptions).pageToken; + } + + return this.requestStream({ + client: 'InstanceAdminClient', + method: 'listInstancesStream', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }); + } + + /** + * Config for the new instance config. + * + * @typedef {object} CreateInstanceConfigRequest + * @property {string} [displayName] The name of this instance configuration as + * it appears in the user interface. + * @property {google.spanner.admin.instance.v1.IReplicaInfo[]} [replicas] The + * geographic placement of nodes in this instance configuration and their + * replication properties. + * @property {string} [baseConfig] Base configuration name, + * e.g. projects//instanceConfigs/nam3 based on which this + * configuration is created. + * @property {Object.} [labels] Cloud Labels are a flexible + * and lightweight mechanism for organizing cloud resources into groups + * that reflect a customer's organizational needs and deployment + * strategies. Cloud Labels can be used to filter collections of + * resources. They can be used to control how resource metrics are + * aggregated. And they can be used as arguments to policy management + * rules (e.g. route, firewall, load balancing, etc.). + * @property {string} [etag] etag is used for optimistic concurrency control + * as a way to help prevent simultaneous updates of a instance config from + * overwriting each other. + * @property {boolean} [validateOnly] An option to validate, but not actually + * execute, a request, and provide the same response. + */ + /** + * @typedef {array} CreateInstanceConfigResponse + * @property {InstanceConfig} 0 The new {@link google.spanner.admin.instance.v1.InstanceConfig}. + * @property {google.longrunning.Operation} 1 An operation object that can be + * used to check the status of the request. + * @property {google.longrunning.IOperation} 2 The full API response. + */ + /** + * @callback CreateInstanceConfigCallback + * @param {?Error} err Request error, if any. + * @param {InstanceConfig} instanceConfig The new {@link google.spanner.admin.instance.v1.InstanceConfig}. + * @param {google.longrunning.Operation} operation An operation object that + * can be used to check the status of the request. + * @param {google.longrunning.IOperation} apiResponse The full API response. + */ + /** + * Create an instance config. + * + * Wrapper around {@link v1.InstanceAdminClient#createInstanceConfig}. + * + * @see {@link v1.InstanceAdminClient#createInstanceConfig} + * @see [CreateInstanceConfig API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceConfig) + * + * @throws {GoogleError} If a name is not provided. + * @throws {GoogleError} If a configuration object is not provided. + * @throws {GoogleError} If a base config is not provided in the configuration + * object. + * + * @param {string} name The name of the instance config to be created. + * @param {CreateInstanceConfigRequest} config Configuration object. + * @param {CreateInstanceConfigCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const [baseInstanceConfig] = + * await spanner.getInstanceConfig(baseInstanceConfigId); + * const config = { + * baseConfig: baseInstanceConfig.name, + * replicas: baseInstanceConfig.replicas.concat(baseInstanceConfig.optionalReplicas[0]) + * }; + * + * function callback(err, instance, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Instance created successfully. + * }); + * } + * + * spanner.createInstanceConfig('custom-new-instance-config', config, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * spanner.createInstanceConfig('custom-new-instance-config', config) + * .then(function(data) { + * const instanceConfig = data[0]; + * const operation = data[1]; + * return operation.promise(); + * }) + * .then(function() { + * // Instance config created successfully. + * }); + * ``` + */ + createInstanceConfig( + name: string, + config: CreateInstanceConfigRequest, + ): Promise; + createInstanceConfig( + name: string, + config: CreateInstanceConfigRequest, + callback: CreateInstanceConfigCallback, + ): void; + createInstanceConfig( + name: string, + config: CreateInstanceConfigRequest, + callback?: CreateInstanceConfigCallback, + ): void | Promise { + if (!name) { + throw new GoogleError('A name is required to create an instance config.'); + } + if (!config) { + throw new GoogleError( + [ + 'A configuration object is required to create an instance config.', + ].join(''), + ); + } + if (!config.baseConfig) { + throw new GoogleError( + ['Base instance config is required to create an instance config.'].join( + '', + ), + ); + } + const formattedName = InstanceConfig.formatName_(this.projectId, name); + const displayName = config.displayName || formattedName.split('/').pop(); + const reqOpts = { + parent: this.projectFormattedName_, + instanceConfigId: formattedName.split('/').pop(), + instanceConfig: extend( + { + name: formattedName, + displayName, + }, + config, + ), + validateOnly: config.validateOnly, + }; + + if (config.baseConfig!.indexOf('/') === -1) { + reqOpts.instanceConfig.baseConfig = `projects/${this.projectId}/instanceConfigs/${config.baseConfig}`; + } + + // validateOnly need not be passed in if it is null. + if (reqOpts.validateOnly === null || reqOpts.validateOnly === undefined) + delete reqOpts.validateOnly; + + // validateOnly and gaxOptions are not fields in InstanceConfig. + delete reqOpts.instanceConfig.validateOnly; + delete reqOpts.instanceConfig.gaxOptions; + + this.request( + { + client: 'InstanceAdminClient', + method: 'createInstanceConfig', + reqOpts, + gaxOpts: config.gaxOptions, + headers: this.commonHeaders_, + }, + (err, operation, resp) => { + if (err) { + callback!(err, null, null, resp); + return; + } + const instanceConfig = this.instanceConfig(formattedName); + callback!(null, instanceConfig, operation, resp); + }, + ); + } + + /** + * Lists the supported instance configurations for a given project. + * + * @typedef {object} GetInstanceConfigsOptions + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} GetInstanceConfigsResponse + * @property {object[]} 0 List of all available instance configs. + * @property {string} 0.name The unique identifier for the instance config. + * @property {string} 0.displayName The name of the instance config as it + * appears in UIs. + * @property {google.spanner.admin.instance.v1.IReplicaInfo[]} 0.replicas The replicas used by + * this instance config. + * @property {string[]} 0.leaderOptions The possible leader options for this instance config. + * @property {object} 1 A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetInstanceConfigsCallback + * @param {?Error} err Request error, if any. + * @param {object[]} instanceConfigs List of all available instance configs. + * @param {string} instanceConfigs.name The unique identifier for the instance + * config. + * @param {string} instanceConfigs.displayName The name of the instance config + * as it appears in UIs. + * @param {google.spanner.admin.instance.v1.IReplicaInfo[]} instanceConfigs.replicas The replicas used by + * this instance config. + * @param {string[]} instanceConfigs.leaderOptions The possible leader options for this instance config. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Get a list of instance configs. + * + * Wrapper around {@link v1.InstanceAdminClient#listInstanceConfigs}. + * + * @see {@link v1.InstanceAdminClient#listInstanceConfigs} + * @see [ListInstanceConfigs API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs) + * + * @param {GetInstanceConfigsOptions} [options] Query object for listing instance + * configs. + * @param {GetInstanceConfigsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * spanner.getInstanceConfigs(function(err, instanceConfigs) { + * // `instanceConfigs` is an array of instance configuration descriptors. + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * function callback(err, instanceConfigs, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * spanner.getInstanceConfigs(nextQuery, callback); + * } + * } + * + * spanner.getInstanceConfigs({ + * gaxOptions: { + * autoPaginate: false, + * } + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * spanner.getInstanceConfigs().then(function(data) { + * const instanceConfigs = data[0]; + * }); + * ``` + */ + getInstanceConfigs( + query?: GetInstanceConfigsOptions, + ): Promise; + getInstanceConfigs(callback: GetInstanceConfigsCallback): void; + getInstanceConfigs( + query: GetInstanceConfigsOptions, + callback: GetInstanceConfigsCallback, + ): void; + getInstanceConfigs( + optionsOrCallback?: GetInstanceConfigsOptions | GetInstanceConfigsCallback, + cb?: GetInstanceConfigsCallback, + ): Promise | void { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetInstanceConfigsOptions); + + const gaxOpts = extend(true, {}, options.gaxOptions); + let reqOpts = extend({}, options, { + parent: 'projects/' + this.projectId, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetInstanceConfigsOptions).pageSize, + pageToken: (gaxOpts as GetInstanceConfigsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetInstanceConfigsOptions).pageSize; + delete (gaxOpts as GetInstanceConfigsOptions).pageToken; + } + + return this.request( + { + client: 'InstanceAdminClient', + method: 'listInstanceConfigs', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, instanceConfigs, nextPageRequest, ...args) => { + const nextQuery = nextPageRequest! + ? extend({}, options, nextPageRequest!) + : null; + callback!(err, instanceConfigs, nextQuery, ...args); + }, + ); + } + + /** + * Get a list of instance configs as a readable object stream. + * + * Wrapper around {@link v1.InstanceAdminClient#listInstanceConfigsStream}. + * + * @see {@link v1.InstanceAdminClient#listInstanceConfigsStream} + * @see [ListInstanceConfigs API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs) + * + * @method Spanner#getInstanceConfigsStream + * @param {GetInstanceConfigsOptions} [options] Query object for listing instance + * configs. + * @returns {ReadableStream} A readable stream that emits instance configs. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * spanner.getInstanceConfigsStream() + * .on('error', console.error) + * .on('data', function(instanceConfig) {}) + * .on('end', function() { + * // All instances retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * spanner.getInstanceConfigsStream() + * .on('data', function(instanceConfig) { + * this.end(); + * }); + * ``` + */ + getInstanceConfigsStream( + options: GetInstanceConfigsOptions = {}, + ): NodeJS.ReadableStream { + const gaxOpts = extend(true, {}, options.gaxOptions); + + let reqOpts = extend({}, options, { + parent: 'projects/' + this.projectId, + }); + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetInstancesOptions).pageSize, + pageToken: (gaxOpts as GetInstancesOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetInstancesOptions).pageSize; + delete (gaxOpts as GetInstancesOptions).pageToken; + } + + delete reqOpts.gaxOptions; + return this.requestStream({ + client: 'InstanceAdminClient', + method: 'listInstanceConfigsStream', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }); + } + + /** + * Gets the instance configuration with the specified name. + */ + /** + * @typedef {array} GetInstanceConfigResponse + * @property {object[]} 0 The metadata of the instance config. + * @property {string} 0.name The unique identifier for the instance config. + * @property {string} 0.displayName The name of the instance config as it + * appears in UIs. + * @property {google.spanner.admin.instance.v1.IReplicaInfo[]} 0.replicas The replicas used by + * this instance config. + * @property {string[]} 0.leaderOptions The possible leader options for this instance config. + */ + /** + * @callback GetInstanceConfigCallback + * @param {?Error} err Request error, if any. + * @param {object} instanceConfig The metadata of the instance config. + * @param {string} instanceConfig.name The unique identifier for the instance + * config. + * @param {string} instanceConfig.displayName The name of the instance config + * as it appears in UIs. + * @param {google.spanner.admin.instance.v1.IReplicaInfo[]} instanceConfig.replicas The replicas used by + * this instance config. + * @param {string[]} 0.leaderOptions The possible leader options for this instance config. + */ + /** + * Get a specific instance config. + * + * Wrapper around {@link v1.InstanceAdminClient#getInstanceConfig}. + * + * @see {@link v1.InstanceAdminClient#getInstanceConfig} + * @see [GetInstanceConfig API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig) + * + * @param {string} [name] The name of the instance config to get. + * @param {GetInstanceConfigCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * spanner.getInstanceConfig('nam6', function(err, instanceConfig) { + * // `instanceConfig` is an instance configuration descriptor. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * spanner.getInstanceConfig().then(function(data) { + * const instanceConfig = data[0]; + * }); + * ``` + */ + getInstanceConfig(name: string): Promise; + getInstanceConfig( + name: string, + options: GetInstanceConfigOptions, + ): Promise; + getInstanceConfig(name: string, callback: GetInstanceConfigCallback): void; + getInstanceConfig( + name: string, + options: GetInstanceConfigOptions, + callback: GetInstanceConfigCallback, + ): void; + getInstanceConfig( + name: string, + optionsOrCallback?: GetInstanceConfigOptions | GetInstanceConfigCallback, + cb?: GetInstanceConfigCallback, + ): Promise | void { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetInstanceConfigOptions); + + const reqOpts = extend( + {}, + { + name: 'projects/' + this.projectId + '/instanceConfigs/' + name, + }, + ); + const gaxOpts = extend({}, options.gaxOptions); + + return this.request( + { + client: 'InstanceAdminClient', + method: 'getInstanceConfig', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, instanceConfig) => { + callback!(err, instanceConfig); + }, + ); + } + + /** + * Query object for listing instance config operations. + * + * @typedef {object} GetInstanceConfigOperationsOptions + * @property {string} [filter] An expression for filtering the results of the + * request. Filter can be configured as outlined in + * {@link v1.DatabaseAdminClient#listInstanceConfigOperations}. + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} GetInstanceConfigOperationsResponse + * @property {google.longrunning.IOperation[]} 0 Array of {@link IOperation} instances. + * @property {object} 1 A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetInstanceConfigOperationsCallback + * @param {?Error} err Request error, if any. + * @param {google.longrunning.IOperation[]} 0 Array of {@link IOperation} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * List pending and completed instance config operations. + * + * @see {@link #listOperations} + * + * @param {GetInstanceConfigOperationsOptions} [options] The query object for + * listing InstanceConfig operations. + * @param {gax.CallOptions} [options.gaxOptions] The request configuration + * options, See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @returns {Promise} When resolved, + * contains a paged list of InstanceConfig operations. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const [operations] = await spanner.getInstanceConfigOperations(); + * + * //- + * // To manually handle pagination, set autoPaginate:false in gaxOptions. + * //- + * let pageToken = undefined; + * do { + * const [operations, , response] = await spanner.getInstanceConfigOperations({ + * pageSize: 3, + * pageToken, + * gaxOptions: {autoPaginate: false}, + * }); + * operations.forEach(operation => { + * // Do something with operation + * }); + * pageToken = response.nextPageToken; + * } while (pageToken); + * ``` + */ + getInstanceConfigOperations( + options?: GetInstanceConfigOperationsOptions, + ): Promise; + getInstanceConfigOperations( + callback: GetInstanceConfigOperationsCallback, + ): void; + getInstanceConfigOperations( + options: GetInstanceConfigOperationsOptions, + callback: GetInstanceConfigOperationsCallback, + ): void; + getInstanceConfigOperations( + optionsOrCallback?: + | GetInstanceConfigOperationsOptions + | GetInstanceConfigOperationsCallback, + cb?: GetInstanceConfigOperationsCallback, + ): void | Promise { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetInstanceConfigOperationsOptions); + const gaxOpts = extend(true, {}, options.gaxOptions); + let reqOpts = extend({}, options, { + parent: this.projectFormattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However, values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetInstanceConfigOperationsOptions).pageSize, + pageToken: (gaxOpts as GetInstanceConfigOperationsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetInstanceConfigOperationsOptions).pageSize; + delete (gaxOpts as GetInstanceConfigOperationsOptions).pageToken; + } + + this.request( + { + client: 'InstanceAdminClient', + method: 'listInstanceConfigOperations', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, operations, nextPageRequest, ...args) => { + const nextQuery = nextPageRequest! + ? extend({}, options, nextPageRequest!) + : null; + + callback!(err, operations, nextQuery, ...args); + }, + ); + } + + /** + * Get a reference to an Instance object. + * + * @throws {GoogleError} If a name is not provided. + * + * @param {string} name The name of the instance. + * @returns {Instance} An Instance object. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * ``` + */ + instance(name: string): Instance { + if (!name) { + throw new GoogleError('A name is required to access an Instance object.'); + } + const key = name.split('/').pop()!; + if (!this.instances_.has(key)) { + this.instances_.set(key, new Instance(this, name)); + } + return this.instances_.get(key)!; + } + + /** + * Get a reference to an InstanceConfig object. + * + * @throws {GoogleError} If a name is not provided. + * + * @param {string} name The name of the instance config. + * @returns {InstanceConfig} An InstanceConfig object. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instanceConfig = spanner.instanceConfig('my-instance-config'); + * ``` + */ + instanceConfig(name: string): InstanceConfig { + if (!name) { + throw new GoogleError( + 'A name is required to access an InstanceConfig object.', + ); + } + const key = name.split('/').pop()!; + if (!this.instanceConfigs_.has(key)) { + this.instanceConfigs_.set(key, new InstanceConfig(this, name)); + } + return this.instanceConfigs_.get(key)!; + } + + /** + * Setup the OpenTelemetry metrics capturing for service metrics to Google Cloud Monitoring. + */ + configureMetrics_(disableBuiltInMetrics?: boolean) { + // Only enable metrics if not explicitly disabled and we are not using + // insecure credentials. + const metricsEnabled = + process.env.SPANNER_DISABLE_BUILTIN_METRICS !== 'true' && + !disableBuiltInMetrics && + !this._isInSecureCredentials; + if (metricsEnabled) { + try { + this.auth.getProjectId((err, projectId) => { + if (err || !projectId) { + console.error( + 'Unable to get Project Id for client side metrics, will skip exporting client' + + ' side metrics' + + err, + ); + return; + } + + MetricsTracerFactory.enabled = metricsEnabled; + this.projectId_ = projectId; + const factory = MetricsTracerFactory.getInstance(projectId); + const periodicReader = new PeriodicExportingMetricReader({ + exporter: new CloudMonitoringMetricsExporter( + {auth: this.auth}, + projectId, + ), + exportIntervalMillis: 60000, + }); + // Retrieve the MeterProvider to trigger construction + factory!.getMeterProvider([periodicReader]); + }); + } catch (err) { + console.error( + 'Unable to configure client side metrics, will skip exporting client' + + ' side metrics' + + err, + ); + } + } + } + + /** + * Prepare a gapic request. This will cache the GAX client and replace + * {{projectId}} placeholders, if necessary. + * + * @private + * + * @param {object} config Request config + * @param {function} callback Callback function + */ + prepareGapicRequest_(config, callback) { + this.auth.getProjectId((err, projectId) => { + if (err) { + callback(err); + return; + } + const clientName = config.client; + try { + if (!this.clients_.has(clientName)) { + this.clients_.set(clientName, new v1[clientName](this.options)); + } + } catch (err) { + callback(err, null); + } + const gaxClient = this.clients_.get(clientName)!; + let reqOpts = extend(true, {}, config.reqOpts); + reqOpts = replaceProjectIdToken(reqOpts, projectId!); + // It would have been preferable to replace the projectId already in the + // constructor of Spanner, but that is not possible as auth.getProjectId + // is an async method. This is therefore the first place where we have + // access to the value that should be used instead of the placeholder. + if (!this.projectIdReplaced_) { + this.projectId = replaceProjectIdToken(this.projectId, projectId!); + this.projectFormattedName_ = replaceProjectIdToken( + this.projectFormattedName_, + projectId!, + ); + this.instances_.forEach(instance => { + instance.formattedName_ = replaceProjectIdToken( + instance.formattedName_, + projectId!, + ); + instance.databases_.forEach(database => { + database.formattedName_ = replaceProjectIdToken( + database.formattedName_, + projectId!, + ); + }); + }); + this.projectIdReplaced_ = true; + } + config.headers[CLOUD_RESOURCE_HEADER] = replaceProjectIdToken( + config.headers[CLOUD_RESOURCE_HEADER], + projectId!, + ); + // Do context propagation + propagation.inject(context.active(), config.headers, { + set: (carrier, key, value) => { + carrier[key] = value; // Set the span context (trace and span ID) + }, + }); + // Attach the x-goog-spanner-request-id to the currently active span. + attributeXGoogSpannerRequestIdToActiveSpan(config); + const interceptors: any[] = []; + if (MetricsTracerFactory.enabled) { + interceptors.push(MetricInterceptor); + } + const requestFn = gaxClient[config.method].bind( + gaxClient, + reqOpts, + // Add headers to `gaxOpts` + extend(true, {}, config.gaxOpts, { + otherArgs: { + headers: config.headers, + options: { + interceptors: interceptors, + }, + }, + }), + ); + + // Wrap requestFn to inject the spanner request id into every returned error. + const wrappedRequestFn = (...args) => { + const hasCallback = + args && + args.length > 0 && + typeof args[args.length - 1] === 'function'; + + switch (hasCallback) { + case true: { + const cb = args[args.length - 1]; + const priorArgs = args.slice(0, args.length - 1); + requestFn(...priorArgs, (...results) => { + if (results && results.length > 0) { + const err = results[0] as Error; + injectRequestIDIntoError(config, err); + } + + cb(...results); + }); + return; + } + + case false: { + const res = requestFn(...args); + const stream = res as EventEmitter; + if (stream) { + stream.on('error', err => { + injectRequestIDIntoError(config, err as Error); + }); + } + + const originallyPromise = res instanceof Promise; + if (!originallyPromise) { + return res; + } + + return new Promise((resolve, reject) => { + requestFn(...args) + .then(resolve) + .catch(err => { + injectRequestIDIntoError(config, err as Error); + reject(err); + }); + }); + } + } + }; + + callback(null, wrappedRequestFn); + }); + } + + /** + * Funnel all API requests through this method to be sure we have a project + * ID. + * + * @param {object} config Configuration object. + * @param {object} config.gaxOpts GAX options. + * @param {function} config.method The gax method to call. + * @param {object} config.reqOpts Request options. + * @param {function} [callback] Callback function. + * @returns {Promise} + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + request(config: any, callback?: any): any { + let metricsTracer: MetricsTracer | null = null; + if (config.client === 'SpannerClient' && this.projectId_) { + metricsTracer = + MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer( + config.method, + config.reqOpts.database ?? config.reqOpts.session, + config.headers['x-goog-spanner-request-id'], + ) ?? null; + } + metricsTracer?.recordOperationStart(); + if (typeof callback === 'function') { + this.prepareGapicRequest_(config, (err, requestFn) => { + if (err) { + callback(err); + metricsTracer?.recordOperationCompletion(); + } else { + const wrappedCallback = (...args) => { + metricsTracer?.recordOperationCompletion(); + callback(...args); + }; + requestFn(wrappedCallback); + } + }); + } else { + return new Promise((resolve, reject) => { + this.prepareGapicRequest_(config, (err, requestFn) => { + if (err) { + metricsTracer?.recordOperationCompletion(); + reject(err); + } else { + const result = requestFn(); + if (result && typeof result.then === 'function') { + result + .then(val => { + metricsTracer?.recordOperationCompletion(); + resolve(val); + }) + .catch(error => { + metricsTracer?.recordOperationCompletion(); + reject(error); + }); + } else { + metricsTracer?.recordOperationCompletion(); + resolve(result); + } + } + }); + }); + } + } + + /** + * Funnel all streaming API requests through this method to be sure we have a + * project ID. + * + * @param {object} config Configuration object. + * @param {object} config.gaxOpts GAX options. + * @param {function} config.method The gax method to call. + * @param {object} config.reqOpts Request options. + * @param {function} [callback] Callback function. + * @returns {Stream} + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + requestStream(config): any { + let metricsTracer: MetricsTracer | null = null; + if (config.client === 'SpannerClient' && this.projectId_) { + metricsTracer = + MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer( + config.method, + config.reqOpts.session ?? config.reqOpts.database, + config.headers['x-goog-spanner-request-id'], + ) ?? null; + } + metricsTracer?.recordOperationStart(); + const stream = streamEvents(through.obj()); + stream.once('reading', () => { + this.prepareGapicRequest_(config, (err, requestFn) => { + if (err) { + stream.destroy(err); + return; + } + requestFn() + .on('error', err => { + stream.destroy(err); + }) + .pipe(stream); + }); + }); + stream.on('finish', () => { + stream.destroy(); + }); + stream.on('close', () => { + metricsTracer?.recordOperationCompletion(); + }); + return stream; + } + + static date(dateString?: string); + static date(year: number, month: number, date: number); + /** + * Helper function to get a Cloud Spanner Date object. + * + * DATE types represent a logical calendar date, independent of time zone. + * DATE values do not represent a specific 24-hour period. Rather, a given + * DATE value represents a different 24-hour period when interpreted in a + * different time zone. Because of this, all values passed to + * {@link Spanner.date} will be interpreted as local time. + * + * To represent an absolute point in time, use {@link Spanner.timestamp}. + * + * @param {string|number} [date] String representing the date or number + * representing the year. + * @param {number} [month] Number representing the month. + * @param {number} [date] Number representing the date. + * @returns {SpannerDate} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const date = Spanner.date('08-20-1969'); + * ``` + */ + static date( + dateStringOrYear?: string | number, + month?: number, + date?: number, + ): SpannerDate { + if (typeof dateStringOrYear === 'number') { + return new codec.SpannerDate(dateStringOrYear, month!, date!); + } + return new codec.SpannerDate(dateStringOrYear); + } + + /** + * Date object with nanosecond precision. Supports all standard Date arguments + * in addition to several custom types. + * @external PreciseDate + * @see {@link https://github.com/googleapis/nodejs-precise-date|PreciseDate} + */ + /** + * Helper function to get a Cloud Spanner Timestamp object. + * + * String timestamps should have a canonical format of + * `YYYY-[M]M-[D]D[( |T)[H]H:[M]M:[S]S[.DDDDDDDDD]]Z` + * + * **Timestamp values must be expressed in Zulu time and cannot include a UTC + * offset.** + * + * @see https://cloud.google.com/spanner/docs/data-types#timestamp-type + * + * @param {string|number|google.protobuf.Timestamp|external:PreciseDate} + * [timestamp] Either a RFC 3339 timestamp formatted string or a + * {@link google.protobuf.Timestamp} object. If a PreciseDate is given, it + * will return that timestamp as is. + * @returns {external:PreciseDate} + * + * @example + * ``` + * const timestamp = Spanner.timestamp('2019-02-08T10:34:29.481145231Z'); + * + * ``` + * @example With a `google.protobuf.Timestamp` object + * ``` + * const [seconds, nanos] = process.hrtime(); + * const timestamp = Spanner.timestamp({seconds, nanos}); + * ``` + * + * @example With a Date timestamp + * ``` + * const timestamp = Spanner.timestamp(Date.now()); + * ``` + */ + static timestamp( + value?: string | number | p.ITimestamp | PreciseDate, + ): PreciseDate { + value = value || Date.now(); + if (value instanceof PreciseDate) { + return value; + } + return new PreciseDate(value as number); + } + + /** + * Helper function to get a Cloud Spanner Float32 object. + * + * @param {string|number} value The float as a number or string. + * @returns {Float32} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const float = Spanner.float32(10); + * ``` + */ + static float32(value): Float32 { + return new codec.Float32(value); + } + + /** + * Helper function to get a Cloud Spanner Float64 object. + * + * @param {string|number} value The float as a number or string. + * @returns {Float} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const float = Spanner.float(10); + * ``` + */ + static float(value): Float { + return new codec.Float(value); + } + + /** + * Helper function to get a Cloud Spanner Int64 object. + * + * @param {string|number} value The int as a number or string. + * @returns {Int} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const int = Spanner.int(10); + * ``` + */ + static int(value): Int { + return new codec.Int(value); + } + + /** + * Helper function to get a Cloud Spanner Numeric object. + * + * @param {string} value The numeric value as a string. + * @returns {Numeric} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const numeric = Spanner.numeric("3.141592653"); + * ``` + */ + static numeric(value): Numeric { + return new codec.Numeric(value); + } + + /** + * Helper function to get a Cloud Spanner pgNumeric object. + * + * @param {string} value The pgNumeric value as a string. + * @returns {PGNumeric} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const pgNumeric = Spanner.pgNumeric("3.141592653"); + * ``` + */ + static pgNumeric(value): PGNumeric { + return new codec.PGNumeric(value); + } + + /** + * Helper function to get a Cloud Spanner pgJsonb object. + * + * @param {object|string} value The pgJsonb value as a string or object. + * @returns {PGJsonb} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const pgJsonb1 = Spanner.pgJsonb({rating: 6}); + * const pgJsonb2 = Spanner.pgJsonb(`[ + * { + * "name": null, + * "open": true + * }]`) + * ``` + */ + static pgJsonb(value): PGJsonb { + return new codec.PGJsonb(value); + } + + /** + * Helper function to get a Cloud Spanner Interval object. + * + * @param {number} months The months part of Interval as number. + * @param {number} days The days part of Interval as number. + * @param {bigint} nanoseconds The nanoseconds part of Interval as bigint. + * @returns {Interval} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const interval = Spanner.Interval(10, 20, BigInt(30)); + * ``` + */ + static interval(months: number, days: number, nanoseconds: bigint): Interval { + return new codec.Interval(months, days, nanoseconds); + } + + /** + * @typedef IProtoMessageParams + * @property {object} value Proto Message value as serialized-buffer or message object. + * @property {string} fullName Fully-qualified path name of proto message. + * @property {Function} [messageFunction] Function generated by protobufs containing + * helper methods for deserializing and serializing messages. + */ + /** + * Helper function to get a Cloud Spanner proto Message object. + * + * @param {IProtoMessageParams} params The proto message value params + * @returns {ProtoMessage} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const protoMessage = Spanner.protoMessage({ + * value: singerInfo, + * messageFunction: music.SingerInfo, + * fullName: "examples.spanner.music.SingerInfo" + * }); + * ``` + */ + static protoMessage(params: IProtoMessageParams): ProtoMessage { + return new codec.ProtoMessage(params); + } + + /** + * @typedef IProtoEnumParams + * @property {string | number} value Proto Enum value as a string constant or + * an integer constant. + * @property {string} fullName Fully-qualified path name of proto enum. + * @property {object} [enumObject] An enum object generated by protobufjs-cli. + */ + /** + * Helper function to get a Cloud Spanner proto enum object. + * + * @param {IProtoEnumParams} params The proto enum value params in the format of + * @code{IProtoEnumParams} + * @returns {ProtoEnum} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const protoEnum = Spanner.protoEnum({ + * value: 'ROCK', + * enumObject: music.Genre, + * fullName: "examples.spanner.music.Genre" + * }); + * ``` + */ + static protoEnum(params: IProtoEnumParams): ProtoEnum { + return new codec.ProtoEnum(params); + } + + /** + * Helper function to get a Cloud Spanner Struct object. + * + * @param {object} value The struct as a JSON object. + * @returns {Struct} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const struct = Spanner.struct({ + * user: 'bob', + * age: 32 + * }); + * ``` + */ + static struct(value?): Struct { + if (Array.isArray(value)) { + return codec.Struct.fromArray(value); + } + return codec.Struct.fromJSON(value); + } +} + +let cleanupCalled = false; +const cleanup = async () => { + if (cleanupCalled) return; + cleanupCalled = true; + await MetricsTracerFactory.resetInstance(); +}; + +// For signals (let process exit naturally) +process.on('SIGINT', async () => { + await cleanup(); +}); +process.on('SIGTERM', async () => { + await cleanup(); +}); + +// For natural exit (Node will NOT wait for async, so we must block the event loop) +process.on('beforeExit', () => { + const done = cleanup(); + if (done && typeof done.then === 'function') { + // Handle promise rejection + done.catch(err => { + console.error('Cleanup error before exit:', err); + }); + } +}); + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Spanner, { + exclude: [ + 'date', + 'float32', + 'float', + 'instance', + 'instanceConfig', + 'int', + 'numeric', + 'pgNumeric', + 'pgJsonb', + 'operation', + 'timestamp', + 'interval', + 'getInstanceAdminClient', + 'getDatabaseAdminClient', + ], +}); + +/** + * The default export of the `@google-cloud/spanner` package is the + * {@link Spanner} class. + * + * See {@link Spanner} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {constructor} @google-cloud/spanner + * @alias nodejs-spanner + * + * @example Install the client library with npm: + * ``` + * npm install --save @google-cloud/spanner + * ``` + * + * @example Import the client library + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * ``` + * + * @example Create a client that uses Application + * Default Credentials (ADC): + * ``` + * const client = new Spanner(); + * ``` + * + * @example Create a client with explicit + * credentials: + * ``` + * const client = new Spanner({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example include:samples/quickstart.js + * region_tag:spanner_quickstart + * Full quickstart example: + */ +export {Spanner}; + +/** + * {@link Instance} class. + * + * @name Spanner.Instance + * @see Instance + * @type {Constructor} + */ +export {Instance}; + +/** + * {@link InstanceConfig} class. + * + * @name Spanner.InstanceConfig + * @see InstanceConfig + * @type {Constructor} + */ +export {InstanceConfig}; + +/** + * {@link Database} class. + * + * @name Spanner.Database + * @see Database + * @type {Constructor} + */ +export {Database}; + +/** + * {@link Backup} class. + * + * @name Spanner.Backup + * @see Backup + * @type {Constructor} + */ +export {Backup}; + +/** + * {@link Session} class. + * + * @name Spanner.Session + * @see Session + * @type {Constructor} + */ +export {Session}; + +/** + * {@link SessionPool} class. + * + * @name Spanner.SessionPool + * @see SessionPool + * @type {Constructor} + */ +export {SessionPool}; + +/** + * {@link Table} class. + * + * @name Spanner.Table + * @see Table + * @type {Constructor} + */ +export {Table}; + +/** + * {@link PartitionedDml} class. + * + * @name Spanner.PartitionedDml + * @see PartitionedDml + * @type {Constructor} + */ +export {PartitionedDml}; + +/** + * {@link Snapshot} class. + * + * @name Spanner.Snapshot + * @see Snapshot + * @type {Constructor} + */ +export {Snapshot}; + +/** + * {@link Transaction} class. + * + * @name Spanner.Transaction + * @see Transaction + * @type {Constructor} + */ +export {Transaction}; + +/** + * {@link MutationGroup} class. + * + * @name Spanner.MutationGroup + * @see MutationGroup + * @type {Constructor} + */ +export {MutationGroup}; + +/** + * {@link MutationSet} class. + * + * @name Spanner.MutationSet + * @see MutationSet + * @type {Constructor} + */ +export {MutationSet}; + +/** + * @type {object} + * @property {constructor} DatabaseAdminClient + * Reference to {@link v1.DatabaseAdminClient} + * @property {constructor} InstanceAdminClient + * Reference to {@link v1.InstanceAdminClient} + * @property {constructor} SpannerClient + * Reference to {@link v1.SpannerClient} + */ +import * as protos from '../protos/protos'; +import IInstanceConfig = instanceAdmin.spanner.admin.instance.v1.IInstanceConfig; +import {RunTransactionOptions} from './transaction-runner'; +export {v1, protos}; +export default {Spanner}; +export {Float32, Float, Int, Struct, Numeric, PGNumeric, SpannerDate, Interval}; +export {ObservabilityOptions}; diff --git a/handwritten/spanner/src/instance-config.ts b/handwritten/spanner/src/instance-config.ts new file mode 100644 index 00000000000..626edee9d7e --- /dev/null +++ b/handwritten/spanner/src/instance-config.ts @@ -0,0 +1,534 @@ +/** + * Copyright 2022 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 {ServiceObjectConfig} from '@google-cloud/common'; +const common = require('./common-grpc/service-object'); + +import {google as instanceAdmin} from '../protos/protos'; +import {Operation as GaxOperation} from 'google-gax'; +import snakeCase = require('lodash.snakecase'); +import { + CLOUD_RESOURCE_HEADER, + LongRunningCallback, + RequestCallback, + ResourceCallback, + NormalCallback, +} from './common'; +import { + CreateInstanceConfigRequest, + GetInstanceConfigCallback, + GetInstanceConfigOptions, + GetInstanceConfigResponse, + RequestConfig, + Spanner, +} from './index'; +import {promisifyAll} from '@google-cloud/promisify'; +import {CallOptions, grpc} from 'google-gax'; +import extend = require('extend'); + +export type IOperation = instanceAdmin.longrunning.IOperation; + +export type CreateInstanceConfigCallback = LongRunningCallback; +export type SetInstanceConfigMetadataCallback = ResourceCallback< + GaxOperation, + IOperation +>; +export type DeleteInstanceConfigCallback = + NormalCallback; +export type ExistsInstanceConfigCallback = NormalCallback; + +export type CreateInstanceConfigResponse = [ + InstanceConfig, + GaxOperation, + IOperation, +]; +export type SetInstanceConfigMetadataResponse = [GaxOperation, IOperation]; +export type DeleteInstanceConfigResponse = [instanceAdmin.protobuf.IEmpty]; +export type ExistsInstanceConfigResponse = boolean; + +export type IInstanceConfig = + instanceAdmin.spanner.admin.instance.v1.IInstanceConfig; + +interface InstanceConfigRequest { + ( + config: RequestConfig, + callback: ResourceCallback, + ): void; + (config: RequestConfig, callback: RequestCallback): void; + (config: RequestConfig, callback: RequestCallback): void; +} + +export interface SetInstanceConfigMetadataRequest { + instanceConfig: IInstanceConfig; + validateOnly?: boolean; + gaxOpts?: CallOptions; +} + +interface DeleteInstanceConfigRequest { + etag?: string; + validateOnly?: boolean; + gaxOpts?: CallOptions; +} +/** + * The {@link InstanceConfig} class represents a possible configuration for a + * Cloud Spanner instance. + * + * Create an `InstanceConfig` object to interact with a Cloud Spanner instance + * config. + * + * @class + * + * @param {Spanner} spanner {@link Spanner} instance. + * @param {string} name Name of the instance config. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instanceConfig('my-instance-config'); + * ``` + */ +class InstanceConfig extends common.GrpcServiceObject { + formattedName_: string; + request: InstanceConfigRequest; + metadata?: IInstanceConfig; + resourceHeader_: {[k: string]: string}; + + constructor(spanner: Spanner, name: string) { + const formattedName_ = InstanceConfig.formatName_(spanner.projectId, name); + const methods = { + /** + * Create an instance config. + * + * Wrapper around {@link v1.InstanceAdminClient#createInstanceConfig}. + * + * @see {@link v1.InstanceAdminClient#createInstanceConfig} + * @see [CreateInstanceConfig API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceConfig) + * + * @method InstanceConfig#create + * @param {CreateInstanceConfigRequest} config Configuration object. + * @param {CreateInstanceConfigCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instanceConfig = + * spanner.instanceConfig('custom-my-instance-config'); + * + * instanceConfig.create(function(err, instance, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Instance config created successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instanceConfig.create() + * .then(function(data) { + * const operation = data[0]; + * const apiResponse = data[1]; + * + * return operation.promise(); + * }) + * .then(function() { + * // Instance config created successfully. + * }); + * ``` + */ + create: true, + }; + super({ + parent: spanner, + id: name, + methods, + createMethod( + _: {}, + options: CreateInstanceConfigRequest, + callback: CreateInstanceConfigCallback, + ): void { + spanner.createInstanceConfig(formattedName_, options, callback); + }, + } as {} as ServiceObjectConfig); + this.formattedName_ = formattedName_; + this.request = spanner.request.bind(spanner); + this.resourceHeader_ = { + [CLOUD_RESOURCE_HEADER]: this.formattedName_, + }; + } + + /** + * Gets the metadata from the backend for this InstanceConfig. + */ + /** + * @typedef {array} GetInstanceConfigResponse + * @property {object[]} 0 The metadata of the instance config. + * @property {string} 0.name The unique identifier for the instance config. + * @property {string} 0.displayName The name of the instance config as it + * appears in UIs. + * @property {google.spanner.admin.instance.v1.IReplicaInfo[]} 0.replicas The replicas used by + * this instance config. + * @property {string[]} 0.leaderOptions The possible leader options for this instance config. + */ + /** + * @callback GetInstanceConfigCallback + * @param {?Error} err Request error, if any. + * @param {object} instanceConfig The metadata of the instance config. + * @param {string} instanceConfig.name The unique identifier for the instance + * config. + * @param {string} instanceConfig.displayName The name of the instance config + * as it appears in UIs. + * @param {google.spanner.admin.instance.v1.IReplicaInfo[]} instanceConfig.replicas The replicas used by + * this instance config. + * @param {string[]} 0.leaderOptions The possible leader options for this instance config. + */ + /** + * Gets the metadata from the backend for this InstanceConfig. + * + * Wrapper around {@link v1.InstanceAdminClient#getInstanceConfig}. + * + * @see {@link v1.InstanceAdminClient#getInstanceConfig} + * @see [GetInstanceConfig API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig) + * + * @param {GetInstanceConfigCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instanceConfig = spanner.instanceConfig('custom-my-instance-config'); + * + * instanceConfig.get(function(err, instanceConfig) { + * // `instanceConfig` is an instance configuration descriptor. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instanceConfig.get().then(function(data) { + * const instanceConfig = data[0]; + * }); + * ``` + */ + get(options?: GetInstanceConfigOptions): Promise; + get(callback: GetInstanceConfigCallback): void; + get( + options: GetInstanceConfigOptions, + callback: GetInstanceConfigCallback, + ): void; + get( + optionsOrCallback?: GetInstanceConfigOptions | GetInstanceConfigCallback, + cb?: GetInstanceConfigCallback, + ): void | Promise { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetInstanceConfigOptions); + this.parent.getInstanceConfig(this.id, options, callback); + } + + /** + * Update the metadata for this instance config. Note that this method follows + * PATCH semantics, so previously-configured settings will persist. + * This function can only be called for deleting user managed instance + * configs. + * + * Wrapper around {@link v1.InstanceAdminClient#updateInstanceConfig}. + * + * @see {@link v1.InstanceAdminClient#updateInstanceConfig} + * @see [UpdateInstanceConfig API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceConfig) + * + * @param {object} metadata The metadata you wish to set. + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {SetInstanceConfigMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instanceConfig = spanner.instanceConfig('custom-my-instance-config'); + * + * const metadata = { + * instanceConfig: { + * displayName: 'My Instance Config' + * } + * }; + * + * instanceConfig.setMetadata(metadata, function(err, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Metadata updated successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instanceConfig.setMetadata(metadata).then(function(data) { + * const operation = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + setMetadata( + config: SetInstanceConfigMetadataRequest, + ): Promise; + setMetadata( + config: SetInstanceConfigMetadataRequest, + callback: SetInstanceConfigMetadataCallback, + ): void; + setMetadata( + config: SetInstanceConfigMetadataRequest, + callback?: SetInstanceConfigMetadataCallback, + ): void | Promise { + const reqOpts = { + instanceConfig: extend( + { + name: this.formattedName_, + }, + config.instanceConfig, + ), + updateMask: { + paths: Object.keys(config.instanceConfig).map(snakeCase), + }, + validateOnly: config.validateOnly, + }; + + // validateOnly need not be passed in if it is null or undefined. + if (reqOpts.validateOnly === null || reqOpts.validateOnly === undefined) + delete reqOpts.validateOnly; + + return this.request( + { + client: 'InstanceAdminClient', + method: 'updateInstanceConfig', + reqOpts, + gaxOpts: + config.gaxOpts === null || config.gaxOpts === undefined + ? {} + : config.gaxOpts, + headers: this.resourceHeader_, + }, + callback!, + ); + } + + /** + * @typedef {array} DeleteInstanceConfigResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteInstanceConfigCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the instance config. This function can only be called for deleting + * user managed instance configs. + * + * Wrapper around {@link v1.InstanceAdminClient#deleteInstanceConfig}. + * + * @see {@link v1.InstanceAdminClient#deleteInstanceConfig} + * @see [DeleteInstanceConfig API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstanceConfig) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DeleteInstanceConfigCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instanceConfig = spanner.instanceConfig('custom-my-instance-config'); + * + * instanceConfig.delete(function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Instance config was deleted successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instanceConfig.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + delete( + config?: DeleteInstanceConfigRequest, + ): Promise; + delete(callback: DeleteInstanceConfigCallback): void; + delete( + config: DeleteInstanceConfigRequest, + callback: DeleteInstanceConfigCallback, + ): void; + delete( + optionsOrCallback?: + | DeleteInstanceConfigRequest + | DeleteInstanceConfigCallback, + cb?: DeleteInstanceConfigCallback, + ): void | Promise { + const config = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts = { + name: this.formattedName_, + etag: config.etag, + validateOnly: config.validateOnly, + }; + + // etag/validateOnly need not be passed in if null or undefined. + if (reqOpts.etag === null || reqOpts.etag === undefined) + delete reqOpts.etag; + if (reqOpts.validateOnly === null || reqOpts.etag === undefined) + delete reqOpts.validateOnly; + + this.request( + { + client: 'InstanceAdminClient', + method: 'deleteInstanceConfig', + reqOpts, + gaxOpts: + config.gaxOpts === null || config.gaxOpts === undefined + ? {} + : config.gaxOpts, + headers: this.resourceHeader_, + }, + (err, resp) => { + if (!err) { + this.parent.instanceConfigs_.delete(this.id); + } + callback!(err, resp!); + }, + ); + } + + /** + * @typedef {array} ExistsInstanceConfigResponse + * @property {boolean} 0 Whether the {@link InstanceConfig} exists. + */ + /** + * @callback ExistsInstanceConfigCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link InstanceConfig} exists. + */ + /** + * Check if an instance config exists. + * + * @method InstanceConfig#exists + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {ExistsInstanceConfigCallback} [callback] Callback function. + * @returns {Promise} When resolved, contains + * true if the instance config exists and false if it does not exist. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instanceConfig = spanner.instanceConfig('custom-my-instance-config'); + * + * const exists = await instanceConfig.exists(); + * console.log(`Does instance config exist? ${exists}`); + * ``` + */ + exists(): Promise; + exists(callback: ExistsInstanceConfigCallback): void; + async exists(): Promise { + try { + // Attempt to read metadata to determine whether instance config exists + await this.get(); + // Found, therefore it exists + return true; + } catch (err) { + if ((err as grpc.ServerErrorResponse).code === grpc.status.NOT_FOUND) { + return false; + } + // Some other error occurred, rethrow + throw err; + } + } + + /** + * Format the instance config name to include the project ID. + * + * @private + * + * @param {string} projectId The project ID. + * @param {string} name The instance config name. + * @returns {string} + * + * @example + * ``` + * InstanceConfig.formatName_('grape-spaceship-123', 'my-instance-config'); + * // 'projects/grape-spaceship-123/instanceConfigs/my-instance-config' + * ``` + */ + static formatName_(projectId: string, name: string) { + if (name.indexOf('/') > -1) { + return name; + } + const instanceConfigName = name.split('/').pop(); + return 'projects/' + projectId + '/instanceConfigs/' + instanceConfigName; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(InstanceConfig, { + exclude: ['exists'], +}); + +/** + * Reference to the {@link InstanceConfig} class. + * @name module:@google-cloud/spanner.InstanceConfig + * @see InstanceConfig + */ +export {InstanceConfig}; diff --git a/handwritten/spanner/src/instance.ts b/handwritten/spanner/src/instance.ts new file mode 100644 index 00000000000..25e7dc5272c --- /dev/null +++ b/handwritten/spanner/src/instance.ts @@ -0,0 +1,1694 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 {toArray} from './helper'; +import {ServiceObjectConfig, GetConfig} from '@google-cloud/common'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common-grpc/service-object'); +import {promisifyAll} from '@google-cloud/promisify'; +import * as extend from 'extend'; +import snakeCase = require('lodash.snakecase'); +import {Database, SessionPoolConstructor} from './database'; +import {Spanner, RequestConfig} from '.'; +import { + RequestCallback, + PagedOptions, + PagedResponse, + LongRunningCallback, + NormalCallback, + ResourceCallback, + PagedOptionsWithFilter, + getCommonHeaders, +} from './common'; +import {Duplex} from 'stream'; +import {SessionPoolOptions, SessionPool} from './session-pool'; +import { + grpc, + Operation as GaxOperation, + CallOptions, + GoogleError, +} from 'google-gax'; +import { + Backup, + CopyBackupCallback, + CopyBackupResponse, + CopyBackupOptions, +} from './backup'; +import {google as instanceAdmin} from '../protos/protos'; +import {google as databaseAdmin} from '../protos/protos'; +import {google as spannerClient} from '../protos/protos'; +import {CreateInstanceRequest} from './index'; +import {ObservabilityOptions} from './instrument'; + +export type IBackup = databaseAdmin.spanner.admin.database.v1.IBackup; +export type IDatabase = databaseAdmin.spanner.admin.database.v1.IDatabase; +export type IInstance = instanceAdmin.spanner.admin.instance.v1.IInstance; +export type IOperation = instanceAdmin.longrunning.IOperation; +export type CreateInstanceResponse = [Instance, GaxOperation, IOperation]; +export type CreateDatabaseResponse = [Database, GaxOperation, IOperation]; +export type DeleteInstanceResponse = [instanceAdmin.protobuf.IEmpty]; +export type ExistsInstanceResponse = [boolean]; +export type GetInstanceResponse = [Instance, IInstance]; +export type GetInstanceMetadataResponse = [IInstance]; +export interface GetInstanceMetadataOptions { + fieldNames?: string | string[]; + gaxOptions?: CallOptions; +} +export type GetDatabasesResponse = PagedResponse< + Database, + databaseAdmin.spanner.admin.database.v1.IListDatabasesResponse +>; +export type SetInstanceMetadataResponse = [GaxOperation, IOperation]; +export type GetBackupsResponse = PagedResponse< + Backup, + databaseAdmin.spanner.admin.database.v1.IListBackupsResponse +>; +export type GetBackupOperationsResponse = PagedResponse< + IOperation, + databaseAdmin.spanner.admin.database.v1.IListBackupOperationsResponse +>; +export type GetDatabaseOperationsResponse = PagedResponse< + IOperation, + databaseAdmin.spanner.admin.database.v1.IListDatabaseOperationsResponse +>; + +export interface CreateDatabaseOptions + extends databaseAdmin.spanner.admin.database.v1.ICreateDatabaseRequest { + poolOptions?: SessionPoolOptions; + poolCtor?: SessionPool; + schema?: string | string[]; + gaxOptions?: CallOptions; +} +export type GetDatabasesOptions = PagedOptions; +export type CreateInstanceCallback = LongRunningCallback; +export type CreateDatabaseCallback = LongRunningCallback; +export type DeleteInstanceCallback = + NormalCallback; + +export type ExistsInstanceCallback = NormalCallback; +export type GetDatabasesCallback = RequestCallback< + Database, + databaseAdmin.spanner.admin.database.v1.IListDatabasesResponse +>; +export type GetInstanceCallback = ResourceCallback; +export type GetInstanceMetadataCallback = NormalCallback; +export type SetInstanceMetadataCallback = ResourceCallback< + GaxOperation, + IOperation +>; +export type GetBackupsOptions = PagedOptionsWithFilter; + +export type GetBackupsCallback = RequestCallback< + Backup, + databaseAdmin.spanner.admin.database.v1.IListBackupsResponse +>; +export type GetBackupOperationsOptions = PagedOptionsWithFilter; + +export type GetBackupOperationsCallback = RequestCallback< + IOperation, + databaseAdmin.spanner.admin.database.v1.IListBackupOperationsResponse +>; +export type GetDatabaseOperationsOptions = PagedOptionsWithFilter; + +export type GetDatabaseOperationsCallback = RequestCallback< + IOperation, + databaseAdmin.spanner.admin.database.v1.IListDatabaseOperationsResponse +>; +export interface GetInstanceConfig + extends GetConfig, + CreateInstanceRequest, + GetInstanceMetadataOptions {} + +interface InstanceRequest { + ( + config: RequestConfig, + callback: ResourceCallback, + ): void; + (config: RequestConfig, callback: RequestCallback): void; + (config: RequestConfig, callback: RequestCallback): void; +} +/** + * The {@link Instance} class represents a [Cloud Spanner + * instance](https://cloud.google.com/spanner/docs/instances). + * + * Create an `Instance` object to interact with a Cloud Spanner instance. + * + * @class + * + * @param {Spanner} spanner {@link Spanner} instance. + * @param {string} name Name of the instance. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * ``` + */ +class Instance extends common.GrpcServiceObject { + formattedName_: string; + request: InstanceRequest; + requestStream: (config: RequestConfig) => Duplex; + databases_: Map; + metadata?: IInstance; + commonHeaders_: {[k: string]: string}; + _observabilityOptions?: ObservabilityOptions; + constructor(spanner: Spanner, name: string) { + const formattedName_ = Instance.formatName_(spanner.projectId, name); + const methods = { + /** + * Create an instance. + * + * Wrapper around {@link v1.InstanceAdminClient#createInstance}. + * + * @see {@link v1.InstanceAdminClient#createInstance} + * @see [CreateInstance API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance) + * + * @method Instance#create + * @param {CreateInstanceRequest} config Configuration object. + * @param {CreateInstanceCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * instance.create(function(err, instance, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Instance created successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instance.create() + * .then(function(data) { + * const operation = data[0]; + * const apiResponse = data[1]; + * + * return operation.promise(); + * }) + * .then(function() { + * // Instance created successfully. + * }); + * ``` + */ + create: true, + }; + super({ + parent: spanner, + /** + * @name Instance#id + * @type {string} + */ + id: name, + methods, + createMethod( + _: {}, + options: CreateInstanceRequest, + callback: CreateInstanceCallback, + ): void { + spanner.createInstance(formattedName_, options, callback); + }, + } as {} as ServiceObjectConfig); + this.formattedName_ = formattedName_; + this.request = spanner.request.bind(spanner); + this.requestStream = spanner.requestStream.bind(spanner); + this.databases_ = new Map(); + this._observabilityOptions = spanner._observabilityOptions; + this.commonHeaders_ = getCommonHeaders( + this.formattedName_, + this._observabilityOptions?.enableEndToEndTracing, + ); + } + + /** + * Get a reference to a Backup object. + * + * @throws {GoogleError} If any parameter is not provided. + * + * @param {string} backupId The name of the backup. + * @return {Backup} A Backup object. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.backup('my-backup'); + * ``` + */ + backup(backupId: string): Backup { + if (!backupId) { + throw new GoogleError('A backup ID is required to create a Backup.'); + } + + return new Backup(this, backupId); + } + + /** + * Get a reference to a Backup object. + * + * @throws {GoogleError} If any parameter is not provided. + * + * @typedef {object} CopyBackupOptions + * * @property {string|null} + * * sourceBackup The full path of the backup to be copied + * * @property {string|number|google.protobuf.Timestamp|external:PreciseDate} + * * expireTime The expire time of the backup. + * * @property {google.spanner.admin.database.v1.ICopyBackupEncryptionConfig} + * * encryptionConfig An encryption configuration describing the + * * encryption type and key resources in Cloud KMS to be used to encrypt + * * the copy backup. + * * @property {object} [gaxOptions] The request configuration options, + * * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * * for more details. + * */ + /** + * @callback CopyBackupCallback + * @param {string} sourceBackupId Full path of the source backup to be copied. + * @param {string} backupId The name of the backup. + * @param {CopyBackupOptions} + * @return {Backup} A Backup object. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const backup = instance.copyBackup('my-source-backup','my-backup',{ + * expireTime: expireTime, + * encryptionConfig: { + * encryptionType: 'CUSTOMER_MANAGED_ENCRYPTION', + * kmsKeyName: 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key', + * },); + * ``` + */ + copyBackup( + sourceBackupId: string, + backupId: string, + options: CopyBackupOptions, + callback?: CopyBackupCallback, + ): Promise | void { + if (!backupId || !sourceBackupId) { + throw new GoogleError( + 'A backup ID and source backup ID is required to create a copy of the source backup.', + ); + } + const copyOfBackup = new Backup(this, backupId, sourceBackupId); + if (callback) { + return copyOfBackup.create(options, callback); + } + return copyOfBackup.create(options); + } + + /** + * Query object for listing backups. + * + * @typedef {object} GetBackupsOptions + * @property {string} [filter] An expression for filtering the results of the + * request. Filter can be configured as outlined in + * {@link v1.DatabaseAdminClient#listBackups}. + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} GetBackupsResponse + * @property {Backup[]} 0 Array of {@link Backup} instances. + * @property {object} 1 A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetBackupsCallback + * @param {?Error} err Request error, if any. + * @param {Backup[]} 0 Array of {@link Backup} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * List backups on the instance. + * + * Both completed and in-progress backups are listed if no filter is supplied. + * + * @see {@link #backup} + * + * @param {GetBackupsOptions} [options] The query object for listing backups. + * @param {gax.CallOptions} [options.gaxOptions] The request configuration + * options, See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @returns {Promise} When resolved, contains a paged list + * of backups. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const [backups] = await instance.getBackups(); + * + * //- + * // To manually handle pagination, set autoPaginate:false in gaxOptions. + * //- + * let pageToken = undefined; + * do { + * const [backups, , response] = await instance.getBackups({ + * pageSize: 3, + * pageToken, + * gaxOptions: {autoPaginate: false}, + * }); + * backups.forEach(backup => { + * // Do something with backup + * }); + * pageToken = response.nextPageToken; + * } while (pageToken); + * ``` + */ + getBackups(options?: GetBackupsOptions): Promise; + getBackups(callback: GetBackupsCallback): void; + getBackups(options: GetBackupsOptions, callback: GetBackupsCallback): void; + getBackups( + optionsOrCallback?: GetBackupsOptions | GetBackupsCallback, + cb?: GetBackupsCallback, + ): void | Promise { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetBackupsOptions); + const gaxOpts = extend(true, {}, options.gaxOptions); + let reqOpts = extend({}, options, { + parent: this.formattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetBackupsOptions).pageSize, + pageToken: (gaxOpts as GetBackupsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetBackupsOptions).pageSize; + delete (gaxOpts as GetBackupsOptions).pageToken; + } + + this.request< + IBackup, + databaseAdmin.spanner.admin.database.v1.IListBackupsResponse + >( + { + client: 'DatabaseAdminClient', + method: 'listBackups', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, backups, nextPageRequest, ...args) => { + let backupInstances: Backup[] | null = null; + if (backups) { + backupInstances = backups.map(backup => { + const backupInstance = this.backup(backup.name!); + backupInstance.metadata = backup; + return backupInstance; + }); + } + const nextQuery = nextPageRequest! + ? extend({}, options, nextPageRequest!) + : null; + + callback(err, backupInstances, nextQuery, ...args); + }, + ); + } + + /** + * Get a list of backups as a readable object stream. + * + * Wrapper around {@link v1.DatabaseAdminClient#listBackups}. + * + * @see {@link v1.DatabaseAdminClient#listBackups} + * @see [ListBackups API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListBackups) + * + * @method Spanner#getBackupsStream + * @param {GetBackupOptions} [options] Query object for listing backups. + * @returns {ReadableStream} A readable stream that emits {@link Backup} + * instances. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * instance.getBackupsStream() + * .on('error', console.error) + * .on('data', function(database) { + * // `backups` is a `Backup` object. + * }) + * .on('end', function() { + * // All backups retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * instance.getBackupsStream() + * .on('data', function(database) { + * this.end(); + * }); + * ``` + */ + getBackupsStream(options: GetBackupsOptions = {}): NodeJS.ReadableStream { + const gaxOpts = extend(true, {}, options.gaxOptions); + + let reqOpts = extend({}, options, { + parent: this.formattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetBackupsOptions).pageSize, + pageToken: (gaxOpts as GetBackupsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetBackupsOptions).pageSize; + delete (gaxOpts as GetBackupsOptions).pageToken; + } + + return this.requestStream({ + client: 'DatabaseAdminClient', + method: 'listBackupsStream', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }); + } + + /** + * Query object for listing backup operations. + * + * @typedef {object} GetBackupOperationsOptions + * @property {string} [filter] An expression for filtering the results of the + * request. Filter can be configured as outlined in + * {@link v1.DatabaseAdminClient#listBackupOperations}. + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} GetBackupOperationsResponse + * @property {google.longrunning.IOperation[]} 0 Array of {@link IOperation} instances. + * @property {object} 1 A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetBackupOperationsCallback + * @param {?Error} err Request error, if any. + * @param {google.longrunning.IOperation[]} 0 Array of {@link IOperation} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + getBackupOperations( + options?: GetBackupOperationsOptions, + ): Promise; + getBackupOperations(callback: GetBackupOperationsCallback): void; + getBackupOperations( + options: GetBackupOperationsOptions, + callback: GetBackupOperationsCallback, + ): void; + + /** + * List pending and completed backup operations for all databases in the instance. + * + * @see {@link #listOperations} + * + * @param {GetBackupOperationsOptions} [options] The query object for listing + * backup operations. + * @param {gax.CallOptions} [options.gaxOptions] The request configuration + * options, See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @returns {Promise} When resolved, contains a + * paged list of backup operations. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const [operations] = await instance.getBackupOperations(); + * + * //- + * // To manually handle pagination, set autoPaginate:false in gaxOptions. + * //- + * let pageToken = undefined; + * do { + * const [operations, , response] = await instance.getBackupOperations({ + * pageSize: 3, + * pageToken, + * gaxOptions: {autoPaginate: false}, + * }); + * operations.forEach(operation => { + * // Do something with operation + * }); + * pageToken = response.nextPageToken; + * } while (pageToken); + * ``` + */ + getBackupOperations( + optionsOrCallback?: + | GetBackupOperationsOptions + | GetBackupOperationsCallback, + cb?: GetBackupOperationsCallback, + ): void | Promise { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetBackupOperationsOptions); + const gaxOpts = extend(true, {}, options.gaxOptions); + let reqOpts = extend({}, options, { + parent: this.formattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetBackupsOptions).pageSize, + pageToken: (gaxOpts as GetBackupsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetBackupsOptions).pageSize; + delete (gaxOpts as GetBackupsOptions).pageToken; + } + + this.request< + IOperation, + databaseAdmin.spanner.admin.database.v1.IListBackupOperationsResponse + >( + { + client: 'DatabaseAdminClient', + method: 'listBackupOperations', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, operations, nextPageRequest, ...args) => { + const nextQuery = nextPageRequest! + ? extend({}, options, nextPageRequest!) + : null; + + callback!(err, operations, nextQuery, ...args); + }, + ); + } + + /** + * Query object for listing database operations. + * + * @typedef {object} GetDatabaseOperationsOptions + * @property {string} [filter] An expression for filtering the results of the + * request. Filter can be configured as outlined in + * {@link v1.DatabaseAdminClient#listDatabaseOperations}. + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} GetDatabaseOperationsResponse + * @property {google.longrunning.IOperation[]} 0 Array of {@link IOperation} instances. + * @property {object} 1 A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetDatabaseOperationsCallback + * @param {?Error} err Request error, if any. + * @param {google.longrunning.IOperation[]} 0 Array of {@link IOperation} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + getDatabaseOperations( + options?: GetDatabaseOperationsOptions, + ): Promise; + getDatabaseOperations(callback: GetDatabaseOperationsCallback): void; + getDatabaseOperations( + options: GetDatabaseOperationsOptions, + callback: GetDatabaseOperationsCallback, + ): void; + + /** + * List pending and completed operations for all databases in the instance. + * + * @see {@link Database.getDatabaseOperations} + * + * @param {GetDatabaseOperationsOptions} [options] The query object for + * listing database operations. + * @param {gax.CallOptions} [options.gaxOptions] The request configuration + * options, See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @returns {Promise} When resolved, contains a + * paged list of database operations. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * const instance = spanner.instance('my-instance'); + * const [operations] = await instance.getDatabaseOperations(); + * // ... then do something with the operations + * + * //- + * // To manually handle pagination, set autoPaginate:false in gaxOptions. + * //- + * let pageToken = undefined; + * do { + * const [operations, , response] = await instance.getDatabaseOperations({ + * pageSize: 3, + * pageToken, + * gaxOptions: {autoPaginate: false}, + * }); + * operations.forEach(operation => { + * // Do something with operation + * }); + * pageToken = response.nextPageToken; + * } while (pageToken); + * ``` + */ + getDatabaseOperations( + optionsOrCallback?: + | GetDatabaseOperationsOptions + | GetDatabaseOperationsCallback, + cb?: GetDatabaseOperationsCallback, + ): void | Promise { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetDatabaseOperationsOptions); + const gaxOpts = extend(true, {}, options.gaxOptions); + let reqOpts = extend({}, options, { + parent: this.formattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetBackupsOptions).pageSize, + pageToken: (gaxOpts as GetBackupsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetBackupsOptions).pageSize; + delete (gaxOpts as GetBackupsOptions).pageToken; + } + + this.request< + IOperation, + databaseAdmin.spanner.admin.database.v1.IListDatabaseOperationsResponse + >( + { + client: 'DatabaseAdminClient', + method: 'listDatabaseOperations', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, operations, nextPageRequest, ...args) => { + const nextQuery = nextPageRequest! + ? extend({}, options, nextPageRequest!) + : null; + + callback!(err, operations, nextQuery, ...args); + }, + ); + } + + /** + * Config for the new database. + * + * @typedef {object} CreateDatabaseRequest + * @property {SessionPoolOptions} [poolOptions] + * @property {SessionPoolCtor} [poolCtor] + */ + /** + * @typedef {array} CreateDatabaseResponse + * @property {Database} 0 The new {@link Database}. + * @property {google.longrunning.Operation} 1 An {@link Operation} object that can be used to check + * the status of the request. + * @property {object} 2 The full API response. + */ + /** + * @callback CreateDatabaseCallback + * @param {?Error} err Request error, if any. + * @param {Database} database The new {@link Database}. + * @param {google.longrunning.Operation} operation An {@link Operation} object that can be used to + * check the status of the request. + * @param {object} apiResponse The full API response. + */ + /** + * Create a database in this instance. + * + * Wrapper around {@link v1.DatabaseAdminClient#createDatabase}. + * + * @see {@link v1.DatabaseAdminClient#createDatabase} + * @see [CreateDatabase API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase) + * + * @throws {GoogleError} If a name is not provided. + * + * @param {name} name The name of the database to create. + * @param {CreateDatabaseRequest} [options] Configuration object. + * @param {CreateDatabaseCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * function callback(err, database, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Database created successfully. + * }); + * } + * + * instance.createDatabase('new-database-name', callback); + * + * //- + * // Set the schema for the database. + * //- + * instance.createDatabase('new-database-name', { + * schema: + * 'CREATE TABLE Singers (' + + * ' SingerId STRING(1024) NOT NULL,' + + * ' Name STRING(1024),' + + * ') PRIMARY KEY(SingerId)' + * }, callback); + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instance.createDatabase('new-database-name') + * .then(function(data) { + * const database = data[0]; + * const operation = data[1]; + * return operation.promise(); + * }) + * .then(function() { + * // Database created successfully. + * }); + * + * ``` + * @example include:samples/schema.js + * region_tag:spanner_create_database + * Full example: + */ + createDatabase( + name: string, + options?: CreateDatabaseOptions, + ): Promise; + createDatabase(name: string, callback: CreateDatabaseCallback): void; + createDatabase( + name: string, + options: CreateDatabaseOptions, + callback: CreateDatabaseCallback, + ): void; + createDatabase( + name: string, + optionsOrCallback?: CreateDatabaseOptions | CreateDatabaseCallback, + cb?: CreateDatabaseCallback, + ): void | Promise { + if (!name) { + throw new GoogleError('A name is required to create a database.'); + } + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as CreateDatabaseOptions); + + const poolOptions = options.poolOptions; + const poolCtor = options.poolCtor; + let createStatement = 'CREATE DATABASE `' + name.split('/').pop() + '`'; + if ( + databaseAdmin.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL === + options.databaseDialect + ) { + createStatement = 'CREATE DATABASE "' + name.split('/').pop() + '"'; + } + const reqOpts = extend( + { + parent: this.formattedName_, + createStatement: createStatement, + }, + options, + ); + + delete reqOpts.poolOptions; + delete reqOpts.poolCtor; + delete reqOpts.gaxOptions; + + if (reqOpts.schema) { + reqOpts.extraStatements = toArray(reqOpts.schema); + delete reqOpts.schema; + } + this.request( + { + client: 'DatabaseAdminClient', + method: 'createDatabase', + reqOpts, + gaxOpts: options.gaxOptions, + headers: this.commonHeaders_, + }, + (err, operation, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + const database = this.database(name, poolOptions || poolCtor); + database._observabilityOptions = this._observabilityOptions; + callback(null, database, operation, resp); + }, + ); + } + + /** + * Get a reference to a Database object. + * + * @throws {GoogleError} If a name is not provided. + * + * @param {string} name The name of the instance. + * @param {SessionPoolOptions|SessionPoolCtor} [poolOptions] Session pool + * configuration options. + * @param {spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions] + * Default query options to use with the database. These options will be + * overridden by any query options set in environment variables or that + * are specified on a per-query basis. + * @return {Database} A Database object. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * ``` + */ + database( + name: string, + poolOptions?: SessionPoolOptions | SessionPoolConstructor, + queryOptions?: spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions, + databaseRole?: string | null, + ): Database { + if (!name) { + throw new GoogleError('A name is required to access a Database object.'); + } + // Only add an additional key for SessionPoolOptions and QueryOptions if an + // options object with at least one value was passed in. + let optionsKey = + poolOptions && Object.keys(poolOptions).length > 0 + ? '/' + JSON.stringify(Object.entries(poolOptions).sort()) + : ''; + if (queryOptions && Object.keys(queryOptions).length > 0) { + optionsKey = + optionsKey + '/' + JSON.stringify(Object.entries(queryOptions!).sort()); + } + const key = name.split('/').pop() + optionsKey; + if (!this.databases_.has(key!)) { + const db = new Database( + this, + name, + poolOptions, + queryOptions, + databaseRole, + ); + db._observabilityOptions = this._observabilityOptions; + const parent = this.parent as Spanner; + if (parent && parent._nthClientId) { + db._clientId = parent._nthClientId; + } + this.databases_.set(key!, db); + } + return this.databases_.get(key!)!; + } + + /** + * @typedef {array} DeleteInstanceResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteInstanceCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the instance. + * + * Wrapper around {@link v1.InstanceAdminClient#deleteInstance}. + * + * @see {@link v1.InstanceAdminClient#deleteInstance} + * @see [DeleteInstance API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DeleteInstanceCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * instance.delete(function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Instance was deleted successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instance.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + delete(gaxOptions?: CallOptions): Promise; + delete(callback: DeleteInstanceCallback): void; + delete(gaxOptions: CallOptions, callback: DeleteInstanceCallback): void; + delete( + optionsOrCallback?: CallOptions | DeleteInstanceCallback, + cb?: DeleteInstanceCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts = { + name: this.formattedName_, + }; + void Promise.all( + Array.from(this.databases_.values()).map(database => { + return database.close(); + }), + ) + .catch(() => {}) + .then(() => { + this.databases_.clear(); + this.request( + { + client: 'InstanceAdminClient', + method: 'deleteInstance', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, resp) => { + if (!err) { + this.parent.instances_.delete(this.id); + } + callback!(err, resp!); + }, + ); + }); + } + + /** + * @typedef {array} InstanceExistsResponse + * @property {boolean} 0 Whether the {@link Instance} exists. + */ + /** + * @callback InstanceExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link Instance} exists. + */ + /** + * Check if an instance exists. + * + * @method Instance#exists + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {InstanceExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * instance.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instance.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists(gaxOptions?: CallOptions): Promise; + exists(callback: ExistsInstanceCallback): void; + exists(gaxOptions: CallOptions, callback: ExistsInstanceCallback): void; + exists( + optionsOrCallback?: CallOptions | ExistsInstanceCallback, + cb?: ExistsInstanceCallback, + ): void | Promise { + const gaxOptions = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const NOT_FOUND = 5; + + this.getMetadata({gaxOptions}, err => { + if (err && err.code !== NOT_FOUND) { + callback!(err, null); + return; + } + + const exists = !err || err.code !== NOT_FOUND; + callback!(null, exists); + }); + } + + /** + * @typedef {array} GetInstanceResponse + * @property {Instance} 0 The {@link Instance}. + * @property {object} 1 The full API response. + */ + /** + * @callback GetInstanceCallback + * @param {?Error} err Request error, if any. + * @param {Instance} instance The {@link Instance}. + * @param {object} apiResponse The full API response. + */ + /** + * Get an instance if it exists. + * + * You may optionally use this to "get or create" an object by providing an + * object with `autoCreate` set to `true`. Any extra configuration that is + * normally required for the `create` method must be contained within this + * object as well. + * + * @param {options} [options] Configuration object. + * @param {boolean} [options.autoCreate=false] Automatically create the + * object if it does not exist. + * @param {string | string[]} [options.fieldNames] A list of `Instance` field + * names to be requested. Eligible values are: `name`, `displayName`, + * `endpointUris`, `labels`, `config`, `nodeCount`, `state`. + * @param {GetInstanceCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * instance.get(function(err, instance, apiResponse) { + * // `instance.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instance.get().then(function(data) { + * const instance = data[0]; + * const apiResponse = data[0]; + * }); + * ``` + */ + get(options?: GetInstanceConfig): Promise; + get(callback: GetInstanceCallback): void; + get(options: GetInstanceConfig, callback: GetInstanceCallback): void; + get( + optionsOrCallback?: GetInstanceConfig | GetInstanceCallback, + cb?: GetInstanceCallback, + ): void | Promise { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetInstanceConfig); + + const getMetadataOptions: GetInstanceMetadataOptions = new Object(null); + if (options.fieldNames) { + getMetadataOptions.fieldNames = options.fieldNames; + } + if (options.gaxOptions) { + getMetadataOptions.gaxOptions = options.gaxOptions; + } + + this.getMetadata(getMetadataOptions, (err, metadata) => { + if (err) { + if (err.code === 5 && options.autoCreate) { + const createOptions = extend(true, {}, options); + delete createOptions.fieldNames; + delete createOptions.autoCreate; + this.create( + createOptions, + ( + err: grpc.ServiceError | null, + instance?: Instance, + operation?: GaxOperation | null, + ) => { + if (err) { + callback(err); + return; + } + operation! + .on('error', callback) + .on('complete', (metadata: IInstance) => { + this.metadata = metadata; + callback(null, this, metadata); + }); + }, + ); + return; + } + callback(err); + return; + } + callback(null, this, metadata!); + }); + } + + /** + * Query object for listing databases. + * + * @typedef {object} GetDatabasesRequest + * @property {number} [pageSize] Maximum number of results per page. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {array} GetDatabasesResponse + * @property {Database[]} 0 Array of {@link Database} instances. + * @property {object} nextQuery A query object to receive more results. + * @property {object} apiResponse The full API response. + */ + /** + * @callback GetDatabasesCallback + * @param {?Error} err Request error, if any. + * @param {Database[]} databases Array of {@link Database} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Get a list of databases. + * + * Wrapper around {@link v1.DatabaseAdminClient#listDatabases}. + * + * @see {@link v1.DatabaseAdminClient#listDatabases} + * @see [ListDatabases API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases) + * + * @param {GetDatabasesOptions} [options] Query object for listing databases. + * @param {GetDatabasesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * instance.getDatabases(function(err, databases) { + * // `databases` is an array of `Database` objects. + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * function callback(err, databases, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * instance.getDatabases(nextQuery, callback); + * } + * } + * + * instance.getDatabases({ + * gaxOptions: {autoPaginate: false} + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instance.getDatabases().then(function(data) { + * const databases = data[0]; + * }); + * ``` + */ + getDatabases(options?: GetDatabasesOptions): Promise; + getDatabases(callback: GetDatabasesCallback): void; + getDatabases( + options: GetDatabasesOptions, + callback: GetDatabasesCallback, + ): void; + getDatabases( + optionsOrCallback?: GetDatabasesOptions | GetDatabasesCallback, + cb?: GetDatabasesCallback, + ): void | Promise { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' + ? optionsOrCallback + : ({} as GetDatabasesOptions); + + const gaxOpts = extend(true, {}, options.gaxOptions); + let reqOpts = extend({}, options, { + parent: this.formattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetBackupsOptions).pageSize, + pageToken: (gaxOpts as GetBackupsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetBackupsOptions).pageSize; + delete (gaxOpts as GetBackupsOptions).pageToken; + } + + this.request< + IDatabase, + databaseAdmin.spanner.admin.database.v1.IListDatabasesResponse + >( + { + client: 'DatabaseAdminClient', + method: 'listDatabases', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + (err, rowDatabases, nextPageRequest, ...args) => { + let databases: Database[] | null = null; + if (rowDatabases) { + databases = rowDatabases.map(database => { + const databaseInstance = self.database(database.name!, {min: 0}); + databaseInstance.metadata = database; + databaseInstance._observabilityOptions = this._observabilityOptions; + return databaseInstance; + }); + } + const nextQuery = nextPageRequest! + ? extend({}, options, nextPageRequest!) + : null; + + callback(err, databases, nextQuery, ...args); + }, + ); + } + + /** + * Get a list of databases as a readable object stream. + * + * Wrapper around {@link v1.DatabaseAdminClient#listDatabases}. + * + * @see {@link v1.DatabaseAdminClient#listDatabases} + * @see [ListDatabases API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases) + * + * @method Spanner#getDatabasesStream + * @param {GetDatabasesOptions} [options] Query object for listing databases. + * @returns {ReadableStream} A readable stream that emits {@link Database} + * instances. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * instance.getDatabasesStream() + * .on('error', console.error) + * .on('data', function(database) { + * // `database` is a `Database` object. + * }) + * .on('end', function() { + * // All databases retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * instance.getDatabasesStream() + * .on('data', function(database) { + * this.end(); + * }); + * ``` + */ + getDatabasesStream(options: GetDatabasesOptions = {}): NodeJS.ReadableStream { + const gaxOpts = extend(true, {}, options.gaxOptions); + + let reqOpts = extend({}, options, { + parent: this.formattedName_, + }); + delete reqOpts.gaxOptions; + + // Copy over pageSize and pageToken values from gaxOptions. + // However values set on options take precedence. + if (gaxOpts) { + reqOpts = extend( + {}, + { + pageSize: (gaxOpts as GetBackupsOptions).pageSize, + pageToken: (gaxOpts as GetBackupsOptions).pageToken, + }, + reqOpts, + ); + delete (gaxOpts as GetBackupsOptions).pageSize; + delete (gaxOpts as GetBackupsOptions).pageToken; + } + + return this.requestStream({ + client: 'DatabaseAdminClient', + method: 'listDatabasesStream', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }); + } + + /** + * @typedef {array} GetInstanceMetadataResponse + * @property {object} 0 The {@link Instance} metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetInstanceMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The {@link Instance} metadata. + * @param {object} apiResponse The full API response. + */ + /** + * Get the instance's metadata. + * + * Wrapper around {@link v1.InstanceAdminClient#getInstance}. + * + * @see {@link v1.InstanceAdminClient#getInstance} + * @see [GetInstance API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstance) + * + * @param {GetInstanceMetadataOptions} [options] Configuration object + * @param {string | string[]} [options.fieldNames] A list of `Instance` field + * names to be requested. Eligible values are: `name`, `displayName`, + * `endpointUris`, `labels`, `config`, `nodeCount`, `state`. + * @param {GetInstanceMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * instance.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // Request only `displayName`. + * //- + * instance.getMetadata({fieldNames: 'displayName'}, (err, metadata, apiResponse) => { + * // metadata will only contain value for `displayName` + * const displayName = metadata['displayName']; + * }) + * + * //- + * // Request multiple specific field names. + * //- + * instance.getMetadata({fieldNames: ['displayName', 'nodeCount']}, (err, metadata, apiResponse) => { + * // metadata will only contain value for `displayName` and 'nodeCount' + * const displayName = metadata['displayName']; + * const nodeCount = metadata['nodeCount']; + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instance.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + getMetadata( + options?: GetInstanceMetadataOptions, + ): Promise; + getMetadata(callback: GetInstanceMetadataCallback): void; + getMetadata( + options: GetInstanceMetadataOptions, + callback: GetInstanceMetadataCallback, + ): void; + getMetadata( + optionsOrCallback?: + | GetInstanceMetadataOptions + | GetInstanceMetadataCallback, + cb?: GetInstanceMetadataCallback, + ): Promise | void { + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const reqOpts = { + name: this.formattedName_, + }; + if (options.fieldNames) { + reqOpts['fieldMask'] = { + paths: toArray(options['fieldNames']!).map(snakeCase), + }; + } + return this.request( + { + client: 'InstanceAdminClient', + method: 'getInstance', + reqOpts, + gaxOpts: options.gaxOptions, + headers: this.commonHeaders_, + }, + (err, resp) => { + if (resp) { + this.metadata = resp; + } + callback!(err, resp); + }, + ); + } + + /** + * Update the metadata for this instance. Note that this method follows PATCH + * semantics, so previously-configured settings will persist. + * + * Wrapper around {@link v1.InstanceAdminClient#updateInstance}. + * + * @see {@link v1.InstanceAdminClient#updateInstance} + * @see [UpdateInstance API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance) + * + * @param {object} metadata The metadata you wish to set. + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {SetInstanceMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * + * const metadata = { + * displayName: 'My Instance' + * }; + * + * instance.setMetadata(metadata, function(err, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Metadata updated successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * instance.setMetadata(metadata).then(function(data) { + * const operation = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + setMetadata( + metadata: IInstance, + gaxOptions?: CallOptions, + ): Promise; + setMetadata(metadata: IInstance, callback: SetInstanceMetadataCallback): void; + setMetadata( + metadata: IInstance, + gaxOptions: CallOptions, + callback: SetInstanceMetadataCallback, + ): void; + setMetadata( + metadata: IInstance, + optionsOrCallback?: CallOptions | SetInstanceMetadataCallback, + cb?: SetInstanceMetadataCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts = { + instance: extend( + { + name: this.formattedName_, + }, + metadata, + ), + fieldMask: { + paths: Object.keys(metadata).map(snakeCase), + }, + }; + return this.request( + { + client: 'InstanceAdminClient', + method: 'updateInstance', + reqOpts, + gaxOpts, + headers: this.commonHeaders_, + }, + callback!, + ); + } + /** + * Format the instance name to include the project ID. + * + * @private + * + * @param {string} projectId The project ID. + * @param {string} name The instance name. + * @returns {string} + * + * @example + * ``` + * Instance.formatName_('grape-spaceship-123', 'my-instance'); + * // 'projects/grape-spaceship-123/instances/my-instance' + * ``` + */ + static formatName_(projectId: string, name: string) { + if (name.indexOf('/') > -1) { + return name; + } + const instanceName = name.split('/').pop(); + return 'projects/' + projectId + '/instances/' + instanceName; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Instance, { + exclude: ['database', 'backup'], +}); + +/** + * Reference to the {@link Instance} class. + * @name module:@google-cloud/spanner.Instance + * @see Instance + */ +export {Instance}; diff --git a/handwritten/spanner/src/instrument.ts b/handwritten/spanner/src/instrument.ts new file mode 100644 index 00000000000..9537e51efd9 --- /dev/null +++ b/handwritten/spanner/src/instrument.ts @@ -0,0 +1,305 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 { + ATTR_OTEL_SCOPE_NAME, + ATTR_OTEL_SCOPE_VERSION, +} from '@opentelemetry/semantic-conventions'; + +import { + Span, + SpanStatusCode, + context, + trace, + INVALID_SPAN_CONTEXT, + ROOT_CONTEXT, + SpanAttributes, + TimeInput, + TracerProvider, + Link, + Exception, + SpanContext, + SpanStatus, + SpanKind, +} from '@opentelemetry/api'; + +const optedInPII: boolean = + process.env.SPANNER_ENABLE_EXTENDED_TRACING === 'true'; + +interface SQLStatement { + sql: string; +} + +/* + * ObservabilityOptions defines the configuration to be used for Spanner OpenTelemetry Traces. + * @property [tracerProvider] Sets the TracerProvider to be used for traces, + * Global TracerProvider will be used as a fallback. + * @property [enableExtendedTracing] Sets whether to enable extended OpenTelemetry tracing. Enabling this option will add the + * following additional attributes to the traces that are generated by the client + * db.statement: Contains the SQL statement that is being executed. + * Alternatively, you could set environment variable `SPANNER_ENABLE_EXTENDED_TRACING=true`. + */ +interface ObservabilityOptions { + tracerProvider: TracerProvider; + enableExtendedTracing?: boolean; + enableEndToEndTracing?: boolean; +} + +export type {ObservabilityOptions}; +export type {Span}; + +const TRACER_NAME = 'cloud.google.com/nodejs/spanner'; +const TRACER_VERSION = require('../../package.json').version; + +export {TRACER_NAME, TRACER_VERSION}; // Only exported for testing. + +/** + * getTracer fetches the tracer from the provided tracerProvider. + * @param {TracerProvider} [tracerProvider] optional custom tracer provider + * to use for fetching the tracer. If not provided, the global provider will be used. + * + * @returns {Tracer} The tracer instance associated with the provided or global provider. + */ +export function getTracer(tracerProvider?: TracerProvider) { + if (tracerProvider) { + return tracerProvider.getTracer(TRACER_NAME, TRACER_VERSION); + } + // Otherwise use the global tracer. + return trace.getTracer(TRACER_NAME, TRACER_VERSION); +} + +interface traceConfig { + sql?: string | SQLStatement; + tableName?: string; + dbName?: string; + transactionTag?: string | null; + requestTag?: string | null; + opts?: ObservabilityOptions; +} + +const SPAN_NAMESPACE_PREFIX = 'CloudSpanner'; // TODO: discuss & standardize this prefix. +export {SPAN_NAMESPACE_PREFIX, traceConfig}; + +const { + AsyncHooksContextManager, +} = require('@opentelemetry/context-async-hooks'); + +/* + * This function ensures that async/await works correctly by + * checking if context.active() returns an invalid/unset context + * and if so, sets a global AsyncHooksContextManager otherwise + * spans resulting from async/await invocations won't be correctly + * associated in their respective hierarchies. + */ +function ensureInitialContextManagerSet() { + if (!context['_contextManager'] || context.active() === ROOT_CONTEXT) { + // If no context manager is currently set, or if the active context is the ROOT_CONTEXT, + // trace context propagation cannot + // function correctly with async/await for OpenTelemetry + // See {@link https://opentelemetry.io/docs/languages/js/context/#active-context} + context.disable(); // Disable any prior contextManager. + const contextManager = new AsyncHooksContextManager(); + contextManager.enable(); + context.setGlobalContextManager(contextManager); + } +} + +export {ensureInitialContextManagerSet}; + +/** + * startTrace begins an active span in the current active context + * and passes it back to the set callback function. Each span will + * be prefixed with "cloud.google.com/nodejs/spanner". It is the + * responsibility of the caller to invoke [span.end] when finished tracing. + * + * @returns {Span} The created span. + */ +export function startTrace( + spanNameSuffix: string, + config: traceConfig | undefined, + cb: (span: Span) => T, +): T { + if (!config) { + config = {} as traceConfig; + } + + return getTracer(config.opts?.tracerProvider).startActiveSpan( + SPAN_NAMESPACE_PREFIX + '.' + spanNameSuffix, + {kind: SpanKind.CLIENT}, + span => { + span.setAttribute(ATTR_OTEL_SCOPE_NAME, TRACER_NAME); + span.setAttribute(ATTR_OTEL_SCOPE_VERSION, TRACER_VERSION); + span.setAttribute('gcp.client.service', 'spanner'); + span.setAttribute('gcp.client.version', TRACER_VERSION); + span.setAttribute('gcp.client.repo', 'googleapis/nodejs-spanner'); + + if (config.tableName) { + span.setAttribute('db.sql.table', config.tableName); + } + if (config.dbName) { + span.setAttribute( + 'gcp.resource.name', + `//spanner.googleapis.com/${config.dbName}`, + ); + span.setAttribute('db.name', config.dbName); + } + if (config.requestTag) { + span.setAttribute('request.tag', config.requestTag); + } + if (config.transactionTag) { + span.setAttribute('transaction.tag', config.transactionTag); + } + + const allowExtendedTracing = + optedInPII || config.opts?.enableExtendedTracing; + if (config.sql && allowExtendedTracing) { + const sql = config.sql; + if (typeof sql === 'string') { + span.setAttribute('db.statement', sql as string); + } else { + const stmt = sql as SQLStatement; + span.setAttribute('db.statement', stmt.sql); + } + } + + // If at all the invoked function throws an exception, + // record the exception and then end this span. + try { + return cb(span); + } catch (e) { + setSpanErrorAndException(span, e as Error); + span.end(); + // Finally re-throw the exception. + throw e; + } + }, + ); +} + +/** + * Sets the span status with err, if non-null onto the span with + * status.code=ERROR and the message of err.toString() + * + * @returns {boolean} to signify if the status was set. + */ +export function setSpanError(span: Span, err: Error | String): boolean { + if (!err || !span) { + return false; + } + + let message = ''; + if (typeof err === 'object' && 'message' in err) { + message = err.message as string; + } else { + message = err.toString(); + } + span.setStatus({ + code: SpanStatusCode.ERROR, + message: message, + }); + return true; +} + +/** + * Sets err, if non-null onto the span with + * status.code=ERROR and the message of err.toString() + * as well as recording an exception on the span. + * @param {Span} [span] the subject span + * @param {Error} [err] the error whose message to use to record + * the span error and the span exception. + * + * @returns {boolean} to signify if the status and exception were set. + */ +export function setSpanErrorAndException( + span: Span, + err: Error | String, +): boolean { + if (setSpanError(span, err)) { + span.recordException(err as Error); + return true; + } + return false; +} + +/** + * getActiveOrNoopSpan queries the global tracer for the currently active + * span and returns it, otherwise if there is no active span available, it'll + * simply create a NoopSpan. This is important in the cases where we don't + * want to create a new span, such as in sensitive and frequently called code + * for which the new spans would be too many and thus pollute the trace, + * but yet we'd like to record an important annotation. + * + * @returns {Span} the non-null span. + */ +export function getActiveOrNoopSpan(): Span { + const span = trace.getActiveSpan(); + if (span) { + return span; + } + return new noopSpan(); +} + +/** + * noopSpan is a pass-through Span that does nothing and shall not + * be exported, nor added into any context. It serves as a placeholder + * to allow calls in sensitive areas like sessionPools to transparently + * add attributes to spans without lots of ugly null checks. + * + * It exists because OpenTelemetry-JS does not seem to export the NoopSpan. + */ +class noopSpan implements Span { + constructor() {} + + spanContext(): SpanContext { + return INVALID_SPAN_CONTEXT; + } + + setAttribute(key: string, value: unknown): this { + return this; + } + + setAttributes(attributes: SpanAttributes): this { + return this; + } + + addEvent(name: string, attributes?: SpanAttributes): this { + return this; + } + + addLink(link: Link): this { + return this; + } + + addLinks(links: Link[]): this { + return this; + } + + setStatus(status: SpanStatus): this { + return this; + } + + end(endTime?: TimeInput): void {} + + isRecording(): boolean { + return false; + } + + recordException(exc: Exception, timeAt?: TimeInput): void {} + + updateName(name: string): this { + return this; + } +} diff --git a/handwritten/spanner/src/metrics/README.md b/handwritten/spanner/src/metrics/README.md new file mode 100644 index 00000000000..d0124b8bfeb --- /dev/null +++ b/handwritten/spanner/src/metrics/README.md @@ -0,0 +1,21 @@ +# Custom Metric Exporter +The custom metric exporter, as defined in [spanner-metrics-exporter.ts](./spanner-metrics-exporter.ts), is designed to work in conjunction with OpenTelemetry and the Spanner client. It converts data into its protobuf equivalent and sends it to Google Cloud Monitoring. + +## Filtering Criteria +The exporter filters metrics based on the following conditions, utilizing values defined in [constants.ts](./constants.ts): + +* Metrics with a scope set to `spanner-nodejs`. +* Metrics with one of the following predefined names: + * `attempt_latencies` + * `attempt_count` + * `operation_latencies` + * `operation_count` + * `gfe_latencies` + * `gfe_connectivity_error_count` + * `afe_latencies` + * `afe_connectivity_error_count` + +## Service Endpoint +The exporter sends metrics to the Google Cloud Monitoring [service endpoint](https://cloud.google.com/python/docs/reference/monitoring/latest/google.cloud.monitoring_v3.services.metric_service.MetricServiceClient#google_cloud_monitoring_v3_services_metric_service_MetricServiceClient_create_service_time_series), distinct from the regular client endpoint. This service endpoint operates under a different quota limit than the user endpoint and features an additional server-side filter that only permits a predefined set of metrics to pass through. + +When introducing new service metrics, it is essential to ensure they are allowed through by the server-side filter as well. \ No newline at end of file diff --git a/handwritten/spanner/src/metrics/constants.ts b/handwritten/spanner/src/metrics/constants.ts new file mode 100644 index 00000000000..959eeb3d817 --- /dev/null +++ b/handwritten/spanner/src/metrics/constants.ts @@ -0,0 +1,127 @@ +// 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 { + View, + ExplicitBucketHistogramAggregation, +} from '@opentelemetry/sdk-metrics'; + +export const SPANNER_METER_NAME = 'spanner-nodejs'; +export const CLIENT_METRICS_PREFIX = 'spanner.googleapis.com/internal/client'; +export const SPANNER_RESOURCE_TYPE = 'spanner_instance_client'; +// Maximum time to keep MetricsTracers before considering them stale, and stop tracking them. +export const TRACER_CLEANUP_THRESHOLD_MS = 60 * 60 * 1000; // 60 minutes +export const TRACER_CLEANUP_INTERVAL_MS = 30 * 60 * 1000; // 30 Minutes +// OTel semantic conventions +// See https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv +export const ATTR_CLOUD_REGION = 'cloud.region'; + +// Minimum period that must past between metric exports +export const MIN_EXPORT_FREQUENCY_MS = 30 * 1000; + +// Monitored resource labels +export const MONITORED_RES_LABEL_KEY_PROJECT = 'project_id'; +export const MONITORED_RES_LABEL_KEY_INSTANCE = 'instance_id'; +export const MONITORED_RES_LABEL_KEY_INSTANCE_CONFIG = 'instance_config'; +export const MONITORED_RES_LABEL_KEY_LOCATION = 'location'; +export const MONITORED_RES_LABEL_KEY_CLIENT_HASH = 'client_hash'; +export const MONITORED_RESOURCE_LABELS = new Set([ + MONITORED_RES_LABEL_KEY_PROJECT, + MONITORED_RES_LABEL_KEY_INSTANCE, + MONITORED_RES_LABEL_KEY_INSTANCE_CONFIG, + MONITORED_RES_LABEL_KEY_LOCATION, + MONITORED_RES_LABEL_KEY_CLIENT_HASH, +]); + +// Metric labels +export const METRIC_LABEL_KEY_CLIENT_UID = 'client_uid'; +export const METRIC_LABEL_KEY_CLIENT_NAME = 'client_name'; +export const METRIC_LABEL_KEY_DATABASE = 'database'; +export const METRIC_LABEL_KEY_METHOD = 'method'; +export const METRIC_LABEL_KEY_STATUS = 'status'; +export const METRIC_LABELS = new Set([ + METRIC_LABEL_KEY_CLIENT_UID, + METRIC_LABEL_KEY_CLIENT_NAME, + METRIC_LABEL_KEY_DATABASE, + METRIC_LABEL_KEY_METHOD, + METRIC_LABEL_KEY_STATUS, +]); + +// Metric names +export const METRIC_NAME_OPERATION_LATENCIES = 'operation_latencies'; +export const METRIC_NAME_ATTEMPT_LATENCIES = 'attempt_latencies'; +export const METRIC_NAME_OPERATION_COUNT = 'operation_count'; +export const METRIC_NAME_ATTEMPT_COUNT = 'attempt_count'; +export const METRIC_NAME_GFE_LATENCIES = 'gfe_latencies'; +export const METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT = + 'gfe_connectivity_error_count'; +export const METRIC_NAME_AFE_LATENCIES = 'afe_latencies'; +export const METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT = + 'afe_connectivity_error_count'; +export const METRIC_NAMES = new Set([ + METRIC_NAME_OPERATION_LATENCIES, + METRIC_NAME_ATTEMPT_LATENCIES, + METRIC_NAME_GFE_LATENCIES, + METRIC_NAME_OPERATION_COUNT, + METRIC_NAME_ATTEMPT_COUNT, + METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, + METRIC_NAME_AFE_LATENCIES, + METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT, +]); + +export const UNKNOWN_ATTRIBUTE = 'unknown'; + +// Histogram Bucket boundaries +export const HISTOGRAM_BUCKET_BOUNDARIES = [ + 0.0, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, + 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 25.0, 30.0, 40.0, 50.0, 65.0, 80.0, + 100.0, 130.0, 160.0, 200.0, 250.0, 300.0, 400.0, 500.0, 650.0, 800.0, 1000.0, + 2000.0, 5000.0, 10000.0, 20000.0, 50000.0, 100000.0, 200000.0, 400000.0, + 800000.0, 1600000.0, 3200000.0, +]; + +// Defined Views for metric aggregation +export const OPERATION_LATENCY_VIEW = new View({ + instrumentName: METRIC_NAME_OPERATION_LATENCIES, + aggregation: new ExplicitBucketHistogramAggregation( + HISTOGRAM_BUCKET_BOUNDARIES, + ), +}); + +export const ATTEMPT_LATENCY_VIEW = new View({ + instrumentName: METRIC_NAME_ATTEMPT_LATENCIES, + aggregation: new ExplicitBucketHistogramAggregation( + HISTOGRAM_BUCKET_BOUNDARIES, + ), +}); + +export const GFE_LATENCY_VIEW = new View({ + instrumentName: METRIC_NAME_GFE_LATENCIES, + aggregation: new ExplicitBucketHistogramAggregation( + HISTOGRAM_BUCKET_BOUNDARIES, + ), +}); + +export const AFE_LATENCY_VIEW = new View({ + instrumentName: METRIC_NAME_AFE_LATENCIES, + aggregation: new ExplicitBucketHistogramAggregation( + HISTOGRAM_BUCKET_BOUNDARIES, + ), +}); + +export const METRIC_VIEWS = [ + OPERATION_LATENCY_VIEW, + ATTEMPT_LATENCY_VIEW, + GFE_LATENCY_VIEW, + AFE_LATENCY_VIEW, +]; diff --git a/handwritten/spanner/src/metrics/external-types.ts b/handwritten/spanner/src/metrics/external-types.ts new file mode 100644 index 00000000000..07c08f9b08b --- /dev/null +++ b/handwritten/spanner/src/metrics/external-types.ts @@ -0,0 +1,37 @@ +// 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 {GoogleAuth} from 'google-auth-library'; + +export interface ExporterOptions { + /** + * Optional authentication options for Google services. + */ + auth: GoogleAuth; +} + +export enum MetricKind { + UNSPECIFIED = 'METRIC_KIND_UNSPECIFIED', + GAUGE = 'GAUGE', + DELTA = 'DELTA', + CUMULATIVE = 'CUMULATIVE', +} + +/** The value type of a metric. */ +export enum ValueType { + VALUE_TYPE_UNSPECIFIED = 'VALUE_TYPE_UNSPECIFIED', + INT64 = 'INT64', + DOUBLE = 'DOUBLE', + DISTRIBUTION = 'DISTRIBUTION', +} diff --git a/handwritten/spanner/src/metrics/interceptor.ts b/handwritten/spanner/src/metrics/interceptor.ts new file mode 100644 index 00000000000..9e18511257a --- /dev/null +++ b/handwritten/spanner/src/metrics/interceptor.ts @@ -0,0 +1,98 @@ +// 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 +// +// 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. + +import {grpc} from 'google-gax'; +import {MetricsTracerFactory} from './metrics-tracer-factory'; + +/** + * Interceptor for recording metrics on gRPC calls. + * + * This interceptor records attempt metrics at the start and completion of each gRPC call, + * and also records Google Front End (GFE), AFE metrics such as latency and connectivity errors + * based on the presence and value of the 'server-timing' header in the response metadata. + * + * @param {object} options - The gRPC call options, including method definition. + * @param {function} nextCall - The next function to call in the gRPC request chain. + * @returns {grpc.InterceptingCall} - The intercepting call with added metrics recording. + */ +export const MetricInterceptor = (options, nextCall) => { + return new grpc.InterceptingCall(nextCall(options), { + start: function (metadata, listener, next) { + // Record attempt metric on request start + const resourcePrefix = metadata.get( + 'google-cloud-resource-prefix', + )[0] as string; + const match = resourcePrefix?.match(/^projects\/([^/]+)\//); + const projectId = match ? match[1] : undefined; + let factory; + if (projectId) { + factory = MetricsTracerFactory.getInstance(projectId); + } + const requestId = metadata.get('x-goog-spanner-request-id')[0] as string; + const metricsTracer = factory?.getCurrentTracer(requestId); + metricsTracer?.recordAttemptStart(); + const newListener = { + onReceiveMetadata: function (metadata, next) { + // Record GFE/AFE Metrics + // GFE/AFE latency if available, + // or else increase the GFE/AFE connectivity error count + if (metricsTracer) { + const serverTimingHeader = metadata.getMap()['server-timing']; + const gfeTiming = + metricsTracer?.extractGfeLatency(serverTimingHeader); + metricsTracer.gfeLatency = gfeTiming ?? null; + const afeTiming = + metricsTracer?.extractAfeLatency(serverTimingHeader); + metricsTracer.afeLatency = afeTiming ?? null; + } + + next(metadata); + }, + onReceiveMessage: function (message, next) { + next(message); + }, + onReceiveStatus: function (status, next) { + next(status); + + // Record attempt metric completion + metricsTracer?.recordAttemptCompletion(status.code); + if (metricsTracer?.gfeLatency) { + metricsTracer?.recordGfeLatency(status.code); + } else { + metricsTracer?.recordGfeConnectivityErrorCount(status.code); + } + if (metricsTracer?.afeLatency) { + metricsTracer?.recordAfeLatency(status.code); + } else { + // Disable afe_connectivity_error_count metric as AFE header is disabled in backend + // currently. + // metricsTracer?.recordAfeConnectivityErrorCount(status.code); + } + }, + }; + next(metadata, newListener); + }, + sendMessage: function (message, next) { + next(message); + }, + + halfClose: function (next) { + next(); + }, + + cancel: function (next) { + next(); + }, + }); +}; diff --git a/handwritten/spanner/src/metrics/metrics-tracer-factory.ts b/handwritten/spanner/src/metrics/metrics-tracer-factory.ts new file mode 100644 index 00000000000..d928c6fa832 --- /dev/null +++ b/handwritten/spanner/src/metrics/metrics-tracer-factory.ts @@ -0,0 +1,492 @@ +// 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 +// +// 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. + +import * as crypto from 'crypto'; +import * as os from 'os'; +import * as process from 'process'; +import {v4 as uuidv4} from 'uuid'; +import {MeterProvider, MetricReader} from '@opentelemetry/sdk-metrics'; +import {Counter, Histogram} from '@opentelemetry/api'; +import {detectResources, Resource} from '@opentelemetry/resources'; +import {GcpDetectorSync} from '@google-cloud/opentelemetry-resource-util'; +import * as Constants from './constants'; +import {MetricsTracer} from './metrics-tracer'; +const version = require('../../../package.json').version; + +/** + * Factory class for creating and managing MetricsTracer instances and OTEL metric instruments. + * + * The MetricsTracerFactory is responsible for: + * - Creating and managing a singleton instance for metrics collection. + * - Initializing and providing OTEL MeterProvider. + * - Generating and storing client-specific metadata (UID, hash, name, location, projectId). + * - Creating and tracking MetricsTracer instances for individual gRPC Spanner operations. + * - Providing utility methods for extracting resource attributes and managing tracers. + * + * This class is designed to be used as a singleton. Metrics collection can be enabled or disabled + * globally via the static `enabled` property, that is set from the SpannerClient. + */ +export class MetricsTracerFactory { + private static _instance: MetricsTracerFactory | null = null; + private _meterProvider: MeterProvider | null = null; + private _instrumentAttemptCounter!: Counter; + private _instrumentAttemptLatency!: Histogram; + private _instrumentOperationCounter!: Counter; + private _instrumentOperationLatency!: Histogram; + private _instrumentGfeConnectivityErrorCount!: Counter; + private _instrumentGfeLatency!: Histogram; + private _instrumentAfeConnectivityErrorCount!: Counter; + private _instrumentAfeLatency!: Histogram; + private _clientHash: string; + private _clientName: string; + private _clientUid: string; + private _location = 'global'; + private _projectId: string; + private _currentOperationTracers = new Map(); + private _currentOperationLastUpdatedMs = new Map(); + private _intervalTracerCleanup: NodeJS.Timeout; + public static enabled = true; + + /** + * Private constructor to enforce singleton pattern. + * Initializes client metadata and detects client location if metrics are enabled. + * Location will default to global if host machine is not a GCE or GKE instance. + * @param projectId The GCP project ID used by the Spanner Client. + */ + private constructor(projectId: string) { + this._projectId = projectId; + this._clientUid = MetricsTracerFactory._generateClientUId(); + this._clientName = `${Constants.SPANNER_METER_NAME}/${version}`; + + // Only perform async call to retrieve location is metrics are enabled. + if (MetricsTracerFactory.enabled) { + (async () => { + const location = await MetricsTracerFactory._detectClientLocation(); + this._location = location.length > 0 ? location : 'global'; + })().catch(error => { + throw error; + }); + } + + this._clientHash = MetricsTracerFactory._generateClientHash( + this._clientUid, + ); + + // Start the Tracer cleanup task at an interval + this._intervalTracerCleanup = setInterval( + this._cleanMetricsTracers.bind(this), + Constants.TRACER_CLEANUP_INTERVAL_MS, + ); + // unref the interval to prevent it from blocking app termination + // in the event loop + this._intervalTracerCleanup.unref(); + } + + /** + * Returns the singleton instance of MetricsTracerFactory. + * If metrics are disabled, returns null. + * The instance is created only once, and enabling/disabling metrics can only be done on the initial call. + * @param projectId Optional GCP project ID for the factory instantiation. Does nothing for subsequent calls. + * @returns The singleton MetricsTracerFactory instance or null if disabled. + */ + public static getInstance(projectId: string): MetricsTracerFactory | null { + if (!MetricsTracerFactory.enabled) { + return null; + } + + // Create a singleton instance, enabling/disabling metrics can only be done on the initial call + if (MetricsTracerFactory._instance === null) { + MetricsTracerFactory._instance = new MetricsTracerFactory(projectId); + } + + return MetricsTracerFactory!._instance; + } + + /** + * Returns the MeterProvider, creating it and metric instruments if not already initialized. + * Client-wide attributes that are known at this time are cached to be provided to all MetricsTracers. + * @param readers Optional array of MetricReader instances to attach to the MeterProvider. + * @returns The OTEL MeterProvider instance. + */ + public getMeterProvider(readers: MetricReader[] = []): MeterProvider { + if (this._meterProvider === null) { + const resource = new Resource({ + [Constants.MONITORED_RES_LABEL_KEY_PROJECT]: this._projectId, + [Constants.MONITORED_RES_LABEL_KEY_CLIENT_HASH]: this._clientHash, + [Constants.MONITORED_RES_LABEL_KEY_LOCATION]: this._location, + [Constants.MONITORED_RES_LABEL_KEY_INSTANCE]: 'unknown', + [Constants.MONITORED_RES_LABEL_KEY_INSTANCE_CONFIG]: 'unknown', + }); + this._meterProvider = new MeterProvider({ + resource: resource, + readers: readers, + views: Constants.METRIC_VIEWS, + }); + this._createMetricInstruments(); + } + return this._meterProvider; + } + + /** + * Resets the singleton instance of the MetricsTracerFactory. + */ + public static async resetInstance(projectId?: string) { + clearInterval(MetricsTracerFactory._instance?._intervalTracerCleanup); + await MetricsTracerFactory._instance?.resetMeterProvider(); + MetricsTracerFactory._instance = null; + } + + /** + * Resets the MeterProvider. + */ + public async resetMeterProvider() { + if (this._meterProvider !== null) { + await this._meterProvider!.shutdown(); + } + this._meterProvider = null; + this._currentOperationTracers = new Map(); + this._currentOperationLastUpdatedMs = new Map(); + } + + /** + * Returns the attempt latency histogram instrument. + */ + get instrumentAttemptLatency(): Histogram { + return this._instrumentAttemptLatency; + } + + /** + * Returns the attempt counter instrument. + */ + get instrumentAttemptCounter(): Counter { + return this._instrumentAttemptCounter; + } + + /** + * Returns the operation latency histogram instrument. + */ + get instrumentOperationLatency(): Histogram { + return this._instrumentOperationLatency; + } + + /** + * Returns the operation counter instrument. + */ + get instrumentOperationCounter(): Counter { + return this._instrumentOperationCounter; + } + + /** + * Returns the GFE connectivity error count counter instrument. + */ + get instrumentGfeConnectivityErrorCount(): Counter { + return this._instrumentGfeConnectivityErrorCount; + } + + /** + * Returns the GFE latency histogram instrument. + */ + get instrumentGfeLatency(): Histogram { + return this._instrumentGfeLatency; + } + + /** + * Returns the Client UID. + */ + get clientUid(): string { + return this._clientUid; + } + + /** + * Returns the Client Name. + */ + get clientName(): string { + return this._clientName; + } + + /** + * Creates a new MetricsTracer for a given resource name and method, and stores it for later retrieval. + * Returns null if metrics are disabled. + * @param formattedName The formatted resource name (e.g., full database path). + * @param method The gRPC method name. + * @returns A new MetricsTracer instance or null if metrics are disabled. + */ + public createMetricsTracer( + method: string, + formattedName: string, + requestId: string, + ): MetricsTracer | null { + if (!MetricsTracerFactory.enabled) { + return null; + } + const operationRequest = this._extractOperationRequest(requestId); + + if (this._currentOperationTracers.has(operationRequest)) { + return this._currentOperationTracers.get(operationRequest); + } + + const {instance, database} = this.getInstanceAttributes(formattedName); + const tracer = new MetricsTracer( + this._instrumentAttemptCounter, + this._instrumentAttemptLatency, + this._instrumentOperationCounter, + this._instrumentOperationLatency, + this._instrumentGfeConnectivityErrorCount, + this._instrumentGfeLatency, + this._instrumentAfeConnectivityErrorCount, + this._instrumentAfeLatency, + MetricsTracerFactory.enabled, + database, + instance, + this._projectId, + method, + operationRequest, + ); + this._currentOperationTracers.set(operationRequest, tracer); + this._currentOperationLastUpdatedMs.set(operationRequest, Date.now()); + return tracer; + } + + /** + * Takes a formatted name and parses the project, instance, and database. + * @param formattedName The formatted resource name (e.g., full database path). + * @returns An object containing project, instance, and database strings. + */ + public getInstanceAttributes(formattedName: string) { + if (typeof formattedName !== 'string' || formattedName === '') { + return { + project: Constants.UNKNOWN_ATTRIBUTE, + instance: Constants.UNKNOWN_ATTRIBUTE, + database: Constants.UNKNOWN_ATTRIBUTE, + }; + } + const regex = + /projects\/(?[^/]+)\/instances\/(?[^/]+)(?:\/databases\/(?[^/]+))?/; + const match = formattedName.match(regex); + const project = match?.groups?.projectId || Constants.UNKNOWN_ATTRIBUTE; + const instance = match?.groups?.instanceId || Constants.UNKNOWN_ATTRIBUTE; + const database = match?.groups?.databaseId || Constants.UNKNOWN_ATTRIBUTE; + return {project: project, instance: instance, database: database}; + } + + /** + * Retrieves the current MetricsTracer for a given request id. + * Returns null if no tracer exists for the request. + * Does not implicitly create MetricsTracers as that should be done + * explicitly using the createMetricsTracer function. + * request id is expected to be as set in the gRPC metadata. + * @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'. + * @returns The MetricsTracer instance or null if not found. + */ + public getCurrentTracer(requestId: string): MetricsTracer | null { + const operationRequest: string = this._extractOperationRequest(requestId); + if (!this._currentOperationTracers.has(operationRequest)) { + // Attempting to retrieve tracer that doesn't exist. + return null; + } + this._currentOperationLastUpdatedMs.set(operationRequest, Date.now()); + + return this._currentOperationTracers.get(operationRequest) ?? null; + } + + /** + * Removes the MetricsTracer associated with the given request id. + * @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'. + */ + public clearCurrentTracer(requestId: string) { + const operationRequest = this._extractOperationRequest(requestId); + if (!this._currentOperationTracers.has(operationRequest)) { + return; + } + this._currentOperationTracers.delete(operationRequest); + this._currentOperationLastUpdatedMs.delete(operationRequest); + } + + private _extractOperationRequest(requestId: string): string { + if (!requestId) { + return ''; + } + + const regex = /^(\d+\.[a-z0-9]+\.\d+\.\d+\.\d+)\.\d+$/i; + const match = requestId.match(regex); + + if (!match) { + return ''; + } + + const request = match[1]; + return request; + } + + /** + * Creates and initializes all metric instruments (counters and histograms) for the MeterProvider. + * Instruments are only created if metrics are enabled. + */ + private _createMetricInstruments() { + if (!MetricsTracerFactory.enabled) { + return; + } + + const meter = this.getMeterProvider().getMeter( + Constants.SPANNER_METER_NAME, + version, + ); + + this._instrumentAttemptLatency = meter.createHistogram( + Constants.METRIC_NAME_ATTEMPT_LATENCIES, + {unit: 'ms', description: 'Time an individual attempt took.'}, + ); + + this._instrumentAttemptCounter = meter.createCounter( + Constants.METRIC_NAME_ATTEMPT_COUNT, + {unit: '1', description: 'Number of attempts.'}, + ); + + this._instrumentOperationLatency = meter.createHistogram( + Constants.METRIC_NAME_OPERATION_LATENCIES, + { + unit: 'ms', + description: + 'Total time until final operation success or failure, including retries and backoff.', + }, + ); + + this._instrumentOperationCounter = meter.createCounter( + Constants.METRIC_NAME_OPERATION_COUNT, + {unit: '1', description: 'Number of operations.'}, + ); + + this._instrumentGfeLatency = meter.createHistogram( + Constants.METRIC_NAME_GFE_LATENCIES, + { + unit: 'ms', + description: + "Latency between Google's network receiving an RPC and reading back the first byte of the response", + }, + ); + + this._instrumentGfeConnectivityErrorCount = meter.createCounter( + Constants.METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, + { + unit: '1', + description: + 'Number of requests that failed to reach the Google network.', + }, + ); + + this._instrumentAfeLatency = meter.createHistogram( + Constants.METRIC_NAME_AFE_LATENCIES, + { + unit: 'ms', + description: + 'Latency between Spanner API Frontend receiving an RPC and starting to write back the response', + }, + ); + + this._instrumentAfeConnectivityErrorCount = meter.createCounter( + Constants.METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT, + { + unit: '1', + description: + 'Number of requests that failed to reach the Spanner API Frontend.', + }, + ); + } + + /** + * Generates a unique identifier for the client_uid metric field. The identifier is composed of a + * UUID, the process ID (PID), and the hostname. + * @returns A unique string identifier for the client. + */ + private static _generateClientUId(): string { + const identifier = uuidv4(); + const pid = process.pid.toString(); + let hostname = 'localhost'; + + try { + hostname = os.hostname(); + } catch (err) { + console.warn('Unable to get the hostname.', err); + } + + return `${identifier}@${pid}@${hostname}`; + } + + /** + * Generates a 6-digit zero-padded lowercase hexadecimal hash using the 10 most significant bits + * of a 64-bit hash value. + * + * The primary purpose of this function is to generate a hash value for the `client_hash` + * resource label using `client_uid` metric field. The range of values is chosen to be small + * enough to keep the cardinality of the Resource targets under control. Note: If at later time + * the range needs to be increased, it can be done by increasing the value of `kPrefixLength` to + * up to 24 bits without changing the format of the returned value. + * @param clientUid The client UID string to hash. + * @returns A 6-digit hexadecimal hash string. + */ + private static _generateClientHash(clientUid: string): string { + if (clientUid === null || clientUid === undefined) { + return '000000'; + } + + const hash = crypto.createHash('sha256'); + hash.update(clientUid); + const digest = hash.digest('hex'); + const hashPart = digest.substring(0, 16); + const longHash = BigInt('0x' + hashPart); + const kPrefixLength = 10; + const shiftedValue = longHash >> BigInt(64 - kPrefixLength); + return shiftedValue.toString(16).padStart(6, '0'); + } + + /** + * Gets the location (region) of the client, otherwise returns to the "global" region. + * Uses GcpDetectorSync to detect the region from the environment. + * @returns The detected region string, or "global" if not found. + */ + private static async _detectClientLocation(): Promise { + const defaultRegion = 'global'; + try { + const resource = await detectResources({ + detectors: [new GcpDetectorSync()], + }); + + await resource?.waitForAsyncAttributes?.(); + + const region = resource.attributes[Constants.ATTR_CLOUD_REGION]; + if (typeof region === 'string' && region) { + return region; + } + } catch (err) { + console.warn('Unable to detect location.', err); + } + return defaultRegion; + } + + private _cleanMetricsTracers() { + if (this._currentOperationLastUpdatedMs.size === 0) { + return; + } + + for (const [ + operationTracer, + lastUpdated, + ] of this._currentOperationLastUpdatedMs.entries()) { + if (Date.now() - lastUpdated >= Constants.TRACER_CLEANUP_THRESHOLD_MS) { + this._currentOperationTracers.delete(operationTracer); + this._currentOperationLastUpdatedMs.delete(operationTracer); + } + } + } +} diff --git a/handwritten/spanner/src/metrics/metrics-tracer.ts b/handwritten/spanner/src/metrics/metrics-tracer.ts new file mode 100644 index 00000000000..d41347a03c7 --- /dev/null +++ b/handwritten/spanner/src/metrics/metrics-tracer.ts @@ -0,0 +1,403 @@ +// 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 +// +// 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. + +import {status as Status} from '@grpc/grpc-js'; +import {Counter, Histogram} from '@opentelemetry/api'; +import {MetricsTracerFactory} from './metrics-tracer-factory'; +import { + METRIC_LABEL_KEY_DATABASE, + METRIC_LABEL_KEY_METHOD, + METRIC_LABEL_KEY_STATUS, + MONITORED_RES_LABEL_KEY_INSTANCE, +} from './constants'; +import {Spanner} from '..'; + +/** + * MetricAttemptTracer tracks the start time and status of a single gRPC attempt. + * + * This class is used to record the timestamp when an attempt begins and to store + * the status code of the attempt upon completion. It is to be used + * by MetricsTracer to monitor and report metrics for each individual gRPC call attempt. + */ +class MetricAttemptTracer { + private _startTime: Date; + public status: string; + + constructor() { + this._startTime = new Date(Date.now()); + this.status = Status[Status.UNKNOWN]; + } + + /** + * Returns the start time of the attempt. + */ + get startTime() { + return this._startTime; + } +} + +/** + * MetricOperationTracer tracks the lifecycle and metadata of a single gRPC spanner operation, + * which may consist of multiple attempts. + * + * This class is responsible for: + * - Recording the start time of the operation. + * - Tracking the number of attempts made for the operation. + * - Holding a reference to the current attempt's tracer (MetricAttemptTracer). + * - Storing the final status code of the operation. + * + * Usage: + * - Call `start()` to reset the operation's start time. + * - Call `createNewAttempt()` to begin tracking a new attempt within the operation. + * - Access `currentAttempt` to retrieve the current MetricAttemptTracer instance. + * - Access `attemptCount` to get the number of attempts made so far. + * - Access `startTime` to get the operation's start time. + * - Set or read `status` to track the operation's final status code. + */ +class MetricOperationTracer { + private _attemptCount: number; + private _startTime: Date; + private _currentAttempt: MetricAttemptTracer | null; + + constructor() { + this._attemptCount = 0; + this._startTime = new Date(Date.now()); + this._currentAttempt = null; + } + + /** + * Returns the number of attempts made for this operation. + */ + get attemptCount() { + return this._attemptCount; + } + + /** + * Returns the current MetricAttemptTracer instance for the ongoing attempt. + */ + get currentAttempt() { + return this._currentAttempt; + } + + /** + * Returns the start time of the operation. + */ + get startTime() { + return this._startTime; + } + + /** + * Increments the attempt count and creates a new MetricAttemptTracer + * for tracking the next attempt within this operation. + */ + public createNewAttempt() { + this._attemptCount += 1; + this._currentAttempt = new MetricAttemptTracer(); + } +} + +/** + * MetricsTracer is responsible for recording and managing metrics related to + * gRPC Spanner operations and attempts counters, and latencies, + * as well as Google Front End (GFE)/AFE metrics such as latency and connectivity errors. + * + * This class provides methods to record the start and completion of operations + * and attempts, extract GFE/AFE latency from response headers. + * It also handles setting of required Spanner metric attributes to + * be later consumed by the SpannerMetricsExporter. + */ +export class MetricsTracer { + /** + * The current MetricOperationTracer instance tracking the ongoing operation. + */ + public currentOperation: MetricOperationTracer | null = null; + + /** + * Stores client and resource attributes for labeling metrics. + */ + private _clientAttributes: {[key: string]: string} = {}; + + /* + * The current GFE latency associated with this tracer. + */ + public gfeLatency: number | null = null; + + /* + * The current AFE latency associated with this tracer. + */ + public afeLatency: number | null = null; + + /** + * Constructs a new MetricsTracer. + * + * @param _instrumentAttemptCounter Counter for attempt count metrics. + * @param _instrumentAttemptLatency Histogram for attempt latency metrics. + * @param _instrumentOperationCounter Counter for operation count metrics. + * @param _instrumentOperationLatency Histogram for operation latency metrics. + * @param _instrumentGfeConnectivityErrorCount Counter for GFE connectivity errors. + * @param _instrumentGfeLatency Histogram for GFE latency metrics. + * @param _instrumentAfeConnectivityErrorCount Counter for AFE connectivity errors. + * @param _instrumentAfeLatency Histogram for AFE latency metrics. + * @param enabled Whether metrics recording is enabled. + */ + constructor( + private _instrumentAttemptCounter: Counter | null, + private _instrumentAttemptLatency: Histogram | null, + private _instrumentOperationCounter: Counter | null, + private _instrumentOperationLatency: Histogram | null, + private _instrumentGfeConnectivityErrorCount: Counter | null, + private _instrumentGfeLatency: Histogram | null, + private _instrumentAfeConnectivityErrorCount: Counter | null, + private _instrumentAfeLatency: Histogram | null, + public enabled: boolean, + private _database: string, + private _instance: string, + private _projectId: string, + private _methodName: string, + private _request: string, + ) { + this._clientAttributes[METRIC_LABEL_KEY_DATABASE] = _database; + this._clientAttributes[METRIC_LABEL_KEY_METHOD] = _methodName; + this._clientAttributes[MONITORED_RES_LABEL_KEY_INSTANCE] = _instance; + } + + /** + * Returns the difference in milliseconds between two Date objects. + * @param start The start time. + * @param end The end time. + * @returns The time difference in milliseconds. + */ + private _getMillisecondTimeDifference(start: Date, end: Date): number { + return end.valueOf() - start.valueOf(); + } + + /** + * Gets the current client and resource attributes for metrics. + */ + get clientAttributes() { + return this._clientAttributes; + } + + /** + * Gets the attempt counter OTEL instrument. + */ + get instrumentAttemptCounter() { + return this._instrumentAttemptCounter; + } + + /** + * Gets the attempt latency histogram OTEL instrument. + */ + get instrumentAttemptLatency() { + return this._instrumentAttemptLatency; + } + + /** + * Gets the operation counter OTEL instrument. + */ + get instrumentOperationCounter() { + return this._instrumentOperationCounter; + } + + /** + * Gets the operation latency histogram OTEL instrument. + */ + get instrumentOperationLatency() { + return this._instrumentOperationLatency; + } + + /** + * Records the start of a new attempt within the current operation. + * Increments the attempt count and creates a new MetricAttemptTracer. + */ + public recordAttemptStart() { + if (!this.enabled) return; + this.currentOperation!.createNewAttempt(); + } + + /** + * Records the completion of the current attempt, including its status and latency. + * These statuses code are defined in grpc.status + * @param status The status code of the attempt (default: Status.OK). + */ + public recordAttemptCompletion(statusCode: Status = Status.OK) { + if (!this.enabled) return; + this.currentOperation!.currentAttempt!.status = Status[statusCode]; + const attemptAttributes = this._createAttemptOtelAttributes(); + const endTime = new Date(Date.now()); + const attemptLatencyMilliseconds = this._getMillisecondTimeDifference( + this.currentOperation!.currentAttempt!.startTime, + endTime, + ); + this.instrumentAttemptLatency?.record( + attemptLatencyMilliseconds, + attemptAttributes, + ); + + this.instrumentAttemptCounter?.add(1, attemptAttributes); + } + + /** + * Records the start of a new operation, resetting the operation tracer and start time. + */ + public recordOperationStart() { + if (!this.enabled) return; + if (this.currentOperation !== null) { + return; // Don't re-start an already started operation + } + this.currentOperation = new MetricOperationTracer(); + } + + /** + * Records the completion of the current operation, including its status, + * latency, and attempt count. Also clears the current tracer from the factory. + */ + public recordOperationCompletion() { + if (!this.enabled || !this.currentOperation) return; + const endTime = new Date(Date.now()); + const operationAttributes = this._createOperationOtelAttributes(); + const operationLatencyMilliseconds = this._getMillisecondTimeDifference( + this.currentOperation!.startTime, + endTime, + ); + + this.instrumentOperationCounter?.add(1, operationAttributes); + this.instrumentOperationLatency?.record( + operationLatencyMilliseconds, + operationAttributes, + ); + MetricsTracerFactory.getInstance(this._projectId)!.clearCurrentTracer( + this._request, + ); + } + + /** + * Extracts the GFE latency value (in milliseconds) from a 'server-timing' header string. + * Returns null if the header is missing or does not contain a valid latency value. + * + * @param header The 'server-timing' header string. + * @returns The extracted GFE latency in milliseconds, or null if not found. + */ + public extractGfeLatency(header: string): number | null { + const regex = /gfet4t7; dur=([0-9]+).*/; + if (header === undefined) return null; + const match = header.match(regex); + if (!match) return null; + return Number(match[1]); + } + + /** + * Extracts the AFE latency value (in milliseconds) from a 'server-timing' header string. + * Returns null if the header is missing or does not contain a valid latency value. + * + * @param header The 'server-timing' header string. + * @returns The extracted AFE latency in milliseconds, or null if not found. + */ + public extractAfeLatency(header: string): number | null { + if (!Spanner.isAFEServerTimingEnabled()) return null; + const regex = /afe; dur=([0-9]+).*/; + if (header === undefined) return null; + const match = header.match(regex); + if (!match) return null; + return Number(match[1]); + } + + /** + * Records the provided GFE latency. + * @param latency The GFE latency in milliseconds. + */ + public recordGfeLatency(statusCode: Status) { + if (!this.enabled) return; + if (!this.gfeLatency) { + console.error( + 'ERROR: Attempted to record GFE metric with no latency value.', + ); + return; + } + + const attributes = {...this._clientAttributes}; + attributes[METRIC_LABEL_KEY_STATUS] = Status[statusCode]; + + this._instrumentGfeLatency?.record(this.gfeLatency, attributes); + this.gfeLatency = null; // Reset latency value + } + + /** + * Increments the GFE connectivity error count metric. + */ + public recordGfeConnectivityErrorCount(statusCode: Status) { + if (!this.enabled) return; + const attributes = {...this._clientAttributes}; + attributes[METRIC_LABEL_KEY_STATUS] = Status[statusCode]; + this._instrumentGfeConnectivityErrorCount?.add(1, attributes); + } + + /** + * Increments the AFE connectivity error count metric. + */ + public recordAfeConnectivityErrorCount(statusCode: Status) { + if (!this.enabled || !Spanner.isAFEServerTimingEnabled()) return; + const attributes = {...this._clientAttributes}; + attributes[METRIC_LABEL_KEY_STATUS] = Status[statusCode]; + this._instrumentAfeConnectivityErrorCount?.add(1, attributes); + } + + /** + * Records the provided AFE latency. + * @param latency The AFE latency in milliseconds. + */ + public recordAfeLatency(statusCode: Status) { + if (!this.enabled || !Spanner.isAFEServerTimingEnabled()) return; + if (!this.afeLatency) { + console.error( + 'ERROR: Attempted to record AFE metric with no latency value.', + ); + return; + } + + const attributes = {...this._clientAttributes}; + attributes[METRIC_LABEL_KEY_STATUS] = Status[statusCode]; + + this._instrumentAfeLatency?.record(this.afeLatency, attributes); + this.afeLatency = null; // Reset latency value + } + + /** + * Creates and returns a set of OTEL attributes for operation-level metrics. + * @returns The operation attributes object. + */ + private _createOperationOtelAttributes() { + if (!this.enabled) return {}; + const attributes = {...this._clientAttributes}; + attributes[METRIC_LABEL_KEY_STATUS] = + this.currentOperation!.currentAttempt?.status ?? Status[Status.UNKNOWN]; + return attributes; + } + + /** + * Creates and returns a set of OTEL attributes for attempt-level metrics. + * The overall operation status is set at this time based on the last + * attempt's status. + * @returns The attempt attributes object. + */ + private _createAttemptOtelAttributes() { + if (!this.enabled) return {}; + const attributes = {...this._clientAttributes}; + if (this.currentOperation?.currentAttempt === null) return attributes; + attributes[METRIC_LABEL_KEY_STATUS] = + this.currentOperation!.currentAttempt.status; + + return attributes; + } +} diff --git a/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts b/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts new file mode 100644 index 00000000000..0a1ac7ae6c2 --- /dev/null +++ b/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts @@ -0,0 +1,141 @@ +// 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 {PushMetricExporter, ResourceMetrics} from '@opentelemetry/sdk-metrics'; +import {ExportResult, ExportResultCode} from '@opentelemetry/core'; +import {ExporterOptions} from './external-types'; +import {MetricServiceClient} from '@google-cloud/monitoring'; +import {transformResourceMetricToTimeSeriesArray} from './transform'; +import {status} from '@grpc/grpc-js'; +import {MIN_EXPORT_FREQUENCY_MS} from './constants'; + +// Stackdriver Monitoring v3 only accepts up to 200 TimeSeries per +// CreateTimeSeries call. +export const MAX_BATCH_EXPORT_SIZE = 200; + +/** + * Format and sends metrics information to Google Cloud Monitoring. + */ +export class CloudMonitoringMetricsExporter implements PushMetricExporter { + private _projectId: string; + private _lastExported: Date = new Date(0); + private readonly _client: MetricServiceClient; + private _metricsExportFailureLogged = false; + + constructor({auth}: ExporterOptions, projectId: string) { + this._client = new MetricServiceClient({auth: auth}); + + this._projectId = projectId; + } + + /** + * Implementation for {@link PushMetricExporter.export}. + * Calls the async wrapper method {@link _exportAsync} and + * assures no rejected promises bubble up to the caller. + * + * @param metrics Metrics to be sent to the Google Cloud 3Monitoring backend + * @param resultCallback result callback to be called on finish + */ + export( + metrics: ResourceMetrics, + resultCallback: (result: ExportResult) => void, + ): void { + // Do not export metrics if we've already exported within the last 30s + const now = new Date(); + if ( + now.getTime() - this._lastExported.getTime() <= + MIN_EXPORT_FREQUENCY_MS + ) { + return; + } + + this._lastExported = now; + this._exportAsync(metrics).then(resultCallback, err => { + resultCallback({code: ExportResultCode.FAILED, error: err}); + }); + } + + async shutdown(): Promise {} + async forceFlush(): Promise {} + + /** + * Asnyc wrapper for the {@link export} implementation. + * Writes the current values of all exported {@link MetricRecord}s + * to the Google Cloud Monitoring backend. + * + * @param resourceMetrics Metrics to be sent to the Google Cloud Monitoring backend + */ + private async _exportAsync( + resourceMetrics: ResourceMetrics, + ): Promise { + const timeSeriesList = transformResourceMetricToTimeSeriesArray( + resourceMetrics, + this._projectId, + ); + + let failure: {sendFailed: false} | {sendFailed: true; error: Error} = { + sendFailed: false, + }; + await Promise.all( + this._partitionList(timeSeriesList, MAX_BATCH_EXPORT_SIZE).map( + async batchedTimeSeries => this._sendTimeSeries(batchedTimeSeries), + ), + ).catch(e => { + if (!this._metricsExportFailureLogged) { + const error = e as {code: number}; + let msg = 'Send TimeSeries failed:'; + if (error.code === status.PERMISSION_DENIED) { + msg += ` Need monitoring metric writer permission on project ${this._projectId}. Follow https://cloud.google.com/spanner/docs/view-manage-client-side-metrics#access-client-side-metrics to set up permissions`; + } + console.warn(msg); + this._metricsExportFailureLogged = true; + } + failure = {sendFailed: true, error: asError(e)}; + }); + + if (!failure.sendFailed && this._metricsExportFailureLogged) { + this._metricsExportFailureLogged = false; + } + + return failure.sendFailed + ? { + code: ExportResultCode.FAILED, + error: (failure as {sendFailed: boolean; error: Error}).error, + } + : {code: ExportResultCode.SUCCESS}; + } + + private async _sendTimeSeries(timeSeries) { + if (timeSeries.length === 0) { + return Promise.resolve(); + } + + // TODO: Use createServiceTimeSeries when it is available + await this._client.createTimeSeries({ + name: `projects/${this._projectId}`, + timeSeries: timeSeries, + }); + } + + /** Returns the minimum number of arrays of max size chunkSize, partitioned from the given array. */ + private _partitionList(list, chunkSize: number) { + return Array.from({length: Math.ceil(list.length / chunkSize)}, (_, i) => + list.slice(i * chunkSize, (i + 1) * chunkSize), + ); + } +} + +function asError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); +} diff --git a/handwritten/spanner/src/metrics/transform.ts b/handwritten/spanner/src/metrics/transform.ts new file mode 100644 index 00000000000..71a0052c1ee --- /dev/null +++ b/handwritten/spanner/src/metrics/transform.ts @@ -0,0 +1,344 @@ +// 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 { + Histogram, + MetricData, + DataPoint, + DataPointType, + ExponentialHistogram, + ResourceMetrics, +} from '@opentelemetry/sdk-metrics'; +import {Resource} from '@opentelemetry/resources'; +import {MonitoredResource} from '@google-cloud/opentelemetry-resource-util'; +import * as path from 'path'; +import {MetricKind, ValueType} from './external-types'; +import { + SPANNER_METER_NAME, + CLIENT_METRICS_PREFIX, + SPANNER_RESOURCE_TYPE, + METRIC_LABELS, + MONITORED_RESOURCE_LABELS, + METRIC_NAMES, + METRIC_LABEL_KEY_CLIENT_UID, + METRIC_LABEL_KEY_CLIENT_NAME, + UNKNOWN_ATTRIBUTE, +} from './constants'; +import {MetricsTracerFactory} from './metrics-tracer-factory'; + +/** Transforms a OpenTelemetry instrument type to a GCM MetricKind. */ +function _transformMetricKind(metric: MetricData): MetricKind { + switch (metric.dataPointType) { + case DataPointType.SUM: + return metric.isMonotonic ? MetricKind.CUMULATIVE : MetricKind.GAUGE; + case DataPointType.GAUGE: + return MetricKind.GAUGE; + case DataPointType.HISTOGRAM: + case DataPointType.EXPONENTIAL_HISTOGRAM: + return MetricKind.CUMULATIVE; + default: + exhaust(metric); + // No logging needed as it will be done in transformPoints() + return MetricKind.UNSPECIFIED; + } +} + +/** Transforms resource to Google Cloud Monitoring monitored resource */ +function _transformResource(labels: { + [key: string]: string; +}): MonitoredResource { + return { + type: SPANNER_RESOURCE_TYPE, + labels: labels, + } as MonitoredResource; +} + +/** Transforms a OpenTelemetry ValueType to a GCM ValueType. */ +function _transformValueType(metric: MetricData): ValueType { + const { + dataPointType, + descriptor: {name}, + } = metric; + + if ( + dataPointType === DataPointType.HISTOGRAM || + dataPointType === DataPointType.EXPONENTIAL_HISTOGRAM + ) { + return ValueType.DISTRIBUTION; + } else if (dataPointType === DataPointType.SUM) { + return ValueType.INT64; + } else if (dataPointType === DataPointType.GAUGE) { + return ValueType.DOUBLE; + } + console.warn('Encountered unexpected metric %s', name); + return ValueType.VALUE_TYPE_UNSPECIFIED; +} + +/** + * Convert the metrics data to a list of Google Cloud Monitoring time series. + */ +export function transformResourceMetricToTimeSeriesArray( + resourceMetrics: ResourceMetrics, + projectId: string, +) { + const resource = resourceMetrics?.resource; + const scopeMetrics = resourceMetrics?.scopeMetrics; + if (!scopeMetrics) return []; + + return ( + scopeMetrics + // Only keep those whose scope.name matches 'spanner-nodejs'. + .filter(({scope: {name}}) => name === SPANNER_METER_NAME) + // Takes each metric array and flattens it into one array + .flatMap(({metrics}) => + // Only keeps metrics that match our spanner metric names + metrics.filter(metric => METRIC_NAMES.has(metric.descriptor.name)), + ) + // Flatmap the data points in each metric to create a TimeSeries for each point + .flatMap(metric => + metric.dataPoints.flatMap(dataPoint => + _createTimeSeries(metric, dataPoint, resource, projectId), + ), + ) + ); +} + +/** + * Creates a GCM TimeSeries. + */ +function _createTimeSeries( + metric: MetricData, + dataPoint: DataPoint, + resource: Resource, + projectId: string, +) { + const type = path.posix.join(CLIENT_METRICS_PREFIX, metric.descriptor.name); + const resourceLabels = resource + ? _extractLabels(resource, projectId) + : {metricLabels: {}, monitoredResourceLabels: {}}; + + const dataLabels = _extractLabels(dataPoint, projectId); + + const labels = { + ...resourceLabels.metricLabels, + ...dataLabels.metricLabels, + }; + + const monitoredResourceLabels = { + ...resourceLabels.monitoredResourceLabels, + ...dataLabels.monitoredResourceLabels, + }; + + const transformedMetric = { + type, + labels, + }; + + return { + metric: transformedMetric, + resource: _transformResource(monitoredResourceLabels), + metricKind: _transformMetricKind(metric), + valueType: _transformValueType(metric), + points: [_transformPoint(metric, dataPoint)], + unit: metric.descriptor.unit, + }; +} + +/** + * Transform timeseries's point, so that metric can be uploaded to GCM. + */ +function _transformPoint(metric: MetricData, dataPoint: DataPoint) { + switch (metric.dataPointType) { + case DataPointType.SUM: + case DataPointType.GAUGE: + return { + value: _transformNumberValue( + _transformValueType(metric), + dataPoint.value as number, + ), + interval: { + // Add start time for non-gauge points + ...(metric.dataPointType === DataPointType.SUM && metric.isMonotonic + ? { + startTime: _formatHrTimeToGcmTime(dataPoint.startTime), + } + : null), + endTime: _formatHrTimeToGcmTime(dataPoint.endTime), + }, + }; + case DataPointType.HISTOGRAM: + return { + value: _transformHistogramValue(dataPoint.value as Histogram), + interval: { + startTime: _formatHrTimeToGcmTime(dataPoint.startTime), + endTime: _formatHrTimeToGcmTime(dataPoint.endTime), + }, + }; + case DataPointType.EXPONENTIAL_HISTOGRAM: + return { + value: _transformExponentialHistogramValue( + dataPoint.value as ExponentialHistogram, + ), + interval: { + startTime: _formatHrTimeToGcmTime(dataPoint.startTime), + endTime: _formatHrTimeToGcmTime(dataPoint.endTime), + }, + }; + default: + exhaust(metric); + return { + value: dataPoint.value, + interval: { + endTime: _formatHrTimeToGcmTime(dataPoint.endTime), + }, + }; + } +} + +/** Extracts metric and monitored resource labels from data point */ +function _extractLabels( + {attributes = {}}: DataPoint | Resource, + projectId: string, +) { + const factory = MetricsTracerFactory.getInstance(projectId); + // Add Client name and Client UID metric labels + attributes[METRIC_LABEL_KEY_CLIENT_UID] = + factory?.clientUid ?? UNKNOWN_ATTRIBUTE; + attributes[METRIC_LABEL_KEY_CLIENT_NAME] = + factory?.clientName ?? UNKNOWN_ATTRIBUTE; + return Object.entries(attributes).reduce( + (result, [key, value]) => { + const normalizedKey = _normalizeLabelKey(key); + const val = value?.toString(); + + if (METRIC_LABELS.has(key)) result.metricLabels[normalizedKey] = val; + + if (MONITORED_RESOURCE_LABELS.has(key)) + result.monitoredResourceLabels[normalizedKey] = val; + + return result; + }, + {metricLabels: {}, monitoredResourceLabels: {}}, + ); +} + +function _normalizeLabelKey(key: string): string { + // Replace characters which are not Letter or Decimal_Number unicode category with "_", see + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes + // + // Reimplementation of reference impl in Go: + // https://github.com/GoogleCloudPlatform/opentelemetry-operations-go/blob/e955c204f4f2bfdc92ff0ad52786232b975efcc2/exporter/metric/metric.go#L595-L604 + let sanitized = key.replace(/[^\p{Letter}\p{Decimal_Number}_]/gu, '_'); + + if (sanitized[0].match(/\p{Decimal_Number}/u)) { + sanitized = 'key_' + sanitized; + } + return sanitized; +} + +/** Transforms a OpenTelemetry Point's value to a GCM Point value. */ +function _transformNumberValue(valueType: ValueType, value: number) { + if (valueType === ValueType.INT64) { + return {int64Value: Math.round(value).toString()}; + } else if (valueType === ValueType.DOUBLE) { + const doubleString = Number.isInteger(value) + ? `${value}.0` + : value.toString(); + return {doubleValue: doubleString}; + } + throw Error(`unsupported value type: ${valueType}`); +} + +function _transformHistogramValue(value: Histogram) { + return { + distributionValue: { + // sumOfSquaredDeviation param not aggregated + count: value.count.toString(), + mean: value.count && value.sum ? value.sum / value.count : 0, + bucketOptions: { + explicitBuckets: {bounds: value.buckets.boundaries}, + }, + bucketCounts: value.buckets.counts.map(value => value.toString()), + }, + }; +} + +function _transformExponentialHistogramValue(value: ExponentialHistogram) { + // Adapated from reference impl in Go which has more explanatory comments + // https://github.com/GoogleCloudPlatform/opentelemetry-operations-go/blob/v1.8.0/exporter/collector/metrics.go#L582 + const underflow = + value.zeroCount + + value.negative.bucketCounts.reduce((prev, current) => prev + current, 0); + const bucketCounts = [ + underflow, + ...value.positive.bucketCounts, + 0, // overflow bucket is always empty + ]; + + let bucketOptions; + if (value.positive.bucketCounts.length === 0) { + bucketOptions = { + explicitBuckets: {bounds: []}, + }; + } else { + const growthFactor = Math.pow(2, Math.pow(2, -value.scale)); //exp2(exp2(-value.scale)); + const scale = Math.pow(growthFactor, value.positive.offset); + bucketOptions = { + exponentialBuckets: { + growthFactor, + scale, + numFiniteBuckets: bucketCounts.length - 2, + }, + }; + } + + const mean = + value.sum === undefined || value.count === 0 ? 0 : value.sum / value.count; + + return { + distributionValue: { + // sumOfSquaredDeviation param not aggregated + count: value.count.toString(), + mean, + bucketOptions, + bucketCounts: bucketCounts.map(value => value.toString()), + }, + }; +} + +/** Transforms an OpenTelemetry time value to a GCM time value. */ +function _formatHrTimeToGcmTime(hrTime) { + return { + seconds: hrTime[0], + nanos: hrTime[1], + }; +} + +/** + * Assert switch case is exhaustive + */ +function exhaust(switchValue: never) { + return switchValue; +} + +export const _TEST_ONLY = { + _normalizeLabelKey, + _transformMetricKind, + _extractLabels, + _formatHrTimeToGcmTime, + _transformResource, + _transformPoint, + _transformValueType, + transformResourceMetricToTimeSeriesArray, +}; diff --git a/handwritten/spanner/src/multiplexed-session.ts b/handwritten/spanner/src/multiplexed-session.ts new file mode 100644 index 00000000000..fdcc6675ceb --- /dev/null +++ b/handwritten/spanner/src/multiplexed-session.ts @@ -0,0 +1,250 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 {EventEmitter} from 'events'; +import {Database} from './database'; +import {Session} from './session'; +import {GetSessionCallback} from './session-factory'; +import { + ObservabilityOptions, + getActiveOrNoopSpan, + setSpanError, + startTrace, +} from './instrument'; + +/** + * Interface for implementing multiplexed session logic, it should extend the + * {@link https://nodejs.org/api/events.html|EventEmitter} class + * + * @interface MultiplexedSessionInterface + * @extends external:{@link https://nodejs.org/api/events.html|EventEmitter} + * + * @constructs MultiplexedSessionInterface + * @param {Database} database The database to create a multiplexed session for. + */ +export interface MultiplexedSessionInterface extends EventEmitter { + /** + * When called creates a multiplexed session. + * + * @name MultiplexedSessionInterface#createSession + */ + createSession(): void; + + /** + * When called returns a multiplexed session. + * + * @name MultiplexedSessionInterface#getSession + * @param {GetSessionCallback} callback The callback function. + */ + getSession(callback: GetSessionCallback): void; +} + +/** + * Class used to manage connections to Spanner using multiplexed session. + * + * **You don't need to use this class directly, connections will be handled for + * you.** + * + * @class + * @extends {EventEmitter} + */ +export class MultiplexedSession + extends EventEmitter + implements MultiplexedSessionInterface +{ + database: Database; + // frequency to create new mux session + refreshRate: number; + _multiplexedSession: Session | null; + _refreshHandle!: NodeJS.Timeout; + _observabilityOptions?: ObservabilityOptions; + // shared promise lock to handle concurrent session creation requests + _sharedMuxSessionWaitPromise: Promise | null; + constructor(database: Database) { + super(); + this.database = database; + // default frequency is 7 days + this.refreshRate = 7; + this._multiplexedSession = null; + this._observabilityOptions = database._observabilityOptions; + this._sharedMuxSessionWaitPromise = null; + } + + /** + * Creates a new multiplexed session and manages its maintenance. + * + * This method initiates the session creation process by calling the `_createSession` method, which returns a Promise. + * + * Errors are silently swallowed here to prevent unhandled promise rejections or application crashes during background operations. + */ + createSession(): void { + this._createSession() + .then(() => { + this._maintain(); + }) + // Ignore errors here. If this fails, the next user request will + // automatically trigger a retry via `_getSession`. + .catch(err => {}); + } + + /** + * Creates a new multiplexed session. + * + * This method sends a request to the database to create a new session with multiplexing enabled. + * The response from the database would be an array, the first value of the array will be containing the multiplexed session. + * + * @returns {Promise} Resolves when the session is successfully created. + * @throws {Error} If the request fails, the error is thrown to the caller. + * + * @private + */ + async _createSession(): Promise { + // If a session is already being created, just wait for it to complete. + if (this._sharedMuxSessionWaitPromise) { + return this._sharedMuxSessionWaitPromise; + } + + // Define the async task that performs the actual session creation and tracing. + const task = async () => { + const traceConfig = { + opts: this._observabilityOptions, + dbName: this.database.formattedName_, + }; + return startTrace( + 'MultiplexedSession.createSession', + traceConfig, + async span => { + span.addEvent('Requesting a multiplexed session'); + try { + const [createSessionResponse] = await this.database.createSession({ + multiplexed: true, + }); + this._multiplexedSession = createSessionResponse; + span.addEvent('Created a multiplexed session'); + } catch (e) { + setSpanError(span, e as Error); + throw e; + } finally { + span.end(); + } + }, + ); + }; + + // Assign the running task to the shared promise variable, and ensure + // the lock is released when it completes. + this._sharedMuxSessionWaitPromise = task().finally(() => { + this._sharedMuxSessionWaitPromise = null; + }); + + return this._sharedMuxSessionWaitPromise; + } + + /** + * Maintains the multiplexed session by periodically refreshing it. + * + * This method sets up a periodic refresh interval for maintaining the session. The interval duration + * is determined by the @param refreshRate option, which is provided in days. + * The default value is 7 days. + * + * @throws {Error} If the multiplexed session creation fails in `_createSession`, the error is caught + * and ignored. This is because the currently active multiplexed session has a 30-day expiry, providing + * the maintainer with four opportunities (one every 7 days) to refresh the active session. + * + * Hence, if the `_createSession` fails here, the system will either simply retry at the next interval or + * upon the next user request if the session expires. + * + * @returns {void} This method does not return any value. + * + */ + _maintain(): void { + // If a maintenance loop is already running, stop it first. + // This prevents creating duplicate intervals if _maintain is called multiple times. + if (this._refreshHandle) { + clearInterval(this._refreshHandle); + } + const refreshRate = this.refreshRate! * 24 * 60 * 60000; + this._refreshHandle = setInterval(async () => { + await this._createSession().catch(() => {}); + }, refreshRate); + + // Unreference the timer so it does not prevent the Node.js process from exiting. + // If the application has finished all other work, this background timer shouldn't + // force the process to stay open. + this._refreshHandle.unref(); + } + + /** + * Retrieves a session asynchronously and invokes a callback with the session details. + * + * @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs. + * + * @returns {void} This method does not return any value, as it operates asynchronously and relies on the callback. + * + */ + getSession(callback: GetSessionCallback): void { + this._getSession().then( + session => + callback( + null, + session, + session!.transaction((session!.parent as Database).queryOptions_), + ), + callback, + ); + } + + /** + * Attempts to get a session, waiting for it to become available if necessary. + * + * Logic Flow: + * 1. Cache Hit: If a session exists, return it immediately. + * 2. Join Wait: If another request is currently creating the session (`_sharedMuxSessionWaitPromise` exists), await it. + * 3. Create: If neither, initiate a new creation request (`_createSession`). + * + * @throws {Error} In case of an error, the promise will get rejected and the error will get bubble up to the parent method. + * + * @returns {Promise} A promise that resolves with the active multiplexed session. + * + * @private + * + */ + async _getSession(): Promise { + const span = getActiveOrNoopSpan(); + // Check if the multiplexed session is already available + if (this._multiplexedSession !== null) { + span.addEvent('Cache hit: has usable multiplexed session'); + return this._multiplexedSession; + } + + span.addEvent('Waiting for a multiplexed session to become available'); + + // If initialization is ALREADY in progress, join the existing line! + if (this._sharedMuxSessionWaitPromise) { + await this._sharedMuxSessionWaitPromise; + } else { + // If the session is null, and nobody is currently initializing it + // It means a previous attempt failed and we are in a "Dead" state + // We must kickstart the process again + await this._createSession(); + } + + span.addEvent('Acquired multiplexed session'); + + // Return the multiplexed session after it becomes available + return this._multiplexedSession; + } +} diff --git a/handwritten/spanner/src/partial-result-stream.ts b/handwritten/spanner/src/partial-result-stream.ts new file mode 100644 index 00000000000..e37ec68f0eb --- /dev/null +++ b/handwritten/spanner/src/partial-result-stream.ts @@ -0,0 +1,624 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 {GrpcService} from './common-grpc/service'; +import * as checkpointStream from 'checkpoint-stream'; +import * as eventsIntercept from 'events-intercept'; +import mergeStream = require('merge-stream'); +import {common as p} from 'protobufjs'; +import {Readable, Transform} from 'stream'; +import * as streamEvents from 'stream-events'; +import {grpc, CallOptions} from 'google-gax'; +import {DeadlineError, isRetryableInternalError} from './transaction-runner'; + +import {codec, JSONOptions, Json, Field, Value} from './codec'; +import {google} from '../protos/protos'; +import * as stream from 'stream'; +import {isDefined, isEmpty, isString} from './helper'; + +export type ResumeToken = string | Uint8Array; + +/** + * @callback RequestFunction + * @param {string} [resumeToken] The token used to resume getting results. + * @returns {Stream} + */ +interface RequestFunction { + (resumeToken?: ResumeToken): Readable; +} + +/** + * @typedef RowOptions + * @property {boolean} [json=false] Indicates if the Row objects should be + * formatted into JSON. + * @property {JSONOptions} [jsonOptions] JSON options. + * @property {number} [maxResumeRetries=20] The maximum number of times that the + * stream will retry to push data downstream, when the downstream indicates + * that it is not ready for any more data. Increase this value if you + * experience 'Stream is still not ready to receive data' errors as a + * result of a slow writer in your receiving stream. + * @property {object} [columnsMetadata] An object map that can be used to pass + * additional properties for each column type which can help in deserializing + * the data coming from backend. (Eg: We need to pass Proto Function and Enum + * map to deserialize proto messages and enums, respectively.) + */ +export interface RowOptions { + json?: boolean; + jsonOptions?: JSONOptions; + maxResumeRetries?: number; + /** + * An object where column names as keys and custom objects as corresponding + * values for deserialization. It's specifically useful for data types like + * protobuf where deserialization logic is on user-specific code. When provided, + * the custom object enables deserialization of backend-received column data. + * If not provided, data remains serialized as buffer for Proto Messages and + * integer for Proto Enums. + * + * @example + * To obtain Proto Messages and Proto Enums as JSON objects, you must supply + * additional metadata. This metadata should include the protobufjs-cli + * generated proto message function and enum object. It encompasses the essential + * logic for proper data deserialization. + * + * Eg: To read data from Proto Columns in json format using DQL, you should pass + * columnsMetadata where key is the name of the column and value is the protobufjs-cli + * generated proto message function and enum object. + * + * const query = { + * sql: `SELECT SingerId, + * FirstName, + * LastName, + * SingerInfo, + * SingerGenre, + * SingerInfoArray, + * SingerGenreArray + * FROM Singers + * WHERE SingerId = 6`, + * columnsMetadata: { + * SingerInfo: music.SingerInfo, + * SingerInfoArray: music.SingerInfo, + * SingerGenre: music.Genre, + * SingerGenreArray: music.Genre, + * }, + * }; + */ + columnsMetadata?: object; + gaxOptions?: CallOptions; +} + +/** + * By default rows are an Array of values in the form of objects containing + * `name` and `value` properties. + * + * If you prefer plain objects, you can use the {@link Row#toJSON} method. + * NOTE: If you have duplicate field names only the last field will be present. + * + * @typedef {Array.<{name: string, value}>} Row + */ +export interface Row extends Array { + /** + * Converts the Row object into a pojo (plain old JavaScript object). + * + * @memberof Row + * @name toJSON + * + * @param {JSONOptions} [options] JSON options. + * @returns {object} + */ + toJSON(options?: JSONOptions): Json; +} + +/** + * @callback PartialResultStream~rowCallback + * @param {Row|object} row The row data. + */ +interface RowCallback { + (row: Row | Json): void; +} + +/** + * @callback PartialResultStream~statsCallback + * @param {object} stats The result stats. + */ +interface StatsCallback { + (stats: google.spanner.v1.ResultSetStats): void; +} + +/** + * @callback PartialResultStream~responseCallback + * @param {object} response The full API response. + */ +interface ResponseCallback { + (response: google.spanner.v1.PartialResultSet): void; +} + +interface ResultEvents { + addListener(event: 'data', listener: RowCallback): this; + addListener(event: 'stats', listener: StatsCallback): this; + addListener(event: 'response', listener: ResponseCallback): this; + + emit(event: 'data', data: Row | Json): boolean; + emit(event: 'stats', data: google.spanner.v1.ResultSetStats): boolean; + emit(event: 'response', data: google.spanner.v1.PartialResultSet): boolean; + + on(event: 'data', listener: RowCallback): this; + on(event: 'stats', listener: StatsCallback): this; + on(event: 'response', listener: ResponseCallback): this; + + once(event: 'data', listener: RowCallback): this; + once(event: 'stats', listener: StatsCallback): this; + once(event: 'response', listener: ResponseCallback): this; + + prependListener(event: 'data', listener: RowCallback): this; + prependListener(event: 'stats', listener: StatsCallback): this; + prependListener(event: 'response', listener: ResponseCallback): this; + + prependOnceListener(event: 'data', listener: RowCallback): this; + prependOnceListener(event: 'stats', listener: StatsCallback): this; + prependOnceListener(event: 'response', listener: ResponseCallback): this; +} + +/** + * The PartialResultStream transforms partial result set objects into Row + * objects. + * + * @class + * @extends {Transform} + * + * @param {RowOptions} [options] The row options. + */ +export class PartialResultStream extends Transform implements ResultEvents { + private _destroyed: boolean; + private _fields!: google.spanner.v1.StructType.Field[]; + private _options: RowOptions; + private _pendingValue?: p.IValue; + private _pendingValueForResume?: p.IValue; + private _values: p.IValue[]; + private _numPushFailed = 0; + constructor(options = {}) { + super({objectMode: true}); + + this._destroyed = false; + this._options = Object.assign({maxResumeRetries: 20}, options); + this._values = []; + } + /** + * Destroys the stream. + * + * @param {Error} [err] Optional error to destroy stream with. + */ + destroy(err?: Error): this { + if (this._destroyed) { + return this; + } + + this._destroyed = true; + + process.nextTick(() => { + if (err) { + this.emit('error', err); + } + this.emit('close'); + }); + return this; + } + /** + * Processes each chunk. + * + * @private + * + * @param {object} chunk The partial result set. + * @param {string} encoding Chunk encoding (Not used in object streams). + * @param {function} next Function to be called upon completion. + */ + _transform( + chunk: google.spanner.v1.PartialResultSet, + enc: string, + next: Function, + ): void { + this.emit('response', chunk); + + if (chunk.stats) { + this.emit('stats', chunk.stats); + } + + if (!this._fields && chunk.metadata) { + this._fields = chunk.metadata.rowType! + .fields as google.spanner.v1.StructType.Field[]; + } + + let res = true; + if (!isEmpty(chunk.values)) { + res = this._addChunk(chunk); + } + + if (chunk.last) { + this.push(null); + return; + } + + if (res) { + next(); + } else { + // Wait a little before we push any more data into the pipeline as a + // component downstream has indicated that a break is needed. Pause the + // request stream to prevent it from filling up the buffer while we are + // waiting. + // The stream will initially pause for 2ms, and then double the pause time + // for each new pause. + const initialPauseMs = 2; + setTimeout(() => { + this._tryResume(next, 2 * initialPauseMs); + }, initialPauseMs); + } + } + + private _tryResume(next: Function, timeout: number) { + // Try to push an empty chunk to check whether more data can be accepted. + if (this.push(undefined)) { + this._numPushFailed = 0; + this.emit('resumed'); + next(); + } else { + // Downstream returned false indicating that it is still not ready for + // more data. + this._numPushFailed++; + if (this._numPushFailed === this._options.maxResumeRetries) { + this.destroy( + new Error( + `Stream is still not ready to receive data after ${this._numPushFailed} attempts to resume.`, + ), + ); + return; + } + setTimeout(() => { + const nextTimeout = Math.min(timeout * 2, 1024); + this._tryResume(next, nextTimeout); + }, timeout); + } + } + + _resetPendingValues() { + if (this._pendingValueForResume) { + this._pendingValue = this._pendingValueForResume; + } else { + delete this._pendingValue; + } + } + + /** + * Manages any chunked values. + * + * @private + * + * @param {object} chunk The partial result set. + */ + private _addChunk(chunk: google.spanner.v1.PartialResultSet): boolean { + const values: Value[] = chunk.values.map(GrpcService.decodeValue_); + + // If we have a chunk to merge, merge the values now. + if (this._pendingValue) { + const currentField = this._values.length % this._fields.length; + const field = this._fields[currentField]; + const merged = PartialResultStream.merge( + field.type as google.spanner.v1.Type, + this._pendingValue, + values.shift(), + ); + + values.unshift(...merged); + delete this._pendingValue; + } + + // If the chunk is chunked, store the last value for merging with the next + // chunk to be processed. + if (chunk.chunkedValue) { + this._pendingValue = values.pop(); + if (_hasResumeToken(chunk)) { + this._pendingValueForResume = this._pendingValue; + } + } else if (_hasResumeToken(chunk)) { + delete this._pendingValueForResume; + } + + let res = true; + values.forEach(value => { + res = this._addValue(value) && res; + if (!res) { + this.emit('paused'); + } + }); + return res; + } + /** + * Manages complete values, pushing a completed row into the stream once all + * values have been received. + * + * @private + * + * @param {*} value The complete value. + */ + private _addValue(value: Value): boolean { + const values = this._values; + + values.push(value); + + if (values.length !== this._fields.length) { + return true; + } + + this._values = []; + + const row: Row = this._createRow(values); + + if (this._options.json) { + return this.push(row.toJSON(this._options.jsonOptions)); + } + + return this.push(row); + } + /** + * Converts an array of values into a row. + * + * @private + * + * @param {Array.<*>} values The row values. + * @returns {Row} + */ + private _createRow(values: Value[]): Row { + const fields = values.map((value, index) => { + const {name, type} = this._fields[index]; + const columnMetadata = this._options.columnsMetadata?.[name]; + return { + name, + value: codec.decode( + value, + type as google.spanner.v1.Type, + columnMetadata, + ), + }; + }); + + Object.defineProperty(fields, 'toJSON', { + value: (options?: JSONOptions): Json => { + return codec.convertFieldsToJson(fields, options); + }, + }); + + return fields as Row; + } + /** + * Attempts to merge chunked values together. + * + * @static + * @private + * + * @param {object} type The value type. + * @param {*} head The head of the combined value. + * @param {*} tail The tail of the combined value. + * @returns {Array.<*>} + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static merge( + type: google.spanner.v1.Type, + head: Value, + tail: Value, + ): Value[] { + if ( + type.code === google.spanner.v1.TypeCode.ARRAY || + type.code === 'ARRAY' || + type.code === google.spanner.v1.TypeCode.STRUCT || + type.code === 'STRUCT' + ) { + if (head === null || tail === null) { + return [head, tail]; + } + return [PartialResultStream.mergeLists(type, head, tail)]; + } + + if (isString(head) && isString(tail)) { + return [head + tail]; + } + + return [head, tail]; + } + /** + * Attempts to merge chunked lists together. + * + * @static + * @private + * + * @param {object} type The list type. + * @param {Array.<*>} head The beginning of the list. + * @param {Array.<*>} tail The end of the list. + * @returns {Array.<*>} + */ + static mergeLists( + type: google.spanner.v1.Type, + head: Value[], + tail: Value[], + ): Value[] { + let listType: google.spanner.v1.Type; + + if ( + type.code === 'ARRAY' || + type.code === google.spanner.v1.TypeCode.ARRAY + ) { + listType = type.arrayElementType as google.spanner.v1.Type; + } else { + listType = type.structType!.fields![head.length - 1] + .type as google.spanner.v1.Type; + } + + const merged = PartialResultStream.merge( + listType, + head.pop(), + tail.shift(), + ); + + return [...head, ...merged, ...tail]; + } +} + +/** + * Rows returned from queries may be chunked, requiring them to be stitched + * together. This function returns a stream that will properly assemble these + * rows, as well as retry after an error. Rows are only emitted if they hit a + * "checkpoint", which is when a `resumeToken` is returned from the API. Without + * that token, it's unsafe for the query to be retried, as we wouldn't want to + * emit the same data multiple times. + * + * @private + * + * @param {RequestFunction} requestFn The function that makes an API request. It + * will receive one argument, `resumeToken`, which should be used however is + * necessary to send to the API for additional requests. + * @param {RowOptions} [options] Options for formatting rows. + * @returns {PartialResultStream} + */ +export function partialResultStream( + requestFn: RequestFunction, + options?: RowOptions, +): PartialResultStream { + const retryableCodes = [grpc.status.UNAVAILABLE]; + const maxQueued = 10; + let lastResumeToken: ResumeToken; + let lastRequestStream: Readable; + const startTime = Date.now(); + const timeout = options?.gaxOptions?.timeout ?? Infinity; + + // mergeStream allows multiple streams to be connected into one. This is good; + // if we need to retry a request and pipe more data to the user's stream. + // We also add an additional stream that can be used to flush any remaining + // items in the checkpoint stream that have been received, and that did not + // contain a resume token. + const requestsStream = mergeStream(); + const flushStream = new stream.PassThrough({objectMode: true}); + requestsStream.add(flushStream); + const partialRSStream = new PartialResultStream(options); + const userStream = streamEvents(partialRSStream); + // We keep track of the number of PartialResultSets that did not include a + // resume token, as that is an indication whether it is safe to retry the + // stream halfway. + let withoutCheckpointCount = 0; + const batchAndSplitOnTokenStream = checkpointStream.obj({ + maxQueued, + isCheckpointFn: (chunk: google.spanner.v1.PartialResultSet): boolean => { + const withCheckpoint = _hasResumeToken(chunk); + if (withCheckpoint) { + withoutCheckpointCount = 0; + } else { + withoutCheckpointCount++; + } + return withCheckpoint; + }, + }); + + // This listener ensures that the last request that executed successfully + // after one or more retries will end the requestsStream. + const endListener = () => { + setImmediate(() => { + // Push a fake PartialResultSet without any values but with a resume token + // into the stream to ensure that the checkpoint stream is emptied, and + // then push `null` to end the stream. + flushStream.push({resumeToken: '_'}); + flushStream.push(null); + requestsStream.end(); + }); + }; + const makeRequest = (): void => { + if (isDefined(lastResumeToken) && lastResumeToken.length > 0) { + partialRSStream._resetPendingValues(); + } + lastRequestStream = requestFn(lastResumeToken); + lastRequestStream.on('end', endListener); + requestsStream.add(lastRequestStream); + }; + + const retry = (err: grpc.ServiceError): void => { + const elapsed = Date.now() - startTime; + if (elapsed >= timeout) { + // The timeout has reached so this will flush any rows the + // checkpoint stream has queued. After that, we will destroy the + // user's stream with the Deadline exceeded error. + setImmediate(() => + batchAndSplitOnTokenStream.destroy(new DeadlineError(err)), + ); + return; + } + + if ( + !( + err.code && + (retryableCodes!.includes(err.code) || isRetryableInternalError(err)) + ) || + // If we have received too many chunks without a resume token, it is not + // safe to retry. + withoutCheckpointCount > maxQueued + ) { + // This is not a retryable error so this will flush any rows the + // checkpoint stream has queued. After that, we will destroy the + // user's stream with the same error. + setImmediate(() => batchAndSplitOnTokenStream.destroy(err)); + return; + } + + if (lastRequestStream) { + lastRequestStream.removeListener('end', endListener); + lastRequestStream.destroy(); + } + // Delay the retry until all the values that are already in the stream + // pipeline have been handled. This ensures that the checkpoint stream is + // reset to the correct point. Calling .reset() directly here could cause + // any values that are currently in the pipeline and that have not been + // handled yet, to be pushed twice into the entire stream. + setImmediate(() => { + // Empty queued rows on the checkpoint stream (will not emit them to user). + batchAndSplitOnTokenStream.reset(); + makeRequest(); + }); + }; + + userStream.once('reading', makeRequest); + eventsIntercept.patch(requestsStream); + + // need types for events-intercept + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (requestsStream as any).intercept('error', err => + // Retry __after__ all pending data has been processed to ensure that the + // checkpoint stream is reset at the correct position. + setImmediate(() => retry(err)), + ); + + return ( + requestsStream + .pipe(batchAndSplitOnTokenStream) + // If we get this error, the checkpoint stream has flushed any rows + // it had queued. We can now destroy the user's stream, as our retry + // attempts are over. + .on('error', (err: Error) => userStream.destroy(err)) + .on('checkpoint', (row: google.spanner.v1.PartialResultSet) => { + lastResumeToken = row.resumeToken; + }) + .pipe(userStream) + .on('paused', () => requestsStream.pause()) + .on('resumed', () => requestsStream.resume()) + ); +} + +function _hasResumeToken(chunk: google.spanner.v1.PartialResultSet): boolean { + return isDefined(chunk.resumeToken) && chunk.resumeToken.length > 0; +} diff --git a/handwritten/spanner/src/request_id_header.ts b/handwritten/spanner/src/request_id_header.ts new file mode 100644 index 00000000000..99c081de64c --- /dev/null +++ b/handwritten/spanner/src/request_id_header.ts @@ -0,0 +1,223 @@ +/** + * Copyright 2025 Google LLC. All Rights Reserved. + * + * 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 {randomBytes} from 'crypto'; +// eslint-disable-next-line n/no-extraneous-import +import * as grpc from '@grpc/grpc-js'; +import {getActiveOrNoopSpan} from './instrument'; +const randIdForProcess = randomBytes(8) + .readUint32LE(0) + .toString(16) + .padStart(8, '0'); +const X_GOOG_SPANNER_REQUEST_ID_HEADER = 'x-goog-spanner-request-id'; + +class AtomicCounter { + private readonly backingBuffer: Uint32Array; + + constructor(initialValue?: number) { + this.backingBuffer = new Uint32Array( + new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT), + ); + if (initialValue) { + this.increment(initialValue); + } + } + + public increment(n?: number): number { + if (!n) { + n = 1; + } + Atomics.add(this.backingBuffer, 0, n); + return this.value(); + } + + public value(): number { + return Atomics.load(this.backingBuffer, 0); + } + + public toString(): string { + return `${this.value()}`; + } + + public reset() { + Atomics.store(this.backingBuffer, 0, 0); + } +} + +const REQUEST_HEADER_VERSION = 1; + +function craftRequestId( + nthClientId: number, + channelId: number, + nthRequest: number, + attempt: number, +) { + return `${REQUEST_HEADER_VERSION}.${randIdForProcess}.${nthClientId}.${channelId}.${nthRequest}.${attempt}`; +} + +const nthClientId = new AtomicCounter(); + +// Only exported for deterministic testing. +export function resetNthClientId() { + nthClientId.reset(); +} + +/* + * nextSpannerClientId increments the internal + * counter for created SpannerClients, for use + * with x-goog-spanner-request-id. + */ +function nextSpannerClientId(): number { + nthClientId.increment(1); + return nthClientId.value(); +} + +function newAtomicCounter(n?: number): AtomicCounter { + return new AtomicCounter(n); +} + +interface withHeaders { + headers: {[k: string]: string}; +} + +function extractRequestID(config: any): string { + if (!config) { + return ''; + } + + const hdrs = config as withHeaders; + if (hdrs && hdrs.headers) { + return hdrs.headers[X_GOOG_SPANNER_REQUEST_ID_HEADER]; + } + return ''; +} + +function injectRequestIDIntoError(config: any, err: Error) { + if (!err) { + return; + } + + // Inject that RequestID into the actual + // error object regardless of the type. + const requestID = extractRequestID(config); + if (requestID) { + Object.assign(err, {requestID: requestID}); + } +} + +interface withNextNthRequest { + _nextNthRequest: Function; +} + +interface withMetadataWithRequestId { + _nthClientId: number; + _channelId: number; +} + +function injectRequestIDIntoHeaders( + headers: {[k: string]: string}, + session: any, + nthRequest?: number, + attempt?: number, +) { + if (!session) { + return headers; + } + + if (!nthRequest) { + const database = session.parent as withNextNthRequest; + if (!(database && typeof database._nextNthRequest === 'function')) { + return headers; + } + nthRequest = database._nextNthRequest(); + } + + attempt = attempt || 1; + return _metadataWithRequestId(session, nthRequest!, attempt, headers); +} + +function _metadataWithRequestId( + session: any, + nthRequest: number, + attempt: number, + priorMetadata?: {[k: string]: string}, +): {[k: string]: string} { + if (!priorMetadata) { + priorMetadata = {}; + } + const withReqId = { + ...priorMetadata, + }; + const database = session.parent as withMetadataWithRequestId; + let clientId = 1; + let channelId = 1; + if (database) { + clientId = database._nthClientId || 1; + channelId = database._channelId || 1; + } + withReqId[X_GOOG_SPANNER_REQUEST_ID_HEADER] = craftRequestId( + clientId, + channelId, + nthRequest, + attempt, + ); + return withReqId; +} + +function nextNthRequest(database): number { + if (!(database && typeof database._nextNthRequest === 'function')) { + return 1; + } + return database._nextNthRequest(); +} + +export interface RequestIDError extends grpc.ServiceError { + requestID: string; +} + +const X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR = 'x_goog_spanner_request_id'; + +/* + * attributeXGoogSpannerRequestIdToActiveSpan extracts the x-goog-spanner-request-id + * from config, if possible and then adds it as an attribute to the current/active span. + * Since x-goog-spanner-request-id is associated with RPC invoking methods, it is invoked + * long after tracing has been performed. + */ +function attributeXGoogSpannerRequestIdToActiveSpan(config: any) { + const reqId = extractRequestID(config); + if (!(reqId && reqId.length > 0)) { + return; + } + const span = getActiveOrNoopSpan(); + span.setAttribute(X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR, reqId); +} + +const X_GOOG_REQ_ID_REGEX = /^1\.[0-9A-Fa-f]{8}(\.\d+){3}\.\d+/; + +export { + AtomicCounter, + X_GOOG_REQ_ID_REGEX, + X_GOOG_SPANNER_REQUEST_ID_HEADER, + X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR, + attributeXGoogSpannerRequestIdToActiveSpan, + craftRequestId, + injectRequestIDIntoError, + injectRequestIDIntoHeaders, + nextNthRequest, + nextSpannerClientId, + newAtomicCounter, + randIdForProcess, +}; diff --git a/handwritten/spanner/src/session-factory.ts b/handwritten/spanner/src/session-factory.ts new file mode 100644 index 00000000000..957da022e92 --- /dev/null +++ b/handwritten/spanner/src/session-factory.ts @@ -0,0 +1,274 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 {Database, Session, Transaction} from '.'; +import { + MultiplexedSession, + MultiplexedSessionInterface, +} from './multiplexed-session'; +import { + SessionPool, + SessionPoolInterface, + SessionPoolOptions, +} from './session-pool'; +import {SessionPoolConstructor} from './database'; +import {ServiceObjectConfig} from '@google-cloud/common'; +const common = require('./common-grpc/service-object'); + +/** + * @callback GetSessionCallback + * @param {?Error} error Request error, if any. + * @param {Session} session The read-write session. + * @param {Transaction} transaction The transaction object. + */ +export interface GetSessionCallback { + ( + err: Error | null, + session?: Session | null, + transaction?: Transaction | null, + ): void; +} + +/** + * Interface for implementing session-factory logic. + * + * @interface SessionFactoryInterface + */ +export interface SessionFactoryInterface { + /** + * When called returns a session. + * + * @name SessionFactoryInterface#getSession + * @param {GetSessionCallback} callback The callback function. + */ + getSession(callback: GetSessionCallback): void; + + /** + * When called returns a session for paritioned dml. + * + * @name SessionFactoryInterface#getSessionForPartitionedOps + * @param {GetSessionCallback} callback The callback function. + */ + getSessionForPartitionedOps(callback: GetSessionCallback): void; + + /** + * When called returns a session for read write. + * + * @name SessionFactoryInterface#getSessionForReadWrite + * @param {GetSessionCallback} callback The callback function. + */ + getSessionForReadWrite(callback: GetSessionCallback): void; + + /** + * When called returns the pool object. + * + * @name SessionFactoryInterface#getPool + */ + getPool(): SessionPoolInterface; + + /** + * To be called when releasing a session. + * + * @name SessionFactoryInterface#release + * @param {Session} session The session to be released. + */ + release(session: Session): void; + + /** + * When called returns if the multiplexed is enabled or not. + * + * @name SessionFactoryInterface#isMultiplexedEnabled + */ + isMultiplexedEnabled(): boolean; + + /** + * When called returns if the multiplexed is enabled or not for read write transactions. + * + * @name SessionFactoryInterface#isMultiplexedEnabledForRW + */ + isMultiplexedEnabledForRW(): boolean; +} + +/** + * Creates a SessionFactory object to manage the creation of + * session-pool and multiplexed session. + * + * @class + * + * @param {Database} database Database object. + * @param {String} name Name of the database. + * @param {SessionPoolOptions|SessionPoolInterface} options Session pool + * configuration options or custom pool inteface. + */ +export class SessionFactory + extends common.GrpcServiceObject + implements SessionFactoryInterface +{ + multiplexedSession_: MultiplexedSessionInterface; + pool_: SessionPoolInterface; + isMultiplexed: boolean; + isMultiplexedPartitionOps: boolean; + isMultiplexedRW: boolean; + constructor( + database: Database, + name: String, + poolOptions?: SessionPoolConstructor | SessionPoolOptions, + ) { + super({ + parent: database, + id: name, + } as {} as ServiceObjectConfig); + // initialize regular pool + this.pool_ = + typeof poolOptions === 'function' + ? new (poolOptions as SessionPoolConstructor)(database, null) + : new SessionPool(database, poolOptions); + + // initialize multiplexed session + this.multiplexedSession_ = new MultiplexedSession(database); + this.multiplexedSession_.createSession(); + + // set the isMultiplexed property to false if multiplexed session is disabled, otherwise set the property to true + this.isMultiplexed = !( + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS === 'false' + ); + + // set the isMultiplexedPartitionedOps property to false if multiplexed session is disabled for paritioned ops, otherwise set the property to true + this.isMultiplexedPartitionOps = !( + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS === 'false' && + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS === + 'false' + ); + + // set the isMultiplexedRW property to false if multiplexed session is disabled for read/write, otherwise set the property to true + this.isMultiplexedRW = !( + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS === 'false' && + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW === 'false' + ); + + // Regular sessions should only be created if mux is disabled. + if (!this.isMultiplexed) { + this.pool_.on('error', this.emit.bind(database, 'error')); + this.pool_.open(); + } + } + + /** + * Retrieves a session, either a regular session or a multiplexed session, based on the environment variable configuration. + * + * If the environment variable `GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS` is set to `false`, the method will attempt to + * retrieve a regular session. Otherwise, it will return a multiplexed session. + * + * @param {GetSessionCallback} callback The callback function. + */ + + getSession(callback: GetSessionCallback): void { + const sessionHandler = this.isMultiplexed + ? this.multiplexedSession_ + : this.pool_; + + sessionHandler!.getSession((err, session, transaction) => + callback(err, session, transaction), + ); + } + + /** + * Retrieves a session for partitioned operations, selecting the appropriate session type + * based on whether multiplexed sessions are disabled or not. + * + * If multiplexed sessions are disabled for partitioned ops this methods delegates the request to `getSession()`, which returns + * either a multiplexed session or a regular session based on the env configuration. + * + * If the multiplexed sessions are disabled, a session will get retrieved from the regular session pool. + * Otherwise a multiplexed session will be used. + * + * @param {GetSessionCallback} callback The callback function. + */ + getSessionForPartitionedOps(callback: GetSessionCallback): void { + this.isMultiplexedPartitionOps + ? this.getSession(callback) + : this.pool_.getSession(callback); + } + + /** + * Retrieves a session for read write operations, selecting the appropriate session type + * based on whether multiplexed sessions are enabled. + * + * If multiplexed sessions are disabled for read write this methods delegates the request to `getSession()`, which returns + * either a multiplexed session or a regular session based on the env configuration. + * + * If the multiplexed sessions are disabled, a session will get retrieved from the regular session pool. + * Otherise a multiplexed session will be used. + * + * @param {GetSessionCallback} callback The callback function. + */ + getSessionForReadWrite(callback: GetSessionCallback): void { + this.isMultiplexedRW + ? this.getSession(callback) + : this.pool_.getSession(callback); + } + + /** + * Returns the regular session pool object. + * + * @returns {SessionPoolInterface} The session pool used by current instance. + */ + + getPool(): SessionPoolInterface { + return this.pool_; + } + + /** + * Releases a regular session back to the session pool. + * + * This methods does not release a multiplexed session. + * + * It returns a session to the pool after it is no longer needed. + * It is a no-op for multiplexed sessions. + * + * @param {Session} session - The session to be released. This should be an instance of `Session` that was + * previously acquired from the session pool. + * + * @throws {Error} If the session is invalid or cannot be released. + */ + release(session: Session): void { + if (!session.metadata?.multiplexed) { + this.pool_.release(session); + } + } + + /** + * Returns if a multiplexed is enabled or not. + * + * This method returns true if multiplexed session is enabled, otherwise returns false + * + * @returns {boolean} + */ + isMultiplexedEnabled(): boolean { + return this.isMultiplexed; + } + + /** + * Returns if a multiplexed is enabled or not for read write transaction. + * + * This method returns true if multiplexed session is enabled for read write transactions, otherwise returns false + * + * @returns {boolean} + */ + isMultiplexedEnabledForRW(): boolean { + return this.isMultiplexedRW; + } +} diff --git a/handwritten/spanner/src/session-pool.ts b/handwritten/spanner/src/session-pool.ts new file mode 100644 index 00000000000..3c80e5bdceb --- /dev/null +++ b/handwritten/spanner/src/session-pool.ts @@ -0,0 +1,1084 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 {EventEmitter} from 'events'; +import PQueue from 'p-queue'; + +import {Database} from './database'; +import {Session} from './session'; +import {Transaction} from './transaction'; +import {NormalCallback} from './common'; +import {GoogleError, grpc, ServiceError} from 'google-gax'; +import trace = require('stack-trace'); +import { + ObservabilityOptions, + getActiveOrNoopSpan, + setSpanErrorAndException, + startTrace, +} from './instrument'; +import {GetSessionCallback} from './session-factory'; +import { + isDatabaseNotFoundError, + isInstanceNotFoundError, + isDefaultCredentialsNotSetError, + isProjectIdNotSetInEnvironmentError, + isCreateSessionPermissionError, + isInfinite, +} from './helper'; + +/** + * @callback SessionPoolCloseCallback + * @param {?Error} error Closing error, if any. + */ +export interface SessionPoolCloseCallback { + (error?: SessionLeakError): void; +} + +/** @deprecated. Use GetSessionCallback instead. */ +export type GetReadSessionCallback = NormalCallback; + +/** @deprecated. Use GetSessionCallback instead. */ +export interface GetWriteSessionCallback { + ( + err: Error | null, + session?: Session | null, + transaction?: Transaction | null, + ): void; +} + +/** + * Interface for implementing custom session pooling logic, it should extend the + * {@link https://nodejs.org/api/events.html|EventEmitter} class and emit any + * asynchronous errors via an error event. + * + * @interface SessionPoolInterface + * @extends external:{@link https://nodejs.org/api/events.html|EventEmitter} + */ +/** + * @constructs SessionPoolInterface + * @param {Database} database The database to create a pool for. + */ +export interface SessionPoolInterface extends EventEmitter { + /** + * Will be called via {@link Database#close}. Indicates that the pool should + * perform any necessary teardown actions to its resources. + * + * @name SessionPoolInterface#close + * @param {SessionPoolCloseCallback} callback The callback function. + */ + /** + * Will be called by the Database object, should be used to start creating + * sessions/etc. + * + * @name SessionPoolInterface#open + */ + /** + * When called returns a session. + * + * @name SessionPoolInterface#getSession + * @param {GetSessionCallback} callback The callback function. + */ + /** + * When called returns a session. + * + * @deprecated Use getSession instead. + * @name SessionPoolInterface#getReadSession + * @param {GetReadSessionCallback} callback The callback function. + */ + /** + * When called returns a session. + * + * @deprecated Use getSession instead. + * @name SessionPoolInterface#getWriteSession + * @param {GetWriteSessionCallback} callback The callback function. + */ + /** + * To be called when releasing a session back into the pool. + * + * @name SessionPoolInterface#release + * @param {Session} session The session to be released. + */ + close(callback: SessionPoolCloseCallback): void; + open(): void; + getSession(callback: GetSessionCallback): void; + getReadSession(callback: GetReadSessionCallback): void; + getWriteSession(callback: GetWriteSessionCallback): void; + release(session: Session): void; +} + +/** + * Session pool configuration options. + * + * @typedef {object} SessionPoolOptions + * @property {number} [acquireTimeout=Infinity] Time in milliseconds before + * giving up trying to acquire a session. If the specified value is + * `Infinity`, a timeout will not occur. + * @property {number} [concurrency=Infinity] How many concurrent requests the pool is + * allowed to make. + * @property {boolean} [fail=false] If set to true, an error will be thrown when + * there are no available sessions for a request. + * @property {number} [idlesAfter=10] How long until a resource becomes idle, in + * minutes. + * @property {number} [keepAlive=30] How often to ping idle sessions, in + * minutes. Must be less than 1 hour. + * @property {Object} [labels] Labels to apply to any session + * created by the pool. + * @property {number} [max=100] Maximum number of resources to create at any + * given time. + * @property {number} [maxIdle=1] Maximum number of idle resources to keep in + * the pool at any given time. + * @property {number} [min=25] Minimum number of resources to keep in the pool at + * any given time. + * @property {number} [writes=0.0]. Deprecated. + * @property {number} [incStep=25] The number of new sessions to create when at + * least one more session is needed. + */ +export interface SessionPoolOptions { + acquireTimeout?: number; + concurrency?: number; + fail?: boolean; + idlesAfter?: number; + keepAlive?: number; + /** + * @deprecated Use SpannerOptions.sessionLabels instead. + */ + labels?: {[label: string]: string}; + max?: number; + maxIdle?: number; + min?: number; + /** + * @deprecated. Starting from v6.5.0 the same session can be reused for + * different types of transactions. + */ + writes?: number; + incStep?: number; + /** + * @deprecated Use Database constructor to pass databaseRole. + */ + databaseRole?: string | null; +} + +const DEFAULTS: SessionPoolOptions = { + acquireTimeout: Infinity, + concurrency: Infinity, + fail: false, + idlesAfter: 10, + keepAlive: 30, + max: 100, + maxIdle: 1, + min: 25, + incStep: 25, +}; + +/** + * Error to be thrown when attempting to release unknown resources. + * + * @private + */ +export class ReleaseError extends GoogleError { + resource: unknown; + constructor(resource: unknown) { + super('Unable to release unknown resource.'); + this.resource = resource; + } +} + +/** + * Error to be thrown when session leaks are detected. + * + * @private + */ +export class SessionLeakError extends GoogleError { + messages: string[]; + constructor(leaks: string[]) { + super(`${leaks.length} session leak(s) detected.`); + // Restore error name that was overwritten by the super constructor call. + this.name = SessionLeakError.name; + this.messages = leaks; + } +} + +/** + * Error to be thrown when the session pool is exhausted. + */ +export class SessionPoolExhaustedError extends GoogleError { + messages: string[]; + constructor(leaks: string[]) { + super(errors.Exhausted); + // Restore error name that was overwritten by the super constructor call. + this.name = SessionPoolExhaustedError.name; + this.messages = leaks; + } +} + +/** + * Checks whether the given error is a 'Session not found' error. + * @param error the error to check + * @return true if the error is a 'Session not found' error, and otherwise false. + */ +export function isSessionNotFoundError( + error: grpc.ServiceError | undefined, +): boolean { + return ( + error !== undefined && + error.code === grpc.status.NOT_FOUND && + error.message.includes('Session not found') + ); +} + +/** + * enum to capture errors that can appear from multiple places + */ +const enum errors { + Closed = 'Database is closed.', + Timeout = 'Timeout occurred while acquiring session.', + Exhausted = 'No resources available.', +} + +interface SessionInventory { + sessions: Session[]; + borrowed: Set; +} + +/** @deprecated. */ +export interface CreateSessionsOptions { + writes?: number; + reads?: number; +} + +/** + * Class used to manage connections to Spanner. + * + * **You don't need to use this class directly, connections will be handled for + * you.** + * + * @class + * @extends {EventEmitter} + */ +export class SessionPool extends EventEmitter implements SessionPoolInterface { + database: Database; + isOpen: boolean; + options: SessionPoolOptions; + _acquires: PQueue; + _evictHandle!: NodeJS.Timer; + _inventory: SessionInventory; + _onClose!: Promise; + _pending = 0; + _waiters = 0; + _pingHandle!: NodeJS.Timer; + _requests: PQueue; + _traces: Map; + _observabilityOptions?: ObservabilityOptions; + + /** + * Formats stack trace objects into Node-like stack trace. + * + * @param {object[]} trace The trace object. + * @return {string} + */ + static formatTrace(frames: trace.StackFrame[]): string { + const stack = frames.map(frame => { + const name = frame.getFunctionName() || frame.getMethodName(); + const file = frame.getFileName(); + const lineno = frame.getLineNumber(); + const columnno = frame.getColumnNumber(); + + return ` at ${name} (${file}:${lineno}:${columnno})`; + }); + + return `Session leak detected!\n${stack.join('\n')}`; + } + + /** + * Total number of available sessions. + * @type {number} + */ + get available(): number { + return this._inventory.sessions.length; + } + /** @deprecated Starting from v6.5.0 the same session can be reused for + * different types of transactions. + */ + get currentWriteFraction(): number { + return 0; + } + + /** + * Total number of borrowed sessions. + * @type {number} + */ + get borrowed(): number { + return this._inventory.borrowed.size + this._pending; + } + + /** + * Flag to determine if Pool is full. + * @type {boolean} + */ + get isFull(): boolean { + return this.size >= this.options.max!; + } + + /** @deprecated Use `size()` instead. */ + get reads(): number { + return this.size; + } + + /** + * Total size of pool. + * @type {number} + */ + get size(): number { + return this.available + this.borrowed; + } + + /** @deprecated Use `size()` instead. */ + get writes(): number { + return this.size; + } + + /** @deprecated Starting v6.5.0 the pending prepare state is obsolete. */ + get pendingPrepare(): number { + return 0; + } + + /** + * Number of sessions being created or prepared for a read/write transaction. + * @type {number} + */ + get totalPending(): number { + return this._pending; + } + + /** @deprecated Use totalWaiters instead. */ + get numReadWaiters(): number { + return this.totalWaiters; + } + + /** @deprecated Use totalWaiters instead. */ + get numWriteWaiters(): number { + return this.totalWaiters; + } + + /** + * Sum of read and write waiters. + * @type {number} + */ + get totalWaiters(): number { + return this._waiters; + } + + /** + * @constructor + * @param {Database} database The DB instance. + * @param {SessionPoolOptions} [options] Configuration options. + */ + constructor(database: Database, options?: SessionPoolOptions) { + super(); + + if (options && options.min && options.max && options.min > options.max) { + throw new TypeError('Min sessions may not be greater than max sessions.'); + } + this.isOpen = false; + this.database = database; + this.options = Object.assign({}, DEFAULTS, options); + this.options.min = Math.min(this.options.min!, this.options.max!); + this.options.databaseRole = this.options.databaseRole + ? this.options.databaseRole + : database.databaseRole; + + this._inventory = { + sessions: [], + borrowed: new Set(), + }; + this._waiters = 0; + this._requests = new PQueue({ + concurrency: this.options.concurrency!, + }); + + this._acquires = new PQueue({ + concurrency: 1, + }); + + this._traces = new Map(); + this._observabilityOptions = database._observabilityOptions; + } + + /** + * Closes and the pool. + * + * @emits SessionPool#close + * @param {SessionPoolCloseCallback} callback The callback function. + */ + close(callback: SessionPoolCloseCallback): void { + const sessions: Session[] = [ + ...this._inventory.sessions, + ...this._inventory.borrowed, + ]; + + this.isOpen = false; + + this._stopHouseKeeping(); + this.emit('close'); + + sessions.forEach(session => this._destroy(session)); + + this._requests + .onIdle() + .then(() => { + const leaks = this._getLeaks(); + let error; + + this._inventory.sessions = []; + this._inventory.borrowed.clear(); + + if (leaks.length) { + error = new SessionLeakError(leaks); + } + + callback(error); + }) + .catch(err => callback(err)); + } + + /** + * Retrieve a read session. + * + * @deprecated Use getSession instead. + * @param {GetReadSessionCallback} callback The callback function. + */ + getReadSession(callback: GetReadSessionCallback): void { + this.getSession((error, session) => + callback(error as ServiceError, session), + ); + } + + /** + * Retrieve a read/write session. + * + * @deprecated use getSession instead. + * @param {GetWriteSessionCallback} callback The callback function. + */ + getWriteSession(callback: GetWriteSessionCallback): void { + this.getSession(callback); + } + + /** + * Retrieve a session. + * + * @param {GetSessionCallback} callback The callback function. + */ + getSession(callback: GetSessionCallback): void { + this._acquire().then( + session => callback(null, session, session.txn!), + callback, + ); + } + + /** + * Opens the pool, filling it to the configured number of read and write + * sessions. + * + * @emits SessionPool#open + * @return {Promise} + */ + open(): void { + this._onClose = new Promise(resolve => this.once('close', resolve)); + this._startHouseKeeping(); + + this.isOpen = true; + this.emit('open'); + + this._fill().catch(err => { + // Ignore `Database not found` error. This allows a user to call instance.database('db-name') + // for a database that does not yet exist with SessionPoolOptions.min > 0. + if ( + isDatabaseNotFoundError(err) || + isInstanceNotFoundError(err) || + isCreateSessionPermissionError(err) || + isDefaultCredentialsNotSetError(err) || + isProjectIdNotSetInEnvironmentError(err) + ) { + return; + } + this.emit('error', err); + }); + } + + /** + * Releases session back into the pool. + * + * @throws {Error} For unknown sessions. + * @emits SessionPool#available + * @emits SessionPool#error + * @fires SessionPool#session-available + * @fires @deprecated SessionPool#readonly-available + * @fires @deprecated SessionPool#readwrite-available + * @param {Session} session The session to release. + */ + release(session: Session): void { + if (!this._inventory.borrowed.has(session)) { + throw new ReleaseError(session); + } + + delete session.txn; + session.lastUsed = Date.now(); + + if (isSessionNotFoundError(session.lastError)) { + // Remove the session from the pool. It is not necessary to call _destroy, + // as the session is already removed from the backend. + this._inventory.borrowed.delete(session); + this._traces.delete(session.id); + return; + } + session.lastError = undefined; + + // Delete the trace associated with this session to mark the session as checked + // back into the pool. This will prevent the session to be marked as leaked if + // the pool is closed while the session is being prepared. + this._traces.delete(session.id); + // Release it into the pool as a session if there are more waiters than + // there are sessions available. Releasing it will unblock a waiter as soon + // as possible. + this._release(session); + } + + /** + * Attempts to borrow a session from the pool. + * + * @private + * + * @returns {Promise} + */ + async _acquire(): Promise { + const span = getActiveOrNoopSpan(); + if (!this.isOpen) { + span.addEvent('SessionPool is closed'); + throw new GoogleError(errors.Closed); + } + + // Get the stacktrace of the caller before we call any async methods, as calling an async method will break the stacktrace. + const frames = trace.get(); + const startTime = Date.now(); + const timeout = this.options.acquireTimeout; + + // wrapping this logic in a function to call recursively if the session + // we end up with is already dead + const getSession = async (): Promise => { + span.addEvent('Acquiring session'); + const elapsed = Date.now() - startTime; + + if (elapsed >= timeout!) { + span.addEvent('Could not acquire session due to an exceeded timeout'); + throw new GoogleError(errors.Timeout); + } + + const session = await this._getSession(startTime); + + if (this._isValidSession(session)) { + span.addEvent('Acquired session', { + 'time.elapsed': Date.now() - startTime, + 'session.id': session.id.toString(), + }); + return session; + } + + span.addEvent( + 'Could not acquire session because it was invalid. Retrying', + { + 'session.id': session.id.toString(), + }, + ); + this._inventory.borrowed.delete(session); + return getSession(); + }; + + const session = await this._acquires.add(getSession); + this._prepareTransaction(session); + this._traces.set(session.id, frames); + return session; + } + + /** + * Moves a session into the borrowed group. + * + * @private + * + * @param {Session} session The session object. + */ + _borrow(session: Session): void { + const index = this._inventory.sessions.indexOf(session); + + this._inventory.borrowed.add(session); + this._inventory.sessions.splice(index, 1); + } + + /** + * Borrows the first session from the inventory. + * + * @private + * + * @return {Session} + */ + _borrowFrom(): Session { + const session = this._inventory.sessions.pop()!; + this._inventory.borrowed.add(session); + return session; + } + + /** + * Grabs the next available session. + * + * @private + * + * @returns {Promise} + */ + _borrowNextAvailableSession(): Session { + return this._borrowFrom(); + } + + /** + * Attempts to create a single session. + * + * @private + * + * @returns {Promise} + */ + _createSession(): Promise { + return this._createSessions(1); + } + + /** + * Batch creates sessions. + * + * @private + * + * @param {number} [amount] Config specifying how many sessions to create. + * @returns {Promise} + * @emits SessionPool#createError + */ + async _createSessions(amount: number): Promise { + const labels = this.options.labels; + const databaseRole = this.options.databaseRole; + + if (amount <= 0) { + return; + } + this._pending += amount; + + let nReturned = 0; + const nRequested: number = amount; + + // TODO: Inlining this code for now and later on shall go + // extract _traceConfig to the constructor when we have plenty of time. + const traceConfig = { + opts: this._observabilityOptions, + dbName: this.database.formattedName_, + }; + return startTrace('SessionPool.createSessions', traceConfig, async span => { + span.addEvent(`Requesting ${amount} sessions`); + + // while we can request as many sessions be created as we want, the backend + // will return at most 100 at a time, hence the need for a while loop. + while (amount > 0) { + let sessions: Session[] | null = null; + + span.addEvent(`Creating ${amount} sessions`); + + try { + [sessions] = await this.database.batchCreateSessions({ + count: amount, + labels: labels, + databaseRole: databaseRole, + }); + + amount -= sessions.length; + nReturned += sessions.length; + } catch (e) { + this._pending -= amount; + this.emit('createError', e); + span.addEvent( + `Requested for ${nRequested} sessions returned ${nReturned}`, + ); + setSpanErrorAndException(span, e as Error); + span.end(); + throw e; + } + + sessions.forEach((session: Session) => { + setImmediate(() => { + this._inventory.borrowed.add(session); + this._pending -= 1; + this.release(session); + }); + }); + } + + span.addEvent( + `Requested for ${nRequested} sessions returned ${nReturned}`, + ); + span.end(); + }); + } + + /** + * Attempts to delete a session, optionally creating a new one of the same + * type if the pool is still open and we're under the configured min value. + * + * @private + * + * @fires SessionPool#error + * @param {Session} session The session to delete. + * @returns {Promise} + */ + async _destroy(session: Session): Promise { + try { + await this._requests.add(() => session.delete()); + } catch (e) { + this.emit('error', e); + } + } + + /** + * Deletes idle sessions that exceed the maxIdle configuration. + * + * @private + */ + _evictIdleSessions(): void { + const {maxIdle, min} = this.options; + const size = this.size; + const idle = this._getIdleSessions(); + + let count = idle.length; + let evicted = 0; + + while (count-- > maxIdle! && size - evicted++ > min!) { + const session = idle.pop(); + + if (!session) { + continue; + } + + const index = this._inventory.sessions.indexOf(session); + + this._inventory.sessions.splice(index, 1); + void this._destroy(session); + } + } + + /** + * Fills the pool with the minimum number of sessions. + * + * @return {Promise} + */ + async _fill(): Promise { + const needed = this.options.min! - this.size; + if (needed <= 0) { + return; + } + + await this._createSessions(needed); + } + + /** + * Retrieves a list of all the idle sessions. + * + * @private + * + * @returns {Session[]} + */ + _getIdleSessions(): Session[] { + const idlesAfter = this.options.idlesAfter! * 60000; + const sessions: Session[] = this._inventory.sessions; + + return sessions.filter(session => { + return Date.now() - session.lastUsed! >= idlesAfter; + }); + } + + /** + * Returns stack traces for sessions that have not been released. + * + * @return {string[]} + */ + _getLeaks(): string[] { + return [...this._traces.values()].map(SessionPool.formatTrace); + } + + /** + * Returns true if the pool has a usable session. + * @private + */ + _hasSessionUsableFor(): boolean { + return this._inventory.sessions.length > 0; + } + + /** + * Attempts to get a session. + * + * @private + * + * @param {number} startTime Timestamp to use when determining timeouts. + * @returns {Promise} + */ + async _getSession(startTime: number): Promise { + const span = getActiveOrNoopSpan(); + if (this._hasSessionUsableFor()) { + span.addEvent('Cache hit: has usable session'); + return this._borrowNextAvailableSession(); + } + if (this.isFull && this.options.fail!) { + span.addEvent('Session pool is full and failFast=true'); + throw new SessionPoolExhaustedError(this._getLeaks()); + } + + let removeOnceCloseListener: Function; + let removeListener: Function; + + // Wait for a session to become available. + span.addEvent('Waiting for a session to become available'); + const availableEvent = 'session-available'; + const promises = [ + new Promise((_, reject) => { + const onceCloseListener = () => reject(new GoogleError(errors.Closed)); + this.once('close', onceCloseListener); + removeOnceCloseListener = this.removeListener.bind( + this, + 'close', + onceCloseListener, + ); + }), + new Promise(resolve => { + this.once(availableEvent, resolve); + removeListener = this.removeListener.bind( + this, + availableEvent, + resolve, + ); + }), + ]; + + const timeout = this.options.acquireTimeout; + + let removeTimeoutListener = () => {}; + if (!isInfinite(timeout!)) { + const elapsed = Date.now() - startTime!; + const remaining = timeout! - elapsed; + + promises.push( + new Promise((_, reject) => { + const error = new Error(errors.Timeout); + const timeoutFunction = setTimeout( + reject.bind(null, error), + remaining, + ); + removeTimeoutListener = () => clearTimeout(timeoutFunction); + }), + ); + } + + // Only create a new session if there are more waiters than sessions already + // being created. The current requester will be waiter number _numWaiters+1. + if (!this.isFull && this.totalPending <= this.totalWaiters) { + let amount = this.options.incStep + ? this.options.incStep + : DEFAULTS.incStep!; + // Create additional sessions if the configured minimum has not been reached. + const min = this.options.min ? this.options.min : 0; + if (this.size + this.totalPending + amount < min) { + amount = min - this.size - this.totalPending; + } + // Make sure we don't create more sessions than the pool should have. + if (amount + this.size > this.options.max!) { + amount = this.options.max! - this.size; + } + if (amount > 0) { + this._pending += amount; + promises.push( + new Promise((_, reject) => { + this._pending -= amount; + this._createSessions(amount).catch(reject); + }), + ); + } + } + + let removeErrorListener: Function; + promises.push( + new Promise((_, reject) => { + this.once('createError', reject); + removeErrorListener = this.removeListener.bind( + this, + 'createError', + reject, + ); + }), + ); + + try { + this._waiters++; + await Promise.race(promises); + } finally { + this._waiters--; + removeOnceCloseListener!(); + removeListener!(); + removeErrorListener!(); + removeTimeoutListener(); + } + + return this._borrowNextAvailableSession(); + } + + /** + * Checks to see whether or not session is expired. + * + * @param {Session} session The session to check. + * @returns {boolean} + */ + _isValidSession(session: Session): boolean { + // unpinged sessions only stay good for 1 hour + const MAX_DURATION = 60000 * 60; + + return Date.now() - session.lastUsed! < MAX_DURATION; + } + + /** + * Pings an individual session. + * + * @private + * + * @param {Session} session The session to ping. + * @returns {Promise} + */ + async _ping(session: Session): Promise { + // NOTE: Please do not trace Ping as it gets quite spammy + // with many root spans polluting the main span. + // Please see https://github.com/googleapis/google-cloud-go/issues/1691 + + this._borrow(session); + + if (!this._isValidSession(session)) { + this._inventory.borrowed.delete(session); + return; + } + + try { + await session.keepAlive(); + this.release(session); + } catch (e) { + this._inventory.borrowed.delete(session); + await this._destroy(session); + } + } + + /** + * Makes a keep alive request to all the idle sessions. + * + * @private + * + * @returns {Promise} + */ + async _pingIdleSessions(): Promise { + const sessions = this._getIdleSessions(); + const pings = sessions.map(session => this._ping(session)); + + await Promise.all(pings); + try { + await this._fill(); + } catch (error) { + // Ignore `Database not found` error. This allows a user to call instance.database('db-name') + // for a database that does not yet exist with SessionPoolOptions.min > 0. + const err = error as ServiceError; + if ( + isDatabaseNotFoundError(err) || + isInstanceNotFoundError(err) || + isCreateSessionPermissionError(err) || + isDefaultCredentialsNotSetError(err) || + isProjectIdNotSetInEnvironmentError(err) + ) { + return; + } + this.emit('error', err); + } + return; + } + + /** + * Creates a transaction for a session. + * + * @private + * + * @param {Session} session The session object. + * @param {object} options The transaction options. + */ + _prepareTransaction(session: Session): void { + const transaction = session.transaction( + (session.parent as Database).queryOptions_, + ); + session.txn = transaction; + } + + /** + * Releases a session back into the pool. + * + * @private + * + * @fires SessionPool#available + * @fires SessionPool#session-available + * @fires @deprecated SessionPool#readonly-available + * @fires @deprecated SessionPool#readwrite-available + * @param {Session} session The session object. + */ + _release(session: Session): void { + this._inventory.sessions.push(session); + this._inventory.borrowed.delete(session); + this._traces.delete(session.id); + + this.emit('available'); + this.emit('session-available'); + this.emit('readonly-available'); + this.emit('readwrite-available'); + } + + /** + * Starts housekeeping (pinging/evicting) of idle sessions. + * + * @private + */ + _startHouseKeeping(): void { + const evictRate = this.options.idlesAfter! * 60000; + + this._evictHandle = setInterval(() => this._evictIdleSessions(), evictRate); + this._evictHandle.unref(); + + const pingRate = this.options.keepAlive! * 60000; + + this._pingHandle = setInterval(() => this._pingIdleSessions(), pingRate); + this._pingHandle.unref(); + } + + /** + * Stops housekeeping. + * + * @private + */ + _stopHouseKeeping(): void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + clearInterval(this._pingHandle as any); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + clearInterval(this._evictHandle as any); + } +} diff --git a/handwritten/spanner/src/session.ts b/handwritten/spanner/src/session.ts new file mode 100644 index 00000000000..b0dfa814b47 --- /dev/null +++ b/handwritten/spanner/src/session.ts @@ -0,0 +1,573 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +/*! + * @module spanner/session + */ + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common-grpc/service-object'); +import {promisifyAll} from '@google-cloud/promisify'; +import * as extend from 'extend'; +import * as r from 'teeny-request'; +import { + Snapshot, + Transaction, + PartitionedDml, + TimestampBounds, +} from './transaction'; +import {google} from '../protos/protos'; +import { + Database, + CreateSessionCallback, + CreateSessionOptions, +} from './database'; +import {ServiceObjectConfig} from '@google-cloud/common'; +import { + NormalCallback, + addLeaderAwareRoutingHeader, + getCommonHeaders, +} from './common'; +import {ObservabilityOptions} from './instrument'; +import {grpc, CallOptions} from 'google-gax'; +import IRequestOptions = google.spanner.v1.IRequestOptions; +import {Spanner} from '.'; +import {injectRequestIDIntoHeaders, nextNthRequest} from './request_id_header'; +export type GetSessionResponse = [Session, r.Response]; + +/** + * @deprecated. enum to capture the possible session types + */ +export const enum types { + ReadOnly = 'readonly', + ReadWrite = 'readwrite', +} + +export interface GetSessionMetadataResponse { + name?: string | null; + labels?: {[k: string]: string} | null; + createTime?: google.protobuf.ITimestamp | null; + approximateLastUseTime?: google.protobuf.ITimestamp | null; + databaseRole?: string | null; +} + +export type GetSessionMetadataCallback = + NormalCallback; + +export type KeepAliveCallback = NormalCallback; +export type KeepAliveResponse = [google.spanner.v1.IResultSet]; +export type DeleteSessionResponse = [google.protobuf.IEmpty]; +export type DeleteSessionCallback = NormalCallback; + +/** + * Create a Session object to interact with a Cloud Spanner session. + * + * **It is unlikely you will need to interact with sessions directly. By + * default, sessions are created and utilized for maximum performance + * automatically.** + * + * @class + * @param {Database} database Parent {@link Database} instance. + * @param {string} [name] The name of the session. If not provided, it is + * assumed you are going to create it. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * //- + * // To create a session manually, don't provide a name. + * //- + * const session = database.session(); + * + * session.create(function(err) { + * if (err) { + * // Error handling omitted. + * } + * + * // Session created successfully. + * // `session.id` = The name of the session. + * }); + * + * //- + * // To access a previously-created session, provide a name. + * //- + * const session = database.session('session-name'); + * ``` + */ +export class Session extends common.GrpcServiceObject { + formattedName_?: string; + txn?: Transaction; + lastUsed?: number; + lastError?: grpc.ServiceError; + commonHeaders_: {[k: string]: string}; + _observabilityOptions?: ObservabilityOptions; + constructor(database: Database, name?: string) { + const methods = { + /** + * Create a session. + * + * @method Session#create + * @param {object} [options] See {@link Database#createSession}. + * @param {CreateSessionCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * session.create(function(err, session, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Session created successfully. + * }); + * + * //- + * //Returns a Promise if the callback is omitted. + * //- + * session.create() + * .then(function(data) { + * const session = data[0]; + * const apiResponse = data[1]; + * + * // Session created successfully. + * }); + * ``` + */ + create: true, + /** + * @typedef {array} SessionExistsResponse + * @property {boolean} 0 Whether the {@link Session} exists. + */ + /** + * @callback SessionExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link Session} exists. + */ + /** + * Check if a session exists. + * + * @method Session#exists + * @param {SessionExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * session.exists(function(err, exists) {}); + * + * //- + * //Returns a Promise if the callback is omitted. + * //- + * session.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: true, + /** + * @typedef {array} GetSessionResponse + * @property {Session} 0 The {@link Session}. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateSessionCallback + * @param {?Error} err Request error, if any. + * @param {Session} session The {@link Session}. + * @param {object} apiResponse The full API response. + */ + /** + * Get a session if it exists. + * + * You may optionally use this to "get or create" an object by providing + * an object with `autoCreate` set to `true`. Any extra configuration that + * is normally required for the `create` method must be contained within + * this object as well. + * + * @method Session#get + * @param {options} [options] Configuration object. + * @param {boolean} [options.autoCreate=false] Automatically create the + * object if it does not exist. + * @param {CreateSessionCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * session.get(function(err, session, apiResponse) { + * // `session.metadata` has been populated. + * }); + * + * //- + * //Returns a Promise if the callback is omitted. + * //- + * session.get().then(function(data) { + * const session = data[0]; + * const apiResponse = data[0]; + * }); + * ``` + */ + get: true, + }; + super({ + parent: database, + /** + * @name Session#id + * @type {string} + */ + id: name, + methods, + createMethod: ( + _: {}, + optionsOrCallback: CreateSessionOptions | CreateSessionCallback, + callback: CreateSessionCallback, + ) => { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' + ? optionsOrCallback + : callback; + + this.labels = options.labels || null; + this.databaseRole = + options.databaseRole || database.databaseRole || null; + + return database.createSession(options, (err, session, apiResponse) => { + if (err) { + callback(err, null, apiResponse); + return; + } + + extend(this, session); + callback(null, this, apiResponse); + }); + }, + } as {} as ServiceObjectConfig); + + this._observabilityOptions = database._observabilityOptions; + this.commonHeaders_ = getCommonHeaders( + (this.parent as Database).formattedName_, + this._observabilityOptions?.enableEndToEndTracing, + ); + this.request = database.request; + this.requestStream = database.requestStream; + + if (name) { + this.formattedName_ = Session.formatName_(database.formattedName_, name); + } + } + /** + * Delete a session. + * + * Wrapper around {@link v1.SpannerClient#deleteSession}. + * + * @see {@link v1.SpannerClient#deleteSession} + * @see [DeleteSession API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.DeleteSession) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DeleteSessionCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * session.delete(function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Session deleted successfully. + * }); + * + * //- + * //Returns a Promise if the callback is omitted. + * //- + * session.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + delete(gaxOptions?: CallOptions): Promise; + delete(callback: DeleteSessionCallback): void; + delete(gaxOptions: CallOptions, callback: DeleteSessionCallback): void; + delete( + optionsOrCallback?: CallOptions | DeleteSessionCallback, + cb?: DeleteSessionCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts = { + name: this.formattedName_, + }; + const database = this.parent as Database; + return this.request( + { + client: 'SpannerClient', + method: 'deleteSession', + reqOpts, + gaxOpts, + headers: injectRequestIDIntoHeaders( + this.commonHeaders_, + this, + nextNthRequest(database), + 1, + ), + }, + callback!, + ); + } + /** + * @typedef {array} GetSessionMetadataResponse + * @property {object} 0 The session's metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetSessionMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The session's metadata. + * @param {object} apiResponse The full API response. + */ + /** + * Get the session's metadata. + * + * Wrapper around {@link v1.SpannerClient#getSession}. + * + * @see {@link v1.SpannerClient#getSession} + * @see [GetSession API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.GetSession) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {GetSessionMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * session.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * //Returns a Promise if the callback is omitted. + * //- + * session.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + getMetadata(gaxOptions?: CallOptions): Promise; + getMetadata(callback: GetSessionMetadataCallback): void; + getMetadata( + gaxOptions: CallOptions, + callback: GetSessionMetadataCallback, + ): void; + getMetadata( + optionsOrCallback?: CallOptions | GetSessionMetadataCallback, + cb?: GetSessionMetadataCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts = { + name: this.formattedName_, + }; + + const headers = this.commonHeaders_; + if (this._getSpanner().routeToLeaderEnabled) { + addLeaderAwareRoutingHeader(headers); + } + const database = this.parent as Database; + return this.request( + { + client: 'SpannerClient', + method: 'getSession', + reqOpts, + gaxOpts, + headers: injectRequestIDIntoHeaders( + headers, + this.session, + nextNthRequest(database), + 1, + ), + }, + (err, resp) => { + if (resp) { + resp.databaseRole = resp.creatorRole; + delete resp.creatorRole; + this.metadata = resp; + } + callback!(err, resp); + }, + ); + } + /** + * Ping the session with `SELECT 1` to prevent it from expiring. + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {BasicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * session.keepAlive(function(err) { + * if (err) { + * // An error occurred while trying to keep this session alive. + * } + * }); + * ``` + */ + keepAlive(gaxOptions?: CallOptions): Promise; + keepAlive(callback: KeepAliveCallback): void; + keepAlive(gaxOptions: CallOptions, callback: KeepAliveCallback): void; + keepAlive( + optionsOrCallback?: CallOptions | KeepAliveCallback, + cb?: KeepAliveCallback, + ): void | Promise { + const gaxOpts = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + const reqOpts = { + session: this.formattedName_, + sql: 'SELECT 1', + }; + + const database = this.parent as Database; + return this.request( + { + client: 'SpannerClient', + method: 'executeSql', + reqOpts, + gaxOpts, + headers: injectRequestIDIntoHeaders( + this.commonHeaders_, + this, + nextNthRequest(database), + 1, + ), + }, + callback!, + ); + } + + /** + * Create a PartitionedDml transaction. + * + * @returns {PartitionedDml} + * + * @example + * ``` + * const transaction = session.partitionedDml(); + * ``` + */ + partitionedDml() { + return new PartitionedDml(this); + } + /** + * Create a Snapshot transaction. + * + * @param {TimestampBounds} [options] The timestamp bounds. + * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions] The default query options to use. + * @returns {Snapshot} + * + * @example + * ``` + * const snapshot = session.snapshot({strong: false}); + * ``` + */ + snapshot( + options?: TimestampBounds, + queryOptions?: google.spanner.v1.ExecuteSqlRequest.IQueryOptions, + ) { + return new Snapshot(this, options, queryOptions); + } + /** + * Create a read write Transaction. + * + * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions] The default query options to use. + * @return {Transaction} + * + * @example + * ``` + * const transaction = session.transaction(); + * ``` + */ + transaction( + queryOptions?: google.spanner.v1.ExecuteSqlRequest.IQueryOptions, + requestOptions?: Pick, + ) { + return new Transaction(this, undefined, queryOptions, requestOptions); + } + /** + * Format the session name to include the parent database's name. + * + * @private + * + * @param {string} databaseName The parent database's name. + * @param {string} name The instance name. + * @returns {string} + * + * @example + * ``` + * Session.formatName_('my-database', 'my-session'); + * // 'projects/grape-spaceship-123/instances/my-instance/' + + * // 'databases/my-database/sessions/my-session' + * ``` + */ + static formatName_(databaseName: string, name: string) { + if (name.indexOf('/') > -1) { + return name; + } + const sessionName = name.split('/').pop(); + return databaseName + '/sessions/' + sessionName; + } + + /** + * Gets the Spanner object + * + * @private + * + * @returns {Spanner} + */ + private _getSpanner(): Spanner { + return this.parent.parent.parent as Spanner; + } + + private channelId(): number { + // The Node.js client does not use a gRPC channel pool, so this always returns 1. + return 1; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Session, { + exclude: ['delete', 'partitionedDml', 'snapshot', 'transaction'], +}); diff --git a/handwritten/spanner/src/spanner_grpc_config.json b/handwritten/spanner/src/spanner_grpc_config.json new file mode 100644 index 00000000000..bd640bdbe0b --- /dev/null +++ b/handwritten/spanner/src/spanner_grpc_config.json @@ -0,0 +1,92 @@ +{ + "channelPool": { + "maxSize": 10, + "maxConcurrentStreamsLowWatermark": 100 + }, + "method": [ + { + "name": ["/google.spanner.v1.Spanner/CreateSession"], + "affinity": { + "command": "BIND", + "affinityKey": "name" + } + }, + { + "name": ["/google.spanner.v1.Spanner/GetSession"], + "affinity": { + "command": "BOUND", + "affinityKey": "name" + } + }, + { + "name": ["/google.spanner.v1.Spanner/DeleteSession"], + "affinity": { + "command": "UNBIND", + "affinityKey": "name" + } + }, + { + "name": ["/google.spanner.v1.Spanner/ExecuteSql"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + }, + { + "name": ["/google.spanner.v1.Spanner/ExecuteStreamingSql"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + }, + { + "name": ["/google.spanner.v1.Spanner/Read"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + }, + { + "name": ["/google.spanner.v1.Spanner/StreamingRead"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + }, + { + "name": ["/google.spanner.v1.Spanner/BeginTransaction"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + }, + { + "name": ["/google.spanner.v1.Spanner/Commit"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + }, + { + "name": ["/google.spanner.v1.Spanner/Rollback"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + }, + { + "name": ["/google.spanner.v1.Spanner/PartitionQuery"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + }, + { + "name": ["/google.spanner.v1.Spanner/PartitionRead"], + "affinity": { + "command": "BOUND", + "affinityKey": "session" + } + } + ] +} diff --git a/handwritten/spanner/src/table.ts b/handwritten/spanner/src/table.ts new file mode 100644 index 00000000000..0171272abad --- /dev/null +++ b/handwritten/spanner/src/table.ts @@ -0,0 +1,1177 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 {promisifyAll} from '@google-cloud/promisify'; +import * as through from 'through2'; +import {Operation as GaxOperation, CallOptions} from 'google-gax'; +import {Database, UpdateSchemaCallback, UpdateSchemaResponse} from './database'; +import {PartialResultStream, Row} from './partial-result-stream'; +import { + ReadRequest, + TimestampBounds, + CommitOptions, + CommitResponse, + ReadResponse, + ReadCallback, + CommitCallback, +} from './transaction'; +import {google as databaseAdmin} from '../protos/protos'; +import {Schema, LongRunningCallback} from './common'; +import IRequestOptions = databaseAdmin.spanner.v1.IRequestOptions; +import { + ObservabilityOptions, + startTrace, + setSpanError, + traceConfig, +} from './instrument'; +import {google} from '../protos/protos'; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import {Int, SpannerDate, Numeric, Float32, Float} from './codec'; + +// valid scalar types that Spanner accepts in a Key +export type KeyScalar = + | string + | number + | boolean + | SpannerDate + | Buffer + | Uint8Array + | Int + | Numeric + | Float32 + | Float; + +export type Key = KeyScalar | KeyScalar[]; + +export type CreateTableResponse = [ + Table, + GaxOperation, + databaseAdmin.longrunning.IOperation, +]; +export type CreateTableCallback = LongRunningCallback; + +export type DropTableResponse = UpdateSchemaResponse; +export type DropTableCallback = UpdateSchemaCallback; + +interface MutateRowsOptions extends CommitOptions { + requestOptions?: Omit; + excludeTxnFromChangeStreams?: boolean; + isolationLevel?: IsolationLevel; + readLockMode?: ReadLockMode; +} + +export type DeleteRowsCallback = CommitCallback; +export type DeleteRowsResponse = CommitResponse; +export type DeleteRowsOptions = MutateRowsOptions; + +export type InsertRowsCallback = CommitCallback; +export type InsertRowsResponse = CommitResponse; +export type InsertRowsOptions = MutateRowsOptions; + +export type ReplaceRowsCallback = CommitCallback; +export type ReplaceRowsResponse = CommitResponse; +export type ReplaceRowsOptions = MutateRowsOptions; + +export type UpdateRowsCallback = CommitCallback; +export type UpdateRowsResponse = CommitResponse; +export type UpdateRowsOptions = MutateRowsOptions; + +export type UpsertRowsCallback = CommitCallback; +export type UpsertRowsResponse = CommitResponse; +export type UpsertRowsOptions = MutateRowsOptions; + +const GOOGLE_STANDARD_SQL = 'GOOGLE_STANDARD_SQL'; +const POSTGRESQL = 'POSTGRESQL'; +/** + * Create a Table object to interact with a table in a Cloud Spanner + * database. + * + * @class + * + * @param {Database} database {@link Database} instance. + * @param {string} name Name of the table. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('my-table'); + * ``` + */ +class Table { + database: Database; + name: string; + _observabilityOptions?: ObservabilityOptions; + constructor(database: Database, name: string) { + /** + * The {@link Database} instance of this {@link Table} instance. + * @name Table#database + * @type {Database} + */ + this.database = database; + /** + * The name of this table. + * @name Table#name + * @type {string} + */ + this.name = name; + this._observabilityOptions = database._observabilityOptions; + } + /** + * Create a table. + * + * @param {string} schema See {@link Database#createTable}. + * @param {object} [gaxOptions] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {CreateTableCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * const schema = + * 'CREATE TABLE Singers (' + + * ' SingerId INT64 NOT NULL,' + + * ' FirstName STRING(1024),' + + * ' LastName STRING(1024),' + + * ' SingerInfo BYTES(MAX),' + + * ') PRIMARY KEY(SingerId)'; + * + * table.create(schema, function(err, table, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Table created successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.create(schema) + * .then(function(data) { + * const table = data[0]; + * const operation = data[1]; + * + * return operation.promise(); + * }) + * .then(function() { + * // Table created successfully. + * }); + * ``` + */ + create( + schema: Schema, + gaxOptions?: CallOptions, + ): Promise; + create(schema: Schema, callback: CreateTableCallback): void; + create( + schema: Schema, + gaxOptions: CallOptions, + callback: CreateTableCallback, + ): void; + create( + schema: Schema, + gaxOptionsOrCallback?: CallOptions | CreateTableCallback, + cb?: CreateTableCallback, + ): Promise | void { + const gaxOptions = + typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; + const callback = + typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; + + this.database.createTable(schema, gaxOptions, callback!); + } + + protected getDBName(): string { + return this.database.formattedName_; + } + + /** + * Create a readable object stream to receive rows from the database using key + * lookups and scans. + * + * @see [StreamingRead API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.StreamingRead) + * @see [ReadRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest) + * + * @param {ReadRequest} query Configuration object, describing what to read from the table.. + * @param {TimestampBounds} [options] [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds). + * @returns {PartialResultStream} A readable stream that emits rows. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * table.createReadStream({ + * keys: ['1'], + * columns: ['SingerId', 'name'] + * }) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }) + * .on('end', function() { + * // All results retrieved. + * }); + * + * //- + * // Provide an array for `query.keys` to read with a composite key. + * //- + * const query = { + * keys: [ + * [ + * 'Id1', + * 'Name1' + * ], + * [ + * 'Id2', + * 'Name2' + * ] + * ], + * // ... + * }; + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * table.createReadStream({ + * keys: ['1'], + * columns: ['SingerId', 'name'] + * }) + * .on('data', function(row) { + * this.end(); + * }); + * ``` + */ + createReadStream( + request: ReadRequest, + options: TimestampBounds = {}, + ): PartialResultStream { + const proxyStream = through.obj(); + + this.database.getSnapshot(options, (err, snapshot) => { + if (err) { + proxyStream.destroy(err); + return; + } + + snapshot! + .createReadStream(this.name, request) + .on('error', err => { + proxyStream.destroy(err); + snapshot!.end(); + }) + .on('end', () => snapshot!.end()) + .pipe(proxyStream); + }); + + return proxyStream as PartialResultStream; + } + /** + * @typedef {array} DropTableResponse + * @property {google.longrunning.Operation} 0 An {@link Operation} object that can be used to check + * the status of the request. + * @property {object} 1 The full API response. + */ + /** + * @callback DropTableCallback + * @param {?Error} err Request error, if any. + * @param {google.longrunning.Operation} operation An {@link Operation} object that can be used to + * check the status of the request. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the table. Not to be confused with {@link Table#deleteRows}. + * + * Wrapper around {@link Database#updateSchema}. + * + * @see {@link Database#updateSchema} + * + * @throws {TypeError} If any arguments are passed in. + * @param {object} [gaxOptions] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DropTableCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * table.delete(function(err, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Table deleted successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.delete() + * .then(function(data) { + * const operation = data[0]; + * return operation.promise(); + * }) + * .then(function() { + * // Table deleted successfully. + * }); + * ``` + */ + delete(gaxOptions?: CallOptions): Promise; + delete(callback: DropTableCallback): void; + delete(gaxOptions: CallOptions, callback: DropTableCallback): void; + delete( + gaxOptionsOrCallback?: CallOptions | DropTableCallback, + cb?: DropTableCallback, + ): Promise | void { + const gaxOptions = + typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; + const callback = + typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; + + const [schema, table] = this.name.includes('.') + ? this.name.split('.') + : [null, this.name]; + + let dropStatement = 'DROP TABLE `' + table + '`'; + + const performDelete = async (): Promise => { + const result = await this.database.getDatabaseDialect(gaxOptions); + + if (result && result.includes(POSTGRESQL)) { + dropStatement = schema + ? `DROP TABLE "${schema}"."${table}"` + : `DROP TABLE "${table}"`; + } else if (result && result.includes(GOOGLE_STANDARD_SQL)) { + dropStatement = schema + ? 'DROP TABLE `' + schema + '`.`' + table + '`' + : dropStatement; + } + + const updateSchemaResult = callback + ? this.database.updateSchema(dropStatement, gaxOptions, callback) + : this.database.updateSchema(dropStatement, gaxOptions); + + return updateSchemaResult as Promise; + }; + + if (!callback) { + return performDelete() as Promise; + } else { + void performDelete(); + } + } + /** + * @typedef {array} DeleteRowsResponse + * @property {CommitResponse} 0 The commit response. + */ + /** + * @callback DeleteRowsCallback + * @param {?Error} error Request error, if any. + * @param {CommitResponse} apiResponse The full API response. + */ + /** + * @typedef {object} DeleteRowsOptions + * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include + * with the commit request. + * @property {boolean} returnCommitStats Include statistics related to the + * transaction in the {@link CommitResponse}. + * @property {object} [gaxOptions] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * Delete rows from this table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {array} keys The keys for the rows to delete. If using a + * composite key, provide an array within this array. See the example + * below. + * @param {DeleteRowsOptions|CallOptions} [options] Options for configuring the request. + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DeleteRowsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * const keys = ['Id1', 'Id2', 'Id3']; + * + * table.deleteRows(keys, function(err, apiResponse) {}); + * + * //- + * // Provide an array for `keys` to delete rows with a composite key. + * //- + * const keys = [ + * [ + * 'Id1', + * 'Name1' + * ], + * [ + * 'Id2', + * 'Name2' + * ] + * ]; + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.deleteRows(keys) + * .then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + deleteRows( + keys: Key[], + options?: DeleteRowsOptions | CallOptions, + ): Promise; + deleteRows(keys: Key[], callback: DeleteRowsCallback): void; + deleteRows( + keys: Key[], + options: DeleteRowsOptions | CallOptions, + callback: DeleteRowsCallback, + ): void; + deleteRows( + keys: Key[], + optionsOrCallback?: DeleteRowsOptions | CallOptions | DeleteRowsCallback, + cb?: DeleteRowsCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + return this._mutate('deleteRows', keys, options, callback!); + } + /** + * Drop the table. + * + * @see {@link Table#delete} + * @see {@link Database#updateSchema} + * + * @param {object} [gaxOptions] Request configuration options. + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {DropTableCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * table.drop(function(err, operation, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * operation + * .on('error', function(err) {}) + * .on('complete', function() { + * // Table dropped successfully. + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.drop() + * .then(function(data) { + * const operation = data[0]; + * return operation.promise(); + * }) + * .then(function() { + * // Table dropped successfully. + * }); + * ``` + */ + drop(gaxOptions?: CallOptions): Promise; + drop(callback: DropTableCallback): void; + drop(gaxOptions: CallOptions, callback: DropTableCallback): void; + drop( + gaxOptionsOrCallback?: CallOptions | DropTableCallback, + cb?: DropTableCallback, + ): Promise | void { + const gaxOptions = + typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; + const callback = + typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; + + return this.delete(gaxOptions, callback!); + } + /** + * @typedef {array} InsertRowsResponse + * @property {CommitResponse} 0 The commit response. + */ + /** + * @callback InsertRowsCallback + * @param {?Error} error Request error, if any. + * @param {CommitResponse} apiResponse The full API response. + */ + /** + * @typedef {object} InsertRowsOptions + * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include + * with the commit request. + * @property {boolean} returnCommitStats Include statistics related to the + * transaction in the {@link CommitResponse}. + * @property {object} [gaxOptions] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * Insert rows of data into this table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * @param {InsertRowsOptions|CallOptions} [options] Options for configuring the request. + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {InsertRowsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * const row = { + * SingerId: 'Id3', + * Name: 'Eddie Wilson' + * }; + * + * table.insert(row, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Rows inserted successfully. + * }); + * + * //- + * // Multiple rows can be inserted at once. + * //- + * const row2 = { + * SingerId: 'Id3b', + * Name: 'Joe West' + * }; + * + * table.insert([ + * row, + * row2 + * ], function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.insert(row) + * .then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example + * region_tag:spanner_insert_data + * Full example: + */ + insert( + rows: object | object[], + options?: InsertRowsOptions | CallOptions, + ): Promise; + insert(rows: object | object[], callback: InsertRowsCallback): void; + insert( + rows: object | object[], + options: InsertRowsOptions | CallOptions, + callback: InsertRowsCallback, + ): void; + insert( + rows: object | object[], + optionsOrCallback?: InsertRowsOptions | CallOptions | InsertRowsCallback, + cb?: InsertRowsCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + this._mutate('insert', rows, options, callback!); + } + /** + * Configuration object, describing what to read from the table. + */ + /** + * @typedef {array} TableReadResponse + * @property {array[]} 0 Rows are returned as an array of object arrays. Each + * object has a `name` and `value` property. To get a serialized object, + * call `toJSON()`. Optionally, provide an options object to `toJSON()` + * specifying `wrapNumbers: true` to protect large integer values outside + * of the range of JavaScript Number. If set, FLOAT64 values will be returned + * as {@link Spanner.Float} objects and INT64 values as {@link + * Spanner.Int}. + */ + /** + * @callback TableReadCallback + * @param {?Error} err Request error, if any. + * @param {array[]} rows Rows are returned as an array of object arrays. Each + * object has a `name` and `value` property. To get a serialized object, + * call `toJSON()`. Optionally, provide an options object to `toJSON()` + * specifying `wrapNumbers: true` to protect large integer values outside + * of the range of JavaScript Number. If set, FLOAT64 values will be returned + * as {@link Spanner.Float} objects and INT64 values as {@link + * Spanner.Int}. + */ + /** + * Receive rows from the database using key lookups and scans. + * + * **Performance Considerations:** + * + * This method wraps the streaming method, + * {@link Table#createReadStream} for your convenience. All rows will + * be stored in memory before being released to your callback. If you intend + * on receiving a lot of results from your query, consider using the streaming + * method, so you can free each result from memory after consuming it. + * + * @param {ReadRequest} query Configuration object, describing + * what to read from the table. + * @param {TimestampBounds} options [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds). + * @param {TableReadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * const query = { + * keys: ['1'], + * columns: ['SingerId', 'name'] + * }; + * + * table.read(query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * const firstRow = rows[0]; + * + * // firstRow = [ + * // { + * // name: 'SingerId', + * // value: '1' + * // }, + * // { + * // name: 'Name', + * // value: 'Eddie Wilson' + * // } + * // ] + * }); + * + * //- + * // Provide an array for `query.keys` to read with a composite key. + * //- + * const query = { + * keys: [ + * [ + * 'Id1', + * 'Name1' + * ], + * [ + * 'Id2', + * 'Name2' + * ] + * ], + * // ... + * }; + * + * //- + * // Rows are returned as an array of object arrays. Each object has a `name` + * // and `value` property. To get a serialized object, call `toJSON()`. + * // + * // Alternatively, set `query.json` to `true`, and this step will be + * performed + * // automatically. + * //- + * table.read(query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * const firstRow = rows[0]; + * + * // firstRow.toJSON() = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.read(query) + * .then(function(data) { + * const rows = data[0]; + * }); + * + * ``` + * @example + * region_tag:spanner_read_data + * Full example: + * + * @example + * region_tag:spanner_read_stale_data + * Reading stale data: + * + * @example + * region_tag:spanner_read_data_with_index + * Reading data using an index: + * + * @example + * region_tag:spanner_read_data_with_storing_index + * Reading data using a storing index: + */ + read(request: ReadRequest, options?: TimestampBounds): Promise; + read(request: ReadRequest, callback: ReadCallback): void; + read( + request: ReadRequest, + options: TimestampBounds, + callback: ReadCallback, + ): void; + read( + request: ReadRequest, + optionsOrCallback?: TimestampBounds | ReadCallback, + cb?: ReadCallback, + ): Promise | void { + const rows: Row[] = []; + + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + const options = + typeof optionsOrCallback === 'object' + ? (optionsOrCallback as TimestampBounds) + : {}; + + this.createReadStream(request, options) + .on('error', callback!) + .on('data', (row: Row) => rows.push(row)) + .on('end', () => callback!(null, rows)); + } + /** + * @typedef {array} ReplaceRowsResponse + * @property {CommitResponse} 0 The commit response. + */ + /** + * @callback ReplaceRowsCallback + * @param {?Error} error Request error, if any. + * @param {CommitResponse} apiResponse The full API response. + */ + /** + * @typedef {object} ReplaceRowsOptions + * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include + * with the commit request. + * @property {boolean} returnCommitStats Include statistics related to the + * transaction in the {@link CommitResponse}. + * @property {object} [gaxOptions] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * Replace rows of data within this table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * @param {ReplaceRowsOptions|CallOptions} [options] Options for configuring the request. + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {ReplaceRowsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * const row = { + * SingerId: 'Id3', + * Name: 'Joe West' + * }; + * + * table.replace(row, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Row replaced successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.replace(row) + * .then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + replace( + rows: object | object[], + options?: ReplaceRowsOptions | CallOptions, + ): Promise; + replace(rows: object | object[], callback: ReplaceRowsCallback): void; + replace( + rows: object | object[], + options: ReplaceRowsOptions | CallOptions, + callback: ReplaceRowsCallback, + ): void; + replace( + rows: object | object[], + optionsOrCallback?: ReplaceRowsOptions | CallOptions | ReplaceRowsCallback, + cb?: ReplaceRowsCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + this._mutate('replace', rows, options, callback!); + } + /** + * @typedef {array} UpdateRowsResponse + * @property {CommitResponse} 0 The commit response. + */ + /** + * @callback UpdateRowsCallback + * @param {?Error} error Request error, if any. + * @param {CommitResponse} apiResponse The full API response. + */ + /** + * @typedef {object} UpdateRowsOptions + * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include + * with the commit request. + * @property {boolean} returnCommitStats Include statistics related to the + * transaction in the {@link CommitResponse}. + * @property {object} [gaxOptions] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * Update rows of data within this table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * @param {UpdateRowsOptions|CallOptions} [options] Options for configuring the request. + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {UpdateRowsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * const row = { + * SingerId: 'Id3', + * Name: 'Joe West' + * }; + * + * table.update(row, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Row updated successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.update(row) + * .then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example + * region_tag:spanner_update_data + * Full example: + */ + update( + rows: object | object[], + options?: UpdateRowsOptions | CallOptions, + ): Promise; + update(rows: object | object[], callback: UpdateRowsCallback): void; + update( + rows: object | object[], + options: UpdateRowsOptions | CallOptions, + callback: UpdateRowsCallback, + ): void; + update( + rows: object | object[], + optionsOrCallback?: UpdateRowsOptions | CallOptions | UpdateRowsCallback, + cb?: UpdateRowsCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + this._mutate('update', rows, options, callback!); + } + /** + * @typedef {array} UpsertRowsResponse + * @property {CommitResponse} 0 The commit response. + */ + /** + * @callback UpsertRowsCallback + * @param {?Error} error Request error, if any. + * @param {CommitResponse} apiResponse The full API response. + */ + /** + * @typedef {object} UpsertRowsOptions + * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include + * with the commit request. + * @property {boolean} returnCommitStats Include statistics related to the + * transaction in the {@link CommitResponse}. + * @property {object} [gaxOptions] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * Insert or update rows of data within this table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * + * @param {UpsertRowsOptions|CallOptions} [options] Options for configuring the request. + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {UpsertRowsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * const table = database.table('Singers'); + * + * const row = { + * SingerId: 'Id3', + * Name: 'Joe West' + * }; + * + * table.upsert(row, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // Row inserted or updated successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * table.upsert(row) + * .then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + upsert( + rows: object | object[], + options?: UpsertRowsOptions | CallOptions, + ): Promise; + upsert(rows: object | object[], callback: UpsertRowsCallback): void; + upsert( + rows: object | object[], + options: UpsertRowsOptions | CallOptions, + callback: UpsertRowsCallback, + ): void; + upsert( + rows: object | object[], + optionsOrCallback?: UpsertRowsOptions | CallOptions | UpsertRowsCallback, + cb?: UpsertRowsCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + + this._mutate('upsert', rows, options, callback!); + } + /** + * Creates a new transaction and applies the desired mutation via + * {@link Transaction#commit}. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @private + * + * @param {string} method CRUD method (insert, update, etc.). + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * @param {function} callback The callback function. + */ + private _mutate( + method: 'deleteRows' | 'insert' | 'replace' | 'update' | 'upsert', + rows: object | object[], + options: MutateRowsOptions | CallOptions = {}, + callback: CommitCallback, + ): void { + const traceConfig: traceConfig = { + opts: this._observabilityOptions, + tableName: this.name, + dbName: this.getDBName(), + transactionTag: (options as MutateRowsOptions)?.requestOptions + ?.transactionTag, + }; + + startTrace('Table.' + method, traceConfig, span => { + const requestOptions = + 'requestOptions' in options ? options.requestOptions : {}; + + const excludeTxnFromChangeStreams = + 'excludeTxnFromChangeStreams' in options + ? options.excludeTxnFromChangeStreams + : false; + + const isolationLevel = + 'isolationLevel' in options + ? options.isolationLevel + : IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED; + + const readLockMode = + 'readLockMode' in options + ? options.readLockMode + : ReadLockMode.READ_LOCK_MODE_UNSPECIFIED; + + this.database.runTransaction( + { + requestOptions: requestOptions, + excludeTxnFromChangeStreams: excludeTxnFromChangeStreams, + isolationLevel: isolationLevel, + readLockMode: readLockMode, + }, + (err, transaction) => { + if (err) { + setSpanError(span, err); + span.end(); + callback(err); + return; + } + + transaction![method](this.name, rows as Key[]); + transaction!.commit(options, (err, resp) => { + if (err) { + setSpanError(span, err); + } + span.end(); + callback(err, resp); + }); + }, + ); + }); + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Table, { + exclude: ['delete', 'drop'], +}); + +/** + * Reference to the {@link Table} class. + * @name module:@google-cloud/spanner.Table + * @see Table + */ +export {Table}; diff --git a/handwritten/spanner/src/transaction-runner.ts b/handwritten/spanner/src/transaction-runner.ts new file mode 100644 index 00000000000..4f569fcbf97 --- /dev/null +++ b/handwritten/spanner/src/transaction-runner.ts @@ -0,0 +1,411 @@ +/*! + * Copyright 2019 Google Inc. All Rights Reserved. + * + * 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 {promisify} from '@google-cloud/promisify'; +import {grpc} from 'google-gax'; +import {Root} from 'protobufjs'; +import * as through from 'through2'; + +import {Session} from './session'; +import {Transaction} from './transaction'; +import {NormalCallback} from './common'; +import {isSessionNotFoundError} from './session-pool'; +import {Database} from './database'; +import {google} from '../protos/protos'; +import IRequestOptions = google.spanner.v1.IRequestOptions; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const jsonProtos = require('../protos/protos.json'); +const RETRY_INFO = 'google.rpc.retryinfo-bin'; + +const RETRYABLE: grpc.status[] = [grpc.status.ABORTED]; + +// tslint:disable-next-line variable-name +const RetryInfo = Root.fromJSON(jsonProtos).lookup('google.rpc.RetryInfo'); + +/** + * @typedef {object} RunTransactionOptions + * @property {number} [timeout] The maximum amount of time (in ms) that a + * {@link Transaction} should be ran for. + */ +export interface RunTransactionOptions { + timeout?: number; + requestOptions?: Pick; + /** + * @deprecated Use readLockMode instead. + */ + optimisticLock?: boolean; + excludeTxnFromChangeStreams?: boolean; + isolationLevel?: IsolationLevel; + readLockMode?: ReadLockMode; +} + +/** + * A function to execute in the context of a transaction. + * @callback RunTransactionCallback + * @param {?Error} err An error returned while making this request. + * @param {Transaction} transaction The transaction object. The transaction has + * already been created, and is ready to be queried and committed against. + */ +export type RunTransactionCallback = NormalCallback; + +/** + * A function to execute in the context of a transaction. + * @callback AsyncRunTransactionCallback + * @param {Transaction} transaction The transaction object. The transaction has + * already been created, and is ready to be queried and committed against. + */ +export interface AsyncRunTransactionCallback { + (transaction: Transaction): Promise; +} + +interface ErrorCallback { + (err: grpc.ServiceError): void; +} + +/** + * Error class used to signal a Transaction timeout. + * + * @private + * @class + * + * @param {Error} [err] The last known retryable Error. + */ +export class DeadlineError extends Error implements grpc.ServiceError { + code: grpc.status; + details: string; + metadata: grpc.Metadata; + errors: grpc.ServiceError[]; + constructor(error?: grpc.ServiceError) { + super('Deadline for Transaction exceeded.'); + + this.code = grpc.status.DEADLINE_EXCEEDED; + this.details = error?.details || ''; + this.metadata = error?.metadata || new grpc.Metadata(); + this.errors = []; + + if (error) { + this.errors.push(error); + } + } +} + +/** + * Base class for running/retrying Transactions. + * + * @private + * @class + * @abstract + * + * @param {Database} database The Database to pull Sessions/Transactions from. + * @param {RunTransactionOptions} [options] The runner options. + */ +export abstract class Runner { + abstract runFn: Function; + attempts: number; + session: Session; + transaction?: Transaction; + options: RunTransactionOptions; + multiplexedSessionPreviousTransactionId?: Uint8Array | string; + constructor( + session: Session, + transaction: Transaction, + options?: RunTransactionOptions, + ) { + this.attempts = 0; + this.session = session; + this.transaction = transaction; + this.transaction.useInRunner(); + + const defaults = { + timeout: 3600000, + isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED, + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }; + + this.options = Object.assign(defaults, options); + } + /** + * Runs the user function against the provided transaction. Resolving the + * returned Promise upon completion/error. + * + * @private + * + * @param {Transaction} transaction The transaction to run against. + * @returns {Promise} + */ + protected abstract _run(transaction: Transaction): Promise; + /** + * Attempts to retrieve the retry delay from the supplied error. If absent it + * will create one based on the number of attempts made thus far. + * + * @private + * + * @param {Error} err The service error. + * @returns {number} Delay in milliseconds. + */ + getNextDelay(err: grpc.ServiceError): number { + const retryInfo = err.metadata && err.metadata.get(RETRY_INFO); + + if (retryInfo && retryInfo.length) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const {retryDelay} = (RetryInfo as any).decode(retryInfo[0]); + let {seconds} = retryDelay; + + if (typeof seconds !== 'number') { + seconds = seconds.toNumber(); + } + + const secondsInMs = Math.floor(seconds) * 1000; + const nanosInMs = Math.floor(retryDelay.nanos) / 1e6; + + return secondsInMs + nanosInMs; + } + // A 'Session not found' error without any specific retry info should not + // cause any delay between retries. + if (isSessionNotFoundError(err)) { + return 0; + } + + // Max backoff should be 32 seconds. + return ( + Math.pow(2, Math.min(this.attempts, 5)) * 1000 + + Math.floor(Math.random() * 1000) + ); + } + + /** Returns whether the given error should cause a transaction retry. */ + shouldRetry(err: grpc.ServiceError): boolean { + return ( + RETRYABLE.includes(err.code!) || + isSessionNotFoundError(err) || + isRetryableInternalError(err) + ); + } + /** + * Retrieves a transaction to run against. + * + * @private + * + * @returns Promise + */ + async getTransaction(): Promise { + if (this.transaction) { + const transaction = this.transaction; + delete this.transaction; + return transaction; + } + + const transaction = this.session.transaction( + (this.session.parent as Database).queryOptions_, + ); + transaction!.setReadWriteTransactionOptions( + this.options as RunTransactionOptions, + ); + transaction.multiplexedSessionPreviousTransactionId = + this.multiplexedSessionPreviousTransactionId; + if (this.attempts > 0) { + await transaction.begin(); + } + return transaction; + } + /** + * This function is responsible for getting transactions, running them and + * handling any errors, retrying if necessary. + * + * @private + * + * @returns {Promise} + */ + async run(): Promise { + const start = Date.now(); + const timeout = this.options.timeout!; + + let lastError: grpc.ServiceError; + + // The transaction runner should always execute at least one attempt before + // timing out. + while (this.attempts === 0 || Date.now() - start < timeout) { + const transaction = await this.getTransaction(); + + try { + return await this._run(transaction); + } catch (e) { + this.session.lastError = e as grpc.ServiceError; + lastError = e as grpc.ServiceError; + } finally { + this.multiplexedSessionPreviousTransactionId = transaction.id; + } + + // Note that if the error is a 'Session not found' error, it will be + // thrown here. We do this to bubble this error up to the caller who is + // responsible for retrying the transaction on a different session. + if ( + !RETRYABLE.includes(lastError.code!) && + !isRetryableInternalError(lastError) + ) { + throw lastError; + } + + this.attempts += 1; + + const delay = this.getNextDelay(lastError); + await new Promise(resolve => setTimeout(resolve, delay)); + } + + throw new DeadlineError(lastError!); + } +} + +/** + * This class handles transactions expecting to be ran in callback mode. + * + * @private + * @class + * + * @param {Database} database The database to pull sessions/transactions from. + * @param {RunTransactionCallback} runFn The user supplied run function. + * @param {RunTransactionOptions} [options] Runner options. + */ +export class TransactionRunner extends Runner { + runFn: RunTransactionCallback; + constructor( + session: Session, + transaction: Transaction, + runFn: RunTransactionCallback, + options?: RunTransactionOptions, + ) { + super(session, transaction, options); + this.runFn = runFn; + } + /** + * Because the user has decided to use callback mode, we want to try and + * intercept any ABORTED or UNKNOWN errors and stop the current function + * execution. + * + * @private + * + * @param {Transaction} transaction The transaction to intercept errors for. + * @param {Function} reject Function to call when a retryable error is found. + */ + private _interceptErrors( + transaction: Transaction, + reject: ErrorCallback, + ): void { + const request = transaction.request; + + transaction.request = promisify((config: object, callback: Function) => { + request(config, (err: null | grpc.ServiceError, resp: object) => { + if (!err || !this.shouldRetry(err)) { + callback(err, resp); + return; + } + + reject(err); + }); + }); + + const requestStream = transaction.requestStream; + + transaction.requestStream = (config: object) => { + const proxyStream = through.obj(); + const stream = requestStream(config); + + stream + .on('error', (err: grpc.ServiceError) => { + if (!this.shouldRetry(err)) { + proxyStream.destroy(err); + return; + } + + stream.unpipe(proxyStream); + reject(err); + }) + .pipe(proxyStream); + + return proxyStream as typeof stream; + }; + } + /** + * Creates a Promise that should resolve when the provided transaction has + * been committed or rolled back. Rejects if a retryable error occurs. + * + * @private + * + * @param {Transaction} + * @returns {Promise} + */ + protected _run(transaction: Transaction): Promise { + return new Promise((resolve, reject) => { + transaction.once('end', resolve); + this._interceptErrors(transaction, reject); + this.runFn(null, transaction); + }); + } +} + +/** + * This class handles transactions expecting to be ran in promise mode. + * + * @private + * @class + * + * @param {Database} database The database to pull sessions/transactions from. + * @param {AsyncRunTransactionCallback} runFn The user supplied run function. + * @param {RunTransactionOptions} [options] Runner options. + */ +export class AsyncTransactionRunner extends Runner { + runFn: AsyncRunTransactionCallback; + constructor( + session: Session, + transaction: Transaction, + runFn: AsyncRunTransactionCallback, + options?: RunTransactionOptions, + ) { + super(session, transaction, options); + this.runFn = runFn; + } + /** + * Since this is promise mode all we need to do is return the user function. + * + * @private + * + * @param {Transaction} transaction The transaction to be ran against. + * @returns {Promise} + */ + protected _run(transaction: Transaction): Promise { + return this.runFn(transaction); + } +} + +/** + * Checks whether the given error is a retryable internal error. + * @param error the error to check + * @return true if the error is a retryable internal error, and otherwise false. + */ +export function isRetryableInternalError(err: grpc.ServiceError): boolean { + return ( + err.code === grpc.status.INTERNAL && + (err.message.includes( + 'Received unexpected EOS on DATA frame from server', + ) || + err.message.includes('RST_STREAM') || + err.message.includes('HTTP/2 error code: INTERNAL_ERROR') || + err.message.includes('Connection closed with unknown cause')) + ); +} diff --git a/handwritten/spanner/src/transaction.ts b/handwritten/spanner/src/transaction.ts new file mode 100644 index 00000000000..75d4b2d0079 --- /dev/null +++ b/handwritten/spanner/src/transaction.ts @@ -0,0 +1,3350 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 {DateStruct, PreciseDate} from '@google-cloud/precise-date'; +import {promisifyAll} from '@google-cloud/promisify'; +import {isEmpty, toArray} from './helper'; +import Long = require('long'); +import {EventEmitter} from 'events'; +import {grpc, CallOptions, ServiceError, Status, GoogleError} from 'google-gax'; +import {common as p} from 'protobufjs'; +import {finished, Readable, PassThrough, Stream} from 'stream'; + +import {codec, Json, JSONOptions, Type, Value} from './codec'; +import { + PartialResultStream, + partialResultStream, + ResumeToken, + Row, +} from './partial-result-stream'; +import {Session} from './session'; +import {Key} from './table'; +import {Span} from './instrument'; +import {google as spannerClient} from '../protos/protos'; +import { + NormalCallback, + addLeaderAwareRoutingHeader, + getCommonHeaders, +} from './common'; +import {google} from '../protos/protos'; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import IAny = google.protobuf.IAny; +import IQueryOptions = google.spanner.v1.ExecuteSqlRequest.IQueryOptions; +import IRequestOptions = google.spanner.v1.IRequestOptions; +import {Database, Spanner} from '.'; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import { + ObservabilityOptions, + startTrace, + setSpanError, + setSpanErrorAndException, + traceConfig, +} from './instrument'; +import {RunTransactionOptions} from './transaction-runner'; +import {injectRequestIDIntoHeaders, nextNthRequest} from './request_id_header'; + +export type Rows = Array; +const RETRY_INFO_TYPE = 'type.googleapis.com/google.rpc.retryinfo'; +const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin'; + +export interface TimestampBounds { + strong?: boolean; + minReadTimestamp?: PreciseDate | spannerClient.protobuf.ITimestamp; + maxStaleness?: number | spannerClient.protobuf.IDuration; + readTimestamp?: PreciseDate | spannerClient.protobuf.ITimestamp; + exactStaleness?: number | spannerClient.protobuf.IDuration; + returnReadTimestamp?: boolean; +} + +export interface BatchWriteOptions { + requestOptions?: Pick; + gaxOptions?: CallOptions; + excludeTxnFromChangeStreams?: boolean; +} + +export interface RequestOptions { + json?: boolean; + jsonOptions?: JSONOptions; + gaxOptions?: CallOptions; + maxResumeRetries?: number; + /** + * An object where column names as keys and custom objects as corresponding + * values for deserialization. This is only needed for proto columns + * where deserialization logic is on user-specific code. When provided, + * the custom object enables deserialization of backend-received column data. + * If not provided, data remains serialized as buffer for Proto Messages and + * integer for Proto Enums. + * + * @example + * To obtain Proto Messages and Proto Enums as JSON objects, you must supply + * additional metadata. This metadata should include the protobufjs-cli + * generated proto message function and enum object. It encompasses the essential + * logic for proper data deserialization. + * + * Eg: To read data from Proto Columns in json format using DQL, you should pass + * columnsMetadata where key is the name of the column and value is the protobufjs-cli + * generated proto message function and enum object. + * + * const query = { + * sql: `SELECT SingerId, + * FirstName, + * LastName, + * SingerInfo, + * SingerGenre, + * SingerInfoArray, + * SingerGenreArray + * FROM Singers + * WHERE SingerId = 6`, + * columnsMetadata: { + * SingerInfo: music.SingerInfo, + * SingerInfoArray: music.SingerInfo, + * SingerGenre: music.Genre, + * SingerGenreArray: music.Genre, + * }, + * }; + */ + columnsMetadata?: object; +} + +export interface CommitOptions { + requestOptions?: Pick; + returnCommitStats?: boolean; + maxCommitDelay?: spannerClient.protobuf.IDuration; + gaxOptions?: CallOptions; +} + +export interface Statement { + sql: string; + params?: {[param: string]: Value}; + types?: Type | {[param: string]: Value}; + // This property is used internally as a mapping for types. Do not set it manually + paramTypes?: {[k: string]: google.spanner.v1.Type} | null; +} + +export interface ExecuteSqlRequest extends Statement, RequestOptions { + resumeToken?: ResumeToken; + queryMode?: spannerClient.spanner.v1.ExecuteSqlRequest.QueryMode; + partitionToken?: Uint8Array | string; + seqno?: number; + queryOptions?: IQueryOptions; + requestOptions?: Omit; + dataBoostEnabled?: boolean | null; + directedReadOptions?: google.spanner.v1.IDirectedReadOptions; +} + +export interface KeyRange { + startClosed?: Value[]; + startOpen?: Value[]; + endClosed?: Value[]; + endOpen?: Value[]; +} + +export interface ReadRequest extends RequestOptions { + table?: string; + index?: string; + columns?: string[] | null; + keys?: string[] | string[][]; + ranges?: KeyRange[]; + keySet?: spannerClient.spanner.v1.IKeySet | null; + limit?: number | Long | string | null; + resumeToken?: Uint8Array | null; + partitionToken?: Uint8Array | null; + requestOptions?: Omit; + dataBoostEnabled?: boolean | null; + directedReadOptions?: google.spanner.v1.IDirectedReadOptions; +} + +export interface BatchUpdateError extends grpc.ServiceError { + rowCounts: number[]; +} + +export type CommitRequest = spannerClient.spanner.v1.ICommitRequest; + +export type BatchUpdateResponse = [ + number[], + spannerClient.spanner.v1.ExecuteBatchDmlResponse, +]; +export type BeginResponse = [spannerClient.spanner.v1.ITransaction]; + +export type BeginTransactionCallback = + NormalCallback; +export type CommitResponse = [spannerClient.spanner.v1.ICommitResponse]; + +export type ReadResponse = [Rows]; +export type RunResponse = [ + Rows, + spannerClient.spanner.v1.ResultSetStats, + spannerClient.spanner.v1.ResultSetMetadata, +]; +export type RunUpdateResponse = [number]; + +export interface BatchUpdateOptions { + requestOptions?: Omit; + gaxOptions?: CallOptions; +} +export interface BatchUpdateCallback { + ( + err: null | BatchUpdateError, + rowCounts: number[], + response?: spannerClient.spanner.v1.ExecuteBatchDmlResponse, + ): void; +} +export interface BatchUpdateOptions { + requestOptions?: Omit; + gaxOptions?: CallOptions; +} + +export type ReadCallback = NormalCallback; + +export interface RunCallback { + ( + err: null | grpc.ServiceError, + rows: Rows, + stats: spannerClient.spanner.v1.ResultSetStats, + metadata?: spannerClient.spanner.v1.ResultSetMetadata, + ): void; +} + +export interface RunUpdateCallback { + (err: null | grpc.ServiceError, rowCount: number): void; +} + +export type CommitCallback = + NormalCallback; + +type PrecommitTokenProvider = + | spannerClient.spanner.v1.ITransaction + | spannerClient.spanner.v1.IPartialResultSet + | spannerClient.spanner.v1.IExecuteBatchDmlResponse + | spannerClient.spanner.v1.ICommitResponse; + +/** + * @typedef {object} TimestampBounds + * @property {boolean} [strong=true] Read at a timestamp where all previously + * committed transactions are visible. + * @property {external:PreciseDate|google.protobuf.Timestamp} [minReadTimestamp] + * Executes all reads at a `timestamp >= minReadTimestamp`. + * @property {number|google.protobuf.Timestamp} [maxStaleness] Read data at a + * `timestamp >= NOW - maxStaleness` (milliseconds). + * @property {external:PreciseDate|google.protobuf.Timestamp} [readTimestamp] + * Executes all reads at the given timestamp. + * @property {number|google.protobuf.Timestamp} [exactStaleness] Executes all + * reads at a timestamp that is `exactStaleness` (milliseconds) old. + * @property {boolean} [returnReadTimestamp=true] When true, + * {@link Snapshot#readTimestamp} will be populated after + * {@link Snapshot#begin} is called. + */ +/** + * This transaction type provides guaranteed consistency across several reads, + * but does not allow writes. Snapshot read-only transactions can be configured + * to read at timestamps in the past. + * + * When finished with the Snapshot, call {@link Snapshot#end} to + * release the underlying {@link Session}. Failure to do so can result in a + * Session leak. + * + * **This object is created and returned from {@link Database#getSnapshot}.** + * + * @class + * @hideconstructor + * + * @see [Timestamp Bounds API Documentation](https://cloud.google.com/spanner/docs/timestamp-bounds) + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const timestampBounds = { + * strong: true + * }; + * + * database.getSnapshot(timestampBounds, (err, transaction) => { + * if (err) { + * // Error handling omitted. + * } + * + * // It should be called when the snapshot finishes. + * transaction.end(); + * }); + * ``` + */ +export class Snapshot extends EventEmitter { + protected _options!: spannerClient.spanner.v1.ITransactionOptions; + protected _seqno = 1; + protected _waitingRequests: Array<() => void>; + protected _inlineBeginStarted; + protected _useInRunner = false; + protected _latestPreCommitToken: + | spannerClient.spanner.v1.IMultiplexedSessionPrecommitToken + | undefined + | null; + id?: Uint8Array | string; + multiplexedSessionPreviousTransactionId?: Uint8Array | string; + ended: boolean; + metadata?: spannerClient.spanner.v1.ITransaction; + readTimestamp?: PreciseDate; + readTimestampProto?: spannerClient.protobuf.ITimestamp; + request: (config: {}, callback: Function) => void; + requestStream: (config: {}) => Readable; + session: Session; + queryOptions?: IQueryOptions; + commonHeaders_: {[k: string]: string}; + requestOptions?: Pick; + _observabilityOptions?: ObservabilityOptions; + _traceConfig: traceConfig; + protected _dbName?: string; + protected _mutationKey: spannerClient.spanner.v1.Mutation | null; + + /** + * The transaction ID. + * + * @name Snapshot#id + * @type {?(string|Buffer)} + */ + /** + * Whether or not the transaction has ended. If true, make no further + * requests, and discard the transaction. + * + * @name Snapshot#ended + * @type {boolean} + */ + /** + * The raw transaction response object. It is populated after + * {@link Snapshot#begin} is called. + * + * @name Snapshot#metadata + * @type {?TransactionResponse} + */ + /** + * **Snapshot only** + * The timestamp at which all reads are performed. + * + * @name Snapshot#readTimestamp + * @type {?external:PreciseDate} + */ + /** + * **Snapshot only** + * The protobuf version of {@link Snapshot#readTimestamp}. This is useful if + * you require microsecond precision. + * + * @name Snapshot#readTimestampProto + * @type {?google.protobuf.Timestamp} + */ + /** + * @constructor + * + * @param {Session} session The parent Session object. + * @param {TimestampBounds} [options] Snapshot timestamp bounds. + * @param {QueryOptions} [queryOptions] Default query options to use when none + * are specified for a query. + */ + constructor( + session: Session, + options?: TimestampBounds, + queryOptions?: IQueryOptions, + ) { + super(); + + this.ended = false; + this.session = session; + this.queryOptions = Object.assign({}, queryOptions); + this.request = session.request.bind(session); + this.requestStream = session.requestStream.bind(session); + + const readOnly = Snapshot.encodeTimestampBounds(options || {}); + this._options = {readOnly}; + this._dbName = (this.session.parent as Database).formattedName_; + this._waitingRequests = []; + this._inlineBeginStarted = false; + this._observabilityOptions = session._observabilityOptions; + this.commonHeaders_ = getCommonHeaders( + this._dbName, + this._observabilityOptions?.enableEndToEndTracing, + ); + this._traceConfig = { + opts: this._observabilityOptions, + dbName: this._dbName, + }; + this._latestPreCommitToken = null; + this._mutationKey = null; + } + + protected _updatePrecommitToken(resp: PrecommitTokenProvider): void { + if ( + this._latestPreCommitToken === null || + this._latestPreCommitToken === undefined || + (resp.precommitToken && + this._latestPreCommitToken!.seqNum! < resp.precommitToken!.seqNum!) + ) { + this._latestPreCommitToken = resp.precommitToken; + } + } + + /** + * Selects a single representative mutation from a list to be used as the + * transaction's `mutationKey`. + * + * This key is required by Spanner and is sent in the `BeginTransactionRequest` + * for read-write transactions that only contain mutations. The selection follows + * a two-tiered heuristic to choose the most significant mutation. + * + * The selection heuristic is as follows: + * + * 1. Priority of Operation Type: High-priority mutations (`delete`, `update`, + * `replace`, `insertOrUpdate`) are always chosen over low-priority + * (`insert`) mutations. + * + * 2. Selection Strategy: + * - If any high-priority mutations exist, one is chosen randomly from + * that group, ignoring the number of rows. + * - If only `insert` mutations exist, the one(s) with the largest number + * of rows are identified, and one is chosen randomly from that subset. + * + * @protected + * @param mutations The list of mutations from which to select the key. + */ + protected _setMutationKey(mutations: spannerClient.spanner.v1.Mutation[]) { + // return if the list is empty + if (mutations.length === 0) { + return; + } + + // maintain a set of high priority keys + const HIGH_PRIORITY_KEYS = new Set([ + 'delete', + 'update', + 'replace', + 'insertOrUpdate', + ]); + + // maintain a variable for low priority key + const LOW_PRIORITY_KEY = 'insert'; + + // Partition mutations into high and low priority groups. + const [highPriority, lowPriority] = mutations.reduce( + (acc, mutation) => { + const key = Object.keys(mutation)[0] as keyof typeof mutation; + if (HIGH_PRIORITY_KEYS.has(key)) { + acc[0].push(mutation); + } else if (key === LOW_PRIORITY_KEY) { + acc[1].push(mutation); + } + // return accumulated mutations list + return acc; + }, + [[], []] as [ + spannerClient.spanner.v1.Mutation[], + spannerClient.spanner.v1.Mutation[], + ], + ); + + // Apply the selection logic based on the rules. + if (highPriority.length > 0) { + // RULE 1: If high-priority keys exist, pick one randomly. + const randomIndex = Math.floor(Math.random() * highPriority.length); + this._mutationKey = highPriority[randomIndex]; + } else if (lowPriority.length > 0) { + // RULE 2: If only 'insert' key(s) exist, find the one with + // highest number of values + const {bestCandidates} = lowPriority.reduce( + (acc, mutation) => { + const size = mutation.insert?.values?.length || 0; + + if (size > acc.maxSize) { + // New largest size found, start a new list + return {maxSize: size, bestCandidates: [mutation]}; + } + if (size === acc.maxSize) { + // Same size as current max, add to list + acc.bestCandidates.push(mutation); + } + // return accumulated mutations list + return acc; + }, + { + maxSize: -1, + bestCandidates: [] as spannerClient.spanner.v1.Mutation[], + }, + ); + + // Pick randomly from the largest 'insert' mutation(s). + const randomIndex = Math.floor(Math.random() * bestCandidates.length); + this._mutationKey = bestCandidates[randomIndex]; + } else { + // No mutations to select from. + this._mutationKey = null; + } + } + + /** + * Modifies transaction selector to include the multiplexed session previous + * transaction id. + * This is essential for operations that use an `inline begin`. + * @protected + * @param transaction The transaction selector object that will be mutated + * to include the multiplexed session previous transaction id. + */ + protected _setPreviousTransactionId( + transaction: spannerClient.spanner.v1.ITransactionSelector, + ): void { + transaction.begin!.readWrite! = Object.assign( + {}, + transaction.begin!.readWrite! || {}, + { + multiplexedSessionPreviousTransactionId: + this.multiplexedSessionPreviousTransactionId, + }, + ); + } + + /** + * @typedef {object} TransactionResponse + * @property {string|Buffer} id The transaction ID. + * @property {?google.protobuf.Timestamp} readTimestamp For snapshot read-only + * transactions, the read timestamp chosen for the transaction. + */ + /** + * @typedef {array} TransactionBeginResponse + * @property {TransactionResponse} 0 The raw transaction object. + */ + /** + * @callback TransactionBeginCallback + * @param {?Error} err Request error, if any. + * @param {TransactionResponse} apiResponse The raw transaction object. + */ + /** + * Begin a new transaction. Typically, you need not call this unless + * manually creating transactions via {@link Session} objects. + * + * @see [BeginTransaction API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.BeginTransaction) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {TransactionBeginCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * transaction.begin(function(err) { + * if (!err) { + * // transaction began successfully. + * } + * }); + * + * ``` + * @example If the callback is omitted, the function returns a Promise + * ``` + * transaction.begin() + * .then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + begin(gaxOptions?: CallOptions): Promise; + begin(callback: BeginTransactionCallback): void; + begin(gaxOptions: CallOptions, callback: BeginTransactionCallback): void; + begin( + gaxOptionsOrCallback?: CallOptions | BeginTransactionCallback, + cb?: BeginTransactionCallback, + ): void | Promise { + const gaxOpts = + typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; + const callback = + typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; + + const session = this.session.formattedName_!; + const options = this._options; + if ( + this.multiplexedSessionPreviousTransactionId && + (this.session.parent as Database).isMuxEnabledForRW_ + ) { + options.readWrite!.multiplexedSessionPreviousTransactionId = + this.multiplexedSessionPreviousTransactionId; + } + const reqOpts: spannerClient.spanner.v1.IBeginTransactionRequest = { + session, + options, + }; + + if (this._mutationKey) { + reqOpts.mutationKey = this._mutationKey; + } + + // Only hand crafted read-write transactions will be able to set a + // transaction tag for the BeginTransaction RPC. Also, this.requestOptions + // is only set in the constructor of Transaction, which is the constructor + // for read/write transactions. + if (this.requestOptions) { + reqOpts.requestOptions = this.requestOptions; + } + + const headers = this.commonHeaders_; + if ( + this._getSpanner().routeToLeaderEnabled && + (this._options.readWrite !== undefined || + this._options.partitionedDml !== undefined) + ) { + addLeaderAwareRoutingHeader(headers); + } + + return startTrace( + 'Snapshot.begin', + { + transactionTag: this.requestOptions?.transactionTag, + ...this._traceConfig, + }, + span => { + span.addEvent('Begin Transaction'); + + this.request( + { + client: 'SpannerClient', + method: 'beginTransaction', + reqOpts, + gaxOpts, + headers: injectRequestIDIntoHeaders(headers, this.session), + }, + ( + err: null | grpc.ServiceError, + resp: spannerClient.spanner.v1.ITransaction, + ) => { + if (err) { + setSpanError(span, err); + } else { + this._updatePrecommitToken(resp); + this._update(resp, span); + } + span.end(); + callback!(err, resp); + }, + ); + }, + ); + } + + /** + * A KeyRange represents a range of rows in a table or index. + * + * A range has a start key and an end key. These keys can be open or closed, + * indicating if the range includes rows with that key. + * + * Keys are represented by an array of strings where the nth value in the list + * corresponds to the nth component of the table or index primary key. + * + * @typedef {object} KeyRange + * @property {string[]} [startClosed] If the start is closed, then the range + * includes all rows whose first key columns exactly match. + * @property {string[]} [startOpen] If the start is open, then the range + * excludes rows whose first key columns exactly match. + * @property {string[]} [endClosed] If the end is closed, then the range + * includes all rows whose first key columns exactly match. + * @property {string[]} [endOpen] If the end is open, then the range excludes + * rows whose first key columns exactly match. + */ + /** + * Read request options. This includes all standard ReadRequest options as + * well as several convenience properties. + * + * @see [StreamingRead API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.StreamingRead) + * @see [ReadRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest) + * + * @typedef {object} ReadRequest + * @property {string} table The name of the table in the database to be read. + * @property {string[]} columns The columns of the table to be returned for each + * row matching this query. + * @property {string[]|string[][]} keys The primary or index keys of the rows in this table to be + * yielded. If using a composite key, provide an array within this array. + * See the example below. + * @property {KeyRange[]} [ranges] An alternative to the keys property; this can + * be used to define a range of keys to be yielded. + * @property {string} [index] The name of an index on the table if a + * different index than the primary key should be used to determine which rows to return. + * @property {boolean} [json=false] Receive the rows as serialized objects. This + * is the equivalent of calling `toJSON()` on each row. + * @property {JSONOptions} [jsonOptions] Configuration options for the serialized + * objects. + * @property {object} [keySet] Defines a collection of keys and/or key ranges to + * read. + * @property {number} [limit] The number of rows to yield. + * @property {Buffer} [partitionToken] + * If present, results will be restricted to the specified partition + * previously created using PartitionRead(). There must be an exact + * match for the values of fields common to this message and the + * PartitionReadRequest message used to create this partition_token. + * @property {google.spanner.v1.RequestOptions} [requestOptions] + * Common options for this request. + * @property {google.spanner.v1.IDirectedReadOptions} [directedReadOptions] + * Indicates which replicas or regions should be used for non-transactional reads or queries. + * @property {object} [gaxOptions] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * Create a readable object stream to receive rows from the database using key + * lookups and scans. + * + * Wrapper around {@link v1.SpannerClient#streamingRead}. + * + * @see {@link v1.SpannerClient#streamingRead} + * @see [StreamingRead API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.StreamingRead) + * @see [ReadRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest) + * + * @fires PartialResultStream#response + * @fires PartialResultStream#stats + * + * @param {string} table The table to read from. + * @param {ReadRequest} query Configuration object. See official + * [`ReadRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest). + * API documentation. + * @returns {ReadableStream} A readable stream that emits rows. + * + * @example + * ``` + * transaction.createReadStream('Singers', { + * keys: ['1'], + * columns: ['SingerId', 'name'] + * }) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row = [ + * // { + * // name: 'SingerId', + * // value: '1' + * // }, + * // { + * // name: 'Name', + * // value: 'Eddie Wilson' + * // } + * // ] + * }) + * .on('end', function() { + * // All results retrieved. + * }); + * + * ``` + * @example Provide an array for `query.keys` to read with a + * composite key. + * ``` + * const query = { + * keys: [ + * [ + * 'Id1', + * 'Name1' + * ], + * [ + * 'Id2', + * 'Name2' + * ] + * ], + * // ... + * }; + * ``` + * + * @example Rows are returned as an array of object arrays. Each + * object has a `name` and `value` property. To get a serialized object, call + * `toJSON()`. + * ``` + * transaction.createReadStream('Singers', { + * keys: ['1'], + * columns: ['SingerId', 'name'] + * }) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row.toJSON() = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }) + * .on('end', function() { + * // All results retrieved. + * }); + * ``` + * + * @example Alternatively, set `query.json` to `true`, and this step + * will perform automatically. + * ``` + * transaction.createReadStream('Singers', { + * keys: ['1'], + * columns: ['SingerId', 'name'], + * json: true, + * }) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }) + * .on('end', function() { + * // All results retrieved. + * }); + * ``` + * + * @example If you anticipate many results, you can end a stream + * early to prevent unnecessary processing and API requests. + * ``` + * transaction.createReadStream('Singers', { + * keys: ['1'], + * columns: ['SingerId', 'name'] + * }) + * .on('data', function(row) { + * this.end(); + * }); + * ``` + */ + createReadStream( + table: string, + request = {} as ReadRequest, + ): PartialResultStream { + const { + gaxOptions, + json, + jsonOptions, + maxResumeRetries, + requestOptions, + columnsMetadata, + } = request; + const keySet = Snapshot.encodeKeySet(request); + const transaction: spannerClient.spanner.v1.ITransactionSelector = {}; + + if (this.id) { + transaction.id = this.id as Uint8Array; + } else if (this._options.readWrite) { + transaction.begin = this._options; + } else { + transaction.singleUse = this._options; + } + + if ( + !this.id && + this._options.readWrite && + (this.session.parent as Database).isMuxEnabledForRW_ + ) { + this._setPreviousTransactionId(transaction); + } + + const directedReadOptions = this._getDirectedReadOptions( + request.directedReadOptions, + ); + + request = Object.assign({}, request); + + delete request.gaxOptions; + delete request.json; + delete request.jsonOptions; + delete request.maxResumeRetries; + delete request.keys; + delete request.ranges; + delete request.requestOptions; + delete request.directedReadOptions; + delete request.columnsMetadata; + + const reqOpts: spannerClient.spanner.v1.IReadRequest = Object.assign( + request, + { + session: this.session.formattedName_!, + requestOptions: this.configureTagOptions( + typeof transaction.singleUse !== 'undefined', + this.requestOptions?.transactionTag ?? undefined, + requestOptions, + ), + directedReadOptions: directedReadOptions, + transaction, + table, + keySet, + }, + ); + + const headers = this.commonHeaders_; + if ( + this._getSpanner().routeToLeaderEnabled && + (this._options.readWrite !== undefined || + this._options.partitionedDml !== undefined) + ) { + addLeaderAwareRoutingHeader(headers); + } + + const traceConfig: traceConfig = { + ...this._traceConfig, + tableName: table, + transactionTag: this.requestOptions?.transactionTag, + requestTag: requestOptions?.requestTag, + }; + + return startTrace('Snapshot.createReadStream', traceConfig, span => { + let attempt = 0; + const database = this.session.parent as Database; + const nthRequest = nextNthRequest(database); + const makeRequest = (resumeToken?: ResumeToken): Readable => { + if (this.id && transaction.begin) { + delete transaction.begin; + transaction.id = this.id; + } + + attempt++; + + if (!resumeToken) { + if (attempt === 1) { + span.addEvent('Starting stream'); + } else { + span.addEvent('Re-attempting start stream', {attempt: attempt}); + } + } else { + span.addEvent('Resuming stream', { + resume_token: resumeToken!.toString(), + attempt: attempt, + }); + } + + return this.requestStream({ + client: 'SpannerClient', + method: 'streamingRead', + reqOpts: Object.assign({}, reqOpts, {resumeToken}), + gaxOpts: gaxOptions, + headers: injectRequestIDIntoHeaders( + headers, + this.session, + nthRequest, + attempt, + ), + }); + }; + + const resultStream = partialResultStream( + this._wrapWithIdWaiter(makeRequest), + { + json, + jsonOptions, + maxResumeRetries, + columnsMetadata, + gaxOptions, + }, + ) + ?.on('response', response => { + this._updatePrecommitToken(response); + if (response.metadata && response.metadata!.transaction && !this.id) { + this._update(response.metadata!.transaction, span); + } + }) + .on('error', err => { + setSpanError(span, err); + const wasAborted = isErrorAborted(err); + if (!this.id && this._useInRunner && !wasAborted) { + // TODO: resolve https://github.com/googleapis/nodejs-spanner/issues/2170 + void this.begin(); + } else { + if (wasAborted) { + span.addEvent('Stream broken. Not safe to retry', { + 'transaction.id': this.id?.toString(), + }); + } + } + span.end(); + }) + .on('end', err => { + if (err) { + setSpanError(span, err); + } + span.end(); + }); + + if (resultStream instanceof Stream) { + finished(resultStream, err => { + if (err) { + setSpanError(span, err); + } + span.end(); + }); + } + + return resultStream; + }); + } + + /** + * Let the client know you're done with a particular transaction. This should + * mainly be called for {@link Snapshot} objects, however in certain cases + * you may want to call them for {@link Transaction} objects as well. + * + * @example Calling `end` on a read only snapshot + * ``` + * database.getSnapshot((err, transaction) => { + * if (err) { + * // Error handling omitted. + * } + * + * transaction.run('SELECT * FROM Singers', (err, rows) => { + * if (err) { + * // Error handling omitted. + * } + * + * // End the snapshot. + * transaction.end(); + * }); + * }); + * ``` + * + * @example Calling `end` on a read/write transaction + * ``` + * database.runTransaction((err, transaction) => { + * if (err) { + * // Error handling omitted. + * } + * + * const query = 'UPDATE Account SET Balance = 1000 WHERE Key = 1'; + * + * transaction.runUpdate(query, err => { + * if (err) { + * // In the event of an error, there would be nothing to rollback, + * so + * // instead of continuing, discard the + * transaction. transaction.end(); return; + * } + * + * transaction.commit(err => {}); + * }); + * }); + * ``` + */ + end(): void { + if (this.ended) { + return; + } + + this.ended = true; + process.nextTick(() => this.emit('end')); + } + + /** + * @typedef {array} ReadResponse + * @property {array[]} 0 Rows are returned as an array of object arrays. Each + * object has a `name` and `value` property. To get a serialized object, + * call `toJSON()`. Optionally, provide an options object to `toJSON()` + * specifying `wrapNumbers: true` to protect large integer values outside + * of the range of JavaScript Number. If set, FLOAT64 values are returned + * as {@link Spanner.Float} objects and INT64 values as {@link + * Spanner.Int}. + */ + /** + * @callback ReadCallback + * @param {?Error} err Request error, if any. + * @param {array[]} rows Rows are returned as an array of object arrays. Each + * object has a `name` and `value` property. To get a serialized object, + * call `toJSON()`. Optionally, provide an options object to `toJSON()` + * specifying `wrapNumbers: true` to protect large integer values outside + * of the range of JavaScript Number. If set, FLOAT64 values are returned + * as {@link Spanner.Float} objects and INT64 values as {@link + * Spanner.Int}. + */ + /** + * Performs a read request against the specified Table. + * + * Wrapper around {@link v1.SpannerClient#read}. + * + * @see {@link v1.SpannerClient#read} + * + * @param {string} table The table to read from. + * @param {ReadRequest} query Configuration object. See official + * [`ReadRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ReadRequest). + * API documentation. + * @param {ReadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const query = { + * keys: ['1'], + * columns: ['SingerId', 'name'] + * }; + * + * transaction.read('Singers', query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * const firstRow = rows[0]; + * + * // firstRow = [ + * // { + * // name: 'SingerId', + * // value: '1' + * // }, + * // { + * // name: 'Name', + * // value: 'Eddie Wilson' + * // } + * // ] + * }); + * + * ``` + * @example Provide an array for `query.keys` to read with a + * composite key. + * ``` + * const query = { + * keys: [ + * [ + * 'Id1', + * 'Name1' + * ], + * [ + * 'Id2', + * 'Name2' + * ] + * ], + * // ... + * }; + * ``` + * + * @example Rows are returned as an array of object arrays. Each + * object has a `name` and `value` property. To get a serialized object, call + * `toJSON()`. + * ``` + * transaction.read('Singers', query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * const firstRow = rows[0]; + * + * // firstRow.toJSON() = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }); + * ``` + * + * @example Alternatively, set `query.json` to `true`, and this step + * will perform automatically. + * ``` + * query.json = true; + * + * transaction.read('Singers', query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * const firstRow = rows[0]; + * + * // firstRow = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }); + * ``` + */ + read(table: string, request: ReadRequest): Promise; + read(table: string, callback: ReadCallback): void; + read(table: string, request: ReadRequest, callback: ReadCallback): void; + read( + table: string, + requestOrCallback: ReadRequest | ReadCallback, + cb?: ReadCallback, + ): void | Promise { + const rows: Rows = []; + + let request: ReadRequest; + let callback: ReadCallback; + + if (typeof requestOrCallback === 'function') { + request = {} as RequestOptions; + callback = requestOrCallback as ReadCallback; + } else { + request = requestOrCallback as RequestOptions; + callback = cb as ReadCallback; + } + + return startTrace( + 'Snapshot.read', + { + tableName: table, + ...this._traceConfig, + }, + span => { + this.createReadStream(table, request) + .on('error', err => { + const e = err as grpc.ServiceError; + setSpanError(span, e); + span.end(); + callback!(e, null); + }) + .on('data', row => rows.push(row)) + .on('end', () => { + span.end(); + callback!(null, rows); + }); + }, + ); + } + + /** + * Execute a SQL statement on this database inside of a transaction. + * + * **Performance Considerations:** + * + * This method wraps the streaming method, + * {@link Snapshot#run} for your convenience. All rows are stored in memory + * before releasing to your callback. If you intend to receive a lot of + * results from your query, consider using the streaming method, + * so you can free each result from memory after consuming it. + * + * Wrapper around {@link v1.SpannerClient#executeStreamingSql}. + * + * @see {@link v1.SpannerClient#executeStreamingSql} + * @see [ExecuteStreamingSql API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ExecuteStreamingSql) + * @see [ExecuteSqlRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest) + * + * @param {string|ExecuteSqlRequest} query A SQL query or + * {@link ExecuteSqlRequest} object. + * @param {RunCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * transaction.run(query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * + * // rows = [ + * // { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * // ] + * }); + * + * ``` + * @example The SQL query string can contain parameter placeholders. + * A parameter placeholder consists of '@' followed by the parameter name. + * ``` + * const query = { + * sql: 'SELECT * FROM Singers WHERE name = @name', + * params: { + * name: 'Eddie Wilson' + * } + * }; + * + * transaction.run(query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * }); + * ``` + * + * @example If you need to enforce a specific param type, a types map + * can be provided. This is typically useful if your param value can be null. + * ``` + * const query = { + * sql: 'SELECT * FROM Singers WHERE name = @name AND id = @id', + * params: { + * id: spanner.int(8), + * name: null + * }, + * types: { + * id: 'int64', + * name: 'string' + * } + * }; + * + * transaction.run(query, function(err, rows) { + * if (err) { + * // Error handling omitted. + * } + * }); + * ``` + */ + run(query: string | ExecuteSqlRequest): Promise; + run(query: string | ExecuteSqlRequest, callback: RunCallback): void; + run( + query: string | ExecuteSqlRequest, + callback?: RunCallback, + ): void | Promise { + const rows: Rows = []; + let stats: google.spanner.v1.ResultSetStats; + let metadata: google.spanner.v1.ResultSetMetadata; + + startTrace( + 'Snapshot.run', + { + ...(query as ExecuteSqlRequest), + ...this._traceConfig, + }, + span => { + return this.runStream(query) + .on('error', err => { + setSpanError(span, err); + span.end(); + if (!('code' in err)) { + Object.assign(err, { + code: grpc.status.UNKNOWN, + details: err.message, + metadata: new grpc.Metadata(), + }); + } + callback!(err as ServiceError, rows, stats, metadata); + }) + .on('response', response => { + if (response.metadata) { + metadata = response.metadata; + if (metadata.transaction && !this.id) { + this._update(metadata.transaction, span); + } + } + }) + .on('data', row => rows.push(row)) + .on('stats', _stats => (stats = _stats)) + .on('end', () => { + span.end(); + callback!(null, rows, stats, metadata); + }); + }, + ); + } + + /** + * ExecuteSql request options. This includes all standard ExecuteSqlRequest + * options as well as several convenience properties. + * + * @see [Query Syntax](https://cloud.google.com/spanner/docs/query-syntax) + * @see [ExecuteSql API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ExecuteSql) + * + * @typedef {object} ExecuteSqlRequest + * @property {string} resumeToken The token used to resume getting results. + * @property {google.spanner.v1.ExecuteSqlRequest.QueryMode} queryMode Query plan and + * execution statistics for the SQL statement that + * produced this result set. + * @property {string} partitionToken The partition token. + * @property {number} seqno The Sequence number. This option is used internally and will be overridden. + * @property {string} sql The SQL string. + * @property {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions] + * Default query options to use with the database. These options will be + * overridden by any query options set in environment variables or that + * are specified on a per-query basis. + * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include + * with the commit request. + * @property {Object.} [params] A map of parameter names to values. + * @property {Object.} [types] A map of parameter + * names to types. If omitted the client will attempt to guess for all + * non-null values. + * @property {boolean} [json=false] Receive the rows as serialized objects. This + * is the equivalent of calling `toJSON()` on each row. + * @property {JSONOptions} [jsonOptions] Configuration options for the + * serialized objects. + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @property {number} [maxResumeRetries] The maximum number of times that the + * stream will retry to push data downstream, when the downstream indicates + * that it is not ready for any more data. Increase this value if you + * experience 'Stream is still not ready to receive data' errors as a + * result of a slow writer in your receiving stream. + * @property {object} [directedReadOptions] + * Indicates which replicas or regions should be used for non-transactional reads or queries. + */ + /** + * Create a readable object stream to receive resulting rows from a SQL + * statement. + * + * Wrapper around {@link v1.SpannerClient#executeStreamingSql}. + * + * @see {@link v1.SpannerClient#executeStreamingSql} + * @see [ExecuteStreamingSql API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ExecuteStreamingSql) + * @see [ExecuteSqlRequest API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest) + * + * @fires PartialResultStream#response + * @fires PartialResultStream#stats + * + * @param {string|ExecuteSqlRequest} query A SQL query or + * {@link ExecuteSqlRequest} object. + * @returns {ReadableStream} + * + * @example + * ``` + * const query = 'SELECT * FROM Singers'; + * + * transaction.runStream(query) + * .on('error', function(err) {}) + * .on('data', function(row) { + * // row = { + * // SingerId: '1', + * // Name: 'Eddie Wilson' + * // } + * }) + * .on('end', function() { + * // All results retrieved. + * }); + * + * ``` + * @example The SQL query string can contain parameter placeholders. + * A parameter placeholder consists of '@' followed by the parameter name. + * ``` + * const query = { + * sql: 'SELECT * FROM Singers WHERE name = @name', + * params: { + * name: 'Eddie Wilson' + * } + * }; + * + * transaction.runStream(query) + * .on('error', function(err) {}) + * .on('data', function(row) {}) + * .on('end', function() {}); + * ``` + * + * @example If you anticipate many results, you can end a stream + * early to prevent unnecessary processing and API requests. + * ``` + * transaction.runStream(query) + * .on('data', function(row) { + * this.end(); + * }); + * ``` + */ + runStream(query: string | ExecuteSqlRequest): PartialResultStream { + if (typeof query === 'string') { + query = {sql: query} as ExecuteSqlRequest; + } + + query = Object.assign({}, query) as ExecuteSqlRequest; + query.queryOptions = Object.assign( + Object.assign({}, this.queryOptions), + query.queryOptions, + ); + + const { + gaxOptions, + json, + jsonOptions, + maxResumeRetries, + requestOptions, + columnsMetadata, + } = query; + let reqOpts; + + const directedReadOptions = this._getDirectedReadOptions( + query.directedReadOptions, + ); + + const sanitizeRequest = () => { + query = query as ExecuteSqlRequest; + const {params, paramTypes} = Snapshot.encodeParams(query); + const transaction: spannerClient.spanner.v1.ITransactionSelector = {}; + if (this.id) { + transaction.id = this.id as Uint8Array; + } else if (this._options.readWrite) { + transaction.begin = this._options; + } else { + transaction.singleUse = this._options; + } + + if ( + !this.id && + this._options.readWrite && + (this.session.parent as Database).isMuxEnabledForRW_ + ) { + this._setPreviousTransactionId(transaction); + } + delete query.gaxOptions; + delete query.json; + delete query.jsonOptions; + delete query.maxResumeRetries; + delete query.requestOptions; + delete query.types; + delete query.directedReadOptions; + delete query.columnsMetadata; + + reqOpts = Object.assign(query, { + session: this.session.formattedName_!, + seqno: this._seqno++, + requestOptions: this.configureTagOptions( + typeof transaction.singleUse !== 'undefined', + this.requestOptions?.transactionTag ?? undefined, + requestOptions, + ), + directedReadOptions: directedReadOptions, + transaction, + params, + paramTypes, + }); + }; + + const headers = this.commonHeaders_; + if ( + this._getSpanner().routeToLeaderEnabled && + (this._options.readWrite !== undefined || + this._options.partitionedDml !== undefined) + ) { + addLeaderAwareRoutingHeader(headers); + } + + const traceConfig: traceConfig = { + transactionTag: this.requestOptions?.transactionTag, + requestTag: requestOptions?.requestTag, + ...query, + ...this._traceConfig, + }; + return startTrace('Snapshot.runStream', traceConfig, span => { + let attempt = 0; + const database = this.session.parent as Database; + const nthRequest = nextNthRequest(database); + const makeRequest = (resumeToken?: ResumeToken): Readable => { + attempt++; + + if (!resumeToken) { + if (attempt === 1) { + span.addEvent('Starting stream'); + } else { + span.addEvent('Re-attempting start stream', {attempt: attempt}); + } + } else { + span.addEvent('Resuming stream', { + resume_token: resumeToken!.toString(), + attempt: attempt, + }); + } + + if (!reqOpts || (this.id && !reqOpts.transaction.id)) { + try { + sanitizeRequest(); + } catch (e) { + const errorStream = new PassThrough(); + setSpanErrorAndException(span, e as Error); + span.end(); + setImmediate(() => errorStream.destroy(e as Error)); + return errorStream; + } + } + + return this.requestStream({ + client: 'SpannerClient', + method: 'executeStreamingSql', + reqOpts: Object.assign({}, reqOpts, {resumeToken}), + gaxOpts: gaxOptions, + headers: injectRequestIDIntoHeaders( + headers, + this.session, + nthRequest, + attempt, + ), + }); + }; + + const resultStream = partialResultStream( + this._wrapWithIdWaiter(makeRequest), + { + json, + jsonOptions, + maxResumeRetries, + columnsMetadata, + gaxOptions, + }, + ) + .on('response', response => { + this._updatePrecommitToken(response); + if (response.metadata && response.metadata!.transaction && !this.id) { + this._update(response.metadata!.transaction, span); + } + }) + .on('error', err => { + setSpanError(span, err as Error); + const wasAborted = isErrorAborted(err); + if (!this.id && this._useInRunner && !wasAborted) { + span.addEvent('Stream broken. Safe to retry'); + // TODO: resolve https://github.com/googleapis/nodejs-spanner/issues/2170 + void this.begin(); + } else { + if (wasAborted) { + span.addEvent('Stream broken. Not safe to retry', { + 'transaction.id': this.id?.toString(), + }); + } + } + span.end(); + }) + .on('end', err => { + if (err) { + setSpanError(span, err as Error); + } + span.end(); + }); + + if (resultStream instanceof Stream) { + finished(resultStream, err => { + if (err) { + setSpanError(span, err); + } + span.end(); + }); + } + + return resultStream; + }); + } + + /** + * + * @private + */ + configureTagOptions( + singleUse?: boolean, + transactionTag?: string, + requestOptions = {}, + ): IRequestOptions | null { + if (!singleUse && transactionTag) { + (requestOptions as IRequestOptions).transactionTag = transactionTag; + } + + return requestOptions!; + } + + /** + * Transforms convenience options `keys` and `ranges` into a KeySet object. + * + * @private + * @static + * + * @param {ReadRequest} request The read request. + * @returns {object} + */ + static encodeKeySet(request: ReadRequest): spannerClient.spanner.v1.IKeySet { + const keySet: spannerClient.spanner.v1.IKeySet = request.keySet || {}; + + if (request.keys) { + keySet.keys = toArray(request.keys as string[]).map( + codec.convertToListValue, + ); + } + + if (request.ranges) { + keySet.ranges = toArray(request.ranges).map(range => { + const encodedRange: spannerClient.spanner.v1.IKeyRange = {}; + + Object.keys(range).forEach(bound => { + encodedRange[bound] = codec.convertToListValue(range[bound]); + }); + + return encodedRange; + }); + } + + if (isEmpty(keySet)) { + keySet.all = true; + } + + return keySet; + } + + /** + * Formats timestamp options into proto format. + * + * @private + * @static + * + * @param {TimestampBounds} options The user supplied options. + * @returns {object} + */ + static encodeTimestampBounds( + options: TimestampBounds, + ): spannerClient.spanner.v1.TransactionOptions.IReadOnly { + const readOnly: spannerClient.spanner.v1.TransactionOptions.IReadOnly = {}; + const {returnReadTimestamp = true} = options; + + if (options.minReadTimestamp instanceof PreciseDate) { + readOnly.minReadTimestamp = ( + options.minReadTimestamp as PreciseDate + ).toStruct(); + } + + if (options.readTimestamp instanceof PreciseDate) { + readOnly.readTimestamp = ( + options.readTimestamp as PreciseDate + ).toStruct(); + } + + if (typeof options.maxStaleness === 'number') { + readOnly.maxStaleness = codec.convertMsToProtoTimestamp( + options.maxStaleness as number, + ); + } + + if (typeof options.exactStaleness === 'number') { + readOnly.exactStaleness = codec.convertMsToProtoTimestamp( + options.exactStaleness as number, + ); + } + + // If we didn't detect a convenience format, we'll just assume that + // they passed in a protobuf timestamp. + if (isEmpty(readOnly)) { + Object.assign(readOnly, options); + } + + readOnly.returnReadTimestamp = returnReadTimestamp; + return readOnly; + } + + /** + * Encodes convenience options `param` and `types` into the proto formatted. + * + * @private + * @static + * + * @param {ExecuteSqlRequest} request The SQL request. + * @returns {object} + */ + static encodeParams(request: ExecuteSqlRequest) { + const typeMap = request.types || {}; + + const params: p.IStruct = {fields: request.params?.fields || {}}; + const paramTypes: {[field: string]: spannerClient.spanner.v1.Type} = + request.paramTypes || {}; + + if (request.params && !request.params.fields) { + const fields = {}; + + Object.keys(request.params).forEach(param => { + const value = request.params![param]; + + if (!typeMap[param]) { + typeMap[param] = codec.getType(value); + } + fields[param] = codec.encode(value); + }); + + params.fields = fields; + } + + if (!isEmpty(typeMap)) { + Object.keys(typeMap).forEach(param => { + const type = typeMap[param]; + if (process.env['SPANNER_ENABLE_UUID_AS_UNTYPED'] === 'true') { + const typeObject = codec.createTypeObject(type); + if ( + (type.child && + typeObject.code === 'ARRAY' && + typeObject.arrayElementType?.code !== 'TYPE_CODE_UNSPECIFIED') || + (!type.child && typeObject.code !== 'TYPE_CODE_UNSPECIFIED') + ) { + paramTypes[param] = typeObject; + } + } else { + paramTypes[param] = codec.createTypeObject(type); + } + }); + } + + return {params, paramTypes}; + } + + /** + * Get directed read options + * @private + * @param {google.spanner.v1.IDirectedReadOptions} directedReadOptions Request directedReadOptions object. + */ + protected _getDirectedReadOptions( + directedReadOptions: + | google.spanner.v1.IDirectedReadOptions + | null + | undefined, + ) { + if ( + !directedReadOptions && + this._getSpanner().directedReadOptions && + this._options.readOnly + ) { + return this._getSpanner().directedReadOptions; + } + + return directedReadOptions; + } + + /** + * Update transaction properties from the response. + * + * @private + * + * @param {spannerClient.spanner.v1.ITransaction} resp Response object. + */ + protected _update( + resp: spannerClient.spanner.v1.ITransaction, + span: Span, + ): void { + const {id, readTimestamp} = resp; + + this.id = id!; + this.metadata = resp; + + span.addEvent('Transaction Creation Done', {id: this.id.toString()}); + + if (readTimestamp) { + this.readTimestampProto = readTimestamp; + this.readTimestamp = new PreciseDate(readTimestamp as DateStruct); + } + this._releaseWaitingRequests(); + } + + /** + * Wrap `makeRequest` function with the lock to make sure the inline begin + * transaction can happen only once. + * + * @param makeRequest + * @private + */ + private _wrapWithIdWaiter( + makeRequest: (resumeToken?: ResumeToken) => Readable, + ): (resumeToken?: ResumeToken) => Readable { + if (this.id || !this._options.readWrite) { + return makeRequest; + } + if (!this._inlineBeginStarted) { + this._inlineBeginStarted = true; + return makeRequest; + } + + // Queue subsequent requests. + return (resumeToken?: ResumeToken): Readable => { + const streamProxy = new Readable({ + read() {}, + }); + + this._waitingRequests.push(() => { + makeRequest(resumeToken) + .on('data', chunk => streamProxy.emit('data', chunk)) + .on('error', err => streamProxy.emit('error', err)) + .on('end', () => streamProxy.emit('end')); + }); + + return streamProxy; + }; + } + + _releaseWaitingRequests() { + while (this._waitingRequests.length > 0) { + const request = this._waitingRequests.shift(); + request?.(); + } + } + + /** + * Gets the Spanner object + * + * @private + * + * @returns {Spanner} + */ + protected _getSpanner(): Spanner { + return this.session.parent.parent.parent as Spanner; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Snapshot, { + exclude: ['configureTagOptions', 'end'], +}); + +/** + * Never use DML class directly. Instead, it should be extended upon + * if a class requires DML capabilities. + * + * @private + * @class + */ +export class Dml extends Snapshot { + /** + * @typedef {array} RunUpdateResponse + * @property {number} 0 Affected row count. + */ + /** + * @callback RunUpdateCallback + * @param {?Error} err Request error, if any. + * @param {number} rowCount Affected row count. + */ + /** + * Execute a DML statement and get the affected row count. + * + * @private + * + * @see {@link Transaction#run} + * + * @param {string|object} query A DML statement or + * [`ExecuteSqlRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest) + * object. + * @param {object} [query.params] A map of parameter name to values. + * @param {object} [query.types] A map of parameter types. + * @param {RunUpdateCallback} [callback] Callback function. + * @returns {Promise} + */ + runUpdate(query: string | ExecuteSqlRequest): Promise; + runUpdate( + query: string | ExecuteSqlRequest, + callback: RunUpdateCallback, + ): void; + runUpdate( + query: string | ExecuteSqlRequest, + callback?: RunUpdateCallback, + ): void | Promise { + if (typeof query === 'string') { + query = {sql: query} as ExecuteSqlRequest; + } + + return startTrace( + 'Dml.runUpdate', + { + ...query, + ...this._traceConfig, + transactionTag: this.requestOptions?.transactionTag, + requestTag: query.requestOptions?.requestTag, + }, + span => { + this.run( + query, + ( + err: null | grpc.ServiceError, + rows: Rows, + stats: spannerClient.spanner.v1.ResultSetStats, + ) => { + let rowCount = 0; + + if (stats && stats.rowCount) { + rowCount = Math.floor(stats[stats.rowCount] as number); + } + + if (err) { + setSpanError(span, err); + } + + span.end(); + callback!(err, rowCount); + }, + ); + }, + ); + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Dml); + +/** + * This type of transaction is the only way to write data into Cloud Spanner. + * These transactions rely on pessimistic locking and, if necessary, two-phase + * commit. Locking read-write transactions may abort, requiring the application + * to retry. + * + * Calling either {@link Transaction#commit} or {@link Transaction#rollback} + * signals that the transaction is finished and no further requests will be + * made. If for some reason you decide not to call one of the aformentioned + * methods, call {@link Transaction#end} to release the underlying + * {@link Session}. + * + * Running a transaction via {@link Database#runTransaction} or + * {@link Database#runTransactionAsync} automatically re-runs the + * transaction on `ABORTED` errors. + * + * {@link Database#getTransaction} returns a plain {@link Transaction} + * object, requiring the user to retry manually. + * + * @class + * @extends Snapshot + * + * @param {Session} session The parent Session object. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * database.runTransaction(function(err, transaction) { + * // The `transaction` object is ready for use. + * }); + * + * ``` + * @example To manually control retrying the transaction, use the + * `getTransaction` method. + * ``` + * database.getTransaction(function(err, transaction) { + * // The `transaction` object is ready for use. + * }); + * ``` + */ +export class Transaction extends Dml { + commitTimestamp?: PreciseDate; + commitTimestampProto?: spannerClient.protobuf.ITimestamp; + private _queuedMutations: spannerClient.spanner.v1.Mutation[]; + private _retryCommit: Boolean; + + /** + * Timestamp at which the transaction was committed. Will be populated once + * {@link Transaction#commit} is called. + * + * @name Transaction#commitTimestamp + * @type {?external:PreciseDate} + */ + /** + * The protobuf version of {@link Transaction#commitTimestamp}. This is useful + * if you require microsecond precision. + * + * @name Transaction#commitTimestampProto + * @type {?google.protobuf.Timestamp} + */ + /** + * Execute a DML statement and get the affected row count. + * + * @name Transaction#runUpdate + * + * @see {@link Transaction#run} + * + * @param {string|object} query A DML statement or + * [`ExecuteSqlRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest) + * object. + * @param {object} [query.params] A map of parameter name to values. + * @param {object} [query.types] A map of parameter types. + * @param {RunUpdateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const query = 'UPDATE Account SET Balance = 1000 WHERE Key = 1'; + * + * transaction.runUpdate(query, (err, rowCount) => { + * if (err) { + * // Error handling omitted. + * } + * }); + * ``` + */ + constructor( + session: Session, + options = {} as spannerClient.spanner.v1.TransactionOptions.ReadWrite, + queryOptions?: IQueryOptions, + requestOptions?: Pick, + ) { + super(session, undefined, queryOptions); + + this._queuedMutations = []; + this._options = {readWrite: options}; + this._options.isolationLevel = IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED; + this.requestOptions = requestOptions; + this._retryCommit = false; + } + + /** + * @typedef {error} BatchUpdateError + * @property {number} code gRPC status code. + * @property {?object} metadata gRPC metadata. + * @property {number[]} rowCounts The affected row counts for any DML + * statements that were executed successfully before this error occurred. + */ + /** + * @typedef {object} BatchUpdateOptions + * @property {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @property {google.spanner.v1.IRequestOptions} [requestOptions] The request options to include + * with the commit request. + */ + /** + * @typedef {array} BatchUpdateResponse + * @property {number[]} 0 Affected row counts. + * @property {object} 1 The full API response. + */ + /** + * @callback BatchUpdateCallback + * @param {?BatchUpdateError} err Request error, if any. + * @param {number[]} rowCounts Affected row counts. + * @param {object} apiResponse The full API response. + */ + /** + * Execute a series of DML statements and get the affected row counts. + * + * If any of the DML statements fail, the returned error will contain a list + * of results for all successfully executed statements. + * + * @param {string[]|object[]} query A DML statement or + * [`ExecuteSqlRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest) + * object. + * @param {object} [query.params] A map of parameter name to values. + * @param {object} [query.types] A map of parameter types. + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {BatchUpdateOptions} [options] Options for configuring the request. + * @param {RunUpdateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const queries = [ + * { + * sql: 'INSERT INTO MyTable (Key, Value) VALUES (@key, @value)', + * params: {key: 'my-key', value: 'my-value'}, + * }, + * { + * sql: 'UPDATE MyTable t SET t.Value = @value WHERE t.KEY = @key', + * params: {key: 'my-other-key', value: 'my-other-value'} + * } + * ]; + * + * transaction.batchUpdate(queries, (err, rowCounts, apiResponse) => { + * if (err) { + * // Error handling omitted. + * } + * }); + * + * ``` + * @example If the callback is omitted, we'll return a Promise. + * ``` + * const [rowCounts, apiResponse] = await transaction.batchUpdate(queries); + * ``` + */ + batchUpdate( + queries: Array, + options?: BatchUpdateOptions | CallOptions, + ): Promise; + batchUpdate( + queries: Array, + callback: BatchUpdateCallback, + ): void; + batchUpdate( + queries: Array, + options: BatchUpdateOptions | CallOptions, + callback: BatchUpdateCallback, + ): void; + batchUpdate( + queries: Array, + optionsOrCallback?: BatchUpdateOptions | CallOptions | BatchUpdateCallback, + cb?: BatchUpdateCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const gaxOpts = + 'gaxOptions' in options + ? (options as BatchUpdateOptions).gaxOptions + : options; + + if (!Array.isArray(queries) || !queries.length) { + const rowCounts: number[] = []; + const error = new Error('batchUpdate requires at least 1 DML statement.'); + const batchError: BatchUpdateError = Object.assign(error, { + code: 3, // invalid argument + rowCounts, + }) as BatchUpdateError; + callback!(batchError, rowCounts); + return; + } + + const statements: spannerClient.spanner.v1.ExecuteBatchDmlRequest.IStatement[] = + queries.map(query => { + if (typeof query === 'string') { + return {sql: query}; + } + const {sql} = query; + const {params, paramTypes} = Snapshot.encodeParams(query); + return {sql, params, paramTypes}; + }); + + const transaction: spannerClient.spanner.v1.ITransactionSelector = {}; + if (this.id) { + transaction.id = this.id as Uint8Array; + } else { + transaction.begin = this._options; + } + + if ( + !this.id && + this._options.readWrite && + (this.session.parent as Database).isMuxEnabledForRW_ + ) { + this._setPreviousTransactionId(transaction); + } + + const requestOptionsWithTag = this.configureTagOptions( + false, + this.requestOptions?.transactionTag ?? undefined, + (options as BatchUpdateOptions).requestOptions, + ); + const reqOpts: spannerClient.spanner.v1.ExecuteBatchDmlRequest = { + session: this.session.formattedName_!, + requestOptions: requestOptionsWithTag, + transaction, + seqno: this._seqno++, + statements, + } as spannerClient.spanner.v1.ExecuteBatchDmlRequest; + + const database = this.session.parent as Database; + const headers = injectRequestIDIntoHeaders( + this.commonHeaders_, + this.session, + nextNthRequest(database), + 1, + ); + if (this._getSpanner().routeToLeaderEnabled) { + addLeaderAwareRoutingHeader(headers); + } + + const traceConfig: traceConfig = { + ...this._traceConfig, + transactionTag: requestOptionsWithTag?.transactionTag, + requestTag: (options as BatchUpdateOptions)?.requestOptions?.requestTag, + }; + return startTrace('Transaction.batchUpdate', traceConfig, span => { + this.request( + { + client: 'SpannerClient', + method: 'executeBatchDml', + reqOpts, + gaxOpts, + headers: headers, + }, + ( + err: null | grpc.ServiceError, + resp: spannerClient.spanner.v1.ExecuteBatchDmlResponse, + ) => { + let batchUpdateError: BatchUpdateError; + + if (err) { + const rowCounts: number[] = []; + batchUpdateError = Object.assign(err, {rowCounts}); + setSpanError(span, batchUpdateError); + span.end(); + callback!(batchUpdateError, rowCounts, resp); + return; + } + + this._updatePrecommitToken(resp); + + const {resultSets, status} = resp; + for (const resultSet of resultSets) { + if (!this.id && resultSet.metadata?.transaction) { + this._update(resultSet.metadata.transaction, span); + } + } + const rowCounts: number[] = resultSets.map(({stats}) => { + return ( + (stats && + Number( + stats[ + (stats as spannerClient.spanner.v1.ResultSetStats).rowCount! + ], + )) || + 0 + ); + }); + + if (status && status.code !== 0) { + const error = new Error(status.message!); + batchUpdateError = Object.assign(error, { + code: status.code, + metadata: Transaction.extractKnownMetadata(status.details!), + rowCounts, + }) as BatchUpdateError; + setSpanError(span, batchUpdateError); + } + + span.end(); + callback!(batchUpdateError!, rowCounts, resp); + }, + ); + }); + } + + private static extractKnownMetadata( + details: IAny[], + ): grpc.Metadata | undefined { + if (details && typeof details[Symbol.iterator] === 'function') { + const metadata = new grpc.Metadata(); + for (const detail of details) { + if (detail.type_url === RETRY_INFO_TYPE && detail.value) { + metadata.add(RETRY_INFO_BIN, detail.value as string); + } + } + return metadata; + } + return undefined; + } + + /** + * This method updates the _queuedMutations property of the transaction. + * + * @public + * + * @param {spannerClient.spanner.v1.Mutation[]} [mutation] + */ + setQueuedMutations(mutation: spannerClient.spanner.v1.Mutation[]): void { + this._queuedMutations = mutation; + } + + /** + * @typedef {object} CommitOptions + * @property {google.spanner.v1.IRequestOptions} requestOptions The request options to include + * with the commit request. + * @property {boolean} returnCommitStats Include statistics related to the + * transaction in the {@link CommitResponse}. + * @property {spannerClient.proto.IDuration} maxCommitDelay Maximum amount + * of delay the commit is willing to incur in order to improve + * throughput. Value should be between 0ms and 500ms. + * @property {object} [gaxOptions] The request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + */ + /** + * @typedef {object} CommitResponse + * @property {google.protobuf.Timestamp} commitTimestamp The transaction + * commit timestamp. + * @property {google.spanner.v1.CommitResponse.ICommitStats|null} commitStats + * The statistics about this commit. Only populated if requested in + * {@link CommitOptions}. + */ + /** + * @typedef {array} CommitPromiseResponse + * @property {CommitResponse} 0 The commit response. + */ + /** + * @callback CommitCallback + * @param {?Error} error Request error, if any. + * @param {CommitResponse} apiResponse The full API response. + */ + /** + * Commit the transaction. + * + * Wrapper around {@link v1.SpannerClient#commit}. + * + * @see {@link v1.SpannerClient#commit} + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {CommitOptions} [options] Options for configuring the request. + * @param {CommitCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Queue a mutation (note that there is no callback passed to `insert`). + * transaction.insert('Singers', { + * SingerId: 'Id3b', + * Name: 'Joe West' + * }); + * + * // Commit the transaction. + * transaction.commit(function(err, apiResponse) { + * if (!err) { + * // Get the commit timestamp on successful commits. + * const {commitTimestamp} = apiResponse; + * } + * }); + * }); + * ``` + */ + commit(options?: CommitOptions | CallOptions): Promise; + commit(callback: CommitCallback): void; + commit(options: CommitOptions | CallOptions, callback: CommitCallback): void; + commit( + optionsOrCallback?: CommitOptions | CallOptions | CommitCallback, + cb?: CommitCallback, + ): void | Promise { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb!; + const gaxOpts = + 'gaxOptions' in options ? (options as CommitOptions).gaxOptions : options; + + const mutations = this._queuedMutations; + const session = this.session.formattedName_!; + const precommitToken = this._latestPreCommitToken; + const requestOptions = (options as CommitOptions).requestOptions; + const reqOpts: CommitRequest = { + mutations, + session, + requestOptions, + precommitToken, + }; + + return startTrace( + 'Transaction.commit', + { + transactionTag: this.requestOptions?.transactionTag, + ...this._traceConfig, + }, + span => { + if (this.id) { + reqOpts.transactionId = this.id as Uint8Array; + } else if (!this._useInRunner) { + reqOpts.singleUseTransaction = this._options; + } else { + if ((this.session.parent as Database).isMuxEnabledForRW_) { + this._setMutationKey(mutations); + } + this.begin().then( + () => { + this.commit(options, (err, resp) => { + if (err) { + setSpanError(span, err); + } + span.end(); + callback(err, resp); + }); + }, + err => { + setSpanError(span, err); + span.end(); + callback(err, null); + }, + ); + return; + } + + if ( + 'returnCommitStats' in options && + (options as CommitOptions).returnCommitStats + ) { + reqOpts.returnCommitStats = ( + options as CommitOptions + ).returnCommitStats; + } + if ( + 'maxCommitDelay' in options && + (options as CommitOptions).maxCommitDelay + ) { + reqOpts.maxCommitDelay = (options as CommitOptions).maxCommitDelay; + } + reqOpts.requestOptions = Object.assign( + requestOptions || {}, + this.requestOptions, + ); + + const headers = this.commonHeaders_; + if (this._getSpanner().routeToLeaderEnabled) { + addLeaderAwareRoutingHeader(headers); + } + + span.addEvent('Starting Commit'); + + const database = this.session.parent as Database; + this.request( + { + client: 'SpannerClient', + method: 'commit', + reqOpts, + gaxOpts: gaxOpts, + headers: injectRequestIDIntoHeaders( + headers, + this.session, + nextNthRequest(database), + 1, + ), + }, + ( + err: null | Error, + resp: spannerClient.spanner.v1.ICommitResponse, + ) => { + if ( + resp && + 'MultiplexedSessionRetry' in resp && + !this._retryCommit + ) { + this._retryCommit = true; + this._updatePrecommitToken(resp); + return this.commit(options, callback); + } + + this.end(); + + if (err) { + span.addEvent('Commit failed'); + setSpanError(span, err); + } else { + span.addEvent('Commit Done'); + } + + if (resp && resp.commitTimestamp) { + this.commitTimestampProto = resp.commitTimestamp; + this.commitTimestamp = new PreciseDate( + resp.commitTimestamp as DateStruct, + ); + } + err = Transaction.decorateCommitError( + err as ServiceError, + mutations, + ); + + span.end(); + callback!(err as ServiceError | null, resp); + }, + ); + }, + ); + } + + /** + * Decorates an error returned by a commit with additional information for + * specific known errors. + * @param err the error to check and decorate with additional information if possible + * @param mutations the mutations included in the commit request + * @private + */ + private static decorateCommitError( + err: null | ServiceError, + mutations: spannerClient.spanner.v1.Mutation[], + ): null | Error { + if (!err) { + return err; + } + if (err.code === Status.FAILED_PRECONDITION) { + const mismatchErr = Transaction.decoratePossibleJsonMismatchError( + err, + mutations, + ); + if (mismatchErr) { + return mismatchErr; + } + } + return err; + } + + /** + * Decorates an error returned by a commit with additional information if the + * error was returned because the application tried to insert an array of + * objects into a JSON column. An array of objects will by default be encoded + * as ARRAY, but can also be interpreted as JSON. An application must + * specify a top-level array of objects that should be inserted into a JSON + * column as a string instead of as an array of objects. + * @param err the error returned by the commit RPC + * @param mutations the mutations included in the commit request + * @private + */ + private static decoratePossibleJsonMismatchError( + err: ServiceError, + mutations: spannerClient.spanner.v1.Mutation[], + ): null | ServiceError { + const errorMessage = + /Invalid value for column (?.+) in table (?
include:samples/crud.jsinclude:samples/crud.jsinclude:samples/crud.jsinclude:samples/index-read-data.jsinclude:samples/index-read-data-with-storing.jsinclude:samples/crud.js
.+): Expected JSON./; + const found = err.message && err.message.match(errorMessage); + if (found && found.groups) { + const table = found.groups.table; + const column = found.groups.column; + for (const mutation of mutations) { + const write = + mutation.insert || + mutation.update || + mutation.insertOrUpdate || + mutation.replace; + if (write && write.table === table) { + const index = write.columns?.indexOf(column); + if (index && index > -1 && write.values) { + for (const row of write.values) { + if ( + row.values?.length && + row.values.length > index && + row.values[index].listValue + ) { + // If the value is an array, the client library also encoded it as + // an array. Inserting an array into a JSON column is not possible, + // although if it is encoded as a string containing a top-level JSON + // array it will work. + const additionalMessage = + 'The value is an array. Convert the value to a JSON string containing an array instead in order to insert it into a JSON column. Example: `[{"key": "value 1"}, {"key": "value 2"}]` instead of [{key: "value 1"}, {key: "value 2"}]'; + return { + code: err.code, + details: `${err.details} ${additionalMessage}`, + message: `${err.message} ${additionalMessage}`, + metadata: err.metadata, + name: err.name, + stack: err.stack, + }; + } + } + } + } + } + } + return null; + } + + /** + * Delete rows from a table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {string} table The name of the table. + * @param {array} keys The keys for the rows to delete. If using a + * composite key, provide an array within this array. See the example + * below. + * + * @example + * ``` + * const keys = ['Id1', 'Id2', 'Id3']; + * + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Queue this mutation until later calling `commit`. + * // Note that a callback is not passed to `deleteRows`. + * transaction.deleteRows('Singers', keys); + * + * // Commit the transaction. + * transaction.commit(function(err) { + * if (!err) { + * // The rows were deleted successfully. + * } + * }); + * }); + * + * ``` + * @example Provide an array for `keys` to delete rows with a + * composite key. + * ``` + * const keys = [ + * [ + * 'Id1', + * 'Name1' + * ], + * [ + * 'Id2', + * 'Name2' + * ] + * ]; + * ``` + */ + deleteRows(table: string, keys: Key[]): void { + this._queuedMutations.push(buildDeleteMutation(table, keys)); + } + + /** + * Insert rows of data into this table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {string} table The name of the table. + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * + * @example + * ``` + * const row = { + * SingerId: 'Id3', + * Name: 'Eddie Wilson' + * }; + * + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Queue this mutation until later calling `commit`. + * // Note that a callback is not passed to `insert`. + * transaction.insert('Singers', row); + * + * // Commit the transaction. + * transaction.commit(function(err) { + * if (!err) { + * // The row was inserted successfully. + * } + * }); + * }); + * + * ``` + * @example Multiple rows can be inserted at once. + * ``` + * const row2 = { + * SingerId: 'Id3b', + * Name: 'Joe West' + * }; + * + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Queue multiple mutations until later calling `commit`. + * // Note that a callback is not passed to `insert`. + * transaction.insert('Singers', [ + * row, + * row2 + * ]); + * + * // Commit the transaction. + * transaction.commit(function(err) { + * if (!err) { + * // The rows were inserted successfully. + * } + * }); + * }); + * ``` + */ + insert(table: string, rows: object | object[]): void { + this._mutate('insert', table, rows); + } + + /** + * Replace rows of data within a table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {string} table The table to read from. + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * + * @example + * ``` + * const row = { + * SingerId: 'Id3', + * Name: 'Joe West' + * }; + * + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Queue this mutation until later calling `commit`. + * // Note that a callback is not passed to `replace`. + * transaction.replace('Singers', row); + * + * // Commit the transaction. + * transaction.commit(function(err) { + * if (!err) { + * // The row was replaced successfully. + * } + * }); + * }); + * ``` + */ + replace(table: string, rows: object | object[]): void { + this._mutate('replace', table, rows); + } + + /** + * Roll back a transaction, releasing any locks it holds. It is a good idea to + * call this for any transaction that includes one or more queries that you + * decide not to commit. + * + * Wrapper around {@link v1.SpannerClient#rollback}. + * + * @see {@link v1.SpannerClient#rollback} + * @see [Rollback API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Rollback) + * + * @param {object} [gaxOptions] Request configuration options, + * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} + * for more details. + * @param {BasicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * transaction.rollback(function(err) { + * if (!err) { + * // Transaction rolled back successfully. + * } + * }); + * }); + * ``` + */ + rollback(gaxOptions?: CallOptions): Promise; + rollback(callback: spannerClient.spanner.v1.Spanner.RollbackCallback): void; + rollback( + gaxOptions: CallOptions, + callback: spannerClient.spanner.v1.Spanner.RollbackCallback, + ): void; + rollback( + gaxOptionsOrCallback?: + | CallOptions + | spannerClient.spanner.v1.Spanner.RollbackCallback, + cb?: spannerClient.spanner.v1.Spanner.RollbackCallback, + ): void | Promise { + const gaxOpts = + typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {}; + const callback = + typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb!; + + return startTrace('Transaction.rollback', this._traceConfig, span => { + if (!this.id) { + span.addEvent('Transaction ID is unknown, nothing to rollback.'); + span.end(); + callback(null); + return; + } + + const session = this.session.formattedName_!; + const transactionId = this.id; + const reqOpts: spannerClient.spanner.v1.IRollbackRequest = { + session, + transactionId, + }; + + const headers = this.commonHeaders_; + if (this._getSpanner().routeToLeaderEnabled) { + addLeaderAwareRoutingHeader(headers); + } + + this.request( + { + client: 'SpannerClient', + method: 'rollback', + reqOpts, + gaxOpts, + headers: headers, + }, + (err: null | ServiceError) => { + if (err) { + setSpanError(span, err); + } + span.end(); + this.end(); + callback!(err); + }, + ); + }); + } + + /** + * Update rows of data within a table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {string} table The table to read from. + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * + * @example + * ``` + * const row = { + * SingerId: 'Id3', + * Name: 'Joe West' + * }; + * + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Queue this mutation until later calling `commit`. + * // Note that a callback is not passed to `update`. + * transaction.update('Singers', row); + * + * // Commit the transaction. + * transaction.commit(function(err) { + * if (!err) { + * // The row was updated successfully. + * } + * }); + * }); + * ``` + */ + update(table: string, rows: object | object[]): void { + this._mutate('update', table, rows); + } + + /** + * Insert or update rows of data within a table. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @param {string} table The table to read from. + * @param {object|object[]} rows A map of names to values of data to insert + * into this table. + * + * @example + * ``` + * const row = { + * SingerId: 'Id3', + * Name: 'Joe West' + * }; + * + * database.runTransaction(function(err, transaction) { + * if (err) { + * // Error handling omitted. + * } + * + * // Queue this mutation until later calling `commit`. + * // Note that a callback is not passed to `upsert`. + * transaction.upsert('Singers', row); + * + * // Commit the transaction. + * transaction.commit(function(err) { + * if (!err) { + * // The row was updated or inserted successfully. + * } + * }); + * }); + * ``` + */ + upsert(table: string, rows: object | object[]): void { + this._mutate('insertOrUpdate', table, rows); + } + + /** + * Formats the mutations. + * + * @see [Commit API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit) + * + * @private + * + * @param {string} method CRUD method (insert, update, etc.). + * @param {string} table Table to perform mutations in. + * @param {object} rows Hash of key value pairs. + */ + private _mutate( + method: string, + table: string, + keyVals: object | object[], + ): void { + this._queuedMutations.push(buildMutation(method, table, keyVals)); + } + + /** + * Takes a list of rows and returns all unique column names. + * + * @private + * + * @param {object[]} rows The rows. + * @returns {string[]} + */ + static getUniqueKeys(rows: object[]): string[] { + const allKeys: string[] = []; + rows.forEach(row => allKeys.push(...Object.keys(row))); + const unique = new Set(allKeys); + return Array.from(unique).sort(); + } + + /** + * Mark transaction as started from the runner. + */ + useInRunner(): void { + this._useInRunner = true; + } + + /** + * Use optimistic concurrency control for the transaction. + * + * In this concurrency mode, operations during the execution phase, i.e., + * reads and queries, are performed without acquiring locks, and transactional + * consistency is ensured by running a validation process in the commit phase + * (when any needed locks are acquired). The validation process succeeds only + * if there are no conflicting committed transactions (that committed + * mutations to the read data at a commit timestamp after the read timestamp). + * + * @deprecated Set readLockMode through setReadWriteTransactionOptions instead. + */ + useOptimisticLock(): void { + this._options.readWrite!.readLockMode = ReadLockMode.OPTIMISTIC; + } + + /** + * Use option excludeTxnFromChangeStreams to exclude read/write transactions + * from being tracked in change streams. + * + * Enabling this options to true will effectively disable change stream tracking + * for a specified transaction, allowing read/write transaction to operate without being + * included in change streams. + */ + excludeTxnFromChangeStreams(): void { + this._options.excludeTxnFromChangeStreams = true; + } + + setReadWriteTransactionOptions(options: RunTransactionOptions) { + /** + * Set option excludeTxnFromChangeStreams=true to exclude read/write transactions + * from being tracked in change streams. + */ + if (options?.excludeTxnFromChangeStreams) { + this._options.excludeTxnFromChangeStreams = true; + } + /** + * Set isolation level. + */ + this._options.isolationLevel = options?.isolationLevel + ? options?.isolationLevel + : this._getSpanner().defaultTransactionOptions.isolationLevel; + + /** + * Set read lock mode. + */ + this._options.readWrite!.readLockMode = options?.readLockMode + ? options?.readLockMode + : this._getSpanner().defaultTransactionOptions.readLockMode; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Transaction, { + exclude: ['deleteRows', 'insert', 'replace', 'update', 'upsert'], +}); + +/** + * Builds an array of protobuf Mutations from the given row(s). + * + * @param {string} method - CRUD method (insert, update, etc.). + * @param {string} table - Table to perform mutations in. + * @param {object | object[]} keyVals - Hash of key-value pairs representing the rows. + * @returns {spannerClient.spanner.v1.Mutation} - The formatted mutation. + * @throws {GoogleError} - If a row does not contain the correct number of columns. + */ +function buildMutation( + method: string, + table: string, + keyVals: object | object[], +): spannerClient.spanner.v1.Mutation { + const rows: object[] = toArray(keyVals); + const columns = Transaction.getUniqueKeys(rows); + + const values = rows.map((row, index) => { + const keys = Object.keys(row); + const missingColumns = columns.filter(column => !keys.includes(column)); + + if (missingColumns.length > 0) { + throw new GoogleError( + [ + `Row at index ${index} does not contain the correct number of columns.`, + `Missing columns: ${JSON.stringify(missingColumns)}`, + ].join('\n\n'), + ); + } + + const values = columns.map(column => row[column]); + return codec.convertToListValue(values); + }); + + const mutation: spannerClient.spanner.v1.IMutation = { + [method]: {table, columns, values}, + }; + return mutation as spannerClient.spanner.v1.Mutation; +} + +/** + * Builds a delete mutation. + * + * @param {string} table - The name of the table. + * @param {Key[]} keys - The keys for the rows to delete. + * @returns {spannerClient.spanner.v1.Mutation} - The formatted delete mutation. + */ +function buildDeleteMutation( + table: string, + keys: Key[], +): spannerClient.spanner.v1.Mutation { + const keySet: spannerClient.spanner.v1.IKeySet = { + keys: toArray(keys).map(codec.convertToListValue), + }; + const mutation: spannerClient.spanner.v1.IMutation = { + delete: {table, keySet}, + }; + return mutation as spannerClient.spanner.v1.Mutation; +} + +/** + * MutationSet represent a set of changes to be applied atomically to a Cloud Spanner + * database with a {@link Transaction}. + * Mutations are used to insert, update, upsert(insert or update), replace, or + * delete rows within tables. + * + * Mutations are added to a {@link Transaction} and are not executed until the + * transaction is committed via {@link Transaction#commit}. + * + * If the transaction is rolled back or encounters an error, the mutations are + * discarded. + * + * @example + * ``` + * const {Spanner, Mutation} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const mutations = new MutationSet(); + * mutations.insert('Singers', {SingerId: '123', FirstName: 'David'}); + * mutations.update('Singers', {SingerId: '123', FirstName: 'Marc'}); + * + * try { + * database.writeAtLeastOnce(mutations, (err, res) => { + * console.log("RESPONSE: ", res); + * }); + * } catch(err) { + * console.log("ERROR: ", err); + * } + * ``` + */ +export class MutationSet { + /** + * An array to store the mutations. + */ + private _queuedMutations: spannerClient.spanner.v1.Mutation[]; + + /** + * Creates a new Mutation object. + */ + constructor() { + this._queuedMutations = []; + } + + /** + * Adds an insert operation to the mutation set. + * @param {string} table. The name of the table to insert into. + * @param {object|object[]} rows. A single row object or an array of row objects to insert. + */ + insert(table: string, rows: object | object[]): void { + this._queuedMutations.push(buildMutation('insert', table, rows)); + } + + /** + * Adds an update operation to the mutation set. + * @param {string} table. The name of the table to update. + * @param {object|object[]} rows. A single row object or an array of row objects to update. + * Each row object must contain the primary key values to indentify the row to update. + */ + update(table: string, rows: object | object[]): void { + this._queuedMutations.push(buildMutation('update', table, rows)); + } + + /** + * Adds an upsert operation to the mutation set. + * An upsert will insert a new row if it does not exist or update an existing row if it does. + * @param {string} table. The name of the table to upsert. + * @param {object|object[]} rows. A single row object or an array of row objects to upsert. + */ + upsert(table: string, rows: object | object[]): void { + this._queuedMutations.push(buildMutation('insertOrUpdate', table, rows)); + } + + /** + * Adds a replace operation to the mutation set. + * A replace operation deletes the existing row (if it exists) and inserts the new row. + * @param {string} table. The name of the table to replace. + * @param {object|object[]} rows. A single row object or an array of row objects to replace. + */ + replace(table: string, rows: object | object[]): void { + this._queuedMutations.push(buildMutation('replace', table, rows)); + } + + /** + * Adds a deleteRows operation to the mutation set. + * This operation deletes rows from the specified table based on their primary keys. + * @param {string} table. The name of the table to deleteRows from. + * @param {key[]} key. An array of key objects, each represeting the primary key of a row to delete. + */ + deleteRows(table: string, keys: Key[]): void { + this._queuedMutations.push(buildDeleteMutation(table, keys)); + } + + /** + * Returns the internal representation of the queued mutations as a protobuf message. + * @returns {spannerClient.spanner.v1.Mutation[]}. The protobuf message representing the mutations. + */ + proto(): spannerClient.spanner.v1.Mutation[] { + return this._queuedMutations; + } +} + +/** + * A group of mutations to be committed together. + * Related mutations should be placed in a group. + * + * For example, two mutations inserting rows with the same primary + * key prefix in both parent and child tables are related. + * + * This object is created and returned from {@link Database#MutationGroup}. + * + * @example + * ``` + * const {Spanner} = require('@google-cloud/spanner'); + * const spanner = new Spanner(); + * + * const instance = spanner.instance('my-instance'); + * const database = instance.database('my-database'); + * + * const mutationGroup = new MutationGroup(); + * mutationGroup.insert('Singers', {SingerId: '123', FirstName: 'David'}); + * mutationGroup.update('Singers', {SingerId: '123', FirstName: 'Marc'}); + * + * database.batchWriteAtLeastOnce([mutationGroup], {}) + * .on('error', console.error) + * .on('data', response => { + * console.log('response: ', response); + * }) + * .on('end', () => { + * console.log('Request completed successfully'); + * }); + * ``` + */ +export class MutationGroup { + private _proto: spannerClient.spanner.v1.BatchWriteRequest.MutationGroup; + + constructor() { + this._proto = + new spannerClient.spanner.v1.BatchWriteRequest.MutationGroup(); + } + + insert(table: string, rows: object | object[]): void { + this._proto.mutations.push(buildMutation('insert', table, rows)); + } + + update(table: string, rows: object | object[]): void { + this._proto.mutations.push(buildMutation('update', table, rows)); + } + + upsert(table: string, rows: object | object[]): void { + this._proto.mutations.push(buildMutation('insertOrUpdate', table, rows)); + } + + replace(table: string, rows: object | object[]): void { + this._proto.mutations.push(buildMutation('replace', table, rows)); + } + + deleteRows(table: string, keys: Key[]): void { + this._proto.mutations.push(buildDeleteMutation(table, keys)); + } + + proto(): spannerClient.spanner.v1.BatchWriteRequest.IMutationGroup { + return this._proto; + } +} + +/** + * This type of transaction is used to execute a single Partitioned DML + * statement. Partitioned DML partitions the key space and runs the DML + * statement over each partition in parallel using separate, internal + * transactions that commit independently. + * + * Chances are, you'll never need to create a partitioned DML transaction + * directly, instead you'll want to use {@link Database#runPartitionedUpdate}. + * + * @class + * @extends Snapshot + * + * @see Database#runPartitionedUpdate + */ +export class PartitionedDml extends Dml { + constructor( + session: Session, + options = {} as spannerClient.spanner.v1.TransactionOptions.PartitionedDml, + ) { + super(session); + this._options = {partitionedDml: options}; + } + /** + * Use option excludeTxnFromChangeStreams to exclude partitionedDml + * queries from being tracked in change streams. + * + * Enabling this options to true will effectively disable change stream tracking + * for a specified partitionedDml query, allowing write queries to operate + * without being included in change streams. + */ + excludeTxnFromChangeStreams(): void { + this._options.excludeTxnFromChangeStreams = true; + } + + /** + * Execute a DML statement and get the affected row count. Unlike + * {@link Transaction#runUpdate} after using this method you should + * immediately discard this transaction, internally it will invoke + * {@link PartitionedDml#end}. + * + * @see Database#runPartitionedUpdate + * + * @param {string|object} query A DML statement or + * [`ExecuteSqlRequest`](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest) + * object. + * @param {object} [query.params] A map of parameter name to values. + * @param {object} [query.types] A map of parameter types. + * @param {RunUpdateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * transaction.runUpdate(query, (err, rowRount) => { + * if (err) { + * // Error handling omitted. + * } + * }); + * ``` + */ + runUpdate(query: string | ExecuteSqlRequest): Promise; + runUpdate( + query: string | ExecuteSqlRequest, + callback: RunUpdateCallback, + ): void; + runUpdate( + query: string | ExecuteSqlRequest, + callback?: RunUpdateCallback, + ): void | Promise { + return startTrace( + 'PartitionedDml.runUpdate', + { + ...(query as ExecuteSqlRequest), + ...this._traceConfig, + }, + span => { + super.runUpdate(query, (err, count) => { + if (err) { + setSpanError(span, err); + } + this.end(); + span.end(); + callback!(err, count); + }); + }, + ); + } +} + +function isErrorAborted(err): boolean { + return ( + err && + typeof err === 'object' && + 'code' in err && + (err as grpc.ServiceError).code === grpc.status.ABORTED + ); +} + +/*! Developer Documentation + * + * All async methods (except for streams) return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(PartitionedDml); diff --git a/handwritten/spanner/src/v1/database_admin_client.ts b/handwritten/spanner/src/v1/database_admin_client.ts new file mode 100644 index 00000000000..32b6cf6ea1b --- /dev/null +++ b/handwritten/spanner/src/v1/database_admin_client.ts @@ -0,0 +1,6448 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/database_admin_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './database_admin_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Cloud Spanner Database Admin API + * + * The Cloud Spanner Database Admin API can be used to: + * * create, drop, and list databases + * * update the schema of pre-existing databases + * * create, delete, copy and list backups for a database + * * restore a database from an existing backup + * @class + * @memberof v1 + */ +export class DatabaseAdminClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('spanner'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + operationsClient: gax.OperationsClient; + databaseAdminStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of DatabaseAdminClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new DatabaseAdminClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof DatabaseAdminClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; + this._servicePath = 'spanner.' + this._universeDomain; + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = + opts?.fallback ?? + (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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + backupPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/backups/{backup}', + ), + backupSchedulePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}/backupSchedules/{schedule}', + ), + cryptoKeyPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}', + ), + databasePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}', + ), + databaseRolePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}/databaseRoles/{role}', + ), + instancePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}', + ), + }; + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listDatabases: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'databases', + ), + listBackups: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'backups', + ), + listDatabaseOperations: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'operations', + ), + listBackupOperations: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'operations', + ), + listDatabaseRoles: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'databaseRoles', + ), + listBackupSchedules: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'backupSchedules', + ), + }; + + const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); + // This API contains "long-running operations", which return a + // an Operation object that allows for tracking of the operation, + // rather than holding a request open. + const lroOptions: GrpcClientOptions = { + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, + }; + if (opts.fallback) { + lroOptions.protoJson = protoFilesRoot; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1/{name=projects/*/instances/*/databases/*/operations/*}:cancel', + additional_bindings: [ + {post: '/v1/{name=projects/*/instances/*/operations/*}:cancel'}, + { + post: '/v1/{name=projects/*/instances/*/backups/*/operations/*}:cancel', + }, + { + post: '/v1/{name=projects/*/instanceConfigs/*/operations/*}:cancel', + }, + ], + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1/{name=projects/*/instances/*/databases/*/operations/*}', + additional_bindings: [ + {delete: '/v1/{name=projects/*/instances/*/operations/*}'}, + { + delete: + '/v1/{name=projects/*/instances/*/backups/*/operations/*}', + }, + {delete: '/v1/{name=projects/*/instanceConfigs/*/operations/*}'}, + ], + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1/{name=projects/*/instances/*/databases/*/operations/*}', + additional_bindings: [ + {get: '/v1/{name=projects/*/instances/*/operations/*}'}, + {get: '/v1/{name=projects/*/instances/*/backups/*/operations/*}'}, + {get: '/v1/{name=projects/*/instanceConfigs/*/operations/*}'}, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1/{name=projects/*/instances/*/databases/*/operations}', + additional_bindings: [ + {get: '/v1/{name=projects/*/instances/*/operations}'}, + {get: '/v1/{name=projects/*/instances/*/backups/*/operations}'}, + {get: '/v1/{name=projects/*/instanceConfigs/*/operations}'}, + ], + }, + ]; + } + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); + const createDatabaseResponse = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.Database', + ) as gax.protobuf.Type; + const createDatabaseMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.CreateDatabaseMetadata', + ) as gax.protobuf.Type; + const updateDatabaseResponse = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.Database', + ) as gax.protobuf.Type; + const updateDatabaseMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.UpdateDatabaseMetadata', + ) as gax.protobuf.Type; + const updateDatabaseDdlResponse = protoFilesRoot.lookup( + '.google.protobuf.Empty', + ) as gax.protobuf.Type; + const updateDatabaseDdlMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata', + ) as gax.protobuf.Type; + const createBackupResponse = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.Backup', + ) as gax.protobuf.Type; + const createBackupMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.CreateBackupMetadata', + ) as gax.protobuf.Type; + const copyBackupResponse = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.Backup', + ) as gax.protobuf.Type; + const copyBackupMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.CopyBackupMetadata', + ) as gax.protobuf.Type; + const restoreDatabaseResponse = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.Database', + ) as gax.protobuf.Type; + const restoreDatabaseMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.database.v1.RestoreDatabaseMetadata', + ) as gax.protobuf.Type; + + this.descriptors.longrunning = { + createDatabase: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createDatabaseResponse.decode.bind(createDatabaseResponse), + createDatabaseMetadata.decode.bind(createDatabaseMetadata), + ), + updateDatabase: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + updateDatabaseResponse.decode.bind(updateDatabaseResponse), + updateDatabaseMetadata.decode.bind(updateDatabaseMetadata), + ), + updateDatabaseDdl: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + updateDatabaseDdlResponse.decode.bind(updateDatabaseDdlResponse), + updateDatabaseDdlMetadata.decode.bind(updateDatabaseDdlMetadata), + ), + createBackup: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createBackupResponse.decode.bind(createBackupResponse), + createBackupMetadata.decode.bind(createBackupMetadata), + ), + copyBackup: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + copyBackupResponse.decode.bind(copyBackupResponse), + copyBackupMetadata.decode.bind(copyBackupMetadata), + ), + restoreDatabase: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + restoreDatabaseResponse.decode.bind(restoreDatabaseResponse), + restoreDatabaseMetadata.decode.bind(restoreDatabaseMetadata), + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.spanner.admin.database.v1.DatabaseAdmin', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')}, + ); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.databaseAdminStub) { + return this.databaseAdminStub; + } + + // Put together the "service stub" for + // google.spanner.admin.database.v1.DatabaseAdmin. + this.databaseAdminStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.spanner.admin.database.v1.DatabaseAdmin', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.spanner.admin.database.v1.DatabaseAdmin, + this._opts, + this._providedCustomServicePath, + ) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const databaseAdminStubMethods = [ + 'listDatabases', + 'createDatabase', + 'getDatabase', + 'updateDatabase', + 'updateDatabaseDdl', + 'dropDatabase', + 'getDatabaseDdl', + 'setIamPolicy', + 'getIamPolicy', + 'testIamPermissions', + 'createBackup', + 'copyBackup', + 'getBackup', + 'updateBackup', + 'deleteBackup', + 'listBackups', + 'restoreDatabase', + 'listDatabaseOperations', + 'listBackupOperations', + 'listDatabaseRoles', + 'addSplitPoints', + 'createBackupSchedule', + 'getBackupSchedule', + 'updateBackupSchedule', + 'deleteBackupSchedule', + 'listBackupSchedules', + 'internalUpdateGraphOperation', + ]; + for (const methodName of databaseAdminStubMethods) { + const callPromise = this.databaseAdminStub.then( + stub => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = + this.descriptors.page[methodName] || + this.descriptors.longrunning[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.databaseAdminStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'spanner.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'spanner.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.admin', + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId( + callback?: Callback, + ): Promise | void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + /** + * Gets the state of a Cloud Spanner database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the requested database. Values are of the form + * `projects//instances//databases/`. + * @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.spanner.admin.database.v1.Database|Database}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getDatabase( + request?: protos.google.spanner.admin.database.v1.IGetDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ] + >; + getDatabase( + request: protos.google.spanner.admin.database.v1.IGetDatabaseRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IDatabase, + | protos.google.spanner.admin.database.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getDatabase( + request: protos.google.spanner.admin.database.v1.IGetDatabaseRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IDatabase, + | protos.google.spanner.admin.database.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getDatabase( + request?: protos.google.spanner.admin.database.v1.IGetDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IDatabase, + | protos.google.spanner.admin.database.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IDatabase, + | protos.google.spanner.admin.database.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getDatabase request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IDatabase, + | protos.google.spanner.admin.database.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getDatabase response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getDatabase(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IDatabase, + ( + | protos.google.spanner.admin.database.v1.IGetDatabaseRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDatabase response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Drops (aka deletes) a Cloud Spanner database. + * Completed backups for the database will be retained according to their + * `expire_time`. + * Note: Cloud Spanner might continue to accept requests for a few seconds + * after the database has been deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database to be dropped. + * @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.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. + */ + dropDatabase( + request?: protos.google.spanner.admin.database.v1.IDropDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IDropDatabaseRequest | undefined, + {} | undefined, + ] + >; + dropDatabase( + request: protos.google.spanner.admin.database.v1.IDropDatabaseRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDropDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + dropDatabase( + request: protos.google.spanner.admin.database.v1.IDropDatabaseRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDropDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + dropDatabase( + request?: protos.google.spanner.admin.database.v1.IDropDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDropDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDropDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IDropDatabaseRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('dropDatabase request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDropDatabaseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('dropDatabase response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .dropDatabase(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.database.v1.IDropDatabaseRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('dropDatabase response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Returns the schema of a Cloud Spanner database as a list of formatted + * DDL statements. This method does not show pending schema updates, those may + * be queried using the {@link protos.google.longrunning.Operations|Operations} API. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database whose schema we wish to get. + * Values are of the form + * `projects//instances//databases/` + * @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.spanner.admin.database.v1.GetDatabaseDdlResponse|GetDatabaseDdlResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getDatabaseDdl( + request?: protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse, + ( + | protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest + | undefined + ), + {} | undefined, + ] + >; + getDatabaseDdl( + request: protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse, + | protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getDatabaseDdl( + request: protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse, + | protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getDatabaseDdl( + request?: protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse, + | protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse, + | protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse, + ( + | protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getDatabaseDdl request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse, + | protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getDatabaseDdl response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getDatabaseDdl(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse, + ( + | protos.google.spanner.admin.database.v1.IGetDatabaseDdlRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDatabaseDdl response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Sets the access control policy on a database or backup resource. + * Replaces any existing policy. + * + * Authorization requires `spanner.databases.setIamPolicy` + * permission on {@link protos.google.iam.v1.SetIamPolicyRequest.resource|resource}. + * For backups, authorization requires `spanner.backups.setIamPolicy` + * permission on {@link protos.google.iam.v1.SetIamPolicyRequest.resource|resource}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being specified. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.Policy} request.policy + * REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @param {google.protobuf.FieldMask} request.updateMask + * OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only + * the fields in the mask will be modified. If no mask is provided, the + * following default mask is used: + * + * `paths: "bindings, etag"` + * @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.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + setIamPolicy( + request?: protos.google.iam.v1.ISetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ] + >; + setIamPolicy( + request: protos.google.iam.v1.ISetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; + setIamPolicy( + request: protos.google.iam.v1.ISetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; + setIamPolicy( + request?: protos.google.iam.v1.ISetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('setIamPolicy request %j', request); + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('setIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .setIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('setIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets the access control policy for a database or backup resource. + * Returns an empty policy if a database or backup exists but does not have a + * policy set. + * + * Authorization requires `spanner.databases.getIamPolicy` permission on + * {@link protos.google.iam.v1.GetIamPolicyRequest.resource|resource}. + * For backups, authorization requires `spanner.backups.getIamPolicy` + * permission on {@link protos.google.iam.v1.GetIamPolicyRequest.resource|resource}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.GetPolicyOptions} request.options + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. + * @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.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getIamPolicy( + request?: protos.google.iam.v1.IGetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + >; + getIamPolicy( + request: protos.google.iam.v1.IGetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; + getIamPolicy( + request: protos.google.iam.v1.IGetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; + getIamPolicy( + request?: protos.google.iam.v1.IGetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getIamPolicy request %j', request); + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Returns permissions that the caller has on the specified database or backup + * resource. + * + * Attempting this RPC on a non-existent Cloud Spanner database will + * result in a NOT_FOUND error if the user has + * `spanner.databases.list` permission on the containing Cloud + * Spanner instance. Otherwise returns an empty set of permissions. + * Calling this method on a backup that does not exist will + * result in a NOT_FOUND error if the user has + * `spanner.backups.list` permission on the containing instance. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @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.iam.v1.TestIamPermissionsResponse|TestIamPermissionsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + testIamPermissions( + request?: protos.google.iam.v1.ITestIamPermissionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ] + >; + testIamPermissions( + request: protos.google.iam.v1.ITestIamPermissionsRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): void; + testIamPermissions( + request: protos.google.iam.v1.ITestIamPermissionsRequest, + callback: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): void; + testIamPermissions( + request?: protos.google.iam.v1.ITestIamPermissionsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('testIamPermissions request %j', request); + const wrappedCallback: + | Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('testIamPermissions response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .testIamPermissions(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('testIamPermissions response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets metadata on a pending or completed + * {@link protos.google.spanner.admin.database.v1.Backup|Backup}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup. + * Values are of the form + * `projects//instances//backups/`. + * @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.spanner.admin.database.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getBackup( + request?: protos.google.spanner.admin.database.v1.IGetBackupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + >; + getBackup( + request: protos.google.spanner.admin.database.v1.IGetBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IGetBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getBackup( + request: protos.google.spanner.admin.database.v1.IGetBackupRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IGetBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getBackup( + request?: protos.google.spanner.admin.database.v1.IGetBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IGetBackupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IGetBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getBackup request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IGetBackupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getBackup response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getBackup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.IGetBackupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBackup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Updates a pending or completed + * {@link protos.google.spanner.admin.database.v1.Backup|Backup}. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.spanner.admin.database.v1.Backup} request.backup + * Required. The backup to update. `backup.name`, and the fields to be updated + * as specified by `update_mask` are required. Other fields are ignored. + * Update is only supported for the following fields: + * * `backup.expire_time`. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. A mask specifying which fields (e.g. `expire_time`) in the + * Backup resource should be updated. This mask is relative to the Backup + * resource, not to the request message. The field mask must always be + * specified; this prevents any future fields from being erased accidentally + * by clients that do not know about them. + * @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.spanner.admin.database.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + updateBackup( + request?: protos.google.spanner.admin.database.v1.IUpdateBackupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.IUpdateBackupRequest | undefined, + {} | undefined, + ] + >; + updateBackup( + request: protos.google.spanner.admin.database.v1.IUpdateBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IUpdateBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + updateBackup( + request: protos.google.spanner.admin.database.v1.IUpdateBackupRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IUpdateBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + updateBackup( + request?: protos.google.spanner.admin.database.v1.IUpdateBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IUpdateBackupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IUpdateBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.IUpdateBackupRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'backup.name': request.backup!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('updateBackup request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IBackup, + | protos.google.spanner.admin.database.v1.IUpdateBackupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateBackup response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateBackup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IBackup, + ( + | protos.google.spanner.admin.database.v1.IUpdateBackupRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateBackup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes a pending or completed + * {@link protos.google.spanner.admin.database.v1.Backup|Backup}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to delete. + * Values are of the form + * `projects//instances//backups/`. + * @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.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. + */ + deleteBackup( + request?: protos.google.spanner.admin.database.v1.IDeleteBackupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + >; + deleteBackup( + request: protos.google.spanner.admin.database.v1.IDeleteBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteBackup( + request: protos.google.spanner.admin.database.v1.IDeleteBackupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteBackup( + request?: protos.google.spanner.admin.database.v1.IDeleteBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteBackup request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteBackup response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteBackup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.database.v1.IDeleteBackupRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteBackup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Adds split points to specified tables, indexes of a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database on whose tables/indexes split points are to be + * added. Values are of the form + * `projects//instances//databases/`. + * @param {number[]} request.splitPoints + * Required. The split points to add. + * @param {string} [request.initiator] + * Optional. A user-supplied tag associated with the split points. + * For example, "intital_data_load", "special_event_1". + * Defaults to "CloudAddSplitPointsAPI" if not specified. + * The length of the tag must not exceed 50 characters,else will be trimmed. + * Only valid UTF8 characters are allowed. + * @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.spanner.admin.database.v1.AddSplitPointsResponse|AddSplitPointsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + addSplitPoints( + request?: protos.google.spanner.admin.database.v1.IAddSplitPointsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IAddSplitPointsResponse, + ( + | protos.google.spanner.admin.database.v1.IAddSplitPointsRequest + | undefined + ), + {} | undefined, + ] + >; + addSplitPoints( + request: protos.google.spanner.admin.database.v1.IAddSplitPointsRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IAddSplitPointsResponse, + | protos.google.spanner.admin.database.v1.IAddSplitPointsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + addSplitPoints( + request: protos.google.spanner.admin.database.v1.IAddSplitPointsRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IAddSplitPointsResponse, + | protos.google.spanner.admin.database.v1.IAddSplitPointsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + addSplitPoints( + request?: protos.google.spanner.admin.database.v1.IAddSplitPointsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IAddSplitPointsResponse, + | protos.google.spanner.admin.database.v1.IAddSplitPointsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IAddSplitPointsResponse, + | protos.google.spanner.admin.database.v1.IAddSplitPointsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IAddSplitPointsResponse, + ( + | protos.google.spanner.admin.database.v1.IAddSplitPointsRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('addSplitPoints request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IAddSplitPointsResponse, + | protos.google.spanner.admin.database.v1.IAddSplitPointsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('addSplitPoints response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .addSplitPoints(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IAddSplitPointsResponse, + ( + | protos.google.spanner.admin.database.v1.IAddSplitPointsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('addSplitPoints response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Creates a new backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the database that this backup schedule applies to. + * @param {string} request.backupScheduleId + * Required. The Id to use for the backup schedule. The `backup_schedule_id` + * appended to `parent` forms the full backup schedule name of the form + * `projects//instances//databases//backupSchedules/`. + * @param {google.spanner.admin.database.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to create. + * @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.spanner.admin.database.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + createBackupSchedule( + request?: protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest + | undefined + ), + {} | undefined, + ] + >; + createBackupSchedule( + request: protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createBackupSchedule( + request: protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createBackupSchedule( + request?: protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createBackupSchedule request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.ICreateBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createBackupSchedule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets backup schedule for the input schedule name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the schedule to retrieve. + * Values are of the form + * `projects//instances//databases//backupSchedules/`. + * @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.spanner.admin.database.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getBackupSchedule( + request?: protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest + | undefined + ), + {} | undefined, + ] + >; + getBackupSchedule( + request: protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getBackupSchedule( + request: protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getBackupSchedule( + request?: protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getBackupSchedule request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.IGetBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getBackupSchedule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Updates a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.spanner.admin.database.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to update. `backup_schedule.name`, and the + * fields to be updated as specified by `update_mask` are required. Other + * fields are ignored. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. A mask specifying which fields in the BackupSchedule resource + * should be updated. This mask is relative to the BackupSchedule resource, + * not to the request message. The field mask must always be + * specified; this prevents any future fields from being erased + * accidentally. + * @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.spanner.admin.database.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + updateBackupSchedule( + request?: protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest + | undefined + ), + {} | undefined, + ] + >; + updateBackupSchedule( + request: protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + updateBackupSchedule( + request: protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + updateBackupSchedule( + request?: protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'backup_schedule.name': request.backupSchedule!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('updateBackupSchedule request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IBackupSchedule, + | protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IBackupSchedule, + ( + | protos.google.spanner.admin.database.v1.IUpdateBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateBackupSchedule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the schedule to delete. + * Values are of the form + * `projects//instances//databases//backupSchedules/`. + * @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.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. + */ + deleteBackupSchedule( + request?: protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest + | undefined + ), + {} | undefined, + ] + >; + deleteBackupSchedule( + request: protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteBackupSchedule( + request: protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteBackupSchedule( + request?: protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteBackupSchedule request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.database.v1.IDeleteBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteBackupSchedule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * This is an internal API called by Spanner Graph jobs. You should never need + * to call this API directly. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Internal field, do not use directly. + * @param {string} request.operationId + * Internal field, do not use directly. + * @param {string} request.vmIdentityToken + * Internal field, do not use directly. + * @param {number} [request.progress] + * Internal field, do not use directly. + * @param {google.rpc.Status} [request.status] + * Internal field, do not use directly. + * @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.spanner.admin.database.v1.InternalUpdateGraphOperationResponse|InternalUpdateGraphOperationResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + internalUpdateGraphOperation( + request?: protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, + ( + | protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest + | undefined + ), + {} | undefined, + ] + >; + internalUpdateGraphOperation( + request: protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, + | protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + internalUpdateGraphOperation( + request: protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest, + callback: Callback< + protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, + | protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + internalUpdateGraphOperation( + request?: protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, + | protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, + | protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, + ( + | protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + this.initialize().catch(err => { + throw err; + }); + this._log.info('internalUpdateGraphOperation request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, + | protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('internalUpdateGraphOperation response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .internalUpdateGraphOperation(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse, + ( + | protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('internalUpdateGraphOperation response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + + /** + * Creates a new Cloud Spanner database and starts to prepare it for serving. + * The returned {@link protos.google.longrunning.Operation|long-running operation} will + * have a name of the format `/operations/` and + * can be used to track preparation of the database. The + * {@link protos.google.longrunning.Operation.metadata|metadata} field type is + * {@link protos.google.spanner.admin.database.v1.CreateDatabaseMetadata|CreateDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} field type is + * {@link protos.google.spanner.admin.database.v1.Database|Database}, if successful. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the instance that will serve the new database. + * Values are of the form `projects//instances/`. + * @param {string} request.createStatement + * Required. A `CREATE DATABASE` statement, which specifies the ID of the + * new database. The database ID must conform to the regular expression + * `{@link protos.a-z0-9_\-|a-z}*[a-z0-9]` and be between 2 and 30 characters in length. + * If the database ID is a reserved word or if it contains a hyphen, the + * database ID must be enclosed in backticks (`` ` ``). + * @param {string[]} [request.extraStatements] + * Optional. A list of DDL statements to run inside the newly created + * database. Statements can create tables, indexes, etc. These + * statements execute atomically with the creation of the database: + * if there is an error in any statement, the database is not created. + * @param {google.spanner.admin.database.v1.EncryptionConfig} [request.encryptionConfig] + * Optional. The encryption configuration for the database. If this field is + * not specified, Cloud Spanner will encrypt/decrypt all data at rest using + * Google default encryption. + * @param {google.spanner.admin.database.v1.DatabaseDialect} [request.databaseDialect] + * Optional. The dialect of the Cloud Spanner Database. + * @param {Buffer} [request.protoDescriptors] + * Optional. Proto descriptors used by CREATE/ALTER PROTO BUNDLE statements in + * 'extra_statements' above. + * Contains a protobuf-serialized + * [google.protobuf.FileDescriptorSet](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto). + * To generate it, [install](https://grpc.io/docs/protoc-installation/) and + * run `protoc` with --include_imports and --descriptor_set_out. For example, + * to generate for moon/shot/app.proto, run + * ``` + * $protoc --proto_path=/app_path --proto_path=/lib_path \ + * --include_imports \ + * --descriptor_set_out=descriptors.data \ + * moon/shot/app.proto + * ``` + * For more details, see protobuffer [self + * description](https://developers.google.com/protocol-buffers/docs/techniques#self-description). + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + createDatabase( + request?: protos.google.spanner.admin.database.v1.ICreateDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createDatabase( + request: protos.google.spanner.admin.database.v1.ICreateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createDatabase( + request: protos.google.spanner.admin.database.v1.ICreateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createDatabase( + request?: protos.google.spanner.admin.database.v1.ICreateDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createDatabase request %j', request); + return this.innerApiCalls + .createDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkCreateDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.database.v1.Database, + protos.google.spanner.admin.database.v1.CreateDatabaseMetadata + > + > { + this._log.info('createDatabase long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createDatabase, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.database.v1.Database, + protos.google.spanner.admin.database.v1.CreateDatabaseMetadata + >; + } + /** + * Updates a Cloud Spanner database. The returned + * {@link protos.google.longrunning.Operation|long-running operation} can be used to track + * the progress of updating the database. If the named database does not + * exist, returns `NOT_FOUND`. + * + * While the operation is pending: + * + * * The database's + * {@link protos.google.spanner.admin.database.v1.Database.reconciling|reconciling} + * field is set to true. + * * Cancelling the operation is best-effort. If the cancellation succeeds, + * the operation metadata's + * {@link protos.google.spanner.admin.database.v1.UpdateDatabaseMetadata.cancel_time|cancel_time} + * is set, the updates are reverted, and the operation terminates with a + * `CANCELLED` status. + * * New UpdateDatabase requests will return a `FAILED_PRECONDITION` error + * until the pending operation is done (returns successfully or with + * error). + * * Reading the database via the API continues to give the pre-request + * values. + * + * Upon completion of the returned operation: + * + * * The new values are in effect and readable via the API. + * * The database's + * {@link protos.google.spanner.admin.database.v1.Database.reconciling|reconciling} + * field becomes false. + * + * The returned {@link protos.google.longrunning.Operation|long-running operation} will + * have a name of the format + * `projects//instances//databases//operations/` + * and can be used to track the database modification. The + * {@link protos.google.longrunning.Operation.metadata|metadata} field type is + * {@link protos.google.spanner.admin.database.v1.UpdateDatabaseMetadata|UpdateDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} field type is + * {@link protos.google.spanner.admin.database.v1.Database|Database}, if successful. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.spanner.admin.database.v1.Database} request.database + * Required. The database to update. + * The `name` field of the database is of the form + * `projects//instances//databases/`. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. Currently, only + * `enable_drop_protection` field can be updated. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + updateDatabase( + request?: protos.google.spanner.admin.database.v1.IUpdateDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateDatabase( + request: protos.google.spanner.admin.database.v1.IUpdateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateDatabase( + request: protos.google.spanner.admin.database.v1.IUpdateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateDatabase( + request?: protos.google.spanner.admin.database.v1.IUpdateDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'database.name': request.database!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateDatabase request %j', request); + return this.innerApiCalls + .updateDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkUpdateDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.database.v1.Database, + protos.google.spanner.admin.database.v1.UpdateDatabaseMetadata + > + > { + this._log.info('updateDatabase long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateDatabase, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.database.v1.Database, + protos.google.spanner.admin.database.v1.UpdateDatabaseMetadata + >; + } + /** + * Updates the schema of a Cloud Spanner database by + * creating/altering/dropping tables, columns, indexes, etc. The returned + * {@link protos.google.longrunning.Operation|long-running operation} will have a name of + * the format `/operations/` and can be used to + * track execution of the schema change(s). The + * {@link protos.google.longrunning.Operation.metadata|metadata} field type is + * {@link protos.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata|UpdateDatabaseDdlMetadata}. + * The operation has no response. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database to update. + * @param {string[]} request.statements + * Required. DDL statements to be applied to the database. + * @param {string} request.operationId + * If empty, the new update request is assigned an + * automatically-generated operation ID. Otherwise, `operation_id` + * is used to construct the name of the resulting + * {@link protos.google.longrunning.Operation|Operation}. + * + * Specifying an explicit operation ID simplifies determining + * whether the statements were executed in the event that the + * {@link protos.google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl|UpdateDatabaseDdl} + * call is replayed, or the return value is otherwise lost: the + * {@link protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database|database} + * and `operation_id` fields can be combined to form the + * {@link protos.google.longrunning.Operation.name|name} of the resulting + * {@link protos.google.longrunning.Operation|longrunning.Operation}: + * `/operations/`. + * + * `operation_id` should be unique within the database, and must be + * a valid identifier: `{@link protos.a-z0-9_|a-z}*`. Note that + * automatically-generated operation IDs always begin with an + * underscore. If the named operation already exists, + * {@link protos.google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl|UpdateDatabaseDdl} + * returns `ALREADY_EXISTS`. + * @param {Buffer} [request.protoDescriptors] + * Optional. Proto descriptors used by CREATE/ALTER PROTO BUNDLE statements. + * Contains a protobuf-serialized + * [google.protobuf.FileDescriptorSet](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto). + * To generate it, [install](https://grpc.io/docs/protoc-installation/) and + * run `protoc` with --include_imports and --descriptor_set_out. For example, + * to generate for moon/shot/app.proto, run + * ``` + * $protoc --proto_path=/app_path --proto_path=/lib_path \ + * --include_imports \ + * --descriptor_set_out=descriptors.data \ + * moon/shot/app.proto + * ``` + * For more details, see protobuffer [self + * description](https://developers.google.com/protocol-buffers/docs/techniques#self-description). + * @param {boolean} [request.throughputMode] + * Optional. This field is exposed to be used by the Spanner Migration Tool. + * For more details, see + * [SMT](https://github.com/GoogleCloudPlatform/spanner-migration-tool). + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + updateDatabaseDdl( + request?: protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateDatabaseDdl( + request: protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateDatabaseDdl( + request: protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateDatabaseDdl( + request?: protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateDatabaseDdl response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateDatabaseDdl request %j', request); + return this.innerApiCalls + .updateDatabaseDdl(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateDatabaseDdl response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `updateDatabaseDdl()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkUpdateDatabaseDdlProgress( + name: string, + ): Promise< + LROperation< + protos.google.protobuf.Empty, + protos.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + > + > { + this._log.info('updateDatabaseDdl long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateDatabaseDdl, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.protobuf.Empty, + protos.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata + >; + } + /** + * Starts creating a new Cloud Spanner Backup. + * The returned backup {@link protos.google.longrunning.Operation|long-running operation} + * will have a name of the format + * `projects//instances//backups//operations/` + * and can be used to track creation of the backup. The + * {@link protos.google.longrunning.Operation.metadata|metadata} field type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} field type is + * {@link protos.google.spanner.admin.database.v1.Backup|Backup}, if successful. + * Cancelling the returned operation will stop the creation and delete the + * backup. There can be only one pending backup creation per database. Backup + * creation of different databases can run concurrently. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the instance in which the backup will be + * created. This must be the same instance that contains the database the + * backup will be created from. The backup will be stored in the + * location(s) specified in the instance configuration of this + * instance. Values are of the form + * `projects//instances/`. + * @param {string} request.backupId + * Required. The id of the backup to be created. The `backup_id` appended to + * `parent` forms the full backup name of the form + * `projects//instances//backups/`. + * @param {google.spanner.admin.database.v1.Backup} request.backup + * Required. The backup to create. + * @param {google.spanner.admin.database.v1.CreateBackupEncryptionConfig} [request.encryptionConfig] + * Optional. The encryption configuration used to encrypt the backup. If this + * field is not specified, the backup will use the same encryption + * configuration as the database by default, namely + * {@link protos.google.spanner.admin.database.v1.CreateBackupEncryptionConfig.encryption_type|encryption_type} + * = `USE_DATABASE_ENCRYPTION`. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + createBackup( + request?: protos.google.spanner.admin.database.v1.ICreateBackupRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createBackup( + request: protos.google.spanner.admin.database.v1.ICreateBackupRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createBackup( + request: protos.google.spanner.admin.database.v1.ICreateBackupRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createBackup( + request?: protos.google.spanner.admin.database.v1.ICreateBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createBackup response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createBackup request %j', request); + return this.innerApiCalls + .createBackup(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createBackup response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `createBackup()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkCreateBackupProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.database.v1.Backup, + protos.google.spanner.admin.database.v1.CreateBackupMetadata + > + > { + this._log.info('createBackup long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createBackup, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.database.v1.Backup, + protos.google.spanner.admin.database.v1.CreateBackupMetadata + >; + } + /** + * Starts copying a Cloud Spanner Backup. + * The returned backup {@link protos.google.longrunning.Operation|long-running operation} + * will have a name of the format + * `projects//instances//backups//operations/` + * and can be used to track copying of the backup. The operation is associated + * with the destination backup. + * The {@link protos.google.longrunning.Operation.metadata|metadata} field type is + * {@link protos.google.spanner.admin.database.v1.CopyBackupMetadata|CopyBackupMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} field type is + * {@link protos.google.spanner.admin.database.v1.Backup|Backup}, if successful. + * Cancelling the returned operation will stop the copying and delete the + * destination backup. Concurrent CopyBackup requests can run on the same + * source backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the destination instance that will contain the backup + * copy. Values are of the form: `projects//instances/`. + * @param {string} request.backupId + * Required. The id of the backup copy. + * The `backup_id` appended to `parent` forms the full backup_uri of the form + * `projects//instances//backups/`. + * @param {string} request.sourceBackup + * Required. The source backup to be copied. + * The source backup needs to be in READY state for it to be copied. + * Once CopyBackup is in progress, the source backup cannot be deleted or + * cleaned up on expiration until CopyBackup is finished. + * Values are of the form: + * `projects//instances//backups/`. + * @param {google.protobuf.Timestamp} request.expireTime + * Required. The expiration time of the backup in microsecond granularity. + * The expiration time must be at least 6 hours and at most 366 days + * from the `create_time` of the source backup. Once the `expire_time` has + * passed, the backup is eligible to be automatically deleted by Cloud Spanner + * to free the resources used by the backup. + * @param {google.spanner.admin.database.v1.CopyBackupEncryptionConfig} [request.encryptionConfig] + * Optional. The encryption configuration used to encrypt the backup. If this + * field is not specified, the backup will use the same encryption + * configuration as the source backup by default, namely + * {@link protos.google.spanner.admin.database.v1.CopyBackupEncryptionConfig.encryption_type|encryption_type} + * = `USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION`. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + copyBackup( + request?: protos.google.spanner.admin.database.v1.ICopyBackupRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + copyBackup( + request: protos.google.spanner.admin.database.v1.ICopyBackupRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + copyBackup( + request: protos.google.spanner.admin.database.v1.ICopyBackupRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + copyBackup( + request?: protos.google.spanner.admin.database.v1.ICopyBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('copyBackup response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('copyBackup request %j', request); + return this.innerApiCalls + .copyBackup(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('copyBackup response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `copyBackup()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkCopyBackupProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.database.v1.Backup, + protos.google.spanner.admin.database.v1.CopyBackupMetadata + > + > { + this._log.info('copyBackup long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.copyBackup, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.database.v1.Backup, + protos.google.spanner.admin.database.v1.CopyBackupMetadata + >; + } + /** + * Create a new database by restoring from a completed backup. The new + * database must be in the same project and in an instance with the same + * instance configuration as the instance containing + * the backup. The returned database [long-running + * operation][google.longrunning.Operation] has a name of the format + * `projects//instances//databases//operations/`, + * and can be used to track the progress of the operation, and to cancel it. + * The {@link protos.google.longrunning.Operation.metadata|metadata} field type is + * {@link protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type + * is {@link protos.google.spanner.admin.database.v1.Database|Database}, if + * successful. Cancelling the returned operation will stop the restore and + * delete the database. + * There can be only one database being restored into an instance at a time. + * Once the restore operation completes, a new restore operation can be + * initiated, without waiting for the optimize operation associated with the + * first restore to complete. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the instance in which to create the + * restored database. This instance must be in the same project and + * have the same instance configuration as the instance containing + * the source backup. Values are of the form + * `projects//instances/`. + * @param {string} request.databaseId + * Required. The id of the database to create and restore to. This + * database must not already exist. The `database_id` appended to + * `parent` forms the full database name of the form + * `projects//instances//databases/`. + * @param {string} request.backup + * Name of the backup from which to restore. Values are of the form + * `projects//instances//backups/`. + * @param {google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig} [request.encryptionConfig] + * Optional. An encryption configuration describing the encryption type and + * key resources in Cloud KMS used to encrypt/decrypt the database to restore + * to. If this field is not specified, the restored database will use the same + * encryption configuration as the backup by default, namely + * {@link protos.google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.encryption_type|encryption_type} + * = `USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION`. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + restoreDatabase( + request?: protos.google.spanner.admin.database.v1.IRestoreDatabaseRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + restoreDatabase( + request: protos.google.spanner.admin.database.v1.IRestoreDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + restoreDatabase( + request: protos.google.spanner.admin.database.v1.IRestoreDatabaseRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + restoreDatabase( + request?: protos.google.spanner.admin.database.v1.IRestoreDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('restoreDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('restoreDatabase request %j', request); + return this.innerApiCalls + .restoreDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('restoreDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkRestoreDatabaseProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.database.v1.Database, + protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata + > + > { + this._log.info('restoreDatabase long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.restoreDatabase, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.database.v1.Database, + protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata + >; + } + /** + * Lists Cloud Spanner databases. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance whose databases should be listed. + * Values are of the form `projects//instances/`. + * @param {number} request.pageSize + * Number of databases to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabasesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabasesResponse|ListDatabasesResponse}. + * @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 Array of {@link protos.google.spanner.admin.database.v1.Database|Database}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDatabasesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDatabases( + request?: protos.google.spanner.admin.database.v1.IListDatabasesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IDatabase[], + protos.google.spanner.admin.database.v1.IListDatabasesRequest | null, + protos.google.spanner.admin.database.v1.IListDatabasesResponse, + ] + >; + listDatabases( + request: protos.google.spanner.admin.database.v1.IListDatabasesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabasesRequest, + | protos.google.spanner.admin.database.v1.IListDatabasesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabase + >, + ): void; + listDatabases( + request: protos.google.spanner.admin.database.v1.IListDatabasesRequest, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabasesRequest, + | protos.google.spanner.admin.database.v1.IListDatabasesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabase + >, + ): void; + listDatabases( + request?: protos.google.spanner.admin.database.v1.IListDatabasesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabasesRequest, + | protos.google.spanner.admin.database.v1.IListDatabasesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabase + >, + callback?: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabasesRequest, + | protos.google.spanner.admin.database.v1.IListDatabasesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabase + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IDatabase[], + protos.google.spanner.admin.database.v1.IListDatabasesRequest | null, + protos.google.spanner.admin.database.v1.IListDatabasesResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabasesRequest, + | protos.google.spanner.admin.database.v1.IListDatabasesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabase + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listDatabases values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listDatabases request %j', request); + return this.innerApiCalls + .listDatabases(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.spanner.admin.database.v1.IDatabase[], + protos.google.spanner.admin.database.v1.IListDatabasesRequest | null, + protos.google.spanner.admin.database.v1.IListDatabasesResponse, + ]) => { + this._log.info('listDatabases values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listDatabases`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance whose databases should be listed. + * Values are of the form `projects//instances/`. + * @param {number} request.pageSize + * Number of databases to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabasesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabasesResponse|ListDatabasesResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.spanner.admin.database.v1.Database|Database} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDatabasesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDatabasesStream( + request?: protos.google.spanner.admin.database.v1.IListDatabasesRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listDatabases']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDatabases stream %j', request); + return this.descriptors.page.listDatabases.createStream( + this.innerApiCalls.listDatabases as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listDatabases`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance whose databases should be listed. + * Values are of the form `projects//instances/`. + * @param {number} request.pageSize + * Number of databases to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabasesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabasesResponse|ListDatabasesResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.spanner.admin.database.v1.Database|Database}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listDatabasesAsync( + request?: protos.google.spanner.admin.database.v1.IListDatabasesRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listDatabases']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDatabases iterate %j', request); + return this.descriptors.page.listDatabases.asyncIterate( + this.innerApiCalls['listDatabases'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists completed and pending backups. + * Backups returned are ordered by `create_time` in descending order, + * starting from the most recent `create_time`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance to list backups from. Values are of the + * form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the + * {@link protos.google.spanner.admin.database.v1.Backup|Backup} are eligible for + * filtering: + * + * * `name` + * * `database` + * * `state` + * * `create_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `expire_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `version_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `size_bytes` + * * `backup_schedules` + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic, but + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `name:Howl` - The backup's name contains the string "howl". + * * `database:prod` + * - The database's name contains the string "prod". + * * `state:CREATING` - The backup is pending creation. + * * `state:READY` - The backup is fully created and ready for use. + * * `(name:howl) AND (create_time < \"2018-03-28T14:50:00Z\")` + * - The backup name contains the string "howl" and `create_time` + * of the backup is before 2018-03-28T14:50:00Z. + * * `expire_time < \"2018-03-28T14:50:00Z\"` + * - The backup `expire_time` is before 2018-03-28T14:50:00Z. + * * `size_bytes > 10000000000` - The backup's size is greater than 10GB + * * `backup_schedules:daily` + * - The backup is created from a schedule with "daily" in its name. + * @param {number} request.pageSize + * Number of backups to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupsResponse|ListBackupsResponse} + * to the same `parent` and with the same `filter`. + * @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 Array of {@link protos.google.spanner.admin.database.v1.Backup|Backup}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBackupsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listBackups( + request?: protos.google.spanner.admin.database.v1.IListBackupsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackup[], + protos.google.spanner.admin.database.v1.IListBackupsRequest | null, + protos.google.spanner.admin.database.v1.IListBackupsResponse, + ] + >; + listBackups( + request: protos.google.spanner.admin.database.v1.IListBackupsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupsRequest, + | protos.google.spanner.admin.database.v1.IListBackupsResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackup + >, + ): void; + listBackups( + request: protos.google.spanner.admin.database.v1.IListBackupsRequest, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupsRequest, + | protos.google.spanner.admin.database.v1.IListBackupsResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackup + >, + ): void; + listBackups( + request?: protos.google.spanner.admin.database.v1.IListBackupsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupsRequest, + | protos.google.spanner.admin.database.v1.IListBackupsResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackup + >, + callback?: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupsRequest, + | protos.google.spanner.admin.database.v1.IListBackupsResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackup + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackup[], + protos.google.spanner.admin.database.v1.IListBackupsRequest | null, + protos.google.spanner.admin.database.v1.IListBackupsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupsRequest, + | protos.google.spanner.admin.database.v1.IListBackupsResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackup + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listBackups values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listBackups request %j', request); + return this.innerApiCalls + .listBackups(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.spanner.admin.database.v1.IBackup[], + protos.google.spanner.admin.database.v1.IListBackupsRequest | null, + protos.google.spanner.admin.database.v1.IListBackupsResponse, + ]) => { + this._log.info('listBackups values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listBackups`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance to list backups from. Values are of the + * form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the + * {@link protos.google.spanner.admin.database.v1.Backup|Backup} are eligible for + * filtering: + * + * * `name` + * * `database` + * * `state` + * * `create_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `expire_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `version_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `size_bytes` + * * `backup_schedules` + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic, but + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `name:Howl` - The backup's name contains the string "howl". + * * `database:prod` + * - The database's name contains the string "prod". + * * `state:CREATING` - The backup is pending creation. + * * `state:READY` - The backup is fully created and ready for use. + * * `(name:howl) AND (create_time < \"2018-03-28T14:50:00Z\")` + * - The backup name contains the string "howl" and `create_time` + * of the backup is before 2018-03-28T14:50:00Z. + * * `expire_time < \"2018-03-28T14:50:00Z\"` + * - The backup `expire_time` is before 2018-03-28T14:50:00Z. + * * `size_bytes > 10000000000` - The backup's size is greater than 10GB + * * `backup_schedules:daily` + * - The backup is created from a schedule with "daily" in its name. + * @param {number} request.pageSize + * Number of backups to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupsResponse|ListBackupsResponse} + * to the same `parent` and with the same `filter`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.spanner.admin.database.v1.Backup|Backup} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBackupsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listBackupsStream( + request?: protos.google.spanner.admin.database.v1.IListBackupsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listBackups']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listBackups stream %j', request); + return this.descriptors.page.listBackups.createStream( + this.innerApiCalls.listBackups as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listBackups`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance to list backups from. Values are of the + * form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the + * {@link protos.google.spanner.admin.database.v1.Backup|Backup} are eligible for + * filtering: + * + * * `name` + * * `database` + * * `state` + * * `create_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `expire_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `version_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + * * `size_bytes` + * * `backup_schedules` + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic, but + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `name:Howl` - The backup's name contains the string "howl". + * * `database:prod` + * - The database's name contains the string "prod". + * * `state:CREATING` - The backup is pending creation. + * * `state:READY` - The backup is fully created and ready for use. + * * `(name:howl) AND (create_time < \"2018-03-28T14:50:00Z\")` + * - The backup name contains the string "howl" and `create_time` + * of the backup is before 2018-03-28T14:50:00Z. + * * `expire_time < \"2018-03-28T14:50:00Z\"` + * - The backup `expire_time` is before 2018-03-28T14:50:00Z. + * * `size_bytes > 10000000000` - The backup's size is greater than 10GB + * * `backup_schedules:daily` + * - The backup is created from a schedule with "daily" in its name. + * @param {number} request.pageSize + * Number of backups to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupsResponse|ListBackupsResponse} + * to the same `parent` and with the same `filter`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.spanner.admin.database.v1.Backup|Backup}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listBackupsAsync( + request?: protos.google.spanner.admin.database.v1.IListBackupsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listBackups']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listBackups iterate %j', request); + return this.descriptors.page.listBackups.asyncIterate( + this.innerApiCalls['listBackups'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists database {@link protos.google.longrunning.Operation|longrunning-operations}. + * A database operation has a name of the form + * `projects//instances//databases//operations/`. + * The long-running operation + * {@link protos.google.longrunning.Operation.metadata|metadata} field type + * `metadata.type_url` describes the type of the metadata. Operations returned + * include those that have completed/failed/canceled within the last 7 days, + * and pending operations. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance of the database operations. + * Values are of the form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.longrunning.Operation|Operation} + * are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata} + * is + * `type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata) AND` \ + * `(metadata.source_type:BACKUP) AND` \ + * `(metadata.backup_info.backup:backup_howl) AND` \ + * `(metadata.name:restored_howl) AND` \ + * `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * * The database is restored from a backup. + * * The backup name contains "backup_howl". + * * The restored database's name contains "restored_howl". + * * The operation started before 2018-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabaseOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabaseOperationsResponse|ListDatabaseOperationsResponse} + * to the same `parent` and with the same `filter`. + * @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 Array of {@link protos.google.longrunning.Operation|Operation}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDatabaseOperationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDatabaseOperations( + request?: protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest | null, + protos.google.spanner.admin.database.v1.IListDatabaseOperationsResponse, + ] + >; + listDatabaseOperations( + request: protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): void; + listDatabaseOperations( + request: protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): void; + listDatabaseOperations( + request?: protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + callback?: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): Promise< + [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest | null, + protos.google.spanner.admin.database.v1.IListDatabaseOperationsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listDatabaseOperations values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listDatabaseOperations request %j', request); + return this.innerApiCalls + .listDatabaseOperations(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest | null, + protos.google.spanner.admin.database.v1.IListDatabaseOperationsResponse, + ]) => { + this._log.info('listDatabaseOperations values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listDatabaseOperations`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance of the database operations. + * Values are of the form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.longrunning.Operation|Operation} + * are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata} + * is + * `type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata) AND` \ + * `(metadata.source_type:BACKUP) AND` \ + * `(metadata.backup_info.backup:backup_howl) AND` \ + * `(metadata.name:restored_howl) AND` \ + * `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * * The database is restored from a backup. + * * The backup name contains "backup_howl". + * * The restored database's name contains "restored_howl". + * * The operation started before 2018-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabaseOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabaseOperationsResponse|ListDatabaseOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.longrunning.Operation|Operation} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDatabaseOperationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDatabaseOperationsStream( + request?: protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listDatabaseOperations']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDatabaseOperations stream %j', request); + return this.descriptors.page.listDatabaseOperations.createStream( + this.innerApiCalls.listDatabaseOperations as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listDatabaseOperations`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance of the database operations. + * Values are of the form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.longrunning.Operation|Operation} + * are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata} + * is + * `type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata) AND` \ + * `(metadata.source_type:BACKUP) AND` \ + * `(metadata.backup_info.backup:backup_howl) AND` \ + * `(metadata.name:restored_howl) AND` \ + * `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * * The database is restored from a backup. + * * The backup name contains "backup_howl". + * * The restored database's name contains "restored_howl". + * * The operation started before 2018-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabaseOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabaseOperationsResponse|ListDatabaseOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.longrunning.Operation|Operation}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listDatabaseOperationsAsync( + request?: protos.google.spanner.admin.database.v1.IListDatabaseOperationsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listDatabaseOperations']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDatabaseOperations iterate %j', request); + return this.descriptors.page.listDatabaseOperations.asyncIterate( + this.innerApiCalls['listDatabaseOperations'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists the backup {@link protos.google.longrunning.Operation|long-running operations} in + * the given instance. A backup operation has a name of the form + * `projects//instances//backups//operations/`. + * The long-running operation + * {@link protos.google.longrunning.Operation.metadata|metadata} field type + * `metadata.type_url` describes the type of the metadata. Operations returned + * include those that have completed/failed/canceled within the last 7 days, + * and pending operations. Operations returned are ordered by + * `operation.metadata.value.progress.start_time` in descending order starting + * from the most recently started operation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance of the backup operations. Values are of + * the form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned backup operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.longrunning.Operation|operation} + * are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata} + * is + * `type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic, but + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `metadata.database:prod` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata}. + * * The source database name of backup contains the string "prod". + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `(metadata.name:howl) AND` \ + * `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata}. + * * The backup name contains the string "howl". + * * The operation started before 2018-03-28T14:50:00Z. + * * The operation resulted in an error. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) AND` \ + * `(metadata.source_backup:test) AND` \ + * `(metadata.progress.start_time < \"2022-01-18T14:50:00Z\") AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CopyBackupMetadata|CopyBackupMetadata}. + * * The source backup name contains the string "test". + * * The operation started before 2022-01-18T14:50:00Z. + * * The operation resulted in an error. + * * `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `(metadata.database:test_db)) OR` \ + * `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) + * AND` \ + * `(metadata.source_backup:test_bkp)) AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata matches either of criteria: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata} + * AND the source database name of the backup contains the string + * "test_db" + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CopyBackupMetadata|CopyBackupMetadata} + * AND the source backup name contains the string "test_bkp" + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupOperationsResponse|ListBackupOperationsResponse} + * to the same `parent` and with the same `filter`. + * @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 Array of {@link protos.google.longrunning.Operation|Operation}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBackupOperationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listBackupOperations( + request?: protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.database.v1.IListBackupOperationsRequest | null, + protos.google.spanner.admin.database.v1.IListBackupOperationsResponse, + ] + >; + listBackupOperations( + request: protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + | protos.google.spanner.admin.database.v1.IListBackupOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): void; + listBackupOperations( + request: protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + | protos.google.spanner.admin.database.v1.IListBackupOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): void; + listBackupOperations( + request?: protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + | protos.google.spanner.admin.database.v1.IListBackupOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + callback?: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + | protos.google.spanner.admin.database.v1.IListBackupOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): Promise< + [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.database.v1.IListBackupOperationsRequest | null, + protos.google.spanner.admin.database.v1.IListBackupOperationsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + | protos.google.spanner.admin.database.v1.IListBackupOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listBackupOperations values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listBackupOperations request %j', request); + return this.innerApiCalls + .listBackupOperations(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.database.v1.IListBackupOperationsRequest | null, + protos.google.spanner.admin.database.v1.IListBackupOperationsResponse, + ]) => { + this._log.info('listBackupOperations values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listBackupOperations`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance of the backup operations. Values are of + * the form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned backup operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.longrunning.Operation|operation} + * are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata} + * is + * `type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic, but + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `metadata.database:prod` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata}. + * * The source database name of backup contains the string "prod". + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `(metadata.name:howl) AND` \ + * `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata}. + * * The backup name contains the string "howl". + * * The operation started before 2018-03-28T14:50:00Z. + * * The operation resulted in an error. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) AND` \ + * `(metadata.source_backup:test) AND` \ + * `(metadata.progress.start_time < \"2022-01-18T14:50:00Z\") AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CopyBackupMetadata|CopyBackupMetadata}. + * * The source backup name contains the string "test". + * * The operation started before 2022-01-18T14:50:00Z. + * * The operation resulted in an error. + * * `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `(metadata.database:test_db)) OR` \ + * `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) + * AND` \ + * `(metadata.source_backup:test_bkp)) AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata matches either of criteria: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata} + * AND the source database name of the backup contains the string + * "test_db" + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CopyBackupMetadata|CopyBackupMetadata} + * AND the source backup name contains the string "test_bkp" + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupOperationsResponse|ListBackupOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.longrunning.Operation|Operation} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBackupOperationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listBackupOperationsStream( + request?: protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listBackupOperations']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listBackupOperations stream %j', request); + return this.descriptors.page.listBackupOperations.createStream( + this.innerApiCalls.listBackupOperations as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listBackupOperations`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance of the backup operations. Values are of + * the form `projects//instances/`. + * @param {string} request.filter + * An expression that filters the list of returned backup operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.longrunning.Operation|operation} + * are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata} + * is + * `type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic, but + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `metadata.database:prod` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata}. + * * The source database name of backup contains the string "prod". + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `(metadata.name:howl) AND` \ + * `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata}. + * * The backup name contains the string "howl". + * * The operation started before 2018-03-28T14:50:00Z. + * * The operation resulted in an error. + * * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) AND` \ + * `(metadata.source_backup:test) AND` \ + * `(metadata.progress.start_time < \"2022-01-18T14:50:00Z\") AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CopyBackupMetadata|CopyBackupMetadata}. + * * The source backup name contains the string "test". + * * The operation started before 2022-01-18T14:50:00Z. + * * The operation resulted in an error. + * * `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + * `(metadata.database:test_db)) OR` \ + * `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) + * AND` \ + * `(metadata.source_backup:test_bkp)) AND` \ + * `(error:*)` - Returns operations where: + * * The operation's metadata matches either of criteria: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CreateBackupMetadata|CreateBackupMetadata} + * AND the source database name of the backup contains the string + * "test_db" + * * The operation's metadata type is + * {@link protos.google.spanner.admin.database.v1.CopyBackupMetadata|CopyBackupMetadata} + * AND the source backup name contains the string "test_bkp" + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupOperationsResponse|ListBackupOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.longrunning.Operation|Operation}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listBackupOperationsAsync( + request?: protos.google.spanner.admin.database.v1.IListBackupOperationsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listBackupOperations']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listBackupOperations iterate %j', request); + return this.descriptors.page.listBackupOperations.asyncIterate( + this.innerApiCalls['listBackupOperations'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists Cloud Spanner database roles. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The database whose roles should be listed. + * Values are of the form + * `projects//instances//databases/`. + * @param {number} request.pageSize + * Number of database roles to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabaseRolesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabaseRolesResponse|ListDatabaseRolesResponse}. + * @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 Array of {@link protos.google.spanner.admin.database.v1.DatabaseRole|DatabaseRole}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDatabaseRolesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDatabaseRoles( + request?: protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IDatabaseRole[], + protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest | null, + protos.google.spanner.admin.database.v1.IListDatabaseRolesResponse, + ] + >; + listDatabaseRoles( + request: protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseRolesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabaseRole + >, + ): void; + listDatabaseRoles( + request: protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseRolesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabaseRole + >, + ): void; + listDatabaseRoles( + request?: protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseRolesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabaseRole + >, + callback?: PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseRolesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabaseRole + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IDatabaseRole[], + protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest | null, + protos.google.spanner.admin.database.v1.IListDatabaseRolesResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + | protos.google.spanner.admin.database.v1.IListDatabaseRolesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IDatabaseRole + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listDatabaseRoles values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listDatabaseRoles request %j', request); + return this.innerApiCalls + .listDatabaseRoles(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.spanner.admin.database.v1.IDatabaseRole[], + protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest | null, + protos.google.spanner.admin.database.v1.IListDatabaseRolesResponse, + ]) => { + this._log.info('listDatabaseRoles values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listDatabaseRoles`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The database whose roles should be listed. + * Values are of the form + * `projects//instances//databases/`. + * @param {number} request.pageSize + * Number of database roles to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabaseRolesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabaseRolesResponse|ListDatabaseRolesResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.spanner.admin.database.v1.DatabaseRole|DatabaseRole} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDatabaseRolesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listDatabaseRolesStream( + request?: protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listDatabaseRoles']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDatabaseRoles stream %j', request); + return this.descriptors.page.listDatabaseRoles.createStream( + this.innerApiCalls.listDatabaseRoles as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listDatabaseRoles`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The database whose roles should be listed. + * Values are of the form + * `projects//instances//databases/`. + * @param {number} request.pageSize + * Number of database roles to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListDatabaseRolesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListDatabaseRolesResponse|ListDatabaseRolesResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.spanner.admin.database.v1.DatabaseRole|DatabaseRole}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listDatabaseRolesAsync( + request?: protos.google.spanner.admin.database.v1.IListDatabaseRolesRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listDatabaseRoles']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listDatabaseRoles iterate %j', request); + return this.descriptors.page.listDatabaseRoles.asyncIterate( + this.innerApiCalls['listDatabaseRoles'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists all the backup schedules for the database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Database is the parent resource whose backup schedules should be + * listed. Values are of the form + * projects//instances//databases/ + * @param {number} [request.pageSize] + * Optional. Number of backup schedules to be returned in the response. If 0 + * or less, defaults to the server's maximum allowed page size. + * @param {string} [request.pageToken] + * Optional. If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupSchedulesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse} + * to the same `parent`. + * @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 Array of {@link protos.google.spanner.admin.database.v1.BackupSchedule|BackupSchedule}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listBackupSchedulesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listBackupSchedules( + request?: protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackupSchedule[], + protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest | null, + protos.google.spanner.admin.database.v1.IListBackupSchedulesResponse, + ] + >; + listBackupSchedules( + request: protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + | protos.google.spanner.admin.database.v1.IListBackupSchedulesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackupSchedule + >, + ): void; + listBackupSchedules( + request: protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + callback: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + | protos.google.spanner.admin.database.v1.IListBackupSchedulesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackupSchedule + >, + ): void; + listBackupSchedules( + request?: protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + | protos.google.spanner.admin.database.v1.IListBackupSchedulesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackupSchedule + >, + callback?: PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + | protos.google.spanner.admin.database.v1.IListBackupSchedulesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackupSchedule + >, + ): Promise< + [ + protos.google.spanner.admin.database.v1.IBackupSchedule[], + protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest | null, + protos.google.spanner.admin.database.v1.IListBackupSchedulesResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + | protos.google.spanner.admin.database.v1.IListBackupSchedulesResponse + | null + | undefined, + protos.google.spanner.admin.database.v1.IBackupSchedule + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listBackupSchedules values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listBackupSchedules request %j', request); + return this.innerApiCalls + .listBackupSchedules(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.spanner.admin.database.v1.IBackupSchedule[], + protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest | null, + protos.google.spanner.admin.database.v1.IListBackupSchedulesResponse, + ]) => { + this._log.info('listBackupSchedules values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listBackupSchedules`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Database is the parent resource whose backup schedules should be + * listed. Values are of the form + * projects//instances//databases/ + * @param {number} [request.pageSize] + * Optional. Number of backup schedules to be returned in the response. If 0 + * or less, defaults to the server's maximum allowed page size. + * @param {string} [request.pageToken] + * Optional. If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupSchedulesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse} + * to the same `parent`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.spanner.admin.database.v1.BackupSchedule|BackupSchedule} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listBackupSchedulesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listBackupSchedulesStream( + request?: protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listBackupSchedules']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listBackupSchedules stream %j', request); + return this.descriptors.page.listBackupSchedules.createStream( + this.innerApiCalls.listBackupSchedules as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listBackupSchedules`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Database is the parent resource whose backup schedules should be + * listed. Values are of the form + * projects//instances//databases/ + * @param {number} [request.pageSize] + * Optional. Number of backup schedules to be returned in the response. If 0 + * or less, defaults to the server's maximum allowed page size. + * @param {string} [request.pageToken] + * Optional. If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.database.v1.ListBackupSchedulesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.database.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse} + * to the same `parent`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.spanner.admin.database.v1.BackupSchedule|BackupSchedule}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listBackupSchedulesAsync( + request?: protos.google.spanner.admin.database.v1.IListBackupSchedulesRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listBackupSchedules']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listBackupSchedules iterate %j', request); + return this.descriptors.page.listBackupSchedules.asyncIterate( + this.innerApiCalls['listBackupSchedules'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation( + request: protos.google.longrunning.GetOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + ): Promise<[protos.google.longrunning.Operation]> { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.getOperation(request, options, callback); + } + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | iteration protocols}. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync( + request: protos.google.longrunning.ListOperationsRequest, + options?: gax.CallOptions, + ): AsyncIterable { + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.listOperationsAsync(request, options); + } + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation( + request: protos.google.longrunning.CancelOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + callback?: Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + ): Promise { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.cancelOperation(request, options, callback); + } + + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation( + request: protos.google.longrunning.DeleteOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + ): Promise { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.deleteOperation(request, options, callback); + } + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified backup resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} backup + * @returns {string} Resource name string. + */ + backupPath(project: string, instance: string, backup: string) { + return this.pathTemplates.backupPathTemplate.render({ + project: project, + instance: instance, + backup: backup, + }); + } + + /** + * Parse the project from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).project; + } + + /** + * Parse the instance from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).instance; + } + + /** + * Parse the backup from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the backup. + */ + matchBackupFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).backup; + } + + /** + * Return a fully-qualified backupSchedule resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @param {string} schedule + * @returns {string} Resource name string. + */ + backupSchedulePath( + project: string, + instance: string, + database: string, + schedule: string, + ) { + return this.pathTemplates.backupSchedulePathTemplate.render({ + project: project, + instance: instance, + database: database, + schedule: schedule, + }); + } + + /** + * Parse the project from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).project; + } + + /** + * Parse the instance from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).instance; + } + + /** + * Parse the database from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).database; + } + + /** + * Parse the schedule from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the schedule. + */ + matchScheduleFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).schedule; + } + + /** + * Return a fully-qualified cryptoKey resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} key_ring + * @param {string} crypto_key + * @returns {string} Resource name string. + */ + cryptoKeyPath( + project: string, + location: string, + keyRing: string, + cryptoKey: string, + ) { + return this.pathTemplates.cryptoKeyPathTemplate.render({ + project: project, + location: location, + key_ring: keyRing, + crypto_key: cryptoKey, + }); + } + + /** + * Parse the project from CryptoKey resource. + * + * @param {string} cryptoKeyName + * A fully-qualified path representing CryptoKey resource. + * @returns {string} A string representing the project. + */ + matchProjectFromCryptoKeyName(cryptoKeyName: string) { + return this.pathTemplates.cryptoKeyPathTemplate.match(cryptoKeyName) + .project; + } + + /** + * Parse the location from CryptoKey resource. + * + * @param {string} cryptoKeyName + * A fully-qualified path representing CryptoKey resource. + * @returns {string} A string representing the location. + */ + matchLocationFromCryptoKeyName(cryptoKeyName: string) { + return this.pathTemplates.cryptoKeyPathTemplate.match(cryptoKeyName) + .location; + } + + /** + * Parse the key_ring from CryptoKey resource. + * + * @param {string} cryptoKeyName + * A fully-qualified path representing CryptoKey resource. + * @returns {string} A string representing the key_ring. + */ + matchKeyRingFromCryptoKeyName(cryptoKeyName: string) { + return this.pathTemplates.cryptoKeyPathTemplate.match(cryptoKeyName) + .key_ring; + } + + /** + * Parse the crypto_key from CryptoKey resource. + * + * @param {string} cryptoKeyName + * A fully-qualified path representing CryptoKey resource. + * @returns {string} A string representing the crypto_key. + */ + matchCryptoKeyFromCryptoKeyName(cryptoKeyName: string) { + return this.pathTemplates.cryptoKeyPathTemplate.match(cryptoKeyName) + .crypto_key; + } + + /** + * Return a fully-qualified database resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @returns {string} Resource name string. + */ + databasePath(project: string, instance: string, database: string) { + return this.pathTemplates.databasePathTemplate.render({ + project: project, + instance: instance, + database: database, + }); + } + + /** + * Parse the project from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).project; + } + + /** + * Parse the instance from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).instance; + } + + /** + * Parse the database from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).database; + } + + /** + * Return a fully-qualified databaseRole resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @param {string} role + * @returns {string} Resource name string. + */ + databaseRolePath( + project: string, + instance: string, + database: string, + role: string, + ) { + return this.pathTemplates.databaseRolePathTemplate.render({ + project: project, + instance: instance, + database: database, + role: role, + }); + } + + /** + * Parse the project from DatabaseRole resource. + * + * @param {string} databaseRoleName + * A fully-qualified path representing DatabaseRole resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseRoleName(databaseRoleName: string) { + return this.pathTemplates.databaseRolePathTemplate.match(databaseRoleName) + .project; + } + + /** + * Parse the instance from DatabaseRole resource. + * + * @param {string} databaseRoleName + * A fully-qualified path representing DatabaseRole resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromDatabaseRoleName(databaseRoleName: string) { + return this.pathTemplates.databaseRolePathTemplate.match(databaseRoleName) + .instance; + } + + /** + * Parse the database from DatabaseRole resource. + * + * @param {string} databaseRoleName + * A fully-qualified path representing DatabaseRole resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseRoleName(databaseRoleName: string) { + return this.pathTemplates.databaseRolePathTemplate.match(databaseRoleName) + .database; + } + + /** + * Parse the role from DatabaseRole resource. + * + * @param {string} databaseRoleName + * A fully-qualified path representing DatabaseRole resource. + * @returns {string} A string representing the role. + */ + matchRoleFromDatabaseRoleName(databaseRoleName: string) { + return this.pathTemplates.databaseRolePathTemplate.match(databaseRoleName) + .role; + } + + /** + * Return a fully-qualified instance resource name string. + * + * @param {string} project + * @param {string} instance + * @returns {string} Resource name string. + */ + instancePath(project: string, instance: string) { + return this.pathTemplates.instancePathTemplate.render({ + project: project, + instance: instance, + }); + } + + /** + * Parse the project from Instance resource. + * + * @param {string} instanceName + * A fully-qualified path representing Instance resource. + * @returns {string} A string representing the project. + */ + matchProjectFromInstanceName(instanceName: string) { + return this.pathTemplates.instancePathTemplate.match(instanceName).project; + } + + /** + * Parse the instance from Instance resource. + * + * @param {string} instanceName + * A fully-qualified path representing Instance resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromInstanceName(instanceName: string) { + return this.pathTemplates.instancePathTemplate.match(instanceName).instance; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.databaseAdminStub && !this._terminated) { + return this.databaseAdminStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + void this.operationsClient.close(); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/spanner/src/v1/database_admin_client_config.json b/handwritten/spanner/src/v1/database_admin_client_config.json new file mode 100644 index 00000000000..5b58878bcb1 --- /dev/null +++ b/handwritten/spanner/src/v1/database_admin_client_config.json @@ -0,0 +1,169 @@ +{ + "interfaces": { + "google.spanner.admin.database.v1.DatabaseAdmin": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + }, + "e9fafda332ce8a1702dc1575de3ca81c4feb4799": { + "initial_retry_delay_millis": 1000, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 32000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "ListDatabases": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "CreateDatabase": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetDatabase": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "UpdateDatabase": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "UpdateDatabaseDdl": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "DropDatabase": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "GetDatabaseDdl": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "SetIamPolicy": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "TestIamPermissions": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateBackup": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CopyBackup": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetBackup": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "UpdateBackup": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "DeleteBackup": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "ListBackups": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "RestoreDatabase": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListDatabaseOperations": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "ListBackupOperations": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "ListDatabaseRoles": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "AddSplitPoints": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "CreateBackupSchedule": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "GetBackupSchedule": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "UpdateBackupSchedule": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "DeleteBackupSchedule": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "ListBackupSchedules": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "InternalUpdateGraphOperation": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/spanner/src/v1/database_admin_proto_list.json b/handwritten/spanner/src/v1/database_admin_proto_list.json new file mode 100644 index 00000000000..8d5db481c20 --- /dev/null +++ b/handwritten/spanner/src/v1/database_admin_proto_list.json @@ -0,0 +1,6 @@ +[ + "../../protos/google/spanner/admin/database/v1/backup.proto", + "../../protos/google/spanner/admin/database/v1/backup_schedule.proto", + "../../protos/google/spanner/admin/database/v1/common.proto", + "../../protos/google/spanner/admin/database/v1/spanner_database_admin.proto" +] diff --git a/handwritten/spanner/src/v1/gapic_metadata.json b/handwritten/spanner/src/v1/gapic_metadata.json new file mode 100644 index 00000000000..fd7e7f8cc29 --- /dev/null +++ b/handwritten/spanner/src/v1/gapic_metadata.json @@ -0,0 +1,27 @@ +{ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "typescript", + "protoPackage": "google.spanner.executor.v1", + "libraryPackage": "@google-cloud/executor", + "services": { + "SpannerExecutorProxy": { + "clients": { + "grpc": { + "libraryClient": "SpannerExecutorProxyClient", + "rpcs": { + "ExecuteActionAsync": { + "methods": [ + "executeActionAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "SpannerExecutorProxyClient", + "rpcs": {} + } + } + } + } +} diff --git a/handwritten/spanner/src/v1/index.ts b/handwritten/spanner/src/v1/index.ts new file mode 100644 index 00000000000..d079433882d --- /dev/null +++ b/handwritten/spanner/src/v1/index.ts @@ -0,0 +1,22 @@ +// Copyright 2020 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +export {SpannerClient} from './spanner_client'; +export {DatabaseAdminClient} from './database_admin_client'; +export {InstanceAdminClient} from './instance_admin_client'; +export {SpannerExecutorProxyClient} from './spanner_executor_proxy_client'; diff --git a/handwritten/spanner/src/v1/instance_admin_client.ts b/handwritten/spanner/src/v1/instance_admin_client.ts new file mode 100644 index 00000000000..88d5796a1d7 --- /dev/null +++ b/handwritten/spanner/src/v1/instance_admin_client.ts @@ -0,0 +1,5446 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/instance_admin_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './instance_admin_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Cloud Spanner Instance Admin API + * + * The Cloud Spanner Instance Admin API can be used to create, delete, + * modify and list instances. Instances are dedicated Cloud Spanner serving + * and storage resources to be used by Cloud Spanner databases. + * + * Each instance has a "configuration", which dictates where the + * serving resources for the Cloud Spanner instance are located (e.g., + * US-central, Europe). Configurations are created by Google based on + * resource availability. + * + * Cloud Spanner billing is based on the instances that exist and their + * sizes. After an instance exists, there are no additional + * per-database or per-operation charges for use of the instance + * (though there may be additional network bandwidth charges). + * Instances offer isolation: problems with databases in one instance + * will not affect other instances. However, within an instance + * databases can affect each other. For example, if one database in an + * instance receives a lot of requests and consumes most of the + * instance resources, fewer resources are available for other + * databases in that instance, and their performance may suffer. + * @class + * @memberof v1 + */ +export class InstanceAdminClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('spanner'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + operationsClient: gax.OperationsClient; + instanceAdminStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of InstanceAdminClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new InstanceAdminClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof InstanceAdminClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; + this._servicePath = 'spanner.' + this._universeDomain; + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = + opts?.fallback ?? + (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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + instancePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}', + ), + instanceConfigPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instanceConfigs/{instance_config}', + ), + instancePartitionPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/instancePartitions/{instance_partition}', + ), + projectPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}', + ), + }; + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listInstanceConfigs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'instanceConfigs', + ), + listInstanceConfigOperations: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'operations', + ), + listInstances: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'instances', + ), + listInstancePartitions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'instancePartitions', + ), + listInstancePartitionOperations: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'operations', + ), + }; + + const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); + // This API contains "long-running operations", which return a + // an Operation object that allows for tracking of the operation, + // rather than holding a request open. + const lroOptions: GrpcClientOptions = { + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, + }; + if (opts.fallback) { + lroOptions.protoJson = protoFilesRoot; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1/{name=projects/*/instances/*/databases/*/operations/*}:cancel', + additional_bindings: [ + {post: '/v1/{name=projects/*/instances/*/operations/*}:cancel'}, + { + post: '/v1/{name=projects/*/instances/*/backups/*/operations/*}:cancel', + }, + { + post: '/v1/{name=projects/*/instances/*/instancePartitions/*/operations/*}:cancel', + }, + { + post: '/v1/{name=projects/*/instanceConfigs/*/operations/*}:cancel', + }, + { + post: '/v1/{name=projects/*/instanceConfigs/*/ssdCaches/*/operations/*}:cancel', + }, + ], + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1/{name=projects/*/instances/*/databases/*/operations/*}', + additional_bindings: [ + {delete: '/v1/{name=projects/*/instances/*/operations/*}'}, + { + delete: + '/v1/{name=projects/*/instances/*/backups/*/operations/*}', + }, + { + delete: + '/v1/{name=projects/*/instances/*/instancePartitions/*/operations/*}', + }, + {delete: '/v1/{name=projects/*/instanceConfigs/*/operations/*}'}, + { + delete: + '/v1/{name=projects/*/instanceConfigs/*/ssdCaches/*/operations/*}', + }, + ], + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1/{name=projects/*/instances/*/databases/*/operations/*}', + additional_bindings: [ + {get: '/v1/{name=projects/*/instances/*/operations/*}'}, + {get: '/v1/{name=projects/*/instances/*/backups/*/operations/*}'}, + { + get: '/v1/{name=projects/*/instances/*/instancePartitions/*/operations/*}', + }, + {get: '/v1/{name=projects/*/instanceConfigs/*/operations/*}'}, + { + get: '/v1/{name=projects/*/instanceConfigs/*/ssdCaches/*/operations/*}', + }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1/{name=projects/*/instances/*/databases/*/operations}', + additional_bindings: [ + {get: '/v1/{name=projects/*/instances/*/operations}'}, + {get: '/v1/{name=projects/*/instances/*/backups/*/operations}'}, + { + get: '/v1/{name=projects/*/instances/*/instancePartitions/*/operations}', + }, + {get: '/v1/{name=projects/*/instanceConfigs/*/operations}'}, + { + get: '/v1/{name=projects/*/instanceConfigs/*/ssdCaches/*/operations}', + }, + ], + }, + ]; + } + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); + const createInstanceConfigResponse = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.InstanceConfig', + ) as gax.protobuf.Type; + const createInstanceConfigMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata', + ) as gax.protobuf.Type; + const updateInstanceConfigResponse = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.InstanceConfig', + ) as gax.protobuf.Type; + const updateInstanceConfigMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata', + ) as gax.protobuf.Type; + const createInstanceResponse = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.Instance', + ) as gax.protobuf.Type; + const createInstanceMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.CreateInstanceMetadata', + ) as gax.protobuf.Type; + const updateInstanceResponse = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.Instance', + ) as gax.protobuf.Type; + const updateInstanceMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.UpdateInstanceMetadata', + ) as gax.protobuf.Type; + const createInstancePartitionResponse = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.InstancePartition', + ) as gax.protobuf.Type; + const createInstancePartitionMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata', + ) as gax.protobuf.Type; + const updateInstancePartitionResponse = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.InstancePartition', + ) as gax.protobuf.Type; + const updateInstancePartitionMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata', + ) as gax.protobuf.Type; + const moveInstanceResponse = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.MoveInstanceResponse', + ) as gax.protobuf.Type; + const moveInstanceMetadata = protoFilesRoot.lookup( + '.google.spanner.admin.instance.v1.MoveInstanceMetadata', + ) as gax.protobuf.Type; + + this.descriptors.longrunning = { + createInstanceConfig: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createInstanceConfigResponse.decode.bind(createInstanceConfigResponse), + createInstanceConfigMetadata.decode.bind(createInstanceConfigMetadata), + ), + updateInstanceConfig: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + updateInstanceConfigResponse.decode.bind(updateInstanceConfigResponse), + updateInstanceConfigMetadata.decode.bind(updateInstanceConfigMetadata), + ), + createInstance: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createInstanceResponse.decode.bind(createInstanceResponse), + createInstanceMetadata.decode.bind(createInstanceMetadata), + ), + updateInstance: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + updateInstanceResponse.decode.bind(updateInstanceResponse), + updateInstanceMetadata.decode.bind(updateInstanceMetadata), + ), + createInstancePartition: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + createInstancePartitionResponse.decode.bind( + createInstancePartitionResponse, + ), + createInstancePartitionMetadata.decode.bind( + createInstancePartitionMetadata, + ), + ), + updateInstancePartition: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + updateInstancePartitionResponse.decode.bind( + updateInstancePartitionResponse, + ), + updateInstancePartitionMetadata.decode.bind( + updateInstancePartitionMetadata, + ), + ), + moveInstance: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + moveInstanceResponse.decode.bind(moveInstanceResponse), + moveInstanceMetadata.decode.bind(moveInstanceMetadata), + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.spanner.admin.instance.v1.InstanceAdmin', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')}, + ); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.instanceAdminStub) { + return this.instanceAdminStub; + } + + // Put together the "service stub" for + // google.spanner.admin.instance.v1.InstanceAdmin. + this.instanceAdminStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.spanner.admin.instance.v1.InstanceAdmin', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.spanner.admin.instance.v1.InstanceAdmin, + this._opts, + this._providedCustomServicePath, + ) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const instanceAdminStubMethods = [ + 'listInstanceConfigs', + 'getInstanceConfig', + 'createInstanceConfig', + 'updateInstanceConfig', + 'deleteInstanceConfig', + 'listInstanceConfigOperations', + 'listInstances', + 'listInstancePartitions', + 'getInstance', + 'createInstance', + 'updateInstance', + 'deleteInstance', + 'setIamPolicy', + 'getIamPolicy', + 'testIamPermissions', + 'getInstancePartition', + 'createInstancePartition', + 'deleteInstancePartition', + 'updateInstancePartition', + 'listInstancePartitionOperations', + 'moveInstance', + ]; + for (const methodName of instanceAdminStubMethods) { + const callPromise = this.instanceAdminStub.then( + stub => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = + this.descriptors.page[methodName] || + this.descriptors.longrunning[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.instanceAdminStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'spanner.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'spanner.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.admin', + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId( + callback?: Callback, + ): Promise | void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + /** + * Gets information about a particular instance configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the requested instance configuration. Values are of + * the form `projects//instanceConfigs/`. + * @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.spanner.admin.instance.v1.InstanceConfig|InstanceConfig}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getInstanceConfig( + request?: protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstanceConfig, + ( + | protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest + | undefined + ), + {} | undefined, + ] + >; + getInstanceConfig( + request: protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + | protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getInstanceConfig( + request: protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest, + callback: Callback< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + | protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getInstanceConfig( + request?: protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + | protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + | protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstanceConfig, + ( + | protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getInstanceConfig request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + | protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getInstanceConfig response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getInstanceConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.instance.v1.IInstanceConfig, + ( + | protos.google.spanner.admin.instance.v1.IGetInstanceConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getInstanceConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes the instance configuration. Deletion is only allowed when no + * instances are using the configuration. If any instances are using + * the configuration, returns `FAILED_PRECONDITION`. + * + * Only user-managed configurations can be deleted. + * + * Authorization requires `spanner.instanceConfigs.delete` permission on + * the resource {@link protos.google.spanner.admin.instance.v1.InstanceConfig.name|name}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the instance configuration to be deleted. + * Values are of the form + * `projects//instanceConfigs/` + * @param {string} request.etag + * Used for optimistic concurrency control as a way to help prevent + * simultaneous deletes of an instance configuration from overwriting each + * other. If not empty, the API + * only deletes the instance configuration when the etag provided matches the + * current status of the requested instance configuration. Otherwise, deletes + * the instance configuration without checking the current status of the + * requested instance configuration. + * @param {boolean} request.validateOnly + * An option to validate, but not actually execute, a request, + * and provide the same response. + * @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.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. + */ + deleteInstanceConfig( + request?: protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest + | undefined + ), + {} | undefined, + ] + >; + deleteInstanceConfig( + request: protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteInstanceConfig( + request: protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteInstanceConfig( + request?: protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteInstanceConfig request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteInstanceConfig response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteInstanceConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstanceConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteInstanceConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets information about a particular instance. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the requested instance. Values are of the form + * `projects//instances/`. + * @param {google.protobuf.FieldMask} request.fieldMask + * If field_mask is present, specifies the subset of + * {@link protos.google.spanner.admin.instance.v1.Instance|Instance} fields that should be + * returned. If absent, all + * {@link protos.google.spanner.admin.instance.v1.Instance|Instance} fields are returned. + * @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.spanner.admin.instance.v1.Instance|Instance}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getInstance( + request?: protos.google.spanner.admin.instance.v1.IGetInstanceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IGetInstanceRequest | undefined, + {} | undefined, + ] + >; + getInstance( + request: protos.google.spanner.admin.instance.v1.IGetInstanceRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.instance.v1.IInstance, + | protos.google.spanner.admin.instance.v1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getInstance( + request: protos.google.spanner.admin.instance.v1.IGetInstanceRequest, + callback: Callback< + protos.google.spanner.admin.instance.v1.IInstance, + | protos.google.spanner.admin.instance.v1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getInstance( + request?: protos.google.spanner.admin.instance.v1.IGetInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.instance.v1.IInstance, + | protos.google.spanner.admin.instance.v1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.instance.v1.IInstance, + | protos.google.spanner.admin.instance.v1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IGetInstanceRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getInstance request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.instance.v1.IInstance, + | protos.google.spanner.admin.instance.v1.IGetInstanceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getInstance response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getInstance(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.instance.v1.IInstance, + ( + | protos.google.spanner.admin.instance.v1.IGetInstanceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getInstance response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes an instance. + * + * Immediately upon completion of the request: + * + * * Billing ceases for all of the instance's reserved resources. + * + * Soon afterward: + * + * * The instance and *all of its databases* immediately and + * irrevocably disappear from the API. All data in the databases + * is permanently deleted. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the instance to be deleted. Values are of the form + * `projects//instances/` + * @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.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. + */ + deleteInstance( + request?: protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest + | undefined + ), + {} | undefined, + ] + >; + deleteInstance( + request: protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteInstance( + request: protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteInstance( + request?: protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteInstance request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteInstance response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteInstance(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstanceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteInstance response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Sets the access control policy on an instance resource. Replaces any + * existing policy. + * + * Authorization requires `spanner.instances.setIamPolicy` on + * {@link protos.google.iam.v1.SetIamPolicyRequest.resource|resource}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being specified. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.Policy} request.policy + * REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @param {google.protobuf.FieldMask} request.updateMask + * OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only + * the fields in the mask will be modified. If no mask is provided, the + * following default mask is used: + * + * `paths: "bindings, etag"` + * @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.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + setIamPolicy( + request?: protos.google.iam.v1.ISetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ] + >; + setIamPolicy( + request: protos.google.iam.v1.ISetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; + setIamPolicy( + request: protos.google.iam.v1.ISetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; + setIamPolicy( + request?: protos.google.iam.v1.ISetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('setIamPolicy request %j', request); + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('setIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .setIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.ISetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('setIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets the access control policy for an instance resource. Returns an empty + * policy if an instance exists but does not have a policy set. + * + * Authorization requires `spanner.instances.getIamPolicy` on + * {@link protos.google.iam.v1.GetIamPolicyRequest.resource|resource}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {google.iam.v1.GetPolicyOptions} request.options + * OPTIONAL: A `GetPolicyOptions` object for specifying options to + * `GetIamPolicy`. + * @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.iam.v1.Policy|Policy}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getIamPolicy( + request?: protos.google.iam.v1.IGetIamPolicyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + >; + getIamPolicy( + request: protos.google.iam.v1.IGetIamPolicyRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; + getIamPolicy( + request: protos.google.iam.v1.IGetIamPolicyRequest, + callback: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): void; + getIamPolicy( + request?: protos.google.iam.v1.IGetIamPolicyRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getIamPolicy request %j', request); + const wrappedCallback: + | Callback< + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getIamPolicy(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.IPolicy, + protos.google.iam.v1.IGetIamPolicyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Returns permissions that the caller has on the specified instance resource. + * + * Attempting this RPC on a non-existent Cloud Spanner instance resource will + * result in a NOT_FOUND error if the user has `spanner.instances.list` + * permission on the containing Google Cloud Project. Otherwise returns an + * empty set of permissions. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * See the operation documentation for the appropriate value for this field. + * @param {string[]} request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @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.iam.v1.TestIamPermissionsResponse|TestIamPermissionsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + testIamPermissions( + request?: protos.google.iam.v1.ITestIamPermissionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ] + >; + testIamPermissions( + request: protos.google.iam.v1.ITestIamPermissionsRequest, + options: CallOptions, + callback: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): void; + testIamPermissions( + request: protos.google.iam.v1.ITestIamPermissionsRequest, + callback: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): void; + testIamPermissions( + request?: protos.google.iam.v1.ITestIamPermissionsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + resource: request.resource ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('testIamPermissions request %j', request); + const wrappedCallback: + | Callback< + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('testIamPermissions response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .testIamPermissions(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.iam.v1.ITestIamPermissionsResponse, + protos.google.iam.v1.ITestIamPermissionsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('testIamPermissions response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets information about a particular instance partition. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the requested instance partition. Values are of + * the form + * `projects/{project}/instances/{instance}/instancePartitions/{instance_partition}`. + * @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.spanner.admin.instance.v1.InstancePartition|InstancePartition}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getInstancePartition( + request?: protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstancePartition, + ( + | protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest + | undefined + ), + {} | undefined, + ] + >; + getInstancePartition( + request: protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.admin.instance.v1.IInstancePartition, + | protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getInstancePartition( + request: protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest, + callback: Callback< + protos.google.spanner.admin.instance.v1.IInstancePartition, + | protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getInstancePartition( + request?: protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.admin.instance.v1.IInstancePartition, + | protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.admin.instance.v1.IInstancePartition, + | protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstancePartition, + ( + | protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getInstancePartition request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.admin.instance.v1.IInstancePartition, + | protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getInstancePartition response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getInstancePartition(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.admin.instance.v1.IInstancePartition, + ( + | protos.google.spanner.admin.instance.v1.IGetInstancePartitionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getInstancePartition response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Deletes an existing instance partition. Requires that the + * instance partition is not used by any database or backup and is not the + * default instance partition of an instance. + * + * Authorization requires `spanner.instancePartitions.delete` permission on + * the resource + * {@link protos.google.spanner.admin.instance.v1.InstancePartition.name|name}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the instance partition to be deleted. + * Values are of the form + * `projects/{project}/instances/{instance}/instancePartitions/{instance_partition}` + * @param {string} request.etag + * Optional. If not empty, the API only deletes the instance partition when + * the etag provided matches the current status of the requested instance + * partition. Otherwise, deletes the instance partition without checking the + * current status of the requested instance partition. + * @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.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. + */ + deleteInstancePartition( + request?: protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest + | undefined + ), + {} | undefined, + ] + >; + deleteInstancePartition( + request: protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteInstancePartition( + request: protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + deleteInstancePartition( + request?: protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest + | undefined + ), + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteInstancePartition request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteInstancePartition response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteInstancePartition(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.spanner.admin.instance.v1.IDeleteInstancePartitionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteInstancePartition response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + + /** + * Creates an instance configuration and begins preparing it to be used. The + * returned long-running operation + * can be used to track the progress of preparing the new + * instance configuration. The instance configuration name is assigned by the + * caller. If the named instance configuration already exists, + * `CreateInstanceConfig` returns `ALREADY_EXISTS`. + * + * Immediately after the request returns: + * + * * The instance configuration is readable via the API, with all requested + * attributes. The instance configuration's + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig.reconciling|reconciling} + * field is set to true. Its state is `CREATING`. + * + * While the operation is pending: + * + * * Cancelling the operation renders the instance configuration immediately + * unreadable via the API. + * * Except for deleting the creating resource, all other attempts to modify + * the instance configuration are rejected. + * + * Upon completion of the returned operation: + * + * * Instances can be created using the instance configuration. + * * The instance configuration's + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig.reconciling|reconciling} + * field becomes false. Its state becomes `READY`. + * + * The returned long-running operation will + * have a name of the format + * `/operations/` and can be used to track + * creation of the instance configuration. The + * metadata field type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata|CreateInstanceConfigMetadata}. + * The response field type is + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig|InstanceConfig}, if + * successful. + * + * Authorization requires `spanner.instanceConfigs.create` permission on + * the resource + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceConfigRequest.parent|parent}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project in which to create the instance + * configuration. Values are of the form `projects/`. + * @param {string} request.instanceConfigId + * Required. The ID of the instance configuration to create. Valid identifiers + * are of the form `custom-[-a-z0-9]*[a-z0-9]` and must be between 2 and 64 + * characters in length. The `custom-` prefix is required to avoid name + * conflicts with Google-managed configurations. + * @param {google.spanner.admin.instance.v1.InstanceConfig} request.instanceConfig + * Required. The `InstanceConfig` proto of the configuration to create. + * `instance_config.name` must be + * `/instanceConfigs/`. + * `instance_config.base_config` must be a Google-managed configuration name, + * e.g. /instanceConfigs/us-east1, /instanceConfigs/nam3. + * @param {boolean} request.validateOnly + * An option to validate, but not actually execute, a request, + * and provide the same response. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + createInstanceConfig( + request?: protos.google.spanner.admin.instance.v1.ICreateInstanceConfigRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createInstanceConfig( + request: protos.google.spanner.admin.instance.v1.ICreateInstanceConfigRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createInstanceConfig( + request: protos.google.spanner.admin.instance.v1.ICreateInstanceConfigRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createInstanceConfig( + request?: protos.google.spanner.admin.instance.v1.ICreateInstanceConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createInstanceConfig response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createInstanceConfig request %j', request); + return this.innerApiCalls + .createInstanceConfig(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createInstanceConfig response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `createInstanceConfig()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkCreateInstanceConfigProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.instance.v1.InstanceConfig, + protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + > + > { + this._log.info('createInstanceConfig long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createInstanceConfig, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.instance.v1.InstanceConfig, + protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata + >; + } + /** + * Updates an instance configuration. The returned + * long-running operation can be used to track + * the progress of updating the instance. If the named instance configuration + * does not exist, returns `NOT_FOUND`. + * + * Only user-managed configurations can be updated. + * + * Immediately after the request returns: + * + * * The instance configuration's + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig.reconciling|reconciling} + * field is set to true. + * + * While the operation is pending: + * + * * Cancelling the operation sets its metadata's + * {@link protos.google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.cancel_time|cancel_time}. + * The operation is guaranteed to succeed at undoing all changes, after + * which point it terminates with a `CANCELLED` status. + * * All other attempts to modify the instance configuration are rejected. + * * Reading the instance configuration via the API continues to give the + * pre-request values. + * + * Upon completion of the returned operation: + * + * * Creating instances using the instance configuration uses the new + * values. + * * The new values of the instance configuration are readable via the API. + * * The instance configuration's + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig.reconciling|reconciling} + * field becomes false. + * + * The returned long-running operation will + * have a name of the format + * `/operations/` and can be used to track + * the instance configuration modification. The + * metadata field type is + * {@link protos.google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata|UpdateInstanceConfigMetadata}. + * The response field type is + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig|InstanceConfig}, if + * successful. + * + * Authorization requires `spanner.instanceConfigs.update` permission on + * the resource {@link protos.google.spanner.admin.instance.v1.InstanceConfig.name|name}. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.spanner.admin.instance.v1.InstanceConfig} request.instanceConfig + * Required. The user instance configuration to update, which must always + * include the instance configuration name. Otherwise, only fields mentioned + * in + * {@link protos.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest.update_mask|update_mask} + * need be included. To prevent conflicts of concurrent updates, + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig.reconciling|etag} can + * be used. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. A mask specifying which fields in + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig|InstanceConfig} should be + * updated. The field mask must always be specified; this prevents any future + * fields in {@link protos.google.spanner.admin.instance.v1.InstanceConfig|InstanceConfig} + * from being erased accidentally by clients that do not know about them. Only + * display_name and labels can be updated. + * @param {boolean} request.validateOnly + * An option to validate, but not actually execute, a request, + * and provide the same response. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + updateInstanceConfig( + request?: protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateInstanceConfig( + request: protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateInstanceConfig( + request: protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateInstanceConfig( + request?: protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'instance_config.name': request.instanceConfig!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateInstanceConfig response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateInstanceConfig request %j', request); + return this.innerApiCalls + .updateInstanceConfig(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateInstanceConfig response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `updateInstanceConfig()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkUpdateInstanceConfigProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.instance.v1.InstanceConfig, + protos.google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + > + > { + this._log.info('updateInstanceConfig long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateInstanceConfig, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.instance.v1.InstanceConfig, + protos.google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata + >; + } + /** + * Creates an instance and begins preparing it to begin serving. The + * returned long-running operation + * can be used to track the progress of preparing the new + * instance. The instance name is assigned by the caller. If the + * named instance already exists, `CreateInstance` returns + * `ALREADY_EXISTS`. + * + * Immediately upon completion of this request: + * + * * The instance is readable via the API, with all requested attributes + * but no allocated resources. Its state is `CREATING`. + * + * Until completion of the returned operation: + * + * * Cancelling the operation renders the instance immediately unreadable + * via the API. + * * The instance can be deleted. + * * All other attempts to modify the instance are rejected. + * + * Upon completion of the returned operation: + * + * * Billing for all successfully-allocated resources begins (some types + * may have lower than the requested levels). + * * Databases can be created in the instance. + * * The instance's allocated resource levels are readable via the API. + * * The instance's state becomes `READY`. + * + * The returned long-running operation will + * have a name of the format `/operations/` and + * can be used to track creation of the instance. The + * metadata field type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceMetadata|CreateInstanceMetadata}. + * The response field type is + * {@link protos.google.spanner.admin.instance.v1.Instance|Instance}, if successful. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project in which to create the instance. Values + * are of the form `projects/`. + * @param {string} request.instanceId + * Required. The ID of the instance to create. Valid identifiers are of the + * form `{@link protos.-a-z0-9|a-z}*[a-z0-9]` and must be between 2 and 64 characters in + * length. + * @param {google.spanner.admin.instance.v1.Instance} request.instance + * Required. The instance to create. The name may be omitted, but if + * specified must be `/instances/`. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + createInstance( + request?: protos.google.spanner.admin.instance.v1.ICreateInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createInstance( + request: protos.google.spanner.admin.instance.v1.ICreateInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createInstance( + request: protos.google.spanner.admin.instance.v1.ICreateInstanceRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createInstance( + request?: protos.google.spanner.admin.instance.v1.ICreateInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createInstance response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createInstance request %j', request); + return this.innerApiCalls + .createInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `createInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkCreateInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.instance.v1.Instance, + protos.google.spanner.admin.instance.v1.CreateInstanceMetadata + > + > { + this._log.info('createInstance long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.instance.v1.Instance, + protos.google.spanner.admin.instance.v1.CreateInstanceMetadata + >; + } + /** + * Updates an instance, and begins allocating or releasing resources + * as requested. The returned long-running operation can be used to track the + * progress of updating the instance. If the named instance does not + * exist, returns `NOT_FOUND`. + * + * Immediately upon completion of this request: + * + * * For resource types for which a decrease in the instance's allocation + * has been requested, billing is based on the newly-requested level. + * + * Until completion of the returned operation: + * + * * Cancelling the operation sets its metadata's + * {@link protos.google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time|cancel_time}, + * and begins restoring resources to their pre-request values. The + * operation is guaranteed to succeed at undoing all resource changes, + * after which point it terminates with a `CANCELLED` status. + * * All other attempts to modify the instance are rejected. + * * Reading the instance via the API continues to give the pre-request + * resource levels. + * + * Upon completion of the returned operation: + * + * * Billing begins for all successfully-allocated resources (some types + * may have lower than the requested levels). + * * All newly-reserved resources are available for serving the instance's + * tables. + * * The instance's new resource levels are readable via the API. + * + * The returned long-running operation will + * have a name of the format `/operations/` and + * can be used to track the instance modification. The + * metadata field type is + * {@link protos.google.spanner.admin.instance.v1.UpdateInstanceMetadata|UpdateInstanceMetadata}. + * The response field type is + * {@link protos.google.spanner.admin.instance.v1.Instance|Instance}, if successful. + * + * Authorization requires `spanner.instances.update` permission on + * the resource {@link protos.google.spanner.admin.instance.v1.Instance.name|name}. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.spanner.admin.instance.v1.Instance} request.instance + * Required. The instance to update, which must always include the instance + * name. Otherwise, only fields mentioned in + * {@link protos.google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask|field_mask} + * need be included. + * @param {google.protobuf.FieldMask} request.fieldMask + * Required. A mask specifying which fields in + * {@link protos.google.spanner.admin.instance.v1.Instance|Instance} should be updated. + * The field mask must always be specified; this prevents any future fields in + * {@link protos.google.spanner.admin.instance.v1.Instance|Instance} from being erased + * accidentally by clients that do not know about them. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + updateInstance( + request?: protos.google.spanner.admin.instance.v1.IUpdateInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateInstance( + request: protos.google.spanner.admin.instance.v1.IUpdateInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateInstance( + request: protos.google.spanner.admin.instance.v1.IUpdateInstanceRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateInstance( + request?: protos.google.spanner.admin.instance.v1.IUpdateInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'instance.name': request.instance!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateInstance response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateInstance request %j', request); + return this.innerApiCalls + .updateInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `updateInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkUpdateInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.instance.v1.Instance, + protos.google.spanner.admin.instance.v1.UpdateInstanceMetadata + > + > { + this._log.info('updateInstance long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.instance.v1.Instance, + protos.google.spanner.admin.instance.v1.UpdateInstanceMetadata + >; + } + /** + * Creates an instance partition and begins preparing it to be used. The + * returned long-running operation + * can be used to track the progress of preparing the new instance partition. + * The instance partition name is assigned by the caller. If the named + * instance partition already exists, `CreateInstancePartition` returns + * `ALREADY_EXISTS`. + * + * Immediately upon completion of this request: + * + * * The instance partition is readable via the API, with all requested + * attributes but no allocated resources. Its state is `CREATING`. + * + * Until completion of the returned operation: + * + * * Cancelling the operation renders the instance partition immediately + * unreadable via the API. + * * The instance partition can be deleted. + * * All other attempts to modify the instance partition are rejected. + * + * Upon completion of the returned operation: + * + * * Billing for all successfully-allocated resources begins (some types + * may have lower than the requested levels). + * * Databases can start using this instance partition. + * * The instance partition's allocated resource levels are readable via the + * API. + * * The instance partition's state becomes `READY`. + * + * The returned long-running operation will + * have a name of the format + * `/operations/` and can be used to + * track creation of the instance partition. The + * metadata field type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata|CreateInstancePartitionMetadata}. + * The response field type is + * {@link protos.google.spanner.admin.instance.v1.InstancePartition|InstancePartition}, if + * successful. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the instance in which to create the instance + * partition. Values are of the form + * `projects//instances/`. + * @param {string} request.instancePartitionId + * Required. The ID of the instance partition to create. Valid identifiers are + * of the form `{@link protos.-a-z0-9|a-z}*[a-z0-9]` and must be between 2 and 64 + * characters in length. + * @param {google.spanner.admin.instance.v1.InstancePartition} request.instancePartition + * Required. The instance partition to create. The instance_partition.name may + * be omitted, but if specified must be + * `/instancePartitions/`. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + createInstancePartition( + request?: protos.google.spanner.admin.instance.v1.ICreateInstancePartitionRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createInstancePartition( + request: protos.google.spanner.admin.instance.v1.ICreateInstancePartitionRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createInstancePartition( + request: protos.google.spanner.admin.instance.v1.ICreateInstancePartitionRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + createInstancePartition( + request?: protos.google.spanner.admin.instance.v1.ICreateInstancePartitionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createInstancePartition response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createInstancePartition request %j', request); + return this.innerApiCalls + .createInstancePartition(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createInstancePartition response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `createInstancePartition()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkCreateInstancePartitionProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.instance.v1.InstancePartition, + protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + > + > { + this._log.info('createInstancePartition long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createInstancePartition, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.instance.v1.InstancePartition, + protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata + >; + } + /** + * Updates an instance partition, and begins allocating or releasing resources + * as requested. The returned long-running operation can be used to track the + * progress of updating the instance partition. If the named instance + * partition does not exist, returns `NOT_FOUND`. + * + * Immediately upon completion of this request: + * + * * For resource types for which a decrease in the instance partition's + * allocation has been requested, billing is based on the newly-requested + * level. + * + * Until completion of the returned operation: + * + * * Cancelling the operation sets its metadata's + * {@link protos.google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata.cancel_time|cancel_time}, + * and begins restoring resources to their pre-request values. The + * operation is guaranteed to succeed at undoing all resource changes, + * after which point it terminates with a `CANCELLED` status. + * * All other attempts to modify the instance partition are rejected. + * * Reading the instance partition via the API continues to give the + * pre-request resource levels. + * + * Upon completion of the returned operation: + * + * * Billing begins for all successfully-allocated resources (some types + * may have lower than the requested levels). + * * All newly-reserved resources are available for serving the instance + * partition's tables. + * * The instance partition's new resource levels are readable via the API. + * + * The returned long-running operation will + * have a name of the format + * `/operations/` and can be used to + * track the instance partition modification. The + * metadata field type is + * {@link protos.google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata|UpdateInstancePartitionMetadata}. + * The response field type is + * {@link protos.google.spanner.admin.instance.v1.InstancePartition|InstancePartition}, if + * successful. + * + * Authorization requires `spanner.instancePartitions.update` permission on + * the resource + * {@link protos.google.spanner.admin.instance.v1.InstancePartition.name|name}. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.spanner.admin.instance.v1.InstancePartition} request.instancePartition + * Required. The instance partition to update, which must always include the + * instance partition name. Otherwise, only fields mentioned in + * {@link protos.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest.field_mask|field_mask} + * need be included. + * @param {google.protobuf.FieldMask} request.fieldMask + * Required. A mask specifying which fields in + * {@link protos.google.spanner.admin.instance.v1.InstancePartition|InstancePartition} + * should be updated. The field mask must always be specified; this prevents + * any future fields in + * {@link protos.google.spanner.admin.instance.v1.InstancePartition|InstancePartition} + * from being erased accidentally by clients that do not know about them. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + updateInstancePartition( + request?: protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateInstancePartition( + request: protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateInstancePartition( + request: protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + updateInstancePartition( + request?: protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'instance_partition.name': request.instancePartition!.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateInstancePartition response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateInstancePartition request %j', request); + return this.innerApiCalls + .updateInstancePartition(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateInstancePartition response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `updateInstancePartition()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkUpdateInstancePartitionProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.instance.v1.InstancePartition, + protos.google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + > + > { + this._log.info('updateInstancePartition long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateInstancePartition, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.instance.v1.InstancePartition, + protos.google.spanner.admin.instance.v1.UpdateInstancePartitionMetadata + >; + } + /** + * Moves an instance to the target instance configuration. You can use the + * returned long-running operation to track + * the progress of moving the instance. + * + * `MoveInstance` returns `FAILED_PRECONDITION` if the instance meets any of + * the following criteria: + * + * * Is undergoing a move to a different instance configuration + * * Has backups + * * Has an ongoing update + * * Contains any CMEK-enabled databases + * * Is a free trial instance + * + * While the operation is pending: + * + * * All other attempts to modify the instance, including changes to its + * compute capacity, are rejected. + * * The following database and backup admin operations are rejected: + * + * * `DatabaseAdmin.CreateDatabase` + * * `DatabaseAdmin.UpdateDatabaseDdl` (disabled if default_leader is + * specified in the request.) + * * `DatabaseAdmin.RestoreDatabase` + * * `DatabaseAdmin.CreateBackup` + * * `DatabaseAdmin.CopyBackup` + * + * * Both the source and target instance configurations are subject to + * hourly compute and storage charges. + * * The instance might experience higher read-write latencies and a higher + * transaction abort rate. However, moving an instance doesn't cause any + * downtime. + * + * The returned long-running operation has + * a name of the format + * `/operations/` and can be used to track + * the move instance operation. The + * metadata field type is + * {@link protos.google.spanner.admin.instance.v1.MoveInstanceMetadata|MoveInstanceMetadata}. + * The response field type is + * {@link protos.google.spanner.admin.instance.v1.Instance|Instance}, + * if successful. + * Cancelling the operation sets its metadata's + * {@link protos.google.spanner.admin.instance.v1.MoveInstanceMetadata.cancel_time|cancel_time}. + * Cancellation is not immediate because it involves moving any data + * previously moved to the target instance configuration back to the original + * instance configuration. You can use this operation to track the progress of + * the cancellation. Upon successful completion of the cancellation, the + * operation terminates with `CANCELLED` status. + * + * If not cancelled, upon completion of the returned operation: + * + * * The instance successfully moves to the target instance + * configuration. + * * You are billed for compute and storage in target instance + * configuration. + * + * Authorization requires the `spanner.instances.update` permission on + * the resource {@link protos.google.spanner.admin.instance.v1.Instance|instance}. + * + * For more details, see + * [Move an instance](https://cloud.google.com/spanner/docs/move-instance). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The instance to move. + * Values are of the form `projects//instances/`. + * @param {string} request.targetConfig + * Required. The target instance configuration where to move the instance. + * Values are of the form `projects//instanceConfigs/`. + * @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 + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + moveInstance( + request?: protos.google.spanner.admin.instance.v1.IMoveInstanceRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + moveInstance( + request: protos.google.spanner.admin.instance.v1.IMoveInstanceRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + moveInstance( + request: protos.google.spanner.admin.instance.v1.IMoveInstanceRequest, + callback: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; + moveInstance( + request?: protos.google.spanner.admin.instance.v1.IMoveInstanceRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('moveInstance response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('moveInstance request %j', request); + return this.innerApiCalls + .moveInstance(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('moveInstance response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); + } + /** + * Check the status of the long running operation returned by `moveInstance()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + */ + async checkMoveInstanceProgress( + name: string, + ): Promise< + LROperation< + protos.google.spanner.admin.instance.v1.MoveInstanceResponse, + protos.google.spanner.admin.instance.v1.MoveInstanceMetadata + > + > { + this._log.info('moveInstance long-running'); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name}, + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.moveInstance, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.spanner.admin.instance.v1.MoveInstanceResponse, + protos.google.spanner.admin.instance.v1.MoveInstanceMetadata + >; + } + /** + * Lists the supported instance configurations for a given project. + * + * Returns both Google-managed configurations and user-managed + * configurations. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project for which a list of supported instance + * configurations is requested. Values are of the form + * `projects/`. + * @param {number} request.pageSize + * Number of instance configurations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigsResponse|ListInstanceConfigsResponse}. + * @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 Array of {@link protos.google.spanner.admin.instance.v1.InstanceConfig|InstanceConfig}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInstanceConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstanceConfigs( + request?: protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstanceConfig[], + protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstanceConfigsResponse, + ] + >; + listInstanceConfigs( + request: protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstanceConfig + >, + ): void; + listInstanceConfigs( + request: protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstanceConfig + >, + ): void; + listInstanceConfigs( + request?: protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstanceConfig + >, + callback?: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstanceConfig + >, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstanceConfig[], + protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstanceConfigsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstanceConfig + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listInstanceConfigs values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listInstanceConfigs request %j', request); + return this.innerApiCalls + .listInstanceConfigs(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.spanner.admin.instance.v1.IInstanceConfig[], + protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstanceConfigsResponse, + ]) => { + this._log.info('listInstanceConfigs values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listInstanceConfigs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project for which a list of supported instance + * configurations is requested. Values are of the form + * `projects/`. + * @param {number} request.pageSize + * Number of instance configurations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigsResponse|ListInstanceConfigsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.spanner.admin.instance.v1.InstanceConfig|InstanceConfig} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInstanceConfigsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstanceConfigsStream( + request?: protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listInstanceConfigs']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstanceConfigs stream %j', request); + return this.descriptors.page.listInstanceConfigs.createStream( + this.innerApiCalls.listInstanceConfigs as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listInstanceConfigs`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project for which a list of supported instance + * configurations is requested. Values are of the form + * `projects/`. + * @param {number} request.pageSize + * Number of instance configurations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigsResponse|ListInstanceConfigsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.spanner.admin.instance.v1.InstanceConfig|InstanceConfig}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listInstanceConfigsAsync( + request?: protos.google.spanner.admin.instance.v1.IListInstanceConfigsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listInstanceConfigs']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstanceConfigs iterate %j', request); + return this.descriptors.page.listInstanceConfigs.asyncIterate( + this.innerApiCalls['listInstanceConfigs'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists the user-managed instance configuration long-running + * operations in the given project. An instance + * configuration operation has a name of the form + * `projects//instanceConfigs//operations/`. + * The long-running operation + * metadata field type + * `metadata.type_url` describes the type of the metadata. Operations returned + * include those that have completed/failed/canceled within the last 7 days, + * and pending operations. Operations returned are ordered by + * `operation.metadata.value.start_time` in descending order starting + * from the most recently started operation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project of the instance configuration operations. + * Values are of the form `projects/`. + * @param {string} request.filter + * An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the Operation are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata|CreateInstanceConfigMetadata} + * is + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=` \ + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata) + * AND` \ + * `(metadata.instance_config.name:custom-config) AND` \ + * `(metadata.progress.start_time < \"2021-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata|CreateInstanceConfigMetadata}. + * * The instance configuration name contains "custom-config". + * * The operation started before 2021-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse|ListInstanceConfigOperationsResponse} + * to the same `parent` and with the same `filter`. + * @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 Array of {@link protos.google.longrunning.Operation|Operation}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInstanceConfigOperationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstanceConfigOperations( + request?: protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse, + ] + >; + listInstanceConfigOperations( + request: protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): void; + listInstanceConfigOperations( + request: protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): void; + listInstanceConfigOperations( + request?: protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + callback?: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): Promise< + [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listInstanceConfigOperations values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listInstanceConfigOperations request %j', request); + return this.innerApiCalls + .listInstanceConfigOperations(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsResponse, + ]) => { + this._log.info('listInstanceConfigOperations values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listInstanceConfigOperations`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project of the instance configuration operations. + * Values are of the form `projects/`. + * @param {string} request.filter + * An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the Operation are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata|CreateInstanceConfigMetadata} + * is + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=` \ + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata) + * AND` \ + * `(metadata.instance_config.name:custom-config) AND` \ + * `(metadata.progress.start_time < \"2021-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata|CreateInstanceConfigMetadata}. + * * The instance configuration name contains "custom-config". + * * The operation started before 2021-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse|ListInstanceConfigOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.longrunning.Operation|Operation} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInstanceConfigOperationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstanceConfigOperationsStream( + request?: protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listInstanceConfigOperations']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstanceConfigOperations stream %j', request); + return this.descriptors.page.listInstanceConfigOperations.createStream( + this.innerApiCalls.listInstanceConfigOperations as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listInstanceConfigOperations`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project of the instance configuration operations. + * Values are of the form `projects/`. + * @param {string} request.filter + * An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the Operation are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata|CreateInstanceConfigMetadata} + * is + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=` \ + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata) + * AND` \ + * `(metadata.instance_config.name:custom-config) AND` \ + * `(metadata.progress.start_time < \"2021-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstanceConfigMetadata|CreateInstanceConfigMetadata}. + * * The instance configuration name contains "custom-config". + * * The operation started before 2021-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} request.pageSize + * Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsResponse|ListInstanceConfigOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.longrunning.Operation|Operation}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listInstanceConfigOperationsAsync( + request?: protos.google.spanner.admin.instance.v1.IListInstanceConfigOperationsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listInstanceConfigOperations']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstanceConfigOperations iterate %j', request); + return this.descriptors.page.listInstanceConfigOperations.asyncIterate( + this.innerApiCalls['listInstanceConfigOperations'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists all instances in the given project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project for which a list of instances is + * requested. Values are of the form `projects/`. + * @param {number} request.pageSize + * Number of instances to be returned in the response. If 0 or less, defaults + * to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse|ListInstancesResponse}. + * @param {string} request.filter + * An expression for filtering the results of the request. Filter rules are + * case insensitive. The fields eligible for filtering are: + * + * * `name` + * * `display_name` + * * `labels.key` where key is the name of a label + * + * Some examples of using filters are: + * + * * `name:*` --> The instance has a name. + * * `name:Howl` --> The instance's name contains the string "howl". + * * `name:HOWL` --> Equivalent to above. + * * `NAME:howl` --> Equivalent to above. + * * `labels.env:*` --> The instance has the label "env". + * * `labels.env:dev` --> The instance has the label "env" and the value of + * the label contains the string "dev". + * * `name:howl labels.env:dev` --> The instance's name contains "howl" and + * it has the label "env" with its value + * containing "dev". + * @param {google.protobuf.Timestamp} request.instanceDeadline + * Deadline used while retrieving metadata for instances. + * Instances whose metadata cannot be retrieved within this deadline will be + * added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse.unreachable|unreachable} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse|ListInstancesResponse}. + * @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 Array of {@link protos.google.spanner.admin.instance.v1.Instance|Instance}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInstancesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstances( + request?: protos.google.spanner.admin.instance.v1.IListInstancesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstance[], + protos.google.spanner.admin.instance.v1.IListInstancesRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancesResponse, + ] + >; + listInstances( + request: protos.google.spanner.admin.instance.v1.IListInstancesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancesRequest, + | protos.google.spanner.admin.instance.v1.IListInstancesResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstance + >, + ): void; + listInstances( + request: protos.google.spanner.admin.instance.v1.IListInstancesRequest, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancesRequest, + | protos.google.spanner.admin.instance.v1.IListInstancesResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstance + >, + ): void; + listInstances( + request?: protos.google.spanner.admin.instance.v1.IListInstancesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancesRequest, + | protos.google.spanner.admin.instance.v1.IListInstancesResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstance + >, + callback?: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancesRequest, + | protos.google.spanner.admin.instance.v1.IListInstancesResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstance + >, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstance[], + protos.google.spanner.admin.instance.v1.IListInstancesRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancesResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancesRequest, + | protos.google.spanner.admin.instance.v1.IListInstancesResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstance + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listInstances values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listInstances request %j', request); + return this.innerApiCalls + .listInstances(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.spanner.admin.instance.v1.IInstance[], + protos.google.spanner.admin.instance.v1.IListInstancesRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancesResponse, + ]) => { + this._log.info('listInstances values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listInstances`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project for which a list of instances is + * requested. Values are of the form `projects/`. + * @param {number} request.pageSize + * Number of instances to be returned in the response. If 0 or less, defaults + * to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse|ListInstancesResponse}. + * @param {string} request.filter + * An expression for filtering the results of the request. Filter rules are + * case insensitive. The fields eligible for filtering are: + * + * * `name` + * * `display_name` + * * `labels.key` where key is the name of a label + * + * Some examples of using filters are: + * + * * `name:*` --> The instance has a name. + * * `name:Howl` --> The instance's name contains the string "howl". + * * `name:HOWL` --> Equivalent to above. + * * `NAME:howl` --> Equivalent to above. + * * `labels.env:*` --> The instance has the label "env". + * * `labels.env:dev` --> The instance has the label "env" and the value of + * the label contains the string "dev". + * * `name:howl labels.env:dev` --> The instance's name contains "howl" and + * it has the label "env" with its value + * containing "dev". + * @param {google.protobuf.Timestamp} request.instanceDeadline + * Deadline used while retrieving metadata for instances. + * Instances whose metadata cannot be retrieved within this deadline will be + * added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse.unreachable|unreachable} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse|ListInstancesResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.spanner.admin.instance.v1.Instance|Instance} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInstancesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstancesStream( + request?: protos.google.spanner.admin.instance.v1.IListInstancesRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listInstances']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstances stream %j', request); + return this.descriptors.page.listInstances.createStream( + this.innerApiCalls.listInstances as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listInstances`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project for which a list of instances is + * requested. Values are of the form `projects/`. + * @param {number} request.pageSize + * Number of instances to be returned in the response. If 0 or less, defaults + * to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse|ListInstancesResponse}. + * @param {string} request.filter + * An expression for filtering the results of the request. Filter rules are + * case insensitive. The fields eligible for filtering are: + * + * * `name` + * * `display_name` + * * `labels.key` where key is the name of a label + * + * Some examples of using filters are: + * + * * `name:*` --> The instance has a name. + * * `name:Howl` --> The instance's name contains the string "howl". + * * `name:HOWL` --> Equivalent to above. + * * `NAME:howl` --> Equivalent to above. + * * `labels.env:*` --> The instance has the label "env". + * * `labels.env:dev` --> The instance has the label "env" and the value of + * the label contains the string "dev". + * * `name:howl labels.env:dev` --> The instance's name contains "howl" and + * it has the label "env" with its value + * containing "dev". + * @param {google.protobuf.Timestamp} request.instanceDeadline + * Deadline used while retrieving metadata for instances. + * Instances whose metadata cannot be retrieved within this deadline will be + * added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse.unreachable|unreachable} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancesResponse|ListInstancesResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.spanner.admin.instance.v1.Instance|Instance}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listInstancesAsync( + request?: protos.google.spanner.admin.instance.v1.IListInstancesRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listInstances']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstances iterate %j', request); + return this.descriptors.page.listInstances.asyncIterate( + this.innerApiCalls['listInstances'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists all instance partitions for the given instance. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance whose instance partitions should be listed. Values + * are of the form `projects//instances/`. Use `{instance} + * = '-'` to list instance partitions for all Instances in a project, e.g., + * `projects/myproject/instances/-`. + * @param {number} request.pageSize + * Number of instance partitions to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse|ListInstancePartitionsResponse}. + * @param {google.protobuf.Timestamp} [request.instancePartitionDeadline] + * Optional. Deadline used while retrieving metadata for instance partitions. + * Instance partitions whose metadata cannot be retrieved within this deadline + * will be added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse.unreachable|unreachable} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse|ListInstancePartitionsResponse}. + * @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 Array of {@link protos.google.spanner.admin.instance.v1.InstancePartition|InstancePartition}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInstancePartitionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstancePartitions( + request?: protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstancePartition[], + protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancePartitionsResponse, + ] + >; + listInstancePartitions( + request: protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstancePartition + >, + ): void; + listInstancePartitions( + request: protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstancePartition + >, + ): void; + listInstancePartitions( + request?: protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstancePartition + >, + callback?: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstancePartition + >, + ): Promise< + [ + protos.google.spanner.admin.instance.v1.IInstancePartition[], + protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancePartitionsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionsResponse + | null + | undefined, + protos.google.spanner.admin.instance.v1.IInstancePartition + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listInstancePartitions values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listInstancePartitions request %j', request); + return this.innerApiCalls + .listInstancePartitions(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.spanner.admin.instance.v1.IInstancePartition[], + protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancePartitionsResponse, + ]) => { + this._log.info('listInstancePartitions values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listInstancePartitions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance whose instance partitions should be listed. Values + * are of the form `projects//instances/`. Use `{instance} + * = '-'` to list instance partitions for all Instances in a project, e.g., + * `projects/myproject/instances/-`. + * @param {number} request.pageSize + * Number of instance partitions to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse|ListInstancePartitionsResponse}. + * @param {google.protobuf.Timestamp} [request.instancePartitionDeadline] + * Optional. Deadline used while retrieving metadata for instance partitions. + * Instance partitions whose metadata cannot be retrieved within this deadline + * will be added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse.unreachable|unreachable} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse|ListInstancePartitionsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.spanner.admin.instance.v1.InstancePartition|InstancePartition} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInstancePartitionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstancePartitionsStream( + request?: protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listInstancePartitions']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstancePartitions stream %j', request); + return this.descriptors.page.listInstancePartitions.createStream( + this.innerApiCalls.listInstancePartitions as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listInstancePartitions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The instance whose instance partitions should be listed. Values + * are of the form `projects//instances/`. Use `{instance} + * = '-'` to list instance partitions for all Instances in a project, e.g., + * `projects/myproject/instances/-`. + * @param {number} request.pageSize + * Number of instance partitions to be returned in the response. If 0 or less, + * defaults to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse|ListInstancePartitionsResponse}. + * @param {google.protobuf.Timestamp} [request.instancePartitionDeadline] + * Optional. Deadline used while retrieving metadata for instance partitions. + * Instance partitions whose metadata cannot be retrieved within this deadline + * will be added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse.unreachable|unreachable} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionsResponse|ListInstancePartitionsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.spanner.admin.instance.v1.InstancePartition|InstancePartition}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listInstancePartitionsAsync( + request?: protos.google.spanner.admin.instance.v1.IListInstancePartitionsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listInstancePartitions']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstancePartitions iterate %j', request); + return this.descriptors.page.listInstancePartitions.asyncIterate( + this.innerApiCalls['listInstancePartitions'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Lists instance partition long-running operations in the given instance. + * An instance partition operation has a name of the form + * `projects//instances//instancePartitions//operations/`. + * The long-running operation + * metadata field type + * `metadata.type_url` describes the type of the metadata. Operations returned + * include those that have completed/failed/canceled within the last 7 days, + * and pending operations. Operations returned are ordered by + * `operation.metadata.value.start_time` in descending order starting from the + * most recently started operation. + * + * Authorization requires `spanner.instancePartitionOperations.list` + * permission on the resource + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest.parent|parent}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent instance of the instance partition operations. + * Values are of the form `projects//instances/`. + * @param {string} [request.filter] + * Optional. An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the Operation are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata|CreateInstancePartitionMetadata} + * is + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=` \ + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata) + * AND` \ + * `(metadata.instance_partition.name:custom-instance-partition) AND` \ + * `(metadata.start_time < \"2021-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata|CreateInstancePartitionMetadata}. + * * The instance partition name contains "custom-instance-partition". + * * The operation started before 2021-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} [request.pageSize] + * Optional. Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} [request.pageToken] + * Optional. If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse|ListInstancePartitionOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {google.protobuf.Timestamp} [request.instancePartitionDeadline] + * Optional. Deadline used while retrieving metadata for instance partition + * operations. Instance partitions whose operation metadata cannot be + * retrieved within this deadline will be added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.unreachable_instance_partitions|unreachable_instance_partitions} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse|ListInstancePartitionOperationsResponse}. + * @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 Array of {@link protos.google.longrunning.Operation|Operation}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listInstancePartitionOperationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstancePartitionOperations( + request?: protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse, + ] + >; + listInstancePartitionOperations( + request: protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): void; + listInstancePartitionOperations( + request: protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + callback: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): void; + listInstancePartitionOperations( + request?: protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + callback?: PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + >, + ): Promise< + [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + | protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse + | null + | undefined, + protos.google.longrunning.IOperation + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listInstancePartitionOperations values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listInstancePartitionOperations request %j', request); + return this.innerApiCalls + .listInstancePartitionOperations(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.longrunning.IOperation[], + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest | null, + protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsResponse, + ]) => { + this._log.info('listInstancePartitionOperations values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listInstancePartitionOperations`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent instance of the instance partition operations. + * Values are of the form `projects//instances/`. + * @param {string} [request.filter] + * Optional. An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the Operation are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata|CreateInstancePartitionMetadata} + * is + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=` \ + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata) + * AND` \ + * `(metadata.instance_partition.name:custom-instance-partition) AND` \ + * `(metadata.start_time < \"2021-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata|CreateInstancePartitionMetadata}. + * * The instance partition name contains "custom-instance-partition". + * * The operation started before 2021-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} [request.pageSize] + * Optional. Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} [request.pageToken] + * Optional. If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse|ListInstancePartitionOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {google.protobuf.Timestamp} [request.instancePartitionDeadline] + * Optional. Deadline used while retrieving metadata for instance partition + * operations. Instance partitions whose operation metadata cannot be + * retrieved within this deadline will be added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.unreachable_instance_partitions|unreachable_instance_partitions} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse|ListInstancePartitionOperationsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.longrunning.Operation|Operation} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listInstancePartitionOperationsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listInstancePartitionOperationsStream( + request?: protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listInstancePartitionOperations']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstancePartitionOperations stream %j', request); + return this.descriptors.page.listInstancePartitionOperations.createStream( + this.innerApiCalls.listInstancePartitionOperations as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listInstancePartitionOperations`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent instance of the instance partition operations. + * Values are of the form `projects//instances/`. + * @param {string} [request.filter] + * Optional. An expression that filters the list of returned operations. + * + * A filter expression consists of a field name, a + * comparison operator, and a value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the Operation are eligible for filtering: + * + * * `name` - The name of the long-running operation + * * `done` - False if the operation is in progress, else true. + * * `metadata.@type` - the type of metadata. For example, the type string + * for + * {@link protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata|CreateInstancePartitionMetadata} + * is + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata`. + * * `metadata.` - any field in metadata.value. + * `metadata.@type` must be specified first, if filtering on metadata + * fields. + * * `error` - Error associated with the long-running operation. + * * `response.@type` - the type of response. + * * `response.` - any field in response.value. + * + * You can combine multiple expressions by enclosing each expression in + * parentheses. By default, expressions are combined with AND logic. However, + * you can specify AND, OR, and NOT logic explicitly. + * + * Here are a few examples: + * + * * `done:true` - The operation is complete. + * * `(metadata.@type=` \ + * `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstancePartitionMetadata) + * AND` \ + * `(metadata.instance_partition.name:custom-instance-partition) AND` \ + * `(metadata.start_time < \"2021-03-28T14:50:00Z\") AND` \ + * `(error:*)` - Return operations where: + * * The operation's metadata type is + * {@link protos.google.spanner.admin.instance.v1.CreateInstancePartitionMetadata|CreateInstancePartitionMetadata}. + * * The instance partition name contains "custom-instance-partition". + * * The operation started before 2021-03-28T14:50:00Z. + * * The operation resulted in an error. + * @param {number} [request.pageSize] + * Optional. Number of operations to be returned in the response. If 0 or + * less, defaults to the server's maximum allowed page size. + * @param {string} [request.pageToken] + * Optional. If non-empty, `page_token` should contain a + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse|ListInstancePartitionOperationsResponse} + * to the same `parent` and with the same `filter`. + * @param {google.protobuf.Timestamp} [request.instancePartitionDeadline] + * Optional. Deadline used while retrieving metadata for instance partition + * operations. Instance partitions whose operation metadata cannot be + * retrieved within this deadline will be added to + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse.unreachable_instance_partitions|unreachable_instance_partitions} + * in + * {@link protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsResponse|ListInstancePartitionOperationsResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.longrunning.Operation|Operation}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listInstancePartitionOperationsAsync( + request?: protos.google.spanner.admin.instance.v1.IListInstancePartitionOperationsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listInstancePartitionOperations']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listInstancePartitionOperations iterate %j', request); + return this.descriptors.page.listInstancePartitionOperations.asyncIterate( + this.innerApiCalls['listInstancePartitionOperations'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation( + request: protos.google.longrunning.GetOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + ): Promise<[protos.google.longrunning.Operation]> { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.getOperation(request, options, callback); + } + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | iteration protocols}. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync( + request: protos.google.longrunning.ListOperationsRequest, + options?: gax.CallOptions, + ): AsyncIterable { + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.listOperationsAsync(request, options); + } + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation( + request: protos.google.longrunning.CancelOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + callback?: Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + >, + ): Promise { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.cancelOperation(request, options, callback); + } + + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation( + request: protos.google.longrunning.DeleteOperationRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + ): Promise { + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + return this.operationsClient.deleteOperation(request, options, callback); + } + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified instance resource name string. + * + * @param {string} project + * @param {string} instance + * @returns {string} Resource name string. + */ + instancePath(project: string, instance: string) { + return this.pathTemplates.instancePathTemplate.render({ + project: project, + instance: instance, + }); + } + + /** + * Parse the project from Instance resource. + * + * @param {string} instanceName + * A fully-qualified path representing Instance resource. + * @returns {string} A string representing the project. + */ + matchProjectFromInstanceName(instanceName: string) { + return this.pathTemplates.instancePathTemplate.match(instanceName).project; + } + + /** + * Parse the instance from Instance resource. + * + * @param {string} instanceName + * A fully-qualified path representing Instance resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromInstanceName(instanceName: string) { + return this.pathTemplates.instancePathTemplate.match(instanceName).instance; + } + + /** + * Return a fully-qualified instanceConfig resource name string. + * + * @param {string} project + * @param {string} instance_config + * @returns {string} Resource name string. + */ + instanceConfigPath(project: string, instanceConfig: string) { + return this.pathTemplates.instanceConfigPathTemplate.render({ + project: project, + instance_config: instanceConfig, + }); + } + + /** + * Parse the project from InstanceConfig resource. + * + * @param {string} instanceConfigName + * A fully-qualified path representing InstanceConfig resource. + * @returns {string} A string representing the project. + */ + matchProjectFromInstanceConfigName(instanceConfigName: string) { + return this.pathTemplates.instanceConfigPathTemplate.match( + instanceConfigName, + ).project; + } + + /** + * Parse the instance_config from InstanceConfig resource. + * + * @param {string} instanceConfigName + * A fully-qualified path representing InstanceConfig resource. + * @returns {string} A string representing the instance_config. + */ + matchInstanceConfigFromInstanceConfigName(instanceConfigName: string) { + return this.pathTemplates.instanceConfigPathTemplate.match( + instanceConfigName, + ).instance_config; + } + + /** + * Return a fully-qualified instancePartition resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} instance_partition + * @returns {string} Resource name string. + */ + instancePartitionPath( + project: string, + instance: string, + instancePartition: string, + ) { + return this.pathTemplates.instancePartitionPathTemplate.render({ + project: project, + instance: instance, + instance_partition: instancePartition, + }); + } + + /** + * Parse the project from InstancePartition resource. + * + * @param {string} instancePartitionName + * A fully-qualified path representing InstancePartition resource. + * @returns {string} A string representing the project. + */ + matchProjectFromInstancePartitionName(instancePartitionName: string) { + return this.pathTemplates.instancePartitionPathTemplate.match( + instancePartitionName, + ).project; + } + + /** + * Parse the instance from InstancePartition resource. + * + * @param {string} instancePartitionName + * A fully-qualified path representing InstancePartition resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromInstancePartitionName(instancePartitionName: string) { + return this.pathTemplates.instancePartitionPathTemplate.match( + instancePartitionName, + ).instance; + } + + /** + * Parse the instance_partition from InstancePartition resource. + * + * @param {string} instancePartitionName + * A fully-qualified path representing InstancePartition resource. + * @returns {string} A string representing the instance_partition. + */ + matchInstancePartitionFromInstancePartitionName( + instancePartitionName: string, + ) { + return this.pathTemplates.instancePartitionPathTemplate.match( + instancePartitionName, + ).instance_partition; + } + + /** + * Return a fully-qualified project resource name string. + * + * @param {string} project + * @returns {string} Resource name string. + */ + projectPath(project: string) { + return this.pathTemplates.projectPathTemplate.render({ + project: project, + }); + } + + /** + * Parse the project from Project resource. + * + * @param {string} projectName + * A fully-qualified path representing Project resource. + * @returns {string} A string representing the project. + */ + matchProjectFromProjectName(projectName: string) { + return this.pathTemplates.projectPathTemplate.match(projectName).project; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.instanceAdminStub && !this._terminated) { + return this.instanceAdminStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + void this.operationsClient.close(); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/spanner/src/v1/instance_admin_client_config.json b/handwritten/spanner/src/v1/instance_admin_client_config.json new file mode 100644 index 00000000000..cbe3ae620e0 --- /dev/null +++ b/handwritten/spanner/src/v1/instance_admin_client_config.json @@ -0,0 +1,129 @@ +{ + "interfaces": { + "google.spanner.admin.instance.v1.InstanceAdmin": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + }, + "e9fafda332ce8a1702dc1575de3ca81c4feb4799": { + "initial_retry_delay_millis": 1000, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 32000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "ListInstanceConfigs": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "GetInstanceConfig": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "CreateInstanceConfig": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateInstanceConfig": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteInstanceConfig": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListInstanceConfigOperations": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListInstances": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "ListInstancePartitions": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetInstance": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "CreateInstance": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateInstance": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteInstance": { + "timeout_millis": 3600000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "SetIamPolicy": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "e9fafda332ce8a1702dc1575de3ca81c4feb4799" + }, + "TestIamPermissions": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetInstancePartition": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateInstancePartition": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteInstancePartition": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateInstancePartition": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListInstancePartitionOperations": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "MoveInstance": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/spanner/src/v1/instance_admin_proto_list.json b/handwritten/spanner/src/v1/instance_admin_proto_list.json new file mode 100644 index 00000000000..ce2400d42e0 --- /dev/null +++ b/handwritten/spanner/src/v1/instance_admin_proto_list.json @@ -0,0 +1,4 @@ +[ + "../../protos/google/spanner/admin/instance/v1/common.proto", + "../../protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto" +] diff --git a/handwritten/spanner/src/v1/spanner_client.ts b/handwritten/spanner/src/v1/spanner_client.ts new file mode 100644 index 00000000000..07a538fbd3f --- /dev/null +++ b/handwritten/spanner/src/v1/spanner_client.ts @@ -0,0 +1,3058 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import {Transform, PassThrough} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/spanner_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './spanner_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Cloud Spanner API + * + * The Cloud Spanner API can be used to manage sessions and execute + * transactions on data stored in Cloud Spanner databases. + * @class + * @memberof v1 + */ +export class SpannerClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('spanner'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + spannerStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of SpannerClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new SpannerClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof SpannerClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; + this._servicePath = 'spanner.' + this._universeDomain; + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = + opts?.fallback ?? + (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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + databasePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}', + ), + sessionPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}/sessions/{session}', + ), + }; + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listSessions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'sessions', + ), + }; + + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this.descriptors.stream = { + executeStreamingSql: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + streamingRead: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + batchWrite: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.spanner.v1.Spanner', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')}, + ); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.spannerStub) { + return this.spannerStub; + } + + // Put together the "service stub" for + // google.spanner.v1.Spanner. + this.spannerStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.spanner.v1.Spanner', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.spanner.v1.Spanner, + this._opts, + this._providedCustomServicePath, + ) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const spannerStubMethods = [ + 'createSession', + 'batchCreateSessions', + 'getSession', + 'listSessions', + 'deleteSession', + 'executeSql', + 'executeStreamingSql', + 'executeBatchDml', + 'read', + 'streamingRead', + 'beginTransaction', + 'commit', + 'rollback', + 'partitionQuery', + 'partitionRead', + 'batchWrite', + ]; + for (const methodName of spannerStubMethods) { + const callPromise = this.spannerStub.then( + stub => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({objectMode: true}); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = + this.descriptors.page[methodName] || + this.descriptors.stream[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.spannerStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'spanner.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'spanner.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.data', + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId( + callback?: Callback, + ): Promise | void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + /** + * Creates a new session. A session can be used to perform + * transactions that read and/or modify data in a Cloud Spanner database. + * Sessions are meant to be reused for many consecutive + * transactions. + * + * Sessions can only execute one transaction at a time. To execute + * multiple concurrent read-write/write-only transactions, create + * multiple sessions. Note that standalone reads and queries use a + * transaction internally, and count toward the one transaction + * limit. + * + * Active sessions use additional server resources, so it's a good idea to + * delete idle and unneeded sessions. + * Aside from explicit deletes, Cloud Spanner can delete sessions when no + * operations are sent for more than an hour. If a session is deleted, + * requests to it return `NOT_FOUND`. + * + * Idle sessions can be kept alive by sending a trivial SQL query + * periodically, for example, `"SELECT 1"`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database in which the new session is created. + * @param {google.spanner.v1.Session} request.session + * Required. The session to create. + * @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.spanner.v1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + createSession( + request?: protos.google.spanner.v1.ICreateSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.ICreateSessionRequest | undefined, + {} | undefined, + ] + >; + createSession( + request: protos.google.spanner.v1.ICreateSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; + createSession( + request: protos.google.spanner.v1.ICreateSessionRequest, + callback: Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; + createSession( + request?: protos.google.spanner.v1.ICreateSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.ICreateSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.ICreateSessionRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('createSession request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.ICreateSessionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createSession response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.ICreateSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Creates multiple new sessions. + * + * This API can be used to initialize a session cache on the clients. + * See https://goo.gl/TgSFN2 for best practices on session cache management. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database in which the new sessions are created. + * @param {google.spanner.v1.Session} request.sessionTemplate + * Parameters to apply to each created session. + * @param {number} request.sessionCount + * Required. The number of sessions to be created in this batch call. At least + * one session is created. The API can return fewer than the requested number + * of sessions. If a specific number of sessions are desired, the client can + * make additional calls to `BatchCreateSessions` (adjusting + * {@link protos.google.spanner.v1.BatchCreateSessionsRequest.session_count|session_count} + * as necessary). + * @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.spanner.v1.BatchCreateSessionsResponse|BatchCreateSessionsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + batchCreateSessions( + request?: protos.google.spanner.v1.IBatchCreateSessionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.IBatchCreateSessionsResponse, + protos.google.spanner.v1.IBatchCreateSessionsRequest | undefined, + {} | undefined, + ] + >; + batchCreateSessions( + request: protos.google.spanner.v1.IBatchCreateSessionsRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.IBatchCreateSessionsResponse, + protos.google.spanner.v1.IBatchCreateSessionsRequest | null | undefined, + {} | null | undefined + >, + ): void; + batchCreateSessions( + request: protos.google.spanner.v1.IBatchCreateSessionsRequest, + callback: Callback< + protos.google.spanner.v1.IBatchCreateSessionsResponse, + protos.google.spanner.v1.IBatchCreateSessionsRequest | null | undefined, + {} | null | undefined + >, + ): void; + batchCreateSessions( + request?: protos.google.spanner.v1.IBatchCreateSessionsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.IBatchCreateSessionsResponse, + | protos.google.spanner.v1.IBatchCreateSessionsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.IBatchCreateSessionsResponse, + protos.google.spanner.v1.IBatchCreateSessionsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.IBatchCreateSessionsResponse, + protos.google.spanner.v1.IBatchCreateSessionsRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('batchCreateSessions request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.IBatchCreateSessionsResponse, + | protos.google.spanner.v1.IBatchCreateSessionsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('batchCreateSessions response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .batchCreateSessions(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.IBatchCreateSessionsResponse, + protos.google.spanner.v1.IBatchCreateSessionsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('batchCreateSessions response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets a session. Returns `NOT_FOUND` if the session doesn't exist. + * This is mainly useful for determining whether a session is still + * alive. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the session to retrieve. + * @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.spanner.v1.Session|Session}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + getSession( + request?: protos.google.spanner.v1.IGetSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.IGetSessionRequest | undefined, + {} | undefined, + ] + >; + getSession( + request: protos.google.spanner.v1.IGetSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; + getSession( + request: protos.google.spanner.v1.IGetSessionRequest, + callback: Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; + getSession( + request?: protos.google.spanner.v1.IGetSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.IGetSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.IGetSessionRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('getSession request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.IGetSessionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getSession response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.ISession, + protos.google.spanner.v1.IGetSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Ends a session, releasing server resources associated with it. This + * asynchronously triggers the cancellation of any operations that are running + * with this session. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the session to delete. + * @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.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. + */ + deleteSession( + request?: protos.google.spanner.v1.IDeleteSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + >; + deleteSession( + request: protos.google.spanner.v1.IDeleteSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteSession( + request: protos.google.spanner.v1.IDeleteSessionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): void; + deleteSession( + request?: protos.google.spanner.v1.IDeleteSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IDeleteSessionRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('deleteSession request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IDeleteSessionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteSession response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IDeleteSessionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Executes an SQL statement, returning all results in a single reply. This + * method can't be used to return a result set larger than 10 MiB; + * if the query yields more data than that, the query fails with + * a `FAILED_PRECONDITION` error. + * + * Operations inside read-write transactions might return `ABORTED`. If + * this occurs, the application should restart the transaction from + * the beginning. See {@link protos.google.spanner.v1.Transaction|Transaction} for more + * details. + * + * Larger result sets can be fetched in streaming fashion by calling + * {@link protos.google.spanner.v1.Spanner.ExecuteStreamingSql|ExecuteStreamingSql} + * instead. + * + * The query string can be SQL or [Graph Query Language + * (GQL)](https://cloud.google.com/spanner/docs/reference/standard-sql/graph-intro). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the SQL query should be performed. + * @param {google.spanner.v1.TransactionSelector} request.transaction + * The transaction to use. + * + * For queries, if none is provided, the default is a temporary read-only + * transaction with strong concurrency. + * + * Standard DML statements require a read-write transaction. To protect + * against replays, single-use transactions are not supported. The caller + * must either supply an existing transaction ID or begin a new transaction. + * + * Partitioned DML requires an existing Partitioned DML transaction ID. + * @param {string} request.sql + * Required. The SQL string. + * @param {google.protobuf.Struct} request.params + * Parameter names and values that bind to placeholders in the SQL string. + * + * A parameter placeholder consists of the `@` character followed by the + * parameter name (for example, `@firstName`). Parameter names must conform + * to the naming requirements of identifiers as specified at + * https://cloud.google.com/spanner/docs/lexical#identifiers. + * + * Parameters can appear anywhere that a literal value is expected. The same + * parameter name can be used more than once, for example: + * + * `"WHERE id > @msg_id AND id < @msg_id + 100"` + * + * It's an error to execute a SQL statement with unbound parameters. + * @param {number[]} request.paramTypes + * It isn't always possible for Cloud Spanner to infer the right SQL type + * from a JSON value. For example, values of type `BYTES` and values + * of type `STRING` both appear in + * {@link protos.google.spanner.v1.ExecuteSqlRequest.params|params} as JSON strings. + * + * In these cases, you can use `param_types` to specify the exact + * SQL type for some or all of the SQL statement parameters. See the + * definition of {@link protos.google.spanner.v1.Type|Type} for more information + * about SQL types. + * @param {Buffer} request.resumeToken + * If this request is resuming a previously interrupted SQL statement + * execution, `resume_token` should be copied from the last + * {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} yielded before the + * interruption. Doing this enables the new SQL statement execution to resume + * where the last one left off. The rest of the request parameters must + * exactly match the request that yielded this token. + * @param {google.spanner.v1.ExecuteSqlRequest.QueryMode} request.queryMode + * Used to control the amount of debugging information returned in + * {@link protos.google.spanner.v1.ResultSetStats|ResultSetStats}. If + * {@link protos.google.spanner.v1.ExecuteSqlRequest.partition_token|partition_token} is + * set, {@link protos.google.spanner.v1.ExecuteSqlRequest.query_mode|query_mode} can only + * be set to + * {@link protos.google.spanner.v1.ExecuteSqlRequest.QueryMode.NORMAL|QueryMode.NORMAL}. + * @param {Buffer} request.partitionToken + * If present, results are restricted to the specified partition + * previously created using `PartitionQuery`. There must be an exact + * match for the values of fields common to this message and the + * `PartitionQueryRequest` message used to create this `partition_token`. + * @param {number} request.seqno + * A per-transaction sequence number used to identify this request. This field + * makes each request idempotent such that if the request is received multiple + * times, at most one succeeds. + * + * The sequence number must be monotonically increasing within the + * transaction. If a request arrives for the first time with an out-of-order + * sequence number, the transaction can be aborted. Replays of previously + * handled requests yield the same response as the first execution. + * + * Required for DML statements. Ignored for queries. + * @param {google.spanner.v1.ExecuteSqlRequest.QueryOptions} request.queryOptions + * Query optimizer configuration to use for the given query. + * @param {google.spanner.v1.RequestOptions} request.requestOptions + * Common options for this request. + * @param {google.spanner.v1.DirectedReadOptions} request.directedReadOptions + * Directed read options for this request. + * @param {boolean} request.dataBoostEnabled + * If this is for a partitioned query and this field is set to `true`, the + * request is executed with Spanner Data Boost independent compute resources. + * + * If the field is set to `true` but the request doesn't set + * `partition_token`, the API returns an `INVALID_ARGUMENT` error. + * @param {boolean} [request.lastStatement] + * Optional. If set to `true`, this statement marks the end of the + * transaction. After this statement executes, you must commit or abort the + * transaction. Attempts to execute any other requests against this + * transaction (including reads and queries) are rejected. + * + * For DML statements, setting this option might cause some error reporting to + * be deferred until commit time (for example, validation of unique + * constraints). Given this, successful execution of a DML statement shouldn't + * be assumed until a subsequent `Commit` call completes successfully. + * @param {google.spanner.v1.RoutingHint} [request.routingHint] + * Optional. If present, it makes the Spanner requests location-aware. + * + * It gives the server hints that can be used to route the request + * to an appropriate server, potentially significantly decreasing latency and + * improving throughput. To achieve improved performance, most fields must be + * filled in with accurate values. + * @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.spanner.v1.ResultSet|ResultSet}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + executeSql( + request?: protos.google.spanner.v1.IExecuteSqlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IExecuteSqlRequest | undefined, + {} | undefined, + ] + >; + executeSql( + request: protos.google.spanner.v1.IExecuteSqlRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IExecuteSqlRequest | null | undefined, + {} | null | undefined + >, + ): void; + executeSql( + request: protos.google.spanner.v1.IExecuteSqlRequest, + callback: Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IExecuteSqlRequest | null | undefined, + {} | null | undefined + >, + ): void; + executeSql( + request?: protos.google.spanner.v1.IExecuteSqlRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IExecuteSqlRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IExecuteSqlRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IExecuteSqlRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('executeSql request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IExecuteSqlRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('executeSql response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .executeSql(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IExecuteSqlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('executeSql response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Executes a batch of SQL DML statements. This method allows many statements + * to be run with lower latency than submitting them sequentially with + * {@link protos.google.spanner.v1.Spanner.ExecuteSql|ExecuteSql}. + * + * Statements are executed in sequential order. A request can succeed even if + * a statement fails. The + * {@link protos.google.spanner.v1.ExecuteBatchDmlResponse.status|ExecuteBatchDmlResponse.status} + * field in the response provides information about the statement that failed. + * Clients must inspect this field to determine whether an error occurred. + * + * Execution stops after the first failed statement; the remaining statements + * are not executed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the DML statements should be performed. + * @param {google.spanner.v1.TransactionSelector} request.transaction + * Required. The transaction to use. Must be a read-write transaction. + * + * To protect against replays, single-use transactions are not supported. The + * caller must either supply an existing transaction ID or begin a new + * transaction. + * @param {number[]} request.statements + * Required. The list of statements to execute in this batch. Statements are + * executed serially, such that the effects of statement `i` are visible to + * statement `i+1`. Each statement must be a DML statement. Execution stops at + * the first failed statement; the remaining statements are not executed. + * + * Callers must provide at least one statement. + * @param {number} request.seqno + * Required. A per-transaction sequence number used to identify this request. + * This field makes each request idempotent such that if the request is + * received multiple times, at most one succeeds. + * + * The sequence number must be monotonically increasing within the + * transaction. If a request arrives for the first time with an out-of-order + * sequence number, the transaction might be aborted. Replays of previously + * handled requests yield the same response as the first execution. + * @param {google.spanner.v1.RequestOptions} request.requestOptions + * Common options for this request. + * @param {boolean} [request.lastStatements] + * Optional. If set to `true`, this request marks the end of the transaction. + * After these statements execute, you must commit or abort the transaction. + * Attempts to execute any other requests against this transaction + * (including reads and queries) are rejected. + * + * Setting this option might cause some error reporting to be deferred until + * commit time (for example, validation of unique constraints). Given this, + * successful execution of statements shouldn't be assumed until a subsequent + * `Commit` call completes successfully. + * @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.spanner.v1.ExecuteBatchDmlResponse|ExecuteBatchDmlResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + executeBatchDml( + request?: protos.google.spanner.v1.IExecuteBatchDmlRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.IExecuteBatchDmlResponse, + protos.google.spanner.v1.IExecuteBatchDmlRequest | undefined, + {} | undefined, + ] + >; + executeBatchDml( + request: protos.google.spanner.v1.IExecuteBatchDmlRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.IExecuteBatchDmlResponse, + protos.google.spanner.v1.IExecuteBatchDmlRequest | null | undefined, + {} | null | undefined + >, + ): void; + executeBatchDml( + request: protos.google.spanner.v1.IExecuteBatchDmlRequest, + callback: Callback< + protos.google.spanner.v1.IExecuteBatchDmlResponse, + protos.google.spanner.v1.IExecuteBatchDmlRequest | null | undefined, + {} | null | undefined + >, + ): void; + executeBatchDml( + request?: protos.google.spanner.v1.IExecuteBatchDmlRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.IExecuteBatchDmlResponse, + protos.google.spanner.v1.IExecuteBatchDmlRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.IExecuteBatchDmlResponse, + protos.google.spanner.v1.IExecuteBatchDmlRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.IExecuteBatchDmlResponse, + protos.google.spanner.v1.IExecuteBatchDmlRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('executeBatchDml request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.IExecuteBatchDmlResponse, + protos.google.spanner.v1.IExecuteBatchDmlRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('executeBatchDml response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .executeBatchDml(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.IExecuteBatchDmlResponse, + protos.google.spanner.v1.IExecuteBatchDmlRequest | undefined, + {} | undefined, + ]) => { + this._log.info('executeBatchDml response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Reads rows from the database using key lookups and scans, as a + * simple key/value style alternative to + * {@link protos.google.spanner.v1.Spanner.ExecuteSql|ExecuteSql}. This method can't be + * used to return a result set larger than 10 MiB; if the read matches more + * data than that, the read fails with a `FAILED_PRECONDITION` + * error. + * + * Reads inside read-write transactions might return `ABORTED`. If + * this occurs, the application should restart the transaction from + * the beginning. See {@link protos.google.spanner.v1.Transaction|Transaction} for more + * details. + * + * Larger result sets can be yielded in streaming fashion by calling + * {@link protos.google.spanner.v1.Spanner.StreamingRead|StreamingRead} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the read should be performed. + * @param {google.spanner.v1.TransactionSelector} request.transaction + * The transaction to use. If none is provided, the default is a + * temporary read-only transaction with strong concurrency. + * @param {string} request.table + * Required. The name of the table in the database to be read. + * @param {string} request.index + * If non-empty, the name of an index on + * {@link protos.google.spanner.v1.ReadRequest.table|table}. This index is used instead of + * the table primary key when interpreting + * {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} and sorting result rows. + * See {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} for further + * information. + * @param {string[]} request.columns + * Required. The columns of {@link protos.google.spanner.v1.ReadRequest.table|table} to be + * returned for each row matching this request. + * @param {google.spanner.v1.KeySet} request.keySet + * Required. `key_set` identifies the rows to be yielded. `key_set` names the + * primary keys of the rows in {@link protos.google.spanner.v1.ReadRequest.table|table} to + * be yielded, unless {@link protos.google.spanner.v1.ReadRequest.index|index} is present. + * If {@link protos.google.spanner.v1.ReadRequest.index|index} is present, then + * {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} instead names index keys + * in {@link protos.google.spanner.v1.ReadRequest.index|index}. + * + * If the {@link protos.google.spanner.v1.ReadRequest.partition_token|partition_token} + * field is empty, rows are yielded in table primary key order (if + * {@link protos.google.spanner.v1.ReadRequest.index|index} is empty) or index key order + * (if {@link protos.google.spanner.v1.ReadRequest.index|index} is non-empty). If the + * {@link protos.google.spanner.v1.ReadRequest.partition_token|partition_token} field + * isn't empty, rows are yielded in an unspecified order. + * + * It isn't an error for the `key_set` to name rows that don't + * exist in the database. Read yields nothing for nonexistent rows. + * @param {number} request.limit + * If greater than zero, only the first `limit` rows are yielded. If `limit` + * is zero, the default is no limit. A limit can't be specified if + * `partition_token` is set. + * @param {Buffer} request.resumeToken + * If this request is resuming a previously interrupted read, + * `resume_token` should be copied from the last + * {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} yielded before the + * interruption. Doing this enables the new read to resume where the last read + * left off. The rest of the request parameters must exactly match the request + * that yielded this token. + * @param {Buffer} request.partitionToken + * If present, results are restricted to the specified partition + * previously created using `PartitionRead`. There must be an exact + * match for the values of fields common to this message and the + * PartitionReadRequest message used to create this partition_token. + * @param {google.spanner.v1.RequestOptions} request.requestOptions + * Common options for this request. + * @param {google.spanner.v1.DirectedReadOptions} request.directedReadOptions + * Directed read options for this request. + * @param {boolean} request.dataBoostEnabled + * If this is for a partitioned read and this field is set to `true`, the + * request is executed with Spanner Data Boost independent compute resources. + * + * If the field is set to `true` but the request doesn't set + * `partition_token`, the API returns an `INVALID_ARGUMENT` error. + * @param {google.spanner.v1.ReadRequest.OrderBy} [request.orderBy] + * Optional. Order for the returned rows. + * + * By default, Spanner returns result rows in primary key order except for + * PartitionRead requests. For applications that don't require rows to be + * returned in primary key (`ORDER_BY_PRIMARY_KEY`) order, setting + * `ORDER_BY_NO_ORDER` option allows Spanner to optimize row retrieval, + * resulting in lower latencies in certain cases (for example, bulk point + * lookups). + * @param {google.spanner.v1.ReadRequest.LockHint} [request.lockHint] + * Optional. Lock Hint for the request, it can only be used with read-write + * transactions. + * @param {google.spanner.v1.RoutingHint} [request.routingHint] + * Optional. If present, it makes the Spanner requests location-aware. + * + * It gives the server hints that can be used to route the request + * to an appropriate server, potentially significantly decreasing latency and + * improving throughput. To achieve improved performance, most fields must be + * filled in with accurate values. + * @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.spanner.v1.ResultSet|ResultSet}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + read( + request?: protos.google.spanner.v1.IReadRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IReadRequest | undefined, + {} | undefined, + ] + >; + read( + request: protos.google.spanner.v1.IReadRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IReadRequest | null | undefined, + {} | null | undefined + >, + ): void; + read( + request: protos.google.spanner.v1.IReadRequest, + callback: Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IReadRequest | null | undefined, + {} | null | undefined + >, + ): void; + read( + request?: protos.google.spanner.v1.IReadRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IReadRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IReadRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IReadRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('read request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IReadRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('read response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .read(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.IResultSet, + protos.google.spanner.v1.IReadRequest | undefined, + {} | undefined, + ]) => { + this._log.info('read response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Begins a new transaction. This step can often be skipped: + * {@link protos.google.spanner.v1.Spanner.Read|Read}, + * {@link protos.google.spanner.v1.Spanner.ExecuteSql|ExecuteSql} and + * {@link protos.google.spanner.v1.Spanner.Commit|Commit} can begin a new transaction as a + * side-effect. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the transaction runs. + * @param {google.spanner.v1.TransactionOptions} request.options + * Required. Options for the new transaction. + * @param {google.spanner.v1.RequestOptions} request.requestOptions + * Common options for this request. + * Priority is ignored for this request. Setting the priority in this + * `request_options` struct doesn't do anything. To set the priority for a + * transaction, set it on the reads and writes that are part of this + * transaction instead. + * @param {google.spanner.v1.Mutation} [request.mutationKey] + * Optional. Required for read-write transactions on a multiplexed session + * that commit mutations but don't perform any reads or queries. You must + * randomly select one of the mutations from the mutation set and send it as a + * part of this request. + * @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.spanner.v1.Transaction|Transaction}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + beginTransaction( + request?: protos.google.spanner.v1.IBeginTransactionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.ITransaction, + protos.google.spanner.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + >; + beginTransaction( + request: protos.google.spanner.v1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.ITransaction, + protos.google.spanner.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + ): void; + beginTransaction( + request: protos.google.spanner.v1.IBeginTransactionRequest, + callback: Callback< + protos.google.spanner.v1.ITransaction, + protos.google.spanner.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + ): void; + beginTransaction( + request?: protos.google.spanner.v1.IBeginTransactionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.ITransaction, + protos.google.spanner.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.ITransaction, + protos.google.spanner.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.ITransaction, + protos.google.spanner.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('beginTransaction request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.ITransaction, + protos.google.spanner.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('beginTransaction response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .beginTransaction(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.ITransaction, + protos.google.spanner.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('beginTransaction response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Commits a transaction. The request includes the mutations to be + * applied to rows in the database. + * + * `Commit` might return an `ABORTED` error. This can occur at any time; + * commonly, the cause is conflicts with concurrent + * transactions. However, it can also happen for a variety of other + * reasons. If `Commit` returns `ABORTED`, the caller should retry + * the transaction from the beginning, reusing the same session. + * + * On very rare occasions, `Commit` might return `UNKNOWN`. This can happen, + * for example, if the client job experiences a 1+ hour networking failure. + * At that point, Cloud Spanner has lost track of the transaction outcome and + * we recommend that you perform another read from the database to see the + * state of things as they are now. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the transaction to be committed is running. + * @param {Buffer} request.transactionId + * Commit a previously-started transaction. + * @param {google.spanner.v1.TransactionOptions} request.singleUseTransaction + * Execute mutations in a temporary transaction. Note that unlike + * commit of a previously-started transaction, commit with a + * temporary transaction is non-idempotent. That is, if the + * `CommitRequest` is sent to Cloud Spanner more than once (for + * instance, due to retries in the application, or in the + * transport library), it's possible that the mutations are + * executed more than once. If this is undesirable, use + * {@link protos.google.spanner.v1.Spanner.BeginTransaction|BeginTransaction} and + * {@link protos.google.spanner.v1.Spanner.Commit|Commit} instead. + * @param {number[]} request.mutations + * The mutations to be executed when this transaction commits. All + * mutations are applied atomically, in the order they appear in + * this list. + * @param {boolean} request.returnCommitStats + * If `true`, then statistics related to the transaction is included in + * the {@link protos.google.spanner.v1.CommitResponse.commit_stats|CommitResponse}. + * Default value is `false`. + * @param {google.protobuf.Duration} [request.maxCommitDelay] + * Optional. The amount of latency this request is configured to incur in + * order to improve throughput. If this field isn't set, Spanner assumes + * requests are relatively latency sensitive and automatically determines an + * appropriate delay time. You can specify a commit delay value between 0 and + * 500 ms. + * @param {google.spanner.v1.RequestOptions} request.requestOptions + * Common options for this request. + * @param {google.spanner.v1.MultiplexedSessionPrecommitToken} [request.precommitToken] + * Optional. If the read-write transaction was executed on a multiplexed + * session, then you must include the precommit token with the highest + * sequence number received in this transaction attempt. Failing to do so + * results in a `FailedPrecondition` error. + * @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.spanner.v1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + commit( + request?: protos.google.spanner.v1.ICommitRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.ICommitResponse, + protos.google.spanner.v1.ICommitRequest | undefined, + {} | undefined, + ] + >; + commit( + request: protos.google.spanner.v1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.ICommitResponse, + protos.google.spanner.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + commit( + request: protos.google.spanner.v1.ICommitRequest, + callback: Callback< + protos.google.spanner.v1.ICommitResponse, + protos.google.spanner.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): void; + commit( + request?: protos.google.spanner.v1.ICommitRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.ICommitResponse, + protos.google.spanner.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.ICommitResponse, + protos.google.spanner.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.ICommitResponse, + protos.google.spanner.v1.ICommitRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('commit request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.ICommitResponse, + protos.google.spanner.v1.ICommitRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('commit response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .commit(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.ICommitResponse, + protos.google.spanner.v1.ICommitRequest | undefined, + {} | undefined, + ]) => { + this._log.info('commit response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Rolls back a transaction, releasing any locks it holds. It's a good + * idea to call this for any transaction that includes one or more + * {@link protos.google.spanner.v1.Spanner.Read|Read} or + * {@link protos.google.spanner.v1.Spanner.ExecuteSql|ExecuteSql} requests and ultimately + * decides not to commit. + * + * `Rollback` returns `OK` if it successfully aborts the transaction, the + * transaction was already aborted, or the transaction isn't + * found. `Rollback` never returns `ABORTED`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the transaction to roll back is running. + * @param {Buffer} request.transactionId + * Required. The transaction to roll back. + * @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.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. + */ + rollback( + request?: protos.google.spanner.v1.IRollbackRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IRollbackRequest | undefined, + {} | undefined, + ] + >; + rollback( + request: protos.google.spanner.v1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + rollback( + request: protos.google.spanner.v1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): void; + rollback( + request?: protos.google.spanner.v1.IRollbackRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IRollbackRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('rollback request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IRollbackRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('rollback response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .rollback(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.spanner.v1.IRollbackRequest | undefined, + {} | undefined, + ]) => { + this._log.info('rollback response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Creates a set of partition tokens that can be used to execute a query + * operation in parallel. Each of the returned partition tokens can be used + * by {@link protos.google.spanner.v1.Spanner.ExecuteStreamingSql|ExecuteStreamingSql} to + * specify a subset of the query result to read. The same session and + * read-only transaction must be used by the `PartitionQueryRequest` used to + * create the partition tokens and the `ExecuteSqlRequests` that use the + * partition tokens. + * + * Partition tokens become invalid when the session used to create them + * is deleted, is idle for too long, begins a new transaction, or becomes too + * old. When any of these happen, it isn't possible to resume the query, and + * the whole operation must be restarted from the beginning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session used to create the partitions. + * @param {google.spanner.v1.TransactionSelector} request.transaction + * Read-only snapshot transactions are supported, read and write and + * single-use transactions are not. + * @param {string} request.sql + * Required. The query request to generate partitions for. The request fails + * if the query isn't root partitionable. For a query to be root + * partitionable, it needs to satisfy a few conditions. For example, if the + * query execution plan contains a distributed union operator, then it must be + * the first operator in the plan. For more information about other + * conditions, see [Read data in + * parallel](https://cloud.google.com/spanner/docs/reads#read_data_in_parallel). + * + * The query request must not contain DML commands, such as `INSERT`, + * `UPDATE`, or `DELETE`. Use + * {@link protos.google.spanner.v1.Spanner.ExecuteStreamingSql|`ExecuteStreamingSql`} with + * a `PartitionedDml` transaction for large, partition-friendly DML + * operations. + * @param {google.protobuf.Struct} [request.params] + * Optional. Parameter names and values that bind to placeholders in the SQL + * string. + * + * A parameter placeholder consists of the `@` character followed by the + * parameter name (for example, `@firstName`). Parameter names can contain + * letters, numbers, and underscores. + * + * Parameters can appear anywhere that a literal value is expected. The same + * parameter name can be used more than once, for example: + * + * `"WHERE id > @msg_id AND id < @msg_id + 100"` + * + * It's an error to execute a SQL statement with unbound parameters. + * @param {number[]} [request.paramTypes] + * Optional. It isn't always possible for Cloud Spanner to infer the right SQL + * type from a JSON value. For example, values of type `BYTES` and values of + * type `STRING` both appear in + * {@link protos.google.spanner.v1.PartitionQueryRequest.params|params} as JSON strings. + * + * In these cases, `param_types` can be used to specify the exact + * SQL type for some or all of the SQL query parameters. See the + * definition of {@link protos.google.spanner.v1.Type|Type} for more information + * about SQL types. + * @param {google.spanner.v1.PartitionOptions} request.partitionOptions + * Additional options that affect how many partitions are created. + * @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.spanner.v1.PartitionResponse|PartitionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + partitionQuery( + request?: protos.google.spanner.v1.IPartitionQueryRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionQueryRequest | undefined, + {} | undefined, + ] + >; + partitionQuery( + request: protos.google.spanner.v1.IPartitionQueryRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionQueryRequest | null | undefined, + {} | null | undefined + >, + ): void; + partitionQuery( + request: protos.google.spanner.v1.IPartitionQueryRequest, + callback: Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionQueryRequest | null | undefined, + {} | null | undefined + >, + ): void; + partitionQuery( + request?: protos.google.spanner.v1.IPartitionQueryRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionQueryRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionQueryRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionQueryRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('partitionQuery request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionQueryRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('partitionQuery response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .partitionQuery(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionQueryRequest | undefined, + {} | undefined, + ]) => { + this._log.info('partitionQuery response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Creates a set of partition tokens that can be used to execute a read + * operation in parallel. Each of the returned partition tokens can be used + * by {@link protos.google.spanner.v1.Spanner.StreamingRead|StreamingRead} to specify a + * subset of the read result to read. The same session and read-only + * transaction must be used by the `PartitionReadRequest` used to create the + * partition tokens and the `ReadRequests` that use the partition tokens. + * There are no ordering guarantees on rows returned among the returned + * partition tokens, or even within each individual `StreamingRead` call + * issued with a `partition_token`. + * + * Partition tokens become invalid when the session used to create them + * is deleted, is idle for too long, begins a new transaction, or becomes too + * old. When any of these happen, it isn't possible to resume the read, and + * the whole operation must be restarted from the beginning. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session used to create the partitions. + * @param {google.spanner.v1.TransactionSelector} request.transaction + * Read only snapshot transactions are supported, read/write and single use + * transactions are not. + * @param {string} request.table + * Required. The name of the table in the database to be read. + * @param {string} request.index + * If non-empty, the name of an index on + * {@link protos.google.spanner.v1.PartitionReadRequest.table|table}. This index is used + * instead of the table primary key when interpreting + * {@link protos.google.spanner.v1.PartitionReadRequest.key_set|key_set} and sorting + * result rows. See {@link protos.google.spanner.v1.PartitionReadRequest.key_set|key_set} + * for further information. + * @param {string[]} request.columns + * The columns of {@link protos.google.spanner.v1.PartitionReadRequest.table|table} to be + * returned for each row matching this request. + * @param {google.spanner.v1.KeySet} request.keySet + * Required. `key_set` identifies the rows to be yielded. `key_set` names the + * primary keys of the rows in + * {@link protos.google.spanner.v1.PartitionReadRequest.table|table} to be yielded, unless + * {@link protos.google.spanner.v1.PartitionReadRequest.index|index} is present. If + * {@link protos.google.spanner.v1.PartitionReadRequest.index|index} is present, then + * {@link protos.google.spanner.v1.PartitionReadRequest.key_set|key_set} instead names + * index keys in {@link protos.google.spanner.v1.PartitionReadRequest.index|index}. + * + * It isn't an error for the `key_set` to name rows that don't + * exist in the database. Read yields nothing for nonexistent rows. + * @param {google.spanner.v1.PartitionOptions} request.partitionOptions + * Additional options that affect how many partitions are created. + * @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.spanner.v1.PartitionResponse|PartitionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + */ + partitionRead( + request?: protos.google.spanner.v1.IPartitionReadRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionReadRequest | undefined, + {} | undefined, + ] + >; + partitionRead( + request: protos.google.spanner.v1.IPartitionReadRequest, + options: CallOptions, + callback: Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionReadRequest | null | undefined, + {} | null | undefined + >, + ): void; + partitionRead( + request: protos.google.spanner.v1.IPartitionReadRequest, + callback: Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionReadRequest | null | undefined, + {} | null | undefined + >, + ): void; + partitionRead( + request?: protos.google.spanner.v1.IPartitionReadRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionReadRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionReadRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionReadRequest | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('partitionRead request %j', request); + const wrappedCallback: + | Callback< + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionReadRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('partitionRead response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .partitionRead(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.spanner.v1.IPartitionResponse, + protos.google.spanner.v1.IPartitionReadRequest | undefined, + {} | undefined, + ]) => { + this._log.info('partitionRead response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + + /** + * Like {@link protos.google.spanner.v1.Spanner.ExecuteSql|ExecuteSql}, except returns the + * result set as a stream. Unlike + * {@link protos.google.spanner.v1.Spanner.ExecuteSql|ExecuteSql}, there is no limit on + * the size of the returned result set. However, no individual row in the + * result set can exceed 100 MiB, and no column value can exceed 10 MiB. + * + * The query string can be SQL or [Graph Query Language + * (GQL)](https://cloud.google.com/spanner/docs/reference/standard-sql/graph-intro). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the SQL query should be performed. + * @param {google.spanner.v1.TransactionSelector} request.transaction + * The transaction to use. + * + * For queries, if none is provided, the default is a temporary read-only + * transaction with strong concurrency. + * + * Standard DML statements require a read-write transaction. To protect + * against replays, single-use transactions are not supported. The caller + * must either supply an existing transaction ID or begin a new transaction. + * + * Partitioned DML requires an existing Partitioned DML transaction ID. + * @param {string} request.sql + * Required. The SQL string. + * @param {google.protobuf.Struct} request.params + * Parameter names and values that bind to placeholders in the SQL string. + * + * A parameter placeholder consists of the `@` character followed by the + * parameter name (for example, `@firstName`). Parameter names must conform + * to the naming requirements of identifiers as specified at + * https://cloud.google.com/spanner/docs/lexical#identifiers. + * + * Parameters can appear anywhere that a literal value is expected. The same + * parameter name can be used more than once, for example: + * + * `"WHERE id > @msg_id AND id < @msg_id + 100"` + * + * It's an error to execute a SQL statement with unbound parameters. + * @param {number[]} request.paramTypes + * It isn't always possible for Cloud Spanner to infer the right SQL type + * from a JSON value. For example, values of type `BYTES` and values + * of type `STRING` both appear in + * {@link protos.google.spanner.v1.ExecuteSqlRequest.params|params} as JSON strings. + * + * In these cases, you can use `param_types` to specify the exact + * SQL type for some or all of the SQL statement parameters. See the + * definition of {@link protos.google.spanner.v1.Type|Type} for more information + * about SQL types. + * @param {Buffer} request.resumeToken + * If this request is resuming a previously interrupted SQL statement + * execution, `resume_token` should be copied from the last + * {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} yielded before the + * interruption. Doing this enables the new SQL statement execution to resume + * where the last one left off. The rest of the request parameters must + * exactly match the request that yielded this token. + * @param {google.spanner.v1.ExecuteSqlRequest.QueryMode} request.queryMode + * Used to control the amount of debugging information returned in + * {@link protos.google.spanner.v1.ResultSetStats|ResultSetStats}. If + * {@link protos.google.spanner.v1.ExecuteSqlRequest.partition_token|partition_token} is + * set, {@link protos.google.spanner.v1.ExecuteSqlRequest.query_mode|query_mode} can only + * be set to + * {@link protos.google.spanner.v1.ExecuteSqlRequest.QueryMode.NORMAL|QueryMode.NORMAL}. + * @param {Buffer} request.partitionToken + * If present, results are restricted to the specified partition + * previously created using `PartitionQuery`. There must be an exact + * match for the values of fields common to this message and the + * `PartitionQueryRequest` message used to create this `partition_token`. + * @param {number} request.seqno + * A per-transaction sequence number used to identify this request. This field + * makes each request idempotent such that if the request is received multiple + * times, at most one succeeds. + * + * The sequence number must be monotonically increasing within the + * transaction. If a request arrives for the first time with an out-of-order + * sequence number, the transaction can be aborted. Replays of previously + * handled requests yield the same response as the first execution. + * + * Required for DML statements. Ignored for queries. + * @param {google.spanner.v1.ExecuteSqlRequest.QueryOptions} request.queryOptions + * Query optimizer configuration to use for the given query. + * @param {google.spanner.v1.RequestOptions} request.requestOptions + * Common options for this request. + * @param {google.spanner.v1.DirectedReadOptions} request.directedReadOptions + * Directed read options for this request. + * @param {boolean} request.dataBoostEnabled + * If this is for a partitioned query and this field is set to `true`, the + * request is executed with Spanner Data Boost independent compute resources. + * + * If the field is set to `true` but the request doesn't set + * `partition_token`, the API returns an `INVALID_ARGUMENT` error. + * @param {boolean} [request.lastStatement] + * Optional. If set to `true`, this statement marks the end of the + * transaction. After this statement executes, you must commit or abort the + * transaction. Attempts to execute any other requests against this + * transaction (including reads and queries) are rejected. + * + * For DML statements, setting this option might cause some error reporting to + * be deferred until commit time (for example, validation of unique + * constraints). Given this, successful execution of a DML statement shouldn't + * be assumed until a subsequent `Commit` call completes successfully. + * @param {google.spanner.v1.RoutingHint} [request.routingHint] + * Optional. If present, it makes the Spanner requests location-aware. + * + * It gives the server hints that can be used to route the request + * to an appropriate server, potentially significantly decreasing latency and + * improving throughput. To achieve improved performance, most fields must be + * filled in with accurate values. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + */ + executeStreamingSql( + request?: protos.google.spanner.v1.IExecuteSqlRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('executeStreamingSql stream %j', options); + return this.innerApiCalls.executeStreamingSql(request, options); + } + + /** + * Like {@link protos.google.spanner.v1.Spanner.Read|Read}, except returns the result set + * as a stream. Unlike {@link protos.google.spanner.v1.Spanner.Read|Read}, there is no + * limit on the size of the returned result set. However, no individual row in + * the result set can exceed 100 MiB, and no column value can exceed + * 10 MiB. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the read should be performed. + * @param {google.spanner.v1.TransactionSelector} request.transaction + * The transaction to use. If none is provided, the default is a + * temporary read-only transaction with strong concurrency. + * @param {string} request.table + * Required. The name of the table in the database to be read. + * @param {string} request.index + * If non-empty, the name of an index on + * {@link protos.google.spanner.v1.ReadRequest.table|table}. This index is used instead of + * the table primary key when interpreting + * {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} and sorting result rows. + * See {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} for further + * information. + * @param {string[]} request.columns + * Required. The columns of {@link protos.google.spanner.v1.ReadRequest.table|table} to be + * returned for each row matching this request. + * @param {google.spanner.v1.KeySet} request.keySet + * Required. `key_set` identifies the rows to be yielded. `key_set` names the + * primary keys of the rows in {@link protos.google.spanner.v1.ReadRequest.table|table} to + * be yielded, unless {@link protos.google.spanner.v1.ReadRequest.index|index} is present. + * If {@link protos.google.spanner.v1.ReadRequest.index|index} is present, then + * {@link protos.google.spanner.v1.ReadRequest.key_set|key_set} instead names index keys + * in {@link protos.google.spanner.v1.ReadRequest.index|index}. + * + * If the {@link protos.google.spanner.v1.ReadRequest.partition_token|partition_token} + * field is empty, rows are yielded in table primary key order (if + * {@link protos.google.spanner.v1.ReadRequest.index|index} is empty) or index key order + * (if {@link protos.google.spanner.v1.ReadRequest.index|index} is non-empty). If the + * {@link protos.google.spanner.v1.ReadRequest.partition_token|partition_token} field + * isn't empty, rows are yielded in an unspecified order. + * + * It isn't an error for the `key_set` to name rows that don't + * exist in the database. Read yields nothing for nonexistent rows. + * @param {number} request.limit + * If greater than zero, only the first `limit` rows are yielded. If `limit` + * is zero, the default is no limit. A limit can't be specified if + * `partition_token` is set. + * @param {Buffer} request.resumeToken + * If this request is resuming a previously interrupted read, + * `resume_token` should be copied from the last + * {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} yielded before the + * interruption. Doing this enables the new read to resume where the last read + * left off. The rest of the request parameters must exactly match the request + * that yielded this token. + * @param {Buffer} request.partitionToken + * If present, results are restricted to the specified partition + * previously created using `PartitionRead`. There must be an exact + * match for the values of fields common to this message and the + * PartitionReadRequest message used to create this partition_token. + * @param {google.spanner.v1.RequestOptions} request.requestOptions + * Common options for this request. + * @param {google.spanner.v1.DirectedReadOptions} request.directedReadOptions + * Directed read options for this request. + * @param {boolean} request.dataBoostEnabled + * If this is for a partitioned read and this field is set to `true`, the + * request is executed with Spanner Data Boost independent compute resources. + * + * If the field is set to `true` but the request doesn't set + * `partition_token`, the API returns an `INVALID_ARGUMENT` error. + * @param {google.spanner.v1.ReadRequest.OrderBy} [request.orderBy] + * Optional. Order for the returned rows. + * + * By default, Spanner returns result rows in primary key order except for + * PartitionRead requests. For applications that don't require rows to be + * returned in primary key (`ORDER_BY_PRIMARY_KEY`) order, setting + * `ORDER_BY_NO_ORDER` option allows Spanner to optimize row retrieval, + * resulting in lower latencies in certain cases (for example, bulk point + * lookups). + * @param {google.spanner.v1.ReadRequest.LockHint} [request.lockHint] + * Optional. Lock Hint for the request, it can only be used with read-write + * transactions. + * @param {google.spanner.v1.RoutingHint} [request.routingHint] + * Optional. If present, it makes the Spanner requests location-aware. + * + * It gives the server hints that can be used to route the request + * to an appropriate server, potentially significantly decreasing latency and + * improving throughput. To achieve improved performance, most fields must be + * filled in with accurate values. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.spanner.v1.PartialResultSet|PartialResultSet} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + */ + streamingRead( + request?: protos.google.spanner.v1.IReadRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('streamingRead stream %j', options); + return this.innerApiCalls.streamingRead(request, options); + } + + /** + * Batches the supplied mutation groups in a collection of efficient + * transactions. All mutations in a group are committed atomically. However, + * mutations across groups can be committed non-atomically in an unspecified + * order and thus, they must be independent of each other. Partial failure is + * possible, that is, some groups might have been committed successfully, + * while some might have failed. The results of individual batches are + * streamed into the response as the batches are applied. + * + * `BatchWrite` requests are not replay protected, meaning that each mutation + * group can be applied more than once. Replays of non-idempotent mutations + * can have undesirable effects. For example, replays of an insert mutation + * can produce an already exists error or if you use generated or commit + * timestamp-based keys, it can result in additional rows being added to the + * mutation's table. We recommend structuring your mutation groups to be + * idempotent to avoid this issue. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.session + * Required. The session in which the batch request is to be run. + * @param {google.spanner.v1.RequestOptions} request.requestOptions + * Common options for this request. + * @param {number[]} request.mutationGroups + * Required. The groups of mutations to be applied. + * @param {boolean} [request.excludeTxnFromChangeStreams] + * Optional. If you don't set the `exclude_txn_from_change_streams` option or + * if it's set to `false`, then any change streams monitoring columns modified + * by transactions will capture the updates made within that transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.spanner.v1.BatchWriteResponse|BatchWriteResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + */ + batchWrite( + request?: protos.google.spanner.v1.IBatchWriteRequest, + options?: CallOptions, + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + session: request.session ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + this._log.info('batchWrite stream %j', options); + return this.innerApiCalls.batchWrite(request, options); + } + + /** + * Lists all sessions in a given database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database in which to list sessions. + * @param {number} request.pageSize + * Number of sessions to be returned in the response. If 0 or less, defaults + * to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.v1.ListSessionsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.v1.ListSessionsResponse|ListSessionsResponse}. + * @param {string} request.filter + * An expression for filtering the results of the request. Filter rules are + * case insensitive. The fields eligible for filtering are: + * + * * `labels.key` where key is the name of a label + * + * Some examples of using filters are: + * + * * `labels.env:*` --> The session has the label "env". + * * `labels.env:dev` --> The session has the label "env" and the value of + * the label contains the string "dev". + * @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 Array of {@link protos.google.spanner.v1.Session|Session}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listSessions( + request?: protos.google.spanner.v1.IListSessionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.spanner.v1.ISession[], + protos.google.spanner.v1.IListSessionsRequest | null, + protos.google.spanner.v1.IListSessionsResponse, + ] + >; + listSessions( + request: protos.google.spanner.v1.IListSessionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.spanner.v1.IListSessionsRequest, + protos.google.spanner.v1.IListSessionsResponse | null | undefined, + protos.google.spanner.v1.ISession + >, + ): void; + listSessions( + request: protos.google.spanner.v1.IListSessionsRequest, + callback: PaginationCallback< + protos.google.spanner.v1.IListSessionsRequest, + protos.google.spanner.v1.IListSessionsResponse | null | undefined, + protos.google.spanner.v1.ISession + >, + ): void; + listSessions( + request?: protos.google.spanner.v1.IListSessionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< + protos.google.spanner.v1.IListSessionsRequest, + protos.google.spanner.v1.IListSessionsResponse | null | undefined, + protos.google.spanner.v1.ISession + >, + callback?: PaginationCallback< + protos.google.spanner.v1.IListSessionsRequest, + protos.google.spanner.v1.IListSessionsResponse | null | undefined, + protos.google.spanner.v1.ISession + >, + ): Promise< + [ + protos.google.spanner.v1.ISession[], + protos.google.spanner.v1.IListSessionsRequest | null, + protos.google.spanner.v1.IListSessionsResponse, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.spanner.v1.IListSessionsRequest, + protos.google.spanner.v1.IListSessionsResponse | null | undefined, + protos.google.spanner.v1.ISession + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listSessions values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listSessions request %j', request); + return this.innerApiCalls + .listSessions(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.spanner.v1.ISession[], + protos.google.spanner.v1.IListSessionsRequest | null, + protos.google.spanner.v1.IListSessionsResponse, + ]) => { + this._log.info('listSessions values %j', response); + return [response, input, output]; + }, + ); + } + + /** + * Equivalent to `listSessions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database in which to list sessions. + * @param {number} request.pageSize + * Number of sessions to be returned in the response. If 0 or less, defaults + * to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.v1.ListSessionsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.v1.ListSessionsResponse|ListSessionsResponse}. + * @param {string} request.filter + * An expression for filtering the results of the request. Filter rules are + * case insensitive. The fields eligible for filtering are: + * + * * `labels.key` where key is the name of a label + * + * Some examples of using filters are: + * + * * `labels.env:*` --> The session has the label "env". + * * `labels.env:dev` --> The session has the label "env" and the value of + * the label contains the string "dev". + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.spanner.v1.Session|Session} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listSessionsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listSessionsStream( + request?: protos.google.spanner.v1.IListSessionsRequest, + options?: CallOptions, + ): Transform { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + const defaultCallSettings = this._defaults['listSessions']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSessions stream %j', request); + return this.descriptors.page.listSessions.createStream( + this.innerApiCalls.listSessions as GaxCall, + request, + callSettings, + ); + } + + /** + * Equivalent to `listSessions`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database in which to list sessions. + * @param {number} request.pageSize + * Number of sessions to be returned in the response. If 0 or less, defaults + * to the server's maximum allowed page size. + * @param {string} request.pageToken + * If non-empty, `page_token` should contain a + * {@link protos.google.spanner.v1.ListSessionsResponse.next_page_token|next_page_token} + * from a previous + * {@link protos.google.spanner.v1.ListSessionsResponse|ListSessionsResponse}. + * @param {string} request.filter + * An expression for filtering the results of the request. Filter rules are + * case insensitive. The fields eligible for filtering are: + * + * * `labels.key` where key is the name of a label + * + * Some examples of using filters are: + * + * * `labels.env:*` --> The session has the label "env". + * * `labels.env:dev` --> The session has the label "env" and the value of + * the label contains the string "dev". + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.spanner.v1.Session|Session}. The API will be called under the hood as needed, once per the page, + * 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. + */ + listSessionsAsync( + request?: protos.google.spanner.v1.IListSessionsRequest, + options?: CallOptions, + ): AsyncIterable { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + const defaultCallSettings = this._defaults['listSessions']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => { + throw err; + }); + this._log.info('listSessions iterate %j', request); + return this.descriptors.page.listSessions.asyncIterate( + this.innerApiCalls['listSessions'] as GaxCall, + request as {}, + callSettings, + ) as AsyncIterable; + } + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified database resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @returns {string} Resource name string. + */ + databasePath(project: string, instance: string, database: string) { + return this.pathTemplates.databasePathTemplate.render({ + project: project, + instance: instance, + database: database, + }); + } + + /** + * Parse the project from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).project; + } + + /** + * Parse the instance from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).instance; + } + + /** + * Parse the database from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).database; + } + + /** + * Return a fully-qualified session resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @param {string} session + * @returns {string} Resource name string. + */ + sessionPath( + project: string, + instance: string, + database: string, + session: string, + ) { + return this.pathTemplates.sessionPathTemplate.render({ + project: project, + instance: instance, + database: database, + session: session, + }); + } + + /** + * Parse the project from Session resource. + * + * @param {string} sessionName + * A fully-qualified path representing Session resource. + * @returns {string} A string representing the project. + */ + matchProjectFromSessionName(sessionName: string) { + return this.pathTemplates.sessionPathTemplate.match(sessionName).project; + } + + /** + * Parse the instance from Session resource. + * + * @param {string} sessionName + * A fully-qualified path representing Session resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromSessionName(sessionName: string) { + return this.pathTemplates.sessionPathTemplate.match(sessionName).instance; + } + + /** + * Parse the database from Session resource. + * + * @param {string} sessionName + * A fully-qualified path representing Session resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromSessionName(sessionName: string) { + return this.pathTemplates.sessionPathTemplate.match(sessionName).database; + } + + /** + * Parse the session from Session resource. + * + * @param {string} sessionName + * A fully-qualified path representing Session resource. + * @returns {string} A string representing the session. + */ + matchSessionFromSessionName(sessionName: string) { + return this.pathTemplates.sessionPathTemplate.match(sessionName).session; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.spannerStub && !this._terminated) { + return this.spannerStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/spanner/src/v1/spanner_client_config.json b/handwritten/spanner/src/v1/spanner_client_config.json new file mode 100644 index 00000000000..3d50869462d --- /dev/null +++ b/handwritten/spanner/src/v1/spanner_client_config.json @@ -0,0 +1,119 @@ +{ + "interfaces": { + "google.spanner.v1.Spanner": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "resource_exhausted_unavailable": [ + "RESOURCE_EXHAUSTED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + }, + "9442ca297df43f7314712e1a19d003838e738a45": { + "initial_retry_delay_millis": 250, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 32000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateSession": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "BatchCreateSessions": { + "timeout_millis": 60000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "GetSession": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "ListSessions": { + "timeout_millis": 3600000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "DeleteSession": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "ExecuteSql": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "ExecuteStreamingSql": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ExecuteBatchDml": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "Read": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "StreamingRead": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "BeginTransaction": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "Commit": { + "timeout_millis": 3600000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "Rollback": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "PartitionQuery": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "PartitionRead": { + "timeout_millis": 30000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "9442ca297df43f7314712e1a19d003838e738a45" + }, + "BatchWrite": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/spanner/src/v1/spanner_executor_proxy_client.ts b/handwritten/spanner/src/v1/spanner_executor_proxy_client.ts new file mode 100644 index 00000000000..675f8127b12 --- /dev/null +++ b/handwritten/spanner/src/v1/spanner_executor_proxy_client.ts @@ -0,0 +1,910 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import {PassThrough} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/spanner_executor_proxy_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './spanner_executor_proxy_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Service that executes SpannerActions asynchronously. + * @class + * @memberof v1 + */ +export class SpannerExecutorProxyClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('executor'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + spannerExecutorProxyStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of SpannerExecutorProxyClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new SpannerExecutorProxyClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof SpannerExecutorProxyClient; + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; + this._servicePath = 'spanner-cloud-executor.' + this._universeDomain; + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + + // 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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + backupPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/backups/{backup}', + ), + backupSchedulePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}/backupSchedules/{schedule}', + ), + databasePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}', + ), + databaseRolePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}/databaseRoles/{role}', + ), + instancePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}', + ), + instanceConfigPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instanceConfigs/{instance_config}', + ), + instancePartitionPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/instancePartitions/{instance_partition}', + ), + sessionPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}/sessions/{session}', + ), + }; + + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this.descriptors.stream = { + executeActionAsync: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.spanner.executor.v1.SpannerExecutorProxy', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')}, + ); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.spannerExecutorProxyStub) { + return this.spannerExecutorProxyStub; + } + + // Put together the "service stub" for + // google.spanner.executor.v1.SpannerExecutorProxy. + this.spannerExecutorProxyStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.spanner.executor.v1.SpannerExecutorProxy', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.spanner.executor.v1.SpannerExecutorProxy, + this._opts, + this._providedCustomServicePath, + ) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const spannerExecutorProxyStubMethods = ['executeActionAsync']; + for (const methodName of spannerExecutorProxyStubMethods) { + const callPromise = this.spannerExecutorProxyStub.then( + stub => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({objectMode: true}); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.', + ), + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = this.descriptors.stream[methodName] || undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.spannerExecutorProxyStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'spanner-cloud-executor.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'spanner-cloud-executor.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return []; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId( + callback?: Callback, + ): Promise | void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + + /** + * ExecuteActionAsync is a streaming call that starts executing a new Spanner + * action. + * + * For each request, the server will reply with one or more responses, but + * only the last response will contain status in the outcome. + * + * Responses can be matched to requests by action_id. It is allowed to have + * multiple actions in flight--in that case, actions are be executed in + * parallel. + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.spanner.executor.v1.SpannerAsyncActionRequest|SpannerAsyncActionRequest} for write() method, and + * will emit objects representing {@link protos.google.spanner.executor.v1.SpannerAsyncActionResponse|SpannerAsyncActionResponse} 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 + * region_tag:spanner-cloud-executor_v1_generated_SpannerExecutorProxy_ExecuteActionAsync_async + */ + executeActionAsync(options?: CallOptions): gax.CancellableStream { + this.initialize().catch(err => { + throw err; + }); + this._log.info('executeActionAsync stream %j', options); + return this.innerApiCalls.executeActionAsync(null, options); + } + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified backup resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} backup + * @returns {string} Resource name string. + */ + backupPath(project: string, instance: string, backup: string) { + return this.pathTemplates.backupPathTemplate.render({ + project: project, + instance: instance, + backup: backup, + }); + } + + /** + * Parse the project from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).project; + } + + /** + * Parse the instance from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).instance; + } + + /** + * Parse the backup from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the backup. + */ + matchBackupFromBackupName(backupName: string) { + return this.pathTemplates.backupPathTemplate.match(backupName).backup; + } + + /** + * Return a fully-qualified backupSchedule resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @param {string} schedule + * @returns {string} Resource name string. + */ + backupSchedulePath( + project: string, + instance: string, + database: string, + schedule: string, + ) { + return this.pathTemplates.backupSchedulePathTemplate.render({ + project: project, + instance: instance, + database: database, + schedule: schedule, + }); + } + + /** + * Parse the project from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).project; + } + + /** + * Parse the instance from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).instance; + } + + /** + * Parse the database from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).database; + } + + /** + * Parse the schedule from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the schedule. + */ + matchScheduleFromBackupScheduleName(backupScheduleName: string) { + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName, + ).schedule; + } + + /** + * Return a fully-qualified database resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @returns {string} Resource name string. + */ + databasePath(project: string, instance: string, database: string) { + return this.pathTemplates.databasePathTemplate.render({ + project: project, + instance: instance, + database: database, + }); + } + + /** + * Parse the project from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).project; + } + + /** + * Parse the instance from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).instance; + } + + /** + * Parse the database from Database resource. + * + * @param {string} databaseName + * A fully-qualified path representing Database resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseName(databaseName: string) { + return this.pathTemplates.databasePathTemplate.match(databaseName).database; + } + + /** + * Return a fully-qualified databaseRole resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @param {string} role + * @returns {string} Resource name string. + */ + databaseRolePath( + project: string, + instance: string, + database: string, + role: string, + ) { + return this.pathTemplates.databaseRolePathTemplate.render({ + project: project, + instance: instance, + database: database, + role: role, + }); + } + + /** + * Parse the project from DatabaseRole resource. + * + * @param {string} databaseRoleName + * A fully-qualified path representing DatabaseRole resource. + * @returns {string} A string representing the project. + */ + matchProjectFromDatabaseRoleName(databaseRoleName: string) { + return this.pathTemplates.databaseRolePathTemplate.match(databaseRoleName) + .project; + } + + /** + * Parse the instance from DatabaseRole resource. + * + * @param {string} databaseRoleName + * A fully-qualified path representing DatabaseRole resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromDatabaseRoleName(databaseRoleName: string) { + return this.pathTemplates.databaseRolePathTemplate.match(databaseRoleName) + .instance; + } + + /** + * Parse the database from DatabaseRole resource. + * + * @param {string} databaseRoleName + * A fully-qualified path representing DatabaseRole resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromDatabaseRoleName(databaseRoleName: string) { + return this.pathTemplates.databaseRolePathTemplate.match(databaseRoleName) + .database; + } + + /** + * Parse the role from DatabaseRole resource. + * + * @param {string} databaseRoleName + * A fully-qualified path representing DatabaseRole resource. + * @returns {string} A string representing the role. + */ + matchRoleFromDatabaseRoleName(databaseRoleName: string) { + return this.pathTemplates.databaseRolePathTemplate.match(databaseRoleName) + .role; + } + + /** + * Return a fully-qualified instance resource name string. + * + * @param {string} project + * @param {string} instance + * @returns {string} Resource name string. + */ + instancePath(project: string, instance: string) { + return this.pathTemplates.instancePathTemplate.render({ + project: project, + instance: instance, + }); + } + + /** + * Parse the project from Instance resource. + * + * @param {string} instanceName + * A fully-qualified path representing Instance resource. + * @returns {string} A string representing the project. + */ + matchProjectFromInstanceName(instanceName: string) { + return this.pathTemplates.instancePathTemplate.match(instanceName).project; + } + + /** + * Parse the instance from Instance resource. + * + * @param {string} instanceName + * A fully-qualified path representing Instance resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromInstanceName(instanceName: string) { + return this.pathTemplates.instancePathTemplate.match(instanceName).instance; + } + + /** + * Return a fully-qualified instanceConfig resource name string. + * + * @param {string} project + * @param {string} instance_config + * @returns {string} Resource name string. + */ + instanceConfigPath(project: string, instanceConfig: string) { + return this.pathTemplates.instanceConfigPathTemplate.render({ + project: project, + instance_config: instanceConfig, + }); + } + + /** + * Parse the project from InstanceConfig resource. + * + * @param {string} instanceConfigName + * A fully-qualified path representing InstanceConfig resource. + * @returns {string} A string representing the project. + */ + matchProjectFromInstanceConfigName(instanceConfigName: string) { + return this.pathTemplates.instanceConfigPathTemplate.match( + instanceConfigName, + ).project; + } + + /** + * Parse the instance_config from InstanceConfig resource. + * + * @param {string} instanceConfigName + * A fully-qualified path representing InstanceConfig resource. + * @returns {string} A string representing the instance_config. + */ + matchInstanceConfigFromInstanceConfigName(instanceConfigName: string) { + return this.pathTemplates.instanceConfigPathTemplate.match( + instanceConfigName, + ).instance_config; + } + + /** + * Return a fully-qualified instancePartition resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} instance_partition + * @returns {string} Resource name string. + */ + instancePartitionPath( + project: string, + instance: string, + instancePartition: string, + ) { + return this.pathTemplates.instancePartitionPathTemplate.render({ + project: project, + instance: instance, + instance_partition: instancePartition, + }); + } + + /** + * Parse the project from InstancePartition resource. + * + * @param {string} instancePartitionName + * A fully-qualified path representing InstancePartition resource. + * @returns {string} A string representing the project. + */ + matchProjectFromInstancePartitionName(instancePartitionName: string) { + return this.pathTemplates.instancePartitionPathTemplate.match( + instancePartitionName, + ).project; + } + + /** + * Parse the instance from InstancePartition resource. + * + * @param {string} instancePartitionName + * A fully-qualified path representing InstancePartition resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromInstancePartitionName(instancePartitionName: string) { + return this.pathTemplates.instancePartitionPathTemplate.match( + instancePartitionName, + ).instance; + } + + /** + * Parse the instance_partition from InstancePartition resource. + * + * @param {string} instancePartitionName + * A fully-qualified path representing InstancePartition resource. + * @returns {string} A string representing the instance_partition. + */ + matchInstancePartitionFromInstancePartitionName( + instancePartitionName: string, + ) { + return this.pathTemplates.instancePartitionPathTemplate.match( + instancePartitionName, + ).instance_partition; + } + + /** + * Return a fully-qualified session resource name string. + * + * @param {string} project + * @param {string} instance + * @param {string} database + * @param {string} session + * @returns {string} Resource name string. + */ + sessionPath( + project: string, + instance: string, + database: string, + session: string, + ) { + return this.pathTemplates.sessionPathTemplate.render({ + project: project, + instance: instance, + database: database, + session: session, + }); + } + + /** + * Parse the project from Session resource. + * + * @param {string} sessionName + * A fully-qualified path representing Session resource. + * @returns {string} A string representing the project. + */ + matchProjectFromSessionName(sessionName: string) { + return this.pathTemplates.sessionPathTemplate.match(sessionName).project; + } + + /** + * Parse the instance from Session resource. + * + * @param {string} sessionName + * A fully-qualified path representing Session resource. + * @returns {string} A string representing the instance. + */ + matchInstanceFromSessionName(sessionName: string) { + return this.pathTemplates.sessionPathTemplate.match(sessionName).instance; + } + + /** + * Parse the database from Session resource. + * + * @param {string} sessionName + * A fully-qualified path representing Session resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromSessionName(sessionName: string) { + return this.pathTemplates.sessionPathTemplate.match(sessionName).database; + } + + /** + * Parse the session from Session resource. + * + * @param {string} sessionName + * A fully-qualified path representing Session resource. + * @returns {string} A string representing the session. + */ + matchSessionFromSessionName(sessionName: string) { + return this.pathTemplates.sessionPathTemplate.match(sessionName).session; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.spannerExecutorProxyStub && !this._terminated) { + return this.spannerExecutorProxyStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/spanner/src/v1/spanner_executor_proxy_client_config.json b/handwritten/spanner/src/v1/spanner_executor_proxy_client_config.json new file mode 100644 index 00000000000..a26ec11660d --- /dev/null +++ b/handwritten/spanner/src/v1/spanner_executor_proxy_client_config.json @@ -0,0 +1,30 @@ +{ + "interfaces": { + "google.spanner.executor.v1.SpannerExecutorProxy": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "ExecuteActionAsync": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/spanner/src/v1/spanner_executor_proxy_proto_list.json b/handwritten/spanner/src/v1/spanner_executor_proxy_proto_list.json new file mode 100644 index 00000000000..eaca520c9a6 --- /dev/null +++ b/handwritten/spanner/src/v1/spanner_executor_proxy_proto_list.json @@ -0,0 +1,15 @@ +[ + "../../protos/google/spanner/admin/database/v1/backup.proto", + "../../protos/google/spanner/admin/database/v1/backup_schedule.proto", + "../../protos/google/spanner/admin/database/v1/common.proto", + "../../protos/google/spanner/admin/instance/v1/common.proto", + "../../protos/google/spanner/executor/v1/cloud_executor.proto", + "../../protos/google/spanner/v1/commit_response.proto", + "../../protos/google/spanner/v1/keys.proto", + "../../protos/google/spanner/v1/location.proto", + "../../protos/google/spanner/v1/mutation.proto", + "../../protos/google/spanner/v1/query_plan.proto", + "../../protos/google/spanner/v1/result_set.proto", + "../../protos/google/spanner/v1/transaction.proto", + "../../protos/google/spanner/v1/type.proto" +] diff --git a/handwritten/spanner/src/v1/spanner_proto_list.json b/handwritten/spanner/src/v1/spanner_proto_list.json new file mode 100644 index 00000000000..a27ba58caf7 --- /dev/null +++ b/handwritten/spanner/src/v1/spanner_proto_list.json @@ -0,0 +1,12 @@ +[ + "../../protos/google/spanner/v1/change_stream.proto", + "../../protos/google/spanner/v1/commit_response.proto", + "../../protos/google/spanner/v1/keys.proto", + "../../protos/google/spanner/v1/location.proto", + "../../protos/google/spanner/v1/mutation.proto", + "../../protos/google/spanner/v1/query_plan.proto", + "../../protos/google/spanner/v1/result_set.proto", + "../../protos/google/spanner/v1/spanner.proto", + "../../protos/google/spanner/v1/transaction.proto", + "../../protos/google/spanner/v1/type.proto" +] diff --git a/handwritten/spanner/system-test/fixtures/sample/package.json b/handwritten/spanner/system-test/fixtures/sample/package.json new file mode 100644 index 00000000000..590bb1b3861 --- /dev/null +++ b/handwritten/spanner/system-test/fixtures/sample/package.json @@ -0,0 +1,23 @@ +{ + "name": "spanner-sample-fixture", + "description": "An app we're using to test the library.", + "scripts": { + "check": "gts check", + "clean": "gts clean", + "compile": "tsc -p .", + "fix": "gts fix", + "prepare": "npm run compile", + "pretest": "npm run compile", + "posttest": "npm run check", + "start": "node build/src/index.js" + }, + "license": "Apache-2.0", + "dependencies": { + "@google-cloud/spanner": "file:./spanner.tgz" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "typescript": "^4.0.0", + "gts": "^3.0.0" + } +} diff --git a/handwritten/spanner/system-test/fixtures/sample/src/index.ts b/handwritten/spanner/system-test/fixtures/sample/src/index.ts new file mode 100644 index 00000000000..bde3afb3518 --- /dev/null +++ b/handwritten/spanner/system-test/fixtures/sample/src/index.ts @@ -0,0 +1,6 @@ +import {Spanner} from '@google-cloud/spanner'; +async function main() { + const spanner = new Spanner(); + console.log(spanner); +} +main(); diff --git a/handwritten/spanner/system-test/fixtures/sample/tsconfig.json b/handwritten/spanner/system-test/fixtures/sample/tsconfig.json new file mode 100644 index 00000000000..ba3a016c167 --- /dev/null +++ b/handwritten/spanner/system-test/fixtures/sample/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "./node_modules/gts/tsconfig-google.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "build", + "types": ["node"] + }, + "include": [ + "src/*.ts" + ] +} diff --git a/handwritten/spanner/system-test/install.ts b/handwritten/spanner/system-test/install.ts new file mode 100644 index 00000000000..85d72114493 --- /dev/null +++ b/handwritten/spanner/system-test/install.ts @@ -0,0 +1,58 @@ +// Copyright 2019 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 * as execa from 'execa'; +import * as mv from 'mv'; +import {ncp} from 'ncp'; +import * as tmp from 'tmp'; +import {promisify} from 'util'; +import {describe, it, after} from 'mocha'; + +const keep = false; +const mvp = promisify(mv) as {} as (...args: string[]) => Promise; +const ncpp = promisify(ncp); +const stagingDir = tmp.dirSync({keep, unsafeCleanup: true}); +const stagingPath = stagingDir.name; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const pkg = require('../../package.json'); + +describe('📦 pack and install', () => { + /** + * Create a staging directory with temp fixtures used to test on a fresh + * application. + */ + it('should be able to use the d.ts', async () => { + await execa('npm', ['pack', '--unsafe-perm']); + const tarball = `google-cloud-spanner-${pkg.version}.tgz`; + await mvp(tarball, `${stagingPath}/spanner.tgz`); + await ncpp('system-test/fixtures/sample', `${stagingPath}/`); + await execa('npm', ['install', '--unsafe-perm'], { + cwd: `${stagingPath}/`, + stdio: 'inherit', + }); + await execa('node', ['--throw-deprecation', 'build/src/index.js'], { + cwd: `${stagingPath}/`, + stdio: 'inherit', + }); + }); + + /** + * CLEAN UP - remove the staging directory when done. + */ + after('cleanup staging', async () => { + if (!keep) { + stagingDir.removeCallback(); + } + }); +}); diff --git a/handwritten/spanner/system-test/spanner.ts b/handwritten/spanner/system-test/spanner.ts new file mode 100644 index 00000000000..5ee4fcbd706 --- /dev/null +++ b/handwritten/spanner/system-test/spanner.ts @@ -0,0 +1,8932 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 {DateStruct, PreciseDate} from '@google-cloud/precise-date'; +import * as assert from 'assert'; +import {describe, it, before, after, beforeEach} from 'mocha'; +import pLimit = require('p-limit'); +import concat = require('concat-stream'); +import * as crypto from 'crypto'; +import * as extend from 'extend'; +import * as uuid from 'uuid'; +import { + Backup, + Database, + Spanner, + Instance, + InstanceConfig, + Session, + protos, + Float, + Interval, +} from '../src'; +import {Key} from '../src/table'; +import { + ReadRequest, + ExecuteSqlRequest, + TimestampBounds, + MutationGroup, + ReadResponse, + RunResponse, +} from '../src/transaction'; +import {Row} from '../src/partial-result-stream'; +import {GetDatabaseConfig} from '../src/database'; +import {grpc, CallOptions} from 'google-gax'; +import {google} from '../protos/protos'; +import CreateDatabaseMetadata = google.spanner.admin.database.v1.CreateDatabaseMetadata; +import CreateBackupMetadata = google.spanner.admin.database.v1.CreateBackupMetadata; +import CreateInstanceConfigMetadata = google.spanner.admin.instance.v1.CreateInstanceConfigMetadata; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +const singer = require('../test/data/singer'); +const music = singer.examples.spanner.music; +import {util} from 'protobufjs'; +import {MetricsTracerFactory} from '../src/metrics/metrics-tracer-factory'; +import Long = util.Long; +import { + CreateQueryPartitionsResponse, + CreateReadPartitionsResponse, +} from '../src/batch-transaction'; +import {isNull, isNumber} from '../src/helper'; +const fs = require('fs'); + +const SKIP_BACKUPS = process.env.SKIP_BACKUPS; +const KOKORO_JOB_NAME = process.env.KOKORO_JOB_NAME; +const SKIP_FGAC_TESTS = (process.env.SKIP_FGAC_TESTS || 'false').toLowerCase(); + +const IAM_MEMBER = process.env.IAM_MEMBER; +const PREFIX = 'gcloud-tests-'; +const RUN_ID = shortUUID(); +const LABEL = `node-spanner-systests-${RUN_ID}`; +const spanner = new Spanner({ + projectId: process.env.GCLOUD_PROJECT, + apiEndpoint: process.env.API_ENDPOINT, +}); +const GAX_OPTIONS: CallOptions = { + retry: { + retryCodes: [ + grpc.status.RESOURCE_EXHAUSTED, + grpc.status.DEADLINE_EXCEEDED, + grpc.status.UNAVAILABLE, + ], + backoffSettings: { + initialRetryDelayMillis: 1000, + retryDelayMultiplier: 1.3, + maxRetryDelayMillis: 32000, + initialRpcTimeoutMillis: 60000, + rpcTimeoutMultiplier: 1, + maxRpcTimeoutMillis: 60000, + totalTimeoutMillis: 600000, + }, + }, +}; + +const CURRENT_TIME = Math.round(Date.now() / 1000).toString(); + +describe('Spanner', () => { + const envInstanceName = process.env.SPANNERTEST_INSTANCE; + // True if a new instance has been created for this test run, false if reusing an existing instance + const generateInstanceForTest = !envInstanceName; + const IS_EMULATOR_ENABLED = + typeof process.env.SPANNER_EMULATOR_HOST !== 'undefined'; + const RESOURCES_TO_CLEAN: Array = []; + const INSTANCE_CONFIGS_TO_CLEAN: Array = []; + const instanceId = generateInstanceForTest + ? generateName('instance') + : envInstanceName; + const instanceConfigId = 'custom-' + generateName('instance-config'); + const gSQLdatabaseId1 = generateName('database'); + const gSQLdatabaseId2 = generateName('database'); + const pgdatabaseId = generateName('pg-db'); + const projectId = process.env.GCLOUD_PROJECT; + let instance; + let instanceConfig; + let DATABASE; + let PG_DATABASE; + let DATABASE_DROP_PROTECTION; + const TABLE_NAME = 'Singers'; + const INSTANCE_CONFIG = { + config: 'regional-us-central1', + nodes: 1, + labels: { + [LABEL]: 'true', + created: CURRENT_TIME, + }, + gaxOptions: GAX_OPTIONS, + }; + + async function createInstance(id) { + const instanceAdminClient = spanner.getInstanceAdminClient(); + const [instanceCreationOperation] = + await instanceAdminClient.createInstance({ + instanceId: id, + parent: instanceAdminClient.projectPath(projectId!), + instance: { + config: instanceAdminClient.instanceConfigPath( + projectId!, + INSTANCE_CONFIG.config, + ), + nodeCount: 1, + displayName: 'Test name for instance.', + labels: { + created: Math.round(Date.now() / 1000).toString(), // current time + }, + }, + }); + await instanceCreationOperation.promise(); + } + + async function creategSQLDatabase(gSQLdatabaseId, protoDescriptor) { + const databaseAdminClient = spanner.getDatabaseAdminClient(); + const createSingersTableStatement = protoDescriptor + ? [ + `CREATE PROTO BUNDLE ( + examples.spanner.music.SingerInfo, + examples.spanner.music.Genre, + )`, + ` + CREATE TABLE ${TABLE_NAME} ( + SingerId STRING(1024) NOT NULL, + Name STRING(1024), + ) PRIMARY KEY(SingerId)`, + ] + : [ + `CREATE TABLE ${TABLE_NAME} ( + SingerId STRING(1024) NOT NULL, + Name STRING(1024), + ) PRIMARY KEY(SingerId)`, + ]; + + const [googleSqlOperation] = await databaseAdminClient.createDatabase({ + createStatement: 'CREATE DATABASE `' + gSQLdatabaseId + '`', + extraStatements: createSingersTableStatement, + parent: databaseAdminClient.instancePath(projectId!, instanceId!), + protoDescriptors: protoDescriptor ? protoDescriptor : null, + }); + await googleSqlOperation.promise(); + } + + async function createPostgresDatabase(pgdatabaseId) { + const databaseAdminClient = spanner.getDatabaseAdminClient(); + const [pgOperation] = await databaseAdminClient.createDatabase({ + createStatement: 'CREATE DATABASE "' + pgdatabaseId + '"', + parent: databaseAdminClient.instancePath(projectId!, instanceId!), + databaseDialect: + protos.google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL, + }); + await pgOperation.promise(); + const statements = [ + `CREATE TABLE ${TABLE_NAME} ( + SingerId VARCHAR(1024) NOT NULL, + Name VARCHAR(1024), + PRIMARY KEY (SingerId) + );`, + ]; + const [postgreSqlOperationUpdateDDL] = + await databaseAdminClient.updateDatabaseDdl({ + database: databaseAdminClient.databasePath( + projectId!, + instanceId!, + pgdatabaseId, + ), + statements: statements, + }); + await postgreSqlOperationUpdateDDL.promise(); + } + + async function createBackup(database, backupId, expireTime) { + const databaseAdminClient = spanner.getDatabaseAdminClient(); + const [operation] = await databaseAdminClient.createBackup({ + parent: databaseAdminClient.instancePath(projectId!, instanceId), + backupId: backupId, + backup: { + database: database.formattedName_, + expireTime: Spanner.timestamp(expireTime).toStruct(), + name: databaseAdminClient.backupPath(projectId!, instanceId, backupId), + }, + }); + + if ('database' in operation.metadata!) { + assert.strictEqual( + operation.metadata!.name, + `${instance.formattedName_}/backups/${backupId}`, + ); + } + + if ('database' in operation.metadata!) { + assert.strictEqual(operation.metadata!.database, database.formattedName_); + } + + await operation.promise(); + } + + before(async () => { + await MetricsTracerFactory.resetInstance(); + await deleteOldTestInstances(); + if (generateInstanceForTest) { + await createInstance(instanceId!); + instance = spanner.instance(instanceId!); + RESOURCES_TO_CLEAN.push(instance); + } else { + instance = spanner.instance(envInstanceName); + console.log( + `Not creating temp instance, using + ${instance.formattedName_}...`, + ); + } + if (IS_EMULATOR_ENABLED) { + await creategSQLDatabase(gSQLdatabaseId1, null); + DATABASE = instance.database(gSQLdatabaseId1); + RESOURCES_TO_CLEAN.push(DATABASE); + } else { + // Reading proto descriptor file + const protoDescriptor = fs + .readFileSync('test/data/descriptors.pb') + .toString('base64'); + await creategSQLDatabase(gSQLdatabaseId1, protoDescriptor); + DATABASE = instance.database(gSQLdatabaseId1); + RESOURCES_TO_CLEAN.push(DATABASE); + } + await createPostgresDatabase(pgdatabaseId); + PG_DATABASE = instance.database(pgdatabaseId, {incStep: 1}); + RESOURCES_TO_CLEAN.push(PG_DATABASE); + + await creategSQLDatabase(gSQLdatabaseId2, null); + DATABASE_DROP_PROTECTION = instance.database(gSQLdatabaseId2, { + incStep: 1, + }); + RESOURCES_TO_CLEAN.push(DATABASE_DROP_PROTECTION); + }); + + after(async () => { + await MetricsTracerFactory.resetInstance(); + try { + if (generateInstanceForTest) { + // Sleep for 30 seconds before cleanup, just in case + await new Promise(resolve => setTimeout(resolve, 30000)); + // Deleting all backups before an instance can be deleted. + await Promise.all( + RESOURCES_TO_CLEAN.filter(resource => resource instanceof Backup).map( + backup => backup.delete(GAX_OPTIONS), + ), + ); + /** + * Deleting instances created during this test. + * All databasess will automatically be deleted with instance. + * @see {@link https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance} + */ + await Promise.all( + RESOURCES_TO_CLEAN.filter( + resource => resource instanceof Instance, + ).map(async instance => { + await deleteInstance(instance); + }), + ); + } else { + /** + * Limit the number of concurrent 'Administrative requests per minute' + * Not to exceed quota + * @see {@link https://cloud.google.com/spanner/quotas#administrative_limits} + */ + const limit = pLimit(5); + await Promise.all( + RESOURCES_TO_CLEAN.map(resource => + limit(() => resource.delete(GAX_OPTIONS)), + ), + ); + } + await MetricsTracerFactory.resetInstance(); + } catch (err) { + console.error('Cleanup failed:', err); + } + }); + + describe('Autogenerated Admin Client', async () => { + const instanceAdminClient = spanner.getInstanceAdminClient(); + const databaseAdminClient = spanner.getDatabaseAdminClient(); + + describe('Instances', () => { + it('should have created the instance', async () => { + assert(projectId); + try { + const [metadata] = await instanceAdminClient.getInstance({ + name: instanceAdminClient.instancePath(projectId, instanceId), + }); + assert.strictEqual( + metadata!.name, + instanceAdminClient.instancePath(projectId, instanceId), + ); + } catch (err) { + if (!err) { + assert.ifError(err); + } + } + }); + + it('should list the instances', async () => { + assert(projectId); + const [instances] = await instanceAdminClient.listInstances({ + parent: instanceAdminClient.projectPath(projectId), + }); + assert(instances!.length > 0); + }); + }); + + describe('Databases', () => { + async function createDatabase(database, dialect) { + assert(projectId); + const [metadata] = await databaseAdminClient.getDatabase({ + name: databaseAdminClient.databasePath( + projectId, + instanceId, + database.id, + ), + }); + assert.strictEqual( + metadata!.name, + databaseAdminClient.databasePath(projectId, instanceId, database.id), + ); + assert.strictEqual(metadata!.state, 'READY'); + assert.strictEqual(metadata!.databaseDialect, dialect); + } + + it('GOOGLE_STANDARD_SQL should have created the database', async () => { + await createDatabase(DATABASE, 'GOOGLE_STANDARD_SQL'); + }); + + it('POSTGRESQL should have created the database', async () => { + await createDatabase(PG_DATABASE, 'POSTGRESQL'); + }); + }); + }); + + describe('types', () => { + const TABLE_NAME = 'TypeCheck'; + let googleSqlTable; + let postgreSqlTable; + + before(async () => { + googleSqlTable = DATABASE.table(TABLE_NAME); + postgreSqlTable = PG_DATABASE.table(TABLE_NAME); + if (IS_EMULATOR_ENABLED) { + const [googleSqlOperationUpdateDDL] = await DATABASE.updateSchema( + ` + CREATE TABLE ${TABLE_NAME} + ( + Key STRING( MAX) NOT NULL, + BytesValue BYTES( MAX), + BoolValue BOOL, + DateValue DATE, + UUIDValue UUID, + Float32Value FLOAT32, + FloatValue FLOAT64, + IntValue INT64, + NumericValue NUMERIC, + StringValue STRING( MAX), + TimestampValue TIMESTAMP, + BytesArray ARRAY, + BoolArray ARRAY, + DateArray ARRAY< DATE >, + UUIDArray ARRAY, + Float32Array ARRAY, + FloatArray ARRAY, + IntArray ARRAY, + NumericArray ARRAY< NUMERIC >, + StringArray ARRAY, + TimestampArray ARRAY< TIMESTAMP >, + CommitTimestamp TIMESTAMP OPTIONS (allow_commit_timestamp= true) + ) PRIMARY KEY (Key) + `, + ); + await googleSqlOperationUpdateDDL.promise(); + // TODO: Add column "UUID"(type UUID) and "UUIDArray"(type UUID[]), while using uuid type.(currently UUID type is not supported for postgreSql dialect) + const [postgreSqlOperationUpdateDDL] = await PG_DATABASE.updateSchema( + ` + CREATE TABLE ${TABLE_NAME} + ( + "Key" VARCHAR NOT NULL PRIMARY KEY, + "BytesValue" BYTEA, + "BoolValue" BOOL, + "Float32Value" DOUBLE PRECISION, + "FloatValue" DOUBLE PRECISION, + "IntValue" BIGINT, + "NumericValue" NUMERIC, + "StringValue" VARCHAR, + "TimestampValue" TIMESTAMPTZ, + "DateValue" DATE, + "JsonbValue" JSONB, + "BytesArray" BYTEA[], + "BoolArray" BOOL[], + "Float32Array" DOUBLE PRECISION[], + "FloatArray" DOUBLE PRECISION[], + "IntArray" BIGINT[], + "NumericArray" NUMERIC[], + "StringArray" VARCHAR[], + "TimestampArray" TIMESTAMPTZ[], + "DateArray" DATE[], + "JsonbArray" JSONB[], + "CommitTimestamp" SPANNER.COMMIT_TIMESTAMP + ); + `, + ); + await postgreSqlOperationUpdateDDL.promise(); + } else { + const [googleSqlOperationUpdateDDL] = await DATABASE.updateSchema( + ` + CREATE TABLE ${TABLE_NAME} + ( + Key STRING( MAX) NOT NULL, + BytesValue BYTES( MAX), + BoolValue BOOL, + DateValue DATE, + UUIDValue UUID, + Float32Value FLOAT32, + FloatValue FLOAT64, + JsonValue JSON, + IntValue INT64, + NumericValue NUMERIC, + StringValue STRING( MAX), + TimestampValue TIMESTAMP, + ProtoMessageValue examples.spanner.music.SingerInfo, + ProtoEnumValue examples.spanner.music.Genre, + BytesArray ARRAY, + BoolArray ARRAY, + DateArray ARRAY< DATE >, + UUIDArray ARRAY, + Float32Array ARRAY, + FloatArray ARRAY, + JsonArray ARRAY, + IntArray ARRAY, + NumericArray ARRAY< NUMERIC >, + StringArray ARRAY, + TimestampArray ARRAY< TIMESTAMP >, + ProtoMessageArray ARRAY, + ProtoEnumArray ARRAY, + CommitTimestamp TIMESTAMP OPTIONS (allow_commit_timestamp= true) + ) PRIMARY KEY (Key) + `, + ); + await googleSqlOperationUpdateDDL.promise(); + // TODO: add columns using Interval Value and Interval Array Value. + // TODO: add column "UUIDValue" (type UUID) and "UUIDArray" (type UUID[]) while using uuid type. (currently uuid type is not supported in postgreSql) + const [postgreSqlOperationUpdateDDL] = await PG_DATABASE.updateSchema( + ` + CREATE TABLE ${TABLE_NAME} + ( + "Key" VARCHAR NOT NULL PRIMARY KEY, + "BytesValue" BYTEA, + "BoolValue" BOOL, + "Float32Value" DOUBLE PRECISION, + "FloatValue" DOUBLE PRECISION, + "IntValue" BIGINT, + "NumericValue" NUMERIC, + "StringValue" VARCHAR, + "TimestampValue" TIMESTAMPTZ, + "DateValue" DATE, + "JsonbValue" JSONB, + "BytesArray" BYTEA[], + "BoolArray" BOOL[], + "Float32Array" DOUBLE PRECISION[], + "FloatArray" DOUBLE PRECISION[], + "IntArray" BIGINT[], + "NumericArray" NUMERIC[], + "StringArray" VARCHAR[], + "TimestampArray" TIMESTAMPTZ[], + "DateArray" DATE[], + "JsonbArray" JSONB[], + "CommitTimestamp" SPANNER.COMMIT_TIMESTAMP + ); + `, + ); + await postgreSqlOperationUpdateDDL.promise(); + } + }); + + /** + * + * @param insertData data to insert + * @param dialect sql dialect + * @param callback + * @param columnsMetadataForRead Optional parameter use for read/query for + * deserializing Proto messages and enum + */ + async function insert(insertData, dialect, columnsMetadataForRead?: {}) { + const id = generateName('id'); + + insertData.Key = id; + + let table = googleSqlTable; + let query: ExecuteSqlRequest = { + sql: 'SELECT * FROM `' + table.name + '` WHERE Key = @id', + params: { + id, + }, + columnsMetadata: columnsMetadataForRead, + }; + let database = DATABASE; + if (dialect === Spanner.POSTGRESQL) { + table = postgreSqlTable; + query = { + sql: 'SELECT * FROM ' + table.name + ' WHERE "Key" = $1', + params: { + p1: id, + }, + }; + database = PG_DATABASE; + } + const [insertResp] = await table.insert(insertData); + const [rows, readResp] = await database.run(query); + return { + row: rows.shift(), + insertResp, + readResp, + }; + } + + const incorrectValueType = async table => { + try { + await table.insert({BoolValue: 'abc'}); + assert.fail('Expected an error to be thrown, but it was not.'); + } catch (err: any) { + KOKORO_JOB_NAME?.includes('system-test-regular-session') + ? assert.strictEqual(err.code, grpc.status.FAILED_PRECONDITION) + : assert.strictEqual(err.code, grpc.status.INVALID_ARGUMENT); + } + }; + + it('GOOGLE_STANDARD_SQL should throw an error for incorrect value types', async () => { + await incorrectValueType(googleSqlTable); + }); + + it('POSTGRESQL should throw an error for incorrect value types', async () => { + await incorrectValueType(postgreSqlTable); + }); + + describe('uneven rows', () => { + const differentlyOrderedRows = async dialect => { + const data = [ + { + Key: generateName('id'), + BoolValue: true, + IntValue: 10, + }, + { + Key: generateName('id'), + IntValue: 10, + BoolValue: true, + }, + ]; + + let table = googleSqlTable; + let database = DATABASE; + let query: ExecuteSqlRequest = { + sql: `SELECT * FROM \`${table.name}\` WHERE Key = @a OR KEY = @b`, + params: { + a: data[0].Key, + b: data[1].Key, + }, + }; + if (dialect === Spanner.POSTGRESQL) { + table = postgreSqlTable; + database = PG_DATABASE; + query = { + sql: `SELECT * FROM ${table.name} WHERE "Key" = $1 OR "Key" = $2`, + params: { + p1: data[0].Key, + p2: data[1].Key, + }, + }; + } + try { + await table.insert(data); + const [rows] = await database.run(query); + const row1 = rows![0].toJSON(); + assert.deepStrictEqual(row1.IntValue, data[0].IntValue); + assert.deepStrictEqual(row1.BoolValue, data[0].BoolValue); + + const row2 = rows![1].toJSON(); + assert.deepStrictEqual(row2.IntValue, data[1].IntValue); + assert.deepStrictEqual(row2.BoolValue, data[1].BoolValue); + } catch (err) { + assert.ifError(err); + } + }; + + it('GOOGLE_STANDARD_SQL should allow differently-ordered rows', async () => { + await differentlyOrderedRows(Spanner.GOOGLE_STANDARD_SQL); + }); + + it('POSTGRESQL should allow differently-ordered rows}', async () => { + await differentlyOrderedRows(Spanner.POSTGRESQL); + }); + }); + + describe('structs', () => { + it('GOOGLE_STANDARD_SQL should correctly decode structs', async () => { + const query = 'SELECT ARRAY(SELECT as struct 1, "hello")'; + const expected = [ + { + name: '', + value: [ + [ + { + name: '', + value: { + value: '1', + }, + }, + { + name: '', + value: 'hello', + }, + ], + ], + }, + ]; + try { + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual( + JSON.stringify(rows![0][0].value[0][0]), + JSON.stringify(expected[0].value[0][0]), + ); + assert.deepStrictEqual( + JSON.stringify(rows![0][0].value[0][1]), + JSON.stringify(expected[0].value[0][1]), + ); + } catch (err) { + assert.ifError(err); + } + }); + + it('GOOGLE_STANDARD_SQL should correctly decode structs', async () => { + const query = + 'SELECT 1 as id, ARRAY(select as struct 2 as id, "hello" as name)'; + + const expected = [ + { + name: 'id', + value: { + value: '1', + }, + }, + { + name: '', + value: [ + [ + { + name: 'id', + value: { + value: '2', + }, + }, + { + name: 'name', + value: 'hello', + }, + ], + ], + }, + ]; + + try { + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual( + JSON.stringify(rows![0][0]), + JSON.stringify(expected[0]), + ); + assert.deepStrictEqual( + JSON.stringify(rows![0][1].value[0][0]), + JSON.stringify(expected[1].value[0][0]), + ); + assert.deepStrictEqual( + JSON.stringify(rows![0][1].value[0][1]), + JSON.stringify(expected[1].value[0][1]), + ); + } catch (err) { + assert.ifError(err); + } + }); + }); + + describe('booleans', () => { + const booleanInsert = async (dialect, value) => { + const {row} = await insert({BoolValue: value}, dialect); + assert.strictEqual(row.toJSON().BoolValue, value); + }; + + it('GOOGLE_STANDARD_SQL should write boolean values', async () => { + await booleanInsert(Spanner.GOOGLE_STANDARD_SQL, true); + }); + + it('POSTGRESQL should write boolean values', async () => { + await booleanInsert(Spanner.POSTGRESQL, true); + }); + + it('GOOGLE_STANDARD_SQL should write null boolean values', async () => { + await booleanInsert(Spanner.GOOGLE_STANDARD_SQL, null); + }); + + it('POSTGRESQL should write null boolean values', async () => { + await booleanInsert(Spanner.POSTGRESQL, null); + }); + + it('GOOGLE_STANDARD_SQL should write empty boolean array values', async () => { + const {row} = await insert( + {BoolArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().BoolArray, []); + }); + + it('POSTGRESQL should write empty boolean array values', async () => { + const {row} = await insert({BoolArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().BoolArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null boolean array values', async () => { + const {row} = await insert( + {BoolArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().BoolArray, [null]); + }); + + it('POSTGRESQL should write null boolean array values', async () => { + const {row} = await insert({BoolArray: [null]}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().BoolArray, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write boolean array values', async () => { + const {row} = await insert( + {BoolArray: [true, false]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().BoolArray, [true, false]); + }); + + it('POSTGRESQL should write boolean array values', async () => { + const {row} = await insert( + {BoolArray: [true, false]}, + Spanner.POSTGRESQL, + ); + assert.deepStrictEqual(row.toJSON().BoolArray, [true, false]); + }); + }); + + describe('int64s', () => { + const int64Insert = async (dialect, value) => { + const {row} = await insert({IntValue: value}, dialect); + if (value) { + value = value.valueOf(); + } + assert.deepStrictEqual(row.toJSON().IntValue, value); + }; + + it('GOOGLE_STANDARD_SQL should write int64 values', async () => { + await int64Insert(Spanner.GOOGLE_STANDARD_SQL, Spanner.int(1234)); + }); + + it('POSTGRESQL should write int64 values', async () => { + await int64Insert(Spanner.POSTGRESQL, Spanner.int(1234)); + }); + + it('GOOGLE_STANDARD_SQL should write null int64 values', async () => { + await int64Insert(Spanner.GOOGLE_STANDARD_SQL, null); + }); + + it('POSTGRESQL should write null int64 values', async () => { + await int64Insert(Spanner.POSTGRESQL, null); + }); + + const int64OutOfBounds = async dialect => { + const value = '9223372036854775807'; + const {row} = await insert({IntValue: value}, dialect); + assert.throws(() => { + row.toJSON(); + }, new RegExp('Serializing column "IntValue" encountered an error')); + }; + + it('GOOGLE_STANDARD_SQL should throw for of bounds integers', async () => { + await int64OutOfBounds(Spanner.GOOGLE_STANDARD_SQL); + }); + + it('POSTGRESQL should throw for of bounds integers', async () => { + await int64OutOfBounds(Spanner.POSTGRESQL); + }); + + const int64WrapOutOfBounds = async dialect => { + const value = '9223372036854775807'; + const {row} = await insert({IntValue: value}, dialect); + const expected = Spanner.int(value); + const actual = row.toJSON({wrapNumbers: true}).IntValue; + assert.deepStrictEqual(actual, expected); + }; + + it('GOOGLE_STANDARD_SQL should optionally wrap out of bounds integers', async () => { + await int64WrapOutOfBounds(Spanner.GOOGLE_STANDARD_SQL); + }); + + it('POSTGRESQL should optionally wrap out of bounds integers', async () => { + await int64WrapOutOfBounds(Spanner.POSTGRESQL); + }); + + it('GOOGLE_STANDARD_SQL should write empty in64 array values', async () => { + const {row} = await insert({IntArray: []}, Spanner.GOOGLE_STANDARD_SQL); + assert.deepStrictEqual(row.toJSON().IntArray, []); + }); + + it('POSTGRESQL should write empty in64 array values', async () => { + const {row} = await insert({IntArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().IntArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null int64 array values', async () => { + const {row} = await insert( + {IntArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().IntArray, [null]); + }); + + it('POSTGRESQL should write null int64 array values', async () => { + const {row} = await insert({IntArray: [null]}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().IntArray, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write int64 array values', async () => { + const values = [1, 2, 3]; + const {row} = await insert( + {IntArray: values}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().IntArray, values); + }); + + it('POSTGRESQL should write int64 array values', async () => { + const values = [1, 2, 3]; + const {row} = await insert({IntArray: values}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().IntArray, values); + }); + }); + + describe('oids', () => { + it('POSTGRESQL should read non-null pgOid values', async () => { + const [rows] = await PG_DATABASE.run('SELECT 123::oid'); + let queriedValue = rows[0][0].value; + if (rows[0][0].value) { + queriedValue = rows[0][0].value.value; + } + assert.strictEqual(queriedValue, '123'); + }); + + it('POSTGRESQL should read null pgOid values', async () => { + const [rows] = await PG_DATABASE.run('SELECT null::oid'); + let queriedValue = rows[0][0].value; + if (rows[0][0].value) { + queriedValue = rows[0][0].value.value; + } + assert.strictEqual(queriedValue, null); + }); + }); + + describe('uuids', () => { + const uuidInsert = async (dialect, value) => { + const {row} = await insert({UUIDValue: value}, dialect); + + let expectedValue = value; + if (typeof value === 'object' && value !== null) { + expectedValue = value.value; + } + + assert.deepStrictEqual(row.toJSON().UUIDValue, expectedValue); + }; + + it('GOOGLE_STANDARD_SQL should write uuid values', async () => { + await uuidInsert(Spanner.GOOGLE_STANDARD_SQL, uuid.v4()); + }); + + it.skip('POSTGRESQL should write uuid values', async () => { + await uuidInsert(Spanner.POSTGRESQL, uuid.v4()); + }); + + it('GOOGLE_STANDARD_SQL should write empty uuid array values', async () => { + const {row} = await insert( + {UUIDArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().UUIDArray, []); + }); + + it.skip('POSTGRESQL should write empty uuid array values', async () => { + const {row} = await insert({UUIDArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().UUIDArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write uuid array values', async () => { + const values = [uuid.v4(), uuid.v4(), uuid.v4()]; + const {row} = await insert( + {UUIDArray: values}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().UUIDArray, values); + }); + + it.skip('POSTGRESQL should write uuid array values', async () => { + const values = [uuid.v4(), uuid.v4(), uuid.v4()]; + const {row} = await insert({UUIDArray: values}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().UUIDArray, values); + }); + }); + + describe('float32s', () => { + const float32Insert = async (dialect, value) => { + const {row} = await insert({Float32Value: value}, dialect); + if (typeof value === 'object' && value !== null) { + value = value.value; + } + if (Number.isNaN(row.toJSON().Float32Value)) { + assert.deepStrictEqual(row.toJSON().Float32Value, value); + } else if (row.toJSON().Float32Value === value) { + assert.deepStrictEqual(row.toJSON().Float32Value, value); + } else { + assert.ok(row.toJSON().Float32Value - value <= 0.00001); + } + }; + + it('GOOGLE_STANDARD_SQL should write float32 values', async () => { + await float32Insert(Spanner.GOOGLE_STANDARD_SQL, 8.2); + }); + + it('POSTGRESQL should write float32 values', async () => { + await float32Insert(Spanner.POSTGRESQL, 8.2); + }); + + it('GOOGLE_STANDARD_SQL should write null float32 values', async () => { + await float32Insert(Spanner.GOOGLE_STANDARD_SQL, null); + }); + + it('POSTGRESQL should write null float32 values', async () => { + await float32Insert(Spanner.POSTGRESQL, null); + }); + + it('GOOGLE_STANDARD_SQL should accept a Float object with an Int-like value', async () => { + await float32Insert(Spanner.GOOGLE_STANDARD_SQL, Spanner.float32(8)); + }); + + it('POSTGRESQL should accept a Float object with an Int-like value', async () => { + await float32Insert(Spanner.POSTGRESQL, Spanner.float32(8)); + }); + + it('GOOGLE_STANDARD_SQL should handle Infinity', async () => { + await float32Insert(Spanner.GOOGLE_STANDARD_SQL, Infinity); + }); + + it('POSTGRESQL should handle Infinity', async () => { + await float32Insert(Spanner.POSTGRESQL, Infinity); + }); + + it('GOOGLE_STANDARD_SQL should handle -Infinity', async () => { + await float32Insert(Spanner.GOOGLE_STANDARD_SQL, -Infinity); + }); + + it('POSTGRESQL should handle -Infinity', async () => { + await float32Insert(Spanner.POSTGRESQL, -Infinity); + }); + + it('GOOGLE_STANDARD_SQL should handle NaN', async () => { + await float32Insert(Spanner.GOOGLE_STANDARD_SQL, NaN); + }); + + it('POSTGRESQL should handle NaN', async () => { + await float32Insert(Spanner.POSTGRESQL, NaN); + }); + + it('GOOGLE_STANDARD_SQL should write empty float32 array values', async () => { + const {row} = await insert( + {Float32Array: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().Float32Array, []); + }); + + it('POSTGRESQL should write empty float32 array values', async () => { + const {row} = await insert({Float32Array: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().Float32Array, []); + }); + + it('GOOGLE_STANDARD_SQL should write null float32 array values', async () => { + const {row} = await insert( + {Float32Array: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().Float32Array, [null]); + }); + + it('POSTGRESQL should write null float32 array values', async () => { + const {row} = await insert({Float32Array: [null]}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().Float32Array, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write float32 array values', async () => { + const values = [1.2, 2.3, 3.4]; + const {row} = await insert( + {Float32Array: values}, + Spanner.GOOGLE_STANDARD_SQL, + ); + for (let i = 0; i < values.length; i++) { + assert.ok(row.toJSON().Float32Array[i] - values[i] <= 0.00001); + } + }); + + it('POSTGRESQL should write float32 array values', async () => { + const values = [1.2, 2.3, 3.4]; + const {row} = await insert({Float32Array: values}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().Float32Array, values); + }); + }); + + describe('float64s', () => { + const float64Insert = async (dialect, value) => { + const {row} = await insert({FloatValue: value}, dialect); + if (typeof value === 'object' && value !== null) { + value = value.value; + } + assert.deepStrictEqual(row.toJSON().FloatValue, value); + }; + + it('GOOGLE_STANDARD_SQL should write float64 values', async () => { + await float64Insert(Spanner.GOOGLE_STANDARD_SQL, 8.2); + }); + + it('POSTGRESQL should write float64 values', async () => { + await float64Insert(Spanner.POSTGRESQL, 8.2); + }); + + it('GOOGLE_STANDARD_SQL should write null float64 values', async () => { + await float64Insert(Spanner.GOOGLE_STANDARD_SQL, null); + }); + + it('POSTGRESQL should write null float64 values', async () => { + await float64Insert(Spanner.POSTGRESQL, null); + }); + + it('GOOGLE_STANDARD_SQL should accept a Float object with an Int-like value', async () => { + await float64Insert(Spanner.GOOGLE_STANDARD_SQL, Spanner.float(8)); + }); + + it('POSTGRESQL should accept a Float object with an Int-like value', async () => { + await float64Insert(Spanner.POSTGRESQL, Spanner.float(8)); + }); + + it('GOOGLE_STANDARD_SQL should handle Infinity', async () => { + await float64Insert(Spanner.GOOGLE_STANDARD_SQL, Infinity); + }); + + it('POSTGRESQL should handle Infinity', async () => { + await float64Insert(Spanner.POSTGRESQL, Infinity); + }); + + it('GOOGLE_STANDARD_SQL should handle -Infinity', async () => { + await float64Insert(Spanner.GOOGLE_STANDARD_SQL, -Infinity); + }); + + it('POSTGRESQL should handle -Infinity', async () => { + await float64Insert(Spanner.POSTGRESQL, -Infinity); + }); + + it('GOOGLE_STANDARD_SQL should handle NaN', async () => { + await float64Insert(Spanner.GOOGLE_STANDARD_SQL, NaN); + }); + + it('POSTGRESQL should handle NaN', async () => { + await float64Insert(Spanner.POSTGRESQL, NaN); + }); + + it('GOOGLE_STANDARD_SQL should write empty float64 array values', async () => { + const {row} = await insert( + {FloatArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().FloatArray, []); + }); + + it('POSTGRESQL should write empty float64 array values', async () => { + const {row} = await insert({FloatArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().FloatArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null float64 array values', async () => { + const {row} = await insert( + {FloatArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().FloatArray, [null]); + }); + + it('POSTGRESQL should write null float64 array values', async () => { + const {row} = await insert({FloatArray: [null]}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().FloatArray, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write float64 array values', async () => { + const values = [1.2, 2.3, 3.4]; + const {row} = await insert( + {FloatArray: values}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().FloatArray, values); + }); + + it('POSTGRESQL should write float64 array values', async () => { + const values = [1.2, 2.3, 3.4]; + const {row} = await insert({FloatArray: values}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().FloatArray, values); + }); + }); + + describe('numerics', () => { + const numericInsert = async (dialect, value) => { + const {row} = await insert({NumericValue: value}, dialect); + assert.deepStrictEqual(row.toJSON().NumericValue, value); + }; + + it('GOOGLE_STANDARD_SQL should write numeric values', async () => { + await numericInsert( + Spanner.GOOGLE_STANDARD_SQL, + Spanner.numeric('3.141592653'), + ); + }); + + it('POSTGRESQL should write numeric values', async () => { + await numericInsert( + Spanner.POSTGRESQL, + Spanner.pgNumeric('3.141592653'), + ); + }); + + it('GOOGLE_STANDARD_SQL should write null numeric values', async () => { + await numericInsert(Spanner.GOOGLE_STANDARD_SQL, null); + }); + + it('POSTGRESQL should write null numeric values', async () => { + await numericInsert(Spanner.POSTGRESQL, null); + }); + + it('POSTGRESQL should bind NaN', async () => { + await numericInsert(Spanner.POSTGRESQL, Spanner.pgNumeric('NaN')); + }); + + const numericInsertOutOfBounds = async (dialect, value) => { + try { + await insert({NumericValue: value}, dialect); + assert.fail('Expected an error to be thrown, but it was not.'); + } catch (err: any) { + KOKORO_JOB_NAME?.includes('system-test-regular-session') + ? assert.strictEqual(err.code, grpc.status.FAILED_PRECONDITION) + : assert.strictEqual(err.code, grpc.status.INVALID_ARGUMENT); + } + }; + + it('GOOGLE_STANDARD_SQL should throw for out of bounds values', async () => { + await numericInsertOutOfBounds( + Spanner.GOOGLE_STANDARD_SQL, + Spanner.numeric('3.1415926535'), + ); + }); + + it('POSTGRESQL should throw for out of bounds values', async () => { + await numericInsertOutOfBounds( + Spanner.POSTGRESQL, + Spanner.pgNumeric('1e131072'), + ); + }); + + it('GOOGLE_STANDARD_SQL should write empty numeric array values', async () => { + const {row} = await insert( + {NumericArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().NumericArray, []); + }); + + it('POSTGRESQL should write empty numeric array values', async () => { + const {row} = await insert({NumericArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().NumericArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null numeric array values', async () => { + const {row} = await insert( + {NumericArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().NumericArray, [null]); + }); + + it('POSTGRESQL should write null numeric array values', async () => { + try { + const {row} = await insert( + {NumericArray: [null]}, + Spanner.POSTGRESQL, + ); + assert.deepStrictEqual(row.toJSON().NumericArray, [null]); + } catch (err) { + assert.ifError(err); + } + }); + + it('GOOGLE_STANDARD_SQL should write numeric array values', async () => { + const values = [ + Spanner.numeric('-99999999999999999999999999999.999999999'), + Spanner.numeric('3.141592653'), + Spanner.numeric('99999999999999999999999999999.999999999'), + ]; + + const {row} = await insert( + {NumericArray: values}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().NumericArray, values); + }); + + it('POSTGRESQL should write numeric array values', async () => { + const values = [ + Spanner.pgNumeric('-99999999999999999999999999999.999999999'), + Spanner.pgNumeric('3.141592653'), + Spanner.pgNumeric('99999999999999999999999999999.999999999'), + ]; + + const {row} = await insert({NumericArray: values}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().NumericArray, values); + }); + }); + + describe('strings', () => { + const stringInsert = async (dialect, value) => { + const {row} = await insert({StringValue: value}, dialect); + assert.strictEqual(row.toJSON().StringValue, value); + }; + + it('GOOGLE_STANDARD_SQL should write string values', async () => { + await stringInsert(Spanner.GOOGLE_STANDARD_SQL, 'abc'); + }); + + it('POSTGRESQL should write string values', async () => { + await stringInsert(Spanner.POSTGRESQL, 'abc'); + }); + + it('GOOGLE_STANDARD_SQL should write null string values', async () => { + await stringInsert(Spanner.GOOGLE_STANDARD_SQL, null); + }); + + it('POSTGRESQL should write null string values', async () => { + await stringInsert(Spanner.POSTGRESQL, null); + }); + + it('GOOGLE_STANDARD_SQL should write empty string array values', async () => { + const {row} = await insert( + {StringArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().StringArray, []); + }); + + it('POSTGRESQL should write empty string array values', async () => { + const {row} = await insert({StringArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().StringArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null string array values', async () => { + const {row} = await insert( + {StringArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().StringArray, [null]); + }); + + it('POSTGRESQL should write null string array values', async () => { + const {row} = await insert({StringArray: [null]}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().StringArray, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write string array values', async () => { + const {row} = await insert( + {StringArray: ['abc', 'def']}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().StringArray, ['abc', 'def']); + }); + + it('POSTGRESQL should write string array values', async () => { + const {row} = await insert( + {StringArray: ['abc', 'def']}, + Spanner.POSTGRESQL, + ); + assert.deepStrictEqual(row.toJSON().StringArray, ['abc', 'def']); + }); + }); + + describe('bytes', () => { + const bytesInsert = async (dialect, value) => { + const {row} = await insert({BytesValue: value}, dialect); + assert.deepStrictEqual(row.toJSON().BytesValue, value); + }; + + it('GOOGLE_STANDARD_SQL should write bytes values', async () => { + await bytesInsert(Spanner.GOOGLE_STANDARD_SQL, Buffer.from('abc')); + }); + + it('POSTGRESQL should write bytes values', async () => { + await bytesInsert(Spanner.POSTGRESQL, Buffer.from('abc')); + }); + + it('GOOGLE_STANDARD_SQL should write null bytes values', async () => { + await bytesInsert(Spanner.GOOGLE_STANDARD_SQL, null); + }); + + it('POSTGRESQL should write null bytes values', async () => { + await bytesInsert(Spanner.POSTGRESQL, null); + }); + + it('GOOGLE_STANDARD_SQL should write empty bytes array values', async () => { + const {row} = await insert( + {BytesArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().BytesArray, []); + }); + + it('POSTGRESQL should write empty bytes array values', async () => { + const {row} = await insert({BytesArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().BytesArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null bytes array values', async () => { + const {row} = await insert( + {BytesArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().BytesArray, [null]); + }); + + it('POSTGRESQL should write null bytes array values', async () => { + const {row} = await insert({BytesArray: [null]}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().BytesArray, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write bytes array values', async () => { + const values = [Buffer.from('a'), Buffer.from('b')]; + const {row} = await insert( + {BytesArray: values}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().BytesArray, values); + }); + + it('POSTGRESQL should write bytes array values', async () => { + const values = [Buffer.from('a'), Buffer.from('b')]; + const {row} = await insert({BytesArray: values}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().BytesArray, values); + }); + }); + + describe('jsons', () => { + before(async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + }); + + it('GOOGLE_STANDARD_SQL should write json values', async () => { + const {row} = await insert( + {JsonValue: {key1: 'value1', key2: 'value2'}}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().JsonValue, { + key1: 'value1', + key2: 'value2', + }); + }); + + it('GOOGLE_STANDARD_SQL should write null json values', async () => { + const {row} = await insert( + {JsonValue: null}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.strictEqual(row.toJSON().JsonValue, null); + }); + + it('GOOGLE_STANDARD_SQL should write empty json array values', async () => { + const {row} = await insert( + {JsonArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().JsonArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null json array values', async () => { + const {row} = await insert( + {JsonArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().JsonArray, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write json array values', async () => { + const {row} = await insert( + {JsonArray: [{key1: 'value1'}, {key2: 'value2'}]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().JsonArray, [ + {key1: 'value1'}, + {key2: 'value2'}, + ]); + }); + }); + + describe('timestamps', () => { + const timestampInsert = async dialect => { + const date = Spanner.timestamp(); + const {row} = await insert({TimestampValue: date}, dialect); + const time = row.toJSON().TimestampValue.getTime(); + assert.strictEqual(time, date.getTime()); + }; + + it('GOOGLE_STANDARD_SQL should write timestamp values', async () => { + await timestampInsert(Spanner.GOOGLE_STANDARD_SQL); + }); + + it('POSTGRESQL should write timestamp values', async () => { + await timestampInsert(Spanner.POSTGRESQL); + }); + + const timestampInsertNull = async dialect => { + const {row} = await insert({TimestampValue: null}, dialect); + assert.strictEqual(row.toJSON().TimestampValue, null); + }; + + it('GOOGLE_STANDARD_SQL should write null timestamp values', async () => { + await timestampInsertNull(Spanner.GOOGLE_STANDARD_SQL); + }); + + it('POSTGRESQL should write null timestamp values', async () => { + await timestampInsertNull(Spanner.POSTGRESQL); + }); + + it('GOOGLE_STANDARD_SQL should write empty timestamp array values', async () => { + const {row} = await insert( + {TimestampArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().TimestampArray, []); + }); + + it('POSTGRESQL should write empty timestamp array values', async () => { + const {row} = await insert({TimestampArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().TimestampArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null timestamp array values', async () => { + const {row} = await insert( + {TimestampArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().TimestampArray, [null]); + }); + + it('POSTGRESQL should write null timestamp array values', async () => { + const {row} = await insert( + {TimestampArray: [null]}, + Spanner.POSTGRESQL, + ); + assert.deepStrictEqual(row.toJSON().TimestampArray, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write timestamp array values', async () => { + const values = [Spanner.timestamp(), Spanner.timestamp('3-3-1933')]; + const {row} = await insert( + {TimestampArray: values}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().TimestampArray, values); + }); + + it('POSTGRESQL should write timestamp array values', async () => { + const values = [Spanner.timestamp(), Spanner.timestamp('3-3-1933')]; + const {row} = await insert( + {TimestampArray: values}, + Spanner.POSTGRESQL, + ); + assert.deepStrictEqual(row.toJSON().TimestampArray, values); + }); + }); + + describe('dates', () => { + const dateInsert = async dialect => { + const {row} = await insert({DateValue: Spanner.date()}, dialect); + assert.deepStrictEqual( + Spanner.date(row.toJSON().DateValue), + Spanner.date(), + ); + }; + + it('GOOGLE_STANDARD_SQL should write date values', async () => { + await dateInsert(Spanner.GOOGLE_STANDARD_SQL); + }); + + it('POSTGRESQL should write date values', async () => { + await dateInsert(Spanner.POSTGRESQL); + }); + + const dateInsertNull = async dialect => { + const {row} = await insert({DateValue: null}, dialect); + assert.strictEqual(row.toJSON().DateValue, null); + }; + + it('GOOGLE_STANDARD_SQL should write null date values', async () => { + await dateInsertNull(Spanner.GOOGLE_STANDARD_SQL); + }); + + it('POSTGRESQL should write null date values', async () => { + await dateInsertNull(Spanner.POSTGRESQL); + }); + + it('GOOGLE_STANDARD_SQL should write empty date array values', async () => { + const {row} = await insert( + {DateArray: []}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().DateArray, []); + }); + + it('POSTGRESQL should write empty date array values', async () => { + const {row} = await insert({DateArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().DateArray, []); + }); + + it('GOOGLE_STANDARD_SQL should write null date array values', async () => { + const {row} = await insert( + {DateArray: [null]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().DateArray, [null]); + }); + + it('POSTGRESQL should write null date array values', async () => { + const {row} = await insert({DateArray: [null]}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().DateArray, [null]); + }); + + it('GOOGLE_STANDARD_SQL should write date array values', async () => { + const values = [Spanner.date(), Spanner.date('3-3-1933')]; + const {row} = await insert( + {DateArray: values}, + Spanner.GOOGLE_STANDARD_SQL, + ); + const {DateArray} = row.toJSON(); + assert.deepStrictEqual(DateArray, values); + }); + + it('POSTGRESQL should write date array values', async () => { + const values = [Spanner.date(), Spanner.date('3-3-1933')]; + const {row} = await insert({DateArray: values}, Spanner.POSTGRESQL); + const {DateArray} = row.toJSON(); + assert.deepStrictEqual(DateArray, values); + }); + }); + + describe('protoMessage', () => { + before(async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + }); + + const protoMessageParams = { + value: music.SingerInfo.create({ + singerId: new Long(1), + genre: music.Genre.POP, + birthDate: 'January', + nationality: 'Country1', + }), + messageFunction: music.SingerInfo, + fullName: 'examples.spanner.music.SingerInfo', + }; + + it('GOOGLE_STANDARD_SQL should write protoMessage values', async () => { + const value = Spanner.protoMessage(protoMessageParams); + const {row} = await insert( + {ProtoMessageValue: value}, + Spanner.GOOGLE_STANDARD_SQL, + {ProtoMessageValue: music.SingerInfo}, + ); + assert.deepStrictEqual( + row.toJSON().ProtoMessageValue, + music.SingerInfo.toObject(protoMessageParams.value), + ); + }); + + it('GOOGLE_STANDARD_SQL should write bytes in the protoMessage column', async () => { + const value = music.SingerInfo.encode( + protoMessageParams.value, + ).finish(); + const {row} = await insert( + {ProtoMessageValue: value}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual( + row.toJSON().ProtoMessageValue, + value.toString(), + ); + }); + + it('GOOGLE_STANDARD_SQL should write null in the protoMessage column', async () => { + const {row} = await insert( + {ProtoMessageValue: null}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.equal(row.toJSON().ProtoMessageValue, null); + }); + + it('GOOGLE_STANDARD_SQL should write protoMessageArray', async () => { + const value = Spanner.protoMessage(protoMessageParams); + const {row} = await insert( + {ProtoMessageArray: [value]}, + Spanner.GOOGLE_STANDARD_SQL, + {ProtoMessageArray: music.SingerInfo}, + ); + assert.deepStrictEqual(row.toJSON().ProtoMessageArray, [ + music.SingerInfo.toObject(protoMessageParams.value), + ]); + }); + + it('GOOGLE_STANDARD_SQL should write bytes array in the protoMessageArray column', async () => { + const value = music.SingerInfo.encode( + protoMessageParams.value, + ).finish(); + const {row} = await insert( + {ProtoMessageArray: [value]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().ProtoMessageArray, [ + value.toString(), + ]); + }); + + it('GOOGLE_STANDARD_SQL should write null in the protoMessageArray column', async () => { + const {row} = await insert( + {ProtoMessageArray: null}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.equal(row.toJSON().ProtoMessageArray, null); + }); + }); + + describe('protoEnum', () => { + before(async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + }); + + const enumParams = { + value: music.Genre.JAZZ, + enumObject: music.Genre, + fullName: 'examples.spanner.music.Genre', + }; + + it('GOOGLE_STANDARD_SQL should write protoEnum values', async () => { + const value = Spanner.protoEnum(enumParams); + const {row} = await insert( + {ProtoEnumValue: value}, + Spanner.GOOGLE_STANDARD_SQL, + {ProtoEnumValue: music.Genre}, + ); + assert.deepStrictEqual( + row.toJSON().ProtoEnumValue, + Object.getPrototypeOf(music.Genre)[enumParams.value], + ); + }); + + it('GOOGLE_STANDARD_SQL should write int in the protoEnum column', async () => { + const value = 2; + const {row} = await insert( + {ProtoEnumValue: value}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().ProtoEnumValue, value.toString()); + }); + + it('GOOGLE_STANDARD_SQL should write null in the protoEnum column', async () => { + const {row} = await insert( + {ProtoEnumValue: null}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.equal(row.toJSON().ProtoEnumValue, null); + }); + + it('GOOGLE_STANDARD_SQL should write protoEnumArray', async () => { + const value = Spanner.protoEnum(enumParams); + const {row} = await insert( + {ProtoEnumArray: [value]}, + Spanner.GOOGLE_STANDARD_SQL, + {ProtoEnumArray: music.Genre}, + ); + assert.deepStrictEqual(row.toJSON().ProtoEnumArray, [ + Object.getPrototypeOf(music.Genre)[enumParams.value], + ]); + }); + + it('GOOGLE_STANDARD_SQL should write int array in the protoEnumArray column', async () => { + const value = 3; + const {row} = await insert( + {ProtoEnumArray: [value]}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.deepStrictEqual(row.toJSON().ProtoEnumArray, [value.toString()]); + }); + + it('GOOGLE_STANDARD_SQL should write null in the protoEnumArray column', async () => { + const {row} = await insert( + {ProtoEnumArray: null}, + Spanner.GOOGLE_STANDARD_SQL, + ); + assert.equal(row.toJSON().ProtoEnumArray, null); + }); + }); + + describe('jsonb', () => { + before(async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + }); + + it('POSTGRESQL should write jsonb values', async () => { + const value = Spanner.pgJsonb({ + key1: 'value1', + key2: 'value2', + }); + const {row} = await insert({JsonbValue: value}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().JsonbValue, value); + }); + + it('POSTGRESQL should write null jsonb values', async () => { + const {row} = await insert({JsonbValue: null}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().JsonbValue, null); + }); + + it('POSTGRESQL should write empty json array values', async () => { + const {row} = await insert({JsonbArray: []}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().JsonbArray, []); + }); + + it('POSTGRESQL should write null json array values', async () => { + const {row} = await insert({JsonbArray: [null]}, Spanner.POSTGRESQL); + assert.deepStrictEqual(row.toJSON().JsonbArray, [null]); + }); + + it('POSTGRESQL should write json array values', async () => { + const {row} = await insert( + {JsonbArray: [{key1: 'value1'}, {key2: 'value2'}]}, + Spanner.POSTGRESQL, + ); + assert.deepStrictEqual(row.toJSON().JsonbArray, [ + Spanner.pgJsonb({key1: 'value1'}), + Spanner.pgJsonb({key2: 'value2'}), + ]); + }); + }); + + describe('commit timestamp', () => { + const commitTimestamp = async dialect => { + const data = {CommitTimestamp: Spanner.COMMIT_TIMESTAMP}; + + const {row, insertResp} = await insert(data, dialect); + const timestampFromCommit = Spanner.timestamp( + insertResp.commitTimestamp, + ); + const timestampFromRead = row.toJSON().CommitTimestamp; + + assert.deepStrictEqual(timestampFromCommit, timestampFromRead); + }; + + it('GOOGLE_STANDARD_SQL should accept the commit timestamp placeholder', async () => { + await commitTimestamp(Spanner.GOOGLE_STANDARD_SQL); + }); + + it('POSTGRESQL should accept the commit timestamp placeholder', async () => { + await commitTimestamp(Spanner.POSTGRESQL); + }); + }); + }); + + describe('Instances', () => { + it('should have created the instance', async () => { + const [metadata] = await instance.getMetadata(); + assert.strictEqual(metadata!.name, instance.formattedName_); + }); + + it('should respect the FieldMask', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const fieldNames = ['name', 'displayName']; + + const [metadata] = await instance.getMetadata({fieldNames}); + assert.deepStrictEqual(metadata['endpointUris'], []); + assert.deepStrictEqual(metadata['labels'], {}); + assert.strictEqual(metadata.name, instance.formattedName_); + assert.ok(!metadata['config']); + assert.ok(metadata['displayName']); + assert.strictEqual(metadata['nodeCount'], 0); + assert.strictEqual(metadata['state'], 'STATE_UNSPECIFIED'); + }); + + it('should auto create an instance', async () => { + const instance = spanner.instance(generateName('instance')); + + const config = extend( + { + autoCreate: true, + }, + INSTANCE_CONFIG, + ); + + await instance.get(config); + RESOURCES_TO_CLEAN.push(instance); + await instance.getMetadata(); + }); + + it('should list the instances', async () => { + const [instances] = await spanner.getInstances(); + assert(instances!.length > 0); + }); + + it('should list the instances in promise mode', async () => { + const [instances] = await spanner.getInstances(); + assert(instances.length > 0); + }); + + it('should list the instances in stream mode', done => { + spanner + .getInstancesStream() + .on('error', done) + .pipe( + concat(instances => { + assert(instances.length > 0); + done(); + }), + ); + }); + + it('should update the metadata', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + + const newData = { + displayName: 'new-display-name-' + shortUUID(), + }; + const [operation] = await instance.setMetadata(newData); + await operation.promise(); + const [metadata] = await instance.getMetadata(); + assert.strictEqual(metadata.displayName, newData.displayName); + }); + + it('should return true for instances that exist', async () => { + const [exists] = await instance.exists(); + assert.strictEqual(exists, true); + }); + + it('should return false for instances that do not exist', async () => { + const [exists] = await spanner.instance('bad-instance').exists(); + assert.strictEqual(exists, false); + }); + }); + + describe('instanceConfigs', () => { + before(async () => { + if (!IS_EMULATOR_ENABLED) { + // Create a user-managed instance config from a base instance config. + const instanceAdminClient = spanner.getInstanceAdminClient(); + const [baseInstanceConfig] = + await instanceAdminClient.getInstanceConfig({ + name: instanceAdminClient.instanceConfigPath( + projectId!, + INSTANCE_CONFIG.config, + ), + }); + const [instanceConfigCreationOperation] = + await instanceAdminClient.createInstanceConfig({ + instanceConfigId: instanceConfigId, + parent: instanceAdminClient.projectPath(projectId!), + instanceConfig: { + name: instanceAdminClient.instanceConfigPath( + projectId!, + instanceConfigId, + ), + baseConfig: instanceAdminClient.instanceConfigPath( + projectId!, + INSTANCE_CONFIG.config, + ), + displayName: instanceConfigId, + replicas: baseInstanceConfig.replicas!.concat( + baseInstanceConfig.optionalReplicas![0], + ), + }, + }); + await instanceConfigCreationOperation.promise(); + instanceConfig = spanner.instanceConfig(instanceConfigId); + INSTANCE_CONFIGS_TO_CLEAN.push(instanceConfig); + } + }); + + after(async () => { + /** + * Deleting instance configs created during this test. + * @see {@link https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstanceConfig} + */ + await Promise.all( + INSTANCE_CONFIGS_TO_CLEAN.map(instanceConfig => + instanceConfig.delete({gaxOpts: GAX_OPTIONS}), + ), + ); + }); + + it('should have created the instance config', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const [metadata] = await instanceConfig.get(); + assert.strictEqual(metadata!.name, instanceConfig.formattedName_); + }); + + it('should list the available instanceConfigs', async () => { + const [instanceConfigs] = await spanner.getInstanceConfigs(); + assert(instanceConfigs!.length > 0); + }); + + it('should list the instanceConfigs in promise mode', async () => { + const [instanceConfigs] = await spanner.getInstanceConfigs(); + assert(instanceConfigs.length > 0); + }); + + it('should list the instanceConfigs in stream mode', done => { + spanner + .getInstanceConfigsStream() + .on('error', done) + .pipe( + concat(instanceConfigs => { + assert(instanceConfigs.length > 0); + done(); + }), + ); + }); + + it("should get an instanceConfig's metadata using getInstanceConfig", async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const [instanceConfig] = await spanner.getInstanceConfig('nam6'); + assert(instanceConfig!.displayName); + }); + + it("should get an instanceConfig's metadata in promise mode using getInstanceConfig", async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const [instanceConfig] = await spanner.getInstanceConfig('nam6'); + assert(instanceConfig.displayName); + }); + + it("should get an instanceConfig's metadata using get", async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const [instanceConfig] = await spanner.instanceConfig('nam6').get(); + assert(instanceConfig.displayName); + }); + + it("should list an instanceConfig's operations without filter", async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + + const [operationsWithoutFilter] = + await spanner.getInstanceConfigOperations(); + const operationForCurrentInstanceConfig = operationsWithoutFilter!.find( + operation => + operation.name && + operation.name.includes(instanceConfig.formattedName_), + ); + assert.ok(operationForCurrentInstanceConfig); + assert.strictEqual( + operationForCurrentInstanceConfig!.metadata!.type_url, + 'type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata', + ); + }); + + it("should list an instanceConfig's operations with filter", async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + + const [operationsWithFilter] = await spanner.getInstanceConfigOperations({ + filter: `(metadata.@type:type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata) AND + (name:${instanceConfig.formattedName_})`, + }); + const operationForCurrentInstanceConfigWithFilter = + operationsWithFilter[0]; + assert.ok(operationForCurrentInstanceConfigWithFilter); + const operationForCurrentInstanceConfigWithFilterMetadata = + CreateInstanceConfigMetadata.decode( + operationForCurrentInstanceConfigWithFilter!.metadata! + .value! as Uint8Array, + ); + assert.strictEqual( + operationForCurrentInstanceConfigWithFilterMetadata.instanceConfig! + .name, + `${instanceConfig.formattedName_}`, + ); + }); + + it('should update the instance config metadata', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + + const newData = { + instanceConfig: { + displayName: 'new-display-name-' + shortUUID(), + }, + }; + const [operation] = await instanceConfig.setMetadata(newData); + await operation.promise(); + const [metadata] = await instanceConfig.get(); + assert.strictEqual( + metadata.displayName, + newData.instanceConfig.displayName, + ); + }); + + it('should return true for instance config that exist', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const doesExist = await instanceConfig.exists(); + assert.strictEqual(doesExist, true); + }); + + it('should return false for instance configs that do not exist', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const doesExist = await spanner + .instanceConfig('bad-instance-config') + .exists(); + assert.strictEqual(doesExist, false); + }); + }); + + describe('Databases', () => { + const TABLE_NAME = 'SingersTest'; + const autoCreateDatabase = async databaseId => { + const database = instance.database(generateName(databaseId)); + await database.get({autoCreate: true} as GetDatabaseConfig); + RESOURCES_TO_CLEAN.push(database); + await database.getMetadata(); + }; + + it('GOOGLE_STANDARD_SQL should auto create a database', async () => { + await autoCreateDatabase('database'); + }); + + it('POSTGRESQL should auto create a database', async () => { + await autoCreateDatabase('pg-db'); + }); + + const createDatabase = async (database, dialect) => { + const [metadata] = await database.getMetadata(); + assert.strictEqual(metadata!.name, database.formattedName_); + assert.strictEqual(metadata!.state, 'READY'); + assert.strictEqual(metadata!.databaseDialect, dialect); + }; + + it('GOOGLE_STANDARD_SQL should have created the database', async () => { + await createDatabase(DATABASE, 'GOOGLE_STANDARD_SQL'); + }); + + it('POSTGRESQL should have created the database', async () => { + await createDatabase(PG_DATABASE, 'POSTGRESQL'); + }); + + it('should list the databases from an instance', async () => { + const [databases] = await instance.getDatabases(); + assert(databases!.length > 0); + // check if enableDropProtection is populated for databases. + databases!.map(db => { + assert.notStrictEqual(db.metadata.enableDropProtection, null); + }); + }); + + it('should list the databases in promise mode', async () => { + const [databases] = await instance.getDatabases(); + assert(databases.length > 0); + }); + + it('should list the databases in stream mode', done => { + instance + .getDatabasesStream() + .on('error', done) + .pipe( + concat(databases => { + assert(databases.length > 0); + done(); + }), + ); + }); + + it('should return true for databases that exist', async () => { + const [exists] = await DATABASE.exists(); + assert.strictEqual(exists, true); + }); + + it('should return false for databases that do not exist', async () => { + const [exists] = await instance.database('bad-database').exists(); + assert.strictEqual(exists, false); + }); + + const createTable = async (database, dialect, createTableStatement) => { + const [operation] = await database.updateSchema([createTableStatement]); + await operation.promise(); + function replaceNewLinesAndSpacing(str, dialect) { + const schema = str.replace(/\n\s*/g, '').replace(/\s+/g, ' '); + if (dialect === Spanner.GOOGLE_STANDARD_SQL) { + return schema; + } else { + return schema.toLowerCase(); + } + } + const [statements] = await database.getSchema(); + assert.ok( + statements.some( + s => + replaceNewLinesAndSpacing(s, dialect) === + replaceNewLinesAndSpacing(createTableStatement, dialect), + ), + ); + }; + + it('GOOGLE_STANDARD_SQL should create a table', async () => { + const createTableStatement = ` + CREATE TABLE ${TABLE_NAME} ( + SingerId INT64 NOT NULL, + FirstName STRING(1024), + LastName STRING(1024), + SingerInfo BYTES(MAX), + ) PRIMARY KEY(SingerId)`; + + await createTable( + DATABASE, + Spanner.GOOGLE_STANDARD_SQL, + createTableStatement, + ); + }); + + it('POSTGRESQL should create a table', async () => { + const createTableStatement = ` + CREATE TABLE ${TABLE_NAME} ( + SingerId BIGINT NOT NULL, + FirstName CHARACTER VARYING, + LastName CHARACTER VARYING, + SingerInfo BYTEA, + PRIMARY KEY(SingerId) + )`; + + await createTable(PG_DATABASE, Spanner.POSTGRESQL, createTableStatement); + }); + + it('should list database operations on an instance', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + // Look up the database full name from the metadata to expand any {{projectId}} tokens. + const [databaseMetadata] = await DATABASE.getMetadata(); + const databaseFullName = databaseMetadata.name; + + // List operations and ensure operation for creation of test database exists. + const [databaseCreateOperations] = await instance.getDatabaseOperations({ + filter: `(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.CreateDatabaseMetadata) AND + (metadata.database:${DATABASE.formattedName_})`, + }); + + // Validate operation and its metadata. + assert.strictEqual(databaseCreateOperations.length, 1); + const databaseCreateOperation = databaseCreateOperations[0]; + assert.strictEqual( + databaseCreateOperation.metadata!.type_url, + 'type.googleapis.com/google.spanner.admin.database.v1.CreateDatabaseMetadata', + ); + const createMeta = CreateDatabaseMetadata.decode( + databaseCreateOperation.metadata!.value! as Uint8Array, + ); + assert.strictEqual(createMeta.database, databaseFullName); + }); + + const listDatabaseOperation = async function (database) { + // Look up the database full name from the metadata to expand any {{projectId}} tokens. + const [databaseMetadata] = await database.getMetadata(); + const databaseFullName = databaseMetadata.name; + + // List operations. + const [databaseOperations] = await database.getOperations(); + + // Validate operation has at least the create operation for the database. + assert.ok(databaseOperations.length > 0); + const databaseCreateOperation = databaseOperations.find( + op => + op.metadata!.type_url === + 'type.googleapis.com/google.spanner.admin.database.v1.CreateDatabaseMetadata', + ); + const createMeta = CreateDatabaseMetadata.decode( + databaseCreateOperation!.metadata!.value! as Uint8Array, + ); + assert.strictEqual(createMeta.database, databaseFullName); + }; + + it('GOOGLE_STANDARD_SQL should list database operations on a database', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await listDatabaseOperation(DATABASE); + }); + + it('POSTGRESQL should list database operations on a database', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await listDatabaseOperation(PG_DATABASE); + }); + + it('enable_drop_protection should be disabled by default', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const [databaseMetadata] = await DATABASE_DROP_PROTECTION.getMetadata(); + assert.strictEqual(databaseMetadata!.enableDropProtection, false); + }); + + it('enable_drop_protection on database', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const [operation1] = await DATABASE_DROP_PROTECTION.setMetadata({ + enableDropProtection: true, + }); + await operation1.promise(); + + try { + await DATABASE_DROP_PROTECTION.delete(); + assert.ok(false); + } catch (err) { + assert.ok(true); + } + + const [operation2] = await DATABASE_DROP_PROTECTION.setMetadata({ + enableDropProtection: false, + }); + await operation2.promise(); + }); + + describe('FineGrainedAccessControl', () => { + before(function () { + if (SKIP_FGAC_TESTS === 'true') { + this.skip(); + } + }); + const createUserDefinedDatabaseRole = async (database, query) => { + const [operation] = await database.updateSchema([query]); + await operation.promise(); + const [statements] = await database.getSchema(); + assert.ok(statements.includes(query)); + }; + + it('GOOGLE_STANDARD_SQL should create a user defined role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await createUserDefinedDatabaseRole(DATABASE, 'CREATE ROLE parent'); + await new Promise(resolve => setTimeout(resolve, 60000)); + }); + + it('POSTGRESQL should create a user defined role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await createUserDefinedDatabaseRole(PG_DATABASE, 'CREATE ROLE parent'); + await new Promise(resolve => setTimeout(resolve, 60000)); + }); + + const grantAccessToRole = async ( + database, + createRoleQuery, + grantAccessQuery, + ) => { + const [operation] = await database.updateSchema([ + createRoleQuery, + grantAccessQuery, + ]); + await operation.promise(); + const [statements] = await database.getSchema(); + assert.ok(statements.includes(createRoleQuery)); + assert.ok(statements.includes(grantAccessQuery)); + }; + + it('GOOGLE_STANDARD_SQL should grant access to a user defined role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await grantAccessToRole( + DATABASE, + 'CREATE ROLE child', + 'GRANT SELECT ON TABLE Singers TO ROLE child', + ); + await new Promise(resolve => setTimeout(resolve, 60000)); + }); + + it('POSTGRESQL should grant access to a user defined role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await grantAccessToRole( + PG_DATABASE, + 'CREATE ROLE child', + 'GRANT SELECT ON TABLE singers TO child', + ); + await new Promise(resolve => setTimeout(resolve, 60000)); + }); + + const userDefinedDatabaseRoleRevoked = async ( + database, + createRoleQuery, + grantPermissionQuery, + revokePermissionQuery, + ) => { + const [grantOperation] = await database.updateSchema([ + createRoleQuery, + grantPermissionQuery, + ]); + await grantOperation.promise(); + const [statementsAfterGrant] = await database.getSchema(); + assert.ok(statementsAfterGrant.includes(createRoleQuery)); + assert.ok(statementsAfterGrant.includes(grantPermissionQuery)); + const [revokeOperation] = await database.updateSchema([ + revokePermissionQuery, + ]); + await revokeOperation.promise(); + const [statementsAfterRevoke] = await database.getSchema(); + assert.ok(!statementsAfterRevoke.includes(grantPermissionQuery)); + }; + + it('GOOGLE_STANDARD_SQL should revoke permissions of a user defined role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await userDefinedDatabaseRoleRevoked( + DATABASE, + 'CREATE ROLE orphan', + 'GRANT SELECT ON TABLE Singers TO ROLE orphan', + 'REVOKE SELECT ON TABLE Singers FROM ROLE orphan', + ); + await new Promise(resolve => setTimeout(resolve, 60000)); + }); + + it('POSTGRESQL should revoke permissions of a user defined role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await userDefinedDatabaseRoleRevoked( + PG_DATABASE, + 'CREATE ROLE orphan', + 'GRANT SELECT ON TABLE singers TO orphan', + 'REVOKE SELECT ON TABLE singers FROM orphan', + ); + await new Promise(resolve => setTimeout(resolve, 60000)); + }); + + const userDefinedDatabaseRoleDropped = async ( + database, + createRoleQuery, + dropRoleQuery, + ) => { + const [createOperation] = await database.updateSchema([ + createRoleQuery, + ]); + await createOperation.promise(); + const [statementsAfterCreate] = await database.getSchema(); + assert.ok(statementsAfterCreate.includes(createRoleQuery)); + const [dropOperation] = await database.updateSchema([dropRoleQuery]); + await dropOperation.promise(); + const [statementsAfterDrop] = await database.getSchema(); + assert.ok(!statementsAfterDrop.includes(createRoleQuery)); + }; + + it('GOOGLE_STANDARD_SQL should drop the user defined role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await userDefinedDatabaseRoleDropped( + DATABASE, + 'CREATE ROLE new_parent', + 'DROP ROLE new_parent', + ); + await new Promise(resolve => setTimeout(resolve, 60000)); + }); + + it('POSTGRESQL should drop the user defined role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await userDefinedDatabaseRoleDropped( + PG_DATABASE, + 'CREATE ROLE new_parent', + 'DROP ROLE new_parent', + ); + await new Promise(resolve => setTimeout(resolve, 60000)); + }); + + const grantAccessSuccess = async (database, grantPermissionQuery) => { + const id = 7; + const [operation] = await database.updateSchema([ + 'CREATE ROLE read_access', + grantPermissionQuery, + ]); + await operation.promise(); + const table = database.table('Singers'); + await table.insert({ + SingerId: id, + }); + const dbReadRole = instance.database(database.formattedName_, { + databaseRole: 'read_access', + }); + const query = { + sql: 'SELECT SingerId, Name FROM Singers', + }; + const [rows] = await dbReadRole.run(query); + assert.ok(rows.length > 0); + await table.deleteRows([id]); + }; + + it('GOOGLE_STANDARD_SQL should run query with access granted', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await grantAccessSuccess( + DATABASE, + 'GRANT SELECT ON TABLE Singers TO ROLE read_access', + ); + }); + + it('POSTGRESQL should run query with access granted', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await grantAccessSuccess( + PG_DATABASE, + 'GRANT SELECT ON TABLE singers TO read_access', + ); + }); + + const grantAccessFailure = async (database, grantPermissionQuery) => { + const id = 8; + const [operation] = await database.updateSchema([ + 'CREATE ROLE write_access', + grantPermissionQuery, + ]); + await operation.promise(); + const table = database.table('Singers'); + await table.insert({ + SingerId: id, + }); + const dbWriteRole = instance.database(database.formattedName_, { + databaseRole: 'write_access', + }); + + const query = { + sql: 'SELECT SingerId, Name FROM Singers', + }; + await assert.rejects(async () => { + await dbWriteRole.run(query); + }); + await table.deleteRows([id]); + }; + + it('GOOGLE_STANDARD_SQL should fail run query due to no access granted', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await grantAccessFailure( + DATABASE, + 'GRANT INSERT ON TABLE Singers TO ROLE write_access', + ); + }); + + it('POSTGRESQL should fail run query due to no access granted', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await grantAccessFailure( + PG_DATABASE, + 'GRANT INSERT ON TABLE singers TO write_access', + ); + }); + + const listDatabaseRoles = async database => { + const [updateRole] = await database.updateSchema([ + 'CREATE ROLE new_parent', + ]); + await updateRole.promise(); + + const [databaseRoles] = await database.getDatabaseRoles(); + assert.ok(databaseRoles.length > 0); + assert.ok( + databaseRoles.find( + role => + role.name === + database.formattedName_ + '/databaseRoles/new_parent', + ), + ); + }; + + it('GOOGLE_STANDARD_SQL should list database roles', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await listDatabaseRoles(DATABASE); + }); + + it('POSTGRESQL should list database roles', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await listDatabaseRoles(PG_DATABASE); + }); + + const getIamPolicy = async database => { + const [policy] = await database.getIamPolicy(); + assert.strictEqual(policy!.version, 0); + assert.deepStrictEqual(policy!.bindings, []); + }; + + it('GOOGLE_STANDARD_SQL should get IAM Policy', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await getIamPolicy(DATABASE); + }); + + it('POSTGRESQL should should get IAM Policy', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await getIamPolicy(PG_DATABASE); + }); + + const setIamPolicy = async database => { + const newBinding = { + role: 'roles/spanner.fineGrainedAccessUser', + members: [`user:${IAM_MEMBER}`], + condition: { + title: 'new condition', + expression: 'resource.name.endsWith("/databaseRoles/parent")', + }, + }; + const policy = { + bindings: [newBinding], + version: 3, + }; + await database.setIamPolicy({policy: policy}, (err, policy) => { + assert.ifError(err); + assert.strictEqual(policy.version, 3); + assert.deepStrictEqual(policy.bindings, newBinding); + }); + }; + + it('GOOGLE_STANDARD_SQL should set IAM Policy', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await setIamPolicy(DATABASE); + }); + + it('POSTGRESQL should should set IAM Policy', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await setIamPolicy(PG_DATABASE); + }); + }); + + describe('ForeignKeyDeleteCascadeAction', () => { + before(async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + }); + + const fkadc_database_id = generateName('fkadc'); + const fkadc_database_pg_id = generateName('fkadc-pg'); + + const fkadc_schema = [ + `CREATE TABLE Customers ( + CustomerId INT64, + CustomerName STRING(62) NOT NULL + ) PRIMARY KEY (CustomerId)`, + `CREATE TABLE ShoppingCarts ( + CartId INT64 NOT NULL, + CustomerId INT64 NOT NULL, + CustomerName STRING(62) NOT NULL, + CONSTRAINT FKShoppingCartsCustomerId FOREIGN KEY (CustomerId) + REFERENCES Customers (CustomerId) ON DELETE CASCADE, + ) PRIMARY KEY (CartId)`, + ]; + const fkadc_pg_schema = [ + `CREATE TABLE Customers ( + CustomerId BIGINT, + CustomerName VARCHAR(62) NOT NULL, + PRIMARY KEY (CustomerId) + ) `, + `CREATE TABLE ShoppingCarts ( + CartId BIGINT, + CustomerId BIGINT NOT NULL, + CustomerName VARCHAR(62) NOT NULL, + CONSTRAINT "FKShoppingCartsCustomerId" FOREIGN KEY (CustomerId) + REFERENCES Customers (CustomerId) ON DELETE CASCADE, + PRIMARY KEY (CartId) + )`, + ]; + + const createDatabaseWithFKADC = async ( + dialect, + database_id, + database_schema, + ) => { + const [database, operation] = await instance.createDatabase( + database_id, + {databaseDialect: dialect}, + ); + await operation.promise(); + + const [operationUpdateDDL] = + await database.updateSchema(database_schema); + await operationUpdateDDL.promise(); + + const [schema] = await database.getSchema(); + assert.strictEqual( + schema.filter(x => x.includes('FKShoppingCartsCustomerId')).length, + 1, + ); + }; + + it('GOOGLE_STANDARD_SQL should create a database with foreign key delete cascade action', async () => { + await createDatabaseWithFKADC( + Spanner.GOOGLE_STANDARD_SQL, + fkadc_database_id, + fkadc_schema, + ); + }); + + it('POSTGRESQL should create a database with foreign key delete cascade action', async () => { + await createDatabaseWithFKADC( + Spanner.POSTGRESQL, + fkadc_database_pg_id, + fkadc_pg_schema, + ); + }); + + const alterDatabaseWithFKADC = async (dialect, database) => { + const constraint_name = + dialect === Spanner.POSTGRESQL + ? '"FKShoppingCartsCustomerName"' + : 'FKShoppingCartsCustomerName'; + + const ddl_statements_add_constraints = [ + `ALTER TABLE ShoppingCarts ADD CONSTRAINT ${constraint_name} FOREIGN KEY (CustomerName) REFERENCES Customers(CustomerName) ON DELETE CASCADE`, + ]; + const [operationAddConstraint] = await database.updateSchema( + ddl_statements_add_constraints, + ); + await operationAddConstraint.promise(); + const [schema] = await database.getSchema(); + assert.strictEqual( + schema.filter(x => x.includes('FKShoppingCartsCustomerName')).length, + 1, + ); + + const ddl_statements_drop_constraints = [ + 'ALTER TABLE ShoppingCarts DROP CONSTRAINT FKShoppingCartsCustomerName', + ]; + const [operationDropConstraint] = await database.updateSchema( + ddl_statements_drop_constraints, + ); + await operationDropConstraint.promise(); + const [schema1] = await database.getSchema(); + assert.strictEqual( + schema1.filter(x => x.includes('FKShoppingCartsCustomerName')).length, + 0, + ); + }; + + it('GOOGLE_STANDARD_SQL should alter a database with foreign key delete cascade action', async () => { + const fkadc_database = instance.database(fkadc_database_id); + await alterDatabaseWithFKADC( + Spanner.GOOGLE_STANDARD_SQL, + fkadc_database, + ); + }); + + it('POSTGRESQL should alter a database with foreign key delete cascade action', async () => { + const fkadc_database_pg = instance.database(fkadc_database_pg_id); + await alterDatabaseWithFKADC(Spanner.POSTGRESQL, fkadc_database_pg); + }); + + const insertAndDeleteRowWithFKADC = async database => { + const customersTable = database.table('Customers'); + await customersTable.insert({ + CustomerId: 1, + CustomerName: 'Marc', + }); + + const cartsTable = database.table('ShoppingCarts'); + await cartsTable.insert({ + CartId: 1, + CustomerId: 1, + CustomerName: 'Marc', + }); + + const [rows] = await cartsTable.read({ + columns: ['CartId', 'CustomerId'], + }); + assert.strictEqual(rows.length, 1); + + await customersTable.deleteRows([1]); + const [rows1] = await cartsTable.read({ + columns: ['CartId', 'CustomerId'], + }); + assert.strictEqual(rows1.length, 0); + }; + + it('GOOGLE_STANDARD_SQL should insert a row and then delete with all references', async () => { + const fkadc_database = instance.database(fkadc_database_id); + await insertAndDeleteRowWithFKADC(fkadc_database); + }); + + it('POSTGRESQL should insert a row and then delete with all references', async () => { + const fkadc_database_pg = instance.database(fkadc_database_pg_id); + await insertAndDeleteRowWithFKADC(fkadc_database_pg); + }); + + const insertRowErrorWithFKADC = async database => { + const cartsTable = database.table('ShoppingCarts'); + await cartsTable.insert({ + CartId: 2, + CustomerId: 2, + CustomerName: 'Jack', + }); + }; + + it('GOOGLE_STANDARD_SQL should throw error when insert a row without reference', async () => { + try { + const fkadc_database = instance.database(fkadc_database_id); + await insertRowErrorWithFKADC(fkadc_database); + } catch (err) { + assert.match( + (err as grpc.ServiceError).message, + /Foreign key constraint `FKShoppingCartsCustomerId` is violated on table `ShoppingCarts`\./, + ); + } + }); + + it('POSTGRESQL should throw error when insert a row without reference', async () => { + try { + const fkadc_database_pg = instance.database(fkadc_database_pg_id); + await insertRowErrorWithFKADC(fkadc_database_pg); + } catch (err) { + assert.match( + (err as grpc.ServiceError).message, + /Foreign key constraint `FKShoppingCartsCustomerId` is violated on table `shoppingcarts`\./, + ); + } + }); + + const insertAndDeleteInSameTransactionErrorWithFKADC = async database => { + await database.runTransactionAsync(async transaction => { + transaction!.insert('Customers', { + CustomerId: 2, + CustomerName: 'John', + }); + transaction!.deleteRows('Customers', [2]); + try { + await transaction!.commit(); + } catch (err) { + assert.match( + (err as grpc.ServiceError).message.toLowerCase(), + /9 failed_precondition: cannot write a value for the referenced column `customers.customerid` and delete it in the same transaction\./, + ); + } + }); + }; + + it('GOOGLE_STANDARD_SQL should throw error when insert and delete a referenced key', async () => { + const fkadc_database = instance.database(fkadc_database_id); + await insertAndDeleteInSameTransactionErrorWithFKADC(fkadc_database); + }); + + it('POSTGRESQL should throw error when insert and delete a referenced key', async () => { + const fkadc_database_pg = instance.database(fkadc_database_pg_id); + await insertAndDeleteInSameTransactionErrorWithFKADC(fkadc_database_pg); + }); + + const insertReferencingKeyAndDeleteReferencedKeyErrorWithFKADC = + async database => { + const customersTable = database.table('Customers'); + const cartsTable = database.table('ShoppingCarts'); + await customersTable.insert([ + { + CustomerId: 2, + CustomerName: 'Marc', + }, + { + CustomerId: 3, + CustomerName: 'John', + }, + ]); + await cartsTable.insert({ + CartId: 2, + CustomerId: 2, + CustomerName: 'Marc', + }); + + await database.runTransactionAsync(async transaction => { + transaction!.update('ShoppingCarts', { + CartId: 2, + CustomerId: 3, + CustomerName: 'John', + }); + transaction!.deleteRows('Customers', [2]); + try { + await transaction!.commit(); + } catch (err) { + assert.match( + (err as grpc.ServiceError).message.toLowerCase(), + /9 failed_precondition: cannot modify a row in the table `shoppingcarts` because a referential action is deleting it in the same transaction\./, + ); + } + }); + }; + + it('GOOGLE_STANDARD_SQL should throw error when insert a referencing key and delete a referenced key', async () => { + const fkadc_database = instance.database(fkadc_database_id); + await insertReferencingKeyAndDeleteReferencedKeyErrorWithFKADC( + fkadc_database, + ); + }); + + it('POSTGRESQL should throw error when insert a referencing key and delete a referenced key', async () => { + const fkadc_database_pg = instance.database(fkadc_database_pg_id); + await insertReferencingKeyAndDeleteReferencedKeyErrorWithFKADC( + fkadc_database_pg, + ); + }); + + const deleteRuleOnInformationSchemaReferentialConstraints = + async database => { + const [transaction] = await database.getSnapshot(); + const [rows] = await transaction!.run( + "SELECT DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FKShoppingCartsCustomerId'", + ); + assert.strictEqual(rows[0][0].value, 'CASCADE'); + transaction!.end(); + }; + + it('GOOGLE_STANDARD_SQL should test information schema referential constraints', async () => { + const fkadc_database = instance.database(fkadc_database_id); + await deleteRuleOnInformationSchemaReferentialConstraints( + fkadc_database, + ); + }); + + it('POSTGRESQL should test information schema referential constraints', async () => { + const fkadc_database_pg = instance.database(fkadc_database_pg_id); + await deleteRuleOnInformationSchemaReferentialConstraints( + fkadc_database_pg, + ); + }); + }); + }); + + describe('Backups', () => { + const SKIP_POSTGRESQL_BACKUP_TESTS = true; + + let googleSqlDatabase1: Database; + let googleSqlRestoreDatabase: Database; + let postgreSqlRestoreDatabase: Database; + let postgreSqlDatabase1: Database; + let googleSqlBackup1: Backup; + let postgreSqlBackup1: Backup; + const googleSqlBackup1Name = generateName('backup'); + const postgreSqlBackup1Name = generateName('pg-backup'); + const backupExpiryDate = futureDateByHours(12); + const backupExpiryPreciseDate = Spanner.timestamp(backupExpiryDate); + + before(async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + if (SKIP_BACKUPS === 'true' || KOKORO_JOB_NAME?.includes('presubmit')) { + this.skip(); + } + googleSqlDatabase1 = DATABASE; + postgreSqlDatabase1 = PG_DATABASE; + + await googleSqlDatabase1.table(TABLE_NAME).insert({ + SingerId: generateName('id'), + Name: generateName('name'), + }); + + googleSqlBackup1 = instance.backup(googleSqlBackup1Name); + + if (!SKIP_POSTGRESQL_BACKUP_TESTS) { + await postgreSqlDatabase1.table(TABLE_NAME).insert({ + SingerId: generateName('id'), + Name: generateName('name'), + }); + postgreSqlBackup1 = instance.backup(postgreSqlBackup1Name); + } + }); + + function futureDateByHours(futureHours: number): number { + return Date.now() + 1000 * 60 * 60 * futureHours; + } + + const completedBackup = async (backup1, backup1Name, database1) => { + // Validate backup has completed. + const [backupInfo] = await backup1.getMetadata(); + assert.strictEqual(backupInfo.state, 'READY'); + assert.strictEqual( + backupInfo.name, + `${instance.formattedName_}/backups/${backup1Name}`, + ); + assert.strictEqual(backupInfo.database, database1.formattedName_); + assert.ok(backupInfo.createTime); + assert.deepStrictEqual( + Number(backupInfo.expireTime!.seconds), + backupExpiryPreciseDate.toStruct().seconds, + ); + assert.ok(backupInfo.sizeBytes! > 0); + + // Validate additional metadata functions on backup. + const backupState = await backup1.getState(); + assert.strictEqual(backupState, 'READY'); + const expireTime = await backup1.getExpireTime(); + assert.deepStrictEqual( + expireTime!.getFullTime(), + backupExpiryPreciseDate.getFullTime(), + ); + const exists = await backup1.exists(); + assert.strictEqual(exists, true); + }; + + it('GOOGLE_STANDARD_SQL should have completed a backup', async () => { + // Create backups. + await createBackup( + googleSqlDatabase1, + googleSqlBackup1Name, + backupExpiryDate, + ); + await completedBackup( + googleSqlBackup1, + googleSqlBackup1Name, + googleSqlDatabase1, + ); + }); + + it.skip('POSTGRESQL should have completed a backup', async () => { + await createBackup( + postgreSqlDatabase1, + postgreSqlBackup1Name, + backupExpiryDate, + ); + await completedBackup( + postgreSqlBackup1, + postgreSqlBackup1Name, + postgreSqlDatabase1, + ); + }); + + const pastBackupExpirationTimeError = async database1 => { + // Create backup. + const backupName = generateName('backup'); + const backupExpiryDate = futureDateByHours(-12); + const backup = instance.backup(backupName); + try { + await backup.create({ + databasePath: database1.formattedName_, + expireTime: backupExpiryDate, + }); + assert.fail( + 'Backup should have failed for expiration time in the past', + ); + } catch (err) { + // Expect to get invalid argument error indicating the expiry date + assert.strictEqual( + (err as grpc.ServiceError).code, + grpc.status.INVALID_ARGUMENT, + ); + } + }; + + it('GOOGLE_STANDARD_SQL should return error for backup expiration time in the past', async () => { + await pastBackupExpirationTimeError(googleSqlDatabase1); + }); + + it.skip('POSTGRESQL should return error for backup expiration time in the past', async () => { + await pastBackupExpirationTimeError(postgreSqlDatabase1); + }); + + it('should return false for a backup that does not exist', async () => { + // This backup won't exist, we're just generating the name without creating the backup itself. + const backupName = generateName('backup'); + const backup = instance.backup(backupName); + + const exists = await backup.exists(); + assert.strictEqual(exists, false); + }); + + it('should list backups', async () => { + const [backups] = await instance.getBackups(); + assert.ok(backups.length > 0); + assert.ok( + backups.find( + backup => backup.formattedName_ === googleSqlBackup1.formattedName_, + ), + ); + if (!SKIP_POSTGRESQL_BACKUP_TESTS) { + assert.ok( + backups.find( + backup => + backup.formattedName_ === postgreSqlBackup1.formattedName_, + ), + ); + } + }); + + it('should list backups with pagination', async () => { + const [page1, , resp1] = await instance.getBackups({ + pageSize: 1, + gaxOptions: {autoPaginate: false}, + }); + + let totalPageSize = 1; + if (!SKIP_POSTGRESQL_BACKUP_TESTS) { + totalPageSize = 2; + } + const [totalPages] = await instance.getBackups({ + pageSize: totalPageSize, + gaxOptions: {autoPaginate: false}, + }); + assert.strictEqual(page1.length, 1); + assert.strictEqual(totalPages.length, totalPageSize); + assert.ok( + totalPages.find( + backup => backup.formattedName_ === googleSqlBackup1.formattedName_, + ), + ); + if (!SKIP_POSTGRESQL_BACKUP_TESTS) { + assert.ok( + totalPages.find( + backup => + backup.formattedName_ === postgreSqlBackup1.formattedName_, + ), + ); + } + }); + + const restoreBackup = async (restoreDatabaseId, backup1, database1) => { + // Perform restore to a different database. + const databaseAdminClient = spanner.getDatabaseAdminClient(); + const [restoreOperation] = await databaseAdminClient.restoreDatabase({ + parent: databaseAdminClient.instancePath(projectId!, instanceId), + databaseId: restoreDatabaseId, + backup: backup1.formattedName_, + }); + + // Wait for restore to complete. + await restoreOperation.promise(); + + const restoreDatabase = instance.database(restoreDatabaseId); + + const [databaseMetadata] = await restoreDatabase.getMetadata(); + assert.ok( + databaseMetadata.state === 'READY' || + databaseMetadata.state === 'READY_OPTIMIZING', + ); + + // Validate restore state of database directly. + const restoreState = await restoreDatabase.getState(); + assert.ok( + restoreState === 'READY' || restoreState === 'READY_OPTIMIZING', + ); + + // Validate new database has restored data. + const [rows] = await restoreDatabase + .table(TABLE_NAME) + .read({columns: ['SingerId', 'Name']}); + const results = rows.map(row => row.toJSON); + assert.strictEqual(results.length, 1); + + // Validate restore info of database. + const restoreInfo = await restoreDatabase.getRestoreInfo(); + assert.strictEqual( + restoreInfo!.backupInfo!.backup, + backup1.formattedName_, + ); + const [originalDatabaseMetadata] = await database1.getMetadata(); + assert.strictEqual( + restoreInfo!.backupInfo!.sourceDatabase, + originalDatabaseMetadata.name, + ); + assert.strictEqual(restoreInfo!.sourceType, 'BACKUP'); + + // Check that restore operation ends up in the operations list. + const [restoreOperations] = await restoreDatabase.getOperations({ + filter: 'metadata.@type:RestoreDatabaseMetadata', + }); + assert.strictEqual(restoreOperations.length, 1); + + return restoreDatabase; + }; + + it('GOOGLE_STANDARD_SQL should restore a backup', async () => { + const googleSqlRestoreDatabaseId = generateName('database'); + googleSqlRestoreDatabase = await restoreBackup( + googleSqlRestoreDatabaseId, + googleSqlBackup1, + googleSqlDatabase1, + ); + }); + + it.skip('POSTGRESQL should restore a backup', async () => { + const postgreSqlRestoreDatabaseId = generateName('pg-db'); + postgreSqlRestoreDatabase = await restoreBackup( + postgreSqlRestoreDatabaseId, + postgreSqlBackup1, + postgreSqlDatabase1, + ); + }); + + const restoreExistingDatabaseFail = async (database1, backup1) => { + // Perform restore to the same database - should fail. + try { + await database1.restore(backup1.formattedName_); + assert.fail('Should not have restored backup over existing database'); + } catch (err) { + // Expect to get error indicating database already exists. + assert.strictEqual( + (err as grpc.ServiceError).code, + grpc.status.ALREADY_EXISTS, + ); + } + }; + + it('GOOGLE_STANDARD_SQL should not be able to restore to an existing database', async () => { + await restoreExistingDatabaseFail( + googleSqlRestoreDatabase, + googleSqlBackup1, + ); + }); + + it.skip('POSTGRESQL should not be able to restore to an existing database', async () => { + await restoreExistingDatabaseFail( + postgreSqlRestoreDatabase, + postgreSqlBackup1, + ); + }); + + const updateBackupExpiry = async backup1 => { + // Update backup expiry date. + const updatedBackupExpiryDate = futureDateByHours(24); + await backup1.updateExpireTime(updatedBackupExpiryDate); + + // Read metadata, verify expiry date was updated. + const [updatedMetadata] = await backup1.getMetadata(); + const expiryDateFromMetadataAfterUpdate = new PreciseDate( + updatedMetadata.expireTime as DateStruct, + ); + + assert.deepStrictEqual( + expiryDateFromMetadataAfterUpdate, + Spanner.timestamp(updatedBackupExpiryDate), + ); + }; + + it('GOOGLE_STANDARD_SQL should update backup expiry', async () => { + await updateBackupExpiry(googleSqlBackup1); + }); + + it.skip('POSTGRESQL should update backup expiry', async () => { + await updateBackupExpiry(postgreSqlBackup1); + }); + + const pastBackupUpdateExpiryDateFail = async backup1 => { + // Attempt to update expiry date to the past. + const expiryDateInPast = futureDateByHours(-24); + try { + await backup1.updateExpireTime(expiryDateInPast); + assert.fail( + 'Backup should have failed for expiration time in the past', + ); + } catch (err) { + // Expect to get invalid argument error indicating the expiry date. + assert.strictEqual( + (err as grpc.ServiceError).code, + grpc.status.INVALID_ARGUMENT, + ); + } + }; + + it('GOOGLE_STANDARD_SQL should not update backup expiry to the past', async () => { + await pastBackupUpdateExpiryDateFail(googleSqlBackup1); + }); + + it.skip('POSTGRESQL should not update backup expiry to the past', async () => { + await pastBackupUpdateExpiryDateFail(postgreSqlBackup1); + }); + + const deleteBackup = async backup2 => { + // Delete backup. + await backup2.delete(); + + // Verify backup is gone by querying metadata. + // Expect backup not to be found. + try { + const [deletedMetadata] = await backup2.getMetadata(); + assert.fail('Backup was not deleted: ' + deletedMetadata.name); + } catch (err) { + assert.strictEqual( + (err as grpc.ServiceError).code, + grpc.status.NOT_FOUND, + ); + } + }; + + const listBackupOperations = async (backup1, database1) => { + // List operations and ensure operation for current backup exists. + // Without a filter. + const [operationsWithoutFilter] = await instance.getBackupOperations(); + const operationForCurrentBackup = operationsWithoutFilter.find( + operation => + operation.name && operation.name.includes(backup1.formattedName_), + ); + assert.ok(operationForCurrentBackup); + assert.strictEqual( + operationForCurrentBackup!.metadata!.type_url, + 'type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata', + ); + + // With a filter. + const [operationsWithFilter] = await instance.getBackupOperations({ + filter: `(metadata.@type:CreateBackupMetadata AND + metadata.name:${backup1.formattedName_})`, + }); + const operationForCurrentBackupWithFilter = operationsWithFilter[0]; + assert.ok(operationForCurrentBackupWithFilter); + assert.strictEqual( + operationForCurrentBackupWithFilter!.metadata!.type_url, + 'type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata', + ); + const operationForCurrentBackupWithFilterMetadata = + CreateBackupMetadata.decode( + operationForCurrentBackupWithFilter!.metadata!.value! as Uint8Array, + ); + assert.strictEqual( + operationForCurrentBackupWithFilterMetadata.database, + database1.formattedName_, + ); + }; + + it('GOOGLE_STANDARD_SQL should list backup operations', async () => { + await listBackupOperations(googleSqlBackup1, googleSqlDatabase1); + }); + + it.skip('POSTGRESQL should list backup operations', async () => { + await listBackupOperations(postgreSqlBackup1, postgreSqlDatabase1); + }); + + it('GOOGLE_STANDARD_SQL should delete backups', async () => { + // Delete the restored database before deleting the backup, as backup deletion can fail if the restored database remains in the READY_OPTIMIZING state. + await googleSqlRestoreDatabase.delete(); + await deleteBackup(googleSqlBackup1); + }); + + it.skip('POSTGRESQL should delete backups', async () => { + // Delete the restored database before deleting the backup, as backup deletion can fail if the restored database remains in the READY_OPTIMIZING state. + await postgreSqlRestoreDatabase.delete(); + await deleteBackup(postgreSqlBackup1); + }); + }); + + describe('Sessions', () => { + let session; + let dbNewRole; + let sessionWithDatabaseRole; + let sessionWithRole: Session; + let sessionWithOverridingRole: Session; + + before(async () => { + session = DATABASE.session(); + + dbNewRole = instance.database(DATABASE.formattedName_, { + databaseRole: 'parent_role', + }); + + sessionWithDatabaseRole = dbNewRole.session(); + await session.create(); + if (!IS_EMULATOR_ENABLED) { + const [operation] = await DATABASE.updateSchema([ + 'CREATE ROLE parent_role', + 'CREATE ROLE child_role', + 'CREATE ROLE orphan_role', + ]); + await operation.promise(); + await sessionWithDatabaseRole.create(); + [sessionWithRole] = await DATABASE.createSession({ + databaseRole: 'child_role', + }); + [sessionWithOverridingRole] = await dbNewRole.createSession({ + databaseRole: 'orphan_role', + }); + } + }); + + after(async () => { + await session.delete(); + if (!IS_EMULATOR_ENABLED) { + await sessionWithDatabaseRole.delete(); + await sessionWithRole.delete(); + } + }); + + it('should have created the session', async () => { + const [metadata] = await session.getMetadata(); + assert.strictEqual(session.formattedName_, metadata!.name); + }); + + it('should get a session by name', async () => { + const shortName = session.formattedName_!.split('/').pop(); + const sessionByShortName = DATABASE.session(shortName); + + const [metadataByName] = await sessionByShortName.getMetadata(); + const [metadata] = await session.getMetadata(); + assert.strictEqual(metadataByName!.name, metadata!.name); + }); + + it('should keep the session alive', async () => { + await session.keepAlive(); + }); + + it('should batch create sessions', async () => { + const count = 5; + const [sessions] = await DATABASE.batchCreateSessions({count}); + + assert.strictEqual(sessions.length, count); + + await Promise.all(sessions.map(session => session.delete())); + }); + + it('should have created the session with database database role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const [metadata] = await sessionWithDatabaseRole.getMetadata(); + assert.strictEqual('parent_role', metadata!.databaseRole); + }); + + it('should have created the session with database role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const metadata = await sessionWithRole.getMetadata(); + assert.strictEqual('child_role', metadata[0]!.databaseRole); + }); + + it('should have created the session by overriding database database role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const metadata = await sessionWithOverridingRole.getMetadata(); + assert.strictEqual('orphan_role', metadata[0]!.databaseRole); + }); + + it('should batch create sessions with database role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const count = 5; + const [sessions] = await dbNewRole.batchCreateSessions({count}); + + assert.strictEqual(sessions.length, count); + await Promise.all( + sessions.map(async session => { + const metadata = await session.getMetadata(); + assert.strictEqual('parent_role', metadata[0].databaseRole); + await session.delete(); + }), + ); + }); + + it('should batch create sessions with database role by overriding session database-role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const count = 5; + const [sessions] = await DATABASE.batchCreateSessions({ + count, + databaseRole: 'child_role', + }); + + assert.strictEqual(sessions.length, count); + await Promise.all( + sessions.map(async session => { + const metadata = await session.getMetadata(); + assert.strictEqual('child_role', metadata[0].databaseRole); + await session.delete(); + }), + ); + }); + + it('should batch create sessions with database role by overriding database-role', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const count = 5; + const [sessions] = await dbNewRole.batchCreateSessions({ + count, + databaseRole: 'orphan_role', + }); + + assert.strictEqual(sessions.length, count); + await Promise.all( + sessions.map(async session => { + const metadata = await session.getMetadata(); + assert.strictEqual('orphan_role', metadata[0].databaseRole); + await session.delete(); + }), + ); + }); + }); + + describe('Tables', () => { + const TABLE_NAME = 'SingersTables'; + let googleSqlTable; + let postgreSqlTable; + + before(async () => { + googleSqlTable = DATABASE.table(TABLE_NAME); + postgreSqlTable = PG_DATABASE.table(TABLE_NAME); + const googleSqlCreateTable = await googleSqlTable.create( + `CREATE TABLE ${TABLE_NAME} + ( + SingerId STRING(1024) NOT NULL, + Name STRING(1024), + UUID UUID, + Float32 FLOAT32, + Float FLOAT64, + Int INT64, + Info BYTES( MAX), + Created TIMESTAMP, + DOB DATE, + Accents ARRAY, + PhoneNumbers ARRAY, + HasGear BOOL, + ) PRIMARY KEY(SingerId)`, + GAX_OPTIONS, + ); + await onPromiseOperationComplete(googleSqlCreateTable); + + // TODO: Add column "UUID" UUID while using uuid type.(currently UUID type is not supported for postgreSql dialect) + const postgreSqlCreateTable = await postgreSqlTable.create( + `CREATE TABLE ${TABLE_NAME} + ( + "SingerId" VARCHAR(1024) NOT NULL PRIMARY KEY, + "Name" VARCHAR(1024), + "Float32" DOUBLE PRECISION, + "Float" DOUBLE PRECISION, + "Int" BIGINT, + "Info" BYTEA, + "Created" TIMESTAMPTZ, + "HasGear" BOOL + )`, + GAX_OPTIONS, + ); + await onPromiseOperationComplete(postgreSqlCreateTable); + }); + + const nonExistentTable = async database => { + const table = database.table(generateName('nope')); + + try { + await table.insert({SingerId: generateName('id')}); + assert.fail('Expected an error to be thrown, but it was not.'); + } catch (err: any) { + assert.strictEqual(err!.code, grpc.status.NOT_FOUND); + } + }; + + it('GOOGLE_STANDARD_SQL should throw an error for non-existent tables', async () => { + await nonExistentTable(DATABASE); + }); + + it('POSTGRESQL should throw an error for non-existent tables', async () => { + await nonExistentTable(PG_DATABASE); + }); + + const nonExistentColumn = async table => { + try { + await table.insert({SingerId: generateName('id'), Nope: 'abc'}); + assert.fail('Expected an error to be thrown, but it was not.'); + } catch (err: any) { + assert.strictEqual(err!.code, grpc.status.NOT_FOUND); + } + }; + + it('GOOGLE_STANDARD_SQL should throw an error for non-existent columns', async () => { + await nonExistentColumn(googleSqlTable); + }); + + it('POSTGRESQL should throw an error for non-existent columns', async () => { + await nonExistentColumn(postgreSqlTable); + }); + + const readRowsStream = (done, table) => { + const id = generateName('id'); + const name = generateName('name'); + + table.insert( + { + SingerId: id, + Name: name, + }, + err => { + assert.ifError(err); + + let rows: Array<{}> = []; + + table + .createReadStream({ + keys: [id], + columns: ['SingerId', 'Name'], + }) + .on('error', done) + .on('data', row => { + rows.push(row); + }) + .on('end', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + rows = rows.map(x => (x as any).toJSON()); + + assert.deepStrictEqual(rows, [ + { + SingerId: id, + Name: name, + }, + ]); + + done(); + }); + }, + ); + }; + + it('GOOGLE_STANDARD_SQL should read rows as a stream', done => { + readRowsStream(done, googleSqlTable); + }); + + it('POSTGRESQL should read rows as a stream', done => { + readRowsStream(done, postgreSqlTable); + }); + + const automaticallyConvertToJson = (done, table) => { + const id = generateName('id'); + const name = generateName('name'); + + table.insert( + { + SingerId: id, + Name: name, + }, + err => { + assert.ifError(err); + + const rows: Array<{}> = []; + + table + .createReadStream({ + keys: [id], + columns: ['SingerId', 'name'], + json: true, + }) + .on('error', done) + .on('data', row => rows.push(row)) + .on('end', () => { + assert.deepStrictEqual(rows, [ + { + SingerId: id, + Name: name, + }, + ]); + + done(); + }); + }, + ); + }; + + it('GOOGLE_STANDARD_SQL should automatically convert to JSON', done => { + automaticallyConvertToJson(done, googleSqlTable); + }); + + it('POSTGRESQL should automatically convert to JSON', done => { + automaticallyConvertToJson(done, postgreSqlTable); + }); + + const automaticallyConvertToJsonWithOptions = (done, table) => { + const id = generateName('id'); + + table.insert( + { + SingerId: id, + Int: 8, + }, + err => { + assert.ifError(err); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rows: any[] = []; + + table + .createReadStream({ + keys: [id], + columns: ['SingerId', 'Int'], + json: true, + jsonOptions: {wrapNumbers: true}, + }) + .on('error', done) + .on('data', row => { + rows.push(row); + }) + .on('end', () => { + assert.strictEqual(rows[0].Int.value, '8'); + done(); + }); + }, + ); + }; + + it('GOOGLE_STANDARD_SQL should automatically convert to JSON with options', done => { + automaticallyConvertToJsonWithOptions(done, googleSqlTable); + }); + + it('POSTGRESQL should automatically convert to JSON with options', done => { + automaticallyConvertToJsonWithOptions(done, postgreSqlTable); + }); + + const insertAndDeleteSingleRow = (done, table) => { + const id = generateName('id'); + const name = generateName('name'); + + table.insert( + { + SingerId: id, + Name: name, + }, + err => { + assert.ifError(err); + + table.deleteRows([id], err => { + assert.ifError(err); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rows: any[] = []; + + table + .createReadStream({ + keys: [id], + columns: ['SingerId'], + }) + .on('error', done) + .on('data', row => { + rows.push(row); + }) + .on('end', () => { + assert.strictEqual(rows.length, 0); + done(); + }); + }); + }, + ); + }; + + it('GOOGLE_STANDARD_SQL should insert and delete a row', done => { + insertAndDeleteSingleRow(done, googleSqlTable); + }); + + it('POSTGRESQL should insert and delete a row', done => { + insertAndDeleteSingleRow(done, postgreSqlTable); + }); + + const insertAndDeleteMultipleRows = (done, table) => { + const id = generateName('id'); + const id2 = generateName('id2'); + + const name = generateName('name'); + + table.insert( + [ + { + SingerId: id, + Name: name, + }, + { + SingerId: id2, + Name: name, + }, + ], + err => { + assert.ifError(err); + + table.deleteRows([id, id2], err => { + assert.ifError(err); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const rows: any[] = []; + + table + .createReadStream({ + keys: [id, id2], + columns: ['SingerId'], + }) + .on('error', done) + .on('data', row => { + rows.push(row); + }) + .on('end', () => { + assert.strictEqual(rows.length, 0); + done(); + }); + }); + }, + ); + }; + + it('GOOGLE_STANDARD_SQL should insert and delete multiple rows', done => { + insertAndDeleteMultipleRows(done, googleSqlTable); + }); + + it('POSTGRESQL should insert and delete multiple rows', done => { + insertAndDeleteMultipleRows(done, postgreSqlTable); + }); + + const insertAndDeleteMultipleCompositeKeyRows = async ( + database, + createTableStatement, + ) => { + const id1 = 1; + const name1 = generateName('name1'); + + const id2 = 2; + const name2 = generateName('name2'); + + const table = database.table('SingersComposite'); + + const keys = [ + [id1, name1], + [id2, name2], + ] as {} as string[]; + + const [, operation] = await table.create(createTableStatement); + await operation.promise(); + await table.insert([ + {SingerId: id1, Name: name1}, + {SingerId: id2, Name: name2}, + ]); + const [rows] = await table.read({keys, columns: ['SingerId', 'Name']}); + assert.strictEqual(rows.length, 2); + await table.deleteRows(keys as Key[]); + const [rowsAfterDelete] = await table.read({ + keys, + columns: ['SingerId', 'Name'], + }); + assert.strictEqual(rowsAfterDelete.length, 0); + }; + + it('GOOGLE_STANDARD_SQL should insert and delete composite key rows', async () => { + const createTableStatement = ` + CREATE TABLE SingersComposite ( + SingerId INT64 NOT NULL, + Name STRING(1024), + ) PRIMARY KEY(SingerId, Name) + `; + await insertAndDeleteMultipleCompositeKeyRows( + DATABASE, + createTableStatement, + ); + }); + + it('POSTGRESQL should insert and delete multiple composite key rows', async () => { + const createTableStatement = ` + CREATE TABLE SingersComposite ( + "SingerId" BIGINT NOT NULL, + "Name" VARCHAR(1024), + PRIMARY KEY("SingerId", "Name") + )`; + await insertAndDeleteMultipleCompositeKeyRows( + PG_DATABASE, + createTableStatement, + ); + }); + + const insertAndQueryMultipleRows = async (database, table, query) => { + const id1 = generateName('id1'); + const name1 = generateName('name'); + + const id2 = generateName('id2'); + const name2 = generateName('name'); + + await table.insert([ + {SingerId: id1, Name: name1}, + {SingerId: id2, Name: name2}, + ]); + const [rows] = await database.run(query); + // We just want the two most recent ones. + rows!.splice(0, rows!.length - 2); + + const rowJson = rows!.map(x => x.toJSON()); + + assert.strictEqual(rowJson[0].SingerId, id1); + assert.strictEqual(rowJson[0].Name, name1); + + assert.strictEqual(rowJson[1].SingerId, id2); + assert.strictEqual(rowJson[1].Name, name2); + }; + + it('GOOGLE_STANDARD_SQL should insert and query multiple rows', async () => { + await insertAndQueryMultipleRows( + DATABASE, + googleSqlTable, + `SELECT * FROM ${TABLE_NAME} ORDER BY SingerId`, + ); + }); + + it('POSTGRESQL should should insert and query multiple rows', async () => { + await insertAndQueryMultipleRows( + PG_DATABASE, + postgreSqlTable, + `SELECT * FROM ${TABLE_NAME} ORDER BY "SingerId"`, + ); + }); + + const insertThenReplaceRow = async table => { + const originalRow = { + SingerId: generateName('id'), + Name: generateName('name'), + }; + + const replacedRow = { + SingerId: originalRow.SingerId, + }; + + await table.insert(originalRow); + await table.replace(replacedRow); + const [rows] = await table.read({ + keys: [originalRow.SingerId], + columns: Object.keys(originalRow), + }); + const row = rows![0].toJSON(); + assert.strictEqual(row.SingerId, replacedRow.SingerId); + assert.strictEqual(row.Name, null); + }; + + it('GOOGLE_STANDARD_SQL should insert then replace a row', async () => { + await insertThenReplaceRow(googleSqlTable); + }); + + it('POSTGRESQL should insert then replace a row', async () => { + await insertThenReplaceRow(postgreSqlTable); + }); + + const insertThenUpdateRow = async table => { + const originalRow = { + SingerId: generateName('id'), + Name: generateName('name'), + }; + + const updatedRow = { + SingerId: originalRow.SingerId, + Name: generateName('name'), + }; + + await table.insert(originalRow); + await table.update(updatedRow); + const [rows] = await table.read({ + keys: [originalRow.SingerId], + columns: Object.keys(originalRow), + }); + const row = rows![0].toJSON(); + assert.strictEqual(row.SingerId, updatedRow.SingerId); + assert.strictEqual(row.Name, updatedRow.Name); + }; + + it('GOOGLE_STANDARD_SQL should insert then replace a row', async () => { + await insertThenUpdateRow(googleSqlTable); + }); + + it('POSTGRESQL should insert then replace a row', async () => { + await insertThenUpdateRow(postgreSqlTable); + }); + + describe('insert & query', () => { + const ID = generateName('id'); + const NAME = generateName('name'); + const UUID = uuid.v4(); + const FLOAT32 = 8.2; + const FLOAT = 8.2; + const INT = 2; + const INFO = Buffer.from(generateName('info')); + const CREATED = Spanner.timestamp(); + const DOB = Spanner.date('1969-08-20'); + const ACCENTS = ['jamaican']; + const PHONE_NUMBERS = [123123123, 234234234]; + const HAS_GEAR = true; + + const GOOGLE_SQL_INSERT_ROW = { + SingerId: ID, + Name: NAME, + UUID: UUID, + Float32: FLOAT32, + Float: FLOAT, + Int: INT, + Info: INFO, + Created: CREATED, + DOB, + Accents: ACCENTS, + PhoneNumbers: PHONE_NUMBERS, + HasGear: HAS_GEAR, + }; + + const POSTGRESQL_INSERT_ROW = { + SingerId: ID, + Name: NAME, + // UUID: UUID, // TODO: Uncomment while using uuid type. + Float32: FLOAT32, + Float: FLOAT, + Int: INT, + Info: INFO, + Created: CREATED, + HasGear: HAS_GEAR, + }; + + const GOOGLE_SQL_EXPECTED_ROW = extend(true, {}, GOOGLE_SQL_INSERT_ROW); + const POSTGRESQL_EXPECTED_ROW = extend(true, {}, POSTGRESQL_INSERT_ROW); + + before(async () => { + await googleSqlTable.insert(GOOGLE_SQL_INSERT_ROW); + await postgreSqlTable.insert(POSTGRESQL_INSERT_ROW); + }); + + const queryCallbackMode = async (database, query, EXPECTED_ROW) => { + const options = { + strong: true, + }; + + const [rows] = await database.run(query, options); + const actualRows = rows!.shift()!.toJSON() as {} as Row[]; + for (const [key, value] of Object.entries(actualRows)) { + if (value && key === 'Float32') { + assert.ok( + EXPECTED_ROW[key] - (value as unknown as number) <= 0.00001, + ); + } else { + assert.deepStrictEqual(EXPECTED_ROW[key], value); + } + } + }; + + it('GOOGLE_STANDARD_SQL should query in callback mode', async () => { + const query = { + sql: `SELECT * FROM ${TABLE_NAME} WHERE SingerId=@id`, + params: {id: ID}, + }; + await queryCallbackMode(DATABASE, query, GOOGLE_SQL_EXPECTED_ROW); + }); + + it('POSTGRESQL should query in callback mode', async () => { + const query = { + sql: `SELECT * FROM ${TABLE_NAME} WHERE "SingerId"=$1`, + params: {p1: ID}, + }; + await queryCallbackMode(PG_DATABASE, query, POSTGRESQL_EXPECTED_ROW); + }); + + const queryPromiseMode = async (database, query, EXPECTED_ROW) => { + const options = { + strong: true, + }; + + const data = await database.run(query, options); + const rows = data[0]!.shift()!.toJSON() as {} as Row[]; + for (const [key, value] of Object.entries(rows)) { + if (key === 'Float32') { + assert.ok( + EXPECTED_ROW[key] - (value as unknown as number) <= 0.00001, + ); + } else { + assert.deepStrictEqual(EXPECTED_ROW[key], value); + } + } + }; + + it('GOOGLE_STANDARD_SQL should query in promise mode', async () => { + const query = { + sql: `SELECT * FROM ${TABLE_NAME} WHERE SingerId=@id`, + params: {id: ID}, + }; + await queryPromiseMode(DATABASE, query, GOOGLE_SQL_EXPECTED_ROW); + }); + + it('POSTGRESQL should query in promise mode', async () => { + const query = { + sql: `SELECT * FROM ${TABLE_NAME} WHERE "SingerId"=$1`, + params: {p1: ID}, + }; + await queryPromiseMode(PG_DATABASE, query, POSTGRESQL_EXPECTED_ROW); + }); + + const queryStreamMode = (done, database, query, EXPECTED_ROW) => { + const options = { + strong: true, + }; + let row; + + const stream = database + .runStream(query, options) + .on('error', done) + .once('data', row_ => { + row = row_; + stream.end(); + }) + .on('end', () => { + const actualRows = row!.toJSON() as {} as Row[]; + for (const [key, value] of Object.entries(actualRows)) { + if (key === 'Float32') { + assert.ok( + EXPECTED_ROW[key] - (value as unknown as number) <= 0.00001, + ); + } else { + assert.deepStrictEqual(EXPECTED_ROW[key], value); + } + } + done(); + }); + }; + + it('GOOGLE_STANDARD_SQL should query in stream mode', done => { + const query = { + sql: `SELECT * FROM ${TABLE_NAME} WHERE SingerId=@id`, + params: {id: ID}, + }; + queryStreamMode(done, DATABASE, query, GOOGLE_SQL_EXPECTED_ROW); + }); + + it('POSTGRESQL should query in stream mode', done => { + const query = { + sql: `SELECT * FROM ${TABLE_NAME} WHERE "SingerId"=$1`, + params: {p1: ID}, + }; + queryStreamMode(done, PG_DATABASE, query, POSTGRESQL_EXPECTED_ROW); + }); + + it('GOOGLE_STANDARD_SQL should execute mutation group using Batch write', function (done) { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const mutationGroup = new MutationGroup(); + mutationGroup.upsert(TABLE_NAME, {SingerId: ID, Name: NAME}); + DATABASE.batchWriteAtLeastOnce([mutationGroup], {}) + .on('data', data => { + assert.strictEqual(data.status.code, 0); + }) + .on('end', () => { + done(); + }) + .on('error', error => { + done(error); + }); + }); + + it('GOOGLE_STANDARD_SQL should execute multiple mutation groups with success and failure using Batch write', function (done) { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const id = generateName('id'); + + // Valid mutation group + const mutationGroup1 = new MutationGroup(); + mutationGroup1.insert(TABLE_NAME, {SingerId: id, Name: NAME}); + + // InValid mutation group with duplicate data + const mutationGroup2 = new MutationGroup(); + mutationGroup2.insert(TABLE_NAME, {SingerId: id, Name: NAME}); + + // Valid mutation group with invalid signer id + const mutationGroup3 = new MutationGroup(); + mutationGroup3.insert(TABLE_NAME, { + SingerId: null, + Name: NAME, + }); + + // Array of expected status code + // Code 0 is for mutation group with valid id + // Code 6 is for mutation group with duplicate id + // Code 9 is for mutation group with null id + const expectedStatusCode: number[] = [0, 6, 9]; + + // Array of status codes in the stream + const actualStatusCode: number[] = []; + + DATABASE.batchWriteAtLeastOnce([ + mutationGroup1, + mutationGroup2, + mutationGroup3, + ]) + .on('data', data => { + actualStatusCode.push(data.status.code); + }) + .on('error', error => { + done(error); + }) + .on('end', () => { + // make sure two mutation groups are failing and + // one mutation group is getting success + assert.deepStrictEqual( + actualStatusCode.sort(), + expectedStatusCode.sort(), + ); + done(); + }); + }); + + it('POSTGRESQL should execute mutation group using Batch write', function (done) { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const mutationGroup = new MutationGroup(); + mutationGroup.upsert(TABLE_NAME, {SingerId: ID, Name: NAME}); + PG_DATABASE.batchWriteAtLeastOnce([mutationGroup], {}) + .on('data', data => { + assert.strictEqual(data.status.code, 0); + }) + .on('end', () => { + done(); + }) + .on('error', error => { + done(error); + }); + }); + + it('GOOGLE_STANDARD_SQL should allow "SELECT 1" queries', done => { + DATABASE.run('SELECT 1', done); + }); + + it('POSTGRESQL should allow "SELECT 1" queries', done => { + PG_DATABASE.run('SELECT 1', done); + }); + + it('GOOGLE_STANDARD_SQL should return metadata', async () => { + const [rows, , metadata] = await DATABASE.run({ + sql: `SELECT * FROM ${TABLE_NAME} WHERE SingerId=@id`, + params: {id: ID}, + }); + assert.strictEqual(rows.length, 1); + for (const [key, value] of Object.entries(rows[0].toJSON())) { + if (value && key === 'Float32') { + assert.ok( + GOOGLE_SQL_EXPECTED_ROW[key] - (value as unknown as number) <= + 0.00001, + ); + } else { + assert.deepStrictEqual(GOOGLE_SQL_EXPECTED_ROW[key], value); + } + } + assert.ok(metadata); + assert.strictEqual(metadata.rowType!.fields!.length, 12); + assert.strictEqual(metadata.rowType!.fields![0].name, 'SingerId'); + assert.strictEqual(metadata.rowType!.fields![1].name, 'Name'); + assert.strictEqual(metadata.rowType!.fields![2].name, 'UUID'); + assert.strictEqual(metadata.rowType!.fields![3].name, 'Float32'); + assert.strictEqual(metadata.rowType!.fields![4].name, 'Float'); + assert.strictEqual(metadata.rowType!.fields![5].name, 'Int'); + assert.strictEqual(metadata.rowType!.fields![6].name, 'Info'); + assert.strictEqual(metadata.rowType!.fields![7].name, 'Created'); + assert.strictEqual(metadata.rowType!.fields![8].name, 'DOB'); + assert.strictEqual(metadata.rowType!.fields![9].name, 'Accents'); + assert.strictEqual(metadata.rowType!.fields![10].name, 'PhoneNumbers'); + assert.strictEqual(metadata.rowType!.fields![11].name, 'HasGear'); + }); + + it('POSTGRESQL should return metadata', async () => { + const [rows, , metadata] = await PG_DATABASE.run({ + sql: `SELECT * FROM ${TABLE_NAME} WHERE "SingerId"=$1`, + params: {p1: ID}, + }); + assert.strictEqual(rows.length, 1); + for (const [key, value] of Object.entries(rows[0].toJSON())) { + if (value && key === 'Float32') { + assert.ok( + POSTGRESQL_EXPECTED_ROW[key] - (value as unknown as number) <= + 0.00001, + ); + } else { + assert.deepStrictEqual(POSTGRESQL_EXPECTED_ROW[key], value); + } + } + assert.ok(metadata); + assert.strictEqual(metadata.rowType!.fields!.length, 8); + assert.strictEqual(metadata.rowType!.fields![0].name, 'SingerId'); + assert.strictEqual(metadata.rowType!.fields![1].name, 'Name'); + // uncomment while using uuid type. + // assert.strictEqual(metadata.rowType!.fields![2].name, 'UUID'); + assert.strictEqual(metadata.rowType!.fields![2].name, 'Float32'); + assert.strictEqual(metadata.rowType!.fields![3].name, 'Float'); + assert.strictEqual(metadata.rowType!.fields![4].name, 'Int'); + assert.strictEqual(metadata.rowType!.fields![5].name, 'Info'); + assert.strictEqual(metadata.rowType!.fields![6].name, 'Created'); + assert.strictEqual(metadata.rowType!.fields![7].name, 'HasGear'); + }); + + const invalidQueries = async database => { + try { + await database.run('SELECT Apples AND Oranges'); + } catch (err: any) { + assert.strictEqual(err!.code, 3); + } + }; + + it('GOOGLE_STANDARD_SQL should allow "SELECT 1" queries', async () => { + await invalidQueries(DATABASE); + }); + + it('POSTGRESQL should allow "SELECT 1" queries', async () => { + await invalidQueries(PG_DATABASE); + }); + + it('GOOGLE_STANDARD_SQL should query an array of structs', async () => { + const query = ` + SELECT ARRAY(SELECT AS STRUCT C1, C2 + FROM (SELECT 'a' AS C1, 1 AS C2 UNION ALL SELECT 'b' AS C1, 2 AS C2) + ORDER BY C1 ASC)`; + + const [rows] = await DATABASE.run(query); + const values = rows![0][0].value; + assert.strictEqual(values.length, 2); + + assert.strictEqual(values[0][0].value, 'a'); + assert.deepStrictEqual( + JSON.stringify(values[0][1].value), + JSON.stringify({value: '1'}), + ); + + assert.strictEqual(values[1][0].value, 'b'); + assert.deepStrictEqual( + JSON.stringify(values[1][1].value), + JSON.stringify({value: '2'}), + ); + }); + + it('GOOGLE_STANDARD_SQL should query an empty array of structs', async () => { + const query = ` + SELECT ARRAY(SELECT AS STRUCT * FROM (SELECT 'a', 1) WHERE 0 = 1)`; + + const [rows] = await DATABASE.run(query); + assert.strictEqual(rows![0][0].value.length, 0); + }); + + describe('params', () => { + describe('boolean', () => { + const booleanQuery = async (database, query, value) => { + const [rows] = await database.run(query); + assert.strictEqual(rows[0][0].value, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: true, + }, + }; + await booleanQuery(DATABASE, query, true); + }); + + it('POSTGRESQL should bind the value', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: true, + }, + }; + await booleanQuery(PG_DATABASE, query, true); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'bool', + }, + }; + await booleanQuery(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'bool', + }, + }; + await booleanQuery(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [false, true, false]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows[0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'bool', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'bool', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + }); + + describe('int64', () => { + const int64Query = async (database, query, value) => { + const [rows] = await database.run(query); + let queriedValue = rows[0][0].value; + if (rows[0][0].value) { + queriedValue = rows[0][0].value.value; + } + assert.strictEqual(queriedValue, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: 1234, + }, + }; + await int64Query(DATABASE, query, '1234'); + }); + + it('POSTGRESQL should bind the value', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: 1234, + }, + }; + await int64Query(PG_DATABASE, query, '1234'); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'int64', + }, + }; + await int64Query(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'int64', + }, + }; + await int64Query(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [1, 2, 3, null]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + }; + + const [rows] = await DATABASE.run(query); + + const expected = values.map(val => { + return isNumber(val) ? {value: String(val)} : val; + }); + + assert.strictEqual( + JSON.stringify(rows[0][0].value), + JSON.stringify(expected), + ); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'int64', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'int64', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + }); + + describe('pgOid', () => { + const oidQuery = async (database, query, value) => { + const [rows] = await database.run(query); + let queriedValue = rows[0][0].value; + if (rows[0][0].value) { + queriedValue = rows[0][0].value.value; + } + assert.strictEqual(queriedValue, value); + }; + + it('POSTGRESQL should bind the value', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: 1234, + }, + types: { + v: 'pgOid', + }, + }; + await oidQuery(PG_DATABASE, query, '1234'); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'pgOid', + }, + }; + await oidQuery(PG_DATABASE, query, null); + }); + }); + + describe('uuid', () => { + const uuidQuery = async (database, query, value) => { + const [rows] = await database.run(query); + const queriedValue = rows[0][0].value; + assert.deepStrictEqual(queriedValue, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value when param type uuid is used', async () => { + const value = uuid.v4(); + const query = { + sql: 'SELECT @v', + params: { + v: value, + }, + types: { + v: 'uuid', + }, + }; + await uuidQuery(DATABASE, query, value); + }); + + it('GOOGLE_STANDARD_SQL should bind the value as uuid when param type is not specified', async () => { + const val = uuid.v4(); + const id = generateName('id'); + try { + await googleSqlTable.insert({SingerId: id, UUID: val}); + const query = { + sql: + 'SELECT SingerId, UUID FROM `' + + googleSqlTable.name + + '` WHERE UUID = @v', + params: { + v: val, + }, + }; + const [rows] = await DATABASE.run(query); + assert.strictEqual(rows[0][0].value, id); + assert.strictEqual(uuid.validate(rows[0][1].value), true); + } catch (err) { + assert.ifError(err); + } + }); + + it.skip('POSTGRESQL should bind the value when param type uuid is used', async () => { + const value = uuid.v4(); + const query = { + sql: 'SELECT $1', + params: { + p1: value, + }, + types: { + p1: 'uuid', + }, + }; + await uuidQuery(PG_DATABASE, query, value); + }); + + it.skip('POSTGRESQL should bind the value as uuid when param type is not specified', async () => { + const val = uuid.v4(); + const id = generateName('id'); + try { + await postgreSqlTable.insert({SingerId: id, UUID: val}); + const query = { + sql: + 'SELECT "SingerId", "UUID" FROM ' + + postgreSqlTable.name + + ' WHERE "UUID" = $1', + params: { + p1: val, + }, + }; + const [rows] = await PG_DATABASE.run(query); + assert.strictEqual(rows[0][0].value, id); + assert.strictEqual(uuid.validate(rows[0][1].value), true); + } catch (err) { + assert.ifError(err); + } + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [uuid.v4(), uuid.v4(), uuid.v4()]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'uuid', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows[0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'uuid', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows[0][0].value, values); + }); + + it.skip('POSTGRESQL should bind arrays', async () => { + const values = [uuid.v4(), uuid.v4(), uuid.v4()]; + + const query = { + sql: 'SELECT $1', + params: { + p1: values, + }, + types: { + p1: { + type: 'array', + child: 'uuid', + }, + }, + }; + + const [rows] = await PG_DATABASE.run(query); + assert.deepStrictEqual(rows[0][0].value, values); + }); + + it.skip('POSTGRESQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT $1', + params: { + p1: values, + }, + types: { + p1: { + type: 'array', + child: 'uuid', + }, + }, + }; + + const [rows] = await PG_DATABASE.run(query); + assert.deepStrictEqual(rows[0][0].value, values); + }); + }); + + describe('float32', () => { + const float32Query = async (database, query, value) => { + const [rows] = await database.run(query); + let queriedValue = rows[0][0].value; + if (rows[0][0].value) { + queriedValue = rows[0][0].value.value; + } + if (Number.isNaN(queriedValue)) { + assert.deepStrictEqual(queriedValue, value); + } else if (queriedValue === value) { + assert.deepStrictEqual(queriedValue, value); + } else { + assert.ok(queriedValue - value <= 0.00001); + } + }; + + it('GOOGLE_STANDARD_SQL should bind the value when param type float32 is used', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: 2.2, + }, + types: { + v: 'float32', + }, + }; + await float32Query(DATABASE, query, 2.2); + }); + + it('GOOGLE_STANDARD_SQL should bind the value when spanner.float32 is used', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: Spanner.float32(2.2), + }, + }; + await float32Query(DATABASE, query, 2.2); + }); + + it('GOOGLE_STANDARD_SQL should bind the value as float64 when param type is not specified', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: 2.2, + }, + }; + const [rows] = await DATABASE.run(query); + assert.strictEqual(rows[0][0].value instanceof Float, true); + }); + + it('POSTGRESQL should bind the value when param type float32 is used', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: 2.2, + }, + types: { + p1: 'float32', + }, + }; + await float32Query(PG_DATABASE, query, 2.2); + }); + + it('POSTGRESQL should bind the value when Spanner.float32 is used', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: Spanner.float32(2.2), + }, + }; + await float32Query(PG_DATABASE, query, 2.2); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'float32', + }, + }; + await float32Query(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'float32', + }, + }; + await float32Query(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [null, 1.1, 2.3, 3.5, null]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'float32', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + const expected = values.map(val => { + return isNumber(val) ? Spanner.float32(val) : val; + }); + + for (let i = 0; i < rows[0][0].value.length; i++) { + if (rows[0][0].value[i] === null || expected[i] === null) { + assert.deepStrictEqual(rows[0][0].value[i], expected[i]); + } else { + assert.ok( + rows[0][0].value[i] - expected[i]!['value'] <= 0.00001, + ); + } + } + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'float32', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'float32', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + + it('GOOGLE_STANDARD_SQL should bind Infinity', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: Infinity, + }, + types: { + v: 'float32', + }, + }; + await float32Query(DATABASE, query, 'Infinity'); + }); + + it('POSTGRESQL should bind Infinity', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: Infinity, + }, + types: { + p1: 'float32', + }, + }; + await float32Query(PG_DATABASE, query, 'Infinity'); + }); + + it('GOOGLE_STANDARD_SQL should bind -Infinity', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: -Infinity, + }, + types: { + v: 'float32', + }, + }; + await float32Query(DATABASE, query, '-Infinity'); + }); + + it('POSTGRESQL should bind -Infinity', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: -Infinity, + }, + types: { + p1: 'float32', + }, + }; + await float32Query(PG_DATABASE, query, '-Infinity'); + }); + + it('GOOGLE_STANDARD_SQL should bind NaN', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: NaN, + }, + types: { + v: 'float32', + }, + }; + await float32Query(DATABASE, query, 'NaN'); + }); + + it('POSTGRESQL should bind NaN', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: NaN, + }, + types: { + p1: 'float32', + }, + }; + await float32Query(PG_DATABASE, query, 'NaN'); + }); + + it('GOOGLE_STANDARD_SQL should bind an array of Infinity and NaN', async () => { + const values = [Infinity, -Infinity, NaN]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'float32', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + + const expected = values.map(val => { + return isNumber(val) ? {value: val + ''} : val; + }); + + assert.strictEqual( + JSON.stringify(rows[0][0].value), + JSON.stringify(expected), + ); + }); + }); + + describe('float64', () => { + const float64Query = async (database, query, value) => { + const [rows] = await database.run(query); + let queriedValue = rows[0][0].value; + if (rows[0][0].value) { + queriedValue = rows[0][0].value.value; + } + assert.strictEqual(queriedValue, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: 2.2, + }, + }; + await float64Query(DATABASE, query, 2.2); + }); + + it('POSTGRESQL should bind the value', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: 2.2, + }, + }; + await float64Query(PG_DATABASE, query, 2.2); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'float64', + }, + }; + await float64Query(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'float64', + }, + }; + await float64Query(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [null, 1.1, 2.3, 3.5, null]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + }; + + const [rows] = await DATABASE.run(query); + + const expected = values.map(val => { + return isNumber(val) ? {value: val} : val; + }); + + assert.strictEqual( + JSON.stringify(rows[0][0].value), + JSON.stringify(expected), + ); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'float64', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'float64', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + + it('GOOGLE_STANDARD_SQL should bind Infinity', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: Infinity, + }, + }; + await float64Query(DATABASE, query, 'Infinity'); + }); + + it('POSTGRESQL should bind Infinity', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: Infinity, + }, + }; + await float64Query(PG_DATABASE, query, 'Infinity'); + }); + + it('GOOGLE_STANDARD_SQL should bind -Infinity', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: -Infinity, + }, + }; + await float64Query(DATABASE, query, '-Infinity'); + }); + + it('POSTGRESQL should bind -Infinity', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: -Infinity, + }, + }; + await float64Query(PG_DATABASE, query, '-Infinity'); + }); + + it('GOOGLE_STANDARD_SQL should bind NaN', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: NaN, + }, + }; + await float64Query(DATABASE, query, 'NaN'); + }); + + it('POSTGRESQL should bind NaN', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: NaN, + }, + }; + await float64Query(PG_DATABASE, query, 'NaN'); + }); + + it('GOOGLE_STANDARD_SQL should bind an array of Infinity and NaN', async () => { + const values = [Infinity, -Infinity, NaN]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + }; + + const [rows] = await DATABASE.run(query); + + const expected = values.map(val => { + return isNumber(val) ? {value: val + ''} : val; + }); + + assert.strictEqual( + JSON.stringify(rows[0][0].value), + JSON.stringify(expected), + ); + }); + }); + + describe('string', () => { + const stringQuery = async (database, query, value) => { + const [rows] = await database.run(query); + assert.strictEqual(rows[0][0].value, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: 'abc', + }, + }; + await stringQuery(DATABASE, query, 'abc'); + }); + + it('POSTGRESQL should bind the value', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: 'abc', + }, + }; + await stringQuery(PG_DATABASE, query, 'abc'); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'string', + }, + }; + await stringQuery(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'string', + }, + }; + await stringQuery(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = ['a', 'b', 'c', null]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows[0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'string', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'string', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + }); + + describe('bytes', () => { + const bytesQuery = async (database, query, value) => { + const [rows] = await database.run(query); + assert.deepStrictEqual(rows[0][0].value, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: Buffer.from('abc'), + }, + }; + await bytesQuery(DATABASE, query, Buffer.from('abc')); + }); + + it('POSTGRESQL should bind the value', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: Buffer.from('abc'), + }, + }; + await bytesQuery(PG_DATABASE, query, Buffer.from('abc')); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'bytes', + }, + }; + await bytesQuery(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'bytes', + }, + }; + await bytesQuery(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [Buffer.from('a'), Buffer.from('b'), null]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows[0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'bytes', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'bytes', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + }); + + describe('timestamp', () => { + const timestampQuery = async (database, query, value) => { + const [rows] = await database.run(query); + assert.deepStrictEqual(rows[0][0].value, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value', async () => { + const timestamp = Spanner.timestamp(); + const query = { + sql: 'SELECT @v', + params: { + v: timestamp, + }, + }; + await timestampQuery(DATABASE, query, timestamp); + }); + + it('POSTGRESQL should bind the value', async () => { + const timestamp = Spanner.timestamp(); + const query = { + sql: 'SELECT $1', + params: { + p1: timestamp, + }, + }; + await timestampQuery(PG_DATABASE, query, timestamp); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'timestamp', + }, + }; + await timestampQuery(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'timestamp', + }, + }; + await timestampQuery(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [ + Spanner.timestamp(), + Spanner.timestamp('3-3-1999'), + null, + ]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows[0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'timestamp', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'timestamp', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + }); + + describe('date', () => { + const dateQuery = async (database, query, value) => { + const [rows] = await database.run(query); + let returnedDate = Spanner.date(rows[0][0].value); + if (value === null) { + returnedDate = rows[0][0].value; + } + assert.deepStrictEqual(returnedDate, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value', async () => { + const date = Spanner.date(); + const query = { + sql: 'SELECT @v', + params: { + v: date, + }, + }; + await dateQuery(DATABASE, query, date); + }); + + it('POSTGRESQL should bind the value', async () => { + const date = Spanner.date(); + const query = { + sql: 'SELECT $1', + params: { + p1: date, + }, + }; + await dateQuery(PG_DATABASE, query, date); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'date', + }, + }; + await dateQuery(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'date', + }, + }; + await dateQuery(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [Spanner.date(), Spanner.date('3-3-1999'), null]; + + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + }; + + const [rows] = await DATABASE.run(query); + const returnedValues = rows[0][0].value.map(val => { + return isNull(val) ? val : Spanner.date(val); + }); + + assert.deepStrictEqual(returnedValues, values); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'date', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'date', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + }); + + describe('structs', () => { + it('GOOGLE_STANDARD_SQL should bind a simple struct', async () => { + const query = { + sql: 'SELECT @structParam.userf, @p4', + params: { + structParam: Spanner.struct({ + userf: 'bob', + threadf: Spanner.int(1), + }), + p4: Spanner.int(10), + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0].toJSON(); + assert.strictEqual(row.userf, 'bob'); + }); + + it('GOOGLE_STANDARD_SQL should bind null structs', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @structParam.userf is NULL', + params: { + structParam: null, + }, + types: { + structParam: { + type: 'struct', + fields: [ + { + name: 'userf', + type: 'string', + }, + { + name: 'threadf', + type: 'int64', + }, + ], + }, + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows![0]; + assert.strictEqual(row[0].value, true); + }); + + it('GOOGLE_STANDARD_SQL should bind nested structs', async () => { + const query = { + sql: 'SELECT @structParam.structf.nestedf', + params: { + structParam: Spanner.struct({ + structf: Spanner.struct({ + nestedf: 'bob', + }), + }), + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0].toJSON(); + assert.strictEqual(row.nestedf, 'bob'); + }); + + it('GOOGLE_STANDARD_SQL should bind null nested structs', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @structParam.structf.nestedf', + params: { + structParam: null, + }, + types: { + structParam: { + type: 'struct', + fields: [ + { + name: 'structf', + type: 'struct', + fields: [ + { + name: 'nestedf', + type: 'string', + }, + ], + }, + ], + }, + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows![0].toJSON(); + assert.strictEqual(row.nestedf, null); + }); + + it('GOOGLE_STANDARD_SQL should bind empty structs', async () => { + const query = { + sql: 'SELECT @structParam IS NULL', + params: { + structParam: Spanner.struct(), + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0]; + assert.strictEqual(row[0].value, false); + }); + + it('GOOGLE_STANDARD_SQL should bind null structs with no fields', async () => { + const query = { + sql: 'SELECT @structParam IS NULL', + params: { + structParam: null, + }, + types: { + structParam: 'struct', + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0]; + assert.strictEqual(row[0].value, true); + }); + + it('GOOGLE_STANDARD_SQL should bind structs with null fields', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @structParam.f1', + params: { + structParam: Spanner.struct({ + f1: null, + }), + }, + types: { + structParam: { + type: 'struct', + fields: [ + { + name: 'f1', + type: 'int64', + }, + ], + }, + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows![0].toJSON(); + assert.strictEqual(row.f1, null); + }); + + it('GOOGLE_STANDARD_SQL should bind structs with duplicate fields', async () => { + const query = { + sql: 'SELECT @structParam=STRUCT(10, 11)', + params: { + structParam: Spanner.struct([ + { + name: 'f1', + value: Spanner.int(10), + }, + { + name: 'f1', + value: Spanner.int(11), + }, + ]), + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0]; + assert.strictEqual(row[0].value, true); + }); + + it('GOOGLE_STANDARD_SQL should bind structs with missing field names', async () => { + const query = { + sql: 'SELECT @structParam=STRUCT(5)', + params: { + structParam: Spanner.struct([{value: Spanner.int(5)}]), + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0]; + assert.strictEqual(row[0].value, true); + }); + + it('GOOGLE_STANDARD_SQL should allow equality checks', async () => { + const query = { + sql: 'SELECT @structParam=STRUCT(1, "bob")', + params: { + structParam: Spanner.struct({ + threadf: Spanner.int(1), + userf: 'bob', + }), + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0]; + assert.strictEqual(row[0].value, true); + }); + + it('GOOGLE_STANDARD_SQL should allow nullness checks', async () => { + const query = { + sql: 'SELECT @structParam IS NULL', + params: { + structParam: Spanner.struct({ + userf: 'bob', + threadf: Spanner.int(1), + }), + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0]; + assert.strictEqual(row[0].value, false); + }); + + it('GOOGLE_STANDARD_SQL should allow an array of non-null structs', async () => { + const query = { + sql: 'SELECT a.threadid FROM UNNEST(@arraysf) a', + params: { + arraysf: [ + Spanner.struct({ + threadid: Spanner.int(12), + }), + Spanner.struct({ + threadid: Spanner.int(13), + }), + ], + }, + }; + let rows; + [rows] = await DATABASE.run(query); + rows = rows.map(row => row.toJSON()); + + assert.strictEqual(rows.length, 2); + assert.strictEqual(rows[0].threadid, 12); + assert.strictEqual(rows[1].threadid, 13); + }); + + it('GOOGLE_STANDARD_SQL should allow an array of structs with null fields', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT a.threadid FROM UNNEST(@structParam.arraysf) a', + params: { + structParam: Spanner.struct({ + intf: Spanner.int(10), + arraysf: null, + }), + }, + types: { + structParam: { + type: 'struct', + fields: [ + { + name: 'intf', + type: 'int64', + }, + { + name: 'arraysf', + type: 'array', + child: { + type: 'struct', + fields: [ + { + name: 'threadid', + type: 'int64', + }, + ], + }, + }, + ], + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.strictEqual(rows!.length, 0); + }); + + it('GOOGLE_STANDARD_SQL should allow a null array of structs', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT a.threadid FROM UNNEST(@structParamArray) a', + params: { + structParamArray: null, + }, + types: { + structParamArray: { + type: 'array', + child: { + type: 'struct', + fields: [ + { + name: 'threadid', + type: 'int64', + }, + ], + }, + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.strictEqual(rows!.length, 0); + }); + }); + + describe('interval', () => { + before(function () { + // TODO: Remove this check once Interval is supported in emulator + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + }); + + const intervalQuery = async (database, query, value) => { + const [rows] = await database.run(query); + const queriedValue = rows[0][0].value; + assert.deepStrictEqual(queriedValue, value); + }; + + it('GOOGLE_STANDARD_SQL should bind the value when param type interval is used', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: new Interval(19, 768, BigInt('123456789123')), + }, + types: { + v: 'interval', + }, + }; + await intervalQuery( + DATABASE, + query, + new Interval(19, 768, BigInt('123456789123')), + ); + }); + + it('GOOGLE_STANDARD_SQL should bind the value when spanner.interval is used', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: Spanner.interval(19, 768, BigInt('123456789123')), + }, + }; + await intervalQuery( + DATABASE, + query, + new Interval(19, 768, BigInt('123456789123')), + ); + }); + + it('POSTGRESQL should bind the value when param type interval is used', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: new Interval(19, 768, BigInt('123456789123')), + }, + types: { + p1: 'interval', + }, + }; + await intervalQuery( + PG_DATABASE, + query, + new Interval(19, 768, BigInt('123456789123')), + ); + }); + + it('POSTGRESQL should bind the value when Spanner.interval is used', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: Spanner.interval(-19, -768, BigInt('123456789123')), + }, + }; + await intervalQuery( + PG_DATABASE, + query, + new Interval(-19, -768, BigInt('123456789123')), + ); + }); + + it('GOOGLE_STANDARD_SQL should allow for null values', async () => { + const query = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: 'interval', + }, + }; + await intervalQuery(DATABASE, query, null); + }); + + it('POSTGRESQL should allow for null values', async () => { + const query = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: 'interval', + }, + }; + await intervalQuery(PG_DATABASE, query, null); + }); + + it('GOOGLE_STANDARD_SQL should bind arrays', async () => { + const values = [ + null, + new Interval(100, 200, BigInt('123456789123')), + Interval.ZERO, + new Interval(-100, -200, BigInt('-123456789123')), + null, + ]; + const query = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'interval', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + const expected = values; + for (let i = 0; i < rows[0][0].value.length; i++) { + assert.deepStrictEqual(rows[0][0].value[i], expected[i]); + } + }); + + it('GOOGLE_STANDARD_SQL should handle interval passed as string', async () => { + const query = { + sql: "SELECT INTERVAL '1' DAY + @v", + params: { + v: new Interval(100, 200, BigInt('123456789123')).toISO8601(), + }, + types: { + v: 'interval', + }, + }; + await intervalQuery( + DATABASE, + query, + new Interval(100, 201, BigInt('123456789123')), + ); + }); + + it('GOOGLE_STANDARD_SQL should bind empty arrays', async () => { + const values = []; + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: values, + }, + types: { + v: { + type: 'array', + child: 'interval', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('GOOGLE_STANDARD_SQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT @v', + params: { + v: null, + }, + types: { + v: { + type: 'array', + child: 'interval', + }, + }, + }; + + const [rows] = await DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + + it('POSTGRESQL should bind arrays', async () => { + const values = [ + null, + new Interval(100, 200, BigInt('123456789123')), + Interval.ZERO, + new Interval(-100, -200, BigInt('-123456789123')), + null, + ]; + const query = { + sql: 'SELECT $1', + params: { + p1: values, + }, + types: { + p1: { + type: 'array', + child: 'interval', + }, + }, + }; + + const [rows] = await PG_DATABASE.run(query); + const expected = values; + for (let i = 0; i < rows[0][0].value.length; i++) { + assert.deepStrictEqual(rows[0][0].value[i], expected[i]); + } + }); + + it('POSTGRESQL should bind empty arrays', async () => { + const values = []; + const query: ExecuteSqlRequest = { + sql: 'SELECT $1', + params: { + p1: values, + }, + types: { + p1: { + type: 'array', + child: 'interval', + }, + }, + }; + + const [rows] = await PG_DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, values); + }); + + it('POSTGRESQL should bind null arrays', async () => { + const query: ExecuteSqlRequest = { + sql: 'SELECT $1', + params: { + p1: null, + }, + types: { + p1: { + type: 'array', + child: 'interval', + }, + }, + }; + + const [rows] = await PG_DATABASE.run(query); + assert.deepStrictEqual(rows![0][0].value, null); + }); + }); + }); + + describe('large reads', () => { + const TABLE_NAME = 'LargeReads'; + let googleSqlTable; + let postgreSqlTable; + + const googleSqlExpectedRow = { + Key: generateName('key'), + StringValue: string(), + StringArray: [string(), string(), string(), string()], + BytesValue: bytes(), + BytesArray: [bytes(), bytes(), bytes(), bytes()], + }; + + const postgreSqlExpectedRow = { + Key: generateName('key'), + StringValue: string(), + BytesValue: bytes(), + }; + + function string() { + const offset = Math.floor(Math.random() * 500); + + return new Array(25000 + offset) + .fill('The quick brown fox jumps over the lazy dog.') + .join('\n'); + } + + function bytes() { + const offset = Math.floor(Math.random() * 2048); + + return crypto.randomBytes(1024 * 1024 + offset); + } + + function base64ToBuffer(bytes) { + return Buffer.from(bytes, 'base64'); + } + + before(async () => { + googleSqlTable = DATABASE.table(TABLE_NAME); + postgreSqlTable = PG_DATABASE.table(TABLE_NAME); + const googleSqlCreateTable = await googleSqlTable.create( + ` + CREATE TABLE ${TABLE_NAME} ( + Key STRING(MAX) NOT NULL, + StringValue STRING(MAX), + StringArray ARRAY, + BytesValue BYTES(MAX), + BytesArray ARRAY + ) PRIMARY KEY (Key)`, + GAX_OPTIONS, + ); + await onPromiseOperationComplete(googleSqlCreateTable); + await googleSqlTable.insert(googleSqlExpectedRow); + + const postgreSqlCreateTable = await postgreSqlTable.create( + `CREATE TABLE ${TABLE_NAME} ( + "Key" VARCHAR NOT NULL PRIMARY KEY, + "StringValue" VARCHAR, + "BytesValue" BYTEA + )`, + GAX_OPTIONS, + ); + await onPromiseOperationComplete(postgreSqlCreateTable); + await postgreSqlTable.insert(postgreSqlExpectedRow); + }); + + it('GOOGLE_STANDARD_SQL should read large datasets', async () => { + const [rows] = await googleSqlTable.read({ + keys: [googleSqlExpectedRow.Key], + columns: [ + 'Key', + 'StringValue', + 'StringArray', + 'BytesValue', + 'BytesArray', + ], + }); + + const row = rows[0].toJSON(); + + assert.strictEqual(row.Key, googleSqlExpectedRow.Key); + assert.strictEqual(row.StringValue, googleSqlExpectedRow.StringValue); + assert.deepStrictEqual( + row.StringArray, + googleSqlExpectedRow.StringArray, + ); + + row.BytesValue = base64ToBuffer(row.BytesValue); + row.BytesArray = row.BytesArray.map(base64ToBuffer); + + assert.deepStrictEqual( + row.BytesValue, + googleSqlExpectedRow.BytesValue, + ); + assert.deepStrictEqual( + row.BytesArray, + googleSqlExpectedRow.BytesArray, + ); + }); + + it('POSTGRESQL should read large datasets', async () => { + const [rows] = await postgreSqlTable.read({ + keys: [postgreSqlExpectedRow.Key], + columns: ['Key', 'StringValue', 'BytesValue'], + }); + + const row = rows[0].toJSON(); + + assert.strictEqual(row.Key, postgreSqlExpectedRow.Key); + assert.strictEqual( + row.StringValue, + postgreSqlExpectedRow.StringValue, + ); + + row.BytesValue = base64ToBuffer(row.BytesValue); + assert.deepStrictEqual( + row.BytesValue, + postgreSqlExpectedRow.BytesValue, + ); + }); + + it('GOOGLE_STANDARD_SQL should query large datasets', async () => { + const query = { + sql: 'SELECT * FROM ' + googleSqlTable.name + ' WHERE Key = @key', + params: { + key: googleSqlExpectedRow.Key, + }, + }; + + const [rows] = await DATABASE.run(query); + const row = rows[0].toJSON(); + + assert.strictEqual(row.Key, googleSqlExpectedRow.Key); + assert.strictEqual(row.StringValue, googleSqlExpectedRow.StringValue); + assert.deepStrictEqual( + row.StringArray, + googleSqlExpectedRow.StringArray, + ); + + row.BytesValue = base64ToBuffer(row.BytesValue); + row.BytesArray = row.BytesArray.map(base64ToBuffer); + + assert.deepStrictEqual( + row.BytesValue, + googleSqlExpectedRow.BytesValue, + ); + assert.deepStrictEqual( + row.BytesArray, + googleSqlExpectedRow.BytesArray, + ); + }); + + it('POSTGRESQL should query large datasets', async () => { + const query = { + sql: 'SELECT * FROM ' + postgreSqlTable.name + ' WHERE "Key" = $1', + params: { + p1: postgreSqlExpectedRow.Key, + }, + }; + + const [rows] = await PG_DATABASE.run(query); + const row = rows[0].toJSON(); + + assert.strictEqual(row.Key, postgreSqlExpectedRow.Key); + assert.strictEqual( + row.StringValue, + postgreSqlExpectedRow.StringValue, + ); + + row.BytesValue = base64ToBuffer(row.BytesValue); + assert.deepStrictEqual( + row.BytesValue, + postgreSqlExpectedRow.BytesValue, + ); + }); + }); + }); + + describe('upsert', () => { + const ROW = { + SingerId: generateName('id'), + Name: generateName('name'), + }; + + const updateRow = async table => { + const row = { + SingerId: ROW.SingerId, + Name: generateName('name'), + }; + + await table.insert(row); + await table.upsert(ROW); + const [rows] = await table.read({ + keys: [ROW.SingerId], + columns: Object.keys(ROW), + }); + assert.deepStrictEqual(rows![0].toJSON(), ROW); + }; + + it('GOOGLE_STANDARD_SQL should update a row', async () => { + await updateRow(googleSqlTable); + }); + + it('POSTGRESQL should update a row', async () => { + await updateRow(postgreSqlTable); + }); + + const insertRow = async table => { + await table.upsert(ROW); + const [rows] = await table.read({ + keys: [ROW.SingerId], + columns: Object.keys(ROW), + }); + assert.deepStrictEqual(rows![0].toJSON(), ROW); + }; + + it('GOOGLE_STANDARD_SQL should update a row', async () => { + await insertRow(googleSqlTable); + }); + + it('POSTGRESQL should update a row', async () => { + await insertRow(postgreSqlTable); + }); + }); + + describe('read', () => { + const TABLE_NAME = 'ReadTestTable'; + let googleSqlTable; + let postgreSqlTable; + + const ALL_COLUMNS = ['Key', 'StringValue']; + + before(async () => { + googleSqlTable = DATABASE.table(TABLE_NAME); + postgreSqlTable = PG_DATABASE.table(TABLE_NAME); + const googleSqlCreateTable = await googleSqlTable.create( + ` + CREATE TABLE ${TABLE_NAME} ( + Key STRING(MAX) NOT NULL, + StringValue STRING(MAX) + ) PRIMARY KEY (Key)`, + GAX_OPTIONS, + ); + await onPromiseOperationComplete(googleSqlCreateTable); + const googleSqlCreateIndex = await DATABASE.updateSchema(` + CREATE INDEX ReadByValue ON ${TABLE_NAME}(StringValue)`); + await onPromiseOperationComplete(googleSqlCreateIndex); + + const data: Array<{}> = []; + + for (let i = 0; i < 15; ++i) { + data.push({ + Key: 'k' + i, + StringValue: 'v' + i, + }); + } + await googleSqlTable.insert(data); + + const postgreSqlCreateTable = await postgreSqlTable.create( + `CREATE TABLE ${TABLE_NAME} ( + "Key" VARCHAR NOT NULL PRIMARY KEY, + "StringValue" VARCHAR + )`, + GAX_OPTIONS, + ); + await onPromiseOperationComplete(postgreSqlCreateTable); + const postgreSqlCreateIndex = await PG_DATABASE.updateSchema(` + CREATE INDEX ReadByValue ON ${TABLE_NAME}("StringValue")`); + await onPromiseOperationComplete(postgreSqlCreateIndex); + await postgreSqlTable.insert(data); + }); + + // all of these tests require testing with and without an index, + // to cut back on duplication, the core sections of the tests have been + // turned into configurations + [ + { + test: 'should perform an empty read', + query: { + ranges: [ + { + startClosed: 'k99', + endOpen: 'z', + }, + ], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 0); + }, + }, + { + test: 'should read a single key', + query: { + keys: ['k1'], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 1); + + const row = rows[0].toJSON(); + + assert.strictEqual(row.Key, 'k1'); + assert.strictEqual(row.StringValue, 'v1'); + }, + }, + { + test: 'should read a non-existant single key', + query: { + keys: ['k999'], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 0); + }, + }, + { + test: 'should read using partial keys', + query: { + ranges: [ + { + startClosed: 'k7', + endClosed: null, + }, + ], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + + assert.strictEqual(rows.length, 3); + + rows = rows.map(row => { + return row.toJSON(); + }); + + assert.strictEqual(rows[0].Key, 'k7'); + assert.strictEqual(rows[1].Key, 'k8'); + assert.strictEqual(rows[2].Key, 'k9'); + }, + }, + { + test: 'should read using an open-open range', + query: { + ranges: [ + { + startOpen: 'k3', + endOpen: 'k5', + }, + ], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 1); + + const row = rows[0].toJSON(); + + assert.strictEqual(row.Key, 'k4'); + }, + }, + { + test: 'should read using an open-closed range', + query: { + ranges: [ + { + startOpen: 'k3', + endClosed: 'k5', + }, + ], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 2); + + rows = rows.map(row => { + return row.toJSON(); + }); + + assert.strictEqual(rows[0].Key, 'k4'); + assert.strictEqual(rows[1].Key, 'k5'); + }, + }, + { + test: 'should read using a closed-closed range', + query: { + ranges: [ + { + startClosed: 'k3', + endClosed: 'k5', + }, + ], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 3); + + rows = rows.map(row => { + return row.toJSON(); + }); + + assert.strictEqual(rows[0].Key, 'k3'); + assert.strictEqual(rows[1].Key, 'k4'); + assert.strictEqual(rows[2].Key, 'k5'); + }, + }, + { + test: 'should read using a closed-open range', + query: { + ranges: [ + { + startClosed: 'k3', + endOpen: 'k5', + }, + ], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 2); + + rows = rows.map(row => { + return row.toJSON(); + }); + + assert.strictEqual(rows[0].Key, 'k3'); + assert.strictEqual(rows[1].Key, 'k4'); + }, + }, + { + test: 'should accept a limit', + query: { + ranges: [ + { + startClosed: 'k3', + endClosed: 'k7', + }, + ], + columns: ALL_COLUMNS, + limit: 2, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 2); + }, + }, + { + test: 'should ignore limits of 0', + query: { + ranges: [ + { + startClosed: 'k3', + endClosed: 'k7', + }, + ], + columns: ALL_COLUMNS, + limit: 0, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 5); + }, + }, + { + test: 'should read using point keys', + query: { + keys: ['k3', 'k5', 'k7'], + columns: ALL_COLUMNS, + }, + assertions(err, rows) { + assert.ifError(err); + assert.strictEqual(rows.length, 3); + + rows = rows.map(row => { + return row.toJSON(); + }); + + assert.strictEqual(rows[0].Key, 'k3'); + assert.strictEqual(rows[1].Key, 'k5'); + assert.strictEqual(rows[2].Key, 'k7'); + }, + }, + ].forEach(test => { + // test normally + it(`GOOGLE_STANDARD_SQL ${test.test}`, async () => { + let rows; + try { + [rows] = await googleSqlTable.read(test.query as ReadRequest); + } catch (err) { + test.assertions(err, rows); + } + }); + + it(`POSTGRESQL ${test.test}`, async () => { + let rows; + try { + await postgreSqlTable.read(test.query as ReadRequest); + } catch (err) { + test.assertions(err, rows); + } + }); + + // test using an index + const readUsingIndex = async (test, table) => { + const query = extend( + { + index: 'ReadByValue', + }, + test.query, + ); + + if (query.keys) { + query.keys = query.keys.map(key => { + return key.replace('k', 'v'); + }); + } + + if (query.ranges) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + query.ranges = (query as any).ranges.map(range_ => { + const range = extend({}, range_); + Object.keys(range).forEach(bound => { + if (range[bound]) { + range[bound] = range[bound].replace('k', 'v'); + } + }); + return range; + }); + } + + table.read(query as ReadRequest, (err, rows) => { + test.assertions(err, rows); + }); + }; + + it(`GOOGLE_STANDARD_SQL ${test.test}` + ' with an index', async () => { + await readUsingIndex(test, googleSqlTable); + }); + + it(`POSTGRESQL ${test.test}` + ' with an index', async () => { + await readUsingIndex(test, postgreSqlTable); + }); + }); + + it('should read over invalid database fails', async () => { + const database = instance.database(generateName('invalid')); + const table = database.table(TABLE_NAME); + + const query = { + keys: ['k1'], + columns: ALL_COLUMNS, + }; + + try { + await table.read(query); + } catch (err: any) { + assert.strictEqual(err.code, 5); + } + + await database.close(); + }); + + const readInvalidTable = async database => { + const table = database.table('ReadTestTablezzz'); + + const query = { + keys: ['k1'], + columns: ALL_COLUMNS, + }; + + try { + await table.read(query); + } catch (err: any) { + assert.strictEqual(err.code, 5); + } + }; + + it('GOOGLE_STANDARD_SQL should read over invalid table fails', async () => { + await readInvalidTable(DATABASE); + }); + + it('POSTGRESQL should read over invalid table fails', async () => { + await readInvalidTable(PG_DATABASE); + }); + + const readInvalidColumn = async table => { + const query = { + keys: ['k1'], + columns: ['ohnoes'], + }; + + try { + table.read(query); + } catch (err: any) { + assert.strictEqual(err.code, 5); + } + }; + + it('GOOGLE_STANDARD_SQL should read over invalid column fails', async () => { + await readInvalidColumn(googleSqlTable); + }); + + it('POSTGRESQL should read over invalid column fails', async () => { + await readInvalidColumn(postgreSqlTable); + }); + + const failDeadlineExceed = async table => { + const query = { + keys: ['k1'], + columns: ALL_COLUMNS, + gaxOptions: { + timeout: 0.1, + }, + }; + + try { + await table.read(query); + } catch (err: any) { + assert.strictEqual(err.code, 4); + } + }; + + it('GOOGLE_STANDARD_SQL should fail if deadline exceeds', async function () { + // This test case somehow causes the emulator to return a RESOURCE_EXHAUSTED + // error for this or following gRPC calls. + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await failDeadlineExceed(googleSqlTable); + }); + + it('POSTGRESQL should fail if deadline exceeds', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await failDeadlineExceed(postgreSqlTable); + }); + }); + }); + + describe('Multiplexed Sessions', () => { + let table; + + before(() => { + table = DATABASE.table(TABLE_NAME); + }); + + it('should insert and query a row', async () => { + const id = generateName('id'); + const name = generateName('name'); + + await table.insert({ + SingerId: id, + Name: name, + }); + + const [rows] = await DATABASE.run(`SELECT * FROM ${TABLE_NAME}`); + assert.ok( + rows!.some( + r => + JSON.stringify(r.toJSON()) === + JSON.stringify({SingerId: id, Name: name}), + ), + ); + }); + + it('should insert and query multiple rows', async () => { + const id1 = generateName('id1'); + const name1 = generateName('name'); + + const id2 = generateName('id2'); + const name2 = generateName('name'); + + await table.insert([ + { + SingerId: id1, + Name: name1, + }, + { + SingerId: id2, + Name: name2, + }, + ]); + const [rows] = await DATABASE.run( + `SELECT * FROM ${TABLE_NAME} ORDER BY SingerId`, + ); + // We just want the two most recent ones. + rows!.splice(0, rows!.length - 2); + + const rowJson = rows!.map(x => x.toJSON()); + + assert.deepStrictEqual(rowJson, [ + { + SingerId: id1, + Name: name1, + }, + { + SingerId: id2, + Name: name2, + }, + ]); + }); + + it('should read rows as a stream', done => { + const id = generateName('id'); + const name = generateName('name'); + + table.insert( + { + SingerId: id, + Name: name, + }, + err => { + assert.ifError(err); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let rows: any[] = []; + + table + .createReadStream({ + keys: [id], + columns: ['SingerId', 'name'], + }) + .on('error', done) + .on('data', row => { + rows.push(row); + }) + .on('end', () => { + rows = rows.map(x => x.toJSON()); + + assert.deepStrictEqual(rows, [ + { + SingerId: id, + Name: name, + }, + ]); + + done(); + }); + }, + ); + }); + + it('should read rows', async () => { + const id = generateName('id'); + const name = generateName('name'); + + await table.insert({SingerId: id, Name: name}); + let rows; + [rows] = await table.read({keys: [id], columns: ['SingerId', 'Name']}); + rows = rows!.map(x => x.toJSON()); + + assert.deepStrictEqual(rows, [ + { + SingerId: id, + Name: name, + }, + ]); + }); + }); + + describe('Transactions', () => { + const TABLE_NAME = 'TxnTable'; + let googleSqlTable; + let postgreSqlTable; + + const googleSqlSchema = ` + CREATE TABLE ${TABLE_NAME} ( + Key STRING(MAX) NOT NULL, + StringValue STRING(MAX), + NumberValue INT64 + ) PRIMARY KEY (Key) + `; + const postgreSqlSchema = ` + CREATE TABLE ${TABLE_NAME} ( + "Key" VARCHAR NOT NULL PRIMARY KEY, + "StringValue" VARCHAR , + "NumberValue" BIGINT + )`; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const googleSqlRecords = []; + const postgreSqlRecords = []; + + before(async () => { + googleSqlTable = DATABASE.table(TABLE_NAME); + postgreSqlTable = PG_DATABASE.table(TABLE_NAME); + const insertRecords = async function (table, records) { + for (let i = 0; i < 5; i++) { + const entry = {Key: `k${i}`, StringValue: `v${i}`}; + + const [{commitTimestamp}] = await table.insert(entry); + const record = Object.assign(entry, { + commitTimestamp, + localTimestamp: Date.now(), + }); + + records.push(record); + await wait(1000); + } + }; + await onPromiseOperationComplete( + await googleSqlTable.create(googleSqlSchema, GAX_OPTIONS), + ); + await insertRecords(googleSqlTable, googleSqlRecords); + + await onPromiseOperationComplete( + await postgreSqlTable.create(postgreSqlSchema, GAX_OPTIONS), + ); + await insertRecords(postgreSqlTable, postgreSqlRecords); + }); + + describe('snapshots', () => { + const readOnlyTransaction = async (database, records) => { + const options = { + strong: true, + }; + + const [transaction] = await database.getSnapshot(options); + const [rows] = await transaction!.run(`SELECT * FROM ${TABLE_NAME}`); + assert.strictEqual(rows.length, records.length); + transaction!.end(); + }; + + it('GOOGLE_STANDARD_SQL should run a read only transaction', async () => { + await readOnlyTransaction(DATABASE, googleSqlRecords); + }); + + it('POSTGRESQL should run a read only transaction', async () => { + await readOnlyTransaction(PG_DATABASE, postgreSqlRecords); + }); + + const readKeysFromTable = async (database, table, records) => { + const [transaction] = await database.getSnapshot(); + const query = { + ranges: [ + { + startClosed: 'k0', + endClosed: 'k4', + }, + ], + columns: ['Key'], + } as {} as ReadRequest; + + const [rows] = await transaction!.read(table.name, query); + assert.strictEqual(rows!.length, records.length); + transaction!.end(); + }; + + it('GOOGLE_STANDARD_SQL should read keys from a table', async () => { + await readKeysFromTable(DATABASE, googleSqlTable, googleSqlRecords); + }); + + it('POSTGRESQL should read keys from a table', async () => { + await readKeysFromTable( + PG_DATABASE, + postgreSqlTable, + postgreSqlRecords, + ); + }); + + const acceptReadTimestamp = async (database, records) => { + const options = { + readTimestamp: records[0].commitTimestamp, + }; + + const [transaction] = await database.getSnapshot(options); + const [rows] = await transaction!.run(`SELECT * FROM ${TABLE_NAME}`); + assert.strictEqual(rows.length, 1); + + const row = rows[0].toJSON(); + + assert.strictEqual(row.Key, records[0].Key); + assert.strictEqual(row.StringValue, records[0].StringValue); + + transaction!.end(); + }; + + it('GOOGLE_STANDARD_SQL should accept a read timestamp', async () => { + await acceptReadTimestamp(DATABASE, googleSqlRecords); + }); + + it('POSTGRESQL should accept a read timestamp', async () => { + await acceptReadTimestamp(PG_DATABASE, postgreSqlRecords); + }); + + const acceptMinTimestamp = async (database, records) => { + const query = 'SELECT * FROM ' + TABLE_NAME; + + const options = { + minReadTimestamp: new PreciseDate(), + } as TimestampBounds; + + // minTimestamp can only be used in single use transactions + // so we can't use database.getSnapshot here + const [rows] = await database.run(query, options); + assert.strictEqual(rows!.length, records.length); + }; + + it('GOOGLE_STANDARD_SQL should accept a min timestamp', async () => { + await acceptMinTimestamp(DATABASE, googleSqlRecords); + }); + + it('POSTGRESQL should accept a min timestamp', async () => { + await acceptMinTimestamp(PG_DATABASE, postgreSqlRecords); + }); + + const acceptExactStaleness = async (database, records, query) => { + const options = { + exactStaleness: Date.now() - records[1].localTimestamp, + }; + + const [transaction] = await database.getSnapshot(options); + const [rows] = await transaction!.run(query); + assert.strictEqual(rows.length, 2); + + const rowJson = rows.map(x => x.toJSON()); + + assert.strictEqual(rowJson[0].Key, 'k0'); + assert.strictEqual(rowJson[0].StringValue, 'v0'); + assert.strictEqual(rowJson[1].Key, 'k1'); + assert.strictEqual(rowJson[1].StringValue, 'v1'); + + transaction!.end(); + }; + + it('GOOGLE_STANDARD_SQL should accept an exact staleness', async () => { + await acceptExactStaleness( + DATABASE, + googleSqlRecords, + `SELECT * FROM ${TABLE_NAME} ORDER BY Key`, + ); + }); + + it('POSTGRESQL should accept an exact staleness', async () => { + await acceptExactStaleness( + PG_DATABASE, + postgreSqlRecords, + `SELECT * FROM ${TABLE_NAME} ORDER BY "Key"`, + ); + }); + + const acceptMaxStaleness = (database, records) => { + const query = 'SELECT * FROM TxnTable'; + + const options = { + maxStaleness: 1, + }; + + // maxStaleness can only be used in single use transactions + // so we can't use database.getSnapshot here + database.run(query, options, (err, rows) => { + assert.ifError(err); + assert.strictEqual(rows!.length, records.length); + }); + }; + + it('GOOGLE_STANDARD_SQL should accept a max staleness', async () => { + await acceptMaxStaleness(DATABASE, googleSqlRecords); + }); + + it('POSTGRESQL should accept a max staleness', async () => { + await acceptMaxStaleness(PG_DATABASE, postgreSqlRecords); + }); + + const strongReadWithConcurrentUpdates = async ( + database, + table, + records, + ) => { + const options = { + strong: true, + }; + + const [transaction] = await database.getSnapshot(options); + const query = 'SELECT * FROM TxnTable'; + + const [rows] = await transaction!.run(query); + assert.strictEqual(rows.length, records.length); + + await table.update({Key: 'k4', StringValue: 'v44'}); + const [rows_] = await transaction!.run(query); + const row = rows_!.pop()!.toJSON(); + assert.strictEqual(row.StringValue, 'v4'); + + transaction!.end(); + }; + + it('GOOGLE_STANDARD_SQL should do a strong read with concurrent updates', async () => { + await strongReadWithConcurrentUpdates( + DATABASE, + googleSqlTable, + googleSqlRecords, + ); + }); + + it('POSTGRESQL should do a strong read with concurrent updates', async () => { + await strongReadWithConcurrentUpdates( + PG_DATABASE, + postgreSqlTable, + postgreSqlRecords, + ); + }); + + const exactReadWithConcurrentUpdates = async ( + database, + table, + records, + ) => { + const options = { + readTimestamp: records[records.length - 1].commitTimestamp, + }; + + const [transaction] = await database.getSnapshot(options); + const query = 'SELECT * FROM TxnTable'; + + const [rows] = await transaction!.run(query); + const originalRows = extend(true, {}, rows); + + // Make arbitrary update. + await table.update({ + Key: rows[0].toJSON().Key, + StringValue: 'overridden value', + }); + let rows_; + [rows_] = await transaction!.run(query); + rows_ = extend(true, {}, rows_); + + assert.deepStrictEqual(rows_, originalRows); + + transaction!.end(); + }; + + it('GOOGLE_STANDARD_SQL should do a strong read with concurrent updates', async () => { + await exactReadWithConcurrentUpdates( + DATABASE, + googleSqlTable, + googleSqlRecords, + ); + }); + + it('POSTGRESQL should do a strong read with concurrent updates', async () => { + await exactReadWithConcurrentUpdates( + PG_DATABASE, + postgreSqlTable, + postgreSqlRecords, + ); + }); + + const readWithStalenessAndConcurrentUpdates = async ( + database, + table, + records, + ) => { + const options = { + exactStaleness: Date.now() - records[0].localTimestamp, + }; + + const [transaction] = await database.getSnapshot(options); + const query = 'SELECT * FROM TxnTable'; + + const [rows1] = await transaction!.run(query); + assert.strictEqual(rows1.length, 1); + + await table.update({Key: 'k4', StringValue: 'overridden value'}); + const [rows2] = await transaction!.run(query); + assert.strictEqual(rows2.length, 1); + + transaction!.end(); + }; + + it('GOOGLE_STANDARD_SQL should read with staleness & concurrent updates', async () => { + await readWithStalenessAndConcurrentUpdates( + DATABASE, + googleSqlTable, + googleSqlRecords, + ); + }); + + it('POSTGRESQL should read with staleness & concurrent updates', async () => { + await readWithStalenessAndConcurrentUpdates( + PG_DATABASE, + postgreSqlTable, + postgreSqlRecords, + ); + }); + + it('GOOGLE_STANDARD_SQL should pass directedReadOptions at query level read-only transactions', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const directedReadOptionsForRequest = { + includeReplicas: { + replicaSelections: [ + { + type: protos.google.spanner.v1.DirectedReadOptions + .ReplicaSelection.Type.READ_ONLY, + }, + ], + autoFailoverDisabled: true, + }, + }; + + const [transaction] = await DATABASE.getSnapshot(); + const [rows] = await transaction!.run({ + sql: `SELECT * FROM ${TABLE_NAME}`, + directedReadOptions: directedReadOptionsForRequest, + }); + assert.strictEqual(rows.length, googleSqlRecords.length); + transaction!.end(); + }); + }); + + describe('dml', () => { + before(async () => { + const psqlTransaction = await PG_DATABASE.runTransactionAsync( + async transaction => { + await transaction!.runUpdate({ + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' ("Key", "StringValue") VALUES($1, $2)', + params: { + p1: 'k999', + p2: 'abc', + }, + }); + await transaction!.commit(); + }, + ); + + const gsqlTransaction = DATABASE.runTransactionAsync( + async transaction => { + await transaction!.runUpdate({ + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' (Key, StringValue) VALUES(@key, @str)', + params: { + key: 'k999', + str: 'abc', + }, + }); + await transaction!.commit(); + }, + ); + + return Promise.all([psqlTransaction, gsqlTransaction]); + }); + + const rowCountRunUpdate = async (database, query) => { + await database.runTransactionAsync(async transaction => { + const [rowCount] = await transaction!.runUpdate(query); + assert.strictEqual(rowCount, 1); + await transaction!.rollback(); + }); + }; + + it('GOOGLE_STANDARD_SQL should return rowCount from runUpdate', async () => { + const query = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.StringValue = @str WHERE t.Key = @key', + params: { + key: 'k999', + str: 'abcd', + }, + }; + await rowCountRunUpdate(DATABASE, query); + }); + + it('POSTGRESQL should return rowCount from runUpdate', async () => { + const query = { + sql: + 'UPDATE ' + TABLE_NAME + ' SET "StringValue" = $1 WHERE "Key" = $2', + params: { + p1: 'abcd', + p2: 'k999', + }, + }; + await rowCountRunUpdate(PG_DATABASE, query); + }); + + const rowCountRun = async (database, query) => { + await database.runTransactionAsync(async transaction => { + const [rows, stats] = await transaction!.run(query); + const rowCount = Math.floor(stats[stats.rowCount!] as number); + assert.strictEqual(rowCount, 1); + await transaction!.rollback(); + }); + }; + it('GOOGLE_STANDARD_SQL should return rowCount from run', async () => { + const query = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.StringValue = @str WHERE t.Key = @key', + params: { + key: 'k999', + str: 'abcd', + }, + }; + await rowCountRun(DATABASE, query); + }); + + it('POSTGRESQL should return rowCount from run', async () => { + const query = { + sql: + 'UPDATE ' + TABLE_NAME + ' SET "StringValue" = $1 WHERE "Key" = $2', + params: { + p1: 'abcd', + p2: 'k999', + }, + }; + await rowCountRun(PG_DATABASE, query); + }); + + const multipleDmlOnTxn = async ( + database, + insertQuery, + updateQuery, + selectQuery, + ) => { + await database.runTransactionAsync(async transaction => { + const [insertRowCount] = await transaction!.runUpdate(insertQuery); + assert.strictEqual(insertRowCount, 1); + const [updateRowCount] = await transaction!.runUpdate(updateQuery); + assert.strictEqual(updateRowCount, 1); + let rows; + [rows] = await transaction!.run(selectQuery); + rows = rows.map(row => row.toJSON()); + assert.strictEqual(rows.length, 1); + assert.deepStrictEqual(rows[0], { + Key: 'k1000', + StringValue: 'abcd', + NumberValue: 11, + }); + await transaction!.rollback(); + }); + }; + + it('GOOGLE_STANDARD_SQL should exec multiple dml statements on the same txn', async () => { + const key = 'k1000'; + const str = 'abcd'; + const num = 11; + const insertQuery = { + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' (Key, StringValue) VALUES (@key, @str)', + params: {key, str}, + }; + const updateQuery = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.NumberValue = @num WHERE t.KEY = @key', + params: {key, num}, + }; + const selectQuery = { + sql: 'SELECT * FROM ' + TABLE_NAME + ' WHERE Key = @key', + params: {key}, + }; + await multipleDmlOnTxn(DATABASE, insertQuery, updateQuery, selectQuery); + }); + + it('POSTGRESQL should exec multiple dml statements on the same txn', async () => { + const key = 'k1000'; + const str = 'abcd'; + const num = 11; + const insertQuery = { + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' ("Key", "StringValue") VALUES ($1, $2)', + params: {p1: key, p2: str}, + }; + const updateQuery = { + sql: + 'UPDATE ' + TABLE_NAME + ' SET "NumberValue" = $1 WHERE "Key" = $2', + params: {p1: num, p2: key}, + }; + const selectQuery = { + sql: 'SELECT * FROM ' + TABLE_NAME + ' WHERE "Key" = $1', + params: {p1: key}, + }; + await multipleDmlOnTxn( + PG_DATABASE, + insertQuery, + updateQuery, + selectQuery, + ); + }); + + const dmlChangesInQueryResults = async ( + database, + updateQuery, + selectQuery, + ) => { + await database.runTransactionAsync(async transaction => { + await transaction!.runUpdate(updateQuery); + let rows; + [rows] = await transaction!.run(selectQuery); + rows = rows.map(row => row.toJSON()); + assert.strictEqual(rows.length, 1); + assert.strictEqual(rows[0].StringValue, 'abcd'); + await transaction!.rollback(); + }); + }; + + it('GOOGLE_STANDARD_SQL should show dml changes in query results', async () => { + const key = 'k999'; + const str = 'abcd'; + const updateQuery = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.StringValue = @str WHERE t.Key = @key', + params: {key, str}, + }; + const selectQuery = { + sql: 'SELECT * FROM ' + TABLE_NAME + ' WHERE Key = @key', + params: {key}, + }; + await dmlChangesInQueryResults(DATABASE, updateQuery, selectQuery); + }); + + it('POSTGRESQL should show dml changes in query results', async () => { + const key = 'k999'; + const str = 'abcd'; + const updateQuery = { + sql: + 'UPDATE ' + TABLE_NAME + ' SET "StringValue" = $1 WHERE "Key" = $2', + params: {p1: str, p2: key}, + }; + const selectQuery = { + sql: 'SELECT * FROM ' + TABLE_NAME + ' WHERE "Key" = $1', + params: {p1: key}, + }; + await dmlChangesInQueryResults(PG_DATABASE, updateQuery, selectQuery); + }); + + const rollbackDmlStatement = async ( + database, + updateQuery, + selectQuery, + ) => { + await database.runTransactionAsync(async transaction => { + await transaction!.runUpdate(updateQuery); + await transaction!.rollback(); + let rows; + [rows] = await database.run(selectQuery); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + rows = rows.map(row => (row as any).toJSON()); + assert.notStrictEqual(rows[0].StringValue, 'abcd'); + }); + }; + + it('GOOGLE_STANDARD_SQL should rollback a dml statement', async () => { + const key = 'k999'; + const str = 'abcd'; + const updateQuery = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.StringValue = @str WHERE t.Key = @key', + params: {key, str}, + }; + const selectQuery = { + sql: 'SELECT * FROM ' + TABLE_NAME + ' WHERE Key = @key', + params: {key}, + }; + await rollbackDmlStatement(DATABASE, updateQuery, selectQuery); + }); + + it('POSTGRESQL should rollback a dml statement', async () => { + const key = 'k999'; + const str = 'abcd'; + const updateQuery = { + sql: + 'UPDATE ' + TABLE_NAME + ' SET "StringValue" = $1 WHERE "Key" = $2', + params: {p1: str, p2: key}, + }; + const selectQuery = { + sql: 'SELECT * FROM ' + TABLE_NAME + ' WHERE "Key" = $1', + params: {p1: key}, + }; + await rollbackDmlStatement(PG_DATABASE, updateQuery, selectQuery); + }); + + const handleDmlAndInsert = async (database, insertQuery, selectQuery) => { + await database.runTransactionAsync(async transaction => { + await transaction!.runUpdate(insertQuery); + transaction!.insert('TxnTable', { + Key: 'k1002', + StringValue: 'dml+mutation', + }); + + await transaction!.commit(); + const [rows] = await database.run(selectQuery); + assert.strictEqual(rows.length, 2); + }); + }; + + it('GOOGLE_STANDARD_SQL should handle using both dml and insert methods', async () => { + const str = 'dml+mutation'; + const insertQuery = { + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' (Key, StringValue) VALUES (@key, @str)', + params: { + key: 'k1001', + str, + }, + }; + const selectQuery = { + sql: 'SELECT * FROM ' + TABLE_NAME + ' WHERE StringValue = @str', + params: {str}, + }; + await handleDmlAndInsert(DATABASE, insertQuery, selectQuery); + }); + + it('POSTGRESQL should handle using both dml and insert methods', async () => { + const str = 'dml+mutation'; + const insertQuery = { + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' ("Key", "StringValue") VALUES ($1, $2)', + params: { + p1: 'k1001', + p2: str, + }, + }; + const selectQuery = { + sql: 'SELECT * FROM ' + TABLE_NAME + ' WHERE "StringValue" = $1', + params: {p1: str}, + }; + await handleDmlAndInsert(PG_DATABASE, insertQuery, selectQuery); + }); + + describe('dml returning', () => { + const key = 'k1003'; + const str = 'abcd'; + const num = 11; + + const googleSqlInsertReturning = { + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' (Key, StringValue) VALUES (@key, @str) ' + + 'THEN RETURN *', + params: {key, str}, + }; + + const googleSqlUpdateReturning = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.NumberValue = @num WHERE t.KEY = @key ' + + 'THEN RETURN *', + params: {num, key}, + }; + + const googleSqlDeleteReturning = { + sql: + 'DELETE FROM ' + + TABLE_NAME + + ' t WHERE t.KEY = @key ' + + 'THEN RETURN *', + params: {key}, + }; + + const googleSqlDelete = { + sql: 'DELETE FROM ' + TABLE_NAME + ' t WHERE t.KEY = @key', + params: {key, num}, + }; + + const postgreSqlUpdateReturning = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' SET "NumberValue" = $1 WHERE "Key" = $2 ' + + 'RETURNING *', + params: {p1: num, p2: key}, + }; + + const postgreSqlDeleteReturning = { + sql: + 'DELETE FROM ' + TABLE_NAME + ' WHERE "Key" = $1 ' + 'RETURNING *', + params: {p1: key}, + }; + + const postgreSqlInsertReturning = { + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' ("Key", "StringValue") VALUES ($1, $2) ' + + 'RETURNING *', + params: {p1: key, p2: str}, + }; + + const postgreSqlDelete = { + sql: 'DELETE FROM ' + TABLE_NAME + ' WHERE "Key" = $1', + params: {p1: key}, + }; + + const rowCountRunUpdate = async ( + database, + insertQuery, + updateQuery, + deletequery, + ) => { + await database.runTransactionAsync(async transaction => { + const [insertRowCount] = await transaction!.runUpdate(insertQuery); + assert.strictEqual(insertRowCount, 1); + const [updateRowCount] = await transaction!.runUpdate(updateQuery); + assert.strictEqual(updateRowCount, 1); + const [deleteRowCount] = await transaction!.runUpdate(deletequery); + assert.strictEqual(deleteRowCount, 1); + await transaction!.commit(); + }); + }; + + it('GOOGLE_STANDARD_SQL should return rowCount from runUpdate with dml returning', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await rowCountRunUpdate( + DATABASE, + googleSqlInsertReturning, + googleSqlUpdateReturning, + googleSqlDeleteReturning, + ); + }); + + it('POSTGRESQL should return rowCount from runUpdate with dml returning', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await rowCountRunUpdate( + PG_DATABASE, + postgreSqlInsertReturning, + postgreSqlUpdateReturning, + postgreSqlDeleteReturning, + ); + }); + + const assertRowsAndRowCount = data => { + const rows = data[0]; + const stats = data[1]; + const rowCount = Math.floor(stats[stats.rowCount!] as number); + assert.strictEqual(rowCount, 1); + rows.forEach(row => { + const json = row.toJSON(); + assert.strictEqual(json.Key, key); + assert.strictEqual(json.StringValue, str); + }); + }; + + const rowCountRun = async ( + database, + insertQuery, + updateQuery, + deletequery, + ) => { + await database.runTransactionAsync(async transaction => { + const rows = await transaction!.run(insertQuery); + assertRowsAndRowCount(rows); + const updateRowsCount = await transaction!.run(updateQuery); + assertRowsAndRowCount(updateRowsCount); + const deleteRowsCount = await transaction!.run(deletequery); + assertRowsAndRowCount(deleteRowsCount); + await transaction!.commit(); + }); + }; + + it('GOOGLE_STANDARD_SQL should return rowCount and rows from run with dml returning', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await rowCountRun( + DATABASE, + googleSqlInsertReturning, + googleSqlUpdateReturning, + googleSqlDeleteReturning, + ); + }); + + it('POSTGRESQL should return rowCount and rows from run with dml returning', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + + await rowCountRun( + PG_DATABASE, + postgreSqlInsertReturning, + postgreSqlUpdateReturning, + postgreSqlDeleteReturning, + ); + }); + + const partitionedUpdate = async (database, query) => { + try { + await database.runPartitionedUpdate(query); + } catch (err: any) { + assert.match( + err.details, + /THEN RETURN is not supported in Partitioned DML\./, + ); + } + }; + + it('GOOGLE_STANDARD_SQL should throw error from partitioned update with dml returning', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await partitionedUpdate(DATABASE, googleSqlUpdateReturning); + }); + + it('POSTGRESQL should throw error from partitioned update with dml returning', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + + await partitionedUpdate(PG_DATABASE, postgreSqlUpdateReturning); + }); + + const batchUpdate = async ( + database, + insertquery, + updateQuery, + deleteQuery, + ) => { + const rowCounts = await database.runTransactionAsync(async txn => { + const [rowCounts] = await txn.batchUpdate([ + insertquery, + updateQuery, + deleteQuery, + ]); + await txn.commit(); + return rowCounts; + }); + assert.deepStrictEqual(rowCounts, [1, 1, 1]); + }; + + it('GOOGLE_STANDARD_SQL should run multiple statements from batch update with mix of dml returning', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await batchUpdate( + DATABASE, + googleSqlInsertReturning, + googleSqlUpdateReturning, + googleSqlDelete, + ); + }); + + it('POSTGRESQL should run multiple statements from batch update with mix of dml returning', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + + await batchUpdate( + PG_DATABASE, + postgreSqlInsertReturning, + postgreSqlUpdateReturning, + postgreSqlDelete, + ); + }); + }); + }); + + describe('pdml', () => { + const simplePdml = async (database, query) => { + const [rowCount] = await database.runPartitionedUpdate(query); + assert.strictEqual(rowCount, 1); + }; + + it('GOOGLE_STANDARD_SQL should execute a simple pdml statement', async () => { + const query = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.StringValue = @str WHERE t.Key = @key', + params: { + key: 'k1', + str: 'abcde', + }, + }; + await simplePdml(DATABASE, query); + }); + + it('POSTGRESQL should execute a simple pdml statement', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const query = { + sql: + 'UPDATE ' + TABLE_NAME + ' SET "StringValue" = $1 WHERE "Key" = $2', + params: { + p1: 'abcde', + p2: 'k1', + }, + }; + await simplePdml(PG_DATABASE, query); + }); + + const longRunningPdml = async function ( + database, + updateQuery, + selectQuery, + ) { + const count = 10000; + + const tableData = new Array(count).fill(0).map((_, i) => { + return {Key: `longpdml${i}`, StringValue: 'a'}; + }); + + await database.runTransactionAsync(async transaction => { + transaction.insert('TxnTable', tableData); + await transaction.commit(); + }); + const [rowCount] = await database.runPartitionedUpdate(updateQuery); + assert.strictEqual(rowCount, count); + const [rows] = await database.run(selectQuery); + assert.strictEqual(rows.length, count); + }; + + it('GOOGLE_STANDARD_SQL should execute a long running pdml statement', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const str = new Array(1000).fill('b').join('\n'); + const updateQuery = { + sql: + 'UPDATE ' + + TABLE_NAME + + " t SET t.StringValue = @str WHERE t.StringValue = 'a'", + params: {str}, + }; + const selectQuery = { + sql: 'SELECT Key FROM ' + TABLE_NAME + ' WHERE StringValue = @str', + params: {str}, + }; + await longRunningPdml(DATABASE, updateQuery, selectQuery); + }); + + it('POSTGRESQL should execute a long running pdml statement', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const str = new Array(1000).fill('b').join('\n'); + const updateQuery = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' SET "StringValue" = $1 WHERE "StringValue" = \'a\'', + params: {p1: str}, + }; + const selectQuery = { + sql: 'SELECT "Key" FROM ' + TABLE_NAME + ' WHERE "StringValue" = $1', + params: {p1: str}, + }; + await longRunningPdml(PG_DATABASE, updateQuery, selectQuery); + }); + }); + + describe('batch dml', () => { + const key = 'k1234'; + const str = 'abcd'; + const num = 11; + + const googleSqlInsert = { + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' (Key, StringValue) VALUES (@key, @str)', + params: {key, str}, + }; + + const postgreSqlInsert = { + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' ("Key", "StringValue") VALUES ($1, $2)', + params: {p1: key, p2: str}, + }; + + const googleSqlUpdate = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.NumberValue = @num WHERE t.KEY = @key', + params: {key, num}, + }; + + const posgreSqlUpdate = { + sql: + 'UPDATE ' + TABLE_NAME + ' SET "NumberValue" = $1 WHERE "Key" = $2', + params: {p1: num, p2: key}, + }; + + // this should fail since we're not binding params + const googleSqlBorked = { + sql: + 'UPDATE ' + + TABLE_NAME + + ' t SET t.NumberValue = @num WHERE t.KEY = @key', + }; + + const postgreSqlBorked = { + sql: + 'UPDATE ' + TABLE_NAME + ' SET "NumberValue" = $1 WHERE "Key" = $2', + }; + + const executeSingleStatement = async (database, insert) => { + const rowCounts = await database.runTransactionAsync(async txn => { + const [rowCounts] = await txn.batchUpdate([insert]); + await txn.rollback(); + return rowCounts; + }); + + assert.deepStrictEqual(rowCounts, [1]); + }; + + it('GOOGLE_STANDARD_SQL should execute a single statement', async () => { + await executeSingleStatement(DATABASE, googleSqlInsert); + }); + + it('POSTGRESQL should execute a single statement', async () => { + await executeSingleStatement(PG_DATABASE, postgreSqlInsert); + }); + + const noStatementError = async database => { + const err = await database.runTransactionAsync(async txn => { + let err; + + try { + await txn.batchUpdate(null as unknown as []); + } catch (e) { + err = e; + } + + txn.end(); + return err; + }); + + assert.strictEqual( + err.message, + 'batchUpdate requires at least 1 DML statement.', + ); + assert.strictEqual(err.code, 3); + }; + + it('GOOGLE_STANDARD_SQL should return an error when no statements are supplied', async () => { + await noStatementError(DATABASE); + }); + + it('POSTGRESQL should return an error when no statements are supplied', async () => { + await noStatementError(PG_DATABASE); + }); + + const multipleDependingStatements = async (database, insert, update) => { + const rowCounts = await database.runTransactionAsync(async txn => { + const [rowCounts] = await txn.batchUpdate([insert, update]); + await txn.rollback(); + return rowCounts; + }); + + assert.deepStrictEqual(rowCounts, [1, 1]); + }; + + it('GOOGLE_STANDARD_SQL should run multiple statements that depend on each other', async () => { + await multipleDependingStatements( + DATABASE, + googleSqlInsert, + googleSqlUpdate, + ); + }); + + it('POSTGRESQL should run multiple statements that depend on each other', async () => { + await multipleDependingStatements( + PG_DATABASE, + postgreSqlInsert, + posgreSqlUpdate, + ); + }); + + const runAfterRunUpdate = async (database, insert, update) => { + const rowCounts = await database.runTransactionAsync(async txn => { + await txn.runUpdate(insert); + const [rowCounts] = await txn.batchUpdate([update]); + await txn.rollback(); + return rowCounts; + }); + + assert.deepStrictEqual(rowCounts, [1]); + }; + + it('GOOGLE_STANDARD_SQL should run after a runUpdate call', async () => { + await runAfterRunUpdate(DATABASE, googleSqlInsert, googleSqlUpdate); + }); + + it('POSTGRESQL should run after a runUpdate call', async () => { + await runAfterRunUpdate(PG_DATABASE, postgreSqlInsert, posgreSqlUpdate); + }); + + const runBeforeRunUpdate = async (database, insert, update) => { + const rowCounts = await database.runTransactionAsync(async txn => { + const [rowCounts] = await txn.batchUpdate([insert]); + await txn.runUpdate(update); + await txn.rollback(); + return rowCounts; + }); + + assert.deepStrictEqual(rowCounts, [1]); + }; + + it('GOOGLE_STANDARD_SQL should run before a runUpdate call', async () => { + await runBeforeRunUpdate(DATABASE, googleSqlInsert, googleSqlUpdate); + }); + + it('POSTGRESQL should run before a runUpdate call', async () => { + await runBeforeRunUpdate( + PG_DATABASE, + postgreSqlInsert, + posgreSqlUpdate, + ); + }); + + const stopExecutingStatementsIfError = async ( + database, + insert, + borked, + update, + ) => { + const err = await database.runTransactionAsync(async txn => { + let err; + + try { + await txn.batchUpdate([insert, borked, update]); + } catch (e) { + // Re-throw if the transaction was aborted to trigger a retry. + if ((err as grpc.ServiceError)?.code === grpc.status.ABORTED) { + throw e; + } + err = e; + } + + await txn.rollback(); + return err; + }); + + assert.strictEqual(err.code, grpc.status.INVALID_ARGUMENT); + assert.deepStrictEqual(err.rowCounts, [1]); + }; + + it('GOOGLE_STANDARD_SQL should stop executing statements if an error occurs', async () => { + await stopExecutingStatementsIfError( + DATABASE, + googleSqlInsert, + googleSqlBorked, + googleSqlUpdate, + ); + }); + + it('POSTGRESQL should stop executing statements if an error occurs', async () => { + await stopExecutingStatementsIfError( + PG_DATABASE, + postgreSqlInsert, + postgreSqlBorked, + posgreSqlUpdate, + ); + }); + + const ignoreAdditionalStatementErrors = async ( + database, + insert, + borked, + ) => { + const err = await database.runTransactionAsync(async txn => { + let err; + + try { + await txn.batchUpdate([insert, borked, borked]); + } catch (e) { + err = e; + } + + await txn.rollback(); + return err; + }); + + assert.strictEqual(err.code, 3); + assert.deepStrictEqual(err.rowCounts, [1]); + }; + + it('GOOGLE_STANDARD_SQL should ignore any additional statement errors', async () => { + await ignoreAdditionalStatementErrors( + DATABASE, + googleSqlInsert, + googleSqlBorked, + ); + }); + + it('POSTGRESQL should ignore any additional statement errors', async () => { + await ignoreAdditionalStatementErrors( + PG_DATABASE, + postgreSqlInsert, + postgreSqlBorked, + ); + }); + }); + + describe('read/write', () => { + const mismatchedColumnError = async (database, table) => { + await database.runTransactionAsync(transaction => { + const rows = [ + { + Key: 'k1', + StringValue: 'hi', + }, + { + Key: 'k2', + NumberValue: 4, + }, + ]; + + const expectedErrorMessage = [ + 'Row at index 0 does not contain the correct number of columns.', + `Missing columns: ${JSON.stringify(['NumberValue'])}`, + ].join('\n\n'); + let caughtErrorMessage; + try { + transaction!.insert(table.name, rows); + } catch (e) { + caughtErrorMessage = (e as grpc.ServiceError).message; + } + assert.strictEqual(caughtErrorMessage, expectedErrorMessage); + + transaction!.end(); + }); + }; + + it('GOOGLE_STANDARD_SQL should throw an error for mismatched columns', async () => { + await mismatchedColumnError(DATABASE, googleSqlTable); + }); + + it('GOOGLE_STANDARD_SQL should use getTransaction for executing sql', async () => { + const transaction = ( + await DATABASE.getTransaction({readLockMode: ReadLockMode.OPTIMISTIC}) + )[0]; + + try { + const [rows] = await transaction!.run('SELECT * FROM TxnTable'); + assert.strictEqual(rows.length, googleSqlRecords.length); + } catch (err) { + // flaky failures are acceptable here as long as the error is not due to a lock conflict + if ((err as grpc.ServiceError).code === grpc.status.ABORTED) { + assert.ok(err, 'Transaction is aborted'); + } + } finally { + transaction.end(); + } + }); + + it('POSTGRESQL should throw an error for mismatched columns', async () => { + await mismatchedColumnError(PG_DATABASE, postgreSqlTable); + }); + + const commitTransaction = async (database, table) => { + await database.runTransactionAsync(async transaction => { + transaction!.insert(table.name, { + Key: 'k5', + StringValue: 'v5', + }); + + await transaction!.commit(); + }); + }; + + it('GOOGLE_STANDARD_SQL should commit a transaction', async () => { + await commitTransaction(DATABASE, googleSqlTable); + }); + + it('POSTGRESQL should commit a transaction', async () => { + await commitTransaction(PG_DATABASE, postgreSqlTable); + }); + + describe('parallel transactions', async () => { + async function insertAndCommitTransaction(database, sync, table, key) { + await database.runTransactionAsync(async transaction => { + // read from table TxnTable + await transaction.run('SELECT * FROM TxnTable'); + + // insert mutation + transaction!.insert(table.name, { + Key: key, + StringValue: 'v6', + }); + + // increment the shared counter + sync.count++; + if (sync.count === sync.target) { + // resolve the commit promise so that both the threads can continue to commit the transaction + sync.resolveCommitPromise(); + } + + // wait till the commit promise is resolved + await sync.promise; + + // commit transaction once both the transactions are ready to commit + await transaction!.commit(); + }); + } + + it('should insert and commit transaction when running parallely', async () => { + const promises: Promise[] = []; + let resolvePromise; + const commitPromise = new Promise( + resolve => (resolvePromise = resolve), + ); + const sync = { + target: 2, // both the transactions to be ready + count: 0, // 0 transactions are ready so far + promise: commitPromise, // the promise both the transactions wait at + resolveCommitPromise: () => resolvePromise(), // the function to resolve the commit promise + }; + // run the transactions in parallel + promises.push( + insertAndCommitTransaction(DATABASE, sync, googleSqlTable, 'k1100'), + ); + promises.push( + insertAndCommitTransaction(DATABASE, sync, googleSqlTable, 'k1101'), + ); + + // wait for both the transactions to complete their execution + await Promise.all(promises); + }); + }); + + const rollbackTransaction = async database => { + await database.runTransactionAsync(async transaction => { + await transaction!.run('SELECT * FROM TxnTable'); + await transaction!.rollback(); + }); + }; + + it('GOOGLE_STANDARD_SQL should rollback a transaction', async () => { + await rollbackTransaction(DATABASE); + }); + + it('POSTGRESQL should rollback a transaction', async () => { + await rollbackTransaction(PG_DATABASE); + }); + + describe('concurrent transactions', () => { + const defaultRowValues = { + Key: 'k0', + NumberValue: 0, + }; + + beforeEach(async () => { + await googleSqlTable.update(defaultRowValues); + if (!IS_EMULATOR_ENABLED) { + await postgreSqlTable.update(defaultRowValues); + } + }); + + const readConcurrentTransaction = async (database, table) => { + await database.runTransactionAsync(async transaction => { + await incrementValue(); + const value = await getValue(transaction); + assert.strictEqual(value, defaultRowValues.NumberValue + 1); + }); + + async function incrementValue() { + await database.runTransactionAsync(async transaction => { + const value = await getValue(transaction); + transaction!.update(table.name, { + Key: defaultRowValues.Key, + NumberValue: value + 1, + }); + + await transaction!.commit(); + }); + } + + async function getValue(txn) { + try { + const [rows] = await txn.read(table.name, { + keys: [defaultRowValues.Key], + columns: ['NumberValue'], + }); + const row = rows[0].toJSON(); + return row.NumberValue; + } catch (err) { + return err; + } + } + }; + + it('GOOGLE_STANDARD_SQL should handle concurrent transactions with read', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await readConcurrentTransaction(DATABASE, googleSqlTable); + }); + + it('POSTGRESQL should handle concurrent transactions with read', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await readConcurrentTransaction(PG_DATABASE, postgreSqlTable); + }); + + const queryConcurrentTransaction = async (database, table, query) => { + await database.runTransactionAsync(async transaction => { + await incrementValue(); + const value = await getValue(transaction); + assert.strictEqual(value, defaultRowValues.NumberValue + 1); + }); + + async function incrementValue() { + await database.runTransactionAsync(async transaction => { + const value = await getValue(transaction); + transaction!.update(table.name, { + Key: defaultRowValues.Key, + NumberValue: value + 1, + }); + + await transaction!.commit(); + }); + } + + async function getValue(txn) { + let rows; + try { + [rows] = await txn.run(query); + const row = rows[0].toJSON(); + return row.NumberValue; + } catch (err) { + return err; + } + } + }; + + it('GOOGLE_STANDARD_SQL should handle concurrent transactions with query', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const query = { + sql: 'SELECT * FROM ' + googleSqlTable.name + ' WHERE Key = @key', + params: { + key: defaultRowValues.Key, + }, + }; + await queryConcurrentTransaction(DATABASE, googleSqlTable, query); + }); + + it('POSTGRESQL should handle concurrent transactions with query', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const query = { + sql: 'SELECT * FROM ' + postgreSqlTable.name + ' WHERE "Key" = $1', + params: { + p1: defaultRowValues.Key, + }, + }; + await queryConcurrentTransaction(PG_DATABASE, postgreSqlTable, query); + }); + }); + + const retryAbortedTxnWhenReadingFails = async ( + database, + table, + query, + ) => { + const key = 'k888'; + let attempts = 0; + const expectedRow = { + Key: key, + NumberValue: null, + StringValue: 'abc', + }; + const runOtherTransaction = async () => { + await database.runTransactionAsync(async transaction => { + await transaction.run(query); + transaction.insert(table.name, expectedRow); + await transaction.commit(); + }); + }; + + await database.runTransactionAsync(async transaction => { + attempts++; + const [rows] = await transaction.run(query); + if (attempts === 1) { + await runOtherTransaction(); + } + transaction.insert(table.name, { + Key: generateName('key'), + StringValue: generateName('val'), + }); + if (attempts > 1 && rows.length > 0) { + const lastRow = rows.pop().toJSON(); + assert.deepStrictEqual(lastRow, expectedRow); + } + await transaction.commit(); + }); + assert.ok(attempts >= 2); + }; + + it('GOOGLE_STANDARD_SQL should retry an aborted txn when reading fails', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const key = 'k888'; + const query = `SELECT * FROM ${googleSqlTable.name} WHERE Key = '${key}'`; + + await retryAbortedTxnWhenReadingFails(DATABASE, googleSqlTable, query); + }); + + it('POSTGRESQL should retry an aborted txn when reading fails', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const key = 'k888'; + const query = { + sql: `SELECT * FROM ${postgreSqlTable.name} WHERE "Key" = $1`, + params: { + p1: key, + }, + }; + + await retryAbortedTxnWhenReadingFails( + PG_DATABASE, + postgreSqlTable, + query, + ); + }); + + const retryAbortedTxnWhenCommitFails = async (database, table, query) => { + const key = 'k9999'; + let attempts = 0; + + const expectedRow = { + Key: key, + NumberValue: null, + StringValue: 'abc', + }; + + const runOtherTransaction = async () => { + await database.runTransactionAsync(async transaction => { + await transaction.run(query); + transaction.insert(table.name, expectedRow); + await transaction.commit(); + }); + }; + + await database.runTransactionAsync(async transaction => { + attempts++; + const [rows] = await transaction.run(query); + transaction.insert(table.name, { + Key: generateName('key'), + StringValue: generateName('val'), + }); + if (attempts === 1) { + await runOtherTransaction(); + } + if (attempts > 1 && rows.length > 0) { + const lastRow = rows.pop().toJSON(); + assert.deepStrictEqual(lastRow, expectedRow); + } + await transaction.commit(); + }); + assert.ok(attempts >= 2); + }; + + it('GOOGLE_STANDARD_SQL should retry an aborted txn when commit fails', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const key = 'k9999'; + const query = `SELECT * FROM ${googleSqlTable.name} WHERE Key = '${key}'`; + await retryAbortedTxnWhenCommitFails(DATABASE, googleSqlTable, query); + }); + + it('POSTGRESQL should retry an aborted txn when commit fails', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const key = 'k9999'; + const query = { + sql: `SELECT * FROM ${postgreSqlTable.name} WHERE "Key" = $1`, + params: { + p1: key, + }, + }; + await retryAbortedTxnWhenCommitFails( + PG_DATABASE, + postgreSqlTable, + query, + ); + }); + + const deadlineErrorInsteadOfAbort = async (database, table) => { + const options = { + timeout: 10, + }; + + const query = `SELECT * FROM ${table.name}`; + const runOtherTransaction = async () => { + await database.runTransactionAsync(async transaction => { + await transaction.run(query); + transaction.insert(table.name, { + Key: generateName('key'), + }); + await transaction.commit(); + }); + }; + await assert.rejects( + async () => { + await database.runTransactionAsync(options, async transaction => { + await transaction.run(query); + transaction.insert(table.name, { + Key: generateName('key'), + }); + await runOtherTransaction(); + await transaction.commit(); + }); + }, + (err: any) => { + assert.strictEqual(err.code, 4); + assert.ok( + err.message.startsWith('Deadline for Transaction exceeded'), + ); + return true; + }, + ); + }; + + it('GOOGLE_STANDARD_SQL should return a deadline error instead of aborted', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await deadlineErrorInsteadOfAbort(DATABASE, googleSqlTable); + }); + + it('POSTGRESQL should return a deadline error instead of aborted', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + await deadlineErrorInsteadOfAbort(PG_DATABASE, postgreSqlTable); + }); + + it('GOOGLE_STANDARD_SQL should throw error when directedReadOptions at query level is set with read-write transactions', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const directedReadOptionsForRequest = { + includeReplicas: { + replicaSelections: [ + { + type: protos.google.spanner.v1.DirectedReadOptions + .ReplicaSelection.Type.READ_WRITE, + }, + ], + autoFailoverDisabled: true, + }, + }; + + await DATABASE.runTransactionAsync(async transaction => { + const expectedErrorMessage = + 'Directed reads can only be performed in a read-only transaction.'; + try { + await transaction!.run({ + sql: `SELECT * FROM ${googleSqlTable.name}`, + directedReadOptions: directedReadOptionsForRequest, + }); + } catch (err: any) { + assert.strictEqual(err?.details, expectedErrorMessage); + await transaction!.end(); + } + }); + }); + + const handleReadAndMutation = async database => { + await database.runTransactionAsync(async transaction => { + try { + await transaction.run('SELECT abc'); + } catch (err) { + // add a sleep to let the explicit begin call finish + await new Promise(resolve => { + setTimeout(() => { + resolve(); + }, 4000); + }); + } + transaction!.insert('TxnTable', { + Key: 'k1003', + StringValue: 'mutation', + }); + await transaction.commit(); + }); + }; + + it('GOOGLE_STANDARD_SQL should handle commit retry based on multiplexed enable or not', async () => { + await handleReadAndMutation(DATABASE); + }); + }); + + describe('batch transactions', () => { + before(async () => { + if (!IS_EMULATOR_ENABLED) { + await DATABASE.runTransactionAsync(async transaction => { + await transaction!.runUpdate({ + sql: + 'INSERT INTO ' + + TABLE_NAME + + ' (Key, StringValue) VALUES(@key, @str)', + params: { + key: 'k998', + str: 'abc', + }, + }); + await transaction!.commit(); + }); + } + }); + + it('should create and execute a query partition using callback', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const selectQuery = { + sql: 'SELECT * FROM TxnTable where Key = @id', + params: { + id: 'k998', + }, + }; + + let row_count = 0; + const [transaction] = await DATABASE.createBatchTransaction(); + const [partitions] = + await transaction!.createQueryPartitions(selectQuery); + assert.deepStrictEqual(partitions.length, 1); + partitions.forEach(async partition => { + const [results] = await transaction!.execute(partition); + row_count += results.map(row => row.toJSON()).length; + assert.deepStrictEqual(row_count, 1); + await transaction!.close(); + }); + }); + + it('should create and execute a read partition using callback', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const key = 'k998'; + const QUERY = { + table: googleSqlTable.name, + // Set databoostenabled to true for enabling serveless analytics. + dataBoostEnabled: true, + keys: [key], + columns: ['Key'], + }; + + let read_row_count = 0; + const [transaction] = await DATABASE.createBatchTransaction(); + const [partitions] = await transaction!.createReadPartitions(QUERY); + assert.deepStrictEqual(partitions.length, 1); + partitions.forEach(async partition => { + const [results] = await transaction!.execute(partition); + read_row_count += results.map(row => row.toJSON()).length; + assert.deepStrictEqual(read_row_count, 1); + await transaction!.close(); + }); + }); + + it('should create and execute a query partition using await', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + + const [transaction] = await DATABASE.createBatchTransaction(); + const selectQuery = { + sql: 'SELECT * FROM TxnTable where Key = @id', + params: { + id: 'k998', + }, + }; + + let row_count = 0; + try { + const [queryPartitions]: CreateQueryPartitionsResponse = + await transaction.createQueryPartitions(selectQuery); + assert.deepStrictEqual(queryPartitions.length, 1); + + const promises = queryPartitions.map(async queryPartition => { + const [results]: RunResponse = + await transaction.execute(queryPartition); + row_count += results.map(row => row.toJSON()).length; + assert.strictEqual(row_count, 1); + }); + + await Promise.all(promises); + } catch (err) { + assert.ifError(err); + } + }); + + it('should create and execute a read partition using await', async function () { + if (IS_EMULATOR_ENABLED) { + this.skip(); + } + const [transaction] = await DATABASE.createBatchTransaction(); + const key = 'k998'; + const QUERY = { + table: googleSqlTable.name, + // Set databoostenabled to true for enabling serveless analytics. + dataBoostEnabled: true, + keys: [key], + columns: ['Key'], + }; + + let read_row_count = 0; + try { + const [readPartitions]: CreateReadPartitionsResponse = + await transaction.createReadPartitions(QUERY); + assert.deepStrictEqual(readPartitions.length, 1); + + const promises = readPartitions.map(async readPartition => { + const [results]: ReadResponse = + await transaction.execute(readPartition); + read_row_count += results.map(row => row.toJSON()).length; + assert.strictEqual(read_row_count, 1); + }); + + await Promise.all(promises); + } catch (err) { + assert.ifError(err); + } + }); + }); + }); +}); + +function shortUUID() { + return uuid.v4().split('-').shift(); +} + +function generateName(resourceType) { + return PREFIX + resourceType + '-' + shortUUID(); +} + +function onPromiseOperationComplete(data) { + const length = + data[data.length - 1] === undefined ? data.length - 1 : data.length; + const operation = data[length - 2]; + return operation.promise(); +} + +async function deleteOldTestInstances() { + const [instances] = await spanner.getInstances(); + const currentTimestampSeconds = Math.round(Date.now() / 1000); + // Leave only instances that contain PREFIX in their name + // and where created more that an hour ago. + function isOld(timestampCreated: number) { + return currentTimestampSeconds - timestampCreated >= 60 * 60 * 4; + } + const toDelete = instances.filter( + instance => + instance.id.includes(PREFIX) && + isOld(Number(instance.metadata!.labels!.created)), + ); + + return deleteInstanceArray(toDelete); +} + +function deleteInstanceArray(instanceArray) { + /** + * Delay to allow instance and its databases to fully clear. + * Refer to "Soon afterwards" + * @see {@link https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance} + */ + const delay = 500; + const limit = pLimit(5); + return Promise.all( + instanceArray.map(instance => + limit(() => setTimeout(deleteInstance, delay, instance)), + ), + ); +} +async function deleteInstance(instance: Instance) { + const [backups] = await instance.getBackups(); + await Promise.all(backups.map(backup => backup.delete(GAX_OPTIONS))); + return instance.delete(GAX_OPTIONS); +} + +function wait(time) { + return new Promise(resolve => { + setTimeout(resolve, time); + }); +} diff --git a/handwritten/spanner/system-test/tpc-test.ts b/handwritten/spanner/system-test/tpc-test.ts new file mode 100644 index 00000000000..225910c9e99 --- /dev/null +++ b/handwritten/spanner/system-test/tpc-test.ts @@ -0,0 +1,126 @@ +// 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 +// +// 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. + +import {describe, it} from 'mocha'; +import {MutationSet, Spanner} from '../src'; +import * as assert from 'assert'; + +// INSTRUCTIONS FOR RUNNING TEST: +// 1. Change describe.skip to describe.only below. +// 2. Reassign process.env.GOOGLE_APPLICATION_CREDENTIALS to local key file. +// 3. Reassign UNIVERSE_DOMAIN_CONSTANT to the universe domain to test. +// 4. Run `npm run system-test`. + +describe.skip('Universe domain tests', () => { + // These tests are only designed to pass when using the service account + // credentials for the universe domain environment so we skip them in the CI pipeline. + + before(() => { + process.env.GOOGLE_APPLICATION_CREDENTIALS = 'path to your credential file'; + }); + + async function runTest(spanner: Spanner, instanceId, databaseId) { + const instance = spanner.instance(instanceId); + const database = instance.database(databaseId); + const tableName = 'VenueDetails'; + const table = database.table(tableName); + + const schema = `CREATE TABLE ${tableName} ( + VenueId INT64 NOT NULL, + VenueName STRING(100), + Capacity INT64, + ) PRIMARY KEY (VenueId)`; + + console.log(`Creating table ${table.name}`); + const [, operation] = await table.create(schema); + + await operation.promise(); + + console.log(`${table.name} create successfully.`); + + const venuesTable = database.table(tableName); + console.log(`Inserting data into the table ${table.name}`); + await venuesTable.insert([ + {VenueId: 1, VenueName: 'Marc', Capacity: 100}, + {VenueId: 2, VenueName: 'Marc', Capacity: 200}, + ]); + + const mutations = new MutationSet(); + + mutations.insert(tableName, { + VenueId: '3', + VenueName: 'Marc', + Capacity: 700, + }); + mutations.insert(tableName, { + VenueId: '4', + VenueName: 'Marc', + Capacity: 800, + }); + mutations.update(tableName, { + VenueId: '3', + VenueName: 'Marc', + Capacity: 300, + }); + mutations.update(tableName, { + VenueId: '4', + VenueName: 'Marc', + Capacity: 400, + }); + + await database.writeAtLeastOnce(mutations); + + const query = { + columns: ['VenueId', 'VenueName', 'Capacity'], + keySet: { + all: true, + }, + }; + + const [rows] = await venuesTable.read(query); + + console.log(`Inserted ${rows.length} rows into the table ${table.name}`); + + console.log(`Reading rows in the table ${table.name}`); + + rows.forEach(row => { + const json = row.toJSON(); + console.log( + `VenueId: ${json.VenueId}, VenueName: ${json.VenueName}, Capacity: ${json.Capacity}`, + ); + }); + + console.log(`deleting table ${table.name}`); + await table.delete(); + console.log(`deleted table ${table.name}`); + } + it('should be able to run apis successfully against TPC environment', async () => { + const UNIVERSE_DOMAIN_CONSTANT = 'my-universe-domain'; + const projectId = 'tpc-project-id'; + const universeDomain = UNIVERSE_DOMAIN_CONSTANT; + const options = { + projectId, + universeDomain, + }; + const spanner = new Spanner(options); + const instanceId = 'your-test-instance-id'; + const databaseId = 'your-test-database-id'; + + try { + await runTest(spanner, instanceId, databaseId); + } catch (e) { + assert.ifError(e); + } + }); +}); diff --git a/handwritten/spanner/test/backup.ts b/handwritten/spanner/test/backup.ts new file mode 100644 index 00000000000..a331f82beba --- /dev/null +++ b/handwritten/spanner/test/backup.ts @@ -0,0 +1,748 @@ +/** + * Copyright 2020 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. + */ + +'use strict'; + +import * as assert from 'assert'; +import {EventEmitter} from 'events'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import {util} from '@google-cloud/common'; +import * as pfy from '@google-cloud/promisify'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import {Instance, Spanner} from '../src'; +import * as bu from '../src/backup'; +import {GetMetadataResponse} from '../src/backup'; +import {grpc} from 'google-gax'; +import {CLOUD_RESOURCE_HEADER} from '../src/common'; +import {google} from '../protos/protos'; +import EncryptionType = google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType; + +let promisified = false; +// let callbackified = false; +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'Backup') { + return; + } + promisified = true; + assert.deepStrictEqual(options.exclude, [ + 'getState', + 'getExpireTime', + 'exists', + ]); + }, +}); + +class FakeGrpcServiceObject extends EventEmitter { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + calledWith_: any[]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + constructor(...args: any[]) { + super(); + this.calledWith_ = args; + } +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const fakeCodec: any = { + encode: util.noop, + Int() {}, + Float() {}, + SpannerDate() {}, +}; + +describe('Backup', () => { + const sandbox = sinon.createSandbox(); + + // tslint:disable-next-line variable-name + let Backup: typeof bu.Backup; + + const INSTANCE = { + request: util.noop, + requestStream: util.noop, + formattedName_: 'instance-name', + databases_: new Map(), + } as {} as Instance; + + const BACKUP_NAME = 'backup-name'; + const DATABASE_NAME = 'database-name'; + const DATABASE_FORMATTED_NAME = + INSTANCE.formattedName_ + '/databases/' + DATABASE_NAME; + const BACKUP_FORMATTED_NAME = + INSTANCE.formattedName_ + '/backups/' + BACKUP_NAME; + const BACKUP_EXPIRE_TIME = '2019-02-08T10:34:29.481145231Z'; + const EXP_BACKUP_EXPIRE_TIME = Spanner.timestamp(BACKUP_EXPIRE_TIME); + const BACKUP_VERSION_TIME = '2019-02-07T10:34:29.481145231Z'; + const EXP_BACKUP_VERSION_TIME = Spanner.timestamp(BACKUP_VERSION_TIME); + + let backup: bu.Backup; + + before(() => { + Backup = proxyquire('../src/backup.js', { + '@google-cloud/common-grpc': { + ServiceObject: FakeGrpcServiceObject, + }, + '@google-cloud/promisify': fakePfy, + }).Backup; + }); + + beforeEach(() => { + fakeCodec.encode = util.noop; + backup = new Backup(INSTANCE, BACKUP_NAME); + }); + + afterEach(() => sandbox.restore()); + + describe('instantiation', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should localize the request function', () => { + assert.strictEqual(backup.request, INSTANCE.request); + }); + + it('should localize the formatted instance name', () => { + assert.strictEqual( + backup.instanceFormattedName_, + INSTANCE.formattedName_, + ); + }); + + it('should format the name', () => { + const formatName_ = Backup.formatName_; + const formattedName = 'formatted-name'; + + Backup.formatName_ = (instanceName, name) => { + Backup.formatName_ = formatName_; + + assert.strictEqual(instanceName, INSTANCE.formattedName_); + assert.strictEqual(name, BACKUP_NAME); + + return formattedName; + }; + + const backup = new Backup(INSTANCE, BACKUP_NAME); + assert(backup.formattedName_, formattedName); + }); + + it('should set the backup id', () => { + assert.strictEqual(backup.id, BACKUP_NAME); + }); + + it('should set the resourceHeader_', () => { + assert.deepStrictEqual(backup.resourceHeader_, { + [CLOUD_RESOURCE_HEADER]: backup.instanceFormattedName_, + }); + }); + }); + + describe('create', () => { + const INSTANCE_NAME = 'instance-name'; + const BACKUP_NAME = 'backup-name'; + + it('should make the correct request', done => { + const QUERY = {}; + const ORIGINAL_QUERY = extend({}, QUERY); + const expectedReqOpts = extend({}, QUERY, { + parent: INSTANCE_NAME, + backupId: BACKUP_NAME, + backup: { + name: BACKUP_FORMATTED_NAME, + database: DATABASE_FORMATTED_NAME, + expireTime: EXP_BACKUP_EXPIRE_TIME.toStruct(), + }, + }); + + backup.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'createBackup'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, QUERY); + assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); + assert.deepStrictEqual(config.headers, backup.resourceHeader_); + done(); + }; + + backup.create( + { + databasePath: DATABASE_FORMATTED_NAME, + expireTime: BACKUP_EXPIRE_TIME, + }, + assert.ifError, + ); + }); + + it('should accept gaxOptions and a callback', done => { + const gaxOptions = { + timeout: 1000, + }; + + backup.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + + backup.create( + { + databasePath: DATABASE_FORMATTED_NAME, + expireTime: BACKUP_EXPIRE_TIME, + gaxOptions, + }, + assert.ifError, + ); + }); + + it('should accept an encryption config', done => { + const encryptionConfig = { + encryptionType: EncryptionType.CUSTOMER_MANAGED_ENCRYPTION, + kmsKeyName: 'some/key/path', + }; + + backup.request = config => { + assert.strictEqual(config.reqOpts.encryptionConfig, encryptionConfig); + done(); + }; + + backup.create( + { + databasePath: DATABASE_FORMATTED_NAME, + expireTime: BACKUP_EXPIRE_TIME, + encryptionConfig, + }, + assert.ifError, + ); + }); + + it('should call Spanner.timestamp() with expireTime', done => { + const spanner_timestamp_ = Spanner.timestamp; + + Spanner.timestamp = timestamp => { + Spanner.timestamp = spanner_timestamp_; + + assert.deepStrictEqual(timestamp, BACKUP_EXPIRE_TIME); + + return EXP_BACKUP_EXPIRE_TIME; + }; + + backup.request = config => { + assert.deepStrictEqual( + config.reqOpts.backup.expireTime, + EXP_BACKUP_EXPIRE_TIME.toStruct(), + ); + done(); + }; + + backup.create( + { + databasePath: DATABASE_FORMATTED_NAME, + expireTime: BACKUP_EXPIRE_TIME, + }, + assert.ifError, + ); + }); + + it('versionTime should not be set by default', done => { + backup.request = config => { + assert.strictEqual(config.reqOpts.backup.versionTime, undefined); + done(); + }; + + backup.create( + { + databasePath: DATABASE_FORMATTED_NAME, + expireTime: BACKUP_EXPIRE_TIME, + }, + assert.ifError, + ); + }); + + it('should make request with versionTime when provided', done => { + backup.request = config => { + assert.deepStrictEqual( + config.reqOpts.backup.versionTime, + EXP_BACKUP_VERSION_TIME.toStruct(), + ); + done(); + }; + + backup.create( + { + databasePath: DATABASE_FORMATTED_NAME, + expireTime: BACKUP_EXPIRE_TIME, + versionTime: BACKUP_VERSION_TIME, + }, + assert.ifError, + ); + }); + + describe('error', () => { + const API_RESPONSE = {}; + const REQUEST_RESPONSE_ARGS = [new Error('Error.'), null, API_RESPONSE]; + + beforeEach(() => { + backup.request = (config, callback: Function) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + }); + + it('should execute callback with original arguments', done => { + backup.create( + { + databasePath: DATABASE_FORMATTED_NAME, + expireTime: BACKUP_EXPIRE_TIME, + }, + (err, bk, op, resp) => { + assert.deepStrictEqual(err, REQUEST_RESPONSE_ARGS[0]); + assert.strictEqual(bk, null); + assert.strictEqual(op, null); + assert.deepStrictEqual(resp, API_RESPONSE); + done(); + }, + ); + }); + }); + + describe('success', () => { + const OPERATION = {}; + const API_RESPONSE = {}; + + beforeEach(() => { + backup.request = (config, callback: Function) => { + callback(null, OPERATION, API_RESPONSE); + }; + }); + + it('should execute callback with a Backup and Operation', done => { + backup.create( + { + databasePath: DATABASE_FORMATTED_NAME, + expireTime: BACKUP_EXPIRE_TIME, + }, + (err, bk, op, resp) => { + assert.ifError(err); + assert.strictEqual(bk, backup); + assert.strictEqual(op, OPERATION); + assert.strictEqual(resp, API_RESPONSE); + done(); + }, + ); + }); + }); + }); + + describe('getMetadata', () => { + const BACKUP_NAME = 'backup-name'; + + it('should make the correct request', done => { + const QUERY = {}; + const ORIGINAL_QUERY = extend({}, QUERY); + const expectedReqOpts = extend({}, QUERY, { + name: BACKUP_FORMATTED_NAME, + }); + + backup.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'getBackup'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, QUERY); + assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); + assert.deepStrictEqual(config.headers, backup.resourceHeader_); + done(); + }; + + backup.getMetadata(assert.ifError); + }); + + it('should accept gaxOpts', done => { + const gaxOptions = { + timeout: 1000, + }; + + backup.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + + backup.getMetadata(gaxOptions, assert.ifError); + }); + + it('should get backup info', done => { + const INFO = { + name: 'backup-name', + database: 'database-name', + expireTime: BACKUP_EXPIRE_TIME, + }; + const fakeInfo = { + name: BACKUP_NAME, + database: DATABASE_NAME, + expireTime: BACKUP_EXPIRE_TIME, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const REQUEST_RESPONSE_ARGS: any = [null, INFO, {}]; + + backup.request = (config, callback: Function) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + + backup.getMetadata((...args) => { + assert.ifError(args[0]); + assert.strictEqual(args[0], REQUEST_RESPONSE_ARGS[0]); + const backupInfo = args[1]; + assert.deepStrictEqual(backupInfo, fakeInfo); + done(); + }); + }); + + it('should update metadata', done => { + const metadata = {}; + backup.request = (config: {}, callback: Function) => { + callback(null, metadata); + }; + backup.getMetadata(() => { + assert.strictEqual(backup.metadata, metadata); + done(); + }); + }); + + it('should call callback with error', done => { + const error = new Error('Error'); + backup.request = (config: {}, callback: Function) => { + callback(error); + }; + backup.getMetadata(err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('getState', () => { + it('should return the state from backup info', async () => { + const BACKUP_INFO_RESPONSE: GetMetadataResponse = [ + { + state: 'CREATING', + }, + ]; + backup.getMetadata = async () => BACKUP_INFO_RESPONSE; + + const result = await backup.getState(); + assert.strictEqual(result, 'CREATING'); + }); + + it('should throw errors', async () => { + const err = {code: grpc.status.INTERNAL}; + backup.getMetadata = async () => { + throw err; + }; + + try { + await backup.getState(); + assert.fail('Should have rethrown error'); + } catch (thrown) { + assert.deepStrictEqual(thrown, err); + } + }); + + it('should accept callback and return state', done => { + const BACKUP_INFO_RESPONSE: GetMetadataResponse = [ + { + state: 'CREATING', + }, + ]; + backup.getMetadata = async () => BACKUP_INFO_RESPONSE; + + backup.getState((err, state) => { + if (err) { + assert.ifError(err); + } + assert.strictEqual(state, 'CREATING'); + done(); + }); + }); + + it('should accept callback and return errors', done => { + const err = {code: grpc.status.INTERNAL}; + backup.getMetadata = async () => { + throw err; + }; + + backup.getState(error => { + assert.strictEqual(error, err); + done(); + }); + }); + }); + + describe('getExpireTime', () => { + it('should return the expire time from backup info', async () => { + const BACKUP_INFO_RESPONSE: GetMetadataResponse = [ + { + expireTime: EXP_BACKUP_EXPIRE_TIME.toStruct(), + }, + ]; + backup.getMetadata = async () => BACKUP_INFO_RESPONSE; + + const result = await backup.getExpireTime(); + assert.deepStrictEqual(result, EXP_BACKUP_EXPIRE_TIME); + }); + + it('should throw errors', async () => { + const err = {code: grpc.status.INTERNAL}; + backup.getMetadata = async () => { + throw err; + }; + + try { + await backup.getExpireTime(); + assert.fail('Should have rethrown error'); + } catch (thrown) { + assert.deepStrictEqual(thrown, err); + } + }); + + it('should accept callback and return the expire time from backup info', done => { + const BACKUP_INFO_RESPONSE: GetMetadataResponse = [ + { + expireTime: EXP_BACKUP_EXPIRE_TIME.toStruct(), + }, + ]; + backup.getMetadata = async () => BACKUP_INFO_RESPONSE; + + backup.getExpireTime((err, result) => { + assert.deepStrictEqual(result, EXP_BACKUP_EXPIRE_TIME); + done(); + }); + }); + + it('should accept callback and return errors', done => { + const err = {code: grpc.status.INTERNAL}; + backup.getMetadata = async () => { + throw err; + }; + + backup.getExpireTime(error => { + assert.deepStrictEqual(error, err); + done(); + }); + }); + }); + + describe('exists', () => { + it('should return true when backup info indicates backup exists', async () => { + const BACKUP_INFO_RESPONSE: GetMetadataResponse = [{}]; + backup.getMetadata = async () => BACKUP_INFO_RESPONSE; + + const result = await backup.exists(); + assert.strictEqual(result, true); + }); + + it('should return false when backup does not exist', async () => { + backup.getMetadata = async () => { + throw {code: grpc.status.NOT_FOUND}; + }; + + const result = await backup.exists(); + assert.strictEqual(result, false); + }); + + it('should rethrow other errors', async () => { + const err = {code: grpc.status.INTERNAL}; + backup.getMetadata = async () => { + throw err; + }; + + try { + await backup.exists(); + assert.fail('Should have rethrown error'); + } catch (thrown) { + assert.deepStrictEqual(thrown, err); + } + }); + + it('should accept backup and return true when backup info indicates backup exists', done => { + const BACKUP_INFO_RESPONSE: GetMetadataResponse = [{}]; + backup.getMetadata = async () => BACKUP_INFO_RESPONSE; + + backup.exists((err, result) => { + if (err) { + assert.ifError(err); + } + assert.strictEqual(result, true); + done(); + }); + }); + + it('should accept callback and return false when backup does not exist', done => { + backup.getMetadata = async () => { + throw {code: grpc.status.NOT_FOUND}; + }; + + backup.exists((err, result) => { + if (err) { + assert.ifError(err); + } + assert.strictEqual(result, false); + done(); + }); + }); + + it('should accept callback and return other errors', done => { + const err = {code: grpc.status.INTERNAL}; + backup.getMetadata = async () => { + throw err; + }; + + backup.exists(error => { + assert.strictEqual(error, err); + done(); + }); + }); + }); + + describe('updateExpireTime', () => { + const NEW_EXPIRE_TIME = '2019-03-08T10:34:29.481145231Z'; + const EXP_NEW_EXPIRE_TIME = Spanner.timestamp(NEW_EXPIRE_TIME); + + it('should make the correct request', done => { + const QUERY = {}; + const ORIGINAL_QUERY = extend({}, QUERY); + const expectedReqOpts = extend({}, QUERY, { + backup: { + name: BACKUP_FORMATTED_NAME, + expireTime: EXP_NEW_EXPIRE_TIME.toStruct(), + }, + updateMask: { + paths: ['expire_time'], + }, + }); + + backup.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'updateBackup'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, QUERY); + assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); + assert.deepStrictEqual(config.headers, backup.resourceHeader_); + done(); + }; + + backup.updateExpireTime(NEW_EXPIRE_TIME, assert.ifError); + }); + + it('should accept gaxOpts', done => { + const gaxOpts = { + timeout: 1000, + }; + + backup.request = config => { + assert.deepStrictEqual(config.gaxOpts, gaxOpts); + done(); + }; + + backup.updateExpireTime(NEW_EXPIRE_TIME, gaxOpts, assert.ifError); + }); + + it('should execute callback with the API resonse', done => { + const API_RESPONSE = { + name: 'backup-name', + database: 'database-name', + expireTime: EXP_NEW_EXPIRE_TIME, + }; + + backup.request = (config, callback: Function) => { + callback(null, API_RESPONSE); + }; + + backup.updateExpireTime(NEW_EXPIRE_TIME, (err, resp) => { + assert.ifError(err); + assert.strictEqual(resp, API_RESPONSE); + done(); + }); + }); + }); + + describe('delete', () => { + it('should make the correct request', done => { + const QUERY = {}; + const ORIGINAL_QUERY = extend({}, QUERY); + const expectedReqOpts = extend({}, QUERY, { + name: BACKUP_FORMATTED_NAME, + }); + + backup.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'deleteBackup'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, QUERY); + assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); + assert.deepStrictEqual(config.headers, backup.resourceHeader_); + done(); + }; + + void backup.delete(); + }); + + it('should accept gaxOpts', done => { + const gaxOpts = { + timeout: 1000, + }; + + backup.request = config => { + assert.deepStrictEqual(config.gaxOpts, gaxOpts); + done(); + }; + + backup.delete(gaxOpts, assert.ifError); + }); + + it('should execute callback with original arguments', done => { + const REQUEST_RESPONSE_ARGS = [new Error('Error.')]; + + backup.request = (config, callback: Function) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + + backup.delete(err => { + assert.deepStrictEqual(err, REQUEST_RESPONSE_ARGS[0]); + done(); + }); + }); + }); + + describe('formatName_', () => { + it('should return the name if already formatted', () => { + assert.strictEqual( + Backup.formatName_(INSTANCE.formattedName_, BACKUP_FORMATTED_NAME), + BACKUP_FORMATTED_NAME, + ); + }); + + it('should format the name', () => { + const formattedName_ = Backup.formatName_( + INSTANCE.formattedName_, + BACKUP_NAME, + ); + assert.strictEqual(formattedName_, BACKUP_FORMATTED_NAME); + }); + }); +}); diff --git a/handwritten/spanner/test/batch-transaction.ts b/handwritten/spanner/test/batch-transaction.ts new file mode 100644 index 00000000000..6f8d1389497 --- /dev/null +++ b/handwritten/spanner/test/batch-transaction.ts @@ -0,0 +1,557 @@ +/*! + * Copyright 2018 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable prefer-rest-params */ + +import {util} from '@google-cloud/common'; +import * as pfy from '@google-cloud/promisify'; +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; + +import {Session, Database, Spanner} from '../src'; +import {protos} from '../src'; +import * as bt from '../src/batch-transaction'; +import {PartialResultStream} from '../src/partial-result-stream'; +import { + CLOUD_RESOURCE_HEADER, + LEADER_AWARE_ROUTING_HEADER, +} from '../src/common'; +import {ExecuteSqlRequest} from '../src/transaction'; +import {CallOptions} from 'google-gax'; + +let promisified = false; +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'BatchTransaction') { + return; + } + assert.deepStrictEqual(options.exclude, ['identifier']); + promisified = true; + }, +}); + +class FakeTimestamp { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const fakeCodec: any = { + encode: util.noop, + Timestamp: FakeTimestamp, + Int() {}, + Float() {}, + SpannerDate() {}, + convertProtoTimestampToDate() {}, +}; + +const SPANNER = { + routeToLeaderEnabled: true, +}; + +const INSTANCE = { + parent: SPANNER, +}; + +const DATABASE = { + formattedName_: 'database', + parent: INSTANCE, +}; + +class FakeTransaction { + calledWith_: IArguments; + session; + constructor(session) { + this.calledWith_ = arguments; + this.session = session; + } + static encodeKeySet(): object { + return {}; + } + static encodeParams(): object { + return {}; + } + + _getSpanner(): Spanner { + return SPANNER as Spanner; + } + + run() {} + read() {} +} + +describe('BatchTransaction', () => { + const sandbox = sinon.createSandbox(); + + // tslint:disable-next-line variable-name + let BatchTransaction: typeof bt.BatchTransaction; + let batchTransaction: bt.BatchTransaction; + + const SESSION = { + parent: DATABASE, + // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any + delete: (callback: any) => {}, + }; + + before(() => { + BatchTransaction = proxyquire('../src/batch-transaction.js', { + '@google-cloud/precise-date': {PreciseDate: FakeTimestamp}, + '@google-cloud/promisify': fakePfy, + './codec.js': {codec: fakeCodec}, + './transaction.js': {Snapshot: FakeTransaction}, + }).BatchTransaction; + }); + + beforeEach(() => { + batchTransaction = new BatchTransaction(SESSION as {} as Session); + }); + + afterEach(() => sandbox.restore()); + + describe('instantiation', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should extend the Snapshot class', () => { + const batchTransaction = new BatchTransaction(SESSION as {} as Session); + assert(batchTransaction instanceof FakeTransaction); + }); + }); + + describe('close', () => { + it('should end the transaction', done => { + batchTransaction.end = done; + + batchTransaction.close(); + }); + }); + + describe('createQueryPartitions', () => { + const GAX_OPTS = {a: 'b'}; + + const fakeDirectedReadOptionsForRequest = { + includeReplicas: { + replicaSelections: [ + { + location: 'us-west1', + type: protos.google.spanner.v1.DirectedReadOptions.ReplicaSelection + .Type.READ_WRITE, + }, + ], + autoFailoverDisabled: true, + }, + }; + + const QUERY: ExecuteSqlRequest = { + sql: 'SELECT * FROM Singers', + gaxOptions: GAX_OPTS as CallOptions, + params: {}, + types: {}, + dataBoostEnabled: true, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + it('should make the correct request using callback', () => { + const fakeParams = { + params: {a: 'b'}, + paramTypes: {a: 'string'}, + dataBoostEnabled: true, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + const expectedQuery = Object.assign({sql: QUERY.sql}, fakeParams); + const stub = sandbox.stub(batchTransaction, 'createPartitions_'); + + (sandbox.stub(FakeTransaction, 'encodeParams') as sinon.SinonStub) + .withArgs(QUERY) + .returns(fakeParams); + + batchTransaction.createQueryPartitions(QUERY, assert.ifError); + + const {client, method, reqOpts, gaxOpts, headers} = stub.lastCall.args[0]; + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'partitionQuery'); + assert.deepStrictEqual(reqOpts, expectedQuery); + assert.strictEqual(gaxOpts, GAX_OPTS); + assert.deepStrictEqual( + headers, + Object.assign({[LEADER_AWARE_ROUTING_HEADER]: 'true'}), + ); + }); + + it('should accept query as string in a callback based request to createQueryPartitions', () => { + const query = 'SELECT * FROM Singers'; + + const expectedQuery = Object.assign({}, {sql: query}); + const stub = sandbox.stub(batchTransaction, 'createPartitions_'); + + (sandbox.stub(FakeTransaction, 'encodeParams') as sinon.SinonStub) + .withArgs({sql: query}) + .returns({sql: query}); + + batchTransaction.createQueryPartitions(query, assert.ifError); + + const {client, method, reqOpts, gaxOpts} = stub.lastCall.args[0]; + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'partitionQuery'); + assert.deepStrictEqual(reqOpts, expectedQuery); + assert.strictEqual(gaxOpts, undefined); + }); + + it('should make the correct request using await', async () => { + const fakeParams = { + params: {a: 'b'}, + paramTypes: {a: 'string'}, + dataBoostEnabled: true, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + const expectedQuery = Object.assign({sql: QUERY.sql}, fakeParams); + const stub = sandbox.stub(batchTransaction, 'createPartitions_'); + + (sandbox.stub(FakeTransaction, 'encodeParams') as sinon.SinonStub) + .withArgs(QUERY) + .returns(fakeParams); + + await batchTransaction.createQueryPartitions(QUERY); + + const {client, method, reqOpts, gaxOpts, headers} = stub.lastCall.args[0]; + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'partitionQuery'); + assert.deepStrictEqual(reqOpts, expectedQuery); + assert.strictEqual(gaxOpts, GAX_OPTS); + assert.deepStrictEqual( + headers, + Object.assign({[LEADER_AWARE_ROUTING_HEADER]: 'true'}), + ); + }); + }); + + describe('createPartitions_', () => { + const REQUEST = sandbox.stub(); + const SESSION = { + parent: DATABASE, + formattedName_: 'abcdef', + request: REQUEST, + }; + const ID = 'ghijkl'; + const TIMESTAMP = {seconds: 0, nanos: 0}; + + const PARTITIONS = [{partitionToken: 'a'}, {partitionToken: 'b'}]; + const RESPONSE = {partitions: PARTITIONS}; + + const QUERY = {a: 'b'}; + const CONFIG = {reqOpts: QUERY}; + + beforeEach(() => { + batchTransaction.session = SESSION as {} as Session; + batchTransaction.id = ID; + + REQUEST.callsFake((_, callback) => callback(null, RESPONSE)); + }); + + it('should insert the session and transaction ids', () => { + batchTransaction.createPartitions_(CONFIG, assert.ifError); + + const {reqOpts} = REQUEST.lastCall.args[0]; + assert.strictEqual(reqOpts.a, 'b'); + assert.strictEqual(reqOpts.session, SESSION.formattedName_); + assert.deepStrictEqual(reqOpts.transaction, {id: ID}); + }); + + it('should pass headers', done => { + batchTransaction.createPartitions_(CONFIG, assert.ifError); + const {headers} = REQUEST.lastCall.args[0]; + assert.deepStrictEqual(headers, { + [CLOUD_RESOURCE_HEADER]: (batchTransaction.session.parent as Database) + .formattedName_, + }); + done(); + }); + + it('should return any request errors', done => { + const error = new Error('err'); + const response = {}; + + REQUEST.callsFake((_, callback) => callback(error, response)); + + batchTransaction.createPartitions_(CONFIG, (err, parts, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(parts, null); + assert.strictEqual(resp, response); + done(); + }); + }); + + it('should return the prepared partition configs', done => { + const expectedQuery = { + a: 'b', + session: SESSION.formattedName_, + transaction: {id: ID}, + }; + + batchTransaction.createPartitions_(CONFIG, (err, parts) => { + assert.ifError(err); + + parts.forEach((partition, i) => { + const expectedPartition = extend({}, expectedQuery, PARTITIONS[i]); + assert.deepStrictEqual(partition, expectedPartition); + }); + + done(); + }); + }); + + it('should update the transaction with returned metadata', done => { + const response = extend({}, RESPONSE, { + transaction: { + id: ID, + readTimestamp: TIMESTAMP, + }, + }); + + REQUEST.callsFake((_, callback) => callback(null, response)); + + batchTransaction.createPartitions_(CONFIG, (err, parts, resp) => { + assert.strictEqual(resp, response); + assert.strictEqual(batchTransaction.id, ID); + assert.strictEqual(batchTransaction.readTimestampProto, TIMESTAMP); + + const timestamp = + batchTransaction.readTimestamp as unknown as FakeTimestamp; + assert(timestamp instanceof FakeTimestamp); + assert.strictEqual(timestamp.calledWith_[0], TIMESTAMP); + + done(); + }); + }); + }); + + describe('createReadPartitions', () => { + const GAX_OPTS = {}; + + const fakeDirectedReadOptionsForRequest = { + includeReplicas: { + replicaSelections: [ + { + location: 'us-west1', + type: protos.google.spanner.v1.DirectedReadOptions.ReplicaSelection + .Type.READ_WRITE, + }, + ], + autoFailoverDisabled: true, + }, + }; + + const QUERY = { + table: 'abc', + keys: ['a', 'b'], + ranges: [{}, {}], + gaxOptions: GAX_OPTS, + dataBoostEnabled: true, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + it('should make the correct request using callback', () => { + const fakeKeySet = {}; + const expectedQuery = { + table: QUERY.table, + keySet: fakeKeySet, + dataBoostEnabled: true, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + const stub = sandbox.stub(batchTransaction, 'createPartitions_'); + + (sandbox.stub(FakeTransaction, 'encodeKeySet') as sinon.SinonStub) + .withArgs(QUERY) + .returns(fakeKeySet); + + batchTransaction.createReadPartitions(QUERY, assert.ifError); + + const {client, method, reqOpts, gaxOpts, headers} = stub.lastCall.args[0]; + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'partitionRead'); + assert.deepStrictEqual(reqOpts, expectedQuery); + assert.strictEqual(gaxOpts, GAX_OPTS); + assert.deepStrictEqual( + headers, + Object.assign({[LEADER_AWARE_ROUTING_HEADER]: 'true'}), + ); + }); + + it('should make the correct request using await', async () => { + const fakeKeySet = {}; + const expectedQuery = { + table: QUERY.table, + keySet: fakeKeySet, + dataBoostEnabled: true, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + const stub = sandbox.stub(batchTransaction, 'createPartitions_'); + + (sandbox.stub(FakeTransaction, 'encodeKeySet') as sinon.SinonStub) + .withArgs(QUERY) + .returns(fakeKeySet); + + await batchTransaction.createReadPartitions(QUERY); + + const {client, method, reqOpts, gaxOpts, headers} = stub.lastCall.args[0]; + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'partitionRead'); + assert.deepStrictEqual(reqOpts, expectedQuery); + assert.strictEqual(gaxOpts, GAX_OPTS); + assert.deepStrictEqual( + headers, + Object.assign({[LEADER_AWARE_ROUTING_HEADER]: 'true'}), + ); + }); + }); + + describe('execute', () => { + const directedReadOptionsForRequest = { + includeReplicas: { + replicaSelections: [ + { + type: protos.google.spanner.v1.DirectedReadOptions.ReplicaSelection + .Type.READ_ONLY, + }, + ], + autoFailoverDisabled: true, + }, + }; + + it('should make read requests for read partitions using callback', () => { + const partition = {table: 'abc'}; + const stub = sandbox.stub(batchTransaction, 'read'); + + batchTransaction.execute(partition, assert.ifError); + + const [table, options] = stub.lastCall.args; + assert.strictEqual(table, partition.table); + assert.strictEqual(options, partition); + }); + + it('should make query requests for non-read partitions', () => { + const partition = {sql: 'SELECT * FROM Singers'}; + const stub = sandbox.stub(batchTransaction, 'run'); + + batchTransaction.execute(partition, assert.ifError); + + const query = stub.lastCall.args[0]; + assert.strictEqual(query, partition); + }); + + it('should make read requests for read partitions with request options', () => { + const partition = { + table: 'abc', + dataBoostEnabled: true, + directedReadOptions: directedReadOptionsForRequest, + }; + const stub = sandbox.stub(batchTransaction, 'read'); + + batchTransaction.execute(partition, assert.ifError); + + const [table, options] = stub.lastCall.args; + assert.strictEqual(table, partition.table); + assert.strictEqual(options, partition); + }); + + it('should make query requests for non-read partitions with request options', () => { + const partition = { + sql: 'SELECT * FROM Singers', + dataBoostEnabled: true, + directedReadOptions: directedReadOptionsForRequest, + }; + const stub = sandbox.stub(batchTransaction, 'run'); + + batchTransaction.execute(partition, assert.ifError); + + const query = stub.lastCall.args[0]; + assert.strictEqual(query, partition); + }); + + it('should make read requests for read partitions using await', async () => { + const partition = {table: 'abc'}; + const stub = sandbox.stub(batchTransaction, 'read'); + + await batchTransaction.execute(partition); + + const [table, options] = stub.lastCall.args; + assert.strictEqual(table, partition.table); + assert.strictEqual(options, partition); + }); + }); + + describe('executeStream', () => { + const STREAM = {} as PartialResultStream; + + it('should make read streams for read partitions', () => { + const partition = {table: 'abc'}; + + batchTransaction.createReadStream = (table, options) => { + assert.strictEqual(table, partition.table); + assert.strictEqual(options, partition); + return STREAM; + }; + + const stream = batchTransaction.executeStream(partition); + + assert.strictEqual(stream, STREAM); + }); + + it('should make query streams for query partitions', () => { + const partition = {sql: 'SELECT * FROM Singers'}; + + batchTransaction.runStream = query => { + assert.strictEqual(query, partition); + return STREAM; + }; + + const stream = batchTransaction.executeStream(partition); + + assert.strictEqual(stream, STREAM); + }); + }); + + describe('identifier', () => { + const ID = Buffer.from('abc'); + const SESSION = {id: 'def'}; + const TIMESTAMP = {seconds: 0, nanos: 0}; + + beforeEach(() => { + batchTransaction.id = ID; + batchTransaction.session = SESSION as unknown as Session; + batchTransaction.readTimestampProto = TIMESTAMP; + }); + + it('should create a transaction identifier', () => { + const expectedId = ID.toString('base64'); + const identifier = batchTransaction.identifier(); + + assert.strictEqual(identifier.transaction, expectedId); + assert.strictEqual(identifier.session, SESSION.id); + assert.strictEqual(identifier.timestamp, TIMESTAMP); + }); + }); +}); diff --git a/handwritten/spanner/test/codec.ts b/handwritten/spanner/test/codec.ts new file mode 100644 index 00000000000..6406ad66067 --- /dev/null +++ b/handwritten/spanner/test/codec.ts @@ -0,0 +1,2168 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import {Big} from 'big.js'; +import {PreciseDate} from '@google-cloud/precise-date'; +import {GrpcService} from '../src/common-grpc/service'; +import {google} from '../protos/protos'; +import {GoogleError} from 'google-gax'; +import {util} from 'protobufjs'; +import * as uuid from 'uuid'; +import Long = util.Long; +import {isString} from '../src/helper'; +const singer = require('./data/singer'); +const music = singer.examples.spanner.music; + +describe('codec', () => { + let codec; + + const sandbox = sinon.createSandbox(); + + before(() => { + codec = proxyquire('../src/codec.js', { + './common-grpc/service': {GrpcService}, + }).codec; + }); + + beforeEach(() => { + sandbox.stub(GrpcService, 'encodeValue_').callsFake(value => value); + sandbox.stub(GrpcService, 'decodeValue_').callsFake(value => value); + }); + + afterEach(() => sandbox.restore()); + + describe('SpannerDate', () => { + describe('instantiation', () => { + it('should accept date strings', () => { + const date = new codec.SpannerDate('3-22-1986'); + const json = date.toJSON(); + + assert.strictEqual(json, '1986-03-22'); + }); + + it('should accept dates before 1000AD', () => { + const date = new codec.SpannerDate('2-25-985'); + const json = date.toJSON(); + + assert.strictEqual(json, '0985-02-25'); + }); + + it('should default to the current local date', () => { + const date = new codec.SpannerDate(); + const today = new Date(); + const year = today.getFullYear(); + const month = today.getMonth(); + const day = today.getDate(); + const expected = new codec.SpannerDate(year, month, day); + + assert.deepStrictEqual(date, expected); + }); + + it('should interpret ISO date strings as local time', () => { + const date = new codec.SpannerDate('1986-03-22'); + const json = date.toJSON(); + + assert.strictEqual(json, '1986-03-22'); + }); + + it('should accept y/m/d number values', () => { + const date = new codec.SpannerDate(1986, 2, 22); + const json = date.toJSON(); + + assert.strictEqual(json, '1986-03-22'); + }); + + it('should accept year zero in y/m/d number values', () => { + const d = new codec.SpannerDate(null!); + const date = new codec.SpannerDate(0, 2, 22); + const json = date.toJSON(); + + assert.ok(d); + assert.strictEqual(json, '1900-03-22'); + }); + + it('should truncate additional date fields', () => { + const truncated = new codec.SpannerDate(1986, 2, 22, 4, 8, 10); + const expected = new codec.SpannerDate(1986, 2, 22); + + assert.deepStrictEqual(truncated, expected); + }); + }); + + describe('toJSON', () => { + let date: Date; + + beforeEach(() => { + date = new codec.SpannerDate(); + sandbox.stub(date, 'getFullYear').returns(1999); + sandbox.stub(date, 'getMonth').returns(11); + sandbox.stub(date, 'getDate').returns(31); + }); + + it('should return the spanner date string', () => { + const json = date.toJSON(); + assert.strictEqual(json, '1999-12-31'); + }); + + it('should pad single digit months', () => { + (date.getMonth as sinon.SinonStub).returns(8); + const json = date.toJSON(); + assert.strictEqual(json, '1999-09-31'); + }); + + it('should pad single digit dates', () => { + (date.getDate as sinon.SinonStub).returns(3); + const json = date.toJSON(); + assert.strictEqual(json, '1999-12-03'); + }); + + it('should pad single digit years', () => { + (date.getFullYear as sinon.SinonStub).returns(5); + const json = date.toJSON(); + assert.strictEqual(json, '0005-12-31'); + }); + + it('should pad double digit years', () => { + (date.getFullYear as sinon.SinonStub).returns(52); + const json = date.toJSON(); + assert.strictEqual(json, '0052-12-31'); + }); + + it('should pad triple digit years', () => { + (date.getFullYear as sinon.SinonStub).returns(954); + const json = date.toJSON(); + assert.strictEqual(json, '0954-12-31'); + }); + }); + }); + + describe('Float', () => { + it('should store the value', () => { + const value = 8; + const float = new codec.Float(value); + + assert.strictEqual(float.value, value); + }); + + it('should return as a float', () => { + const value = '8.2'; + const float = new codec.Float(value); + + assert.strictEqual(float.valueOf(), Number(value)); + assert.strictEqual(float + 2, Number(value) + 2); + }); + }); + + describe('Float32', () => { + it('should store the value', () => { + const value = 8; + const float32 = new codec.Float32(value); + + assert.strictEqual(float32.value, value); + }); + + it('should return as a float32', () => { + const value = '8.2'; + const float32 = new codec.Float32(value); + + assert.strictEqual(float32.valueOf(), Number(value)); + assert.strictEqual(float32 + 2, Number(value) + 2); + }); + }); + + describe('Int', () => { + it('should stringify the value', () => { + const value = 8; + const int = new codec.Int(value); + + assert.strictEqual(int.value, '8'); + }); + + it('should return as a number', () => { + const value = 8; + const int = new codec.Int(value); + + assert.strictEqual(int.valueOf(), 8); + assert.strictEqual(int + 2, 10); + }); + + it('should throw if number is out of bounds', () => { + const value = '9223372036854775807'; + const int = new codec.Int(value); + + assert.throws( + () => { + int.valueOf(); + }, + new RegExp('Integer ' + value + ' is out of bounds.'), + ); + }); + }); + + describe('PGOid', () => { + it('should stringify the value', () => { + const value = 8; + const oid = new codec.PGOid(value); + + assert.strictEqual(oid.value, '8'); + }); + + it('should return as a number', () => { + const value = 8; + const oid = new codec.PGOid(value); + + assert.strictEqual(oid.valueOf(), 8); + assert.strictEqual(oid + 2, 10); + }); + + it('should throw if number is out of bounds', () => { + const value = '9223372036854775807'; + const oid = new codec.PGOid(value); + + assert.throws( + () => { + oid.valueOf(); + }, + new RegExp('PG.OID ' + value + ' is out of bounds.'), + ); + }); + }); + + describe('Numeric', () => { + it('should store value as a string', () => { + const value = '8.01911'; + const numeric = new codec.Numeric(value); + + assert.strictEqual(numeric.value, '8.01911'); + }); + + it('should return as a Big', () => { + const value = '8.01911'; + const numeric = new codec.Numeric(value); + + const expected = new Big(value); + assert.ok(numeric.valueOf().eq(expected)); + }); + + it('toJSON', () => { + const value = '8.01911'; + const numeric = new codec.Numeric(value); + + assert.strictEqual(numeric.toJSON(), value); + }); + }); + + describe('PGNumeric', () => { + it('should store value as a string', () => { + const value = '8.01911'; + const pgNumeric = new codec.PGNumeric(value); + + assert.strictEqual(pgNumeric.value, '8.01911'); + }); + + it('should store NaN value as a string', () => { + const value = 'NaN'; + const pgNumeric = new codec.PGNumeric(value); + + assert.strictEqual(pgNumeric.value, 'NaN'); + }); + + it('should return as a Big', () => { + const value = '8.01911'; + const pgNumeric = new codec.PGNumeric(value); + + const expected = new Big(value); + assert.ok(pgNumeric.valueOf().eq(expected)); + }); + + it('should throw an error when trying to return NaN as a Big', () => { + const value = 'NaN'; + const pgNumeric = new codec.PGNumeric(value); + + assert.throws(() => { + pgNumeric.valueOf(); + }, new RegExp('NaN cannot be converted to a numeric value')); + }); + + it('toJSON', () => { + const value = '8.01911'; + const pgNumeric = new codec.PGNumeric(value); + + assert.strictEqual(pgNumeric.toJSON(), value); + }); + }); + + describe('Interval', () => { + describe('constructor', () => { + it('should create an Interval instance with correct properties', () => { + const interval = new codec.Interval(1, 2, BigInt(1000)); + assert.equal(interval.getMonths(), 1); + assert.equal(interval.getDays(), 2); + assert.equal(interval.getNanoseconds(), BigInt(1000)); + }); + + it('should throw an error if months is not an integer', () => { + assert.throws( + () => new codec.Interval(1.5, 2, BigInt(1000)), + new RegExp('Invalid months: 1.5, months should be an integral value'), + ); + }); + + it('should throw an error if days is not an integer', () => { + assert.throws( + () => new codec.Interval(1, 2.5, BigInt(1000)), + new RegExp('Invalid days: 2.5, days should be an integral value'), + ); + }); + + it('should throw an error if days is not an integer', () => { + assert.throws( + () => new codec.Interval(1, 2, null), + new RegExp( + 'Invalid nanoseconds: null, nanoseconds should be a valid bigint value', + ), + ); + }); + }); + + describe('fromMonths', () => { + it('should create an Interval from months', () => { + const interval = codec.Interval.fromMonths(5); + assert.equal(interval.getMonths(), 5); + assert.equal(interval.getDays(), 0); + assert.equal(interval.getNanoseconds(), BigInt(0)); + }); + + it('should throw an error if input is undefined', () => { + assert.throws(() => codec.Interval.fromMonths(undefined), GoogleError); + }); + + it('should throw an error if input is null', () => { + assert.throws(() => codec.Interval.fromMonths(null), GoogleError); + }); + }); + + describe('fromDays', () => { + it('should create an Interval from days', () => { + const interval = codec.Interval.fromDays(10); + assert.equal(interval.getMonths(), 0); + assert.equal(interval.getDays(), 10); + assert.equal(interval.getNanoseconds(), BigInt(0)); + }); + + it('should throw an error if input is undefined', () => { + assert.throws(() => codec.Interval.fromDays(undefined), GoogleError); + }); + + it('should throw an error if input is null', () => { + assert.throws(() => codec.Interval.fromDays(null), GoogleError); + }); + }); + + describe('fromSeconds', () => { + it('should create an Interval from seconds', () => { + const interval = codec.Interval.fromSeconds(60); + assert.equal(interval.getMonths(), 0); + assert.equal(interval.getDays(), 0); + assert.equal(interval.getNanoseconds(), BigInt(60 * 1000000000)); + }); + + it('should throw an error if input is undefined', () => { + assert.throws(() => codec.Interval.fromSeconds(undefined), GoogleError); + }); + + it('should throw an error if input is null', () => { + assert.throws(() => codec.Interval.fromSeconds(null), GoogleError); + }); + }); + + describe('fromMilliseconds', () => { + it('should create an Interval from milliseconds', () => { + const interval = codec.Interval.fromMilliseconds(1000); + assert.equal(interval.getMonths(), 0); + assert.equal(interval.getDays(), 0); + assert.equal(interval.getNanoseconds(), BigInt(1000 * 1000000)); + }); + + it('should throw an error if input is undefined', () => { + assert.throws( + () => codec.Interval.fromMilliseconds(undefined), + GoogleError, + ); + }); + + it('should throw an error if input is null', () => { + assert.throws(() => codec.Interval.fromMilliseconds(null), GoogleError); + }); + }); + + describe('fromMicroseconds', () => { + it('should create an Interval from microseconds', () => { + const interval = codec.Interval.fromMicroseconds(1000000); + assert.equal(interval.getMonths(), 0); + assert.equal(interval.getDays(), 0); + assert.equal(interval.getNanoseconds(), BigInt(1000000 * 1000)); + }); + + it('should throw an error if input is undefined', () => { + assert.throws( + () => codec.Interval.fromMicroseconds(undefined), + GoogleError, + ); + }); + + it('should throw an error if input is null', () => { + assert.throws(() => codec.Interval.fromMicroseconds(null), GoogleError); + }); + }); + + describe('fromNanoseconds', () => { + it('should create an Interval from nanoseconds', () => { + const interval = codec.Interval.fromNanoseconds(BigInt(1000000000)); + assert.equal(interval.getMonths(), 0); + assert.equal(interval.getDays(), 0); + assert.equal(interval.getNanoseconds(), BigInt(1000000000)); + }); + + it('should throw an error if input is undefined', () => { + assert.throws( + () => codec.Interval.fromNanoseconds(undefined), + GoogleError, + ); + }); + + it('should throw an error if input is null', () => { + assert.throws(() => codec.Interval.fromNanoseconds(null), GoogleError); + }); + }); + + describe('fromISO8601', () => { + it('should parse valid ISO8601 strings correctly', () => { + const testCases = [ + { + input: 'P1Y2M3DT12H12M6.789000123S', + expected: new codec.Interval(14, 3, BigInt('43926789000123')), + }, + { + input: 'P1Y2M3DT13H-48M6S', + expected: new codec.Interval(14, 3, BigInt('43926000000000')), + }, + { + input: 'P1Y2M3D', + expected: new codec.Interval(14, 3, BigInt('0')), + }, + { + input: 'P1Y2M', + expected: new codec.Interval(14, 0, BigInt('0')), + }, + { + input: 'P1Y', + expected: new codec.Interval(12, 0, BigInt('0')), + }, + { + input: 'P2M', + expected: new codec.Interval(2, 0, BigInt('0')), + }, + { + input: 'P3D', + expected: new codec.Interval(0, 3, BigInt('0')), + }, + { + input: 'PT4H25M6.7890001S', + expected: new codec.Interval(0, 0, BigInt('15906789000100')), + }, + { + input: 'PT4H25M6S', + expected: new codec.Interval(0, 0, BigInt('15906000000000')), + }, + { + input: 'PT4H30S', + expected: new codec.Interval(0, 0, BigInt('14430000000000')), + }, + { + input: 'PT4H1M', + expected: new codec.Interval(0, 0, BigInt('14460000000000')), + }, + { + input: 'PT5M', + expected: new codec.Interval(0, 0, BigInt('300000000000')), + }, + { + input: 'PT6.789S', + expected: new codec.Interval(0, 0, BigInt('6789000000')), + }, + { + input: 'PT0.123S', + expected: new codec.Interval(0, 0, BigInt('123000000')), + }, + { + input: 'PT.000000123S', + expected: new codec.Interval(0, 0, BigInt('123')), + }, + { + input: 'P0Y', + expected: new codec.Interval(0, 0, BigInt('0')), + }, + { + input: 'P-1Y-2M-3DT-12H-12M-6.789000123S', + expected: new codec.Interval(-14, -3, BigInt('-43926789000123')), + }, + { + input: 'P1Y-2M3DT13H-51M6.789S', + expected: new codec.Interval(10, 3, BigInt('43746789000000')), + }, + { + input: 'P-1Y2M-3DT-13H49M-6.789S', + expected: new codec.Interval(-10, -3, BigInt('-43866789000000')), + }, + { + input: 'P1Y2M3DT-4H25M-6.7890001S', + expected: new codec.Interval(14, 3, BigInt('-12906789000100')), + }, + { + input: 'PT100H100M100.5S', + expected: new codec.Interval(0, 0, BigInt('366100500000000')), + }, + { + input: 'P0Y', + expected: new codec.Interval(0, 0, BigInt('0')), + }, + { + input: 'PT12H30M1S', + expected: new codec.Interval(0, 0, BigInt('45001000000000')), + }, + { + input: 'P1Y2M3D', + expected: new codec.Interval(14, 3, BigInt('0')), + }, + { + input: 'P1Y2M3DT12H30M', + expected: new codec.Interval(14, 3, BigInt('45000000000000')), + }, + { + input: 'PT0.123456789S', + expected: new codec.Interval(0, 0, BigInt('123456789')), + }, + { + input: 'PT1H0.5S', + expected: new codec.Interval(0, 0, BigInt('3600500000000')), + }, + { + input: 'P1Y2M3DT12H30M1.23456789S', + expected: new codec.Interval(14, 3, BigInt('45001234567890')), + }, + { + input: 'P1Y2M3DT12H30M1,23456789S', + expected: new codec.Interval(14, 3, BigInt('45001234567890')), + }, + { + input: 'PT.5S', + expected: new codec.Interval(0, 0, BigInt('500000000')), + }, + { + input: 'P-1Y2M3DT12H-30M1.234S', + expected: new codec.Interval(-10, 3, BigInt('41401234000000')), + }, + { + input: 'P1Y-2M3DT-12H30M-1.234S', + expected: new codec.Interval(10, 3, BigInt('-41401234000000')), + }, + { + input: 'PT1.234000S', + expected: new codec.Interval(0, 0, BigInt('1234000000')), + }, + { + input: 'PT1.000S', + expected: new codec.Interval(0, 0, BigInt('1000000000')), + }, + { + input: 'PT87840000H', + expected: new codec.Interval(0, 0, BigInt('316224000000000000000')), + }, + { + input: 'PT-87840000H', + expected: new codec.Interval( + 0, + 0, + BigInt('-316224000000000000000'), + ), + }, + { + input: 'P2Y1M15DT87839999H59M59.999999999S', + expected: new codec.Interval( + 25, + 15, + BigInt('316223999999999999999'), + ), + }, + { + input: 'P2Y1M15DT-87839999H-59M-59.999999999S', + expected: new codec.Interval( + 25, + 15, + BigInt('-316223999999999999999'), + ), + }, + ]; + + testCases.forEach(({input, expected}) => { + assert.deepStrictEqual(codec.Interval.fromISO8601(input), expected); + }); + }); + + it('should throw error for invalid ISO8601 strings', () => { + const invalidStrings = [ + 'invalid', + 'P', + 'PT', + 'P1YM', + 'P1Y2M3D4H5M6S', // Missing T + 'P1Y2M3DT4H5M6.S', // Missing decimal value + 'P1Y2M3DT4H5M6.789SS', // Extra S + 'P1Y2M3DT4H5M6.', // Missing value after decimal point + 'P1Y2M3DT4H5M6.ABC', // Non-digit characters after decimal point + 'P1Y2M3', // Missing unit specifier + 'P1Y2M3DT', // Missing time components + 'P-T1H', // Invalid negative sign position + 'PT1H-', // Invalid negative sign position + 'P1Y2M3DT4H5M6.789123456789S', // Too many digits after decimal + 'P1Y2M3DT4H5M6.123.456S', // Multiple decimal points + 'P1Y2M3DT4H5M6.,789S', // Dot and comma both for decimal + null, + undefined, + ]; + + invalidStrings.forEach(str => { + assert.throws( + () => { + codec.Interval.fromISO8601(str); + }, + new RegExp('Invalid ISO8601 duration string'), + `Expected exception on parsing ${str}`, + ); + }); + }); + + it('should throw error when months is not a safe integer', () => { + // Assuming Number.MAX_SAFE_INTEGER / 12 is the max safe years + const maxSafeYears = Math.ceil(Number.MAX_SAFE_INTEGER / 12); + const invalidISOString = `P${maxSafeYears}Y4M`; + assert.throws(() => { + codec.Interval.fromISO8601(invalidISOString); + }, new RegExp('Total months is outside of the range of safe integer')); + }); + }); + + describe('toISO8601', () => { + it('should convert Interval to valid ISO8601 strings', () => { + const testCases = [ + {input: new codec.Interval(0, 0, BigInt(0)), expected: 'P0Y'}, + { + input: new codec.Interval(14, 3, BigInt(43926789000123)), + expected: 'P1Y2M3DT12H12M6.789000123S', + }, + { + input: new codec.Interval(14, 3, BigInt(14706789000000)), + expected: 'P1Y2M3DT4H5M6.789S', + }, + {input: new codec.Interval(14, 3, BigInt(0)), expected: 'P1Y2M3D'}, + {input: new codec.Interval(14, 0, BigInt(0)), expected: 'P1Y2M'}, + {input: new codec.Interval(12, 0, BigInt(0)), expected: 'P1Y'}, + {input: new codec.Interval(2, 0, BigInt(0)), expected: 'P2M'}, + {input: new codec.Interval(0, 3, BigInt(0)), expected: 'P3D'}, + { + input: new codec.Interval(0, 0, BigInt(15906789000000)), + expected: 'PT4H25M6.789S', + }, + { + input: new codec.Interval(0, 0, BigInt(14430000000000)), + expected: 'PT4H30S', + }, + { + input: new codec.Interval(0, 0, BigInt(300000000000)), + expected: 'PT5M', + }, + { + input: new codec.Interval(0, 0, BigInt(6789000000)), + expected: 'PT6.789S', + }, + { + input: new codec.Interval(0, 0, BigInt(123000000)), + expected: 'PT0.123S', + }, + { + input: new codec.Interval(0, 0, BigInt(123)), + expected: 'PT0.000000123S', + }, + { + input: new codec.Interval(0, 0, BigInt(100000000)), + expected: 'PT0.100S', + }, + { + input: new codec.Interval(0, 0, BigInt(100100000)), + expected: 'PT0.100100S', + }, + { + input: new codec.Interval(0, 0, BigInt(100100100)), + expected: 'PT0.100100100S', + }, + { + input: new codec.Interval(0, 0, BigInt(9)), + expected: 'PT0.000000009S', + }, + { + input: new codec.Interval(0, 0, BigInt(9000)), + expected: 'PT0.000009S', + }, + { + input: new codec.Interval(0, 0, BigInt(9000000)), + expected: 'PT0.009S', + }, + {input: new codec.Interval(0, 0, BigInt(0)), expected: 'P0Y'}, + {input: new codec.Interval(0, 0, BigInt(0)), expected: 'P0Y'}, + {input: new codec.Interval(1, 0, BigInt(0)), expected: 'P1M'}, + {input: new codec.Interval(0, 1, BigInt(0)), expected: 'P1D'}, + { + input: new codec.Interval(0, 0, BigInt(10010)), + expected: 'PT0.000010010S', + }, + { + input: new codec.Interval(-14, -3, BigInt(-43926789000123)), + expected: 'P-1Y-2M-3DT-12H-12M-6.789000123S', + }, + { + input: new codec.Interval(10, 3, BigInt(43746789100000)), + expected: 'P10M3DT12H9M6.789100S', + }, + { + input: new codec.Interval(-10, -3, BigInt(-43866789010000)), + expected: 'P-10M-3DT-12H-11M-6.789010S', + }, + { + input: new codec.Interval(14, 3, BigInt(-12906662400000)), + expected: 'P1Y2M3DT-3H-35M-6.662400S', + }, + { + input: new codec.Interval(0, 0, BigInt(500000000)), + expected: 'PT0.500S', + }, + { + input: new codec.Interval(0, 0, BigInt(-500000000)), + expected: 'PT-0.500S', + }, + { + input: new codec.Interval(0, 0, BigInt('316224000000000000000')), + expected: 'PT87840000H', + }, + { + input: new codec.Interval(0, 0, BigInt('-316224000000000000000')), + expected: 'PT-87840000H', + }, + { + input: new codec.Interval(25, 15, BigInt('316223999999999999999')), + expected: 'P2Y1M15DT87839999H59M59.999999999S', + }, + { + input: new codec.Interval(25, 15, BigInt('-316223999999999999999')), + expected: 'P2Y1M15DT-87839999H-59M-59.999999999S', + }, + {input: new codec.Interval(13, 0, BigInt(0)), expected: 'P1Y1M'}, + { + input: new codec.Interval(0, 0, BigInt(86400000000000)), + expected: 'PT24H', + }, + {input: new codec.Interval(0, 31, BigInt(0)), expected: 'P31D'}, + {input: new codec.Interval(-12, 0, BigInt(0)), expected: 'P-1Y'}, + ]; + + testCases.forEach(({input, expected}) => { + assert.equal(input.toISO8601(), expected); + }); + }); + }); + + it('should check equality correctly', () => { + const interval1 = new codec.Interval(1, 2, BigInt(3)); + const interval2 = new codec.Interval(1, 2, BigInt(3)); + const interval3 = new codec.Interval(-4, -5, BigInt(-6)); // Negative values + + // Test with identical intervals + assert.equal(interval1.equals(interval2), true); + assert.equal(interval2.equals(interval1), true); + + // Test with different intervals + assert.equal(interval1.equals(interval3), false); + assert.equal(interval3.equals(interval1), false); + + // Test with different values for each field (including negative) + assert.equal( + interval1.equals(new codec.Interval(1, 2, BigInt(-4))), + false, + ); + assert.equal( + interval1.equals(new codec.Interval(1, -3, BigInt(3))), + false, + ); + assert.equal( + interval1.equals(new codec.Interval(-2, 2, BigInt(3))), + false, + ); + assert.equal( + interval3.equals(new codec.Interval(-4, -5, BigInt(6))), + false, + ); + assert.equal( + interval3.equals(new codec.Interval(-4, 5, BigInt(-6))), + false, + ); + assert.equal( + interval3.equals(new codec.Interval(4, -5, BigInt(-6))), + false, + ); + + // Test with null and undefined + assert.equal(interval1.equals(null), false); + assert.equal(interval1.equals(undefined), false); + + // Test with an object that is not an Interval + assert.equal(interval1.equals({} as BigInt), false); + }); + + it('should return the correct value with valueOf()', () => { + const interval = new codec.Interval(1, 2, BigInt(3)); + assert.equal(interval.valueOf(), interval); + }); + + it('should return the correct JSON representation', () => { + const interval = new codec.Interval(1, 2, BigInt(3)); + const expectedJson = interval.toISO8601(); + assert.equal(interval.toJSON(), expectedJson); + }); + + describe('ISO8601 roundtrip', () => { + it('should convert Interval to ISO8601 and back without losing data', () => { + const testCases = [ + new codec.Interval(14, 3, BigInt('43926789000000')), + new codec.Interval(12, 0, BigInt(0)), + new codec.Interval(1, 0, BigInt(0)), + new codec.Interval(0, 1, BigInt(0)), + new codec.Interval(0, 0, BigInt(3600000000000)), + new codec.Interval(0, 0, BigInt(60000000000)), + new codec.Interval(0, 0, BigInt(1000000000)), + new codec.Interval(0, 0, BigInt(100000000)), + new codec.Interval(0, 0, BigInt(0)), + new codec.Interval(-10, 3, BigInt('43926000000000')), + new codec.Interval(25, 15, BigInt('86399123456789')), + new codec.Interval(-25, -15, BigInt('-86399123456789')), + new codec.Interval(13, 0, BigInt('0')), + new codec.Interval(0, 0, BigInt('86400000000000')), + new codec.Interval(0, 31, BigInt('0')), + new codec.Interval(-12, 0, BigInt('0')), + ]; + + testCases.forEach(interval => { + const isoString = interval.toISO8601(); + const roundtripInterval = codec.Interval.fromISO8601(isoString); + assert.deepStrictEqual(roundtripInterval, interval); + }); + }); + }); + }); + + describe('ProtoMessage', () => { + const protoMessageParams = { + value: music.SingerInfo.create({ + singerId: new Long(1), + genre: music.Genre.POP, + birthDate: 'January', + nationality: 'Country1', + }), + messageFunction: music.SingerInfo, + fullName: 'examples.spanner.music.SingerInfo', + }; + + it('should store value as buffer', () => { + const protoMessage = new codec.ProtoMessage(protoMessageParams); + assert(Buffer.isBuffer(protoMessage.value)); + }); + + it('should throw an error when value is not object and protoMessage is not passed', () => { + assert.throws( + () => { + new codec.ProtoMessage({ + value: { + singerId: 1, + genre: music.Genre.POP, + birthDate: 'January', + }, + fullName: 'examples.spanner.music.SingerInfo', + }); + }, + new GoogleError(`protoMessageParams cannot be used to construct + the ProtoMessage. Pass the serialized buffer of the + proto message as the value or provide the message object along with the + corresponding messageFunction generated by protobufjs-cli.`), + ); + }); + + it('toJSON with messageFunction', () => { + assert.deepEqual( + new codec.ProtoMessage(protoMessageParams).toJSON(), + music.SingerInfo.toObject(protoMessageParams.value), + ); + }); + + it('toJSON without messageFunction', () => { + const message = new codec.ProtoMessage({ + value: music.SingerInfo.encode(protoMessageParams.value).finish(), + fullName: 'examples.spanner.music.SingerInfo', + }); + assert.deepEqual(message.toJSON(), message.value.toString()); + }); + }); + + describe('ProtoEnum', () => { + const enumParams = { + value: music.Genre.JAZZ, + enumObject: music.Genre, + fullName: 'examples.spanner.music.Genre', + }; + + it('should store value as string', () => { + const protoEnum = new codec.ProtoEnum(enumParams); + assert(isString(protoEnum.value)); + }); + + it('should throw an error when value is non numeric string and enumObject is not passed', () => { + assert.throws( + () => { + new codec.ProtoEnum({ + value: 'POP', + fullName: 'examples.spanner.music.Genre', + }); + }, + new GoogleError(`protoEnumParams cannot be used for constructing the + ProtoEnum. Pass the number as the value or provide the enum string + constant as the value along with the corresponding enumObject generated + by protobufjs-cli.`), + ); + }); + + it('toJSON with enumObject', () => { + assert.deepEqual(new codec.ProtoEnum(enumParams).toJSON(), 'JAZZ'); + }); + + it('toJSON without enumObject', () => { + assert.deepEqual( + new codec.ProtoEnum({ + value: music.Genre.JAZZ, + fullName: 'examples.spanner.music.Genre', + }).toJSON(), + 1, + ); + }); + }); + + describe('Struct', () => { + describe('toJSON', () => { + it('should covert the struct to JSON', () => { + const struct = new codec.Struct(); + const options = {}; + const fakeJson = {}; + + (sandbox.stub(codec, 'convertFieldsToJson') as sinon.SinonStub) + .withArgs(struct, options) + .returns(fakeJson); + + assert.strictEqual(struct.toJSON(options), fakeJson); + }); + }); + + describe('fromArray', () => { + it('should wrap the array in a struct', () => { + const fields = [{name: 'name', value: 'value'}]; + const struct = codec.Struct.fromArray(fields); + + assert(struct instanceof codec.Struct); + + fields.forEach((field, i) => { + assert.strictEqual(struct[i], field); + }); + }); + }); + + describe('fromJSON', () => { + it('should covert json to a struct', () => { + const json = {a: 'b', c: 'd'}; + const expected = [ + {name: 'a', value: 'b'}, + {name: 'c', value: 'd'}, + ]; + const struct = codec.Struct.fromJSON(json); + + assert(struct instanceof codec.Struct); + + expected.forEach((field, i) => { + assert.deepStrictEqual(struct[i], field); + }); + }); + }); + }); + + describe('convertFieldsToJson', () => { + const ROW = [ + { + name: 'name', + value: 'value', + }, + ]; + + it('should not require options', () => { + assert.doesNotThrow(() => codec.convertFieldsToJson(ROW)); + }); + + it('should return serialized rows', () => { + const json = codec.convertFieldsToJson(ROW); + + assert.deepStrictEqual(json, {name: 'value'}); + }); + + it('should not return nameless values by default', () => { + const row = [ + { + value: 'value', + }, + ]; + + const json = codec.convertFieldsToJson(row); + assert.deepStrictEqual(json, {}); + }); + + it('should return nameless values when requested', () => { + const row = [ + { + value: 'value', + }, + ]; + + const json = codec.convertFieldsToJson(row, {includeNameless: true}); + assert.deepStrictEqual(json, {_0: 'value'}); + }); + + describe('structs', () => { + it('should not wrap structs by default', () => { + const options = { + wrapNumbers: false, + wrapStructs: false, + includeNameless: false, + }; + const fakeStructJson = {}; + + const struct = new codec.Struct(); + const stub = sandbox.stub(struct, 'toJSON').returns(fakeStructJson); + + const row = [{name: 'Struct', value: struct}]; + + const json = codec.convertFieldsToJson(row, options); + + assert.strictEqual(json.Struct, fakeStructJson); + assert.deepStrictEqual(stub.lastCall.args[0], options); + }); + + it('should wrap structs with option', () => { + const value = 3.3; + + const expectedStruct = codec.Struct.fromJSON({Number: value}); + const struct = codec.Struct.fromJSON({Number: new codec.Float(value)}); + + const row = [{name: 'Struct', value: struct}]; + + const json = codec.convertFieldsToJson(row, {wrapStructs: true}); + assert.deepStrictEqual(json.Struct, expectedStruct); + }); + }); + + describe('numbers', () => { + it('should not wrap numbers by default', () => { + const row = [ + { + name: 'Number', + value: new codec.Int(3), + }, + ]; + + const json = codec.convertFieldsToJson(row); + assert.strictEqual(typeof json.Number, 'number'); + assert.strictEqual(json.Number, 3); + }); + + it('should wrap numbers with option', () => { + const int = new codec.Int(3); + + const row = [ + { + name: 'Number', + value: int, + }, + ]; + + const json = codec.convertFieldsToJson(row, {wrapNumbers: true}); + + assert(json.Number instanceof codec.Int); + assert.deepStrictEqual(json.Number, int); + }); + + it('should throw an error if number is out of bounds', () => { + const int = new codec.Int('9223372036854775807'); + + const row = [ + { + name: 'Number', + value: int, + }, + ]; + + assert.throws(() => { + codec.convertFieldsToJson(row); + }, new RegExp('Serializing column "Number" encountered an error')); + }); + }); + + describe('arrays', () => { + it('should not wrap numbers by default', () => { + const value = 3; + + const row = [ + { + name: 'List', + value: [new codec.Int(value)], + }, + ]; + + const json = codec.convertFieldsToJson(row); + assert.deepStrictEqual(json.List, [value]); + }); + + it('should wrap numbers with option', () => { + const value = new codec.Int(3); + + const row = [{name: 'List', value: [value]}]; + + const json = codec.convertFieldsToJson(row, {wrapNumbers: true}); + assert.deepStrictEqual(json.List, [value]); + }); + + it('should not wrap structs by default', () => { + const struct = new codec.Struct(); + const expectedStruct = {a: 'b', c: 'd'}; + + sandbox.stub(struct, 'toJSON').returns(expectedStruct); + + const row = [{name: 'List', value: [struct]}]; + + const json = codec.convertFieldsToJson(row); + assert.deepStrictEqual(json.List, [expectedStruct]); + }); + + it('should wrap structs with option', () => { + const expectedStruct = codec.Struct.fromJSON({a: 'b', c: 'd'}); + + const row = [{name: 'List', value: [expectedStruct]}]; + + const json = codec.convertFieldsToJson(row, {wrapStructs: true}); + assert.deepStrictEqual(json.List, [expectedStruct]); + }); + }); + }); + + describe('decode', () => { + // Does not require any special decoding. + const BYPASS_FIELD = { + code: 'not-real-code', + }; + + it('should return the same value if not a special type', () => { + const value = {}; + + const decoded = codec.decode(value, BYPASS_FIELD); + assert.strictEqual(decoded, value); + }); + + it('should return null values as null', () => { + (GrpcService.decodeValue_ as sinon.SinonStub).returns(null); + const decoded = codec.decode(null, BYPASS_FIELD); + assert.strictEqual(decoded, null); + }); + + it('should decode BYTES', () => { + const expected = Buffer.from('bytes value'); + const encoded = expected.toString('base64'); + + const decoded = codec.decode(encoded, { + code: google.spanner.v1.TypeCode.BYTES, + }); + + assert.deepStrictEqual(decoded, expected); + }); + + it('should decode ProtoMessage', () => { + const expected = new codec.ProtoMessage({ + value: music.SingerInfo.create({ + singerId: 1, + genre: music.Genre.POP, + birthDate: 'January', + nationality: 'Country1', + }), + messageFunction: music.SingerInfo, + fullName: 'examples.spanner.music.SingerInfo', + }); + const encoded = expected.value.toString('base64'); + + const decoded = codec.decode( + encoded, + { + code: google.spanner.v1.TypeCode.PROTO, + protoTypeFqn: 'examples.spanner.music.SingerInfo', + }, + music.SingerInfo, + ); + + assert.deepStrictEqual(decoded, expected); + }); + + it('should decode ProtoEnum', () => { + const expected = Buffer.from('bytes value'); + const encoded = expected.toString('base64'); + + const decoded = codec.decode(encoded, { + code: google.spanner.v1.TypeCode.BYTES, + }); + + assert.deepStrictEqual(decoded, expected); + }); + + it('should decode UUID', () => { + const value = uuid.v4(); + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.UUID, + }); + + assert.strictEqual(decoded, value); + }); + + it('should decode FLOAT32', () => { + const value = 'Infinity'; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.FLOAT32, + }); + + assert(decoded instanceof codec.Float32); + assert.strictEqual(decoded.value, value); + }); + + it('should decode FLOAT64', () => { + const value = 'Infinity'; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.FLOAT64, + }); + + assert(decoded instanceof codec.Float); + assert.strictEqual(decoded.value, value); + }); + + it('should decode INT64', () => { + const value = '64'; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.INT64, + }); + + assert(decoded instanceof codec.Int); + assert.strictEqual(decoded.value, value); + }); + + it('should decode NUMERIC', () => { + const value = '8.01911'; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.NUMERIC, + }); + + assert(decoded instanceof codec.Numeric); + assert.strictEqual(decoded.value, value); + }); + + it('should decode PG NUMERIC', () => { + const value = '8.01911'; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.NUMERIC, + typeAnnotation: google.spanner.v1.TypeAnnotationCode.PG_NUMERIC, + }); + + assert(decoded instanceof codec.PGNumeric); + assert.strictEqual(decoded.value, value); + }); + + it('should decode JSON', () => { + const value = '{"result":true, "count":42}'; + const expected = JSON.parse(value); + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.JSON, + }); + + assert.deepStrictEqual(decoded, expected); + }); + + it('should decode complex JSON string to object', () => { + const value = + '{"boolKey":true,"numberKey":3.14,"stringKey":"test","objectKey":{"innerKey":"inner-value"}}'; + const expected = { + boolKey: true, + numberKey: 3.14, + stringKey: 'test', + objectKey: {innerKey: 'inner-value'}, + }; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.JSON, + }); + + assert.deepStrictEqual(decoded, expected); + }); + + it('should decode JSONB', () => { + const value = '{"result":true, "count":42}'; + const expected = JSON.parse(value); + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.JSON, + typeAnnotation: google.spanner.v1.TypeAnnotationCode.PG_JSONB, + }); + + assert.deepStrictEqual(decoded.value, expected); + }); + + it('should decode JSONB object to string', () => { + const value = + '{"boolKey":true,"numberKey":3.14,"stringKey":"test","objectKey":{"innerKey":"inner-value"}}'; + const expected = JSON.stringify({ + boolKey: true, + numberKey: 3.14, + stringKey: 'test', + objectKey: {innerKey: 'inner-value'}, + }); + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.JSON, + typeAnnotation: google.spanner.v1.TypeAnnotationCode.PG_JSONB, + }); + + assert.deepStrictEqual(decoded.toString(), expected); + }); + + it('should decode PG OID', () => { + const value = '64'; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.INT64, + typeAnnotation: google.spanner.v1.TypeAnnotationCode.PG_OID, + }); + + assert(decoded instanceof codec.PGOid); + assert.strictEqual(decoded.value, value); + }); + + it('should decode TIMESTAMP', () => { + const value = new Date(); + const expected = new PreciseDate(value.getTime()); + const decoded = codec.decode(value.toJSON(), { + code: google.spanner.v1.TypeCode.TIMESTAMP, + }); + + assert.deepStrictEqual(decoded, expected); + }); + + it('should decode DATE', () => { + const value = new Date(); + const expected = new codec.SpannerDate(value.toISOString()); + const decoded = codec.decode(value.toJSON(), { + code: google.spanner.v1.TypeCode.DATE, + }); + + assert.deepStrictEqual(decoded, expected); + }); + + it('should decode INTERVAL', () => { + const value = 'P1Y2M-45DT67H12M6.789045638S'; + const expected = codec.Interval.fromISO8601(value); + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.INTERVAL, + }); + + assert(decoded instanceof codec.Interval); + assert.deepStrictEqual(decoded, expected); + }); + + it('should decode ARRAY and inner members', () => { + const value = ['1']; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.ARRAY, + arrayElementType: { + code: google.spanner.v1.TypeCode.INT64, + }, + }); + + assert(decoded[0] instanceof codec.Int); + }); + + it('should decode object STRUCT value and inner members', () => { + const value = { + keys: 1, + fieldName: '2', + }; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.STRUCT, + structType: { + fields: [ + { + name: 'keys', + type: { + code: google.spanner.v1.TypeCode.JSON, + }, + }, + { + name: 'fieldName', + type: { + code: google.spanner.v1.TypeCode.INT64, + }, + }, + ], + }, + }); + + const expectedStruct = new codec.Struct( + { + name: 'keys', + value: value.keys, + }, + { + name: 'fieldName', + value: new codec.Int(value.fieldName), + }, + ); + + assert(decoded instanceof codec.Struct); + assert.deepStrictEqual(decoded, expectedStruct); + }); + + it('should decode array STRUCT value and inner members', () => { + const value = ['1', '2']; + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.STRUCT, + structType: { + fields: [ + { + name: 'keys', + type: { + code: google.spanner.v1.TypeCode.JSON, + }, + }, + { + name: 'fieldName', + type: { + code: google.spanner.v1.TypeCode.INT64, + }, + }, + ], + }, + }); + + const expectedStruct = new codec.Struct( + { + name: 'keys', + value: JSON.parse(value[0]), + }, + { + name: 'fieldName', + value: new codec.Int(value[1]), + }, + ); + + assert(decoded instanceof codec.Struct); + assert.deepStrictEqual(decoded, expectedStruct); + }); + }); + + describe('encode', () => { + it('should return the value from the common encoder', () => { + const value = {}; + const defaultEncodedValue = '{}'; + + (GrpcService.encodeValue_ as sinon.SinonStub) + .withArgs(value) + .returns(defaultEncodedValue); + + const encoded = codec.encode(value); + assert.strictEqual(encoded, defaultEncodedValue); + }); + + it('should encode BYTES', () => { + const value = Buffer.from('bytes value'); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value.toString('base64')); + }); + + it('should encode ProtoMessage', () => { + const genre = music.Genre.ROCK; + const singerInfo = music.SingerInfo.create({ + singerId: 1, + genre: genre, + birthDate: 'January', + nationality: 'Country1', + }); + + const protoMessage = new codec.ProtoMessage({ + value: singerInfo, + messageFunction: music.SingerInfo, + fullName: 'examples.spanner.music.SingerInfo', + }); + + const encoded = codec.encode(protoMessage); + + assert.strictEqual( + encoded, + music.SingerInfo.encode(singerInfo).finish().toString('base64'), + ); + }); + + it('should encode ProtoEnum', () => { + const genre = music.Genre.ROCK; + const protoEnum = new codec.ProtoEnum({ + value: genre, + enumObject: music.Genre, + fullName: 'examples.spanner.music.Genre', + }); + + const encoded = codec.encode(protoEnum); + + assert.strictEqual(encoded, genre.toString()); + }); + + it('should encode structs', () => { + const value = codec.Struct.fromJSON({a: 'b', c: 'd'}); + const encoded = codec.encode(value); + assert.deepStrictEqual(encoded, ['b', 'd']); + }); + + it('should stringify Infinity', () => { + const value = Infinity; + const encoded = codec.encode(value); + assert.strictEqual(encoded, value.toString()); + }); + + it('should stringify -Infinity', () => { + const value = -Infinity; + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value.toString()); + }); + + it('should stringify NaN', () => { + const value = NaN; + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value.toString()); + }); + + it('should stringify INT64', () => { + const value = 5; + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value.toString()); + }); + + it('should stringify NUMERIC', () => { + const value = new codec.Numeric('8.01911'); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value.value); + }); + + it('should stringify PG NUMERIC', () => { + const value = new codec.PGNumeric('8.01911'); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value.value); + }); + + it('should encode ARRAY and inner members', () => { + const value = [5]; + + const encoded = codec.encode(value); + + assert.deepStrictEqual(encoded, [ + value.toString(), // (tests that it is stringified) + ]); + }); + + it('should encode TIMESTAMP', () => { + const value = new PreciseDate(); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value.toJSON()); + }); + + it('should encode DATE', () => { + const value = new codec.SpannerDate(); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value.toJSON()); + }); + + it('should encode INTERVAL', () => { + const value = new codec.Interval(17, -20, BigInt(30001)); + const encoded = codec.encode(value); + assert.strictEqual(encoded, 'P1Y5M-20DT0.000030001S'); + }); + + it('should encode INT64', () => { + const value = new codec.Int(10); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, '10'); + }); + + it('should encode PG OID', () => { + const value = new codec.PGOid(10); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, '10'); + }); + + it('should encode UUID', () => { + const value = uuid.v4(); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, value); + }); + + it('should encode FLOAT32', () => { + const value = new codec.Float32(10); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, 10); + }); + + it('should encode FLOAT64', () => { + const value = new codec.Float(10); + + const encoded = codec.encode(value); + + assert.strictEqual(encoded, 10); + }); + + it('should encode JSON', () => { + const expected = '{"result":true,"count":42}'; + const value = JSON.parse('{"result": true, "count": 42}'); + + const encoded = codec.encode(value); + + assert.deepStrictEqual(encoded, expected); + }); + + it('should encode complex object as JSON', () => { + const value = { + boolKey: true, + numberKey: 3.14, + stringKey: 'test', + objectKey: {innerKey: 'inner-value'}, + }; + + const encoded = codec.encode(value); + + assert.deepStrictEqual( + encoded, + '{"boolKey":true,"numberKey":3.14,"stringKey":"test","objectKey":{"innerKey":"inner-value"}}', + ); + }); + + it('should encode deeply-nested object as JSON', () => { + // Cloud Spanner accepts a nesting level in a JSON string of at most 100. + // This test ensures that the encoder is able to encode such an object to + // a JSON string. + const nesting = 100; + const value = JSON.parse( + '{"k": '.repeat(nesting).concat('"v"').concat('}'.repeat(nesting)), + ); + + const encoded = codec.encode(value); + + assert.deepStrictEqual( + encoded, + '{"k":'.repeat(nesting).concat('"v"').concat('}'.repeat(nesting)), + ); + }); + + it('should decode deeply-nested object as JSON', () => { + // Cloud Spanner accepts a nesting level in a JSON string of at most 100. + // This test ensures that the decoder is able to decode such a string. + const nesting = 100; + const value = '{"k": ' + .repeat(nesting) + .concat('"v"') + .concat('}'.repeat(nesting)); + + const decoded = codec.decode(value, { + code: google.spanner.v1.TypeCode.JSON, + }); + + assert.deepStrictEqual( + decoded, + JSON.parse( + '{"k":'.repeat(nesting).concat('"v"').concat('}'.repeat(nesting)), + ), + ); + }); + }); + + describe('getType', () => { + it('should determine if the value is a boolean', () => { + assert.deepStrictEqual(codec.getType(true), {type: 'bool'}); + }); + + it('should determine if the value is a float', () => { + assert.deepStrictEqual(codec.getType(NaN), {type: 'float64'}); + assert.deepStrictEqual(codec.getType(Infinity), {type: 'float64'}); + assert.deepStrictEqual(codec.getType(-Infinity), {type: 'float64'}); + assert.deepStrictEqual(codec.getType(2.2), {type: 'float64'}); + assert.deepStrictEqual(codec.getType(new codec.Float(1.1)), { + type: 'float64', + }); + }); + + it('should determine if the uuid value is string', () => { + assert.deepStrictEqual(codec.getType(uuid.v4()), { + type: 'string', + }); + }); + + it('should determine if the uuid value is unspecified when SPANNER_ENABLE_UUID_AS_UNTYPED is true', () => { + const emitWarningStub = sandbox.stub(process, 'emitWarning'); + try { + process.env['SPANNER_ENABLE_UUID_AS_UNTYPED'] = 'true'; + assert.deepStrictEqual(codec.getType(uuid.v4()), { + type: 'unspecified', + }); + assert.strictEqual(emitWarningStub.calledOnce, true); + assert.strictEqual( + emitWarningStub.firstCall.args[0], + 'SPANNER_ENABLE_UUID_AS_UNTYPED environment variable is deprecated and will be removed in a future release.', + ); + } finally { + delete process.env['SPANNER_ENABLE_UUID_AS_UNTYPED']; + emitWarningStub.restore(); + } + }); + + it('should determine if the uuid value is string when SPANNER_ENABLE_UUID_AS_UNTYPED is false', () => { + try { + process.env['SPANNER_ENABLE_UUID_AS_UNTYPED'] = 'false'; + assert.deepStrictEqual(codec.getType(uuid.v4()), { + type: 'string', + }); + } finally { + delete process.env['SPANNER_ENABLE_UUID_AS_UNTYPED']; + } + }); + + it('should determine if the value is a float32', () => { + assert.deepStrictEqual(codec.getType(new codec.Float32(1.1)), { + type: 'float32', + }); + }); + + it('should determine if the value is an int', () => { + assert.deepStrictEqual(codec.getType(1234), {type: 'int64'}); + assert.deepStrictEqual(codec.getType(new codec.Int(1)), {type: 'int64'}); + }); + + it('should determine if the value is numeric', () => { + assert.deepStrictEqual(codec.getType(new codec.Numeric('8.01911')), { + type: 'numeric', + }); + }); + + it('should determine if the value is a string', () => { + assert.deepStrictEqual(codec.getType('abc'), {type: 'string'}); + }); + + it('should determine if the value is bytes', () => { + assert.deepStrictEqual(codec.getType(Buffer.from('abc')), { + type: 'bytes', + }); + }); + + it('should determine if the value is json', () => { + assert.deepStrictEqual(codec.getType({key: 'value'}), { + type: 'json', + }); + }); + + it('should determine if the value is a date', () => { + assert.deepStrictEqual(codec.getType(new codec.SpannerDate()), { + type: 'date', + }); + }); + + it('should determine if the value is a timestamp', () => { + assert.deepStrictEqual(codec.getType(new PreciseDate()), { + type: 'timestamp', + }); + }); + + it('should accept a plain date object as a timestamp', () => { + assert.deepStrictEqual(codec.getType(new Date()), {type: 'timestamp'}); + }); + + it.skip('should determine if the value is a interval', () => { + assert.deepStrictEqual( + codec.getType(new codec.Interval(1, 2, BigInt(3))), + { + type: 'interval', + }, + ); + }); + + it('should determine if the value is a struct', () => { + const struct = codec.Struct.fromJSON({a: 'b'}); + const type = codec.getType(struct); + + assert.deepStrictEqual(type, { + type: 'struct', + fields: [{name: 'a', type: 'string'}], + }); + }); + + it('should attempt to determine arrays and their values', () => { + assert.deepStrictEqual(codec.getType([Infinity]), { + type: 'array', + child: { + type: 'float64', + }, + }); + }); + + it('should return unspecified for unknown values', () => { + assert.deepStrictEqual(codec.getType(null), {type: 'unspecified'}); + + assert.deepStrictEqual(codec.getType([null]), { + type: 'array', + child: { + type: 'unspecified', + }, + }); + }); + + it('should determine if the value is a PGNumeric', () => { + assert.deepStrictEqual(codec.getType(new codec.PGNumeric('7248')), { + type: 'pgNumeric', + }); + }); + + it('should determine if the value is a PGOid', () => { + assert.deepStrictEqual(codec.getType(new codec.PGOid(5678)), { + type: 'pgOid', + }); + }); + }); + + describe('convertToListValue', () => { + beforeEach(() => { + sandbox.stub(codec, 'encode').callsFake(value => { + return {stringValue: value}; + }); + }); + + it('should map values to encoded versions', () => { + const actual = ['hi', 'bye']; + const expected = { + values: [{stringValue: 'hi'}, {stringValue: 'bye'}], + }; + + const converted = codec.convertToListValue(actual); + assert.deepStrictEqual(converted, expected); + }); + + it('should convert a single value to a list value', () => { + const actual = 'hi'; + const expected = { + values: [{stringValue: 'hi'}], + }; + + const converted = codec.convertToListValue(actual); + assert.deepStrictEqual(converted, expected); + }); + }); + + describe('convertMsToProtoTimestamp', () => { + it('should convert ms to google.protobuf.Timestamp', () => { + const ms = 5000.00001; + const expected = { + nanos: 10, + seconds: 5, + }; + + const converted = codec.convertMsToProtoTimestamp(ms); + assert.deepStrictEqual(converted, expected); + }); + }); + + describe('convertProtoTimestampToDate', () => { + it('should convert google.protobuf.Timestamp to Date', () => { + const timestamp = {nanos: 10, seconds: 5}; + + const expected = new Date(5000.00001); + const converted = codec.convertProtoTimestampToDate(timestamp); + + assert.deepStrictEqual(converted, expected); + }); + }); + + describe('createTypeObject', () => { + it('should convert strings to the corresponding type', () => { + const typeMap = { + unspecified: { + code: google.spanner.v1.TypeCode[ + google.spanner.v1.TypeCode.TYPE_CODE_UNSPECIFIED + ], + }, + bool: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.BOOL], + }, + int64: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.INT64], + }, + uuid: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.UUID], + }, + float32: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.FLOAT32], + }, + float64: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.FLOAT64], + }, + timestamp: { + code: google.spanner.v1.TypeCode[ + google.spanner.v1.TypeCode.TIMESTAMP + ], + }, + date: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.DATE], + }, + string: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.STRING], + }, + bytes: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.BYTES], + }, + interval: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.INTERVAL], + }, + array: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.ARRAY], + arrayElementType: { + code: google.spanner.v1.TypeCode[ + google.spanner.v1.TypeCode.TYPE_CODE_UNSPECIFIED + ], + }, + }, + struct: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.STRUCT], + structType: {fields: []}, + }, + }; + + Object.keys(typeMap).forEach(key => { + const type = codec.createTypeObject(key); + assert.deepStrictEqual(type, typeMap[key]); + }); + }); + + it('should default to unspecified for unknown types', () => { + const type = codec.createTypeObject('unicorn'); + + assert.deepStrictEqual(type, { + code: google.spanner.v1.TypeCode[ + google.spanner.v1.TypeCode.TYPE_CODE_UNSPECIFIED + ], + }); + }); + + it('should set the arrayElementType', () => { + const type = codec.createTypeObject({ + type: 'array', + child: 'bool', + }); + + assert.deepStrictEqual(type, { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.ARRAY], + arrayElementType: { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.BOOL], + }, + }); + }); + + it('should set the struct fields', () => { + const type = codec.createTypeObject({ + type: 'struct', + fields: [ + {name: 'boolKey', type: 'bool'}, + {name: 'intKey', type: 'int64'}, + ], + }); + + assert.deepStrictEqual(type, { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.STRUCT], + structType: { + fields: [ + { + name: 'boolKey', + type: { + code: google.spanner.v1.TypeCode[ + google.spanner.v1.TypeCode.BOOL + ], + }, + }, + { + name: 'intKey', + type: { + code: google.spanner.v1.TypeCode[ + google.spanner.v1.TypeCode.INT64 + ], + }, + }, + ], + }, + }); + }); + + it('should handle nested structs', () => { + const type = codec.createTypeObject({ + type: 'struct', + fields: [ + { + name: 'nestedStruct', + type: 'struct', + fields: [ + { + type: 'bool', + name: 'boolKey', + }, + ], + }, + ], + }); + + assert.deepStrictEqual(type, { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.STRUCT], + structType: { + fields: [ + { + name: 'nestedStruct', + type: { + code: google.spanner.v1.TypeCode[ + google.spanner.v1.TypeCode.STRUCT + ], + structType: { + fields: [ + { + name: 'boolKey', + type: { + code: google.spanner.v1.TypeCode[ + google.spanner.v1.TypeCode.BOOL + ], + }, + }, + ], + }, + }, + }, + ], + }, + }); + }); + it('should set code and typeAnnotation for pgNumeric string', () => { + const type = codec.createTypeObject('pgNumeric'); + + assert.deepStrictEqual(type, { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.NUMERIC], + typeAnnotation: google.spanner.v1.TypeAnnotationCode.PG_NUMERIC, + }); + }); + + it('should set code and typeAnnotation for pgNumeric friendlyType object', () => { + const type = codec.createTypeObject({type: 'pgNumeric'}); + + assert.deepStrictEqual(type, { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.NUMERIC], + typeAnnotation: google.spanner.v1.TypeAnnotationCode.PG_NUMERIC, + }); + }); + + it('should set code and typeAnnotation for pgOid string', () => { + const type = codec.createTypeObject('pgOid'); + + assert.deepStrictEqual(type, { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.INT64], + typeAnnotation: google.spanner.v1.TypeAnnotationCode.PG_OID, + }); + }); + + it('should set code and typeAnnotation for pgOid friendlyType object', () => { + const type = codec.createTypeObject({type: 'pgOid'}); + + assert.deepStrictEqual(type, { + code: google.spanner.v1.TypeCode[google.spanner.v1.TypeCode.INT64], + typeAnnotation: google.spanner.v1.TypeAnnotationCode.PG_OID, + }); + }); + }); +}); diff --git a/handwritten/spanner/test/common/service-object.ts b/handwritten/spanner/test/common/service-object.ts new file mode 100644 index 00000000000..7e5544eb8e9 --- /dev/null +++ b/handwritten/spanner/test/common/service-object.ts @@ -0,0 +1,260 @@ +// Copyright 2019 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. + +/* eslint-disable prefer-rest-params */ +/* eslint-disable prefer-spread */ + +import * as pfy from '@google-cloud/promisify'; +import * as assert from 'assert'; +import {before, beforeEach, describe, it} from 'mocha'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; + +let promisified = false; +const fakePfy = Object.assign({}, pfy, { + promisifyAll(klass) { + if (klass.name === 'GrpcServiceObject') { + promisified = true; + } + }, +}); + +class FakeServiceObject { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +describe('GrpcServiceObject', () => { + // tslint:disable-next-line:variable-name + let GrpcServiceObject; + let grpcServiceObject; + + const CONFIG = {}; + const PROTO_OPTS = {}; + const REQ_OPTS = {}; + + before(() => { + GrpcServiceObject = proxyquire('../../src/common-grpc/service-object', { + '@google-cloud/common': { + ServiceObject: FakeServiceObject, + }, + '@google-cloud/promisify': fakePfy, + }).GrpcServiceObject; + }); + + beforeEach(() => { + grpcServiceObject = new GrpcServiceObject(CONFIG); + + grpcServiceObject.methods = { + delete: { + protoOpts: PROTO_OPTS, + reqOpts: REQ_OPTS, + }, + getMetadata: { + protoOpts: PROTO_OPTS, + reqOpts: REQ_OPTS, + }, + setMetadata: { + protoOpts: PROTO_OPTS, + reqOpts: REQ_OPTS, + }, + }; + }); + + describe('instantiation', () => { + it('should inherit from ServiceObject', () => { + assert(grpcServiceObject instanceof FakeServiceObject); + + const calledWith = grpcServiceObject.calledWith_; + assert.strictEqual(calledWith[0], CONFIG); + }); + + it('should promisify all the things', () => { + assert(promisified); + }); + }); + + describe('delete', () => { + it('should make the correct request', done => { + grpcServiceObject.request = (protoOpts, reqOpts, callback) => { + const deleteMethod = grpcServiceObject.methods.delete; + assert.strictEqual(protoOpts, deleteMethod.protoOpts); + assert.strictEqual(reqOpts, deleteMethod.reqOpts); + callback(); // done() + }; + + grpcServiceObject.delete(done); + }); + + it('should not require a callback', done => { + grpcServiceObject.request = (protoOpts, reqOpts, callback) => { + assert.doesNotThrow(callback); + done(); + }; + + grpcServiceObject.delete(); + }); + }); + + describe('getMetadata', () => { + it('should make the correct request', done => { + grpcServiceObject.request = (protoOpts, reqOpts, callback) => { + const getMetadataMethod = grpcServiceObject.methods.getMetadata; + assert.strictEqual(protoOpts, getMetadataMethod.protoOpts); + assert.strictEqual(reqOpts, getMetadataMethod.reqOpts); + callback(); // done() + }; + + grpcServiceObject.getMetadata(done); + }); + + describe('error', () => { + const error = new Error('Error.'); + const apiResponse = {}; + + beforeEach(() => { + grpcServiceObject.request = (protoOpts, reqOpts, callback) => { + callback(error, apiResponse); + }; + }); + + it('should execute callback with error & API response', done => { + grpcServiceObject.getMetadata((err, metadata, apiResponse_) => { + assert.strictEqual(err, error); + assert.strictEqual(metadata, null); + assert.strictEqual(apiResponse_, apiResponse); + done(); + }); + }); + }); + + describe('success', () => { + const apiResponse = {}; + + beforeEach(() => { + grpcServiceObject.request = (protoOpts, reqOpts, callback) => { + callback(null, apiResponse); + }; + }); + + it('should exec callback with metadata & API response', done => { + grpcServiceObject.getMetadata((err, metadata, apiResponse_) => { + assert.ifError(err); + assert.strictEqual(metadata, apiResponse); + assert.strictEqual(apiResponse_, apiResponse); + done(); + }); + }); + + it('should update the metadata on the instance', done => { + grpcServiceObject.getMetadata(err => { + assert.ifError(err); + assert.strictEqual(grpcServiceObject.metadata, apiResponse); + done(); + }); + }); + }); + }); + + describe('setMetadata', () => { + const DEFAULT_REQ_OPTS = {a: 'b'}; + const METADATA = {a: 'c'}; + + it('should make the correct request', done => { + const setMetadataMethod = grpcServiceObject.methods.setMetadata; + const expectedReqOpts = extend(true, {}, DEFAULT_REQ_OPTS, METADATA); + + grpcServiceObject.methods.setMetadata.reqOpts = DEFAULT_REQ_OPTS; + + grpcServiceObject.request = (protoOpts, reqOpts, callback) => { + assert.strictEqual(protoOpts, setMetadataMethod.protoOpts); + assert.deepStrictEqual(reqOpts, expectedReqOpts); + callback(); // done() + }; + + grpcServiceObject.setMetadata(METADATA, done); + }); + + it('should not require a callback', done => { + grpcServiceObject.request = (protoOpts, reqOpts, callback) => { + assert.doesNotThrow(callback); + done(); + }; + + grpcServiceObject.setMetadata(METADATA); + }); + }); + + describe('request', () => { + it('should call the parent instance request method', () => { + const args = [1, 2, 3]; + const expectedReturnValue = {}; + + grpcServiceObject.parent = { + request() { + assert.strictEqual(this, grpcServiceObject.parent); + assert.deepStrictEqual([].slice.call(arguments), args); + return expectedReturnValue; + }, + }; + + const ret = grpcServiceObject.request.apply(grpcServiceObject, args); + assert.strictEqual(ret, expectedReturnValue); + }); + }); + + describe('requestStream', () => { + it('should call the parent instance requestStream method', () => { + const args = [1, 2, 3]; + const expectedReturnValue = {}; + + grpcServiceObject.parent = { + requestStream() { + assert.strictEqual(this, grpcServiceObject.parent); + assert.deepStrictEqual([].slice.call(arguments), args); + return expectedReturnValue; + }, + }; + + const ret = grpcServiceObject.requestStream.apply( + grpcServiceObject, + args, + ); + assert.strictEqual(ret, expectedReturnValue); + }); + }); + + describe('requestWritableStream', () => { + it('should call the parent requestWritableStream method', () => { + const args = [1, 2, 3]; + const expectedReturnValue = {}; + + grpcServiceObject.parent = { + requestWritableStream() { + assert.strictEqual(this, grpcServiceObject.parent); + assert.deepStrictEqual([].slice.call(arguments), args); + return expectedReturnValue; + }, + }; + + const ret = grpcServiceObject.requestWritableStream.apply( + grpcServiceObject, + args, + ); + assert.strictEqual(ret, expectedReturnValue); + }); + }); +}); diff --git a/handwritten/spanner/test/common/service.ts b/handwritten/spanner/test/common/service.ts new file mode 100644 index 00000000000..45c05354b4e --- /dev/null +++ b/handwritten/spanner/test/common/service.ts @@ -0,0 +1,2141 @@ +// Copyright 2019 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 * as path from 'path'; +import {util} from '@google-cloud/common'; +import {replaceProjectIdToken} from '@google-cloud/projectify'; +import * as grpcProtoLoader from '@grpc/proto-loader'; +import * as assert from 'assert'; +import {before, beforeEach, after, afterEach, describe, it} from 'mocha'; +import * as duplexify from 'duplexify'; +import * as extend from 'extend'; +import {grpc, GrpcClient} from 'google-gax'; +import * as proxyquire from 'proxyquire'; +import * as retryRequest from 'retry-request'; +import * as sn from 'sinon'; +import {PassThrough} from 'stream'; +import {isDate} from '../../src/helper'; + +const sinon = sn.createSandbox(); +const glob = global as {} as {GCLOUD_SANDBOX_ENV?: boolean | {}}; + +const gaxProtosDir = path.join( + path.dirname(require.resolve('google-gax')), + '..', + 'protos', +); + +let getUserAgentFromPackageJsonOverride: Function | null; +const fakeUtil = Object.assign({}, util, { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getUserAgentFromPackageJson: (...args: any[]) => { + return ( + getUserAgentFromPackageJsonOverride || util.getUserAgentFromPackageJson + )(...args); + }, +}); + +class FakeService { + calledWith_: IArguments; + constructor() { + // eslint-disable-next-line prefer-rest-params + this.calledWith_ = arguments; + } +} + +let replaceProjectIdTokenOverride; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function fakeReplaceProjectIdTokenOverride(...args: any[]) { + return (replaceProjectIdTokenOverride || replaceProjectIdToken)(...args); +} + +let retryRequestOverride; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function fakeRetryRequest(...args: any[]) { + return (retryRequestOverride || retryRequest)(...args); +} + +let grpcProtoLoadOverride: typeof grpcProtoLoader.loadSync | null = null; + +const fakeGrpcProtoLoader = { + loadSync(filename: string, options?: grpcProtoLoader.Options) { + return (grpcProtoLoadOverride || grpcProtoLoader.loadSync)( + filename, + options, + ); + }, +}; + +describe('GrpcService', () => { + // tslint:disable-next-line:variable-name + let GrpcServiceCached; + // tslint:disable-next-line:variable-name + let GrpcService; + let grpcService; + + // tslint:disable-next-line:variable-name + let ObjectToStructConverter; + + const ROOT_DIR = '/root/dir'; + const PROTO_FILE_PATH = 'filepath.proto'; + const SERVICE_PATH = 'service.path'; + + interface Config { + proto: {}; + protosDir: string; + protoServices: { + Service: { + path: string; + service: string; + }; + }; + packageJson: { + name: string; + version: string; + }; + grpcMetadata?: { + property: string; + }; + } + + const CONFIG = { + proto: {}, + protosDir: ROOT_DIR, + protoServices: { + Service: { + path: PROTO_FILE_PATH, + service: SERVICE_PATH, + }, + }, + packageJson: { + name: '@google-cloud/service', + version: '0.2.0', + }, + grpcMetadata: { + property: 'value', + }, + }; + + const OPTIONS = { + maxRetries: 3, + }; + + const grpcJsVersion = new GrpcClient().grpcVersion; + + const EXPECTED_API_CLIENT_HEADER = [ + 'gl-node/' + process.versions.node, + 'gccl/' + CONFIG.packageJson.version, + 'grpc/' + grpcJsVersion, + ].join(' '); + + const MOCK_GRPC_API: grpcProtoLoader.PackageDefinition = { + [`google.${SERVICE_PATH}.Service`]: {}, + }; + + before(() => { + GrpcService = proxyquire('../../src/common-grpc/service', { + '@google-cloud/common': { + Service: FakeService, + util: fakeUtil, + }, + '@google-cloud/projectify': { + replaceProjectIdToken: fakeReplaceProjectIdTokenOverride, + }, + '@grpc/proto-loader': fakeGrpcProtoLoader, + 'retry-request': fakeRetryRequest, + }).GrpcService; + GrpcServiceCached = extend(true, {}, GrpcService); + ObjectToStructConverter = GrpcService.ObjectToStructConverter; + }); + + beforeEach(() => { + retryRequestOverride = null; + getUserAgentFromPackageJsonOverride = null; + grpcProtoLoadOverride = () => { + return MOCK_GRPC_API; + }; + Object.assign(GrpcService, GrpcServiceCached); + grpcService = new GrpcService(CONFIG, OPTIONS); + }); + + afterEach(() => { + grpcProtoLoadOverride = null; + // Clear the proto object cache, to ensure that state isn't being carried + // across tests. + GrpcService['protoObjectCache'] = {}; + sinon.restore(); + }); + + it('should use grpc from config object', () => { + let metadataUsed = 0; + let credentialsUsed = 0; + class Credentials { + createInsecure() { + ++credentialsUsed; + } + } + class Metadata { + add() { + ++metadataUsed; + } + } + const fakeGrpc = { + Metadata, + credentials: new Credentials(), + }; + const grpcService = new GrpcService( + Object.assign( + { + grpc: fakeGrpc, + grpcVersion: 'grpc-foo/1.2.3', + customEndpoint: 'endpoint', + }, + CONFIG, + ), + OPTIONS, + ); + assert.strictEqual(grpcService.grpc, fakeGrpc); + assert.strictEqual(grpcService.grpcVersion, 'grpc-foo/1.2.3'); + assert(metadataUsed > 0); + assert(credentialsUsed > 0); + }); + + it('should not use @grpc/grpc-js version if grpc object is passed', () => { + class Metadata { + add() {} + } + const fakeGrpc = { + Metadata, + }; + const grpcService = new GrpcService( + Object.assign({grpc: fakeGrpc}, CONFIG), + OPTIONS, + ); + assert.strictEqual(grpcService.grpc, fakeGrpc); + assert.strictEqual(grpcService.grpcVersion, 'grpc/unknown'); + }); + + it('should use @grpc/grpc-js by default', () => { + const grpcService = new GrpcService(CONFIG, OPTIONS); + assert.strictEqual(grpcService.grpcVersion, 'grpc/' + grpcJsVersion); + assert.strictEqual(grpcService.grpc, grpc); + }); + + describe('grpc error to http error map', () => { + it('should export grpc error map', () => { + assert.deepStrictEqual(GrpcService.GRPC_ERROR_CODE_TO_HTTP, { + 0: { + code: 200, + message: 'OK', + }, + + 1: { + code: 499, + message: 'Client Closed Request', + }, + + 2: { + code: 500, + message: 'Internal Server Error', + }, + + 3: { + code: 400, + message: 'Bad Request', + }, + + 4: { + code: 504, + message: 'Gateway Timeout', + }, + + 5: { + code: 404, + message: 'Not Found', + }, + + 6: { + code: 409, + message: 'Conflict', + }, + + 7: { + code: 403, + message: 'Forbidden', + }, + + 8: { + code: 429, + message: 'Too Many Requests', + }, + + 9: { + code: 412, + message: 'Precondition Failed', + }, + + 10: { + code: 409, + message: 'Conflict', + }, + + 11: { + code: 400, + message: 'Bad Request', + }, + + 12: { + code: 501, + message: 'Not Implemented', + }, + + 13: { + code: 500, + message: 'Internal Server Error', + }, + + 14: { + code: 503, + message: 'Service Unavailable', + }, + + 15: { + code: 500, + message: 'Internal Server Error', + }, + + 16: { + code: 401, + message: 'Unauthorized', + }, + }); + }); + }); + + describe('grpc service options', () => { + it('should define the correct default options', () => { + assert.deepStrictEqual(GrpcService.GRPC_SERVICE_OPTIONS, { + 'grpc.max_send_message_length': -1, + 'grpc.max_receive_message_length': -1, + 'grpc.initial_reconnect_backoff_ms': 5000, + }); + }); + }); + + describe('instantiation', () => { + let sandbox: sn.SinonSandbox; + beforeEach(() => { + sandbox = sn.createSandbox(); + }); + afterEach(() => { + sandbox.restore(); + }); + + it('should inherit from Service', () => { + assert(grpcService instanceof FakeService); + + const calledWith = grpcService.calledWith_; + assert.strictEqual(calledWith[0], CONFIG); + assert.strictEqual(calledWith[1], OPTIONS); + }); + + it('should set insecure credentials if using customEndpoint', () => { + const config = Object.assign({}, CONFIG, {customEndpoint: true}); + const spy = sandbox.spy(grpc.credentials, 'createInsecure'); + new GrpcService(config, OPTIONS); + assert(spy.called); + }); + + it('should default grpcMetadata to empty metadata', () => { + const fakeGrpcMetadata = { + 'x-goog-api-client': EXPECTED_API_CLIENT_HEADER, + }; + + const config: Config = Object.assign({}, CONFIG); + delete config.grpcMetadata; + + const grpcService = new GrpcService(config, OPTIONS); + assert.deepStrictEqual( + grpcService.grpcMetadata.getMap(), + fakeGrpcMetadata, + ); + }); + + it('should create and localize grpcMetadata', () => { + const fakeGrpcMetadata = Object.assign( + { + 'x-goog-api-client': EXPECTED_API_CLIENT_HEADER, + }, + CONFIG.grpcMetadata, + ); + const grpcService = new GrpcService(CONFIG, OPTIONS); + assert.deepStrictEqual( + grpcService.grpcMetadata.getMap(), + fakeGrpcMetadata, + ); + }); + + it('should localize maxRetries', () => { + assert.strictEqual(grpcService.maxRetries, OPTIONS.maxRetries); + }); + + it('should set the correct user-agent', () => { + const userAgent = 'user-agent/0.0.0'; + + getUserAgentFromPackageJsonOverride = packageJson => { + assert.strictEqual(packageJson, CONFIG.packageJson); + return userAgent; + }; + + const grpcService = new GrpcService(CONFIG, OPTIONS); + assert.strictEqual(grpcService.userAgent, userAgent); + }); + + it('should set the primary_user_agent from user-agent', () => { + const userAgent = 'user-agent/0.0.0'; + + getUserAgentFromPackageJsonOverride = packageJson => { + assert.strictEqual(packageJson, CONFIG.packageJson); + return userAgent; + }; + + new GrpcService(CONFIG, OPTIONS); + assert.strictEqual(OPTIONS['grpc.primary_user_agent'], userAgent); + }); + + it('should localize the service', () => { + assert.deepStrictEqual( + Object.keys(grpcService.protos), + Object.keys(CONFIG.protoServices), + ); + }); + + it('should localize an empty Map of services', () => { + assert(grpcService.activeServiceMap_ instanceof Map); + assert.strictEqual(grpcService.activeServiceMap_.size, 0); + }); + + it('should call grpc.load correctly', () => { + grpcProtoLoadOverride = (file, options) => { + assert.deepStrictEqual(options!.includeDirs, [ROOT_DIR]); + assert.strictEqual(file, PROTO_FILE_PATH); + + assert.strictEqual(options!.bytes, String); + assert.strictEqual(options!.keepCase, false); + + return MOCK_GRPC_API; + }; + + const grpcService = new GrpcService(CONFIG, OPTIONS); + + for (const serviceName of Object.keys(CONFIG.protoServices)) { + assert.strictEqual( + grpcService.protos[serviceName], + MOCK_GRPC_API[`google.${SERVICE_PATH}.${serviceName}`], + ); + } + }); + + it('should store the baseUrl properly', () => { + const fakeBaseUrl = 'a.googleapis.com'; + + grpcProtoLoadOverride = () => { + return MOCK_GRPC_API; + }; + + const config = extend(true, {}, CONFIG, { + protoServices: { + Service: {baseUrl: fakeBaseUrl}, + }, + }); + + const grpcService = new GrpcService(config, OPTIONS); + + assert.strictEqual(grpcService.protos.Service.baseUrl, fakeBaseUrl); + }); + + it('should not run in the gcloud sandbox environment', () => { + glob.GCLOUD_SANDBOX_ENV = {}; + const grpcService = new GrpcService(); + assert.strictEqual(grpcService, glob.GCLOUD_SANDBOX_ENV); + delete glob.GCLOUD_SANDBOX_ENV; + }); + }); + + describe('decodeValue_', () => { + it('should decode a struct value', () => { + const structValue = { + kind: 'structValue', + structValue: {}, + }; + + const decodedValue = {}; + sinon.stub(GrpcService, 'structToObj_').returns(decodedValue); + assert.strictEqual(GrpcService.decodeValue_(structValue), decodedValue); + }); + + it('should decode a null value', () => { + const nullValue = { + kind: 'nullValue', + }; + + const decodedValue = null; + + assert.strictEqual(GrpcService.decodeValue_(nullValue), decodedValue); + }); + + it('should decode a list value', () => { + const listValue = { + kind: 'listValue', + listValue: { + values: [ + { + kind: 'nullValue', + }, + ], + }, + }; + + assert.deepStrictEqual(GrpcService.decodeValue_(listValue), [null]); + }); + + it('should return the raw value', () => { + const numberValue = { + kind: 'numberValue', + numberValue: 8, + }; + + assert.strictEqual(GrpcService.decodeValue_(numberValue), 8); + }); + }); + + describe('objToStruct_', () => { + it('should convert the object using ObjectToStructConverter', () => { + const options = {}; + const obj = {}; + const convertedObject = {}; + sinon.stub(GrpcService, 'ObjectToStructConverter').callsFake(options_ => { + assert.strictEqual(options_, options); + return { + convert(obj_) { + assert.strictEqual(obj_, obj); + return convertedObject; + }, + }; + }); + assert.strictEqual( + GrpcService.objToStruct_(obj, options), + convertedObject, + ); + }); + }); + + describe('structToObj_', () => { + it('should convert a struct to an object', () => { + const inputValue = {}; + const decodedValue = {}; + + const struct = { + fields: { + a: inputValue, + }, + }; + + sinon.stub(GrpcService, 'decodeValue_').callsFake(value => { + assert.strictEqual(value, inputValue); + return decodedValue; + }); + + assert.deepStrictEqual(GrpcService.structToObj_(struct), { + a: decodedValue, + }); + }); + }); + + describe('request', () => { + const PROTO_OPTS = {service: 'service', method: 'method', timeout: 3000}; + const REQ_OPTS = {reqOpts: true}; + const GRPC_CREDENTIALS = {}; + + function ProtoService() {} + ProtoService.prototype.method = () => {}; + + beforeEach(() => { + grpcService.grpcCredentials = GRPC_CREDENTIALS; + + grpcService.getService_ = () => { + return ProtoService; + }; + }); + + it('should not run in the gcloud sandbox environment', () => { + glob.GCLOUD_SANDBOX_ENV = true; + assert.strictEqual(grpcService.request(), glob.GCLOUD_SANDBOX_ENV); + delete glob.GCLOUD_SANDBOX_ENV; + }); + + it('should access the specified service proto object', done => { + retryRequestOverride = () => {}; + + grpcService.getService_ = protoOpts => { + assert.strictEqual(protoOpts, PROTO_OPTS); + setImmediate(done); + return ProtoService; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + }); + + it('should use and return retry-request', () => { + const retryRequestInstance = {}; + + retryRequestOverride = () => { + return retryRequestInstance; + }; + + const request = grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + assert.strictEqual(request, retryRequestInstance); + }); + + describe('getting gRPC credentials', () => { + beforeEach(() => { + delete grpcService.grpcCredentials; + }); + + describe('getting credentials error', () => { + const error = new Error('Error.'); + + beforeEach(() => { + grpcService.getGrpcCredentials_ = callback => { + callback(error); + }; + }); + + it('should execute callback with error', done => { + grpcService.request(PROTO_OPTS, REQ_OPTS, err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('getting credentials success', () => { + const authClient = {}; + + beforeEach(() => { + grpcService.getGrpcCredentials_ = callback => { + callback(null, authClient); + }; + }); + + it('should make the gRPC request again', done => { + grpcService.getService_ = () => { + assert.strictEqual(grpcService.grpcCredentials, authClient); + setImmediate(done); + return new ProtoService(); + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + }); + }); + }); + + describe('retry strategy', () => { + let retryRequestReqOpts; + let retryRequestOptions; + let retryRequestCallback; + + beforeEach(() => { + retryRequestOverride = (reqOpts, options, callback) => { + retryRequestReqOpts = reqOpts; + retryRequestOptions = options; + retryRequestCallback = callback; + }; + }); + + it('should use retry-request', done => { + const error = {}; + const response = {}; + + grpcService.request(PROTO_OPTS, REQ_OPTS, (err, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(resp, response); + done(); + }); + + assert.strictEqual(retryRequestReqOpts, null); + assert.strictEqual(retryRequestOptions.retries, grpcService.maxRetries); + assert.strictEqual(retryRequestOptions.currentRetryAttempt, 0); + + retryRequestCallback(error, response); + }); + + it('should retry on 429, 500, 502, and 503', () => { + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + + const shouldRetryFn = retryRequestOptions.shouldRetryFn; + + const retryErrors = [ + {code: 429}, + {code: 500}, + {code: 502}, + {code: 503}, + ]; + + const nonRetryErrors = [ + {code: 200}, + {code: 401}, + {code: 404}, + {code: 409}, + {code: 412}, + ]; + + assert.strictEqual(retryErrors.every(shouldRetryFn), true); + assert.strictEqual(nonRetryErrors.every(shouldRetryFn), false); + }); + + it('should treat a retriable error as an HTTP response', done => { + const grpcError500 = {code: 2}; + + grpcService.getService_ = () => { + return { + method(reqOpts, metadata, grpcOpts, callback) { + callback(grpcError500); + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + + const onResponse = (err, resp) => { + assert.strictEqual(err, null); + assert.deepStrictEqual(resp, GrpcService.GRPC_ERROR_CODE_TO_HTTP[2]); + done(); + }; + + retryRequestOptions.request({}, onResponse); + }); + + it('should return grpc request', () => { + const grpcRequest = {}; + + grpcService.getService_ = () => { + return { + method() { + return grpcRequest; + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + + const request = retryRequestOptions.request(); + assert.strictEqual(request, grpcRequest); + }); + + it('should exec callback with response error as error', done => { + const grpcError500 = {code: 2}; + + grpcService.getService_ = () => { + return { + method(reqOpts, metadata, grpcOpts, callback) { + callback(grpcError500); + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, (err, resp) => { + assert.deepStrictEqual(err, GrpcService.GRPC_ERROR_CODE_TO_HTTP[2]); + assert.strictEqual(resp, null); + done(); + }); + + // When the gRPC error is passed to "onResponse", it will just invoke + // the callback passed to retry-request. We will check if the grpc Error + retryRequestOptions.request({}, retryRequestCallback); + }); + + it('should exec callback with unknown error', done => { + const unknownError = {a: 'a'}; + + grpcService.getService_ = () => { + return { + method(reqOpts, metadata, grpcOpts, callback) { + callback(unknownError, null); + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, (err, resp) => { + assert.strictEqual(err, unknownError); + assert.strictEqual(resp, null); + done(); + }); + + // When the gRPC error is passed to "onResponse", it will just invoke + // the callback passed to retry-request. We will check if the grpc Error + retryRequestOptions.request({}, retryRequestCallback); + }); + }); + + describe('request option decoration', () => { + describe('decoration success', () => { + it('should decorate the request', done => { + const decoratedRequest = {}; + + grpcService.decorateRequest_ = reqOpts => { + assert.deepStrictEqual(reqOpts, REQ_OPTS); + return decoratedRequest; + }; + + grpcService.getService_ = () => { + return { + method(reqOpts) { + assert.strictEqual(reqOpts, decoratedRequest); + done(); + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + }); + }); + + describe('decoration error', () => { + const error = new Error('Error.'); + + it('should return a thrown error to the callback', done => { + grpcService.decorateRequest_ = () => { + throw error; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + }); + + describe('retry request', () => { + it('should make the correct request on the service', done => { + grpcService.getService_ = () => { + return { + method(reqOpts) { + assert.deepStrictEqual(reqOpts, REQ_OPTS); + done(); + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + }); + + it('should pass the grpc metadata with the request', done => { + grpcService.getService_ = () => { + return { + method(reqOpts, metadata) { + assert.strictEqual(metadata, grpcService.grpcMetadata); + done(); + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + }); + + it('should set a deadline if a timeout is provided', done => { + const expectedDeadlineRange = [ + Date.now() + PROTO_OPTS.timeout - 250, + Date.now() + PROTO_OPTS.timeout + 250, + ]; + + grpcService.getService_ = () => { + return { + method(reqOpts, metadata, grpcOpts) { + assert(isDate(grpcOpts.deadline)); + + assert(grpcOpts.deadline.getTime() > expectedDeadlineRange[0]); + assert(grpcOpts.deadline.getTime() < expectedDeadlineRange[1]); + + done(); + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, assert.ifError); + }); + + describe('request response error', () => { + it('should look up the http status from the code', () => { + // tslint:disable-next-line:forin + for (const grpcErrorCode in GrpcService.GRPC_ERROR_CODE_TO_HTTP) { + const grpcError = {code: grpcErrorCode}; + const httpError = + GrpcService.GRPC_ERROR_CODE_TO_HTTP[grpcErrorCode]; + + grpcService.getService_ = () => { + return { + method(reqOpts, metadata, grpcOpts, callback) { + callback(grpcError); + }, + }; + }; + + grpcService.request(PROTO_OPTS, REQ_OPTS, err => { + assert.strictEqual(err.code, httpError.code); + }); + } + /*jshint loopfunc:false */ + }); + }); + + describe('request response success', () => { + const RESPONSE = {}; + + beforeEach(() => { + grpcService.getService_ = () => { + return { + method(reqOpts, metadata, grpcOpts, callback) { + callback(null, RESPONSE); + }, + }; + }; + }); + + it('should execute callback with response', done => { + grpcService.request(PROTO_OPTS, REQ_OPTS, (err, resp) => { + assert.ifError(err); + assert.strictEqual(resp, RESPONSE); + done(); + }); + }); + }); + }); + }); + + describe('requestStream', () => { + let PROTO_OPTS; + const REQ_OPTS = {}; + const GRPC_CREDENTIALS = {}; + let fakeStream; + + function ProtoService() {} + + beforeEach(() => { + PROTO_OPTS = {service: 'service', method: 'method', timeout: 3000}; + ProtoService.prototype.method = () => {}; + + grpcService.grpcCredentials = GRPC_CREDENTIALS; + grpcService.baseUrl = 'http://base-url'; + grpcService.proto = {}; + grpcService.proto.service = ProtoService; + + grpcService.getService_ = () => { + return new ProtoService(); + }; + + fakeStream = new PassThrough({objectMode: true}); + retryRequestOverride = () => { + return fakeStream; + }; + }); + + afterEach(() => { + retryRequestOverride = null; + }); + + it('should not run in the gcloud sandbox environment', () => { + delete grpcService.grpcCredentials; + + grpcService.getGrpcCredentials_ = () => { + throw new Error('Should not be called.'); + }; + + glob.GCLOUD_SANDBOX_ENV = true; + grpcService.requestStream(); + delete glob.GCLOUD_SANDBOX_ENV; + }); + + describe('getting gRPC credentials', () => { + beforeEach(() => { + delete grpcService.grpcCredentials; + }); + + describe('credentials error', () => { + const error = new Error('err'); + + beforeEach(() => { + grpcService.getGrpcCredentials_ = callback => { + callback(error); + }; + }); + + it('should execute callback with error', done => { + grpcService.requestStream(PROTO_OPTS, REQ_OPTS).on('error', err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('credentials success', () => { + const authClient = {}; + + beforeEach(() => { + grpcService.getGrpcCredentials_ = callback => { + callback(null, authClient); + }; + }); + + it('should make the gRPC request again', done => { + grpcService.getService_ = () => { + assert.strictEqual(grpcService.grpcCredentials, authClient); + setImmediate(done); + return new ProtoService(); + }; + + grpcService.requestStream(PROTO_OPTS, REQ_OPTS).on('error', done); + }); + }); + }); + + it('should get the proto service', done => { + grpcService.getService_ = protoOpts => { + assert.strictEqual(protoOpts, PROTO_OPTS); + setImmediate(done); + return new ProtoService(); + }; + + grpcService.requestStream(PROTO_OPTS, REQ_OPTS, assert.ifError); + }); + + it('should set the deadline', done => { + const createDeadline = GrpcService.createDeadline_; + const fakeDeadline = createDeadline(PROTO_OPTS.timeout); + + GrpcService.createDeadline_ = timeout => { + assert.strictEqual(timeout, PROTO_OPTS.timeout); + return fakeDeadline; + }; + + ProtoService.prototype.method = (reqOpts, metadata, grpcOpts) => { + assert.strictEqual(grpcOpts.deadline, fakeDeadline); + + GrpcService.createDeadline_ = createDeadline; + setImmediate(done); + + return new PassThrough({objectMode: true}); + }; + + retryRequestOverride = (_, retryOpts) => { + return retryOpts.request(); + }; + + grpcService.requestStream(PROTO_OPTS, REQ_OPTS); + }); + + it('should pass the grpc metadata with the request', done => { + ProtoService.prototype.method = (reqOpts, metadata) => { + assert.strictEqual(metadata, grpcService.grpcMetadata); + setImmediate(done); + return new PassThrough({objectMode: true}); + }; + + retryRequestOverride = (_, retryOpts) => { + return retryOpts.request(); + }; + + grpcService.requestStream(PROTO_OPTS, REQ_OPTS); + }); + + describe('request option decoration', () => { + beforeEach(() => { + ProtoService.prototype.method = () => { + return new PassThrough({objectMode: true}); + }; + + retryRequestOverride = (reqOpts, options) => { + return options.request(); + }; + }); + + describe('requestStream() success', () => { + it('should decorate the request', done => { + const decoratedRequest = {}; + + grpcService.decorateRequest_ = reqOpts => { + assert.strictEqual(reqOpts, REQ_OPTS); + return decoratedRequest; + }; + + ProtoService.prototype.method = reqOpts => { + assert.strictEqual(reqOpts, decoratedRequest); + setImmediate(done); + return new PassThrough({objectMode: true}); + }; + + grpcService + .requestStream(PROTO_OPTS, REQ_OPTS) + .on('error', assert.ifError); + }); + }); + + describe('requestStream() error', () => { + it('should end stream with a thrown error', done => { + const error = new Error('Error.'); + + grpcService.decorateRequest_ = () => { + throw error; + }; + + grpcService.requestStream(PROTO_OPTS, REQ_OPTS).on('error', err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + }); + + describe('retry strategy', () => { + let retryRequestReqOpts; + let retryRequestOptions; + let retryStream; + + beforeEach(() => { + retryRequestReqOpts = retryRequestOptions = null; + retryStream = new PassThrough({objectMode: true}); + + retryRequestOverride = (reqOpts, options) => { + retryRequestReqOpts = reqOpts; + retryRequestOptions = options; + return retryStream; + }; + }); + + afterEach(() => { + retryRequestOverride = null; + }); + + it('should use retry-request', () => { + const reqOpts = Object.assign( + { + objectMode: true, + }, + REQ_OPTS, + ); + + grpcService.requestStream(PROTO_OPTS, reqOpts); + + assert.strictEqual(retryRequestReqOpts, null); + assert.strictEqual(retryRequestOptions.retries, grpcService.maxRetries); + assert.strictEqual(retryRequestOptions.currentRetryAttempt, 0); + assert.strictEqual(retryRequestOptions.objectMode, true); + assert.strictEqual( + retryRequestOptions.shouldRetryFn, + GrpcService.shouldRetryRequest_, + ); + }); + + it('should emit the metadata event as a response event', done => { + const fakeStream = new PassThrough({objectMode: true}); + + ProtoService.prototype.method = () => { + return fakeStream; + }; + + retryRequestOverride = (reqOpts, options) => { + return options.request(); + }; + + fakeStream.on('error', done).on('response', resp => { + assert.deepStrictEqual(resp, GrpcService.GRPC_ERROR_CODE_TO_HTTP[0]); + done(); + }); + + grpcService.requestStream(PROTO_OPTS, REQ_OPTS); + fakeStream.emit('metadata'); + }); + + it('should forward `request` events', done => { + const requestStream = grpcService.requestStream(PROTO_OPTS, REQ_OPTS); + + requestStream.on('request', () => { + done(); + }); + + retryStream.emit('request'); + }); + + it('should emit the response error', done => { + const grpcError500 = {code: 2}; + const requestStream = grpcService.requestStream(PROTO_OPTS, REQ_OPTS); + + requestStream.destroy = err => { + assert.deepStrictEqual(err, GrpcService.GRPC_ERROR_CODE_TO_HTTP[2]); + done(); + }; + + retryStream.emit('error', grpcError500); + }); + }); + }); + + describe('requestWritableStream', () => { + let PROTO_OPTS; + const REQ_OPTS = {}; + const GRPC_CREDENTIALS = {}; + + function ProtoService() {} + + beforeEach(() => { + PROTO_OPTS = {service: 'service', method: 'method', timeout: 3000}; + ProtoService.prototype.method = () => {}; + + grpcService.grpcCredentials = GRPC_CREDENTIALS; + grpcService.baseUrl = 'http://base-url'; + grpcService.proto = {}; + grpcService.proto.service = ProtoService; + + grpcService.getService_ = () => { + return new ProtoService(); + }; + }); + + it('should not run in the gcloud sandbox environment', () => { + delete grpcService.grpcCredentials; + + grpcService.getGrpcCredentials_ = () => { + throw new Error('Should not be called.'); + }; + + glob.GCLOUD_SANDBOX_ENV = true; + grpcService.requestWritableStream({}); + + delete glob.GCLOUD_SANDBOX_ENV; + }); + + it('should get the proto service', done => { + ProtoService.prototype.method = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return (duplexify as any).obj(); + }; + grpcService.getService_ = protoOpts => { + assert.strictEqual(protoOpts, PROTO_OPTS); + setImmediate(done); + return new ProtoService(); + }; + + grpcService.requestWritableStream(PROTO_OPTS, REQ_OPTS); + }); + + it('should set the deadline', done => { + const createDeadline = GrpcService.createDeadline_; + const fakeDeadline = createDeadline(PROTO_OPTS.timeout); + + GrpcService.createDeadline_ = timeout => { + assert.strictEqual(timeout, PROTO_OPTS.timeout); + return fakeDeadline; + }; + + ProtoService.prototype.method = (reqOpts, metadata, grpcOpts) => { + assert.strictEqual(grpcOpts.deadline, fakeDeadline); + + GrpcService.createDeadline_ = createDeadline; + setImmediate(done); + + return new PassThrough({objectMode: true}); + }; + + retryRequestOverride = (_, retryOpts) => { + return retryOpts.request(); + }; + + grpcService.requestWritableStream(PROTO_OPTS, REQ_OPTS); + }); + + it('should pass the grpc metadata with the request', done => { + ProtoService.prototype.method = (reqOpts, metadata) => { + assert.strictEqual(metadata, grpcService.grpcMetadata); + setImmediate(done); + return new PassThrough({objectMode: true}); + }; + + retryRequestOverride = (_, retryOpts) => { + return retryOpts.request(); + }; + + grpcService.requestWritableStream(PROTO_OPTS, REQ_OPTS); + }); + + describe('getting gRPC credentials', () => { + beforeEach(() => { + delete grpcService.grpcCredentials; + }); + + describe('grpcCredentials error', () => { + const error = new Error('err'); + + beforeEach(() => { + grpcService.getGrpcCredentials_ = callback => { + setImmediate(() => { + callback(error); + }); + }; + }); + + it('should execute callback with error', done => { + grpcService + .requestWritableStream(PROTO_OPTS, REQ_OPTS) + .on('error', err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('grpcCredentials success', () => { + const authClient = {}; + + beforeEach(() => { + grpcService.getGrpcCredentials_ = callback => { + callback(null, authClient); + }; + }); + + it('should make the gRPC request again', done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const stream = (duplexify as any).obj(); + ProtoService.prototype.method = () => { + return stream; + }; + grpcService.getService_ = () => { + assert.strictEqual(grpcService.grpcCredentials, authClient); + setImmediate(done); + return new ProtoService(); + }; + + grpcService.requestWritableStream(PROTO_OPTS, REQ_OPTS); + }); + }); + }); + + describe('request option decoration', () => { + beforeEach(() => { + ProtoService.prototype.method = () => { + return new PassThrough({objectMode: true}); + }; + + retryRequestOverride = (reqOpts, options) => { + return options.request(); + }; + }); + + describe('requestWritableStream() success', () => { + it('should decorate the request', done => { + const decoratedRequest = {}; + + grpcService.decorateRequest_ = reqOpts => { + assert.strictEqual(reqOpts, REQ_OPTS); + return decoratedRequest; + }; + + ProtoService.prototype.method = reqOpts => { + assert.strictEqual(reqOpts, decoratedRequest); + setImmediate(done); + return new PassThrough({objectMode: true}); + }; + + grpcService.requestWritableStream(PROTO_OPTS, REQ_OPTS); + }); + }); + + describe('requestWritableStream() error', () => { + const error = new Error('Error.'); + + it('should end stream with a thrown error', done => { + grpcService.decorateRequest_ = () => { + throw error; + }; + + grpcService + .requestWritableStream(PROTO_OPTS, REQ_OPTS) + .on('error', err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + }); + + describe('stream success', () => { + const authClient = {}; + + beforeEach(() => { + delete grpcService.grpcCredentials; + grpcService.getGrpcCredentials_ = callback => { + callback(null, authClient); + }; + sinon.spy(GrpcService, 'decorateStatus_'); + }); + + it('should emit response', done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const stream = (duplexify as any).obj(); + ProtoService.prototype.method = () => { + return stream; + }; + grpcService.getService_ = () => { + assert.strictEqual(grpcService.grpcCredentials, authClient); + return new ProtoService(); + }; + + grpcService + .requestWritableStream(PROTO_OPTS, REQ_OPTS) + .on('response', status => { + assert.strictEqual(status, 'foo'); + assert.strictEqual(GrpcService.decorateStatus_.callCount, 1); + assert(GrpcService.decorateStatus_.calledWith('foo')); + GrpcService.decorateStatus_.restore(); + done(); + }) + .on('error', done); + + setImmediate(() => { + stream.emit('status', 'foo'); + }); + }); + }); + + describe('stream error', () => { + const authClient = {}; + + beforeEach(() => { + delete grpcService.grpcCredentials; + grpcService.getGrpcCredentials_ = callback => { + callback(null, authClient); + }; + }); + + it('should emit a decorated error', done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const grpcStream = (duplexify as any).obj(); + ProtoService.prototype.method = () => { + return grpcStream; + }; + grpcService.getService_ = () => { + assert.strictEqual(grpcService.grpcCredentials, authClient); + return new ProtoService(); + }; + + const error = new Error('Error.'); + const expectedDecoratedError = new Error('Decorated error.'); + + sinon.stub(GrpcService, 'decorateError_').callsFake(() => { + return expectedDecoratedError; + }); + + const stream = grpcService.requestWritableStream(PROTO_OPTS, REQ_OPTS); + + stream.on('error', err => { + assert.strictEqual(err, expectedDecoratedError); + assert.strictEqual(GrpcService.decorateError_.callCount, 1); + assert(GrpcService.decorateError_.calledWith(error)); + GrpcService.decorateError_.restore(); + done(); + }); + + setImmediate(() => { + grpcStream.emit('error', error); + }); + }); + + it('should emit the original error', done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const grpcStream = (duplexify as any).obj(); + ProtoService.prototype.method = () => grpcStream; + grpcService.getService_ = () => { + assert.strictEqual(grpcService.grpcCredentials, authClient); + return new ProtoService(); + }; + const error = new Error('Error.'); + sinon.stub(GrpcService, 'decorateError_').returns(null!); + const stream = grpcService.requestWritableStream(PROTO_OPTS, REQ_OPTS); + stream.on('error', err => { + assert.strictEqual(err, error); + assert.strictEqual(GrpcService.decorateError_.callCount, 1); + assert(GrpcService.decorateError_.calledWith(error)); + GrpcService.decorateError_.restore(); + done(); + }); + + setImmediate(() => { + grpcStream.emit('error', error); + }); + }); + }); + }); + + describe('encodeValue_', () => { + it('should encode value using ObjectToStructConverter fn', () => { + const obj = {}; + const convertedObject = {}; + sinon.stub(GrpcService, 'ObjectToStructConverter').returns({ + encodeValue_(obj_) { + assert.strictEqual(obj_, obj); + return convertedObject; + }, + }); + assert.strictEqual(GrpcService.encodeValue_(obj), convertedObject); + }); + }); + + describe('createDeadline_', () => { + const nowTimestamp = Date.now(); + let now; + + before(() => { + now = Date.now; + + Date.now = () => { + return nowTimestamp; + }; + }); + + after(() => { + Date.now = now; + }); + + it('should create a deadline', () => { + const timeout = 3000; + const deadline = GrpcService.createDeadline_(timeout); + + assert.strictEqual(deadline.getTime(), nowTimestamp + timeout); + }); + }); + + describe('decorateError_', () => { + const expectedDecoratedError = new Error('err.'); + + beforeEach(() => { + sinon.stub(GrpcService, 'decorateGrpcResponse_').callsFake(() => { + return expectedDecoratedError; + }); + }); + + it('should decorate an Error object', () => { + const grpcError = new Error('Hello'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (grpcError as any).code = 2; + + const decoratedError = GrpcService.decorateError_(grpcError); + const decorateArgs = GrpcService.decorateGrpcResponse_.getCall(0).args; + + assert.strictEqual(decoratedError, expectedDecoratedError); + assert.strictEqual(decorateArgs[0] instanceof Error, true); + assert.strictEqual(decorateArgs[1], grpcError); + }); + + it('should decorate a plain object', () => { + const grpcMessage = {code: 2}; + + const decoratedError = GrpcService.decorateError_(grpcMessage); + const decorateArgs = GrpcService.decorateGrpcResponse_.getCall(0).args; + + assert.strictEqual(decoratedError, expectedDecoratedError); + assert.deepStrictEqual(decorateArgs[0], {}); + assert.strictEqual(decorateArgs[0] instanceof Error, false); + assert.strictEqual(decorateArgs[1], grpcMessage); + }); + }); + + describe('decorateGrpcResponse_', () => { + it('should retrieve the HTTP code from the gRPC error map', () => { + const errorMap = GrpcService.GRPC_ERROR_CODE_TO_HTTP; + const codes = Object.keys(errorMap); + + codes.forEach(code => { + const error = new Error(); + const extended = GrpcService.decorateGrpcResponse_(error, {code}); + + assert.notStrictEqual(extended, errorMap[code]); + assert.strictEqual(extended.code, errorMap[code].code); + assert.strictEqual(extended.message, errorMap[code].message); + assert.strictEqual(error, extended); + }); + }); + + it('should use the message from the error', () => { + const errorMessage = 'This is an error message.'; + + const err = { + code: 1, + message: errorMessage, + }; + + const error = new Error(); + const extended = GrpcService.decorateGrpcResponse_(error, err); + + assert.strictEqual(extended.message, errorMessage); + }); + + it('should use a stringified JSON message from the error', () => { + const errorMessage = 'This is an error message.'; + + const err = { + code: 1, + message: JSON.stringify({ + description: errorMessage, + }), + }; + + const error = new Error(); + const extended = GrpcService.decorateGrpcResponse_(error, err); + + assert.strictEqual(extended.message, errorMessage); + }); + + it('should return null for unknown errors', () => { + const error = new Error(); + const extended = GrpcService.decorateGrpcResponse_(error, {code: 9999}); + + assert.strictEqual(extended, null); + }); + }); + + describe('decorateStatus_', () => { + const fakeStatus = {status: 'a'}; + + beforeEach(() => { + sinon.stub(GrpcService, 'decorateGrpcResponse_').callsFake(() => { + return fakeStatus; + }); + }); + + it('should call decorateGrpcResponse_ with an object', () => { + const grpcStatus = {code: 2}; + + const status = GrpcService.decorateStatus_(grpcStatus); + const args = GrpcService.decorateGrpcResponse_.getCall(0).args; + + assert.strictEqual(status, fakeStatus); + assert.deepStrictEqual(args[0], {}); + assert.strictEqual(args[1], grpcStatus); + }); + }); + + describe('shouldRetryRequest_', () => { + it('should retry on 429, 500, 502, and 503', () => { + const shouldRetryFn = GrpcService.shouldRetryRequest_; + + const retryErrors = [{code: 429}, {code: 500}, {code: 502}, {code: 503}]; + + const nonRetryErrors = [ + {code: 200}, + {code: 401}, + {code: 404}, + {code: 409}, + {code: 412}, + ]; + + assert.strictEqual(retryErrors.every(shouldRetryFn), true); + assert.strictEqual(nonRetryErrors.every(shouldRetryFn), false); + }); + }); + + describe('decorateRequest_', () => { + it('should delete custom API values without modifying object', () => { + const reqOpts = { + autoPaginate: true, + autoPaginateVal: true, + objectMode: true, + }; + + const originalReqOpts = Object.assign({}, reqOpts); + + assert.deepStrictEqual(grpcService.decorateRequest_(reqOpts), {}); + assert.deepStrictEqual(reqOpts, originalReqOpts); + }); + + it('should execute and return replaceProjectIdToken', () => { + const reqOpts = { + a: 'b', + c: 'd', + }; + + const replacedReqOpts = {}; + + replaceProjectIdTokenOverride = (reqOpts_, projectId) => { + assert.deepStrictEqual(reqOpts_, reqOpts); + assert.strictEqual(projectId, grpcService.projectId); + return replacedReqOpts; + }; + + assert.strictEqual( + grpcService.decorateRequest_(reqOpts), + replacedReqOpts, + ); + }); + }); + + describe('getGrpcCredentials_', () => { + it('should get credentials from the auth client', done => { + grpcService.authClient = { + async getClient() { + return ''; + }, + }; + + grpcService.getGrpcCredentials_(done); + }); + + describe('credential fetching error', () => { + const error = new Error('Error.'); + + beforeEach(() => { + grpcService.authClient = { + async getClient() { + throw error; + }, + }; + }); + + it('should execute callback with error', done => { + grpcService.getGrpcCredentials_(err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('credential fetching success', () => { + const AUTH_CLIENT = { + projectId: 'project-id', + }; + + beforeEach(() => { + grpcService.authClient = { + async getClient() { + return AUTH_CLIENT; + }, + }; + }); + + it('should return grpcCredentials', done => { + grpcService.getGrpcCredentials_((err, grpcCredentials) => { + assert.ifError(err); + assert(grpcCredentials.constructor.name.match(/credentials/i)); + done(); + }); + }); + + it('should set projectId', done => { + grpcService.getGrpcCredentials_(err => { + assert.ifError(err); + assert.strictEqual(grpcService.projectId, AUTH_CLIENT.projectId); + done(); + }); + }); + + it('should not change projectId that was already set', done => { + grpcService.projectId = 'project-id'; + + grpcService.getGrpcCredentials_(err => { + assert.ifError(err); + assert.strictEqual(grpcService.projectId, AUTH_CLIENT.projectId); + done(); + }); + }); + + it('should change placeholder projectId', done => { + grpcService.projectId = '{{projectId}}'; + + grpcService.getGrpcCredentials_(err => { + assert.ifError(err); + assert.strictEqual(grpcService.projectId, AUTH_CLIENT.projectId); + done(); + }); + }); + + it('should not update projectId if it was not found', done => { + grpcService.projectId = 'project-id'; + + grpcService.authClient = { + async getClient() { + return { + projectId: undefined, + }; + }, + }; + + grpcService.getGrpcCredentials_(err => { + assert.ifError(err); + assert.strictEqual(grpcService.projectId, grpcService.projectId); + done(); + }); + }); + }); + }); + + describe('loadProtoFile', () => { + const fakeServices: grpcProtoLoader.PackageDefinition = { + 'google.FakeService': {}, + }; + + it('should load a proto file', () => { + const fakeProtoPath = '/root/dir/path'; + + const fakeMainConfig = { + protosDir: ROOT_DIR, + }; + + grpcProtoLoadOverride = (file, options) => { + assert.deepStrictEqual(options!.includeDirs, [ + fakeMainConfig.protosDir, + gaxProtosDir, + ]); + assert.strictEqual(file, fakeProtoPath); + + assert.strictEqual(options!.bytes, String); + assert.strictEqual(options!.keepCase, false); + + return fakeServices; + }; + + const services = grpcService.loadProtoFile(fakeProtoPath, fakeMainConfig); + assert.deepStrictEqual(services, fakeServices); + }); + + it('should cache the expensive proto object creation', () => { + const protoPath = '/root/dir/path'; + + const mainConfig = { + service: 'OtherFakeService', + apiVersion: 'v2', + }; + + let gprcLoadCalled = 0; + grpcProtoLoadOverride = () => { + gprcLoadCalled++; + return fakeServices; + }; + + const services1 = grpcService.loadProtoFile(protoPath, mainConfig); + const services2 = grpcService.loadProtoFile(protoPath, mainConfig); + assert.strictEqual(services1, services2); + assert.strictEqual(gprcLoadCalled, 1); + }); + + it('should return the services object if invalid version', () => { + const fakeProtoPath = '/root/dir/path'; + + const fakeMainConfig = { + service: 'OtherFakeService', + apiVersion: 'v2', + }; + + grpcProtoLoadOverride = () => { + return fakeServices; + }; + + const services = grpcService.loadProtoFile(fakeProtoPath, fakeMainConfig); + assert.deepStrictEqual(services, fakeServices); + }); + }); + + describe('getService_', () => { + it('should get a new service instance', () => { + const fakeService = {}; + grpcService.protos = { + Service: { + Service: class Service { + constructor(baseUrl, grpcCredentials, userAgent) { + assert.strictEqual(baseUrl, grpcService.baseUrl); + assert.strictEqual(grpcCredentials, grpcService.grpcCredentials); + assert.deepStrictEqual( + userAgent, + Object.assign( + { + 'grpc.primary_user_agent': grpcService.userAgent, + }, + GrpcService.GRPC_SERVICE_OPTIONS, + ), + ); + + return fakeService; + } + }, + }, + }; + + const service = grpcService.getService_({service: 'Service'}); + assert.strictEqual(service, fakeService); + + const cachedService = grpcService.activeServiceMap_.get('Service'); + assert.strictEqual(cachedService, fakeService); + }); + + it('should return the cached version of a service', () => { + const fakeService = {}; + + grpcService.protos = { + Service: { + Service() { + throw new Error('should not be called'); + }, + }, + }; + + grpcService.activeServiceMap_.set('Service', fakeService); + + const service = grpcService.getService_({service: 'Service'}); + assert.strictEqual(service, fakeService); + + const cachedService = grpcService.activeServiceMap_.get('Service'); + assert.strictEqual(cachedService, fakeService); + }); + + it('should use the baseUrl override if applicable', () => { + const fakeBaseUrl = 'a.googleapis.com'; + const fakeService = {}; + + grpcService.protos = { + Service: { + baseUrl: fakeBaseUrl, + Service: class Service { + constructor(baseUrl) { + assert.strictEqual(baseUrl, fakeBaseUrl); + return fakeService; + } + }, + }, + }; + + const service = grpcService.getService_({service: 'Service'}); + assert.strictEqual(service, fakeService); + }); + }); + + describe('ObjectToStructConverter', () => { + let objectToStructConverter; + + beforeEach(() => { + objectToStructConverter = new ObjectToStructConverter(OPTIONS); + }); + + describe('instantiation', () => { + it('should not require an options object', () => { + assert.doesNotThrow(() => { + new ObjectToStructConverter(); + }); + }); + + it('should localize an empty Set for seenObjects', () => { + assert(objectToStructConverter.seenObjects instanceof Set); + assert.strictEqual(objectToStructConverter.seenObjects.size, 0); + }); + + it('should localize options', () => { + const objectToStructConverter = new ObjectToStructConverter({ + removeCircular: true, + stringify: true, + }); + + assert.strictEqual(objectToStructConverter.removeCircular, true); + assert.strictEqual(objectToStructConverter.stringify, true); + }); + + it('should set correct defaults', () => { + assert.strictEqual(objectToStructConverter.removeCircular, false); + assert.strictEqual(objectToStructConverter.stringify, false); + }); + }); + + describe('convert', () => { + it('should encode values in an Object', () => { + const inputValue = {}; + const convertedValue = {}; + + objectToStructConverter.encodeValue_ = value => { + assert.strictEqual(value, inputValue); + return convertedValue; + }; + + const struct = objectToStructConverter.convert({ + a: inputValue, + }); + + assert.strictEqual(struct.fields.a, convertedValue); + }); + + it('should support host objects', () => { + const hostObject = {hasOwnProperty: null}; + + objectToStructConverter.encodeValue_ = () => {}; + + assert.doesNotThrow(() => { + objectToStructConverter.convert(hostObject); + }); + }); + + it('should not include undefined values', done => { + objectToStructConverter.encodeValue_ = () => { + done(new Error('Should not be called')); + }; + + const struct = objectToStructConverter.convert({ + a: undefined, + }); + + assert.deepStrictEqual(struct.fields, {}); + + done(); + }); + + it('should add seen objects to set then empty set', done => { + const obj = {}; + let objectAdded; + + objectToStructConverter.seenObjects = { + add(obj) { + objectAdded = obj; + }, + delete(obj_) { + assert.strictEqual(obj_, obj); + assert.strictEqual(objectAdded, obj); + done(); + }, + }; + + objectToStructConverter.convert(obj); + }); + }); + + describe('encodeValue_', () => { + it('should convert primitive values correctly', () => { + const buffer = Buffer.from('Value'); + + assert.deepStrictEqual(objectToStructConverter.encodeValue_(null), { + nullValue: 0, + }); + + assert.deepStrictEqual(objectToStructConverter.encodeValue_(1), { + numberValue: 1, + }); + + assert.deepStrictEqual(objectToStructConverter.encodeValue_('Hi'), { + stringValue: 'Hi', + }); + + assert.deepStrictEqual(objectToStructConverter.encodeValue_(true), { + boolValue: true, + }); + + assert.strictEqual( + objectToStructConverter.encodeValue_(buffer).blobValue.toString(), + 'Value', + ); + }); + + it('should convert arrays', () => { + const convertedValue = objectToStructConverter.encodeValue_([1, 2, 3]); + + assert.deepStrictEqual(convertedValue.listValue, { + values: [ + objectToStructConverter.encodeValue_(1), + objectToStructConverter.encodeValue_(2), + objectToStructConverter.encodeValue_(3), + ], + }); + }); + + it('should throw if a type is not recognized', () => { + assert.throws(() => { + objectToStructConverter.encodeValue_(); + }, /Value of type undefined not recognized./); + }); + + describe('objects', () => { + const VALUE: {circularReference?: {}} = {}; + VALUE.circularReference = VALUE; + + it('should convert objects', () => { + const convertedValue = {}; + + objectToStructConverter.convert = value => { + assert.strictEqual(value, VALUE); + return convertedValue; + }; + + assert.deepStrictEqual(objectToStructConverter.encodeValue_(VALUE), { + structValue: convertedValue, + }); + }); + + describe('circular references', () => { + it('should throw if circular', () => { + const errorMessage = [ + 'This object contains a circular reference. To automatically', + 'remove it, set the `removeCircular` option to true.', + ].join(' '); + + objectToStructConverter.seenObjects.add(VALUE); + + assert.throws(() => { + objectToStructConverter.encodeValue_(VALUE); + }, new RegExp(errorMessage)); + }); + + describe('options.removeCircular', () => { + let objectToStructConverter; + + beforeEach(() => { + objectToStructConverter = new ObjectToStructConverter({ + removeCircular: true, + }); + + objectToStructConverter.seenObjects.add(VALUE); + }); + + it('should replace circular reference with [Circular]', () => { + assert.deepStrictEqual( + objectToStructConverter.encodeValue_(VALUE), + {stringValue: '[Circular]'}, + ); + }); + }); + }); + }); + + describe('options.stringify', () => { + let objectToStructConverter; + + beforeEach(() => { + objectToStructConverter = new ObjectToStructConverter({ + stringify: true, + }); + }); + + it('should return a string if the value is not recognized', () => { + const date = new Date(); + + assert.deepStrictEqual( + objectToStructConverter.encodeValue_(date, OPTIONS), + {stringValue: String(date)}, + ); + }); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/data/README.md b/handwritten/spanner/test/data/README.md new file mode 100644 index 00000000000..6de5c0ae0ec --- /dev/null +++ b/handwritten/spanner/test/data/README.md @@ -0,0 +1,8 @@ +#### To generate singer.js and singer.d.ts file from singer.proto +```shell +npm install -g protobufjs-cli +cd test/data +pbjs -t static-module -w commonjs -o singer.js singer.proto +pbts -o singer.d.ts singer.js +protoc --proto_path=. --include_imports --descriptor_set_out=descriptors.pb singer.proto +``` diff --git a/handwritten/spanner/test/data/descriptors.pb b/handwritten/spanner/test/data/descriptors.pb new file mode 100644 index 00000000000..10193075ede Binary files /dev/null and b/handwritten/spanner/test/data/descriptors.pb differ diff --git a/handwritten/spanner/test/data/singer.d.ts b/handwritten/spanner/test/data/singer.d.ts new file mode 100644 index 00000000000..07913d33bea --- /dev/null +++ b/handwritten/spanner/test/data/singer.d.ts @@ -0,0 +1,175 @@ +// 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 +// +// 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 * as $protobuf from 'protobufjs'; +import Long = require('long'); +/** Namespace examples. */ +export namespace examples { + /** Namespace spanner. */ + namespace spanner { + /** Namespace music. */ + namespace music { + /** Properties of a SingerInfo. */ + interface ISingerInfo { + /** SingerInfo singerId */ + singerId?: number | Long | null; + + /** SingerInfo birthDate */ + birthDate?: string | null; + + /** SingerInfo nationality */ + nationality?: string | null; + + /** SingerInfo genre */ + genre?: examples.spanner.music.Genre | null; + } + + /** Represents a SingerInfo. */ + class SingerInfo implements ISingerInfo { + /** + * Constructs a new SingerInfo. + * @param [properties] Properties to set + */ + constructor(properties?: examples.spanner.music.ISingerInfo); + + /** SingerInfo singerId. */ + public singerId?: number | Long | null; + + /** SingerInfo birthDate. */ + public birthDate?: string | null; + + /** SingerInfo nationality. */ + public nationality?: string | null; + + /** SingerInfo genre. */ + public genre?: examples.spanner.music.Genre | null; + + /** SingerInfo _singerId. */ + public _singerId?: 'singerId'; + + /** SingerInfo _birthDate. */ + public _birthDate?: 'birthDate'; + + /** SingerInfo _nationality. */ + public _nationality?: 'nationality'; + + /** SingerInfo _genre. */ + public _genre?: 'genre'; + + /** + * Creates a new SingerInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SingerInfo instance + */ + public static create( + properties?: examples.spanner.music.ISingerInfo, + ): examples.spanner.music.SingerInfo; + + /** + * Encodes the specified SingerInfo message. Does not implicitly {@link examples.spanner.music.SingerInfo.verify|verify} messages. + * @param message SingerInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode( + message: examples.spanner.music.ISingerInfo, + writer?: $protobuf.Writer, + ): $protobuf.Writer; + + /** + * Encodes the specified SingerInfo message, length delimited. Does not implicitly {@link examples.spanner.music.SingerInfo.verify|verify} messages. + * @param message SingerInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited( + message: examples.spanner.music.ISingerInfo, + writer?: $protobuf.Writer, + ): $protobuf.Writer; + + /** + * Decodes a SingerInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SingerInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode( + reader: $protobuf.Reader | Uint8Array, + length?: number, + ): examples.spanner.music.SingerInfo; + + /** + * Decodes a SingerInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SingerInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited( + reader: $protobuf.Reader | Uint8Array, + ): examples.spanner.music.SingerInfo; + + /** + * Verifies a SingerInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: {[k: string]: any}): string | null; + + /** + * Creates a SingerInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SingerInfo + */ + public static fromObject(object: { + [k: string]: any; + }): examples.spanner.music.SingerInfo; + + /** + * Creates a plain object from a SingerInfo message. Also converts values to other types if specified. + * @param message SingerInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject( + message: examples.spanner.music.SingerInfo, + options?: $protobuf.IConversionOptions, + ): {[k: string]: any}; + + /** + * Converts this SingerInfo to JSON. + * @returns JSON object + */ + public toJSON(): {[k: string]: any}; + + /** + * Gets the default type url for SingerInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Genre enum. */ + enum Genre { + POP = 0, + JAZZ = 1, + FOLK = 2, + ROCK = 3, + } + } + } +} diff --git a/handwritten/spanner/test/data/singer.js b/handwritten/spanner/test/data/singer.js new file mode 100644 index 00000000000..df7792d17a0 --- /dev/null +++ b/handwritten/spanner/test/data/singer.js @@ -0,0 +1,505 @@ +// 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 +// +// 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. + +/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ +'use strict'; + +var $protobuf = require('protobufjs/minimal'); + +// Common aliases +var $Reader = $protobuf.Reader, + $Writer = $protobuf.Writer, + $util = $protobuf.util; + +// Exported root namespace +var $root = $protobuf.roots['default'] || ($protobuf.roots['default'] = {}); + +$root.examples = (function () { + /** + * Namespace examples. + * @exports examples + * @namespace + */ + var examples = {}; + + examples.spanner = (function () { + /** + * Namespace spanner. + * @memberof examples + * @namespace + */ + var spanner = {}; + + spanner.music = (function () { + /** + * Namespace music. + * @memberof examples.spanner + * @namespace + */ + var music = {}; + + music.SingerInfo = (function () { + /** + * Properties of a SingerInfo. + * @memberof examples.spanner.music + * @interface ISingerInfo + * @property {number|Long|null} [singerId] SingerInfo singerId + * @property {string|null} [birthDate] SingerInfo birthDate + * @property {string|null} [nationality] SingerInfo nationality + * @property {examples.spanner.music.Genre|null} [genre] SingerInfo genre + */ + + /** + * Constructs a new SingerInfo. + * @memberof examples.spanner.music + * @classdesc Represents a SingerInfo. + * @implements ISingerInfo + * @constructor + * @param {examples.spanner.music.ISingerInfo=} [properties] Properties to set + */ + function SingerInfo(properties) { + if (properties) + for ( + var keys = Object.keys(properties), i = 0; + i < keys.length; + ++i + ) + if (properties[keys[i]] !== null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SingerInfo singerId. + * @member {number|Long|null|undefined} singerId + * @memberof examples.spanner.music.SingerInfo + * @instance + */ + SingerInfo.prototype.singerId = null; + + /** + * SingerInfo birthDate. + * @member {string|null|undefined} birthDate + * @memberof examples.spanner.music.SingerInfo + * @instance + */ + SingerInfo.prototype.birthDate = null; + + /** + * SingerInfo nationality. + * @member {string|null|undefined} nationality + * @memberof examples.spanner.music.SingerInfo + * @instance + */ + SingerInfo.prototype.nationality = null; + + /** + * SingerInfo genre. + * @member {examples.spanner.music.Genre|null|undefined} genre + * @memberof examples.spanner.music.SingerInfo + * @instance + */ + SingerInfo.prototype.genre = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * SingerInfo _singerId. + * @member {"singerId"|undefined} _singerId + * @memberof examples.spanner.music.SingerInfo + * @instance + */ + Object.defineProperty(SingerInfo.prototype, '_singerId', { + get: $util.oneOfGetter(($oneOfFields = ['singerId'])), + set: $util.oneOfSetter($oneOfFields), + }); + + /** + * SingerInfo _birthDate. + * @member {"birthDate"|undefined} _birthDate + * @memberof examples.spanner.music.SingerInfo + * @instance + */ + Object.defineProperty(SingerInfo.prototype, '_birthDate', { + get: $util.oneOfGetter(($oneOfFields = ['birthDate'])), + set: $util.oneOfSetter($oneOfFields), + }); + + /** + * SingerInfo _nationality. + * @member {"nationality"|undefined} _nationality + * @memberof examples.spanner.music.SingerInfo + * @instance + */ + Object.defineProperty(SingerInfo.prototype, '_nationality', { + get: $util.oneOfGetter(($oneOfFields = ['nationality'])), + set: $util.oneOfSetter($oneOfFields), + }); + + /** + * SingerInfo _genre. + * @member {"genre"|undefined} _genre + * @memberof examples.spanner.music.SingerInfo + * @instance + */ + Object.defineProperty(SingerInfo.prototype, '_genre', { + get: $util.oneOfGetter(($oneOfFields = ['genre'])), + set: $util.oneOfSetter($oneOfFields), + }); + + /** + * Creates a new SingerInfo instance using the specified properties. + * @function create + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {examples.spanner.music.ISingerInfo=} [properties] Properties to set + * @returns {examples.spanner.music.SingerInfo} SingerInfo instance + */ + SingerInfo.create = function create(properties) { + return new SingerInfo(properties); + }; + + /** + * Encodes the specified SingerInfo message. Does not implicitly {@link examples.spanner.music.SingerInfo.verify|verify} messages. + * @function encode + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {examples.spanner.music.ISingerInfo} message SingerInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SingerInfo.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create(); + if ( + message.singerId !== null && + Object.hasOwnProperty.call(message, 'singerId') + ) + writer.uint32(/* id 1, wireType 0 =*/ 8).int64(message.singerId); + if ( + message.birthDate !== null && + Object.hasOwnProperty.call(message, 'birthDate') + ) + writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.birthDate); + if ( + message.nationality !== null && + Object.hasOwnProperty.call(message, 'nationality') + ) + writer + .uint32(/* id 3, wireType 2 =*/ 26) + .string(message.nationality); + if ( + message.genre !== null && + Object.hasOwnProperty.call(message, 'genre') + ) + writer.uint32(/* id 4, wireType 0 =*/ 32).int32(message.genre); + return writer; + }; + + /** + * Encodes the specified SingerInfo message, length delimited. Does not implicitly {@link examples.spanner.music.SingerInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {examples.spanner.music.ISingerInfo} message SingerInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SingerInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SingerInfo message from the specified reader or buffer. + * @function decode + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {examples.spanner.music.SingerInfo} SingerInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SingerInfo.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, + message = new $root.examples.spanner.music.SingerInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + switch (tag >>> 3) { + case 1: { + message.singerId = reader.int64(); + break; + } + case 2: { + message.birthDate = reader.string(); + break; + } + case 3: { + message.nationality = reader.string(); + break; + } + case 4: { + message.genre = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SingerInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {examples.spanner.music.SingerInfo} SingerInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SingerInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SingerInfo message. + * @function verify + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SingerInfo.verify = function verify(message) { + if (typeof message !== 'object' || message === null) + return 'object expected'; + var properties = {}; + if (message.singerId !== null && message.hasOwnProperty('singerId')) { + properties._singerId = 1; + if ( + !$util.isInteger(message.singerId) && + !( + message.singerId && + $util.isInteger(message.singerId.low) && + $util.isInteger(message.singerId.high) + ) + ) + return 'singerId: integer|Long expected'; + } + if ( + message.birthDate !== null && + message.hasOwnProperty('birthDate') + ) { + properties._birthDate = 1; + if (!$util.isString(message.birthDate)) + return 'birthDate: string expected'; + } + if ( + message.nationality !== null && + message.hasOwnProperty('nationality') + ) { + properties._nationality = 1; + if (!$util.isString(message.nationality)) + return 'nationality: string expected'; + } + if (message.genre !== null && message.hasOwnProperty('genre')) { + properties._genre = 1; + switch (message.genre) { + default: + return 'genre: enum value expected'; + case 0: + case 1: + case 2: + case 3: + break; + } + } + return null; + }; + + /** + * Creates a SingerInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {Object.} object Plain object + * @returns {examples.spanner.music.SingerInfo} SingerInfo + */ + SingerInfo.fromObject = function fromObject(object) { + if (object instanceof $root.examples.spanner.music.SingerInfo) + return object; + var message = new $root.examples.spanner.music.SingerInfo(); + if (object.singerId !== null) + if ($util.Long) + (message.singerId = $util.Long.fromValue( + object.singerId, + )).unsigned = false; + else if (typeof object.singerId === 'string') + message.singerId = parseInt(object.singerId, 10); + else if (typeof object.singerId === 'number') + message.singerId = object.singerId; + else if (typeof object.singerId === 'object') + message.singerId = new $util.LongBits( + object.singerId.low >>> 0, + object.singerId.high >>> 0, + ).toNumber(); + if (object.birthDate !== null) + message.birthDate = String(object.birthDate); + if (object.nationality !== null) + message.nationality = String(object.nationality); + switch (object.genre) { + default: + if (typeof object.genre === 'number') { + message.genre = object.genre; + break; + } + break; + case 'POP': + case 0: + message.genre = 0; + break; + case 'JAZZ': + case 1: + message.genre = 1; + break; + case 'FOLK': + case 2: + message.genre = 2; + break; + case 'ROCK': + case 3: + message.genre = 3; + break; + } + return message; + }; + + /** + * Creates a plain object from a SingerInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {examples.spanner.music.SingerInfo} message SingerInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SingerInfo.toObject = function toObject(message, options) { + if (!options) options = {}; + var object = {}; + if (message.singerId !== null && message.hasOwnProperty('singerId')) { + if (typeof message.singerId === 'number') + object.singerId = + options.longs === String + ? String(message.singerId) + : message.singerId; + else + object.singerId = + options.longs === String + ? $util.Long.prototype.toString.call(message.singerId) + : options.longs === Number + ? new $util.LongBits( + message.singerId.low >>> 0, + message.singerId.high >>> 0, + ).toNumber() + : message.singerId; + if (options.oneofs) object._singerId = 'singerId'; + } + if ( + message.birthDate !== null && + message.hasOwnProperty('birthDate') + ) { + object.birthDate = message.birthDate; + if (options.oneofs) object._birthDate = 'birthDate'; + } + if ( + message.nationality !== null && + message.hasOwnProperty('nationality') + ) { + object.nationality = message.nationality; + if (options.oneofs) object._nationality = 'nationality'; + } + if (message.genre !== null && message.hasOwnProperty('genre')) { + object.genre = + options.enums === String + ? $root.examples.spanner.music.Genre[message.genre] === + undefined + ? message.genre + : $root.examples.spanner.music.Genre[message.genre] + : message.genre; + if (options.oneofs) object._genre = 'genre'; + } + return object; + }; + + /** + * Converts this SingerInfo to JSON. + * @function toJSON + * @memberof examples.spanner.music.SingerInfo + * @instance + * @returns {Object.} JSON object + */ + SingerInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SingerInfo + * @function getTypeUrl + * @memberof examples.spanner.music.SingerInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SingerInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = 'type.googleapis.com'; + } + return typeUrlPrefix + '/examples.spanner.music.SingerInfo'; + }; + + return SingerInfo; + })(); + + /** + * Genre enum. + * @name examples.spanner.music.Genre + * @enum {number} + * @property {number} POP=0 POP value + * @property {number} JAZZ=1 JAZZ value + * @property {number} FOLK=2 FOLK value + * @property {number} ROCK=3 ROCK value + */ + music.Genre = (function () { + var valuesById = {}, + values = Object.create(valuesById); + values[(valuesById[0] = 'POP')] = 0; + values[(valuesById[1] = 'JAZZ')] = 1; + values[(valuesById[2] = 'FOLK')] = 2; + values[(valuesById[3] = 'ROCK')] = 3; + return values; + })(); + + return music; + })(); + + return spanner; + })(); + + return examples; +})(); + +module.exports = $root; diff --git a/handwritten/spanner/test/data/singer.proto b/handwritten/spanner/test/data/singer.proto new file mode 100644 index 00000000000..adc79d18c3e --- /dev/null +++ b/handwritten/spanner/test/data/singer.proto @@ -0,0 +1,31 @@ +// Copyright 2023 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. + +syntax = "proto3"; + +package examples.spanner.music; + +message SingerInfo { + optional int64 singer_id = 1; + optional string birth_date = 2; + optional string nationality = 3; + optional Genre genre = 4; +} + +enum Genre { + POP = 0; + JAZZ = 1; + FOLK = 2; + ROCK = 3; +} diff --git a/handwritten/spanner/test/data/streaming-read-acceptance-test.json b/handwritten/spanner/test/data/streaming-read-acceptance-test.json new file mode 100644 index 00000000000..e9606046572 --- /dev/null +++ b/handwritten/spanner/test/data/streaming-read-acceptance-test.json @@ -0,0 +1,363 @@ +{ + "tests": [ + { + "result": { + "value": [ + [ + true, + "abc", + "100", + 1.1, + "YWJj", + [ + "abc", + "def", + null, + "ghi" + ], + [ + [ + "abc" + ], + [ + "def" + ], + [ + "ghi" + ] + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"BOOL\"\n }\n }, {\n \"name\": \"f2\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }, {\n \"name\": \"f3\",\n \"type\": {\n \"code\": \"INT64\"\n }\n }, {\n \"name\": \"f4\",\n \"type\": {\n \"code\": \"FLOAT64\"\n }\n }, {\n \"name\": \"f5\",\n \"type\": {\n \"code\": \"BYTES\"\n }\n }, {\n \"name\": \"f6\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRING\"\n }\n }\n }, {\n \"name\": \"f7\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f71\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }]\n }\n }\n }\n }]\n }\n },\n \"values\": [true, \"abc\", \"100\", 1.1, \"YWJj\", [\"abc\", \"def\", null, \"ghi\"], [[\"abc\"], [\"def\"], [\"ghi\"]]]\n}" + ], + "name": "Basic Test" + }, + { + "result": { + "value": [ + [ + "abcdefghi" + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }]\n }\n },\n \"values\": [\"abc\"],\n \"chunkedValue\": true\n}", + "{\n \"values\": [\"def\"],\n \"chunkedValue\": true\n}", + "{\n \"values\": [\"ghi\"]\n}" + ], + "name": "String Chunking Test" + }, + { + "result": { + "value": [ + [ + [ + "abc", + "def", + "ghi", + "jkl" + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRING\"\n }\n }\n }]\n }\n },\n \"values\": [[\"abc\", \"d\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"ef\", \"gh\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"i\", \"jkl\"]]\n}" + ], + "name": "String Array Chunking Test" + }, + { + "result": { + "value": [ + [ + [ + "abc", + "def", + null, + "ghi", + null, + "jkl" + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRING\"\n }\n }\n }]\n }\n },\n \"values\": [[\"abc\", \"def\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[null, \"ghi\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[null, \"jkl\"]]\n}" + ], + "name": "String Array Chunking Test With Nulls" + }, + { + "result": { + "value": [ + [ + [ + "abc", + "def", + "ghi", + "jkl" + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRING\"\n }\n }\n }]\n }\n },\n \"values\": [[\"abc\", \"def\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"\", \"ghi\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"\", \"jkl\"]]\n}" + ], + "name": "String Array Chunking Test With Empty Strings" + }, + { + "result": { + "value": [ + [ + [ + "abcdefghi" + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRING\"\n }\n }\n }]\n }\n },\n \"values\": [[\"abc\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"def\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"ghi\"]]\n}" + ], + "name": "String Array Chunking Test With One Large String" + }, + { + "result": { + "value": [ + [ + [ + "1", + "23", + "4", + null, + "5" + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"INT64\"\n }\n }\n }]\n }\n },\n \"values\": [[\"1\", \"2\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"3\", \"4\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"\", null, \"5\"]]\n}" + ], + "name": "INT64 Array Chunking Test" + }, + { + "result": { + "value": [ + [ + [ + 1, + 2, + "Infinity", + "-Infinity", + "NaN", + null, + 3 + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"FLOAT64\"\n }\n }\n }]\n }\n },\n \"values\": [[1.0, 2.0]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"Infinity\", \"-Infinity\", \"NaN\"]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[\"\", null, 3.0]]\n}" + ], + "name": "FLOAT64 Array Chunking Test" + }, + { + "result": { + "value": [ + [ + [ + [ + "abc", + "defghi" + ], + [ + "123", + "456" + ] + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f11\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }, {\n \"name\": \"f12\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }]\n }\n }\n }\n }]\n }\n },\n \"values\": [[[\"abc\", \"def\"]]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[[\"ghi\"], [\"123\", \"456\"]]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[[\"\"]]]\n}" + ], + "name": "Struct Array Chunking Test" + }, + { + "result": { + "value": [ + [ + [ + [ + [ + [ + "abc" + ] + ] + ] + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f11\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f12\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }]\n }\n }\n }\n }]\n }\n }\n }\n }]\n }\n },\n \"values\": [[[[[\"abc\"]]]]]\n}" + ], + "name": "Nested Struct Array Test" + }, + { + "result": { + "value": [ + [ + [ + [ + [ + [ + "abc" + ], + [ + "def" + ] + ] + ] + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f11\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f12\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }]\n }\n }\n }\n }]\n }\n }\n }\n }]\n }\n },\n \"values\": [[[[[\"ab\"]]]]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[[[[\"c\"], [\"def\"]]]]]\n}" + ], + "name": "Nested Struct Array Chunking Test" + }, + { + "result": { + "value": [ + [ + "1", + [ + [ + "ab" + ] + ] + ], + [ + "2", + [ + [ + "c" + ] + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }, {\n \"name\": \"f2\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f21\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }]\n }\n }\n }\n }]\n }\n },\n \"values\": [\"1\", [[\"a\"]]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[[\"b\"]], \"2\"],\n \"chunkedValue\": true\n}", + "{\n \"values\": [\"\", [[\"c\"]]]\n}" + ], + "name": "Struct Array And String Chunking Test" + }, + { + "result": { + "value": [ + [ + "abc", + "1" + ], + [ + "def", + "2" + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }, {\n \"name\": \"f2\",\n \"type\": {\n \"code\": \"INT64\"\n }\n }]\n }\n },\n \"values\": [\"abc\", \"1\", \"def\", \"2\"]\n}" + ], + "name": "Multiple Row Single Chunk" + }, + { + "result": { + "value": [ + [ + "abc", + "1" + ], + [ + "def", + "2" + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }, {\n \"name\": \"f2\",\n \"type\": {\n \"code\": \"INT64\"\n }\n }]\n }\n },\n \"values\": [\"ab\"],\n \"chunkedValue\": true\n}", + "{\n \"values\": [\"c\", \"1\", \"de\"],\n \"chunkedValue\": true\n}", + "{\n \"values\": [\"f\", \"2\"]\n}" + ], + "name": "Multiple Row Multiple Chunks" + }, + { + "result": { + "value": [ + [ + "ab" + ], + [ + "c" + ], + [ + "d" + ], + [ + "ef" + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }]\n }\n },\n \"values\": [\"a\"],\n \"chunkedValue\": true\n}", + "{\n \"values\": [\"b\", \"c\"]\n}", + "{\n \"values\": [\"d\", \"e\"],\n \"chunkedValue\": true\n}", + "{\n \"values\": [\"f\"]\n}" + ], + "name": "Multiple Row Chunks/Non Chunks Interleaved" + }, + { + "result": { + "value": [ + [ + [ + [ + [ + [ + "abc" + ], + null, + [ + "def" + ] + ] + ] + ] + ] + ] + }, + "chunks": [ + "{\n \"metadata\": {\n \"rowType\": {\n \"fields\": [{\n \"name\": \"f1\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f11\",\n \"type\": {\n \"code\": \"ARRAY\",\n \"arrayElementType\": {\n \"code\": \"STRUCT\",\n \"structType\": {\n \"fields\": [{\n \"name\": \"f12\",\n \"type\": {\n \"code\": \"STRING\"\n }\n }]\n }\n }\n }\n }]\n }\n }\n }\n }]\n }\n },\n \"values\": [[[[[\"abc\"], null]]]],\n \"chunkedValue\": true\n}", + "{\n \"values\": [[[[[\"def\"]]]]]\n}" + ], + "name": "Nested Struct Array Chunking Test With null" + } + ] +} diff --git a/handwritten/spanner/test/database.ts b/handwritten/spanner/test/database.ts new file mode 100644 index 00000000000..71923d4e0d7 --- /dev/null +++ b/handwritten/spanner/test/database.ts @@ -0,0 +1,3619 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable prefer-rest-params */ + +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import {EventEmitter} from 'events'; +import * as extend from 'extend'; +import {ApiError, util} from '@google-cloud/common'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import {Transform, Duplex} from 'stream'; +import * as through from 'through2'; +import * as pfy from '@google-cloud/promisify'; +import {grpc} from 'google-gax'; +import * as db from '../src/database'; +import {Spanner, Instance, MutationGroup} from '../src'; +import {MockError} from './mockserver/mockspanner'; +import {IOperation} from '../src/instance'; +import { + CLOUD_RESOURCE_HEADER, + LEADER_AWARE_ROUTING_HEADER, + AFE_SERVER_TIMING_HEADER, +} from '../src/common'; +import {google} from '../protos/protos'; +import {protos} from '../src'; +import * as inst from '../src/instance'; +import RequestOptions = google.spanner.v1.RequestOptions; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import EncryptionType = google.spanner.admin.database.v1.RestoreDatabaseEncryptionConfig.EncryptionType; +import { + BatchWriteOptions, + CommitCallback, + CommitOptions, + MutationSet, +} from '../src/transaction'; +import {SessionFactory} from '../src/session-factory'; +import {RunTransactionOptions} from '../src/transaction-runner'; +import { + X_GOOG_SPANNER_REQUEST_ID_HEADER, + craftRequestId, +} from '../src/request_id_header'; + +let promisified = false; +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'Database') { + return; + } + promisified = true; + assert.deepStrictEqual(options.exclude, [ + 'batchTransaction', + 'batchWriteAtLeastOnce', + 'getRestoreInfo', + 'getState', + 'getDatabaseDialect', + 'getOperations', + 'runTransaction', + 'runTransactionAsync', + 'table', + 'session', + ]); + }, +}); + +class FakeBatchTransaction { + calledWith_: IArguments; + id?: string; + readTimestamp?: {seconds: number; nanos: number}; + constructor() { + this.calledWith_ = arguments; + } +} + +export class FakeGrpcServiceObject extends EventEmitter { + calledWith_: IArguments; + constructor() { + super(); + this.calledWith_ = arguments; + } +} + +function fakePartialResultStream(this: Function & {calledWith_: IArguments}) { + this.calledWith_ = arguments; + return this; +} + +export class FakeSession { + calledWith_: IArguments; + formattedName_: any; + constructor() { + this.calledWith_ = arguments; + } + partitionedDml(): FakeTransaction { + return new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.PartitionedDml, + ); + } + snapshot(): FakeTransaction { + return new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + } +} + +export class FakeSessionPool extends EventEmitter { + calledWith_: IArguments; + constructor() { + super(); + this.calledWith_ = arguments; + } + open() {} + getSession() {} + release() {} +} + +export class FakeMultiplexedSession extends EventEmitter { + calledWith_: IArguments; + formattedName_: any; + constructor() { + super(); + this.calledWith_ = arguments; + } + createSession() {} + getSession() {} +} + +export class FakeSessionFactory extends EventEmitter { + calledWith_: IArguments; + constructor() { + super(); + this.calledWith_ = arguments; + } + getSession() {} + getSessionForPartitionedOps() {} + getSessionForReadWrite() {} + getPool(): FakeSessionPool { + return new FakeSessionPool(); + } + release() {} + isMultiplexedEnabled(): boolean { + return process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS! === 'false'; + } + isMultiplexedEnabledForRW(): boolean { + return ( + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS! === 'false' && + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW! === 'false' + ); + } +} + +class FakeTable { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +class FakeTransaction extends EventEmitter { + calledWith_: IArguments; + _options!: google.spanner.v1.ITransactionOptions; + private _queuedMutations: google.spanner.v1.Mutation[]; + constructor(options) { + super(); + this._options = options; + this.calledWith_ = arguments; + this._queuedMutations = []; + } + begin() {} + end() {} + runStream(): Transform { + return through.obj(); + } + runUpdate() {} + setQueuedMutations(mutation) { + this._queuedMutations = mutation; + } + setReadWriteTransactionOptions(options: RunTransactionOptions) {} + commit( + options?: CommitOptions, + callback?: CommitCallback, + ): void | Promise { + if (callback) { + callback(null, {commitTimestamp: {seconds: 1, nanos: 0}}); + } + return Promise.resolve({commitTimestamp: {seconds: 1, nanos: 0}}); + } +} + +let fakeTransactionRunner: FakeTransactionRunner; + +class FakeTransactionRunner { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + // eslint-disable-next-line @typescript-eslint/no-this-alias + fakeTransactionRunner = this; + } + async run(): Promise {} +} + +let fakeAsyncTransactionRunner: FakeAsyncTransactionRunner<{}>; + +class FakeAsyncTransactionRunner { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + // eslint-disable-next-line @typescript-eslint/no-this-alias + fakeAsyncTransactionRunner = this; + } + async run(): Promise { + return {} as T; + } +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const fakeCodec: any = { + encode: util.noop, + Int() {}, + Float() {}, + SpannerDate() {}, +}; + +class FakeAbortError { + error; + constructor(err) { + this.error = err; + } +} + +const fakeRetry = fn => { + return fn(); +}; + +fakeRetry.AbortError = FakeAbortError; + +describe('Database', () => { + const sandbox = sinon.createSandbox(); + + // tslint:disable-next-line variable-name + let Database: typeof db.Database; + // tslint:disable-next-line variable-name + let DatabaseCached: typeof db.Database; + + const SPANNER = { + routeToLeaderEnabled: true, + options: {}, + } as {} as Spanner; + + const INSTANCE = { + request: util.noop, + requestStream: util.noop, + formattedName_: 'instance-name', + databases_: new Map(), + parent: SPANNER, + } as {} as Instance; + + const NAME = 'table-name'; + const DATABASE_FORMATTED_NAME = + INSTANCE.formattedName_ + '/databases/' + NAME; + + const POOL_OPTIONS = {}; + + let database; + + before(() => { + Database = proxyquire('../src/database.js', { + './common-grpc/service-object': { + GrpcServiceObject: FakeGrpcServiceObject, + }, + '@google-cloud/promisify': fakePfy, + 'p-retry': fakeRetry, + './batch-transaction': {BatchTransaction: FakeBatchTransaction}, + './codec': {codec: fakeCodec}, + './partial-result-stream': {partialResultStream: fakePartialResultStream}, + './session-pool': {SessionPool: FakeSessionPool}, + './multiplexed-session': {MultiplexedSession: FakeMultiplexedSession}, + './session-factory': {SessionFactory: FakeSessionFactory}, + './session': {Session: FakeSession}, + './table': {Table: FakeTable}, + './transaction-runner': { + TransactionRunner: FakeTransactionRunner, + AsyncTransactionRunner: FakeAsyncTransactionRunner, + }, + }).Database; + // The following commented out line is the one that will trigger the error. + // DatabaseCached = extend({}, Database); + DatabaseCached = Object.assign({}, Database); + }); + + beforeEach(() => { + fakeCodec.encode = util.noop; + extend(Database, DatabaseCached); + database = new Database(INSTANCE, NAME, POOL_OPTIONS); + database.parent = INSTANCE; + database.databaseRole = 'parent_role'; + }); + + afterEach(() => sandbox.restore()); + + describe('instantiation', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should localize the request function', () => { + assert.strictEqual(database.request, INSTANCE.request); + }); + + it('should localize the requestStream function', () => { + assert.strictEqual(database.requestStream, INSTANCE.requestStream); + }); + + it('should format the name', () => { + const formatName_ = Database.formatName_; + const formattedName = 'formatted-name'; + + Database.formatName_ = (instanceName, name) => { + Database.formatName_ = formatName_; + + assert.strictEqual(instanceName, INSTANCE.formattedName_); + assert.strictEqual(name, NAME); + + return formattedName; + }; + + const database = new Database(INSTANCE, NAME); + assert(database.formattedName_, formattedName); + }); + + it('should accept a custom Pool class', () => { + function FakePool() {} + const database = new Database( + INSTANCE, + NAME, + FakePool as {} as db.SessionPoolConstructor, + ); + assert(database.pool_ instanceof FakeSessionPool); + }); + + describe('when multiplexed session is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + + it('should re-emit SessionPool errors', done => { + const error = new Error('err'); + + const sessionFactory = new SessionFactory(database, NAME); + + database.on('error', err => { + assert.strictEqual(err, error); + done(); + }); + + sessionFactory.pool_.emit('error', error); + }); + }); + + it('should inherit from ServiceObject', done => { + const options = {}; + + const instanceInstance = extend({}, INSTANCE, { + createDatabase(name, options_, callback) { + assert.strictEqual(name, database.formattedName_); + assert.strictEqual(options_, options); + callback(); // done() + }, + }); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const database: any = new Database(instanceInstance, NAME); + assert(database instanceof FakeGrpcServiceObject); + + const calledWith = database.calledWith_[0]; + + assert.strictEqual(calledWith.parent, instanceInstance); + assert.strictEqual(calledWith.id, NAME); + assert.deepStrictEqual(calledWith.methods, {create: true}); + + calledWith.createMethod(null, options, done); + }); + + it('should set the commonHeaders_', () => { + assert.deepStrictEqual(database.commonHeaders_, { + [CLOUD_RESOURCE_HEADER]: database.formattedName_, + [AFE_SERVER_TIMING_HEADER]: 'true', + }); + }); + + it('should accept databaseRole in constructor', () => { + const databaseRole = 'child_role'; + const database = new Database( + INSTANCE, + NAME, + POOL_OPTIONS, + undefined, + databaseRole, + ); + assert.strictEqual(database.databaseRole, databaseRole); + }); + + it('should use sessionLabels from Spanner options', () => { + const sessionLabels = {env: 'test'}; + const spanner = new Spanner({ + sessionLabels, + }); + const instanceCtx = { + parent: spanner, + _observabilityOptions: {}, + request: util.noop, + requestStream: util.noop, + formattedName_: 'instance-name', + databases_: new Map(), + } as {} as Instance; + + const database = new Database(instanceCtx, NAME); + assert.deepStrictEqual(database.labels, sessionLabels); + }); + }); + + describe('formatName_', () => { + it('should return the name if already formatted', () => { + assert.strictEqual( + Database.formatName_(INSTANCE.formattedName_, DATABASE_FORMATTED_NAME), + DATABASE_FORMATTED_NAME, + ); + }); + + it('should format the name', () => { + const formattedName_ = Database.formatName_( + INSTANCE.formattedName_, + NAME, + ); + assert.strictEqual(formattedName_, DATABASE_FORMATTED_NAME); + }); + }); + + describe('batchCreateSessions', () => { + it('should make the correct request', () => { + const stub = sandbox.stub(database, 'request'); + const count = 10; + + database.batchCreateSessions({count}, assert.ifError); + + const {client, method, reqOpts, gaxOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'batchCreateSessions'); + assert.strictEqual(reqOpts.database, DATABASE_FORMATTED_NAME); + assert.strictEqual(reqOpts.sessionCount, count); + assert.strictEqual(gaxOpts, undefined); + assert.deepStrictEqual( + headers, + Object.assign( + { + [LEADER_AWARE_ROUTING_HEADER]: true, + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + }, + database.commonHeaders_, + ), + ); + }); + + it('should accept just a count number', () => { + const stub = sandbox.stub(database, 'request'); + const count = 10; + + database.batchCreateSessions(count, assert.ifError); + + const {reqOpts} = stub.lastCall.args[0]; + assert.strictEqual(reqOpts.sessionCount, count); + }); + + it('should accept session labels', () => { + const stub = sandbox.stub(database, 'request'); + const labels = {foo: 'bar'}; + + database.batchCreateSessions({count: 10, labels}, assert.ifError); + + const {reqOpts} = stub.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.sessionTemplate.labels, labels); + }); + + it('should accept session databaseRole', () => { + const stub = sandbox.stub(database, 'request'); + + database.batchCreateSessions( + {count: 10, databaseRole: 'child_role'}, + assert.ifError, + ); + + const {reqOpts} = stub.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.sessionTemplate.creatorRole, 'child_role'); + }); + + it('should use default databaseRole', () => { + const stub = sandbox.stub(database, 'request'); + + database.batchCreateSessions({count: 10}, assert.ifError); + + const {reqOpts} = stub.lastCall.args[0]; + + assert.deepStrictEqual( + reqOpts.sessionTemplate.creatorRole, + 'parent_role', + ); + }); + + it('should accept gaxOptions', () => { + const stub = sandbox.stub(database, 'request'); + const gaxOptions = {timeout: 1000}; + + database.batchCreateSessions({count: 10, gaxOptions}, assert.ifError); + + const {gaxOpts} = stub.lastCall.args[0]; + + assert.strictEqual(gaxOpts, gaxOptions); + }); + + it('should return any request errors', done => { + const error = new Error('err'); + const response = {}; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sandbox.stub(database, 'request').callsFake((_, cb: any) => { + cb(error, response); + }); + + database.batchCreateSessions({count: 10}, (err, sessions, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(sessions, null); + assert.strictEqual(resp, response); + done(); + }); + }); + + it('should create session objects from the response', done => { + const stub = sandbox.stub(database, 'session'); + const fakeSessions = [{}, {}, {}]; + const response = { + session: [{name: 'a'}, {name: 'b'}, {name: 'c'}], + }; + + response.session.forEach((session, i) => { + stub.withArgs(session.name).returns(fakeSessions[i]); + }); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sandbox.stub(database, 'request').callsFake((_, cb: any) => { + cb(null, response); + }); + + database.batchCreateSessions({count: 10}, (err, sessions, resp) => { + assert.strictEqual(err, null); + assert.deepStrictEqual(sessions, fakeSessions); + assert.strictEqual(resp, response); + done(); + }); + }); + }); + + describe('setMetadata', () => { + const METADATA = { + needsToBeSnakeCased: true, + } as inst.IDatabase; + const ORIGINAL_METADATA = extend({}, METADATA); + + it('should make and return the request', () => { + const requestReturnValue = {}; + + function callback() {} + + database.request = (config, callback_) => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'updateDatabase'); + + const expectedReqOpts = extend({}, METADATA, { + name: database.formattedName_, + }); + + assert.deepStrictEqual(config.reqOpts.database, expectedReqOpts); + assert.deepStrictEqual(config.reqOpts.updateMask, { + paths: ['needs_to_be_snake_cased'], + }); + + assert.deepStrictEqual(METADATA, ORIGINAL_METADATA); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, database.commonHeaders_); + + assert.strictEqual(callback_, callback); + + return requestReturnValue; + }; + + const returnValue = database.setMetadata(METADATA, callback); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + database.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + database.setMetadata(METADATA, gaxOptions, assert.ifError); + }); + + it('should not require a callback', () => { + assert.doesNotThrow(() => { + database.setMetadata(METADATA); + }); + }); + }); + + describe('batchTransaction', () => { + const SESSION = {id: 'hijklmnop'}; + const ID = 'abcdefg'; + const READ_TIMESTAMP = {seconds: 0, nanos: 0}; + + it('should create a transaction object', () => { + const identifier = { + session: SESSION, + transaction: ID, + timestamp: READ_TIMESTAMP, + }; + + const transaction = database.batchTransaction(identifier); + + assert(transaction instanceof FakeBatchTransaction); + assert.deepStrictEqual(transaction.calledWith_[0], SESSION); + assert.strictEqual(transaction.id, ID); + assert.strictEqual(transaction.readTimestamp, READ_TIMESTAMP); + }); + + it('should optionally accept a session id', () => { + const identifier = { + session: SESSION.id, + transaction: ID, + timestamp: READ_TIMESTAMP, + }; + + database.session = id => { + assert.strictEqual(id, SESSION.id); + return SESSION; + }; + + const transaction = database.batchTransaction(identifier); + assert.deepStrictEqual(transaction.calledWith_[0], SESSION); + }); + }); + + describe('batchWrite', () => { + const mutationGroup1 = new MutationGroup(); + mutationGroup1.insert('MyTable', { + Key: 'k1', + Thing: 'abc', + }); + const mutationGroup2 = new MutationGroup(); + mutationGroup2.insert('MyTable', { + Key: 'k2', + Thing: 'xyz', + }); + + const mutationGroups = [mutationGroup1, mutationGroup2]; + + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakeDataStream: Transform; + let getSessionStub: sinon.SinonStub; + let requestStreamStub: sinon.SinonStub; + + const options = { + requestOptions: { + transactionTag: 'batch-write-tag', + }, + excludeTxnFromChangeStream: true, + gaxOptions: {autoPaginate: false}, + } as BatchWriteOptions; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakeDataStream = through.obj(); + + getSessionStub = ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForReadWrite', + ) as sinon.SinonStub + ).callsFake(callback => callback(null, fakeSession)); + + requestStreamStub = sandbox + .stub(database, 'requestStream') + .returns(fakeDataStream); + }); + + it('should get a session via `getSessionForReadWrite`', done => { + getSessionStub.callsFake(() => {}); + database.batchWriteAtLeastOnce(mutationGroups, options); + assert.strictEqual(getSessionStub.callCount, 1); + done(); + }); + + it('should destroy the stream if `getSessionForReadWrite` errors', done => { + const fakeError = new Error('err'); + + getSessionStub.callsFake(callback => callback(fakeError)); + database + .batchWriteAtLeastOnce(mutationGroups, options) + .on('error', err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should call `requestStream` with correct arguments', () => { + const expectedGaxOpts = extend(true, {}, options?.gaxOptions); + const expectedReqOpts = Object.assign( + {} as google.spanner.v1.BatchWriteRequest, + { + session: fakeSession!.formattedName_!, + mutationGroups: mutationGroups.map(mg => mg.proto()), + requestOptions: options?.requestOptions, + excludeTxnFromChangeStream: options?.excludeTxnFromChangeStreams, + }, + ); + + database.batchWriteAtLeastOnce(mutationGroups, options); + + assert.strictEqual(requestStreamStub.callCount, 1); + const args = requestStreamStub.firstCall.args[0]; + assert.strictEqual(args.client, 'SpannerClient'); + assert.strictEqual(args.method, 'batchWrite'); + assert.deepStrictEqual(args.reqOpts, expectedReqOpts); + assert.deepStrictEqual(args.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(args.headers, database.commonHeaders_); + }); + + it('should return error when passing an empty list of mutationGroups', done => { + const fakeError = new Error('err'); + database.batchWriteAtLeastOnce([], options).on('error', error => { + assert.strictEqual(error, fakeError); + done(); + }); + fakeDataStream.emit('error', fakeError); + }); + + it('should return data when passing a valid list of mutationGroups', done => { + database + .batchWriteAtLeastOnce(mutationGroups, options) + .on('data', data => { + assert.strictEqual(data, 'test'); + done(); + }); + fakeDataStream.emit('data', 'test'); + }); + + it('should emit correct event based on valid/invalid list of mutationGroups', done => { + const fakeError = new Error('err'); + const FakeMutationGroup1 = new MutationGroup(); + FakeMutationGroup1.insert('Singers', { + SingerId: 1, + FirstName: 'Scarlet', + LastName: 'Terry', + }); + FakeMutationGroup1.insert('Singers', { + SingerId: 1000000000000000000000000000000000, + FirstName: 'Scarlet', + LastName: 'Terry', + }); + + const FakeMutationGroup2 = new MutationGroup(); + FakeMutationGroup2.insert('Singers', { + SingerId: 2, + FirstName: 'Marc', + }); + FakeMutationGroup2.insert('Singers', { + SingerId: 3, + FirstName: 'Catalina', + LastName: 'Smith', + }); + FakeMutationGroup2.insert('Albums', { + AlbumId: 1, + SingerId: 2, + AlbumTitle: 'Total Junk', + }); + FakeMutationGroup2.insert('Albums', { + AlbumId: 2, + SingerId: 3, + AlbumTitle: 'Go, Go, Go', + }); + database + .batchWriteAtLeastOnce( + [FakeMutationGroup1, FakeMutationGroup2], + options, + ) + .on('data', data => { + assert.strictEqual(data, 'testData'); + }) + .on('error', err => { + assert.strictEqual(err, fakeError); + }); + fakeDataStream.emit('data', 'testData'); + fakeDataStream.emit('error', fakeError); + done(); + }); + + it('should retry on "Session not found" error', done => { + const sessionNotFoundError = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as grpc.ServiceError; + let retryCount = 0; + + database + .batchWriteAtLeastOnce(mutationGroups, options) + .on('data', () => {}) + .on('error', err => { + assert.fail(err); + }) + .on('end', () => { + assert.strictEqual(retryCount, 1); + done(); + }); + + fakeDataStream.emit('error', sessionNotFoundError); + retryCount++; + }); + + it('should release session on stream end', () => { + const releaseStub = sandbox.stub( + fakeSessionFactory, + 'release', + ) as sinon.SinonStub; + + database.batchWriteAtLeastOnce(mutationGroups, options); + fakeDataStream.emit('end'); + + assert.strictEqual(releaseStub.callCount, 1); + assert.strictEqual(releaseStub.firstCall.args[0], fakeSession); + }); + }); + + describe('writeAtLeastOnce', () => { + const mutations = new MutationSet(); + mutations.insert('MyTable', { + Key: 'k3', + Thing: 'xyz', + }); + + const SESSION = new FakeSession(); + const RESPONSE = {commitTimestamp: {seconds: 1, nanos: 0}}; + const TRANSACTION = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadWrite, + ); + + let sessionFactory: FakeSessionFactory; + + beforeEach(() => { + sandbox.restore(); + sessionFactory = database.sessionFactory_; + (sandbox.stub(sessionFactory, 'getSession') as sinon.SinonStub).callsFake( + callback => { + callback(null, SESSION, TRANSACTION); + }, + ); + }); + + it('should return any errors getting a session', done => { + const fakeErr = new Error('err'); + + (sessionFactory.getSession as sinon.SinonStub).callsFake(callback => + callback(fakeErr, null, null), + ); + + database.writeAtLeastOnce(mutations, err => { + assert.deepStrictEqual(err, fakeErr); + done(); + }); + }); + + it('should return successful CommitResponse when passing an empty mutation', done => { + const fakeMutations = new MutationSet(); + try { + database.writeAtLeastOnce(fakeMutations, (err, response) => { + assert.ifError(err); + assert.deepStrictEqual( + response.commitTimestamp, + RESPONSE.commitTimestamp, + ); + }); + done(); + } catch (error) { + assert(error instanceof Error); + } + }); + + it('should return an error when passing null mutation', done => { + try { + database.writeAtLeastOnce(null, () => {}); + } catch (err) { + const errorMessage = (err as grpc.ServiceError).message; + assert.ok( + errorMessage.includes( + "Cannot read properties of null (reading 'proto')", + ) || errorMessage.includes("Cannot read property 'proto' of null"), + ); + + done(); + } + }); + + it('should return CommitResponse on successful write using Callback', done => { + database.writeAtLeastOnce(mutations, (err, res) => { + assert.deepStrictEqual(err, null); + assert.deepStrictEqual(res, RESPONSE); + done(); + }); + }); + + it('should return CommitResponse on successful write using await', async () => { + sinon.stub(database, 'writeAtLeastOnce').resolves([RESPONSE]); + const [response] = await database.writeAtLeastOnce(mutations, {}); + assert.deepStrictEqual( + response.commitTimestamp, + RESPONSE.commitTimestamp, + ); + }); + }); + + describe('close', () => { + const FAKE_ID = 'a/c/b/d'; + + beforeEach(() => { + database.id = FAKE_ID; + }); + + describe('success', () => { + beforeEach(() => { + database.parent = INSTANCE; + database.pool_ = { + close(callback) { + callback(null); + }, + }; + }); + + it('should close the database', done => { + database.close(done); + }); + + it('should remove the database cache', done => { + const cache = INSTANCE.databases_; + const cacheId = FAKE_ID.split('/').pop()!; + + cache.set(cacheId, database); + assert(cache.has(cacheId)); + + database.close(err => { + assert.ifError(err); + assert.strictEqual(cache.has(cacheId), false); + done(); + }); + }); + }); + + describe('error', () => { + it('should return the closing error', done => { + const error = new Error('err.'); + + database.pool_ = { + close(callback) { + callback(error); + }, + }; + + database.close(err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + }); + + describe('createBatchTransaction', () => { + const SESSION = {}; + const RESPONSE = {a: 'b'}; + + beforeEach(() => { + database.sessionFactory_ = { + getSession(callback) { + callback(null, SESSION); + }, + }; + }); + + it('should return any get session errors', done => { + const error = new Error('err'); + + database.sessionFactory_ = { + getSession(callback) { + callback(error); + }, + }; + + database.createBatchTransaction((err, transaction, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(transaction, null); + assert.strictEqual(resp, undefined); + done(); + }); + }); + + it('should create a transaction', done => { + const opts = {a: 'b'}; + + const fakeTransaction = { + begin(callback) { + callback(null, RESPONSE); + }, + + once() {}, + }; + + database.batchTransaction = (identifier, options) => { + assert.deepStrictEqual(identifier, {session: SESSION}); + assert.strictEqual(options, opts); + return fakeTransaction; + }; + + database.createBatchTransaction(opts, (err, transaction, resp) => { + assert.strictEqual(err, null); + assert.strictEqual(transaction, fakeTransaction); + assert.strictEqual(resp, RESPONSE); + done(); + }); + }); + + it('should return any transaction errors', done => { + const error = new Error('err'); + + const fakeTransaction = { + begin(callback) { + callback(error, RESPONSE); + }, + + once() {}, + }; + + database.batchTransaction = () => { + return fakeTransaction; + }; + + database.createBatchTransaction((err, transaction, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(transaction, null); + assert.strictEqual(resp, RESPONSE); + done(); + }); + }); + }); + + describe('createTable', () => { + const TABLE_NAME = 'table-name'; + const SCHEMA = 'CREATE TABLE `' + TABLE_NAME + '`'; + + it('should call updateSchema', done => { + database.updateSchema = schema => { + assert.strictEqual(schema, SCHEMA); + done(); + }; + + database.createTable(SCHEMA, assert.ifError); + }); + + it('should accept and pass gaxOptions to updateSchema', done => { + const gaxOptions = {}; + database.updateSchema = (schema, options) => { + assert.strictEqual(options, gaxOptions); + done(); + }; + database.createTable(SCHEMA, gaxOptions, assert.ifError); + }); + + describe('error', () => { + const ERROR = new Error('Error.'); + const API_RESPONSE = {}; + + beforeEach(() => { + database.updateSchema = (name, options, callback) => { + callback(ERROR, null, API_RESPONSE); + }; + }); + + it('should execute callback with error & API response', done => { + database.createTable(SCHEMA, (err, table, op, apiResponse) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(table, null); + assert.strictEqual(op, null); + assert.strictEqual(apiResponse, API_RESPONSE); + done(); + }); + }); + }); + + describe('success', () => { + const OPERATION = {}; + const API_RESPONSE = {}; + + beforeEach(() => { + database.updateSchema = (name, options, callback) => { + callback(null, OPERATION, API_RESPONSE); + }; + }); + + describe('table name parsing', () => { + it('should recognize an escaped name', done => { + database.table = name => { + assert.strictEqual(name, TABLE_NAME); + done(); + }; + + database.createTable(SCHEMA, assert.ifError); + }); + + it('should recognize a non-escaped name', done => { + database.table = name => { + assert.strictEqual(name, TABLE_NAME); + done(); + }; + + database.createTable('CREATE TABLE ' + TABLE_NAME, assert.ifError); + }); + }); + + it('should exec callback with Table, op & API response', done => { + const tableInstance = {}; + + database.table = name => { + assert.strictEqual(name, TABLE_NAME); + return tableInstance; + }; + + database.createTable(SCHEMA, (err, table, op, apiResponse) => { + assert.ifError(err); + assert.strictEqual(table, tableInstance); + assert.strictEqual(op, OPERATION); + assert.strictEqual(apiResponse, API_RESPONSE); + done(); + }); + }); + }); + }); + + describe('delete', () => { + beforeEach(() => { + database.close = callback => { + callback(); + }; + }); + + it('should close the database', done => { + database.close = () => { + done(); + }; + + database.delete(); + }); + + it('should make the correct request', () => { + database.request = (config, callback) => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'dropDatabase'); + assert.deepStrictEqual(config.reqOpts, { + database: database.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, database.commonHeaders_); + assert.strictEqual(callback, assert.ifError); + }; + + database.delete(assert.ifError); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + + database.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + + database.delete(gaxOptions, assert.ifError); + }); + }); + + describe('exists', () => { + it('should return any non-404 like errors', done => { + const error = {code: 3}; + + database.getMetadata = (options, callback) => { + callback(error); + }; + + database.exists((err, exists) => { + assert.strictEqual(err, error); + assert.strictEqual(exists, undefined); + done(); + }); + }); + + it('should return true if error is absent', done => { + database.getMetadata = (options, callback) => { + callback(null); + }; + + database.exists((err, exists) => { + assert.ifError(err); + assert.strictEqual(exists, true); + done(); + }); + }); + + it('should return false if not found error if present', done => { + const error = {code: 5}; + + database.getMetadata = (options, callback) => { + callback(error); + }; + + database.exists((err, exists) => { + assert.ifError(err); + assert.strictEqual(exists, false); + done(); + }); + }); + + it('should accept and pass gaxOptions to getMetadata', done => { + const gaxOptions = {}; + + database.getMetadata = options => { + assert.strictEqual(options, gaxOptions); + done(); + }; + database.exists(gaxOptions, assert.ifError); + }); + }); + + describe('get', () => { + it('should call getMetadata', done => { + const options = {}; + + database.getMetadata = () => { + done(); + }; + + database.get(options, assert.ifError); + }); + + it('should accept and pass gaxOptions to getMetadata', done => { + const gaxOptions = {}; + database.getMetadata = options => { + assert.strictEqual(options, gaxOptions); + done(); + }; + + database.get({gaxOptions}); + }); + + it('should not require an options object', done => { + database.getMetadata = () => { + done(); + }; + + database.get(assert.ifError); + }); + + describe('autoCreate', () => { + const error = new Error('Error.'); + (error as ApiError).code = 5; + + const OPTIONS = { + autoCreate: true, + }; + + const OPERATION = { + listeners: {}, + on(eventName, callback) { + OPERATION.listeners[eventName] = callback; + return OPERATION; + }, + }; + + beforeEach(() => { + OPERATION.listeners = {}; + + database.getMetadata = (options, callback) => { + callback(error); + }; + + database.create = (options, callback) => { + callback(null, null, OPERATION); + }; + }); + + it('should call create', done => { + database.create = options => { + assert.strictEqual(options, OPTIONS); + done(); + }; + + database.get(OPTIONS, assert.ifError); + }); + + it('should pass gaxOptions to create', done => { + const gaxOptions = {}; + const options = Object.assign({}, OPTIONS, {gaxOptions}); + database.create = opts => { + assert.strictEqual(opts.gaxOptions, options.gaxOptions); + done(); + }; + + database.get(options, assert.ifError); + }); + + it('should return error if create failed', done => { + const error = new Error('Error.'); + + database.create = (options, callback) => { + callback(error); + }; + + database.get(OPTIONS, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return operation error', done => { + const error = new Error('Error.'); + + setImmediate(() => { + OPERATION.listeners['error'](error); + }); + + database.get(OPTIONS, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should execute callback if opereation succeeded', done => { + const metadata = {}; + + setImmediate(() => { + OPERATION.listeners['complete'](metadata); + }); + + database.get(OPTIONS, (err, database_, apiResponse) => { + assert.ifError(err); + assert.strictEqual(database_, database); + assert.strictEqual(database.metadata, metadata); + assert.strictEqual(metadata, apiResponse); + done(); + }); + }); + }); + + it('should not auto create without error code 5', done => { + const error = new Error('Error.'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (error as any).code = 'NOT-5'; + + const options = { + autoCreate: true, + }; + + database.getMetadata = (options, callback) => { + callback(error); + }; + + database.create = () => { + throw new Error('Should not create.'); + }; + + database.get(options, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should not auto create unless requested', done => { + const error = new ApiError('Error.'); + error.code = 5; + + database.getMetadata = (options, callback) => { + callback(error); + }; + + database.create = () => { + throw new Error('Should not create.'); + }; + + database.get(err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return an error from getMetadata', done => { + const error = new Error('Error.'); + + database.getMetadata = (options, callback) => { + callback(error); + }; + + database.get(err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return self and API response', done => { + const apiResponse = {}; + + database.getMetadata = (options, callback) => { + callback(null, apiResponse); + }; + + database.get((err, database_, apiResponse_) => { + assert.ifError(err); + assert.strictEqual(database_, database); + assert.strictEqual(apiResponse_, apiResponse); + done(); + }); + }); + }); + + describe('getMetadata', () => { + it('should call and return the request', () => { + const requestReturnValue = {}; + + database.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'getDatabase'); + assert.deepStrictEqual(config.reqOpts, { + name: database.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, database.commonHeaders_); + return requestReturnValue; + }; + + const returnValue = database.getMetadata(assert.ifError); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + database.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + database.getMetadata(gaxOptions, assert.ifError); + }); + }); + + describe('getSchema', () => { + it('should make the correct request', done => { + database.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'getDatabaseDdl'); + assert.deepStrictEqual(config.reqOpts, { + database: database.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, database.commonHeaders_); + done(); + }; + + database.getSchema(assert.ifError); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + database.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + + database.getSchema(gaxOptions, assert.ifError); + }); + + describe('error', () => { + const ARG_1 = {}; + const STATEMENTS_ARG = null; + const ARG_3 = {}; + const ARG_4 = {}; + const ARG_5 = {}; + + beforeEach(() => { + database.request = (config, callback) => { + callback(ARG_1, STATEMENTS_ARG, ARG_3, ARG_4, ARG_5); + }; + }); + + it('should return the arguments from the request', done => { + database.getSchema((arg1, arg2, arg3, arg4, arg5) => { + assert.strictEqual(arg1, ARG_1); + assert.strictEqual(arg2, STATEMENTS_ARG); + assert.strictEqual(arg3, ARG_3); + assert.strictEqual(arg4, ARG_4); + assert.strictEqual(arg5, ARG_5); + done(); + }); + }); + }); + + describe('success', () => { + const ARG_1 = {}; + const ARG_3 = {}; + const ARG_4 = {}; + const ARG_5 = {}; + + const STATEMENTS_ARG = { + statements: {}, + }; + + beforeEach(() => { + database.request = (config, callback) => { + callback(ARG_1, STATEMENTS_ARG, ARG_3, ARG_4, ARG_5); + }; + }); + + it('should return just the statements property', done => { + database.getSchema((arg1, statements, arg3, arg4, arg5) => { + assert.strictEqual(arg1, ARG_1); + assert.strictEqual(statements, STATEMENTS_ARG.statements); + assert.strictEqual(arg3, ARG_3); + assert.strictEqual(arg4, ARG_4); + assert.strictEqual(arg5, ARG_5); + done(); + }); + }); + + it('should update metadata', done => { + const metadata = {}; + database.request = (config: {}, callback: Function) => { + callback(null, metadata); + }; + database.getMetadata(() => { + assert.strictEqual(database.metadata, metadata); + done(); + }); + }); + + it('should call callback with error', done => { + const error = new Error('Error'); + database.request = (config: {}, callback: Function) => { + callback(error); + }; + database.getMetadata(err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + }); + + describe('makePooledRequest_', () => { + let CONFIG; + + const SESSION = { + formattedName_: 'formatted-name', + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const SESSIONFACTORY: any = {}; + + beforeEach(() => { + CONFIG = { + reqOpts: {}, + }; + + database.sessionFactory_ = SESSIONFACTORY; + + SESSIONFACTORY.getSessionForReadWrite = callback => { + callback(null, SESSION); + }; + + SESSIONFACTORY.release = util.noop; + }); + + it('should get a session', done => { + SESSIONFACTORY.getSessionForReadWrite = () => { + done(); + }; + + database.makePooledRequest_(CONFIG, assert.ifError); + }); + + it('should return error if it cannot get a session', done => { + const error = new Error('Error.'); + + SESSIONFACTORY.getSessionForReadWrite = callback => { + callback(error); + }; + + database.makePooledRequest_(CONFIG, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should call the method with the session', done => { + CONFIG.reqOpts = { + a: 'b', + }; + + database.request = config => { + assert.deepStrictEqual( + config.reqOpts, + extend({}, CONFIG.reqOpts, { + session: SESSION.formattedName_, + }), + ); + done(); + }; + + database.makePooledRequest_(CONFIG, assert.ifError); + }); + + it('should release the session after calling the method', done => { + SESSIONFACTORY.release = session => { + assert.deepStrictEqual(session, SESSION); + done(); + }; + + database.request = (config, callback) => { + callback(); + }; + + database.makePooledRequest_(CONFIG, assert.ifError); + }); + + it('should execute the callback with original arguments', done => { + const originalArgs = ['a', 'b', 'c']; + + database.request = (config, callback) => { + callback(...originalArgs); + }; + + database.makePooledRequest_(CONFIG, (...args) => { + assert.deepStrictEqual(args, originalArgs); + done(); + }); + }); + }); + + describe('makePooledStreamingRequest_', () => { + let CONFIG; + let REQUEST_STREAM; + + const SESSION = { + formattedName_: 'formatted-name', + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const SESSIONFACTORY: any = {}; + beforeEach(() => { + REQUEST_STREAM = through(); + + CONFIG = { + reqOpts: {}, + }; + + database.sessionFactory_ = SESSIONFACTORY; + + database.requestStream = () => { + return REQUEST_STREAM; + }; + + SESSIONFACTORY.getSession = callback => { + callback(null, SESSION); + }; + + SESSIONFACTORY.release = util.noop; + }); + + it('should get a session when stream opens', done => { + SESSIONFACTORY.getSession = () => { + done(); + }; + + database.makePooledStreamingRequest_(CONFIG).emit('reading'); + }); + + describe('could not get session', () => { + const ERROR = new Error('Error.'); + + beforeEach(() => { + SESSIONFACTORY.getSession = callback => { + callback(ERROR); + }; + }); + + it('should destroy the stream', done => { + database + .makePooledStreamingRequest_(CONFIG) + .on('error', err => { + assert.strictEqual(err, ERROR); + done(); + }) + .emit('reading'); + }); + }); + + describe('session retrieved successfully', () => { + beforeEach(() => { + SESSIONFACTORY.getSession = callback => { + callback(null, SESSION); + }; + }); + + it('should assign session to request options', done => { + database.requestStream = config => { + assert.strictEqual(config.reqOpts.session, SESSION.formattedName_); + setImmediate(done); + return through.obj(); + }; + + database.makePooledStreamingRequest_(CONFIG).emit('reading'); + }); + + it('should make request and pipe to the stream', done => { + const responseData = Buffer.from('response-data'); + + database.makePooledStreamingRequest_(CONFIG).on('data', data => { + assert.deepStrictEqual(data, responseData); + done(); + }); + + REQUEST_STREAM.end(responseData); + }); + + it('should release session when request stream ends', done => { + SESSIONFACTORY.release = session => { + assert.strictEqual(session, SESSION); + done(); + }; + + database.makePooledStreamingRequest_(CONFIG).emit('reading'); + + REQUEST_STREAM.end(); + }); + + it('should release session when request stream errors', done => { + SESSIONFACTORY.release = session => { + assert.strictEqual(session, SESSION); + done(); + }; + + database.makePooledStreamingRequest_(CONFIG).emit('reading'); + + setImmediate(() => { + REQUEST_STREAM.emit('error'); + }); + }); + + it('should error user stream when request stream errors', done => { + const error = new Error('Error.'); + + database + .makePooledStreamingRequest_(CONFIG) + .on('error', err => { + assert.strictEqual(err, error); + done(); + }) + .emit('reading'); + + setImmediate(() => { + REQUEST_STREAM.destroy(error); + }); + }); + }); + + describe('abort', () => { + let SESSION; + + beforeEach(() => { + REQUEST_STREAM.cancel = util.noop; + + SESSION = { + cancel: util.noop, + }; + + SESSIONFACTORY.getSession = callback => { + callback(null, SESSION); + }; + }); + + it('should release the session', done => { + SESSIONFACTORY.release = session => { + assert.strictEqual(session, SESSION); + done(); + }; + + const requestStream = database.makePooledStreamingRequest_(CONFIG); + + requestStream.emit('reading'); + + setImmediate(() => { + requestStream.abort(); + }); + }); + + it('should not release the session more than once', done => { + let numTimesReleased = 0; + + SESSIONFACTORY.release = session => { + numTimesReleased++; + assert.strictEqual(session, SESSION); + }; + + const requestStream = database.makePooledStreamingRequest_(CONFIG); + + requestStream.emit('reading'); + + setImmediate(() => { + requestStream.abort(); + assert.strictEqual(numTimesReleased, 1); + + requestStream.abort(); + assert.strictEqual(numTimesReleased, 1); + + done(); + }); + }); + + it('should cancel the request stream', done => { + REQUEST_STREAM.cancel = done; + const requestStream = database.makePooledStreamingRequest_(CONFIG); + requestStream.emit('reading'); + setImmediate(() => { + requestStream.abort(); + }); + }); + }); + }); + + describe('run', () => { + const QUERY = 'SELECT query FROM query'; + + let QUERY_STREAM; + + const ROW_1 = {}; + const ROW_2 = {}; + const ROW_3 = {}; + + beforeEach(() => { + QUERY_STREAM = through.obj(); + QUERY_STREAM.push(ROW_1); + QUERY_STREAM.push(ROW_2); + QUERY_STREAM.push(ROW_3); + + database.runStream = () => { + return QUERY_STREAM; + }; + }); + + it('should correctly call runStream', done => { + database.runStream = (query, options) => { + assert.strictEqual(query, QUERY); + assert.deepStrictEqual(options, {}); + setImmediate(done); + return QUERY_STREAM; + }; + + database.run(QUERY, assert.ifError); + }); + + it('should optionally accept options', done => { + const OPTIONS = {}; + + database.runStream = (query, options) => { + assert.strictEqual(options, OPTIONS); + setImmediate(done); + return QUERY_STREAM; + }; + + database.run(QUERY, OPTIONS, assert.ifError); + }); + + it('should return rows from the stream to the callback', done => { + QUERY_STREAM.end(); + + database.run(QUERY, (err, rows) => { + assert.ifError(err); + assert.deepStrictEqual(rows, [ROW_1, ROW_2, ROW_3]); + done(); + }); + }); + + it('should execute callback with error from stream', done => { + const error = new Error('Error.'); + + QUERY_STREAM.destroy(error); + + database.run(QUERY, err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('runStream', () => { + const QUERY = { + sql: 'SELECT * FROM table', + a: 'b', + c: 'd', + }; + + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakeSession2: FakeSession; + let fakeSnapshot: FakeTransaction; + let fakeSnapshot2: FakeTransaction; + let fakeStream: Transform; + let fakeStream2: Transform; + + let getSessionStub: sinon.SinonStub; + let snapshotStub: sinon.SinonStub; + let runStreamStub: sinon.SinonStub; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakeSession2 = new FakeSession(); + fakeSnapshot = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + fakeSnapshot2 = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + fakeStream = through.obj(); + fakeStream2 = through.obj(); + + getSessionStub = ( + sandbox.stub(fakeSessionFactory, 'getSession') as sinon.SinonStub + ) + .onFirstCall() + .callsFake(callback => callback(null, fakeSession)) + .onSecondCall() + .callsFake(callback => callback(null, fakeSession2)); + + snapshotStub = sandbox + .stub(fakeSession, 'snapshot') + .returns(fakeSnapshot); + + sandbox.stub(fakeSession2, 'snapshot').returns(fakeSnapshot2); + + runStreamStub = sandbox + .stub(fakeSnapshot, 'runStream') + .returns(fakeStream); + + sandbox.stub(fakeSnapshot2, 'runStream').returns(fakeStream2); + + sandbox.stub(fakeSessionFactory, 'isMultiplexedEnabled').returns(true); + }); + + it('should get a read session via `getSession`', () => { + getSessionStub.callsFake(() => {}); + database.runStream(QUERY); + + assert.strictEqual(getSessionStub.callCount, 1); + }); + + it('should destroy the stream if `getSession` errors', done => { + const fakeError = new Error('err'); + + getSessionStub.onFirstCall().callsFake(callback => callback(fakeError)); + + database.runStream(QUERY).on('error', err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should pass through timestamp bounds', () => { + const fakeOptions = {strong: false}; + database.runStream(QUERY, fakeOptions); + + const options = snapshotStub.lastCall.args[0]; + assert.strictEqual(options, fakeOptions); + }); + + it('should call through to `snapshot.runStream`', () => { + const pipeStub = sandbox.stub(fakeStream, 'pipe'); + const proxyStream = database.runStream(QUERY); + + const query = runStreamStub.lastCall.args[0]; + assert.strictEqual(query, QUERY); + + const stream = pipeStub.lastCall.args[0]; + assert.strictEqual(stream, proxyStream); + }); + + it('should end the snapshot on stream end', done => { + const endStub = sandbox.stub(fakeSnapshot, 'end'); + + database + .runStream(QUERY) + .on('data', done) + .on('end', () => { + assert.strictEqual(endStub.callCount, 1); + done(); + }); + + fakeStream.push(null); + }); + + it('should clean up the stream/transaction on error', done => { + const fakeError = new Error('err'); + const endStub = sandbox.stub(fakeSnapshot, 'end'); + + database.runStream(QUERY).on('error', err => { + assert.strictEqual(err, fakeError); + assert.strictEqual(endStub.callCount, 1); + done(); + }); + + fakeStream.destroy(fakeError); + }); + + it('should not retry on "Session not found" error', done => { + const sessionNotFoundError = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as grpc.ServiceError; + const endStub = sandbox.stub(fakeSnapshot, 'end'); + const endStub2 = sandbox.stub(fakeSnapshot2, 'end'); + const rows = 0; + + database.runStream(QUERY).on('error', err => { + assert.strictEqual(err, sessionNotFoundError); + assert.strictEqual(endStub.callCount, 1); + // make sure it is not retrying the stream + assert.strictEqual(endStub2.callCount, 0); + // row count should be 0 + assert.strictEqual(rows, 0); + done(); + }); + + fakeStream.emit('error', sessionNotFoundError); + fakeStream2.push('row1'); + fakeStream2.push(null); + }); + + it('should release the session on transaction end', () => { + const releaseStub = sandbox.stub( + fakeSessionFactory, + 'release', + ) as sinon.SinonStub; + + database.runStream(QUERY); + fakeSnapshot.emit('end'); + + const session = releaseStub.lastCall.args[0]; + assert.strictEqual(session, fakeSession); + }); + + // since mux is default enabled, session pool is not getting created + it.skip('should retry "Session not found" error', done => { + const sessionNotFoundError = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as grpc.ServiceError; + const endStub = sandbox.stub(fakeSnapshot, 'end'); + const endStub2 = sandbox.stub(fakeSnapshot2, 'end'); + let rows = 0; + + database + .runStream(QUERY) + .on('data', () => rows++) + .on('error', err => { + assert.fail(err); + }) + .on('end', () => { + assert.strictEqual(endStub.callCount, 1); + assert.strictEqual(endStub2.callCount, 1); + assert.strictEqual(rows, 1); + done(); + }); + + fakeStream.emit('error', sessionNotFoundError); + fakeStream2.push('row1'); + fakeStream2.push(null); + }); + }); + + describe('table', () => { + const NAME = 'table-name'; + + it('should throw if a name is not provided', () => { + assert.throws(() => { + database.table(); + }, /A name is required to access a Table object\./); + }); + + it('should return an instance of Tession', () => { + const table = database.table(NAME); + + assert(table instanceof FakeTable); + assert.strictEqual(table.calledWith_[0], database); + assert.strictEqual(table.calledWith_[1], NAME); + }); + }); + + describe('updateSchema', () => { + const STATEMENTS = ['statement-1', 'statement-2']; + + it('should call and return the request', () => { + const requestReturnValue = {}; + + database.request = (config, callback) => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'updateDatabaseDdl'); + assert.deepStrictEqual(config.reqOpts, { + database: database.formattedName_, + statements: STATEMENTS, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, database.commonHeaders_); + assert.strictEqual(callback, assert.ifError); + return requestReturnValue; + }; + + const returnValue = database.updateSchema(STATEMENTS, assert.ifError); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should arrify a string statement', done => { + database.request = config => { + assert.deepStrictEqual(config.reqOpts.statements, [STATEMENTS[0]]); + done(); + }; + + database.updateSchema(STATEMENTS[0], assert.ifError); + }); + + it('should accept an object', done => { + const config = { + statements: STATEMENTS, + otherConfiguration: {}, + }; + + const expectedReqOpts = extend({}, config, { + database: database.formattedName_, + }); + + database.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + done(); + }; + + database.updateSchema(config, assert.ifError); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + database.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + database.updateSchema(STATEMENTS, gaxOptions, assert.ifError); + }); + }); + + describe('createSession', () => { + const gaxOptions = {}; + const OPTIONS = {gaxOptions}; + + it('should make the correct request', done => { + database.request = config => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'createSession'); + assert.deepStrictEqual(config.reqOpts, { + database: database.formattedName_, + session: { + creatorRole: database.databaseRole, + labels: null, + }, + }); + assert.strictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual( + config.headers, + Object.assign( + { + [LEADER_AWARE_ROUTING_HEADER]: 'true', + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + }, + database.commonHeaders_, + ), + ); + + done(); + }; + + database.createSession(OPTIONS, assert.ifError); + }); + + it('should not require options', done => { + database.request = config => { + assert.deepStrictEqual(config.reqOpts, { + database: database.formattedName_, + session: { + creatorRole: database.databaseRole, + labels: null, + }, + }); + + assert.strictEqual(config.gaxOpts, undefined); + done(); + }; + + database.createSession(assert.ifError); + }); + + it('should send labels correctly', done => { + const labels = {a: 'b'}; + const options = {a: 'b', labels}; + const originalOptions = extend(true, {}, options); + + database.request = config => { + assert.deepStrictEqual(config.reqOpts.session.labels, labels); + assert.deepStrictEqual(options, originalOptions); + done(); + }; + + database.createSession({labels}, assert.ifError); + }); + + it('should send databaseRole correctly', done => { + const databaseRole = {databaseRole: 'child_role'}; + const options = {a: 'b', databaseRole: databaseRole}; + const originalOptions = extend(true, {}, options); + + database.request = config => { + assert.deepStrictEqual( + config.reqOpts.session.creatorRole, + databaseRole.databaseRole, + ); + assert.deepStrictEqual(options, originalOptions); + done(); + }; + + database.createSession(databaseRole, assert.ifError); + }); + + it('should send default databaseRole correctly', done => { + const databaseRole = {databaseRole: 'parent_role'}; + const options = {a: 'b'}; + const originalOptions = extend(true, {}, options); + + database.request = config => { + assert.deepStrictEqual( + config.reqOpts.session.creatorRole, + databaseRole.databaseRole, + ); + assert.deepStrictEqual(options, originalOptions); + done(); + }; + + database.createSession(databaseRole, assert.ifError); + }); + + it('should send multiplexed correctly', done => { + const multiplexed = {multiplexed: true}; + const options = {a: 'b', multiplexed}; + const originalOptions = extend(true, {}, options); + + database.request = config => { + assert.deepStrictEqual( + config.reqOpts.session.multiplexed, + multiplexed.multiplexed, + ); + assert.deepStrictEqual(options, originalOptions); + done(); + }; + + database.createSession(multiplexed, assert.ifError); + }); + + describe('error', () => { + const ERROR = new Error('Error.'); + const API_RESPONSE = {}; + + beforeEach(() => { + database.request = (config, callback) => { + callback(ERROR, API_RESPONSE); + }; + }); + + it('should execute callback with error & API response', done => { + database.createSession((err, session, apiResponse) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(session, null); + assert.strictEqual(apiResponse, API_RESPONSE); + done(); + }); + }); + }); + + describe('success', () => { + const API_RESPONSE = { + name: 'session-name', + }; + + beforeEach(() => { + database.request = (config, callback) => { + callback(null, API_RESPONSE); + }; + }); + + it('should execute callback with session & API response', done => { + const sessionInstance = {}; + + database.session = name => { + assert.strictEqual(name, API_RESPONSE.name); + return sessionInstance; + }; + + database.createSession((err, session, apiResponse) => { + assert.ifError(err); + + assert.strictEqual(session, sessionInstance); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.strictEqual((session as any).metadata, API_RESPONSE); + + assert.strictEqual(apiResponse, API_RESPONSE); + + done(); + }); + }); + }); + }); + + describe('getSnapshot', () => { + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakeSnapshot: FakeTransaction; + + let beginSnapshotStub: sinon.SinonStub; + let getSessionStub: sinon.SinonStub; + let snapshotStub: sinon.SinonStub; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakeSnapshot = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + + beginSnapshotStub = ( + sandbox.stub(fakeSnapshot, 'begin') as sinon.SinonStub + ).callsFake(callback => callback(null)); + + getSessionStub = ( + sandbox.stub(fakeSessionFactory, 'getSession') as sinon.SinonStub + ).callsFake(callback => callback(null, fakeSession)); + + snapshotStub = ( + sandbox.stub(fakeSession, 'snapshot') as sinon.SinonStub + ).returns(fakeSnapshot); + + ( + sandbox.stub( + fakeSessionFactory, + 'isMultiplexedEnabled', + ) as sinon.SinonStub + ).returns(true); + }); + + it('should return any multiplexed session errors', done => { + const fakeError = new Error('err'); + + getSessionStub.callsFake(callback => callback(fakeError)); + + database.getSnapshot(err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should pass the timestamp bounds to the snapshot', () => { + const fakeTimestampBounds = {}; + + database.getSnapshot(fakeTimestampBounds, assert.ifError); + + const bounds = snapshotStub.lastCall.args[0]; + assert.strictEqual(bounds, fakeTimestampBounds); + }); + + it('should throw error if maxStaleness is passed in the timestamp bounds to the snapshot', () => { + const fakeTimestampBounds = {maxStaleness: 10}; + + database.getSnapshot(fakeTimestampBounds, err => { + assert.strictEqual(err.code, 3); + assert.strictEqual( + err.message, + 'maxStaleness / minReadTimestamp is not supported for multi-use read-only transactions.', + ); + }); + }); + + it('should throw error if minReadTimestamp is passed in the timestamp bounds to the snapshot', () => { + const fakeTimestampBounds = {minReadTimestamp: 10}; + + database.getSnapshot(fakeTimestampBounds, err => { + assert.strictEqual(err.code, 3); + assert.strictEqual( + err.message, + 'maxStaleness / minReadTimestamp is not supported for multi-use read-only transactions.', + ); + }); + }); + + it('should pass when maxStaleness is undefined', () => { + const fakeTimestampBounds = {minReadTimestamp: undefined}; + + database.getSnapshot(fakeTimestampBounds, assert.ifError); + + const bounds = snapshotStub.lastCall.args[0]; + assert.strictEqual(bounds, fakeTimestampBounds); + }); + + it('should return the `snapshot`', done => { + database.getSnapshot((err, snapshot) => { + assert.ifError(err); + assert.strictEqual(snapshot, fakeSnapshot); + done(); + }); + }); + + it('should throw an error if `begin` errors with `Session not found`', done => { + const fakeError = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError; + + beginSnapshotStub.callsFake(callback => callback(fakeError)); + + database.getSnapshot((err, snapshot) => { + assert.strictEqual(err, fakeError); + assert.strictEqual(snapshot, undefined); + done(); + }); + }); + + it('should release the session if `begin` errors', done => { + const fakeError = new Error('err'); + + beginSnapshotStub.callsFake(callback => callback(fakeError)); + + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(fakeSession); + + database.getSnapshot(err => { + assert.strictEqual(err, fakeError); + assert.strictEqual(releaseStub.callCount, 1); + done(); + }); + }); + + // since mux is default enabled, session pool is not getting created + it.skip('should retry if `begin` errors with `Session not found`', done => { + const fakeError = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError; + + const fakeSession2 = new FakeSession(); + const fakeSnapshot2 = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadOnly, + ); + (sandbox.stub(fakeSnapshot2, 'begin') as sinon.SinonStub).callsFake( + callback => callback(null), + ); + sandbox.stub(fakeSession2, 'snapshot').returns(fakeSnapshot2); + + getSessionStub + .onFirstCall() + .callsFake(callback => callback(null, fakeSession)) + .onSecondCall() + .callsFake(callback => callback(null, fakeSession2)); + + beginSnapshotStub.callsFake(callback => callback(fakeError)); + + // The first session that was not found should be released back into the + // pool, so that the pool can remove it from its inventory. + const releaseStub = sandbox.stub(fakeSessionFactory, 'release'); + + database.getSnapshot((err, snapshot) => { + assert.ifError(err); + assert.strictEqual(snapshot, fakeSnapshot2); + // The first session that error should already have been released back + // to the pool. + assert.strictEqual(releaseStub.callCount, 1); + // Ending the valid snapshot will release its session back into the + // pool. + snapshot.emit('end'); + assert.strictEqual(releaseStub.callCount, 2); + done(); + }); + }); + + it('should release the snapshot on `end`', done => { + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(fakeSession); + + database.getSnapshot(err => { + assert.ifError(err); + fakeSnapshot.emit('end'); + assert.strictEqual(releaseStub.callCount, 1); + done(); + }); + }); + }); + + describe('getTransaction', () => { + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakeTransaction: FakeTransaction; + + let getSessionStub: sinon.SinonStub; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakeTransaction = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadWrite, + ); + + getSessionStub = ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForReadWrite', + ) as sinon.SinonStub + ).callsFake(callback => { + callback(null, fakeSession, fakeTransaction); + }); + }); + + it('should get a read/write transaction', () => { + getSessionStub.callsFake(() => {}); + + database.getTransaction(assert.ifError); + + assert.strictEqual(getSessionStub.callCount, 1); + }); + + it('should return any multiplexed session errors', done => { + const fakeError = new Error('err'); + + getSessionStub.callsFake(callback => callback(fakeError)); + + database.getTransaction(err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should return the read/write transaction', done => { + database.getTransaction((err, transaction) => { + assert.ifError(err); + assert.strictEqual(transaction, fakeTransaction); + done(); + }); + }); + + it('should propagate an error', done => { + const error = new Error('resource'); + (sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub) + .withArgs(fakeSession) + .throws(error); + + database.on('error', err => { + assert.deepStrictEqual(err, error); + done(); + }); + + database.getTransaction((err, transaction) => { + assert.ifError(err); + transaction.emit('end'); + }); + }); + + it('should release the session on transaction end', done => { + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(fakeSession); + + database.getTransaction((err, transaction) => { + assert.ifError(err); + transaction.emit('end'); + assert.strictEqual(releaseStub.callCount, 1); + done(); + }); + }); + }); + + describe('getSessions', () => { + it('should make the correct request', done => { + const gaxOpts = {}; + const options: { + a: string; + gaxOptions?: {}; + } = {a: 'a', gaxOptions: gaxOpts}; + + const expectedReqOpts = extend({}, options, { + database: database.formattedName_, + }); + + delete expectedReqOpts.gaxOptions; + + database.request = config => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'listSessions'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.deepStrictEqual(config.gaxOpts, gaxOpts); + assert.deepStrictEqual(config.headers, { + ...database.commonHeaders_, + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + }); + done(); + }; + + database.getSessions(options, assert.ifError); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options: { + a: string; + gaxOptions?: {pageSize: number; pageToken: string; timeout: number}; + } = {a: 'a', gaxOptions: gaxOptions}; + const expectedReqOpts = extend( + {}, + options, + { + database: database.formattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + delete expectedReqOpts.gaxOptions; + + database.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + database.getSessions(options, assert.ifError); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options: { + gaxOptions?: {pageSize: number; pageToken: string; timeout: number}; + } = Object.assign( + {}, + { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }, + ); + const expectedReqOpts = extend( + {}, + options, + { + database: database.formattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + delete expectedReqOpts.gaxOptions; + + database.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + database.getSessions(options, assert.ifError); + }); + + it('should not require options', done => { + database.request = config => { + assert.deepStrictEqual(config.reqOpts, { + database: database.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + done(); + }; + database.getSessions(assert.ifError); + }); + + it('should return all arguments on error', done => { + const ARGS = [new Error('err'), null, {}]; + database.request = (config, callback) => { + callback(...ARGS); + }; + database.getSessions((...args) => { + assert.deepStrictEqual(args, ARGS); + done(); + }); + }); + + it('should create and return Session objects', done => { + const ERR = null; + const SESSIONS = [{name: 'abc'}]; + const NEXTPAGEREQUEST = null; + const FULLAPIRESPONSE = {}; + const SESSION_INSTANCE = {}; + const RESPONSE = [ERR, SESSIONS, NEXTPAGEREQUEST, FULLAPIRESPONSE]; + + database.request = (config, callback) => { + callback(...RESPONSE); + }; + + database.session = name => { + assert.strictEqual(name, SESSIONS[0].name); + return SESSION_INSTANCE; + }; + + database.getSessions((err, sessions, nextQuery, resp) => { + assert.ifError(err); + assert.strictEqual(sessions[0], SESSION_INSTANCE); + assert.strictEqual(resp, FULLAPIRESPONSE); + done(); + }); + }); + + it('should return a complete nexQuery object', done => { + const pageSize = 1; + const filter = 'filter'; + const NEXTPAGEREQUEST = { + database: database.formattedName_, + pageSize, + filter, + pageToken: 'pageToken', + }; + const RESPONSE = [null, [], NEXTPAGEREQUEST, {}]; + + const GETSESSIONOPTIONS = { + pageSize, + filter, + gaxOptions: {timeout: 1000, autoPaginate: false}, + }; + const EXPECTEDNEXTQUERY = extend({}, GETSESSIONOPTIONS, NEXTPAGEREQUEST); + database.request = (config, callback) => { + callback(...RESPONSE); + }; + function callback(err, sessions, nextQuery) { + assert.deepStrictEqual(nextQuery, EXPECTEDNEXTQUERY); + done(); + } + database.getSessions(GETSESSIONOPTIONS, callback); + }); + }); + + describe('getSessionsStream', () => { + const OPTIONS = { + gaxOptions: {autoPaginate: false}, + } as db.GetSessionsOptions; + const returnValue = {} as Duplex; + + it('should make and return the correct gax API call', () => { + const expectedReqOpts = extend({}, OPTIONS, { + database: database.formattedName_, + }); + delete expectedReqOpts.gaxOptions; + + database.requestStream = config => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'listSessionsStream'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, OPTIONS.gaxOptions); + assert.deepStrictEqual(config.headers, database.commonHeaders_); + return returnValue; + }; + + const returnedValue = database.getSessionsStream(OPTIONS); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options = {gaxOptions}; + const expectedReqOpts = extend( + {}, + { + database: database.formattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + + database.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + return returnValue; + }; + + const returnedValue = database.getSessionsStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }; + const expectedReqOpts = extend( + {}, + { + database: database.formattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + + database.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + return returnValue; + }; + + const returnedValue = database.getSessionsStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should not require options', () => { + database.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, { + database: database.formattedName_, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + + return returnValue; + }; + + const returnedValue = database.getSessionsStream(); + assert.strictEqual(returnedValue, returnValue); + }); + }); + + describe('runPartitionedUpdate', () => { + const QUERY = { + sql: 'INSERT INTO `MyTable` (Key, Thing) VALUES(@key, @thing)', + params: { + key: 'k999', + thing: 'abc', + }, + }; + + let fakeSessionFactory: FakeSessionFactory; + let fakeSession: FakeSession; + let fakePartitionedDml: FakeTransaction; + + let getSessionStub; + let beginStub; + let runUpdateStub; + + const fakeDirectedReadOptions = { + includeReplicas: { + replicaSelections: [ + { + location: 'us-west1', + type: protos.google.spanner.v1.DirectedReadOptions.ReplicaSelection + .Type.READ_WRITE, + }, + ], + autoFailoverDisabled: true, + }, + }; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + fakeSession = new FakeSession(); + fakePartitionedDml = fakeSession.partitionedDml(); + + getSessionStub = ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForPartitionedOps', + ) as sinon.SinonStub + ).callsFake(callback => { + callback(null, fakeSession); + }); + + sandbox.stub(fakeSession, 'partitionedDml').returns(fakePartitionedDml); + + beginStub = ( + sandbox.stub(fakePartitionedDml, 'begin') as sinon.SinonStub + ).callsFake(callback => callback(null)); + + runUpdateStub = ( + sandbox.stub(fakePartitionedDml, 'runUpdate') as sinon.SinonStub + ).callsFake((_, callback) => callback(null)); + }); + + it('should make a call to getSessionForPartitionedOps', () => { + getSessionStub.callsFake(() => {}); + + database.runPartitionedUpdate(QUERY, assert.ifError); + + assert.strictEqual(getSessionStub.callCount, 1); + }); + + it('should get a session from the session factory', () => { + const fakeCallback = sandbox.spy(); + getSessionStub.callsFake(callback => callback(fakeSession)); + database.runPartitionedUpdate(QUERY, fakeCallback); + const [resp] = fakeCallback.lastCall.args; + assert.strictEqual(resp, fakeSession); + }); + + it('should return errors from getSessionForPartitionedOps', () => { + const fakeError = new Error('err'); + const fakeCallback = sandbox.spy(); + + getSessionStub.callsFake(callback => callback(fakeError)); + database.runPartitionedUpdate(QUERY, fakeCallback); + + const [err, rowCount] = fakeCallback.lastCall.args; + + assert.strictEqual(err, fakeError); + assert.strictEqual(rowCount, 0); + }); + + it('should get a partitioned dml transaction from the session factory', () => { + const fakeCallback = sandbox.spy(); + getSessionStub.callsFake(callback => callback(fakePartitionedDml)); + database.runPartitionedUpdate(QUERY, fakeCallback); + const [resp] = fakeCallback.lastCall.args; + assert.strictEqual(resp, fakePartitionedDml); + }); + + it('should call transaction begin', () => { + beginStub.callsFake(() => {}); + database.runPartitionedUpdate(QUERY, assert.ifError); + + assert.strictEqual(beginStub.callCount, 1); + }); + + it('should return any begin errors', done => { + const fakeError = new Error('err'); + + beginStub.callsFake(callback => callback(fakeError)); + + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(fakeSession); + + database.runPartitionedUpdate(QUERY, (err, rowCount) => { + assert.strictEqual(err, fakeError); + assert.strictEqual(rowCount, 0); + assert.strictEqual(releaseStub.callCount, 1); + done(); + }); + }); + + it('call `runUpdate` on the transaction', () => { + const fakeCallback = sandbox.spy(); + + database.runPartitionedUpdate(QUERY, fakeCallback); + + const [query] = runUpdateStub.lastCall.args; + + assert.strictEqual(query.sql, QUERY.sql); + assert.deepStrictEqual(query.params, QUERY.params); + assert.ok(fakeCallback.calledOnce); + }); + + it('should release the session on transaction end', () => { + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(fakeSession); + + database.runPartitionedUpdate(QUERY, assert.ifError); + fakePartitionedDml.emit('end'); + + assert.strictEqual(releaseStub.callCount, 1); + }); + + it('should accept requestOptions', () => { + const fakeCallback = sandbox.spy(); + + database.runPartitionedUpdate( + { + sql: QUERY.sql, + params: QUERY.params, + requestOptions: { + priority: RequestOptions.Priority.PRIORITY_LOW, + }, + }, + fakeCallback, + ); + + const [query] = runUpdateStub.lastCall.args; + + assert.deepStrictEqual(query, { + sql: QUERY.sql, + params: QUERY.params, + requestOptions: {priority: RequestOptions.Priority.PRIORITY_LOW}, + }); + assert.ok(fakeCallback.calledOnce); + }); + + it('should accept excludeTxnFromChangeStreams', () => { + const fakeCallback = sandbox.spy(); + + database.runPartitionedUpdate( + { + excludeTxnFromChangeStream: true, + }, + fakeCallback, + ); + + const [query] = runUpdateStub.lastCall.args; + + assert.deepStrictEqual(query, { + excludeTxnFromChangeStream: true, + }); + assert.ok(fakeCallback.calledOnce); + }); + + it('should ignore directedReadOptions set for client', () => { + const fakeCallback = sandbox.spy(); + + database.parent.parent = { + routeToLeaderEnabled: true, + directedReadOptions: fakeDirectedReadOptions, + options: {}, + }; + + database.runPartitionedUpdate( + { + sql: QUERY.sql, + params: QUERY.params, + requestOptions: { + priority: RequestOptions.Priority.PRIORITY_LOW, + }, + }, + fakeCallback, + ); + + const [query] = runUpdateStub.lastCall.args; + + assert.deepStrictEqual(query, { + sql: QUERY.sql, + params: QUERY.params, + requestOptions: {priority: RequestOptions.Priority.PRIORITY_LOW}, + }); + assert.ok(fakeCallback.calledOnce); + }); + }); + + describe('runTransaction', () => { + const SESSION = new FakeSession(); + const TRANSACTION = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadWrite, + ); + + let fakeSessionFactory: FakeSessionFactory; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + + ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForReadWrite', + ) as sinon.SinonStub + ).callsFake(callback => { + callback(null, SESSION, TRANSACTION); + }); + }); + + it('should return any errors getting a session', done => { + const fakeErr = new Error('err'); + + (fakeSessionFactory.getSessionForReadWrite as sinon.SinonStub).callsFake( + callback => callback(fakeErr), + ); + + database.runTransaction(err => { + assert.strictEqual(err, fakeErr); + done(); + }); + }); + + it('should create a `TransactionRunner`', () => { + const fakeRunFn = sandbox.spy(); + + database.runTransaction(fakeRunFn); + + const [session, transaction, runFn, options] = + fakeTransactionRunner.calledWith_; + + assert.strictEqual(session, SESSION); + assert.strictEqual(transaction, TRANSACTION); + assert.deepStrictEqual(options, {}); + }); + + it('should optionally accept runner `options`', () => { + const fakeOptions = {timeout: 1}; + + database.runTransaction(fakeOptions, assert.ifError); + + const options = fakeTransactionRunner.calledWith_[3]; + + assert.strictEqual(options, fakeOptions); + }); + + it('should optionally accept runner `option` isolationLevel', async () => { + const fakeOptions = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + + await database.runTransaction(fakeOptions, assert.ifError); + + const options = fakeTransactionRunner.calledWith_[3]; + assert.strictEqual(options, fakeOptions); + }); + + it('should optionally accept runner `option` readLockMode', async () => { + const fakeOptions = { + readLockMode: ReadLockMode.PESSIMISTIC, + }; + + await database.runTransaction(fakeOptions, assert.ifError); + + const options = fakeTransactionRunner.calledWith_[3]; + assert.strictEqual(options, fakeOptions); + }); + + it('should release the session when finished', done => { + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(SESSION); + + sandbox.stub(FakeTransactionRunner.prototype, 'run').resolves(); + + database.runTransaction(assert.ifError); + + setImmediate(() => { + assert.strictEqual(releaseStub.callCount, 1); + done(); + }); + }); + + it('should catch any run errors and return them', done => { + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(SESSION); + const fakeError = new Error('err'); + + sandbox.stub(FakeTransactionRunner.prototype, 'run').rejects(fakeError); + + database.runTransaction(err => { + assert.strictEqual(err, fakeError); + assert.strictEqual(releaseStub.callCount, 1); + done(); + }); + }); + }); + + describe('runTransactionAsync', () => { + const SESSION = new FakeSession(); + const TRANSACTION = new FakeTransaction( + {} as google.spanner.v1.TransactionOptions.ReadWrite, + ); + + let fakeSessionFactory: FakeSessionFactory; + + beforeEach(() => { + fakeSessionFactory = database.sessionFactory_; + ( + sandbox.stub( + fakeSessionFactory, + 'getSessionForReadWrite', + ) as sinon.SinonStub + ).callsFake(callback => { + callback(null, SESSION, TRANSACTION); + }); + }); + + it('should create an `AsyncTransactionRunner`', async () => { + const fakeRunFn = sandbox.spy(); + + await database.runTransactionAsync(fakeRunFn); + + const [session, transaction, runFn, options] = + fakeAsyncTransactionRunner.calledWith_; + assert.strictEqual(session, SESSION); + assert.strictEqual(transaction, TRANSACTION); + assert.strictEqual(runFn, fakeRunFn); + assert.deepStrictEqual(options, {}); + }); + + it('should optionally accept runner `options`', async () => { + const fakeOptions = {timeout: 1}; + + await database.runTransactionAsync(fakeOptions, assert.ifError); + + const options = fakeAsyncTransactionRunner.calledWith_[3]; + assert.strictEqual(options, fakeOptions); + }); + + it('should optionally accept runner `option` isolationLevel', async () => { + const fakeOptions = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + + await database.runTransactionAsync(fakeOptions, assert.ifError); + + const options = fakeAsyncTransactionRunner.calledWith_[3]; + assert.strictEqual(options, fakeOptions); + }); + + it('should optionally accept runner `option` readLockMode', async () => { + const fakeOptions = { + readLockMode: ReadLockMode.PESSIMISTIC, + }; + + await database.runTransactionAsync(fakeOptions, assert.ifError); + + const options = fakeAsyncTransactionRunner.calledWith_[3]; + assert.strictEqual(options, fakeOptions); + }); + + it('should return the runners resolved value', async () => { + const fakeValue = {}; + + sandbox + .stub(FakeAsyncTransactionRunner.prototype, 'run') + .resolves(fakeValue); + + const value = await database.runTransactionAsync(assert.ifError); + assert.strictEqual(value, fakeValue); + }); + + it('should release the session when finished', async () => { + const releaseStub = ( + sandbox.stub(fakeSessionFactory, 'release') as sinon.SinonStub + ).withArgs(SESSION); + + sandbox.stub(FakeAsyncTransactionRunner.prototype, 'run').resolves(); + + await database.runTransactionAsync(assert.ifError); + assert.strictEqual(releaseStub.callCount, 1); + }); + }); + + describe('session', () => { + const NAME = 'session-name'; + + it('should return an instance of Session', () => { + const session = database.session(NAME); + assert(session instanceof FakeSession); + assert.strictEqual(session.calledWith_[0], database); + assert.strictEqual(session.calledWith_[1], NAME); + }); + }); + + describe('getState', () => { + it('should get state from database metadata', async () => { + database.getMetadata = async () => [{state: 'READY'}]; + const result = await database.getState(); + assert.strictEqual(result, 'READY'); + }); + + it('should accept and pass gaxOptions to getMetadata', async () => { + const options = {}; + database.getMetadata = async gaxOptions => { + assert.strictEqual(gaxOptions, options); + return [{}]; + }; + await database.getState(options); + }); + + it('should accept callback and return state', done => { + const state = 'READY'; + database.getMetadata = async () => [{state}]; + database.getState((err, result) => { + assert.ifError(err); + assert.strictEqual(result, state); + done(); + }); + }); + }); + + describe('getDatabaseDialect', () => { + it('should get database dialect from database metadata', async () => { + database.getMetadata = async () => [ + {databaseDialect: 'GOOGLE_STANDARD_SQL'}, + ]; + const result = await database.getDatabaseDialect(); + assert.strictEqual(result, 'GOOGLE_STANDARD_SQL'); + }); + + it('should accept and pass gaxOptions to getMetadata', async () => { + const options = {}; + database.getMetadata = async gaxOptions => { + assert.strictEqual(gaxOptions, options); + return [{}]; + }; + await database.getDatabaseDialect(options); + }); + + it('should accept callback and return database dialect', done => { + const databaseDialect = 'GOOGLE_STANDARD_SQL'; + database.getMetadata = async () => [{databaseDialect}]; + database.getDatabaseDialect((err, result) => { + assert.ifError(err); + assert.strictEqual(result, databaseDialect); + done(); + }); + }); + }); + + describe('getRestoreInfo', () => { + it('should get restore info from database metadata', async () => { + const restoreInfo = {sourceType: 'BACKUP'}; + database.getMetadata = async () => [{restoreInfo}]; + const result = await database.getRestoreInfo(); + assert.deepStrictEqual(result, restoreInfo); + }); + + it('should accept and pass gaxOptions to getMetadata', async () => { + const options = {}; + database.getMetadata = async gaxOptions => { + assert.strictEqual(gaxOptions, options); + return [{}]; + }; + await database.getRestoreInfo(options); + }); + + it('should accept callback and return info', done => { + const restoreInfo = {sourceType: 'BACKUP'}; + database.getMetadata = async () => [{restoreInfo}]; + database.getRestoreInfo((err, result) => { + assert.ifError(err); + assert.strictEqual(result, restoreInfo); + done(); + }); + }); + }); + + describe('getOperations', () => { + it('should create filter for querying the database', async () => { + const operations: IOperation[] = [{name: 'my-operation'}]; + + database.instance.getDatabaseOperations = async options => { + assert.strictEqual(options.filter, `name:${DATABASE_FORMATTED_NAME}`); + return [operations, {}]; + }; + + const [results] = await database.getOperations(); + assert.deepStrictEqual(results, operations); + }); + + it('should create filter for querying the database in combination with user supplied filter', async () => { + const operations: IOperation[] = [{name: 'my-operation'}]; + + database.instance.getDatabaseOperations = async options => { + assert.strictEqual( + options.filter, + `(name:${DATABASE_FORMATTED_NAME}) AND (someOtherAttribute: aValue)`, + ); + return [operations, {}]; + }; + + const [results] = await database.getOperations({ + filter: 'someOtherAttribute: aValue', + }); + assert.deepStrictEqual(results, operations); + }); + + it('should accept options with given gaxOptions', async () => { + const operations: IOperation[] = [{name: 'my-operation'}]; + const gaxOpts = { + timeout: 1000, + }; + + database.instance.getDatabaseOperations = async options => { + assert.strictEqual(options.gaxOptions, gaxOpts); + return [operations, {}]; + }; + + const [results] = await database.getOperations({ + filter: 'someOtherAttribute: aValue', + gaxOptions: gaxOpts, + }); + assert.deepStrictEqual(results, operations); + }); + + it('should accept callback', done => { + const operations: IOperation[] = [{name: 'my-operation'}]; + + database.instance.getDatabaseOperations = async () => [operations, {}]; + + database.getOperations((err, results) => { + assert.ifError(err); + assert.deepStrictEqual(results, operations); + done(); + }); + }); + }); + + describe('restore', () => { + const BACKUP_NAME = 'backup-name'; + const BACKUP_FORMATTED_NAME = + INSTANCE.formattedName_ + '/backups/' + BACKUP_NAME; + + it('should make the correct request', done => { + const QUERY = {}; + const ORIGINAL_QUERY = extend({}, QUERY); + const expectedReqOpts = extend({}, QUERY, { + databaseId: NAME, + parent: INSTANCE.formattedName_, + backup: BACKUP_FORMATTED_NAME, + }); + + database.id = NAME; + database.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'restoreDatabase'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, QUERY); + assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, database.commonHeaders_); + done(); + }; + + database.restore(BACKUP_FORMATTED_NAME, assert.ifError); + }); + + it('should accept a backup name', done => { + const QUERY = {}; + const expectedReqOpts = extend({}, QUERY, { + databaseId: NAME, + parent: INSTANCE.formattedName_, + backup: BACKUP_FORMATTED_NAME, + }); + + database.id = NAME; + database.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + done(); + }; + + database.restore(BACKUP_NAME, assert.ifError); + }); + + it('should accept restore options', done => { + const encryptionConfig = { + encryptionType: EncryptionType.CUSTOMER_MANAGED_ENCRYPTION, + kmsKeyName: 'some/key/path', + }; + const options = {encryptionConfig}; + + database.request = config => { + assert.deepStrictEqual( + config.reqOpts.encryptionConfig, + encryptionConfig, + ); + done(); + }; + + database.restore(BACKUP_NAME, options, assert.ifError); + }); + + it('should accept gaxOpts as CallOptions', done => { + const gaxOptions = {timeout: 1000}; + + database.request = config => { + assert.deepStrictEqual(config.gaxOpts, gaxOptions); + done(); + }; + + database.restore(BACKUP_NAME, gaxOptions, assert.ifError); + }); + + it('should accept restore and gax options', done => { + const encryptionConfig = { + encryptionType: EncryptionType.CUSTOMER_MANAGED_ENCRYPTION, + kmsKeyName: 'some/key/path', + }; + const gaxOptions = {timeout: 1000}; + const options = {gaxOptions, encryptionConfig}; + + database.request = config => { + assert.deepStrictEqual( + config.reqOpts.encryptionConfig, + encryptionConfig, + ); + assert.deepStrictEqual(config.gaxOpts, options.gaxOptions); + done(); + }; + + database.restore(BACKUP_NAME, options, assert.ifError); + }); + + describe('error', () => { + const ERROR = new Error('Error.'); + const API_RESPONSE = {}; + + beforeEach(() => { + database.request = (config, callback: Function) => { + callback(ERROR, null, API_RESPONSE); + }; + }); + + it('should execute callback with error & API response', done => { + database.restore(BACKUP_FORMATTED_NAME, (err, db, op, resp) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(db, null); + assert.strictEqual(op, null); + assert.strictEqual(resp, API_RESPONSE); + done(); + }); + }); + }); + + describe('success', () => { + const OPERATION = {}; + const API_RESPONSE = {}; + + beforeEach(() => { + database.request = (config, callback: Function) => { + callback(null, OPERATION, API_RESPONSE); + }; + }); + + it('should execute callback with a Database and Operation', done => { + database.restore(BACKUP_FORMATTED_NAME, (err, db, op, resp) => { + assert.ifError(err); + assert.strictEqual(db, database); + assert.strictEqual(op, OPERATION); + assert.strictEqual(resp, API_RESPONSE); + done(); + }); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/gapic_database_admin_v1.ts b/handwritten/spanner/test/gapic_database_admin_v1.ts new file mode 100644 index 00000000000..f9e1fd72380 --- /dev/null +++ b/handwritten/spanner/test/gapic_database_admin_v1.ts @@ -0,0 +1,6121 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as databaseadminModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf, LROperation, operationsProtos} 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'), +).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); +} + +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); +} + +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); +} + +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); + } + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.DatabaseAdminClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new databaseadminModule.v1.DatabaseAdminClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'spanner.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new databaseadminModule.v1.DatabaseAdminClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + databaseadminModule.v1.DatabaseAdminClient.servicePath; + assert.strictEqual(servicePath, 'spanner.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + databaseadminModule.v1.DatabaseAdminClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'spanner.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new databaseadminModule.v1.DatabaseAdminClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new databaseadminModule.v1.DatabaseAdminClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = databaseadminModule.v1.DatabaseAdminClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new databaseadminModule.v1.DatabaseAdminClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.databaseAdminStub, undefined); + await client.initialize(); + assert(client.databaseAdminStub); + }); + + it('has close method for the initialized client', done => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.databaseAdminStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has close method for the non-initialized client', done => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.databaseAdminStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getDatabase', () => { + it('invokes getDatabase without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ); + client.innerApiCalls.getDatabase = stubSimpleCall(expectedResponse); + const [response] = await client.getDatabase(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabase without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ); + client.innerApiCalls.getDatabase = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDatabase( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IDatabase | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabase with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDatabase = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabase with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetDatabaseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getDatabase(request), expectedError); + }); + }); + + describe('dropDatabase', () => { + it('invokes dropDatabase without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DropDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DropDatabaseRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.dropDatabase = stubSimpleCall(expectedResponse); + const [response] = await client.dropDatabase(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.dropDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.dropDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes dropDatabase without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DropDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DropDatabaseRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.dropDatabase = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.dropDatabase( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.dropDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.dropDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes dropDatabase with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DropDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DropDatabaseRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.dropDatabase = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.dropDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.dropDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.dropDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes dropDatabase with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DropDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DropDatabaseRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.dropDatabase(request), expectedError); + }); + }); + + describe('getDatabaseDdl', () => { + it('invokes getDatabaseDdl without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseDdlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetDatabaseDdlRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseDdlResponse(), + ); + client.innerApiCalls.getDatabaseDdl = stubSimpleCall(expectedResponse); + const [response] = await client.getDatabaseDdl(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDatabaseDdl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabaseDdl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabaseDdl without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseDdlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetDatabaseDdlRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseDdlResponse(), + ); + client.innerApiCalls.getDatabaseDdl = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDatabaseDdl( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IGetDatabaseDdlResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDatabaseDdl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabaseDdl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabaseDdl with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseDdlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetDatabaseDdlRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDatabaseDdl = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDatabaseDdl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDatabaseDdl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabaseDdl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDatabaseDdl with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetDatabaseDdlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetDatabaseDdlRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getDatabaseDdl(request), expectedError); + }); + }); + + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.setIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.setIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.setIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.setIamPolicy(request), expectedError); + }); + }); + + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getIamPolicy(request), expectedError); + }); + }); + + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.innerApiCalls.testIamPermissions = + stubSimpleCall(expectedResponse); + const [response] = await client.testIamPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.innerApiCalls.testIamPermissions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.testIamPermissions( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.ITestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.testIamPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.testIamPermissions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.testIamPermissions(request), expectedError); + }); + }); + + describe('getBackup', () => { + it('invokes getBackup without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ); + client.innerApiCalls.getBackup = stubSimpleCall(expectedResponse); + const [response] = await client.getBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackup without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ); + client.innerApiCalls.getBackup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBackup( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IBackup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackup with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBackup = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackup with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getBackup(request), expectedError); + }); + }); + + describe('updateBackup', () => { + it('invokes updateBackup without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateBackupRequest(), + ); + request.backup ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateBackupRequest', + ['backup', 'name'], + ); + request.backup.name = defaultValue1; + const expectedHeaderRequestParams = `backup.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ); + client.innerApiCalls.updateBackup = stubSimpleCall(expectedResponse); + const [response] = await client.updateBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackup without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateBackupRequest(), + ); + request.backup ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateBackupRequest', + ['backup', 'name'], + ); + request.backup.name = defaultValue1; + const expectedHeaderRequestParams = `backup.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ); + client.innerApiCalls.updateBackup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBackup( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IBackup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackup with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateBackupRequest(), + ); + request.backup ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateBackupRequest', + ['backup', 'name'], + ); + request.backup.name = defaultValue1; + const expectedHeaderRequestParams = `backup.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBackup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackup with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateBackupRequest(), + ); + request.backup ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateBackupRequest', + ['backup', 'name'], + ); + request.backup.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.updateBackup(request), expectedError); + }); + }); + + describe('deleteBackup', () => { + it('invokes deleteBackup without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DeleteBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DeleteBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBackup = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackup without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DeleteBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DeleteBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBackup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBackup( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackup with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DeleteBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DeleteBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBackup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackup with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DeleteBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DeleteBackupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteBackup(request), expectedError); + }); + }); + + describe('addSplitPoints', () => { + it('invokes addSplitPoints without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.AddSplitPointsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.AddSplitPointsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.AddSplitPointsResponse(), + ); + client.innerApiCalls.addSplitPoints = stubSimpleCall(expectedResponse); + const [response] = await client.addSplitPoints(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addSplitPoints as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addSplitPoints as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes addSplitPoints without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.AddSplitPointsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.AddSplitPointsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.AddSplitPointsResponse(), + ); + client.innerApiCalls.addSplitPoints = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.addSplitPoints( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IAddSplitPointsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.addSplitPoints as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addSplitPoints as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes addSplitPoints with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.AddSplitPointsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.AddSplitPointsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.addSplitPoints = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.addSplitPoints(request), expectedError); + const actualRequest = ( + client.innerApiCalls.addSplitPoints as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.addSplitPoints as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes addSplitPoints with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.AddSplitPointsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.AddSplitPointsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.addSplitPoints(request), expectedError); + }); + }); + + describe('createBackupSchedule', () => { + it('invokes createBackupSchedule without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateBackupScheduleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ); + client.innerApiCalls.createBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.createBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackupSchedule without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateBackupScheduleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ); + client.innerApiCalls.createBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IBackupSchedule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackupSchedule with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateBackupScheduleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBackupSchedule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackupSchedule with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateBackupScheduleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createBackupSchedule(request), expectedError); + }); + }); + + describe('getBackupSchedule', () => { + it('invokes getBackupSchedule without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ); + client.innerApiCalls.getBackupSchedule = stubSimpleCall(expectedResponse); + const [response] = await client.getBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackupSchedule without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ); + client.innerApiCalls.getBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IBackupSchedule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackupSchedule with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBackupSchedule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBackupSchedule with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.GetBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.GetBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getBackupSchedule(request), expectedError); + }); + }); + + describe('updateBackupSchedule', () => { + it('invokes updateBackupSchedule without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateBackupScheduleRequest(), + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'], + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ); + client.innerApiCalls.updateBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.updateBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackupSchedule without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateBackupScheduleRequest(), + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'], + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ); + client.innerApiCalls.updateBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IBackupSchedule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackupSchedule with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateBackupScheduleRequest(), + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'], + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBackupSchedule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBackupSchedule with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateBackupScheduleRequest(), + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'], + ); + request.backupSchedule.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.updateBackupSchedule(request), expectedError); + }); + }); + + describe('deleteBackupSchedule', () => { + it('invokes deleteBackupSchedule without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DeleteBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DeleteBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackupSchedule without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DeleteBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DeleteBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackupSchedule with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DeleteBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DeleteBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBackupSchedule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBackupSchedule with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.DeleteBackupScheduleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.DeleteBackupScheduleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteBackupSchedule(request), expectedError); + }); + }); + + describe('internalUpdateGraphOperation', () => { + it('invokes internalUpdateGraphOperation without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse(), + ); + client.innerApiCalls.internalUpdateGraphOperation = + stubSimpleCall(expectedResponse); + const [response] = await client.internalUpdateGraphOperation(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes internalUpdateGraphOperation without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.database.v1.InternalUpdateGraphOperationResponse(), + ); + client.innerApiCalls.internalUpdateGraphOperation = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.internalUpdateGraphOperation( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IInternalUpdateGraphOperationResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes internalUpdateGraphOperation with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.internalUpdateGraphOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.internalUpdateGraphOperation(request), + expectedError, + ); + }); + + it('invokes internalUpdateGraphOperation with closed client', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.InternalUpdateGraphOperationRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects( + client.internalUpdateGraphOperation(request), + expectedError, + ); + }); + }); + + describe('createDatabase', () => { + it('invokes createDatabase without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.ICreateDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase with call error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDatabase = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase with LRO error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateDatabaseProgress without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateDatabaseProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateDatabaseProgress with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateDatabaseProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateDatabase', () => { + it('invokes updateDatabase without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateDatabaseRequest(), + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateDatabaseRequest', + ['database', 'name'], + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateDatabaseRequest(), + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateDatabaseRequest', + ['database', 'name'], + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IUpdateDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase with call error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateDatabaseRequest(), + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateDatabaseRequest', + ['database', 'name'], + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabase = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase with LRO error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateDatabaseRequest(), + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateDatabaseRequest', + ['database', 'name'], + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateDatabaseProgress without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateDatabaseProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateDatabaseProgress with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkUpdateDatabaseProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateDatabaseDdl', () => { + it('invokes updateDatabaseDdl without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateDatabaseDdl = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateDatabaseDdl(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDatabaseDdl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabaseDdl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabaseDdl without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateDatabaseDdl = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDatabaseDdl( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.protobuf.IEmpty, + protos.google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDatabaseDdl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabaseDdl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabaseDdl with call error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabaseDdl = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDatabaseDdl(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDatabaseDdl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabaseDdl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabaseDdl with LRO error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabaseDdl = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateDatabaseDdl(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDatabaseDdl as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabaseDdl as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateDatabaseDdlProgress without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateDatabaseDdlProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateDatabaseDdlProgress with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkUpdateDatabaseDdlProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('createBackup', () => { + it('invokes createBackup without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateBackupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createBackup = stubLongRunningCall(expectedResponse); + const [operation] = await client.createBackup(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackup without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateBackupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createBackup = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBackup( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICreateBackupMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackup with call error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateBackupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBackup = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBackup with LRO error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CreateBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CreateBackupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBackup = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createBackup(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateBackupProgress without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateBackupProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateBackupProgress with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkCreateBackupProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('copyBackup', () => { + it('invokes copyBackup without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CopyBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CopyBackupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.copyBackup = stubLongRunningCall(expectedResponse); + const [operation] = await client.copyBackup(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.copyBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.copyBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes copyBackup without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CopyBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CopyBackupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.copyBackup = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.copyBackup( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.database.v1.IBackup, + protos.google.spanner.admin.database.v1.ICopyBackupMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.copyBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.copyBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes copyBackup with call error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CopyBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CopyBackupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.copyBackup = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.copyBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.copyBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.copyBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes copyBackup with LRO error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.CopyBackupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.CopyBackupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.copyBackup = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.copyBackup(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.copyBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.copyBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCopyBackupProgress without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCopyBackupProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCopyBackupProgress with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkCopyBackupProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('restoreDatabase', () => { + it('invokes restoreDatabase without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.RestoreDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.RestoreDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.restoreDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.restoreDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.RestoreDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.RestoreDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.restoreDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.restoreDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.database.v1.IDatabase, + protos.google.spanner.admin.database.v1.IRestoreDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase with call error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.RestoreDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.RestoreDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreDatabase = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.restoreDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase with LRO error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.RestoreDatabaseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.RestoreDatabaseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.restoreDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkRestoreDatabaseProgress without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkRestoreDatabaseProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkRestoreDatabaseProgress with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkRestoreDatabaseProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listDatabases', () => { + it('invokes listDatabases without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + ]; + client.innerApiCalls.listDatabases = stubSimpleCall(expectedResponse); + const [response] = await client.listDatabases(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabases without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + ]; + client.innerApiCalls.listDatabases = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDatabases( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IDatabase[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabases with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDatabases = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDatabases(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabasesStream without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + ]; + client.descriptors.page.listDatabases.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDatabasesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.database.v1.Database[] = + []; + stream.on( + 'data', + (response: protos.google.spanner.admin.database.v1.Database) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDatabases.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDatabases, request), + ); + assert( + (client.descriptors.page.listDatabases.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listDatabasesStream with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatabases.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDatabasesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.database.v1.Database[] = + []; + stream.on( + 'data', + (response: protos.google.spanner.admin.database.v1.Database) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDatabases.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDatabases, request), + ); + assert( + (client.descriptors.page.listDatabases.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDatabases without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Database(), + ), + ]; + client.descriptors.page.listDatabases.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.spanner.admin.database.v1.IDatabase[] = []; + const iterable = client.listDatabasesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatabases.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDatabases.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDatabases with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabasesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabasesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatabases.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDatabasesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.spanner.admin.database.v1.IDatabase[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatabases.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDatabases.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listBackups', () => { + it('invokes listBackups without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + ]; + client.innerApiCalls.listBackups = stubSimpleCall(expectedResponse); + const [response] = await client.listBackups(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackups without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + ]; + client.innerApiCalls.listBackups = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackups( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.database.v1.IBackup[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackups with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackups = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBackups(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupsStream without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + ]; + client.descriptors.page.listBackups.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBackupsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.database.v1.Backup[] = []; + stream.on( + 'data', + (response: protos.google.spanner.admin.database.v1.Backup) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBackups.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBackups, request), + ); + assert( + (client.descriptors.page.listBackups.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listBackupsStream with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBackups.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listBackupsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.database.v1.Backup[] = []; + stream.on( + 'data', + (response: protos.google.spanner.admin.database.v1.Backup) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBackups.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBackups, request), + ); + assert( + (client.descriptors.page.listBackups.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listBackups without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.Backup(), + ), + ]; + client.descriptors.page.listBackups.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.spanner.admin.database.v1.IBackup[] = []; + const iterable = client.listBackupsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listBackups.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBackups.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listBackups with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBackups.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listBackupsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.spanner.admin.database.v1.IBackup[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listBackups.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listBackups.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDatabaseOperations', () => { + it('invokes listDatabaseOperations without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.innerApiCalls.listDatabaseOperations = + stubSimpleCall(expectedResponse); + const [response] = await client.listDatabaseOperations(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabaseOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabaseOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabaseOperations without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.innerApiCalls.listDatabaseOperations = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDatabaseOperations( + request, + ( + err?: Error | null, + result?: protos.google.longrunning.IOperation[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabaseOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabaseOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabaseOperations with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDatabaseOperations = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listDatabaseOperations(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listDatabaseOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabaseOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabaseOperationsStream without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.descriptors.page.listDatabaseOperations.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDatabaseOperationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.longrunning.Operation[] = []; + stream.on('data', (response: protos.google.longrunning.Operation) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listDatabaseOperations + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listDatabaseOperations, request), + ); + assert( + ( + client.descriptors.page.listDatabaseOperations + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listDatabaseOperationsStream with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatabaseOperations.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDatabaseOperationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.longrunning.Operation[] = []; + stream.on('data', (response: protos.google.longrunning.Operation) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listDatabaseOperations + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listDatabaseOperations, request), + ); + assert( + ( + client.descriptors.page.listDatabaseOperations + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listDatabaseOperations without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.descriptors.page.listDatabaseOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.longrunning.IOperation[] = []; + const iterable = client.listDatabaseOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatabaseOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDatabaseOperations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listDatabaseOperations with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatabaseOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDatabaseOperationsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatabaseOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDatabaseOperations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listBackupOperations', () => { + it('invokes listBackupOperations without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.innerApiCalls.listBackupOperations = + stubSimpleCall(expectedResponse); + const [response] = await client.listBackupOperations(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackupOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupOperations without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.innerApiCalls.listBackupOperations = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackupOperations( + request, + ( + err?: Error | null, + result?: protos.google.longrunning.IOperation[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackupOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupOperations with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackupOperations = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBackupOperations(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBackupOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupOperationsStream without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.descriptors.page.listBackupOperations.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBackupOperationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.longrunning.Operation[] = []; + stream.on('data', (response: protos.google.longrunning.Operation) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBackupOperations.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBackupOperations, request), + ); + assert( + (client.descriptors.page.listBackupOperations.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listBackupOperationsStream with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBackupOperations.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listBackupOperationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.longrunning.Operation[] = []; + stream.on('data', (response: protos.google.longrunning.Operation) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBackupOperations.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBackupOperations, request), + ); + assert( + (client.descriptors.page.listBackupOperations.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listBackupOperations without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.descriptors.page.listBackupOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.longrunning.IOperation[] = []; + const iterable = client.listBackupOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listBackupOperations.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listBackupOperations.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listBackupOperations with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBackupOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listBackupOperationsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listBackupOperations.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listBackupOperations.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDatabaseRoles', () => { + it('invokes listDatabaseRoles without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseRolesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseRolesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + ]; + client.innerApiCalls.listDatabaseRoles = stubSimpleCall(expectedResponse); + const [response] = await client.listDatabaseRoles(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabaseRoles as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabaseRoles as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabaseRoles without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseRolesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseRolesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + ]; + client.innerApiCalls.listDatabaseRoles = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDatabaseRoles( + request, + ( + err?: Error | null, + result?: + | protos.google.spanner.admin.database.v1.IDatabaseRole[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabaseRoles as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabaseRoles as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabaseRoles with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseRolesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseRolesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDatabaseRoles = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDatabaseRoles(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDatabaseRoles as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabaseRoles as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDatabaseRolesStream without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseRolesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseRolesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + ]; + client.descriptors.page.listDatabaseRoles.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDatabaseRolesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.database.v1.DatabaseRole[] = + []; + stream.on( + 'data', + (response: protos.google.spanner.admin.database.v1.DatabaseRole) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDatabaseRoles.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDatabaseRoles, request), + ); + assert( + (client.descriptors.page.listDatabaseRoles.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listDatabaseRolesStream with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseRolesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseRolesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatabaseRoles.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDatabaseRolesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.database.v1.DatabaseRole[] = + []; + stream.on( + 'data', + (response: protos.google.spanner.admin.database.v1.DatabaseRole) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDatabaseRoles.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDatabaseRoles, request), + ); + assert( + (client.descriptors.page.listDatabaseRoles.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDatabaseRoles without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseRolesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseRolesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.DatabaseRole(), + ), + ]; + client.descriptors.page.listDatabaseRoles.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.spanner.admin.database.v1.IDatabaseRole[] = + []; + const iterable = client.listDatabaseRolesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatabaseRoles.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDatabaseRoles.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDatabaseRoles with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListDatabaseRolesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListDatabaseRolesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDatabaseRoles.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDatabaseRolesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.spanner.admin.database.v1.IDatabaseRole[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDatabaseRoles.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDatabaseRoles.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listBackupSchedules', () => { + it('invokes listBackupSchedules without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + ]; + client.innerApiCalls.listBackupSchedules = + stubSimpleCall(expectedResponse); + const [response] = await client.listBackupSchedules(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupSchedules without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + ]; + client.innerApiCalls.listBackupSchedules = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackupSchedules( + request, + ( + err?: Error | null, + result?: + | protos.google.spanner.admin.database.v1.IBackupSchedule[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupSchedules with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackupSchedules = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBackupSchedules(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listBackupSchedulesStream without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + ]; + client.descriptors.page.listBackupSchedules.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBackupSchedulesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.database.v1.BackupSchedule[] = + []; + stream.on( + 'data', + ( + response: protos.google.spanner.admin.database.v1.BackupSchedule, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listBackupSchedules.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBackupSchedules, request), + ); + assert( + (client.descriptors.page.listBackupSchedules.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listBackupSchedulesStream with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBackupSchedules.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listBackupSchedulesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.database.v1.BackupSchedule[] = + []; + stream.on( + 'data', + ( + response: protos.google.spanner.admin.database.v1.BackupSchedule, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBackupSchedules.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBackupSchedules, request), + ); + assert( + (client.descriptors.page.listBackupSchedules.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listBackupSchedules without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + generateSampleMessage( + new protos.google.spanner.admin.database.v1.BackupSchedule(), + ), + ]; + client.descriptors.page.listBackupSchedules.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.spanner.admin.database.v1.IBackupSchedule[] = + []; + const iterable = client.listBackupSchedulesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listBackupSchedules.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listBackupSchedules.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listBackupSchedules with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.database.v1.ListBackupSchedulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.database.v1.ListBackupSchedulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBackupSchedules.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listBackupSchedulesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.spanner.admin.database.v1.IBackupSchedule[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listBackupSchedules.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listBackupSchedules.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + describe('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const response = await client.getOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes getOperation without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .getOperation( + request, + undefined, + ( + err?: Error | null, + result?: operationsProtos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + it('invokes getOperation with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.getOperation(request); + }, expectedError); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = + stubSimpleCall(expectedResponse); + const response = await client.cancelOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes cancelOperation without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.cancelOperation as SinonStub).getCall(0)); + }); + it('invokes cancelOperation with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.cancelOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.cancelOperation(request); + }, expectedError); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('deleteOperation', () => { + it('invokes deleteOperation without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = + stubSimpleCall(expectedResponse); + const response = await client.deleteOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes deleteOperation without error using callback', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.deleteOperation as SinonStub).getCall(0)); + }); + it('invokes deleteOperation with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.deleteOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.deleteOperation(request); + }, expectedError); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('listOperationsAsync', () => { + it('uses async iteration with listOperations without error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + ]; + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: operationsProtos.google.longrunning.IOperation[] = []; + const iterable = client.operationsClient.listOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + it('uses async iteration with listOperations with error', async () => { + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.operationsClient.listOperationsAsync(request); + await assert.rejects(async () => { + const responses: operationsProtos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('backup', async () => { + const fakePath = '/rendered/path/backup'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + backup: 'backupValue', + }; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.backupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('backupPath', () => { + const result = client.backupPath( + 'projectValue', + 'instanceValue', + 'backupValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.backupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBackupName', () => { + const result = client.matchProjectFromBackupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromBackupName', () => { + const result = client.matchInstanceFromBackupName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBackupFromBackupName', () => { + const result = client.matchBackupFromBackupName(fakePath); + assert.strictEqual(result, 'backupValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('backupSchedule', async () => { + const fakePath = '/rendered/path/backupSchedule'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + schedule: 'scheduleValue', + }; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupSchedulePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.backupSchedulePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('backupSchedulePath', () => { + const result = client.backupSchedulePath( + 'projectValue', + 'instanceValue', + 'databaseValue', + 'scheduleValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.backupSchedulePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBackupScheduleName', () => { + const result = client.matchProjectFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromBackupScheduleName', () => { + const result = client.matchInstanceFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromBackupScheduleName', () => { + const result = client.matchDatabaseFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchScheduleFromBackupScheduleName', () => { + const result = client.matchScheduleFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'scheduleValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('cryptoKey', async () => { + const fakePath = '/rendered/path/cryptoKey'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + key_ring: 'keyRingValue', + crypto_key: 'cryptoKeyValue', + }; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cryptoKeyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cryptoKeyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cryptoKeyPath', () => { + const result = client.cryptoKeyPath( + 'projectValue', + 'locationValue', + 'keyRingValue', + 'cryptoKeyValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cryptoKeyPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromCryptoKeyName', () => { + const result = client.matchProjectFromCryptoKeyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.cryptoKeyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromCryptoKeyName', () => { + const result = client.matchLocationFromCryptoKeyName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.cryptoKeyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchKeyRingFromCryptoKeyName', () => { + const result = client.matchKeyRingFromCryptoKeyName(fakePath); + assert.strictEqual(result, 'keyRingValue'); + assert( + (client.pathTemplates.cryptoKeyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCryptoKeyFromCryptoKeyName', () => { + const result = client.matchCryptoKeyFromCryptoKeyName(fakePath); + assert.strictEqual(result, 'cryptoKeyValue'); + assert( + (client.pathTemplates.cryptoKeyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('database', async () => { + const fakePath = '/rendered/path/database'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + }; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.databasePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.databasePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('databasePath', () => { + const result = client.databasePath( + 'projectValue', + 'instanceValue', + 'databaseValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.databasePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromDatabaseName', () => { + const result = client.matchProjectFromDatabaseName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromDatabaseName', () => { + const result = client.matchInstanceFromDatabaseName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromDatabaseName', () => { + const result = client.matchDatabaseFromDatabaseName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('databaseRole', async () => { + const fakePath = '/rendered/path/databaseRole'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + role: 'roleValue', + }; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.databaseRolePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.databaseRolePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('databaseRolePath', () => { + const result = client.databaseRolePath( + 'projectValue', + 'instanceValue', + 'databaseValue', + 'roleValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.databaseRolePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromDatabaseRoleName', () => { + const result = client.matchProjectFromDatabaseRoleName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.databaseRolePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromDatabaseRoleName', () => { + const result = client.matchInstanceFromDatabaseRoleName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.databaseRolePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromDatabaseRoleName', () => { + const result = client.matchDatabaseFromDatabaseRoleName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.databaseRolePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchRoleFromDatabaseRoleName', () => { + const result = client.matchRoleFromDatabaseRoleName(fakePath); + assert.strictEqual(result, 'roleValue'); + assert( + (client.pathTemplates.databaseRolePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('instance', async () => { + const fakePath = '/rendered/path/instance'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + }; + const client = new databaseadminModule.v1.DatabaseAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.instancePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instancePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instancePath', () => { + const result = client.instancePath('projectValue', 'instanceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.instancePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstanceName', () => { + const result = client.matchProjectFromInstanceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromInstanceName', () => { + const result = client.matchInstanceFromInstanceName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/gapic_instance_admin_v1.ts b/handwritten/spanner/test/gapic_instance_admin_v1.ts new file mode 100644 index 00000000000..cff2b7cc7b9 --- /dev/null +++ b/handwritten/spanner/test/gapic_instance_admin_v1.ts @@ -0,0 +1,5130 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as instanceadminModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf, LROperation, operationsProtos} 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'), +).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); +} + +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); +} + +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error, +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); +} + +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); + } + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.InstanceAdminClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new instanceadminModule.v1.InstanceAdminClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'spanner.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new instanceadminModule.v1.InstanceAdminClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + instanceadminModule.v1.InstanceAdminClient.servicePath; + assert.strictEqual(servicePath, 'spanner.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + instanceadminModule.v1.InstanceAdminClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'spanner.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new instanceadminModule.v1.InstanceAdminClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new instanceadminModule.v1.InstanceAdminClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new instanceadminModule.v1.InstanceAdminClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = instanceadminModule.v1.InstanceAdminClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new instanceadminModule.v1.InstanceAdminClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.instanceAdminStub, undefined); + await client.initialize(); + assert(client.instanceAdminStub); + }); + + it('has close method for the initialized client', done => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.instanceAdminStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has close method for the non-initialized client', done => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.instanceAdminStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getInstanceConfig', () => { + it('invokes getInstanceConfig without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstanceConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ); + client.innerApiCalls.getInstanceConfig = stubSimpleCall(expectedResponse); + const [response] = await client.getInstanceConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstanceConfig without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstanceConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ); + client.innerApiCalls.getInstanceConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getInstanceConfig( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.instance.v1.IInstanceConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstanceConfig with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstanceConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getInstanceConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getInstanceConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstanceConfig with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstanceConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getInstanceConfig(request), expectedError); + }); + }); + + describe('deleteInstanceConfig', () => { + it('invokes deleteInstanceConfig without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInstanceConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteInstanceConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstanceConfig without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInstanceConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteInstanceConfig( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstanceConfig with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInstanceConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteInstanceConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstanceConfig with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteInstanceConfig(request), expectedError); + }); + }); + + describe('getInstance', () => { + it('invokes getInstance without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ); + client.innerApiCalls.getInstance = stubSimpleCall(expectedResponse); + const [response] = await client.getInstance(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstance without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ); + client.innerApiCalls.getInstance = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getInstance( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.instance.v1.IInstance | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstance with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getInstance = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstance with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getInstance(request), expectedError); + }); + }); + + describe('deleteInstance', () => { + it('invokes deleteInstance without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInstance = stubSimpleCall(expectedResponse); + const [response] = await client.deleteInstance(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstance without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInstance = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteInstance( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstance with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInstance = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstance with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteInstance(request), expectedError); + }); + }); + + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.setIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.setIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.setIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.setIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.setIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.SetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.SetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.setIamPolicy(request), expectedError); + }); + }); + + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.Policy(), + ); + client.innerApiCalls.getIamPolicy = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.IPolicy | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIamPolicy as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.GetIamPolicyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.GetIamPolicyRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getIamPolicy(request), expectedError); + }); + }); + + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.innerApiCalls.testIamPermissions = + stubSimpleCall(expectedResponse); + const [response] = await client.testIamPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsResponse(), + ); + client.innerApiCalls.testIamPermissions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.testIamPermissions( + request, + ( + err?: Error | null, + result?: protos.google.iam.v1.ITestIamPermissionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedHeaderRequestParams = `resource=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.testIamPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.testIamPermissions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.testIamPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.iam.v1.TestIamPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.iam.v1.TestIamPermissionsRequest', + ['resource'], + ); + request.resource = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.testIamPermissions(request), expectedError); + }); + }); + + describe('getInstancePartition', () => { + it('invokes getInstancePartition without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstancePartitionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ); + client.innerApiCalls.getInstancePartition = + stubSimpleCall(expectedResponse); + const [response] = await client.getInstancePartition(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstancePartition without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstancePartitionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ); + client.innerApiCalls.getInstancePartition = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getInstancePartition( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.instance.v1.IInstancePartition | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstancePartition with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstancePartitionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getInstancePartition = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getInstancePartition(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getInstancePartition with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.GetInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.GetInstancePartitionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getInstancePartition(request), expectedError); + }); + }); + + describe('deleteInstancePartition', () => { + it('invokes deleteInstancePartition without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInstancePartition = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteInstancePartition(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstancePartition without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteInstancePartition = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteInstancePartition( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstancePartition with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteInstancePartition = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteInstancePartition(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteInstancePartition with closed client', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.DeleteInstancePartitionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects( + client.deleteInstancePartition(request), + expectedError, + ); + }); + }); + + describe('createInstanceConfig', () => { + it('invokes createInstanceConfig without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstanceConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstanceConfig = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createInstanceConfig(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstanceConfig without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstanceConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstanceConfig = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createInstanceConfig( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.ICreateInstanceConfigMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstanceConfig with call error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstanceConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstanceConfig = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createInstanceConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstanceConfig with LRO error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstanceConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstanceConfigRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstanceConfig = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createInstanceConfig(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateInstanceConfigProgress without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateInstanceConfigProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateInstanceConfigProgress with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateInstanceConfigProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateInstanceConfig', () => { + it('invokes updateInstanceConfig without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest(), + ); + request.instanceConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest', + ['instanceConfig', 'name'], + ); + request.instanceConfig.name = defaultValue1; + const expectedHeaderRequestParams = `instance_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstanceConfig = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateInstanceConfig(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstanceConfig without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest(), + ); + request.instanceConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest', + ['instanceConfig', 'name'], + ); + request.instanceConfig.name = defaultValue1; + const expectedHeaderRequestParams = `instance_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstanceConfig = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateInstanceConfig( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.instance.v1.IInstanceConfig, + protos.google.spanner.admin.instance.v1.IUpdateInstanceConfigMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstanceConfig with call error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest(), + ); + request.instanceConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest', + ['instanceConfig', 'name'], + ); + request.instanceConfig.name = defaultValue1; + const expectedHeaderRequestParams = `instance_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstanceConfig = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateInstanceConfig(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstanceConfig with LRO error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest(), + ); + request.instanceConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest', + ['instanceConfig', 'name'], + ); + request.instanceConfig.name = defaultValue1; + const expectedHeaderRequestParams = `instance_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstanceConfig = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateInstanceConfig(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstanceConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstanceConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateInstanceConfigProgress without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateInstanceConfigProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateInstanceConfigProgress with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkUpdateInstanceConfigProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('createInstance', () => { + it('invokes createInstance without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstance without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.ICreateInstanceMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstance with call error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstance with LRO error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstanceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateInstanceProgress without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateInstanceProgress with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateInstance', () => { + it('invokes updateInstance without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstance = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstance without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.instance.v1.IInstance, + protos.google.spanner.admin.instance.v1.IUpdateInstanceMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstance with call error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstance with LRO error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstanceRequest(), + ); + request.instance ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstanceRequest', + ['instance', 'name'], + ); + request.instance.name = defaultValue1; + const expectedHeaderRequestParams = `instance.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateInstanceProgress without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateInstanceProgress with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkUpdateInstanceProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('createInstancePartition', () => { + it('invokes createInstancePartition without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstancePartitionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstancePartition = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createInstancePartition(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstancePartition without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstancePartitionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createInstancePartition = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createInstancePartition( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.ICreateInstancePartitionMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstancePartition with call error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstancePartitionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstancePartition = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createInstancePartition(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createInstancePartition with LRO error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.CreateInstancePartitionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.CreateInstancePartitionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createInstancePartition = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createInstancePartition(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateInstancePartitionProgress without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = + await client.checkCreateInstancePartitionProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateInstancePartitionProgress with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkCreateInstancePartitionProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateInstancePartition', () => { + it('invokes updateInstancePartition without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest(), + ); + request.instancePartition ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest', + ['instancePartition', 'name'], + ); + request.instancePartition.name = defaultValue1; + const expectedHeaderRequestParams = `instance_partition.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstancePartition = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateInstancePartition(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstancePartition without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest(), + ); + request.instancePartition ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest', + ['instancePartition', 'name'], + ); + request.instancePartition.name = defaultValue1; + const expectedHeaderRequestParams = `instance_partition.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateInstancePartition = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateInstancePartition( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.instance.v1.IInstancePartition, + protos.google.spanner.admin.instance.v1.IUpdateInstancePartitionMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstancePartition with call error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest(), + ); + request.instancePartition ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest', + ['instancePartition', 'name'], + ); + request.instancePartition.name = defaultValue1; + const expectedHeaderRequestParams = `instance_partition.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstancePartition = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateInstancePartition(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateInstancePartition with LRO error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest(), + ); + request.instancePartition ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.UpdateInstancePartitionRequest', + ['instancePartition', 'name'], + ); + request.instancePartition.name = defaultValue1; + const expectedHeaderRequestParams = `instance_partition.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateInstancePartition = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateInstancePartition(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateInstancePartition as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateInstancePartition as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateInstancePartitionProgress without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = + await client.checkUpdateInstancePartitionProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateInstancePartitionProgress with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.checkUpdateInstancePartitionProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('moveInstance', () => { + it('invokes moveInstance without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.MoveInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.MoveInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.moveInstance = stubLongRunningCall(expectedResponse); + const [operation] = await client.moveInstance(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.moveInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.moveInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes moveInstance without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.MoveInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.MoveInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.moveInstance = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.moveInstance( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.spanner.admin.instance.v1.IMoveInstanceResponse, + protos.google.spanner.admin.instance.v1.IMoveInstanceMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.moveInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.moveInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes moveInstance with call error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.MoveInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.MoveInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.moveInstance = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.moveInstance(request), expectedError); + const actualRequest = ( + client.innerApiCalls.moveInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.moveInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes moveInstance with LRO error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.MoveInstanceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.MoveInstanceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.moveInstance = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.moveInstance(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.moveInstance as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.moveInstance as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkMoveInstanceProgress without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkMoveInstanceProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkMoveInstanceProgress with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkMoveInstanceProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listInstanceConfigs', () => { + it('invokes listInstanceConfigs without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + ]; + client.innerApiCalls.listInstanceConfigs = + stubSimpleCall(expectedResponse); + const [response] = await client.listInstanceConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstanceConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstanceConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstanceConfigs without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + ]; + client.innerApiCalls.listInstanceConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInstanceConfigs( + request, + ( + err?: Error | null, + result?: + | protos.google.spanner.admin.instance.v1.IInstanceConfig[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstanceConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstanceConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstanceConfigs with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInstanceConfigs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listInstanceConfigs(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listInstanceConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstanceConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstanceConfigsStream without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + ]; + client.descriptors.page.listInstanceConfigs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInstanceConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.instance.v1.InstanceConfig[] = + []; + stream.on( + 'data', + ( + response: protos.google.spanner.admin.instance.v1.InstanceConfig, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listInstanceConfigs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInstanceConfigs, request), + ); + assert( + (client.descriptors.page.listInstanceConfigs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listInstanceConfigsStream with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstanceConfigs.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInstanceConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.instance.v1.InstanceConfig[] = + []; + stream.on( + 'data', + ( + response: protos.google.spanner.admin.instance.v1.InstanceConfig, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listInstanceConfigs.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInstanceConfigs, request), + ); + assert( + (client.descriptors.page.listInstanceConfigs.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listInstanceConfigs without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstanceConfig(), + ), + ]; + client.descriptors.page.listInstanceConfigs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.spanner.admin.instance.v1.IInstanceConfig[] = + []; + const iterable = client.listInstanceConfigsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstanceConfigs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInstanceConfigs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listInstanceConfigs with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstanceConfigs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInstanceConfigsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.spanner.admin.instance.v1.IInstanceConfig[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstanceConfigs.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInstanceConfigs.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listInstanceConfigOperations', () => { + it('invokes listInstanceConfigOperations without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.innerApiCalls.listInstanceConfigOperations = + stubSimpleCall(expectedResponse); + const [response] = await client.listInstanceConfigOperations(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstanceConfigOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstanceConfigOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstanceConfigOperations without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.innerApiCalls.listInstanceConfigOperations = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInstanceConfigOperations( + request, + ( + err?: Error | null, + result?: protos.google.longrunning.IOperation[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstanceConfigOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstanceConfigOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstanceConfigOperations with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInstanceConfigOperations = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listInstanceConfigOperations(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listInstanceConfigOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstanceConfigOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstanceConfigOperationsStream without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.descriptors.page.listInstanceConfigOperations.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInstanceConfigOperationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.longrunning.Operation[] = []; + stream.on('data', (response: protos.google.longrunning.Operation) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listInstanceConfigOperations + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listInstanceConfigOperations, + request, + ), + ); + assert( + ( + client.descriptors.page.listInstanceConfigOperations + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listInstanceConfigOperationsStream with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstanceConfigOperations.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInstanceConfigOperationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.longrunning.Operation[] = []; + stream.on('data', (response: protos.google.longrunning.Operation) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listInstanceConfigOperations + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listInstanceConfigOperations, + request, + ), + ); + assert( + ( + client.descriptors.page.listInstanceConfigOperations + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listInstanceConfigOperations without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.descriptors.page.listInstanceConfigOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.longrunning.IOperation[] = []; + const iterable = client.listInstanceConfigOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstanceConfigOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listInstanceConfigOperations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listInstanceConfigOperations with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstanceConfigOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstanceConfigOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInstanceConfigOperationsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstanceConfigOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listInstanceConfigOperations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listInstances', () => { + it('invokes listInstances without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + ]; + client.innerApiCalls.listInstances = stubSimpleCall(expectedResponse); + const [response] = await client.listInstances(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstances without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + ]; + client.innerApiCalls.listInstances = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInstances( + request, + ( + err?: Error | null, + result?: protos.google.spanner.admin.instance.v1.IInstance[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstances with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInstances = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listInstances(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstances as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstancesStream without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + ]; + client.descriptors.page.listInstances.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInstancesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.instance.v1.Instance[] = + []; + stream.on( + 'data', + (response: protos.google.spanner.admin.instance.v1.Instance) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInstances, request), + ); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listInstancesStream with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstances.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInstancesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.instance.v1.Instance[] = + []; + stream.on( + 'data', + (response: protos.google.spanner.admin.instance.v1.Instance) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listInstances, request), + ); + assert( + (client.descriptors.page.listInstances.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listInstances without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.Instance(), + ), + ]; + client.descriptors.page.listInstances.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.spanner.admin.instance.v1.IInstance[] = []; + const iterable = client.listInstancesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstances.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInstances.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listInstances with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstances.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInstancesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.spanner.admin.instance.v1.IInstance[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstances.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listInstances.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listInstancePartitions', () => { + it('invokes listInstancePartitions without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + ]; + client.innerApiCalls.listInstancePartitions = + stubSimpleCall(expectedResponse); + const [response] = await client.listInstancePartitions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstancePartitions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstancePartitions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstancePartitions without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + ]; + client.innerApiCalls.listInstancePartitions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInstancePartitions( + request, + ( + err?: Error | null, + result?: + | protos.google.spanner.admin.instance.v1.IInstancePartition[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstancePartitions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstancePartitions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstancePartitions with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInstancePartitions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listInstancePartitions(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listInstancePartitions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstancePartitions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstancePartitionsStream without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + ]; + client.descriptors.page.listInstancePartitions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInstancePartitionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.instance.v1.InstancePartition[] = + []; + stream.on( + 'data', + ( + response: protos.google.spanner.admin.instance.v1.InstancePartition, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listInstancePartitions + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listInstancePartitions, request), + ); + assert( + ( + client.descriptors.page.listInstancePartitions + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listInstancePartitionsStream with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstancePartitions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInstancePartitionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.admin.instance.v1.InstancePartition[] = + []; + stream.on( + 'data', + ( + response: protos.google.spanner.admin.instance.v1.InstancePartition, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listInstancePartitions + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listInstancePartitions, request), + ); + assert( + ( + client.descriptors.page.listInstancePartitions + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listInstancePartitions without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + generateSampleMessage( + new protos.google.spanner.admin.instance.v1.InstancePartition(), + ), + ]; + client.descriptors.page.listInstancePartitions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.spanner.admin.instance.v1.IInstancePartition[] = + []; + const iterable = client.listInstancePartitionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstancePartitions + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listInstancePartitions + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listInstancePartitions with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstancePartitions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInstancePartitionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.spanner.admin.instance.v1.IInstancePartition[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstancePartitions + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listInstancePartitions + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listInstancePartitionOperations', () => { + it('invokes listInstancePartitionOperations without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.innerApiCalls.listInstancePartitionOperations = + stubSimpleCall(expectedResponse); + const [response] = await client.listInstancePartitionOperations(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstancePartitionOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstancePartitionOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstancePartitionOperations without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.innerApiCalls.listInstancePartitionOperations = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listInstancePartitionOperations( + request, + ( + err?: Error | null, + result?: protos.google.longrunning.IOperation[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listInstancePartitionOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstancePartitionOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstancePartitionOperations with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listInstancePartitionOperations = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listInstancePartitionOperations(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listInstancePartitionOperations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listInstancePartitionOperations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listInstancePartitionOperationsStream without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.descriptors.page.listInstancePartitionOperations.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listInstancePartitionOperationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.longrunning.Operation[] = []; + stream.on('data', (response: protos.google.longrunning.Operation) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listInstancePartitionOperations + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listInstancePartitionOperations, + request, + ), + ); + assert( + ( + client.descriptors.page.listInstancePartitionOperations + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listInstancePartitionOperationsStream with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstancePartitionOperations.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listInstancePartitionOperationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.longrunning.Operation[] = []; + stream.on('data', (response: protos.google.longrunning.Operation) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listInstancePartitionOperations + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listInstancePartitionOperations, + request, + ), + ); + assert( + ( + client.descriptors.page.listInstancePartitionOperations + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listInstancePartitionOperations without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + generateSampleMessage(new protos.google.longrunning.Operation()), + ]; + client.descriptors.page.listInstancePartitionOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.longrunning.IOperation[] = []; + const iterable = client.listInstancePartitionOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstancePartitionOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listInstancePartitionOperations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listInstancePartitionOperations with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.admin.instance.v1.ListInstancePartitionOperationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listInstancePartitionOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listInstancePartitionOperationsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listInstancePartitionOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listInstancePartitionOperations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + describe('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const response = await client.getOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes getOperation without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation(), + ); + client.operationsClient.getOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .getOperation( + request, + undefined, + ( + err?: Error | null, + result?: operationsProtos.google.longrunning.Operation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + it('invokes getOperation with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.getOperation(request); + }, expectedError); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = + stubSimpleCall(expectedResponse); + const response = await client.cancelOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes cancelOperation without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.cancelOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.cancelOperation as SinonStub).getCall(0)); + }); + it('invokes cancelOperation with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.cancelOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.cancelOperation(request); + }, expectedError); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('deleteOperation', () => { + it('invokes deleteOperation without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = + stubSimpleCall(expectedResponse); + const response = await client.deleteOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + it('invokes deleteOperation without error using callback', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.operationsClient.deleteOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.deleteOperation as SinonStub).getCall(0)); + }); + it('invokes deleteOperation with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.deleteOperation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(async () => { + await client.deleteOperation(request); + }, expectedError); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request), + ); + }); + }); + describe('listOperationsAsync', () => { + it('uses async iteration with listOperations without error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse(), + ), + ]; + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: operationsProtos.google.longrunning.IOperation[] = []; + const iterable = client.operationsClient.listOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + it('uses async iteration with listOperations with error', async () => { + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest(), + ); + const expectedError = new Error('expected'); + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.operationsClient.listOperationsAsync(request); + await assert.rejects(async () => { + const responses: operationsProtos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('instance', async () => { + const fakePath = '/rendered/path/instance'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + }; + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.instancePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instancePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instancePath', () => { + const result = client.instancePath('projectValue', 'instanceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.instancePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstanceName', () => { + const result = client.matchProjectFromInstanceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromInstanceName', () => { + const result = client.matchInstanceFromInstanceName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('instanceConfig', async () => { + const fakePath = '/rendered/path/instanceConfig'; + const expectedParameters = { + project: 'projectValue', + instance_config: 'instanceConfigValue', + }; + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.instanceConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instanceConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instanceConfigPath', () => { + const result = client.instanceConfigPath( + 'projectValue', + 'instanceConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.instanceConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstanceConfigName', () => { + const result = client.matchProjectFromInstanceConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.instanceConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceConfigFromInstanceConfigName', () => { + const result = + client.matchInstanceConfigFromInstanceConfigName(fakePath); + assert.strictEqual(result, 'instanceConfigValue'); + assert( + (client.pathTemplates.instanceConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('instancePartition', async () => { + const fakePath = '/rendered/path/instancePartition'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + instance_partition: 'instancePartitionValue', + }; + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.instancePartitionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instancePartitionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instancePartitionPath', () => { + const result = client.instancePartitionPath( + 'projectValue', + 'instanceValue', + 'instancePartitionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.instancePartitionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstancePartitionName', () => { + const result = client.matchProjectFromInstancePartitionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.instancePartitionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromInstancePartitionName', () => { + const result = client.matchInstanceFromInstancePartitionName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + ( + client.pathTemplates.instancePartitionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstancePartitionFromInstancePartitionName', () => { + const result = + client.matchInstancePartitionFromInstancePartitionName(fakePath); + assert.strictEqual(result, 'instancePartitionValue'); + assert( + ( + client.pathTemplates.instancePartitionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new instanceadminModule.v1.InstanceAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/gapic_spanner_executor_proxy_v1.ts b/handwritten/spanner/test/gapic_spanner_executor_proxy_v1.ts new file mode 100644 index 00000000000..7266a296643 --- /dev/null +++ b/handwritten/spanner/test/gapic_spanner_executor_proxy_v1.ts @@ -0,0 +1,917 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as spannerexecutorproxyModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf} 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'), +).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; +} + +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); +} + +describe('v1.SpannerExecutorProxyClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'spanner-cloud-executor.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + spannerexecutorproxyModule.v1.SpannerExecutorProxyClient.servicePath; + assert.strictEqual( + servicePath, + 'spanner-cloud-executor.googleapis.com', + ); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + spannerexecutorproxyModule.v1.SpannerExecutorProxyClient.apiEndpoint; + assert.strictEqual( + apiEndpoint, + 'spanner-cloud-executor.googleapis.com', + ); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner-cloud-executor.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner-cloud-executor.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner-cloud-executor.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'spanner-cloud-executor.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = + spannerexecutorproxyModule.v1.SpannerExecutorProxyClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.spannerExecutorProxyStub, undefined); + await client.initialize(); + assert(client.spannerExecutorProxyStub); + }); + + it('has close method for the initialized client', done => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.spannerExecutorProxyStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has close method for the non-initialized client', done => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.spannerExecutorProxyStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('executeActionAsync', () => { + it('invokes executeActionAsync without error', async () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.executor.v1.SpannerAsyncActionRequest(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.spanner.executor.v1.SpannerAsyncActionResponse(), + ); + client.innerApiCalls.executeActionAsync = + stubBidiStreamingCall(expectedResponse); + const stream = client.executeActionAsync(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.spanner.executor.v1.SpannerAsyncActionResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.executeActionAsync as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + + it('invokes executeActionAsync with error', async () => { + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.executor.v1.SpannerAsyncActionRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.executeActionAsync = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.executeActionAsync(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.spanner.executor.v1.SpannerAsyncActionResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.executeActionAsync as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('backup', async () => { + const fakePath = '/rendered/path/backup'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + backup: 'backupValue', + }; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.backupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('backupPath', () => { + const result = client.backupPath( + 'projectValue', + 'instanceValue', + 'backupValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.backupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBackupName', () => { + const result = client.matchProjectFromBackupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromBackupName', () => { + const result = client.matchInstanceFromBackupName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBackupFromBackupName', () => { + const result = client.matchBackupFromBackupName(fakePath); + assert.strictEqual(result, 'backupValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('backupSchedule', async () => { + const fakePath = '/rendered/path/backupSchedule'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + schedule: 'scheduleValue', + }; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupSchedulePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.backupSchedulePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('backupSchedulePath', () => { + const result = client.backupSchedulePath( + 'projectValue', + 'instanceValue', + 'databaseValue', + 'scheduleValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.backupSchedulePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromBackupScheduleName', () => { + const result = client.matchProjectFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromBackupScheduleName', () => { + const result = client.matchInstanceFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromBackupScheduleName', () => { + const result = client.matchDatabaseFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchScheduleFromBackupScheduleName', () => { + const result = client.matchScheduleFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'scheduleValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('database', async () => { + const fakePath = '/rendered/path/database'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + }; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.databasePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.databasePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('databasePath', () => { + const result = client.databasePath( + 'projectValue', + 'instanceValue', + 'databaseValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.databasePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromDatabaseName', () => { + const result = client.matchProjectFromDatabaseName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromDatabaseName', () => { + const result = client.matchInstanceFromDatabaseName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromDatabaseName', () => { + const result = client.matchDatabaseFromDatabaseName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('databaseRole', async () => { + const fakePath = '/rendered/path/databaseRole'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + role: 'roleValue', + }; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.databaseRolePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.databaseRolePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('databaseRolePath', () => { + const result = client.databaseRolePath( + 'projectValue', + 'instanceValue', + 'databaseValue', + 'roleValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.databaseRolePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromDatabaseRoleName', () => { + const result = client.matchProjectFromDatabaseRoleName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.databaseRolePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromDatabaseRoleName', () => { + const result = client.matchInstanceFromDatabaseRoleName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.databaseRolePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromDatabaseRoleName', () => { + const result = client.matchDatabaseFromDatabaseRoleName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.databaseRolePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchRoleFromDatabaseRoleName', () => { + const result = client.matchRoleFromDatabaseRoleName(fakePath); + assert.strictEqual(result, 'roleValue'); + assert( + (client.pathTemplates.databaseRolePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('instance', async () => { + const fakePath = '/rendered/path/instance'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + }; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.instancePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instancePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instancePath', () => { + const result = client.instancePath('projectValue', 'instanceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.instancePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstanceName', () => { + const result = client.matchProjectFromInstanceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromInstanceName', () => { + const result = client.matchInstanceFromInstanceName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.instancePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('instanceConfig', async () => { + const fakePath = '/rendered/path/instanceConfig'; + const expectedParameters = { + project: 'projectValue', + instance_config: 'instanceConfigValue', + }; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.instanceConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instanceConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instanceConfigPath', () => { + const result = client.instanceConfigPath( + 'projectValue', + 'instanceConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.instanceConfigPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstanceConfigName', () => { + const result = client.matchProjectFromInstanceConfigName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.instanceConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceConfigFromInstanceConfigName', () => { + const result = + client.matchInstanceConfigFromInstanceConfigName(fakePath); + assert.strictEqual(result, 'instanceConfigValue'); + assert( + (client.pathTemplates.instanceConfigPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('instancePartition', async () => { + const fakePath = '/rendered/path/instancePartition'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + instance_partition: 'instancePartitionValue', + }; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.instancePartitionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.instancePartitionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('instancePartitionPath', () => { + const result = client.instancePartitionPath( + 'projectValue', + 'instanceValue', + 'instancePartitionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.instancePartitionPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromInstancePartitionName', () => { + const result = client.matchProjectFromInstancePartitionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.instancePartitionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromInstancePartitionName', () => { + const result = client.matchInstanceFromInstancePartitionName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + ( + client.pathTemplates.instancePartitionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstancePartitionFromInstancePartitionName', () => { + const result = + client.matchInstancePartitionFromInstancePartitionName(fakePath); + assert.strictEqual(result, 'instancePartitionValue'); + assert( + ( + client.pathTemplates.instancePartitionPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + session: 'sessionValue', + }; + const client = + new spannerexecutorproxyModule.v1.SpannerExecutorProxyClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath( + 'projectValue', + 'instanceValue', + 'databaseValue', + 'sessionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromSessionName', () => { + const result = client.matchProjectFromSessionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromSessionName', () => { + const result = client.matchInstanceFromSessionName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromSessionName', () => { + const result = client.matchDatabaseFromSessionName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/gapic_spanner_v1.ts b/handwritten/spanner/test/gapic_spanner_v1.ts new file mode 100644 index 00000000000..d215e9a3836 --- /dev/null +++ b/handwritten/spanner/test/gapic_spanner_v1.ts @@ -0,0 +1,2874 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as spannerModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf} 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'), +).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject, + ) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error, +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); +} + +function stubServerStreamingCall( + response?: ResponseType, + error?: Error, +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); +} + +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error, +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); + } + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error, +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.SpannerClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new spannerModule.v1.SpannerClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'spanner.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new spannerModule.v1.SpannerClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); + + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = spannerModule.v1.SpannerClient.servicePath; + assert.strictEqual(servicePath, 'spanner.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = spannerModule.v1.SpannerClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'spanner.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new spannerModule.v1.SpannerClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new spannerModule.v1.SpannerClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new spannerModule.v1.SpannerClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new spannerModule.v1.SpannerClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'spanner.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new spannerModule.v1.SpannerClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = spannerModule.v1.SpannerClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new spannerModule.v1.SpannerClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new spannerModule.v1.SpannerClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.spannerStub, undefined); + await client.initialize(); + assert(client.spannerStub); + }); + + it('has close method for the initialized client', done => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.spannerStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has close method for the non-initialized client', done => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.spannerStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; + }); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createSession', () => { + it('invokes createSession without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.CreateSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.CreateSessionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.Session(), + ); + client.innerApiCalls.createSession = stubSimpleCall(expectedResponse); + const [response] = await client.createSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSession without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.CreateSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.CreateSessionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.Session(), + ); + client.innerApiCalls.createSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSession( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSession with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.CreateSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.CreateSessionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSession with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.CreateSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.CreateSessionRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createSession(request), expectedError); + }); + }); + + describe('batchCreateSessions', () => { + it('invokes batchCreateSessions without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BatchCreateSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BatchCreateSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.BatchCreateSessionsResponse(), + ); + client.innerApiCalls.batchCreateSessions = + stubSimpleCall(expectedResponse); + const [response] = await client.batchCreateSessions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateSessions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateSessions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchCreateSessions without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BatchCreateSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BatchCreateSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.BatchCreateSessionsResponse(), + ); + client.innerApiCalls.batchCreateSessions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchCreateSessions( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.IBatchCreateSessionsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateSessions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateSessions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchCreateSessions with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BatchCreateSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BatchCreateSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchCreateSessions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchCreateSessions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchCreateSessions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateSessions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchCreateSessions with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BatchCreateSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BatchCreateSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.batchCreateSessions(request), expectedError); + }); + }); + + describe('getSession', () => { + it('invokes getSession without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.Session(), + ); + client.innerApiCalls.getSession = stubSimpleCall(expectedResponse); + const [response] = await client.getSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSession without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.Session(), + ); + client.innerApiCalls.getSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSession( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.ISession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSession with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSession with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.GetSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.GetSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getSession(request), expectedError); + }); + }); + + describe('deleteSession', () => { + it('invokes deleteSession without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = stubSimpleCall(expectedResponse); + const [response] = await client.deleteSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSession without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSession( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSession with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSession with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.DeleteSessionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.DeleteSessionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteSession(request), expectedError); + }); + }); + + describe('executeSql', () => { + it('invokes executeSql without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteSqlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteSqlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.ResultSet(), + ); + client.innerApiCalls.executeSql = stubSimpleCall(expectedResponse); + const [response] = await client.executeSql(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executeSql as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeSql as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeSql without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteSqlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteSqlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.ResultSet(), + ); + client.innerApiCalls.executeSql = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.executeSql( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.IResultSet | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executeSql as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeSql as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeSql with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteSqlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteSqlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.executeSql = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.executeSql(request), expectedError); + const actualRequest = ( + client.innerApiCalls.executeSql as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeSql as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeSql with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteSqlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteSqlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.executeSql(request), expectedError); + }); + }); + + describe('executeBatchDml', () => { + it('invokes executeBatchDml without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteBatchDmlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteBatchDmlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.ExecuteBatchDmlResponse(), + ); + client.innerApiCalls.executeBatchDml = stubSimpleCall(expectedResponse); + const [response] = await client.executeBatchDml(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executeBatchDml as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeBatchDml as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeBatchDml without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteBatchDmlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteBatchDmlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.ExecuteBatchDmlResponse(), + ); + client.innerApiCalls.executeBatchDml = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.executeBatchDml( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.IExecuteBatchDmlResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executeBatchDml as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeBatchDml as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeBatchDml with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteBatchDmlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteBatchDmlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.executeBatchDml = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.executeBatchDml(request), expectedError); + const actualRequest = ( + client.innerApiCalls.executeBatchDml as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeBatchDml as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeBatchDml with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteBatchDmlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteBatchDmlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.executeBatchDml(request), expectedError); + }); + }); + + describe('read', () => { + it('invokes read without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.ResultSet(), + ); + client.innerApiCalls.read = stubSimpleCall(expectedResponse); + const [response] = await client.read(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.read as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.read as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes read without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.ResultSet(), + ); + client.innerApiCalls.read = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.read( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.IResultSet | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.read as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.read as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes read with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.read = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.read(request), expectedError); + const actualRequest = (client.innerApiCalls.read as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.read as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes read with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.read(request), expectedError); + }); + }); + + describe('beginTransaction', () => { + it('invokes beginTransaction without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BeginTransactionRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.Transaction(), + ); + client.innerApiCalls.beginTransaction = stubSimpleCall(expectedResponse); + const [response] = await client.beginTransaction(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BeginTransactionRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.Transaction(), + ); + client.innerApiCalls.beginTransaction = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.beginTransaction( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.ITransaction | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BeginTransactionRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.beginTransaction = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.beginTransaction(request), expectedError); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes beginTransaction with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BeginTransactionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BeginTransactionRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.beginTransaction(request), expectedError); + }); + }); + + describe('commit', () => { + it('invokes commit without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.CommitRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.CommitResponse(), + ); + client.innerApiCalls.commit = stubSimpleCall(expectedResponse); + const [response] = await client.commit(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.CommitRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.CommitResponse(), + ); + client.innerApiCalls.commit = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.commit( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.ICommitResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.CommitRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.commit = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.commit(request), expectedError); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes commit with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.CommitRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.CommitRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.commit(request), expectedError); + }); + }); + + describe('rollback', () => { + it('invokes rollback without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.RollbackRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.rollback = stubSimpleCall(expectedResponse); + const [response] = await client.rollback(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.RollbackRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.rollback = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.rollback( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.RollbackRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.rollback = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.rollback(request), expectedError); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes rollback with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.RollbackRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.RollbackRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.rollback(request), expectedError); + }); + }); + + describe('partitionQuery', () => { + it('invokes partitionQuery without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.PartitionQueryRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.PartitionResponse(), + ); + client.innerApiCalls.partitionQuery = stubSimpleCall(expectedResponse); + const [response] = await client.partitionQuery(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQuery without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.PartitionQueryRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.PartitionResponse(), + ); + client.innerApiCalls.partitionQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.partitionQuery( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.IPartitionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQuery with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.PartitionQueryRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.partitionQuery = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.partitionQuery(request), expectedError); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionQuery with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.PartitionQueryRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.PartitionQueryRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.partitionQuery(request), expectedError); + }); + }); + + describe('partitionRead', () => { + it('invokes partitionRead without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.PartitionReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.PartitionReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.PartitionResponse(), + ); + client.innerApiCalls.partitionRead = stubSimpleCall(expectedResponse); + const [response] = await client.partitionRead(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionRead as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionRead as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionRead without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.PartitionReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.PartitionReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.PartitionResponse(), + ); + client.innerApiCalls.partitionRead = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.partitionRead( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.IPartitionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionRead as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionRead as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionRead with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.PartitionReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.PartitionReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.partitionRead = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.partitionRead(request), expectedError); + const actualRequest = ( + client.innerApiCalls.partitionRead as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionRead as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes partitionRead with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.PartitionReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.PartitionReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.partitionRead(request), expectedError); + }); + }); + + describe('executeStreamingSql', () => { + it('invokes executeStreamingSql without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteSqlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteSqlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.PartialResultSet(), + ); + client.innerApiCalls.executeStreamingSql = + stubServerStreamingCall(expectedResponse); + const stream = client.executeStreamingSql(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.PartialResultSet) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executeStreamingSql as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeStreamingSql as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeStreamingSql without error and gaxServerStreamingRetries enabled', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteSqlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteSqlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.PartialResultSet(), + ); + client.innerApiCalls.executeStreamingSql = + stubServerStreamingCall(expectedResponse); + const stream = client.executeStreamingSql(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.PartialResultSet) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executeStreamingSql as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeStreamingSql as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeStreamingSql with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteSqlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteSqlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.executeStreamingSql = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.executeStreamingSql(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.PartialResultSet) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.executeStreamingSql as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executeStreamingSql as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executeStreamingSql with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ExecuteSqlRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ExecuteSqlRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.executeStreamingSql(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.PartialResultSet) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new spannerModule.v1.SpannerClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('streamingRead', () => { + it('invokes streamingRead without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.PartialResultSet(), + ); + client.innerApiCalls.streamingRead = + stubServerStreamingCall(expectedResponse); + const stream = client.streamingRead(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.PartialResultSet) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamingRead as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamingRead as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes streamingRead without error and gaxServerStreamingRetries enabled', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.PartialResultSet(), + ); + client.innerApiCalls.streamingRead = + stubServerStreamingCall(expectedResponse); + const stream = client.streamingRead(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.PartialResultSet) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamingRead as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamingRead as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes streamingRead with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.streamingRead = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.streamingRead(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.PartialResultSet) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.streamingRead as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamingRead as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes streamingRead with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ReadRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ReadRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.streamingRead(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.PartialResultSet) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new spannerModule.v1.SpannerClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('batchWrite', () => { + it('invokes batchWrite without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BatchWriteRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.BatchWriteResponse(), + ); + client.innerApiCalls.batchWrite = + stubServerStreamingCall(expectedResponse); + const stream = client.batchWrite(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.BatchWriteResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite without error and gaxServerStreamingRetries enabled', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BatchWriteRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.spanner.v1.BatchWriteResponse(), + ); + client.innerApiCalls.batchWrite = + stubServerStreamingCall(expectedResponse); + const stream = client.batchWrite(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.BatchWriteResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BatchWriteRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedHeaderRequestParams = `session=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchWrite = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.batchWrite(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.BatchWriteResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchWrite with closed client', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.BatchWriteRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.BatchWriteRequest', + ['session'], + ); + request.session = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.batchWrite(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.spanner.v1.BatchWriteResponse) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new spannerModule.v1.SpannerClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('listSessions', () => { + it('invokes listSessions without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ListSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ListSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.spanner.v1.Session()), + generateSampleMessage(new protos.google.spanner.v1.Session()), + generateSampleMessage(new protos.google.spanner.v1.Session()), + ]; + client.innerApiCalls.listSessions = stubSimpleCall(expectedResponse); + const [response] = await client.listSessions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSessions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSessions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSessions without error using callback', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ListSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ListSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.spanner.v1.Session()), + generateSampleMessage(new protos.google.spanner.v1.Session()), + generateSampleMessage(new protos.google.spanner.v1.Session()), + ]; + client.innerApiCalls.listSessions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSessions( + request, + ( + err?: Error | null, + result?: protos.google.spanner.v1.ISession[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSessions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSessions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSessions with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ListSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ListSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listSessions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listSessions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listSessions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSessions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSessionsStream without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ListSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ListSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.spanner.v1.Session()), + generateSampleMessage(new protos.google.spanner.v1.Session()), + generateSampleMessage(new protos.google.spanner.v1.Session()), + ]; + client.descriptors.page.listSessions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.v1.Session[] = []; + stream.on('data', (response: protos.google.spanner.v1.Session) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listSessionsStream with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ListSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ListSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listSessionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.spanner.v1.Session[] = []; + stream.on('data', (response: protos.google.spanner.v1.Session) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listSessions, request), + ); + assert( + (client.descriptors.page.listSessions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listSessions without error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ListSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ListSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.spanner.v1.Session()), + generateSampleMessage(new protos.google.spanner.v1.Session()), + generateSampleMessage(new protos.google.spanner.v1.Session()), + ]; + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.spanner.v1.ISession[] = []; + const iterable = client.listSessionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listSessions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listSessions with error', async () => { + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.spanner.v1.ListSessionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.spanner.v1.ListSessionsRequest', + ['database'], + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSessions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listSessionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.spanner.v1.ISession[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSessions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listSessions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('database', async () => { + const fakePath = '/rendered/path/database'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + }; + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.databasePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.databasePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('databasePath', () => { + const result = client.databasePath( + 'projectValue', + 'instanceValue', + 'databaseValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.databasePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromDatabaseName', () => { + const result = client.matchProjectFromDatabaseName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromDatabaseName', () => { + const result = client.matchInstanceFromDatabaseName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromDatabaseName', () => { + const result = client.matchDatabaseFromDatabaseName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('session', async () => { + const fakePath = '/rendered/path/session'; + const expectedParameters = { + project: 'projectValue', + instance: 'instanceValue', + database: 'databaseValue', + session: 'sessionValue', + }; + const client = new spannerModule.v1.SpannerClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.sessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('sessionPath', () => { + const result = client.sessionPath( + 'projectValue', + 'instanceValue', + 'databaseValue', + 'sessionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.sessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromSessionName', () => { + const result = client.matchProjectFromSessionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchInstanceFromSessionName', () => { + const result = client.matchInstanceFromSessionName(fakePath); + assert.strictEqual(result, 'instanceValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatabaseFromSessionName', () => { + const result = client.matchDatabaseFromSessionName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSessionFromSessionName', () => { + const result = client.matchSessionFromSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.sessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/index.ts b/handwritten/spanner/test/index.ts new file mode 100644 index 00000000000..39f4dfdd24a --- /dev/null +++ b/handwritten/spanner/test/index.ts @@ -0,0 +1,2400 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable prefer-rest-params */ + +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import * as extend from 'extend'; +import * as path from 'path'; +import * as proxyquire from 'proxyquire'; +import * as through from 'through2'; +import {util} from '@google-cloud/common'; +import {PreciseDate} from '@google-cloud/precise-date'; +import {replaceProjectIdToken} from '@google-cloud/projectify'; +import * as pfy from '@google-cloud/promisify'; +import {grpc} from 'google-gax'; +import * as sinon from 'sinon'; +import * as spnr from '../src'; +import {protos} from '../src'; +import {Duplex} from 'stream'; +import {CreateInstanceRequest, CreateInstanceConfigRequest} from '../src/index'; +import { + GetInstanceConfigOptions, + GetInstanceConfigsOptions, + GetInstancesOptions, +} from '../src'; +import {CLOUD_RESOURCE_HEADER, AFE_SERVER_TIMING_HEADER} from '../src/common'; +import {MetricsTracerFactory} from '../src/metrics/metrics-tracer-factory'; +import IsolationLevel = protos.google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = protos.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +const singer = require('./data/singer'); +const music = singer.examples.spanner.music; + +// Verify that CLOUD_RESOURCE_HEADER is set to a correct value. +assert.strictEqual(CLOUD_RESOURCE_HEADER, 'google-cloud-resource-prefix'); + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const apiConfig = require('../src/spanner_grpc_config.json'); + +async function disableMetrics(sandbox: sinon.SinonSandbox) { + sandbox.stub(process.env, 'SPANNER_DISABLE_BUILTIN_METRICS').value('true'); + await MetricsTracerFactory.resetInstance(); + MetricsTracerFactory.enabled = false; +} + +async function enableMetrics(sandbox: sinon.SinonSandbox) { + sandbox.stub(process.env, 'SPANNER_DISABLE_BUILTIN_METRICS').value('false'); + await MetricsTracerFactory.resetInstance(); +} + +function getFake(obj: {}) { + return obj as { + calledWith_: IArguments; + }; +} + +function asAny(obj) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return obj as any; +} + +let replaceProjectIdTokenOverride; +function fakeReplaceProjectIdToken(...args) { + return (replaceProjectIdTokenOverride || replaceProjectIdToken)(...args); +} + +const fakeGrpcGcp = () => { + return { + gcpChannelFactoryOverride: {}, + gcpCallInvocationTransformer: {}, + createGcpApiConfig: apiConfig => { + return { + calledWith_: apiConfig, + }; + }, + }; +}; + +let promisified = false; +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'Spanner') { + return; + } + promisified = true; + assert.deepStrictEqual(options.exclude, [ + 'date', + 'float32', + 'float', + 'instance', + 'instanceConfig', + 'int', + 'numeric', + 'pgNumeric', + 'pgJsonb', + 'operation', + 'timestamp', + 'interval', + 'getInstanceAdminClient', + 'getDatabaseAdminClient', + ]); + }, +}); + +let fakeGapicClient = util.noop; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +(fakeGapicClient as any).scopes = []; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const fakeV1: any = { + DatabaseAdminClient: fakeGapicClient, + InstanceAdminClient: fakeGapicClient, + SpannerClient: fakeGapicClient, +}; + +function fakeGoogleAuth() { + return { + calledWith_: arguments, + getProjectId: function (callback) { + if (callback) { + callback(null, 'project-id'); + return; + } else { + return Promise.resolve('project-id'); + } + }, + }; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const fakeCodec: any = { + SpannerDate: util.noop, +}; + +class FakeGrpcService { + calledWith_: IArguments; + projectId: string; + constructor() { + this.calledWith_ = arguments; + this.projectId = arguments[1].projectId; + } +} + +class FakeInstance { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } + static formatName_(projectId: string, name: string) { + return name; + } +} + +class FakeInstanceConfig { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } + static formatName_(projectId: string, name: string) { + return name; + } +} + +describe('Spanner', () => { + // tslint:disable-next-line variable-name + let Spanner: typeof spnr.Spanner; + let spanner: spnr.Spanner; + let sandbox: sinon.SinonSandbox; + + const OPTIONS = { + projectId: 'project-id', + }; + + before(() => { + Spanner = proxyquire('../src', { + './common-grpc/service': { + GrpcService: FakeGrpcService, + }, + '@google-cloud/promisify': fakePfy, + '@google-cloud/projectify': { + replaceProjectIdToken: fakeReplaceProjectIdToken, + }, + 'google-auth-library': { + GoogleAuth: fakeGoogleAuth, + }, + 'grpc-gcp': fakeGrpcGcp, + './codec.js': {codec: fakeCodec}, + './instance.js': {Instance: FakeInstance}, + './instance-config.js': {InstanceConfig: FakeInstanceConfig}, + './v1': fakeV1, + }).Spanner; + }); + + beforeEach(async () => { + sandbox = sinon.createSandbox(); + fakeGapicClient = util.noop; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (fakeGapicClient as any).scopes = []; + fakeV1.DatabaseAdminClient = fakeGapicClient; + fakeV1.InstanceAdminClient = fakeGapicClient; + fakeV1.SpannerClient = fakeGapicClient; + fakeCodec.SpannerDate = util.noop; + fakeCodec.Int = util.noop; + await disableMetrics(sandbox); + spanner = new Spanner(OPTIONS); + spanner.projectId = OPTIONS.projectId; + replaceProjectIdTokenOverride = null; + }); + + afterEach(() => sandbox.restore()); + + describe('instantiation', () => { + const EXPECTED_OPTIONS = extend({}, OPTIONS, { + libName: 'gccl', + libVersion: require('../../package.json').version, + scopes: [], + grpc, + 'grpc.keepalive_time_ms': 120000, + 'grpc.callInvocationTransformer': + fakeGrpcGcp().gcpCallInvocationTransformer, + 'grpc.channelFactoryOverride': fakeGrpcGcp().gcpChannelFactoryOverride, + 'grpc.gcpApiConfig': { + calledWith_: apiConfig, + }, + }); + + it('should localize a cached gapic client map', () => { + assert(spanner.clients_ instanceof Map); + assert.strictEqual(spanner.clients_.size, 0); + }); + + it('should localize an instance map', () => { + assert(spanner.instances_ instanceof Map); + assert.strictEqual(spanner.instances_.size, 0); + }); + + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should create an auth instance from google-auth-library', () => { + assert.deepStrictEqual( + getFake(spanner.auth).calledWith_[0], + EXPECTED_OPTIONS, + ); + }); + + it('should combine and uniquify all gapic client scopes', () => { + const expectedScopes = ['a', 'b', 'c']; + fakeV1.DatabaseAdminClient.scopes = ['a', 'c']; + fakeV1.InstanceAdminClient.scopes = ['a', 'b']; + fakeV1.SpannerClient.scopes = ['a', 'b', 'c']; + + const spanner = new Spanner(OPTIONS); + + const expectedOptions = extend({}, EXPECTED_OPTIONS, { + scopes: expectedScopes, + }); + + assert.deepStrictEqual( + getFake(spanner.auth).calledWith_[0], + expectedOptions, + ); + }); + + it('should override grpc settings', () => { + const keepaliveOptions = { + 'grpc.keepalive_time_ms': 300, + 'grpc.keepalive_timeout_ms': 100, + }; + const options = extend({}, OPTIONS, keepaliveOptions); + const spanner = new Spanner(options); + const expectedOptions = Object.assign( + {}, + EXPECTED_OPTIONS, + keepaliveOptions, + ); + assert.deepStrictEqual( + getFake(spanner.auth).calledWith_[0], + expectedOptions, + ); + }); + + it('should inherit from GrpcService', () => { + assert(spanner instanceof FakeGrpcService); + + const config = getFake(spanner).calledWith_[0]; + const options = getFake(spanner).calledWith_[1]; + + assert.deepStrictEqual(config, { + baseUrl: 'spanner.googleapis.com', + protosDir: path.resolve(__dirname, '../protos'), + protoServices: { + Operations: { + path: 'google/longrunning/operations.proto', + service: 'longrunning', + }, + }, + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + packageJson: require('../../package.json'), + }); + + assert.deepStrictEqual(options, EXPECTED_OPTIONS); + }); + + it('should optionally accept a servicePath', () => { + const SERVICE_PATH = 'abc.def.ghi'; + const spanner = new Spanner({servicePath: SERVICE_PATH}); + + const config = getFake(spanner).calledWith_[0]; + + assert.strictEqual(config.baseUrl, SERVICE_PATH); + }); + + it('should optionally accept routeToLeaderEnabled', () => { + const spanner = new Spanner({routeToLeaderEnabled: false}); + assert.strictEqual(spanner.routeToLeaderEnabled, false); + }); + + it('should configure metrics if project Id is not passed', async () => { + await enableMetrics(sandbox); + const spanner = new Spanner(); + assert.strictEqual(MetricsTracerFactory.enabled, true); + await disableMetrics(sandbox); + }); + + it('should optionally accept disableBuiltInMetrics', () => { + const spanner = new Spanner({disableBuiltInMetrics: true}); + assert.strictEqual(MetricsTracerFactory.enabled, false); + MetricsTracerFactory.enabled = true; // Reset for other tests. + }); + + it('should optionally accept directedReadOptions', () => { + const fakeDirectedReadOptions = { + includeReplicas: { + replicaSelections: [ + { + location: 'us-west1', + type: protos.google.spanner.v1.DirectedReadOptions + .ReplicaSelection.Type.READ_ONLY, + }, + ], + autoFailoverDisabled: true, + }, + }; + + const spanner = new Spanner({ + directedReadOptions: fakeDirectedReadOptions, + }); + assert.strictEqual(spanner.directedReadOptions, fakeDirectedReadOptions); + }); + + it('should optionally accept defaultTransactionOptions', () => { + const fakeDefaultTxnOptions = { + defaultTransactionOptions: { + isolationLevel: IsolationLevel.REPEATABLE_READ, + readLockMode: ReadLockMode.PESSIMISTIC, + }, + }; + + const spanner = new Spanner(fakeDefaultTxnOptions); + assert.strictEqual( + spanner.defaultTransactionOptions, + fakeDefaultTxnOptions.defaultTransactionOptions, + ); + }); + + it('should set projectFormattedName_', () => { + assert.strictEqual( + spanner.projectFormattedName_, + `projects/${spanner.projectId}`, + ); + }); + + it('should set the commonHeaders_', () => { + assert.deepStrictEqual(spanner.commonHeaders_, { + [CLOUD_RESOURCE_HEADER]: spanner.projectFormattedName_, + [AFE_SERVER_TIMING_HEADER]: 'true', + }); + }); + + describe('SPANNER_EMULATOR_HOST', () => { + let currentEmulator: string | undefined; + + beforeEach(() => (currentEmulator = process.env.SPANNER_EMULATOR_HOST)); + + afterEach(() => { + if (currentEmulator) { + process.env.SPANNER_EMULATOR_HOST = currentEmulator; + } else { + delete process.env.SPANNER_EMULATOR_HOST; + } + }); + + it('should parse emulator host without port correctly', () => { + const EMULATOR_HOST = 'somehost.local'; + process.env.SPANNER_EMULATOR_HOST = `${EMULATOR_HOST}`; + + const emulator = Spanner.getSpannerEmulatorHost(); + + assert.deepStrictEqual(emulator, {endpoint: EMULATOR_HOST}); + }); + + it('should parse emulator host with port correctly', () => { + const EMULATOR_HOST = 'somehost.local'; + const EMULATOR_PORT = 1610; + process.env.SPANNER_EMULATOR_HOST = `${EMULATOR_HOST}:${EMULATOR_PORT}`; + + const emulator = Spanner.getSpannerEmulatorHost(); + + assert.deepStrictEqual(emulator, { + endpoint: EMULATOR_HOST, + port: EMULATOR_PORT, + }); + }); + + it('should reject emulator host with protocol', () => { + try { + const EMULATOR_HOST = 'https://somehost.local:1234'; + process.env.SPANNER_EMULATOR_HOST = `${EMULATOR_HOST}`; + Spanner.getSpannerEmulatorHost(); + assert.fail('Missing expected error'); + } catch (e) { + assert.strictEqual( + (e as Error).message, + 'SPANNER_EMULATOR_HOST must not start with a protocol specification (http/https)', + ); + } + }); + + it('should reject emulator host with invalid port number', () => { + try { + const EMULATOR_HOST = 'somehost.local:not_a_port'; + process.env.SPANNER_EMULATOR_HOST = `${EMULATOR_HOST}`; + Spanner.getSpannerEmulatorHost(); + assert.fail('Missing expected error'); + } catch (e) { + assert.strictEqual( + (e as Error).message, + 'Invalid port number: not_a_port', + ); + } + }); + + it('should use SPANNER_EMULATOR_HOST', () => { + const EMULATOR_HOST = 'somehost.local'; + const EMULATOR_PORT = 1610; + process.env.SPANNER_EMULATOR_HOST = `${EMULATOR_HOST}:${EMULATOR_PORT}`; + const spanner = new Spanner(); + + const config = getFake(spanner).calledWith_[0]; + const options = getFake(spanner).calledWith_[1]; + + assert.strictEqual(config.baseUrl, EMULATOR_HOST); + assert.strictEqual(options.port, EMULATOR_PORT); + }); + }); + }); + + describe('TPC tests', () => { + const UNIVERSE_DOMAIN_CONSTANT = 'fake-universe-domain'; + + it('should have default universe domain set to `googleapis.com`', () => { + try { + const spanner = new Spanner(); + // get default universe domain from spanner object when + // neither of univserDomain and universe_domain are set + // nor env GOOGLE_CLOUD_UNIVERSE_DOMAIN is set + assert.strictEqual(spanner.universeDomain, 'googleapis.com'); + // GoogleAuthOption's univserseDomain property must be undefined here + // as it will get configure to default value in the gax library + // please see: https://github.com/googleapis/gax-nodejs/blob/de43edd3524b7f995bd3cf5c34ddead03828b546/gax/src/grpc.ts#L431 + assert.strictEqual(spanner.options.universeDomain, undefined); + } catch (err) { + assert.ifError(err); + } + }); + + it('should optionally accept universeDomain', () => { + const fakeOption = { + universeDomain: UNIVERSE_DOMAIN_CONSTANT, + }; + + try { + const spanner = new Spanner(fakeOption); + // get universe domain from spanner object + assert.strictEqual(spanner.universeDomain, fakeOption.universeDomain); + // GoogleAuthOption's univserseDomain property must be set + // to match it with the universe from Auth Client + assert.strictEqual( + spanner.options.universeDomain, + fakeOption.universeDomain, + ); + } catch (err) { + assert.ifError(err); + } + }); + + it('should optionally accept universe_domain', () => { + const fakeOption = { + universe_domain: UNIVERSE_DOMAIN_CONSTANT, + }; + + try { + const spanner = new Spanner(fakeOption); + // get universe domain from spanner object + assert.strictEqual(spanner.universeDomain, fakeOption.universe_domain); + // GoogleAuthOption's univserseDomain property must be set + // to match it with the universe from Auth Client + assert.strictEqual( + spanner.options.universeDomain, + fakeOption.universe_domain, + ); + } catch (err) { + assert.ifError(err); + } + }); + + it('should set universe domain upon setting env GOOGLE_CLOUD_UNIVERSE_DOMAIN', () => { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = UNIVERSE_DOMAIN_CONSTANT; + + try { + const spanner = new Spanner(); + // get universe domain from spanner object + assert.strictEqual(spanner.universeDomain, UNIVERSE_DOMAIN_CONSTANT); + // GoogleAuthOption's univserseDomain property must be set + // to match it with the universe from Auth Client + assert.strictEqual( + spanner.options.universeDomain, + UNIVERSE_DOMAIN_CONSTANT, + ); + } catch (err) { + assert.ifError(err); + } + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + }); + + it('should throw an error if universe_domain and universeDomain both are set to different values', () => { + const fakeOption = { + universeDomain: 'fake-universe-domain-1', + universe_domain: 'fake-universe-domain-2', + }; + const fakeError = new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + + try { + const spanner = new Spanner(fakeOption); + // this line should never reach client must throw an error. + throw new Error('should never reach this line'); + } catch (err) { + assert.deepStrictEqual(err, fakeError); + } + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + }); + }); + + describe('date', () => { + it('should create a default SpannerDate instance', () => { + const customValue = {}; + + fakeCodec.SpannerDate = class { + constructor() { + return customValue; + } + }; + + const date = Spanner.date(); + assert.strictEqual(date, customValue); + }); + + it('should create a SpannerDate instance', () => { + const value = '1999-1-1'; + const customValue = {}; + + fakeCodec.SpannerDate = class { + constructor(value_) { + assert.strictEqual(value_, value); + return customValue; + } + }; + + const date = Spanner.date(value); + assert.strictEqual(date, customValue); + }); + + it('should create a SpannerDate instance from year/month/day', () => { + const year = 1999; + const month = 1; + const day = 1; + const customValue = {}; + + fakeCodec.SpannerDate = class { + constructor(year_, month_, day_) { + assert.strictEqual(year_, year); + assert.strictEqual(month_, month); + assert.strictEqual(day_, day); + return customValue; + } + }; + + const date = Spanner.date(year, month, day); + assert.strictEqual(date, customValue); + }); + + it('should create a SpannerDate instance in year 0', () => { + const year = 0; + const month = 1; + const day = 1; + const customValue = {}; + + fakeCodec.SpannerDate = class { + constructor(year_, month_, day_) { + assert.strictEqual(year_, year); + assert.strictEqual(month_, month); + assert.strictEqual(day_, day); + return customValue; + } + }; + + const date = Spanner.date(year, month, day); + assert.strictEqual(date, customValue); + }); + }); + + describe('timestamp', () => { + it('should create a PreciseDate instance', () => { + const date = Spanner.timestamp(); + assert(date instanceof PreciseDate); + }); + + it('should return same instance if a PreciseData was given', () => { + const timestamp = new PreciseDate('2019-02-08T10:34:29.481145231Z'); + const converted_timestamp = Spanner.timestamp(timestamp); + assert(timestamp instanceof PreciseDate); + assert.deepStrictEqual(converted_timestamp, timestamp); + }); + }); + + describe('float', () => { + it('should create a Float instance', () => { + const value = {}; + const customValue = {}; + + fakeCodec.Float = class { + constructor(value_) { + assert.strictEqual(value_, value); + return customValue; + } + }; + + const float = Spanner.float(value); + assert.strictEqual(float, customValue); + }); + }); + + describe('float32', () => { + it('should create a Float32 instance', () => { + const value = {}; + const customValue = {}; + + fakeCodec.Float32 = class { + constructor(value_) { + assert.strictEqual(value_, value); + return customValue; + } + }; + + const float32 = Spanner.float32(value); + assert.strictEqual(float32, customValue); + }); + }); + + describe('int', () => { + it('should create an Int instance', () => { + const value = {}; + const customValue = {}; + + fakeCodec.Int = class { + constructor(value_) { + assert.strictEqual(value_, value); + return customValue; + } + }; + + const int = Spanner.int(value); + assert.strictEqual(int, customValue); + }); + }); + + describe('struct', () => { + it('should create a struct from JSON', () => { + const json = {}; + const fakeStruct = []; + fakeCodec.Struct = { + fromJSON(value) { + assert.strictEqual(value, json); + return fakeStruct; + }, + }; + const struct = Spanner.struct(json); + assert.strictEqual(struct, fakeStruct); + }); + + it('should create a struct from an Array', () => { + const arr = []; + const fakeStruct = []; + + fakeCodec.Struct = { + fromArray(value) { + assert.strictEqual(value, arr); + return fakeStruct; + }, + }; + + const struct = Spanner.struct(arr); + + assert.strictEqual(struct, fakeStruct); + }); + }); + + describe('numeric', () => { + it('should create a Numeric instance', () => { + const value = '3.145'; + const customValue = {value: '3.145'}; + + fakeCodec.Numeric = class { + constructor(value_) { + assert.strictEqual(value_, value); + return customValue; + } + }; + + const numeric = Spanner.numeric(value); + assert.strictEqual(numeric, customValue); + }); + }); + + describe('pgNumeric', () => { + it('should create a PGNumeric instance', () => { + const value = '3.145'; + const customValue = {value: '3.145'}; + + fakeCodec.PGNumeric = class { + constructor(value_) { + assert.strictEqual(value_, value); + return customValue; + } + }; + + const pgNumeric = Spanner.pgNumeric(value); + assert.strictEqual(pgNumeric, customValue); + }); + }); + + describe('jsonb', () => { + it('should create a PGJsonb instance', () => { + const value = { + key1: 'value1', + key2: 'value2', + }; + const customValue = { + value: { + key1: 'value1', + key2: 'value2', + }, + }; + + fakeCodec.PGJsonb = class { + constructor(value_) { + assert.strictEqual(value_, value); + return customValue; + } + }; + + const pgJsonb = Spanner.pgJsonb(value); + assert.strictEqual(pgJsonb, customValue); + }); + }); + + describe('interval', () => { + it('should create an Interval instance', () => { + const months = 18; + const days = -25; + const nanos = BigInt('1234567891234'); + const customValue = {}; + + fakeCodec.Interval = class { + constructor(months_, days_, nanoseconds_) { + assert.strictEqual(months_, months); + assert.strictEqual(days_, days); + assert.strictEqual(nanoseconds_, nanos); + return customValue; + } + }; + + const interval = Spanner.interval(months, days, nanos); + assert.strictEqual(interval, customValue); + }); + }); + + describe('protoMessage', () => { + it('should create a ProtoMessage instance', () => { + const protoMessageParams = { + value: music.SingerInfo.create({ + singerId: 2, + genre: music.Genre.POP, + birthDate: 'January', + }), + messageFunction: music.SingerInfo, + fullName: 'examples.spanner.music.SingerInfo', + }; + + const customValue = { + value: { + singerId: 2, + genre: music.Genre.POP, + birthDate: 'January', + }, + messageFunction: music.SingerInfo, + fullName: 'examples.spanner.music.SingerInfo', + }; + + fakeCodec.ProtoMessage = class { + constructor(value_) { + assert.strictEqual(value_, protoMessageParams); + return customValue; + } + }; + + const protoMessage = Spanner.protoMessage(protoMessageParams); + assert.strictEqual(protoMessage, customValue); + }); + }); + + describe('protoEnum', () => { + it('should create a ProtoEnum instance', () => { + const enumParams = { + value: music.Genre.JAZZ, + enumObject: music.Genre, + fullName: 'examples.spanner.music.Genre', + }; + + const customValue = { + value: music.Genre.JAZZ, + enumObject: music.Genre, + fullName: 'examples.spanner.music.Genre', + }; + + fakeCodec.ProtoEnum = class { + constructor(value_) { + assert.strictEqual(value_, enumParams); + return customValue; + } + }; + + const protoEnum = Spanner.protoEnum(enumParams); + assert.strictEqual(protoEnum, customValue); + }); + }); + + describe('createInstance', () => { + const NAME = 'instance-name'; + let PATH; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const CONFIG: any = { + config: 'b', + }; + const ORIGINAL_CONFIG = extend({}, CONFIG); + + beforeEach(() => { + PATH = 'projects/' + spanner.projectId + '/instances/' + NAME; + spanner.request = util.noop; + }); + + it('should throw if a name is not provided', () => { + assert.throws(() => { + void spanner.createInstance(null!, {} as CreateInstanceRequest); + }, /A name is required to create an instance\./); + }); + + it('should throw if a config object is not provided', () => { + assert.throws(() => { + void spanner.createInstance(NAME, null!); + }, /A configuration object is required to create an instance\./); + }); + + it('should set the correct defaults on the request', done => { + const stub = sandbox.stub(FakeInstance, 'formatName_').returns(PATH); + + spanner.request = config => { + const [projectId, name] = stub.lastCall.args; + assert.strictEqual(projectId, spanner.projectId); + assert.strictEqual(name, NAME); + + assert.deepStrictEqual(CONFIG, ORIGINAL_CONFIG); + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'createInstance'); + + const reqOpts = config.reqOpts; + assert.deepStrictEqual(reqOpts, { + parent: 'projects/' + spanner.projectId, + instanceId: NAME, + instance: { + name: PATH, + displayName: NAME, + nodeCount: 1, + processingUnits: undefined, + config: `projects/project-id/instanceConfigs/${CONFIG.config}`, + }, + }); + assert.strictEqual(config.gaxOpts, undefined); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + done(); + }; + spanner.createInstance(NAME, CONFIG, assert.ifError); + }); + + it('should accept a path', () => { + const stub = sandbox.stub(FakeInstance, 'formatName_').callThrough(); + spanner.createInstance(PATH, CONFIG, assert.ifError); + + const [, name] = stub.lastCall.args; + assert.strictEqual(name, PATH); + }); + + it('should accept the displayName', done => { + const displayName = 'my-instance'; + const config = Object.assign({}, CONFIG, {displayName}); + + spanner.request = config => { + assert.strictEqual(config.reqOpts.instance.displayName, displayName); + done(); + }; + + spanner.createInstance(NAME, config, assert.ifError); + }); + + it('should accept the edition', done => { + const edition = + protos.google.spanner.admin.instance.v1.Instance.Edition.STANDARD; + const config = Object.assign({}, CONFIG, {edition}); + + spanner.request = config => { + assert.strictEqual(config.reqOpts.instance.edition, edition); + done(); + }; + + spanner.createInstance(NAME, config, assert.ifError); + }); + + it('should create an instance with processing units', done => { + const processingUnits = 500; + const config = Object.assign({}, CONFIG, {processingUnits}); + + spanner.request = config => { + assert.strictEqual( + config.reqOpts.instance.processingUnits, + processingUnits, + ); + assert.strictEqual(config.reqOpts.instance.nodeCount, undefined); + done(); + }; + + spanner.createInstance(NAME, config, assert.ifError); + }); + + it('should throw if both nodes and processingUnits are given', () => { + const nodeCount = 1; + const processingUnits = 500; + const config = Object.assign({}, CONFIG, {nodeCount, processingUnits}); + + assert.throws(() => { + void spanner.createInstance(NAME, config); + }, /Only one of nodeCount or processingUnits can be specified\./); + }); + + it('should accept gaxOptions', done => { + const cfg = Object.assign({}, CONFIG, {gaxOptions: {}}); + spanner.request = config => { + assert.strictEqual(config.gaxOpts, cfg.gaxOptions); + done(); + }; + spanner.createInstance(NAME, cfg, assert.ifError); + }); + + describe('config.nodes', () => { + it('should rename to nodeCount', () => { + const config = extend({}, CONFIG, {nodes: 10}); + const stub = sandbox.stub(spanner, 'request'); + spanner.createInstance(NAME, config, assert.ifError); + + const [config_] = stub.lastCall.args; + const reqOpts = config_.reqOpts; + assert.strictEqual(reqOpts.instance.nodeCount, config.nodes); + assert.strictEqual(reqOpts.instance.nodes, undefined); + }); + }); + + describe('config.config', () => { + it('should format a name', done => { + const name = 'config-name'; + const config = extend({}, CONFIG, {config: name}); + const originalConfig = extend({}, config); + spanner.request = config_ => { + assert.deepStrictEqual(config, originalConfig); + const reqOpts = config_.reqOpts; + assert.strictEqual( + reqOpts.instance.config, + 'projects/' + spanner.projectId + '/instanceConfigs/' + name, + ); + done(); + }; + spanner.createInstance(NAME, config, assert.ifError); + }); + }); + + describe('error', () => { + const ERROR = new Error('Error.'); + const API_RESPONSE = {}; + + beforeEach(() => { + spanner.request = (config, callback) => { + callback(ERROR, null, API_RESPONSE); + }; + }); + + it('should execute callback with error & API response', done => { + spanner.createInstance(NAME, CONFIG, (err, instance, op, resp) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(instance, null); + assert.strictEqual(op, null); + assert.strictEqual(resp, API_RESPONSE); + done(); + }); + }); + }); + + describe('success', () => { + const OPERATION = {}; + const API_RESPONSE = {}; + + beforeEach(() => { + spanner.request = (config, callback) => { + callback(null, OPERATION, API_RESPONSE); + }; + }); + + it('should create an Instance and return an Operation', done => { + const formattedName = 'formatted-name'; + sandbox.stub(FakeInstance, 'formatName_').returns(formattedName); + const fakeInstanceInstance = {} as spnr.Instance; + const instanceStub = sandbox + .stub(spanner, 'instance') + .returns(fakeInstanceInstance); + + spanner.createInstance(NAME, CONFIG, (err, instance, op, resp) => { + assert.ifError(err); + const [instanceName] = instanceStub.lastCall.args; + assert.strictEqual(instanceName, formattedName); + assert.strictEqual(instance, fakeInstanceInstance); + assert.strictEqual(op, OPERATION); + assert.strictEqual(resp, API_RESPONSE); + done(); + }); + }); + }); + }); + + describe('getInstances', () => { + const OPTIONS: GetInstancesOptions = { + filter: 'b', + }; + const ORIGINAL_OPTIONS = extend({}, OPTIONS); + + beforeEach(() => { + spanner.request = util.noop; + }); + + it('should make the correct request', done => { + const expectedReqOpts = extend({}, OPTIONS, { + parent: 'projects/' + spanner.projectId, + }); + + spanner.request = config => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'listInstances'); + + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.reqOpts, OPTIONS); + assert.deepStrictEqual(OPTIONS, ORIGINAL_OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + done(); + }; + + spanner.getInstances(OPTIONS as GetInstancesOptions, assert.ifError); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const options = Object.assign({}, OPTIONS, {gaxOptions}); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: 'projects/' + spanner.projectId, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + const expectedGaxOpts = {timeout: 1000}; + + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + done(); + }; + + spanner.getInstances(options, assert.ifError); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = Object.assign({}, OPTIONS, { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: 'projects/' + spanner.projectId, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + + const expectedGaxOpts = {timeout: 1000}; + + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + done(); + }; + + spanner.getInstances(options, assert.ifError); + }); + + it('should not require options', done => { + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: 'projects/' + spanner.projectId, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + + done(); + }; + + spanner.getInstances(assert.ifError); + }); + + describe('error', () => { + const GAX_RESPONSE_ARGS = [new Error('Error.'), null, null, {}]; + + beforeEach(() => { + spanner.request = (config, callback) => { + callback(...GAX_RESPONSE_ARGS); + }; + }); + + it('should execute callback with original arguments', done => { + spanner.getInstances(OPTIONS as GetInstancesOptions, (...args) => { + assert.deepStrictEqual(args, GAX_RESPONSE_ARGS); + done(); + }); + }); + }); + + describe('success', () => { + const INSTANCES = [ + { + name: 'instance-name', + }, + ]; + + const GAX_RESPONSE_ARGS = [null, INSTANCES, null, {}]; + + beforeEach(() => { + spanner.request = (config, callback) => { + callback(...GAX_RESPONSE_ARGS); + }; + }); + + it('should create and return Instance objects', done => { + const fakeInstanceInstance = {} as spnr.Instance; + + spanner.instance = name => { + assert.strictEqual(name, INSTANCES[0].name); + return fakeInstanceInstance; + }; + + spanner.getInstances(OPTIONS as GetInstancesOptions, (...args) => { + assert.ifError(args[0]); + assert.strictEqual(args[0], GAX_RESPONSE_ARGS[0]); + const instance = args[1]!.pop(); + assert.strictEqual(instance, fakeInstanceInstance); + assert.strictEqual(instance!.metadata, GAX_RESPONSE_ARGS[1]![0]); + assert.strictEqual(args[2], GAX_RESPONSE_ARGS[2]); + assert.strictEqual(args[3], GAX_RESPONSE_ARGS[3]); + done(); + }); + }); + + it('should return a complete nextQuery object', done => { + const pageSize = 1; + const filter = 'filter'; + const NEXTPAGEREQUEST = { + parent: 'projects/' + spanner.projectId, + pageSize, + filter, + pageToken: 'pageToken', + }; + const GAX_RESPONSE_ARGS = [null, [], NEXTPAGEREQUEST, {}]; + + const GETINSTANCESOPTIONS = { + pageSize, + filter, + gaxOptions: {timeout: 1000, autoPaginate: false}, + }; + const EXPECTEDNEXTQUERY = extend( + {}, + GETINSTANCESOPTIONS, + NEXTPAGEREQUEST, + ); + spanner.request = (config, callback) => { + callback(...GAX_RESPONSE_ARGS); + }; + function callback(err, instances, nextQuery) { + assert.deepStrictEqual(nextQuery, EXPECTEDNEXTQUERY); + done(); + } + spanner.getInstances(GETINSTANCESOPTIONS, callback); + }); + }); + }); + + describe('getInstancesStream', () => { + const OPTIONS: GetInstancesOptions = { + filter: 'b', + }; + const ORIGINAL_OPTIONS = extend({}, OPTIONS); + const returnValue = {}; + + it('should make and return the correct gax API call', () => { + const expectedReqOpts = extend({}, OPTIONS, { + parent: 'projects/' + spanner.projectId, + }); + + spanner.requestStream = config => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'listInstancesStream'); + + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.reqOpts, OPTIONS); + assert.deepStrictEqual(OPTIONS, ORIGINAL_OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + return returnValue as Duplex; + }; + + const returnedValue = spanner.getInstancesStream(OPTIONS); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const options = {gaxOptions}; + const expectedReqOpts = extend( + {}, + { + parent: 'projects/' + spanner.projectId, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + const expectedGaxOpts = {timeout: 1000}; + + spanner.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + return returnValue; + }; + + const returnedValue = spanner.getInstancesStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }; + const expectedReqOpts = extend( + {}, + { + parent: 'projects/' + spanner.projectId, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + const expectedGaxOpts = {timeout: 1000}; + + spanner.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + return returnValue; + }; + + const returnedValue = spanner.getInstancesStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should not require options', () => { + spanner.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: 'projects/' + spanner.projectId, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + + return returnValue; + }; + + const returnedValue = spanner.getInstancesStream(); + assert.strictEqual(returnedValue, returnValue); + }); + }); + + describe('createInstanceConfig', () => { + const NAME = 'instance-config-name'; + let PATH; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const CONFIG: any = { + baseConfig: 'x', + }; + const ORIGINAL_CONFIG = extend({}, CONFIG); + + beforeEach(() => { + PATH = 'projects/' + spanner.projectId + '/instanceConfigs/' + NAME; + spanner.request = util.noop; + }); + + it('should throw if a name is not provided', () => { + assert.throws(() => { + void spanner.createInstanceConfig( + null!, + {} as CreateInstanceConfigRequest, + ); + }, /A name is required to create an instance config\./); + }); + + it('should throw if a config object is not provided', () => { + assert.throws(() => { + void spanner.createInstanceConfig(NAME, null!); + }, /A configuration object is required to create an instance config\./); + }); + + it('should throw if the provided config object does not have baseConfig', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const {baseConfig, ...CONFIG_WITHOUT_BASE_CONFIG} = ORIGINAL_CONFIG; + assert.throws(() => { + void spanner.createInstanceConfig(NAME, CONFIG_WITHOUT_BASE_CONFIG!); + }, /Base instance config is required to create an instance config\./); + }); + + it('should set the correct defaults on the request', done => { + const stub = sandbox + .stub(FakeInstanceConfig, 'formatName_') + .returns(PATH); + + spanner.request = config => { + const [projectId, name] = stub.lastCall.args; + assert.strictEqual(projectId, spanner.projectId); + assert.strictEqual(name, NAME); + + assert.deepStrictEqual(CONFIG, ORIGINAL_CONFIG); + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'createInstanceConfig'); + + const reqOpts = config.reqOpts; + assert.deepStrictEqual(reqOpts, { + parent: 'projects/' + spanner.projectId, + instanceConfigId: NAME, + instanceConfig: { + name: PATH, + displayName: NAME, + baseConfig: `projects/project-id/instanceConfigs/${CONFIG.baseConfig}`, + }, + }); + assert.strictEqual(config.gaxOpts, undefined); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + done(); + }; + spanner.createInstanceConfig(NAME, CONFIG, assert.ifError); + }); + + it('should accept a path', () => { + const stub = sandbox + .stub(FakeInstanceConfig, 'formatName_') + .callThrough(); + spanner.createInstanceConfig(PATH, CONFIG, assert.ifError); + + const [, name] = stub.lastCall.args; + assert.strictEqual(name, PATH); + }); + + it('should accept the displayName', done => { + const displayName = 'my-instance-config-display-name'; + const config = Object.assign({}, CONFIG, {displayName}); + + spanner.request = config => { + assert.strictEqual( + config.reqOpts.instanceConfig.displayName, + displayName, + ); + done(); + }; + + spanner.createInstanceConfig(NAME, config, assert.ifError); + }); + + it('should accept gaxOptions', done => { + const cfg = Object.assign({}, CONFIG, {gaxOptions: {}}); + spanner.request = config => { + assert.strictEqual(config.gaxOpts, cfg.gaxOptions); + done(); + }; + spanner.createInstanceConfig(NAME, cfg, assert.ifError); + }); + + describe('error', () => { + const ERROR = new Error('Error.'); + const API_RESPONSE = {}; + + beforeEach(() => { + spanner.request = (config, callback) => { + callback(ERROR, null, API_RESPONSE); + }; + }); + + it('should execute callback with error & API response', done => { + spanner.createInstanceConfig( + NAME, + CONFIG, + (err, instance, op, resp) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(instance, null); + assert.strictEqual(op, null); + assert.strictEqual(resp, API_RESPONSE); + done(); + }, + ); + }); + }); + + describe('success', () => { + const OPERATION = {}; + const API_RESPONSE = {}; + + beforeEach(() => { + spanner.request = (config, callback) => { + callback(null, OPERATION, API_RESPONSE); + }; + }); + + it('should create an Instance and return an Operation', done => { + const formattedName = 'formatted-name'; + sandbox.stub(FakeInstanceConfig, 'formatName_').returns(formattedName); + const fakeInstanceConfigInstanceConfig = {} as spnr.InstanceConfig; + const instanceStub = sandbox + .stub(spanner, 'instanceConfig') + .returns(fakeInstanceConfigInstanceConfig); + + spanner.createInstanceConfig( + NAME, + CONFIG, + (err, instance, op, resp) => { + assert.ifError(err); + const [instanceConfigName] = instanceStub.lastCall.args; + assert.strictEqual(instanceConfigName, formattedName); + assert.strictEqual(instance, fakeInstanceConfigInstanceConfig); + assert.strictEqual(op, OPERATION); + assert.strictEqual(resp, API_RESPONSE); + done(); + }, + ); + }); + }); + }); + + describe('getInstanceConfigs', () => { + beforeEach(() => { + spanner.request = util.noop; + }); + + it('should make and return the correct request', () => { + const options: GetInstanceConfigsOptions = { + pageSize: 5, + gaxOptions: {autoPaginate: false}, + }; + const expectedQuery = extend({}, options, { + parent: 'projects/' + spanner.projectId, + }); + delete expectedQuery.gaxOptions; + + function callback() {} + + const returnValue = {}; + + spanner.request = config => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'listInstanceConfigs'); + + const reqOpts = config.reqOpts; + assert.deepStrictEqual(reqOpts, expectedQuery); + assert.notStrictEqual(reqOpts, options); + + const gaxOpts = config.gaxOpts; + assert.deepStrictEqual(gaxOpts, options.gaxOptions); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + return returnValue; + }; + + const returnedValue = spanner.getInstanceConfigs(options, callback); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const options = Object.assign({}, OPTIONS, {gaxOptions}); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: 'projects/' + spanner.projectId, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + const expectedGaxOpts = {timeout: 1000}; + + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + done(); + }; + + spanner.getInstanceConfigs(options, assert.ifError); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = Object.assign({}, OPTIONS, { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: 'projects/' + spanner.projectId, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + const expectedGaxOpts = {timeout: 1000}; + + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + done(); + }; + + spanner.getInstanceConfigs(options, assert.ifError); + }); + + it('should not require options', done => { + spanner.request = config => { + const reqOpts = config.reqOpts; + assert.deepStrictEqual(reqOpts, { + parent: 'projects/' + spanner.projectId, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + + done(); + }; + + spanner.getInstanceConfigs(assert.ifError); + }); + + it('should return a complete nextQuery object', done => { + const pageSize = 1; + const filter = 'filter'; + const NEXTPAGEREQUEST = { + parent: 'projects/' + spanner.projectId, + pageSize, + filter, + pageToken: 'pageToken', + }; + const RESPONSE = [null, [], NEXTPAGEREQUEST, {}]; + + const GETINSTANCECONFIGSOPTIONS = { + pageSize, + filter, + gaxOptions: {timeout: 1000, autoPaginate: false}, + }; + const EXPECTEDNEXTQUERY = extend( + {}, + GETINSTANCECONFIGSOPTIONS, + NEXTPAGEREQUEST, + ); + spanner.request = (config, callback) => { + callback(...RESPONSE); + }; + function callback(err, instanceConfigs, nextQuery) { + assert.deepStrictEqual(nextQuery, EXPECTEDNEXTQUERY); + done(); + } + spanner.getInstanceConfigs(GETINSTANCECONFIGSOPTIONS, callback); + }); + }); + + describe('getInstanceConfigOperations', () => { + const OPTIONS = { + a: 'b', + } as spnr.GetInstanceConfigOperationsOptions; + const ORIGINAL_OPTIONS = extend({}, OPTIONS); + + it('should make the correct request', done => { + const gaxOpts = { + timeout: 1000, + }; + const options = {a: 'b', gaxOptions: gaxOpts}; + + const expectedReqOpts = extend({}, OPTIONS, { + parent: spanner.projectFormattedName_, + }); + + spanner.request = config => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'listInstanceConfigOperations'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, OPTIONS); + assert.deepStrictEqual(OPTIONS, ORIGINAL_OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, options.gaxOptions); + done(); + }; + + spanner.getInstanceConfigOperations(options, assert.ifError); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options = Object.assign({}, OPTIONS, {gaxOptions}); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: spanner.projectFormattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + spanner.getInstanceConfigOperations(options, assert.ifError); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = Object.assign({}, OPTIONS, { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: spanner.projectFormattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + spanner.getInstanceConfigOperations(options, assert.ifError); + }); + + it('should not require options', done => { + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: spanner.projectFormattedName_, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + done(); + }; + + spanner.getInstanceConfigOperations(assert.ifError); + }); + + it('should return a complete nextQuery object', done => { + const pageSize = 1; + const filter = 'filter'; + const NEXT_PAGE_REQUEST = { + parent: spanner.projectFormattedName_, + pageSize, + filter, + pageToken: 'pageToken', + }; + const RESPONSE = [null, [], NEXT_PAGE_REQUEST, {}]; + + const GET_INSTANCE_CONFIGS_OPERATIONS_OPTIONS = { + pageSize, + filter, + gaxOptions: {timeout: 1000, autoPaginate: false}, + }; + const EXPECTED_NEXT_QUERY = extend( + {}, + GET_INSTANCE_CONFIGS_OPERATIONS_OPTIONS, + NEXT_PAGE_REQUEST, + ); + spanner.request = (config, callback) => { + callback(...RESPONSE); + }; + function callback(err, instanceConfigOps, nextQuery) { + assert.deepStrictEqual(nextQuery, EXPECTED_NEXT_QUERY); + done(); + } + spanner.getInstanceConfigOperations( + GET_INSTANCE_CONFIGS_OPERATIONS_OPTIONS, + callback, + ); + }); + }); + + describe('getInstanceConfigsStream', () => { + beforeEach(() => { + spanner.requestStream = util.noop; + }); + + const OPTIONS = { + gaxOptions: {autoPaginate: false}, + }; + const returnValue = {}; + + it('should make and return the correct gax API call', () => { + const expectedOptions: {gaxOptions?: {}} = extend({}, OPTIONS, { + parent: 'projects/' + spanner.projectId, + }); + delete expectedOptions.gaxOptions; + const returnValue = {}; + + spanner.requestStream = config => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'listInstanceConfigsStream'); + + const reqOpts = config.reqOpts; + assert.deepStrictEqual(reqOpts, expectedOptions); + assert.notStrictEqual(reqOpts, OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, OPTIONS.gaxOptions); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + return returnValue; + }; + + const returnedValue = spanner.getInstanceConfigsStream( + OPTIONS as GetInstanceConfigsOptions, + ); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should not require options', () => { + const expectedOptions = { + parent: 'projects/' + spanner.projectId, + }; + const returnValue = {}; + + spanner.requestStream = config => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'listInstanceConfigsStream'); + + const reqOpts = config.reqOpts; + assert.deepStrictEqual(reqOpts, expectedOptions); + + assert.deepStrictEqual(config.gaxOpts, {}); + + return returnValue; + }; + const returnedValue = spanner.getInstanceConfigsStream(); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const options: {gaxOptions?: {}} = {gaxOptions}; + const expectedReqOpts = extend( + true, + {}, + options, + { + parent: 'projects/' + spanner.projectId, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + delete expectedReqOpts.gaxOptions; + const expectedGaxOpts = {timeout: 1000}; + + spanner.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + return returnValue; + }; + + const returnedValue = spanner.getInstanceConfigsStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = Object.assign( + {}, + { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }, + ); + const expectedReqOpts: {gaxOptions?: {}} = extend( + {}, + OPTIONS, + { + parent: 'projects/' + spanner.projectId, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + delete expectedReqOpts.gaxOptions; + const expectedGaxOpts = {timeout: 1000}; + + spanner.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + return returnValue; + }; + + const returnedValue = spanner.getInstanceConfigs(options, assert.ifError); + assert.strictEqual(returnedValue, returnValue); + }); + }); + + describe('getInstanceConfig', () => { + beforeEach(() => { + spanner.request = util.noop; + }); + + it('should make and return the correct request', () => { + const options: GetInstanceConfigOptions = { + gaxOptions: {timeout: 5}, + }; + const expectedReqOpts = { + name: `projects/${spanner.projectId}/instanceConfigs/nam1`, + }; + + function callback() {} + + const returnValue = {}; + + spanner.request = config => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'getInstanceConfig'); + + const reqOpts = config.reqOpts; + assert.deepStrictEqual(reqOpts, expectedReqOpts); + assert.notStrictEqual(reqOpts, options); + + const gaxOpts = config.gaxOpts; + assert.deepStrictEqual(gaxOpts, options.gaxOptions); + assert.deepStrictEqual(config.headers, spanner.commonHeaders_); + + return returnValue; + }; + + const returnedValue = spanner.getInstanceConfig( + 'nam1', + options, + callback, + ); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should not require options', done => { + spanner.request = config => { + const reqOpts = config.reqOpts; + assert.deepStrictEqual(reqOpts, { + name: `projects/${spanner.projectId}/instanceConfigs/nam1`, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + + done(); + }; + + spanner.getInstanceConfig('nam1', assert.ifError); + }); + }); + + describe('instance', () => { + const NAME = 'instance-name'; + + it('should throw if a name is not provided', () => { + assert.throws(() => { + spanner.instance(null!); + }, /A name is required to access an Instance object\./); + }); + + it('should create and cache an Instance', () => { + const cache = spanner.instances_; + assert.strictEqual(cache.has(NAME), false); + + const instance = spanner.instance(NAME)!; + assert(instance instanceof FakeInstance); + assert.strictEqual(getFake(instance).calledWith_[0], spanner); + assert.strictEqual(getFake(instance).calledWith_[1], NAME); + assert.strictEqual(instance, cache.get(NAME)); + }); + + it('should re-use cached objects', () => { + const cache = spanner.instances_; + const fakeInstance = {} as spnr.Instance; + cache.set(NAME, fakeInstance); + + const instance = spanner.instance(NAME); + assert.strictEqual(instance, fakeInstance); + }); + }); + + describe('instanceConfig', () => { + const NAME = 'instance-config-name'; + + it('should throw if a name is not provided', () => { + assert.throws(() => { + spanner.instanceConfig(null!); + }, /A name is required to access an InstanceConfig object\./); + }); + + it('should create and cache an InstanceConfig', () => { + const cache = spanner.instanceConfigs_; + assert.strictEqual(cache.has(NAME), false); + + const instanceConfig = spanner.instanceConfig(NAME)!; + assert(instanceConfig instanceof FakeInstanceConfig); + assert.strictEqual(getFake(instanceConfig).calledWith_[0], spanner); + assert.strictEqual(getFake(instanceConfig).calledWith_[1], NAME); + assert.strictEqual(instanceConfig, cache.get(NAME)); + }); + + it('should re-use cached objects', () => { + const cache = spanner.instanceConfigs_; + const fakeInstanceConfig = {} as spnr.InstanceConfig; + cache.set(NAME, fakeInstanceConfig); + + const instanceConfig = spanner.instanceConfig(NAME); + assert.strictEqual(instanceConfig, fakeInstanceConfig); + }); + }); + + describe('prepareGapicRequest_', () => { + const PROJECT_ID = 'project-id'; + const CONFIG = { + client: 'SpannerClient', + method: 'methodName', + reqOpts: { + a: 'b', + c: 'd', + }, + gaxOpts: {}, + headers: { + [CLOUD_RESOURCE_HEADER]: 'header', + }, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const FAKE_GAPIC_CLIENT: any = { + [CONFIG.method]: util.noop, + }; + + beforeEach(() => { + FAKE_GAPIC_CLIENT[CONFIG.method] = util.noop; + + asAny(spanner).auth.getProjectId = callback => { + callback(null, PROJECT_ID); + }; + + fakeV1[CONFIG.client] = class { + constructor() { + return FAKE_GAPIC_CLIENT; + } + }; + }); + + it('should get the project ID from google-auth-library', done => { + asAny(spanner).auth.getProjectId = () => { + done(); + }; + + spanner.prepareGapicRequest_(CONFIG, assert.ifError); + }); + + it('should return an error from google-auth-library', done => { + const error = new Error('Error.'); + + asAny(spanner).auth.getProjectId = callback => { + callback(error); + }; + + spanner.prepareGapicRequest_(CONFIG, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should be able to catch any error from google-gax-library', done => { + const error = new Error('Error.'); + + fakeV1[CONFIG.client] = class { + constructor(options) { + assert.strictEqual(options, spanner.options); + throw error; + } + }; + + spanner.prepareGapicRequest_(CONFIG, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should create and cache a gapic client', done => { + fakeV1[CONFIG.client] = class { + constructor(options) { + assert.strictEqual(options, spanner.options); + + setImmediate(() => { + const cachedClient = spanner.clients_.get(CONFIG.client); + assert.strictEqual(cachedClient, FAKE_GAPIC_CLIENT); + done(); + }); + + return FAKE_GAPIC_CLIENT; + } + }; + spanner.prepareGapicRequest_(CONFIG, assert.ifError); + }); + + it('should re-use a cached gapic client', () => { + fakeV1[CONFIG.client] = () => { + throw new Error('Should not have re-created client!'); + }; + spanner.clients_.set(CONFIG.client, FAKE_GAPIC_CLIENT); + spanner.prepareGapicRequest_(CONFIG, assert.ifError); + }); + + it('should replace project ID tokens within the reqOpts', done => { + const replacedReqOpts = {}; + + replaceProjectIdTokenOverride = (reqOpts, projectId) => { + if (typeof reqOpts === 'object') { + assert.deepStrictEqual(reqOpts, CONFIG.reqOpts); + assert.notStrictEqual(reqOpts, CONFIG.reqOpts); + } + assert.strictEqual(projectId, PROJECT_ID); + return replacedReqOpts; + }; + + FAKE_GAPIC_CLIENT[CONFIG.method] = reqOpts => { + assert.strictEqual(reqOpts, replacedReqOpts); + done(); + }; + + spanner.prepareGapicRequest_(CONFIG, (err, requestFn) => { + requestFn(); // (FAKE_GAPIC_CLIENT[CONFIG.method]) + }); + }); + + it('should return the gax client method with correct args', done => { + replaceProjectIdTokenOverride = reqOpts => { + return reqOpts; + }; + const expectedGaxOpts = extend(true, {}, CONFIG.gaxOpts, { + otherArgs: { + headers: CONFIG.headers, + }, + }); + + FAKE_GAPIC_CLIENT[CONFIG.method] = function (reqOpts, gaxOpts, arg) { + assert.strictEqual(this, FAKE_GAPIC_CLIENT); + assert.deepStrictEqual(reqOpts, CONFIG.reqOpts); + assert.notStrictEqual(reqOpts, CONFIG.reqOpts); + + // Check that gaxOpts has the expected structure + assert.ok(gaxOpts.otherArgs); + assert.deepStrictEqual(gaxOpts.otherArgs.headers, CONFIG.headers); + + arg(); // done() + }; + + spanner.prepareGapicRequest_(CONFIG, (err, requestFn) => { + requestFn(done); // (FAKE_GAPIC_CLIENT[CONFIG.method]) + }); + }); + }); + + describe('request', () => { + const CONFIG = {}; + + beforeEach(() => { + spanner.prepareGapicRequest_ = util.noop; + }); + + describe('callback mode', () => { + it('should not return a promise', () => { + const returnedValue = spanner.request(CONFIG, assert.ifError); + assert.strictEqual(returnedValue, undefined); + }); + + it('should prepare the gapic request', done => { + spanner.prepareGapicRequest_ = config => { + assert.strictEqual(config, CONFIG); + done(); + }; + + spanner.request(CONFIG, assert.ifError); + }); + + it('should execute callback with error', done => { + const error = new Error('Error.'); + + spanner.prepareGapicRequest_ = (config, callback) => { + callback(error); + }; + + spanner.request(CONFIG, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should pass callback to request function', done => { + function gapicRequestFn(callback) { + callback(); // done() + } + + spanner.prepareGapicRequest_ = (config, callback) => { + callback(null, gapicRequestFn); + }; + + spanner.request(CONFIG, done); + }); + }); + + describe('promise mode', () => { + it('should return a promise', () => { + const returnedValue = spanner.request(CONFIG); + assert(returnedValue instanceof Promise); + }); + + it('should prepare the gapic request', done => { + spanner.prepareGapicRequest_ = config => { + assert.strictEqual(config, CONFIG); + done(); + }; + + spanner.request(CONFIG); + }); + + it('should reject the promise', done => { + const error = new Error('Error.'); + + spanner.prepareGapicRequest_ = (config, callback) => { + callback(error); + }; + + spanner.request(CONFIG).catch(err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should resolve the promise with the request fn', () => { + const gapicRequestFnResult = {}; + + function gapicRequestFn() { + return gapicRequestFnResult; + } + + spanner.prepareGapicRequest_ = (config, callback) => { + callback(null, gapicRequestFn); + }; + + return spanner.request(CONFIG).then(result => { + assert.strictEqual(result, gapicRequestFnResult); + }); + }); + }); + }); + + describe('requestStream', () => { + const CONFIG = {}; + + beforeEach(() => { + spanner.prepareGapicRequest_ = util.noop; + }); + + it('should prepare the gapic request', done => { + spanner.prepareGapicRequest_ = config => { + assert.strictEqual(config, CONFIG); + done(); + }; + + spanner.requestStream(CONFIG).emit('reading'); + }); + + it('should destroy the stream with an error', done => { + const error = new Error('Error.'); + + spanner.prepareGapicRequest_ = (config, callback) => { + callback(error); + }; + + spanner + .requestStream(CONFIG) + .on('error', err => { + assert.strictEqual(err, error); + done(); + }) + .emit('reading'); + }); + + it('should pipe the request stream to the user stream', done => { + const requestStream = through.obj(); + const data = {}; + + spanner.prepareGapicRequest_ = (config, callback) => { + callback(null, () => { + setImmediate(() => { + requestStream.end(data); + }); + + return requestStream; + }); + }; + + spanner + .requestStream(CONFIG) + .on('data', data_ => { + assert.strictEqual(data_, data); + done(); + }) + .emit('reading'); + }); + + it('should pass errors from the request stream', done => { + const requestStream = through.obj(); + const error = new Error('Error.'); + + spanner.prepareGapicRequest_ = (config, callback) => { + callback(null, () => { + setImmediate(() => { + requestStream.destroy(error); + }); + + return requestStream; + }); + }; + + spanner + .requestStream(CONFIG) + .on('error', err => { + assert.strictEqual(err, error); + done(); + }) + .emit('reading'); + }); + }); +}); diff --git a/handwritten/spanner/test/instance-config.ts b/handwritten/spanner/test/instance-config.ts new file mode 100644 index 00000000000..eb5db686392 --- /dev/null +++ b/handwritten/spanner/test/instance-config.ts @@ -0,0 +1,369 @@ +/** + * Copyright 2022 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. + */ + +/* eslint-disable prefer-rest-params */ + +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import {grpc} from 'google-gax'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; +import * as pfy from '@google-cloud/promisify'; +import * as sinon from 'sinon'; + +import * as instConfig from '../src/instance-config'; +import {Spanner, GetInstanceConfigResponse} from '../src'; +import {CLOUD_RESOURCE_HEADER} from '../src/common'; + +let promisified = false; +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'InstanceConfig') { + return; + } + promisified = true; + assert.deepStrictEqual(options.exclude, ['exists']); + }, +}); + +class FakeGrpcServiceObject { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +describe('InstanceConfig', () => { + // tslint:disable-next-line variable-name + let InstanceConfig: typeof instConfig.InstanceConfig; + let instanceConfig: instConfig.InstanceConfig; + + const sandbox = sinon.createSandbox(); + + const SPANNER = { + request: () => {}, + requestStream: () => {}, + getInstanceConfig: () => {}, + projectId: 'project-id', + instances_: new Map(), + instanceConfigs_: new Map(), + projectFormattedName_: 'projects/project-id', + } as {} as Spanner; + + const NAME = 'instance-config-name'; + + before(() => { + InstanceConfig = proxyquire('../src/instance-config.js', { + './common-grpc/service-object': { + GrpcServiceObject: FakeGrpcServiceObject, + }, + '@google-cloud/promisify': fakePfy, + }).InstanceConfig; + }); + + beforeEach(() => { + instanceConfig = new InstanceConfig(SPANNER, NAME); + }); + + describe('instantiation', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should format the name', () => { + const formatName_ = InstanceConfig.formatName_; + const formattedName = 'formatted-name'; + + InstanceConfig.formatName_ = (projectId, name) => { + InstanceConfig.formatName_ = formatName_; + + assert.strictEqual(projectId, SPANNER.projectId); + assert.strictEqual(name, NAME); + + return formattedName; + }; + + const instanceConfig = new InstanceConfig(SPANNER, NAME); + assert(instanceConfig.formattedName_, formattedName); + }); + + it('should localize the request function', done => { + const spannerInstance = extend({}, SPANNER); + + spannerInstance.request = function () { + assert.strictEqual(this, spannerInstance); + done(); + }; + + const instanceConfig = new InstanceConfig(spannerInstance, NAME); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (instanceConfig as any).request(); + }); + + it('should inherit from ServiceObject', done => { + const options = {}; + const spannerInstance = extend({}, SPANNER, { + createInstanceConfig(name, options_, callback) { + assert.strictEqual(name, instanceConfig.formattedName_); + assert.strictEqual(options_, options); + callback(); // done() + }, + }); + + const instanceConfig = new InstanceConfig(spannerInstance, NAME); + assert(instanceConfig instanceof FakeGrpcServiceObject); + + const calledWith = instanceConfig.calledWith_[0]; + + assert.strictEqual(calledWith.parent, spannerInstance); + assert.strictEqual(calledWith.id, NAME); + assert.deepStrictEqual(calledWith.methods, {create: true}); + + calledWith.createMethod(null, options, done); + }); + + it('should set the resourceHeader_', () => { + assert.deepStrictEqual(instanceConfig.resourceHeader_, { + [CLOUD_RESOURCE_HEADER]: instanceConfig.formattedName_, + }); + }); + }); + + describe('formatName_', () => { + const PATH = 'projects/' + SPANNER.projectId + '/instanceConfigs/' + NAME; + + it('should return the name if already formatted', () => { + assert.strictEqual( + InstanceConfig.formatName_(SPANNER.projectId, PATH), + PATH, + ); + }); + + it('should format the name', () => { + const formattedName = InstanceConfig.formatName_(SPANNER.projectId, NAME); + assert.strictEqual(formattedName, PATH); + }); + }); + + describe('delete', () => { + beforeEach(() => { + instanceConfig.parent = SPANNER; + }); + + it('should make the correct request', done => { + instanceConfig.request = (config, callback: Function) => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'deleteInstanceConfig'); + assert.deepStrictEqual(config.reqOpts, { + name: instanceConfig.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, instanceConfig.resourceHeader_); + callback(); // done() + }; + + instanceConfig.delete(done); + }); + + it('should remove the InstanceConfig from the cache', done => { + const cache = instanceConfig.parent.instanceConfigs_; + + instanceConfig.request = (config, callback) => { + callback(null); + }; + + cache.set(instanceConfig.id, instanceConfig); + assert.strictEqual(cache.get(instanceConfig.id), instanceConfig); + + instanceConfig.delete(err => { + assert.ifError(err); + assert.strictEqual(cache.has(instanceConfig.id), false); + done(); + }); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + + instanceConfig.request = (config, callback: Function) => { + assert.deepStrictEqual(config.gaxOpts, gaxOptions); + callback(); // done() + }; + + instanceConfig.delete(gaxOptions, done); + }); + }); + + describe('exists', () => { + beforeEach(() => (instanceConfig.parent = SPANNER)); + afterEach(() => sandbox.restore()); + + it('should return any non-404 like errors', async () => { + const err = {code: grpc.status.INTERNAL}; + instanceConfig.get = async () => { + throw err; + }; + + try { + await instanceConfig.exists(); + assert.fail('Should have rethrown error'); + } catch (thrown) { + assert.deepStrictEqual(thrown, err); + } + }); + + it('should return true if error is absent', async () => { + const INSTANCE_CONFIG_INFO_RESPONSE: GetInstanceConfigResponse = [{}]; + instanceConfig.get = async () => INSTANCE_CONFIG_INFO_RESPONSE; + + const doesExist = await instanceConfig.exists(); + assert.strictEqual(doesExist, true); + }); + + it('should return false if instance config does not exist', async () => { + instanceConfig.get = async () => { + throw {code: grpc.status.NOT_FOUND}; + }; + + const doesExist = await instanceConfig.exists(); + assert.strictEqual(doesExist, false); + }); + }); + + describe('get', () => { + beforeEach(() => { + instanceConfig.parent = SPANNER; + }); + afterEach(() => { + sandbox.restore(); + }); + + it('should call getInstanceConfig', done => { + const options = {}; + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + sandbox.stub(SPANNER, 'getInstanceConfig').callsFake(_ => done()); + + instanceConfig.get(options, assert.ifError); + }); + + it('should accept and pass gaxOptions to getInstanceConfig', done => { + const gaxOptions = {}; + + sandbox.stub(SPANNER, 'getInstanceConfig').callsFake((_, options) => { + assert.strictEqual(options.gaxOptions, gaxOptions); + done(); + }); + + instanceConfig.get({gaxOptions}, assert.ifError); + }); + + it('should not require an options object', done => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + sandbox.stub(SPANNER, 'getInstanceConfig').callsFake(_ => done()); + instanceConfig.get(assert.ifError); + }); + + it('should return an error from getMetadata', done => { + const error = new Error('Error.') as grpc.ServiceError; + + sandbox + .stub(SPANNER, 'getInstanceConfig') + .callsFake((_, opts_: {}, callback) => callback!(error)); + + instanceConfig.get(err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return self and API response', done => { + const apiResponse = {} as instConfig.IInstanceConfig; + sandbox + .stub(SPANNER, 'getInstanceConfig') + .callsFake((_, opts_: {}, callback) => callback!(null, apiResponse)); + + instanceConfig.get((err, instanceConfigMetadata_) => { + assert.ifError(err); + assert.strictEqual(instanceConfigMetadata_, apiResponse); + done(); + }); + }); + }); + + describe('setMetadata', () => { + const METADATA = { + needsToBeSnakeCased: true, + } as instConfig.IInstanceConfig; + const ORIGINAL_METADATA = extend({}, METADATA); + + it('should make and return the request', () => { + const requestReturnValue = {}; + + function callback() {} + + instanceConfig.request = (config, callback_) => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'updateInstanceConfig'); + + const expectedReqOpts = extend( + {}, + extend({}, METADATA, { + name: instanceConfig.formattedName_, + }), + ) as instConfig.IInstanceConfig as instConfig.SetInstanceConfigMetadataRequest; + + assert.deepStrictEqual(config.reqOpts.instanceConfig, expectedReqOpts); + assert.deepStrictEqual(config.reqOpts.updateMask, { + paths: ['needs_to_be_snake_cased'], + }); + + assert.deepStrictEqual(METADATA, ORIGINAL_METADATA); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, instanceConfig.resourceHeader_); + + assert.strictEqual(callback_, callback); + + return requestReturnValue; + }; + + const returnValue = instanceConfig.setMetadata( + Object.assign({}, {instanceConfig: METADATA}), + callback, + ); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + instanceConfig.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + instanceConfig.setMetadata( + Object.assign({}, {instanceConfig: METADATA}, {gaxOpts: gaxOptions}), + assert.ifError, + ); + }); + + it('should not require a callback', () => { + assert.doesNotThrow(async () => { + await instanceConfig.setMetadata( + Object.assign({}, {instanceConfig: METADATA}), + ); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/instance.ts b/handwritten/spanner/test/instance.ts new file mode 100644 index 00000000000..7f9be090c1b --- /dev/null +++ b/handwritten/spanner/test/instance.ts @@ -0,0 +1,1938 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable prefer-rest-params */ + +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import {ApiError} from '@google-cloud/common'; +import {grpc} from 'google-gax'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; +import * as pfy from '@google-cloud/promisify'; +import * as sinon from 'sinon'; +import snakeCase = require('lodash.snakecase'); +import {Duplex} from 'stream'; + +import * as inst from '../src/instance'; +import {Spanner, Database, RequestConfig} from '../src'; +import {toArray} from '../src/helper'; +import {SessionPoolOptions} from '../src/session-pool'; +import {Backup} from '../src/backup'; +import {PreciseDate} from '@google-cloud/precise-date'; +import {CLOUD_RESOURCE_HEADER, AFE_SERVER_TIMING_HEADER} from '../src/common'; + +let promisified = false; +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'Instance') { + return; + } + promisified = true; + assert.deepStrictEqual(options.exclude, ['database', 'backup']); + }, +}); + +class FakeDatabase { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +class FakeGrpcServiceObject { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +class FakeBackup { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +describe('Instance', () => { + // tslint:disable-next-line variable-name + let Instance: typeof inst.Instance; + let instance: inst.Instance; + + const sandbox = sinon.createSandbox(); + + const SPANNER = { + request: () => {}, + requestStream: () => {}, + projectId: 'project-id', + instances_: new Map(), + projectFormattedName_: 'projects/project-id', + } as {} as Spanner; + + const NAME = 'instance-name'; + + before(() => { + Instance = proxyquire('../src/instance.js', { + './common-grpc/service-object': { + GrpcServiceObject: FakeGrpcServiceObject, + }, + '@google-cloud/promisify': fakePfy, + './database.js': {Database: FakeDatabase}, + './backup.js': {Backup: FakeBackup}, + }).Instance; + }); + + beforeEach(() => { + instance = new Instance(SPANNER, NAME); + }); + + describe('instantiation', () => { + it('should localize an database map', () => { + assert(instance.databases_ instanceof Map); + }); + + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should format the name', () => { + const formatName_ = Instance.formatName_; + const formattedName = 'formatted-name'; + + Instance.formatName_ = (projectId, name) => { + Instance.formatName_ = formatName_; + + assert.strictEqual(projectId, SPANNER.projectId); + assert.strictEqual(name, NAME); + + return formattedName; + }; + + const instance = new Instance(SPANNER, NAME); + assert(instance.formattedName_, formattedName); + }); + + it('should localize the request function', done => { + const spannerInstance = extend({}, SPANNER); + + spannerInstance.request = function () { + assert.strictEqual(this, spannerInstance); + done(); + }; + + const instance = new Instance(spannerInstance, NAME); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (instance as any).request(); + }); + + it('should localize the requestStream function', done => { + const spannerInstance = extend({}, SPANNER); + const CONFIG = {}; + + spannerInstance.requestStream = function (config) { + assert.strictEqual(this, spannerInstance); + assert.strictEqual(config, CONFIG); + done(); + }; + + const instance = new Instance(spannerInstance, NAME); + instance.requestStream(CONFIG as RequestConfig); + }); + + it('should inherit from ServiceObject', done => { + const options = {}; + const spannerInstance = extend({}, SPANNER, { + createInstance(name, options_, callback) { + assert.strictEqual(name, instance.formattedName_); + assert.strictEqual(options_, options); + callback(); // done() + }, + }); + + const instance = new Instance(spannerInstance, NAME); + assert(instance instanceof FakeGrpcServiceObject); + + const calledWith = instance.calledWith_[0]; + + assert.strictEqual(calledWith.parent, spannerInstance); + assert.strictEqual(calledWith.id, NAME); + assert.deepStrictEqual(calledWith.methods, {create: true}); + + calledWith.createMethod(null, options, done); + }); + + it('should set the commonHeaders_', () => { + assert.deepStrictEqual(instance.commonHeaders_, { + [CLOUD_RESOURCE_HEADER]: instance.formattedName_, + [AFE_SERVER_TIMING_HEADER]: 'true', + }); + }); + }); + + describe('formatName_', () => { + const PATH = 'projects/' + SPANNER.projectId + '/instances/' + NAME; + + it('should return the name if already formatted', () => { + assert.strictEqual(Instance.formatName_(SPANNER.projectId, PATH), PATH); + }); + + it('should format the name', () => { + const formattedName = Instance.formatName_(SPANNER.projectId, NAME); + assert.strictEqual(formattedName, PATH); + }); + }); + + describe('createDatabase', () => { + const NAME = 'database-name'; + const PATH = 'projects/project-id/databases/' + NAME; + + const OPTIONS = { + a: 'b', + } as inst.CreateDatabaseOptions; + const ORIGINAL_OPTIONS = extend({}, OPTIONS); + + it('should throw if a name is not provided', () => { + assert.throws(() => { + void instance.createDatabase(null!); + }, /A name is required to create a database\./); + }); + + it('should make the correct default request', done => { + instance.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'createDatabase'); + assert.deepStrictEqual(config.reqOpts, { + parent: instance.formattedName_, + createStatement: 'CREATE DATABASE `' + NAME + '`', + }); + assert.strictEqual(config.gaxOpts, undefined); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + + done(); + }; + + instance.createDatabase(NAME, assert.ifError); + }); + + it('should accept options', done => { + instance.request = config => { + assert.deepStrictEqual(OPTIONS, ORIGINAL_OPTIONS); + + const expectedReqOpts = extend( + { + parent: instance.formattedName_, + createStatement: 'CREATE DATABASE `' + NAME + '`', + }, + OPTIONS, + ); + + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + done(); + }; + + instance.createDatabase(NAME, OPTIONS, assert.ifError); + }); + + it('should not alter the original options', done => { + const options = Object.assign({}, OPTIONS, { + poolOptions: {}, + poolCtor: {}, + }); + const originalOptions = Object.assign({}, options); + instance.request = (config, callback: Function) => { + assert.strictEqual(config.reqOpts.poolOptions, undefined); + callback(); + }; + + instance.createDatabase(NAME, options, err => { + if (err) { + assert.ifError(err); + } + assert.deepStrictEqual(options, originalOptions); + done(); + }); + }); + + it('should accept gaxOptions', done => { + const options = Object.assign({}, OPTIONS, {gaxOptions: {}}); + instance.request = config => { + assert.strictEqual(config.gaxOpts, options.gaxOptions); + assert.strictEqual(config.reqOpts.gaxOptions, undefined); + + done(); + }; + + instance.createDatabase(NAME, options, assert.ifError); + }); + + it('should only use the name in the createStatement', done => { + instance.request = config => { + const expectedReqOpts = extend( + { + parent: instance.formattedName_, + createStatement: 'CREATE DATABASE `' + NAME + '`', + }, + OPTIONS, + ); + + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + done(); + }; + + instance.createDatabase(PATH, OPTIONS, assert.ifError); + }); + + describe('options.poolOptions/poolCtor', () => { + it('should allow specifying session pool options', done => { + const poolOptions = {}; + + const options = extend({}, OPTIONS, { + poolOptions, + }); + + instance.request = (config, callback: Function) => { + assert.strictEqual(config.reqOpts.poolOptions, undefined); + callback(); + }; + + instance.database = (name, poolOptions_) => { + assert.strictEqual(poolOptions_, poolOptions); + done(); + return {} as Database; + }; + + instance.createDatabase(PATH, options, assert.ifError); + }); + + it('should allow specifying session pool constructor', done => { + const poolCtor = {}; + + const options = extend({}, OPTIONS, { + poolCtor, + }); + + instance.request = (config, callback: Function) => { + assert.strictEqual(config.reqOpts.poolCtor, undefined); + callback(); + }; + + instance.database = (name, poolOptions_) => { + assert.strictEqual(poolOptions_, poolCtor); + done(); + return {} as Database; + }; + + instance.createDatabase(PATH, options, assert.ifError); + }); + }); + + describe('options.schema', () => { + it('should arrify and rename to extraStatements', done => { + const SCHEMA = 'schema'; + + const options = extend({}, OPTIONS, { + schema: SCHEMA, + }); + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts.extraStatements, [SCHEMA]); + assert.strictEqual(config.reqOpts.schema, undefined); + done(); + }; + + instance.createDatabase(NAME, options, assert.ifError); + }); + + it('should arrify and rename to extraStatements from array style schema filed', done => { + const SCHEMA = ['schema', 'schema2']; + + const options = extend({}, OPTIONS, { + schema: SCHEMA, + }); + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts.extraStatements, SCHEMA); + assert.strictEqual(config.reqOpts.schema, undefined); + done(); + }; + + instance.createDatabase(NAME, options, assert.ifError); + }); + }); + + describe('error', () => { + const ERROR = new Error('Error.'); + const API_RESPONSE = {}; + + beforeEach(() => { + instance.request = (config, callback: Function) => { + callback(ERROR, null, API_RESPONSE); + }; + }); + + it('should execute callback with error & API response', done => { + instance.createDatabase(NAME, OPTIONS, (err, db, op, resp) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(op, null); + assert.strictEqual(resp, API_RESPONSE); + done(); + }); + }); + }); + + describe('success', () => { + const OPERATION = {}; + const API_RESPONSE = {}; + + beforeEach(() => { + instance.request = (config, callback: Function) => { + callback(null, OPERATION, API_RESPONSE); + }; + }); + + it('should exec callback with a Database and Operation', done => { + const fakeDatabaseInstance = {}; + + instance.database = name => { + assert.strictEqual(name, NAME); + return fakeDatabaseInstance as Database; + }; + + instance.createDatabase(NAME, OPTIONS, (err, db, op, resp) => { + assert.ifError(err); + assert.strictEqual(db, fakeDatabaseInstance); + assert.strictEqual(op, OPERATION); + assert.strictEqual(resp, API_RESPONSE); + done(); + }); + }); + }); + }); + + describe('database', () => { + const NAME = 'database-name'; + + it('should throw if a name is not provided', () => { + assert.throws(() => { + instance.database(null!); + }, /A name is required to access a Database object\./); + }); + + it('should create and cache a Database', () => { + const cache = instance.databases_; + const poolOptions = {}; + + assert.strictEqual(cache.has(NAME), false); + + const database = instance.database( + NAME, + poolOptions, + ) as {} as FakeDatabase; + + assert(database instanceof FakeDatabase); + assert.strictEqual(database.calledWith_[0], instance); + assert.strictEqual(database.calledWith_[1], NAME); + assert.strictEqual(database.calledWith_[2], poolOptions); + assert.strictEqual(database, cache.get(NAME)); + }); + + it('should re-use cached objects', () => { + const cache = instance.databases_; + const fakeDatabase = {} as Database; + + cache.set(NAME, fakeDatabase); + + const database = instance.database(NAME); + + assert.strictEqual(database, fakeDatabase); + }); + + it('should create and cache different objects when called with different session pool options', () => { + const cache = instance.databases_; + const fakeDatabase = {} as Database; + const fakeDatabaseWithSessionPoolOptions = {} as Database; + const emptySessionPoolOptions = {} as SessionPoolOptions; + const fakeSessionPoolOptions = { + min: 1000, + max: 1000, + } as SessionPoolOptions; + const fakeSessionPoolOptionsInOtherOrder = { + max: 1000, + min: 1000, + } as SessionPoolOptions; + + cache.set(NAME, fakeDatabase); + cache.set( + NAME + + '/' + + JSON.stringify(Object.entries(fakeSessionPoolOptions).sort()), + fakeDatabaseWithSessionPoolOptions, + ); + + const database = instance.database(NAME); + const databaseWithEmptyOptions = instance.database( + NAME, + emptySessionPoolOptions, + ); + const databaseWithOptions = instance.database( + NAME, + fakeSessionPoolOptions, + ); + const databaseWithOptionsInOtherOrder = instance.database( + NAME, + fakeSessionPoolOptionsInOtherOrder, + ); + + assert.strictEqual(database, fakeDatabase); + assert.strictEqual(databaseWithEmptyOptions, fakeDatabase); + assert.strictEqual( + databaseWithOptions, + fakeDatabaseWithSessionPoolOptions, + ); + assert.strictEqual( + databaseWithOptionsInOtherOrder, + fakeDatabaseWithSessionPoolOptions, + ); + }); + }); + + describe('delete', () => { + beforeEach(() => { + instance.parent = SPANNER; + }); + + it('should close all cached databases', done => { + let closed = false; + + instance.databases_.set('key', { + close() { + closed = true; + return Promise.resolve(); + }, + } as {} as Database); + + instance.request = () => { + assert.strictEqual(closed, true); + assert.strictEqual(instance.databases_.size, 0); + done(); + }; + + instance.delete(assert.ifError); + }); + + it('should ignore closing errors', done => { + instance.databases_.set('key', { + close() { + return Promise.reject(new Error('err')); + }, + } as {} as Database); + + instance.request = () => { + done(); + }; + + instance.delete(assert.ifError); + }); + + it('should make the correct request', done => { + instance.request = (config, callback: Function) => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'deleteInstance'); + assert.deepStrictEqual(config.reqOpts, { + name: instance.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + callback(); // done() + }; + + instance.delete(done); + }); + + it('should remove the Instance from the cache', done => { + const cache = instance.parent.instances_; + + instance.request = (config, callback) => { + callback(null); + }; + + cache.set(instance.id, instance); + assert.strictEqual(cache.get(instance.id), instance); + + instance.delete(err => { + assert.ifError(err); + assert.strictEqual(cache.has(instance.id), false); + done(); + }); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + + instance.request = (config, callback: Function) => { + assert.strictEqual(config.gaxOpts, gaxOptions); + callback(); // done() + }; + + instance.delete(gaxOptions, done); + }); + }); + + describe('exists', () => { + afterEach(() => sandbox.restore()); + + it('should return any non-404 like errors', done => { + const error = {code: 3}; + + sandbox + .stub(instance, 'getMetadata') + .callsFake( + ( + opts_: + | inst.GetInstanceMetadataOptions + | inst.GetInstanceMetadataCallback, + cb, + ) => { + cb = typeof opts_ === 'function' ? opts_ : cb; + cb(error as grpc.ServiceError); + }, + ); + + instance.exists((err, exists) => { + assert.strictEqual(err, error); + assert.strictEqual(exists, null); + done(); + }); + }); + + it('should return true if error is absent', done => { + sandbox + .stub(instance, 'getMetadata') + .callsFake( + ( + opts_: + | inst.GetInstanceMetadataOptions + | inst.GetInstanceMetadataCallback, + cb, + ) => { + cb = typeof opts_ === 'function' ? opts_ : cb; + cb(null); + }, + ); + + instance.exists((err, exists) => { + assert.ifError(err); + assert.strictEqual(exists, true); + done(); + }); + }); + + it('should return false if not found error if present', done => { + const error = {code: 5}; + + sandbox + .stub(instance, 'getMetadata') + .callsFake( + ( + opts_: + | inst.GetInstanceMetadataOptions + | inst.GetInstanceMetadataCallback, + callback, + ) => { + callback = typeof opts_ === 'function' ? opts_ : callback; + + callback(error as grpc.ServiceError); + }, + ); + + instance.exists((err, exists) => { + assert.ifError(err); + assert.strictEqual(exists, false); + done(); + }); + }); + + it('should accept and pass gaxOptions to getMetadata', done => { + const gaxOptions = {}; + (instance.getMetadata as Function) = options => { + assert.strictEqual(options.gaxOptions, gaxOptions); + done(); + }; + instance.exists(gaxOptions, assert.ifError); + }); + }); + + describe('get', () => { + it('should call getMetadata', done => { + const options = {}; + + sandbox.stub(instance, 'getMetadata').callsFake(() => done()); + + instance.get(options, assert.ifError); + }); + + it('should accept and pass gaxOptions to getMetadata', done => { + const gaxOptions = {}; + (instance.getMetadata as Function) = options => { + assert.strictEqual(options.gaxOptions, gaxOptions); + done(); + }; + + instance.get({gaxOptions}, assert.ifError); + }); + + it('should not require an options object', done => { + sandbox.stub(instance, 'getMetadata').callsFake(() => done()); + + instance.get(assert.ifError); + }); + + it('should accept and pass `fields` string as is', () => { + const fieldNames = 'nodeCount'; + const spyMetadata = sandbox.spy(instance, 'getMetadata'); + + instance.get({fieldNames}, assert.ifError); + + assert.ok(spyMetadata.calledWith({fieldNames})); + }); + + it('should accept and pass `fields` array as is', () => { + const fieldNames = ['name', 'labels', 'nodeCount']; + const spyMetadata = sandbox.stub(instance, 'getMetadata'); + + instance.get({fieldNames}, assert.ifError); + + assert.ok(spyMetadata.calledWith({fieldNames})); + }); + + describe('autoCreate', () => { + const error = new ApiError('Error.') as grpc.ServiceError; + error.code = 5; + + const OPTIONS = { + autoCreate: true, + }; + + const OPERATION = { + listeners: {}, + on(eventName, callback) { + OPERATION.listeners[eventName] = callback; + return OPERATION; + }, + }; + + beforeEach(() => { + OPERATION.listeners = {}; + + sandbox + .stub(instance, 'getMetadata') + .callsFake((opts_: {}, callback) => callback!(error)); + + instance.create = (options, callback) => { + callback(null, null, OPERATION); + }; + }); + + it('should accet and pass createInstanceRequest options to create', done => { + const config = 'config'; + const nodes = 1; + const displayName = 'displayName'; + const labels = {label: 'mayLabael'}; + + instance.create = options => { + assert.strictEqual(options.fieldNames, undefined); + assert.strictEqual(options.autoCreate, undefined); + assert.deepStrictEqual(options, {config, nodes, displayName, labels}); + done(); + }; + instance.get( + { + autoCreate: true, + config, + nodes, + displayName, + labels, + fieldNames: 'labels', + }, + assert.ifError, + ); + }); + + it('should accept and pass gaxOptions to instance#create', done => { + const gaxOptions = {timeout: 1000}; + const options = Object.assign({}, OPTIONS, {gaxOptions}); + instance.create = options => { + assert.deepStrictEqual(options.gaxOptions, gaxOptions); + done(); + }; + + instance.get(options, assert.ifError); + }); + + it('should call create', done => { + const createOptions: {autoCreate?: {}} = Object.assign({}, OPTIONS); + delete createOptions.autoCreate; + instance.create = options => { + assert.deepStrictEqual(options, createOptions); + done(); + }; + + instance.get(OPTIONS, assert.ifError); + }); + + it('should return error if create failed', done => { + const error = new Error('Error.'); + + instance.create = (options, callback) => { + callback(error); + }; + + instance.get(OPTIONS, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return operation error', done => { + const error = new Error('Error.'); + + setImmediate(() => { + OPERATION.listeners['error'](error); + }); + + instance.get(OPTIONS, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should execute callback if opereation succeeded', done => { + const metadata = {}; + + setImmediate(() => { + OPERATION.listeners['complete'](metadata); + }); + + instance.get(OPTIONS, (err, instance_, apiResponse) => { + assert.ifError(err); + assert.strictEqual(instance_, instance); + assert.strictEqual(instance.metadata, metadata); + assert.strictEqual(metadata, apiResponse); + done(); + }); + }); + }); + + it('should not auto create without error code 5', done => { + const error = new Error('Error.') as grpc.ServiceError; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (error as any).code = 'NOT-5'; + + const options = { + autoCreate: true, + }; + + sandbox + .stub(instance, 'getMetadata') + .callsFake((opts_: {}, callback) => callback!(error)); + + instance.create = () => { + throw new Error('Should not create.'); + }; + + instance.get(options, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should not auto create unless requested', done => { + const error = new ApiError('Error.') as grpc.ServiceError; + error.code = 5; + + sandbox + .stub(instance, 'getMetadata') + .callsFake((opts_: {}, callback) => callback!(error)); + + instance.create = () => { + throw new Error('Should not create.'); + }; + + instance.get(err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return an error from getMetadata', done => { + const error = new Error('Error.') as grpc.ServiceError; + + sandbox + .stub(instance, 'getMetadata') + .callsFake((opts_: {}, callback) => callback!(error)); + + instance.get(err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return self and API response', done => { + const apiResponse = {} as inst.IInstance; + + sandbox + .stub(instance, 'getMetadata') + .callsFake((opts_: {}, callback) => callback!(null, apiResponse)); + + instance.get((err, instance_, apiResponse_) => { + assert.ifError(err); + assert.strictEqual(instance_, instance); + assert.strictEqual(apiResponse_, apiResponse); + done(); + }); + }); + }); + + describe('getDatabases', () => { + const pageSize = 3; + const OPTIONS = { + pageSize, + gaxOptions: {autoPaginate: false}, + } as inst.GetDatabasesOptions; + const ORIGINAL_OPTIONS = extend({}, OPTIONS); + + it('should make the correct request', done => { + const expectedReqOpts = extend({}, OPTIONS, { + parent: instance.formattedName_, + }); + delete expectedReqOpts.gaxOptions; + + instance.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'listDatabases'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, OPTIONS); + assert.deepStrictEqual(OPTIONS, ORIGINAL_OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, OPTIONS.gaxOptions); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + + done(); + }; + + instance.getDatabases(OPTIONS, assert.ifError); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options = {gaxOptions}; + const expectedReqOpts: {gaxOptions?: {}} = extend( + {}, + options, + { + parent: instance.formattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + delete expectedReqOpts.gaxOptions; + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + instance.getDatabases(options, assert.ifError); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', done => { + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }; + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: instance.formattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + delete expectedReqOpts.gaxOptions; + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + instance.getDatabases(options, assert.ifError); + }); + + it('should not require options', done => { + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: instance.formattedName_, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + + done(); + }; + + instance.getDatabases(assert.ifError); + }); + + describe('error', () => { + const REQUEST_RESPONSE_ARGS = [new Error('Error.'), null, null, {}]; + + beforeEach(() => { + instance.request = (config, callback: Function) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + }); + + it('should execute callback with original arguments', done => { + instance.getDatabases(OPTIONS, (...args) => { + assert.deepStrictEqual(args, REQUEST_RESPONSE_ARGS); + done(); + }); + }); + }); + + describe('success', () => { + const DATABASES = [ + { + name: 'database-name', + }, + ]; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const REQUEST_RESPONSE_ARGS: any = [null, DATABASES, null, {}]; + + beforeEach(() => { + instance.request = (config, callback) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + }); + + it('should create and return Database objects', done => { + const fakeDatabaseInstance = {}; + + instance.database = (name, options) => { + assert.strictEqual(name, DATABASES[0].name); + assert.strictEqual((options as SessionPoolOptions).min, 0); + return fakeDatabaseInstance as Database; + }; + + instance.getDatabases(OPTIONS, (...args) => { + assert.ifError(args[0]); + assert.strictEqual(args[0], REQUEST_RESPONSE_ARGS[0]); + const database = args[1]!.pop(); + assert.strictEqual(database, fakeDatabaseInstance); + assert.strictEqual(database!.metadata, REQUEST_RESPONSE_ARGS[1][0]); + assert.strictEqual(args[2], REQUEST_RESPONSE_ARGS[2]); + assert.strictEqual(args[3], REQUEST_RESPONSE_ARGS[3]); + done(); + }); + }); + + it('should return a complete nextQuery object', done => { + const pageSize = 1; + const filter = 'filter'; + const NEXTPAGEREQUEST = { + parent: instance.formattedName_, + pageSize, + filter, + pageToken: 'pageToken', + }; + const REQUEST_RESPONSE_ARGS = [null, [], NEXTPAGEREQUEST, {}]; + + const GETDATABASESOPTIONS = { + pageSize, + filter, + gaxOptions: {timeout: 1000, autoPaginate: false}, + }; + const EXPECTEDNEXTQUERY = extend( + {}, + GETDATABASESOPTIONS, + NEXTPAGEREQUEST, + ); + instance.request = (config, callback) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + function callback(err, databases, nextQuery) { + assert.deepStrictEqual(nextQuery, EXPECTEDNEXTQUERY); + done(); + } + instance.getDatabases(GETDATABASESOPTIONS, callback); + }); + }); + }); + + describe('getDatabasesStream', () => { + const OPTIONS = { + gaxOptions: {autoPaginate: false}, + } as inst.GetDatabasesOptions; + const returnValue = {} as Duplex; + + it('should make and return the correct gax API call', () => { + const expectedReqOpts = extend({}, OPTIONS, { + parent: instance.formattedName_, + }); + delete expectedReqOpts.gaxOptions; + + instance.requestStream = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'listDatabasesStream'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, OPTIONS.gaxOptions); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + + return returnValue; + }; + + const returnedValue = instance.getDatabasesStream(OPTIONS); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options = {gaxOptions}; + const expectedReqOpts = extend( + {}, + { + parent: instance.formattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + + instance.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + return returnValue; + }; + + const returnedValue = instance.getDatabasesStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }; + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: instance.formattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + delete expectedReqOpts.gaxOptions; + + instance.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + return returnValue; + }; + + const returnedValue = instance.getDatabasesStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should not require options', () => { + instance.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: instance.formattedName_, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + + return returnValue; + }; + + const returnedValue = instance.getDatabasesStream(); + assert.strictEqual(returnedValue, returnValue); + }); + }); + + describe('getMetadata', () => { + it('should correctly call and return request', () => { + const requestReturnValue = {}; + + function callback() {} + + instance.request = config => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'getInstance'); + assert.deepStrictEqual(config.reqOpts, { + name: instance.formattedName_, + }); + assert.strictEqual(config.gaxOpts, undefined); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + return requestReturnValue; + }; + + const returnValue = instance.getMetadata(callback); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should accept `fieldNames` as string', done => { + const fieldNames = 'nodeCount'; + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, { + fieldMask: { + paths: toArray(fieldNames).map(snakeCase), + }, + name: instance.formattedName_, + }); + done(); + }; + instance.getMetadata({fieldNames}, assert.ifError); + }); + + it('should accept `fieldNames` as string array', done => { + const fieldNames = ['name', 'labels', 'nodeCount']; + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, { + fieldMask: { + paths: fieldNames.map(snakeCase), + }, + name: instance.formattedName_, + }); + done(); + }; + instance.getMetadata({fieldNames}, assert.ifError); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + instance.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + instance.getMetadata({gaxOptions}, assert.ifError); + }); + + it('should update metadata', done => { + const metadata = {}; + instance.request = (config, callback) => { + callback(null, metadata); + }; + instance.getMetadata(() => { + assert.strictEqual(instance.metadata, metadata); + done(); + }); + + it('should call callback with error', done => { + const error = new Error('Error'); + instance.request = (config, callback) => { + callback(error); + }; + instance.getMetadata(err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + }); + + describe('setMetadata', () => { + const METADATA = { + needsToBeSnakeCased: true, + } as inst.IInstance; + const ORIGINAL_METADATA = extend({}, METADATA); + + it('should make and return the request', () => { + const requestReturnValue = {}; + + function callback() {} + + instance.request = (config, callback_) => { + assert.strictEqual(config.client, 'InstanceAdminClient'); + assert.strictEqual(config.method, 'updateInstance'); + + const expectedReqOpts = extend({}, METADATA, { + name: instance.formattedName_, + }); + + assert.deepStrictEqual(config.reqOpts.instance, expectedReqOpts); + assert.deepStrictEqual(config.reqOpts.fieldMask, { + paths: ['needs_to_be_snake_cased'], + }); + + assert.deepStrictEqual(METADATA, ORIGINAL_METADATA); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + + assert.strictEqual(callback_, callback); + + return requestReturnValue; + }; + + const returnValue = instance.setMetadata(METADATA, callback); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + instance.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + instance.setMetadata(METADATA, gaxOptions, assert.ifError); + }); + + it('should not require a callback', () => { + assert.doesNotThrow(async () => { + await instance.setMetadata(METADATA); + }); + }); + }); + + describe('getBackups', () => { + const OPTIONS = { + a: 'b', + } as inst.GetBackupsOptions; + const ORIGINAL_OPTIONS = extend({}, OPTIONS); + + it('should make the correct request', done => { + const gaxOpts = { + timeout: 1000, + }; + const options = {a: 'b', gaxOptions: gaxOpts}; + + const expectedReqOpts = extend({}, OPTIONS, { + parent: instance.formattedName_, + }); + + instance.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'listBackups'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, OPTIONS); + assert.deepStrictEqual(OPTIONS, ORIGINAL_OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, options.gaxOptions); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + done(); + }; + + instance.getBackups(options, assert.ifError); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options = {gaxOptions}; + const expectedReqOpts = extend( + {}, + { + parent: instance.formattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + instance.getBackups(options, assert.ifError); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }; + const expectedReqOpts = extend( + {}, + { + parent: instance.formattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + instance.getBackups(options, assert.ifError); + }); + + it('should not require options', done => { + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: instance.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + done(); + }; + + instance.getBackups(assert.ifError); + }); + + describe('error', () => { + const REQUEST_RESPONSE_ARGS = [new Error('Error.'), null, null, {}]; + + beforeEach(() => { + instance.request = (config, callback: Function) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + }); + + it('should execute callback with original arguments', done => { + instance.getBackups(OPTIONS, (...args) => { + assert.deepStrictEqual(args, REQUEST_RESPONSE_ARGS); + done(); + }); + }); + }); + + describe('success', () => { + const BACKUPS = [ + { + name: 'backup-name', + database: 'database-name', + expireTime: new PreciseDate(1000), + }, + ]; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const REQUEST_RESPONSE_ARGS: any = [null, BACKUPS, null, {}]; + + beforeEach(() => { + instance.request = (config, callback) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + }); + + it('should create and return Backup objects', done => { + const fakeBackupInstance = {}; + + instance.backup = backupId => { + assert.strictEqual(backupId, BACKUPS[0].name); + return fakeBackupInstance as Backup; + }; + + instance.getBackups(OPTIONS, (...args) => { + assert.ifError(args[0]); + assert.strictEqual(args[0], REQUEST_RESPONSE_ARGS[0]); + const backup = args[1]!.pop(); + assert.strictEqual(backup, fakeBackupInstance); + assert.strictEqual(backup!.metadata, REQUEST_RESPONSE_ARGS[1][0]); + assert.strictEqual(args[2], REQUEST_RESPONSE_ARGS[2]); + assert.strictEqual(args[3], REQUEST_RESPONSE_ARGS[3]); + done(); + }); + }); + + it('should return a complete nextQuery object', done => { + const pageSize = 1; + const filter = 'filter'; + const NEXTPAGEREQUEST = { + parent: instance.formattedName_, + pageSize, + filter, + pageToken: 'pageToken', + }; + const REQUEST_RESPONSE_ARGS = [null, [], NEXTPAGEREQUEST, {}]; + + const GETBACKUPSOPTIONS = { + pageSize, + filter, + gaxOptions: {timeout: 1000, autoPaginate: false}, + }; + const EXPECTEDNEXTQUERY = extend( + {}, + GETBACKUPSOPTIONS, + NEXTPAGEREQUEST, + ); + instance.request = (config, callback) => { + callback(...REQUEST_RESPONSE_ARGS); + }; + function callback(err, backups, nextQuery) { + assert.deepStrictEqual(nextQuery, EXPECTEDNEXTQUERY); + done(); + } + instance.getBackups(GETBACKUPSOPTIONS, callback); + }); + }); + }); + + describe('getBackupsStream', () => { + const OPTIONS = { + gaxOptions: {autoPaginate: false}, + } as inst.GetDatabasesOptions; + const returnValue = {} as Duplex; + + it('should make and return the correct gax API call', () => { + const expectedReqOpts = extend({}, OPTIONS, { + parent: instance.formattedName_, + }); + delete expectedReqOpts.gaxOptions; + + instance.requestStream = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'listBackupsStream'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, OPTIONS.gaxOptions); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + + return returnValue; + }; + + const returnedValue = instance.getBackupsStream(OPTIONS); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options = {gaxOptions}; + const expectedReqOpts = extend( + {}, + { + parent: instance.formattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + + instance.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + return returnValue; + }; + + const returnedValue = instance.getBackupsStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', () => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }; + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: instance.formattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + delete expectedReqOpts.gaxOptions; + + instance.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + return returnValue; + }; + + const returnedValue = instance.getBackupsStream(options); + assert.strictEqual(returnedValue, returnValue); + }); + + it('should not require options', () => { + instance.requestStream = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: instance.formattedName_, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + + return returnValue; + }; + + const returnedValue = instance.getBackupsStream(); + assert.strictEqual(returnedValue, returnValue); + }); + }); + + describe('backup', () => { + const BACKUP_NAME = 'backup-name'; + + it('should throw if a backup ID is not provided', () => { + assert.throws(() => { + instance.backup(null!); + }, /A backup ID is required to create a Backup\./); + }); + + it('should return an instance of Backup', () => { + const backup = instance.backup(BACKUP_NAME) as {} as FakeBackup; + assert(backup instanceof FakeBackup); + assert.strictEqual(backup.calledWith_[0], instance); + assert.strictEqual(backup.calledWith_[1], BACKUP_NAME); + }); + }); + + describe('getBackupOperations', () => { + const OPTIONS = { + a: 'b', + } as inst.GetBackupOperationsOptions; + const ORIGINAL_OPTIONS = extend({}, OPTIONS); + + it('should make the correct request', done => { + const gaxOpts = { + timeout: 1000, + }; + const options = {a: 'b', gaxOptions: gaxOpts}; + + const expectedReqOpts = extend({}, OPTIONS, { + parent: instance.formattedName_, + }); + + instance.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'listBackupOperations'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, OPTIONS); + assert.deepStrictEqual(OPTIONS, ORIGINAL_OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, options.gaxOptions); + done(); + }; + + instance.getBackupOperations(options, assert.ifError); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options = Object.assign({}, OPTIONS, {gaxOptions}); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: instance.formattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + instance.getBackupOperations(options, assert.ifError); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = Object.assign({}, OPTIONS, { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: instance.formattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + instance.getBackupOperations(options, assert.ifError); + }); + + it('should not require options', done => { + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: instance.formattedName_, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + done(); + }; + + instance.getBackupOperations(assert.ifError); + }); + + it('should return a complete nextQuery object', done => { + const pageSize = 1; + const filter = 'filter'; + const NEXTPAGEREQUEST = { + parent: instance.formattedName_, + pageSize, + filter, + pageToken: 'pageToken', + }; + const RESPONSE = [null, [], NEXTPAGEREQUEST, {}]; + + const GETBACKUPOPSOPTIONS = { + pageSize, + filter, + gaxOptions: {timeout: 1000, autoPaginate: false}, + }; + const EXPECTEDNEXTQUERY = extend( + {}, + GETBACKUPOPSOPTIONS, + NEXTPAGEREQUEST, + ); + instance.request = (config, callback) => { + callback(...RESPONSE); + }; + function callback(err, backupOps, nextQuery) { + assert.deepStrictEqual(nextQuery, EXPECTEDNEXTQUERY); + done(); + } + instance.getBackupOperations(GETBACKUPOPSOPTIONS, callback); + }); + }); + + describe('getDatabaseOperations', () => { + const OPTIONS = { + a: 'b', + } as inst.GetDatabaseOperationsOptions; + const ORIGINAL_OPTIONS = extend({}, OPTIONS); + + it('should make the correct request', done => { + const gaxOpts = { + timeout: 1000, + }; + const options = {a: 'b', gaxOptions: gaxOpts}; + + const expectedReqOpts = extend({}, OPTIONS, { + parent: instance.formattedName_, + }); + + instance.request = config => { + assert.strictEqual(config.client, 'DatabaseAdminClient'); + assert.strictEqual(config.method, 'listDatabaseOperations'); + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + + assert.notStrictEqual(config.reqOpts, OPTIONS); + assert.deepStrictEqual(OPTIONS, ORIGINAL_OPTIONS); + + assert.deepStrictEqual(config.gaxOpts, options.gaxOptions); + assert.deepStrictEqual(config.headers, instance.commonHeaders_); + done(); + }; + + instance.getDatabaseOperations(options, assert.ifError); + }); + + it('should pass pageSize and pageToken from gaxOptions into reqOpts', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + const options = Object.assign({}, OPTIONS, {gaxOptions}); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: instance.formattedName_, + }, + {pageSize: gaxOptions.pageSize, pageToken: gaxOptions.pageToken}, + ); + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + instance.getDatabaseOperations(options, assert.ifError); + }); + + it('pageSize and pageToken in options should take precedence over gaxOptions', done => { + const pageSize = 3; + const pageToken = 'token'; + const gaxOptions = {pageSize, pageToken, timeout: 1000}; + const expectedGaxOpts = {timeout: 1000}; + + const optionsPageSize = 5; + const optionsPageToken = 'optionsToken'; + const options = Object.assign({}, OPTIONS, { + pageSize: optionsPageSize, + pageToken: optionsPageToken, + gaxOptions, + }); + const expectedReqOpts = extend( + {}, + OPTIONS, + { + parent: instance.formattedName_, + }, + {pageSize: optionsPageSize, pageToken: optionsPageToken}, + ); + + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, expectedReqOpts); + assert.notStrictEqual(config.gaxOpts, gaxOptions); + assert.notDeepStrictEqual(config.gaxOpts, gaxOptions); + assert.deepStrictEqual(config.gaxOpts, expectedGaxOpts); + + done(); + }; + + instance.getDatabaseOperations(options, assert.ifError); + }); + + it('should not require options', done => { + instance.request = config => { + assert.deepStrictEqual(config.reqOpts, { + parent: instance.formattedName_, + }); + + assert.deepStrictEqual(config.gaxOpts, {}); + done(); + }; + + instance.getDatabaseOperations(assert.ifError); + }); + + it('should return a complete nextQuery object', done => { + const pageSize = 1; + const filter = 'filter'; + const NEXTPAGEREQUEST = { + parent: instance.formattedName_, + pageSize, + filter, + pageToken: 'pageToken', + }; + const RESPONSE = [null, [], NEXTPAGEREQUEST, {}]; + + const GETDATABASEOPSOPTIONS = { + pageSize, + filter, + gaxOptions: {timeout: 1000, autoPaginate: false}, + }; + const EXPECTEDNEXTQUERY = extend( + {}, + GETDATABASEOPSOPTIONS, + NEXTPAGEREQUEST, + ); + instance.request = (config, callback) => { + callback(...RESPONSE); + }; + function callback(err, databaseOps, nextQuery) { + assert.deepStrictEqual(nextQuery, EXPECTEDNEXTQUERY); + done(); + } + instance.getDatabaseOperations(GETDATABASEOPSOPTIONS, callback); + }); + }); +}); diff --git a/handwritten/spanner/test/metrics/interceptor.ts b/handwritten/spanner/test/metrics/interceptor.ts new file mode 100644 index 00000000000..fdb5cf88980 --- /dev/null +++ b/handwritten/spanner/test/metrics/interceptor.ts @@ -0,0 +1,218 @@ +// 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 +// +// 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. + +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {grpc} from 'google-gax'; +import {status as Status} from '@grpc/grpc-js'; +import {MetricsTracerFactory} from '../../src/metrics/metrics-tracer-factory'; +import {MetricsTracer} from '../../src/metrics/metrics-tracer'; +import {MetricInterceptor} from '../../src/metrics/interceptor'; + +describe('MetricInterceptor', () => { + let sandbox: sinon.SinonSandbox; + let mockMetricsTracer: sinon.SinonStubbedInstance; + let mockFactory: sinon.SinonStubbedInstance; + let mockNextCall: sinon.SinonStub; + let mockInterceptingCall: any; + let mockListener: any; + let serverTimingMetadata: any; + let emptyMetadata: any; + let mockStatus: any; + let mockOptions: any; + let capturedListener: any; + let testMetadata: grpc.Metadata; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + + // Mock MetricsTracer + mockMetricsTracer = sandbox.createStubInstance(MetricsTracer); + mockMetricsTracer.recordAttemptStart = sandbox.stub<[], void>(); + mockMetricsTracer.recordAttemptCompletion = sandbox.stub< + [status?: number], + void + >(); + mockMetricsTracer.extractGfeLatency = sandbox + .stub() + .callsFake((header: string) => { + if (header === 'gfet4t7; dur=90, afe; dur=30') { + return 90; + } + return null; + }) as sinon.SinonStub<[string], number | null>; + mockMetricsTracer.extractAfeLatency = sandbox + .stub() + .callsFake((header: string) => { + if (header === 'gfet4t7; dur=90, afe; dur=30') { + return 30; + } + return null; + }) as sinon.SinonStub<[string], number | null>; + mockMetricsTracer.recordGfeLatency = sandbox.stub< + [latency: number], + void + >(); + mockMetricsTracer.recordGfeConnectivityErrorCount = sandbox.stub< + [statusCode: number], + void + >(); + + // Mock MetricsTracerFactory + mockFactory = sandbox.createStubInstance(MetricsTracerFactory); + mockFactory.getCurrentTracer = sandbox + .stub() + .returns(mockMetricsTracer) as sinon.SinonStub< + [string], + MetricsTracer | null + >; + sandbox.stub(MetricsTracerFactory, 'getInstance').returns(mockFactory); + + // Mock GRPC call components + mockInterceptingCall = { + start: sinon.spy((metadata: grpc.Metadata, listener: grpc.Listener) => { + capturedListener = listener; + }), + }; + + mockNextCall = sinon.stub().returns(mockInterceptingCall); + + mockListener = { + onReceiveMetadata: sandbox.stub(), + onReceiveMessage: sandbox.stub(), + onReceiveStatus: sandbox.stub(), + }; + + serverTimingMetadata = new grpc.Metadata(); + serverTimingMetadata.set('content-type', 'application/grpc'); + serverTimingMetadata.set('date', 'Thu, 19 Jun 2020 00:01:02 GMT'); + serverTimingMetadata.set('server-timing', 'gfet4t7; dur=90, afe; dur=30'); + serverTimingMetadata.set( + 'alt-svc', + 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000', + ); + + emptyMetadata = new grpc.Metadata(); + + mockStatus = { + code: Status.OK, + details: 'OK', + metadata: new grpc.Metadata(), + }; + + mockOptions = { + method_definition: { + path: '/google.spanner.v1.Spanner/ExecuteSql', + }, + }; + testMetadata = new grpc.Metadata(); + testMetadata.set( + 'google-cloud-resource-prefix', + 'projects/test-project/instances/instance/databases/database-1', + ); + }); + + afterEach(() => { + sandbox.restore(); + }); + + describe('Metrics recorded from interceptor', () => { + it('AttemptMetrics', () => { + const interceptingCall = MetricInterceptor(mockOptions, mockNextCall); + + // Start recording attempt metrics at the beginning of the gRPC call + interceptingCall.start(testMetadata, mockListener); + assert.equal(mockMetricsTracer.recordAttemptStart.callCount, 1); + assert.equal(mockMetricsTracer.recordAttemptCompletion.callCount, 0); + + capturedListener.onReceiveStatus(mockStatus); + + // Complete attempt recording when status is received back from the call + assert.equal(mockMetricsTracer.recordAttemptStart.callCount, 1); + assert.equal(mockMetricsTracer.recordAttemptCompletion.callCount, 1); + }); + + it('GFE Metrics - Latency', () => { + const interceptingCall = MetricInterceptor(mockOptions, mockNextCall); + interceptingCall.start(testMetadata, mockListener); + + // duration value from the header's gfet4t7 value should be recorded as GFE latency + capturedListener.onReceiveMetadata(serverTimingMetadata); + capturedListener.onReceiveStatus(mockStatus); + assert.equal(mockMetricsTracer.recordGfeLatency.callCount, 1); + assert.equal( + mockMetricsTracer.recordGfeLatency.getCall(0).args, + Status.OK, + ); + assert.equal( + mockMetricsTracer.recordGfeConnectivityErrorCount.callCount, + 0, + ); + }); + + it('AFE Metrics - Latency', () => { + const interceptingCall = MetricInterceptor(mockOptions, mockNextCall); + interceptingCall.start(testMetadata, mockListener); + + // duration value from the header's afe value should be recorded as AFE latency + capturedListener.onReceiveMetadata(serverTimingMetadata); + capturedListener.onReceiveStatus(mockStatus); + assert.equal(mockMetricsTracer.recordAfeLatency.callCount, 1); + assert.equal( + mockMetricsTracer.recordAfeLatency.getCall(0).args, + Status.OK, + ); + assert.equal( + mockMetricsTracer.recordAfeConnectivityErrorCount.callCount, + 0, + ); + }); + + it('GFE Metrics - Connectivity Error Count', () => { + const interceptingCall = MetricInterceptor(mockOptions, mockNextCall); + interceptingCall.start(testMetadata, mockListener); + + // Calls received without latency values should increase connectivity error count + capturedListener.onReceiveMetadata(emptyMetadata); + capturedListener.onReceiveStatus(mockStatus); + assert.equal(mockMetricsTracer.recordGfeLatency.callCount, 0); + assert.equal( + mockMetricsTracer.recordGfeConnectivityErrorCount.callCount, + 1, + ); + assert.equal( + mockMetricsTracer.recordGfeConnectivityErrorCount.getCall(0).args, + Status.OK, + ); + }); + + it.skip('AFE Metrics - Connectivity Error Count', () => { + const interceptingCall = MetricInterceptor(mockOptions, mockNextCall); + interceptingCall.start(testMetadata, mockListener); + + // Calls received without latency values should increase connectivity error count + capturedListener.onReceiveMetadata(emptyMetadata); + capturedListener.onReceiveStatus(mockStatus); + assert.equal(mockMetricsTracer.recordAfeLatency.callCount, 0); + assert.equal( + mockMetricsTracer.recordAfeConnectivityErrorCount.callCount, + 1, + ); + assert.equal( + mockMetricsTracer.recordAfeConnectivityErrorCount.getCall(0).args, + Status.OK, + ); + }); + }); +}); diff --git a/handwritten/spanner/test/metrics/metrics-tracer-factory.ts b/handwritten/spanner/test/metrics/metrics-tracer-factory.ts new file mode 100644 index 00000000000..c5db377aeac --- /dev/null +++ b/handwritten/spanner/test/metrics/metrics-tracer-factory.ts @@ -0,0 +1,299 @@ +// 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 +// +// 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. + +import { + MeterProvider, + PeriodicExportingMetricReader, +} from '@opentelemetry/sdk-metrics'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import * as Constants from '../../src/metrics/constants'; +import {MetricsTracerFactory} from '../../src/metrics/metrics-tracer-factory'; +import {CloudMonitoringMetricsExporter} from '../../src/metrics/spanner-metrics-exporter'; + +describe('MetricsTracerFactory', () => { + let sandbox: sinon.SinonSandbox; + let mockExporter: CloudMonitoringMetricsExporter; + let recordAttemptLatencyStub: sinon.SinonStub; + let addAttemptCounterStub: sinon.SinonStub; + let recordOperationLatencyStub: sinon.SinonStub; + let addOperationCounterStub: sinon.SinonStub; + let recordGfeLatencyStub: sinon.SinonStub; + let addGfeConnectivityErrorCountStub: sinon.SinonStub; + + before(() => { + sandbox = sinon.createSandbox(); + + recordAttemptLatencyStub = sandbox.stub(); + addAttemptCounterStub = sandbox.stub(); + recordOperationLatencyStub = sandbox.stub(); + addOperationCounterStub = sandbox.stub(); + recordGfeLatencyStub = sandbox.stub(); + addGfeConnectivityErrorCountStub = sandbox.stub(); + + const meterStub = { + createHistogram: sandbox.stub(), + createCounter: sandbox.stub(), + }; + + // Stub the methods called by _createMetricInstruments + meterStub.createHistogram + .onFirstCall() + .returns({record: recordAttemptLatencyStub}) + .onSecondCall() + .returns({record: recordOperationLatencyStub}) + .onThirdCall() + .returns({record: recordGfeLatencyStub}); + + meterStub.createCounter + .onFirstCall() + .returns({add: addAttemptCounterStub}) + .onSecondCall() + .returns({add: addOperationCounterStub}) + .onThirdCall() + .returns({add: addGfeConnectivityErrorCountStub}); + + sandbox.stub(MeterProvider.prototype, 'getMeter').returns(meterStub as any); + + // metrics provider and related objects + mockExporter = sandbox.createStubInstance(CloudMonitoringMetricsExporter); + }); + + after(async () => { + sandbox.restore(); + await MetricsTracerFactory.resetInstance(); + }); + + beforeEach(async () => { + MetricsTracerFactory.enabled = true; + sandbox.resetHistory(); + await MetricsTracerFactory.resetInstance(); + const provider = + MetricsTracerFactory.getInstance('project-id')!.getMeterProvider(); + const reader = new PeriodicExportingMetricReader({ + exporter: mockExporter, + exportIntervalMillis: 60000, + }); + provider.addMetricReader(reader); + }); + + afterEach(async () => { + await MetricsTracerFactory.resetInstance(); + }); + + it('should use the set meter provider', async () => { + const factory = MetricsTracerFactory.getInstance('project-id'); + const tracer = factory!.createMetricsTracer( + 'some-method', + 'projects/project/instances/instance/databases/database', + '1.1a2bc3d4.1.1.1.1', + ); + + const operations = 3; + const attempts = 5; + for (let i = 0; i < operations; i++) { + tracer!.recordOperationStart(); + for (let j = 0; j < attempts; j++) { + tracer!.recordAttemptStart(); + // Simulate processing time during attempt + await new Promise(resolve => { + setTimeout(resolve, 50); + }); + tracer!.recordAttemptCompletion(); + } + tracer!.recordOperationCompletion(); + } + + assert.ok(recordOperationLatencyStub.calledWith(sinon.match.number)); + assert.strictEqual(recordOperationLatencyStub.callCount, operations); + + assert.ok(recordAttemptLatencyStub.calledWith(sinon.match.number)); + assert.strictEqual( + recordAttemptLatencyStub.callCount, + operations * attempts, + ); + }); + + it('should initialize metric instruments when enabled', () => { + const factory = MetricsTracerFactory.getInstance('project-id'); + + assert.deepStrictEqual(factory!.instrumentAttemptLatency, { + record: recordAttemptLatencyStub, + }); + assert.deepStrictEqual(factory!.instrumentAttemptCounter, { + add: addAttemptCounterStub, + }); + assert.deepStrictEqual(factory!.instrumentOperationLatency, { + record: recordOperationLatencyStub, + }); + assert.deepStrictEqual(factory!.instrumentOperationCounter, { + add: addOperationCounterStub, + }); + assert.deepStrictEqual(factory!.instrumentGfeLatency, { + record: recordGfeLatencyStub, + }); + assert.deepStrictEqual(factory!.instrumentGfeConnectivityErrorCount, { + add: addGfeConnectivityErrorCountStub, + }); + }); + + it('should create a MetricsTracer instance', () => { + const factory = MetricsTracerFactory.getInstance('project-id'); + const tracer = factory!.createMetricsTracer( + 'some-method', + 'method-name', + '1.1a2bc3d4.1.1.1.1', + ); + assert.ok(tracer); + }); + + it('should correctly set default attributes', () => { + const factory = MetricsTracerFactory.getInstance('project-id'); + const tracer = factory!.createMetricsTracer( + 'test-method', + 'projects/project/instances/instance/databases/database', + '1.1a2bc3d4.1.1.1.1', + ); + assert.strictEqual( + tracer!.clientAttributes[Constants.METRIC_LABEL_KEY_DATABASE], + 'database', + ); + assert.strictEqual( + tracer!.clientAttributes[Constants.METRIC_LABEL_KEY_METHOD], + 'test-method', + ); + assert.strictEqual( + tracer!.clientAttributes[Constants.MONITORED_RES_LABEL_KEY_INSTANCE], + 'instance', + ); + }); +}); + +describe('getInstanceAttributes', () => { + let factory: MetricsTracerFactory; + beforeEach(() => { + factory = new (MetricsTracerFactory as any)(); + }); + + afterEach(async () => { + await factory.resetMeterProvider(); + clearInterval(factory['_intervalTracerCleanup']); + }); + + it('should extract project, instance, and database from full resource path', () => { + const formattedName = 'projects/proj1/instances/inst1/databases/db1'; + const attrs = factory.getInstanceAttributes(formattedName); + assert.deepStrictEqual(attrs, { + project: 'proj1', + instance: 'inst1', + database: 'db1', + }); + }); + + it('should extract project and instance, and unknown database if database is missing', () => { + const formattedName = 'projects/proj2/instances/inst2'; + const attrs = factory.getInstanceAttributes(formattedName); + assert.deepStrictEqual(attrs, { + project: 'proj2', + instance: 'inst2', + database: 'unknown', + }); + }); + + it('should return unknown strings for all if input is empty', () => { + const attrs = factory.getInstanceAttributes(''); + assert.deepStrictEqual(attrs, { + project: 'unknown', + instance: 'unknown', + database: 'unknown', + }); + }); + + it('should return unknown strings for all if input is malformed', () => { + const attrs = factory.getInstanceAttributes('foo/bar/baz'); + assert.deepStrictEqual(attrs, { + project: 'unknown', + instance: 'unknown', + database: 'unknown', + }); + }); +}); + +describe('MetricsTracerFactory with set clock', () => { + let clock: sinon.SinonFakeTimers; + + beforeEach(async () => { + MetricsTracerFactory.enabled = true; + await MetricsTracerFactory.resetInstance(); + // Use fake timers to control the clock + clock = sinon.useFakeTimers(); + }); + + afterEach(() => { + // Restore the real timers + clock.restore(); + }); + + describe('_cleanMetricTracers', () => { + it('should prune stale tracers', () => { + const factory = MetricsTracerFactory.getInstance('test-project'); + assert(factory); + + factory.createMetricsTracer( + 'method1', + 'projects/p/instances/i/databases/d', + '1.1a2b3c.1.1.1.1', + ); + + // Advance the clock to make the tracer stale + clock.tick(Constants.TRACER_CLEANUP_THRESHOLD_MS); + + // Add another tracer to trigger pruning + factory.createMetricsTracer( + 'method2', + 'projects/p/instances/i/databases/d', + '2.1a2b3c.1.1.1.1', + ); + // Only most recent tracer should remain + assert.strictEqual(factory['_currentOperationTracers'].size, 1); + assert.ok(factory['_currentOperationTracers'].has('2.1a2b3c.1.1.1')); + }); + + it('should not prune recent tracers', () => { + const factory = MetricsTracerFactory.getInstance('test-project'); + assert(factory); + + factory.createMetricsTracer( + 'method1', + 'projects/p/instances/i/databases/d', + '1.1a2b3c.1.1.1.1', + ); + + // Advance the clock, but not enough to hit the threshold + clock.tick(Constants.TRACER_CLEANUP_INTERVAL_MS); + + // Add another tracer to trigger pruning + factory.createMetricsTracer( + 'method2', + 'projects/p/instances/i/databases/d', + '2.1a2b3c.1.1.1.1', + ); + + // Both tracers should be available + assert.strictEqual(factory['_currentOperationTracers'].size, 2); + assert.ok(factory['_currentOperationTracers'].has('1.1a2b3c.1.1.1')); + assert.ok(factory['_currentOperationTracers'].has('2.1a2b3c.1.1.1')); + }); + }); +}); diff --git a/handwritten/spanner/test/metrics/metrics-tracer.ts b/handwritten/spanner/test/metrics/metrics-tracer.ts new file mode 100644 index 00000000000..fef4e909944 --- /dev/null +++ b/handwritten/spanner/test/metrics/metrics-tracer.ts @@ -0,0 +1,299 @@ +// 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 +// +// 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. + +import {status as Status} from '@grpc/grpc-js'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import * as Constants from '../../src/metrics/constants'; +import {MetricsTracer} from '../../src/metrics/metrics-tracer'; + +import {MetricsTracerFactory} from '../../src/metrics/metrics-tracer-factory'; +import {Spanner} from '../../src'; + +const DATABASE = 'test-db'; +const INSTANCE = 'instance'; +const PROJECT_ID = 'project_id'; +const METHOD = 'test-method'; +const REQUEST = 'test-request'; + +describe('MetricsTracer', () => { + let tracer: MetricsTracer; + let fakeAttemptCounter: any; + let fakeAttemptLatency: any; + let fakeOperationCounter: any; + let fakeOperationLatency: any; + let fakeGfeCounter: any; + let fakeGfeLatency: any; + let fakeAfeCounter: any; + let fakeAfeLatency: any; + let sandbox: sinon.SinonSandbox; + beforeEach(() => { + sandbox = sinon.createSandbox(); + fakeAttemptCounter = { + add: sinon.spy(), + }; + + fakeAttemptLatency = { + record: sinon.spy(), + }; + + fakeOperationCounter = { + add: sinon.spy(), + }; + + fakeOperationLatency = { + record: sinon.spy(), + }; + + fakeGfeCounter = { + add: sinon.spy(), + }; + + fakeGfeLatency = { + record: sinon.spy(), + }; + + fakeAfeCounter = { + add: sinon.spy(), + }; + + fakeAfeLatency = { + record: sinon.spy(), + }; + + tracer = new MetricsTracer( + fakeAttemptCounter, + fakeAttemptLatency, + fakeOperationCounter, + fakeOperationLatency, + fakeGfeCounter, + fakeGfeLatency, + fakeAfeCounter, + fakeAfeLatency, + true, // enabled, + DATABASE, + INSTANCE, + PROJECT_ID, + METHOD, + REQUEST, + ); + }); + + afterEach(() => { + sandbox.restore(); + }); + + describe('recordAttemptCompletion', () => { + it('should record attempt latency when enabled', () => { + tracer.recordOperationStart(); + tracer.recordAttemptStart(); + assert.ok(tracer.currentOperation!.currentAttempt); + assert.ok(tracer.currentOperation!.currentAttempt.startTime); + assert.strictEqual(tracer.currentOperation!.attemptCount, 1); + + tracer.recordAttemptCompletion(Status.OK); + + assert.strictEqual(fakeAttemptLatency.record.calledOnce, true); + const [[latency, otelAttrs]] = fakeAttemptLatency.record.args; + assert.strictEqual(typeof latency, 'number'); + assert.strictEqual( + otelAttrs[Constants.METRIC_LABEL_KEY_STATUS], + Status[Status.OK], + ); + }); + + it('should do nothing if disabled', () => { + tracer.enabled = false; + tracer.recordAttemptStart(); + tracer.recordAttemptCompletion(Status.OK); + assert.strictEqual(fakeAttemptLatency.record.called, false); + }); + }); + + describe('recordOperationCompletion', () => { + it('should record operation and attempt metrics when enabled', () => { + const factory = sandbox + .stub(MetricsTracerFactory, 'getInstance') + .returns({ + clearCurrentTracer: sinon.spy(), + } as any); + tracer.recordOperationStart(); + assert.ok(tracer.currentOperation!.startTime); + tracer.recordAttemptStart(); + tracer.recordAttemptCompletion(Status.OK); + tracer.recordOperationCompletion(); + + assert.strictEqual(fakeOperationCounter.add.calledOnce, true); + assert.strictEqual(fakeAttemptCounter.add.calledOnce, true); + assert.strictEqual(fakeOperationLatency.record.calledOnce, true); + + const [[_, opAttrs]] = fakeOperationLatency.record.args; + assert.strictEqual(opAttrs[Constants.METRIC_LABEL_KEY_STATUS], 'OK'); + }); + + it('should do nothing if disabled', () => { + tracer.enabled = false; + tracer.recordOperationCompletion(); + assert.strictEqual(fakeOperationCounter.add.called, false); + assert.strictEqual(fakeOperationLatency.record.called, false); + }); + }); + + describe('recordGfeLatency', () => { + it('should record GFE latency if enabled', () => { + tracer.enabled = true; + tracer.gfeLatency = 123; + tracer.recordGfeLatency(Status.OK); + assert.strictEqual(fakeGfeLatency.record.calledOnce, true); + }); + + it('should not record if disabled', () => { + tracer.enabled = false; + tracer.gfeLatency = 123; + tracer.recordGfeLatency(Status.OK); + assert.strictEqual(fakeGfeLatency.record.called, false); + }); + }); + + describe('recordGfeConnectivityErrorCount', () => { + it('should increment GFE error counter if enabled', () => { + tracer.recordGfeConnectivityErrorCount(Status.OK); + assert.strictEqual(fakeGfeCounter.add.calledOnce, true); + }); + + it('should not increment if disabled', () => { + tracer.enabled = false; + tracer.recordGfeConnectivityErrorCount(Status.OK); + assert.strictEqual(fakeGfeCounter.add.called, false); + }); + }); + + describe('recordAfeLatency', () => { + afterEach(() => { + Spanner._resetAFEServerTimingForTest(); + process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] = 'false'; + }); + + it('should record AFE latency if enabled', () => { + tracer.enabled = true; + tracer.afeLatency = 123; + tracer.recordAfeLatency(Status.OK); + assert.strictEqual(fakeAfeLatency.record.calledOnce, true); + }); + + it('should not record if AFE server timing is disabled', () => { + tracer.enabled = true; + Spanner._resetAFEServerTimingForTest(); + process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] = 'true'; + tracer.afeLatency = 123; + tracer.recordAfeLatency(Status.OK); + assert.strictEqual(fakeAfeLatency.record.called, false); + }); + + it('should not record if metrics are disabled', () => { + tracer.enabled = false; + tracer.afeLatency = 123; + tracer.recordAfeLatency(Status.OK); + assert.strictEqual(fakeAfeLatency.record.called, false); + }); + }); + + describe('recordGfeConnectivityErrorCount', () => { + afterEach(() => { + Spanner._resetAFEServerTimingForTest(); + process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] = 'false'; + }); + + it('should increment AFE error counter if enabled', () => { + tracer.enabled = true; + tracer.recordAfeConnectivityErrorCount(Status.OK); + assert.strictEqual(fakeAfeCounter.add.calledOnce, true); + }); + + it('should not increment if metrics are disabled', () => { + tracer.enabled = false; + tracer.recordAfeConnectivityErrorCount(Status.OK); + assert.strictEqual(fakeAfeCounter.add.called, false); + }); + + it('should not increment if AFE server timing is disabled', () => { + tracer.enabled = true; + Spanner._resetAFEServerTimingForTest(); + process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] = 'true'; + tracer.recordAfeConnectivityErrorCount(Status.OK); + assert.strictEqual(fakeAfeCounter.add.called, false); + }); + }); + + describe('extractGfeLatency & extractAfeLatency', () => { + let tracer: MetricsTracer; + beforeEach(() => { + tracer = new MetricsTracer( + null, + null, + null, + null, + null, + null, + null, + null, + true, + DATABASE, + INSTANCE, + PROJECT_ID, + METHOD, + REQUEST, + ); + }); + + it('should extract afe and gfe latency from a valid server-timing header', () => { + const header = 'gfet4t7; dur=123, afe; dur=30, other=value'; + const gfeLatency = tracer.extractGfeLatency(header); + assert.strictEqual(gfeLatency, 123); + const afeLatency = tracer.extractAfeLatency(header); + assert.strictEqual(afeLatency, 30); + }); + + it('should return null if header is undefined', () => { + const gfeLatency = tracer.extractGfeLatency(undefined as any); + assert.strictEqual(gfeLatency, null); + const afeLatency = tracer.extractAfeLatency(undefined as any); + assert.strictEqual(afeLatency, null); + }); + + it('should return null if header does not match expected format', () => { + const header = 'some-other-header'; + const gfeLatency = tracer.extractGfeLatency(header); + assert.strictEqual(gfeLatency, null); + const afeLatency = tracer.extractAfeLatency(header); + assert.strictEqual(afeLatency, null); + }); + + it('should extract only the gfe latency if extra data is present', () => { + const header = 'gfet4t7; dur=456; other=value'; + const gfeLatency = tracer.extractGfeLatency(header); + assert.strictEqual(gfeLatency, 456); + const afeLatency = tracer.extractAfeLatency(header); + assert.strictEqual(afeLatency, null); + }); + + it('should extract only the afe latency if extra data is present', () => { + const header = 'other=value, afe; dur=30; '; + const gfeLatency = tracer.extractGfeLatency(header); + assert.strictEqual(gfeLatency, null); + const afeLatency = tracer.extractAfeLatency(header); + assert.strictEqual(afeLatency, 30); + }); + }); +}); diff --git a/handwritten/spanner/test/metrics/metrics.ts b/handwritten/spanner/test/metrics/metrics.ts new file mode 100644 index 00000000000..5344fdc58cc --- /dev/null +++ b/handwritten/spanner/test/metrics/metrics.ts @@ -0,0 +1,746 @@ +// 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 * as sinon from 'sinon'; +import * as assert from 'assert'; +import {grpc} from 'google-gax'; +import * as mock from '../mockserver/mockspanner'; +import {MockError, SimulatedExecutionTime} from '../mockserver/mockspanner'; +import {Database, Instance, Spanner} from '../../src'; +import {MetricsTracerFactory} from '../../src/metrics/metrics-tracer-factory'; +import {MetricsTracer} from '../../src/metrics/metrics-tracer'; +import {MetricReader} from '@opentelemetry/sdk-metrics'; +import {CloudMonitoringMetricsExporter} from '../../src/metrics/spanner-metrics-exporter'; +import { + METRIC_NAME_OPERATION_LATENCIES, + METRIC_NAME_ATTEMPT_LATENCIES, + METRIC_NAME_OPERATION_COUNT, + METRIC_NAME_ATTEMPT_COUNT, + METRIC_NAME_GFE_LATENCIES, + METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, + METRIC_NAME_AFE_LATENCIES, + METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT, +} from '../../src/metrics/constants'; + +describe('Test metrics with mock server', () => { + let sandbox: sinon.SinonSandbox; + let instance: Instance; + let spanner: Spanner; + let port: number; + let dbCounter = 0; + const selectSql = 'SELECT NUM, NAME FROM NUMBERS'; + const server = new grpc.Server(); + const spannerMock = mock.createMockSpanner(server); + const PROJECT_ID = 'test-project'; + + class InMemoryMetricReader extends MetricReader { + protected async onForceFlush(): Promise {} + protected async onShutdown(): Promise {} + } + + function newTestDatabase(): Database { + return instance.database(`database-${++dbCounter}`, undefined); + } + + function assertApprox(expected: number, actual: number, delta: number) { + assert.ok( + Math.abs(expected - actual) <= delta, + `Expected value of ${expected} and actual value of ${actual} is greater than the approximation delta (${delta})`, + ); + } + + function compareAttributes(expected: object, actual: object): boolean { + // Check that all expected keys match in actual + for (const key of Object.keys(expected)) { + if ((actual as any)[key] !== (expected as any)[key]) { + return false; + } + } + // Check that actual does not contain extra keys + for (const key of Object.keys(actual)) { + // Check if the key in 'actual' is not present in 'expected' + if (!Object.prototype.hasOwnProperty.call(expected, key)) { + return false; + } + } + return true; + } + + function getMetricData(resourceMetrics, metricName: string) { + const filteredMetrics = resourceMetrics.scopeMetrics.flatMap(scopeMetric => + scopeMetric.metrics.filter( + metric => metric.descriptor.name === metricName, + ), + ); + assert.ok( + filteredMetrics.length > 0, + `No metric entry found with name: ${metricName}`, + ); + assert.strictEqual( + filteredMetrics.length, + 1, + `Found multiple metrics with name: ${metricName}`, + ); + return filteredMetrics[0]; + } + + function hasMetricData(resourceMetrics, metricName: string): boolean { + const filteredMetrics = resourceMetrics.scopeMetrics.flatMap(scopeMetric => + scopeMetric.metrics.filter( + metric => metric.descriptor.name === metricName, + ), + ); + return filteredMetrics.length > 0; + } + + function getAggregatedValue(metricsData: any, attributes: any) { + const dataPoint = metricsData.dataPoints.filter(dp => + compareAttributes(dp.attributes, attributes), + ); + assert.strictEqual( + dataPoint.length, + 1, + 'Failed to filter for attribute values.', + ); + switch (metricsData.descriptor.type) { + case 'HISTOGRAM': + return dataPoint[0].value.sum / dataPoint[0].value.count; + case 'COUNTER': + return dataPoint[0].value; + default: + return 0; + } + } + + async function setupMockSpanner() { + sandbox = sinon.createSandbox(); + port = await new Promise((resolve, reject) => { + server.bindAsync( + '0.0.0.0:0', + grpc.ServerCredentials.createInsecure(), + (err, assignedPort) => { + if (err) { + reject(err); + } else { + resolve(assignedPort); + } + }, + ); + }); + spannerMock.putStatementResult( + selectSql, + mock.StatementResult.resultSet(mock.createSimpleResultSet()), + ); + sandbox + .stub(MetricsTracerFactory as any, '_detectClientLocation') + .resolves('test-location'); + await MetricsTracerFactory.resetInstance(); + if ( + Object.prototype.hasOwnProperty.call( + process.env, + 'SPANNER_DISABLE_BUILTIN_METRICS', + ) + ) { + sandbox.replace(process.env, 'SPANNER_DISABLE_BUILTIN_METRICS', 'false'); + } else { + sandbox.define(process.env, 'SPANNER_DISABLE_BUILTIN_METRICS', 'false'); + } + await MetricsTracerFactory.resetInstance(); + MetricsTracerFactory.enabled = true; + spanner = new Spanner({ + projectId: PROJECT_ID, + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + }); + instance = spanner.instance('instance'); + } + + before(async () => { + await MetricsTracerFactory.resetInstance(); + await setupMockSpanner(); + }); + + after(async () => { + spanner.close(); + server.tryShutdown(() => {}); + sandbox.restore(); + await MetricsTracerFactory.resetInstance(); + MetricsTracerFactory.enabled = false; + }); + + describe('With InMemMetricReader', async () => { + let reader: InMemoryMetricReader; + let factory: MetricsTracerFactory | null; + let gfeStub; + let afeStub; + let exporterStub; + const MIN_LATENCY = 0; + const commonAttributes = { + instance_id: 'instance', + status: 'OK', + }; + + before(() => { + exporterStub = sinon.stub( + CloudMonitoringMetricsExporter.prototype, + 'export', + ); + }); + + after(() => { + exporterStub.restore(); + }); + + beforeEach(async function () { + // Increase the timeout because the MeterProvider shutdown exceed + // the default 10s timeout. + this.timeout(50000); + spannerMock.resetRequests(); + spannerMock.removeExecutionTimes(); + // Reset the MetricsFactoryReader to an in-memory reader for the tests + MetricsTracerFactory.enabled = true; + factory = MetricsTracerFactory.getInstance(PROJECT_ID); + await factory!.resetMeterProvider(); + reader = new InMemoryMetricReader(); + factory!.getMeterProvider([reader]); + }); + + afterEach(async () => { + gfeStub?.restore(); + afeStub?.restore(); + await factory?.resetMeterProvider(); + await MetricsTracerFactory.resetInstance(); + }); + + it('should have correct latency values in metrics', async () => { + gfeStub = sandbox + .stub(MetricsTracer.prototype, 'extractGfeLatency') + .callsFake(() => 123); + afeStub = sandbox + .stub(MetricsTracer.prototype, 'extractAfeLatency') + .callsFake(() => 30); + const database = newTestDatabase(); + const startTime = new Date(); + await database.run(selectSql); + const endTime = new Date(); + + const elapsedTime = endTime.valueOf() - startTime.valueOf(); + + const methods = ['createSession', 'executeStreamingSql']; + + const {resourceMetrics} = await reader.collect(); + const operationCountData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_COUNT, + ); + const gfeLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_GFE_LATENCIES, + ); + const afeLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_AFE_LATENCIES, + ); + const attemptCountData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_COUNT, + ); + const operationLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_LATENCIES, + ); + const attemptLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_LATENCIES, + ); + + let totalOperationLatency = 0; + methods.forEach(method => { + const attributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: method, + }; + const operationCount = getAggregatedValue( + operationCountData, + attributes, + ); + assert.strictEqual(operationCount, 1); + + const attemptCount = getAggregatedValue(attemptCountData, attributes); + assert.strictEqual(attemptCount, 1); + + const operationLatency = getAggregatedValue( + operationLatenciesData, + attributes, + ); + totalOperationLatency += operationLatency; + + const attemptLatency = getAggregatedValue( + attemptLatenciesData, + attributes, + ); + // Since we only have one attempt, the attempt latency should be fairly close to the operation latency + assertApprox(operationLatency, attemptLatency, 30); + + const gfeLatency = getAggregatedValue(gfeLatenciesData, attributes); + assert.strictEqual(gfeLatency, 123); + + const afeLatency = getAggregatedValue(afeLatenciesData, attributes); + assert.strictEqual(afeLatency, 30); + }); + + // check that the latency matches up with the measured elapsed time within 10ms + assertApprox(elapsedTime, totalOperationLatency, 10); + + // Make sure no GFE/AFE connectivity errors ar emitted since we got GFE latencies + const gfeMissingData = hasMetricData( + resourceMetrics, + METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, + ); + const afeMissingData = hasMetricData( + resourceMetrics, + METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT, + ); + + assert.ok(!gfeMissingData); + assert.ok(!afeMissingData); + + await database.close(); + }); + + it('should increase attempts on retries', async () => { + gfeStub = sandbox + .stub(MetricsTracer.prototype, 'extractGfeLatency') + .callsFake(() => 123); + afeStub = sandbox + .stub(MetricsTracer.prototype, 'extractAfeLatency') + .callsFake(() => 30); + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + + await database.run(selectSql); + const {resourceMetrics} = await reader.collect(); + + const operationCountData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_COUNT, + ); + const attemptCountData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_COUNT, + ); + const operationLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_LATENCIES, + ); + const attemptLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_LATENCIES, + ); + const gfeLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_GFE_LATENCIES, + ); + const afeLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_AFE_LATENCIES, + ); + + const sessionAttributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: 'createSession', + }; + // Verify batchCreateSession metrics are unaffected + assert.strictEqual( + getAggregatedValue(operationCountData, sessionAttributes), + 1, + ); + getAggregatedValue(operationLatenciesData, sessionAttributes); + assert.strictEqual( + getAggregatedValue(attemptCountData, sessionAttributes), + 1, + ); + getAggregatedValue(attemptLatenciesData, sessionAttributes); + assert.strictEqual( + getAggregatedValue(gfeLatenciesData, sessionAttributes), + 123, + ); + assert.strictEqual( + getAggregatedValue(afeLatenciesData, sessionAttributes), + 30, + ); + + const executeAttributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: 'executeStreamingSql', + }; + const executeUnavailableAttributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: 'executeStreamingSql', + status: 'UNAVAILABLE', + }; + // Verify executeStreamingSql has 2 attempts and 1 operation + assert.strictEqual( + 1, + getAggregatedValue(operationCountData, executeAttributes), + ); + getAggregatedValue(operationLatenciesData, executeAttributes); + assert.strictEqual( + 1, + getAggregatedValue(attemptCountData, executeAttributes), + ); + assert.strictEqual( + 1, + getAggregatedValue(attemptCountData, executeUnavailableAttributes), + ); + getAggregatedValue(attemptLatenciesData, executeAttributes); + assert.strictEqual( + 123, + getAggregatedValue(gfeLatenciesData, executeAttributes), + ); + assert.strictEqual( + 30, + getAggregatedValue(afeLatenciesData, executeAttributes), + ); + }); + + it('should create connectivity error count metric if GFE/AFE latency is not in header', async () => { + gfeStub = sandbox + .stub(MetricsTracer.prototype, 'extractGfeLatency') + .callsFake(() => null); + afeStub = sandbox + .stub(MetricsTracer.prototype, 'extractAfeLatency') + .callsFake(() => null); + const database = newTestDatabase(); + await database.run(selectSql); + const {resourceMetrics} = await reader.collect(); + + const operationCountData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_COUNT, + ); + const attemptCountData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_COUNT, + ); + const operationLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_LATENCIES, + ); + const attemptLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_LATENCIES, + ); + const connectivityErrorCountData = getMetricData( + resourceMetrics, + METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, + ); + + // Verify GFE AFE latency doesn't exist + assert.ok(!hasMetricData(resourceMetrics, METRIC_NAME_GFE_LATENCIES)); + assert.ok(!hasMetricData(resourceMetrics, METRIC_NAME_AFE_LATENCIES)); + const methods = ['createSession', 'executeStreamingSql']; + methods.forEach(method => { + const attributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: method, + }; + // Verify attempt and operational metrics are unaffected + assert.strictEqual( + getAggregatedValue(operationCountData, attributes), + 1, + ); + getAggregatedValue(operationLatenciesData, attributes); + assert.strictEqual(getAggregatedValue(attemptCountData, attributes), 1); + getAggregatedValue(attemptLatenciesData, attributes); + + // Verify that GFE AFE connectivity error count increased + assert.strictEqual( + getAggregatedValue(connectivityErrorCountData, attributes), + 1, + ); + }); + }); + + it('should increase attempts on retries for non streaming calls with gax options', async () => { + gfeStub = sandbox + .stub(MetricsTracer.prototype, 'extractGfeLatency') + .callsFake(() => 123); + afeStub = sandbox + .stub(MetricsTracer.prototype, 'extractAfeLatency') + .callsFake(() => 30); + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.commit, + SimulatedExecutionTime.ofError(err), + ); + + const GAX_OPTIONS = { + retry: { + retryCodes: [4, 8, 14], + backoffSettings: { + initialRetryDelayMillis: 1000, + retryDelayMultiplier: 1.3, + maxRetryDelayMillis: 32000, + initialRpcTimeoutMillis: 60000, + rpcTimeoutMultiplier: 1, + maxRpcTimeoutMillis: 60000, + totalTimeoutMillis: 600000, + }, + }, + }; + await database.runTransactionAsync(async tx => { + await tx.run(selectSql); + // Commit RPC will be retried by GAX + await tx.commit({gaxOptions: GAX_OPTIONS}); + }); + + const {resourceMetrics} = await reader.collect(); + + const operationCountData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_COUNT, + ); + // Attempt count is correct here but status of attempts are not correct + const attemptCountData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_COUNT, + ); + const operationLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_LATENCIES, + ); + const attemptLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_LATENCIES, + ); + const gfeLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_GFE_LATENCIES, + ); + const afeLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_AFE_LATENCIES, + ); + + const sessionAttributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: 'createSession', + }; + // Verify createSession metrics are unaffected + assert.strictEqual( + 1, + getAggregatedValue(operationCountData, sessionAttributes), + ); + assert.ok(getAggregatedValue(operationLatenciesData, sessionAttributes)); + assert.strictEqual( + 1, + getAggregatedValue(attemptCountData, sessionAttributes), + ); + assert.ok(getAggregatedValue(attemptLatenciesData, sessionAttributes)); + assert.strictEqual( + 123, + getAggregatedValue(gfeLatenciesData, sessionAttributes), + ); + assert.strictEqual( + 30, + getAggregatedValue(afeLatenciesData, sessionAttributes), + ); + + const executeAttributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: 'executeStreamingSql', + }; + + // Verify executeStreamingSql metrics are unaffected + assert.strictEqual( + 1, + getAggregatedValue(operationCountData, executeAttributes), + ); + assert.ok(getAggregatedValue(operationLatenciesData, executeAttributes)); + assert.strictEqual( + 1, + getAggregatedValue(attemptCountData, executeAttributes), + ); + assert.ok(getAggregatedValue(attemptLatenciesData, executeAttributes)); + assert.strictEqual( + 123, + getAggregatedValue(gfeLatenciesData, executeAttributes), + ); + assert.strictEqual( + 30, + getAggregatedValue(afeLatenciesData, executeAttributes), + ); + + // Verify that commit metrics have 2 attempts and 1 operation + const commitOkAttributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: 'commit', + }; + const commitUnavailableAttributes = { + ...commitOkAttributes, + status: 'UNAVAILABLE', + }; + + assert.strictEqual( + getAggregatedValue(operationCountData, commitOkAttributes), + 1, + ); + + assert.ok(getAggregatedValue(operationLatenciesData, commitOkAttributes)); + assert.strictEqual( + 1, + getAggregatedValue(attemptCountData, commitOkAttributes), + '1 of 2 attempts for Commit should have status: OK.', + ); + assert.strictEqual( + 1, + getAggregatedValue(attemptCountData, commitUnavailableAttributes), + '1 of 2 attempts for Commit should have status: Unavailable.', + ); + assert.ok(getAggregatedValue(attemptLatenciesData, commitOkAttributes)); + assert.ok( + getAggregatedValue(attemptLatenciesData, commitUnavailableAttributes), + ); + assert.strictEqual( + 123, + getAggregatedValue(gfeLatenciesData, commitOkAttributes), + ); + assert.strictEqual( + 30, + getAggregatedValue(afeLatenciesData, commitOkAttributes), + ); + }); + + it('should have correct latency values in metrics except AFE when AFE Server timing is disabled', async () => { + Spanner._resetAFEServerTimingForTest(); + process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] = 'true'; + gfeStub = sandbox + .stub(MetricsTracer.prototype, 'extractGfeLatency') + .callsFake(() => 123); + afeStub = sandbox + .stub(MetricsTracer.prototype, 'extractAfeLatency') + .callsFake(() => 30); + const database = newTestDatabase(); + const startTime = new Date(); + await database.run(selectSql); + const endTime = new Date(); + + const elapsedTime = endTime.valueOf() - startTime.valueOf(); + + const methods = ['createSession', 'executeStreamingSql']; + + const {resourceMetrics} = await reader.collect(); + const operationCountData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_COUNT, + ); + const gfeLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_GFE_LATENCIES, + ); + const attemptCountData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_COUNT, + ); + const operationLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_OPERATION_LATENCIES, + ); + const attemptLatenciesData = getMetricData( + resourceMetrics, + METRIC_NAME_ATTEMPT_LATENCIES, + ); + + let totalOperationLatency = 0; + methods.forEach(method => { + const attributes = { + ...commonAttributes, + database: `database-${dbCounter}`, + method: method, + }; + const operationCount = getAggregatedValue( + operationCountData, + attributes, + ); + assert.strictEqual(operationCount, 1); + + const attemptCount = getAggregatedValue(attemptCountData, attributes); + assert.strictEqual(attemptCount, 1); + + const operationLatency = getAggregatedValue( + operationLatenciesData, + attributes, + ); + totalOperationLatency += operationLatency; + + const attemptLatency = getAggregatedValue( + attemptLatenciesData, + attributes, + ); + // Since we only have one attempt, the attempt latency should be fairly close to the operation latency + assertApprox(operationLatency, attemptLatency, 30); + + const gfeLatency = getAggregatedValue(gfeLatenciesData, attributes); + assert.strictEqual(gfeLatency, 123); + }); + + // check that the latency matches up with the measured elapsed time within 10ms + assertApprox(elapsedTime, totalOperationLatency, 10); + + // Make sure no GFE connectivity errors are not emitted since we got GFE latencies + const gfeMissingData = hasMetricData( + resourceMetrics, + METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, + ); + assert.ok(!gfeMissingData); + + // Make sure no AFE metrics are not emitted since AFE is disabled. + const afeMissingData = hasMetricData( + resourceMetrics, + METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT, + ); + const afeLatencyMissingData = hasMetricData( + resourceMetrics, + METRIC_NAME_AFE_LATENCIES, + ); + assert.ok(!afeMissingData); + assert.ok(!afeLatencyMissingData); + + await database.close(); + Spanner._resetAFEServerTimingForTest(); + process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] = 'false'; + }); + }); +}); diff --git a/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts b/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts new file mode 100644 index 00000000000..cd1bb178705 --- /dev/null +++ b/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts @@ -0,0 +1,269 @@ +// 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 +// +// 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. + +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {MeterProvider, MetricReader} from '@opentelemetry/sdk-metrics'; +import {GoogleAuth} from 'google-auth-library'; +import { + CloudMonitoringMetricsExporter, + MAX_BATCH_EXPORT_SIZE, +} from '../../src/metrics/spanner-metrics-exporter'; +import { + SPANNER_METER_NAME, + METRIC_NAME_ATTEMPT_COUNT, + METRIC_NAME_ATTEMPT_LATENCIES, + METRIC_NAME_OPERATION_COUNT, + METRIC_NAME_OPERATION_LATENCIES, + METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, + METRIC_NAME_GFE_LATENCIES, +} from '../../src/metrics/constants'; +import {Counter, Meter, Histogram} from '@opentelemetry/api'; +import {ExportResult, ExportResultCode} from '@opentelemetry/core'; +import {Resource} from '@opentelemetry/resources'; + +const PROJECT_ID = 'test-project'; +const INSTANCE_ID = 'test-instance'; +const CLIENT_HASH = 'test-hash'; +const INSTANCE_CONFIG = 'test-config'; +const DATABASE_ID = 'test-db'; +const LOCATION = 'test-location'; + +const auth = new GoogleAuth(); + +// Ensure custom exporter is valid +describe('CustomExporter', () => { + it('should construct an exporter', () => { + const exporter = new CloudMonitoringMetricsExporter({auth}, PROJECT_ID); + assert.ok(typeof exporter.export === 'function'); + assert.ok(typeof exporter.shutdown === 'function'); + }); + + it('should construct an exporter with credentials', () => { + const auth = new GoogleAuth({ + credentials: { + client_email: 'fake', + private_key: '', + }, + }); + auth.getProjectId = sinon.stub().resolves(PROJECT_ID); + const exporter = new CloudMonitoringMetricsExporter({auth}, PROJECT_ID); + + assert(exporter); + }); + + it('should be able to shutdown', async () => { + const exporter = new CloudMonitoringMetricsExporter({auth}, PROJECT_ID); + await assert.doesNotReject(exporter.shutdown()); + }); + + it('should be able to force flush', async () => { + const exporter = new CloudMonitoringMetricsExporter({auth}, PROJECT_ID); + await assert.doesNotReject(exporter.forceFlush()); + }); +}); + +// Verify that the export call will convert and send the requests out. +describe('Export', () => { + class InMemoryMetricReader extends MetricReader { + protected async onForceFlush(): Promise {} + protected async onShutdown(): Promise {} + } + let reader: MetricReader; + let meterProvider: MeterProvider; + let meter: Meter; + let attempt_counter: Counter; + let operation_counter: Counter; + let gfe_connectivity_error_count: Counter; + let attempt_latency: Histogram; + let operation_latency: Histogram; + let gfe_latency: Histogram; + let metricAttributes: {[key: string]: string}; + let exporter: CloudMonitoringMetricsExporter; + + beforeEach(() => { + exporter = new CloudMonitoringMetricsExporter({auth}, PROJECT_ID); + reader = new InMemoryMetricReader(); + const resource = new Resource({ + ['project_id']: PROJECT_ID, + ['client_hash']: CLIENT_HASH, + ['location']: LOCATION, + ['instance_id']: INSTANCE_ID, + ['instance_config']: INSTANCE_CONFIG, + }); + meterProvider = new MeterProvider({ + resource: resource, + readers: [reader], + }); + meter = meterProvider.getMeter(SPANNER_METER_NAME); + metricAttributes = { + client_uid: 'test_uid', + client_name: 'test_name', + database: DATABASE_ID, + method: 'test_method', + status: 'test_status', + other: 'ignored', + }; + + attempt_counter = meter.createCounter(METRIC_NAME_ATTEMPT_COUNT, { + description: 'Count of attempts', + unit: '1', + }); + + operation_counter = meter.createCounter(METRIC_NAME_OPERATION_COUNT, { + description: 'Count of operations', + unit: '1', + }); + + gfe_connectivity_error_count = meter.createCounter( + METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT, + { + description: 'Count of missing headers', + unit: '1', + }, + ); + + attempt_latency = meter.createHistogram(METRIC_NAME_ATTEMPT_LATENCIES, { + description: 'Test attempt latencies in ms', + unit: 'ms', + }); + + operation_latency = meter.createHistogram(METRIC_NAME_OPERATION_LATENCIES, { + description: 'Test operation latencies in ms', + unit: 'ms', + }); + + gfe_latency = meter.createHistogram(METRIC_NAME_GFE_LATENCIES, { + description: 'Test GFE latencies in ms', + unit: 'ms', + }); + }); + + it('should export GCM metrics', async () => { + attempt_counter.add(10, metricAttributes); + operation_counter.add(25, metricAttributes); + gfe_connectivity_error_count.add(12, metricAttributes); + attempt_latency.record(30, metricAttributes); + operation_latency.record(45, metricAttributes); + gfe_latency.record(22, metricAttributes); + + const {errors, resourceMetrics} = await reader.collect(); + if (errors.length !== 0) { + throw errors; + } + + const sendTimeSeriesStub = sinon + .stub(exporter as any, '_sendTimeSeries') + .resolves(); + + await new Promise(resolve => { + exporter.export(resourceMetrics, result => { + if (result.error) { + console.error(result.error); + } + resolve(result); + }); + }); + + assert(sendTimeSeriesStub.calledOnce); + + const [timeseries] = sendTimeSeriesStub.getCall(0).args; + + assert.strictEqual(timeseries.length, 6); + }); + + it('should exit early if resource metrics are empty', async () => { + const {errors, resourceMetrics} = await reader.collect(); + + if (errors.length !== 0) { + throw errors; + } + const sendTimeSeriesStub = sinon + .stub(exporter as any, '_sendTimeSeries') + .resolves(); + + await new Promise(resolve => { + exporter.export(resourceMetrics, result => { + if (result.error) { + console.error(result.error); + } + resolve(result); + }); + }); + + assert(sendTimeSeriesStub.notCalled); + }); + + it('should handle failed send during time series export with callback', async () => { + const sendTimeSeriesStub = sinon + .stub(exporter as any, '_sendTimeSeries') + .rejects(new Error('Network error')); + + attempt_counter.add(10, metricAttributes); + + const {resourceMetrics} = await reader.collect(); + + const resultCallbackSpy = sinon.spy(); + + exporter.export(resourceMetrics, resultCallbackSpy); + + await new Promise(resolve => setImmediate(resolve)); + + const callbackResult = resultCallbackSpy.getCall(0).args[0]; + assert.strictEqual(callbackResult.code, ExportResultCode.FAILED); + assert.strictEqual(callbackResult.error.message, 'Network error'); + + assert(sendTimeSeriesStub.calledOnce); + }); + + it('should batch exports into multiple calls', async () => { + // Create metircs larger than the batch size + const numberOfDistinctMetrics = MAX_BATCH_EXPORT_SIZE * 2 + 1; + for (let i = 0; i < numberOfDistinctMetrics; i++) { + attempt_counter.add(1, {...metricAttributes, testId: `batch-test-${i}`}); + } + + const {resourceMetrics} = await reader.collect(); + + const sendTimeSeriesStub = sinon + .stub(exporter as any, '_sendTimeSeries') + .resolves(); + const resultCallbackSpy = sinon.spy(); + + exporter.export(resourceMetrics, resultCallbackSpy); + + await new Promise(resolve => setImmediate(resolve)); + + // Confirm number of metrics for each batch + const expectedNumberOfCalls = Math.ceil( + numberOfDistinctMetrics / MAX_BATCH_EXPORT_SIZE, + ); + assert.strictEqual(sendTimeSeriesStub.callCount, expectedNumberOfCalls); + assert.strictEqual( + sendTimeSeriesStub.getCall(0).args[0].length, + MAX_BATCH_EXPORT_SIZE, + ); + assert.strictEqual( + sendTimeSeriesStub.getCall(1).args[0].length, + MAX_BATCH_EXPORT_SIZE, + ); + assert.strictEqual( + sendTimeSeriesStub.getCall(2).args[0].length, + numberOfDistinctMetrics % MAX_BATCH_EXPORT_SIZE, + ); + + const callbackResult = resultCallbackSpy.getCall(0).args[0]; + assert.strictEqual(callbackResult.code, ExportResultCode.SUCCESS); + }); +}); diff --git a/handwritten/spanner/test/metrics/transform.ts b/handwritten/spanner/test/metrics/transform.ts new file mode 100644 index 00000000000..c9cadd05044 --- /dev/null +++ b/handwritten/spanner/test/metrics/transform.ts @@ -0,0 +1,469 @@ +// 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 +// +// 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. + +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {_TEST_ONLY} from '../../src/metrics/transform'; +import { + AggregationTemporality, + DataPoint, + DataPointType, + ExponentialHistogramMetricData, + GaugeMetricData, + HistogramMetricData, + SumMetricData, + Histogram, + ExponentialHistogram, + MeterProvider, + MetricReader, +} from '@opentelemetry/sdk-metrics'; +import {Resource} from '@opentelemetry/resources'; +import { + Attributes, + Counter, + Meter, + ValueType as OTValueType, +} from '@opentelemetry/api'; +import { + SPANNER_RESOURCE_TYPE, + SPANNER_METER_NAME, + METRIC_NAME_ATTEMPT_COUNT, +} from '../../src/metrics/constants'; +import {MetricKind, ValueType} from '../../src/metrics/external-types'; +import {MetricsTracerFactory} from '../../src/metrics/metrics-tracer-factory'; + +const { + _normalizeLabelKey, + _transformMetricKind, + _extractLabels, + _formatHrTimeToGcmTime, + _transformResource, + _transformValueType, + _transformPoint, + transformResourceMetricToTimeSeriesArray, +} = _TEST_ONLY; + +describe('transform', () => { + let reader: MetricReader; + let meterProvider: MeterProvider; + let attributes: Attributes; + let resource: Resource; + let metricSum: SumMetricData; + let metricGauge: GaugeMetricData; + let metricHistogram: HistogramMetricData; + let metricExponentialHistogram: ExponentialHistogramMetricData; + let metricUnknown; + let sumDataPoint: DataPoint; + let gaugeDataPoint: DataPoint; + let histogramDataPoint: DataPoint; + let exponentialHistogramDataPoint: DataPoint; + let sandbox; + let mockFactory; + + class InMemoryMetricReader extends MetricReader { + protected async onShutdown(): Promise {} + protected async onForceFlush(): Promise {} + } + + before(() => { + sandbox = sinon.createSandbox(); + mockFactory = sandbox.createStubInstance(MetricsTracerFactory); + sandbox.stub(mockFactory, 'clientUid').get(() => 'test_uid'); + sandbox.stub(mockFactory, 'clientName').get(() => 'test_name'); + sandbox.stub(MetricsTracerFactory, 'getInstance').returns(mockFactory); + + reader = new InMemoryMetricReader(); + resource = new Resource({ + ['project_id']: 'project_id', + ['client_hash']: 'test_hash', + ['location']: 'test_location', + ['instance_id']: 'instance_id', + ['instance_config']: 'test_config', + }); + meterProvider = new MeterProvider({ + resource: resource, + readers: [reader], + }); + attributes = { + client_uid: 'test_uid', + client_name: 'test_name', + database: 'database_id', + method: 'test_method', + status: 'test_status', + other: 'ignored', + } as Attributes; + + metricSum = { + dataPoints: [], + aggregationTemporality: AggregationTemporality.DELTA, + isMonotonic: true, + dataPointType: DataPointType.SUM, + descriptor: {valueType: OTValueType.INT, name: 'some_count'} as any, + }; + + metricGauge = { + dataPoints: [], + aggregationTemporality: '' as any, + dataPointType: DataPointType.GAUGE, + descriptor: {valueType: OTValueType.DOUBLE, name: 'a_count'} as any, + }; + + metricHistogram = { + dataPoints: [], + aggregationTemporality: '' as any, + dataPointType: DataPointType.HISTOGRAM, + descriptor: {} as any, + }; + + metricExponentialHistogram = { + dataPoints: [], + aggregationTemporality: '' as any, + dataPointType: DataPointType.EXPONENTIAL_HISTOGRAM, + descriptor: {} as any, + }; + + metricUnknown = { + dataPoints: [], + aggregationTemporality: '' as any, + dataPointType: 'UNKNOWN_TYPE' as any, + descriptor: {name: ''} as any, + }; + + sumDataPoint = { + attributes, + value: 0, + startTime: process.hrtime(), + endTime: process.hrtime(), + }; + + gaugeDataPoint = { + attributes, + value: 0.0, + startTime: process.hrtime(), + endTime: process.hrtime(), + }; + + histogramDataPoint = { + attributes, + startTime: process.hrtime(), + endTime: process.hrtime(), + value: { + count: 1, + buckets: { + boundaries: [ + 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, + 10000, + ], + counts: [0, 0, 0, 0, 1, 0], + }, + }, + }; + + exponentialHistogramDataPoint = { + attributes: {}, + startTime: [1687103020, 679000000], + endTime: [1687103020, 680000000], + value: { + count: 7, + sum: 12.5, + scale: -1, + zeroCount: 1, + positive: { + offset: -1, + bucketCounts: [1, 3, 1], + }, + negative: { + bucketCounts: [1], + offset: 0, + }, + }, + }; + }); + + after(() => { + sandbox.restore(); + }); + + it('normalizes label keys', () => { + [ + ['valid_key_1', 'valid_key_1'], + ['hellø', 'hellø'], + ['123', 'key_123'], + ['key!321', 'key_321'], + ['hyphens-dots.slashes/', 'hyphens_dots_slashes_'], + ['non_letters_:£¢$∞', 'non_letters______'], + ].map(([key, expected]) => { + assert.strictEqual(_normalizeLabelKey(key), expected); + }); + }); + + it('should convert metric types to GCM metric kinds', () => { + assert.strictEqual(_transformMetricKind(metricSum), MetricKind.CUMULATIVE); + + const nonMonotonicMetricSum = { + dataPoints: [], + aggregationTemporality: '' as any, + isMonotonic: false, + dataPointType: DataPointType.SUM, + descriptor: {} as any, + } as SumMetricData; + + assert.strictEqual( + _transformMetricKind(nonMonotonicMetricSum), + MetricKind.GAUGE, + ); + + assert.strictEqual(_transformMetricKind(metricGauge), MetricKind.GAUGE); + + assert.strictEqual( + _transformMetricKind(metricHistogram), + MetricKind.CUMULATIVE, + ); + + assert.strictEqual( + _transformMetricKind(metricExponentialHistogram), + MetricKind.CUMULATIVE, + ); + + assert.strictEqual( + _transformMetricKind(metricUnknown), + MetricKind.UNSPECIFIED, + ); + }); + + it('should extract metric and resource labels', () => { + const dataLabels = _extractLabels(sumDataPoint, 'project_id'); + const resourceLabels = _extractLabels(resource, 'project_id'); + + // Metric Labels + assert.strictEqual(dataLabels.metricLabels['client_uid'], 'test_uid'); + assert.strictEqual(dataLabels.metricLabels['client_name'], 'test_name'); + assert.strictEqual(dataLabels.metricLabels['database'], 'database_id'); + assert.strictEqual(dataLabels.metricLabels['method'], 'test_method'); + assert.strictEqual(dataLabels.metricLabels['status'], 'test_status'); + + // Resource Labels + assert.strictEqual( + resourceLabels.monitoredResourceLabels['project_id'], + 'project_id', + ); + assert.strictEqual( + resourceLabels.monitoredResourceLabels['instance_id'], + 'instance_id', + ); + assert.strictEqual( + resourceLabels.monitoredResourceLabels['instance_config'], + 'test_config', + ); + assert.strictEqual( + resourceLabels.monitoredResourceLabels['location'], + 'test_location', + ); + assert.strictEqual( + resourceLabels.monitoredResourceLabels['client_hash'], + 'test_hash', + ); + + // Other Labels + assert(!('other' in dataLabels.metricLabels)); + assert(!('other' in resourceLabels.metricLabels)); + assert(!('other' in dataLabels.monitoredResourceLabels)); + assert(!('other' in resourceLabels.monitoredResourceLabels)); + }); + + it('should transform otel value types to GCM value types', () => { + assert.strictEqual(_transformValueType(metricSum), ValueType.INT64); + + assert.strictEqual(_transformValueType(metricGauge), ValueType.DOUBLE); + + assert.strictEqual( + _transformValueType(metricHistogram), + ValueType.DISTRIBUTION, + ); + + assert.strictEqual( + _transformValueType(metricExponentialHistogram), + ValueType.DISTRIBUTION, + ); + + assert.strictEqual( + _transformValueType(metricUnknown), + ValueType.VALUE_TYPE_UNSPECIFIED, + ); + }); + + it('should tranform the datapoint to a GCM point type', () => { + const sumExpectation = { + value: { + int64Value: '0', + }, + interval: { + startTime: _formatHrTimeToGcmTime(sumDataPoint.startTime), + endTime: _formatHrTimeToGcmTime(sumDataPoint.endTime), + }, + }; + assert.deepStrictEqual( + _transformPoint(metricSum, sumDataPoint), + sumExpectation, + ); + + const gaugeExpectation = { + value: { + doubleValue: '0.0', + }, + interval: { + endTime: _formatHrTimeToGcmTime(gaugeDataPoint.endTime), + }, + }; + + assert.deepStrictEqual( + _transformPoint(metricGauge, gaugeDataPoint), + gaugeExpectation, + ); + + const histogramExpectation = { + value: { + distributionValue: { + count: '1', + mean: 0, + bucketOptions: { + explicitBuckets: { + bounds: [ + 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, + 7500, 10000, + ], + }, + }, + bucketCounts: ['0', '0', '0', '0', '1', '0'], + }, + }, + interval: { + startTime: _formatHrTimeToGcmTime(histogramDataPoint.startTime), + endTime: _formatHrTimeToGcmTime(histogramDataPoint.endTime), + }, + }; + + assert.deepStrictEqual( + _transformPoint(metricHistogram, histogramDataPoint), + histogramExpectation, + ); + + const exponentialHistogramExpectation = { + interval: { + startTime: _formatHrTimeToGcmTime( + exponentialHistogramDataPoint.startTime, + ), + endTime: _formatHrTimeToGcmTime(exponentialHistogramDataPoint.endTime), + }, + value: { + distributionValue: { + bucketCounts: ['2', '1', '3', '1', '0'], + bucketOptions: { + exponentialBuckets: { + growthFactor: 4, + numFiniteBuckets: 3, + scale: 0.25, + }, + }, + count: '7', + mean: 1.7857142857142858, + }, + }, + }; + + assert.deepStrictEqual( + _transformPoint( + metricExponentialHistogram, + exponentialHistogramDataPoint, + ), + exponentialHistogramExpectation, + ); + }); + + it('should create a MonitoredResource with spanner type', () => { + const labels = {}; + const resource = _transformResource(labels); + assert(resource); + assert.strictEqual(resource.type, SPANNER_RESOURCE_TYPE); + }); + + it('should convert otel metrics to GCM TimeSeries', async () => { + const meter: Meter = meterProvider.getMeter(SPANNER_METER_NAME); + + const attemptCounter: Counter = meter.createCounter( + METRIC_NAME_ATTEMPT_COUNT, + { + description: 'Count of attempts', + unit: 'count', + }, + ); + + attemptCounter.add(1, {}); + attemptCounter.add(2, {}); + + const {errors, resourceMetrics} = await reader.collect(); + if (errors.length !== 0) { + throw errors; + } + const timeseries = transformResourceMetricToTimeSeriesArray( + resourceMetrics, + 'project_id', + ); + assert.strictEqual(timeseries.length, 1); + + // Verify the contents of the TimeSeries + const ts = timeseries[0]; + + assert.strictEqual(ts.valueType, 'INT64'); + + assert.strictEqual(ts.points?.length, 1); + + assert.strictEqual( + (ts.points[0].value as {int64Value: string})?.int64Value, + '3', + ); + }); + + it('should filter out metrics without spanner-nodejs scope', async () => { + reader = new InMemoryMetricReader(); + meterProvider = new MeterProvider({ + readers: [reader], + }); + + const meter: Meter = meterProvider.getMeter('wrong_scope'); + + const attemptCounter: Counter = meter.createCounter( + METRIC_NAME_ATTEMPT_COUNT, + { + description: 'Count of attempts', + unit: 'count', + }, + ); + + attemptCounter.add(1, {}); + attemptCounter.add(2, {}); + + const {errors, resourceMetrics} = await reader.collect(); + + if (errors.length !== 0) { + throw errors; + } + const timeseries = transformResourceMetricToTimeSeriesArray( + resourceMetrics, + 'project_id', + ); + + assert.strictEqual(timeseries.length, 0); + }); +}); diff --git a/handwritten/spanner/test/mockserver/mockdatabaseadmin.ts b/handwritten/spanner/test/mockserver/mockdatabaseadmin.ts new file mode 100644 index 00000000000..7b2e5954c52 --- /dev/null +++ b/handwritten/spanner/test/mockserver/mockdatabaseadmin.ts @@ -0,0 +1,262 @@ +/*! + * Copyright 2020 Google LLC. All Rights Reserved. + * + * 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 * as path from 'path'; +import {google} from '../../protos/protos'; +import {grpc} from 'google-gax'; +import * as protoLoader from '@grpc/proto-loader'; +import {createUnimplementedError} from './mockspanner'; +import v1 = google.spanner.admin.database.v1; +import iam = google.iam.v1; +import longrunning = google.longrunning; +import Any = google.protobuf.Any; + +const PROTO_PATH = 'spanner_database_admin.proto'; +const IMPORT_PATH = __dirname + '/../../../protos'; +const PROTO_DIR = + __dirname + '/../../../protos/google/spanner/admin/database/v1'; +const GAX_PROTO_DIR = path.join( + path.dirname(require.resolve('google-gax')), + '..', + 'protos', +); + +/** + * Load the Spanner Database Admin service proto. + */ +const packageDefinition = protoLoader.loadSync(PROTO_PATH, { + keepCase: false, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [IMPORT_PATH, PROTO_DIR, GAX_PROTO_DIR], +}); +const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); +const databaseAdminProtoDescriptor = + protoDescriptor['google']['spanner']['admin']['database']['v1']; +const TEST_DATABASE_NAME = + 'projects/mock-project/instances/test/databases/test'; +const PROD_DATABASE_NAME = + 'projects/mock-project/instances/prod/databases/prod'; + +export class MockDatabaseAdmin { + private static TEST_DATABASE = v1.Database.create({ + name: TEST_DATABASE_NAME, + state: v1.Database.State.READY, + }); + + private static PROD_DATABASE = v1.Database.create({ + name: PROD_DATABASE_NAME, + state: v1.Database.State.READY, + }); + + private static CREATE_TEST_DATABASE_OPERATION = longrunning.Operation.create({ + name: `${TEST_DATABASE_NAME}/operations/1`, + done: true, + response: Any.create({ + value: v1.Database.encode(MockDatabaseAdmin.TEST_DATABASE).finish(), + }), + metadata: Any.create({ + value: v1.CreateDatabaseMetadata.encode( + v1.CreateDatabaseMetadata.create({ + database: MockDatabaseAdmin.TEST_DATABASE.name, + }), + ).finish(), + }), + }); + + private static CREATE_PROD_DATABASE_OPERATION = longrunning.Operation.create({ + name: `${PROD_DATABASE_NAME}/operations/1`, + done: true, + response: Any.create({ + value: v1.Database.encode(MockDatabaseAdmin.PROD_DATABASE).finish(), + }), + metadata: Any.create({ + value: v1.CreateDatabaseMetadata.encode( + v1.CreateDatabaseMetadata.create({ + database: MockDatabaseAdmin.PROD_DATABASE.name, + }), + ).finish(), + }), + }); + + private constructor() {} + + /** + * Creates a MockDatabaseAdmin. + */ + static create(): MockDatabaseAdmin { + return new MockDatabaseAdmin(); + } + + private static createNotFoundError(msg: string): grpc.ServiceError { + const error = new Error(msg); + return Object.assign(error, { + code: grpc.status.NOT_FOUND, + }) as grpc.ServiceError; + } + + private static createServiceError(msg: string, code: grpc.status) { + const error = new Error(msg); + return Object.assign(error, { + code, + }); + } + + listDatabases( + call: grpc.ServerUnaryCall< + v1.ListDatabasesRequest, + v1.ListDatabasesResponse + >, + callback: v1.DatabaseAdmin.ListDatabasesCallback, + ) { + callback( + null, + v1.ListDatabasesResponse.create({ + databases: [ + MockDatabaseAdmin.TEST_DATABASE, + MockDatabaseAdmin.PROD_DATABASE, + ], + }), + ); + } + + listDatabaseOperations( + call: grpc.ServerUnaryCall< + v1.ListDatabaseOperationsRequest, + v1.ListDatabaseOperationsResponse + >, + callback: v1.DatabaseAdmin.ListDatabaseOperationsCallback, + ) { + callback( + null, + v1.ListDatabaseOperationsResponse.create({ + operations: [ + MockDatabaseAdmin.CREATE_TEST_DATABASE_OPERATION, + MockDatabaseAdmin.CREATE_PROD_DATABASE_OPERATION, + ], + }), + ); + } + + createDatabase( + call: grpc.ServerUnaryCall, + callback: v1.DatabaseAdmin.CreateDatabaseCallback, + ) { + let name = call.request!.createStatement.replace('CREATE DATABASE ', ''); + name = name.substring(1, name.length - 1); + const database = v1.Database.create({ + name: `${call.request!.parent}/databases/${name}`, + state: v1.Database.State.READY, + }); + const metadataBuffer = v1.CreateDatabaseMetadata.encode( + v1.CreateDatabaseMetadata.create({ + database: database.name, + }), + ).finish(); + const databaseBuffer = v1.Database.encode(database).finish(); + callback( + null, + longrunning.Operation.create({ + name: 'projects/mock-project/operations/mock-operation', + done: true, + metadata: Any.create({ + value: metadataBuffer, + }), + response: Any.create({ + value: databaseBuffer, + }), + }), + ); + } + + getDatabase( + call: grpc.ServerUnaryCall, + callback: v1.DatabaseAdmin.GetDatabaseCallback, + ) { + callback(createUnimplementedError('GetDatabase is not yet implemented')); + } + + updateDatabaseDdl( + call: grpc.ServerUnaryCall, + callback: v1.DatabaseAdmin.UpdateDatabaseDdlCallback, + ) { + callback( + createUnimplementedError('UpdateDatabaseDdl is not yet implemented'), + ); + } + + dropDatabase( + call: grpc.ServerUnaryCall, + callback: v1.DatabaseAdmin.DropDatabaseCallback, + ) { + callback(createUnimplementedError('DropDatabase is not yet implemented')); + } + + getDatabaseDdl( + call: grpc.ServerUnaryCall, + callback: v1.DatabaseAdmin.GetDatabaseDdlCallback, + ) { + callback(createUnimplementedError('GetDatabaseDdl is not yet implemented')); + } + + setIamPolicy( + call: grpc.ServerUnaryCall, + callback: iam.IAMPolicy.SetIamPolicyCallback, + ) { + callback(createUnimplementedError('SetIamPolicy is not yet implemented')); + } + + getIamPolicy( + call: grpc.ServerUnaryCall, + callback: iam.IAMPolicy.GetIamPolicyCallback, + ) { + callback(createUnimplementedError('GetIamPolicy is not yet implemented')); + } + + testIamPermissions( + call: grpc.ServerUnaryCall, + callback: iam.IAMPolicy.TestIamPermissionsCallback, + ) { + callback( + createUnimplementedError('TestIamPermissions is not yet implemented'), + ); + } +} + +/** + * Creates and adds a MockDatabaseAdmin instance to the given server. The mock contains the following data by default: + * 1. Two Databases: 'projects/mock-project/instances/test/databases/test' and 'projects/mock-project/instances/prod/databases/prod'. + */ +export function createMockDatabaseAdmin( + server: grpc.Server, +): MockDatabaseAdmin { + const mock = MockDatabaseAdmin.create(); + server.addService(databaseAdminProtoDescriptor.DatabaseAdmin.service, { + listDatabases: mock.listDatabases, + createDatabase: mock.createDatabase, + getDatabase: mock.getDatabase, + updateDatabaseDdl: mock.updateDatabaseDdl, + dropDatabase: mock.dropDatabase, + getDatabaseDdl: mock.getDatabaseDdl, + listDatabaseOperations: mock.listDatabaseOperations, + setIamPolicy: mock.setIamPolicy, + getIamPolicy: mock.getIamPolicy, + testIamPermissions: mock.testIamPermissions, + }); + return mock; +} diff --git a/handwritten/spanner/test/mockserver/mockinstanceadmin.ts b/handwritten/spanner/test/mockserver/mockinstanceadmin.ts new file mode 100644 index 00000000000..c773f7da46f --- /dev/null +++ b/handwritten/spanner/test/mockserver/mockinstanceadmin.ts @@ -0,0 +1,353 @@ +/*! + * Copyright 2020 Google LLC. All Rights Reserved. + * + * 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 * as path from 'path'; +import {google} from '../../protos/protos'; +import {grpc} from 'google-gax'; +import * as protoLoader from '@grpc/proto-loader'; +import {createUnimplementedError, now} from './mockspanner'; +import v1 = google.spanner.admin.instance.v1; +import iam = google.iam.v1; +import longrunning = google.longrunning; +import Any = google.protobuf.Any; +import Empty = google.protobuf.Empty; + +const PROTO_PATH = 'spanner_instance_admin.proto'; +const IMPORT_PATH = __dirname + '/../../../protos'; +const PROTO_DIR = + __dirname + '/../../../protos/google/spanner/admin/instance/v1'; +const GAX_PROTO_DIR = path.join( + path.dirname(require.resolve('google-gax')), + '..', + 'protos', +); + +/** + * Load the Spanner Instance Admin service proto. + */ +const packageDefinition = protoLoader.loadSync(PROTO_PATH, { + keepCase: false, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [IMPORT_PATH, PROTO_DIR, GAX_PROTO_DIR], +}); +const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); +const instanceAdminProtoDescriptor = + protoDescriptor['google']['spanner']['admin']['instance']['v1']; +export const TEST_INSTANCE_CONFIG_NAME = + 'projects/mock-project/instanceConfigs/test-instance-config'; +export const TEST_INSTANCE_NAME = 'projects/mock-project/instances/test'; +export const PROD_INSTANCE_NAME = 'projects/mock-project/instances/prod'; + +export class MockInstanceAdmin { + private static TEST_INSTANCE_CONFIG = v1.InstanceConfig.create({ + name: TEST_INSTANCE_CONFIG_NAME, + displayName: 'Test Instance Config', + replicas: [ + v1.ReplicaInfo.create({ + type: v1.ReplicaInfo.ReplicaType.READ_WRITE, + location: 'local', + defaultLeaderLocation: true, + }), + ], + }); + + private static TEST_INSTANCE = v1.Instance.create({ + config: TEST_INSTANCE_CONFIG_NAME, + name: TEST_INSTANCE_NAME, + displayName: 'Test Instance', + nodeCount: 1, + state: v1.Instance.State.READY, + labels: {purpose: 'Test'}, + }); + + private static PROD_INSTANCE = v1.Instance.create({ + config: TEST_INSTANCE_CONFIG_NAME, + name: PROD_INSTANCE_NAME, + displayName: 'Production Instance', + nodeCount: 6, + state: v1.Instance.State.READY, + labels: {purpose: 'Production'}, + }); + + private constructor() {} + + /** + * Creates a MockInstanceAdmin. + */ + static create(): MockInstanceAdmin { + return new MockInstanceAdmin(); + } + + private static createNotFoundError(msg: string): grpc.ServiceError { + const error = new Error(msg); + return Object.assign(error, { + code: grpc.status.NOT_FOUND, + }) as grpc.ServiceError; + } + + private static createServiceError(msg: string, code: grpc.status) { + const error = new Error(msg); + return Object.assign(error, { + code, + }); + } + + listInstanceConfigs( + call: grpc.ServerUnaryCall< + v1.ListInstanceConfigsRequest, + v1.ListInstanceConfigsResponse + >, + callback: v1.InstanceAdmin.ListInstanceConfigsCallback, + ) { + callback( + null, + v1.ListInstanceConfigsResponse.create({ + instanceConfigs: [MockInstanceAdmin.TEST_INSTANCE_CONFIG], + }), + ); + } + + getInstanceConfig( + call: grpc.ServerUnaryCall, + callback: v1.InstanceAdmin.GetInstanceConfigCallback, + ) { + if (call.request!.name === TEST_INSTANCE_CONFIG_NAME) { + callback(null, MockInstanceAdmin.TEST_INSTANCE_CONFIG); + } else { + callback( + MockInstanceAdmin.createNotFoundError( + `InstanceConfig not found: ${call.request!.name}`, + ), + ); + } + } + + listInstances( + call: grpc.ServerUnaryCall< + v1.ListInstancesRequest, + v1.ListInstancesResponse + >, + callback: v1.InstanceAdmin.ListInstancesCallback, + ) { + let instances: google.spanner.admin.instance.v1.IInstance[] = []; + if ( + !call.request!.filter || + call.request!.filter.includes( + `name:${MockInstanceAdmin.TEST_INSTANCE.name}`, + ) + ) { + instances.push(MockInstanceAdmin.TEST_INSTANCE); + } + if ( + !call.request!.filter || + call.request!.filter.includes( + `name:${MockInstanceAdmin.PROD_INSTANCE.name}`, + ) + ) { + instances.push(MockInstanceAdmin.PROD_INSTANCE); + } + if (call.request!.pageToken) { + const beginIndex = Number.parseInt(call.request!.pageToken, 10); + instances = instances.slice(beginIndex); + } + if (call.request!.pageSize && call.request!.pageSize < instances.length) { + instances = instances.slice(0, call.request!.pageSize); + } + callback( + null, + v1.ListInstancesResponse.create({ + instances, + }), + ); + } + + getInstance( + call: grpc.ServerUnaryCall, + callback: v1.InstanceAdmin.GetInstanceCallback, + ) { + if (call.request!.name === TEST_INSTANCE_NAME) { + callback(null, MockInstanceAdmin.TEST_INSTANCE); + } else if (call.request!.name === PROD_INSTANCE_NAME) { + callback(null, MockInstanceAdmin.PROD_INSTANCE); + } else { + callback( + MockInstanceAdmin.createNotFoundError( + `Instance not found: ${call.request!.name}`, + ), + ); + } + } + + createInstance( + call: grpc.ServerUnaryCall, + callback: v1.InstanceAdmin.CreateInstanceCallback, + ) { + const instance = v1.Instance.create({ + name: `${call.request!.parent}/instances/${call.request!.instanceId}`, + displayName: call.request!.instance + ? call.request!.instance.displayName + : undefined, + config: call.request!.instance + ? call.request!.instance.config + : undefined, + nodeCount: call.request!.instance + ? call.request!.instance.nodeCount + : undefined, + processingUnits: call.request!.instance + ? call.request!.instance.processingUnits + : undefined, + labels: call.request!.instance + ? call.request!.instance.labels + : undefined, + state: v1.Instance.State.READY, + }); + const metadataBuffer = v1.CreateInstanceMetadata.encode( + v1.CreateInstanceMetadata.create({ + instance, + startTime: now(), + endTime: now(), + }), + ).finish(); + const instanceBuffer = v1.Instance.encode(instance).finish(); + callback( + null, + longrunning.Operation.create({ + name: 'projects/mock-project/operations/mock-operation', + done: true, + metadata: Any.create({ + value: metadataBuffer, + }), + response: Any.create({ + value: instanceBuffer, + }), + }), + ); + } + + updateInstance( + call: grpc.ServerUnaryCall, + callback: v1.InstanceAdmin.UpdateInstanceCallback, + ) { + if (call.request!.instance) { + if ( + call.request!.instance.name === PROD_INSTANCE_NAME || + call.request!.instance.name === TEST_INSTANCE_NAME + ) { + const metadataBuffer = v1.CreateInstanceMetadata.encode( + v1.CreateInstanceMetadata.create({ + instance: call.request!.instance, + startTime: now(), + endTime: now(), + }), + ).finish(); + callback( + null, + longrunning.Operation.create({ + name: 'projects/mock-project/operations/mock-operation', + done: true, + metadata: Any.create({ + value: metadataBuffer, + }), + response: Any.create({ + value: v1.Instance.encode(call.request!.instance).finish(), + }), + }), + ); + } else { + callback( + MockInstanceAdmin.createNotFoundError( + `Instance not found: ${call.request!.instance.name}`, + ), + ); + } + } else { + callback( + MockInstanceAdmin.createServiceError( + 'Missing instance in UpdateInstance request', + grpc.status.INVALID_ARGUMENT, + ), + ); + } + } + + deleteInstance( + call: grpc.ServerUnaryCall, + callback: v1.InstanceAdmin.DeleteInstanceCallback, + ) { + if ( + call.request!.name === PROD_INSTANCE_NAME || + call.request!.name === TEST_INSTANCE_NAME + ) { + callback(null, Empty.create({})); + } else { + callback( + MockInstanceAdmin.createNotFoundError( + `Instance not found: ${call.request!.name}`, + ), + ); + } + } + + setIamPolicy( + call: grpc.ServerUnaryCall, + callback: iam.IAMPolicy.SetIamPolicyCallback, + ) { + callback(createUnimplementedError('SetIamPolicy is not yet implemented')); + } + + getIamPolicy( + call: grpc.ServerUnaryCall, + callback: iam.IAMPolicy.GetIamPolicyCallback, + ) { + callback(createUnimplementedError('GetIamPolicy is not yet implemented')); + } + + testIamPermissions( + call: grpc.ServerUnaryCall, + callback: iam.IAMPolicy.TestIamPermissionsCallback, + ) { + callback( + createUnimplementedError('TestIamPermissions is not yet implemented'), + ); + } +} + +/** + * Creates and adds a MockInstanceAdmin instance to the given server. The mock contains the following data by default: + * 1. One InstanceConfig with the name 'projects/mock-project/instanceConfigs/test-instance-config'. + * 2. Two Instances: 'projects/mock-project/instances/test' and 'projects/mock-project/instances/prod'. + */ +export function createMockInstanceAdmin( + server: grpc.Server, +): MockInstanceAdmin { + const mock = MockInstanceAdmin.create(); + server.addService(instanceAdminProtoDescriptor.InstanceAdmin.service, { + listInstanceConfigs: mock.listInstanceConfigs, + getInstanceConfig: mock.getInstanceConfig, + listInstances: mock.listInstances, + getInstance: mock.getInstance, + createInstance: mock.createInstance, + updateInstance: mock.updateInstance, + deleteInstance: mock.deleteInstance, + setIamPolicy: mock.setIamPolicy, + getIamPolicy: mock.getIamPolicy, + testIamPermissions: mock.testIamPermissions, + }); + return mock; +} diff --git a/handwritten/spanner/test/mockserver/mockspanner.ts b/handwritten/spanner/test/mockserver/mockspanner.ts new file mode 100644 index 00000000000..57937c98e68 --- /dev/null +++ b/handwritten/spanner/test/mockserver/mockspanner.ts @@ -0,0 +1,1917 @@ +/*! + * Copyright 2020 Google LLC. All Rights Reserved. + * + * 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 * as path from 'path'; +import {google} from '../../protos/protos'; +import {grpc, ServiceError} from 'google-gax'; +import * as protoLoader from '@grpc/proto-loader'; +// eslint-disable-next-line n/no-extraneous-import +import {Metadata} from '@grpc/grpc-js'; +import {Transaction} from '../../src'; +import protobuf = google.spanner.v1; +import Timestamp = google.protobuf.Timestamp; +import RetryInfo = google.rpc.RetryInfo; +import ExecuteBatchDmlResponse = google.spanner.v1.ExecuteBatchDmlResponse; +import ResultSet = google.spanner.v1.ResultSet; +import Status = google.rpc.Status; +import Any = google.protobuf.Any; +import QueryMode = google.spanner.v1.ExecuteSqlRequest.QueryMode; +import NullValue = google.protobuf.NullValue; +import {ExecuteSqlRequest, ReadRequest} from '../../src/transaction'; +import {randomInt} from 'crypto'; + +const PROTO_PATH = 'spanner.proto'; +const IMPORT_PATH = __dirname + '/../../../protos'; +const PROTO_DIR = __dirname + '/../../../protos/google/spanner/v1'; +const GAX_PROTO_DIR = path.join( + path.dirname(require.resolve('google-gax')), + '..', + 'protos', +); + +/** + * Load the Spanner service proto. + */ +const packageDefinition = protoLoader.loadSync(PROTO_PATH, { + keepCase: false, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [IMPORT_PATH, PROTO_DIR, GAX_PROTO_DIR], +}); +const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); +const spannerProtoDescriptor = protoDescriptor['google']['spanner']['v1']; +const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin'; +const RETRY_INFO_TYPE = 'type.googleapis.com/google.rpc.retryinfo'; + +/** + * Specifies the type of result that a mock server should return for a `ReadRequest`. + * + * `ERROR`: Simulates an error response from the server. + * `RESULT_SET`: Simulates a successful response with a result set. + */ +enum ReadRequestResultType { + ERROR, + RESULT_SET, +} + +/** + * The type of result for an SQL statement that the mock server should return. + */ +enum StatementResultType { + ERROR, + RESULT_SET, + UPDATE_COUNT, +} + +/** + * Represents the result of executing a `ReadRequest` on a mock Spanner server. + */ +export class ReadRequestResult { + private readonly _type: ReadRequestResultType; + + /** + * The type of result this instance represents. + */ + get type(): ReadRequestResultType { + return this._type; + } + + private readonly _error: Error | null; + + /** + * The error associated with the result, if any. + * + * @throws If the result type is not `ERROR`. + */ + get error(): Error { + if (this._error) { + return this._error; + } + throw new Error('The ReadRequestResult does not contain an Error'); + } + + private readonly _resultSet: + | protobuf.ResultSet + | protobuf.PartialResultSet[] + | null; + + /** + * The result set associated with the result, if any. + * + * Can be a full `ResultSet` or a stream of `PartialResultSet`s. + * + * @throws If the result type is not `RESULT_SET`. + */ + get resultSet(): protobuf.ResultSet | protobuf.PartialResultSet[] { + if (this._resultSet) { + return this._resultSet; + } + throw new Error('The ReadRequestResult does not contain a ResultSet'); + } + + private constructor( + type: ReadRequestResultType, + error: Error | null, + resultSet: protobuf.ResultSet | protobuf.PartialResultSet[] | null, + ) { + this._type = type; + this._error = error; + this._resultSet = resultSet; + } + + /** + * Creates a `ReadRequestResult` that simulates an error response. + * + * @param error The error to return for the read request. + * @returns A `ReadRequestResult` instance representing an error. + */ + static error(error: Error): ReadRequestResult { + return new ReadRequestResult(ReadRequestResultType.ERROR, error, null); + } + + /** + * Create a ReadRequestResult that will return a ResultSet or a stream of PartialResultSets. + * @param resultSet The result set to return. + */ + static resultSet( + resultSet: protobuf.ResultSet | protobuf.PartialResultSet[], + ): ReadRequestResult { + return new ReadRequestResult( + ReadRequestResultType.RESULT_SET, + null, + resultSet, + ); + } +} + +/** + * StatementResult contains the result for an SQL statement on the mock server. + */ +export class StatementResult { + private readonly _type: StatementResultType; + get type(): StatementResultType { + return this._type; + } + private readonly _error: Error | null; + get error(): Error { + if (this._error) { + return this._error; + } + throw new Error('The StatementResult does not contain an Error'); + } + private readonly _resultSet: + | protobuf.ResultSet + | protobuf.PartialResultSet[] + | null; + get resultSet(): protobuf.ResultSet | protobuf.PartialResultSet[] { + if (this._resultSet) { + return this._resultSet; + } + throw new Error('The StatementResult does not contain a ResultSet'); + } + private readonly _updateCount: number | null; + get updateCount(): number { + if (this._updateCount) { + return this._updateCount; + } + throw new Error('The StatementResult does not contain an UpdateCount'); + } + + private constructor( + type: StatementResultType, + error: Error | null, + resultSet: protobuf.ResultSet | protobuf.PartialResultSet[] | null, + updateCount: number | null, + ) { + this._type = type; + this._error = error; + this._resultSet = resultSet; + this._updateCount = updateCount; + } + + /** + * Create a StatementResult that will return an error. + * @param error The error to return for the statement. + */ + static error(error: Error): StatementResult { + return new StatementResult(StatementResultType.ERROR, error, null, null); + } + + /** + * Create a StatementResult that will return a ResultSet or a stream of PartialResultSets. + * @param resultSet The result set to return. + */ + static resultSet( + resultSet: protobuf.ResultSet | protobuf.PartialResultSet[], + ): StatementResult { + return new StatementResult( + StatementResultType.RESULT_SET, + null, + resultSet, + null, + ); + } + + /** + * Create a StatementResult that will return an update count. + * @param updateCount The row count to return. + * @param error The status error to return. + */ + static updateCount(updateCount: number, error?: Error): StatementResult { + return new StatementResult( + StatementResultType.UPDATE_COUNT, + error || null, + null, + updateCount, + ); + } +} + +export interface MockError extends grpc.ServiceError { + streamIndex?: number; +} + +export class SimulatedExecutionTime { + private readonly _minimumExecutionTime?: number; + get minimumExecutionTime(): number | undefined { + return this._minimumExecutionTime; + } + private readonly _randomExecutionTime?: number; + get randomExecutionTime(): number | undefined { + return this._randomExecutionTime; + } + private readonly _errors?: grpc.ServiceError[]; + get errors(): MockError[] | undefined { + return this._errors; + } + // Keep error after execution. The error will continue to be returned until + // it is cleared. + private readonly _keepError?: boolean; + + private constructor(input: { + minimumExecutionTime?: number; + randomExecutionTime?: number; + errors?: grpc.ServiceError[]; + keepError?: boolean; + }) { + this._minimumExecutionTime = input.minimumExecutionTime; + this._randomExecutionTime = input.randomExecutionTime; + this._errors = input.errors; + this._keepError = input.keepError; + } + + static ofError(error: MockError): SimulatedExecutionTime { + return new SimulatedExecutionTime({errors: [error]}); + } + + static ofErrors(errors: MockError[]): SimulatedExecutionTime { + return new SimulatedExecutionTime({errors}); + } + + static ofMinAndRandomExecTime(minExecTime: number, randomExecTime: number) { + return new SimulatedExecutionTime({ + minimumExecutionTime: minExecTime, + randomExecutionTime: randomExecTime, + }); + } + + async simulateExecutionTime() { + if (!(this.randomExecutionTime || this.minimumExecutionTime)) { + return; + } + const rnd = this.randomExecutionTime + ? Math.random() * this.randomExecutionTime + : 0; + const total = + (this.minimumExecutionTime ? this.minimumExecutionTime : 0) + rnd; + await MockSpanner.sleep(total); + } +} + +export function createUnimplementedError(msg: string): grpc.ServiceError { + const error = new Error(msg); + return Object.assign(error, { + code: grpc.status.UNIMPLEMENTED, + }) as grpc.ServiceError; +} + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +interface Request {} + +/** + * MockSpanner is a mocked in-mem Spanner server that manages sessions and transactions automatically. Results for SQL statements must be registered on the server using the MockSpanner.putStatementResult function. + */ +export class MockSpanner { + private requests: Request[] = []; + private metadata: Metadata[] = []; + private frozen = 0; + private sessionCounter = 0; + private sessions: Map = new Map< + string, + protobuf.Session + >(); + private mutationOnly: boolean; + private transactionSeqNum: Map = new Map(); + private transactionCounters: Map = new Map(); + private transactions: Map = new Map< + string, + protobuf.Transaction + >(); + private transactionOptions: Map< + string, + protobuf.ITransactionOptions | null | undefined + > = new Map(); + private abortedTransactions: Set = new Set(); + private statementResults: Map = new Map< + string, + StatementResult + >(); + private readRequestResults: Map = new Map< + string, + ReadRequestResult + >(); + private executionTimes: Map = new Map< + string, + SimulatedExecutionTime + >(); + + private constructor() { + this.putStatementResult = this.putStatementResult.bind(this); + this.putReadRequestResult = this.putReadRequestResult.bind(this); + this.batchCreateSessions = this.batchCreateSessions.bind(this); + this.createSession = this.createSession.bind(this); + this.deleteSession = this.deleteSession.bind(this); + this.getSession = this.getSession.bind(this); + this.listSessions = this.listSessions.bind(this); + + this.beginTransaction = this.beginTransaction.bind(this); + this.commit = this.commit.bind(this); + this.rollback = this.rollback.bind(this); + + this.executeBatchDml = this.executeBatchDml.bind(this); + this.executeStreamingSql = this.executeStreamingSql.bind(this); + this.partitionQuery = this.partitionQuery.bind(this); + + this.read = this.read.bind(this); + this.streamingRead = this.streamingRead.bind(this); + this.partitionRead = this.partitionRead.bind(this); + this.batchWrite = this.batchWrite.bind(this); + this.mutationOnly = false; + } + + /** + * Creates a MockSpanner instance. + */ + static create(): MockSpanner { + return new MockSpanner(); + } + + resetRequests(): void { + this.requests = []; + this.metadata = []; + } + + /** + * @return the requests that have been received by this mock server. + */ + getRequests(): Request[] { + return this.requests; + } + + /** + * @return the metadata that have been received by this mock server. + */ + getMetadata(): Metadata[] { + return this.metadata; + } + + /** + * Register the expected result for a given `ReadRequest` on the mock server. + * + * @param query The `ReadRequest` to associate with the result. + * @param result The `ReadRequestResult` to return when the `query` is received. + */ + putReadRequestResult(query: ReadRequest, result: ReadRequestResult) { + const keySet = JSON.stringify( + query.keySet ?? {}, + Object.keys(query.keySet ?? {}).sort(), + ); + const key = `${query.table}|${keySet}`; + this.readRequestResults.set(key, result); + } + + /** + * Registers a result for an SQL statement on the server. + * @param sql The SQL statement that should return the result. + * @param result The result to return. + */ + putStatementResult(sql: string, result: StatementResult) { + this.statementResults.set(sql, result); + } + + removeExecutionTime(fn: Function) { + this.executionTimes.delete(fn.name); + } + + setExecutionTime(fn: Function, time: SimulatedExecutionTime) { + this.executionTimes.set(fn.name, time); + } + + removeExecutionTimes() { + this.executionTimes.clear(); + } + + abortTransaction(transaction: Transaction): void { + const formattedId = `${transaction.session.formattedName_}/transactions/${transaction.id}`; + if (this.transactions.has(formattedId) || !transaction.id) { + this.transactions.delete(formattedId); + this.transactionOptions.delete(formattedId); + this.abortedTransactions.add(formattedId); + } else { + throw new Error(`Transaction ${formattedId} does not exist`); + } + } + + freeze() { + this.frozen++; + } + + unfreeze() { + if (this.frozen === 0) { + throw new Error('This mock server is already unfrozen'); + } + this.frozen--; + } + + /** + * Creates a new session for the given database and adds it to the map of sessions of this server. + * @param database The database to create the session for. + */ + private newSession( + database: string, + multiplexed?: boolean, + ): protobuf.Session { + const id = this.sessionCounter++; + const name = `${database}/sessions/${id}`; + const session = protobuf.Session.create({ + name, + multiplexed: multiplexed, + createTime: now(), + }); + this.sessions.set(name, session); + return session; + } + + private static createSessionNotFoundError(name: string): grpc.ServiceError { + const error = new Error(`Session not found: ${name}`); + return Object.assign(error, { + code: grpc.status.NOT_FOUND, + }) as grpc.ServiceError; + } + + private static createTransactionNotFoundError( + name: string, + ): grpc.ServiceError { + const error = new Error(`Transaction not found: ${name}`); + return Object.assign(error, { + code: grpc.status.NOT_FOUND, + }) as grpc.ServiceError; + } + + private static createTransactionAbortedError( + name: string, + ): grpc.ServiceError { + const error = Object.assign(new Error(`Transaction aborted: ${name}`), { + code: grpc.status.ABORTED, + }); + return Object.assign(error, { + metadata: this.createMinimalRetryDelayMetadata(), + }) as grpc.ServiceError; + } + + static createMinimalRetryDelayMetadata(): grpc.Metadata { + const metadata = new grpc.Metadata(); + const retry = RetryInfo.encode({ + retryDelay: { + seconds: 0, + nanos: 1, + }, + }); + metadata.add(RETRY_INFO_BIN, Buffer.from(retry.finish())); + return metadata; + } + + static sleep(ms): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + private async simulateExecutionTime(functionName: string): Promise { + while (this.frozen > 0) { + await MockSpanner.sleep(10); + } + const execTime = this.executionTimes.get(functionName); + if (execTime) { + await execTime.simulateExecutionTime(); + } + if ( + execTime && + execTime.errors && + execTime.errors.length && + !execTime.errors[0].streamIndex + ) { + throw execTime.errors.shift(); + } + return Promise.resolve(); + } + + private shiftStreamError( + functionName: string, + index: number, + ): MockError | undefined { + const execTime = this.executionTimes.get(functionName); + if (execTime) { + if ( + execTime.errors && + execTime.errors.length && + execTime.errors[0].streamIndex === index + ) { + return execTime.errors.shift(); + } + } + return undefined; + } + + private pushRequest(request: Request, metadata: Metadata): void { + this.requests.push(request); + this.metadata.push(metadata); + } + + batchCreateSessions( + call: grpc.ServerUnaryCall< + protobuf.BatchCreateSessionsRequest, + protobuf.BatchCreateSessionsResponse + >, + callback: protobuf.Spanner.BatchCreateSessionsCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.batchCreateSessions.name) + .then(() => { + const sessions = new Array(); + for (let i = 0; i < call.request!.sessionCount; i++) { + sessions.push(this.newSession(call.request!.database)); + } + callback( + null, + protobuf.BatchCreateSessionsResponse.create({session: sessions}), + ); + }) + .catch(err => { + callback(err); + }); + } + + createSession( + call: grpc.ServerUnaryCall, + callback: protobuf.Spanner.CreateSessionCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.createSession.name) + .then(() => { + callback( + null, + this.newSession( + call.request!.database, + call.request!.session?.multiplexed ?? false, + ), + ); + }) + .catch(err => { + callback(err); + }); + } + + getSession( + call: grpc.ServerUnaryCall, + callback: protobuf.Spanner.GetSessionCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.getSession.name) + .then(() => { + const session = this.sessions[call.request!.name]; + if (session) { + callback(null, session); + } else { + callback(MockSpanner.createSessionNotFoundError(call.request!.name)); + } + }) + .catch(err => { + callback(err); + }); + } + + listSessions( + call: grpc.ServerUnaryCall< + protobuf.ListSessionsRequest, + protobuf.ListSessionsResponse + >, + callback: protobuf.Spanner.ListSessionsCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.listSessions.name) + .then(() => { + callback( + null, + protobuf.ListSessionsResponse.create({ + sessions: Array.from(this.sessions.values()).filter(session => { + return session.name.startsWith(call.request!.database); + }), + }), + ); + }) + .catch(err => { + callback(err); + }); + } + + deleteSession( + call: grpc.ServerUnaryCall< + protobuf.DeleteSessionRequest, + google.protobuf.Empty + >, + callback: protobuf.Spanner.DeleteSessionCallback, + ) { + this.pushRequest(call.request!, call.metadata); + if (this.sessions.delete(call.request!.name)) { + callback(null, google.protobuf.Empty.create()); + } else { + callback(MockSpanner.createSessionNotFoundError(call.request!.name)); + } + } + + executeSql( + call: grpc.ServerUnaryCall, + callback: protobuf.Spanner.ExecuteSqlCallback, + ) { + this.pushRequest(call.request!, call.metadata); + callback(createUnimplementedError('ExecuteSql is not yet implemented')); + } + + executeStreamingSql( + call: grpc.ServerWritableStream< + protobuf.ExecuteSqlRequest, + protobuf.PartialResultSet + >, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.executeStreamingSql.name) + .then(() => { + let transactionKey; + if (call.request!.transaction) { + const fullTransactionId = `${call.request!.session}/transactions/${ + call.request!.transaction.id + }`; + transactionKey = fullTransactionId; + if (this.abortedTransactions.has(fullTransactionId)) { + call.sendMetadata(new Metadata()); + call.emit( + 'error', + MockSpanner.createTransactionAbortedError(`${fullTransactionId}`), + ); + call.end(); + return; + } + } + const res = this.statementResults.get(call.request!.sql); + const session = this.sessions.get(call.request!.session); + if (res) { + if (call.request!.transaction?.begin) { + const txn = this._updateTransaction( + call.request!.session, + call.request!.transaction.begin, + ); + if (txn instanceof Error) { + call.sendMetadata(new Metadata()); + call.emit('error', txn); + call.end(); + return; + } + transactionKey = `${call.request!.session}/transactions/${txn.id.toString()}`; + if (res.type === StatementResultType.RESULT_SET) { + (res.resultSet as protobuf.ResultSet).metadata!.transaction = txn; + } + } + + // get the current seqNum + const currentSeqNum = this.transactionSeqNum.get(transactionKey) || 0; + const nextSeqNum = currentSeqNum + 1; + + // set the next seqNum + this.transactionSeqNum.set(transactionKey, nextSeqNum); + const precommitToken = session?.multiplexed + ? protobuf.MultiplexedSessionPrecommitToken.create({ + precommitToken: Buffer.from('mock-precommit-token'), + seqNum: nextSeqNum, + }) + : null; + let partialResultSets; + let resumeIndex; + let streamErr; + switch (res.type) { + case StatementResultType.RESULT_SET: + (res.resultSet as protobuf.ResultSet).precommitToken = + precommitToken; + if (Array.isArray(res.resultSet)) { + partialResultSets = res.resultSet; + } else { + partialResultSets = MockSpanner.toPartialResultSets( + res.resultSet, + call.request!.queryMode, + ); + } + // Resume on the next index after the last one seen by the client. + resumeIndex = + call.request!.resumeToken.length === 0 + ? 0 + : Number.parseInt(call.request!.resumeToken.toString(), 10) + + 1; + for ( + let index = resumeIndex; + index < partialResultSets.length; + index++ + ) { + const streamErr = this.shiftStreamError( + this.executeStreamingSql.name, + index, + ); + if (streamErr) { + call.sendMetadata(new Metadata()); + call.emit('error', streamErr); + break; + } + call.write(partialResultSets[index]); + } + break; + case StatementResultType.UPDATE_COUNT: + call.write( + MockSpanner.emptyPartialResultSet( + precommitToken, + Buffer.from('1'.padStart(8, '0')), + ), + ); + streamErr = this.shiftStreamError( + this.executeStreamingSql.name, + 1, + ); + if (streamErr) { + call.sendMetadata(new Metadata()); + call.emit('error', streamErr); + break; + } + call.write( + MockSpanner.toPartialResultSet(precommitToken, res.updateCount), + ); + break; + case StatementResultType.ERROR: + call.sendMetadata(new Metadata()); + call.emit('error', res.error); + break; + default: + call.emit( + 'error', + new Error(`Unknown StatementResult type: ${res.type}`), + ); + } + } else { + call.emit( + 'error', + new Error(`There is no result registered for ${call.request!.sql}`), + ); + } + call.end(); + }) + .catch(err => { + call.sendMetadata(new Metadata()); + call.emit('error', err); + call.end(); + }); + } + + /** + * Splits a ResultSet into one PartialResultSet per row. This ensure that we can also test returning multiple partial results sets from a streaming method. + * @param resultSet The ResultSet to split. + * @param queryMode The query mode that was used to execute the query. + */ + private static toPartialResultSets( + resultSet: protobuf.ResultSet, + queryMode: + | google.spanner.v1.ExecuteSqlRequest.QueryMode + | keyof typeof google.spanner.v1.ExecuteSqlRequest.QueryMode, + rowsPerPartialResultSet = 1, + ): protobuf.PartialResultSet[] { + const res: protobuf.PartialResultSet[] = []; + let first = true; + for (let i = 0; i < resultSet.rows.length; i += rowsPerPartialResultSet) { + const token = i.toString().padStart(8, '0'); + const partial = protobuf.PartialResultSet.create({ + resumeToken: Buffer.from(token), + values: [], + precommitToken: resultSet.precommitToken, + }); + for ( + let row = i; + row < Math.min(i + rowsPerPartialResultSet, resultSet.rows.length); + row++ + ) { + partial.values.push(...resultSet.rows[row].values!); + } + if (first) { + partial.metadata = resultSet.metadata; + first = false; + } + res.push(partial); + } + if (queryMode === QueryMode.PROFILE || queryMode === 'PROFILE') { + // Include an empty query plan and statistics. + res[res.length - 1].stats = { + queryStats: {fields: {}}, + queryPlan: {planNodes: []}, + }; + } + return res; + } + + private static emptyPartialResultSet( + precommitToken: + | protobuf.IMultiplexedSessionPrecommitToken + | null + | undefined, + resumeToken: Uint8Array, + ): protobuf.PartialResultSet { + return protobuf.PartialResultSet.create({ + resumeToken, + precommitToken: precommitToken, + }); + } + + private static toPartialResultSet( + precommitToken: + | protobuf.IMultiplexedSessionPrecommitToken + | null + | undefined, + rowCount: number, + ): protobuf.PartialResultSet { + const stats = { + rowCountExact: rowCount, + rowCount: 'rowCountExact', + }; + return protobuf.PartialResultSet.create({ + stats, + precommitToken: precommitToken, + }); + } + + private static toResultSet(rowCount: number): protobuf.ResultSet { + const stats = { + rowCountExact: rowCount, + rowCount: 'rowCountExact', + }; + return protobuf.ResultSet.create({ + stats, + }); + } + + executeBatchDml( + call: grpc.ServerUnaryCall< + protobuf.ExecuteBatchDmlRequest, + protobuf.ExecuteBatchDmlResponse + >, + callback: protobuf.Spanner.ExecuteBatchDmlCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.executeBatchDml.name) + .then(() => { + if (call.request!.transaction) { + const fullTransactionId = `${call.request!.session}/transactions/${ + call.request!.transaction.id + }`; + if (this.abortedTransactions.has(fullTransactionId)) { + callback( + MockSpanner.createTransactionAbortedError(`${fullTransactionId}`), + ); + return; + } + } + const results: ResultSet[] = []; + let statementStatus = Status.create({code: grpc.status.OK}); + for ( + let i = 0; + i < call.request!.statements.length && + statementStatus.code === grpc.status.OK; + i++ + ) { + const streamErr = this.shiftStreamError(this.executeBatchDml.name, i); + if (streamErr) { + statementStatus = Status.create({ + code: streamErr.code, + message: streamErr.message, + }); + if (streamErr.metadata && streamErr.metadata.get(RETRY_INFO_BIN)) { + const retryInfo = streamErr.metadata.get(RETRY_INFO_BIN)[0]; + statementStatus.details = [ + Any.create({ + type_url: RETRY_INFO_TYPE, + value: retryInfo, + }), + ]; + } + continue; + } + const statement = call.request!.statements[i]; + const res = this.statementResults.get(statement.sql!); + if (res) { + switch (res.type) { + case StatementResultType.RESULT_SET: + callback(new Error('Wrong result type for batch DML')); + break; + case StatementResultType.UPDATE_COUNT: { + const resultSet = MockSpanner.toResultSet(res.updateCount); + if (call.request!.transaction!.begin && i === 0) { + const transaction = this._updateTransaction( + call.request!.session, + call.request?.transaction!.begin, + ); + if (transaction instanceof Error) { + callback(transaction); + break; + } + resultSet.metadata = protobuf.ResultSetMetadata.create({ + transaction, + }); + } + results.push(resultSet); + break; + } + case StatementResultType.ERROR: + if ((res.error as grpc.ServiceError).code) { + const serviceError = res.error as grpc.ServiceError; + statementStatus = { + code: serviceError.code, + message: serviceError.message, + } as Status; + } else { + statementStatus = { + code: grpc.status.INTERNAL, + message: res.error.message, + } as Status; + } + break; + default: + callback( + new Error(`Unknown StatementResult type: ${res.type}`), + ); + } + } else { + callback( + new Error(`There is no result registered for ${statement.sql}`), + ); + } + } + callback( + null, + ExecuteBatchDmlResponse.create({ + resultSets: results, + status: statementStatus, + }), + ); + }) + .catch(err => { + callback(err); + }); + } + + read( + call: grpc.ServerUnaryCall, + callback: protobuf.Spanner.ReadCallback, + ) { + this.pushRequest(call.request!, call.metadata); + callback(createUnimplementedError('Read is not yet implemented')); + } + + streamingRead(call: grpc.ServerWritableStream) { + this.pushRequest(call.request!, call.metadata); + + this.simulateExecutionTime(this.streamingRead.name) + .then(() => { + let transactionKey; + if (call.request!.transaction) { + const fullTransactionId = `${call.request!.session}/transactions/${ + call.request!.transaction.id + }`; + transactionKey = fullTransactionId; + if (this.abortedTransactions.has(fullTransactionId)) { + call.sendMetadata(new Metadata()); + call.emit( + 'error', + MockSpanner.createTransactionAbortedError(`${fullTransactionId}`), + ); + call.end(); + return; + } + } + const keySet = JSON.stringify( + call.request!.keySet ?? {}, + Object.keys(call.request!.keySet ?? {}).sort(), + ); + const key = `${call.request!.table}|${keySet}`; + const res = this.readRequestResults.get(key); + const session = this.sessions.get(call.request!.session); + if (res) { + if (call.request!.transaction?.begin) { + const txn = this._updateTransaction( + call.request!.session, + call.request!.transaction.begin, + ); + if (txn instanceof Error) { + call.sendMetadata(new Metadata()); + call.emit('error', txn); + call.end(); + return; + } + transactionKey = `${call.request!.session}/transactions/${txn.id.toString()}`; + if (res.type === ReadRequestResultType.RESULT_SET) { + call.sendMetadata(new Metadata()); + (res.resultSet as protobuf.ResultSet).metadata!.transaction = txn; + } + } + + // get the current seqNum + const currentSeqNum = this.transactionSeqNum.get(transactionKey) || 0; + const nextSeqNum = currentSeqNum + 1; + + // set the next SeqNum + this.transactionSeqNum.set(transactionKey, nextSeqNum); + const precommitToken = session?.multiplexed + ? protobuf.MultiplexedSessionPrecommitToken.create({ + precommitToken: Buffer.from('mock-precommit-token'), + seqNum: nextSeqNum, + }) + : null; + let partialResultSets; + let resumeIndex; + switch (res.type) { + case ReadRequestResultType.RESULT_SET: + (res.resultSet as protobuf.ResultSet).precommitToken = + precommitToken; + if (Array.isArray(res.resultSet)) { + partialResultSets = res.resultSet; + } else { + partialResultSets = MockSpanner.toPartialResultSets( + res.resultSet, + 'NORMAL', + ); + } + // Resume on the next index after the last one seen by the client. + resumeIndex = + call.request!.resumeToken.length === 0 + ? 0 + : parseInt( + Buffer.from(call.request!.resumeToken).toString(), + 10, + ) + 1; + for ( + let index = resumeIndex; + index < partialResultSets.length; + index++ + ) { + const streamErr = this.shiftStreamError( + this.streamingRead.name, + index, + ); + if (streamErr) { + call.sendMetadata(new Metadata()); + call.emit('error', streamErr); + break; + } + call.write(partialResultSets[index]); + } + break; + case ReadRequestResultType.ERROR: + call.sendMetadata(new Metadata()); + call.emit('error', res.error); + break; + default: + call.emit( + 'error', + new Error(`Unknown ReadRequestResult type: ${res.type}`), + ); + } + } else { + call.emit( + 'error', + new Error( + `There is no result registered for ${call.request!.table}`, + ), + ); + } + call.end(); + }) + .catch(err => { + call.sendMetadata(new Metadata()); + call.emit('error', err); + call.end(); + }); + } + + beginTransaction( + call: grpc.ServerUnaryCall< + protobuf.BeginTransactionRequest, + protobuf.Transaction + >, + callback: protobuf.Spanner.BeginTransactionCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.beginTransaction.name) + .then(() => { + this.mutationOnly = call.request.mutationKey ? true : false; + const res = this._updateTransaction( + call.request!.session, + call.request!.options, + ); + if (res instanceof Error) { + callback(res); + } else { + callback(null, res); + } + }) + .catch(err => { + callback(err); + }); + } + + commit( + call: grpc.ServerUnaryCall, + callback: protobuf.Spanner.CommitCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.commit.name) + .then(() => { + const fullTransactionId = `${call.request!.session}/transactions/${ + call.request!.transactionId + }`; + if (this.abortedTransactions.has(fullTransactionId)) { + callback( + MockSpanner.createTransactionAbortedError(`${fullTransactionId}`), + ); + return; + } + const session = this.sessions.get(call.request!.session); + if (session) { + if (call.request!.transactionId) { + const buffer = Buffer.from(call.request!.transactionId as string); + const transactionId = buffer.toString(); + const fullTransactionId = + session.name + '/transactions/' + transactionId; + const transaction = this.transactions.get(fullTransactionId); + if (transaction) { + // unique transaction key + const transactionKey = `${call.request.session}/transactions/${call.request.transactionId}`; + // delete the transaction key + this.transactionSeqNum.delete(transactionKey); + this.transactions.delete(fullTransactionId); + this.transactionOptions.delete(fullTransactionId); + callback( + null, + protobuf.CommitResponse.create({ + commitTimestamp: now(), + }), + ); + } else { + callback( + MockSpanner.createTransactionNotFoundError(fullTransactionId), + ); + } + } else if (call.request!.singleUseTransaction) { + callback( + null, + protobuf.CommitResponse.create({ + commitTimestamp: now(), + }), + ); + } + } else { + callback( + MockSpanner.createSessionNotFoundError(call.request!.session), + ); + } + }) + .catch(err => { + callback(err); + }); + } + + rollback( + call: grpc.ServerUnaryCall, + callback: protobuf.Spanner.RollbackCallback, + ) { + this.pushRequest(call.request!, call.metadata); + const session = this.sessions.get(call.request!.session); + if (session) { + const buffer = Buffer.from(call.request!.transactionId as string); + const transactionId = buffer.toString(); + const fullTransactionId = session.name + '/transactions/' + transactionId; + const transaction = this.transactions.get(fullTransactionId); + if (transaction) { + // unique transaction key + const transactionKey = `${call.request.session}/transactions/${call.request.transactionId}`; + // delete the key + this.transactionSeqNum.delete(transactionKey); + this.transactions.delete(fullTransactionId); + this.transactionOptions.delete(fullTransactionId); + callback(null, google.protobuf.Empty.create()); + } else { + callback(MockSpanner.createTransactionNotFoundError(fullTransactionId)); + } + } else { + callback(MockSpanner.createSessionNotFoundError(call.request!.session)); + } + } + + partitionQuery( + call: grpc.ServerUnaryCall, + callback: protobuf.Spanner.PartitionQueryCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.partitionQuery.name) + .then(() => { + const response = protobuf.PartitionResponse.create({ + partitions: [{partitionToken: Buffer.from('mock-token')}], + }); + callback(null, response); + }) + .catch(err => callback(err)); + } + + partitionRead( + call: grpc.ServerUnaryCall, + callback: protobuf.Spanner.PartitionReadCallback, + ) { + this.pushRequest(call.request!, call.metadata); + this.simulateExecutionTime(this.partitionRead.name) + .then(() => { + const response = protobuf.PartitionResponse.create({ + partitions: [{partitionToken: Buffer.from('mock-token')}], + }); + callback(null, response); + }) + .catch(err => callback(err)); + } + + batchWrite( + call: grpc.ServerWritableStream< + protobuf.BatchWriteRequest, + protobuf.BatchWriteResponse + >, + ) { + this.pushRequest(call.request, call.metadata); + this.simulateExecutionTime(this.batchWrite.name) + .then(() => { + const response = protobuf.BatchWriteResponse.create({ + commitTimestamp: now(), + }); + call.write(response); + call.end(); + }) + .catch(err => call.destroy(err)); + } + + private _updateTransaction( + sessionName: string, + options: google.spanner.v1.ITransactionOptions | null | undefined, + ): google.spanner.v1.Transaction | ServiceError { + const session = this.sessions.get(sessionName); + if (!session) { + return MockSpanner.createSessionNotFoundError(sessionName); + } + let counter = this.transactionCounters.get(session.name); + if (!counter) { + counter = 0; + } + const id = ++counter; + this.transactionCounters.set(session.name, counter); + const transactionId = id.toString().padStart(12, '0'); + const fullTransactionId = session.name + '/transactions/' + transactionId; + const readTimestamp = options && options.readOnly ? now() : undefined; + let precommitToken; + if (this.mutationOnly && session.multiplexed && options?.readWrite) { + // get the current seqNum + const currentSeqNum = this.transactionSeqNum.get(fullTransactionId) || 0; + const nextSeqNum = currentSeqNum + 1; + // set the next seqNum + this.transactionSeqNum.set(fullTransactionId, nextSeqNum); + precommitToken = { + precommitToken: Buffer.from('mock-precommit-token'), + seqNum: nextSeqNum, + }; + } + const transaction = protobuf.Transaction.create({ + id: Buffer.from(transactionId), + readTimestamp, + precommitToken, + }); + this.transactions.set(fullTransactionId, transaction); + this.transactionOptions.set(fullTransactionId, options); + return transaction; + } +} + +/** + * Creates and adds a MockSpanner instance to the given server. The MockSpanner instance does not contain any mocked results. + */ +export function createMockSpanner(server: grpc.Server): MockSpanner { + const mock = MockSpanner.create(); + server.addService(spannerProtoDescriptor.Spanner.service, { + batchCreateSessions: mock.batchCreateSessions, + createSession: mock.createSession, + getSession: mock.getSession, + listSessions: mock.listSessions, + deleteSession: mock.deleteSession, + executeSql: mock.executeSql, + executeStreamingSql: mock.executeStreamingSql, + executeBatchDml: mock.executeBatchDml, + read: mock.read, + streamingRead: mock.streamingRead, + beginTransaction: mock.beginTransaction, + commit: mock.commit, + rollback: mock.rollback, + partitionQuery: mock.partitionQuery, + partitionRead: mock.partitionRead, + batchWrite: mock.batchWrite, + }); + return mock; +} + +/** + * Creates a simple result set containing the following data: + * + * |-------------------------------| + * | ID (STRING) | VALUE (STRING) | + * |-------------------------------| + * | 'a' | 'Alpha' | + * | 'b' | 'Beta' | + * | 'c' | 'Gamma' | + * -------------------------------- + * + * This ResultSet can be used to mock read operations in a mock Spanner server. + */ +export function createReadRequestResultSet(): protobuf.ResultSet { + const fields = [ + protobuf.StructType.Field.create({ + name: 'ID', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + protobuf.StructType.Field.create({ + name: 'VALUE', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({fields}), + }); + + return protobuf.ResultSet.create({ + metadata, + rows: [ + {values: [{stringValue: 'a'}, {stringValue: 'Alpha'}]}, + {values: [{stringValue: 'b'}, {stringValue: 'Beta'}]}, + {values: [{stringValue: 'c'}, {stringValue: 'Gamma'}]}, + ], + }); +} + +/** + * Creates a simple result set containing the following data: + * + * |-----------------------------| + * | NUM (INT64) | NAME (STRING) | + * |-----------------------------| + * | 1 | 'One' | + * | 2 | 'Two' | + * | 3 | 'Three' | + * ------------------------------- + * + * This ResultSet can be used to easily mock queries on a mock Spanner server. + */ +export function createSimpleResultSet(): protobuf.ResultSet { + const fields = [ + protobuf.StructType.Field.create({ + name: 'NUM', + type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), + }), + protobuf.StructType.Field.create({ + name: 'NAME', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + return protobuf.ResultSet.create({ + metadata, + rows: [ + {values: [{stringValue: '1'}, {stringValue: 'One'}]}, + {values: [{stringValue: '2'}, {stringValue: 'Two'}]}, + {values: [{stringValue: '3'}, {stringValue: 'Three'}]}, + ], + }); +} + +export const NUM_ROWS_LARGE_RESULT_SET = 100; + +export function createLargeResultSet(): protobuf.ResultSet { + const fields = [ + protobuf.StructType.Field.create({ + name: 'NUM', + type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), + }), + protobuf.StructType.Field.create({ + name: 'NAME', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + const rows: google.protobuf.IListValue[] = []; + for (let num = 1; num <= NUM_ROWS_LARGE_RESULT_SET; num++) { + rows.push({ + values: [ + {stringValue: `${num}`}, + {stringValue: generateRandomString(100)}, + ], + }); + } + return protobuf.ResultSet.create({ + metadata, + rows, + }); +} + +export function createSelect1ResultSet(): protobuf.ResultSet { + const fields = [ + protobuf.StructType.Field.create({ + name: '', + type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + return protobuf.ResultSet.create({ + metadata, + rows: [{values: [{stringValue: '1'}]}], + }); +} + +export function createResultSetWithAllDataTypes(): protobuf.ResultSet { + const fields = [ + protobuf.StructType.Field.create({ + name: 'COLBOOL', + type: protobuf.Type.create({code: protobuf.TypeCode.BOOL}), + }), + protobuf.StructType.Field.create({ + name: 'COLINT64', + type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), + }), + protobuf.StructType.Field.create({ + name: 'COLFLOAT64', + type: protobuf.Type.create({code: protobuf.TypeCode.FLOAT64}), + }), + protobuf.StructType.Field.create({ + name: 'COLNUMERIC', + type: protobuf.Type.create({code: protobuf.TypeCode.NUMERIC}), + }), + protobuf.StructType.Field.create({ + name: 'COLSTRING', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + protobuf.StructType.Field.create({ + name: 'COLBYTES', + type: protobuf.Type.create({code: protobuf.TypeCode.BYTES}), + }), + protobuf.StructType.Field.create({ + name: 'COLJSON', + type: protobuf.Type.create({code: protobuf.TypeCode.JSON}), + }), + protobuf.StructType.Field.create({ + name: 'COLDATE', + type: protobuf.Type.create({code: protobuf.TypeCode.DATE}), + }), + protobuf.StructType.Field.create({ + name: 'COLTIMESTAMP', + type: protobuf.Type.create({code: protobuf.TypeCode.TIMESTAMP}), + }), + protobuf.StructType.Field.create({ + name: 'COLBOOLARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.BOOL}), + }), + }), + protobuf.StructType.Field.create({ + name: 'COLINT64ARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.INT64}), + }), + }), + protobuf.StructType.Field.create({ + name: 'COLFLOAT64ARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({ + code: protobuf.TypeCode.FLOAT64, + }), + }), + }), + protobuf.StructType.Field.create({ + name: 'COLNUMERICARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({ + code: protobuf.TypeCode.NUMERIC, + }), + }), + }), + protobuf.StructType.Field.create({ + name: 'COLSTRINGARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({ + code: protobuf.TypeCode.STRING, + }), + }), + }), + protobuf.StructType.Field.create({ + name: 'COLBYTESARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.BYTES}), + }), + }), + protobuf.StructType.Field.create({ + name: 'COLJSONARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.JSON}), + }), + }), + protobuf.StructType.Field.create({ + name: 'COLDATEARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.DATE}), + }), + }), + protobuf.StructType.Field.create({ + name: 'COLTIMESTAMPARRAY', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({ + code: protobuf.TypeCode.TIMESTAMP, + }), + }), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + return protobuf.ResultSet.create({ + metadata, + rows: [ + { + values: [ + {boolValue: true}, + {stringValue: '1'}, + {numberValue: 3.14}, + {stringValue: '6.626'}, + {stringValue: 'One'}, + {stringValue: Buffer.from('test').toString('base64')}, + {stringValue: '{"result":true, "count":42}'}, + {stringValue: '2021-05-11'}, + {stringValue: '2021-05-11T16:46:04.872Z'}, + { + listValue: { + values: [ + {boolValue: true}, + {boolValue: false}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '1'}, + {stringValue: '100'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {numberValue: 3.14}, + {numberValue: 100.9}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '6.626'}, + {stringValue: '100'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: 'One'}, + {stringValue: 'test'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: Buffer.from('test1').toString('base64')}, + {stringValue: Buffer.from('test2').toString('base64')}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '{"result":true, "count":42}'}, + {stringValue: '{}'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '2021-05-12'}, + {stringValue: '2000-02-29'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '2021-05-12T08:38:19.8474Z'}, + {stringValue: '2000-02-29T07:00:00Z'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + ], + }, + { + values: [ + {boolValue: false}, + {stringValue: '2'}, + {numberValue: 3.14}, + {stringValue: '6.626'}, + {stringValue: 'Two'}, + {stringValue: Buffer.from('test').toString('base64')}, + {stringValue: '{"result":true, "count":42}'}, + {stringValue: '2021-05-11'}, + {stringValue: '2021-05-11T16:46:04.872Z'}, + { + listValue: { + values: [ + {boolValue: true}, + {boolValue: false}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '2'}, + {stringValue: '200'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {numberValue: 3.14}, + {numberValue: 100.9}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '6.626'}, + {stringValue: '100'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: 'Two'}, + {stringValue: 'test'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: Buffer.from('test1').toString('base64')}, + {stringValue: Buffer.from('test2').toString('base64')}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '{"result":true, "count":42}'}, + {stringValue: '{}'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '2021-05-12'}, + {stringValue: '2000-02-29'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + { + listValue: { + values: [ + {stringValue: '2021-05-12T08:38:19.8474Z'}, + {stringValue: '2000-02-29T07:00:00Z'}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + ], + }, + { + values: [ + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + {nullValue: NullValue.NULL_VALUE}, + ], + }, + ], + }); +} + +export function createResultSetWithStringArray(): protobuf.ResultSet { + const fields = [ + protobuf.StructType.Field.create({ + name: 'string1', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + protobuf.StructType.Field.create({ + name: 'string2', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + protobuf.StructType.Field.create({ + name: 'bool1', + type: protobuf.Type.create({code: protobuf.TypeCode.BOOL}), + }), + protobuf.StructType.Field.create({ + name: 'stringArray', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({ + code: protobuf.TypeCode.STRING, + }), + }), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + return protobuf.ResultSet.create({ + metadata, + rows: [ + { + values: [ + {stringValue: 'test1_1'}, + {stringValue: 'test2_1'}, + {boolValue: true}, + { + listValue: { + values: [{stringValue: 'One'}, {stringValue: 'test 1'}], + }, + }, + ], + }, + { + values: [ + {stringValue: 'test1_2'}, + {stringValue: 'test2_2'}, + {boolValue: true}, + { + listValue: { + values: [{stringValue: 'Two'}, {stringValue: 'test 2'}], + }, + }, + ], + }, + { + values: [ + {stringValue: 'test1_3'}, + {stringValue: 'test2_3'}, + {boolValue: true}, + { + listValue: { + values: [{stringValue: 'Three'}, {stringValue: 'test 3'}], + }, + }, + ], + }, + ], + }); +} + +function generateRandomString(length: number) { + let result = ''; + const characters = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + const charactersLength = characters.length; + for (let i = 0; i < length; i++) { + result += characters.charAt(Math.floor(Math.random() * charactersLength)); + } + return result; +} + +/** + * Returns a protobuf Timestamp containing the current local system time. + */ +export function now(): Timestamp { + const now = Date.now(); + return Timestamp.create({seconds: now / 1000, nanos: (now % 1000) * 1e6}); +} diff --git a/handwritten/spanner/test/multiplexed-session.ts b/handwritten/spanner/test/multiplexed-session.ts new file mode 100644 index 00000000000..d21f912f5e8 --- /dev/null +++ b/handwritten/spanner/test/multiplexed-session.ts @@ -0,0 +1,290 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {beforeEach, afterEach, describe, it} from 'mocha'; +import * as events from 'events'; +import * as sinon from 'sinon'; +import {Database} from '../src/database'; +import {Session} from '../src/session'; +import {MultiplexedSession} from '../src/multiplexed-session'; +import {Transaction} from '../src/transaction'; +import {FakeTransaction} from './session-pool'; +import {grpc} from 'google-gax'; + +describe('MultiplexedSession', () => { + let multiplexedSession; + + function noop() {} + const DATABASE = { + createSession: noop, + databaseRole: 'parent_role', + } as unknown as Database; + + let fakeMuxSession; + let createSessionStub; + const sandbox = sinon.createSandbox(); + + const createSession = (name = 'id', props?): Session => { + props = props || {multiplexed: true}; + + return Object.assign(new Session(DATABASE, name), props, { + create: sandbox.stub().resolves(), + transaction: sandbox.stub().returns(new FakeTransaction()), + }); + }; + + beforeEach(() => { + fakeMuxSession = createSession(); + createSessionStub = sandbox + .stub(DATABASE, 'createSession') + .withArgs({multiplexed: true}) + .callsFake(() => { + return Promise.resolve([fakeMuxSession]); + }); + multiplexedSession = new MultiplexedSession(DATABASE); + }); + + afterEach(() => { + sandbox.restore(); + }); + + describe('instantiation', () => { + it('should correctly initialize the fields', () => { + assert.strictEqual(multiplexedSession.database, DATABASE); + assert.strictEqual(multiplexedSession.refreshRate, 7); + assert.deepStrictEqual(multiplexedSession._multiplexedSession, null); + assert(multiplexedSession instanceof events.EventEmitter); + assert.strictEqual( + (multiplexedSession as MultiplexedSession)._sharedMuxSessionWaitPromise, + null, + ); + }); + }); + + describe('createSession', () => { + let _createSessionStub; + let _maintainStub; + + beforeEach(() => { + _maintainStub = sandbox.stub(multiplexedSession, '_maintain'); + _createSessionStub = sandbox + .stub(multiplexedSession, '_createSession') + .resolves(); + }); + + it('should create mux session', () => { + multiplexedSession.createSession(); + assert.strictEqual(_createSessionStub.callCount, 1); + }); + + it('should start housekeeping', done => { + multiplexedSession.createSession(); + setImmediate(() => { + try { + assert.strictEqual(_maintainStub.callCount, 1); + done(); + } catch (err) { + done(err); + } + }); + }); + + it('should not throw error when database not found', async () => { + const error = { + code: grpc.status.NOT_FOUND, + message: 'Database not found', + } as grpc.ServiceError; + const multiplexedSession = new MultiplexedSession(DATABASE); + sandbox.stub(multiplexedSession, '_createSession').rejects(error); + + try { + await multiplexedSession.createSession(); + } catch (err) { + assert.ifError(err); + } + }); + }); + + describe('_maintain', () => { + let clock; + let createSessionStub; + + beforeEach(() => { + createSessionStub = sandbox + .stub(multiplexedSession, '_createSession') + .resolves(); + clock = sandbox.useFakeTimers(); + }); + + afterEach(() => { + clock.restore(); + }); + + it('should set an interval to refresh mux sessions', () => { + const expectedInterval = + multiplexedSession.refreshRate! * 24 * 60 * 60000; + + multiplexedSession._maintain(); + clock.tick(expectedInterval); + assert.strictEqual(createSessionStub.callCount, 1); + }); + }); + + describe('_createSession', () => { + it('should create the mux sessions with multiplexed option', async () => { + await multiplexedSession._createSession(); + assert.strictEqual(createSessionStub.callCount, 1); + assert.deepStrictEqual(createSessionStub.lastCall.args[0], { + multiplexed: true, + }); + }); + + it('should reject with any request errors', async () => { + const error = new Error('create session error'); + createSessionStub.rejects(error); + + try { + await multiplexedSession._createSession(); + throw new Error('Should not make it this far.'); + } catch (e) { + assert.strictEqual(e, error); + } + }); + }); + + describe('getSession', () => { + it('should acquire a session', done => { + sandbox.stub(multiplexedSession, '_getSession').resolves(fakeMuxSession); + multiplexedSession.getSession((err, session) => { + assert.ifError(err); + assert.strictEqual(session, fakeMuxSession); + done(); + }); + }); + + it('should pass any errors to the callback', done => { + const error = new Error('err'); + sandbox.stub(multiplexedSession, '_getSession').rejects(error); + multiplexedSession.getSession(err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should pass back the session and txn', done => { + const fakeTxn = new FakeTransaction() as unknown as Transaction; + sandbox.stub(multiplexedSession, '_getSession').resolves(fakeMuxSession); + multiplexedSession.getSession((err, session, txn) => { + assert.ifError(err); + assert.strictEqual(session, fakeMuxSession); + assert.deepStrictEqual(txn, fakeTxn); + done(); + }); + }); + }); + + describe('_getSession', () => { + it('should return a session if one is available (Cache Hit)', async () => { + const createSessionStub = sandbox + .stub(multiplexedSession, '_createSession') + .resolves(fakeMuxSession); + multiplexedSession._multiplexedSession = fakeMuxSession; + assert.doesNotThrow(async () => { + const session = await multiplexedSession._getSession(); + assert.strictEqual(session, fakeMuxSession); + }); + // ensure _createSession was not called + sinon.assert.notCalled(createSessionStub); + }); + + it('should wait for a pending session to become available (Join Existing)', async () => { + const multiplexedSession = new MultiplexedSession(DATABASE); + + // create a manual lock to simulate another request currently running + let resolveLock!: () => void; + const pendingLock = new Promise(resolve => { + resolveLock = resolve; + }); + + // inject the lock into the class + multiplexedSession._sharedMuxSessionWaitPromise = pendingLock; + + // stub _createSession to verify it is NOT called (since we are joining an existing one) + const createSessionStub = sandbox + .stub(multiplexedSession, '_createSession') + .resolves(); + + // call _getSession() but do not await it yet + // it will hit the "await this._sharedMuxSessionWaitPromise" line and pause there + const getSessionPromise = multiplexedSession._getSession(); + + // now, simulate the "other" request finishing successfully: + // set the session (as if the background task finished) + multiplexedSession._multiplexedSession = fakeMuxSession; + + // now resolve the lock to wake up _getSession + resolveLock(); + + // wait for the method to finish + const session = await getSessionPromise; + assert.strictEqual(session, fakeMuxSession); + + // ensure _createSession was not called + sinon.assert.notCalled(createSessionStub); + }); + + it('should create a new session if none exists and no creation is in progress', async () => { + // ensure _multiplexedSession & _sharedMuxSessionWaitPromise is null + multiplexedSession._multiplexedSession = null; + multiplexedSession._sharedMuxSessionWaitPromise = null; + + // stub _createSession to simulate success + const createSessionStub = sandbox + .stub(multiplexedSession, '_createSession') + .callsFake(async () => { + multiplexedSession._multiplexedSession = fakeMuxSession; + }); + + assert.doesNotThrow(async () => { + const session = await multiplexedSession._getSession(); + assert.strictEqual(session, fakeMuxSession); + }); + + // ensure _createSession was called + sinon.assert.calledOnce(createSessionStub); + }); + + it('should propagate errors if session creation fails', async () => { + const fakeError = new Error('Network Error'); + // ensure that _multiplexedSession is null + multiplexedSession._multiplexedSession = null; + + // stub creation to fail + const createSessionStub = sandbox + .stub(multiplexedSession, '_createSession') + .rejects(fakeError); + + try { + await multiplexedSession._getSession(); + } catch (err) { + assert.strictEqual(err, fakeError); + } + // ensure _createSession was called + sinon.assert.calledOnce(createSessionStub); + }); + }); +}); diff --git a/handwritten/spanner/test/partial-result-stream.ts b/handwritten/spanner/test/partial-result-stream.ts new file mode 100644 index 00000000000..957c5f69c57 --- /dev/null +++ b/handwritten/spanner/test/partial-result-stream.ts @@ -0,0 +1,529 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const checkpointStream = require('checkpoint-stream'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const concat = require('concat-stream'); +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import {Transform} from 'stream'; +import * as through from 'through2'; + +import {codec} from '../src/codec'; +import * as prs from '../src/partial-result-stream'; +import {grpc} from 'google-gax'; +import {Row} from '../src/partial-result-stream'; + +describe('PartialResultStream', () => { + const sandbox = sinon.createSandbox(); + + // tslint:disable-next-line variable-name + let PartialResultStream: typeof prs.PartialResultStream; + let partialResultStream; + + const NAME = 'f1'; + const VALUE = 'abc'; + const STATS = {rowCountExact: 1}; + + const EXPECTED_ROW = [{name: NAME, value: VALUE}]; + + const RESULT = { + metadata: { + rowType: { + fields: [ + { + name: NAME, + type: {code: 'STRING'}, + }, + ], + }, + }, + stats: STATS, + values: [convertToIValue(VALUE)], + }; + + before(() => { + const prsExports = proxyquire('../src/partial-result-stream.js', { + 'checkpoint-stream': checkpointStream, + stream: {Transform}, + './codec': {codec}, + }); + + PartialResultStream = prsExports.PartialResultStream; + partialResultStream = prsExports.partialResultStream; + }); + + afterEach(() => sandbox.restore()); + + describe('acceptance tests', () => { + const TESTS = + require('../../test/data/streaming-read-acceptance-test.json').tests; + + beforeEach(() => { + sandbox.stub(codec, 'decode').callsFake(value => value); + }); + + TESTS.forEach(test => { + it(`should pass acceptance test: ${test.name}`, done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const values: any[] = []; + const stream = new PartialResultStream({}); + + stream + .on('error', done) + .on('data', row => { + values.push(row.map(({value}) => value)); + }) + .on('end', () => { + assert.deepStrictEqual(values, test.result.value); + done(); + }); + + test.chunks.forEach(chunk => { + const parsed = JSON.parse(chunk); + // for whatever reason the acceptance test values come as raw values + // where as grpc gives them to us as google.protobuf.Value objects + parsed.values = parsed.values.map(convertToIValue); + stream.write(parsed); + }); + + stream.end(); + }); + }); + }); + + // use this block to test anything the acceptance tests don't cover + describe('PartialResultStream', () => { + let stream: prs.PartialResultStream; + + beforeEach(() => { + stream = new PartialResultStream({}); + }); + + afterEach(() => stream.destroy()); + + it('should emit the response', done => { + const stream = new PartialResultStream({}); + + stream.on('error', done).on('response', response => { + assert.strictEqual(response, RESULT); + done(); + }); + + stream.write(RESULT); + }); + + it('should emit the result stats', done => { + stream.on('error', done).on('stats', stats => { + assert.strictEqual(stats, STATS); + done(); + }); + + stream.write(RESULT); + }); + + it('should "skip" responses with empty values', done => { + const fakeResponse = Object.assign({}, RESULT, {values: []}); + const shouldNotBeCalled = () => { + done(new Error('Should not be called.')); + }; + + stream + .on('error', done) + .on('data', shouldNotBeCalled) + .on('response', response => { + assert.strictEqual(response, fakeResponse); + done(); + }); + + stream.write(fakeResponse); + }); + + it('should emit rows', done => { + stream.on('error', done).on('data', row => { + assert.deepStrictEqual(row, EXPECTED_ROW); + done(); + }); + + stream.write(RESULT); + }); + + it('should emit rows as JSON', done => { + const jsonOptions = {}; + const stream = new PartialResultStream({json: true, jsonOptions}); + + const fakeJson = {}; + const stub = sandbox.stub(codec, 'convertFieldsToJson').returns(fakeJson); + + stream.on('error', done).on('data', json => { + assert.deepStrictEqual(json, fakeJson); + + const [row, options] = stub.lastCall.args; + assert.deepStrictEqual(row, EXPECTED_ROW); + assert.strictEqual(options, jsonOptions); + done(); + }); + + stream.write(RESULT); + }); + + describe('destroy', () => { + it('should ponyfill the destroy method', done => { + const fakeError = new Error('err'); + + const errorStub = sandbox.stub().withArgs(fakeError); + const closeStub = sandbox.stub(); + + stream.on('error', errorStub).on('close', closeStub); + stream.destroy(fakeError); + + setImmediate(() => { + assert.strictEqual(errorStub.callCount, 1); + assert.strictEqual(closeStub.callCount, 1); + done(); + }); + }); + }); + + it('should not lose data if paused when last chunk is received', done => { + const stream = new PartialResultStream({}); + // Pause the stream initially to force buffering + stream.pause(); + + const rows: any[] = []; + stream.on('data', row => rows.push(row)); + stream.on('end', () => { + try { + // We expect 2 rows. + assert.strictEqual(rows.length, 2); + done(); + } catch (e) { + done(e); + } + }); + + const fields = [{name: NAME, type: {code: 'STRING'}}]; + + // Write a normal chunk + stream.write({ + metadata: {rowType: {fields}}, + values: [convertToIValue('row1')], + resumeToken: 't1', + }); + + // Write the last chunk immediately + stream.write({ + values: [convertToIValue('row2')], + resumeToken: 't2', + last: true, + }); + + // Resume after a tick. + // If emit('end') was called synchronously during write, the 'end' event might fire + // and close the stream before we consume the buffered 'row1' and 'row2'. + // With push(null), it waits for buffer to drain. + process.nextTick(() => { + stream.resume(); + }); + }); + }); + + describe('partialResultStream', () => { + let stream: prs.PartialResultStream; + let fakeRequestStream; + + const RESULT_WITH_TOKEN = Object.assign({}, RESULT, { + resumeToken: '...', + }); + + beforeEach(() => { + fakeRequestStream = through.obj(); + stream = partialResultStream(() => fakeRequestStream); + }); + + it('should only push rows when there is a token', done => { + const expectedRow = sinon.match(EXPECTED_ROW); + const stub = sandbox + .stub() + .withArgs(expectedRow) + .callsFake(() => { + if (stub.callCount === 3) { + done(); + } + }); + + function assertDoesNotEmit() { + done(new Error('Should not be called.')); + } + + stream.on('data', assertDoesNotEmit); + fakeRequestStream.push(RESULT); + fakeRequestStream.push(RESULT); + stream.removeListener('data', assertDoesNotEmit); + + stream.on('data', stub); + fakeRequestStream.push(RESULT_WITH_TOKEN); + fakeRequestStream.push(null); + }); + + it('should not queue more than 10 results', done => { + for (let i = 0; i < 11; i += 1) { + fakeRequestStream.push(RESULT); + } + + fakeRequestStream.push(null); + + stream.on('error', done).pipe( + concat(rows => { + assert.strictEqual(rows.length, 11); + done(); + }), + ); + }); + + it('should retry if the initial call returned a retryable error', done => { + // This test will emit two rows total: + // - UNAVAILABLE error (should retry) + // - Two rows + // - Confirm all rows were received. + const fakeCheckpointStream = through.obj(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (fakeCheckpointStream as any).reset = () => {}; + + sandbox.stub(checkpointStream, 'obj').returns(fakeCheckpointStream); + + const firstFakeRequestStream = through.obj(); + const secondFakeRequestStream = through.obj(); + + const requestFnStub = sandbox.stub(); + + requestFnStub.onCall(0).callsFake(() => { + setTimeout(() => { + // This causes a new request stream to be created. + firstFakeRequestStream.emit('error', { + code: grpc.status.UNAVAILABLE, + message: 'Error.', + } as grpc.ServiceError); + }, 50); + + return firstFakeRequestStream; + }); + + requestFnStub.onCall(1).callsFake(resumeToken => { + assert.ok( + !resumeToken, + 'Retry should be called with empty resume token', + ); + + setTimeout(() => { + secondFakeRequestStream.push(RESULT_WITH_TOKEN); + fakeCheckpointStream.emit('checkpoint', RESULT_WITH_TOKEN); + secondFakeRequestStream.push(RESULT_WITH_TOKEN); + fakeCheckpointStream.emit('checkpoint', RESULT_WITH_TOKEN); + + secondFakeRequestStream.end(); + }, 500); + + return secondFakeRequestStream; + }); + + partialResultStream(requestFnStub) + .on('error', done) + .pipe( + concat(rows => { + assert.strictEqual(rows.length, 2); + done(); + }), + ); + }); + + it('should get Deadline exceeded error if timeout has reached', done => { + const fakeCheckpointStream = through.obj(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (fakeCheckpointStream as any).reset = () => {}; + + sandbox.stub(checkpointStream, 'obj').returns(fakeCheckpointStream); + + const firstFakeRequestStream = through.obj(); + + const requestFnStub = sandbox.stub(); + + requestFnStub.onCall(0).callsFake(() => { + setTimeout(() => { + // This causes a new request stream to be created. + firstFakeRequestStream.emit('error', { + code: grpc.status.UNAVAILABLE, + message: 'Error.', + } as grpc.ServiceError); + }, 50); + + return firstFakeRequestStream; + }); + + partialResultStream(requestFnStub, {gaxOptions: {timeout: 0}}) + .on('data', () => {}) + .on('error', err => { + assert.strictEqual(err.code, grpc.status.DEADLINE_EXCEEDED); + assert.strictEqual(requestFnStub.callCount, 1); + done(); + }); + }); + + it('should resume if there was a retryable error', done => { + // This test will emit four rows total: + // - Two rows + // - Error event (should retry) + // - Two rows + // - Confirm all rows were received. + const fakeCheckpointStream = through.obj(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (fakeCheckpointStream as any).reset = () => {}; + sandbox.stub(checkpointStream, 'obj').returns(fakeCheckpointStream); + + const firstFakeRequestStream = through.obj(); + const secondFakeRequestStream = through.obj(); + + const requestFnStub = sandbox.stub(); + + requestFnStub.onCall(0).callsFake(() => { + setTimeout(() => { + firstFakeRequestStream.push(RESULT_WITH_TOKEN); + fakeCheckpointStream.emit('checkpoint', RESULT_WITH_TOKEN); + firstFakeRequestStream.push(RESULT_WITH_TOKEN); + fakeCheckpointStream.emit('checkpoint', RESULT_WITH_TOKEN); + + setTimeout(() => { + // This causes a new request stream to be created. + firstFakeRequestStream.emit('error', { + code: grpc.status.UNAVAILABLE, + message: 'Error.', + } as grpc.ServiceError); + }, 50); + }, 50); + + return firstFakeRequestStream; + }); + + requestFnStub.onCall(1).callsFake(resumeToken => { + assert.strictEqual(resumeToken, RESULT_WITH_TOKEN.resumeToken); + + setTimeout(() => { + secondFakeRequestStream.push(RESULT_WITH_TOKEN); + fakeCheckpointStream.emit('checkpoint', RESULT_WITH_TOKEN); + secondFakeRequestStream.push(RESULT_WITH_TOKEN); + fakeCheckpointStream.emit('checkpoint', RESULT_WITH_TOKEN); + + secondFakeRequestStream.end(); + }, 500); + + return secondFakeRequestStream; + }); + + partialResultStream(requestFnStub) + .on('error', done) + .pipe( + concat(rows => { + assert.strictEqual(rows.length, 4); + done(); + }), + ); + }); + + it('should emit non-retryable error', done => { + // This test will emit two rows and then an error. + const fakeCheckpointStream = through.obj(); + sandbox.stub(checkpointStream, 'obj').returns(fakeCheckpointStream); + + const fakeRequestStream = through.obj(); + + const requestFnStub = sandbox.stub(); + + requestFnStub.onCall(0).callsFake(() => { + setTimeout(() => { + fakeRequestStream.push(RESULT_WITH_TOKEN); + fakeCheckpointStream.emit('checkpoint', RESULT_WITH_TOKEN); + fakeRequestStream.push(RESULT_WITH_TOKEN); + fakeCheckpointStream.emit('checkpoint', RESULT_WITH_TOKEN); + + setTimeout(() => { + fakeRequestStream.emit('error', { + code: grpc.status.DATA_LOSS, + message: 'Non-retryable error.', + } as grpc.ServiceError); + }, 50); + }, 50); + + return fakeRequestStream; + }); + + const receivedRows: Row[] = []; + partialResultStream(requestFnStub) + .on('data', row => { + receivedRows.push(row); + }) + .on('error', err => { + // We should receive two rows before we get an error. + assert.strictEqual(receivedRows.length, 2); + assert.strictEqual(err.code, grpc.status.DATA_LOSS); + assert.strictEqual(requestFnStub.callCount, 1); + done(); + }); + }); + + it('should emit rows and error when there is no token', done => { + const expectedRow = sinon.match(EXPECTED_ROW); + const error = new Error('Error.'); + + const dataStub = sandbox.stub().withArgs(expectedRow); + + stream.on('data', dataStub).on('error', err => { + assert.strictEqual(err, error); + assert.strictEqual(dataStub.callCount, 3); + done(); + }); + + // No rows with tokens were emitted, so this should destroy the stream. + fakeRequestStream.push(RESULT); + fakeRequestStream.push(RESULT); + fakeRequestStream.push(RESULT); + fakeRequestStream.destroy(error); + }); + }); +}); + +function convertToIValue(value) { + let kind: string; + + if (typeof value === 'number') { + kind = 'numberValue'; + } else if (typeof value === 'string') { + kind = 'stringValue'; + } else if (typeof value === 'boolean') { + kind = 'boolValue'; + } else if (Array.isArray(value)) { + const values = value.map(convertToIValue); + kind = 'listValue'; + value = {values}; + } else { + kind = 'nullValue'; + value = null; + } + + return {kind, [kind]: value}; +} diff --git a/handwritten/spanner/test/request_id_header.ts b/handwritten/spanner/test/request_id_header.ts new file mode 100644 index 00000000000..9eda0d3d298 --- /dev/null +++ b/handwritten/spanner/test/request_id_header.ts @@ -0,0 +1,171 @@ +/** + * Copyright 2025 Google LLC. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable prefer-rest-params */ +import * as assert from 'assert'; +import { + RequestIDError, + X_GOOG_SPANNER_REQUEST_ID_HEADER, + craftRequestId, + injectRequestIDIntoError, + injectRequestIDIntoHeaders, + newAtomicCounter, + nextNthRequest, + randIdForProcess, +} from '../src/request_id_header'; + +describe('RequestId', () => { + describe('AtomicCounter', () => { + it('Constructor with initialValue', done => { + const ac0 = newAtomicCounter(); + assert.deepStrictEqual(ac0.value(), 0); + assert.deepStrictEqual( + ac0.increment(2), + 2, + 'increment should return the added value', + ); + assert.deepStrictEqual( + ac0.value(), + 2, + 'increment should have modified the value', + ); + + const ac1 = newAtomicCounter(1); + assert.deepStrictEqual(ac1.value(), 1); + assert.deepStrictEqual( + ac1.increment(1 << 27), + (1 << 27) + 1, + 'increment should return the added value', + ); + assert.deepStrictEqual( + ac1.value(), + (1 << 27) + 1, + 'increment should have modified the value', + ); + done(); + }); + + it('reset', done => { + const ac0 = newAtomicCounter(1); + ac0.increment(); + assert.strictEqual(ac0.value(), 2); + ac0.reset(); + assert.strictEqual(ac0.value(), 0); + done(); + }); + + it('toString', done => { + const ac0 = newAtomicCounter(1); + ac0.increment(); + assert.strictEqual(ac0.value(), 2); + assert.strictEqual(ac0.toString(), '2'); + assert.strictEqual(`${ac0}`, '2'); + done(); + }); + }); + + describe('craftRequestId', () => { + it('has a 32-bit hex-formatted process-id', done => { + assert.match( + randIdForProcess, + /^[0-9A-Fa-f]{8}$/, + `process-id should be a 32-bit hexadecimal number, but was ${randIdForProcess}`, + ); + done(); + }); + + it('with attempts', done => { + assert.strictEqual( + craftRequestId(1, 2, 3, 4), + `1.${randIdForProcess}.1.2.3.4`, + ); + done(); + }); + }); + + describe('injectRequestIDIntoError', () => { + it('with non-null error', done => { + const err: Error = new Error('this one'); + const config = {headers: {}}; + config.headers[X_GOOG_SPANNER_REQUEST_ID_HEADER] = '1.2.3.4.5.6'; + injectRequestIDIntoError(config, err); + assert.strictEqual((err as RequestIDError).requestID, '1.2.3.4.5.6'); + done(); + }); + }); + + describe('injectRequestIDIntoHeaders', () => { + it('with null session', done => { + const hdrs = {}; + injectRequestIDIntoHeaders(hdrs, null, 2, 1); + done(); + }); + + it('with nthRequest explicitly passed in', done => { + const session = { + parent: { + _nextNthRequest: () => { + return 5; + }, + }, + }; + const got = injectRequestIDIntoHeaders({}, session, 2, 5); + const want = { + 'x-goog-spanner-request-id': `1.${randIdForProcess}.1.1.2.5`, + }; + assert.deepStrictEqual(got, want); + done(); + }); + + it('infer nthRequest from session', done => { + const session = { + parent: { + _nextNthRequest: () => { + return 5; + }, + }, + }; + + const inputHeaders: {[k: string]: string} = {}; + const got = injectRequestIDIntoHeaders(inputHeaders, session); + const want = { + 'x-goog-spanner-request-id': `1.${randIdForProcess}.1.1.5.1`, + }; + assert.deepStrictEqual(got, want); + done(); + }); + }); + + describe('nextNthRequest', () => { + const fauxDatabase = {}; + assert.deepStrictEqual( + nextNthRequest(fauxDatabase), + 1, + 'Without override, should default to 1', + ); + + Object.assign(fauxDatabase, { + _nextNthRequest: () => { + return 4; + }, + }); + assert.deepStrictEqual( + nextNthRequest(fauxDatabase), + 4, + 'With override should infer value', + ); + }); +}); diff --git a/handwritten/spanner/test/session-factory.ts b/handwritten/spanner/test/session-factory.ts new file mode 100644 index 00000000000..e61199ab248 --- /dev/null +++ b/handwritten/spanner/test/session-factory.ts @@ -0,0 +1,413 @@ +/*! + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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 {Database, Session, SessionPool} from '../src'; +import {SessionFactory} from '../src/session-factory'; +import * as sinon from 'sinon'; +import * as assert from 'assert'; +import {MultiplexedSession} from '../src/multiplexed-session'; +import {util} from '@google-cloud/common'; +import * as db from '../src/database'; +import {FakeTransaction} from './session-pool'; +import {ReleaseError} from '../src/session-pool'; + +describe('SessionFactory', () => { + let sessionFactory; + let fakeSession; + let fakeMuxSession; + const sandbox = sinon.createSandbox(); + const NAME = 'table-name'; + const POOL_OPTIONS = {}; + function noop() {} + const DATABASE = { + createSession: noop, + batchCreateSessions: noop, + databaseRole: 'parent_role', + } as unknown as Database; + + const createMuxSession = (name = 'id', props?): Session => { + props = props || {}; + + const muxSession = Object.assign(new Session(DATABASE, name), props, { + create: sandbox.stub().resolves(), + transaction: sandbox.stub().returns(new FakeTransaction()), + }); + + muxSession.metadata = { + multiplexed: true, + }; + + return muxSession; + }; + + const createSession = (name = 'id', props?): Session => { + props = props || {}; + + const session = Object.assign(new Session(DATABASE, name), props, { + create: sandbox.stub().resolves(), + transaction: sandbox.stub().returns(new FakeTransaction()), + }); + + session.metadata = {multiplexed: false}; + + return session; + }; + + beforeEach(() => { + fakeSession = createSession(); + fakeMuxSession = createMuxSession(); + sandbox.stub(DATABASE, 'batchCreateSessions').callsFake(() => { + return Promise.resolve([[fakeSession, fakeSession, fakeSession]]); + }); + sandbox + .stub(DATABASE, 'createSession') + .withArgs({multiplexed: true}) + .callsFake(() => { + return Promise.resolve([fakeMuxSession]); + }); + sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + sessionFactory.parent = DATABASE; + }); + + afterEach(() => { + sandbox.restore(); + }); + + describe('instantiation', () => { + describe('when multiplexed session is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + + it('should create a SessionPool object', () => { + assert(sessionFactory.pool_ instanceof SessionPool); + }); + + it('should accept a custom Pool class', () => { + function FakePool() {} + FakePool.prototype.on = util.noop; + FakePool.prototype.open = util.noop; + + const sessionFactory = new SessionFactory( + DATABASE, + NAME, + FakePool as {} as db.SessionPoolConstructor, + ); + assert(sessionFactory.pool_ instanceof FakePool); + }); + + it('should open the pool', () => { + const openStub = sandbox + .stub(SessionPool.prototype, 'open') + .callsFake(() => {}); + + new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + + assert.strictEqual(openStub.callCount, 1); + }); + + it('should correctly initialize the isMultiplexedEnabled field when GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is disabled', () => { + const sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + assert.strictEqual(sessionFactory.isMultiplexed, false); + }); + }); + + describe('when multiplexed session is default', () => { + it('should create a MultiplexedSession object', () => { + assert( + sessionFactory.multiplexedSession_ instanceof MultiplexedSession, + ); + }); + + it('should initiate the multiplexed session creation', () => { + const createSessionStub = sandbox + .stub(MultiplexedSession.prototype, 'createSession') + .callsFake(() => {}); + + new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + + assert.strictEqual(createSessionStub.callCount, 1); + }); + + it('should correctly initialize the isMultiplexedEnabled field when GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is enabled', () => { + const sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + assert.strictEqual(sessionFactory.isMultiplexed, true); + }); + }); + + describe('when multiplexed session is disabled for r/w', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW; + }); + + it('should correctly initialize the isMultiplexedRW field', () => { + const sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + assert.strictEqual(sessionFactory.isMultiplexedRW, false); + }); + }); + + describe('when multiplexed session is default for r/w', () => { + it('should correctly initialize the isMultiplexedRW field', () => { + const sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + assert.strictEqual(sessionFactory.isMultiplexedRW, true); + }); + }); + }); + + describe('getSession', () => { + describe('when multiplexed session is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + + it('should retrieve a regular session from the pool', done => { + ( + sandbox.stub(sessionFactory.pool_, 'getSession') as sinon.SinonStub + ).callsFake(callback => callback(null, fakeSession)); + sessionFactory.getSession((err, resp) => { + assert.strictEqual(err, null); + assert.strictEqual(resp, fakeSession); + done(); + }); + }); + + it('should propagate errors when regular session retrieval fails', done => { + const fakeError = new Error(); + ( + sandbox.stub(sessionFactory.pool_, 'getSession') as sinon.SinonStub + ).callsFake(callback => callback(fakeError, null)); + sessionFactory.getSession((err, resp) => { + assert.strictEqual(err, fakeError); + assert.strictEqual(resp, null); + done(); + }); + }); + }); + + describe('when multiplexed session is default', () => { + it('should return the multiplexed session', done => { + ( + sandbox.stub( + sessionFactory.multiplexedSession_, + 'getSession', + ) as sinon.SinonStub + ).callsFake(callback => callback(null, fakeMuxSession)); + sessionFactory.getSession((err, resp) => { + assert.strictEqual(err, null); + assert.strictEqual(resp, fakeMuxSession); + assert.strictEqual(resp?.metadata.multiplexed, true); + assert.strictEqual(fakeMuxSession.metadata.multiplexed, true); + done(); + }); + }); + + it('should propagate error when multiplexed session return fails', done => { + const fakeError = new Error(); + ( + sandbox.stub( + sessionFactory.multiplexedSession_, + 'getSession', + ) as sinon.SinonStub + ).callsFake(callback => callback(fakeError, null)); + sessionFactory.getSession((err, resp) => { + assert.strictEqual(err, fakeError); + assert.strictEqual(resp, null); + done(); + }); + }); + }); + }); + + describe('getSessionForReadWrite', () => { + describe('when multiplexed session for r/w disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW; + }); + + it('should retrieve a regular session from the pool', done => { + ( + sandbox.stub(sessionFactory.pool_, 'getSession') as sinon.SinonStub + ).callsFake(callback => callback(null, fakeSession)); + sessionFactory.getSessionForReadWrite((err, resp) => { + assert.strictEqual(err, null); + assert.strictEqual(resp, fakeSession); + done(); + }); + }); + + it('should propagate errors when regular session retrieval fails', done => { + const fakeError = new Error(); + ( + sandbox.stub(sessionFactory.pool_, 'getSession') as sinon.SinonStub + ).callsFake(callback => callback(fakeError, null)); + sessionFactory.getSessionForReadWrite((err, resp) => { + assert.strictEqual(err, fakeError); + assert.strictEqual(resp, null); + done(); + }); + }); + }); + + describe('when multiplexed session for r/w not disabled', () => { + it('should return the multiplexed session', done => { + ( + sandbox.stub( + sessionFactory.multiplexedSession_, + 'getSession', + ) as sinon.SinonStub + ).callsFake(callback => callback(null, fakeMuxSession)); + sessionFactory.getSessionForReadWrite((err, resp) => { + assert.strictEqual(err, null); + assert.strictEqual(resp, fakeMuxSession); + assert.strictEqual(resp?.metadata.multiplexed, true); + assert.strictEqual(fakeMuxSession.metadata.multiplexed, true); + done(); + }); + }); + + it('should propagate error when multiplexed session return fails', done => { + const fakeError = new Error(); + ( + sandbox.stub( + sessionFactory.multiplexedSession_, + 'getSession', + ) as sinon.SinonStub + ).callsFake(callback => callback(fakeError, null)); + sessionFactory.getSessionForReadWrite((err, resp) => { + assert.strictEqual(err, fakeError); + assert.strictEqual(resp, null); + done(); + }); + }); + }); + }); + + describe('getPool', () => { + it('should return the session pool object', () => { + const pool = sessionFactory.getPool(); + assert(pool instanceof SessionPool); + assert.deepStrictEqual(pool, sessionFactory.pool_); + }); + }); + + describe('release', () => { + describe('when GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is not disabled', () => { + it('should not call the release method', () => { + const releaseStub = sandbox.stub(sessionFactory.pool_, 'release'); + const fakeMuxSession = createMuxSession(); + sessionFactory.release(fakeMuxSession); + assert.strictEqual(releaseStub.callCount, 0); + }); + }); + + describe('when GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + + it('should call the release method to release a regular session', () => { + const releaseStub = sandbox.stub(sessionFactory.pool_, 'release'); + const fakeSession = createSession(); + sessionFactory.release(fakeSession); + assert.strictEqual(releaseStub.callCount, 1); + }); + + it('should propagate an error when release fails', () => { + const fakeSession = createSession(); + try { + sessionFactory.release(fakeSession); + assert.fail('Expected error was not thrown'); + } catch (error) { + assert.strictEqual( + (error as ReleaseError).message, + 'Unable to release unknown resource.', + ); + assert.strictEqual((error as ReleaseError).resource, fakeSession); + } + }); + }); + }); + + describe('isMultiplexedEnabled', () => { + describe('when GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is not disabled', () => { + it('should have enabled the multiplexed', () => { + const sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + assert.strictEqual(sessionFactory.isMultiplexedEnabled(), true); + }); + }); + + describe('when GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + it('should not have enabled the multiplexed', () => { + const sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + assert.strictEqual(sessionFactory.isMultiplexedEnabled(), false); + }); + }); + }); + + describe('isMultiplexedEnabledForRW', () => { + describe('when multiplexed session is not disabled for read/write transactions', () => { + it('should have enabled the multiplexed', () => { + const sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + assert.strictEqual(sessionFactory.isMultiplexedEnabledForRW(), true); + }); + }); + + describe('when multiplexed session is disabled for read/write transactions', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW = 'false'; + }); + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW; + }); + it('should not have enabled the multiplexed', () => { + const sessionFactory = new SessionFactory(DATABASE, NAME, POOL_OPTIONS); + assert.strictEqual(sessionFactory.isMultiplexedEnabledForRW(), false); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/session-pool.ts b/handwritten/spanner/test/session-pool.ts new file mode 100644 index 00000000000..b27f2b43e78 --- /dev/null +++ b/handwritten/spanner/test/session-pool.ts @@ -0,0 +1,1434 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import * as events from 'events'; +import * as extend from 'extend'; +import PQueue from 'p-queue'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import stackTrace = require('stack-trace'); +import timeSpan = require('time-span'); + +import {Database} from '../src/database'; +import {Session} from '../src/session'; +import * as sp from '../src/session-pool'; +import {Transaction} from '../src/transaction'; +import {grpc} from 'google-gax'; +const {startTrace} = require('../src/instrument'); + +let pQueueOverride: typeof PQueue | null = null; + +function FakePQueue(options) { + return new (pQueueOverride || PQueue)(options); +} + +FakePQueue.default = FakePQueue; + +export class FakeTransaction { + options; + constructor(options?) { + this.options = options; + } + async begin(): Promise {} +} + +const fakeStackTrace = extend({}, stackTrace); + +function noop() {} + +describe('SessionPool', () => { + let sessionPool: sp.SessionPool; + // tslint:disable-next-line variable-name + let SessionPool: typeof sp.SessionPool; + let inventory; + + const DATABASE = { + batchCreateSessions: noop, + databaseRole: 'parent_role', + } as unknown as Database; + + const sandbox = sinon.createSandbox(); + const shouldNotBeCalled = sandbox.stub().throws('Should not be called.'); + + const createSession = (name = 'id', props?): Session => { + props = props || {}; + + return Object.assign(new Session(DATABASE, name), props, { + create: sandbox.stub().resolves(), + delete: sandbox.stub().resolves(), + keepAlive: sandbox.stub().resolves(), + transaction: sandbox.stub().returns(new FakeTransaction()), + }); + }; + + const createStackFrame = (): stackTrace.StackFrame => { + return { + getFunctionName: sandbox.stub().returns('myFunction'), + getMethodName: sandbox.stub().returns('MyClass.myMethod'), + getFileName: sandbox.stub().returns('path/to/file.js'), + getLineNumber: sandbox.stub().returns('99'), + getColumnNumber: sandbox.stub().returns('13'), + getTypeName: sandbox.stub().returns('type'), + isNative: sandbox.stub().returns(false), + isConstructor: sandbox.stub().returns(false), + }; + }; + + before(() => { + SessionPool = proxyquire('../src/session-pool.js', { + 'p-queue': FakePQueue, + 'stack-trace': fakeStackTrace, + }).SessionPool; + }); + + beforeEach(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS = + 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW = 'false'; + DATABASE.session = createSession; + sessionPool = new SessionPool(DATABASE); + inventory = sessionPool._inventory; + }); + + afterEach(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + delete process.env + .GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS; + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW; + pQueueOverride = null; + sandbox.restore(); + }); + + describe('formatTrace', () => { + let stackFrame: stackTrace.StackFrame; + let fakeTrace: stackTrace.StackFrame[]; + let file: string; + + beforeEach(() => { + stackFrame = createStackFrame(); + fakeTrace = [stackFrame]; + file = `${stackFrame.getFileName()}:${stackFrame.getLineNumber()}:${stackFrame.getColumnNumber()}`; + }); + + it('should return a trace with the method name', () => { + (stackFrame.getFunctionName as sinon.SinonStub).returns(undefined); + + const expected = `Session leak detected!\n at ${stackFrame.getMethodName()} (${file})`; + const actual = SessionPool.formatTrace(fakeTrace); + + assert.strictEqual(expected, actual); + }); + + it('should return a trace with the function name', () => { + (stackFrame.getMethodName as sinon.SinonStub).returns(undefined); + + const expected = `Session leak detected!\n at ${stackFrame.getFunctionName()} (${file})`; + const actual = SessionPool.formatTrace(fakeTrace); + + assert.strictEqual(expected, actual); + }); + }); + + describe('available', () => { + it('should return the number of available sessions', () => { + inventory.sessions = [createSession(), createSession(), createSession()]; + + assert.strictEqual(sessionPool.available, 3); + }); + }); + + describe('borrowed', () => { + beforeEach(() => { + inventory.borrowed = new Set([createSession(), createSession()]); + }); + + it('should return the number of borrowed sessions', () => { + assert.strictEqual(sessionPool.borrowed, 2); + }); + + it('should factor in any creation pending sessions', () => { + sessionPool._pending = 1; + assert.strictEqual(sessionPool.borrowed, 3); + }); + }); + + describe('isFull', () => { + it('should indicate if the pool is full', () => { + sessionPool.options.max = 1; + + assert.strictEqual(sessionPool.isFull, false); + inventory.borrowed = new Set([createSession()]); + assert.strictEqual(sessionPool.isFull, true); + }); + }); + + describe('size', () => { + it('should return the size of the pool', () => { + inventory.sessions = [createSession(), createSession(), createSession()]; + inventory.borrowed = new Set([createSession()]); + + assert.strictEqual(sessionPool.size, 4); + }); + }); + + describe('writes', () => { + beforeEach(() => { + inventory.sessions = [createSession(), createSession(), createSession()]; + }); + + it('should get the total number of read/write sessions', () => { + assert.strictEqual(sessionPool.size, 3); + }); + + it('should factor in borrowed sessions', () => { + const session = createSession('id', {}); + + inventory.borrowed.add(session); + + assert.strictEqual(sessionPool.size, 4); + assert.strictEqual(sessionPool.available, 3); + assert.strictEqual(sessionPool.borrowed, 1); + }); + }); + + describe('instantiation', () => { + it('should localize the database instance', () => { + assert.strictEqual(sessionPool.database, DATABASE); + }); + + describe('options', () => { + it('should apply defaults', () => { + assert.strictEqual(sessionPool.options.acquireTimeout, Infinity); + assert.strictEqual(sessionPool.options.concurrency, Infinity); + assert.strictEqual(sessionPool.options.fail, false); + assert.strictEqual(sessionPool.options.idlesAfter, 10); + assert.strictEqual(sessionPool.options.keepAlive, 30); + assert.strictEqual(sessionPool.options.labels, undefined); + assert.strictEqual(sessionPool.options.min, 25); + assert.strictEqual(sessionPool.options.max, 100); + assert.strictEqual(sessionPool.options.maxIdle, 1); + }); + + it('should not override user options', () => { + sessionPool = new SessionPool(DATABASE, {acquireTimeout: 0}); + assert.strictEqual(sessionPool.options.acquireTimeout, 0); + }); + + it('should override user options for databaseRole', () => { + sessionPool = new SessionPool(DATABASE, {databaseRole: 'child_role'}); + assert.strictEqual(sessionPool.options.databaseRole, 'child_role'); + }); + + it('should use default value of Database for databaseRole', () => { + sessionPool = new SessionPool(DATABASE); + assert.strictEqual(sessionPool.options.databaseRole, 'parent_role'); + }); + + describe('min and max', () => { + const minGtMax = /Min sessions may not be greater than max sessions\./; + + it('should not accept min>max', () => { + assert.throws(() => { + return new SessionPool(DATABASE, {min: 20, max: 10}); + }, minGtMax); + }); + }); + }); + + it('should set isOpen to false', () => { + assert.strictEqual(sessionPool.isOpen, false); + }); + + it('should create an inventory object', () => { + assert.deepStrictEqual(inventory, { + sessions: [], + borrowed: new Set(), + }); + }); + + it('should create a request queue', () => { + const poolOptions = { + concurrency: 11, + }; + + pQueueOverride = class { + constructor(options) { + return options; + } + } as typeof PQueue; + + sessionPool = new SessionPool(DATABASE, poolOptions); + assert.deepStrictEqual(sessionPool._requests, { + concurrency: poolOptions.concurrency, + }); + }); + + it('should create an acquire queue', () => { + pQueueOverride = class { + constructor(options) { + return options; + } + } as typeof PQueue; + + sessionPool = new SessionPool(DATABASE); + assert.deepStrictEqual(sessionPool._acquires, { + concurrency: 1, + }); + }); + + it('should create a map of traces', () => { + assert.deepStrictEqual(sessionPool._traces, new Map()); + }); + + it('should inherit from EventEmitter', () => { + assert(sessionPool instanceof events.EventEmitter); + }); + }); + + describe('close', () => { + beforeEach(() => { + inventory.sessions = [createSession(), createSession(), createSession()]; + inventory.borrowed = new Set([createSession(), createSession()]); + sessionPool._destroy = sandbox.stub().resolves(); + }); + + it('should clear the inventory', done => { + sessionPool.close(() => { + assert.strictEqual(sessionPool.size, 0); + done(); + }); + }); + + it('should stop housekeeping', done => { + sessionPool._stopHouseKeeping = done; + sessionPool.close(noop); + }); + + it('should set isOpen to false', () => { + sessionPool.isOpen = true; + sessionPool.close(noop); + + assert.strictEqual(sessionPool.isOpen, false); + }); + + it('should emit the close event', done => { + sessionPool.on('close', done); + sessionPool.close(noop); + }); + + it('should destroy all the sessions', done => { + const sessions = [...inventory.sessions, ...inventory.borrowed]; + + let destroyed = 0; + + sessionPool._destroy = async session => { + assert.strictEqual(session, sessions[destroyed++]); + }; + + sessionPool.close(err => { + assert.ifError(err); + assert.strictEqual(destroyed, sessions.length); + done(); + }); + }); + + it('should execute the callback on idle', done => { + const stub = sandbox.stub(sessionPool._requests, 'onIdle').resolves(); + + sessionPool.close(err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + done(); + }); + }); + + it('should return a leak error', done => { + const fakeLeaks = ['a', 'b']; + + sandbox.stub(sessionPool, '_getLeaks').returns(fakeLeaks); + + sessionPool.close((err?: sp.SessionLeakError) => { + assert.strictEqual(err!.name, 'SessionLeakError'); + assert.strictEqual( + err!.message, + `${fakeLeaks.length} session leak(s) detected.`, + ); + assert.strictEqual(err!.messages, fakeLeaks); + done(); + }); + }); + }); + + describe('getSession', () => { + it('should acquire a session', done => { + const fakeSession = createSession(); + + sandbox.stub(sessionPool, '_acquire').resolves(fakeSession); + + sessionPool.getSession((err, session) => { + assert.ifError(err); + assert.strictEqual(session, fakeSession); + done(); + }); + }); + + it('should pass any errors to the callback', done => { + const error = new Error('err'); + + sandbox.stub(sessionPool, '_acquire').rejects(error); + + sessionPool.getSession(err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should pass back the session and txn', done => { + const fakeTxn = new FakeTransaction() as unknown as Transaction; + const fakeSession = createSession(); + + fakeSession.txn = fakeTxn; + + sandbox.stub(sessionPool, '_acquire').resolves(fakeSession); + + sessionPool.getSession((err, session, txn) => { + assert.ifError(err); + assert.strictEqual(session, fakeSession); + assert.strictEqual(txn, fakeTxn); + done(); + }); + }); + }); + + describe('open', () => { + let fillStub: sinon.SinonStub<[], Promise>; + + beforeEach(() => { + sessionPool._stopHouseKeeping = sandbox.stub(); + fillStub = sandbox.stub(sessionPool, '_fill').resolves(); + }); + + it('should create an onclose promise', () => { + sessionPool.open(); + + assert(sessionPool._onClose instanceof Promise); + setImmediate(() => sessionPool.emit('close')); + return sessionPool._onClose; + }); + + it('should start housekeeping', done => { + sessionPool._startHouseKeeping = done; + sessionPool.open(); + }); + + it('should set isOpen to true', () => { + sessionPool.open(); + assert.strictEqual(sessionPool.isOpen, true); + }); + + it('should emit the open event', done => { + sessionPool.on('open', done); + sessionPool.open(); + }); + + it('should fill the pool', () => { + sessionPool.open(); + assert.strictEqual(fillStub.callCount, 1); + }); + + it('should not trigger unhandled promise rejection', () => { + const error = { + code: grpc.status.PERMISSION_DENIED, + message: 'spanner.sessions.create', + } as grpc.ServiceError; + + sandbox.restore(); + sandbox.stub(sessionPool, '_fill').rejects(error); + + const originalRejection = process.listeners('unhandledRejection').pop(); + if (originalRejection) { + process.removeListener('unhandledRejection', originalRejection!); + } + + process.once('unhandledRejection', err => { + assert.ifError(err); + }); + + sessionPool.open(); + + if (originalRejection) { + process.listeners('unhandledRejection').push(originalRejection!); + } + }); + + it('should not trigger unhandled promise rejection when default credentials not set', () => { + const error = { + message: 'Could not load the default credentials', + } as grpc.ServiceError; + + sandbox.restore(); + sandbox.stub(sessionPool, '_fill').rejects(error); + + const originalRejection = process.listeners('unhandledRejection').pop(); + if (originalRejection) { + process.removeListener('unhandledRejection', originalRejection!); + } + + process.once('unhandledRejection', err => { + assert.ifError(err); + }); + + sessionPool.open(); + + if (originalRejection) { + process.listeners('unhandledRejection').push(originalRejection!); + } + }); + + it('should not trigger unhandled promise rejection when projectId not set', () => { + const error = { + message: 'Unable to detect a Project Id in the current environment', + } as grpc.ServiceError; + + sandbox.restore(); + sandbox.stub(sessionPool, '_fill').rejects(error); + + const originalRejection = process.listeners('unhandledRejection').pop(); + if (originalRejection) { + process.removeListener('unhandledRejection', originalRejection!); + } + + process.once('unhandledRejection', err => { + assert.ifError(err); + }); + + sessionPool.open(); + + if (originalRejection) { + process.listeners('unhandledRejection').push(originalRejection!); + } + }); + }); + + describe('release', () => { + let prepStub: sinon.SinonStub<[Session], void>; + + beforeEach(() => { + prepStub = sandbox.stub(sessionPool, '_prepareTransaction').resolves(); + }); + + it('should throw an error when returning unknown resources', () => { + const badResource = createSession(); + + try { + sessionPool.release(badResource); + shouldNotBeCalled(); + } catch (e) { + assert.strictEqual( + (e as sp.ReleaseError).message, + 'Unable to release unknown resource.', + ); + assert.strictEqual((e as sp.ReleaseError).resource, badResource); + } + }); + + it('should delete any old transactions', () => { + const session = createSession(); + + sessionPool._release = noop; + inventory.borrowed.add(session); + session.txn = {} as Transaction; + + sessionPool.release(session); + assert.strictEqual(session.txn, undefined); + }); + + it('should update the lastUsed timestamp', () => { + const session = createSession(); + + sessionPool._release = noop; + inventory.borrowed.add(session); + session.lastUsed = null!; + + sessionPool.release(session); + assert(isAround(session.lastUsed, Date.now())); + }); + + describe('read and write', () => { + let fakeSession; + + beforeEach(() => { + fakeSession = createSession('id'); + inventory.borrowed.add(fakeSession); + }); + + it('should release the read/write session', done => { + prepStub.resolves(); + sandbox + .stub(sessionPool, '_release') + .withArgs(fakeSession) + .callsFake(() => done()); + + sessionPool.release(fakeSession); + }); + }); + }); + + describe('_acquire', () => { + beforeEach(() => { + sessionPool.isOpen = true; + sessionPool._isValidSession = () => true; + }); + + it('should return a closed error if not open', async () => { + sessionPool.isOpen = false; + + try { + await sessionPool._acquire(); + shouldNotBeCalled(); + } catch (e) { + assert.strictEqual( + (e as sp.ReleaseError).message, + 'Database is closed.', + ); + } + }); + + it('should return a timeout error if a timeout happens', async () => { + sessionPool.options.acquireTimeout = 1; + + sessionPool._acquires.add = fn => { + return new Promise(r => setTimeout(r, 3)).then(fn); + }; + + try { + await sessionPool._acquire(); + shouldNotBeCalled(); + } catch (e) { + assert.strictEqual( + (e as sp.ReleaseError).message, + 'Timeout occurred while acquiring session.', + ); + } + }); + + it('should return a session', async () => { + const fakeSession = createSession(); + const now = Date.now(); + + const stub = sandbox + .stub(sessionPool, '_getSession') + .resolves(fakeSession); + const session = await sessionPool._acquire(); + const [startTime] = stub.getCall(0).args; + + assert(isAround(startTime, now)); + assert.strictEqual(session, fakeSession); + }); + + it('should drop expired sessions', async () => { + const badSession = createSession(); + const goodSession = createSession(); + + sessionPool._isValidSession = session => session === goodSession; + inventory.borrowed.add(badSession); + inventory.borrowed.add(goodSession); + + const stub = sandbox.stub(sessionPool, '_getSession'); + + stub.onFirstCall().resolves(badSession); + stub.onSecondCall().resolves(goodSession); + + const session = await sessionPool._acquire(); + + assert.strictEqual(session, goodSession); + assert.strictEqual(sessionPool.size, 1); + }); + + it('should capture the stack trace', async () => { + const id = 'abc'; + const fakeSession = createSession(); + const fakeTrace = []; + + fakeSession.id = id; + sandbox.stub(sessionPool, '_getSession').resolves(fakeSession); + sandbox.stub(fakeStackTrace, 'get').returns(fakeTrace); + + await sessionPool._acquire(); + + const trace = sessionPool._traces.get(id); + assert.strictEqual(trace, fakeTrace); + }); + + it('should convert read sessions to write sessions', async () => { + const fakeSession = createSession('id'); + + sandbox.stub(sessionPool, '_getSession').resolves(fakeSession); + const prepStub = sandbox + .stub(sessionPool, '_prepareTransaction') + .withArgs(fakeSession); + + const session = await sessionPool._acquire(); + + assert.strictEqual(session, fakeSession); + assert.strictEqual(prepStub.callCount, 1); + }); + }); + + describe('_borrow', () => { + it('should mark the session as borrowed', () => { + const fakeSession = createSession(); + + inventory.sessions.push(fakeSession); + + sessionPool._borrow(fakeSession); + + assert.strictEqual(inventory.sessions.indexOf(fakeSession), -1); + assert(inventory.borrowed.has(fakeSession)); + }); + }); + + describe('_borrowFrom', () => { + it('should borrow the last pushed session', () => { + const fakeSession1 = createSession(); + const fakeSession2 = createSession(); + + inventory.sessions.push(fakeSession1); + inventory.sessions.push(fakeSession2); + + let session = sessionPool._borrowFrom(); + assert.strictEqual(session, fakeSession2); + session = sessionPool._borrowFrom(); + assert.strictEqual(session, fakeSession1); + }); + }); + + describe('_borrowNextAvailableSession', () => { + it('should borrow when available', () => { + const fakeSession = createSession(); + + inventory.sessions.push(fakeSession); + sandbox.stub(sessionPool, '_borrowFrom').returns(fakeSession); + + const session = sessionPool._borrowNextAvailableSession(); + + assert.strictEqual(session, fakeSession); + }); + }); + + describe('_createSession', () => { + let stub: sinon.SinonStub<[number], Promise>; + + beforeEach(() => { + stub = sandbox.stub(sessionPool, '_createSessions').resolves(); + }); + + it('should create a single session', async () => { + await sessionPool._createSession(); + const [numbers] = stub.lastCall.args; + assert.deepStrictEqual(numbers, 1); + }); + }); + + describe('_createSessions', () => { + const OPTIONS = 3; + const RESPONSE = [[{}, {}, {}]]; + + let stub; + let releaseStub; + + beforeEach(() => { + stub = sandbox.stub(DATABASE, 'batchCreateSessions').resolves(RESPONSE); + releaseStub = sandbox.stub(sessionPool, 'release'); + }); + + it('should update the number of pending sessions', async () => { + await sessionPool._createSessions(OPTIONS); + assert.strictEqual(sessionPool.size, 3); + }); + + it('should create the appropriate number of sessions', async () => { + await sessionPool._createSessions(OPTIONS); + const [options] = stub.lastCall.args; + assert.strictEqual(options.count, 3); + }); + + it('should pass the session labels', async () => { + const labels = {foo: 'bar'}; + sessionPool.options.labels = labels; + await sessionPool._createSessions(OPTIONS); + const [options] = stub.lastCall.args; + assert.strictEqual(options.labels, labels); + }); + + it('should pass the session database role', async () => { + const databaseRole = 'child_role'; + sessionPool.options.databaseRole = databaseRole; + await sessionPool._createSessions(OPTIONS); + const [options] = stub.lastCall.args; + assert.strictEqual(options.databaseRole, databaseRole); + }); + + it('should make multiple requests if needed', async () => { + stub.onCall(0).resolves([[{}, {}]]); + stub.onCall(1).resolves([[{}]]); + + await sessionPool._createSessions(OPTIONS); + + assert.strictEqual(stub.callCount, 2); + assert.strictEqual(sessionPool.size, 3); + }); + + it('should reject with any request errors', async () => { + const error = new Error('err'); + stub.rejects(error); + + try { + await sessionPool._createSessions(OPTIONS); + throw new Error('Should not make it this far.'); + } catch (e) { + assert.strictEqual(e, error); + } + }); + + it('should add each session to the inventory', async () => { + await sessionPool._createSessions(OPTIONS); + assert.strictEqual(sessionPool.borrowed, 3); + + setImmediate(() => { + RESPONSE[0].forEach((fakeSession, i) => { + const [session] = releaseStub.getCall(i).args; + assert.strictEqual(session, fakeSession); + }); + }); + }); + + it('should prepare the correct number of write sessions', async () => { + await sessionPool._createSessions(OPTIONS); + + setImmediate(() => { + assert.strictEqual(sessionPool.size, OPTIONS); + }); + }); + }); + + describe('_destroy', () => { + it('should delete the session', async () => { + const fakeSession = createSession(); + const stub = fakeSession.delete as sinon.SinonStub; + + await sessionPool._destroy(fakeSession); + assert.strictEqual(stub.callCount, 1); + }); + + it('should emit any errors', done => { + const error = new Error('err'); + const fakeSession = createSession(); + const stub = fakeSession.delete as sinon.SinonStub; + + stub.rejects(error); + + sessionPool.on('error', err => { + assert.strictEqual(err, error); + done(); + }); + + void sessionPool._destroy(fakeSession); + }); + }); + + describe('_evictIdleSessions', () => { + let destroyStub: sinon.SinonStub<[Session], Promise>; + let fakeSessions; + + beforeEach(() => { + inventory.sessions = [ + createSession('id'), + createSession('id'), + createSession('id'), + ]; + + sessionPool.options.maxIdle = 0; + sessionPool.options.min = 0; + + fakeSessions = [...inventory.sessions]; + + sandbox + .stub(sessionPool, '_getIdleSessions') + .returns(fakeSessions.slice()); + + fakeSessions.reverse(); + destroyStub = sandbox.stub(sessionPool, '_destroy').resolves(); + }); + + it('should evict the sessions', () => { + sessionPool._evictIdleSessions(); + + assert.strictEqual(destroyStub.callCount, fakeSessions.length); + + fakeSessions.forEach((session, i) => { + const destroyed = destroyStub.getCall(i).args[0]; + assert.strictEqual(destroyed, session); + }); + }); + + it('should respect the maxIdle option', () => { + sessionPool.options.maxIdle = 2; + sessionPool._evictIdleSessions(); + + assert.strictEqual(destroyStub.callCount, 1); + const destroyed = destroyStub.getCall(0).args[0]; + assert.strictEqual(destroyed, fakeSessions[0]); + }); + + it('should respect the min value', () => { + sessionPool.options.min = 1; + sessionPool._evictIdleSessions(); + + assert.strictEqual(destroyStub.callCount, 2); + + fakeSessions.slice(0, 2).forEach((session, i) => { + const destroyed = destroyStub.getCall(i).args[0]; + assert.strictEqual(destroyed, session); + }); + }); + + it('should not evict if the session is not there', () => { + sandbox.restore(); + fakeSessions[1] = undefined; + sandbox + .stub(sessionPool, '_getIdleSessions') + .returns(fakeSessions.slice()); + destroyStub = sandbox.stub(sessionPool, '_destroy').resolves(); + + sessionPool._evictIdleSessions(); + + assert.strictEqual(destroyStub.callCount, fakeSessions.length - 1); + }); + }); + + describe('_fill', () => { + let stub: sinon.SinonStub<[number], Promise>; + + beforeEach(() => { + stub = sandbox.stub(sessionPool, '_createSessions'); + sessionPool.options.min = 8; + }); + + it('should create the min number of required sessions', async () => { + await sessionPool._fill(); + + const amount = stub.lastCall.args[0]; + + assert.strictEqual(amount, 8); + }); + + it('should respect the current size of the pool', async () => { + inventory.sessions = [createSession(), createSession(), createSession()]; + + await sessionPool._fill(); + + const amount = stub.lastCall.args[0]; + + assert.strictEqual(amount, 5); + }); + + it('should noop when no sessions are needed', async () => { + sessionPool.options.min = 0; + await sessionPool._fill(); + + assert.strictEqual(stub.callCount, 0); + }); + + it('should emit any request errors that occur', done => { + const error = new Error('err'); + + stub.rejects(error); + + sessionPool._fill().catch(err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('_getIdleSessions', () => { + it('should return a list of idle sessions', () => { + const idlesAfter = (sessionPool.options.idlesAfter = 1); // 1 minute + const idleTimestamp = Date.now() - idlesAfter * 60000; + + const fake = (inventory.sessions = [ + {lastUsed: Date.now()}, + {lastUsed: idleTimestamp}, + {lastUsed: idleTimestamp}, + ]); + + const expectedSessions = [fake[1], fake[2]]; + const idleSessions = sessionPool._getIdleSessions(); + + assert.deepStrictEqual(idleSessions, expectedSessions); + }); + }); + + describe('_getLeaks', () => { + it('should return an array of leaks', () => { + const trace1 = [createStackFrame()]; + const trace2 = [createStackFrame(), createStackFrame()]; + + const formatted1 = 'c'; + const formatted2 = 'd'; + + const stub = sandbox.stub(SessionPool, 'formatTrace'); + + stub.withArgs(trace1).returns(formatted1); + stub.withArgs(trace2).returns(formatted2); + + sessionPool._traces.set('a', trace1); + sessionPool._traces.set('b', trace2); + + const leaks = sessionPool._getLeaks(); + + assert.deepStrictEqual(leaks, [formatted1, formatted2]); + }); + }); + + describe('_getSession', () => { + let startTime: number; + + beforeEach(() => { + sessionPool._onClose = new Promise(resolve => { + sessionPool.on('close', resolve); + }); + sessionPool.options.max = 0; + startTime = Date.now(); + }); + + it('should return a session if one is available', async () => { + const fakeSession = createSession(); + + inventory.sessions = [fakeSession]; + + sandbox + .stub(sessionPool, '_borrowNextAvailableSession') + .returns(fakeSession); + + const session = await sessionPool._getSession(startTime); + assert.strictEqual(session, fakeSession); + }); + + it('should return an error if empty and fail = true', async () => { + sessionPool.options.fail = true; + + try { + await sessionPool._getSession(startTime); + shouldNotBeCalled(); + } catch (e) { + assert.strictEqual( + (e as sp.ReleaseError).message, + 'No resources available.', + ); + } + }); + + it('should throw a closed error if the pool closes', async () => { + setTimeout(() => sessionPool.emit('close'), 100); + + try { + await sessionPool._getSession(startTime); + shouldNotBeCalled(); + } catch (e) { + assert.strictEqual( + (e as sp.ReleaseError).message, + 'Database is closed.', + ); + } + }); + + it('should return a session when it becomes available', async () => { + const fakeSession = createSession(); + + sandbox + .stub(sessionPool, '_borrowNextAvailableSession') + .returns(fakeSession); + setTimeout(() => sessionPool.emit('session-available'), 100); + + const session = await sessionPool._getSession(startTime); + assert.strictEqual(session, fakeSession); + }); + + it('should use the acquireTimeout if set', async () => { + const end = timeSpan(); + const timeout = (sessionPool.options.acquireTimeout = 100); + + try { + await sessionPool._getSession(startTime); + shouldNotBeCalled(); + } catch (e) { + assert(isAround(timeout, end())); + assert.strictEqual( + (e as sp.ReleaseError).message, + 'Timeout occurred while acquiring session.', + ); + } + }); + + it('should create a session if the pool is not full', async () => { + const fakeSession = createSession(); + const stub = sandbox + .stub(sessionPool, '_createSessions') + .withArgs(1) + .callsFake(() => { + // this will fire off via _createSessions + setImmediate(() => sessionPool.emit('session-available')); + return Promise.resolve(); + }); + + sessionPool.options.max = 1; + sessionPool.options.incStep = 25; + sandbox + .stub(sessionPool, '_borrowNextAvailableSession') + .returns(fakeSession); + + const session = await sessionPool._getSession(startTime); + + assert.strictEqual(session, fakeSession); + assert.strictEqual(stub.callCount, 1); + }); + + it('should create enough sessions for the minimum configured to be reached', async () => { + const fakeSession = createSession(); + const stub = sandbox + .stub(sessionPool, '_createSessions') + .withArgs(20) + .callsFake(() => { + // this will fire off via _createSessions + setImmediate(() => sessionPool.emit('session-available')); + return Promise.resolve(); + }); + + sessionPool.options.min = 20; + sessionPool.options.max = 400; + sessionPool.options.incStep = 10; + sandbox + .stub(sessionPool, '_borrowNextAvailableSession') + .returns(fakeSession); + + const session = await sessionPool._getSession(startTime); + + assert.strictEqual(session, fakeSession); + assert.strictEqual(stub.callCount, 1); + }); + + it('should wait for a pending session to become available', async () => { + const fakeSession = createSession(); + + sessionPool.options.max = 2; + sessionPool._pending = 1; + const stub = sandbox.stub(sessionPool, '_createSession').callsFake(() => { + return Promise.reject(new Error('should not be called')); + }); + sandbox + .stub(sessionPool, '_borrowNextAvailableSession') + .returns(fakeSession); + setTimeout(() => sessionPool.emit('session-available'), 100); + + const session = await sessionPool._getSession(startTime); + assert.strictEqual(session, fakeSession); + assert.strictEqual(stub.callCount, 0); + }); + + it('should return any create errors', async () => { + const error = new Error('err'); + + sessionPool.options.max = 1; + sandbox.stub(sessionPool, '_createSessions').rejects(error); + + try { + await sessionPool._getSession(startTime); + shouldNotBeCalled(); + } catch (e) { + assert.strictEqual(e, error); + } + }); + + it('should remove the available listener on error', async () => { + sessionPool.options.acquireTimeout = 100; + + const promise = sessionPool._getSession(startTime); + + assert.strictEqual(sessionPool.listenerCount('session-available'), 1); + + try { + await promise; + shouldNotBeCalled(); + } catch (e) { + assert.strictEqual(sessionPool.listenerCount('available'), 0); + } + }); + }); + + describe('_isValidSession', () => { + it('should return true if the session is good', () => { + const fakeSession = createSession('id', {lastUsed: Date.now()}); + const isValid = sessionPool._isValidSession(fakeSession); + + assert.strictEqual(isValid, true); + }); + + it('should return true if the session has gone bad', () => { + const fakeSession = createSession('id', { + lastUsed: Date.now() - 61 * 60000, + }); + const isValid = sessionPool._isValidSession(fakeSession); + + assert.strictEqual(isValid, false); + }); + }); + + describe('_ping', () => { + beforeEach(() => { + sandbox.stub(sessionPool, '_borrow'); + }); + + it('should borrow the session', async () => { + const fakeSession = createSession(); + const stub = sessionPool._borrow as sinon.SinonStub; + + stub.withArgs(fakeSession); + await sessionPool._ping(fakeSession); + + assert.strictEqual(stub.callCount, 1); + }); + + it('should discard it if expired', async () => { + const fakeSession = createSession(); + const keepAliveStub = fakeSession.keepAlive as sinon.SinonStub; + + inventory.borrowed.add(fakeSession); + sandbox.stub(sessionPool, '_isValidSession').returns(false); + await sessionPool._ping(fakeSession); + + const inPool = inventory.borrowed.has(fakeSession); + + assert.strictEqual(inPool, false); + assert.strictEqual(keepAliveStub.callCount, 0); + }); + + it('should keep alive the session then release it', async () => { + const fakeSession = createSession(); + const keepAliveStub = fakeSession.keepAlive as sinon.SinonStub; + + const releaseStub = sandbox + .stub(sessionPool, 'release') + .withArgs(fakeSession); + sandbox.stub(sessionPool, '_isValidSession').returns(true); + + await sessionPool._ping(fakeSession); + + assert.strictEqual(keepAliveStub.callCount, 1); + assert.strictEqual(releaseStub.callCount, 1); + }); + + it('should destroy the session if the ping fails', async () => { + const fakeSession = createSession(); + const keepAliveStub = fakeSession.keepAlive as sinon.SinonStub; + + keepAliveStub.rejects(); + sandbox.stub(sessionPool, '_isValidSession').returns(true); + + const destroyStub = sandbox + .stub(sessionPool, '_destroy') + .withArgs(fakeSession) + .resolves(); + + await sessionPool._ping(fakeSession); + + const inPool = inventory.borrowed.has(fakeSession); + + assert.strictEqual(inPool, false); + assert.strictEqual(destroyStub.callCount, 1); + }); + }); + + describe('_pingIdleSessions', () => { + it('should ping each idle session', async () => { + const fakeSessions = [createSession(), createSession(), createSession()]; + + const pingStub = sandbox.stub(sessionPool, '_ping').resolves(); + sandbox.stub(sessionPool, '_getIdleSessions').returns(fakeSessions); + sandbox.stub(sessionPool, '_fill').resolves(); + + await sessionPool._pingIdleSessions(); + + assert.strictEqual(pingStub.callCount, 3); + + fakeSessions.forEach((session, i) => { + const pinged = pingStub.getCall(i).args[0]; + assert.strictEqual(pinged, session); + }); + }); + + it('should fill the pool after pinging', async () => { + const fillStub = sandbox.stub(sessionPool, '_fill').resolves(); + + sandbox.stub(sessionPool, '_getIdleSessions').returns([]); + await sessionPool._pingIdleSessions(); + + assert.strictEqual(fillStub.callCount, 1); + }); + + it('should not throw error when database not found', async () => { + const fakeSessions = [createSession()]; + sandbox.stub(sessionPool, '_getIdleSessions').returns(fakeSessions); + + const error = { + code: grpc.status.NOT_FOUND, + message: 'Database not found', + } as grpc.ServiceError; + sandbox.stub(sessionPool, '_fill').rejects(error); + + try { + await sessionPool._pingIdleSessions(); + } catch (err) { + assert.ifError(err); + } + }); + }); + + describe('_release', () => { + it('should release the session', () => { + const fakeSession = createSession('id'); + + inventory.borrowed.add(fakeSession); + sessionPool._release(fakeSession); + + assert.strictEqual(inventory.borrowed.has(fakeSession), false); + assert.strictEqual(inventory.sessions.indexOf(fakeSession), 0); + }); + + it('should delete any stack traces', () => { + const id = 'abc'; + const fakeSession = createSession(id); + + sessionPool._traces.set(id, []); + sessionPool._release(fakeSession); + + assert.strictEqual(sessionPool._traces.has(id), false); + }); + }); + + describe('_startHouseKeeping', () => { + it('should set an interval to evict idle sessions', done => { + const expectedInterval = sessionPool.options.idlesAfter! * 60000; + const clock = sandbox.useFakeTimers(); + + sandbox.stub(sessionPool, '_evictIdleSessions').callsFake(done); + + sessionPool._startHouseKeeping(); + clock.tick(expectedInterval); + }); + + it('should set an interval to ping sessions', done => { + const expectedInterval = sessionPool.options.keepAlive! * 60000; + const clock = sandbox.useFakeTimers(); + + sandbox + .stub(sessionPool, '_pingIdleSessions') + .callsFake(async () => done()); + + sessionPool._startHouseKeeping(); + clock.tick(expectedInterval); + }); + }); + + describe('_stopHouseKeeping', () => { + it('should clear the intervals', () => { + sessionPool._pingHandle = setTimeout(noop, 1); + sessionPool._evictHandle = setTimeout(noop, 1); + + const fakeHandles = [sessionPool._pingHandle, sessionPool._evictHandle]; + const stub = sandbox.stub(global, 'clearInterval'); + + sessionPool._stopHouseKeeping(); + + fakeHandles.forEach((fakeHandle, i) => { + const [handle] = stub.getCall(i).args; + assert.strictEqual(handle, fakeHandle); + }); + }); + }); + + describe('trace annotations on active span', () => { + beforeEach(() => { + sessionPool.isOpen = true; + sessionPool._isValidSession = () => true; + }); + + it('annotations when acquiring a session', done => { + const topLevelSpanName = 'testSessionPool.acquire'; + startTrace(topLevelSpanName, {}, async span => { + const fakeSession = createSession(); + const now = Date.now(); + + const stub = sandbox + .stub(sessionPool, '_getSession') + .resolves(fakeSession); + const session = await sessionPool._acquire(); + const [startTime] = stub.getCall(0).args; + + assert(isAround(startTime, now)); + assert.strictEqual(session, fakeSession); + + await sessionPool._release(session); + span.end(); + + const events = span.events; + assert.strictEqual(!events, false, 'Events must be set'); + assert.strictEqual( + events.length > 0, + true, + 'Expecting at least 1 event', + ); + + // Sort the events by earliest time of occurence. + events.sort((evtA, evtB) => { + return evtA.time < evtB.time; + }); + + const gotEventNames: string[] = []; + events.forEach(event => { + gotEventNames.push(event.name); + }); + + const wantEventNames = ['Acquiring session', 'Acquired session']; + assert.deepEqual( + gotEventNames, + wantEventNames, + `Mismatched events\n\tGot: ${gotEventNames}\n\tWant: ${wantEventNames}`, + ); + + done(); + }); + }); + }); +}); + +function isAround(actual, expected) { + return actual > expected - 50 && actual < expected + 50; +} diff --git a/handwritten/spanner/test/session.ts b/handwritten/spanner/test/session.ts new file mode 100644 index 00000000000..ef7d78c8214 --- /dev/null +++ b/handwritten/spanner/test/session.ts @@ -0,0 +1,463 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable prefer-rest-params */ + +import * as pfy from '@google-cloud/promisify'; +import * as assert from 'assert'; +import {before, beforeEach, describe, it} from 'mocha'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; +import { + CLOUD_RESOURCE_HEADER, + LEADER_AWARE_ROUTING_HEADER, + AFE_SERVER_TIMING_HEADER, +} from '../src/common'; +import {Database, Instance, Spanner} from '../src'; +import { + X_GOOG_SPANNER_REQUEST_ID_HEADER, + craftRequestId, +} from '../src/request_id_header'; + +let promisified = false; +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'Session') { + return; + } + + promisified = true; + assert.deepStrictEqual(options.exclude, [ + 'delete', + 'partitionedDml', + 'snapshot', + 'transaction', + ]); + }, +}); + +class FakeGrpcServiceObject { + calledWith_: IArguments; + parent: Database; + constructor() { + this.calledWith_ = arguments; + this.parent = arguments[0].parent; + } +} + +class FakeSnapshot { + calledWith_: IArguments; + constructor() { + this.calledWith_ = arguments; + } +} + +class FakeTransaction extends FakeSnapshot {} +class FakePartitionedDml extends FakeSnapshot {} + +describe('Session', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Session: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let session: any; + + const SPANNER = { + routeToLeaderEnabled: true, + } as {} as Spanner; + + const INSTANCE = { + parent: SPANNER, + } as {} as Instance; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const DATABASE: any = { + request: () => {}, + formattedName_: 'formatted-database-name', + parent: INSTANCE, + }; + + const NAME = 'session-name'; + + before(() => { + Session = proxyquire('../src/session.js', { + './common-grpc/service-object': { + GrpcServiceObject: FakeGrpcServiceObject, + }, + '@google-cloud/promisify': fakePfy, + './transaction.js': { + Snapshot: FakeSnapshot, + Transaction: FakeTransaction, + PartitionedDml: FakePartitionedDml, + }, + }).Session; + }); + + beforeEach(() => { + session = new Session(DATABASE, NAME); + session.parent = DATABASE; + }); + + describe('instantiation', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should localize the request function', () => { + assert.strictEqual(session.request, DATABASE.request); + }); + + it('should localize the requestStream function', () => { + assert.strictEqual(session.requestStream, DATABASE.requestStream); + }); + + it('should format the name', () => { + const formatName_ = Session.formatName_; + const formattedName = 'formatted-name'; + + Session.formatName_ = (databaseName, name) => { + Session.formatName_ = formatName_; + assert.strictEqual(databaseName, DATABASE.formattedName_); + assert.strictEqual(name, NAME); + return formattedName; + }; + + const instance = new Session(DATABASE, NAME); + assert(instance.formattedName_, formattedName); + }); + + it('should inherit from ServiceObject', () => { + assert(session instanceof FakeGrpcServiceObject); + + const calledWith = session.calledWith_[0]; + + assert.strictEqual(calledWith.parent, DATABASE); + assert.strictEqual(calledWith.id, NAME); + assert.deepStrictEqual(calledWith.methods, { + create: true, + exists: true, + get: true, + }); + }); + + it('should set the commonHeaders_', () => { + assert.deepStrictEqual(session.commonHeaders_, { + [CLOUD_RESOURCE_HEADER]: session.parent.formattedName_, + [AFE_SERVER_TIMING_HEADER]: 'true', + }); + }); + + describe('createMethod', () => { + it('should create and return a Session', done => { + const options = {}; + + const apiResponse = {}; + + const createdSession = { + uniqueProperty: true, + }; + + const databaseInstance = extend({}, DATABASE, { + createSession(options_, callback) { + assert.strictEqual(options_, options); + callback(null, createdSession, apiResponse); + }, + }); + + const session = new Session(databaseInstance, NAME); + assert(session instanceof FakeGrpcServiceObject); + + session.calledWith_[0].createMethod( + null, + options, + (err, sess, resp) => { + assert.ifError(err); + + assert.strictEqual(sess, session); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.strictEqual((session as any).uniqueProperty, true); + + assert.strictEqual(resp, apiResponse); + + done(); + }, + ); + }); + + it('should check for options', done => { + const databaseInstance = extend({}, DATABASE, { + createSession(options, callback) { + assert.deepStrictEqual(options, {}); + callback(null, {}, apiResponse); + }, + }); + + const session = new Session(databaseInstance, NAME); + const apiResponse = {}; + + session.calledWith_[0].createMethod(null, (err, sess, resp) => { + assert.ifError(err); + assert.strictEqual(sess, session); + assert.strictEqual(resp, apiResponse); + done(); + }); + }); + + it('should return an error from creating a Session', done => { + const error = new Error('Error.'); + const apiResponse = {}; + + const databaseInstance = extend({}, DATABASE, { + createSession(options_, callback) { + callback(error, null, apiResponse); + }, + }); + + const session = new Session(databaseInstance, NAME); + assert(session instanceof FakeGrpcServiceObject); + + session.calledWith_[0].createMethod(null, (err, sess, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(sess, null); + assert.strictEqual(resp, apiResponse); + done(); + }); + }); + }); + }); + + describe('formatName_', () => { + const PATH = DATABASE.formattedName_ + '/sessions/' + NAME; + + it('should return the name if already formatted', () => { + assert.strictEqual( + Session.formatName_(DATABASE.formattedName_, PATH), + PATH, + ); + }); + + it('should format the name', () => { + const formattedName = Session.formatName_(DATABASE.formattedName_, NAME); + assert.strictEqual(formattedName, PATH); + }); + }); + + describe('delete', () => { + it('should correctly call and return the request', () => { + const requestReturnValue = {}; + + function callback() {} + + session.request = (config, callback_) => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'deleteSession'); + assert.deepStrictEqual(config.reqOpts, { + name: session.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, { + ...session.commonHeaders_, + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + }); + + assert.strictEqual(callback_, callback); + return requestReturnValue; + }; + + const returnValue = session.delete(callback); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + + session.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + session.delete(gaxOptions, assert.ifError); + }); + }); + + describe('getMetadata', () => { + it('should correctly call and return the request using callback', done => { + const requestReturnValue = {}; + + session.request = (config, callback) => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'getSession'); + assert.deepStrictEqual(config.reqOpts, { + name: session.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual( + config.headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + session.commonHeaders_, + ), + ); + callback(null, requestReturnValue); + }; + + session.getMetadata((err, returnValue) => { + assert.ifError(err); + assert.strictEqual(returnValue, requestReturnValue); + done(); + }); + }); + + it('should correctly call and return the request using promise', async () => { + const requestReturnValue = {}; + + session.request = config => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'getSession'); + assert.deepStrictEqual(config.reqOpts, { + name: session.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual( + config.headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + session.commonHeaders_, + ), + ); + return new Promise(resolve => resolve(requestReturnValue)); + }; + + const returnValue = await session.getMetadata(); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should correctly call and return the request with Leader Aware Routing disabled.', () => { + const requestReturnValue = {}; + + function callback() {} + + session.parent.parent.parent.routeToLeaderEnabled = false; + session.request = config => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'getSession'); + assert.deepStrictEqual(config.reqOpts, { + name: session.formattedName_, + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, session.commonHeaders_); + return requestReturnValue; + }; + + const returnValue = session.getMetadata(callback); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should accept and pass gaxOptions to request', done => { + const gaxOptions = {}; + session.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + session.getMetadata(gaxOptions, assert.ifError); + }); + + it('should update metadata', done => { + const metadata = {}; + session.request = (config, callback) => { + callback(null, metadata); + }; + session.getMetadata(err => { + assert.ifError(err); + assert.strictEqual(session.metadata, metadata); + done(); + }); + }); + + it('should call callback with error', done => { + const error = new Error('Error'); + session.request = (config, callback) => { + callback(error); + }; + session.getMetadata(err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('keepAlive', () => { + it('should correctly call and return the request', () => { + const requestReturnValue = {}; + + function callback() {} + + session.request = (config, callback_) => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'executeSql'); + assert.deepStrictEqual(config.reqOpts, { + session: session.formattedName_, + sql: 'SELECT 1', + }); + assert.deepStrictEqual(config.gaxOpts, {}); + assert.deepStrictEqual(config.headers, { + ...session.commonHeaders_, + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + }); + assert.strictEqual(callback_, callback); + return requestReturnValue; + }; + + const returnValue = session.keepAlive(callback); + assert.strictEqual(returnValue, requestReturnValue); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + session.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + session.keepAlive(gaxOptions, assert.ifError); + }); + }); + + describe('partitionedDml', () => { + it('should return a Transaction object', () => { + const pdml = session.partitionedDml(); + assert(pdml instanceof FakePartitionedDml); + assert.strictEqual(pdml.calledWith_[0], session); + }); + }); + + describe('snapshot', () => { + const OPTIONS = {}; + + it('should return a Transaction object', () => { + const snapshot = session.snapshot(OPTIONS); + assert(snapshot instanceof FakeSnapshot); + assert.strictEqual(snapshot.calledWith_[0], session); + assert.strictEqual(snapshot.calledWith_[1], OPTIONS); + }); + }); + + describe('transaction', () => { + it('should return a Transaction object', () => { + const transaction = session.transaction(); + assert(transaction instanceof FakeTransaction); + assert.strictEqual(transaction.calledWith_[0], session); + }); + }); +}); diff --git a/handwritten/spanner/test/spanner.ts b/handwritten/spanner/test/spanner.ts new file mode 100644 index 00000000000..fc14dff5378 --- /dev/null +++ b/handwritten/spanner/test/spanner.ts @@ -0,0 +1,7373 @@ +/*! + * Copyright 2020 Google LLC. All Rights Reserved. + * + * 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 {after, before, beforeEach, describe, Done, it} from 'mocha'; +import * as assert from 'assert'; +import {grpc, Status, ServiceError} from 'google-gax'; +// eslint-disable-next-line n/no-extraneous-import +import * as grpcModule from '@grpc/grpc-js'; +import { + Database, + Instance, + MutationGroup, + MutationSet, + SessionPool, + Snapshot, + Spanner, + Transaction, +} from '../src'; +import * as mock from './mockserver/mockspanner'; +import { + MockError, + MockSpanner, + NUM_ROWS_LARGE_RESULT_SET, + SimulatedExecutionTime, +} from './mockserver/mockspanner'; +import * as mockInstanceAdmin from './mockserver/mockinstanceadmin'; +import {TEST_INSTANCE_NAME} from './mockserver/mockinstanceadmin'; +import * as mockDatabaseAdmin from './mockserver/mockdatabaseadmin'; +import * as sinon from 'sinon'; +import {google} from '../protos/protos'; +import {ExecuteSqlRequest, ReadRequest, RunResponse} from '../src/transaction'; +import {Row} from '../src/partial-result-stream'; +import {GetDatabaseOperationsOptions} from '../src/instance'; +import { + isSessionNotFoundError, + SessionLeakError, + SessionPoolExhaustedError, + SessionPoolOptions, +} from '../src/session-pool'; +import {Float, Int, Json, Numeric, SpannerDate} from '../src/codec'; +import * as stream from 'stream'; +import * as util from 'util'; +import {PreciseDate} from '@google-cloud/precise-date'; +import { + CLOUD_RESOURCE_HEADER, + LEADER_AWARE_ROUTING_HEADER, +} from '../src/common'; +import { + RequestIDError, + X_GOOG_REQ_ID_REGEX, + X_GOOG_SPANNER_REQUEST_ID_HEADER, + X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR, + randIdForProcess, + resetNthClientId, +} from '../src/request_id_header'; +import CreateInstanceMetadata = google.spanner.admin.instance.v1.CreateInstanceMetadata; +import QueryOptions = google.spanner.v1.ExecuteSqlRequest.QueryOptions; +import v1 = google.spanner.v1; +import IQueryOptions = google.spanner.v1.ExecuteSqlRequest.IQueryOptions; +import ResultSetStats = google.spanner.v1.ResultSetStats; +import RequestOptions = google.spanner.v1.RequestOptions; +import PartialResultSet = google.spanner.v1.PartialResultSet; +import protobuf = google.spanner.v1; +import Priority = google.spanner.v1.RequestOptions.Priority; +import TypeCode = google.spanner.v1.TypeCode; +import NullValue = google.protobuf.NullValue; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import {SessionFactory} from '../src/session-factory'; +import {MultiplexedSession} from '../src/multiplexed-session'; +import {WriteAtLeastOnceOptions} from '../src/database'; +import {MetricsTracerFactory} from '../src/metrics/metrics-tracer-factory'; +import {randomUUID} from 'crypto'; + +const { + AlwaysOnSampler, + NodeTracerProvider, + InMemorySpanExporter, +} = require('@opentelemetry/sdk-trace-node'); +const {SimpleSpanProcessor} = require('@opentelemetry/sdk-trace-base'); +const {startTrace, ObservabilityOptions} = require('../src/instrument'); + +function numberToEnglishWord(num: number): string { + switch (num) { + case 1: + return 'One'; + case 2: + return 'Two'; + case 3: + return 'Three'; + default: + throw new Error(`Unknown or unsupported number: ${num}`); + } +} + +async function disableMetrics(sandbox: sinon.SinonSandbox) { + if ( + Object.prototype.hasOwnProperty.call( + process.env, + 'SPANNER_DISABLE_BUILTIN_METRICS', + ) + ) { + sandbox.replace(process.env, 'SPANNER_DISABLE_BUILTIN_METRICS', 'true'); + } else { + sandbox.define(process.env, 'SPANNER_DISABLE_BUILTIN_METRICS', 'true'); + } + await MetricsTracerFactory.resetInstance(); + MetricsTracerFactory.enabled = false; +} + +class XGoogRequestHeaderInterceptor { + private nStream: number; + private nUnary: number; + private streamCalls: any[]; + private unaryCalls: any[]; + private prefixesToIgnore?: string[]; + constructor(prefixesToIgnore?: string[]) { + this.nStream = 0; + this.streamCalls = []; + this.nUnary = 0; + this.unaryCalls = []; + this.prefixesToIgnore = prefixesToIgnore || []; + } + + assertHasHeader(call): string | unknown { + const metadata = call.metadata; + const gotReqId = metadata[X_GOOG_SPANNER_REQUEST_ID_HEADER]; + if (!gotReqId) { + throw new Error( + `${call.method} is missing ${X_GOOG_SPANNER_REQUEST_ID_HEADER} header`, + ); + } + + if (!gotReqId.match(X_GOOG_REQ_ID_REGEX)) { + throw new Error( + `${call.method} reqID header ${gotReqId} does not match ${X_GOOG_REQ_ID_REGEX}`, + ); + } + return gotReqId; + } + + interceptUnary(call, next) { + const gotReqId = this.assertHasHeader(call); + this.unaryCalls.push({method: call.method, reqId: gotReqId}); + this.nUnary++; + next(call); + } + + generateClientInterceptor() { + return this.interceptUnary.bind(this); + } + + interceptStream(call, next) { + const gotReqId = this.assertHasHeader(call); + this.streamCalls.push({method: call.method, reqId: gotReqId}); + this.nStream++; + next(call); + } + + generateServerInterceptor() { + return this.serverInterceptor.bind(this); + } + + reset() { + this.nStream = 0; + this.streamCalls = []; + this.nUnary = 0; + this.unaryCalls = []; + } + + public getUnaryCalls() { + return this.unaryCalls; + } + + public getStreamingCalls() { + return this.streamCalls; + } + + serverInterceptor(methodDescriptor, call) { + const method = call.handler.path; + const isUnary = call.handler.type === 'unary'; + const listener = new grpcModule.ServerListenerBuilder() + .withOnReceiveMetadata((metadata, next) => { + let i = 0; + const prefixesToIgnore: string[] = this.prefixesToIgnore || []; + for (i = 0; i < prefixesToIgnore.length; i++) { + const prefix = prefixesToIgnore[i]; + if (method.startsWith(prefix)) { + next(metadata); + return; + } + } + + const gotReqIds = metadata.get(X_GOOG_SPANNER_REQUEST_ID_HEADER); + if (!(gotReqIds && gotReqIds.length > 0)) { + call.sendStatus({ + code: grpcModule.status.INVALID_ARGUMENT, + details: `${method} is missing ${X_GOOG_SPANNER_REQUEST_ID_HEADER} header`, + }); + return; + } + + if (gotReqIds.length !== 1) { + call.sendStatus({ + code: grpcModule.status.INVALID_ARGUMENT, + details: `${method} set multiple ${X_GOOG_SPANNER_REQUEST_ID_HEADER} headers: ${gotReqIds}`, + }); + return; + } + + const gotReqId = gotReqIds[0].toString(); + if (!gotReqId.match(X_GOOG_REQ_ID_REGEX)) { + call.sendStatus({ + code: grpcModule.status.INVALID_ARGUMENT, + details: `${method} reqID header ${gotReqId} does not match ${X_GOOG_REQ_ID_REGEX}`, + }); + return; + } + + if (isUnary) { + this.unaryCalls.push({method: method, reqId: gotReqId}); + this.nUnary++; + } else { + this.streamCalls.push({method: method, reqId: gotReqId}); + this.nStream++; + } + + next(metadata); + }) + .build(); + + const responder = new grpcModule.ResponderBuilder() + .withStart(next => next(listener)) + .build(); + return new grpcModule.ServerInterceptingCall(call, responder); + } +} +describe('Spanner with mock server', () => { + let sandbox: sinon.SinonSandbox; + const selectSql = 'SELECT NUM, NAME FROM NUMBERS'; + const select1 = 'SELECT 1'; + const invalidSql = 'SELECT * FROM FOO'; + const insertSql = "INSERT INTO NUMBER (NUM, NAME) VALUES (4, 'Four')"; + const selectAllTypes = 'SELECT * FROM TABLE_WITH_ALL_TYPES'; + const insertSqlForAllTypes = `INSERT INTO TABLE_WITH_ALL_TYPES (COLBOOL, COLINT64, COLFLOAT64, COLNUMERIC, COLSTRING, COLBYTES, COLJSON, COLDATE, COLTIMESTAMP) + VALUES (@bool, @int64, @float64, @numeric, @string, @bytes, @json, @date, @timestamp)`; + const updateSql = "UPDATE NUMBER SET NAME='Unknown' WHERE NUM IN (5, 6)"; + const readPartitionsQuery = { + table: 'abc', + keySet: { + keys: [], + all: true, + ranges: [{}, {}], + }, + gaxOptions: {}, + dataBoostEnabled: true, + }; + const fooNotFoundErr = Object.assign(new Error('Table FOO not found'), { + code: grpc.status.NOT_FOUND, + }); + const xGoogReqIDInterceptor = new XGoogRequestHeaderInterceptor([ + '/google.spanner.admin', + ]); + const server = new grpc.Server({ + interceptors: [xGoogReqIDInterceptor.generateServerInterceptor()], + }); + const spannerMock = mock.createMockSpanner(server); + mockInstanceAdmin.createMockInstanceAdmin(server); + mockDatabaseAdmin.createMockDatabaseAdmin(server); + let port: number; + let spanner: Spanner; + let instance: Instance; + let dbCounter = 1; + + function newTestDatabase(options?: SessionPoolOptions): Database { + return instance.database(`database-${dbCounter++}`, options); + } + + beforeEach(() => { + resetNthClientId(); + xGoogReqIDInterceptor.reset(); + }); + + before(async () => { + sandbox = sinon.createSandbox(); + port = await new Promise((resolve, reject) => { + server.bindAsync( + '0.0.0.0:0', + grpc.ServerCredentials.createInsecure(), + (err, assignedPort) => { + if (err) { + reject(err); + } else { + resolve(assignedPort); + } + }, + ); + }); + spannerMock.putReadRequestResult( + readPartitionsQuery, + mock.ReadRequestResult.resultSet(mock.createReadRequestResultSet()), + ); + spannerMock.putStatementResult( + selectSql, + mock.StatementResult.resultSet(mock.createSimpleResultSet()), + ); + spannerMock.putStatementResult( + select1, + mock.StatementResult.resultSet(mock.createSelect1ResultSet()), + ); + spannerMock.putStatementResult( + selectAllTypes, + mock.StatementResult.resultSet(mock.createResultSetWithAllDataTypes()), + ); + spannerMock.putStatementResult( + invalidSql, + mock.StatementResult.error(fooNotFoundErr), + ); + spannerMock.putStatementResult( + insertSql, + mock.StatementResult.updateCount(1), + ); + spannerMock.putStatementResult( + insertSqlForAllTypes, + mock.StatementResult.updateCount(1), + ); + spannerMock.putStatementResult( + updateSql, + mock.StatementResult.updateCount(2), + ); + + // TODO(loite): Enable when SPANNER_EMULATOR_HOST is supported. + // Set environment variable for SPANNER_EMULATOR_HOST to the mock server. + // process.env.SPANNER_EMULATOR_HOST = `localhost:${port}`; + process.env.GOOGLE_CLOUD_PROJECT = 'test-project'; + await disableMetrics(sandbox); + spanner = new Spanner({ + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + }); + // Gets a reference to a Cloud Spanner instance and database + instance = spanner.instance('instance'); + }); + + after(() => { + spanner.close(); + server.tryShutdown(() => {}); + delete process.env.SPANNER_EMULATOR_HOST; + sandbox.restore(); + }); + + beforeEach(() => { + spannerMock.resetRequests(); + spannerMock.removeExecutionTimes(); + }); + + describe('basics', () => { + it('should return different database instances when the same database is requested twice with different session pool options', async () => { + const dbWithDefaultOptions = newTestDatabase(); + const dbWithWriteSessions = instance.database(dbWithDefaultOptions.id!, { + fail: false, + }); + assert.notStrictEqual(dbWithDefaultOptions, dbWithWriteSessions); + }); + + it('should execute query', async () => { + // The query to execute + const query = { + sql: selectSql, + }; + const database = newTestDatabase(); + try { + const [rows] = await database.run(query); + assert.strictEqual(rows.length, 3); + let i = 0; + (rows as Row[]).forEach(row => { + i++; + const [numCol, nameCol] = row; + assert.strictEqual(numCol.name, 'NUM'); + assert.strictEqual(numCol.value.valueOf(), i); + assert.strictEqual(nameCol.name, 'NAME'); + assert.strictEqual(nameCol.value.valueOf(), numberToEnglishWord(i)); + }); + } finally { + await database.close(); + } + }); + + it('should replace {{projectId}} in resource header', async () => { + const query = { + sql: selectSql, + }; + const database = newTestDatabase(); + try { + await database.run(query); + spannerMock.getMetadata().forEach(metadata => { + assert.strictEqual( + metadata.get(CLOUD_RESOURCE_HEADER)[0], + `projects/test-project/instances/instance/databases/${database.id}`, + ); + }); + } finally { + await database.close(); + } + }); + + it('should execute query with requestOptions', async () => { + const priority = RequestOptions.Priority.PRIORITY_HIGH; + const database = newTestDatabase(); + try { + const [rows] = await database.run({ + sql: selectSql, + requestOptions: {priority: priority, requestTag: 'request-tag'}, + }); + assert.strictEqual(rows.length, 3); + } finally { + await database.close(); + } + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on ExecuteSqlRequest', + ); + assert.strictEqual(request.requestOptions!.priority, 'PRIORITY_HIGH'); + assert.strictEqual(request.requestOptions!.requestTag, 'request-tag'); + }); + + it('should execute read with requestOptions', async () => { + const database = newTestDatabase(); + const [snapshot] = await database.getSnapshot(); + try { + await snapshot.read('foo', { + keySet: {all: true}, + requestOptions: { + priority: Priority.PRIORITY_MEDIUM, + requestTag: 'request-tag', + }, + }); + } catch (e) { + assert.strictEqual((e as ServiceError).code, Status.UNKNOWN); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.3.1`, + ); + } finally { + snapshot.end(); + await database.close(); + } + const request = spannerMock.getRequests().find(val => { + return (val as v1.ReadRequest).table === 'foo'; + }) as v1.ReadRequest; + assert.ok(request, 'no ReadRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on ReadRequest', + ); + assert.strictEqual(request.requestOptions!.priority, 'PRIORITY_MEDIUM'); + assert.strictEqual(request.requestOptions!.requestTag, 'request-tag'); + }); + + it('should execute batchUpdate with requestOptions', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + {requestOptions: {transactionTag: 'transaction-tag'}}, + async tx => { + await tx!.batchUpdate([insertSql, insertSql], { + requestOptions: { + priority: RequestOptions.Priority.PRIORITY_MEDIUM, + requestTag: 'request-tag', + }, + }); + await tx!.batchUpdate([insertSql, insertSql]); + return await tx.commit(); + }, + ); + await database.close(); + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteBatchDmlRequest).statements; + }) as v1.ExecuteBatchDmlRequest; + assert.ok(request, 'no ExecuteBatchDmlRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on ExecuteBatchDmlRequest', + ); + assert.strictEqual(request.requestOptions!.priority, 'PRIORITY_MEDIUM'); + assert.strictEqual(request.requestOptions!.requestTag, 'request-tag'); + assert.strictEqual( + request.requestOptions!.transactionTag, + 'transaction-tag', + ); + assert.ok(request.transaction?.begin, 'transaction is not empty'); + const nextBatchRequest = spannerMock + .getRequests() + .reverse() + .find(val => { + return (val as v1.ExecuteBatchDmlRequest).statements; + }) as v1.ExecuteBatchDmlRequest; + assert.ok(nextBatchRequest, 'no ExecuteBatchDmlRequest found'); + assert.ok(nextBatchRequest.transaction?.id, 'no transaction ID'); + + const commitRequest = spannerMock.getRequests().find(val => { + return (val as v1.CommitRequest).mutations; + }) as v1.CommitRequest; + assert.strictEqual(commitRequest.requestOptions!.requestTag, ''); + assert.strictEqual( + commitRequest.requestOptions!.transactionTag, + 'transaction-tag', + ); + }); + + it('should use txn ID from batchUpdate if non-ok status', async () => { + const sql = "INSERT INTO TBL (NUM, NAME) VALUES (14, 'Four')"; + const database = newTestDatabase(); + const err = { + message: 'Not OK', + } as MockError; + spannerMock.putStatementResult( + sql, + mock.StatementResult.updateCount(1, err), + ); + + await database.runTransactionAsync(async tx => { + await tx!.batchUpdate([sql, insertSql]); + await tx!.batchUpdate([sql, insertSql]); + return await tx.commit(); + }); + await database.close(); + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteBatchDmlRequest).statements; + }) as v1.ExecuteBatchDmlRequest; + assert.ok(request, 'no ExecuteBatchDmlRequest found'); + assert.ok(request.transaction?.begin, 'transaction is not empty'); + const nextBatchRequest = spannerMock + .getRequests() + .reverse() + .find(val => { + return (val as v1.ExecuteBatchDmlRequest).statements; + }) as v1.ExecuteBatchDmlRequest; + assert.ok(nextBatchRequest, 'no ExecuteBatchDmlRequest found'); + assert.ok(nextBatchRequest.transaction?.id, 'no transaction ID'); + }); + + it('should execute update with requestOptions', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + {requestOptions: {transactionTag: 'transaction-tag'}}, + async tx => { + await tx!.runUpdate({ + sql: insertSql, + requestOptions: { + priority: RequestOptions.Priority.PRIORITY_LOW, + requestTag: 'request-tag', + }, + }); + return await tx.commit(); + }, + ); + await database.close(); + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on ExecuteSqlRequest', + ); + assert.strictEqual(request.requestOptions!.priority, 'PRIORITY_LOW'); + assert.strictEqual(request.requestOptions!.requestTag, 'request-tag'); + assert.ok(request.transaction!.begin!.readWrite, 'ReadWrite is not set'); + assert.strictEqual( + request.requestOptions!.transactionTag, + 'transaction-tag', + ); + const commitRequest = spannerMock.getRequests().find(val => { + return (val as v1.CommitRequest).mutations; + }) as v1.CommitRequest; + assert.strictEqual(commitRequest.requestOptions!.requestTag, ''); + assert.strictEqual( + commitRequest.requestOptions!.transactionTag, + 'transaction-tag', + ); + }); + + it('should execute read with requestOptions in a read/write transaction', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + { + readLockMode: ReadLockMode.OPTIMISTIC, + requestOptions: {transactionTag: 'transaction-tag'}, + }, + async tx => { + try { + return await tx.read('foo', { + keySet: {all: true}, + requestOptions: { + priority: Priority.PRIORITY_LOW, + requestTag: 'request-tag', + }, + }); + } catch (e) { + assert.strictEqual((e as ServiceError).code, Status.UNKNOWN); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + return undefined; + } finally { + tx.end(); + } + }, + ); + // awaiting 10ms for begin call to finish its execution + await new Promise(resolve => setTimeout(resolve, 10)); + await database.close(); + const request = spannerMock.getRequests().find(val => { + return (val as v1.ReadRequest).table === 'foo'; + }) as v1.ReadRequest; + assert.ok(request, 'no ReadRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on ReadRequest', + ); + assert.strictEqual(request.requestOptions!.priority, 'PRIORITY_LOW'); + assert.strictEqual(request.requestOptions!.requestTag, 'request-tag'); + assert.strictEqual( + request.requestOptions!.transactionTag, + 'transaction-tag', + ); + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + assert.strictEqual( + beginTxnRequest.options?.readWrite!.readLockMode, + 'OPTIMISTIC', + ); + }); + + it('should return an array of json objects', async () => { + const database = newTestDatabase(); + try { + const [rows] = await database.run({sql: selectSql, json: true}); + assert.strictEqual(rows.length, 3); + let i = 0; + (rows as Json[]).forEach(row => { + i++; + assert.strictEqual(row.NUM, i); + assert.strictEqual(row.NAME, numberToEnglishWord(i)); + }); + } finally { + await database.close(); + } + }); + + it('should support all data types', async () => { + const database = newTestDatabase(); + try { + const [rows] = await database.run(selectAllTypes); + assert.strictEqual(rows.length, 3); + let i = 0; + (rows as Row[]).forEach(row => { + i++; + const [ + boolCol, + int64Col, + float64Col, + numericCol, + stringCol, + bytesCol, + jsonCol, + dateCol, + timestampCol, + arrayBoolCol, + arrayInt64Col, + arrayFloat64Col, + arrayNumericCol, + arrayStringCol, + arrayBytesCol, + arrayJsonCol, + arrayDateCol, + arrayTimestampCol, + ] = row; + if (i === 3) { + assert.ok(boolCol.value === null); + assert.ok(int64Col.value === null); + assert.ok(float64Col.value === null); + assert.ok(numericCol.value === null); + assert.ok(stringCol.value === null); + assert.ok(bytesCol.value === null); + assert.ok(jsonCol.value === null); + assert.ok(dateCol.value === null); + assert.ok(timestampCol.value === null); + assert.ok(arrayBoolCol.value === null); + assert.ok(arrayInt64Col.value === null); + assert.ok(arrayFloat64Col.value === null); + assert.ok(arrayNumericCol.value === null); + assert.ok(arrayStringCol.value === null); + assert.ok(arrayBytesCol.value === null); + assert.ok(arrayJsonCol.value === null); + assert.ok(arrayDateCol.value === null); + assert.ok(arrayTimestampCol.value === null); + } else { + assert.strictEqual(boolCol.value, i === 1); + assert.deepStrictEqual(int64Col.value, new Int(`${i}`)); + assert.deepStrictEqual(float64Col.value, new Float(3.14)); + assert.deepStrictEqual(numericCol.value, new Numeric('6.626')); + assert.strictEqual(stringCol.value, numberToEnglishWord(i)); + assert.deepStrictEqual(bytesCol.value, Buffer.from('test')); + assert.deepStrictEqual(jsonCol.value, { + result: true, + count: 42, + }); + assert.deepStrictEqual( + dateCol.value, + new SpannerDate('2021-05-11'), + ); + assert.deepStrictEqual( + timestampCol.value, + new PreciseDate('2021-05-11T16:46:04.872Z'), + ); + assert.deepStrictEqual(arrayBoolCol.value, [true, false, null]); + assert.deepStrictEqual(arrayInt64Col.value, [ + new Int(`${i}`), + new Int(`${i}00`), + null, + ]); + assert.deepStrictEqual(arrayFloat64Col.value, [ + new Float(3.14), + new Float(100.9), + null, + ]); + assert.deepStrictEqual(arrayNumericCol.value, [ + new Numeric('6.626'), + new Numeric('100'), + null, + ]); + assert.deepStrictEqual(arrayStringCol.value, [ + numberToEnglishWord(i), + 'test', + null, + ]); + assert.deepStrictEqual(arrayBytesCol.value, [ + Buffer.from('test1'), + Buffer.from('test2'), + null, + ]); + assert.deepStrictEqual(arrayJsonCol.value, [ + {result: true, count: 42}, + {}, + null, + ]); + assert.deepStrictEqual(arrayDateCol.value, [ + new SpannerDate('2021-05-12'), + new SpannerDate('2000-02-29'), + null, + ]); + assert.deepStrictEqual(arrayTimestampCol.value, [ + new PreciseDate('2021-05-12T08:38:19.8474Z'), + new PreciseDate('2000-02-29T07:00:00Z'), + null, + ]); + } + }); + } finally { + await database.close(); + } + }); + + it('should support all data types as JSON', async () => { + const database = newTestDatabase(); + try { + const [rows] = await database.run({ + sql: selectAllTypes, + json: true, + }); + assert.strictEqual(rows.length, 3); + let i = 0; + (rows as Json[]).forEach(row => { + i++; + if (i === 3) { + assert.ok(row.COLBOOL === null); + assert.ok(row.COLINT64 === null); + assert.ok(row.COLFLOAT64 === null); + assert.ok(row.COLNUMERIC === null); + assert.ok(row.COLSTRING === null); + assert.ok(row.COLBYTES === null); + assert.ok(row.COLJSON === null); + assert.ok(row.COLDATE === null); + assert.ok(row.COLTIMESTAMP === null); + assert.ok(row.COLBOOLARRAY === null); + assert.ok(row.COLINT64ARRAY === null); + assert.ok(row.COLFLOAT64ARRAY === null); + assert.ok(row.COLNUMERICARRAY === null); + assert.ok(row.COLSTRINGARRAY === null); + assert.ok(row.COLBYTESARRAY === null); + assert.ok(row.COLJSONARRAY === null); + assert.ok(row.COLDATEARRAY === null); + assert.ok(row.COLTIMESTAMPARRAY === null); + } else { + assert.strictEqual(row.COLBOOL, i === 1); + assert.strictEqual(row.COLINT64, i); + assert.strictEqual(row.COLFLOAT64, 3.14); + assert.deepStrictEqual(row.COLNUMERIC, new Numeric('6.626')); + assert.strictEqual(row.COLSTRING, numberToEnglishWord(i)); + assert.deepStrictEqual(row.COLBYTES, Buffer.from('test')); + assert.deepStrictEqual(row.COLJSON, { + result: true, + count: 42, + }); + assert.deepStrictEqual(row.COLDATE, new SpannerDate('2021-05-11')); + assert.deepStrictEqual( + row.COLTIMESTAMP, + new PreciseDate('2021-05-11T16:46:04.872Z'), + ); + assert.deepStrictEqual(row.COLBOOLARRAY, [true, false, null]); + assert.deepStrictEqual(row.COLINT64ARRAY, [i, 100 * i, null]); + assert.deepStrictEqual(row.COLFLOAT64ARRAY, [3.14, 100.9, null]); + assert.deepStrictEqual(row.COLNUMERICARRAY, [ + new Numeric('6.626'), + new Numeric('100'), + null, + ]); + assert.deepStrictEqual(row.COLSTRINGARRAY, [ + numberToEnglishWord(i), + 'test', + null, + ]); + assert.deepStrictEqual(row.COLBYTESARRAY, [ + Buffer.from('test1'), + Buffer.from('test2'), + null, + ]); + assert.deepStrictEqual(row.COLJSONARRAY, [ + {result: true, count: 42}, + {}, + null, + ]); + assert.deepStrictEqual(row.COLDATEARRAY, [ + new SpannerDate('2021-05-12'), + new SpannerDate('2000-02-29'), + null, + ]); + assert.deepStrictEqual(row.COLTIMESTAMPARRAY, [ + new PreciseDate('2021-05-12T08:38:19.8474Z'), + new PreciseDate('2000-02-29T07:00:00Z'), + null, + ]); + } + }); + } finally { + await database.close(); + } + }); + + it('should receive metadata', async () => { + // The query to execute + const query = { + sql: selectSql, + }; + const database = newTestDatabase(); + try { + const [rows, , metadata] = await database.run(query); + assert.strictEqual(rows.length, 3); + assert.ok(metadata); + assert.strictEqual(metadata.rowType!.fields!.length, 2); + assert.strictEqual(metadata.rowType!.fields![0].name, 'NUM'); + assert.strictEqual(metadata.rowType!.fields![1].name, 'NAME'); + } finally { + await database.close(); + } + }); + + it('should return result without column name in JSON', async () => { + // The query to execute + const query = { + sql: select1, + json: true, + jsonOptions: {includeNameless: true}, + } as ExecuteSqlRequest; + const database = newTestDatabase(); + try { + const [rows, , metadata] = await database.run(query); + assert.strictEqual(rows.length, 1); + assert.ok(metadata); + assert.strictEqual(metadata.rowType!.fields!.length, 1); + assert.strictEqual(metadata.rowType!.fields![0].name, ''); + assert.strictEqual(rows[0]['_0'], 1); + } finally { + await database.close(); + } + }); + + it('should pause on slow writer', async () => { + const largeSelect = 'select * from large_table'; + spannerMock.putStatementResult( + largeSelect, + mock.StatementResult.resultSet(mock.createLargeResultSet()), + ); + const database = newTestDatabase(); + let rowCount = 0; + let paused = false; + try { + const rs = database.runStream({ + sql: largeSelect, + }); + const pipeline = util.promisify(stream.pipeline); + const simulateSlowFlushInterval = Math.floor( + NUM_ROWS_LARGE_RESULT_SET / 10, + ); + + await pipeline( + rs, + // Create an artificially slow transformer to simulate network latency. + new stream.Transform({ + highWaterMark: 1, + objectMode: true, + transform(chunk, encoding, callback) { + rowCount++; + if (rowCount % simulateSlowFlushInterval === 0) { + // Simulate a slow flush. + setTimeout(() => { + paused = paused || rs.isPaused(); + callback(undefined, chunk); + }, 50); + } else { + callback(undefined, chunk); + } + }, + }), + new stream.Transform({ + objectMode: true, + transform(chunk, encoding, callback) { + callback(); + }, + }), + ); + assert.strictEqual(rowCount, NUM_ROWS_LARGE_RESULT_SET); + assert.ok(paused, 'stream should have been paused'); + } finally { + await database.close(); + } + }); + + it('should fail on slow writer when maxResumeRetries has been exceeded', async () => { + const largeSelect = 'select * from large_table'; + spannerMock.putStatementResult( + largeSelect, + mock.StatementResult.resultSet(mock.createLargeResultSet()), + ); + const database = newTestDatabase(); + try { + const rs = database.runStream({ + sql: largeSelect, + maxResumeRetries: 1, + }); + const pipeline = util.promisify(stream.pipeline); + + await pipeline( + rs, + // Create an artificially slow transformer to simulate network latency. + new stream.Transform({ + highWaterMark: 1, + objectMode: true, + transform(chunk, encoding, callback) { + // Simulate a slow flush. + setTimeout(() => { + callback(undefined, chunk); + }, 50); + }, + }), + new stream.Transform({ + objectMode: true, + transform(chunk, encoding, callback) { + callback(); + }, + }), + ); + assert.fail('missing expected error'); + } catch (err) { + assert.strictEqual( + (err as ServiceError).message, + 'Stream is still not ready to receive data after 1 attempts to resume.', + ); + } finally { + await database.close(); + } + }); + + it('should return statistics', async () => { + const database = newTestDatabase(); + try { + const [rows, stats] = await database.run({ + sql: selectSql, + queryMode: google.spanner.v1.ExecuteSqlRequest.QueryMode.PROFILE, + }); + assert.strictEqual(rows.length, 3); + assert.ok(stats); + assert.ok(stats.queryPlan); + } finally { + await database.close(); + } + }); + + it('should return statistics from snapshot', async () => { + const database = newTestDatabase(); + try { + const [snapshot] = await database.getSnapshot(); + const [rows, stats] = await snapshot.run({ + sql: selectSql, + queryMode: google.spanner.v1.ExecuteSqlRequest.QueryMode.PROFILE, + }); + assert.strictEqual(rows.length, 3); + assert.ok(stats); + assert.ok(stats.queryPlan); + snapshot.end(); + } finally { + await database.close(); + } + }); + + it('should emit query statistics', done => { + const database = newTestDatabase(); + let rowCount = 0; + let stats: ResultSetStats; + database + .runStream({ + sql: selectSql, + queryMode: google.spanner.v1.ExecuteSqlRequest.QueryMode.PROFILE, + }) + .on('data', () => rowCount++) + .on('stats', _stats => (stats = _stats)) + .on('end', () => { + assert.strictEqual(rowCount, 3); + assert.ok(stats); + assert.ok(stats.queryPlan); + database + .close() + .then(() => done()) + .catch(() => done()); + }); + }); + + it('should emit query statistics from snapshot', done => { + const database = newTestDatabase(); + let rowCount = 0; + let stats: ResultSetStats; + database + .getSnapshot() + .then(response => { + const [snapshot] = response; + snapshot + .runStream({ + sql: selectSql, + queryMode: google.spanner.v1.ExecuteSqlRequest.QueryMode.PROFILE, + }) + .on('data', () => rowCount++) + .on('stats', _stats => (stats = _stats)) + .on('end', () => { + assert.strictEqual(rowCount, 3); + assert.ok(stats); + assert.ok(stats.queryPlan); + snapshot.end(); + database + .close() + .then(() => done()) + .catch(() => done()); + }); + }) + .catch(err => done(err)); + }); + + it('should call callback with statistics', done => { + const database = newTestDatabase(); + database.run( + { + sql: selectSql, + queryMode: google.spanner.v1.ExecuteSqlRequest.QueryMode.PROFILE, + }, + (err, rows, stats) => { + assert.ifError(err); + assert.strictEqual(rows.length, 3); + assert.ok(stats); + assert.ok(stats.queryPlan); + database + .close() + .then(() => done()) + .catch(() => done()); + }, + ); + }); + + it('should execute update', async () => { + const update = { + sql: insertSql, + }; + const database = newTestDatabase(); + try { + const updated = await executeSimpleUpdate(database, update); + assert.deepStrictEqual(updated, [1]); + } finally { + await database.close(); + } + }); + + it('should execute update with all types', async () => { + const update = { + sql: insertSqlForAllTypes, + params: { + bool: true, + int64: 100, + float64: 3.14, + numeric: new Numeric('6.626'), + string: 'test', + bytes: Buffer.from('test'), + json: {key1: 'value1', key2: 'value2', key3: ['1', '2', '3']}, + date: new SpannerDate('2021-05-11'), + timestamp: new PreciseDate('2021-05-11T17:55:16.9823Z'), + }, + }; + const database = newTestDatabase(); + try { + const updated = await executeSimpleUpdate(database, update); + assert.deepStrictEqual(updated, [1]); + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual(request.params!.fields!['bool'].boolValue, true); + assert.strictEqual(request.params!.fields!['int64'].stringValue, '100'); + assert.strictEqual( + request.params!.fields!['float64'].numberValue, + 3.14, + ); + assert.strictEqual( + request.params!.fields!['numeric'].stringValue, + '6.626', + ); + assert.strictEqual( + request.params!.fields!['string'].stringValue, + 'test', + ); + assert.strictEqual( + request.params!.fields!['bytes'].stringValue, + Buffer.from('test').toString('base64'), + ); + assert.strictEqual( + request.params!.fields!['json'].stringValue, + '{"key1":"value1","key2":"value2","key3":["1","2","3"]}', + ); + assert.strictEqual( + request.params!.fields!['date'].stringValue, + '2021-05-11', + ); + assert.strictEqual( + request.params!.fields!['timestamp'].stringValue, + '2021-05-11T17:55:16.982300000Z', + ); + assert.strictEqual(request.paramTypes!['bool'].code, 'BOOL'); + assert.strictEqual(request.paramTypes!['int64'].code, 'INT64'); + assert.strictEqual(request.paramTypes!['float64'].code, 'FLOAT64'); + assert.strictEqual(request.paramTypes!['numeric'].code, 'NUMERIC'); + assert.strictEqual(request.paramTypes!['string'].code, 'STRING'); + assert.strictEqual(request.paramTypes!['bytes'].code, 'BYTES'); + assert.strictEqual(request.paramTypes!['json'].code, 'JSON'); + assert.strictEqual(request.paramTypes!['date'].code, 'DATE'); + assert.strictEqual(request.paramTypes!['timestamp'].code, 'TIMESTAMP'); + } finally { + await database.close(); + } + }); + + it('should execute queries in parallel', async () => { + // The query to execute + const query = { + sql: selectSql, + }; + const database = newTestDatabase({incStep: 1, min: 0}); + try { + const sessionFactory = database.sessionFactory_ as SessionFactory; + const pool = sessionFactory.pool_ as SessionPool; + const multiplexedSession = + sessionFactory.multiplexedSession_ as MultiplexedSession; + const promises: Array> = []; + for (let i = 0; i < 10; i++) { + promises.push(database.run(query)); + } + await Promise.all(promises); + assert.notEqual( + multiplexedSession, + null, + 'Multiplexed session should be not null', + ); + } finally { + await database.close(); + } + }); + + it('should execute updates in parallel', async () => { + spannerMock.freeze(); + const update = { + sql: insertSql, + }; + const database = newTestDatabase({incStep: 1, min: 0}); + try { + const sessionFactory = database.sessionFactory_ as SessionFactory; + const pool = sessionFactory.pool_ as SessionPool; + const multiplexedSession = + sessionFactory.multiplexedSession_ as MultiplexedSession; + const promises: Array> = []; + for (let i = 0; i < 10; i++) { + promises.push(executeSimpleUpdate(database, update)); + } + spannerMock.unfreeze(); + await Promise.all(promises); + assert.notEqual( + multiplexedSession, + null, + 'Multiplexed session should be not null', + ); + } finally { + await database.close(); + } + }); + + it('should retry UNAVAILABLE from executeStreamingSql with a callback', done => { + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + database.run(selectSql, (err, rows) => { + assert.ifError(err); + assert.strictEqual(rows!.length, 3); + database + .close() + .then(() => { + const gotStreamingCalls = xGoogReqIDInterceptor.getStreamingCalls(); + const wantStreamingCalls = [ + { + method: '/google.spanner.v1.Spanner/ExecuteStreamingSql', + reqId: `1.${randIdForProcess}.1.1.2.1`, + }, + { + method: '/google.spanner.v1.Spanner/ExecuteStreamingSql', + reqId: `1.${randIdForProcess}.1.1.2.2`, + }, + ]; + assert.deepStrictEqual(gotStreamingCalls, wantStreamingCalls); + done(); + }) + .catch(err => done(err)); + }); + }); + + it('should not retry non-retryable error from executeStreamingSql with a callback', done => { + const database = newTestDatabase(); + const err = { + message: 'Non-retryable error', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + database.run(selectSql, err => { + assert.ok(err, 'Missing expected error'); + assert.strictEqual(err!.message, '2 UNKNOWN: Non-retryable error'); + database + .close() + .then(() => done()) + .catch(err => done(err)); + }); + }); + + it('should emit non-retryable error to runStream', done => { + const database = newTestDatabase(); + const err = { + message: 'Test error', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + const rows: Row[] = []; + const stream = database.runStream(selectSql); + stream + .on('error', err => { + assert.strictEqual(err.message, '2 UNKNOWN: Test error'); + database + .close() + .then(() => done()) + .catch(err => done(err)); + }) + .on('data', row => rows.push(row)) + .on('end', () => { + if (rows.length) { + assert.fail('Should not receive data'); + } + assert.fail('Missing expected error'); + }); + }); + + it('should retry UNAVAILABLE from executeStreamingSql', async () => { + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + details: 'Transient error', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + try { + const [rows] = await database.run(selectSql); + assert.strictEqual(rows.length, 3); + } finally { + await database.close(); + } + }); + + it('should not retry non-retryable errors from executeStreamingSql', async () => { + const database = newTestDatabase(); + const err = { + message: 'Test error', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + try { + await database.run(selectSql); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + '2 UNKNOWN: Test error', + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + } finally { + await database.close(); + } + }); + + it('should not retry UNAVAILABLE from executeStreamingSql when maxQueued was exceeded', async () => { + // Setup a query result with more than maxQueued (10) PartialResultSets. + // None of the PartialResultSets include a resume token. + const sql = 'SELECT C1 FROM TestTable'; + const fields = [ + protobuf.StructType.Field.create({ + name: 'C1', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + const results: PartialResultSet[] = []; + for (let i = 0; i < 12; i++) { + results.push( + PartialResultSet.create({ + metadata, + values: [{stringValue: `V${i}`}], + }), + ); + } + spannerMock.putStatementResult( + sql, + mock.StatementResult.resultSet(results), + ); + // Register an error after maxQueued has been exceeded. + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + details: 'Transient error', + streamIndex: 11, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + + const database = newTestDatabase(); + try { + await database.run(sql); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + '14 UNAVAILABLE: Transient error', + ); + // Ensure that we have a requestID returned and it was on the 2nd request. + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + } finally { + await database.close(); + } + }); + + it('should return the results correctly when last field is present in PartialResultSet for query', async () => { + // Setup a query result with more than maxQueued (10) PartialResultSets. + // None of the PartialResultSets include a resume token. + const sql = 'SELECT C1 FROM TestTable'; + const fields = [ + protobuf.StructType.Field.create({ + name: 'C1', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + const results: PartialResultSet[] = []; + for (let i = 0; i < 2; i++) { + results.push( + PartialResultSet.create({ + metadata, + values: [{stringValue: `V${i}`}], + last: i === 1, + }), + ); + } + spannerMock.putStatementResult( + sql, + mock.StatementResult.resultSet(results), + ); + + const database = newTestDatabase(); + const [rows] = await database.run(sql); + assert.equal(rows.length, 2); + await database.close(); + }); + + it('should return the results correctly when last field is present in PartialResultSet for read', async () => { + // Setup a query result with more than maxQueued (10) PartialResultSets. + // None of the PartialResultSets include a resume token. + const fields = [ + protobuf.StructType.Field.create({ + name: 'C1', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + ]; + const metadata = new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + const results: PartialResultSet[] = []; + for (let i = 0; i < 2; i++) { + results.push( + PartialResultSet.create({ + metadata, + values: [{stringValue: `V${i}`}], + last: i === 0, + }), + ); + } + const request = { + table: 'TestTable', + keySet: { + keys: [], + all: true, + ranges: [], + }, + }; + spannerMock.putReadRequestResult( + request, + mock.ReadRequestResult.resultSet(results), + ); + + const database = newTestDatabase(); + const table = database.table('TestTable'); + const query = { + columns: ['C1'], + }; + const [rows] = await table.read(query); + assert.equal(rows.length, 1); + await database.close(); + }); + + it('should handle missing parameters in query', async () => { + const sql = + 'SELECT * FROM tableId WHERE namedParameter = @namedParameter'; + const database = newTestDatabase(); + const q = { + json: true, + params: {namedParameter: undefined}, + sql, + }; + spannerMock.putStatementResult( + sql, + mock.StatementResult.resultSet(mock.createSimpleResultSet()), + ); + try { + await database.run(q); + assert.fail('missing expected exception'); + } catch (err) { + assert.ok( + (err as ServiceError).message.includes( + 'Value of type undefined not recognized.', + ), + ); + } finally { + await database.close(); + } + }); + + it('should handle missing parameters in query stream', done => { + const sql = + 'SELECT * FROM tableId WHERE namedParameter = @namedParameter'; + const database = newTestDatabase(); + const q = { + json: true, + params: {namedParameter: undefined}, + sql, + }; + spannerMock.putStatementResult( + sql, + mock.StatementResult.resultSet(mock.createSimpleResultSet()), + ); + const prs = database.runStream(q); + setImmediate(() => { + prs + .on('data', () => {}) + .on('error', () => { + // The stream should end with an error, so the test should succeed. + done(); + }) + .on('end', () => { + database + .close() + .then(() => { + done(assert.fail('missing error')); + }) + .catch(err => done(err)); + }); + }); + }); + + it('should handle missing parameters in update', async () => { + const sql = + "UPDATE tableId SET namedParameter='Foo' WHERE namedParameter = @namedParameter"; + const database = newTestDatabase(); + const q = { + json: true, + params: {namedParameter: undefined}, + sql, + }; + await database.runTransactionAsync(async tx => { + try { + await tx.runUpdate(q); + assert.fail('missing expected exception'); + } catch (err) { + assert.ok( + (err as ServiceError).message.includes( + 'Value of type undefined not recognized.', + ), + ); + } + }); + await database.close(); + }); + + describe('PartialResultStream', () => { + const streamIndexes = [1, 2]; + streamIndexes.forEach(index => { + it('should retry UNAVAILABLE during streaming', async () => { + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + const [rows] = await database.run(selectSql); + assert.strictEqual(rows.length, 3); + await database.close(); + }); + + it('should retry UNAVAILABLE during streaming with txn ID from inline begin response', async () => { + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + const database = newTestDatabase(); + + await database.runTransactionAsync(async tx => { + await tx.run(selectSql); + await tx.commit(); + }); + await database.close(); + + const requests = spannerMock + .getRequests() + .filter(val => (val as v1.ExecuteSqlRequest).sql) + .map(req => req as v1.ExecuteSqlRequest); + assert.strictEqual(requests.length, 2); + assert.ok( + requests[0].transaction?.begin!.readWrite, + 'inline txn is not set.', + ); + assert.ok( + requests[1].transaction!.id, + 'Transaction ID is not used for retries.', + ); + assert.ok( + requests[1].resumeToken, + 'Resume token is not set for the retried', + ); + }); + + it('should retry UNAVAILABLE during streaming with txn ID from inline begin response with parallel queries', async () => { + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + const database = newTestDatabase(); + + await database.runTransactionAsync(async tx => { + const [rows1, rows2] = await Promise.all([ + tx!.run(selectSql), + tx!.run(selectSql), + ]); + assert.equal(rows1.length, 3); + assert.equal(rows2.length, 3); + await tx.commit(); + }); + await database.close(); + + const requests = spannerMock + .getRequests() + .filter(val => (val as v1.ExecuteSqlRequest).sql) + .map(req => req as v1.ExecuteSqlRequest); + assert.strictEqual(requests.length, 3); + assert.ok( + requests[0].transaction?.begin!.readWrite, + 'inline txn is not set.', + ); + assert.ok( + requests[1].transaction!.id, + 'Transaction ID is not used for retries.', + ); + assert.ok( + requests[1].resumeToken, + 'Resume token is not set for the retried', + ); + const commitRequests = spannerMock + .getRequests() + .filter(val => (val as v1.CommitRequest).mutations) + .map(req => req as v1.CommitRequest); + assert.strictEqual(commitRequests.length, 1); + assert.deepStrictEqual( + requests[1].transaction!.id, + requests[2].transaction!.id, + ); + assert.deepStrictEqual( + requests[1].transaction!.id, + commitRequests[0].transactionId, + ); + const beginTxnRequests = spannerMock + .getRequests() + .filter( + val => (val as v1.BeginTransactionRequest).options?.readWrite, + ) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequests.length, 0); + }); + + it('should not retry non-retryable error during streaming', async () => { + const database = newTestDatabase(); + const err = { + message: 'Test error', + streamIndex: index, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + try { + await database.run(selectSql); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + '2 UNKNOWN: Test error', + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + } + await database.close(); + }); + + it('should retry UNAVAILABLE during streaming with a callback', done => { + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + database.run(selectSql, (err, rows) => { + assert.ifError(err); + assert.strictEqual(rows!.length, 3); + database + .close() + .then(() => done()) + .catch(err => done(err)); + }); + }); + + it('should not retry non-retryable error during streaming with a callback', done => { + const database = newTestDatabase(); + const err = { + message: 'Non-retryable error', + streamIndex: index, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + database.run(selectSql, err => { + assert.ok(err, 'Missing expected error'); + assert.strictEqual(err!.message, '2 UNKNOWN: Non-retryable error'); + assert.deepStrictEqual( + (err as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + database + .close() + .then(() => done()) + .catch(err => done(err)); + }); + }); + + it('should emit non-retryable error during streaming to stream', done => { + const database = newTestDatabase(); + const err = { + message: 'Non-retryable error', + streamIndex: index, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + const receivedRows: Row[] = []; + database + .runStream(selectSql) + .on('error', err => { + assert.strictEqual(err.message, '2 UNKNOWN: Non-retryable error'); + assert.strictEqual(receivedRows.length, index); + assert.deepStrictEqual( + (err as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + database + .close() + .then(() => done()) + .catch(err => done(err)); + }) + // We will receive data for the partial result sets that are + // returned before the error occurs. + .on('data', row => { + receivedRows.push(row); + }) + .on('end', () => { + assert.fail('Missing expected error'); + }); + }); + }); + }); + + it('should retry UNAVAILABLE from executeStreamingSql with multiple errors during streaming', async () => { + const database = newTestDatabase(); + const errors: MockError[] = []; + for (const index of [0, 1, 1, 2, 2]) { + errors.push({ + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as MockError); + } + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofErrors(errors), + ); + const [rows] = await database.run(selectSql); + assert.strictEqual(rows.length, 3); + await database.close(); + }); + + it('should retry UNAVAILABLE on update', done => { + const database = newTestDatabase(); + const err = { + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + database.runTransaction((err, tx) => { + assert.ifError(err); + tx!.runUpdate(insertSql, (err, updateCount) => { + assert.ifError(err); + assert.strictEqual(updateCount, 1); + tx! + .commit() + .then(() => { + database + .close() + .then(() => done()) + .catch(err => done(err)); + }) + .catch(() => {}); + }); + }); + }); + + it('should not retry non-retryable error on update', done => { + const database = newTestDatabase(); + const err = { + message: 'Permanent error', + // We need to specify a non-retryable error code to prevent the entire + // transaction to retry. Not specifying an error code, will result in + // an error with code UNKNOWN, which again will retry the transaction. + code: grpc.status.INVALID_ARGUMENT, + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(err), + ); + let attempts = 0; + database.runTransaction((err, tx) => { + assert.ifError(err); + attempts++; + tx!.runUpdate(insertSql, err => { + assert.ok(err, 'Missing expected error'); + assert.deepStrictEqual( + (err as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + assert.strictEqual(err!.code, grpc.status.INVALID_ARGUMENT); + // Only the update RPC should be retried and not the entire + // transaction. + assert.strictEqual(attempts, 1); + tx! + .commit() + .then(() => { + database + .close() + .then(() => done()) + .catch(err => done(err)); + }) + .catch(done); + }); + }); + }); + + describe('LeaderAwareRouting', () => { + let spannerWithLARDisabled: Spanner; + let instanceWithLARDisabled: Instance; + + function newTestDatabaseWithLARDisabled( + options?: SessionPoolOptions, + queryOptions?: IQueryOptions, + ): Database { + return instanceWithLARDisabled.database( + `database-${dbCounter++}`, + options, + queryOptions, + ); + } + + before(() => { + spannerWithLARDisabled = new Spanner({ + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + routeToLeaderEnabled: false, + }); + // Gets a reference to a Cloud Spanner instance and database + instanceWithLARDisabled = spannerWithLARDisabled.instance('instance'); + }); + + it('should execute with leader aware routing enabled in a read/write transaction', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + await tx!.runUpdate({ + sql: insertSql, + }); + return await tx.commit(); + }); + await database.close(); + let metadataCountWithLAREnabled = 0; + spannerMock.getMetadata().forEach(metadata => { + if (metadata.get(LEADER_AWARE_ROUTING_HEADER)[0] !== undefined) { + metadataCountWithLAREnabled++; + assert.strictEqual( + metadata.get(LEADER_AWARE_ROUTING_HEADER)[0], + 'true', + ); + } + }); + assert.notStrictEqual(metadataCountWithLAREnabled, 0); + }); + + it('should execute with leader aware routing disabled in a read/write transaction', async () => { + const database = newTestDatabaseWithLARDisabled(); + await database.runTransactionAsync(async tx => { + await tx!.runUpdate({ + sql: insertSql, + }); + return await tx.commit(); + }); + await database.close(); + spannerMock.getMetadata().forEach(metadata => { + assert.strictEqual( + metadata.get(LEADER_AWARE_ROUTING_HEADER)[0], + undefined, + ); + }); + }); + }); + }); + + describe('read-only transactions', () => { + describe('when session mode is default for read-only', () => { + it('should make a request to CreateSession', async () => { + const database = newTestDatabase(); + await database.run('SELECT 1'); + const requests = spannerMock.getRequests().find(val => { + return (val as v1.CreateSessionRequest).session; + }) as v1.CreateSessionRequest; + assert.ok(requests, 'CreateSessionRequest should be called'); + assert.strictEqual( + requests.session?.multiplexed, + true, + 'Multiplexed should be true', + ); + }); + + it('should execute the transaction(database.run) successfully using multiplexed session', done => { + const query = { + sql: selectSql, + } as ExecuteSqlRequest; + const database = newTestDatabase(); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.run(query, (err, resp) => { + assert.strictEqual(pool._inventory.borrowed.size, 0); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.ifError(err); + assert.strictEqual(resp.length, 3); + done(); + }); + }); + + it('should execute the transaction(database.getSnapshot) successfully using multiplexed session', done => { + const database = newTestDatabase(); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.getSnapshot((err, resp) => { + assert.strictEqual(pool._inventory.borrowed.size, 0); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.ifError(err); + assert(resp instanceof Snapshot); + resp.end(); + done(); + }); + }); + + it('should execute the transaction(database.writeAtLeastOnce) successfully using multiplexed session', done => { + const database = newTestDatabase(); + const mutations = new MutationSet(); + mutations.upsert('Singers', { + SingerId: 1, + FirstName: 'Scarlet', + LastName: 'Terry', + }); + mutations.upsert('Singers', { + SingerId: 2, + FirstName: 'Marc', + }); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.writeAtLeastOnce(mutations, (err, resp) => { + assert.strictEqual(pool._inventory.borrowed.size, 0); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.ifError(err); + assert.strictEqual(typeof resp?.commitTimestamp?.nanos, 'number'); + assert.strictEqual(typeof resp?.commitTimestamp?.seconds, 'string'); + assert.strictEqual(resp?.commitStats, null); + done(); + }); + }); + + it('should fail the transaction, if multiplexed session creation is failed', async () => { + const query = { + sql: selectSql, + } as ExecuteSqlRequest; + const err = { + code: grpc.status.NOT_FOUND, + message: 'create session failed', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.createSession, + SimulatedExecutionTime.ofError(err), + ); + const database = newTestDatabase().on('error', err => { + assert.strictEqual(err.code, Status.NOT_FOUND); + }); + try { + await database.run(query); + } catch (error) { + assert.strictEqual((error as grpc.ServiceError).code, err.code); + assert.strictEqual( + (error as grpc.ServiceError).details, + 'create session failed', + ); + assert.strictEqual( + (error as grpc.ServiceError).message, + '5 NOT_FOUND: create session failed', + ); + } + }); + + it('should fail the transaction, if query returns session not found error', done => { + const query = { + sql: selectSql, + } as ExecuteSqlRequest; + const error = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError(error), + ); + const database = newTestDatabase(); + database.run(query, (err, _) => { + assert.strictEqual(err!.code, error.code); + assert.strictEqual(err!.details, error.message); + done(); + }); + }); + }); + + describe('when multiplexed session is disabled for read-only', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + it('should make a request to BatchCreateSessions', async () => { + const database = newTestDatabase(); + await database.run('SELECT 1'); + const requests = spannerMock.getRequests().find(val => { + return (val as v1.BatchCreateSessionsRequest).sessionTemplate; + }) as v1.BatchCreateSessionsRequest; + assert.ok(requests, 'BatchCreateSessionsRequest should be called'); + assert.strictEqual( + requests.sessionTemplate?.multiplexed, + false, + 'Multiplexed should be false', + ); + }); + + it('should execute the transaction(database.run) successfully using regular session', done => { + const query = { + sql: selectSql, + } as ExecuteSqlRequest; + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.run(query, (err, resp) => { + assert.ifError(err); + assert.strictEqual(pool._inventory.sessions.length, 1); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.strictEqual(resp.length, 3); + done(); + }); + }); + + it('should execute the transaction(database.getSnapshot) successfully using regular session', done => { + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.getSnapshot((err, resp) => { + assert.ifError(err); + assert.strictEqual(pool._inventory.borrowed.size, 1); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert(resp instanceof Snapshot); + resp.end(); + done(); + }); + }); + + it('should execute the transaction(database.writeAtLeastOnce) successfully using regular session', done => { + const database = newTestDatabase({min: 1, max: 1}); + const mutations = new MutationSet(); + mutations.upsert('Singers', { + SingerId: 1, + FirstName: 'Scarlet', + LastName: 'Terry', + }); + mutations.upsert('Singers', { + SingerId: 2, + FirstName: 'Marc', + }); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.writeAtLeastOnce(mutations, (err, resp) => { + assert.ifError(err); + assert.strictEqual(pool._inventory.borrowed.size, 1); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.strictEqual(typeof resp?.commitTimestamp?.nanos, 'number'); + assert.strictEqual(typeof resp?.commitTimestamp?.seconds, 'string'); + assert.strictEqual(resp?.commitStats, null); + done(); + }); + }); + }); + }); + + describe('partitioned ops', () => { + describe('default session mode for partitioned ops', () => { + it('should execute the transaction(database.runPartitionedUpdate) successfully using multiplexed session', done => { + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.runPartitionedUpdate({sql: updateSql}, (err, resp) => { + assert.strictEqual(pool._inventory.borrowed.size, 0); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.strictEqual(resp, 2); + assert.ifError(err); + done(); + }); + }); + }); + + describe('when only GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + + it('should execute the transaction(database.runPartitionedUpdate) successfully using multiplexed session', done => { + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.runPartitionedUpdate({sql: updateSql}, (err, resp) => { + assert.strictEqual(pool._inventory.borrowed.size, 0); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.strictEqual(resp, 2); + assert.ifError(err); + done(); + }); + }); + }); + + describe('when only GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS = + 'false'; + }); + + after(() => { + delete process.env + .GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS; + }); + + it('should execute the transaction(database.runPartitionedUpdate) successfully using multiplexed session', done => { + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.runPartitionedUpdate({sql: updateSql}, (err, resp) => { + assert.strictEqual(pool._inventory.borrowed.size, 0); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.strictEqual(resp, 2); + assert.ifError(err); + done(); + }); + }); + }); + + describe('when multiplexed session is disabled for partitioned ops', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS = + 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + delete process.env + .GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS; + }); + + it('should execute the transaction(database.runPartitionedUpdate) successfully using regular/pool session', done => { + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.runPartitionedUpdate({sql: updateSql}, (err, resp) => { + assert.ifError(err); + assert.strictEqual(pool._inventory.sessions.length, 1); + assert.strictEqual( + pool._inventory.sessions[0].metadata.multiplexed, + false, + ); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + assert.strictEqual(resp, 2); + done(); + }); + }); + }); + }); + + describe('batch write', () => { + describe('default session mode for r/w', () => { + it('should use multiplexed session', done => { + const mutationGroup = new MutationGroup(); + mutationGroup.upsert('FOO', { + Id: '1', + Name: 'One', + }); + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.commonHeaders_ = { + 'x-goog-spanner-request-id': `1.${randIdForProcess}.1.1.5.1`, + }; + database + .batchWriteAtLeastOnce([mutationGroup]) + .on('error', done) + .on('data', response => { + // ensure that response is coming + assert.notEqual(response.commitTimestamp, null); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + + // regular session will not get created since GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is not disabled + assert.strictEqual(pool._inventory.sessions.length, 0); + }) + .on('end', done); + }); + }); + + describe('when only GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + + it('should use multiplexed session', done => { + const mutationGroup = new MutationGroup(); + mutationGroup.upsert('FOO', { + Id: '1', + Name: 'One', + }); + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.commonHeaders_ = { + 'x-goog-spanner-request-id': `1.${randIdForProcess}.1.1.5.1`, + }; + database + .batchWriteAtLeastOnce([mutationGroup]) + .on('error', done) + .on('data', response => { + // ensure that response is coming + assert.notEqual(response.commitTimestamp, null); + // multiplexed session will get created by default during client initialization + assert.notEqual(multiplexedSession._multiplexedSession, null); + // session pool will not get created since GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is not false + assert.strictEqual(pool._inventory.sessions.length, 0); + }) + .on('end', done); + }); + }); + + describe('when only GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW; + }); + + it('should use multiplexed session', done => { + const mutationGroup = new MutationGroup(); + mutationGroup.upsert('FOO', { + Id: '1', + Name: 'One', + }); + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.commonHeaders_ = { + 'x-goog-spanner-request-id': `1.${randIdForProcess}.1.1.5.1`, + }; + database + .batchWriteAtLeastOnce([mutationGroup]) + .on('error', done) + .on('data', response => { + // ensure that response is not null + assert.notEqual(response.commitTimestamp, null); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + // session pool will not get created since GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS is not false + assert.strictEqual(pool._inventory.sessions.length, 0); + }) + .on('end', done); + }); + }); + + describe('when multiplexed session is disabled for r/w', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW; + }); + + it('should use regular session', done => { + const mutationGroup = new MutationGroup(); + mutationGroup.upsert('FOO', { + Id: '1', + Name: 'One', + }); + const database = newTestDatabase({min: 1, max: 1}); + const pool = (database.sessionFactory_ as SessionFactory) + .pool_ as SessionPool; + const multiplexedSession = (database.sessionFactory_ as SessionFactory) + .multiplexedSession_ as MultiplexedSession; + database.commonHeaders_ = { + 'x-goog-spanner-request-id': `1.${randIdForProcess}.1.1.5.1`, + }; + database + .batchWriteAtLeastOnce([mutationGroup]) + .on('error', done) + .on('data', response => { + // ensure that response is coming + assert.notEqual(response.commitTimestamp, null); + assert.strictEqual( + Array.from(pool._inventory.borrowed)[0].metadata.multiplexed, + false, + ); + assert.strictEqual(pool._inventory.borrowed.size, 1); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + }) + .on('end', done); + }); + }); + }); + + describe('queryOptions', () => { + /** Common verify method for QueryOptions tests. */ + function verifyQueryOptions( + optimizerVersion: string, + optimizerStatisticsPackage: string, + ) { + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.ok( + request.queryOptions, + 'no queryOptions found on ExecuteSqlRequest', + ); + assert.strictEqual( + request.queryOptions!.optimizerVersion, + optimizerVersion, + ); + assert.strictEqual( + request.queryOptions!.optimizerStatisticsPackage, + optimizerStatisticsPackage, + ); + } + + describe('on request', () => { + const OPTIMIZER_VERSION = '100'; + const OPTIMIZER_STATISTICS_PACKAGE = 'auto_20191128_14_47_22UTC'; + + it('database.run', async () => { + const query = { + sql: selectSql, + queryOptions: QueryOptions.create({ + optimizerVersion: OPTIMIZER_VERSION, + optimizerStatisticsPackage: OPTIMIZER_STATISTICS_PACKAGE, + }), + } as ExecuteSqlRequest; + const database = newTestDatabase(); + try { + await database.run(query); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + } finally { + await database.close(); + } + }); + + it('snapshot.run', async () => { + const query = { + sql: selectSql, + queryOptions: QueryOptions.create({ + optimizerVersion: OPTIMIZER_VERSION, + optimizerStatisticsPackage: OPTIMIZER_STATISTICS_PACKAGE, + }), + } as ExecuteSqlRequest; + const database = newTestDatabase(); + try { + const [snapshot] = await database.getSnapshot(); + await snapshot.run(query); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await snapshot.end(); + } finally { + await database.close(); + } + }); + + it('transaction.run', done => { + const query = { + sql: selectSql, + queryOptions: QueryOptions.create({ + optimizerVersion: OPTIMIZER_VERSION, + optimizerStatisticsPackage: OPTIMIZER_STATISTICS_PACKAGE, + }), + } as ExecuteSqlRequest; + const database = newTestDatabase(); + database.runTransaction(async (err, transaction) => { + assert.ifError(err); + await transaction!.run(query); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await transaction!.commit(); + await database.close(); + done(); + }); + }); + + it('async transaction.run', async () => { + const query = { + sql: selectSql, + queryOptions: QueryOptions.create({ + optimizerVersion: OPTIMIZER_VERSION, + optimizerStatisticsPackage: OPTIMIZER_STATISTICS_PACKAGE, + }), + } as ExecuteSqlRequest; + const database = newTestDatabase(); + try { + await database.runTransactionAsync(async transaction => { + await transaction.run(query); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await transaction.commit(); + }); + } finally { + await database.close(); + } + }); + }); + + describe('with environment variable', () => { + const OPTIMIZER_VERSION = '20'; + const OPTIMIZER_STATISTICS_PACKAGE = 'auto_20191128_14_47_22UTC'; + + let spannerWithEnvVar: Spanner; + let instanceWithEnvVar: Instance; + + function newTestDatabase( + options?: SessionPoolOptions, + queryOptions?: IQueryOptions, + ): Database { + return instanceWithEnvVar.database( + `database-${dbCounter++}`, + options, + queryOptions, + ); + } + + before(() => { + process.env.SPANNER_OPTIMIZER_VERSION = OPTIMIZER_VERSION; + process.env.SPANNER_OPTIMIZER_STATISTICS_PACKAGE = + OPTIMIZER_STATISTICS_PACKAGE; + spannerWithEnvVar = new Spanner({ + projectId: 'fake-project-id', + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + }); + // Gets a reference to a Cloud Spanner instance and database + instanceWithEnvVar = spannerWithEnvVar.instance('instance'); + }); + + after(() => { + delete process.env.SPANNER_OPTIMIZER_VERSION; + delete process.env.SPANNER_OPTIMIZER_STATISTICS_PACKAGE; + }); + + it('database.run', async () => { + const database = newTestDatabase(); + try { + await database.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + } finally { + await database.close(); + } + }); + + it('database.run with database-with-query-options', async () => { + // The options that are given in the database options will not be used + // as they are overridden by the environment variable. + const database = newTestDatabase(undefined, { + optimizerVersion: 'version-in-db-opts', + optimizerStatisticsPackage: 'stats-package-in-db-opts', + }); + try { + await database.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + } finally { + await database.close(); + } + }); + + it('database.run with query-options', async () => { + const database = newTestDatabase(); + try { + await database.run({ + sql: selectSql, + queryOptions: { + optimizerVersion: 'version-on-query', + optimizerStatisticsPackage: 'stats-package-on-query', + }, + }); + verifyQueryOptions('version-on-query', 'stats-package-on-query'); + } finally { + await database.close(); + } + }); + + it('snapshot.run', async () => { + const database = newTestDatabase(); + try { + const [snapshot] = await database.getSnapshot(); + await snapshot.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await snapshot.end(); + } finally { + await database.close(); + } + }); + + it('snapshot.run with query-options', async () => { + const database = newTestDatabase(); + try { + const [snapshot] = await database.getSnapshot(); + await snapshot.run({ + sql: selectSql, + queryOptions: { + optimizerVersion: 'version-on-query', + optimizerStatisticsPackage: 'stats-package-on-query', + }, + }); + verifyQueryOptions('version-on-query', 'stats-package-on-query'); + await snapshot.end(); + } finally { + await database.close(); + } + }); + + it('snapshot.run with database-with-query-options', async () => { + const database = newTestDatabase(undefined, { + optimizerVersion: 'version-in-db-opts', + optimizerStatisticsPackage: 'stats-package-in-db-opts', + }); + try { + const [snapshot] = await database.getSnapshot(); + await snapshot.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await snapshot.end(); + } finally { + await database.close(); + } + }); + + it('transaction.run', done => { + const database = newTestDatabase(); + database.runTransaction(async (err, transaction) => { + assert.ifError(err); + await transaction!.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await transaction!.commit(); + await database.close(); + done(); + }); + }); + + it('transaction.run with query-options', done => { + const database = newTestDatabase(); + database.runTransaction(async (err, transaction) => { + assert.ifError(err); + await transaction!.run({ + sql: selectSql, + queryOptions: { + optimizerVersion: 'version-on-query', + optimizerStatisticsPackage: 'stats-package-on-query', + }, + }); + verifyQueryOptions('version-on-query', 'stats-package-on-query'); + await transaction!.commit(); + await database.close(); + done(); + }); + }); + + it('transaction.run with database-with-query-options', done => { + const database = newTestDatabase(undefined, { + optimizerVersion: 'version-in-db-opts', + optimizerStatisticsPackage: 'stats-package-in-db-opts', + }); + database.runTransaction(async (err, transaction) => { + assert.ifError(err); + await transaction!.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await transaction!.commit(); + await database.close(); + done(); + }); + }); + + it('async transaction.run', async () => { + const database = newTestDatabase(); + try { + await database.runTransactionAsync(async transaction => { + await transaction.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await transaction.commit(); + }); + } finally { + await database.close(); + } + }); + + it('async transaction.run with query-options', async () => { + const database = newTestDatabase(); + try { + await database.runTransactionAsync(async transaction => { + await transaction.run({ + sql: selectSql, + queryOptions: { + optimizerVersion: 'version-on-query', + optimizerStatisticsPackage: 'stats-package-on-query', + }, + }); + verifyQueryOptions('version-on-query', 'stats-package-on-query'); + await transaction.commit(); + }); + } finally { + await database.close(); + } + }); + + it('async transaction.run with database-with-query-options', async () => { + const database = newTestDatabase(undefined, { + optimizerVersion: 'version-in-db-opts', + optimizerStatisticsPackage: 'stats-package-in-db-opts', + }); + try { + await database.runTransactionAsync(async transaction => { + await transaction.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await transaction.commit(); + }); + } finally { + await database.close(); + } + }); + }); + + describe('on database options', () => { + const OPTIMIZER_VERSION = '40'; + const OPTIMIZER_STATISTICS_PACKAGE = 'auto_20191128_14_47_22UTC'; + + // Request a database with default query options. + function newTestDatabase(options?: SessionPoolOptions): Database { + return instance.database(`database-${dbCounter++}`, options, { + optimizerVersion: OPTIMIZER_VERSION, + optimizerStatisticsPackage: OPTIMIZER_STATISTICS_PACKAGE, + } as IQueryOptions); + } + + it('database.run', async () => { + const database = newTestDatabase(); + try { + await database.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + } finally { + await database.close(); + } + }); + + it('snapshot.run', async () => { + const database = newTestDatabase(); + try { + const [snapshot] = await database.getSnapshot(); + await snapshot.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await snapshot.end(); + } finally { + await database.close(); + } + }); + + it('transaction.run', done => { + const database = newTestDatabase(); + database.runTransaction(async (err, transaction) => { + assert.ifError(err); + await transaction!.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await transaction!.commit(); + await database.close(); + done(); + }); + }); + + it('async transaction.run', async () => { + const database = newTestDatabase(); + try { + await database.runTransactionAsync(async transaction => { + await transaction.run(selectSql); + verifyQueryOptions(OPTIMIZER_VERSION, OPTIMIZER_STATISTICS_PACKAGE); + await transaction.commit(); + }); + } finally { + await database.close(); + } + }); + }); + }); + + describe('session-not-found', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS = + 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + delete process.env + .GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS; + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW; + }); + + it('should retry "Session not found" errors on Database.run()', done => { + const db = newTestDatabase({ + incStep: 1, + min: 0, + }); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + db.run(selectSql, (err, rows) => { + if (err) { + assert.fail(err); + } + assert.strictEqual(rows!.length, 3); + db.getSessions((err, results) => { + if (err) { + assert.fail(err); + } + // The mock server should have exactly 3 sessions. + // Two from session pool where, the first one was + // removed from the session pool because of the simulated + // 'Session not found' error. The second one was created by the retry. + // As we only simulate the 'Session not found' error, the first + // session is still present on the mock server. + // one session will be multiplexed session. + assert.strictEqual(results!.length, 3); + if (results!.length !== 3) { + done(); + } + db.close() + .then(() => done()) + .catch(err => assert.fail(err)); + }); + }); + }); + + it('should retry "Session not found" errors for Database.runStream()', () => { + const db = newTestDatabase(); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + let rowCount = 0; + db.runStream(selectSql) + .on('data', () => rowCount++) + .on('error', err => { + assert.fail(err); + }) + .on('end', () => { + assert.strictEqual(rowCount, 3); + }); + }); + + it('should retry multiple "Session not found" errors on Database.run()', done => { + const db = newTestDatabase(); + for (let i = 0; i < 10; i++) { + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + } + db.run(selectSql, (err, rows) => { + if (err) { + assert.fail(err); + } + assert.strictEqual(rows!.length, 3); + done(); + }); + }); + + it('should not retry "Session not found" errors halfway a stream', done => { + const db = newTestDatabase(); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + streamIndex: 1, + } as MockError), + ); + db.run(selectSql, err => { + if (err) { + assert.ok(isSessionNotFoundError(err)); + done(); + return; + } + assert.fail('Missing expected "Session not found" error'); + }); + }); + + it('should retry "Session not found" errors for Database.getSnapshot() with callbacks', done => { + const db = newTestDatabase(); + const sessionNotFound = { + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError; + // The beginTransaction call will fail 3 times with 'Session not found' + // before succeeding. + spannerMock.setExecutionTime( + spannerMock.beginTransaction, + SimulatedExecutionTime.ofErrors([ + sessionNotFound, + sessionNotFound, + sessionNotFound, + ]), + ); + db.getSnapshot((err, snapshot) => { + assert.ifError(err); + snapshot!.run(selectSql, (err, rows) => { + assert.ifError(err); + assert.strictEqual(rows.length, 3); + snapshot!.end(); + db.close(done); + }); + }); + }); + + it('should retry "Session not found" errors for a query on a session on Database.runTransaction()', done => { + const db = newTestDatabase({min: 1, incStep: 1}); + const pool = db.pool_ as SessionPool; + // Wait until one session with a transaction has been created. + pool.once('available', () => { + assert.strictEqual(pool.size, 1); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + runTransactionWithExpectedSessionRetry(db, done); + }); + }); + + function runTransactionWithExpectedSessionRetry(db: Database, done: Done) { + db.runTransaction((err, transaction) => { + assert.ifError(err); + transaction!.run(selectSql, (err, rows) => { + assert.ifError(err); + assert.strictEqual(rows.length, 3); + // Verify that the server has two sessions: The first one was marked + // as 'not found' by the client because of the mocked error, and a + // second one that was created as a result of the retry. + db.getSessions((err, sessions) => { + assert.ifError(err); + // sessions length is 3 as the list will contain default multiplexed session as well. + assert.strictEqual(sessions!.length, 3); + transaction!.commit(err => { + assert.ifError(err); + db.close(done); + }); + }); + }); + }); + } + + it('should retry "Session not found" errors for Commit on a session on Database.runTransaction()', done => { + const db = newTestDatabase({min: 1, incStep: 1}); + const pool = db.pool_ as SessionPool; + // Wait until one session with a transaction has been created. + pool.once('available', () => { + assert.strictEqual(pool.size, 1); + spannerMock.setExecutionTime( + spannerMock.commit, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + db.runTransaction((err, transaction) => { + assert.ifError(err); + transaction!.insert('FOO', {Id: 1, Name: 'foo'}); + transaction!.commit(err => { + assert.ifError(err); + db.getSessions((err, sessions) => { + assert.ifError(err); + // sessions length is 3 as the list will contain default multiplexed session as well. + assert.strictEqual(sessions!.length, 3); + db.close(done); + }); + }); + }); + }); + }); + + it('should retry "Session not found" errors for Database.getSnapshot()', done => { + const db = newTestDatabase(); + spannerMock.setExecutionTime( + spannerMock.beginTransaction, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + db.getSnapshot() + .then(response => { + const [snapshot] = response; + snapshot + .run(selectSql) + .then(response => { + const [rows] = response; + assert.strictEqual(rows.length, 3); + snapshot.end(); + db.close(done); + }) + .catch(done); + }) + .catch(done); + }); + + it('should retry "Session not found" errors for runUpdate on a session on Database.runTransaction()', done => { + const db = newTestDatabase({min: 1, incStep: 1}); + const pool = db.pool_ as SessionPool; + // Wait until one session with a transaction has been created. + pool.once('available', () => { + assert.strictEqual(pool.size, 1); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + db.runTransaction((err, transaction) => { + assert.ifError(err); + transaction!.runUpdate(insertSql, (err, updateCount) => { + assert.ifError(err); + assert.strictEqual(updateCount, 1); + transaction!.commit(err => { + assert.ifError(err); + db.getSessions((err, sessions) => { + assert.ifError(err); + // sessions length is 3 as the list will contain default multiplexed session as well. + assert.strictEqual(sessions!.length, 3); + db.close(done); + }); + }); + }); + }); + }); + }); + + it('should retry "Session not found" errors for executeBatchDml on a session on Database.runTransaction()', done => { + const db = newTestDatabase({min: 1, incStep: 1}); + const pool = db.pool_ as SessionPool; + // Wait until one session with a transaction has been created. + pool.once('available', () => { + assert.strictEqual(pool.size, 1); + spannerMock.setExecutionTime( + spannerMock.executeBatchDml, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + db.runTransaction((err, transaction) => { + assert.ifError(err); + transaction!.batchUpdate( + [insertSql, insertSql], + (err, updateCounts) => { + assert.ifError(err); + assert.deepStrictEqual(updateCounts, [1, 1]); + transaction!.commit(err => { + assert.ifError(err); + db.getSessions((err, sessions) => { + assert.ifError(err); + // sessions length is 3 as the list will contain default multiplexed session as well. + assert.strictEqual(sessions!.length, 3); + db.close(done); + }); + }); + }, + ); + }); + }); + }); + + it('should retry "Session not found" errors for a query on a session on Database.runTransactionAsync()', done => { + const db = newTestDatabase({min: 1, incStep: 1}); + const pool = db.pool_ as SessionPool; + // Wait until one session with a transaction has been created. + pool.once('available', () => { + assert.strictEqual(pool.size, 1); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + runAsyncTransactionWithExpectedSessionRetry(db).then(done).catch(done); + }); + }); + + async function runAsyncTransactionWithExpectedSessionRetry(db: Database) { + try { + await db.runTransactionAsync(async (transaction): Promise => { + try { + const [rows] = await transaction.run(selectSql); + assert.strictEqual(rows.length, 3); + const [sessions] = await db.getSessions(); + // sessions length is 3 as the list will contain default multiplexed session as well. + assert.strictEqual(sessions!.length, 3); + await transaction.commit(); + return Promise.resolve(); + } catch (e) { + return Promise.reject(e); + } + }); + await db.close(); + } catch (e) { + assert.fail(e as ServiceError); + } + } + + it('should retry "Session not found" errors for Commit on a session on Database.runTransactionAsync()', done => { + const db = newTestDatabase({min: 1, incStep: 1}); + const pool = db.pool_ as SessionPool; + // Wait until one session with a transaction has been created. + pool.once('available', async () => { + assert.strictEqual(pool.size, 1); + spannerMock.setExecutionTime( + spannerMock.commit, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + try { + await db + .runTransactionAsync(async (transaction): Promise => { + transaction.insert('FOO', {Id: 1, Name: 'foo'}); + await transaction.commit(); + const [sessions] = await db.getSessions(); + // sessions length is 3 as the list will contain default multiplexed session as well. + assert.strictEqual(sessions!.length, 3); + }) + .catch(assert.ifError); + await db.close(); + } catch (e) { + done(e); + return; + } + done(); + }); + }); + + it('should retry "Session not found" errors for runUpdate on a session on Database.runTransactionAsync()', done => { + const db = newTestDatabase({min: 1, incStep: 1}); + const pool = db.pool_ as SessionPool; + // Wait until one session with a transaction has been created. + pool.once('available', async () => { + assert.strictEqual(pool.size, 1); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + try { + await db + .runTransactionAsync(async (transaction): Promise => { + const [updateCount] = await transaction.runUpdate(insertSql); + assert.strictEqual(updateCount, 1); + await transaction.commit(); + const [sessions] = await db.getSessions(); + // sessions length is 3 as the list will contain default multiplexed session as well. + assert.strictEqual(sessions!.length, 3); + }) + .catch(assert.ifError); + await db.close(); + } catch (e) { + done(e); + return; + } + done(); + }); + }); + + it('should retry "Session not found" errors for executeBatchDml on a session on Database.runTransactionAsync()', done => { + const db = newTestDatabase({min: 1, incStep: 1}); + const pool = db.pool_ as SessionPool; + // Wait until one session with a transaction has been created. + pool.once('available', async () => { + assert.strictEqual(pool.size, 1); + spannerMock.setExecutionTime( + spannerMock.executeBatchDml, + SimulatedExecutionTime.ofError({ + code: grpc.status.NOT_FOUND, + message: 'Session not found', + } as MockError), + ); + try { + await db + .runTransactionAsync(async (transaction): Promise => { + const [updateCounts] = await transaction.batchUpdate([ + insertSql, + insertSql, + ]); + assert.deepStrictEqual(updateCounts, [1, 1]); + await transaction.commit(); + const [sessions] = await db.getSessions(); + // sessions length is 3 as the list will contain default multiplexed session as well. + assert.strictEqual(sessions!.length, 3); + }) + .catch(assert.ifError); + await db.close(); + } catch (e) { + done(e); + return; + } + done(); + }); + }); + }); + + describe('session-pool', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS = + 'false'; + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW = 'false'; + }); + + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + delete process.env + .GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_PARTITIONED_OPS; + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS_FOR_RW; + }); + + it('should execute table mutations without leaking sessions', async () => { + const database = newTestDatabase(); + try { + await database.table('foo').upsert({id: 1, name: 'bar'}); + } finally { + await database.close(); + } + }); + + it('should throw an error with a stacktrace when leaking a session', async () => { + await testLeakSession(); + }); + + async function testLeakSession() { + // The query to execute + const query = { + sql: selectSql, + }; + const db = newTestDatabase(); + await db + .getSnapshot({strong: true, returnReadTimestamp: true}) + .then(([tx]) => { + return tx.run(query); + }) + .then(([rows]) => { + // Assert that we get all results from the server. + assert.strictEqual(rows.length, 3); + // Note that we do not call transaction.end(). This will cause a session leak. + }) + .catch(reason => { + assert.fail(reason); + }); + await db + .close() + .then(() => { + assert.fail('Missing expected SessionLeakError'); + }) + .catch((reason: SessionLeakError) => { + assert.strictEqual(reason.name, 'SessionLeakError', reason); + assert.strictEqual(reason.messages.length, 1); + assert.ok(reason.messages[0].indexOf('testLeakSession') > -1); + }); + } + + it('should reuse sessions', async () => { + const database = newTestDatabase({incStep: 1, min: 0}); + try { + await verifyReadSessionReuse(database); + } finally { + await database.close(); + } + }); + + it('should reuse sessions when fail=true', async () => { + const db = newTestDatabase({ + min: 0, + max: 10, + incStep: 1, + concurrency: 5, + fail: true, + }); + try { + await verifyReadSessionReuse(db); + } finally { + await db.close(); + } + }); + + async function verifyReadSessionReuse(database: Database) { + // The query to execute + const query = { + sql: selectSql, + }; + const pool = database.pool_ as SessionPool; + let sessionId = ''; + for (let i = 0; i < 10; i++) { + const [rows] = await database.run(query); + assert.strictEqual(rows.length, 3); + rows.forEach(() => {}); + assert.strictEqual(pool.size, 1); + if (i > 0) { + assert.strictEqual(pool._inventory.sessions[0].id, sessionId); + } + sessionId = pool._inventory.sessions[0].id; + } + } + + it('should throw SessionPoolExhaustedError with stacktraces when pool is exhausted', async () => { + await testSessionPoolExhaustedError(); + }); + + async function testSessionPoolExhaustedError() { + const database = newTestDatabase({ + incStep: 1, + min: 0, + max: 1, + fail: true, + }); + try { + const [tx1] = await database.getSnapshot(); + try { + await database.getSnapshot(); + assert.fail('missing expected exception'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).name, + SessionPoolExhaustedError.name, + ); + const exhausted = e as SessionPoolExhaustedError; + assert.ok(exhausted.messages); + assert.strictEqual(exhausted.messages.length, 1); + assert.ok( + exhausted.messages[0].indexOf('testSessionPoolExhaustedError') > -1, + ); + } + tx1.end(); + } finally { + await database.close(); + } + } + + it('should reuse sessions after executing invalid sql', async () => { + // The query to execute + const requestIDRegex = new RegExp(`1.${randIdForProcess}.1.1.\\d+.1`); + const query = { + sql: invalidSql, + }; + const database = newTestDatabase({incStep: 1, min: 0}); + try { + const pool = database.pool_ as SessionPool; + for (let i = 0; i < 10; i++) { + try { + const [rows] = await database.run(query); + assert.fail(`missing expected exception, got ${rows.length} rows`); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + `${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`, + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID.match(requestIDRegex) !== null, + true, + ); + } + } + assert.strictEqual(pool.size, 1); + } finally { + await database.close(); + } + }); + + it('should reuse sessions after executing streaming sql', async () => { + // The query to execute + const query = { + sql: selectSql, + }; + const database = newTestDatabase({incStep: 1, min: 0}); + try { + const pool = database.pool_ as SessionPool; + for (let i = 0; i < 10; i++) { + const rowCount = await getRowCountFromStreamingSql(database, query); + assert.strictEqual(rowCount, 3); + } + assert.strictEqual(pool.size, 1); + } finally { + await database.close(); + } + }); + + it('should reuse sessions after executing an invalid streaming sql', async () => { + // The query to execute + const requestIDRegex = new RegExp(`1.${randIdForProcess}.1.1.\\d+.1`); + const query = { + sql: invalidSql, + }; + const database = newTestDatabase({incStep: 1, min: 0}); + try { + const pool = database.pool_ as SessionPool; + for (let i = 0; i < 10; i++) { + try { + const rowCount = await getRowCountFromStreamingSql(database, query); + assert.fail(`missing expected exception, got ${rowCount}`); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + `${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`, + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID.match(requestIDRegex) !== null, + true, + ); + } + } + assert.strictEqual(pool.size, 1); + } finally { + await database.close(); + } + }); + + it('should reuse write sessions', async () => { + const database = newTestDatabase({incStep: 1, min: 0}); + try { + await verifyWriteSessionReuse(database); + } finally { + await database.close(); + } + }); + + it('should reuse write sessions when fail=true', async () => { + const db = newTestDatabase({ + min: 0, + max: 10, + incStep: 1, + concurrency: 5, + fail: true, + }); + try { + await verifyWriteSessionReuse(db); + } finally { + await db.close(); + } + }); + + async function verifyWriteSessionReuse(database: Database) { + const update = { + sql: insertSql, + }; + const pool = database.pool_ as SessionPool; + for (let i = 0; i < 10; i++) { + await executeSimpleUpdate(database, update); + // The pool should not contain more sessions than the number of transactions that we have executed. + // The exact number depends on the time needed to prepare new transactions, as checking in a read/write + // transaction to the pool will cause the session to be prepared with a read/write transaction before it is added + // to the list of available sessions. + assert.ok(pool.size <= i + 1); + } + } + + it('should re-use write session as read-session', async () => { + const database = newTestDatabase({incStep: 1, max: 1}); + const pool = database.pool_ as SessionPool; + try { + // Execute a simple read/write transaction to create 1 write session. + const w = executeSimpleUpdate(database, updateSql); + const r = database.run(selectSql); + await Promise.all([w, r]); + assert.strictEqual(pool.size, 1); + } finally { + await database.close(); + } + }); + + it('should fail on session pool exhaustion and fail=true', async () => { + const database = newTestDatabase({ + max: 1, + incStep: 1, + fail: true, + }); + let tx1; + try { + try { + [tx1] = await database.getSnapshot(); + await database.getSnapshot(); + assert.fail('missing expected exception'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + 'No resources available.', + ); + } + } finally { + if (tx1) { + tx1.end(); + } + await database.close(); + } + }); + + it('should pre-fill session pool', async () => { + const database = newTestDatabase({ + min: 100, + max: 200, + }); + const pool = database.pool_ as SessionPool; + const expectedAmount = pool.options.min!; + assert.strictEqual(pool.size, expectedAmount); + // Wait until all sessions have been created and prepared. + const started = new Date().getTime(); + while ( + pool._inventory.sessions.length < expectedAmount && + new Date().getTime() - started < 1000 + ) { + await sleep(1); + } + await database.close(); + }); + + it('should use pre-filled session pool', async () => { + const database = newTestDatabase({ + min: 100, + max: 200, + }); + const pool = database.pool_ as SessionPool; + const expectedAmount = pool.options.min!; + // Start executing a query. This query should use one of the sessions that + // has been pre-filled into the pool. + const [rows] = await database.run(selectSql); + assert.strictEqual(rows.length, 3); + // Wait until all sessions have been created and prepared. + const started = new Date().getTime(); + while ( + pool._inventory.sessions.length < expectedAmount && + new Date().getTime() - started < 1000 + ) { + await sleep(1); + } + assert.strictEqual(pool.size, expectedAmount); + assert.strictEqual(pool._inventory.sessions.length, expectedAmount); + await database.close(); + }); + + it('should propagate database not found errors', async () => { + spannerMock.setExecutionTime( + spannerMock.batchCreateSessions, + // Two errors; one for the initial _fill of the session pool, and one + // for the query. + SimulatedExecutionTime.ofErrors([ + { + code: Status.NOT_FOUND, + message: 'Database not found', + }, + { + code: Status.NOT_FOUND, + message: 'Database not found', + }, + ] as MockError[]), + ); + const database = newTestDatabase(); + try { + await database.run(selectSql); + assert.fail('missing expected error'); + } catch (err) { + assert.strictEqual((err as ServiceError).code, Status.NOT_FOUND); + } finally { + await database.close(); + } + }); + + it('should not propagate instance and database not found errors for SessionPoolOptions.min > 0', async () => { + for (const msg of ['Instance not found', 'Database not found']) { + spannerMock.setExecutionTime( + spannerMock.batchCreateSessions, + SimulatedExecutionTime.ofErrors([ + { + code: Status.NOT_FOUND, + message: msg, + }, + ] as MockError[]), + ); + try { + const database = newTestDatabase({ + incStep: 1, + min: 25, + max: 400, + }); + const response = await database.create(); + assert.ok(response); + const [rows] = await database.run(selectSql); + assert.strictEqual(rows.length, 3); + // Make sure the pool of the newly created database is filled. + const pool = database.pool_ as SessionPool; + assert.strictEqual(pool.size, 25); + await database.close(); + } catch (err) { + assert.fail(err as ServiceError); + } + } + }); + + it('should propagate permission denied errors on initialization', async () => { + spannerMock.setExecutionTime( + spannerMock.batchCreateSessions, + SimulatedExecutionTime.ofErrors([ + { + code: Status.PERMISSION_DENIED, + message: 'Needs permission', + }, + { + code: Status.PERMISSION_DENIED, + message: 'Needs permission', + }, + ] as MockError[]), + ); + const database = newTestDatabase().on('error', err => { + assert.strictEqual(err.code, Status.PERMISSION_DENIED); + }); + try { + await database.run(selectSql); + assert.fail('missing expected error'); + } catch (err) { + assert.strictEqual( + (err as ServiceError).code, + Status.PERMISSION_DENIED, + ); + } finally { + await database.close(); + } + }); + + it('should create new session when numWaiters >= pending', async () => { + const database = newTestDatabase({ + min: 1, + max: 10, + incStep: 1, + }); + const pool = database.pool_ as SessionPool; + // Start executing a query. This query should use the one session that is + // being pre-filled into the pool. + const promise1 = database.run(selectSql); + // Start executing another query. This query should initiate the creation + // of a new session. + const promise2 = database.run(selectSql); + const rows = await Promise.all([promise1, promise2]); + assert.strictEqual(pool.size, 2); + assert.strictEqual(rows[0][0].length, 3); + assert.strictEqual(rows[1][0].length, 3); + await database.close(); + }); + + it('should respect options.incStep', async () => { + const database = newTestDatabase({ + min: 100, + max: 400, + incStep: 25, + }); + const pool = database.pool_ as SessionPool; + assert.strictEqual(pool.size, pool.options.min); + // Request options.min + 1 sessions. + const snapshots: Snapshot[] = []; + for (let i = 0; i < pool.options.min! + 1; i++) { + const [snapshot] = await database.getSnapshot(); + snapshots.unshift(snapshot); + } + // The pool should create a batch of sessions. + assert.strictEqual(pool.size, pool.options.min! + pool.options.incStep!); + for (const s of snapshots) { + s.end(); + } + await database.close(); + }); + + it('should respect options.max', async () => { + const database = newTestDatabase({ + min: 0, + max: 3, + incStep: 2, + }); + const pool = database.pool_ as SessionPool; + const [tx1] = await database.getSnapshot(); + assert.strictEqual(pool.size, pool.options.incStep); + const [tx2] = await database.getSnapshot(); + const [tx3] = await database.getSnapshot(); + assert.strictEqual(pool.size, pool.options.max); + tx1.end(); + tx2.end(); + tx3.end(); + await database.close(); + }); + + it('should respect options.max when a write session is requested', async () => { + const database = newTestDatabase({ + min: 0, + max: 3, + incStep: 2, + }); + const pool = database.pool_ as SessionPool; + const [tx1] = await database.getSnapshot(); + const [tx2] = await database.getSnapshot(); + assert.strictEqual(pool.size, pool.options.incStep); + await database.runTransactionAsync(async tx => { + if (!tx) { + assert.fail('Transaction failed'); + } + await tx.runUpdate(updateSql); + await tx.commit(); + }); + assert.strictEqual(pool.size, pool.options.max); + tx1.end(); + tx2.end(); + await database.close(); + }); + }); + + describe('multiplexed-session', () => { + it('should recover from a failed session creation when idle (Deadlock Fix)', async () => { + const err = { + code: grpc.status.INTERNAL, // Use a non-retryable error to force failures + message: 'Simulated failure', + } as MockError; + // Mock Setup: + // 1st createSession call -> FAILS (Simulates network blip) + // 2nd createSession call -> SUCCEEDS (Default behavior) + spannerMock.setExecutionTime( + spannerMock.createSession, + SimulatedExecutionTime.ofErrors([err]), + ); + + const database = newTestDatabase(); + + // Attempt 1: Should fail + try { + await database.getSnapshot(); + assert.fail('First request should have failed'); + } catch (e) { + // we expect this to fail and catch it so the test continues + assert.strictEqual((e as ServiceError).code, grpc.status.INTERNAL); + } + // Attempt 2: Should trigger a new createSession call + // The lazy loader sees _sharedMuxSessionWaitPromise is null, so it retries. + const [snapshot] = await database.getSnapshot(); + assert.ok( + snapshot, + 'Should have successfully acquired a session on retry', + ); + snapshot.end(); + await database.close(); + // Filter for CreateSession requests specifically. + const request = spannerMock.getRequests().filter(val => { + return (val as v1.CreateSessionRequest).session?.multiplexed; + }) as v1.CreateSessionRequest[]; + + // Assert that we tried to create the session exactly twice + // 1st attempt: Failed (Simulated Error) + // 2nd attempt: Succeeded (Retry) + assert.strictEqual(request.length, 2); + }); + + it('should share a single session creation promise among concurrent requests (Initialization Race)', async () => { + // This guarantees that the very first request to createSession (from constructor) gets delayed. + spannerMock.setExecutionTime( + spannerMock.createSession, + SimulatedExecutionTime.ofMinAndRandomExecTime(100, 0), + ); + + // this request is now stuck pending for 100ms (because of above delay). + const database = newTestDatabase(); + + // fire multiple concurrent requests immediately, while Request 1 is still pending + // This forces them to hit the "Join Existing Promise" logic. + const promises: Promise<[Snapshot]>[] = []; + for (let i = 0; i < 10; i++) { + promises.push(database.getSnapshot()); + } + + // await all of them + const snapshots = await Promise.all(promises); + + // assert all requests succeeded + assert.strictEqual(snapshots.length, 10); + snapshots.forEach(([snapshot]) => snapshot.end()); + + // assert there was only one CreateSession request was sent + const request = spannerMock.getRequests().filter(val => { + return (val as v1.CreateSessionRequest).session?.multiplexed; + }) as v1.CreateSessionRequest[]; + + // the CreateSessionRequest should be 1, if the shared promise is working fine + assert.strictEqual( + request.length, + 1, + 'Should have only created one session for all requests', + ); + + await database.close(); + }); + + it('should retry only once shared across concurrent requests after an initial failure', async () => { + const err = { + code: grpc.status.INTERNAL, // Use a non-retryable error to force failures + message: 'Simulated failure', + } as MockError; + + // Mock: Delay 50ms per call, fail next 2 requests (Startup + Retry) + spannerMock.setExecutionTime(spannerMock.createSession, { + simulateExecutionTime: async () => { + await new Promise(resolve => setTimeout(resolve, 50)); + }, + errors: [err, err], + } as any); + + // Trigger initial session creation (fails due to mock setup) + const database = newTestDatabase(); + + // wait to ensure 1st request finishes and locks are cleared + await new Promise(resolve => setTimeout(resolve, 100)); + + // Trigger Concurrent RPCs (The Retry) + // Now that we are idle, these 3 requests will trigger a retry. + // They should ALL fail, but they should share ONE retry request. + const rpcPromises = [ + database.getSnapshot(), + database.getSnapshot(), + database.getSnapshot(), + ]; + + // Verify Failure + // We expect all of them to reject with the simulated error + await assert.rejects(rpcPromises[0], /Simulated failure/); + await assert.rejects(rpcPromises[1], /Simulated failure/); + await assert.rejects(rpcPromises[2], /Simulated failure/); + + // Verify exactly 2 create session request + const request = spannerMock.getRequests().filter(val => { + return (val as v1.CreateSessionRequest).session?.multiplexed; + }) as v1.CreateSessionRequest[]; + + assert.strictEqual( + request.length, + 2, + 'Should have attempted exactly 2 creations (1 startup + 1 shared retry)', + ); + + await database.close(); + }); + + it('should propagate a single delayed failure to all concurrent listeners without spawning duplicate requests', async () => { + const err = { + code: grpc.status.INTERNAL, // Use a non-retryable error to force failures + message: 'Simulated failure', + } as MockError; + + // Mock: Delay 50ms to keep request pending, then fail + spannerMock.setExecutionTime(spannerMock.createSession, { + simulateExecutionTime: async () => { + await new Promise(resolve => setTimeout(resolve, 50)); + }, + errors: [err], + } as any); + + // Trigger Initialization + const database = newTestDatabase(); + + // Fire 3 RPCs immediately. They should join the pending initialization promise + const rpcPromises = [ + database.getSnapshot(), + database.getSnapshot(), + database.getSnapshot(), + ]; + // Verify Failure + // We expect all of them to reject with the simulated error + await assert.rejects(rpcPromises[0], /Simulated failure/); + await assert.rejects(rpcPromises[1], /Simulated failure/); + await assert.rejects(rpcPromises[2], /Simulated failure/); + + // Verify exactly 1 create session request + const request = spannerMock.getRequests().filter(val => { + return (val as v1.CreateSessionRequest).session?.multiplexed; + }) as v1.CreateSessionRequest[]; + + assert.strictEqual( + request.length, + 1, + 'Should have attempted exactly 2 creations (1 startup + 1 shared retry)', + ); + + await database.close(); + }); + }); + + describe('transaction', () => { + it('should retry on aborted query', async () => { + let attempts = 0; + const database = newTestDatabase(); + const rowCount = await database.runTransactionAsync( + (transaction): Promise => { + if (!attempts) { + spannerMock.abortTransaction(transaction); + } + attempts++; + return transaction.run(selectSql).then(([rows]) => { + let count = 0; + rows.forEach(() => count++); + return transaction.commit().then(() => count); + }); + }, + ); + assert.strictEqual(rowCount, 3); + assert.strictEqual(attempts, 2); + await database.close(); + }); + + it('should retry on aborted query with callback', done => { + let attempts = 0; + const database = newTestDatabase(); + let rowCount = 0; + database.runTransaction((err, transaction) => { + assert.ifError(err); + if (!attempts) { + spannerMock.abortTransaction(transaction!); + } + attempts++; + transaction!.run(selectSql, (err, rows) => { + assert.ifError(err); + rows.forEach(() => rowCount++); + assert.strictEqual(rowCount, 3); + assert.strictEqual(attempts, 2); + transaction! + .commit() + .then(() => { + database + .close() + .then(() => done()) + .catch(err => done(err)); + }) + .catch(err => done(err)); + }); + }); + }); + + it('should retry on aborted when running parallel query', async () => { + let attempts = 0; + const database = newTestDatabase(); + const rowCount = await database.runTransactionAsync( + (transaction): Promise => { + if (!attempts) { + spannerMock.abortTransaction(transaction); + } + attempts++; + return Promise.all([ + transaction!.run(selectSql), + transaction!.run(selectSql), + ]).then(([rows1, rows2]) => { + assert.strictEqual(rows1.length, 3); + assert.strictEqual(rows2.length, 3); + return transaction.commit().then(() => rows1.length + rows2.length); + }); + }, + ); + assert.strictEqual(rowCount, 6); + assert.strictEqual(attempts, 2); + const requests = spannerMock + .getRequests() + .filter(val => { + return (val as v1.ExecuteSqlRequest).sql === selectSql; + }) + .map(req => req as v1.ExecuteSqlRequest); + + // First request will fail and second blocked request will get discarded, once Abort error is received. + assert.strictEqual(requests.length, 3); + assert.ok( + requests[0].transaction?.begin!.readWrite, + 'Inline txn is not set in request.', + ); + requests.slice(1, 3).forEach((request, index) => { + assert.ok( + request.transaction!.id, + `Transaction ID is not used for retries. ${index}.`, + ); + }); + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + const commitRequests = spannerMock + .getRequests() + .filter(val => (val as v1.CommitRequest).mutations) + .map(req => req as v1.CommitRequest); + assert.strictEqual(commitRequests.length, 1); + await database.close(); + }); + + it('should retry on aborted update statement', async () => { + let attempts = 0; + const database = newTestDatabase(); + const [updated] = await database.runTransactionAsync( + (transaction): Promise => { + if (!attempts) { + spannerMock.abortTransaction(transaction); + } + attempts++; + return transaction + .runUpdate(insertSql) + .then(updateCount => transaction.commit().then(() => updateCount)); + }, + ); + assert.strictEqual(updated, 1); + assert.strictEqual(attempts, 2); + await database.close(); + }); + + it('should retry on aborted update statement with callback', done => { + let attempts = 0; + const database = newTestDatabase(); + database.runTransaction((err, transaction) => { + assert.ifError(err); + if (!attempts) { + spannerMock.abortTransaction(transaction!); + } + attempts++; + transaction!.runUpdate(insertSql, (err, rowCount) => { + assert.ifError(err); + transaction!.commit(err => { + assert.ifError(err); + assert.strictEqual(rowCount, 1); + assert.strictEqual(attempts, 2); + database + .close() + .then(() => done()) + .catch(err => done(err)); + }); + }); + }); + }); + + it('should retry on aborted batch DML statement', async () => { + let attempts = 0; + const database = newTestDatabase(); + spannerMock.setExecutionTime( + spannerMock.executeBatchDml, + SimulatedExecutionTime.ofError({ + code: grpc.status.ABORTED, + message: 'Transaction aborted', + metadata: MockSpanner.createMinimalRetryDelayMetadata(), + streamIndex: 1, + } as MockError), + ); + const response = await database.runTransactionAsync(transaction => { + attempts++; + return transaction + .batchUpdate([insertSql, updateSql]) + .then(response => transaction.commit().then(() => response)); + }); + const updateCounts = response[0]; + assert.deepStrictEqual(updateCounts, [1, 2]); + assert.strictEqual(attempts, 2); + await database.close(); + }); + + it('should retry on aborted commit', async () => { + let attempts = 0; + const database = newTestDatabase(); + const [updated] = await database.runTransactionAsync( + (transaction): Promise => { + void transaction.begin(); + return transaction.runUpdate(insertSql).then(updateCount => { + if (!attempts) { + spannerMock.abortTransaction(transaction); + } + attempts++; + return transaction.commit().then(() => updateCount); + }); + }, + ); + assert.strictEqual(updated, 1); + assert.strictEqual(attempts, 2); + await database.close(); + }); + + it('should throw DeadlineError', async () => { + let attempts = 0; + const database = newTestDatabase(); + try { + await database.runTransactionAsync( + {timeout: 1}, + (transaction): Promise => { + void transaction.begin(); + attempts++; + return transaction.runUpdate(insertSql).then(updateCount => { + // Always abort the transaction. + spannerMock.abortTransaction(transaction); + return transaction.commit().then(() => updateCount); + }); + }, + ); + assert.fail('missing expected DEADLINE_EXCEEDED error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).code, + grpc.status.DEADLINE_EXCEEDED, + `Got unexpected error ${e} with code ${(e as ServiceError).code}`, + ); + // The transaction should be tried at least once before timing out. + assert.ok(attempts >= 1); + } + await database.close(); + }); + + it('should retry on internal error', async () => { + let attempts = 0; + const database = newTestDatabase(); + + const [updated] = await database.runTransactionAsync( + (transaction): Promise => { + void transaction.begin(); + return transaction.runUpdate(insertSql).then(updateCount => { + if (!attempts) { + spannerMock.setExecutionTime( + spannerMock.commit, + SimulatedExecutionTime.ofError({ + code: grpc.status.INTERNAL, + message: 'Received RST_STREAM', + } as MockError), + ); + } + attempts++; + return transaction.commit().then(() => updateCount); + }); + }, + ); + assert.strictEqual(updated, 1); + assert.strictEqual(attempts, 2); + + await database.close(); + }); + + describe('batch-readonly-transaction', () => { + describe('when multiplexed session is disabled', () => { + before(() => { + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + }); + after(() => { + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + }); + it('should use session from pool', async () => { + const database = newTestDatabase({min: 0, incStep: 1}); + const pool = database.pool_ as SessionPool; + assert.strictEqual(pool.size, 0); + const [transaction] = await database.createBatchTransaction(); + assert.strictEqual(pool.size, 1); + assert.strictEqual(pool.available, 0); + transaction.close(); + await database.close(); + }); + it('failing to close transaction should cause session leak error', async () => { + const database = newTestDatabase(); + await database.createBatchTransaction(); + try { + await database.close(); + assert.fail('missing expected session leak error'); + } catch (err) { + assert.ok(err instanceof SessionLeakError); + } + }); + }); + + describe('when session mode is default', () => { + it('should use multiplexed session', async () => { + const database = newTestDatabase({min: 0, incStep: 1}); + const pool = database.pool_ as SessionPool; + const multiplexedSession = ( + database.sessionFactory_ as SessionFactory + ).multiplexedSession_ as MultiplexedSession; + // pool is empty before call to createBatchTransaction + assert.strictEqual(pool.size, 0); + const [transaction] = await database.createBatchTransaction(); + // pool is empty after call to createBatchTransaction + assert.strictEqual(pool.size, 0); + // multiplexed session will get created by default + assert.notEqual(multiplexedSession._multiplexedSession, null); + transaction.close(); + await database.close(); + }); + }); + }); + + describe('batch-transactions', () => { + describe('createReadPartitions', () => { + it('should create set of read partitions', async () => { + const database = newTestDatabase({min: 0, incStep: 1}); + const query = { + table: 'abc', + keys: ['a', 'b'], + ranges: [{}, {}], + gaxOptions: {}, + dataBoostEnabled: true, + }; + const [transaction] = await database.createBatchTransaction(); + const [readPartitions] = + await transaction.createReadPartitions(query); + assert.strictEqual(readPartitions.length, 1); + assert.strictEqual(readPartitions[0].table, 'abc'); + }); + }); + + describe('createQueryPartitions', () => { + it('should create set of query partitions', async () => { + const database = newTestDatabase({min: 0, incStep: 1}); + const query = { + sql: select1, + }; + const [transaction] = await database.createBatchTransaction(); + const [queryPartitions] = + await transaction.createQueryPartitions(query); + assert.strictEqual(Object.keys(queryPartitions).length, 1); + assert.strictEqual(queryPartitions[0].sql, select1); + transaction.close(); + await database.close(); + }); + }); + + describe('execute', () => { + it('should create and execute query partitions', async () => { + const database = newTestDatabase({min: 0, incStep: 1}); + const [transaction] = await database.createBatchTransaction(); + const [queryPartitions] = + await transaction.createQueryPartitions(selectSql); + assert.strictEqual(queryPartitions.length, 1); + const [resp] = await transaction.execute(queryPartitions[0]); + assert.strictEqual(resp.length, 3); + }); + + it('should create and execute read partitions', async () => { + const database = newTestDatabase({min: 0, incStep: 1}); + const [transaction] = await database.createBatchTransaction(); + const [readPartitions] = + await transaction.createReadPartitions(readPartitionsQuery); + assert.strictEqual(readPartitions.length, 1); + const [resp] = await transaction.execute(readPartitions[0]); + assert.strictEqual(resp.length, 3); + }); + }); + }); + + describe('pdml', () => { + it('should retry on aborted error', async () => { + const database = newTestDatabase(); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.ABORTED, + message: 'Transaction aborted', + metadata: MockSpanner.createMinimalRetryDelayMetadata(), + streamIndex: 1, + } as MockError), + ); + const [updateCount] = await database.runPartitionedUpdate(updateSql); + assert.strictEqual(updateCount, 2); + await database.close(); + }); + + it('should retry on specific internal error', async () => { + const database = newTestDatabase(); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.INTERNAL, + message: 'Received unexpected EOS on DATA frame from server', + streamIndex: 1, + } as MockError), + ); + const [updateCount] = await database.runPartitionedUpdate(updateSql); + assert.strictEqual(updateCount, 2); + await database.close(); + }); + + it('should fail on generic internal error', async () => { + const database = newTestDatabase(); + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofError({ + code: grpc.status.INTERNAL, + message: 'Generic internal error', + streamIndex: 1, + } as MockError), + ); + try { + await database.runPartitionedUpdate(updateSql); + assert.fail('missing expected INTERNAL error'); + } catch (err) { + assert.strictEqual((err as ServiceError).code, grpc.status.INTERNAL); + assert.ok( + (err as ServiceError).message.includes('Generic internal error'), + ); + assert.deepStrictEqual( + (err as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.3.1`, + ); + } finally { + await database.close(); + } + }); + + it('should use request options', async () => { + const database = newTestDatabase(); + await database.runPartitionedUpdate({ + sql: updateSql, + requestOptions: { + priority: Priority.PRIORITY_LOW, + requestTag: 'request-tag', + }, + }); + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on ExecuteSqlRequest', + ); + assert.strictEqual(request.requestOptions!.priority, 'PRIORITY_LOW'); + assert.strictEqual(request.requestOptions!.requestTag, 'request-tag'); + await database.close(); + }); + + it('should use excludeTxnFromChangeStreams', async () => { + const database = newTestDatabase(); + await database.runPartitionedUpdate({ + sql: updateSql, + excludeTxnFromChangeStreams: true, + }); + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options + ?.excludeTxnFromChangeStreams; + }) as v1.BeginTransactionRequest; + assert.strictEqual( + beginTxnRequest.options?.excludeTxnFromChangeStreams, + true, + ); + await database.close(); + }); + }); + + // tests for mutation key heuristics, lock order prevention and commit retry protocol + // test(s) for mutation key heuristic + describe('should be able to select correct mutation key in case of mutation(s) only transaction(s)', () => { + it('should select the insertOrUpdate(upsert)/delete(deleteRows) mutation key over insert', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + tx.upsert('foo', [ + {id: 1, name: 'One'}, + {id: 2, name: 'Two'}, + ]); + tx.insert('foo', [{id: 3, name: 'Three'}]); + tx.insert('foo', [{id: 4, name: 'Four'}]); + tx.deleteRows('foo', ['3', '4']); + await tx.commit(); + }); + + const beginTransactionRequest = spannerMock + .getRequests() + .filter(val => { + return (val as v1.BeginTransactionRequest).mutationKey; + }) as v1.BeginTransactionRequest[]; + + // assert on begin transaction request + assert.strictEqual(beginTransactionRequest.length, 1); + + // selected mutation key + const selectedMutationKey = beginTransactionRequest[0]!.mutationKey; + + // assert that mutation key have been selected + assert.ok( + selectedMutationKey, + 'A mutation key should have been selected', + ); + + // get the type of mutation key + const mutationType = Object.keys(selectedMutationKey!)[0]; + + // assert that mutation key is either insertOrUpdate or delete + assert.ok( + ['insertOrUpdate', 'delete'].includes(mutationType), + "Expected either 'insertOrUpdate' or 'delete' key.", + ); + + const commitRequest = spannerMock.getRequests().filter(val => { + return (val as v1.CommitRequest).precommitToken; + }) as v1.CommitRequest[]; + + // assert on commit request + assert.strictEqual(commitRequest.length, 1); + await database.close(); + }); + + it('should select the mutation key with highest number of values when insert key(s) are present', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + tx.insert('foo', [ + {id: randomUUID(), name: 'One'}, + {id: randomUUID(), name: 'Two'}, + {id: randomUUID(), name: 'Three'}, + ]); + tx.insert('foo', {id: randomUUID(), name: 'Four'}); + await tx.commit(); + }); + + const beginTransactionRequest = spannerMock + .getRequests() + .filter(val => { + return (val as v1.BeginTransactionRequest).mutationKey; + }) as v1.BeginTransactionRequest[]; + + // assert on begin transaction request + assert.strictEqual(beginTransactionRequest.length, 1); + + // selected mutation key + const selectedMutationKey = beginTransactionRequest[0]!.mutationKey; + + // assert that mutation key have been selected + assert.ok( + selectedMutationKey, + 'A mutation key should have been selected', + ); + + // assert that mutation key is insert + const mutationType = Object.keys(selectedMutationKey!)[0]; + assert.ok( + ['insert'].includes(mutationType), + 'insert key must have been selected', + ); + + // assert that insert mutation key with highest number of rows has been selected + assert.strictEqual(selectedMutationKey.insert?.values?.length, 3); + + const commitRequest = spannerMock.getRequests().filter(val => { + return (val as v1.CommitRequest).precommitToken; + }) as v1.CommitRequest[]; + + // assert on commit request + assert.strictEqual(commitRequest.length, 1); + await database.close(); + }); + }); + + // test(s) for lock order prevention + describe('should be able to track multiplexedSessionPreviousTransactionId in case of abort transactions and retries', () => { + describe('using runTransaction', () => { + it('case 1: transaction abortion on first query execution', async () => { + let attempts = 0; + let rowCount = 0; + const database = newTestDatabase(); + const transactionObjects: Transaction[] = []; + try { + await new Promise((resolve, reject) => { + database.runTransaction(async (err, transaction) => { + try { + if (err) { + return reject(err); + } + transactionObjects.push(transaction!); + if (!attempts) { + // abort the transaction + spannerMock.abortTransaction(transaction!); + } + attempts++; + const [rows1] = await transaction!.run(selectSql); + rows1.forEach(() => rowCount++); + + // assert on number of rows + assert.strictEqual(rowCount, 3); + + // assert on number of retries + assert.strictEqual(attempts, 2); + + const beginTxnRequest = spannerMock + .getRequests() + .find(val => { + return (val as v1.BeginTransactionRequest).options + ?.readWrite; + }) as v1.BeginTransactionRequest; + + const txnId = + beginTxnRequest.options?.readWrite + ?.multiplexedSessionPreviousTransactionId; + // no transaction id should be in the begintransactionrequest + // since first transaction got abort before getting an id + assert.ok(txnId instanceof Buffer && txnId.byteLength === 0); + // transactionObjects must have two transaction objects + // one the aborted transaction + // another the retried transaction + assert.strictEqual(transactionObjects.length, 2); + // first transaction must have an id undefined + // as the transaction got aborted before query execution + // which results in failure of inline begin + assert.strictEqual(transactionObjects[0].id, undefined); + // first transaction must not be having any previous transaction id + assert.strictEqual( + transactionObjects[0] + .multiplexedSessionPreviousTransactionId, + undefined, + ); + // the second transaction object(retried transaction) must have + // non null transaction id + assert.notEqual(transactionObjects[1].id, undefined); + // since the first transaction did not got any id previous transaction id + // for second transaction must be undefined + assert.strictEqual( + transactionObjects[1] + .multiplexedSessionPreviousTransactionId, + undefined, + ); + resolve(); + } catch (e: any) { + if (e.code === 10) { + throw e; + } else { + reject(e); + } + } + }); + }); + } finally { + await database.close(); + } + }); + }); + describe('using runTransactionAsync', () => { + it('case 1: transaction abortion on first query execution', async () => { + let attempts = 0; + const database = newTestDatabase(); + const transactionObjects: Transaction[] = []; + const rowCount = await database.runTransactionAsync( + (transaction): Promise => { + transactionObjects.push(transaction); + if (!attempts) { + // abort the transaction + spannerMock.abortTransaction(transaction); + } + attempts++; + return transaction.run(selectSql).then(([rows]) => { + let count = 0; + rows.forEach(() => count++); + return transaction.commit().then(() => count); + }); + }, + ); + assert.strictEqual(rowCount, 3); + assert.strictEqual(attempts, 2); + await database.close(); + + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + const txnId = + beginTxnRequest.options?.readWrite + ?.multiplexedSessionPreviousTransactionId; + // no transaction id should be in the begintransactionrequest + // since first transaction got abort before getting an id + assert.ok(txnId instanceof Buffer && txnId.byteLength === 0); + // transactionObjects must have two transaction objects + // one the aborted transaction + // another the retried transaction + assert.strictEqual(transactionObjects.length, 2); + // first transaction must have an id undefined + // as the transaction got aborted before query execution + // which results in failure of inline begin + assert.strictEqual(transactionObjects[0].id, undefined); + // first transaction must not be having any previous transaction id + assert.strictEqual( + transactionObjects[0].multiplexedSessionPreviousTransactionId, + undefined, + ); + // the second transaction object(retried transaction) must have + // non null transaction id + assert.notEqual(transactionObjects[1].id, undefined); + // since the first transaction did not got any id previous transaction id + // for second transaction must be undefined + assert.strictEqual( + transactionObjects[1].multiplexedSessionPreviousTransactionId, + undefined, + ); + }); + it('case 2: transaction abortion on second query execution', async () => { + let attempts = 0; + let rowCount = 0; + const database = newTestDatabase(); + const transactionObjects: Transaction[] = []; + await database.runTransactionAsync( + async (transaction): Promise => { + transactionObjects.push(transaction); + attempts++; + const [rows1] = await transaction.run(selectSql); + rows1.forEach(() => rowCount++); + if (attempts === 1) { + // abort the transaction + spannerMock.abortTransaction(transaction); + } + const [rows2] = await transaction.run(selectSql); + rows2.forEach(() => rowCount++); + await transaction.commit(); + }, + ); + assert.strictEqual(rowCount, 9); + assert.strictEqual(attempts, 2); + await database.close(); + + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + const txnId = + beginTxnRequest.options?.readWrite + ?.multiplexedSessionPreviousTransactionId; + // begin transaction request must contain the aborted transaction id + // as the previous transaction id upon retrying + assert.deepStrictEqual(txnId, transactionObjects[0].id); + // transactionObjects must contain have both the transaction + // one the aborted transaction + // another the retried transaction + assert.strictEqual(transactionObjects.length, 2); + // since inline begin was successfull with first query execution + // the transaction id would not be undefined for first transaction + assert.notEqual(transactionObjects[0].id, undefined); + // multiplexed session previous transaction id would be undefined + // for first transaction + assert.strictEqual( + transactionObjects[0].multiplexedSessionPreviousTransactionId, + undefined, + ); + // the second transction object (the retried transaction) must have an id + assert.notEqual(transactionObjects[1].id, undefined); + // first transaction id would be the multiplexed session previous transction id + // for retried transction + assert.strictEqual( + transactionObjects[1].multiplexedSessionPreviousTransactionId, + transactionObjects[0].id, + ); + }); + it('case 3: multiple transaction abortion', async () => { + let attempts = 0; + let rowCount = 0; + const database = newTestDatabase(); + const transactionObjects: Transaction[] = []; + await database.runTransactionAsync( + async (transaction): Promise => { + transactionObjects.push(transaction); + attempts++; + const [rows1] = await transaction.run(selectSql); + rows1.forEach(() => rowCount++); + if (attempts === 1) { + // abort the transaction + spannerMock.abortTransaction(transaction); + } + const [rows2] = await transaction.run(selectSql); + rows2.forEach(() => rowCount++); + if (attempts === 2) { + // abort the transaction + spannerMock.abortTransaction(transaction); + } + const [rows3] = await transaction.run(selectSql); + rows3.forEach(() => rowCount++); + await transaction.commit(); + }, + ); + assert.strictEqual(rowCount, 18); + assert.strictEqual(attempts, 3); + await database.close(); + const beginTxnRequest = spannerMock.getRequests().filter(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest[]; + // begin transaction request must have been called twice + // as transaction abortion happend twice + assert.strictEqual(beginTxnRequest.length, 2); + // multiplexedSessionPreviousTransactionId for first + // begin transaction request must be the id of first transaction object + assert.deepStrictEqual( + beginTxnRequest[0].options?.readWrite + ?.multiplexedSessionPreviousTransactionId, + transactionObjects[0].id, + ); + // multiplexedSessionPreviousTransactionId must get updated with an id of + // second transaction object on second begin transaction request + assert.deepStrictEqual( + beginTxnRequest[1].options?.readWrite + ?.multiplexedSessionPreviousTransactionId, + transactionObjects[1].id, + ); + // transactionObjects must contain 3 transaction objects + // as the transaction abortion happend twice + assert.strictEqual(transactionObjects.length, 3); + // first transaction must have a non null id + assert.notEqual(transactionObjects[0].id, undefined); + // first transaction must not have any previous transaction id + assert.strictEqual( + transactionObjects[0].multiplexedSessionPreviousTransactionId, + undefined, + ); + // second transaction must have a non null id + assert.notEqual(transactionObjects[1].id, undefined); + // second transaction must have previous transaction id as the + // id of first transaction object + assert.strictEqual( + transactionObjects[1].multiplexedSessionPreviousTransactionId, + transactionObjects[0].id, + ); + // third transction must have a non null id + assert.notEqual(transactionObjects[2].id, undefined); + // third transaction must have previous transaction id + // set to second transaction object id + assert.strictEqual( + transactionObjects[2].multiplexedSessionPreviousTransactionId, + transactionObjects[1].id, + ); + }); + it('case 4: commit abort', async () => { + const database = newTestDatabase(); + let attempts = 0; + let rowCount = 0; + const transactionObjects: Transaction[] = []; + const err = { + message: 'Simulated error for commit abortion', + code: grpc.status.ABORTED, + } as MockError; + await database.runTransactionAsync(async tx => { + attempts++; + transactionObjects.push(tx); + try { + const [rows] = await tx.runUpdate(invalidSql); + rowCount = rowCount + rows; + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + `${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`, + ); + } + const [rows] = await tx.run(selectSql); + rows.forEach(() => rowCount++); + if (attempts === 1) { + spannerMock.setExecutionTime( + spannerMock.commit, + SimulatedExecutionTime.ofError(err), + ); + // abort commit + spannerMock.abortTransaction(tx); + } + await tx.commit(); + }); + assert.strictEqual(attempts, 2); + assert.strictEqual(rowCount, 6); + await database.close(); + const beginTxnRequest = spannerMock + .getRequests() + .filter( + val => (val as v1.BeginTransactionRequest).options?.readWrite, + ) + .map(req => req as v1.BeginTransactionRequest); + // begin must have been requested twice + // one during explicit begin on unsucessful inline begin + // another time during retrying of aborted transaction + assert.deepStrictEqual(beginTxnRequest.length, 2); + // there must be two transaction in the transactionObjects + // one aborted transaction, another retried transaction + assert.strictEqual(transactionObjects.length, 2); + // since, inline begin was sucessful before commit got abort + // hence, the first transaction will have the id not null/undefined + assert.notEqual(transactionObjects[0].id, undefined); + // multiplexedSessionPreviousTransactionId must be undefined for first transaction + assert.strictEqual( + transactionObjects[0].multiplexedSessionPreviousTransactionId, + undefined, + ); + // retried transction will have the id not null/undefined + assert.notEqual(transactionObjects[1].id, undefined); + // multiplexedSessionPreviousTransactionId for retried transaction would be the id of aborted transaction + assert.strictEqual( + transactionObjects[1].multiplexedSessionPreviousTransactionId, + transactionObjects[0].id, + ); + }); + }); + describe('using getTransaction', () => { + it('case 1: transaction abortion on first query execution', async () => { + let attempts = 0; + let rowCount = 0; + const MAX_ATTEMPTS = 2; + let multiplexedSessionPreviousTransactionId; + let transaction; + const database = newTestDatabase(); + const transactionObjects: Transaction[] = []; + while (attempts < MAX_ATTEMPTS) { + try { + [transaction] = await database.getTransaction(); + transactionObjects.push(transaction); + transaction.multiplexedSessionPreviousTransactionId = + multiplexedSessionPreviousTransactionId; + if (attempts > 0) { + transaction.begin(); + } + const [rows1] = await transaction.run(selectSql); + rows1.forEach(() => rowCount++); + if (!attempts) { + // abort the transaction + spannerMock.abortTransaction(transaction); + } + const [rows2] = await transaction.run(selectSql); + rows2.forEach(() => rowCount++); + await transaction.commit(); + } catch (err) { + assert.strictEqual( + (err as grpc.ServiceError).code, + grpc.status.ABORTED, + ); + } finally { + attempts++; + multiplexedSessionPreviousTransactionId = transaction.id; + } + } + // assert on row count + assert.strictEqual(rowCount, 9); + // assert on number of attempts + assert.strictEqual(attempts, 2); + await database.close(); + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + const txnId = + beginTxnRequest.options?.readWrite + ?.multiplexedSessionPreviousTransactionId; + // begin transaction request must contain the aborted transaction id + // as the previous transaction id upon retrying + assert.deepStrictEqual(txnId, transactionObjects[0].id); + // transactionObjects must contain have both the transaction + // one the aborted transaction + // another the retried transaction + assert.strictEqual(transactionObjects.length, 2); + // since inline begin was successful with first query execution + // the transaction id would not be undefined for first transaction + assert.notEqual(transactionObjects[0].id, undefined); + // multiplexed session previous transaction id would be undefined + // for first transaction + assert.strictEqual( + transactionObjects[0].multiplexedSessionPreviousTransactionId, + undefined, + ); + // the second transction object (the retried transaction) must have an id + assert.notEqual(transactionObjects[1].id, undefined); + // first transaction id would be the multiplexed session previous transction id + // for retried transction + assert.strictEqual( + transactionObjects[1].multiplexedSessionPreviousTransactionId, + transactionObjects[0].id, + ); + }); + }); + }); + + // test(s) for commit retry logic + describe('Transaction Commit Retry Logic', () => { + let commitCallCount = 0; + let capturedCommitRequests: any[] = []; + + it('should retry commit only once with a precommit token', async () => { + commitCallCount = 0; + capturedCommitRequests = []; + + const database = newTestDatabase({min: 1, max: 1}); + const fakeRetryToken = Buffer.from('mock-retry-token-123'); + + const commitRetryResponse = { + MultiplexedSessionRetry: 'precommitToken', + precommitToken: { + precommitToken: fakeRetryToken, + seqNum: 2, + }, + commitTimestamp: mock.now(), + }; + + const commitSuccessResponse = { + commitTimestamp: mock.now(), + }; + + await database.runTransactionAsync(async tx => { + // mock commit request + tx.request = (config: any, callback: Function) => { + const cb = callback as (err: any, response: any) => void; + + if (config.method !== 'commit') return; + + commitCallCount++; + capturedCommitRequests.push(config.reqOpts); + + if (commitCallCount === 1) { + cb(null, commitRetryResponse); + } else { + cb(null, commitSuccessResponse); + } + }; + + // perform read + await tx!.run(selectSql); + + // perform mutations + tx.upsert('foo', [ + {id: 1, name: 'One'}, + {id: 2, name: 'Two'}, + ]); + + // make a call to commit + await tx.commit(); + + // assert that retry heppen only once + assert.strictEqual( + commitCallCount, + 2, + 'The mock commit method should have been called exactly twice.', + ); + + const secondRequest = capturedCommitRequests[1]; + // assert that during the second request to commit + // the precommitToken was present + assert.deepStrictEqual( + secondRequest.precommitToken, + commitRetryResponse.precommitToken, + 'The second commit request should have the precommitToken from the retry response.', + ); + }); + await database.close(); + }); + }); + + // parallel transactions + describe('parallel transactions', async () => { + async function readAndMutations(database) { + await database.runTransactionAsync(async tx => { + await tx.run(selectSql); + await tx.run(selectSql); + tx.upsert('foo', [ + {id: 1, name: 'One'}, + {id: 2, name: 'Two'}, + ]); + await tx.commit(); + }); + } + it('should have different precommit tokens for each transactions when running parallely', async () => { + const promises: Promise[] = []; + const database = newTestDatabase(); + + // run the transactions parallely + promises.push(readAndMutations(database)); + promises.push(readAndMutations(database)); + + // wait for the transaction to complete its execution + await Promise.all(promises); + + const commitRequest = spannerMock.getRequests().filter(val => { + return (val as v1.CommitRequest).precommitToken; + }) as v1.CommitRequest[]; + + // assert that there are two commit requests one for each transaction + assert.strictEqual(commitRequest.length, 2); + + // assert that precommitToken is not null during first request to commit + assert.notEqual(commitRequest[0].precommitToken, null); + + // assert that precommitToken is instance of Buffer + assert.ok( + commitRequest[0].precommitToken?.precommitToken instanceof Buffer, + ); + + // assert that precommitToken is not null during second request to commit + assert.notEqual(commitRequest[1].precommitToken, null); + + // assert that precommitToken is instance of Buffer + assert.ok( + commitRequest[1].precommitToken?.precommitToken instanceof Buffer, + ); + + // assert that precommitToken is different in both the commit request + assert.notEqual( + commitRequest[0].precommitToken.precommitToken, + commitRequest[1].precommitToken.precommitToken, + ); + }); + }); + }); + + describe('hand-crafted transaction', () => { + it('should use transactionTag on beginTransaction', async () => { + const database = newTestDatabase({min: 0}); + const [session] = await database.createSession({}); + const transaction = session.transaction( + {}, + {transactionTag: 'transaction-tag'}, + ); + await transaction.begin(); + await database.close(); + const request = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + assert.ok(request, 'no BeginTransactionRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on BeginTransactionRequest', + ); + assert.strictEqual(request.requestOptions!.requestTag, ''); + assert.strictEqual( + request.requestOptions!.transactionTag, + 'transaction-tag', + ); + }); + + it('should use inline begin transaction', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + await tx!.run(selectSql); + await tx!.run(insertSql); + await tx.commit(); + }); + await database.close(); + + let request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.ok(request.transaction!.begin!.readWrite, 'ReadWrite is not set'); + assert.strictEqual(request.sql, selectSql); + + request = spannerMock + .getRequests() + .slice() + .reverse() + .find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual(request.sql, insertSql); + assert.ok(request.transaction!.id, 'TransactionID is not set.'); + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + assert.ok(!beginTxnRequest, 'beginTransaction was called'); + }); + + it('should catch an exception error during invalid queries while using inline begin transaction', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + try { + await Promise.all([tx!.run(selectSql), tx!.run(invalidSql)]); + await tx.commit(); + } catch (err) { + assert(err, 'Expected an error to be thrown'); + assert.match((err as Error).message, /Table FOO not found/); + assert.deepStrictEqual( + (err as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.3.1`, + ); + } + }); + }); + + it('should apply blind writes only once', async () => { + const database = newTestDatabase(); + let attempts = 0; + await database.runTransactionAsync(async tx => { + attempts++; + if (attempts === 1) { + spannerMock.abortTransaction(tx); + } + tx!.insert('foo', {id: 1, value: 'One'}); + await tx!.run(insertSql); + await tx.commit(); + }); + await database.close(); + + assert.strictEqual(2, attempts); + // Verify that we have 2 ExecuteSqlRequests. The first one should use inline-begin. The second one should use a + // transaction ID. + const firstExecuteSqlRequest = spannerMock.getRequests().find(val => { + return ( + (val as v1.ExecuteSqlRequest).sql === insertSql && + (val as v1.ExecuteSqlRequest).transaction?.begin + ); + }) as v1.ExecuteSqlRequest; + assert.ok(firstExecuteSqlRequest.transaction?.begin?.readWrite); + const secondExecuteSqlRequest = spannerMock.getRequests().find(val => { + return ( + (val as v1.ExecuteSqlRequest).sql === insertSql && + (val as v1.ExecuteSqlRequest).transaction?.id + ); + }) as v1.ExecuteSqlRequest; + assert.ok(secondExecuteSqlRequest.transaction?.id); + // Verify that we have a BeginTransaction request for the retry. + const beginTxnRequests = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequests.length, 1); + // Verify that we have a single Commit request, and that the Commit request contains only one mutation. + assert.strictEqual( + 1, + spannerMock.getRequests().filter(val => { + return (val as v1.CommitRequest).mutations; + }).length, + ); + const commitRequest = spannerMock.getRequests().find(val => { + return (val as v1.CommitRequest).mutations; + }) as v1.CommitRequest; + assert.ok(commitRequest, 'Commit was called'); + assert.strictEqual(commitRequest.mutations.length, 1); + }); + + it('should apply blind writes only once with mutations', async () => { + const database = newTestDatabase(); + const mutations = new MutationSet(); + mutations.upsert('Singers', { + SingerId: 1, + FirstName: 'Scarlet', + LastName: 'Terry', + }); + mutations.upsert('Singers', { + SingerId: 2, + FirstName: 'Marc', + }); + await database.writeAtLeastOnce(mutations, {}); + await database.close(); + + // Verify that we don't have a BeginTransaction request for the transaction. + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + assert.deepStrictEqual(beginTxnRequest, undefined); + + // Verify that we have a single Commit request, and that the Commit request + // contains only two mutations and uses a single-use read/write transaction. + assert.strictEqual( + 1, + spannerMock.getRequests().filter(val => { + return (val as v1.CommitRequest).mutations; + }).length, + ); + const commitRequest = spannerMock.getRequests().find(val => { + const request = val as v1.CommitRequest; + return request.mutations || request.singleUseTransaction?.readWrite; + }) as v1.CommitRequest; + assert.ok(commitRequest, 'Commit was called'); + assert.strictEqual(commitRequest.mutations.length, 2); + }); + + it('should execute deleteRows with various key types', async () => { + const database = newTestDatabase(); + const mutations = new MutationSet(); + + // define different types of keys + const intKey = 123; + const boolKey = true; + const floatKey = 3.14; + const bytesKey = Buffer.from('test-buffer'); + const dateKey = new SpannerDate('2023-09-22'); + const timestampKey = new PreciseDate('2023-09-22T10:00:00.123Z'); + const numericKey = new Numeric('123.456'); + + // queue deletes for each type + mutations.deleteRows('IntTable', [intKey]); + mutations.deleteRows('BoolTable', [boolKey]); + mutations.deleteRows('FloatTable', [floatKey]); + mutations.deleteRows('BytesTable', [bytesKey]); + mutations.deleteRows('DateTable', [dateKey]); + mutations.deleteRows('TimestampTable', [timestampKey]); + mutations.deleteRows('NumericTable', [numericKey]); + + // execute blind writes + await database.writeAtLeastOnce(mutations, {}); + + // get the request sent to mock server + const request = spannerMock.getRequests().find(val => { + return (val as v1.CommitRequest).mutations; + }) as v1.CommitRequest; + + assert.strictEqual(request.mutations!.length, 7); + + await database.close(); + }); + + it('should apply blind writes only once with isolationLevel option', async () => { + const database = newTestDatabase(); + const mutations = new MutationSet(); + mutations.upsert('Singers', { + SingerId: 1, + FirstName: 'Marc', + LastName: 'Terry', + }); + mutations.upsert('Singers', { + SingerId: 2, + FirstName: 'Scarlet', + }); + const options: WriteAtLeastOnceOptions = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + await database.writeAtLeastOnce(mutations, options); + await database.close(); + const request = spannerMock.getRequests().find(val => { + return (val as v1.CommitRequest).singleUseTransaction?.isolationLevel; + }) as v1.CommitRequest; + assert.strictEqual( + request.singleUseTransaction?.isolationLevel, + 'REPEATABLE_READ', + ); + }); + + it('should apply blind writes only once with excludeTxnFromChangeStreams option', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + { + excludeTxnFromChangeStreams: true, + }, + async tx => { + await tx!.insert('foo', {id: 1, value: 'One'}); + await tx.commit(); + }, + ); + await database.close(); + + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + assert.strictEqual( + beginTxnRequest.options?.excludeTxnFromChangeStreams, + true, + ); + }); + + it('should use optimistic lock for runTransactionAsync', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + { + readLockMode: ReadLockMode.OPTIMISTIC, + }, + async tx => { + await tx!.run(selectSql); + await tx.commit(); + }, + ); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.readWrite!.readLockMode, + 'OPTIMISTIC', + ); + }); + + it('should use exclude transaction from change streams for runTransactionAsync', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + { + excludeTxnFromChangeStreams: true, + }, + async tx => { + await tx!.run(selectSql); + await tx.commit(); + }, + ); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin?.excludeTxnFromChangeStreams, + true, + ); + }); + + it('should use isolationLevel for runTransactionAsync', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }, + async tx => { + await tx!.run(selectSql); + await tx.commit(); + }, + ); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.isolationLevel, + 'REPEATABLE_READ', + ); + }); + + it('should use isolationLevel when passed in Spanner Options', async () => { + const spanner = new Spanner({ + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + defaultTransactionOptions: { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }, + }); + instance = spanner.instance('instance'); + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + await tx!.run(selectSql); + await tx.commit(); + }); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.isolationLevel, + 'REPEATABLE_READ', + ); + }); + + it('should be able to use isolationLevel from Spanner Option when other options are passed at transaction level', async () => { + const spanner = new Spanner({ + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + defaultTransactionOptions: { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }, + }); + instance = spanner.instance('instance'); + const database = newTestDatabase(); + await database.runTransactionAsync( + { + readLockMode: ReadLockMode.OPTIMISTIC, + excludeTxnFromChangeStreams: true, + }, + async tx => { + await tx!.run(selectSql); + await tx.commit(); + }, + ); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.readWrite?.readLockMode, + 'OPTIMISTIC', + ); + assert.strictEqual( + request.transaction!.begin!.excludeTxnFromChangeStreams, + true, + ); + assert.strictEqual( + request.transaction!.begin!.isolationLevel, + 'REPEATABLE_READ', + ); + }); + + it('should override isolationLevel from Spanner Option when passed at transaction level', async () => { + const spanner = new Spanner({ + servicePath: 'localhost', + port, + sslCreds: grpc.credentials.createInsecure(), + defaultTransactionOptions: { + isolationLevel: IsolationLevel.SERIALIZABLE, + }, + }); + instance = spanner.instance('instance'); + const database = newTestDatabase(); + await database.runTransactionAsync( + { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }, + async tx => { + await tx!.run(selectSql); + await tx.commit(); + }, + ); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.isolationLevel, + 'REPEATABLE_READ', + ); + }); + + it('should use optimistic lock for runTransaction', done => { + const database = newTestDatabase(); + database.runTransaction( + { + readLockMode: ReadLockMode.OPTIMISTIC, + }, + async (err, tx) => { + assert.ifError(err); + await tx!.run(selectSql); + await tx!.commit(); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.readWrite!.readLockMode, + 'OPTIMISTIC', + ); + done(); + }, + ); + }); + + it('should use exclude transaction from change stream for runTransaction', done => { + const database = newTestDatabase(); + database.runTransaction( + {excludeTxnFromChangeStreams: true}, + async (err, tx) => { + assert.ifError(err); + await tx!.run(selectSql); + await tx!.commit(); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.excludeTxnFromChangeStreams, + true, + ); + done(); + }, + ); + }); + + it('should use isolationLevel for runTransaction', done => { + const database = newTestDatabase(); + database.runTransaction( + {isolationLevel: IsolationLevel.REPEATABLE_READ}, + async (err, tx) => { + assert.ifError(err); + await tx!.run(selectSql); + await tx!.commit(); + await database.close(); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.isolationLevel, + 'REPEATABLE_READ', + ); + done(); + }, + ); + }); + + it('should use optimistic lock and transaction tag for getTransaction', async () => { + const database = newTestDatabase(); + const promise = await database.getTransaction({ + readLockMode: ReadLockMode.OPTIMISTIC, + requestOptions: {transactionTag: 'transaction-tag'}, + }); + const transaction = promise[0]; + await transaction.run('SELECT 1').then(() => { + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.readWrite!.readLockMode, + 'OPTIMISTIC', + ); + assert.strictEqual( + request.requestOptions?.transactionTag, + 'transaction-tag', + ); + }); + }); + + it('should use isolation level for getTransaction', async () => { + const database = newTestDatabase(); + const [transaction] = await database.getTransaction({ + isolationLevel: IsolationLevel.REPEATABLE_READ, + }); + await transaction.run('SELECT 1').then(() => { + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual( + request.transaction!.begin!.isolationLevel, + 'REPEATABLE_READ', + ); + }); + }); + + it('should reuse a session for optimistic and pessimistic locks', async () => { + const database = newTestDatabase({min: 1, max: 1}); + let session1; + let session2; + await database.runTransactionAsync( + { + readLockMode: ReadLockMode.OPTIMISTIC, + }, + async tx => { + session1 = tx!.session.id; + await tx!.run(selectSql); + await tx.commit(); + }, + ); + spannerMock.resetRequests(); + await database.runTransactionAsync(async tx => { + session2 = tx!.session.id; + await tx!.run(selectSql); + await tx.commit(); + }); + assert.strictEqual(session1, session2); + const request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.notStrictEqual( + request.transaction!.begin!.readWrite!.readLockMode, + 'OPTIMISTIC', + ); + }); + + it('should only inline one begin transaction', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + const rowCount1 = getRowCountFromStreamingSql(tx!, {sql: selectSql}); + const rowCount2 = getRowCountFromStreamingSql(tx!, {sql: selectSql}); + await Promise.all([rowCount1, rowCount2]); + await tx.commit(); + }); + await database.close(); + + let request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.ok(request.transaction!.begin!.readWrite, 'ReadWrite is not set'); + assert.strictEqual(request.sql, selectSql); + + request = spannerMock + .getRequests() + .slice() + .reverse() + .find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual(request.sql, selectSql); + assert.ok(request.transaction!.id, 'TransactionID is not set.'); + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + assert.ok(!beginTxnRequest, 'beginTransaction was called'); + }); + + it('should handle parallel request with inline begin transaction', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + const rowCount1 = getRowCountFromStreamingSql(tx!, {sql: selectSql}); + const rowCount2 = getRowCountFromStreamingSql(tx!, {sql: selectSql}); + const rowCount3 = getRowCountFromStreamingSql(tx!, {sql: selectSql}); + await Promise.all([rowCount1, rowCount2, rowCount3]); + await tx.commit(); + }); + await database.close(); + + let request = spannerMock.getRequests().find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.ok(request.transaction!.begin!.readWrite, 'ReadWrite is not set'); + assert.strictEqual(request.sql, selectSql); + + request = spannerMock + .getRequests() + .slice() + .reverse() + .find(val => { + return (val as v1.ExecuteSqlRequest).sql; + }) as v1.ExecuteSqlRequest; + assert.ok(request, 'no ExecuteSqlRequest found'); + assert.strictEqual(request.sql, selectSql); + assert.ok(request.transaction!.id, 'TransactionID is not set.'); + const beginTxnRequest = spannerMock.getRequests().find(val => { + return (val as v1.BeginTransactionRequest).options?.readWrite; + }) as v1.BeginTransactionRequest; + assert.ok(!beginTxnRequest, 'beginTransaction was called'); + }); + + it('should use beginTransaction on retry', async () => { + const database = newTestDatabase(); + let attempts = 0; + await database.runTransactionAsync(async tx => { + await tx!.run(selectSql); + if (!attempts) { + spannerMock.abortTransaction(tx); + } + attempts++; + await tx!.run(insertSql); + await tx.commit(); + }); + await database.close(); + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + }); + + it('should use beginTransaction on retry for parallel queries', async () => { + const database = newTestDatabase(); + let attempts = 0; + await database.runTransactionAsync(async tx => { + await Promise.all([tx!.run(selectSql), tx!.run(selectSql)]); + if (!attempts) { + spannerMock.abortTransaction(tx); + } + attempts++; + await Promise.all([tx!.run(insertSql), tx!.run(insertSql)]); + await tx.commit(); + }); + await database.close(); + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + }); + + it('should use beginTransaction on retry with excludeTxnFromChangeStreams', async () => { + const database = newTestDatabase(); + let attempts = 0; + await database.runTransactionAsync( + {excludeTxnFromChangeStreams: true}, + async tx => { + await tx!.run(selectSql); + if (!attempts) { + spannerMock.abortTransaction(tx); + } + attempts++; + await tx!.run(insertSql); + await tx.commit(); + }, + ); + await database.close(); + + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + assert.strictEqual( + beginTxnRequest[0].options?.excludeTxnFromChangeStreams, + true, + ); + }); + + it('should use beginTransaction on retry with optimistic lock', async () => { + const database = newTestDatabase(); + let attempts = 0; + await database.runTransactionAsync( + { + readLockMode: ReadLockMode.OPTIMISTIC, + }, + async tx => { + await tx!.run(selectSql); + if (!attempts) { + spannerMock.abortTransaction(tx); + } + attempts++; + await tx!.run(insertSql); + await tx.commit(); + }, + ); + await database.close(); + + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + assert.strictEqual( + beginTxnRequest[0].options!.readWrite!.readLockMode, + 'OPTIMISTIC', + ); + }); + + it('should use beginTransaction on retry for unknown reason', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + try { + await tx.runUpdate(invalidSql); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + `${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`, + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + } + await tx.run(selectSql); + await tx.commit(); + }); + await database.close(); + + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + }); + + it('should use beginTransaction on retry for unknown reason with excludeTxnFromChangeStreams', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + { + excludeTxnFromChangeStreams: true, + }, + async tx => { + try { + await tx.runUpdate(invalidSql); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + `${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`, + ); + } + await tx.run(selectSql); + await tx.commit(); + }, + ); + await database.close(); + + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + assert.strictEqual( + beginTxnRequest[0].options?.excludeTxnFromChangeStreams, + true, + ); + }); + + it('should use beginTransaction for streaming on retry for unknown reason', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + try { + await getRowCountFromStreamingSql(tx!, {sql: invalidSql}); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + `${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`, + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + } + await tx.run(selectSql); + await tx.commit(); + }); + await database.close(); + + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + }); + + it('should use beginTransaction for streaming on retry for unknown reason with excludeTxnFromChangeStreams', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + { + excludeTxnFromChangeStreams: true, + }, + async tx => { + try { + await getRowCountFromStreamingSql(tx!, {sql: invalidSql}); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + `${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`, + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + } + await tx.run(selectSql); + await tx.commit(); + }, + ); + await database.close(); + + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + assert.strictEqual( + beginTxnRequest[0].options?.excludeTxnFromChangeStreams, + true, + ); + }); + + it('should fail if beginTransaction fails', async () => { + const database = newTestDatabase(); + const err = { + message: 'Test error', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.beginTransaction, + SimulatedExecutionTime.ofError(err), + ); + try { + await database.runTransactionAsync(async tx => { + await tx!.run(selectSql); + spannerMock.abortTransaction(tx); + await tx!.run(insertSql); + await tx.commit(); + }); + assert.fail('missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + '2 UNKNOWN: Test error', + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.4.1`, + ); + } finally { + await database.close(); + } + }); + + it('should use transactionTag on blind commit', async () => { + const database = newTestDatabase({min: 0}); + const [session] = await database.createSession({}); + const transaction = session.transaction( + {}, + {transactionTag: 'transaction-tag'}, + ); + transaction.insert('foo', {id: 1, name: 'One'}); + await transaction.commit(); + await database.close(); + const request = spannerMock.getRequests().find(val => { + return (val as v1.CommitRequest).singleUseTransaction?.readWrite; + }) as v1.CommitRequest; + assert.ok(request, 'no CommitRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on CommitRequest', + ); + assert.strictEqual(request.requestOptions!.requestTag, ''); + assert.strictEqual( + request.requestOptions!.transactionTag, + 'transaction-tag', + ); + }); + + it('should run begin transaction on blind commit', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async tx => { + tx.insert('foo', {id: 1, name: 'One'}); + await tx.commit(); + }); + await database.close(); + + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + }); + + it('should run begin transaction on blind commit with excludeTxnFromChangeStreams', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync( + { + excludeTxnFromChangeStreams: true, + }, + async tx => { + tx.insert('foo', {id: 1, name: 'One'}); + await tx.commit(); + }, + ); + await database.close(); + + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + assert.strictEqual( + beginTxnRequest[0].options?.excludeTxnFromChangeStreams, + true, + ); + }); + + it('should throw error if begin transaction fails on blind commit', async () => { + const database = newTestDatabase(); + const err = { + message: 'Test error', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.beginTransaction, + SimulatedExecutionTime.ofError(err), + ); + try { + await database.runTransactionAsync(async tx => { + tx.insert('foo', {id: 1, name: 'One'}); + await tx.commit(); + }); + } catch (e) { + assert.strictEqual( + (e as ServiceError).message, + '2 UNKNOWN: Test error', + ); + assert.deepStrictEqual( + (e as RequestIDError).requestID, + `1.${randIdForProcess}.1.1.2.1`, + ); + } finally { + await database.close(); + } + }); + + it('should throw error if begin transaction fails on blind commit with excludeTxnFromChangeStreams', async () => { + const database = newTestDatabase(); + const err = { + message: 'Test error', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.beginTransaction, + SimulatedExecutionTime.ofError(err), + ); + try { + await database.runTransactionAsync( + { + excludeTxnFromChangeStreams: true, + }, + async tx => { + tx.insert('foo', {id: 1, name: 'One'}); + await tx.commit(); + }, + ); + } catch (e) { + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + assert.strictEqual( + beginTxnRequest[0].options?.excludeTxnFromChangeStreams, + true, + ); + assert.strictEqual( + (e as ServiceError).message, + '2 UNKNOWN: Test error', + ); + } finally { + await database.close(); + } + }); + }); + + describe('table', () => { + it('should use requestOptions for mutations', async () => { + const database = newTestDatabase(); + await database.table('foo').upsert( + {id: 1, name: 'bar'}, + { + requestOptions: { + priority: RequestOptions.Priority.PRIORITY_MEDIUM, + transactionTag: 'transaction-tag', + }, + }, + ); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.CommitRequest).mutations; + }) as v1.CommitRequest; + assert.ok(request, 'no CommitRequest found'); + assert.ok( + request.requestOptions, + 'no requestOptions found on CommitRequest', + ); + assert.strictEqual(request.requestOptions!.priority, 'PRIORITY_MEDIUM'); + assert.strictEqual( + request.requestOptions!.transactionTag, + 'transaction-tag', + ); + + await database.close(); + }); + + it('should use excludeTxnFromChangeStreams for mutations', async () => { + const database = newTestDatabase(); + await database.table('foo').upsert( + {id: 1, name: 'bar'}, + { + excludeTxnFromChangeStreams: true, + }, + ); + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + assert.strictEqual( + beginTxnRequest[0].options?.excludeTxnFromChangeStreams, + true, + ); + await database.close(); + }); + + it('should use isolationLevel for mutations', async () => { + const database = newTestDatabase(); + const options = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + await database.table('foo').upsert({id: 1, name: 'bar'}, options); + const beginTxnRequest = spannerMock + .getRequests() + .filter(val => (val as v1.BeginTransactionRequest).options?.readWrite) + .map(req => req as v1.BeginTransactionRequest); + assert.deepStrictEqual(beginTxnRequest.length, 1); + assert.strictEqual( + beginTxnRequest[0].options?.isolationLevel, + 'REPEATABLE_READ', + ); + await database.close(); + }); + + it('should encode object to JSON', async () => { + const database = newTestDatabase(); + await database + .table('foo') + .upsert({id: 1, value: {key1: 'value1', key2: 'value2'}}); + + const request = spannerMock.getRequests().find(val => { + return (val as v1.CommitRequest).mutations; + }) as v1.CommitRequest; + assert.ok(request, 'no CommitRequest found'); + assert.ok(request.mutations, 'no mutations found'); + assert.strictEqual(request.mutations.length, 1); + assert.strictEqual( + request.mutations[0].insertOrUpdate?.values?.length, + 1, + ); + assert.strictEqual( + request.mutations[0].insertOrUpdate!.columns![0], + 'id', + ); + assert.strictEqual( + request.mutations[0].insertOrUpdate!.columns![1], + 'value', + ); + assert.strictEqual( + request.mutations[0].insertOrUpdate!.values![0].values![0].stringValue, + '1', + ); + assert.strictEqual( + request.mutations[0].insertOrUpdate!.values![0].values![1].stringValue, + '{"key1":"value1","key2":"value2"}', + ); + + await database.close(); + }); + + it('should decorate error with additional information if an array of objects was inserted into a JSON column', async () => { + const database = newTestDatabase(); + const err = { + code: Status.FAILED_PRECONDITION, + message: + 'Invalid value for column TestCol2 in table TestTable: Expected JSON.', + } as MockError; + spannerMock.setExecutionTime( + spannerMock.commit, + SimulatedExecutionTime.ofError(err), + ); + try { + await database.table('TestTable').upsert({ + TestCol1: 1, + TestCol2: [{key1: 'value1'}, {key2: 'value2'}], + }); + assert.fail('Missing expected error'); + } catch (e) { + assert.strictEqual( + (e as ServiceError).code, + Status.FAILED_PRECONDITION, + ); + assert.ok( + (e as ServiceError).message.includes( + 'Convert the value to a JSON string containing an array instead', + ), + ); + } + + await database.close(); + }); + // tests for mutation key heuristic + describe('when multiplexed session is enabled for R/W', () => { + it('should pass the mutation key in begin transaction request in case of mutations only transactions', async () => { + const database = newTestDatabase(); + await database.table('foo').upsert({id: 1, name: randomUUID()}); + await database.table('foo').insert({id: 2, name: randomUUID()}); + await database.table('foo').deleteRows(['2']); + + const beginTransactionRequest = spannerMock + .getRequests() + .filter(val => { + return (val as v1.BeginTransactionRequest).mutationKey; + }) as v1.BeginTransactionRequest[]; + + // assert on begin transaction request + assert.strictEqual(beginTransactionRequest.length, 3); + + // assert that on first begin transaction request insertOrUpdate is being selected as mutation key + assert.ok( + ['insertOrUpdate'].includes( + Object.keys(beginTransactionRequest[0]!.mutationKey!)[0], + ), + 'insertOrUpdate key must have been selected', + ); + + // assert that on second begin transaction request insert is being selected as mutation key + assert.ok( + ['insert'].includes( + Object.keys(beginTransactionRequest[1]!.mutationKey!)[0], + ), + 'insert key must have been selected', + ); + + // assert that on third begin transaction request delete is being selected as mutation key + assert.ok( + ['delete'].includes( + Object.keys(beginTransactionRequest[2]!.mutationKey!)[0], + ), + 'delete key must have been selected', + ); + + const commitRequest = spannerMock.getRequests().filter(val => { + return (val as v1.CommitRequest).precommitToken; + }) as v1.CommitRequest[]; + + // assert on commit request + assert.strictEqual(commitRequest.length, 3); + + await database.close(); + }); + }); + }); + + describe('chunking', () => { + it('should return each value only once when all partial results miss a resume token and the buffer size is exceeded', async () => { + const sql = 'SELECT * FROM TestTable'; + const partials: PartialResultSet[] = []; + for (let i = 0; i < 11; i++) { + partials.push( + PartialResultSet.create({ + metadata: createMetadata(), + values: [ + {stringValue: 'Value'}, + { + listValue: { + values: [{stringValue: '1'}, {stringValue: '2'}], + }, + }, + ], + }), + ); + } + spannerMock.putStatementResult( + sql, + mock.StatementResult.resultSet(partials), + ); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[]; + assert.strictEqual(rows.length, 11); + } finally { + await database.close(); + } + }); + + it('should return all values from PartialResultSet with chunked string value', async () => { + for (const includeResumeToken of [true, false]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let errorOnIndexes: any; + for (errorOnIndexes of [[], [0], [1], [0, 1]]) { + const sql = 'SELECT * FROM TestTable'; + const prs1 = PartialResultSet.create({ + resumeToken: includeResumeToken + ? Buffer.from('00000000') + : undefined, + metadata: createMetadata(), + values: [{stringValue: 'This value is '}], + chunkedValue: true, + }); + const prs2 = PartialResultSet.create({ + resumeToken: includeResumeToken + ? Buffer.from('00000001') + : undefined, + values: [ + {stringValue: 'chunked'}, + { + listValue: { + values: [{stringValue: 'One'}, {stringValue: 'Two'}], + }, + }, + {stringValue: 'This value is not chunked'}, + { + listValue: { + values: [{stringValue: 'Three'}, {stringValue: 'Four'}], + }, + }, + ], + }); + setupResultsAndErrors(sql, [prs1, prs2], errorOnIndexes); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[]; + assert.strictEqual(rows.length, 2); + assert.strictEqual(rows[0].ColString, 'This value is chunked'); + assert.deepStrictEqual(rows[0].ColStringArray, ['One', 'Two']); + assert.strictEqual(rows[1].ColString, 'This value is not chunked'); + assert.deepStrictEqual(rows[1].ColStringArray, ['Three', 'Four']); + } finally { + await database.close(); + } + } + } + }); + + it('should return all values from PartialResultSet with chunked string value in an array', async () => { + for (const includeResumeToken of [true, false]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let errorOnIndexes: any; + for (errorOnIndexes of [[], [0], [1], [0, 1]]) { + const sql = 'SELECT * FROM TestTable'; + const prs1 = PartialResultSet.create({ + resumeToken: includeResumeToken + ? Buffer.from('00000000') + : undefined, + metadata: createMetadata(), + values: [ + {stringValue: 'This value is not chunked'}, + {listValue: {values: [{stringValue: 'On'}]}}, + ], + chunkedValue: true, + }); + const prs2 = PartialResultSet.create({ + resumeToken: includeResumeToken + ? Buffer.from('00000001') + : undefined, + values: [ + {listValue: {values: [{stringValue: 'e'}, {stringValue: 'Two'}]}}, + {stringValue: 'This value is also not chunked'}, + { + listValue: { + values: [{stringValue: 'Three'}, {stringValue: 'Four'}], + }, + }, + ], + }); + setupResultsAndErrors(sql, [prs1, prs2], errorOnIndexes); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[]; + assert.strictEqual(rows.length, 2); + assert.strictEqual(rows[0].ColString, 'This value is not chunked'); + assert.deepStrictEqual(rows[0].ColStringArray, ['One', 'Two']); + assert.strictEqual( + rows[1].ColString, + 'This value is also not chunked', + ); + assert.deepStrictEqual(rows[1].ColStringArray, ['Three', 'Four']); + } finally { + await database.close(); + } + } + } + }); + + it('should return all values from PartialResultSet with chunked list value', async () => { + for (const includeResumeToken of [true, false]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let errorOnIndexes: any; + for (errorOnIndexes of [[], [0], [1], [0, 1]]) { + const sql = 'SELECT * FROM TestTable'; + const prs1 = PartialResultSet.create({ + resumeToken: includeResumeToken + ? Buffer.from('00000000') + : undefined, + metadata: createMetadata(), + values: [ + {stringValue: 'This value is not chunked'}, + // The last value in this list value is a null value. A null value + // cannot be chunked, which means that in this case the list value + // itself is what is chunked. + { + listValue: { + values: [ + {stringValue: 'One'}, + {nullValue: google.protobuf.NullValue.NULL_VALUE}, + ], + }, + }, + ], + chunkedValue: true, + }); + const prs2 = PartialResultSet.create({ + resumeToken: includeResumeToken + ? Buffer.from('00000001') + : undefined, + values: [ + {listValue: {values: [{stringValue: 'Two'}]}}, + {stringValue: 'This value is also not chunked'}, + { + listValue: { + values: [{stringValue: 'Three'}, {stringValue: 'Four'}], + }, + }, + ], + }); + setupResultsAndErrors(sql, [prs1, prs2], errorOnIndexes); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[]; + assert.strictEqual(rows.length, 2); + assert.strictEqual(rows[0].ColString, 'This value is not chunked'); + assert.deepStrictEqual(rows[0].ColStringArray, [ + 'One', + null, + 'Two', + ]); + assert.strictEqual( + rows[1].ColString, + 'This value is also not chunked', + ); + assert.deepStrictEqual(rows[1].ColStringArray, ['Three', 'Four']); + } finally { + await database.close(); + } + } + } + }); + + it('should return all values from PartialResultSet with chunked struct with a null array field', async () => { + const sql = 'SELECT * FROM TestTable'; + const prs1 = PartialResultSet.create({ + metadata: createArrayOfStructMetadata(), + values: [ + { + listValue: { + values: [ + { + listValue: { + values: [ + // The array field is NULL. + {nullValue: NullValue.NULL_VALUE}, + ], + }, + }, + ], + }, + }, + ], + // This PartialResultSet is chunked, and the last value was the NULL value for the ARRAY field. + // This means that the next value will be the STRING field. + chunkedValue: true, + }); + const prs2 = PartialResultSet.create({ + values: [ + { + listValue: { + values: [ + { + listValue: { + values: [{stringValue: 'First row'}], + }, + }, + ], + }, + }, + { + listValue: { + values: [ + { + listValue: { + values: [ + {listValue: {values: [{stringValue: '1'}]}}, + {stringValue: 'Second row'}, + ], + }, + }, + ], + }, + }, + ], + }); + setupResultsAndErrors(sql, [prs1, prs2], []); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[]; + assert.strictEqual(rows.length, 2); + assert.strictEqual(rows[0].outerArray.length, 1); + assert.strictEqual(rows[0].outerArray[0].innerField, 'First row'); + assert.ok( + rows[0].outerArray[0].innerArray === null, + 'Inner array should be null', + ); + assert.strictEqual(rows[1].outerArray.length, 1); + assert.strictEqual(rows[1].outerArray[0].innerField, 'Second row'); + assert.strictEqual(rows[1].outerArray[0].innerArray.length, 1); + assert.strictEqual(rows[1].outerArray[0].innerArray[0], '1'); + } finally { + await database.close(); + } + }); + + function createArrayOfStructMetadata() { + const fields = [ + protobuf.StructType.Field.create({ + name: 'outerArray', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({ + code: protobuf.TypeCode.STRUCT, + structType: protobuf.StructType.create({ + fields: [ + { + name: 'innerArray', + type: protobuf.Type.create({ + code: TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({ + code: TypeCode.STRING, + }), + }), + }, + { + name: 'innerField', + type: protobuf.Type.create({code: TypeCode.STRING}), + }, + ], + }), + }), + }), + }), + ]; + return new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + } + + it('should reset to the chunked value of the last PartialResultSet with a resume token on retry', async () => { + // This tests the following scenario: + // 1. PartialResultSet without resume token, no chunked value. + // 2. PartialResultSet with resume token and chunked value. + // 3. PartialResultSet without resume token and chunked value. + // 4. PartialResultSet without resume token and no chunked value. + // The stream breaks with UNAVAILABLE after receiving 3 but before + // receiving 4. This means that the stream must retry from PRS 2, and + // reset the pending value that should be merged with the next result to + // the chunked value that was returned by PRS 2 and not the one from PRS + // 3. + const sql = 'SELECT * FROM TestTable'; + const prs1 = PartialResultSet.create({ + metadata: createMetadata(), + values: [ + {stringValue: 'This value is not chunked'}, + { + listValue: { + values: [{stringValue: 'One'}, {stringValue: 'Two'}], + }, + }, + ], + }); + const prs2 = PartialResultSet.create({ + resumeToken: Buffer.from('00000001'), + values: [{stringValue: 'This value is'}], + chunkedValue: true, + }); + const prs3 = PartialResultSet.create({ + values: [ + {stringValue: ' chunked'}, + { + listValue: { + values: [{stringValue: 'Three'}, {stringValue: 'Four'}], + }, + }, + {stringValue: 'This value is also'}, + ], + chunkedValue: true, + }); + const prs4 = PartialResultSet.create({ + values: [ + {stringValue: ' chunked'}, + { + listValue: { + values: [{stringValue: 'Five'}, {stringValue: 'Six'}], + }, + }, + ], + }); + setupResultsAndErrors(sql, [prs1, prs2, prs3, prs4], [3]); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[]; + assert.strictEqual(rows.length, 3); + assert.strictEqual(rows[0].ColString, 'This value is not chunked'); + assert.deepStrictEqual(rows[0].ColStringArray, ['One', 'Two']); + assert.strictEqual(rows[1].ColString, 'This value is chunked'); + assert.deepStrictEqual(rows[1].ColStringArray, ['Three', 'Four']); + assert.strictEqual(rows[2].ColString, 'This value is also chunked'); + assert.deepStrictEqual(rows[2].ColStringArray, ['Five', 'Six']); + } finally { + await database.close(); + } + }); + + it('should clear pending values if the last partial result did not have a resume token and was not a complete row', async () => { + const sql = 'SELECT * FROM TestTable'; + const prs1 = PartialResultSet.create({ + resumeToken: undefined, + metadata: createMultiColumnMetadata(), + values: [ + {stringValue: 'id1.1'}, + {stringValue: 'id1.2'}, + {stringValue: '100'}, + ], + chunkedValue: false, + }); + const prs2 = PartialResultSet.create({ + resumeToken: undefined, + values: [ + {boolValue: true}, + {boolValue: true}, + {numberValue: 0.5}, + {stringValue: 'id2.1'}, + {stringValue: 'id2.2'}, + ], + chunkedValue: false, + }); + const prs3 = PartialResultSet.create({ + resumeToken: undefined, + values: [ + {stringValue: '200'}, + {boolValue: true}, + {boolValue: true}, + {numberValue: 0.5}, + ], + }); + // Let the stream return UNAVAILABLE on index 1 (so the second PartialResultSet). + setupResultsAndErrors(sql, [prs1, prs2, prs3], [1]); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[][]; + verifyQueryResult(rows); + } finally { + await database.close(); + } + }); + + it('should not clear pending values if the last partial result had a resume token and was not a complete row', async () => { + for (const errorIndexes of [[1], [2]]) { + const sql = 'SELECT * FROM TestTable'; + const prs1 = PartialResultSet.create({ + resumeToken: Buffer.from('00000000'), + metadata: createMultiColumnMetadata(), + values: [ + {stringValue: 'id1.1'}, + {stringValue: 'id1.2'}, + {stringValue: '100'}, + ], + chunkedValue: false, + }); + const prs2 = PartialResultSet.create({ + resumeToken: undefined, + values: [ + {boolValue: true}, + {boolValue: true}, + {numberValue: 0.5}, + {stringValue: 'id2.1'}, + {stringValue: 'id2.2'}, + ], + chunkedValue: false, + }); + const prs3 = PartialResultSet.create({ + resumeToken: undefined, + values: [ + {stringValue: '200'}, + {boolValue: true}, + {boolValue: true}, + {numberValue: 0.5}, + ], + }); + setupResultsAndErrors(sql, [prs1, prs2, prs3], errorIndexes); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[][]; + verifyQueryResult(rows); + } finally { + await database.close(); + } + } + }); + + it('should not clear pending values if the last partial result was chunked and had a resume token', async () => { + for (const errorIndexes of [[2]]) { + const sql = 'SELECT * FROM TestTable'; + const prs1 = PartialResultSet.create({ + resumeToken: Buffer.from('00000000'), + metadata: createMultiColumnMetadata(), + values: [ + {stringValue: 'id1.1'}, + {stringValue: 'id1.2'}, + {stringValue: '100'}, + ], + chunkedValue: true, + }); + const prs2 = PartialResultSet.create({ + resumeToken: undefined, + values: [ + // The previous value was chunked, but it is still perfectly possible that it actually contained + // the entire value. So in this case the actual value was '100'. + {stringValue: ''}, + {boolValue: true}, + {boolValue: true}, + {numberValue: 0.5}, + {stringValue: 'id2.1'}, + {stringValue: 'id2.2'}, + ], + chunkedValue: false, + }); + const prs3 = PartialResultSet.create({ + resumeToken: undefined, + values: [ + {stringValue: '200'}, + {boolValue: true}, + {boolValue: true}, + {numberValue: 0.5}, + ], + }); + setupResultsAndErrors(sql, [prs1, prs2, prs3], errorIndexes); + const database = newTestDatabase(); + try { + const [rows] = (await database.run({ + sql, + json: true, + })) as Json[][]; + verifyQueryResult(rows); + } finally { + await database.close(); + } + } + }); + + function verifyQueryResult(rows: Json[]) { + assert.strictEqual(rows.length, 2); + assert.strictEqual(rows[0].col1, 'id1.1'); + assert.strictEqual(rows[0].col2, 'id1.2'); + assert.strictEqual(rows[0].col3, 100); + assert.strictEqual(rows[0].col4, true); + assert.strictEqual(rows[0].col5, true); + assert.strictEqual(rows[0].col6, 0.5); + + assert.strictEqual(rows[1].col1, 'id2.1'); + assert.strictEqual(rows[1].col2, 'id2.2'); + assert.strictEqual(rows[1].col3, 200); + assert.strictEqual(rows[1].col4, true); + assert.strictEqual(rows[1].col5, true); + assert.strictEqual(rows[1].col6, 0.5); + } + + function createMultiColumnMetadata() { + const fields = [ + protobuf.StructType.Field.create({ + name: 'col1', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + protobuf.StructType.Field.create({ + name: 'col2', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + protobuf.StructType.Field.create({ + name: 'col3', + type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), + }), + protobuf.StructType.Field.create({ + name: 'col4', + type: protobuf.Type.create({code: protobuf.TypeCode.BOOL}), + }), + protobuf.StructType.Field.create({ + name: 'col5', + type: protobuf.Type.create({code: protobuf.TypeCode.BOOL}), + }), + protobuf.StructType.Field.create({ + name: 'col6', + type: protobuf.Type.create({code: protobuf.TypeCode.FLOAT64}), + }), + ]; + return new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + } + + function createMetadata() { + const fields = [ + protobuf.StructType.Field.create({ + name: 'ColString', + type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), + }), + protobuf.StructType.Field.create({ + name: 'ColStringArray', + type: protobuf.Type.create({ + code: protobuf.TypeCode.ARRAY, + arrayElementType: protobuf.Type.create({ + code: protobuf.TypeCode.STRING, + }), + }), + }), + ]; + return new protobuf.ResultSetMetadata({ + rowType: new protobuf.StructType({ + fields, + }), + }); + } + + function setupResultsAndErrors( + sql: string, + results: PartialResultSet[], + errorOnIndexes: number[], + ) { + spannerMock.putStatementResult( + sql, + mock.StatementResult.resultSet(results), + ); + if (errorOnIndexes.length) { + const errors: MockError[] = []; + for (const index of errorOnIndexes) { + errors.push({ + message: 'Temporary unavailable', + code: grpc.status.UNAVAILABLE, + streamIndex: index, + } as MockError); + } + spannerMock.setExecutionTime( + spannerMock.executeStreamingSql, + SimulatedExecutionTime.ofErrors(errors), + ); + } + } + }); + + describe('instanceAdmin', () => { + it('should list instance configurations', async () => { + const [configs] = await spanner.getInstanceConfigs(); + assert.strictEqual(configs.length, 1); + }); + + it('should return all instance configs in a stream', done => { + let count = 0; + const stream = spanner.getInstanceConfigsStream(); + stream + .on('error', err => { + assert.fail(err); + }) + .on('data', () => count++) + .on('end', () => { + assert.strictEqual(count, 1); + done(); + }); + }); + + it('should list all instances', async () => { + const [instances] = await spanner.getInstances(); + assert.strictEqual(instances.length, 2); + }); + + it('should filter instances', async () => { + const [instances] = await spanner.getInstances({ + filter: `name:${TEST_INSTANCE_NAME}`, + }); + assert.strictEqual(instances.length, 1); + }); + + it('should cap results', async () => { + const [instances] = await spanner.getInstances({ + gaxOptions: {maxResults: 1}, + }); + assert.strictEqual(instances.length, 1); + }); + + it('should maximize api calls', async () => { + const [instances] = await spanner.getInstances({ + pageSize: 1, + }); + assert.strictEqual(instances.length, 1); + }); + + it('should list all instances with a callback', done => { + spanner.getInstances((err, instances) => { + assert.ifError(err); + assert.strictEqual(instances!.length, 2); + done(); + }); + }); + + it('should create an instance', async () => { + const [createdInstance] = await spanner + .createInstance('new-instance', { + config: 'test-instance-config', + nodes: 10, + }) + .then(data => { + const operation = data[1]; + return operation.promise() as Promise< + [Instance, CreateInstanceMetadata, object] + >; + }) + .then(response => { + return response; + }); + assert.strictEqual( + createdInstance.name, + `projects/${spanner.projectId}/instances/new-instance`, + ); + assert.strictEqual(createdInstance.nodeCount, 10); + }); + + it('should create an instance with a display name', async () => { + const [createdInstance] = await spanner + .createInstance('new-instance', { + config: 'test-instance-config', + nodes: 10, + displayName: 'some new instance', + }) + .then(data => { + const operation = data[1]; + return operation.promise() as Promise< + [Instance, CreateInstanceMetadata, object] + >; + }) + .then(response => { + return response; + }); + assert.strictEqual( + createdInstance.name, + `projects/${spanner.projectId}/instances/new-instance`, + ); + assert.strictEqual(createdInstance.nodeCount, 10); + assert.strictEqual(createdInstance.displayName, 'some new instance'); + }); + + it('should create an instance using a callback', done => { + spanner.createInstance( + 'new-instance', + { + config: 'test-instance-config', + nodes: 10, + }, + (err, resource, operation) => { + assert.ifError(err); + assert.ok(resource, 'no instance returned'); + assert.strictEqual( + resource!.formattedName_, + `projects/${spanner.projectId}/instances/new-instance`, + ); + assert.ok(operation, 'no operation returned'); + operation!.on('error', assert.ifError).on('complete', instance => { + // Instance created successfully. + assert.strictEqual( + instance.name, + `projects/${spanner.projectId}/instances/new-instance`, + ); + assert.strictEqual(instance.nodeCount, 10); + done(); + }); + }, + ); + }); + + it('should create an instance with processing units', async () => { + const [createdInstance] = await spanner + .createInstance('new-instance', { + config: 'test-instance-config', + processingUnits: 500, + }) + .then(data => { + const operation = data[1]; + return operation.promise() as Promise< + [Instance, CreateInstanceMetadata, object] + >; + }) + .then(response => { + return response; + }); + assert.strictEqual( + createdInstance.name, + `projects/${spanner.projectId}/instances/new-instance`, + ); + assert.strictEqual(createdInstance.processingUnits, 500); + assert.strictEqual(createdInstance.nodeCount, 0); + }); + + it('should update an instance', async () => { + const instance = spanner.instance(mockInstanceAdmin.PROD_INSTANCE_NAME); + const [updatedInstance] = await instance + .setMetadata({ + nodeCount: 20, + displayName: 'Production instance with 20 nodes', + }) + .then(data => { + return data[0].promise() as Promise< + [google.spanner.admin.instance.v1.Instance] + >; + }) + .then(instance => { + return instance; + }); + assert.strictEqual(updatedInstance.nodeCount, 20); + }); + + it('should delete an instance', async () => { + const instance = spanner.instance(mockInstanceAdmin.PROD_INSTANCE_NAME); + const [res] = await instance.delete(); + assert.ok(res); + }); + + it('should list databases', async () => { + const [databases] = await instance.getDatabases(); + assert.strictEqual(databases.length, 2); + // Assert that listing the databases does not cause a session pool to be + // initialized for the databases. + for (const db of databases) { + assert.strictEqual((db.pool_ as SessionPool).size, 0); + } + }); + + it('should create a database', async () => { + const [createdDatabase] = await instance + .createDatabase('new-database') + .then(data => { + const operation = data[1]; + return operation.promise(); + }) + .then(database => { + return database as [google.spanner.admin.database.v1.Database]; + }); + assert.strictEqual( + createdDatabase.name, + `${instance.formattedName_}/databases/new-database`, + ); + }); + + it('should list database operations', async () => { + const dbSpecificFilter = + 'name:projects/p/instances/i/databases/test-database'; + const dbSpecificQuery: GetDatabaseOperationsOptions = { + filter: dbSpecificFilter, + }; + const [operations1] = + await instance.getDatabaseOperations(dbSpecificQuery); + + const database = instance.database('test-database'); + const [operations2] = await database.getOperations(); + assert.strictEqual(operations1.length, 2); + assert.strictEqual(operations2.length, 2); + assert.deepStrictEqual(operations1, operations2); + }); + }); + + // TODO: Refactor this file's Spanner creation to make it more + // self contained and remove the tight coupling that requires + // and tests the database/instance suffix is an iteration of + // each afresh invocation of newTestDatabase, which has been + // causing test flakes. + it('Check for span annotations', done => { + const exporter = new InMemorySpanExporter(); + const provider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: exporter, + spanProcessors: [new SimpleSpanProcessor(exporter)], + }); + provider.register(); + + after(async () => { + await provider.shutdown(); + }); + + const opts: typeof ObservabilityOptions = {tracerProvider: provider}; + startTrace('aSpan', {opts: opts}, async span => { + instance._observabilityOptions = opts; + const database = newTestDatabase(); + database._observabilityOptions = opts; + + const query = { + sql: 'SELECT 1', + }; + + const [rows] = await database.run(query); + assert.strictEqual(rows.length, 1); + + span.end(); + + exporter.forceFlush(); + const spans = exporter.getFinishedSpans(); + + // Sort the spans by startTime. + spans.sort((spanA, spanB) => { + spanA.startTime < spanB.startTime; + }); + + const actualSpanNames: string[] = []; + const actualEventNames: string[] = []; + spans.forEach(span => { + actualSpanNames.push(span.name); + span.events.forEach(event => { + actualEventNames.push(event.name); + }); + }); + + const expectedSpanNames = [ + 'CloudSpanner.Database.createSession', + 'CloudSpanner.MultiplexedSession.createSession', + 'CloudSpanner.Snapshot.runStream', + 'CloudSpanner.Database.runStream', + 'CloudSpanner.Database.run', + 'CloudSpanner.aSpan', + ]; + assert.deepStrictEqual( + actualSpanNames, + expectedSpanNames, + `span names mismatch:\n\tGot: ${actualSpanNames}\n\tWant: ${expectedSpanNames}`, + ); + + const expectedEventNames = [ + 'Requesting a multiplexed session', + 'Created a multiplexed session', + 'Starting stream', + 'Waiting for a multiplexed session to become available', + 'Acquired multiplexed session', + 'Using Session', + ]; + + assert.deepEqual( + actualEventNames, + expectedEventNames, + `Mismatched events\n\tGot: ${actualEventNames}\n\tWant: ${expectedEventNames}`, + ); + done(); + }); + }); + + describe('session-factory', () => { + it('should not propagate any error when disabling GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS after client initialization', done => { + const database = newTestDatabase(); + // disable env after database creation + process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS = 'false'; + const sessionFactory = database.sessionFactory_ as SessionFactory; + sessionFactory.getSession((err, _) => { + assert.ifError(err); + delete process.env.GOOGLE_CLOUD_SPANNER_MULTIPLEXED_SESSIONS; + done(); + }); + }); + }); + + describe('XGoogRequestId', () => { + const exporter = new InMemorySpanExporter(); + const provider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + exporter: exporter, + spanProcessors: [new SimpleSpanProcessor(exporter)], + }); + provider.register(); + + beforeEach(async () => { + await exporter.forceFlush(); + await exporter.reset(); + }); + + after(async () => { + await provider.shutdown(); + }); + + it('with retry on aborted query', async () => { + let attempts = 0; + const database = newTestDatabase(); + let rowCount = 0; + const maxAttempts = 4; + await database.runTransactionAsync(async transaction => { + attempts++; + if (attempts < maxAttempts) { + spannerMock.abortTransaction(transaction!); + } + const [rows] = await transaction!.run(selectSql); + rows.forEach(() => rowCount++); + assert.strictEqual(rowCount, 3); + assert.strictEqual(attempts, 4); + await transaction!.commit(); + }); + + const wantUnaryCallsWithoutBatchCreateSessions = [ + { + method: '/google.spanner.v1.Spanner/BeginTransaction', + reqId: `1.${randIdForProcess}.1.1.3.1`, + }, + { + method: '/google.spanner.v1.Spanner/BeginTransaction', + reqId: `1.${randIdForProcess}.1.1.5.1`, + }, + { + method: '/google.spanner.v1.Spanner/BeginTransaction', + reqId: `1.${randIdForProcess}.1.1.7.1`, + }, + { + method: '/google.spanner.v1.Spanner/Commit', + reqId: `1.${randIdForProcess}.1.1.9.1`, + }, + ]; + const gotUnaryCalls = xGoogReqIDInterceptor.getUnaryCalls(); + assert.deepStrictEqual( + gotUnaryCalls[0].method, + '/google.spanner.v1.Spanner/CreateSession', + ); + // It is non-deterministic to try to get the exact clientId used to invoke .BatchCreateSessions + // given that these tests run as a collective and sessions are pooled. + assert.deepStrictEqual( + gotUnaryCalls.slice(1), + wantUnaryCallsWithoutBatchCreateSessions, + ); + + const gotStreamingCalls = xGoogReqIDInterceptor.getStreamingCalls(); + const wantStreamingCalls = [ + { + method: '/google.spanner.v1.Spanner/ExecuteStreamingSql', + reqId: `1.${randIdForProcess}.1.1.2.1`, + }, + { + method: '/google.spanner.v1.Spanner/ExecuteStreamingSql', + reqId: `1.${randIdForProcess}.1.1.4.1`, + }, + { + method: '/google.spanner.v1.Spanner/ExecuteStreamingSql', + reqId: `1.${randIdForProcess}.1.1.6.1`, + }, + { + method: '/google.spanner.v1.Spanner/ExecuteStreamingSql', + reqId: `1.${randIdForProcess}.1.1.8.1`, + }, + ]; + assert.deepStrictEqual(gotStreamingCalls, wantStreamingCalls); + await database.close(); + }); + + it('check span attributes for x-goog-spanner-request-id', async () => { + const database = newTestDatabase(); + await database.runTransactionAsync(async transaction => { + await transaction!.run(selectSql); + await transaction!.commit(); + }); + + await exporter.forceFlush(); + const spans = exporter.getFinishedSpans(); + + // The RPC invoking spans that we expect to have our value. + const rpcMakingSpans = [ + 'CloudSpanner.Database.batchCreateSessions', + 'CloudSpanner.Snapshot.run', + 'CloudSpanner.Transaction.commit', + ]; + + spans.forEach(span => { + if (rpcMakingSpans.includes(span.name)) { + assert.strictEqual( + X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR in span.attributes, + true, + `Missing ${X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR} for ${span.name}`, + ); + } + }); + }); + + // TODO(@odeke-em): introduce tests for incremented attempts to verify + // that retries from GAX produce the required results. + }); +}); + +function executeSimpleUpdate( + database: Database, + update: string | ExecuteSqlRequest, +): Promise { + return database + .runTransactionAsync<[number]>((transaction): Promise<[number]> => { + return transaction + .runUpdate(update) + .then(rowCount => { + return rowCount; + }) + .then(rowCount => { + return transaction.commit().then(() => rowCount); + }) + .then(rowCount => { + return rowCount; + }) + .catch(() => { + transaction + .rollback() + .then(() => {}) + .catch(() => {}); + return [-1]; + }); + }) + .then(updated => { + return updated; + }); +} + +function getRowCountFromStreamingSql( + context: Database | Transaction, + query: ExecuteSqlRequest, +): Promise { + return new Promise((resolve, reject) => { + let rows = 0; + let errored = false; + context + .runStream(query) + .on('error', err => { + errored = true; + return reject(err); + }) + .on('data', () => rows++) + .on('end', () => { + if (!errored) { + return resolve(rows); + } + }); + }); +} + +function sleep(ms): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); +} diff --git a/handwritten/spanner/test/table.ts b/handwritten/spanner/test/table.ts new file mode 100644 index 00000000000..9eb322621c2 --- /dev/null +++ b/handwritten/spanner/test/table.ts @@ -0,0 +1,1018 @@ +/*! + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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 * as pfy from '@google-cloud/promisify'; +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import * as extend from 'extend'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import {split} from 'split-array-stream'; +import {Transform} from 'stream'; +import * as through from 'through2'; + +import {TimestampBounds} from '../src/transaction'; +import {google} from '../protos/protos'; +import RequestOptions = google.spanner.v1.RequestOptions; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; + +let promisified = false; +const fakePfy = extend({}, pfy, { + promisifyAll(klass, options) { + if (klass.name !== 'Table') { + return; + } + promisified = true; + assert.deepStrictEqual(options.exclude, ['delete', 'drop']); + }, +}); + +class FakeTransaction { + commit(gaxOptions, callback) { + callback(null, {}); + } + createReadStream() { + return through.obj(); + } + deleteRows() {} + end() {} + insert() {} + replace() {} + upsert() {} + update() {} +} + +interface GetSnapshotCallback { + (err: Error, snapshot?: null): void; + (err: null, snapshot: FakeTransaction): void; +} + +describe('Table', () => { + const sandbox = sinon.createSandbox(); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Table: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let TableCached: any; + let table; + let tableWithSchema; + let transaction: FakeTransaction; + + const DATABASE = { + runTransaction: (opts, callback) => callback(null, transaction), + getSnapshot: (options, callback) => callback(null, transaction), + }; + + const NAME = 'table-name'; + const NAMEWITHSCHEMA = 'schema.' + NAME; + + before(() => { + Table = proxyquire('../src/table.js', { + '@google-cloud/promisify': fakePfy, + }).Table; + TableCached = extend({}, Table); + }); + + beforeEach(() => { + extend(Table, TableCached); + table = new Table(DATABASE, NAME); + tableWithSchema = new Table(DATABASE, NAMEWITHSCHEMA); + transaction = new FakeTransaction(); + }); + + afterEach(() => sandbox.restore()); + + describe('instantiation', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should localize database', () => { + assert.strictEqual(table.database, DATABASE); + }); + + it('should localize name', () => { + assert.strictEqual(table.name, NAME); + }); + }); + + describe('create', () => { + it('should create a table from the database', done => { + const schema = 'schema'; + + table.database = { + createTable(schema_, gaxOptions_, callback) { + assert.strictEqual(schema_, schema); + callback(); // done() + }, + }; + + table.create(schema, done); + }); + + it('should accept gaxOptions', done => { + const gaxOpts = {}; + + table.database = { + createTable(schema_, gaxOptions, callback) { + assert.strictEqual(gaxOptions, gaxOpts); + callback(); // done() + }, + }; + + table.create('schema', gaxOpts, done); + }); + }); + + describe('createReadStream', () => { + let fakeReadStream: Transform; + let getSnapshotStub: sinon.SinonStub< + [TimestampBounds, GetSnapshotCallback], + void + >; + + const REQUEST = {keys: ['key']}; + + beforeEach(() => { + fakeReadStream = through.obj(); + sandbox.stub(transaction, 'createReadStream').returns(fakeReadStream); + getSnapshotStub = sandbox + .stub(DATABASE, 'getSnapshot') + .callsFake((_, callback) => callback(null, transaction)); + }); + + it('should destroy the user stream if unable to get a snapshot', done => { + const fakeError = new Error('err'); + + getSnapshotStub.callsFake((options, callback) => callback(fakeError)); + + table.createReadStream(REQUEST).on('error', err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should pass in timestamp bounds', () => { + const fakeOptions = {}; + + table.createReadStream(REQUEST, fakeOptions); + + const options = getSnapshotStub.lastCall.args[0]; + + assert.strictEqual(options, fakeOptions); + }); + + it('should destroy the user stream and end the txn on error', done => { + const endStub = sandbox.stub(transaction, 'end'); + const fakeError = new Error('err'); + + table.createReadStream(REQUEST).on('error', err => { + assert.strictEqual(err, fakeError); + assert.strictEqual(endStub.callCount, 1); + done(); + }); + + fakeReadStream.destroy(fakeError); + }); + + it('should pipe data into the user stream', done => { + const expectedData = [{}, {}, {}]; + const received: Array<{}> = []; + + table + .createReadStream(REQUEST) + .on('error', done) + .on('data', data => received.push(data)) + .on('end', () => { + assert.deepStrictEqual(received, expectedData); + done(); + }); + + expectedData.forEach(data => fakeReadStream.write(data)); + fakeReadStream.end(); + }); + + it('should end the transaction on stream end', done => { + sandbox.stub(transaction, 'end').callsFake(done); + table.createReadStream(REQUEST).on('error', done); + fakeReadStream.end(); + }); + }); + + describe('delete', () => { + it('should update the schema on the database for GoogleSQL using await', async () => { + table.database = { + getDatabaseDialect: () => { + return 'GOOGLE_STANDARD_SQL'; + }, + updateSchema: schema => { + assert.strictEqual(schema, 'DROP TABLE `table-name`'); + }, + }; + + await table.delete(); + }); + + it('should update the schema on the database for GoogleSQL using callbacks', () => { + function callback() {} + table.database = { + getDatabaseDialect: () => { + return 'GOOGLE_STANDARD_SQL'; + }, + updateSchema: (schema, gaxOptions, callback_) => { + assert.strictEqual(schema, 'DROP TABLE `table-name`'); + assert.strictEqual(callback_, callback); + }, + }; + table.delete(callback); + }); + + it('should update the schema on the database for GoogleSQL with schema in the table name using await', async () => { + tableWithSchema.database = { + getDatabaseDialect: () => { + return 'GOOGLE_STANDARD_SQL'; + }, + updateSchema: schema => { + assert.strictEqual(schema, 'DROP TABLE `schema`.`table-name`'); + }, + }; + + await tableWithSchema.delete(); + }); + + it('should update the schema on the database for GoogleSQL with schema in the table name using callbacks', () => { + function callback() {} + tableWithSchema.database = { + getDatabaseDialect: () => { + return 'GOOGLE_STANDARD_SQL'; + }, + updateSchema: (schema, gaxOptions, callback_) => { + assert.strictEqual(schema, 'DROP TABLE `schema`.`table-name`'); + assert.strictEqual(callback_, callback); + }, + }; + tableWithSchema.delete(callback); + }); + + it('should update the schema on the database for PostgresSQL using await', async () => { + table.database = { + getDatabaseDialect: () => { + return 'POSTGRESQL'; + }, + updateSchema: schema => { + assert.strictEqual(schema, `DROP TABLE "${table.name}"`); + }, + }; + + await table.delete(); + }); + + it('should update the schema on the database for PostgresSQL using callbacks', () => { + function callback() {} + + table.database = { + getDatabaseDialect: () => { + return 'POSTGRESQL'; + }, + updateSchema: (schema, gaxOptions, callback_) => { + assert.strictEqual(schema, 'DROP TABLE "table-name"'); + assert.strictEqual(callback_, callback); + }, + }; + + table.delete(callback); + }); + + it('should update the schema on the database for PostgresSQL with schema in the table name using await', async () => { + tableWithSchema.database = { + getDatabaseDialect: () => { + return 'POSTGRESQL'; + }, + updateSchema: schema => { + assert.strictEqual(schema, `DROP TABLE "schema"."${table.name}"`); + }, + }; + + await tableWithSchema.delete(); + }); + + it('should update the schema on the database for PostgresSQL with schema in the table name using callbacks', () => { + function callback() {} + tableWithSchema.database = { + getDatabaseDialect: () => { + return 'POSTGRESQL'; + }, + updateSchema: (schema, gaxOptions, callback_) => { + assert.strictEqual(schema, `DROP TABLE "schema"."${table.name}"`); + assert.strictEqual(callback_, callback); + }, + }; + + tableWithSchema.delete(callback); + }); + + it('should accept and pass gaxOptions to updateSchema', done => { + const gaxOptions = {}; + table.database = { + getDatabaseDialect: gaxOptionsFromTable => { + assert.strictEqual(gaxOptionsFromTable, gaxOptions); + return 'GOOGLE_STANDARD_SQL'; + }, + updateSchema: (schema, gaxOptionsFromTable) => { + assert.strictEqual(gaxOptionsFromTable, gaxOptions); + done(); + }, + }; + table.delete(gaxOptions, assert.ifError); + }); + }); + + describe('deleteRows', () => { + const KEYS = ['key']; + + it('should return an error if unable to get a txn', done => { + const fakeError = new Error('err'); + + sandbox + .stub(DATABASE, 'runTransaction') + .callsFake((opts, callback) => callback(fakeError)); + + table.deleteRows(KEYS, err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + transaction.commit = options => { + assert.strictEqual(options, gaxOptions); + done(); + }; + table.deleteRows(KEYS, gaxOptions, assert.ifError); + }); + + it('should accept commit options', done => { + const deleteRowsOptions = {returnCommitStats: true}; + transaction.commit = options => { + assert.strictEqual(options, deleteRowsOptions); + done(); + }; + table.deleteRows(KEYS, deleteRowsOptions, assert.ifError); + }); + + it('should accept gax options in commit options', done => { + const deleteRowsOptions = { + returnCommitStats: true, + gaxOptions: {}, + }; + transaction.commit = options => { + assert.strictEqual(options, deleteRowsOptions); + done(); + }; + table.deleteRows(KEYS, deleteRowsOptions, assert.ifError); + }); + + it('should accept requestOptions', done => { + const deleteRowsOptions = { + requestOptions: {priority: RequestOptions.Priority.PRIORITY_HIGH}, + }; + transaction.commit = options => { + assert.strictEqual(options, deleteRowsOptions); + done(); + }; + table.deleteRows(KEYS, deleteRowsOptions, assert.ifError); + }); + + it('should accept isolationLevel option', done => { + const deleteRowsOptions = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + transaction.commit = options => { + assert.strictEqual(options, deleteRowsOptions); + done(); + }; + table.deleteRows(KEYS, deleteRowsOptions, assert.ifError); + }); + + it('should accept readLockMode option', done => { + const deleteRowsOptions = { + readLockMode: ReadLockMode.OPTIMISTIC, + }; + transaction.commit = options => { + assert.strictEqual(options, deleteRowsOptions); + done(); + }; + table.deleteRows(KEYS, deleteRowsOptions, assert.ifError); + }); + + it('should delete the rows via transaction', done => { + const stub = ( + sandbox.stub(transaction, 'deleteRows') as sinon.SinonStub + ).withArgs(table.name, KEYS); + + sandbox.stub(transaction, 'commit').callsFake((opts, callback) => { + callback(); + }); + + table.deleteRows(KEYS, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + done(); + }); + }); + }); + + describe('drop', () => { + it('should call through to Table#delete', done => { + const returnVal = Promise.resolve(); + + table.delete = (gaxOptions, callback) => { + setImmediate(callback); // the done fn + return returnVal; + }; + + const promise = table.drop(done); + + assert.strictEqual(promise, returnVal); + }); + + it('should accept and pass gaxOptions to Table#delete', done => { + const gaxOptions = {}; + table.delete = gaxOptionsFromDrop => { + assert.strictEqual(gaxOptionsFromDrop, gaxOptions); + done(); + }; + table.drop(gaxOptions, assert.ifError); + }); + }); + + describe('insert', () => { + const ROW = {}; + + it('should return any runTransaction errors', done => { + const fakeError = new Error('err'); + + sandbox + .stub(DATABASE, 'runTransaction') + .callsFake((opts, callback) => callback(fakeError)); + + table.insert(ROW, err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should insert via transaction', done => { + const stub = ( + sandbox.stub(transaction, 'insert') as sinon.SinonStub + ).withArgs(table.name, ROW); + + table.insert(ROW, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + done(); + }); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + (sandbox.stub(transaction, 'insert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, gaxOptions); + done(); + }; + + table.insert(ROW, gaxOptions, assert.ifError); + }); + + it('should accept commit options', done => { + const insertRowsOptions = {returnCommitStats: true}; + (sandbox.stub(transaction, 'insert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, insertRowsOptions); + done(); + }; + + table.insert(ROW, insertRowsOptions, assert.ifError); + }); + + it('should accept gax options in commit options', done => { + const insertRowsOptions = { + returnCommitStats: true, + gaxOptions: {}, + }; + (sandbox.stub(transaction, 'insert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, insertRowsOptions); + done(); + }; + + table.insert(ROW, insertRowsOptions, assert.ifError); + }); + + it('should accept requestOptions', done => { + const insertRowsOptions = { + requestOptions: {priority: RequestOptions.Priority.PRIORITY_HIGH}, + }; + (sandbox.stub(transaction, 'insert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, insertRowsOptions); + done(); + }; + + table.insert(ROW, insertRowsOptions, assert.ifError); + }); + + it('should accept isolationLevel options', done => { + const insertRowsOptions = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + (sandbox.stub(transaction, 'insert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, insertRowsOptions); + done(); + }; + + table.insert(ROW, insertRowsOptions, assert.ifError); + }); + + it('should accept readLockMode options', done => { + const insertRowsOptions = { + readLockMode: ReadLockMode.OPTIMISTIC, + }; + (sandbox.stub(transaction, 'insert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, insertRowsOptions); + done(); + }; + + table.insert(ROW, insertRowsOptions, assert.ifError); + }); + }); + + describe('read', () => { + it('should call and collect results from a stream', done => { + const keyVals = []; + + const rows = [{}, {}]; + + table.createReadStream = (keyVals_, options) => { + assert.strictEqual(keyVals_, keyVals); + assert.deepStrictEqual(options, {}); + + const stream = through.obj(); + + setImmediate(async () => { + try { + await split(rows, stream); + stream.end(); + } catch (err) { + stream.destroy(err as Error); + } + }); + + return stream; + }; + + table.read(keyVals, (err, rows_) => { + assert.ifError(err); + assert.deepStrictEqual(rows_, rows); + done(); + }); + }); + + it('should accept an options object', done => { + const OPTIONS = {}; + + table.createReadStream = (keyVals, options) => { + assert.strictEqual(OPTIONS, options); + + const stream = through.obj(); + + setImmediate(() => { + stream.end(); + }); + + return stream; + }; + + table.read([], OPTIONS, done); + }); + + it('should execute callback with error', done => { + const error = new Error('Error.'); + + table.createReadStream = () => { + const stream = through.obj(); + setImmediate(() => { + stream.destroy(error); + }); + return stream; + }; + + table.read([], err => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('replace', () => { + const ROW = {}; + + it('should return any runTransaction errors', done => { + const fakeError = new Error('err'); + + sandbox + .stub(DATABASE, 'runTransaction') + .callsFake((opts, callback) => callback(fakeError)); + + table.replace(ROW, err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should replace via transaction', done => { + const stub = ( + sandbox.stub(transaction, 'replace') as sinon.SinonStub + ).withArgs(table.name, ROW); + + table.replace(ROW, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + done(); + }); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + (sandbox.stub(transaction, 'replace') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, gaxOptions); + done(); + }; + + table.replace(ROW, gaxOptions, assert.ifError); + }); + + it('should accept commit options', done => { + const replaceRowsOptions = {returnCommitStats: true}; + (sandbox.stub(transaction, 'replace') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, replaceRowsOptions); + done(); + }; + + table.replace(ROW, replaceRowsOptions, assert.ifError); + }); + + it('should accept gax options in commit options', done => { + const replaceRowsOptions = { + returnCommitStats: true, + gaxOptions: {}, + }; + (sandbox.stub(transaction, 'replace') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, replaceRowsOptions); + done(); + }; + + table.replace(ROW, replaceRowsOptions, assert.ifError); + }); + + it('should accept requestOptions', done => { + const replaceRowsOptions = { + requestOptions: {priority: RequestOptions.Priority.PRIORITY_HIGH}, + }; + (sandbox.stub(transaction, 'replace') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, replaceRowsOptions); + done(); + }; + + table.replace(ROW, replaceRowsOptions, assert.ifError); + }); + + it('should accept isolationLevel options', done => { + const replaceRowsOptions = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + (sandbox.stub(transaction, 'replace') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, replaceRowsOptions); + done(); + }; + + table.replace(ROW, replaceRowsOptions, assert.ifError); + }); + + it('should accept readLockMode options', done => { + const replaceRowsOptions = { + readLockMode: ReadLockMode.OPTIMISTIC, + }; + (sandbox.stub(transaction, 'replace') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, replaceRowsOptions); + done(); + }; + + table.replace(ROW, replaceRowsOptions, assert.ifError); + }); + }); + + describe('update', () => { + const ROW = {}; + + it('should return any runTransaction errors', done => { + const fakeError = new Error('err'); + + sandbox + .stub(DATABASE, 'runTransaction') + .callsFake((opts, callback) => callback(fakeError)); + + table.update(ROW, err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should update via transaction', done => { + const stub = ( + sandbox.stub(transaction, 'update') as sinon.SinonStub + ).withArgs(table.name, ROW); + + table.update(ROW, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + done(); + }); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + (sandbox.stub(transaction, 'update') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, gaxOptions); + done(); + }; + + table.update(ROW, gaxOptions, assert.ifError); + }); + + it('should accept commit options', done => { + const updateRowsOptions = {returnCommitStats: true}; + (sandbox.stub(transaction, 'update') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, updateRowsOptions); + done(); + }; + + table.update(ROW, updateRowsOptions, assert.ifError); + }); + + it('should accept gax options in commit options', done => { + const updateRowsOptions = { + returnCommitStats: true, + gaxOptions: {}, + }; + (sandbox.stub(transaction, 'update') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, updateRowsOptions); + done(); + }; + + table.update(ROW, updateRowsOptions, assert.ifError); + }); + + it('should accept requestOptions', done => { + const updateRowsOptions = { + requestOptions: {priority: RequestOptions.Priority.PRIORITY_LOW}, + }; + (sandbox.stub(transaction, 'update') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, updateRowsOptions); + done(); + }; + + table.update(ROW, updateRowsOptions, assert.ifError); + }); + + it('should accept isolationLevel option', done => { + const updateRowsOptions = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + (sandbox.stub(transaction, 'update') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, updateRowsOptions); + done(); + }; + + table.update(ROW, updateRowsOptions, assert.ifError); + }); + + it('should accept readLockMode option', done => { + const updateRowsOptions = { + readLockMode: ReadLockMode.OPTIMISTIC, + }; + (sandbox.stub(transaction, 'update') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, updateRowsOptions); + done(); + }; + + table.update(ROW, updateRowsOptions, assert.ifError); + }); + }); + + describe('upsert', () => { + const ROW = {}; + + it('should return any runTransaction errors', done => { + const fakeError = new Error('err'); + + sandbox + .stub(DATABASE, 'runTransaction') + .callsFake((opts, callback) => callback(fakeError)); + + table.upsert(ROW, err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should upsert via transaction', done => { + const stub = ( + sandbox.stub(transaction, 'upsert') as sinon.SinonStub + ).withArgs(table.name, ROW); + + table.upsert(ROW, err => { + assert.ifError(err); + assert.strictEqual(stub.callCount, 1); + done(); + }); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + (sandbox.stub(transaction, 'upsert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, gaxOptions); + done(); + }; + + table.upsert(ROW, gaxOptions, assert.ifError); + }); + + it('should accept commit options', done => { + const upsertRowsOptions = {returnCommitStats: true}; + (sandbox.stub(transaction, 'upsert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, upsertRowsOptions); + done(); + }; + + table.upsert(ROW, upsertRowsOptions, assert.ifError); + }); + + it('should accept gax options in commit options', done => { + const upsertRowsOptions = { + returnCommitStats: true, + gaxOptions: {}, + }; + (sandbox.stub(transaction, 'upsert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, upsertRowsOptions); + done(); + }; + + table.upsert(ROW, upsertRowsOptions, assert.ifError); + }); + + it('should accept requestOptions', done => { + const upsertRowsOptions = { + requestOptions: {priority: RequestOptions.Priority.PRIORITY_MEDIUM}, + }; + (sandbox.stub(transaction, 'upsert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, upsertRowsOptions); + done(); + }; + + table.upsert(ROW, upsertRowsOptions, assert.ifError); + }); + + it('should accept isolationLevel option', done => { + const upsertRowsOptions = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + }; + (sandbox.stub(transaction, 'upsert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, upsertRowsOptions); + done(); + }; + + table.upsert(ROW, upsertRowsOptions, assert.ifError); + }); + + it('should accept readLockMode option', done => { + const upsertRowsOptions = { + readLockMode: ReadLockMode.OPTIMISTIC, + }; + (sandbox.stub(transaction, 'upsert') as sinon.SinonStub).withArgs( + table.name, + ROW, + ); + transaction.commit = options => { + assert.strictEqual(options, upsertRowsOptions); + done(); + }; + + table.upsert(ROW, upsertRowsOptions, assert.ifError); + }); + }); +}); diff --git a/handwritten/spanner/test/transaction-runner.ts b/handwritten/spanner/test/transaction-runner.ts new file mode 100644 index 00000000000..bd3fac82cc1 --- /dev/null +++ b/handwritten/spanner/test/transaction-runner.ts @@ -0,0 +1,671 @@ +/*! + * Copyright 2019 Google Inc. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import {EventEmitter} from 'events'; +import {grpc} from 'google-gax'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; +import * as through from 'through2'; +import {RunTransactionOptions} from '../src/transaction-runner'; +import {google} from '../protos/protos'; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import {randomUUID} from 'crypto'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const concat = require('concat-stream'); + +class FakeTransaction extends EventEmitter { + multiplexedSessionPreviousTransactionId; + async begin(): Promise {} + request() {} + requestStream() {} + useInRunner() {} + setReadWriteTransactionOptions(options: RunTransactionOptions) {} +} + +describe('TransactionRunner', () => { + const sandbox = sinon.createSandbox(); + + const RETRY_KEY = 'google.rpc.retryinfo-bin'; + const DECODE = sandbox.stub(); + + const RETRY_INFO = { + decode: DECODE, + }; + + const LOOKUP = sandbox.stub().withArgs(RETRY_KEY).returns(RETRY_INFO); + const FROM_JSON = sandbox.stub().returns({lookup: LOOKUP}); + + const SESSION = { + parent: {}, + transaction: () => fakeTransaction, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Runner; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let TransactionRunner; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let AsyncTransactionRunner; + + let fakeTransaction; + + before(() => { + const runners = proxyquire('../src/transaction-runner', { + protobufjs: {Root: {fromJSON: FROM_JSON}}, + }); + + Runner = runners.Runner; + TransactionRunner = runners.TransactionRunner; + AsyncTransactionRunner = runners.AsyncTransactionRunner; + }); + + beforeEach(() => { + fakeTransaction = new FakeTransaction(); + sandbox.stub(fakeTransaction, 'begin').resolves(); + sandbox.stub(fakeTransaction, 'request'); + sandbox.stub(fakeTransaction, 'requestStream'); + }); + + afterEach(() => sandbox.restore()); + + describe('Runner', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let ExtendedRunner; + + let runFn; + let runner; + + beforeEach(() => { + runFn = sandbox.stub(); + + ExtendedRunner = class ExtendedRunner extends Runner { + protected async _run(transaction): Promise { + return runFn(transaction); + } + }; + + runner = new ExtendedRunner(SESSION, fakeTransaction); + }); + + describe('initialization', () => { + it('should initialize `attempts` to 0', () => { + assert.strictEqual(runner.attempts, 0); + }); + + it('should localize the `session`', () => { + assert.strictEqual(runner.session, SESSION); + }); + + it('should localize the `transaction`', () => { + assert.strictEqual(runner.transaction, fakeTransaction); + }); + + it('should set default `options`', () => { + const expectedOptions = { + timeout: 3600000, + isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED, + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }; + + assert.deepStrictEqual(runner.options, expectedOptions); + }); + + it('should accept user `options`', () => { + const options = { + isolationLevel: IsolationLevel.SERIALIZABLE, + readLockMode: ReadLockMode.OPTIMISTIC, + timeout: 1000, + }; + const r = new ExtendedRunner(SESSION, fakeTransaction, options); + + assert.deepStrictEqual(r.options, options); + assert.notStrictEqual(r.options, options); + }); + }); + + describe('getNextDelay', () => { + const FAKE_RETRY_INFO = Buffer.from('fake-retry-info'); + + const FAKE_ERROR = new Error('err') as grpc.ServiceError; + FAKE_ERROR.metadata = new grpc.Metadata(); + FAKE_ERROR.metadata.set(RETRY_KEY, FAKE_RETRY_INFO); + + it('should extract `retryInfo` when available', () => { + const fakeRetryDelay = { + nanos: 10, + seconds: 5, + }; + + DECODE.withArgs(FAKE_RETRY_INFO).returns({retryDelay: fakeRetryDelay}); + + const expectedDelay = 5000.00001; + const delay = runner.getNextDelay(FAKE_ERROR); + + assert.strictEqual(delay, expectedDelay); + }); + + it('should check if `seconds` is a Long', () => { + const fakeRetryDelay = { + nanos: 10, + seconds: {toNumber: () => 5}, + }; + + DECODE.withArgs(FAKE_RETRY_INFO).returns({retryDelay: fakeRetryDelay}); + + const expectedDelay = 5000.00001; + const delay = runner.getNextDelay(FAKE_ERROR); + + assert.strictEqual(delay, expectedDelay); + }); + + it('should create a backoff when `retryInfo` is absent', () => { + const random = Math.random(); + + runner.attempts = 3; + sandbox.stub(global.Math, 'random').returns(random); + + const badError = new Error('err') as grpc.ServiceError; + badError.metadata = new grpc.Metadata(); + + const expectedDelay = Math.pow(2, 3) * 1000 + Math.floor(random * 1000); + const delay = runner.getNextDelay(badError); + + assert.strictEqual(delay, expectedDelay); + }); + + it('should use a backoff of max 32 seconds when `retryInfo` is absent', () => { + const random = Math.random(); + + runner.attempts = 10; + sandbox.stub(global.Math, 'random').returns(random); + + const badError = new Error('err') as grpc.ServiceError; + badError.metadata = new grpc.Metadata(); + + const expectedDelay = Math.pow(2, 5) * 1000 + Math.floor(random * 1000); + const delay = runner.getNextDelay(badError); + + assert.strictEqual(delay, expectedDelay); + }); + }); + + describe('getTransaction', () => { + it('should return and forget the prepared transaction', async () => { + sandbox + .stub(SESSION, 'transaction') + .throws(new Error('Should not be called')); + + const cachedTransaction = runner.transaction; + const transaction = await runner.getTransaction(); + + assert.strictEqual(transaction, cachedTransaction); + assert.strictEqual(runner.transaction, undefined); + }); + + it('should create a new transaction if need be', async () => { + const expectedTransaction = new FakeTransaction(); + const beginStub = sandbox.stub(expectedTransaction, 'begin').resolves(); + + sandbox.stub(SESSION, 'transaction').returns(expectedTransaction); + delete runner.transaction; + + const transaction = await runner.getTransaction(); + + assert.strictEqual(transaction, expectedTransaction); + assert.strictEqual(beginStub.callCount, 0); + runner.attempts++; + await runner.getTransaction(); + assert.strictEqual(beginStub.callCount, 1); + }); + + describe('when multiplexed session is enabled for read/write transaction', () => { + it('should set the multiplexedSessionPreviousTransactionId in the new transaction object', async () => { + const expectedTransaction = new FakeTransaction(); + const fakePreviousTransactionId = 'fake-transaction-id'; + sandbox.stub(expectedTransaction, 'begin').resolves(); + + sandbox.stub(SESSION, 'transaction').returns(expectedTransaction); + delete runner.transaction; + + runner.multiplexedSessionPreviousTransactionId = + fakePreviousTransactionId; + + // multiplexed session + runner.session = Object.assign({multiplexed: true}, SESSION); + + const transaction = await runner.getTransaction(); + + assert.strictEqual( + transaction.multiplexedSessionPreviousTransactionId, + fakePreviousTransactionId, + ); + }); + }); + }); + + describe('run', () => { + let getTransactionStub; + beforeEach(() => { + getTransactionStub = sandbox + .stub(runner, 'getTransaction') + .resolves(fakeTransaction); + }); + + it('should run a transaction', async () => { + await runner.run(); + + const transaction = runFn.lastCall.args[0]; + + assert.strictEqual(transaction, fakeTransaction); + assert.strictEqual(runFn.callCount, 1); + }); + + it('should return the transaction results', async () => { + const fakeReturnValue = 10; + + runFn.resolves(fakeReturnValue); + + const returnVal = await runner.run(); + + assert.strictEqual(returnVal, fakeReturnValue); + }); + + it('should reject for non-retryable errors', done => { + const fakeError = new Error('err') as grpc.ServiceError; + fakeError.code = grpc.status.UNKNOWN; + + runFn.rejects(fakeError); + + runner.run().catch(err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should retry on ABORTED errors', async () => { + const fakeReturnValue = 11; + const fakeError = new Error('err') as grpc.ServiceError; + fakeError.code = grpc.status.ABORTED; + + runFn.onCall(0).rejects(fakeError); + runFn.onCall(1).resolves(fakeReturnValue); + + const delayStub = sandbox + .stub(runner, 'getNextDelay') + .withArgs(fakeError) + .returns(0); + + const returnValue = await runner.run(); + + assert.strictEqual(returnValue, fakeReturnValue); + assert.strictEqual(runner.attempts, 1); + assert.strictEqual(delayStub.callCount, 1); + }); + + it('should throw a DeadlineError if the timeout is exceeded', done => { + const fakeError = new Error('err') as grpc.ServiceError; + fakeError.code = grpc.status.ABORTED; + + runFn.onCall(0).rejects(fakeError); + sandbox.stub(runner, 'getNextDelay').returns(2); + runner.options.timeout = 1; + + runner + .run() + .then(() => { + done(new Error('missing expected DEADLINE_EXCEEDED error')); + }) + .catch(err => { + assert.strictEqual(err.code, grpc.status.DEADLINE_EXCEEDED); + assert.deepStrictEqual(err.errors, [fakeError]); + done(); + }); + }); + + describe('when multiplexed session is enabled for read/write', () => { + it('should update the multiplexedSessionPreviousTransactionId before retrying aborted transaction', async () => { + const fakeReturnValue = 12; + const fakeError = new Error('err') as grpc.ServiceError; + fakeError.code = grpc.status.ABORTED; + + const fakeTransaction1 = Object.assign( + {id: randomUUID()}, + new FakeTransaction(), + ); + const fakeTransaction2 = Object.assign( + {id: randomUUID()}, + new FakeTransaction(), + ); + const fakeTransaction3 = Object.assign( + {id: randomUUID()}, + new FakeTransaction(), + ); + + getTransactionStub.onCall(0).resolves(fakeTransaction1); + getTransactionStub.onCall(1).resolves(fakeTransaction2); + getTransactionStub.onCall(2).resolves(fakeTransaction3); + + runFn.onCall(0).callsFake(() => { + // assert on first call the multiplexedSessionPreviousTransactionId is set to undefined + assert.strictEqual( + runner.multiplexedSessionPreviousTransactionId, + undefined, + ); + return Promise.reject(fakeError); + }); + + // first retry + runFn.onCall(1).callsFake(() => { + // assert on second call the multiplexedSessionPreviousTransactionId is set to first transaction id + assert.strictEqual( + runner.multiplexedSessionPreviousTransactionId, + fakeTransaction1.id, + ); + return Promise.reject(fakeError); + }); + + // second retry + runFn.onCall(2).callsFake(() => { + // assert on third call multiplexedSessionPreviousTransactionId is set to second transaction id + assert.strictEqual( + runner.multiplexedSessionPreviousTransactionId, + fakeTransaction2.id, + ); + return Promise.resolve(fakeReturnValue); + }); + + const delayStub = sandbox + .stub(runner, 'getNextDelay') + .withArgs(fakeError) + .returns(0); + + const returnValue = await runner.run(); + + assert.strictEqual(returnValue, fakeReturnValue); + // assert that retry happens twice + assert.strictEqual(runner.attempts, 2); + assert.strictEqual(delayStub.callCount, 2); + }); + }); + }); + }); + + describe('TransactionRunner', () => { + let runFn; + let runner; + + beforeEach(() => { + runFn = sandbox.stub(); + runner = new TransactionRunner(SESSION, fakeTransaction, runFn); + sandbox.stub(runner, 'getNextDelay').returns(0); + }); + + describe('initialization', () => { + it('should pass the `session` to `Runner`', () => { + assert.strictEqual(runner.session, SESSION); + }); + + it('should pass the `transaction` to `Runner`', () => { + assert.strictEqual(runner.transaction, fakeTransaction); + }); + + it('should pass `options` to `Runner`', () => { + const options = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + readLockMode: ReadLockMode.PESSIMISTIC, + timeout: 1, + }; + const r = new TransactionRunner( + SESSION, + fakeTransaction, + runFn, + options, + ); + + assert.deepStrictEqual(r.options, options); + }); + + it('should localize the `runFn`', () => { + assert.strictEqual(runner.runFn, runFn); + }); + }); + + describe('run', () => { + it('should correctly call the `runFn`', async () => { + setImmediate(() => fakeTransaction.emit('end')); + await runner.run(); + + const {args} = runFn.lastCall; + + assert.deepStrictEqual(args, [null, fakeTransaction]); + }); + + describe('transaction requests', () => { + const CONFIG = {}; + + let callbackStub; + + beforeEach(() => { + callbackStub = sandbox.spy(); + + runFn.callsFake((err, transaction) => { + assert.ifError(err); + transaction.request(CONFIG, callbackStub); + }); + }); + + it('should return the request response', async () => { + const fakeResponse = {}; + + fakeTransaction.request.withArgs(CONFIG).callsFake((_, callback) => { + callback(null, fakeResponse); + setImmediate(() => fakeTransaction.emit('end')); + }); + + await runner.run(); + + const [error, response] = callbackStub.lastCall.args; + + assert.strictEqual(error, null); + assert.strictEqual(response, fakeResponse); + assert.strictEqual(runFn.callCount, 1); + }); + + it('should return non-retryable request errors', async () => { + const fakeError = new Error('err') as grpc.ServiceError; + fakeError.code = grpc.status.UNKNOWN; + + fakeTransaction.request.withArgs(CONFIG).callsFake((_, callback) => { + callback(fakeError); + setImmediate(() => fakeTransaction.emit('end')); + }); + + await runner.run(); + + const error = callbackStub.lastCall.args[0]; + + assert.strictEqual(error, fakeError); + assert.strictEqual(callbackStub.callCount, 1); + assert.strictEqual(runFn.callCount, 1); + }); + + it('should intercept ABORTED request errors', async () => { + const fakeError = new Error('err') as grpc.ServiceError; + fakeError.code = grpc.status.ABORTED; + + fakeTransaction.request + .onCall(0) + .callsFake((_, callback) => callback(fakeError)); + + fakeTransaction.request.onCall(1).callsFake((_, callback) => { + callback(null); + setImmediate(() => fakeTransaction.emit('end')); + }); + + await runner.run(); + + assert.strictEqual(callbackStub.callCount, 1); + assert.strictEqual(runFn.callCount, 2); + }); + }); + + describe('transaction streams', () => { + const CONFIG = {}; + + it('should pipe the data through', done => { + const fakeStream = through.obj(); + fakeTransaction.requestStream.withArgs(CONFIG).returns(fakeStream); + + const fakeData = [{a: 'b'}, {c: 'd'}, {e: 'f'}]; + fakeData.forEach(data => fakeStream.push(data)); + fakeStream.push(null); + + runFn.callsFake((err, transaction) => { + assert.ifError(err); + + transaction.requestStream(CONFIG).pipe( + concat(data => { + assert.deepStrictEqual(data, fakeData); + done(); + }), + ); + }); + + runner.run().catch(done); + }); + + it('should destroy on non-retryable streaming errors', done => { + const fakeStream = through.obj(); + fakeTransaction.requestStream.withArgs(CONFIG).returns(fakeStream); + + const fakeError = new Error('err') as grpc.ServiceError; + fakeError.code = grpc.status.UNKNOWN; + + runFn.callsFake((err, transaction) => { + assert.ifError(err); + + transaction.requestStream(CONFIG).on('error', err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + runner.run().catch(done); + setImmediate(() => fakeStream.destroy(fakeError)); + }); + + it('should intercept ABORTED streaming errors', done => { + const badStream = through.obj(); + const goodStream = through.obj(); + + const fakeError = new Error('err') as grpc.ServiceError; + fakeError.code = grpc.status.ABORTED; + + const fakeData = [{a: 'b'}, {c: 'd'}, {e: 'f'}]; + fakeData.forEach(data => goodStream.push(data)); + goodStream.push(null); + + fakeTransaction.requestStream.onCall(0).returns(badStream); + fakeTransaction.requestStream.onCall(1).returns(goodStream); + + runFn.callsFake((err, transaction) => { + assert.ifError(err); + + transaction + .requestStream(CONFIG) + .on('error', done) + .pipe( + concat(data => { + assert.deepStrictEqual(data, fakeData); + assert.strictEqual(runFn.callCount, 2); + done(); + }), + ); + }); + + runner.run().catch(done); + setImmediate(() => badStream.destroy(fakeError)); + }); + }); + }); + }); + + describe('AsyncTransactionRunner', () => { + let runFn; + let runner; + + beforeEach(() => { + runFn = sandbox.stub(); + runner = new AsyncTransactionRunner(SESSION, fakeTransaction, runFn); + sandbox.stub(runner, 'getNextDelay').returns(0); + }); + + describe('initialization', () => { + it('should pass the `session` to `Runner`', () => { + assert.strictEqual(runner.session, SESSION); + }); + + it('should pass the `transaction` to `Runner`', () => { + assert.strictEqual(runner.transaction, fakeTransaction); + }); + + it('should pass `options` to `Runner`', () => { + const options = { + isolationLevel: IsolationLevel.REPEATABLE_READ, + readLockMode: ReadLockMode.OPTIMISTIC, + timeout: 1, + }; + const r = new AsyncTransactionRunner( + SESSION, + fakeTransaction, + runFn, + options, + ); + + assert.deepStrictEqual(r.options, options); + }); + + it('should localize the `runFn`', () => { + assert.strictEqual(runner.runFn, runFn); + }); + }); + + describe('run', () => { + it('should correctly call the `runFn`', async () => { + runFn.resolves(); + await runner.run(); + + const {args} = runFn.lastCall; + + assert.deepStrictEqual(args, [fakeTransaction]); + }); + + it('should resolve with the `runFn` return value', async () => { + const fakeReturnValue = 'abc'; + + runFn.resolves(fakeReturnValue); + + const returnValue = await runner.run(); + + assert.strictEqual(returnValue, fakeReturnValue); + }); + }); + }); +}); diff --git a/handwritten/spanner/test/transaction.ts b/handwritten/spanner/test/transaction.ts new file mode 100644 index 00000000000..4c7f4aae217 --- /dev/null +++ b/handwritten/spanner/test/transaction.ts @@ -0,0 +1,3005 @@ +/*! + * Copyright 2017 Google Inc. All Rights Reserved. + * + * 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 {PreciseDate} from '@google-cloud/precise-date'; +import * as assert from 'assert'; +import {before, beforeEach, afterEach, describe, it} from 'mocha'; +import {EventEmitter} from 'events'; +import {common as p} from 'protobufjs'; +import * as proxyquire from 'proxyquire'; +import * as sinon from 'sinon'; + +import {protos} from '../src'; +import {codec} from '../src/codec'; +import {google} from '../protos/protos'; +import { + CLOUD_RESOURCE_HEADER, + LEADER_AWARE_ROUTING_HEADER, + AFE_SERVER_TIMING_HEADER, +} from '../src/common'; +import { + X_GOOG_SPANNER_REQUEST_ID_HEADER, + craftRequestId, +} from '../src/request_id_header'; +import RequestOptions = google.spanner.v1.RequestOptions; +import ReadLockMode = google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel; +import { + BatchUpdateOptions, + ExecuteSqlRequest, + ReadRequest, +} from '../src/transaction'; +import {grpc} from 'google-gax'; + +describe('Transaction', () => { + const sandbox = sinon.createSandbox(); + + const REQUEST = sandbox.stub(); + const REQUEST_STREAM = sandbox.stub(); + const SESSION_NAME = 'session-123'; + + const SPANNER = { + routeToLeaderEnabled: true, + directedReadOptions: {}, + defaultTransactionOptions: { + isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED, + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }, + }; + + const INSTANCE = { + parent: SPANNER, + }; + + const DATABASE = { + formattedName_: 'formatted-database-name', + parent: INSTANCE, + }; + + const SESSION = { + parent: DATABASE, + formattedName_: SESSION_NAME, + request: REQUEST, + requestStream: REQUEST_STREAM, + }; + + const PARTIAL_RESULT_STREAM = sandbox.stub(); + const PROMISIFY_ALL = sandbox.stub(); + + const fakeDirectedReadOptions = { + includeReplicas: { + replicaSelections: [ + { + location: 'us-west1', + type: protos.google.spanner.v1.DirectedReadOptions.ReplicaSelection + .Type.READ_ONLY, + }, + ], + autoFailoverDisabled: true, + }, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Snapshot; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Dml; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Transaction; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let PartitionedDml; + + before(() => { + const txns = proxyquire('../src/transaction', { + '@google-cloud/promisify': {promisifyAll: PROMISIFY_ALL}, + './codec': {codec}, + './partial-result-stream': {partialResultStream: PARTIAL_RESULT_STREAM}, + }); + + Snapshot = txns.Snapshot; + Dml = txns.Dml; + Transaction = txns.Transaction; + PartitionedDml = txns.PartitionedDml; + }); + + afterEach(() => sandbox.restore()); + + describe('Snapshot', () => { + const OPTIONS = {a: 'b', c: 'd'}; + + let snapshot; + + beforeEach(() => { + sandbox.stub(Snapshot, 'encodeTimestampBounds').returns(OPTIONS); + snapshot = new Snapshot(SESSION); + }); + + describe('initialization', () => { + it('should promisify all the things', () => { + const expectedOptions = sinon.match({ + exclude: ['configureTagOptions', 'end'], + }); + + const stub = PROMISIFY_ALL.withArgs(Snapshot, expectedOptions); + + assert.strictEqual(stub.callCount, 1); + }); + + it('should extend EventEmitter', () => { + assert(snapshot instanceof EventEmitter); + }); + + it('should default `ended` to false', () => { + assert.strictEqual(snapshot.ended, false); + }); + + it('should localize the session', () => { + assert.strictEqual(snapshot.session, SESSION); + }); + + it('should localize `Session#request`', () => { + snapshot.request(); + assert.strictEqual(REQUEST.callCount, 1); + }); + + it('should localize `Session#requestStream`', () => { + snapshot.requestStream(); + assert.strictEqual(REQUEST_STREAM.callCount, 1); + }); + + it('should set the commonHeaders_', () => { + assert.deepStrictEqual(snapshot.commonHeaders_, { + [CLOUD_RESOURCE_HEADER]: snapshot.session.parent.formattedName_, + [AFE_SERVER_TIMING_HEADER]: 'true', + }); + }); + }); + + describe('begin', () => { + const BEGIN_RESPONSE = { + id: Buffer.from('transaction-id-123'), + }; + + it('should send the correct request', () => { + snapshot.begin(); + + const {client, method, reqOpts, gaxOpts, headers} = + REQUEST.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'beginTransaction'); + assert.strictEqual(reqOpts.session, SESSION_NAME); + assert.deepStrictEqual(gaxOpts, {}); + assert.deepStrictEqual(headers, snapshot.commonHeaders_); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = { + timeout: 1000, + }; + + snapshot.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + + snapshot.begin(gaxOptions); + }); + + it('should send the formatted options', () => { + const fakeOptions = {a: 'b'}; + const fakeEncodedOptions = {c: 'd'}; + const expectedOptions = {readOnly: fakeEncodedOptions}; + + Snapshot.encodeTimestampBounds + .withArgs(fakeOptions) + .returns(fakeEncodedOptions); + + new Snapshot(SESSION, fakeOptions).begin(); + + const {reqOpts} = REQUEST.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.options, expectedOptions); + }); + + it('should return any request errors', done => { + const fakeError = new Error('err'); + + REQUEST.callsFake((_, callback) => callback(fakeError)); + + snapshot.begin(err => { + assert.strictEqual(err, fakeError); + done(); + }); + }); + + it('should localize `id`', done => { + REQUEST.callsFake((_, callback) => callback(null, BEGIN_RESPONSE)); + + snapshot.begin(err => { + assert.ifError(err); + assert.strictEqual(snapshot.id, BEGIN_RESPONSE.id); + done(); + }); + }); + + it('should localize the response as `metadata`', done => { + REQUEST.callsFake((_, callback) => callback(null, BEGIN_RESPONSE)); + + snapshot.begin(err => { + assert.ifError(err); + assert.strictEqual(snapshot.metadata, BEGIN_RESPONSE); + done(); + }); + }); + + it('should localize `readTimestamp` if present', done => { + const expectedTimestamp = new PreciseDate(0); + const readTimestamp = {seconds: 0, nanos: 0}; + const response = Object.assign({readTimestamp}, BEGIN_RESPONSE); + + REQUEST.callsFake((_, callback) => callback(null, response)); + + snapshot.begin(err => { + assert.ifError(err); + assert.deepStrictEqual(snapshot.readTimestamp, expectedTimestamp); + assert.strictEqual(snapshot.readTimestampProto, readTimestamp); + done(); + }); + }); + + it('should localize precommitToken if present', done => { + const precommitToken = { + precommitToken: Buffer.from('precommit-token-begin'), + seqNum: 1, + }; + const response = Object.assign({precommitToken}, BEGIN_RESPONSE); + + REQUEST.callsFake((_, callback) => callback(null, response)); + + snapshot.begin(err => { + assert.ifError(err); + assert.strictEqual(snapshot._latestPreCommitToken, precommitToken); + done(); + }); + }); + + it('should return the response', done => { + REQUEST.callsFake((_, callback) => callback(null, BEGIN_RESPONSE)); + + snapshot.begin((err, resp) => { + assert.ifError(err); + assert.strictEqual(resp, BEGIN_RESPONSE); + done(); + }); + }); + }); + + describe('createReadStream', () => { + const TABLE = 'my-table-123'; + + beforeEach(() => { + PARTIAL_RESULT_STREAM.callsFake(makeRequest => makeRequest()); + }); + + it('should send the correct request', () => { + snapshot.createReadStream(TABLE); + + const {client, method, headers} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'streamingRead'); + assert.deepStrictEqual(headers, { + ...snapshot.commonHeaders_, + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + }); + }); + + it('should use the transaction id if present', () => { + const id = 'transaction-id-123'; + const expectedTransaction = {id}; + + snapshot.id = id; + snapshot.createReadStream(TABLE); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.transaction, expectedTransaction); + }); + + it('should configure `singleUse` if id is absent', () => { + const expectedTransaction = { + singleUse: {readOnly: OPTIONS}, + }; + + snapshot.createReadStream(TABLE); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.transaction, expectedTransaction); + }); + + it('should set request tag', () => { + const requestTag = 'foo'; + const request: ReadRequest = {requestOptions: {requestTag}}; + + snapshot.createReadStream(TABLE, request); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.requestOptions, {requestTag}); + }); + + it('should send the correct `reqOpts`', () => { + const id = 'transaction-id-123'; + const fakeKeySet = {all: true}; + + const fakeRequest = { + keys: ['a', 'b', 'c'], + ranges: [{}, {}], + columns: ['name'], + directedReadOptions: fakeDirectedReadOptions, + }; + + const expectedRequest = { + session: SESSION_NAME, + requestOptions: {}, + transaction: {id}, + table: TABLE, + keySet: fakeKeySet, + resumeToken: undefined, + columns: ['name'], + directedReadOptions: fakeDirectedReadOptions, + }; + + sandbox + .stub(Snapshot, 'encodeKeySet') + .withArgs(fakeRequest) + .returns(fakeKeySet); + + snapshot.id = id; + snapshot.createReadStream(TABLE, fakeRequest); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts, expectedRequest); + }); + + it('should pass along `gaxOpts`', () => { + const fakeOptions = {}; + + snapshot.createReadStream(TABLE, {gaxOptions: fakeOptions}); + + const {gaxOpts, reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(gaxOpts, fakeOptions); + assert.strictEqual(reqOpts.gaxOptions, undefined); + }); + + it('should pass a stream to `PartialResultStream`', () => { + const fakeStream = new EventEmitter(); + + REQUEST_STREAM.returns(fakeStream); + snapshot.createReadStream(TABLE); + + const makeRequest = PARTIAL_RESULT_STREAM.lastCall.args[0]; + const stream = makeRequest(); + + assert.strictEqual(stream, fakeStream); + }); + + it('should update the `resumeToken` for subsequent requests', () => { + const fakeToken = 'fake-token-123'; + + PARTIAL_RESULT_STREAM.callsFake(makeRequest => makeRequest(fakeToken)); + snapshot.createReadStream(TABLE); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(reqOpts.resumeToken, fakeToken); + }); + + it('should return a `PartialResultStream`', () => { + const fakeStream = new EventEmitter(); + + PARTIAL_RESULT_STREAM.returns(fakeStream); + + const stream = snapshot.createReadStream(TABLE); + + assert.strictEqual(stream, fakeStream); + }); + + it('should pass along row options', () => { + const gaxOptions = { + timeout: 60, + }; + const fakeOptions = { + json: true, + jsonOptions: {a: 'b'}, + maxResumeRetries: 10, + columnsMetadata: {column1: {test: 'ss'}, column2: Function}, + gaxOptions: gaxOptions, + }; + + snapshot.createReadStream(TABLE, fakeOptions); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(reqOpts.json, undefined); + assert.strictEqual(reqOpts.jsonOptions, undefined); + assert.strictEqual(reqOpts.maxResumeRetries, undefined); + + const options = PARTIAL_RESULT_STREAM.lastCall.args[1]; + + assert.deepStrictEqual(options, fakeOptions); + }); + + it('should accept directedReadOptions set for client', () => { + const id = 'transaction-id-123'; + SESSION.parent.parent.parent = { + routeToLeaderEnabled: true, + directedReadOptions: fakeDirectedReadOptions, + defaultTransactionOptions: { + isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED, + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }, + }; + + const expectedRequest = { + session: SESSION_NAME, + requestOptions: {}, + transaction: {id}, + table: TABLE, + keySet: {all: true}, + resumeToken: undefined, + directedReadOptions: fakeDirectedReadOptions, + }; + + snapshot.id = id; + snapshot.createReadStream(TABLE); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts, expectedRequest); + }); + + it('should override directedReadOptions set at client level when passed at request level', () => { + const id = 'transaction-id-123'; + const fakeDirectedReadOptionsForRequest = { + includeReplicas: { + replicaSelections: [ + { + location: 'us-east1', + }, + ], + }, + }; + + const fakeRequest = { + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + SESSION.parent.parent.parent = { + routeToLeaderEnabled: true, + directedReadOptions: fakeDirectedReadOptions, + defaultTransactionOptions: { + isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED, + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }, + }; + + const expectedRequest = { + session: SESSION_NAME, + requestOptions: {}, + transaction: {id}, + table: TABLE, + keySet: {all: true}, + resumeToken: undefined, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + snapshot.id = id; + snapshot.createReadStream(TABLE, fakeRequest); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts, expectedRequest); + }); + }); + + describe('end', () => { + it('should set `ended` to true', () => { + snapshot.end(); + + assert.strictEqual(snapshot.ended, true); + }); + + it('should emit an "end" event', done => { + snapshot.on('end', done); + snapshot.end(); + }); + + it('should noop if already ended', done => { + snapshot.on('end', done); + snapshot.end(); + snapshot.end(); + }); + }); + + describe('read', () => { + const TABLE = 'my-table-123'; + + let fakeStream; + let stub; + + beforeEach(() => { + fakeStream = new EventEmitter(); + stub = sandbox.stub(snapshot, 'createReadStream').returns(fakeStream); + }); + + it('should call through to `createReadStream`', () => { + const fakeRequest = {}; + + snapshot.read(TABLE, fakeRequest, () => {}); + + const [table, request] = stub.lastCall.args; + + assert.strictEqual(table, TABLE); + assert.strictEqual(request, fakeRequest); + }); + + it('should return any request errors', done => { + const fakeError = new Error('err'); + + snapshot.read(TABLE, {}, err => { + assert.strictEqual(err, fakeError); + done(); + }); + + fakeStream.emit('error', fakeError); + }); + + it('should concatenate rows and return them on "end" event', done => { + const fakeRows = [{a: 'b'}, {c: 'd'}, {e: 'f'}]; + + snapshot.read(TABLE, {}, (err, rows) => { + assert.ifError(err); + assert.deepStrictEqual(rows, fakeRows); + done(); + }); + + fakeRows.forEach(row => fakeStream.emit('data', row)); + fakeStream.emit('end'); + }); + + it('should optionally accept a request object', done => { + snapshot.read(TABLE, done); + fakeStream.emit('end'); + }); + }); + + describe('run', () => { + const QUERY = 'SELET * FROM `MyTable`'; + + let fakeStream; + let stub; + + beforeEach(() => { + fakeStream = new EventEmitter(); + stub = sandbox.stub(snapshot, 'runStream').returns(fakeStream); + }); + + it('should call through to `runStream`', () => { + snapshot.run(QUERY, () => {}); + + const query = stub.lastCall.args[0]; + + assert.strictEqual(query, QUERY); + }); + + it('should return any request errors', done => { + const fakeError = new Error('err'); + + snapshot.run(QUERY, err => { + assert.strictEqual(err, fakeError); + done(); + }); + + fakeStream.emit('error', fakeError); + }); + + it('should concatenate rows and return them on "end" event', done => { + const fakeRows = [{a: 'b'}, {c: 'd'}, {e: 'f'}]; + + snapshot.run(QUERY, (err, rows) => { + assert.ifError(err); + assert.deepStrictEqual(rows, fakeRows); + done(); + }); + + fakeRows.forEach(row => fakeStream.emit('data', row)); + fakeStream.emit('end'); + }); + + it('should pass back `stats` if available', done => { + const fakeStats = {}; + + snapshot.run(QUERY, (err, rows, stats) => { + assert.ifError(err); + assert.strictEqual(stats, fakeStats); + done(); + }); + + fakeStream.emit('stats', fakeStats); + fakeStream.emit('end'); + }); + }); + + describe('runStream', () => { + const QUERY = { + sql: 'SELECT * FROM `MyTable`', + }; + + beforeEach(() => { + PARTIAL_RESULT_STREAM.callsFake(makeRequest => makeRequest()); + }); + + it('should send the correct request', () => { + snapshot.runStream(QUERY); + + const {client, method, headers} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'executeStreamingSql'); + assert.deepStrictEqual(headers, { + ...snapshot.commonHeaders_, + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + }); + }); + + it('should use the transaction id if present', () => { + const id = 'transaction-id-123'; + const expectedTransaction = {id}; + + snapshot.id = id; + snapshot.runStream(QUERY); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.transaction, expectedTransaction); + }); + + it('should configure `singleUse` if id is absent', () => { + const expectedTransaction = { + singleUse: {readOnly: OPTIONS}, + }; + + snapshot.runStream(QUERY); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.transaction, expectedTransaction); + }); + + it('should set request tag', () => { + const requestTag = 'foo'; + const query = Object.assign({}, QUERY, { + requestOptions: {requestTag}, + }); + + snapshot.runStream(query); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.requestOptions, {requestTag}); + }); + + it('should send the correct `reqOpts`', () => { + const id = 'transaction-id-123'; + const fakeParams = {b: 'a'}; + const fakeParamTypes = {b: 'number'}; + + const fakeQuery = Object.assign({}, QUERY, { + params: {a: 'b'}, + types: {a: 'string'}, + seqno: 1, + queryOptions: {}, + directedReadOptions: fakeDirectedReadOptions, + }); + + const expectedRequest = { + session: SESSION_NAME, + requestOptions: {}, + transaction: {id}, + sql: QUERY.sql, + params: fakeParams, + paramTypes: fakeParamTypes, + seqno: 1, + queryOptions: {}, + resumeToken: undefined, + directedReadOptions: fakeDirectedReadOptions, + }; + + sandbox.stub(Snapshot, 'encodeParams').withArgs(fakeQuery).returns({ + params: fakeParams, + paramTypes: fakeParamTypes, + }); + + snapshot.id = id; + snapshot.runStream(fakeQuery); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts, expectedRequest); + }); + + it('should accept just a sql string', () => { + snapshot.runStream(QUERY.sql); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(reqOpts.sql, QUERY.sql); + }); + + it('should pass along `gaxOpts`', () => { + const fakeQuery = Object.assign({gaxOptions: {}}, QUERY); + + snapshot.runStream(fakeQuery); + + const {gaxOpts, reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(reqOpts.gaxOptions, undefined); + assert.strictEqual(gaxOpts, fakeQuery.gaxOptions); + }); + + it('should update the `seqno` for each call', () => { + snapshot.runStream(QUERY); + const call1 = REQUEST_STREAM.lastCall.args[0]; + + snapshot.runStream(QUERY); + const call2 = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(call1.reqOpts.seqno, 1); + assert.strictEqual(call2.reqOpts.seqno, 2); + }); + + it('should pass a stream to `PartialResultStream`', () => { + const fakeStream = new EventEmitter(); + + REQUEST_STREAM.returns(fakeStream); + snapshot.runStream(QUERY); + + const makeRequest = PARTIAL_RESULT_STREAM.lastCall.args[0]; + const stream = makeRequest(); + + assert.strictEqual(stream, fakeStream); + }); + + it('should return a `PartialResultStream`', () => { + const fakeStream = new EventEmitter(); + + PARTIAL_RESULT_STREAM.returns(fakeStream); + + const stream = snapshot.runStream(QUERY); + + assert.strictEqual(stream, fakeStream); + }); + + it('should update the `resumeToken` for subsequent requests', () => { + const fakeToken = 'fake-token-123'; + + snapshot.runStream(QUERY); + + const makeRequest = PARTIAL_RESULT_STREAM.lastCall.args[0]; + + makeRequest(fakeToken); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(reqOpts.resumeToken, fakeToken); + }); + + it('should pass along row options', () => { + const gaxOptions = { + timeout: 60, + }; + const expectedOptions = { + json: true, + jsonOptions: {a: 'b'}, + maxResumeRetries: 10, + columnsMetadata: {column1: {test: 'ss'}, column2: Function}, + gaxOptions: gaxOptions, + }; + + const fakeQuery = Object.assign({}, QUERY, expectedOptions); + + snapshot.runStream(fakeQuery); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(reqOpts.json, undefined); + assert.strictEqual(reqOpts.jsonOptions, undefined); + assert.strictEqual(reqOpts.maxResumeRetries, undefined); + + const options = PARTIAL_RESULT_STREAM.lastCall.args[1]; + + assert.deepStrictEqual(options, expectedOptions); + }); + + it('should use valid parameters', () => { + const fakeQuery = Object.assign({}, QUERY, { + params: { + a: 'a', + b: 3.14, + c: true, + }, + }); + const expectedParams = { + fields: { + a: {stringValue: 'a'}, + b: {numberValue: 3.14}, + c: {boolValue: true}, + }, + }; + + snapshot.runStream(fakeQuery); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + assert.deepStrictEqual(reqOpts.params, expectedParams); + }); + + it('should return an error stream for invalid parameters', done => { + REQUEST_STREAM.resetHistory(); + + const fakeQuery = Object.assign({}, QUERY, { + params: {a: undefined}, + }); + + const stream = snapshot.runStream(fakeQuery); + stream.on('error', error => { + assert.strictEqual( + error.message, + 'Value of type undefined not recognized.', + ); + done(); + }); + assert.ok(!REQUEST_STREAM.called, 'No request should be made'); + }); + + it('should accept directedReadOptions set for client', () => { + const id = 'transaction-id-123'; + const fakeParams = {b: 'a'}; + const fakeParamTypes = {b: 'number'}; + SESSION.parent.parent.parent = { + routeToLeaderEnabled: true, + directedReadOptions: fakeDirectedReadOptions, + defaultTransactionOptions: { + isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED, + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }, + }; + + const fakeQuery = Object.assign({}, QUERY, { + params: {a: 'b'}, + types: {a: 'string'}, + seqno: 1, + queryOptions: {}, + }); + + const expectedRequest = { + session: SESSION_NAME, + requestOptions: {}, + transaction: {id}, + sql: QUERY.sql, + params: fakeParams, + paramTypes: fakeParamTypes, + seqno: 1, + queryOptions: {}, + resumeToken: undefined, + directedReadOptions: fakeDirectedReadOptions, + }; + + sandbox.stub(Snapshot, 'encodeParams').withArgs(fakeQuery).returns({ + params: fakeParams, + paramTypes: fakeParamTypes, + }); + + snapshot.id = id; + snapshot.runStream(fakeQuery); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts, expectedRequest); + }); + + it('should override directedReadOptions set at client level when passed for request level', () => { + const id = 'transaction-id-123'; + const fakeParams = {b: 'a'}; + const fakeParamTypes = {b: 'number'}; + + SESSION.parent.parent.parent = { + routeToLeaderEnabled: true, + directedReadOptions: fakeDirectedReadOptions, + defaultTransactionOptions: { + isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED, + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }, + }; + + const fakeDirectedReadOptionsForRequest = { + includeReplicas: { + replicaSelections: [ + { + location: 'us-east1', + }, + ], + }, + }; + + const fakeQuery = Object.assign({}, QUERY, { + params: {a: 'b'}, + types: {a: 'string'}, + seqno: 1, + queryOptions: {}, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }); + + const expectedRequest = { + session: SESSION_NAME, + requestOptions: {}, + transaction: {id}, + sql: QUERY.sql, + params: fakeParams, + paramTypes: fakeParamTypes, + seqno: 1, + queryOptions: {}, + resumeToken: undefined, + directedReadOptions: fakeDirectedReadOptionsForRequest, + }; + + sandbox.stub(Snapshot, 'encodeParams').withArgs(fakeQuery).returns({ + params: fakeParams, + paramTypes: fakeParamTypes, + }); + + snapshot.id = id; + snapshot.runStream(fakeQuery); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts, expectedRequest); + }); + }); + + describe('encodeKeySet', () => { + function toListValue(thing): p.IListValue { + return { + values: [{stringValue: thing}], + }; + } + + it('should encode an array of `keys`', () => { + const fakeKeys = ['a', 'b', 'c']; + const encodedKeys = fakeKeys.map(toListValue); + + const stub = sandbox.stub(codec, 'convertToListValue'); + + fakeKeys.forEach((key, i) => { + stub.withArgs(key).returns(encodedKeys[i]); + }); + + const expectedKeySet = {keys: encodedKeys}; + const keySet = Snapshot.encodeKeySet({keys: fakeKeys}); + + assert.deepStrictEqual(keySet, expectedKeySet); + }); + + it('should encode an array of `ranges`', () => { + const fakeRanges = [ + {startClosed: 'a', endOpen: 'b'}, + {startOpen: 'c', endClosed: 'd'}, + ]; + + const encodedRanges = [ + {startClosed: toListValue('a'), endOpen: toListValue('b')}, + {startOpen: toListValue('c'), endClosed: toListValue('d')}, + ]; + + sandbox.stub(codec, 'convertToListValue').callsFake(toListValue); + + const expectedKeySet = {ranges: encodedRanges}; + const keySet = Snapshot.encodeKeySet({ranges: fakeRanges}); + + assert.deepStrictEqual(keySet, expectedKeySet); + }); + + it('should return all keys by default', () => { + const keySet = Snapshot.encodeKeySet({}); + + assert.deepStrictEqual(keySet, {all: true}); + }); + + it('should preserve passed in keySet', () => { + const fakeKeySet = {all: false}; + const keySet = Snapshot.encodeKeySet({keySet: fakeKeySet}); + + assert.deepStrictEqual(keySet, fakeKeySet); + }); + }); + + describe('encodeTimestampBounds', () => { + const PROTO_TIMESTAMP = { + nanos: 123123, + seconds: 453452234, + }; + + beforeEach(() => { + Snapshot.encodeTimestampBounds.restore(); + }); + + it('should accept `strong` user value', () => { + const options = Snapshot.encodeTimestampBounds({strong: false}); + + assert.strictEqual(options.strong, false); + }); + + it('should default `returnReadTimestamp` to true', () => { + const options = Snapshot.encodeTimestampBounds({}); + + assert.strictEqual(options.returnReadTimestamp, true); + }); + + it('should accept `returnReadTimestamp` user value', () => { + const options = Snapshot.encodeTimestampBounds({ + returnReadTimestamp: false, + }); + + assert.strictEqual(options.returnReadTimestamp, false); + }); + + it('should convert `minReadTimestamp` Date to proto', () => { + const fakeTimestamp = new PreciseDate(); + + sandbox.stub(fakeTimestamp, 'toStruct').returns(PROTO_TIMESTAMP); + + const options = Snapshot.encodeTimestampBounds({ + minReadTimestamp: fakeTimestamp, + }); + + assert.strictEqual(options.minReadTimestamp, PROTO_TIMESTAMP); + }); + + it('should convert `readTimestamp` Date to proto', () => { + const fakeTimestamp = new PreciseDate(); + + sandbox.stub(fakeTimestamp, 'toStruct').returns(PROTO_TIMESTAMP); + + const options = Snapshot.encodeTimestampBounds({ + readTimestamp: fakeTimestamp, + }); + + assert.strictEqual(options.readTimestamp, PROTO_TIMESTAMP); + }); + + it('should convert `maxStaleness` ms to proto', () => { + const fakeTimestamp = Date.now(); + + sandbox + .stub(codec, 'convertMsToProtoTimestamp') + .withArgs(fakeTimestamp) + .returns(PROTO_TIMESTAMP); + + const options = Snapshot.encodeTimestampBounds({ + maxStaleness: fakeTimestamp, + }); + + assert.strictEqual(options.maxStaleness, PROTO_TIMESTAMP); + }); + + it('should convert `exactStaleness` ms to proto', () => { + const fakeTimestamp = Date.now(); + + sandbox + .stub(codec, 'convertMsToProtoTimestamp') + .withArgs(fakeTimestamp) + .returns(PROTO_TIMESTAMP); + + const options = Snapshot.encodeTimestampBounds({ + exactStaleness: fakeTimestamp, + }); + + assert.strictEqual(options.exactStaleness, PROTO_TIMESTAMP); + }); + + it('should accept proto timestamp', () => { + const fakeOptions = { + exactStaleness: { + seconds: 23423424, + nanos: 23234234, + }, + returnReadTimestamp: false, + }; + + const options = Snapshot.encodeTimestampBounds(fakeOptions); + + assert.deepStrictEqual(options, fakeOptions); + assert.notStrictEqual(options, fakeOptions); + }); + }); + + describe('encodeParams', () => { + it('should encode param values', () => { + const fakeParams = {a: 'foo', b: 3}; + const encodedParams = { + a: {stringValue: 'bar'}, + b: {numberValue: 4}, + }; + + const stub = sandbox.stub(codec, 'encode'); + + stub.withArgs(fakeParams.a).returns(encodedParams.a); + stub.withArgs(fakeParams.b).returns(encodedParams.b); + + const expectedParams = {fields: encodedParams}; + const {params} = Snapshot.encodeParams({params: fakeParams}); + + assert.deepStrictEqual(params, expectedParams); + }); + + it('should encode param types', () => { + const fakeTypes = {a: 'string', b: 'number'}; + const expectedTypes = { + a: {code: google.spanner.v1.TypeCode.STRING}, + b: {code: google.spanner.v1.TypeCode.INT64}, + }; + + const stub = sandbox.stub(codec, 'createTypeObject') as sinon.SinonStub; + + stub + .withArgs(fakeTypes.a) + .returns(expectedTypes.a as google.spanner.v1.Type); + stub + .withArgs(fakeTypes.b) + .returns(expectedTypes.b as google.spanner.v1.Type); + + const {paramTypes} = Snapshot.encodeParams({types: fakeTypes}); + + assert.deepStrictEqual(paramTypes, expectedTypes); + }); + + it('should guess missing param types', () => { + const fakeParams = {a: 'foo', b: 3}; + const fakeTypes = {b: 'number'}; + const fakeMissingType = {type: 'string'}; + const expectedTypes = { + a: {code: google.spanner.v1.TypeCode.STRING}, + b: {code: google.spanner.v1.TypeCode.INT64}, + }; + + sandbox + .stub(codec, 'createTypeObject') + .withArgs(fakeTypes.b) + .returns(expectedTypes.b as google.spanner.v1.Type) + .withArgs(fakeMissingType) + .returns(expectedTypes.a as google.spanner.v1.Type); + + const {paramTypes} = Snapshot.encodeParams({ + params: fakeParams, + types: fakeTypes, + }); + + assert.strictEqual(paramTypes.a, expectedTypes.a); + }); + }); + }); + + describe('Dml', () => { + let dml; + + beforeEach(() => { + dml = new Dml(SESSION); + }); + + describe('initialization', () => { + it('should promisify all the things', () => { + const stub = PROMISIFY_ALL.withArgs(Dml); + + assert.strictEqual(stub.callCount, 1); + }); + + it('should inherit from Snapshot', () => { + assert(dml instanceof Snapshot); + }); + }); + + describe('runUpdate', () => { + const SQL = 'SELECT * FROM `MyTable`'; + + it('should call through to `run`', () => { + const fakeQuery = {sql: SQL}; + + const stub = sandbox.stub(dml, 'run').withArgs(fakeQuery); + + dml.runUpdate(fakeQuery); + + assert.strictEqual(stub.callCount, 1); + }); + + it('should accept a sql string', () => { + const expectedQuery = {sql: SQL}; + + const stub = sandbox + .stub(dml, 'run') + .withArgs(sinon.match(expectedQuery)); + + dml.runUpdate(SQL); + + assert.strictEqual(stub.callCount, 1); + }); + + it('should return any request errors', () => { + const fakeError = new Error('err'); + const stub = sandbox.stub(dml, 'run'); + const callback = sandbox.stub().withArgs(fakeError, 0); + + dml.runUpdate(SQL, callback); + + const runCallback = stub.lastCall.args[1]; + runCallback(fakeError); + + assert.strictEqual(callback.callCount, 1); + }); + + it('should return 0 for `rowCount`', () => { + const stub = sandbox.stub(dml, 'run'); + const callback = sandbox.stub().withArgs(null, 0); + + dml.runUpdate(SQL, callback); + + const runCallback = stub.lastCall.args[1]; + runCallback(null); + + assert.strictEqual(callback.callCount, 1); + assert.strictEqual(callback.args[0][1], 0); + }); + + it('should return the `rowCountExact`', () => { + const fakeRowCount = 5.5; + const fakeStats = { + rowCount: 'rowCountExact', + rowCountExact: fakeRowCount, + }; + + const stub = sandbox.stub(dml, 'run'); + const callback = sandbox.stub().withArgs(null, fakeRowCount); + + dml.runUpdate(SQL, callback); + + const runCallback = stub.lastCall.args[1]; + runCallback(null, undefined, fakeStats); + + assert.strictEqual(callback.callCount, 1); + assert.strictEqual(callback.args[0][1], Math.floor(fakeRowCount)); + }); + }); + }); + + describe('Transaction', () => { + let transaction; + + beforeEach(() => { + transaction = new Transaction(SESSION); + }); + + describe('initialization', () => { + it('should promisify all the things', () => { + const expectedOptions = sinon.match({ + exclude: ['deleteRows', 'insert', 'replace', 'update', 'upsert'], + }); + + const stub = PROMISIFY_ALL.withArgs(Transaction, expectedOptions); + + assert.strictEqual(stub.callCount, 1); + }); + + it('should inherit from Dml', () => { + assert(transaction instanceof Dml); + }); + }); + + describe('batchUpdate', () => { + const STRING_STATEMENTS = [ + "INSERT INTO Table (Key, Str) VALUES('a', 'b')", + "UPDATE Table t SET t.Str = 'c' WHERE t.Key = 'a'", + ]; + + const OBJ_STATEMENTS = [ + { + sql: 'INSERT INTO TxnTable (Key, StringValue) VALUES(@key, @str)', + params: { + key: 'k999', + str: 'abc', + }, + }, + { + sql: 'UPDATE TxnTable t SET t.StringValue = @str WHERE t.Key = @key', + params: { + key: 'k999', + str: 'abcd', + }, + }, + ]; + + const FORMATTED_STATEMENTS = [ + { + sql: OBJ_STATEMENTS[0].sql, + params: { + fields: { + key: {stringValue: OBJ_STATEMENTS[0].params.key}, + str: {stringValue: OBJ_STATEMENTS[0].params.str}, + }, + }, + paramTypes: { + key: {code: 'STRING'}, + str: {code: 'STRING'}, + }, + }, + { + sql: OBJ_STATEMENTS[1].sql, + params: { + fields: { + key: {stringValue: OBJ_STATEMENTS[1].params.key}, + str: {stringValue: OBJ_STATEMENTS[1].params.str}, + }, + }, + paramTypes: { + key: {code: 'STRING'}, + str: {code: 'STRING'}, + }, + }, + ]; + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + transaction.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + transaction.batchUpdate(STRING_STATEMENTS, gaxOptions, assert.ifError); + }); + + it('should set transactionTag', done => { + const transactionTag = 'bar'; + transaction.requestOptions = {transactionTag}; + transaction.request = config => { + assert.deepStrictEqual(config.reqOpts.requestOptions, { + transactionTag, + }); + done(); + }; + transaction.batchUpdate(STRING_STATEMENTS, assert.ifError); + }); + + it('should set requestTag', done => { + const requestTag = 'foo'; + const options: BatchUpdateOptions = {requestOptions: {requestTag}}; + transaction.request = config => { + assert.deepStrictEqual(config.reqOpts.requestOptions, { + requestTag, + }); + done(); + }; + transaction.batchUpdate(STRING_STATEMENTS, options, assert.ifError); + }); + + it('should set both tags and accept gaxOptions', done => { + const transactionTag = 'bar'; + transaction.requestOptions = {transactionTag}; + + const requestTag = 'foo'; + const gaxOptions = {timeout: 1000}; + const options: BatchUpdateOptions = { + requestOptions: {requestTag}, + gaxOptions, + }; + transaction.request = config => { + assert.deepStrictEqual(config.reqOpts.requestOptions, { + transactionTag, + requestTag, + }); + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + transaction.batchUpdate(STRING_STATEMENTS, options, assert.ifError); + }); + + it('should return an error if statements are missing', done => { + transaction.batchUpdate(null, err => { + assert.strictEqual( + err.message, + 'batchUpdate requires at least 1 DML statement.', + ); + assert.strictEqual(err.code, 3); + assert.deepStrictEqual(err.rowCounts, []); + done(); + }); + }); + + it('should return an error if statements are empty', done => { + transaction.batchUpdate([], err => { + assert.strictEqual( + err.message, + 'batchUpdate requires at least 1 DML statement.', + ); + assert.strictEqual(err.code, 3); + assert.deepStrictEqual(err.rowCounts, []); + done(); + }); + }); + + it('should make the correct request', () => { + const stub = sandbox.stub(transaction, 'request'); + const fakeId = 'transaction-id-123'; + + transaction.id = fakeId; + transaction.batchUpdate(STRING_STATEMENTS, assert.ifError); + + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'executeBatchDml'); + assert.strictEqual(reqOpts.session, SESSION_NAME); + assert.deepStrictEqual(reqOpts.transaction, {id: fakeId}); + assert.strictEqual(reqOpts.seqno, 1); + assert.deepStrictEqual( + headers, + Object.assign( + { + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + [LEADER_AWARE_ROUTING_HEADER]: 'true', + }, + transaction.commonHeaders_, + ), + ); + }); + + it('should encode sql string statements', () => { + const stub = sandbox.stub(transaction, 'request'); + const expectedStatements = STRING_STATEMENTS.map(sql => ({sql})); + + transaction.batchUpdate(STRING_STATEMENTS, assert.ifError); + + const {reqOpts} = stub.lastCall.args[0]; + assert.deepStrictEqual(reqOpts.statements, expectedStatements); + }); + + it('should encode DML object statements', () => { + const stub = sandbox.stub(transaction, 'request'); + transaction.batchUpdate(OBJ_STATEMENTS, assert.ifError); + + const {reqOpts} = stub.lastCall.args[0]; + assert.deepStrictEqual(reqOpts.statements, FORMATTED_STATEMENTS); + }); + + it('should wrap and return any request errors', done => { + const stub = sandbox.stub(transaction, 'request'); + const fakeError = new Error('err'); + const fakeResponse = {}; + + transaction.batchUpdate( + OBJ_STATEMENTS, + (err, rowCounts, apiResponse) => { + assert.strictEqual(err, fakeError); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.deepStrictEqual((err as any).rowCounts, []); + assert.deepStrictEqual(rowCounts, []); + assert.strictEqual(apiResponse, fakeResponse); + done(); + }, + ); + + const requestCallback = stub.lastCall.args[1]; + setImmediate(requestCallback, fakeError, fakeResponse); + }); + + it('should return a list of row counts upon success', done => { + const stub = sandbox.stub(transaction, 'request'); + const expectedRowCounts = [5, 7]; + const fakeResponse = { + resultSets: [ + {stats: {rowCount: 'a', a: '5'}}, + {stats: {rowCount: 'b', b: '7'}}, + ], + }; + + transaction.batchUpdate( + OBJ_STATEMENTS, + (err, rowCounts, apiResponse) => { + assert.ifError(err); + assert.deepStrictEqual(rowCounts, expectedRowCounts); + assert.strictEqual(apiResponse, fakeResponse); + done(); + }, + ); + + const requestCallback = stub.lastCall.args[1]; + setImmediate(requestCallback, null, fakeResponse); + }); + + it('should return list of 0s for row counts when stats or rowCount value is empty', done => { + const stub = sandbox.stub(transaction, 'request'); + const expectedRowCounts = [0, 0]; + const fakeResponse = { + resultSets: [{stats: {rowCount: 'a'}}, {stats: undefined}], + }; + + transaction.batchUpdate( + OBJ_STATEMENTS, + (err, rowCounts, apiResponse) => { + assert.ifError(err); + assert.deepStrictEqual(rowCounts, expectedRowCounts); + assert.strictEqual(apiResponse, fakeResponse); + done(); + }, + ); + + const requestCallback = stub.lastCall.args[1]; + setImmediate(requestCallback, null, fakeResponse); + }); + + it('should return both error and row counts for partial failures', done => { + const stub = sandbox.stub(transaction, 'request'); + const expectedRowCounts = [6, 8]; + const fakeResponse = { + resultSets: [ + {stats: {rowCount: 'a', a: '6'}}, + {stats: {rowCount: 'b', b: '8'}}, + ], + status: {code: 3, message: 'Err'}, + }; + + transaction.batchUpdate( + OBJ_STATEMENTS, + (err, rowCounts, apiResponse) => { + assert(err instanceof Error); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.strictEqual((err as any).code, fakeResponse.status.code); + assert.strictEqual(err.message, fakeResponse.status.message); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.deepStrictEqual((err as any).rowCounts, expectedRowCounts); + assert.deepStrictEqual(rowCounts, expectedRowCounts); + assert.deepStrictEqual(apiResponse, fakeResponse); + done(); + }, + ); + + const requestCallback = stub.lastCall.args[1]; + setImmediate(requestCallback, null, fakeResponse); + }); + + it('should return precommitToken in the api response', done => { + const stub = sandbox.stub(transaction, 'request'); + const expectedRowCounts = [5, 7]; + const fakeResponse = { + resultSets: [ + {stats: {rowCount: 'a', a: '5'}}, + {stats: {rowCount: 'b', b: '7'}}, + ], + precommitToken: { + precommitToken: Buffer.from('precommit-token-batch-update'), + seqNum: 1, + }, + }; + + transaction.batchUpdate( + OBJ_STATEMENTS, + (err, rowCounts, apiResponse) => { + assert.ifError(err); + assert.deepStrictEqual(rowCounts, expectedRowCounts); + assert.strictEqual(apiResponse, fakeResponse); + done(); + }, + ); + + const requestCallback = stub.lastCall.args[1]; + setImmediate(requestCallback, null, fakeResponse); + }); + }); + + describe('begin', () => { + it('should send the correct options', () => { + const stub = sandbox.stub(transaction, 'request'); + + transaction.begin(); + + const expectedOptions = {isolationLevel: 0, readWrite: {}}; + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'beginTransaction'); + assert.deepStrictEqual(reqOpts.options, expectedOptions); + assert.deepStrictEqual( + headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + transaction.commonHeaders_, + ), + ); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + transaction.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + transaction.begin(gaxOptions, assert.ifError); + }); + + it('should set transaction tag', done => { + const transactionTag = 'bar'; + transaction.requestOptions = {transactionTag}; + transaction.request = config => { + assert.deepStrictEqual(config.reqOpts.requestOptions, { + transactionTag, + }); + done(); + }; + transaction.begin(assert.ifError); + }); + + it('should set optimistic lock using setReadWriteTransactionOptions', () => { + const rw = { + readLockMode: ReadLockMode.OPTIMISTIC, + }; + transaction = new Transaction(SESSION); + transaction.setReadWriteTransactionOptions({ + readLockMode: ReadLockMode.OPTIMISTIC, + }); + const stub = sandbox.stub(transaction, 'request'); + transaction.begin(); + + const expectedOptions = {isolationLevel: 0, readWrite: rw}; + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'beginTransaction'); + assert.deepStrictEqual(reqOpts.options, expectedOptions); + assert.deepStrictEqual( + headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + transaction.commonHeaders_, + ), + ); + }); + + it('should set repeatable read using setReadWriteTransactionOptions', () => { + const rw = { + readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED, + }; + transaction = new Transaction(SESSION); + transaction.setReadWriteTransactionOptions({ + isolationLevel: IsolationLevel.REPEATABLE_READ, + }); + const stub = sandbox.stub(transaction, 'request'); + transaction.begin(); + + const expectedOptions = {isolationLevel: 2, readWrite: rw}; + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'beginTransaction'); + assert.deepStrictEqual(reqOpts.options, expectedOptions); + assert.deepStrictEqual( + headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + transaction.commonHeaders_, + ), + ); + }); + + it('should set repeatable read isolation and pessimistic lock using setReadWriteTransactionOptions', () => { + const rw = { + readLockMode: ReadLockMode.PESSIMISTIC, + }; + transaction = new Transaction(SESSION); + transaction.setReadWriteTransactionOptions({ + isolationLevel: IsolationLevel.REPEATABLE_READ, + readLockMode: ReadLockMode.PESSIMISTIC, + }); + const stub = sandbox.stub(transaction, 'request'); + transaction.begin(); + + const expectedOptions = {isolationLevel: 2, readWrite: rw}; + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'beginTransaction'); + assert.deepStrictEqual(reqOpts.options, expectedOptions); + assert.deepStrictEqual( + headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + transaction.commonHeaders_, + ), + ); + }); + + it('should pass multiplexedSessionPreviousTransactionId in the BeginTransactionRequest upon retrying an aborted transaction', () => { + const fakePreviousTransactionId = 'fake-previous-transaction-id'; + const database = { + formattedName_: 'formatted-database-name', + isMuxEnabledForRW_: true, + parent: INSTANCE, + }; + const SESSION = { + parent: database, + formattedName_: SESSION_NAME, + request: REQUEST, + requestStream: REQUEST_STREAM, + }; + // multiplexed session + const multiplexedSession = Object.assign({multiplexed: true}, SESSION); + const transaction = new Transaction(multiplexedSession); + // transaction option must contain the previous transaction id for multiplexed session + transaction.multiplexedSessionPreviousTransactionId = + fakePreviousTransactionId; + const stub = sandbox.stub(transaction, 'request'); + transaction.begin(); + + const expectedOptions = { + isolationLevel: 0, + readWrite: { + multiplexedSessionPreviousTransactionId: fakePreviousTransactionId, + }, + }; + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'beginTransaction'); + // request options should contain the multiplexedSessionPreviousTransactionId + assert.deepStrictEqual(reqOpts.options, expectedOptions); + assert.deepStrictEqual( + headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + transaction.commonHeaders_, + ), + ); + }); + + it('should send the correct options if _mutationKey is set in the transaction object', () => { + // session with multiplexed enabled + const multiplexedSession = Object.assign({multiplexed: true}, SESSION); + + // fake mutation key + const fakeMutationKey = { + insertOrUpdate: { + table: 'my-table-123', + columns: ['Id', 'Name'], + values: [ + { + values: [{stringValue: 'Id3'}, {stringValue: 'Name3'}], + }, + ], + }, + } as google.spanner.v1.Mutation; + + const transaction = new Transaction(multiplexedSession); + + // stub the transaction request + const stub = sandbox.stub(transaction, 'request'); + + // set the _mutationKey in the transaction object + transaction._mutationKey = fakeMutationKey; + + // make a call to begin + transaction.begin(); + + const expectedOptions = {isolationLevel: 0, readWrite: {}}; + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + // assert on the begin transaction call + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'beginTransaction'); + assert.deepStrictEqual(reqOpts.options, expectedOptions); + // assert that if the _mutationKey is set in the transaction object + // it is getting pass in the request as well along with request options + assert.deepStrictEqual(reqOpts.mutationKey, fakeMutationKey); + assert.deepStrictEqual( + headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + transaction.commonHeaders_, + ), + ); + }); + }); + + describe('commit', () => { + const DEADLINE_EXCEEDED_STATUS_CODE = 4; + + it('should make the correct request', () => { + const stub = sandbox.stub(transaction, 'request'); + + transaction.commit(); + + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'commit'); + assert.strictEqual(reqOpts.session, SESSION_NAME); + assert.deepStrictEqual(reqOpts.mutations, []); + assert.deepStrictEqual( + headers, + Object.assign( + { + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + [LEADER_AWARE_ROUTING_HEADER]: true, + }, + transaction.commonHeaders_, + ), + ); + }); + + it('should accept gaxOptions as CallOptions', done => { + const gaxOptions = { + retry: { + retryCodes: [DEADLINE_EXCEEDED_STATUS_CODE], + }, + }; + transaction.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + transaction.commit(gaxOptions, assert.ifError); + }); + + it('should accept commit options', done => { + const maxCommitDelay = new google.protobuf.Duration({ + seconds: 0, // 0 seconds + nanos: 100000000, // 100,000,000 nanoseconds = 100 milliseconds + }); + const options = { + returnCommitStats: true, + maxCommitDelay: maxCommitDelay, + }; + transaction.request = config => { + assert.strictEqual(config.reqOpts.returnCommitStats, true); + done(); + }; + transaction.commit(options, assert.ifError); + }); + + it('should accept commit and gaxOptions', done => { + const gaxOptions = { + retry: { + retryCodes: [DEADLINE_EXCEEDED_STATUS_CODE], + }, + }; + const options = { + returnCommitStats: true, + gaxOptions, + }; + transaction.request = config => { + assert.strictEqual(config.reqOpts.returnCommitStats, true); + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + transaction.commit(options, assert.ifError); + }); + + it('should accept gaxOptions in CommitOptions', done => { + const options = {gaxOptions: {}}; + transaction.request = config => { + assert.strictEqual(config.gaxOpts, options.gaxOptions); + done(); + }; + transaction.commit(options, assert.ifError); + }); + + it('should accept requestOptions', done => { + const options = { + requestOptions: {priority: RequestOptions.Priority.PRIORITY_MEDIUM}, + }; + transaction.request = config => { + assert.strictEqual( + config.reqOpts.requestOptions, + options.requestOptions, + ); + done(); + }; + transaction.commit(options, assert.ifError); + }); + + it('should accept precommitToken', done => { + const precommitToken = { + precommitToken: Buffer.from('precommit-token-commit'), + seqNum: 1, + }; + transaction._latestPreCommitToken = precommitToken; + transaction.request = config => { + assert.strictEqual(config.reqOpts.precommitToken, precommitToken); + done(); + }; + transaction.commit(assert.ifError); + }); + + it('should use the transaction `id` when set', () => { + const id = 'transaction-id-123'; + const stub = sandbox.stub(transaction, 'request'); + + transaction.id = id; + transaction.commit(); + + const {reqOpts} = stub.lastCall.args[0]; + + assert.strictEqual(reqOpts.transactionId, id); + }); + + it('should set transactionTag when not single use transaction', done => { + const id = 'transaction-id-123'; + const transactionTag = 'bar'; + transaction.id = id; + transaction.requestOptions = {transactionTag}; + + transaction.request = config => { + assert.strictEqual( + config.reqOpts.requestOptions.transactionTag, + transactionTag, + ); + done(); + }; + transaction.commit(assert.ifError); + }); + + it('should set `singleUseTransaction` when `id` is not set', () => { + const expectedOptions = {isolationLevel: 0, readWrite: {}}; + const stub = sandbox.stub(transaction, 'request'); + + transaction.commit(); + + const {reqOpts} = stub.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.singleUseTransaction, expectedOptions); + }); + + it('should call _setMutationKey when neither `id` is set nor `singleUseTransaction` is used', async () => { + // fake mutation key + const fakeMutations = [ + { + insertOrUpdate: { + table: 'my-table-123', + columns: ['Id', 'Name'], + values: [ + { + values: [{stringValue: 'Id1'}, {stringValue: 'Name1'}], + }, + ], + }, + } as google.spanner.v1.Mutation, + ]; + + // fake transaction id + const fakeTransactionId = 'fake-tx-id-12345'; + + const database = { + formattedName_: 'formatted-database-name', + isMuxEnabledForRW_: true, + parent: INSTANCE, + }; + const SESSION = { + parent: database, + formattedName_: SESSION_NAME, + request: REQUEST, + requestStream: REQUEST_STREAM, + }; + // multiplexed session + const multiplexedSession = Object.assign({multiplexed: true}, SESSION); + + // transaction object + const transaction = new Transaction(multiplexedSession); + + // ensure transaction is not single use transaction + transaction._useInRunner = true; + + // ensure transaction ID is not set + transaction.id = undefined; + + // set the _queuedMutations with the fakeMutations list + transaction._queuedMutations = fakeMutations; + + // spy on _setMutationKey + const setMutationKeySpy = sandbox.spy(transaction, '_setMutationKey'); + + // stub the begin method + const beginStub = sandbox.stub(transaction, 'begin').callsFake(() => { + transaction.id = fakeTransactionId; + return Promise.resolve(); + }); + + // stub transaction request + sandbox.stub(transaction, 'request'); + + // make a call to commit + transaction.commit(); + + // ensure that _setMutationKey was got called once + sinon.assert.calledOnce(setMutationKeySpy); + + // ensure that _setMutationKey got called with correct arguments + sinon.assert.calledWith(setMutationKeySpy, fakeMutations); + + // ensure begin was called + sinon.assert.calledOnce(beginStub); + + // ensure begin set the transaction id + assert.strictEqual(transaction.id, fakeTransactionId); + + // ensure _mutationKey is set + assert.strictEqual(transaction._mutationKey, fakeMutations[0]); + }); + + it('should call `end` once complete', () => { + const endStub = sandbox.stub(transaction, 'end'); + const requestStub = sandbox.stub(transaction, 'request'); + + transaction.commit(() => {}); + + const requestCallback = requestStub.lastCall.args[1]; + requestCallback(); + + assert.strictEqual(endStub.callCount, 1); + }); + + it('should set the `commitTimestamp` if in response', () => { + const requestStub = sandbox.stub(transaction, 'request'); + + const expectedTimestamp = new PreciseDate(0); + const fakeTimestamp = {seconds: 0, nanos: 0}; + + transaction.commit(() => {}); + + const requestCallback = requestStub.lastCall.args[1]; + requestCallback(null, {commitTimestamp: fakeTimestamp}); + + assert.deepStrictEqual(transaction.commitTimestamp, expectedTimestamp); + assert.strictEqual(transaction.commitTimestampProto, fakeTimestamp); + }); + + it('should retry commit only once upon sending precommitToken to read-only participants', () => { + const requestStub = sandbox.stub(transaction, 'request'); + + const expectedTimestamp = new PreciseDate(0); + const fakeTimestamp = {seconds: 0, nanos: 0}; + + const fakeResponse = {commitTimestamp: fakeTimestamp}; + const fakePrecommitToken = { + precommitToken: Buffer.from('precommit-token-commit'), + seqNum: 1, + }; + + transaction._latestPreCommitToken = fakePrecommitToken; + + // retry response on commit retry + const fakeCommitRetryResponse = { + commitTimestamp: null, + MultiplexedSessionRetry: 'precommitToken', + precommitToken: { + precommitToken: Buffer.from('precommit-token-commit-retry'), + seqNum: 2, + }, + }; + + requestStub.onFirstCall().callsFake((_, callback) => { + // assert that the transaction contains the precommit token + assert.deepStrictEqual( + transaction._latestPreCommitToken, + fakePrecommitToken, + ); + // retry commit response + callback(null, fakeCommitRetryResponse); + }); + + requestStub.onSecondCall().callsFake((_, callback) => { + // assert that before second commit retry the _latestPreCommitToken + // containing the commit retry reponse in the transaction object + assert.deepStrictEqual( + transaction._latestPreCommitToken, + fakeCommitRetryResponse.precommitToken, + ); + callback(null, fakeResponse); + }); + + transaction.commit((err, resp) => { + // assert there is no error + assert.ifError(err); + // make sure that retry happens only once + assert.strictEqual(requestStub.callCount, 2); + assert.deepStrictEqual( + transaction.commitTimestamp, + expectedTimestamp, + ); + assert.strictEqual(transaction.commitTimestampProto, fakeTimestamp); + // assert on the successfull commit response + assert.deepStrictEqual(resp, fakeResponse); + }); + }); + + it('should return any errors and the response', () => { + const requestStub = sandbox.stub(transaction, 'request'); + + const fakeError = new Error('err'); + const fakeResponse = {}; + const callback = sandbox.stub().withArgs(fakeError, fakeResponse); + + transaction.commit(callback); + + const requestCallback = requestStub.lastCall.args[1]; + requestCallback(fakeError, fakeResponse); + + assert.strictEqual(callback.callCount, 1); + }); + + it('should not decorate non-gRPC error', () => { + const fakeError = new Error('err'); + const decoratedError = Transaction.decorateCommitError(fakeError, []); + assert.strictEqual(decoratedError, fakeError); + }); + + it('should not decorate generic gRPC error', () => { + const tableNotFoundErr = Object.assign( + new Error('Table TestTable not found'), + { + code: grpc.status.NOT_FOUND, + }, + ); + const decoratedError = Transaction.decorateCommitError( + tableNotFoundErr, + [], + ); + assert.strictEqual(decoratedError, tableNotFoundErr); + }); + + it('should not decorate FAILED_PRECONDITION error without specific JSON error', () => { + const failedPreconditionErr = Object.assign( + new Error('Invalid value for column TestColumn'), + { + code: grpc.status.FAILED_PRECONDITION, + }, + ); + const decoratedError = Transaction.decorateCommitError( + failedPreconditionErr, + [], + ); + assert.strictEqual(decoratedError, failedPreconditionErr); + }); + + it('should not decorate FAILED_PRECONDITION error with specific JSON error if mutations are empty', () => { + const failedPreconditionErr = Object.assign( + new Error( + 'Invalid value for column TestCol2 in table TestTable: Expected JSON.', + ), + { + code: grpc.status.FAILED_PRECONDITION, + }, + ); + const decoratedError = Transaction.decorateCommitError( + failedPreconditionErr, + [], + ); + assert.strictEqual(decoratedError, failedPreconditionErr); + }); + + it('should not decorate FAILED_PRECONDITION error with specific JSON error if mutations do not contain a JSON array value', () => { + transaction._mutate('insert', 'TestTable', { + TestCol1: 1, + TestCol2: 'value', + }); + const mutations = transaction._queuedMutations; + + const failedPreconditionErr = Object.assign( + new Error( + 'Invalid value for column TestCol2 in table TestTable: Expected JSON.', + ), + { + code: grpc.status.FAILED_PRECONDITION, + }, + ); + const decoratedError = Transaction.decorateCommitError( + failedPreconditionErr, + mutations, + ); + assert.strictEqual(decoratedError, failedPreconditionErr); + }); + + it('should decorate FAILED_PRECONDITION error with specific JSON error if mutations contain a JSON array value', () => { + transaction._mutate('insert', 'TestTable', { + TestCol1: 1, + TestCol2: [{key1: 'value'}], + }); + const mutations = transaction._queuedMutations; + + const failedPreconditionErr = Object.assign( + new Error( + 'Invalid value for column TestCol2 in table TestTable: Expected JSON.', + ), + { + code: grpc.status.FAILED_PRECONDITION, + }, + ); + const decoratedError = Transaction.decorateCommitError( + failedPreconditionErr, + mutations, + ); + assert.notStrictEqual(decoratedError, failedPreconditionErr); + assert.ok( + decoratedError.message.includes( + 'The value is an array. Convert the value to a JSON string containing an array instead in order to insert it into a JSON column. Example: `[{"key": "value 1"}, {"key": "value 2"}]` instead of [{key: "value 1"}, {key: "value 2"}]', + ), + ); + }); + }); + + describe('deleteRows', () => { + it('should queue a "delete" mutation', () => { + const fakeTable = 'my-table-123'; + const fakeKeys = ['a', 'b']; + + const expectedKeySet = { + keys: fakeKeys.map(key => { + return { + values: [{stringValue: key}], + }; + }), + }; + + const stub = sandbox.stub(transaction, 'request'); + + transaction.deleteRows(fakeTable, fakeKeys); + transaction.commit(); + + const {reqOpts} = stub.lastCall.args[0]; + const {table, keySet} = reqOpts.mutations[0].delete; + + assert.strictEqual(table, fakeTable); + assert.deepStrictEqual(keySet, expectedKeySet); + }); + }); + + describe('insert', () => { + it('should queue an "insert" mutation', () => { + const fakeTable = 'my-table-123'; + const fakeKeyVals = { + name: 'Joe West', + id: 'Id3b', + }; + + const expectedColumns = Object.keys(fakeKeyVals).sort(); + const expectedValues = [ + { + values: expectedColumns.map(column => { + return {stringValue: fakeKeyVals[column]}; + }), + }, + ]; + + const stub = sandbox.stub(transaction, 'request'); + + transaction.insert(fakeTable, fakeKeyVals); + transaction.commit(); + + const {reqOpts} = stub.lastCall.args[0]; + const {table, columns, values} = reqOpts.mutations[0].insert; + + assert.strictEqual(table, fakeTable); + assert.deepStrictEqual(columns, expectedColumns); + assert.deepStrictEqual(values, expectedValues); + }); + }); + + describe('replace', () => { + it('should queue a "replace" mutation', () => { + const fakeTable = 'my-table-123'; + const fakeKeyVals = { + name: 'Joe West', + id: 'Id3b', + }; + + const expectedColumns = Object.keys(fakeKeyVals).sort(); + const expectedValues = [ + { + values: expectedColumns.map(column => { + return {stringValue: fakeKeyVals[column]}; + }), + }, + ]; + + const stub = sandbox.stub(transaction, 'request'); + + transaction.replace(fakeTable, fakeKeyVals); + transaction.commit(); + + const {reqOpts} = stub.lastCall.args[0]; + const {table, columns, values} = reqOpts.mutations[0].replace; + + assert.strictEqual(table, fakeTable); + assert.deepStrictEqual(columns, expectedColumns); + assert.deepStrictEqual(values, expectedValues); + }); + }); + + describe('rollback', () => { + const ID = 'transaction-id-123'; + + beforeEach(() => { + transaction.id = ID; + }); + + it('should not return an error if the `id` is not set', done => { + delete transaction.id; + transaction.rollback(err => { + assert.deepStrictEqual(err, null); + done(); + }); + }); + + it('should make the correct request', () => { + const stub = sandbox.stub(transaction, 'request'); + const expectedReqOpts = { + session: SESSION_NAME, + transactionId: ID, + }; + + transaction.rollback(); + + const {client, method, reqOpts, headers} = stub.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'rollback'); + assert.deepStrictEqual(reqOpts, expectedReqOpts); + assert.deepStrictEqual( + headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + transaction.commonHeaders_, + ), + ); + }); + + it('should accept gaxOptions', done => { + const gaxOptions = {}; + transaction.request = config => { + assert.strictEqual(config.gaxOpts, gaxOptions); + done(); + }; + transaction.rollback(gaxOptions, assert.ifError); + }); + + it('should call through to `end`', () => { + const endStub = sandbox.stub(transaction, 'end'); + const requestStub = sandbox.stub(transaction, 'request'); + + transaction.rollback(() => {}); + + const requestCallback = requestStub.lastCall.args[1]; + requestCallback(null); + + assert.strictEqual(endStub.callCount, 1); + }); + + it('should return any request errors', () => { + const fakeError = new Error('err'); + const callback = sandbox.stub().withArgs(fakeError); + const requestStub = sandbox.stub(transaction, 'request'); + + transaction.rollback(callback); + + const requestCallback = requestStub.lastCall.args[1]; + requestCallback(fakeError); + + assert.strictEqual(callback.callCount, 1); + }); + }); + + describe('update', () => { + it('should queue an "update" mutation', () => { + const fakeTable = 'my-table-123'; + const fakeKeyVals = { + name: 'Joe West', + id: 'Id3b', + }; + + const expectedColumns = Object.keys(fakeKeyVals).sort(); + const expectedValues = [ + { + values: expectedColumns.map(column => { + return {stringValue: fakeKeyVals[column]}; + }), + }, + ]; + + const stub = sandbox.stub(transaction, 'request'); + + transaction.update(fakeTable, fakeKeyVals); + transaction.commit(); + + const {reqOpts} = stub.lastCall.args[0]; + const {table, columns, values} = reqOpts.mutations[0].update; + + assert.strictEqual(table, fakeTable); + assert.deepStrictEqual(columns, expectedColumns); + assert.deepStrictEqual(values, expectedValues); + }); + }); + + describe('upsert', () => { + it('should queue an "insertOrUpdate" mutation', () => { + const fakeTable = 'my-table-123'; + const fakeKeyVals = { + name: 'Joe West', + id: 'Id3b', + }; + + const expectedColumns = Object.keys(fakeKeyVals).sort(); + const expectedValues = [ + { + values: expectedColumns.map(column => { + return {stringValue: fakeKeyVals[column]}; + }), + }, + ]; + + const stub = sandbox.stub(transaction, 'request'); + + transaction.upsert(fakeTable, fakeKeyVals); + transaction.commit(); + + const {reqOpts} = stub.lastCall.args[0]; + const {table, columns, values} = reqOpts.mutations[0].insertOrUpdate; + + assert.strictEqual(table, fakeTable); + assert.deepStrictEqual(columns, expectedColumns); + assert.deepStrictEqual(values, expectedValues); + }); + }); + + describe('mutations', () => { + it('should accept an array of rows', () => { + const stub = sandbox.stub(transaction, 'request'); + + const fakeTable = 'my-table-123'; + const rows = [ + {name: 'dave', id: '1'}, + {name: 'stephen', id: '2'}, + ]; + + const expectedColumns = Object.keys(rows[0]).sort(); + const expectedValues = rows.map(row => { + return { + values: expectedColumns.map(column => { + return {stringValue: row[column]}; + }), + }; + }); + + transaction.insert(fakeTable, rows); + transaction.commit(); + + const {reqOpts} = stub.lastCall.args[0]; + const {columns, values} = reqOpts.mutations[0].insert; + + assert.deepStrictEqual(columns, expectedColumns); + assert.deepStrictEqual(values, expectedValues); + }); + + it('should throw an error if missing columns', () => { + const table = 'my-table-123'; + const rows = [{name: 'dave', id: '1'}, {name: 'stephen'}]; + + const errorRegExp = + /Row at index 1 does not contain the correct number of columns\.\n\nMissing columns: \["id"\]/; + + assert.throws(() => transaction.insert(table, rows), errorRegExp); + }); + }); + + describe('_setMutationKey', () => { + let transaction; + before(() => { + transaction = new Transaction(SESSION); + }); + + it('should have _mutationKey set to null, if mutations list is empty', () => { + // empty mutations list + const mutations: google.spanner.v1.Mutation[] = []; + // make a call to _setMutationKey + transaction._setMutationKey(mutations); + // ensure that the transaction's _mutationKey is null + assert.strictEqual(transaction._mutationKey, null); + }); + + it('should select a high-priority mutation when both types are present', () => { + // expected mutation objects + const insertMutation = { + insert: { + table: 'my-table-123', + columns: ['Id', 'Name'], + values: [ + { + values: [ + { + stringValue: 'Id1', + }, + { + stringValue: 'Name1', + }, + ], + }, + ], + }, + } as google.spanner.v1.Mutation; + + const updateMutation = { + update: { + table: 'my-table-123', + columns: ['Id', 'Name'], + values: [ + { + values: [ + { + stringValue: 'Id2', + }, + { + stringValue: 'Name2', + }, + ], + }, + ], + }, + } as google.spanner.v1.Mutation; + + const deleteMutation = { + delete: { + table: 'my-table-123', + keySet: { + keys: [ + { + values: [ + { + stringValue: 'Id1', + }, + ], + }, + ], + }, + }, + } as google.spanner.v1.Mutation; + + const mutations = [insertMutation, updateMutation, deleteMutation]; + + transaction._setMutationKey(mutations); + + // assert that _mutationKeys is not null + assert.notEqual(transaction._mutationKey, null); + + // get the selected mutation key + const selectedKey = Object.keys(transaction._mutationKey!)[0]; + + // assert that chosen key is not insert + assert.notStrictEqual( + selectedKey, + 'insert', + 'The selected mutation should not be an insert', + ); + + // assert that chosen key is either insertOrUpdate or delete + assert.ok( + ['update', 'delete'].includes(selectedKey), + 'The selected mutation should be a high-priority type', + ); + }); + + it('should select a mutation with maximum number of rows when only insert keys are present', () => { + // insert mutation objects + const insertMutation1 = { + insert: { + table: 'my-table-123', + columns: ['Id', 'Name'], + values: [ + // Row 1 + { + values: [{stringValue: 'Id1'}, {stringValue: 'Name1'}], + }, + // Row 2 + { + values: [{stringValue: 'Id2'}, {stringValue: 'Name2'}], + }, + // Row 3 + { + values: [{stringValue: 'Id3'}, {stringValue: 'Name3'}], + }, + ], + }, + } as google.spanner.v1.Mutation; + + const insertMutation2 = { + insert: { + table: 'my-table-123', + columns: ['Id', 'Name'], + values: [ + // Row 1 + { + values: [{stringValue: 'Id1'}, {stringValue: 'Name1'}], + }, + // Row 2 + { + values: [{stringValue: 'Id2'}, {stringValue: 'Name2'}], + }, + // Row 3 + { + values: [{stringValue: 'Id3'}, {stringValue: 'Name3'}], + }, + // Row 4 + { + values: [{stringValue: 'Id4'}, {stringValue: 'Name4'}], + }, + ], + }, + } as google.spanner.v1.Mutation; + + const mutations = [insertMutation1, insertMutation2]; + + transaction._setMutationKey(mutations); + + // assert that _mutationKeys is not null + assert.notEqual(transaction._mutationKey, null); + + // get the selected mutation key + const selectedKey = Object.keys(transaction._mutationKey!)[0]; + + // assert that chosen key is insert + assert.strictEqual( + selectedKey, + 'insert', + 'The selected mutation should be an insert', + ); + // assert that key with maximum of rows is selected + assert.strictEqual( + transaction._mutationKey, + insertMutation2, + 'The mutation with the most rows should have been selected', + ); + }); + }); + + describe('getUniqueKeys', () => { + it('should create a list of unique keys', () => { + const rows = [ + {name: 'dave', id: '1'}, + {name: 'stephen', age: 102}, + {big: 'monies', no: 'whammies', id: '2'}, + ]; + + const expectedKeys = ['age', 'big', 'id', 'name', 'no']; + const keys = Transaction.getUniqueKeys(rows); + + assert.deepStrictEqual(keys, expectedKeys); + }); + }); + + describe('runStream', () => { + before(() => { + PARTIAL_RESULT_STREAM.callsFake(makeRequest => makeRequest()); + }); + + it('should send the correct options', done => { + const QUERY: ExecuteSqlRequest = { + sql: 'SELET * FROM `MyTable`', + }; + + transaction.requestStream = config => { + assert.strictEqual(config.client, 'SpannerClient'); + assert.strictEqual(config.method, 'executeStreamingSql'); + assert.deepStrictEqual( + config.headers, + Object.assign( + { + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + [LEADER_AWARE_ROUTING_HEADER]: true, + }, + transaction.commonHeaders_, + ), + ); + done(); + }; + + transaction.runStream(QUERY); + }); + + it('should set transaction tag when not `singleUse`', done => { + const QUERY: ExecuteSqlRequest = { + sql: 'SELET * FROM `MyTable`', + }; + + const transactionTag = 'bar'; + transaction.requestOptions = {transactionTag}; + + const id = 'transaction-id-123'; + transaction.id = id; + + transaction.requestStream = config => { + assert.deepStrictEqual(config.reqOpts.requestOptions, { + transactionTag, + }); + done(); + }; + + transaction.runStream(QUERY); + }); + + it('should return a precommitToken in response', done => { + const QUERY: ExecuteSqlRequest = { + sql: 'SELET * FROM `MyTable`', + }; + const fakeStream = new EventEmitter(); + const fakePrecommitToken = { + precommitToken: Buffer.from('precommit-token-runStream'), + seqNum: 1, + }; + + PARTIAL_RESULT_STREAM.returns(fakeStream); + + const stream = transaction.runStream(QUERY); + assert.strictEqual(stream, fakeStream); + + stream.on('response', resp => { + assert.deepStrictEqual(resp.precommitToken, fakePrecommitToken); + done(); + }); + + fakeStream.emit('response', { + precommitToken: fakePrecommitToken, + }); + }); + }); + + describe('createReadStream', () => { + before(() => { + PARTIAL_RESULT_STREAM.callsFake(makeRequest => makeRequest()); + }); + + it('should send the correct options', () => { + const TABLE = 'my-table-123'; + transaction.createReadStream(TABLE); + + const {client, method, headers} = REQUEST_STREAM.lastCall.args[0]; + + assert.strictEqual(client, 'SpannerClient'); + assert.strictEqual(method, 'streamingRead'); + assert.deepStrictEqual( + headers, + Object.assign( + { + [X_GOOG_SPANNER_REQUEST_ID_HEADER]: craftRequestId(1, 1, 1, 1), + [LEADER_AWARE_ROUTING_HEADER]: true, + }, + transaction.commonHeaders_, + ), + ); + }); + + it('should set transaction tag if not `singleUse`', () => { + const TABLE = 'my-table-123'; + const transactionTag = 'bar'; + transaction.id = 'transaction-id-123'; + transaction.requestOptions = {transactionTag}; + + transaction.createReadStream(TABLE); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.requestOptions, { + transactionTag, + }); + }); + + it('should set transaction tag if `begin`', () => { + const TABLE = 'my-table-123'; + const transactionTag = 'bar'; + transaction.requestOptions = {transactionTag}; + + transaction.createReadStream(TABLE); + + const {reqOpts} = REQUEST_STREAM.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.requestOptions, { + transactionTag, + }); + }); + + it('should return a precommitToken in response', done => { + const TABLE = 'my-table-123'; + const fakeStream = new EventEmitter(); + const fakePrecommitToken = { + precommitToken: Buffer.from('precommit-token-createReadStream'), + seqNum: 1, + }; + + PARTIAL_RESULT_STREAM.returns(fakeStream); + + const stream = transaction.createReadStream(TABLE); + assert.strictEqual(stream, fakeStream); + + stream.on('response', resp => { + assert.deepStrictEqual(resp.precommitToken, fakePrecommitToken); + done(); + }); + + fakeStream.emit('response', { + precommitToken: fakePrecommitToken, + }); + }); + + it('should override the precommitToken with the value that has higher seqNum received in response', done => { + const TABLE = 'my-table-123'; + const fakeStream = new EventEmitter(); + const fakePrecommitToken1 = { + precommitToken: Buffer.from('precommit-token1-createReadStream'), + seqNum: 1, + }; + + const fakePrecommitToken2 = { + precommitToken: Buffer.from('precommit-token2-createReadStream'), + seqNum: 2, + }; + + const fakePrecommitToken3 = { + precommitToken: Buffer.from('precommit-token3-createReadStream'), + seqNum: 0, + }; + + PARTIAL_RESULT_STREAM.returns(fakeStream); + + const stream = transaction.createReadStream(TABLE); + assert.strictEqual(stream, fakeStream); + + assert.strictEqual(transaction._latestPreCommitToken, null); + + let responseCount = 0; + + stream.on('response', resp => { + responseCount++; + if (responseCount === 1) { + assert.deepStrictEqual(resp.precommitToken, fakePrecommitToken1); + assert.deepStrictEqual( + transaction._latestPreCommitToken, + fakePrecommitToken1, + ); + } else if (responseCount === 2) { + assert.deepStrictEqual(resp.precommitToken, fakePrecommitToken2); + assert.deepStrictEqual( + transaction._latestPreCommitToken, + fakePrecommitToken2, + ); + } else if (responseCount === 3) { + // fakePrecommitToken3 should get ignored + assert.deepStrictEqual(resp.precommitToken, fakePrecommitToken3); + assert.deepStrictEqual( + transaction._latestPreCommitToken, + fakePrecommitToken2, + ); + done(); + } + }); + + fakeStream.emit('response', { + precommitToken: fakePrecommitToken1, + }); + + fakeStream.emit('response', { + precommitToken: fakePrecommitToken2, + }); + + fakeStream.emit('response', { + precommitToken: fakePrecommitToken3, + }); + }); + }); + }); + + describe('PartitionedDml', () => { + let pdml; + + beforeEach(() => { + pdml = new PartitionedDml(SESSION); + }); + + describe('initialization', () => { + it('should promisify all the things', () => { + const stub = PROMISIFY_ALL.withArgs(PartitionedDml); + + assert.strictEqual(stub.callCount, 1); + }); + + it('should inherit from Dml', () => { + assert(pdml instanceof Dml); + }); + }); + + describe('begin', () => { + it('should send the correct options', () => { + const stub = sandbox.stub(pdml, 'request'); + + pdml.begin(); + + const expectedOptions = {partitionedDml: {}}; + const {reqOpts, headers} = stub.lastCall.args[0]; + + assert.deepStrictEqual(reqOpts.options, expectedOptions); + assert.deepStrictEqual( + headers, + Object.assign( + {[LEADER_AWARE_ROUTING_HEADER]: true}, + pdml.commonHeaders_, + ), + ); + }); + }); + + describe('runUpdate', () => { + const SQL = 'SELECT * FROM `MyTable`'; + + it('should call through to `super.runUpdate`', () => { + const stub = sandbox.stub(Dml.prototype, 'runUpdate'); + + pdml.runUpdate(SQL); + + const query = stub.lastCall.args[0]; + + assert.strictEqual(query, SQL); + }); + + it('should end the transaction after a request', () => { + const endStub = sandbox.stub(pdml, 'end'); + const superStub = sandbox.stub(Dml.prototype, 'runUpdate'); + + pdml.runUpdate(SQL, () => {}); + + const superCallback = superStub.lastCall.args[1]; + superCallback(); + + assert.strictEqual(endStub.callCount, 1); + }); + + it('should return any errors and the row count', () => { + const fakeErr = new Error('err'); + const fakeRowCount = 5; + + const superStub = sandbox.stub(Dml.prototype, 'runUpdate'); + const callback = sandbox.stub().withArgs(fakeErr, fakeRowCount); + + pdml.runUpdate(SQL, callback); + + const superCallback = superStub.lastCall.args[1]; + superCallback(fakeErr, fakeRowCount); + + assert.strictEqual(callback.callCount, 1); + }); + }); + }); +}); diff --git a/handwritten/spanner/tsconfig.json b/handwritten/spanner/tsconfig.json new file mode 100644 index 00000000000..7721598f2d9 --- /dev/null +++ b/handwritten/spanner/tsconfig.json @@ -0,0 +1,29 @@ +{ + "extends": "./node_modules/gts/tsconfig-google.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "build", + "noImplicitAny": false, + "resolveJsonModule": true, + "lib": [ + "es2018", + "dom" + ] + }, + "include": [ + "src/*.ts", + "src/**/*.ts", + "src/v1/*.d.ts", + "src/**/*.js", + "src/**/*.json", + "test/*.ts", + "test/**/*.ts", + "system-test/*.ts", + "benchmark/*.ts", + "observability-test/*.ts", + "src/**/*.json", + "system-test/*.ts", + "protos/protos.json", + "samples/**/*.d.ts" + ] +} diff --git a/handwritten/spanner/webpack.config.js b/handwritten/spanner/webpack.config.js new file mode 100644 index 00000000000..c8dbdbf75e1 --- /dev/null +++ b/handwritten/spanner/webpack.config.js @@ -0,0 +1,64 @@ +// Copyright 2021 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. + +const path = require('path'); + +module.exports = { + entry: './src/index.ts', + output: { + library: 'spanner', + filename: './spanner.js', + }, + node: { + child_process: 'empty', + fs: 'empty', + crypto: 'empty', + }, + resolve: { + alias: { + '../../../package.json': path.resolve(__dirname, 'package.json'), + }, + extensions: ['.js', '.json', '.ts'], + }, + module: { + rules: [ + { + test: /\.tsx?$/, + use: 'ts-loader', + exclude: /node_modules/, + }, + { + test: /node_modules[\\/]@grpc[\\/]grpc-js/, + use: 'null-loader', + }, + { + test: /node_modules[\\/]grpc/, + use: 'null-loader', + }, + { + test: /node_modules[\\/]retry-request/, + use: 'null-loader', + }, + { + test: /node_modules[\\/]https?-proxy-agent/, + use: 'null-loader', + }, + { + test: /node_modules[\\/]gtoken/, + use: 'null-loader', + }, + ], + }, + mode: 'production', +}; diff --git a/handwritten/storage/.OwlBot.yaml b/handwritten/storage/.OwlBot.yaml new file mode 100644 index 00000000000..5781d72d218 --- /dev/null +++ b/handwritten/storage/.OwlBot.yaml @@ -0,0 +1,19 @@ +# Copyright 2021 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. + +deep-preserve-regex: + - /.kokoro/samples-test.sh + + +begin-after-commit-hash: 674a41e0de2869f44f45eb7b1a605852a5394bba diff --git a/handwritten/storage/.eslintignore b/handwritten/storage/.eslintignore new file mode 100644 index 00000000000..ea5b04aebe6 --- /dev/null +++ b/handwritten/storage/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/coverage +test/fixtures +build/ +docs/ +protos/ +samples/generated/ diff --git a/handwritten/storage/.eslintrc.json b/handwritten/storage/.eslintrc.json new file mode 100644 index 00000000000..78215349546 --- /dev/null +++ b/handwritten/storage/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "./node_modules/gts" +} diff --git a/handwritten/storage/.gitattributes b/handwritten/storage/.gitattributes new file mode 100644 index 00000000000..33739cb74e4 --- /dev/null +++ b/handwritten/storage/.gitattributes @@ -0,0 +1,4 @@ +*.ts text eol=lf +*.js text eol=lf +protos/* linguist-generated +**/api-extractor.json linguist-language=JSON-with-Comments diff --git a/handwritten/storage/.gitignore b/handwritten/storage/.gitignore new file mode 100644 index 00000000000..6ff88ca912c --- /dev/null +++ b/handwritten/storage/.gitignore @@ -0,0 +1,16 @@ +**/*.log +**/node_modules +.coverage +.nyc_output +docs/ +out/ +build/ +system-test/secrets.js +system-test/*key.json +*.lock +.DS_Store +google-cloud-logging-winston-*.tgz +google-cloud-logging-bunyan-*.tgz +.vscode +package-lock.json +__pycache__ diff --git a/handwritten/storage/.jsdoc.json b/handwritten/storage/.jsdoc.json new file mode 100644 index 00000000000..1873939a0ae --- /dev/null +++ b/handwritten/storage/.jsdoc.json @@ -0,0 +1,29 @@ +{ + "opts": { + "readme": "./README.md", + "package": "./package.json", + "template": "./node_modules/jsdoc-fresh", + "recurse": true, + "verbose": true, + "destination": "./docs/" + }, + "plugins": ["plugins/markdown", "jsdoc-region-tag"], + "source": { + "excludePattern": "(^|\\/|\\\\)[._]", + "include": ["build/cjs/src"], + "includePattern": "\\.js$" + }, + "templates": { + "copyright": "Copyright 2019 Google, LLC.", + "includeDate": false, + "sourceFiles": false, + "systemName": "@google-cloud/storage", + "theme": "lumen", + "default": { + "outputSourceFiles": false + } + }, + "markdown": { + "idInHeadings": true + } +} diff --git a/handwritten/storage/.kokoro/.gitattributes b/handwritten/storage/.kokoro/.gitattributes new file mode 100644 index 00000000000..87acd4f484e --- /dev/null +++ b/handwritten/storage/.kokoro/.gitattributes @@ -0,0 +1 @@ +* linguist-generated=true diff --git a/handwritten/storage/.kokoro/common.cfg b/handwritten/storage/.kokoro/common.cfg new file mode 100644 index 00000000000..f34b972eed8 --- /dev/null +++ b/handwritten/storage/.kokoro/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-storage/handwritten/storage/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/test.sh" +} diff --git a/handwritten/storage/.kokoro/conformance-test.sh b/handwritten/storage/.kokoro/conformance-test.sh new file mode 100644 index 00000000000..190f6dfc0e8 --- /dev/null +++ b/handwritten/storage/.kokoro/conformance-test.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +# Copyright 2021 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. + +set -eo pipefail +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +cd $(dirname $0)/.. + +npm install +# If tests are running against main branch, configure flakybot +# to open issues on failures: +if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP +fi + +npm run conformance-test diff --git a/handwritten/storage/.kokoro/continuous/node14/common.cfg b/handwritten/storage/.kokoro/continuous/node14/common.cfg new file mode 100644 index 00000000000..9df80119791 --- /dev/null +++ b/handwritten/storage/.kokoro/continuous/node14/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-storage/handwritten/storage/.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" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/test.sh" +} diff --git a/handwritten/storage/.kokoro/continuous/node14/lint.cfg b/handwritten/storage/.kokoro/continuous/node14/lint.cfg new file mode 100644 index 00000000000..7a49e5d4776 --- /dev/null +++ b/handwritten/storage/.kokoro/continuous/node14/lint.cfg @@ -0,0 +1,4 @@ +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/lint.sh" +} diff --git a/handwritten/storage/.kokoro/continuous/node14/samples-test.cfg b/handwritten/storage/.kokoro/continuous/node14/samples-test.cfg new file mode 100644 index 00000000000..5e9326097d0 --- /dev/null +++ b/handwritten/storage/.kokoro/continuous/node14/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/storage/.kokoro/continuous/node14/system-test.cfg b/handwritten/storage/.kokoro/continuous/node14/system-test.cfg new file mode 100644 index 00000000000..240576acdaf --- /dev/null +++ b/handwritten/storage/.kokoro/continuous/node14/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account,client-library-test-universe-domain-credential" +} \ No newline at end of file diff --git a/handwritten/storage/.kokoro/continuous/node14/test.cfg b/handwritten/storage/.kokoro/continuous/node14/test.cfg new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/storage/.kokoro/continuous/node18/common.cfg b/handwritten/storage/.kokoro/continuous/node18/common.cfg new file mode 100644 index 00000000000..f34b972eed8 --- /dev/null +++ b/handwritten/storage/.kokoro/continuous/node18/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-storage/handwritten/storage/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/test.sh" +} diff --git a/handwritten/storage/.kokoro/continuous/node18/lint.cfg b/handwritten/storage/.kokoro/continuous/node18/lint.cfg new file mode 100644 index 00000000000..7a49e5d4776 --- /dev/null +++ b/handwritten/storage/.kokoro/continuous/node18/lint.cfg @@ -0,0 +1,4 @@ +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/lint.sh" +} diff --git a/handwritten/storage/.kokoro/continuous/node18/samples-test.cfg b/handwritten/storage/.kokoro/continuous/node18/samples-test.cfg new file mode 100644 index 00000000000..5e9326097d0 --- /dev/null +++ b/handwritten/storage/.kokoro/continuous/node18/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/storage/.kokoro/continuous/node18/system-test.cfg b/handwritten/storage/.kokoro/continuous/node18/system-test.cfg new file mode 100644 index 00000000000..e1fcec9e9ad --- /dev/null +++ b/handwritten/storage/.kokoro/continuous/node18/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/storage/.kokoro/continuous/node18/test.cfg b/handwritten/storage/.kokoro/continuous/node18/test.cfg new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/storage/.kokoro/docs.sh b/handwritten/storage/.kokoro/docs.sh new file mode 100755 index 00000000000..85901242b5e --- /dev/null +++ b/handwritten/storage/.kokoro/docs.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +cd $(dirname $0)/.. + +npm install + +npm run docs-test diff --git a/handwritten/storage/.kokoro/lint.sh b/handwritten/storage/.kokoro/lint.sh new file mode 100755 index 00000000000..c7ffa6438b0 --- /dev/null +++ b/handwritten/storage/.kokoro/lint.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global +export PATH="${NPM_CONFIG_PREFIX}/bin:${PATH}" + +# Ensure the npm global directory is writable, otherwise rebuild `npm` +mkdir -p ${NPM_CONFIG_PREFIX}/lib +npm config -g ls || npm i -g npm@`npm --version` + +cd $(dirname $0)/.. + +npm install + +# Install and link samples +if [ -f samples/package.json ]; then + cd samples/ + npm link ../ + npm install + cd .. +fi + +npm run lint diff --git a/handwritten/storage/.kokoro/populate-secrets.sh b/handwritten/storage/.kokoro/populate-secrets.sh new file mode 100755 index 00000000000..deb2b199eb4 --- /dev/null +++ b/handwritten/storage/.kokoro/populate-secrets.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# Copyright 2020 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. + +# This file is called in the early stage of `trampoline_v2.sh` to +# populate secrets needed for the CI builds. + +set -eo pipefail + +function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;} +function msg { println "$*" >&2 ;} +function println { printf '%s\n' "$(now) $*" ;} + +# Populates requested secrets set in SECRET_MANAGER_KEYS + +# In Kokoro CI builds, we use the service account attached to the +# Kokoro VM. This means we need to setup auth on other CI systems. +# For local run, we just use the gcloud command for retrieving the +# secrets. + +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + GCLOUD_COMMANDS=( + "docker" + "run" + "--entrypoint=gcloud" + "--volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR}" + "gcr.io/google.com/cloudsdktool/cloud-sdk" + ) + if [[ "${TRAMPOLINE_CI:-}" == "kokoro" ]]; then + SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" + else + echo "Authentication for this CI system is not implemented yet." + exit 2 + # TODO: Determine appropriate SECRET_LOCATION and the GCLOUD_COMMANDS. + fi +else + # For local run, use /dev/shm or temporary directory for + # KOKORO_GFILE_DIR. + if [[ -d "/dev/shm" ]]; then + export KOKORO_GFILE_DIR=/dev/shm + else + export KOKORO_GFILE_DIR=$(mktemp -d -t ci-XXXXXXXX) + fi + SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" + GCLOUD_COMMANDS=("gcloud") +fi + +msg "Creating folder on disk for secrets: ${SECRET_LOCATION}" +mkdir -p ${SECRET_LOCATION} + +for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g") +do + msg "Retrieving secret ${key}" + "${GCLOUD_COMMANDS[@]}" \ + secrets versions access latest \ + --project cloud-devrel-kokoro-resources \ + --secret $key > \ + "$SECRET_LOCATION/$key" + if [[ $? == 0 ]]; then + msg "Secret written to ${SECRET_LOCATION}/${key}" + else + msg "Error retrieving secret ${key}" + exit 2 + fi +done diff --git a/handwritten/storage/.kokoro/pre-samples-test.sh b/handwritten/storage/.kokoro/pre-samples-test.sh new file mode 100644 index 00000000000..a1ffa0cea3b --- /dev/null +++ b/handwritten/storage/.kokoro/pre-samples-test.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +# Copyright 2018 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. + +. .kokoro/setup-vars.sh diff --git a/handwritten/storage/.kokoro/pre-system-test.sh b/handwritten/storage/.kokoro/pre-system-test.sh new file mode 100755 index 00000000000..abc85f9d4b8 --- /dev/null +++ b/handwritten/storage/.kokoro/pre-system-test.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# Copyright 2018 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. + +. .kokoro/setup-vars.sh + +# Lease a second service account for testing listing with multiple service accounts +export HMAC_KEY_TEST_SECOND_SERVICE_ACCOUNT=$(./gimmeproj -project=$HMAC_PROJECT lease 15m) +# Add to the list of leased service account for clean up after tests +export LEASED_SERVICE_ACCOUNTS="$LEASED_SERVICE_ACCOUNTS $HMAC_KEY_TEST_SECOND_SERVICE_ACCOUNT" diff --git a/handwritten/storage/.kokoro/presubmit/node14/common.cfg b/handwritten/storage/.kokoro/presubmit/node14/common.cfg new file mode 100644 index 00000000000..9df80119791 --- /dev/null +++ b/handwritten/storage/.kokoro/presubmit/node14/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-storage/handwritten/storage/.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" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/test.sh" +} diff --git a/handwritten/storage/.kokoro/presubmit/node14/samples-test.cfg b/handwritten/storage/.kokoro/presubmit/node14/samples-test.cfg new file mode 100644 index 00000000000..5e9326097d0 --- /dev/null +++ b/handwritten/storage/.kokoro/presubmit/node14/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/storage/.kokoro/presubmit/node14/system-test.cfg b/handwritten/storage/.kokoro/presubmit/node14/system-test.cfg new file mode 100644 index 00000000000..240576acdaf --- /dev/null +++ b/handwritten/storage/.kokoro/presubmit/node14/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account,client-library-test-universe-domain-credential" +} \ No newline at end of file diff --git a/handwritten/storage/.kokoro/presubmit/node14/test.cfg b/handwritten/storage/.kokoro/presubmit/node14/test.cfg new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/storage/.kokoro/presubmit/node18/common.cfg b/handwritten/storage/.kokoro/presubmit/node18/common.cfg new file mode 100644 index 00000000000..f34b972eed8 --- /dev/null +++ b/handwritten/storage/.kokoro/presubmit/node18/common.cfg @@ -0,0 +1,24 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-storage/handwritten/storage/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/test.sh" +} diff --git a/handwritten/storage/.kokoro/presubmit/node18/samples-test.cfg b/handwritten/storage/.kokoro/presubmit/node18/samples-test.cfg new file mode 100644 index 00000000000..5e9326097d0 --- /dev/null +++ b/handwritten/storage/.kokoro/presubmit/node18/samples-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/samples-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/storage/.kokoro/presubmit/node18/system-test.cfg b/handwritten/storage/.kokoro/presubmit/node18/system-test.cfg new file mode 100644 index 00000000000..e1fcec9e9ad --- /dev/null +++ b/handwritten/storage/.kokoro/presubmit/node18/system-test.cfg @@ -0,0 +1,12 @@ +# Download resources for system tests (service account key, etc.) +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/google-cloud-nodejs" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/system-test.sh" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "long-door-651-kokoro-system-test-service-account" +} \ No newline at end of file diff --git a/handwritten/storage/.kokoro/presubmit/node18/test.cfg b/handwritten/storage/.kokoro/presubmit/node18/test.cfg new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/storage/.kokoro/presubmit/windows/common.cfg b/handwritten/storage/.kokoro/presubmit/windows/common.cfg new file mode 100644 index 00000000000..d6e25e0b1b8 --- /dev/null +++ b/handwritten/storage/.kokoro/presubmit/windows/common.cfg @@ -0,0 +1,2 @@ +# Format: //devtools/kokoro/config/proto/build.proto + diff --git a/handwritten/storage/.kokoro/presubmit/windows/test.cfg b/handwritten/storage/.kokoro/presubmit/windows/test.cfg new file mode 100644 index 00000000000..eb8febf58d9 --- /dev/null +++ b/handwritten/storage/.kokoro/presubmit/windows/test.cfg @@ -0,0 +1,2 @@ +# Use the test file directly +build_file: "nodejs-storage/handwritten/storage/.kokoro/test.bat" diff --git a/handwritten/storage/.kokoro/publish.sh b/handwritten/storage/.kokoro/publish.sh new file mode 100755 index 00000000000..ca1d47af347 --- /dev/null +++ b/handwritten/storage/.kokoro/publish.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +# Start the releasetool reporter +python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script + +cd $(dirname $0)/.. + +NPM_TOKEN=$(cat $KOKORO_KEYSTORE_DIR/73713_google-cloud-npm-token-1) +echo "//wombat-dressing-room.appspot.com/:_authToken=${NPM_TOKEN}" > ~/.npmrc + +npm install +npm pack . +# npm provides no way to specify, observe, or predict the name of the tarball +# file it generates. We have to look in the current directory for the freshest +# .tgz file. +TARBALL=$(ls -1 -t *.tgz | head -1) + +npm publish --access=public --registry=https://wombat-dressing-room.appspot.com "$TARBALL" + +# Kokoro collects *.tgz and package-lock.json files and stores them in Placer +# so we can generate SBOMs and attestations. +# However, we *don't* want Kokoro to collect package-lock.json and *.tgz files +# that happened to be installed with dependencies. +find node_modules -name package-lock.json -o -name "*.tgz" | xargs rm -f \ No newline at end of file diff --git a/handwritten/storage/.kokoro/release/common.cfg b/handwritten/storage/.kokoro/release/common.cfg new file mode 100644 index 00000000000..3ba2eb095fe --- /dev/null +++ b/handwritten/storage/.kokoro/release/common.cfg @@ -0,0 +1,8 @@ +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "yoshi-automation-github-key" + } + } +} diff --git a/handwritten/storage/.kokoro/release/docs-devsite.cfg b/handwritten/storage/.kokoro/release/docs-devsite.cfg new file mode 100644 index 00000000000..aed93dc0989 --- /dev/null +++ b/handwritten/storage/.kokoro/release/docs-devsite.cfg @@ -0,0 +1,26 @@ +# service account used to publish up-to-date docs. +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +# doc publications use a Python image. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-storage/handwritten/storage/.kokoro/trampoline_v2.sh" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/release/docs-devsite.sh" +} diff --git a/handwritten/storage/.kokoro/release/docs-devsite.sh b/handwritten/storage/.kokoro/release/docs-devsite.sh new file mode 100755 index 00000000000..81a89f6c172 --- /dev/null +++ b/handwritten/storage/.kokoro/release/docs-devsite.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# Copyright 2021 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. + +set -eo pipefail + +if [[ -z "$CREDENTIALS" ]]; then + # if CREDENTIALS are explicitly set, assume we're testing locally + # and don't set NPM_CONFIG_PREFIX. + export NPM_CONFIG_PREFIX=${HOME}/.npm-global + export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin" + cd $(dirname $0)/../.. +fi + +npm install +npm install --no-save @google-cloud/cloud-rad@^0.4.0 +# publish docs to devsite +npx @google-cloud/cloud-rad . cloud-rad diff --git a/handwritten/storage/.kokoro/release/docs.cfg b/handwritten/storage/.kokoro/release/docs.cfg new file mode 100644 index 00000000000..dde75bb7342 --- /dev/null +++ b/handwritten/storage/.kokoro/release/docs.cfg @@ -0,0 +1,26 @@ +# service account used to publish up-to-date docs. +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +# doc publications use a Python image. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-storage/handwritten/storage/.kokoro/trampoline_v2.sh" + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/release/docs.sh" +} diff --git a/handwritten/storage/.kokoro/release/docs.sh b/handwritten/storage/.kokoro/release/docs.sh new file mode 100755 index 00000000000..e9079a60530 --- /dev/null +++ b/handwritten/storage/.kokoro/release/docs.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +# Copyright 2019 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. + +set -eo pipefail + +# 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. + export NPM_CONFIG_PREFIX=${HOME}/.npm-global + export PATH="$PATH:${NPM_CONFIG_PREFIX}/bin" + cd $(dirname $0)/../.. +fi +npm install +npm run docs + +# create docs.metadata, based on package.json and .repo-metadata.json. +npm i json@9.0.6 -g +python3 -m docuploader create-metadata \ + --name=$(cat .repo-metadata.json | json name) \ + --version=$(cat package.json | json version) \ + --language=$(cat .repo-metadata.json | json language) \ + --distribution-name=$(cat .repo-metadata.json | json distribution_name) \ + --product-page=$(cat .repo-metadata.json | json product_documentation) \ + --github-repository=$(cat .repo-metadata.json | json repo) \ + --issue-tracker=$(cat .repo-metadata.json | json issue_tracker) +cp docs.metadata ./docs/docs.metadata + +# deploy the docs. +if [[ -z "$CREDENTIALS" ]]; then + CREDENTIALS=${KOKORO_KEYSTORE_DIR}/73713_docuploader_service_account +fi +if [[ -z "$BUCKET" ]]; then + BUCKET=docs-staging +fi +python3 -m docuploader upload ./docs --credentials $CREDENTIALS --staging-bucket $BUCKET diff --git a/handwritten/storage/.kokoro/release/publish.cfg b/handwritten/storage/.kokoro/release/publish.cfg new file mode 100644 index 00000000000..f7e75eae268 --- /dev/null +++ b/handwritten/storage/.kokoro/release/publish.cfg @@ -0,0 +1,51 @@ +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "docuploader_service_account" + } + } +} + +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google-cloud-npm-token-1" + } + } +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,client-library-test-universe-domain-credential" +} + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "nodejs-storage/handwritten/storage/.kokoro/trampoline_v2.sh" + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/node:18-user" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/nodejs-storage/handwritten/storage/.kokoro/publish.sh" +} + +# Store the packages we uploaded to npmjs.org and their corresponding +# package-lock.jsons in Placer. That way, we have a record of exactly +# what we published, and which version of which tools we used to publish +# it, which we can use to generate SBOMs and attestations. +action { + define_artifacts { + regex: "github/**/*.tgz" + regex: "github/**/package-lock.json" + strip_prefix: "github" + } +} diff --git a/handwritten/storage/.kokoro/samples-test.sh b/handwritten/storage/.kokoro/samples-test.sh new file mode 100755 index 00000000000..d195fbf7cf3 --- /dev/null +++ b/handwritten/storage/.kokoro/samples-test.sh @@ -0,0 +1,72 @@ +#!/bin/bash + +# Copyright 2018 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. + +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 +export GCLOUD_PROJECT=long-door-651 + +cd $(dirname $0)/.. + +# Run a pre-test hook, if a pre-samples-test.sh is in the project +if [ -f .kokoro/pre-samples-test.sh ]; then + set +x + . .kokoro/pre-samples-test.sh + set -x +fi + +if [ -f samples/package.json ]; then + npm install + + # Install and link samples + cd samples/ + npm link ../ + npm install + cd .. + # If tests are running against main branch, configure flakybot + # to open issues on failures: + if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP + fi + + npm run samples-test +fi + +# codecov combines coverage across integration and unit tests. Include +# the logic below for any environment you wish to collect coverage for: +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 + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/storage/.kokoro/setup-vars.sh b/handwritten/storage/.kokoro/setup-vars.sh new file mode 100644 index 00000000000..b6ce41d93c9 --- /dev/null +++ b/handwritten/storage/.kokoro/setup-vars.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +# Copyright 2018 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. + +# nodejs-storage/handwritten/storage's system tests require additional project and +# system test key +export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/storage-key.json +export GCN_STORAGE_2ND_PROJECT_ID=gcloud-node-whitelist-ci-tests +export GCN_STORAGE_2ND_PROJECT_KEY=${KOKORO_GFILE_DIR}/no-whitelist-key.json + +export GOOGLE_CLOUD_KMS_KEY_ASIA="projects/long-door-651/locations/asia/keyRings/test-key-asia/cryptoKeys/test-key-asia" +export GOOGLE_CLOUD_KMS_KEY_US="projects/long-door-651/locations/us/keyRings/test-key-us/cryptoKeys/test-key-us" + +# For testing SA HMAC +export HMAC_PROJECT=gimme-acc +curl https://storage.googleapis.com/gimme-proj/linux_amd64/gimmeproj > gimmeproj +chmod +x gimmeproj +./gimmeproj version + +export HMAC_KEY_TEST_SERVICE_ACCOUNT=$(./gimmeproj -project=$HMAC_PROJECT lease 15m) +echo Leased service account: $HMAC_KEY_TEST_SERVICE_ACCOUNT +export LEASED_SERVICE_ACCOUNTS=$HMAC_KEY_TEST_SERVICE_ACCOUNT + +cleanup_service_accounts () { + for i in $LEASED_SERVICE_ACCOUNTS; do + ./gimmeproj -project=$HMAC_PROJECT "done" $i + done +} + +trap cleanup_service_accounts EXIT diff --git a/handwritten/storage/.kokoro/system-test.sh b/handwritten/storage/.kokoro/system-test.sh new file mode 100755 index 00000000000..6b69337ef07 --- /dev/null +++ b/handwritten/storage/.kokoro/system-test.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +# Setup service account credentials. +export GOOGLE_APPLICATION_CREDENTIALS=${KOKORO_GFILE_DIR}/secret_manager/long-door-651-kokoro-system-test-service-account +export GCLOUD_PROJECT=long-door-651 + +# For universe domain testing +export TEST_UNIVERSE_DOMAIN_CREDENTIAL=${KOKORO_GFILE_DIR}/secret_manager/client-library-test-universe-domain-credential +export TEST_UNIVERSE_DOMAIN=$(gcloud secrets versions access latest --project cloud-devrel-kokoro-resources --secret=client-library-test-universe-domain) +export TEST_UNIVERSE_PROJECT_ID=$(gcloud secrets versions access latest --project cloud-devrel-kokoro-resources --secret=client-library-test-universe-project-id) +export TEST_UNIVERSE_LOCATION=$(gcloud secrets versions access latest --project cloud-devrel-kokoro-resources --secret=client-library-test-universe-storage-location) + +cd $(dirname $0)/.. + +# Run a pre-test hook, if a pre-system-test.sh is in the project +if [ -f .kokoro/pre-system-test.sh ]; then + set +x + . .kokoro/pre-system-test.sh + set -x +fi + +npm install + +# If tests are running against main branch, configure flakybot +# to open issues on failures: +if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP +fi + +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=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 + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/storage/.kokoro/test.bat b/handwritten/storage/.kokoro/test.bat new file mode 100644 index 00000000000..caf825656c2 --- /dev/null +++ b/handwritten/storage/.kokoro/test.bat @@ -0,0 +1,33 @@ +@rem Copyright 2018 Google LLC. All rights reserved. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. + +@echo "Starting Windows build" + +cd /d %~dp0 +cd .. + +@rem npm path is not currently set in our image, we should fix this next time +@rem we upgrade Node.js in the image: +SET PATH=%PATH%;/cygdrive/c/Program Files/nodejs/npm + +call nvm use 18 +call which node + +call npm install || goto :error +call npm run test || goto :error + +goto :EOF + +:error +exit /b 1 diff --git a/handwritten/storage/.kokoro/test.sh b/handwritten/storage/.kokoro/test.sh new file mode 100755 index 00000000000..0d9f6392a75 --- /dev/null +++ b/handwritten/storage/.kokoro/test.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +# Copyright 2018 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. + +set -eo pipefail + +export NPM_CONFIG_PREFIX=${HOME}/.npm-global + +cd $(dirname $0)/.. + +npm install +# If tests are running against main branch, configure flakybot +# to open issues on failures: +if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"continuous"* ]] || [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"nightly"* ]]; then + export MOCHA_REPORTER_OUTPUT=test_output_sponge_log.xml + export MOCHA_REPORTER=xunit + cleanup() { + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + } + trap cleanup EXIT HUP +fi +# Unit tests exercise the entire API surface, which may include +# deprecation warnings: +export MOCHA_THROW_DEPRECATION=false +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=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 + $NYC_BIN report || true + fi + bash $KOKORO_GFILE_DIR/codecov.sh +else + echo "coverage is only reported for Node $COVERAGE_NODE" +fi diff --git a/handwritten/storage/.kokoro/trampoline.sh b/handwritten/storage/.kokoro/trampoline.sh new file mode 100755 index 00000000000..f693a1ce7aa --- /dev/null +++ b/handwritten/storage/.kokoro/trampoline.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This file is not used any more, but we keep this file for making it +# easy to roll back. +# TODO: Remove this file from the template. + +set -eo pipefail + +# Always run the cleanup script, regardless of the success of bouncing into +# the container. +function cleanup() { + chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + echo "cleanup"; +} +trap cleanup EXIT + +$(dirname $0)/populate-secrets.sh # Secret Manager secrets. +python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" diff --git a/handwritten/storage/.kokoro/trampoline_v2.sh b/handwritten/storage/.kokoro/trampoline_v2.sh new file mode 100755 index 00000000000..e1adcd24e9e --- /dev/null +++ b/handwritten/storage/.kokoro/trampoline_v2.sh @@ -0,0 +1,510 @@ +#!/usr/bin/env bash +# Copyright 2020 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. + +# trampoline_v2.sh +# +# If you want to make a change to this file, consider doing so at: +# https://github.com/googlecloudplatform/docker-ci-helper +# +# This script is for running CI builds. For Kokoro builds, we +# set this script to `build_file` field in the Kokoro configuration. + +# This script does 3 things. +# +# 1. Prepare the Docker image for the test +# 2. Run the Docker with appropriate flags to run the test +# 3. Upload the newly built Docker image +# +# in a way that is somewhat compatible with trampoline_v1. +# +# These environment variables are required: +# TRAMPOLINE_IMAGE: The docker image to use. +# TRAMPOLINE_DOCKERFILE: The location of the Dockerfile. +# +# You can optionally change these environment variables: +# TRAMPOLINE_IMAGE_UPLOAD: +# (true|false): Whether to upload the Docker image after the +# successful builds. +# TRAMPOLINE_BUILD_FILE: The script to run in the docker container. +# TRAMPOLINE_WORKSPACE: The workspace path in the docker container. +# Defaults to /workspace. +# Potentially there are some repo specific envvars in .trampolinerc in +# the project root. +# +# Here is an example for running this script. +# TRAMPOLINE_IMAGE=gcr.io/cloud-devrel-kokoro-resources/node:18-user \ +# TRAMPOLINE_BUILD_FILE=.kokoro/system-test.sh \ +# .kokoro/trampoline_v2.sh + +set -euo pipefail + +TRAMPOLINE_VERSION="2.0.7" + +if command -v tput >/dev/null && [[ -n "${TERM:-}" ]]; then + readonly IO_COLOR_RED="$(tput setaf 1)" + readonly IO_COLOR_GREEN="$(tput setaf 2)" + readonly IO_COLOR_YELLOW="$(tput setaf 3)" + readonly IO_COLOR_RESET="$(tput sgr0)" +else + readonly IO_COLOR_RED="" + readonly IO_COLOR_GREEN="" + readonly IO_COLOR_YELLOW="" + readonly IO_COLOR_RESET="" +fi + +function function_exists { + [ $(LC_ALL=C type -t $1)"" == "function" ] +} + +# Logs a message using the given color. The first argument must be one +# of the IO_COLOR_* variables defined above, such as +# "${IO_COLOR_YELLOW}". The remaining arguments will be logged in the +# given color. The log message will also have an RFC-3339 timestamp +# prepended (in UTC). You can disable the color output by setting +# TERM=vt100. +function log_impl() { + local color="$1" + shift + local timestamp="$(date -u "+%Y-%m-%dT%H:%M:%SZ")" + echo "================================================================" + echo "${color}${timestamp}:" "$@" "${IO_COLOR_RESET}" + echo "================================================================" +} + +# Logs the given message with normal coloring and a timestamp. +function log() { + log_impl "${IO_COLOR_RESET}" "$@" +} + +# Logs the given message in green with a timestamp. +function log_green() { + log_impl "${IO_COLOR_GREEN}" "$@" +} + +# Logs the given message in yellow with a timestamp. +function log_yellow() { + log_impl "${IO_COLOR_YELLOW}" "$@" +} + +# Logs the given message in red with a timestamp. +function log_red() { + log_impl "${IO_COLOR_RED}" "$@" +} + +readonly tmpdir=$(mktemp -d -t ci-XXXXXXXX) +readonly tmphome="${tmpdir}/h" +mkdir -p "${tmphome}" + +function cleanup() { + rm -rf "${tmpdir}" +} +trap cleanup EXIT + +RUNNING_IN_CI="${RUNNING_IN_CI:-false}" + +# The workspace in the container, defaults to /workspace. +TRAMPOLINE_WORKSPACE="${TRAMPOLINE_WORKSPACE:-/workspace}" + +pass_down_envvars=( + # TRAMPOLINE_V2 variables. + # Tells scripts whether they are running as part of CI or not. + "RUNNING_IN_CI" + # Indicates which CI system we're in. + "TRAMPOLINE_CI" + # Indicates the version of the script. + "TRAMPOLINE_VERSION" + # Contains path to build artifacts being executed. + "KOKORO_BUILD_ARTIFACTS_SUBDIR" +) + +log_yellow "Building with Trampoline ${TRAMPOLINE_VERSION}" + +# Detect which CI systems we're in. If we're in any of the CI systems +# we support, `RUNNING_IN_CI` will be true and `TRAMPOLINE_CI` will be +# the name of the CI system. Both envvars will be passing down to the +# container for telling which CI system we're in. +if [[ -n "${KOKORO_BUILD_ID:-}" ]]; then + # descriptive env var for indicating it's on CI. + RUNNING_IN_CI="true" + TRAMPOLINE_CI="kokoro" + if [[ "${TRAMPOLINE_USE_LEGACY_SERVICE_ACCOUNT:-}" == "true" ]]; then + if [[ ! -f "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" ]]; then + log_red "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json does not exist. Did you forget to mount cloud-devrel-kokoro-resources/trampoline? Aborting." + exit 1 + fi + # This service account will be activated later. + TRAMPOLINE_SERVICE_ACCOUNT="${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" + else + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + gcloud auth list + fi + log_yellow "Configuring Container Registry access" + gcloud auth configure-docker --quiet + fi + pass_down_envvars+=( + # KOKORO dynamic variables. + "KOKORO_BUILD_NUMBER" + "KOKORO_BUILD_ID" + "KOKORO_JOB_NAME" + "KOKORO_GIT_COMMIT" + "KOKORO_GITHUB_COMMIT" + "KOKORO_GITHUB_PULL_REQUEST_NUMBER" + "KOKORO_GITHUB_PULL_REQUEST_COMMIT" + # For flakybot + "KOKORO_GITHUB_COMMIT_URL" + "KOKORO_GITHUB_PULL_REQUEST_URL" + ) +elif [[ "${TRAVIS:-}" == "true" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="travis" + pass_down_envvars+=( + "TRAVIS_BRANCH" + "TRAVIS_BUILD_ID" + "TRAVIS_BUILD_NUMBER" + "TRAVIS_BUILD_WEB_URL" + "TRAVIS_COMMIT" + "TRAVIS_COMMIT_MESSAGE" + "TRAVIS_COMMIT_RANGE" + "TRAVIS_JOB_NAME" + "TRAVIS_JOB_NUMBER" + "TRAVIS_JOB_WEB_URL" + "TRAVIS_PULL_REQUEST" + "TRAVIS_PULL_REQUEST_BRANCH" + "TRAVIS_PULL_REQUEST_SHA" + "TRAVIS_PULL_REQUEST_SLUG" + "TRAVIS_REPO_SLUG" + "TRAVIS_SECURE_ENV_VARS" + "TRAVIS_TAG" + ) +elif [[ -n "${GITHUB_RUN_ID:-}" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="github-workflow" + pass_down_envvars+=( + "GITHUB_WORKFLOW" + "GITHUB_RUN_ID" + "GITHUB_RUN_NUMBER" + "GITHUB_ACTION" + "GITHUB_ACTIONS" + "GITHUB_ACTOR" + "GITHUB_REPOSITORY" + "GITHUB_EVENT_NAME" + "GITHUB_EVENT_PATH" + "GITHUB_SHA" + "GITHUB_REF" + "GITHUB_HEAD_REF" + "GITHUB_BASE_REF" + ) +elif [[ "${CIRCLECI:-}" == "true" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="circleci" + pass_down_envvars+=( + "CIRCLE_BRANCH" + "CIRCLE_BUILD_NUM" + "CIRCLE_BUILD_URL" + "CIRCLE_COMPARE_URL" + "CIRCLE_JOB" + "CIRCLE_NODE_INDEX" + "CIRCLE_NODE_TOTAL" + "CIRCLE_PREVIOUS_BUILD_NUM" + "CIRCLE_PROJECT_REPONAME" + "CIRCLE_PROJECT_USERNAME" + "CIRCLE_REPOSITORY_URL" + "CIRCLE_SHA1" + "CIRCLE_STAGE" + "CIRCLE_USERNAME" + "CIRCLE_WORKFLOW_ID" + "CIRCLE_WORKFLOW_JOB_ID" + "CIRCLE_WORKFLOW_UPSTREAM_JOB_IDS" + "CIRCLE_WORKFLOW_WORKSPACE_ID" + ) +fi + +# Configure the service account for pulling the docker image. +function repo_root() { + local dir="$1" + while [[ ! -d "${dir}/.git" ]]; do + dir="$(dirname "$dir")" + done + echo "${dir}" +} + +# Detect the project root. In CI builds, we assume the script is in +# the git tree and traverse from there, otherwise, traverse from `pwd` +# to find `.git` directory. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + PROGRAM_PATH="$(realpath "$0")" + PROGRAM_DIR="$(dirname "${PROGRAM_PATH}")" + PROJECT_ROOT="$(repo_root "${PROGRAM_DIR}")/handwritten/storage" +else + PROJECT_ROOT="$(repo_root $(pwd))/handwritten/storage" +fi + +log_yellow "Changing to the project root: ${PROJECT_ROOT}." +cd "${PROJECT_ROOT}" + +# Auto-injected conditional check +# Check if the package directory has changes. If not, skip tests. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + # The package path is hardcoded during migration + RELATIVE_PKG_PATH="handwritten/storage" + + echo "Checking for changes in ${RELATIVE_PKG_PATH}..." + + # Determine the diff range based on the CI system/event + # Safe default: HEAD~1..HEAD + DIFF_RANGE="HEAD~1..HEAD" + + if git diff --quiet "${DIFF_RANGE}" -- "${RELATIVE_PKG_PATH}"; then + echo "No changes detected in ${RELATIVE_PKG_PATH}. Skipping tests." + exit 0 + else + echo "Changes detected in ${RELATIVE_PKG_PATH}. Proceeding with tests." + fi +fi + +# To support relative path for `TRAMPOLINE_SERVICE_ACCOUNT`, we need +# to use this environment variable in `PROJECT_ROOT`. +if [[ -n "${TRAMPOLINE_SERVICE_ACCOUNT:-}" ]]; then + + mkdir -p "${tmpdir}/gcloud" + gcloud_config_dir="${tmpdir}/gcloud" + + log_yellow "Using isolated gcloud config: ${gcloud_config_dir}." + export CLOUDSDK_CONFIG="${gcloud_config_dir}" + + log_yellow "Using ${TRAMPOLINE_SERVICE_ACCOUNT} for authentication." + gcloud auth activate-service-account \ + --key-file "${TRAMPOLINE_SERVICE_ACCOUNT}" + log_yellow "Configuring Container Registry access" + gcloud auth configure-docker --quiet +fi + +required_envvars=( + # The basic trampoline configurations. + "TRAMPOLINE_IMAGE" + "TRAMPOLINE_BUILD_FILE" +) + +if [[ -f "${PROJECT_ROOT}/.trampolinerc" ]]; then + source "${PROJECT_ROOT}/.trampolinerc" +fi + +log_yellow "Checking environment variables." +for e in "${required_envvars[@]}" +do + if [[ -z "${!e:-}" ]]; then + log "Missing ${e} env var. Aborting." + exit 1 + fi +done + +# We want to support legacy style TRAMPOLINE_BUILD_FILE used with V1 +# script: e.g. "github/repo-name/.kokoro/run_tests.sh" +TRAMPOLINE_BUILD_FILE="${TRAMPOLINE_BUILD_FILE#github/*/}" +log_yellow "Using TRAMPOLINE_BUILD_FILE: ${TRAMPOLINE_BUILD_FILE}" + +# ignore error on docker operations and test execution +set +e + +log_yellow "Preparing Docker image." +# We only download the docker image in CI builds. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + # Download the docker image specified by `TRAMPOLINE_IMAGE` + + # We may want to add --max-concurrent-downloads flag. + + log_yellow "Start pulling the Docker image: ${TRAMPOLINE_IMAGE}." + if docker pull "${TRAMPOLINE_IMAGE}"; then + log_green "Finished pulling the Docker image: ${TRAMPOLINE_IMAGE}." + has_image="true" + else + log_red "Failed pulling the Docker image: ${TRAMPOLINE_IMAGE}." + has_image="false" + fi +else + # For local run, check if we have the image. + if docker images "${TRAMPOLINE_IMAGE}" | grep "${TRAMPOLINE_IMAGE%:*}"; then + has_image="true" + else + has_image="false" + fi +fi + + +# The default user for a Docker container has uid 0 (root). To avoid +# creating root-owned files in the build directory we tell docker to +# use the current user ID. +user_uid="$(id -u)" +user_gid="$(id -g)" +user_name="$(id -un)" + +# To allow docker in docker, we add the user to the docker group in +# the host os. +docker_gid=$(cut -d: -f3 < <(getent group docker)) + +update_cache="false" +if [[ "${TRAMPOLINE_DOCKERFILE:-none}" != "none" ]]; then + # Build the Docker image from the source. + context_dir=$(dirname "${TRAMPOLINE_DOCKERFILE}") + docker_build_flags=( + "-f" "${TRAMPOLINE_DOCKERFILE}" + "-t" "${TRAMPOLINE_IMAGE}" + "--build-arg" "UID=${user_uid}" + "--build-arg" "USERNAME=${user_name}" + ) + if [[ "${has_image}" == "true" ]]; then + docker_build_flags+=("--cache-from" "${TRAMPOLINE_IMAGE}") + fi + + log_yellow "Start building the docker image." + if [[ "${TRAMPOLINE_VERBOSE:-false}" == "true" ]]; then + echo "docker build" "${docker_build_flags[@]}" "${context_dir}" + fi + + # ON CI systems, we want to suppress docker build logs, only + # output the logs when it fails. + if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + if docker build "${docker_build_flags[@]}" "${context_dir}" \ + > "${tmpdir}/docker_build.log" 2>&1; then + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + cat "${tmpdir}/docker_build.log" + fi + + log_green "Finished building the docker image." + update_cache="true" + else + log_red "Failed to build the Docker image, aborting." + log_yellow "Dumping the build logs:" + cat "${tmpdir}/docker_build.log" + exit 1 + fi + else + if docker build "${docker_build_flags[@]}" "${context_dir}"; then + log_green "Finished building the docker image." + update_cache="true" + else + log_red "Failed to build the Docker image, aborting." + exit 1 + fi + fi +else + if [[ "${has_image}" != "true" ]]; then + log_red "We do not have ${TRAMPOLINE_IMAGE} locally, aborting." + exit 1 + fi +fi + +# We use an array for the flags so they are easier to document. +docker_flags=( + # Remove the container after it exists. + "--rm" + + # Use the host network. + "--network=host" + + # Run in priviledged mode. We are not using docker for sandboxing or + # isolation, just for packaging our dev tools. + "--privileged" + + # Run the docker script with the user id. Because the docker image gets to + # write in ${PWD} you typically want this to be your user id. + # To allow docker in docker, we need to use docker gid on the host. + "--user" "${user_uid}:${docker_gid}" + + # Pass down the USER. + "--env" "USER=${user_name}" + + # Mount the project directory inside the Docker container. + "--volume" "${PROJECT_ROOT}:${TRAMPOLINE_WORKSPACE}" + "--workdir" "${TRAMPOLINE_WORKSPACE}" + "--env" "PROJECT_ROOT=${TRAMPOLINE_WORKSPACE}" + + # Mount the temporary home directory. + "--volume" "${tmphome}:/h" + "--env" "HOME=/h" + + # Allow docker in docker. + "--volume" "/var/run/docker.sock:/var/run/docker.sock" + + # Mount the /tmp so that docker in docker can mount the files + # there correctly. + "--volume" "/tmp:/tmp" + # Pass down the KOKORO_GFILE_DIR and KOKORO_KEYSTORE_DIR + # TODO(tmatsuo): This part is not portable. + "--env" "TRAMPOLINE_SECRET_DIR=/secrets" + "--volume" "${KOKORO_GFILE_DIR:-/dev/shm}:/secrets/gfile" + "--env" "KOKORO_GFILE_DIR=/secrets/gfile" + "--volume" "${KOKORO_KEYSTORE_DIR:-/dev/shm}:/secrets/keystore" + "--env" "KOKORO_KEYSTORE_DIR=/secrets/keystore" +) + +# Add an option for nicer output if the build gets a tty. +if [[ -t 0 ]]; then + docker_flags+=("-it") +fi + +# Passing down env vars +for e in "${pass_down_envvars[@]}" +do + if [[ -n "${!e:-}" ]]; then + docker_flags+=("--env" "${e}=${!e}") + fi +done + +# If arguments are given, all arguments will become the commands run +# in the container, otherwise run TRAMPOLINE_BUILD_FILE. +if [[ $# -ge 1 ]]; then + log_yellow "Running the given commands '" "${@:1}" "' in the container." + readonly commands=("${@:1}") + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" + fi + docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" +else + log_yellow "Running the tests in a Docker container." + docker_flags+=("--entrypoint=${TRAMPOLINE_BUILD_FILE}") + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" + fi + docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" +fi + + +test_retval=$? + +if [[ ${test_retval} -eq 0 ]]; then + log_green "Build finished with ${test_retval}" +else + log_red "Build finished with ${test_retval}" +fi + +# Only upload it when the test passes. +if [[ "${update_cache}" == "true" ]] && \ + [[ $test_retval == 0 ]] && \ + [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]]; then + log_yellow "Uploading the Docker image." + if docker push "${TRAMPOLINE_IMAGE}"; then + log_green "Finished uploading the Docker image." + else + log_red "Failed uploading the Docker image." + fi + # Call trampoline_after_upload_hook if it's defined. + if function_exists trampoline_after_upload_hook; then + trampoline_after_upload_hook + fi + +fi + +exit "${test_retval}" diff --git a/handwritten/storage/.mocharc.cjs b/handwritten/storage/.mocharc.cjs new file mode 100644 index 00000000000..0b600509bed --- /dev/null +++ b/handwritten/storage/.mocharc.cjs @@ -0,0 +1,29 @@ +// Copyright 2020 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. +const config = { + "enable-source-maps": true, + "throw-deprecation": true, + "timeout": 10000, + "recursive": true +} +if (process.env.MOCHA_THROW_DEPRECATION === 'false') { + delete config['throw-deprecation']; +} +if (process.env.MOCHA_REPORTER) { + config.reporter = process.env.MOCHA_REPORTER; +} +if (process.env.MOCHA_REPORTER_OUTPUT) { + config['reporter-option'] = `output=${process.env.MOCHA_REPORTER_OUTPUT}`; +} +module.exports = config diff --git a/handwritten/storage/.nycrc b/handwritten/storage/.nycrc new file mode 100644 index 00000000000..b18d5472b62 --- /dev/null +++ b/handwritten/storage/.nycrc @@ -0,0 +1,24 @@ +{ + "report-dir": "./.coverage", + "reporter": ["text", "lcov"], + "exclude": [ + "**/*-test", + "**/.coverage", + "**/apis", + "**/benchmark", + "**/conformance", + "**/docs", + "**/samples", + "**/scripts", + "**/protos", + "**/test", + "**/*.d.ts", + ".jsdoc.js", + "**/.jsdoc.js", + "karma.conf.js", + "webpack-tests.config.js", + "webpack.config.js" + ], + "exclude-after-remap": false, + "all": true +} diff --git a/handwritten/storage/.prettierignore b/handwritten/storage/.prettierignore new file mode 100644 index 00000000000..9340ad9b86d --- /dev/null +++ b/handwritten/storage/.prettierignore @@ -0,0 +1,6 @@ +**/node_modules +**/coverage +test/fixtures +build/ +docs/ +protos/ diff --git a/handwritten/storage/.prettierrc.cjs b/handwritten/storage/.prettierrc.cjs new file mode 100644 index 00000000000..d1b95106f4c --- /dev/null +++ b/handwritten/storage/.prettierrc.cjs @@ -0,0 +1,17 @@ +// Copyright 2020 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. + +module.exports = { + ...require('gts/.prettierrc.json') +} diff --git a/handwritten/storage/.readme-partials.yaml b/handwritten/storage/.readme-partials.yaml new file mode 100644 index 00000000000..f764f6b95a3 --- /dev/null +++ b/handwritten/storage/.readme-partials.yaml @@ -0,0 +1,8 @@ +introduction: |- + > Node.js idiomatic client for [Cloud Storage][product-docs]. + + [Cloud Storage](https://cloud.google.com/storage/docs) allows world-wide + storage and retrieval of any amount of data at any time. You can use Google + Cloud Storage for a range of scenarios including serving website content, + storing data for archival and disaster recovery, or distributing large data + objects to users via direct download. diff --git a/handwritten/storage/.repo-metadata.json b/handwritten/storage/.repo-metadata.json new file mode 100644 index 00000000000..20b7ff6ce50 --- /dev/null +++ b/handwritten/storage/.repo-metadata.json @@ -0,0 +1,16 @@ +{ + "name": "storage", + "name_pretty": "Google Cloud Storage", + "product_documentation": "https://cloud.google.com/storage", + "client_documentation": "https://cloud.google.com/nodejs/docs/reference/storage/latest", + "issue_tracker": "https://issuetracker.google.com/savedsearches/559782", + "release_level": "stable", + "language": "nodejs", + "repo": "googleapis/google-cloud-node", + "distribution_name": "@google-cloud/storage", + "api_id": "storage-api.googleapis.com", + "requires_billing": true, + "codeowner_team": "@googleapis/gcs-team", + "api_shortname": "storage", + "library_type": "GAPIC_MANUAL" +} diff --git a/handwritten/storage/.trampolinerc b/handwritten/storage/.trampolinerc new file mode 100644 index 00000000000..2feed5b5844 --- /dev/null +++ b/handwritten/storage/.trampolinerc @@ -0,0 +1,52 @@ +# Copyright 2020 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. + +# Template for .trampolinerc + +# Add required env vars here. +required_envvars+=( +) + +# Add env vars which are passed down into the container here. +pass_down_envvars+=( + "AUTORELEASE_PR" + "VERSION" +) + +# Prevent unintentional override on the default image. +if [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]] && \ + [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + echo "Please set TRAMPOLINE_IMAGE if you want to upload the Docker image." + exit 1 +fi + +# Define the default value if it makes sense. +if [[ -z "${TRAMPOLINE_IMAGE_UPLOAD:-}" ]]; then + TRAMPOLINE_IMAGE_UPLOAD="" +fi + +if [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + TRAMPOLINE_IMAGE="" +fi + +if [[ -z "${TRAMPOLINE_DOCKERFILE:-}" ]]; then + TRAMPOLINE_DOCKERFILE="" +fi + +if [[ -z "${TRAMPOLINE_BUILD_FILE:-}" ]]; then + TRAMPOLINE_BUILD_FILE="" +fi + +# Secret Manager secrets. +source ${PROJECT_ROOT}/handwritten/storage/.kokoro/populate-secrets.sh diff --git a/handwritten/storage/CHANGELOG.md b/handwritten/storage/CHANGELOG.md new file mode 100644 index 00000000000..e6b755e5812 --- /dev/null +++ b/handwritten/storage/CHANGELOG.md @@ -0,0 +1,1824 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/@google-cloud/storage?activeTab=versions + +## [7.19.0](https://github.com/googleapis/nodejs-storage/compare/v7.18.0...v7.19.0) (2026-02-05) + + +### Features + +* Enable full object checksum validation on JSON path ([#2687](https://github.com/googleapis/nodejs-storage/issues/2687)) ([08a8962](https://github.com/googleapis/nodejs-storage/commit/08a896240e2ee110c13a5803ce5a2fbf38fbedc4)) + + +### Bug Fixes + +* **deps:** Update dependency fast-xml-parser to v5 [security] ([#2713](https://github.com/googleapis/nodejs-storage/issues/2713)) ([420935a](https://github.com/googleapis/nodejs-storage/commit/420935a0334b0723ec052bb4d6b8527dd2acffea)) + +## [7.18.0](https://github.com/googleapis/nodejs-storage/compare/v7.17.3...v7.18.0) (2025-11-28) + + +### Features + +* **listBuckets:** Add support for returning partial success ([#2678](https://github.com/googleapis/nodejs-storage/issues/2678)) ([c7004da](https://github.com/googleapis/nodejs-storage/commit/c7004daae0b506eeefc5f4f241d9e3df3589b0e8)) + +## [7.17.3](https://github.com/googleapis/nodejs-storage/compare/v7.17.2...v7.17.3) (2025-11-03) + + +### Bug Fixes + +* :bug: fix the issue 2667, do not mutate object given to options … ([#2668](https://github.com/googleapis/nodejs-storage/issues/2668)) ([8a9f259](https://github.com/googleapis/nodejs-storage/commit/8a9f25968a08dc5cdaeb056054104db738fe651b)) +* Revert implement path containment to prevent traversal attacks ([254b6b2](https://github.com/googleapis/nodejs-storage/commit/254b6b2f9e79ce2e572f87694998538c9b1371c1)) + +## [7.17.2](https://github.com/googleapis/nodejs-storage/compare/v7.17.1...v7.17.2) (2025-10-06) + + +### Bug Fixes + +* Common Service: should retry a request failed ([#2652](https://github.com/googleapis/nodejs-storage/issues/2652)) ([b38b5d2](https://github.com/googleapis/nodejs-storage/commit/b38b5d221f2cb72658c1eb4a726315ab395a542c)) +* Implement path containment to prevent traversal attacks ([#2654](https://github.com/googleapis/nodejs-storage/issues/2654)) ([08d7abf](https://github.com/googleapis/nodejs-storage/commit/08d7abf32dd365b24ce34c66174be06c30bfce8f)) + +## [7.17.1](https://github.com/googleapis/nodejs-storage/compare/v7.17.0...v7.17.1) (2025-08-27) + + +### Bug Fixes + +* Respect useAuthWithCustomEndpoint flag for resumable uploads ([#2637](https://github.com/googleapis/nodejs-storage/issues/2637)) ([707b4f2](https://github.com/googleapis/nodejs-storage/commit/707b4f2fe1d67878bcd8f1434e4cbb57c951994e)) + +## [7.17.0](https://github.com/googleapis/nodejs-storage/compare/v7.16.0...v7.17.0) (2025-08-18) + + +### Features + +* Add CSEK to download ([#2604](https://github.com/googleapis/nodejs-storage/issues/2604)) ([cacc0be](https://github.com/googleapis/nodejs-storage/commit/cacc0be49a4fe81c384180bdfd77820b6b3f3001)) + + +### Bug Fixes + +* Propagate errors when using pipelines ([#2560](https://github.com/googleapis/nodejs-storage/issues/2560)) ([#2624](https://github.com/googleapis/nodejs-storage/issues/2624)) ([a43b490](https://github.com/googleapis/nodejs-storage/commit/a43b4904ecf2ebacde22bc6efbdcf97ac886e28d)) +* Typo correction ([#2610](https://github.com/googleapis/nodejs-storage/issues/2610)) ([9cae69c](https://github.com/googleapis/nodejs-storage/commit/9cae69cc280227737b5a1a1476eae1b2612b162b)) + +## [7.16.0](https://github.com/googleapis/nodejs-storage/compare/v7.15.2...v7.16.0) (2025-03-31) + + +### Features + +* Add moveFileAtomic method ([#2586](https://github.com/googleapis/nodejs-storage/issues/2586)) ([e25fb8c](https://github.com/googleapis/nodejs-storage/commit/e25fb8c659dbdf4a08c87fe2a929c8d62e6162e1)) + +## [7.15.2](https://github.com/googleapis/nodejs-storage/compare/v7.15.1...v7.15.2) (2025-02-20) + + +### Bug Fixes + +* Export SaveData type from index.ts ([#2580](https://github.com/googleapis/nodejs-storage/issues/2580)) ([dbf510c](https://github.com/googleapis/nodejs-storage/commit/dbf510c08f28c720ba66268eea6a62e139179ab4)) + +## [7.15.1](https://github.com/googleapis/nodejs-storage/compare/v7.15.0...v7.15.1) (2025-02-11) + + +### Bug Fixes + +* **getFiles:** Add nextPageToken to fields for autoPaginate ([#2570](https://github.com/googleapis/nodejs-storage/issues/2570)) ([75c309c](https://github.com/googleapis/nodejs-storage/commit/75c309c0761e4029dcd13024e748d8957052f766)) + +## [7.15.0](https://github.com/googleapis/nodejs-storage/compare/v7.14.0...v7.15.0) (2024-12-20) + + +### Features + +* Add ability to configure and utilize soft-delete and restore buckets ([#2566](https://github.com/googleapis/nodejs-storage/issues/2566)) ([25cdbb9](https://github.com/googleapis/nodejs-storage/commit/25cdbb918645362ce6994679e8a1c5e7cc666c87)) + +## [7.14.0](https://github.com/googleapis/nodejs-storage/compare/v7.13.0...v7.14.0) (2024-10-29) + + +### Features + +* Add support for restore token ([#2548](https://github.com/googleapis/nodejs-storage/issues/2548)) ([8241e91](https://github.com/googleapis/nodejs-storage/commit/8241e91e78d47b4cdaea2d941f75fd6a4fa29230)) +* Adds integration tests for Universe Domain configuration ([#2538](https://github.com/googleapis/nodejs-storage/issues/2538)) ([53db6ba](https://github.com/googleapis/nodejs-storage/commit/53db6ba7406b99e507cacfa6195cb5a7d308914b)) +* Adds integration tests for Universe Domain configuration with ([53db6ba](https://github.com/googleapis/nodejs-storage/commit/53db6ba7406b99e507cacfa6195cb5a7d308914b)) +* **storage:** Add support for 'skipIfExists' option for downloadMany ([#2526](https://github.com/googleapis/nodejs-storage/issues/2526)) ([729efb2](https://github.com/googleapis/nodejs-storage/commit/729efb213f96b1a406a1caa54870f50e96796639)) + +## [7.13.0](https://github.com/googleapis/nodejs-storage/compare/v7.12.1...v7.13.0) (2024-09-17) + + +### Features + +* **storage:** Add support for 'fields' query parameter to getFiles ([#2521](https://github.com/googleapis/nodejs-storage/issues/2521)) ([f78fe92](https://github.com/googleapis/nodejs-storage/commit/f78fe92348a0b383314b4fbfb55638d47af052ff)) + + +### Bug Fixes + +* **retry:** Export RETRYABLE_ERR_FN_DEFAULT ([#2517](https://github.com/googleapis/nodejs-storage/issues/2517)) ([db890fd](https://github.com/googleapis/nodejs-storage/commit/db890fd1b25d5cd94e3bcd97ec21fa8f77b1b724)) + +## [7.12.1](https://github.com/googleapis/nodejs-storage/compare/v7.12.0...v7.12.1) (2024-08-07) + + +### Bug Fixes + +* **deps:** Update fast-xml-parser to 4.4.1 due to security vulnerability ([#2505](https://github.com/googleapis/nodejs-storage/issues/2505)) ([b97d474](https://github.com/googleapis/nodejs-storage/commit/b97d474445efbcde91e690f6ea4160cfc9fd1ed4)) + +## [7.12.0](https://github.com/googleapis/nodejs-storage/compare/v7.11.3...v7.12.0) (2024-07-15) + + +### Features + +* Add function to allow user to set destination in transfer manager ([#2497](https://github.com/googleapis/nodejs-storage/issues/2497)) ([dc1e488](https://github.com/googleapis/nodejs-storage/commit/dc1e488b50dd7e2deab3e8b28c7d6ece36b90b0e)) + +## [7.11.3](https://github.com/googleapis/nodejs-storage/compare/v7.11.2...v7.11.3) (2024-07-09) + + +### Bug Fixes + +* Error serialization in resumable-upload.ts ([#2493](https://github.com/googleapis/nodejs-storage/issues/2493)) ([c2e555c](https://github.com/googleapis/nodejs-storage/commit/c2e555c95f7a8e3e231e57e2fa3967caeb860772)) +* Handle unhandled error in `startResumableUpload_` ([#2495](https://github.com/googleapis/nodejs-storage/issues/2495)) ([d5257ba](https://github.com/googleapis/nodejs-storage/commit/d5257ba4aa9efc1dd70c303286782d23a95e8568)) +* Make CreateBucketRequest extend from BucketMetadata to allow all… ([#2489](https://github.com/googleapis/nodejs-storage/issues/2489)) ([013a5a4](https://github.com/googleapis/nodejs-storage/commit/013a5a45aed8734f797837deb0e805f0ca43a9a6)) + +## [7.11.2](https://github.com/googleapis/nodejs-storage/compare/v7.11.1...v7.11.2) (2024-06-07) + + +### Bug Fixes + +* Support uint8array in file.save ([#2480](https://github.com/googleapis/nodejs-storage/issues/2480)) ([1477fe1](https://github.com/googleapis/nodejs-storage/commit/1477fe15e5b6dae7cdfb2a1d00121e5d674c8f7c)) + +## [7.11.1](https://github.com/googleapis/nodejs-storage/compare/v7.11.0...v7.11.1) (2024-05-21) + + +### Bug Fixes + +* Add missing projectIdentifier to GetServiceAccountOptions ([#2468](https://github.com/googleapis/nodejs-storage/issues/2468)) ([d49e9d2](https://github.com/googleapis/nodejs-storage/commit/d49e9d2cbab42eb2390eeeccc562e3283df6384c)) +* Allow files in directories to be downloaded onto local machine ([#2199](https://github.com/googleapis/nodejs-storage/issues/2199)) ([9f62429](https://github.com/googleapis/nodejs-storage/commit/9f62429dad234167dc6f0969b40c7942bab83aee)) +* Do not set `customEndpoint` if `apiEndpoint === default` ([#2460](https://github.com/googleapis/nodejs-storage/issues/2460)) ([b4dbd73](https://github.com/googleapis/nodejs-storage/commit/b4dbd73189b9fae4c23d614753670ee562bc717b)) +* Improve GetFilesResponse interface ([#2466](https://github.com/googleapis/nodejs-storage/issues/2466)) ([918db28](https://github.com/googleapis/nodejs-storage/commit/918db2818395488ff925324a9962879bb56368d7)) + +## [7.11.0](https://github.com/googleapis/nodejs-storage/compare/v7.10.2...v7.11.0) (2024-05-03) + + +### Features + +* Add ability to enable hierarchical namespace on buckets ([#2453](https://github.com/googleapis/nodejs-storage/issues/2453)) ([4e5726f](https://github.com/googleapis/nodejs-storage/commit/4e5726fe60ecede6bec6508e4b4ec214f2e173dd)) + +## [7.10.2](https://github.com/googleapis/nodejs-storage/compare/v7.10.1...v7.10.2) (2024-04-26) + + +### Bug Fixes + +* Use correct indices for file.from and fix tests to verify names ([#2449](https://github.com/googleapis/nodejs-storage/issues/2449)) ([d4240fa](https://github.com/googleapis/nodejs-storage/commit/d4240fa5c8c0353de81cc8c052eea2915c3e383c)) + +## [7.10.1](https://github.com/googleapis/nodejs-storage/compare/v7.10.0...v7.10.1) (2024-04-22) + + +### Bug Fixes + +* Change copyoptions type ([#2439](https://github.com/googleapis/nodejs-storage/issues/2439)) ([2ebd7ac](https://github.com/googleapis/nodejs-storage/commit/2ebd7aca6c474147e5a1d1fb2a96b7d052a08a21)) +* Expand types of custom metadata within FileMetadata ([#2442](https://github.com/googleapis/nodejs-storage/issues/2442)) ([1d434a9](https://github.com/googleapis/nodejs-storage/commit/1d434a905392b00bb48ebbb812034e062ed27dd2)) + +## [7.10.0](https://github.com/googleapis/nodejs-storage/compare/v7.9.0...v7.10.0) (2024-04-15) + + +### Features + +* Add ability to create a File object from URL ([#2432](https://github.com/googleapis/nodejs-storage/issues/2432)) ([1b71fcc](https://github.com/googleapis/nodejs-storage/commit/1b71fcc7687fb8d66e04fb92b15671729f1407e7)) +* Allow setting contentEncoding during compose ([#2431](https://github.com/googleapis/nodejs-storage/issues/2431)) ([6e81e05](https://github.com/googleapis/nodejs-storage/commit/6e81e05b2615f1b8307fcca9a147362677e95e7f)) + + +### Bug Fixes + +* Destroy pipeline streams when returned stream errors ([#2437](https://github.com/googleapis/nodejs-storage/issues/2437)) ([fe1ac65](https://github.com/googleapis/nodejs-storage/commit/fe1ac655a8d321e225f4828c7adf57342c4a8455)) +* Remove extraneous mime-types package in favor of mime ([#2435](https://github.com/googleapis/nodejs-storage/issues/2435)) ([63a71f2](https://github.com/googleapis/nodejs-storage/commit/63a71f2e81181ad976e982ef79d6148913a87c1f)) + +## [7.9.0](https://github.com/googleapis/nodejs-storage/compare/v7.8.0...v7.9.0) (2024-03-18) + + +### Features + +* Add ability to configure and utilize soft-delete and restore ([#2425](https://github.com/googleapis/nodejs-storage/issues/2425)) ([7da5a7d](https://github.com/googleapis/nodejs-storage/commit/7da5a7da86ad649a8132e3183f4b3e3f9bb2eace)) + +## [7.8.0](https://github.com/googleapis/nodejs-storage/compare/v7.7.0...v7.8.0) (2024-03-07) + + +### Features + +* Add includeFoldersAsPrefixes for managed folders ([#2413](https://github.com/googleapis/nodejs-storage/issues/2413)) ([3044d3c](https://github.com/googleapis/nodejs-storage/commit/3044d3cfb1b4a24f07fd6ec29e3d20d5818c4ca3)) +* Base TPC Support ([#2397](https://github.com/googleapis/nodejs-storage/issues/2397)) ([a3f4891](https://github.com/googleapis/nodejs-storage/commit/a3f4891ee60e57cc19929489cae6110b07955216)) + + +### Bug Fixes + +* Cannot read properties of null (reading length) in stream-shift ([#2422](https://github.com/googleapis/nodejs-storage/issues/2422)) ([11ebe2b](https://github.com/googleapis/nodejs-storage/commit/11ebe2bf905f8c15101446ecfe5a2d7c6005d0c3)) +* Do not automatically set overrideUnlockedRetention ([#2421](https://github.com/googleapis/nodejs-storage/issues/2421)) ([c781bdc](https://github.com/googleapis/nodejs-storage/commit/c781bdcd89f63b22af1c491a6e517e110331d4ca)) + +## [7.7.0](https://github.com/googleapis/nodejs-storage/compare/v7.6.0...v7.7.0) (2023-11-29) + + +### Features + +* Implement object retention lock for bucket / files ([#2365](https://github.com/googleapis/nodejs-storage/issues/2365)) ([c140868](https://github.com/googleapis/nodejs-storage/commit/c140868bb5c7d1f0edd586fb2ca55bc613caf5d4)) + + +### Bug Fixes + +* TransferManager#downloadFileInChunks issues ([#2373](https://github.com/googleapis/nodejs-storage/issues/2373)) ([65950f3](https://github.com/googleapis/nodejs-storage/commit/65950f3d5c2ed73c56afdf579d7a949b4505e649)) + +## [7.6.0](https://github.com/googleapis/nodejs-storage/compare/v7.5.0...v7.6.0) (2023-11-08) + + +### Features + +* Resume Resumable Uploads ([#2333](https://github.com/googleapis/nodejs-storage/issues/2333)) ([2ba4009](https://github.com/googleapis/nodejs-storage/commit/2ba4009e599c5690c51849f307199be3452d3b07)) + +## [7.5.0](https://github.com/googleapis/nodejs-storage/compare/v7.4.0...v7.5.0) (2023-10-30) + + +### Features + +* Support autoclass v2.1 ([#2325](https://github.com/googleapis/nodejs-storage/issues/2325)) ([6572ce9](https://github.com/googleapis/nodejs-storage/commit/6572ce9dc146a0d1e13418a43204058d5909510e)) + +## [7.4.0](https://github.com/googleapis/nodejs-storage/compare/v7.3.2...v7.4.0) (2023-10-24) + + +### Features + +* Support building in CJS and ESM formats ([#2296](https://github.com/googleapis/nodejs-storage/issues/2296)) ([c848076](https://github.com/googleapis/nodejs-storage/commit/c84807662839b3671230a50b2a0c6f7a6efef528)) + +## [7.3.2](https://github.com/googleapis/nodejs-storage/compare/v7.3.1...v7.3.2) (2023-10-24) + + +### Bug Fixes + +* Close Open Handle for Empty Objects ([#2338](https://github.com/googleapis/nodejs-storage/issues/2338)) ([c51cd94](https://github.com/googleapis/nodejs-storage/commit/c51cd946171e8749453eef080d2853d31a6e72c8)) + +## [7.3.1](https://github.com/googleapis/nodejs-storage/compare/v7.3.0...v7.3.1) (2023-10-19) + + +### Bug Fixes + +* Add user-agent header to transfer manager and resumable upload ([#2334](https://github.com/googleapis/nodejs-storage/issues/2334)) ([0520867](https://github.com/googleapis/nodejs-storage/commit/0520867e51a2758ddf2773c0d910c937d55e21b1)) +* **deps:** Update dependency retry-request to v7 ([#2327](https://github.com/googleapis/nodejs-storage/issues/2327)) ([f20ef3c](https://github.com/googleapis/nodejs-storage/commit/f20ef3cb7bf8cbdda988e792edc7abd9a1b516f1)) +* Destroy sockets to stop memory leaking when stream errors ([#2336](https://github.com/googleapis/nodejs-storage/issues/2336)) ([04939ee](https://github.com/googleapis/nodejs-storage/commit/04939ee4976581cc4168943f0c578bc49458cff7)) + +## [7.3.0](https://github.com/googleapis/nodejs-storage/compare/v7.2.0...v7.3.0) (2023-10-11) + + +### Features + +* Add transfer manager MPU sample, adjust defaults, prepare for GA ([#2318](https://github.com/googleapis/nodejs-storage/issues/2318)) ([a7d09c1](https://github.com/googleapis/nodejs-storage/commit/a7d09c16aa7f732db089c55d2692ce5fd88c52f3)) + + +### Bug Fixes + +* Simplify the code for downloadInChunks ([#2323](https://github.com/googleapis/nodejs-storage/issues/2323)) ([6519929](https://github.com/googleapis/nodejs-storage/commit/6519929153e0006b61d205860de93c9e64b99d81)) + +## [7.2.0](https://github.com/googleapis/nodejs-storage/compare/v7.1.0...v7.2.0) (2023-10-05) + + +### Features + +* Add headers option to MPU ([#2303](https://github.com/googleapis/nodejs-storage/issues/2303)) ([7f58f30](https://github.com/googleapis/nodejs-storage/commit/7f58f30588735d129fda0503e1daec5f605f8447)) +* Transfer Manager Metrics ([#2305](https://github.com/googleapis/nodejs-storage/issues/2305)) ([9be3b6a](https://github.com/googleapis/nodejs-storage/commit/9be3b6a97d9c4685d3c01a6d44e618087be54ea1)) + + +### Bug Fixes + +* Make sure destination uses posix separator instead of win ([#2304](https://github.com/googleapis/nodejs-storage/issues/2304)) ([1d4ea74](https://github.com/googleapis/nodejs-storage/commit/1d4ea74a3cc441dfccc47893f0318234f213921b)) + +## [7.1.0](https://github.com/googleapis/nodejs-storage/compare/v7.0.1...v7.1.0) (2023-09-07) + + +### Features + +* Export `ApiError` ([#2291](https://github.com/googleapis/nodejs-storage/issues/2291)) ([c1d1b35](https://github.com/googleapis/nodejs-storage/commit/c1d1b3505b1c6b0306f632a48cbd7d774b2b94d0)) +* Support iterables in file@save ([4356dd0](https://github.com/googleapis/nodejs-storage/commit/4356dd0e6bea5241c4cacd1a58697a332ccf4784)) +* Support iterables in file@save ([49327ff](https://github.com/googleapis/nodejs-storage/commit/49327ff576b2367d9efdff2f82a515b0538ee471)) +* Support iterables in file@save ([c0d9d58](https://github.com/googleapis/nodejs-storage/commit/c0d9d58b56a9a3485b6c0e5eb92411bb094f7bcb)) + + +### Bug Fixes + +* `File#save` iterable fixes ([#2293](https://github.com/googleapis/nodejs-storage/issues/2293)) ([87c3f41](https://github.com/googleapis/nodejs-storage/commit/87c3f419e2a5a3a30ea581aaa6127dfac261be17)) +* **deps:** Update dependency @google-cloud/paginator to v5 ([#2263](https://github.com/googleapis/nodejs-storage/issues/2263)) ([0c9b342](https://github.com/googleapis/nodejs-storage/commit/0c9b3425b47c3031ec4bac6d45d8cdca48b2f1a6)) +* **deps:** Update dependency @google-cloud/projectify to v4 ([#2264](https://github.com/googleapis/nodejs-storage/issues/2264)) ([c881bae](https://github.com/googleapis/nodejs-storage/commit/c881bae96b40f609d2b7a8d7388c6a76d34faab1)) +* **deps:** Update dependency @google-cloud/promisify to v4 ([#2262](https://github.com/googleapis/nodejs-storage/issues/2262)) ([9d46ff3](https://github.com/googleapis/nodejs-storage/commit/9d46ff3c02315c5a3516aa5f2755ee0471ba036b)) +* **deps:** Update dependency @google-cloud/pubsub to v4 ([#2256](https://github.com/googleapis/nodejs-storage/issues/2256)) ([18282bb](https://github.com/googleapis/nodejs-storage/commit/18282bbefe1201e51867c676a86301f8086aaf1e)) + + +### Miscellaneous Chores + +* Release 7.1.0 ([#2274](https://github.com/googleapis/nodejs-storage/issues/2274)) ([e0f45c2](https://github.com/googleapis/nodejs-storage/commit/e0f45c24b44d11c72ff40cc534be11cb2a65192f)) + +## [7.0.1](https://github.com/googleapis/nodejs-storage/compare/v7.0.0...v7.0.1) (2023-08-07) + + +### Bug Fixes + +* Export new types from index.ts ([#2258](https://github.com/googleapis/nodejs-storage/issues/2258)) ([93d2a0f](https://github.com/googleapis/nodejs-storage/commit/93d2a0f9f6d6a3de652aaeb3dd914bbc0bb593e0)) + +## [7.0.0](https://github.com/googleapis/nodejs-storage/compare/v6.12.0...v7.0.0) (2023-08-03) + + +### ⚠ BREAKING CHANGES + +* Make node 14 the minimum supported version ([#2244](https://github.com/googleapis/nodejs-storage/issues/2244)) +* Add stronger typings to metadata ([#2234](https://github.com/googleapis/nodejs-storage/issues/2234)) +* Remove extend and Treat Provided Options as Mutable ([#2204](https://github.com/googleapis/nodejs-storage/issues/2204)) +* Stronger typing for lifecycle rules ([#2215](https://github.com/googleapis/nodejs-storage/issues/2215)) +* Do not return responsebody in delete, only raw response ([#2236](https://github.com/googleapis/nodejs-storage/issues/2236)) +* Remove extraneous validation in favor of server errors ([#2237](https://github.com/googleapis/nodejs-storage/issues/2237)) +* Mark bucket.setLabels and associated interfaces as deprecated ([#2214](https://github.com/googleapis/nodejs-storage/issues/2214)) +* Disable source maps for smaller bundle size ([#2240](https://github.com/googleapis/nodejs-storage/issues/2240)) + + + +### Features + +* Make node 14 the minimum supported version ([#2244](https://github.com/googleapis/nodejs-storage/issues/2244)) ([f48dcd2](https://github.com/googleapis/nodejs-storage/commit/f48dcd2d00081aea8990f35b68a91248f3862abe)) + +## [6.12.0](https://github.com/googleapis/nodejs-storage/compare/v6.11.0...v6.12.0) (2023-07-13) + + +### Features + +* Add header for deno runtime for metrics tracking ([#2220](https://github.com/googleapis/nodejs-storage/issues/2220)) ([5083920](https://github.com/googleapis/nodejs-storage/commit/50839209063e75996b2a57bd7664760e0e5331ca)) +* MPU for transfer manager ([#2192](https://github.com/googleapis/nodejs-storage/issues/2192)) ([ae83421](https://github.com/googleapis/nodejs-storage/commit/ae83421e617a5761c75a7c8a15eaa1ea7c7fb1de)) + +## [6.11.0](https://github.com/googleapis/nodejs-storage/compare/v6.10.1...v6.11.0) (2023-06-02) + + +### Features + +* Add support for matchGlob list option ([#2206](https://github.com/googleapis/nodejs-storage/issues/2206)) ([79dd839](https://github.com/googleapis/nodejs-storage/commit/79dd8394fbbc0c97aa3acb86ad2248fd58b243b4)) + +## [6.10.1](https://github.com/googleapis/nodejs-storage/compare/v6.10.0...v6.10.1) (2023-05-10) + + +### Performance Improvements + +* Improve Multiple Chunk Upload Performance ([#2185](https://github.com/googleapis/nodejs-storage/issues/2185)) ([3b2b877](https://github.com/googleapis/nodejs-storage/commit/3b2b87707072e5dc9221a5ba3c727c70db13a593)) + +## [6.10.0](https://github.com/googleapis/nodejs-storage/compare/v6.9.5...v6.10.0) (2023-05-02) + + +### Features + +* Retry Socket Connection Timeouts on Node 20+ ([#2187](https://github.com/googleapis/nodejs-storage/issues/2187)) ([733b560](https://github.com/googleapis/nodejs-storage/commit/733b560c2f634884dd31c916c208ee6395d4fbe1)) + +## [6.9.5](https://github.com/googleapis/nodejs-storage/compare/v6.9.4...v6.9.5) (2023-03-30) + + +### Bug Fixes + +* Check that err.message is a string before attempting indexOf ([#2173](https://github.com/googleapis/nodejs-storage/issues/2173)) ([130818d](https://github.com/googleapis/nodejs-storage/commit/130818d291a0004e5d36e5ee72a8c0687b9db181)) +* V4 Signing Errors with exactly 7 day expiry ([#2170](https://github.com/googleapis/nodejs-storage/issues/2170)) ([f930998](https://github.com/googleapis/nodejs-storage/commit/f9309985d130a574dd23ecf7b6fb5b58b01d42a0)) + +## [6.9.4](https://github.com/googleapis/nodejs-storage/compare/v6.9.3...v6.9.4) (2023-03-02) + + +### Bug Fixes + +* Refactor createReadStream to remove unnecessary stream ([#2153](https://github.com/googleapis/nodejs-storage/issues/2153)) ([2c97310](https://github.com/googleapis/nodejs-storage/commit/2c97310da9edd1afbf61711631979433f10249a5)) + +## [6.9.3](https://github.com/googleapis/nodejs-storage/compare/v6.9.2...v6.9.3) (2023-02-15) + + +### Bug Fixes + +* Reduce memory footprint of deleteFiles by utilizing getFilesStream and using smaller queue of promises ([#2147](https://github.com/googleapis/nodejs-storage/issues/2147)) ([f792f25](https://github.com/googleapis/nodejs-storage/commit/f792f25e3fd38003056f649eaa638a782290cbac)) + +## [6.9.2](https://github.com/googleapis/nodejs-storage/compare/v6.9.1...v6.9.2) (2023-02-06) + + +### Bug Fixes + +* Correctly handle if a user has no permissions when calling iam.testPermissions ([#2140](https://github.com/googleapis/nodejs-storage/issues/2140)) ([cce902d](https://github.com/googleapis/nodejs-storage/commit/cce902d27cf3c4a23730550b72d10dc76425c974)) + +## [6.9.1](https://github.com/googleapis/nodejs-storage/compare/v6.9.0...v6.9.1) (2023-01-24) + + +### Bug Fixes + +* Setting file metadata is conditionally idempotent on ifmetagenerationmatch not ifgenerationmatch ([#2131](https://github.com/googleapis/nodejs-storage/issues/2131)) ([f20c28c](https://github.com/googleapis/nodejs-storage/commit/f20c28c5875c9a7095b028912550512459fbf844)) + +## [6.9.0](https://github.com/googleapis/nodejs-storage/compare/v6.8.0...v6.9.0) (2023-01-04) + + +### Features + +* Add ability to upload entire directory, add samples for upload … ([#2118](https://github.com/googleapis/nodejs-storage/issues/2118)) ([b0f32ce](https://github.com/googleapis/nodejs-storage/commit/b0f32ced04eae1b8ad88a0939fa763cb16b08df9)) + +## [6.8.0](https://github.com/googleapis/nodejs-storage/compare/v6.7.0...v6.8.0) (2022-12-07) + + +### Features + +* Implement parallel operations ([#2067](https://github.com/googleapis/nodejs-storage/issues/2067)) ([#2109](https://github.com/googleapis/nodejs-storage/issues/2109)) ([ce15b5e](https://github.com/googleapis/nodejs-storage/commit/ce15b5ef68353efbc005cb3a1a780e064ea04deb)) + +## [6.7.0](https://github.com/googleapis/nodejs-storage/compare/v6.6.0...v6.7.0) (2022-11-03) + + +### Features + +* Support autoclass ([#2078](https://github.com/googleapis/nodejs-storage/issues/2078)) ([7e83580](https://github.com/googleapis/nodejs-storage/commit/7e8358008467dd2d77702734e05f54bc06c9ca5b)) + +## [6.6.0](https://github.com/googleapis/nodejs-storage/compare/v6.5.4...v6.6.0) (2022-10-25) + + +### Features + +* **crc32c:** Convenient Method For Reading Files ([#2095](https://github.com/googleapis/nodejs-storage/issues/2095)) ([2145c81](https://github.com/googleapis/nodejs-storage/commit/2145c8177f3659fb5f193045866fbcd1220aaeaf)) + + +### Bug Fixes + +* Remove async from final function which causes double invocation … ([#2094](https://github.com/googleapis/nodejs-storage/issues/2094)) ([1a3df98](https://github.com/googleapis/nodejs-storage/commit/1a3df985e9096229bc2909921b4974680e12be2a)) + +## [6.5.4](https://github.com/googleapis/nodejs-storage/compare/v6.5.3...v6.5.4) (2022-10-20) + + +### Bug Fixes + +* Revert STORAGE_EMULATOR_HOST handling ([#2089](https://github.com/googleapis/nodejs-storage/issues/2089)) ([48dce65](https://github.com/googleapis/nodejs-storage/commit/48dce654064470f7496d160d87b696ab5cfd65d4)) + +## [6.5.3](https://github.com/googleapis/nodejs-storage/compare/v6.5.2...v6.5.3) (2022-10-18) + + +### Bug Fixes + +* Correct STORAGE_EMULATOR_HOST handling ([#2069](https://github.com/googleapis/nodejs-storage/issues/2069), [#1314](https://github.com/googleapis/nodejs-storage/issues/1314)) ([#2070](https://github.com/googleapis/nodejs-storage/issues/2070)) ([c75b8b8](https://github.com/googleapis/nodejs-storage/commit/c75b8b82262dddb794304a71f648bd6e03cafb30)) + +## [6.5.2](https://github.com/googleapis/nodejs-storage/compare/v6.5.1...v6.5.2) (2022-09-23) + + +### Bug Fixes + +* Determine `Content-Length` Before Attempting Multi-chunk Upload ([#2074](https://github.com/googleapis/nodejs-storage/issues/2074)) ([666402a](https://github.com/googleapis/nodejs-storage/commit/666402a6a65c2ee8e91bc4fe072e91c0b893864e)) + +## [6.5.1](https://github.com/googleapis/nodejs-storage/compare/v6.5.0...v6.5.1) (2022-09-20) + + +### Bug Fixes + +* Revert skip validation ([#2023](https://github.com/googleapis/nodejs-storage/issues/2023)) ([70ab224](https://github.com/googleapis/nodejs-storage/commit/70ab22459b51b9781e40b0cc86663c1658e43520)) + +## [6.5.0](https://github.com/googleapis/nodejs-storage/compare/v6.4.2...v6.5.0) (2022-09-15) + + +### Features + +* Add multiple lifecycle rules ([#2062](https://github.com/googleapis/nodejs-storage/issues/2062)) ([fbe2deb](https://github.com/googleapis/nodejs-storage/commit/fbe2deb72bd98db54a03cf228a360a871ba1915b)) + +## [6.4.2](https://github.com/googleapis/nodejs-storage/compare/v6.4.1...v6.4.2) (2022-09-01) + + +### Bug Fixes + +* remove pip install statements ([#1546](https://github.com/googleapis/nodejs-storage/issues/1546)) ([#2049](https://github.com/googleapis/nodejs-storage/issues/2049)) ([c90ba0f](https://github.com/googleapis/nodejs-storage/commit/c90ba0feecca9d39de3c52f12cc9423b7a2d4d47)) +* truncated `createReadStream` through early `end` event ([#2056](https://github.com/googleapis/nodejs-storage/issues/2056)) ([a4716a4](https://github.com/googleapis/nodejs-storage/commit/a4716a4ed1053560f2692647c8a90131763c1e72)) + +## [6.4.1](https://github.com/googleapis/nodejs-storage/compare/v6.4.0...v6.4.1) (2022-08-12) + + +### Bug Fixes + +* Remove `pumpify` ([#2029](https://github.com/googleapis/nodejs-storage/issues/2029)) ([edc1d64](https://github.com/googleapis/nodejs-storage/commit/edc1d64069a6038c301c3b775f116fbf69b10b28)) +* Retry `EPIPE` Connection Errors + Attempt Retries in Resumable Upload Connection Errors ([#2040](https://github.com/googleapis/nodejs-storage/issues/2040)) ([ba35321](https://github.com/googleapis/nodejs-storage/commit/ba35321c3fef9a1874ff8fbea43885e2e7746b4f)) + +## [6.4.0](https://github.com/googleapis/nodejs-storage/compare/v6.3.0...v6.4.0) (2022-08-10) + + +### Features + +* add functionality for passing preconditions at the function level ([#1993](https://github.com/googleapis/nodejs-storage/issues/1993)) ([21f173e](https://github.com/googleapis/nodejs-storage/commit/21f173eb17d4216e2b42ffdd1ed0104aeda7cf13)) + +## [6.3.0](https://github.com/googleapis/nodejs-storage/compare/v6.2.3...v6.3.0) (2022-08-01) + + +### Features + +* custom dual regions refactor implementation ([#2012](https://github.com/googleapis/nodejs-storage/issues/2012)) ([9a614fb](https://github.com/googleapis/nodejs-storage/commit/9a614fb2b624f8234fa9d40f352dae177b2b0374)) + +## [6.2.3](https://github.com/googleapis/nodejs-storage/compare/v6.2.2...v6.2.3) (2022-07-13) + + +### Bug Fixes + +* force setMetadata calls to use promise version, invoke callbacks manually ([#2000](https://github.com/googleapis/nodejs-storage/issues/2000)) ([f488647](https://github.com/googleapis/nodejs-storage/commit/f488647d5ac8ccfdb479d7ea24a377d10573b8c4)) + +## [6.2.2](https://github.com/googleapis/nodejs-storage/compare/v6.2.1...v6.2.2) (2022-06-29) + + +### Bug Fixes + +* correctly handle an empty file in download function ([#1995](https://github.com/googleapis/nodejs-storage/issues/1995)) ([f1a5a0b](https://github.com/googleapis/nodejs-storage/commit/f1a5a0bd121b84c3d56a9eddbd31593089634574)) + +## [6.2.1](https://github.com/googleapis/nodejs-storage/compare/v6.2.0...v6.2.1) (2022-06-27) + + +### Bug Fixes + +* explicitly import URL so that .d.ts file is correctly generated ([#1992](https://github.com/googleapis/nodejs-storage/issues/1992)) ([a968f50](https://github.com/googleapis/nodejs-storage/commit/a968f508e7c98e160b658ffc3ab568997548172f)) + +## [6.2.0](https://github.com/googleapis/nodejs-storage/compare/v6.1.0...v6.2.0) (2022-06-22) + + +### Features + +* Convenient `gs://` URI retrieval ([#1987](https://github.com/googleapis/nodejs-storage/issues/1987)) ([58fad6d](https://github.com/googleapis/nodejs-storage/commit/58fad6d9a3bd92966306e98fd7dedd3992995cb7)) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/projectify to v3 ([#1986](https://github.com/googleapis/nodejs-storage/issues/1986)) ([71a61ec](https://github.com/googleapis/nodejs-storage/commit/71a61ec4ef2436bc091f390af14a02b6920b2b87)) +* **deps:** update dependency @google-cloud/pubsub to v3 ([#1972](https://github.com/googleapis/nodejs-storage/issues/1972)) ([004b97e](https://github.com/googleapis/nodejs-storage/commit/004b97ec0ae866997c84ee2327db87e59f510f00)) +* Requests Respect `config.projectIdRequired` === `false` ([#1988](https://github.com/googleapis/nodejs-storage/issues/1988)) ([8813369](https://github.com/googleapis/nodejs-storage/commit/881336944be37e15c45b12973064245adc519860)) + +## [6.1.0](https://github.com/googleapis/nodejs-storage/compare/v6.0.1...v6.1.0) (2022-06-08) + + +### Features + +* support OLM Prefix/Suffix ([#1847](https://github.com/googleapis/nodejs-storage/issues/1847)) ([c22984c](https://github.com/googleapis/nodejs-storage/commit/c22984caa8e8ae09a61d308876b2b3d97503777b)) + +### [6.0.1](https://github.com/googleapis/nodejs-storage/compare/v6.0.0...v6.0.1) (2022-05-25) + + +### Bug Fixes + +* capture and throw on non-existent files ([#1969](https://github.com/googleapis/nodejs-storage/issues/1969)) ([52d81c0](https://github.com/googleapis/nodejs-storage/commit/52d81c026f30aef0902ea7173dfa6da2e7f97d50)) + +## [6.0.0](https://github.com/googleapis/nodejs-storage/compare/v5.20.5...v6.0.0) (2022-05-24) + + +### ⚠ BREAKING CHANGES + +* update TypeScript +* remove deprecated fields +* remove configstore +* align resumable upload behavior +* utilize internalized CRC32C utilities +* drop node 10 support + +### Build System + +* drop node 10 support ([77fa8d9](https://github.com/googleapis/nodejs-storage/commit/77fa8d9f95afbc830b57188ce0d2dfac46476d0b)) + + +### Code Refactoring + +* align resumable upload behavior ([77fa8d9](https://github.com/googleapis/nodejs-storage/commit/77fa8d9f95afbc830b57188ce0d2dfac46476d0b)) +* remove configstore ([77fa8d9](https://github.com/googleapis/nodejs-storage/commit/77fa8d9f95afbc830b57188ce0d2dfac46476d0b)) +* remove deprecated fields ([77fa8d9](https://github.com/googleapis/nodejs-storage/commit/77fa8d9f95afbc830b57188ce0d2dfac46476d0b)) +* utilize internalized CRC32C utilities ([77fa8d9](https://github.com/googleapis/nodejs-storage/commit/77fa8d9f95afbc830b57188ce0d2dfac46476d0b)) + + +### deps + +* update TypeScript ([77fa8d9](https://github.com/googleapis/nodejs-storage/commit/77fa8d9f95afbc830b57188ce0d2dfac46476d0b)) + +### [5.20.5](https://github.com/googleapis/nodejs-storage/compare/v5.20.4...v5.20.5) (2022-05-19) + + +### Bug Fixes + +* **chore:** move uuid package to dependencies ([#1952](https://github.com/googleapis/nodejs-storage/issues/1952)) ([0ff5aa3](https://github.com/googleapis/nodejs-storage/commit/0ff5aa3e9ff8b4dcc536b9494e44b9a2fb217727)) + +### [5.20.4](https://github.com/googleapis/nodejs-storage/compare/v5.20.3...v5.20.4) (2022-05-18) + + +### Bug Fixes + +* revert native typescript mocha tests ([#1947](https://github.com/googleapis/nodejs-storage/issues/1947)) ([1d0ea7d](https://github.com/googleapis/nodejs-storage/commit/1d0ea7d2281a049bc99c6bd810dd24ffc83c6a09)) +* support empty object uploads for resumable upload ([#1949](https://github.com/googleapis/nodejs-storage/issues/1949)) ([da6016e](https://github.com/googleapis/nodejs-storage/commit/da6016e20b681d6a75ed1a5459cfd333b58c70a9)) + +### [5.20.3](https://github.com/googleapis/nodejs-storage/compare/v5.20.2...v5.20.3) (2022-05-17) + + +### Bug Fixes + +* move retrieval of package.json to utility function ([#1941](https://github.com/googleapis/nodejs-storage/issues/1941)) ([ac5cbdf](https://github.com/googleapis/nodejs-storage/commit/ac5cbdf0d3c363e7dab43e9002b01a0dae877642)) + +### [5.20.2](https://github.com/googleapis/nodejs-storage/compare/v5.20.1...v5.20.2) (2022-05-17) + + +### Bug Fixes + +* use path.join and __dirname for require package.json ([#1936](https://github.com/googleapis/nodejs-storage/issues/1936)) ([b868762](https://github.com/googleapis/nodejs-storage/commit/b86876201ec7d4ce58ae5c1d9635dad82a1fdc4b)) + +### [5.20.1](https://github.com/googleapis/nodejs-storage/compare/v5.20.0...v5.20.1) (2022-05-16) + + +### Bug Fixes + +* do not use import on package.json ([#1932](https://github.com/googleapis/nodejs-storage/issues/1932)) ([d0f0494](https://github.com/googleapis/nodejs-storage/commit/d0f04941f1cabf7c153f7e5abb91c358f12ef83e)) + +## [5.20.0](https://github.com/googleapis/nodejs-storage/compare/v5.19.4...v5.20.0) (2022-05-16) + + +### Features + +* add x-goog-api-client headers for retry metrics ([#1920](https://github.com/googleapis/nodejs-storage/issues/1920)) ([0c7e4f6](https://github.com/googleapis/nodejs-storage/commit/0c7e4f6ade4cee1715e14b3cd9abf2aa2a56c0b9)) + +### [5.19.4](https://github.com/googleapis/nodejs-storage/compare/v5.19.3...v5.19.4) (2022-04-28) + + +### Bug Fixes + +* don't modify passed in options ([#1895](https://github.com/googleapis/nodejs-storage/issues/1895)) ([cd80ca3](https://github.com/googleapis/nodejs-storage/commit/cd80ca318a2b10379b8b166a59f3943b97576475)) + +### [5.19.3](https://github.com/googleapis/nodejs-storage/compare/v5.19.2...v5.19.3) (2022-04-20) + + +### Bug Fixes + +* export idempotencystrategy and preconditionoptions from index ([#1880](https://github.com/googleapis/nodejs-storage/issues/1880)) ([8aafe04](https://github.com/googleapis/nodejs-storage/commit/8aafe0453a8e2dc41f848dd5165d3e86d6a160ed)) + +### [5.19.2](https://github.com/googleapis/nodejs-storage/compare/v5.19.1...v5.19.2) (2022-04-14) + + +### Bug Fixes + +* deleting, getting, and getting metadata for notifications ([#1872](https://github.com/googleapis/nodejs-storage/issues/1872)) ([451570e](https://github.com/googleapis/nodejs-storage/commit/451570e6038a1b91b5723db9b941cd916fd76348)) + +### [5.19.1](https://github.com/googleapis/nodejs-storage/compare/v5.19.0...v5.19.1) (2022-04-08) + + +### Bug Fixes + +* prevent retrying 200 response ([#1857](https://github.com/googleapis/nodejs-storage/issues/1857)) ([638a47b](https://github.com/googleapis/nodejs-storage/commit/638a47b4e7ecc6e94b3b11d1ccc7c52afdeaafe1)) + +## [5.19.0](https://github.com/googleapis/nodejs-storage/compare/v5.18.3...v5.19.0) (2022-04-06) + + +### Features + +* Dual Region Support ([#1814](https://github.com/googleapis/nodejs-storage/issues/1814)) ([caf7ee5](https://github.com/googleapis/nodejs-storage/commit/caf7ee561fd640b0daea92c7837c47e66070c30c)) + +### [5.18.3](https://github.com/googleapis/nodejs-storage/compare/v5.18.2...v5.18.3) (2022-03-28) + + +### Bug Fixes + +* encode name portion when calling publicUrl function ([#1828](https://github.com/googleapis/nodejs-storage/issues/1828)) ([5522b35](https://github.com/googleapis/nodejs-storage/commit/5522b35e83857421a00e71c4e93ba6ae0ffccb90)) +* fixed typo ([#1803](https://github.com/googleapis/nodejs-storage/issues/1803)) ([be70dae](https://github.com/googleapis/nodejs-storage/commit/be70dae33751ddc3e0ae5a55b5cdbf2002a42932)) + +### [5.18.2](https://github.com/googleapis/nodejs-storage/compare/v5.18.1...v5.18.2) (2022-02-16) + + +### Bug Fixes + +* resumable uploads should respect autoRetry & multipart uploads should correctly use preconditions ([#1779](https://github.com/googleapis/nodejs-storage/issues/1779)) ([1e72586](https://github.com/googleapis/nodejs-storage/commit/1e725867dce8f78070435b96b65f97f2253c0e80)) + +### [5.18.1](https://github.com/googleapis/nodejs-storage/compare/v5.18.0...v5.18.1) (2022-01-26) + + +### Bug Fixes + +* **gcs-resumable-upload:** Stop Duplicate Response Handlers on Retries ([#1764](https://github.com/googleapis/nodejs-storage/issues/1764)) ([fe44871](https://github.com/googleapis/nodejs-storage/commit/fe4487187aa405e7d7f8e0bec485bbddb76ea050)) + +## [5.18.0](https://github.com/googleapis/nodejs-storage/compare/v5.17.0...v5.18.0) (2022-01-18) + + +### Features + +* Expose `chunkSize` param for `CreateResumableUploadOptions` ([#1754](https://github.com/googleapis/nodejs-storage/issues/1754)) ([3acfd5b](https://github.com/googleapis/nodejs-storage/commit/3acfd5b2412d046c471d8d707023e034dc1a167a)) + +## [5.17.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.16.1...v5.17.0) (2022-01-10) + + +### Features + +* add support for rpo (turbo replication) metadata field when cre… ([#1648](https://www.github.com/googleapis/nodejs-storage/issues/1648)) ([291e6ef](https://www.github.com/googleapis/nodejs-storage/commit/291e6ef48efcfca55b4a7dca8868a57c0eeec89b)) + + +### Bug Fixes + +* remove compodoc dev dependency ([#1745](https://www.github.com/googleapis/nodejs-storage/issues/1745)) ([809bf11](https://www.github.com/googleapis/nodejs-storage/commit/809bf11b8a2a2203db82aec38b6a6023a805bd62)) + +### [5.16.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.16.0...v5.16.1) (2021-11-29) + + +### Bug Fixes + +* change properties with function value to methods ([#1715](https://www.github.com/googleapis/nodejs-storage/issues/1715)) ([c365254](https://www.github.com/googleapis/nodejs-storage/commit/c36525402da8e748971473b1cdd2423e8fd953e1)) +* revert skip validation ([#1718](https://www.github.com/googleapis/nodejs-storage/issues/1718)) ([0c75e33](https://www.github.com/googleapis/nodejs-storage/commit/0c75e33eb0291aa7dfc704c86733f4c0dc78d322)) +* stop File.download from truncating output file on failure ([#1720](https://www.github.com/googleapis/nodejs-storage/issues/1720)) ([d77979b](https://www.github.com/googleapis/nodejs-storage/commit/d77979b1003dbb89cd9d4725330de50b1f8d9262)) + +## [5.16.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.15.5...v5.16.0) (2021-11-09) + + +### Features + +* improved error messages for resumable uploads ([#1708](https://www.github.com/googleapis/nodejs-storage/issues/1708)) ([50cdbb6](https://www.github.com/googleapis/nodejs-storage/commit/50cdbb6f730ee7f96cb598c4cda412fc4bcc8807)) + + +### Bug Fixes + +* add scenario 3 conformance tests ([#1702](https://www.github.com/googleapis/nodejs-storage/issues/1702)) ([e16a3a5](https://www.github.com/googleapis/nodejs-storage/commit/e16a3a5eb09a388743259d54c31e62d7fc220bf0)) +* retry uri creation dep update & conformance tests ([#1700](https://www.github.com/googleapis/nodejs-storage/issues/1700)) ([d265f8c](https://www.github.com/googleapis/nodejs-storage/commit/d265f8c5e4e6a8c8239e959dfb4d0acbf4cdfe0a)) + +### [5.15.6](https://www.github.com/googleapis/nodejs-storage/compare/v5.15.5...v5.15.6) (2021-11-05) + + +### Bug Fixes + +* add scenario 3 conformance tests ([#1702](https://www.github.com/googleapis/nodejs-storage/issues/1702)) ([e16a3a5](https://www.github.com/googleapis/nodejs-storage/commit/e16a3a5eb09a388743259d54c31e62d7fc220bf0)) +* retry uri creation dep update & conformance tests ([#1700](https://www.github.com/googleapis/nodejs-storage/issues/1700)) ([d265f8c](https://www.github.com/googleapis/nodejs-storage/commit/d265f8c5e4e6a8c8239e959dfb4d0acbf4cdfe0a)) + +### [5.15.5](https://www.github.com/googleapis/nodejs-storage/compare/v5.15.4...v5.15.5) (2021-11-03) + + +### Bug Fixes + +* **deps:** update dependency mime to v3 ([#1696](https://www.github.com/googleapis/nodejs-storage/issues/1696)) ([f337208](https://www.github.com/googleapis/nodejs-storage/commit/f33720883bb6d797d2fb89d5e6ff9584d216be74)) +* explicitly define function type of getFilesStream ([#1697](https://www.github.com/googleapis/nodejs-storage/issues/1697)) ([c950c23](https://www.github.com/googleapis/nodejs-storage/commit/c950c23742bb9291a3e15b95ae0ee4a13466c361)) + +### [5.15.4](https://www.github.com/googleapis/nodejs-storage/compare/v5.15.3...v5.15.4) (2021-11-01) + + +### Bug Fixes + +* check e is not null ([#1692](https://www.github.com/googleapis/nodejs-storage/issues/1692)) ([56ff485](https://www.github.com/googleapis/nodejs-storage/commit/56ff485cbe28ba048c9a689711b034c416853b1f)) + +### [5.15.3](https://www.github.com/googleapis/nodejs-storage/compare/v5.15.2...v5.15.3) (2021-10-14) + + +### Bug Fixes + +* do not use src precondition options in copy. ([#1666](https://www.github.com/googleapis/nodejs-storage/issues/1666)) ([678ae77](https://www.github.com/googleapis/nodejs-storage/commit/678ae77dfb2c1eb2272734f34315b4d0ec726076)) + +### [5.15.2](https://www.github.com/googleapis/nodejs-storage/compare/v5.15.1...v5.15.2) (2021-10-13) + + +### Bug Fixes + +* remove bucket preconditions from deleteFiles, it is a file operation not bucket ([#1661](https://www.github.com/googleapis/nodejs-storage/issues/1661)) ([6b7a06d](https://www.github.com/googleapis/nodejs-storage/commit/6b7a06defe1a3cadc6fad9258ff3fb01a2ecce0a)) + +### [5.15.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.15.0...v5.15.1) (2021-10-12) + + +### Bug Fixes + +* check generation on source files not metageneration on bucket ([#1654](https://www.github.com/googleapis/nodejs-storage/issues/1654)) ([760231c](https://www.github.com/googleapis/nodejs-storage/commit/760231ca520f4eedf878c245489cb07f95e153af)) + +## [5.15.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.7...v5.15.0) (2021-10-07) + + +### Features + +* add support for useAuthWithCustomEndpoint option ([#1645](https://www.github.com/googleapis/nodejs-storage/issues/1645)) ([d11d6b4](https://www.github.com/googleapis/nodejs-storage/commit/d11d6b4b2678cb240928e2dfe20f983d2ae896f6)) + + +### Bug Fixes + +* update common dep ([#1644](https://www.github.com/googleapis/nodejs-storage/issues/1644)) ([793467f](https://www.github.com/googleapis/nodejs-storage/commit/793467f25abf46eb7ba5e6cd1b80f735faa035dc)) + +### [5.14.8](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.7...v5.14.8) (2021-10-06) + + +### Bug Fixes + +* update common dep ([#1644](https://www.github.com/googleapis/nodejs-storage/issues/1644)) ([793467f](https://www.github.com/googleapis/nodejs-storage/commit/793467f25abf46eb7ba5e6cd1b80f735faa035dc)) + +### [5.14.7](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.6...v5.14.7) (2021-10-06) + + +### Bug Fixes + +* file preconditions should respect ifGenerationMatch not ifMetagenerationMatch ([#1642](https://www.github.com/googleapis/nodejs-storage/issues/1642)) ([eb6f31f](https://www.github.com/googleapis/nodejs-storage/commit/eb6f31f3f6c439e21bbc0cd46f32a7327e15f65e)) + +### [5.14.6](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.5...v5.14.6) (2021-10-06) + + +### Bug Fixes + +* pass precondition opts to new file ([#1638](https://www.github.com/googleapis/nodejs-storage/issues/1638)) ([1523ca9](https://www.github.com/googleapis/nodejs-storage/commit/1523ca962fda070cf60e5b81d062e3a291461c83)) + +### [5.14.5](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.4...v5.14.5) (2021-10-01) + + +### Bug Fixes + +* fix logic for buckets that do not have a generation ([#1634](https://www.github.com/googleapis/nodejs-storage/issues/1634)) ([9069bdc](https://www.github.com/googleapis/nodejs-storage/commit/9069bdc9a0ab495ab62033f432ea0e180e3b182e)) +* updated connection reset string ([#1632](https://www.github.com/googleapis/nodejs-storage/issues/1632)) ([b841d5b](https://www.github.com/googleapis/nodejs-storage/commit/b841d5b98c3d98b5f1dc7776a887159294eb0b36)) + +### [5.14.4](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.3...v5.14.4) (2021-09-27) + + +### Bug Fixes + +* respect precondition settings from constructors ([#1617](https://www.github.com/googleapis/nodejs-storage/issues/1617)) ([6a48942](https://www.github.com/googleapis/nodejs-storage/commit/6a48942e540e3d96e2a5b396b8e74cbe732178be)) + +### [5.14.3](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.2...v5.14.3) (2021-09-22) + + +### Bug Fixes + +* set autoretry back to instance value at end of file functions ([#1604](https://www.github.com/googleapis/nodejs-storage/issues/1604)) ([db3b59d](https://www.github.com/googleapis/nodejs-storage/commit/db3b59d731c9760d55bf112c211bdd644da911c4)) + +### [5.14.2](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.1...v5.14.2) (2021-09-13) + + +### Bug Fixes + +* **build:** set default branch to main ([#1587](https://www.github.com/googleapis/nodejs-storage/issues/1587)) ([b39ce95](https://www.github.com/googleapis/nodejs-storage/commit/b39ce95a2ec9d8dd2114863898181ea10670d962)) + +### [5.14.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.14.0...v5.14.1) (2021-09-08) + + +### Bug Fixes + +* **types:** remove duplicated definition of BucketOptions and make sure proper version is exported ([#1583](https://www.github.com/googleapis/nodejs-storage/issues/1583)) ([d8f4bc5](https://www.github.com/googleapis/nodejs-storage/commit/d8f4bc59bd3e2cebfe6494842414cd9f7e32018f)) + +## [5.14.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.13.2...v5.14.0) (2021-08-26) + + +### Features + +* retries for conditionally idempotent operations ([#1561](https://www.github.com/googleapis/nodejs-storage/issues/1561)) ([653f4b4](https://www.github.com/googleapis/nodejs-storage/commit/653f4b488e8603e4008e51b45920fb7de7138eab)) + + +### Bug Fixes + +* allow retries of metadatata operations in system tests ([#1568](https://www.github.com/googleapis/nodejs-storage/issues/1568)) ([9398566](https://www.github.com/googleapis/nodejs-storage/commit/939856680d279dcd9587328d0cc58f789b022f5a)) + +### [5.13.2](https://www.github.com/googleapis/nodejs-storage/compare/v5.13.1...v5.13.2) (2021-08-26) + + +### Bug Fixes + +* update getLabels definition to actually allow no arguments when used in typescript ([#1559](https://www.github.com/googleapis/nodejs-storage/issues/1559)) ([176dbb5](https://www.github.com/googleapis/nodejs-storage/commit/176dbb5223f4442d10fd098ffa2cda5cf12144f2)) + +### [5.13.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.13.0...v5.13.1) (2021-08-18) + + +### Bug Fixes + +* **deps:** update dependency date-and-time to v2 ([#1537](https://www.github.com/googleapis/nodejs-storage/issues/1537)) ([9d0d69e](https://www.github.com/googleapis/nodejs-storage/commit/9d0d69eaf908817dec274abe915bd96bb22c663a)) + +## [5.13.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.12.0...v5.13.0) (2021-08-09) + + +### Features + +* Precondition checks ([#1523](https://www.github.com/googleapis/nodejs-storage/issues/1523)) ([7c24417](https://www.github.com/googleapis/nodejs-storage/commit/7c244178649f120cfefe58994b515da7ca6b7ffb)) + +## [5.12.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.11.1...v5.12.0) (2021-08-03) + + +### Features + +* pass precondition parameters to gcs-resumable-upload ([#1516](https://www.github.com/googleapis/nodejs-storage/issues/1516)) ([65211dd](https://www.github.com/googleapis/nodejs-storage/commit/65211ddb8ae19229154b4aca3d5ff97f2aaa9f56)) + +### [5.11.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.11.0...v5.11.1) (2021-08-02) + + +### Bug Fixes + +* don't retry non-idempotent functions ([#1517](https://www.github.com/googleapis/nodejs-storage/issues/1517)) ([c938795](https://www.github.com/googleapis/nodejs-storage/commit/c938795e8a5f14ba7724f2d0e334310dd8e8f207)) + +## [5.11.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.10.0...v5.11.0) (2021-07-23) + + +### Features + +* retries for resumable bucket.upload and file.save ([#1511](https://www.github.com/googleapis/nodejs-storage/issues/1511)) ([9bf163c](https://www.github.com/googleapis/nodejs-storage/commit/9bf163c3e3569bad1440940ff1a6bfd42404bb32)) + +## [5.10.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.9.0...v5.10.0) (2021-07-22) + + +### Features + +* retry multipart Bucket.upload ([#1509](https://www.github.com/googleapis/nodejs-storage/issues/1509)) ([730d0a0](https://www.github.com/googleapis/nodejs-storage/commit/730d0a0d4a6aa5192d998c54292d3423d3ddeaaa)) + +## [5.9.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.8.5...v5.9.0) (2021-07-21) + + +### Features + +* customize retry behavior implementation ([#1474](https://www.github.com/googleapis/nodejs-storage/issues/1474)) ([#1493](https://www.github.com/googleapis/nodejs-storage/issues/1493)) ([49008e3](https://www.github.com/googleapis/nodejs-storage/commit/49008e313b89ce6035543bf2cf1e60e253404520)) + +### [5.8.5](https://www.github.com/googleapis/nodejs-storage/compare/v5.8.4...v5.8.5) (2021-05-04) + + +### Bug Fixes + +* **deps:** updated gcs-resumable-upload dependency ([#1459](https://www.github.com/googleapis/nodejs-storage/issues/1459)) ([afaccc7](https://www.github.com/googleapis/nodejs-storage/commit/afaccc70375a2c778e4306a59bf8a86736c17f6c)) + +### [5.8.4](https://www.github.com/googleapis/nodejs-storage/compare/v5.8.3...v5.8.4) (2021-04-19) + + +### Bug Fixes + +* **deps:** update dependency date-and-time to v1 ([#1434](https://www.github.com/googleapis/nodejs-storage/issues/1434)) ([91ee6ca](https://www.github.com/googleapis/nodejs-storage/commit/91ee6cab38769d36b00d702e17b222518ad4e752)) +* don't fail if ~/.config doesn't exist ([#1428](https://www.github.com/googleapis/nodejs-storage/issues/1428)) ([3cfaba1](https://www.github.com/googleapis/nodejs-storage/commit/3cfaba19d4223c68f4382c06674f135838d32eb8)) + +### [5.8.3](https://www.github.com/googleapis/nodejs-storage/compare/v5.8.2...v5.8.3) (2021-03-29) + + +### Bug Fixes + +* update CopyOptions type to include cacheControl, contentType and contentEncoding ([#1426](https://www.github.com/googleapis/nodejs-storage/issues/1426)) ([efa5bb8](https://www.github.com/googleapis/nodejs-storage/commit/efa5bb8a22ab68c0c3e8549850e5db4d57ff29bb)) + +### [5.8.2](https://www.github.com/googleapis/nodejs-storage/compare/v5.8.1...v5.8.2) (2021-03-23) + + +### Bug Fixes + +* **perf:** pull hashes without refreshing metadata ([#1419](https://www.github.com/googleapis/nodejs-storage/issues/1419)) ([f3ec627](https://www.github.com/googleapis/nodejs-storage/commit/f3ec6278df3c3df4d4cddf5293be4dda95f0cbf7)) + +### [5.8.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.8.0...v5.8.1) (2021-03-02) + + +### Bug Fixes + +* deprecate `options.promise` and sync options with Service ([#1391](https://www.github.com/googleapis/nodejs-storage/issues/1391)) ([59cfe27](https://www.github.com/googleapis/nodejs-storage/commit/59cfe272de16c41e9c768953a25677294f520cc7)) +* **types:** support metadata override in file.copy() ([#1406](https://www.github.com/googleapis/nodejs-storage/issues/1406)) ([dda6d30](https://www.github.com/googleapis/nodejs-storage/commit/dda6d305638a07cbca188e459544393d8624f4f0)) + +## [5.8.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.7.4...v5.8.0) (2021-02-18) + + +### Features + +* adds support workload identity federation ([#1404](https://www.github.com/googleapis/nodejs-storage/issues/1404)) ([7d3a3f1](https://www.github.com/googleapis/nodejs-storage/commit/7d3a3f148361e56cbcd4dc4c8fb178b75f9208bf)) + +### [5.7.4](https://www.github.com/googleapis/nodejs-storage/compare/v5.7.3...v5.7.4) (2021-02-01) + + +### Bug Fixes + +* specified acceptable types for File.save data parameter ([#1388](https://www.github.com/googleapis/nodejs-storage/issues/1388)) ([607f6c1](https://www.github.com/googleapis/nodejs-storage/commit/607f6c1c8b9ae5414513957f54a5de2490c454b1)) + +### [5.7.3](https://www.github.com/googleapis/nodejs-storage/compare/v5.7.2...v5.7.3) (2021-01-22) + + +### Bug Fixes + +* retry multipart uploads on File.save() ([#1385](https://www.github.com/googleapis/nodejs-storage/issues/1385)) ([4dec8c1](https://www.github.com/googleapis/nodejs-storage/commit/4dec8c1a362e3f80cbbf49f8bf7e7eaa2e2ce3bc)) + +### [5.7.2](https://www.github.com/googleapis/nodejs-storage/compare/v5.7.1...v5.7.2) (2021-01-11) + + +### Bug Fixes + +* deprecated directory. prefix should be used instead ([#1370](https://www.github.com/googleapis/nodejs-storage/issues/1370)) ([fae4c06](https://www.github.com/googleapis/nodejs-storage/commit/fae4c0635909a831d65bd3111b27250795d4735b)) + +### [5.7.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.7.0...v5.7.1) (2021-01-07) + + +### Bug Fixes + +* bump dependencies See [#1372](https://www.github.com/googleapis/nodejs-storage/issues/1372) for details ([#1375](https://www.github.com/googleapis/nodejs-storage/issues/1375)) ([7cf0264](https://www.github.com/googleapis/nodejs-storage/commit/7cf0264c0cea2e0d668818924aaa737381c07bfa)) + +## [5.7.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.6.0...v5.7.0) (2020-12-10) + + +### Features + +* support metadata updates from makePrivate() methods ([#1355](https://www.github.com/googleapis/nodejs-storage/issues/1355)) ([3db1e83](https://www.github.com/googleapis/nodejs-storage/commit/3db1e832af1cd3a394305b0a1120953d85f86249)) + + +### Bug Fixes + +* capitalize action in Bucket#addLifecycleRule ([#1358](https://www.github.com/googleapis/nodejs-storage/issues/1358)) ([205f39f](https://www.github.com/googleapis/nodejs-storage/commit/205f39f970639c06258fb1e0cd18a4d963729262)) +* jsdoc for bucket ([#1359](https://www.github.com/googleapis/nodejs-storage/issues/1359)) ([5fa530a](https://www.github.com/googleapis/nodejs-storage/commit/5fa530ab909e837558deecd7e1aa50a7cc4f5830)) + +## [5.6.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.5.1...v5.6.0) (2020-12-02) + + +### Features + +* allow ignoring 404 errors during delete() operations ([#1347](https://www.github.com/googleapis/nodejs-storage/issues/1347)) ([dab0e7d](https://www.github.com/googleapis/nodejs-storage/commit/dab0e7d9345499411cec57186ef7404026f041eb)) + +### [5.5.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.5.0...v5.5.1) (2020-12-01) + + +### Bug Fixes + +* add publicUrl to exclude promisifyAll ([#1339](https://www.github.com/googleapis/nodejs-storage/issues/1339)) ([ea2c2c9](https://www.github.com/googleapis/nodejs-storage/commit/ea2c2c9d670b8a8eefffa3e67dd2599135c0d933)) +* error if both `storageClass` and specific storage class name are provided ([#1323](https://www.github.com/googleapis/nodejs-storage/issues/1323)) ([91a65f8](https://www.github.com/googleapis/nodejs-storage/commit/91a65f86fe5f9608437b91d6e67192c78b0e8d7b)) +* only throw if `storageClass` and specific storage class name provide different values ([#1346](https://www.github.com/googleapis/nodejs-storage/issues/1346)) ([1765608](https://www.github.com/googleapis/nodejs-storage/commit/1765608430d98c555e4a7431c28cd5878e65c7df)) +* **docs:** explain manual pagination and add usage sample ([#1317](https://www.github.com/googleapis/nodejs-storage/issues/1317)) ([16b779d](https://www.github.com/googleapis/nodejs-storage/commit/16b779de912f6ac082ec5ee3d904b125a5526485)) + +## [5.5.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.4.0...v5.5.0) (2020-11-03) + + +### Features + +* accessibleAt v4 signed urls ([#1328](https://www.github.com/googleapis/nodejs-storage/issues/1328)) ([1e0295e](https://www.github.com/googleapis/nodejs-storage/commit/1e0295eebd1120ce6cbcabee4cf1aaa825455d4b)) + +## [5.4.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.3.0...v5.4.0) (2020-10-29) + + +### Features + +* **userAgent:** allow for optional user agent to be provided ([#1313](https://www.github.com/googleapis/nodejs-storage/issues/1313)) ([13a064f](https://www.github.com/googleapis/nodejs-storage/commit/13a064f3e7342640c5c6e64e060e8558062a31c7)) +* add custom time field in metadata sample ([#1285](https://www.github.com/googleapis/nodejs-storage/issues/1285)) ([9e3474f](https://www.github.com/googleapis/nodejs-storage/commit/9e3474f87dabd300d914c0f44f49a13dae34227d)) +* add File#rename ([#1311](https://www.github.com/googleapis/nodejs-storage/issues/1311)) ([c77eaa3](https://www.github.com/googleapis/nodejs-storage/commit/c77eaa363be18b6b9ddd1f7b505e23be8cd5bf98)) +* public url of a file ([#1324](https://www.github.com/googleapis/nodejs-storage/issues/1324)) ([5ec256e](https://www.github.com/googleapis/nodejs-storage/commit/5ec256e58d04dbcb8dee8cde7460b306da5ff880)) + + +### Bug Fixes + +* set customEndpoint for custom environments ([#1316](https://www.github.com/googleapis/nodejs-storage/issues/1316)) ([60910e1](https://www.github.com/googleapis/nodejs-storage/commit/60910e1903f95a0abca6b9855d11833b32666e2c)) +* **deps:** update dependency gaxios to v4 ([#1322](https://www.github.com/googleapis/nodejs-storage/issues/1322)) ([f9b16d8](https://www.github.com/googleapis/nodejs-storage/commit/f9b16d82e5c6a26d76f721a277cf07b518b63a42)) +* moved publicUrl comment ([#1327](https://www.github.com/googleapis/nodejs-storage/issues/1327)) ([249ed2c](https://www.github.com/googleapis/nodejs-storage/commit/249ed2c4e5fe9cfb029ca8e60c1bafab5c370a48)) +* self-upload files for Unicode system tests ([#1318](https://www.github.com/googleapis/nodejs-storage/issues/1318)) ([e826a52](https://www.github.com/googleapis/nodejs-storage/commit/e826a526c3a5a8515cc7a07c15f86fcfb0fb2f93)) +* **deps:** update dependency duplexify to v4 ([#1302](https://www.github.com/googleapis/nodejs-storage/issues/1302)) ([1ce3d89](https://www.github.com/googleapis/nodejs-storage/commit/1ce3d895b3f5d12776f0634b41b1baef7aa4491c)) +* **deps:** update dependency yargs to v16 ([#1289](https://www.github.com/googleapis/nodejs-storage/issues/1289)) ([12f2133](https://www.github.com/googleapis/nodejs-storage/commit/12f2133b7e3ec9612b3694d93b9ff756cb1bbd66)) +* **types:** add `CreateBucketRequest.storageClass` ([#1299](https://www.github.com/googleapis/nodejs-storage/issues/1299)) ([d854c26](https://www.github.com/googleapis/nodejs-storage/commit/d854c2609eb87886a010e726daa5f1339ee9ea38)), closes [#1248](https://www.github.com/googleapis/nodejs-storage/issues/1248) + +## [5.3.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.2.0...v5.3.0) (2020-08-24) + + +### Features + +* support noncurrent time object lifecycle condition ([#1216](https://www.github.com/googleapis/nodejs-storage/issues/1216)) ([d198aff](https://www.github.com/googleapis/nodejs-storage/commit/d198affa98b0dd027d6628eaff9fcd2dca5c7b47)) + +## [5.2.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.1.2...v5.2.0) (2020-08-10) + + +### Features + +* remove through2 dependency ([#1240](https://www.github.com/googleapis/nodejs-storage/issues/1240)) ([97c73dd](https://www.github.com/googleapis/nodejs-storage/commit/97c73ddec4dbb7cbf7a1486c16ed24dbe9be6d83)) + + +### Bug Fixes + +* support request interceptors for file uploads ([#1225](https://www.github.com/googleapis/nodejs-storage/issues/1225)) ([aa4e4ec](https://www.github.com/googleapis/nodejs-storage/commit/aa4e4ecf49c2e67fdeb90d54e06335fe8671c185)) +* **deps:** update dependency date-and-time to ^0.14.0 ([#1263](https://www.github.com/googleapis/nodejs-storage/issues/1263)) ([408aff9](https://www.github.com/googleapis/nodejs-storage/commit/408aff9234b30f4d68bc9027fbc3088ab059578a)) + +### [5.1.2](https://www.github.com/googleapis/nodejs-storage/compare/v5.1.1...v5.1.2) (2020-07-06) + + +### Bug Fixes + +* **deps:** update dependency through2 to v4 ([#1226](https://www.github.com/googleapis/nodejs-storage/issues/1226)) ([2be25e8](https://www.github.com/googleapis/nodejs-storage/commit/2be25e8fbd4bc60f8e702c2120cf99510508cd15)) + +### [5.1.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.1.0...v5.1.1) (2020-06-19) + + +### Bug Fixes + +* **deps:** update dependency p-limit to v3 ([#1210](https://www.github.com/googleapis/nodejs-storage/issues/1210)) ([7da0379](https://www.github.com/googleapis/nodejs-storage/commit/7da03797791ed20ffbbc6456c7cfad1653c59e76)) +* update node issue template ([#1220](https://www.github.com/googleapis/nodejs-storage/issues/1220)) ([eaac92b](https://www.github.com/googleapis/nodejs-storage/commit/eaac92bb789aea32718280fb67c6496022fa56d3)) + +## [5.1.0](https://www.github.com/googleapis/nodejs-storage/compare/v5.0.1...v5.1.0) (2020-06-11) + + +### Features + +* **secrets:** begin migration to secret manager from keystore ([#1211](https://www.github.com/googleapis/nodejs-storage/issues/1211)) ([11b16ae](https://www.github.com/googleapis/nodejs-storage/commit/11b16ae1b06273ab169d7b1f65a54196956ef4ea)) +* allow setting timeouts on uploads ([#1208](https://www.github.com/googleapis/nodejs-storage/issues/1208)) ([01b3691](https://www.github.com/googleapis/nodejs-storage/commit/01b3691bbfc4a93e2229ea07184637479c515183)) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/pubsub to v2 ([#1201](https://www.github.com/googleapis/nodejs-storage/issues/1201)) ([c684b2a](https://www.github.com/googleapis/nodejs-storage/commit/c684b2abe99169a8801d76fda38a4cbfba91f417)) + +### [5.0.1](https://www.github.com/googleapis/nodejs-storage/compare/v5.0.0...v5.0.1) (2020-05-20) + + +### Bug Fixes + +* StorageOptions.apiEndpoint overrides simple and resumable uploads ([#1161](https://www.github.com/googleapis/nodejs-storage/issues/1161)) ([cf8ea5c](https://www.github.com/googleapis/nodejs-storage/commit/cf8ea5cbbecea50233b1681c7f8aba121ec37a1a)) +* **types:** assert in typescript 3.7 ([#1198](https://www.github.com/googleapis/nodejs-storage/issues/1198)) ([d5aa8b7](https://www.github.com/googleapis/nodejs-storage/commit/d5aa8b7892366c9fbbdc33dd001f644da61bb22e)) + +## [5.0.0](https://www.github.com/googleapis/nodejs-storage/compare/v4.7.0...v5.0.0) (2020-05-13) + + +### ⚠ BREAKING CHANGES + +* automatically detect contentType if not provided (#1190) +* drop keepAcl parameter in file copy (#1166) +* drop support for node.js 8.x + +### Features + +* automatically detect contentType if not provided ([#1190](https://www.github.com/googleapis/nodejs-storage/issues/1190)) ([b31ba4a](https://www.github.com/googleapis/nodejs-storage/commit/b31ba4a11399b57538ddf0d6ca2e10b2aa3fbc3a)) +* enable bytes read tracking ([#1074](https://www.github.com/googleapis/nodejs-storage/issues/1074)) ([0776a04](https://www.github.com/googleapis/nodejs-storage/commit/0776a044f3b2149b485e114369e952688df75645)) + + +### Bug Fixes + +* **bucket:** Only disable resumable uploads for bucket.upload (fixes [#1133](https://www.github.com/googleapis/nodejs-storage/issues/1133)) ([#1135](https://www.github.com/googleapis/nodejs-storage/issues/1135)) ([2c20148](https://www.github.com/googleapis/nodejs-storage/commit/2c201486b7b2d3146846ac96c877a904c4a674b0)), closes [/github.com/googleapis/nodejs-storage/pull/1135#issuecomment-620070038](https://www.github.com/googleapis//github.com/googleapis/nodejs-storage/pull/1135/issues/issuecomment-620070038) +* add whitespace to generateV4SignedPolicy ([#1136](https://www.github.com/googleapis/nodejs-storage/issues/1136)) ([dcee78b](https://www.github.com/googleapis/nodejs-storage/commit/dcee78b98da23b02fe7d2f13a9270546bc07bba8)) +* apache license URL ([#468](https://www.github.com/googleapis/nodejs-storage/issues/468)) ([#1151](https://www.github.com/googleapis/nodejs-storage/issues/1151)) ([e8116d3](https://www.github.com/googleapis/nodejs-storage/commit/e8116d3c6fa7412858692e67745b514eef78850e)) +* Point to team in correct org ([#1185](https://www.github.com/googleapis/nodejs-storage/issues/1185)) ([0bb1909](https://www.github.com/googleapis/nodejs-storage/commit/0bb19098013acf71cc3842f78ff333a8e356331a)) +* **deps:** update dependency @google-cloud/common to v3 ([#1134](https://www.github.com/googleapis/nodejs-storage/issues/1134)) ([774ac5c](https://www.github.com/googleapis/nodejs-storage/commit/774ac5c75f02238418cc8ed7242297ea573ca9cb)) +* **deps:** update dependency @google-cloud/paginator to v3 ([#1131](https://www.github.com/googleapis/nodejs-storage/issues/1131)) ([c1614d9](https://www.github.com/googleapis/nodejs-storage/commit/c1614d98e3047db379e09299b1014e80d73ed52f)) +* **deps:** update dependency @google-cloud/promisify to v2 ([#1127](https://www.github.com/googleapis/nodejs-storage/issues/1127)) ([06624a5](https://www.github.com/googleapis/nodejs-storage/commit/06624a534cd1fdbc38455eee8d89f9f60ba75758)) +* **deps:** update dependency uuid to v8 ([#1170](https://www.github.com/googleapis/nodejs-storage/issues/1170)) ([6a98d64](https://www.github.com/googleapis/nodejs-storage/commit/6a98d64831baf1ca1ec2f03ecc4914745cba1c86)) +* **deps:** update gcs-resumable-upload, remove gitnpm usage ([#1186](https://www.github.com/googleapis/nodejs-storage/issues/1186)) ([c78c9cd](https://www.github.com/googleapis/nodejs-storage/commit/c78c9cde49dccb2fcd4ce10e4e9f8299d65f6838)) +* **v4-policy:** encode special characters ([#1169](https://www.github.com/googleapis/nodejs-storage/issues/1169)) ([6e48539](https://www.github.com/googleapis/nodejs-storage/commit/6e48539d76ca27e6f4c6cf2ac0872970f7391fed)) +* sync to googleapis/conformance-tests@fa559a1 ([#1167](https://www.github.com/googleapis/nodejs-storage/issues/1167)) ([5500446](https://www.github.com/googleapis/nodejs-storage/commit/550044619d2f17a1977c83bce5df915c6dc9578c)), closes [#1168](https://www.github.com/googleapis/nodejs-storage/issues/1168) + + +### Miscellaneous Chores + +* drop keepAcl parameter in file copy ([#1166](https://www.github.com/googleapis/nodejs-storage/issues/1166)) ([5a4044a](https://www.github.com/googleapis/nodejs-storage/commit/5a4044a8ba13f248fc4f791248f797eb0f1f3c16)) + + +### Build System + +* drop support for node.js 8.x ([b80c025](https://www.github.com/googleapis/nodejs-storage/commit/b80c025f106052fd25554c64314b3b3520e829b5)) + +## [4.7.0](https://www.github.com/googleapis/nodejs-storage/compare/v4.6.0...v4.7.0) (2020-03-26) + + +### Features + +* add remove conditional binding ([#1107](https://www.github.com/googleapis/nodejs-storage/issues/1107)) ([2143705](https://www.github.com/googleapis/nodejs-storage/commit/21437053e9497aa95ef37a865ffbdbaf4134138f)) +* v4 POST with signed policy ([#1102](https://www.github.com/googleapis/nodejs-storage/issues/1102)) ([a3d5b88](https://www.github.com/googleapis/nodejs-storage/commit/a3d5b88b8d3d25b6e16808eb5c1425aa0a8c5ecc)), closes [#1125](https://www.github.com/googleapis/nodejs-storage/issues/1125) + + +### Bug Fixes + +* **deps:** update dependency date-and-time to ^0.13.0 ([#1106](https://www.github.com/googleapis/nodejs-storage/issues/1106)) ([b759605](https://www.github.com/googleapis/nodejs-storage/commit/b7596058e130ee2d82dc2221f24220b83c04fdae)) +* **deps:** update dependency gaxios to v3 ([#1129](https://www.github.com/googleapis/nodejs-storage/issues/1129)) ([5561452](https://www.github.com/googleapis/nodejs-storage/commit/5561452cb0b6e5a1dcabea6973db57799422abb7)) +* **types:** wrap GetSignedUrlResponse ([#1119](https://www.github.com/googleapis/nodejs-storage/issues/1119)) ([0c7ac16](https://www.github.com/googleapis/nodejs-storage/commit/0c7ac161f808201562f60710b9ec7bce4fbf819f)) + +## [4.6.0](https://www.github.com/googleapis/nodejs-storage/compare/v4.5.0...v4.6.0) (2020-03-13) + + +### Features + +* **storage:** Add versioning as optional metadata param of createBucket ([#1090](https://www.github.com/googleapis/nodejs-storage/issues/1090)) ([39869e3](https://www.github.com/googleapis/nodejs-storage/commit/39869e3c6c62eabe1840f0fd884b361265e2cb76)) + +## [4.5.0](https://www.github.com/googleapis/nodejs-storage/compare/v4.4.0...v4.5.0) (2020-03-06) + + +### Features + +* **v4:** support v4 signed URL for GA ([#1072](https://www.github.com/googleapis/nodejs-storage/issues/1072)) ([79d7b8f](https://www.github.com/googleapis/nodejs-storage/commit/79d7b8f5a187f23e58bf84db3f4b8c4b1a921978)), closes [#1051](https://www.github.com/googleapis/nodejs-storage/issues/1051) [#1056](https://www.github.com/googleapis/nodejs-storage/issues/1056) [#1066](https://www.github.com/googleapis/nodejs-storage/issues/1066) [#1068](https://www.github.com/googleapis/nodejs-storage/issues/1068) [#1069](https://www.github.com/googleapis/nodejs-storage/issues/1069) [#1067](https://www.github.com/googleapis/nodejs-storage/issues/1067) [#1070](https://www.github.com/googleapis/nodejs-storage/issues/1070) + +## [4.4.0](https://www.github.com/googleapis/nodejs-storage/compare/v4.3.2...v4.4.0) (2020-03-03) + + +### Features + +* **bucket:** support single source in combine ([#1076](https://www.github.com/googleapis/nodejs-storage/issues/1076)) ([#1085](https://www.github.com/googleapis/nodejs-storage/issues/1085)) ([251a617](https://www.github.com/googleapis/nodejs-storage/commit/251a617791ca4b0e148b741d1931013150becc02)) + +### [4.3.2](https://www.github.com/googleapis/nodejs-storage/compare/v4.3.1...v4.3.2) (2020-03-02) + + +### Bug Fixes + +* **deps:** update dependency uuid to v7 ([#1081](https://www.github.com/googleapis/nodejs-storage/issues/1081)) ([c72d57f](https://www.github.com/googleapis/nodejs-storage/commit/c72d57f6f2982dad512d425ee3f041b43a87c278)) +* **tests:** flaky getSignedPolicy tests ([#1093](https://www.github.com/googleapis/nodejs-storage/issues/1093)) ([531050a](https://www.github.com/googleapis/nodejs-storage/commit/531050a05e5b1eeedb25647417a8ae9df8d76f29)) + +### [4.3.1](https://www.github.com/googleapis/nodejs-storage/compare/v4.3.0...v4.3.1) (2020-02-06) + + +### Bug Fixes + +* **samples:** fix overwritten IAM conditions sample ([#1042](https://www.github.com/googleapis/nodejs-storage/issues/1042)) ([25d839c](https://www.github.com/googleapis/nodejs-storage/commit/25d839ccf421276d8a4c18b2be95004ca832d84d)) +* skip validation for server decompressed objects ([#1063](https://www.github.com/googleapis/nodejs-storage/issues/1063)) ([d6e3738](https://www.github.com/googleapis/nodejs-storage/commit/d6e37382da1ed3b72771770cb9447c62c91f26a5)) +* unhandled promise rejection warning in samples ([#1056](https://www.github.com/googleapis/nodejs-storage/issues/1056)) ([e95ec19](https://www.github.com/googleapis/nodejs-storage/commit/e95ec19756388e6fc4fc8e0d49a40c613ed006c6)) + +## [4.3.0](https://www.github.com/googleapis/nodejs-storage/compare/v4.2.0...v4.3.0) (2020-01-21) + + +### Features + +* add support for CORS as a first class citizen ([#1020](https://www.github.com/googleapis/nodejs-storage/issues/1020)) ([9fee6d9](https://www.github.com/googleapis/nodejs-storage/commit/9fee6d969a1311a3db18bf523d3614adef0526ce)) + + +### Bug Fixes + +* **deps:** update dependency date-and-time to ^0.12.0 ([#1032](https://www.github.com/googleapis/nodejs-storage/issues/1032)) ([a324564](https://www.github.com/googleapis/nodejs-storage/commit/a324564e8f29345412047b7f6296098211e0e831)) +* a couple of typos from the refactorNodeSampleStorage branch ([#1038](https://www.github.com/googleapis/nodejs-storage/issues/1038)) ([8faa6c6](https://www.github.com/googleapis/nodejs-storage/commit/8faa6c6698b3b7ef4857d978482209bc5077e08e)) +* do not modify constructor options ([#974](https://www.github.com/googleapis/nodejs-storage/issues/974)) ([4969148](https://www.github.com/googleapis/nodejs-storage/commit/4969148f5e114d86aa4928109f099ec15d56fda5)) +* refactor getMetadata sample into its own file ([#1008](https://www.github.com/googleapis/nodejs-storage/issues/1008)) ([6ed1af8](https://www.github.com/googleapis/nodejs-storage/commit/6ed1af8aadd6f72cf0957d02e403f7c551166a5c)) +* refactor getRetentionPolicy sample into its own file ([#993](https://www.github.com/googleapis/nodejs-storage/issues/993)) ([47e4ad8](https://www.github.com/googleapis/nodejs-storage/commit/47e4ad8c8a4fd16f4f1d9d6d9bfdc9e30b1ab999)) +* refactor getUniformBucketLevelAccess into its own file ([#981](https://www.github.com/googleapis/nodejs-storage/issues/981)) ([0ba69f1](https://www.github.com/googleapis/nodejs-storage/commit/0ba69f1b3d6093701dac927fa4543d2d911ce8b0)) +* refactor rotateEncryptionKey sample into its own file ([#1030](https://www.github.com/googleapis/nodejs-storage/issues/1030)) ([afdf0fe](https://www.github.com/googleapis/nodejs-storage/commit/afdf0febe8760c0819736961065d134e231a0afa)) +* refactor uploadEncryptedFile sample into its own file ([#1028](https://www.github.com/googleapis/nodejs-storage/issues/1028)) ([ba4520b](https://www.github.com/googleapis/nodejs-storage/commit/ba4520b5f925968717222ffe5d2b1dbcfbea4334)) +* refactoring disableUniformBucketLevelAccess into its own file ([#980](https://www.github.com/googleapis/nodejs-storage/issues/980)) ([1481e20](https://www.github.com/googleapis/nodejs-storage/commit/1481e20d8332ee2806116166fb16028506487d2d)) + +## [4.2.0](https://www.github.com/googleapis/nodejs-storage/compare/v4.1.3...v4.2.0) (2020-01-02) + + +### Features + +* **iam:** getIamPolicy to support requestedPolicyVersion ([#960](https://www.github.com/googleapis/nodejs-storage/issues/960)) ([0f38f75](https://www.github.com/googleapis/nodejs-storage/commit/0f38f7597f5e671b4c08830f8d457f9ca2c03cd1)) +* add support for Archive storage class ([#908](https://www.github.com/googleapis/nodejs-storage/issues/908)) ([63f63f4](https://www.github.com/googleapis/nodejs-storage/commit/63f63f448d2d220b1e77a7dcd379f7ac7fc22af3)) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([#952](https://www.github.com/googleapis/nodejs-storage/issues/952)) ([1fea60c](https://www.github.com/googleapis/nodejs-storage/commit/1fea60c04fd9762c5506c22df0992cdb8fce4ea0)) +* add createBucket file and updated relevant test ([#940](https://www.github.com/googleapis/nodejs-storage/issues/940)) ([913b43e](https://www.github.com/googleapis/nodejs-storage/commit/913b43e66bb10bd5dbf6b0bca9e65edd48b54234)) +* update PolicyDocument types ([#944](https://www.github.com/googleapis/nodejs-storage/issues/944)) ([b1c05b2](https://www.github.com/googleapis/nodejs-storage/commit/b1c05b27029215c8bc313a8f4f16ff13d5af2391)) + +### [4.1.3](https://www.github.com/googleapis/nodejs-storage/compare/v4.1.2...v4.1.3) (2019-11-18) + + +### Bug Fixes + +* **deps:** update dependency date-and-time to ^0.11.0 ([#934](https://www.github.com/googleapis/nodejs-storage/issues/934)) ([c4bf1c6](https://www.github.com/googleapis/nodejs-storage/commit/c4bf1c616d0a9402237708bddac1341c620f0542)) +* **deps:** update dependency yargs to v15 ([#933](https://www.github.com/googleapis/nodejs-storage/issues/933)) ([f40fe0c](https://www.github.com/googleapis/nodejs-storage/commit/f40fe0c5bd4e9b89ebe007e59986580fae4d7e09)) + +### [4.1.2](https://www.github.com/googleapis/nodejs-storage/compare/v4.1.1...v4.1.2) (2019-11-12) + + +### Bug Fixes + +* do not check access of configPath ([#915](https://www.github.com/googleapis/nodejs-storage/issues/915)) ([a21a644](https://www.github.com/googleapis/nodejs-storage/commit/a21a6443346f91f275233a9a07fb79550035e157)) +* missing snippets with jsdoc-region-tag ([#924](https://www.github.com/googleapis/nodejs-storage/issues/924)) ([310ba90](https://www.github.com/googleapis/nodejs-storage/commit/310ba90a48c6f02a31c1254037dfcdb4da4b7150)) +* **docs:** add jsdoc-region-tag plugin ([#929](https://www.github.com/googleapis/nodejs-storage/issues/929)) ([74526e7](https://www.github.com/googleapis/nodejs-storage/commit/74526e7f42cfa92c18ff332d0b9e10ea3b1324cf)) + +### [4.1.1](https://www.github.com/googleapis/nodejs-storage/compare/v4.1.0...v4.1.1) (2019-11-07) + + +### Bug Fixes + +* update format for upload sample ([#918](https://www.github.com/googleapis/nodejs-storage/issues/918)) ([d77208b](https://www.github.com/googleapis/nodejs-storage/commit/d77208bee82dc2d76c72fbe8d5db1bfeb8e392ff)) + +## [4.1.0](https://www.github.com/googleapis/nodejs-storage/compare/v4.0.1...v4.1.0) (2019-10-31) + + +### Features + +* [Storage] Support UniformBucketLevelAccess ([#903](https://www.github.com/googleapis/nodejs-storage/issues/903)) ([35b1bd9](https://www.github.com/googleapis/nodejs-storage/commit/35b1bd9f6db351ad1e51b135a3f25cc5e1566600)) + +### [4.0.1](https://www.github.com/googleapis/nodejs-storage/compare/v4.0.0...v4.0.1) (2019-10-31) + + +### Bug Fixes + +* **docs:** missing quote in signed url jsdoc ([#896](https://www.github.com/googleapis/nodejs-storage/issues/896)) ([f2d567f](https://www.github.com/googleapis/nodejs-storage/commit/f2d567f279fee0f48c2d6a607f4066c9da372549)) +* use storage.googleapis.com for api endpoint ([862fb16](https://www.github.com/googleapis/nodejs-storage/commit/862fb16db2990c958c0097252a44c775431a7b3f)) +* **signed-url:** replace encodeURIComponent with custom encoding function ([#905](https://www.github.com/googleapis/nodejs-storage/issues/905)) ([ba41517](https://www.github.com/googleapis/nodejs-storage/commit/ba415179f1d5951742c1b239e0500bbd2a815ddd)) + +## [4.0.0](https://www.github.com/googleapis/nodejs-storage/compare/v3.5.0...v4.0.0) (2019-10-17) + + +### ⚠ BREAKING CHANGES + +* allow leading slashes in file name (#820) + +### Bug Fixes + +* **deps:** update hash-stream-validation ([#884](https://www.github.com/googleapis/nodejs-storage/issues/884)) ([96a7fc2](https://www.github.com/googleapis/nodejs-storage/commit/96a7fc297a563819b09727990eb9ee15a421310b)) +* allow leading slashes in file name ([#820](https://www.github.com/googleapis/nodejs-storage/issues/820)) ([92e115d](https://www.github.com/googleapis/nodejs-storage/commit/92e115dca81604909fc34e983abcf47409d3f417)) + +## [3.5.0](https://www.github.com/googleapis/nodejs-storage/compare/v3.4.0...v3.5.0) (2019-10-14) + + +### Features + +* **bucket:** add enableLogging method ([#876](https://www.github.com/googleapis/nodejs-storage/issues/876)) ([b09ecac](https://www.github.com/googleapis/nodejs-storage/commit/b09ecac79b70bf99e19f0f23ffcecd17e34516bb)) + +## [3.4.0](https://www.github.com/googleapis/nodejs-storage/compare/v3.3.1...v3.4.0) (2019-10-10) + + +### Bug Fixes + +* file#move do not delete origin file if same as destination ([#874](https://www.github.com/googleapis/nodejs-storage/issues/874)) ([dcaba8a](https://www.github.com/googleapis/nodejs-storage/commit/dcaba8a)) +* pass predefined acl as destinationPredefinedAcl to qs ([#872](https://www.github.com/googleapis/nodejs-storage/issues/872)) ([09b8fa4](https://www.github.com/googleapis/nodejs-storage/commit/09b8fa4)) + + +### Features + +* add flag to allow disabling auto decompression by client ([#850](https://www.github.com/googleapis/nodejs-storage/issues/850)) ([9ebface](https://www.github.com/googleapis/nodejs-storage/commit/9ebface)) +* allow setting standard Bucket storage class ([#873](https://www.github.com/googleapis/nodejs-storage/issues/873)) ([12a99e9](https://www.github.com/googleapis/nodejs-storage/commit/12a99e9)) + +### [3.3.1](https://www.github.com/googleapis/nodejs-storage/compare/v3.3.0...v3.3.1) (2019-09-30) + + +### Bug Fixes + +* create correct v4 signed url with cname ([#868](https://www.github.com/googleapis/nodejs-storage/issues/868)) ([ace3b5e](https://www.github.com/googleapis/nodejs-storage/commit/ace3b5e)) + +## [3.3.0](https://www.github.com/googleapis/nodejs-storage/compare/v3.2.1...v3.3.0) (2019-09-19) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/pubsub to ^0.32.0 ([#849](https://www.github.com/googleapis/nodejs-storage/issues/849)) ([fdf70bb](https://www.github.com/googleapis/nodejs-storage/commit/fdf70bb)) +* add warning for unsupported keepAcl param in file#copy ([#841](https://www.github.com/googleapis/nodejs-storage/issues/841)) ([473bda0](https://www.github.com/googleapis/nodejs-storage/commit/473bda0)) +* remove unsupported keepAcl param ([#837](https://www.github.com/googleapis/nodejs-storage/issues/837)) ([5f69a3d](https://www.github.com/googleapis/nodejs-storage/commit/5f69a3d)) +* use storage.googleapis.com for api endpoint ([#854](https://www.github.com/googleapis/nodejs-storage/issues/854)) ([27fa02f](https://www.github.com/googleapis/nodejs-storage/commit/27fa02f)) +* **deps:** update dependency @google-cloud/pubsub to v1 ([#858](https://www.github.com/googleapis/nodejs-storage/issues/858)) ([31466f4](https://www.github.com/googleapis/nodejs-storage/commit/31466f4)) +* **deps:** update dependency date-and-time to ^0.10.0 ([#857](https://www.github.com/googleapis/nodejs-storage/issues/857)) ([e9ec9cf](https://www.github.com/googleapis/nodejs-storage/commit/e9ec9cf)) + + +### Features + +* adds support for asyncIterators (via readable-stream@3 dependency) ([dd5ae7f](https://www.github.com/googleapis/nodejs-storage/commit/dd5ae7f)) +* allow removal of resumable upload cache ([#773](https://www.github.com/googleapis/nodejs-storage/issues/773)) ([da943db](https://www.github.com/googleapis/nodejs-storage/commit/da943db)), closes [#217](https://www.github.com/googleapis/nodejs-storage/issues/217) + +### [3.2.1](https://www.github.com/googleapis/nodejs-storage/compare/v3.2.0...v3.2.1) (2019-08-28) + + +### Bug Fixes + +* **docs:** stop redirecting reference docs to anchor, add new sample to README ([bbb5537](https://www.github.com/googleapis/nodejs-storage/commit/bbb5537)) +* **samples:** fix failing sample view IAM member-role groups ([1c4f21f](https://www.github.com/googleapis/nodejs-storage/commit/1c4f21f)) + +## [3.2.0](https://www.github.com/googleapis/nodejs-storage/compare/v3.1.0...v3.2.0) (2019-08-22) + + +### Bug Fixes + +* **deps:** update @google-cloud/common with fixes for http ([#809](https://www.github.com/googleapis/nodejs-storage/issues/809)) ([8598631](https://www.github.com/googleapis/nodejs-storage/commit/8598631)) +* **deps:** update dependency @google-cloud/pubsub to ^0.31.0 ([#814](https://www.github.com/googleapis/nodejs-storage/issues/814)) ([604e564](https://www.github.com/googleapis/nodejs-storage/commit/604e564)) +* **deps:** update dependency date-and-time to ^0.9.0 ([#805](https://www.github.com/googleapis/nodejs-storage/issues/805)) ([8739a7d](https://www.github.com/googleapis/nodejs-storage/commit/8739a7d)) +* **ts:** fix nock @~11.0.0 ([#819](https://www.github.com/googleapis/nodejs-storage/issues/819)) ([48f9b44](https://www.github.com/googleapis/nodejs-storage/commit/48f9b44)) + + +### Features + +* hmac service account ([#751](https://www.github.com/googleapis/nodejs-storage/issues/751)) ([ed1ec7b](https://www.github.com/googleapis/nodejs-storage/commit/ed1ec7b)) + +## [3.1.0](https://www.github.com/googleapis/nodejs-storage/compare/v3.0.4...v3.1.0) (2019-08-09) + + +### Bug Fixes + +* **deps:** update dependency @google-cloud/paginator to v2 ([#781](https://www.github.com/googleapis/nodejs-storage/issues/781)) ([23244e9](https://www.github.com/googleapis/nodejs-storage/commit/23244e9)) +* **deps:** update dependency @google-cloud/pubsub to ^0.30.0 ([#778](https://www.github.com/googleapis/nodejs-storage/issues/778)) ([7256650](https://www.github.com/googleapis/nodejs-storage/commit/7256650)) +* allow calls with no request, add JSON proto ([30fff15](https://www.github.com/googleapis/nodejs-storage/commit/30fff15)) +* **deps:** update dependency date-and-time to ^0.8.0 ([#779](https://www.github.com/googleapis/nodejs-storage/issues/779)) ([ab2734d](https://www.github.com/googleapis/nodejs-storage/commit/ab2734d)) +* **deps:** upgrade @google-cloud/common version to show original… ([#795](https://www.github.com/googleapis/nodejs-storage/issues/795)) ([ea63cbe](https://www.github.com/googleapis/nodejs-storage/commit/ea63cbe)) +* **deps:** use the latest extend ([#800](https://www.github.com/googleapis/nodejs-storage/issues/800)) ([a7f0172](https://www.github.com/googleapis/nodejs-storage/commit/a7f0172)) + + +### Features + +* **file:** allow setting configPath of resumable upload ([#642](https://www.github.com/googleapis/nodejs-storage/issues/642)) ([a8ceb78](https://www.github.com/googleapis/nodejs-storage/commit/a8ceb78)) + +### [3.0.4](https://www.github.com/googleapis/nodejs-storage/compare/v3.0.3...v3.0.4) (2019-07-25) + + +### Bug Fixes + +* **deps:** update dependency pumpify to v2 ([#740](https://www.github.com/googleapis/nodejs-storage/issues/740)) ([71a4f59](https://www.github.com/googleapis/nodejs-storage/commit/71a4f59)) + +### [3.0.3](https://www.github.com/googleapis/nodejs-storage/compare/v3.0.2...v3.0.3) (2019-07-16) + + +### Bug Fixes + +* **typescript:** make SetLabelOptions optional ([#766](https://www.github.com/googleapis/nodejs-storage/issues/766)) ([4336882](https://www.github.com/googleapis/nodejs-storage/commit/4336882)) + +### [3.0.2](https://www.github.com/googleapis/nodejs-storage/compare/v3.0.1...v3.0.2) (2019-07-01) + + +### Bug Fixes + +* **docs:** fix sample code in docs ([#759](https://www.github.com/googleapis/nodejs-storage/issues/759)) ([f9e5fd8](https://www.github.com/googleapis/nodejs-storage/commit/f9e5fd8)) +* **docs:** link to reference docs section on googleapis.dev ([#753](https://www.github.com/googleapis/nodejs-storage/issues/753)) ([5e3a96b](https://www.github.com/googleapis/nodejs-storage/commit/5e3a96b)) + +### [3.0.1](https://www.github.com/googleapis/nodejs-storage/compare/v3.0.0...v3.0.1) (2019-06-14) + + +### Bug Fixes + +* async should be dependency ([#743](https://www.github.com/googleapis/nodejs-storage/issues/743)) ([e542b8b](https://www.github.com/googleapis/nodejs-storage/commit/e542b8b)) + +## [3.0.0](https://www.github.com/googleapis/nodejs-storage/compare/v2.5.0...v3.0.0) (2019-06-14) + + +### ⚠ BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#688) + +### Bug Fixes + +* **deps:** update dependency @google-cloud/common to v1 ([#705](https://www.github.com/googleapis/nodejs-storage/issues/705)) ([72a9f51](https://www.github.com/googleapis/nodejs-storage/commit/72a9f51)) +* **deps:** update dependency @google-cloud/paginator to v1 ([#695](https://www.github.com/googleapis/nodejs-storage/issues/695)) ([ada995e](https://www.github.com/googleapis/nodejs-storage/commit/ada995e)) +* **deps:** update dependency @google-cloud/promisify to v1 ([#693](https://www.github.com/googleapis/nodejs-storage/issues/693)) ([5df2f83](https://www.github.com/googleapis/nodejs-storage/commit/5df2f83)) +* **deps:** update dependency @google-cloud/pubsub to ^0.29.0 ([#714](https://www.github.com/googleapis/nodejs-storage/issues/714)) ([3ee1a2c](https://www.github.com/googleapis/nodejs-storage/commit/3ee1a2c)) +* **deps:** update dependency arrify to v2 ([#667](https://www.github.com/googleapis/nodejs-storage/issues/667)) ([ce02c27](https://www.github.com/googleapis/nodejs-storage/commit/ce02c27)) +* validate action of getSignedUrl() function ([#684](https://www.github.com/googleapis/nodejs-storage/issues/684)) ([1b09d24](https://www.github.com/googleapis/nodejs-storage/commit/1b09d24)) +* **deps:** update dependency date-and-time to ^0.7.0 ([#736](https://www.github.com/googleapis/nodejs-storage/issues/736)) ([7071f26](https://www.github.com/googleapis/nodejs-storage/commit/7071f26)) +* **deps:** update dependency xdg-basedir to v4 ([#681](https://www.github.com/googleapis/nodejs-storage/issues/681)) ([8b40e6a](https://www.github.com/googleapis/nodejs-storage/commit/8b40e6a)) +* **docs:** move to new client docs URL ([#738](https://www.github.com/googleapis/nodejs-storage/issues/738)) ([a637f99](https://www.github.com/googleapis/nodejs-storage/commit/a637f99)) +* **ts:** improve return types for response metadata ([#666](https://www.github.com/googleapis/nodejs-storage/issues/666)) ([da42bed](https://www.github.com/googleapis/nodejs-storage/commit/da42bed)) +* **types:** fix signatures of listing methods ([#703](https://www.github.com/googleapis/nodejs-storage/issues/703)) ([42937a8](https://www.github.com/googleapis/nodejs-storage/commit/42937a8)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#688](https://www.github.com/googleapis/nodejs-storage/issues/688)) ([6a1fa0f](https://www.github.com/googleapis/nodejs-storage/commit/6a1fa0f)) + + +### Features + +* add file.isPublic() function ([#708](https://www.github.com/googleapis/nodejs-storage/issues/708)) ([f86cadb](https://www.github.com/googleapis/nodejs-storage/commit/f86cadb)) +* support apiEndpoint override ([#728](https://www.github.com/googleapis/nodejs-storage/issues/728)) ([61eeb64](https://www.github.com/googleapis/nodejs-storage/commit/61eeb64)) + +## v2.5.0 + +04-04-2019 12:27 PDT + +This release brings an option to file#getSignedURL to create a version 4 Signed URL. + +```javascript +file.getSignedUrl({ + version: 'v4', // optional, defaults to v2 (existing version) + action: 'read', + expires: FUTURE_DATE, +}) +``` + +### New Features +- feat: introduce v4 signed url ([#637](https://github.com/googleapis/nodejs-storage/pull/637)) + +### Dependencies +- chore(deps): update dependency @types/node to v11.13.0 ([#662](https://github.com/googleapis/nodejs-storage/pull/662)) +- chore(deps): update dependency @types/tmp to v0.1.0 +- chore(deps): upgrade to newest version of @google-cloud/common ([#657](https://github.com/googleapis/nodejs-storage/pull/657)) +- chore(deps): update dependency typescript to ~3.4.0 +- chore(deps): update dependency tmp to ^0.1.0 ([#641](https://github.com/googleapis/nodejs-storage/pull/641)) + +### Documentation +- docs: regenerate the samples/README.md ([#649](https://github.com/googleapis/nodejs-storage/pull/649)) +- docs: slight difference in how nightly synthtool run generated README ([#650](https://github.com/googleapis/nodejs-storage/pull/650)) +- docs: new synthtool generated README ([#645](https://github.com/googleapis/nodejs-storage/pull/645)) +- docs(samples): refactor the quickstart to match the new rubric ([#647](https://github.com/googleapis/nodejs-storage/pull/647)) +- docs: update README format +- docs: add requires_billing, retire .cloud-repo-tools.json ([#644](https://github.com/googleapis/nodejs-storage/pull/644)) +- docs: add additional api_id field ([#640](https://github.com/googleapis/nodejs-storage/pull/640)) +- docs: document destination option ([#633](https://github.com/googleapis/nodejs-storage/pull/633)) +- docs: clarify in docs, the meaning of ASIA and coldline ([#632](https://github.com/googleapis/nodejs-storage/pull/632)) +- docs: add a .repo-metadata.json ([#639](https://github.com/googleapis/nodejs-storage/pull/639)) + +### Internal / Testing Changes +- test(v2-sign): add multi-valued headers system-test ([#646](https://github.com/googleapis/nodejs-storage/pull/646)) +- refactor: replace once with onetime ([#660](https://github.com/googleapis/nodejs-storage/pull/660)) +- fix: do not download cached files ([#643](https://github.com/googleapis/nodejs-storage/pull/643)) +- chore: publish to npm using wombat ([#634](https://github.com/googleapis/nodejs-storage/pull/634)) +- build: use per-repo npm publish token ([#630](https://github.com/googleapis/nodejs-storage/pull/630)) + +## v2.4.3 + +03-13-2019 17:10 PDT + +### Bug Fixes / Implementation Changes +- fix: getSigned(Policy|Url) throws if expiration is invalid Date ([#614](https://github.com/googleapis/nodejs-storage/pull/614)) +- fix: handle errors from file#createReadStream ([#615](https://github.com/googleapis/nodejs-storage/pull/615)) + +### Dependencies +- fix(deps): update dependency @google-cloud/paginator to ^0.2.0 +- fix(deps): update dependency gcs-resumable-upload to v1 ([#619](https://github.com/googleapis/nodejs-storage/pull/619)) +- fix(deps): update dependency @google-cloud/pubsub to ^0.27.0 ([#620](https://github.com/googleapis/nodejs-storage/pull/620)) +- fix(deps): update dependency @google-cloud/pubsub to ^0.26.0 ([#618](https://github.com/googleapis/nodejs-storage/pull/618)) +- fix(deps): update dependency @google-cloud/pubsub to ^0.25.0 ([#616](https://github.com/googleapis/nodejs-storage/pull/616)) +- chore(deps): update dependency mocha to v6 ([#611](https://github.com/googleapis/nodejs-storage/pull/611)) +- fix(deps): update dependency @google-cloud/promisify to ^0.4.0 ([#609](https://github.com/googleapis/nodejs-storage/pull/609)) +- chore(deps): update dependency @types/tmp to v0.0.34 ([#608](https://github.com/googleapis/nodejs-storage/pull/608)) +- fix(deps): update dependency yargs to v13 ([#606](https://github.com/googleapis/nodejs-storage/pull/606)) + +### Documentation +- docs: update links in contrib guide ([#610](https://github.com/googleapis/nodejs-storage/pull/610)) +- docs: update contributing path in README ([#603](https://github.com/googleapis/nodejs-storage/pull/603)) +- chore: move CONTRIBUTING.md to root ([#601](https://github.com/googleapis/nodejs-storage/pull/601)) + +### Internal / Testing Changes +- build: Add docuploader credentials to node publish jobs ([#624](https://github.com/googleapis/nodejs-storage/pull/624)) +- build: use node10 to run samples-test, system-test etc ([#623](https://github.com/googleapis/nodejs-storage/pull/623)) +- build: update release configuration +- build: use linkinator for docs test ([#607](https://github.com/googleapis/nodejs-storage/pull/607)) +- build: create docs test npm scripts ([#605](https://github.com/googleapis/nodejs-storage/pull/605)) +- build: test using @grpc/grpc-js in CI ([#604](https://github.com/googleapis/nodejs-storage/pull/604)) +- chore: remove console.log in system test ([#599](https://github.com/googleapis/nodejs-storage/pull/599)) + +## v2.4.2 + +02-05-2019 16:55 PST + +### Dependencies + +- deps: update @google-cloud/common ([#596](https://github.com/googleapis/nodejs-storage/pull/596)) +- chore(deps): update dependency typescript to ~3.3.0 ([#591](https://github.com/googleapis/nodejs-storage/pull/591)) + +### Documentation + +- docs: add lint/fix example to contributing guide ([#594](https://github.com/googleapis/nodejs-storage/pull/594)) + +### Internal / Testing Changes + +- test: skip public bucket system tests running under VPCSC ([#595](https://github.com/googleapis/nodejs-storage/pull/595)) + +## v2.4.1 + +01-29-2019 13:05 PST + +### Implementation Changes +- fix(ts): fix Storage.createBucket overloaded signature ([#589](https://github.com/googleapis/nodejs-storage/pull/589)) + +### Dependencies +- fix(deps): update dependency @google-cloud/pubsub to ^0.24.0 ([#588](https://github.com/googleapis/nodejs-storage/pull/588)) + +## v2.4.0 + +01-28-2019 12:13 PST + +### New Features +- fix: `expires` can be a Date, string, or number ([#548](https://github.com/googleapis/nodejs-storage/pull/548)) + +### Dependencies +- deps: upgrade nodejs-common ([#582](https://github.com/googleapis/nodejs-storage/pull/582)) +- chore(deps): update dependency eslint-config-prettier to v4 ([#586](https://github.com/googleapis/nodejs-storage/pull/586)) +- fix(deps): update dependency @google-cloud/pubsub to ^0.23.0 ([#583](https://github.com/googleapis/nodejs-storage/pull/583)) +- fix(deps): update dependency concat-stream to v2 ([#563](https://github.com/googleapis/nodejs-storage/pull/563)) + +### Documentation +- docs(samples): Bucket Policy Only Samples ([#557](https://github.com/googleapis/nodejs-storage/pull/557)) +- fix(docs): move jsdoc away from interface ([#565](https://github.com/googleapis/nodejs-storage/pull/565)) + +### Internal / Testing Changes +- test: Bucket Policy Only related system test ([#579](https://github.com/googleapis/nodejs-storage/pull/579)) +- build: check broken links in generated docs ([#567](https://github.com/googleapis/nodejs-storage/pull/567)) +- build: include only build/src in compiled source ([#572](https://github.com/googleapis/nodejs-storage/pull/572)) + +## v2.3.4 + +12-19-2018 14:21 PST + +### Implementation Changes +- fix(types): file.getMetadata should resolves to Metadata, not File ([#560](https://github.com/googleapis/nodejs-storage/pull/560)) + +### Internal / Testing Changes +- refactor: modernize the sample tests ([#558](https://github.com/googleapis/nodejs-storage/pull/558)) +- chore(build): inject yoshi automation key ([#555](https://github.com/googleapis/nodejs-storage/pull/555)) +- chore: update nyc and eslint configs ([#554](https://github.com/googleapis/nodejs-storage/pull/554)) +- chore: fix publish.sh permission +x ([#552](https://github.com/googleapis/nodejs-storage/pull/552)) +- fix(build): fix Kokoro release script ([#551](https://github.com/googleapis/nodejs-storage/pull/551)) +- build: add Kokoro configs for autorelease ([#550](https://github.com/googleapis/nodejs-storage/pull/550)) + +## v2.3.3 + +12-06-2018 17:09 PST + +### Dependencies +- chore(deps): update dependency @types/configstore to v4 ([#537](https://github.com/googleapis/nodejs-storage/pull/537)) +- chore(deps): update dependency @google-cloud/pubsub to ^0.22.0 ([#535](https://github.com/googleapis/nodejs-storage/pull/535)) + +### Documentation +- fix(docs): place doc comment above the last overload ([#544](https://github.com/googleapis/nodejs-storage/pull/544)) +- docs: update readme badges ([#536](https://github.com/googleapis/nodejs-storage/pull/536)) + +### Internal / Testing Changes +- chore: always nyc report before calling codecov ([#543](https://github.com/googleapis/nodejs-storage/pull/543)) +- chore: nyc ignore build/test by default ([#542](https://github.com/googleapis/nodejs-storage/pull/542)) +- chore: update license file ([#539](https://github.com/googleapis/nodejs-storage/pull/539)) + +## v2.3.2 + +This patch release fixed an issue affecting reading from a file on GCS ([#528](https://github.com/googleapis/nodejs-storage/issues/528)). + +### Dependencies +- fix(dep): upgrade teeny-request to v3.11.3 ([#529](https://github.com/googleapis/nodejs-storage/pull/529)) +- fix(deps): update dependency @google-cloud/common to ^0.27.0 ([#525](https://github.com/googleapis/nodejs-storage/pull/525)) + +### Internal / Testing Changes +- refactor: convert sample tests from ava to mocha ([#523](https://github.com/googleapis/nodejs-storage/pull/523)) +- docs(samples): updated samples code to use async await ([#521](https://github.com/googleapis/nodejs-storage/pull/521)) +- chore: add synth.metadata +- fix(ts): Update bucket options types ([#518](https://github.com/googleapis/nodejs-storage/pull/518)) + +## v2.3.1 + +11-14-2018 22:15 PST + +### Bug fixes +- fix: fix TypeScript and system tests ([#515](https://github.com/googleapis/nodejs-storage/pull/515)) +- fix(deps): update dependency through2 to v3 ([#507](https://github.com/googleapis/nodejs-storage/pull/507)) +- docs: File#setMetadata in parallel results in unpredictable state ([#504](https://github.com/googleapis/nodejs-storage/pull/504)) + +### Internal / Testing Changes +- chore(deps): update dependency gts to ^0.9.0 ([#514](https://github.com/googleapis/nodejs-storage/pull/514)) +- chore: update eslintignore config ([#513](https://github.com/googleapis/nodejs-storage/pull/513)) +- chore(deps): update dependency @google-cloud/nodejs-repo-tools to v3 ([#512](https://github.com/googleapis/nodejs-storage/pull/512)) +- refactor: use object.assign where possible ([#510](https://github.com/googleapis/nodejs-storage/pull/510)) +- chore: drop contributors from multiple places ([#511](https://github.com/googleapis/nodejs-storage/pull/511)) +- chore: use latest npm on Windows ([#509](https://github.com/googleapis/nodejs-storage/pull/509)) + +## v2.3.0 + +### Implementation Changes +- fix(types): Fixes getSignedUrl Return Type ([#496](https://github.com/googleapis/nodejs-storage/pull/496)) +- +### New Features +- Introduce Object Lifecycle Management ([#471](https://github.com/googleapis/nodejs-storage/pull/471)) + +### Dependencies +- chore(deps): update dependency eslint-plugin-node to v8 ([#490](https://github.com/googleapis/nodejs-storage/pull/490)) + +### Internal / Testing Changes +- chore: update issue templates ([#488](https://github.com/googleapis/nodejs-storage/pull/488)) + +## v2.2.0 + +### Bug Fixes +- fix: re-enable typescript types ([#484](https://github.com/googleapis/nodejs-storage/pull/484)) + +### Dependencies +- fix(deps): update dependency @google-cloud/common to ^0.26.0 (edited) ([#480](https://github.com/googleapis/nodejs-storage/pull/480)) +- chore: Remove 'is' dependency ([#462](https://github.com/googleapis/nodejs-storage/pull/462)) +- chore: upgrade teeny-request to 3.11.0 with type definitions ([#457](https://github.com/googleapis/nodejs-storage/pull/457)) +- feat: use small HTTP dependency ([#416](https://github.com/googleapis/nodejs-storage/pull/416)) + +### Documentation +- docs: Minor docs correction ([#465](https://github.com/googleapis/nodejs-storage/pull/465)) + +### Internal / Testing Changes +- chore: remove old issue template ([#485](https://github.com/googleapis/nodejs-storage/pull/485)) +- chore(typescript): enable noImplicitAny ([#483](https://github.com/googleapis/nodejs-storage/pull/483)) +- chore(typescript): improve typescript types and update tests ([#482](https://github.com/googleapis/nodejs-storage/pull/482)) +- build: run tests on node11 ([#481](https://github.com/googleapis/nodejs-storage/pull/481)) +- chores(build): do not collect sponge.xml from windows builds ([#478](https://github.com/googleapis/nodejs-storage/pull/478)) +- chores(build): run codecov on continuous builds ([#476](https://github.com/googleapis/nodejs-storage/pull/476)) +- chore: update new issue template ([#475](https://github.com/googleapis/nodejs-storage/pull/475)) +- fix: enable noImplicitAny for src/bucket.ts ([#472](https://github.com/googleapis/nodejs-storage/pull/472)) +- fix(tests): use unique prefix for system tests to avoid collision with another run ([#468](https://github.com/googleapis/nodejs-storage/pull/468)) +- fix: improve the types ([#467](https://github.com/googleapis/nodejs-storage/pull/467)) +- chore: move class Storage to storage.ts, create index.ts that contains all exports ([#464](https://github.com/googleapis/nodejs-storage/pull/464)) +- chore: add types to many unit tests ([#463](https://github.com/googleapis/nodejs-storage/pull/463)) +- fix: Annotate Iam types ([#461](https://github.com/googleapis/nodejs-storage/pull/461)) +- fix: complete bucket.ts noImplicitAny ([#460](https://github.com/googleapis/nodejs-storage/pull/460)) +- fix: improve the types on acl.ts ([#459](https://github.com/googleapis/nodejs-storage/pull/459)) +- fix: improve types (7) ([#458](https://github.com/googleapis/nodejs-storage/pull/458)) +- fix: improve the types ([#453](https://github.com/googleapis/nodejs-storage/pull/453)) +- chore: update build config ([#455](https://github.com/googleapis/nodejs-storage/pull/455)) +- fix: improve typescript types in src/file.ts ([#450](https://github.com/googleapis/nodejs-storage/pull/450)) +- build: fix codecov uploading on Kokoro ([#451](https://github.com/googleapis/nodejs-storage/pull/451)) +- test: Attempt to re-enable iam#testPermissions ([#429](https://github.com/googleapis/nodejs-storage/pull/429)) +- chore(deps): update dependency sinon to v7 ([#449](https://github.com/googleapis/nodejs-storage/pull/449)) +- Re-generate library using /synth.py ([#448](https://github.com/googleapis/nodejs-storage/pull/448)) +- Correct parameter name. ([#446](https://github.com/googleapis/nodejs-storage/pull/446)) + +## v2.1.0 + +This release brings support for Bucket/Object lock operations, as well as disable TypeScript as we continue to annotate the project with types. + +### New Features +- feat: Support Bucket/Object lock operations ([#374](https://github.com/googleapis/nodejs-storage/pull/374)) + +### Implementation Changes +- disable types for now ([#392](https://github.com/googleapis/nodejs-storage/pull/392)) +- Don't publish sourcemaps ([#412](https://github.com/googleapis/nodejs-storage/pull/412)) +#### TypeScript support (in progress) +- fix: add better types for file.ts ([#436](https://github.com/googleapis/nodejs-storage/pull/436)) +- fix: use ~ for typescript (and fix compile errors) ([#426](https://github.com/googleapis/nodejs-storage/pull/426)) +- fix: Add typing for File#download() ([#409](https://github.com/googleapis/nodejs-storage/pull/409)) +- chore: convert system tests to typescript ([#424](https://github.com/googleapis/nodejs-storage/pull/424)) +- Improve TypeScript types (part 4) ([#402](https://github.com/googleapis/nodejs-storage/pull/402)) +- ts: convert jsdoc types to typescript interfaces (1) ([#383](https://github.com/googleapis/nodejs-storage/pull/383)) +- fix: TS definition ([#387](https://github.com/googleapis/nodejs-storage/pull/387)) +- Annotate types [#3](https://github.com/googleapis/nodejs-storage/pull/3) ([#391](https://github.com/googleapis/nodejs-storage/pull/391)) +- Annotate types (2) ([#388](https://github.com/googleapis/nodejs-storage/pull/388)) + +### Dependencies +- chore(deps): update dependency eslint-plugin-prettier to v3 ([#419](https://github.com/googleapis/nodejs-storage/pull/419)) + +### Documentation +- docs: Modify source location for templates ([#410](https://github.com/googleapis/nodejs-storage/pull/410)) +- docs: Explain `Bucket#upload()` still exists ([#421](https://github.com/googleapis/nodejs-storage/pull/421)) + +### Internal / Testing Changes +- fix(tests): fix system tests on CircleCI ([#431](https://github.com/googleapis/nodejs-storage/pull/431)) +- fix(tests): system-test compiles to ./build, fix relative path ([#428](https://github.com/googleapis/nodejs-storage/pull/428)) +- Update kokoro config ([#425](https://github.com/googleapis/nodejs-storage/pull/425)) +- chore(samples): convert samples to async/await ([#422](https://github.com/googleapis/nodejs-storage/pull/422)) +- build: samples test by adding approprate test variables ([#423](https://github.com/googleapis/nodejs-storage/pull/423)) +- build: bring in latest kokoro cfgs to run System tests on PRs ([#413](https://github.com/googleapis/nodejs-storage/pull/413)) +- test: remove appveyor config ([#411](https://github.com/googleapis/nodejs-storage/pull/411)) +- Enable prefer-const in the eslint config ([#404](https://github.com/googleapis/nodejs-storage/pull/404)) +- fix(test): instantiate PubSub using new ([#403](https://github.com/googleapis/nodejs-storage/pull/403)) +- fix: optionsOrCallback could be undefined if not given, check before assign ([#401](https://github.com/googleapis/nodejs-storage/pull/401)) +- Fix the requesterPays methods ([#400](https://github.com/googleapis/nodejs-storage/pull/400)) +- Enable no-var in eslint ([#398](https://github.com/googleapis/nodejs-storage/pull/398)) +- samples: don't use USA formatted dates for expiry ([#396](https://github.com/googleapis/nodejs-storage/pull/396)) +- fix: copy(): Use correct destination file name in URI ([#389](https://github.com/googleapis/nodejs-storage/pull/389)) + +## v2.0.3 + +### Implementation Changes +- Improve TypeScript types ([#381](https://github.com/googleapis/nodejs-storage/pull/381)) +- Make some parameters optional ([#380](https://github.com/googleapis/nodejs-storage/pull/380)) + +## v2.0.2 + +### Implementation Changes +- Improve the types (#377) + +## v2.0.1 + +**This fixes types declaration issues with projects using TypeScript.** + +### Implementation Changes +- Enable noImplicitThis in the tsconfig ([#370](https://github.com/googleapis/nodejs-storage/pull/370)) +- Fix the path to the d.ts ([#364](https://github.com/googleapis/nodejs-storage/pull/364)) +- fix: make dependency on request explicit ([#361](https://github.com/googleapis/nodejs-storage/pull/361)) +- fix: remove trailing slashes from bucket name. ([#266](https://github.com/googleapis/nodejs-storage/pull/266)) + +### Dependencies +- fix(deps): update dependency @google-cloud/common to ^0.24.0 ([#367](https://github.com/googleapis/nodejs-storage/pull/367)) +- fix(deps): update dependency gcs-resumable-upload to ^0.13.0 ([#368](https://github.com/googleapis/nodejs-storage/pull/368)) +- Remove unused dependencies ([#363](https://github.com/googleapis/nodejs-storage/pull/363)) +- Remove safe-buffer ([#359](https://github.com/googleapis/nodejs-storage/pull/359)) +- samples: update dependency @google-cloud/storage to v2 ([#350](https://github.com/googleapis/nodejs-storage/pull/350)) + +### Internal / Testing Changes +- Update CI config ([#371](https://github.com/googleapis/nodejs-storage/pull/371)) +- build(kokoro): run docker as user node ([#358](https://github.com/googleapis/nodejs-storage/pull/358)) +- build: fix multiline in circle.yml ([#357](https://github.com/googleapis/nodejs-storage/pull/357)) +- fix executable modes on .sh's; add pre-system-test.sh hook ([#356](https://github.com/googleapis/nodejs-storage/pull/356)) +- decrypt both service account keys ([#353](https://github.com/googleapis/nodejs-storage/pull/353)) +- Retry npm install in CI ([#352](https://github.com/googleapis/nodejs-storage/pull/352)) +- Add synth script and run it ([#351](https://github.com/googleapis/nodejs-storage/pull/351)) + +## v2.0.0 + +**This release has breaking changes**. This release has a few notable breaking changes. Please take care when upgrading! + +### require syntax changes +The import style of this library has been changed to support [es module](https://nodejs.org/api/esm.html) syntax. This provides both forward compatibility with es modules, and better supports the TypeScript and Babel ecosystems. As a result, the import syntax has changed: + +#### Old Code +```js +const storage = require('@google-cloud/storage')(); +// or... +const Storage = require('@google-cloud/storage'); +const storage = new Storage({ + // config... +}); +``` + +#### New Code +```js +const {Storage} = require('@google-cloud/storage'); +const storage = new Storage({ + // config... +}); +``` + +### `bucket.upload` no longer accepts URLs +To better support a variety of HTTP clients, the remote fetching functionality of `bucket.upload` has been removed. It can be replaced with your favorite HTTP client. + +#### Old Code +```js +bucket.upload('https://example.com/images/image.png', function(err, file, res) { + // handle upload... +}); +``` + +#### New Code + +```js +const request = require('request'); +const file = bucket.file(name); +const writeStream = file.createWriteStream(); +request(url).pipe(writeStream); +``` + +### Breaking changes +- semver: do not support upload() from url (#337) +- fix: drop support for node.js 4.x and 9.x (#282) + +### Features +- refactor(ts): merge initial TypeScript conversion (#334) +- feat: Add Storage#getServiceAccount(). (#331) +- Kms sample (#209) + +### Bug fixes +- fix: gzip and Cache-Control headers in upload sample (#225) +- fix: move this.[ROLE]s initialization from Acl to AclAccessorRoleMethods (#252) +- fix: signedURL cname (#210) (#234) + +### Internal / Testing Changes +- chore(deps): update dependency nyc to v13 (#341) +- fix(deps): update dependency @google-cloud/common to ^0.23.0 (#340) +- test: throw on deprecation (#319) +- chore(deps): update dependency eslint-config-prettier to v3 (#336) +- fix(deps): update dependency gcs-resumable-upload to ^0.12.0 (#317) +- Fix system tests for string comparisons (#328) +- chore: ignore package-lock.json (#326) +- chore: update renovate config (#322) +- chore: regen lock files (#318) +- chore(deps): lock file maintenance (#313) +- chore: move mocha options to mocha.opts (#311) +- chore(deps): lock file maintenance (#309) +- test: use strictEqual in tests (#306) +- chore(deps): update dependency eslint-plugin-node to v7 (#305) +- chore(deps): lock file maintenance (#303) +- chore(deps): lock file maintenance (#285) +- fix: test meant to assert err msg exists (#280) +- fix(deps): update dependency yargs to v12 (#270) +- fix(deps): update dependency uuid to v3.3.2 (#269) +- chore: update gcs-resumable-upload to 0.11.1 (#265) +- fix(deps): update dependency uuid to v3.3.0 (#262) +- chore(deps): update dependency sinon to v6 (#263) +- Configure Renovate (#250) +- refactor: drop repo-tool as an exec wrapper (#258) +- chore: update sample lockfiles (#256) +- fix: update linking for samples (#254) +- chore(package): update eslint to version 5.0.0 (#253) +- refactor(es6): Refactor constructor pattern as ES6 class (#246) +- Update @google-cloud/common to the latest version 🚀 (#226) +- system-tests: fix channel test. (#243) +- refactor: Update to the latest version of nodejs-common and gcs-resumable-upload (#202) +- Fix permission of bash script for Kokoro (#223) +- chore(package): update nyc to version 12.0.2 (#216) +- chore: fix prettier incompatibility (#211) diff --git a/handwritten/storage/CODE_OF_CONDUCT.md b/handwritten/storage/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..2add2547a81 --- /dev/null +++ b/handwritten/storage/CODE_OF_CONDUCT.md @@ -0,0 +1,94 @@ + +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/handwritten/storage/CONTRIBUTING.md b/handwritten/storage/CONTRIBUTING.md new file mode 100644 index 00000000000..72c44cada5e --- /dev/null +++ b/handwritten/storage/CONTRIBUTING.md @@ -0,0 +1,74 @@ +# How to become a contributor and submit your own code + +**Table of contents** + +* [Contributor License Agreements](#contributor-license-agreements) +* [Contributing a patch](#contributing-a-patch) +* [Running the tests](#running-the-tests) +* [Releasing the library](#releasing-the-library) + +## Contributor License Agreements + +We'd love to accept your sample apps and patches! Before we can take them, we +have to jump a couple of legal hurdles. + +Please fill out either the individual or corporate Contributor License Agreement +(CLA). + + * If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). + * If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). + +Follow either of the two links above to access the appropriate CLA and +instructions for how to sign and return it. Once we receive it, we'll be able to +accept your pull requests. + +## Contributing A Patch + +1. Submit an issue describing your proposed change to the repo in question. +1. The repo owner will respond to your issue promptly. +1. If your proposed change is accepted, and you haven't already done so, sign a + Contributor License Agreement (see details above). +1. Fork the desired repo, develop and test your code changes. +1. Ensure that your code adheres to the existing style in the code to which + you are contributing. +1. Ensure that your code has an appropriate set of tests which all pass. +1. Title your pull request following [Conventional Commits](https://www.conventionalcommits.org/) styling. +1. Submit a pull request. + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Set up authentication with a service account][auth] so you can access the + API from your local workstation. + + +## Running the tests + +1. [Prepare your environment for Node.js setup][setup]. + +1. Install dependencies: + + npm install + +1. Run the tests: + + # Run unit tests. + npm test + + # Run sample integration tests. + npm run samples-test + + # Run all system tests. + npm run system-test + +1. Lint (and maybe fix) any changes: + + npm run fix + +[setup]: https://cloud.google.com/nodejs/docs/setup +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/getting-started \ No newline at end of file diff --git a/handwritten/storage/LICENSE b/handwritten/storage/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/handwritten/storage/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/handwritten/storage/README.md b/handwritten/storage/README.md new file mode 100644 index 00000000000..ea2c8dc0d8a --- /dev/null +++ b/handwritten/storage/README.md @@ -0,0 +1,302 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Google Cloud Storage: Node.js Client](https://github.com/googleapis/nodejs-storage) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/@google-cloud/storage.svg)](https://www.npmjs.com/package/@google-cloud/storage) + + + + +> Node.js idiomatic client for [Cloud Storage][product-docs]. + +[Cloud Storage](https://cloud.google.com/storage/docs) allows world-wide +storage and retrieval of any amount of data at any time. You can use Google +Cloud Storage for a range of scenarios including serving website content, +storing data for archival and disaster recovery, or distributing large data +objects to users via direct download. + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/nodejs-storage/blob/main/CHANGELOG.md). + +* [Google Cloud Storage Node.js Client API Reference][client-docs] +* [Google Cloud Storage Documentation][product-docs] +* [github.com/googleapis/nodejs-storage](https://github.com/googleapis/nodejs-storage) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + * [Before you begin](#before-you-begin) + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Before you begin + +1. [Select or create a Cloud Platform project][projects]. +1. [Enable billing for your project][billing]. +1. [Enable the Google Cloud Storage API][enable_api]. +1. [Set up authentication][auth] so you can access the + API from your local workstation. + +### Installing the client library + +```bash +npm install @google-cloud/storage +``` + + +### Using the client library + +```javascript +// Imports the Google Cloud client library +const {Storage} = require('@google-cloud/storage'); + +// For more information on ways to initialize Storage, please see +// https://googleapis.dev/nodejs/storage/latest/Storage.html + +// Creates a client using Application Default Credentials +const storage = new Storage(); + +// Creates a client from a Google service account key +// const storage = new Storage({keyFilename: 'key.json'}); + +/** + * TODO(developer): Uncomment these variables before running the sample. + */ +// The ID of your GCS bucket +// const bucketName = 'your-unique-bucket-name'; + +async function createBucket() { + // Creates the new bucket + await storage.createBucket(bucketName); + console.log(`Bucket ${bucketName} created.`); +} + +createBucket().catch(console.error); + +``` + + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/nodejs-storage/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Add Bucket Conditional Binding | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketConditionalBinding.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketConditionalBinding.js,samples/README.md) | +| Add Bucket Default Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketDefaultOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketDefaultOwnerAcl.js,samples/README.md) | +| Add Bucket Iam Member | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketIamMember.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketIamMember.js,samples/README.md) | +| Storage Add Bucket Label. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketLabel.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketLabel.js,samples/README.md) | +| Add Bucket Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketOwnerAcl.js,samples/README.md) | +| Bucket Website Configuration. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addBucketWebsiteConfiguration.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addBucketWebsiteConfiguration.js,samples/README.md) | +| Add File Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/addFileOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/addFileOwnerAcl.js,samples/README.md) | +| Storage Get Bucket Metadata. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/bucketMetadata.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/bucketMetadata.js,samples/README.md) | +| Change Bucket's Default Storage Class. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/changeDefaultStorageClass.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/changeDefaultStorageClass.js,samples/README.md) | +| Storage File Convert CSEK to CMEK. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/changeFileCSEKToCMEK.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/changeFileCSEKToCMEK.js,samples/README.md) | +| Storage Combine files. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/composeFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/composeFile.js,samples/README.md) | +| Storage Configure Bucket Cors. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/configureBucketCors.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/configureBucketCors.js,samples/README.md) | +| Configure Retries | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/configureRetries.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/configureRetries.js,samples/README.md) | +| Copy File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/copyFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/copyFile.js,samples/README.md) | +| Copy Old Version Of File. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/copyOldVersionOfFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/copyOldVersionOfFile.js,samples/README.md) | +| Create a Dual-Region Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithDualRegion.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithDualRegion.js,samples/README.md) | +| Create a hierarchical namespace enabled bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithHierarchicalNamespace.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithHierarchicalNamespace.js,samples/README.md) | +| Create a Bucket with object retention enabled. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithObjectRetention.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithObjectRetention.js,samples/README.md) | +| Create Bucket With Storage Class and Location. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithStorageClassAndLocation.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithStorageClassAndLocation.js,samples/README.md) | +| Create Bucket With Turbo Replication | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createBucketWithTurboReplication.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createBucketWithTurboReplication.js,samples/README.md) | +| Create New Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createNewBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createNewBucket.js,samples/README.md) | +| Create Notification | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/createNotification.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/createNotification.js,samples/README.md) | +| Delete Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/deleteBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/deleteBucket.js,samples/README.md) | +| Delete File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/deleteFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/deleteFile.js,samples/README.md) | +| Delete Notification | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/deleteNotification.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/deleteNotification.js,samples/README.md) | +| Delete Old Version Of File. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/deleteOldVersionOfFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/deleteOldVersionOfFile.js,samples/README.md) | +| Disable Bucket Lifecycle Management | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableBucketLifecycleManagement.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableBucketLifecycleManagement.js,samples/README.md) | +| Storage Disable Bucket Versioning. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableBucketVersioning.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableBucketVersioning.js,samples/README.md) | +| Disable Default Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableDefaultEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableDefaultEventBasedHold.js,samples/README.md) | +| Disable Requester Pays | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableRequesterPays.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableRequesterPays.js,samples/README.md) | +| Disable Soft Delete | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableSoftDelete.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableSoftDelete.js,samples/README.md) | +| Disable Uniform Bucket Level Access | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/disableUniformBucketLevelAccess.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/disableUniformBucketLevelAccess.js,samples/README.md) | +| Download Byte Range | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadByteRange.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadByteRange.js,samples/README.md) | +| Download Encrypted File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadEncryptedFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadEncryptedFile.js,samples/README.md) | +| Download File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadFile.js,samples/README.md) | +| Download a File in Chunks With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadFileInChunksWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadFileInChunksWithTransferManager.js,samples/README.md) | +| Download File Using Requester Pays | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadFileUsingRequesterPays.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadFileUsingRequesterPays.js,samples/README.md) | +| Download Folder With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadFolderWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadFolderWithTransferManager.js,samples/README.md) | +| Download Into Memory | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadIntoMemory.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadIntoMemory.js,samples/README.md) | +| Download Many Files With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadManyFilesWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadManyFilesWithTransferManager.js,samples/README.md) | +| Storage Download Public File. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/downloadPublicFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/downloadPublicFile.js,samples/README.md) | +| Enable Bucket Lifecycle Management | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableBucketLifecycleManagement.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableBucketLifecycleManagement.js,samples/README.md) | +| Storage Enable Bucket Versioning. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableBucketVersioning.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableBucketVersioning.js,samples/README.md) | +| Enable Default Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableDefaultEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableDefaultEventBasedHold.js,samples/README.md) | +| Enable Default KMS Key | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableDefaultKMSKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableDefaultKMSKey.js,samples/README.md) | +| Enable Requester Pays | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableRequesterPays.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableRequesterPays.js,samples/README.md) | +| Enable Uniform Bucket Level Access | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/enableUniformBucketLevelAccess.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/enableUniformBucketLevelAccess.js,samples/README.md) | +| Change File's Storage Class. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/fileChangeStorageClass.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/fileChangeStorageClass.js,samples/README.md) | +| Storage Set File Metadata. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/fileSetMetadata.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/fileSetMetadata.js,samples/README.md) | +| Generate Encryption Key | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateEncryptionKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateEncryptionKey.js,samples/README.md) | +| Generate Signed Url | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateSignedUrl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateSignedUrl.js,samples/README.md) | +| Generate V4 Read Signed Url | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateV4ReadSignedUrl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateV4ReadSignedUrl.js,samples/README.md) | +| Generate V4 Signed Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateV4SignedPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateV4SignedPolicy.js,samples/README.md) | +| Generate V4 Upload Signed Url | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/generateV4UploadSignedUrl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/generateV4UploadSignedUrl.js,samples/README.md) | +| Get Autoclass | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getAutoclass.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getAutoclass.js,samples/README.md) | +| Get Default Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getDefaultEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getDefaultEventBasedHold.js,samples/README.md) | +| Get Metadata | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getMetadata.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getMetadata.js,samples/README.md) | +| Get Metadata Notifications | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getMetadataNotifications.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getMetadataNotifications.js,samples/README.md) | +| Get Public Access Prevention | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getPublicAccessPrevention.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getPublicAccessPrevention.js,samples/README.md) | +| Get RPO | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getRPO.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getRPO.js,samples/README.md) | +| Get Requester Pays Status | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getRequesterPaysStatus.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getRequesterPaysStatus.js,samples/README.md) | +| Get Retention Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getRetentionPolicy.js,samples/README.md) | +| Storage Get Service Account. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getServiceAccount.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getServiceAccount.js,samples/README.md) | +| Get Soft Delete Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getSoftDeletePolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getSoftDeletePolicy.js,samples/README.md) | +| Get Soft Deleted Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getSoftDeletedBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getSoftDeletedBucket.js,samples/README.md) | +| Get Uniform Bucket Level Access | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/getUniformBucketLevelAccess.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/getUniformBucketLevelAccess.js,samples/README.md) | +| Activate HMAC SA Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyActivate.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyActivate.js,samples/README.md) | +| Create HMAC SA Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyCreate.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyCreate.js,samples/README.md) | +| Deactivate HMAC SA Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyDeactivate.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyDeactivate.js,samples/README.md) | +| Delete HMAC SA Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyDelete.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyDelete.js,samples/README.md) | +| Get HMAC SA Key Metadata. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeyGet.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeyGet.js,samples/README.md) | +| List HMAC SA Keys Metadata. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/hmacKeysList.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/hmacKeysList.js,samples/README.md) | +| List Buckets | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listBuckets.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listBuckets.js,samples/README.md) | +| List Buckets Partial Success | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listBucketsPartialSuccess.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listBucketsPartialSuccess.js,samples/README.md) | +| List Files | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listFiles.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listFiles.js,samples/README.md) | +| List Files By Prefix | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listFilesByPrefix.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listFilesByPrefix.js,samples/README.md) | +| List Files Paginate | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listFilesPaginate.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listFilesPaginate.js,samples/README.md) | +| List Files with Old Versions. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listFilesWithOldVersions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listFilesWithOldVersions.js,samples/README.md) | +| List Notifications | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listNotifications.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listNotifications.js,samples/README.md) | +| List Soft Deleted Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listSoftDeletedBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listSoftDeletedBucket.js,samples/README.md) | +| List Soft Deleted Object Versions | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listSoftDeletedObjectVersions.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listSoftDeletedObjectVersions.js,samples/README.md) | +| List Soft Deleted Objects | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/listSoftDeletedObjects.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/listSoftDeletedObjects.js,samples/README.md) | +| Lock Retention Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/lockRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/lockRetentionPolicy.js,samples/README.md) | +| Storage Make Bucket Public. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/makeBucketPublic.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/makeBucketPublic.js,samples/README.md) | +| Make Public | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/makePublic.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/makePublic.js,samples/README.md) | +| Move File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/moveFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/moveFile.js,samples/README.md) | +| Move File Atomic | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/moveFileAtomic.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/moveFileAtomic.js,samples/README.md) | +| Print Bucket Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/printBucketAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/printBucketAcl.js,samples/README.md) | +| Print Bucket Acl For User | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/printBucketAclForUser.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/printBucketAclForUser.js,samples/README.md) | +| Print File Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/printFileAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/printFileAcl.js,samples/README.md) | +| Print File Acl For User | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/printFileAclForUser.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/printFileAclForUser.js,samples/README.md) | +| Quickstart | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | +| Release Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/releaseEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/releaseEventBasedHold.js,samples/README.md) | +| Release Temporary Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/releaseTemporaryHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/releaseTemporaryHold.js,samples/README.md) | +| Remove Bucket Conditional Binding | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketConditionalBinding.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketConditionalBinding.js,samples/README.md) | +| Storage Remove Bucket Cors Configuration. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketCors.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketCors.js,samples/README.md) | +| Remove Bucket Default Owner | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketDefaultOwner.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketDefaultOwner.js,samples/README.md) | +| Remove Bucket Iam Member | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketIamMember.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketIamMember.js,samples/README.md) | +| Storage Remove Bucket Label. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketLabel.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketLabel.js,samples/README.md) | +| Remove Bucket Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeBucketOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeBucketOwnerAcl.js,samples/README.md) | +| Remove Default KMS Key. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeDefaultKMSKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeDefaultKMSKey.js,samples/README.md) | +| Remove File Owner Acl | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeFileOwnerAcl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeFileOwnerAcl.js,samples/README.md) | +| Remove Retention Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/removeRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/removeRetentionPolicy.js,samples/README.md) | +| Rename File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/renameFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/renameFile.js,samples/README.md) | +| Restore Soft Deleted Bucket | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/restoreSoftDeletedBucket.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/restoreSoftDeletedBucket.js,samples/README.md) | +| Restore Soft Deleted Object | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/restoreSoftDeletedObject.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/restoreSoftDeletedObject.js,samples/README.md) | +| Rotate Encryption Key | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/rotateEncryptionKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/rotateEncryptionKey.js,samples/README.md) | +| Set Autoclass | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setAutoclass.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setAutoclass.js,samples/README.md) | +| Set Client Endpoint | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setClientEndpoint.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setClientEndpoint.js,samples/README.md) | +| Set Event Based Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setEventBasedHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setEventBasedHold.js,samples/README.md) | +| Set the object retention policy of a File. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setObjectRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setObjectRetentionPolicy.js,samples/README.md) | +| Set Public Access Prevention Enforced | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setPublicAccessPreventionEnforced.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setPublicAccessPreventionEnforced.js,samples/README.md) | +| Set Public Access Prevention Inherited | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setPublicAccessPreventionInherited.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setPublicAccessPreventionInherited.js,samples/README.md) | +| Set RPO Async Turbo | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setRPOAsyncTurbo.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setRPOAsyncTurbo.js,samples/README.md) | +| Set RPO Default | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setRPODefault.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setRPODefault.js,samples/README.md) | +| Set Retention Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setRetentionPolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setRetentionPolicy.js,samples/README.md) | +| Set Soft Delete Policy | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setSoftDeletePolicy.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setSoftDeletePolicy.js,samples/README.md) | +| Set Temporary Hold | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/setTemporaryHold.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/setTemporaryHold.js,samples/README.md) | +| Stream File Download | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/streamFileDownload.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/streamFileDownload.js,samples/README.md) | +| Stream File Upload | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/streamFileUpload.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/streamFileUpload.js,samples/README.md) | +| Upload a directory to a bucket. | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadDirectory.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadDirectory.js,samples/README.md) | +| Upload Directory With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadDirectoryWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadDirectoryWithTransferManager.js,samples/README.md) | +| Upload Encrypted File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadEncryptedFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadEncryptedFile.js,samples/README.md) | +| Upload File | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadFile.js,samples/README.md) | +| Upload a File in Chunks With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFileInChunksWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadFileInChunksWithTransferManager.js,samples/README.md) | +| Upload File With Kms Key | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFileWithKmsKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadFileWithKmsKey.js,samples/README.md) | +| Upload From Memory | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadFromMemory.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadFromMemory.js,samples/README.md) | +| Upload Many Files With Transfer Manager | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadManyFilesWithTransferManager.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadManyFilesWithTransferManager.js,samples/README.md) | +| Upload Without Authentication | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadWithoutAuthentication.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadWithoutAuthentication.js,samples/README.md) | +| Upload Without Authentication Signed Url | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/uploadWithoutAuthenticationSignedUrl.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/uploadWithoutAuthenticationSignedUrl.js,samples/README.md) | +| View Bucket Iam Members | [source code](https://github.com/googleapis/nodejs-storage/blob/main/samples/viewBucketIamMembers.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-storage&page=editor&open_in_editor=samples/viewBucketIamMembers.js,samples/README.md) | + + + +The [Google Cloud Storage Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install @google-cloud/storage@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-storage/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/nodejs-storage/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/storage/latest +[product-docs]: https://cloud.google.com/storage +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing +[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=storage-api.googleapis.com +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/handwritten/storage/conformance-test/conformanceCommon.ts b/handwritten/storage/conformance-test/conformanceCommon.ts new file mode 100644 index 00000000000..65da9293811 --- /dev/null +++ b/handwritten/storage/conformance-test/conformanceCommon.ts @@ -0,0 +1,235 @@ +/*! + * Copyright 2021 Google LLC. All Rights Reserved. + * + * 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 * as jsonToNodeApiMapping from './test-data/retryInvocationMap.json'; +import * as libraryMethods from './libraryMethods'; +import {Bucket, File, HmacKey, Notification, Storage} from '../src/'; +import * as uuid from 'uuid'; +import * as assert from 'assert'; +import {DecorateRequestOptions} from '../src/nodejs-common'; +import fetch from 'node-fetch'; + +interface RetryCase { + instructions: String[]; +} + +interface Method { + name: String; + resources: String[]; + group?: String; +} + +export interface RetryTestCase { + id: number; + description: String; + cases: RetryCase[]; + methods: Method[]; + preconditionProvided: boolean; + expectSuccess: boolean; +} + +interface ConformanceTestCreationResult { + id: string; +} + +interface ConformanceTestResult { + completed: boolean; +} + +type LibraryMethodsModuleType = typeof import('./libraryMethods'); +const methodMap: Map = new Map( + Object.entries(jsonToNodeApiMapping) +); + +const DURATION_SECONDS = 600; // 10 mins. +const TESTS_PREFIX = `storage.retry.tests.${shortUUID()}.`; +const TESTBENCH_HOST = + process.env.STORAGE_EMULATOR_HOST || 'http://localhost:9000/'; +const CONF_TEST_PROJECT_ID = 'my-project-id'; +const TIMEOUT_FOR_INDIVIDUAL_TEST = 20000; +const RETRY_MULTIPLIER_FOR_CONFORMANCE_TESTS = 0.01; + +export function executeScenario(testCase: RetryTestCase) { + for ( + let instructionNumber = 0; + instructionNumber < testCase.cases.length; + instructionNumber++ + ) { + const instructionSet: RetryCase = testCase.cases[instructionNumber]; + testCase.methods.forEach(async jsonMethod => { + const functionList = + jsonMethod?.group !== undefined + ? methodMap.get(jsonMethod?.group) + : methodMap.get(jsonMethod?.name); + functionList?.forEach(storageMethodString => { + const storageMethodObject = + libraryMethods[storageMethodString as keyof LibraryMethodsModuleType]; + let bucket: Bucket; + let file: File; + let notification: Notification; + let creationResult: {id: string}; + let storage: Storage; + let hmacKey: HmacKey; + + describe(`${storageMethodString}`, async () => { + beforeEach(async () => { + storage = new Storage({ + apiEndpoint: TESTBENCH_HOST, + projectId: CONF_TEST_PROJECT_ID, + retryOptions: { + retryDelayMultiplier: RETRY_MULTIPLIER_FOR_CONFORMANCE_TESTS, + }, + }); + creationResult = await createTestBenchRetryTest( + instructionSet.instructions, + jsonMethod?.name.toString() + ); + if (storageMethodString.includes('InstancePrecondition')) { + bucket = await createBucketForTest( + storage, + testCase.preconditionProvided, + storageMethodString + ); + file = await createFileForTest( + testCase.preconditionProvided, + storageMethodString, + bucket + ); + } else { + bucket = await createBucketForTest( + storage, + false, + storageMethodString + ); + file = await createFileForTest( + false, + storageMethodString, + bucket + ); + } + notification = bucket.notification(`${TESTS_PREFIX}`); + await notification.create(); + + [hmacKey] = await storage.createHmacKey( + `${TESTS_PREFIX}@email.com` + ); + + storage.interceptors.push({ + request: requestConfig => { + requestConfig.headers = requestConfig.headers || {}; + Object.assign(requestConfig.headers, { + 'x-retry-test-id': creationResult.id, + }); + return requestConfig as DecorateRequestOptions; + }, + }); + }); + + it(`${instructionNumber}`, async () => { + const methodParameters: libraryMethods.ConformanceTestOptions = { + bucket: bucket, + file: file, + notification: notification, + storage: storage, + hmacKey: hmacKey, + }; + if (testCase.preconditionProvided) { + methodParameters.preconditionRequired = true; + } + if (testCase.expectSuccess) { + assert.ifError(await storageMethodObject(methodParameters)); + } else { + await assert.rejects(storageMethodObject(methodParameters)); + } + const testBenchResult = await getTestBenchRetryTest( + creationResult.id + ); + assert.strictEqual(testBenchResult.completed, true); + }).timeout(TIMEOUT_FOR_INDIVIDUAL_TEST); + }); + }); + }); + } +} + +async function createBucketForTest( + storage: Storage, + preconditionShouldBeOnInstance: boolean, + storageMethodString: String +) { + const name = generateName(storageMethodString, 'bucket'); + const bucket = storage.bucket(name); + await bucket.create(); + await bucket.setRetentionPeriod(DURATION_SECONDS); + + if (preconditionShouldBeOnInstance) { + return new Bucket(storage, bucket.name, { + preconditionOpts: { + ifMetagenerationMatch: 2, + }, + }); + } + return bucket; +} + +async function createFileForTest( + preconditionShouldBeOnInstance: boolean, + storageMethodString: String, + bucket: Bucket +) { + const name = generateName(storageMethodString, 'file'); + const file = bucket.file(name); + await file.save(name); + if (preconditionShouldBeOnInstance) { + return new File(bucket, file.name, { + preconditionOpts: { + ifMetagenerationMatch: file.metadata.metageneration, + ifGenerationMatch: file.metadata.generation, + }, + }); + } + return file; +} + +function generateName(storageMethodString: String, bucketOrFile: string) { + return `${TESTS_PREFIX}${storageMethodString.toLowerCase()}${bucketOrFile}.${shortUUID()}`; +} + +async function createTestBenchRetryTest( + instructions: String[], + methodName: string +): Promise { + const requestBody = {instructions: {[methodName]: instructions}}; + const response = await fetch(`${TESTBENCH_HOST}retry_test`, { + method: 'POST', + body: JSON.stringify(requestBody), + headers: {'Content-Type': 'application/json'}, + }); + return response.json() as Promise; +} + +async function getTestBenchRetryTest( + testId: string +): Promise { + const response = await fetch(`${TESTBENCH_HOST}retry_test/${testId}`, { + method: 'GET', + }); + + return response.json() as Promise; +} + +function shortUUID() { + return uuid.v1().split('-').shift(); +} diff --git a/handwritten/storage/conformance-test/fixtures/signing-service-account.json b/handwritten/storage/conformance-test/fixtures/signing-service-account.json new file mode 100644 index 00000000000..5fdc01240ef --- /dev/null +++ b/handwritten/storage/conformance-test/fixtures/signing-service-account.json @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "dummy-project-id", + "private_key_id": "ffffffffffffffffffffffffffffffffffffffff", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCsPzMirIottfQ2\nryjQmPWocSEeGo7f7Q4/tMQXHlXFzo93AGgU2t+clEj9L5loNhLVq+vk+qmnyDz5\nQ04y8jVWyMYzzGNNrGRW/yaYqnqlKZCy1O3bmnNjV7EDbC/jE1ZLBY0U3HaSHfn6\nS9ND8MXdgD0/ulRTWwq6vU8/w6i5tYsU7n2LLlQTl1fQ7/emO9nYcCFJezHZVa0H\nmeWsdHwWsok0skwQYQNIzP3JF9BpR5gJT2gNge6KopDesJeLoLzaX7cUnDn+CAnn\nLuLDwwSsIVKyVxhBFsFXPplgpaQRwmGzwEbf/Xpt9qo26w2UMgn30jsOaKlSeAX8\ncS6ViF+tAgMBAAECggEACKRuJCP8leEOhQziUx8Nmls8wmYqO4WJJLyk5xUMUC22\nSI4CauN1e0V8aQmxnIc0CDkFT7qc9xBmsMoF+yvobbeKrFApvlyzNyM7tEa/exh8\nDGD/IzjbZ8VfWhDcUTwn5QE9DCoon9m1sG+MBNlokB3OVOt8LieAAREdEBG43kJu\nyQTOkY9BGR2AY1FnAl2VZ/jhNDyrme3tp1sW1BJrawzR7Ujo8DzlVcS2geKA9at7\n55ua5GbHz3hfzFgjVXDfnkWzId6aHypUyqHrSn1SqGEbyXTaleKTc6Pgv0PgkJjG\nhZazWWdSuf1T5Xbs0OhAK9qraoAzT6cXXvMEvvPt6QKBgQDXcZKqJAOnGEU4b9+v\nOdoh+nssdrIOBNMu1m8mYbUVYS1aakc1iDGIIWNM3qAwbG+yNEIi2xi80a2RMw2T\n9RyCNB7yqCXXVKLBiwg9FbKMai6Vpk2bWIrzahM9on7AhCax/X2AeOp+UyYhFEy6\nUFG4aHb8THscL7b515ukSuKb5QKBgQDMq+9PuaB0eHsrmL6q4vHNi3MLgijGg/zu\nAXaPygSYAwYW8KglcuLZPvWrL6OG0+CrfmaWTLsyIZO4Uhdj7MLvX6yK7IMnagvk\nL3xjgxSklEHJAwi5wFeJ8ai/1MIuCn8p2re3CbwISKpvf7Sgs/W4196P4vKvTiAz\njcTiSYFIKQKBgCjMpkS4O0TakMlGTmsFnqyOneLmu4NyIHgfPb9cA4n/9DHKLKAT\noaWxBPgatOVWs7RgtyGYsk+XubHkpC6f3X0+15mGhFwJ+CSE6tN+l2iF9zp52vqP\nQwkjzm7+pdhZbmaIpcq9m1K+9lqPWJRz/3XXuqi+5xWIZ7NaxGvRjqaNAoGAdK2b\nutZ2y48XoI3uPFsuP+A8kJX+CtWZrlE1NtmS7tnicdd19AtfmTuUL6fz0FwfW4Su\nlQZfPT/5B339CaEiq/Xd1kDor+J7rvUHM2+5p+1A54gMRGCLRv92FQ4EON0RC1o9\nm2I4SHysdO3XmjmdXmfp4BsgAKJIJzutvtbqlakCgYB+Cb10z37NJJ+WgjDt+yT2\nyUNH17EAYgWXryfRgTyi2POHuJitd64Xzuy6oBVs3wVveYFM6PIKXlj8/DahYX5I\nR2WIzoCNLL3bEZ+nC6Jofpb4kspoAeRporj29SgesK6QBYWHWX2H645RkRGYGpDo\n51gjy9m/hSNqBbH2zmh04A==\n-----END PRIVATE KEY-----\n", + "client_email": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com", + "client_id": "000000000000000000000", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com" +} \ No newline at end of file diff --git a/handwritten/storage/conformance-test/globalHooks.ts b/handwritten/storage/conformance-test/globalHooks.ts new file mode 100644 index 00000000000..0775b74578e --- /dev/null +++ b/handwritten/storage/conformance-test/globalHooks.ts @@ -0,0 +1,41 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 { + getTestBenchDockerImage, + runTestBenchDockerImage, + stopTestBenchDockerImage, +} from './testBenchUtil'; + +const TIMEOUT_FOR_DOCKER_OPS = 60000; +const TIME_TO_WAIT_FOR_CONTAINER_READY = 10000; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function mochaGlobalSetup(this: any) { + // Increase the timeout for this before block so that the docker images have time to download and run. + this.suite._timeout = TIMEOUT_FOR_DOCKER_OPS; + await getTestBenchDockerImage(); + await runTestBenchDockerImage(); + await new Promise(resolve => + setTimeout(resolve, TIME_TO_WAIT_FOR_CONTAINER_READY) + ); +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function mochaGlobalTeardown(this: any) { + // Increase the timeout for this block so that docker has time to stop the container. + this.suite._timeout = TIMEOUT_FOR_DOCKER_OPS; + await stopTestBenchDockerImage(); +} diff --git a/handwritten/storage/conformance-test/libraryMethods.ts b/handwritten/storage/conformance-test/libraryMethods.ts new file mode 100644 index 00000000000..2dd2e586beb --- /dev/null +++ b/handwritten/storage/conformance-test/libraryMethods.ts @@ -0,0 +1,836 @@ +// Copyright 2021 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 {Bucket, File, Notification, Storage, HmacKey, Policy} from '../src'; +import * as path from 'path'; +import {ApiError} from '../src/nodejs-common'; +import { + createTestBuffer, + createTestFileFromBuffer, + deleteTestFile, +} from './testBenchUtil'; +import * as uuid from 'uuid'; +import {getDirName} from '../src/util.js'; + +const FILE_SIZE_BYTES = 9 * 1024 * 1024; +const CHUNK_SIZE_BYTES = 2 * 1024 * 1024; + +export interface ConformanceTestOptions { + bucket?: Bucket; + file?: File; + notification?: Notification; + storage?: Storage; + hmacKey?: HmacKey; + preconditionRequired?: boolean; +} + +///////////////////////////////////////////////// +//////////////////// BUCKET ///////////////////// +///////////////////////////////////////////////// + +export async function addLifecycleRuleInstancePrecondition( + options: ConformanceTestOptions +) { + await options.bucket!.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + age: 365 * 3, // Specified in days. + }, + }); +} + +export async function addLifecycleRule(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.bucket!.addLifecycleRule( + { + action: { + type: 'Delete', + }, + condition: { + age: 365 * 3, // Specified in days. + }, + }, + { + ifMetagenerationMatch: 2, + } + ); + } else { + await options.bucket!.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + age: 365 * 3, // Specified in days. + }, + }); + } +} + +export async function combineInstancePrecondition( + options: ConformanceTestOptions +) { + const file1 = options.bucket!.file('file1.txt'); + const file2 = options.bucket!.file('file2.txt'); + await file1.save('file1 contents'); + await file2.save('file2 contents'); + let allFiles; + const sources = [file1, file2]; + if (options.preconditionRequired) { + allFiles = options.bucket!.file('all-files.txt', { + preconditionOpts: { + ifGenerationMatch: 0, + }, + }); + } else { + allFiles = options.bucket!.file('all-files.txt'); + } + + await options.bucket!.combine(sources, allFiles); +} + +export async function combine(options: ConformanceTestOptions) { + const file1 = options.bucket!.file('file1.txt'); + const file2 = options.bucket!.file('file2.txt'); + await file1.save('file1 contents'); + await file2.save('file2 contents'); + const sources = [file1, file2]; + const allFiles = options.bucket!.file('all-files.txt'); + await allFiles.save('allfiles contents'); + if (options.preconditionRequired) { + await options.bucket!.combine(sources, allFiles, { + ifGenerationMatch: allFiles.metadata.generation!, + }); + } else { + await options.bucket!.combine(sources, allFiles); + } +} + +export async function create(options: ConformanceTestOptions) { + const [bucketExists] = await options.bucket!.exists(); + if (bucketExists) { + await options.bucket!.deleteFiles(); + await options.bucket!.delete({ + ignoreNotFound: true, + }); + } + await options.bucket!.create(); +} + +export async function createNotification(options: ConformanceTestOptions) { + await options.bucket!.createNotification('my-topic'); +} + +export async function deleteBucket(options: ConformanceTestOptions) { + await options.bucket!.deleteFiles(); + await options.bucket!.delete(); +} + +// Note: bucket.deleteFiles is missing from these tests +// Preconditions cannot be implemented with current setup. + +export async function deleteLabelsInstancePrecondition( + options: ConformanceTestOptions +) { + await options.bucket!.deleteLabels(); +} + +export async function deleteLabels(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.bucket!.deleteLabels({ + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.deleteLabels(); + } +} + +export async function disableRequesterPaysInstancePrecondition( + options: ConformanceTestOptions +) { + await options.bucket!.disableRequesterPays(); +} + +export async function disableRequesterPays(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.bucket!.disableRequesterPays({ + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.disableRequesterPays(); + } +} + +export async function enableLoggingInstancePrecondition( + options: ConformanceTestOptions +) { + const config = { + prefix: 'log', + }; + await options.bucket!.enableLogging(config); +} + +export async function enableLogging(options: ConformanceTestOptions) { + let config; + if (options.preconditionRequired) { + config = { + prefix: 'log', + ifMetagenerationMatch: 2, + }; + } else { + config = { + prefix: 'log', + }; + } + await options.bucket!.enableLogging(config); +} + +export async function enableRequesterPaysInstancePrecondition( + options: ConformanceTestOptions +) { + await options.bucket!.enableRequesterPays(); +} + +export async function enableRequesterPays(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.bucket!.enableRequesterPays({ + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.enableRequesterPays(); + } +} + +export async function bucketExists(options: ConformanceTestOptions) { + await options.bucket!.exists(); +} + +export async function bucketGet(options: ConformanceTestOptions) { + await options.bucket!.get(); +} + +export async function getFilesStream(options: ConformanceTestOptions) { + return new Promise((resolve, reject) => { + options + .bucket!.getFilesStream() + .on('data', () => {}) + .on('end', () => resolve(undefined)) + .on('error', (err: ApiError) => reject(err)); + }); +} + +export async function getLabels(options: ConformanceTestOptions) { + await options.bucket!.getLabels(); +} + +export async function bucketGetMetadata(options: ConformanceTestOptions) { + await options.bucket!.getMetadata(); +} + +export async function getNotifications(options: ConformanceTestOptions) { + await options.bucket!.getNotifications(); +} + +export async function lock(options: ConformanceTestOptions) { + const metageneration = 0; + await options.bucket!.lock(metageneration); +} + +export async function bucketMakePrivateInstancePrecondition( + options: ConformanceTestOptions +) { + await options.bucket!.makePrivate(); +} + +export async function bucketMakePrivate(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.bucket!.makePrivate({ + preconditionOpts: {ifMetagenerationMatch: 2}, + }); + } else { + await options.bucket!.makePrivate(); + } +} + +export async function bucketMakePublic(options: ConformanceTestOptions) { + await options.bucket!.makePublic(); +} + +export async function removeRetentionPeriodInstancePrecondition( + options: ConformanceTestOptions +) { + await options.bucket!.removeRetentionPeriod(); +} + +export async function removeRetentionPeriod(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.bucket!.removeRetentionPeriod({ + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.removeRetentionPeriod(); + } +} + +export async function setCorsConfigurationInstancePrecondition( + options: ConformanceTestOptions +) { + const corsConfiguration = [{maxAgeSeconds: 3600}]; // 1 hour + await options.bucket!.setCorsConfiguration(corsConfiguration); +} + +export async function setCorsConfiguration(options: ConformanceTestOptions) { + const corsConfiguration = [{maxAgeSeconds: 3600}]; // 1 hour + if (options.preconditionRequired) { + await options.bucket!.setCorsConfiguration(corsConfiguration, { + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.setCorsConfiguration(corsConfiguration); + } +} + +export async function setLabelsInstancePrecondition( + options: ConformanceTestOptions +) { + const labels = { + labelone: 'labelonevalue', + labeltwo: 'labeltwovalue', + }; + await options.bucket!.setLabels(labels); +} + +export async function setLabels(options: ConformanceTestOptions) { + const labels = { + labelone: 'labelonevalue', + labeltwo: 'labeltwovalue', + }; + if (options.preconditionRequired) { + await options.bucket!.setLabels(labels, { + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.setLabels(labels); + } +} + +export async function bucketSetMetadataInstancePrecondition( + options: ConformanceTestOptions +) { + const metadata = { + website: { + mainPageSuffix: 'http://example.com', + notFoundPage: 'http://example.com/404.html', + }, + }; + await options.bucket!.setMetadata(metadata); +} + +export async function bucketSetMetadata(options: ConformanceTestOptions) { + const metadata = { + website: { + mainPageSuffix: 'http://example.com', + notFoundPage: 'http://example.com/404.html', + }, + }; + if (options.preconditionRequired) { + await options.bucket!.setMetadata(metadata, { + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.setMetadata(metadata); + } +} + +export async function setRetentionPeriodInstancePrecondition( + options: ConformanceTestOptions +) { + const DURATION_SECONDS = 15780000; // 6 months. + await options.bucket!.setRetentionPeriod(DURATION_SECONDS); +} + +export async function setRetentionPeriod(options: ConformanceTestOptions) { + const DURATION_SECONDS = 15780000; // 6 months. + if (options.preconditionRequired) { + await options.bucket!.setRetentionPeriod(DURATION_SECONDS, { + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.setRetentionPeriod(DURATION_SECONDS); + } +} + +export async function bucketSetStorageClassInstancePrecondition( + options: ConformanceTestOptions +) { + await options.bucket!.setStorageClass('nearline'); +} + +export async function bucketSetStorageClass(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.bucket!.setStorageClass('nearline', { + ifMetagenerationMatch: 2, + }); + } else { + await options.bucket!.setStorageClass('nearline'); + } +} + +export async function bucketUploadResumableInstancePrecondition( + options: ConformanceTestOptions +) { + const filePath = path.join( + getDirName(), + `../conformance-test/test-data/tmp-${uuid.v4()}.txt` + ); + createTestFileFromBuffer(FILE_SIZE_BYTES, filePath); + if (options.bucket!.instancePreconditionOpts) { + options.bucket!.instancePreconditionOpts.ifGenerationMatch = 0; + delete options.bucket!.instancePreconditionOpts.ifMetagenerationMatch; + } + await options.bucket!.upload(filePath, { + resumable: true, + chunkSize: CHUNK_SIZE_BYTES, + metadata: {contentLength: FILE_SIZE_BYTES}, + }); + deleteTestFile(filePath); +} + +export async function bucketUploadResumable(options: ConformanceTestOptions) { + const filePath = path.join( + getDirName(), + `../conformance-test/test-data/tmp-${uuid.v4()}.txt` + ); + createTestFileFromBuffer(FILE_SIZE_BYTES, filePath); + if (options.preconditionRequired) { + await options.bucket!.upload(filePath, { + resumable: true, + chunkSize: CHUNK_SIZE_BYTES, + metadata: {contentLength: FILE_SIZE_BYTES}, + preconditionOpts: {ifGenerationMatch: 0}, + }); + } else { + await options.bucket!.upload(filePath, { + resumable: true, + chunkSize: CHUNK_SIZE_BYTES, + metadata: {contentLength: FILE_SIZE_BYTES}, + }); + } + deleteTestFile(filePath); +} + +export async function bucketUploadMultipartInstancePrecondition( + options: ConformanceTestOptions +) { + if (options.bucket!.instancePreconditionOpts) { + delete options.bucket!.instancePreconditionOpts.ifMetagenerationMatch; + options.bucket!.instancePreconditionOpts.ifGenerationMatch = 0; + } + await options.bucket!.upload( + path.join( + getDirName(), + '../../../conformance-test/test-data/retryStrategyTestData.json' + ), + {resumable: false} + ); +} + +export async function bucketUploadMultipart(options: ConformanceTestOptions) { + if (options.bucket!.instancePreconditionOpts) { + delete options.bucket!.instancePreconditionOpts.ifMetagenerationMatch; + } + + if (options.preconditionRequired) { + await options.bucket!.upload( + path.join( + getDirName(), + '../../../conformance-test/test-data/retryStrategyTestData.json' + ), + {resumable: false, preconditionOpts: {ifGenerationMatch: 0}} + ); + } else { + await options.bucket!.upload( + path.join( + getDirName(), + '../../../conformance-test/test-data/retryStrategyTestData.json' + ), + {resumable: false} + ); + } +} + +///////////////////////////////////////////////// +//////////////////// FILE ///////////////////// +///////////////////////////////////////////////// + +export async function copy(options: ConformanceTestOptions) { + const newFile = new File(options.bucket!, 'a-different-file.png'); + await newFile.save('a-different-file.png'); + + if (options.preconditionRequired) { + await options.file!.copy('a-different-file.png', { + preconditionOpts: { + ifGenerationMatch: newFile.metadata.generation!, + }, + }); + } else { + await options.file!.copy('a-different-file.png'); + } +} + +export async function createReadStream(options: ConformanceTestOptions) { + return new Promise((resolve, reject) => { + options + .file!.createReadStream() + .on('data', () => {}) + .on('end', () => resolve(undefined)) + .on('error', (err: ApiError) => reject(err)); + }); +} + +export async function createResumableUploadInstancePrecondition( + options: ConformanceTestOptions +) { + await options.file!.createResumableUpload(); +} + +export async function createResumableUpload(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.file!.createResumableUpload({ + preconditionOpts: {ifGenerationMatch: 0}, + }); + } else { + await options.file!.createResumableUpload(); + } +} + +export async function fileDeleteInstancePrecondition( + options: ConformanceTestOptions +) { + await options.file!.delete(); +} + +export async function fileDelete(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.file!.delete({ + ifGenerationMatch: options.file!.metadata.generation, + }); + } else { + await options.file!.delete(); + } +} + +export async function download(options: ConformanceTestOptions) { + await options.file!.download(); +} + +export async function exists(options: ConformanceTestOptions) { + await options.file!.exists(); +} + +export async function get(options: ConformanceTestOptions) { + await options.file!.get(); +} + +export async function getExpirationDate(options: ConformanceTestOptions) { + await options.file!.getExpirationDate(); +} + +export async function getMetadata(options: ConformanceTestOptions) { + await options.file!.getMetadata(); +} + +export async function isPublic(options: ConformanceTestOptions) { + await options.file!.isPublic(); +} + +export async function fileMakePrivateInstancePrecondition( + options: ConformanceTestOptions +) { + await options.file!.makePrivate(); +} + +export async function fileMakePrivate(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.file!.makePrivate({ + preconditionOpts: { + ifMetagenerationMatch: options.file!.metadata.metageneration, + }, + }); + } else { + await options.file!.makePrivate(); + } +} + +export async function fileMakePublic(options: ConformanceTestOptions) { + await options.file!.makePublic(); +} + +export async function move(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.file!.move('new-file', { + preconditionOpts: {ifGenerationMatch: 0}, + }); + } else { + await options.file!.move('new-file'); + } +} + +export async function rename(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.file!.rename('new-name', { + preconditionOpts: {ifGenerationMatch: 0}, + }); + } else { + await options.file!.rename('new-name'); + } +} + +export async function rotateEncryptionKey(options: ConformanceTestOptions) { + const crypto = require('crypto'); + const buffer = crypto.randomBytes(32); + const newKey = buffer.toString('base64'); + if (options.preconditionRequired) { + await options.file!.rotateEncryptionKey({ + encryptionKey: Buffer.from(newKey, 'base64'), + preconditionOpts: {ifGenerationMatch: options.file!.metadata.generation}, + }); + } else { + await options.file!.rotateEncryptionKey({ + encryptionKey: Buffer.from(newKey, 'base64'), + }); + } +} + +export async function saveResumableInstancePrecondition( + options: ConformanceTestOptions +) { + const buf = createTestBuffer(FILE_SIZE_BYTES); + await options.file!.save(buf, { + resumable: true, + chunkSize: CHUNK_SIZE_BYTES, + metadata: {contentLength: FILE_SIZE_BYTES}, + }); +} + +export async function saveResumable(options: ConformanceTestOptions) { + const buf = createTestBuffer(FILE_SIZE_BYTES); + if (options.preconditionRequired) { + await options.file!.save(buf, { + resumable: true, + chunkSize: CHUNK_SIZE_BYTES, + metadata: {contentLength: FILE_SIZE_BYTES}, + preconditionOpts: { + ifGenerationMatch: options.file!.metadata.generation, + ifMetagenerationMatch: options.file!.metadata.metageneration, + }, + }); + } else { + await options.file!.save(buf, { + resumable: true, + chunkSize: CHUNK_SIZE_BYTES, + metadata: {contentLength: FILE_SIZE_BYTES}, + }); + } +} + +export async function saveMultipartInstancePrecondition( + options: ConformanceTestOptions +) { + await options.file!.save('testdata', {resumable: false}); +} + +export async function saveMultipart(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.file!.save('testdata', { + resumable: false, + preconditionOpts: { + ifGenerationMatch: options.file!.metadata.generation, + }, + }); + } else { + await options.file!.save('testdata', { + resumable: false, + }); + } +} + +export async function setMetadataInstancePrecondition( + options: ConformanceTestOptions +) { + const metadata = { + contentType: 'application/x-font-ttf', + metadata: { + my: 'custom', + properties: 'go here', + }, + }; + await options.file!.setMetadata(metadata); +} + +export async function setMetadata(options: ConformanceTestOptions) { + const metadata = { + contentType: 'application/x-font-ttf', + metadata: { + my: 'custom', + properties: 'go here', + }, + }; + if (options.preconditionRequired) { + await options.file!.setMetadata(metadata, { + ifMetagenerationMatch: options.file!.metadata.metageneration, + }); + } else { + await options.file!.setMetadata(metadata); + } +} + +export async function setStorageClass(options: ConformanceTestOptions) { + if (options.preconditionRequired) { + await options.file!.setStorageClass('nearline', { + preconditionOpts: { + ifGenerationMatch: options.file!.metadata.generation, + }, + }); + } else { + await options.file!.setStorageClass('nearline'); + } +} + +// ///////////////////////////////////////////////// +// /////////////////// HMAC KEY //////////////////// +// ///////////////////////////////////////////////// + +export async function deleteHMAC(options: ConformanceTestOptions) { + const metadata = { + state: 'INACTIVE', + }; + await options.hmacKey!.setMetadata(metadata); + await options.hmacKey!.delete(); +} + +export async function getHMAC(options: ConformanceTestOptions) { + await options.hmacKey!.get(); +} + +export async function getMetadataHMAC(options: ConformanceTestOptions) { + await options.hmacKey!.getMetadata(); +} + +export async function setMetadataHMAC(options: ConformanceTestOptions) { + const metadata = { + state: 'INACTIVE', + }; + await options.hmacKey!.setMetadata(metadata); +} + +///////////////////////////////////////////////// +////////////////////// IAM ////////////////////// +///////////////////////////////////////////////// + +export async function iamGetPolicy(options: ConformanceTestOptions) { + await options.bucket!.iam.getPolicy({requestedPolicyVersion: 1}); +} + +export async function iamSetPolicy(options: ConformanceTestOptions) { + const testPolicy: Policy = { + bindings: [ + { + role: 'roles/storage.admin', + members: ['serviceAccount:myotherproject@appspot.gserviceaccount.com'], + }, + ], + }; + if (options.preconditionRequired) { + const currentPolicy = await options.bucket!.iam.getPolicy(); + testPolicy.etag = currentPolicy[0].etag; + } + await options.bucket!.iam.setPolicy(testPolicy); +} + +export async function iamTestPermissions(options: ConformanceTestOptions) { + const permissionToTest = 'storage.buckets.delete'; + await options.bucket!.iam.testPermissions(permissionToTest); +} + +///////////////////////////////////////////////// +///////////////// NOTIFICATION ////////////////// +///////////////////////////////////////////////// + +export async function notificationDelete(options: ConformanceTestOptions) { + await options.notification!.delete(); +} + +export async function notificationCreate(options: ConformanceTestOptions) { + await options.notification!.create(); +} + +export async function notificationExists(options: ConformanceTestOptions) { + await options.notification!.exists(); +} + +export async function notificationGet(options: ConformanceTestOptions) { + await options.notification!.get(); +} + +export async function notificationGetMetadata(options: ConformanceTestOptions) { + await options.notification!.getMetadata(); +} + +///////////////////////////////////////////////// +/////////////////// STORAGE ///////////////////// +///////////////////////////////////////////////// + +export async function createBucket(options: ConformanceTestOptions) { + const bucket = options.storage!.bucket('test-creating-bucket'); + const [exists] = await bucket.exists(); + if (exists) { + bucket.delete(); + } + await options.storage!.createBucket('test-creating-bucket'); +} + +export async function createHMACKey(options: ConformanceTestOptions) { + const serviceAccountEmail = 'my-service-account@appspot.gserviceaccount.com'; + await options.storage!.createHmacKey(serviceAccountEmail); +} + +export async function getBuckets(options: ConformanceTestOptions) { + await options.storage!.getBuckets(); +} + +export async function getBucketsStream(options: ConformanceTestOptions) { + return new Promise((resolve, reject) => { + options + .storage!.getBucketsStream() + .on('data', () => {}) + .on('end', () => resolve(undefined)) + .on('error', err => reject(err)); + }); +} + +export function getHMACKeyStream(options: ConformanceTestOptions) { + return new Promise((resolve, reject) => { + options + .storage!.getHmacKeysStream() + .on('data', () => {}) + .on('end', () => resolve(undefined)) + .on('error', err => reject(err)); + }); +} + +export async function getServiceAccount(options: ConformanceTestOptions) { + await options.storage!.getServiceAccount(); +} diff --git a/handwritten/storage/conformance-test/scenarios/scenarioFive.ts b/handwritten/storage/conformance-test/scenarios/scenarioFive.ts new file mode 100644 index 00000000000..9c3a3b57215 --- /dev/null +++ b/handwritten/storage/conformance-test/scenarios/scenarioFive.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 * as testFile from '../test-data/retryStrategyTestData.json'; +import {executeScenario, RetryTestCase} from '../conformanceCommon'; +import assert from 'assert'; + +const SCENARIO_NUMBER_TO_TEST = 5; +const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( + test => test.id === SCENARIO_NUMBER_TO_TEST +); + +describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { + assert(retryTestCase); + executeScenario(retryTestCase); +}); diff --git a/handwritten/storage/conformance-test/scenarios/scenarioFour.ts b/handwritten/storage/conformance-test/scenarios/scenarioFour.ts new file mode 100644 index 00000000000..0072461e40f --- /dev/null +++ b/handwritten/storage/conformance-test/scenarios/scenarioFour.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 * as testFile from '../test-data/retryStrategyTestData.json'; +import {executeScenario, RetryTestCase} from '../conformanceCommon'; +import assert from 'assert'; + +const SCENARIO_NUMBER_TO_TEST = 4; +const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( + test => test.id === SCENARIO_NUMBER_TO_TEST +); + +describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { + assert(retryTestCase); + executeScenario(retryTestCase); +}); diff --git a/handwritten/storage/conformance-test/scenarios/scenarioOne.ts b/handwritten/storage/conformance-test/scenarios/scenarioOne.ts new file mode 100644 index 00000000000..981da527b87 --- /dev/null +++ b/handwritten/storage/conformance-test/scenarios/scenarioOne.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 * as testFile from '../test-data/retryStrategyTestData.json'; +import {executeScenario, RetryTestCase} from '../conformanceCommon'; +import assert from 'assert'; + +const SCENARIO_NUMBER_TO_TEST = 1; +const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( + test => test.id === SCENARIO_NUMBER_TO_TEST +); + +describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { + assert(retryTestCase); + executeScenario(retryTestCase); +}); diff --git a/handwritten/storage/conformance-test/scenarios/scenarioSeven.ts b/handwritten/storage/conformance-test/scenarios/scenarioSeven.ts new file mode 100644 index 00000000000..d1204d3b48d --- /dev/null +++ b/handwritten/storage/conformance-test/scenarios/scenarioSeven.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 * as testFile from '../test-data/retryStrategyTestData.json'; +import {executeScenario, RetryTestCase} from '../conformanceCommon'; +import assert from 'assert'; + +const SCENARIO_NUMBER_TO_TEST = 7; +const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( + test => test.id === SCENARIO_NUMBER_TO_TEST +); + +describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { + assert(retryTestCase); + executeScenario(retryTestCase); +}); diff --git a/handwritten/storage/conformance-test/scenarios/scenarioSix.ts b/handwritten/storage/conformance-test/scenarios/scenarioSix.ts new file mode 100644 index 00000000000..6d2b452ff7b --- /dev/null +++ b/handwritten/storage/conformance-test/scenarios/scenarioSix.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 * as testFile from '../test-data/retryStrategyTestData.json'; +import {executeScenario, RetryTestCase} from '../conformanceCommon'; +import assert from 'assert'; + +const SCENARIO_NUMBER_TO_TEST = 6; +const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( + test => test.id === SCENARIO_NUMBER_TO_TEST +); + +describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { + assert(retryTestCase); + executeScenario(retryTestCase); +}); diff --git a/handwritten/storage/conformance-test/scenarios/scenarioThree.ts b/handwritten/storage/conformance-test/scenarios/scenarioThree.ts new file mode 100644 index 00000000000..7b6c9002184 --- /dev/null +++ b/handwritten/storage/conformance-test/scenarios/scenarioThree.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 * as testFile from '../test-data/retryStrategyTestData.json'; +import {executeScenario, RetryTestCase} from '../conformanceCommon'; +import assert from 'assert'; + +const SCENARIO_NUMBER_TO_TEST = 3; +const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( + test => test.id === SCENARIO_NUMBER_TO_TEST +); + +describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { + assert(retryTestCase); + executeScenario(retryTestCase); +}); diff --git a/handwritten/storage/conformance-test/scenarios/scenarioTwo.ts b/handwritten/storage/conformance-test/scenarios/scenarioTwo.ts new file mode 100644 index 00000000000..fe2e6fb117e --- /dev/null +++ b/handwritten/storage/conformance-test/scenarios/scenarioTwo.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 * as testFile from '../test-data/retryStrategyTestData.json'; +import {executeScenario, RetryTestCase} from '../conformanceCommon'; +import assert from 'assert'; + +const SCENARIO_NUMBER_TO_TEST = 2; +const retryTestCase: RetryTestCase | undefined = testFile.retryTests.find( + test => test.id === SCENARIO_NUMBER_TO_TEST +); + +describe(`Scenario ${SCENARIO_NUMBER_TO_TEST}`, () => { + assert(retryTestCase); + executeScenario(retryTestCase); +}); diff --git a/handwritten/storage/conformance-test/test-data/retryInvocationMap.json b/handwritten/storage/conformance-test/test-data/retryInvocationMap.json new file mode 100644 index 00000000000..8dea345f12c --- /dev/null +++ b/handwritten/storage/conformance-test/test-data/retryInvocationMap.json @@ -0,0 +1,147 @@ +{ + "storage.buckets.delete": [ + "deleteBucket" + ], + "storage.buckets.patch": [ + "addLifecycleRuleInstancePrecondition", + "bucketMakePrivateInstancePrecondition", + "deleteLabelsInstancePrecondition", + "disableRequesterPaysInstancePrecondition", + "enableRequesterPaysInstancePrecondition", + "enableLoggingInstancePrecondition", + "removeRetentionPeriodInstancePrecondition", + "setCorsConfigurationInstancePrecondition", + "setLabelsInstancePrecondition", + "setRetentionPeriodInstancePrecondition", + "bucketSetStorageClassInstancePrecondition", + "bucketSetMetadataInstancePrecondition", + "addLifecycleRule", + "bucketMakePrivate", + "deleteLabels", + "disableRequesterPays", + "enableRequesterPays", + "enableLogging", + "removeRetentionPeriod", + "setCorsConfiguration", + "setLabels", + "setRetentionPeriod", + "bucketSetStorageClass", + "bucketSetMetadata" + ], + "storage.buckets.insert": [ + "create", + "createBucket" + ], + "storage.buckets.get": [ + "bucketGet", + "getLabels", + "bucketGetMetadata", + "bucketExists" + ], + "storage.objects.list": [ + "getFilesStream" + ], + "storage.notifications.list": [ + "getNotifications" + ], + "storage.buckets.lockRententionPolicy": [ + "lock" + ], + "storage.objects.patch": [ + "fileMakePrivateInstancePrecondition", + "setMetadataInstancePrecondition", + "fileMakePrivate", + "setMetadata" + ], + "storage.bucket_acl.insert": [ + "bucketMakePublic" + ], + "storage.object_acl.insert": [ + "fileMakePublic" + ], + "storage.objects.rewrite": [ + "copy", + "move", + "rename", + "rotateEncryptionKey", + "setStorageClass" + ], + "storage.objects.insert": [ + "bucketUploadResumableInstancePrecondition", + "saveResumableInstancePrecondition", + "bucketUploadMultipartInstancePrecondition", + "saveMultipartInstancePrecondition", + "createResumableUploadInstancePrecondition", + "bucketUploadResumable", + "saveResumable", + "bucketUploadMultipart", + "saveMultipart", + "createResumableUpload" + ], + "storage.resumable.upload": [ + "bucketUploadResumableInstancePrecondition", + "saveResumableInstancePrecondition", + "bucketUploadResumable", + "saveResumable" + ], + "storage.objects.delete": [ + "fileDeleteInstancePrecondition", + "fileDelete" + ], + "storage.objects.get": [ + "get", + "download", + "exists", + "getExpirationDate", + "getMetadata", + "isPublic", + "createReadStream" + ], + "storage.notifications.delete": [ + "notificationDelete" + ], + "storage.notifications.insert": [ + "createNotification", + "notificationCreate" + ], + "storage.notifications.get": [ + "notificationExists", + "notificationGet", + "notificationGetMetadata" + ], + "storage.buckets.getIamPolicy": [ + "iamGetPolicy" + ], + "storage.buckets.setIamPolicy": [ + "iamSetPolicy" + ], + "storage.buckets.testIamPermission": [ + "iamTestPermissions" + ], + "storage.buckets.list": [ + "getBuckets", + "getBucketsStream" + ], + "storage.objects.compose": [ + "combineInstancePrecondition", + "combine" + ], + "storage.hmacKey.delete": [ + "deleteHMAC" + ], + "storage.hmacKey.get": [ + "getHMAC", + "getMetadataHMAC" + ], + "storage.hmacKey.update": [ + ], + "storage.hmacKey.create": [ + "createHMACKey" + ], + "storage.hmacKey.list": [ + "getHMACKeyStream" + ], + "storage.serviceaccount.get": [ + "getServiceAccount" + ] +} diff --git a/handwritten/storage/conformance-test/test-data/retryStrategyTestData.json b/handwritten/storage/conformance-test/test-data/retryStrategyTestData.json new file mode 100644 index 00000000000..b302c007272 --- /dev/null +++ b/handwritten/storage/conformance-test/test-data/retryStrategyTestData.json @@ -0,0 +1,267 @@ +{ + "retryTests": [ + { + "id": 1, + "description": "always_idempotent", + "cases": [ + { + "instructions": ["return-503", "return-503"] + }, + { + "instructions": ["return-reset-connection", "return-reset-connection"] + }, + { + "instructions": ["return-reset-connection", "return-503"] + } + ], + "methods": [ + {"name": "storage.bucket_acl.get", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.list", "resources": ["BUCKET"]}, + {"name": "storage.buckets.delete", "resources": ["BUCKET"]}, + {"name": "storage.buckets.get", "resources": ["BUCKET"]}, + {"name": "storage.buckets.getIamPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.insert", "resources": []}, + {"name": "storage.buckets.list", "resources": ["BUCKET"]}, + {"name": "storage.buckets.lockRetentionPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.testIamPermissions", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.get", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.list", "resources": ["BUCKET"]}, + {"name": "storage.hmacKey.delete", "resources": ["HMAC_KEY"]}, + {"name": "storage.hmacKey.get", "resources": ["HMAC_KEY"]}, + {"name": "storage.hmacKey.list", "resources": ["HMAC_KEY"]}, + {"name": "storage.notifications.delete", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.notifications.get", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.notifications.list", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.object_acl.get", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.list", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.get", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.list", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.serviceaccount.get", "resources": []} + ], + "preconditionProvided": false, + "expectSuccess": true + }, + { + "id": 2, + "description": "conditionally_idempotent_retries_when_precondition_is_present", + "cases": [ + { + "instructions": ["return-503", "return-503"] + }, + { + "instructions": ["return-reset-connection", "return-reset-connection"] + }, + { + "instructions": ["return-reset-connection", "return-503"] + } + ], + "methods": [ + {"name": "storage.buckets.patch", "resources": ["BUCKET"]}, + {"name": "storage.buckets.setIamPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.update", "resources": ["BUCKET"]}, + {"name": "storage.hmacKey.update", "resources": ["HMAC_KEY"]}, + {"name": "storage.objects.compose", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.copy", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.delete", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.insert", "resources": ["BUCKET"]}, + {"name": "storage.objects.patch", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.rewrite", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.update", "resources": ["BUCKET", "OBJECT"]} + ], + "preconditionProvided": true, + "expectSuccess": true + }, + { + "id": 3, + "description": "conditionally_idempotent_no_retries_when_precondition_is_absent", + "cases": [ + { + "instructions": ["return-503"] + }, + { + "instructions": ["return-reset-connection"] + } + ], + "methods": [ + {"name": "storage.buckets.patch", "resources": ["BUCKET"]}, + {"name": "storage.buckets.setIamPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.update", "resources": ["BUCKET"]}, + {"name": "storage.hmacKey.update", "resources": ["HMAC_KEY"]}, + {"name": "storage.objects.compose", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.copy", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.delete", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.insert", "resources": ["BUCKET"]}, + {"name": "storage.objects.patch", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.rewrite", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.update", "resources": ["BUCKET", "OBJECT"]} + ], + "preconditionProvided": false, + "expectSuccess": false + }, + { + "id": 4, + "description": "non_idempotent", + "cases": [ + { + "instructions": ["return-503"] + }, + { + "instructions": ["return-reset-connection"] + } + ], + "methods": [ + {"name": "storage.bucket_acl.delete", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.insert", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.patch", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.update", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.delete", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.insert", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.patch", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.update", "resources": ["BUCKET"]}, + {"name": "storage.hmacKey.create", "resources": []}, + {"name": "storage.notifications.insert", "resources": ["BUCKET"]}, + {"name": "storage.object_acl.delete", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.insert", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.patch", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.update", "resources": ["BUCKET", "OBJECT"]} + ], + "preconditionProvided": false, + "expectSuccess": false + }, + { + "id": 5, + "description": "non-retryable errors", + "cases": [ + { + "instructions": ["return-400"] + }, + { + "instructions": ["return-401"] + } + ], + "methods": [ + {"name": "storage.bucket_acl.delete", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.get", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.insert", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.list", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.patch", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.update", "resources": ["BUCKET"]}, + {"name": "storage.buckets.delete", "resources": ["BUCKET"]}, + {"name": "storage.buckets.get", "resources": ["BUCKET"]}, + {"name": "storage.buckets.getIamPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.insert", "resources": ["BUCKET"]}, + {"name": "storage.buckets.list", "resources": ["BUCKET"]}, + {"name": "storage.buckets.lockRetentionPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.patch", "resources": ["BUCKET"]}, + {"name": "storage.buckets.setIamPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.testIamPermissions", "resources": ["BUCKET"]}, + {"name": "storage.buckets.update", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.delete", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.get", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.insert", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.list", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.patch", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.update", "resources": ["BUCKET"]}, + {"name": "storage.hmacKey.create", "resources": []}, + {"name": "storage.hmacKey.delete", "resources": ["HMAC_KEY"]}, + {"name": "storage.hmacKey.get", "resources": ["HMAC_KEY"]}, + {"name": "storage.hmacKey.list", "resources": ["HMAC_KEY"]}, + {"name": "storage.hmacKey.update", "resources": ["HMAC_KEY"]}, + {"name": "storage.notifications.delete", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.notifications.get", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.notifications.insert", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.notifications.list", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.object_acl.delete", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.get", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.insert", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.list", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.patch", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.update", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.compose", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.copy", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.delete", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.get", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.insert", "resources": ["BUCKET"]}, + {"name": "storage.objects.list", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.patch", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.rewrite", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.update", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.serviceaccount.get", "resources": []} + ], + "preconditionProvided": false, + "expectSuccess": false + }, + { + "id": 6, + "description": "mix_retryable_non_retryable_errors", + "cases": [ + { + "instructions": ["return-503", "return-400"] + }, + { + "instructions": ["return-reset-connection", "return-401"] + } + ], + "methods": [ + {"name": "storage.bucket_acl.get", "resources": ["BUCKET"]}, + {"name": "storage.bucket_acl.list", "resources": ["BUCKET"]}, + {"name": "storage.buckets.delete", "resources": ["BUCKET"]}, + {"name": "storage.buckets.get", "resources": ["BUCKET"]}, + {"name": "storage.buckets.getIamPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.insert", "resources": []}, + {"name": "storage.buckets.list", "resources": ["BUCKET"]}, + {"name": "storage.buckets.lockRetentionPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.patch", "resources": ["BUCKET"]}, + {"name": "storage.buckets.setIamPolicy", "resources": ["BUCKET"]}, + {"name": "storage.buckets.testIamPermissions", "resources": ["BUCKET"]}, + {"name": "storage.buckets.update", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.get", "resources": ["BUCKET"]}, + {"name": "storage.default_object_acl.list", "resources": ["BUCKET"]}, + {"name": "storage.hmacKey.delete", "resources": ["HMAC_KEY"]}, + {"name": "storage.hmacKey.get", "resources": ["HMAC_KEY"]}, + {"name": "storage.hmacKey.list", "resources": ["HMAC_KEY"]}, + {"name": "storage.hmacKey.update", "resources": ["HMAC_KEY"]}, + {"name": "storage.notifications.delete", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.notifications.get", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.notifications.list", "resources": ["BUCKET", "NOTIFICATION"]}, + {"name": "storage.object_acl.get", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.object_acl.list", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.compose", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.copy", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.delete", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.get", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.list", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.insert", "resources": ["BUCKET"]}, + {"name": "storage.objects.patch", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.rewrite", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.objects.update", "resources": ["BUCKET", "OBJECT"]}, + {"name": "storage.serviceaccount.get", "resources": []} + ], + "preconditionProvided": true, + "expectSuccess": false + }, + { + "id": 7, + "description": "resumable_uploads_handle_complex_retries", + "cases": [ + { + "instructions": ["return-reset-connection", "return-503"] + }, + { + "instructions": ["return-408"] + }, + { + "instructions": ["return-503-after-256K"] + }, + { + "instructions": ["return-503-after-8192K"] + } + ], + "methods": [ + {"name": "storage.objects.insert", "group": "storage.resumable.upload", "resources": ["BUCKET"]} + ], + "preconditionProvided": true, + "expectSuccess": true + } + ] +} diff --git a/handwritten/storage/conformance-test/test-data/v4SignedUrl.json b/handwritten/storage/conformance-test/test-data/v4SignedUrl.json new file mode 100644 index 00000000000..86a51e0ba3c --- /dev/null +++ b/handwritten/storage/conformance-test/test-data/v4SignedUrl.json @@ -0,0 +1,698 @@ +{ + "signingV4Tests": [ + { + "description": "Simple GET", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=95e6a13d43a1d1962e667f17397f2b80ac9bdd1669210d5e08e0135df9dff4e56113485dbe429ca2266487b9d1796ebdee2d7cf682a6ef3bb9fbb4c351686fba90d7b621cf1c4eb1fdf126460dd25fa0837dfdde0a9fd98662ce60844c458448fb2b352c203d9969cb74efa4bdb742287744a4f2308afa4af0e0773f55e32e92973619249214b97283b2daa14195244444e33f938138d1e5f561088ce8011f4986dda33a556412594db7c12fc40e1ff3f1bedeb7a42f5bcda0b9567f17f65855f65071fabb88ea12371877f3f77f10e1466fff6ff6973b74a933322ff0949ce357e20abe96c3dd5cfab42c9c83e740a4d32b9e11e146f0eb3404d2e975896f74", + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Simple PUT", + "bucket": "test-bucket", + "object": "test-object", + "method": "PUT", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=8adff1d4285739e31aa68e73767a46bc5511fde377497dbe08481bf5ceb34e29cc9a59921748d8ec3dd4085b7e9b7772a952afedfcdaecb3ae8352275b8b7c867f204e3db85076220a3127a8a9589302fc1181eae13b9b7fe41109ec8cdc93c1e8bac2d7a0cc32a109ca02d06957211326563ab3d3e678a0ba296e298b5fc5e14593c99d444c94724cc4be97015dbff1dca377b508fa0cb7169195de98d0e4ac96c42b918d28c8d92d33e1bd125ce0fb3cd7ad2c45dae65c22628378f6584971b8bf3945b26f2611eb651e9b6a8648970c1ecf386bb71327b082e7296c4e1ee2fc0bdd8983da80af375c817fb1ad491d0bc22c0f51dba0d66e2cffbc90803e47", + "scheme": "https", + "expectedCanonicalRequest": "PUT\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n78742860705da91404222d5d66ff89850292471199c3c2808d116ad12e6177b4" + }, + { + "description": "POST for resumable uploads", + "bucket": "test-bucket", + "object": "test-object", + "method": "POST", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bx-goog-resumable&X-Goog-Signature=4a6d39b23343cedf4c30782aed4b384001828c79ffa3a080a481ea01a640dea0a0ceb58d67a12cef3b243c3f036bb3799c6ee88e8db3eaf7d0bdd4b70a228d0736e07eaa1ee076aff5c6ce09dff1f1f03a0d8ead0d2893408dd3604fdabff553aa6d7af2da67cdba6790006a70240f96717b98f1a6ccb24f00940749599be7ef72aaa5358db63ddd54b2de9e2d6d6a586eac4fe25f36d86fc6ab150418e9c6fa01b732cded226c6d62fc95b72473a4cc55a8257482583fe66d9ab6ede909eb41516a8690946c3e87b0f2052eb0e97e012a14b2f721c42e6e19b8a1cd5658ea36264f10b9b1ada66b8ed5bf7ed7d1708377ac6e5fe608ae361fb594d2e5b24c54", + "headers": { + "X-Goog-Resumable": "start" + }, + "scheme": "https", + "expectedCanonicalRequest": "POST\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bx-goog-resumable\nhost:storage.googleapis.com\nx-goog-resumable:start\n\nhost;x-goog-resumable\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n877f8b40179d2753296f2fd6de815ab40503c7a3c446a7b44aa4e74422ff4daf" + }, + { + "description": "Vary expiration and timestamp", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 20, + "timestamp": "2019-03-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190301%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190301T090000Z&X-Goog-Expires=20&X-Goog-SignedHeaders=host&X-Goog-Signature=9669ed5b10664dc594c758296580662912cf4bcc5a4ba0b6bf055bcbf6f34eed7bdad664f534962174a924741a0c273a4f67bc1847cef20192a6beab44223bd9d4fbbd749c407b79997598c30f82ddc269ff47ec09fa3afe74e00616d438df0d96a7d8ad0adacfad1dc3286f864d924fe919fb0dce45d3d975c5afe8e13af2db9cc37ba77835f92f7669b61e94c6d562196c1274529e76cfff1564cc2cad7d5387dc8e12f7a5dfd925685fe92c30b43709eee29fa2f66067472cee5423d1a3a4182fe8cea75c9329d181dc6acad7c393cd04f8bf5bc0515127d8ebd65d80c08e19ad03316053ea60033fd1b1fd85a69c576415da3bf0a3718d9ea6d03e0d66f0", + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190301%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190301T090000Z&X-Goog-Expires=20&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190301T090000Z\n20190301/auto/storage/goog4_request\n779f19fdb6fd381390e2d5af04947cf21750277ee3c20e0c97b7e46a1dff8907" + }, + { + "description": "Vary bucket and object", + "bucket": "test-bucket2", + "object": "test-object2", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket2/test-object2?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=36e3d58dfd3ec1d2dd2f24b5ee372a71e811ffaa2162a2b871d26728d0354270bc116face87127532969c4a3967ed05b7309af741e19c7202f3167aa8c2ac420b61417d6451442bb91d7c822cd17be8783f01e05372769c88913561d27e6660dd8259f0081a71f831be6c50283626cbf04494ac10c394b29bb3bce74ab91548f58a37118a452693cf0483d77561fc9cac8f1765d2c724994cca46a83517a10157ee0347a233a2aaeae6e6ab5e204ff8fc5f54f90a3efdb8301d9fff5475d58cd05b181affd657f48203f4fb133c3a3d355b8eefbd10d5a0a5fd70d06e9515460ad74e22334b2cba4b29cae4f6f285cdb92d8f3126d7a1479ca3bdb69c207d860", + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket2/test-object2\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\na139afbf35ac30e9864f63197f79609731ab1b0ca166e2a456dba156fcd3f9ce" + }, + { + "description": "Slashes in object name should not be URL encoded", + "bucket": "test-bucket", + "object": "path/with/slashes/under_score/amper&sand/file.ext", + "headers": { + "header/name/with/slash": "should-be-encoded" + }, + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/path/with/slashes/under_score/amper%26sand/file.ext?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=header%2Fname%2Fwith%2Fslash%3Bhost&X-Goog-Signature=2a9a82e84e39f5d2c0d980514db17f8c3dece473c9a5743d54e8453f9811927b1b99ce548c534cababd8fa339183e75b410e12e32a4c72f5ff176e95651fabed0072e59e7e236eb7e26f52c0ce599db1c47ae07af1a98d20872b6fde23432c0a5fcf4fb2dda735169198c80cd5cc51be9904f7e5eef2cc489ff44ac5697c529e4b34ac08709a7d2e425619377212c64561ed8b4d2fcb70a26e4f9236f995ab4658d240ac85c7a353bae6b2d39d5fc0716afa435a1f6e100db5504612b5e610db370623ab4b8eba3c03c98f23dcb4b9ffd518f2212abb2f93649d25385d71603d470cff0b7631adb9d0849d38609dedb3097761c8f47ec0d57777bb063611c05b", + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/path/with/slashes/under_score/amper%26sand/file.ext\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=header%2Fname%2Fwith%2Fslash%3Bhost\nheader/name/with/slash:should-be-encoded\nhost:storage.googleapis.com\n\nheader/name/with/slash;host\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\nf1d206dd8cbe1b892d4081ccddae0927d9f5fee5653fb2a2f43e7c20ed455cad" + }, + { + "description": "Forward Slashes should not be stripped", + "bucket": "test-bucket", + "object": "/path/with/slashes/under_score/amper&sand/file.ext", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket//path/with/slashes/under_score/amper%26sand/file.ext?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=2db8b70e3f85b39be7824f6d02be31af2e6a2eb63f6bb41254851f7ef51bdad8963a9d2b254f8379c1780c8e6898be002d4100a0abd3d45f1437687fed65d15dd237c3a6f3c399c64ffd4e4cea7ef1c2f0391d35ecbeeaf3e3148d23c6f24c839cfcd92c1496332f5bfbbf1ed1e957eb45fad57df24828c96cf243eec23fba014d277c22a572708beb355888c5a8c0047cb3015d7f62cc90285676e7e34626fd0ce9ba5e0da39fc3de0035cc3ad120c46cb73db87246ae123f7a342c235e9480bd7d7e00c13b1e1bb7be5e2bce74d59a53505172463b48aefeedb48281d90874aa4177c881d3596ed1067f02eaac13d810a7aed234c41978b1394d0ce3662f76", + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket//path/with/slashes/under_score/amper%26sand/file.ext\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n63c601ecd6ccfec84f1113fc906609cbdf7651395f4300cecd96ddd2c35164f8" + }, + { + "description": "Simple headers", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=bar%3Bfoo%3Bhost&X-Goog-Signature=68ecd3b008328ed30d91e2fe37444ed7b9b03f28ed4424555b5161980531ef87db1c3a5bc0265aad5640af30f96014c94fb2dba7479c41bfe1c020eb90c0c6d387d4dd09d4a5df8b60ea50eb6b01cdd786a1e37020f5f95eb8f9b6cd3f65a1f8a8a65c9fcb61ea662959efd9cd73b683f8d8804ef4d6d9b2852419b013368842731359d7f9e6d1139032ceca75d5e67cee5fd0192ea2125e5f2955d38d3d50cf116f3a52e6a62de77f6207f5b95aaa1d7d0f8a46de89ea72e7ea30f21286318d7eba0142232b0deb3a1dc9e1e812a981c66b5ffda3c6b01a8a9d113155792309fd53a3acfd054ca7776e8eec28c26480cd1e3c812f67f91d14217f39a606669d", + "headers": { + "BAR": "BAR-value", + "foo": "foo-value" + }, + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=bar%3Bfoo%3Bhost\nbar:BAR-value\nfoo:foo-value\nhost:storage.googleapis.com\n\nbar;foo;host\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n59c1ac1a6ee7d773d5c4487ecc861d60b71c4871dd18fc7d8485fac09df1d296" + }, + { + "description": "Headers with colons", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-Signature=30b831c18b5cdef6dceaa476a395a28d80002ad70b4419af8fd63eaad02c2fbb4b4829b3a4e33e7796a9ce92735498dfc20e0fbc177172f7c8ab6a07736512c7c923ef2f28a2e72d727fd61ca89495c9e62d51b93a2f7061451240c909ed8d05a7bcf616c1ad90fa5cdbc27c4724dec6b29db04129b32402db4ddf7b5b554724481bfdbf41cb24c3c6b9e33bb411c864077d6a19a750a90eb5ad9370d2b171df2813c9a864b40b2ee215ae9790d7916155de863708aa5121bca42e4695def5322f3726f8e1a7ec56da7a1a4f6b959253513a10f7edf6594c02340021b8cc709b0177ec6bb127fc2fb705f508bde045ed94603471c19c1c6af165f559a3c4741b&X-Goog-SignedHeaders=bar%3Bfoo%3Bhost", + "headers": { + "BAR": "2023-02-10T03:", + "foo": "2023-02-10T02:00:00Z" + }, + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=bar%3Bfoo%3Bhost\nbar:2023-02-10T03:\nfoo:2023-02-10T02:00:00Z\nhost:storage.googleapis.com\n\nbar;foo;host\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\na2a6df7e6bd818894e1f60ac3c393901b512ca1cf1061ba602dace3fb38c19a6" + }, + { + "description": "Headers should be trimmed", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=collapsed%3Bhost%3Bleading%3Btabs%3Btrailing&X-Goog-Signature=75d77a3ed2d9b74ff7e1e23b2fd7cc714ad4cc32518c65f3a8197827cd87d302623bab990cf2ff3a633bfaae69b6c2d897add78c105aa68411229610421c4239579add4aff6bdbd5067a0fd61c3aa0029d7de0f8ae88fa3458fa70f875e841d6df9598597d9012b9f848c6857e08f2704ca2f332c71738490ffdda2ed928f9340549d7295745725062d28dc1696eab7cb3b88ac4fd445e951423f645d680a60dd8033d65b65f4c10286f59f4258dbb2bcf36a76ffdd40574104cbbf0b76901c24df5854f24c42e9192fcedc386d85704fec6a6bad3a5201e1fb6c491a4c43371b0913420743580daf3504e99204c6ec894b4d70cd27bc60c3fe2850e8bf3ed22", + "headers": { + "collapsed": "abc def", + "leading": " xyz", + "trailing": "abc ", + "tabs": "\tabc\t\t\t\tdef\t" + }, + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=collapsed%3Bhost%3Bleading%3Btabs%3Btrailing\ncollapsed:abc def\nhost:storage.googleapis.com\nleading:xyz\ntabs:abc def\ntrailing:abc\n\ncollapsed;host;leading;tabs;trailing\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n19153e83555808dbfeb8969043cc8ce8d5db0cce91dc11fb9df58b8130f09d42" + }, + { + "description": "Header value with multiple inline values", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bmultiple&X-Goog-Signature=5cc113735625341f59c7203f0c2c9febc95ba6af6b9c38814f8e523214712087dc0996e4960d273ae1889f248ac1e58d4d19cb3a69ad7670e9a8ca1b434e878f59339dc7006cf32dfd715337e9f593e0504371839174962a08294586e0c78160a7aa303397888c8350637c6af3b32ac310886cc4590bfda9ca561ee58fb5b8ec56bc606d2ada6e7df31f4276e9dcb96bcaea39dc2cd096f3fad774f9c4b30e317ad43736c05f76831437f44e8726c1e90d3f6c9827dc273f211f32fc85658dfc5d357eb606743a6b00a29e519eef1bebaf9db3e8f4b1f5f9afb648ad06e60bc42fa8b57025056697c874c9ea76f5a73201c9717ea43e54713ff3502ff3fc626b", + "headers": { + "multiple": " xyz , abc, def , xyz " + }, + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bmultiple\nhost:storage.googleapis.com\nmultiple:xyz , abc, def , xyz\n\nhost;multiple\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n4df8e486146c31f1c8cd4e4c730554cde4326791ba48ec11fa969a3de064cd7f" + }, + { + "description": "Customer-supplied encryption key", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bx-goog-encryption-algorithm%3Bx-goog-encryption-key%3Bx-goog-encryption-key-sha256&X-Goog-Signature=278a1c5a3bad248637054a047014760353942433955871031ed08f515b54588654ad033e91f046ab202b68673030e117d1b786c325e870238b035ba75b3feed560a17aff9bab6bddebd4a31a52cb68b214e27d3b0bd886502c6b36b164306fe88b5a07c6063592afe746b2a5d205dbe90dd5386b94f0a78f75d9f53ee884e18f476e8fc2eb1dd910ce0b4ae1f5d7b09876ef9bf983f539c028429e14bad3c75dbd4ed1ae37856f6d6f8a1805eaf8b52a0d6fc993902e4c1ee8de477661f7b67c3663000474cb00e178189789b2a3ed6bd21b4ade684fca8108ac4dd106acb17f5954d045775f7aa5a98ebda5d3075e11a8ea49c64c6ad1481e463e8c9f11f704", + "headers": { + "X-Goog-Encryption-Algorithm": "AES256", + "X-Goog-Encryption-Key": "key", + "X-Goog-Encryption-Key-Sha256": "key-hash" + }, + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bx-goog-encryption-algorithm%3Bx-goog-encryption-key%3Bx-goog-encryption-key-sha256\nhost:storage.googleapis.com\nx-goog-encryption-algorithm:AES256\nx-goog-encryption-key:key\nx-goog-encryption-key-sha256:key-hash\n\nhost;x-goog-encryption-algorithm;x-goog-encryption-key;x-goog-encryption-key-sha256\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n66a45104eba8bdd9748723b45cbd54c3f0f6dba337a5deb9fb6a66334223dc06" + }, + { + "description": "List Objects", + "bucket": "test-bucket", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=6dbe94f8e52b2b8a9a476b1c857efa474e09944e2b52b925800316e094a7169d8dbe0df9c0ac08dabb22ac7e827470ceccd65f5a3eadba2a4fb9beebfe37f0d9bb1e552b851fa31a25045bdf019e507f5feb44f061551ef1aeb18dcec0e38ba2e2f77d560a46eaace9c56ed9aa642281301a9d848b0eb30749e34bc7f73a3d596240533466ff9b5f289cd0d4c845c7d96b82a35a5abd0c3aff83e4440ee6873e796087f43545544dc8c01afe1d79c726696b6f555371e491980e7ec145cca0803cf562c38f3fa1d724242f5dea25aac91d74ec9ddd739ff65523627763eaef25cd1f95ad985aaf0079b7c74eb5bcb2870a9b137a7b2c8e41fbe838c95872f75b", + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n51a7426c2a6c6ab80f336855fc629461ff182fb1d2cb552ac68e5ce8e25db487" + }, + { + "description": "Query Parameter Encoding", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&aA0%C3%A9%2F%3D%25-_.~=~%20._-%25%3D%2F%C3%A90Aa&X-Goog-Signature=0e4f289c28626a32af95d78f5a0d2c75e5f0bef1cfe5035a532a8185e3ad45b1d5e8ad5ae0fb1898420e40a1576479861c6579db7e3b28ef8386160995ac1374be85e780ac3dfcc62538e9b2e2c51555950fb6fd0d7ecc509d3ccd9c02af5a6c6eb930d21a7383792300eb50a093a597c1da2a290ed56b01844251f8271d0d5e61fc3f4273a0c26f80e061c06124d93346ea1c50388e3fe73494c05ac27a54caedc04d1476c276c7602554e4cc1933e41df31ea523f4009e879c92333f98b4313755470d7e400bbbde9f5bef36f40b2a1c4a85edbd62aaa84a516e3df055d5d3f575b9ea0f1c24f057240852d9e618403e1dd2cd0fa7fc16b071b07322172256", + "queryParameters": { + "aA0é/=%-_.~": "~ ._-%=/é0Aa" + }, + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&aA0%C3%A9%2F%3D%25-_.~=~%20._-%25%3D%2F%C3%A90Aa\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n448f96c23dafa8210900554e138b2b5fd55bc53ef53b8637cecc3edec45a8fcf" + }, + { + "description": "Query Parameter Ordering", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-Meta-Foo=bar&X-Goog-SignedHeaders=host&prefix=%2Ffoo&X-Goog-Signature=a07745e1b3d59b85cbe11aa766df72c22468959e7217615dccb7f030234f66b60b37e480f30725ed51f29816362ca8286c619ebb66448ff1d370be2a4a48aacf20d3d2d6200ed17341a5791baf2ee5cd9c2823adacc6264f66c8a54fa887e1bce3c55cf78fb2f6a52618cf09d6f945f63d148052a7b66a75e075ff5065828a806b84bdc49a42399be7483225c720d5e18a6160f79d815f433e7921694fe1d041099851793c2581db0e5ca503cfb566e414f900ceede5f9b22030edd32ab20b6f7f9fb2afba89098b9364e03397c03a94eac3a140c99979b8786844fb4f6c62c1985378939dd1bbaea8e41b9100dda85a27733171cc78d96ee362ea2c3432f4d8", + "queryParameters": { + "prefix": "/foo", + "X-Goog-Meta-Foo": "bar" + }, + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-Meta-Foo=bar&X-Goog-SignedHeaders=host&prefix=%2Ffoo\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n4dafe74ad142f32b7c25fc4e6b38fd3b8a6339d7f112247573fb0066f637db6c" + }, + { + "description": "Header Ordering", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bx-goog-date&X-Goog-Signature=55a28435997457f1498291e878fd39c5f321973057d2541886020fdfd212b1467d9eeffdc70951ea952d634cb4193e657ed5b7860c46d37f7d904774680a16e518aa9dff273e8441d6893de615eb592e3113d682ad64a87eb0e0c48df17c30f899e7f940ba230530b30f725ab9ec38789682413752de6a026ae69dd858843100645f3ec986aed618d229f8844d378e0e66e907ede6dff7aac56723f51eb830e8877a56100c86a876173424602abefe6c22b6540a2b36634860b2e89137f297cca8f080bdf3433a9d614c5ab2ec84f65412b45516b30500886a2300f23c3423ae0e91546e3471ee08d06894bddc76203a418d46f35bf0b4574f7b24a693fb046c", + "headers": { + "X-Goog-Date": "20190201T090000Z" + }, + "scheme": "https", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bx-goog-date\nhost:storage.googleapis.com\nx-goog-date:20190201T090000Z\n\nhost;x-goog-date\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n4052143280d90d5f4a8c878ff7418be6fee5d34e50b1da28d8081a094b88fa61" + }, + { + "description": "Signed Payload Instead of UNSIGNED-PAYLOAD", + "bucket": "test-bucket", + "object": "test-object", + "method": "PUT", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bx-goog-content-sha256%3Bx-testcasemetadata-payload-value&X-Goog-Signature=3e5a9669e9aa162888dff1553d24c159bad4f16d444987f6a1b26d8ad0cb7927f15bfaf79c205324d2138fd1f62edb255430c77a03c0d6e9601399e2519014f9e1a7051d9be735cde530022c84602b1c4c25c86cb1e1584489e49d511c9a618a1a8443af31626ca5b2ad105eda1e4499f52b4043f3c1a3bd40c06c0cae36bb19a50ed8671e5d2cdbb148a196ce5a8c14d6970c08225da293e1ef400c92e7a3d5ba0a29ad0893827c96b203a04b04ebd51929bf99b323beba93097dfee700ee2c1bd97013779e5c8f156e56175d4d07e453b2eb0d616086f9f4753dde63507efe88b0dec29c872d25d9465f07778b16b532814148c578ee7e64ed8437006fa551", + "headers": { + "X-Goog-Content-SHA256": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b982", + "X-TestCaseMetadata-Payload-Value": "hello" + }, + "scheme": "https", + "expectedCanonicalRequest": "PUT\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host%3Bx-goog-content-sha256%3Bx-testcasemetadata-payload-value\nhost:storage.googleapis.com\nx-goog-content-sha256:2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b982\nx-testcasemetadata-payload-value:hello\n\nhost;x-goog-content-sha256;x-testcasemetadata-payload-value\n2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b982", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\nbe21a0841a897930ff5cf72e6e74ec5274efd76c3fe4cde6678f24a0a3d6dbec" + }, + { + "description": "Virtual Hosted Style", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://test-bucket.storage.googleapis.com/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=06c633ea060b0eda81ee58dd3337b01b0d243a44f18cb03ec948861f533a129e579c7fd4c856d187f1c7b86e5715ea0abf6a1c6ba32b69274d22b1b0406df6847dc87f0d289fe8dc0682351574849b8b13e4b66922f39441af96becb73ea4c56cd5e3eeb30bc91fe84e8bd205adca8639253bdb65b2fcaf2598a230c6d8f6d8177c9e58a61b6e826767f594056b490184d676897c4bbedc15d6fbf08c3fa82a406c62e74db661e6c5d7d3ced29e0619ee719dce4b8136360345b8dce120b9f1debd511c8dac3e6d874ee05bfda8c8f1c4fedd0c07fc6d98f5f18a349bb204d8ff401402a025194e2792df8a09282141157e4ca51d26a8d0d142a01c805321911", + "scheme": "https", + "urlStyle": "VIRTUAL_HOSTED_STYLE", + "expectedCanonicalRequest": "GET\n/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:test-bucket.storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n89eeae48258eccdcb1f592fb908008e3f5d36a949c002c1e614c94356dc18fc6" + }, + { + "description": "HTTP Bucket Bound Hostname Support", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "http://mydomain.tld/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=7115a77f8c7ed1a8b74bca8b520904fca7f3bab90d69ea052687a94efd9b3a4e2a7fb7135d40e295e0a21958194c55da7e106227957c22ed6edc9d8b3d2a8133bc8af84fc9695dda8081d53f0db5ea9f28e5bfc225d78f873e9f571fd287bb7a95330e726aebd8eb4623cdb0b1a7ceb210b2ce1351b6be0191c2ad7b38f7ceb6c5ce2f98dbfb5a5a649050585e46e97f72f1f5407de657a56e34a3fdc80cdaa0598bd47f3e8af5ff22d0916b19b106890bff8c3f6587f1d3b076b16cd0ba0508607a672be33b9c75d537e15258450b43d22a21c4d528090acbb8e5bae7b31fc394e61394106ef1d6a8ed43074ab05bcec65674cd8113fb3de388da4d97e62f56", + "scheme": "http", + "urlStyle": "BUCKET_BOUND_HOSTNAME", + "bucketBoundHostname": "mydomain.tld", + "expectedCanonicalRequest": "GET\n/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:mydomain.tld\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\nd6c309924b51a5abbe4d6356f7bf29c2120c6b14649b1e97b3bc9309adca7d4b" + }, + { + "description": "HTTPS Bucket Bound Hostname Support", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://mydomain.tld/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=7115a77f8c7ed1a8b74bca8b520904fca7f3bab90d69ea052687a94efd9b3a4e2a7fb7135d40e295e0a21958194c55da7e106227957c22ed6edc9d8b3d2a8133bc8af84fc9695dda8081d53f0db5ea9f28e5bfc225d78f873e9f571fd287bb7a95330e726aebd8eb4623cdb0b1a7ceb210b2ce1351b6be0191c2ad7b38f7ceb6c5ce2f98dbfb5a5a649050585e46e97f72f1f5407de657a56e34a3fdc80cdaa0598bd47f3e8af5ff22d0916b19b106890bff8c3f6587f1d3b076b16cd0ba0508607a672be33b9c75d537e15258450b43d22a21c4d528090acbb8e5bae7b31fc394e61394106ef1d6a8ed43074ab05bcec65674cd8113fb3de388da4d97e62f56", + "scheme": "https", + "urlStyle": "BUCKET_BOUND_HOSTNAME", + "bucketBoundHostname": "mydomain.tld", + "expectedCanonicalRequest": "GET\n/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:mydomain.tld\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\nd6c309924b51a5abbe4d6356f7bf29c2120c6b14649b1e97b3bc9309adca7d4b" + }, + { + "description": "Simple GET with hostname", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=95e6a13d43a1d1962e667f17397f2b80ac9bdd1669210d5e08e0135df9dff4e56113485dbe429ca2266487b9d1796ebdee2d7cf682a6ef3bb9fbb4c351686fba90d7b621cf1c4eb1fdf126460dd25fa0837dfdde0a9fd98662ce60844c458448fb2b352c203d9969cb74efa4bdb742287744a4f2308afa4af0e0773f55e32e92973619249214b97283b2daa14195244444e33f938138d1e5f561088ce8011f4986dda33a556412594db7c12fc40e1ff3f1bedeb7a42f5bcda0b9567f17f65855f65071fabb88ea12371877f3f77f10e1466fff6ff6973b74a933322ff0949ce357e20abe96c3dd5cfab42c9c83e740a4d32b9e11e146f0eb3404d2e975896f74", + "scheme": "https", + "hostname": "storage.googleapis.com", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Simple GET with non-default hostname", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "http://localhost:8080/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=66c8c0371ca7d933a0d50f110abdf4fc7e3e379329134f272ebe4aa8100ccd5f21cd56ca5ccffae5ed36c8d6840e7cac80c2e7d786cd85b10d0faea34cddf09d2e7eb7f5c7c53934e4bf8f5cd654bc3c1b5ee9e3f8ca2189cd225b445bb866563fc4bd0d0b4d116111655611d12ec18f2d854fd7142d9afcc977dbd8f6d0524e4170506abf2b119bbe00d17697321d225162fabddb4ddae77781b4f3277a6b6fccfeb47d70b88537e5efb416001274aaeb1535b5aae757c997edc66d03898a5d08f767313d018d10992981d00e2a18ed9a6839b8a1ac7b3be1cab2e9511ba91e14a786443b59e9f21e1ae74a2c60106180646a764531fbe1fcd9c1e40550e56e", + "scheme": "http", + "hostname": "localhost:8080", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Simple GET with endpoint on client", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.googleapis.com:443/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=95e6a13d43a1d1962e667f17397f2b80ac9bdd1669210d5e08e0135df9dff4e56113485dbe429ca2266487b9d1796ebdee2d7cf682a6ef3bb9fbb4c351686fba90d7b621cf1c4eb1fdf126460dd25fa0837dfdde0a9fd98662ce60844c458448fb2b352c203d9969cb74efa4bdb742287744a4f2308afa4af0e0773f55e32e92973619249214b97283b2daa14195244444e33f938138d1e5f561088ce8011f4986dda33a556412594db7c12fc40e1ff3f1bedeb7a42f5bcda0b9567f17f65855f65071fabb88ea12371877f3f77f10e1466fff6ff6973b74a933322ff0949ce357e20abe96c3dd5cfab42c9c83e740a4d32b9e11e146f0eb3404d2e975896f74", + "scheme": "https", + "clientEndpoint": "storage.googleapis.com:443", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Endpoint on client with scheme", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "http://localhost:8080/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=66c8c0371ca7d933a0d50f110abdf4fc7e3e379329134f272ebe4aa8100ccd5f21cd56ca5ccffae5ed36c8d6840e7cac80c2e7d786cd85b10d0faea34cddf09d2e7eb7f5c7c53934e4bf8f5cd654bc3c1b5ee9e3f8ca2189cd225b445bb866563fc4bd0d0b4d116111655611d12ec18f2d854fd7142d9afcc977dbd8f6d0524e4170506abf2b119bbe00d17697321d225162fabddb4ddae77781b4f3277a6b6fccfeb47d70b88537e5efb416001274aaeb1535b5aae757c997edc66d03898a5d08f767313d018d10992981d00e2a18ed9a6839b8a1ac7b3be1cab2e9511ba91e14a786443b59e9f21e1ae74a2c60106180646a764531fbe1fcd9c1e40550e56e", + "scheme": "http", + "clientEndpoint": "http://localhost:8080", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Emulator host", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://xyz.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=53b20003ff2c552b3194a6bccc25024663662392554b3334e989e2704f3a0308455eaacf45c335a78c0186a5cf8eef78bf5781a7267465d28a35c9e1291f87ff340e9ee40b3b9bdce70561bf000887ce38ccd7d2445a8749453960a8f11d37576dfd5942f92d6f4527bbeffb90526b5de9653b6ca16136e9f19bcb65d984ddaf22c4ade45d6a168bb4752a43de33ab121206f50d994612824407711bff720cb1b207b61b613c44c85d3ce16dc4fc6eba24e494e176b0780d0ab85a800b13fcbf31434ddf51992efae1efde330ebda0617d1c20078ef22a4f10a7bcbed961237442d9a8db78d7aeb777a4994b50efdd41e07c4966e912a30f92a7426f207e9545", + "emulatorHostname": "https://xyz.googleapis.com", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Endpoint on client takes precedence over emulator", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "http://localhost:8080/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=66c8c0371ca7d933a0d50f110abdf4fc7e3e379329134f272ebe4aa8100ccd5f21cd56ca5ccffae5ed36c8d6840e7cac80c2e7d786cd85b10d0faea34cddf09d2e7eb7f5c7c53934e4bf8f5cd654bc3c1b5ee9e3f8ca2189cd225b445bb866563fc4bd0d0b4d116111655611d12ec18f2d854fd7142d9afcc977dbd8f6d0524e4170506abf2b119bbe00d17697321d225162fabddb4ddae77781b4f3277a6b6fccfeb47d70b88537e5efb416001274aaeb1535b5aae757c997edc66d03898a5d08f767313d018d10992981d00e2a18ed9a6839b8a1ac7b3be1cab2e9511ba91e14a786443b59e9f21e1ae74a2c60106180646a764531fbe1fcd9c1e40550e56e", + "scheme": "http", + "clientEndpoint": "http://localhost:8080", + "emulatorHostname": "https://xyz.googleapis.com", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Hostname takes precendence over endpoint and emulator", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://xyz.googleapis.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=53b20003ff2c552b3194a6bccc25024663662392554b3334e989e2704f3a0308455eaacf45c335a78c0186a5cf8eef78bf5781a7267465d28a35c9e1291f87ff340e9ee40b3b9bdce70561bf000887ce38ccd7d2445a8749453960a8f11d37576dfd5942f92d6f4527bbeffb90526b5de9653b6ca16136e9f19bcb65d984ddaf22c4ade45d6a168bb4752a43de33ab121206f50d994612824407711bff720cb1b207b61b613c44c85d3ce16dc4fc6eba24e494e176b0780d0ab85a800b13fcbf31434ddf51992efae1efde330ebda0617d1c20078ef22a4f10a7bcbed961237442d9a8db78d7aeb777a4994b50efdd41e07c4966e912a30f92a7426f207e9545", + "emulatorHostname": "http://localhost:9000", + "clientEndpoint": "http://localhost:8080", + "hostname": "https://xyz.googleapis.com", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Universe domain", + "bucket": "test-bucket", + "object": "test-object", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://storage.domain.com/test-bucket/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=8cd0d479a88fb7d791a2dcc8fc5b5f020ca817eeef5b5a5cb3260eb63cf47ecd271faa238d0fa31efca35bc2a9244bd122178c520749f922c0235726a5a6be099bf4f33a0d54187eee2e0208964c2a13104b03e235cdeb4f07b3eb566b8a33259cf7540a3fe823be601ace2a54a79acd6834cb646380c4cfc7ef0fd95d3ebbc1f97d840f6fe1dceed4269ecb4e91ff7e6633f38adab82049a965968367b9e7c362cec868d804bd42abbb6d2e837ce5d45ee9e1d92c7acc09623acaae3df6128ca15f9f80bb6543944e8c997f691c35113b9e9f44e86fd343524343b08dd8f887685588acc103e0b432f24912e7e1c63e086aeed1890e41b75beb64164fe6bfcf", + "universeDomain": "domain.com", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + }, + { + "description": "Universe domain with virtual hosted style", + "bucket": "test-bucket", + "object": "test-object", + "urlStyle": "VIRTUAL_HOSTED_STYLE", + "method": "GET", + "expiration": 10, + "timestamp": "2019-02-01T09:00:00Z", + "expectedUrl": "https://test-bucket.storage.domain.com/test-object?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host&X-Goog-Signature=25820e3a60856596cba594511d7d4039239b2728a9738f15d3a7acce8d70aa5435d0c91f99a9318f932afc73355ac562e014cb654e16ed5524b403536f1cba74489701fdc0c088b8826fccf20a648d3b2b704bd6661e01786d4132174c21441d0752be07e8af93e84e24b87799ee91fabef24a0a58d0889263280c3d37423fab677bd4d98469ab01aa36efaad62ff81ca27bf7fc92f14e20faa71e34de9ffbc5eb4ecf1b0361de42270665bb78367bd0a8cc6a604a8e347f0c864754bf14514aac3106fe73572a6c068ce2c380cc2a943b35502093d162ba9ae8de9abbbc9541ef765d5679857a89d36cc01be30cf1e04c4a477bbcd59a02955dcc1a903d8baa", + "universeDomain": "domain.com", + "expectedCanonicalRequest": "GET\n/test-bucket/test-object\nX-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=test-iam-credentials%40dummy-project-id.iam.gserviceaccount.com%2F20190201%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20190201T090000Z&X-Goog-Expires=10&X-Goog-SignedHeaders=host\nhost:storage.googleapis.com\n\nhost\nUNSIGNED-PAYLOAD", + "expectedStringToSign": "GOOG4-RSA-SHA256\n20190201T090000Z\n20190201/auto/storage/goog4_request\n00e2fb794ea93d7adb703edaebdd509821fcc7d4f1a79ac5c8d2b394df109320" + } + ], + "postPolicyV4Tests": [ + { + "description": "POST Policy Simple", + "policyInput": { + "scheme": "https", + "bucket": "rsaposttest-1579902670-h3q7wvodjor6bc7y", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z" + }, + "policyOutput": { + "url": "https://storage.googleapis.com/rsaposttest-1579902670-h3q7wvodjor6bc7y/", + "fields": { + "key": "test-object", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "9eb947e08891be62a6c26d214c5b639506a57c20e1242a135dce45326a821aa9d8eaf5a8b6961a7ba87ab4da09668eb303b615dabdd6344970a024d4697aa3c467ec527cb8318d6c971782c6f82555c8cdd791589226962f0c26d5c415bf9d257cf9ed266a43e1b74891c35f009be741cef42a1eec150ffa5783de217e3704e8f278209250423f62c57864c50c6e525e6e9b724fcafc3844898c6a219effedfaf1204cb95eb135f63307db86726b8d6c12b8a75df61f93143b5e798acdffee0b5ad481075fa89a9d49a470cea339e5e43b61a0d87ef54f355dc401a659b583e7906c20bf84b8da7941d2e932acab21ffe92416985262fe772a117483b6e70410", + "policy": "eyJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJyc2Fwb3N0dGVzdC0xNTc5OTAyNjcwLWgzcTd3dm9kam9yNmJjN3kifSx7ImtleSI6InRlc3Qtb2JqZWN0In0seyJ4LWdvb2ctZGF0ZSI6IjIwMjAwMTIzVDA0MzUzMFoifSx7IngtZ29vZy1jcmVkZW50aWFsIjoidGVzdC1pYW0tY3JlZGVudGlhbHNAZHVtbXktcHJvamVjdC1pZC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbS8yMDIwMDEyMy9hdXRvL3N0b3JhZ2UvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIwLTAxLTIzVDA0OjM1OjQwWiJ9" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"bucket\":\"rsaposttest-1579902670-h3q7wvodjor6bc7y\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy Simple Virtual Hosted Style", + "policyInput": { + "scheme": "https", + "urlStyle": "VIRTUAL_HOSTED_STYLE", + "bucket": "rsaposttest-1579902670-h3q7wvodjor6bc7y", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z" + }, + "policyOutput": { + "url": "https://rsaposttest-1579902670-h3q7wvodjor6bc7y.storage.googleapis.com/", + "fields": { + "key": "test-object", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "9eb947e08891be62a6c26d214c5b639506a57c20e1242a135dce45326a821aa9d8eaf5a8b6961a7ba87ab4da09668eb303b615dabdd6344970a024d4697aa3c467ec527cb8318d6c971782c6f82555c8cdd791589226962f0c26d5c415bf9d257cf9ed266a43e1b74891c35f009be741cef42a1eec150ffa5783de217e3704e8f278209250423f62c57864c50c6e525e6e9b724fcafc3844898c6a219effedfaf1204cb95eb135f63307db86726b8d6c12b8a75df61f93143b5e798acdffee0b5ad481075fa89a9d49a470cea339e5e43b61a0d87ef54f355dc401a659b583e7906c20bf84b8da7941d2e932acab21ffe92416985262fe772a117483b6e70410", + "policy": "eyJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJyc2Fwb3N0dGVzdC0xNTc5OTAyNjcwLWgzcTd3dm9kam9yNmJjN3kifSx7ImtleSI6InRlc3Qtb2JqZWN0In0seyJ4LWdvb2ctZGF0ZSI6IjIwMjAwMTIzVDA0MzUzMFoifSx7IngtZ29vZy1jcmVkZW50aWFsIjoidGVzdC1pYW0tY3JlZGVudGlhbHNAZHVtbXktcHJvamVjdC1pZC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbS8yMDIwMDEyMy9hdXRvL3N0b3JhZ2UvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIwLTAxLTIzVDA0OjM1OjQwWiJ9" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"bucket\":\"rsaposttest-1579902670-h3q7wvodjor6bc7y\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy Simple Bucket Bound Hostname", + "policyInput": { + "scheme": "https", + "urlStyle": "BUCKET_BOUND_HOSTNAME", + "bucketBoundHostname": "mydomain.tld", + "bucket": "rsaposttest-1579902670-h3q7wvodjor6bc7y", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z" + }, + "policyOutput": { + "url": "https://mydomain.tld/", + "fields": { + "key": "test-object", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "9eb947e08891be62a6c26d214c5b639506a57c20e1242a135dce45326a821aa9d8eaf5a8b6961a7ba87ab4da09668eb303b615dabdd6344970a024d4697aa3c467ec527cb8318d6c971782c6f82555c8cdd791589226962f0c26d5c415bf9d257cf9ed266a43e1b74891c35f009be741cef42a1eec150ffa5783de217e3704e8f278209250423f62c57864c50c6e525e6e9b724fcafc3844898c6a219effedfaf1204cb95eb135f63307db86726b8d6c12b8a75df61f93143b5e798acdffee0b5ad481075fa89a9d49a470cea339e5e43b61a0d87ef54f355dc401a659b583e7906c20bf84b8da7941d2e932acab21ffe92416985262fe772a117483b6e70410", + "policy": "eyJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJyc2Fwb3N0dGVzdC0xNTc5OTAyNjcwLWgzcTd3dm9kam9yNmJjN3kifSx7ImtleSI6InRlc3Qtb2JqZWN0In0seyJ4LWdvb2ctZGF0ZSI6IjIwMjAwMTIzVDA0MzUzMFoifSx7IngtZ29vZy1jcmVkZW50aWFsIjoidGVzdC1pYW0tY3JlZGVudGlhbHNAZHVtbXktcHJvamVjdC1pZC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbS8yMDIwMDEyMy9hdXRvL3N0b3JhZ2UvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIwLTAxLTIzVDA0OjM1OjQwWiJ9" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"bucket\":\"rsaposttest-1579902670-h3q7wvodjor6bc7y\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy Simple Bucket Bound Hostname HTTP", + "policyInput": { + "scheme": "http", + "urlStyle": "BUCKET_BOUND_HOSTNAME", + "bucketBoundHostname": "mydomain.tld", + "bucket": "rsaposttest-1579902670-h3q7wvodjor6bc7y", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z" + }, + "policyOutput": { + "url": "http://mydomain.tld/", + "fields": { + "key": "test-object", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "9eb947e08891be62a6c26d214c5b639506a57c20e1242a135dce45326a821aa9d8eaf5a8b6961a7ba87ab4da09668eb303b615dabdd6344970a024d4697aa3c467ec527cb8318d6c971782c6f82555c8cdd791589226962f0c26d5c415bf9d257cf9ed266a43e1b74891c35f009be741cef42a1eec150ffa5783de217e3704e8f278209250423f62c57864c50c6e525e6e9b724fcafc3844898c6a219effedfaf1204cb95eb135f63307db86726b8d6c12b8a75df61f93143b5e798acdffee0b5ad481075fa89a9d49a470cea339e5e43b61a0d87ef54f355dc401a659b583e7906c20bf84b8da7941d2e932acab21ffe92416985262fe772a117483b6e70410", + "policy": "eyJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJyc2Fwb3N0dGVzdC0xNTc5OTAyNjcwLWgzcTd3dm9kam9yNmJjN3kifSx7ImtleSI6InRlc3Qtb2JqZWN0In0seyJ4LWdvb2ctZGF0ZSI6IjIwMjAwMTIzVDA0MzUzMFoifSx7IngtZ29vZy1jcmVkZW50aWFsIjoidGVzdC1pYW0tY3JlZGVudGlhbHNAZHVtbXktcHJvamVjdC1pZC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbS8yMDIwMDEyMy9hdXRvL3N0b3JhZ2UvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIwLTAxLTIzVDA0OjM1OjQwWiJ9" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"bucket\":\"rsaposttest-1579902670-h3q7wvodjor6bc7y\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy ACL matching", + "policyInput": { + "scheme": "https", + "bucket": "rsaposttest-1579902662-x2kd7kjwh2w5izcw", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z", + "conditions": { + "startsWith": [ + "$acl", + "public" + ] + } + }, + "policyOutput": { + "url": "https://storage.googleapis.com/rsaposttest-1579902662-x2kd7kjwh2w5izcw/", + "fields": { + "key": "test-object", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "134b88d3d7ed57fd7ba79fe53b52191f2ccf46bde0ed1b1fe1557025dc76388fab367b55e887e7a2a23425c98c72d5d1095700568ca5e71f0bd38042b8d94ace6d75bce2c17760b53a8af7706944fd9f382b3a78c9651d9214a5d6252f099c18a759cd98f8dd3e32ac024d5e1b63d4c01d44954d4e943254f3a4cc4cab74cd251a733d4794a22e5840993b6d2970aa050f403c68c25019e91d133d47ff7188facf13560f918ae8efe49ec9ebcc4080d141154554f65cc6d9d6ef0e8bc12119c7491800d79769b5f27707ea9fe78c7af3c39df82608ca78f6f60b638510fd45a14404ed0224365c7ea45b839d91db99a7f8af50a64b754817318fae7bb94b3574", + "policy": "eyJjb25kaXRpb25zIjpbWyJzdGFydHMtd2l0aCIsIiRhY2wiLCJwdWJsaWMiXSx7ImJ1Y2tldCI6InJzYXBvc3R0ZXN0LTE1Nzk5MDI2NjIteDJrZDdrandoMnc1aXpjdyJ9LHsia2V5IjoidGVzdC1vYmplY3QifSx7IngtZ29vZy1kYXRlIjoiMjAyMDAxMjNUMDQzNTMwWiJ9LHsieC1nb29nLWNyZWRlbnRpYWwiOiJ0ZXN0LWlhbS1jcmVkZW50aWFsc0BkdW1teS1wcm9qZWN0LWlkLmlhbS5nc2VydmljZWFjY291bnQuY29tLzIwMjAwMTIzL2F1dG8vc3RvcmFnZS9nb29nNF9yZXF1ZXN0In0seyJ4LWdvb2ctYWxnb3JpdGhtIjoiR09PRzQtUlNBLVNIQTI1NiJ9XSwiZXhwaXJhdGlvbiI6IjIwMjAtMDEtMjNUMDQ6MzU6NDBaIn0=" + }, + "expectedDecodedPolicy": "{\"conditions\":[[\"starts-with\",\"$acl\",\"public\"],{\"bucket\":\"rsaposttest-1579902662-x2kd7kjwh2w5izcw\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy Within Content-Range", + "policyInput": { + "scheme": "https", + "bucket": "rsaposttest-1579902672-lpd47iogn6hx4sle", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z", + "conditions": { + "contentLengthRange": [ + 246, + 266 + ] + } + }, + "policyOutput": { + "url": "https://storage.googleapis.com/rsaposttest-1579902672-lpd47iogn6hx4sle/", + "fields": { + "key": "test-object", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "7f81e41a67c60dda3578c3e4f6457692e9cdb7b920da30204de893dac10e625fabea5f8002c8e1891bedc47e6136c8a012dbb8df4e532aea3e186b6c98050cdaf8d82d6cf01495ed87d97af6909589e456cd4d1a624462166cdd4c3bb3a6f945a69d69768bef4d8542add6c2971c3d9993af805f9e4cf2ad8abc69cf8dc3a99eb658eb51030d84037583a5991de29cad34edf7c0d88f6e904f8a00b86022394cc35e9552ed7bdcec3f04e46165952f78cd8bfcabb2def569b6076d0009f6ccc79b94fd67497481711dea1351e82f9e2626c9de374c81aa418000bff039f97367d021afb85d228230b4f3cd5ffe58ccb140bebc62a34e45fc42ba75aec4335035", + "policy": "eyJjb25kaXRpb25zIjpbWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMjQ2LDI2Nl0seyJidWNrZXQiOiJyc2Fwb3N0dGVzdC0xNTc5OTAyNjcyLWxwZDQ3aW9nbjZoeDRzbGUifSx7ImtleSI6InRlc3Qtb2JqZWN0In0seyJ4LWdvb2ctZGF0ZSI6IjIwMjAwMTIzVDA0MzUzMFoifSx7IngtZ29vZy1jcmVkZW50aWFsIjoidGVzdC1pYW0tY3JlZGVudGlhbHNAZHVtbXktcHJvamVjdC1pZC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbS8yMDIwMDEyMy9hdXRvL3N0b3JhZ2UvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIwLTAxLTIzVDA0OjM1OjQwWiJ9" + }, + "expectedDecodedPolicy": "{\"conditions\":[[\"content-length-range\",246,266],{\"bucket\":\"rsaposttest-1579902672-lpd47iogn6hx4sle\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy Cache-Control File Header", + "policyInput": { + "scheme": "https", + "bucket": "rsaposttest-1579902669-nwk5s7vvfjgdjs62", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z", + "fields": { + "acl": "public-read", + "cache-control": "public,max-age=86400" + } + }, + "policyOutput": { + "url": "https://storage.googleapis.com/rsaposttest-1579902669-nwk5s7vvfjgdjs62/", + "fields": { + "key": "test-object", + "acl": "public-read", + "cache-control": "public,max-age=86400", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "99f29892dca68c13a1a9939392efa0891e68def63376ee6de4cf978e1537fcf79e1f8ef8ed068bc00a1c6a311fafbcc95eee5ad59aee502fe443b06905a6942f04e9f516e6bdd4162571b989a45378850d0721956a1808d5f4e3d531b6c20c654886b6910acd4c334127f78f8e6bfcb38ed82c65ecd2b0283e4e17275cbae40c43619ccecfe47cea81dad5ec180bbebc239c1c323af6719df4916e85db2b0a7f9a931ccb8ffe4d6f23899359339593c92f246be884324a1959327a5108a88f48da5be22444c943ff58493b3d1579f4dc734a7b14b3759b8e4a9350666e55e187a3b14f8b6388cf474ec8b7c7ed67cd5e21d0e13c1cf09884fdf5deb045b8bb6f", + "policy": "eyJjb25kaXRpb25zIjpbeyJhY2wiOiJwdWJsaWMtcmVhZCJ9LHsiY2FjaGUtY29udHJvbCI6InB1YmxpYyxtYXgtYWdlPTg2NDAwIn0seyJidWNrZXQiOiJyc2Fwb3N0dGVzdC0xNTc5OTAyNjY5LW53azVzN3Z2ZmpnZGpzNjIifSx7ImtleSI6InRlc3Qtb2JqZWN0In0seyJ4LWdvb2ctZGF0ZSI6IjIwMjAwMTIzVDA0MzUzMFoifSx7IngtZ29vZy1jcmVkZW50aWFsIjoidGVzdC1pYW0tY3JlZGVudGlhbHNAZHVtbXktcHJvamVjdC1pZC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbS8yMDIwMDEyMy9hdXRvL3N0b3JhZ2UvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIwLTAxLTIzVDA0OjM1OjQwWiJ9" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"acl\":\"public-read\"},{\"cache-control\":\"public,max-age=86400\"},{\"bucket\":\"rsaposttest-1579902669-nwk5s7vvfjgdjs62\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy Success With Status", + "policyInput": { + "scheme": "https", + "bucket": "rsaposttest-1579902678-pt5yms55j47r6qy4", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z", + "fields": { + "success_action_status": "200" + } + }, + "policyOutput": { + "url": "https://storage.googleapis.com/rsaposttest-1579902678-pt5yms55j47r6qy4/", + "fields": { + "key": "test-object", + "success_action_status": "200", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "4b93fb02fa09f8eca92fc27eaa79028ae56c4b61fef83715833ebf7601607dbee627d6101e078881e4b24d795e9e2062ddb7b01470a742b9f6b1aac5c7b7c86d17bf298259189fd6ae0d6ae952b993a6a9f4eaf218bcc462d8dbc0b8553ca4d00349714e1143655a8eed18b02c71e9e53558055976cf3dc58f5946c9e9d6bda9305eed0575f7be80abff41d7a02fe2ab9a2abe87ab7040314734c1179e3a8edb0a024f227509391ca1ef4705140252a1a0bd6022096e9ef0ef5789639bce5953d5c4595b81b262768dbbfe2b7f68e3ebd2cf42f746897fe7c0ac8ec08c6cb85db8b1737a98d25bfa4a4022be72c4e17a1687856c1020b4fdd9438e91949437be", + "policy": "eyJjb25kaXRpb25zIjpbeyJzdWNjZXNzX2FjdGlvbl9zdGF0dXMiOiIyMDAifSx7ImJ1Y2tldCI6InJzYXBvc3R0ZXN0LTE1Nzk5MDI2NzgtcHQ1eW1zNTVqNDdyNnF5NCJ9LHsia2V5IjoidGVzdC1vYmplY3QifSx7IngtZ29vZy1kYXRlIjoiMjAyMDAxMjNUMDQzNTMwWiJ9LHsieC1nb29nLWNyZWRlbnRpYWwiOiJ0ZXN0LWlhbS1jcmVkZW50aWFsc0BkdW1teS1wcm9qZWN0LWlkLmlhbS5nc2VydmljZWFjY291bnQuY29tLzIwMjAwMTIzL2F1dG8vc3RvcmFnZS9nb29nNF9yZXF1ZXN0In0seyJ4LWdvb2ctYWxnb3JpdGhtIjoiR09PRzQtUlNBLVNIQTI1NiJ9XSwiZXhwaXJhdGlvbiI6IjIwMjAtMDEtMjNUMDQ6MzU6NDBaIn0=" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"success_action_status\":\"200\"},{\"bucket\":\"rsaposttest-1579902678-pt5yms55j47r6qy4\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy Success With Redirect", + "policyInput": { + "scheme": "https", + "bucket": "rsaposttest-1579902671-6ldm6caw4se52vrx", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z", + "fields": { + "success_action_redirect": "http://www.google.com/" + } + }, + "policyOutput": { + "url": "https://storage.googleapis.com/rsaposttest-1579902671-6ldm6caw4se52vrx/", + "fields": { + "key": "test-object", + "success_action_redirect": "http://www.google.com/", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "6e83c57e73b1794eb6c5903a1eebdb5c29b0adc333010a5cd623fcb1a9716a31c680c94d43fd9f1f18134b864c380c78f8c1ab048038e743f9da080148365acaa01374dc7aa626cc93c73010a67b79c6776faf5edb8eb7ad56c8f9b9c998a1dab7ea1de675f2b315951c4ca2f54a3d21570896aaa66d8980ed09adf4e4240b49478bdabdaf51b720124569e94b1918856893c14c119c529fcb2e01838198b5d18042994d180fd4b9e26aef1d97fe5646c328e15a05decf6005e1c64cb7783811811f4cd5a720cbd6aa4cfc27ac81fc0b163ee9719c53af5019fd2be83b87e0da6d285f0270bc94f1e8788993794c309745c22709ee0dbad0e463f06830aabbbf", + "policy": "eyJjb25kaXRpb25zIjpbeyJzdWNjZXNzX2FjdGlvbl9yZWRpcmVjdCI6Imh0dHA6Ly93d3cuZ29vZ2xlLmNvbS8ifSx7ImJ1Y2tldCI6InJzYXBvc3R0ZXN0LTE1Nzk5MDI2NzEtNmxkbTZjYXc0c2U1MnZyeCJ9LHsia2V5IjoidGVzdC1vYmplY3QifSx7IngtZ29vZy1kYXRlIjoiMjAyMDAxMjNUMDQzNTMwWiJ9LHsieC1nb29nLWNyZWRlbnRpYWwiOiJ0ZXN0LWlhbS1jcmVkZW50aWFsc0BkdW1teS1wcm9qZWN0LWlkLmlhbS5nc2VydmljZWFjY291bnQuY29tLzIwMjAwMTIzL2F1dG8vc3RvcmFnZS9nb29nNF9yZXF1ZXN0In0seyJ4LWdvb2ctYWxnb3JpdGhtIjoiR09PRzQtUlNBLVNIQTI1NiJ9XSwiZXhwaXJhdGlvbiI6IjIwMjAtMDEtMjNUMDQ6MzU6NDBaIn0=" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"success_action_redirect\":\"http://www.google.com/\"},{\"bucket\":\"rsaposttest-1579902671-6ldm6caw4se52vrx\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy Character Escaping", + "policyInput": { + "scheme": "https", + "bucket": "rsaposttest-1579902671-6ldm6caw4se52vrx", + "object": "$test-object-é", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z", + "fields": { + "success_action_redirect": "http://www.google.com/", + "x-goog-meta-custom-1": "$test-object-é-metadata" + } + }, + "policyOutput": { + "url": "https://storage.googleapis.com/rsaposttest-1579902671-6ldm6caw4se52vrx/", + "fields": { + "key": "$test-object-é", + "success_action_redirect": "http://www.google.com/", + "x-goog-meta-custom-1": "$test-object-é-metadata", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "a79ab836c4a36c3cd1dd3253c9482e2bb65ab461ac61fccee8757169da32c77f07a0da4c47745314fc9fba24d93679c864bb197e6eff26caddf3099b72db962451131afa969bf901d6d4ef63db3e36d48af4040b743b37ab8a08174e63cb5da39082490c03a8a28f7ede43f847a8f4447bb82b73434a1bcd365c8e6f62ae09a7b30a0706745787542a919096632840925d5677f668800220e6dbe83c8a42dc8343c85c16499b7179b96a677cfb35af6cf0face1b0409f40f41fd159df50d9fe4dd915439bd34d98ae22f4e2376e6b6c86654abe147083f2766fa75cc2cee9241f0ea5bcb8daa431712952f1038e7c596568500d80834957988be69560de5ce5d", + "policy": "eyJjb25kaXRpb25zIjpbeyJzdWNjZXNzX2FjdGlvbl9yZWRpcmVjdCI6Imh0dHA6Ly93d3cuZ29vZ2xlLmNvbS8ifSx7IngtZ29vZy1tZXRhLWN1c3RvbS0xIjoiJHRlc3Qtb2JqZWN0LVx1MDBlOS1tZXRhZGF0YSJ9LHsiYnVja2V0IjoicnNhcG9zdHRlc3QtMTU3OTkwMjY3MS02bGRtNmNhdzRzZTUydnJ4In0seyJrZXkiOiIkdGVzdC1vYmplY3QtXHUwMGU5In0seyJ4LWdvb2ctZGF0ZSI6IjIwMjAwMTIzVDA0MzUzMFoifSx7IngtZ29vZy1jcmVkZW50aWFsIjoidGVzdC1pYW0tY3JlZGVudGlhbHNAZHVtbXktcHJvamVjdC1pZC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbS8yMDIwMDEyMy9hdXRvL3N0b3JhZ2UvZ29vZzRfcmVxdWVzdCJ9LHsieC1nb29nLWFsZ29yaXRobSI6IkdPT0c0LVJTQS1TSEEyNTYifV0sImV4cGlyYXRpb24iOiIyMDIwLTAxLTIzVDA0OjM1OjQwWiJ9" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"success_action_redirect\":\"http://www.google.com/\"},{\"x-goog-meta-custom-1\":\"$test-object-\u00e9-metadata\"},{\"bucket\":\"rsaposttest-1579902671-6ldm6caw4se52vrx\"},{\"key\":\"$test-object-\u00e9\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + }, + { + "description": "POST Policy With Additional Metadata", + "policyInput": { + "scheme": "https", + "bucket": "rsaposttest-1579902671-6ldm6caw4se52vrx", + "object": "test-object", + "expiration": 10, + "timestamp": "2020-01-23T04:35:30Z", + "fields": { + "content-disposition": "attachment; filename=\"~._-%=/é0Aa\"", + "content-encoding": "gzip", + "content-type": "text/plain", + "success_action_redirect": "http://www.google.com/" + } + }, + "policyOutput": { + "url": "https://storage.googleapis.com/rsaposttest-1579902671-6ldm6caw4se52vrx/", + "fields": { + "content-disposition": "attachment; filename=\"~._-%=/é0Aa\"", + "content-encoding": "gzip", + "content-type": "text/plain", + "key": "test-object", + "success_action_redirect": "http://www.google.com/", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "x-goog-credential": "test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request", + "x-goog-date": "20200123T043530Z", + "x-goog-signature": "10e881a484d257672192a50892f7373ef243e1ff0e9043e47b3487d8280e4a27e85b0b16a60e5f9f539fc04c5b6141ca8a568fd2b66555000061cad696d6841cb31dc78862dbf0f66b7d55e72156c21a2ffa116923f86df523e4b16ef686acb46bc2665a7827c5dfafc26d7a6919ffea7f2d7803aa61f93d6389731adface622a848e663b5106858754e06e1a63d55feca12d814e1bcbcf5c42cd573950f53c0e9aa9bf2e746aa1287d0a293e07c24cf15698d42f11639cbd385ba8d9fc7db17dffdcab6d4b4be2e2219f7b98a58303294087858c120a0bc550bad31e4f101615066b9e946f0d54bcd7ae8e1306608b539213c809c13deae16a2a5d62b2e9cb7", + "policy": "eyJjb25kaXRpb25zIjpbeyJjb250ZW50LWRpc3Bvc2l0aW9uIjoiYXR0YWNobWVudDsgZmlsZW5hbWU9XCJ+Ll8tJT0vXHUwMGU5MEFhXCIifSx7ImNvbnRlbnQtZW5jb2RpbmciOiJnemlwIn0seyJjb250ZW50LXR5cGUiOiJ0ZXh0L3BsYWluIn0seyJzdWNjZXNzX2FjdGlvbl9yZWRpcmVjdCI6Imh0dHA6Ly93d3cuZ29vZ2xlLmNvbS8ifSx7ImJ1Y2tldCI6InJzYXBvc3R0ZXN0LTE1Nzk5MDI2NzEtNmxkbTZjYXc0c2U1MnZyeCJ9LHsia2V5IjoidGVzdC1vYmplY3QifSx7IngtZ29vZy1kYXRlIjoiMjAyMDAxMjNUMDQzNTMwWiJ9LHsieC1nb29nLWNyZWRlbnRpYWwiOiJ0ZXN0LWlhbS1jcmVkZW50aWFsc0BkdW1teS1wcm9qZWN0LWlkLmlhbS5nc2VydmljZWFjY291bnQuY29tLzIwMjAwMTIzL2F1dG8vc3RvcmFnZS9nb29nNF9yZXF1ZXN0In0seyJ4LWdvb2ctYWxnb3JpdGhtIjoiR09PRzQtUlNBLVNIQTI1NiJ9XSwiZXhwaXJhdGlvbiI6IjIwMjAtMDEtMjNUMDQ6MzU6NDBaIn0=" + }, + "expectedDecodedPolicy": "{\"conditions\":[{\"content-disposition\":\"attachment; filename=\\\"~._-%=/é0Aa\\\"\"},{\"content-encoding\":\"gzip\"},{\"content-type\":\"text/plain\"},{\"success_action_redirect\":\"http://www.google.com/\"},{\"bucket\":\"rsaposttest-1579902671-6ldm6caw4se52vrx\"},{\"key\":\"test-object\"},{\"x-goog-date\":\"20200123T043530Z\"},{\"x-goog-credential\":\"test-iam-credentials@dummy-project-id.iam.gserviceaccount.com/20200123/auto/storage/goog4_request\"},{\"x-goog-algorithm\":\"GOOG4-RSA-SHA256\"}],\"expiration\":\"2020-01-23T04:35:40Z\"}" + } + } + ] +} diff --git a/handwritten/storage/conformance-test/testBenchUtil.ts b/handwritten/storage/conformance-test/testBenchUtil.ts new file mode 100644 index 00000000000..b66f8309458 --- /dev/null +++ b/handwritten/storage/conformance-test/testBenchUtil.ts @@ -0,0 +1,54 @@ +/*! + * Copyright 2021 Google LLC. All Rights Reserved. + * + * 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 {execSync} from 'child_process'; +import {unlinkSync, writeFileSync} from 'fs'; +import {URL} from 'url'; + +const HOST = process.env.STORAGE_EMULATOR_HOST || 'http://localhost:9000'; +const PORT = new URL(HOST).port; +const CONTAINER_NAME = 'storage-testbench'; +const DEFAULT_IMAGE_NAME = + 'gcr.io/cloud-devrel-public-resources/storage-testbench'; +const DEFAULT_IMAGE_TAG = 'v0.35.0'; +const DOCKER_IMAGE = `${DEFAULT_IMAGE_NAME}:${DEFAULT_IMAGE_TAG}`; +const PULL_CMD = `docker pull ${DOCKER_IMAGE}`; +const RUN_CMD = `docker run --rm -d -p ${PORT}:${PORT} --name ${CONTAINER_NAME} ${DOCKER_IMAGE} && sleep 1`; +const STOP_CMD = `docker stop ${CONTAINER_NAME};`; + +export async function getTestBenchDockerImage(): Promise { + return execSync(PULL_CMD); +} + +export async function runTestBenchDockerImage(): Promise { + return execSync(RUN_CMD); +} + +export async function stopTestBenchDockerImage(): Promise { + return execSync(STOP_CMD); +} + +export function createTestBuffer(sizeInBytes: number): Buffer { + return Buffer.alloc(sizeInBytes, 'testdata'); +} + +export function createTestFileFromBuffer(sizeInMb: number, path: string): void { + const buf = createTestBuffer(sizeInMb); + writeFileSync(path, buf); +} + +export function deleteTestFile(path: string): void { + unlinkSync(path); +} diff --git a/handwritten/storage/conformance-test/v4SignedUrl.ts b/handwritten/storage/conformance-test/v4SignedUrl.ts new file mode 100644 index 00000000000..ecf378bd7d6 --- /dev/null +++ b/handwritten/storage/conformance-test/v4SignedUrl.ts @@ -0,0 +1,287 @@ +/*! + * Copyright 2019 Google LLC. All Rights Reserved. + * + * 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 * as assert from 'assert'; +import {describe, it} from 'mocha'; +import * as fs from 'fs'; +import {OutgoingHttpHeaders} from 'http'; +import * as path from 'path'; +import * as sinon from 'sinon'; +import * as querystring from 'querystring'; + +import {Storage, GenerateSignedPostPolicyV4Options} from '../src/'; +import * as url from 'url'; +import {getDirName} from '../src/util.js'; + +export enum UrlStyle { + PATH_STYLE = 'PATH_STYLE', + VIRTUAL_HOSTED_STYLE = 'VIRTUAL_HOSTED_STYLE', + BUCKET_BOUND_HOSTNAME = 'BUCKET_BOUND_HOSTNAME', +} + +interface V4SignedURLTestCase { + description: string; + hostname?: string; + emulatorHostname?: string; + clientEndpoint?: string; + universeDomain?: string; + bucket: string; + object?: string; + urlStyle?: keyof typeof UrlStyle; + bucketBoundHostname?: string; + scheme?: 'https' | 'http'; + headers?: OutgoingHttpHeaders; + queryParameters?: {[key: string]: string}; + method: string; + expiration: number; + timestamp: string; + expectedUrl: string; + expectedCanonicalRequest: string; + expectedStringToSign: string; +} + +interface V4SignedPolicyTestCase { + description: string; + policyInput: PolicyInput; + policyOutput: PolicyOutput; +} + +interface PolicyInput { + scheme: 'https' | 'http'; + bucket: string; + object: string; + expiration: number; + timestamp: string; + urlStyle?: UrlStyle; + bucketBoundHostname?: string; + conditions?: Conditions; + fields?: {[key: string]: string}; +} + +interface Conditions { + contentLengthRange: [number, number]; + startsWith: [string, string]; + acl: string; +} + +interface PolicyOutput { + url: string; + fields: {[key: string]: string}; + expectedDecodedPolicy: string; +} + +interface FileAction { + [key: string]: 'read' | 'resumable' | 'write' | 'delete'; +} + +interface BucketAction { + [key: string]: 'list'; +} + +const testFile = fs.readFileSync( + path.join( + getDirName(), + '../../../conformance-test/test-data/v4SignedUrl.json' + ), + 'utf-8' +); + +const testCases = JSON.parse(testFile); +const v4SignedUrlCases: V4SignedURLTestCase[] = testCases.signingV4Tests; +const v4SignedPolicyCases: V4SignedPolicyTestCase[] = + testCases.postPolicyV4Tests; + +const SERVICE_ACCOUNT = path.join( + getDirName(), + '../../../conformance-test/fixtures/signing-service-account.json' +); + +let storage: Storage; + +describe('v4 conformance test', () => { + let fakeTimer: sinon.SinonFakeTimers; + + beforeEach(() => { + delete process.env.STORAGE_EMULATOR_HOST; + }); + + afterEach(() => { + fakeTimer.restore(); + }); + + describe('v4 signed url', () => { + v4SignedUrlCases.forEach(testCase => { + it(testCase.description, async () => { + const NOW = new Date(testCase.timestamp); + fakeTimer = sinon.useFakeTimers(NOW); + + if (testCase.emulatorHostname) { + process.env.STORAGE_EMULATOR_HOST = testCase.emulatorHostname; + } + + storage = new Storage({ + keyFilename: SERVICE_ACCOUNT, + apiEndpoint: testCase.clientEndpoint, + universeDomain: testCase.universeDomain, + }); + + const bucket = storage.bucket(testCase.bucket); + const expires = NOW.valueOf() + testCase.expiration * 1000; + const version = 'v4' as const; + const host = testCase.hostname + ? new URL( + (testCase.scheme ? testCase.scheme + '://' : '') + + testCase.hostname + ) + : undefined; + const origin = testCase.bucketBoundHostname + ? `${testCase.scheme}://${testCase.bucketBoundHostname}` + : undefined; + const {bucketBoundHostname, virtualHostedStyle} = parseUrlStyle( + testCase.urlStyle, + origin + ); + const extensionHeaders = testCase.headers; + const queryParams = testCase.queryParameters; + const baseConfig = { + extensionHeaders, + version, + expires, + cname: bucketBoundHostname, + virtualHostedStyle, + queryParams, + host, + } as const; + let signedUrl: string; + + if (testCase.object) { + const file = bucket.file(testCase.object); + + const action = ( + { + GET: 'read', + POST: 'resumable', + PUT: 'write', + DELETE: 'delete', + } as FileAction + )[testCase.method]; + + [signedUrl] = await file.getSignedUrl({ + action, + ...baseConfig, + }); + } else { + // bucket operation + const action = ( + { + GET: 'list', + } as BucketAction + )[testCase.method]; + + [signedUrl] = await bucket.getSignedUrl({ + action, + ...baseConfig, + }); + } + + const expected = new url.URL(testCase.expectedUrl); + const actual = new url.URL(signedUrl); + + assert.strictEqual(actual.origin, expected.origin); + assert.strictEqual(actual.pathname, expected.pathname); + // Order-insensitive comparison of query params + assert.deepStrictEqual( + querystring.parse(actual.search), + querystring.parse(expected.search) + ); + }); + }); + }); + + describe('v4 signed policy', () => { + v4SignedPolicyCases.forEach(testCase => { + it(testCase.description, async () => { + const input = testCase.policyInput; + const NOW = new Date(input.timestamp); + fakeTimer = sinon.useFakeTimers(NOW); + + storage = new Storage({ + keyFilename: SERVICE_ACCOUNT, + }); + + const bucket = storage.bucket(input.bucket); + const expires = NOW.valueOf() + input.expiration * 1000; + const options: GenerateSignedPostPolicyV4Options = { + expires, + }; + + const conditions: (string | number)[][] = []; + if (input.conditions) { + if (input.conditions.startsWith) { + const variable = input.conditions.startsWith[0]; + const prefix = input.conditions.startsWith[1]; + conditions.push(['starts-with', variable, prefix]); + } + + if (input.conditions.contentLengthRange) { + const min = input.conditions.contentLengthRange[0]; + const max = input.conditions.contentLengthRange[1]; + conditions.push(['content-length-range', min, max]); + } + } + + const origin = input.bucketBoundHostname + ? `${input.scheme}://${input.bucketBoundHostname}` + : undefined; + const {bucketBoundHostname, virtualHostedStyle} = parseUrlStyle( + input.urlStyle, + origin + ); + options.virtualHostedStyle = virtualHostedStyle; + options.bucketBoundHostname = bucketBoundHostname; + options.fields = input.fields; + options.conditions = conditions; + + const file = bucket.file(input.object); + const [policy] = await file.generateSignedPostPolicyV4(options); + + assert.strictEqual(policy.url, testCase.policyOutput.url); + const outputFields = testCase.policyOutput.fields; + const decodedPolicy = JSON.parse( + Buffer.from(policy.fields.policy, 'base64').toString() + ); + assert.deepStrictEqual( + decodedPolicy, + JSON.parse(testCase.policyOutput.expectedDecodedPolicy) + ); + + assert.deepStrictEqual(policy.fields, outputFields); + }); + }); + }); +}); + +function parseUrlStyle( + style?: keyof typeof UrlStyle, + origin?: string +): {bucketBoundHostname?: string; virtualHostedStyle?: boolean} { + if (style === UrlStyle.BUCKET_BOUND_HOSTNAME) { + return {bucketBoundHostname: origin}; + } else if (style === UrlStyle.VIRTUAL_HOSTED_STYLE) { + return {virtualHostedStyle: true}; + } else { + return {virtualHostedStyle: false}; + } +} diff --git a/handwritten/storage/internal-tooling/README.md b/handwritten/storage/internal-tooling/README.md new file mode 100644 index 00000000000..9a40bb4c97a --- /dev/null +++ b/handwritten/storage/internal-tooling/README.md @@ -0,0 +1,43 @@ +# nodejs-storage benchmarking + +**This is not a supported Google product** + +This benchmarking script intended for use by Storage client library maintainers to benchmark various workloads and collect metrics in order to improve performance of the library. Currently the benchmarking runs a Write-1-Read-3 workload and measures throughput. + +## Run example: +This runs 10K iterations of Write-1-Read-3 on 5KiB to 2GiB files, and generates output to a CSV file: +```bash +$ cd nodejs-storage +$ npm install +$ cd build/internal-tooling +$ node performanceTest.js --iterations 10000 +``` + +## CLI parameters + +| Parameter | Description | Possible values | Default | +| --------- | ----------- | --------------- |:-------:| +| --iterations | number of iterations to run | any positive integer | `100` | +| --numthreads | number of threads to run | any positive integer | `1` | +| --bucket | bucket to upload/download to/from | any string bucket name | `nodejs-perf-metrics` | +| --small | number of bytes for lower bound file size | any positive integer | `5120` | +| --large | number of bytes for upper bound file size | any positive integer | `2.147e9` | +| --projectid | project ID to use | any string project ID | `undefined` | + + +## Workload definition and CSV headers + +For each invocation of the benchmark, write a new object of random size between `small` and `large` . After the successful write, download the object in full three times. For each of the 4 operations record the following fields: + +| Field | Description | +| ----- | ----------- | +| Op | the name of the operations (WRITE, READ[{0,1,2}]) | +| ObjectSize | the number of bytes of the object | +| LibBufferSize | configured to use the library default of 100 MiB | +| Crc32cEnabled | whether crc32c was computed for the operation | +| MD5Enabled | whether MD5 was computed for the operation | +| ApiName | default to JSON| +| ElapsedTimeUs | the elapsed time in microseconds the operation took | +| Status | completion state of the operation [OK, FAIL] | +| AppBufferSize | N/A | +| CpuTimeUs | N/A | \ No newline at end of file diff --git a/handwritten/storage/internal-tooling/helpers/package.cjs.json b/handwritten/storage/internal-tooling/helpers/package.cjs.json new file mode 100644 index 00000000000..6a0d2ef2aa8 --- /dev/null +++ b/handwritten/storage/internal-tooling/helpers/package.cjs.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} \ No newline at end of file diff --git a/handwritten/storage/internal-tooling/performApplicationPerformanceTest.ts b/handwritten/storage/internal-tooling/performApplicationPerformanceTest.ts new file mode 100644 index 00000000000..eedcda1f604 --- /dev/null +++ b/handwritten/storage/internal-tooling/performApplicationPerformanceTest.ts @@ -0,0 +1,191 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable n/no-unsupported-features/node-builtins */ +import yargs from 'yargs'; +import {promises as fsp, rmSync} from 'fs'; +import { + Bucket, + DownloadOptions, + DownloadResponse, + UploadOptions, + UploadResponse, +} from '../src/index.js'; +import {performance} from 'perf_hooks'; +import {parentPort} from 'worker_threads'; +import { + NODE_DEFAULT_HIGHWATER_MARK_BYTES, + generateRandomDirectoryStructure, + getValidationType, + performanceTestSetup, + TestResult, + performanceTestCommand, + getLowHighFileSize, + PERFORMANCE_TEST_TYPES, +} from './performanceUtils.js'; + +const TEST_NAME_STRING = 'nodejs-perf-metrics-application'; + +let bucket: Bucket; + +const checkType = getValidationType(); + +const argv = yargs(process.argv.slice(2)) + .command(performanceTestCommand) + .parseSync(); + +/** + * Main entry point. This function performs a test iteration and posts the message back + * to the parent thread. + */ +async function main() { + let result: TestResult | undefined = undefined; + + ({bucket} = await performanceTestSetup( + argv.project! as string, + argv.bucket! as string, + )); + + switch (argv.test_type) { + case PERFORMANCE_TEST_TYPES.APPLICATION_UPLOAD_MULTIPLE_OBJECTS: + result = await performWriteTest(); + break; + case PERFORMANCE_TEST_TYPES.APPLICATION_DOWNLOAD_MULTIPLE_OBJECTS: + result = await performReadTest(); + break; + // case TRANSFER_MANAGER_TEST_TYPES.APPLICATION_LARGE_FILE_DOWNLOAD: + // result = await performLargeReadTest(); + // break; + default: + break; + } + parentPort?.postMessage(result); +} + +async function uploadInParallel( + bucket: Bucket, + paths: string[], + options: UploadOptions, +) { + const promises: Promise[] = []; + for (const index in paths) { + const path = paths[index]; + const stat = await fsp.lstat(path); + if (stat.isDirectory()) { + continue; + } + options.destination = path; + promises.push(bucket.upload(path, options)); + } + await Promise.all(promises).catch(console.error); +} + +async function downloadInParallel(bucket: Bucket, options: DownloadOptions) { + const promises: Promise[] = []; + const [files] = await bucket.getFiles(); + files.forEach(file => { + promises.push(file.download(options)); + }); + await Promise.all(promises).catch(console.error); +} + +/** + * Performs an iteration of the Write multiple objects test. + * + * @returns {Promise} Promise that resolves to a test result of an iteration. + */ +async function performWriteTest(): Promise { + await bucket.deleteFiles(); //start clean + + const fileSizeRange = getLowHighFileSize(argv.object_size as string); + const creationInfo = generateRandomDirectoryStructure( + argv.num_objects as number, + TEST_NAME_STRING, + fileSizeRange.low, + fileSizeRange.high, + ); + + const start = performance.now(); + await uploadInParallel(bucket, creationInfo.paths, {validation: checkType}); + const end = performance.now(); + + await bucket.deleteFiles(); //cleanup files + rmSync(TEST_NAME_STRING, {recursive: true, force: true}); + + const result: TestResult = { + op: 'WRITE', + objectSize: creationInfo.totalSizeInBytes, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: checkType === 'crc32c', + md5Enabled: checkType === 'md5', + api: 'JSON', + elapsedTimeUs: Math.round((end - start) * 1000), + cpuTimeUs: -1, + status: 'OK', + chunkSize: creationInfo.totalSizeInBytes, + workers: argv.workers as number, + library: 'nodejs', + transferSize: creationInfo.totalSizeInBytes, + transferOffset: 0, + bucketName: bucket.name, + }; + return result; +} + +/** + * Performs an iteration of the read multiple objects test. + * + * @returns {Promise} Promise that resolves to an array of test results for the iteration. + */ +async function performReadTest(): Promise { + const fileSizeRange = getLowHighFileSize(argv.object_size as string); + await bucket.deleteFiles(); // start clean + const creationInfo = generateRandomDirectoryStructure( + argv.num_objects as number, + TEST_NAME_STRING, + fileSizeRange.low, + fileSizeRange.high, + ); + await uploadInParallel(bucket, creationInfo.paths, {validation: checkType}); + + const start = performance.now(); + await downloadInParallel(bucket, {validation: checkType}); + const end = performance.now(); + + const result: TestResult = { + op: 'READ[0]', + objectSize: creationInfo.totalSizeInBytes, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: checkType === 'crc32c', + md5Enabled: checkType === 'md5', + api: 'JSON', + elapsedTimeUs: Math.round((end - start) * 1000), + cpuTimeUs: -1, + status: 'OK', + chunkSize: creationInfo.totalSizeInBytes, + workers: argv.workers as number, + library: 'nodejs', + transferSize: creationInfo.totalSizeInBytes, + transferOffset: 0, + bucketName: bucket.name, + }; + + rmSync(TEST_NAME_STRING, {recursive: true, force: true}); + await bucket.deleteFiles({force: true}); //cleanup + return result; +} + +main(); diff --git a/handwritten/storage/internal-tooling/performPerformanceTest.ts b/handwritten/storage/internal-tooling/performPerformanceTest.ts new file mode 100644 index 00000000000..82fda1c9f73 --- /dev/null +++ b/handwritten/storage/internal-tooling/performPerformanceTest.ts @@ -0,0 +1,217 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 yargs from 'yargs'; +import {performance} from 'perf_hooks'; +import {parentPort} from 'worker_threads'; +import * as path from 'path'; +import { + cleanupFile, + generateRandomFile, + generateRandomFileName, + getLowHighFileSize, + getValidationType, + NODE_DEFAULT_HIGHWATER_MARK_BYTES, + performanceTestCommand, + performanceTestSetup, + PERFORMANCE_TEST_TYPES, + TestResult, +} from './performanceUtils.js'; +import {Bucket} from '../src/index.js'; +import {getDirName} from '../src/util.js'; + +const TEST_NAME_STRING = 'nodejs-perf-metrics'; +const DEFAULT_NUMBER_OF_WRITES = 1; +const DEFAULT_NUMBER_OF_READS = 3; +const DEFAULT_RANGE_READS = 3; + +let bucket: Bucket; +const checkType = getValidationType(); + +const argv = yargs(process.argv.slice(2)) + .command(performanceTestCommand) + .parseSync(); + +/** + * Main entry point. This function performs a test iteration and posts the message back + * to the parent thread. + */ +async function main() { + let results: TestResult[] = []; + + ({bucket} = await performanceTestSetup( + argv.project! as string, + argv.bucket! as string, + )); + + switch (argv.test_type) { + case PERFORMANCE_TEST_TYPES.WRITE_ONE_READ_THREE: + results = await performWriteReadTest(); + break; + case PERFORMANCE_TEST_TYPES.RANGE_READ: + results = await performRangedReadTest(); + break; + default: + break; + } + + parentPort?.postMessage(results); +} + +/** + * Performs an iteration of a ranged read test. Only the last result will be reported. + * + * @returns {Promise} Promise that resolves to an array of test results for the iteration. + */ +async function performRangedReadTest(): Promise { + const results: TestResult[] = []; + const fileSizeRange = getLowHighFileSize(argv.object_size as string); + const fileName = generateRandomFileName(TEST_NAME_STRING); + generateRandomFile( + fileName, + fileSizeRange.low, + fileSizeRange.high, + getDirName(), + ); + const file = bucket.file(`${fileName}`); + const destinationFileName = generateRandomFileName(TEST_NAME_STRING); + const destination = path.join(getDirName(), destinationFileName); + + const iterationResult: TestResult = { + op: 'READ[0]', + objectSize: argv.range_read_size as number, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: false, + md5Enabled: false, + api: 'JSON', + elapsedTimeUs: 0, + cpuTimeUs: -1, + status: 'OK', + chunkSize: argv.range_read_size as number, + workers: argv.workers as number, + library: 'nodejs', + transferSize: argv.range_read_size as number, + transferOffset: 0, + bucketName: bucket.name, + }; + + await bucket.upload(`${getDirName()}/${fileName}`); + cleanupFile(fileName); + + for (let i = 0; i < DEFAULT_RANGE_READS; i++) { + const start = performance.now(); + await file.download({ + start: 0, + end: argv.range_read_size as number, + destination, + }); + const end = performance.now(); + cleanupFile(destinationFileName); + iterationResult.elapsedTimeUs = Math.round((end - start) * 1000); + } + + await file.delete({ignoreNotFound: true}); + results.push(iterationResult); + return results; +} + +/** + * Performs an iteration of the Write 1 / Read 3 performance measuring test. + * + * @returns {Promise} Promise that resolves to an array of test results for the iteration. + */ +async function performWriteReadTest(): Promise { + const results: TestResult[] = []; + const fileSizeRange = getLowHighFileSize(argv.object_size as string); + const fileName = generateRandomFileName(TEST_NAME_STRING); + const file = bucket.file(`${fileName}`); + const sizeInBytes = generateRandomFile( + fileName, + fileSizeRange.low, + fileSizeRange.high, + getDirName(), + ); + + for (let j = 0; j < DEFAULT_NUMBER_OF_WRITES; j++) { + let start = 0; + let end = 0; + + const iterationResult: TestResult = { + op: 'WRITE', + objectSize: sizeInBytes, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: checkType === 'crc32c', + md5Enabled: checkType === 'md5', + api: 'JSON', + elapsedTimeUs: 0, + cpuTimeUs: -1, + status: 'OK', + chunkSize: sizeInBytes, + workers: argv.workers as number, + library: 'nodejs', + transferSize: sizeInBytes, + transferOffset: 0, + bucketName: bucket.name, + }; + + start = performance.now(); + await bucket.upload(`${getDirName()}/${fileName}`, {validation: checkType}); + end = performance.now(); + + iterationResult.elapsedTimeUs = Math.round((end - start) * 1000); + results.push(iterationResult); + cleanupFile(fileName); + } + + const iterationResult: TestResult = { + op: 'READ[0]', + objectSize: sizeInBytes, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: checkType === 'crc32c', + md5Enabled: checkType === 'md5', + api: 'JSON', + elapsedTimeUs: 0, + cpuTimeUs: -1, + status: 'OK', + chunkSize: sizeInBytes, + workers: argv.workers as number, + library: 'nodejs', + transferSize: sizeInBytes, + transferOffset: 0, + bucketName: bucket.name, + }; + + for (let j = 0; j < DEFAULT_NUMBER_OF_READS; j++) { + let start = 0; + let end = 0; + + const destinationFileName = generateRandomFileName(TEST_NAME_STRING); + const destination = path.join(getDirName(), destinationFileName); + + start = performance.now(); + await file.download({validation: checkType, destination}); + end = performance.now(); + + cleanupFile(destinationFileName); + iterationResult.elapsedTimeUs = Math.round((end - start) * 1000); + } + + await file.delete({ignoreNotFound: true}); + results.push(iterationResult); + return results; +} + +main(); diff --git a/handwritten/storage/internal-tooling/performTransferManagerTest.ts b/handwritten/storage/internal-tooling/performTransferManagerTest.ts new file mode 100644 index 00000000000..6e21e774630 --- /dev/null +++ b/handwritten/storage/internal-tooling/performTransferManagerTest.ts @@ -0,0 +1,279 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable n/no-unsupported-features/node-builtins */ +import yargs from 'yargs'; +import {parentPort} from 'worker_threads'; +import {Bucket, File, TransferManager} from '../src/index.js'; +import { + cleanupFile, + generateRandomDirectoryStructure, + generateRandomFile, + generateRandomFileName, + getValidationType, + NODE_DEFAULT_HIGHWATER_MARK_BYTES, + performanceTestSetup, + TestResult, + performanceTestCommand, + getLowHighFileSize, + PERFORMANCE_TEST_TYPES, +} from './performanceUtils.js'; +import {performance} from 'perf_hooks'; +import {rmSync} from 'fs'; +import * as path from 'path'; +import {getDirName} from '../src/util.js'; + +const TEST_NAME_STRING = 'tm-perf-metrics'; +const DIRECTORY_PROBABILITY = 0.1; + +let bucket: Bucket; +let transferManager: TransferManager; +const checkType = getValidationType(); + +const argv = yargs(process.argv.slice(2)) + .command(performanceTestCommand) + .parseSync(); + +/** + * Main entry point. This function performs a test iteration and posts the message back + * to the parent thread. + */ +async function main() { + let results: TestResult[] = []; + + ({bucket, transferManager} = await performanceTestSetup( + argv.project! as string, + argv.bucket! as string, + )); + + switch (argv.test_type) { + case PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_UPLOAD_MANY_FILES: + results = await performUploadManyFilesTest(); + break; + case PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_DOWNLOAD_MANY_FILES: + results = await performDownloadManyFilesTest(); + break; + case PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_CHUNKED_FILE_DOWNLOAD: + results = await performChunkUploadDownloadTest(); + break; + default: + break; + } + parentPort?.postMessage(results); +} + +/** + * Cleans up after a test is complete by removing files from the bucket + */ +async function performTestCleanup(fileOrFiles: File[] | File | string[]) { + const filesToDelete = Array.isArray(fileOrFiles) + ? fileOrFiles + : [fileOrFiles]; + const promises = filesToDelete.map(f => { + let fileToDelete = f; + if (typeof f === 'string') { + fileToDelete = bucket.file(f); + } + (fileToDelete as File).delete({ignoreNotFound: true}); + }); + return Promise.all(promises); +} + +/** + * Performs a test where multiple objects are uploaded in parallel to a bucket. + * + * @returns {Promise} A promise that resolves containing information about the test results. + */ +async function performUploadManyFilesTest(): Promise { + const fileSizeRange = getLowHighFileSize(argv.object_size as string); + const creationInfo = generateRandomDirectoryStructure( + argv.num_objects as number, + TEST_NAME_STRING, + fileSizeRange.low, + fileSizeRange.high, + DIRECTORY_PROBABILITY, + ); + + const start = performance.now(); + await transferManager.uploadManyFiles(creationInfo.paths, { + concurrencyLimit: argv.workers as number, + passthroughOptions: { + validation: checkType, + }, + }); + const end = performance.now(); + + rmSync(TEST_NAME_STRING, {recursive: true, force: true}); + + const result: TestResult = { + op: 'WRITE', + objectSize: creationInfo.totalSizeInBytes, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: checkType === 'crc32c', + md5Enabled: checkType === 'md5', + api: 'JSON', + elapsedTimeUs: Math.round((end - start) * 1000), + cpuTimeUs: -1, + status: 'OK', + chunkSize: creationInfo.totalSizeInBytes, + workers: argv.workers as number, + library: 'nodejs', + transferSize: creationInfo.totalSizeInBytes, + transferOffset: 0, + bucketName: bucket.name, + }; + + await performTestCleanup(creationInfo.paths); + + return [result]; +} + +/** + * Performs a test where multiple objects are downloaded in parallel from a bucket. + * + * @returns {Promise} A promise that resolves containing information about the test results. + */ +async function performDownloadManyFilesTest(): Promise { + const fileSizeRange = getLowHighFileSize(argv.object_size as string); + const creationInfo = generateRandomDirectoryStructure( + argv.num_objects as number, + TEST_NAME_STRING, + fileSizeRange.low, + fileSizeRange.high, + DIRECTORY_PROBABILITY, + ); + + await transferManager.uploadManyFiles(creationInfo.paths, { + concurrencyLimit: argv.workers as number, + passthroughOptions: { + validation: checkType, + }, + }); + const start = performance.now(); + await transferManager.downloadManyFiles(TEST_NAME_STRING, { + prefix: path.join(getDirName(), '..', '..'), + concurrencyLimit: argv.workers as number, + passthroughOptions: { + validation: checkType, + }, + }); + const end = performance.now(); + + rmSync(TEST_NAME_STRING, {recursive: true, force: true}); + + const result: TestResult = { + op: 'READ[0]', + objectSize: creationInfo.totalSizeInBytes, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: checkType === 'crc32c', + md5Enabled: checkType === 'md5', + api: 'JSON', + elapsedTimeUs: Math.round((end - start) * 1000), + cpuTimeUs: -1, + status: 'OK', + chunkSize: creationInfo.totalSizeInBytes, + workers: argv.workers as number, + library: 'nodejs', + transferSize: creationInfo.totalSizeInBytes, + transferOffset: 0, + bucketName: bucket.name, + }; + + await performTestCleanup(creationInfo.paths); + + return [result]; +} + +/** + * Performs a test where a large file is uploaded and downloaded as chunks in parallel. + * + * @returns {Promise} A promise that resolves containing information about the test results. + */ +async function performChunkUploadDownloadTest(): Promise { + const results: TestResult[] = []; + const fileSizeRange = getLowHighFileSize(argv.object_size as string); + const fileName = generateRandomFileName(TEST_NAME_STRING); + const sizeInBytes = generateRandomFile( + fileName, + fileSizeRange.low, + fileSizeRange.high, + getDirName(), + ); + const file = bucket.file(`${fileName}`); + let result: TestResult = { + op: 'WRITE', + objectSize: sizeInBytes, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: checkType === 'crc32c', + md5Enabled: false, + api: 'JSON', + elapsedTimeUs: -1, + cpuTimeUs: -1, + status: 'OK', + chunkSize: argv.range_read_size as number, + workers: argv.workers as number, + library: 'nodejs', + transferSize: sizeInBytes, + transferOffset: 0, + bucketName: bucket.name, + }; + + let start = performance.now(); + await transferManager.uploadFileInChunks(`${getDirName()}/${fileName}`, { + concurrencyLimit: argv.workers as number, + chunkSizeBytes: argv.range_read_size as number, + }); + let end = performance.now(); + result.elapsedTimeUs = Math.round((end - start) * 1000); + results.push(result); + cleanupFile(fileName); + + start = performance.now(); + await transferManager.downloadFileInChunks(file, { + concurrencyLimit: argv.workers as number, + chunkSizeBytes: argv.range_read_size as number, + destination: path.join(getDirName(), fileName), + validation: checkType === 'crc32c' ? checkType : false, + }); + end = performance.now(); + + cleanupFile(fileName); + + result = { + op: 'READ[0]', + objectSize: sizeInBytes, + appBufferSize: NODE_DEFAULT_HIGHWATER_MARK_BYTES, + crc32cEnabled: checkType === 'crc32c', + md5Enabled: false, + api: 'JSON', + elapsedTimeUs: Math.round((end - start) * 1000), + cpuTimeUs: -1, + status: 'OK', + chunkSize: argv.range_read_size as number, + workers: argv.workers as number, + library: 'nodejs', + transferSize: sizeInBytes, + transferOffset: 0, + bucketName: bucket.name, + }; + results.push(result); + + await performTestCleanup(file); + + return results; +} + +main(); diff --git a/handwritten/storage/internal-tooling/performanceTest.ts b/handwritten/storage/internal-tooling/performanceTest.ts new file mode 100644 index 00000000000..02adc10f76f --- /dev/null +++ b/handwritten/storage/internal-tooling/performanceTest.ts @@ -0,0 +1,133 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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. + */ + +/* eslint-disable n/no-process-exit */ +import yargs from 'yargs'; +import {appendFile} from 'fs/promises'; +import {Worker} from 'worker_threads'; +import { + convertToCloudMonitoringFormat, + TestResult, + log, + performanceTestCommand, + PERFORMANCE_TEST_TYPES, +} from './performanceUtils.js'; +import {getDirName} from '../src/util.js'; + +const argv = yargs(process.argv.slice(2)) + .command(performanceTestCommand) + .parseSync(); + +let iterationsRemaining: number = argv.samples as number; + +/** + * Main entry point for performing a Write 1 Read 3 performance measurement test. + * This function will create the number of threads supplied in the numthreads argument or + * default to 1 if no argument is provided. The test will be run for the number of iterations + * specified by the iterations parameter or 100 if not specified. + */ +function main() { + let numThreads: number = argv.workers as number; + if (numThreads > iterationsRemaining) { + log( + `${numThreads} is greater than number of iterations (${iterationsRemaining}). Using ${iterationsRemaining} threads instead.`, + argv.debug as boolean, + ); + numThreads = iterationsRemaining; + } + if (argv.test_type !== PERFORMANCE_TEST_TYPES.WRITE_ONE_READ_THREE) { + numThreads = 1; + } + for (let i = 0; i < numThreads; i++) { + createWorker(); + } +} + +/** + * Creates a new worker thread and performs a test iteration in that worker. + * When the worker passes back the results, they are appended to the results file. + */ +function createWorker() { + const dirName = getDirName().replace('/src', '/internal-tooling'); + iterationsRemaining--; + log( + `Starting new iteration. Current iterations remaining: ${iterationsRemaining}`, + argv.debug as boolean, + ); + let testPath = ''; + if ( + argv.test_type === PERFORMANCE_TEST_TYPES.WRITE_ONE_READ_THREE || + argv.test_type === PERFORMANCE_TEST_TYPES.RANGE_READ + ) { + testPath = `${dirName}/performPerformanceTest.js`; + } else if ( + argv.test_type === + PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_UPLOAD_MANY_FILES || + argv.test_type === + PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_CHUNKED_FILE_DOWNLOAD || + argv.test_type === + PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_DOWNLOAD_MANY_FILES + ) { + testPath = `${dirName}/performTransferManagerTest.js`; + } else if ( + argv.test_type === + PERFORMANCE_TEST_TYPES.APPLICATION_UPLOAD_MULTIPLE_OBJECTS || + argv.test_type === PERFORMANCE_TEST_TYPES.APPLICATION_LARGE_FILE_DOWNLOAD || + argv.test_type === + PERFORMANCE_TEST_TYPES.APPLICATION_DOWNLOAD_MULTIPLE_OBJECTS + ) { + testPath = `${dirName}/performApplicationPerformanceTest.js`; + } + + const w = new Worker(testPath, { + argv: process.argv.slice(2), + }); + + w.on('message', data => { + log('Successfully completed iteration.', argv.debug as boolean); + recordResult(data); + if (iterationsRemaining > 0) { + createWorker(); + } + }); + w.on('error', e => { + log(e, true, true); + // BBMC will not report errors unless the process is terminated with a non zero code. + // eslint-disable-next-line no-process-exit + process.exit(1); + }); +} + +/** + * Records the test result to the appropriate place based on specified command line arguments. + * + * @param {TestResult[]} results result of a test iteration. + */ +async function recordResult(results: TestResult[] | TestResult) { + const resultsToAppend: TestResult[] = Array.isArray(results) + ? results + : [results]; + + for await (const outputString of convertToCloudMonitoringFormat( + resultsToAppend, + )) { + argv.file_name + ? await appendFile(argv.file_name as string, `${outputString}\n`) + : log(outputString, true); + } +} + +main(); diff --git a/handwritten/storage/internal-tooling/performanceUtils.ts b/handwritten/storage/internal-tooling/performanceUtils.ts new file mode 100644 index 00000000000..b0633bdf1c4 --- /dev/null +++ b/handwritten/storage/internal-tooling/performanceUtils.ts @@ -0,0 +1,410 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 {execSync} from 'child_process'; +import {mkdirSync, mkdtempSync, unlinkSync} from 'fs'; +import * as path from 'path'; +import * as yargs from 'yargs'; +import {Bucket, Storage, TransferManager} from '../src/index.js'; +import {getDirName} from '../src/util.js'; + +export const NODE_DEFAULT_HIGHWATER_MARK_BYTES = 16384; +export const DEFAULT_DIRECTORY_PROBABILITY = 0.1; +export const DEFAULT_NUMBER_OF_OBJECTS = 1000; + +export const OUTPUT_FORMATS = { + CLOUD_MONITORING: 'cloud-monitoring', +} as const; + +export const PERFORMANCE_TEST_TYPES = { + WRITE_ONE_READ_THREE: 'w1r3', + RANGE_READ: 'range-read', + TRANSFER_MANAGER_UPLOAD_MANY_FILES: 'tm-upload', + TRANSFER_MANAGER_DOWNLOAD_MANY_FILES: 'tm-download', + TRANSFER_MANAGER_CHUNKED_FILE_DOWNLOAD: 'tm-chunked', + APPLICATION_LARGE_FILE_DOWNLOAD: 'application-large', + APPLICATION_UPLOAD_MULTIPLE_OBJECTS: 'application-upload', + APPLICATION_DOWNLOAD_MULTIPLE_OBJECTS: 'application-download', +} as const; + +const APIS = { + JSON: 'json', +} as const; + +const DEFAULT_SAMPLES = 8000; +const DEFAULT_WORKERS = 16; +const SSB_SIZE_THRESHOLD_BYTES = 1048576; +const DEFAULT_OBJECT_RANGE_SIZE_BYTES = '1048576..1048576'; +const DEFAULT_RANGE_READ_SIZE_BYTES = 0; //0 means read the full object +const DEFAULT_MINIMUM_READ_OFFSET_BYTES = 0; +const DEFAULT_MAXIMUM_READ_OFFSET_BYTES = 0; + +export interface TestResult { + library: 'nodejs'; + op: 'WRITE' | 'READ[0]' | 'READ[1]' | 'READ[2]'; + objectSize: number; + transferSize: number; + transferOffset: number; + appBufferSize: number; + crc32cEnabled: boolean; + md5Enabled: boolean; + api: 'JSON' | 'XML' | 'GRPC' | 'DirectPath'; + cpuTimeUs: number; + status: 'OK' | 'FAIL' | 'TIMEOUT'; + chunkSize: number; + workers: number; + bucketName: string; + elapsedTimeUs: number; +} + +export interface Arguments { + project?: string; + bucket?: string; + output_type: string; + samples: number; + workers: number; + api: string; + object_size: string; + range_read_size: number; + minimum_read_offset: number; + maximum_read_offset: number; + debug: boolean; + file_name: string | undefined; + num_objects: number; + test_type: string; +} + +export const performanceTestCommand: yargs.CommandModule<{}, Arguments> = { + command: 'performance-test', + builder(yargs) { + return yargs + .option('project', {type: 'string', demand: true}) + .option('bucket', {type: 'string', demand: true}) + .option('output_type', { + type: 'string', + choices: [OUTPUT_FORMATS.CLOUD_MONITORING], + default: OUTPUT_FORMATS.CLOUD_MONITORING, + }) + .option('samples', {type: 'number', default: DEFAULT_SAMPLES}) + .option('workers', {type: 'number', default: DEFAULT_WORKERS}) + .option('api', { + type: 'string', + choices: [APIS.JSON], + default: APIS.JSON, + }) + .option('object_size', { + type: 'string', + default: DEFAULT_OBJECT_RANGE_SIZE_BYTES, + }) + .option('range_read_size', { + type: 'number', + default: DEFAULT_RANGE_READ_SIZE_BYTES, + }) + .option('minimum_read_offset', { + type: 'number', + default: DEFAULT_MINIMUM_READ_OFFSET_BYTES, + }) + .option('maximum_read_offset', { + type: 'number', + default: DEFAULT_MAXIMUM_READ_OFFSET_BYTES, + }) + .option('debug', {type: 'boolean', default: false}) + .option('file_name', {type: 'string'}) + .option('num_objects', { + type: 'number', + default: DEFAULT_NUMBER_OF_OBJECTS, + }) + .option('test_type', { + type: 'string', + choices: [ + PERFORMANCE_TEST_TYPES.WRITE_ONE_READ_THREE, + PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_UPLOAD_MANY_FILES, + PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_DOWNLOAD_MANY_FILES, + PERFORMANCE_TEST_TYPES.TRANSFER_MANAGER_CHUNKED_FILE_DOWNLOAD, + PERFORMANCE_TEST_TYPES.APPLICATION_DOWNLOAD_MULTIPLE_OBJECTS, + PERFORMANCE_TEST_TYPES.APPLICATION_LARGE_FILE_DOWNLOAD, + PERFORMANCE_TEST_TYPES.APPLICATION_UPLOAD_MULTIPLE_OBJECTS, + ], + default: PERFORMANCE_TEST_TYPES.WRITE_ONE_READ_THREE, + }); + }, + async handler() {}, +}; + +export interface RandomDirectoryCreationInformation { + paths: string[]; + totalSizeInBytes: number; +} + +export interface PerformanceTestSetupResults { + storage: Storage; + bucket: Bucket; + transferManager: TransferManager; +} + +/** + * Create a uniformly distributed random integer beween the inclusive min and max provided. + * + * @param {number} minInclusive lower bound (inclusive) of the range of random integer to return. + * @param {number} maxInclusive upper bound (inclusive) of the range of random integer to return. + * @returns {number} returns a random integer between minInclusive and maxInclusive + */ +export function randomInteger(minInclusive: number, maxInclusive: number) { + // Utilizing Math.random will generate uniformly distributed random numbers. + return ( + Math.floor(Math.random() * (maxInclusive - minInclusive + 1)) + minInclusive + ); +} + +/** + * Returns a boolean value with the provided probability + * + * @param {number} trueProbablity the probability the value will be true + * + * @returns {boolean} a boolean value with the probablity provided. + */ +export function weightedRandomBoolean(trueProbablity: number): boolean { + return Math.random() <= trueProbablity ? true : false; +} + +/** + * Return a string of 6 random characters + * + * @returns {string} a random string value with length of 6 + */ +export function randomString(): string { + return Math.random().toString(36).slice(-6); +} + +/** + * Creates a random file name by appending a UUID to the baseName. + * + * @param {string} baseName the base file name. A random uuid will be appended to this value. + * + * @returns {string} random file name that was generated. + */ +export function generateRandomFileName(baseName: string): string { + return `${baseName}.${randomString()}`; +} + +/** + * Creates a file with a size between the small (default 5120 bytes) and large (2.147e9 bytes) parameters. + * The file is filled with random data. + * + * @param {string} fileName name of the file to generate. + * @param {number} fileSizeLowerBoundBytes minimum size of file to generate. + * @param {number} fileSizeUpperBoundBytes maximum size of file to generate. + * @param {string} currentDirectory the directory in which to generate the file. + * + * @returns {number} the size of the file generated. + */ +export function generateRandomFile( + fileName: string, + fileSizeLowerBoundBytes: number = getLowHighFileSize( + DEFAULT_OBJECT_RANGE_SIZE_BYTES, + ).low, + fileSizeUpperBoundBytes: number = getLowHighFileSize( + DEFAULT_OBJECT_RANGE_SIZE_BYTES, + ).high, + currentDirectory: string = mkdtempSync(randomString()), +): number { + const fileSizeBytes = randomInteger( + fileSizeLowerBoundBytes, + fileSizeUpperBoundBytes, + ); + + execSync( + `head --bytes=${fileSizeBytes} /dev/urandom > ${currentDirectory}/${fileName}`, + ); + + return fileSizeBytes; +} + +/** + * Creates a random directory structure consisting of subdirectories and random files. + * + * @param {number} maxObjects the total number of subdirectories and files to generate. + * @param {string} baseName the starting directory under which everything else is added. File names will have this value prepended. + * @param {number} fileSizeLowerBoundBytes minimum size of file to generate. + * @param {number} fileSizeUpperBoundBytes maximum size of file to generate. + * + * @returns {array} an array of all the generated paths + */ +export function generateRandomDirectoryStructure( + maxObjects: number, + baseName: string, + fileSizeLowerBoundBytes: number = getLowHighFileSize( + DEFAULT_OBJECT_RANGE_SIZE_BYTES, + ).low, + fileSizeUpperBoundBytes: number = getLowHighFileSize( + DEFAULT_OBJECT_RANGE_SIZE_BYTES, + ).high, + directoryProbability: number = DEFAULT_DIRECTORY_PROBABILITY, +): RandomDirectoryCreationInformation { + let curPath = baseName; + const creationInfo: RandomDirectoryCreationInformation = { + paths: [], + totalSizeInBytes: 0, + }; + + mkdirSync(curPath); + for (let i = 0; i < maxObjects; i++) { + if (weightedRandomBoolean(directoryProbability)) { + curPath = path.join(curPath, randomString()); + mkdirSync(curPath, {recursive: true}); + creationInfo.paths.push(curPath); + } else { + const randomName = randomString(); + creationInfo.totalSizeInBytes += generateRandomFile( + randomName, + fileSizeLowerBoundBytes, + fileSizeUpperBoundBytes, + curPath, + ); + creationInfo.paths.push(path.join(curPath, randomName)); + } + } + + return creationInfo; +} + +/** + * Deletes the file specified by the fileName parameter. + * + * @param {string} fileName name of the file to delete. + */ +export function cleanupFile( + fileName: string, + directoryName: string = getDirName(), +): void { + unlinkSync(`${directoryName}/${fileName}`); +} + +/** + * Creates the necessary structures for performing a performance test. + * + * @param {string} projectId the project ID to use. + * @param {string} bucketName the name of the bucket to use. + * @returns {object} object containing the created storage, bucket, and transfer manager instance. + */ +export async function performanceTestSetup( + projectId: string, + bucketName: string, +): Promise { + const storage = new Storage({projectId}); + const bucket = storage.bucket(bucketName, { + preconditionOpts: { + ifGenerationMatch: 0, + }, + }); + if (!(await bucket.exists())[0]) { + await bucket.create(); + } + const transferManager = new TransferManager(bucket); + return { + storage, + bucket, + transferManager, + }; +} + +/** + * Randomly returns the type of validation check to run on upload / download + * + * @returns {string | boolean | undefined} the type of validation to run (crc32c, md5, or none). + */ +export function getValidationType(): 'md5' | 'crc32c' | boolean | undefined { + const checkType = randomInteger(0, 2); + if (checkType === 0) { + return false; + } else if (checkType === 1) { + return 'crc32c'; + } else { + return 'md5'; + } +} + +/** + * Converts the supplied test results from javascript objects to a cloud monitoring formatted string. + * + * @param {TestResult[]} results An array of test iteration result objects that will be converted to cloud monitoring format. + * @param {string} bucket The bucket name used for the test. + * + * @returns {AsyncGenerator} A string containing the results of the conversion to cloud monitoring format. + */ +export async function* convertToCloudMonitoringFormat( + results: TestResult[], +): AsyncGenerator { + for (const curResult of results) { + const throughput = + // If the object size is greater than the defined threshold, report in MiB/s, otherwise report in KiB/s. + curResult.objectSize >= SSB_SIZE_THRESHOLD_BYTES + ? curResult.objectSize / + 1024 / + 1024 / + (curResult.elapsedTimeUs / 1000000) + : curResult.objectSize / 1024 / (curResult.elapsedTimeUs / 1000000); + yield `throughput{\ + library="${curResult.library}",\ + api="${curResult.api}",\ + op="${curResult.op}",\ + object_size="${curResult.objectSize}",\ + transfer_offset="${curResult.transferOffset}",\ + transfer_size="${curResult.chunkSize}",\ + app_buffer_size="${curResult.appBufferSize}",\ + crc32c_enabled="${curResult.crc32cEnabled}",\ + md5_enabled="${curResult.md5Enabled}",\ + cpu_time_us="${curResult.cpuTimeUs}",\ + bucket_name="${curResult.bucketName}",\ + workers="${curResult.workers}",\ + status_code="${curResult.status}"} ${throughput}`; + } +} + +/** + * Logs the provided message if debugging is enabled. + * + * @param {string | error} messageOrError the message or error object to be printed utilizing console.debug. + * @param {boolean} shouldLog flag indicating whether or not the message should be logged to stdout or stderr. + * @param {boolean} isError if set to true and shouldLog is true, write the output to stderr instead of stdout. + */ +export function log( + messageOrError: string | Error, + shouldLog: boolean, + isError = false, +): void { + if (shouldLog) { + isError ? console.error(messageOrError) : console.log(messageOrError); + } +} + +/** + * Converts the provided rangeSize from string format to an object containing the low and high size values. + * + * @param {string} rangeSize a string in the format low..high. + * + * @returns {object} An object containing integers low and high. + */ +export function getLowHighFileSize(rangeSize: string): { + low: number; + high: number; +} { + const split = rangeSize.split('..'); + return { + low: parseInt(split[0]), + high: parseInt(split[1]), + }; +} diff --git a/handwritten/storage/linkinator.config.json b/handwritten/storage/linkinator.config.json new file mode 100644 index 00000000000..165d1cbf45c --- /dev/null +++ b/handwritten/storage/linkinator.config.json @@ -0,0 +1,12 @@ +{ + "recurse": true, + "skip": [ + "https://codecov.io/gh/googleapis/", + "www.googleapis.com", + "img.shields.io", + "node_modules/", + "CHANGELOG.md" + ], + "silent": true, + "concurrency": 10 +} diff --git a/handwritten/storage/owlbot.py b/handwritten/storage/owlbot.py new file mode 100644 index 00000000000..5a8886e5a7e --- /dev/null +++ b/handwritten/storage/owlbot.py @@ -0,0 +1,44 @@ +# Copyright 2019 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 synthtool as s +import synthtool.gcp as gcp +import synthtool.languages.node_mono_repo as node +import logging + +logging.basicConfig(level=logging.DEBUG) + +common_templates = gcp.CommonTemplates() +templates = common_templates.node_mono_repo_library(relative_dir="handwriten/storage", source_location='build/src') +s.copy(templates, destination="handwritten/storage", excludes=['.jsdoc.js', + '.github/release-please.yml', + '.github/sync-repo-settings.yaml', + '.github/workflows/ci.yaml', + '.prettierrc.js', + '.mocharc.js', + '.kokoro/continuous/node14/system-test.cfg', + '.kokoro/presubmit/node14/system-test.cfg', + '.kokoro/release/publish.cfg', + '.kokoro/system-test.sh', + '.kokoro/samples-test.sh', + '.OwlBot.yaml' + ]) + +# Create .config directory under $HOME to get around permissions issues +# with resumable upload. +s.replace( + "handwriten/storage/.circleci/config.yml", + "command: npm run system-test", + "command: mkdir $HOME/.config && npm run system-test") +node.fix_hermetic(relative_dir="handwritten/storage") diff --git a/handwritten/storage/package.json b/handwritten/storage/package.json new file mode 100644 index 00000000000..63a55ea7373 --- /dev/null +++ b/handwritten/storage/package.json @@ -0,0 +1,136 @@ +{ + "name": "@google-cloud/storage", + "description": "Cloud Storage Client Library for Node.js", + "version": "7.19.0", + "license": "Apache-2.0", + "author": "Google Inc.", + "engines": { + "node": ">=14" + }, + "repository": { + "type": "git", + "directory": "handwritten/storage", + "url": "https://github.com/googleapis/google-cloud-node.git" + }, + "main": "./build/cjs/src/index.js", + "types": "./build/cjs/src/index.d.ts", + "type": "module", + "exports": { + ".": { + "import": { + "types": "./build/esm/src/index.d.ts", + "default": "./build/esm/src/index.js" + }, + "require": { + "types": "./build/cjs/src/index.d.ts", + "default": "./build/cjs/src/index.js" + } + } + }, + "files": [ + "build/cjs/src", + "build/cjs/package.json", + "!build/cjs/src/**/*.map", + "build/esm/src", + "!build/esm/src/**/*.map" + ], + "keywords": [ + "google apis client", + "google api client", + "google apis", + "google api", + "google", + "google cloud platform", + "google cloud", + "cloud", + "google storage", + "storage" + ], + "scripts": { + "all-test": "npm test && npm run system-test && npm run samples-test", + "benchwrapper": "node bin/benchwrapper.js", + "check": "gts check", + "clean": "rm -rf build/", + "compile:cjs": "tsc -p ./tsconfig.cjs.json", + "compile:esm": "tsc -p .", + "compile": "npm run compile:cjs && npm run compile:esm", + "conformance-test": "mocha --parallel build/cjs/conformance-test/ --require build/cjs/conformance-test/globalHooks.js", + "docs-test": "linkinator docs", + "docs": "jsdoc -c .jsdoc.json", + "fix": "gts fix", + "lint": "gts check", + "postcompile": "cp ./src/package-json-helper.cjs ./build/cjs/src && cp ./src/package-json-helper.cjs ./build/esm/src", + "postcompile:cjs": "babel --plugins gapic-tools/build/src/replaceImportMetaUrl,gapic-tools/build/src/toggleESMFlagVariable build/cjs/src/util.js -o build/cjs/src/util.js && cp internal-tooling/helpers/package.cjs.json build/cjs/package.json", + "precompile": "rm -rf build/", + "preconformance-test": "npm run compile:cjs -- --sourceMap", + "predocs-test": "npm run docs", + "predocs": "npm run compile:cjs -- --sourceMap", + "prelint": "cd samples; npm link ../; npm install", + "prepare": "npm run compile", + "presystem-test:esm": "npm run compile:esm", + "presystem-test": "npm run compile -- --sourceMap", + "pretest": "npm run compile -- --sourceMap", + "samples-test": "npm link && cd samples/ && npm link ../ && npm test && cd ../", + "system-test:esm": "mocha build/esm/system-test --timeout 600000 --exit", + "system-test": "mocha build/cjs/system-test --timeout 600000 --exit", + "test": "c8 mocha build/cjs/test" + }, + "dependencies": { + "@google-cloud/paginator": "^5.0.0", + "@google-cloud/projectify": "^4.0.0", + "@google-cloud/promisify": "<4.1.0", + "abort-controller": "^3.0.0", + "async-retry": "^1.3.3", + "duplexify": "^4.1.3", + "fast-xml-parser": "^5.3.4", + "gaxios": "^6.0.2", + "google-auth-library": "^9.6.3", + "html-entities": "^2.5.2", + "mime": "^3.0.0", + "p-limit": "^3.0.1", + "retry-request": "^7.0.0", + "teeny-request": "^9.0.0", + "uuid": "^8.0.0" + }, + "devDependencies": { + "@babel/cli": "^7.22.10", + "@babel/core": "^7.22.11", + "@google-cloud/pubsub": "^4.0.0", + "@grpc/grpc-js": "^1.0.3", + "@grpc/proto-loader": "^0.8.0", + "@types/async-retry": "^1.4.3", + "@types/duplexify": "^3.6.4", + "@types/mime": "^3.0.0", + "@types/mocha": "^9.1.1", + "@types/mockery": "^1.4.29", + "@types/node": "^24.0.0", + "@types/node-fetch": "^2.1.3", + "@types/proxyquire": "^1.3.28", + "@types/request": "^2.48.4", + "@types/sinon": "^17.0.0", + "@types/tmp": "0.2.6", + "@types/uuid": "^8.0.0", + "@types/yargs": "^17.0.10", + "c8": "^9.0.0", + "form-data": "^4.0.4", + "gapic-tools": "^0.4.0", + "gts": "^5.0.0", + "jsdoc": "^4.0.4", + "jsdoc-fresh": "^5.0.0", + "jsdoc-region-tag": "^4.0.0", + "linkinator": "^3.0.0", + "mocha": "^9.2.2", + "mockery": "^2.1.0", + "nock": "~13.5.0", + "node-fetch": "^2.6.7", + "pack-n-play": "^2.0.0", + "proxyquire": "^2.1.3", + "sinon": "^18.0.0", + "nise": "6.0.0", + "path-to-regexp": "6.3.0", + "tmp": "^0.2.0", + "typescript": "^5.1.6", + "yargs": "^17.3.1" + }, + "homepage": "https://github.com/googleapis/google-cloud-node/tree/main/handwritten/storage" +} diff --git a/handwritten/storage/src/acl.ts b/handwritten/storage/src/acl.ts new file mode 100644 index 00000000000..ecd02bb7a83 --- /dev/null +++ b/handwritten/storage/src/acl.ts @@ -0,0 +1,914 @@ +// Copyright 2019 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 { + BodyResponseCallback, + DecorateRequestOptions, + BaseMetadata, +} from './nodejs-common/index.js'; +import {promisifyAll} from '@google-cloud/promisify'; + +export interface AclOptions { + pathPrefix: string; + request: ( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ) => void; +} + +export type GetAclResponse = [ + AccessControlObject | AccessControlObject[], + AclMetadata, +]; +export interface GetAclCallback { + ( + err: Error | null, + acl?: AccessControlObject | AccessControlObject[] | null, + apiResponse?: AclMetadata, + ): void; +} +export interface GetAclOptions { + entity: string; + generation?: number; + userProject?: string; +} + +export interface UpdateAclOptions { + entity: string; + role: string; + generation?: number; + userProject?: string; +} +export type UpdateAclResponse = [AccessControlObject, AclMetadata]; +export interface UpdateAclCallback { + ( + err: Error | null, + acl?: AccessControlObject | null, + apiResponse?: AclMetadata, + ): void; +} + +export interface AddAclOptions { + entity: string; + role: string; + generation?: number; + userProject?: string; +} +export type AddAclResponse = [AccessControlObject, AclMetadata]; +export interface AddAclCallback { + ( + err: Error | null, + acl?: AccessControlObject | null, + apiResponse?: AclMetadata, + ): void; +} +export type RemoveAclResponse = [AclMetadata]; +export interface RemoveAclCallback { + (err: Error | null, apiResponse?: AclMetadata): void; +} +export interface RemoveAclOptions { + entity: string; + generation?: number; + userProject?: string; +} + +interface AclQuery { + generation: number; + userProject: string; +} + +export interface AccessControlObject { + entity: string; + role: string; + projectTeam: string; +} + +export interface AclMetadata extends BaseMetadata { + bucket?: string; + domain?: string; + entity?: string; + entityId?: string; + generation?: string; + object?: string; + projectTeam?: { + projectNumber?: string; + team?: 'editors' | 'owners' | 'viewers'; + }; + role?: 'OWNER' | 'READER' | 'WRITER' | 'FULL_CONTROL'; + [key: string]: unknown; +} + +/** + * Attach functionality to a {@link Storage.acl} instance. This will add an + * object for each role group (owners, readers, and writers), with each object + * containing methods to add or delete a type of entity. + * + * As an example, here are a few methods that are created. + * + * myBucket.acl.readers.deleteGroup('groupId', function(err) {}); + * + * myBucket.acl.owners.addUser('email@example.com', function(err, acl) {}); + * + * myBucket.acl.writers.addDomain('example.com', function(err, acl) {}); + * + * @private + */ +class AclRoleAccessorMethods { + private static accessMethods = ['add', 'delete']; + + private static entities = [ + // Special entity groups that do not require further specification. + 'allAuthenticatedUsers', + 'allUsers', + + // Entity groups that require specification, e.g. `user-email@example.com`. + 'domain-', + 'group-', + 'project-', + 'user-', + ]; + + private static roles = ['OWNER', 'READER', 'WRITER']; + + owners = {}; + + readers = {}; + + writers = {}; + + constructor() { + /** + * An object of convenience methods to add or delete owner ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.owners.addAllAuthenticatedUsers` + * - `myFile.acl.owners.deleteAllAuthenticatedUsers` + * - `myFile.acl.owners.addAllUsers` + * - `myFile.acl.owners.deleteAllUsers` + * - `myFile.acl.owners.addDomain` + * - `myFile.acl.owners.deleteDomain` + * - `myFile.acl.owners.addGroup` + * - `myFile.acl.owners.deleteGroup` + * - `myFile.acl.owners.addProject` + * - `myFile.acl.owners.deleteProject` + * - `myFile.acl.owners.addUser` + * - `myFile.acl.owners.deleteUser` + * + * @name Acl#owners + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as an owner of a file. + * //- + * const myBucket = gcs.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * myFile.acl.owners.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.OWNER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.owners.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.owners = {}; + + /** + * An object of convenience methods to add or delete reader ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.readers.addAllAuthenticatedUsers` + * - `myFile.acl.readers.deleteAllAuthenticatedUsers` + * - `myFile.acl.readers.addAllUsers` + * - `myFile.acl.readers.deleteAllUsers` + * - `myFile.acl.readers.addDomain` + * - `myFile.acl.readers.deleteDomain` + * - `myFile.acl.readers.addGroup` + * - `myFile.acl.readers.deleteGroup` + * - `myFile.acl.readers.addProject` + * - `myFile.acl.readers.deleteProject` + * - `myFile.acl.readers.addUser` + * - `myFile.acl.readers.deleteUser` + * + * @name Acl#readers + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as a reader of a file. + * //- + * myFile.acl.readers.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.READER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.readers.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.readers = {}; + + /** + * An object of convenience methods to add or delete writer ACL permissions + * for a given entity. + * + * The supported methods include: + * + * - `myFile.acl.writers.addAllAuthenticatedUsers` + * - `myFile.acl.writers.deleteAllAuthenticatedUsers` + * - `myFile.acl.writers.addAllUsers` + * - `myFile.acl.writers.deleteAllUsers` + * - `myFile.acl.writers.addDomain` + * - `myFile.acl.writers.deleteDomain` + * - `myFile.acl.writers.addGroup` + * - `myFile.acl.writers.deleteGroup` + * - `myFile.acl.writers.addProject` + * - `myFile.acl.writers.deleteProject` + * - `myFile.acl.writers.addUser` + * - `myFile.acl.writers.deleteUser` + * + * @name Acl#writers + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * //- + * // Add a user as a writer of a file. + * //- + * myFile.acl.writers.addUser('email@example.com', function(err, aclObject) + * {}); + * + * //- + * // For reference, the above command is the same as running the following. + * //- + * myFile.acl.add({ + * entity: 'user-email@example.com', + * role: gcs.acl.WRITER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.writers.addUser('email@example.com').then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + this.writers = {}; + AclRoleAccessorMethods.roles.forEach(this._assignAccessMethods.bind(this)); + } + + _assignAccessMethods(role: string) { + const accessMethods = AclRoleAccessorMethods.accessMethods; + const entities = AclRoleAccessorMethods.entities; + const roleGroup = role.toLowerCase() + 's'; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this as any)[roleGroup] = entities.reduce((acc, entity) => { + const isPrefix = entity.charAt(entity.length - 1) === '-'; + + accessMethods.forEach(accessMethod => { + let method = + accessMethod + entity[0].toUpperCase() + entity.substring(1); + + if (isPrefix) { + method = method.replace('-', ''); + } + + // Wrap the parent accessor method (e.g. `add` or `delete`) to avoid the + // more complex API of specifying an `entity` and `role`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (acc as any)[method] = ( + entityId: string, + options: {}, + callback: Function | {}, + ) => { + let apiEntity; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (isPrefix) { + apiEntity = entity + entityId; + } else { + // If the entity is not a prefix, it is a special entity group + // that does not require further details. The accessor methods + // only accept a callback. + apiEntity = entity; + callback = entityId; + } + + options = Object.assign( + { + entity: apiEntity, + role, + }, + options, + ); + + const args = [options]; + + if (typeof callback === 'function') { + args.push(callback); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return (this as any)[accessMethod].apply(this, args); + }; + }); + + return acc; + }, {}); + } +} + +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against an + * object or bucket (for example, `READ` or `WRITE`); the entity defines who the + * permission applies to (for example, a specific user or group of users). + * + * Where an `entity` value is accepted, we follow the format the Cloud Storage + * API expects. + * + * Refer to + * https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls + * for the most up-to-date values. + * + * - `user-userId` + * - `user-email` + * - `group-groupId` + * - `group-email` + * - `domain-domain` + * - `project-team-projectId` + * - `allUsers` + * - `allAuthenticatedUsers` + * + * Examples: + * + * - The user "liz@example.com" would be `user-liz@example.com`. + * - The group "example@googlegroups.com" would be + * `group-example@googlegroups.com`. + * - To refer to all members of the Google Apps for Business domain + * "example.com", the entity would be `domain-example.com`. + * + * For more detailed information, see + * {@link http://goo.gl/6qBBPO| About Access Control Lists}. + * + * @constructor Acl + * @mixin + * @param {object} options Configuration options. + */ +class Acl extends AclRoleAccessorMethods { + default!: Acl; + pathPrefix: string; + request_: ( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ) => void; + + constructor(options: AclOptions) { + super(); + this.pathPrefix = options.pathPrefix; + this.request_ = options.request; + } + + add(options: AddAclOptions): Promise; + add(options: AddAclOptions, callback: AddAclCallback): void; + /** + * @typedef {array} AddAclResponse + * @property {object} 0 The Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback AddAclCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Add access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert| BucketAccessControls: insert API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation} + * + * @param {object} options Configuration options. + * @param {string} options.entity Whose permissions will be added. + * @param {string} options.role Permissions allowed for the defined entity. + * See {@link https://cloud.google.com/storage/docs/access-control Access + * Control}. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {AddAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * const options = { + * entity: 'user-useremail@example.com', + * role: gcs.acl.OWNER_ROLE + * }; + * + * myBucket.acl.add(options, function(err, aclObject, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * // Here is how you would grant ownership permissions to a user on a + * specific + * // revision of a file. + * //- + * myFile.acl.add({ + * entity: 'user-useremail@example.com', + * role: gcs.acl.OWNER_ROLE, + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_add_file_owner + * Example of adding an owner to a file: + * + * @example + * region_tag:storage_add_bucket_owner + * Example of adding an owner to a bucket: + * + * @example + * region_tag:storage_add_bucket_default_owner + * Example of adding a default owner to a bucket: + */ + add( + options: AddAclOptions, + callback?: AddAclCallback, + ): void | Promise { + const query = {} as AclQuery; + + if (options.generation) { + query.generation = options.generation; + } + + if (options.userProject) { + query.userProject = options.userProject; + } + + this.request( + { + method: 'POST', + uri: '', + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + json: { + entity: options.entity, + role: options.role.toUpperCase(), + }, + }, + (err, resp) => { + if (err) { + callback!(err, null, resp); + return; + } + + callback!(null, this.makeAclObject_(resp), resp); + }, + ); + } + + delete(options: RemoveAclOptions): Promise; + delete(options: RemoveAclOptions, callback: RemoveAclCallback): void; + /** + * @typedef {array} RemoveAclResponse + * @property {object} 0 The full API response. + */ + /** + * @callback RemoveAclCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/delete| BucketAccessControls: delete API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/delete| ObjectAccessControls: delete API Documentation} + * + * @param {object} options Configuration object. + * @param {string} options.entity Whose permissions will be revoked. + * @param {int} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {RemoveAclCallback} callback The callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * myBucket.acl.delete({ + * entity: 'user-useremail@example.com' + * }, function(err, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.delete({ + * entity: 'user-useremail@example.com', + * generation: 1 + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example + * region_tag:storage_remove_bucket_owner + * Example of removing an owner from a bucket: + * + * @example + * region_tag:storage_remove_bucket_default_owner + * Example of removing a default owner from a bucket: + * + * @example + * region_tag:storage_remove_file_owner + * Example of removing an owner from a bucket: + */ + delete( + options: RemoveAclOptions, + callback?: RemoveAclCallback, + ): void | Promise { + const query = {} as AclQuery; + + if (options.generation) { + query.generation = options.generation; + } + + if (options.userProject) { + query.userProject = options.userProject; + } + + this.request( + { + method: 'DELETE', + uri: '/' + encodeURIComponent(options.entity), + qs: query, + }, + (err, resp) => { + callback!(err, resp); + }, + ); + } + + get(options?: GetAclOptions): Promise; + get(options: GetAclOptions, callback: GetAclCallback): void; + get(callback: GetAclCallback): void; + /** + * @typedef {array} GetAclResponse + * @property {object|object[]} 0 Single or array of Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback GetAclCallback + * @param {?Error} err Request error, if any. + * @param {object|object[]} acl Single or array of Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Get access controls on a {@link Bucket} or {@link File}. If + * an entity is omitted, you will receive an array of all applicable access + * controls. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/get| BucketAccessControls: get API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get| ObjectAccessControls: get API Documentation} + * + * @param {object|function} [options] Configuration options. If you want to + * receive a list of all access controls, pass the callback function as + * the only argument. + * @param {string} options.entity Whose permissions will be fetched. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * myBucket.acl.get({ + * entity: 'user-useremail@example.com' + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // Get all access controls. + * //- + * myBucket.acl.get(function(err, aclObjects, apiResponse) { + * // aclObjects = [ + * // { + * // entity: 'user-useremail@example.com', + * // role: 'owner' + * // } + * // ] + * }); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.get({ + * entity: 'user-useremail@example.com', + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.get().then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_print_file_acl + * Example of printing a file's ACL: + * + * @example + * region_tag:storage_print_file_acl_for_user + * Example of printing a file's ACL for a specific user: + * + * @example + * region_tag:storage_print_bucket_acl + * Example of printing a bucket's ACL: + * + * @example + * region_tag:storage_print_bucket_acl_for_user + * Example of printing a bucket's ACL for a specific user: + */ + get( + optionsOrCallback?: GetAclOptions | GetAclCallback, + cb?: GetAclCallback, + ): void | Promise { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : null; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + let path = ''; + const query = {} as AclQuery; + + if (options) { + path = '/' + encodeURIComponent(options.entity); + + if (options.generation) { + query.generation = options.generation; + } + + if (options.userProject) { + query.userProject = options.userProject; + } + } + + this.request( + { + uri: path, + qs: query, + }, + (err, resp) => { + if (err) { + callback!(err, null, resp); + return; + } + + let results; + + if (resp.items) { + results = resp.items.map(this.makeAclObject_); + } else { + results = this.makeAclObject_(resp); + } + + callback!(null, results, resp); + }, + ); + } + + update(options: UpdateAclOptions): Promise; + update(options: UpdateAclOptions, callback: UpdateAclCallback): void; + /** + * @typedef {array} UpdateAclResponse + * @property {object} 0 The updated Acl Objects. + * @property {object} 1 The full API response. + */ + /** + * @callback UpdateAclCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The updated Acl Objects. + * @param {object} apiResponse The full API response. + */ + /** + * Update access controls on a {@link Bucket} or {@link File}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/update| BucketAccessControls: update API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/update| ObjectAccessControls: update API Documentation} + * + * @param {object} options Configuration options. + * @param {string} options.entity Whose permissions will be updated. + * @param {string} options.role Permissions allowed for the defined entity. + * See {@link Storage.acl}. + * @param {number} [options.generation] **File Objects Only** Select a specific + * revision of this file (as opposed to the latest version, the default). + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {UpdateAclCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * const myFile = myBucket.file('my-file'); + * + * const options = { + * entity: 'user-useremail@example.com', + * role: gcs.acl.WRITER_ROLE + * }; + * + * myBucket.acl.update(options, function(err, aclObject, apiResponse) {}); + * + * //- + * // For file ACL operations, you can also specify a `generation` property. + * //- + * myFile.acl.update({ + * entity: 'user-useremail@example.com', + * role: gcs.acl.WRITER_ROLE, + * generation: 1 + * }, function(err, aclObject, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myFile.acl.update(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + update( + options: UpdateAclOptions, + callback?: UpdateAclCallback, + ): void | Promise { + const query = {} as AclQuery; + + if (options.generation) { + query.generation = options.generation; + } + + if (options.userProject) { + query.userProject = options.userProject; + } + + this.request( + { + method: 'PUT', + uri: '/' + encodeURIComponent(options.entity), + qs: query, + json: { + role: options.role.toUpperCase(), + }, + }, + (err, resp) => { + if (err) { + callback!(err, null, resp); + return; + } + + callback!(null, this.makeAclObject_(resp), resp); + }, + ); + } + + /** + * Transform API responses to a consistent object format. + * + * @private + */ + makeAclObject_( + accessControlObject: AccessControlObject, + ): AccessControlObject { + const obj = { + entity: accessControlObject.entity, + role: accessControlObject.role, + } as AccessControlObject; + + if (accessControlObject.projectTeam) { + obj.projectTeam = accessControlObject.projectTeam; + } + + return obj; + } + + /** + * Patch requests up to the bucket's request object. + * + * @private + * + * @param {string} method Action. + * @param {string} path Request path. + * @param {*} query Request query object. + * @param {*} body Request body contents. + * @param {function} callback Callback function. + */ + request( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void { + reqOpts.uri = this.pathPrefix + reqOpts.uri; + this.request_(reqOpts, callback); + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Acl, { + exclude: ['request'], +}); + +export {Acl, AclRoleAccessorMethods}; diff --git a/handwritten/storage/src/bucket.ts b/handwritten/storage/src/bucket.ts new file mode 100644 index 00000000000..fde1a9bfd18 --- /dev/null +++ b/handwritten/storage/src/bucket.ts @@ -0,0 +1,4603 @@ +// Copyright 2019 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 { + ApiError, + BodyResponseCallback, + DecorateRequestOptions, + DeleteCallback, + ExistsCallback, + GetConfig, + MetadataCallback, + ServiceObject, + SetMetadataResponse, + util, +} from './nodejs-common/index.js'; +import {RequestResponse} from './nodejs-common/service-object.js'; +import {paginator} from '@google-cloud/paginator'; +import {promisifyAll} from '@google-cloud/promisify'; +import * as fs from 'fs'; +import * as http from 'http'; +import mime from 'mime'; +import * as path from 'path'; +import pLimit from 'p-limit'; +import {promisify} from 'util'; +import AsyncRetry from 'async-retry'; +import {convertObjKeysToSnakeCase} from './util.js'; + +import {Acl, AclMetadata} from './acl.js'; +import {Channel} from './channel.js'; +import { + File, + FileOptions, + CreateResumableUploadOptions, + CreateWriteStreamOptions, + FileMetadata, +} from './file.js'; +import {Iam} from './iam.js'; +import {Notification, NotificationMetadata} from './notification.js'; +import { + Storage, + Cors, + PreconditionOptions, + IdempotencyStrategy, + BucketOptions, +} from './storage.js'; +import { + GetSignedUrlResponse, + GetSignedUrlCallback, + SignerGetSignedUrlConfig, + URLSigner, + Query, +} from './signer.js'; +import {Readable} from 'stream'; +import {CRC32CValidatorGenerator} from './crc32c.js'; +import {URL} from 'url'; +import { + BaseMetadata, + SetMetadataOptions, +} from './nodejs-common/service-object.js'; + +interface SourceObject { + name: string; + generation?: number; +} + +interface CreateNotificationQuery { + userProject?: string; +} + +interface MetadataOptions { + predefinedAcl: string; + userProject?: string; + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} + +export type GetFilesResponse = [ + File[], + (GetFilesOptions | {}) & Partial>, + unknown, +]; +export interface GetFilesCallback { + ( + err: Error | null, + files?: File[], + nextQuery?: {}, + apiResponse?: unknown, + ): void; +} + +interface WatchAllOptions { + delimiter?: string; + maxResults?: number; + pageToken?: string; + prefix?: string; + projection?: string; + userProject?: string; + versions?: boolean; +} + +export interface AddLifecycleRuleOptions extends PreconditionOptions { + append?: boolean; +} + +export interface LifecycleAction { + type: 'Delete' | 'SetStorageClass' | 'AbortIncompleteMultipartUpload'; + storageClass?: string; +} +export interface LifecycleCondition { + age?: number; + createdBefore?: Date | string; + customTimeBefore?: Date | string; + daysSinceCustomTime?: number; + daysSinceNoncurrentTime?: number; + isLive?: boolean; + matchesPrefix?: string[]; + matchesSuffix?: string[]; + matchesStorageClass?: string[]; + noncurrentTimeBefore?: Date | string; + numNewerVersions?: number; +} + +export interface LifecycleRule { + action: LifecycleAction; + condition: LifecycleCondition; +} + +export interface LifecycleCondition { + age?: number; + createdBefore?: Date | string; + customTimeBefore?: Date | string; + daysSinceCustomTime?: number; + daysSinceNoncurrentTime?: number; + isLive?: boolean; + matchesPrefix?: string[]; + matchesSuffix?: string[]; + matchesStorageClass?: string[]; + noncurrentTimeBefore?: Date | string; + numNewerVersions?: number; +} + +export interface LifecycleRule { + action: LifecycleAction; + condition: LifecycleCondition; +} + +export interface EnableLoggingOptions extends PreconditionOptions { + bucket?: string | Bucket; + prefix: string; +} + +export interface GetFilesOptions { + autoPaginate?: boolean; + delimiter?: string; + endOffset?: string; + includeFoldersAsPrefixes?: boolean; + includeTrailingDelimiter?: boolean; + prefix?: string; + matchGlob?: string; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + softDeleted?: boolean; + startOffset?: string; + userProject?: string; + versions?: boolean; + fields?: string; +} + +export interface CombineOptions extends PreconditionOptions { + kmsKeyName?: string; + userProject?: string; +} + +export interface CombineCallback { + (err: Error | null, newFile: File | null, apiResponse: unknown): void; +} + +export type CombineResponse = [File, unknown]; + +export interface CreateChannelConfig extends WatchAllOptions { + address: string; +} + +export interface CreateChannelOptions { + userProject?: string; +} + +export type CreateChannelResponse = [Channel, unknown]; + +export interface CreateChannelCallback { + (err: Error | null, channel: Channel | null, apiResponse: unknown): void; +} + +export interface CreateNotificationOptions { + customAttributes?: {[key: string]: string}; + eventTypes?: string[]; + objectNamePrefix?: string; + payloadFormat?: string; + userProject?: string; +} + +export interface CreateNotificationCallback { + ( + err: Error | null, + notification: Notification | null, + apiResponse: unknown, + ): void; +} + +export type CreateNotificationResponse = [Notification, unknown]; + +export interface DeleteBucketOptions { + ignoreNotFound?: boolean; + userProject?: string; +} + +export type DeleteBucketResponse = [unknown]; + +export interface DeleteBucketCallback extends DeleteCallback { + (err: Error | null, apiResponse: unknown): void; +} + +export interface DeleteFilesOptions + extends GetFilesOptions, + PreconditionOptions { + force?: boolean; +} + +export interface DeleteFilesCallback { + (err: Error | Error[] | null, apiResponse?: object): void; +} + +export type DeleteLabelsResponse = [unknown]; + +export type DeleteLabelsCallback = SetLabelsCallback; + +export type DeleteLabelsOptions = PreconditionOptions; + +export type DisableRequesterPaysOptions = PreconditionOptions; + +export type DisableRequesterPaysResponse = [unknown]; + +export interface DisableRequesterPaysCallback { + (err?: Error | null, apiResponse?: object): void; +} + +export type EnableRequesterPaysResponse = [unknown]; + +export interface EnableRequesterPaysCallback { + (err?: Error | null, apiResponse?: unknown): void; +} + +export type EnableRequesterPaysOptions = PreconditionOptions; +export interface BucketExistsOptions extends GetConfig { + userProject?: string; +} + +export type BucketExistsResponse = [boolean]; + +export type BucketExistsCallback = ExistsCallback; + +export interface GetBucketOptions extends GetConfig { + userProject?: string; +} + +export type GetBucketResponse = [Bucket, unknown]; + +export interface GetBucketCallback { + (err: ApiError | null, bucket: Bucket | null, apiResponse: unknown): void; +} + +export interface GetLabelsOptions { + userProject?: string; +} + +export type GetLabelsResponse = [unknown]; + +export interface GetLabelsCallback { + (err: Error | null, labels: object | null): void; +} + +export interface RestoreOptions { + generation: string; + projection?: 'full' | 'noAcl'; +} +export interface BucketMetadata extends BaseMetadata { + acl?: AclMetadata[] | null; + autoclass?: { + enabled?: boolean; + toggleTime?: string; + terminalStorageClass?: string; + terminalStorageClassUpdateTime?: string; + }; + billing?: { + requesterPays?: boolean; + }; + cors?: Cors[]; + customPlacementConfig?: { + dataLocations?: string[]; + }; + defaultEventBasedHold?: boolean; + defaultObjectAcl?: AclMetadata[]; + encryption?: { + defaultKmsKeyName?: string; + } | null; + hierarchicalNamespace?: { + enabled?: boolean; + }; + iamConfiguration?: { + publicAccessPrevention?: string; + uniformBucketLevelAccess?: { + enabled?: boolean; + lockedTime?: string; + }; + }; + labels?: { + [key: string]: string | null; + }; + lifecycle?: { + rule?: LifecycleRule[]; + } | null; + location?: string; + locationType?: string; + logging?: { + logBucket?: string; + logObjectPrefix?: string; + }; + generation?: string; + metageneration?: string; + name?: string; + objectRetention?: { + mode?: string; + }; + owner?: { + entity?: string; + entityId?: string; + }; + projectNumber?: string | number; + retentionPolicy?: { + effectiveTime?: string; + isLocked?: boolean; + retentionPeriod?: string | number; + } | null; + rpo?: string; + softDeleteTime?: string; + hardDeleteTime?: string; + softDeletePolicy?: { + retentionDurationSeconds?: string | number; + readonly effectiveTime?: string; + }; + storageClass?: string; + timeCreated?: string; + updated?: string; + versioning?: { + enabled?: boolean; + }; + website?: { + mainPageSuffix?: string; + notFoundPage?: string; + }; +} + +export type GetBucketMetadataResponse = [BucketMetadata, unknown]; + +export interface GetBucketMetadataCallback { + ( + err: ApiError | null, + metadata: BucketMetadata | null, + apiResponse: unknown, + ): void; +} + +export interface GetBucketMetadataOptions { + userProject?: string; +} + +export interface GetBucketSignedUrlConfig + extends Pick { + action: 'list'; + version?: 'v2' | 'v4'; + cname?: string; + virtualHostedStyle?: boolean; + expires: string | number | Date; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; +} + +export enum BucketActionToHTTPMethod { + list = 'GET', +} + +export enum AvailableServiceObjectMethods { + setMetadata, + delete, +} + +export interface GetNotificationsOptions { + userProject?: string; +} + +export interface GetNotificationsCallback { + ( + err: Error | null, + notifications: Notification[] | null, + apiResponse: unknown, + ): void; +} + +export type GetNotificationsResponse = [Notification[], unknown]; + +export interface MakeBucketPrivateOptions { + includeFiles?: boolean; + force?: boolean; + metadata?: BucketMetadata; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} + +interface MakeBucketPrivateRequest extends MakeBucketPrivateOptions { + private?: boolean; +} + +export type MakeBucketPrivateResponse = [File[]]; + +export interface MakeBucketPrivateCallback { + (err?: Error | null, files?: File[]): void; +} + +export interface MakeBucketPublicOptions { + includeFiles?: boolean; + force?: boolean; +} + +export interface MakeBucketPublicCallback { + (err?: Error | null, files?: File[]): void; +} + +export type MakeBucketPublicResponse = [File[]]; + +export interface SetBucketMetadataOptions extends PreconditionOptions { + userProject?: string; +} + +export type SetBucketMetadataResponse = [BucketMetadata]; + +export interface SetBucketMetadataCallback { + (err?: Error | null, metadata?: BucketMetadata): void; +} + +export interface BucketLockCallback { + (err?: Error | null, apiResponse?: unknown): void; +} + +export type BucketLockResponse = [unknown]; + +export interface Labels { + [key: string]: string; +} + +export interface SetLabelsOptions extends PreconditionOptions { + userProject?: string; +} + +export type SetLabelsResponse = [unknown]; + +export interface SetLabelsCallback { + (err?: Error | null, metadata?: unknown): void; +} + +export interface SetBucketStorageClassOptions extends PreconditionOptions { + userProject?: string; +} + +export interface SetBucketStorageClassCallback { + (err?: Error | null): void; +} + +export type UploadResponse = [File, unknown]; + +export interface UploadCallback { + (err: Error | null, file?: File | null, apiResponse?: unknown): void; +} + +export interface UploadOptions + extends CreateResumableUploadOptions, + CreateWriteStreamOptions { + destination?: string | File; + encryptionKey?: string | Buffer; + kmsKeyName?: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onUploadProgress?: (progressEvent: any) => void; +} + +export interface MakeAllFilesPublicPrivateOptions { + force?: boolean; + private?: boolean; + public?: boolean; + userProject?: string; +} + +interface MakeAllFilesPublicPrivateCallback { + (err?: Error | Error[] | null, files?: File[]): void; +} + +type MakeAllFilesPublicPrivateResponse = [File[]]; + +export enum BucketExceptionMessages { + PROVIDE_SOURCE_FILE = 'You must provide at least one source file.', + DESTINATION_FILE_NOT_SPECIFIED = 'A destination file must be specified.', + CHANNEL_ID_REQUIRED = 'An ID is required to create a channel.', + TOPIC_NAME_REQUIRED = 'A valid topic name is required.', + CONFIGURATION_OBJECT_PREFIX_REQUIRED = 'A configuration object with a prefix is required.', + SPECIFY_FILE_NAME = 'A file name must be specified.', + METAGENERATION_NOT_PROVIDED = 'A metageneration must be provided.', + SUPPLY_NOTIFICATION_ID = 'You must supply a notification ID.', +} + +/** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ +/** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ +/** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ +/** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ +/** + * A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + * + * @name Bucket#crc32cGenerator + * @type {CRC32CValidator} + */ +/** + * Get and set IAM policies for your bucket. + * + * @name Bucket#iam + * @mixes Iam + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Get the IAM policy for your bucket. + * //- + * bucket.iam.getPolicy(function(err, policy) { + * console.log(policy); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.getPolicy().then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_view_bucket_iam_members + * Example of retrieving a bucket's IAM policy: + * + * @example + * region_tag:storage_add_bucket_iam_member + * Example of adding to a bucket's IAM policy: + * + * @example + * region_tag:storage_remove_bucket_iam_member + * Example of removing from a bucket's IAM policy: + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a Bucket instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * Buckets also have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. Default ACLs specify permissions that all new + * objects added to the bucket will inherit by default. You can add, delete, + * get, and update entities and permissions for these as well with + * {@link Bucket#acl.default}. + * + * See {@link http://goo.gl/6qBBPO| About Access Control Lists} + * See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs} + * + * @name Bucket#acl + * @mixes Acl + * @property {Acl} default Cloud Storage Buckets have + * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs} + * for all created files. You can add, delete, get, and update entities and + * permissions for these as well. The method signatures and examples are all + * the same, after only prefixing the method call with `default`. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Make a bucket's contents publicly readable. + * //- + * const myBucket = storage.bucket('my-bucket'); + * + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * myBucket.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_print_bucket_acl + * Example of printing a bucket's ACL: + * + * @example + * region_tag:storage_print_bucket_acl_for_user + * Example of printing a bucket's ACL for a specific user: + * + * @example + * region_tag:storage_add_bucket_owner + * Example of adding an owner to a bucket: + * + * @example + * region_tag:storage_remove_bucket_owner + * Example of removing an owner from a bucket: + * + * @example + * region_tag:storage_add_bucket_default_owner + * Example of adding a default owner to a bucket: + * + * @example + * region_tag:storage_remove_bucket_default_owner + * Example of removing a default owner from a bucket: + */ +/** + * The API-formatted resource description of the bucket. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Bucket#metadata + * @type {object} + */ +/** + * The bucket's name. + * @name Bucket#name + * @type {string} + */ +/** + * Get {@link File} objects for the files currently in the bucket as a + * readable object stream. + * + * @method Bucket#getFilesStream + * @param {GetFilesOptions} [query] Query object for listing files. + * @returns {ReadableStream} A readable stream that emits {@link File} instances. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getFilesStream() + * .on('error', console.error) + * .on('data', function(file) { + * // file is a File object. + * }) + * .on('end', function() { + * // All files retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * bucket.getFilesStream() + * .on('data', function(file) { + * this.end(); + * }); + * + * //- + * // If you're filtering files with a delimiter, you should use + * // {@link Bucket#getFiles} and set `autoPaginate: false` in order to + * // preserve the `apiResponse` argument. + * //- + * const prefixes = []; + * + * function callback(err, files, nextQuery, apiResponse) { + * prefixes = prefixes.concat(apiResponse.prefixes); + * + * if (nextQuery) { + * bucket.getFiles(nextQuery, callback); + * } else { + * // prefixes = The finished array of prefixes. + * } + * } + * + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/' + * }, callback); + * ``` + */ +/** + * Create a Bucket object to interact with a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Storage} storage A {@link Storage} instance. + * @param {string} name The name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.userProject] User project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * ``` + */ +class Bucket extends ServiceObject { + name: string; + + /** + * A reference to the {@link Storage} associated with this {@link Bucket} + * instance. + * @name Bucket#storage + * @type {Storage} + */ + storage: Storage; + + /** + * A user project to apply to each request from this bucket. + * @name Bucket#userProject + * @type {string} + */ + userProject?: string; + + acl: Acl; + iam: Iam; + crc32cGenerator: CRC32CValidatorGenerator; + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getFilesStream(query?: GetFilesOptions): Readable { + // placeholder body, overwritten in constructor + return new Readable(); + } + signer?: URLSigner; + + private instanceRetryValue?: boolean; + instancePreconditionOpts?: PreconditionOptions; + + /** + * Indicates whether this Bucket object is a placeholder for an item + * that the API failed to retrieve (unreachable) due to partial failure. + * Consumers must check this flag before accessing other properties. + */ + unreachable = false; + + constructor(storage: Storage, name: string, options?: BucketOptions) { + options = options || {}; + + // Allow for "gs://"-style input, and strip any trailing slashes. + name = name.replace(/^gs:\/\//, '').replace(/\/+$/, ''); + + const requestQueryObject: { + userProject?: string; + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; + } = {}; + + if (options?.preconditionOpts?.ifGenerationMatch) { + requestQueryObject.ifGenerationMatch = + options.preconditionOpts.ifGenerationMatch; + } + if (options?.preconditionOpts?.ifGenerationNotMatch) { + requestQueryObject.ifGenerationNotMatch = + options.preconditionOpts.ifGenerationNotMatch; + } + if (options?.preconditionOpts?.ifMetagenerationMatch) { + requestQueryObject.ifMetagenerationMatch = + options.preconditionOpts.ifMetagenerationMatch; + } + if (options?.preconditionOpts?.ifMetagenerationNotMatch) { + requestQueryObject.ifMetagenerationNotMatch = + options.preconditionOpts.ifMetagenerationNotMatch; + } + + const userProject = options.userProject; + if (typeof userProject === 'string') { + requestQueryObject.userProject = userProject; + } + + const methods = { + /** + * Create a bucket. + * + * @method Bucket#create + * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket. + * @param {CreateBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * bucket.create(function(err, bucket, apiResponse) { + * if (!err) { + * // The bucket was created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.create().then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + create: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * IamDeleteBucketOptions Configuration options. + * @property {boolean} [ignoreNotFound = false] Ignore an error if + * the bucket does not exist. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} DeleteBucketResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteBucketCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/delete| Buckets: delete API Documentation} + * + * @method Bucket#delete + * @param {DeleteBucketOptions} [options] Configuration options. + * @param {boolean} [options.ignoreNotFound = false] Ignore an error if + * the bucket does not exist. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * bucket.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example + * region_tag:storage_delete_bucket + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} BucketExistsOptions Configuration options for Bucket#exists(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} BucketExistsResponse + * @property {boolean} 0 Whether the {@link Bucket} exists. + */ + /** + * @callback BucketExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link Bucket} exists. + */ + /** + * Check if the bucket exists. + * + * @method Bucket#exists + * @param {BucketExistsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {BucketExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} [GetBucketOptions] Configuration options for Bucket#get() + * @property {boolean} [autoCreate] Automatically create the object if + * it does not exist. Default: `false` + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} GetBucketResponse + * @property {Bucket} 0 The {@link Bucket}. + * @property {object} 1 The full API response. + */ + /** + * @callback GetBucketCallback + * @param {?Error} err Request error, if any. + * @param {Bucket} bucket The {@link Bucket}. + * @param {object} apiResponse The full API response. + */ + /** + * Get a bucket if it exists. + * + * You may optionally use this to "get or create" an object by providing + * an object with `autoCreate` set to `true`. Any extra configuration that + * is normally required for the `create` method must be contained within + * this object as well. + * + * @method Bucket#get + * @param {GetBucketOptions} [options] Configuration options. + * @param {boolean} [options.autoCreate] Automatically create the object if + * it does not exist. Default: `false` + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetBucketCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.get(function(err, bucket, apiResponse) { + * // `bucket.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.get().then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetBucketMetadataResponse + * @property {object} 0 The bucket metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} GetBucketMetadataOptions Configuration options for Bucket#getMetadata(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Get the bucket's metadata. + * + * To set metadata, see {@link Bucket#setMetadata}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/get| Buckets: get API Documentation} + * + * @method Bucket#getMetadata + * @param {GetBucketMetadataOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_get_requester_pays_status + * Example of retrieving the requester pays status of a bucket: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} SetBucketMetadataOptions Configuration options for Bucket#setMetadata(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} SetBucketMetadataResponse + * @property {object} apiResponse The full API response. + */ + /** + * @callback SetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + */ + /** + * Set the bucket's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @method Bucket#setMetadata + * @param {object} metadata The metadata you wish to set. + * @param {SetBucketMetadataOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Set website metadata field on the bucket. + * //- + * const metadata = { + * website: { + * mainPageSuffix: 'http://example.com', + * notFoundPage: 'http://example.com/404.html' + * } + * }; + * + * bucket.setMetadata(metadata, function(err, apiResponse) {}); + * + * //- + * // Enable versioning for your bucket. + * //- + * bucket.setMetadata({ + * versioning: { + * enabled: true + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Enable KMS encryption for objects within this bucket. + * //- + * bucket.setMetadata({ + * encryption: { + * defaultKmsKeyName: 'projects/grape-spaceship-123/...' + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Set the default event-based hold value for new objects in this + * // bucket. + * //- + * bucket.setMetadata({ + * defaultEventBasedHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // Remove object lifecycle rules. + * //- + * bucket.setMetadata({ + * lifecycle: null + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setMetadata(metadata).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + }; + + super({ + parent: storage, + baseUrl: '/b', + id: name, + createMethod: storage.createBucket.bind(storage), + methods, + }); + + this.name = name; + + this.storage = storage; + + this.userProject = options.userProject; + + this.acl = new Acl({ + request: this.request.bind(this), + pathPrefix: '/acl', + }); + + this.acl.default = new Acl({ + request: this.request.bind(this), + pathPrefix: '/defaultObjectAcl', + }); + + this.crc32cGenerator = + options.crc32cGenerator || this.storage.crc32cGenerator; + + this.iam = new Iam(this); + + this.getFilesStream = paginator.streamify('getFiles'); + + this.instanceRetryValue = storage.retryOptions.autoRetry; + this.instancePreconditionOpts = options?.preconditionOpts; + } + + /** + * The bucket's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * // `gs://my-bucket` + * const href = bucket.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI(): URL { + const uri = new URL('gs://'); + + uri.host = this.name; + + return uri; + } + + addLifecycleRule( + rule: LifecycleRule | LifecycleRule[], + options?: AddLifecycleRuleOptions, + ): Promise; + addLifecycleRule( + rule: LifecycleRule | LifecycleRule[], + options: AddLifecycleRuleOptions, + callback: SetBucketMetadataCallback, + ): void; + addLifecycleRule( + rule: LifecycleRule | LifecycleRule[], + callback: SetBucketMetadataCallback, + ): void; + /** + * @typedef {object} AddLifecycleRuleOptions Configuration options for Bucket#addLifecycleRule(). + * @property {boolean} [append=true] The new rules will be appended to any + * pre-existing rules. + */ + /** + * + * @typedef {object} LifecycleRule The new lifecycle rule to be added to objects + * in this bucket. + * @property {string|object} action The action to be taken upon matching of + * all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'. + * **Note**: For configuring a raw-formatted rule object to be passed as `action` + * please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}. + * @property {object} condition Condition a bucket must meet before the + * action occurs on the bucket. Refer to following supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}. + * @property {string} [storageClass] When using the `setStorageClass` + * action, provide this option to dictate which storage class the object + * should update to. Please see + * [SetStorageClass option documentation]{@link https://cloud.google.com/storage/docs/lifecycle#setstorageclass} for supported transitions. + */ + /** + * Add an object lifecycle management rule to the bucket. + * + * By default, an Object Lifecycle Management rule provided to this method + * will be included to the existing policy. To replace all existing rules, + * supply the `options` argument, setting `append` to `false`. + * + * To add multiple rules, pass a list to the `rule` parameter. Calling this + * function multiple times asynchronously does not guarantee that all rules + * are added correctly. + * + * See {@link https://cloud.google.com/storage/docs/lifecycle| Object Lifecycle Management} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {LifecycleRule|LifecycleRule[]} rule The new lifecycle rule or rules to be added to objects + * in this bucket. + * @param {string|object} rule.action The action to be taken upon matching of + * all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'. + * **Note**: For configuring a raw-formatted rule object to be passed as `action` + * please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}. + * @param {object} rule.condition Condition a bucket must meet before the + * action occurs on the bucket. Refer to following supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}. + * @param {string} [rule.storageClass] When using the `setStorageClass` + * action, provide this option to dictate which storage class the object + * should update to. + * @param {AddLifecycleRuleOptions} [options] Configuration object. + * @param {boolean} [options.append=true] Append the new rule to the existing + * policy. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Automatically have an object deleted from this bucket once it is 3 years + * // of age. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * age: 365 * 3 // Specified in days. + * } + * }, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * const lifecycleRules = bucket.metadata.lifecycle.rule; + * + * // Iterate over the Object Lifecycle Management rules on this bucket. + * lifecycleRules.forEach(lifecycleRule => {}); + * }); + * + * //- + * // By default, the rule you provide will be added to the existing policy. + * // Optionally, you can disable this behavior to replace all of the + * // pre-existing rules. + * //- + * const options = { + * append: false + * }; + * + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * age: 365 * 3 // Specified in days. + * } + * }, options, function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // All rules have been replaced with the new "delete" rule. + * + * // Iterate over the Object Lifecycle Management rules on this bucket. + * lifecycleRules.forEach(lifecycleRule => {}); + * }); + * + * //- + * // For objects created before 2018, "downgrade" the storage class. + * //- + * bucket.addLifecycleRule({ + * action: 'setStorageClass', + * storageClass: 'COLDLINE', + * condition: { + * createdBefore: new Date('2018') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete objects created before 2016 which have the Coldline storage + * // class. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * matchesStorageClass: [ + * 'COLDLINE' + * ], + * createdBefore: new Date('2016') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a noncurrent timestamp that is at least 100 days. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * daysSinceNoncurrentTime: 100 + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a noncurrent timestamp before 2020-01-01. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * noncurrentTimeBefore: new Date('2020-01-01') + * } + * }, function(err, apiResponse) {}); + * + * //- + * // Delete object that has a customTime that is at least 100 days. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * daysSinceCustomTime: 100 + * } + * }, function(err, apiResponse) ()); + * + * //- + * // Delete object that has a customTime before 2020-01-01. + * //- + * bucket.addLifecycleRule({ + * action: 'delete', + * condition: { + * customTimeBefore: new Date('2020-01-01') + * } + * }, function(err, apiResponse) {}); + * ``` + */ + addLifecycleRule( + rule: LifecycleRule | LifecycleRule[], + optionsOrCallback?: AddLifecycleRuleOptions | SetBucketMetadataCallback, + callback?: SetBucketMetadataCallback, + ): Promise | void { + let options: AddLifecycleRuleOptions = {}; + + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + options = options || {}; + + const rules = Array.isArray(rule) ? rule : [rule]; + for (const curRule of rules) { + if (curRule.condition.createdBefore instanceof Date) { + curRule.condition.createdBefore = curRule.condition.createdBefore + .toISOString() + .replace(/T.+$/, ''); + } + if (curRule.condition.customTimeBefore instanceof Date) { + curRule.condition.customTimeBefore = curRule.condition.customTimeBefore + .toISOString() + .replace(/T.+$/, ''); + } + if (curRule.condition.noncurrentTimeBefore instanceof Date) { + curRule.condition.noncurrentTimeBefore = + curRule.condition.noncurrentTimeBefore + .toISOString() + .replace(/T.+$/, ''); + } + } + + if (options.append === false) { + this.setMetadata({lifecycle: {rule: rules}}, options, callback!); + return; + } + + // The default behavior appends the previously-defined lifecycle rules with + // the new ones just passed in by the user. + this.getMetadata((err: ApiError | null, metadata: BucketMetadata) => { + if (err) { + callback!(err); + return; + } + + const currentLifecycleRules = Array.isArray(metadata.lifecycle?.rule) + ? metadata.lifecycle?.rule + : []; + + this.setMetadata( + { + lifecycle: {rule: currentLifecycleRules!.concat(rules)}, + }, + options as AddLifecycleRuleOptions, + callback!, + ); + }); + } + + combine( + sources: string[] | File[], + destination: string | File, + options?: CombineOptions, + ): Promise; + combine( + sources: string[] | File[], + destination: string | File, + options: CombineOptions, + callback: CombineCallback, + ): void; + combine( + sources: string[] | File[], + destination: string | File, + callback: CombineCallback, + ): void; + /** + * @typedef {object} CombineOptions + * @property {string} [kmsKeyName] Resource name of the Cloud KMS key, of + * the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback CombineCallback + * @param {?Error} err Request error, if any. + * @param {File} newFile The new {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} CombineResponse + * @property {File} 0 The new {@link File}. + * @property {object} 1 The full API response. + */ + /** + * Combine multiple files into one new file. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/compose| Objects: compose API Documentation} + * + * @throws {Error} if a non-array is provided as sources argument. + * @throws {Error} if no sources are provided. + * @throws {Error} if no destination is provided. + * + * @param {string[]|File[]} sources The source files that will be + * combined. + * @param {string|File} destination The file you would like the + * source files combined into. + * @param {CombineOptions} [options] Configuration options. + * @param {string} [options.kmsKeyName] Resource name of the Cloud KMS key, of + * the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + + * @param {CombineCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const logBucket = storage.bucket('log-bucket'); + * + * const sources = [ + * logBucket.file('2013-logs.txt'), + * logBucket.file('2014-logs.txt') + * ]; + * + * const allLogs = logBucket.file('all-logs.txt'); + * + * logBucket.combine(sources, allLogs, function(err, newFile, apiResponse) { + * // newFile === allLogs + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * logBucket.combine(sources, allLogs).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + combine( + sources: string[] | File[], + destination: string | File, + optionsOrCallback?: CombineOptions | CombineCallback, + callback?: CombineCallback, + ): Promise | void { + if (!Array.isArray(sources) || sources.length === 0) { + throw new Error(BucketExceptionMessages.PROVIDE_SOURCE_FILE); + } + + if (!destination) { + throw new Error(BucketExceptionMessages.DESTINATION_FILE_NOT_SPECIFIED); + } + + let options: CombineOptions = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + this.disableAutoRetryConditionallyIdempotent_( + this.methods.setMetadata, // Not relevant but param is required + AvailableServiceObjectMethods.setMetadata, // Same as above + options, + ); + + const convertToFile = (file: string | File): File => { + if (file instanceof File) { + return file; + } + return this.file(file); + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sources = (sources as any).map(convertToFile); + const destinationFile = convertToFile(destination); + callback = callback || util.noop; + + if (!destinationFile.metadata.contentType) { + const destinationContentType = + mime.getType(destinationFile.name) || undefined; + + if (destinationContentType) { + destinationFile.metadata.contentType = destinationContentType; + } + } + + let maxRetries = this.storage.retryOptions.maxRetries; + if ( + (destinationFile?.instancePreconditionOpts?.ifGenerationMatch === + undefined && + options.ifGenerationMatch === undefined && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever + ) { + maxRetries = 0; + } + + if (options.ifGenerationMatch === undefined) { + Object.assign(options, destinationFile.instancePreconditionOpts, options); + } + + // Make the request from the destination File object. + destinationFile.request( + { + method: 'POST', + uri: '/compose', + maxRetries, + json: { + destination: { + contentType: destinationFile.metadata.contentType, + contentEncoding: destinationFile.metadata.contentEncoding, + }, + sourceObjects: (sources as File[]).map(source => { + const sourceObject = { + name: source.name, + } as SourceObject; + + if (source.metadata && source.metadata.generation) { + sourceObject.generation = parseInt( + source.metadata.generation.toString(), + ); + } + + return sourceObject; + }), + }, + qs: options, + }, + (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback!(err, null, resp); + return; + } + + callback!(null, destinationFile, resp); + }, + ); + } + + createChannel( + id: string, + config: CreateChannelConfig, + options?: CreateChannelOptions, + ): Promise; + createChannel( + id: string, + config: CreateChannelConfig, + callback: CreateChannelCallback, + ): void; + createChannel( + id: string, + config: CreateChannelConfig, + options: CreateChannelOptions, + callback: CreateChannelCallback, + ): void; + /** + * See a {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll request body}. + * + * @typedef {object} CreateChannelConfig + * @property {string} address The address where notifications are + * delivered for this channel. + * @property {string} [delimiter] Returns results in a directory-like mode. + * @property {number} [maxResults] Maximum number of `items` plus `prefixes` + * to return in a single page of responses. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [prefix] Filter results to objects whose names begin + * with this prefix. + * @property {string} [projection=noAcl] Set of properties to return. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {boolean} [versions=false] If `true`, lists all versions of an object + * as distinct results. + */ + /** + * @typedef {object} CreateChannelOptions + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} CreateChannelResponse + * @property {Channel} 0 The new {@link Channel}. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateChannelCallback + * @param {?Error} err Request error, if any. + * @param {Channel} channel The new {@link Channel}. + * @param {object} apiResponse The full API response. + */ + /** + * Create a channel that will be notified when objects in this bucket changes. + * + * @throws {Error} If an ID is not provided. + * @throws {Error} If an address is not provided. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll API Documentation} + * + * @param {string} id The ID of the channel to create. + * @param {CreateChannelConfig} config Configuration for creating channel. + * @param {string} config.address The address where notifications are + * delivered for this channel. + * @param {string} [config.delimiter] Returns results in a directory-like mode. + * @param {number} [config.maxResults] Maximum number of `items` plus `prefixes` + * to return in a single page of responses. + * @param {string} [config.pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @param {string} [config.prefix] Filter results to objects whose names begin + * with this prefix. + * @param {string} [config.projection=noAcl] Set of properties to return. + * @param {string} [config.userProject] The ID of the project which will be + * billed for the request. + * @param {boolean} [config.versions=false] If `true`, lists all versions of an object + * as distinct results. + * @param {CreateChannelOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {CreateChannelCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const id = 'new-channel-id'; + * + * const config = { + * address: 'https://...' + * }; + * + * bucket.createChannel(id, config, function(err, channel, apiResponse) { + * if (!err) { + * // Channel created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.createChannel(id, config).then(function(data) { + * const channel = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + createChannel( + id: string, + config: CreateChannelConfig, + optionsOrCallback?: CreateChannelOptions | CreateChannelCallback, + callback?: CreateChannelCallback, + ): Promise | void { + if (typeof id !== 'string') { + throw new Error(BucketExceptionMessages.CHANNEL_ID_REQUIRED); + } + + let options: CreateChannelOptions = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + this.request( + { + method: 'POST', + uri: '/o/watch', + json: Object.assign( + { + id, + type: 'web_hook', + }, + config, + ), + qs: options, + }, + (err, apiResponse) => { + if (err) { + callback!(err, null, apiResponse); + return; + } + + const resourceId = apiResponse.resourceId; + const channel = this.storage.channel(id, resourceId); + + channel.metadata = apiResponse; + + callback!(null, channel, apiResponse); + }, + ); + } + + createNotification( + topic: string, + options?: CreateNotificationOptions, + ): Promise; + createNotification( + topic: string, + options: CreateNotificationOptions, + callback: CreateNotificationCallback, + ): void; + createNotification(topic: string, callback: CreateNotificationCallback): void; + /** + * Metadata to set for the Notification. + * + * @typedef {object} CreateNotificationOptions + * @property {object} [customAttributes] An optional list of additional + * attributes to attach to each Cloud PubSub message published for this + * notification subscription. + * @property {string[]} [eventTypes] If present, only send notifications about + * listed event types. If empty, sent notifications for all event types. + * @property {string} [objectNamePrefix] If present, only apply this + * notification configuration to object names that begin with this prefix. + * @property {string} [payloadFormat] The desired content of the Payload. + * Defaults to `JSON_API_V1`. + * + * Acceptable values are: + * - `JSON_API_V1` + * + * - `NONE` + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback CreateNotificationCallback + * @param {?Error} err Request error, if any. + * @param {Notification} notification The new {@link Notification}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} CreateNotificationResponse + * @property {Notification} 0 The new {@link Notification}. + * @property {object} 1 The full API response. + */ + /** + * Creates a notification subscription for the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert} + * + * @param {Topic|string} topic The Cloud PubSub topic to which this + * subscription publishes. If the project ID is omitted, the current + * project ID will be used. + * + * Acceptable formats are: + * - `projects/grape-spaceship-123/topics/my-topic` + * + * - `my-topic` + * @param {CreateNotificationOptions} [options] Metadata to set for the + * notification. + * @param {object} [options.customAttributes] An optional list of additional + * attributes to attach to each Cloud PubSub message published for this + * notification subscription. + * @param {string[]} [options.eventTypes] If present, only send notifications about + * listed event types. If empty, sent notifications for all event types. + * @param {string} [options.objectNamePrefix] If present, only apply this + * notification configuration to object names that begin with this prefix. + * @param {string} [options.payloadFormat] The desired content of the Payload. + * Defaults to `JSON_API_V1`. + * + * Acceptable values are: + * - `JSON_API_V1` + * + * - `NONE` + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {CreateNotificationCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a valid topic is not provided. + * @see Notification#create + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const callback = function(err, notification, apiResponse) { + * if (!err) { + * // The notification was created successfully. + * } + * }; + * + * myBucket.createNotification('my-topic', callback); + * + * //- + * // Configure the notification by providing Notification metadata. + * //- + * const metadata = { + * objectNamePrefix: 'prefix-' + * }; + * + * myBucket.createNotification('my-topic', metadata, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * myBucket.createNotification('my-topic').then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_create_bucket_notifications + * Another example: + */ + createNotification( + topic: string, + optionsOrCallback?: CreateNotificationOptions | CreateNotificationCallback, + callback?: CreateNotificationCallback, + ): Promise | void { + let options: CreateNotificationOptions = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + const topicIsObject = topic !== null && typeof topic === 'object'; + if (topicIsObject && util.isCustomType(topic, 'pubsub/topic')) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + topic = (topic as any).name; + } + + if (typeof topic !== 'string') { + throw new Error(BucketExceptionMessages.TOPIC_NAME_REQUIRED); + } + + const body = Object.assign({topic}, options); + + if (body.topic.indexOf('projects') !== 0) { + body.topic = 'projects/{{projectId}}/topics/' + body.topic; + } + + body.topic = `//pubsub.${this.storage.universeDomain}/` + body.topic; + + if (!body.payloadFormat) { + body.payloadFormat = 'JSON_API_V1'; + } + + const query = {} as CreateNotificationQuery; + + if (body.userProject) { + query.userProject = body.userProject; + delete body.userProject; + } + + this.request( + { + method: 'POST', + uri: '/notificationConfigs', + json: convertObjKeysToSnakeCase(body), + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + }, + (err, apiResponse) => { + if (err) { + callback!(err, null, apiResponse); + return; + } + + const notification = this.notification(apiResponse.id); + + notification.metadata = apiResponse; + + callback!(null, notification, apiResponse); + }, + ); + } + + deleteFiles(query?: DeleteFilesOptions): Promise; + deleteFiles(callback: DeleteFilesCallback): void; + deleteFiles(query: DeleteFilesOptions, callback: DeleteFilesCallback): void; + /** + * @typedef {object} DeleteFilesOptions Query object. See {@link Bucket#getFiles} + * for all of the supported properties. + * @property {boolean} [force] Suppress errors until all files have been + * processed. + */ + /** + * @callback DeleteFilesCallback + * @param {?Error|?Error[]} err Request error, if any, or array of errors from + * files that were not able to be deleted. + * @param {object} [apiResponse] The full API response. + */ + /** + * Iterate over the bucket's files, calling `file.delete()` on each. + * + * This is not an atomic request. A delete attempt will be + * made for each file individually. Any one can fail, in which case only a + * portion of the files you intended to be deleted would have. + * + * Operations are performed in parallel, up to 10 at once. The first error + * breaks the loop and will execute the provided callback with it. Specify + * `{ force: true }` to suppress the errors until all files have had a chance + * to be processed. + * + * File preconditions cannot be passed to this function. It will not retry unless + * the idempotency strategy is set to retry always. + * + * The `query` object passed as the first argument will also be passed to + * {@link Bucket#getFiles}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation} + * + * @param {DeleteFilesOptions} [query] Query object. See {@link Bucket#getFiles} + * @param {boolean} [query.force] Suppress errors until all files have been + * processed. + * @param {DeleteFilesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Delete all of the files in the bucket. + * //- + * bucket.deleteFiles(function(err) {}); + * + * //- + * // By default, if a file cannot be deleted, this method will stop deleting + * // files from your bucket. You can override this setting with `force: + * // true`. + * //- + * bucket.deleteFiles({ + * force: true + * }, function(errors) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * }); + * + * //- + * // The first argument to this method acts as a query to + * // {@link Bucket#getFiles}. As an example, you can delete files + * // which match a prefix. + * //- + * bucket.deleteFiles({ + * prefix: 'images/' + * }, function(err) { + * if (!err) { + * // All files in the `images` directory have been deleted. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.deleteFiles().then(function() {}); + * ``` + */ + deleteFiles( + queryOrCallback?: DeleteFilesOptions | DeleteFilesCallback, + callback?: DeleteFilesCallback, + ): Promise | void { + let query: DeleteFilesOptions = {}; + if (typeof queryOrCallback === 'function') { + callback = queryOrCallback; + } else if (queryOrCallback) { + query = queryOrCallback; + } + + const MAX_PARALLEL_LIMIT = 10; + const MAX_QUEUE_SIZE = 1000; + const errors = [] as Error[]; + + const deleteFile = (file: File) => { + return file.delete(query).catch(err => { + if (!query.force) { + throw err; + } + errors.push(err); + }); + }; + + (async () => { + try { + let promises = []; + const limit = pLimit(MAX_PARALLEL_LIMIT); + const filesStream = this.getFilesStream(query); + + for await (const curFile of filesStream) { + if (promises.length >= MAX_QUEUE_SIZE) { + await Promise.all(promises); + promises = []; + } + promises.push( + limit(() => deleteFile(curFile)).catch(e => { + filesStream.destroy(); + throw e; + }), + ); + } + + await Promise.all(promises); + callback!(errors.length > 0 ? errors : null); + } catch (e) { + callback!(e as Error); + return; + } + })(); + } + + deleteLabels(labels?: string | string[]): Promise; + deleteLabels(options: DeleteLabelsOptions): Promise; + deleteLabels(callback: DeleteLabelsCallback): void; + deleteLabels( + labels: string | string[], + options: DeleteLabelsOptions, + ): Promise; + deleteLabels(labels: string | string[], callback: DeleteLabelsCallback): void; + deleteLabels( + labels: string | string[], + options: DeleteLabelsOptions, + callback: DeleteLabelsCallback, + ): void; + /** + * @deprecated + * @typedef {array} DeleteLabelsResponse + * @property {object} 0 The full API response. + */ + /** + * @deprecated + * @callback DeleteLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata Bucket's metadata. + */ + /** + * @deprecated Use setMetadata directly + * Delete one or more labels from this bucket. + * + * @param {string|string[]} [labels] The labels to delete. If no labels are + * provided, all of the labels are removed. + * @param {DeleteLabelsCallback} [callback] Callback function. + * @param {DeleteLabelsOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Delete all of the labels from this bucket. + * //- + * bucket.deleteLabels(function(err, apiResponse) {}); + * + * //- + * // Delete a single label. + * //- + * bucket.deleteLabels('labelone', function(err, apiResponse) {}); + * + * //- + * // Delete a specific set of labels. + * //- + * bucket.deleteLabels([ + * 'labelone', + * 'labeltwo' + * ], function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.deleteLabels().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + deleteLabels( + labelsOrCallbackOrOptions?: + | string + | string[] + | DeleteLabelsCallback + | DeleteLabelsOptions, + optionsOrCallback?: DeleteLabelsCallback | DeleteLabelsOptions, + callback?: DeleteLabelsCallback, + ): Promise | void { + let labels = new Array(); + let options: DeleteLabelsOptions = {}; + + if (typeof labelsOrCallbackOrOptions === 'function') { + callback = labelsOrCallbackOrOptions; + } else if (typeof labelsOrCallbackOrOptions === 'string') { + labels = [labelsOrCallbackOrOptions]; + } else if (Array.isArray(labelsOrCallbackOrOptions)) { + labels = labelsOrCallbackOrOptions; + } else if (labelsOrCallbackOrOptions) { + options = labelsOrCallbackOrOptions; + } + + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + const deleteLabels = (labels: string[]) => { + const nullLabelMap = labels.reduce((nullLabelMap, labelKey) => { + (nullLabelMap as {[index: string]: null})[labelKey] = null; + return nullLabelMap; + }, {}); + + if (options?.ifMetagenerationMatch !== undefined) { + this.setLabels(nullLabelMap, options, callback!); + } else { + this.setLabels(nullLabelMap, callback!); + } + }; + + if (labels.length === 0) { + this.getLabels((err, labels) => { + if (err) { + callback!(err); + return; + } + deleteLabels(Object.keys(labels!)); + }); + } else { + deleteLabels(labels); + } + } + + disableRequesterPays( + options?: DisableRequesterPaysOptions, + ): Promise; + disableRequesterPays(callback: DisableRequesterPaysCallback): void; + disableRequesterPays( + options: DisableRequesterPaysOptions, + callback: DisableRequesterPaysCallback, + ): void; + /** + * @typedef {array} DisableRequesterPaysResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DisableRequesterPaysCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + *
+ * Early Access Testers Only + *

+ * This feature is not yet widely-available. + *

+ *
+ * + * Disable `requesterPays` functionality from this bucket. + * + * @param {DisableRequesterPaysCallback} [callback] Callback function. + * @param {DisableRequesterPaysOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.disableRequesterPays(function(err, apiResponse) { + * if (!err) { + * // requesterPays functionality disabled successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.disableRequesterPays().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example
+ * region_tag:storage_disable_requester_pays + * Example of disabling requester pays: + */ + disableRequesterPays( + optionsOrCallback?: + | DisableRequesterPaysOptions + | DisableRequesterPaysCallback, + callback?: DisableRequesterPaysCallback, + ): Promise | void { + let options: DisableRequesterPaysOptions = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + this.setMetadata( + { + billing: { + requesterPays: false, + }, + }, + options, + callback!, + ); + } + + enableLogging( + config: EnableLoggingOptions, + ): Promise; + enableLogging( + config: EnableLoggingOptions, + callback: SetBucketMetadataCallback, + ): void; + /** + * Configuration object for enabling logging. + * + * @typedef {object} EnableLoggingOptions + * @property {string|Bucket} [bucket] The bucket for the log entries. By + * default, the current bucket is used. + * @property {string} prefix A unique prefix for log object names. + */ + /** + * Enable logging functionality for this bucket. This will make two API + * requests, first to grant Cloud Storage WRITE permission to the bucket, then + * to set the appropriate configuration on the Bucket's metadata. + * + * @param {EnableLoggingOptions} config Configuration options. + * @param {string|Bucket} [config.bucket] The bucket for the log entries. By + * default, the current bucket is used. + * @param {string} config.prefix A unique prefix for log object names. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * const config = { + * prefix: 'log' + * }; + * + * bucket.enableLogging(config, function(err, apiResponse) { + * if (!err) { + * // Logging functionality enabled successfully. + * } + * }); + * + * ``` + * @example + * Optionally, provide a destination bucket. + * ``` + * const config = { + * prefix: 'log', + * bucket: 'destination-bucket' + * }; + * + * bucket.enableLogging(config, function(err, apiResponse) {}); + * ``` + * + * @example + * If the callback is omitted, we'll return a Promise. + * ``` + * bucket.enableLogging(config).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + enableLogging( + config: EnableLoggingOptions, + callback?: SetBucketMetadataCallback, + ): Promise | void { + if ( + !config || + typeof config === 'function' || + typeof config.prefix === 'undefined' + ) { + throw new Error( + BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED, + ); + } + + let logBucket = this.id; + if (config.bucket && config.bucket instanceof Bucket) { + logBucket = config.bucket.id; + } else if (config.bucket && typeof config.bucket === 'string') { + logBucket = config.bucket; + } + + const options: PreconditionOptions = {}; + if (config?.ifMetagenerationMatch) { + options.ifMetagenerationMatch = config.ifMetagenerationMatch; + } + if (config?.ifMetagenerationNotMatch) { + options.ifMetagenerationNotMatch = config.ifMetagenerationNotMatch; + } + (async () => { + try { + const [policy] = await this.iam.getPolicy(); + policy.bindings.push({ + members: ['group:cloud-storage-analytics@google.com'], + role: 'roles/storage.objectCreator', + }); + await this.iam.setPolicy(policy); + this.setMetadata( + { + logging: { + logBucket, + logObjectPrefix: config.prefix, + }, + }, + options, + callback!, + ); + } catch (e) { + callback!(e as Error); + return; + } + })(); + } + + enableRequesterPays( + options?: EnableRequesterPaysOptions, + ): Promise; + enableRequesterPays(callback: EnableRequesterPaysCallback): void; + enableRequesterPays( + options: EnableRequesterPaysOptions, + callback: EnableRequesterPaysCallback, + ): void; + + /** + * @typedef {array} EnableRequesterPaysResponse + * @property {object} 0 The full API response. + */ + /** + * @callback EnableRequesterPaysCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + *
+ * Early Access Testers Only + *

+ * This feature is not yet widely-available. + *

+ *
+ * + * Enable `requesterPays` functionality for this bucket. This enables you, the + * bucket owner, to have the requesting user assume the charges for the access + * to your bucket and its contents. + * + * @param {EnableRequesterPaysCallback | EnableRequesterPaysOptions} [optionsOrCallback] + * Callback function or precondition options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.enableRequesterPays(function(err, apiResponse) { + * if (!err) { + * // requesterPays functionality enabled successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.enableRequesterPays().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example
+ * region_tag:storage_enable_requester_pays + * Example of enabling requester pays: + */ + enableRequesterPays( + optionsOrCallback?: + | EnableRequesterPaysCallback + | EnableRequesterPaysOptions, + cb?: EnableRequesterPaysCallback, + ): Promise | void { + let options: EnableRequesterPaysOptions = {}; + if (typeof optionsOrCallback === 'function') { + cb = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + this.setMetadata( + { + billing: { + requesterPays: true, + }, + }, + options, + cb!, + ); + } + + /** + * Create a {@link File} object. See {@link File} to see how to handle + * the different use cases you may have. + * + * @param {string} name The name of the file in this bucket. + * @param {FileOptions} [options] Configuration options. + * @param {string|number} [options.generation] Only use a specific revision of + * this file. + * @param {string} [options.encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * KMS key ring must use the same location as the bucket. + * @param {string} [options.userProject] The ID of the project which will be + * billed for all requests made from File object. + * @returns {File} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-existing-file.png'); + * ``` + */ + file(name: string, options?: FileOptions): File { + if (!name) { + throw Error(BucketExceptionMessages.SPECIFY_FILE_NAME); + } + + return new File(this, name, options); + } + + getFiles(query?: GetFilesOptions): Promise; + getFiles(query: GetFilesOptions, callback: GetFilesCallback): void; + getFiles(callback: GetFilesCallback): void; + /** + * @typedef {array} GetFilesResponse + * @property {File[]} 0 Array of {@link File} instances. + * @param {object} nextQuery 1 A query object to receive more results. + * @param {object} apiResponse 2 The full API response. + */ + /** + * @callback GetFilesCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files Array of {@link File} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Query object for listing files. + * + * @typedef {object} GetFilesOptions + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {string} [delimiter] Results will contain only objects whose + * names, aside from the prefix, do not contain delimiter. Objects whose + * names, aside from the prefix, contain delimiter will have their name + * truncated after the delimiter, returned in `apiResponse.prefixes`. + * Duplicate prefixes are omitted. + * @property {string} [endOffset] Filter results to objects whose names are + * lexicographically before endOffset. If startOffset is also set, the objects + * listed have names between startOffset (inclusive) and endOffset (exclusive). + * @property {boolean} [includeFoldersAsPrefixes] If true, includes folders and + * managed folders in the set of prefixes returned by the query. Only applicable if + * delimiter is set to / and autoPaginate is set to false. + * See: https://cloud.google.com/storage/docs/managed-folders + * @property {boolean} [includeTrailingDelimiter] If true, objects that end in + * exactly one instance of delimiter have their metadata included in items[] + * in addition to the relevant part of the object name appearing in prefixes[]. + * @property {string} [prefix] Filter results to objects whose names begin + * with this prefix. + * @property {string} [matchGlob] A glob pattern used to filter results, + * for example foo*bar + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {boolean} [softDeleted] If true, only soft-deleted object versions will be + * listed as distinct results in order of generation number. Note `soft_deleted` and + * `versions` cannot be set to true simultaneously. + * @property {string} [startOffset] Filter results to objects whose names are + * lexicographically equal to or after startOffset. If endOffset is also set, + * the objects listed have names between startOffset (inclusive) and endOffset (exclusive). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {boolean} [versions] If true, returns File objects scoped to + * their versions. + */ + /** + * Get {@link File} objects for the files currently in the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/list| Objects: list API Documentation} + * + * @param {GetFilesOptions} [query] Query object for listing files. + * @param {boolean} [query.autoPaginate=true] Have pagination handled + * automatically. + * @param {string} [query.delimiter] Results will contain only objects whose + * names, aside from the prefix, do not contain delimiter. Objects whose + * names, aside from the prefix, contain delimiter will have their name + * truncated after the delimiter, returned in `apiResponse.prefixes`. + * Duplicate prefixes are omitted. + * @param {string} [query.endOffset] Filter results to objects whose names are + * lexicographically before endOffset. If startOffset is also set, the objects + * listed have names between startOffset (inclusive) and endOffset (exclusive). + * @param {boolean} [query.includeFoldersAsPrefixes] If true, includes folders and + * managed folders in the set of prefixes returned by the query. Only applicable if + * delimiter is set to / and autoPaginate is set to false. + * See: https://cloud.google.com/storage/docs/managed-folders + * @param {boolean} [query.includeTrailingDelimiter] If true, objects that end in + * exactly one instance of delimiter have their metadata included in items[] + * in addition to the relevant part of the object name appearing in prefixes[]. + * @param {string} [query.prefix] Filter results to objects whose names begin + * with this prefix. + * @param {number} [query.maxApiCalls] Maximum number of API calls to make. + * @param {number} [query.maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @param {string} [query.pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @param {boolean} [query.softDeleted] If true, only soft-deleted object versions will be + * listed as distinct results in order of generation number. Note `soft_deleted` and + * `versions` cannot be set to true simultaneously. + * @param {string} [query.startOffset] Filter results to objects whose names are + * lexicographically equal to or after startOffset. If endOffset is also set, + * the objects listed have names between startOffset (inclusive) and endOffset (exclusive). + * @param {string} [query.userProject] The ID of the project which will be + * billed for the request. + * @param {boolean} [query.versions] If true, returns File objects scoped to + * their versions. + * @param {GetFilesCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getFiles(function(err, files) { + * if (!err) { + * // files is an array of File objects. + * } + * }); + * + * //- + * // If your bucket has versioning enabled, you can get all of your files + * // scoped to their generation. + * //- + * bucket.getFiles({ + * versions: true + * }, function(err, files) { + * // Each file is scoped to its generation. + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, files, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * bucket.getFiles(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * files[0].metadata; + * + * // However, in cases where you are concerned the metadata could have + * // changed, use the `getMetadata` method. + * files[0].getMetadata(function(err, metadata) {}); + * }; + * + * bucket.getFiles({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getFiles().then(function(data) { + * const files = data[0]; + * }); + * + * ``` + * @example + *
Simulating a File System

With `autoPaginate: false`, it's possible to iterate over files which incorporate a common structure using a delimiter.

Consider the following remote objects:

  1. "a"
  2. "a/b/c/d"
  3. "b/d/e"

Using a delimiter of `/` will return a single file, "a".

`apiResponse.prefixes` will return the "sub-directories" that were found:

  1. "a/"
  2. "b/"
+ * ``` + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/' + * }, function(err, files, nextQuery, apiResponse) { + * // files = [ + * // {File} // File object for file "a" + * // ] + * + * // apiResponse.prefixes = [ + * // 'a/', + * // 'b/' + * // ] + * }); + * ``` + * + * @example + * Using prefixes, it's now possible to simulate a file system with follow-up requests. + * ``` + * bucket.getFiles({ + * autoPaginate: false, + * delimiter: '/', + * prefix: 'a/' + * }, function(err, files, nextQuery, apiResponse) { + * // No files found within "directory" a. + * // files = [] + * + * // However, a "sub-directory" was found. + * // This prefix can be used to continue traversing the "file system". + * // apiResponse.prefixes = [ + * // 'a/b/' + * // ] + * }); + * ``` + * + * @example
+ * region_tag:storage_list_files + * Another example: + * + * @example + * region_tag:storage_list_files_with_prefix + * Example of listing files, filtered by a prefix: + */ + getFiles( + queryOrCallback?: GetFilesOptions | GetFilesCallback, + callback?: GetFilesCallback, + ): void | Promise { + let query = typeof queryOrCallback === 'object' ? queryOrCallback : {}; + if (!callback) { + callback = queryOrCallback as GetFilesCallback; + } + query = Object.assign({}, query); + if ( + query.fields && + query.autoPaginate && + !query.fields.includes('nextPageToken') + ) { + query.fields = `${query.fields},nextPageToken`; + } + + this.request( + { + uri: '/o', + qs: query, + }, + (err, resp) => { + if (err) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (callback as any)(err, null, null, resp); + return; + } + + const itemsArray = resp.items ? resp.items : []; + const files = itemsArray.map((file: FileMetadata) => { + const options = {} as FileOptions; + + if (query.fields) { + const fileInstance = file; + return fileInstance; + } + + if (query.versions) { + options.generation = file.generation; + } + + if (file.kmsKeyName) { + options.kmsKeyName = file.kmsKeyName; + } + + const fileInstance = this.file(file.name!, options); + fileInstance.metadata = file; + + return fileInstance; + }); + + let nextQuery: object | null = null; + if (resp.nextPageToken) { + nextQuery = Object.assign({}, query, { + pageToken: resp.nextPageToken, + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (callback as any)(null, files, nextQuery, resp); + }, + ); + } + + getLabels(options?: GetLabelsOptions): Promise; + getLabels(callback: GetLabelsCallback): void; + getLabels(options: GetLabelsOptions, callback: GetLabelsCallback): void; + /** + * @deprecated + * @typedef {object} GetLabelsOptions Configuration options for Bucket#getLabels(). + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @deprecated + * @typedef {array} GetLabelsResponse + * @property {object} 0 Object of labels currently set on this bucket. + */ + /** + * @deprecated + * @callback GetLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} labels Object of labels currently set on this bucket. + */ + /** + * @deprecated Use getMetadata directly. + * Get the labels currently set on this bucket. + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetLabelsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.getLabels(function(err, labels) { + * if (err) { + * // Error handling omitted. + * } + * + * // labels = { + * // label: 'labelValue', + * // ... + * // } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getLabels().then(function(data) { + * const labels = data[0]; + * }); + * ``` + */ + getLabels( + optionsOrCallback?: GetLabelsOptions | GetLabelsCallback, + callback?: GetLabelsCallback, + ): Promise | void { + let options: GetLabelsOptions = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + this.getMetadata( + options, + (err: ApiError | null, metadata: BucketMetadata | undefined) => { + if (err) { + callback!(err, null); + return; + } + + callback!(null, metadata?.labels || {}); + }, + ); + } + + getNotifications( + options?: GetNotificationsOptions, + ): Promise; + getNotifications(callback: GetNotificationsCallback): void; + getNotifications( + options: GetNotificationsOptions, + callback: GetNotificationsCallback, + ): void; + /** + * @typedef {object} GetNotificationsOptions Configuration options for Bucket#getNotification(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback GetNotificationsCallback + * @param {?Error} err Request error, if any. + * @param {Notification[]} notifications Array of {@link Notification} + * instances. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} GetNotificationsResponse + * @property {Notification[]} 0 Array of {@link Notification} instances. + * @property {object} 1 The full API response. + */ + /** + * Retrieves a list of notification subscriptions for a given bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/list| Notifications: list} + * + * @param {GetNotificationsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * bucket.getNotifications(function(err, notifications, apiResponse) { + * if (!err) { + * // notifications is an array of Notification objects. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getNotifications().then(function(data) { + * const notifications = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_list_bucket_notifications + * Another example: + */ + getNotifications( + optionsOrCallback?: GetNotificationsOptions | GetNotificationsCallback, + callback?: GetNotificationsCallback, + ): Promise | void { + let options: GetNotificationsOptions = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + this.request( + { + uri: '/notificationConfigs', + qs: options, + }, + (err, resp) => { + if (err) { + callback!(err, null, resp); + return; + } + const itemsArray = resp.items ? resp.items : []; + const notifications = itemsArray.map( + (notification: NotificationMetadata) => { + const notificationInstance = this.notification(notification.id!); + notificationInstance.metadata = notification; + return notificationInstance; + }, + ); + + callback!(null, notifications, resp); + }, + ); + } + + getSignedUrl(cfg: GetBucketSignedUrlConfig): Promise; + getSignedUrl( + cfg: GetBucketSignedUrlConfig, + callback: GetSignedUrlCallback, + ): void; + /** + * @typedef {array} GetSignedUrlResponse + * @property {object} 0 The signed URL. + */ + /** + * @callback GetSignedUrlCallback + * @param {?Error} err Request error, if any. + * @param {object} url The signed URL. + */ + /** + * @typedef {object} GetBucketSignedUrlConfig + * @property {string} action Only listing objects within a bucket (HTTP: GET) is supported for bucket-level signed URLs. + * @property {*} expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * @property {string} [version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @property {boolean} [virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @property {string} [cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @property {object} [extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @property {object} [queryParams] Additional query parameters to include + * in the signed URL. + */ + /** + * Get a signed URL to allow limited time access to a bucket. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed URL. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/access-control/signed-urls| Signed URLs Reference} + * + * @throws {Error} if an expiration timestamp from the past is given. + * + * @param {GetBucketSignedUrlConfig} config Configuration object. + * @param {string} config.action Currently only supports "list" (HTTP: GET). + * @param {*} config.expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * @param {string} [config.version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @param {object} [config.extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @property {object} [config.queryParams] Additional query parameters to include + * in the signed URL. + * @param {GetSignedUrlCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * //- + * // Generate a URL that allows temporary access to list files in a bucket. + * //- + * const request = require('request'); + * + * const config = { + * action: 'list', + * expires: '03-17-2025' + * }; + * + * bucket.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The bucket is now available to be listed from this URL. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.getSignedUrl(config).then(function(data) { + * const url = data[0]; + * }); + * ``` + */ + getSignedUrl( + cfg: GetBucketSignedUrlConfig, + callback?: GetSignedUrlCallback, + ): void | Promise { + const method = BucketActionToHTTPMethod[cfg.action]; + + const signConfig: SignerGetSignedUrlConfig = { + method, + expires: cfg.expires, + version: cfg.version, + cname: cfg.cname, + extensionHeaders: cfg.extensionHeaders || {}, + queryParams: cfg.queryParams || {}, + host: cfg.host, + signingEndpoint: cfg.signingEndpoint, + }; + + if (!this.signer) { + this.signer = new URLSigner( + this.storage.authClient, + this, + undefined, + this.storage, + ); + } + + this.signer + .getSignedUrl(signConfig) + .then(signedUrl => callback!(null, signedUrl), callback!); + } + + lock(metageneration: number | string): Promise; + lock(metageneration: number | string, callback: BucketLockCallback): void; + /** + * @callback BucketLockCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Lock a previously-defined retention policy. This will prevent changes to + * the policy. + * + * @throws {Error} if a metageneration is not provided. + * + * @param {number|string} metageneration The bucket's metageneration. This is + * accessible from calling {@link File#getMetadata}. + * @param {BucketLockCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const metageneration = 2; + * + * bucket.lock(metageneration, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.lock(metageneration).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + lock( + metageneration: number | string, + callback?: BucketLockCallback, + ): Promise | void { + const metatype = typeof metageneration; + if (metatype !== 'number' && metatype !== 'string') { + throw new Error(BucketExceptionMessages.METAGENERATION_NOT_PROVIDED); + } + + this.request( + { + method: 'POST', + uri: '/lockRetentionPolicy', + qs: { + ifMetagenerationMatch: metageneration, + }, + }, + callback!, + ); + } + + /** + * @typedef {object} RestoreOptions Options for Bucket#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/restore#resource| Object resource}. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + */ + /** + * Restores a soft-deleted bucket + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + async restore(options: RestoreOptions): Promise { + const [bucket] = await this.request({ + method: 'POST', + uri: '/restore', + qs: options, + }); + + return bucket as Bucket; + } + + makePrivate( + options?: MakeBucketPrivateOptions, + ): Promise; + makePrivate(callback: MakeBucketPrivateCallback): void; + makePrivate( + options: MakeBucketPrivateOptions, + callback: MakeBucketPrivateCallback, + ): void; + /** + * @typedef {array} MakeBucketPrivateResponse + * @property {File[]} 0 List of files made private. + */ + /** + * @callback MakeBucketPrivateCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files List of files made private. + */ + /** + * @typedef {object} MakeBucketPrivateOptions + * @property {boolean} [includeFiles=false] Make each file in the bucket + * private. + * @property {Metadata} [metadata] Define custom metadata properties to define + * along with the operation. + * @property {boolean} [force] Queue errors occurred while making files + * private until all files have been processed. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Make the bucket listing private. + * + * You may also choose to make the contents of the bucket private by + * specifying `includeFiles: true`. This will automatically run + * {@link File#makePrivate} for every file in the bucket. + * + * When specifying `includeFiles: true`, use `force: true` to delay execution + * of your callback until all files have been processed. By default, the + * callback is executed after the first error. Use `force` to queue such + * errors until all files have been processed, after which they will be + * returned as an array as the first argument to your callback. + * + * NOTE: This may cause the process to be long-running and use a high number + * of requests. Use with caution. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {MakeBucketPrivateOptions} [options] Configuration options. + * @param {boolean} [options.includeFiles=false] Make each file in the bucket + * private. + * @param {Metadata} [options.metadata] Define custom metadata properties to define + * along with the operation. + * @param {boolean} [options.force] Queue errors occurred while making files + * private until all files have been processed. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {MakeBucketPrivateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Make the bucket private. + * //- + * bucket.makePrivate(function(err) {}); + * + * //- + * // Make the bucket and its contents private. + * //- + * const opts = { + * includeFiles: true + * }; + * + * bucket.makePrivate(opts, function(err, files) { + * // `err`: + * // The first error to occur, otherwise null. + * // + * // `files`: + * // Array of files successfully made private in the bucket. + * }); + * + * //- + * // Make the bucket and its contents private, using force to suppress errors + * // until all files have been processed. + * //- + * const opts = { + * includeFiles: true, + * force: true + * }; + * + * bucket.makePrivate(opts, function(errors, files) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * // + * // `files`: + * // Array of files successfully made private in the bucket. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.makePrivate(opts).then(function(data) { + * const files = data[0]; + * }); + * ``` + */ + makePrivate( + optionsOrCallback?: MakeBucketPrivateOptions | MakeBucketPrivateCallback, + callback?: MakeBucketPrivateCallback, + ): Promise | void { + const options: MakeBucketPrivateRequest = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + options.private = true; + + const query: MetadataOptions = { + predefinedAcl: 'projectPrivate', + }; + + if (options.userProject) { + query.userProject = options.userProject; + } + + if (options.preconditionOpts?.ifGenerationMatch) { + query.ifGenerationMatch = options.preconditionOpts.ifGenerationMatch; + } + + if (options.preconditionOpts?.ifGenerationNotMatch) { + query.ifGenerationNotMatch = + options.preconditionOpts.ifGenerationNotMatch; + } + + if (options.preconditionOpts?.ifMetagenerationMatch) { + query.ifMetagenerationMatch = + options.preconditionOpts.ifMetagenerationMatch; + } + + if (options.preconditionOpts?.ifMetagenerationNotMatch) { + query.ifMetagenerationNotMatch = + options.preconditionOpts.ifMetagenerationNotMatch; + } + + // You aren't allowed to set both predefinedAcl & acl properties on a bucket + // so acl must explicitly be nullified. + const metadata = {...options.metadata, acl: null}; + + this.setMetadata(metadata, query, (err: Error | null | undefined) => { + if (err) { + callback!(err); + } + const internalCall = () => { + if (options.includeFiles) { + return promisify( + this.makeAllFilesPublicPrivate_, + ).call(this, options); + } + return Promise.resolve([] as File[]); + }; + internalCall() + .then(files => callback!(null, files)) + .catch(callback!); + }); + } + + makePublic( + options?: MakeBucketPublicOptions, + ): Promise; + makePublic(callback: MakeBucketPublicCallback): void; + makePublic( + options: MakeBucketPublicOptions, + callback: MakeBucketPublicCallback, + ): void; + /** + * @typedef {object} MakeBucketPublicOptions + * @property {boolean} [includeFiles=false] Make each file in the bucket + * private. + * @property {boolean} [force] Queue errors occurred while making files + * private until all files have been processed. + */ + /** + * @callback MakeBucketPublicCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files List of files made public. + */ + /** + * @typedef {array} MakeBucketPublicResponse + * @property {File[]} 0 List of files made public. + */ + /** + * Make the bucket publicly readable. + * + * You may also choose to make the contents of the bucket publicly readable by + * specifying `includeFiles: true`. This will automatically run + * {@link File#makePublic} for every file in the bucket. + * + * When specifying `includeFiles: true`, use `force: true` to delay execution + * of your callback until all files have been processed. By default, the + * callback is executed after the first error. Use `force` to queue such + * errors until all files have been processed, after which they will be + * returned as an array as the first argument to your callback. + * + * NOTE: This may cause the process to be long-running and use a high number + * of requests. Use with caution. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation} + * + * @param {MakeBucketPublicOptions} [options] Configuration options. + * @param {boolean} [options.includeFiles=false] Make each file in the bucket + * private. + * @param {boolean} [options.force] Queue errors occurred while making files + * private until all files have been processed. + * @param {MakeBucketPublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Make the bucket publicly readable. + * //- + * bucket.makePublic(function(err) {}); + * + * //- + * // Make the bucket and its contents publicly readable. + * //- + * const opts = { + * includeFiles: true + * }; + * + * bucket.makePublic(opts, function(err, files) { + * // `err`: + * // The first error to occur, otherwise null. + * // + * // `files`: + * // Array of files successfully made public in the bucket. + * }); + * + * //- + * // Make the bucket and its contents publicly readable, using force to + * // suppress errors until all files have been processed. + * //- + * const opts = { + * includeFiles: true, + * force: true + * }; + * + * bucket.makePublic(opts, function(errors, files) { + * // `errors`: + * // Array of errors if any occurred, otherwise null. + * // + * // `files`: + * // Array of files successfully made public in the bucket. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.makePublic(opts).then(function(data) { + * const files = data[0]; + * }); + * ``` + */ + makePublic( + optionsOrCallback?: MakeBucketPublicOptions | MakeBucketPublicCallback, + callback?: MakeBucketPublicCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + const req = {public: true, ...options}; + + this.acl + .add({ + entity: 'allUsers', + role: 'READER', + }) + .then(() => { + return this.acl.default!.add({ + entity: 'allUsers', + role: 'READER', + }); + }) + .then(() => { + if (req.includeFiles) { + return promisify( + this.makeAllFilesPublicPrivate_, + ).call(this, req); + } + return []; + }) + .then(files => callback!(null, files), callback); + } + + /** + * Get a reference to a Cloud Pub/Sub Notification. + * + * @param {string} id ID of notification. + * @returns {Notification} + * @see Notification + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const notification = bucket.notification('1'); + * ``` + */ + notification(id: string): Notification { + if (!id) { + throw new Error(BucketExceptionMessages.SUPPLY_NOTIFICATION_ID); + } + + return new Notification(this, id); + } + + removeRetentionPeriod( + options?: SetBucketMetadataOptions, + ): Promise; + removeRetentionPeriod(callback: SetBucketMetadataCallback): void; + removeRetentionPeriod( + options: SetBucketMetadataOptions, + callback: SetBucketMetadataCallback, + ): void; + /** + * Remove an already-existing retention policy from this bucket, if it is not + * locked. + * + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataOptions} [options] Options, including precondition options + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * bucket.removeRetentionPeriod(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.removeRetentionPeriod().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + removeRetentionPeriod( + optionsOrCallback?: SetBucketMetadataOptions | SetBucketMetadataCallback, + callback?: SetBucketMetadataCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + this.setMetadata( + { + retentionPolicy: null, + }, + options, + callback!, + ); + } + + request(reqOpts: DecorateRequestOptions): Promise; + request( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void; + /** + * Makes request and applies userProject query parameter if necessary. + * + * @private + * + * @param {object} reqOpts - The request options. + * @param {function} callback - The callback function. + */ + request( + reqOpts: DecorateRequestOptions, + callback?: BodyResponseCallback, + ): void | Promise { + if (this.userProject && (!reqOpts.qs || !reqOpts.qs.userProject)) { + reqOpts.qs = {...reqOpts.qs, userProject: this.userProject}; + } + return super.request(reqOpts, callback!); + } + + setLabels( + labels: Labels, + options?: SetLabelsOptions, + ): Promise; + setLabels(labels: Labels, callback: SetLabelsCallback): void; + setLabels( + labels: Labels, + options: SetLabelsOptions, + callback: SetLabelsCallback, + ): void; + /** + * @deprecated + * @typedef {array} SetLabelsResponse + * @property {object} 0 The bucket metadata. + */ + /** + * @deprecated + * @callback SetLabelsCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The bucket metadata. + */ + /** + * @deprecated + * @typedef {object} SetLabelsOptions Configuration options for Bucket#setLabels(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @deprecated Use setMetadata directly. + * Set labels on the bucket. + * + * This makes an underlying call to {@link Bucket#setMetadata}, which + * is a PATCH request. This means an individual label can be overwritten, but + * unmentioned labels will not be touched. + * + * @param {object} labels Labels to set on the bucket. + * @param {SetLabelsOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetLabelsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * const labels = { + * labelone: 'labelonevalue', + * labeltwo: 'labeltwovalue' + * }; + * + * bucket.setLabels(labels, function(err, metadata) { + * if (!err) { + * // Labels set successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setLabels(labels).then(function(data) { + * const metadata = data[0]; + * }); + * ``` + */ + setLabels( + labels: Labels, + optionsOrCallback?: SetLabelsOptions | SetLabelsCallback, + callback?: SetLabelsCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + callback = callback || util.noop; + + this.setMetadata({labels}, options, callback); + } + + setMetadata( + metadata: BucketMetadata, + options?: SetMetadataOptions, + ): Promise>; + setMetadata( + metadata: BucketMetadata, + callback: MetadataCallback, + ): void; + setMetadata( + metadata: BucketMetadata, + options: SetMetadataOptions, + callback: MetadataCallback, + ): void; + setMetadata( + metadata: BucketMetadata, + optionsOrCallback: SetMetadataOptions | MetadataCallback, + cb?: MetadataCallback, + ): Promise> | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as MetadataCallback) + : cb; + + this.disableAutoRetryConditionallyIdempotent_( + this.methods.setMetadata, + AvailableServiceObjectMethods.setMetadata, + options, + ); + + super + .setMetadata(metadata, options) + .then(resp => cb!(null, ...resp)) + .catch(cb!) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + + setRetentionPeriod( + duration: number, + options?: SetBucketMetadataOptions, + ): Promise; + setRetentionPeriod( + duration: number, + callback: SetBucketMetadataCallback, + ): void; + setRetentionPeriod( + duration: number, + options: SetBucketMetadataOptions, + callback: SetBucketMetadataCallback, + ): void; + /** + * Lock all objects contained in the bucket, based on their creation time. Any + * attempt to overwrite or delete objects younger than the retention period + * will result in a `PERMISSION_DENIED` error. + * + * An unlocked retention policy can be modified or removed from the bucket via + * {@link File#removeRetentionPeriod} and {@link File#setRetentionPeriod}. A + * locked retention policy cannot be removed or shortened in duration for the + * lifetime of the bucket. Attempting to remove or decrease period of a locked + * retention policy will result in a `PERMISSION_DENIED` error. You can still + * increase the policy. + * + * @param {*} duration In seconds, the minimum retention time for all objects + * contained in this bucket. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataCallback} [options] Options, including precondition options. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const DURATION_SECONDS = 15780000; // 6 months. + * + * //- + * // Lock the objects in this bucket for 6 months. + * //- + * bucket.setRetentionPeriod(DURATION_SECONDS, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setRetentionPeriod(DURATION_SECONDS).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setRetentionPeriod( + duration: number, + optionsOrCallback?: SetBucketMetadataOptions | SetBucketMetadataCallback, + callback?: SetBucketMetadataCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + this.setMetadata( + { + retentionPolicy: { + retentionPeriod: duration.toString(), + }, + }, + options, + callback!, + ); + } + + setCorsConfiguration( + corsConfiguration: Cors[], + options?: SetBucketMetadataOptions, + ): Promise; + setCorsConfiguration( + corsConfiguration: Cors[], + callback: SetBucketMetadataCallback, + ): void; + setCorsConfiguration( + corsConfiguration: Cors[], + options: SetBucketMetadataOptions, + callback: SetBucketMetadataCallback, + ): void; + /** + * + * @typedef {object} Cors + * @property {number} [maxAgeSeconds] The number of seconds the browser is + * allowed to make requests before it must repeat the preflight request. + * @property {string[]} [method] HTTP method allowed for cross origin resource + * sharing with this bucket. + * @property {string[]} [origin] an origin allowed for cross origin resource + * sharing with this bucket. + * @property {string[]} [responseHeader] A header allowed for cross origin + * resource sharing with this bucket. + */ + /** + * This can be used to set the CORS configuration on the bucket. + * + * The configuration will be overwritten with the value passed into this. + * + * @param {Cors[]} corsConfiguration The new CORS configuration to set + * @param {number} [corsConfiguration.maxAgeSeconds] The number of seconds the browser is + * allowed to make requests before it must repeat the preflight request. + * @param {string[]} [corsConfiguration.method] HTTP method allowed for cross origin resource + * sharing with this bucket. + * @param {string[]} [corsConfiguration.origin] an origin allowed for cross origin resource + * sharing with this bucket. + * @param {string[]} [corsConfiguration.responseHeader] A header allowed for cross origin + * resource sharing with this bucket. + * @param {SetBucketMetadataCallback} [callback] Callback function. + * @param {SetBucketMetadataOptions} [options] Options, including precondition options. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const bucket = storage.bucket('albums'); + * + * const corsConfiguration = [{maxAgeSeconds: 3600}]; // 1 hour + * bucket.setCorsConfiguration(corsConfiguration); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setCorsConfiguration(corsConfiguration).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setCorsConfiguration( + corsConfiguration: Cors[], + optionsOrCallback?: SetBucketMetadataOptions | SetBucketMetadataCallback, + callback?: SetBucketMetadataCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + this.setMetadata( + { + cors: corsConfiguration, + }, + options, + callback!, + ); + } + + setStorageClass( + storageClass: string, + options?: SetBucketStorageClassOptions, + ): Promise; + setStorageClass( + storageClass: string, + callback: SetBucketStorageClassCallback, + ): void; + setStorageClass( + storageClass: string, + options: SetBucketStorageClassOptions, + callback: SetBucketStorageClassCallback, + ): void; + /** + * @typedef {object} SetBucketStorageClassOptions + * @property {string} [userProject] - The ID of the project which will be + * billed for the request. + */ + /** + * @callback SetBucketStorageClassCallback + * @param {?Error} err Request error, if any. + */ + /** + * Set the default storage class for new files in this bucket. + * + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} storageClass The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`). + * **Note:** The storage classes `multi_regional`, `regional`, and + * `durable_reduced_availability` are now legacy and will be deprecated in + * the future. + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] - The ID of the project which will be + * billed for the request. + * @param {SetStorageClassCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.setStorageClass('nearline', function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // The storage class was updated successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.setStorageClass('nearline').then(function() {}); + * ``` + */ + setStorageClass( + storageClass: string, + optionsOrCallback?: + | SetBucketStorageClassOptions + | SetBucketStorageClassCallback, + callback?: SetBucketStorageClassCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + // In case we get input like `storageClass`, convert to `storage_class`. + storageClass = storageClass + .replace(/-/g, '_') + .replace(/([a-z])([A-Z])/g, (_, low, up) => { + return low + '_' + up; + }) + .toUpperCase(); + + this.setMetadata({storageClass}, options, callback!); + } + + /** + * Set a user project to be billed for all requests made from this Bucket + * object and any files referenced from this Bucket object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * bucket.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject: string) { + this.userProject = userProject; + + const methods = [ + 'create', + 'delete', + 'exists', + 'get', + 'getMetadata', + 'setMetadata', + ]; + methods.forEach(method => { + const methodConfig = this.methods[method]; + if (typeof methodConfig === 'object') { + if (typeof methodConfig.reqOpts === 'object') { + Object.assign(methodConfig.reqOpts.qs, {userProject}); + } else { + methodConfig.reqOpts = { + qs: {userProject}, + }; + } + } + }); + } + + upload(pathString: string, options?: UploadOptions): Promise; + upload( + pathString: string, + options: UploadOptions, + callback: UploadCallback, + ): void; + upload(pathString: string, callback: UploadCallback): void; + /** + * @typedef {object} UploadOptions Configuration options for Bucket#upload(). + * @property {string|File} [destination] The place to save + * your file. If given a string, the file will be uploaded to the bucket + * using the string as a filename. When given a File object, your local + * file will be uploaded to the File object's bucket and under the File + * object's name. Lastly, when this argument is omitted, the file is uploaded + * to your bucket using the name of the local file. + * @property {string} [encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @property {boolean} [gzip] Automatically gzip the file. This will set + * `options.metadata.contentEncoding` to `gzip`. + * @property {string} [kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * @property {object} [metadata] See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}. + * @property {string} [offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {boolean} [resumable=true] Resumable uploads are automatically + * enabled and must be shut off explicitly by setting to false. + * @property {number} [timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @property {string} [uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with an + * MD5 checksum for maximum reliability. CRC32c will provide better + * performance with less reliability. You may also choose to skip + * validation completely, however this is **not recommended**. + */ + /** + * @typedef {array} UploadResponse + * @property {object} 0 The uploaded {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback UploadCallback + * @param {?Error} err Request error, if any. + * @param {object} file The uploaded {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * Upload a file to the bucket. This is a convenience method that wraps + * {@link File#createWriteStream}. + * + * Resumable uploads are enabled by default + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#uploads| Upload Options (Simple or Resumable)} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert| Objects: insert API Documentation} + * + * @param {string} pathString The fully qualified path to the file you + * wish to upload to your bucket. + * @param {UploadOptions} [options] Configuration options. + * @param {string|File} [options.destination] The place to save + * your file. If given a string, the file will be uploaded to the bucket + * using the string as a filename. When given a File object, your local + * file will be uploaded to the File object's bucket and under the File + * object's name. Lastly, when this argument is omitted, the file is uploaded + * to your bucket using the name of the local file. + * @param {string} [options.encryptionKey] A custom encryption key. See + * {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}. + * @param {boolean} [options.gzip] Automatically gzip the file. This will set + * `options.metadata.contentEncoding` to `gzip`. + * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will + * be used to encrypt the object. Must be in the format: + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`. + * @param {object} [options.metadata] See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}. + * @param {string} [options.offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @param {string} [options.predefinedAcl] Apply a predefined set of access + * controls to this object. + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @param {boolean} [options.private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @param {boolean} [options.public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @param {boolean} [options.resumable=true] Resumable uploads are automatically + * enabled and must be shut off explicitly by setting to false. + * @param {number} [options.timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @param {string} [options.uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {string|boolean} [options.validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with an + * MD5 checksum for maximum reliability. CRC32c will provide better + * performance with less reliability. You may also choose to skip + * validation completely, however this is **not recommended**. + * @param {UploadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * + * //- + * // Upload a file from a local path. + * //- + * bucket.upload('/local/path/image.png', function(err, file, apiResponse) { + * // Your bucket now contains: + * // - "image.png" (with the contents of `/local/path/image.png') + * + * // `file` is an instance of a File object that refers to your new file. + * }); + * + * + * //- + * // It's not always that easy. You will likely want to specify the filename + * // used when your new file lands in your bucket. + * // + * // You may also want to set metadata or customize other options. + * //- + * const options = { + * destination: 'new-image.png', + * validation: 'crc32c', + * metadata: { + * metadata: { + * event: 'Fall trip to the zoo' + * } + * } + * }; + * + * bucket.upload('local-image.png', options, function(err, file) { + * // Your bucket now contains: + * // - "new-image.png" (with the contents of `local-image.png') + * + * // `file` is an instance of a File object that refers to your new file. + * }); + * + * //- + * // You can also have a file gzip'd on the fly. + * //- + * bucket.upload('index.html', { gzip: true }, function(err, file) { + * // Your bucket now contains: + * // - "index.html" (automatically compressed with gzip) + * + * // Downloading the file with `file.download` will automatically decode + * the + * // file. + * }); + * + * //- + * // You may also re-use a File object, {File}, that references + * // the file you wish to create or overwrite. + * //- + * const options = { + * destination: bucket.file('existing-file.png'), + * resumable: false + * }; + * + * bucket.upload('local-img.png', options, function(err, newFile) { + * // Your bucket now contains: + * // - "existing-file.png" (with the contents of `local-img.png') + * + * // Note: + * // The `newFile` parameter is equal to `file`. + * }); + * + * //- + * // To use + * // + * // Customer-supplied Encryption Keys, provide the `encryptionKey` + * option. + * //- + * const crypto = require('crypto'); + * const encryptionKey = crypto.randomBytes(32); + * + * bucket.upload('img.png', { + * encryptionKey: encryptionKey + * }, function(err, newFile) { + * // `img.png` was uploaded with your custom encryption key. + * + * // `newFile` is already configured to use the encryption key when making + * // operations on the remote object. + * + * // However, to use your encryption key later, you must create a `File` + * // instance with the `key` supplied: + * const file = bucket.file('img.png', { + * encryptionKey: encryptionKey + * }); + * + * // Or with `file#setEncryptionKey`: + * const file = bucket.file('img.png'); + * file.setEncryptionKey(encryptionKey); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.upload('local-image.png').then(function(data) { + * const file = data[0]; + * }); + * + * To upload a file from a URL, use {@link File#createWriteStream}. + * + * ``` + * @example + * region_tag:storage_upload_file + * Another example: + * + * @example + * region_tag:storage_upload_encrypted_file + * Example of uploading an encrypted file: + */ + upload( + pathString: string, + optionsOrCallback?: UploadOptions | UploadCallback, + callback?: UploadCallback, + ): Promise | void { + const upload = (numberOfRetries: number | undefined) => { + const returnValue = AsyncRetry( + async (bail: (err: Error) => void) => { + await new Promise((resolve, reject) => { + if ( + numberOfRetries === 0 && + newFile?.storage?.retryOptions?.autoRetry + ) { + newFile.storage.retryOptions.autoRetry = false; + } + const writable = newFile.createWriteStream(options); + if (options.onUploadProgress) { + writable.on('progress', options.onUploadProgress); + } + fs.createReadStream(pathString) + .on('error', bail) + .pipe(writable) + .on('error', err => { + if ( + this.storage.retryOptions.autoRetry && + this.storage.retryOptions.retryableErrorFn!(err) + ) { + return reject(err); + } else { + return bail(err); + } + }) + .on('finish', () => { + return resolve(); + }); + }); + }, + { + retries: numberOfRetries, + factor: this.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.storage.retryOptions.maxRetryDelay! * 1000, //convert to milliseconds + maxRetryTime: this.storage.retryOptions.totalTimeout! * 1000, //convert to milliseconds + }, + ); + + if (!callback) { + return returnValue; + } else { + return returnValue + .then(() => { + if (callback) { + return callback!(null, newFile, newFile.metadata); + } + }) + .catch(callback); + } + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if ((global as any)['GCLOUD_SANDBOX_ENV']) { + return; + } + + let options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + options = Object.assign( + { + metadata: {}, + }, + options, + ); + + // Do not retry if precondition option ifGenerationMatch is not set + // because this is a file operation + let maxRetries = this.storage.retryOptions.maxRetries; + if ( + (options?.preconditionOpts?.ifGenerationMatch === undefined && + this.instancePreconditionOpts?.ifGenerationMatch === undefined && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever + ) { + maxRetries = 0; + } + + let newFile: File; + if (options.destination instanceof File) { + newFile = options.destination; + } else if ( + options.destination !== null && + typeof options.destination === 'string' + ) { + // Use the string as the name of the file. + newFile = this.file(options.destination, { + encryptionKey: options.encryptionKey, + kmsKeyName: options.kmsKeyName, + preconditionOpts: this.instancePreconditionOpts, + }); + } else { + // Resort to using the name of the incoming file. + const destination = path.basename(pathString); + newFile = this.file(destination, { + encryptionKey: options.encryptionKey, + kmsKeyName: options.kmsKeyName, + preconditionOpts: this.instancePreconditionOpts, + }); + } + + upload(maxRetries); + } + + makeAllFilesPublicPrivate_( + options?: MakeAllFilesPublicPrivateOptions, + ): Promise; + makeAllFilesPublicPrivate_(callback: MakeAllFilesPublicPrivateCallback): void; + makeAllFilesPublicPrivate_( + options: MakeAllFilesPublicPrivateOptions, + callback: MakeAllFilesPublicPrivateCallback, + ): void; + /** + * @private + * + * @typedef {object} MakeAllFilesPublicPrivateOptions + * @property {boolean} [force] Suppress errors until all files have been + * processed. + * @property {boolean} [private] Make files private. + * @property {boolean} [public] Make files public. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @private + * + * @callback SetBucketMetadataCallback + * @param {?Error} err Request error, if any. + * @param {File[]} files Files that were updated. + */ + /** + * @typedef {array} MakeAllFilesPublicPrivateResponse + * @property {File[]} 0 List of files affected. + */ + /** + * Iterate over all of a bucket's files, calling `file.makePublic()` (public) + * or `file.makePrivate()` (private) on each. + * + * Operations are performed in parallel, up to 10 at once. The first error + * breaks the loop, and will execute the provided callback with it. Specify + * `{ force: true }` to suppress the errors. + * + * @private + * + * @param {MakeAllFilesPublicPrivateOptions} [options] Configuration options. + * @param {boolean} [options.force] Suppress errors until all files have been + * processed. + * @param {boolean} [options.private] Make files private. + * @param {boolean} [options.public] Make files public. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + + * @param {MakeAllFilesPublicPrivateCallback} callback Callback function. + * + * @return {Promise} + */ + makeAllFilesPublicPrivate_( + optionsOrCallback?: + | MakeAllFilesPublicPrivateOptions + | MakeAllFilesPublicPrivateCallback, + callback?: MakeAllFilesPublicPrivateCallback, + ): Promise | void { + const MAX_PARALLEL_LIMIT = 10; + const errors = [] as Error[]; + const updatedFiles = [] as File[]; + + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + const processFile = async (file: File) => { + try { + await (options.public ? file.makePublic() : file.makePrivate(options)); + updatedFiles.push(file); + } catch (e) { + if (!options.force) { + throw e; + } + errors.push(e as Error); + } + }; + + this.getFiles(options) + .then(([files]) => { + const limit = pLimit(MAX_PARALLEL_LIMIT); + const promises = files.map(file => { + return limit(() => processFile(file)); + }); + return Promise.all(promises); + }) + .then( + () => callback!(errors.length > 0 ? errors : null, updatedFiles), + err => callback!(err, updatedFiles), + ); + } + + getId(): string { + return this.id!; + } + + disableAutoRetryConditionallyIdempotent_( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coreOpts: any, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodType: AvailableServiceObjectMethods, + localPreconditionOptions?: PreconditionOptions, + ): void { + if ( + typeof coreOpts === 'object' && + coreOpts?.reqOpts?.qs?.ifMetagenerationMatch === undefined && + localPreconditionOptions?.ifMetagenerationMatch === undefined && + (methodType === AvailableServiceObjectMethods.setMetadata || + methodType === AvailableServiceObjectMethods.delete) && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional + ) { + this.storage.retryOptions.autoRetry = false; + } else if ( + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever + ) { + this.storage.retryOptions.autoRetry = false; + } + } +} + +/*! Developer Documentation + * + * These methods can be auto-paginated. + */ +paginator.extend(Bucket, 'getFiles'); + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Bucket, { + exclude: ['cloudStorageURI', 'request', 'file', 'notification', 'restore'], +}); + +/** + * Reference to the {@link Bucket} class. + * @name module:@google-cloud/storage.Bucket + * @see Bucket + */ +export {Bucket}; diff --git a/handwritten/storage/src/channel.ts b/handwritten/storage/src/channel.ts new file mode 100644 index 00000000000..eccb2707194 --- /dev/null +++ b/handwritten/storage/src/channel.ts @@ -0,0 +1,126 @@ +// Copyright 2019 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 {BaseMetadata, ServiceObject, util} from './nodejs-common/index.js'; +import {promisifyAll} from '@google-cloud/promisify'; + +import {Storage} from './storage.js'; + +export interface StopCallback { + (err: Error | null, apiResponse?: unknown): void; +} + +/** + * Create a channel object to interact with a Cloud Storage channel. + * + * See {@link https://cloud.google.com/storage/docs/object-change-notification| Object Change Notification} + * + * @class + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ +class Channel extends ServiceObject { + constructor(storage: Storage, id: string, resourceId: string) { + const config = { + parent: storage, + baseUrl: '/channels', + + // An ID shouldn't be included in the API requests. + // RE: + // https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1145 + id: '', + + methods: { + // Only need `request`. + }, + }; + + super(config); + + this.metadata.id = id; + this.metadata.resourceId = resourceId; + } + + stop(): Promise; + stop(callback: StopCallback): void; + /** + * @typedef {array} StopResponse + * @property {object} 0 The full API response. + */ + /** + * @callback StopCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Stop this channel. + * + * @param {StopCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * channel.stop(function(err, apiResponse) { + * if (!err) { + * // Channel stopped successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * channel.stop().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + stop(callback?: StopCallback): Promise | void { + callback = callback || util.noop; + this.request( + { + method: 'POST', + uri: '/stop', + json: this.metadata, + }, + (err, apiResponse) => { + callback!(err, apiResponse); + }, + ); + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Channel); + +/** + * Reference to the {@link Channel} class. + * @name module:@google-cloud/storage.Channel + * @see Channel + */ +export {Channel}; diff --git a/handwritten/storage/src/crc32c.ts b/handwritten/storage/src/crc32c.ts new file mode 100644 index 00000000000..5d4ac75a6c9 --- /dev/null +++ b/handwritten/storage/src/crc32c.ts @@ -0,0 +1,339 @@ +// Copyright 2022 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 {PathLike, createReadStream} from 'fs'; + +/** + * Ported from {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc#L16-L59 github.com/google/crc32c} + */ +const CRC32C_EXTENSIONS = [ + 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c, + 0x26a1e7e8, 0xd4ca64eb, 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, + 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, 0x105ec76f, 0xe235446c, + 0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, + 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc, + 0xbc267848, 0x4e4dfb4b, 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, + 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, 0xaa64d611, 0x580f5512, + 0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, + 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad, + 0x1642ae59, 0xe4292d5a, 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, + 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, 0x417b1dbc, 0xb3109ebf, + 0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, + 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f, + 0xed03a29b, 0x1f682198, 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, + 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, 0xdbfc821c, 0x2997011f, + 0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, + 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e, + 0x4767748a, 0xb50cf789, 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, + 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, 0x7198540d, 0x83f3d70e, + 0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, + 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de, + 0xdde0eb2a, 0x2f8b6829, 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, + 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, 0x082f63b7, 0xfa44e0b4, + 0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, + 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b, + 0xb4091bff, 0x466298fc, 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, + 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, 0xa24bb5a6, 0x502036a5, + 0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, + 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975, + 0x0e330a81, 0xfc588982, 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, + 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, 0x38cc2a06, 0xcaa7a905, + 0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, + 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8, + 0xe52cc12c, 0x1747422f, 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, + 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, 0xd3d3e1ab, 0x21b862a8, + 0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, + 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78, + 0x7fab5e8c, 0x8dc0dd8f, 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, + 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, 0x69e9f0d5, 0x9b8273d6, + 0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, + 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69, + 0xd5cf889d, 0x27a40b9e, 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, + 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351, +] as const; + +const CRC32C_EXTENSION_TABLE = new Int32Array(CRC32C_EXTENSIONS); + +/** An interface for CRC32C hashing and validation */ +interface CRC32CValidator { + /** + * A method returning the CRC32C as a base64-encoded string. + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + toString: () => string; + /** + * A method validating a base64-encoded CRC32C string. + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + */ + validate: (value: string) => boolean; + /** + * A method for passing `Buffer`s for CRC32C generation. + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + */ + update: (data: Buffer) => void; +} + +/** A function that generates a CRC32C Validator */ +interface CRC32CValidatorGenerator { + /** Should return a new, ready-to-use `CRC32CValidator` */ + (): CRC32CValidator; +} + +const CRC32C_DEFAULT_VALIDATOR_GENERATOR: CRC32CValidatorGenerator = () => + new CRC32C(); + +const CRC32C_EXCEPTION_MESSAGES = { + INVALID_INIT_BASE64_RANGE: (l: number) => + `base64-encoded data expected to equal 4 bytes, not ${l}`, + INVALID_INIT_BUFFER_LENGTH: (l: number) => + `Buffer expected to equal 4 bytes, not ${l}`, + INVALID_INIT_INTEGER: (l: number) => + `Number expected to be a safe, unsigned 32-bit integer, not ${l}`, +} as const; + +class CRC32C implements CRC32CValidator { + /** Current CRC32C value */ + #crc32c = 0; + + /** + * Constructs a new `CRC32C` object. + * + * Reconstruction is recommended via the `CRC32C.from` static method. + * + * @param initialValue An initial CRC32C value - a signed 32-bit integer. + */ + constructor(initialValue = 0) { + this.#crc32c = initialValue; + } + + /** + * Calculates a CRC32C from a provided buffer. + * + * Implementation inspired from: + * - {@link https://github.com/google/crc32c/blob/21fc8ef30415a635e7351ffa0e5d5367943d4a94/src/crc32c_portable.cc github.com/google/crc32c} + * - {@link https://github.com/googleapis/python-crc32c/blob/a595e758c08df445a99c3bf132ee8e80a3ec4308/src/google_crc32c/python.py github.com/googleapis/python-crc32c} + * - {@link https://github.com/googleapis/java-storage/pull/1376/files github.com/googleapis/java-storage} + * + * @param data The `Buffer` to generate the CRC32C from + */ + update(data: Buffer) { + let current = this.#crc32c ^ 0xffffffff; + + for (const d of data) { + const tablePoly = CRC32C.CRC32C_EXTENSION_TABLE[(d ^ current) & 0xff]; + current = tablePoly ^ (current >>> 8); + } + + this.#crc32c = current ^ 0xffffffff; + } + + /** + * Validates a provided input to the current CRC32C value. + * + * @param input A Buffer, `CRC32C`-compatible object, base64-encoded data (string), or signed 32-bit integer + */ + validate(input: Buffer | CRC32CValidator | string | number): boolean { + if (typeof input === 'number') { + return input === this.#crc32c; + } else if (typeof input === 'string') { + return input === this.toString(); + } else if (Buffer.isBuffer(input)) { + return Buffer.compare(input, this.toBuffer()) === 0; + } else { + // `CRC32C`-like object + return input.toString() === this.toString(); + } + } + + /** + * Returns a `Buffer` representation of the CRC32C value + */ + toBuffer(): Buffer { + const buffer = Buffer.alloc(4); + buffer.writeInt32BE(this.#crc32c); + + return buffer; + } + + /** + * Returns a JSON-compatible, base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify `JSON#stringify`} + */ + toJSON(): string { + return this.toString(); + } + + /** + * Returns a base64-encoded representation of the CRC32C value. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString `Object#toString`} + */ + toString(): string { + return this.toBuffer().toString('base64'); + } + + /** + * Returns the `number` representation of the CRC32C value as a signed 32-bit integer + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf `Object#valueOf`} + */ + valueOf(): number { + return this.#crc32c; + } + + static readonly CRC32C_EXTENSIONS = CRC32C_EXTENSIONS; + static readonly CRC32C_EXTENSION_TABLE = CRC32C_EXTENSION_TABLE; + + /** + * Generates a `CRC32C` from a compatible buffer format. + * + * @param value 4-byte `ArrayBufferView`/`Buffer`/`TypedArray` + */ + private static fromBuffer( + value: ArrayBuffer | ArrayBufferView | Buffer, + ): CRC32C { + let buffer: Buffer; + + if (Buffer.isBuffer(value)) { + buffer = value; + } else if ('buffer' in value) { + // `ArrayBufferView` + buffer = Buffer.from(value.buffer); + } else { + // `ArrayBuffer` + buffer = Buffer.from(value); + } + + if (buffer.byteLength !== 4) { + throw new RangeError( + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(buffer.byteLength), + ); + } + + return new CRC32C(buffer.readInt32BE()); + } + + static async fromFile(file: PathLike) { + const crc32c = new CRC32C(); + + await new Promise((resolve, reject) => { + createReadStream(file) + .on('data', (d: string | Buffer) => { + if (typeof d === 'string') { + crc32c.update(Buffer.from(d)); + } else { + crc32c.update(d); + } + }) + .on('end', () => resolve()) + .on('error', reject); + }); + + return crc32c; + } + + /** + * Generates a `CRC32C` from 4-byte base64-encoded data (string). + * + * @param value 4-byte base64-encoded data (string) + */ + private static fromString(value: string): CRC32C { + const buffer = Buffer.from(value, 'base64'); + + if (buffer.byteLength !== 4) { + throw new RangeError( + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BASE64_RANGE(buffer.byteLength), + ); + } + + return this.fromBuffer(buffer); + } + + /** + * Generates a `CRC32C` from a safe, unsigned 32-bit integer. + * + * @param value an unsigned 32-bit integer + */ + private static fromNumber(value: number): CRC32C { + if (!Number.isSafeInteger(value) || value > 2 ** 32 || value < -(2 ** 32)) { + throw new RangeError( + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_INTEGER(value), + ); + } + + return new CRC32C(value); + } + + /** + * Generates a `CRC32C` from a variety of compatable types. + * Note: strings are treated as input, not as file paths to read from. + * + * @param value A number, 4-byte `ArrayBufferView`/`Buffer`/`TypedArray`, or 4-byte base64-encoded data (string) + */ + static from( + value: ArrayBuffer | ArrayBufferView | CRC32CValidator | string | number, + ): CRC32C { + if (typeof value === 'number') { + return this.fromNumber(value); + } else if (typeof value === 'string') { + return this.fromString(value); + } else if ('byteLength' in value) { + // `ArrayBuffer` | `Buffer` | `ArrayBufferView` + return this.fromBuffer(value); + } else { + // `CRC32CValidator`/`CRC32C`-like + return this.fromString(value.toString()); + } + } +} + +export { + CRC32C, + CRC32C_DEFAULT_VALIDATOR_GENERATOR, + CRC32C_EXCEPTION_MESSAGES, + CRC32C_EXTENSIONS, + CRC32C_EXTENSION_TABLE, + CRC32CValidator, + CRC32CValidatorGenerator, +}; diff --git a/handwritten/storage/src/file.ts b/handwritten/storage/src/file.ts new file mode 100644 index 00000000000..5c51e63dfb0 --- /dev/null +++ b/handwritten/storage/src/file.ts @@ -0,0 +1,4640 @@ +// Copyright 2019 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 { + BodyResponseCallback, + DecorateRequestOptions, + GetConfig, + Interceptor, + MetadataCallback, + ServiceObject, + SetMetadataResponse, + util, +} from './nodejs-common/index.js'; +import {promisifyAll} from '@google-cloud/promisify'; + +import * as crypto from 'crypto'; +import * as fs from 'fs'; +import mime from 'mime'; +import * as resumableUpload from './resumable-upload.js'; +import {Writable, Readable, pipeline, Transform, PipelineSource} from 'stream'; +import * as zlib from 'zlib'; +import * as http from 'http'; + +import { + ExceptionMessages, + IdempotencyStrategy, + PreconditionOptions, + Storage, +} from './storage.js'; +import {AvailableServiceObjectMethods, Bucket} from './bucket.js'; +import {Acl, AclMetadata} from './acl.js'; +import { + GetSignedUrlResponse, + SigningError, + GetSignedUrlCallback, + URLSigner, + SignerGetSignedUrlConfig, + Query, +} from './signer.js'; +import { + ResponseBody, + ApiError, + Duplexify, + GCCL_GCS_CMD_KEY, +} from './nodejs-common/util.js'; +import duplexify from 'duplexify'; +import { + normalize, + objectKeyToLowercase, + unicodeJSONStringify, + formatAsUTCISO, + PassThroughShim, +} from './util.js'; +import {CRC32C, CRC32CValidatorGenerator} from './crc32c.js'; +import {HashStreamValidator} from './hash-stream-validator.js'; +import {URL} from 'url'; + +import AsyncRetry from 'async-retry'; +import { + BaseMetadata, + DeleteCallback, + DeleteOptions, + GetResponse, + InstanceResponseCallback, + RequestResponse, + SetMetadataOptions, +} from './nodejs-common/service-object.js'; +import * as r from 'teeny-request'; + +export type GetExpirationDateResponse = [Date]; +export interface GetExpirationDateCallback { + ( + err: Error | null, + expirationDate?: Date | null, + apiResponse?: unknown, + ): void; +} + +export interface PolicyDocument { + string: string; + base64: string; + signature: string; +} + +export type SaveData = + | string + | Buffer + | Uint8Array + | PipelineSource; + +export type GenerateSignedPostPolicyV2Response = [PolicyDocument]; + +export interface GenerateSignedPostPolicyV2Callback { + (err: Error | null, policy?: PolicyDocument): void; +} + +export interface GenerateSignedPostPolicyV2Options { + equals?: string[] | string[][]; + expires: string | number | Date; + startsWith?: string[] | string[][]; + acl?: string; + successRedirect?: string; + successStatus?: string; + contentLengthRange?: {min?: number; max?: number}; + /** + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string; +} + +export interface PolicyFields { + [key: string]: string; +} + +export interface GenerateSignedPostPolicyV4Options { + expires: string | number | Date; + bucketBoundHostname?: string; + virtualHostedStyle?: boolean; + conditions?: object[]; + fields?: PolicyFields; + /** + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string; +} + +export interface GenerateSignedPostPolicyV4Callback { + (err: Error | null, output?: SignedPostPolicyV4Output): void; +} + +export type GenerateSignedPostPolicyV4Response = [SignedPostPolicyV4Output]; + +export interface SignedPostPolicyV4Output { + url: string; + fields: PolicyFields; +} + +export interface GetSignedUrlConfig + extends Pick { + action: 'read' | 'write' | 'delete' | 'resumable'; + version?: 'v2' | 'v4'; + virtualHostedStyle?: boolean; + cname?: string; + contentMd5?: string; + contentType?: string; + expires: string | number | Date; + accessibleAt?: string | number | Date; + extensionHeaders?: http.OutgoingHttpHeaders; + promptSaveAs?: string; + responseDisposition?: string; + responseType?: string; + queryParams?: Query; +} + +export interface GetFileMetadataOptions { + userProject?: string; +} + +export type GetFileMetadataResponse = [FileMetadata, unknown]; + +export interface GetFileMetadataCallback { + (err: Error | null, metadata?: FileMetadata, apiResponse?: unknown): void; +} + +export interface GetFileOptions extends GetConfig { + userProject?: string; + generation?: number; + restoreToken?: string; + softDeleted?: boolean; +} + +export type GetFileResponse = [File, unknown]; + +export interface GetFileCallback { + (err: Error | null, file?: File, apiResponse?: unknown): void; +} + +export interface FileExistsOptions { + userProject?: string; +} + +export type FileExistsResponse = [boolean]; + +export interface FileExistsCallback { + (err: Error | null, exists?: boolean): void; +} + +export interface DeleteFileOptions { + ignoreNotFound?: boolean; + userProject?: string; +} + +export type DeleteFileResponse = [unknown]; + +export interface DeleteFileCallback { + (err: Error | null, apiResponse?: unknown): void; +} + +export type PredefinedAcl = + | 'authenticatedRead' + | 'bucketOwnerFullControl' + | 'bucketOwnerRead' + | 'private' + | 'projectPrivate' + | 'publicRead'; + +type PublicResumableUploadOptions = + | 'chunkSize' + | 'highWaterMark' + | 'isPartialUpload' + | 'metadata' + | 'origin' + | 'offset' + | 'predefinedAcl' + | 'private' + | 'public' + | 'uri' + | 'userProject'; + +export interface CreateResumableUploadOptions + extends Pick { + /** + * A CRC32C to resume from when continuing a previous upload. It is recommended + * to capture the `crc32c` event from previous upload sessions to provide in + * subsequent requests in order to accurately track the upload. This is **required** + * when validating a final portion of the uploaded object. + * + * @see {@link CRC32C.from} for possible values. + */ + resumeCRC32C?: Parameters<(typeof CRC32C)['from']>[0]; + preconditionOpts?: PreconditionOptions; + [GCCL_GCS_CMD_KEY]?: resumableUpload.UploadConfig[typeof GCCL_GCS_CMD_KEY]; +} + +export type CreateResumableUploadResponse = [string]; + +export interface CreateResumableUploadCallback { + (err: Error | null, uri?: string): void; +} + +export interface CreateWriteStreamOptions extends CreateResumableUploadOptions { + contentType?: string; + gzip?: string | boolean; + resumable?: boolean; + timeout?: number; + validation?: string | boolean; +} + +export interface MakeFilePrivateOptions { + metadata?: FileMetadata; + strict?: boolean; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} + +export type MakeFilePrivateResponse = [unknown]; + +export type MakeFilePrivateCallback = SetFileMetadataCallback; + +export interface IsPublicCallback { + (err: Error | null, resp?: boolean): void; +} + +export type IsPublicResponse = [boolean]; + +export type MakeFilePublicResponse = [unknown]; + +export interface MakeFilePublicCallback { + (err?: Error | null, apiResponse?: unknown): void; +} + +interface MoveFileAtomicQuery { + userProject?: string; + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} + +export type MoveResponse = [unknown]; + +export interface MoveCallback { + ( + err: Error | null, + destinationFile?: File | null, + apiResponse?: unknown, + ): void; +} + +export interface MoveOptions { + userProject?: string; + preconditionOpts?: PreconditionOptions; +} + +export type MoveFileAtomicOptions = MoveOptions; +export type MoveFileAtomicCallback = MoveCallback; +export type MoveFileAtomicResponse = MoveResponse; + +export type RenameOptions = MoveOptions; +export type RenameResponse = MoveResponse; +export type RenameCallback = MoveCallback; + +export type RotateEncryptionKeyOptions = string | Buffer | EncryptionKeyOptions; + +export interface EncryptionKeyOptions { + encryptionKey?: string | Buffer; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; +} + +export type RotateEncryptionKeyCallback = CopyCallback; + +export type RotateEncryptionKeyResponse = CopyResponse; + +export enum ActionToHTTPMethod { + read = 'GET', + write = 'PUT', + delete = 'DELETE', + resumable = 'POST', +} + +/** + * @deprecated - no longer used + */ +export const STORAGE_POST_POLICY_BASE_URL = 'https://storage.googleapis.com'; + +/** + * @private + */ +const GS_URL_REGEXP = /^gs:\/\/([a-z0-9_.-]+)\/(.+)$/; + +/** + * @private + * This regex will match compressible content types. These are primarily text/*, +json, +text, +xml content types. + * This was based off of mime-db and may periodically need to be updated if new compressible content types become + * standards. + */ +const COMPRESSIBLE_MIME_REGEX = new RegExp( + [ + /^text\/|application\/ecmascript|application\/javascript|application\/json/, + /|application\/postscript|application\/rtf|application\/toml|application\/vnd.dart/, + /|application\/vnd.ms-fontobject|application\/wasm|application\/x-httpd-php|application\/x-ns-proxy-autoconfig/, + /|application\/x-sh(?!ockwave-flash)|application\/x-tar|application\/x-virtualbox-hdd|application\/x-virtualbox-ova|application\/x-virtualbox-ovf/, + /|^application\/x-virtualbox-vbox$|application\/x-virtualbox-vdi|application\/x-virtualbox-vhd|application\/x-virtualbox-vmdk/, + /|application\/xml|application\/xml-dtd|font\/otf|font\/ttf|image\/bmp|image\/vnd.adobe.photoshop|image\/vnd.microsoft.icon/, + /|image\/vnd.ms-dds|image\/x-icon|image\/x-ms-bmp|message\/rfc822|model\/gltf-binary|\+json|\+text|\+xml|\+yaml/, + ] + .map(r => r.source) + .join(''), + 'i', +); + +export interface FileOptions { + crc32cGenerator?: CRC32CValidatorGenerator; + encryptionKey?: string | Buffer; + generation?: number | string; + restoreToken?: string; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; + userProject?: string; +} + +export interface CopyOptions { + cacheControl?: string; + contentEncoding?: string; + contentType?: string; + contentDisposition?: string; + destinationKmsKeyName?: string; + metadata?: { + [key: string]: string | boolean | number | null; + }; + predefinedAcl?: string; + token?: string; + userProject?: string; + preconditionOpts?: PreconditionOptions; +} + +export type CopyResponse = [File, unknown]; + +export interface CopyCallback { + (err: Error | null, file?: File | null, apiResponse?: unknown): void; +} + +export type DownloadResponse = [Buffer]; + +export type DownloadCallback = ( + err: RequestError | null, + contents: Buffer, +) => void; + +export interface DownloadOptions extends CreateReadStreamOptions { + destination?: string; + encryptionKey?: string | Buffer; +} + +interface CopyQuery { + sourceGeneration?: number; + rewriteToken?: string; + userProject?: string; + destinationKmsKeyName?: string; + destinationPredefinedAcl?: string; + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} + +interface FileQuery { + alt: string; + generation?: number; + userProject?: string; +} + +export interface CreateReadStreamOptions { + userProject?: string; + validation?: 'md5' | 'crc32c' | false | true; + start?: number; + end?: number; + decompress?: boolean; + [GCCL_GCS_CMD_KEY]?: string; +} + +export interface SaveOptions extends CreateWriteStreamOptions { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onUploadProgress?: (progressEvent: any) => void; +} + +export interface SaveCallback { + (err?: Error | null): void; +} + +export interface SetFileMetadataOptions { + userProject?: string; +} + +export interface SetFileMetadataCallback { + (err?: Error | null, apiResponse?: unknown): void; +} + +export type SetFileMetadataResponse = [unknown]; + +export type SetStorageClassResponse = [unknown]; + +export interface SetStorageClassOptions { + userProject?: string; + preconditionOpts?: PreconditionOptions; +} + +export interface SetStorageClassCallback { + (err?: Error | null, apiResponse?: unknown): void; +} + +export interface RestoreOptions extends PreconditionOptions { + generation: number; + restoreToken?: string; + projection?: 'full' | 'noAcl'; +} + +export interface FileMetadata extends BaseMetadata { + acl?: AclMetadata[] | null; + bucket?: string; + cacheControl?: string; + componentCount?: number; + contentDisposition?: string; + contentEncoding?: string; + contentLanguage?: string; + contentType?: string; + crc32c?: string; + customerEncryption?: { + encryptionAlgorithm?: string; + keySha256?: string; + }; + customTime?: string; + eventBasedHold?: boolean | null; + readonly eventBasedHoldReleaseTime?: string; + generation?: string | number; + restoreToken?: string; + hardDeleteTime?: string; + kmsKeyName?: string; + md5Hash?: string; + mediaLink?: string; + metadata?: { + [key: string]: string | boolean | number | null; + }; + metageneration?: string | number; + name?: string; + owner?: { + entity?: string; + entityId?: string; + }; + retention?: { + retainUntilTime?: string; + mode?: string; + } | null; + retentionExpirationTime?: string; + size?: string | number; + softDeleteTime?: string; + storageClass?: string; + temporaryHold?: boolean | null; + timeCreated?: string; + timeDeleted?: string; + timeStorageClassUpdated?: string; + updated?: string; +} + +export class RequestError extends Error { + code?: string; + errors?: Error[]; +} + +const SEVEN_DAYS = 7 * 24 * 60 * 60; +const GS_UTIL_URL_REGEX = /(gs):\/\/([a-z0-9_.-]+)\/(.+)/g; +const HTTPS_PUBLIC_URL_REGEX = + /(https):\/\/(storage\.googleapis\.com)\/([a-z0-9_.-]+)\/(.+)/g; + +export enum FileExceptionMessages { + EXPIRATION_TIME_NA = 'An expiration time is not available.', + DESTINATION_NO_NAME = 'Destination file should have a name.', + INVALID_VALIDATION_FILE_RANGE = 'Cannot use validation with file ranges (start/end).', + MD5_NOT_AVAILABLE = 'MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects.', + EQUALS_CONDITION_TWO_ELEMENTS = 'Equals condition must be an array of 2 elements.', + STARTS_WITH_TWO_ELEMENTS = 'StartsWith condition must be an array of 2 elements.', + CONTENT_LENGTH_RANGE_MIN_MAX = 'ContentLengthRange must have numeric min & max fields.', + DOWNLOAD_MISMATCH = 'The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again.', + UPLOAD_MISMATCH_DELETE_FAIL = `The uploaded data did not match the data from the server. + As a precaution, we attempted to delete the file, but it was not successful. + To be sure the content is the same, you should try removing the file manually, + then uploading the file again. + \n\nThe delete attempt failed with this message:\n\n `, + UPLOAD_MISMATCH = `The uploaded data did not match the data from the server. + As a precaution, the file has been deleted. + To be sure the content is the same, you should try uploading the file again.`, + MD5_RESUMED_UPLOAD = 'MD5 cannot be used with a continued resumable upload as MD5 cannot be extended from an existing value', + MISSING_RESUME_CRC32C_FINAL_UPLOAD = 'The CRC32C is missing for the final portion of a resumed upload, which is required for validation. Please provide `resumeCRC32C` if validation is required, or disable `validation`.', +} + +/** + * A File object is created from your {@link Bucket} object using + * {@link Bucket#file}. + * + * @class + */ +class File extends ServiceObject { + acl: Acl; + crc32cGenerator: CRC32CValidatorGenerator; + bucket: Bucket; + storage: Storage; + kmsKeyName?: string; + userProject?: string; + signer?: URLSigner; + name: string; + + generation?: number; + restoreToken?: string; + parent!: Bucket; + + private encryptionKey?: string | Buffer; + private encryptionKeyBase64?: string; + private encryptionKeyHash?: string; + private encryptionKeyInterceptor?: Interceptor; + private instanceRetryValue?: boolean; + instancePreconditionOpts?: PreconditionOptions; + + /** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * An ACL consists of one or more entries, where each entry grants permissions + * to an entity. Permissions define the actions that can be performed against + * an object or bucket (for example, `READ` or `WRITE`); the entity defines + * who the permission applies to (for example, a specific user or group of + * users). + * + * The `acl` object on a File instance provides methods to get you a list of + * the ACLs defined on your bucket, as well as set, update, and delete them. + * + * See {@link http://goo.gl/6qBBPO| About Access Control lists} + * + * @name File#acl + * @mixes Acl + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * //- + * // Make a file publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * file.acl.add(options, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + /** + * The API-formatted resource description of the file. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name File#metadata + * @type {object} + */ + /** + * The file's name. + * @name File#name + * @type {string} + */ + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} FileOptions Options passed to the File constructor. + * @property {string} [encryptionKey] A custom encryption key. + * @property {number} [generation] Generation to scope the file to. + * @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this + * object, if the object is encrypted by such a key. Limited availability; + * usable only by enabled projects. + * @property {string} [userProject] The ID of the project which will be + * billed for all requests made from File object. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs a file object. + * + * @param {Bucket} bucket The Bucket instance this file is + * attached to. + * @param {string} name The name of the remote file. + * @param {FileOptions} [options] Configuration options. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * ``` + */ + constructor(bucket: Bucket, name: string, options: FileOptions = {}) { + const requestQueryObject: { + generation?: number; + userProject?: string; + ifGenerationMatch?: number; + ifGenerationNotMatch?: number; + ifMetagenerationMatch?: number; + ifMetagenerationNotMatch?: number; + } = {}; + + let generation: number; + if (options.generation !== null) { + if (typeof options.generation === 'string') { + generation = Number(options.generation); + } else { + generation = options.generation!; + } + if (!isNaN(generation)) { + requestQueryObject.generation = generation; + } + } + + Object.assign(requestQueryObject, options.preconditionOpts); + + const userProject = options.userProject || bucket.userProject; + if (typeof userProject === 'string') { + requestQueryObject.userProject = userProject; + } + + const methods = { + /** + * @typedef {array} DeleteFileResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteFileCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Delete the file. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation} + * + * @method File#delete + * @param {object} [options] Configuration options. + * @param {boolean} [options.ignoreNotFound = false] Ignore an error if + * the file does not exist. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteFileCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * file.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example + * region_tag:storage_delete_file + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} FileExistsResponse + * @property {boolean} 0 Whether the {@link File} exists. + */ + /** + * @callback FileExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the {@link File} exists. + */ + /** + * Check if the file exists. + * + * @method File#exists + * @param {options} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {FileExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetFileResponse + * @property {File} 0 The {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback GetFileCallback + * @param {?Error} err Request error, if any. + * @param {File} file The {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * Get a file object and its metadata if it exists. + * + * @method File#get + * @param {options} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {number} [options.generation] The generation number to get + * @param {string} [options.restoreToken] If this is a soft-deleted object in an HNS-enabled bucket, returns the restore token which will + * be necessary to restore it if there's a name conflict with another object. + * @param {boolean} [options.softDeleted] If true, returns the soft-deleted object. + Object `generation` is required if `softDeleted` is set to True. + * @param {GetFileCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.get(function(err, file, apiResponse) { + * // file.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.get().then(function(data) { + * const file = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {array} GetFileMetadataResponse + * @property {object} 0 The {@link File} metadata. + * @property {object} 1 The full API response. + */ + /** + * @callback GetFileMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} metadata The {@link File} metadata. + * @param {object} apiResponse The full API response. + */ + /** + * Get the file's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/get| Objects: get API Documentation} + * + * @method File#getMetadata + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetFileMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_get_metadata + * Another example: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + /** + * @typedef {object} SetFileMetadataOptions Configuration options for File#setMetadata(). + * @param {string} [userProject] The ID of the project which will be billed for the request. + */ + /** + * @callback SetFileMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} SetFileMetadataResponse + * @property {object} 0 The full API response. + */ + /** + * Merge the given metadata with the current remote file's metadata. This + * will set metadata if it was previously unset or update previously set + * metadata. To unset previously set metadata, set its value to null. + * + * You can set custom key/value pairs in the metadata key of the given + * object, however the other properties outside of this object must adhere + * to the {@link https://goo.gl/BOnnCK| official API documentation}. + * + * + * See the examples below for more information. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch| Objects: patch API Documentation} + * + * @method File#setMetadata + * @param {object} [metadata] The metadata you wish to update. + * @param {SetFileMetadataOptions} [options] Configuration options. + * @param {SetFileMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * const metadata = { + * contentType: 'application/x-font-ttf', + * metadata: { + * my: 'custom', + * properties: 'go here' + * } + * }; + * + * file.setMetadata(metadata, function(err, apiResponse) {}); + * + * // Assuming current metadata = { hello: 'world', unsetMe: 'will do' } + * file.setMetadata({ + * metadata: { + * abc: '123', // will be set. + * unsetMe: null, // will be unset (deleted). + * hello: 'goodbye' // will be updated from 'world' to 'goodbye'. + * } + * }, function(err, apiResponse) { + * // metadata should now be { abc: '123', hello: 'goodbye' } + * }); + * + * //- + * // Set a temporary hold on this file from its bucket's retention period + * // configuration. + * // + * file.setMetadata({ + * temporaryHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // Alternatively, you may set a temporary hold. This will follow the + * // same behavior as an event-based hold, with the exception that the + * // bucket's retention policy will not renew for this file from the time + * // the hold is released. + * //- + * file.setMetadata({ + * eventBasedHold: true + * }, function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.setMetadata(metadata).then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + setMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + }; + + super({ + parent: bucket, + baseUrl: '/o', + id: encodeURIComponent(name), + methods, + }); + + this.bucket = bucket; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.storage = (bucket as any).parent as Storage; + + // @TODO Can this duplicate code from above be avoided? + if (options.generation !== null) { + let generation: number; + if (typeof options.generation === 'string') { + generation = Number(options.generation); + } else { + generation = options.generation!; + } + if (!isNaN(generation)) { + this.generation = generation; + } + } + this.kmsKeyName = options.kmsKeyName; + this.userProject = userProject; + + this.name = name; + + if (options.encryptionKey) { + this.setEncryptionKey(options.encryptionKey); + } + + this.acl = new Acl({ + request: this.request.bind(this), + pathPrefix: '/acl', + }); + + this.crc32cGenerator = + options.crc32cGenerator || this.bucket.crc32cGenerator; + + this.instanceRetryValue = this.storage?.retryOptions?.autoRetry; + this.instancePreconditionOpts = options?.preconditionOpts; + } + + /** + * The object's Cloud Storage URI (`gs://`) + * + * @example + * ```ts + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('image.png'); + * + * // `gs://my-bucket/image.png` + * const href = file.cloudStorageURI.href; + * ``` + */ + get cloudStorageURI(): URL { + const uri = this.bucket.cloudStorageURI; + + uri.pathname = this.name; + + return uri; + } + + /** + * A helper method for determining if a request should be retried based on preconditions. + * This should only be used for methods where the idempotency is determined by + * `ifGenerationMatch` + * @private + * + * A request should not be retried under the following conditions: + * - if precondition option `ifGenerationMatch` is not set OR + * - if `idempotencyStrategy` is set to `RetryNever` + */ + private shouldRetryBasedOnPreconditionAndIdempotencyStrat( + options?: PreconditionOptions, + ): boolean { + return !( + (options?.ifGenerationMatch === undefined && + this.instancePreconditionOpts?.ifGenerationMatch === undefined && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever + ); + } + + copy( + destination: string | Bucket | File, + options?: CopyOptions, + ): Promise; + copy(destination: string | Bucket | File, callback: CopyCallback): void; + copy( + destination: string | Bucket | File, + options: CopyOptions, + callback: CopyCallback, + ): void; + /** + * @typedef {array} CopyResponse + * @property {File} 0 The copied {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback CopyCallback + * @param {?Error} err Request error, if any. + * @param {File} copiedFile The copied {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} CopyOptions Configuration options for File#copy(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @property {string} [cacheControl] The cacheControl setting for the new file. + * @property {string} [contentEncoding] The contentEncoding setting for the new file. + * @property {string} [contentType] The contentType setting for the new file. + * @property {string} [destinationKmsKeyName] Resource name of the Cloud + * KMS key, of the form + * `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overwrites the object + * metadata's `kms_key_name` value, if any. + * @property {Metadata} [metadata] Metadata to specify on the copied file. + * @property {string} [predefinedAcl] Set the ACL for the new file. + * @property {string} [token] A previously-returned `rewriteToken` from an + * unfinished rewrite request. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Copy this file to another file. By default, this will copy the file to the + * same bucket, but you can choose to copy it to another Bucket by providing + * a Bucket or File object or a URL starting with "gs://". + * The generation of the file will not be preserved. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/rewrite| Objects: rewrite API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|Bucket|File} destination Destination file. + * @param {CopyOptions} [options] Configuration options. See an + * @param {CopyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // You can pass in a variety of types for the destination. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is copied to its + * // current bucket, under the new name provided. + * //- + * file.copy('my-image-copy.png', function(err, copiedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "my-image.png" + * // - "my-image-copy.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a string starting with "gs://" for the destination, the + * // file is copied to the other bucket and under the new name provided. + * //- + * const newLocation = 'gs://another-bucket/my-image-copy.png'; + * file.copy(newLocation, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image-copy.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a Bucket object, the file will be copied to that bucket + * // using the same name. + * //- + * const anotherBucket = storage.bucket('another-bucket'); + * file.copy(anotherBucket, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image.png" + * + * // `copiedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // If you pass in a File object, you have complete control over the new + * // bucket and filename. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * file.copy(anotherFile, function(err, copiedFile, apiResponse) { + * // `my-bucket` still contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-awesome-image.png" + * + * // Note: + * // The `copiedFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.copy(newLocation).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_copy_file + * Another example: + */ + copy( + destination: string | Bucket | File, + optionsOrCallback?: CopyOptions | CopyCallback, + callback?: CopyCallback, + ): Promise | void { + const noDestinationError = new Error( + FileExceptionMessages.DESTINATION_NO_NAME, + ); + + if (!destination) { + throw noDestinationError; + } + + let options: CopyOptions = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = {...optionsOrCallback}; + } + + callback = callback || util.noop; + + let destBucket: Bucket; + let destName: string; + let newFile: File; + + if (typeof destination === 'string') { + const parsedDestination = GS_URL_REGEXP.exec(destination); + if (parsedDestination !== null && parsedDestination.length === 3) { + destBucket = this.storage.bucket(parsedDestination[1]); + destName = parsedDestination[2]; + } else { + destBucket = this.bucket; + destName = destination; + } + } else if (destination instanceof Bucket) { + destBucket = destination; + destName = this.name; + } else if (destination instanceof File) { + destBucket = destination.bucket; + destName = destination.name; + newFile = destination; + } else { + throw noDestinationError; + } + + const query = {} as CopyQuery; + if (this.generation !== undefined) { + query.sourceGeneration = this.generation; + } + if (options.token !== undefined) { + query.rewriteToken = options.token; + } + if (options.userProject !== undefined) { + query.userProject = options.userProject; + delete options.userProject; + } + if (options.predefinedAcl !== undefined) { + query.destinationPredefinedAcl = options.predefinedAcl; + delete options.predefinedAcl; + } + + newFile = newFile! || destBucket.file(destName); + + const headers: {[index: string]: string | undefined} = {}; + + if (this.encryptionKey !== undefined) { + headers['x-goog-copy-source-encryption-algorithm'] = 'AES256'; + headers['x-goog-copy-source-encryption-key'] = this.encryptionKeyBase64; + headers['x-goog-copy-source-encryption-key-sha256'] = + this.encryptionKeyHash; + } + + if (newFile.encryptionKey !== undefined) { + this.setEncryptionKey(newFile.encryptionKey!); + } else if (options.destinationKmsKeyName !== undefined) { + query.destinationKmsKeyName = options.destinationKmsKeyName; + delete options.destinationKmsKeyName; + } else if (newFile.kmsKeyName !== undefined) { + query.destinationKmsKeyName = newFile.kmsKeyName; + } + + if (query.destinationKmsKeyName) { + this.kmsKeyName = query.destinationKmsKeyName; + + const keyIndex = this.interceptors.indexOf( + this.encryptionKeyInterceptor!, + ); + if (keyIndex > -1) { + this.interceptors.splice(keyIndex, 1); + } + } + + if ( + !this.shouldRetryBasedOnPreconditionAndIdempotencyStrat( + options?.preconditionOpts, + ) + ) { + this.storage.retryOptions.autoRetry = false; + } + + if (options.preconditionOpts?.ifGenerationMatch !== undefined) { + query.ifGenerationMatch = options.preconditionOpts?.ifGenerationMatch; + delete options.preconditionOpts; + } + + this.request( + { + method: 'POST', + uri: `/rewriteTo/b/${destBucket.name}/o/${encodeURIComponent( + newFile.name, + )}`, + qs: query, + json: options, + headers, + }, + (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback!(err, null, resp); + return; + } + + if (resp.rewriteToken) { + const options = { + token: resp.rewriteToken, + } as CopyOptions; + + if (query.userProject) { + options.userProject = query.userProject; + } + + if (query.destinationKmsKeyName) { + options.destinationKmsKeyName = query.destinationKmsKeyName; + } + + this.copy(newFile, options, callback!); + return; + } + + callback!(null, newFile, resp); + }, + ); + } + + /** + * @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. + * @property {number} [start] A byte offset to begin the file's download + * from. Default is 0. NOTE: Byte ranges are inclusive; that is, + * `options.start = 0` and `options.end = 999` represent the first 1000 + * bytes in a file or object. NOTE: when specifying a byte range, data + * integrity is not available. + * @property {number} [end] A byte offset to stop reading the file at. + * NOTE: Byte ranges are inclusive; that is, `options.start = 0` and + * `options.end = 999` represent the first 1000 bytes in a file or object. + * NOTE: when specifying a byte range, data integrity is not available. + * @property {boolean} [decompress=true] Disable auto decompression of the + * received data. By default this option is set to `true`. + * Applicable in cases where the data was uploaded with + * `gzip: true` option. See {@link File#createWriteStream}. + */ + /** + * Create a readable stream to read the contents of the remote file. It can be + * piped to a writable stream or listened to for 'data' events to read a + * file's contents. + * + * In the unlikely event there is a mismatch between what you downloaded and + * the version in your Bucket, your error handler will receive an error with + * code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best + * recourse is to try downloading the file again. + * + * NOTE: Readable streams will emit the `end` event when the file is fully + * downloaded. + * + * @param {CreateReadStreamOptions} [options] Configuration options. + * @returns {ReadableStream} + * + * @example + * ``` + * //- + * //

Downloading a File

+ * // + * // The example below demonstrates how we can reference a remote file, then + * // pipe its contents to a local file. This is effectively creating a local + * // backup of your remote data. + * //- + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * const fs = require('fs'); + * const remoteFile = bucket.file('image.png'); + * const localFilename = '/Users/stephen/Photos/image.png'; + * + * remoteFile.createReadStream() + * .on('error', function(err) {}) + * .on('response', function(response) { + * // Server connected and responded with the specified status and headers. + * }) + * .on('end', function() { + * // The file is fully downloaded. + * }) + * .pipe(fs.createWriteStream(localFilename)); + * + * //- + * // To limit the downloaded data to only a byte range, pass an options + * // object. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * start: 10000, + * end: 20000 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * + * //- + * // To read a tail byte range, specify only `options.end` as a negative + * // number. + * //- + * const logFile = myBucket.file('access_log'); + * logFile.createReadStream({ + * end: -100 + * }) + * .on('error', function(err) {}) + * .pipe(fs.createWriteStream('/Users/stephen/logfile.txt')); + * ``` + */ + createReadStream(options: CreateReadStreamOptions = {}): Readable { + options = Object.assign({decompress: true}, options); + const rangeRequest = + typeof options.start === 'number' || typeof options.end === 'number'; + const tailRequest = options.end! < 0; + + let validateStream: HashStreamValidator | undefined = undefined; + let request: r.Request | undefined = undefined; + + const throughStream = new PassThroughShim(); + + let crc32c = true; + let md5 = false; + + if (typeof options.validation === 'string') { + const value = options.validation.toLowerCase().trim(); + + crc32c = value === 'crc32c'; + md5 = value === 'md5'; + } else if (options.validation === false) { + crc32c = false; + } + + const shouldRunValidation = !rangeRequest && (crc32c || md5); + + if (rangeRequest) { + if ( + typeof options.validation === 'string' || + options.validation === true + ) { + throw new Error(FileExceptionMessages.INVALID_VALIDATION_FILE_RANGE); + } + // Range requests can't receive data integrity checks. + crc32c = false; + md5 = false; + } + + const onComplete = (err: Error | null) => { + if (err) { + // There is an issue with node-fetch 2.x that if the stream errors the underlying socket connection is not closed. + // This causes a memory leak, so cleanup the sockets manually here by destroying the agent. + if (request?.agent) { + request.agent.destroy(); + } + throughStream.destroy(err); + } + }; + + // We listen to the response event from the request stream so that we + // can... + // + // 1) Intercept any data from going to the user if an error occurred. + // 2) Calculate the hashes from the http.IncomingMessage response + // stream, + // which will return the bytes from the source without decompressing + // gzip'd content. We then send it through decompressed, if + // applicable, to the user. + const onResponse = ( + err: Error | null, + _body: ResponseBody, + rawResponseStream: unknown, + ) => { + if (err) { + // Get error message from the body. + this.getBufferFromReadable(rawResponseStream as Readable).then(body => { + err.message = body.toString('utf8'); + throughStream.destroy(err); + }); + + return; + } + + request = (rawResponseStream as r.Response).request; + const headers = (rawResponseStream as ResponseBody).toJSON().headers; + const isCompressed = headers['content-encoding'] === 'gzip'; + const hashes: {crc32c?: string; md5?: string} = {}; + + // The object is safe to validate if: + // 1. It was stored gzip and returned to us gzip OR + // 2. It was never stored as gzip + const safeToValidate = + (headers['x-goog-stored-content-encoding'] === 'gzip' && + isCompressed) || + headers['x-goog-stored-content-encoding'] === 'identity'; + + const transformStreams: Transform[] = []; + + if (shouldRunValidation) { + // The x-goog-hash header should be set with a crc32c and md5 hash. + // ex: headers['x-goog-hash'] = 'crc32c=xxxx,md5=xxxx' + if (typeof headers['x-goog-hash'] === 'string') { + headers['x-goog-hash'] + .split(',') + .forEach((hashKeyValPair: string) => { + const delimiterIndex = hashKeyValPair.indexOf('='); + const hashType = hashKeyValPair.substring(0, delimiterIndex); + const hashValue = hashKeyValPair.substring(delimiterIndex + 1); + hashes[hashType as 'crc32c' | 'md5'] = hashValue; + }); + } + + validateStream = new HashStreamValidator({ + crc32c, + md5, + crc32cGenerator: this.crc32cGenerator, + crc32cExpected: hashes.crc32c, + md5Expected: hashes.md5, + }); + } + + if (md5 && !hashes.md5) { + const hashError = new RequestError( + FileExceptionMessages.MD5_NOT_AVAILABLE, + ); + hashError.code = 'MD5_NOT_AVAILABLE'; + throughStream.destroy(hashError); + return; + } + + if (safeToValidate && shouldRunValidation && validateStream) { + transformStreams.push(validateStream); + } + + if (isCompressed && options.decompress) { + transformStreams.push(zlib.createGunzip()); + } + + pipeline( + rawResponseStream as Readable, + ...(transformStreams as [Transform]), + throughStream, + onComplete, + ); + }; + + // Authenticate the request, then pipe the remote API request to the stream + // returned to the user. + const makeRequest = () => { + const query: FileQuery = {alt: 'media'}; + + if (this.generation) { + query.generation = this.generation; + } + + if (options.userProject) { + query.userProject = options.userProject; + } + + interface Headers { + [index: string]: string; + } + + const headers = { + 'Accept-Encoding': 'gzip', + 'Cache-Control': 'no-store', + } as Headers; + + if (rangeRequest) { + const start = typeof options.start === 'number' ? options.start : '0'; + const end = typeof options.end === 'number' ? options.end : ''; + + headers.Range = `bytes=${tailRequest ? end : `${start}-${end}`}`; + } + + const reqOpts: DecorateRequestOptions = { + uri: '', + headers, + qs: query, + }; + + if (options[GCCL_GCS_CMD_KEY]) { + reqOpts[GCCL_GCS_CMD_KEY] = options[GCCL_GCS_CMD_KEY]; + } + + this.requestStream(reqOpts) + .on('error', err => { + throughStream.destroy(err); + }) + .on('response', res => { + throughStream.emit('response', res); + util.handleResp(null, res, null, onResponse); + }) + .resume(); + }; + throughStream.on('reading', makeRequest); + + return throughStream; + } + + createResumableUpload( + options?: CreateResumableUploadOptions, + ): Promise; + createResumableUpload( + options: CreateResumableUploadOptions, + callback: CreateResumableUploadCallback, + ): void; + createResumableUpload(callback: CreateResumableUploadCallback): void; + /** + * @callback CreateResumableUploadCallback + * @param {?Error} err Request error, if any. + * @param {string} uri The resumable upload's unique session URI. + */ + /** + * @typedef {array} CreateResumableUploadResponse + * @property {string} 0 The resumable upload's unique session URI. + */ + /** + * @typedef {object} CreateResumableUploadOptions + * @property {object} [metadata] Metadata to set on the file. + * @property {number} [offset] The starting byte of the upload stream for resuming an interrupted upload. + * @property {string} [origin] Origin header to set for the upload. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string} [chunkSize] Create a separate request per chunk. This + * value is in bytes and should be a multiple of 256 KiB (2^18). + * {@link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload| We recommend using at least 8 MiB for the chunk size.} + */ + /** + * Create a unique resumable upload session URI. This is the first step when + * performing a resumable upload. + * + * See the {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload| Resumable upload guide} + * for more on how the entire process works. + * + *

Note

+ * + * If you are just looking to perform a resumable upload without worrying + * about any of the details, see {@link File#createWriteStream}. Resumable + * uploads are performed by default. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload| Resumable upload guide} + * + * @param {CreateResumableUploadOptions} [options] Configuration options. + * @param {CreateResumableUploadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * file.createResumableUpload(function(err, uri) { + * if (!err) { + * // `uri` can be used to PUT data to. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.createResumableUpload().then(function(data) { + * const uri = data[0]; + * }); + * ``` + */ + createResumableUpload( + optionsOrCallback?: + | CreateResumableUploadOptions + | CreateResumableUploadCallback, + callback?: CreateResumableUploadCallback, + ): void | Promise { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + const retryOptions = this.storage.retryOptions; + if ( + (options?.preconditionOpts?.ifGenerationMatch === undefined && + this.instancePreconditionOpts?.ifGenerationMatch === undefined && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever + ) { + retryOptions.autoRetry = false; + } + + resumableUpload.createURI( + { + authClient: this.storage.authClient, + apiEndpoint: this.storage.apiEndpoint, + bucket: this.bucket.name, + customRequestOptions: this.getRequestInterceptors().reduce( + (reqOpts, interceptorFn) => interceptorFn(reqOpts), + {}, + ), + file: this.name, + generation: this.generation, + key: this.encryptionKey, + kmsKeyName: this.kmsKeyName, + metadata: options.metadata, + offset: options.offset, + origin: options.origin, + predefinedAcl: options.predefinedAcl, + private: options.private, + public: options.public, + userProject: options.userProject || this.userProject, + retryOptions: retryOptions, + params: options?.preconditionOpts || this.instancePreconditionOpts, + universeDomain: this.bucket.storage.universeDomain, + useAuthWithCustomEndpoint: this.storage.useAuthWithCustomEndpoint, + [GCCL_GCS_CMD_KEY]: options[GCCL_GCS_CMD_KEY], + }, + callback!, + ); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + } + + /** + * @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream(). + * @property {string} [contentType] Alias for + * `options.metadata.contentType`. If set to `auto`, the file name is used + * to determine the contentType. + * @property {string|boolean} [gzip] If true, automatically gzip the file. + * If set to `auto`, the contentType is used to determine if the file + * should be gzipped. This will set `options.metadata.contentEncoding` to + * `gzip` if necessary. + * @property {object} [metadata] See the examples below or + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body} + * for more details. + * @property {number} [offset] The starting byte of the upload stream, for + * resuming an interrupted upload. Defaults to 0. + * @property {string} [predefinedAcl] Apply a predefined set of access + * controls to this object. + * + * Acceptable values are: + * - **`authenticatedRead`** - Object owner gets `OWNER` access, and + * `allAuthenticatedUsers` get `READER` access. + * + * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and + * project team owners get `OWNER` access. + * + * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project + * team owners get `READER` access. + * + * - **`private`** - Object owner gets `OWNER` access. + * + * - **`projectPrivate`** - Object owner gets `OWNER` access, and project + * team members get access according to their roles. + * + * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers` + * get `READER` access. + * @property {boolean} [private] Make the uploaded file private. (Alias for + * `options.predefinedAcl = 'private'`) + * @property {boolean} [public] Make the uploaded file public. (Alias for + * `options.predefinedAcl = 'publicRead'`) + * @property {boolean} [resumable] Force a resumable upload. NOTE: When + * working with streams, the file format and size is unknown until it's + * completely consumed. Because of this, it's best for you to be explicit + * for what makes sense given your input. + * @property {number} [timeout=60000] Set the HTTP request timeout in + * milliseconds. This option is not available for resumable uploads. + * Default: `60000` + * @property {string} [uri] The URI for an already-created resumable + * upload. See {@link File#createResumableUpload}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {string|boolean} [validation] Possible values: `"md5"`, + * `"crc32c"`, or `false`. By default, data integrity is validated with a + * CRC32c checksum. You may use MD5 if preferred, but that hash is not + * supported for composite objects. An error will be raised if MD5 is + * specified but is not available. You may also choose to skip validation + * completely, however this is **not recommended**. In addition to specifying + * validation type, providing `metadata.crc32c` or `metadata.md5Hash` will + * cause the server to perform validation in addition to client validation. + * NOTE: Validation is automatically skipped for objects that were + * uploaded using the `gzip` option and have already compressed content. + */ + /** + * Create a writable stream to overwrite the contents of the file in your + * bucket. + * + * A File object can also be used to create files for the first time. + * + * Resumable uploads are automatically enabled and must be shut off explicitly + * by setting `options.resumable` to `false`. + * + * + *

+ * There is some overhead when using a resumable upload that can cause + * noticeable performance degradation while uploading a series of small + * files. When uploading files less than 10MB, it is recommended that the + * resumable feature is disabled. + *

+ * + * NOTE: Writable streams will emit the `finish` event when the file is fully + * uploaded. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload Upload Options (Simple or Resumable)} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects: insert API Documentation} + * + * @param {CreateWriteStreamOptions} [options] Configuration options. + * @returns {WritableStream} + * + * @example + * ``` + * const fs = require('fs'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * //

Uploading a File

+ * // + * // Now, consider a case where we want to upload a file to your bucket. You + * // have the option of using {@link Bucket#upload}, but that is just + * // a convenience method which will do the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream()) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * //

Uploading a File with gzip compression

+ * //- + * fs.createReadStream('/Users/stephen/site/index.html') + * .pipe(file.createWriteStream({ gzip: true })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * + * //- + * // Downloading the file with `createReadStream` will automatically decode + * // the file. + * //- + * + * //- + * //

Uploading a File with Metadata

+ * // + * // One last case you may run into is when you want to upload a file to your + * // bucket and set its metadata at the same time. Like above, you can use + * // {@link Bucket#upload} to do this, which is just a wrapper around + * // the following. + * //- + * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg') + * .pipe(file.createWriteStream({ + * metadata: { + * contentType: 'image/jpeg', + * metadata: { + * custom: 'metadata' + * } + * } + * })) + * .on('error', function(err) {}) + * .on('finish', function() { + * // The file upload is complete. + * }); + * ``` + * + * //- + * //

Continuing a Resumable Upload

+ * // + * // One can capture a `uri` from a resumable upload to reuse later. + * // Additionally, for validation, one can also capture and pass `crc32c`. + * //- + * let uri: string | undefined = undefined; + * let resumeCRC32C: string | undefined = undefined; + * + * fs.createWriteStream() + * .on('uri', link => {uri = link}) + * .on('crc32', crc32c => {resumeCRC32C = crc32c}); + * + * // later... + * fs.createWriteStream({uri, resumeCRC32C}); + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createWriteStream(options: CreateWriteStreamOptions = {}): Writable { + options.metadata ??= {}; + + if (options.contentType) { + options!.metadata!.contentType = options.contentType; + } + + if ( + !options!.metadata!.contentType || + options!.metadata!.contentType === 'auto' + ) { + const detectedContentType = mime.getType(this.name); + if (detectedContentType) { + options!.metadata!.contentType = detectedContentType; + } + } + + let gzip = options.gzip; + + if (gzip === 'auto') { + gzip = COMPRESSIBLE_MIME_REGEX.test(options!.metadata!.contentType || ''); + } + + if (gzip) { + options!.metadata!.contentEncoding = 'gzip'; + } + + let crc32c = true; + let md5 = false; + + if (typeof options.validation === 'string') { + options.validation = options.validation.toLowerCase(); + crc32c = options.validation === 'crc32c'; + md5 = options.validation === 'md5'; + } else if (options.validation === false) { + crc32c = false; + md5 = false; + } + + if (options.offset) { + if (md5) { + throw new RangeError(FileExceptionMessages.MD5_RESUMED_UPLOAD); + } + + if (crc32c && !options.isPartialUpload && !options.resumeCRC32C) { + throw new RangeError( + FileExceptionMessages.MISSING_RESUME_CRC32C_FINAL_UPLOAD, + ); + } + } + + /** + * A callback for determining when the underlying pipeline is complete. + * It's possible the pipeline callback could error before the write stream + * calls `final` so by default this will destroy the write stream unless the + * write stream sets this callback via its `final` handler. + * @param error An optional error + */ + let pipelineCallback: (error?: Error | null) => void = error => { + writeStream.destroy(error || undefined); + }; + + // A stream for consumer to write to + const writeStream = new Writable({ + final(cb) { + // Set the pipeline callback to this callback so the pipeline's results + // can be populated to the consumer + pipelineCallback = cb; + + emitStream.end(); + }, + write(chunk, encoding, cb) { + emitStream.write(chunk, encoding, cb); + }, + }); + // If the write stream, which is returned to the caller, catches an error we need to make sure that + // at least one of the streams in the pipeline below gets notified so that they + // all get cleaned up / destroyed. + writeStream.once('error', e => { + emitStream.destroy(e); + }); + // If the write stream is closed, cleanup the pipeline below by calling destroy on one of the streams. + writeStream.once('close', () => { + emitStream.destroy(); + }); + + const transformStreams: Transform[] = []; + + if (gzip) { + transformStreams.push(zlib.createGzip()); + } + + const emitStream = new PassThroughShim(); + + // If `writeStream` is destroyed before the `writing` event, `emitStream` will not have any listeners. This prevents an unhandled error. + const noop = () => {}; + emitStream.on('error', noop); + + let hashCalculatingStream: HashStreamValidator | null = null; + + if (crc32c || md5) { + const crc32cInstance = options.resumeCRC32C + ? CRC32C.from(options.resumeCRC32C) + : undefined; + + hashCalculatingStream = new HashStreamValidator({ + crc32c, + crc32cInstance, + md5, + crc32cGenerator: this.crc32cGenerator, + updateHashesOnly: true, + }); + + transformStreams.push(hashCalculatingStream); + } + + const fileWriteStream = duplexify(); + let fileWriteStreamMetadataReceived = false; + + // Handing off emitted events to users + emitStream.on('reading', () => writeStream.emit('reading')); + emitStream.on('writing', () => writeStream.emit('writing')); + fileWriteStream.on('uri', evt => writeStream.emit('uri', evt)); + fileWriteStream.on('progress', evt => writeStream.emit('progress', evt)); + fileWriteStream.on('response', resp => writeStream.emit('response', resp)); + fileWriteStream.once('metadata', () => { + fileWriteStreamMetadataReceived = true; + }); + + writeStream.once('writing', () => { + if (options.resumable === false) { + this.startSimpleUpload_(fileWriteStream, options); + } else { + this.startResumableUpload_(fileWriteStream, options); + } + + // remove temporary noop listener as we now create a pipeline that handles the errors + emitStream.removeListener('error', noop); + + pipeline( + emitStream, + ...(transformStreams as [Transform]), + fileWriteStream, + async e => { + if (e) { + return pipelineCallback(e); + } + + // If this is a partial upload, we don't expect final metadata yet. + if (options.isPartialUpload) { + // Emit CRC32c for this completed chunk if hash validation is active. + if (hashCalculatingStream?.crc32c) { + writeStream.emit('crc32c', hashCalculatingStream.crc32c); + } + // Resolve the pipeline for this *partial chunk*. + return pipelineCallback(); + } + + // We want to make sure we've received the metadata from the server in order + // to properly validate the object's integrity. Depending on the type of upload, + // the stream could close before the response is returned. + if (!fileWriteStreamMetadataReceived) { + try { + await new Promise((resolve, reject) => { + fileWriteStream.once('metadata', resolve); + fileWriteStream.once('error', reject); + }); + } catch (e) { + return pipelineCallback(e as Error); + } + } + + // Emit the local CRC32C value for future validation, if validation is enabled. + if (hashCalculatingStream?.crc32c) { + writeStream.emit('crc32c', hashCalculatingStream.crc32c); + } + + try { + // Metadata may not be ready if the upload is a partial upload, + // nothing to validate yet. + const metadataNotReady = options.isPartialUpload && !this.metadata; + + if (hashCalculatingStream && !metadataNotReady) { + await this.#validateIntegrity(hashCalculatingStream, { + crc32c, + md5, + }); + } + + pipelineCallback(); + } catch (e) { + pipelineCallback(e as Error); + } + }, + ); + }); + + return writeStream; + } + + /** + * Delete the object. + * + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + delete(options?: DeleteOptions): Promise<[r.Response]>; + delete(options: DeleteOptions, callback: DeleteCallback): void; + delete(callback: DeleteCallback): void; + delete( + optionsOrCallback?: DeleteOptions | DeleteCallback, + cb?: DeleteCallback, + ): Promise<[r.Response]> | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb; + + this.disableAutoRetryConditionallyIdempotent_( + this.methods.delete, + AvailableServiceObjectMethods.delete, + options, + ); + + super + .delete(options) + .then(resp => cb!(null, ...resp)) + .catch(cb!) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + + download(options?: DownloadOptions): Promise; + download(options: DownloadOptions, callback: DownloadCallback): void; + download(callback: DownloadCallback): void; + /** + * @typedef {array} DownloadResponse + * @property [0] The contents of a File. + */ + /** + * @callback DownloadCallback + * @param err Request error, if any. + * @param contents The contents of a File. + */ + /** + * Convenience method to download a file into memory or to a local + * destination. + * + * @param {object} [options] Configuration options. The arguments match those + * passed to {@link File#createReadStream}. + * @param {string} [options.destination] Local file path to write the file's + * contents to. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DownloadCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Download a file into memory. The contents will be available as the + * second + * // argument in the demonstration below, `contents`. + * //- + * file.download(function(err, contents) {}); + * + * //- + * // Download a file to a local destination. + * //- + * file.download({ + * destination: '/Users/me/Desktop/file-backup.txt' + * }, function(err) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.download().then(function(data) { + * const contents = data[0]; + * }); + * + * ``` + * @example
+ * region_tag:storage_download_file + * Another example: + * + * @example + * region_tag:storage_download_encrypted_file + * Example of downloading an encrypted file: + * + * @example + * region_tag:storage_download_file_requester_pays + * Example of downloading a file where the requester pays: + */ + download( + optionsOrCallback?: DownloadOptions | DownloadCallback, + cb?: DownloadCallback, + ): Promise | void { + let options: DownloadOptions; + if (typeof optionsOrCallback === 'function') { + cb = optionsOrCallback as DownloadCallback; + options = {}; + } else { + options = Object.assign({}, optionsOrCallback); + } + + let called = false; + const callback = ((...args) => { + if (!called) cb!(...args); + called = true; + }) as DownloadCallback; + + const destination = options.destination; + delete options.destination; + + if (options.encryptionKey) { + this.setEncryptionKey(options.encryptionKey); + delete options.encryptionKey; + } + + const fileStream = this.createReadStream(options); + let receivedData = false; + + if (destination) { + fileStream + .on('error', callback) + .once('data', data => { + receivedData = true; + // We know that the file exists the server - now we can truncate/write to a file + const writable = fs.createWriteStream(destination); + writable.write(data); + fileStream + .pipe(writable) + .on('error', (err: Error) => { + callback(err, Buffer.from('')); + }) + .on('finish', () => { + callback(null, data); + }); + }) + .on('end', () => { + // In the case of an empty file no data will be received before the end event fires + if (!receivedData) { + const data = Buffer.alloc(0); + + try { + fs.writeFileSync(destination, data); + callback(null, data); + } catch (e) { + callback(e as Error, data); + } + } + }); + } else { + this.getBufferFromReadable(fileStream) + .then(contents => callback?.(null, contents)) + .catch(callback as (err: RequestError) => void); + } + } + + /** + * The Storage API allows you to use a custom key for server-side encryption. + * + * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys} + * + * @param {string|buffer} encryptionKey An AES-256 encryption key. + * @returns {File} + * + * @example + * ``` + * const crypto = require('crypto'); + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const encryptionKey = crypto.randomBytes(32); + * + * const fileWithCustomEncryption = myBucket.file('my-file'); + * fileWithCustomEncryption.setEncryptionKey(encryptionKey); + * + * const fileWithoutCustomEncryption = myBucket.file('my-file'); + * + * fileWithCustomEncryption.save('data', function(err) { + * // Try to download with the File object that hasn't had + * // `setEncryptionKey()` called: + * fileWithoutCustomEncryption.download(function(err) { + * // We will receive an error: + * // err.message === 'Bad Request' + * + * // Try again with the File object we called `setEncryptionKey()` on: + * fileWithCustomEncryption.download(function(err, contents) { + * // contents.toString() === 'data' + * }); + * }); + * }); + * + * ``` + * @example + * region_tag:storage_upload_encrypted_file + * Example of uploading an encrypted file: + * + * @example + * region_tag:storage_download_encrypted_file + * Example of downloading an encrypted file: + */ + setEncryptionKey(encryptionKey: string | Buffer) { + this.encryptionKey = encryptionKey; + this.encryptionKeyBase64 = Buffer.from(encryptionKey as string).toString( + 'base64', + ); + this.encryptionKeyHash = crypto + .createHash('sha256') + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .update(this.encryptionKeyBase64, 'base64' as any) + .digest('base64'); + + this.encryptionKeyInterceptor = { + request: reqOpts => { + reqOpts.headers = reqOpts.headers || {}; + reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256'; + reqOpts.headers['x-goog-encryption-key'] = this.encryptionKeyBase64; + reqOpts.headers['x-goog-encryption-key-sha256'] = + this.encryptionKeyHash; + return reqOpts as DecorateRequestOptions; + }, + }; + + this.interceptors.push(this.encryptionKeyInterceptor!); + + return this; + } + + /** + * Gets a reference to a Cloud Storage {@link File} file from the provided URL in string format. + * @param {string} publicUrlOrGsUrl the URL as a string. Must be of the format gs://bucket/file + * or https://storage.googleapis.com/bucket/file. + * @param {Storage} storageInstance an instance of a Storage object. + * @param {FileOptions} [options] Configuration options + * @returns {File} + */ + static from( + publicUrlOrGsUrl: string, + storageInstance: Storage, + options?: FileOptions, + ): File { + const gsMatches = [...publicUrlOrGsUrl.matchAll(GS_UTIL_URL_REGEX)]; + const httpsMatches = [...publicUrlOrGsUrl.matchAll(HTTPS_PUBLIC_URL_REGEX)]; + + if (gsMatches.length > 0) { + const bucket = new Bucket(storageInstance, gsMatches[0][2]); + return new File(bucket, gsMatches[0][3], options); + } else if (httpsMatches.length > 0) { + const bucket = new Bucket(storageInstance, httpsMatches[0][3]); + return new File(bucket, httpsMatches[0][4], options); + } else { + throw new Error( + 'URL string must be of format gs://bucket/file or https://storage.googleapis.com/bucket/file', + ); + } + } + + get(options?: GetFileOptions): Promise>; + get(callback: InstanceResponseCallback): void; + get(options: GetFileOptions, callback: InstanceResponseCallback): void; + get( + optionsOrCallback?: GetFileOptions | InstanceResponseCallback, + cb?: InstanceResponseCallback, + ): Promise> | void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options: any = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as InstanceResponseCallback) + : cb; + + super + .get(options) + .then(resp => cb!(null, ...resp)) + .catch(cb!); + } + + getExpirationDate(): Promise; + getExpirationDate(callback: GetExpirationDateCallback): void; + /** + * @typedef {array} GetExpirationDateResponse + * @property {date} 0 A Date object representing the earliest time this file's + * retention policy will expire. + */ + /** + * @callback GetExpirationDateCallback + * @param {?Error} err Request error, if any. + * @param {date} expirationDate A Date object representing the earliest time + * this file's retention policy will expire. + */ + /** + * If this bucket has a retention policy defined, use this method to get a + * Date object representing the earliest time this file will expire. + * + * @param {GetExpirationDateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const storage = require('@google-cloud/storage')(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.getExpirationDate(function(err, expirationDate) { + * // expirationDate is a Date object. + * }); + * ``` + */ + getExpirationDate( + callback?: GetExpirationDateCallback, + ): void | Promise { + this.getMetadata( + (err: ApiError | null, metadata: FileMetadata, apiResponse: unknown) => { + if (err) { + callback!(err, null, apiResponse); + return; + } + + if (!metadata.retentionExpirationTime) { + const error = new Error(FileExceptionMessages.EXPIRATION_TIME_NA); + callback!(error, null, apiResponse); + return; + } + + callback!( + null, + new Date(metadata.retentionExpirationTime), + apiResponse, + ); + }, + ); + } + + generateSignedPostPolicyV2( + options: GenerateSignedPostPolicyV2Options, + ): Promise; + generateSignedPostPolicyV2( + options: GenerateSignedPostPolicyV2Options, + callback: GenerateSignedPostPolicyV2Callback, + ): void; + generateSignedPostPolicyV2( + callback: GenerateSignedPostPolicyV2Callback, + ): void; + /** + * @typedef {array} GenerateSignedPostPolicyV2Response + * @property {object} 0 The document policy. + */ + /** + * @callback GenerateSignedPostPolicyV2Callback + * @param {?Error} err Request error, if any. + * @param {object} policy The document policy. + */ + /** + * Get a signed policy document to allow a user to upload data with a POST + * request. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed policy. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object-v2| POST Object with the V2 signing process} + * + * @throws {Error} If an expiration timestamp from the past is given. + * @throws {Error} If options.equals has an array with less or more than two + * members. + * @throws {Error} If options.startsWith has an array with less or more than two + * members. + * + * @param {object} options Configuration options. + * @param {array|array[]} [options.equals] Array of request parameters and + * their expected value (e.g. [['$', '']]). Values are + * translated into equality constraints in the conditions field of the + * policy document (e.g. ['eq', '$', '']). If only one + * equality condition is to be specified, options.equals can be a one- + * dimensional array (e.g. ['$', '']). + * @param {*} options.expires - A timestamp when this policy will expire. Any + * value given is passed to `new Date()`. + * @param {array|array[]} [options.startsWith] Array of request parameters and + * their expected prefixes (e.g. [['$', '']). Values are + * translated into starts-with constraints in the conditions field of the + * policy document (e.g. ['starts-with', '$', '']). If only + * one prefix condition is to be specified, options.startsWith can be a + * one- dimensional array (e.g. ['$', '']). + * @param {string} [options.acl] ACL for the object from possibly predefined + * ACLs. + * @param {string} [options.successRedirect] The URL to which the user client + * is redirected if the upload is successful. + * @param {string} [options.successStatus] - The status of the Google Storage + * response if the upload is successful (must be string). + * @param {object} [options.contentLengthRange] + * @param {number} [options.contentLengthRange.min] Minimum value for the + * request's content length. + * @param {number} [options.contentLengthRange.max] Maximum value for the + * request's content length. + * @param {GenerateSignedPostPolicyV2Callback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const options = { + * equals: ['$Content-Type', 'image/jpeg'], + * expires: '10-25-2022', + * contentLengthRange: { + * min: 0, + * max: 1024 + * } + * }; + * + * file.generateSignedPostPolicyV2(options, function(err, policy) { + * // policy.string: the policy document in plain text. + * // policy.base64: the policy document in base64. + * // policy.signature: the policy signature in base64. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.generateSignedPostPolicyV2(options).then(function(data) { + * const policy = data[0]; + * }); + * ``` + */ + generateSignedPostPolicyV2( + optionsOrCallback?: + | GenerateSignedPostPolicyV2Options + | GenerateSignedPostPolicyV2Callback, + cb?: GenerateSignedPostPolicyV2Callback, + ): void | Promise { + const args = normalize( + optionsOrCallback, + cb, + ); + let options = args.options; + const callback = args.callback; + const expires = new Date( + (options as GenerateSignedPostPolicyV2Options).expires, + ); + + if (isNaN(expires.getTime())) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_INVALID); + } + + if (expires.valueOf() < Date.now()) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_PAST); + } + + options = Object.assign({}, options); + + const conditions = [ + ['eq', '$key', this.name], + { + bucket: this.bucket.name, + }, + ] as object[]; + + if (Array.isArray(options.equals)) { + if (!Array.isArray((options.equals as string[][])[0])) { + options.equals = [options.equals as string[]]; + } + (options.equals as string[][]).forEach(condition => { + if (!Array.isArray(condition) || condition.length !== 2) { + throw new Error(FileExceptionMessages.EQUALS_CONDITION_TWO_ELEMENTS); + } + conditions.push(['eq', condition[0], condition[1]]); + }); + } + + if (Array.isArray(options.startsWith)) { + if (!Array.isArray((options.startsWith as string[][])[0])) { + options.startsWith = [options.startsWith as string[]]; + } + (options.startsWith as string[][]).forEach(condition => { + if (!Array.isArray(condition) || condition.length !== 2) { + throw new Error(FileExceptionMessages.STARTS_WITH_TWO_ELEMENTS); + } + conditions.push(['starts-with', condition[0], condition[1]]); + }); + } + + if (options.acl) { + conditions.push({ + acl: options.acl, + }); + } + + if (options.successRedirect) { + conditions.push({ + success_action_redirect: options.successRedirect, + }); + } + + if (options.successStatus) { + conditions.push({ + success_action_status: options.successStatus, + }); + } + + if (options.contentLengthRange) { + const min = options.contentLengthRange.min; + const max = options.contentLengthRange.max; + if (typeof min !== 'number' || typeof max !== 'number') { + throw new Error(FileExceptionMessages.CONTENT_LENGTH_RANGE_MIN_MAX); + } + conditions.push(['content-length-range', min, max]); + } + + const policy = { + expiration: expires.toISOString(), + conditions, + }; + + const policyString = JSON.stringify(policy); + const policyBase64 = Buffer.from(policyString).toString('base64'); + + this.storage.authClient.sign(policyBase64, options.signingEndpoint).then( + signature => { + callback(null, { + string: policyString, + base64: policyBase64, + signature, + }); + }, + err => { + callback(new SigningError(err.message)); + }, + ); + } + + generateSignedPostPolicyV4( + options: GenerateSignedPostPolicyV4Options, + ): Promise; + generateSignedPostPolicyV4( + options: GenerateSignedPostPolicyV4Options, + callback: GenerateSignedPostPolicyV4Callback, + ): void; + generateSignedPostPolicyV4( + callback: GenerateSignedPostPolicyV4Callback, + ): void; + /** + * @typedef {object} SignedPostPolicyV4Output + * @property {string} url The request URL. + * @property {object} fields The form fields to include in the POST request. + */ + /** + * @typedef {array} GenerateSignedPostPolicyV4Response + * @property {SignedPostPolicyV4Output} 0 An object containing the request URL and form fields. + */ + /** + * @callback GenerateSignedPostPolicyV4Callback + * @param {?Error} err Request error, if any. + * @param {SignedPostPolicyV4Output} output An object containing the request URL and form fields. + */ + /** + * Get a v4 signed policy document to allow a user to upload data with a POST + * request. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed policy. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object#policydocument| Policy Document Reference} + * + * @param {object} options Configuration options. + * @param {Date|number|string} options.expires - A timestamp when this policy will expire. Any + * value given is passed to `new Date()`. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style + * ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.bucketBoundHostname] The bucket-bound hostname to return in + * the result, e.g. "https://cdn.example.com". + * @param {object} [config.fields] [Form fields]{@link https://cloud.google.com/storage/docs/xml-api/post-object#policydocument} + * to include in the signed policy. Any fields with key beginning with 'x-ignore-' + * will not be included in the policy to be signed. + * @param {object[]} [config.conditions] [Conditions]{@link https://cloud.google.com/storage/docs/authentication/signatures#policy-document} + * to include in the signed policy. All fields given in `config.fields` are + * automatically included in the conditions array, adding the same entry + * in both `fields` and `conditions` will result in duplicate entries. + * + * @param {GenerateSignedPostPolicyV4Callback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const options = { + * expires: '10-25-2022', + * conditions: [ + * ['eq', '$Content-Type', 'image/jpeg'], + * ['content-length-range', 0, 1024], + * ], + * fields: { + * acl: 'public-read', + * 'x-goog-meta-foo': 'bar', + * 'x-ignore-mykey': 'data' + * } + * }; + * + * file.generateSignedPostPolicyV4(options, function(err, response) { + * // response.url The request URL + * // response.fields The form fields (including the signature) to include + * // to be used to upload objects by HTML forms. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.generateSignedPostPolicyV4(options).then(function(data) { + * const response = data[0]; + * // response.url The request URL + * // response.fields The form fields (including the signature) to include + * // to be used to upload objects by HTML forms. + * }); + * ``` + */ + generateSignedPostPolicyV4( + optionsOrCallback?: + | GenerateSignedPostPolicyV4Options + | GenerateSignedPostPolicyV4Callback, + cb?: GenerateSignedPostPolicyV4Callback, + ): void | Promise { + const args = normalize< + GenerateSignedPostPolicyV4Options, + GenerateSignedPostPolicyV4Callback + >(optionsOrCallback, cb); + let options = args.options; + const callback = args.callback; + const expires = new Date( + (options as GenerateSignedPostPolicyV4Options).expires, + ); + + if (isNaN(expires.getTime())) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_INVALID); + } + + if (expires.valueOf() < Date.now()) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_PAST); + } + + if (expires.valueOf() - Date.now() > SEVEN_DAYS * 1000) { + throw new Error( + `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`, + ); + } + + options = Object.assign({}, options); + let fields = Object.assign({}, options.fields); + + const now = new Date(); + const nowISO = formatAsUTCISO(now, true); + const todayISO = formatAsUTCISO(now); + + const sign = async () => { + const {client_email} = await this.storage.authClient.getCredentials(); + const credential = `${client_email}/${todayISO}/auto/storage/goog4_request`; + + fields = { + ...fields, + bucket: this.bucket.name, + key: this.name, + 'x-goog-date': nowISO, + 'x-goog-credential': credential, + 'x-goog-algorithm': 'GOOG4-RSA-SHA256', + }; + + const conditions = options.conditions || []; + + Object.entries(fields).forEach(([key, value]) => { + if (!key.startsWith('x-ignore-')) { + conditions.push({[key]: value}); + } + }); + + delete fields.bucket; + + const expiration = formatAsUTCISO(expires, true, '-', ':'); + + const policy = { + conditions, + expiration, + }; + + const policyString = unicodeJSONStringify(policy); + const policyBase64 = Buffer.from(policyString).toString('base64'); + + try { + const signature = await this.storage.authClient.sign( + policyBase64, + options.signingEndpoint, + ); + const signatureHex = Buffer.from(signature, 'base64').toString('hex'); + const universe = this.parent.storage.universeDomain; + fields['policy'] = policyBase64; + fields['x-goog-signature'] = signatureHex; + + let url: string; + + const EMULATOR_HOST = process.env.STORAGE_EMULATOR_HOST; + + if (this.storage.customEndpoint && typeof EMULATOR_HOST === 'string') { + url = `${this.storage.apiEndpoint}/${this.bucket.name}`; + } else if (this.storage.customEndpoint) { + url = this.storage.apiEndpoint; + } else if (options.virtualHostedStyle) { + url = `https://${this.bucket.name}.storage.${universe}/`; + } else if (options.bucketBoundHostname) { + url = `${options.bucketBoundHostname}/`; + } else { + url = `https://storage.${universe}/${this.bucket.name}/`; + } + + return { + url, + fields, + }; + } catch (err) { + throw new SigningError((err as Error).message); + } + }; + + sign().then(res => callback!(null, res), callback!); + } + + getSignedUrl(cfg: GetSignedUrlConfig): Promise; + getSignedUrl(cfg: GetSignedUrlConfig, callback: GetSignedUrlCallback): void; + /** + * @typedef {array} GetSignedUrlResponse + * @property {object} 0 The signed URL. + */ + /** + * @callback GetSignedUrlCallback + * @param {?Error} err Request error, if any. + * @param {object} url The signed URL. + */ + /** + * Get a signed URL to allow limited time access to the file. + * + * In Google Cloud Platform environments, such as Cloud Functions and App + * Engine, you usually don't provide a `keyFilename` or `credentials` during + * instantiation. In those environments, we call the + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API} + * to create a signed URL. That API requires either the + * `https://www.googleapis.com/auth/iam` or + * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are + * enabled. + * + * See {@link https://cloud.google.com/storage/docs/access-control/signed-urls| Signed URLs Reference} + * + * @throws {Error} if an expiration timestamp from the past is given. + * + * @param {object} config Configuration object. + * @param {string} config.action "read" (HTTP: GET), "write" (HTTP: PUT), or + * "delete" (HTTP: DELETE), "resumable" (HTTP: POST). + * When using "resumable", the header `X-Goog-Resumable: start` has + * to be sent when making a request with the signed URL. + * @param {*} config.expires A timestamp when this link will expire. Any value + * given is passed to `new Date()`. + * Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. + * See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example} + * @param {string} [config.version='v2'] The signing version to use, either + * 'v2' or 'v4'. + * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style + * URLs (e.g. 'https://mybucket.storage.googleapis.com/...') instead of path-style + * (e.g. 'https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs + * should generally be preferred instead of path-style URL. + * Currently defaults to `false` for path-style, although this may change in a + * future major-version release. + * @param {string} [config.cname] The cname for this bucket, i.e., + * "https://cdn.example.com". + * @param {string} [config.contentMd5] The MD5 digest value in base64. Just like + * if you provide this, the client must provide this HTTP header with this same + * value in its request, so to if this parameter is not provided here, + * the client must not provide any value for this HTTP header in its request. + * @param {string} [config.contentType] Just like if you provide this, the client + * must provide this HTTP header with this same value in its request, so to if + * this parameter is not provided here, the client must not provide any value + * for this HTTP header in its request. + * @param {object} [config.extensionHeaders] If these headers are used, the + * server will check to make sure that the client provides matching + * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers} + * for the requirements of this feature, most notably: + * - The header name must be prefixed with `x-goog-` + * - The header name must be all lowercase + * + * Note: Multi-valued header passed as an array in the extensionHeaders + * object is converted into a string, delimited by `,` with + * no space. Requests made using the signed URL will need to + * delimit multi-valued headers using a single `,` as well, or + * else the server will report a mismatched signature. + * @param {object} [config.queryParams] Additional query parameters to include + * in the signed URL. + * @param {string} [config.promptSaveAs] The filename to prompt the user to + * save the file as when the signed url is accessed. This is ignored if + * `config.responseDisposition` is set. + * @param {string} [config.responseDisposition] The + * {@link http://goo.gl/yMWxQV| response-content-disposition parameter} of the + * signed url. + * @param {*} [config.accessibleAt=Date.now()] A timestamp when this link became usable. Any value + * given is passed to `new Date()`. + * Note: Use for 'v4' only. + * @param {string} [config.responseType] The response-content-type parameter + * of the signed url. + * @param {GetSignedUrlCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Generate a URL that allows temporary access to download your file. + * //- + * const request = require('request'); + * + * const config = { + * action: 'read', + * expires: '03-17-2025', + * }; + * + * file.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file is now available to read from this URL. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // Generate a URL that allows temporary access to download your file. + * // Access will begin at accessibleAt and end at expires. + * //- + * const request = require('request'); + * + * const config = { + * action: 'read', + * expires: '03-17-2025', + * accessibleAt: '03-13-2025' + * }; + * + * file.getSignedUrl(config, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file will be available to read from this URL from 03-13-2025 to 03-17-2025. + * request(url, function(err, resp) { + * // resp.statusCode = 200 + * }); + * }); + * + * //- + * // Generate a URL to allow write permissions. This means anyone with this + * URL + * // can send a POST request with new data that will overwrite the file. + * //- + * file.getSignedUrl({ + * action: 'write', + * expires: '03-17-2025' + * }, function(err, url) { + * if (err) { + * console.error(err); + * return; + * } + * + * // The file is now available to be written to. + * const writeStream = request.put(url); + * writeStream.end('New data'); + * + * writeStream.on('complete', function(resp) { + * // Confirm the new content was saved. + * file.download(function(err, fileContents) { + * console.log('Contents:', fileContents.toString()); + * // Contents: New data + * }); + * }); + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.getSignedUrl(config).then(function(data) { + * const url = data[0]; + * }); + * + * ``` + * @example + * region_tag:storage_generate_signed_url + * Another example: + */ + getSignedUrl( + cfg: GetSignedUrlConfig, + callback?: GetSignedUrlCallback, + ): void | Promise { + const method = ActionToHTTPMethod[cfg.action]; + const extensionHeaders = objectKeyToLowercase(cfg.extensionHeaders || {}); + if (cfg.action === 'resumable') { + extensionHeaders['x-goog-resumable'] = 'start'; + } + + const queryParams = Object.assign({}, cfg.queryParams); + if (typeof cfg.responseType === 'string') { + queryParams['response-content-type'] = cfg.responseType!; + } + if (typeof cfg.promptSaveAs === 'string') { + queryParams['response-content-disposition'] = + 'attachment; filename="' + cfg.promptSaveAs + '"'; + } + if (typeof cfg.responseDisposition === 'string') { + queryParams['response-content-disposition'] = cfg.responseDisposition!; + } + if (this.generation) { + queryParams['generation'] = this.generation.toString(); + } + + const signConfig: SignerGetSignedUrlConfig = { + method, + expires: cfg.expires, + accessibleAt: cfg.accessibleAt, + extensionHeaders, + queryParams, + contentMd5: cfg.contentMd5, + contentType: cfg.contentType, + host: cfg.host, + }; + + if (cfg.cname) { + signConfig.cname = cfg.cname; + } + + if (cfg.version) { + signConfig.version = cfg.version; + } + + if (cfg.virtualHostedStyle) { + signConfig.virtualHostedStyle = cfg.virtualHostedStyle; + } + + if (!this.signer) { + this.signer = new URLSigner( + this.storage.authClient, + this.bucket, + this, + this.storage, + ); + } + + this.signer + .getSignedUrl(signConfig) + .then(signedUrl => callback!(null, signedUrl), callback!); + } + + isPublic(): Promise; + isPublic(callback: IsPublicCallback): void; + /** + * @callback IsPublicCallback + * @param {?Error} err Request error, if any. + * @param {boolean} resp Whether file is public or not. + */ + /** + * @typedef {array} IsPublicResponse + * @property {boolean} 0 Whether file is public or not. + */ + /** + * Check whether this file is public or not by sending + * a HEAD request without credentials. + * No errors from the server indicates that the current + * file is public. + * A 403-Forbidden error {@link https://cloud.google.com/storage/docs/json_api/v1/status-codes#403_Forbidden} + * indicates that file is private. + * Any other non 403 error is propagated to user. + * + * @param {IsPublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Check whether the file is publicly accessible. + * //- + * file.isPublic(function(err, resp) { + * if (err) { + * console.error(err); + * return; + * } + * console.log(`the file ${file.id} is public: ${resp}`) ; + * }) + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.isPublic().then(function(data) { + * const resp = data[0]; + * }); + * ``` + */ + + isPublic(callback?: IsPublicCallback): Promise | void { + // Build any custom headers based on the defined interceptors on the parent + // storage object and this object + const storageInterceptors = this.storage?.interceptors || []; + const fileInterceptors = this.interceptors || []; + const allInterceptors = storageInterceptors.concat(fileInterceptors); + const headers = allInterceptors.reduce((acc, curInterceptor) => { + const currentHeaders = curInterceptor.request({ + uri: `${this.storage.apiEndpoint}/${ + this.bucket.name + }/${encodeURIComponent(this.name)}`, + }); + + Object.assign(acc, currentHeaders.headers); + return acc; + }, {}); + + util.makeRequest( + { + method: 'GET', + uri: `${this.storage.apiEndpoint}/${ + this.bucket.name + }/${encodeURIComponent(this.name)}`, + headers, + }, + { + retryOptions: this.storage.retryOptions, + }, + (err: Error | ApiError | null) => { + if (err) { + const apiError = err as ApiError; + if (apiError.code === 403) { + callback!(null, false); + } else { + callback!(err); + } + } else { + callback!(null, true); + } + }, + ); + } + + makePrivate( + options?: MakeFilePrivateOptions, + ): Promise; + makePrivate(callback: MakeFilePrivateCallback): void; + makePrivate( + options: MakeFilePrivateOptions, + callback: MakeFilePrivateCallback, + ): void; + /** + * @typedef {object} MakeFilePrivateOptions Configuration options for File#makePrivate(). + * @property {Metadata} [metadata] Define custom metadata properties to define + * along with the operation. + * @property {boolean} [strict] If true, set the file to be private to + * only the owner user. Otherwise, it will be private to the project. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback MakeFilePrivateCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} MakeFilePrivateResponse + * @property {object} 0 The full API response. + */ + /** + * Make a file private to the project and remove all other permissions. + * Set `options.strict` to true to make the file private to only the owner. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch| Objects: patch API Documentation} + * + * @param {MakeFilePrivateOptions} [options] Configuration options. + * @param {MakeFilePrivateCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * //- + * // Set the file private so only project maintainers can see and modify it. + * //- + * file.makePrivate(function(err) {}); + * + * //- + * // Set the file private so only the owner can see and modify it. + * //- + * file.makePrivate({ strict: true }, function(err) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.makePrivate().then(function(data) { + * const apiResponse = data[0]; + * }); + * ``` + */ + makePrivate( + optionsOrCallback?: MakeFilePrivateOptions | MakeFilePrivateCallback, + callback?: MakeFilePrivateCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + const query = { + predefinedAcl: options.strict ? 'private' : 'projectPrivate', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; + + if (options.preconditionOpts?.ifMetagenerationMatch !== undefined) { + query.ifMetagenerationMatch = + options.preconditionOpts?.ifMetagenerationMatch; + delete options.preconditionOpts; + } + + if (options.userProject) { + query.userProject = options.userProject; + } + + // You aren't allowed to set both predefinedAcl & acl properties on a file, + // so acl must explicitly be nullified, destroying all previous acls on the + // file. + const metadata = {...options.metadata, acl: null}; + + this.setMetadata(metadata, query, callback!); + } + + makePublic(): Promise; + makePublic(callback: MakeFilePublicCallback): void; + /** + * @typedef {array} MakeFilePublicResponse + * @property {object} 0 The full API response. + */ + /** + * @callback MakeFilePublicCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Set a file to be publicly readable and maintain all previous permissions. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation} + * + * @param {MakeFilePublicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * + * file.makePublic(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.makePublic().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example + * region_tag:storage_make_public + * Another example: + */ + makePublic( + callback?: MakeFilePublicCallback, + ): Promise | void { + callback = callback || util.noop; + this.acl.add( + { + entity: 'allUsers', + role: 'READER', + }, + (err, acl, resp) => { + callback!(err, resp); + }, + ); + } + + /** + * The public URL of this File + * Use {@link File#makePublic} to enable anonymous access via the returned URL. + * + * @returns {string} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * // publicUrl will be "https://storage.googleapis.com/albums/my-file" + * const publicUrl = file.publicUrl(); + * ``` + */ + publicUrl(): string { + return `${this.storage.apiEndpoint}/${ + this.bucket.name + }/${encodeURIComponent(this.name)}`; + } + + moveFileAtomic( + destination: string | File, + options?: MoveFileAtomicOptions, + ): Promise; + moveFileAtomic( + destination: string | File, + callback: MoveFileAtomicCallback, + ): void; + moveFileAtomic( + destination: string | File, + options: MoveFileAtomicOptions, + callback: MoveFileAtomicCallback, + ): void; + /** + * @typedef {array} MoveFileAtomicResponse + * @property {File} 0 The moved {@link File}. + * @property {object} 1 The full API response. + */ + /** + * @callback MoveFileAtomicCallback + * @param {?Error} err Request error, if any. + * @param {File} movedFile The moved {@link File}. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} MoveFileAtomicOptions Configuration options for File#moveFileAtomic(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + * @property {object} [preconditionOpts] Precondition options. + * @property {number} [preconditionOpts.ifGenerationMatch] Makes the operation conditional on whether the object's current generation matches the given value. + */ + /** + * Move this file within the same bucket. + * The source object must exist and be a live object. + * The source and destination object IDs must be different. + * Overwriting the destination object is allowed by default, but can be prevented + * using preconditions. + * If the destination path includes non-existent parent folders, they will be created. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/move| Objects: move API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|File} destination Destination file name or File object within the same bucket.. + * @param {MoveFileAtomicOptions} [options] Configuration options. See an + * @param {MoveFileAtomicCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Assume 'my-bucket' is a bucket. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is copied to its + * // current bucket, under the new name provided. + * //- + * file.moveFileAtomic('moved-image.png', function(err, movedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "moved-image.png" + * + * // `movedFile` is an instance of a File object that refers to your new + * // file. + * }); + * + * //- + * // Move the file to a subdirectory, creating parent folders if necessary. + * //- + * file.moveFileAtomic('new-folder/subfolder/moved-image.png', function(err, movedFile, apiResponse) { + * // `my-bucket` now contains: + * // - "new-folder/subfolder/moved-image.png" + * }); + * + * //- + * // Prevent overwriting an existing destination object using preconditions. + * //- + * file.moveFileAtomic('existing-destination.png', { + * preconditionOpts: { + * ifGenerationMatch: 0 // Fails if the destination object exists. + * } + * }, function(err, movedFile, apiResponse) { + * if (err) { + * // Handle the error (e.g., the destination object already exists). + * } else { + * // Move successful. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.moveFileAtomic('moved-image.png).then(function(data) { + * const newFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_move_file + * Another example: + */ + moveFileAtomic( + destination: string | File, + optionsOrCallback?: MoveFileAtomicOptions | MoveFileAtomicCallback, + callback?: MoveFileAtomicCallback, + ): Promise | void { + const noDestinationError = new Error( + FileExceptionMessages.DESTINATION_NO_NAME, + ); + + if (!destination) { + throw noDestinationError; + } + + let options: MoveFileAtomicOptions = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = {...optionsOrCallback}; + } + + callback = callback || util.noop; + + let destName: string; + let newFile: File; + + if (typeof destination === 'string') { + const parsedDestination = GS_URL_REGEXP.exec(destination); + if (parsedDestination !== null && parsedDestination.length === 3) { + destName = parsedDestination[2]; + } else { + destName = destination; + } + } else if (destination instanceof File) { + destName = destination.name; + newFile = destination; + } else { + throw noDestinationError; + } + + newFile = newFile! || this.bucket.file(destName); + + if ( + !this.shouldRetryBasedOnPreconditionAndIdempotencyStrat( + options?.preconditionOpts, + ) + ) { + this.storage.retryOptions.autoRetry = false; + } + const query = {} as MoveFileAtomicQuery; + if (options.userProject !== undefined) { + query.userProject = options.userProject; + delete options.userProject; + } + if (options.preconditionOpts?.ifGenerationMatch !== undefined) { + query.ifGenerationMatch = options.preconditionOpts?.ifGenerationMatch; + delete options.preconditionOpts; + } + + this.request( + { + method: 'POST', + uri: `/moveTo/o/${encodeURIComponent(newFile.name)}`, + qs: query, + json: options, + }, + (err, resp) => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + if (err) { + callback!(err, null, resp); + return; + } + + callback!(null, newFile, resp); + }, + ); + } + + move( + destination: string | Bucket | File, + options?: MoveOptions, + ): Promise; + move(destination: string | Bucket | File, callback: MoveCallback): void; + move( + destination: string | Bucket | File, + options: MoveOptions, + callback: MoveCallback, + ): void; + /** + * @typedef {array} MoveResponse + * @property {File} 0 The destination File. + * @property {object} 1 The full API response. + */ + /** + * @callback MoveCallback + * @param {?Error} err Request error, if any. + * @param {?File} destinationFile The destination File. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} MoveOptions Configuration options for File#move(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Move this file to another location. By default, this will rename the file + * and keep it in the same bucket, but you can choose to move it to another + * Bucket by providing a Bucket or File object or a URL beginning with + * "gs://". + * + * **Warning**: + * There is currently no atomic `move` method in the Cloud Storage API, + * so this method is a composition of {@link File#copy} (to the new + * location) and {@link File#delete} (from the old location). While + * unlikely, it is possible that an error returned to your callback could be + * triggered from either one of these API calls failing, which could leave a + * duplicate file lingering. The error message will indicate what operation + * has failed. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/copy| Objects: copy API Documentation} + * + * @throws {Error} If the destination file is not provided. + * + * @param {string|Bucket|File} destination Destination file. + * @param {MoveCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * //- + * // You can pass in a variety of types for the destination. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // If you pass in a string for the destination, the file is moved to its + * // current bucket, under the new name provided. + * //- + * file.move('my-image-new.png', function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // but contains instead: + * // - "my-image-new.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a string starting with "gs://" for the destination, the + * // file is copied to the other bucket and under the new name provided. + * //- + * const newLocation = 'gs://another-bucket/my-image-new.png'; + * file.move(newLocation, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image-new.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a Bucket object, the file will be moved to that bucket + * // using the same name. + * //- + * const anotherBucket = gcs.bucket('another-bucket'); + * + * file.move(anotherBucket, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-image.png" + * + * // `destinationFile` is an instance of a File object that refers to your + * // new file. + * }); + * + * //- + * // If you pass in a File object, you have complete control over the new + * // bucket and filename. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * + * file.move(anotherFile, function(err, destinationFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // + * // `another-bucket` now contains: + * // - "my-awesome-image.png" + * + * // Note: + * // The `destinationFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.move('my-image-new.png').then(function(data) { + * const destinationFile = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_move_file + * Another example: + */ + move( + destination: string | Bucket | File, + optionsOrCallback?: MoveOptions | MoveCallback, + callback?: MoveCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + callback = callback || util.noop; + + this.copy(destination, options, (err, destinationFile, copyApiResponse) => { + if (err) { + err.message = 'file#copy failed with an error - ' + err.message; + callback!(err, null, copyApiResponse); + return; + } + + if ( + this.name !== destinationFile!.name || + this.bucket.name !== destinationFile!.bucket.name + ) { + this.delete(options, (err, apiResponse) => { + if (err) { + err.message = 'file#delete failed with an error - ' + err.message; + callback!(err, destinationFile, apiResponse); + return; + } + callback!(null, destinationFile, copyApiResponse); + }); + } else { + callback!(null, destinationFile, copyApiResponse); + } + }); + } + + rename( + destinationFile: string | File, + options?: RenameOptions, + ): Promise; + rename(destinationFile: string | File, callback: RenameCallback): void; + rename( + destinationFile: string | File, + options: RenameOptions, + callback: RenameCallback, + ): void; + /** + * @typedef {array} RenameResponse + * @property {File} 0 The destination File. + * @property {object} 1 The full API response. + */ + /** + * @callback RenameCallback + * @param {?Error} err Request error, if any. + * @param {?File} destinationFile The destination File. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {object} RenameOptions Configuration options for File#move(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * Rename this file. + * + * **Warning**: + * There is currently no atomic `rename` method in the Cloud Storage API, + * so this method is an alias of {@link File#move}, which in turn is a + * composition of {@link File#copy} (to the new location) and + * {@link File#delete} (from the old location). While + * unlikely, it is possible that an error returned to your callback could be + * triggered from either one of these API calls failing, which could leave a + * duplicate file lingering. The error message will indicate what operation + * has failed. + * + * @param {string|File} destinationFile Destination file. + * @param {RenameCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // You can pass in a string or a File object. + * // + * // For all of the below examples, assume we are working with the following + * // Bucket and File objects. + * //- + * + * const bucket = storage.bucket('my-bucket'); + * const file = bucket.file('my-image.png'); + * + * //- + * // You can pass in a string for the destinationFile. + * //- + * file.rename('renamed-image.png', function(err, renamedFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * // but contains instead: + * // - "renamed-image.png" + * + * // `renamedFile` is an instance of a File object that refers to your + * // renamed file. + * }); + * + * //- + * // You can pass in a File object. + * //- + * const anotherFile = anotherBucket.file('my-awesome-image.png'); + * + * file.rename(anotherFile, function(err, renamedFile, apiResponse) { + * // `my-bucket` no longer contains: + * // - "my-image.png" + * + * // Note: + * // The `renamedFile` parameter is equal to `anotherFile`. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.rename('my-renamed-image.png').then(function(data) { + * const renamedFile = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + rename( + destinationFile: string | File, + optionsOrCallback?: RenameOptions | RenameCallback, + callback?: RenameCallback, + ): Promise | void { + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + + callback = callback || util.noop; + + this.move(destinationFile, options, callback); + } + + /** + * @typedef {object} RestoreOptions Options for File#restore(). See an + * {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}. + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + * @param {number} [generation] If present, selects a specific revision of this object. + * @param {string} [restoreToken] Returns an option that must be specified when getting a soft-deleted object from an HNS-enabled + * bucket that has a naming and generation conflict with another object in the same bucket. + * @param {string} [projection] Specifies the set of properties to return. If used, must be 'full' or 'noAcl'. + * @param {string | number} [ifGenerationMatch] Request proceeds if the generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifGenerationNotMatch] Request proceeds if the generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + * @param {string | number} [ifMetagenerationMatch] Request proceeds if the meta-generation of the target resource + * matches the value used in the precondition. + * If the values don't match, the request fails with a 412 Precondition Failed response. + * @param {string | number} [ifMetagenerationNotMatch] Request proceeds if the meta-generation of the target resource does + * not match the value used in the precondition. If the values match, the request fails with a 304 Not Modified response. + */ + /** + * Restores a soft-deleted file + * @param {RestoreOptions} options Restore options. + * @returns {Promise} + */ + async restore(options: RestoreOptions): Promise { + const [file] = await this.request({ + method: 'POST', + uri: '/restore', + qs: options, + }); + + return file as File; + } + + request(reqOpts: DecorateRequestOptions): Promise; + request( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void; + /** + * Makes request and applies userProject query parameter if necessary. + * + * @private + * + * @param {object} reqOpts - The request options. + * @param {function} callback - The callback function. + */ + request( + reqOpts: DecorateRequestOptions, + callback?: BodyResponseCallback, + ): void | Promise { + return this.parent.request.call(this, reqOpts, callback!); + } + + rotateEncryptionKey( + options?: RotateEncryptionKeyOptions, + ): Promise; + rotateEncryptionKey(callback: RotateEncryptionKeyCallback): void; + rotateEncryptionKey( + options: RotateEncryptionKeyOptions, + callback: RotateEncryptionKeyCallback, + ): void; + /** + * @callback RotateEncryptionKeyCallback + * @extends CopyCallback + */ + /** + * @typedef RotateEncryptionKeyResponse + * @extends CopyResponse + */ + /** + * @param {string|buffer|object} RotateEncryptionKeyOptions Configuration options + * for File#rotateEncryptionKey(). + * If a string or Buffer is provided, it is interpreted as an AES-256, + * customer-supplied encryption key. If you'd like to use a Cloud KMS key + * name, you must specify an options object with the property name: + * `kmsKeyName`. + * @param {string|buffer} [options.encryptionKey] An AES-256 encryption key. + * @param {string} [options.kmsKeyName] A Cloud KMS key name. + */ + /** + * This method allows you to update the encryption key associated with this + * file. + * + * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys} + * + * @param {RotateEncryptionKeyOptions} [options] - Configuration options. + * @param {RotateEncryptionKeyCallback} [callback] + * @returns {Promise} + * + * @example + * region_tag:storage_rotate_encryption_key + * Example of rotating the encryption key for this file: + */ + rotateEncryptionKey( + optionsOrCallback?: + | RotateEncryptionKeyOptions + | RotateEncryptionKeyCallback, + callback?: RotateEncryptionKeyCallback, + ): Promise | void { + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + let options: EncryptionKeyOptions = {}; + if ( + typeof optionsOrCallback === 'string' || + optionsOrCallback instanceof Buffer + ) { + options = { + encryptionKey: optionsOrCallback, + }; + } else if (typeof optionsOrCallback === 'object') { + options = optionsOrCallback as EncryptionKeyOptions; + } + + const newFile = this.bucket.file(this.id!, options); + const copyOptions = + options.preconditionOpts?.ifGenerationMatch !== undefined + ? {preconditionOpts: options.preconditionOpts} + : {}; + this.copy(newFile, copyOptions, callback!); + } + + save(data: SaveData, options?: SaveOptions): Promise; + save(data: SaveData, callback: SaveCallback): void; + save(data: SaveData, options: SaveOptions, callback: SaveCallback): void; + /** + * @typedef {object} SaveOptions + * @extends CreateWriteStreamOptions + */ + /** + * @callback SaveCallback + * @param {?Error} err Request error, if any. + */ + /** + * Write strings or buffers to a file. + * + * *This is a convenience method which wraps {@link File#createWriteStream}.* + * To upload arbitrary data to a file, please use {@link File#createWriteStream} directly. + * + * Resumable uploads are automatically enabled and must be shut off explicitly + * by setting `options.resumable` to `false`. + * + * Multipart uploads with retryable error codes will be retried 3 times with exponential backoff. + * + *

+ * There is some overhead when using a resumable upload that can cause + * noticeable performance degradation while uploading a series of small + * files. When uploading files less than 10MB, it is recommended that the + * resumable feature is disabled. + *

+ * + * @param {SaveData} data The data to write to a file. + * @param {SaveOptions} [options] See {@link File#createWriteStream}'s `options` + * parameter. + * @param {SaveCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const file = myBucket.file('my-file'); + * const contents = 'This is the contents of the file.'; + * + * file.save(contents, function(err) { + * if (!err) { + * // File written successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.save(contents).then(function() {}); + * ``` + */ + save( + data: SaveData, + optionsOrCallback?: SaveOptions | SaveCallback, + callback?: SaveCallback, + ): Promise | void { + // tslint:enable:no-any + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + + let maxRetries = this.storage.retryOptions.maxRetries; + if ( + !this.shouldRetryBasedOnPreconditionAndIdempotencyStrat( + options?.preconditionOpts, + ) + ) { + maxRetries = 0; + } + const returnValue = AsyncRetry( + async (bail: (err: Error) => void) => { + return new Promise((resolve, reject) => { + if (maxRetries === 0) { + this.storage.retryOptions.autoRetry = false; + } + const writable = this.createWriteStream(options); + + if (options.onUploadProgress) { + writable.on('progress', options.onUploadProgress); + } + + const handleError = (err: Error) => { + if ( + this.storage.retryOptions.autoRetry && + this.storage.retryOptions.retryableErrorFn!(err) + ) { + return reject(err); + } + + return bail(err); + }; + + if ( + typeof data === 'string' || + Buffer.isBuffer(data) || + data instanceof Uint8Array + ) { + writable + .on('error', handleError) + .on('finish', () => resolve()) + .end(data); + } else { + pipeline(data, writable, err => { + if (err) { + if (typeof data !== 'function') { + // Only PipelineSourceFunction can be retried. Async-iterables + // and Readable streams can only be consumed once. + return bail(err); + } + + handleError(err); + } else { + resolve(); + } + }); + } + }); + }, + { + retries: maxRetries, + factor: this.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.storage.retryOptions.maxRetryDelay! * 1000, //convert to milliseconds + maxRetryTime: this.storage.retryOptions.totalTimeout! * 1000, //convert to milliseconds + }, + ); + if (!callback) { + return returnValue; + } else { + return returnValue + .then(() => { + if (callback) { + return callback(); + } + }) + .catch(callback); + } + } + + setMetadata( + metadata: FileMetadata, + options?: SetMetadataOptions, + ): Promise>; + setMetadata( + metadata: FileMetadata, + callback: MetadataCallback, + ): void; + setMetadata( + metadata: FileMetadata, + options: SetMetadataOptions, + callback: MetadataCallback, + ): void; + setMetadata( + metadata: FileMetadata, + optionsOrCallback: SetMetadataOptions | MetadataCallback, + cb?: MetadataCallback, + ): Promise> | void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options: any = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as MetadataCallback) + : cb; + + this.disableAutoRetryConditionallyIdempotent_( + this.methods.setMetadata, + AvailableServiceObjectMethods.setMetadata, + options, + ); + + super + .setMetadata(metadata, options) + .then(resp => cb!(null, ...resp)) + .catch(cb!) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } + + setStorageClass( + storageClass: string, + options?: SetStorageClassOptions, + ): Promise; + setStorageClass( + storageClass: string, + options: SetStorageClassOptions, + callback: SetStorageClassCallback, + ): void; + setStorageClass( + storageClass: string, + callback?: SetStorageClassCallback, + ): void; + /** + * @typedef {array} SetStorageClassResponse + * @property {object} 0 The full API response. + */ + /** + * @typedef {object} SetStorageClassOptions Configuration options for File#setStorageClass(). + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @callback SetStorageClassCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Set the storage class for this file. + * + * See {@link https://cloud.google.com/storage/docs/per-object-storage-class| Per-Object Storage Class} + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} storageClass The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`) + * **Note:** The storage classes `multi_regional` and `regional` + * are now legacy and will be deprecated in the future. + * @param {SetStorageClassOptions} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {SetStorageClassCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * file.setStorageClass('nearline', function(err, apiResponse) { + * if (err) { + * // Error handling omitted. + * } + * + * // The storage class was updated successfully. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * file.setStorageClass('nearline').then(function() {}); + * ``` + */ + setStorageClass( + storageClass: string, + optionsOrCallback?: SetStorageClassOptions | SetStorageClassCallback, + callback?: SetStorageClassCallback, + ): Promise | void { + callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : callback; + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + + const req = { + ...options, + // In case we get input like `storageClass`, convert to `storage_class`. + storageClass: storageClass + .replace(/-/g, '_') + .replace(/([a-z])([A-Z])/g, (_, low, up) => { + return low + '_' + up; + }) + .toUpperCase(), + }; + + this.copy(this, req, (err, file, apiResponse) => { + if (err) { + callback!(err, apiResponse!); + return; + } + + this.metadata = file!.metadata; + + callback!(null, apiResponse!); + }); + } + + /** + * Set a user project to be billed for all requests made from this File + * object. + * + * @param {string} userProject The user project. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('albums'); + * const file = bucket.file('my-file'); + * + * file.setUserProject('grape-spaceship-123'); + * ``` + */ + setUserProject(userProject: string): void { + this.bucket.setUserProject.call(this, userProject); + } + + /** + * This creates a resumable-upload upload stream. + * + * @param {Duplexify} stream - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startResumableUpload_( + dup: Duplexify, + options: CreateResumableUploadOptions = {}, + ): void { + options.metadata ??= {}; + + const retryOptions = this.storage.retryOptions; + if ( + !this.shouldRetryBasedOnPreconditionAndIdempotencyStrat( + options.preconditionOpts, + ) + ) { + retryOptions.autoRetry = false; + } + const cfg = { + authClient: this.storage.authClient, + apiEndpoint: this.storage.apiEndpoint, + bucket: this.bucket.name, + customRequestOptions: this.getRequestInterceptors().reduce( + (reqOpts, interceptorFn) => interceptorFn(reqOpts), + {}, + ), + file: this.name, + generation: this.generation, + isPartialUpload: options.isPartialUpload, + key: this.encryptionKey, + kmsKeyName: this.kmsKeyName, + metadata: options.metadata, + offset: options.offset, + predefinedAcl: options.predefinedAcl, + private: options.private, + public: options.public, + uri: options.uri, + userProject: options.userProject || this.userProject, + retryOptions: {...retryOptions}, + params: options?.preconditionOpts || this.instancePreconditionOpts, + chunkSize: options?.chunkSize, + highWaterMark: options?.highWaterMark, + universeDomain: this.bucket.storage.universeDomain, + [GCCL_GCS_CMD_KEY]: options[GCCL_GCS_CMD_KEY], + }; + + let uploadStream: resumableUpload.Upload; + + try { + uploadStream = resumableUpload.upload(cfg); + } catch (error) { + dup.destroy(error as Error); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + return; + } + + uploadStream + .on('response', resp => { + dup.emit('response', resp); + }) + .on('uri', uri => { + dup.emit('uri', uri); + }) + .on('metadata', metadata => { + this.metadata = metadata; + dup.emit('metadata'); + }) + .on('finish', () => { + dup.emit('complete'); + }) + .on('progress', evt => dup.emit('progress', evt)); + + dup.setWritable(uploadStream); + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + } + + /** + * Takes a readable stream and pipes it to a remote file. Unlike + * `startResumableUpload_`, which uses the resumable upload technique, this + * method uses a simple upload (all or nothing). + * + * @param {Duplexify} dup - Duplexify stream of data to pipe to the file. + * @param {object=} options - Configuration object. + * + * @private + */ + startSimpleUpload_( + dup: Duplexify, + options: CreateWriteStreamOptions = {}, + ): void { + options.metadata ??= {}; + + const apiEndpoint = this.storage.apiEndpoint; + const bucketName = this.bucket.name; + const uri = `${apiEndpoint}/upload/storage/v1/b/${bucketName}/o`; + + const reqOpts: DecorateRequestOptions = { + qs: { + name: this.name, + }, + uri: uri, + [GCCL_GCS_CMD_KEY]: options[GCCL_GCS_CMD_KEY], + }; + + if (this.generation !== undefined) { + reqOpts.qs.ifGenerationMatch = this.generation; + } + + if (this.kmsKeyName !== undefined) { + reqOpts.qs.kmsKeyName = this.kmsKeyName; + } + + if (typeof options.timeout === 'number') { + reqOpts.timeout = options.timeout; + } + + if (options.userProject || this.userProject) { + reqOpts.qs.userProject = options.userProject || this.userProject; + } + + if (options.predefinedAcl) { + reqOpts.qs.predefinedAcl = options.predefinedAcl; + } else if (options.private) { + reqOpts.qs.predefinedAcl = 'private'; + } else if (options.public) { + reqOpts.qs.predefinedAcl = 'publicRead'; + } + + Object.assign( + reqOpts.qs, + this.instancePreconditionOpts, + options.preconditionOpts, + ); + + util.makeWritableStream(dup, { + makeAuthenticatedRequest: (reqOpts: object) => { + this.request(reqOpts as DecorateRequestOptions, (err, body, resp) => { + if (err) { + dup.destroy(err); + return; + } + + this.metadata = body; + dup.emit('metadata', body); + dup.emit('response', resp); + dup.emit('complete'); + }); + }, + metadata: options.metadata, + request: reqOpts, + }); + } + + disableAutoRetryConditionallyIdempotent_( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + coreOpts: any, + methodType: AvailableServiceObjectMethods, + localPreconditionOptions?: PreconditionOptions, + ): void { + if ( + (typeof coreOpts === 'object' && + coreOpts?.reqOpts?.qs?.ifGenerationMatch === undefined && + localPreconditionOptions?.ifGenerationMatch === undefined && + methodType === AvailableServiceObjectMethods.delete && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever + ) { + this.storage.retryOptions.autoRetry = false; + } + + if ( + (typeof coreOpts === 'object' && + coreOpts?.reqOpts?.qs?.ifMetagenerationMatch === undefined && + localPreconditionOptions?.ifMetagenerationMatch === undefined && + methodType === AvailableServiceObjectMethods.setMetadata && + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryConditional) || + this.storage.retryOptions.idempotencyStrategy === + IdempotencyStrategy.RetryNever + ) { + this.storage.retryOptions.autoRetry = false; + } + } + + private async getBufferFromReadable(readable: Readable): Promise { + const buf = []; + for await (const chunk of readable) { + buf.push(chunk); + } + + return Buffer.concat(buf); + } + + /** + * + * @param hashCalculatingStream + * @param verify + * @returns {boolean} Returns `true` if valid, throws with error otherwise + */ + async #validateIntegrity( + hashCalculatingStream: HashStreamValidator, + verify: {crc32c?: boolean; md5?: boolean} = {}, + ) { + const metadata = this.metadata; + + // If we're doing validation, assume the worst + let dataMismatch = !!(verify.crc32c || verify.md5); + + if (verify.crc32c && metadata.crc32c) { + dataMismatch = !hashCalculatingStream.test('crc32c', metadata.crc32c); + } + + if (verify.md5 && metadata.md5Hash) { + dataMismatch = !hashCalculatingStream.test('md5', metadata.md5Hash); + } + + if (dataMismatch) { + const errors: Error[] = []; + let code = ''; + let message = ''; + + try { + await this.delete(); + + if (verify.md5 && !metadata.md5Hash) { + code = 'MD5_NOT_AVAILABLE'; + message = FileExceptionMessages.MD5_NOT_AVAILABLE; + } else { + code = 'FILE_NO_UPLOAD'; + message = FileExceptionMessages.UPLOAD_MISMATCH; + } + } catch (e) { + const error = e as Error; + + code = 'FILE_NO_UPLOAD_DELETE'; + message = `${FileExceptionMessages.UPLOAD_MISMATCH_DELETE_FAIL}${error.message}`; + + errors.push(error); + } + + const error = new RequestError(message); + error.code = code; + error.errors = errors; + + throw error; + } + + return true; + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(File, { + exclude: [ + 'cloudStorageURI', + 'publicUrl', + 'request', + 'save', + 'setEncryptionKey', + 'shouldRetryBasedOnPreconditionAndIdempotencyStrat', + 'getBufferFromReadable', + 'restore', + ], +}); + +/** + * Reference to the {@link File} class. + * @name module:@google-cloud/storage.File + * @see File + */ +export {File}; diff --git a/handwritten/storage/src/hash-stream-validator.ts b/handwritten/storage/src/hash-stream-validator.ts new file mode 100644 index 00000000000..b41dd51b6dc --- /dev/null +++ b/handwritten/storage/src/hash-stream-validator.ts @@ -0,0 +1,161 @@ +// Copyright 2022 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 {createHash, Hash} from 'crypto'; +import {Transform} from 'stream'; + +import { + CRC32CValidatorGenerator, + CRC32C_DEFAULT_VALIDATOR_GENERATOR, + CRC32CValidator, +} from './crc32c.js'; +import {FileExceptionMessages, RequestError} from './file.js'; + +interface HashStreamValidatorOptions { + /** Enables CRC32C calculation. To validate a provided value use `crc32cExpected`. */ + crc32c: boolean; + /** Enables MD5 calculation. To validate a provided value use `md5Expected`. */ + md5: boolean; + /** A CRC32C instance for validation. To validate a provided value use `crc32cExpected`. */ + crc32cInstance: CRC32CValidator; + /** Set a custom CRC32C generator. Used if `crc32cInstance` has not been provided. */ + crc32cGenerator: CRC32CValidatorGenerator; + /** Sets the expected CRC32C value to verify once all data has been consumed. Also sets the `crc32c` option to `true` */ + crc32cExpected?: string; + /** Sets the expected MD5 value to verify once all data has been consumed. Also sets the `md5` option to `true` */ + md5Expected?: string; + /** Indicates whether or not to run a validation check or only update the hash values */ + updateHashesOnly?: boolean; +} +class HashStreamValidator extends Transform { + readonly crc32cEnabled: boolean; + readonly md5Enabled: boolean; + readonly crc32cExpected: string | undefined; + readonly md5Expected: string | undefined; + readonly updateHashesOnly: boolean = false; + + #crc32cHash?: CRC32CValidator = undefined; + #md5Hash?: Hash = undefined; + #md5Digest = ''; + + constructor(options: Partial = {}) { + super(); + + this.crc32cEnabled = !!options.crc32c; + this.md5Enabled = !!options.md5; + this.updateHashesOnly = !!options.updateHashesOnly; + this.crc32cExpected = options.crc32cExpected; + this.md5Expected = options.md5Expected; + + if (this.crc32cEnabled) { + if (options.crc32cInstance) { + this.#crc32cHash = options.crc32cInstance; + } else { + const crc32cGenerator = + options.crc32cGenerator || CRC32C_DEFAULT_VALIDATOR_GENERATOR; + + this.#crc32cHash = crc32cGenerator(); + } + } + + if (this.md5Enabled) { + this.#md5Hash = createHash('md5'); + } + } + + /** + * Return the current CRC32C value, if available. + */ + get crc32c() { + return this.#crc32cHash?.toString(); + } + + /** + * Return the calculated MD5 value, if available. + */ + get md5Digest(): string | undefined { + if (this.#md5Hash && !this.#md5Digest) { + this.#md5Digest = this.#md5Hash.digest('base64'); + } + return this.#md5Digest; + } + + _flush(callback: (error?: Error | null | undefined) => void) { + // Triggers the getter logic to finalize and cache the MD5 digest + this.md5Digest; + + if (this.updateHashesOnly) { + callback(); + return; + } + + // If we're doing validation, assume the worst-- a data integrity + // mismatch. If not, these tests won't be performed, and we can assume + // the best. + // We must check if the server decompressed the data on serve because hash + // validation is not possible in this case. + let failed = this.crc32cEnabled || this.md5Enabled; + + if (this.crc32cEnabled && this.crc32cExpected) { + failed = !this.test('crc32c', this.crc32cExpected); + } + + if (this.md5Enabled && this.md5Expected) { + failed = !this.test('md5', this.md5Expected); + } + + if (failed) { + const mismatchError = new RequestError( + FileExceptionMessages.DOWNLOAD_MISMATCH, + ); + mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; + + callback(mismatchError); + } else { + callback(); + } + } + + _transform( + chunk: Buffer, + encoding: BufferEncoding, + callback: (e?: Error) => void, + ) { + this.push(chunk, encoding); + + try { + if (this.#crc32cHash) this.#crc32cHash.update(chunk); + if (this.#md5Hash) this.#md5Hash.update(chunk); + callback(); + } catch (e) { + callback(e as Error); + } + } + + test(hash: 'crc32c' | 'md5', sum: Buffer | string): boolean { + const check = Buffer.isBuffer(sum) ? sum.toString('base64') : sum; + + if (hash === 'crc32c' && this.#crc32cHash) { + return this.#crc32cHash.validate(check); + } + + if (hash === 'md5' && this.#md5Hash) { + return this.#md5Digest === check; + } + + return false; + } +} + +export {HashStreamValidator, HashStreamValidatorOptions}; diff --git a/handwritten/storage/src/hmacKey.ts b/handwritten/storage/src/hmacKey.ts new file mode 100644 index 00000000000..4f73737331d --- /dev/null +++ b/handwritten/storage/src/hmacKey.ts @@ -0,0 +1,419 @@ +// Copyright 2019 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 { + ServiceObject, + Methods, + MetadataCallback, + SetMetadataResponse, +} from './nodejs-common/index.js'; +import { + BaseMetadata, + SetMetadataOptions, +} from './nodejs-common/service-object.js'; +import {IdempotencyStrategy, Storage} from './storage.js'; +import {promisifyAll} from '@google-cloud/promisify'; + +export interface HmacKeyOptions { + projectId?: string; +} + +export interface HmacKeyMetadata extends BaseMetadata { + accessId?: string; + etag?: string; + projectId?: string; + serviceAccountEmail?: string; + state?: string; + timeCreated?: string; + updated?: string; +} + +export interface SetHmacKeyMetadataOptions { + /** + * This parameter is currently ignored. + */ + userProject?: string; +} + +export interface SetHmacKeyMetadata { + state?: 'ACTIVE' | 'INACTIVE'; + etag?: string; +} + +export interface HmacKeyMetadataCallback { + (err: Error | null, metadata?: HmacKeyMetadata, apiResponse?: unknown): void; +} + +export type HmacKeyMetadataResponse = [HmacKeyMetadata, unknown]; + +/** + * The API-formatted resource description of the HMAC key. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name HmacKey#metadata + * @type {object} + */ +/** + * An HmacKey object contains metadata of an HMAC key created from a + * service account through the {@link Storage} client using + * {@link Storage#createHmacKey}. + * + * See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation} + * + * @class + */ +export class HmacKey extends ServiceObject { + /** + * A reference to the {@link Storage} associated with this {@link HmacKey} + * instance. + * @name HmacKey#storage + * @type {Storage} + */ + storage: Storage; + private instanceRetryValue?: boolean; + + /** + * @typedef {object} HmacKeyOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + */ + /** + * Constructs an HmacKey object. + * + * Note: this only create a local reference to an HMAC key, to create + * an HMAC key, use {@link Storage#createHmacKey}. + * + * @param {Storage} storage The Storage instance this HMAC key is + * attached to. + * @param {string} accessId The unique accessId for this HMAC key. + * @param {HmacKeyOptions} options Constructor configurations. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('access-id'); + * ``` + */ + constructor(storage: Storage, accessId: string, options?: HmacKeyOptions) { + const methods = { + /** + * @typedef {object} DeleteHmacKeyOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {array} DeleteHmacKeyResponse + * @property {object} 0 The full API response. + */ + /** + * @callback DeleteHmacKeyCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ + /** + * Deletes an HMAC key. + * Key state must be set to `INACTIVE` prior to deletion. + * Caution: HMAC keys cannot be recovered once you delete them. + * + * The authenticated user must have `storage.hmacKeys.delete` permission for the project in which the key exists. + * + * @method HmacKey#delete + * @param {DeleteHmacKeyOptions} [options] Configuration options. + * @param {DeleteHmacKeyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Delete HMAC key after making the key inactive. + * //- + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * hmacKey.setMetadata({state: 'INACTIVE'}, (err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * hmacKey.delete((err) => { + * if (err) { + * console.error(err); + * return; + * } + * // The HMAC key is deleted. + * }); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * hmacKey + * .setMetadata({state: 'INACTIVE'}) + * .then(() => { + * return hmacKey.delete(); + * }); + * ``` + */ + delete: true, + /** + * @callback GetHmacKeyCallback + * @param {?Error} err Request error, if any. + * @param {HmacKey} hmacKey this {@link HmacKey} instance. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} GetHmacKeyResponse + * @property {HmacKey} 0 This {@link HmacKey} instance. + * @property {object} 1 The full API response. + */ + /** + * @typedef {object} GetHmacKeyOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * Retrieves and populate an HMAC key's metadata, and return + * this {@link HmacKey} instance. + * + * HmacKey.get() does not give the HMAC key secret, as + * it is only returned on creation. + * + * The authenticated user must have `storage.hmacKeys.get` permission + * for the project in which the key exists. + * + * @method HmacKey#get + * @param {GetHmacKeyOptions} [options] Configuration options. + * @param {GetHmacKeyCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Get the HmacKey's Metadata. + * //- + * storage.hmacKey('ACCESS_ID') + * .get((err, hmacKey) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * // do something with the returned HmacKey object. + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .get() + * .then((data) => { + * const hmacKey = data[0]; + * }); + * ``` + */ + get: true, + /** + * @typedef {object} GetHmacKeyMetadataOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * Retrieves and populate an HMAC key's metadata, and return + * the HMAC key's metadata as an object. + * + * HmacKey.getMetadata() does not give the HMAC key secret, as + * it is only returned on creation. + * + * The authenticated user must have `storage.hmacKeys.get` permission + * for the project in which the key exists. + * + * @method HmacKey#getMetadata + * @param {GetHmacKeyMetadataOptions} [options] Configuration options. + * @param {HmacKeyMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * //- + * // Get the HmacKey's metadata and populate to the metadata property. + * //- + * storage.hmacKey('ACCESS_ID') + * .getMetadata((err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * console.log(hmacKeyMetadata); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .getMetadata() + * .then((data) => { + * const hmacKeyMetadata = data[0]; + * console.log(hmacKeyMetadata); + * }); + * ``` + */ + getMetadata: true, + /** + * @typedef {object} SetHmacKeyMetadata Subset of {@link HmacKeyMetadata} to update. + * @property {string} state New state of the HmacKey. Either 'ACTIVE' or 'INACTIVE'. + * @property {string} [etag] Include an etag from a previous get HMAC key request + * to perform safe read-modify-write. + */ + /** + * @typedef {object} SetHmacKeyMetadataOptions + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @callback HmacKeyMetadataCallback + * @param {?Error} err Request error, if any. + * @param {HmacKeyMetadata} metadata The updated {@link HmacKeyMetadata} object. + * @param {object} apiResponse The full API response. + */ + /** + * @typedef {array} HmacKeyMetadataResponse + * @property {HmacKeyMetadata} 0 The updated {@link HmacKeyMetadata} object. + * @property {object} 1 The full API response. + */ + /** + * Updates the state of an HMAC key. See {@link SetHmacKeyMetadata} for + * valid states. + * + * @method HmacKey#setMetadata + * @param {SetHmacKeyMetadata} metadata The new metadata. + * @param {SetHmacKeyMetadataOptions} [options] Configuration options. + * @param {HmacKeyMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * const metadata = { + * state: 'INACTIVE', + * }; + * + * storage.hmacKey('ACCESS_ID') + * .setMetadata(metadata, (err, hmacKeyMetadata) => { + * if (err) { + * // The request was an error. + * console.error(err); + * return; + * } + * console.log(hmacKeyMetadata); + * }); + * + * //- + * // If the callback is omitted, a promise is returned. + * //- + * storage.hmacKey('ACCESS_ID') + * .setMetadata(metadata) + * .then((data) => { + * const hmacKeyMetadata = data[0]; + * console.log(hmacKeyMetadata); + * }); + * ``` + */ + setMetadata: { + reqOpts: { + method: 'PUT', + }, + }, + } as Methods; + + const projectId = (options && options.projectId) || storage.projectId; + + super({ + parent: storage, + id: accessId, + baseUrl: `/projects/${projectId}/hmacKeys`, + methods, + }); + + this.storage = storage; + this.instanceRetryValue = storage.retryOptions.autoRetry; + } + + /** + * Set the metadata for this object. + * + * @param {object} metadata - The metadata to set on this object. + * @param {object=} options - Configuration options. + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + setMetadata( + metadata: HmacKeyMetadata, + options?: SetMetadataOptions, + ): Promise>; + setMetadata( + metadata: HmacKeyMetadata, + callback: MetadataCallback, + ): void; + setMetadata( + metadata: HmacKeyMetadata, + options: SetMetadataOptions, + callback: MetadataCallback, + ): void; + setMetadata( + metadata: HmacKeyMetadata, + optionsOrCallback: SetMetadataOptions | MetadataCallback, + cb?: MetadataCallback, + ): Promise> | void { + // ETag preconditions are not currently supported. Retries should be disabled if the idempotency strategy is not set to RetryAlways + if ( + this.storage.retryOptions.idempotencyStrategy !== + IdempotencyStrategy.RetryAlways + ) { + this.storage.retryOptions.autoRetry = false; + } + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : {}; + cb = + typeof optionsOrCallback === 'function' + ? (optionsOrCallback as MetadataCallback) + : cb; + + super + .setMetadata(metadata, options) + .then(resp => cb!(null, ...resp)) + .catch(cb!) + .finally(() => { + this.storage.retryOptions.autoRetry = this.instanceRetryValue; + }); + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(HmacKey); diff --git a/handwritten/storage/src/iam.ts b/handwritten/storage/src/iam.ts new file mode 100644 index 00000000000..7a90a1b36d4 --- /dev/null +++ b/handwritten/storage/src/iam.ts @@ -0,0 +1,497 @@ +// Copyright 2019 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 { + BodyResponseCallback, + DecorateRequestOptions, +} from './nodejs-common/index.js'; +import {promisifyAll} from '@google-cloud/promisify'; + +import {Bucket} from './bucket.js'; +import {normalize} from './util.js'; + +export interface GetPolicyOptions { + userProject?: string; + requestedPolicyVersion?: number; +} + +export type GetPolicyResponse = [Policy, unknown]; + +/** + * @callback GetPolicyCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The policy. + * @param {object} apiResponse The full API response. + */ +export interface GetPolicyCallback { + (err?: Error | null, acl?: Policy, apiResponse?: unknown): void; +} + +/** + * @typedef {object} SetPolicyOptions + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ +export interface SetPolicyOptions { + userProject?: string; +} + +/** + * @typedef {array} SetPolicyResponse + * @property {object} 0 The policy. + * @property {object} 1 The full API response. + */ +export type SetPolicyResponse = [Policy, unknown]; + +/** + * @callback SetPolicyCallback + * @param {?Error} err Request error, if any. + * @param {object} acl The policy. + * @param {object} apiResponse The full API response. + */ +export interface SetPolicyCallback { + (err?: Error | null, acl?: Policy, apiResponse?: object): void; +} + +export interface Policy { + bindings: PolicyBinding[]; + version?: number; + etag?: string; +} + +export interface PolicyBinding { + role: string; + members: string[]; + condition?: Expr; +} + +export interface Expr { + title?: string; + description?: string; + expression: string; +} + +/** + * @typedef {array} TestIamPermissionsResponse + * @property {object} 0 A subset of permissions that the caller is allowed. + * @property {object} 1 The full API response. + */ +export type TestIamPermissionsResponse = [{[key: string]: boolean}, unknown]; + +/** + * @callback TestIamPermissionsCallback + * @param {?Error} err Request error, if any. + * @param {object} acl A subset of permissions that the caller is allowed. + * @param {object} apiResponse The full API response. + */ +export interface TestIamPermissionsCallback { + ( + err?: Error | null, + acl?: {[key: string]: boolean} | null, + apiResponse?: unknown, + ): void; +} + +/** + * @typedef {object} TestIamPermissionsOptions Configuration options for Iam#testPermissions(). + * @param {string} [userProject] The ID of the project which will be + * billed for the request. + */ +export interface TestIamPermissionsOptions { + userProject?: string; +} + +interface GetPolicyRequest { + userProject?: string; + optionsRequestedPolicyVersion?: number; +} + +export enum IAMExceptionMessages { + POLICY_OBJECT_REQUIRED = 'A policy object is required.', + PERMISSIONS_REQUIRED = 'Permissions are required.', +} + +/** + * Get and set IAM policies for your Cloud Storage bucket. + * + * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management} + * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @constructor Iam + * + * @param {Bucket} bucket The parent instance. + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * // bucket.iam + * ``` + */ +class Iam { + private request_: ( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ) => void; + private resourceId_: string; + + constructor(bucket: Bucket) { + this.request_ = bucket.request.bind(bucket); + this.resourceId_ = 'buckets/' + bucket.getId(); + } + + getPolicy(options?: GetPolicyOptions): Promise; + getPolicy(options: GetPolicyOptions, callback: GetPolicyCallback): void; + getPolicy(callback: GetPolicyCallback): void; + /** + * @typedef {object} GetPolicyOptions Requested options for IAM#getPolicy(). + * @property {number} [requestedPolicyVersion] The version of IAM policies to + * request. If a policy with a condition is requested without setting + * this, the server will return an error. This must be set to a value + * of 3 to retrieve IAM policies containing conditions. This is to + * prevent client code that isn't aware of IAM conditions from + * interpreting and modifying policies incorrectly. The service might + * return a policy with version lower than the one that was requested, + * based on the feature syntax in the policy fetched. + * See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions} + * @property {string} [userProject] The ID of the project which will be + * billed for the request. + */ + /** + * @typedef {array} GetPolicyResponse + * @property {Policy} 0 The policy. + * @property {object} 1 The full API response. + */ + /** + * @typedef {object} Policy + * @property {PolicyBinding[]} policy.bindings Bindings associate members with roles. + * @property {string} [policy.etag] Etags are used to perform a read-modify-write. + * @property {number} [policy.version] The syntax schema version of the Policy. + * To set an IAM policy with conditional binding, this field must be set to + * 3 or greater. + * See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions} + */ + /** + * @typedef {object} PolicyBinding + * @property {string} role Role that is assigned to members. + * @property {string[]} members Specifies the identities requesting access for the bucket. + * @property {Expr} [condition] The condition that is associated with this binding. + */ + /** + * @typedef {object} Expr + * @property {string} [title] An optional title for the expression, i.e. a + * short string describing its purpose. This can be used e.g. in UIs + * which allow to enter the expression. + * @property {string} [description] An optional description of the + * expression. This is a longer text which describes the expression, + * e.g. when hovered over it in a UI. + * @property {string} expression Textual representation of an expression in + * Common Expression Language syntax. The application context of the + * containing message determines which well-known feature set of CEL + * is supported.The condition that is associated with this binding. + * + * @see [Condition] https://cloud.google.com/storage/docs/access-control/iam#conditions + */ + /** + * Get the IAM policy. + * + * @param {GetPolicyOptions} [options] Request options. + * @param {GetPolicyCallback} [callback] Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy| Buckets: setIamPolicy API Documentation} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * bucket.iam.getPolicy( + * {requestedPolicyVersion: 3}, + * function(err, policy, apiResponse) { + * + * }, + * ); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.getPolicy({requestedPolicyVersion: 3}) + * .then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example
+ * region_tag:storage_view_bucket_iam_members + * Example of retrieving a bucket's IAM policy: + */ + getPolicy( + optionsOrCallback?: GetPolicyOptions | GetPolicyCallback, + callback?: GetPolicyCallback, + ): Promise | void { + const {options, callback: cb} = normalize< + GetPolicyOptions, + GetPolicyCallback + >(optionsOrCallback, callback); + + const qs: GetPolicyRequest = {}; + if (options.userProject) { + qs.userProject = options.userProject; + } + + if ( + options.requestedPolicyVersion !== null && + options.requestedPolicyVersion !== undefined + ) { + qs.optionsRequestedPolicyVersion = options.requestedPolicyVersion; + } + + this.request_( + { + uri: '/iam', + qs, + }, + cb!, + ); + } + + setPolicy( + policy: Policy, + options?: SetPolicyOptions, + ): Promise; + setPolicy(policy: Policy, callback: SetPolicyCallback): void; + setPolicy( + policy: Policy, + options: SetPolicyOptions, + callback: SetPolicyCallback, + ): void; + /** + * Set the IAM policy. + * + * @throws {Error} If no policy is provided. + * + * @param {Policy} policy The policy. + * @param {SetPolicyOptions} [options] Configuration options. + * @param {SetPolicyCallback} callback Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy| Buckets: setIamPolicy API Documentation} + * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * const myPolicy = { + * bindings: [ + * { + * role: 'roles/storage.admin', + * members: + * ['serviceAccount:myotherproject@appspot.gserviceaccount.com'] + * } + * ] + * }; + * + * bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.setPolicy(myPolicy).then(function(data) { + * const policy = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_add_bucket_iam_member + * Example of adding to a bucket's IAM policy: + * + * @example + * region_tag:storage_remove_bucket_iam_member + * Example of removing from a bucket's IAM policy: + */ + setPolicy( + policy: Policy, + optionsOrCallback?: SetPolicyOptions | SetPolicyCallback, + callback?: SetPolicyCallback, + ): Promise | void { + if (policy === null || typeof policy !== 'object') { + throw new Error(IAMExceptionMessages.POLICY_OBJECT_REQUIRED); + } + + const {options, callback: cb} = normalize< + SetPolicyOptions, + SetPolicyCallback + >(optionsOrCallback, callback); + + let maxRetries; + if (policy.etag === undefined) { + maxRetries = 0; + } + + this.request_( + { + method: 'PUT', + uri: '/iam', + maxRetries, + json: Object.assign( + { + resourceId: this.resourceId_, + }, + policy, + ), + qs: options, + }, + cb, + ); + } + + testPermissions( + permissions: string | string[], + options?: TestIamPermissionsOptions, + ): Promise; + testPermissions( + permissions: string | string[], + callback: TestIamPermissionsCallback, + ): void; + testPermissions( + permissions: string | string[], + options: TestIamPermissionsOptions, + callback: TestIamPermissionsCallback, + ): void; + /** + * Test a set of permissions for a resource. + * + * @throws {Error} If permissions are not provided. + * + * @param {string|string[]} permissions The permission(s) to test for. + * @param {TestIamPermissionsOptions} [options] Configuration object. + * @param {TestIamPermissionsCallback} [callback] Callback function. + * @returns {Promise} + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions| Buckets: testIamPermissions API Documentation} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * + * //- + * // Test a single permission. + * //- + * const test = 'storage.buckets.delete'; + * + * bucket.iam.testPermissions(test, function(err, permissions, apiResponse) { + * console.log(permissions); + * // { + * // "storage.buckets.delete": true + * // } + * }); + * + * //- + * // Test several permissions at once. + * //- + * const tests = [ + * 'storage.buckets.delete', + * 'storage.buckets.get' + * ]; + * + * bucket.iam.testPermissions(tests, function(err, permissions) { + * console.log(permissions); + * // { + * // "storage.buckets.delete": false, + * // "storage.buckets.get": true + * // } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * bucket.iam.testPermissions(test).then(function(data) { + * const permissions = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + testPermissions( + permissions: string | string[], + optionsOrCallback?: TestIamPermissionsOptions | TestIamPermissionsCallback, + callback?: TestIamPermissionsCallback, + ): Promise | void { + if (!Array.isArray(permissions) && typeof permissions !== 'string') { + throw new Error(IAMExceptionMessages.PERMISSIONS_REQUIRED); + } + + const {options, callback: cb} = normalize< + TestIamPermissionsOptions, + TestIamPermissionsCallback + >(optionsOrCallback, callback); + + const permissionsArray = Array.isArray(permissions) + ? permissions + : [permissions]; + + const req = Object.assign( + { + permissions: permissionsArray, + }, + options, + ); + + this.request_( + { + uri: '/iam/testPermissions', + qs: req, + useQuerystring: true, + }, + (err, resp) => { + if (err) { + cb!(err, null, resp); + return; + } + + const availablePermissions = Array.isArray(resp.permissions) + ? resp.permissions + : []; + + const permissionsHash = permissionsArray.reduce( + (acc: {[index: string]: boolean}, permission) => { + acc[permission] = availablePermissions.indexOf(permission) > -1; + return acc; + }, + {}, + ); + + cb!(null, permissionsHash, resp); + }, + ); + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Iam); + +export {Iam}; diff --git a/handwritten/storage/src/index.ts b/handwritten/storage/src/index.ts new file mode 100644 index 00000000000..32d2728bdeb --- /dev/null +++ b/handwritten/storage/src/index.ts @@ -0,0 +1,272 @@ +// Copyright 2019 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. + +/** + * The `@google-cloud/storage` package has a single named export which is the + * {@link Storage} (ES6) class, which should be instantiated with `new`. + * + * See {@link Storage} and {@link ClientConfig} for client methods and + * configuration options. + * + * @module {Storage} @google-cloud/storage + * @alias nodejs-storage + * + * @example + * Install the client library with npm: + * ``` + * npm install --save @google-cloud/storage + * ``` + * + * @example + * Import the client library + * ``` + * const {Storage} = require('@google-cloud/storage'); + * ``` + * + * @example + * Create a client that uses Application + * Default Credentials (ADC): + * ``` + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit + * credentials: + * ``` + * const storage = new Storage({ projectId: + * 'your-project-id', keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example + * region_tag:storage_quickstart + * Full quickstart example: + */ +export {ApiError} from './nodejs-common/index.js'; +export { + BucketCallback, + BucketOptions, + CreateBucketQuery, + CreateBucketRequest, + CreateBucketResponse, + CreateHmacKeyCallback, + CreateHmacKeyOptions, + CreateHmacKeyResponse, + GetBucketsCallback, + GetBucketsRequest, + GetBucketsResponse, + GetHmacKeysCallback, + GetHmacKeysOptions, + GetHmacKeysResponse, + GetServiceAccountCallback, + GetServiceAccountOptions, + GetServiceAccountResponse, + HmacKeyResourceResponse, + IdempotencyStrategy, + PreconditionOptions, + RETRYABLE_ERR_FN_DEFAULT, + ServiceAccount, + Storage, + StorageOptions, +} from './storage.js'; +export { + AclMetadata, + AccessControlObject, + AclOptions, + AddAclCallback, + AddAclOptions, + AddAclResponse, + GetAclCallback, + GetAclOptions, + GetAclResponse, + RemoveAclCallback, + RemoveAclOptions, + RemoveAclResponse, + UpdateAclCallback, + UpdateAclOptions, + UpdateAclResponse, +} from './acl.js'; +export { + Bucket, + BucketExistsCallback, + BucketExistsOptions, + BucketExistsResponse, + BucketLockCallback, + BucketLockResponse, + BucketMetadata, + CombineCallback, + CombineOptions, + CombineResponse, + CreateChannelCallback, + CreateChannelConfig, + CreateChannelOptions, + CreateChannelResponse, + CreateNotificationCallback, + CreateNotificationOptions, + CreateNotificationResponse, + DeleteBucketCallback, + DeleteBucketOptions, + DeleteBucketResponse, + DeleteFilesCallback, + DeleteFilesOptions, + DeleteLabelsCallback, + DeleteLabelsResponse, + DisableRequesterPaysCallback, + DisableRequesterPaysResponse, + EnableRequesterPaysCallback, + EnableRequesterPaysResponse, + GetBucketCallback, + GetBucketMetadataCallback, + GetBucketMetadataOptions, + GetBucketMetadataResponse, + GetBucketOptions, + GetBucketResponse, + GetBucketSignedUrlConfig, + GetFilesCallback, + GetFilesOptions, + GetFilesResponse, + GetLabelsCallback, + GetLabelsOptions, + GetLabelsResponse, + GetNotificationsCallback, + GetNotificationsOptions, + GetNotificationsResponse, + Labels, + LifecycleAction, + LifecycleCondition, + LifecycleRule, + MakeBucketPrivateCallback, + MakeBucketPrivateOptions, + MakeBucketPrivateResponse, + MakeBucketPublicCallback, + MakeBucketPublicOptions, + MakeBucketPublicResponse, + SetBucketMetadataCallback, + SetBucketMetadataOptions, + SetBucketMetadataResponse, + SetBucketStorageClassCallback, + SetBucketStorageClassOptions, + SetLabelsCallback, + SetLabelsOptions, + SetLabelsResponse, + UploadCallback, + UploadOptions, + UploadResponse, +} from './bucket.js'; +export * from './crc32c.js'; +export {Channel, StopCallback} from './channel.js'; +export { + CopyCallback, + CopyOptions, + CopyResponse, + CreateReadStreamOptions, + CreateResumableUploadCallback, + CreateResumableUploadOptions, + CreateResumableUploadResponse, + CreateWriteStreamOptions, + DeleteFileCallback, + DeleteFileOptions, + DeleteFileResponse, + DownloadCallback, + DownloadOptions, + DownloadResponse, + EncryptionKeyOptions, + File, + FileExistsCallback, + FileExistsOptions, + FileExistsResponse, + FileMetadata, + FileOptions, + GetExpirationDateCallback, + GetExpirationDateResponse, + GetFileCallback, + GetFileMetadataCallback, + GetFileMetadataOptions, + GetFileMetadataResponse, + GetFileOptions, + GetFileResponse, + GenerateSignedPostPolicyV2Callback, + GenerateSignedPostPolicyV2Options, + GenerateSignedPostPolicyV2Response, + GenerateSignedPostPolicyV4Callback, + GenerateSignedPostPolicyV4Options, + GenerateSignedPostPolicyV4Response, + GetSignedUrlConfig, + MakeFilePrivateCallback, + MakeFilePrivateOptions, + MakeFilePrivateResponse, + MakeFilePublicCallback, + MakeFilePublicResponse, + MoveCallback, + MoveOptions, + MoveResponse, + MoveFileAtomicOptions, + MoveFileAtomicCallback, + MoveFileAtomicResponse, + PolicyDocument, + PolicyFields, + PredefinedAcl, + RotateEncryptionKeyCallback, + RotateEncryptionKeyOptions, + RotateEncryptionKeyResponse, + SaveCallback, + SaveData, + SaveOptions, + SetFileMetadataCallback, + SetFileMetadataOptions, + SetFileMetadataResponse, + SetStorageClassCallback, + SetStorageClassOptions, + SetStorageClassResponse, + SignedPostPolicyV4Output, +} from './file.js'; +export * from './hash-stream-validator.js'; +export { + HmacKey, + HmacKeyMetadata, + HmacKeyMetadataCallback, + HmacKeyMetadataResponse, + SetHmacKeyMetadata, + SetHmacKeyMetadataOptions, +} from './hmacKey.js'; +export { + GetPolicyCallback, + GetPolicyOptions, + GetPolicyResponse, + Iam, + Policy, + SetPolicyCallback, + SetPolicyOptions, + SetPolicyResponse, + TestIamPermissionsCallback, + TestIamPermissionsOptions, + TestIamPermissionsResponse, +} from './iam.js'; +export { + DeleteNotificationCallback, + DeleteNotificationOptions, + GetNotificationCallback, + GetNotificationMetadataCallback, + GetNotificationMetadataOptions, + GetNotificationMetadataResponse, + GetNotificationOptions, + GetNotificationResponse, + Notification, + NotificationMetadata, +} from './notification.js'; +export {GetSignedUrlCallback, GetSignedUrlResponse} from './signer.js'; +export * from './transfer-manager.js'; diff --git a/handwritten/storage/src/nodejs-common/index.ts b/handwritten/storage/src/nodejs-common/index.ts new file mode 100644 index 00000000000..89ed3ea815e --- /dev/null +++ b/handwritten/storage/src/nodejs-common/index.ts @@ -0,0 +1,50 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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. + */ +export {GoogleAuthOptions} from 'google-auth-library'; + +export { + Service, + ServiceConfig, + ServiceOptions, + StreamRequestOptions, +} from './service.js'; + +export { + BaseMetadata, + DeleteCallback, + ExistsCallback, + GetConfig, + InstanceResponseCallback, + Interceptor, + MetadataCallback, + MetadataResponse, + Methods, + ResponseCallback, + ServiceObject, + ServiceObjectConfig, + ServiceObjectParent, + SetMetadataResponse, +} from './service-object.js'; + +export { + Abortable, + AbortableDuplex, + ApiError, + BodyResponseCallback, + DecorateRequestOptions, + ResponseBody, + util, +} from './util.js'; diff --git a/handwritten/storage/src/nodejs-common/service-object.ts b/handwritten/storage/src/nodejs-common/service-object.ts new file mode 100644 index 00000000000..4f83189d525 --- /dev/null +++ b/handwritten/storage/src/nodejs-common/service-object.ts @@ -0,0 +1,621 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 {promisifyAll} from '@google-cloud/promisify'; +import {EventEmitter} from 'events'; +import * as r from 'teeny-request'; + +import {StreamRequestOptions} from './service.js'; +import { + ApiError, + BodyResponseCallback, + DecorateRequestOptions, + ResponseBody, + util, +} from './util.js'; + +export type RequestResponse = [unknown, r.Response]; + +export interface ServiceObjectParent { + interceptors: Interceptor[]; + getRequestInterceptors(): Function[]; + requestStream(reqOpts: DecorateRequestOptions): r.Request; + request( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void; +} + +export interface Interceptor { + request(opts: r.Options): DecorateRequestOptions; +} + +export type GetMetadataOptions = object; + +export type MetadataResponse = [K, r.Response]; +export type MetadataCallback = ( + err: Error | null, + metadata?: K, + apiResponse?: r.Response, +) => void; + +export type ExistsOptions = object; +export interface ExistsCallback { + (err: Error | null, exists?: boolean): void; +} + +export interface ServiceObjectConfig { + /** + * The base URL to make API requests to. + */ + baseUrl?: string; + + /** + * The method which creates this object. + */ + createMethod?: Function; + + /** + * The identifier of the object. For example, the name of a Storage bucket or + * Pub/Sub topic. + */ + id?: string; + + /** + * A map of each method name that should be inherited. + */ + methods?: Methods; + + /** + * The parent service instance. For example, an instance of Storage if the + * object is Bucket. + */ + parent: ServiceObjectParent; + + /** + * Override of projectId, used to allow access to resources in another project. + * For example, a BigQuery dataset in another project to which the user has been + * granted permission. + */ + projectId?: string; +} + +export interface Methods { + [methodName: string]: {reqOpts?: r.CoreOptions} | boolean; +} + +export interface InstanceResponseCallback { + (err: ApiError | null, instance?: T | null, apiResponse?: r.Response): void; +} + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface CreateOptions {} +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars +export type CreateResponse = any[]; +export interface CreateCallback { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (err: ApiError | null, instance?: T | null, ...args: any[]): void; +} + +export type DeleteOptions = { + ignoreNotFound?: boolean; + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} & object; +export interface DeleteCallback { + (err: Error | null, apiResponse?: r.Response): void; +} + +export interface GetConfig { + /** + * Create the object if it doesn't already exist. + */ + autoCreate?: boolean; +} +export type GetOrCreateOptions = GetConfig & CreateOptions; +export type GetResponse = [T, r.Response]; + +export interface ResponseCallback { + (err?: Error | null, apiResponse?: r.Response): void; +} + +export type SetMetadataResponse = [K]; +export type SetMetadataOptions = object; + +export interface BaseMetadata { + id?: string; + kind?: string; + etag?: string; + selfLink?: string; + [key: string]: unknown; +} + +/** + * ServiceObject is a base class, meant to be inherited from by a "service + * object," like a BigQuery dataset or Storage bucket. + * + * Most of the time, these objects share common functionality; they can be + * created or deleted, and you can get or set their metadata. + * + * By inheriting from this class, a service object will be extended with these + * shared behaviors. Note that any method can be overridden when the service + * object requires specific behavior. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +class ServiceObject extends EventEmitter { + metadata: K; + baseUrl?: string; + parent: ServiceObjectParent; + id?: string; + private createMethod?: Function; + protected methods: Methods; + interceptors: Interceptor[]; + projectId?: string; + + /* + * @constructor + * @alias module:common/service-object + * + * @private + * + * @param {object} config - Configuration object. + * @param {string} config.baseUrl - The base URL to make API requests to. + * @param {string} config.createMethod - The method which creates this object. + * @param {string=} config.id - The identifier of the object. For example, the + * name of a Storage bucket or Pub/Sub topic. + * @param {object=} config.methods - A map of each method name that should be inherited. + * @param {object} config.methods[].reqOpts - Default request options for this + * particular method. A common use case is when `setMetadata` requires a + * `PUT` method to override the default `PATCH`. + * @param {object} config.parent - The parent service instance. For example, an + * instance of Storage if the object is Bucket. + */ + constructor(config: ServiceObjectConfig) { + super(); + this.metadata = {} as K; + this.baseUrl = config.baseUrl; + this.parent = config.parent; // Parent class. + this.id = config.id; // Name or ID (e.g. dataset ID, bucket name, etc). + this.createMethod = config.createMethod; + this.methods = config.methods || {}; + this.interceptors = []; + this.projectId = config.projectId; + + if (config.methods) { + // This filters the ServiceObject instance (e.g. a "File") to only have + // the configured methods. We make a couple of exceptions for core- + // functionality ("request()" and "getRequestInterceptors()") + Object.getOwnPropertyNames(ServiceObject.prototype) + .filter(methodName => { + return ( + // All ServiceObjects need `request` and `getRequestInterceptors`. + // clang-format off + !/^request/.test(methodName) && + !/^getRequestInterceptors/.test(methodName) && + // clang-format on + // The ServiceObject didn't redefine the method. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this as any)[methodName] === + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (ServiceObject.prototype as any)[methodName] && + // This method isn't wanted. + !config.methods![methodName] + ); + }) + .forEach(methodName => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this as any)[methodName] = undefined; + }); + } + } + + /** + * Create the object. + * + * @param {object=} options - Configuration object. + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.instance - The instance. + * @param {object} callback.apiResponse - The full API response. + */ + create(options?: CreateOptions): Promise>; + create(options: CreateOptions, callback: CreateCallback): void; + create(callback: CreateCallback): void; + create( + optionsOrCallback?: CreateOptions | CreateCallback, + callback?: CreateCallback, + ): void | Promise> { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + const args = [this.id] as Array<{}>; + + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback as CreateCallback; + } + + if (typeof optionsOrCallback === 'object') { + args.push(optionsOrCallback); + } + + // Wrap the callback to return *this* instance of the object, not the + // newly-created one. + // tslint: disable-next-line no-any + function onCreate(...args: [Error, ServiceObject]) { + const [err, instance] = args; + if (!err) { + self.metadata = instance.metadata; + if (self.id && instance.metadata) { + self.id = instance.metadata.id; + } + args[1] = self; // replace the created `instance` with this one. + } + callback!(...(args as {} as [Error, T])); + } + args.push(onCreate); + // eslint-disable-next-line prefer-spread + this.createMethod!.apply(null, args); + } + + /** + * Delete the object. + * + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + delete(options?: DeleteOptions): Promise<[r.Response]>; + delete(options: DeleteOptions, callback: DeleteCallback): void; + delete(callback: DeleteCallback): void; + delete( + optionsOrCallback?: DeleteOptions | DeleteCallback, + cb?: DeleteCallback, + ): Promise<[r.Response]> | void { + const [options, callback] = util.maybeOptionsOrCallback< + DeleteOptions, + DeleteCallback + >(optionsOrCallback, cb); + + const ignoreNotFound = options.ignoreNotFound!; + delete options.ignoreNotFound; + + const methodConfig = + (typeof this.methods.delete === 'object' && this.methods.delete) || {}; + + const reqOpts = { + method: 'DELETE', + uri: '', + ...methodConfig.reqOpts, + qs: { + ...methodConfig.reqOpts?.qs, + ...options, + }, + }; + + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call( + this, + reqOpts, + (err: ApiError | null, body?: ResponseBody, res?: r.Response) => { + if (err) { + if (err.code === 404 && ignoreNotFound) { + err = null; + } + } + callback(err, res); + }, + ); + } + + /** + * Check if the object exists. + * + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {boolean} callback.exists - Whether the object exists or not. + */ + exists(options?: ExistsOptions): Promise<[boolean]>; + exists(options: ExistsOptions, callback: ExistsCallback): void; + exists(callback: ExistsCallback): void; + exists( + optionsOrCallback?: ExistsOptions | ExistsCallback, + cb?: ExistsCallback, + ): void | Promise<[boolean]> { + const [options, callback] = util.maybeOptionsOrCallback< + ExistsOptions, + ExistsCallback + >(optionsOrCallback, cb); + + this.get(options, err => { + if (err) { + if (err.code === 404) { + callback!(null, false); + } else { + callback!(err); + } + return; + } + callback!(null, true); + }); + } + + /** + * Get the object if it exists. Optionally have the object created if an + * options object is provided with `autoCreate: true`. + * + * @param {object=} options - The configuration object that will be used to + * create the object if necessary. + * @param {boolean} options.autoCreate - Create the object if it doesn't already exist. + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.instance - The instance. + * @param {object} callback.apiResponse - The full API response. + */ + get(options?: GetOrCreateOptions): Promise>; + get(callback: InstanceResponseCallback): void; + get(options: GetOrCreateOptions, callback: InstanceResponseCallback): void; + get( + optionsOrCallback?: GetOrCreateOptions | InstanceResponseCallback, + cb?: InstanceResponseCallback, + ): Promise> | void { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const self = this; + + const [opts, callback] = util.maybeOptionsOrCallback< + GetOrCreateOptions, + InstanceResponseCallback + >(optionsOrCallback, cb); + const options = Object.assign({}, opts); + + const autoCreate = options.autoCreate && typeof this.create === 'function'; + delete options.autoCreate; + + function onCreate( + err: ApiError | null, + instance: T, + apiResponse: r.Response, + ) { + if (err) { + if (err.code === 409) { + self.get(options, callback!); + return; + } + callback!(err, null, apiResponse); + return; + } + callback!(null, instance, apiResponse); + } + + this.getMetadata(options, (err: ApiError | null, metadata) => { + if (err) { + if (err.code === 404 && autoCreate) { + const args: Array = []; + if (Object.keys(options).length > 0) { + args.push(options); + } + args.push(onCreate); + self.create(...args); + return; + } + callback!(err, null, metadata as unknown as r.Response); + return; + } + callback!(null, self as {} as T, metadata as unknown as r.Response); + }); + } + + /** + * Get the metadata of this object. + * + * @param {function} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.metadata - The metadata for this object. + * @param {object} callback.apiResponse - The full API response. + */ + getMetadata(options?: GetMetadataOptions): Promise>; + getMetadata(options: GetMetadataOptions, callback: MetadataCallback): void; + getMetadata(callback: MetadataCallback): void; + getMetadata( + optionsOrCallback: GetMetadataOptions | MetadataCallback, + cb?: MetadataCallback, + ): Promise> | void { + const [options, callback] = util.maybeOptionsOrCallback< + GetMetadataOptions, + MetadataCallback + >(optionsOrCallback, cb); + + const methodConfig = + (typeof this.methods.getMetadata === 'object' && + this.methods.getMetadata) || + {}; + const reqOpts = { + uri: '', + ...methodConfig.reqOpts, + qs: { + ...methodConfig.reqOpts?.qs, + ...options, + }, + }; + + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call( + this, + reqOpts, + (err: Error | null, body?: ResponseBody, res?: r.Response) => { + this.metadata = body; + callback!(err, this.metadata, res); + }, + ); + } + + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors(): Function[] { + // Interceptors should be returned in the order they were assigned. + const localInterceptors = this.interceptors + .filter(interceptor => typeof interceptor.request === 'function') + .map(interceptor => interceptor.request); + return this.parent.getRequestInterceptors().concat(localInterceptors); + } + + /** + * Set the metadata for this object. + * + * @param {object} metadata - The metadata to set on this object. + * @param {object=} options - Configuration options. + * @param {function=} callback - The callback function. + * @param {?error} callback.err - An error returned while making this request. + * @param {object} callback.apiResponse - The full API response. + */ + setMetadata( + metadata: K, + options?: SetMetadataOptions, + ): Promise>; + setMetadata(metadata: K, callback: MetadataCallback): void; + setMetadata( + metadata: K, + options: SetMetadataOptions, + callback: MetadataCallback, + ): void; + setMetadata( + metadata: K, + optionsOrCallback: SetMetadataOptions | MetadataCallback, + cb?: MetadataCallback, + ): Promise> | void { + const [options, callback] = util.maybeOptionsOrCallback< + SetMetadataOptions, + MetadataCallback + >(optionsOrCallback, cb); + const methodConfig = + (typeof this.methods.setMetadata === 'object' && + this.methods.setMetadata) || + {}; + + const reqOpts = { + method: 'PATCH', + uri: '', + ...methodConfig.reqOpts, + json: { + ...methodConfig.reqOpts?.json, + ...metadata, + }, + qs: { + ...methodConfig.reqOpts?.qs, + ...options, + }, + }; + + // The `request` method may have been overridden to hold any special + // behavior. Ensure we call the original `request` method. + ServiceObject.prototype.request.call( + this, + reqOpts, + (err: Error | null, body?: ResponseBody, res?: r.Response) => { + this.metadata = body; + callback!(err, this.metadata, res); + }, + ); + } + + /** + * Make an authenticated API request. + * + * @private + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + private request_(reqOpts: StreamRequestOptions): r.Request; + private request_( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void; + private request_( + reqOpts: DecorateRequestOptions | StreamRequestOptions, + callback?: BodyResponseCallback, + ): void | r.Request { + reqOpts = {...reqOpts}; + + if (this.projectId) { + reqOpts.projectId = this.projectId; + } + + const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; + const uriComponents = [this.baseUrl, this.id || '', reqOpts.uri]; + + if (isAbsoluteUrl) { + uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri)); + } + + reqOpts.uri = uriComponents + .filter(x => x!.trim()) // Limit to non-empty strings. + .map(uriComponent => { + const trimSlashesRegex = /^\/*|\/*$/g; + return uriComponent!.replace(trimSlashesRegex, ''); + }) + .join('/'); + + const childInterceptors = Array.isArray(reqOpts.interceptors_) + ? reqOpts.interceptors_ + : []; + const localInterceptors = [].slice.call(this.interceptors); + + reqOpts.interceptors_ = childInterceptors.concat(localInterceptors); + + if (reqOpts.shouldReturnStream) { + return this.parent.requestStream(reqOpts); + } + this.parent.request(reqOpts, callback!); + } + + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + request(reqOpts: DecorateRequestOptions): Promise; + request( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void; + request( + reqOpts: DecorateRequestOptions, + callback?: BodyResponseCallback, + ): void | Promise { + this.request_(reqOpts, callback!); + } + + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts: DecorateRequestOptions): r.Request { + const opts = {...reqOpts, shouldReturnStream: true}; + return this.request_(opts as StreamRequestOptions); + } +} + +promisifyAll(ServiceObject, {exclude: ['getRequestInterceptors']}); + +export {ServiceObject}; diff --git a/handwritten/storage/src/nodejs-common/service.ts b/handwritten/storage/src/nodejs-common/service.ts new file mode 100644 index 00000000000..6e2a6cb9078 --- /dev/null +++ b/handwritten/storage/src/nodejs-common/service.ts @@ -0,0 +1,316 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 { + AuthClient, + DEFAULT_UNIVERSE, + GoogleAuth, + GoogleAuthOptions, +} from 'google-auth-library'; +import * as r from 'teeny-request'; +import * as uuid from 'uuid'; + +import {Interceptor} from './service-object.js'; +import { + BodyResponseCallback, + DecorateRequestOptions, + GCCL_GCS_CMD_KEY, + MakeAuthenticatedRequest, + PackageJson, + util, +} from './util.js'; +import { + getRuntimeTrackingString, + getUserAgentString, + getModuleFormat, +} from '../util.js'; + +export const DEFAULT_PROJECT_ID_TOKEN = '{{projectId}}'; + +export interface StreamRequestOptions extends DecorateRequestOptions { + shouldReturnStream: true; +} + +export interface ServiceConfig { + /** + * The base URL to make API requests to. + */ + baseUrl: string; + + /** + * The API Endpoint to use when connecting to the service. + * Example: storage.googleapis.com + */ + apiEndpoint: string; + + /** + * The scopes required for the request. + */ + scopes: string[]; + + projectIdRequired?: boolean; + packageJson: PackageJson; + + /** + * Reuse an existing `AuthClient` or `GoogleAuth` client instead of creating a new one. + */ + authClient?: AuthClient | GoogleAuth; + + /** + * Set to true if the endpoint is a custom URL + */ + customEndpoint?: boolean; + + /** + * Controls whether or not to use authentication when using a custom endpoint. + */ + useAuthWithCustomEndpoint?: boolean; +} + +export interface ServiceOptions extends Omit { + authClient?: AuthClient | GoogleAuth; + interceptors_?: Interceptor[]; + email?: string; + token?: string; + timeout?: number; // http.request.options.timeout + userAgent?: string; + useAuthWithCustomEndpoint?: boolean; +} + +export class Service { + baseUrl: string; + private globalInterceptors: Interceptor[]; + interceptors: Interceptor[]; + private packageJson: PackageJson; + projectId: string; + private projectIdRequired: boolean; + providedUserAgent?: string; + makeAuthenticatedRequest: MakeAuthenticatedRequest; + authClient: GoogleAuth; + apiEndpoint: string; + timeout?: number; + universeDomain: string; + customEndpoint: boolean; + useAuthWithCustomEndpoint?: boolean; + + /** + * Service is a base class, meant to be inherited from by a "service," like + * BigQuery or Storage. + * + * This handles making authenticated requests by exposing a `makeReq_` + * function. + * + * @constructor + * @alias module:common/service + * + * @param {object} config - Configuration object. + * @param {string} config.baseUrl - The base URL to make API requests to. + * @param {string[]} config.scopes - The scopes required for the request. + * @param {object=} options - [Configuration object](#/docs). + */ + constructor(config: ServiceConfig, options: ServiceOptions = {}) { + this.baseUrl = config.baseUrl; + this.apiEndpoint = config.apiEndpoint; + this.timeout = options.timeout; + this.globalInterceptors = Array.isArray(options.interceptors_) + ? options.interceptors_ + : []; + this.interceptors = []; + this.packageJson = config.packageJson; + this.projectId = options.projectId || DEFAULT_PROJECT_ID_TOKEN; + this.projectIdRequired = config.projectIdRequired !== false; + this.providedUserAgent = options.userAgent; + this.universeDomain = options.universeDomain || DEFAULT_UNIVERSE; + this.customEndpoint = config.customEndpoint || false; + this.useAuthWithCustomEndpoint = config.useAuthWithCustomEndpoint; + + this.makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory({ + ...config, + projectIdRequired: this.projectIdRequired, + projectId: this.projectId, + authClient: options.authClient || config.authClient, + credentials: options.credentials, + keyFile: options.keyFilename, + email: options.email, + clientOptions: { + universeDomain: options.universeDomain, + ...options.clientOptions, + }, + }); + this.authClient = this.makeAuthenticatedRequest.authClient; + + const isCloudFunctionEnv = !!process.env.FUNCTION_NAME; + + if (isCloudFunctionEnv) { + this.interceptors.push({ + request(reqOpts: DecorateRequestOptions) { + reqOpts.forever = false; + return reqOpts; + }, + }); + } + } + + /** + * Return the user's custom request interceptors. + */ + getRequestInterceptors(): Function[] { + // Interceptors should be returned in the order they were assigned. + return ([] as Interceptor[]).slice + .call(this.globalInterceptors) + .concat(this.interceptors) + .filter(interceptor => typeof interceptor.request === 'function') + .map(interceptor => interceptor.request); + } + + /** + * Get and update the Service's project ID. + * + * @param {function} callback - The callback function. + */ + getProjectId(): Promise; + getProjectId(callback: (err: Error | null, projectId?: string) => void): void; + getProjectId( + callback?: (err: Error | null, projectId?: string) => void, + ): Promise | void { + if (!callback) { + return this.getProjectIdAsync(); + } + this.getProjectIdAsync().then(p => callback(null, p), callback); + } + + protected async getProjectIdAsync(): Promise { + const projectId = await this.authClient.getProjectId(); + if (this.projectId === DEFAULT_PROJECT_ID_TOKEN && projectId) { + this.projectId = projectId; + } + return this.projectId; + } + + /** + * Make an authenticated API request. + * + * @private + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + private request_(reqOpts: StreamRequestOptions): r.Request; + private request_( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void; + private request_( + reqOpts: DecorateRequestOptions | StreamRequestOptions, + callback?: BodyResponseCallback, + ): void | r.Request { + reqOpts = {...reqOpts, timeout: this.timeout}; + const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0; + const uriComponents = [this.baseUrl]; + + if (this.projectIdRequired) { + if (reqOpts.projectId) { + uriComponents.push('projects'); + uriComponents.push(reqOpts.projectId); + } else { + uriComponents.push('projects'); + uriComponents.push(this.projectId); + } + } + + uriComponents.push(reqOpts.uri); + + if (isAbsoluteUrl) { + uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri)); + } + + reqOpts.uri = uriComponents + .map(uriComponent => { + const trimSlashesRegex = /^\/*|\/*$/g; + return uriComponent.replace(trimSlashesRegex, ''); + }) + .join('/') + // Some URIs have colon separators. + // Bad: https://.../projects/:list + // Good: https://.../projects:list + .replace(/\/:/g, ':'); + + const requestInterceptors = this.getRequestInterceptors(); + const interceptorArray = Array.isArray(reqOpts.interceptors_) + ? reqOpts.interceptors_ + : []; + interceptorArray.forEach(interceptor => { + if (typeof interceptor.request === 'function') { + requestInterceptors.push(interceptor.request); + } + }); + + requestInterceptors.forEach(requestInterceptor => { + reqOpts = requestInterceptor(reqOpts); + }); + + delete reqOpts.interceptors_; + + const pkg = this.packageJson; + let userAgent = getUserAgentString(); + if (this.providedUserAgent) { + userAgent = `${this.providedUserAgent} ${userAgent}`; + } + reqOpts.headers = { + ...reqOpts.headers, + 'User-Agent': userAgent, + 'x-goog-api-client': `${getRuntimeTrackingString()} gccl/${ + pkg.version + }-${getModuleFormat()} gccl-invocation-id/${uuid.v4()}`, + }; + + if (reqOpts[GCCL_GCS_CMD_KEY]) { + reqOpts.headers['x-goog-api-client'] += + ` gccl-gcs-cmd/${reqOpts[GCCL_GCS_CMD_KEY]}`; + } + + if (reqOpts.shouldReturnStream) { + return this.makeAuthenticatedRequest(reqOpts) as {} as r.Request; + } else { + this.makeAuthenticatedRequest(reqOpts, callback); + } + } + + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + * @param {function} callback - The callback function passed to `request`. + */ + request( + reqOpts: DecorateRequestOptions, + callback: BodyResponseCallback, + ): void { + Service.prototype.request_.call(this, reqOpts, callback); + } + + /** + * Make an authenticated API request. + * + * @param {object} reqOpts - Request options that are passed to `request`. + * @param {string} reqOpts.uri - A URI relative to the baseUrl. + */ + requestStream(reqOpts: DecorateRequestOptions): r.Request { + const opts = {...reqOpts, shouldReturnStream: true}; + return (Service.prototype.request_ as Function).call(this, opts); + } +} diff --git a/handwritten/storage/src/nodejs-common/util.ts b/handwritten/storage/src/nodejs-common/util.ts new file mode 100644 index 00000000000..9ba3051add3 --- /dev/null +++ b/handwritten/storage/src/nodejs-common/util.ts @@ -0,0 +1,1058 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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. + */ + +/*! + * @module common/util + */ + +import { + replaceProjectIdToken, + MissingProjectIdError, +} from '@google-cloud/projectify'; +import * as htmlEntities from 'html-entities'; +import {AuthClient, GoogleAuth, GoogleAuthOptions} from 'google-auth-library'; +import {CredentialBody} from 'google-auth-library'; +import * as r from 'teeny-request'; +import retryRequest from 'retry-request'; +import {Duplex, DuplexOptions, Readable, Transform, Writable} from 'stream'; +import {teenyRequest} from 'teeny-request'; +import {Interceptor} from './service-object.js'; +import * as uuid from 'uuid'; +import {DEFAULT_PROJECT_ID_TOKEN} from './service.js'; +import { + getModuleFormat, + getRuntimeTrackingString, + getUserAgentString, +} from '../util.js'; +import duplexify from 'duplexify'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import {getPackageJSON} from '../package-json-helper.cjs'; + +const packageJson = getPackageJSON(); + +/** + * A unique symbol for providing a `gccl-gcs-cmd` value + * for the `X-Goog-API-Client` header. + * + * E.g. the `V` in `X-Goog-API-Client: gccl-gcs-cmd/V` + **/ +export const GCCL_GCS_CMD_KEY = Symbol.for('GCCL_GCS_CMD'); + +const requestDefaults: r.CoreOptions = { + timeout: 60000, + gzip: true, + forever: true, + pool: { + maxSockets: Infinity, + }, +}; + +/** + * Default behavior: Automatically retry retriable server errors. + * + * @const {boolean} + * @private + */ +const AUTO_RETRY_DEFAULT = true; + +/** + * Default behavior: Only attempt to retry retriable errors 3 times. + * + * @const {number} + * @private + */ +const MAX_RETRY_DEFAULT = 3; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type ResponseBody = any; + +// Directly copy over Duplexify interfaces +export interface DuplexifyOptions extends DuplexOptions { + autoDestroy?: boolean; + end?: boolean; +} + +export interface Duplexify extends Duplex { + readonly destroyed: boolean; + setWritable(writable: Writable | false | null): void; + setReadable(readable: Readable | false | null): void; +} + +export interface DuplexifyConstructor { + obj( + writable?: Writable | false | null, + readable?: Readable | false | null, + options?: DuplexifyOptions, + ): Duplexify; + new ( + writable?: Writable | false | null, + readable?: Readable | false | null, + options?: DuplexifyOptions, + ): Duplexify; + ( + writable?: Writable | false | null, + readable?: Readable | false | null, + options?: DuplexifyOptions, + ): Duplexify; +} + +export interface ParsedHttpRespMessage { + resp: r.Response; + err?: ApiError; +} + +export interface MakeAuthenticatedRequest { + (reqOpts: DecorateRequestOptions): Duplexify; + ( + reqOpts: DecorateRequestOptions, + options?: MakeAuthenticatedRequestOptions, + ): void | Abortable; + ( + reqOpts: DecorateRequestOptions, + callback?: BodyResponseCallback, + ): void | Abortable; + ( + reqOpts: DecorateRequestOptions, + optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback, + ): void | Abortable | Duplexify; + getCredentials: ( + callback: (err?: Error | null, credentials?: CredentialBody) => void, + ) => void; + authClient: GoogleAuth; +} + +export interface Abortable { + abort(): void; +} +export type AbortableDuplex = Duplexify & Abortable; + +export interface PackageJson { + name: string; + version: string; +} + +export interface MakeAuthenticatedRequestFactoryConfig + extends Omit { + /** + * Automatically retry requests if the response is related to rate limits or + * certain intermittent server errors. We will exponentially backoff + * subsequent requests by default. (default: true) + */ + autoRetry?: boolean; + + /** + * If true, just return the provided request options. Default: false. + */ + customEndpoint?: boolean; + + /** + * If true, will authenticate when using a custom endpoint. Default: false. + */ + useAuthWithCustomEndpoint?: boolean; + + /** + * Account email address, required for PEM/P12 usage. + */ + email?: string; + + /** + * Maximum number of automatic retries attempted before returning the error. + * (default: 3) + */ + maxRetries?: number; + + stream?: Duplexify; + + /** + * A pre-instantiated `AuthClient` or `GoogleAuth` client that should be used. + * A new client will be created if this is not set. + */ + authClient?: AuthClient | GoogleAuth; + + /** + * Determines if a projectId is required for authenticated requests. Defaults to `true`. + */ + projectIdRequired?: boolean; +} + +export interface MakeAuthenticatedRequestOptions { + onAuthenticated: OnAuthenticatedCallback; +} + +export interface OnAuthenticatedCallback { + (err: Error | null, reqOpts?: DecorateRequestOptions): void; +} + +export interface GoogleErrorBody { + code: number; + errors?: GoogleInnerError[]; + response: r.Response; + message?: string; +} + +export interface GoogleInnerError { + reason?: string; + message?: string; +} + +export interface MakeWritableStreamOptions { + /** + * A connection instance used to get a token with and send the request + * through. + */ + connection?: {}; + + /** + * Metadata to send at the head of the request. + */ + metadata?: {contentType?: string}; + + /** + * Request object, in the format of a standard Node.js http.request() object. + */ + request?: r.Options; + + makeAuthenticatedRequest( + reqOpts: r.OptionsWithUri & { + [GCCL_GCS_CMD_KEY]?: string; + }, + fnobj: { + onAuthenticated( + err: Error | null, + authenticatedReqOpts?: r.Options, + ): void; + }, + ): void; +} + +export interface DecorateRequestOptions extends r.CoreOptions { + autoPaginate?: boolean; + autoPaginateVal?: boolean; + objectMode?: boolean; + maxRetries?: number; + uri: string; + interceptors_?: Interceptor[]; + shouldReturnStream?: boolean; + projectId?: string; + [GCCL_GCS_CMD_KEY]?: string; +} + +export interface ParsedHttpResponseBody { + body: ResponseBody; + err?: Error; +} + +/** + * Custom error type for API errors. + * + * @param {object} errorBody - Error object. + */ +export class ApiError extends Error { + code?: number; + errors?: GoogleInnerError[]; + response?: r.Response; + constructor(errorMessage: string); + constructor(errorBody: GoogleErrorBody); + constructor(errorBodyOrMessage?: GoogleErrorBody | string) { + super(); + if (typeof errorBodyOrMessage !== 'object') { + this.message = errorBodyOrMessage || ''; + return; + } + const errorBody = errorBodyOrMessage; + + this.code = errorBody.code; + this.errors = errorBody.errors; + this.response = errorBody.response; + + try { + this.errors = JSON.parse(this.response.body).error.errors; + } catch (e) { + this.errors = errorBody.errors; + } + + this.message = ApiError.createMultiErrorMessage(errorBody, this.errors); + Error.captureStackTrace(this); + } + /** + * Pieces together an error message by combining all unique error messages + * returned from a single GoogleError + * + * @private + * + * @param {GoogleErrorBody} err The original error. + * @param {GoogleInnerError[]} [errors] Inner errors, if any. + * @returns {string} + */ + static createMultiErrorMessage( + err: GoogleErrorBody, + errors?: GoogleInnerError[], + ): string { + const messages: Set = new Set(); + + if (err.message) { + messages.add(err.message); + } + + if (errors && errors.length) { + errors.forEach(({message}) => messages.add(message!)); + } else if (err.response && err.response.body) { + messages.add(htmlEntities.decode(err.response.body.toString())); + } else if (!err.message) { + messages.add('A failure occurred during this request.'); + } + + let messageArr: string[] = Array.from(messages); + + if (messageArr.length > 1) { + messageArr = messageArr.map((message, i) => ` ${i + 1}. ${message}`); + messageArr.unshift( + 'Multiple errors occurred during the request. Please see the `errors` array for complete details.\n', + ); + messageArr.push('\n'); + } + + return messageArr.join('\n'); + } +} + +/** + * Custom error type for partial errors returned from the API. + * + * @param {object} b - Error object. + */ +export class PartialFailureError extends Error { + errors?: GoogleInnerError[]; + response?: r.Response; + constructor(b: GoogleErrorBody) { + super(); + const errorObject = b; + + this.errors = errorObject.errors; + this.name = 'PartialFailureError'; + this.response = errorObject.response; + + this.message = ApiError.createMultiErrorMessage(errorObject, this.errors); + } +} + +export interface BodyResponseCallback { + (err: Error | ApiError | null, body?: ResponseBody, res?: r.Response): void; +} + +export interface RetryOptions { + retryDelayMultiplier?: number; + totalTimeout?: number; + maxRetryDelay?: number; + autoRetry?: boolean; + maxRetries?: number; + retryableErrorFn?: (err: ApiError) => boolean; +} + +export interface MakeRequestConfig { + /** + * Automatically retry requests if the response is related to rate limits or + * certain intermittent server errors. We will exponentially backoff + * subsequent requests by default. (default: true) + */ + autoRetry?: boolean; + + /** + * Maximum number of automatic retries attempted before returning the error. + * (default: 3) + */ + maxRetries?: number; + + retries?: number; + + retryOptions?: RetryOptions; + + stream?: Duplexify; + + shouldRetryFn?: (response?: r.Response) => boolean; +} + +export class Util { + ApiError = ApiError; + PartialFailureError = PartialFailureError; + + /** + * No op. + * + * @example + * function doSomething(callback) { + * callback = callback || noop; + * } + */ + noop() {} + + /** + * Uniformly process an API response. + * + * @param {*} err - Error value. + * @param {*} resp - Response value. + * @param {*} body - Body value. + * @param {function} callback - The callback function. + */ + handleResp( + err: Error | null, + resp?: r.Response | null, + body?: ResponseBody, + callback?: BodyResponseCallback, + ) { + callback = callback || util.noop; + + const parsedResp = { + err: err || null, + ...(resp && util.parseHttpRespMessage(resp)), + ...(body && util.parseHttpRespBody(body)), + }; + + // Assign the parsed body to resp.body, even if { json: false } was passed + // as a request option. + // We assume that nobody uses the previously unparsed value of resp.body. + if (!parsedResp.err && resp && typeof parsedResp.body === 'object') { + parsedResp.resp.body = parsedResp.body; + } + + if (parsedResp.err && resp) { + parsedResp.err.response = resp; + } + + callback(parsedResp.err, parsedResp.body, parsedResp.resp); + } + + /** + * Sniff an incoming HTTP response message for errors. + * + * @param {object} httpRespMessage - An incoming HTTP response message from `request`. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.resp - The original response object. + */ + parseHttpRespMessage(httpRespMessage: r.Response) { + const parsedHttpRespMessage = { + resp: httpRespMessage, + } as ParsedHttpRespMessage; + + if (httpRespMessage.statusCode < 200 || httpRespMessage.statusCode > 299) { + // Unknown error. Format according to ApiError standard. + parsedHttpRespMessage.err = new ApiError({ + errors: new Array(), + code: httpRespMessage.statusCode, + message: httpRespMessage.statusMessage, + response: httpRespMessage, + }); + } + + return parsedHttpRespMessage; + } + + /** + * Parse the response body from an HTTP request. + * + * @param {object} body - The response body. + * @return {object} parsedHttpRespMessage - The parsed response. + * @param {?error} parsedHttpRespMessage.err - An error detected. + * @param {object} parsedHttpRespMessage.body - The original body value provided + * will try to be JSON.parse'd. If it's successful, the parsed value will + * be returned here, otherwise the original value and an error will be returned. + */ + parseHttpRespBody(body: ResponseBody) { + const parsedHttpRespBody: ParsedHttpResponseBody = { + body, + }; + + if (typeof body === 'string') { + try { + parsedHttpRespBody.body = JSON.parse(body); + } catch (err) { + parsedHttpRespBody.body = body; + } + } + + if (parsedHttpRespBody.body && parsedHttpRespBody.body.error) { + // Error from JSON API. + parsedHttpRespBody.err = new ApiError(parsedHttpRespBody.body.error); + } + + return parsedHttpRespBody; + } + + /** + * Take a Duplexify stream, fetch an authenticated connection header, and + * create an outgoing writable stream. + * + * @param {Duplexify} dup - Duplexify stream. + * @param {object} options - Configuration object. + * @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through. + * @param {object} options.metadata - Metadata to send at the head of the request. + * @param {object} options.request - Request object, in the format of a standard Node.js http.request() object. + * @param {string=} options.request.method - Default: "POST". + * @param {string=} options.request.qs.uploadType - Default: "multipart". + * @param {string=} options.streamContentType - Default: "application/octet-stream". + * @param {function} onComplete - Callback, executed after the writable Request stream has completed. + */ + makeWritableStream( + dup: Duplexify, + options: MakeWritableStreamOptions, + onComplete?: Function, + ) { + onComplete = onComplete || util.noop; + + const writeStream = new ProgressStream(); + writeStream.on('progress', evt => dup.emit('progress', evt)); + dup.setWritable(writeStream); + + const defaultReqOpts = { + method: 'POST', + qs: { + uploadType: 'multipart', + }, + timeout: 0, + maxRetries: 0, + }; + + const metadata = options.metadata || {}; + + const reqOpts = { + ...defaultReqOpts, + ...options.request, + qs: { + ...defaultReqOpts.qs, + ...options.request?.qs, + }, + multipart: [ + { + 'Content-Type': 'application/json', + body: JSON.stringify(metadata), + }, + { + 'Content-Type': metadata.contentType || 'application/octet-stream', + body: writeStream, + }, + ], + } as {} as r.OptionsWithUri & { + [GCCL_GCS_CMD_KEY]?: string; + }; + + options.makeAuthenticatedRequest(reqOpts, { + onAuthenticated(err, authenticatedReqOpts) { + if (err) { + dup.destroy(err); + return; + } + + requestDefaults.headers = util._getDefaultHeaders( + reqOpts[GCCL_GCS_CMD_KEY], + ); + const request = teenyRequest.defaults(requestDefaults); + request(authenticatedReqOpts!, (err, resp, body) => { + util.handleResp(err, resp, body, (err, data) => { + if (err) { + dup.destroy(err); + return; + } + dup.emit('response', resp); + onComplete!(data); + }); + }); + }, + }); + } + + /** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. This is used for rate limit + * related errors as well as intermittent server errors. + * + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ + shouldRetryRequest(err?: ApiError) { + if (err) { + if ([408, 429, 500, 502, 503, 504].indexOf(err.code!) !== -1) { + return true; + } + + if (err.errors) { + for (const e of err.errors) { + const reason = e.reason; + if (reason === 'rateLimitExceeded') { + return true; + } + if (reason === 'userRateLimitExceeded') { + return true; + } + if (reason && reason.includes('EAI_AGAIN')) { + return true; + } + } + } + } + + return false; + } + + /** + * Get a function for making authenticated requests. + * + * @param {object} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {object=} config.credentials - Credentials object. + * @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false. + * @param {boolean=} config.useAuthWithCustomEndpoint - If true, will authenticate when using a custom endpoint. Default: false. + * @param {string=} config.email - Account email address, required for PEM/P12 usage. + * @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3) + * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile. + * @param {array} config.scopes - Array of scopes required for the API. + */ + makeAuthenticatedRequestFactory( + config: MakeAuthenticatedRequestFactoryConfig, + ) { + const googleAutoAuthConfig = {...config}; + if (googleAutoAuthConfig.projectId === DEFAULT_PROJECT_ID_TOKEN) { + delete googleAutoAuthConfig.projectId; + } + + let authClient: GoogleAuth; + + if (googleAutoAuthConfig.authClient instanceof GoogleAuth) { + // Use an existing `GoogleAuth` + authClient = googleAutoAuthConfig.authClient; + } else { + // Pass an `AuthClient` & `clientOptions` to `GoogleAuth`, if available + authClient = new GoogleAuth({ + ...googleAutoAuthConfig, + authClient: googleAutoAuthConfig.authClient, + clientOptions: googleAutoAuthConfig.clientOptions, + }); + } + + /** + * The returned function that will make an authenticated request. + * + * @param {type} reqOpts - Request options in the format `request` expects. + * @param {object|function} options - Configuration object or callback function. + * @param {function=} options.onAuthenticated - If provided, a request will + * not be made. Instead, this function is passed the error & + * authenticated request options. + */ + function makeAuthenticatedRequest( + reqOpts: DecorateRequestOptions, + ): Duplexify; + function makeAuthenticatedRequest( + reqOpts: DecorateRequestOptions, + options?: MakeAuthenticatedRequestOptions, + ): void | Abortable; + function makeAuthenticatedRequest( + reqOpts: DecorateRequestOptions, + callback?: BodyResponseCallback, + ): void | Abortable; + function makeAuthenticatedRequest( + reqOpts: DecorateRequestOptions, + optionsOrCallback?: + | MakeAuthenticatedRequestOptions + | BodyResponseCallback, + ): void | Abortable | Duplexify { + let stream: Duplexify; + let projectId: string; + const reqConfig = {...config}; + let activeRequest_: void | Abortable | null; + + if (!optionsOrCallback) { + stream = duplexify(); + reqConfig.stream = stream; + } + + const options = + typeof optionsOrCallback === 'object' ? optionsOrCallback : undefined; + const callback = + typeof optionsOrCallback === 'function' ? optionsOrCallback : undefined; + + async function setProjectId() { + projectId = await authClient.getProjectId(); + } + + const onAuthenticated = async ( + err: Error | null, + authenticatedReqOpts?: DecorateRequestOptions, + ) => { + const authLibraryError = err; + const autoAuthFailed = + err && + typeof err.message === 'string' && + err.message.indexOf('Could not load the default credentials') > -1; + + if (autoAuthFailed) { + // Even though authentication failed, the API might not actually + // care. + authenticatedReqOpts = reqOpts; + } + + if (!err || autoAuthFailed) { + try { + // Try with existing `projectId` value + authenticatedReqOpts = util.decorateRequest( + authenticatedReqOpts!, + projectId, + ); + + err = null; + } catch (e) { + if (e instanceof MissingProjectIdError) { + // A `projectId` was required, but we don't have one. + try { + // Attempt to get the `projectId` + await setProjectId(); + + authenticatedReqOpts = util.decorateRequest( + authenticatedReqOpts!, + projectId, + ); + + err = null; + } catch (e) { + // Re-use the "Could not load the default credentials error" if + // auto auth failed. + err = err || (e as Error); + } + } else { + // Some other error unrelated to missing `projectId` + err = err || (e as Error); + } + } + } + + if (err) { + if (stream) { + stream.destroy(err); + } else { + const fn = + options && options.onAuthenticated + ? options.onAuthenticated + : callback; + (fn as Function)(err); + } + return; + } + + if (options && options.onAuthenticated) { + options.onAuthenticated(null, authenticatedReqOpts); + } else { + activeRequest_ = util.makeRequest( + authenticatedReqOpts!, + reqConfig, + (apiResponseError, ...params) => { + if ( + apiResponseError && + (apiResponseError as ApiError).code === 401 && + authLibraryError + ) { + // Re-use the "Could not load the default credentials error" if + // the API request failed due to missing credentials. + apiResponseError = authLibraryError; + } + callback!(apiResponseError, ...params); + }, + ); + } + }; + + const prepareRequest = async () => { + try { + const getProjectId = async () => { + if ( + config.projectId && + config.projectId !== DEFAULT_PROJECT_ID_TOKEN + ) { + // The user provided a project ID. We don't need to check with the + // auth client, it could be incorrect. + return config.projectId; + } + + if (config.projectIdRequired === false) { + // A projectId is not required. Return the default. + return DEFAULT_PROJECT_ID_TOKEN; + } + + return setProjectId(); + }; + + const authorizeRequest = async () => { + if ( + reqConfig.customEndpoint && + !reqConfig.useAuthWithCustomEndpoint + ) { + // Using a custom API override. Do not use `google-auth-library` for + // authentication. (ex: connecting to a local Datastore server) + return reqOpts; + } else { + return authClient.authorizeRequest(reqOpts); + } + }; + + const [_projectId, authorizedReqOpts] = await Promise.all([ + getProjectId(), + authorizeRequest(), + ]); + + if (_projectId) { + projectId = _projectId; + } + + return onAuthenticated( + null, + authorizedReqOpts as DecorateRequestOptions, + ); + } catch (e) { + return onAuthenticated(e as Error); + } + }; + + prepareRequest(); + + if (stream!) { + return stream!; + } + + return { + abort() { + setImmediate(() => { + if (activeRequest_) { + activeRequest_.abort(); + activeRequest_ = null; + } + }); + }, + }; + } + const mar = makeAuthenticatedRequest as MakeAuthenticatedRequest; + mar.getCredentials = authClient.getCredentials.bind(authClient); + mar.authClient = authClient; + return mar; + } + + /** + * Make a request through the `retryRequest` module with built-in error + * handling and exponential back off. + * + * @param {object} reqOpts - Request options in the format `request` expects. + * @param {object=} config - Configuration object. + * @param {boolean=} config.autoRetry - Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * (default: true) + * @param {number=} config.maxRetries - Maximum number of automatic retries + * attempted before returning the error. (default: 3) + * @param {object=} config.request - HTTP module for request calls. + * @param {function} callback - The callback function. + */ + makeRequest( + reqOpts: DecorateRequestOptions, + config: MakeRequestConfig, + callback: BodyResponseCallback, + ): void | Abortable { + let autoRetryValue = AUTO_RETRY_DEFAULT; + if (config.autoRetry !== undefined) { + autoRetryValue = config.autoRetry; + } else if (config.retryOptions?.autoRetry !== undefined) { + autoRetryValue = config.retryOptions.autoRetry; + } + + let maxRetryValue = MAX_RETRY_DEFAULT; + if (config.maxRetries !== undefined) { + maxRetryValue = config.maxRetries; + } else if (config.retryOptions?.maxRetries !== undefined) { + maxRetryValue = config.retryOptions.maxRetries; + } + + requestDefaults.headers = this._getDefaultHeaders( + reqOpts[GCCL_GCS_CMD_KEY], + ); + const options = { + request: teenyRequest.defaults(requestDefaults), + retries: autoRetryValue !== false ? maxRetryValue : 0, + noResponseRetries: autoRetryValue !== false ? maxRetryValue : 0, + shouldRetryFn(httpRespMessage: r.Response) { + const err = util.parseHttpRespMessage(httpRespMessage).err; + if (config.retryOptions?.retryableErrorFn) { + return err && config.retryOptions?.retryableErrorFn(err); + } + return err && util.shouldRetryRequest(err); + }, + maxRetryDelay: config.retryOptions?.maxRetryDelay, + retryDelayMultiplier: config.retryOptions?.retryDelayMultiplier, + totalTimeout: config.retryOptions?.totalTimeout, + } as {} as retryRequest.Options; + + if (typeof reqOpts.maxRetries === 'number') { + options.retries = reqOpts.maxRetries; + options.noResponseRetries = reqOpts.maxRetries; + } + + if (!config.stream) { + return retryRequest( + reqOpts, + options, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (err: Error | null, response: {}, body: any) => { + util.handleResp(err, response as {} as r.Response, body, callback!); + }, + ); + } + const dup = config.stream as AbortableDuplex; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let requestStream: any; + const isGetRequest = (reqOpts.method || 'GET').toUpperCase() === 'GET'; + + if (isGetRequest) { + requestStream = retryRequest(reqOpts, options); + dup.setReadable(requestStream); + } else { + // Streaming writable HTTP requests cannot be retried. + requestStream = (options.request as unknown as Function)!(reqOpts); + dup.setWritable(requestStream); + } + + // Replay the Request events back to the stream. + requestStream + .on('error', dup.destroy.bind(dup)) + .on('response', dup.emit.bind(dup, 'response')) + .on('complete', dup.emit.bind(dup, 'complete')); + + dup.abort = requestStream.abort; + return dup; + } + + /** + * Decorate the options about to be made in a request. + * + * @param {object} reqOpts - The options to be passed to `request`. + * @param {string} projectId - The project ID. + * @return {object} reqOpts - The decorated reqOpts. + */ + decorateRequest(reqOpts: DecorateRequestOptions, projectId: string) { + delete reqOpts.autoPaginate; + delete reqOpts.autoPaginateVal; + delete reqOpts.objectMode; + + if (reqOpts.qs !== null && typeof reqOpts.qs === 'object') { + delete reqOpts.qs.autoPaginate; + delete reqOpts.qs.autoPaginateVal; + reqOpts.qs = replaceProjectIdToken(reqOpts.qs, projectId); + } + + if (Array.isArray(reqOpts.multipart)) { + reqOpts.multipart = (reqOpts.multipart as []).map(part => { + return replaceProjectIdToken(part, projectId); + }); + } + + if (reqOpts.json !== null && typeof reqOpts.json === 'object') { + delete reqOpts.json.autoPaginate; + delete reqOpts.json.autoPaginateVal; + reqOpts.json = replaceProjectIdToken(reqOpts.json, projectId); + } + + reqOpts.uri = replaceProjectIdToken(reqOpts.uri, projectId); + + return reqOpts; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + isCustomType(unknown: any, module: string) { + function getConstructorName(obj: Function) { + return obj.constructor && obj.constructor.name.toLowerCase(); + } + + const moduleNameParts = module.split('/'); + + const parentModuleName = + moduleNameParts[0] && moduleNameParts[0].toLowerCase(); + const subModuleName = + moduleNameParts[1] && moduleNameParts[1].toLowerCase(); + + if (subModuleName && getConstructorName(unknown) !== subModuleName) { + return false; + } + + let walkingModule = unknown; + // eslint-disable-next-line no-constant-condition + while (true) { + if (getConstructorName(walkingModule) === parentModuleName) { + return true; + } + walkingModule = walkingModule.parent; + if (!walkingModule) { + return false; + } + } + } + + /** + * Given two parameters, figure out if this is either: + * - Just a callback function + * - An options object, and then a callback function + * @param optionsOrCallback An options object or callback. + * @param cb A potentially undefined callback. + */ + maybeOptionsOrCallback void>( + optionsOrCallback?: T | C, + cb?: C, + ): [T, C] { + return typeof optionsOrCallback === 'function' + ? [{} as T, optionsOrCallback as C] + : [optionsOrCallback as T, cb as C]; + } + + _getDefaultHeaders(gcclGcsCmd?: string) { + const headers = { + 'User-Agent': getUserAgentString(), + 'x-goog-api-client': `${getRuntimeTrackingString()} gccl/${ + packageJson.version + }-${getModuleFormat()} gccl-invocation-id/${uuid.v4()}`, + }; + + if (gcclGcsCmd) { + headers['x-goog-api-client'] += ` gccl-gcs-cmd/${gcclGcsCmd}`; + } + + return headers; + } +} + +/** + * Basic Passthrough Stream that records the number of bytes read + * every time the cursor is moved. + */ +class ProgressStream extends Transform { + bytesRead = 0; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _transform(chunk: any, encoding: string, callback: Function) { + this.bytesRead += chunk.length; + this.emit('progress', {bytesWritten: this.bytesRead, contentLength: '*'}); + this.push(chunk); + callback(); + } +} + +const util = new Util(); +export {util}; diff --git a/handwritten/storage/src/notification.ts b/handwritten/storage/src/notification.ts new file mode 100644 index 00000000000..95b2e081188 --- /dev/null +++ b/handwritten/storage/src/notification.ts @@ -0,0 +1,362 @@ +// Copyright 2019 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 {BaseMetadata, ServiceObject} from './nodejs-common/index.js'; +import {ResponseBody} from './nodejs-common/util.js'; +import {promisifyAll} from '@google-cloud/promisify'; + +import {Bucket} from './bucket.js'; + +export interface DeleteNotificationOptions { + userProject?: string; +} + +export interface GetNotificationMetadataOptions { + userProject?: string; +} + +/** + * @typedef {array} GetNotificationMetadataResponse + * @property {object} 0 The notification metadata. + * @property {object} 1 The full API response. + */ +export type GetNotificationMetadataResponse = [ResponseBody, unknown]; + +/** + * @callback GetNotificationMetadataCallback + * @param {?Error} err Request error, if any. + * @param {object} files The notification metadata. + * @param {object} apiResponse The full API response. + */ +export interface GetNotificationMetadataCallback { + (err: Error | null, metadata?: ResponseBody, apiResponse?: unknown): void; +} + +/** + * @typedef {array} GetNotificationResponse + * @property {Notification} 0 The {@link Notification} + * @property {object} 1 The full API response. + */ +export type GetNotificationResponse = [Notification, unknown]; + +export interface GetNotificationOptions { + /** + * Automatically create the object if it does not exist. Default: `false`. + */ + autoCreate?: boolean; + + /** + * The ID of the project which will be billed for the request. + */ + userProject?: string; +} + +/** + * @callback GetNotificationCallback + * @param {?Error} err Request error, if any. + * @param {Notification} notification The {@link Notification}. + * @param {object} apiResponse The full API response. + */ +export interface GetNotificationCallback { + ( + err: Error | null, + notification?: Notification | null, + apiResponse?: unknown, + ): void; +} + +/** + * @callback DeleteNotificationCallback + * @param {?Error} err Request error, if any. + * @param {object} apiResponse The full API response. + */ +export interface DeleteNotificationCallback { + (err: Error | null, apiResponse?: unknown): void; +} + +export interface NotificationMetadata extends BaseMetadata { + custom_attributes?: { + [key: string]: string; + }; + event_types?: string[]; + object_name_prefix?: string; + payload_format?: 'JSON_API_V1' | 'NONE'; + topic?: string; +} + +/** + * The API-formatted resource description of the notification. + * + * Note: This is not guaranteed to be up-to-date when accessed. To get the + * latest record, call the `getMetadata()` method. + * + * @name Notification#metadata + * @type {object} + */ +/** + * A Notification object is created from your {@link Bucket} object using + * {@link Bucket#notification}. Use it to interact with Cloud Pub/Sub + * notifications. + * + * See {@link https://cloud.google.com/storage/docs/pubsub-notifications| Cloud Pub/Sub Notifications for Google Cloud Storage} + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket The bucket instance this notification is attached to. + * @param {string} id The ID of the notification. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * + * const notification = myBucket.notification('1'); + * ``` + */ +class Notification extends ServiceObject { + constructor(bucket: Bucket, id: string) { + const requestQueryObject: { + ifGenerationMatch?: number; + ifGenerationNotMatch?: number; + ifMetagenerationMatch?: number; + ifMetagenerationNotMatch?: number; + } = {}; + + const methods = { + /** + * Creates a notification subscription for the bucket. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert} + * @method Notification#create + * + * @param {Topic|string} topic The Cloud PubSub topic to which this + * subscription publishes. If the project ID is omitted, the current + * project ID will be used. + * + * Acceptable formats are: + * - `projects/grape-spaceship-123/topics/my-topic` + * + * - `my-topic` + * @param {CreateNotificationRequest} [options] Metadata to set for + * the notification. + * @param {CreateNotificationCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a valid topic is not provided. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.create(function(err, notification, apiResponse) { + * if (!err) { + * // The notification was created successfully. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.create().then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + create: true, + + /** + * @typedef {array} DeleteNotificationResponse + * @property {object} 0 The full API response. + */ + /** + * Permanently deletes a notification subscription. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/delete| Notifications: delete API Documentation} + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {DeleteNotificationCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.delete(function(err, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.delete().then(function(data) { + * const apiResponse = data[0]; + * }); + * + * ``` + * @example + * region_tag:storage_delete_bucket_notification + * Another example: + */ + delete: { + reqOpts: { + qs: requestQueryObject, + }, + }, + + /** + * Get a notification and its metadata if it exists. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get| Notifications: get API Documentation} + * + * @param {object} [options] Configuration options. + * See {@link Bucket#createNotification} for create options. + * @param {boolean} [options.autoCreate] Automatically create the object if + * it does not exist. Default: `false`. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationCallback} [callback] Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.get(function(err, notification, apiResponse) { + * // `notification.metadata` has been populated. + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.get().then(function(data) { + * const notification = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ + get: { + reqOpts: { + qs: requestQueryObject, + }, + }, + + /** + * Get the notification's metadata. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/get| Notifications: get API Documentation} + * + * @param {object} [options] Configuration options. + * @param {string} [options.userProject] The ID of the project which will be + * billed for the request. + * @param {GetNotificationMetadataCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.getMetadata(function(err, metadata, apiResponse) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.getMetadata().then(function(data) { + * const metadata = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example + * region_tag:storage_print_pubsub_bucket_notification + * Another example: + */ + getMetadata: { + reqOpts: { + qs: requestQueryObject, + }, + }, + + /** + * @typedef {array} NotificationExistsResponse + * @property {boolean} 0 Whether the notification exists or not. + */ + /** + * @callback NotificationExistsCallback + * @param {?Error} err Request error, if any. + * @param {boolean} exists Whether the notification exists or not. + */ + /** + * Check if the notification exists. + * + * @method Notification#exists + * @param {NotificationExistsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const myBucket = storage.bucket('my-bucket'); + * const notification = myBucket.notification('1'); + * + * notification.exists(function(err, exists) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * notification.exists().then(function(data) { + * const exists = data[0]; + * }); + * ``` + */ + exists: true, + }; + + super({ + parent: bucket, + baseUrl: '/notificationConfigs', + id: id.toString(), + createMethod: bucket.createNotification.bind(bucket), + methods, + }); + } +} + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Notification); + +/** + * Reference to the {@link Notification} class. + * @name module:@google-cloud/storage.Notification + * @see Notification + */ +export {Notification}; diff --git a/handwritten/storage/src/package-json-helper.cjs b/handwritten/storage/src/package-json-helper.cjs new file mode 100644 index 00000000000..794923b5f96 --- /dev/null +++ b/handwritten/storage/src/package-json-helper.cjs @@ -0,0 +1,21 @@ +// Copyright 2023 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. + +/* eslint-disable node/no-missing-require */ + +function getPackageJSON() { + return require('../../../package.json'); +} + +exports.getPackageJSON = getPackageJSON; diff --git a/handwritten/storage/src/resumable-upload.ts b/handwritten/storage/src/resumable-upload.ts new file mode 100644 index 00000000000..af9e92a0cc2 --- /dev/null +++ b/handwritten/storage/src/resumable-upload.ts @@ -0,0 +1,1488 @@ +// Copyright 2022 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 AbortController from 'abort-controller'; +import {createHash} from 'crypto'; +import { + GaxiosOptions, + GaxiosPromise, + GaxiosResponse, + GaxiosError, +} from 'gaxios'; +import * as gaxios from 'gaxios'; +import { + DEFAULT_UNIVERSE, + GoogleAuth, + GoogleAuthOptions, +} from 'google-auth-library'; +import {Readable, Writable, WritableOptions} from 'stream'; +import AsyncRetry from 'async-retry'; +import {RetryOptions, PreconditionOptions} from './storage.js'; +import * as uuid from 'uuid'; +import { + getRuntimeTrackingString, + getModuleFormat, + getUserAgentString, +} from './util.js'; +import {GCCL_GCS_CMD_KEY} from './nodejs-common/util.js'; +import {FileExceptionMessages, FileMetadata, RequestError} from './file.js'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import {getPackageJSON} from './package-json-helper.cjs'; +import {HashStreamValidator} from './hash-stream-validator.js'; + +const NOT_FOUND_STATUS_CODE = 404; +const RESUMABLE_INCOMPLETE_STATUS_CODE = 308; +const packageJson = getPackageJSON(); + +export const PROTOCOL_REGEX = /^(\w*):\/\//; + +export interface ErrorWithCode extends Error { + code: number; + status?: number | string; +} + +export type CreateUriCallback = (err: Error | null, uri?: string) => void; +export interface Encryption { + key: {}; + hash: {}; +} + +export type PredefinedAcl = + | 'authenticatedRead' + | 'bucketOwnerFullControl' + | 'bucketOwnerRead' + | 'private' + | 'projectPrivate' + | 'publicRead'; + +export interface QueryParameters extends PreconditionOptions { + contentEncoding?: string; + kmsKeyName?: string; + predefinedAcl?: PredefinedAcl; + projection?: 'full' | 'noAcl'; + userProject?: string; +} + +export interface UploadConfig extends Pick { + /** + * The API endpoint used for the request. + * Defaults to `storage.googleapis.com`. + * + * **Warning**: + * If this value does not match the current GCP universe an emulator context + * will be assumed and authentication will be bypassed. + */ + apiEndpoint?: string; + + /** + * The name of the destination bucket. + */ + bucket: string; + + /** + * The name of the destination file. + */ + file: string; + + /** + * The GoogleAuthOptions passed to google-auth-library + */ + authConfig?: GoogleAuthOptions; + + /** + * If you want to re-use an auth client from google-auto-auth, pass an + * instance here. + * Defaults to GoogleAuth and gets automatically overridden if an + * emulator context is detected. + */ + authClient?: { + request: ( + opts: GaxiosOptions, + ) => Promise> | GaxiosPromise; + }; + + /** + * Create a separate request per chunk. + * + * This value is in bytes and should be a multiple of 256 KiB (2^18). + * We recommend using at least 8 MiB for the chunk size. + * + * @link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + */ + chunkSize?: number; + + /** + * For each API request we send, you may specify custom request options that + * we'll add onto the request. The request options follow the gaxios API: + * https://github.com/googleapis/gaxios#request-options. + */ + customRequestOptions?: GaxiosOptions; + + /** + * This will cause the upload to fail if the current generation of the remote + * object does not match the one provided here. + */ + generation?: number; + + /** + * Set to `true` if the upload is only a subset of the overall object to upload. + * This can be used when planning to continue the upload an object in another + * session. + * + * **Must be used with {@link UploadConfig.chunkSize} != `0`**. + * + * If this is a continuation of a previous upload, {@link UploadConfig.offset} + * should be set. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + */ + isPartialUpload?: boolean; + + clientCrc32c?: string; + clientMd5Hash?: string; + /** + * Enables CRC32C calculation on the client side. + * The calculated hash will be sent in the final PUT request if `clientCrc32c` is not provided. + */ + crc32c?: boolean; + /** + * Enables MD5 calculation on the client side. + * The calculated hash will be sent in the final PUT request if `clientMd5Hash` is not provided. + */ + md5?: boolean; + + /** + * A customer-supplied encryption key. See + * https://cloud.google.com/storage/docs/encryption#customer-supplied. + */ + key?: string | Buffer; + + /** + * Resource name of the Cloud KMS key, of the form + * `projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key`, + * that will be used to encrypt the object. Overrides the object metadata's + * `kms_key_name` value, if any. + */ + kmsKeyName?: string; + + /** + * Any metadata you wish to set on the object. + */ + metadata?: ConfigMetadata; + + /** + * The starting byte in relation to the final uploaded object. + * **Must be used with {@link UploadConfig.uri}**. + * + * If resuming an interrupted stream, do not supply this argument unless you + * know the exact number of bytes the service has AND the provided stream's + * first byte is a continuation from that provided offset. If resuming an + * interrupted stream and this option has not been provided, we will treat + * the provided upload stream as the object to upload - where the first byte + * of the upload stream is the first byte of the object to upload; skipping + * any bytes that are already present on the server. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + * @see {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload#resume-upload.} + */ + offset?: number; + + /** + * Set an Origin header when creating the resumable upload URI. + */ + origin?: string; + + /** + * Specify query parameters that go along with the initial upload request. See + * https://cloud.google.com/storage/docs/json_api/v1/objects/insert#parameters + */ + params?: QueryParameters; + + /** + * Apply a predefined set of access controls to the created file. + */ + predefinedAcl?: PredefinedAcl; + + /** + * Make the uploaded file private. (Alias for config.predefinedAcl = + * 'private') + */ + private?: boolean; + + /** + * Make the uploaded file public. (Alias for config.predefinedAcl = + * 'publicRead') + */ + public?: boolean; + + /** + * The service domain for a given Cloud universe. + */ + universeDomain?: string; + + /** + * If you already have a resumable URI from a previously-created resumable + * upload, just pass it in here and we'll use that. + * + * If resuming an interrupted stream and the {@link UploadConfig.offset} + * option has not been provided, we will treat the provided upload stream as + * the object to upload - where the first byte of the upload stream is the + * first byte of the object to upload; skipping any bytes that are already + * present on the server. + * + * @see {@link checkUploadStatus} for checking the status of an existing upload. + */ + uri?: string; + + /** + * If the bucket being accessed has requesterPays functionality enabled, this + * can be set to control which project is billed for the access of this file. + */ + userProject?: string; + + /** + * Configuration options for retrying retryable errors. + */ + retryOptions: RetryOptions; + + /** + * Controls whether or not to use authentication when using a custom endpoint. + */ + useAuthWithCustomEndpoint?: boolean; + + [GCCL_GCS_CMD_KEY]?: string; +} + +export interface ConfigMetadata { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any; + + /** + * Set the length of the object being uploaded. If uploading a partial + * object, this is the overall size of the finalized object. + */ + contentLength?: number; + + /** + * Set the content type of the incoming data. + */ + contentType?: string; +} + +export interface GoogleInnerError { + reason?: string; +} + +export interface ApiError extends Error { + code?: number; + errors?: GoogleInnerError[]; +} + +export interface CheckUploadStatusConfig { + /** + * Set to `false` to disable retries within this method. + * + * @defaultValue `true` + */ + retry?: boolean; +} + +export class Upload extends Writable { + bucket: string; + file: string; + apiEndpoint: string; + baseURI: string; + authConfig?: {scopes?: string[]}; + /* + * Defaults to GoogleAuth and gets automatically overridden if an + * emulator context is detected. + */ + authClient: { + request: ( + opts: GaxiosOptions, + ) => Promise> | GaxiosPromise; + }; + cacheKey: string; + chunkSize?: number; + customRequestOptions: GaxiosOptions; + generation?: number; + key?: string | Buffer; + kmsKeyName?: string; + metadata: ConfigMetadata; + offset?: number; + origin?: string; + params: QueryParameters; + predefinedAcl?: PredefinedAcl; + private?: boolean; + public?: boolean; + uri?: string; + userProject?: string; + encryption?: Encryption; + uriProvidedManually: boolean; + numBytesWritten = 0; + numRetries = 0; + contentLength: number | '*'; + retryOptions: RetryOptions; + timeOfFirstRequest: number; + isPartialUpload: boolean; + + private currentInvocationId = { + checkUploadStatus: uuid.v4(), + chunk: uuid.v4(), + uri: uuid.v4(), + }; + /** + * A cache of buffers written to this instance, ready for consuming + */ + private writeBuffers: Buffer[] = []; + private numChunksReadInRequest = 0; + + #hashValidator?: HashStreamValidator; + #clientCrc32c?: string; + #clientMd5Hash?: string; + + /** + * An array of buffers used for caching the most recent upload chunk. + * We should not assume that the server received all bytes sent in the request. + * - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + */ + private localWriteCache: Buffer[] = []; + private localWriteCacheByteLength = 0; + private upstreamEnded = false; + #gcclGcsCmd?: string; + + constructor(cfg: UploadConfig) { + super(cfg); + cfg = cfg || {}; + + if (!cfg.bucket || !cfg.file) { + throw new Error('A bucket and file name are required'); + } + + if (cfg.offset && !cfg.uri) { + throw new RangeError( + 'Cannot provide an `offset` without providing a `uri`', + ); + } + + if (cfg.isPartialUpload && !cfg.chunkSize) { + throw new RangeError( + 'Cannot set `isPartialUpload` without providing a `chunkSize`', + ); + } + + cfg.authConfig = cfg.authConfig || {}; + cfg.authConfig.scopes = [ + 'https://www.googleapis.com/auth/devstorage.full_control', + ]; + this.authClient = cfg.authClient || new GoogleAuth(cfg.authConfig); + + const universe = cfg.universeDomain || DEFAULT_UNIVERSE; + + this.apiEndpoint = `https://storage.${universe}`; + if (cfg.apiEndpoint && cfg.apiEndpoint !== this.apiEndpoint) { + this.apiEndpoint = this.sanitizeEndpoint(cfg.apiEndpoint); + + const hostname = new URL(this.apiEndpoint).hostname; + + // check if it is a domain of a known universe + const isDomain = hostname === universe; + const isDefaultUniverseDomain = hostname === DEFAULT_UNIVERSE; + + // check if it is a subdomain of a known universe + // by checking a last (universe's length + 1) of a hostname + const isSubDomainOfUniverse = + hostname.slice(-(universe.length + 1)) === `.${universe}`; + const isSubDomainOfDefaultUniverse = + hostname.slice(-(DEFAULT_UNIVERSE.length + 1)) === + `.${DEFAULT_UNIVERSE}`; + + if ( + !isDomain && + !isDefaultUniverseDomain && + !isSubDomainOfUniverse && + !isSubDomainOfDefaultUniverse + ) { + // Check if we should use auth with custom endpoint + if (cfg.useAuthWithCustomEndpoint !== true) { + // Only bypass auth if explicitly not requested + this.authClient = gaxios; + } + // Otherwise keep the authenticated client + } + } + + this.baseURI = `${this.apiEndpoint}/upload/storage/v1/b`; + this.bucket = cfg.bucket; + + const cacheKeyElements = [cfg.bucket, cfg.file]; + if (typeof cfg.generation === 'number') { + cacheKeyElements.push(`${cfg.generation}`); + } + + this.cacheKey = cacheKeyElements.join('/'); + + this.customRequestOptions = cfg.customRequestOptions || {}; + this.file = cfg.file; + this.generation = cfg.generation; + this.kmsKeyName = cfg.kmsKeyName; + this.metadata = cfg.metadata || {}; + this.offset = cfg.offset; + this.origin = cfg.origin; + this.params = cfg.params || {}; + this.userProject = cfg.userProject; + this.chunkSize = cfg.chunkSize; + this.retryOptions = cfg.retryOptions; + this.isPartialUpload = cfg.isPartialUpload ?? false; + + this.#clientCrc32c = cfg.clientCrc32c; + this.#clientMd5Hash = cfg.clientMd5Hash; + + const calculateCrc32c = !cfg.clientCrc32c && cfg.crc32c; + const calculateMd5 = !cfg.clientMd5Hash && cfg.md5; + + if (calculateCrc32c || calculateMd5) { + this.#hashValidator = new HashStreamValidator({ + crc32c: calculateCrc32c, + md5: calculateMd5, + updateHashesOnly: true, + }); + } + + if (cfg.key) { + if (typeof cfg.key === 'string') { + const base64Key = Buffer.from(cfg.key).toString('base64'); + this.encryption = { + key: base64Key, + hash: createHash('sha256').update(cfg.key).digest('base64'), + }; + } else { + const base64Key = cfg.key.toString('base64'); + this.encryption = { + key: base64Key, + hash: createHash('sha256').update(cfg.key).digest('base64'), + }; + } + } + + this.predefinedAcl = cfg.predefinedAcl; + if (cfg.private) this.predefinedAcl = 'private'; + if (cfg.public) this.predefinedAcl = 'publicRead'; + + const autoRetry = cfg.retryOptions.autoRetry; + this.uriProvidedManually = !!cfg.uri; + this.uri = cfg.uri; + + if (this.offset) { + // we're resuming an incomplete upload + this.numBytesWritten = this.offset; + } + + this.numRetries = 0; // counter for number of retries currently executed + if (!autoRetry) { + cfg.retryOptions.maxRetries = 0; + } + + this.timeOfFirstRequest = Date.now(); + + const contentLength = cfg.metadata + ? Number(cfg.metadata.contentLength) + : NaN; + this.contentLength = isNaN(contentLength) ? '*' : contentLength; + + this.#gcclGcsCmd = cfg[GCCL_GCS_CMD_KEY]; + + this.once('writing', () => { + if (this.uri) { + this.continueUploading(); + } else { + this.createURI(err => { + if (err) { + return this.destroy(err); + } + this.startUploading(); + return; + }); + } + }); + } + + /** + * Prevent 'finish' event until the upload has succeeded. + * + * @param fireFinishEvent The finish callback + */ + _final(fireFinishEvent = () => {}) { + this.upstreamEnded = true; + + this.once('uploadFinished', fireFinishEvent); + + process.nextTick(() => { + this.emit('upstreamFinished'); + // it's possible `_write` may not be called - namely for empty object uploads + this.emit('writing'); + }); + } + + /** + * Handles incoming data from upstream + * + * @param chunk The chunk to append to the buffer + * @param encoding The encoding of the chunk + * @param readCallback A callback for when the buffer has been read downstream + */ + _write( + chunk: Buffer | string, + encoding: BufferEncoding, + readCallback = () => {}, + ) { + // Backwards-compatible event + this.emit('writing'); + + const bufferChunk = + typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk; + + if (this.#hashValidator) { + try { + this.#hashValidator.write(bufferChunk); + } catch (e) { + this.destroy(e as Error); + return; + } + } + + this.writeBuffers.push(bufferChunk); + + this.once('readFromChunkBuffer', readCallback); + + process.nextTick(() => this.emit('wroteToChunkBuffer')); + } + + #resetLocalBuffersCache() { + this.localWriteCache = []; + this.localWriteCacheByteLength = 0; + } + + #addLocalBufferCache(buf: Buffer) { + this.localWriteCache.push(buf); + this.localWriteCacheByteLength += buf.byteLength; + } + + /** + * Compares the client's calculated or provided hash against the server's + * returned hash for a specific checksum type. Destroys the stream on mismatch. + * @param clientHash The client's calculated or provided hash (Base64). + * @param serverHash The hash returned by the server (Base64). + * @param hashType The type of hash ('CRC32C' or 'MD5'). + */ + #validateChecksum( + clientHash: string | undefined, + serverHash: string | undefined, + hashType: 'CRC32C' | 'MD5', + ): boolean { + // Only validate if both client and server hashes are present. + if (clientHash && serverHash) { + if (clientHash !== serverHash) { + const detailMessage = `${hashType} checksum mismatch. Client calculated: ${clientHash}, Server returned: ${serverHash}`; + const detailError = new Error(detailMessage); + const error = new RequestError(FileExceptionMessages.UPLOAD_MISMATCH); + error.code = 'FILE_NO_UPLOAD'; + error.errors = [detailError]; + + this.destroy(error); + return true; + } + } + return false; + } + + /** + * Builds and applies the X-Goog-Hash header to the request options + * using either calculated hashes from #hashValidator or pre-calculated + * client-side hashes. This should only be called on the final request. + * + * @param headers The headers object to modify. + */ + #applyChecksumHeaders(headers: GaxiosOptions['headers']) { + const checksums: string[] = []; + + if (this.#hashValidator?.crc32cEnabled) { + checksums.push(`crc32c=${this.#hashValidator.crc32c!}`); + } else if (this.#clientCrc32c) { + checksums.push(`crc32c=${this.#clientCrc32c}`); + } + + if (this.#hashValidator?.md5Enabled) { + checksums.push(`md5=${this.#hashValidator.md5Digest!}`); + } else if (this.#clientMd5Hash) { + checksums.push(`md5=${this.#clientMd5Hash}`); + } + + if (checksums.length > 0) { + headers!['X-Goog-Hash'] = checksums.join(','); + } + } + + /** + * Prepends the local buffer to write buffer and resets it. + * + * @param keepLastBytes number of bytes to keep from the end of the local buffer. + */ + private prependLocalBufferToUpstream(keepLastBytes?: number) { + // Typically, the upstream write buffers should be smaller than the local + // cache, so we can save time by setting the local cache as the new + // upstream write buffer array and appending the old array to it + let initialBuffers: Buffer[] = []; + + if (keepLastBytes) { + // we only want the last X bytes + let bytesKept = 0; + + while (keepLastBytes > bytesKept) { + // load backwards because we want the last X bytes + // note: `localWriteCacheByteLength` is reset below + let buf = this.localWriteCache.pop(); + if (!buf) break; + + bytesKept += buf.byteLength; + + if (bytesKept > keepLastBytes) { + // we have gone over the amount desired, let's keep the last X bytes + // of this buffer + const diff = bytesKept - keepLastBytes; + buf = buf.subarray(diff); + bytesKept -= diff; + } + + initialBuffers.unshift(buf); + } + } else { + // we're keeping all of the local cache, simply use it as the initial buffer + initialBuffers = this.localWriteCache; + } + + // Append the old upstream to the new + const append = this.writeBuffers; + this.writeBuffers = initialBuffers; + + for (const buf of append) { + this.writeBuffers.push(buf); + } + + // reset last buffers sent + this.#resetLocalBuffersCache(); + } + + /** + * Retrieves data from upstream's buffer. + * + * @param limit The maximum amount to return from the buffer. + */ + private *pullFromChunkBuffer(limit: number) { + while (limit) { + const buf = this.writeBuffers.shift(); + if (!buf) break; + + let bufToYield = buf; + + if (buf.byteLength > limit) { + bufToYield = buf.subarray(0, limit); + this.writeBuffers.unshift(buf.subarray(limit)); + limit = 0; + } else { + limit -= buf.byteLength; + } + + yield bufToYield; + + // Notify upstream we've read from the buffer and we're able to consume + // more. It can also potentially send more data down as we're currently + // iterating. + this.emit('readFromChunkBuffer'); + } + } + + /** + * A handler for determining if data is ready to be read from upstream. + * + * @returns If there will be more chunks to read in the future + */ + private async waitForNextChunk(): Promise { + const willBeMoreChunks = await new Promise(resolve => { + // There's data available - it should be digested + if (this.writeBuffers.length) { + return resolve(true); + } + + // The upstream writable ended, we shouldn't expect any more data. + if (this.upstreamEnded) { + return resolve(false); + } + + // Nothing immediate seems to be determined. We need to prepare some + // listeners to determine next steps... + + const wroteToChunkBufferCallback = () => { + removeListeners(); + return resolve(true); + }; + + const upstreamFinishedCallback = () => { + removeListeners(); + + // this should be the last chunk, if there's anything there + if (this.writeBuffers.length) return resolve(true); + + return resolve(false); + }; + + // Remove listeners when we're ready to callback. + const removeListeners = () => { + this.removeListener('wroteToChunkBuffer', wroteToChunkBufferCallback); + this.removeListener('upstreamFinished', upstreamFinishedCallback); + }; + + // If there's data recently written it should be digested + this.once('wroteToChunkBuffer', wroteToChunkBufferCallback); + + // If the upstream finishes let's see if there's anything to grab + this.once('upstreamFinished', upstreamFinishedCallback); + }); + + return willBeMoreChunks; + } + + /** + * Reads data from upstream up to the provided `limit`. + * Ends when the limit has reached or no data is expected to be pushed from upstream. + * + * @param limit The most amount of data this iterator should return. `Infinity` by default. + */ + private async *upstreamIterator(limit = Infinity) { + // read from upstream chunk buffer + while (limit && (await this.waitForNextChunk())) { + // read until end or limit has been reached + for (const chunk of this.pullFromChunkBuffer(limit)) { + limit -= chunk.byteLength; + yield chunk; + } + } + } + + createURI(): Promise; + createURI(callback: CreateUriCallback): void; + createURI(callback?: CreateUriCallback): void | Promise { + if (!callback) { + return this.createURIAsync(); + } + this.createURIAsync().then(r => callback(null, r), callback); + } + + protected async createURIAsync(): Promise { + const metadata = {...this.metadata}; + const headers: gaxios.Headers = {}; + + // Delete content length and content type from metadata if they exist. + // These are headers and should not be sent as part of the metadata. + if (metadata.contentLength) { + headers['X-Upload-Content-Length'] = metadata.contentLength.toString(); + delete metadata.contentLength; + } + + if (metadata.contentType) { + headers!['X-Upload-Content-Type'] = metadata.contentType; + delete metadata.contentType; + } + + let googAPIClient = `${getRuntimeTrackingString()} gccl/${ + packageJson.version + }-${getModuleFormat()} gccl-invocation-id/${this.currentInvocationId.uri}`; + + if (this.#gcclGcsCmd) { + googAPIClient += ` gccl-gcs-cmd/${this.#gcclGcsCmd}`; + } + + // Check if headers already exist before creating new ones + const reqOpts: GaxiosOptions = { + method: 'POST', + url: [this.baseURI, this.bucket, 'o'].join('/'), + params: Object.assign( + { + name: this.file, + uploadType: 'resumable', + }, + this.params, + ), + data: metadata, + headers: { + 'User-Agent': getUserAgentString(), + 'x-goog-api-client': googAPIClient, + ...headers, + }, + }; + + if (metadata.contentLength) { + reqOpts.headers!['X-Upload-Content-Length'] = + metadata.contentLength.toString(); + } + + if (metadata.contentType) { + reqOpts.headers!['X-Upload-Content-Type'] = metadata.contentType; + } + + if (typeof this.generation !== 'undefined') { + reqOpts.params.ifGenerationMatch = this.generation; + } + + if (this.kmsKeyName) { + reqOpts.params.kmsKeyName = this.kmsKeyName; + } + + if (this.predefinedAcl) { + reqOpts.params.predefinedAcl = this.predefinedAcl; + } + + if (this.origin) { + reqOpts.headers!.Origin = this.origin; + } + const uri = await AsyncRetry( + async (bail: (err: Error) => void) => { + try { + const res = await this.makeRequest(reqOpts); + // We have successfully got a URI we can now create a new invocation id + this.currentInvocationId.uri = uuid.v4(); + return res.headers.location; + } catch (err) { + const e = err as GaxiosError; + const apiError = { + code: e.response?.status, + name: e.response?.statusText, + message: e.response?.statusText, + errors: [ + { + reason: e.code as string, + }, + ], + }; + if ( + this.retryOptions.maxRetries! > 0 && + this.retryOptions.retryableErrorFn!(apiError as ApiError) + ) { + throw e; + } else { + return bail(e); + } + } + }, + { + retries: this.retryOptions.maxRetries, + factor: this.retryOptions.retryDelayMultiplier, + maxTimeout: this.retryOptions.maxRetryDelay! * 1000, //convert to milliseconds + maxRetryTime: this.retryOptions.totalTimeout! * 1000, //convert to milliseconds + }, + ); + + this.uri = uri; + this.offset = 0; + + // emit the newly generated URI for future reuse, if necessary. + this.emit('uri', uri); + + return uri; + } + + private async continueUploading() { + this.offset ?? (await this.getAndSetOffset()); + + return this.startUploading(); + } + + async startUploading() { + const multiChunkMode = !!this.chunkSize; + let responseReceived = false; + this.numChunksReadInRequest = 0; + + if (!this.offset) { + this.offset = 0; + } + + // Check if the offset (server) is too far behind the current stream + if (this.offset < this.numBytesWritten) { + const delta = this.numBytesWritten - this.offset; + const message = `The offset is lower than the number of bytes written. The server has ${this.offset} bytes and while ${this.numBytesWritten} bytes has been uploaded - thus ${delta} bytes are missing. Stopping as this could result in data loss. Initiate a new upload to continue.`; + + this.emit('error', new RangeError(message)); + return; + } + + // Check if we should 'fast-forward' to the relevant data to upload + if (this.numBytesWritten < this.offset) { + // 'fast-forward' to the byte where we need to upload. + // only push data from the byte after the one we left off on + const fastForwardBytes = this.offset - this.numBytesWritten; + + for await (const _chunk of this.upstreamIterator(fastForwardBytes)) { + _chunk; // discard the data up until the point we want + } + + this.numBytesWritten = this.offset; + } + + let expectedUploadSize: number | undefined = undefined; + + // Set `expectedUploadSize` to `contentLength - this.numBytesWritten`, if available + if (typeof this.contentLength === 'number') { + expectedUploadSize = this.contentLength - this.numBytesWritten; + } + + // `expectedUploadSize` should be no more than the `chunkSize`. + // It's possible this is the last chunk request for a multiple + // chunk upload, thus smaller than the chunk size. + if (this.chunkSize) { + expectedUploadSize = expectedUploadSize + ? Math.min(this.chunkSize, expectedUploadSize) + : this.chunkSize; + } + + // A queue for the upstream data + const upstreamQueue = this.upstreamIterator(expectedUploadSize); + + // The primary read stream for this request. This stream retrieves no more + // than the exact requested amount from upstream. + const requestStream = new Readable({ + read: async () => { + // Don't attempt to retrieve data upstream if we already have a response + if (responseReceived) requestStream.push(null); + + const result = await upstreamQueue.next(); + + if (result.value) { + this.numChunksReadInRequest++; + + if (multiChunkMode) { + // save ever buffer used in the request in multi-chunk mode + this.#addLocalBufferCache(result.value); + } else { + this.#resetLocalBuffersCache(); + this.#addLocalBufferCache(result.value); + } + + this.numBytesWritten += result.value.byteLength; + + this.emit('progress', { + bytesWritten: this.numBytesWritten, + contentLength: this.contentLength, + }); + + requestStream.push(result.value); + } + + if (result.done) { + requestStream.push(null); + } + }, + }); + + let googAPIClient = `${getRuntimeTrackingString()} gccl/${ + packageJson.version + }-${getModuleFormat()} gccl-invocation-id/${ + this.currentInvocationId.chunk + }`; + + if (this.#gcclGcsCmd) { + googAPIClient += ` gccl-gcs-cmd/${this.#gcclGcsCmd}`; + } + + const headers: GaxiosOptions['headers'] = { + 'User-Agent': getUserAgentString(), + 'x-goog-api-client': googAPIClient, + }; + + // If using multiple chunk upload, set appropriate header + if (multiChunkMode) { + // We need to know how much data is available upstream to set the `Content-Range` header. + // https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + for await (const chunk of this.upstreamIterator(expectedUploadSize)) { + // This will conveniently track and keep the size of the buffers. + // We will reach either the expected upload size or the remainder of the stream. + this.#addLocalBufferCache(chunk); + } + + // This is the sum from the `#addLocalBufferCache` calls + const bytesToUpload = this.localWriteCacheByteLength; + + // Important: we want to know if the upstream has ended and the queue is empty before + // unshifting data back into the queue. This way we will know if this is the last request or not. + const isLastChunkOfUpload = !(await this.waitForNextChunk()); + + if (isLastChunkOfUpload && this.#hashValidator) { + this.#hashValidator.end(); + } + + // Important: put the data back in the queue for the actual upload + this.prependLocalBufferToUpstream(); + + let totalObjectSize = this.contentLength; + + if ( + typeof this.contentLength !== 'number' && + isLastChunkOfUpload && + !this.isPartialUpload + ) { + // Let's let the server know this is the last chunk of the object since we didn't set it before. + totalObjectSize = bytesToUpload + this.numBytesWritten; + } + + // `- 1` as the ending byte is inclusive in the request. + const endingByte = bytesToUpload + this.numBytesWritten - 1; + + // `Content-Length` for multiple chunk uploads is the size of the chunk, + // not the overall object + headers['Content-Length'] = bytesToUpload; + headers['Content-Range'] = + `bytes ${this.offset}-${endingByte}/${totalObjectSize}`; + + // Apply X-Goog-Hash header ONLY on the final chunk (WriteObject call) + if (isLastChunkOfUpload) { + this.#applyChecksumHeaders(headers); + } + } else { + headers['Content-Range'] = `bytes ${this.offset}-*/${this.contentLength}`; + + if (this.#hashValidator) { + this.#hashValidator.end(); + } + this.#applyChecksumHeaders(headers); + } + + const reqOpts: GaxiosOptions = { + method: 'PUT', + url: this.uri, + headers, + body: requestStream, + }; + + try { + const resp = await this.makeRequestStream(reqOpts); + if (resp) { + responseReceived = true; + await this.responseHandler(resp); + } + } catch (e) { + const err = e as ApiError; + + if (this.retryOptions.retryableErrorFn!(err)) { + this.attemptDelayedRetry({ + status: NaN, + data: err, + }); + return; + } + + this.destroy(err); + } + } + + // Process the API response to look for errors that came in + // the response body. + private async responseHandler(resp: GaxiosResponse) { + if (resp.data.error) { + this.destroy(resp.data.error); + return; + } + + // At this point we can safely create a new id for the chunk + this.currentInvocationId.chunk = uuid.v4(); + + const moreDataToUpload = await this.waitForNextChunk(); + + const shouldContinueWithNextMultiChunkRequest = + this.chunkSize && + resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE && + resp.headers.range && + moreDataToUpload; + + /** + * This is true when we're expecting to upload more data in a future request, + * yet the upstream for the upload session has been exhausted. + */ + const shouldContinueUploadInAnotherRequest = + this.isPartialUpload && + resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE && + !moreDataToUpload; + + if (shouldContinueWithNextMultiChunkRequest) { + // Use the upper value in this header to determine where to start the next chunk. + // We should not assume that the server received all bytes sent in the request. + // https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + const range: string = resp.headers.range; + this.offset = Number(range.split('-')[1]) + 1; + + // We should not assume that the server received all bytes sent in the request. + // - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + const missingBytes = this.numBytesWritten - this.offset; + if (missingBytes) { + // As multi-chunk uploads send one chunk per request and pulls one + // chunk into the pipeline, prepending the missing bytes back should + // be fine for the next request. + this.prependLocalBufferToUpstream(missingBytes); + this.numBytesWritten -= missingBytes; + } else { + // No bytes missing - no need to keep the local cache + this.#resetLocalBuffersCache(); + } + + // continue uploading next chunk + this.continueUploading(); + } else if ( + !this.isSuccessfulResponse(resp.status) && + !shouldContinueUploadInAnotherRequest + ) { + const err: ApiError = new Error('Upload failed'); + err.code = resp.status; + err.name = 'Upload failed'; + if (resp?.data) { + err.errors = [resp?.data]; + } + + this.destroy(err); + } else if (this.isSuccessfulResponse(resp.status)) { + const serverCrc32c = resp.data.crc32c; + const serverMd5 = resp.data.md5Hash; + + if (this.#hashValidator) { + this.#hashValidator.end(); + } + + const clientCrc32cToValidate = + this.#hashValidator?.crc32c || this.#clientCrc32c; + const clientMd5HashToValidate = + this.#hashValidator?.md5Digest || this.#clientMd5Hash; + if ( + this.#validateChecksum( + clientCrc32cToValidate, + serverCrc32c, + 'CRC32C', + ) || + this.#validateChecksum(clientMd5HashToValidate, serverMd5, 'MD5') + ) { + return; + } + + // no need to keep the cache + this.#resetLocalBuffersCache(); + + if (resp && resp.data) { + resp.data.size = Number(resp.data.size); + } + this.emit('metadata', resp.data); + + // Allow the object (Upload) to continue naturally so the user's + // "finish" event fires. + this.emit('uploadFinished'); + } else { + // Handles the case where shouldContinueUploadInAnotherRequest is true + // and the response is not successful (e.g., 308 for a partial upload). + // This is the expected behavior for partial uploads that have finished their chunk. + this.emit('uploadFinished'); + } + } + + /** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ + async checkUploadStatus( + config: CheckUploadStatusConfig = {}, + ): Promise> { + let googAPIClient = `${getRuntimeTrackingString()} gccl/${ + packageJson.version + }-${getModuleFormat()} gccl-invocation-id/${ + this.currentInvocationId.checkUploadStatus + }`; + + if (this.#gcclGcsCmd) { + googAPIClient += ` gccl-gcs-cmd/${this.#gcclGcsCmd}`; + } + + const opts: GaxiosOptions = { + method: 'PUT', + url: this.uri, + headers: { + 'Content-Length': 0, + 'Content-Range': 'bytes */*', + 'User-Agent': getUserAgentString(), + 'x-goog-api-client': googAPIClient, + }, + }; + + try { + const resp = await this.makeRequest(opts); + + // Successfully got the offset we can now create a new offset invocation id + this.currentInvocationId.checkUploadStatus = uuid.v4(); + + return resp; + } catch (e) { + if ( + config.retry === false || + !(e instanceof Error) || + !this.retryOptions.retryableErrorFn!(e) + ) { + throw e; + } + + const retryDelay = this.getRetryDelay(); + + if (retryDelay <= 0) { + throw e; + } + + await new Promise(res => setTimeout(res, retryDelay)); + + return this.checkUploadStatus(config); + } + } + + private async getAndSetOffset() { + try { + // we want to handle retries in this method. + const resp = await this.checkUploadStatus({retry: false}); + + if (resp.status === RESUMABLE_INCOMPLETE_STATUS_CODE) { + if (typeof resp.headers.range === 'string') { + this.offset = Number(resp.headers.range.split('-')[1]) + 1; + return; + } + } + this.offset = 0; + } catch (e) { + const err = e as ApiError; + + if (this.retryOptions.retryableErrorFn!(err)) { + this.attemptDelayedRetry({ + status: NaN, + data: err, + }); + return; + } + + this.destroy(err); + } + } + + private async makeRequest(reqOpts: GaxiosOptions): GaxiosPromise { + if (this.encryption) { + reqOpts.headers = reqOpts.headers || {}; + reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256'; + reqOpts.headers['x-goog-encryption-key'] = this.encryption.key.toString(); + reqOpts.headers['x-goog-encryption-key-sha256'] = + this.encryption.hash.toString(); + } + + if (this.userProject) { + reqOpts.params = reqOpts.params || {}; + reqOpts.params.userProject = this.userProject; + } + // Let gaxios know we will handle a 308 error code ourselves. + reqOpts.validateStatus = (status: number) => { + return ( + this.isSuccessfulResponse(status) || + status === RESUMABLE_INCOMPLETE_STATUS_CODE + ); + }; + + const combinedReqOpts = { + ...this.customRequestOptions, + ...reqOpts, + headers: { + ...this.customRequestOptions.headers, + ...reqOpts.headers, + }, + }; + + const res = await this.authClient.request<{error?: object}>( + combinedReqOpts, + ); + if (res.data && res.data.error) { + throw res.data.error; + } + return res; + } + + private async makeRequestStream(reqOpts: GaxiosOptions) { + const controller = new AbortController(); + const errorCallback = () => controller.abort(); + this.once('error', errorCallback); + + if (this.userProject) { + reqOpts.params = reqOpts.params || {}; + reqOpts.params.userProject = this.userProject; + } + reqOpts.signal = controller.signal; + reqOpts.validateStatus = () => true; + + const combinedReqOpts = { + ...this.customRequestOptions, + ...reqOpts, + headers: { + ...this.customRequestOptions.headers, + ...reqOpts.headers, + }, + }; + const res = await this.authClient.request(combinedReqOpts); + const successfulRequest = this.onResponse(res); + this.removeListener('error', errorCallback); + + return successfulRequest ? res : null; + } + + /** + * @return {bool} is the request good? + */ + private onResponse(resp: GaxiosResponse) { + if ( + resp.status !== 200 && + this.retryOptions.retryableErrorFn!({ + code: resp.status, + message: resp.statusText, + name: resp.statusText, + }) + ) { + this.attemptDelayedRetry(resp); + return false; + } + + this.emit('response', resp); + return true; + } + + /** + * @param resp GaxiosResponse object from previous attempt + */ + private attemptDelayedRetry(resp: Pick) { + if (this.numRetries < this.retryOptions.maxRetries!) { + if ( + resp.status === NOT_FOUND_STATUS_CODE && + this.numChunksReadInRequest === 0 + ) { + this.startUploading(); + } else { + const retryDelay = this.getRetryDelay(); + + if (retryDelay <= 0) { + this.destroy( + new Error( + `Retry total time limit exceeded - ${JSON.stringify(resp.data)}`, + ), + ); + return; + } + + // Unshift the local cache back in case it's needed for the next request. + this.numBytesWritten -= this.localWriteCacheByteLength; + this.prependLocalBufferToUpstream(); + + // We don't know how much data has been received by the server. + // `continueUploading` will recheck the offset via `getAndSetOffset`. + // If `offset` < `numberBytesReceived` then we will raise a RangeError + // as we've streamed too much data that has been missed - this should + // not be the case for multi-chunk uploads as `lastChunkSent` is the + // body of the entire request. + this.offset = undefined; + + setTimeout(this.continueUploading.bind(this), retryDelay); + } + this.numRetries++; + } else { + this.destroy( + new Error(`Retry limit exceeded - ${JSON.stringify(resp.data)}`), + ); + } + } + + /** + * The amount of time to wait before retrying the request, in milliseconds. + * If negative, do not retry. + * + * @returns the amount of time to wait, in milliseconds. + */ + private getRetryDelay(): number { + const randomMs = Math.round(Math.random() * 1000); + const waitTime = + Math.pow(this.retryOptions.retryDelayMultiplier!, this.numRetries) * + 1000 + + randomMs; + const maxAllowableDelayMs = + this.retryOptions.totalTimeout! * 1000 - + (Date.now() - this.timeOfFirstRequest); + const maxRetryDelayMs = this.retryOptions.maxRetryDelay! * 1000; + + return Math.min(waitTime, maxRetryDelayMs, maxAllowableDelayMs); + } + + /* + * Prepare user-defined API endpoint for compatibility with our API. + */ + private sanitizeEndpoint(url: string) { + if (!PROTOCOL_REGEX.test(url)) { + url = `https://${url}`; + } + return url.replace(/\/+$/, ''); // Remove trailing slashes + } + + /** + * Check if a given status code is 2xx + * + * @param status The status code to check + * @returns if the status is 2xx + */ + public isSuccessfulResponse(status: number): boolean { + return status >= 200 && status < 300; + } +} + +export function upload(cfg: UploadConfig) { + return new Upload(cfg); +} + +export function createURI(cfg: UploadConfig): Promise; +export function createURI(cfg: UploadConfig, callback: CreateUriCallback): void; +export function createURI( + cfg: UploadConfig, + callback?: CreateUriCallback, +): void | Promise { + const up = new Upload(cfg); + if (!callback) { + return up.createURI(); + } + up.createURI().then(r => callback(null, r), callback); +} + +/** + * Check the status of an existing resumable upload. + * + * @param cfg A configuration to use. `uri` is required. + * @returns the current upload status + */ +export function checkUploadStatus( + cfg: UploadConfig & Required>, +) { + const up = new Upload(cfg); + + return up.checkUploadStatus(); +} diff --git a/handwritten/storage/src/signer.ts b/handwritten/storage/src/signer.ts new file mode 100644 index 00000000000..a657cef6133 --- /dev/null +++ b/handwritten/storage/src/signer.ts @@ -0,0 +1,491 @@ +// Copyright 2020 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 * as crypto from 'crypto'; +import * as http from 'http'; +import * as url from 'url'; +import {ExceptionMessages, Storage} from './storage.js'; +import {encodeURI, qsStringify, objectEntries, formatAsUTCISO} from './util.js'; +import {GoogleAuth} from 'google-auth-library'; + +type GoogleAuthLike = Pick; + +/** + * @deprecated Use {@link GoogleAuth} instead + */ +export interface AuthClient { + sign(blobToSign: string): Promise; + getCredentials(): Promise<{ + client_email?: string; + }>; +} + +export interface BucketI { + name: string; +} + +export interface FileI { + name: string; +} + +export interface Query { + [key: string]: string; +} + +export interface GetSignedUrlConfigInternal { + expiration: number; + accessibleAt?: Date; + method: string; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; + cname?: string; + contentMd5?: string; + contentType?: string; + bucket: string; + file?: string; + /** + * The host for the generated signed URL + * + * @example + * 'https://localhost:8080/' + */ + host?: string | URL; + /** + * An endpoint for generating the signed URL + * + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string | URL; +} + +interface SignedUrlQuery { + generation?: number; + 'response-content-type'?: string; + 'response-content-disposition'?: string; +} + +interface V2SignedUrlQuery extends SignedUrlQuery { + GoogleAccessId: string; + Expires: number; + Signature: string; +} + +export interface SignerGetSignedUrlConfig { + method: 'GET' | 'PUT' | 'DELETE' | 'POST'; + expires: string | number | Date; + accessibleAt?: string | number | Date; + virtualHostedStyle?: boolean; + version?: 'v2' | 'v4'; + cname?: string; + extensionHeaders?: http.OutgoingHttpHeaders; + queryParams?: Query; + contentMd5?: string; + contentType?: string; + /** + * The host for the generated signed URL + * + * @example + * 'https://localhost:8080/' + */ + host?: string | URL; + /** + * An endpoint for generating the signed URL + * + * @example + * 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/' + */ + signingEndpoint?: string | URL; +} + +export type SignerGetSignedUrlResponse = string; + +export type GetSignedUrlResponse = [SignerGetSignedUrlResponse]; + +export interface GetSignedUrlCallback { + (err: Error | null, url?: string): void; +} +type ValueOf = T[keyof T]; +type HeaderValue = ValueOf; + +export enum SignerExceptionMessages { + ACCESSIBLE_DATE_INVALID = 'The accessible at date provided was invalid.', + EXPIRATION_BEFORE_ACCESSIBLE_DATE = 'An expiration date cannot be before accessible date.', + X_GOOG_CONTENT_SHA256 = 'The header X-Goog-Content-SHA256 must be a hexadecimal string.', +} + +/* + * Default signing version for getSignedUrl is 'v2'. + */ +const DEFAULT_SIGNING_VERSION = 'v2'; + +const SEVEN_DAYS = 7 * 24 * 60 * 60; + +/** + * @const {string} + * @deprecated - unused + */ +export const PATH_STYLED_HOST = 'https://storage.googleapis.com'; + +export class URLSigner { + constructor( + private auth: AuthClient | GoogleAuthLike, + private bucket: BucketI, + private file?: FileI, + /** + * A {@link Storage} object. + * + * @privateRemarks + * + * Technically this is a required field, however it would be a breaking change to + * move it before optional properties. In the next major we should refactor the + * constructor of this class to only accept a config object. + */ + private storage: Storage = new Storage(), + ) {} + + getSignedUrl( + cfg: SignerGetSignedUrlConfig, + ): Promise { + const expiresInSeconds = this.parseExpires(cfg.expires); + const method = cfg.method; + const accessibleAtInSeconds = this.parseAccessibleAt(cfg.accessibleAt); + + if (expiresInSeconds < accessibleAtInSeconds) { + throw new Error( + SignerExceptionMessages.EXPIRATION_BEFORE_ACCESSIBLE_DATE, + ); + } + + let customHost: string | undefined; + // Default style is `path`. + const isVirtualHostedStyle = cfg.virtualHostedStyle || false; + + if (cfg.cname) { + customHost = cfg.cname; + } else if (isVirtualHostedStyle) { + customHost = `https://${this.bucket.name}.storage.${this.storage.universeDomain}`; + } + + const secondsToMilliseconds = 1000; + const config: GetSignedUrlConfigInternal = Object.assign({}, cfg, { + method, + expiration: expiresInSeconds, + accessibleAt: new Date(secondsToMilliseconds * accessibleAtInSeconds), + bucket: this.bucket.name, + file: this.file ? encodeURI(this.file.name, false) : undefined, + }); + + if (customHost) { + config.cname = customHost; + } + + const version = cfg.version || DEFAULT_SIGNING_VERSION; + + let promise: Promise; + if (version === 'v2') { + promise = this.getSignedUrlV2(config); + } else if (version === 'v4') { + promise = this.getSignedUrlV4(config); + } else { + throw new Error( + `Invalid signed URL version: ${version}. Supported versions are 'v2' and 'v4'.`, + ); + } + + return promise.then(query => { + query = Object.assign(query, cfg.queryParams); + + const signedUrl = new url.URL( + cfg.host?.toString() || config.cname || this.storage.apiEndpoint, + ); + + signedUrl.pathname = this.getResourcePath( + !!config.cname, + this.bucket.name, + config.file, + ); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + signedUrl.search = qsStringify(query as any); + return signedUrl.href; + }); + } + + private getSignedUrlV2( + config: GetSignedUrlConfigInternal, + ): Promise { + const canonicalHeadersString = this.getCanonicalHeaders( + config.extensionHeaders || {}, + ); + const resourcePath = this.getResourcePath( + false, + config.bucket, + config.file, + ); + + const blobToSign = [ + config.method, + config.contentMd5 || '', + config.contentType || '', + config.expiration, + canonicalHeadersString + resourcePath, + ].join('\n'); + + const sign = async () => { + const auth = this.auth; + try { + const signature = await auth.sign( + blobToSign, + config.signingEndpoint?.toString(), + ); + const credentials = await auth.getCredentials(); + + return { + GoogleAccessId: credentials.client_email!, + Expires: config.expiration, + Signature: signature, + } as V2SignedUrlQuery; + } catch (err) { + const error = err as Error; + const signingErr = new SigningError(error.message); + signingErr.stack = error.stack; + throw signingErr; + } + }; + return sign(); + } + + private getSignedUrlV4( + config: GetSignedUrlConfigInternal, + ): Promise { + config.accessibleAt = config.accessibleAt + ? config.accessibleAt + : new Date(); + const millisecondsToSeconds = 1.0 / 1000.0; + const expiresPeriodInSeconds = + config.expiration - config.accessibleAt.valueOf() * millisecondsToSeconds; + + // v4 limit expiration to be 7 days maximum + if (expiresPeriodInSeconds > SEVEN_DAYS) { + throw new Error( + `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`, + ); + } + + const extensionHeaders = Object.assign({}, config.extensionHeaders); + const fqdn = new url.URL( + config.host?.toString() || config.cname || this.storage.apiEndpoint, + ); + extensionHeaders.host = fqdn.hostname; + if (config.contentMd5) { + extensionHeaders['content-md5'] = config.contentMd5; + } + if (config.contentType) { + extensionHeaders['content-type'] = config.contentType; + } + + let contentSha256: string; + const sha256Header = extensionHeaders['x-goog-content-sha256']; + if (sha256Header) { + if ( + typeof sha256Header !== 'string' || + !/[A-Fa-f0-9]{40}/.test(sha256Header) + ) { + throw new Error(SignerExceptionMessages.X_GOOG_CONTENT_SHA256); + } + contentSha256 = sha256Header; + } + + const signedHeaders = Object.keys(extensionHeaders) + .map(header => header.toLowerCase()) + .sort() + .join(';'); + + const extensionHeadersString = this.getCanonicalHeaders(extensionHeaders); + + const datestamp = formatAsUTCISO(config.accessibleAt); + const credentialScope = `${datestamp}/auto/storage/goog4_request`; + + const sign = async () => { + const credentials = await this.auth.getCredentials(); + const credential = `${credentials.client_email}/${credentialScope}`; + const dateISO = formatAsUTCISO( + config.accessibleAt ? config.accessibleAt : new Date(), + true, + ); + const queryParams: Query = { + 'X-Goog-Algorithm': 'GOOG4-RSA-SHA256', + 'X-Goog-Credential': credential, + 'X-Goog-Date': dateISO, + 'X-Goog-Expires': expiresPeriodInSeconds.toString(10), + 'X-Goog-SignedHeaders': signedHeaders, + ...(config.queryParams || {}), + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const canonicalQueryParams = this.getCanonicalQueryParams(queryParams); + + const canonicalRequest = this.getCanonicalRequest( + config.method, + this.getResourcePath(!!config.cname, config.bucket, config.file), + canonicalQueryParams, + extensionHeadersString, + signedHeaders, + contentSha256, + ); + + const hash = crypto + .createHash('sha256') + .update(canonicalRequest) + .digest('hex'); + + const blobToSign = [ + 'GOOG4-RSA-SHA256', + dateISO, + credentialScope, + hash, + ].join('\n'); + + try { + const signature = await this.auth.sign( + blobToSign, + config.signingEndpoint?.toString(), + ); + const signatureHex = Buffer.from(signature, 'base64').toString('hex'); + const signedQuery: Query = Object.assign({}, queryParams, { + 'X-Goog-Signature': signatureHex, + }); + return signedQuery; + } catch (err) { + const error = err as Error; + const signingErr = new SigningError(error.message); + signingErr.stack = error.stack; + throw signingErr; + } + }; + + return sign(); + } + + /** + * Create canonical headers for signing v4 url. + * + * The canonical headers for v4-signing a request demands header names are + * first lowercased, followed by sorting the header names. + * Then, construct the canonical headers part of the request: + * + ":" + Trim() + "\n" + * .. + * + ":" + Trim() + "\n" + * + * @param headers + * @private + */ + getCanonicalHeaders(headers: http.OutgoingHttpHeaders) { + // Sort headers by their lowercased names + const sortedHeaders = objectEntries(headers) + // Convert header names to lowercase + .map<[string, HeaderValue]>(([headerName, value]) => [ + headerName.toLowerCase(), + value, + ]) + .sort((a, b) => a[0].localeCompare(b[0])); + + return sortedHeaders + .filter(([, value]) => value !== undefined) + .map(([headerName, value]) => { + // - Convert Array (multi-valued header) into string, delimited by + // ',' (no space). + // - Trim leading and trailing spaces. + // - Convert sequential (2+) spaces into a single space + const canonicalValue = `${value}`.trim().replace(/\s{2,}/g, ' '); + + return `${headerName}:${canonicalValue}\n`; + }) + .join(''); + } + + getCanonicalRequest( + method: string, + path: string, + query: string, + headers: string, + signedHeaders: string, + contentSha256?: string, + ) { + return [ + method, + path, + query, + headers, + signedHeaders, + contentSha256 || 'UNSIGNED-PAYLOAD', + ].join('\n'); + } + + getCanonicalQueryParams(query: Query) { + return objectEntries(query) + .map(([key, value]) => [encodeURI(key, true), encodeURI(value, true)]) + .sort((a, b) => (a[0] < b[0] ? -1 : 1)) + .map(([key, value]) => `${key}=${value}`) + .join('&'); + } + + getResourcePath(cname: boolean, bucket: string, file?: string): string { + if (cname) { + return '/' + (file || ''); + } else if (file) { + return `/${bucket}/${file}`; + } else { + return `/${bucket}`; + } + } + + parseExpires( + expires: string | number | Date, + current: Date = new Date(), + ): number { + const expiresInMSeconds = new Date(expires).valueOf(); + + if (isNaN(expiresInMSeconds)) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_INVALID); + } + + if (expiresInMSeconds < current.valueOf()) { + throw new Error(ExceptionMessages.EXPIRATION_DATE_PAST); + } + + return Math.floor(expiresInMSeconds / 1000); // The API expects seconds. + } + + parseAccessibleAt(accessibleAt?: string | number | Date): number { + const accessibleAtInMSeconds = new Date( + accessibleAt || new Date(), + ).valueOf(); + + if (isNaN(accessibleAtInMSeconds)) { + throw new Error(SignerExceptionMessages.ACCESSIBLE_DATE_INVALID); + } + + return Math.floor(accessibleAtInMSeconds / 1000); // The API expects seconds. + } +} + +/** + * Custom error type for errors related to getting signed errors and policies. + * + * @private + */ +export class SigningError extends Error { + name = 'SigningError'; +} diff --git a/handwritten/storage/src/storage.ts b/handwritten/storage/src/storage.ts new file mode 100644 index 00000000000..dd0f735f6ed --- /dev/null +++ b/handwritten/storage/src/storage.ts @@ -0,0 +1,1634 @@ +// Copyright 2019 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 {ApiError, Service, ServiceOptions} from './nodejs-common/index.js'; +import {paginator} from '@google-cloud/paginator'; +import {promisifyAll} from '@google-cloud/promisify'; +import {Readable} from 'stream'; + +import {Bucket, BucketMetadata} from './bucket.js'; +import {Channel} from './channel.js'; +import {File} from './file.js'; +import {normalize} from './util.js'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import {getPackageJSON} from './package-json-helper.cjs'; +import {HmacKey, HmacKeyMetadata, HmacKeyOptions} from './hmacKey.js'; +import { + CRC32CValidatorGenerator, + CRC32C_DEFAULT_VALIDATOR_GENERATOR, +} from './crc32c.js'; +import {DEFAULT_UNIVERSE} from 'google-auth-library'; + +export interface GetServiceAccountOptions { + userProject?: string; + projectIdentifier?: string; +} +export interface ServiceAccount { + emailAddress?: string; +} +export type GetServiceAccountResponse = [ServiceAccount, unknown]; +export interface GetServiceAccountCallback { + ( + err: Error | null, + serviceAccount?: ServiceAccount, + apiResponse?: unknown, + ): void; +} + +export interface CreateBucketQuery { + enableObjectRetention: boolean; + predefinedAcl?: + | 'authenticatedRead' + | 'private' + | 'projectPrivate' + | 'publicRead' + | 'publicReadWrite'; + predefinedDefaultObjectAcl?: + | 'authenticatedRead' + | 'bucketOwnerFullControl' + | 'bucketOwnerRead' + | 'private' + | 'projectPrivate' + | 'publicRead'; + project: string; + projection?: 'full' | 'noAcl'; + userProject: string; +} + +export enum IdempotencyStrategy { + RetryAlways, + RetryConditional, + RetryNever, +} + +export interface RetryOptions { + retryDelayMultiplier?: number; + totalTimeout?: number; + maxRetryDelay?: number; + autoRetry?: boolean; + maxRetries?: number; + retryableErrorFn?: (err: ApiError) => boolean; + idempotencyStrategy?: IdempotencyStrategy; +} + +export interface PreconditionOptions { + ifGenerationMatch?: number | string; + ifGenerationNotMatch?: number | string; + ifMetagenerationMatch?: number | string; + ifMetagenerationNotMatch?: number | string; +} + +export interface StorageOptions extends ServiceOptions { + /** + * The API endpoint of the service used to make requests. + * Defaults to `storage.googleapis.com`. + */ + apiEndpoint?: string; + crc32cGenerator?: CRC32CValidatorGenerator; + retryOptions?: RetryOptions; +} + +export interface BucketOptions { + crc32cGenerator?: CRC32CValidatorGenerator; + kmsKeyName?: string; + preconditionOpts?: PreconditionOptions; + userProject?: string; + generation?: number; + softDeleted?: boolean; +} + +export interface Cors { + maxAgeSeconds?: number; + method?: string[]; + origin?: string[]; + responseHeader?: string[]; +} + +interface Versioning { + enabled: boolean; +} + +/** + * Custom placement configuration. + * Initially used for dual-region buckets. + **/ +export interface CustomPlacementConfig { + dataLocations?: string[]; +} + +export interface AutoclassConfig { + enabled?: boolean; + terminalStorageClass?: 'NEARLINE' | 'ARCHIVE'; +} + +export interface CreateBucketRequest extends BucketMetadata { + archive?: boolean; + coldline?: boolean; + dataLocations?: string[]; + dra?: boolean; + enableObjectRetention?: boolean; + multiRegional?: boolean; + nearline?: boolean; + predefinedAcl?: + | 'authenticatedRead' + | 'private' + | 'projectPrivate' + | 'publicRead' + | 'publicReadWrite'; + predefinedDefaultObjectAcl?: + | 'authenticatedRead' + | 'bucketOwnerFullControl' + | 'bucketOwnerRead' + | 'private' + | 'projectPrivate' + | 'publicRead'; + projection?: 'full' | 'noAcl'; + regional?: boolean; + requesterPays?: boolean; + rpo?: string; + standard?: boolean; + storageClass?: string; + userProject?: string; + versioning?: Versioning; +} + +export type CreateBucketResponse = [Bucket, unknown]; + +export interface BucketCallback { + (err: Error | null, bucket?: Bucket | null, apiResponse?: unknown): void; +} + +export type GetBucketsResponse = [Bucket[], {}, unknown]; +export interface GetBucketsCallback { + ( + err: Error | null, + buckets: Bucket[], + nextQuery?: {}, + apiResponse?: unknown, + ): void; +} +export interface GetBucketsRequest { + prefix?: string; + project?: string; + autoPaginate?: boolean; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + userProject?: string; + softDeleted?: boolean; + generation?: number; + returnPartialSuccess?: boolean; +} + +export interface HmacKeyResourceResponse { + metadata: HmacKeyMetadata; + secret: string; +} + +export type CreateHmacKeyResponse = [HmacKey, string, HmacKeyResourceResponse]; + +export interface CreateHmacKeyOptions { + projectId?: string; + userProject?: string; +} + +export interface CreateHmacKeyCallback { + ( + err: Error | null, + hmacKey?: HmacKey | null, + secret?: string | null, + apiResponse?: HmacKeyResourceResponse, + ): void; +} + +export interface GetHmacKeysOptions { + projectId?: string; + serviceAccountEmail?: string; + showDeletedKeys?: boolean; + autoPaginate?: boolean; + maxApiCalls?: number; + maxResults?: number; + pageToken?: string; + userProject?: string; +} + +export interface GetHmacKeysCallback { + ( + err: Error | null, + hmacKeys: HmacKey[] | null, + nextQuery?: {}, + apiResponse?: unknown, + ): void; +} + +export enum ExceptionMessages { + EXPIRATION_DATE_INVALID = 'The expiration date provided was invalid.', + EXPIRATION_DATE_PAST = 'An expiration date cannot be in the past.', +} + +export enum StorageExceptionMessages { + BUCKET_NAME_REQUIRED = 'A bucket name is needed to use Cloud Storage.', + BUCKET_NAME_REQUIRED_CREATE = 'A name is required to create a bucket.', + HMAC_SERVICE_ACCOUNT = 'The first argument must be a service account email to create an HMAC key.', + HMAC_ACCESS_ID = 'An access ID is needed to create an HmacKey object.', +} + +export type GetHmacKeysResponse = [HmacKey[]]; + +export const PROTOCOL_REGEX = /^(\w*):\/\//; + +/** + * Default behavior: Automatically retry retriable server errors. + * + * @const {boolean} + */ +export const AUTO_RETRY_DEFAULT = true; + +/** + * Default behavior: Only attempt to retry retriable errors 3 times. + * + * @const {number} + */ +export const MAX_RETRY_DEFAULT = 3; + +/** + * Default behavior: Wait twice as long as previous retry before retrying. + * + * @const {number} + */ +export const RETRY_DELAY_MULTIPLIER_DEFAULT = 2; + +/** + * Default behavior: If the operation doesn't succeed after 600 seconds, + * stop retrying. + * + * @const {number} + */ +export const TOTAL_TIMEOUT_DEFAULT = 600; + +/** + * Default behavior: Wait no more than 64 seconds between retries. + * + * @const {number} + */ +export const MAX_RETRY_DELAY_DEFAULT = 64; + +/** + * Default behavior: Retry conditionally idempotent operations if correct preconditions are set. + * + * @const {enum} + * @private + */ +const IDEMPOTENCY_STRATEGY_DEFAULT = IdempotencyStrategy.RetryConditional; + +/** + * Returns true if the API request should be retried, given the error that was + * given the first time the request was attempted. + * @const + * @param {error} err - The API error to check if it is appropriate to retry. + * @return {boolean} True if the API request should be retried, false otherwise. + */ +export const RETRYABLE_ERR_FN_DEFAULT = function (err?: ApiError) { + const isConnectionProblem = (reason: string) => { + return ( + reason.includes('eai_again') || // DNS lookup error + reason === 'econnreset' || + reason === 'unexpected connection closure' || + reason === 'epipe' || + reason === 'socket connection timeout' + ); + }; + + if (err) { + if ([408, 429, 500, 502, 503, 504].indexOf(err.code!) !== -1) { + return true; + } + + if (typeof err.code === 'string') { + if (['408', '429', '500', '502', '503', '504'].indexOf(err.code) !== -1) { + return true; + } + const reason = (err.code as string).toLowerCase(); + if (isConnectionProblem(reason)) { + return true; + } + } + + if (err.errors) { + for (const e of err.errors) { + const reason = e?.reason?.toString().toLowerCase(); + if (reason && isConnectionProblem(reason)) { + return true; + } + } + } + } + return false; +}; + +/*! Developer Documentation + * + * Invoke this method to create a new Storage object bound with pre-determined + * configuration options. For each object that can be created (e.g., a bucket), + * there is an equivalent static and instance method. While they are classes, + * they can be instantiated without use of the `new` keyword. + */ +/** + * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share objects with other + * users and allow other users to access your buckets and objects. + * + * This object provides constants to refer to the three permission levels that + * can be granted to an entity: + * + * - `gcs.acl.OWNER_ROLE` - ("OWNER") + * - `gcs.acl.READER_ROLE` - ("READER") + * - `gcs.acl.WRITER_ROLE` - ("WRITER") + * + * See {@link https://cloud.google.com/storage/docs/access-control/lists| About Access Control Lists} + * + * @name Storage#acl + * @type {object} + * @property {string} OWNER_ROLE + * @property {string} READER_ROLE + * @property {string} WRITER_ROLE + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * + * //- + * // Make all of the files currently in a bucket publicly readable. + * //- + * const options = { + * entity: 'allUsers', + * role: storage.acl.READER_ROLE + * }; + * + * albums.acl.add(options, function(err, aclObject) {}); + * + * //- + * // Make any new objects added to a bucket publicly readable. + * //- + * albums.acl.default.add(options, function(err, aclObject) {}); + * + * //- + * // Grant a user ownership permissions to a bucket. + * //- + * albums.acl.add({ + * entity: 'user-useremail@example.com', + * role: storage.acl.OWNER_ROLE + * }, function(err, aclObject) {}); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * albums.acl.add(options).then(function(data) { + * const aclObject = data[0]; + * const apiResponse = data[1]; + * }); + * ``` + */ +/** + * Get {@link Bucket} objects for all of the buckets in your project as + * a readable object stream. + * + * @method Storage#getBucketsStream + * @param {GetBucketsRequest} [query] Query object for listing buckets. + * @returns {ReadableStream} A readable stream that emits {@link Bucket} + * instances. + * + * @example + * ``` + * storage.getBucketsStream() + * .on('error', console.error) + * .on('data', function(bucket) { + * // bucket is a Bucket object. + * }) + * .on('end', function() { + * // All buckets retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getBucketsStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + * Get {@link HmacKey} objects for all of the HMAC keys in the project in a + * readable object stream. + * + * @method Storage#getHmacKeysStream + * @param {GetHmacKeysOptions} [options] Configuration options. + * @returns {ReadableStream} A readable stream that emits {@link HmacKey} + * instances. + * + * @example + * ``` + * storage.getHmacKeysStream() + * .on('error', console.error) + * .on('data', function(hmacKey) { + * // hmacKey is an HmacKey object. + * }) + * .on('end', function() { + * // All HmacKey retrieved. + * }); + * + * //- + * // If you anticipate many results, you can end a stream early to prevent + * // unnecessary processing and API requests. + * //- + * storage.getHmacKeysStream() + * .on('data', function(bucket) { + * this.end(); + * }); + * ``` + */ +/** + *

ACLs

+ * Cloud Storage uses access control lists (ACLs) to manage object and + * bucket access. ACLs are the mechanism you use to share files with other users + * and allow other users to access your buckets and files. + * + * To learn more about ACLs, read this overview on + * {@link https://cloud.google.com/storage/docs/access-control| Access Control}. + * + * See {@link https://cloud.google.com/storage/docs/overview| Cloud Storage overview} + * See {@link https://cloud.google.com/storage/docs/access-control| Access Control} + * + * @class + */ +export class Storage extends Service { + /** + * {@link Bucket} class. + * + * @name Storage.Bucket + * @see Bucket + * @type {Constructor} + */ + static Bucket: typeof Bucket = Bucket; + + /** + * {@link Channel} class. + * + * @name Storage.Channel + * @see Channel + * @type {Constructor} + */ + static Channel: typeof Channel = Channel; + + /** + * {@link File} class. + * + * @name Storage.File + * @see File + * @type {Constructor} + */ + static File: typeof File = File; + + /** + * {@link HmacKey} class. + * + * @name Storage.HmacKey + * @see HmacKey + * @type {Constructor} + */ + static HmacKey: typeof HmacKey = HmacKey; + + static acl = { + OWNER_ROLE: 'OWNER', + READER_ROLE: 'READER', + WRITER_ROLE: 'WRITER', + }; + + /** + * Reference to {@link Storage.acl}. + * + * @name Storage#acl + * @see Storage.acl + */ + acl: typeof Storage.acl; + + crc32cGenerator: CRC32CValidatorGenerator; + + getBucketsStream(): Readable { + // placeholder body, overwritten in constructor + return new Readable(); + } + + getHmacKeysStream(): Readable { + // placeholder body, overwritten in constructor + return new Readable(); + } + + retryOptions: RetryOptions; + + /** + * @callback Crc32cGeneratorToStringCallback + * A method returning the CRC32C as a base64-encoded string. + * + * @returns {string} + * + * @example + * Hashing the string 'data' should return 'rth90Q==' + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.toString(); // 'rth90Q==' + * ``` + **/ + /** + * @callback Crc32cGeneratorValidateCallback + * A method validating a base64-encoded CRC32C string. + * + * @param {string} [value] base64-encoded CRC32C string to validate + * @returns {boolean} + * + * @example + * Should return `true` if the value matches, `false` otherwise + * + * ```js + * const buffer = Buffer.from('data'); + * crc32c.update(buffer); + * crc32c.validate('DkjKuA=='); // false + * crc32c.validate('rth90Q=='); // true + * ``` + **/ + /** + * @callback Crc32cGeneratorUpdateCallback + * A method for passing `Buffer`s for CRC32C generation. + * + * @param {Buffer} [data] data to update CRC32C value with + * @returns {undefined} + * + * @example + * Hashing buffers from 'some ' and 'text\n' + * + * ```js + * const buffer1 = Buffer.from('some '); + * crc32c.update(buffer1); + * + * const buffer2 = Buffer.from('text\n'); + * crc32c.update(buffer2); + * + * crc32c.toString(); // 'DkjKuA==' + * ``` + **/ + /** + * @typedef {object} CRC32CValidator + * @property {Crc32cGeneratorToStringCallback} + * @property {Crc32cGeneratorValidateCallback} + * @property {Crc32cGeneratorUpdateCallback} + */ + /** + * @callback Crc32cGeneratorCallback + * @returns {CRC32CValidator} + */ + /** + * @typedef {object} StorageOptions + * @property {string} [projectId] The project ID from the Google 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://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application + * Application Default Credentials}, your project ID will be detected + * automatically. + * @property {string} [keyFilename] Full path to the a .json, .pem, or .p12 key + * downloaded from the Google Developers Console. If you provide a path to + * a JSON file, the `projectId` option above is not necessary. NOTE: .pem and + * .p12 require you to specify the `email` option as well. + * @property {string} [email] Account email address. Required when using a .pem + * or .p12 keyFilename. + * @property {object} [credentials] Credentials object. + * @property {string} [credentials.client_email] + * @property {string} [credentials.private_key] + * @property {object} [retryOptions] Options for customizing retries. Retriable server errors + * will be retried with exponential delay between them dictated by the formula + * max(maxRetryDelay, retryDelayMultiplier*retryNumber) until maxRetries or totalTimeout + * has been reached. Retries will only happen if autoRetry is set to true. + * @property {boolean} [retryOptions.autoRetry=true] Automatically retry requests if the + * response is related to rate limits or certain intermittent server + * errors. We will exponentially backoff subsequent requests by default. + * @property {number} [retryOptions.retryDelayMultiplier = 2] the multiplier by which to + * increase the delay time between the completion of failed requests, and the + * initiation of the subsequent retrying request. + * @property {number} [retryOptions.totalTimeout = 600] The total time, starting from + * when the initial request is sent, after which an error will + * be returned, regardless of the retrying attempts made meanwhile. + * @property {number} [retryOptions.maxRetryDelay = 64] The maximum delay time between requests. + * When this value is reached, ``retryDelayMultiplier`` will no longer be used to + * increase delay time. + * @property {number} [retryOptions.maxRetries=3] Maximum number of automatic retries + * attempted before returning the error. + * @property {function} [retryOptions.retryableErrorFn] Function that returns true if a given + * error should be retried and false otherwise. + * @property {enum} [retryOptions.idempotencyStrategy=IdempotencyStrategy.RetryConditional] Enumeration + * controls how conditionally idempotent operations are retried. Possible values are: RetryAlways - + * will respect other retry settings and attempt to retry conditionally idempotent operations. RetryConditional - + * will retry conditionally idempotent operations if the correct preconditions are set. RetryNever - never + * retry a conditionally idempotent operation. + * @property {string} [userAgent] The value to be prepended to the User-Agent + * header in API requests. + * @property {object} [authClient] `AuthClient` or `GoogleAuth` client to reuse instead of creating a new one. + * @property {number} [timeout] The amount of time in milliseconds to wait per http request before timing out. + * @property {object[]} [interceptors_] Array of custom request interceptors to be returned in the order they were assigned. + * @property {string} [apiEndpoint = storage.google.com] The API endpoint of the service used to make requests. + * @property {boolean} [useAuthWithCustomEndpoint = false] Controls whether or not to use authentication when using a custom endpoint. + * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C} + */ + /** + * Constructs the Storage client. + * + * @example + * Create a client that uses Application Default Credentials + * (ADC) + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * ``` + * + * @example + * Create a client with explicit credentials + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * keyFilename: '/path/to/keyfile.json' + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by value as a JavaScript object + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: { + * type: 'service_account', + * project_id: 'xxxxxxx', + * private_key_id: 'xxxx', + * private_key:'-----BEGIN PRIVATE KEY-----xxxxxxx\n-----END PRIVATE KEY-----\n', + * client_email: 'xxxx', + * client_id: 'xxx', + * auth_uri: 'https://accounts.google.com/o/oauth2/auth', + * token_uri: 'https://oauth2.googleapis.com/token', + * auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs', + * client_x509_cert_url: 'xxx', + * } + * }); + * ``` + * + * @example + * Create a client with credentials passed + * by loading a JSON file directly from disk + * ``` + * const storage = new Storage({ + * projectId: 'your-project-id', + * credentials: require('/path/to-keyfile.json') + * }); + * ``` + * + * @example + * Create a client with an `AuthClient` (e.g. `DownscopedClient`) + * ``` + * const {DownscopedClient} = require('google-auth-library'); + * const authClient = new DownscopedClient({...}); + * + * const storage = new Storage({authClient}); + * ``` + * + * Additional samples: + * - https://github.com/googleapis/google-auth-library-nodejs#sample-usage-1 + * - https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js + * + * @param {StorageOptions} [options] Configuration options. + */ + constructor(options: StorageOptions = {}) { + const universe = options.universeDomain || DEFAULT_UNIVERSE; + + let apiEndpoint = `https://storage.${universe}`; + let customEndpoint = false; + + // Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead. + const EMULATOR_HOST = process.env.STORAGE_EMULATOR_HOST; + if (typeof EMULATOR_HOST === 'string') { + apiEndpoint = Storage.sanitizeEndpoint(EMULATOR_HOST); + customEndpoint = true; + } + + if (options.apiEndpoint && options.apiEndpoint !== apiEndpoint) { + apiEndpoint = Storage.sanitizeEndpoint(options.apiEndpoint); + customEndpoint = true; + } + + options = Object.assign({}, options, {apiEndpoint}); + + // Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead. + const baseUrl = EMULATOR_HOST || `${options.apiEndpoint}/storage/v1`; + + const config = { + apiEndpoint: options.apiEndpoint!, + retryOptions: { + autoRetry: + options.retryOptions?.autoRetry !== undefined + ? options.retryOptions?.autoRetry + : AUTO_RETRY_DEFAULT, + maxRetries: options.retryOptions?.maxRetries + ? options.retryOptions?.maxRetries + : MAX_RETRY_DEFAULT, + retryDelayMultiplier: options.retryOptions?.retryDelayMultiplier + ? options.retryOptions?.retryDelayMultiplier + : RETRY_DELAY_MULTIPLIER_DEFAULT, + totalTimeout: options.retryOptions?.totalTimeout + ? options.retryOptions?.totalTimeout + : TOTAL_TIMEOUT_DEFAULT, + maxRetryDelay: options.retryOptions?.maxRetryDelay + ? options.retryOptions?.maxRetryDelay + : MAX_RETRY_DELAY_DEFAULT, + retryableErrorFn: options.retryOptions?.retryableErrorFn + ? options.retryOptions?.retryableErrorFn + : RETRYABLE_ERR_FN_DEFAULT, + idempotencyStrategy: + options.retryOptions?.idempotencyStrategy !== undefined + ? options.retryOptions?.idempotencyStrategy + : IDEMPOTENCY_STRATEGY_DEFAULT, + }, + baseUrl, + customEndpoint, + useAuthWithCustomEndpoint: options?.useAuthWithCustomEndpoint, + projectIdRequired: false, + scopes: [ + 'https://www.googleapis.com/auth/iam', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/devstorage.full_control', + ], + packageJson: getPackageJSON(), + }; + + super(config, options); + + /** + * Reference to {@link Storage.acl}. + * + * @name Storage#acl + * @see Storage.acl + */ + this.acl = Storage.acl; + this.crc32cGenerator = + options.crc32cGenerator || CRC32C_DEFAULT_VALIDATOR_GENERATOR; + + this.retryOptions = config.retryOptions; + + this.getBucketsStream = paginator.streamify('getBuckets'); + this.getHmacKeysStream = paginator.streamify('getHmacKeys'); + } + + private static sanitizeEndpoint(url: string) { + if (!PROTOCOL_REGEX.test(url)) { + url = `https://${url}`; + } + return url.replace(/\/+$/, ''); // Remove trailing slashes + } + + /** + * Get a reference to a Cloud Storage bucket. + * + * @param {string} name Name of the bucket. + * @param {object} [options] Configuration object. + * @param {string} [options.kmsKeyName] A Cloud KMS key that will be used to + * encrypt objects inserted into this bucket, if no encryption method is + * specified. + * @param {string} [options.userProject] User project to be billed for all + * requests made from this Bucket object. + * @returns {Bucket} + * @see Bucket + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const albums = storage.bucket('albums'); + * const photos = storage.bucket('photos'); + * ``` + */ + bucket(name: string, options?: BucketOptions) { + if (!name) { + throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED); + } + return new Bucket(this, name, options); + } + + /** + * Reference a channel to receive notifications about changes to your bucket. + * + * @param {string} id The ID of the channel. + * @param {string} resourceId The resource ID of the channel. + * @returns {Channel} + * @see Channel + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const channel = storage.channel('id', 'resource-id'); + * ``` + */ + channel(id: string, resourceId: string) { + return new Channel(this, id, resourceId); + } + + createBucket( + name: string, + metadata?: CreateBucketRequest, + ): Promise; + createBucket(name: string, callback: BucketCallback): void; + createBucket( + name: string, + metadata: CreateBucketRequest, + callback: BucketCallback, + ): void; + createBucket( + name: string, + metadata: CreateBucketRequest, + callback: BucketCallback, + ): void; + /** + * @typedef {array} CreateBucketResponse + * @property {Bucket} 0 The new {@link Bucket}. + * @property {object} 1 The full API response. + */ + /** + * @callback CreateBucketCallback + * @param {?Error} err Request error, if any. + * @param {Bucket} bucket The new {@link Bucket}. + * @param {object} apiResponse The full API response. + */ + /** + * Metadata to set for the bucket. + * + * @typedef {object} CreateBucketRequest + * @property {boolean} [archive=false] Specify the storage class as Archive. + * @property {object} [autoclass.enabled=false] Specify whether Autoclass is + * enabled for the bucket. + * @property {object} [autoclass.terminalStorageClass='NEARLINE'] The storage class that objects in an Autoclass bucket eventually transition to if + * they are not read for a certain length of time. Valid values are NEARLINE and ARCHIVE. + * @property {boolean} [coldline=false] Specify the storage class as Coldline. + * @property {Cors[]} [cors=[]] Specify the CORS configuration to use. + * @property {CustomPlacementConfig} [customPlacementConfig={}] Specify the bucket's regions for dual-region buckets. + * For more information, see {@link https://cloud.google.com/storage/docs/locations| Bucket Locations}. + * @property {boolean} [dra=false] Specify the storage class as Durable Reduced + * Availability. + * @property {boolean} [enableObjectRetention=false] Specify whether or not object retention should be enabled on this bucket. + * @property {object} [hierarchicalNamespace.enabled=false] Specify whether or not to enable hierarchical namespace on this bucket. + * @property {string} [location] Specify the bucket's location. If specifying + * a dual-region, the `customPlacementConfig` property should be set in conjunction. + * For more information, see {@link https://cloud.google.com/storage/docs/locations| Bucket Locations}. + * @property {boolean} [multiRegional=false] Specify the storage class as + * Multi-Regional. + * @property {boolean} [nearline=false] Specify the storage class as Nearline. + * @property {boolean} [regional=false] Specify the storage class as Regional. + * @property {boolean} [requesterPays=false] Force the use of the User Project metadata field to assign operational + * costs when an operation is made on a Bucket and its objects. + * @property {string} [rpo] For dual-region buckets, controls whether turbo + * replication is enabled (`ASYNC_TURBO`) or disabled (`DEFAULT`). + * @property {boolean} [standard=true] Specify the storage class as Standard. + * @property {string} [storageClass] The new storage class. (`standard`, + * `nearline`, `coldline`, or `archive`). + * **Note:** The storage classes `multi_regional`, `regional`, and + * `durable_reduced_availability` are now legacy and will be deprecated in + * the future. + * @property {Versioning} [versioning=undefined] Specify the versioning status. + * @property {string} [userProject] The ID of the project which will be billed + * for the request. + */ + /** + * Create a bucket. + * + * Cloud Storage uses a flat namespace, so you can't create a bucket with + * a name that is already in use. For more information, see + * {@link https://cloud.google.com/storage/docs/bucketnaming.html#requirements| Bucket Naming Guidelines}. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/insert| Buckets: insert API Documentation} + * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes} + * + * @param {string} name Name of the bucket to create. + * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket. + * @param {CreateBucketCallback} [callback] Callback function. + * @returns {Promise} + * @throws {Error} If a name is not provided. + * @see Bucket#create + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const callback = function(err, bucket, apiResponse) { + * // `bucket` is a Bucket object. + * }; + * + * storage.createBucket('new-bucket', callback); + * + * //- + * // Create a bucket in a specific location and region. See the + * // Official JSON API docs for complete details on the `location` + * option. + * // + * //- + * const metadata = { + * location: 'US-CENTRAL1', + * regional: true + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // Create a bucket with a retention policy of 6 months. + * //- + * const metadata = { + * retentionPolicy: { + * retentionPeriod: 15780000 // 6 months in seconds. + * } + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // Enable versioning on a new bucket. + * //- + * const metadata = { + * versioning: { + * enabled: true + * } + * }; + * + * storage.createBucket('new-bucket', metadata, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.createBucket('new-bucket').then(function(data) { + * const bucket = data[0]; + * const apiResponse = data[1]; + * }); + * + * ``` + * @example
+ * region_tag:storage_create_bucket + * Another example: + */ + createBucket( + name: string, + metadataOrCallback?: BucketCallback | CreateBucketRequest, + callback?: BucketCallback, + ): Promise | void { + if (!name) { + throw new Error(StorageExceptionMessages.BUCKET_NAME_REQUIRED_CREATE); + } + + let metadata: CreateBucketRequest; + if (!callback) { + callback = metadataOrCallback as BucketCallback; + metadata = {}; + } else { + metadata = metadataOrCallback as CreateBucketRequest; + } + + const body: CreateBucketRequest & {[index: string]: string | {} | null} = { + ...metadata, + name, + }; + + const storageClasses = { + archive: 'ARCHIVE', + coldline: 'COLDLINE', + dra: 'DURABLE_REDUCED_AVAILABILITY', + multiRegional: 'MULTI_REGIONAL', + nearline: 'NEARLINE', + regional: 'REGIONAL', + standard: 'STANDARD', + } as const; + const storageClassKeys = Object.keys( + storageClasses, + ) as (keyof typeof storageClasses)[]; + + for (const storageClass of storageClassKeys) { + if (body[storageClass]) { + if (metadata.storageClass && metadata.storageClass !== storageClass) { + throw new Error( + `Both \`${storageClass}\` and \`storageClass\` were provided.`, + ); + } + body.storageClass = storageClasses[storageClass]; + delete body[storageClass]; + } + } + + if (body.requesterPays) { + body.billing = { + requesterPays: body.requesterPays, + }; + delete body.requesterPays; + } + + const query = { + project: this.projectId, + } as CreateBucketQuery; + + if (body.userProject) { + query.userProject = body.userProject as string; + delete body.userProject; + } + + if (body.enableObjectRetention) { + query.enableObjectRetention = body.enableObjectRetention; + delete body.enableObjectRetention; + } + + if (body.predefinedAcl) { + query.predefinedAcl = body.predefinedAcl; + delete body.predefinedAcl; + } + + if (body.predefinedDefaultObjectAcl) { + query.predefinedDefaultObjectAcl = body.predefinedDefaultObjectAcl; + delete body.predefinedDefaultObjectAcl; + } + + if (body.projection) { + query.projection = body.projection; + delete body.projection; + } + + this.request( + { + method: 'POST', + uri: '/b', + qs: query, + json: body, + }, + (err, resp) => { + if (err) { + callback!(err, null, resp); + return; + } + + const bucket = this.bucket(name); + bucket.metadata = resp; + + callback!(null, bucket, resp); + }, + ); + } + + createHmacKey( + serviceAccountEmail: string, + options?: CreateHmacKeyOptions, + ): Promise; + createHmacKey( + serviceAccountEmail: string, + callback: CreateHmacKeyCallback, + ): void; + createHmacKey( + serviceAccountEmail: string, + options: CreateHmacKeyOptions, + callback: CreateHmacKeyCallback, + ): void; + /** + * @typedef {object} CreateHmacKeyOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {object} HmacKeyMetadata + * @property {string} accessId The access id identifies which HMAC key was + * used to sign a request when authenticating with HMAC. + * @property {string} etag Used to perform a read-modify-write of the key. + * @property {string} id The resource name of the HMAC key. + * @property {string} projectId The project ID. + * @property {string} serviceAccountEmail The service account's email this + * HMAC key is created for. + * @property {string} state The state of this HMAC key. One of "ACTIVE", + * "INACTIVE" or "DELETED". + * @property {string} timeCreated The creation time of the HMAC key in + * RFC 3339 format. + * @property {string} [updated] The time this HMAC key was last updated in + * RFC 3339 format. + */ + /** + * @typedef {array} CreateHmacKeyResponse + * @property {HmacKey} 0 The HmacKey instance created from API response. + * @property {string} 1 The HMAC key's secret used to access the XML API. + * @property {object} 3 The raw API response. + */ + /** + * @callback CreateHmacKeyCallback Callback function. + * @param {?Error} err Request error, if any. + * @param {HmacKey} hmacKey The HmacKey instance created from API response. + * @param {string} secret The HMAC key's secret used to access the XML API. + * @param {object} apiResponse The raw API response. + */ + /** + * Create an HMAC key associated with an service account to authenticate + * requests to the Cloud Storage XML API. + * + * See {@link https://cloud.google.com/storage/docs/authentication/hmackeys| HMAC keys documentation} + * + * @param {string} serviceAccountEmail The service account's email address + * with which the HMAC key is created for. + * @param {CreateHmacKeyCallback} [callback] Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('google-cloud/storage'); + * const storage = new Storage(); + * + * // Replace with your service account's email address + * const serviceAccountEmail = + * 'my-service-account@appspot.gserviceaccount.com'; + * + * storage.createHmacKey(serviceAccountEmail, function(err, hmacKey, secret) { + * if (!err) { + * // Securely store the secret for use with the XML API. + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.createHmacKey(serviceAccountEmail) + * .then((response) => { + * const hmacKey = response[0]; + * const secret = response[1]; + * // Securely store the secret for use with the XML API. + * }); + * ``` + */ + createHmacKey( + serviceAccountEmail: string, + optionsOrCb?: CreateHmacKeyOptions | CreateHmacKeyCallback, + cb?: CreateHmacKeyCallback, + ): Promise | void { + if (typeof serviceAccountEmail !== 'string') { + throw new Error(StorageExceptionMessages.HMAC_SERVICE_ACCOUNT); + } + + const {options, callback} = normalize< + CreateHmacKeyOptions, + CreateHmacKeyCallback + >(optionsOrCb, cb); + const query = Object.assign({}, options, {serviceAccountEmail}); + const projectId = query.projectId || this.projectId; + delete query.projectId; + + this.request( + { + method: 'POST', + uri: `/projects/${projectId}/hmacKeys`, + qs: query, + maxRetries: 0, //explicitly set this value since this is a non-idempotent function + }, + (err, resp: HmacKeyResourceResponse) => { + if (err) { + callback!(err, null, null, resp); + return; + } + + const metadata = resp.metadata; + const hmacKey = this.hmacKey(metadata.accessId!, { + projectId: metadata.projectId, + }); + hmacKey.metadata = resp.metadata; + + callback!(null, hmacKey, resp.secret, resp); + }, + ); + } + + getBuckets(options?: GetBucketsRequest): Promise; + getBuckets(options: GetBucketsRequest, callback: GetBucketsCallback): void; + getBuckets(callback: GetBucketsCallback): void; + /** + * Query object for listing buckets. + * + * @typedef {object} GetBucketsRequest + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [userProject] The ID of the project which will be billed + * for the request. + * @param {boolean} [softDeleted] If true, returns the soft-deleted object. + * Object `generation` is required if `softDeleted` is set to True. + */ + /** + * @typedef {array} GetBucketsResponse + * @property {Bucket[]} 0 Array of {@link Bucket} instances. + * @property {object} 1 nextQuery A query object to receive more results. + * @property {object} 2 The full API response. + */ + /** + * @callback GetBucketsCallback + * @param {?Error} err Request error, if any. + * @param {Bucket[]} buckets Array of {@link Bucket} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Get Bucket objects for all of the buckets in your project. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/list| Buckets: list API Documentation} + * + * @param {GetBucketsRequest} [query] Query object for listing buckets. + * @param {GetBucketsCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * storage.getBuckets(function(err, buckets) { + * if (!err) { + * // buckets is an array of Bucket objects. + * } + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, buckets, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * storage.getBuckets(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * buckets[0].metadata; + * + * // However, in cases where you are concerned the metadata could have + * // changed, use the `getMetadata` method. + * buckets[0].getMetadata(function(err, metadata, apiResponse) {}); + * }; + * + * storage.getBuckets({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getBuckets().then(function(data) { + * const buckets = data[0]; + * }); + * + * ``` + * @example + * region_tag:storage_list_buckets + * Another example: + */ + getBuckets( + optionsOrCallback?: GetBucketsRequest | GetBucketsCallback, + cb?: GetBucketsCallback, + ): void | Promise { + const {options, callback} = normalize( + optionsOrCallback, + cb, + ); + options.project = options.project || this.projectId; + + this.request( + { + uri: '/b', + qs: options, + }, + (err, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + + const itemsArray = resp.items ? resp.items : []; + const unreachableArray = resp.unreachable ? resp.unreachable : []; + + const buckets = itemsArray.map((bucket: BucketMetadata) => { + const bucketInstance = this.bucket(bucket.id!); + bucketInstance.metadata = bucket; + + return bucketInstance; + }); + + if (unreachableArray.length > 0) { + unreachableArray.forEach((fullPath: string) => { + const name = fullPath.split('/').pop(); + if (name) { + const placeholder = this.bucket(name); + placeholder.unreachable = true; + placeholder.metadata = {}; + buckets.push(placeholder); + } + }); + } + + const nextQuery = resp.nextPageToken + ? Object.assign({}, options, {pageToken: resp.nextPageToken}) + : null; + + callback(null, buckets, nextQuery, resp); + }, + ); + } + + /** + * Query object for listing HMAC keys. + * + * @typedef {object} GetHmacKeysOptions + * @property {string} [projectId] The project ID of the project that owns + * the service account of the requested HMAC key. If not provided, + * the project ID used to instantiate the Storage client will be used. + * @property {string} [serviceAccountEmail] If present, only HMAC keys for the + * given service account are returned. + * @property {boolean} [showDeletedKeys=false] If true, include keys in the DELETE + * state. Default is false. + * @property {boolean} [autoPaginate=true] Have pagination handled + * automatically. + * @property {number} [maxApiCalls] Maximum number of API calls to make. + * @property {number} [maxResults] Maximum number of items plus prefixes to + * return per call. + * Note: By default will handle pagination automatically + * if more than 1 page worth of results are requested per call. + * When `autoPaginate` is set to `false` the smaller of `maxResults` + * or 1 page of results will be returned per call. + * @property {string} [pageToken] A previously-returned page token + * representing part of the larger set of results to view. + * @property {string} [userProject] This parameter is currently ignored. + */ + /** + * @typedef {array} GetHmacKeysResponse + * @property {HmacKey[]} 0 Array of {@link HmacKey} instances. + * @param {object} nextQuery 1 A query object to receive more results. + * @param {object} apiResponse 2 The full API response. + */ + /** + * @callback GetHmacKeysCallback + * @param {?Error} err Request error, if any. + * @param {HmacKey[]} hmacKeys Array of {@link HmacKey} instances. + * @param {object} nextQuery A query object to receive more results. + * @param {object} apiResponse The full API response. + */ + /** + * Retrieves a list of HMAC keys matching the criteria. + * + * The authenticated user must have storage.hmacKeys.list permission for the project in which the key exists. + * + * @param {GetHmacKeysOption} options Configuration options. + * @param {GetHmacKeysCallback} callback Callback function. + * @return {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * storage.getHmacKeys(function(err, hmacKeys) { + * if (!err) { + * // hmacKeys is an array of HmacKey objects. + * } + * }); + * + * //- + * // To control how many API requests are made and page through the results + * // manually, set `autoPaginate` to `false`. + * //- + * const callback = function(err, hmacKeys, nextQuery, apiResponse) { + * if (nextQuery) { + * // More results exist. + * storage.getHmacKeys(nextQuery, callback); + * } + * + * // The `metadata` property is populated for you with the metadata at the + * // time of fetching. + * hmacKeys[0].metadata; + * }; + * + * storage.getHmacKeys({ + * autoPaginate: false + * }, callback); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getHmacKeys().then(function(data) { + * const hmacKeys = data[0]; + * }); + * ``` + */ + getHmacKeys(options?: GetHmacKeysOptions): Promise; + getHmacKeys(callback: GetHmacKeysCallback): void; + getHmacKeys(options: GetHmacKeysOptions, callback: GetHmacKeysCallback): void; + getHmacKeys( + optionsOrCb?: GetHmacKeysOptions | GetHmacKeysCallback, + cb?: GetHmacKeysCallback, + ): Promise | void { + const {options, callback} = normalize(optionsOrCb, cb); + const query = Object.assign({}, options); + const projectId = query.projectId || this.projectId; + delete query.projectId; + + this.request( + { + uri: `/projects/${projectId}/hmacKeys`, + qs: query, + }, + (err, resp) => { + if (err) { + callback(err, null, null, resp); + return; + } + + const itemsArray = resp.items ? resp.items : []; + const hmacKeys = itemsArray.map((hmacKey: HmacKeyMetadata) => { + const hmacKeyInstance = this.hmacKey(hmacKey.accessId!, { + projectId: hmacKey.projectId, + }); + hmacKeyInstance.metadata = hmacKey; + return hmacKeyInstance; + }); + + const nextQuery = resp.nextPageToken + ? Object.assign({}, options, {pageToken: resp.nextPageToken}) + : null; + + callback(null, hmacKeys, nextQuery, resp); + }, + ); + } + + getServiceAccount( + options?: GetServiceAccountOptions, + ): Promise; + getServiceAccount( + options?: GetServiceAccountOptions, + ): Promise; + getServiceAccount( + options: GetServiceAccountOptions, + callback: GetServiceAccountCallback, + ): void; + getServiceAccount(callback: GetServiceAccountCallback): void; + /** + * @typedef {array} GetServiceAccountResponse + * @property {object} 0 The service account resource. + * @property {object} 1 The full + * {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| API response}. + */ + /** + * @callback GetServiceAccountCallback + * @param {?Error} err Request error, if any. + * @param {object} serviceAccount The serviceAccount resource. + * @param {string} serviceAccount.emailAddress The service account email + * address. + * @param {object} apiResponse The full + * {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| API response}. + */ + /** + * Get the email address of this project's Google Cloud Storage service + * account. + * + * See {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount/get| Projects.serviceAccount: get API Documentation} + * See {@link https://cloud.google.com/storage/docs/json_api/v1/projects/serviceAccount#resource| Projects.serviceAccount Resource} + * + * @param {object} [options] Configuration object. + * @param {string} [options.userProject] User project to be billed for this + * request. + * @param {GetServiceAccountCallback} [callback] Callback function. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * + * storage.getServiceAccount(function(err, serviceAccount, apiResponse) { + * if (!err) { + * const serviceAccountEmail = serviceAccount.emailAddress; + * } + * }); + * + * //- + * // If the callback is omitted, we'll return a Promise. + * //- + * storage.getServiceAccount().then(function(data) { + * const serviceAccountEmail = data[0].emailAddress; + * const apiResponse = data[1]; + * }); + * ``` + */ + getServiceAccount( + optionsOrCallback?: GetServiceAccountOptions | GetServiceAccountCallback, + cb?: GetServiceAccountCallback, + ): void | Promise { + const {options, callback} = normalize( + optionsOrCallback, + cb, + ); + this.request( + { + uri: `/projects/${this.projectId}/serviceAccount`, + qs: options, + }, + (err, resp) => { + if (err) { + callback(err, null, resp); + return; + } + + const camelCaseResponse = {} as {[index: string]: string}; + + for (const prop in resp) { + // eslint-disable-next-line no-prototype-builtins + if (resp.hasOwnProperty(prop)) { + const camelCaseProp = prop.replace(/_(\w)/g, (_, match) => + match.toUpperCase(), + ); + camelCaseResponse[camelCaseProp] = resp[prop]; + } + } + + callback(null, camelCaseResponse, resp); + }, + ); + } + + /** + * Get a reference to an HmacKey object. + * Note: this does not fetch the HMAC key's metadata. Use HmacKey#get() to + * retrieve and populate the metadata. + * + * To get a reference to an HMAC key that's not created for a service + * account in the same project used to instantiate the Storage client, + * supply the project's ID as `projectId` in the `options` argument. + * + * @param {string} accessId The HMAC key's access ID. + * @param {HmacKeyOptions} options HmacKey constructor options. + * @returns {HmacKey} + * @see HmacKey + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const hmacKey = storage.hmacKey('ACCESS_ID'); + * ``` + */ + hmacKey(accessId: string, options?: HmacKeyOptions) { + if (!accessId) { + throw new Error(StorageExceptionMessages.HMAC_ACCESS_ID); + } + + return new HmacKey(this, accessId, options); + } +} + +/*! Developer Documentation + * + * These methods can be auto-paginated. + */ +paginator.extend(Storage, ['getBuckets', 'getHmacKeys']); + +/*! Developer Documentation + * + * All async methods (except for streams) will return a Promise in the event + * that a callback is omitted. + */ +promisifyAll(Storage, { + exclude: ['bucket', 'channel', 'hmacKey'], +}); diff --git a/handwritten/storage/src/transfer-manager.ts b/handwritten/storage/src/transfer-manager.ts new file mode 100644 index 00000000000..be34c76f08e --- /dev/null +++ b/handwritten/storage/src/transfer-manager.ts @@ -0,0 +1,870 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 {Bucket, UploadOptions, UploadResponse} from './bucket.js'; +import { + DownloadOptions, + DownloadResponse, + File, + FileExceptionMessages, + RequestError, +} from './file.js'; +import pLimit from 'p-limit'; +import * as path from 'path'; +import {createReadStream, existsSync, promises as fsp} from 'fs'; +import {CRC32C} from './crc32c.js'; +import {GoogleAuth} from 'google-auth-library'; +import {XMLParser, XMLBuilder} from 'fast-xml-parser'; +import AsyncRetry from 'async-retry'; +import {ApiError} from './nodejs-common/index.js'; +import {GaxiosResponse, Headers} from 'gaxios'; +import {createHash} from 'crypto'; +import {GCCL_GCS_CMD_KEY} from './nodejs-common/util.js'; +import {getRuntimeTrackingString, getUserAgentString} from './util.js'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import {getPackageJSON} from './package-json-helper.cjs'; + +const packageJson = getPackageJSON(); + +/** + * Default number of concurrently executing promises to use when calling uploadManyFiles. + * + */ +const DEFAULT_PARALLEL_UPLOAD_LIMIT = 5; +/** + * Default number of concurrently executing promises to use when calling downloadManyFiles. + * + */ +const DEFAULT_PARALLEL_DOWNLOAD_LIMIT = 5; +/** + * Default number of concurrently executing promises to use when calling downloadFileInChunks. + * + */ +const DEFAULT_PARALLEL_CHUNKED_DOWNLOAD_LIMIT = 5; +/** + * The minimum size threshold in bytes at which to apply a chunked download strategy when calling downloadFileInChunks. + * + */ +const DOWNLOAD_IN_CHUNKS_FILE_SIZE_THRESHOLD = 32 * 1024 * 1024; +/** + * The chunk size in bytes to use when calling downloadFileInChunks. + * + */ +const DOWNLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024; +/** + * The chunk size in bytes to use when calling uploadFileInChunks. + * + */ +const UPLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024; +/** + * Default number of concurrently executing promises to use when calling uploadFileInChunks. + * + */ +const DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT = 5; + +const EMPTY_REGEX = '(?:)'; + +/** + * The `gccl-gcs-cmd` value for the `X-Goog-API-Client` header. + * Example: `gccl-gcs-cmd/tm.upload_many` + * + * @see {@link GCCL_GCS_CMD}. + * @see {@link GCCL_GCS_CMD_KEY}. + */ +const GCCL_GCS_CMD_FEATURE = { + UPLOAD_MANY: 'tm.upload_many', + DOWNLOAD_MANY: 'tm.download_many', + UPLOAD_SHARDED: 'tm.upload_sharded', + DOWNLOAD_SHARDED: 'tm.download_sharded', +}; + +export interface UploadManyFilesOptions { + concurrencyLimit?: number; + customDestinationBuilder?( + path: string, + options: UploadManyFilesOptions, + ): string; + skipIfExists?: boolean; + prefix?: string; + passthroughOptions?: Omit; +} + +export interface DownloadManyFilesOptions { + concurrencyLimit?: number; + prefix?: string; + stripPrefix?: string; + passthroughOptions?: DownloadOptions; + skipIfExists?: boolean; +} + +export interface DownloadFileInChunksOptions { + concurrencyLimit?: number; + chunkSizeBytes?: number; + destination?: string; + validation?: 'crc32c' | false; + noReturnData?: boolean; +} + +export interface UploadFileInChunksOptions { + concurrencyLimit?: number; + chunkSizeBytes?: number; + uploadName?: string; + maxQueueSize?: number; + uploadId?: string; + autoAbortFailure?: boolean; + partsMap?: Map; + validation?: 'md5' | false; + headers?: {[key: string]: string}; +} + +export interface MultiPartUploadHelper { + bucket: Bucket; + fileName: string; + uploadId?: string; + partsMap?: Map; + initiateUpload(headers?: {[key: string]: string}): Promise; + uploadPart( + partNumber: number, + chunk: Buffer, + validation?: 'md5' | false, + ): Promise; + completeUpload(): Promise; + abortUpload(): Promise; +} + +export type MultiPartHelperGenerator = ( + bucket: Bucket, + fileName: string, + uploadId?: string, + partsMap?: Map, +) => MultiPartUploadHelper; + +const defaultMultiPartGenerator: MultiPartHelperGenerator = ( + bucket, + fileName, + uploadId, + partsMap, +) => { + return new XMLMultiPartUploadHelper(bucket, fileName, uploadId, partsMap); +}; + +export class MultiPartUploadError extends Error { + private uploadId: string; + private partsMap: Map; + + constructor( + message: string, + uploadId: string, + partsMap: Map, + ) { + super(message); + this.uploadId = uploadId; + this.partsMap = partsMap; + } +} +/** + * Class representing an implementation of MPU in the XML API. This class is not meant for public usage. + * + * @private + * + */ +class XMLMultiPartUploadHelper implements MultiPartUploadHelper { + public partsMap; + public uploadId; + public bucket; + public fileName; + + private authClient; + private xmlParser; + private xmlBuilder; + private baseUrl; + private retryOptions; + + constructor( + bucket: Bucket, + fileName: string, + uploadId?: string, + partsMap?: Map, + ) { + this.authClient = bucket.storage.authClient || new GoogleAuth(); + this.uploadId = uploadId || ''; + this.bucket = bucket; + this.fileName = fileName; + this.baseUrl = `https://${bucket.name}.${ + new URL(this.bucket.storage.apiEndpoint).hostname + }/${fileName}`; + this.xmlBuilder = new XMLBuilder({arrayNodeName: 'Part'}); + this.xmlParser = new XMLParser(); + this.partsMap = partsMap || new Map(); + this.retryOptions = { + retries: this.bucket.storage.retryOptions.maxRetries, + factor: this.bucket.storage.retryOptions.retryDelayMultiplier, + maxTimeout: this.bucket.storage.retryOptions.maxRetryDelay! * 1000, + maxRetryTime: this.bucket.storage.retryOptions.totalTimeout! * 1000, + }; + } + + #setGoogApiClientHeaders(headers: Headers = {}): Headers { + let headerFound = false; + let userAgentFound = false; + + for (const [key, value] of Object.entries(headers)) { + if (key.toLocaleLowerCase().trim() === 'x-goog-api-client') { + headerFound = true; + + // Prepend command feature to value, if not already there + if (!value.includes(GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED)) { + headers[key] = + `${value} gccl-gcs-cmd/${GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED}`; + } + } else if (key.toLocaleLowerCase().trim() === 'user-agent') { + userAgentFound = true; + } + } + + // If the header isn't present, add it + if (!headerFound) { + headers['x-goog-api-client'] = `${getRuntimeTrackingString()} gccl/${ + packageJson.version + } gccl-gcs-cmd/${GCCL_GCS_CMD_FEATURE.UPLOAD_SHARDED}`; + } + + // If the User-Agent isn't present, add it + if (!userAgentFound) { + headers['User-Agent'] = getUserAgentString(); + } + + return headers; + } + + /** + * Initiates a multipart upload (MPU) to the XML API and stores the resultant upload id. + * + * @returns {Promise} + */ + async initiateUpload(headers: Headers = {}): Promise { + const url = `${this.baseUrl}?uploads`; + return AsyncRetry(async bail => { + try { + const res = await this.authClient.request({ + headers: this.#setGoogApiClientHeaders(headers), + method: 'POST', + url, + }); + + if (res.data && res.data.error) { + throw res.data.error; + } + const parsedXML = this.xmlParser.parse(res.data); + this.uploadId = parsedXML.InitiateMultipartUploadResult.UploadId; + } catch (e) { + this.#handleErrorResponse(e as Error, bail); + } + }, this.retryOptions); + } + + /** + * Uploads the provided chunk of data to the XML API using the previously created upload id. + * + * @param {number} partNumber the sequence number of this chunk. + * @param {Buffer} chunk the chunk of data to be uploaded. + * @param {string | false} validation whether or not to include the md5 hash in the headers to cause the server + * to validate the chunk was not corrupted. + * @returns {Promise} + */ + async uploadPart( + partNumber: number, + chunk: Buffer, + validation?: 'md5' | false, + ): Promise { + const url = `${this.baseUrl}?partNumber=${partNumber}&uploadId=${this.uploadId}`; + let headers: Headers = this.#setGoogApiClientHeaders(); + + if (validation === 'md5') { + const hash = createHash('md5').update(chunk).digest('base64'); + headers = { + 'Content-MD5': hash, + }; + } + + return AsyncRetry(async bail => { + try { + const res = await this.authClient.request({ + url, + method: 'PUT', + body: chunk, + headers, + }); + if (res.data && res.data.error) { + throw res.data.error; + } + this.partsMap.set(partNumber, res.headers['etag']); + } catch (e) { + this.#handleErrorResponse(e as Error, bail); + } + }, this.retryOptions); + } + + /** + * Sends the final request of the MPU to tell GCS the upload is now complete. + * + * @returns {Promise} + */ + async completeUpload(): Promise { + const url = `${this.baseUrl}?uploadId=${this.uploadId}`; + const sortedMap = new Map( + [...this.partsMap.entries()].sort((a, b) => a[0] - b[0]), + ); + const parts: {}[] = []; + for (const entry of sortedMap.entries()) { + parts.push({PartNumber: entry[0], ETag: entry[1]}); + } + const body = `${this.xmlBuilder.build( + parts, + )}`; + return AsyncRetry(async bail => { + try { + const res = await this.authClient.request({ + headers: this.#setGoogApiClientHeaders(), + url, + method: 'POST', + body, + }); + if (res.data && res.data.error) { + throw res.data.error; + } + return res; + } catch (e) { + this.#handleErrorResponse(e as Error, bail); + return; + } + }, this.retryOptions); + } + + /** + * Aborts an multipart upload that is in progress. Once aborted, any parts in the process of being uploaded fail, + * and future requests using the upload ID fail. + * + * @returns {Promise} + */ + async abortUpload(): Promise { + const url = `${this.baseUrl}?uploadId=${this.uploadId}`; + return AsyncRetry(async bail => { + try { + const res = await this.authClient.request({ + url, + method: 'DELETE', + }); + if (res.data && res.data.error) { + throw res.data.error; + } + } catch (e) { + this.#handleErrorResponse(e as Error, bail); + return; + } + }, this.retryOptions); + } + + /** + * Handles error responses and calls the bail function if the error should not be retried. + * + * @param {Error} err the thrown error + * @param {Function} bail if the error can not be retried, the function to be called. + */ + #handleErrorResponse(err: Error, bail: Function) { + if ( + this.bucket.storage.retryOptions.autoRetry && + this.bucket.storage.retryOptions.retryableErrorFn!(err as ApiError) + ) { + throw err; + } else { + bail(err as Error); + } + } +} + +/** + * Create a TransferManager object to perform parallel transfer operations on a Cloud Storage bucket. + * + * @class + * @hideconstructor + * + * @param {Bucket} bucket A {@link Bucket} instance + * + */ +export class TransferManager { + bucket: Bucket; + constructor(bucket: Bucket) { + this.bucket = bucket; + } + + /** + * @typedef {object} UploadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the files. + * @property {Function} [customDestinationBuilder] A function that will take the current path of a local file + * and return a string representing a custom path to be used to upload the file to GCS. + * @property {boolean} [skipIfExists] Do not upload the file if it already exists in + * the bucket. This will set the precondition ifGenerationMatch = 0. + * @property {string} [prefix] A prefix to append to all of the uploaded files. + * @property {object} [passthroughOptions] {@link UploadOptions} Options to be passed through + * to each individual upload operation. + * + */ + /** + * Upload multiple files in parallel to the bucket. This is a convenience method + * that utilizes {@link Bucket#upload} to perform the upload. + * + * @param {array | string} [filePathsOrDirectory] An array of fully qualified paths to the files or a directory name. + * If a directory name is provided, the directory will be recursively walked and all files will be added to the upload list. + * to be uploaded to the bucket + * @param {UploadManyFilesOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload multiple files in parallel. + * //- + * const response = await transferManager.uploadManyFiles(['/local/path/file1.txt, 'local/path/file2.txt']); + * // Your bucket now contains: + * // - "local/path/file1.txt" (with the contents of '/local/path/file1.txt') + * // - "local/path/file2.txt" (with the contents of '/local/path/file2.txt') + * const response = await transferManager.uploadManyFiles('/local/directory'); + * // Your bucket will now contain all files contained in '/local/directory' maintaining the subdirectory structure. + * ``` + * + */ + async uploadManyFiles( + filePathsOrDirectory: string[] | string, + options: UploadManyFilesOptions = {}, + ): Promise { + if (options.skipIfExists && options.passthroughOptions?.preconditionOpts) { + options.passthroughOptions.preconditionOpts.ifGenerationMatch = 0; + } else if ( + options.skipIfExists && + options.passthroughOptions === undefined + ) { + options.passthroughOptions = { + preconditionOpts: { + ifGenerationMatch: 0, + }, + }; + } + + const limit = pLimit( + options.concurrencyLimit || DEFAULT_PARALLEL_UPLOAD_LIMIT, + ); + const promises: Promise[] = []; + let allPaths: string[] = []; + if (!Array.isArray(filePathsOrDirectory)) { + for await (const curPath of this.getPathsFromDirectory( + filePathsOrDirectory, + )) { + allPaths.push(curPath); + } + } else { + allPaths = filePathsOrDirectory; + } + + for (const filePath of allPaths) { + const stat = await fsp.lstat(filePath); + if (stat.isDirectory()) { + continue; + } + + const passThroughOptionsCopy: UploadOptions = { + ...options.passthroughOptions, + [GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.UPLOAD_MANY, + }; + + passThroughOptionsCopy.destination = options.customDestinationBuilder + ? options.customDestinationBuilder(filePath, options) + : filePath.split(path.sep).join(path.posix.sep); + if (options.prefix) { + passThroughOptionsCopy.destination = path.posix.join( + ...options.prefix.split(path.sep), + passThroughOptionsCopy.destination, + ); + } + + promises.push( + limit(() => + this.bucket.upload(filePath, passThroughOptionsCopy as UploadOptions), + ), + ); + } + + return Promise.all(promises); + } + + /** + * @typedef {object} DownloadManyFilesOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the files. + * @property {string} [prefix] A prefix to append to all of the downloaded files. + * @property {string} [stripPrefix] A prefix to remove from all of the downloaded files. + * @property {object} [passthroughOptions] {@link DownloadOptions} Options to be passed through + * to each individual download operation. + * @property {boolean} [skipIfExists] Do not download the file if it already exists in + * the destination. + * + */ + /** + * Download multiple files in parallel to the local filesystem. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {array | string} [filesOrFolder] An array of file name strings or file objects to be downloaded. If + * a string is provided this will be treated as a GCS prefix and all files with that prefix will be downloaded. + * @param {DownloadManyFilesOptions} [options] Configuration options. Setting options.prefix or options.stripPrefix + * or options.passthroughOptions.destination will cause the downloaded files to be written to the file system + * instead of being returned as a buffer. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download multiple files in parallel. + * //- + * const response = await transferManager.downloadManyFiles(['file1.txt', 'file2.txt']); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles([bucket.File('file1.txt'), bucket.File('file2.txt')]); + * // The following files have been downloaded: + * // - "file1.txt" (with the contents from my-bucket.file1.txt) + * // - "file2.txt" (with the contents from my-bucket.file2.txt) + * const response = await transferManager.downloadManyFiles('test-folder'); + * // All files with GCS prefix of 'test-folder' have been downloaded. + * ``` + * + */ + async downloadManyFiles( + filesOrFolder: File[] | string[] | string, + options: DownloadManyFilesOptions = {}, + ): Promise { + const limit = pLimit( + options.concurrencyLimit || DEFAULT_PARALLEL_DOWNLOAD_LIMIT, + ); + const promises: Promise[] = []; + let files: File[] = []; + + if (!Array.isArray(filesOrFolder)) { + const directoryFiles = await this.bucket.getFiles({ + prefix: filesOrFolder, + }); + files = directoryFiles[0]; + } else { + files = filesOrFolder.map(curFile => { + if (typeof curFile === 'string') { + return this.bucket.file(curFile); + } + return curFile; + }); + } + + const stripRegexString = options.stripPrefix + ? `^${options.stripPrefix}` + : EMPTY_REGEX; + const regex = new RegExp(stripRegexString, 'g'); + + for (const file of files) { + const passThroughOptionsCopy = { + ...options.passthroughOptions, + [GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.DOWNLOAD_MANY, + }; + + if (options.prefix || passThroughOptionsCopy.destination) { + passThroughOptionsCopy.destination = path.join( + options.prefix || '', + passThroughOptionsCopy.destination || '', + file.name, + ); + } + if (options.stripPrefix) { + passThroughOptionsCopy.destination = file.name.replace(regex, ''); + } + if ( + options.skipIfExists && + existsSync(passThroughOptionsCopy.destination || '') + ) { + continue; + } + + promises.push( + limit(async () => { + const destination = passThroughOptionsCopy.destination; + if (destination && destination.endsWith(path.sep)) { + await fsp.mkdir(destination, {recursive: true}); + return Promise.resolve([ + Buffer.alloc(0), + ]) as Promise; + } + + return file.download(passThroughOptionsCopy); + }), + ); + } + + return Promise.all(promises); + } + + /** + * @typedef {object} DownloadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when downloading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be downloaded. + * @property {string | boolean} [validation] Whether or not to perform a CRC32C validation check when download is complete. + * @property {boolean} [noReturnData] Whether or not to return the downloaded data. A `true` value here would be useful for files with a size that will not fit into memory. + * + */ + /** + * Download a large file in chunks utilizing parallel download operations. This is a convenience method + * that utilizes {@link File#download} to perform the download. + * + * @param {File | string} fileOrName {@link File} to download. + * @param {DownloadFileInChunksOptions} [options] Configuration options. + * @returns {Promise} + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Download a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.downloadFileInChunks(bucket.file('large-file.txt'); + * // Your local directory now contains: + * // - "large-file.txt" (with the contents from my-bucket.large-file.txt) + * ``` + * + */ + async downloadFileInChunks( + fileOrName: File | string, + options: DownloadFileInChunksOptions = {}, + ): Promise { + let chunkSize = + options.chunkSizeBytes || DOWNLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE; + let limit = pLimit( + options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_DOWNLOAD_LIMIT, + ); + const noReturnData = Boolean(options.noReturnData); + const promises: Promise[] = []; + const file: File = + typeof fileOrName === 'string' + ? this.bucket.file(fileOrName) + : fileOrName; + + const fileInfo = await file.get(); + const size = parseInt(fileInfo[0].metadata.size!.toString()); + // If the file size does not meet the threshold download it as a single chunk. + if (size < DOWNLOAD_IN_CHUNKS_FILE_SIZE_THRESHOLD) { + limit = pLimit(1); + chunkSize = size; + } + + let start = 0; + const filePath = options.destination || path.basename(file.name); + const fileToWrite = await fsp.open(filePath, 'w'); + while (start < size) { + const chunkStart = start; + let chunkEnd = start + chunkSize - 1; + chunkEnd = chunkEnd > size ? size : chunkEnd; + promises.push( + limit(async () => { + const resp = await file.download({ + start: chunkStart, + end: chunkEnd, + [GCCL_GCS_CMD_KEY]: GCCL_GCS_CMD_FEATURE.DOWNLOAD_SHARDED, + }); + const result = await fileToWrite.write( + resp[0], + 0, + resp[0].length, + chunkStart, + ); + if (noReturnData) return; + return result.buffer; + }), + ); + + start += chunkSize; + } + + let chunks: Array; + try { + chunks = await Promise.all(promises); + } finally { + await fileToWrite.close(); + } + + if (options.validation === 'crc32c' && fileInfo[0].metadata.crc32c) { + const downloadedCrc32C = await CRC32C.fromFile(filePath); + if (!downloadedCrc32C.validate(fileInfo[0].metadata.crc32c)) { + const mismatchError = new RequestError( + FileExceptionMessages.DOWNLOAD_MISMATCH, + ); + mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH'; + throw mismatchError; + } + } + if (noReturnData) return; + return [Buffer.concat(chunks as Buffer[], size)]; + } + + /** + * @typedef {object} UploadFileInChunksOptions + * @property {number} [concurrencyLimit] The number of concurrently executing promises + * to use when uploading the file. + * @property {number} [chunkSizeBytes] The size in bytes of each chunk to be uploaded. + * @property {string} [uploadName] Name of the file when saving to GCS. If omitted the name is taken from the file path. + * @property {number} [maxQueueSize] The number of chunks to be uploaded to hold in memory concurrently. If not specified + * defaults to the specified concurrency limit. + * @property {string} [uploadId] If specified attempts to resume a previous upload. + * @property {Map} [partsMap] If specified alongside uploadId, attempts to resume a previous upload from the last chunk + * specified in partsMap + * @property {object} [headers] headers to be sent when initiating the multipart upload. + * See {@link https://cloud.google.com/storage/docs/xml-api/post-object-multipart#request_headers| Request Headers: Initiate a Multipart Upload} + * @property {boolean} [autoAbortFailure] boolean to indicate if an in progress upload session will be automatically aborted upon failure. If not set, + * failures will be automatically aborted. + * + */ + /** + * Upload a large file in chunks utilizing parallel upload operations. If the upload fails, an uploadId and + * map containing all the successfully uploaded parts will be returned to the caller. These arguments can be used to + * resume the upload. + * + * @param {string} [filePath] The path of the file to be uploaded + * @param {UploadFileInChunksOptions} [options] Configuration options. + * @param {MultiPartHelperGenerator} [generator] A function that will return a type that implements the MPU interface. Most users will not need to use this. + * @returns {Promise} If successful a promise resolving to void, otherwise a error containing the message, uploadId, and parts map. + * + * @example + * ``` + * const {Storage} = require('@google-cloud/storage'); + * const storage = new Storage(); + * const bucket = storage.bucket('my-bucket'); + * const transferManager = new TransferManager(bucket); + * + * //- + * // Upload a large file in chunks utilizing parallel operations. + * //- + * const response = await transferManager.uploadFileInChunks('large-file.txt'); + * // Your bucket now contains: + * // - "large-file.txt" + * ``` + * + * + */ + async uploadFileInChunks( + filePath: string, + options: UploadFileInChunksOptions = {}, + generator: MultiPartHelperGenerator = defaultMultiPartGenerator, + ): Promise { + const chunkSize = + options.chunkSizeBytes || UPLOAD_IN_CHUNKS_DEFAULT_CHUNK_SIZE; + const limit = pLimit( + options.concurrencyLimit || DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT, + ); + const maxQueueSize = + options.maxQueueSize || + options.concurrencyLimit || + DEFAULT_PARALLEL_CHUNKED_UPLOAD_LIMIT; + const fileName = options.uploadName || path.basename(filePath); + const mpuHelper = generator( + this.bucket, + fileName, + options.uploadId, + options.partsMap, + ); + let partNumber = 1; + let promises: Promise[] = []; + try { + if (options.uploadId === undefined) { + await mpuHelper.initiateUpload(options.headers); + } + const startOrResumptionByte = mpuHelper.partsMap!.size * chunkSize; + const readStream = createReadStream(filePath, { + highWaterMark: chunkSize, + start: startOrResumptionByte, + }); + // p-limit only limits the number of running promises. We do not want to hold an entire + // large file in memory at once so promises acts a queue that will hold only maxQueueSize in memory. + for await (const curChunk of readStream) { + if (promises.length >= maxQueueSize) { + await Promise.all(promises); + promises = []; + } + promises.push( + limit(() => + mpuHelper.uploadPart(partNumber++, curChunk, options.validation), + ), + ); + } + await Promise.all(promises); + return await mpuHelper.completeUpload(); + } catch (e) { + if ( + (options.autoAbortFailure === undefined || options.autoAbortFailure) && + mpuHelper.uploadId + ) { + try { + await mpuHelper.abortUpload(); + return; + } catch (e) { + throw new MultiPartUploadError( + (e as Error).message, + mpuHelper.uploadId!, + mpuHelper.partsMap!, + ); + } + } + throw new MultiPartUploadError( + (e as Error).message, + mpuHelper.uploadId!, + mpuHelper.partsMap!, + ); + } + } + + private async *getPathsFromDirectory( + directory: string, + ): AsyncGenerator { + const filesAndSubdirectories = await fsp.readdir(directory, { + withFileTypes: true, + }); + for (const curFileOrDirectory of filesAndSubdirectories) { + const fullPath = path.join(directory, curFileOrDirectory.name); + curFileOrDirectory.isDirectory() + ? yield* this.getPathsFromDirectory(fullPath) + : yield fullPath; + } + } +} diff --git a/handwritten/storage/src/util.ts b/handwritten/storage/src/util.ts new file mode 100644 index 00000000000..4957a210b6c --- /dev/null +++ b/handwritten/storage/src/util.ts @@ -0,0 +1,274 @@ +// Copyright 2019 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 * as path from 'path'; +import * as querystring from 'querystring'; +import {PassThrough} from 'stream'; +import * as url from 'url'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import {getPackageJSON} from './package-json-helper.cjs'; + +// Done to avoid a problem with mangling of identifiers when using esModuleInterop +const fileURLToPath = url.fileURLToPath; +const isEsm = true; + +export function normalize( + optionsOrCallback?: T | U, + cb?: U, +) { + const options = ( + typeof optionsOrCallback === 'object' ? optionsOrCallback : {} + ) as T; + const callback = ( + typeof optionsOrCallback === 'function' ? optionsOrCallback : cb + )! as U; + return {options, callback}; +} + +/** + * Flatten an object into an Array of arrays, [[key, value], ..]. + * Implements Object.entries() for Node.js <8 + * @internal + */ +export function objectEntries(obj: {[key: string]: T}): Array<[string, T]> { + return Object.keys(obj).map(key => [key, obj[key]] as [string, T]); +} + +/** + * Encode `str` with encodeURIComponent, plus these + * reserved characters: `! * ' ( )`. + * + * See {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent| MDN: fixedEncodeURIComponent} + * + * @param {string} str The URI component to encode. + * @return {string} The encoded string. + */ +export function fixedEncodeURIComponent(str: string): string { + return encodeURIComponent(str).replace( + /[!'()*]/g, + c => '%' + c.charCodeAt(0).toString(16).toUpperCase(), + ); +} + +/** + * URI encode `uri` for generating signed URLs, using fixedEncodeURIComponent. + * + * Encode every byte except `A-Z a-Z 0-9 ~ - . _`. + * + * @param {string} uri The URI to encode. + * @param [boolean=false] encodeSlash If `true`, the "/" character is not encoded. + * @return {string} The encoded string. + */ +export function encodeURI(uri: string, encodeSlash: boolean): string { + // Split the string by `/`, and conditionally rejoin them with either + // %2F if encodeSlash is `true`, or '/' if `false`. + return uri + .split('/') + .map(fixedEncodeURIComponent) + .join(encodeSlash ? '%2F' : '/'); +} + +/** + * Serialize an object to a URL query string using util.encodeURI(uri, true). + * @param {string} url The object to serialize. + * @return {string} Serialized string. + */ +export function qsStringify(qs: querystring.ParsedUrlQueryInput): string { + return querystring.stringify(qs, '&', '=', { + encodeURIComponent: (component: string) => encodeURI(component, true), + }); +} + +export function objectKeyToLowercase(object: {[key: string]: T}) { + const newObj: {[key: string]: T} = {}; + for (let key of Object.keys(object)) { + const value = object[key]; + key = key.toLowerCase(); + newObj[key] = value; + } + return newObj; +} + +/** + * JSON encode str, with unicode \u+ representation. + * @param {object} obj The object to encode. + * @return {string} Serialized string. + */ +export function unicodeJSONStringify(obj: object) { + return JSON.stringify(obj).replace( + /[\u0080-\uFFFF]/g, + (char: string) => + '\\u' + ('0000' + char.charCodeAt(0).toString(16)).slice(-4), + ); +} + +/** + * Converts the given objects keys to snake_case + * @param {object} obj object to convert keys to snake case. + * @returns {object} object with keys converted to snake case. + */ +export function convertObjKeysToSnakeCase(obj: object): object { + if (obj instanceof Date || obj instanceof RegExp) { + return obj; + } + if (Array.isArray(obj)) { + return obj.map(convertObjKeysToSnakeCase); + } + if (obj instanceof Object) { + return Object.keys(obj).reduce((acc, cur) => { + const s = + cur[0].toLocaleLowerCase() + + cur.slice(1).replace(/([A-Z]+)/g, (match, p1) => { + return `_${p1.toLowerCase()}`; + }); + + acc[s] = convertObjKeysToSnakeCase(obj[cur as keyof Object]); + return acc; + }, Object()); + } + + return obj; +} + +/** + * Formats the provided date object as a UTC ISO string. + * @param {Date} dateTimeToFormat date object to be formatted. + * @param {boolean} includeTime flag to include hours, minutes, seconds in output. + * @param {string} dateDelimiter delimiter between date components. + * @param {string} timeDelimiter delimiter between time components. + * @returns {string} UTC ISO format of provided date object. + */ +export function formatAsUTCISO( + dateTimeToFormat: Date, + includeTime = false, + dateDelimiter = '', + timeDelimiter = '', +): string { + const year = dateTimeToFormat.getUTCFullYear(); + const month = dateTimeToFormat.getUTCMonth() + 1; + const day = dateTimeToFormat.getUTCDate(); + const hour = dateTimeToFormat.getUTCHours(); + const minute = dateTimeToFormat.getUTCMinutes(); + const second = dateTimeToFormat.getUTCSeconds(); + + let resultString = `${year.toString().padStart(4, '0')}${dateDelimiter}${month + .toString() + .padStart(2, '0')}${dateDelimiter}${day.toString().padStart(2, '0')}`; + if (includeTime) { + resultString = `${resultString}T${hour + .toString() + .padStart(2, '0')}${timeDelimiter}${minute + .toString() + .padStart(2, '0')}${timeDelimiter}${second.toString().padStart(2, '0')}Z`; + } + + return resultString; +} + +/** + * Examines the runtime environment and returns the appropriate tracking string. + * @returns {string} metrics tracking string based on the current runtime environment. + */ +export function getRuntimeTrackingString(): string { + if ( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno && + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno.version && + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno.version.deno + ) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + return `gl-deno/${globalThis.Deno.version.deno}`; + } else { + return `gl-node/${process.versions.node}`; + } +} + +/** + * Looks at package.json and creates the user-agent string to be applied to request headers. + * @returns {string} user agent string. + */ +export function getUserAgentString(): string { + const pkg = getPackageJSON(); + const hyphenatedPackageName = pkg.name + .replace('@google-cloud', 'gcloud-node') // For legacy purposes. + .replace('/', '-'); // For UA spec-compliance purposes. + + return hyphenatedPackageName + '/' + pkg.version; +} + +export function getDirName() { + let dirToUse = ''; + try { + dirToUse = __dirname; + } catch (e) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + dirToUse = path.dirname(fileURLToPath(import.meta.url)); + } + + return dirToUse; +} + +export function getModuleFormat() { + return isEsm ? 'ESM' : 'CJS'; +} + +export class PassThroughShim extends PassThrough { + private shouldEmitReading = true; + private shouldEmitWriting = true; + + _read(size: number): void { + if (this.shouldEmitReading) { + this.emit('reading'); + this.shouldEmitReading = false; + } + super._read(size); + } + + _write( + chunk: never, + encoding: BufferEncoding, + callback: (error?: Error | null | undefined) => void, + ): void { + if (this.shouldEmitWriting) { + this.emit('writing'); + this.shouldEmitWriting = false; + } + // Per the nodejs documentation, callback must be invoked on the next tick + process.nextTick(() => { + super._write(chunk, encoding, callback); + }); + } + + _final(callback: (error?: Error | null | undefined) => void): void { + // If the stream is empty (i.e. empty file) final will be invoked before _read / _write + // and we should still emit the proper events. + if (this.shouldEmitReading) { + this.emit('reading'); + this.shouldEmitReading = false; + } + if (this.shouldEmitWriting) { + this.emit('writing'); + this.shouldEmitWriting = false; + } + callback(null); + } +} diff --git a/handwritten/storage/system-test/common.ts b/handwritten/storage/system-test/common.ts new file mode 100644 index 00000000000..b0364218b5a --- /dev/null +++ b/handwritten/storage/system-test/common.ts @@ -0,0 +1,116 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 {before, describe, it} from 'mocha'; +import assert from 'assert'; +import * as http from 'http'; + +import * as common from '../src/nodejs-common/index.js'; + +describe('Common', () => { + const MOCK_HOST_PORT = 8118; + const MOCK_HOST = `http://localhost:${MOCK_HOST_PORT}`; + + describe('Service', () => { + let service: common.Service; + + before(() => { + service = new common.Service({ + baseUrl: MOCK_HOST, + apiEndpoint: MOCK_HOST, + scopes: [], + packageJson: {name: 'tests', version: '1.0.0'}, + }); + }); + + it('should send a request and receive a response', done => { + const mockResponse = 'response'; + const mockServer = new http.Server((req, res) => { + res.end(mockResponse); + }); + + mockServer.listen(MOCK_HOST_PORT); + + service.request( + { + uri: '/mock-endpoint', + }, + (err, resp) => { + assert.ifError(err); + assert.strictEqual(resp, mockResponse); + mockServer.close(done); + }, + ); + }); + + it('should retry a request', function (done) { + // We've increased the timeout to accommodate the retry backoff strategy. + // The test's retry attempts and the delay between them can exceed the default timeout, + // causing a false negative (test failure due to timeout instead of a logic error). + this.timeout(90 * 1000); + + let numRequestAttempts = 0; + + const mockServer = new http.Server((req, res) => { + numRequestAttempts++; + res.statusCode = 408; + res.end(); + }); + + mockServer.listen(MOCK_HOST_PORT); + + service.request( + { + uri: '/mock-endpoint-retry', + }, + err => { + assert.strictEqual((err! as common.ApiError).code, 408); + assert.strictEqual(numRequestAttempts, 4); + mockServer.close(done); + }, + ); + }); + + it('should retry non-responsive hosts', function (done) { + this.timeout(60 * 1000); + + function getMinimumRetryDelay(retryNumber: number) { + return Math.pow(2, retryNumber) * 1000; + } + + let minExpectedResponseTime = 0; + let numExpectedRetries = 2; + + while (numExpectedRetries--) { + minExpectedResponseTime += getMinimumRetryDelay(numExpectedRetries + 1); + } + + const timeRequest = Date.now(); + + service.request( + { + uri: '/mock-endpoint-no-response', + }, + err => { + assert(err?.message.includes('ECONNREFUSED')); + const timeResponse = Date.now(); + assert(timeResponse - timeRequest > minExpectedResponseTime); + }, + ); + done(); + }); + }); +}); diff --git a/handwritten/storage/system-test/data/CloudPlatform_128px_Retina.png b/handwritten/storage/system-test/data/CloudPlatform_128px_Retina.png new file mode 100644 index 00000000000..86c04e4b44f Binary files /dev/null and b/handwritten/storage/system-test/data/CloudPlatform_128px_Retina.png differ diff --git a/handwritten/storage/system-test/data/empty-file.txt b/handwritten/storage/system-test/data/empty-file.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/storage/system-test/data/long-html-file.html b/handwritten/storage/system-test/data/long-html-file.html new file mode 100644 index 00000000000..a8ea1cc650f --- /dev/null +++ b/handwritten/storage/system-test/data/long-html-file.html @@ -0,0 +1,1720 @@ + + + + + +What is the maximum compression ratio of gzip? - Super User + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + + + +
+
+ +
+ +
+ + + +
+

+your communities

+ +
+ + + + +
+
+ + + + +
+
+ + +
+ + + + + +
+ + +
+ + + +
+
+ + Take the 2-minute tour + × + +
+ Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required. +
+
+ +
+ + +
+ + + +
+ + +
+
include:samples/generated/v1/spanner_executor_proxy.execute_action_async.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/iam.jsinclude:samples/iam.jsinclude:samples/iam.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/acl.jsinclude:samples/buckets.jsinclude:samples/requesterPays.jsinclude:samples/createNotification.jsinclude:samples/requesterPays.jsinclude:samples/requesterPays.jsinclude:samples/files.jsinclude:samples/files.jsinclude:samples/listNotifications.jsinclude:samples/files.jsinclude:samples/encryption.jsinclude:samples/files.jsinclude:samples/files.jsinclude:samples/files.jsinclude:samples/files.jsinclude:samples/encryption.jsinclude:samples/requesterPays.jsinclude:samples/encryption.jsinclude:samples/encryption.jsinclude:samples/files.jsinclude:samples/files.jsinclude:samples/files.jsinclude:samples/files.jsinclude:samples/encryption.jsinclude:samples/iam.jsinclude:samples/iam.jsinclude:samples/iam.jsinclude:samples/quickstart.jsinclude:samples/deleteNotification.jsinclude:samples/getMetadataNotifications.jsinclude:samples/buckets.jsinclude:samples/buckets.js
+ + + + + + + + + +
+ + +
+ + up vote + 25 + down vote + + favorite +
6
+ + +
+ +
+
+
+ +

What is the largest size a gzip (say 10kb for the sake of an example) can be decompressed to?

+
+ + + + + + + +
+
share|improve this question
+
+ + +
+
+
+
+ + + + + +
+
+ + +
+ + +
+ + +
+
+

+ 5 Answers + 5 +

+
+ +
+
+
+ + + + + + +
+ + + + + + + + + + + + + +
+ + +
+ + up vote + 46 + down vote + + + + accepted + +
+ +
+
+

It very much depends ont he data being compressed. A quick test with a 1Gb file full for zeros give a compressed size of ~120Kb, so your 10Kb file could potentially expand into ~85Mbytes.

+ +

If the data has low redundancy to start with, for instance the archive contains images files in a format that is compressed natively (gif, jpg, png, ...), then gzip may add not further compression at all. For binary files like program executables you might see up to 2:1 compression, for plain text, HTML or other markup 3:1 or 4:1 or more is not unlikely. You might see 10:1 in some cases but the ~8700:1 seen with a file filled with a single symbol is something you are not going to see outside similarly artificial circumstances.

+ +

You can check how much data would result from unpacking a gzip file, without actually writing its uncompressed content to disk, with gunzip -c file.gz | wc --bytes - this will uncompress the file but not store the results, instead passing them to wc which will count the number of bytes as they pass then discard them. If compressed content is a tar file containing many many small files you might find that noticably more disk space is required to unpack the full archive, but in most circumstances the count returned from piping gunzip output through wc is going to be as accurate as you need.

+
+ + + + + + + + + +
+
share|improve this answer
+ + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +
+ 1 + +   +
+
+
+ Nice. Limiting case, discussion of common cases and a a "how-to" on answering the question at hand. A model for a good answer. + –  + dmckee + May 9 '10 at 15:09 +
+
+ + + + + + + +
+    + +   +
+
+
+ I've seen HTML expand to 10x (of course x3 and x4 was the most common!).... perhaps a lot of redundant data for those ones that were exploding +8x. I think the page in question that was doing that was a php info page. + –  + Zombies + May 10 '10 at 12:10 + +
+
+ + + + + + + +
+    + +   +
+
+
+ Repetitive markup, as seen in the output of phpinfo(), compresses very well. The technical information in that output contains more direct repetition than the average chunk of natural language would too, and the alphabet distribution is probably less smooth which could help the Huffman stage get better results. + –  + David Spillett + May 10 '10 at 12:55 +
+
+ + + + + + + +
+    + +   +
+
+
+ This answer doesn't account for intentionally malicious compressed data. One can craft a malicious zip file around 10KB that can expand to a bit over 4GB. + –  + David Schwartz + Jan 2 '13 at 2:36 + +
+
+ + + + + + + +
+    + +   +
+
+
+ Zip bombs of that scale rely on nested archives though, so as a human unpacking the file you would noticed something odd before long. They can be used as an effective DoS attack against automated scanners (on mail services and so forth) though. + –  + David Spillett + Jan 2 '13 at 11:47 +
+
+
+ + +
+
+ +
+
+ + +
+ + + + + + + + + + + + + +
+ + +
+ + up vote + 7 + down vote + + + + +
+ +
+
+

Usually you don't get more than 95% compression (so that 10kB gzipped data would decompress to ~200kB), but there are specially crafted files that expand exponentially. Look for 42.zip, it decompresses to few petabytes of (meaningless) data.

+
+ + + + + + + + +
+
share|improve this answer
+ + + +
+
+
+ + + + + + + + + + + + + + +
+ + + + + + + +
+ 2 + +   +
+
+
+ Wikipedia says 42.zip is "containing five layers of nested zip files in sets of 16", so that is not a valid example for decompression (only for recursive decompression). + –  + Tgr + Jul 10 '13 at 13:59 +
+
+ + + + + + + +
+ 1 + +   +
+
+
+ Indeed, 42.zip is specifically a danger to tools that automatically scan zip files recursively, for example virus scanners. + –  + thomasrutter + Feb 5 '14 at 0:42 +
+
+
+ + +
+
+ + + +
+ + + + + + + + + + + + + +
+ + +
+ + up vote + 3 + down vote + + + + +
+ +
+
+

The compression ratio of any compression algorithm will be a function of the data being compressed (besides the length of that data).

+ +

Here is an analysis at MaximumCompression,
+Look at one of the samples like,

+ +

Summary of the multiple file compression benchmark tests

+ +
File type : Multiple file types (46 in total)
+# of files to compress in this test : 510
+Total File Size (bytes) : 316.355.757
+Average File Size (bytes) : 620,305
+Largest File (bytes) : 18,403,071
+Smallest File (bytes) : 3,554
+
+
+ + + + + + + + +
+
share|improve this answer
+ + + +
+
+
+ + + + + +
+
+ + +
+
+ + + +
+ + + + + + + + + + + + + +
+ + +
+ + up vote + 2 + down vote + + + + +
+ +
+
+

A huge file containing only one symbol will compress very well.

+
+ + + + + + + + +
+
share|improve this answer
+ + + +
+
+
+ + + + + +
+
+ + +
+
+ + + +
+ + + + + + + + + + + + + +
+ + +
+ + up vote + 1 + down vote + + + + +
+ +
+
+

10 MB of zeros in file, compress with gzip -9 to 10217. So maximal ratio looks to be around 1000x.

+
+ + + + + + + + +
+
share|improve this answer
+ + + +
+
+
+ + + + + +
+
+ + +
+
+ +
+ + + +

Your Answer

+ + + + + + + + +
+ +
+
+
+ +
+
+ +
 
+ + + + + + +
+
+
+ + +
+ + + +
+
+ + + + +
+ +
+ + discard + +

+By posting your answer, you agree to the privacy policy and terms of service.

+
+
+ + + +

+Not the answer you're looking for? Browse other questions tagged or ask your own question.

+
+ + + + + + + + + + + + + + + + + + diff --git a/handwritten/storage/system-test/data/three-mb-file.tif b/handwritten/storage/system-test/data/three-mb-file.tif new file mode 100644 index 00000000000..5aaa8a1745b Binary files /dev/null and b/handwritten/storage/system-test/data/three-mb-file.tif differ diff --git a/handwritten/storage/system-test/fixtures/index-cjs.js b/handwritten/storage/system-test/fixtures/index-cjs.js new file mode 100644 index 00000000000..b987f57c0d6 --- /dev/null +++ b/handwritten/storage/system-test/fixtures/index-cjs.js @@ -0,0 +1,22 @@ +// Copyright 2023 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. + +/* eslint-disable node/no-missing-require, no-unused-vars, no-undef */ +const {Storage} = require('@google-cloud/storage'); + +function main() { + const storage = new Storage(); +} + +main(); diff --git a/handwritten/storage/system-test/fixtures/index-esm.js b/handwritten/storage/system-test/fixtures/index-esm.js new file mode 100644 index 00000000000..92cae36bcc5 --- /dev/null +++ b/handwritten/storage/system-test/fixtures/index-esm.js @@ -0,0 +1,22 @@ +// Copyright 2023 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. + +/* eslint-disable node/no-missing-import, no-unused-vars */ +import {Storage} from '@google-cloud/storage'; + +function main() { + const storage = new Storage(); +} + +main(); diff --git a/handwritten/storage/system-test/install.ts b/handwritten/storage/system-test/install.ts new file mode 100644 index 00000000000..cb50b632ca6 --- /dev/null +++ b/handwritten/storage/system-test/install.ts @@ -0,0 +1,37 @@ +// Copyright 2023 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. + +import {packNTest} from 'pack-n-play'; +import {readFileSync} from 'fs'; +import {describe, it} from 'mocha'; + +describe('pack-n-play tests', () => { + it('ESM module', async () => { + await packNTest({ + sample: { + description: 'Should be able to import the storage library in ESM', + esm: readFileSync('./system-test/fixtures/index-esm.js').toString(), + }, + }); + }); + + it('CJS module', async () => { + await packNTest({ + sample: { + description: 'Should be able to import the storage library in CJS', + cjs: readFileSync('./system-test/fixtures/index-cjs.js').toString(), + }, + }); + }); +}); diff --git a/handwritten/storage/system-test/kitchen.ts b/handwritten/storage/system-test/kitchen.ts new file mode 100644 index 00000000000..fbfe9bd2eff --- /dev/null +++ b/handwritten/storage/system-test/kitchen.ts @@ -0,0 +1,371 @@ +// Copyright 2022 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 * as assert from 'assert'; +import {describe, it, beforeEach} from 'mocha'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as tmp from 'tmp'; +import * as crypto from 'crypto'; +import * as os from 'os'; +import {pipeline, Readable} from 'stream'; +import { + checkUploadStatus, + createURI, + ErrorWithCode, + upload, +} from '../src/resumable-upload.js'; +import { + RETRY_DELAY_MULTIPLIER_DEFAULT, + TOTAL_TIMEOUT_DEFAULT, + MAX_RETRY_DELAY_DEFAULT, + AUTO_RETRY_DEFAULT, + MAX_RETRY_DEFAULT, + RETRYABLE_ERR_FN_DEFAULT, + Storage, +} from '../src/storage.js'; +import {CRC32C} from '../src/crc32c.js'; + +const bucketName = process.env.BUCKET_NAME || 'gcs-resumable-upload-test'; + +/** + * The known multiple chunk upload size, in bytes + */ +const KNOWN_MULTI_CHUNK_MULTIPLE_BYTES = 256 * 1024; +const FILE_SIZE = 1024 * 1024 * 20; + +describe('resumable-upload', () => { + const retryOptions = { + retryDelayMultiplier: RETRY_DELAY_MULTIPLIER_DEFAULT, + totalTimeout: TOTAL_TIMEOUT_DEFAULT, + maxRetryDelay: MAX_RETRY_DELAY_DEFAULT, + autoRetry: AUTO_RETRY_DEFAULT, + maxRetries: MAX_RETRY_DEFAULT, + retryableErrorFn: RETRYABLE_ERR_FN_DEFAULT, + }; + + const bucket = new Storage({retryOptions}).bucket(bucketName); + let filePath: string; + + before(async () => { + tmp.setGracefulCleanup(); + filePath = path.join(os.tmpdir(), '20MB.zip'); + + await fs.promises.writeFile(filePath, crypto.randomBytes(FILE_SIZE)); + }); + + beforeEach(() => { + upload({ + bucket: bucketName, + file: filePath, + retryOptions: retryOptions, + }); + }); + + afterEach(async () => { + await bucket.file(filePath).delete({ignoreNotFound: true}); + }); + + after(async () => { + await fs.promises.rm(filePath, {force: true}); + }); + + function createReadable(amount: number) { + async function* readableGenerator() { + while (amount > 0) { + yield crypto.randomBytes(KNOWN_MULTI_CHUNK_MULTIPLE_BYTES); + amount -= KNOWN_MULTI_CHUNK_MULTIPLE_BYTES; + } + } + + return Readable.from(readableGenerator()); + } + + async function delay(title: string, retries: number, done: Function) { + if (retries === 0) return done(); // no retry on the first failure. + // see: https://cloud.google.com/storage/docs/exponential-backoff: + const ms = Math.pow(2, retries) * 1000 + Math.random() * 2000; + console.info(`retrying "${title}" in ${ms}ms`); + setTimeout(done(), ms); + } + + it('should work', done => { + let uploadSucceeded = false; + fs.createReadStream(filePath) + .on('error', done) + .pipe( + upload({ + bucket: bucketName, + file: filePath, + retryOptions: retryOptions, + metadata: {contentType: 'image/jpg'}, + }), + ) + .on('error', done) + .on('response', resp => { + uploadSucceeded = resp.status === 200; + }) + .on('finish', () => { + assert.strictEqual(uploadSucceeded, true); + done(); + }); + }); + + let retries = 0; + it('should resume an interrupted upload', function (done) { + this.retries(3); + delay(this.test!.title, retries, () => { + retries++; + // If we've retried, delay. + fs.stat(filePath, (err, fd) => { + assert.ifError(err); + + const size = fd.size; + let uri: string | undefined = undefined; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + type DoUploadCallback = (...args: any[]) => void; + const doUpload = ( + opts: {interrupt?: boolean}, + callback: DoUploadCallback, + ) => { + let sizeStreamed = 0; + let destroyed = false; + + const ws = upload({ + uri, + bucket: bucketName, + file: filePath, + metadata: {contentType: 'image/jpg'}, + retryOptions: retryOptions, + }); + + ws.on('uri', (link: string) => { + uri = link; + }); + + fs.createReadStream(filePath) + .on('error', callback) + .on('data', function (this: Readable, chunk) { + sizeStreamed += chunk.length; + + if (!destroyed && opts.interrupt && sizeStreamed >= size / 2) { + // stop sending data half way through + destroyed = true; + this.destroy(); + process.nextTick(() => ws.destroy(new Error('Interrupted'))); + } + }) + .pipe(ws) + .on('error', callback) + .on('metadata', callback.bind(null, null)); + }; + + doUpload({interrupt: true}, (err: Error) => { + assert.strictEqual(err.message, 'Interrupted'); + + doUpload( + {interrupt: false}, + (err: Error, metadata: {size: number}) => { + assert.ifError(err); + assert.ok(uri); + assert.strictEqual(metadata.size, size); + assert.strictEqual(typeof metadata.size, 'number'); + done(); + }, + ); + }); + }); + }).catch(done); + }); + + it('should create an upload URI', async () => { + const uri = await createURI({ + bucket: bucketName, + file: filePath, + metadata: {contentType: 'image/jpg'}, + retryOptions: retryOptions, + }); + + const resp = await checkUploadStatus({ + bucket: bucketName, + file: filePath, + metadata: {contentType: 'image/jpg'}, + retryOptions: retryOptions, + uri, + }); + + assert.ok(!resp.data); + assert.equal(resp.headers['content-length'], '0'); + }); + + it('should return a non-resumable failed upload', done => { + const metadata = { + metadata: {largeString: 'a'.repeat(2.1e6)}, + }; + + fs.createReadStream(filePath) + .on('error', done) + .pipe( + upload({ + bucket: bucketName, + file: filePath, + metadata, + retryOptions: retryOptions, + }), + ) + .on('error', (err: ErrorWithCode) => { + assert.strictEqual(err.status, 400); + done(); + }); + }); + + it('should upload an object in multiple chunks', async () => { + const file = bucket.file(filePath); + const chunkSize = Math.floor(FILE_SIZE / 4); + + // ensure we're testing a valid size + assert.ok(chunkSize > KNOWN_MULTI_CHUNK_MULTIPLE_BYTES); + + await new Promise((resolve, reject) => + pipeline( + fs.createReadStream(filePath), + file.createWriteStream({ + chunkSize, + }), + e => (e ? reject(e) : resolve()), + ), + ); + + const [results] = await file.getMetadata(); + + assert.equal(results.size, FILE_SIZE); + }); + + it('should complete multiple, partial upload session', async () => { + const count = 4; + const file = bucket.file(filePath); + const chunkSize = Math.floor(FILE_SIZE / count); + + // ensure we're testing a valid size and multiple + assert.equal(chunkSize % KNOWN_MULTI_CHUNK_MULTIPLE_BYTES, 0); + + let uri: string | undefined = undefined; + let uriGenerated = 0; + + let resumeCRC32C = ''; + let crc32cGenerated = 0; + + for (let i = 0; i < count; i++) { + const isPartialUpload = !(i + 1 === count); + const offset = i * chunkSize; + + const readable = createReadable(chunkSize); + const writable = file.createWriteStream({ + uri, + chunkSize, + isPartialUpload, + offset, + resumeCRC32C, + }); + + writable.on('uri', link => { + uri = link; + uriGenerated++; + }); + + writable.on('crc32c', crc32c => { + resumeCRC32C = crc32c; + crc32cGenerated++; + }); + + await new Promise((resolve, reject) => + pipeline(readable, writable, e => (e ? reject(e) : resolve())), + ); + } + + const [results] = await file.getMetadata(); + + assert.ok(uri); + assert.equal(uriGenerated, 1, 'uri should be generated once'); + assert.equal( + crc32cGenerated, + count, + 'crc32c should be generated on each upload', + ); + assert.equal(results.size, FILE_SIZE); + }); + + const KNOWN_CRC32C_OF_ZEROS = 'rthIWA=='; + describe('Validation of Client Checksums Against Server Response', () => { + let crc32c: string; + + before(async () => { + crc32c = (await CRC32C.fromFile(filePath)).toString(); + }); + it('should upload successfully when crc32c calculation is enabled', done => { + let uploadSucceeded = false; + + fs.createReadStream(filePath) + .on('error', done) + .pipe( + upload({ + bucket: bucketName, + file: filePath, + crc32c: true, + clientCrc32c: crc32c, + retryOptions: retryOptions, + }), + ) + .on('error', err => { + console.log(err); + done( + new Error( + `Upload failed unexpectedly on success path: ${err.message}`, + ), + ); + }) + .on('response', resp => { + uploadSucceeded = resp.status === 200; + }) + .on('finish', () => { + assert.strictEqual(uploadSucceeded, true); + done(); + }); + }); + + it('should destroy the stream on a checksum mismatch (client-provided hash mismatch)', done => { + const EXPECTED_ERROR_MESSAGE_PART = `Provided CRC32C "${KNOWN_CRC32C_OF_ZEROS}" doesn't match calculated CRC32C`; + + fs.createReadStream(filePath) + .on('error', done) + .pipe( + upload({ + bucket: bucketName, + file: filePath, + clientCrc32c: KNOWN_CRC32C_OF_ZEROS, + crc32c: true, + retryOptions: retryOptions, + }), + ) + .on('error', (err: Error) => { + assert.ok( + err.message.includes(EXPECTED_ERROR_MESSAGE_PART), + `Expected error message part "${EXPECTED_ERROR_MESSAGE_PART}" not found in: ${err.message}`, + ); + done(); + }); + }); + }); +}); diff --git a/handwritten/storage/system-test/storage.ts b/handwritten/storage/system-test/storage.ts new file mode 100644 index 00000000000..2f14fe01296 --- /dev/null +++ b/handwritten/storage/system-test/storage.ts @@ -0,0 +1,4298 @@ +// Copyright 2019 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 assert from 'assert'; +import {after, afterEach, before, beforeEach, describe, it} from 'mocha'; +import * as crypto from 'crypto'; +import * as fs from 'fs'; +import fetch from 'node-fetch'; +import FormData from 'form-data'; +import pLimit from 'p-limit'; +import {promisify} from 'util'; +import * as path from 'path'; +import * as tmp from 'tmp'; +import * as uuid from 'uuid'; +import {ApiError} from '../src/nodejs-common/index.js'; +import { + AccessControlObject, + Bucket, + CRC32C, + DeleteBucketCallback, + File, + IdempotencyStrategy, + LifecycleRule, + Notification, + Storage, + UploadOptions, +} from '../src/index.js'; +import nock from 'nock'; +import {Transform} from 'stream'; +import {gzipSync} from 'zlib'; + +interface ErrorCallbackFunction { + (err: Error | null): void; +} +import {PubSub, Subscription, Topic} from '@google-cloud/pubsub'; +import {getDirName} from '../src/util.js'; + +class HTTPError extends Error { + code: number; + constructor(message: string, code: number) { + super(message); + this.code = code; + } +} + +// When set to true, skips all tests that is not compatible for +// running inside VPCSC. +const RUNNING_IN_VPCSC = !!process.env['GOOGLE_CLOUD_TESTS_IN_VPCSC']; + +const UNIFORM_ACCESS_TIMEOUT = 60 * 1000; // 60s see: https://cloud.google.com/storage/docs/consistency#eventually_consistent_operations +const UNIFORM_ACCESS_WAIT_TIME = 5 * 1000; // 5s +const BUCKET_METADATA_UPDATE_WAIT_TIME = 1250; // 1.25s buckets have a max rate of one metadata update per second. + +// block all attempts to chat with the metadata server (kokoro runs on GCE) +nock('http://metadata.google.internal') + .get(() => true) + .replyWithError({code: 'ENOTFOUND'}) + .persist(); + +// eslint-disable-next-line prefer-arrow-callback +describe('storage', function () { + this.retries(3); + + const USER_ACCOUNT = 'user-spsawchuk@gmail.com'; + const TESTS_PREFIX = `storage-tests-${shortUUID()}-`; + const RETENTION_DURATION_SECONDS = 10; + + const storage = new Storage({ + retryOptions: { + idempotencyStrategy: IdempotencyStrategy.RetryAlways, + }, + }); + const bucket = storage.bucket(generateName()); + + const pubsub = new PubSub({ + projectId: process.env.PROJECT_ID, + }); + let topic: Topic; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const FILES: {[index: string]: any} = { + logo: { + path: path.join( + getDirName(), + '../../../system-test/data/CloudPlatform_128px_Retina.png', + ), + }, + big: { + path: path.join( + getDirName(), + '../../../system-test/data/three-mb-file.tif', + ), + hash: undefined, + }, + html: { + path: path.join( + getDirName(), + '../../../system-test/data/long-html-file.html', + ), + }, + empty: { + path: path.join(getDirName(), '../../../system-test/data/empty-file.txt'), + }, + }; + + before(async () => { + await bucket.create(); + const data = await pubsub.createTopic(generateName()); + topic = data[0]; + await topic.iam.setPolicy({ + bindings: [ + { + role: 'roles/pubsub.editor', + members: ['allUsers'], + }, + ], + }); + }); + + after(() => { + return Promise.all([deleteAllBucketsAsync(), deleteAllTopicsAsync()]); + }); + + describe('without authentication', () => { + let privateBucket: Bucket; + let privateFile: File; + let storageWithoutAuth: Storage; + + let GOOGLE_APPLICATION_CREDENTIALS: string | undefined; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let GOOGLE_CLOUD_PROJECT: string | undefined; + + before(async () => { + // CI authentication is done with ADC. Cache it here, restore it `after` + GOOGLE_APPLICATION_CREDENTIALS = + process.env.GOOGLE_APPLICATION_CREDENTIALS; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT; + + privateBucket = bucket; // `bucket` was created in the global `before` + privateFile = privateBucket.file('file-name'); + await privateFile.save('data'); + }); + + beforeEach(() => { + delete process.env.GOOGLE_APPLICATION_CREDENTIALS; + delete process.env.GOOGLE_CLOUD_PROJECT; + + storageWithoutAuth = new Storage({ + retryOptions: { + idempotencyStrategy: IdempotencyStrategy.RetryAlways, + retryDelayMultiplier: 3, + }, + }); + }); + + after(() => { + process.env.GOOGLE_APPLICATION_CREDENTIALS = + GOOGLE_APPLICATION_CREDENTIALS; + process.env.GOOGLE_CLOUD_PROJECT = GOOGLE_APPLICATION_CREDENTIALS; + }); + + describe('public data', () => { + before(function () { + if (RUNNING_IN_VPCSC) this.skip(); + }); + + let bucket: Bucket; + + beforeEach(() => { + bucket = storageWithoutAuth.bucket('gcp-public-data-landsat'); + }); + + it('should list and download a file', async () => { + const [files] = await bucket.getFiles({autoPaginate: false}); + const file = files[0]; + const [isPublic] = await file.isPublic(); + assert.strictEqual(isPublic, true); + assert.doesNotReject(file.download()); + }); + }); + + describe('private data', () => { + let bucket: Bucket; + let file: File; + + beforeEach(() => { + bucket = storageWithoutAuth.bucket(privateBucket.id!); + file = bucket.file(privateFile.id!); + }); + + it('should not download a file', async () => { + const [isPublic] = await file.isPublic(); + assert.strictEqual(isPublic, false); + await assert.rejects( + file.download(), + (err: Error) => + err.message.indexOf('does not have storage.objects.get') > -1, + ); + }); + + it('should not upload a file', async () => { + try { + await file.save('new data'); + } catch (e) { + const allowedErrorMessages = [ + /Could not load the default credentials/, + /does not have storage\.objects\.create access/, + ]; + assert( + allowedErrorMessages.some(msg => msg.test((e as Error).message)), + ); + } + }); + }); + }); + + describe('acls', () => { + describe('buckets', () => { + // Some bucket update operations have a rate limit. + // Introduce a delay between tests to avoid getting an error. + beforeEach(async () => { + await new Promise(resolve => + setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME), + ); + }); + + it('should get access controls', async () => { + const accessControls = await bucket.acl.get(); + assert(Array.isArray(accessControls)); + }); + + it('should add entity to default access controls', async () => { + const [accessControl] = await bucket.acl.default.add({ + entity: USER_ACCOUNT, + role: storage.acl.OWNER_ROLE, + }); + assert.strictEqual(accessControl!.role, storage.acl.OWNER_ROLE); + + const [updatedAccessControl] = await bucket.acl.default.update({ + entity: USER_ACCOUNT, + role: storage.acl.READER_ROLE, + }); + assert.strictEqual(updatedAccessControl.role, storage.acl.READER_ROLE); + await bucket.acl.default.delete({entity: USER_ACCOUNT}); + }); + + it('should get default access controls', async () => { + const accessControls = await bucket.acl.default.get(); + assert(Array.isArray(accessControls)); + }); + + it('should grant an account access', async () => { + const [accessControl] = await bucket.acl.add({ + entity: USER_ACCOUNT, + role: storage.acl.OWNER_ROLE, + }); + assert.strictEqual(accessControl!.role, storage.acl.OWNER_ROLE); + const opts = {entity: USER_ACCOUNT}; + const [accessControlGet] = await bucket.acl.get(opts); + assert.strictEqual( + (accessControlGet as AccessControlObject).role, + storage.acl.OWNER_ROLE, + ); + await bucket.acl.delete(opts); + }); + + it('should update an account', async () => { + const [accessControl] = await bucket.acl.add({ + entity: USER_ACCOUNT, + role: storage.acl.OWNER_ROLE, + }); + assert.strictEqual(accessControl!.role, storage.acl.OWNER_ROLE); + const [updatedAcl] = await bucket.acl.update({ + entity: USER_ACCOUNT, + role: storage.acl.WRITER_ROLE, + }); + assert.strictEqual(updatedAcl!.role, storage.acl.WRITER_ROLE); + await bucket.acl.delete({entity: USER_ACCOUNT}); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('should make a bucket public', async () => { + await bucket.makePublic(); + const [aclObject] = await bucket.acl.get({entity: 'allUsers'}); + assert.deepStrictEqual(aclObject, { + entity: 'allUsers', + role: 'READER', + }); + await new Promise(resolve => + setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME), + ); + await bucket.acl.delete({entity: 'allUsers'}); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('should make files public', async () => { + await Promise.all( + ['a', 'b', 'c'].map(text => createFileWithContentPromise(text)), + ); + + await bucket.makePublic({includeFiles: true}); + const [files] = await bucket.getFiles(); + const resps = await Promise.all( + files.map(file => isFilePublicAsync(file)), + ); + resps.forEach(resp => assert.strictEqual(resp, true)); + await Promise.all([ + bucket.acl.default.delete({entity: 'allUsers'}), + bucket.deleteFiles(), + ]); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('should make a bucket private', async () => { + try { + await bucket.makePublic(); + await new Promise(resolve => + setTimeout(resolve, BUCKET_METADATA_UPDATE_WAIT_TIME), + ); + await bucket.makePrivate(); + assert.rejects(bucket.acl.get({entity: 'allUsers'}), err => { + assert.strictEqual((err as ApiError).code, 404); + assert.strictEqual((err as ApiError).errors![0].reason, 'notFound'); + }); + } catch (err) { + assert.ifError(err); + } + }); + + it('should make files private', async () => { + await Promise.all( + ['a', 'b', 'c'].map(text => createFileWithContentPromise(text)), + ); + + await bucket.makePrivate({includeFiles: true}); + const [files] = await bucket.getFiles(); + const resps = await Promise.all( + files.map(file => isFilePublicAsync(file)), + ); + resps.forEach(resp => { + assert.strictEqual(resp, false); + }); + await bucket.deleteFiles(); + }); + }); + + describe('files', () => { + let file: File; + + beforeEach(async () => { + const options = { + destination: generateName() + '.png', + }; + [file] = await bucket.upload(FILES.logo.path, options); + }); + + afterEach(async () => { + await file.delete(); + }); + + it('should get access controls', async () => { + const [accessControls] = await file.acl.get(); + assert(Array.isArray(accessControls)); + }); + + it('should not expose default api', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.strictEqual(typeof (file as any).default, 'undefined'); + }); + + it('should grant an account access', async () => { + const [accessControl] = await file.acl.add({ + entity: USER_ACCOUNT, + role: storage.acl.OWNER_ROLE, + }); + assert.strictEqual(accessControl!.role, storage.acl.OWNER_ROLE); + const [accessControlGet] = await file.acl.get({entity: USER_ACCOUNT}); + assert.strictEqual( + (accessControlGet as AccessControlObject).role, + storage.acl.OWNER_ROLE, + ); + await file.acl.delete({entity: USER_ACCOUNT}); + }); + + it('should update an account', async () => { + const [accessControl] = await file.acl.add({ + entity: USER_ACCOUNT, + role: storage.acl.OWNER_ROLE, + }); + assert.strictEqual(accessControl!.role, storage.acl.OWNER_ROLE); + const [accessControlUpdate] = await file.acl.update({ + entity: USER_ACCOUNT, + role: storage.acl.READER_ROLE, + }); + assert.strictEqual(accessControlUpdate!.role, storage.acl.READER_ROLE); + await file.acl.delete({entity: USER_ACCOUNT}); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('should make a file public', async () => { + await file.makePublic(); + const [aclObject] = await file.acl.get({entity: 'allUsers'}); + assert.deepStrictEqual(aclObject, { + entity: 'allUsers', + role: 'READER', + }); + await file.acl.delete({entity: 'allUsers'}); + }); + + it('should make a file private', async () => { + const validateMakeFilePrivateRejects = (err: ApiError) => { + assert.strictEqual(err.code, 404); + assert.strictEqual(err!.errors![0].reason, 'notFound'); + return true; + }; + assert.doesNotReject(file.makePublic()); + assert.doesNotReject(file.makePrivate()); + assert.rejects( + file.acl.get({entity: 'allUsers'}), + validateMakeFilePrivateRejects, + ); + }); + + it('should set custom encryption during the upload', async () => { + const key = '12345678901234567890123456789012'; + const [file] = await bucket.upload(FILES.big.path, { + encryptionKey: key, + resumable: false, + }); + const [metadata] = await file.getMetadata(); + const encryptionAlgorithm = + metadata.customerEncryption?.encryptionAlgorithm; + assert.strictEqual(encryptionAlgorithm, 'AES256'); + }); + + it('should set custom encryption in a resumable upload', async () => { + const key = crypto.randomBytes(32); + const [file] = await bucket.upload(FILES.big.path, { + encryptionKey: key, + resumable: true, + }); + const [metadata] = await file.getMetadata(); + const encryptionAlgorithm = + metadata.customerEncryption?.encryptionAlgorithm; + assert.strictEqual(encryptionAlgorithm, 'AES256'); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('should make a file public during the upload', async () => { + const [file] = await bucket.upload(FILES.big.path, { + resumable: false, + public: true, + }); + + const [aclObject] = await file.acl.get({entity: 'allUsers'}); + assert.deepStrictEqual(aclObject, { + entity: 'allUsers', + role: 'READER', + }); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('should make a file public from a resumable upload', async () => { + const [file] = await bucket.upload(FILES.big.path, { + resumable: true, + public: true, + }); + const [aclObject] = await file.acl.get({entity: 'allUsers'}); + assert.deepStrictEqual(aclObject, { + entity: 'allUsers', + role: 'READER', + }); + }); + + it('should make a file private from a resumable upload', async () => { + const validateMakeFilePrivateRejects = (err: ApiError) => { + assert.strictEqual((err as ApiError)!.code, 404); + assert.strictEqual((err as ApiError).errors![0].reason, 'notFound'); + return true; + }; + assert.doesNotReject( + bucket.upload(FILES.big.path, { + resumable: true, + private: true, + }), + ); + assert.rejects( + file.acl.get({entity: 'allUsers'}), + validateMakeFilePrivateRejects, + ); + }); + }); + }); + + describe('iam', () => { + let PROJECT_ID: string; + + before(async () => { + PROJECT_ID = await storage.authClient.getProjectId(); + }); + + describe('buckets', () => { + let bucket: Bucket; + + before(() => { + bucket = storage.bucket(generateName()); + return bucket.create(); + }); + + it('should get a policy', async () => { + const [policy] = await bucket.iam.getPolicy(); + assert.deepStrictEqual(policy!.bindings, [ + { + members: [ + 'projectEditor:' + PROJECT_ID, + 'projectOwner:' + PROJECT_ID, + ], + role: 'roles/storage.legacyBucketOwner', + }, + { + members: ['projectViewer:' + PROJECT_ID], + role: 'roles/storage.legacyBucketReader', + }, + ]); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('should set a policy', async () => { + const [policy] = await bucket.iam.getPolicy(); + policy!.bindings.push({ + role: 'roles/storage.legacyBucketReader', + members: ['allUsers'], + }); + const [newPolicy] = await bucket.iam.setPolicy(policy); + const legacyBucketReaderBinding = newPolicy!.bindings.filter( + binding => { + return binding.role === 'roles/storage.legacyBucketReader'; + }, + )[0]; + assert(legacyBucketReaderBinding.members.includes('allUsers')); + }); + + it('should get-modify-set a conditional policy', async () => { + // Uniform-bucket-level-access is required to use IAM Conditions. + await bucket.setMetadata({ + iamConfiguration: { + uniformBucketLevelAccess: { + enabled: true, + }, + }, + }); + + const [policy] = await bucket.iam.getPolicy(); + + const serviceAccount = (await storage.authClient.getCredentials()) + .client_email; + const conditionalBinding = { + role: 'roles/storage.objectViewer', + members: [`serviceAccount:${serviceAccount}`], + condition: { + title: 'always-true', + description: 'this condition is always effective', + expression: 'true', + }, + }; + + policy.version = 3; + policy.bindings.push(conditionalBinding); + + await bucket.iam.setPolicy(policy); + + const [newPolicy] = await bucket.iam.getPolicy({ + requestedPolicyVersion: 3, + }); + assert.deepStrictEqual(newPolicy.bindings, policy.bindings); + }); + + it('should test the iam permissions', async () => { + const testPermissions = [ + 'storage.buckets.get', + 'storage.buckets.getIamPolicy', + ]; + const [permissions] = await bucket.iam.testPermissions(testPermissions); + assert.deepStrictEqual(permissions, { + 'storage.buckets.get': true, + 'storage.buckets.getIamPolicy': true, + }); + }); + }); + }); + + describe('public access prevention', () => { + let bucket: Bucket; + + const PUBLIC_ACCESS_PREVENTION_INHERITED = 'inherited'; + const PUBLIC_ACCESS_PREVENTION_ENFORCED = 'enforced'; + + const createBucket = () => { + bucket = storage.bucket(generateName()); + return bucket.create(); + }; + + const setPublicAccessPrevention = ( + bucket: Bucket, + configuration: string, + ) => { + return bucket.setMetadata({ + iamConfiguration: { + publicAccessPrevention: configuration, + }, + }); + }; + + const validateUnexpectedPublicAccessPreventionValueError = ( + err: ApiError, + ) => { + assert.strictEqual(err.code, 400); + return true; + }; + + const validateConfiguringPublicAccessWhenPAPEnforcedError = ( + err: ApiError, + ) => { + assert.strictEqual(err.code, 412); + return true; + }; + + beforeEach(createBucket); + + it('inserts a bucket with enforced public access prevention', async () => { + await setPublicAccessPrevention( + bucket, + PUBLIC_ACCESS_PREVENTION_ENFORCED, + ); + const [bucketMetadata] = await bucket.getMetadata(); + const publicAccessPreventionStatus = + bucketMetadata!.iamConfiguration!.publicAccessPrevention; + return assert.strictEqual( + publicAccessPreventionStatus, + PUBLIC_ACCESS_PREVENTION_ENFORCED, + ); + }); + + describe('enforced public access prevention behavior', () => { + let bucket: Bucket; + let file: File; + + before(async () => { + bucket = storage.bucket(generateName()); + await bucket.create(); + + const name = 'enforcedPAPBucketFile'; + const contents = + 'Enforced public access prevention bucket file contents'; + file = bucket.file(name); + await file.save(contents); + + await setPublicAccessPrevention( + bucket, + PUBLIC_ACCESS_PREVENTION_ENFORCED, + ); + }); + + it('bucket cannot be made public', async () => { + return assert.rejects( + () => bucket.makePublic(), + validateConfiguringPublicAccessWhenPAPEnforcedError, + ); + }); + + it('object cannot be made public via ACL', async () => { + return assert.rejects( + () => file.makePublic(), + validateConfiguringPublicAccessWhenPAPEnforcedError, + ); + }); + }); + + it('inserts a bucket with inherited public access prevention', async () => { + await setPublicAccessPrevention( + bucket, + PUBLIC_ACCESS_PREVENTION_INHERITED, + ); + const [bucketMetadata] = await bucket.getMetadata(); + const publicAccessPreventionStatus = + bucketMetadata!.iamConfiguration!.publicAccessPrevention; + return assert.strictEqual( + publicAccessPreventionStatus, + PUBLIC_ACCESS_PREVENTION_INHERITED, + ); + }); + + it('makes public a bucket with inherited public access prevention', async () => { + await setPublicAccessPrevention( + bucket, + PUBLIC_ACCESS_PREVENTION_INHERITED, + ); + return assert.ok(() => bucket.makePublic()); + }); + + it('should fail to insert a bucket with unexpected public access prevention value', async () => { + await assert.rejects( + () => setPublicAccessPrevention(bucket, 'unexpected value'), + validateUnexpectedPublicAccessPreventionValueError, + ); + }); + + it('UBLA modification on PAP bucket does not affect pap setting', async () => { + const [bucketMetadata] = await bucket.getMetadata(); + const publicAccessPreventionStatus = + bucketMetadata!.iamConfiguration!.publicAccessPrevention; + await bucket.setMetadata({ + iamConfiguration: { + uniformBucketLevelAccess: { + enabled: true, + }, + }, + }); + const [updatedBucketMetadata] = await bucket.getMetadata(); + return assert.strictEqual( + updatedBucketMetadata!.iamConfiguration!.publicAccessPrevention, + publicAccessPreventionStatus, + ); + }); + + it('PAP modification on UBLA bucket should not affect UBLA setting', async () => { + await bucket.setMetadata({ + iamConfiguration: { + uniformBucketLevelAccess: { + enabled: true, + }, + }, + }); + const [bucketMetadata] = await bucket.getMetadata(); + const ublaSetting = + bucketMetadata!.iamConfiguration!.uniformBucketLevelAccess!.enabled; + await setPublicAccessPrevention( + bucket, + PUBLIC_ACCESS_PREVENTION_INHERITED, + ); + const [updatedBucketMetadata] = await bucket.getMetadata(); + return assert.strictEqual( + updatedBucketMetadata!.iamConfiguration!.uniformBucketLevelAccess! + .enabled, + ublaSetting, + ); + }); + }); + + describe('turbo replication', () => { + let bucket: Bucket; + + const RPO_ASYNC_TURBO = 'ASYNC_TURBO'; + const RPO_DEFAULT = 'DEFAULT'; + + const createBucket = () => { + bucket = storage.bucket(generateName()); + return bucket.create({location: 'NAM4'}); + }; + + const setTurboReplication = ( + bucket: Bucket, + turboReplicationConfiguration: string, + ) => { + return bucket.setMetadata({ + rpo: turboReplicationConfiguration, + }); + }; + + beforeEach(createBucket); + + afterEach(async () => { + await bucket.delete(); + }); + + it("sets bucket's RPO to ASYNC_TURBO", async () => { + await setTurboReplication(bucket, RPO_ASYNC_TURBO); + const [bucketMetadata] = await bucket.getMetadata(); + return assert.strictEqual(bucketMetadata.rpo, RPO_ASYNC_TURBO); + }); + + it("sets a bucket's RPO to DEFAULT", async () => { + await setTurboReplication(bucket, RPO_DEFAULT); + const [bucketMetadata] = await bucket.getMetadata(); + return assert.strictEqual(bucketMetadata.rpo, RPO_DEFAULT); + }); + }); + + describe('soft-delete', () => { + describe('buckets', () => { + let bucket: Bucket; + const SOFT_DELETE_RETENTION_SECONDS = 7 * 24 * 60 * 60; //7 days in seconds; + let generation: string; + + before(async () => { + bucket = storage.bucket(generateName()); + await bucket.create(); + await bucket.setMetadata({ + softDeletePolicy: { + retentionDurationSeconds: SOFT_DELETE_RETENTION_SECONDS, + }, + }); + + const [metadata] = await bucket.getMetadata(); + generation = metadata!.generation!; + await bucket.delete(); + }); + + after(async () => { + await bucket.delete(); + }); + + it('should be listing soft-deleted buckets', async () => { + const [buckets] = await storage.getBuckets({softDeleted: true}); + assert(buckets.length > 0); + + buckets.forEach(bucket => { + assert(bucket.name); + assert(bucket.metadata.generation); + assert(bucket.metadata.softDeleteTime); + assert(bucket.metadata.hardDeleteTime); + }); + }); + + it('should GET a soft-deleted bucket', async () => { + const [softDeletedBucket] = await storage + .bucket(bucket.name) + .getMetadata({ + softDeleted: true, + generation: generation, + }); + assert(softDeletedBucket); + assert.strictEqual(softDeletedBucket.generation, generation); + assert(softDeletedBucket.softDeleteTime); + assert(softDeletedBucket.hardDeleteTime); + }); + + it('should restore a soft-deleted bucket', async () => { + const restoredBucket = await storage.bucket(bucket.name).restore({ + generation: generation, + }); + assert(restoredBucket); + const [metadata] = await bucket.getMetadata(); + assert(metadata); + }); + }); + + describe('files', () => { + let bucket: Bucket; + let hnsBucket: Bucket; + const SOFT_DELETE_RETENTION_SECONDS = 7 * 24 * 60 * 60; //7 days in seconds; + + beforeEach(async () => { + bucket = storage.bucket(generateName()); + await bucket.create(); + await bucket.setMetadata({ + softDeletePolicy: { + retentionDurationSeconds: SOFT_DELETE_RETENTION_SECONDS, + }, + }); + + hnsBucket = storage.bucket(generateName()); + await storage.createBucket(hnsBucket.name, { + hierarchicalNamespace: {enabled: true}, + iamConfiguration: { + uniformBucketLevelAccess: { + enabled: true, + }, + }, + softDeletePolicy: { + retentionDurationSeconds: SOFT_DELETE_RETENTION_SECONDS, + }, + }); + }); + + afterEach(async () => { + await bucket.deleteFiles({force: true, versions: true}); + await bucket.delete(); + await hnsBucket.deleteFiles({force: true, versions: true}); + await hnsBucket.delete(); + }); + + it('should set softDeletePolicy correctly', async () => { + const metadata = await bucket.getMetadata(); + assert(metadata[0].softDeletePolicy); + assert(metadata[0].softDeletePolicy.effectiveTime); + assert.deepStrictEqual( + metadata[0].softDeletePolicy.retentionDurationSeconds, + SOFT_DELETE_RETENTION_SECONDS.toString(), + ); + }); + + it('should LIST soft-deleted files', async () => { + const f1 = bucket.file('file1'); + const f2 = bucket.file('file2'); + await f1.save('file1'); + await f2.save('file2'); + await f1.delete(); + await f2.delete(); + const [notSoftDeletedFiles] = await bucket.getFiles(); + assert.strictEqual(notSoftDeletedFiles.length, 0); + const [softDeletedFiles] = await bucket.getFiles({softDeleted: true}); + assert.strictEqual(softDeletedFiles.length, 2); + }); + + it('should GET a soft-deleted file', async () => { + const f1 = bucket.file('file3'); + await f1.save('file3'); + const [metadata] = await f1.getMetadata(); + await f1.delete(); + const [softDeletedFile] = await f1.get({ + softDeleted: true, + generation: parseInt(metadata.generation?.toString() || '0'), + }); + assert(softDeletedFile); + assert.strictEqual( + softDeletedFile.metadata.generation, + metadata.generation, + ); + }); + + it('should restore a soft-deleted file', async () => { + const f1 = bucket.file('file4'); + await f1.save('file4'); + const [metadata] = await f1.getMetadata(); + await f1.delete(); + let [files] = await bucket.getFiles(); + assert.strictEqual(files.length, 0); + const restoredFile = await f1.restore({ + generation: parseInt(metadata.generation?.toString() || '0'), + }); + assert(restoredFile); + [files] = await bucket.getFiles(); + assert.strictEqual(files.length, 1); + }); + + it('should LIST soft-deleted files with restore token', async () => { + const f1 = hnsBucket.file('file5a'); + const f2 = hnsBucket.file('file5b'); + await f1.save('file5a'); + await f2.save('file5b'); + await f1.delete(); + await f2.delete(); + const [notSoftDeletedFiles] = await hnsBucket.getFiles(); + assert.strictEqual(notSoftDeletedFiles.length, 0); + const [softDeletedFiles] = await hnsBucket.getFiles({ + softDeleted: true, + }); + assert.strictEqual(softDeletedFiles.length, 2); + assert.notStrictEqual( + softDeletedFiles![0].metadata.restoreToken, + undefined, + ); + }); + + it('should GET a soft-deleted file with restore token', async () => { + const f1 = hnsBucket.file('file6'); + await f1.save('file6'); + const [metadata] = await f1.getMetadata(); + await f1.delete(); + const [softDeletedFile] = await f1.get({ + softDeleted: true, + generation: parseInt(metadata.generation?.toString() || '0'), + }); + assert(softDeletedFile); + assert.strictEqual( + softDeletedFile.metadata.generation, + metadata.generation, + ); + assert.notStrictEqual(softDeletedFile.metadata.restoreToken, undefined); + }); + + it('should restore a soft-deleted file using restoreToken', async () => { + const f1 = hnsBucket.file('file7'); + await f1.save('file7'); + const [metadata] = await f1.getMetadata(); + await f1.delete(); + let [files] = await hnsBucket.getFiles(); + assert.strictEqual(files.length, 0); + const [softDeletedFile] = await f1.get({ + softDeleted: true, + generation: parseInt(metadata.generation?.toString() || '0'), + }); + assert(softDeletedFile); + const restoredFile = await f1.restore({ + generation: parseInt( + softDeletedFile.metadata.generation?.toString() || '0', + ), + restoreToken: softDeletedFile.metadata.restoreToken, + }); + assert(restoredFile); + [files] = await hnsBucket.getFiles(); + assert.strictEqual(files.length, 1); + }); + }); + }); + + describe('dual-region', () => { + let bucket: Bucket; + + const LOCATION = 'US'; + const REGION1 = 'US-EAST1'; + const REGION2 = 'US-WEST1'; + + beforeEach(() => { + bucket = storage.bucket(generateName()); + }); + + it('creates a dual-region bucket', async () => { + await bucket.create({ + location: LOCATION, + customPlacementConfig: { + dataLocations: [REGION1, REGION2], + }, + }); + + const [exists] = await bucket.exists(); + assert.strictEqual(exists, true); + + const [bucketMetadata] = await bucket.getMetadata(); + + assert.strictEqual(bucketMetadata.location, LOCATION); + + assert(bucketMetadata.customPlacementConfig); + assert(Array.isArray(bucketMetadata.customPlacementConfig.dataLocations)); + + const dataLocations = bucketMetadata.customPlacementConfig.dataLocations; + + assert(dataLocations.includes(REGION1)); + assert(dataLocations.includes(REGION2)); + + assert.strictEqual(bucketMetadata.locationType, 'dual-region'); + }); + }); + + describe('uniform bucket-level access', () => { + let bucket: Bucket; + + const customAcl = { + entity: USER_ACCOUNT, + role: storage.acl.OWNER_ROLE, + }; + + const createBucket = () => { + bucket = storage.bucket(generateName()); + return bucket.create(); + }; + + const setUniformBucketLevelAccess = (bucket: Bucket, enabled: boolean) => { + return bucket.setMetadata({ + iamConfiguration: { + uniformBucketLevelAccess: { + enabled, + }, + }, + }); + }; + + describe('files', () => { + before(createBucket); + + it('can be written to the bucket by project owner w/o configuration', async () => { + await setUniformBucketLevelAccess(bucket, true); + const file = bucket.file(`file-${uuid.v4()}`); + return assert.doesNotReject(() => file.save('data')); + }); + }); + + describe('disables file ACL', () => { + let file: File; + + const validateUniformBucketLevelAccessEnabledError = (err: ApiError) => { + assert.strictEqual(err.code, 400); + return true; + }; + + before(async () => { + await createBucket(); + await setUniformBucketLevelAccess(bucket, true); + + file = bucket.file(`file-${uuid.v4()}`); + await file.save('data', {resumable: false}); + }); + + it('should fail to get file ACL', async () => { + // Setting uniform bucket level access is eventually consistent and may take up to a minute to be reflected + for (;;) { + try { + await file.acl.get(); + await new Promise(res => setTimeout(res, UNIFORM_ACCESS_WAIT_TIME)); + } catch (err) { + assert( + validateUniformBucketLevelAccessEnabledError(err as ApiError), + ); + break; + } + } + }).timeout(UNIFORM_ACCESS_TIMEOUT); + + it('should fail to update file ACL', async () => { + // Setting uniform bucket level access is eventually consistent and may take up to a minute to be reflected + for (;;) { + try { + await file.acl.update(customAcl); + await new Promise(res => setTimeout(res, UNIFORM_ACCESS_WAIT_TIME)); + } catch (err) { + assert( + validateUniformBucketLevelAccessEnabledError(err as ApiError), + ); + break; + } + } + }).timeout(UNIFORM_ACCESS_TIMEOUT); + }); + + describe('preserves bucket/file ACL over uniform bucket-level access on/off', () => { + beforeEach(createBucket); + + it('should preserve default bucket ACL', async () => { + await bucket.acl.default.update(customAcl); + const [aclBefore] = await bucket.acl.default.get(); + + await setUniformBucketLevelAccess(bucket, true); + await setUniformBucketLevelAccess(bucket, false); + + // Setting uniform bucket level access is eventually consistent and may take up to a minute to be reflected + for (;;) { + try { + const [aclAfter] = await bucket.acl.default.get(); + assert.deepStrictEqual(aclAfter, aclBefore); + break; + } catch { + await new Promise(res => setTimeout(res, UNIFORM_ACCESS_WAIT_TIME)); + } + } + }).timeout(UNIFORM_ACCESS_TIMEOUT); + + it('should preserve file ACL', async () => { + const file = bucket.file(`file-${uuid.v4()}`); + await file.save('data', {resumable: false}); + + await file.acl.update(customAcl); + const [aclBefore] = await file.acl.get(); + + await setUniformBucketLevelAccess(bucket, true); + await setUniformBucketLevelAccess(bucket, false); + + // Setting uniform bucket level access is eventually consistent and may take up to a minute to be reflected + for (;;) { + try { + const [aclAfter] = await file.acl.get(); + assert.deepStrictEqual(aclAfter, aclBefore); + break; + } catch { + await new Promise(res => setTimeout(res, UNIFORM_ACCESS_WAIT_TIME)); + } + } + }).timeout(UNIFORM_ACCESS_TIMEOUT); + }); + }); + + describe('unicode validation', () => { + before(function () { + if (RUNNING_IN_VPCSC) this.skip(); + }); + + let bucket: Bucket; + + before(async () => { + [bucket] = await storage.createBucket(generateName()); + }); + + // Normalization form C: a single character for e-acute; + // URL should end with Cafe%CC%81 + it('should not perform normalization form C', async () => { + const name = 'Caf\u00e9'; + const expectedContents = 'Normalization Form C'; + + const file = bucket.file(name); + await file.save(expectedContents); + + return file + .get() + .then(data => { + const receivedFile = data[0]; + assert.strictEqual(receivedFile.name, name); + return receivedFile.download(); + }) + .then(contents => { + assert.strictEqual(contents.toString(), expectedContents); + }); + }); + + // Normalization form D: an ASCII character followed by U+0301 combining + // character; URL should end with Caf%C3%A9 + it('should not perform normalization form D', async () => { + const name = 'Cafe\u0301'; + const expectedContents = 'Normalization Form D'; + + const file = bucket.file(name); + await file.save(expectedContents); + + return file + .get() + .then(data => { + const receivedFile = data[0]; + assert.strictEqual(receivedFile.name, name); + return receivedFile.download(); + }) + .then(contents => { + assert.strictEqual(contents.toString(), expectedContents); + }); + }); + }); + + describe('getting buckets', () => { + const bucketsToCreate = [generateName(), generateName()]; + + before(async () => { + await Promise.all(bucketsToCreate.map(b => storage.createBucket(b))); + }); + + after(async () => { + await Promise.all( + bucketsToCreate.map(bucket => storage.bucket(bucket).delete()), + ); + }); + + it('should get buckets', async () => { + const [buckets] = await storage.getBuckets(); + const createdBuckets = buckets.filter(bucket => { + return bucketsToCreate.indexOf(bucket.name) > -1; + }); + assert.strictEqual(createdBuckets.length, bucketsToCreate.length); + }); + + it('should get buckets as a stream', done => { + let bucketEmitted = false; + + storage + .getBucketsStream() + .on('error', done) + .on('data', bucket => { + bucketEmitted = bucket instanceof Bucket; + }) + .on('end', () => { + assert.strictEqual(bucketEmitted, true); + done(); + }); + }); + }); + + describe('bucket metadata', () => { + it('should allow setting metadata on a bucket', async () => { + const metadata = { + website: { + mainPageSuffix: 'http://fakeuri', + notFoundPage: 'http://fakeuri/404.html', + }, + }; + const [meta] = await bucket.setMetadata(metadata); + assert.deepStrictEqual(meta.website, metadata.website); + }); + + it('should allow changing the storage class', async () => { + const bucket = storage.bucket(generateName()); + await bucket.create(); + let [metadata] = await bucket.getMetadata(); + assert.strictEqual(metadata.storageClass, 'STANDARD'); + await bucket.setStorageClass('coldline'); + [metadata] = await bucket.getMetadata(); + assert.strictEqual(metadata.storageClass, 'COLDLINE'); + }); + + it('should allow enabling & disabling autoclass', async () => { + const [bucket] = await storage.createBucket(generateName(), { + autoclass: { + enabled: true, + terminalStorageClass: 'ARCHIVE', + }, + }); + let [metadata] = await bucket.getMetadata(); + const timestampEnabled = metadata!.autoclass!.toggleTime; + assert.strictEqual(metadata!.autoclass!.enabled, true); + assert.strictEqual(metadata!.autoclass?.terminalStorageClass, 'ARCHIVE'); + [metadata] = await bucket.setMetadata({ + autoclass: { + enabled: false, + }, + }); + const timestampDisabled = metadata!.autoclass!.toggleTime; + assert.strictEqual(metadata!.autoclass!.enabled, false); + assert.strictEqual(timestampDisabled! > timestampEnabled!, true); + }); + + describe('locationType', () => { + const types = ['multi-region', 'region', 'dual-region']; + + beforeEach(() => { + bucket.metadata = {}; + }); + + it('should be available from getting a bucket', async () => { + const [metadata] = await bucket.getMetadata(); + assert(types.includes(metadata.locationType!)); + }); + + it('should be available from creating a bucket', async () => { + const [bucket] = await storage.createBucket(generateName()); + assert(types.includes(bucket.metadata.locationType!)); + return bucket.delete(); + }); + + it('should be available from listing buckets', async () => { + const [buckets] = await storage.getBuckets(); + + assert(buckets.length > 0); + + buckets.forEach(bucket => { + assert(types.includes(bucket.metadata.locationType!)); + }); + }); + + it('should be available from setting retention policy', async () => { + await bucket.setRetentionPeriod(RETENTION_DURATION_SECONDS); + assert(types.includes(bucket.metadata.locationType!)); + await bucket.removeRetentionPeriod(); + }); + + it('should be available from updating a bucket', async () => { + await bucket.setMetadata({labels: {a: 'b'}}); + assert(types.includes(bucket.metadata.locationType!)); + }); + }); + + describe('labels', () => { + const LABELS = { + label: 'labelvalue', // no caps or spaces allowed (?) + labeltwo: 'labelvaluetwo', + }; + + beforeEach(async () => { + const [metadata] = await bucket.getMetadata(); + const labels: {[index: string]: string | null} = {}; + if (metadata.labels) { + for (const curLabel of Object.keys(metadata.labels)) { + labels[curLabel] = null; + } + await bucket.setMetadata({labels}); + } + }); + + it('should set labels', async () => { + await bucket.setMetadata({labels: LABELS}); + const [metadata] = await bucket.getMetadata(); + assert.deepStrictEqual(metadata.labels, LABELS); + }); + + it('should update labels', async () => { + const newLabels = { + siblinglabel: 'labelvalue', + }; + await bucket.setMetadata({labels: LABELS}); + await bucket.setMetadata({labels: newLabels}); + const [metadata] = await bucket.getMetadata(); + assert.deepStrictEqual( + metadata.labels, + Object.assign({}, LABELS, newLabels), + ); + }); + + it('should delete a single label', async () => { + if (Object.keys(LABELS).length <= 1) { + throw new Error('Maintainer Error: `LABELS` needs 2 labels.'); + } + + const labelKeyToDelete = Object.keys(LABELS)[0]; + await bucket.setMetadata({labels: LABELS}); + const labelsToDelete = { + [labelKeyToDelete]: null, + }; + await bucket.setMetadata({labels: labelsToDelete}); + const [metadata] = await bucket.getMetadata(); + const expectedLabels = Object.assign({}, LABELS); + delete (expectedLabels as {[index: string]: {}})[labelKeyToDelete]; + + assert.deepStrictEqual(metadata.labels, expectedLabels); + }); + + it('should delete all labels', async () => { + let [metadata] = await bucket.getMetadata(); + if (metadata.labels) { + const labels: {[index: string]: string | null} = {}; + for (const curLabel of Object.keys(metadata.labels)) { + labels[curLabel] = null; + } + await bucket.setMetadata({labels}); + } + [metadata] = await bucket.getMetadata(); + assert.deepStrictEqual(metadata.labels, undefined); + }); + }); + }); + + describe('bucket object lifecycle management', () => { + it('should add a rule', async () => { + await bucket.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + age: 30, + isLive: true, + }, + }); + + const rules = [].slice.call(bucket.metadata.lifecycle?.rule); + assert.deepStrictEqual(rules.pop(), { + action: { + type: 'Delete', + }, + condition: { + age: 30, + isLive: true, + }, + }); + }); + + it('should append a new rule', async () => { + const numExistingRules = + (bucket.metadata.lifecycle && bucket.metadata.lifecycle.rule!.length) || + 0; + + await bucket.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + age: 30, + isLive: true, + }, + }); + await bucket.addLifecycleRule({ + action: { + type: 'SetStorageClass', + storageClass: 'coldline', + }, + condition: { + age: 60, + isLive: true, + }, + }); + assert.strictEqual( + bucket.metadata.lifecycle!.rule!.length, + numExistingRules + 2, + ); + }); + + it('should add a prefix rule', async () => { + await bucket.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + matchesPrefix: [TESTS_PREFIX], + }, + }); + + assert( + bucket.metadata.lifecycle!.rule!.some( + (rule: LifecycleRule) => + typeof rule.action === 'object' && + rule.action.type === 'Delete' && + typeof rule.condition.matchesPrefix === 'object' && + (rule.condition.matchesPrefix as string[]).length === 1 && + Array.isArray(rule.condition.matchesPrefix), + ), + ); + }); + + it('should add a suffix rule', async () => { + await bucket.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + matchesSuffix: [TESTS_PREFIX, 'test_suffix'], + }, + }); + + assert( + bucket.metadata.lifecycle!.rule!.some( + (rule: LifecycleRule) => + typeof rule.action === 'object' && + rule.action.type === 'Delete' && + Array.isArray(rule.condition.matchesPrefix), + ), + ); + }); + + it('should convert a rule with createdBefore to a date in string', async () => { + await bucket.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + createdBefore: new Date('2018'), + }, + }); + const rules = [].slice.call(bucket.metadata.lifecycle?.rule); + assert.deepStrictEqual(rules.pop(), { + action: { + type: 'Delete', + }, + condition: { + createdBefore: '2018-01-01', + }, + }); + }); + + it('should add a noncurrent time rule', async () => { + const NONCURRENT_TIME_BEFORE = '2020-01-01'; + + await bucket.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + noncurrentTimeBefore: new Date(NONCURRENT_TIME_BEFORE), + daysSinceNoncurrentTime: 100, + }, + }); + + assert( + bucket.metadata.lifecycle!.rule!.some( + (rule: LifecycleRule) => + typeof rule.action === 'object' && + rule.action.type === 'Delete' && + rule.condition.noncurrentTimeBefore === NONCURRENT_TIME_BEFORE && + rule.condition.daysSinceNoncurrentTime === 100, + ), + ); + }); + + it('should add a custom time rule', async () => { + const CUSTOM_TIME_BEFORE = '2020-01-01'; + + await bucket.addLifecycleRule({ + action: { + type: 'Delete', + }, + condition: { + customTimeBefore: new Date(CUSTOM_TIME_BEFORE), + daysSinceCustomTime: 100, + }, + }); + + assert( + bucket.metadata.lifecycle!.rule!.some( + (rule: LifecycleRule) => + typeof rule.action === 'object' && + rule.action.type === 'Delete' && + rule.condition.customTimeBefore === CUSTOM_TIME_BEFORE && + rule.condition.daysSinceCustomTime === 100, + ), + ); + }); + + it('should remove all existing rules', async () => { + await bucket.setMetadata({ + lifecycle: null, + }); + + assert.strictEqual(bucket.metadata.lifecycle, undefined); + }); + }); + + describe('cors configuration', () => { + const corsEntry = [ + { + maxAgeSeconds: 1600, + }, + { + maxAgeSeconds: 3600, + method: ['GET', 'POST'], + origin: ['*'], + responseHeader: ['Content-Type', 'Access-Control-Allow-Origin'], + }, + ]; + + describe('bucket', () => { + it('should create a bucket with a CORS configuration when passed in', async () => { + const bucket = storage.bucket(generateName()); + await storage.createBucket(bucket.name, { + cors: corsEntry, + }); + + await bucket.getMetadata(); + assert.deepStrictEqual(bucket.metadata.cors, corsEntry); + }); + + it('should set a CORS configuration', async () => { + const bucket = storage.bucket(generateName()); + await bucket.create(); + await bucket.setCorsConfiguration(corsEntry); + await bucket.getMetadata(); + assert.deepStrictEqual(bucket.metadata.cors, corsEntry); + }); + + it('should remove a CORS configuration', async () => { + const bucket = storage.bucket(generateName()); + await bucket.create(); + await bucket.setCorsConfiguration(corsEntry); + await bucket.getMetadata(); + assert.deepStrictEqual(bucket.metadata.cors, corsEntry); + + // And now test the removing + await bucket.setCorsConfiguration([]); + assert.ok(!bucket.metadata.cors); + }); + }); + }); + + describe('bucket versioning', () => { + describe('bucket', () => { + it('should create a bucket with versioning enabled', async () => { + const bucket = storage.bucket(generateName()); + await storage.createBucket(bucket.name, { + versioning: { + enabled: true, + }, + }); + await bucket.getMetadata(); + assert.strictEqual(bucket.metadata!.versioning!.enabled, true); + }); + + it('should by default create a bucket without versioning set', async () => { + const bucket = storage.bucket(generateName()); + await storage.createBucket(bucket.name); + await bucket.getMetadata(); + assert.strictEqual(bucket.metadata.versioning, undefined); + }); + }); + }); + + describe('bucket hierarchical namespace', async () => { + let bucket: Bucket; + + beforeEach(() => { + bucket = storage.bucket(generateName()); + }); + + afterEach(async () => { + try { + await bucket.delete(); + } catch { + //Ignore errors + } + }); + + it('should create a bucket without hierarchical namespace enabled (implicit)', async () => { + await storage.createBucket(bucket.name); + const [metadata] = await bucket.getMetadata(); + assert( + [undefined, false].includes(metadata?.hierarchicalNamespace?.enabled), + ); + }); + + it('should create a bucket without hierarchical namespace enabled (explicit)', async () => { + await storage.createBucket(bucket.name, { + hierarchicalNamespace: {enabled: false}, + }); + const [metadata] = await bucket.getMetadata(); + assert( + [undefined, false].includes(metadata?.hierarchicalNamespace?.enabled), + ); + }); + + it('should create a bucket with hierarchical namespace enabled', async () => { + await storage.createBucket(bucket.name, { + hierarchicalNamespace: {enabled: true}, + iamConfiguration: { + uniformBucketLevelAccess: { + enabled: true, + }, + }, + }); + const [metadata] = await bucket.getMetadata(); + assert(metadata.hierarchicalNamespace); + assert.strictEqual(metadata.hierarchicalNamespace.enabled, true); + }); + }); + + describe('bucket retention policies', () => { + describe('bucket', () => { + it('should create a bucket with a retention policy', async () => { + const bucket = storage.bucket(generateName()); + await storage.createBucket(bucket.name, { + retentionPolicy: { + retentionPeriod: RETENTION_DURATION_SECONDS, + }, + }); + await bucket.getMetadata(); + assert.strictEqual( + bucket.metadata!.retentionPolicy!.retentionPeriod, + `${RETENTION_DURATION_SECONDS}`, + ); + }); + + it('should set a retention policy', async () => { + const bucket = storage.bucket(generateName()); + await bucket.create(); + await bucket.setRetentionPeriod(RETENTION_DURATION_SECONDS); + await bucket.getMetadata(); + assert.strictEqual( + bucket.metadata!.retentionPolicy!.retentionPeriod, + `${RETENTION_DURATION_SECONDS}`, + ); + }); + + it('should lock the retention period', async () => { + const bucket = storage.bucket(generateName()); + await bucket.create(); + await bucket.setRetentionPeriod(RETENTION_DURATION_SECONDS); + await bucket.getMetadata(); + + await bucket.lock(bucket.metadata!.metageneration!.toString()); + await assert.rejects( + bucket.setRetentionPeriod(RETENTION_DURATION_SECONDS / 2), + (err: ApiError) => { + return err.code === 403; + }, + ); + }); + + it('should remove a retention period', async () => { + const bucket = storage.bucket(generateName()); + await bucket.create(); + await bucket.setRetentionPeriod(RETENTION_DURATION_SECONDS); + await bucket.getMetadata(); + assert.strictEqual( + bucket.metadata!.retentionPolicy!.retentionPeriod, + `${RETENTION_DURATION_SECONDS}`, + ); + + await bucket.removeRetentionPeriod(); + await bucket.getMetadata(); + assert.strictEqual(bucket.metadata.retentionPolicy, undefined); + }); + }); + + describe('file', () => { + const BUCKET = storage.bucket(generateName()); + const FILE = BUCKET.file(generateName()); + + const BUCKET_RETENTION_PERIOD = 1; + before(async () => { + await BUCKET.create({ + retentionPolicy: { + retentionPeriod: BUCKET_RETENTION_PERIOD, + }, + }); + await FILE.save('data'); + }); + + afterEach(() => { + return FILE.setMetadata({temporaryHold: null, eventBasedHold: null}); + }); + + after(done => { + setTimeout(() => FILE.delete(done), BUCKET_RETENTION_PERIOD * 1000); + }); + + it('should set and release an event-based hold', async () => { + await FILE.setMetadata({eventBasedHold: true}); + assert.strictEqual(FILE.metadata.eventBasedHold, true); + await FILE.setMetadata({eventBasedHold: false}); + assert.strictEqual(FILE.metadata.eventBasedHold, false); + }); + + it('should set and release a temporary hold', async () => { + await FILE.setMetadata({temporaryHold: true}); + assert.strictEqual(FILE.metadata.temporaryHold, true); + await FILE.setMetadata({temporaryHold: false}); + assert.strictEqual(FILE.metadata.temporaryHold, false); + }); + + it('should get an expiration date', async () => { + const [expirationDate] = await FILE.getExpirationDate(); + assert(expirationDate instanceof Date); + }); + }); + + describe('operations on held objects', () => { + const BUCKET = storage.bucket(generateName()); + const FILES: File[] = []; + + const RETENTION_PERIOD_SECONDS = 5; // Each test has this much time! + + async function createFile(): Promise { + const file = BUCKET.file(generateName()); + await file.save('data'); + FILES.push(file); + return file; + } + + before(async () => { + await BUCKET.create({ + retentionPolicy: { + retentionPeriod: RETENTION_PERIOD_SECONDS, + }, + }); + }); + + after(async () => { + await new Promise(resolve => + setTimeout(resolve, RETENTION_PERIOD_SECONDS * 1000), + ); + await Promise.all( + FILES.map(async file => { + return file.delete(); + }), + ); + }); + + it('should block an overwrite request', async () => { + const file = await createFile(); + assert.rejects(file.save('new data'), (err: ApiError) => { + assert.strictEqual(err.code, 403); + }); + }); + + it('should block a delete request', async () => { + const file = await createFile(); + assert.rejects(file.delete(), (err: ApiError) => { + assert.strictEqual(err.code, 403); + }); + }); + }); + }); + + describe('bucket logging', () => { + const PREFIX = 'sys-test'; + + it('should enable logging on current bucket by default', async () => { + const [metadata] = await bucket.enableLogging({prefix: PREFIX}); + assert.deepStrictEqual(metadata.logging, { + logBucket: bucket.id, + logObjectPrefix: PREFIX, + }); + }); + + it('should enable logging on another bucket', async () => { + const bucketForLogging = storage.bucket(generateName()); + await bucketForLogging.create(); + + const [metadata] = await bucket.enableLogging({ + bucket: bucketForLogging, + prefix: PREFIX, + }); + assert.deepStrictEqual(metadata.logging, { + logBucket: bucketForLogging.id, + logObjectPrefix: PREFIX, + }); + }); + }); + + describe('object retention lock', () => { + const fileName = generateName(); + let objectRetentionBucket: Bucket; + + before(async () => { + objectRetentionBucket = storage.bucket(generateName()); + }); + + after(async () => { + await objectRetentionBucket.deleteFiles({force: true}); + await objectRetentionBucket.delete(); + }); + + it('should create a bucket with object retention enabled', async () => { + const result = await objectRetentionBucket.create({ + enableObjectRetention: true, + }); + + assert.deepStrictEqual(result[0].metadata.objectRetention, { + mode: 'Enabled', + }); + }); + + it('should create a file with object retention enabled', async () => { + const time = new Date(); + time.setMinutes(time.getMinutes() + 1); + const retention = {mode: 'Unlocked', retainUntilTime: time.toISOString()}; + const file = new File(objectRetentionBucket, fileName); + await objectRetentionBucket.upload(FILES.big.path, { + metadata: { + retention, + }, + destination: fileName, + }); + const [metadata] = await file.getMetadata(); + assert.deepStrictEqual(metadata.retention, retention); + }); + + it('should disable object retention on the file', async () => { + const file = new File(objectRetentionBucket, fileName); + const [metadata] = await file.setMetadata( + {retention: null}, + {overrideUnlockedRetention: true}, + ); + assert.strictEqual(metadata.retention, undefined); + }); + }); + + describe('requester pays', () => { + const HAS_2ND_PROJECT = + process.env.GCN_STORAGE_2ND_PROJECT_ID !== undefined; + let bucket: Bucket; + + before(async () => { + bucket = storage.bucket(generateName()); + + await bucket.create({ + requesterPays: true, + }); + }); + + after(async () => { + await bucket.delete(); + }); + + it('should have enabled requesterPays functionality', async () => { + const [metadata] = await bucket.getMetadata(); + assert.strictEqual(metadata.billing!.requesterPays, true); + }); + + // These tests will verify that the requesterPays functionality works from + // the perspective of another project. + (HAS_2ND_PROJECT ? describe : describe.skip)('existing bucket', () => { + const storageNonAllowList = new Storage({ + projectId: process.env.GCN_STORAGE_2ND_PROJECT_ID, + keyFilename: process.env.GCN_STORAGE_2ND_PROJECT_KEY, + retryOptions: { + idempotencyStrategy: IdempotencyStrategy.RetryAlways, + retryDelayMultiplier: 3, + }, + }); + // the source bucket, which will have requesterPays enabled. + let bucket: Bucket; + // the bucket object from the requesting user. + let bucketNonAllowList: Bucket; + + async function isRequesterPaysEnabled(): Promise { + const [metadata] = await bucket.getMetadata(); + const billing = metadata.billing || {}; + return !!billing && billing.requesterPays === true; + } + + before(async () => { + bucket = storage.bucket(generateName()); + bucketNonAllowList = storageNonAllowList.bucket(bucket.name); + await bucket.create(); + }); + + it('should enable requesterPays', async () => { + let isEnabled = await isRequesterPaysEnabled(); + assert.strictEqual(isEnabled, false); + await bucket.enableRequesterPays(); + isEnabled = await isRequesterPaysEnabled(); + assert.strictEqual(isEnabled, true); + }); + + it('should disable requesterPays', async () => { + await bucket.enableRequesterPays(); + let isEnabled = await isRequesterPaysEnabled(); + assert.strictEqual(isEnabled, true); + await bucket.disableRequesterPays(); + isEnabled = await isRequesterPaysEnabled(); + assert.strictEqual(isEnabled, false); + }); + + describe('methods that accept userProject', () => { + let file: File; + let notification: Notification; + let topicName: string; + + const USER_PROJECT_OPTIONS = { + userProject: process.env.GCN_STORAGE_2ND_PROJECT_ID, + }; + + // This acts as a test for the following methods: + // + // - file.save() + // -> file.createWriteStream() + before(async () => { + file = bucketNonAllowList.file(generateName()); + + await bucket.enableRequesterPays(); + const data = await bucket.iam.getPolicy(); + const policy = data[0]; + // Allow an absolute or relative path (from project root) + // for the key file. + let key2 = process.env.GCN_STORAGE_2ND_PROJECT_KEY; + if (key2 && key2.charAt(0) === '.') { + key2 = `${getDirName()}/../../../${key2}`; + } + // Get the service account for the "second" account (the + // one that will read the requester pays file). + const clientEmail = JSON.parse( + fs.readFileSync(key2!, 'utf-8'), + ).client_email; + policy.bindings.push({ + role: 'roles/storage.admin', + members: [`serviceAccount:${clientEmail}`], + }); + await bucket.iam.setPolicy(policy); + await file.save('abc', USER_PROJECT_OPTIONS); + const data_2 = await topic.getMetadata(); + topicName = data_2[0].name!; + }); + + // This acts as a test for the following methods: + // + // - bucket.delete({ userProject: ... }) + // -> bucket.deleteFiles({ userProject: ... }) + // -> bucket.getFiles({ userProject: ... }) + // -> file.delete({ userProject: ... }) + after(done => { + deleteBucket(bucketNonAllowList, USER_PROJECT_OPTIONS, done); + }); + + beforeEach(() => { + bucketNonAllowList = storageNonAllowList.bucket(bucket.name); + file = bucketNonAllowList.file(file.name); + }); + + /** + * A type for requester pays functions. The `options` parameter + * + * Using `typeof USER_PROJECT_OPTIONS` ensures the function should + * support requester pays options, otherwise will fail early at build- + * time rather than runtime. + */ + type requesterPaysFunction< + T = {} | typeof USER_PROJECT_OPTIONS, + R = {} | void, + > = (options?: T) => Promise; + + /** + * Accepts a function and runs 2 tests - a test where the requester pays + * option is absent and another where it is present: + * - The missing requester pays test will assert the expected error + * - The added request pays test will return the function's result + * + * @param testFunction The function/method to test. + * @returns The result of the successful request pays operation. + */ + async function requesterPaysDoubleTest( + testFunction: F, + ): Promise> { + const failureMessage = + 'Bucket is a requester pays bucket but no user project provided.'; + + await assert.rejects(testFunction(), err => { + assert( + (err as Error).message.includes(failureMessage), + `Expected '${ + (err as Error).message + }' to include '${failureMessage}'`, + ); + return true; + }); + + // Validate the desired functionality + const results = await testFunction(USER_PROJECT_OPTIONS); + return results as ReturnType; + } + + it('bucket#combine', async () => { + const files = [ + {file: bucketNonAllowList.file('file-one.txt'), contents: '123'}, + {file: bucketNonAllowList.file('file-two.txt'), contents: '456'}, + ]; + + await Promise.all(files.map(file => createFileAsync(file))); + + const sourceFiles = files.map(x => x.file); + const destinationFile = bucketNonAllowList.file('file-one-n-two.txt'); + await bucketNonAllowList.combine( + sourceFiles, + destinationFile, + USER_PROJECT_OPTIONS, + ); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function createFileAsync(fileObject: any) { + return fileObject.file.save( + fileObject.contents, + USER_PROJECT_OPTIONS, + ); + } + }); + + it('bucket#createNotification', async () => { + const [notif] = await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.createNotification(topicName, options); + }); + + notification = notif; + }); + + it('bucket#exists', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.exists(options); + }); + }); + + it('bucket#get', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.get(options); + }); + }); + + it('bucket#getMetadata', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.getMetadata(options); + }); + }); + + it('bucket#getNotifications', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.getNotifications(options); + }); + }); + + it('bucket#makePrivate', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.makePrivate(options); + }); + }); + + it('bucket#setMetadata', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.setMetadata({newMetadata: true}, options); + }); + }); + + it('bucket#setStorageClass', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.setStorageClass( + 'multi-regional', + options, + ); + }); + }); + + it('bucket#upload', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.upload(FILES.big.path, options); + }); + }); + + it('file#copy', async () => { + await requesterPaysDoubleTest(async options => { + return file.copy('new-file.txt', options); + }); + }); + + it('file#createReadStream', async () => { + await requesterPaysDoubleTest(async options => { + await new Promise((resolve, reject) => { + return file + .createReadStream(options) + .on('error', reject) + .on('end', resolve) + .on('data', () => {}); + }); + }); + }); + + it('file#createResumableUpload', async () => { + await requesterPaysDoubleTest(async options => { + const [uri] = await file.createResumableUpload(options); + + await new Promise((resolve, reject) => { + return file + .createWriteStream({uri}) + .on('error', reject) + .on('finish', resolve) + .end('Test data'); + }); + }); + }); + + it('file#download', async () => { + await requesterPaysDoubleTest(async options => { + return file.download(options); + }); + }); + + it('file#exists', async () => { + await requesterPaysDoubleTest(async options => { + return file.exists(options); + }); + }); + + it('file#get', async () => { + await requesterPaysDoubleTest(async options => { + return file.get(options); + }); + }); + + it('file#getMetadata', async () => { + await requesterPaysDoubleTest(async options => { + return file.getMetadata(options); + }); + }); + + it('file#makePrivate', async () => { + await requesterPaysDoubleTest(async options => { + return file.makePrivate(options); + }); + }); + + it('file#move', async () => { + await requesterPaysDoubleTest(async options => { + const newFile = bucketNonAllowList.file(generateName()); + + await file.move(newFile, options); + + // Re-create the file. The tests need it. + await file.save('newcontent', options); + }); + }); + + it('file#rename', async () => { + await requesterPaysDoubleTest(async options => { + const newFile = bucketNonAllowList.file(generateName()); + + await file.rename(newFile, options); + + // Re-create the file. The tests need it. + await file.save('newcontent', options); + }); + }); + + it('file#setMetadata', async () => { + await requesterPaysDoubleTest(async options => { + return file.setMetadata({newMetadata: true}, options); + }); + }); + + it('file#setStorageClass', async () => { + await requesterPaysDoubleTest(async options => { + return file.setStorageClass('multi-regional', options); + }); + }); + + it('acl#add', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.acl.add({ + entity: USER_ACCOUNT, + role: storage.acl.OWNER_ROLE, + ...options, + }); + }); + }); + + it('acl#update', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.acl.update({ + entity: USER_ACCOUNT, + role: storage.acl.WRITER_ROLE, + ...options, + }); + }); + }); + + it('acl#get', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.acl.get({ + entity: USER_ACCOUNT, + ...options, + }); + }); + }); + + it('acl#delete', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.acl.delete({ + entity: USER_ACCOUNT, + ...options, + }); + }); + }); + + it('iam#getPolicy', async () => { + await requesterPaysDoubleTest(async options => { + return bucketNonAllowList.iam.getPolicy(options); + }); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('iam#setPolicy', async () => { + await requesterPaysDoubleTest(async options => { + const [policy] = await bucket.iam.getPolicy(); + + policy.bindings.push({ + role: 'roles/storage.objectViewer', + members: ['allUsers'], + }); + + return bucketNonAllowList.iam.setPolicy(policy, options); + }); + }); + + it('iam#testPermissions', async () => { + await requesterPaysDoubleTest(async options => { + const tests = ['storage.buckets.delete']; + + return bucketNonAllowList.iam.testPermissions(tests, options); + }); + }); + + it('notification#get', async () => { + await requesterPaysDoubleTest(async options => { + return notification.get(options); + }); + }); + + it('notification#getMetadata', async () => { + await requesterPaysDoubleTest(async options => { + return notification.getMetadata(options); + }); + }); + + it('notification#delete', async () => { + await requesterPaysDoubleTest(async options => { + return notification.delete(options); + }); + }); + }); + }); + }); + + describe('write, read, and remove files', () => { + const FILE_DOWNLOAD_START_BYTE = 0; + const FILE_DOWNLOAD_END_BYTE = 20; + + before(async () => { + function setHash(filesKey: string) { + const file = FILES[filesKey]; + const hash = crypto.createHash('md5'); + + return new Promise(resolve => + fs + .createReadStream(file.path) + .on('data', hash.update.bind(hash)) + .on('end', () => { + file.hash = hash.digest('base64'); + resolve(); + }), + ); + } + await Promise.all(Object.keys(FILES).map(key => setHash(key))); + }); + + it('should read/write from/to a file in a directory', done => { + const file = bucket.file('directory/file'); + const contents = 'test'; + + const writeStream = file.createWriteStream({resumable: false}); + writeStream.write(contents); + writeStream.end(); + + writeStream.on('error', done); + writeStream.on('finish', () => { + let data = Buffer.from('', 'utf8'); + + file + .createReadStream() + .on('error', done) + .on('data', (chunk: Buffer) => { + data = Buffer.concat([data, chunk]); + }) + .on('end', () => { + assert.strictEqual(data.toString(), contents); + done(); + }); + }); + }); + + it('should not push data when a file cannot be read', done => { + const file = bucket.file('non-existing-file'); + let dataEmitted = false; + + file + .createReadStream() + .on('data', () => { + dataEmitted = true; + }) + .on('error', err => { + assert.strictEqual(dataEmitted, false); + assert.strictEqual((err as ApiError).code, 404); + done(); + }); + }); + + it('should throw original error message on non JSON response on large metadata', async () => { + const largeCustomMeta = (size: number) => { + let str = ''; + for (let i = 0; i < size; i++) { + str += 'a'; + } + return str; + }; + + const file = bucket.file('large-metadata-error-test'); + await assert.rejects( + file.save('test', { + resumable: false, + metadata: { + metadata: { + custom: largeCustomMeta(2.1e6), + }, + }, + }), + /Metadata part is too large/, + ); + }); + + it('should read a byte range from a file', done => { + bucket.upload(FILES.big.path, (err: Error | null, file?: File | null) => { + assert.ifError(err); + + const fileSize = parseInt(file!.metadata.size!.toString()); + const byteRange = { + start: Math.floor((fileSize * 1) / 3), + end: Math.floor((fileSize * 2) / 3), + }; + const expectedContentSize = byteRange.start + 1; + + let sizeStreamed = 0; + file! + .createReadStream(byteRange) + .on('data', chunk => { + sizeStreamed += chunk.length; + }) + .on('error', done) + .on('end', () => { + assert.strictEqual(sizeStreamed, expectedContentSize); + file!.delete(done); + }); + }); + }); + + it('should support readable[Symbol.asyncIterator]()', async () => { + const fileContents = fs.readFileSync(FILES.big.path); + + const [file] = await bucket.upload(FILES.big.path); + const stream = file.createReadStream(); + const chunks: Buffer[] = []; + for await (const chunk of stream) { + chunks.push(chunk); + } + const remoteContents = Buffer.concat(chunks).toString(); + assert.strictEqual(String(fileContents), String(remoteContents)); + }); + + it('should download a file to memory', async () => { + const fileContents = fs.readFileSync(FILES.big.path); + const [file] = await bucket.upload(FILES.big.path); + const [remoteContents] = await file.download(); + assert.strictEqual(String(fileContents), String(remoteContents)); + }); + + it('should download an entire file if range `start:0` is provided', async () => { + const fileContents = fs.readFileSync(FILES.big.path); + const [file] = await bucket.upload(FILES.big.path); + const [result] = await file.download({start: 0}); + + assert.strictEqual(result.toString(), fileContents.toString()); + }); + + it('should download an empty file', async () => { + const fileContents = fs.readFileSync(FILES.empty.path); + const [file] = await bucket.upload(FILES.empty.path); + const [remoteContents] = await file.download(); + assert.strictEqual(String(fileContents), String(remoteContents)); + }); + + it('should download the specified bytes of a file', async () => { + const fileContents = fs.readFileSync(FILES.big.path); + const [file] = await bucket.upload(FILES.big.path); + const [remoteContents] = await file!.download({ + start: FILE_DOWNLOAD_START_BYTE, + end: FILE_DOWNLOAD_END_BYTE, + }); + assert.strictEqual( + String(fileContents).slice(0, 20), + String(remoteContents), + ); + }); + + it('should handle non-network errors', async () => { + const file = bucket.file('hi.jpg'); + assert.rejects(file.download(), (err: ApiError) => { + assert.strictEqual((err as ApiError).code, 404); + }); + }); + + it('should gzip a file on the fly and download it', async () => { + const options = { + gzip: true, + }; + const expectedContents = fs.readFileSync(FILES.html.path, 'utf-8'); + const [file] = await bucket.upload(FILES.html.path, options); + const [contents] = await file.download(); + assert.strictEqual(contents.toString(), expectedContents); + await file.delete(); + }); + + it('should upload a gzipped file and download it', async () => { + const options = { + metadata: { + contentEncoding: 'gzip', + contentType: 'text/html', + }, + }; + + const expectedContents = fs.readFileSync(FILES.html.path, 'utf-8'); + + // Prepare temporary gzip file for upload + tmp.setGracefulCleanup(); + const {name: tmpGzFilePath} = tmp.fileSync({postfix: '.gz'}); + fs.writeFileSync(tmpGzFilePath, gzipSync(expectedContents)); + + const file: File = await new Promise((resolve, reject) => { + bucket.upload(tmpGzFilePath, options, (err, file) => { + if (err || !file) return reject(err); + resolve(file); + }); + }); + + const contents: Buffer = await new Promise((resolve, reject) => { + return file.download((error, content) => { + if (error) return reject(error); + resolve(content); + }); + }); + + assert.strictEqual(contents.toString(), expectedContents); + await file.delete(); + }); + + it('should skip validation if file is served decompressed', async () => { + const filename = 'logo-gzipped.png'; + await bucket.upload(FILES.logo.path, {destination: filename, gzip: true}); + + tmp.setGracefulCleanup(); + const {name: tmpFilePath} = tmp.fileSync(); + + const file = bucket.file(filename); + + await new Promise((resolve, reject) => { + file + .createReadStream() + .on('error', reject) + .on('response', raw => { + assert.strictEqual( + raw.toJSON().headers['content-encoding'], + undefined, + ); + }) + .pipe(fs.createWriteStream(tmpFilePath)) + .on('error', reject) + .on('finish', () => resolve()); + }); + + await file.delete(); + }); + + describe('simple write', () => { + it('should save arbitrary data', async () => { + const file = bucket.file('TestFile'); + const data = 'hello'; + await file!.save(data); + const [contents] = await file!.download(); + assert.strictEqual(contents.toString(), data); + }); + }); + + describe('stream write', () => { + it('should stream write, then remove file (3mb)', done => { + const file = bucket.file('LargeFile'); + fs.createReadStream(FILES.big.path) + .pipe(file!.createWriteStream({resumable: false})) + .on('error', done) + .on('finish', () => { + assert.strictEqual(file.metadata.md5Hash, FILES.big.hash); + file.delete(done); + }); + }); + + it('should write metadata', async () => { + const options = { + metadata: {contentType: 'image/png'}, + resumable: false, + }; + const [file] = await bucket.upload(FILES.logo.path, options); + const [metadata] = await file.getMetadata(); + assert.strictEqual(metadata.contentType, options.metadata.contentType); + await file.delete(); + }); + + it('should resume an upload after an interruption', done => { + fs.stat(FILES.big.path, (err, metadata) => { + assert.ifError(err); + + const file = bucket.file(generateName()); + const fileSize = metadata.size; + upload({interrupt: true}, err => { + assert.strictEqual(err!.message, 'Interrupted.'); + upload({interrupt: false}, err => { + assert.ifError(err); + assert.strictEqual(Number(file.metadata.size), fileSize); + file.delete(done); + }); + }); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function upload(opts: any, callback: ErrorCallbackFunction) { + const ws = file.createWriteStream(); + let sizeStreamed = 0; + + const streamTransform = new Transform({ + transform(chunk, enc, next) { + sizeStreamed += chunk.length; + + if (opts.interrupt && sizeStreamed >= fileSize / 2) { + // stop sending data half way through. + this.push(chunk); + this.destroy(); + process.nextTick(() => { + ws.destroy(new Error('Interrupted.')); + }); + } else { + this.push(chunk); + next(); + } + }, + }); + fs.createReadStream(FILES.big.path) + .pipe(streamTransform) + .pipe(ws) + .on('error', callback) + .on('finish', callback); + } + }); + }); + + it('should write/read/remove from a buffer', done => { + tmp.setGracefulCleanup(); + tmp.file((err, tmpFilePath) => { + assert.ifError(err); + + const file = bucket.file('MyBuffer'); + const fileContent = 'Hello World'; + + const writable = file.createWriteStream(); + + writable.write(fileContent); + writable.end(); + + writable.on('finish', () => { + file + .createReadStream() + .on('error', done) + .pipe(fs.createWriteStream(tmpFilePath)) + .on('error', done) + .on('finish', () => { + file.delete((err: ApiError | null) => { + assert.ifError(err); + + fs.readFile(tmpFilePath, (err, data) => { + assert.strictEqual(data.toString(), fileContent); + done(); + }); + }); + }); + }); + }); + }); + }); + + describe('customer-supplied encryption keys', () => { + const encryptionKey = crypto.randomBytes(32); + + const file = bucket.file('encrypted-file', { + encryptionKey, + }); + const unencryptedFile = bucket.file(file.name); + + before(async () => { + await file.save('secret data', {resumable: false}); + }); + + it('should not get the hashes from the unencrypted file', async () => { + const [metadata] = await unencryptedFile.getMetadata(); + assert.strictEqual(metadata.crc32c, undefined); + }); + + it('should get the hashes from the encrypted file', async () => { + const [metadata] = await file.getMetadata(); + assert.notStrictEqual(metadata.crc32c, undefined); + }); + + it('should not download from the unencrypted file', async () => { + assert.rejects(unencryptedFile.download(), (err: ApiError) => { + assert( + err!.message.indexOf( + [ + 'The target object is encrypted by a', + 'customer-supplied encryption key.', + ].join(' '), + ) > -1, + ); + }); + }); + + it('should download from the encrypted file', async () => { + const [contents] = await file.download(); + assert.strictEqual(contents.toString(), 'secret data'); + }); + + it('should rotate encryption keys', async () => { + const newEncryptionKey = crypto.randomBytes(32); + await file.rotateEncryptionKey(newEncryptionKey); + const [contents] = await file.download(); + assert.strictEqual(contents.toString(), 'secret data'); + }); + }); + + describe('kms keys', () => { + const FILE_CONTENTS = 'secret data'; + + const BUCKET_LOCATION = 'us'; + let PROJECT_ID: string; + let SERVICE_ACCOUNT_EMAIL: string; + + const keyRingId = generateName(); + const cryptoKeyId = generateName(); + + const request = promisify(storage.request).bind(storage); + + let bucket: Bucket; + let kmsKeyName: string; + let keyRingsBaseUrl: string; + + function setProjectId(projectId: string) { + PROJECT_ID = projectId; + keyRingsBaseUrl = `https://cloudkms.googleapis.com/v1/projects/${PROJECT_ID}/locations/${BUCKET_LOCATION}/keyRings`; + kmsKeyName = generateKmsKeyName(cryptoKeyId); + } + + function generateKmsKeyName(cryptoKeyId: string) { + return `projects/${PROJECT_ID}/locations/${BUCKET_LOCATION}/keyRings/${keyRingId}/cryptoKeys/${cryptoKeyId}`; + } + + async function createCryptoKeyAsync(cryptoKeyId: string) { + // createCryptoKeyId + await request({ + method: 'POST', + uri: `${keyRingsBaseUrl}/${keyRingId}/cryptoKeys`, + qs: {cryptoKeyId}, + json: {purpose: 'ENCRYPT_DECRYPT'}, + }); + + // getServiceAccountEmail + if (!SERVICE_ACCOUNT_EMAIL) { + const [serviceAccount] = await storage.getServiceAccount(); + SERVICE_ACCOUNT_EMAIL = serviceAccount!.emailAddress!; + } + + await request({ + method: 'POST', + uri: `${keyRingsBaseUrl}/${keyRingId}/cryptoKeys/${cryptoKeyId}:setIamPolicy`, + json: { + policy: { + bindings: [ + { + role: 'roles/cloudkms.cryptoKeyEncrypterDecrypter', + members: `serviceAccount:${SERVICE_ACCOUNT_EMAIL}`, + }, + ], + }, + }, + }); + } + + before(async () => { + bucket = storage.bucket(generateName()); + + setProjectId(await storage.authClient.getProjectId()); + await bucket.create({location: BUCKET_LOCATION}); + + // create keyRing + await request({ + method: 'POST', + uri: keyRingsBaseUrl, + qs: {keyRingId}, + }); + + await createCryptoKeyAsync(cryptoKeyId); + }); + + describe('files', () => { + let file: File; + + before(async () => { + file = bucket.file('kms-encrypted-file', {kmsKeyName}); + await file.save(FILE_CONTENTS, {resumable: false}); + }); + + it('should have set kmsKeyName on created file', async () => { + const [metadata] = await file.getMetadata(); + + // Strip the project ID, as it could be the placeholder locally, but + // the real value upstream. + const projectIdRegExp = /^.+\/locations/; + const actualKmsKeyName = metadata!.kmsKeyName!.replace( + projectIdRegExp, + '', + ); + let expectedKmsKeyName = kmsKeyName.replace(projectIdRegExp, ''); + + // Upstream attaches a version. + expectedKmsKeyName = `${expectedKmsKeyName}/cryptoKeyVersions/1`; + + assert.strictEqual(actualKmsKeyName, expectedKmsKeyName); + }); + + it('should set kmsKeyName on resumable uploaded file', async () => { + const file = bucket.file('resumable-file', {kmsKeyName}); + await file.save(FILE_CONTENTS, {resumable: true}); + const [metadata] = await file.getMetadata(); + + // Strip the project ID, as it could be the placeholder locally, + // but the real value upstream. + const projectIdRegExp = /^.+\/locations/; + const actualKmsKeyName = metadata!.kmsKeyName!.replace( + projectIdRegExp, + '', + ); + let expectedKmsKeyName = kmsKeyName.replace(projectIdRegExp, ''); + + // Upstream attaches a version. + expectedKmsKeyName = `${expectedKmsKeyName}/cryptoKeyVersions/1`; + + assert.strictEqual(actualKmsKeyName, expectedKmsKeyName); + }); + + it('should rotate encryption keys', async () => { + const cryptoKeyId = generateName(); + const newKmsKeyName = generateKmsKeyName(cryptoKeyId); + + await createCryptoKeyAsync(cryptoKeyId); + await file.rotateEncryptionKey({kmsKeyName: newKmsKeyName}); + const [contents] = await file.download(); + assert.strictEqual(contents.toString(), FILE_CONTENTS); + }); + + it('should convert CSEK to KMS key', async () => { + const encryptionKey = crypto.randomBytes(32); + const file = bucket.file('encrypted-file', {encryptionKey}); + await file.save(FILE_CONTENTS, {resumable: false}); + await file.rotateEncryptionKey({kmsKeyName}); + const [contents] = await file.download(); + assert.strictEqual(contents.toString(), 'secret data'); + }); + }); + + describe('buckets', () => { + let bucket: Bucket; + + before(async () => { + bucket = storage.bucket(generateName(), {kmsKeyName}); + await bucket.create(); + }); + + beforeEach(async () => { + await new Promise(res => + setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME), + ); + await bucket.setMetadata({ + encryption: { + defaultKmsKeyName: kmsKeyName, + }, + }); + }); + + afterEach(async () => { + await new Promise(res => + setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME), + ); + await bucket.setMetadata({ + encryption: null, + }); + }); + + it('should have set defaultKmsKeyName on created bucket', async () => { + const [metadata] = await bucket.getMetadata(); + // Strip the project ID, as it could be the placeholder locally, but + // the real value upstream. + const projectIdRegExp = /^.+\/locations/; + const actualKmsKeyName = + metadata!.encryption!.defaultKmsKeyName!.replace( + projectIdRegExp, + '', + ); + const expectedKmsKeyName = kmsKeyName.replace(projectIdRegExp, ''); + assert.strictEqual(actualKmsKeyName, expectedKmsKeyName); + }); + + it('should update the defaultKmsKeyName', async () => { + const cryptoKeyId = generateName(); + const newKmsKeyName = generateKmsKeyName(cryptoKeyId); + + await createCryptoKeyAsync(cryptoKeyId); + await new Promise(res => + setTimeout(res, BUCKET_METADATA_UPDATE_WAIT_TIME), + ); + await bucket.setMetadata({ + encryption: { + defaultKmsKeyName: newKmsKeyName, + }, + }); + }); + + it('should insert an object that inherits the kms key name', async () => { + const file = bucket.file('kms-encrypted-file'); + const [metadata] = await bucket.getMetadata(); + await file.save(FILE_CONTENTS, {resumable: false}); + const [fileMetadata] = await file.getMetadata(); + + assert.strictEqual( + fileMetadata.kmsKeyName, + `${metadata!.encryption!.defaultKmsKeyName}/cryptoKeyVersions/1`, + ); + }); + }); + }); + + it('should copy an existing file', async () => { + const opts = {destination: 'CloudLogo'}; + const [file] = await bucket.upload(FILES.logo.path, opts); + const [copiedFile] = await file.copy('CloudLogoCopy'); + await Promise.all([file.delete, copiedFile.delete()]); + }); + + it('should copy an existing file and overwrite custom metadata', async () => { + const opts = { + destination: 'CloudLogo', + metadata: { + metadata: { + originalProperty: 'true', + }, + }, + }; + const [file] = await bucket.upload(FILES.logo.path, opts); + const copyOpts = {metadata: {newProperty: 'true'}}; + const [copiedFile] = await file.copy('CloudLogoCopy', copyOpts); + const [metadata] = await copiedFile.getMetadata(); + assert.strictEqual( + typeof metadata!.metadata!.originalProperty, + 'undefined', + ); + assert.strictEqual(metadata!.metadata!.newProperty, 'true'); + await Promise.all([file.delete, copiedFile.delete()]); + }); + + it('should copy an existing file and overwrite metadata', async () => { + const opts = { + destination: 'CloudLogo', + }; + const CACHE_CONTROL = 'private'; + const CONTENT_ENCODING = 'gzip'; + const CONTENT_TYPE = 'text/plain'; + const [file] = await bucket.upload(FILES.logo.path, opts); + const copyOpts = { + cacheControl: CACHE_CONTROL, + contentEncoding: CONTENT_ENCODING, + contentType: CONTENT_TYPE, + }; + const [copiedFile] = await file.copy('CloudLogoCopy', copyOpts); + const [metadata] = await copiedFile.getMetadata(); + assert.strictEqual(metadata.contentEncoding, CONTENT_ENCODING); + assert.strictEqual(metadata.cacheControl, CACHE_CONTROL); + assert.strictEqual(metadata.contentType, CONTENT_TYPE); + await Promise.all([file.delete, copiedFile.delete()]); + }); + + /** + * TODO: Re-enable once the test environment allows public IAM roles. + * Currently disabled to avoid 403 errors when adding 'allUsers' or + * 'allAuthenticatedUsers' permissions. + */ + it.skip('should respect predefined Acl at file#copy', async () => { + const opts = {destination: 'CloudLogo'}; + const [file] = await bucket.upload(FILES.logo.path, opts); + const copyOpts = {predefinedAcl: 'publicRead'}; + const [copiedFile] = await file.copy('CloudLogoCopy', copyOpts); + const publicAcl = await isFilePublicAsync(copiedFile); + assert.strictEqual(publicAcl, true); + await Promise.all([file.delete, copiedFile.delete()]); + }); + + it('should copy a large file', async () => { + const otherBucket = storage.bucket(generateName()); + const file = bucket.file('Big'); + const copiedFile = otherBucket.file(file.name); + await bucket.upload(FILES.logo.path, {destination: file}); + await otherBucket.create({ + location: 'ASIA-EAST1', + dra: true, + }); + await file.copy(copiedFile); + await copiedFile.delete(); + await otherBucket.delete(); + await file.delete(); + }); + + it('should copy to another bucket given a gs:// URL', async () => { + const opts = {destination: 'CloudLogo'}; + const [file] = await bucket.upload(FILES.logo.path, opts); + const otherBucket = storage.bucket(generateName()); + await otherBucket.create(); + const destPath = 'gs://' + otherBucket.name + '/CloudLogoCopy'; + await file!.copy(destPath); + const [files] = await otherBucket.getFiles(); + assert.strictEqual(files!.length, 1); + const newFile = files![0]; + assert.strictEqual(newFile.name, 'CloudLogoCopy'); + }); + + it('should allow changing the storage class', async () => { + const file = bucket.file(generateName()); + await bucket.upload(FILES.logo.path, {destination: file}); + await file.setStorageClass('standard'); + const [metadata] = await file.getMetadata(); + assert.strictEqual(metadata.storageClass, 'STANDARD'); + }); + }); + + describe('resumable upload', () => { + describe('multi-chunk upload', () => { + describe('upload configurations', () => { + const filePath: string = FILES.big.path; + const fileSize = fs.statSync(filePath).size; + let crc32c: string; + + before(async () => { + // get a CRC32C value from the file + crc32c = (await CRC32C.fromFile(filePath)).toString(); + }); + + async function uploadAndVerify( + file: File, + options: Omit, + ) { + await bucket.upload(filePath, { + destination: file, + ...options, + }); + + const [metadata] = await file.getMetadata(); + + // assert we uploaded the expected data + assert.equal(metadata.crc32c, crc32c); + } + + it('should support uploads where `contentLength < chunkSize`', async () => { + const file = bucket.file(generateName()); + + const metadata = {contentLength: fileSize}; + // off by +1 to ensure `contentLength < chunkSize` + const chunkSize = fileSize + 1; + + await uploadAndVerify(file, {chunkSize, metadata}); + }); + + it('should support uploads where `contentLength % chunkSize != 0`', async () => { + const file = bucket.file(generateName()); + + const metadata = {contentLength: fileSize}; + // off by -1 to ensure `contentLength % chunkSize != 0` + const chunkSize = fileSize - 1; + + await uploadAndVerify(file, {chunkSize, metadata}); + }); + + it('should support uploads where `fileSize % chunkSize != 0` && `!contentLength`', async () => { + const file = bucket.file(generateName()); + // off by +1 to ensure `fileSize % chunkSize != 0` + const chunkSize = fileSize + 1; + + await uploadAndVerify(file, {chunkSize}); + }); + + it('should support uploads where `fileSize < chunkSize && `!contentLength`', async () => { + const file = bucket.file(generateName()); + // off by `* 2 +1` to ensure `fileSize < chunkSize` + const chunkSize = fileSize * 2 + 1; + + await uploadAndVerify(file, {chunkSize}); + }); + + it('should support uploads where `fileSize > chunkSize` && `!contentLength`', async () => { + const file = bucket.file(generateName()); + // off by -1 to ensure `fileSize > chunkSize` + const chunkSize = fileSize - 1; + + await uploadAndVerify(file, {chunkSize}); + }); + }); + }); + }); + + describe('bucket upload with progress', () => { + it('show bytes sent with resumable upload', async () => { + const fileSize = fs.statSync(FILES.big.path).size; + let called = false; + function onUploadProgress(evt: {bytesWritten: number}) { + called = true; + assert.strictEqual(typeof evt.bytesWritten, 'number'); + assert.ok(evt.bytesWritten >= 0 && evt.bytesWritten <= fileSize); + } + + await bucket.upload(FILES.big.path, { + resumable: true, + onUploadProgress, + }); + + assert.strictEqual(called, true); + }); + + it('show bytes sent with simple upload', async () => { + const fileSize = fs.statSync(FILES.big.path).size; + let called = false; + function onUploadProgress(evt: {bytesWritten: number}) { + called = true; + assert.strictEqual(typeof evt.bytesWritten, 'number'); + assert.ok(evt.bytesWritten >= 0 && evt.bytesWritten <= fileSize); + } + await bucket.upload(FILES.big.path, { + resumable: false, + onUploadProgress, + }); + + assert.strictEqual(called, true); + }); + }); + + describe('channels', () => { + it('should stop a channel', async () => { + // We can't actually create a channel. But we can test to see that we're + // reaching the right endpoint with the API request. + const channel = storage.channel('id', 'resource-id'); + assert.rejects(channel.stop(), (err: ApiError) => { + assert.strictEqual((err as ApiError).code, 404); + assert.strictEqual(err!.message.indexOf("Channel 'id' not found"), 0); + }); + }); + }); + + describe('file#moveFileAtomic', async () => { + it('Should move a file to a new name within the bucket.', async () => { + // Create a source file in the bucket and save some content. + const f1 = bucket.file('move-src-obj'); + await f1.save('move-src-obj'); + assert(f1); + const [f1_metadata] = await f1.getMetadata(); + + // Move the source file to a new destination name within the same bucket. + await f1.moveFileAtomic('move-dst-obj'); + const f2 = bucket.file('move-dst-obj'); + assert(f2); + const [f2_metadata] = await f2.getMetadata(); + + // Assert that the generation of the destination file is different from the source file, + // indicating a new file was created. + assert.notStrictEqual(f1_metadata.generation, f2_metadata.generation); + + const [f1_exists] = await f1.exists(); + const [f2_exists] = await f2.exists(); + // Assert that the source file no longer exists after the move. + assert.strictEqual(f1_exists, false); + // Assert that the destination file exists after the move. + assert.strictEqual(f2_exists, true); + }); + }); + + describe('combine files', () => { + it('should combine multiple files into one', async () => { + const files = [ + {file: bucket.file('file-one.txt'), contents: '123'}, + {file: bucket.file('file-two.txt'), contents: '456'}, + ]; + + await Promise.all(files.map(file => createFileAsync(file))); + + const sourceFiles = files.map(x => x.file); + let destinationFile = bucket.file('file-one-and-two.txt'); + + [destinationFile] = await bucket.combine(sourceFiles, destinationFile); + const [contents] = await destinationFile.download(); + assert.strictEqual( + contents.toString(), + files.map(x => x.contents).join(''), + ); + + await Promise.all( + sourceFiles + .concat([destinationFile]) + .map(file => deleteFileAsync(file)), + ); + }); + }); + + // TODO: Undo this skip once https://github.com/googleapis/nodejs-storage/issues/2461 is complete. + describe.skip('HMAC keys', () => { + // This is generally a valid service account for a project. + const ALTERNATE_SERVICE_ACCOUNT = `${process.env.PROJECT_ID}@appspot.gserviceaccount.com`; + const SERVICE_ACCOUNT = + process.env.HMAC_KEY_TEST_SERVICE_ACCOUNT || ALTERNATE_SERVICE_ACCOUNT; + const HMAC_PROJECT = process.env.HMAC_KEY_TEST_SERVICE_ACCOUNT + ? process.env.HMAC_PROJECT + : process.env.PROJECT_ID; + // Second service account to test listing HMAC keys from different accounts. + const SECOND_SERVICE_ACCOUNT = + process.env.HMAC_KEY_TEST_SECOND_SERVICE_ACCOUNT; + + let accessId: string; + + const delay = async (test: Mocha.Context, accessId: string) => { + const retries = test.currentRetry(); + // see: https://cloud.google.com/storage/docs/exponential-backoff: + const ms = Math.pow(2, retries) * 1000 + Math.random() * 1000; + return new Promise(done => { + console.info( + `retrying "${test.title}" with accessId ${accessId} in ${ms}ms`, + ); + setTimeout(done, ms); + }); + }; + + before(async () => { + await deleteStaleHmacKeys(SERVICE_ACCOUNT, HMAC_PROJECT!); + if (SECOND_SERVICE_ACCOUNT) { + await deleteStaleHmacKeys(SECOND_SERVICE_ACCOUNT, HMAC_PROJECT!); + } + }); + + it('should create an HMAC key for a service account', async () => { + const [hmacKey, secret] = await storage.createHmacKey(SERVICE_ACCOUNT, { + projectId: HMAC_PROJECT, + }); + // We should always get a 40 character secret, which is valid base64. + assert.strictEqual(secret.length, 40); + accessId = hmacKey.id!; + const metadata = hmacKey.metadata!; + assert.strictEqual(metadata.accessId, accessId); + assert.strictEqual(metadata.state, 'ACTIVE'); + assert.strictEqual(metadata.projectId, HMAC_PROJECT); + assert.strictEqual(metadata.serviceAccountEmail, SERVICE_ACCOUNT); + assert(typeof metadata.etag === 'string'); + assert(typeof metadata.timeCreated === 'string'); + assert(typeof metadata.updated === 'string'); + }); + + it('should get metadata for an HMAC key', async function () { + delay(this, accessId); + const hmacKey = storage.hmacKey(accessId, {projectId: HMAC_PROJECT}); + const [metadata] = await hmacKey.getMetadata(); + assert.strictEqual(metadata.accessId, accessId); + }); + + it('should show up from getHmacKeys() without serviceAccountEmail param', async () => { + const [hmacKeys] = await storage.getHmacKeys({projectId: HMAC_PROJECT}); + assert(hmacKeys.length > 0); + assert( + hmacKeys.some(hmacKey => hmacKey.id === accessId), + 'created HMAC key not found from getHmacKeys result', + ); + }); + + it('should make the key INACTIVE', async () => { + const hmacKey = storage.hmacKey(accessId, {projectId: HMAC_PROJECT}); + let [metadata] = await hmacKey.setMetadata({state: 'INACTIVE'}); + assert.strictEqual(metadata.state, 'INACTIVE'); + + [metadata] = await hmacKey.getMetadata(); + assert.strictEqual(metadata.state, 'INACTIVE'); + }); + + it('should delete the key', async () => { + const hmacKey = storage.hmacKey(accessId, {projectId: HMAC_PROJECT}); + await hmacKey.delete(); + const [metadata] = await hmacKey.getMetadata(); + assert.strictEqual(metadata.state, 'DELETED'); + assert.strictEqual(hmacKey.metadata!.state, 'DELETED'); + }); + + it('deleted key should not show up from getHmacKeys() by default', async () => { + const [hmacKeys] = await storage.getHmacKeys({ + serviceAccountEmail: SERVICE_ACCOUNT, + projectId: HMAC_PROJECT, + }); + assert(Array.isArray(hmacKeys)); + assert( + !hmacKeys.some(hmacKey => hmacKey.id === accessId), + 'deleted HMAC key is found from getHmacKeys result', + ); + }); + + describe('second service account', () => { + let accessId: string; + + before(function () { + if (!SECOND_SERVICE_ACCOUNT) { + this.skip(); + } + }); + + after(async () => { + const hmacKey = storage.hmacKey(accessId, {projectId: HMAC_PROJECT}); + await hmacKey.setMetadata({state: 'INACTIVE'}); + await hmacKey.delete(); + }); + + it('should create key for a second service account', async () => { + const [hmacKey] = await storage.createHmacKey(SECOND_SERVICE_ACCOUNT!, { + projectId: HMAC_PROJECT, + }); + accessId = hmacKey.id!; + }); + + it('get HMAC keys for both service accounts', async () => { + // Create a key for the first service account + await storage.createHmacKey(SERVICE_ACCOUNT!, { + projectId: HMAC_PROJECT, + }); + + const [hmacKeys] = await storage.getHmacKeys({projectId: HMAC_PROJECT}); + assert( + hmacKeys.some( + hmacKey => + hmacKey.metadata!.serviceAccountEmail === SERVICE_ACCOUNT, + ), + `Expected at least 1 key for service account: ${SERVICE_ACCOUNT}`, + ); + assert( + hmacKeys.some( + hmacKey => + hmacKey.metadata!.serviceAccountEmail === SECOND_SERVICE_ACCOUNT, + ), + `Expected at least 1 key for service account: ${SECOND_SERVICE_ACCOUNT}`, + ); + }); + + it('filter by service account email', async () => { + const [hmacKeys] = await storage.getHmacKeys({ + serviceAccountEmail: SECOND_SERVICE_ACCOUNT, + projectId: HMAC_PROJECT, + }); + assert( + hmacKeys.every( + hmacKey => + hmacKey.metadata!.serviceAccountEmail === SECOND_SERVICE_ACCOUNT, + ), + 'HMAC key belonging to other service accounts unexpected', + ); + }); + }); + }); + + describe('list files', () => { + const DIRECTORY_NAME = 'directory-name'; + + const NEW_FILES = [ + bucket.file('CloudLogo1'), + bucket.file('CloudLogo2'), + bucket.file('CloudLogo3'), + bucket.file(`${DIRECTORY_NAME}/CloudLogo4`), + bucket.file(`${DIRECTORY_NAME}/CloudLogo5`), + bucket.file(`${DIRECTORY_NAME}/inner/CloudLogo6`), + ]; + + before(async () => { + await bucket.deleteFiles(); + const originalFile = NEW_FILES[0]; + const cloneFiles = NEW_FILES.slice(1); + await bucket.upload(FILES.logo.path, { + destination: originalFile, + }); + await Promise.all(cloneFiles.map(f => originalFile.copy(f))); + }); + + after(async () => { + await Promise.all(NEW_FILES.map(file => deleteFileAsync(file))); + }); + + it('should get files', async () => { + const [files] = await bucket.getFiles(); + assert.strictEqual(files!.length, NEW_FILES.length); + }); + + it('returns file name only when fields is set as name', async () => { + const expected = [ + {name: 'CloudLogo1'}, + {name: 'CloudLogo2'}, + {name: 'CloudLogo3'}, + {name: `${DIRECTORY_NAME}/CloudLogo4`}, + {name: `${DIRECTORY_NAME}/CloudLogo5`}, + {name: `${DIRECTORY_NAME}/inner/CloudLogo6`}, + ]; + const [files] = await bucket.getFiles({fields: 'items(name)'}); + + assert.deepStrictEqual(files, expected); + }); + + it('returns folders as prefixes when includeFoldersAsPrefixes is set', async () => { + const expected = [`${DIRECTORY_NAME}/`]; + const [, , result] = await bucket.getFiles({ + delimiter: '/', + includeFoldersAsPrefixes: true, + autoPaginate: false, + }); + + assert.deepStrictEqual( + (result as {prefixes: string[]}).prefixes, + expected, + ); + }); + + it('should get files as a stream', done => { + let numFilesEmitted = 0; + + bucket + .getFilesStream() + .on('error', done) + .on('data', () => { + numFilesEmitted++; + }) + .on('end', () => { + assert.strictEqual(numFilesEmitted, NEW_FILES.length); + done(); + }); + }); + + it('should only get files matching the supplied matchGlob argument', async () => { + let expectedFileNames = ['CloudLogo1', 'CloudLogo2', 'CloudLogo3']; + let [files] = await bucket.getFiles({matchGlob: 'CloudLogo*'}); + assert.strictEqual(files.length, expectedFileNames.length); + for (const curFile of files) { + assert.strictEqual(expectedFileNames.includes(curFile.name), true); + } + + expectedFileNames = [ + `${DIRECTORY_NAME}/CloudLogo4`, + `${DIRECTORY_NAME}/CloudLogo5`, + `${DIRECTORY_NAME}/inner/CloudLogo6`, + ]; + [files] = await bucket.getFiles({ + matchGlob: `${DIRECTORY_NAME}/**/CloudLogo*`, + }); + assert.strictEqual(files.length, expectedFileNames.length); + for (const curFile of files) { + assert.strictEqual(expectedFileNames.includes(curFile.name), true); + } + }); + + it('should paginate the list', async () => { + const query = { + maxResults: NEW_FILES.length - 1, + }; + + const [files, nextQuery] = await bucket.getFiles(query); + + assert.strictEqual(files!.length, NEW_FILES.length - 1); + assert(nextQuery); + const [nextFiles] = await bucket.getFiles(nextQuery); + assert.strictEqual(nextFiles!.length, 1); + }); + }); + + describe('offset', () => { + const NEW_FILES = [ + bucket.file('startOffset_file1'), + bucket.file('startOffset_file2'), + bucket.file('file3_endOffset'), + ]; + + before(async () => { + await bucket.deleteFiles(); + const originalFile = NEW_FILES[0]; + const cloneFiles = NEW_FILES.slice(1); + await bucket.upload(FILES.logo.path, { + destination: originalFile, + }); + await Promise.all(cloneFiles.map(f => originalFile.copy(f))); + }); + + after(async () => { + await Promise.all(NEW_FILES.map(file => deleteFileAsync(file))); + }); + + it('should get files with offset', async () => { + // Listing files with startOffset. + const [filesWithStartOffset] = await bucket.getFiles({ + startOffset: 'startOffset', + }); + assert.strictEqual(filesWithStartOffset!.length, 2); + + // Listing files with endOffset. + const [filesWithEndOffset] = await bucket.getFiles({ + endOffset: 'set', + }); + assert.strictEqual(filesWithEndOffset!.length, 1); + + // Listing files with startOffset and endOffset. + const [filesWithStartAndEndOffset] = await bucket.getFiles({ + startOffset: 'startOffset', + endOffset: 'endOffset', + }); + assert.strictEqual(filesWithStartAndEndOffset!.length, 0); + }); + }); + + describe('file generations', () => { + const bucketWithVersioning = storage.bucket(generateName()); + + before(async () => { + await bucketWithVersioning.create({ + versioning: { + enabled: true, + }, + }); + }); + + after(async () => { + await bucketWithVersioning.deleteFiles({ + versions: true, + }); + await bucketWithVersioning.delete(); + }); + + it('should overwrite file, then get older version', async () => { + const versionedFile = bucketWithVersioning.file(generateName()); + await versionedFile.save('a'); + const [metadata] = await versionedFile.getMetadata(); + const initialGeneration = metadata.generation; + await versionedFile.save('b'); + const firstGenFile = bucketWithVersioning.file(versionedFile.name, { + generation: initialGeneration, + }); + const [contents] = await firstGenFile.download(); + assert.strictEqual(contents.toString(), 'a'); + }); + + it('should get all files scoped to their version', async () => { + const filesToCreate = [ + {file: bucketWithVersioning.file('file-one.txt'), contents: '123'}, + {file: bucketWithVersioning.file('file-one.txt'), contents: '456'}, + ]; + + await Promise.all(filesToCreate.map(file => createFileAsync(file))); + + const [files] = await bucketWithVersioning.getFiles({versions: true}); + assert.strictEqual(files![0].name, files![1].name); + assert.notStrictEqual( + files![0].metadata.generation, + files![1].metadata.generation, + ); + }); + + it('should throw an error Precondition Failed on overwrite with version 0, then save file with and without resumable', async () => { + const fileName = `test-${Date.now()}.txt`; + + await bucketWithVersioning + .file(fileName) + .save('hello1', {resumable: false}); + await assert.rejects( + bucketWithVersioning.file(fileName, {generation: 0}).save('hello2'), + (err: ApiError) => { + assert.strictEqual(err.code, 412); + assert.strictEqual(err.errors![0].reason, 'conditionNotMet'); + return true; + }, + ); + await bucketWithVersioning + .file(fileName) + .save('hello3', {resumable: false}); + await bucketWithVersioning.file(fileName).save('hello4'); + }); + }); + + describe('v2 signed urls', () => { + const localFile = fs.readFileSync(FILES.logo.path); + let file: File; + + before(done => { + file = bucket.file('LogoToSign.jpg'); + fs.createReadStream(FILES.logo.path) + .pipe(file.createWriteStream()) + .on('error', done) + .on('finish', done.bind(null, null)); + }); + + it('should create a signed read url', async () => { + const [signedReadUrl] = await file.getSignedUrl({ + version: 'v2', + action: 'read', + expires: Date.now() + 5000, + }); + + const res = await fetch(signedReadUrl); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + + it('should work with multi-valued extension headers', async () => { + const HEADERS = { + 'x-goog-custom-header': ['value1', 'value2'], + }; + const [signedReadUrl] = await file.getSignedUrl({ + action: 'read', + expires: Date.now() + 5000, + extensionHeaders: HEADERS, + }); + + const res = await fetch(signedReadUrl, { + headers: {'x-goog-custom-header': 'value1,value2'}, + }); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + + it('should create a signed delete url', async () => { + await file.delete(); + const [signedDeleteUrl] = await file.getSignedUrl({ + version: 'v2', + action: 'delete', + expires: Date.now() + 5000, + }); + + await fetch(signedDeleteUrl, {method: 'DELETE'}); + assert.rejects( + () => file.getMetadata(), + (err: ApiError) => err.code === 404, + ); + }); + }); + + describe('v2 signed url with special characters in file name', () => { + const localFile = fs.readFileSync(FILES.logo.path); + let file: File; + + before(done => { + file = bucket.file("special/azAZ!*'()*%/file.jpg"); + fs.createReadStream(FILES.logo.path) + .pipe(file.createWriteStream()) + .on('error', done) + .on('finish', done.bind(null, null)); + }); + + after(() => file.delete()); + + it('should create a signed read url and fetch a file', async () => { + const [signedUrl] = await file.getSignedUrl({ + version: 'v2', + action: 'read', + expires: Date.now() + 5000, + }); + + const res = await fetch(signedUrl); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + }); + + describe('v4 signed urls', () => { + const localFile = fs.readFileSync(FILES.logo.path); + let file: File; + + before(done => { + file = bucket.file('LogoToSign.jpg'); + fs.createReadStream(FILES.logo.path) + .pipe(file.createWriteStream()) + .on('error', done) + .on('finish', done.bind(null, null)); + }); + + it('should create a signed read url', async () => { + const [signedReadUrl] = await file.getSignedUrl({ + version: 'v4', + action: 'read', + expires: Date.now() + 5000, + }); + + const res = await fetch(signedReadUrl); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + + it('should not throw with expiration of exactly 7 days', async () => { + const ACCESSIBLE_AT = new Date().setMilliseconds(999).valueOf(); + const SEVEN_DAYS_IN_SECONDS = 7 * 24 * 60 * 60; + const SEVEN_DAYS_IN_MS = SEVEN_DAYS_IN_SECONDS * 1000; + await assert.doesNotReject( + async () => { + await file.getSignedUrl({ + version: 'v4', + action: 'read', + accessibleAt: ACCESSIBLE_AT, + expires: ACCESSIBLE_AT + SEVEN_DAYS_IN_MS, + virtualHostedStyle: true, + }); + }, + err => { + assert(err instanceof Error); + assert.strictEqual( + err.message, + `Max allowed expiration is seven days (${SEVEN_DAYS_IN_SECONDS.toString()} seconds).`, + ); + return true; + }, + ); + }); + + it('should create a signed read url with accessibleAt in the past', async () => { + const [signedReadUrl] = await file.getSignedUrl({ + version: 'v4', + action: 'read', + accessibleAt: Date.now() - 5000, + expires: Date.now() + 5000, + }); + + const res = await fetch(signedReadUrl); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + + it('should create a signed read url with accessibleAt in the future', async () => { + const accessibleAtDate = new Date(); + const accessibleAtMinutes = accessibleAtDate.getMinutes(); + const expiresDate = new Date(); + const expiresMinutes = expiresDate.getMinutes(); + const [signedReadUrl] = await file.getSignedUrl({ + version: 'v4', + action: 'read', + accessibleAt: accessibleAtDate.setMinutes(accessibleAtMinutes + 60), + expires: expiresDate.setMinutes(expiresMinutes + 90), + }); + const res = await fetch(signedReadUrl); + assert.strictEqual(res.status, 403); + }); + + it('should work with special characters in extension headers', async () => { + const HEADERS = { + 'x-goog-custom-header': ['value1', "azAZ!*'()*%"], + }; + const [signedReadUrl] = await file.getSignedUrl({ + version: 'v4', + action: 'read', + expires: Date.now() + 5000, + extensionHeaders: HEADERS, + }); + + const res = await fetch(signedReadUrl, { + headers: {'x-goog-custom-header': "value1,azAZ!*'()*%"}, + }); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + + it('should create a virtual-hosted style URL', async () => { + const [signedUrl] = await file.getSignedUrl({ + virtualHostedStyle: true, + version: 'v4', + action: 'read', + expires: Date.now() + 5000, + }); + + const res = await fetch(signedUrl); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + + it('should create a signed delete url', async () => { + const [signedDeleteUrl] = await file.getSignedUrl({ + version: 'v4', + action: 'delete', + expires: Date.now() + 5000, + }); + await fetch(signedDeleteUrl!, {method: 'DELETE'}); + const [exists] = await file.exists(); + assert.strictEqual(exists, false); + }); + + it('should create a signed list bucket url', async () => { + const [signedUrl] = await bucket.getSignedUrl({ + version: 'v4', + action: 'list', + expires: Date.now() + 5000, + }); + const res = await fetch(signedUrl!, {method: 'GET'}); + const body = await res.text(); + assert.strictEqual(res.status, 200); + assert(body.includes('ListBucketResult')); + }); + }); + + describe('v4 signed url with special characters in file name', () => { + const localFile = fs.readFileSync(FILES.logo.path); + let file: File; + + before(done => { + file = bucket.file("special/azAZ!*'()*%/file.jpg"); + fs.createReadStream(FILES.logo.path) + .pipe(file.createWriteStream()) + .on('error', done) + .on('finish', done.bind(null, null)); + }); + + after(async () => file.delete()); + + it('should create a signed read url and fetch a file', async () => { + const [signedUrl] = await file.getSignedUrl({ + version: 'v4', + action: 'read', + expires: Date.now() + 5000, + }); + + const res = await fetch(signedUrl); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + }); + + describe('sign policy', () => { + let file: File; + + before(() => { + file = bucket.file('LogoToSign.jpg'); + }); + + beforeEach(function () { + if (!storage.projectId) { + this.skip(); + } + }); + + it('should create a V2 policy', async () => { + const expires = Date.now() + 60 * 1000; // one minute + const expectedExpiration = new Date(expires).toISOString(); + + const options = { + equals: ['$Content-Type', 'image/jpeg'], + expires, + contentLengthRange: { + min: 0, + max: 1024, + }, + }; + + const [policy] = await file.generateSignedPostPolicyV2(options); + + const policyJson = JSON.parse(policy!.string); + assert.strictEqual(policyJson.expiration, expectedExpiration); + }); + + it('should create a V4 policy', async () => { + const expires = Date.now() + 60 * 1000; // one minute + const options = { + expires, + contentLengthRange: { + min: 0, + max: 50000, + }, + fields: {'x-goog-meta-test': 'data'}, + }; + + const [policy] = await file.generateSignedPostPolicyV4(options); + const form = new FormData(); + for (const [key, value] of Object.entries(policy.fields)) { + form.append(key, value); + } + + const CONTENT = 'my-content'; + + form.append('file', CONTENT); + const res = await fetch(policy.url, {method: 'POST', body: form}); + assert.strictEqual(res.status, 204); + + const [buf] = await file.download(); + assert.strictEqual(buf.toString(), CONTENT); + }); + }); + + describe('notifications', () => { + let notification: Notification; + let subscription: Subscription; + + before(async () => { + const createNotificationData = await bucket.createNotification( + topic.name, + { + eventTypes: ['OBJECT_FINALIZE'], + }, + ); + notification = createNotificationData[0]; + subscription = topic.subscription(generateName()); + await subscription.create(); + }); + + after(async () => { + await subscription.delete(); + const notifications = await bucket.getNotifications(); + const notificationsToDelete = notifications[0].map(notification => { + return notification.delete(); + }); + await Promise.all(notificationsToDelete); + }); + + it('should get an existing notification', async () => { + await notification.get(); + assert(Object.keys(notification.metadata).length > 0); + }); + + it('should get a notifications metadata', async () => { + const [metadata] = await notification.getMetadata(); + assert(metadata !== null && typeof metadata === 'object'); + }); + + it('should tell us if a notification exists', async () => { + const [exists] = await notification.exists(); + assert(exists); + }); + + it('should tell us if a notification does not exist', async () => { + const notification = bucket.notification('123'); + const [exists] = await notification.exists(); + assert.strictEqual(exists, false); + }); + + it('should get a list of notifications', async () => { + const [notifications] = await bucket.getNotifications(); + assert.strictEqual(notifications!.length, 1); + }); + + it('should emit events to a subscription', done => { + subscription + .on('error', err => { + done(err); + }) + .on('message', message => { + const attrs = message.attributes; + assert.strictEqual(attrs.eventType, 'OBJECT_FINALIZE'); + done(); + }); + + bucket.upload(FILES.logo.path, (err: Error | null) => { + if (err) { + done(err); + } + }); + }); + + it('should delete a notification', () => { + let notificationCount = 0; + let notification: Notification; + + return bucket + .createNotification(topic.name, { + eventTypes: ['OBJECT_DELETE'], + }) + .then(data => { + notification = data[0]; + return bucket.getNotifications(); + }) + .then(data => { + notificationCount = data[0].length; + return notification.delete(); + }) + .then(() => { + return bucket.getNotifications(); + }) + .then(data => { + assert.strictEqual(data[0].length, notificationCount - 1); + }); + }); + }); + + describe('CRC32C', () => { + const KNOWN_INPUT_TO_CRC32C = { + /** empty string (i.e. nothing to 'update') */ + '': 'AAAAAA==', + /** known case #1 - validated from actual GCS object upload + metadata retrieval */ + data: 'rth90Q==', + /** known case #2 - validated from actual GCS object upload + metadata retrieval */ + 'some text\n': 'DkjKuA==', + /** arbitrary large string */ + ['a'.repeat(2 ** 16)]: 'TpXtPw==', + } as const; + + it('should generate the appropriate hashes', async () => { + const file = bucket.file('crc32c-test-file'); + + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const buffer = Buffer.from(input); + const crc32c = new CRC32C(); + + await file.save(buffer); + crc32c.update(buffer); + + const [metadata] = await file.getMetadata(); + + assert.equal(metadata.crc32c, expected); + assert(crc32c.validate(metadata.crc32c!)); + } + }); + }); + + describe('universeDomainTests', () => { + let universeDomainStorage: Storage; + const bucketName = generateName(); + const localFile = fs.readFileSync(FILES.logo.path); + let file: File; + + before(async () => { + const TEST_UNIVERSE_DOMAIN = isNullOrUndefined('TEST_UNIVERSE_DOMAIN'); + const TEST_PROJECT_ID = isNullOrUndefined('TEST_UNIVERSE_PROJECT_ID'); + const TEST_UNIVERSE_LOCATION = isNullOrUndefined( + 'TEST_UNIVERSE_LOCATION', + ); + const CREDENTIAL_PATH = isNullOrUndefined( + 'TEST_UNIVERSE_DOMAIN_CREDENTIAL', + ); + // Create a client with universe domain credentials + universeDomainStorage = new Storage({ + projectId: TEST_PROJECT_ID, + keyFilename: CREDENTIAL_PATH, + universeDomain: TEST_UNIVERSE_DOMAIN, + }); + + const [bucket] = await universeDomainStorage.createBucket(bucketName, { + location: TEST_UNIVERSE_LOCATION, + }); + + file = bucket.file('LogoToSign.jpg'); + fs.createReadStream(FILES.logo.path).pipe(file.createWriteStream()); + }); + + after(async () => { + await deleteFileAsync(file); + await deleteBucketAsync(bucket); + }); + + it('should get bucket', async () => { + const [buckets] = await universeDomainStorage.getBuckets(); + const getBucket = buckets.filter(item => item.name === bucketName); + assert.strictEqual(getBucket[0].name, bucketName); + }); + + it('should get files', async () => { + const fileName = await universeDomainStorage + .bucket(bucketName) + .file(file.name).name; + assert.strictEqual(fileName, file.name); + }); + + it('should create a signed read url', async () => { + const [signedReadUrl] = await file.getSignedUrl({ + version: 'v2', + action: 'read', + expires: Date.now() + 5000, + virtualHostedStyle: true, + }); + + const res = await fetch(signedReadUrl); + const body = await res.text(); + assert.strictEqual(body, localFile.toString()); + }); + }); + + async function deleteBucketAsync(bucket: Bucket, options?: {}) { + // After files are deleted, eventual consistency may require a bit of a + // delay to ensure that the bucket recognizes that the files don't exist + // anymore. + const CONSISTENCY_DELAY_MS = 250; + + options = Object.assign({}, options, { + versions: true, + }); + + await bucket.deleteFiles(options); + await new Promise(resolve => setTimeout(resolve, CONSISTENCY_DELAY_MS)); + await bucket.delete(); + } + + function deleteBucket( + bucket: Bucket, + options: {}, + callback: DeleteBucketCallback, + ): void; + function deleteBucket(bucket: Bucket, callback: DeleteBucketCallback): void; + function deleteBucket( + bucket: Bucket, + optsOrCb: {} | DeleteBucketCallback, + callback?: DeleteBucketCallback, + ) { + let options = typeof optsOrCb === 'object' ? optsOrCb : {}; + callback = + typeof optsOrCb === 'function' + ? (optsOrCb as DeleteBucketCallback) + : callback; + + // After files are deleted, eventual consistency may require a bit of a + // delay to ensure that the bucket recognizes that the files don't exist + // anymore. + const CONSISTENCY_DELAY_MS = 250; + + options = Object.assign({}, options, { + versions: true, + }); + + bucket.deleteFiles(options, err => { + if (err) { + callback!(err as Error); + return; + } + + setTimeout(() => { + bucket.delete(options, callback!); + }, CONSISTENCY_DELAY_MS); + }); + } + + function deleteFileAsync(file: File) { + return file.delete(); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function deleteTopicAsync(topic: any) { + return topic.delete(); + } + + function shortUUID() { + return uuid.v1().split('-').shift(); + } + + function generateName() { + return TESTS_PREFIX + shortUUID(); + } + + async function deleteAllBucketsAsync() { + const [buckets] = await storage.getBuckets({prefix: TESTS_PREFIX}); + const limit = pLimit(10); + await new Promise(resolve => + setTimeout(resolve, RETENTION_DURATION_SECONDS * 1000), + ); + return Promise.all( + buckets.map(bucket => limit(() => deleteBucketAsync(bucket))), + ); + } + + async function deleteAllTopicsAsync() { + const [topics] = await pubsub.getTopics(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const filteredTopics = (topics as any[]).filter(topic => { + return topic.name.indexOf(TESTS_PREFIX) > -1; + }); + const limit = pLimit(10); + return Promise.all( + filteredTopics.map(topic => limit(() => deleteTopicAsync(topic))), + ); + } + + async function isFilePublicAsync(file: File) { + try { + const [aclObject] = await file.acl.get({entity: 'allUsers'}); + if ( + (aclObject as AccessControlObject).entity === 'allUsers' && + (aclObject as AccessControlObject).role === 'READER' + ) { + return true; + } else { + return false; + } + } catch (error) { + const err = error as HTTPError; + if (err.code === 404) { + return false; + } else { + throw error; + } + } + } + + async function deleteStaleHmacKeys( + serviceAccountEmail: string, + projectId: string, + ) { + const old = new Date(); + old.setHours(old.getHours() - 1); + const [hmacKeys] = await storage.getHmacKeys({ + serviceAccountEmail, + projectId, + }); + + const limit = pLimit(10); + await Promise.all( + hmacKeys + .filter(hmacKey => { + const hmacKeyCreated = new Date(hmacKey.metadata!.timeCreated!); + return hmacKey.metadata!.state !== 'DELETED' && hmacKeyCreated < old; + }) + .map(hmacKey => + limit(async () => { + await hmacKey.setMetadata({state: 'INACTIVE'}); + await hmacKey.delete(); + }), + ), + ); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function createFileAsync(fileObject: any) { + return fileObject.file.save(fileObject.contents); + } + + function createFileWithContentPromise(content: string) { + return bucket.file(`${generateName()}.txt`).save(content); + } + + function isNullOrUndefined(envVarName: string) { + const value = process.env[envVarName]; + if (value === undefined || value === null) { + throw new Error(`Please set the ${envVarName} environment variable.`); + } + return value; + } +}); diff --git a/handwritten/storage/test/acl.ts b/handwritten/storage/test/acl.ts new file mode 100644 index 00000000000..5c1d73e25ae --- /dev/null +++ b/handwritten/storage/test/acl.ts @@ -0,0 +1,609 @@ +// Copyright 2019 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 {DecorateRequestOptions, util} from '../src/nodejs-common/index.js'; +import assert from 'assert'; +import {describe, it, before, beforeEach} from 'mocha'; +import proxyquire from 'proxyquire'; +import {Storage} from '../src/storage.js'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let Acl: any; +let AclRoleAccessorMethods: Function; +describe('storage/acl', () => { + let promisified = false; + const fakePromisify = { + // tslint:disable-next-line:variable-name + promisifyAll(Class: Function) { + if (Class.name === 'Acl') { + promisified = true; + } + }, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let acl: any; + + const ERROR = new Error('Error.'); + const MAKE_REQ = util.noop; + const PATH_PREFIX = '/acl'; + const ROLE = Storage.acl.OWNER_ROLE; + const ENTITY = 'user-user@example.com'; + + before(() => { + const aclModule = proxyquire('../src/acl.js', { + '@google-cloud/promisify': fakePromisify, + }); + Acl = aclModule.Acl; + AclRoleAccessorMethods = aclModule.AclRoleAccessorMethods; + }); + + beforeEach(() => { + acl = new Acl({request: MAKE_REQ, pathPrefix: PATH_PREFIX}); + }); + + describe('initialization', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should assign makeReq and pathPrefix', () => { + assert.strictEqual(acl.pathPrefix, PATH_PREFIX); + assert.strictEqual(acl.request_, MAKE_REQ); + }); + }); + + describe('add', () => { + it('should make the correct api request', done => { + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.method, 'POST'); + assert.strictEqual(reqOpts.uri, ''); + assert.deepStrictEqual(reqOpts.json, {entity: ENTITY, role: ROLE}); + done(); + }; + + acl.add({entity: ENTITY, role: ROLE}, assert.ifError); + }); + + it('should set the generation', done => { + const options = { + entity: ENTITY, + role: ROLE, + generation: 8, + }; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.generation, options.generation); + done(); + }; + + acl.add(options, assert.ifError); + }); + + it('should set the userProject', done => { + const options = { + entity: ENTITY, + role: ROLE, + userProject: 'grape-spaceship-123', + }; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.userProject, options.userProject); + done(); + }; + + acl.add(options, assert.ifError); + }); + + it('should execute the callback with an ACL object', done => { + const apiResponse = {entity: ENTITY, role: ROLE}; + const expectedAclObject = {entity: ENTITY, role: ROLE}; + + acl.makeAclObject_ = (obj: {}) => { + assert.deepStrictEqual(obj, apiResponse); + return expectedAclObject; + }; + + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, apiResponse); + }; + + acl.add({entity: ENTITY, role: ROLE}, (err: Error, aclObject: {}) => { + assert.ifError(err); + assert.deepStrictEqual(aclObject, expectedAclObject); + done(); + }); + }); + + it('should execute the callback with an error', done => { + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(ERROR); + }; + + acl.add({entity: ENTITY, role: ROLE}, (err: Error) => { + assert.deepStrictEqual(err, ERROR); + done(); + }); + }); + + it('should execute the callback with apiResponse', done => { + const resp = {success: true}; + + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, resp); + }; + + acl.add( + {entity: ENTITY, role: ROLE}, + (err: Error, acls: {}, apiResponse: unknown) => { + assert.deepStrictEqual(resp, apiResponse); + done(); + } + ); + }); + }); + + describe('delete', () => { + it('should make the correct api request', done => { + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.method, 'DELETE'); + assert.strictEqual(reqOpts.uri, '/' + encodeURIComponent(ENTITY)); + + done(); + }; + + acl.delete({entity: ENTITY}, assert.ifError); + }); + + it('should set the generation', done => { + const options = { + entity: ENTITY, + generation: 8, + }; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.generation, options.generation); + done(); + }; + + acl.delete(options, assert.ifError); + }); + + it('should set the userProject', done => { + const options = { + entity: ENTITY, + role: ROLE, + userProject: 'grape-spaceship-123', + }; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.userProject, options.userProject); + done(); + }; + + acl.delete(options, assert.ifError); + }); + + it('should execute the callback with an error', done => { + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(ERROR); + }; + + acl.delete({entity: ENTITY}, (err: Error) => { + assert.deepStrictEqual(err, ERROR); + done(); + }); + }); + + it('should execute the callback with apiResponse', done => { + const resp = {success: true}; + + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, resp); + }; + + acl.delete({entity: ENTITY}, (err: Error, apiResponse: unknown) => { + assert.deepStrictEqual(resp, apiResponse); + done(); + }); + }); + }); + + describe('get', () => { + describe('all ACL objects', () => { + it('should make the correct API request', done => { + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, ''); + + done(); + }; + + acl.get(assert.ifError); + }); + + it('should accept a configuration object', done => { + const generation = 1; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.generation, generation); + + done(); + }; + + acl.get({generation}, assert.ifError); + }); + + it('should pass an array of acl objects to the callback', done => { + const apiResponse = { + items: [ + {entity: ENTITY, role: ROLE}, + {entity: ENTITY, role: ROLE}, + {entity: ENTITY, role: ROLE}, + ], + }; + + const expectedAclObjects = [ + {entity: ENTITY, role: ROLE}, + {entity: ENTITY, role: ROLE}, + {entity: ENTITY, role: ROLE}, + ]; + + acl.makeAclObject_ = (obj: {}, index: number) => { + return expectedAclObjects[index]; + }; + + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, apiResponse); + }; + + acl.get((err: Error, aclObjects: Array<{}>) => { + assert.ifError(err); + assert.deepStrictEqual(aclObjects, expectedAclObjects); + done(); + }); + }); + }); + + describe('ACL object for an entity', () => { + it('should get a specific ACL object', done => { + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, '/' + encodeURIComponent(ENTITY)); + + done(); + }; + + acl.get({entity: ENTITY}, assert.ifError); + }); + + it('should accept a configuration object', done => { + const generation = 1; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.generation, generation); + + done(); + }; + + acl.get({entity: ENTITY, generation}, assert.ifError); + }); + + it('should set the userProject', done => { + const options = { + entity: ENTITY, + userProject: 'grape-spaceship-123', + }; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.userProject, options.userProject); + done(); + }; + + acl.get(options, assert.ifError); + }); + + it('should pass an acl object to the callback', done => { + const apiResponse = {entity: ENTITY, role: ROLE}; + const expectedAclObject = {entity: ENTITY, role: ROLE}; + + acl.makeAclObject_ = () => { + return expectedAclObject; + }; + + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, apiResponse); + }; + + acl.get({entity: ENTITY}, (err: Error, aclObject: {}) => { + assert.ifError(err); + assert.deepStrictEqual(aclObject, expectedAclObject); + done(); + }); + }); + }); + + it('should execute the callback with an error', done => { + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(ERROR); + }; + + acl.get((err: Error) => { + assert.deepStrictEqual(err, ERROR); + done(); + }); + }); + + it('should execute the callback with apiResponse', done => { + const resp = {success: true}; + + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, resp); + }; + + acl.get((err: Error, acls: Array<{}>, apiResponse: unknown) => { + assert.deepStrictEqual(resp, apiResponse); + done(); + }); + }); + }); + + describe('update', () => { + it('should make the correct API request', done => { + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.method, 'PUT'); + assert.strictEqual(reqOpts.uri, '/' + encodeURIComponent(ENTITY)); + assert.deepStrictEqual(reqOpts.json, {role: ROLE}); + + done(); + }; + + acl.update({entity: ENTITY, role: ROLE}, assert.ifError); + }); + + it('should set the generation', done => { + const options = { + entity: ENTITY, + role: ROLE, + generation: 8, + }; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.generation, options.generation); + done(); + }; + + acl.update(options, assert.ifError); + }); + + it('should set the userProject', done => { + const options = { + entity: ENTITY, + role: ROLE, + userProject: 'grape-spaceship-123', + }; + + acl.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.userProject, options.userProject); + done(); + }; + + acl.update(options, assert.ifError); + }); + + it('should pass an acl object to the callback', done => { + const apiResponse = {entity: ENTITY, role: ROLE}; + const expectedAclObject = {entity: ENTITY, role: ROLE}; + + acl.makeAclObject_ = () => { + return expectedAclObject; + }; + + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, apiResponse); + }; + + acl.update({entity: ENTITY, role: ROLE}, (err: Error, aclObject: {}) => { + assert.ifError(err); + assert.deepStrictEqual(aclObject, expectedAclObject); + done(); + }); + }); + + it('should execute the callback with an error', done => { + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(ERROR); + }; + + acl.update({entity: ENTITY, role: ROLE}, (err: Error) => { + assert.deepStrictEqual(err, ERROR); + done(); + }); + }); + + it('should execute the callback with apiResponse', done => { + const resp = {success: true}; + + acl.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, resp); + }; + + const config = {entity: ENTITY, role: ROLE}; + acl.update( + config, + (err: Error, acls: Array<{}>, apiResponse: unknown) => { + assert.deepStrictEqual(resp, apiResponse); + done(); + } + ); + }); + }); + + describe('makeAclObject_', () => { + it('should return an ACL object from an API response', () => { + const projectTeam = { + projectNumber: '283748374', + team: 'awesome', + }; + + const apiResponse = { + entity: ENTITY, + role: ROLE, + projectTeam, + extra: 'ignored', + things: true, + }; + + assert.deepStrictEqual(acl.makeAclObject_(apiResponse), { + entity: ENTITY, + role: ROLE, + projectTeam, + }); + }); + }); + + describe('request', () => { + it('should make the correct request', done => { + const uri = '/uri'; + + const reqOpts = { + uri, + }; + + acl.request_ = (reqOpts_: DecorateRequestOptions, callback: Function) => { + assert.strictEqual(reqOpts_, reqOpts); + assert.strictEqual(reqOpts_.uri, PATH_PREFIX + uri); + callback(); // done() + }; + + acl.request(reqOpts, done); + }); + }); +}); + +describe('storage/AclRoleAccessorMethods', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let aclEntity: any; + + beforeEach(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + aclEntity = new (AclRoleAccessorMethods as any)(); + }); + + describe('initialization', () => { + it('should assign access methods for every role object', () => { + const expectedApi = [ + 'addAllAuthenticatedUsers', + 'deleteAllAuthenticatedUsers', + + 'addAllUsers', + 'deleteAllUsers', + + 'addDomain', + 'deleteDomain', + + 'addGroup', + 'deleteGroup', + + 'addProject', + 'deleteProject', + + 'addUser', + 'deleteUser', + ]; + + const actualOwnersApi = Object.keys(aclEntity.owners); + assert.deepStrictEqual(actualOwnersApi, expectedApi); + + const actualReadersApi = Object.keys(aclEntity.readers); + assert.deepStrictEqual(actualReadersApi, expectedApi); + + const actualWritersApi = Object.keys(aclEntity.writers); + assert.deepStrictEqual(actualWritersApi, expectedApi); + }); + }); + + describe('_assignAccessMethods', () => { + it('should call parent method', async () => { + const userName = 'email@example.com'; + const role = 'fakerole'; + + aclEntity.add = async (options: {}) => { + assert.deepStrictEqual(options, { + entity: 'user-' + userName, + role, + }); + }; + + aclEntity.delete = async (options: {}) => { + assert.deepStrictEqual(options, { + entity: 'allUsers', + role, + }); + }; + + aclEntity._assignAccessMethods(role); + + await Promise.all([ + aclEntity.fakeroles.addUser(userName), + aclEntity.fakeroles.deleteAllUsers(), + ]); + }); + + it('should return the parent methods return value', () => { + const fakeReturn = {}; + + aclEntity.add = () => { + return fakeReturn; + }; + + aclEntity._assignAccessMethods('fakerole'); + + const value = aclEntity.fakeroles.addUser('email@example.com'); + assert.strictEqual(value, fakeReturn); + }); + + it('should not pass in the callback if undefined', done => { + aclEntity.add = (...args: Array<{}>) => { + assert.strictEqual(args.length, 1); + done(); + }; + + aclEntity._assignAccessMethods('fakerole'); + aclEntity.fakeroles.addUser('email@example.com', undefined); + }); + + it('should optionally accept options', done => { + const fakeRole = 'fakerole'; + const fakeUser = 'email@example.com'; + const fakeOptions = { + userProject: 'grape-spaceship-123', + }; + + const expectedOptions = Object.assign( + { + entity: 'user-' + fakeUser, + role: fakeRole, + }, + fakeOptions + ); + + aclEntity.add = (options: {}) => { + assert.deepStrictEqual(options, expectedOptions); + done(); + }; + + aclEntity._assignAccessMethods(fakeRole); + aclEntity.fakeroles.addUser(fakeUser, fakeOptions, assert.ifError); + }); + }); +}); diff --git a/handwritten/storage/test/bucket.ts b/handwritten/storage/test/bucket.ts new file mode 100644 index 00000000000..5b49fa518d8 --- /dev/null +++ b/handwritten/storage/test/bucket.ts @@ -0,0 +1,3303 @@ +// Copyright 2019 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 { + BaseMetadata, + DecorateRequestOptions, + ServiceObject, + ServiceObjectConfig, + util, +} from '../src/nodejs-common/index.js'; +import assert from 'assert'; +import * as fs from 'fs'; +import {describe, it, before, beforeEach, after, afterEach} from 'mocha'; +import mime from 'mime'; +import pLimit from 'p-limit'; +import * as path from 'path'; +import proxyquire from 'proxyquire'; + +import * as stream from 'stream'; +import {Bucket, Channel, Notification, CRC32C} from '../src/index.js'; +import { + CreateWriteStreamOptions, + File, + SetFileMetadataOptions, + FileOptions, + FileMetadata, +} from '../src/file.js'; +import {PromisifyAllOptions} from '@google-cloud/promisify'; +import { + GetBucketMetadataCallback, + GetFilesOptions, + MakeAllFilesPublicPrivateOptions, + SetBucketMetadataResponse, + GetBucketSignedUrlConfig, + AvailableServiceObjectMethods, + BucketExceptionMessages, + BucketMetadata, + LifecycleRule, +} from '../src/bucket.js'; +import {AddAclOptions} from '../src/acl.js'; +import {Policy} from '../src/iam.js'; +import sinon from 'sinon'; +import {Transform} from 'stream'; +import {IdempotencyStrategy} from '../src/storage.js'; +import {convertObjKeysToSnakeCase, getDirName} from '../src/util.js'; +import {DEFAULT_UNIVERSE} from 'google-auth-library'; + +class FakeFile { + calledWith_: IArguments; + bucket: Bucket; + name: string; + options: FileOptions; + metadata: FileMetadata; + createWriteStream: Function; + delete: Function; + isSameFile = () => false; + constructor(bucket: Bucket, name: string, options?: FileOptions) { + // eslint-disable-next-line prefer-rest-params + this.calledWith_ = arguments; + this.bucket = bucket; + this.name = name; + this.options = options || {}; + this.metadata = {}; + + this.createWriteStream = (options: CreateWriteStreamOptions) => { + this.metadata = options.metadata!; + const ws = new stream.Writable(); + ws.write = () => { + ws.emit('complete'); + ws.end(); + return true; + }; + return ws; + }; + + this.delete = () => { + return Promise.resolve(); + }; + } +} + +class FakeNotification { + bucket: Bucket; + id: string; + constructor(bucket: Bucket, id: string) { + this.bucket = bucket; + this.id = id; + } +} + +let fsStatOverride: Function | null; +const fakeFs = { + ...fs, + stat: (filePath: string, callback: Function) => { + return (fsStatOverride || fs.stat)(filePath, callback); + }, +}; + +let pLimitOverride: Function | null; +const fakePLimit = (limit: number) => (pLimitOverride || pLimit)(limit); + +let promisified = false; +const fakePromisify = { + // tslint:disable-next-line:variable-name + promisifyAll(Class: Function, options: PromisifyAllOptions) { + if (Class.name !== 'Bucket') { + return; + } + + promisified = true; + assert.deepStrictEqual(options.exclude, [ + 'cloudStorageURI', + 'request', + 'file', + 'notification', + 'restore', + ]); + }, +}; + +const fakeUtil = Object.assign({}, util); +fakeUtil.noop = util.noop; + +let extended = false; +const fakePaginator = { + paginator: { + // tslint:disable-next-line:variable-name + extend(Class: Function, methods: string[]) { + if (Class.name !== 'Bucket') { + return; + } + methods = Array.isArray(methods) ? methods : [methods]; + assert.strictEqual(Class.name, 'Bucket'); + assert.deepStrictEqual(methods, ['getFiles']); + extended = true; + }, + streamify(methodName: string) { + return methodName; + }, + }, +}; + +class FakeAcl { + calledWith_: Array<{}>; + constructor(...args: Array<{}>) { + this.calledWith_ = args; + } +} + +class FakeIam { + calledWith_: Array<{}>; + constructor(...args: Array<{}>) { + this.calledWith_ = args; + } +} + +class FakeServiceObject extends ServiceObject { + calledWith_: IArguments; + constructor(config: ServiceObjectConfig) { + super(config); + // eslint-disable-next-line prefer-rest-params + this.calledWith_ = arguments; + } +} + +const fakeSigner = { + URLSigner: () => {}, +}; + +class HTTPError extends Error { + code: number; + constructor(message: string, code: number) { + super(message); + this.code = code; + } +} + +describe('Bucket', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Bucket: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let bucket: any; + + const STORAGE = { + createBucket: util.noop, + retryOptions: { + autoRetry: true, + maxRetries: 3, + retryDelayMultiplier: 2, + totalTimeout: 600, + maxRetryDelay: 60, + retryableErrorFn: (err: HTTPError) => { + return err.code === 500; + }, + idempotencyStrategy: IdempotencyStrategy.RetryConditional, + }, + crc32cGenerator: () => new CRC32C(), + universeDomain: DEFAULT_UNIVERSE, + }; + const BUCKET_NAME = 'test-bucket'; + + before(() => { + Bucket = proxyquire('../src/bucket.js', { + fs: fakeFs, + 'p-limit': fakePLimit, + '@google-cloud/promisify': fakePromisify, + '@google-cloud/paginator': fakePaginator, + './nodejs-common': { + ServiceObject: FakeServiceObject, + util: fakeUtil, + }, + './acl.js': {Acl: FakeAcl}, + './file.js': {File: FakeFile}, + './iam.js': {Iam: FakeIam}, + './notification.js': {Notification: FakeNotification}, + './signer.js': fakeSigner, + }).Bucket; + }); + + beforeEach(() => { + fsStatOverride = null; + pLimitOverride = null; + bucket = new Bucket(STORAGE, BUCKET_NAME); + }); + + describe('instantiation', () => { + it('should extend the correct methods', () => { + assert(extended); // See `fakePaginator.extend` + }); + + it('should streamify the correct methods', () => { + assert.strictEqual(bucket.getFilesStream, 'getFiles'); + }); + + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should remove a leading gs://', () => { + const bucket = new Bucket(STORAGE, 'gs://bucket-name'); + assert.strictEqual(bucket.name, 'bucket-name'); + }); + + it('should remove a trailing /', () => { + const bucket = new Bucket(STORAGE, 'bucket-name/'); + assert.strictEqual(bucket.name, 'bucket-name'); + }); + + it('should localize the name', () => { + assert.strictEqual(bucket.name, BUCKET_NAME); + }); + + it('should localize the storage instance', () => { + assert.strictEqual(bucket.storage, STORAGE); + }); + + describe('ACL objects', () => { + let _request: Function; + + before(() => { + _request = Bucket.prototype.request; + }); + + beforeEach(() => { + Bucket.prototype.request = { + bind(ctx: {}) { + return ctx; + }, + }; + + bucket = new Bucket(STORAGE, BUCKET_NAME); + }); + + after(() => { + Bucket.prototype.request = _request; + }); + + it('should create an ACL object', () => { + assert.deepStrictEqual(bucket.acl.calledWith_[0], { + request: bucket, + pathPrefix: '/acl', + }); + }); + + it('should create a default ACL object', () => { + assert.deepStrictEqual(bucket.acl.default.calledWith_[0], { + request: bucket, + pathPrefix: '/defaultObjectAcl', + }); + }); + }); + + it('should inherit from ServiceObject', done => { + const storageInstance = Object.assign({}, STORAGE, { + createBucket: { + bind(context: {}) { + assert.strictEqual(context, storageInstance); + done(); + }, + }, + }); + + const bucket = new Bucket(storageInstance, BUCKET_NAME); + // Using assert.strictEqual instead of assert to prevent + // coercing of types. + assert.strictEqual(bucket instanceof ServiceObject, true); + + const calledWith = bucket.calledWith_[0]; + + assert.strictEqual(calledWith.parent, storageInstance); + assert.strictEqual(calledWith.baseUrl, '/b'); + assert.strictEqual(calledWith.id, BUCKET_NAME); + assert.deepStrictEqual(calledWith.methods, { + create: {reqOpts: {qs: {}}}, + delete: {reqOpts: {qs: {}}}, + exists: {reqOpts: {qs: {}}}, + get: {reqOpts: {qs: {}}}, + getMetadata: {reqOpts: {qs: {}}}, + setMetadata: {reqOpts: {qs: {}}}, + }); + }); + + it('should set the correct query string with a userProject', () => { + const options = {userProject: 'user-project'}; + const bucket = new Bucket(STORAGE, BUCKET_NAME, options); + const calledWith = bucket.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + create: {reqOpts: {qs: options}}, + delete: {reqOpts: {qs: options}}, + exists: {reqOpts: {qs: options}}, + get: {reqOpts: {qs: options}}, + getMetadata: {reqOpts: {qs: options}}, + setMetadata: {reqOpts: {qs: options}}, + }); + }); + + it('should set the correct query string with ifGenerationMatch', () => { + const options = {preconditionOpts: {ifGenerationMatch: 100}}; + const bucket = new Bucket(STORAGE, BUCKET_NAME, options); + + const calledWith = bucket.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + create: {reqOpts: {qs: options.preconditionOpts}}, + delete: {reqOpts: {qs: options.preconditionOpts}}, + exists: {reqOpts: {qs: options.preconditionOpts}}, + get: {reqOpts: {qs: options.preconditionOpts}}, + getMetadata: {reqOpts: {qs: options.preconditionOpts}}, + setMetadata: {reqOpts: {qs: options.preconditionOpts}}, + }); + assert.deepStrictEqual( + bucket.instancePreconditionOpts, + options.preconditionOpts + ); + }); + + it('should set the correct query string with ifGenerationNotMatch', () => { + const options = {preconditionOpts: {ifGenerationNotMatch: 100}}; + const bucket = new Bucket(STORAGE, BUCKET_NAME, options); + + const calledWith = bucket.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + create: {reqOpts: {qs: options.preconditionOpts}}, + delete: {reqOpts: {qs: options.preconditionOpts}}, + exists: {reqOpts: {qs: options.preconditionOpts}}, + get: {reqOpts: {qs: options.preconditionOpts}}, + getMetadata: {reqOpts: {qs: options.preconditionOpts}}, + setMetadata: {reqOpts: {qs: options.preconditionOpts}}, + }); + assert.deepStrictEqual( + bucket.instancePreconditionOpts, + options.preconditionOpts + ); + }); + + it('should set the correct query string with ifMetagenerationMatch', () => { + const options = {preconditionOpts: {ifMetagenerationMatch: 100}}; + const bucket = new Bucket(STORAGE, BUCKET_NAME, options); + + const calledWith = bucket.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + create: {reqOpts: {qs: options.preconditionOpts}}, + delete: {reqOpts: {qs: options.preconditionOpts}}, + exists: {reqOpts: {qs: options.preconditionOpts}}, + get: {reqOpts: {qs: options.preconditionOpts}}, + getMetadata: {reqOpts: {qs: options.preconditionOpts}}, + setMetadata: {reqOpts: {qs: options.preconditionOpts}}, + }); + assert.deepStrictEqual( + bucket.instancePreconditionOpts, + options.preconditionOpts + ); + }); + + it('should set the correct query string with ifMetagenerationNotMatch', () => { + const options = {preconditionOpts: {ifMetagenerationNotMatch: 100}}; + const bucket = new Bucket(STORAGE, BUCKET_NAME, options); + + const calledWith = bucket.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + create: {reqOpts: {qs: options.preconditionOpts}}, + delete: {reqOpts: {qs: options.preconditionOpts}}, + exists: {reqOpts: {qs: options.preconditionOpts}}, + get: {reqOpts: {qs: options.preconditionOpts}}, + getMetadata: {reqOpts: {qs: options.preconditionOpts}}, + setMetadata: {reqOpts: {qs: options.preconditionOpts}}, + }); + assert.deepStrictEqual( + bucket.instancePreconditionOpts, + options.preconditionOpts + ); + }); + + it('should localize an Iam instance', () => { + assert(bucket.iam instanceof FakeIam); + assert.deepStrictEqual(bucket.iam.calledWith_[0], bucket); + }); + + it('should localize userProject if provided', () => { + const fakeUserProject = 'grape-spaceship-123'; + const bucket = new Bucket(STORAGE, BUCKET_NAME, { + userProject: fakeUserProject, + }); + + assert.strictEqual(bucket.userProject, fakeUserProject); + }); + + it('should accept a `crc32cGenerator`', () => { + const crc32cGenerator = () => {}; + + const bucket = new Bucket(STORAGE, 'bucket-name', {crc32cGenerator}); + assert.strictEqual(bucket.crc32cGenerator, crc32cGenerator); + }); + + it("should use storage's `crc32cGenerator` by default", () => { + assert.strictEqual(bucket.crc32cGenerator, STORAGE.crc32cGenerator); + }); + }); + + describe('cloudStorageURI', () => { + it('should return the appropriate `gs://` URI', () => { + const bucket = new Bucket(STORAGE, BUCKET_NAME); + + assert(bucket.cloudStorageURI instanceof URL); + assert.equal(bucket.cloudStorageURI.host, BUCKET_NAME); + }); + }); + + describe('addLifecycleRule', () => { + beforeEach(() => { + bucket.getMetadata = (callback: GetBucketMetadataCallback) => { + callback(null, {}, {}); + }; + }); + + it('should accept raw input', done => { + const rule = { + action: { + type: 'type', + }, + condition: {}, + }; + + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.deepStrictEqual(metadata.lifecycle!.rule, [rule]); + done(); + }; + + bucket.addLifecycleRule(rule, assert.ifError); + }); + + it('should properly set condition', done => { + const rule = { + action: { + type: 'Delete', + }, + condition: { + age: 30, + }, + }; + + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.deepStrictEqual(metadata.lifecycle?.rule, [ + { + action: { + type: 'Delete', + }, + condition: rule.condition, + }, + ]); + done(); + }; + + bucket.addLifecycleRule(rule, assert.ifError); + }); + + it('should convert Date object to date string for condition', done => { + const date = new Date(); + + const rule = { + action: { + type: 'Delete', + }, + condition: { + createdBefore: date, + }, + }; + + bucket.setMetadata = (metadata: BucketMetadata) => { + const expectedDateString = date.toISOString().replace(/T.+$/, ''); + + const rule = metadata!.lifecycle!.rule![0]; + assert.strictEqual(rule.condition.createdBefore, expectedDateString); + + done(); + }; + + bucket.addLifecycleRule(rule, assert.ifError); + }); + + it('should optionally overwrite existing rules', done => { + const rule = { + action: { + type: 'type', + }, + condition: {}, + }; + + const options = { + append: false, + }; + + bucket.getMetadata = () => { + done(new Error('Metadata should not be refreshed.')); + }; + + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.strictEqual(metadata!.lifecycle!.rule!.length, 1); + assert.deepStrictEqual(metadata.lifecycle?.rule, [rule]); + done(); + }; + + bucket.addLifecycleRule(rule, options, assert.ifError); + }); + + it('should combine rule with existing rules by default', done => { + const existingRule: LifecycleRule = { + action: { + type: 'Delete', + }, + condition: {}, + }; + + const newRule: LifecycleRule = { + action: { + type: 'Delete', + }, + condition: {}, + }; + + bucket.getMetadata = (callback: GetBucketMetadataCallback) => { + callback(null, {lifecycle: {rule: [existingRule]}}, {}); + }; + + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.strictEqual(metadata!.lifecycle!.rule!.length, 2); + assert.deepStrictEqual(metadata.lifecycle?.rule, [ + existingRule, + newRule, + ]); + done(); + }; + + bucket.addLifecycleRule(newRule, assert.ifError); + }); + + it('should accept multiple rules', done => { + const existingRule: LifecycleRule = { + action: { + type: 'Delete', + }, + condition: {}, + }; + + const newRules: LifecycleRule[] = [ + { + action: { + type: 'Delete', + }, + condition: {}, + }, + { + action: { + type: 'Delete', + }, + condition: {}, + }, + ]; + + bucket.getMetadata = (callback: GetBucketMetadataCallback) => { + callback(null, {lifecycle: {rule: [existingRule]}}, {}); + }; + + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.strictEqual(metadata!.lifecycle!.rule!.length, 3); + assert.deepStrictEqual(metadata.lifecycle?.rule, [ + existingRule, + newRules[0], + newRules[1], + ]); + done(); + }; + + bucket.addLifecycleRule(newRules, assert.ifError); + }); + + it('should pass error from getMetadata to callback', done => { + const error = new Error('from getMetadata'); + const rule = { + action: 'delete', + condition: {}, + }; + + bucket.getMetadata = (callback: Function) => { + callback(error); + }; + + bucket.setMetadata = () => { + done(new Error('Metadata should not be set.')); + }; + + bucket.addLifecycleRule(rule, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('combine', () => { + it('should throw if invalid sources are provided', () => { + assert.throws(() => { + bucket.combine(), BucketExceptionMessages.PROVIDE_SOURCE_FILE; + }); + + assert.throws(() => { + bucket.combine([]), BucketExceptionMessages.PROVIDE_SOURCE_FILE; + }); + }); + + it('should throw if a destination is not provided', () => { + assert.throws(() => { + bucket.combine(['1', '2']), + BucketExceptionMessages.DESTINATION_FILE_NOT_SPECIFIED; + }); + }); + + it('should accept string or file input for sources', done => { + const file1 = bucket.file('1.txt'); + const file2 = '2.txt'; + const destinationFileName = 'destination.txt'; + + const originalFileMethod = bucket.file; + bucket.file = (name: string) => { + const file = originalFileMethod(name); + + if (name === '2.txt') { + return file; + } + + assert.strictEqual(name, destinationFileName); + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.method, 'POST'); + assert.strictEqual(reqOpts.uri, '/compose'); + assert.strictEqual(reqOpts.json.sourceObjects[0].name, file1.name); + assert.strictEqual(reqOpts.json.sourceObjects[1].name, file2); + + done(); + }; + + return file; + }; + + bucket.combine([file1, file2], destinationFileName); + }); + + it('should use content type from the destination metadata', done => { + const destination = bucket.file('destination.txt'); + + destination.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.json.destination.contentType, + mime.getType(destination.name) + ); + + done(); + }; + + bucket.combine(['1', '2'], destination); + }); + + it('should use content type from the destination metadata', done => { + const destination = bucket.file('destination.txt'); + destination.metadata = {contentType: 'content-type'}; + + destination.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.json.destination.contentType, + destination.metadata.contentType + ); + + done(); + }; + + bucket.combine(['1', '2'], destination); + }); + + it('should detect dest content type if not in metadata', done => { + const destination = bucket.file('destination.txt'); + + destination.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.json.destination.contentType, + mime.getType(destination.name) + ); + + done(); + }; + + bucket.combine(['1', '2'], destination); + }); + + it('should make correct API request', done => { + const sources = [bucket.file('1.foo'), bucket.file('2.foo')]; + const destination = bucket.file('destination.foo'); + + destination.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, '/compose'); + assert.deepStrictEqual(reqOpts.json, { + destination: { + contentType: mime.getType(destination.name) || undefined, + contentEncoding: undefined, + }, + sourceObjects: [{name: sources[0].name}, {name: sources[1].name}], + }); + + done(); + }; + + bucket.combine(sources, destination); + }); + + it('should encode the destination file name', done => { + const sources = [bucket.file('1.txt'), bucket.file('2.txt')]; + const destination = bucket.file('needs encoding.jpg'); + + destination.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri.indexOf(destination), -1); + done(); + }; + + bucket.combine(sources, destination); + }); + + it('should send a source generation value if available', done => { + const sources = [bucket.file('1.txt'), bucket.file('2.txt')]; + sources[0].metadata = {generation: 1}; + sources[1].metadata = {generation: 2}; + + const destination = bucket.file('destination.txt'); + + destination.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.json.sourceObjects, [ + {name: sources[0].name, generation: sources[0].metadata.generation}, + {name: sources[1].name, generation: sources[1].metadata.generation}, + ]); + + done(); + }; + + bucket.combine(sources, destination); + }); + + it('should accept userProject option', done => { + const options = { + userProject: 'user-project-id', + }; + + const sources = [bucket.file('1.txt'), bucket.file('2.txt')]; + const destination = bucket.file('destination.txt'); + + destination.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs, options); + done(); + }; + + bucket.combine(sources, destination, options, assert.ifError); + }); + + it('should accept precondition options', done => { + const options = { + ifGenerationMatch: 100, + ifGenerationNotMatch: 101, + ifMetagenerationMatch: 102, + ifMetagenerationNotMatch: 103, + }; + + const sources = [bucket.file('1.txt'), bucket.file('2.txt')]; + const destination = bucket.file('destination.txt'); + + destination.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.qs.ifGenerationMatch, + options.ifGenerationMatch + ); + assert.strictEqual( + reqOpts.qs.ifGenerationNotMatch, + options.ifGenerationNotMatch + ); + assert.strictEqual( + reqOpts.qs.ifMetagenerationMatch, + options.ifMetagenerationMatch + ); + assert.strictEqual( + reqOpts.qs.ifMetagenerationNotMatch, + options.ifMetagenerationNotMatch + ); + done(); + }; + + bucket.combine(sources, destination, options, assert.ifError); + }); + + it('should execute the callback', done => { + const sources = [bucket.file('1.txt'), bucket.file('2.txt')]; + const destination = bucket.file('destination.txt'); + + destination.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(); + }; + + bucket.combine(sources, destination, done); + }); + + it('should execute the callback with an error', done => { + const sources = [bucket.file('1.txt'), bucket.file('2.txt')]; + const destination = bucket.file('destination.txt'); + + const error = new Error('Error.'); + + destination.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error); + }; + + bucket.combine(sources, destination, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should execute the callback with apiResponse', done => { + const sources = [bucket.file('1.txt'), bucket.file('2.txt')]; + const destination = bucket.file('destination.txt'); + const resp = {success: true}; + + destination.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, resp); + }; + + bucket.combine( + sources, + destination, + (err: Error, obj: {}, apiResponse: {}) => { + assert.strictEqual(resp, apiResponse); + done(); + } + ); + }); + + it('should set maxRetries to 0 when ifGenerationMatch is undefined', done => { + const sources = [bucket.file('1.txt'), bucket.file('2.txt')]; + const destination = bucket.file('destination.txt'); + + destination.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.maxRetries, 0); + callback(); + }; + + bucket.combine(sources, destination, done); + }); + }); + + describe('createChannel', () => { + const ID = 'id'; + const CONFIG = { + address: 'https://...', + }; + + it('should throw if an ID is not provided', () => { + assert.throws(() => { + bucket.createChannel(), BucketExceptionMessages.CHANNEL_ID_REQUIRED; + }); + }); + + it('should make the correct request', done => { + const config = Object.assign({}, CONFIG, { + a: 'b', + c: 'd', + }); + const originalConfig = Object.assign({}, config); + + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.method, 'POST'); + assert.strictEqual(reqOpts.uri, '/o/watch'); + + const expectedJson = Object.assign({}, config, { + id: ID, + type: 'web_hook', + }); + assert.deepStrictEqual(reqOpts.json, expectedJson); + assert.deepStrictEqual(config, originalConfig); + + done(); + }; + + bucket.createChannel(ID, config, assert.ifError); + }); + + it('should accept userProject option', done => { + const options = { + userProject: 'user-project-id', + }; + + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs, options); + done(); + }; + + bucket.createChannel(ID, CONFIG, options, assert.ifError); + }); + + describe('error', () => { + const error = new Error('Error.'); + const apiResponse = {}; + + beforeEach(() => { + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error, apiResponse); + }; + }); + + it('should execute callback with error & API response', done => { + bucket.createChannel( + ID, + CONFIG, + (err: Error, channel: Channel, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(channel, null); + assert.strictEqual(apiResponse_, apiResponse); + + done(); + } + ); + }); + }); + + describe('success', () => { + const apiResponse = { + resourceId: 'resource-id', + }; + + beforeEach(() => { + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, apiResponse); + }; + }); + + it('should exec a callback with Channel & API response', done => { + const channel = {}; + + bucket.storage.channel = (id: string, resourceId: string) => { + assert.strictEqual(id, ID); + assert.strictEqual(resourceId, apiResponse.resourceId); + return channel; + }; + + bucket.createChannel( + ID, + CONFIG, + (err: Error, channel_: Channel, apiResponse_: {}) => { + assert.ifError(err); + assert.strictEqual(channel_, channel); + assert.strictEqual(channel_.metadata, apiResponse); + assert.strictEqual(apiResponse_, apiResponse); + done(); + } + ); + }); + }); + }); + + describe('createNotification', () => { + const PUBSUB_SERVICE_PATH = '//pubsub.googleapis.com/'; + const TOPIC = 'my-topic'; + const FULL_TOPIC_NAME = + PUBSUB_SERVICE_PATH + 'projects/{{projectId}}/topics/' + TOPIC; + + class FakeTopic { + name: string; + constructor(name: string) { + this.name = 'projects/grape-spaceship-123/topics/' + name; + } + } + + beforeEach(() => { + fakeUtil.isCustomType = util.isCustomType; + }); + + it('should throw an error if a valid topic is not provided', () => { + assert.throws(() => { + bucket.createNotification(), + BucketExceptionMessages.TOPIC_NAME_REQUIRED; + }); + }); + + it('should make the correct request', done => { + const topic = 'projects/my-project/topics/my-topic'; + const options = {payloadFormat: 'NONE'}; + const expectedTopic = PUBSUB_SERVICE_PATH + topic; + const expectedJson = Object.assign( + {topic: expectedTopic}, + convertObjKeysToSnakeCase(options) + ); + + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.method, 'POST'); + assert.strictEqual(reqOpts.uri, '/notificationConfigs'); + assert.deepStrictEqual(reqOpts.json, expectedJson); + assert.notStrictEqual(reqOpts.json, options); + done(); + }; + + bucket.createNotification(topic, options, assert.ifError); + }); + + it('should accept incomplete topic names', done => { + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.topic, FULL_TOPIC_NAME); + done(); + }; + + bucket.createNotification(TOPIC, {}, assert.ifError); + }); + + it('should accept a topic object', done => { + const fakeTopic = new FakeTopic('my-topic'); + const expectedTopicName = PUBSUB_SERVICE_PATH + fakeTopic.name; + + fakeUtil.isCustomType = (topic, type) => { + assert.strictEqual(topic, fakeTopic); + assert.strictEqual(type, 'pubsub/topic'); + return true; + }; + + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.topic, expectedTopicName); + done(); + }; + + bucket.createNotification(fakeTopic, {}, assert.ifError); + }); + + it('should set a default payload format', done => { + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.payload_format, 'JSON_API_V1'); + done(); + }; + + bucket.createNotification(TOPIC, {}, assert.ifError); + }); + + it('should optionally accept options', done => { + const expectedJson = { + topic: FULL_TOPIC_NAME, + payload_format: 'JSON_API_V1', + }; + + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.json, expectedJson); + done(); + }; + + bucket.createNotification(TOPIC, assert.ifError); + }); + + it('should accept a userProject', done => { + const options = { + userProject: 'grape-spaceship-123', + }; + + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.userProject, options.userProject); + done(); + }; + + bucket.createNotification(TOPIC, options, assert.ifError); + }); + + it('should return errors to the callback', done => { + const error = new Error('err'); + const response = {}; + + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error, response); + }; + + bucket.createNotification( + TOPIC, + (err: Error, notification: Notification, resp: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(notification, null); + assert.strictEqual(resp, response); + done(); + } + ); + }); + + it('should return a notification object', done => { + const fakeId = '123'; + const response = {id: fakeId}; + const fakeNotification = {}; + + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, response); + }; + + bucket.notification = (id: string) => { + assert.strictEqual(id, fakeId); + return fakeNotification; + }; + + bucket.createNotification( + TOPIC, + (err: Error, notification: Notification, resp: {}) => { + assert.ifError(err); + assert.strictEqual(notification, fakeNotification); + assert.strictEqual(notification.metadata, response); + assert.strictEqual(resp, response); + done(); + } + ); + }); + }); + + describe('deleteFiles', () => { + let readCount: number; + + beforeEach(() => { + readCount = 0; + }); + + it('should accept only a callback', done => { + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.delete = () => { + return Promise.resolve(); + }; + return file; + }); + + const readable = new stream.Readable({ + objectMode: true, + read() { + if (readCount < 1) { + this.push(files[readCount]); + readCount++; + } else { + this.push(null); + } + }, + }); + + bucket.getFilesStream = (query: {}) => { + assert.deepStrictEqual(query, {}); + return readable; + }; + + bucket.deleteFiles(done); + }); + + it('should get files from the bucket', done => { + const query = {a: 'b', c: 'd'}; + + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.delete = () => { + return Promise.resolve(); + }; + return file; + }); + + const readable = new stream.Readable({ + objectMode: true, + read() { + if (readCount < 1) { + this.push(files[readCount]); + readCount++; + } else { + this.push(null); + } + }, + }); + + bucket.getFilesStream = (query_: {}) => { + assert.deepStrictEqual(query_, query); + return readable; + }; + + bucket.deleteFiles(query, done); + }); + + it('should process 10 files at a time', done => { + pLimitOverride = (limit: number) => { + assert.strictEqual(limit, 10); + setImmediate(done); + return () => {}; + }; + + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.delete = () => { + return Promise.resolve(); + }; + return file; + }); + + const readable = new stream.Readable({ + objectMode: true, + read() { + if (readCount < 1) { + this.push(files[readCount]); + readCount++; + } else { + this.push(null); + } + }, + }); + + bucket.getFilesStream = () => readable; + bucket.deleteFiles({}, assert.ifError); + }); + + it('should delete the files', done => { + const query = {}; + let timesCalled = 0; + + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.delete = (query_: {}) => { + timesCalled++; + assert.strictEqual(query_, query); + return Promise.resolve(); + }; + return file; + }); + + const readable = new stream.Readable({ + objectMode: true, + read() { + if (readCount < files.length) { + this.push(files[readCount]); + readCount++; + } else { + this.push(null); + } + }, + }); + + bucket.getFilesStream = (query_: {}) => { + assert.strictEqual(query_, query); + return readable; + }; + + bucket.deleteFiles(query, (err: Error) => { + assert.ifError(err); + assert.strictEqual(timesCalled, files.length); + done(); + }); + }); + + it('should execute callback with error from getting files', done => { + const error = new Error('Error.'); + const readable = new stream.Readable({ + objectMode: true, + read() { + this.destroy(error); + }, + }); + + bucket.getFilesStream = () => { + return readable; + }; + + bucket.deleteFiles({}, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should execute callback with error from deleting file', done => { + const error = new Error('Error.'); + + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.delete = () => Promise.reject(error); + return file; + }); + + const readable = new stream.Readable({ + objectMode: true, + read() { + if (readCount < files.length) { + this.push(files[readCount]); + readCount++; + } else { + this.push(null); + } + }, + }); + + bucket.getFilesStream = () => { + return readable; + }; + + bucket.deleteFiles({}, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should execute callback with queued errors', done => { + const error = new Error('Error.'); + + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.delete = () => Promise.reject(error); + return file; + }); + + const readable = new stream.Readable({ + objectMode: true, + read() { + if (readCount < files.length) { + this.push(files[readCount]); + readCount++; + } else { + this.push(null); + } + }, + }); + + bucket.getFilesStream = () => { + return readable; + }; + + bucket.deleteFiles({force: true}, (errs: Array<{}>) => { + assert.strictEqual(errs[0], error); + assert.strictEqual(errs[1], error); + done(); + }); + }); + }); + + describe('deleteLabels', () => { + describe('all labels', () => { + it('should get all of the label names', done => { + bucket.getLabels = () => { + done(); + }; + + bucket.deleteLabels(assert.ifError); + }); + + it('should return an error from getLabels()', done => { + const error = new Error('Error.'); + + bucket.getLabels = (callback: Function) => { + callback(error); + }; + + bucket.deleteLabels((err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should call setLabels with all label names', done => { + const labels = { + labelone: 'labelonevalue', + labeltwo: 'labeltwovalue', + }; + + bucket.getLabels = (callback: Function) => { + callback(null, labels); + }; + + bucket.setLabels = (labels: {}, callback: Function) => { + assert.deepStrictEqual(labels, { + labelone: null, + labeltwo: null, + }); + callback(); // done() + }; + + bucket.deleteLabels(done); + }); + }); + + describe('single label', () => { + const LABEL = 'labelname'; + + it('should call setLabels with a single label', done => { + bucket.setLabels = (labels: {}, callback: Function) => { + assert.deepStrictEqual(labels, { + [LABEL]: null, + }); + callback(); // done() + }; + + bucket.deleteLabels(LABEL, done); + }); + }); + + describe('multiple labels', () => { + const LABELS = ['labelonename', 'labeltwoname']; + + it('should call setLabels with multiple labels', done => { + bucket.setLabels = (labels: {}, callback: Function) => { + assert.deepStrictEqual(labels, { + labelonename: null, + labeltwoname: null, + }); + callback(); // done() + }; + + bucket.deleteLabels(LABELS, done); + }); + }); + }); + + describe('disableRequesterPays', () => { + it('should call setMetadata correctly', done => { + bucket.setMetadata = ( + metadata: {}, + _optionsOrCallback: {}, + callback: Function + ) => { + assert.deepStrictEqual(metadata, { + billing: { + requesterPays: false, + }, + }); + Promise.resolve([]).then(resp => callback(null, ...resp)); + }; + + bucket.disableRequesterPays(done); + }); + + it('should not require a callback', done => { + bucket.setMetadata = ( + metadata: {}, + optionsOrCallback: {}, + callback: Function + ) => { + assert.strictEqual(callback, undefined); + done(); + }; + + bucket.disableRequesterPays(); + }); + + it('should set autoRetry to false when ifMetagenerationMatch is undefined', done => { + bucket.setMetadata = () => { + Promise.resolve().then(() => { + assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); + done(); + }); + }; + bucket.disableRequesterPays(); + }); + }); + + describe('enableLogging', () => { + const PREFIX = 'prefix'; + + beforeEach(() => { + bucket.iam = { + getPolicy: () => Promise.resolve([{bindings: []}]), + setPolicy: () => Promise.resolve(), + }; + bucket.setMetadata = () => Promise.resolve([]); + }); + + it('should throw if a config object is not provided', () => { + assert.throws(() => { + bucket.enableLogging(), + BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED; + }); + }); + + it('should throw if config is a function', () => { + assert.throws(() => { + bucket.enableLogging(assert.ifError), + BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED; + }); + }); + + it('should throw if a prefix is not provided', () => { + assert.throws(() => { + bucket.enableLogging( + { + bucket: 'bucket-name', + }, + assert.ifError + ), + BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED; + }); + }); + + it('should add IAM permissions', done => { + const policy = { + bindings: [{}], + }; + bucket.iam = { + getPolicy: () => Promise.resolve([policy]), + setPolicy: (policy_: Policy) => { + assert.deepStrictEqual(policy, policy_); + assert.deepStrictEqual(policy_.bindings, [ + policy.bindings[0], + { + members: ['group:cloud-storage-analytics@google.com'], + role: 'roles/storage.objectCreator', + }, + ]); + setImmediate(done); + return Promise.resolve(); + }, + }; + + bucket.enableLogging({prefix: PREFIX}, assert.ifError); + }); + + it('should return an error from getting the IAM policy', done => { + const error = new Error('Error.'); + + bucket.iam.getPolicy = () => { + throw error; + }; + + bucket.enableLogging({prefix: PREFIX}, (err: Error | null) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return an error from setting the IAM policy', done => { + const error = new Error('Error.'); + + bucket.iam.setPolicy = () => { + throw error; + }; + + bucket.enableLogging({prefix: PREFIX}, (err: Error | null) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should update the logging metadata configuration', done => { + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.deepStrictEqual(metadata.logging, { + logBucket: bucket.id, + logObjectPrefix: PREFIX, + }); + setImmediate(done); + return Promise.resolve([]); + }; + + bucket.enableLogging({prefix: PREFIX}, assert.ifError); + }); + + it('should allow a custom bucket to be provided', done => { + const bucketName = 'bucket-name'; + + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.deepStrictEqual(metadata!.logging!.logBucket, bucketName); + setImmediate(done); + return Promise.resolve([]); + }; + + bucket.enableLogging( + { + prefix: PREFIX, + bucket: bucketName, + }, + assert.ifError + ); + }); + + it('should accept a Bucket object', done => { + const bucketForLogging = new Bucket(STORAGE, 'bucket-name'); + + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.deepStrictEqual( + metadata!.logging!.logBucket, + bucketForLogging.id + ); + setImmediate(done); + return Promise.resolve([]); + }; + + bucket.enableLogging( + { + prefix: PREFIX, + bucket: bucketForLogging, + }, + assert.ifError + ); + }); + + it('should execute the callback with the setMetadata response', done => { + const setMetadataResponse = {}; + + bucket.setMetadata = ( + metadata: {}, + optionsOrCallback: {}, + callback: Function + ) => { + Promise.resolve([setMetadataResponse]).then(resp => + callback(null, ...resp) + ); + }; + + bucket.enableLogging( + {prefix: PREFIX}, + (err: Error | null, response: SetBucketMetadataResponse) => { + assert.ifError(err); + assert.strictEqual(response, setMetadataResponse); + done(); + } + ); + }); + + it('should return an error from the setMetadata call failing', done => { + const error = new Error('Error.'); + + bucket.setMetadata = () => { + throw error; + }; + + bucket.enableLogging({prefix: PREFIX}, (err: Error | null) => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('enableRequesterPays', () => { + it('should call setMetadata correctly', done => { + bucket.setMetadata = ( + metadata: {}, + optionsOrCallback: {}, + callback: Function + ) => { + assert.deepStrictEqual(metadata, { + billing: { + requesterPays: true, + }, + }); + Promise.resolve([]).then(resp => callback(null, ...resp)); + }; + + bucket.enableRequesterPays(done); + }); + + it('should not require a callback', done => { + bucket.setMetadata = ( + metadata: {}, + optionsOrCallback: {}, + callback: Function + ) => { + assert.equal(callback, undefined); + done(); + }; + + bucket.enableRequesterPays(); + }); + }); + + describe('file', () => { + const FILE_NAME = 'remote-file-name.jpg'; + let file: FakeFile; + const options = {a: 'b', c: 'd'}; + + beforeEach(() => { + file = bucket.file(FILE_NAME, options); + }); + + it('should throw if no name is provided', () => { + assert.throws(() => { + bucket.file(), BucketExceptionMessages.SPECIFY_FILE_NAME; + }); + }); + + it('should return a File object', () => { + assert(file instanceof FakeFile); + }); + + it('should pass bucket to File object', () => { + assert.deepStrictEqual(file.calledWith_[0], bucket); + }); + + it('should pass filename to File object', () => { + assert.strictEqual(file.calledWith_[1], FILE_NAME); + }); + + it('should pass configuration object to File', () => { + assert.deepStrictEqual(file.calledWith_[2], options); + }); + }); + + describe('getFiles', () => { + it('should get files without a query', done => { + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, '/o'); + assert.deepStrictEqual(reqOpts.qs, {}); + done(); + }; + + bucket.getFiles(util.noop); + }); + + it('should get files with a query', done => { + const token = 'next-page-token'; + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.qs, { + maxResults: 5, + pageToken: token, + includeFoldersAsPrefixes: true, + delimiter: '/', + autoPaginate: false, + }); + done(); + }; + bucket.getFiles( + { + maxResults: 5, + pageToken: token, + includeFoldersAsPrefixes: true, + delimiter: '/', + autoPaginate: false, + }, + util.noop + ); + }); + + it('should return nextQuery if more results exist', () => { + const token = 'next-page-token'; + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, {nextPageToken: token, items: []}); + }; + bucket.getFiles( + {maxResults: 5}, + (err: Error, results: {}, nextQuery: GetFilesOptions) => { + assert.strictEqual(nextQuery.pageToken, token); + assert.strictEqual(nextQuery.maxResults, 5); + } + ); + }); + + it('should return null nextQuery if there are no more results', () => { + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, {items: []}); + }; + bucket.getFiles( + {maxResults: 5}, + (err: Error, results: {}, nextQuery: {}) => { + assert.strictEqual(nextQuery, null); + } + ); + }); + + it('should return File objects', done => { + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, { + items: [{name: 'fake-file-name', generation: 1}], + }); + }; + bucket.getFiles((err: Error, files: FakeFile[]) => { + assert.ifError(err); + assert(files[0] instanceof FakeFile); + assert.strictEqual( + typeof files[0].calledWith_[2].generation, + 'undefined' + ); + done(); + }); + }); + + it('should return versioned Files if queried for versions', done => { + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, { + items: [{name: 'fake-file-name', generation: 1}], + }); + }; + + bucket.getFiles({versions: true}, (err: Error, files: FakeFile[]) => { + assert.ifError(err); + assert(files[0] instanceof FakeFile); + assert.strictEqual(files[0].calledWith_[2].generation, 1); + done(); + }); + }); + + it('should return Files with specified values if queried for fields', done => { + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, { + items: [{name: 'fake-file-name'}], + }); + }; + + bucket.getFiles( + {fields: 'items(name)'}, + (err: Error, files: FakeFile[]) => { + assert.ifError(err); + assert.strictEqual(files[0].name, 'fake-file-name'); + done(); + } + ); + }); + + it('should add nextPageToken to fields for autoPaginate', done => { + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.qs.fields, 'items(name),nextPageToken'); + callback(null, { + items: [{name: 'fake-file-name'}], + nextPageToken: 'fake-page-token', + }); + }; + + bucket.getFiles( + {fields: 'items(name)', autoPaginate: true}, + (err: Error, files: FakeFile[], nextQuery: {pageToken: string}) => { + assert.ifError(err); + assert.strictEqual(files[0].name, 'fake-file-name'); + assert.strictEqual(nextQuery.pageToken, 'fake-page-token'); + done(); + } + ); + }); + + it('should return soft-deleted Files if queried for softDeleted', done => { + const softDeletedTime = new Date('1/1/2024').toISOString(); + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, { + items: [{name: 'fake-file-name', generation: 1, softDeletedTime}], + }); + }; + + bucket.getFiles({softDeleted: true}, (err: Error, files: FakeFile[]) => { + assert.ifError(err); + assert(files[0] instanceof FakeFile); + assert.strictEqual(files[0].metadata.softDeletedTime, softDeletedTime); + done(); + }); + }); + + it('should set kmsKeyName on file', done => { + const kmsKeyName = 'kms-key-name'; + + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, { + items: [{name: 'fake-file-name', kmsKeyName}], + }); + }; + + bucket.getFiles({versions: true}, (err: Error, files: FakeFile[]) => { + assert.ifError(err); + assert.strictEqual(files[0].calledWith_[2].kmsKeyName, kmsKeyName); + done(); + }); + }); + + it('should return apiResponse in callback', done => { + const resp = {items: [{name: 'fake-file-name'}]}; + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, resp); + }; + bucket.getFiles( + (err: Error, files: Array<{}>, nextQuery: {}, apiResponse: {}) => { + assert.deepStrictEqual(resp, apiResponse); + done(); + } + ); + }); + + it('should execute callback with error & API response', done => { + const error = new Error('Error.'); + const apiResponse = {}; + + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error, apiResponse); + }; + + bucket.getFiles( + (err: Error, files: File[], nextQuery: {}, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(files, null); + assert.strictEqual(nextQuery, null); + assert.strictEqual(apiResponse_, apiResponse); + + done(); + } + ); + }); + + it('should populate returned File object with metadata', done => { + const fileMetadata = { + name: 'filename', + contentType: 'x-zebra', + metadata: { + my: 'custom metadata', + }, + }; + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, {items: [fileMetadata]}); + }; + bucket.getFiles((err: Error, files: FakeFile[]) => { + assert.ifError(err); + assert.deepStrictEqual(files[0].metadata, fileMetadata); + done(); + }); + }); + }); + + describe('getLabels', () => { + it('should refresh metadata', done => { + bucket.getMetadata = () => { + done(); + }; + + bucket.getLabels(assert.ifError); + }); + + it('should accept an options object', done => { + const options = {}; + + bucket.getMetadata = (options_: {}) => { + assert.strictEqual(options_, options); + done(); + }; + + bucket.getLabels(options, assert.ifError); + }); + + it('should return error from getMetadata', done => { + const error = new Error('Error.'); + + bucket.getMetadata = (options: {}, callback: Function) => { + callback(error); + }; + + bucket.getLabels((err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return labels metadata property', done => { + const metadata = { + labels: { + label: 'labelvalue', + }, + }; + + bucket.getMetadata = (options: {}, callback: Function) => { + callback(null, metadata); + }; + + bucket.getLabels((err: Error, labels: {}) => { + assert.ifError(err); + assert.strictEqual(labels, metadata.labels); + done(); + }); + }); + + it('should return empty object if no labels exist', done => { + const metadata = {}; + + bucket.getMetadata = (options: {}, callback: Function) => { + callback(null, metadata); + }; + + bucket.getLabels((err: Error, labels: {}) => { + assert.ifError(err); + assert.deepStrictEqual(labels, {}); + done(); + }); + }); + }); + + describe('getNotifications', () => { + it('should make the correct request', done => { + const options = {}; + + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, '/notificationConfigs'); + assert.strictEqual(reqOpts.qs, options); + done(); + }; + + bucket.getNotifications(options, assert.ifError); + }); + + it('should optionally accept options', done => { + bucket.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.qs, {}); + done(); + }; + + bucket.getNotifications(assert.ifError); + }); + + it('should return any errors to the callback', done => { + const error = new Error('err'); + const response = {}; + + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error, response); + }; + + bucket.getNotifications( + (err: Error, notifications: Notification[], resp: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(notifications, null); + assert.strictEqual(resp, response); + done(); + } + ); + }); + + it('should return a list of notification objects', done => { + const fakeItems = [{id: '1'}, {id: '2'}, {id: '3'}]; + const response = {items: fakeItems}; + + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, response); + }; + + let callCount = 0; + const fakeNotifications = [{}, {}, {}]; + + bucket.notification = (id: string) => { + const expectedId = fakeItems[callCount].id; + assert.strictEqual(id, expectedId); + return fakeNotifications[callCount++]; + }; + + bucket.getNotifications( + (err: Error, notifications: Notification[], resp: {}) => { + assert.ifError(err); + notifications.forEach((notification, i) => { + assert.strictEqual(notification, fakeNotifications[i]); + assert.strictEqual(notification.metadata, fakeItems[i]); + }); + assert.strictEqual(resp, response); + done(); + } + ); + }); + }); + + describe('getSignedUrl', () => { + const EXPECTED_SIGNED_URL = 'signed-url'; + const CNAME = 'https://www.example.com'; + + let sandbox: sinon.SinonSandbox; + let signer: {getSignedUrl: Function}; + let signerGetSignedUrlStub: sinon.SinonStub; + let urlSignerStub: sinon.SinonStub; + let SIGNED_URL_CONFIG: GetBucketSignedUrlConfig; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + + signerGetSignedUrlStub = sandbox.stub().resolves(EXPECTED_SIGNED_URL); + + signer = { + getSignedUrl: signerGetSignedUrlStub, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + urlSignerStub = (sandbox.stub as any)(fakeSigner, 'URLSigner').returns( + signer + ); + + SIGNED_URL_CONFIG = { + version: 'v4', + expires: new Date(), + action: 'list', + cname: CNAME, + }; + }); + + afterEach(() => sandbox.restore()); + + it('should construct a URLSigner and call getSignedUrl', done => { + // assert signer is lazily-initialized. + assert.strictEqual(bucket.signer, undefined); + bucket.getSignedUrl( + SIGNED_URL_CONFIG, + (err: Error | null, signedUrl: string) => { + assert.ifError(err); + assert.strictEqual(bucket.signer, signer); + assert.strictEqual(signedUrl, EXPECTED_SIGNED_URL); + + const ctorArgs = urlSignerStub.getCall(0).args; + assert.strictEqual(ctorArgs[0], bucket.storage.authClient); + assert.strictEqual(ctorArgs[1], bucket); + + const getSignedUrlArgs = signerGetSignedUrlStub.getCall(0).args; + assert.deepStrictEqual(getSignedUrlArgs[0], { + method: 'GET', + version: 'v4', + expires: SIGNED_URL_CONFIG.expires, + extensionHeaders: {}, + host: undefined, + queryParams: {}, + cname: CNAME, + signingEndpoint: undefined, + }); + done(); + } + ); + }); + }); + + describe('lock', () => { + it('should throw if a metageneration is not provided', () => { + assert.throws(() => { + bucket.lock(assert.ifError), + BucketExceptionMessages.METAGENERATION_NOT_PROVIDED; + }); + }); + + it('should make the correct request', done => { + const metageneration = 8; + + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.deepStrictEqual(reqOpts, { + method: 'POST', + uri: '/lockRetentionPolicy', + qs: { + ifMetagenerationMatch: metageneration, + }, + }); + + callback(); // done() + }; + + bucket.lock(metageneration, done); + }); + }); + + describe('makePrivate', () => { + it('should set predefinedAcl & privatize files', done => { + let didSetPredefinedAcl = false; + let didMakeFilesPrivate = false; + const opts = { + includeFiles: true, + force: true, + }; + + bucket.setMetadata = (metadata: {}, options: {}, callback: Function) => { + assert.deepStrictEqual(metadata, {acl: null}); + assert.deepStrictEqual(options, {predefinedAcl: 'projectPrivate'}); + + didSetPredefinedAcl = true; + bucket.makeAllFilesPublicPrivate_(opts, callback); + }; + + bucket.makeAllFilesPublicPrivate_ = ( + opts: MakeAllFilesPublicPrivateOptions, + callback: Function + ) => { + assert.strictEqual(opts.private, true); + assert.strictEqual(opts.force, true); + didMakeFilesPrivate = true; + callback(); + }; + + bucket.makePrivate(opts, (err: Error) => { + assert.ifError(err); + assert(didSetPredefinedAcl); + assert(didMakeFilesPrivate); + done(); + }); + }); + + it('should accept metadata', done => { + const options = { + metadata: {a: 'b', c: 'd'}, + }; + bucket.setMetadata = (metadata: {}) => { + assert.deepStrictEqual(metadata, { + acl: null, + ...options.metadata, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.strictEqual(typeof (options.metadata as any).acl, 'undefined'); + done(); + }; + bucket.makePrivate(options, assert.ifError); + }); + + it('should accept userProject', done => { + const options = { + userProject: 'user-project-id', + }; + bucket.setMetadata = (metadata: {}, options_: SetFileMetadataOptions) => { + assert.strictEqual(options_.userProject, options.userProject); + done(); + }; + bucket.makePrivate(options, done); + }); + + it('should not make files private by default', done => { + bucket.parent.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(); + }; + + bucket.makeAllFilesPublicPrivate_ = () => { + throw new Error('Please, no. I do not want to be called.'); + }; + + bucket.makePrivate(done); + }); + + it('should execute callback with error', done => { + const error = new Error('Error.'); + + bucket.parent.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error); + }; + + bucket.makePrivate((err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('makePublic', () => { + beforeEach(() => { + bucket.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(); + }; + }); + + it('should set ACL, default ACL, and publicize files', done => { + let didSetAcl = false; + let didSetDefaultAcl = false; + let didMakeFilesPublic = false; + + bucket.acl.add = (opts: AddAclOptions) => { + assert.strictEqual(opts.entity, 'allUsers'); + assert.strictEqual(opts.role, 'READER'); + didSetAcl = true; + return Promise.resolve(); + }; + + bucket.acl.default.add = (opts: AddAclOptions) => { + assert.strictEqual(opts.entity, 'allUsers'); + assert.strictEqual(opts.role, 'READER'); + didSetDefaultAcl = true; + return Promise.resolve(); + }; + + bucket.makeAllFilesPublicPrivate_ = ( + opts: MakeAllFilesPublicPrivateOptions, + callback: Function + ) => { + assert.strictEqual(opts.public, true); + assert.strictEqual(opts.force, true); + didMakeFilesPublic = true; + callback(); + }; + + bucket.makePublic( + { + includeFiles: true, + force: true, + }, + (err: Error) => { + assert.ifError(err); + assert(didSetAcl); + assert(didSetDefaultAcl); + assert(didMakeFilesPublic); + done(); + } + ); + }); + + it('should not make files public by default', done => { + bucket.acl.add = () => Promise.resolve(); + bucket.acl.default.add = () => Promise.resolve(); + bucket.makeAllFilesPublicPrivate_ = () => { + throw new Error('Please, no. I do not want to be called.'); + }; + bucket.makePublic(done); + }); + + it('should execute callback with error', done => { + const error = new Error('Error.'); + bucket.acl.add = () => Promise.reject(error); + bucket.makePublic((err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('notification', () => { + it('should throw an error if an id is not provided', () => { + assert.throws(() => { + bucket.notification(), BucketExceptionMessages.SUPPLY_NOTIFICATION_ID; + }); + }); + + it('should return a Notification object', () => { + const fakeId = '123'; + const notification = bucket.notification(fakeId); + + assert(notification instanceof FakeNotification); + assert.strictEqual(notification.bucket, bucket); + assert.strictEqual(notification.id, fakeId); + }); + }); + + describe('removeRetentionPeriod', () => { + it('should call setMetadata correctly', done => { + bucket.setMetadata = ( + metadata: {}, + _optionsOrCallback: {}, + callback: Function + ) => { + assert.deepStrictEqual(metadata, { + retentionPolicy: null, + }); + + Promise.resolve([]).then(resp => callback(null, ...resp)); + }; + + bucket.removeRetentionPeriod(done); + }); + }); + + describe('restore', () => { + it('should pass options to underlying request call', async () => { + bucket.request = function ( + reqOpts: DecorateRequestOptions, + callback_: Function + ) { + assert.strictEqual(this, bucket); + assert.deepStrictEqual(reqOpts, { + method: 'POST', + uri: '/restore', + qs: {generation: 123456789}, + }); + assert.strictEqual(callback_, undefined); + return []; + }; + + await bucket.restore({generation: 123456789}); + }); + }); + + describe('request', () => { + const USER_PROJECT = 'grape-spaceship-123'; + + beforeEach(() => { + bucket.userProject = USER_PROJECT; + }); + + it('should set the userProject if qs is undefined', done => { + FakeServiceObject.prototype.request = (( + reqOpts: DecorateRequestOptions + ) => { + assert.strictEqual(reqOpts.qs.userProject, USER_PROJECT); + done(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }) as any; + + bucket.request({}, assert.ifError); + }); + + it('should set the userProject if field is undefined', done => { + const options = { + qs: { + foo: 'bar', + }, + }; + + FakeServiceObject.prototype.request = (( + reqOpts: DecorateRequestOptions + ) => { + assert.strictEqual(reqOpts.qs.userProject, USER_PROJECT); + assert.strictEqual(reqOpts.qs, options.qs); + done(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }) as any; + + bucket.request(options, assert.ifError); + }); + + it('should not overwrite the userProject', done => { + const fakeUserProject = 'not-grape-spaceship-123'; + const options = { + qs: { + userProject: fakeUserProject, + }, + }; + + FakeServiceObject.prototype.request = (( + reqOpts: DecorateRequestOptions + ) => { + assert.strictEqual(reqOpts.qs.userProject, fakeUserProject); + done(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }) as any; + + bucket.request(options, assert.ifError); + }); + + it('should call ServiceObject#request correctly', done => { + const options = {}; + + Object.assign(FakeServiceObject.prototype, { + request(reqOpts: DecorateRequestOptions, callback: Function) { + assert.strictEqual(this, bucket); + assert.strictEqual(reqOpts, options); + callback(); // done fn + }, + }); + + bucket.request(options, done); + }); + }); + + describe('setLabels', () => { + it('should correctly call setMetadata', done => { + const labels = {}; + bucket.setMetadata = ( + metadata: BucketMetadata, + _callbackOrOptions: {}, + callback: Function + ) => { + assert.strictEqual(metadata.labels, labels); + Promise.resolve([]).then(resp => callback(null, ...resp)); + }; + bucket.setLabels(labels, done); + }); + + it('should accept an options object', done => { + const labels = {}; + const options = {}; + bucket.setMetadata = (metadata: {}, options_: {}) => { + assert.strictEqual(options_, options); + done(); + }; + bucket.setLabels(labels, options, done); + }); + }); + + describe('setRetentionPeriod', () => { + it('should call setMetadata correctly', done => { + const duration = 90000; + + bucket.setMetadata = ( + metadata: {}, + _callbackOrOptions: {}, + callback: Function + ) => { + assert.deepStrictEqual(metadata, { + retentionPolicy: { + retentionPeriod: `${duration}`, + }, + }); + + Promise.resolve([]).then(resp => callback(null, ...resp)); + }; + + bucket.setRetentionPeriod(duration, done); + }); + }); + + describe('setCorsConfiguration', () => { + it('should call setMetadata correctly', done => { + const corsConfiguration = [{maxAgeSeconds: 3600}]; + + bucket.setMetadata = ( + metadata: {}, + _callbackOrOptions: {}, + callback: Function + ) => { + assert.deepStrictEqual(metadata, { + cors: corsConfiguration, + }); + + return Promise.resolve([]).then(resp => callback(null, ...resp)); + }; + + bucket.setCorsConfiguration(corsConfiguration, done); + }); + }); + + describe('setStorageClass', () => { + const STORAGE_CLASS = 'NEW_STORAGE_CLASS'; + const OPTIONS = {}; + const CALLBACK = util.noop; + + it('should convert camelCase to snake_case', done => { + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.strictEqual(metadata.storageClass, 'CAMEL_CASE'); + done(); + }; + + bucket.setStorageClass('camelCase', OPTIONS, CALLBACK); + }); + + it('should convert hyphenate to snake_case', done => { + bucket.setMetadata = (metadata: BucketMetadata) => { + assert.strictEqual(metadata.storageClass, 'HYPHENATED_CLASS'); + done(); + }; + + bucket.setStorageClass('hyphenated-class', OPTIONS, CALLBACK); + }); + + it('should call setMetadata correctly', () => { + bucket.setMetadata = ( + metadata: BucketMetadata, + options: {}, + callback: Function + ) => { + assert.deepStrictEqual(metadata, {storageClass: STORAGE_CLASS}); + assert.strictEqual(options, OPTIONS); + Promise.resolve([]).then(resp => callback(null, ...resp)); + }; + + bucket.setStorageClass(STORAGE_CLASS, OPTIONS, CALLBACK); + }); + }); + + describe('setUserProject', () => { + const USER_PROJECT = 'grape-spaceship-123'; + + it('should set the userProject property', () => { + bucket.setUserProject(USER_PROJECT); + assert.strictEqual(bucket.userProject, USER_PROJECT); + }); + + it('should set the userProject on the global request options', () => { + const methods = [ + 'create', + 'delete', + 'exists', + 'get', + 'getMetadata', + 'setMetadata', + ]; + methods.forEach(method => { + assert.strictEqual( + bucket.methods[method].reqOpts.qs.userProject, + undefined + ); + }); + bucket.setUserProject(USER_PROJECT); + methods.forEach(method => { + assert.strictEqual( + bucket.methods[method].reqOpts.qs.userProject, + USER_PROJECT + ); + }); + }); + }); + + describe('upload', () => { + const basename = 'testfile.json'; + const filepath = path.join( + getDirName(), + '../../../test/testdata/' + basename + ); + const nonExistentFilePath = path.join( + getDirName(), + '../../../test/testdata/', + 'non-existent-file' + ); + const metadata = { + metadata: { + a: 'b', + c: 'd', + }, + }; + + beforeEach(() => { + bucket.file = (name: string, metadata: FileMetadata) => { + return new FakeFile(bucket, name, metadata); + }; + }); + + it('should return early in snippet sandbox', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (global as any)['GCLOUD_SANDBOX_ENV'] = true; + const returnValue = bucket.upload(filepath, assert.ifError); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (global as any)['GCLOUD_SANDBOX_ENV']; + assert.strictEqual(returnValue, undefined); + }); + + it('should accept a path & cb', done => { + bucket.upload(filepath, (err: Error, file: File) => { + assert.ifError(err); + assert.strictEqual(file.bucket.name, bucket.name); + assert.strictEqual(file.name, basename); + done(); + }); + }); + + it('should accept a path, metadata, & cb', done => { + const options = { + metadata, + encryptionKey: 'key', + kmsKeyName: 'kms-key-name', + }; + bucket.upload(filepath, options, (err: Error, file: FakeFile) => { + assert.ifError(err); + assert.strictEqual(file.bucket.name, bucket.name); + assert.deepStrictEqual(file.metadata, metadata); + assert.strictEqual(file.options.encryptionKey, options.encryptionKey); + assert.strictEqual(file.options.kmsKeyName, options.kmsKeyName); + done(); + }); + }); + + it('should accept a path, a string dest, & cb', done => { + const newFileName = 'new-file-name.png'; + const options = { + destination: newFileName, + encryptionKey: 'key', + kmsKeyName: 'kms-key-name', + }; + bucket.upload(filepath, options, (err: Error, file: FakeFile) => { + assert.ifError(err); + assert.strictEqual(file.bucket.name, bucket.name); + assert.strictEqual(file.name, newFileName); + assert.strictEqual(file.options.encryptionKey, options.encryptionKey); + assert.strictEqual(file.options.kmsKeyName, options.kmsKeyName); + done(); + }); + }); + + it('should accept a path, a string dest, metadata, & cb', done => { + const newFileName = 'new-file-name.png'; + const options = { + destination: newFileName, + metadata, + encryptionKey: 'key', + kmsKeyName: 'kms-key-name', + }; + bucket.upload(filepath, options, (err: Error, file: FakeFile) => { + assert.ifError(err); + assert.strictEqual(file.bucket.name, bucket.name); + assert.strictEqual(file.name, newFileName); + assert.deepStrictEqual(file.metadata, metadata); + assert.strictEqual(file.options.encryptionKey, options.encryptionKey); + assert.strictEqual(file.options.kmsKeyName, options.kmsKeyName); + done(); + }); + }); + + it('should accept a path, a File dest, & cb', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + fakeFile.isSameFile = () => { + return true; + }; + const options = {destination: fakeFile}; + bucket.upload(filepath, options, (err: Error, file: FakeFile) => { + assert.ifError(err); + assert(file.isSameFile()); + done(); + }); + }); + + it('should accept a path, a File dest, metadata, & cb', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + fakeFile.isSameFile = () => { + return true; + }; + const options = {destination: fakeFile, metadata}; + bucket.upload(filepath, options, (err: Error, file: FakeFile) => { + assert.ifError(err); + assert(file.isSameFile()); + assert.deepStrictEqual(file.metadata, metadata); + done(); + }); + }); + + describe('resumable uploads', () => { + class DelayedStream500Error extends Transform { + retryCount: number; + constructor(retryCount: number) { + super(); + this.retryCount = retryCount; + } + _transform(chunk: string | Buffer, _encoding: string, done: Function) { + this.push(chunk); + setTimeout(() => { + if (this.retryCount === 1) { + done(new HTTPError('first error', 500)); + } else { + done(); + } + }, 5); + } + } + + beforeEach(() => { + fsStatOverride = (path: string, callback: Function) => { + callback(null, {size: 1}); // Small size to guarantee simple upload + }; + }); + + it('should respect setting a resumable upload to false', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile, resumable: false}; + fakeFile.createWriteStream = (options_: CreateWriteStreamOptions) => { + const ws = new stream.Writable(); + ws.write = () => true; + setImmediate(() => { + assert.strictEqual(options_.resumable, options.resumable); + done(); + }); + return ws; + }; + bucket.upload(filepath, options, assert.ifError); + }); + + it('should not retry a nonretryable error code', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile, resumable: true}; + let retryCount = 0; + fakeFile.createWriteStream = (options_: CreateWriteStreamOptions) => { + class DelayedStream403Error extends Transform { + _transform( + chunk: string | Buffer, + _encoding: string, + done: Function + ) { + this.push(chunk); + setTimeout(() => { + retryCount++; + if (retryCount === 1) { + done(new HTTPError('first error', 403)); + } else { + done(); + } + }, 5); + } + } + setImmediate(() => { + assert.strictEqual(options_.resumable, true); + retryCount++; + done(); + }); + return new DelayedStream403Error(); + }; + + bucket.upload(filepath, options, (err: Error) => { + assert.strictEqual(err.message, 'first error'); + assert.ok(retryCount === 2); + done(); + }); + }); + + it('resumable upload should retry', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile, resumable: true}; + let retryCount = 0; + fakeFile.createWriteStream = (options_: CreateWriteStreamOptions) => { + setImmediate(() => { + assert.strictEqual(options_.resumable, true); + retryCount++; + done(); + }); + return new DelayedStream500Error(retryCount); + }; + bucket.upload(filepath, options, (err: Error) => { + assert.strictEqual(err.message, 'first error'); + assert.ok(retryCount === 1); + done(); + }); + }); + }); + + describe('multipart uploads', () => { + class DelayedStream500Error extends Transform { + retryCount: number; + constructor(retryCount: number) { + super(); + this.retryCount = retryCount; + } + _transform(chunk: string | Buffer, _encoding: string, done: Function) { + this.push(chunk); + setTimeout(() => { + if (this.retryCount === 1) { + done(new HTTPError('first error', 500)); + } else { + done(); + } + }, 5); + } + } + + beforeEach(() => { + fsStatOverride = (path: string, callback: Function) => { + callback(null, {size: 1}); // Small size to guarantee simple upload + }; + }); + + it('should save with no errors', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile, resumable: false}; + fakeFile.createWriteStream = (options_: CreateWriteStreamOptions) => { + class DelayedStreamNoError extends Transform { + _transform( + chunk: string | Buffer, + _encoding: string, + done: Function + ) { + this.push(chunk); + setTimeout(() => { + done(); + }, 5); + } + } + assert.strictEqual(options_.resumable, false); + return new DelayedStreamNoError(); + }; + bucket.upload(filepath, options, (err: Error) => { + assert.ifError(err); + done(); + }); + }); + + it('should retry on first failure', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile, resumable: false}; + let retryCount = 0; + fakeFile.createWriteStream = (options_: CreateWriteStreamOptions) => { + setImmediate(() => { + assert.strictEqual(options_.resumable, false); + retryCount++; + done(); + }); + return new DelayedStream500Error(retryCount); + }; + bucket.upload(filepath, options, (err: Error, file: FakeFile) => { + assert.ifError(err); + assert(file.isSameFile()); + assert.deepStrictEqual(file.metadata, metadata); + assert.ok(retryCount === 2); + done(); + }); + }); + + it('should not retry if nonretryable error code', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile, resumable: false}; + let retryCount = 0; + fakeFile.createWriteStream = (options_: CreateWriteStreamOptions) => { + class DelayedStream403Error extends Transform { + _transform( + chunk: string | Buffer, + _encoding: string, + done: Function + ) { + this.push(chunk); + setTimeout(() => { + retryCount++; + if (retryCount === 1) { + done(new HTTPError('first error', 403)); + } else { + done(); + } + }, 5); + } + } + setImmediate(() => { + assert.strictEqual(options_.resumable, false); + retryCount++; + done(); + }); + return new DelayedStream403Error(); + }; + + bucket.upload(filepath, options, (err: Error) => { + assert.strictEqual(err.message, 'first error'); + assert.ok(retryCount === 2); + done(); + }); + }); + + it('non-multipart upload should not retry', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile, resumable: true}; + let retryCount = 0; + fakeFile.createWriteStream = (options_: CreateWriteStreamOptions) => { + setImmediate(() => { + assert.strictEqual(options_.resumable, true); + retryCount++; + done(); + }); + return new DelayedStream500Error(retryCount); + }; + bucket.upload(filepath, options, (err: Error) => { + assert.strictEqual(err.message, 'first error'); + assert.ok(retryCount === 1); + done(); + }); + }); + }); + + it('should allow overriding content type', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const metadata = {contentType: 'made-up-content-type'}; + const options = {destination: fakeFile, metadata}; + fakeFile.createWriteStream = (options: CreateWriteStreamOptions) => { + const ws = new stream.Writable(); + ws.write = () => true; + setImmediate(() => { + assert.strictEqual( + options!.metadata!.contentType, + metadata.contentType + ); + done(); + }); + return ws; + }; + bucket.upload(filepath, options, assert.ifError); + }); + + it('should pass provided options to createWriteStream', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = { + destination: fakeFile, + a: 'b', + c: 'd', + }; + fakeFile.createWriteStream = (options_: {a: {}; c: {}}) => { + const ws = new stream.Writable(); + ws.write = () => true; + setImmediate(() => { + assert.strictEqual(options_.a, options.a); + assert.strictEqual(options_.c, options.c); + done(); + }); + return ws; + }; + bucket.upload(filepath, options, assert.ifError); + }); + + it('should execute callback on error', done => { + const error = new Error('Error.'); + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile}; + fakeFile.createWriteStream = () => { + const ws = new stream.PassThrough(); + setImmediate(() => { + ws.destroy(error); + }); + return ws; + }; + bucket.upload(filepath, options, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should return file and metadata', done => { + const fakeFile = new FakeFile(bucket, 'file-name'); + const options = {destination: fakeFile}; + const metadata = {}; + + fakeFile.createWriteStream = () => { + const ws = new stream.PassThrough(); + setImmediate(() => { + fakeFile.metadata = metadata; + ws.end(); + }); + return ws; + }; + + bucket.upload( + filepath, + options, + (err: Error, file: File, apiResponse: {}) => { + assert.ifError(err); + assert.strictEqual(file, fakeFile); + assert.strictEqual(apiResponse, metadata); + done(); + } + ); + }); + + it('should capture and throw on non-existent files', done => { + bucket.upload(nonExistentFilePath, (err: Error) => { + assert(err); + assert(err.message.includes('ENOENT')); + done(); + }); + }); + }); + + describe('makeAllFilesPublicPrivate_', () => { + it('should get all files from the bucket', done => { + const options = {}; + bucket.getFiles = (options_: {}) => { + assert.strictEqual(options_, options); + return Promise.resolve([[]]); + }; + bucket.makeAllFilesPublicPrivate_(options, done); + }); + + it('should process 10 files at a time', done => { + pLimitOverride = (limit: number) => { + assert.strictEqual(limit, 10); + setImmediate(done); + return () => {}; + }; + + bucket.getFiles = () => Promise.resolve([[]]); + bucket.makeAllFilesPublicPrivate_({}, assert.ifError); + }); + + it('should make files public', done => { + let timesCalled = 0; + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.makePublic = () => { + timesCalled++; + return Promise.resolve(); + }; + return file; + }); + bucket.getFiles = () => Promise.resolve([files]); + bucket.makeAllFilesPublicPrivate_({public: true}, (err: Error) => { + assert.ifError(err); + assert.strictEqual(timesCalled, files.length); + done(); + }); + }); + + it('should make files private', done => { + const options = { + private: true, + }; + let timesCalled = 0; + + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.makePrivate = () => { + timesCalled++; + return Promise.resolve(); + }; + return file; + }); + + bucket.getFiles = () => Promise.resolve([files]); + bucket.makeAllFilesPublicPrivate_(options, (err: Error) => { + assert.ifError(err); + assert.strictEqual(timesCalled, files.length); + done(); + }); + }); + + it('should execute callback with error from getting files', done => { + const error = new Error('Error.'); + bucket.getFiles = () => Promise.reject(error); + bucket.makeAllFilesPublicPrivate_({}, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should execute callback with error from changing file', done => { + const error = new Error('Error.'); + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.makePublic = () => Promise.reject(error); + return file; + }); + bucket.getFiles = () => Promise.resolve([files]); + bucket.makeAllFilesPublicPrivate_({public: true}, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should execute callback with queued errors', done => { + const error = new Error('Error.'); + const files = [bucket.file('1'), bucket.file('2')].map(file => { + file.makePublic = () => Promise.reject(error); + return file; + }); + bucket.getFiles = () => Promise.resolve([files]); + bucket.makeAllFilesPublicPrivate_( + { + public: true, + force: true, + }, + (errs: Error[]) => { + assert.deepStrictEqual(errs, [error, error]); + done(); + } + ); + }); + + it('should execute callback with files changed', done => { + const error = new Error('Error.'); + const successFiles = [bucket.file('1'), bucket.file('2')].map(file => { + file.makePublic = () => Promise.resolve(); + return file; + }); + const errorFiles = [bucket.file('3'), bucket.file('4')].map(file => { + file.makePublic = () => Promise.reject(error); + return file; + }); + + bucket.getFiles = () => { + const files = successFiles.concat(errorFiles); + return Promise.resolve([files]); + }; + + bucket.makeAllFilesPublicPrivate_( + { + public: true, + force: true, + }, + (errs: Error[], files: File[]) => { + assert.deepStrictEqual(errs, [error, error]); + assert.deepStrictEqual(files, successFiles); + done(); + } + ); + }); + }); + describe('disableAutoRetryConditionallyIdempotent_', () => { + beforeEach(() => { + bucket.storage.retryOptions.autoRetry = true; + STORAGE.retryOptions.idempotencyStrategy = + IdempotencyStrategy.RetryConditional; + }); + + it('should set autoRetry to false when ifMetagenerationMatch is undefined (setMetadata)', done => { + bucket.disableAutoRetryConditionallyIdempotent_( + bucket.methods.setMetadata, + AvailableServiceObjectMethods.setMetadata + ); + assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); + done(); + }); + + it('should set autoRetry to false when ifMetagenerationMatch is undefined (delete)', done => { + bucket.disableAutoRetryConditionallyIdempotent_( + bucket.methods.delete, + AvailableServiceObjectMethods.delete + ); + assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); + done(); + }); + + it('should set autoRetry to false when IdempotencyStrategy is set to RetryNever', done => { + STORAGE.retryOptions.idempotencyStrategy = IdempotencyStrategy.RetryNever; + bucket = new Bucket(STORAGE, BUCKET_NAME, { + preconditionOpts: { + ifMetagenerationMatch: 100, + }, + }); + bucket.disableAutoRetryConditionallyIdempotent_( + bucket.methods.delete, + AvailableServiceObjectMethods.delete + ); + assert.strictEqual(bucket.storage.retryOptions.autoRetry, false); + done(); + }); + + it('autoRetry should remain true when ifMetagenerationMatch is not undefined', done => { + bucket = new Bucket(STORAGE, BUCKET_NAME, { + preconditionOpts: { + ifMetagenerationMatch: 100, + }, + }); + bucket.disableAutoRetryConditionallyIdempotent_( + bucket.methods.delete, + AvailableServiceObjectMethods.delete + ); + assert.strictEqual(bucket.storage.retryOptions.autoRetry, true); + done(); + }); + }); +}); diff --git a/handwritten/storage/test/channel.ts b/handwritten/storage/test/channel.ts new file mode 100644 index 00000000000..e70272f2045 --- /dev/null +++ b/handwritten/storage/test/channel.ts @@ -0,0 +1,139 @@ +// Copyright 2019 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. + +/*! + * @module storage/channel + */ + +import { + BaseMetadata, + DecorateRequestOptions, + ServiceObject, + ServiceObjectConfig, +} from '../src/nodejs-common/index.js'; +import assert from 'assert'; +import {describe, it, before, beforeEach} from 'mocha'; +import proxyquire from 'proxyquire'; + +let promisified = false; +const fakePromisify = { + promisifyAll(Class: Function) { + if (Class.name === 'Channel') { + promisified = true; + } + }, +}; + +class FakeServiceObject extends ServiceObject { + calledWith_: IArguments; + constructor(config: ServiceObjectConfig) { + super(config); + // eslint-disable-next-line prefer-rest-params + this.calledWith_ = arguments; + } +} + +describe('Channel', () => { + const STORAGE = {}; + const ID = 'channel-id'; + const RESOURCE_ID = 'resource-id'; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Channel: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let channel: any; + + before(() => { + Channel = proxyquire('../src/channel.js', { + '@google-cloud/promisify': fakePromisify, + './nodejs-common': { + ServiceObject: FakeServiceObject, + }, + }).Channel; + }); + + beforeEach(() => { + channel = new Channel(STORAGE, ID, RESOURCE_ID); + }); + + describe('initialization', () => { + it('should inherit from ServiceObject', () => { + // Using assert.strictEqual instead of assert to prevent + // coercing of types. + assert.strictEqual(channel instanceof ServiceObject, true); + + const calledWith = channel.calledWith_[0]; + + assert.strictEqual(calledWith.parent, STORAGE); + assert.strictEqual(calledWith.baseUrl, '/channels'); + assert.strictEqual(calledWith.id, ''); + assert.deepStrictEqual(calledWith.methods, {}); + }); + + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should set the default metadata', () => { + assert.deepStrictEqual(channel.metadata, { + id: ID, + resourceId: RESOURCE_ID, + }); + }); + }); + + describe('stop', () => { + it('should make the correct request', done => { + channel.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.method, 'POST'); + assert.strictEqual(reqOpts.uri, '/stop'); + assert.strictEqual(reqOpts.json, channel.metadata); + + done(); + }; + + channel.stop(assert.ifError); + }); + + it('should execute callback with error & API response', done => { + const error = {}; + const apiResponse = {}; + + channel.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error, apiResponse); + }; + + channel.stop((err: Error, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(apiResponse_, apiResponse); + done(); + }); + }); + + it('should not require a callback', done => { + channel.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.doesNotThrow(() => callback()); + done(); + }; + + channel.stop(); + }); + }); +}); diff --git a/handwritten/storage/test/crc32c.ts b/handwritten/storage/test/crc32c.ts new file mode 100644 index 00000000000..4a14af96bbc --- /dev/null +++ b/handwritten/storage/test/crc32c.ts @@ -0,0 +1,529 @@ +// Copyright 2022 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 { + CRC32C, + CRC32CValidator, + CRC32C_EXTENSIONS, + CRC32C_EXTENSION_TABLE, + CRC32C_EXCEPTION_MESSAGES, +} from '../src/index.js'; +import assert from 'assert'; +import {join} from 'path'; +import {tmpdir} from 'os'; +import * as fs from 'fs'; + +const KNOWN_INPUT_TO_CRC32C = { + /** empty string (i.e. nothing to 'update') */ + '': 'AAAAAA==', + /** known case #1 - validated from actual GCS object upload + metadata retrieval */ + data: 'rth90Q==', + /** known case #2 - validated from actual GCS object upload + metadata retrieval */ + 'some text\n': 'DkjKuA==', + /** arbitrary large string */ + ['a'.repeat(2 ** 16)]: 'TpXtPw==', +} as const; + +describe('CRC32C', () => { + describe('instance', () => { + describe('#constructor', () => { + it('should initial value to `0`', () => { + const crc32c = new CRC32C(); + + assert.equal(crc32c.valueOf(), 0); + }); + + it('should accept an `initialValue`', () => { + const initialValue = 123; + + const crc32c = new CRC32C(initialValue); + + assert.equal(crc32c.valueOf(), initialValue); + }); + }); + + describe('#update', () => { + it('should produce the correct calculation given the input (single buffer)', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + + const buffer = Buffer.from(input); + + crc32c.update(buffer); + + const result = crc32c.toString(); + + assert.equal( + result, + expected, + `Expected '${input}' to produce \`${expected}\` - not \`${result}\`` + ); + } + }); + + it('should produce the correct calculation given the input (multiple buffers)', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + + for (const char of input) { + const buffer = Buffer.from(char); + + crc32c.update(buffer); + } + + const result = crc32c.toString(); + + assert.equal( + result, + expected, + `Expected '${input}' to produce \`${expected}\` - not \`${result}\`` + ); + } + }); + + it('should not mutate a provided buffer', () => { + const crc32c = new CRC32C(); + + const value = 'abc'; + const buffer = Buffer.from(value); + + crc32c.update(buffer); + + assert.equal(buffer.toString(), value); + }); + }); + + describe('#validate', () => { + it('should validate a provided `number`', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + const expectedNumber = Buffer.from(expected, 'base64').readInt32BE(); + + const wrongNumber = expectedNumber + 1; + + crc32c.update(Buffer.from(input)); + + assert.equal(crc32c.validate(wrongNumber), false); + assert.equal(crc32c.validate(expectedNumber), true); + } + }); + + it('should validate a provided `string`', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + const expectedString = expected; + + // Want to test against a string generated in a valid way + const crc32cForIncorrectString = new CRC32C(); + const wrongStringInput = Buffer.from(input + ' '); + crc32cForIncorrectString.update(wrongStringInput); + const wrongString = crc32cForIncorrectString.toString(); + + crc32c.update(Buffer.from(input)); + + assert.equal(crc32c.validate(wrongString), false); + assert.equal(crc32c.validate(expectedString), true); + } + }); + + it('should validate a provided `Buffer`', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + const expectedBuffer = Buffer.from(expected, 'base64'); + + // Want to test against a `Buffer` generated in a valid way + const crc32cForIncorrectString = new CRC32C(); + const wrongBufferInput = Buffer.from(input + ' '); + crc32cForIncorrectString.update(wrongBufferInput); + const wrongBuffer = crc32cForIncorrectString.toBuffer(); + + crc32c.update(Buffer.from(input)); + + assert.equal(crc32c.validate(wrongBuffer), false); + assert.equal(crc32c.validate(expectedBuffer), true); + } + }); + + it('should validate a provided `CRC32C`', () => { + for (const [input] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + const crc32cExpected = new CRC32C(); + const wrongCRC32C = new CRC32C(); + + const wrongBufferInput = Buffer.from(input + ' '); + + crc32c.update(Buffer.from(input)); + crc32cExpected.update(Buffer.from(input)); + wrongCRC32C.update(wrongBufferInput); + + assert.equal(crc32c.validate(wrongCRC32C), false); + assert.equal(crc32c.validate(crc32cExpected), true); + } + }); + + it('should validate a provided generic `CRC32CValidator`', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + const crc32cExpectedValidator: CRC32CValidator = { + toString: () => expected, + update: () => {}, + validate: () => false, + }; + const wrongCRC32CValidator: CRC32CValidator = { + toString: () => { + const crc32c = new CRC32C(); + // Want to test against a `Buffer` generated in a valid way + const wrongBufferInput = Buffer.from(input + ' '); + + crc32c.update(wrongBufferInput); + + return crc32c.toString(); + }, + update: () => {}, + validate: () => false, + }; + + crc32c.update(Buffer.from(input)); + + assert.equal(crc32c.validate(wrongCRC32CValidator), false); + assert.equal(crc32c.validate(crc32cExpectedValidator), true); + } + }); + }); + + describe('#toBuffer', () => { + it('should return a valid 4-byte buffer', () => { + // At least one of our inputs should produce a negative 32-bit number - to prove we're not using unsigned integers + // This ensures the internally we're accurately handling unsigned integers + let atLeastOneWasSigned = false; + + for (const [input] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + crc32c.update(Buffer.from(input)); + + const value = crc32c.valueOf(); + + if (value < 0) { + // this is a negative number, thus is definitely signed + atLeastOneWasSigned = true; + } + + const buffer = Buffer.alloc(4); + buffer.writeInt32BE(value); + + assert.equal(crc32c.toBuffer().byteLength, 4); + assert.equal(Buffer.compare(crc32c.toBuffer(), buffer), 0); + } + + assert(atLeastOneWasSigned); + }); + }); + + describe('#toJSON', () => { + it('should return the expected JSON', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + crc32c.update(Buffer.from(input)); + + const stringified = JSON.stringify({crc32c}); + + assert.equal(crc32c.toJSON(), expected); + assert.deepStrictEqual(JSON.parse(stringified), {crc32c: expected}); + } + }); + }); + + describe('#toString', () => { + it('should return the expected string', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + crc32c.update(Buffer.from(input)); + + const stringified = `${crc32c}`; + + assert.equal(crc32c.toString(), expected); + assert.equal(stringified, expected); + } + }); + }); + + describe('#valueOf', () => { + it('should return the expected string', () => { + for (const [input, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = new CRC32C(); + crc32c.update(Buffer.from(input)); + + const expectedNumber = Buffer.from(expected, 'base64').readInt32BE(); + + assert.equal(crc32c.valueOf(), expectedNumber); + assert.equal(+crc32c, expectedNumber); + + // All `CRC32C` values should be safe integers + assert(Number.isSafeInteger(+crc32c)); + } + }); + }); + }); + + describe('static', () => { + describe('.CRC32C_EXTENSIONS', () => { + it('should be the same as the exported object', () => { + assert.equal(CRC32C.CRC32C_EXTENSIONS, CRC32C_EXTENSIONS); + }); + }); + + describe('.CRC32C_EXTENSION_TABLE', () => { + it('should be the same as the exported object', () => { + assert.equal(CRC32C.CRC32C_EXTENSION_TABLE, CRC32C_EXTENSION_TABLE); + }); + }); + + describe('.from', () => { + describe('`ArrayBuffer`', () => { + it('should generate from `ArrayBuffer`', () => { + for (const [, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const value = Buffer.from(expected, 'base64').readInt32BE(); + + const arrayBufferView = new Int32Array(1); + const dataView = new DataView(arrayBufferView.buffer); + dataView.setInt32(0, value, false); + + // Pass an `ArrayBuffer` + const crc32c = CRC32C.from(arrayBufferView.buffer); + + assert.equal(crc32c.valueOf(), dataView.getInt32(0, false)); + + // should not update source object + crc32c.update(Buffer.from(' ')); + + assert.notEqual(crc32c.valueOf(), dataView.getInt32(0, false)); + } + }); + + it('should raise a `RangeError` on invalid buffers', () => { + for (let i = 0; i < 8; i++) { + // `Int32Array` with length of 1 are valid + if (i === 1) continue; + + const arrayBufferView = new Int32Array(i); + + const errorMessage = + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(i * 4); + const expectedError = RangeError(errorMessage); + + assert.throws( + () => CRC32C.from(arrayBufferView.buffer), + expectedError + ); + } + }); + }); + + describe('`ArrayBufferView`', () => { + it('should generate from `ArrayBufferView`', () => { + for (const [, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const value = Buffer.from(expected, 'base64').readInt32BE(); + + const arrayBufferView = new Int32Array(1); + const dataView = new DataView(arrayBufferView.buffer); + dataView.setInt32(0, value, false); + + // Pass an `ArrayBufferView` + const crc32c = CRC32C.from(arrayBufferView); + + assert.equal(crc32c.valueOf(), dataView.getInt32(0, false)); + + // should not update source object + crc32c.update(Buffer.from(' ')); + + assert.notEqual(crc32c.valueOf(), dataView.getInt32(0, false)); + } + }); + + it('should raise a `RangeError` on invalid buffers', () => { + for (let i = 0; i < 8; i++) { + // `Int32Array` with length of 1 are valid + if (i === 1) continue; + + const arrayBufferView = new Int32Array(i); + + const errorMessage = + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(i * 4); + const expectedError = RangeError(errorMessage); + + assert.throws(() => CRC32C.from(arrayBufferView), expectedError); + } + }); + }); + + describe('`Buffer`', () => { + it('should generate from `Buffer`', () => { + for (const [, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const buffer = Buffer.from(expected, 'base64'); + + const crc32c = CRC32C.from(buffer); + + assert.equal(Buffer.compare(crc32c.toBuffer(), buffer), 0); + + // should not update source object + crc32c.update(Buffer.from(' ')); + + assert.notEqual(Buffer.compare(crc32c.toBuffer(), buffer), 0); + } + }); + + it('should raise a `RangeError` on invalid buffers', () => { + for (let i = 0; i < 8; i++) { + // Buffers with length of 4 are valid + if (i === 4) continue; + + const buffer = Buffer.alloc(i); + + const errorMessage = + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BUFFER_LENGTH(i); + const expectedError = RangeError(errorMessage); + + assert.throws(() => CRC32C.from(buffer), expectedError); + } + }); + }); + + describe('`CRC32C`', () => { + it('should generate from `CRC32C`', () => { + for (const [, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const baseCRC32C = CRC32C.from(expected); + const crc32c = CRC32C.from(baseCRC32C); + + assert.equal(crc32c.valueOf(), baseCRC32C.valueOf()); + + // should not update source object + crc32c.update(Buffer.from(' ')); + + assert.notEqual(crc32c.valueOf(), baseCRC32C.valueOf()); + } + }); + }); + + describe('`CRC32CValidator`', () => { + it('should generate from `CRC32CValidator`', () => { + for (const [, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const baseCRC32C: CRC32CValidator = { + toString: () => expected, + update: () => {}, + validate: () => false, + }; + const crc32c = CRC32C.from(baseCRC32C); + + assert.equal(crc32c.toString(), baseCRC32C.toString()); + + // should not update source object + crc32c.update(Buffer.from(' ')); + + assert.notEqual(crc32c.toString(), baseCRC32C.toString()); + } + }); + }); + + describe('`string`', () => { + it('should generate from base64-encoded data', () => { + for (const [, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const crc32c = CRC32C.from(expected); + + assert.equal(crc32c.toString(), expected); + } + }); + + it('should raise a `RangeError` on invalid strings', () => { + for (let i = 0; i < 8; i++) { + // Buffers with length of 4 are valid + if (i === 4) continue; + + const string = Buffer.alloc(i).toString('base64'); + + const errorMessage = + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_BASE64_RANGE(i); + const expectedError = RangeError(errorMessage); + + assert.throws(() => CRC32C.from(string), expectedError); + } + }); + }); + + describe('`number`', () => { + it('should generate from `number`', () => { + // At least one of our inputs should produce a negative 32-bit number - to prove we're not using unsigned integers + // This ensures the internally we're accurately handling unsigned integers + let atLeastOneWasSigned = false; + + for (const [, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + const number = Buffer.from(expected, 'base64').readInt32BE(); + + const crc32c = CRC32C.from(number); + + if (number < 0) { + // this is a negative number, thus is definitely signed + atLeastOneWasSigned = true; + } + + assert.equal(crc32c.valueOf(), number); + } + + assert(atLeastOneWasSigned); + }); + + it('should raise a `RangeError` on invalid integers', () => { + const INVALID_SET = [ + NaN, // not a safe number + 0.5, // not an integer + 2 ** 32 + 1, // too high - out of valid range + -(2 ** 32) - 1, // too low - out of valid range + ]; + + for (const number of INVALID_SET) { + const errorMessage = + CRC32C_EXCEPTION_MESSAGES.INVALID_INIT_INTEGER(number); + const expectedError = RangeError(errorMessage); + + assert.throws(() => CRC32C.from(number), expectedError); + } + }); + }); + }); + + describe('.fromFile', () => { + let tempFilePath: string; + + beforeEach(async () => { + tempFilePath = join(tmpdir(), 'test.crc32c.fromFile'); + }); + + after(async () => { + try { + await fs.promises.unlink(tempFilePath); + } catch (e) { + // errors are fine + } + }); + + it('should generate a valid `crc32c` via a file path', async () => { + for (const [key, expected] of Object.entries(KNOWN_INPUT_TO_CRC32C)) { + await fs.promises.writeFile(tempFilePath, key); + + const crc32c = await CRC32C.fromFile(tempFilePath); + assert.equal(crc32c.toString(), expected); + } + }); + }); + }); +}); diff --git a/handwritten/storage/test/file.ts b/handwritten/storage/test/file.ts new file mode 100644 index 00000000000..14b2070aa10 --- /dev/null +++ b/handwritten/storage/test/file.ts @@ -0,0 +1,5661 @@ +// Copyright 2019 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 { + ApiError, + BodyResponseCallback, + DecorateRequestOptions, + MetadataCallback, + ServiceObject, + ServiceObjectConfig, + util, +} from '../src/nodejs-common/index.js'; +import {describe, it, before, beforeEach, afterEach} from 'mocha'; +import {PromisifyAllOptions} from '@google-cloud/promisify'; +import { + Readable, + PassThrough, + Stream, + Duplex, + Transform, + pipeline, +} from 'stream'; +import assert from 'assert'; +import * as crypto from 'crypto'; +import duplexify from 'duplexify'; +import * as fs from 'fs'; +import * as path from 'path'; +import proxyquire from 'proxyquire'; +import * as resumableUpload from '../src/resumable-upload.js'; +import * as sinon from 'sinon'; +import * as tmp from 'tmp'; +import * as zlib from 'zlib'; + +import { + Bucket, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + File, + FileOptions, + PolicyDocument, + SetFileMetadataOptions, + GetSignedUrlConfig, + GenerateSignedPostPolicyV2Options, + CRC32C, +} from '../src/index.js'; +import { + SignedPostPolicyV4Output, + GenerateSignedPostPolicyV4Options, + STORAGE_POST_POLICY_BASE_URL, + MoveOptions, + FileExceptionMessages, + FileMetadata, +} from '../src/file.js'; +import {ExceptionMessages, IdempotencyStrategy} from '../src/storage.js'; +import {formatAsUTCISO} from '../src/util.js'; +import { + BaseMetadata, + SetMetadataOptions, +} from '../src/nodejs-common/service-object.js'; +import {GCCL_GCS_CMD_KEY} from '../src/nodejs-common/util.js'; + +class HTTPError extends Error { + code: number; + constructor(message: string, code: number) { + super(message); + this.code = code; + } +} + +let promisified = false; +let makeWritableStreamOverride: Function | null; +let handleRespOverride: Function | null; +const fakeUtil = Object.assign({}, util, { + handleResp(...args: Array<{}>) { + (handleRespOverride || util.handleResp)(...args); + }, + makeWritableStream(...args: Array<{}>) { + (makeWritableStreamOverride || util.makeWritableStream)(...args); + }, + makeRequest( + reqOpts: DecorateRequestOptions, + config: object, + callback: BodyResponseCallback + ) { + callback(null); + }, +}); + +const fakePromisify = { + // tslint:disable-next-line:variable-name + promisifyAll(Class: Function, options: PromisifyAllOptions) { + if (Class.name !== 'File') { + return; + } + + promisified = true; + assert.deepStrictEqual(options.exclude, [ + 'cloudStorageURI', + 'publicUrl', + 'request', + 'save', + 'setEncryptionKey', + 'shouldRetryBasedOnPreconditionAndIdempotencyStrat', + 'getBufferFromReadable', + 'restore', + ]); + }, +}; + +const fsCached = fs; +const fakeFs = {...fsCached}; + +const zlibCached = zlib; +let createGunzipOverride: Function | null; +const fakeZlib = { + ...zlib, + createGunzip(...args: Array<{}>) { + return (createGunzipOverride || zlibCached.createGunzip)(...args); + }, +}; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const osCached = require('os'); +const fakeOs = {...osCached}; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let resumableUploadOverride: any; +function fakeResumableUpload() { + return () => { + return resumableUploadOverride || resumableUpload; + }; +} +Object.assign(fakeResumableUpload, { + createURI( + ...args: [resumableUpload.UploadConfig, resumableUpload.CreateUriCallback] + ) { + let createURI = resumableUpload.createURI; + + if (resumableUploadOverride && resumableUploadOverride.createURI) { + createURI = resumableUploadOverride.createURI; + } + + return createURI(...args); + }, +}); +Object.assign(fakeResumableUpload, { + upload(...args: [resumableUpload.UploadConfig]) { + let upload = resumableUpload.upload; + if (resumableUploadOverride && resumableUploadOverride.upload) { + upload = resumableUploadOverride.upload; + } + return upload(...args); + }, +}); + +class FakeServiceObject extends ServiceObject { + calledWith_: IArguments; + constructor(config: ServiceObjectConfig) { + super(config); + // eslint-disable-next-line prefer-rest-params + this.calledWith_ = arguments; + } +} + +const fakeSigner = { + URLSigner: () => {}, +}; + +describe('File', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let File: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let file: any; + + const FILE_NAME = 'file-name.png'; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let directoryFile: any; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let specialCharsFile: any; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let STORAGE: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let BUCKET: any; + + const DATA = 'test data'; + // crc32c hash of 'test data' + const CRC32C_HASH = 'M3m0yg=='; + // md5 hash of 'test data' + const MD5_HASH = '63M6AMDJ0zbmVpGjerVCkw=='; + // crc32c hash of `zlib.gzipSync(Buffer.from(DATA), {level: 9})` + const GZIPPED_DATA = Buffer.from( + 'H4sIAAAAAAACEytJLS5RSEksSQQAsq4I0wkAAAA=', + 'base64' + ); + //crc32c hash of `GZIPPED_DATA` + const CRC32C_HASH_GZIP = '64jygg=='; + + before(() => { + File = proxyquire('../src/file.js', { + './nodejs-common': { + ServiceObject: FakeServiceObject, + util: fakeUtil, + }, + '@google-cloud/promisify': fakePromisify, + fs: fakeFs, + '../src/resumable-upload': fakeResumableUpload, + os: fakeOs, + './signer': fakeSigner, + zlib: fakeZlib, + }).File; + }); + + beforeEach(() => { + Object.assign(fakeFs, fsCached); + Object.assign(fakeOs, osCached); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + FakeServiceObject.prototype.request = util.noop as any; + + STORAGE = { + createBucket: util.noop, + request: util.noop, + apiEndpoint: 'https://storage.googleapis.com', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeAuthenticatedRequest(req: {}, callback: any) { + if (callback) { + (callback.onAuthenticated || callback)(null, req); + } + }, + bucket(name: string) { + return new Bucket(this, name); + }, + retryOptions: { + autoRetry: true, + maxRetries: 3, + retryDelayMultiplier: 2, + totalTimeout: 600, + maxRetryDelay: 60, + retryableErrorFn: (err: HTTPError) => { + return err?.code === 500; + }, + idempotencyStrategy: IdempotencyStrategy.RetryConditional, + }, + customEndpoint: false, + }; + + BUCKET = new Bucket(STORAGE, 'bucket-name'); + BUCKET.getRequestInterceptors = () => []; + + file = new File(BUCKET, FILE_NAME); + + directoryFile = new File(BUCKET, 'directory/file.jpg'); + directoryFile.request = util.noop; + + specialCharsFile = new File(BUCKET, "special/azAZ!*'()*%/file.jpg"); + specialCharsFile.request = util.noop; + + createGunzipOverride = null; + handleRespOverride = null; + makeWritableStreamOverride = null; + resumableUploadOverride = null; + }); + + describe('initialization', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should assign file name', () => { + assert.strictEqual(file.name, FILE_NAME); + }); + + it('should assign the bucket instance', () => { + assert.strictEqual(file.bucket, BUCKET); + }); + + it('should assign the storage instance', () => { + assert.strictEqual(file.storage, BUCKET.storage); + }); + + it('should set instanceRetryValue to the storage instance retryOptions.autoRetry value', () => { + assert.strictEqual( + file.instanceRetryValue, + STORAGE.retryOptions.autoRetry + ); + }); + + it('should not strip leading slashes', () => { + const file = new File(BUCKET, '/name'); + assert.strictEqual(file.name, '/name'); + }); + + it('should assign KMS key name', () => { + const kmsKeyName = 'kms-key-name'; + const file = new File(BUCKET, '/name', {kmsKeyName}); + assert.strictEqual(file.kmsKeyName, kmsKeyName); + }); + + it('should accept specifying a generation', () => { + const file = new File(BUCKET, 'name', {generation: 2}); + assert.strictEqual(file.generation, 2); + }); + + it('should inherit from ServiceObject', () => { + // Using assert.strictEqual instead of assert to prevent + // coercing of types. + assert.strictEqual(file instanceof ServiceObject, true); + + const calledWith = file.calledWith_[0]; + + assert.strictEqual(calledWith.parent, BUCKET); + assert.strictEqual(calledWith.baseUrl, '/o'); + assert.strictEqual(calledWith.id, encodeURIComponent(FILE_NAME)); + assert.deepStrictEqual(calledWith.methods, { + delete: {reqOpts: {qs: {}}}, + exists: {reqOpts: {qs: {}}}, + get: {reqOpts: {qs: {}}}, + getMetadata: {reqOpts: {qs: {}}}, + setMetadata: {reqOpts: {qs: {}}}, + }); + }); + + it('should set the correct query string with a generation', () => { + const options = {generation: 2}; + const file = new File(BUCKET, 'name', options); + + const calledWith = file.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + delete: {reqOpts: {qs: options}}, + exists: {reqOpts: {qs: options}}, + get: {reqOpts: {qs: options}}, + getMetadata: {reqOpts: {qs: options}}, + setMetadata: {reqOpts: {qs: options}}, + }); + }); + + it('should set the correct query string with a userProject', () => { + const options = {userProject: 'user-project'}; + const file = new File(BUCKET, 'name', options); + + const calledWith = file.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + delete: {reqOpts: {qs: options}}, + exists: {reqOpts: {qs: options}}, + get: {reqOpts: {qs: options}}, + getMetadata: {reqOpts: {qs: options}}, + setMetadata: {reqOpts: {qs: options}}, + }); + }); + + it('should set the correct query string with ifGenerationMatch', () => { + const options = {preconditionOpts: {ifGenerationMatch: 100}}; + const file = new File(BUCKET, 'name', options); + + const calledWith = file.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + delete: {reqOpts: {qs: options.preconditionOpts}}, + exists: {reqOpts: {qs: options.preconditionOpts}}, + get: {reqOpts: {qs: options.preconditionOpts}}, + getMetadata: {reqOpts: {qs: options.preconditionOpts}}, + setMetadata: {reqOpts: {qs: options.preconditionOpts}}, + }); + assert.deepStrictEqual( + file.instancePreconditionOpts, + options.preconditionOpts + ); + }); + + it('should set the correct query string with ifGenerationNotMatch', () => { + const options = {preconditionOpts: {ifGenerationNotMatch: 100}}; + const file = new File(BUCKET, 'name', options); + + const calledWith = file.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + delete: {reqOpts: {qs: options.preconditionOpts}}, + exists: {reqOpts: {qs: options.preconditionOpts}}, + get: {reqOpts: {qs: options.preconditionOpts}}, + getMetadata: {reqOpts: {qs: options.preconditionOpts}}, + setMetadata: {reqOpts: {qs: options.preconditionOpts}}, + }); + assert.deepStrictEqual( + file.instancePreconditionOpts, + options.preconditionOpts + ); + }); + + it('should set the correct query string with ifMetagenerationMatch', () => { + const options = {preconditionOpts: {ifMetagenerationMatch: 100}}; + const file = new File(BUCKET, 'name', options); + + const calledWith = file.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + delete: {reqOpts: {qs: options.preconditionOpts}}, + exists: {reqOpts: {qs: options.preconditionOpts}}, + get: {reqOpts: {qs: options.preconditionOpts}}, + getMetadata: {reqOpts: {qs: options.preconditionOpts}}, + setMetadata: {reqOpts: {qs: options.preconditionOpts}}, + }); + assert.deepStrictEqual( + file.instancePreconditionOpts, + options.preconditionOpts + ); + }); + + it('should set the correct query string with ifMetagenerationNotMatch', () => { + const options = {preconditionOpts: {ifMetagenerationNotMatch: 100}}; + const file = new File(BUCKET, 'name', options); + + const calledWith = file.calledWith_[0]; + + assert.deepStrictEqual(calledWith.methods, { + delete: {reqOpts: {qs: options.preconditionOpts}}, + exists: {reqOpts: {qs: options.preconditionOpts}}, + get: {reqOpts: {qs: options.preconditionOpts}}, + getMetadata: {reqOpts: {qs: options.preconditionOpts}}, + setMetadata: {reqOpts: {qs: options.preconditionOpts}}, + }); + assert.deepStrictEqual( + file.instancePreconditionOpts, + options.preconditionOpts + ); + }); + + it('should not strip leading slash name in ServiceObject', () => { + const file = new File(BUCKET, '/name'); + const calledWith = file.calledWith_[0]; + + assert.strictEqual(calledWith.id, encodeURIComponent('/name')); + }); + + it('should set a custom encryption key', done => { + const key = 'key'; + const setEncryptionKey = File.prototype.setEncryptionKey; + File.prototype.setEncryptionKey = (key_: {}) => { + File.prototype.setEncryptionKey = setEncryptionKey; + assert.strictEqual(key_, key); + done(); + }; + new File(BUCKET, FILE_NAME, {encryptionKey: key}); + }); + + it('should accept a `crc32cGenerator`', () => { + const crc32cGenerator = () => {}; + + const file = new File(BUCKET, 'name', {crc32cGenerator}); + assert.strictEqual(file.crc32cGenerator, crc32cGenerator); + }); + + it("should use the bucket's `crc32cGenerator` by default", () => { + assert.strictEqual(file.crc32cGenerator, BUCKET.crc32cGenerator); + }); + + describe('userProject', () => { + const USER_PROJECT = 'grapce-spaceship-123'; + + it('should localize the Bucket#userProject', () => { + const bucket = new Bucket(STORAGE, 'bucket-name', { + userProject: USER_PROJECT, + }); + + const file = new File(bucket, '/name'); + assert.strictEqual(file.userProject, USER_PROJECT); + }); + + it('should accept a userProject option', () => { + const file = new File(BUCKET, '/name', { + userProject: USER_PROJECT, + }); + + assert.strictEqual(file.userProject, USER_PROJECT); + }); + }); + }); + + describe('cloudStorageURI', () => { + it('should return the appropriate `gs://` URI', () => { + const file = new File(BUCKET, FILE_NAME); + + assert(file.cloudStorageURI instanceof URL); + assert.equal(file.cloudStorageURI.host, BUCKET.name); + assert.equal(file.cloudStorageURI.pathname, `/${FILE_NAME}`); + }); + }); + + describe('copy', () => { + it('should throw if no destination is provided', () => { + assert.throws(() => { + file.copy(); + }, /Destination file should have a name\./); + }); + + it('should URI encode file names', done => { + const newFile = new File(BUCKET, 'nested/file.jpg'); + + const expectedPath = `/rewriteTo/b/${ + file.bucket.name + }/o/${encodeURIComponent(newFile.name)}`; + + directoryFile.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, expectedPath); + done(); + }; + + directoryFile.copy(newFile); + }); + + it('should execute callback with error & API response', done => { + const error = new Error('Error.'); + const apiResponse = {}; + + const newFile = new File(BUCKET, 'new-file'); + + file.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(error, apiResponse); + }; + + file.copy(newFile, (err: Error, file: {}, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(file, null); + assert.strictEqual(apiResponse_, apiResponse); + + done(); + }); + }); + + it('should send query.sourceGeneration if File has one', done => { + const versionedFile = new File(BUCKET, 'name', {generation: 1}); + const newFile = new File(BUCKET, 'new-file'); + + versionedFile.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.sourceGeneration, 1); + done(); + }; + + versionedFile.copy(newFile, assert.ifError); + }); + + it('should accept an options object', done => { + const newFile = new File(BUCKET, 'name'); + const METADATA = { + metadataKey: 'metadataValue', + }; + const options = { + option: true, + metadata: METADATA, + }; + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.json, options); + assert.strictEqual(reqOpts.json.metadata, METADATA); + done(); + }; + + file.copy(newFile, options, assert.ifError); + }); + + it('should pass through userProject', done => { + const options = { + userProject: 'user-project', + }; + const originalOptions = Object.assign({}, options); + const newFile = new File(BUCKET, 'new-file'); + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.userProject, options.userProject); + assert.strictEqual(reqOpts.json.userProject, undefined); + assert.deepStrictEqual(options, originalOptions); + done(); + }; + + file.copy(newFile, options, assert.ifError); + }); + + it('should set correct headers when file is encrypted', done => { + file.encryptionKey = {}; + file.encryptionKeyBase64 = 'base64'; + file.encryptionKeyHash = 'hash'; + + const newFile = new File(BUCKET, 'new-file'); + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.headers, { + 'x-goog-copy-source-encryption-algorithm': 'AES256', + 'x-goog-copy-source-encryption-key': file.encryptionKeyBase64, + 'x-goog-copy-source-encryption-key-sha256': file.encryptionKeyHash, + }); + done(); + }; + + file.copy(newFile, assert.ifError); + }); + + it('should set encryption key on the new File instance', done => { + const newFile = new File(BUCKET, 'new-file'); + newFile.encryptionKey = 'encryptionKey'; + + file.setEncryptionKey = (encryptionKey: {}) => { + assert.strictEqual(encryptionKey, newFile.encryptionKey); + done(); + }; + + file.copy(newFile, assert.ifError); + }); + + it('should set destination KMS key name', done => { + const newFile = new File(BUCKET, 'new-file'); + newFile.kmsKeyName = 'kms-key-name'; + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.qs.destinationKmsKeyName, + newFile.kmsKeyName + ); + assert.strictEqual(file.kmsKeyName, newFile.kmsKeyName); + done(); + }; + + file.copy(newFile, assert.ifError); + }); + + it('should set destination KMS key name from option', done => { + const newFile = new File(BUCKET, 'new-file'); + const destinationKmsKeyName = 'destination-kms-key-name'; + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.qs.destinationKmsKeyName, + destinationKmsKeyName + ); + assert.strictEqual(file.kmsKeyName, destinationKmsKeyName); + done(); + }; + + file.copy(newFile, {destinationKmsKeyName}, assert.ifError); + }); + + it('should accept predefined Acl', done => { + const options = { + predefinedAcl: 'authenticatedRead', + }; + const newFile = new File(BUCKET, 'new-file'); + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.qs.destinationPredefinedAcl, + options.predefinedAcl + ); + assert.strictEqual(reqOpts.json.destinationPredefinedAcl, undefined); + done(); + }; + + file.copy(newFile, options, assert.ifError); + }); + + it('should favor the option over the File KMS name', done => { + const newFile = new File(BUCKET, 'new-file'); + newFile.kmsKeyName = 'incorrect-kms-key-name'; + const destinationKmsKeyName = 'correct-kms-key-name'; + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.qs.destinationKmsKeyName, + destinationKmsKeyName + ); + assert.strictEqual(file.kmsKeyName, destinationKmsKeyName); + done(); + }; + + file.copy(newFile, {destinationKmsKeyName}, assert.ifError); + }); + + it('should remove custom encryption interceptor if rotating to KMS', done => { + const newFile = new File(BUCKET, 'new-file'); + const destinationKmsKeyName = 'correct-kms-key-name'; + + file.encryptionKeyInterceptor = {}; + file.interceptors = [{}, file.encryptionKeyInterceptor, {}]; + + file.request = () => { + assert.strictEqual(file.interceptors.length, 2); + assert(file.interceptors.indexOf(file.encryptionKeyInterceptor) === -1); + done(); + }; + + file.copy(newFile, {destinationKmsKeyName}, assert.ifError); + }); + + describe('destination types', () => { + function assertPathEquals( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file: any, + expectedPath: string, + callback: Function + ) { + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, expectedPath); + callback(); + }; + } + + it('should allow a string', done => { + const newFileName = 'new-file-name.png'; + const newFile = new File(BUCKET, newFileName); + const expectedPath = `/rewriteTo/b/${file.bucket.name}/o/${newFile.name}`; + assertPathEquals(file, expectedPath, done); + file.copy(newFileName); + }); + + it('should allow a string with leading slash.', done => { + const newFileName = '/new-file-name.png'; + const newFile = new File(BUCKET, newFileName); + // File uri encodes file name when calling this.request during copy + const expectedPath = `/rewriteTo/b/${ + file.bucket.name + }/o/${encodeURIComponent(newFile.name)}`; + assertPathEquals(file, expectedPath, done); + file.copy(newFileName); + }); + + it('should allow a "gs://..." string', done => { + const newFileName = 'gs://other-bucket/new-file-name.png'; + const expectedPath = '/rewriteTo/b/other-bucket/o/new-file-name.png'; + assertPathEquals(file, expectedPath, done); + file.copy(newFileName); + }); + + it('should allow a Bucket', done => { + const expectedPath = `/rewriteTo/b/${BUCKET.name}/o/${file.name}`; + assertPathEquals(file, expectedPath, done); + file.copy(BUCKET); + }); + + it('should allow a File', done => { + const newFile = new File(BUCKET, 'new-file'); + const expectedPath = `/rewriteTo/b/${BUCKET.name}/o/${newFile.name}`; + assertPathEquals(file, expectedPath, done); + file.copy(newFile); + }); + + it('should throw if a destination cannot be parsed', () => { + assert.throws(() => { + file.copy(() => {}); + }, /Destination file should have a name\./); + }); + }); + + describe('not finished copying', () => { + const apiResponse = { + rewriteToken: '...', + }; + + beforeEach(() => { + file.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, apiResponse); + }; + }); + + it('should continue attempting to copy', done => { + const newFile = new File(BUCKET, 'new-file'); + + file.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + file.copy = (newFile_: {}, options: {}, callback: Function) => { + assert.strictEqual(newFile_, newFile); + assert.deepStrictEqual(options, {token: apiResponse.rewriteToken}); + callback(); // done() + }; + + callback(null, apiResponse); + }; + + file.copy(newFile, done); + }); + + it('should pass the userProject in subsequent requests', done => { + const newFile = new File(BUCKET, 'new-file'); + const fakeOptions = { + userProject: 'grapce-spaceship-123', + }; + + file.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.copy = (newFile_: {}, options: any) => { + assert.notStrictEqual(options, fakeOptions); + assert.strictEqual(options.userProject, fakeOptions.userProject); + done(); + }; + + callback(null, apiResponse); + }; + + file.copy(newFile, fakeOptions, assert.ifError); + }); + + it('should pass the KMS key name in subsequent requests', done => { + const newFile = new File(BUCKET, 'new-file'); + const fakeOptions = { + destinationKmsKeyName: 'kms-key-name', + }; + + file.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.copy = (newFile_: {}, options: any) => { + assert.strictEqual( + options.destinationKmsKeyName, + fakeOptions.destinationKmsKeyName + ); + done(); + }; + + callback(null, apiResponse); + }; + + file.copy(newFile, fakeOptions, assert.ifError); + }); + + it('should make the subsequent correct API request', done => { + const newFile = new File(BUCKET, 'new-file'); + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.rewriteToken, apiResponse.rewriteToken); + done(); + }; + + file.copy(newFile, {token: apiResponse.rewriteToken}, assert.ifError); + }); + }); + + describe('returned File object', () => { + beforeEach(() => { + const resp = {success: true}; + file.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, resp); + }; + }); + + it('should re-use file object if one is provided', done => { + const newFile = new File(BUCKET, 'new-file'); + file.copy(newFile, (err: Error, copiedFile: {}) => { + assert.ifError(err); + assert.deepStrictEqual(copiedFile, newFile); + done(); + }); + }); + + it('should create new file on the same bucket', done => { + const newFilename = 'new-filename'; + file.copy(newFilename, (err: Error, copiedFile: File) => { + assert.ifError(err); + assert.strictEqual(copiedFile.bucket.name, BUCKET.name); + assert.strictEqual(copiedFile.name, newFilename); + done(); + }); + }); + + it('should create new file on the destination bucket', done => { + file.copy(BUCKET, (err: Error, copiedFile: File) => { + assert.ifError(err); + assert.strictEqual(copiedFile.bucket.name, BUCKET.name); + assert.strictEqual(copiedFile.name, file.name); + done(); + }); + }); + + it('should pass apiResponse into callback', done => { + file.copy(BUCKET, (err: Error, copiedFile: File, apiResponse: {}) => { + assert.ifError(err); + assert.deepStrictEqual({success: true}, apiResponse); + done(); + }); + }); + }); + }); + + describe('createReadStream', () => { + function getFakeRequest(data?: {}) { + let requestOptions: DecorateRequestOptions | undefined; + + class FakeRequest extends Readable { + constructor(_requestOptions?: DecorateRequestOptions) { + super(); + requestOptions = _requestOptions; + this._read = () => { + if (data) { + this.push(data); + } + this.push(null); + }; + } + + static getRequestOptions() { + return requestOptions; + } + } + + // Return a Proxy of FakeRequest which can be instantiated + // without new. + return new Proxy(FakeRequest, { + apply(target, _, argumentsList) { + return new target(...argumentsList); + }, + }); + } + + function getFakeSuccessfulRequest(data: {}) { + // tslint:disable-next-line:variable-name + const FakeRequest = getFakeRequest(data); + + class FakeSuccessfulRequest extends FakeRequest { + constructor(req?: DecorateRequestOptions) { + super(req); + setImmediate(() => { + const stream = new FakeRequest(); + this.emit('response', stream); + }); + } + } + + // Return a Proxy of FakeSuccessfulRequest which can be instantiated + // without new. + return new Proxy(FakeSuccessfulRequest, { + apply(target, _, argumentsList) { + return new target(...argumentsList); + }, + }); + } + + function getFakeFailedRequest(error: Error) { + // tslint:disable-next-line:variable-name + const FakeRequest = getFakeRequest(); + + class FakeFailedRequest extends FakeRequest { + constructor(_req?: DecorateRequestOptions) { + super(_req); + setImmediate(() => { + this.emit('error', error); + }); + } + } + + // Return a Proxy of FakeFailedRequest which can be instantiated + // without new. + return new Proxy(FakeFailedRequest, { + apply(target, _, argumentsList) { + return new target(...argumentsList); + }, + }); + } + + beforeEach(() => { + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + const rawResponseStream = new PassThrough(); + Object.assign(rawResponseStream, { + toJSON() { + return {headers: {}}; + }, + }); + callback(null, null, rawResponseStream); + setImmediate(() => { + rawResponseStream.end(); + }); + }; + }); + + it('should throw if both a range and validation is given', () => { + assert.throws(() => { + file.createReadStream({ + validation: true, + start: 3, + end: 8, + }); + }, /Cannot use validation with file ranges \(start\/end\)\./); + + assert.throws(() => { + file.createReadStream({ + validation: true, + start: 3, + }); + }, /Cannot use validation with file ranges \(start\/end\)\./); + + assert.throws(() => { + file.createReadStream({ + validation: true, + end: 8, + }); + }, /Cannot use validation with file ranges \(start\/end\)\./); + + assert.doesNotThrow(() => { + file.createReadStream({ + start: 3, + end: 8, + }); + }); + }); + + it('should send query.generation if File has one', done => { + const versionedFile = new File(BUCKET, 'file.txt', {generation: 1}); + + versionedFile.requestStream = (rOpts: DecorateRequestOptions) => { + assert.strictEqual(rOpts.qs.generation, 1); + setImmediate(done); + return duplexify(); + }; + + versionedFile.createReadStream().resume(); + }); + + it('should send query.userProject if provided', done => { + const options = { + userProject: 'user-project-id', + }; + + file.requestStream = (rOpts: DecorateRequestOptions) => { + assert.strictEqual(rOpts.qs.userProject, options.userProject); + setImmediate(done); + return duplexify(); + }; + + file.createReadStream(options).resume(); + }); + + it('should pass the `GCCL_GCS_CMD_KEY` to `requestStream`', done => { + const expected = 'expected/value'; + + file.requestStream = (opts: DecorateRequestOptions) => { + assert.equal(opts[GCCL_GCS_CMD_KEY], expected); + + process.nextTick(() => done()); + + return duplexify(); + }; + + file + .createReadStream({ + [GCCL_GCS_CMD_KEY]: expected, + }) + .resume(); + }); + + describe('authenticating', () => { + it('should create an authenticated request', done => { + file.requestStream = (opts: DecorateRequestOptions) => { + assert.deepStrictEqual(opts, { + uri: '', + headers: { + 'Accept-Encoding': 'gzip', + 'Cache-Control': 'no-store', + }, + qs: { + alt: 'media', + }, + }); + setImmediate(() => { + done(); + }); + return duplexify(); + }; + + file.createReadStream().resume(); + }); + + describe('errors', () => { + const ERROR = new Error('Error.'); + + beforeEach(() => { + file.requestStream = () => { + const requestStream = new PassThrough(); + + setImmediate(() => { + requestStream.emit('error', ERROR); + }); + + return requestStream; + }; + }); + + it('should emit an error from authenticating', done => { + file + .createReadStream() + .once('error', (err: Error) => { + assert.strictEqual(err, ERROR); + done(); + }) + .resume(); + }); + }); + }); + + describe('requestStream', () => { + it('should get readable stream from request', done => { + file.requestStream = () => { + setImmediate(() => { + done(); + }); + + return new PassThrough(); + }; + + file.createReadStream().resume(); + }); + + it('should emit response event from request', done => { + file.requestStream = getFakeSuccessfulRequest('body'); + + file + .createReadStream({validation: false}) + .on('response', () => { + done(); + }) + .resume(); + }); + + it('should let util.handleResp handle the response', done => { + const response = {a: 'b', c: 'd'}; + + handleRespOverride = (err: Error, response_: {}, body: {}) => { + assert.strictEqual(err, null); + assert.strictEqual(response_, response); + assert.strictEqual(body, null); + done(); + }; + + file.requestStream = () => { + const rowRequestStream = new PassThrough(); + setImmediate(() => { + rowRequestStream.emit('response', response); + }); + return rowRequestStream; + }; + + file.createReadStream().resume(); + }); + + describe('errors', () => { + const ERROR = new Error('Error.'); + + beforeEach(() => { + file.requestStream = getFakeFailedRequest(ERROR); + }); + + it('should emit the error', done => { + file + .createReadStream() + .once('error', (err: Error) => { + assert.deepStrictEqual(err, ERROR); + done(); + }) + .resume(); + }); + + it('should parse a response stream for a better error', done => { + const rawResponsePayload = 'error message from body'; + const rawResponseStream = new PassThrough(); + const requestStream = new PassThrough(); + + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + callback(ERROR, null, res); + setImmediate(() => { + rawResponseStream.end(rawResponsePayload); + }); + }; + + file.requestStream = () => { + setImmediate(() => { + requestStream.emit('response', rawResponseStream); + }); + return requestStream; + }; + + file + .createReadStream() + .once('error', (err: Error) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(err.message, rawResponsePayload); + done(); + }) + .resume(); + }); + + it('should emit errors from the request stream', done => { + const error = new Error('Error.'); + const rawResponseStream = new PassThrough(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (rawResponseStream as any).toJSON = () => { + return {headers: {}}; + }; + const requestStream = new PassThrough(); + + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + callback(null, null, rawResponseStream); + setImmediate(() => { + rawResponseStream.emit('error', error); + }); + }; + + file.requestStream = () => { + setImmediate(() => { + requestStream.emit('response', rawResponseStream); + }); + return requestStream; + }; + + file + .createReadStream() + .on('error', (err: Error) => { + assert.strictEqual(err, error); + done(); + }) + .resume(); + }); + + it('should not handle both error and end events', done => { + const error = new Error('Error.'); + const rawResponseStream = new PassThrough(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (rawResponseStream as any).toJSON = () => { + return {headers: {}}; + }; + const requestStream = new PassThrough(); + + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + callback(null, null, rawResponseStream); + setImmediate(() => { + rawResponseStream.emit('error', error); + }); + }; + + file.requestStream = () => { + setImmediate(() => { + requestStream.emit('response', rawResponseStream); + }); + return requestStream; + }; + + file + .createReadStream({validation: false}) + .on('error', (err: Error) => { + assert.strictEqual(err, error); + rawResponseStream.emit('end'); + setImmediate(done); + }) + .on('end', () => { + done(new Error('Should not have been called.')); + }) + .resume(); + }); + }); + }); + + describe('compression', () => { + beforeEach(() => { + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + const rawResponseStream = new PassThrough(); + Object.assign(rawResponseStream, { + toJSON() { + return { + headers: { + 'content-encoding': 'gzip', + 'x-goog-hash': `crc32c=${CRC32C_HASH_GZIP},md5=${MD5_HASH}`, + }, + }; + }, + }); + callback(null, null, rawResponseStream); + + rawResponseStream.end(GZIPPED_DATA); + }; + file.requestStream = getFakeSuccessfulRequest(GZIPPED_DATA); + }); + + it('should gunzip the response', async () => { + const collection: Buffer[] = []; + + for await (const data of file.createReadStream()) { + collection.push(data); + } + + assert.equal(Buffer.concat(collection).toString(), DATA); + }); + + it('should not gunzip the response if "decompress: false" is passed', async () => { + const collection: Buffer[] = []; + + for await (const data of file.createReadStream({decompress: false})) { + collection.push(data); + } + + assert.equal( + Buffer.compare(Buffer.concat(collection), GZIPPED_DATA), + 0 + ); + }); + + it('should emit errors from the gunzip stream', done => { + const error = new Error('Error.'); + const createGunzipStream = new PassThrough(); + createGunzipOverride = () => { + process.nextTick(() => { + createGunzipStream.emit('error', error); + }); + return createGunzipStream; + }; + file + .createReadStream() + .on('error', (err: Error) => { + assert.strictEqual(err, error); + done(); + }) + .resume(); + }); + + it('should not handle both error and end events', done => { + const error = new Error('Error.'); + const createGunzipStream = new PassThrough(); + createGunzipOverride = () => { + process.nextTick(() => { + createGunzipStream.emit('error', error); + }); + return createGunzipStream; + }; + file + .createReadStream({validation: false}) + .on('error', (err: Error) => { + assert.strictEqual(err, error); + createGunzipStream.emit('end'); + setImmediate(done); + }) + .on('end', () => { + done(new Error('Should not have been called.')); + }) + .resume(); + }); + }); + + describe('validation', () => { + let responseCRC32C = CRC32C_HASH; + let responseMD5 = MD5_HASH; + + beforeEach(() => { + responseCRC32C = CRC32C_HASH; + responseMD5 = MD5_HASH; + + file.getMetadata = async () => ({}); + + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + const rawResponseStream = new PassThrough(); + Object.assign(rawResponseStream, { + toJSON() { + return { + headers: { + 'x-goog-hash': `crc32c=${responseCRC32C},md5=${responseMD5}`, + 'x-goog-stored-content-encoding': 'identity', + }, + }; + }, + }); + callback(null, null, rawResponseStream); + setImmediate(() => { + rawResponseStream.end(DATA); + }); + }; + file.requestStream = getFakeSuccessfulRequest(DATA); + }); + + function setFileValidationToError(e: Error = new Error('test-error')) { + // Simulating broken CRC32C instance - used by the validation stream + file.crc32cGenerator = () => { + class C extends CRC32C { + update() { + throw e; + } + } + + return new C(); + }; + } + + describe('server decompression', () => { + it('should skip validation if file was stored compressed and served decompressed', done => { + file.metadata.crc32c = '.invalid.'; + file.metadata.contentEncoding = 'gzip'; + + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + const rawResponseStream = new PassThrough(); + Object.assign(rawResponseStream, { + toJSON() { + return { + headers: { + 'x-goog-hash': `crc32c=${responseCRC32C},md5=${responseMD5}`, + 'x-goog-stored-content-encoding': 'gzip', + }, + }; + }, + }); + callback(null, null, rawResponseStream); + setImmediate(() => { + rawResponseStream.end(DATA); + }); + }; + + file + .createReadStream({validation: 'crc32c'}) + .on('end', done) + .resume(); + }); + }); + + it('should perform validation if file was stored compressed and served compressed', done => { + file.metadata.crc32c = '.invalid.'; + file.metadata.contentEncoding = 'gzip'; + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + const rawResponseStream = new PassThrough(); + Object.assign(rawResponseStream, { + toJSON() { + return { + headers: { + 'x-goog-hash': `crc32c=${responseCRC32C},md5=${responseMD5}`, + 'x-goog-stored-content-encoding': 'gzip', + 'content-encoding': 'gzip', + }, + }; + }, + }); + callback(null, null, rawResponseStream); + setImmediate(() => { + rawResponseStream.end(DATA); + }); + }; + + const expectedError = new Error('test error'); + setFileValidationToError(expectedError); + + file + .createReadStream({validation: 'crc32c'}) + .on('error', (err: Error) => { + assert(err === expectedError); + done(); + }) + .resume(); + }); + + it('should emit errors from the validation stream', done => { + const expectedError = new Error('test error'); + + file.requestStream = getFakeSuccessfulRequest(DATA); + setFileValidationToError(expectedError); + + file + .createReadStream() + .on('error', (err: Error) => { + assert(err === expectedError); + + done(); + }) + .resume(); + }); + + it('should not handle both error and end events', done => { + const expectedError = new Error('test error'); + + file.requestStream = getFakeSuccessfulRequest(DATA); + setFileValidationToError(expectedError); + + file + .createReadStream() + .on('error', (err: Error) => { + assert(err === expectedError); + + setImmediate(done); + }) + .on('end', () => { + done(new Error('Should not have been called.')); + }) + .resume(); + }); + + it('should validate with crc32c', done => { + file.requestStream = getFakeSuccessfulRequest(DATA); + + file + .createReadStream({validation: 'crc32c'}) + .on('error', done) + .on('end', done) + .resume(); + }); + + it('should emit an error if crc32c validation fails', done => { + file.requestStream = getFakeSuccessfulRequest('bad-data'); + + responseCRC32C = 'bad-crc32c'; + + file + .createReadStream({validation: 'crc32c'}) + .on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'CONTENT_DOWNLOAD_MISMATCH'); + done(); + }) + .resume(); + }); + + it('should validate with md5', done => { + file.requestStream = getFakeSuccessfulRequest(DATA); + + file + .createReadStream({validation: 'md5'}) + .on('error', done) + .on('end', done) + .resume(); + }); + + it('should emit an error if md5 validation fails', done => { + file.requestStream = getFakeSuccessfulRequest('bad-data'); + + responseMD5 = 'bad-md5'; + + file + .createReadStream({validation: 'md5'}) + .on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'CONTENT_DOWNLOAD_MISMATCH'); + done(); + }) + .resume(); + }); + + it('should default to crc32c validation', done => { + file.requestStream = getFakeSuccessfulRequest('bad-data'); + + responseCRC32C = 'bad-crc32c'; + + file + .createReadStream() + .on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'CONTENT_DOWNLOAD_MISMATCH'); + done(); + }) + .resume(); + }); + + it('should ignore a data mismatch if validation: false', done => { + file.requestStream = getFakeSuccessfulRequest(DATA); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + // (fakeValidationStream as any).test = () => false; + file + .createReadStream({validation: false}) + .resume() + .on('error', done) + .on('end', done); + }); + + it('should handle x-goog-hash with only crc32c', done => { + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + const rawResponseStream = new PassThrough(); + Object.assign(rawResponseStream, { + toJSON() { + return { + headers: { + 'x-goog-hash': `crc32c=${CRC32C_HASH}`, + }, + }; + }, + }); + callback(null, null, rawResponseStream); + setImmediate(() => { + rawResponseStream.end(DATA); + }); + }; + + file.requestStream = getFakeSuccessfulRequest(DATA); + + file.createReadStream().on('error', done).on('end', done).resume(); + }); + + describe('destroying the through stream', () => { + it('should destroy after failed validation', done => { + file.requestStream = getFakeSuccessfulRequest('bad-data'); + + responseMD5 = 'bad-md5'; + + const readStream = file.createReadStream({validation: 'md5'}); + readStream.on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'CONTENT_DOWNLOAD_MISMATCH'); + done(); + }); + + readStream.resume(); + }); + + it('should destroy if MD5 is requested but absent', done => { + handleRespOverride = ( + err: Error, + res: {}, + body: {}, + callback: Function + ) => { + const rawResponseStream = new PassThrough(); + Object.assign(rawResponseStream, { + toJSON() { + return { + headers: {}, + }; + }, + }); + callback(null, null, rawResponseStream); + setImmediate(() => { + rawResponseStream.end(); + }); + }; + file.requestStream = getFakeSuccessfulRequest('bad-data'); + + const readStream = file.createReadStream({validation: 'md5'}); + + readStream.on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'MD5_NOT_AVAILABLE'); + done(); + }); + + readStream.resume(); + }); + }); + }); + + describe('range requests', () => { + it('should accept a start range', done => { + const startOffset = 100; + + file.requestStream = (opts: DecorateRequestOptions) => { + setImmediate(() => { + assert.strictEqual( + opts.headers!.Range, + 'bytes=' + startOffset + '-' + ); + done(); + }); + return duplexify(); + }; + + file.createReadStream({start: startOffset}).resume(); + }); + + it('should accept an end range and set start to 0', done => { + const endOffset = 100; + + file.requestStream = (opts: DecorateRequestOptions) => { + setImmediate(() => { + assert.strictEqual(opts.headers!.Range, 'bytes=0-' + endOffset); + done(); + }); + return duplexify(); + }; + + file.createReadStream({end: endOffset}).resume(); + }); + + it('should accept both a start and end range', done => { + const startOffset = 100; + const endOffset = 101; + + file.requestStream = (opts: DecorateRequestOptions) => { + setImmediate(() => { + const expectedRange = 'bytes=' + startOffset + '-' + endOffset; + assert.strictEqual(opts.headers!.Range, expectedRange); + done(); + }); + return duplexify(); + }; + + file.createReadStream({start: startOffset, end: endOffset}).resume(); + }); + + it('should accept range start and end as 0', done => { + const startOffset = 0; + const endOffset = 0; + + file.requestStream = (opts: DecorateRequestOptions) => { + setImmediate(() => { + const expectedRange = 'bytes=0-0'; + assert.strictEqual(opts.headers!.Range, expectedRange); + done(); + }); + return duplexify(); + }; + + file.createReadStream({start: startOffset, end: endOffset}).resume(); + }); + + it('should end the through stream', done => { + file.requestStream = getFakeSuccessfulRequest(DATA); + + const readStream = file.createReadStream({start: 100}); + readStream.on('end', done); + readStream.resume(); + }); + }); + + describe('tail requests', () => { + it('should make a request for the tail bytes', done => { + const endOffset = -10; + + file.requestStream = (opts: DecorateRequestOptions) => { + setImmediate(() => { + assert.strictEqual(opts.headers!.Range, 'bytes=' + endOffset); + done(); + }); + return duplexify(); + }; + + file.createReadStream({end: endOffset}).resume(); + }); + }); + }); + + describe('createResumableUpload', () => { + it('should not require options', done => { + resumableUploadOverride = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createURI(opts: any, callback: Function) { + assert.strictEqual(opts.metadata, undefined); + callback(); + }, + }; + + file.createResumableUpload(done); + }); + + it('should disable autoRetry when ifMetagenerationMatch is undefined', done => { + resumableUploadOverride = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createURI(opts: any, callback: Function) { + assert.strictEqual(opts.retryOptions.autoRetry, false); + callback(); + }, + }; + file.createResumableUpload(done); + assert.strictEqual(file.storage.retryOptions.autoRetry, true); + }); + + it('should create a resumable upload URI', done => { + const options = { + metadata: { + contentType: 'application/json', + }, + origin: '*', + predefinedAcl: 'predefined-acl', + private: 'private', + public: 'public', + userProject: 'user-project-id', + retryOptions: { + autoRetry: true, + maxRetries: 3, + maxRetryDelay: 60, + retryDelayMultiplier: 2, + totalTimeout: 600, + }, + preconditionOpts: { + ifGenerationMatch: 100, + ifMetagenerationMatch: 101, + }, + }; + + file.generation = 3; + file.encryptionKey = 'encryption-key'; + file.kmsKeyName = 'kms-key-name'; + + resumableUploadOverride = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createURI(opts: any, callback: Function) { + const bucket = file.bucket; + const storage = bucket.storage; + + assert.strictEqual(opts.authClient, storage.authClient); + assert.strictEqual(opts.apiEndpoint, storage.apiEndpoint); + assert.strictEqual(opts.bucket, bucket.name); + assert.strictEqual(opts.file, file.name); + assert.strictEqual(opts.generation, file.generation); + assert.strictEqual(opts.key, file.encryptionKey); + assert.strictEqual(opts.kmsKeyName, file.kmsKeyName); + assert.strictEqual(opts.metadata, options.metadata); + assert.strictEqual(opts.origin, options.origin); + assert.strictEqual(opts.predefinedAcl, options.predefinedAcl); + assert.strictEqual(opts.private, options.private); + assert.strictEqual(opts.public, options.public); + assert.strictEqual(opts.userProject, options.userProject); + assert.strictEqual( + opts.retryOptions.autoRetry, + options.retryOptions.autoRetry + ); + assert.strictEqual( + opts.retryOptions.maxRetries, + options.retryOptions.maxRetries + ); + assert.strictEqual( + opts.retryOptions.maxRetryDelay, + options.retryOptions.maxRetryDelay + ); + assert.strictEqual( + opts.retryOptions.retryDelayMultiplier, + options.retryOptions.retryDelayMultiplier + ); + assert.strictEqual( + opts.retryOptions.totalTimeout, + options.retryOptions.totalTimeout + ); + assert.strictEqual(opts.params, options.preconditionOpts); + + callback(); + }, + }; + + file.createResumableUpload(options, done); + }); + + it('should create a resumable upload URI using precondition options from constructor', done => { + file = new File(BUCKET, FILE_NAME, { + preconditionOpts: { + ifGenerationMatch: 200, + ifGenerationNotMatch: 201, + ifMetagenerationMatch: 202, + ifMetagenerationNotMatch: 203, + }, + }); + const options = { + metadata: { + contentType: 'application/json', + }, + origin: '*', + predefinedAcl: 'predefined-acl', + private: 'private', + public: 'public', + userProject: 'user-project-id', + retryOptions: { + autoRetry: true, + maxRetries: 3, + maxRetryDelay: 60, + retryDelayMultiplier: 2, + totalTimeout: 600, + }, + }; + + file.generation = 3; + file.encryptionKey = 'encryption-key'; + file.kmsKeyName = 'kms-key-name'; + + resumableUploadOverride = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createURI(opts: any, callback: Function) { + const bucket = file.bucket; + const storage = bucket.storage; + + assert.strictEqual(opts.authClient, storage.authClient); + assert.strictEqual(opts.apiEndpoint, storage.apiEndpoint); + assert.strictEqual(opts.bucket, bucket.name); + assert.strictEqual(opts.file, file.name); + assert.strictEqual(opts.generation, file.generation); + assert.strictEqual(opts.key, file.encryptionKey); + assert.strictEqual(opts.kmsKeyName, file.kmsKeyName); + assert.strictEqual(opts.metadata, options.metadata); + assert.strictEqual(opts.origin, options.origin); + assert.strictEqual(opts.predefinedAcl, options.predefinedAcl); + assert.strictEqual(opts.private, options.private); + assert.strictEqual(opts.public, options.public); + assert.strictEqual(opts.userProject, options.userProject); + assert.strictEqual( + opts.retryOptions.autoRetry, + options.retryOptions.autoRetry + ); + assert.strictEqual( + opts.retryOptions.maxRetries, + options.retryOptions.maxRetries + ); + assert.strictEqual( + opts.retryOptions.maxRetryDelay, + options.retryOptions.maxRetryDelay + ); + assert.strictEqual( + opts.retryOptions.retryDelayMultiplier, + options.retryOptions.retryDelayMultiplier + ); + assert.strictEqual( + opts.retryOptions.totalTimeout, + options.retryOptions.totalTimeout + ); + assert.strictEqual(opts.params, file.instancePreconditionOpts); + + callback(); + }, + }; + + file.createResumableUpload(options, done); + }); + }); + + describe('createWriteStream', () => { + const METADATA = {a: 'b', c: 'd'}; + + beforeEach(() => { + Object.assign(fakeFs, { + access(dir: string, check: {}, callback: Function) { + // Assume that the required config directory is writable. + callback(); + }, + }); + }); + + it('should return a stream', () => { + assert(file.createWriteStream() instanceof Stream); + }); + + it('should emit errors', done => { + const error = new Error('Error.'); + const uploadStream = new PassThrough(); + + file.startResumableUpload_ = (dup: duplexify.Duplexify) => { + dup.setWritable(uploadStream); + uploadStream.emit('error', error); + }; + + const writable = file.createWriteStream(); + + writable.on('error', (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + + writable.write('data'); + }); + + it('should emit RangeError', done => { + const error = new RangeError( + 'Cannot provide an `offset` without providing a `uri`' + ); + + const options = { + offset: 1, + isPartialUpload: true, + }; + const writable = file.createWriteStream(options); + + writable.on('error', (err: RangeError) => { + assert.deepEqual(err, error); + done(); + }); + + writable.write('data'); + }); + + it('should emit progress via resumable upload', done => { + const progress = {}; + + resumableUploadOverride = { + upload() { + const uploadStream = new PassThrough(); + setImmediate(() => { + uploadStream.emit('progress', progress); + }); + + return uploadStream; + }, + }; + + const writable = file.createWriteStream(); + + writable.on('progress', (evt: {}) => { + assert.strictEqual(evt, progress); + done(); + }); + + writable.write('data'); + }); + + it('should emit progress via simple upload', done => { + const progress = {}; + + makeWritableStreamOverride = (dup: duplexify.Duplexify) => { + const uploadStream = new PassThrough(); + uploadStream.on('progress', evt => dup.emit('progress', evt)); + + dup.setWritable(uploadStream); + setImmediate(() => { + uploadStream.emit('progress', progress); + }); + }; + + const writable = file.createWriteStream({resumable: false}); + + writable.on('progress', (evt: {}) => { + assert.strictEqual(evt, progress); + done(); + }); + + writable.write('data'); + }); + + it('should start a simple upload if specified', done => { + const options = { + metadata: METADATA, + resumable: false, + customValue: true, + }; + const writable = file.createWriteStream(options); + + file.startSimpleUpload_ = () => { + done(); + }; + + writable.write('data'); + }); + + it('should start a resumable upload if specified', done => { + const options = { + metadata: METADATA, + resumable: true, + customValue: true, + }; + const writable = file.createWriteStream(options); + + file.startResumableUpload_ = () => { + done(); + }; + + writable.write('data'); + }); + + it('should default to a resumable upload', done => { + const writable = file.createWriteStream({ + metadata: METADATA, + }); + + file.startResumableUpload_ = () => { + done(); + }; + + writable.write('data'); + }); + + it('should alias contentType to metadata object', done => { + const contentType = 'text/html'; + const writable = file.createWriteStream({contentType}); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.metadata.contentType, contentType); + done(); + }; + + writable.write('data'); + }); + + it('should detect contentType with contentType:auto', done => { + const writable = file.createWriteStream({contentType: 'auto'}); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.metadata.contentType, 'image/png'); + done(); + }; + + writable.write('data'); + }); + + it('should detect contentType if not defined', done => { + const writable = file.createWriteStream(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.metadata.contentType, 'image/png'); + done(); + }; + + writable.write('data'); + }); + + it('should not set a contentType if mime lookup failed', done => { + const file = new File('file-without-ext'); + const writable = file.createWriteStream(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(typeof options.metadata.contentType, 'undefined'); + done(); + }; + + writable.write('data'); + }); + + it('should set encoding with gzip:true', done => { + const writable = file.createWriteStream({gzip: true}); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.metadata.contentEncoding, 'gzip'); + done(); + }; + + writable.write('data'); + }); + + it('should set ifGenerationMatch with 100', done => { + const writable = file.createWriteStream({ + preconditionOpts: {ifGenerationMatch: 100}, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.preconditionOpts.ifGenerationMatch, 100); + done(); + }; + + writable.write('data'); + }); + + it('should set ifGenerationNotMatch with 100', done => { + const writable = file.createWriteStream({ + preconditionOpts: {ifGenerationNotMatch: 100}, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.preconditionOpts.ifGenerationNotMatch, 100); + done(); + }; + + writable.write('data'); + }); + + it('should set ifMetagenerationMatch with 100', done => { + const writable = file.createWriteStream({ + preconditionOpts: {ifMetagenerationMatch: 100}, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.preconditionOpts.ifMetagenerationMatch, 100); + done(); + }; + + writable.write('data'); + }); + + it('should set ifMetagenerationNotMatch with 100', done => { + const writable = file.createWriteStream({ + preconditionOpts: {ifMetagenerationNotMatch: 100}, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual( + options.preconditionOpts.ifMetagenerationNotMatch, + 100 + ); + done(); + }; + + writable.write('data'); + }); + + it('should set encoding with gzip:auto & compressible', done => { + const writable = file.createWriteStream({ + gzip: 'auto', + contentType: 'text/html', // (compressible) + }); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.metadata.contentEncoding, 'gzip'); + done(); + }; + + writable.write('data'); + }); + + it('should not set encoding with gzip:auto & non-compressible', done => { + const writable = file.createWriteStream({gzip: 'auto'}); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.startResumableUpload_ = (stream: {}, options: any) => { + assert.strictEqual(options.metadata.contentEncoding, undefined); + done(); + }; + writable.write('data'); + }); + + it('should re-emit response event', done => { + const writable = file.createWriteStream(); + const resp = {}; + + file.startResumableUpload_ = (stream: Duplex) => { + stream.emit('response', resp); + }; + + writable.on('response', (resp_: {}) => { + assert.strictEqual(resp_, resp); + done(); + }); + + writable.write('data'); + }); + + it('should emit `finish` only after underlying pipeline is complete', done => { + const writable = file.createWriteStream({ + resumable: false, + validation: false, + }); + + let streamFinishedCalled = false; + + writable.on('finish', () => { + try { + assert(streamFinishedCalled); + done(); + } catch (e) { + done(e); + } + }); + + file.startSimpleUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + streamFinishedCalled = true; + }); + }; + + writable.end('data'); + }); + + it('should close upstream when pipeline fails', done => { + const writable: Stream.Writable = file.createWriteStream(); + const error = new Error('My error'); + const uploadStream = new PassThrough(); + + let receivedBytes = 0; + const validateStream = new PassThrough(); + validateStream.on('data', (chunk: Buffer) => { + receivedBytes += chunk.length; + if (receivedBytes > 5) { + // this aborts the pipeline which should also close the internal pipeline within createWriteStream + pLine.destroy(error); + } + }); + + file.startResumableUpload_ = (dup: duplexify.Duplexify) => { + dup.setWritable(uploadStream); + // Emit an error so the pipeline's error-handling logic is triggered + uploadStream.emit('error', error); + // Explicitly destroy the stream so that the 'close' event is guaranteed to fire, + // even in Node v14 where autoDestroy defaults may prevent automatic closing + uploadStream.destroy(); + }; + + let closed = false; + uploadStream.on('close', () => { + closed = true; + }); + + const pLine = pipeline( + (function* () { + yield 'foo'; // write some data + yield 'foo'; // write some data + yield 'foo'; // write some data + })(), + validateStream, + writable, + (e: Error | null) => { + assert.strictEqual(e, error); + assert.strictEqual(closed, true); + done(); + } + ); + }); + + it('should error pipeline if source stream emits error before any data', done => { + const writable = file.createWriteStream(); + const error = new Error('Error before first chunk'); + pipeline( + // eslint-disable-next-line require-yield + (function* () { + throw error; + })(), + writable, + (e: Error | null) => { + assert.strictEqual(e, error); + done(); + } + ); + }); + + describe('validation', () => { + const data = 'test'; + + const fakeMetadata = { + crc32c: {crc32c: 'hqBywA=='}, + md5: {md5Hash: 'CY9rzUYh03PK3k6DJie09g=='}, + }; + + it('should validate with crc32c', done => { + const writable = file.createWriteStream({validation: 'crc32c'}); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = fakeMetadata.crc32c; + }); + }; + + writable.end(data); + + writable.on('error', done).on('finish', done); + }); + + it('should emit an error if crc32c validation fails', done => { + const writable = file.createWriteStream({validation: 'crc32c'}); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = fakeMetadata.crc32c; + }); + }; + + file.delete = async () => {}; + + writable.write('bad-data'); + writable.end(); + + writable.on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'FILE_NO_UPLOAD'); + done(); + }); + }); + + it('should validate with md5', done => { + const writable = file.createWriteStream({validation: 'md5'}); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = fakeMetadata.md5; + }); + }; + + writable.write(data); + writable.end(); + + writable.on('error', done).on('finish', done); + }); + + it('should emit an error if md5 validation fails', done => { + const writable = file.createWriteStream({validation: 'md5'}); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = fakeMetadata.md5; + }); + }; + + file.delete = async () => {}; + + writable.write('bad-data'); + writable.end(); + + writable.on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'FILE_NO_UPLOAD'); + done(); + }); + }); + + it('should default to md5 validation', done => { + const writable = file.createWriteStream(); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = {md5Hash: 'bad-hash'}; + }); + }; + + file.delete = async () => {}; + + writable.write(data); + writable.end(); + + writable.on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'FILE_NO_UPLOAD'); + done(); + }); + }); + + it('should ignore a data mismatch if validation: false', done => { + const writable = file.createWriteStream({validation: false}); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = {md5Hash: 'bad-hash'}; + }); + }; + + writable.write(data); + writable.end(); + + writable.on('error', done); + writable.on('finish', done); + }); + + it('should delete the file if validation fails', done => { + const writable = file.createWriteStream(); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = {md5Hash: 'bad-hash'}; + }); + }; + + file.delete = async () => {}; + + writable.on('error', (e: ApiError) => { + assert.equal(e.code, 'FILE_NO_UPLOAD'); + done(); + }); + + writable.write(data); + writable.end(); + }); + + it('should emit an error if MD5 is requested but absent', done => { + const writable = file.createWriteStream({validation: 'md5'}); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = {crc32c: 'not-md5'}; + }); + }; + + file.delete = async () => {}; + + writable.write(data); + writable.end(); + + writable.on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'MD5_NOT_AVAILABLE'); + done(); + }); + }); + + it('should emit a different error if delete fails', done => { + const writable = file.createWriteStream(); + + file.startResumableUpload_ = (stream: duplexify.Duplexify) => { + stream.setWritable(new PassThrough()); + stream.emit('metadata'); + + stream.on('finish', () => { + file.metadata = {md5Hash: 'bad-hash'}; + }); + }; + + const deleteErrorMessage = 'Delete error message.'; + const deleteError = new Error(deleteErrorMessage); + file.delete = async () => { + throw deleteError; + }; + + writable.write(data); + writable.end(); + + writable.on('error', (err: ApiError) => { + assert.strictEqual(err.code, 'FILE_NO_UPLOAD_DELETE'); + assert(err.message.indexOf(deleteErrorMessage) > -1); + done(); + }); + }); + }); + }); + + describe('download', () => { + let fileReadStream: Readable; + let originalSetEncryptionKey: Function; + + beforeEach(() => { + fileReadStream = new Readable(); + fileReadStream._read = util.noop; + + fileReadStream.on('end', () => { + fileReadStream.emit('complete'); + }); + + file.createReadStream = () => { + return fileReadStream; + }; + + originalSetEncryptionKey = file.setEncryptionKey; + file.setEncryptionKey = sinon.stub(); + }); + + afterEach(() => { + file.setEncryptionKey = originalSetEncryptionKey; + }); + + it('should accept just a callback', done => { + fileReadStream._read = () => { + done(); + }; + + file.download(assert.ifError); + }); + + it('should accept an options object and callback', done => { + fileReadStream._read = () => { + done(); + }; + + file.download({}, assert.ifError); + }); + + it('should not mutate options object after use', done => { + const optionsObject = {destination: './unknown.jpg'}; + fileReadStream._read = () => { + assert.strictEqual(optionsObject.destination, './unknown.jpg'); + assert.deepStrictEqual(optionsObject, {destination: './unknown.jpg'}); + done(); + }; + file.download(optionsObject, assert.ifError); + }); + + it('should pass the provided options to createReadStream', done => { + const readOptions = {start: 100, end: 200, destination: './unknown.jpg'}; + + file.createReadStream = (options: {}) => { + assert.deepStrictEqual(options, {start: 100, end: 200}); + assert.deepStrictEqual(readOptions, { + start: 100, + end: 200, + destination: './unknown.jpg', + }); + done(); + return fileReadStream; + }; + + file.download(readOptions, assert.ifError); + }); + + it('should call setEncryptionKey with the provided key and not pass it to createReadStream', done => { + const encryptionKey = Buffer.from('encryption-key'); + const downloadOptions = { + encryptionKey: encryptionKey, + userProject: 'user-project-id', + }; + + file.createReadStream = (options: {}) => { + assert.deepStrictEqual(options, {userProject: 'user-project-id'}); + return fileReadStream; + }; + + file.download(downloadOptions, (err: Error) => { + assert.ifError(err); + // Verify that setEncryptionKey was called with the correct key + assert.ok( + (file.setEncryptionKey as sinon.SinonStub).calledWith(encryptionKey) + ); + done(); + }); + + fileReadStream.push('some data'); + fileReadStream.push(null); + }); + + it('should only execute callback once', done => { + Object.assign(fileReadStream, { + _read(this: Readable) { + // Do not fire the errors immediately as this is a synchronous operation here + // and the iterator getter is also synchronous in file.getBufferFromReadable. + // this is only an issue for <= node 12. This cannot happen in practice. + process.nextTick(() => { + this.emit('error', new Error('Error.')); + this.emit('error', new Error('Error.')); + }); + }, + }); + + file.download(() => { + done(); + }); + }); + + describe('into memory', () => { + it('should buffer a file into memory if no destination', done => { + const fileContents = 'abcdefghijklmnopqrstuvwxyz'; + + Object.assign(fileReadStream, { + _read(this: Readable) { + this.push(fileContents); + this.push(null); + }, + }); + + file.download((err: Error, remoteFileContents: {}) => { + assert.ifError(err); + + assert.strictEqual(fileContents, remoteFileContents.toString()); + done(); + }); + }); + + it('should execute callback with error', done => { + const error = new Error('Error.'); + + Object.assign(fileReadStream, { + _read(this: Readable) { + // Do not fire the errors immediately as this is a synchronous operation here + // and the iterator getter is also synchronous in file.getBufferFromReadable. + // this is only an issue for <= node 12. This cannot happen in practice. + process.nextTick(() => { + this.emit('error', error); + }); + }, + }); + + file.download((err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('with destination', () => { + const sandbox = sinon.createSandbox(); + + afterEach(() => { + sandbox.restore(); + }); + + it('should write the file to a destination if provided', done => { + tmp.setGracefulCleanup(); + tmp.file((err, tmpFilePath) => { + assert.ifError(err); + + const fileContents = 'abcdefghijklmnopqrstuvwxyz'; + + Object.assign(fileReadStream, { + _read(this: Readable) { + this.push(fileContents); + this.push(null); + }, + }); + + file.download({destination: tmpFilePath}, (err: Error) => { + assert.ifError(err); + + fs.readFile(tmpFilePath, (err, tmpFileContents) => { + assert.ifError(err); + + assert.strictEqual(fileContents, tmpFileContents.toString()); + done(); + }); + }); + }); + }); + + it('should process the entire stream', done => { + tmp.setGracefulCleanup(); + tmp.file(async (err, tmpFilePath) => { + assert.ifError(err); + + const fileContents = 'abcdefghijklmnopqrstuvwxyz'; + + fileReadStream.on('resume', () => { + fileReadStream.emit('data', fileContents); + fileReadStream.emit('data', fileContents); + setImmediate(() => { + fileReadStream.emit('end'); + }); + }); + + file.download({destination: tmpFilePath}, (err: Error) => { + assert.ifError(err); + fs.readFile(tmpFilePath, (err, tmpFileContents) => { + assert.ifError(err); + assert.strictEqual( + fileContents + fileContents, + tmpFileContents.toString() + ); + done(); + }); + }); + }); + }); + + it('empty file should be processed correctly', done => { + tmp.setGracefulCleanup(); + tmp.file(async (err, tmpFilePath) => { + assert.ifError(err); + + fileReadStream.on('resume', () => { + setImmediate(() => { + fileReadStream.emit('end'); + }); + }); + + file.download({destination: tmpFilePath}, (err: Error) => { + assert.ifError(err); + fs.readFile(tmpFilePath, (err, tmpFileContents) => { + assert.ifError(err); + assert.strictEqual('', tmpFileContents.toString()); + done(); + }); + }); + }); + }); + + it('file contents should remain unchanged if file nonexistent', done => { + tmp.setGracefulCleanup(); + tmp.file(async (err, tmpFilePath) => { + assert.ifError(err); + + const fileContents = 'file contents that should remain unchanged'; + fs.writeFileSync(tmpFilePath, fileContents, 'utf-8'); + + const error = new Error('Error.'); + fileReadStream.on('resume', () => { + setImmediate(() => { + fileReadStream.emit('error', error); + }); + }); + + file.download({destination: tmpFilePath}, (err: Error) => { + assert.strictEqual(err, error); + fs.readFile(tmpFilePath, (err, tmpFileContents) => { + assert.ifError(err); + assert.strictEqual(fileContents, tmpFileContents.toString()); + done(); + }); + }); + }); + }); + + it('should execute callback with error', done => { + tmp.setGracefulCleanup(); + tmp.file((err, tmpFilePath) => { + assert.ifError(err); + + const error = new Error('Error.'); + + Object.assign(fileReadStream, { + _read(this: Readable) { + this.emit('error', error); + }, + }); + + file.download({destination: tmpFilePath}, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + }); + + it('should fail if provided destination directory does not exist', done => { + tmp.setGracefulCleanup(); + tmp.dir(async (err, tmpDirPath) => { + assert.ifError(err); + + const fileContents = 'nested-abcdefghijklmnopqrstuvwxyz'; + + Object.assign(fileReadStream, { + _read(this: Readable) { + this.push(fileContents); + this.push(null); + }, + }); + + const nestedPath = path.join(tmpDirPath, 'a', 'b', 'c', 'file.txt'); + + file.download({destination: nestedPath}, (err: Error) => { + assert.ok(err); + done(); + }); + }); + }); + }); + }); + + describe('getExpirationDate', () => { + it('should refresh metadata', done => { + file.getMetadata = () => { + done(); + }; + + file.getExpirationDate(assert.ifError); + }); + + it('should return error from getMetadata', done => { + const error = new Error('Error.'); + const apiResponse = {}; + + file.getMetadata = (callback: Function) => { + callback(error, null, apiResponse); + }; + + file.getExpirationDate( + (err: Error, expirationDate: {}, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(expirationDate, null); + assert.strictEqual(apiResponse_, apiResponse); + done(); + } + ); + }); + + it('should return an error if there is no expiration time', done => { + const apiResponse = {}; + + file.getMetadata = (callback: Function) => { + callback(null, {}, apiResponse); + }; + + file.getExpirationDate( + (err: Error, expirationDate: {}, apiResponse_: {}) => { + assert.strictEqual( + err.message, + FileExceptionMessages.EXPIRATION_TIME_NA + ); + assert.strictEqual(expirationDate, null); + assert.strictEqual(apiResponse_, apiResponse); + done(); + } + ); + }); + + it('should return the expiration time as a Date object', done => { + const expirationTime = new Date(); + + const apiResponse = { + retentionExpirationTime: expirationTime.toJSON(), + }; + + file.getMetadata = (callback: Function) => { + callback(null, apiResponse, apiResponse); + }; + + file.getExpirationDate( + (err: Error, expirationDate: {}, apiResponse_: {}) => { + assert.ifError(err); + assert.deepStrictEqual(expirationDate, expirationTime); + assert.strictEqual(apiResponse_, apiResponse); + done(); + } + ); + }); + }); + + describe('generateSignedPostPolicyV2', () => { + let CONFIG: GenerateSignedPostPolicyV2Options; + + beforeEach(() => { + CONFIG = { + expires: Date.now() + 2000, + }; + + BUCKET.storage.authClient = { + sign: () => { + return Promise.resolve('signature'); + }, + }; + }); + + it('should create a signed policy', done => { + BUCKET.storage.authClient.sign = (blobToSign: string) => { + const policy = Buffer.from(blobToSign, 'base64').toString(); + assert.strictEqual(typeof JSON.parse(policy), 'object'); + return Promise.resolve('signature'); + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.generateSignedPostPolicyV2( + CONFIG, + (err: Error, signedPolicy: PolicyDocument) => { + assert.ifError(err); + assert.strictEqual(typeof signedPolicy.string, 'string'); + assert.strictEqual(typeof signedPolicy.base64, 'string'); + assert.strictEqual(typeof signedPolicy.signature, 'string'); + done(); + } + ); + }); + + it('should not modify the configuration object', done => { + const originalConfig = Object.assign({}, CONFIG); + + file.generateSignedPostPolicyV2(CONFIG, (err: Error) => { + assert.ifError(err); + assert.deepStrictEqual(CONFIG, originalConfig); + done(); + }); + }); + + it('should return an error if signBlob errors', done => { + const error = new Error('Error.'); + + BUCKET.storage.authClient.sign = () => { + return Promise.reject(error); + }; + + file.generateSignedPostPolicyV2(CONFIG, (err: Error) => { + assert.strictEqual(err.name, 'SigningError'); + assert.strictEqual(err.message, error.message); + done(); + }); + }); + + it('should add key equality condition', done => { + file.generateSignedPostPolicyV2( + CONFIG, + (err: Error, signedPolicy: PolicyDocument) => { + const conditionString = '["eq","$key","' + file.name + '"]'; + assert.ifError(err); + assert(signedPolicy.string.indexOf(conditionString) > -1); + done(); + } + ); + }); + + it('should add ACL condition', done => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + acl: '', + }, + (err: Error, signedPolicy: PolicyDocument) => { + const conditionString = '{"acl":""}'; + assert.ifError(err); + assert(signedPolicy.string.indexOf(conditionString) > -1); + done(); + } + ); + }); + + it('should add success redirect', done => { + const redirectUrl = 'http://redirect'; + + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + successRedirect: redirectUrl, + }, + (err: Error, signedPolicy: PolicyDocument) => { + assert.ifError(err); + + const policy = JSON.parse(signedPolicy.string); + + assert( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + policy.conditions.some((condition: any) => { + return condition.success_action_redirect === redirectUrl; + }) + ); + + done(); + } + ); + }); + + it('should add success status', done => { + const successStatus = '200'; + + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + successStatus, + }, + (err: Error, signedPolicy: PolicyDocument) => { + assert.ifError(err); + + const policy = JSON.parse(signedPolicy.string); + + assert( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + policy.conditions.some((condition: any) => { + return condition.success_action_status === successStatus; + }) + ); + + done(); + } + ); + }); + + describe('expires', () => { + it('should accept Date objects', done => { + const expires = new Date(Date.now() + 1000 * 60); + + file.generateSignedPostPolicyV2( + { + expires, + }, + (err: Error, policy: PolicyDocument) => { + assert.ifError(err); + const expires_ = JSON.parse(policy.string).expiration; + assert.strictEqual(expires_, expires.toISOString()); + done(); + } + ); + }); + + it('should accept numbers', done => { + const expires = Date.now() + 1000 * 60; + + file.generateSignedPostPolicyV2( + { + expires, + }, + (err: Error, policy: PolicyDocument) => { + assert.ifError(err); + const expires_ = JSON.parse(policy.string).expiration; + assert.strictEqual(expires_, new Date(expires).toISOString()); + done(); + } + ); + }); + + it('should accept strings', done => { + const expires = '12-12-2099'; + + file.generateSignedPostPolicyV2( + { + expires, + }, + (err: Error, policy: PolicyDocument) => { + assert.ifError(err); + const expires_ = JSON.parse(policy.string).expiration; + assert.strictEqual(expires_, new Date(expires).toISOString()); + done(); + } + ); + }); + + it('should throw if a date is invalid', () => { + const expires = new Date('31-12-2019'); + + assert.throws(() => { + file.generateSignedPostPolicyV2( + { + expires, + }, + () => {} + ), + ExceptionMessages.EXPIRATION_DATE_INVALID; + }); + }); + + it('should throw if a date from the past is given', () => { + const expires = Date.now() - 5; + + assert.throws(() => { + file.generateSignedPostPolicyV2( + { + expires, + }, + () => {} + ), + ExceptionMessages.EXPIRATION_DATE_PAST; + }); + }); + }); + + describe('equality condition', () => { + it('should add equality conditions (array of arrays)', done => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + equals: [['$', '']], + }, + (err: Error, signedPolicy: PolicyDocument) => { + const conditionString = '["eq","$",""]'; + assert.ifError(err); + assert(signedPolicy.string.indexOf(conditionString) > -1); + done(); + } + ); + }); + + it('should add equality condition (array)', done => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + equals: ['$', ''], + }, + (err: Error, signedPolicy: PolicyDocument) => { + const conditionString = '["eq","$",""]'; + assert.ifError(err); + assert(signedPolicy.string.indexOf(conditionString) > -1); + done(); + } + ); + }); + + it('should throw if equal condition is not an array', () => { + assert.throws(() => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + equals: [{}], + }, + () => {} + ), + FileExceptionMessages.EQUALS_CONDITION_TWO_ELEMENTS; + }); + }); + + it('should throw if equal condition length is not 2', () => { + assert.throws(() => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + equals: [['1', '2', '3']], + }, + () => {} + ), + FileExceptionMessages.EQUALS_CONDITION_TWO_ELEMENTS; + }); + }); + }); + + describe('prefix conditions', () => { + it('should add prefix conditions (array of arrays)', done => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + startsWith: [['$', '']], + }, + (err: Error, signedPolicy: PolicyDocument) => { + const conditionString = '["starts-with","$",""]'; + assert.ifError(err); + assert(signedPolicy.string.indexOf(conditionString) > -1); + done(); + } + ); + }); + + it('should add prefix condition (array)', done => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + startsWith: ['$', ''], + }, + (err: Error, signedPolicy: PolicyDocument) => { + const conditionString = '["starts-with","$",""]'; + assert.ifError(err); + assert(signedPolicy.string.indexOf(conditionString) > -1); + done(); + } + ); + }); + + it('should throw if prefix condition is not an array', () => { + assert.throws(() => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + startsWith: [{}], + }, + () => {} + ), + FileExceptionMessages.STARTS_WITH_TWO_ELEMENTS; + }); + }); + + it('should throw if prefix condition length is not 2', () => { + assert.throws(() => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + startsWith: [['1', '2', '3']], + }, + () => {} + ), + FileExceptionMessages.STARTS_WITH_TWO_ELEMENTS; + }); + }); + }); + + describe('content length', () => { + it('should add content length condition', done => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + contentLengthRange: {min: 0, max: 1}, + }, + (err: Error, signedPolicy: PolicyDocument) => { + const conditionString = '["content-length-range",0,1]'; + assert.ifError(err); + assert(signedPolicy.string.indexOf(conditionString) > -1); + done(); + } + ); + }); + + it('should throw if content length has no min', () => { + assert.throws(() => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + contentLengthRange: [{max: 1}], + }, + () => {} + ), + FileExceptionMessages.CONTENT_LENGTH_RANGE_MIN_MAX; + }); + }); + + it('should throw if content length has no max', () => { + assert.throws(() => { + file.generateSignedPostPolicyV2( + { + expires: Date.now() + 2000, + contentLengthRange: [{min: 0}], + }, + () => {} + ), + FileExceptionMessages.CONTENT_LENGTH_RANGE_MIN_MAX; + }); + }); + }); + }); + + describe('generateSignedPostPolicyV4', () => { + let CONFIG: GenerateSignedPostPolicyV4Options; + + const NOW = new Date('2020-01-01'); + const CLIENT_EMAIL = 'test@domain.com'; + const SIGNATURE = 'signature'; + + let fakeTimer: sinon.SinonFakeTimers; + let sandbox: sinon.SinonSandbox; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + fakeTimer = sinon.useFakeTimers(NOW); + CONFIG = { + expires: NOW.valueOf() + 2000, + }; + + BUCKET.storage.authClient = { + sign: sandbox.stub().resolves(SIGNATURE), + getCredentials: sandbox.stub().resolves({client_email: CLIENT_EMAIL}), + }; + }); + + afterEach(() => { + sandbox.restore(); + fakeTimer.restore(); + }); + + const fieldsToConditions = (fields: object) => + Object.entries(fields).map(([k, v]) => ({[k]: v})); + + it('should create a signed policy', done => { + CONFIG.fields = { + 'x-goog-meta-foo': 'bar', + }; + + const requiredFields = { + key: file.name, + 'x-goog-date': '20200101T000000Z', + 'x-goog-credential': `${CLIENT_EMAIL}/20200101/auto/storage/goog4_request`, + 'x-goog-algorithm': 'GOOG4-RSA-SHA256', + }; + + const policy = { + conditions: [ + ...fieldsToConditions(CONFIG.fields), + {bucket: BUCKET.name}, + ...fieldsToConditions(requiredFields), + ], + expiration: formatAsUTCISO(new Date(CONFIG.expires), true, '-', ':'), + }; + + const policyString = JSON.stringify(policy); + const EXPECTED_POLICY = Buffer.from(policyString).toString('base64'); + const EXPECTED_SIGNATURE = Buffer.from(SIGNATURE, 'base64').toString( + 'hex' + ); + const EXPECTED_FIELDS = { + ...CONFIG.fields, + ...requiredFields, + 'x-goog-signature': EXPECTED_SIGNATURE, + policy: EXPECTED_POLICY, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + assert(res.url, `${STORAGE_POST_POLICY_BASE_URL}/${BUCKET.name}`); + + assert.deepStrictEqual(res.fields, EXPECTED_FIELDS); + + const signStub = BUCKET.storage.authClient.sign; + assert.deepStrictEqual( + Buffer.from(signStub.getCall(0).args[0], 'base64').toString(), + policyString + ); + + done(); + } + ); + }); + + it('should not modify the configuration object', done => { + const originalConfig = Object.assign({}, CONFIG); + + file.generateSignedPostPolicyV4(CONFIG, (err: Error) => { + assert.ifError(err); + assert.deepStrictEqual(CONFIG, originalConfig); + done(); + }); + }); + + it('should return an error if signBlob errors', done => { + const error = new Error('Error.'); + + BUCKET.storage.authClient.sign.rejects(error); + + file.generateSignedPostPolicyV4(CONFIG, (err: Error) => { + assert.strictEqual(err.name, 'SigningError'); + assert.strictEqual(err.message, error.message); + done(); + }); + }); + + it('should add key condition', done => { + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + + assert.strictEqual(res.fields['key'], file.name); + const EXPECTED_POLICY_ELEMENT = `{"key":"${file.name}"}`; + assert( + Buffer.from(res.fields.policy, 'base64') + .toString('utf-8') + .includes(EXPECTED_POLICY_ELEMENT) + ); + done(); + } + ); + }); + + it('should include fields in conditions', done => { + CONFIG = { + fields: { + 'x-goog-meta-foo': 'bar', + }, + ...CONFIG, + }; + + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + + const expectedConditionString = JSON.stringify(CONFIG.fields); + assert.strictEqual(res.fields['x-goog-meta-foo'], 'bar'); + const decodedPolicy = Buffer.from( + res.fields.policy, + 'base64' + ).toString('utf-8'); + assert(decodedPolicy.includes(expectedConditionString)); + done(); + } + ); + }); + + it('should encode special characters in policy', done => { + CONFIG = { + fields: { + 'x-goog-meta-foo': 'bår', + }, + ...CONFIG, + }; + + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + + assert.strictEqual(res.fields['x-goog-meta-foo'], 'bår'); + const decodedPolicy = Buffer.from( + res.fields.policy, + 'base64' + ).toString('utf-8'); + assert(decodedPolicy.includes('"x-goog-meta-foo":"b\\u00e5r"')); + done(); + } + ); + }); + + it('should not include fields with x-ignore- prefix in conditions', done => { + CONFIG = { + fields: { + 'x-ignore-foo': 'bar', + }, + ...CONFIG, + }; + + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + + const expectedConditionString = JSON.stringify(CONFIG.fields); + assert.strictEqual(res.fields['x-ignore-foo'], 'bar'); + const decodedPolicy = Buffer.from( + res.fields.policy, + 'base64' + ).toString('utf-8'); + assert(!decodedPolicy.includes(expectedConditionString)); + + const signStub = BUCKET.storage.authClient.sign; + assert(!signStub.getCall(0).args[0].includes('x-ignore-foo')); + done(); + } + ); + }); + + it('should accept conditions', done => { + CONFIG = { + conditions: [['starts-with', '$key', 'prefix-']], + ...CONFIG, + }; + + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + + const expectedConditionString = JSON.stringify(CONFIG.conditions); + const decodedPolicy = Buffer.from( + res.fields.policy, + 'base64' + ).toString('utf-8'); + assert(decodedPolicy.includes(expectedConditionString)); + + const signStub = BUCKET.storage.authClient.sign; + assert( + !signStub.getCall(0).args[0].includes(expectedConditionString) + ); + done(); + } + ); + }); + + it('should output url with cname', done => { + CONFIG.bucketBoundHostname = 'http://domain.tld'; + + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + assert(res.url, CONFIG.bucketBoundHostname); + done(); + } + ); + }); + + it('should output a virtualHostedStyle url', done => { + CONFIG.virtualHostedStyle = true; + + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + assert(res.url, `https://${BUCKET.name}.storage.googleapis.com/`); + done(); + } + ); + }); + + it('should prefer a customEndpoint > virtualHostedStyle, cname', done => { + const customEndpoint = 'https://my-custom-endpoint.com'; + + STORAGE.apiEndpoint = customEndpoint; + STORAGE.customEndpoint = true; + + CONFIG.virtualHostedStyle = true; + CONFIG.bucketBoundHostname = 'http://domain.tld'; + + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + assert.ifError(err); + assert(res.url, `https://${BUCKET.name}.storage.googleapis.com/`); + done(); + } + ); + }); + + it('should append bucket name to the URL when using the emulator', done => { + const emulatorHost = 'http://127.0.0.1:9199'; + const originalApiEndpoint = STORAGE.apiEndpoint; + const originalCustomEndpoint = STORAGE.customEndpoint; + const originalEnvHost = process.env.STORAGE_EMULATOR_HOST; + + process.env.STORAGE_EMULATOR_HOST = emulatorHost; + STORAGE.apiEndpoint = emulatorHost; + STORAGE.customEndpoint = true; + + file.generateSignedPostPolicyV4( + CONFIG, + (err: Error, res: SignedPostPolicyV4Output) => { + STORAGE.apiEndpoint = originalApiEndpoint; + STORAGE.customEndpoint = originalCustomEndpoint; + if (originalEnvHost) { + process.env.STORAGE_EMULATOR_HOST = originalEnvHost; + } else { + delete process.env.STORAGE_EMULATOR_HOST; + } + + assert.ifError(err); + assert.strictEqual(res.url, `${emulatorHost}/${BUCKET.name}`); + done(); + } + ); + }); + + describe('expires', () => { + it('should accept Date objects', done => { + const expires = new Date(Date.now() + 1000 * 60); + + file.generateSignedPostPolicyV4( + { + expires, + }, + (err: Error, response: SignedPostPolicyV4Output) => { + assert.ifError(err); + const policy = JSON.parse( + Buffer.from(response.fields.policy, 'base64').toString() + ); + assert.strictEqual( + policy.expiration, + formatAsUTCISO(expires, true, '-', ':') + ); + done(); + } + ); + }); + + it('should accept numbers', done => { + const expires = Date.now() + 1000 * 60; + + file.generateSignedPostPolicyV4( + { + expires, + }, + (err: Error, response: SignedPostPolicyV4Output) => { + assert.ifError(err); + const policy = JSON.parse( + Buffer.from(response.fields.policy, 'base64').toString() + ); + assert.strictEqual( + policy.expiration, + formatAsUTCISO(new Date(expires), true, '-', ':') + ); + done(); + } + ); + }); + + it('should accept strings', done => { + const expires = formatAsUTCISO( + new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), + false, + '-' + ); + + file.generateSignedPostPolicyV4( + { + expires, + }, + (err: Error, response: SignedPostPolicyV4Output) => { + assert.ifError(err); + const policy = JSON.parse( + Buffer.from(response.fields.policy, 'base64').toString() + ); + assert.strictEqual( + policy.expiration, + formatAsUTCISO(new Date(expires), true, '-', ':') + ); + done(); + } + ); + }); + + it('should throw if a date is invalid', () => { + const expires = new Date('31-12-2019'); + + assert.throws(() => { + file.generateSignedPostPolicyV4( + { + expires, + }, + () => {} + ), + ExceptionMessages.EXPIRATION_DATE_INVALID; + }); + }); + + it('should throw if a date from the past is given', () => { + const expires = Date.now() - 5; + + assert.throws(() => { + file.generateSignedPostPolicyV4( + { + expires, + }, + () => {} + ), + ExceptionMessages.EXPIRATION_DATE_PAST; + }); + }); + + it('should throw if a date beyond 7 days is given', () => { + const expires = Date.now() + 7.1 * 24 * 60 * 60 * 1000; + + assert.throws(() => { + file.generateSignedPostPolicyV4( + { + expires, + }, + () => {} + ), + {message: 'Max allowed expiration is seven days (604800 seconds).'}; + }); + }); + }); + }); + + describe('getSignedUrl', () => { + const EXPECTED_SIGNED_URL = 'signed-url'; + const CNAME = 'https://www.example.com'; + + let sandbox: sinon.SinonSandbox; + let signer: {getSignedUrl: Function}; + let signerGetSignedUrlStub: sinon.SinonStub; + let urlSignerStub: sinon.SinonStub; + let SIGNED_URL_CONFIG: GetSignedUrlConfig; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + + signerGetSignedUrlStub = sandbox.stub().resolves(EXPECTED_SIGNED_URL); + + signer = { + getSignedUrl: signerGetSignedUrlStub, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + urlSignerStub = (sandbox.stub as any)(fakeSigner, 'URLSigner').returns( + signer + ); + + SIGNED_URL_CONFIG = { + version: 'v4', + expires: new Date(), + action: 'read', + cname: CNAME, + }; + }); + + afterEach(() => sandbox.restore()); + + it('should construct a URLSigner and call getSignedUrl', done => { + const accessibleAtDate = new Date(); + const config = { + contentMd5: 'md5-hash', + contentType: 'application/json', + accessibleAt: accessibleAtDate, + virtualHostedStyle: true, + ...SIGNED_URL_CONFIG, + }; + // assert signer is lazily-initialized. + assert.strictEqual(file.signer, undefined); + file.getSignedUrl(config, (err: Error | null, signedUrl: string) => { + assert.ifError(err); + assert.strictEqual(file.signer, signer); + assert.strictEqual(signedUrl, EXPECTED_SIGNED_URL); + + const ctorArgs = urlSignerStub.getCall(0).args; + assert.strictEqual(ctorArgs[0], file.storage.authClient); + assert.strictEqual(ctorArgs[1], file.bucket); + assert.strictEqual(ctorArgs[2], file); + + const getSignedUrlArgs = signerGetSignedUrlStub.getCall(0).args; + assert.deepStrictEqual(getSignedUrlArgs[0], { + method: 'GET', + version: 'v4', + expires: config.expires, + accessibleAt: accessibleAtDate, + extensionHeaders: {}, + host: undefined, + queryParams: {}, + contentMd5: config.contentMd5, + contentType: config.contentType, + cname: CNAME, + virtualHostedStyle: true, + }); + done(); + }); + }); + + it('should add "x-goog-resumable: start" header if action is resumable', done => { + SIGNED_URL_CONFIG.action = 'resumable'; + SIGNED_URL_CONFIG.extensionHeaders = { + 'another-header': 'value', + }; + + file.getSignedUrl(SIGNED_URL_CONFIG, (err: Error | null) => { + assert.ifError(err); + const getSignedUrlArgs = signerGetSignedUrlStub.getCall(0).args; + assert.strictEqual(getSignedUrlArgs[0]['method'], 'POST'); + assert.deepStrictEqual(getSignedUrlArgs[0]['extensionHeaders'], { + 'another-header': 'value', + 'x-goog-resumable': 'start', + }); + done(); + }); + }); + + it('should add response-content-type query parameter', done => { + SIGNED_URL_CONFIG.responseType = 'application/json'; + file.getSignedUrl(SIGNED_URL_CONFIG, (err: Error | null) => { + assert.ifError(err); + const getSignedUrlArgs = signerGetSignedUrlStub.getCall(0).args; + assert.deepStrictEqual(getSignedUrlArgs[0]['queryParams'], { + 'response-content-type': 'application/json', + }); + done(); + }); + }); + + it('should respect promptSaveAs argument', done => { + const filename = 'fname.txt'; + SIGNED_URL_CONFIG.promptSaveAs = filename; + file.getSignedUrl(SIGNED_URL_CONFIG, (err: Error | null) => { + assert.ifError(err); + const getSignedUrlArgs = signerGetSignedUrlStub.getCall(0).args; + assert.deepStrictEqual(getSignedUrlArgs[0]['queryParams'], { + 'response-content-disposition': + 'attachment; filename="' + filename + '"', + }); + done(); + }); + }); + + it('should add response-content-disposition query parameter', done => { + const disposition = 'attachment; filename="fname.ext"'; + SIGNED_URL_CONFIG.responseDisposition = disposition; + file.getSignedUrl(SIGNED_URL_CONFIG, (err: Error | null) => { + assert.ifError(err); + const getSignedUrlArgs = signerGetSignedUrlStub.getCall(0).args; + assert.deepStrictEqual(getSignedUrlArgs[0]['queryParams'], { + 'response-content-disposition': disposition, + }); + done(); + }); + }); + + it('should ignore promptSaveAs if set', done => { + const saveAs = 'fname2.ext'; + const disposition = 'attachment; filename="fname.ext"'; + SIGNED_URL_CONFIG.promptSaveAs = saveAs; + SIGNED_URL_CONFIG.responseDisposition = disposition; + + file.getSignedUrl(SIGNED_URL_CONFIG, (err: Error | null) => { + assert.ifError(err); + const getSignedUrlArgs = signerGetSignedUrlStub.getCall(0).args; + assert.deepStrictEqual(getSignedUrlArgs[0]['queryParams'], { + 'response-content-disposition': disposition, + }); + done(); + }); + }); + + it('should add generation to query parameter', done => { + file.generation = '246680131'; + + file.getSignedUrl(SIGNED_URL_CONFIG, (err: Error | null) => { + assert.ifError(err); + const getSignedUrlArgs = signerGetSignedUrlStub.getCall(0).args; + assert.deepStrictEqual(getSignedUrlArgs[0]['queryParams'], { + generation: file.generation, + }); + done(); + }); + }); + }); + + describe('makePrivate', () => { + it('should execute callback with API response', done => { + const apiResponse = {}; + + file.setMetadata = ( + metadata: FileMetadata, + optionsOrCallback: SetMetadataOptions | MetadataCallback, + cb: MetadataCallback + ) => { + Promise.resolve([apiResponse]).then(resp => cb(null, ...resp)); + }; + + file.makePrivate((err: Error, apiResponse_: {}) => { + assert.ifError(err); + assert.strictEqual(apiResponse_, apiResponse); + + done(); + }); + }); + + it('should make the file private to project by default', done => { + file.setMetadata = (metadata: {}, query: {}) => { + assert.deepStrictEqual(metadata, {acl: null}); + assert.deepStrictEqual(query, {predefinedAcl: 'projectPrivate'}); + done(); + }; + + file.makePrivate(util.noop); + }); + + it('should make the file private to user if strict = true', done => { + file.setMetadata = (metadata: {}, query: {}) => { + assert.deepStrictEqual(query, {predefinedAcl: 'private'}); + done(); + }; + + file.makePrivate({strict: true}, util.noop); + }); + + it('should accept metadata', done => { + const options = { + metadata: {a: 'b', c: 'd'}, + }; + file.setMetadata = (metadata: {}) => { + assert.deepStrictEqual(metadata, { + acl: null, + ...options.metadata, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.strictEqual(typeof (options.metadata as any).acl, 'undefined'); + done(); + }; + file.makePrivate(options, assert.ifError); + }); + + it('should accept userProject', done => { + const options = { + userProject: 'user-project-id', + }; + + file.setMetadata = (metadata: {}, query: SetFileMetadataOptions) => { + assert.strictEqual(query.userProject, options.userProject); + done(); + }; + + file.makePrivate(options, assert.ifError); + }); + }); + + describe('makePublic', () => { + it('should execute callback', done => { + file.acl.add = (options: {}, callback: Function) => { + callback(); + }; + + file.makePublic(done); + }); + + it('should make the file public', done => { + file.acl.add = (options: {}) => { + assert.deepStrictEqual(options, {entity: 'allUsers', role: 'READER'}); + done(); + }; + + file.makePublic(util.noop); + }); + }); + + describe('publicUrl', () => { + it('should return the public URL', done => { + const NAME = 'file-name'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + ); + done(); + }); + + it('with slash in the name', done => { + const NAME = 'parent/child'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + ); + done(); + }); + + it('with tilde in the name', done => { + const NAME = 'foo~bar'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + ); + done(); + }); + + it('with non ascii in the name', done => { + const NAME = '\u2603'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + ); + done(); + }); + + it('with an ampersand in the name', done => { + const NAME = '&foo'; + const file = new File(BUCKET, NAME); + assert.strictEqual( + file.publicUrl(), + `https://storage.googleapis.com/bucket-name/${encodeURIComponent(NAME)}` + ); + done(); + }); + }); + + describe('isPublic', () => { + const sandbox = sinon.createSandbox(); + + afterEach(() => sandbox.restore()); + + it('should execute callback with `true` in response', done => { + file.isPublic((err: ApiError, resp: boolean) => { + assert.ifError(err); + assert.strictEqual(resp, true); + done(); + }); + }); + + it('should execute callback with `false` in response', done => { + fakeUtil.makeRequest = function ( + reqOpts: DecorateRequestOptions, + config: object, + callback: BodyResponseCallback + ) { + const error = new ApiError('Permission Denied.'); + error.code = 403; + callback(error); + }; + file.isPublic((err: ApiError, resp: boolean) => { + assert.ifError(err); + assert.strictEqual(resp, false); + done(); + }); + }); + + it('should propagate non-403 errors to user', done => { + const error = new ApiError('400 Error.'); + error.code = 400; + fakeUtil.makeRequest = function ( + reqOpts: DecorateRequestOptions, + config: object, + callback: BodyResponseCallback + ) { + callback(error); + }; + file.isPublic((err: ApiError) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should correctly send a GET request', done => { + fakeUtil.makeRequest = function ( + reqOpts: DecorateRequestOptions, + config: object, + callback: BodyResponseCallback + ) { + assert.strictEqual(reqOpts.method, 'GET'); + callback(null); + }; + file.isPublic((err: ApiError) => { + assert.ifError(err); + done(); + }); + }); + + it('should correctly format URL in the request', done => { + file = new File(BUCKET, 'my#file$.png'); + const expectedURL = `https://storage.googleapis.com/${ + BUCKET.name + }/${encodeURIComponent(file.name)}`; + + fakeUtil.makeRequest = function ( + reqOpts: DecorateRequestOptions, + config: object, + callback: BodyResponseCallback + ) { + assert.strictEqual(reqOpts.uri, expectedURL); + callback(null); + }; + file.isPublic((err: ApiError) => { + assert.ifError(err); + done(); + }); + }); + + it('should not set any headers when there are no interceptors', done => { + fakeUtil.makeRequest = function ( + reqOpts: DecorateRequestOptions, + config: object, + callback: BodyResponseCallback + ) { + assert.deepStrictEqual(reqOpts.headers, {}); + callback(null); + }; + file.isPublic((err: ApiError) => { + assert.ifError(err); + done(); + }); + }); + + it('should set headers when an interceptor is defined', done => { + const expectedHeader = {hello: 'world'}; + file.storage.interceptors = []; + file.storage.interceptors.push({ + request: (requestConfig: DecorateRequestOptions) => { + requestConfig.headers = requestConfig.headers || {}; + Object.assign(requestConfig.headers, expectedHeader); + return requestConfig as DecorateRequestOptions; + }, + }); + + fakeUtil.makeRequest = function ( + reqOpts: DecorateRequestOptions, + config: object, + callback: BodyResponseCallback + ) { + assert.deepStrictEqual(reqOpts.headers, expectedHeader); + callback(null); + }; + file.isPublic((err: ApiError) => { + assert.ifError(err); + done(); + }); + }); + }); + + describe('moveFileAtomic', () => { + function assertmoveFileAtomic( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file: any, + expectedDestination: string, + callback: Function + ) { + file.moveFileAtomic = (destination: string) => { + assert.strictEqual(destination, expectedDestination); + callback(); + }; + } + + it('should throw if no destination is provided', () => { + assert.throws(() => { + file.moveFileAtomic(); + }, /Destination file should have a name\./); + }); + + it('should URI encode file names', done => { + const newFile = new File(BUCKET, 'nested/file.jpg'); + + const expectedPath = `/moveTo/o/${encodeURIComponent(newFile.name)}`; + + directoryFile.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, expectedPath); + done(); + }; + + directoryFile.moveFileAtomic(newFile); + }); + + it('should call moveFileAtomic with string', done => { + const newFileName = 'new-file-name.png'; + assertmoveFileAtomic(file, newFileName, done); + file.moveFileAtomic(newFileName); + }); + + it('should call moveFileAtomic with File', done => { + const newFile = new File(BUCKET, 'new-file'); + assertmoveFileAtomic(file, newFile, done); + file.moveFileAtomic(newFile); + }); + + it('should accept an options object', done => { + const newFile = new File(BUCKET, 'name'); + const options = {}; + + file.moveFileAtomic = (destination: {}, options_: {}) => { + assert.strictEqual(options_, options); + done(); + }; + + file.moveFileAtomic(newFile, options, assert.ifError); + }); + + it('should execute callback with error & API response', done => { + const error = new Error('Error.'); + const apiResponse = {}; + + const newFile = new File(BUCKET, 'new-file'); + + file.request = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(error, apiResponse); + }; + + file.moveFileAtomic(newFile, (err: Error, file: {}, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(file, null); + assert.strictEqual(apiResponse_, apiResponse); + + done(); + }); + }); + + it('should pass through userProject', done => { + const options = { + userProject: 'user-project', + }; + const originalOptions = Object.assign({}, options); + const newFile = new File(BUCKET, 'new-file'); + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.userProject, options.userProject); + assert.strictEqual(reqOpts.json.userProject, undefined); + assert.deepStrictEqual(options, originalOptions); + done(); + }; + + file.moveFileAtomic(newFile, options, assert.ifError); + }); + + it('should handle optionsOrCallback being the options', done => { + const options = { + preconditionOpts: {ifGenerationMatch: 123}, + }; + const originalOptions = Object.assign({}, options); + const newFile = new File(BUCKET, 'new-file'); + + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.qs.ifGenerationMatch, + options.preconditionOpts.ifGenerationMatch + ); + assert.strictEqual(reqOpts.json.userProject, undefined); + assert.deepStrictEqual(options, originalOptions); + done(); + }; + + file.moveFileAtomic(newFile, options, assert.ifError); + }); + + describe('destination types', () => { + function assertPathEquals( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file: any, + expectedPath: string, + callback: Function + ) { + file.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, expectedPath); + callback(); + }; + } + + it('should allow a string', done => { + const newFileName = 'new-file-name.png'; + const newFile = new File(BUCKET, newFileName); + const expectedPath = `/moveTo/o/${newFile.name}`; + assertPathEquals(file, expectedPath, done); + file.moveFileAtomic(newFileName); + }); + + it('should allow a string with leading slash.', done => { + const newFileName = '/new-file-name.png'; + const newFile = new File(BUCKET, newFileName); + const expectedPath = `/moveTo/o/${encodeURIComponent(newFile.name)}`; + assertPathEquals(file, expectedPath, done); + file.moveFileAtomic(newFileName); + }); + + it('should allow a "gs://..." string', done => { + const newFileName = 'gs://other-bucket/new-file-name.png'; + const expectedPath = '/moveTo/o/new-file-name.png'; + assertPathEquals(file, expectedPath, done); + file.moveFileAtomic(newFileName); + }); + + it('should allow a File', done => { + const newFile = new File(BUCKET, 'new-file'); + const expectedPath = `/moveTo/o/${newFile.name}`; + assertPathEquals(file, expectedPath, done); + file.moveFileAtomic(newFile); + }); + + it('should throw if a destination cannot be parsed', () => { + assert.throws(() => { + file.moveFileAtomic(() => {}); + }, /Destination file should have a name\./); + }); + }); + + describe('returned File object', () => { + beforeEach(() => { + const resp = {success: true}; + file.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, resp); + }; + }); + + it('should re-use file object if one is provided', done => { + const newFile = new File(BUCKET, 'new-file'); + file.moveFileAtomic(newFile, (err: Error, copiedFile: {}) => { + assert.ifError(err); + assert.deepStrictEqual(copiedFile, newFile); + done(); + }); + }); + + it('should create new file on the same bucket', done => { + const newFilename = 'new-filename'; + file.moveFileAtomic(newFilename, (err: Error, copiedFile: File) => { + assert.ifError(err); + assert.strictEqual(copiedFile.bucket.name, BUCKET.name); + assert.strictEqual(copiedFile.name, newFilename); + done(); + }); + }); + }); + }); + + describe('move', () => { + describe('copy to destination', () => { + function assertCopyFile( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file: any, + expectedDestination: string, + callback: Function + ) { + file.copy = (destination: string) => { + assert.strictEqual(destination, expectedDestination); + callback(); + }; + } + + it('should call copy with string', done => { + const newFileName = 'new-file-name.png'; + assertCopyFile(file, newFileName, done); + file.move(newFileName); + }); + + it('should call copy with Bucket', done => { + assertCopyFile(file, BUCKET, done); + file.move(BUCKET); + }); + + it('should call copy with File', done => { + const newFile = new File(BUCKET, 'new-file'); + assertCopyFile(file, newFile, done); + file.move(newFile); + }); + + it('should accept an options object', done => { + const newFile = new File(BUCKET, 'name'); + const options = {}; + + file.copy = (destination: {}, options_: {}) => { + assert.strictEqual(options_, options); + done(); + }; + + file.move(newFile, options, assert.ifError); + }); + + it('should fail if copy fails', done => { + const originalErrorMessage = 'Original error message.'; + const error = new Error(originalErrorMessage); + file.copy = (destination: {}, options: {}, callback: Function) => { + callback(error); + }; + file.move('new-filename', (err: Error) => { + assert.strictEqual(err, error); + assert.strictEqual( + err.message, + `file#copy failed with an error - ${originalErrorMessage}` + ); + done(); + }); + }); + }); + + describe('delete original file', () => { + it('should call the callback with destinationFile and copyApiResponse', done => { + const copyApiResponse = {}; + const newFile = new File(BUCKET, 'new-filename'); + file.copy = (destination: {}, options: {}, callback: Function) => { + callback(null, newFile, copyApiResponse); + }; + file.delete = (_: {}, callback: Function) => { + callback(); + }; + + file.move( + 'new-filename', + (err: Error, destinationFile: File, apiResponse: {}) => { + assert.ifError(err); + assert.strictEqual(destinationFile, newFile); + assert.strictEqual(apiResponse, copyApiResponse); + done(); + } + ); + }); + + it('should delete if copy is successful', done => { + const destinationFile = {bucket: {}}; + file.copy = (destination: {}, options: {}, callback: Function) => { + callback(null, destinationFile); + }; + Object.assign(file, { + delete() { + assert.strictEqual(this, file); + done(); + }, + }); + file.move('new-filename'); + }); + + it('should not delete if copy fails', done => { + let deleteCalled = false; + file.copy = (destination: {}, options: {}, callback: Function) => { + callback(new Error('Error.')); + }; + file.delete = () => { + deleteCalled = true; + }; + file.move('new-filename', () => { + assert.strictEqual(deleteCalled, false); + done(); + }); + }); + + it('should not delete the destination is same as origin', done => { + file.request = (config: {}, callback: Function) => { + callback(null, {}); + }; + const stub = sinon.stub(file, 'delete'); + // destination is same bucket as object + file.move(BUCKET, (err: Error) => { + assert.ifError(err); + // destination is same file as object + file.move(file, (err: Error) => { + assert.ifError(err); + // destination is same file name as string + file.move(file.name, (err: Error) => { + assert.ifError(err); + assert.ok(stub.notCalled); + stub.reset(); + done(); + }); + }); + }); + }); + + it('should pass options to delete', done => { + const options = {}; + const destinationFile = {bucket: {}}; + + file.copy = (destination: {}, options: {}, callback: Function) => { + callback(null, destinationFile); + }; + + file.delete = (options_: {}) => { + assert.strictEqual(options_, options); + done(); + }; + + file.move('new-filename', options, assert.ifError); + }); + + it('should fail if delete fails', done => { + const originalErrorMessage = 'Original error message.'; + const error = new Error(originalErrorMessage); + const destinationFile = {bucket: {}}; + file.copy = (destination: {}, options: {}, callback: Function) => { + callback(null, destinationFile); + }; + file.delete = (options: {}, callback: Function) => { + callback(error); + }; + file.move('new-filename', (err: Error) => { + assert.strictEqual(err, error); + assert.strictEqual( + err.message, + `file#delete failed with an error - ${originalErrorMessage}` + ); + done(); + }); + }); + }); + }); + + describe('rename', () => { + it('should correctly call File#move', done => { + const newFileName = 'renamed-file.txt'; + const options = {}; + file.move = (dest: string, opts: MoveOptions, cb: Function) => { + assert.strictEqual(dest, newFileName); + assert.strictEqual(opts, options); + assert.strictEqual(cb, done); + cb(); + }; + file.rename(newFileName, options, done); + }); + + it('should accept File object', done => { + const newFileObject = new File(BUCKET, 'renamed-file.txt'); + const options = {}; + file.move = (dest: string, opts: MoveOptions, cb: Function) => { + assert.strictEqual(dest, newFileObject); + assert.strictEqual(opts, options); + assert.strictEqual(cb, done); + cb(); + }; + file.rename(newFileObject, options, done); + }); + + it('should not require options', done => { + file.move = (dest: string, opts: MoveOptions, cb: Function) => { + assert.deepStrictEqual(opts, {}); + cb(); + }; + file.rename('new-name', done); + }); + }); + + describe('restore', () => { + it('should pass options to underlying request call', async () => { + file.parent.request = function ( + reqOpts: DecorateRequestOptions, + callback_: Function + ) { + assert.strictEqual(this, file); + assert.deepStrictEqual(reqOpts, { + method: 'POST', + uri: '/restore', + qs: {generation: 123}, + }); + assert.strictEqual(callback_, undefined); + return []; + }; + + await file.restore({generation: 123}); + }); + }); + + describe('request', () => { + it('should call the parent request function', () => { + const options = {}; + const callback = () => {}; + const expectedReturnValue = {}; + + file.parent.request = function ( + reqOpts: DecorateRequestOptions, + callback_: Function + ) { + assert.strictEqual(this, file); + assert.strictEqual(reqOpts, options); + assert.strictEqual(callback_, callback); + return expectedReturnValue; + }; + + const returnedValue = file.request(options, callback); + assert.strictEqual(returnedValue, expectedReturnValue); + }); + }); + + describe('rotateEncryptionKey', () => { + it('should create new File correctly', done => { + const options = {}; + + file.bucket.file = (id: {}, options_: {}) => { + assert.strictEqual(id, file.id); + assert.strictEqual(options_, options); + done(); + }; + + file.rotateEncryptionKey(options, assert.ifError); + }); + + it('should default to customer-supplied encryption key', done => { + const encryptionKey = 'encryption-key'; + + file.bucket.file = (id: {}, options: FileOptions) => { + assert.strictEqual(options.encryptionKey, encryptionKey); + done(); + }; + + file.rotateEncryptionKey(encryptionKey, assert.ifError); + }); + + it('should accept a Buffer for customer-supplied encryption key', done => { + const encryptionKey = crypto.randomBytes(32); + + file.bucket.file = (id: {}, options: FileOptions) => { + assert.strictEqual(options.encryptionKey, encryptionKey); + done(); + }; + + file.rotateEncryptionKey(encryptionKey, assert.ifError); + }); + + it('should call copy correctly', done => { + const newFile = {}; + + file.bucket.file = () => { + return newFile; + }; + + file.copy = ( + destination: string, + options: object, + callback: Function + ) => { + assert.strictEqual(destination, newFile); + assert.deepStrictEqual(options, {}); + callback(); // done() + }; + + file.rotateEncryptionKey({}, done); + }); + }); + + describe('save', () => { + const DATA = 'Data!'; + const BUFFER_DATA = Buffer.from(DATA, 'utf8'); + const UINT8_ARRAY_DATA = Uint8Array.from( + Array.from(DATA).map(l => l.charCodeAt(0)) + ); + + class DelayedStreamNoError extends Transform { + _transform(chunk: string | Buffer, _encoding: string, done: Function) { + this.push(chunk); + setTimeout(() => { + done(); + }, 5); + } + } + + class DelayedStream500Error extends Transform { + retryCount: number; + constructor(retryCount: number) { + super(); + this.retryCount = retryCount; + } + _transform(chunk: string | Buffer, _encoding: string, done: Function) { + this.push(chunk); + setTimeout(() => { + if (this.retryCount === 1) { + done(new HTTPError('first error', 500)); + } else { + done(); + } + }, 5); + } + } + + describe('retry multipart upload', () => { + it('should save a string with no errors', async () => { + const options = {resumable: false}; + file.createWriteStream = () => { + return new DelayedStreamNoError(); + }; + await file.save(DATA, options, assert.ifError); + }); + + it('should save a buffer with no errors', async () => { + const options = {resumable: false}; + file.createWriteStream = () => { + return new DelayedStreamNoError(); + }; + await file.save(BUFFER_DATA, options, assert.ifError); + }); + + it('should save a Uint8Array with no errors', async () => { + const options = {resumable: false}; + file.createWriteStream = () => { + return new DelayedStreamNoError(); + }; + await file.save(UINT8_ARRAY_DATA, options, assert.ifError); + }); + + it('string upload should retry on first failure', async () => { + const options = { + resumable: false, + preconditionOpts: {ifGenerationMatch: 100}, + }; + let retryCount = 0; + file.createWriteStream = () => { + retryCount++; + return new DelayedStream500Error(retryCount); + }; + await file.save(DATA, options); + assert.ok(retryCount === 2); + }); + + it('string upload should not retry if nonretryable error code', async () => { + const options = {resumable: false}; + let retryCount = 0; + file.createWriteStream = () => { + class DelayedStream403Error extends Transform { + _transform( + chunk: string | Buffer, + _encoding: string, + done: Function + ) { + this.push(chunk); + setTimeout(() => { + retryCount++; + if (retryCount === 1) { + done(new HTTPError('first error', 403)); + } else { + done(); + } + }, 5); + } + } + return new DelayedStream403Error(); + }; + try { + await file.save(DATA, options); + throw Error('unreachable'); + } catch (e) { + assert.strictEqual((e as Error).message, 'first error'); + } + }); + + it('should save a Readable with no errors (String)', done => { + const options = {resumable: false}; + file.createWriteStream = () => { + const writeStream = new PassThrough(); + writeStream.on('data', data => { + assert.strictEqual(data.toString(), DATA); + }); + writeStream.once('finish', done); + return writeStream; + }; + + const readable = new Readable({ + read() { + this.push(DATA); + this.push(null); + }, + }); + + void file.save(readable, options); + }); + + it('should save a Readable with no errors (Buffer)', done => { + const options = {resumable: false}; + file.createWriteStream = () => { + const writeStream = new PassThrough(); + writeStream.on('data', data => { + assert.strictEqual(data.toString(), DATA); + }); + writeStream.once('finish', done); + return writeStream; + }; + + const readable = new Readable({ + read() { + this.push(BUFFER_DATA); + this.push(null); + }, + }); + + void file.save(readable, options); + }); + + it('should save a Readable with no errors (Uint8Array)', done => { + const options = {resumable: false}; + file.createWriteStream = () => { + const writeStream = new PassThrough(); + writeStream.on('data', data => { + assert.strictEqual(data.toString(), DATA); + }); + writeStream.once('finish', done); + return writeStream; + }; + + const readable = new Readable({ + read() { + this.push(UINT8_ARRAY_DATA); + this.push(null); + }, + }); + + void file.save(readable, options); + }); + + it('should propagate Readable errors', done => { + const options = {resumable: false}; + file.createWriteStream = () => { + const writeStream = new PassThrough(); + let errorCalled = false; + writeStream.on('data', data => { + assert.strictEqual(data.toString(), DATA); + }); + writeStream.on('error', err => { + errorCalled = true; + assert.strictEqual(err.message, 'Error!'); + }); + writeStream.on('finish', () => { + assert.ok(errorCalled); + }); + return writeStream; + }; + + const readable = new Readable({ + read() { + setTimeout(() => { + this.push(DATA); + this.destroy(new Error('Error!')); + }, 50); + }, + }); + + file.save(readable, options, (err: Error) => { + assert.strictEqual(err.message, 'Error!'); + done(); + }); + }); + + it('Readable upload should not retry', async () => { + const options = {resumable: false}; + + let retryCount = 0; + + file.createWriteStream = () => { + retryCount++; + return new Transform({ + transform( + chunk: string | Buffer, + _encoding: string, + done: Function + ) { + this.push(chunk); + setTimeout(() => { + done(new HTTPError('retryable error', 408)); + }, 5); + }, + }); + }; + try { + const readable = new Readable({ + read() { + this.push(DATA); + this.push(null); + }, + }); + + await file.save(readable, options); + throw Error('unreachable'); + } catch (e) { + assert.strictEqual((e as Error).message, 'retryable error'); + assert.ok(retryCount === 1); + } + }); + + it('should save a generator with no error', done => { + const options = {resumable: false}; + file.createWriteStream = () => { + const writeStream = new PassThrough(); + writeStream.on('data', data => { + assert.strictEqual(data.toString(), DATA); + done(); + }); + return writeStream; + }; + + const generator = async function* (arg?: {signal?: AbortSignal}) { + await new Promise(resolve => setTimeout(resolve, 5)); + if (arg?.signal?.aborted) return; + yield DATA; + }; + + void file.save(generator, options); + }); + + it('should propagate async iterable errors', done => { + const options = {resumable: false}; + file.createWriteStream = () => { + const writeStream = new PassThrough(); + let errorCalled = false; + writeStream.on('data', data => { + assert.strictEqual(data.toString(), DATA); + }); + writeStream.on('error', err => { + errorCalled = true; + assert.strictEqual(err.message, 'Error!'); + }); + writeStream.on('finish', () => { + assert.ok(errorCalled); + }); + return writeStream; + }; + + const generator = async function* () { + yield DATA; + throw new Error('Error!'); + }; + + file.save(generator(), options, (err: Error) => { + assert.strictEqual(err.message, 'Error!'); + done(); + }); + }); + + it('buffer upload should retry on first failure', async () => { + const options = { + resumable: false, + preconditionOpts: {ifGenerationMatch: 100}, + }; + let retryCount = 0; + file.createWriteStream = () => { + retryCount++; + return new DelayedStream500Error(retryCount); + }; + await file.save(BUFFER_DATA, options); + assert.ok(retryCount === 2); + }); + + it('resumable upload should retry', async () => { + const options = { + resumable: true, + preconditionOpts: {ifGenerationMatch: 100}, + }; + let retryCount = 0; + file.createWriteStream = () => { + retryCount++; + return new DelayedStream500Error(retryCount); + }; + + await file.save(BUFFER_DATA, options); + assert.ok(retryCount === 2); + }); + + it('should not retry if ifMetagenerationMatch is undefined', async () => { + const options = { + resumable: true, + preconditionOpts: {ifGenerationMatch: 100}, + }; + let retryCount = 0; + file.createWriteStream = () => { + retryCount++; + return new DelayedStream500Error(retryCount); + }; + try { + await file.save(BUFFER_DATA, options); + } catch { + assert.strictEqual(retryCount, 1); + } + }); + }); + + it('should execute callback', async () => { + const options = {resumable: true}; + let retryCount = 0; + file.createWriteStream = () => { + retryCount++; + return new DelayedStream500Error(retryCount); + }; + + file.save(DATA, options, (err: HTTPError) => { + assert.strictEqual(err.code, 500); + }); + }); + + it('should accept an options object', done => { + const options = {}; + + file.createWriteStream = (options_: {}) => { + assert.strictEqual(options_, options); + setImmediate(done); + return new PassThrough(); + }; + + file.save(DATA, options, assert.ifError); + }); + + it('should not require options', done => { + file.createWriteStream = (options_: {}) => { + assert.deepStrictEqual(options_, {}); + setImmediate(done); + return new PassThrough(); + }; + + file.save(DATA, assert.ifError); + }); + + it('should register the error listener', done => { + file.createWriteStream = () => { + const writeStream = new PassThrough(); + writeStream.on('error', done); + setImmediate(() => { + writeStream.emit('error'); + }); + return writeStream; + }; + + file.save(DATA, assert.ifError); + }); + + it('should register the finish listener', done => { + file.createWriteStream = () => { + const writeStream = new PassThrough(); + writeStream.once('finish', done); + return writeStream; + }; + + file.save(DATA, assert.ifError); + }); + + it('should register the progress listener if onUploadProgress is passed', done => { + const onUploadProgress = util.noop; + file.createWriteStream = () => { + const writeStream = new PassThrough(); + setImmediate(() => { + const [listener] = writeStream.listeners('progress'); + assert.strictEqual(listener, onUploadProgress); + done(); + }); + return writeStream; + }; + + file.save(DATA, {onUploadProgress}, assert.ifError); + }); + + it('should write the data', done => { + file.createWriteStream = () => { + const writeStream = new PassThrough(); + writeStream.on('data', data => { + assert.strictEqual(data.toString(), DATA); + done(); + }); + return writeStream; + }; + + file.save(DATA, assert.ifError); + }); + }); + + describe('setMetadata', () => { + it('should accept overrideUnlockedRetention option and set query parameter', done => { + const newFile = new File(BUCKET, 'new-file'); + + newFile.parent.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.overrideUnlockedRetention, true); + done(); + }; + + newFile.setMetadata( + {retention: null}, + {overrideUnlockedRetention: true}, + assert.ifError + ); + }); + }); + + describe('setStorageClass', () => { + const STORAGE_CLASS = 'new_storage_class'; + + it('should make the correct copy request', done => { + file.copy = (newFile: {}, options: {}) => { + assert.strictEqual(newFile, file); + assert.deepStrictEqual(options, { + storageClass: STORAGE_CLASS.toUpperCase(), + }); + done(); + }; + + file.setStorageClass(STORAGE_CLASS, assert.ifError); + }); + + it('should accept options', done => { + const options = { + a: 'b', + c: 'd', + }; + + const expectedOptions = { + a: 'b', + c: 'd', + storageClass: STORAGE_CLASS.toUpperCase(), + }; + + file.copy = (newFile: {}, options: {}) => { + assert.deepStrictEqual(options, expectedOptions); + done(); + }; + + file.setStorageClass(STORAGE_CLASS, options, assert.ifError); + }); + + it('should convert camelCase to snake_case', done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.copy = (newFile: {}, options: any) => { + assert.strictEqual(options.storageClass, 'CAMEL_CASE'); + done(); + }; + + file.setStorageClass('camelCase', assert.ifError); + }); + + it('should convert hyphenate to snake_case', done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + file.copy = (newFile: {}, options: any) => { + assert.strictEqual(options.storageClass, 'HYPHENATED_CLASS'); + done(); + }; + + file.setStorageClass('hyphenated-class', assert.ifError); + }); + + describe('error', () => { + const ERROR = new Error('Error.'); + const API_RESPONSE = {}; + + beforeEach(() => { + file.copy = (newFile: {}, options: {}, callback: Function) => { + callback(ERROR, null, API_RESPONSE); + }; + }); + + it('should execute callback with error & API response', done => { + file.setStorageClass(STORAGE_CLASS, (err: Error, apiResponse: {}) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(apiResponse, API_RESPONSE); + done(); + }); + }); + }); + + describe('success', () => { + const METADATA = {}; + + const COPIED_FILE = { + metadata: METADATA, + }; + + const API_RESPONSE = {}; + + beforeEach(() => { + file.copy = (newFile: {}, options: {}, callback: Function) => { + callback(null, COPIED_FILE, API_RESPONSE); + }; + }); + + it('should update the metadata on the file', done => { + file.setStorageClass(STORAGE_CLASS, (err: Error) => { + assert.ifError(err); + assert.strictEqual(file.metadata, METADATA); + done(); + }); + }); + + it('should execute callback with api response', done => { + file.setStorageClass(STORAGE_CLASS, (err: Error, apiResponse: {}) => { + assert.ifError(err); + assert.strictEqual(apiResponse, API_RESPONSE); + done(); + }); + }); + }); + }); + + describe('setEncryptionKey', () => { + const KEY = crypto.randomBytes(32); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const KEY_BASE64 = Buffer.from(KEY as any).toString('base64'); + const KEY_HASH = crypto + .createHash('sha256') + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .update(KEY_BASE64, 'base64' as any) + .digest('base64'); + let _file: {}; + + beforeEach(() => { + _file = file.setEncryptionKey(KEY); + }); + + it('should localize the key', () => { + assert.strictEqual(file.encryptionKey, KEY); + }); + + it('should localize the base64 key', () => { + assert.strictEqual(file.encryptionKeyBase64, KEY_BASE64); + }); + + it('should localize the hash', () => { + assert.strictEqual(file.encryptionKeyHash, KEY_HASH); + }); + + it('should return the file instance', () => { + assert.strictEqual(_file, file); + }); + + it('should push the correct request interceptor', done => { + const expectedInterceptor = { + headers: { + 'x-goog-encryption-algorithm': 'AES256', + 'x-goog-encryption-key': KEY_BASE64, + 'x-goog-encryption-key-sha256': KEY_HASH, + }, + }; + + assert.deepStrictEqual( + file.interceptors[0].request({}), + expectedInterceptor + ); + assert.deepStrictEqual( + file.encryptionKeyInterceptor.request({}), + expectedInterceptor + ); + + done(); + }); + }); + + describe('startResumableUpload_', () => { + beforeEach(() => { + file.getRequestInterceptors = () => []; + }); + + describe('starting', () => { + it('should start a resumable upload', done => { + const options = { + metadata: {}, + offset: 1234, + public: true, + private: false, + predefinedAcl: 'allUsers', + uri: 'http://resumable-uri', + userProject: 'user-project-id', + chunkSize: 262144, // 256 KiB + }; + + file.generation = 3; + file.encryptionKey = 'key'; + file.kmsKeyName = 'kms-key-name'; + + const customRequestInterceptors = [ + (reqOpts: DecorateRequestOptions) => { + reqOpts.headers = Object.assign({}, reqOpts.headers, { + a: 'b', + }); + return reqOpts; + }, + (reqOpts: DecorateRequestOptions) => { + reqOpts.headers = Object.assign({}, reqOpts.headers, { + c: 'd', + }); + return reqOpts; + }, + ]; + file.getRequestInterceptors = () => { + return customRequestInterceptors; + }; + + resumableUploadOverride = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + upload(opts: any) { + const bucket = file.bucket; + const storage = bucket.storage; + const authClient = storage.makeAuthenticatedRequest.authClient; + + assert.strictEqual(opts.authClient, authClient); + assert.strictEqual(opts.apiEndpoint, storage.apiEndpoint); + assert.strictEqual(opts.bucket, bucket.name); + assert.deepStrictEqual(opts.customRequestOptions, { + headers: { + a: 'b', + c: 'd', + }, + }); + assert.strictEqual(opts.file, file.name); + assert.strictEqual(opts.generation, file.generation); + assert.strictEqual(opts.key, file.encryptionKey); + assert.deepStrictEqual(opts.metadata, options.metadata); + assert.strictEqual(opts.offset, options.offset); + assert.strictEqual(opts.predefinedAcl, options.predefinedAcl); + assert.strictEqual(opts.private, options.private); + assert.strictEqual(opts.public, options.public); + assert.strictEqual(opts.uri, options.uri); + assert.strictEqual(opts.userProject, options.userProject); + assert.deepStrictEqual(opts.retryOptions, { + ...storage.retryOptions, + }); + assert.strictEqual(opts.params, storage.preconditionOpts); + assert.strictEqual(opts.chunkSize, options.chunkSize); + + setImmediate(done); + return new PassThrough(); + }, + }; + + file.startResumableUpload_(duplexify(), options); + }); + + it('should emit the response', done => { + const resp = {}; + const uploadStream = new PassThrough(); + + resumableUploadOverride = { + upload() { + setImmediate(() => { + uploadStream.emit('response', resp); + }); + return uploadStream; + }, + }; + + uploadStream.on('response', resp_ => { + assert.strictEqual(resp_, resp); + done(); + }); + + file.startResumableUpload_(duplexify()); + }); + + it('should set the metadata from the metadata event', done => { + const metadata = {}; + const uploadStream = new PassThrough(); + + resumableUploadOverride = { + upload() { + setImmediate(() => { + uploadStream.emit('metadata', metadata); + + setImmediate(() => { + assert.strictEqual(file.metadata, metadata); + done(); + }); + }); + return uploadStream; + }, + }; + + file.startResumableUpload_(duplexify()); + }); + + it('should emit complete after the stream finishes', done => { + const dup = duplexify(); + + dup.on('complete', done); + + resumableUploadOverride = { + upload() { + const uploadStream = new Transform(); + setImmediate(() => { + uploadStream.end(); + }); + return uploadStream; + }, + }; + + file.startResumableUpload_(dup); + }); + + it('should set the writable stream', done => { + const dup = duplexify(); + const uploadStream = new PassThrough(); + + dup.setWritable = (stream: Duplex) => { + assert.strictEqual(stream, uploadStream); + done(); + }; + + resumableUploadOverride = { + upload() { + return uploadStream; + }, + }; + + file.startResumableUpload_(dup); + }); + + it('should emit progress event', done => { + const progress = {}; + const dup = duplexify(); + dup.on('progress', evt => { + assert.strictEqual(evt, progress); + done(); + }); + + resumableUploadOverride = { + upload() { + const uploadStream = new Transform(); + setImmediate(() => { + uploadStream.emit('progress', progress); + }); + + return uploadStream; + }, + }; + + file.startResumableUpload_(dup); + }); + + it('should set autoRetry to false when ifMetagenerationMatch is undefined', done => { + const dup = duplexify(); + const uploadStream = new PassThrough(); + + dup.setWritable = (stream: Duplex) => { + assert.strictEqual(stream, uploadStream); + done(); + }; + + resumableUploadOverride = { + upload(options_: resumableUpload.UploadConfig) { + assert.strictEqual(options_?.retryOptions?.autoRetry, false); + return uploadStream; + }, + }; + + file.startResumableUpload_(dup, {retryOptions: {autoRetry: true}}); + assert.strictEqual(file.retryOptions.autoRetry, true); + }); + }); + }); + + describe('startSimpleUpload_', () => { + it('should get a writable stream', done => { + makeWritableStreamOverride = () => { + done(); + }; + + file.startSimpleUpload_(duplexify()); + }); + + it('should pass the required arguments', done => { + const options = { + metadata: {}, + predefinedAcl: 'allUsers', + private: true, + public: true, + timeout: 99, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeWritableStreamOverride = (stream: {}, options_: any) => { + assert.deepStrictEqual(options_.metadata, options.metadata); + assert.deepStrictEqual(options_.request, { + [GCCL_GCS_CMD_KEY]: undefined, + qs: { + name: file.name, + predefinedAcl: options.predefinedAcl, + }, + timeout: options.timeout, + uri: + 'https://storage.googleapis.com/upload/storage/v1/b/' + + file.bucket.name + + '/o', + }); + done(); + }; + + file.startSimpleUpload_(duplexify(), options); + }); + + it('should set predefinedAcl when public: true', done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeWritableStreamOverride = (stream: {}, options_: any) => { + assert.strictEqual(options_.request.qs.predefinedAcl, 'publicRead'); + done(); + }; + + file.startSimpleUpload_(duplexify(), {public: true}); + }); + + it('should set predefinedAcl when private: true', done => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeWritableStreamOverride = (stream: {}, options_: any) => { + assert.strictEqual(options_.request.qs.predefinedAcl, 'private'); + done(); + }; + + file.startSimpleUpload_(duplexify(), {private: true}); + }); + + it('should send query.ifGenerationMatch if File has one', done => { + const versionedFile = new File(BUCKET, 'new-file.txt', {generation: 1}); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeWritableStreamOverride = (stream: {}, options: any) => { + assert.strictEqual(options.request.qs.ifGenerationMatch, 1); + done(); + }; + + versionedFile.startSimpleUpload_(duplexify(), {}); + }); + + it('should send query.kmsKeyName if File has one', done => { + file.kmsKeyName = 'kms-key-name'; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeWritableStreamOverride = (stream: {}, options: any) => { + assert.strictEqual(options.request.qs.kmsKeyName, file.kmsKeyName); + done(); + }; + + file.startSimpleUpload_(duplexify(), {}); + }); + + it('should send userProject if set', done => { + const options = { + userProject: 'user-project-id', + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeWritableStreamOverride = (stream: {}, options_: any) => { + assert.strictEqual( + options_.request.qs.userProject, + options.userProject + ); + done(); + }; + + file.startSimpleUpload_(duplexify(), options); + }); + + describe('request', () => { + describe('error', () => { + const error = new Error('Error.'); + + beforeEach(() => { + file.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error); + }; + }); + + it('should destroy the stream', done => { + const stream = duplexify(); + + file.startSimpleUpload_(stream); + + stream.on('error', (err: Error) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.strictEqual((stream as any).destroyed, true); + assert.strictEqual(err, error); + done(); + }); + }); + }); + + describe('success', () => { + const body = {}; + const resp = {}; + + beforeEach(() => { + file.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, body, resp); + }; + }); + + it('should set the metadata', () => { + const stream = duplexify(); + + file.startSimpleUpload_(stream); + + assert.strictEqual(file.metadata, body); + }); + + it('should emit the response', done => { + const stream = duplexify(); + + stream.on('response', resp_ => { + assert.strictEqual(resp_, resp); + done(); + }); + + file.startSimpleUpload_(stream); + }); + + it('should emit complete', done => { + const stream = duplexify(); + + stream.on('complete', done); + + file.startSimpleUpload_(stream); + }); + }); + }); + }); + + describe('setUserProject', () => { + it('should call the parent setUserProject function', done => { + const userProject = 'grape-spaceship-123'; + + file.parent.setUserProject = function (userProject_: string) { + assert.strictEqual(this, file); + assert.strictEqual(userProject_, userProject); + done(); + }; + + file.setUserProject(userProject); + }); + }); + + describe('from', () => { + it('should create a File object from a gs:// formatted URL', () => { + const gsUrl = 'gs://mybucket/myfile'; + const result = File.from(gsUrl, STORAGE); + + assert(result); + assert.strictEqual(result.bucket.name, 'mybucket'); + assert.strictEqual(result.name, 'myfile'); + }); + + it('should create a File object from a gs:// formatted URL including a folder', () => { + const gsUrl = 'gs://mybucket/myfolder/myfile'; + const result = File.from(gsUrl, STORAGE); + + assert(result); + assert.strictEqual(result.bucket.name, 'mybucket'); + assert.strictEqual(result.name, 'myfolder/myfile'); + }); + + it('should create a File object from a https:// formatted URL', () => { + const httpsUrl = 'https://storage.googleapis.com/mybucket/myfile'; + const result = File.from(httpsUrl, STORAGE); + + assert(result); + assert.strictEqual(result.bucket.name, 'mybucket'); + assert.strictEqual(result.name, 'myfile'); + }); + + it('should create a File object from a https:// formatted URL including a folder', () => { + const httpsUrl = + 'https://storage.googleapis.com/mybucket/myfolder/myfile'; + const result = File.from(httpsUrl, STORAGE); + + assert(result); + assert.strictEqual(result.bucket.name, 'mybucket'); + assert.strictEqual(result.name, 'myfolder/myfile'); + }); + + it('should throw an error when invoked with an incorrectly formatted URL', () => { + const invalidUrl = 'https://storage.com/mybucket/myfile'; + + assert.throws(() => File.from(invalidUrl, STORAGE)); + }); + }); +}); diff --git a/handwritten/storage/test/fixtures/keys.json b/handwritten/storage/test/fixtures/keys.json new file mode 100644 index 00000000000..073edb70713 --- /dev/null +++ b/handwritten/storage/test/fixtures/keys.json @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "project-id", + "private_key_id": "12345", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC5z21IhrvlHBj7\nifRhobA9ibn25Od7DpE5OauGmqy7B+A9LQOsk1ZujAFdHItnBPcjihSVHpiYxf1a\nLpFbM8z/hRvDvYS3Hs1pyRejmpGiznoOjCyUf6Wv3T1xKelbgn0twHHjqD1o0xzW\njyUILl7yuCbsAf8QlsV6ewS3IqO3i5A9RNHfKjeap8e6A7U3s9QBtR58RrxaMQpM\nz72gw7yOdJRfElkerQfyZTbtu/EBfE6CcskOyoMoRN3YgkjQqLMr1yVdL5/phEcQ\n5hpbDN5lrafGHN7FUtsrMge2iIuIYFfWQUTqu7HtnNXVmwj1LJNq5WeI1iInWaGz\nb7c1rUT9AgMBAAECggEAEB0FicqVX3L7qk9LsBkeItgKFnfB/eaaKsTuM7K/fqCv\njjPpzlIgprQ20g+i+dYbuytC9Fjo5tFp/SNuBji3Ha7kuil56Yoe9NOJh0M6P0zP\nQj+0W1Rj1p0bB5tDhLoLh6eEDjgNde+zioUeCFhCck4MogmHnbVVfspNnba/99oD\nl36heAioqj/KODdkbQ83+ByiH+3BzqblqJ4TR/3y0wOUXtlQvCHko1qximJFIM0z\n3TNoPiit74hTiFFOYfJyHpmRsiEJ5FUUImkmCJz2gk4fbpafKrgxxOMo1m7GqlsE\nE+ybHxyAq61HYbZOoUOO8B4md1/52QXP7DgPvV7JyQKBgQD+JS5nsR4TXRl61c9G\nNxoPW9yCMCoarIjkpyPmhh0uJ7y68cj9wHFgX6ATi1QuTnG9BzJ4z27PMgvv70N+\nAK6k74sdIT2ts8wYsD8H0UyuxDxeKiAnb2JW2f5GTcXNmELQi6rKkMNMoS8jv00d\ngzLCV7UbCbdf+ng9uRPs+Fvk9wKBgQC7KpNaeYFf5dmIYRWQhlZWBRoftdm1ROH/\n5GJsURkzlEjUH1g1y9eAigBn5I+Z9hylX2q1vHLpUHqONWwDz8oQ1L1o2iLz+tkp\nkNoaLSAb9uCl6t8tpqCG2dqUrxOmy1+xj3G8KI8XuYb+IwVSy6KK2df8fWN4d+i0\ng+TBb75MqwKBgEezwcXriKq554hqblJHFYkjx7DLWfWwm+a26UAOsojlGTA9KxG8\ni8A++nDJLHTsGNbWAv1muMKoQgntnUMdeih6lOshB7/MLFcC0qWn/VSJdOa0R+IY\nYMxUMJMxOg9pV+BypzsDYLZr+1rAjEc5TsbZ6/S25w+jIO15HBANeg+9AoGAZulz\nGkVDCLq2UJGpLM1gvW2Svqrb6RrV9UDbiVlSNRUssk4Fz5akiM3YiUeYWfyEJb4A\nS6sxt+4DZRwkpzfikDyZZQTEQUjFjWBTPB9hz16AiVpKmqxLCbrRv/1AHe8nT9di\nnyXiABaIDkatT6geWKCNbQx43C16a382EdJiXX8CgYEAqyAS2xuDi2+uoljRm1Bp\naz7Q2UBtBbcBr/CQmagEacWPXsSyCL6EySOH0e985k7ABZiW+AzWlOwKS5WMWAIb\nkncmxP0SU6WQDWl8xGbXAQ8Dw+HTu5G1n0vrl1rRO5FPwRs3pbV94ML+d5eoai6D\njHs1asOGIpdQ3OGpBpNRub0=\n-----END PRIVATE KEY-----\n", + "client_email": "some-email@example.com", + "client_id": "12345", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://accounts.google.com/o/oauth2/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/el-gato%40el-gato.iam.gserviceaccount.com" +} diff --git a/handwritten/storage/test/headers.ts b/handwritten/storage/test/headers.ts new file mode 100644 index 00000000000..9ccc685814b --- /dev/null +++ b/handwritten/storage/test/headers.ts @@ -0,0 +1,96 @@ +// Copyright 2019 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 * as assert from 'assert'; +import {describe, it} from 'mocha'; +import proxyquire from 'proxyquire'; + +const error = Error('not implemented'); + +interface Request { + headers: { + [key: string]: string; + }; +} + +describe('headers', () => { + const requests: Request[] = []; + const {Storage} = proxyquire('../src', { + 'google-auth-library': { + GoogleAuth: class { + async getProjectId() { + return 'foo-project'; + } + async getClient() { + return class { + async request() { + return {}; + } + }; + } + getCredentials() { + return {}; + } + async authorizeRequest(req: Request) { + requests.push(req); + throw error; + } + }, + '@global': true, + }, + }); + + afterEach(() => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno = undefined; + }); + + it('populates x-goog-api-client header (node)', async () => { + const storage = new Storage(); + const bucket = storage.bucket('foo-bucket'); + try { + await bucket.create(); + } catch (err) { + if (err !== error) throw err; + } + assert.ok( + /^gl-node\/(?[^W]+) gccl\/(?[^W]+) gccl-invocation-id\/(?[^W]+)$/.test( + requests[0].headers['x-goog-api-client'] + ) + ); + }); + + it('populates x-goog-api-client header (deno)', async () => { + const storage = new Storage(); + const bucket = storage.bucket('foo-bucket'); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + globalThis.Deno = { + version: { + deno: '0.00.0', + }, + }; + try { + await bucket.create(); + } catch (err) { + if (err !== error) throw err; + } + assert.ok( + /^gl-deno\/0.00.0 gccl\/(?[^W]+) gccl-invocation-id\/(?[^W]+)$/.test( + requests[1].headers['x-goog-api-client'] + ) + ); + }); +}); diff --git a/handwritten/storage/test/hmacKey.ts b/handwritten/storage/test/hmacKey.ts new file mode 100644 index 00000000000..309b988358b --- /dev/null +++ b/handwritten/storage/test/hmacKey.ts @@ -0,0 +1,109 @@ +// Copyright 2019 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 * as sinon from 'sinon'; +import proxyquire from 'proxyquire'; +import assert from 'assert'; +import {describe, it, beforeEach, afterEach} from 'mocha'; +import {util, ServiceObject} from '../src/nodejs-common/index.js'; +import {HmacKeyMetadata, IdempotencyStrategy} from '../src/index.js'; + +const sandbox = sinon.createSandbox(); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let STORAGE: any; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let hmacKey: any; + +const ACCESS_ID = 'fake-access-id'; + +class HTTPError extends Error { + code: number; + constructor(message: string, code: number) { + super(message); + this.code = code; + } +} + +describe('HmacKey', () => { + afterEach(() => sandbox.restore()); + + describe('initialization', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let serviceObjectSpy: sinon.SinonSpy; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let commonModule: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let HmacKey: any; + + beforeEach(() => { + commonModule = {ServiceObject}; + serviceObjectSpy = sandbox.spy(commonModule, 'ServiceObject'); + + HmacKey = proxyquire('../src/hmacKey', { + './nodejs-common': commonModule, + }).HmacKey; + + STORAGE = { + request: util.noop, + projectId: 'my-project', + retryOptions: { + autoRetry: true, + maxRetries: 3, + retryDelayMultiplier: 2, + totalTimeout: 600, + maxRetryDelay: 60, + retryableErrorFn: (err: HTTPError) => { + return err.code === 500; + }, + idempotencyStrategy: IdempotencyStrategy.RetryConditional, + }, + }; + + hmacKey = new HmacKey(STORAGE, ACCESS_ID); + }); + + it('should inherit from ServiceObject', () => { + assert(hmacKey instanceof ServiceObject); + const ctorArg = serviceObjectSpy.firstCall.args[0]; + assert(ctorArg.parent, STORAGE); + assert(ctorArg.id, ACCESS_ID); + assert(ctorArg.baseUrl, '/projects/my-project/hmacKeys'); + assert.deepStrictEqual(ctorArg.methods, { + delete: true, + get: true, + getMetadata: true, + setMetadata: { + reqOpts: { + method: 'PUT', + }, + }, + }); + }); + + it('should form baseUrl using options.projectId if given', () => { + hmacKey = new HmacKey(STORAGE, ACCESS_ID, {projectId: 'another-project'}); + const ctorArg = serviceObjectSpy.firstCall.args[0]; + assert(ctorArg.baseUrl, '/projects/another-project/hmacKeys'); + }); + + it('should correctly call setMetadata', done => { + hmacKey.setMetadata = (metadata: HmacKeyMetadata, callback: Function) => { + assert.deepStrictEqual(metadata.accessId, ACCESS_ID); + Promise.resolve([]).then(resp => callback(null, ...resp)); + }; + + hmacKey.setMetadata({accessId: ACCESS_ID}, done); + }); + }); +}); diff --git a/handwritten/storage/test/iam.ts b/handwritten/storage/test/iam.ts new file mode 100644 index 00000000000..92327daa614 --- /dev/null +++ b/handwritten/storage/test/iam.ts @@ -0,0 +1,286 @@ +// Copyright 2019 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 {DecorateRequestOptions, util} from '../src/nodejs-common/index.js'; +import assert from 'assert'; +import {describe, it, before, beforeEach} from 'mocha'; +import proxyquire from 'proxyquire'; +import {IAMExceptionMessages} from '../src/iam.js'; + +describe('storage/iam', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Iam: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let iam: any; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let BUCKET_INSTANCE: any; + let promisified = false; + const fakePromisify = { + // tslint:disable-next-line:variable-name + promisifyAll(Class: Function) { + if (Class.name === 'Iam') { + promisified = true; + } + }, + }; + + before(() => { + Iam = proxyquire('../src/iam.js', { + '@google-cloud/promisify': fakePromisify, + }).Iam; + }); + + beforeEach(() => { + const id = 'bucket-id'; + BUCKET_INSTANCE = { + id, + request: util.noop, + getId: () => id, + }; + + iam = new Iam(BUCKET_INSTANCE); + }); + + describe('initialization', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should localize the request function', done => { + Object.assign(BUCKET_INSTANCE, { + request(callback: Function) { + assert.strictEqual(this, BUCKET_INSTANCE); + callback(); // done() + }, + }); + + const iam = new Iam(BUCKET_INSTANCE); + iam.request_(done); + }); + + it('should localize the resource ID', () => { + assert.strictEqual(iam.resourceId_, 'buckets/' + BUCKET_INSTANCE.id); + }); + }); + + describe('getPolicy', () => { + it('should make the correct api request', done => { + iam.request_ = (reqOpts: DecorateRequestOptions, callback: Function) => { + assert.deepStrictEqual(reqOpts, { + uri: '/iam', + qs: {}, + }); + + callback(); // done() + }; + + iam.getPolicy(done); + }); + + it('should accept an options object', done => { + const options = { + userProject: 'grape-spaceship-123', + }; + + iam.request_ = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.qs, options); + done(); + }; + + iam.getPolicy(options, assert.ifError); + }); + + it('should map requestedPolicyVersion option to optionsRequestedPolicyVersion', done => { + const VERSION = 3; + const options = { + requestedPolicyVersion: VERSION, + }; + + iam.request_ = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.qs, { + optionsRequestedPolicyVersion: VERSION, + }); + done(); + }; + + iam.getPolicy(options, assert.ifError); + }); + }); + + describe('setPolicy', () => { + it('should throw an error if a policy is not supplied', () => { + assert.throws(() => { + iam.setPolicy(util.noop), IAMExceptionMessages.POLICY_OBJECT_REQUIRED; + }); + }); + + it('should make the correct API request', done => { + const policy = { + a: 'b', + }; + + iam.request_ = (reqOpts: DecorateRequestOptions, callback: Function) => { + assert.deepStrictEqual(reqOpts, { + method: 'PUT', + uri: '/iam', + maxRetries: 0, + json: Object.assign( + { + resourceId: iam.resourceId_, + }, + policy + ), + qs: {}, + }); + + callback(); // done() + }; + + iam.setPolicy(policy, done); + }); + + it('should accept an options object', done => { + const policy = { + a: 'b', + }; + + const options = { + userProject: 'grape-spaceship-123', + }; + + iam.request_ = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs, options); + done(); + }; + + iam.setPolicy(policy, options, assert.ifError); + }); + }); + + describe('testPermissions', () => { + it('should throw an error if permissions are missing', () => { + assert.throws(() => { + iam.testPermissions(util.noop), + IAMExceptionMessages.PERMISSIONS_REQUIRED; + }); + }); + + it('should make the correct API request', done => { + const permissions = 'storage.bucket.list'; + + iam.request_ = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts, { + uri: '/iam/testPermissions', + qs: { + permissions: [permissions], + }, + useQuerystring: true, + }); + + done(); + }; + + iam.testPermissions(permissions, assert.ifError); + }); + + it('should send an error back if the request fails', done => { + const permissions = ['storage.bucket.list']; + const error = new Error('Error.'); + const apiResponse = {}; + + iam.request_ = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(error, apiResponse); + }; + + iam.testPermissions( + permissions, + (err: Error, permissions: Array<{}>, apiResp: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(permissions, null); + assert.strictEqual(apiResp, apiResponse); + done(); + } + ); + }); + + it('should pass back a hash of permissions the user has', done => { + const permissions = ['storage.bucket.list', 'storage.bucket.consume']; + const apiResponse = { + permissions: ['storage.bucket.consume'], + }; + + iam.request_ = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, apiResponse); + }; + + iam.testPermissions( + permissions, + (err: Error, permissions: Array<{}>, apiResp: {}) => { + assert.ifError(err); + assert.deepStrictEqual(permissions, { + 'storage.bucket.list': false, + 'storage.bucket.consume': true, + }); + assert.strictEqual(apiResp, apiResponse); + + done(); + } + ); + }); + + it('should return false for supplied permissions if user has no permissions', done => { + const permissions = ['storage.bucket.list', 'storage.bucket.consume']; + const apiResponse = {permissions: undefined}; + + iam.request_ = (reqOpts: DecorateRequestOptions, callback: Function) => { + callback(null, apiResponse); + }; + iam.testPermissions( + permissions, + (err: Error, permissions: Array<{}>, apiResp: {}) => { + assert.ifError(err); + assert.deepStrictEqual(permissions, { + 'storage.bucket.list': false, + 'storage.bucket.consume': false, + }); + assert.strictEqual(apiResp, apiResponse); + + done(); + } + ); + }); + + it('should accept an options object', done => { + const permissions = ['storage.bucket.list']; + const options = { + userProject: 'grape-spaceship-123', + }; + + const expectedQuery = Object.assign( + { + permissions, + }, + options + ); + + iam.request_ = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.qs, expectedQuery); + done(); + }; + + iam.testPermissions(permissions, options, assert.ifError); + }); + }); +}); diff --git a/handwritten/storage/test/index.ts b/handwritten/storage/test/index.ts new file mode 100644 index 00000000000..c7fbed8467b --- /dev/null +++ b/handwritten/storage/test/index.ts @@ -0,0 +1,1550 @@ +// Copyright 2019 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 { + ApiError, + DecorateRequestOptions, + Service, + ServiceConfig, + util, +} from '../src/nodejs-common/index.js'; +import {PromisifyAllOptions} from '@google-cloud/promisify'; +import assert from 'assert'; +import {describe, it, before, beforeEach, after, afterEach} from 'mocha'; +import proxyquire from 'proxyquire'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import {Bucket, CRC32C_DEFAULT_VALIDATOR_GENERATOR} from '../src/index.js'; +import {GetFilesOptions} from '../src/bucket.js'; +import * as sinon from 'sinon'; +import {HmacKey} from '../src/hmacKey.js'; +import { + HmacKeyResourceResponse, + PROTOCOL_REGEX, + StorageExceptionMessages, +} from '../src/storage.js'; +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +import {getPackageJSON} from '../src/package-json-helper.cjs'; + +// eslint-disable-next-line @typescript-eslint/no-var-requires +const hmacKeyModule = require('../src/hmacKey'); + +class FakeChannel { + calledWith_: Array<{}>; + constructor(...args: Array<{}>) { + this.calledWith_ = args; + } +} + +class FakeService extends Service { + calledWith_: Array<{}>; + constructor(...args: Array<{}>) { + super(args[0] as ServiceConfig); + this.calledWith_ = args; + } +} + +let extended = false; +const fakePaginator = { + paginator: { + // tslint:disable-next-line:variable-name + extend(Class: Function, methods: string[]) { + if (Class.name !== 'Storage') { + return; + } + + assert.strictEqual(Class.name, 'Storage'); + assert.deepStrictEqual(methods, ['getBuckets', 'getHmacKeys']); + extended = true; + }, + streamify(methodName: string) { + return methodName; + }, + }, +}; + +let promisified = false; +const fakePromisify = { + // tslint:disable-next-line:variable-name + promisifyAll(Class: Function, options: PromisifyAllOptions) { + if (Class.name !== 'Storage') { + return; + } + + promisified = true; + assert.deepStrictEqual(options.exclude, ['bucket', 'channel', 'hmacKey']); + }, +}; + +describe('Storage', () => { + const PROJECT_ID = 'project-id'; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Storage: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let storage: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Bucket: any; + + before(() => { + Storage = proxyquire('../src/storage', { + '@google-cloud/promisify': fakePromisify, + '@google-cloud/paginator': fakePaginator, + './nodejs-common': { + Service: FakeService, + }, + './channel.js': {Channel: FakeChannel}, + './hmacKey': hmacKeyModule, + }).Storage; + Bucket = Storage.Bucket; + }); + + beforeEach(() => { + storage = new Storage({projectId: PROJECT_ID}); + }); + + describe('instantiation', () => { + it('should extend the correct methods', () => { + assert(extended); // See `fakePaginator.extend` + }); + + it('should streamify the correct methods', () => { + assert.strictEqual(storage.getBucketsStream, 'getBuckets'); + assert.strictEqual(storage.getHmacKeysStream, 'getHmacKeys'); + }); + + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should inherit from Service', () => { + // Using assert.strictEqual instead of assert to prevent + // coercing of types. + assert.strictEqual(storage instanceof Service, true); + + const calledWith = storage.calledWith_[0]; + + const baseUrl = 'https://storage.googleapis.com/storage/v1'; + assert.strictEqual(calledWith.baseUrl, baseUrl); + assert.strictEqual(calledWith.projectIdRequired, false); + assert.deepStrictEqual(calledWith.scopes, [ + 'https://www.googleapis.com/auth/iam', + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/devstorage.full_control', + ]); + assert.deepStrictEqual( + calledWith.packageJson, + // eslint-disable-next-line @typescript-eslint/no-var-requires + getPackageJSON() + ); + }); + + it('should not modify options argument', () => { + const options = { + projectId: PROJECT_ID, + }; + const expectedCalledWith = Object.assign({}, options, { + apiEndpoint: 'https://storage.googleapis.com', + }); + const storage = new Storage(options); + const calledWith = storage.calledWith_[1]; + assert.notStrictEqual(calledWith, options); + assert.notDeepStrictEqual(calledWith, options); + assert.deepStrictEqual(calledWith, expectedCalledWith); + }); + + it('should propagate the apiEndpoint option', () => { + const apiEndpoint = 'https://some.fake.endpoint'; + const storage = new Storage({ + projectId: PROJECT_ID, + apiEndpoint, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.baseUrl, `${apiEndpoint}/storage/v1`); + assert.strictEqual(calledWith.apiEndpoint, `${apiEndpoint}`); + }); + + it('should not set `customEndpoint` if `apiEndpoint` matches default', () => { + const apiEndpoint = 'https://storage.googleapis.com'; + const storage = new Storage({ + apiEndpoint, + }); + + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.apiEndpoint, apiEndpoint); + assert.strictEqual(calledWith.customEndpoint, false); + }); + + it('should not set `customEndpoint` if `apiEndpoint` matches default (w/ universe domain)', () => { + const universeDomain = 'my.universe'; + const apiEndpoint = `https://storage.${universeDomain}`; + const storage = new Storage({ + apiEndpoint, + universeDomain, + }); + + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.apiEndpoint, apiEndpoint); + assert.strictEqual(calledWith.customEndpoint, false); + }); + + it('should propagate the useAuthWithCustomEndpoint option', () => { + const useAuthWithCustomEndpoint = true; + const apiEndpoint = 'https://some.fake.endpoint'; + const storage = new Storage({ + projectId: PROJECT_ID, + useAuthWithCustomEndpoint, + apiEndpoint, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.apiEndpoint, 'https://some.fake.endpoint'); + assert.strictEqual(calledWith.customEndpoint, true); + assert.strictEqual(calledWith.useAuthWithCustomEndpoint, true); + }); + + it('should propagate autoRetry in retryOptions', () => { + const autoRetry = false; + const storage = new Storage({ + projectId: PROJECT_ID, + retryOptions: {autoRetry}, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.retryOptions.autoRetry, autoRetry); + }); + + it('should propagate retryDelayMultiplier', () => { + const retryDelayMultiplier = 4; + const storage = new Storage({ + projectId: PROJECT_ID, + retryOptions: {retryDelayMultiplier}, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual( + calledWith.retryOptions.retryDelayMultiplier, + retryDelayMultiplier + ); + }); + + it('should propagate totalTimeout', () => { + const totalTimeout = 60; + const storage = new Storage({ + projectId: PROJECT_ID, + retryOptions: {totalTimeout}, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.retryOptions.totalTimeout, totalTimeout); + }); + + it('should propagate maxRetryDelay', () => { + const maxRetryDelay = 640; + const storage = new Storage({ + projectId: PROJECT_ID, + retryOptions: {maxRetryDelay}, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.retryOptions.maxRetryDelay, maxRetryDelay); + }); + + it('should set correct defaults for retry configs', () => { + const autoRetryDefault = true; + const maxRetryDefault = 3; + const retryDelayMultiplierDefault = 2; + const totalTimeoutDefault = 600; + const maxRetryDelayDefault = 64; + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.retryOptions.autoRetry, autoRetryDefault); + assert.strictEqual(calledWith.retryOptions.maxRetries, maxRetryDefault); + assert.strictEqual( + calledWith.retryOptions.retryDelayMultiplier, + retryDelayMultiplierDefault + ); + assert.strictEqual( + calledWith.retryOptions.totalTimeout, + totalTimeoutDefault + ); + assert.strictEqual( + calledWith.retryOptions.maxRetryDelay, + maxRetryDelayDefault + ); + }); + + it('should propagate maxRetries in retryOptions', () => { + const maxRetries = 1; + const storage = new Storage({ + projectId: PROJECT_ID, + retryOptions: {maxRetries}, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.retryOptions.maxRetries, maxRetries); + }); + + it('should set retryFunction', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + assert(calledWith.retryOptions.retryableErrorFn); + }); + + it('should retry a 502 error', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + const error = new ApiError('502 Error'); + error.code = 502; + assert.strictEqual(calledWith.retryOptions.retryableErrorFn(error), true); + }); + + it('should not retry blank error', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + const error = undefined; + assert.strictEqual( + calledWith.retryOptions.retryableErrorFn(error), + false + ); + }); + + it('should retry a reset connection error', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + const error = new ApiError('Connection Reset By Peer error'); + error.errors = [ + { + reason: 'ECONNRESET', + }, + ]; + assert.strictEqual(calledWith.retryOptions.retryableErrorFn(error), true); + }); + + it('should retry a broken pipe error', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + const error = new ApiError('Broken pipe'); + error.errors = [ + { + reason: 'EPIPE', + }, + ]; + assert.strictEqual(calledWith.retryOptions.retryableErrorFn(error), true); + }); + + it('should retry a socket connection timeout', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + const error = new ApiError('Broken pipe'); + const innerError = { + /** + * @link https://nodejs.org/api/errors.html#err_socket_connection_timeout + * @link https://github.com/nodejs/node/blob/798db3c92a9b9c9f991eed59ce91e9974c052bc9/lib/internal/errors.js#L1570-L1571 + */ + reason: 'Socket connection timeout', + }; + + error.errors = [innerError]; + assert.strictEqual(calledWith.retryOptions.retryableErrorFn(error), true); + }); + + it('should not retry a 999 error', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + const error = new ApiError('999 Error'); + error.code = 0; + assert.strictEqual( + calledWith.retryOptions.retryableErrorFn(error), + false + ); + }); + + it('should return false if reason and code are both undefined', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + const calledWith = storage.calledWith_[0]; + const error = new ApiError('error without a code'); + error.errors = [ + { + message: 'some error message', + }, + ]; + assert.strictEqual( + calledWith.retryOptions.retryableErrorFn(error), + false + ); + }); + + it('should retry a 999 error if dictated by custom function', () => { + const customRetryFunc = function (err?: ApiError) { + if (err) { + if ([999].indexOf(err.code!) !== -1) { + return true; + } + } + return false; + }; + const storage = new Storage({ + projectId: PROJECT_ID, + retryOptions: {retryableErrorFn: customRetryFunc}, + }); + const calledWith = storage.calledWith_[0]; + const error = new ApiError('999 Error'); + error.code = 999; + assert.strictEqual(calledWith.retryOptions.retryableErrorFn(error), true); + }); + + it('should set customEndpoint to true when using apiEndpoint', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + apiEndpoint: 'https://apiendpoint', + }); + + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.customEndpoint, true); + }); + + it('should prepend apiEndpoint with default protocol', () => { + const protocollessApiEndpoint = 'some.fake.endpoint'; + const storage = new Storage({ + projectId: PROJECT_ID, + apiEndpoint: protocollessApiEndpoint, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual( + calledWith.baseUrl, + `https://${protocollessApiEndpoint}/storage/v1` + ); + assert.strictEqual( + calledWith.apiEndpoint, + `https://${protocollessApiEndpoint}` + ); + }); + + it('should strip trailing slash from apiEndpoint', () => { + const apiEndpoint = 'https://some.fake.endpoint/'; + const storage = new Storage({ + projectId: PROJECT_ID, + apiEndpoint, + }); + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.baseUrl, `${apiEndpoint}storage/v1`); + assert.strictEqual(calledWith.apiEndpoint, 'https://some.fake.endpoint'); + }); + + it('should accept a `crc32cGenerator`', () => { + const crc32cGenerator = () => {}; + + const storage = new Storage({crc32cGenerator}); + assert.strictEqual(storage.crc32cGenerator, crc32cGenerator); + }); + + it('should use `CRC32C_DEFAULT_VALIDATOR_GENERATOR` by default', () => { + assert.strictEqual( + storage.crc32cGenerator, + CRC32C_DEFAULT_VALIDATOR_GENERATOR + ); + }); + + it('should accept and use a `universeDomain`', () => { + const universeDomain = 'my-universe.com'; + + const storage = new Storage({universeDomain}); + + assert.equal(storage.apiEndpoint, `https://storage.${universeDomain}`); + }); + + describe('STORAGE_EMULATOR_HOST', () => { + // Note: EMULATOR_HOST is an experimental configuration variable. Use apiEndpoint instead. + const EMULATOR_HOST = 'https://internal.benchmark.com/path'; + before(() => { + process.env.STORAGE_EMULATOR_HOST = EMULATOR_HOST; + }); + + after(() => { + delete process.env.STORAGE_EMULATOR_HOST; + }); + + it('should set baseUrl to env var STORAGE_EMULATOR_HOST', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.baseUrl, EMULATOR_HOST); + assert.strictEqual( + calledWith.apiEndpoint, + 'https://internal.benchmark.com/path' + ); + }); + + it('should be overridden by apiEndpoint', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + apiEndpoint: 'https://some.api.com', + }); + + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.baseUrl, EMULATOR_HOST); + assert.strictEqual(calledWith.apiEndpoint, 'https://some.api.com'); + }); + + it('should prepend default protocol and strip trailing slash', () => { + const EMULATOR_HOST = 'internal.benchmark.com/path/'; + process.env.STORAGE_EMULATOR_HOST = EMULATOR_HOST; + + const storage = new Storage({ + projectId: PROJECT_ID, + }); + + const calledWith = storage.calledWith_[0]; + assert.strictEqual(calledWith.baseUrl, EMULATOR_HOST); + assert.strictEqual( + calledWith.apiEndpoint, + 'https://internal.benchmark.com/path' + ); + }); + + it('should set customEndpoint to true', () => { + const storage = new Storage({ + projectId: PROJECT_ID, + }); + + assert.strictEqual(storage.customEndpoint, true); + }); + }); + }); + + describe('bucket', () => { + it('should throw if no name was provided', () => { + assert.throws(() => { + storage.bucket(), StorageExceptionMessages.BUCKET_NAME_REQUIRED; + }); + }); + + it('should accept a string for a name', () => { + const newBucketName = 'new-bucket-name'; + const bucket = storage.bucket(newBucketName); + assert(bucket instanceof Bucket); + assert.strictEqual(bucket.name, newBucketName); + }); + + it('should optionally accept options', () => { + const options = { + userProject: 'grape-spaceship-123', + }; + + const bucket = storage.bucket('bucket-name', options); + assert.strictEqual(bucket.userProject, options.userProject); + }); + }); + + describe('channel', () => { + const ID = 'channel-id'; + const RESOURCE_ID = 'resource-id'; + + it('should create a Channel object', () => { + const channel = storage.channel(ID, RESOURCE_ID); + + assert(channel instanceof FakeChannel); + + assert.strictEqual(channel.calledWith_[0], storage); + assert.strictEqual(channel.calledWith_[1], ID); + assert.strictEqual(channel.calledWith_[2], RESOURCE_ID); + }); + }); + + describe('hmacKey', () => { + let hmacKeyCtor: sinon.SinonSpy; + beforeEach(() => { + hmacKeyCtor = sinon.spy(hmacKeyModule, 'HmacKey'); + }); + + afterEach(() => { + hmacKeyCtor.restore(); + }); + + it('should throw if accessId is not provided', () => { + assert.throws(() => { + storage.hmacKey(), StorageExceptionMessages.HMAC_ACCESS_ID; + }); + }); + + it('should pass options object to HmacKey constructor', () => { + const options = {myOpts: 'a'}; + storage.hmacKey('access-id', options); + assert.deepStrictEqual(hmacKeyCtor.getCall(0).args, [ + storage, + 'access-id', + options, + ]); + }); + }); + + describe('createHmacKey', () => { + const SERVICE_ACCOUNT_EMAIL = 'service-account@gserviceaccount.com'; + const ACCESS_ID = 'some-access-id'; + const metadataResponse = { + accessId: ACCESS_ID, + etag: 'etag', + id: ACCESS_ID, + projectId: 'project-id', + serviceAccountEmail: SERVICE_ACCOUNT_EMAIL, + state: 'ACTIVE', + timeCreated: '20190101T00:00:00Z', + updated: '20190101T00:00:00Z', + }; + const response = { + secret: 'my-secret', + metadata: metadataResponse, + }; + const OPTIONS = { + some: 'value', + }; + + let hmacKeyCtor: sinon.SinonSpy; + beforeEach(() => { + hmacKeyCtor = sinon.spy(hmacKeyModule, 'HmacKey'); + }); + + afterEach(() => { + hmacKeyCtor.restore(); + }); + + it('should make correct API request', done => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.method, 'POST'); + assert.strictEqual( + reqOpts.uri, + `/projects/${storage.projectId}/hmacKeys` + ); + assert.strictEqual( + reqOpts.qs.serviceAccountEmail, + SERVICE_ACCOUNT_EMAIL + ); + + callback(null, response); + }; + + storage.createHmacKey(SERVICE_ACCOUNT_EMAIL, done); + }); + + it('should throw without a serviceAccountEmail', () => { + assert.throws(() => { + storage.createHmacKey(), StorageExceptionMessages.HMAC_SERVICE_ACCOUNT; + }); + }); + + it('should throw when first argument is not a string', () => { + assert.throws(() => { + storage.createHmacKey({ + userProject: 'my-project', + }), + StorageExceptionMessages.HMAC_SERVICE_ACCOUNT; + }); + }); + + it('should make request with method options as query parameter', async () => { + storage.request = sinon + .stub() + .returns((_reqOpts: {}, callback: Function) => callback()); + + await storage.createHmacKey(SERVICE_ACCOUNT_EMAIL, OPTIONS); + const reqArg = storage.request.firstCall.args[0]; + assert.deepStrictEqual(reqArg.qs, { + serviceAccountEmail: SERVICE_ACCOUNT_EMAIL, + ...OPTIONS, + }); + }); + + it('should not modify the options object', done => { + storage.request = (_reqOpts: {}, callback: Function) => { + callback(null, response); + }; + const originalOptions = Object.assign({}, OPTIONS); + + storage.createHmacKey(SERVICE_ACCOUNT_EMAIL, OPTIONS, (err: Error) => { + assert.ifError(err); + assert.deepStrictEqual(OPTIONS, originalOptions); + done(); + }); + }); + + it('should invoke callback with a secret and an HmacKey instance', done => { + storage.request = (_reqOpts: {}, callback: Function) => { + callback(null, response); + }; + + storage.createHmacKey( + SERVICE_ACCOUNT_EMAIL, + (err: Error, hmacKey: HmacKey, secret: string) => { + assert.ifError(err); + assert.strictEqual(secret, response.secret); + assert.deepStrictEqual(hmacKeyCtor.getCall(0).args, [ + storage, + response.metadata.accessId, + {projectId: response.metadata.projectId}, + ]); + assert.strictEqual(hmacKey.metadata, metadataResponse); + done(); + } + ); + }); + + it('should invoke callback with raw apiResponse', done => { + storage.request = (_reqOpts: {}, callback: Function) => { + callback(null, response); + }; + + storage.createHmacKey( + SERVICE_ACCOUNT_EMAIL, + ( + err: Error, + _hmacKey: HmacKey, + _secret: string, + apiResponse: HmacKeyResourceResponse + ) => { + assert.ifError(err); + assert.strictEqual(apiResponse, response); + done(); + } + ); + }); + + it('should execute callback with request error', done => { + const error = new Error('Request error'); + const response = {success: false}; + storage.request = (_reqOpts: {}, callback: Function) => { + callback(error, response); + }; + + storage.createHmacKey( + SERVICE_ACCOUNT_EMAIL, + (err: Error, _hmacKey: HmacKey, _secret: string, apiResponse: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(apiResponse, response); + done(); + } + ); + }); + }); + + describe('createBucket', () => { + const BUCKET_NAME = 'new-bucket-name'; + const METADATA = {a: 'b', c: {d: 'e'}}; + const BUCKET = {name: BUCKET_NAME}; + + it('should make correct API request', done => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.method, 'POST'); + assert.strictEqual(reqOpts.uri, '/b'); + assert.strictEqual(reqOpts.qs.project, storage.projectId); + assert.strictEqual(reqOpts.json.name, BUCKET_NAME); + + callback(); + }; + + storage.createBucket(BUCKET_NAME, done); + }); + + it('should accept a name, metadata, and callback', done => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.deepStrictEqual( + reqOpts.json, + Object.assign(METADATA, {name: BUCKET_NAME}) + ); + callback(null, METADATA); + }; + storage.bucket = (name: string) => { + assert.strictEqual(name, BUCKET_NAME); + return BUCKET; + }; + storage.createBucket(BUCKET_NAME, METADATA, (err: Error) => { + assert.ifError(err); + done(); + }); + }); + + it('should accept a name and callback only', done => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(); + }; + storage.createBucket(BUCKET_NAME, done); + }); + + it('should throw if no name is provided', () => { + assert.throws(() => { + storage.createBucket(), + StorageExceptionMessages.BUCKET_NAME_REQUIRED_CREATE; + }); + }); + + it('should honor the userProject option', done => { + const options = { + userProject: 'grape-spaceship-123', + }; + + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs.userProject, options.userProject); + done(); + }; + + storage.createBucket(BUCKET_NAME, options, assert.ifError); + }); + + it('should execute callback with bucket', done => { + storage.bucket = () => { + return BUCKET; + }; + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, METADATA); + }; + storage.createBucket(BUCKET_NAME, (err: Error, bucket: Bucket) => { + assert.ifError(err); + assert.deepStrictEqual(bucket, BUCKET); + assert.deepStrictEqual(bucket.metadata, METADATA); + done(); + }); + }); + + it('should execute callback on error', done => { + const error = new Error('Error.'); + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error); + }; + storage.createBucket(BUCKET_NAME, (err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should execute callback with apiResponse', done => { + const resp = {success: true}; + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, resp); + }; + storage.createBucket( + BUCKET_NAME, + (err: Error, bucket: Bucket, apiResponse: unknown) => { + assert.strictEqual(resp, apiResponse); + done(); + } + ); + }); + + it('should allow a user-specified storageClass', done => { + const storageClass = 'nearline'; + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.json.storageClass, storageClass); + callback(); // done + }; + storage.createBucket(BUCKET_NAME, {storageClass}, done); + }); + + it('should allow settings `storageClass` to same value as provided storage class name', done => { + const storageClass = 'coldline'; + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual( + reqOpts.json.storageClass, + storageClass.toUpperCase() + ); + callback(); // done + }; + + assert.doesNotThrow(() => { + storage.createBucket( + BUCKET_NAME, + {storageClass, [storageClass]: true}, + done + ); + }); + }); + + it('should allow setting rpo', done => { + const location = 'NAM4'; + const rpo = 'ASYNC_TURBO'; + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.json.location, location); + assert.strictEqual(reqOpts.json.rpo, rpo); + callback(); + }; + storage.createBucket(BUCKET_NAME, {location, rpo}, done); + }); + + it('should throw when `storageClass` is set to different value than provided storageClass name', () => { + assert.throws(() => { + storage.createBucket( + BUCKET_NAME, + { + storageClass: 'nearline', + coldline: true, + }, + assert.ifError + ); + }, /Both `coldline` and `storageClass` were provided./); + }); + + it('should allow enabling object retention', done => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.qs.enableObjectRetention, true); + callback(); + }; + storage.createBucket(BUCKET_NAME, {enableObjectRetention: true}, done); + }); + + it('should allow enabling hierarchical namespace', done => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.json.hierarchicalNamespace.enabled, true); + callback(); + }; + storage.createBucket( + BUCKET_NAME, + {hierarchicalNamespace: {enabled: true}}, + done + ); + }); + + describe('storage classes', () => { + it('should expand metadata.archive', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.storageClass, 'ARCHIVE'); + done(); + }; + + storage.createBucket(BUCKET_NAME, {archive: true}, assert.ifError); + }); + + it('should expand metadata.coldline', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.storageClass, 'COLDLINE'); + done(); + }; + + storage.createBucket(BUCKET_NAME, {coldline: true}, assert.ifError); + }); + + it('should expand metadata.dra', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + const body = reqOpts.json; + assert.strictEqual(body.storageClass, 'DURABLE_REDUCED_AVAILABILITY'); + done(); + }; + + storage.createBucket(BUCKET_NAME, {dra: true}, assert.ifError); + }); + + it('should expand metadata.multiRegional', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.storageClass, 'MULTI_REGIONAL'); + done(); + }; + + storage.createBucket( + BUCKET_NAME, + { + multiRegional: true, + }, + assert.ifError + ); + }); + + it('should expand metadata.nearline', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.storageClass, 'NEARLINE'); + done(); + }; + + storage.createBucket(BUCKET_NAME, {nearline: true}, assert.ifError); + }); + + it('should expand metadata.regional', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.storageClass, 'REGIONAL'); + done(); + }; + + storage.createBucket(BUCKET_NAME, {regional: true}, assert.ifError); + }); + + it('should expand metadata.standard', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.json.storageClass, 'STANDARD'); + done(); + }; + + storage.createBucket(BUCKET_NAME, {standard: true}, assert.ifError); + }); + }); + + describe('requesterPays', () => { + it('should accept requesterPays setting', done => { + const options = { + requesterPays: true, + }; + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.json.billing, options); + assert.strictEqual(reqOpts.json.requesterPays, undefined); + done(); + }; + storage.createBucket(BUCKET_NAME, options, assert.ifError); + }); + }); + }); + + describe('getBuckets', () => { + it('should get buckets without a query', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, '/b'); + assert.deepStrictEqual(reqOpts.qs, {project: storage.projectId}); + done(); + }; + storage.getBuckets(util.noop); + }); + + it('should get buckets with a query', done => { + const token = 'next-page-token'; + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.qs, { + project: storage.projectId, + maxResults: 5, + pageToken: token, + }); + done(); + }; + storage.getBuckets({maxResults: 5, pageToken: token}, util.noop); + }); + + it('should execute callback with error', done => { + const error = new Error('Error.'); + const apiResponse = {}; + + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error, apiResponse); + }; + + storage.getBuckets( + {}, + (err: Error, buckets: Bucket[], nextQuery: {}, resp: unknown) => { + assert.strictEqual(err, error); + assert.strictEqual(buckets, null); + assert.strictEqual(nextQuery, null); + assert.strictEqual(resp, apiResponse); + done(); + } + ); + }); + + it('should return nextQuery if more results exist', () => { + const token = 'next-page-token'; + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, {nextPageToken: token, items: []}); + }; + storage.getBuckets( + {maxResults: 5}, + (err: Error, results: {}, nextQuery: GetFilesOptions) => { + assert.strictEqual(nextQuery.pageToken, token); + assert.strictEqual(nextQuery.maxResults, 5); + } + ); + }); + + it('should return null nextQuery if there are no more results', () => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, {items: []}); + }; + storage.getBuckets( + {maxResults: 5}, + (err: Error, results: {}, nextQuery: {}) => { + assert.strictEqual(nextQuery, null); + } + ); + }); + + it('should return Bucket objects', done => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, {items: [{id: 'fake-bucket-name'}]}); + }; + storage.getBuckets((err: Error, buckets: Bucket[]) => { + assert.ifError(err); + assert(buckets[0] instanceof Bucket); + done(); + }); + }); + + it('should return apiResponse', done => { + const resp = {items: [{id: 'fake-bucket-name'}]}; + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, resp); + }; + storage.getBuckets( + (err: Error, buckets: Bucket[], nextQuery: {}, apiResponse: {}) => { + assert.deepStrictEqual(resp, apiResponse); + done(); + } + ); + }); + + it('should populate returned Bucket object with metadata', done => { + const bucketMetadata = { + id: 'bucketname', + contentType: 'x-zebra', + metadata: { + my: 'custom metadata', + }, + }; + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, {items: [bucketMetadata]}); + }; + storage.getBuckets((err: Error, buckets: Bucket[]) => { + assert.ifError(err); + assert.deepStrictEqual(buckets[0].metadata, bucketMetadata); + done(); + }); + }); + + it('should return unreachable when returnPartialSuccess is true', done => { + const unreachableList = ['projects/_/buckets/fail-bucket']; + const itemsList = [{id: 'fake-bucket-name'}]; + const resp = {items: itemsList, unreachable: unreachableList}; + + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.qs.returnPartialSuccess, true); + callback(null, resp); + }; + + storage.getBuckets( + {returnPartialSuccess: true}, + (err: Error, buckets: Bucket[], nextQuery: {}, apiResponse: {}) => { + assert.ifError(err); + assert.strictEqual(buckets.length, 2); + + const reachableBucket = buckets.find( + b => b.name === 'fake-bucket-name' + ); + assert.ok(reachableBucket); + assert.strictEqual(reachableBucket.unreachable, false); + + const unreachableBucket = buckets.find(b => b.name === 'fail-bucket'); + assert.ok(unreachableBucket); + assert.strictEqual(unreachableBucket.unreachable, true); + assert.deepStrictEqual(apiResponse, resp); + done(); + } + ); + }); + + it('should handle partial failure with zero reachable buckets', done => { + const unreachableList = ['projects/_/buckets/fail-bucket']; + const resp = {items: [], unreachable: unreachableList}; + + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.qs.returnPartialSuccess, true); + callback(null, resp); + }; + + storage.getBuckets( + {returnPartialSuccess: true}, + (err: Error, buckets: Bucket[]) => { + assert.ifError(err); + assert.strictEqual(buckets.length, 1); + assert.deepStrictEqual(buckets[0].name, 'fail-bucket'); + assert.strictEqual(buckets[0].unreachable, true); + assert.deepStrictEqual(buckets[0].metadata, {}); + done(); + } + ); + }); + + it('should handle API success where zero items and zero unreachable items are returned', done => { + const resp = {items: [], unreachable: []}; + + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.qs.returnPartialSuccess, true); + callback(null, resp); + }; + + storage.getBuckets( + {returnPartialSuccess: true}, + (err: Error, buckets: Bucket[], nextQuery: {}, apiResponse: {}) => { + assert.ifError(err); + assert.strictEqual(buckets.length, 0); + assert.deepStrictEqual(apiResponse, resp); + done(); + } + ); + }); + }); + + describe('getHmacKeys', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let storageRequestStub: sinon.SinonStub; + const SERVICE_ACCOUNT_EMAIL = 'service-account@gserviceaccount.com'; + const ACCESS_ID = 'some-access-id'; + const metadataResponse = { + accessId: ACCESS_ID, + etag: 'etag', + id: ACCESS_ID, + projectId: 'project-id', + serviceAccountEmail: SERVICE_ACCOUNT_EMAIL, + state: 'ACTIVE', + timeCreated: '20190101T00:00:00Z', + updated: '20190101T00:00:00Z', + }; + + beforeEach(() => { + storageRequestStub = sinon.stub(storage, 'request'); + storageRequestStub.callsFake((_opts: {}, callback: Function) => { + callback(null, {}); + }); + }); + + let hmacKeyCtor: sinon.SinonSpy; + beforeEach(() => { + hmacKeyCtor = sinon.spy(hmacKeyModule, 'HmacKey'); + }); + + afterEach(() => { + hmacKeyCtor.restore(); + }); + + it('should get HmacKeys without a query', done => { + storage.getHmacKeys(() => { + const firstArg = storage.request.firstCall.args[0]; + assert.strictEqual( + firstArg.uri, + `/projects/${storage.projectId}/hmacKeys` + ); + assert.deepStrictEqual(firstArg.qs, {}); + done(); + }); + }); + + it('should get HmacKeys with a query', done => { + const query = { + maxResults: 5, + pageToken: 'next-page-token', + serviceAccountEmail: SERVICE_ACCOUNT_EMAIL, + showDeletedKeys: false, + }; + + storage.getHmacKeys(query, () => { + const firstArg = storage.request.firstCall.args[0]; + assert.strictEqual( + firstArg.uri, + `/projects/${storage.projectId}/hmacKeys` + ); + assert.deepStrictEqual(firstArg.qs, query); + done(); + }); + }); + + it('should execute callback with error', done => { + const error = new Error('Error.'); + const apiResponse = {}; + + storageRequestStub.callsFake((_opts: {}, callback: Function) => { + callback(error, apiResponse); + }); + + storage.getHmacKeys( + {}, + (err: Error, hmacKeys: HmacKey[], nextQuery: {}, resp: unknown) => { + assert.strictEqual(err, error); + assert.strictEqual(hmacKeys, null); + assert.strictEqual(nextQuery, null); + assert.strictEqual(resp, apiResponse); + done(); + } + ); + }); + + it('should return nextQuery if more results exist', done => { + const token = 'next-page-token'; + const query = { + param1: 'a', + param2: 'b', + }; + const expectedNextQuery = Object.assign({}, query, {pageToken: token}); + storageRequestStub.callsFake((_opts: {}, callback: Function) => { + callback(null, {nextPageToken: token, items: []}); + }); + + storage.getHmacKeys( + query, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (err: Error, _hmacKeys: [], nextQuery: any) => { + assert.ifError(err); + assert.deepStrictEqual(nextQuery, expectedNextQuery); + done(); + } + ); + }); + + it('should return null nextQuery if there are no more results', done => { + storageRequestStub.callsFake((_opts: {}, callback: Function) => { + callback(null, {items: []}); + }); + + storage.getHmacKeys({}, (err: Error, _hmacKeys: [], nextQuery: {}) => { + assert.ifError(err); + assert.strictEqual(nextQuery, null); + done(); + }); + }); + + it('should return apiResponse', done => { + const resp = {items: [metadataResponse]}; + storageRequestStub.callsFake((_opts: {}, callback: Function) => { + callback(null, resp); + }); + + storage.getHmacKeys( + (err: Error, _hmacKeys: [], _nextQuery: {}, apiResponse: unknown) => { + assert.ifError(err); + assert.deepStrictEqual(resp, apiResponse); + done(); + } + ); + }); + + it('should populate returned HmacKey object with accessId and metadata', done => { + storageRequestStub.callsFake((_opts: {}, callback: Function) => { + callback(null, {items: [metadataResponse]}); + }); + + storage.getHmacKeys((err: Error, hmacKeys: HmacKey[]) => { + assert.ifError(err); + assert.deepStrictEqual(hmacKeyCtor.getCall(0).args, [ + storage, + metadataResponse.accessId, + {projectId: metadataResponse.projectId}, + ]); + assert.deepStrictEqual(hmacKeys[0].metadata, metadataResponse); + done(); + }); + }); + }); + + describe('getServiceAccount', () => { + it('should make the correct request', done => { + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.uri, + `/projects/${storage.projectId}/serviceAccount` + ); + assert.deepStrictEqual(reqOpts.qs, {}); + done(); + }; + + storage.getServiceAccount(assert.ifError); + }); + + it('should allow user options', done => { + const options = { + projectIdentifier: 'test-identifier', + userProject: 'test-user-project', + }; + + storage.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.qs, options); + done(); + }; + + storage.getServiceAccount(options, assert.ifError); + }); + + describe('error', () => { + const ERROR = new Error('Error.'); + const API_RESPONSE = {}; + + beforeEach(() => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(ERROR, API_RESPONSE); + }; + }); + + it('should return the error and apiResponse', done => { + storage.getServiceAccount( + (err: Error, serviceAccount: {}, apiResponse: unknown) => { + assert.strictEqual(err, ERROR); + assert.strictEqual(serviceAccount, null); + assert.strictEqual(apiResponse, API_RESPONSE); + done(); + } + ); + }); + }); + + describe('success', () => { + const API_RESPONSE = {}; + + beforeEach(() => { + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, API_RESPONSE); + }; + }); + + it('should convert snake_case response to camelCase', done => { + const apiResponse = { + snake_case: true, + }; + + storage.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, apiResponse); + }; + + storage.getServiceAccount( + ( + err: Error, + serviceAccount: {[index: string]: string | undefined} + ) => { + assert.ifError(err); + assert.strictEqual( + serviceAccount.snakeCase, + apiResponse.snake_case + ); + assert.strictEqual(serviceAccount.snake_case, undefined); + done(); + } + ); + }); + + it('should return the serviceAccount and apiResponse', done => { + storage.getServiceAccount( + (err: Error, serviceAccount: {}, apiResponse: {}) => { + assert.ifError(err); + assert.deepStrictEqual(serviceAccount, {}); + assert.strictEqual(apiResponse, API_RESPONSE); + done(); + } + ); + }); + }); + }); + + describe('#sanitizeEndpoint', () => { + const USER_DEFINED_SHORT_API_ENDPOINT = 'myapi.com:8080'; + const USER_DEFINED_PROTOCOL = 'myproto'; + const USER_DEFINED_FULL_API_ENDPOINT = `${USER_DEFINED_PROTOCOL}://myapi.com:8080`; + + it('should default protocol to https', () => { + const endpoint = Storage.sanitizeEndpoint( + USER_DEFINED_SHORT_API_ENDPOINT + ); + assert.strictEqual(endpoint.match(PROTOCOL_REGEX)![1], 'https'); + }); + + it('should not override protocol', () => { + const endpoint = Storage.sanitizeEndpoint(USER_DEFINED_FULL_API_ENDPOINT); + assert.strictEqual( + endpoint.match(PROTOCOL_REGEX)![1], + USER_DEFINED_PROTOCOL + ); + }); + + it('should remove trailing slashes from URL', () => { + const endpointsWithTrailingSlashes = [ + `${USER_DEFINED_FULL_API_ENDPOINT}/`, + `${USER_DEFINED_FULL_API_ENDPOINT}//`, + ]; + for (const endpointWithTrailingSlashes of endpointsWithTrailingSlashes) { + const endpoint = Storage.sanitizeEndpoint(endpointWithTrailingSlashes); + assert.strictEqual(endpoint.endsWith('/'), false); + } + }); + }); +}); diff --git a/handwritten/storage/test/nodejs-common/index.ts b/handwritten/storage/test/nodejs-common/index.ts new file mode 100644 index 00000000000..35bfd07da25 --- /dev/null +++ b/handwritten/storage/test/nodejs-common/index.ts @@ -0,0 +1,26 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 assert from 'assert'; +import {describe, it} from 'mocha'; +import {Service, ServiceObject, util} from '../../src/nodejs-common/index.js'; + +describe('common', () => { + it('should correctly export the common modules', () => { + assert(Service); + assert(ServiceObject); + assert(util); + }); +}); diff --git a/handwritten/storage/test/nodejs-common/service-object.ts b/handwritten/storage/test/nodejs-common/service-object.ts new file mode 100644 index 00000000000..3bba5f4faad --- /dev/null +++ b/handwritten/storage/test/nodejs-common/service-object.ts @@ -0,0 +1,1234 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 { + promisify, + promisifyAll, + PromisifyAllOptions, +} from '@google-cloud/promisify'; +import assert from 'assert'; +import {describe, it, beforeEach, afterEach} from 'mocha'; +import proxyquire from 'proxyquire'; +import * as r from 'teeny-request'; +import * as sinon from 'sinon'; +import {Service} from '../../src/nodejs-common/index.js'; +import * as SO from '../../src/nodejs-common/service-object.js'; + +let promisified = false; +const fakePromisify = { + // tslint:disable-next-line:variable-name + promisifyAll(Class: Function, options: PromisifyAllOptions) { + if (Class.name === 'ServiceObject') { + promisified = true; + assert.deepStrictEqual(options.exclude, ['getRequestInterceptors']); + } + + return promisifyAll(Class, options); + }, +}; +const ServiceObject = proxyquire('../../src/nodejs-common/service-object', { + '@google-cloud/promisify': fakePromisify, +}).ServiceObject; + +import { + ApiError, + BodyResponseCallback, + DecorateRequestOptions, + util, +} from '../../src/nodejs-common/util.js'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type FakeServiceObject = any; +interface InternalServiceObject { + request_: ( + reqOpts: DecorateRequestOptions, + callback?: BodyResponseCallback + ) => void | r.Request; + createMethod?: Function; + methods: SO.Methods; + interceptors: SO.Interceptor[]; +} + +function asInternal( + serviceObject: SO.ServiceObject +) { + return serviceObject as {} as InternalServiceObject; +} + +describe('ServiceObject', () => { + let serviceObject: SO.ServiceObject; + const sandbox = sinon.createSandbox(); + + const CONFIG = { + baseUrl: 'base-url', + parent: {} as Service, + id: 'id', + createMethod: util.noop, + }; + + beforeEach(() => { + serviceObject = new ServiceObject(CONFIG); + serviceObject.parent.interceptors = []; + }); + + afterEach(() => { + sandbox.restore(); + }); + + describe('instantiation', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should create an empty metadata object', () => { + assert.deepStrictEqual(serviceObject.metadata, {}); + }); + + it('should localize the baseUrl', () => { + assert.strictEqual(serviceObject.baseUrl, CONFIG.baseUrl); + }); + + it('should localize the parent instance', () => { + assert.strictEqual(serviceObject.parent, CONFIG.parent); + }); + + it('should localize the ID', () => { + assert.strictEqual(serviceObject.id, CONFIG.id); + }); + + it('should localize the createMethod', () => { + assert.strictEqual( + asInternal(serviceObject).createMethod, + CONFIG.createMethod + ); + }); + + it('should localize the methods', () => { + const methods = {}; + const config = {...CONFIG, methods}; + const serviceObject = new ServiceObject(config); + assert.deepStrictEqual(asInternal(serviceObject).methods, methods); + }); + + it('should default methods to an empty object', () => { + assert.deepStrictEqual(asInternal(serviceObject).methods, {}); + }); + + it('should clear out methods that are not asked for', () => { + const config = { + ...CONFIG, + methods: { + create: true, + }, + }; + const serviceObject = new ServiceObject(config); + assert.strictEqual(typeof serviceObject.create, 'function'); + assert.strictEqual(serviceObject.delete, undefined); + }); + + it('should always expose the request method', () => { + const methods = {}; + const config = {...CONFIG, methods}; + const serviceObject = new ServiceObject(config); + assert.strictEqual(typeof serviceObject.request, 'function'); + }); + + it('should always expose the getRequestInterceptors method', () => { + const methods = {}; + const config = {...CONFIG, methods}; + const serviceObject = new ServiceObject(config); + assert.strictEqual( + typeof serviceObject.getRequestInterceptors, + 'function' + ); + }); + }); + + describe('create', () => { + it('should call createMethod', done => { + const config = {...CONFIG, createMethod}; + const options = {}; + + function createMethod( + id: string, + options_: {}, + callback: (err: Error | null, a: {}, b: {}) => void + ) { + assert.strictEqual(id, config.id); + assert.strictEqual(options_, options); + callback(null, {}, {}); // calls done() + } + + const serviceObject = new ServiceObject(config); + serviceObject.create(options, done); + }); + + it('should not require options', done => { + const config = {...CONFIG, createMethod}; + + function createMethod(id: string, options: Function, callback: Function) { + assert.strictEqual(id, config.id); + assert.strictEqual(typeof options, 'function'); + assert.strictEqual(callback, undefined); + options(null, {}, {}); // calls done() + } + + const serviceObject = new ServiceObject(config); + serviceObject.create(done); + }); + + it('should update id with metadata id', done => { + const config = {...CONFIG, createMethod}; + const options = {}; + + function createMethod( + id: string, + options_: {}, + callback: (err: Error | null, a: {}, b: {}) => void + ) { + assert.strictEqual(id, config.id); + assert.strictEqual(options_, options); + callback(null, {metadata: {id: 14}}, {}); + } + + const serviceObject = new ServiceObject(config); + serviceObject.create(options); + assert.strictEqual(serviceObject.id, 14); + done(); + }); + + it('should pass error to callback', done => { + const config = {...CONFIG, createMethod}; + const options = {}; + const error = new Error('Error.'); + const apiResponse = {}; + function createMethod(id: string, options_: {}, callback: Function) { + callback(error, null, apiResponse); + } + + const serviceObject = new ServiceObject(config); + serviceObject.create( + options, + (err: Error | null, instance: {}, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(instance, null); + assert.strictEqual(apiResponse_, apiResponse); + done(); + } + ); + }); + + it('should return instance and apiResponse to callback', async () => { + const config = {...CONFIG, createMethod}; + const options = {}; + const apiResponse = {}; + function createMethod(id: string, options_: {}, callback: Function) { + callback(null, {}, apiResponse); + } + + const serviceObject = new ServiceObject(config); + const [instance_, apiResponse_] = await serviceObject.create(options); + assert.strictEqual(instance_, serviceObject); + assert.strictEqual(apiResponse_, apiResponse); + }); + + it('should assign metadata', async () => { + const config = {...CONFIG, createMethod}; + const options = {}; + const instance = { + metadata: {}, + }; + function createMethod(id: string, options_: {}, callback: Function) { + callback(null, instance, {}); + } + const serviceObject = new ServiceObject(config); + const [instance_] = await serviceObject.create(options); + assert.strictEqual(instance_.metadata, instance.metadata); + }); + + it('should execute callback with any amount of arguments', done => { + const config = {...CONFIG, createMethod}; + const options = {}; + + const args = ['a', 'b', 'c', 'd', 'e', 'f']; + + function createMethod(id: string, options_: {}, callback: Function) { + callback(...args); + } + + const serviceObject = new ServiceObject(config); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + serviceObject.create(options, (...args: any[]) => { + assert.deepStrictEqual([].slice.call(args), args); + done(); + }); + }); + }); + + describe('delete', () => { + it('should make the correct request', done => { + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.strictEqual(opts.method, 'DELETE'); + assert.strictEqual(opts.uri, ''); + done(); + cb(null, null, {} as r.Response); + }); + serviceObject.delete(assert.ifError); + }); + + it('should accept options', done => { + const options = {queryOptionProperty: true}; + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual(opts.qs, options); + done(); + cb(null, null, {} as r.Response); + }); + serviceObject.delete(options, assert.ifError); + }); + + it('should override method and uri field in request with methodConfig', done => { + const methodConfig = { + reqOpts: { + uri: 'v2', + method: 'PATCH', + }, + }; + + const cachedMethodConfig = {reqOpts: {...methodConfig.reqOpts}}; + + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual( + serviceObject.methods.delete, + cachedMethodConfig + ); + assert.deepStrictEqual(opts.uri, 'v2'); + assert.deepStrictEqual(opts.method, 'PATCH'); + done(); + cb(null, null, null!); + }); + + const serviceObject = new ServiceObject(CONFIG) as FakeServiceObject; + serviceObject.methods.delete = methodConfig; + serviceObject.delete(); + }); + + it('should respect ignoreNotFound option', done => { + const options = {ignoreNotFound: true}; + const error = new ApiError({code: 404, response: {} as r.Response}); + sandbox.stub(ServiceObject.prototype, 'request').callsArgWith(1, error); + serviceObject.delete(options, (err, apiResponse_) => { + assert.ifError(err); + assert.strictEqual(apiResponse_, undefined); + done(); + }); + }); + + it('should propagate other then 404 error', done => { + const options = {ignoreNotFound: true}; + const error = new ApiError({code: 406, response: {} as r.Response}); + sandbox.stub(ServiceObject.prototype, 'request').callsArgWith(1, error); + serviceObject.delete(options, (err, apiResponse_) => { + assert.strictEqual(err, error); + assert.strictEqual(apiResponse_, undefined); + done(); + }); + }); + + it('should not pass ignoreNotFound to request', done => { + const options = {ignoreNotFound: true}; + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.strictEqual(opts.qs.ignoreNotFound, undefined); + done(); + cb(null, null, {} as r.Response); + }); + serviceObject.delete(options, assert.ifError); + }); + + it('should extend the defaults with request options', done => { + const methodConfig = { + reqOpts: { + qs: { + defaultProperty: true, + thisPropertyWasOverridden: false, + }, + }, + }; + + const cachedMethodConfig = {reqOpts: {qs: {...methodConfig.reqOpts.qs}}}; + + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual( + serviceObject.methods.delete, + cachedMethodConfig + ); + assert.deepStrictEqual(opts.qs, { + defaultProperty: true, + optionalProperty: true, + thisPropertyWasOverridden: true, + }); + done(); + cb(null, null, null!); + }); + + const serviceObject = new ServiceObject(CONFIG) as FakeServiceObject; + serviceObject.methods.delete = methodConfig; + serviceObject.delete({ + optionalProperty: true, + thisPropertyWasOverridden: true, + }); + }); + + it('should not require a callback', () => { + sandbox + .stub(ServiceObject.prototype, 'request') + .callsArgWith(1, null, null, {}); + assert.doesNotThrow(() => { + serviceObject.delete(); + }); + }); + + it('should execute callback with correct arguments', done => { + const error = new Error('🦃'); + sandbox.stub(ServiceObject.prototype, 'request').callsArgWith(1, error); + const serviceObject = new ServiceObject(CONFIG); + serviceObject.delete((err: Error, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(apiResponse_, undefined); + done(); + }); + }); + }); + + describe('exists', () => { + it('should call get', done => { + sandbox.stub(serviceObject, 'get').callsFake(() => done()); + serviceObject.exists(() => {}); + }); + + it('should accept options', done => { + const options = {queryOptionProperty: true}; + sandbox + .stub(ServiceObject.prototype, 'get') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual(opts, options); + done(); + cb(null, null, {} as r.Response); + }); + serviceObject.exists(options, assert.ifError); + }); + + it('should execute callback with false if 404', done => { + const error = new ApiError(''); + error.code = 404; + sandbox.stub(serviceObject, 'get').callsArgWith(1, error); + serviceObject.exists((err: Error, exists: boolean) => { + assert.ifError(err); + assert.strictEqual(exists, false); + done(); + }); + }); + + it('should execute callback with error if not 404', done => { + const error = new ApiError(''); + error.code = 500; + sandbox.stub(serviceObject, 'get').callsArgWith(1, error); + serviceObject.exists((err: Error, exists: boolean) => { + assert.strictEqual(err, error); + assert.strictEqual(exists, undefined); + done(); + }); + }); + + it('should execute callback with true if no error', done => { + sandbox.stub(serviceObject, 'get').callsArgWith(1, null); + serviceObject.exists((err: Error, exists: boolean) => { + assert.ifError(err); + assert.strictEqual(exists, true); + done(); + }); + }); + }); + + describe('get', () => { + it('should get the metadata', done => { + serviceObject.getMetadata = promisify((): void => { + done(); + }); + + serviceObject.get(assert.ifError); + }); + + it('should accept options', done => { + const options = {}; + serviceObject.getMetadata = promisify( + (options_: SO.GetMetadataOptions): void => { + assert.deepStrictEqual(options, options_); + done(); + } + ); + serviceObject.exists(options, assert.ifError); + }); + + it('handles not getting a config', done => { + serviceObject.getMetadata = promisify((): void => { + done(); + }); + (serviceObject as FakeServiceObject).get(assert.ifError); + }); + + it('should execute callback with error & metadata', done => { + const error = new Error('Error.'); + const metadata = {} as SO.BaseMetadata; + + serviceObject.getMetadata = promisify( + ( + options: SO.GetMetadataOptions, + callback: SO.MetadataCallback + ) => { + callback(error, metadata); + } + ); + + serviceObject.get((err, instance, metadata_) => { + assert.strictEqual(err, error); + assert.strictEqual(instance, null); + assert.strictEqual(metadata_, metadata); + + done(); + }); + }); + + it('should execute callback with instance & metadata', done => { + const metadata = {} as SO.BaseMetadata; + + serviceObject.getMetadata = promisify( + ( + options: SO.GetMetadataOptions, + callback: SO.MetadataCallback + ) => { + callback(null, metadata); + } + ); + + serviceObject.get((err, instance, metadata_) => { + assert.ifError(err); + + assert.strictEqual(instance, serviceObject); + assert.strictEqual(metadata_, metadata); + + done(); + }); + }); + + describe('autoCreate', () => { + let AUTO_CREATE_CONFIG: {}; + + const ERROR = new ApiError('bad'); + ERROR.code = 404; + const METADATA = {} as SO.BaseMetadata; + + beforeEach(() => { + AUTO_CREATE_CONFIG = { + autoCreate: true, + }; + + serviceObject.getMetadata = promisify( + ( + options: SO.GetMetadataOptions, + callback: SO.MetadataCallback + ) => { + callback(ERROR, METADATA); + } + ); + }); + + it('should keep the original options intact', () => { + const expectedConfig = Object.assign({}, AUTO_CREATE_CONFIG); + serviceObject.get(AUTO_CREATE_CONFIG, () => {}); + assert.deepStrictEqual(AUTO_CREATE_CONFIG, expectedConfig); + }); + + it('should not auto create if there is no create method', done => { + (serviceObject as FakeServiceObject).create = undefined; + + serviceObject.get(AUTO_CREATE_CONFIG, err => { + assert.strictEqual(err, ERROR); + done(); + }); + }); + + it('should pass config to create if it was provided', done => { + const expectedConfig = {maxResults: 5} as SO.GetConfig; + const config = {...AUTO_CREATE_CONFIG, ...expectedConfig}; + + sandbox.stub(serviceObject, 'create').callsFake(config_ => { + assert.deepStrictEqual(config_, expectedConfig); + done(); + }); + serviceObject.get(config, assert.ifError); + }); + + it('should pass only a callback to create if no config', done => { + sandbox.stub(serviceObject, 'create').callsArgWith(0, null); + serviceObject.get(AUTO_CREATE_CONFIG, done); + }); + + describe('error', () => { + it('should execute callback with error & API response', done => { + const error = new Error('Error.'); + const apiResponse = {} as r.Response; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (sandbox.stub(serviceObject, 'create') as any).callsFake( + (optsOrCb: {}, cb: Function) => { + const callback = typeof optsOrCb === 'function' ? optsOrCb : cb; + sandbox.stub(serviceObject, 'get').callsFake((cfg, callback) => { + assert.deepStrictEqual(cfg, {}); + callback!(null); // done() + }); + callback!(error, null, apiResponse); + } + ); + + serviceObject.get(AUTO_CREATE_CONFIG, (err, instance, resp) => { + assert.strictEqual(err, error); + assert.strictEqual(instance, null); + assert.strictEqual(resp, apiResponse); + done(); + }); + }); + + it('should refresh the metadata after a 409', done => { + const error = new ApiError('errrr'); + error.code = 409; + sandbox.stub(serviceObject, 'create').callsFake(callback => { + sandbox.stub(serviceObject, 'get').callsFake((cfgOrCb, cb) => { + const config = typeof cfgOrCb === 'object' ? cfgOrCb : {}; + const callback = typeof cfgOrCb === 'function' ? cfgOrCb : cb; + assert.deepStrictEqual(config, {}); + callback!(null, null, {} as r.Response); // done() + }); + callback(error, null, undefined); + }); + serviceObject.get(AUTO_CREATE_CONFIG, done); + }); + }); + }); + }); + + describe('getMetadata', () => { + it('should make the correct request', done => { + sandbox.stub(ServiceObject.prototype, 'request').callsFake(function ( + this: SO.ServiceObject, + reqOpts, + callback + ) { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.strictEqual(this, serviceObject); + assert.strictEqual(opts.uri, ''); + done(); + cb(null, null, {} as r.Response); + }); + serviceObject.getMetadata(() => {}); + }); + + it('should accept options', done => { + const options = {queryOptionProperty: true}; + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual(opts.qs, options); + done(); + cb(null, null, {} as r.Response); + }); + serviceObject.getMetadata(options, assert.ifError); + }); + + it('should override uri field in request with methodConfig', done => { + const methodConfig = { + reqOpts: { + uri: 'v2', + }, + }; + + const cachedMethodConfig = {reqOpts: {...methodConfig.reqOpts}}; + + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual( + serviceObject.methods.getMetadata, + cachedMethodConfig + ); + assert.deepStrictEqual(opts.uri, 'v2'); + done(); + cb(null, null, null!); + }); + + const serviceObject = new ServiceObject(CONFIG) as FakeServiceObject; + serviceObject.methods.getMetadata = methodConfig; + serviceObject.getMetadata(); + }); + + it('should extend the defaults with request options', done => { + const methodConfig = { + reqOpts: { + qs: { + defaultProperty: true, + thisPropertyWasOverridden: false, + }, + }, + }; + + const cachedMethodConfig = {reqOpts: {qs: {...methodConfig.reqOpts.qs}}}; + + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual( + serviceObject.methods.getMetadata, + cachedMethodConfig + ); + assert.deepStrictEqual(opts.qs, { + defaultProperty: true, + optionalProperty: true, + thisPropertyWasOverridden: true, + }); + done(); + cb(null, null, null!); + }); + + const serviceObject = new ServiceObject(CONFIG) as FakeServiceObject; + serviceObject.methods.getMetadata = methodConfig; + serviceObject.getMetadata({ + optionalProperty: true, + thisPropertyWasOverridden: true, + }); + }); + + it('should execute callback with error & apiResponse', done => { + const error = new Error('ಠ_ಠ'); + sandbox.stub(ServiceObject.prototype, 'request').callsArgWith(1, error); + serviceObject.getMetadata((err: Error, metadata: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(metadata, undefined); + done(); + }); + }); + + it('should update metadata', done => { + const apiResponse = {}; + sandbox + .stub(ServiceObject.prototype, 'request') + .callsArgWith(1, null, {}, apiResponse); + serviceObject.getMetadata((err: Error) => { + assert.ifError(err); + assert.deepStrictEqual(serviceObject.metadata, apiResponse); + done(); + }); + }); + + it('should execute callback with metadata & API response', done => { + const apiResponse = {}; + const requestResponse = {body: apiResponse}; + sandbox + .stub(ServiceObject.prototype, 'request') + .callsArgWith(1, null, apiResponse, requestResponse); + serviceObject.getMetadata((err: Error, metadata: {}) => { + assert.ifError(err); + assert.strictEqual(metadata, apiResponse); + done(); + }); + }); + }); + + describe('getRequestInterceptors', () => { + it('should call the request interceptors in order', () => { + // Called first. + serviceObject.parent.interceptors.push({ + request(reqOpts: DecorateRequestOptions) { + reqOpts.uri = '1'; + return reqOpts; + }, + }); + + // Called third. + serviceObject.interceptors.push({ + request(reqOpts: DecorateRequestOptions) { + reqOpts.uri += '3'; + return reqOpts; + }, + }); + + // Called second. + serviceObject.parent.interceptors.push({ + request(reqOpts: DecorateRequestOptions) { + reqOpts.uri += '2'; + return reqOpts; + }, + }); + + // Called fourth. + serviceObject.interceptors.push({ + request(reqOpts: DecorateRequestOptions) { + reqOpts.uri += '4'; + return reqOpts; + }, + }); + + serviceObject.parent.getRequestInterceptors = () => { + return serviceObject.parent.interceptors.map( + interceptor => interceptor.request + ); + }; + + const reqOpts: DecorateRequestOptions = {uri: ''}; + const requestInterceptors = serviceObject.getRequestInterceptors(); + requestInterceptors.forEach((requestInterceptor: Function) => { + Object.assign(reqOpts, requestInterceptor(reqOpts)); + }); + assert.strictEqual(reqOpts.uri, '1234'); + }); + + it('should not affect original interceptor arrays', () => { + function request(reqOpts: DecorateRequestOptions) { + return reqOpts; + } + + serviceObject.parent.interceptors = [{request}]; + serviceObject.interceptors = [{request}]; + + const originalParentInterceptors = [].slice.call( + serviceObject.parent.interceptors + ); + const originalLocalInterceptors = [].slice.call( + serviceObject.interceptors + ); + + serviceObject.getRequestInterceptors(); + + assert.deepStrictEqual( + serviceObject.parent.interceptors, + originalParentInterceptors + ); + assert.deepStrictEqual( + serviceObject.interceptors, + originalLocalInterceptors + ); + }); + + it('should not call unrelated interceptors', () => { + (serviceObject.interceptors as object[]).push({ + anotherInterceptor() { + throw new Error('Unrelated interceptor was called.'); + }, + request(reqOpts: DecorateRequestOptions) { + return reqOpts; + }, + }); + + const requestInterceptors = serviceObject.getRequestInterceptors(); + requestInterceptors.forEach((requestInterceptor: Function) => { + requestInterceptor(); + }); + }); + }); + + describe('setMetadata', () => { + it('should make the correct request', done => { + const metadata = {metadataProperty: true}; + sandbox.stub(ServiceObject.prototype, 'request').callsFake(function ( + this: SO.ServiceObject, + reqOpts, + callback + ) { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.strictEqual(this, serviceObject); + assert.strictEqual(opts.method, 'PATCH'); + assert.strictEqual(opts.uri, ''); + assert.deepStrictEqual(opts.json, metadata); + done(); + cb(null, null, {} as r.Response); + }); + serviceObject.setMetadata(metadata, () => {}); + }); + + it('should accept options', done => { + const metadata = {}; + const options = {queryOptionProperty: true}; + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual(opts.qs, options); + done(); + cb(null, null, {} as r.Response); + }); + serviceObject.setMetadata(metadata, options, () => {}); + }); + + it('should override uri and method with methodConfig', done => { + const methodConfig = { + reqOpts: { + uri: 'v2', + method: 'PUT', + }, + }; + const cachedMethodConfig = {reqOpts: {...methodConfig.reqOpts}}; + + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual( + serviceObject.methods.setMetadata, + cachedMethodConfig + ); + assert.deepStrictEqual(opts.uri, 'v2'); + assert.deepStrictEqual(opts.method, 'PUT'); + done(); + cb(null, null, null!); + }); + + const serviceObject = new ServiceObject(CONFIG) as FakeServiceObject; + serviceObject.methods.setMetadata = methodConfig; + serviceObject.setMetadata({}); + }); + + it('should extend the defaults with request options', done => { + const methodConfig = { + reqOpts: { + qs: { + defaultProperty: true, + thisPropertyWasOverridden: false, + }, + }, + }; + const cachedMethodConfig = {reqOpts: {qs: {...methodConfig.reqOpts.qs}}}; + + sandbox + .stub(ServiceObject.prototype, 'request') + .callsFake((reqOpts, callback) => { + const opts = reqOpts as r.OptionsWithUri; + const cb = callback as BodyResponseCallback; + assert.deepStrictEqual( + serviceObject.methods.setMetadata, + cachedMethodConfig + ); + assert.deepStrictEqual(opts.qs, { + defaultProperty: true, + optionalProperty: true, + thisPropertyWasOverridden: true, + }); + done(); + cb(null, null, null!); + }); + + const serviceObject = new ServiceObject(CONFIG) as FakeServiceObject; + serviceObject.methods.setMetadata = methodConfig; + serviceObject.setMetadata( + {}, + { + optionalProperty: true, + thisPropertyWasOverridden: true, + } + ); + }); + + it('should execute callback with error & apiResponse', done => { + const error = new Error('Error.'); + sandbox.stub(ServiceObject.prototype, 'request').callsArgWith(1, error); + serviceObject.setMetadata({}, (err: Error, apiResponse_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(apiResponse_, undefined); + done(); + }); + }); + + it('should update metadata', done => { + const apiResponse = {}; + sandbox + .stub(ServiceObject.prototype, 'request') + .callsArgWith(1, undefined, apiResponse); + serviceObject.setMetadata({}, (err: Error) => { + assert.ifError(err); + assert.strictEqual(serviceObject.metadata, apiResponse); + done(); + }); + }); + + it('should execute callback with metadata & API response', done => { + const body = {}; + const apiResponse = {body}; + sandbox + .stub(ServiceObject.prototype, 'request') + .callsArgWith(1, null, body, apiResponse); + serviceObject.setMetadata({}, (err: Error, metadata: {}) => { + assert.ifError(err); + assert.strictEqual(metadata, body); + done(); + }); + }); + }); + + describe('request_', () => { + let reqOpts: DecorateRequestOptions; + beforeEach(() => { + reqOpts = { + uri: 'uri', + }; + }); + + it('should compose the correct request', done => { + const expectedUri = [ + serviceObject.baseUrl, + serviceObject.id, + reqOpts.uri, + ].join('/'); + + serviceObject.parent.request = (reqOpts_, callback) => { + assert.notStrictEqual(reqOpts_, reqOpts); + assert.strictEqual(reqOpts_.uri, expectedUri); + assert.deepStrictEqual(reqOpts_.interceptors_, []); + callback(null, null, {} as r.Response); + }; + asInternal(serviceObject).request_(reqOpts, () => done()); + }); + + it('should not require a service object ID', done => { + const expectedUri = [serviceObject.baseUrl, reqOpts.uri].join('/'); + serviceObject.parent.request = (reqOpts, callback) => { + assert.strictEqual(reqOpts.uri, expectedUri); + callback(null, null, {} as r.Response); + }; + serviceObject.id = undefined; + asInternal(serviceObject).request_(reqOpts, () => done()); + }); + + it('should support absolute uris', done => { + const expectedUri = 'http://www.google.com'; + serviceObject.parent.request = (reqOpts, callback) => { + assert.strictEqual(reqOpts.uri, expectedUri); + callback(null, null, {} as r.Response); + }; + asInternal(serviceObject).request_({uri: expectedUri}, () => { + done(); + }); + }); + + it('should remove empty components', done => { + const reqOpts = {uri: ''}; + const expectedUri = [ + serviceObject.baseUrl, + serviceObject.id, + // reqOpts.uri (reqOpts.uri is an empty string, so it should be removed) + ].join('/'); + serviceObject.parent.request = (reqOpts_, callback) => { + assert.strictEqual(reqOpts_.uri, expectedUri); + callback(null, null, {} as r.Response); + }; + asInternal(serviceObject).request_(reqOpts, () => done()); + }); + + it('should trim slashes', done => { + const reqOpts = { + uri: '//1/2//', + }; + const expectedUri = [serviceObject.baseUrl, serviceObject.id, '1/2'].join( + '/' + ); + serviceObject.parent.request = (reqOpts_, callback) => { + assert.strictEqual(reqOpts_.uri, expectedUri); + callback(null, null, {} as r.Response); + }; + asInternal(serviceObject).request_(reqOpts, () => { + done(); + }); + }); + + it('should extend interceptors from child ServiceObjects', async () => { + const parent = new ServiceObject(CONFIG) as FakeServiceObject; + parent.interceptors.push({ + request(reqOpts: DecorateRequestOptions) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (reqOpts as any).parent = true; + return reqOpts; + }, + }); + + const child = new ServiceObject({...CONFIG, parent}) as FakeServiceObject; + child.interceptors.push({ + request(reqOpts: DecorateRequestOptions) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (reqOpts as any).child = true; + return reqOpts; + }, + }); + + sandbox + .stub( + parent.parent as SO.ServiceObject, + 'request' + ) + .callsFake((reqOpts, callback) => { + assert.deepStrictEqual( + reqOpts.interceptors_![0].request({} as DecorateRequestOptions), + { + child: true, + } + ); + assert.deepStrictEqual( + reqOpts.interceptors_![1].request({} as DecorateRequestOptions), + { + parent: true, + } + ); + callback(null, null, {} as r.Response); + }); + + await child.request_({uri: ''}); + }); + + it('should pass a clone of the interceptors', done => { + asInternal(serviceObject).interceptors.push({ + request(reqOpts: DecorateRequestOptions) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (reqOpts as any).one = true; + return reqOpts; + }, + }); + + serviceObject.parent.request = (reqOpts, callback) => { + const serviceObjectInterceptors = + asInternal(serviceObject).interceptors; + assert.deepStrictEqual( + reqOpts.interceptors_, + serviceObjectInterceptors + ); + assert.notStrictEqual(reqOpts.interceptors_, serviceObjectInterceptors); + callback(null, null, {} as r.Response); + done(); + }; + asInternal(serviceObject).request_({uri: ''}, () => {}); + }); + + it('should call the parent requestStream method', () => { + const fakeObj = {}; + const expectedUri = [ + serviceObject.baseUrl, + serviceObject.id, + reqOpts.uri, + ].join('/'); + + serviceObject.parent.requestStream = reqOpts_ => { + assert.notStrictEqual(reqOpts_, reqOpts); + assert.strictEqual(reqOpts_.uri, expectedUri); + assert.deepStrictEqual(reqOpts_.interceptors_, []); + return fakeObj as r.Request; + }; + + const opts = {...reqOpts, shouldReturnStream: true}; + const res = asInternal(serviceObject).request_(opts); + assert.strictEqual(res, fakeObj); + }); + }); + + describe('request', () => { + it('should call through to request_', async () => { + const fakeOptions = {} as DecorateRequestOptions; + sandbox + .stub(asInternal(serviceObject), 'request_') + .callsFake((reqOpts, callback) => { + assert.strictEqual(reqOpts, fakeOptions); + callback!(null, null, {} as r.Response); + }); + await serviceObject.request(fakeOptions); + }); + + it('should accept a callback', done => { + const response = {body: {abc: '123'}, statusCode: 200} as r.Response; + sandbox + .stub(asInternal(serviceObject), 'request_') + .callsArgWith(1, null, response.body, response); + serviceObject.request({} as DecorateRequestOptions, (err, body, res) => { + assert.ifError(err); + assert.deepStrictEqual(res, response); + assert.deepStrictEqual(body, response.body); + done(); + }); + }); + + it('should return response with a request error and callback', done => { + const errorBody = '🤮'; + const response = {body: {error: errorBody}, statusCode: 500}; + const err = new Error(errorBody); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (err as any).response = response; + sandbox + .stub(asInternal(serviceObject), 'request_') + .callsArgWith(1, err, response.body, response); + serviceObject.request({} as DecorateRequestOptions, (err, body, res) => { + assert(err instanceof Error); + assert.deepStrictEqual(res, response); + assert.deepStrictEqual(body, response.body); + done(); + }); + }); + }); + + describe('requestStream', () => { + it('should call through to request_', async () => { + const fakeOptions = {} as DecorateRequestOptions; + const serviceObject = new ServiceObject(CONFIG); + asInternal(serviceObject).request_ = reqOpts => { + assert.deepStrictEqual(reqOpts, {shouldReturnStream: true}); + }; + serviceObject.requestStream(fakeOptions); + }); + }); +}); diff --git a/handwritten/storage/test/nodejs-common/service.ts b/handwritten/storage/test/nodejs-common/service.ts new file mode 100644 index 00000000000..502c4e5419f --- /dev/null +++ b/handwritten/storage/test/nodejs-common/service.ts @@ -0,0 +1,718 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 assert from 'assert'; +import {describe, it, before, beforeEach, after} from 'mocha'; +import proxyquire from 'proxyquire'; +import {Request} from 'teeny-request'; +import {AuthClient, GoogleAuth, OAuth2Client} from 'google-auth-library'; + +import {Interceptor} from '../../src/nodejs-common/index.js'; +import { + DEFAULT_PROJECT_ID_TOKEN, + ServiceConfig, + ServiceOptions, +} from '../../src/nodejs-common/service.js'; +import { + BodyResponseCallback, + DecorateRequestOptions, + GCCL_GCS_CMD_KEY, + MakeAuthenticatedRequest, + MakeAuthenticatedRequestFactoryConfig, + util, + Util, +} from '../../src/nodejs-common/util.js'; +import {getUserAgentString, getModuleFormat} from '../../src/util.js'; + +proxyquire.noPreserveCache(); + +const fakeCfg = {} as ServiceConfig; + +const makeAuthRequestFactoryCache = util.makeAuthenticatedRequestFactory; +let makeAuthenticatedRequestFactoryOverride: + | null + | (( + config: MakeAuthenticatedRequestFactoryConfig + ) => MakeAuthenticatedRequest); + +util.makeAuthenticatedRequestFactory = function ( + this: Util, + config: MakeAuthenticatedRequestFactoryConfig +) { + if (makeAuthenticatedRequestFactoryOverride) { + return makeAuthenticatedRequestFactoryOverride.call(this, config); + } + return makeAuthRequestFactoryCache.call(this, config); +}; + +describe('Service', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let service: any; + const Service = proxyquire('../../src/nodejs-common/service', { + './util': util, + }).Service; + + const CONFIG = { + scopes: [], + baseUrl: 'base-url', + projectIdRequired: false, + apiEndpoint: 'common.endpoint.local', + packageJson: { + name: '@google-cloud/service', + version: '0.2.0', + }, + }; + + const OPTIONS = { + authClient: new GoogleAuth(), + credentials: {}, + keyFile: {}, + email: 'email', + projectId: 'project-id', + token: 'token', + } as ServiceOptions; + + beforeEach(() => { + makeAuthenticatedRequestFactoryOverride = null; + service = new Service(CONFIG, OPTIONS); + }); + + describe('instantiation', () => { + it('should not require options', () => { + assert.doesNotThrow(() => { + new Service(CONFIG); + }); + }); + + it('should create an authenticated request factory', () => { + const authenticatedRequest = {} as MakeAuthenticatedRequest; + + makeAuthenticatedRequestFactoryOverride = ( + config: MakeAuthenticatedRequestFactoryConfig + ) => { + const expectedConfig = { + ...CONFIG, + authClient: OPTIONS.authClient, + credentials: OPTIONS.credentials, + keyFile: OPTIONS.keyFilename, + email: OPTIONS.email, + projectIdRequired: CONFIG.projectIdRequired, + projectId: OPTIONS.projectId, + clientOptions: { + universeDomain: undefined, + }, + }; + + assert.deepStrictEqual(config, expectedConfig); + + return authenticatedRequest; + }; + + const svc = new Service(CONFIG, OPTIONS); + assert.strictEqual(svc.makeAuthenticatedRequest, authenticatedRequest); + }); + + it('should localize the authClient', () => { + const authClient = {}; + makeAuthenticatedRequestFactoryOverride = () => { + return { + authClient, + } as MakeAuthenticatedRequest; + }; + const service = new Service(CONFIG, OPTIONS); + assert.strictEqual(service.authClient, authClient); + }); + + it('should localize the provided authClient', () => { + const service = new Service(CONFIG, OPTIONS); + assert.strictEqual(service.authClient, OPTIONS.authClient); + }); + + describe('`AuthClient` support', () => { + // Using a custom `AuthClient` to ensure any `AuthClient` would work + class CustomAuthClient extends AuthClient { + async getAccessToken() { + return {token: '', res: undefined}; + } + + async getRequestHeaders() { + return {}; + } + + request = OAuth2Client.prototype.request.bind(this); + } + + it('should accept an `AuthClient` passed to config', async () => { + const authClient = new CustomAuthClient(); + const serviceObject = new Service({...CONFIG, authClient}); + + // The custom `AuthClient` should be passed to `GoogleAuth` and used internally + const client = await serviceObject.authClient.getClient(); + + assert.strictEqual(client, authClient); + }); + + it('should accept an `AuthClient` passed to options', async () => { + const authClient = new CustomAuthClient(); + const serviceObject = new Service(CONFIG, {authClient}); + + // The custom `AuthClient` should be passed to `GoogleAuth` and used internally + const client = await serviceObject.authClient.getClient(); + + assert.strictEqual(client, authClient); + }); + }); + + it('should localize the baseUrl', () => { + assert.strictEqual(service.baseUrl, CONFIG.baseUrl); + }); + + it('should localize the apiEndpoint', () => { + assert.strictEqual(service.apiEndpoint, CONFIG.apiEndpoint); + }); + + it('should default the timeout to undefined', () => { + assert.strictEqual(service.timeout, undefined); + }); + + it('should localize the timeout', () => { + const timeout = 10000; + const options = {...OPTIONS, timeout}; + const service = new Service(fakeCfg, options); + assert.strictEqual(service.timeout, timeout); + }); + + it('should default globalInterceptors to an empty array', () => { + assert.deepStrictEqual(service.globalInterceptors, []); + }); + + it('should preserve the original global interceptors', () => { + const globalInterceptors: Interceptor[] = []; + const options = {...OPTIONS}; + options.interceptors_ = globalInterceptors; + const service = new Service(fakeCfg, options); + assert.strictEqual(service.globalInterceptors, globalInterceptors); + }); + + it('should default interceptors to an empty array', () => { + assert.deepStrictEqual(service.interceptors, []); + }); + + it('should localize package.json', () => { + assert.strictEqual(service.packageJson, CONFIG.packageJson); + }); + + it('should localize the projectId', () => { + assert.strictEqual(service.projectId, OPTIONS.projectId); + }); + + it('should default projectId with placeholder', () => { + const service = new Service(fakeCfg, {}); + assert.strictEqual(service.projectId, DEFAULT_PROJECT_ID_TOKEN); + }); + + it('should localize the projectIdRequired', () => { + assert.strictEqual(service.projectIdRequired, CONFIG.projectIdRequired); + }); + + it('should default projectIdRequired to true', () => { + const service = new Service(fakeCfg, OPTIONS); + assert.strictEqual(service.projectIdRequired, true); + }); + + it('should disable forever agent for Cloud Function envs', () => { + process.env.FUNCTION_NAME = 'cloud-function-name'; + const service = new Service(CONFIG, OPTIONS); + delete process.env.FUNCTION_NAME; + + const interceptor = service.interceptors[0]; + + const modifiedReqOpts = interceptor.request({forever: true}); + assert.strictEqual(modifiedReqOpts.forever, false); + }); + }); + + describe('getRequestInterceptors', () => { + it('should call the request interceptors in order', () => { + // Called first. + service.globalInterceptors.push({ + request(reqOpts: {order: string}) { + reqOpts.order = '1'; + return reqOpts; + }, + }); + + // Called third. + service.interceptors.push({ + request(reqOpts: {order: string}) { + reqOpts.order += '3'; + return reqOpts; + }, + }); + + // Called second. + service.globalInterceptors.push({ + request(reqOpts: {order: string}) { + reqOpts.order += '2'; + return reqOpts; + }, + }); + + // Called fourth. + service.interceptors.push({ + request(reqOpts: {order: string}) { + reqOpts.order += '4'; + return reqOpts; + }, + }); + + const reqOpts: {order?: string} = {}; + const requestInterceptors = service.getRequestInterceptors(); + requestInterceptors.forEach((requestInterceptor: Function) => { + Object.assign(reqOpts, requestInterceptor(reqOpts)); + }); + assert.strictEqual(reqOpts.order, '1234'); + }); + + it('should not affect original interceptor arrays', () => { + function request(reqOpts: DecorateRequestOptions) { + return reqOpts; + } + + service.globalInterceptors = [{request}]; + service.interceptors = [{request}]; + + const originalGlobalInterceptors = [].slice.call( + service.globalInterceptors + ); + const originalLocalInterceptors = [].slice.call(service.interceptors); + + service.getRequestInterceptors(); + + assert.deepStrictEqual( + service.globalInterceptors, + originalGlobalInterceptors + ); + assert.deepStrictEqual(service.interceptors, originalLocalInterceptors); + }); + + it('should not call unrelated interceptors', () => { + service.interceptors.push({ + anotherInterceptor() { + throw new Error('Unrelated interceptor was called.'); + }, + request() { + return {}; + }, + }); + + const requestInterceptors = service.getRequestInterceptors(); + requestInterceptors.forEach((requestInterceptor: Function) => { + requestInterceptor(); + }); + }); + }); + + describe('getProjectId', () => { + it('should get the project ID from the auth client', done => { + service.authClient = { + getProjectId() { + done(); + }, + }; + + service.getProjectId(assert.ifError); + }); + + it('should return error from auth client', done => { + const error = new Error('Error.'); + + service.authClient = { + async getProjectId() { + throw error; + }, + }; + + service.getProjectId((err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should update and return the project ID if found', done => { + const service = new Service(fakeCfg, {}); + const projectId = 'detected-project-id'; + + service.authClient = { + async getProjectId() { + return projectId; + }, + }; + + service.getProjectId((err: Error, projectId_: string) => { + assert.ifError(err); + assert.strictEqual(service.projectId, projectId); + assert.strictEqual(projectId_, projectId); + done(); + }); + }); + + it('should return a promise if no callback is provided', () => { + const value = {}; + service.getProjectIdAsync = () => value; + assert.strictEqual(service.getProjectId(), value); + }); + }); + + describe('request_', () => { + let reqOpts: DecorateRequestOptions; + + beforeEach(() => { + reqOpts = { + uri: 'uri', + }; + }); + + it('should compose the correct request', done => { + const expectedUri = [service.baseUrl, reqOpts.uri].join('/'); + service.makeAuthenticatedRequest = ( + reqOpts_: DecorateRequestOptions, + callback: BodyResponseCallback + ) => { + assert.notStrictEqual(reqOpts_, reqOpts); + assert.strictEqual(reqOpts_.uri, expectedUri); + assert.strictEqual(reqOpts.interceptors_, undefined); + callback(null); // done() + }; + service.request_(reqOpts, () => done()); + }); + + it('should support absolute uris', done => { + const expectedUri = 'http://www.google.com'; + + service.makeAuthenticatedRequest = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, expectedUri); + done(); + }; + + service.request_({uri: expectedUri}, assert.ifError); + }); + + it('should trim slashes', done => { + const reqOpts = { + uri: '//1/2//', + }; + + const expectedUri = [service.baseUrl, '1/2'].join('/'); + + service.makeAuthenticatedRequest = (reqOpts_: DecorateRequestOptions) => { + assert.strictEqual(reqOpts_.uri, expectedUri); + done(); + }; + + service.request_(reqOpts, assert.ifError); + }); + + it('should replace path/:subpath with path:subpath', done => { + const reqOpts = { + uri: ':test', + }; + + const expectedUri = service.baseUrl + reqOpts.uri; + service.makeAuthenticatedRequest = (reqOpts_: DecorateRequestOptions) => { + assert.strictEqual(reqOpts_.uri, expectedUri); + done(); + }; + service.request_(reqOpts, assert.ifError); + }); + + it('should not set timeout', done => { + service.makeAuthenticatedRequest = (reqOpts_: DecorateRequestOptions) => { + assert.strictEqual(reqOpts_.timeout, undefined); + done(); + }; + service.request_(reqOpts, assert.ifError); + }); + + it('should set reqOpt.timeout', done => { + const timeout = 10000; + const config = {...CONFIG}; + const options = {...OPTIONS, timeout}; + const service = new Service(config, options); + + service.makeAuthenticatedRequest = (reqOpts_: DecorateRequestOptions) => { + assert.strictEqual(reqOpts_.timeout, timeout); + done(); + }; + service.request_(reqOpts, assert.ifError); + }); + + it('should add the User Agent', done => { + service.makeAuthenticatedRequest = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual( + reqOpts.headers!['User-Agent'], + getUserAgentString() + ); + done(); + }; + + service.request_(reqOpts, assert.ifError); + }); + + it('should add the api-client header', done => { + service.makeAuthenticatedRequest = (reqOpts: DecorateRequestOptions) => { + const pkg = service.packageJson; + const r = new RegExp( + `^gl-node/${process.versions.node} gccl/${ + pkg.version + }-${getModuleFormat()} gccl-invocation-id/(?[^W]+)$` + ); + assert.ok(r.test(reqOpts.headers!['x-goog-api-client'])); + done(); + }; + + service.request_(reqOpts, assert.ifError); + }); + + it('should add the `gccl-gcs-cmd` to the api-client header when provided', done => { + const expected = 'example.expected/value'; + service.makeAuthenticatedRequest = (reqOpts: DecorateRequestOptions) => { + const pkg = service.packageJson; + const r = new RegExp( + `^gl-node/${process.versions.node} gccl/${ + pkg.version + }-${getModuleFormat()} gccl-invocation-id/(?[^W]+) gccl-gcs-cmd/${expected}$` + ); + assert.ok(r.test(reqOpts.headers!['x-goog-api-client'])); + done(); + }; + + service.request_( + {...reqOpts, [GCCL_GCS_CMD_KEY]: expected}, + assert.ifError + ); + }); + + describe('projectIdRequired', () => { + describe('false', () => { + it('should include the projectId', done => { + const config = {...CONFIG, projectIdRequired: false}; + const service = new Service(config, OPTIONS); + + const expectedUri = [service.baseUrl, reqOpts.uri].join('/'); + + service.makeAuthenticatedRequest = ( + reqOpts_: DecorateRequestOptions + ) => { + assert.strictEqual(reqOpts_.uri, expectedUri); + + done(); + }; + + service.request_(reqOpts, assert.ifError); + }); + }); + + describe('true', () => { + it('should not include the projectId', done => { + const config = {...CONFIG, projectIdRequired: true}; + const service = new Service(config, OPTIONS); + + const expectedUri = [ + service.baseUrl, + 'projects', + service.projectId, + reqOpts.uri, + ].join('/'); + + service.makeAuthenticatedRequest = ( + reqOpts_: DecorateRequestOptions + ) => { + assert.strictEqual(reqOpts_.uri, expectedUri); + + done(); + }; + + service.request_(reqOpts, assert.ifError); + }); + + it('should use projectId override', done => { + const config = {...CONFIG, projectIdRequired: true}; + const service = new Service(config, OPTIONS); + const projectOverride = 'turing'; + + reqOpts.projectId = projectOverride; + + const expectedUri = [ + service.baseUrl, + 'projects', + projectOverride, + reqOpts.uri, + ].join('/'); + + service.makeAuthenticatedRequest = ( + reqOpts_: DecorateRequestOptions + ) => { + assert.strictEqual(reqOpts_.uri, expectedUri); + + done(); + }; + + service.request_(reqOpts, assert.ifError); + }); + }); + }); + + describe('request interceptors', () => { + type FakeRequestOptions = DecorateRequestOptions & {a: string; b: string}; + + it('should include request interceptors', done => { + const requestInterceptors = [ + (reqOpts: FakeRequestOptions) => { + reqOpts.a = 'a'; + return reqOpts; + }, + (reqOpts: FakeRequestOptions) => { + reqOpts.b = 'b'; + return reqOpts; + }, + ]; + + service.getRequestInterceptors = () => { + return requestInterceptors; + }; + + service.makeAuthenticatedRequest = (reqOpts: FakeRequestOptions) => { + assert.strictEqual(reqOpts.a, 'a'); + assert.strictEqual(reqOpts.b, 'b'); + done(); + }; + + service.request_(reqOpts, assert.ifError); + }); + + it('should combine reqOpts interceptors', done => { + const requestInterceptors = [ + (reqOpts: FakeRequestOptions) => { + reqOpts.a = 'a'; + return reqOpts; + }, + ]; + + service.getRequestInterceptors = () => { + return requestInterceptors; + }; + + reqOpts.interceptors_ = [ + { + request: (reqOpts: FakeRequestOptions) => { + reqOpts.b = 'b'; + return reqOpts; + }, + }, + ]; + + service.makeAuthenticatedRequest = (reqOpts: FakeRequestOptions) => { + assert.strictEqual(reqOpts.a, 'a'); + assert.strictEqual(reqOpts.b, 'b'); + assert.strictEqual(typeof reqOpts.interceptors_, 'undefined'); + done(); + }; + + service.request_(reqOpts, assert.ifError); + }); + }); + + describe('error handling', () => { + it('should re-throw any makeAuthenticatedRequest callback error', done => { + const err = new Error('🥓'); + const res = {body: undefined}; + service.makeAuthenticatedRequest = (_: void, callback: Function) => { + callback(err, res.body, res); + }; + service.request_({uri: ''}, (e: Error) => { + assert.strictEqual(e, err); + done(); + }); + }); + }); + }); + + describe('request', () => { + let request_: Request; + + before(() => { + request_ = Service.prototype.request_; + }); + + after(() => { + Service.prototype.request_ = request_; + }); + + it('should call through to _request', async () => { + const fakeOpts = {}; + Service.prototype.request_ = async (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts, fakeOpts); + return Promise.resolve({}); + }; + await service.request(fakeOpts); + }); + + it('should accept a callback', done => { + const fakeOpts = {}; + const response = {body: {abc: '123'}, statusCode: 200}; + Service.prototype.request_ = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts, fakeOpts); + callback(null, response.body, response); + }; + + service.request(fakeOpts, (err: Error, body: {}, res: {}) => { + assert.ifError(err); + assert.deepStrictEqual(res, response); + assert.deepStrictEqual(body, response.body); + done(); + }); + }); + }); + + describe('requestStream', () => { + let request_: Request; + + before(() => { + request_ = Service.prototype.request_; + }); + + after(() => { + Service.prototype.request_ = request_; + }); + + it('should return whatever _request returns', async () => { + const fakeOpts = {}; + const fakeStream = {}; + + Service.prototype.request_ = async (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts, {shouldReturnStream: true}); + return fakeStream; + }; + + const stream = await service.requestStream(fakeOpts); + assert.strictEqual(stream, fakeStream); + }); + }); +}); diff --git a/handwritten/storage/test/nodejs-common/util.ts b/handwritten/storage/test/nodejs-common/util.ts new file mode 100644 index 00000000000..3efc73d11d6 --- /dev/null +++ b/handwritten/storage/test/nodejs-common/util.ts @@ -0,0 +1,1893 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 { + MissingProjectIdError, + replaceProjectIdToken, +} from '@google-cloud/projectify'; +import assert from 'assert'; +import {describe, it, before, beforeEach, afterEach} from 'mocha'; +import { + AuthClient, + GoogleAuth, + GoogleAuthOptions, + OAuth2Client, +} from 'google-auth-library'; +import * as nock from 'nock'; +import proxyquire from 'proxyquire'; +import * as r from 'teeny-request'; +import retryRequest from 'retry-request'; +import * as sinon from 'sinon'; +import * as stream from 'stream'; +import {teenyRequest} from 'teeny-request'; + +import { + Abortable, + ApiError, + DecorateRequestOptions, + Duplexify, + GCCL_GCS_CMD_KEY, + GoogleErrorBody, + GoogleInnerError, + MakeAuthenticatedRequestFactoryConfig, + MakeRequestConfig, + ParsedHttpRespMessage, + Util, +} from '../../src/nodejs-common/util.js'; +import {DEFAULT_PROJECT_ID_TOKEN} from '../../src/nodejs-common/service.js'; +import duplexify from 'duplexify'; + +nock.disableNetConnect(); + +const fakeResponse = { + statusCode: 200, + body: {star: 'trek'}, +} as r.Response; + +const fakeBadResp = { + statusCode: 400, + statusMessage: 'Not Good', +} as r.Response; + +const fakeReqOpts: DecorateRequestOptions = { + uri: 'http://so-fake', + method: 'GET', +}; + +const fakeError = new Error('this error is like so fake'); + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let requestOverride: any; +function fakeRequest() { + // eslint-disable-next-line prefer-spread, prefer-rest-params + return (requestOverride || teenyRequest).apply(null, arguments); +} + +fakeRequest.defaults = (defaults: r.CoreOptions) => { + assert.ok( + /^gl-node\/(?[^W]+) gccl\/(?[^W]+) gccl-invocation-id\/(?[^W]+)$/.test( + defaults.headers!['x-goog-api-client'] + ) + ); + return fakeRequest; +}; + +let retryRequestOverride: Function | null; +function fakeRetryRequest() { + // eslint-disable-next-line prefer-spread, prefer-rest-params + return (retryRequestOverride || retryRequest).apply(null, arguments); +} + +let replaceProjectIdTokenOverride: Function | null; +function fakeReplaceProjectIdToken() { + // eslint-disable-next-line prefer-spread, prefer-rest-params + return (replaceProjectIdTokenOverride || replaceProjectIdToken).apply( + null, + // eslint-disable-next-line prefer-spread, prefer-rest-params + arguments + ); +} + +describe('common/util', () => { + let util: Util & {[index: string]: Function}; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function stub(method: keyof Util, meth: (...args: any[]) => any) { + return sandbox.stub(util, method).callsFake(meth); + } + + function createExpectedErrorMessage(errors: string[]): string { + if (errors.length < 2) { + return errors[0]; + } + + errors = errors.map((error, i) => ` ${i + 1}. ${error}`); + errors.unshift( + 'Multiple errors occurred during the request. Please see the `errors` array for complete details.\n' + ); + errors.push('\n'); + + return errors.join('\n'); + } + + const fakeGoogleAuth = { + // Using a custom `AuthClient` to ensure any `AuthClient` would work + AuthClient: class CustomAuthClient extends AuthClient { + async getAccessToken() { + return {token: '', res: undefined}; + } + + async getRequestHeaders() { + return {}; + } + + request = OAuth2Client.prototype.request.bind(this); + }, + GoogleAuth: class { + constructor(config?: GoogleAuthOptions) { + return new GoogleAuth(config); + } + }, + }; + + before(() => { + util = proxyquire('../../src/nodejs-common/util', { + 'google-auth-library': fakeGoogleAuth, + 'retry-request': fakeRetryRequest, + 'teeny-request': {teenyRequest: fakeRequest}, + '@google-cloud/projectify': { + replaceProjectIdToken: fakeReplaceProjectIdToken, + }, + }).util; + }); + + let sandbox: sinon.SinonSandbox; + beforeEach(() => { + sandbox = sinon.createSandbox(); + requestOverride = null; + retryRequestOverride = null; + replaceProjectIdTokenOverride = null; + }); + afterEach(() => { + sandbox.restore(); + }); + + describe('ApiError', () => { + it('should accept just a message', () => { + const expectedMessage = 'Hi, I am an error message!'; + const apiError = new ApiError(expectedMessage); + + assert.strictEqual(apiError.message, expectedMessage); + }); + + it('should use message in stack', () => { + const expectedMessage = 'Message is in the stack too!'; + const apiError = new ApiError(expectedMessage); + assert(apiError.stack?.includes(expectedMessage)); + }); + + it('should build correct ApiError', () => { + const fakeMessage = 'Formatted Error.'; + const fakeResponse = {statusCode: 200} as r.Response; + const errors = [{message: 'Hi'}, {message: 'Bye'}]; + const error = { + errors, + code: 100, + message: 'Uh oh', + response: fakeResponse, + }; + + sandbox + .stub(ApiError, 'createMultiErrorMessage') + .withArgs(error, errors) + .returns(fakeMessage); + + const apiError = new ApiError(error); + assert.strictEqual(apiError.errors, error.errors); + assert.strictEqual(apiError.code, error.code); + assert.strictEqual(apiError.response, error.response); + assert.strictEqual(apiError.message, fakeMessage); + }); + + it('should parse the response body for errors', () => { + const fakeMessage = 'Formatted Error.'; + const error = {message: 'Error.'}; + const errors = [error, error]; + + const errorBody = { + code: 123, + response: { + body: JSON.stringify({ + error: { + errors, + }, + }), + } as r.Response, + }; + + sandbox + .stub(ApiError, 'createMultiErrorMessage') + .withArgs(errorBody, errors) + .returns(fakeMessage); + + const apiError = new ApiError(errorBody); + assert.strictEqual(apiError.message, fakeMessage); + }); + + describe('createMultiErrorMessage', () => { + it('should append the custom error message', () => { + const errorMessage = 'API error message'; + const customErrorMessage = 'Custom error message'; + + const errors = [new Error(errorMessage)]; + const error = { + code: 100, + response: {} as r.Response, + message: customErrorMessage, + }; + + const expectedErrorMessage = createExpectedErrorMessage([ + customErrorMessage, + errorMessage, + ]); + const multiError = ApiError.createMultiErrorMessage(error, errors); + assert.strictEqual(multiError, expectedErrorMessage); + }); + + it('should use any inner errors', () => { + const messages = ['Hi, I am an error!', 'Me too!']; + const errors: GoogleInnerError[] = messages.map(message => ({message})); + const error: GoogleErrorBody = { + code: 100, + response: {} as r.Response, + }; + + const expectedErrorMessage = createExpectedErrorMessage(messages); + const multiError = ApiError.createMultiErrorMessage(error, errors); + assert.strictEqual(multiError, expectedErrorMessage); + }); + + it('should parse and append the decoded response body', () => { + const errorMessage = 'API error message'; + const responseBodyMsg = 'Response body message <'; + + const error = { + message: errorMessage, + code: 100, + response: { + body: Buffer.from(responseBodyMsg), + } as r.Response, + }; + + const expectedErrorMessage = createExpectedErrorMessage([ + 'API error message', + 'Response body message <', + ]); + const multiError = ApiError.createMultiErrorMessage(error); + assert.strictEqual(multiError, expectedErrorMessage); + }); + + it('should use default message if there are no errors', () => { + const fakeResponse = {statusCode: 200} as r.Response; + const expectedErrorMessage = 'A failure occurred during this request.'; + const error = { + code: 100, + response: fakeResponse, + }; + + const multiError = ApiError.createMultiErrorMessage(error); + assert.strictEqual(multiError, expectedErrorMessage); + }); + + it('should filter out duplicate errors', () => { + const expectedErrorMessage = 'Error during request.'; + const error = { + code: 100, + message: expectedErrorMessage, + response: { + body: expectedErrorMessage, + } as r.Response, + }; + + const multiError = ApiError.createMultiErrorMessage(error); + assert.strictEqual(multiError, expectedErrorMessage); + }); + }); + }); + + describe('PartialFailureError', () => { + it('should build correct PartialFailureError', () => { + const fakeMessage = 'Formatted Error.'; + const errors = [{}, {}]; + const error = { + code: 123, + errors, + response: fakeResponse, + message: 'Partial failure occurred', + }; + + sandbox + .stub(util.ApiError, 'createMultiErrorMessage') + .withArgs(error, errors) + .returns(fakeMessage); + + const partialFailureError = new util.PartialFailureError(error); + + assert.strictEqual(partialFailureError.errors, error.errors); + assert.strictEqual(partialFailureError.name, 'PartialFailureError'); + assert.strictEqual(partialFailureError.response, error.response); + assert.strictEqual(partialFailureError.message, fakeMessage); + }); + }); + + describe('handleResp', () => { + it('should handle errors', done => { + const error = new Error('Error.'); + + util.handleResp(error, fakeResponse, null, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('uses a no-op callback if none is sent', () => { + util.handleResp(null, fakeResponse, ''); + }); + + it('should parse response', done => { + stub('parseHttpRespMessage', resp_ => { + assert.deepStrictEqual(resp_, fakeResponse); + return { + resp: fakeResponse, + }; + }); + + stub('parseHttpRespBody', body_ => { + assert.strictEqual(body_, fakeResponse.body); + return { + body: fakeResponse.body, + }; + }); + + util.handleResp( + fakeError, + fakeResponse, + fakeResponse.body, + (err, body, resp) => { + assert.deepStrictEqual(err, fakeError); + assert.deepStrictEqual(body, fakeResponse.body); + assert.deepStrictEqual(resp, fakeResponse); + done(); + } + ); + }); + + it('should parse response for error', done => { + const error = new Error('Error.'); + + sandbox.stub(util, 'parseHttpRespMessage').callsFake(() => { + return {err: error} as ParsedHttpRespMessage; + }); + + util.handleResp(null, fakeResponse, {}, err => { + assert.deepStrictEqual(err, error); + done(); + }); + }); + + it('should parse body for error', done => { + const error = new Error('Error.'); + + stub('parseHttpRespBody', () => { + return {err: error}; + }); + + util.handleResp(null, fakeResponse, {}, err => { + assert.deepStrictEqual(err, error); + done(); + }); + }); + + it('should not parse undefined response', done => { + stub('parseHttpRespMessage', () => done()); // Will throw. + util.handleResp(null, null, null, done); + }); + + it('should not parse undefined body', done => { + stub('parseHttpRespBody', () => done()); // Will throw. + util.handleResp(null, null, null, done); + }); + + it('should handle non-JSON body', done => { + const unparsableBody = 'Unparsable body.'; + + util.handleResp(null, null, unparsableBody, (err, body) => { + assert(body.includes(unparsableBody)); + done(); + }); + }); + + it('should include the status code when the error body cannot be JSON-parsed', done => { + const unparsableBody = 'Bad gateway'; + const statusCode = 502; + + util.handleResp( + null, + {body: unparsableBody, statusCode} as r.Response, + unparsableBody, + err => { + assert(err, 'there should be an error'); + const apiError = err! as ApiError; + assert.strictEqual(apiError.code, statusCode); + + const response = apiError.response; + if (!response) { + assert.fail('there should be a response property on the error'); + } else { + assert.strictEqual(response.body, unparsableBody); + } + + done(); + } + ); + }); + }); + + describe('parseHttpRespMessage', () => { + it('should build ApiError with non-200 status and message', () => { + const res = util.parseHttpRespMessage(fakeBadResp); + const error_ = res.err!; + assert.strictEqual(error_.code, fakeBadResp.statusCode); + assert.strictEqual(error_.message, fakeBadResp.statusMessage); + assert.strictEqual(error_.response, fakeBadResp); + }); + + it('should return the original response message', () => { + const parsedHttpRespMessage = util.parseHttpRespMessage(fakeBadResp); + assert.strictEqual(parsedHttpRespMessage.resp, fakeBadResp); + }); + }); + + describe('parseHttpRespBody', () => { + it('should detect body errors', () => { + const apiErr = { + errors: [{message: 'bar'}], + code: 400, + message: 'an error occurred', + }; + + const parsedHttpRespBody = util.parseHttpRespBody({error: apiErr}); + const expectedErrorMessage = createExpectedErrorMessage([ + apiErr.message, + apiErr.errors[0].message, + ]); + + const err = parsedHttpRespBody.err as ApiError; + assert.deepStrictEqual(err.errors, apiErr.errors); + assert.strictEqual(err.code, apiErr.code); + assert.deepStrictEqual(err.message, expectedErrorMessage); + }); + + it('should try to parse JSON if body is string', () => { + const httpRespBody = '{ "foo": "bar" }'; + const parsedHttpRespBody = util.parseHttpRespBody(httpRespBody); + + assert.strictEqual(parsedHttpRespBody.body.foo, 'bar'); + }); + + it('should return the original body', () => { + const httpRespBody = {}; + const parsedHttpRespBody = util.parseHttpRespBody(httpRespBody); + assert.strictEqual(parsedHttpRespBody.body, httpRespBody); + }); + }); + + describe('makeWritableStream', () => { + it('should use defaults', done => { + const dup = duplexify(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const metadata = {a: 'b', c: 'd'} as any; + util.makeWritableStream(dup, { + metadata, + makeAuthenticatedRequest(request: DecorateRequestOptions) { + assert.strictEqual(request.method, 'POST'); + assert.strictEqual(request.qs.uploadType, 'multipart'); + assert.strictEqual(request.timeout, 0); + assert.strictEqual(request.maxRetries, 0); + assert.strictEqual(Array.isArray(request.multipart), true); + + const mp = request.multipart as r.RequestPart[]; + + assert.strictEqual( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (mp[0] as any)['Content-Type'], + 'application/json' + ); + assert.strictEqual(mp[0].body, JSON.stringify(metadata)); + + assert.strictEqual( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (mp[1] as any)['Content-Type'], + 'application/octet-stream' + ); + // (is a writable stream:) + assert.strictEqual( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof (mp[1].body as any)._writableState, + 'object' + ); + + done(); + }, + }); + }); + + it('should allow overriding defaults', done => { + const dup = duplexify(); + + const req = { + uri: 'http://foo', + method: 'PUT', + qs: { + uploadType: 'media', + }, + [GCCL_GCS_CMD_KEY]: 'some.value', + } as DecorateRequestOptions; + + util.makeWritableStream(dup, { + metadata: { + contentType: 'application/json', + }, + makeAuthenticatedRequest(request) { + assert.strictEqual(request.method, req.method); + assert.deepStrictEqual(request.qs, req.qs); + assert.strictEqual(request.uri, req.uri); + assert.strictEqual(request[GCCL_GCS_CMD_KEY], req[GCCL_GCS_CMD_KEY]); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mp = request.multipart as any[]; + assert.strictEqual(mp[1]['Content-Type'], 'application/json'); + + done(); + }, + + request: req, + }); + }); + + it('should emit an error', done => { + const error = new Error('Error.'); + + const ws = duplexify(); + ws.on('error', err => { + assert.strictEqual(err, error); + done(); + }); + + util.makeWritableStream(ws, { + makeAuthenticatedRequest(request, opts) { + opts!.onAuthenticated(error); + }, + }); + }); + + it('should set the writable stream', done => { + const dup = duplexify(); + + dup.setWritable = () => { + done(); + }; + + util.makeWritableStream(dup, {makeAuthenticatedRequest() {}}); + }); + + it('dup should emit a progress event with the bytes written', done => { + let happened = false; + + const dup = duplexify(); + dup.on('progress', () => { + happened = true; + }); + + util.makeWritableStream(dup, {makeAuthenticatedRequest() {}}, util.noop); + dup.write(Buffer.from('abcdefghijklmnopqrstuvwxyz'), 'utf-8', util.noop); + + assert.strictEqual(happened, true); + done(); + }); + + it('should emit an error if the request fails', done => { + const dup = duplexify(); + const fakeStream = new stream.Writable(); + const error = new Error('Error.'); + fakeStream.write = () => false; + dup.end = () => dup; + + stub('handleResp', (err, res, body, callback) => { + callback(error); + }); + + requestOverride = ( + reqOpts: DecorateRequestOptions, + callback: (err: Error) => void + ) => { + callback(error); + }; + + requestOverride.defaults = () => requestOverride; + + dup.on('error', err => { + assert.strictEqual(err, error); + done(); + }); + + util.makeWritableStream(dup, { + makeAuthenticatedRequest(request, opts) { + opts.onAuthenticated(null); + }, + }); + + setImmediate(() => { + fakeStream.emit('complete', {}); + }); + }); + + it('should emit the response', done => { + const dup = duplexify(); + const fakeStream = new stream.Writable(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (fakeStream as any).write = () => {}; + + stub('handleResp', (err, res, body, callback) => { + callback(); + }); + + requestOverride = ( + reqOpts: DecorateRequestOptions, + callback: (err: Error | null, res: r.Response) => void + ) => { + callback(null, fakeResponse); + }; + + requestOverride.defaults = () => requestOverride; + const options = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeAuthenticatedRequest(request: DecorateRequestOptions, opts: any) { + opts.onAuthenticated(); + }, + }; + + dup.on('response', resp => { + assert.strictEqual(resp, fakeResponse); + done(); + }); + + util.makeWritableStream(dup, options, util.noop); + }); + + it('should pass back the response data to the callback', done => { + const dup = duplexify(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const fakeStream: any = new stream.Writable(); + const fakeResponse = {}; + + fakeStream.write = () => {}; + + stub('handleResp', (err, res, body, callback) => { + callback(null, fakeResponse); + }); + + requestOverride = ( + reqOpts: DecorateRequestOptions, + callback: () => void + ) => { + callback(); + }; + requestOverride.defaults = () => { + return requestOverride; + }; + + const options = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + makeAuthenticatedRequest(request: DecorateRequestOptions, opts: any) { + opts.onAuthenticated(); + }, + }; + + util.makeWritableStream(dup, options, (data: {}) => { + assert.strictEqual(data, fakeResponse); + done(); + }); + + setImmediate(() => { + fakeStream.emit('complete', {}); + }); + }); + }); + + describe('makeAuthenticatedRequestFactory', () => { + const AUTH_CLIENT_PROJECT_ID = 'authclient-project-id'; + const authClient = { + getCredentials() {}, + getProjectId: () => Promise.resolve(AUTH_CLIENT_PROJECT_ID), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; + + it('should create an authClient', done => { + const config = {test: true} as MakeAuthenticatedRequestFactoryConfig; + + sandbox + .stub(fakeGoogleAuth, 'GoogleAuth') + .callsFake((config_: GoogleAuthOptions) => { + assert.deepStrictEqual(config_, { + ...config, + authClient: undefined, + clientOptions: undefined, + }); + setImmediate(done); + return authClient; + }); + + util.makeAuthenticatedRequestFactory(config); + }); + + it('should pass an `AuthClient` to `GoogleAuth` when provided', done => { + const customAuthClient = new fakeGoogleAuth.AuthClient(); + + const config: MakeAuthenticatedRequestFactoryConfig = { + authClient: customAuthClient, + clientOptions: undefined, + }; + + sandbox + .stub(fakeGoogleAuth, 'GoogleAuth') + .callsFake((config_: GoogleAuthOptions) => { + assert.deepStrictEqual(config_, config); + setImmediate(done); + return authClient; + }); + + util.makeAuthenticatedRequestFactory(config); + }); + + it('should not pass projectId token to google-auth-library', done => { + const config = {projectId: DEFAULT_PROJECT_ID_TOKEN}; + + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').callsFake(config_ => { + assert.strictEqual(config_.projectId, undefined); + setImmediate(done); + return authClient; + }); + + util.makeAuthenticatedRequestFactory(config); + }); + + it('should not remove projectId from config object', done => { + const config = {projectId: DEFAULT_PROJECT_ID_TOKEN}; + + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').callsFake(() => { + assert.strictEqual(config.projectId, DEFAULT_PROJECT_ID_TOKEN); + setImmediate(done); + return authClient; + }); + + util.makeAuthenticatedRequestFactory(config); + }); + + it('should return a function', () => { + assert.strictEqual( + typeof util.makeAuthenticatedRequestFactory({}), + 'function' + ); + }); + + it('should return a getCredentials method', done => { + function getCredentials() { + done(); + } + + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').callsFake(() => { + return {getCredentials}; + }); + + const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory({}); + makeAuthenticatedRequest.getCredentials(util.noop); + }); + + it('should return the authClient', () => { + const authClient = {getCredentials() {}}; + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + const mar = util.makeAuthenticatedRequestFactory({}); + assert.strictEqual(mar.authClient, authClient); + }); + + describe('customEndpoint (no authentication attempted)', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let makeAuthenticatedRequest: any; + const config = {customEndpoint: true}; + + beforeEach(() => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(config); + }); + + it('should decorate the request', done => { + const decoratedRequest = {}; + stub('decorateRequest', reqOpts_ => { + assert.strictEqual(reqOpts_, fakeReqOpts); + return decoratedRequest; + }); + + makeAuthenticatedRequest(fakeReqOpts, { + onAuthenticated( + err: Error, + authenticatedReqOpts: DecorateRequestOptions + ) { + assert.ifError(err); + assert.strictEqual(authenticatedReqOpts, decoratedRequest); + done(); + }, + }); + }); + + it('should return an error while decorating', done => { + const error = new Error('Error.'); + stub('decorateRequest', () => { + throw error; + }); + makeAuthenticatedRequest(fakeReqOpts, { + onAuthenticated(err: Error) { + assert.strictEqual(err, error); + done(); + }, + }); + }); + + it('should pass options back to callback', done => { + const reqOpts = {a: 'b', c: 'd'}; + makeAuthenticatedRequest(reqOpts, { + onAuthenticated( + err: Error, + authenticatedReqOpts: DecorateRequestOptions + ) { + assert.ifError(err); + assert.deepStrictEqual(reqOpts, authenticatedReqOpts); + done(); + }, + }); + }); + + it('should not authenticate requests with a custom API', done => { + const reqOpts = {a: 'b', c: 'd'}; + + stub('makeRequest', rOpts => { + assert.deepStrictEqual(rOpts, reqOpts); + done(); + }); + + makeAuthenticatedRequest(reqOpts, assert.ifError); + }); + }); + + describe('customEndpoint (authentication attempted)', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let makeAuthenticatedRequest: any; + const config = {customEndpoint: true, useAuthWithCustomEndpoint: true}; + + beforeEach(() => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(config); + }); + + it('should authenticate requests with a custom API', done => { + const reqOpts = {a: 'b', c: 'd'}; + + stub('makeRequest', rOpts => { + assert.deepStrictEqual(rOpts, reqOpts); + done(); + }); + + authClient.authorizeRequest = async (opts: {}) => { + assert.strictEqual(opts, reqOpts); + done(); + }; + + makeAuthenticatedRequest(reqOpts, assert.ifError); + }); + }); + + describe('authentication', () => { + it('should pass correct args to authorizeRequest', done => { + const fake = { + ...authClient, + authorizeRequest: async (rOpts: {}) => { + assert.deepStrictEqual(rOpts, fakeReqOpts); + setImmediate(done); + return rOpts; + }, + }; + retryRequestOverride = () => { + return new stream.PassThrough(); + }; + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(fake); + const mar = util.makeAuthenticatedRequestFactory({}); + mar(fakeReqOpts); + }); + + it('should return a stream if callback is missing', () => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').callsFake(() => { + return { + ...authClient, + authorizeRequest: async (rOpts: {}) => { + return rOpts; + }, + }; + }); + retryRequestOverride = () => { + return new stream.PassThrough(); + }; + const mar = util.makeAuthenticatedRequestFactory({}); + const s = mar(fakeReqOpts); + assert(s instanceof stream.Stream); + }); + + describe('projectId', () => { + const reqOpts = {} as DecorateRequestOptions; + + it('should default to authClient projectId', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + stub('decorateRequest', (reqOpts, projectId) => { + assert.strictEqual(projectId, AUTH_CLIENT_PROJECT_ID); + setImmediate(done); + }); + + const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( + {customEndpoint: true} + ); + + makeAuthenticatedRequest(reqOpts, { + onAuthenticated: assert.ifError, + }); + }); + + it('should prefer user-provided projectId', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + + const config = { + customEndpoint: true, + projectId: 'user-provided-project-id', + }; + + stub('decorateRequest', (reqOpts, projectId) => { + assert.strictEqual(projectId, config.projectId); + setImmediate(done); + }); + + const makeAuthenticatedRequest = + util.makeAuthenticatedRequestFactory(config); + + makeAuthenticatedRequest(reqOpts, { + onAuthenticated: assert.ifError, + }); + }); + + it('should use default `projectId` and not call `authClient#getProjectId` when !`projectIdRequired`', done => { + const getProjectIdSpy = sandbox.spy(authClient, 'getProjectId'); + + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + + const config = { + customEndpoint: true, + projectIdRequired: false, + }; + + stub('decorateRequest', (reqOpts, projectId) => { + assert.strictEqual(projectId, DEFAULT_PROJECT_ID_TOKEN); + }); + + const makeAuthenticatedRequest = + util.makeAuthenticatedRequestFactory(config); + + makeAuthenticatedRequest(reqOpts, { + onAuthenticated: e => { + assert.ifError(e); + assert(getProjectIdSpy.notCalled); + done(e); + }, + }); + }); + + it('should fallback to checking for a `projectId` on when missing a `projectId` when !`projectIdRequired`', done => { + const getProjectIdSpy = sandbox.spy(authClient, 'getProjectId'); + + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + + const config = { + customEndpoint: true, + projectIdRequired: false, + }; + + const decorateRequestStub = sandbox.stub(util, 'decorateRequest'); + + decorateRequestStub.onFirstCall().callsFake(() => { + throw new MissingProjectIdError(); + }); + + decorateRequestStub.onSecondCall().callsFake((reqOpts, projectId) => { + assert.strictEqual(projectId, AUTH_CLIENT_PROJECT_ID); + return reqOpts; + }); + + const makeAuthenticatedRequest = + util.makeAuthenticatedRequestFactory(config); + + makeAuthenticatedRequest(reqOpts, { + onAuthenticated: e => { + assert.ifError(e); + assert(getProjectIdSpy.calledOnce); + done(e); + }, + }); + }); + }); + + describe('authentication errors', () => { + const error = new Error('🤮'); + + beforeEach(() => { + authClient.authorizeRequest = async () => { + throw error; + }; + }); + + it('should attempt request anyway', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( + {} + ); + + const correctReqOpts = {} as DecorateRequestOptions; + const incorrectReqOpts = {} as DecorateRequestOptions; + + authClient.authorizeRequest = async () => { + throw new Error('Could not load the default credentials'); + }; + + makeAuthenticatedRequest(correctReqOpts, { + onAuthenticated(err, reqOpts) { + assert.ifError(err); + assert.strictEqual(reqOpts, correctReqOpts); + assert.notStrictEqual(reqOpts, incorrectReqOpts); + done(); + }, + }); + }); + + it('should block 401 API errors', done => { + const authClientError = new Error( + 'Could not load the default credentials' + ); + authClient.authorizeRequest = async () => { + throw authClientError; + }; + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + + const makeRequestArg1 = new Error('API 401 Error.') as ApiError; + makeRequestArg1.code = 401; + const makeRequestArg2 = {}; + const makeRequestArg3 = {}; + stub('makeRequest', (authenticatedReqOpts, cfg, callback) => { + callback(makeRequestArg1, makeRequestArg2, makeRequestArg3); + }); + + const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( + {} + ); + makeAuthenticatedRequest( + {} as DecorateRequestOptions, + (arg1, arg2, arg3) => { + assert.strictEqual(arg1, authClientError); + assert.strictEqual(arg2, makeRequestArg2); + assert.strictEqual(arg3, makeRequestArg3); + done(); + } + ); + }); + + it('should not block 401 errors if auth client succeeds', done => { + authClient.authorizeRequest = async () => { + return {}; + }; + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + + const makeRequestArg1 = new Error('API 401 Error.') as ApiError; + makeRequestArg1.code = 401; + const makeRequestArg2 = {}; + const makeRequestArg3 = {}; + stub('makeRequest', (authenticatedReqOpts, cfg, callback) => { + callback(makeRequestArg1, makeRequestArg2, makeRequestArg3); + }); + + const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( + {} + ); + makeAuthenticatedRequest( + {} as DecorateRequestOptions, + (arg1, arg2, arg3) => { + assert.strictEqual(arg1, makeRequestArg1); + assert.strictEqual(arg2, makeRequestArg2); + assert.strictEqual(arg3, makeRequestArg3); + done(); + } + ); + }); + + it('should block decorateRequest error', done => { + const decorateRequestError = new Error('Error.'); + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + stub('decorateRequest', () => { + throw decorateRequestError; + }); + + const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory( + {} + ); + makeAuthenticatedRequest(fakeReqOpts, { + onAuthenticated(err) { + assert.notStrictEqual(err, decorateRequestError); + assert.strictEqual(err, error); + done(); + }, + }); + }); + + it('should invoke the callback with error', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + const mar = util.makeAuthenticatedRequestFactory({}); + mar(fakeReqOpts, err => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('should exec onAuthenticated callback with error', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + const mar = util.makeAuthenticatedRequestFactory({}); + mar(fakeReqOpts, { + onAuthenticated(err) { + assert.strictEqual(err, error); + done(); + }, + }); + }); + + it('should emit an error and end the stream', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + const mar = util.makeAuthenticatedRequestFactory({}); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const stream = mar(fakeReqOpts) as any; + stream.on('error', (err: Error) => { + assert.strictEqual(err, error); + setImmediate(() => { + assert.strictEqual(stream.destroyed, true); + done(); + }); + }); + }); + }); + + describe('authentication success', () => { + const reqOpts = fakeReqOpts; + beforeEach(() => { + authClient.authorizeRequest = async () => reqOpts; + }); + + it('should return authenticated request to callback', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + stub('decorateRequest', reqOpts_ => { + assert.deepStrictEqual(reqOpts_, reqOpts); + return reqOpts; + }); + + const mar = util.makeAuthenticatedRequestFactory({}); + mar(reqOpts, { + onAuthenticated(err, authenticatedReqOpts) { + assert.strictEqual(authenticatedReqOpts, reqOpts); + done(); + }, + }); + }); + + it('should make request with correct options', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + const config = {keyFile: 'foo'}; + stub('decorateRequest', reqOpts_ => { + assert.deepStrictEqual(reqOpts_, reqOpts); + return reqOpts; + }); + stub('makeRequest', (authenticatedReqOpts, cfg, cb) => { + assert.deepStrictEqual(authenticatedReqOpts, reqOpts); + assert.deepStrictEqual(cfg, config); + cb(); + }); + const mar = util.makeAuthenticatedRequestFactory(config); + mar(reqOpts, done); + }); + + it('should return abort() from the active request', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + const retryRequest = { + abort: done, + }; + sandbox.stub(util, 'makeRequest').returns(retryRequest); + const mar = util.makeAuthenticatedRequestFactory({}); + const req = mar(reqOpts, assert.ifError) as Abortable; + req.abort(); + }); + + it('should only abort() once', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + const retryRequest = { + abort: done, // Will throw if called more than once. + }; + stub('makeRequest', () => { + return retryRequest; + }); + + const mar = util.makeAuthenticatedRequestFactory({}); + const authenticatedRequest = mar( + reqOpts, + assert.ifError + ) as Abortable; + + authenticatedRequest.abort(); // done() + authenticatedRequest.abort(); // done() + }); + + it('should provide stream to makeRequest', done => { + sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient); + stub('makeRequest', (authenticatedReqOpts, cfg) => { + setImmediate(() => { + assert.strictEqual(cfg.stream, stream); + done(); + }); + }); + const mar = util.makeAuthenticatedRequestFactory({}); + const stream = mar(reqOpts); + }); + }); + }); + }); + + describe('shouldRetryRequest', () => { + it('should return false if there is no error', () => { + assert.strictEqual(util.shouldRetryRequest(), false); + }); + + it('should return false from generic error', () => { + const error = new ApiError('Generic error with no code'); + assert.strictEqual(util.shouldRetryRequest(error), false); + }); + + it('should return true with error code 408', () => { + const error = new ApiError('408'); + error.code = 408; + assert.strictEqual(util.shouldRetryRequest(error), true); + }); + + it('should return true with error code 429', () => { + const error = new ApiError('429'); + error.code = 429; + assert.strictEqual(util.shouldRetryRequest(error), true); + }); + + it('should return true with error code 500', () => { + const error = new ApiError('500'); + error.code = 500; + assert.strictEqual(util.shouldRetryRequest(error), true); + }); + + it('should return true with error code 502', () => { + const error = new ApiError('502'); + error.code = 502; + assert.strictEqual(util.shouldRetryRequest(error), true); + }); + + it('should return true with error code 503', () => { + const error = new ApiError('503'); + error.code = 503; + assert.strictEqual(util.shouldRetryRequest(error), true); + }); + + it('should return true with error code 504', () => { + const error = new ApiError('504'); + error.code = 504; + assert.strictEqual(util.shouldRetryRequest(error), true); + }); + + it('should detect rateLimitExceeded reason', () => { + const rateLimitError = new ApiError('Rate limit error without code.'); + rateLimitError.errors = [{reason: 'rateLimitExceeded'}]; + assert.strictEqual(util.shouldRetryRequest(rateLimitError), true); + }); + + it('should detect userRateLimitExceeded reason', () => { + const rateLimitError = new ApiError('Rate limit error without code.'); + rateLimitError.errors = [{reason: 'userRateLimitExceeded'}]; + assert.strictEqual(util.shouldRetryRequest(rateLimitError), true); + }); + + it('should retry on EAI_AGAIN error code', () => { + const eaiAgainError = new ApiError('EAI_AGAIN'); + eaiAgainError.errors = [ + {reason: 'getaddrinfo EAI_AGAIN pubsub.googleapis.com'}, + ]; + assert.strictEqual(util.shouldRetryRequest(eaiAgainError), true); + }); + }); + + describe('makeRequest', () => { + const reqOpts = { + method: 'GET', + } as DecorateRequestOptions; + + function testDefaultRetryRequestConfig(done: () => void) { + return (reqOpts_: DecorateRequestOptions, config: MakeRequestConfig) => { + assert.strictEqual(reqOpts_, reqOpts); + assert.strictEqual(config.retries, 3); + + const error = new Error('Error.'); + stub('parseHttpRespMessage', () => { + return {err: error}; + }); + stub('shouldRetryRequest', err => { + assert.strictEqual(err, error); + done(); + }); + + config.shouldRetryFn!(); + }; + } + const errorMessage = 'Error.'; + const customRetryRequestFunctionConfig = { + retryOptions: { + retryableErrorFn: function (err: ApiError) { + return err.message === errorMessage; + }, + }, + }; + function testCustomFunctionRetryRequestConfig(done: () => void) { + return (reqOpts_: DecorateRequestOptions, config: MakeRequestConfig) => { + assert.strictEqual(reqOpts_, reqOpts); + assert.strictEqual(config.retries, 3); + + const error = new Error(errorMessage); + stub('parseHttpRespMessage', () => { + return {err: error}; + }); + stub('shouldRetryRequest', err => { + assert.strictEqual(err, error); + done(); + }); + + assert.strictEqual(config.shouldRetryFn!(), true); + done(); + }; + } + + const noRetryRequestConfig = {autoRetry: false}; + function testNoRetryRequestConfig(done: () => void) { + return ( + reqOpts: DecorateRequestOptions, + config: retryRequest.Options + ) => { + assert.strictEqual(config.retries, 0); + done(); + }; + } + + const retryOptionsConfig = { + retryOptions: { + autoRetry: false, + maxRetries: 7, + retryDelayMultiplier: 3, + totalTimeout: 60, + maxRetryDelay: 640, + }, + }; + function testRetryOptions(done: () => void) { + return ( + reqOpts: DecorateRequestOptions, + config: retryRequest.Options + ) => { + assert.strictEqual( + config.retries, + 0 //autoRetry was set to false, so shouldn't retry + ); + assert.strictEqual( + config.noResponseRetries, + 0 //autoRetry was set to false, so shouldn't retry + ); + assert.strictEqual( + config.retryDelayMultiplier, + retryOptionsConfig.retryOptions.retryDelayMultiplier + ); + assert.strictEqual( + config.totalTimeout, + retryOptionsConfig.retryOptions.totalTimeout + ); + assert.strictEqual( + config.maxRetryDelay, + retryOptionsConfig.retryOptions.maxRetryDelay + ); + done(); + }; + } + + const customRetryRequestConfig = {maxRetries: 10}; + function testCustomRetryRequestConfig(done: () => void) { + return (reqOpts: DecorateRequestOptions, config: MakeRequestConfig) => { + assert.strictEqual(config.retries, customRetryRequestConfig.maxRetries); + done(); + }; + } + + describe('stream mode', () => { + it('should forward the specified events to the stream', done => { + const requestStream = duplexify(); + const userStream = duplexify(); + + const error = new Error('Error.'); + const response = {}; + const complete = {}; + + userStream + .on('error', error_ => { + assert.strictEqual(error_, error); + requestStream.emit('response', response); + }) + .on('response', response_ => { + assert.strictEqual(response_, response); + requestStream.emit('complete', complete); + }) + .on('complete', complete_ => { + assert.strictEqual(complete_, complete); + done(); + }); + + retryRequestOverride = () => { + setImmediate(() => { + requestStream.emit('error', error); + }); + + return requestStream; + }; + + util.makeRequest(reqOpts, {stream: userStream}, util.noop); + }); + + describe('GET requests', () => { + it('should use retryRequest', done => { + const userStream = duplexify(); + retryRequestOverride = (reqOpts_: DecorateRequestOptions) => { + assert.strictEqual(reqOpts_, reqOpts); + setImmediate(done); + return new stream.Stream(); + }; + util.makeRequest(reqOpts, {stream: userStream}, util.noop); + }); + + it('should set the readable stream', done => { + const userStream = duplexify(); + const retryRequestStream = new stream.Stream(); + retryRequestOverride = () => { + return retryRequestStream; + }; + userStream.setReadable = stream => { + assert.strictEqual(stream, retryRequestStream); + done(); + }; + util.makeRequest(reqOpts, {stream: userStream}, util.noop); + }); + + it('should expose the abort method from retryRequest', done => { + const userStream = duplexify() as Duplexify & Abortable; + + retryRequestOverride = () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const requestStream: any = new stream.Stream(); + requestStream.abort = done; + return requestStream; + }; + + util.makeRequest(reqOpts, {stream: userStream}, util.noop); + userStream.abort(); + }); + }); + + describe('non-GET requests', () => { + it('should not use retryRequest', done => { + const userStream = duplexify(); + const reqOpts = { + method: 'POST', + } as DecorateRequestOptions; + + retryRequestOverride = done; // will throw. + requestOverride = (reqOpts_: DecorateRequestOptions) => { + assert.strictEqual(reqOpts_, reqOpts); + setImmediate(done); + return userStream; + }; + requestOverride.defaults = () => requestOverride; + util.makeRequest(reqOpts, {stream: userStream}, util.noop); + }); + + it('should set the writable stream', done => { + const userStream = duplexify(); + const requestStream = new stream.Stream(); + requestOverride = () => requestStream; + requestOverride.defaults = () => requestOverride; + userStream.setWritable = stream => { + assert.strictEqual(stream, requestStream); + done(); + }; + util.makeRequest( + {method: 'POST'} as DecorateRequestOptions, + {stream: userStream}, + util.noop + ); + }); + + it('should expose the abort method from request', done => { + const userStream = duplexify() as Duplexify & Abortable; + + requestOverride = Object.assign( + () => { + const requestStream = duplexify() as Duplexify & Abortable; + requestStream.abort = done; + return requestStream; + }, + {defaults: () => requestOverride} + ); + + util.makeRequest(reqOpts, {stream: userStream}, util.noop); + userStream.abort(); + }); + }); + }); + + describe('callback mode', () => { + it('should pass the default options to retryRequest', done => { + retryRequestOverride = testDefaultRetryRequestConfig(done); + util.makeRequest( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + reqOpts, + {}, + assert.ifError + ); + }); + + it('should allow setting a custom retry function', done => { + retryRequestOverride = testCustomFunctionRetryRequestConfig(done); + util.makeRequest( + reqOpts, + customRetryRequestFunctionConfig, + assert.ifError + ); + }); + + it('should allow turning off retries to retryRequest', done => { + retryRequestOverride = testNoRetryRequestConfig(done); + util.makeRequest(reqOpts, noRetryRequestConfig, assert.ifError); + }); + + it('should override number of retries to retryRequest', done => { + retryRequestOverride = testCustomRetryRequestConfig(done); + util.makeRequest(reqOpts, customRetryRequestConfig, assert.ifError); + }); + + it('should use retryOptions if provided', done => { + retryRequestOverride = testRetryOptions(done); + util.makeRequest(reqOpts, retryOptionsConfig, assert.ifError); + }); + + it('should allow request options to control retry setting', done => { + retryRequestOverride = testCustomRetryRequestConfig(done); + const reqOptsWithRetrySettings = { + ...reqOpts, + ...customRetryRequestConfig, + }; + util.makeRequest( + reqOptsWithRetrySettings, + noRetryRequestConfig, + assert.ifError + ); + }); + + it('should return the instance of retryRequest', () => { + const requestInstance = {}; + retryRequestOverride = () => { + return requestInstance; + }; + const res = util.makeRequest(reqOpts, {}, assert.ifError); + assert.strictEqual(res, requestInstance); + }); + + it('should let handleResp handle the response', done => { + const error = new Error('Error.'); + const body = fakeResponse.body; + + retryRequestOverride = ( + rOpts: DecorateRequestOptions, + opts: MakeRequestConfig, + callback: r.RequestCallback + ) => { + callback(error, fakeResponse, body); + }; + + stub('handleResp', (err, resp, body_) => { + assert.strictEqual(err, error); + assert.strictEqual(resp, fakeResponse); + assert.strictEqual(body_, body); + done(); + }); + + util.makeRequest(fakeReqOpts, {}, assert.ifError); + }); + }); + }); + + describe('decorateRequest', () => { + const projectId = 'not-a-project-id'; + it('should delete qs.autoPaginate', () => { + const decoratedReqOpts = util.decorateRequest( + { + autoPaginate: true, + } as DecorateRequestOptions, + projectId + ); + + assert.strictEqual(decoratedReqOpts.autoPaginate, undefined); + }); + + it('should delete qs.autoPaginateVal', () => { + const decoratedReqOpts = util.decorateRequest( + { + autoPaginateVal: true, + } as DecorateRequestOptions, + projectId + ); + + assert.strictEqual(decoratedReqOpts.autoPaginateVal, undefined); + }); + + it('should delete objectMode', () => { + const decoratedReqOpts = util.decorateRequest( + { + objectMode: true, + } as DecorateRequestOptions, + projectId + ); + + assert.strictEqual(decoratedReqOpts.objectMode, undefined); + }); + + it('should delete qs.autoPaginate', () => { + const decoratedReqOpts = util.decorateRequest( + { + qs: { + autoPaginate: true, + }, + } as DecorateRequestOptions, + projectId + ); + + assert.strictEqual(decoratedReqOpts.qs.autoPaginate, undefined); + }); + + it('should delete qs.autoPaginateVal', () => { + const decoratedReqOpts = util.decorateRequest( + { + qs: { + autoPaginateVal: true, + }, + } as DecorateRequestOptions, + projectId + ); + + assert.strictEqual(decoratedReqOpts.qs.autoPaginateVal, undefined); + }); + + it('should delete json.autoPaginate', () => { + const decoratedReqOpts = util.decorateRequest( + { + json: { + autoPaginate: true, + }, + } as DecorateRequestOptions, + projectId + ); + + assert.strictEqual(decoratedReqOpts.json.autoPaginate, undefined); + }); + + it('should delete json.autoPaginateVal', () => { + const decoratedReqOpts = util.decorateRequest( + { + json: { + autoPaginateVal: true, + }, + } as DecorateRequestOptions, + projectId + ); + + assert.strictEqual(decoratedReqOpts.json.autoPaginateVal, undefined); + }); + + it('should replace project ID tokens for qs object', () => { + const projectId = 'project-id'; + const reqOpts = { + uri: 'http://', + qs: {}, + }; + const decoratedQs = {}; + + replaceProjectIdTokenOverride = (qs: {}, projectId_: string) => { + if (qs === reqOpts.uri) { + return; + } + assert.deepStrictEqual(qs, reqOpts.qs); + assert.strictEqual(projectId_, projectId); + return decoratedQs; + }; + + const decoratedRequest = util.decorateRequest(reqOpts, projectId); + assert.deepStrictEqual(decoratedRequest.qs, decoratedQs); + }); + + it('should replace project ID tokens for multipart array', () => { + const projectId = 'project-id'; + const reqOpts = { + uri: 'http://', + multipart: [ + { + 'Content-Type': '...', + body: '...', + }, + ], + }; + const decoratedPart = {}; + + replaceProjectIdTokenOverride = (part: {}, projectId_: string) => { + if (part === reqOpts.uri) { + return; + } + assert.deepStrictEqual(part, reqOpts.multipart[0]); + assert.strictEqual(projectId_, projectId); + return decoratedPart; + }; + + const decoratedRequest = util.decorateRequest(reqOpts, projectId); + assert.deepStrictEqual(decoratedRequest.multipart, [decoratedPart]); + }); + + it('should replace project ID tokens for json object', () => { + const projectId = 'project-id'; + const reqOpts = { + uri: 'http://', + json: {}, + }; + const decoratedJson = {}; + + replaceProjectIdTokenOverride = (json: {}, projectId_: string) => { + if (json === reqOpts.uri) { + return; + } + assert.strictEqual(reqOpts.json, json); + assert.strictEqual(projectId_, projectId); + return decoratedJson; + }; + + const decoratedRequest = util.decorateRequest(reqOpts, projectId); + assert.deepStrictEqual(decoratedRequest.json, decoratedJson); + }); + + it('should decorate the request', () => { + const projectId = 'project-id'; + const reqOpts = { + uri: 'http://', + }; + const decoratedUri = 'http://decorated'; + + replaceProjectIdTokenOverride = (uri: string, projectId_: string) => { + assert.strictEqual(uri, reqOpts.uri); + assert.strictEqual(projectId_, projectId); + return decoratedUri; + }; + + assert.deepStrictEqual(util.decorateRequest(reqOpts, projectId), { + uri: decoratedUri, + }); + }); + }); + + describe('isCustomType', () => { + class PubSub {} + + class MiddleLayer { + parent = new PubSub(); + } + + class Subscription { + parent = new MiddleLayer(); + } + + const pubsub = new PubSub(); + const subscription = new Subscription(); + + describe('Service objects', () => { + it('should match by constructor name', () => { + assert(util.isCustomType(pubsub, 'pubsub')); + }); + + it('should support any casing', () => { + assert(util.isCustomType(pubsub, 'PubSub')); + }); + + it('should not match if the wrong Service', () => { + assert(!util.isCustomType(subscription, 'BigQuery')); + }); + }); + + describe('ServiceObject objects', () => { + it('should match by constructor names', () => { + assert(util.isCustomType(subscription, 'pubsub')); + assert(util.isCustomType(subscription, 'pubsub/subscription')); + + assert(util.isCustomType(subscription, 'middlelayer')); + assert(util.isCustomType(subscription, 'middlelayer/subscription')); + }); + + it('should support any casing', () => { + assert(util.isCustomType(subscription, 'PubSub/Subscription')); + }); + + it('should not match if the wrong ServiceObject', () => { + assert(!util.isCustomType(subscription, 'pubsub/topic')); + }); + }); + }); + + describe('maybeOptionsOrCallback', () => { + it('should allow passing just a callback', () => { + const optionsOrCallback = () => {}; + const [opts, cb] = util.maybeOptionsOrCallback(optionsOrCallback); + assert.strictEqual(optionsOrCallback, cb); + assert.deepStrictEqual(opts, {}); + }); + + it('should allow passing both opts and callback', () => { + const optionsOrCallback = {}; + const callback = () => {}; + const [opts, cb] = util.maybeOptionsOrCallback( + optionsOrCallback, + callback + ); + assert.strictEqual(opts, optionsOrCallback); + assert.strictEqual(cb, callback); + }); + }); +}); diff --git a/handwritten/storage/test/notification.ts b/handwritten/storage/test/notification.ts new file mode 100644 index 00000000000..fe396dcb512 --- /dev/null +++ b/handwritten/storage/test/notification.ts @@ -0,0 +1,377 @@ +// Copyright 2019 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 { + BaseMetadata, + DecorateRequestOptions, + ServiceObject, + ServiceObjectConfig, + util, +} from '../src/nodejs-common/index.js'; +import assert from 'assert'; +import {describe, it, before, beforeEach} from 'mocha'; +import proxyquire from 'proxyquire'; + +import {Bucket} from '../src/index.js'; + +class FakeServiceObject extends ServiceObject { + calledWith_: IArguments; + constructor(config: ServiceObjectConfig) { + super(config); + // eslint-disable-next-line prefer-rest-params + this.calledWith_ = arguments; + } +} + +describe('Notification', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let Notification: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let notification: any; + let promisified = false; + const fakeUtil = Object.assign({}, util); + const fakePromisify = { + // tslint:disable-next-line:variable-name + promisifyAll(Class: Function) { + if (Class.name === 'Notification') { + promisified = true; + } + }, + }; + + const BUCKET = { + createNotification: fakeUtil.noop, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + request(_reqOpts: DecorateRequestOptions, _callback: Function) { + return fakeUtil.noop(); + }, + }; + + const ID = '123'; + + before(() => { + Notification = proxyquire('../src/notification.js', { + '@google-cloud/promisify': fakePromisify, + './nodejs-common': { + ServiceObject: FakeServiceObject, + util: fakeUtil, + }, + }).Notification; + }); + + beforeEach(() => { + BUCKET.createNotification = fakeUtil.noop = () => {}; + BUCKET.request = fakeUtil.noop = () => {}; + notification = new Notification(BUCKET, ID); + }); + + describe('instantiation', () => { + it('should promisify all the things', () => { + assert(promisified); + }); + + it('should inherit from ServiceObject', () => { + assert(notification instanceof FakeServiceObject); + + const calledWith = notification.calledWith_[0]; + + assert.strictEqual(calledWith.parent, BUCKET); + assert.strictEqual(calledWith.baseUrl, '/notificationConfigs'); + assert.strictEqual(calledWith.id, ID); + + assert.deepStrictEqual(calledWith.methods, { + create: true, + delete: { + reqOpts: { + qs: {}, + }, + }, + get: { + reqOpts: { + qs: {}, + }, + }, + getMetadata: { + reqOpts: { + qs: {}, + }, + }, + exists: true, + }); + }); + + it('should use Bucket#createNotification for the createMethod', () => { + const bound = () => {}; + + Object.assign(BUCKET.createNotification, { + bind(context: Bucket) { + assert.strictEqual(context, BUCKET); + return bound; + }, + }); + + const notification = new Notification(BUCKET, ID); + const calledWith = notification.calledWith_[0]; + assert.strictEqual(calledWith.createMethod, bound); + }); + + it('should convert number IDs to strings', () => { + const notification = new Notification(BUCKET, 1); + const calledWith = notification.calledWith_[0]; + + assert.strictEqual(calledWith.id, '1'); + }); + }); + + describe('delete', () => { + it('should make the correct request', done => { + const options = {}; + + BUCKET.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.strictEqual(reqOpts.method, 'DELETE'); + assert.strictEqual(reqOpts.uri, 'notificationConfigs/123'); + assert.deepStrictEqual(reqOpts.qs, options); + callback(); // the done fn + }; + + notification.delete(options, done); + }); + + it('should optionally accept options', done => { + BUCKET.request = ( + reqOpts: DecorateRequestOptions, + callback: Function + ) => { + assert.deepStrictEqual(reqOpts.qs, {}); + callback(); // the done fn + }; + + notification.delete(done); + }); + + it('should optionally accept a callback', done => { + BUCKET.request = ( + _reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(); // the done fn + }; + + notification.delete(done); + }); + }); + + describe('get', () => { + it('should get the metadata', done => { + notification.getMetadata = () => { + done(); + }; + + notification.get(assert.ifError); + }); + + it('should accept an options object', done => { + const options = {}; + + notification.getMetadata = (options_: {}) => { + assert.deepStrictEqual(options_, options); + done(); + }; + + notification.get(options, assert.ifError); + }); + + it('should execute callback with error & metadata', done => { + const error = new Error('Error.'); + const metadata = {}; + + notification.getMetadata = (_options: {}, callback: Function) => { + callback(error, metadata); + }; + + notification.get((err: Error, instance: {}, metadata_: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(instance, null); + assert.strictEqual(metadata_, metadata); + + done(); + }); + }); + + it('should execute callback with instance & metadata', done => { + const metadata = {}; + + notification.getMetadata = (_options: {}, callback: Function) => { + callback(null, metadata); + }; + + notification.get((err: Error, instance: {}, metadata_: {}) => { + assert.ifError(err); + + assert.strictEqual(instance, notification); + assert.strictEqual(metadata_, metadata); + + done(); + }); + }); + + describe('autoCreate', () => { + let AUTO_CREATE_CONFIG: {}; + + const ERROR = {code: 404}; + const METADATA = {}; + + beforeEach(() => { + AUTO_CREATE_CONFIG = { + autoCreate: true, + }; + + notification.getMetadata = (_options: {}, callback: Function) => { + callback(ERROR, METADATA); + }; + }); + + it('should pass config to create if it was provided', done => { + const config = Object.assign( + {}, + { + maxResults: 5, + } + ); + + notification.get = (config_: {}) => { + assert.deepStrictEqual(config_, config); + done(); + }; + + notification.get(config); + }); + + it('should pass only a callback to create if no config', done => { + notification.create = (callback: Function) => { + callback(); // done() + }; + + notification.get(AUTO_CREATE_CONFIG, done); + }); + + describe('error', () => { + it('should execute callback with error & API response', done => { + const error = new Error('Error.'); + const apiResponse = {}; + + notification.create = (callback: Function) => { + notification.get = (config: {}, callback: Function) => { + assert.deepStrictEqual(config, {}); + callback(); // done() + }; + + callback(error, null, apiResponse); + }; + + notification.get( + AUTO_CREATE_CONFIG, + (err: Error, instance: {}, resp: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(instance, null); + assert.strictEqual(resp, apiResponse); + done(); + } + ); + }); + + it('should refresh the metadata after a 409', done => { + const error = { + code: 409, + }; + + notification.create = (callback: Function) => { + notification.get = (config: {}, callback: Function) => { + assert.deepStrictEqual(config, {}); + callback(); // done() + }; + + callback(error); + }; + + notification.get(AUTO_CREATE_CONFIG, done); + }); + }); + }); + }); + + describe('getMetadata', () => { + it('should make the correct request', done => { + const options = {}; + + BUCKET.request = (reqOpts: DecorateRequestOptions) => { + assert.strictEqual(reqOpts.uri, 'notificationConfigs/123'); + assert.deepStrictEqual(reqOpts.qs, options); + done(); + }; + + notification.getMetadata(options, assert.ifError); + }); + + it('should optionally accept options', done => { + BUCKET.request = (reqOpts: DecorateRequestOptions) => { + assert.deepStrictEqual(reqOpts.qs, {}); + done(); + }; + + notification.getMetadata(assert.ifError); + }); + + it('should return any errors to the callback', done => { + const error = new Error('err'); + const response = {}; + + BUCKET.request = ( + _reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(error, response, response); + }; + + notification.getMetadata((err: Error, metadata: {}, resp: {}) => { + assert.strictEqual(err, error); + assert.strictEqual(metadata, response); + assert.strictEqual(resp, response); + done(); + }); + }); + + it('should set and return the metadata', done => { + const response = {}; + + BUCKET.request = ( + _reqOpts: DecorateRequestOptions, + callback: Function + ) => { + callback(null, response, response); + }; + + notification.getMetadata((err: Error, metadata: {}, resp: {}) => { + assert.ifError(err); + assert.strictEqual(metadata, response); + assert.strictEqual(notification.metadata, response); + assert.strictEqual(resp, response); + done(); + }); + }); + }); +}); diff --git a/handwritten/storage/test/resumable-upload.ts b/handwritten/storage/test/resumable-upload.ts new file mode 100644 index 00000000000..381044d64d9 --- /dev/null +++ b/handwritten/storage/test/resumable-upload.ts @@ -0,0 +1,3138 @@ +// Copyright 2022 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 assert from 'assert'; +import {describe, it, beforeEach, before, afterEach, after} from 'mocha'; +import * as crypto from 'crypto'; +import * as mockery from 'mockery'; +import nock from 'nock'; +import * as path from 'path'; +import * as sinon from 'sinon'; +import {Readable, Writable} from 'stream'; +import { + RETRY_DELAY_MULTIPLIER_DEFAULT, + TOTAL_TIMEOUT_DEFAULT, + MAX_RETRY_DELAY_DEFAULT, + AUTO_RETRY_DEFAULT, + MAX_RETRY_DEFAULT, + RETRYABLE_ERR_FN_DEFAULT, +} from '../src/storage.js'; + +import { + ApiError, + CreateUriCallback, + PROTOCOL_REGEX, + UploadConfig, +} from '../src/resumable-upload.js'; +import {GaxiosOptions, GaxiosError, GaxiosResponse} from 'gaxios'; +import {GCCL_GCS_CMD_KEY} from '../src/nodejs-common/util.js'; +import {getDirName} from '../src/util.js'; +import {FileExceptionMessages} from '../src/file.js'; + +nock.disableNetConnect(); + +class AbortController { + aborted = false; + signal = this; + abort() { + this.aborted = true; + } +} + +const RESUMABLE_INCOMPLETE_STATUS_CODE = 308; +/** 256 KiB */ +const CHUNK_SIZE_MULTIPLE = 2 ** 18; +const queryPath = '/?userProject=user-project-id'; +const X_GOOG_API_HEADER_REGEX = + /^gl-node\/(?[^W]+) gccl\/(?[^W]+) gccl-invocation-id\/(?[^W]+) gccl-gcs-cmd\/(?[^W]+)$/; +const USER_AGENT_REGEX = /^gcloud-node-storage\/(?[^W]+)$/; +const CORRECT_CLIENT_CRC32C = 'Q2hlY2tzdW0h'; +const INCORRECT_SERVER_CRC32C = 'Q2hlY2tzdVUa'; +const CORRECT_CLIENT_MD5 = 'CorrectMD5Hash'; +const INCORRECT_SERVER_MD5 = 'IncorrectMD5Hash'; + +function mockAuthorizeRequest( + code = 200, + data: {} | string = { + access_token: 'abc123', + } +) { + return nock('https://www.googleapis.com') + .post('/oauth2/v4/token') + .reply(code, data); +} + +describe('resumable-upload', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let upload: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let up: any; + + const BUCKET = 'bucket-name'; + const CUSTOM_REQUEST_OPTIONS = {headers: {'X-My-Header': 'My custom value'}}; + const FILE = 'file-name'; + const GENERATION = Date.now(); + const METADATA = {contentLength: 1024, contentType: 'application/json'}; + const ORIGIN = '*'; + const PARAMS = {ifMetagenerationNotMatch: 3}; + const PREDEFINED_ACL = 'authenticatedRead'; + const USER_PROJECT = 'user-project-id'; + const API_ENDPOINT = 'https://fake.googleapis.com'; + const BASE_URI = `${API_ENDPOINT}/upload/storage/v1/b`; + const RETRY_OPTIONS = { + retryDelayMultiplier: RETRY_DELAY_MULTIPLIER_DEFAULT, + totalTimeout: TOTAL_TIMEOUT_DEFAULT, + maxRetryDelay: MAX_RETRY_DELAY_DEFAULT, + autoRetry: AUTO_RETRY_DEFAULT, + maxRetries: MAX_RETRY_DEFAULT, + retryableErrorFn: RETRYABLE_ERR_FN_DEFAULT, + }; + let REQ_OPTS: GaxiosOptions; + const keyFile = path.join(getDirName(), '../../../test/fixtures/keys.json'); + + before(() => { + mockery.registerMock('abort-controller', AbortController); + mockery.enable({useCleanCache: true, warnOnUnregistered: false}); + upload = require('../src/resumable-upload').upload; + }); + + beforeEach(() => { + REQ_OPTS = {url: 'http://fake.local'}; + up = upload({ + bucket: BUCKET, + file: FILE, + customRequestOptions: CUSTOM_REQUEST_OPTIONS, + generation: GENERATION, + metadata: METADATA, + origin: ORIGIN, + params: PARAMS, + predefinedAcl: PREDEFINED_ACL, + userProject: USER_PROJECT, + authConfig: {keyFile}, + apiEndpoint: API_ENDPOINT, + retryOptions: {...RETRY_OPTIONS}, + [GCCL_GCS_CMD_KEY]: 'sample.command', + clientCrc32c: CORRECT_CLIENT_CRC32C, + clientMd5Hash: CORRECT_CLIENT_MD5, + }); + }); + + afterEach(() => { + nock.cleanAll(); + }); + + after(() => { + mockery.deregisterAll(); + mockery.disable(); + }); + + describe('ctor', () => { + it('should be a Writable', () => { + assert(up instanceof Writable); + }); + + it('should throw if a bucket or file is not given', () => { + assert.throws(() => { + upload(); + }, /A bucket and file name are required/); + }); + + it('should localize the bucket', () => { + assert.strictEqual(up.bucket, BUCKET); + }); + + it('should localize the cacheKey', () => { + assert.strictEqual(up.cacheKey, [BUCKET, FILE, GENERATION].join('/')); + }); + + it('should localize customRequestOptions', () => { + assert.strictEqual(up.customRequestOptions, CUSTOM_REQUEST_OPTIONS); + }); + + it('should default customRequestOptions to empty object', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + }); + assert.deepStrictEqual(up.customRequestOptions, {}); + }); + + it('should include ZERO generation value in the cacheKey', () => { + const upWithZeroGeneration = upload({ + bucket: BUCKET, + file: FILE, + generation: 0, + metadata: METADATA, + origin: ORIGIN, + predefinedAcl: PREDEFINED_ACL, + userProject: USER_PROJECT, + authConfig: {keyFile}, + apiEndpoint: API_ENDPOINT, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual( + upWithZeroGeneration.cacheKey, + [BUCKET, FILE, 0].join('/') + ); + }); + + it('should not include a generation in the cacheKey if it was not set', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + }); + + assert.strictEqual(up.cacheKey, [BUCKET, FILE].join('/')); + }); + + it('should localize the file', () => { + assert.strictEqual(up.file, FILE); + }); + + it('should localize the generation', () => { + assert.strictEqual(up.generation, GENERATION); + }); + + it('should localize the apiEndpoint', () => { + assert.strictEqual(up.apiEndpoint, API_ENDPOINT); + assert.strictEqual(up.baseURI, BASE_URI); + }); + + it('should prepend https:// to apiEndpoint if not present', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + apiEndpoint: 'fake.googleapis.com', + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(up.apiEndpoint, API_ENDPOINT); + assert.strictEqual(up.baseURI, BASE_URI); + }); + + it('should localize the KMS key name', () => { + const kmsKeyName = 'kms-key-name'; + const up = upload({ + bucket: 'BUCKET', + file: FILE, + kmsKeyName, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(up.kmsKeyName, kmsKeyName); + }); + + it('should localize metadata or default to empty object', () => { + assert.strictEqual(up.metadata, METADATA); + + const upWithoutMetadata = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + }); + assert.deepStrictEqual(upWithoutMetadata.metadata, {}); + }); + + it('should set the offset if it is provided', () => { + const offset = 10; + const up = upload({ + bucket: BUCKET, + file: FILE, + offset, + uri: 'https://example.com', + retryOptions: RETRY_OPTIONS, + }); + + assert.strictEqual(up.offset, offset); + }); + + it('should localize the origin', () => { + assert.strictEqual(up.origin, ORIGIN); + }); + + it('should localize the params', () => { + assert.strictEqual(up.params, PARAMS); + }); + + it('should localize userProject', () => { + assert.strictEqual(up.userProject, USER_PROJECT); + }); + + it('should localize an encryption object from a key', () => { + const key = crypto.randomBytes(32); + const up = upload({ + bucket: BUCKET, + file: FILE, + key, + retryOptions: RETRY_OPTIONS, + }); + const expectedKey = key.toString('base64'); + const expectedHash = crypto + .createHash('sha256') + .update(key) + .digest('base64'); + assert.deepStrictEqual(up.encryption, { + key: expectedKey, + hash: expectedHash, + }); + }); + + it('should localize the predefinedAcl', () => { + assert.strictEqual(up.predefinedAcl, PREDEFINED_ACL); + }); + + it('should set the predefinedAcl with public: true', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + public: true, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(up.predefinedAcl, 'publicRead'); + }); + + it('should set the predefinedAcl with private: true', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + private: true, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(up.predefinedAcl, 'private'); + }); + + it('should set numBytesWritten to 0', () => { + assert.strictEqual(up.numBytesWritten, 0); + }); + + it('should set numRetries to 0', () => { + assert.strictEqual(up.numRetries, 0); + }); + + it('should set the contentLength if provided', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + metadata: {contentLength: METADATA.contentLength}, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(up.contentLength, METADATA.contentLength); + }); + + it('should default the contentLength to *', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(up.contentLength, '*'); + }); + + it('should localize the uri', () => { + const uri = 'http://www.blah.com/'; + const upWithUri = upload({ + bucket: BUCKET, + file: FILE, + uri, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(upWithUri.uriProvidedManually, true); + assert.strictEqual(upWithUri.uri, uri); + }); + + it('should not have `chunkSize` by default', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(up.chunkSize, undefined); + }); + + it('should accept and set `chunkSize`', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + chunkSize: 123, + retryOptions: RETRY_OPTIONS, + }); + assert.strictEqual(up.chunkSize, 123); + }); + + it('should have a default `writableHighWaterMark`', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + }); + + assert(up.writableHighWaterMark); + }); + + it('should accept a `highWaterMark` and set a `writableHighWaterMark`', () => { + const up = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + highWaterMark: 123, + }); + assert.strictEqual(up.writableHighWaterMark, 123); + }); + + describe('on write', () => { + let uri = ''; + + beforeEach(() => { + uri = 'uri'; + }); + + it("should emit 'writing' when piped", done => { + let read = false; + const upstreamBuffer = new Readable({ + read() { + if (!read) { + this.push(Buffer.alloc(1)); + read = true; + } + }, + }); + + up.createURI = () => {}; + up.once('writing', () => { + upstreamBuffer.push(null); + done(); + }); + upstreamBuffer.pipe(up); + }); + + it("should set `upstreamEnded` to `true` and emit 'upstreamFinished' on `#end()`", done => { + const upstreamBuffer = new Readable({ + read() { + this.push(Buffer.alloc(1)); + this.push(null); + }, + }); + + up.createURI = () => {}; + up.once('writing', () => { + up.on('upstreamFinished', () => { + assert.equal(up.upstreamEnded, true); + done(); + }); + + assert.equal(up.upstreamEnded, false); + + up.once('wroteToChunkBuffer', () => up.emit('readFromChunkBuffer')); + }); + upstreamBuffer.pipe(up); + }); + + it('should continue uploading', done => { + up.uri = uri; + up.continueUploading = done; + up.emit('writing'); + }); + + it('should create an upload', done => { + up.startUploading = done; + up.createURI = (callback: CreateUriCallback) => { + callback(null); + }; + up.emit('writing'); + }); + + it('should destroy the stream from an error', done => { + const error: ApiError = { + message: ':(', + name: ':(', + code: 123, + }; + up.destroy = (err: ApiError) => { + assert(err.message.indexOf(error.message) > -1); + assert(err.name.indexOf(error.name) > -1); + assert.strictEqual(err.code, 123); + done(); + }; + up.createURI = (callback: CreateUriCallback) => { + callback(error); + }; + up.emit('writing'); + }); + }); + }); + + describe('upstream', () => { + beforeEach(() => { + up.createURI = () => {}; + }); + + it('should handle writes to class', done => { + up.on('wroteToChunkBuffer', () => { + assert.equal(up.writeBuffers[0].byteLength, 16); + done(); + }); + + up.write(Buffer.alloc(16)); + }); + + it("should setup a 'uploadFinished' handler on 'upstreamFinished'", done => { + assert.equal(up.eventNames().includes('uploadFinished'), false); + + up.on('upstreamFinished', () => { + assert.equal(up.eventNames().includes('uploadFinished'), true); + done(); + }); + + up.end(); + }); + + it("should finish only after 'uploadFinished' is emitted", done => { + const upstreamBuffer = new Readable({ + read() { + this.push(Buffer.alloc(1)); + this.push(null); + }, + }); + + // Readable has ended + upstreamBuffer.on('end', () => { + // The data has been written to the buffer + up.on('wroteToChunkBuffer', () => { + // Allow the writer's callback be called immediately + up.emit('readFromChunkBuffer'); + + // setting up the listener now to prove it hasn't been fired before + up.on('finish', done); + process.nextTick(() => up.emit('uploadFinished')); + }); + }); + + upstreamBuffer.pipe(up); + }); + }); + + describe('#_write', () => { + beforeEach(() => { + up.createURI = () => {}; + }); + + it('should append buffer to existing `writeBuffers`', () => { + up.writeBuffers = [Buffer.from('abc')]; + up.write(Buffer.from('def')); + + assert.equal( + Buffer.compare(Buffer.concat(up.writeBuffers), Buffer.from('abcdef')), + 0 + ); + }); + + it('should convert string with encoding to Buffer and append to existing `writeBuffers`', () => { + const existing = 'a '; + const sample = '🦃'; + const concat = existing + sample; + + up.writeBuffers = [Buffer.from(existing)]; + + up.write(sample, 'utf-8', () => {}); + + for (const buf of up.writeBuffers) { + assert(Buffer.isBuffer(buf)); + } + assert.equal(Buffer.concat(up.writeBuffers), concat); + }); + + it("should callback on 'readFromChunkBuffer'", done => { + // The 'done' here is a callback from 'readFromChunkBuffer' + up.write('sample', 'utf-8', done); + up.emit('readFromChunkBuffer'); + }); + + it("should emit 'wroteToChunkBuffer' asynchronously", done => { + up.write('sample', 'utf-8', () => {}); + + // setting this here proves it's async + up.on('wroteToChunkBuffer', done); + }); + }); + + describe('#prependLocalBufferToUpstream', () => { + it('should synchronously prepend to existing buffer', () => { + up.localWriteCache = [Buffer.from('123')]; + up.localWriteCacheByteLength = up.localWriteCache[0].byteLength; + up.writeBuffers = [Buffer.from('456')]; + + up.prependLocalBufferToUpstream(); + + assert.equal(up.localWriteCache.length, 0); + // shouldn't concat any buffers, thus writeBuffers.length = 2 + assert.equal(up.writeBuffers.length, 2); + assert.equal(Buffer.concat(up.writeBuffers).toString(), '123456'); + assert.equal(up.localWriteCacheByteLength, 0); + }); + + it('should keep the desired last few bytes', () => { + up.localWriteCache = [Buffer.from('123'), Buffer.from('456')]; + up.localWriteCacheByteLength = up.localWriteCache.reduce( + (a: Buffer, b: number) => a.byteLength + b + ); + up.writeBuffers = [Buffer.from('789')]; + + up.prependLocalBufferToUpstream(2); + + assert.equal(up.localWriteCache.length, 0); + // shouldn't concat any buffers, thus writeBuffers.length = 2 + assert.equal(up.writeBuffers.length, 2); + assert.equal(Buffer.concat(up.writeBuffers).toString(), '56789'); + assert.equal(up.localWriteCacheByteLength, 0); + }); + }); + + describe('#pullFromChunkBuffer', () => { + it('should retrieve from the beginning of the `writeBuffers`', () => { + up.writeBuffers = [Buffer.from('ab')]; + + const [chunk] = [...up.pullFromChunkBuffer(1)]; + assert.equal(chunk.toString(), 'a'); + assert.equal(up.writeBuffers.length, 1); + assert.equal(up.writeBuffers[0].toString(), 'b'); + }); + + it('should retrieve no more than the limit provided', () => { + up.writeBuffers = [Buffer.from('0123456789')]; + + const chunks = [...up.pullFromChunkBuffer(4)]; + assert.equal(chunks.join('').toString(), '0123'); + + // length should be 1 + assert.equal(up.writeBuffers.length, 1); + assert.equal(up.writeBuffers[0].toString(), '456789'); + }); + + it('should retrieve less than the limit if no more data is available (single write)', () => { + up.writeBuffers = [Buffer.from('0123456789')]; + + const chunks = [...up.pullFromChunkBuffer(512)]; + assert.equal(chunks.join('').toString(), '0123456789'); + assert.equal(up.writeBuffers.length, 0); + }); + + it('should retrieve less than the limit if no more data is available (multi write)', () => { + // an array of 1-char buffers + up.writeBuffers = '0123456789'.split('').map(c => Buffer.from(c)); + + const chunks = [...up.pullFromChunkBuffer(512)]; + assert.equal(chunks.join('').toString(), '0123456789'); + assert.equal(up.writeBuffers.length, 0); + }); + + it('should retrieve a subset of part of a buffer and prepend the remainder', () => { + up.writeBuffers = [ + Buffer.from('0'), + Buffer.from('123'), + Buffer.from('456'), // this buffer should be split + Buffer.from('789'), + ]; + + const chunks = [...up.pullFromChunkBuffer(5)]; + assert.equal(chunks.join('').toString(), '01234'); + assert.equal(up.writeBuffers.length, 2); + assert.equal(up.writeBuffers[0].toString(), '56'); + assert.equal(up.writeBuffers[1].toString(), '789'); + }); + + it('should return all data if `Infinity` is provided', () => { + up.writeBuffers = [Buffer.from('012345'), Buffer.from('6789')]; + const chunks = [...up.pullFromChunkBuffer(Infinity)]; + assert.equal(chunks.join('').toString(), '0123456789'); + assert.equal(up.writeBuffers.length, 0); + }); + + it("should emit 'readFromChunkBuffer' synchronously on each iterator", () => { + up.writeBuffers = [Buffer.from('012345'), Buffer.from('6789')]; + + const iter = up.pullFromChunkBuffer(Infinity); + let count = 0; + let loop = 0; + + up.on('readFromChunkBuffer', () => count++); + + while (!iter.next().done) { + assert.equal(count, loop++); + } + }); + }); + + describe('#waitForNextChunk', () => { + it('should resolve `true` asynchronously if `writeBuffers.length` has data', async () => { + up.writeBuffers = [Buffer.from('ab')]; + + assert(await up.waitForNextChunk()); + }); + + it('should resolve `false` asynchronously if `upstreamEnded`', async () => { + up.upstreamEnded = true; + + assert.equal(await up.waitForNextChunk(), false); + }); + + it('should resolve `true` asynchronously if `writeBuffers.length` and `upstreamEnded`', async () => { + up.writeBuffers = [Buffer.from('ab')]; + up.upstreamEnded = true; + + assert(await up.waitForNextChunk()); + }); + + it('should wait for `wroteToChunkBuffer` if !`writeBuffers.length` && !`upstreamEnded`', async () => { + const result = await new Promise(resolve => { + up.waitForNextChunk().then(resolve); + up.emit('wroteToChunkBuffer'); + }); + + assert(result); + }); + + it("should wait for 'upstreamFinished' if !`writeBuffers.length` && !`upstreamEnded`", async () => { + await new Promise(resolve => { + up.waitForNextChunk().then(resolve); + up.emit('upstreamFinished'); + }); + }); + + it("should wait for 'upstreamFinished' and resolve `false` if data is not available", async () => { + const result = await new Promise(resolve => { + up.waitForNextChunk().then(resolve); + up.emit('upstreamFinished'); + }); + + assert.equal(result, false); + }); + + it("should wait for 'upstreamFinished' and resolve `true` if data is available", async () => { + const result = await new Promise(resolve => { + up.on('newListener', (event: string) => { + if (event === 'upstreamFinished') { + // Update the `writeBuffers` before emitting 'upstreamFinished' + up.writeBuffers = [Buffer.from('abc')]; + + process.nextTick(() => up.emit('upstreamFinished')); + } + }); + + up.waitForNextChunk().then(resolve); + }); + + assert.equal(result, true); + }); + + it("should wait for 'upstreamFinished' if !`writeBuffers.length` && !`upstreamEnded`", async () => { + await new Promise(resolve => { + up.waitForNextChunk().then(resolve); + up.emit('upstreamFinished'); + }); + }); + + it("should wait for 'upstreamFinished' and resolve `false` if data is not available", async () => { + const result = await new Promise(resolve => { + up.waitForNextChunk().then(resolve); + up.emit('upstreamFinished'); + }); + + assert.equal(result, false); + }); + + it("should wait for 'upstreamFinished' and resolve `true` if data is available", async () => { + const result = await new Promise(resolve => { + up.on('newListener', (event: string) => { + if (event === 'upstreamFinished') { + // Update the `writeBuffers` before emitting 'upstreamFinished' + up.writeBuffers = [Buffer.from('abc')]; + + process.nextTick(() => up.emit('upstreamFinished')); + } + }); + + up.waitForNextChunk().then(resolve); + }); + + assert.equal(result, true); + }); + + it('should remove listeners after calling back from `wroteToChunkBuffer`', async () => { + assert.equal(up.listenerCount('wroteToChunkBuffer'), 0); + assert.equal(up.listenerCount('upstreamFinished'), 0); + + await new Promise(resolve => { + up.on('newListener', (event: string) => { + if (event === 'wroteToChunkBuffer') { + process.nextTick(() => up.emit('wroteToChunkBuffer')); + } + }); + + up.waitForNextChunk().then(resolve); + }); + + assert.equal(up.listenerCount('wroteToChunkBuffer'), 0); + assert.equal(up.listenerCount('upstreamFinished'), 0); + }); + + it("should remove listeners after calling back from 'upstreamFinished'", async () => { + assert.equal(up.listenerCount('wroteToChunkBuffer'), 0); + assert.equal(up.listenerCount('upstreamFinished'), 0); + + await new Promise(resolve => { + up.on('newListener', (event: string) => { + if (event === 'upstreamFinished') { + process.nextTick(() => up.emit('upstreamFinished')); + } + }); + + up.waitForNextChunk().then(resolve); + }); + + assert.equal(up.listenerCount('wroteToChunkBuffer'), 0); + assert.equal(up.listenerCount('upstreamFinished'), 0); + }); + }); + + describe('#upstreamIterator', () => { + it('should yield all data from upstream by default', done => { + up.writeBuffers = [Buffer.alloc(1)]; + assert(up.writableHighWaterMark); + + up.pullFromChunkBuffer = (limit: number) => { + assert.equal(limit, Infinity); + done(); + }; + + const iterator = up.upstreamIterator(); + iterator.next(); + }); + + it('should yield up to limit if provided', async () => { + up.writeBuffers = [Buffer.alloc(16)]; + + let data = Buffer.alloc(0); + + for await (const chunk of up.upstreamIterator(8)) { + data = Buffer.concat([data, chunk]); + } + + assert.equal(data.byteLength, 8); + }); + + it("should yield less than the limit if that's all that's available", async () => { + up.writeBuffers = [Buffer.alloc(8)]; + up.upstreamEnded = true; + + let data = Buffer.alloc(0); + + for await (const chunk of up.upstreamIterator(16)) { + data = Buffer.concat([data, chunk]); + } + + assert.equal(data.byteLength, 8); + }); + + it('should yield many, arbitrarily sized chunks', async () => { + up.waitForNextChunk = () => true; + up.pullFromChunkBuffer = () => [Buffer.from('a')]; + + let data = Buffer.alloc(0); + let count = 0; + + for await (const chunk of up.upstreamIterator(16)) { + data = Buffer.concat([data, chunk]); + count++; + } + + assert.equal(data.toString(), 'a'.repeat(16)); + assert.equal(count, 16); + }); + }); + + describe('#createURI', () => { + it('should make the correct request', done => { + up.makeRequest = async (reqOpts: GaxiosOptions) => { + assert.strictEqual(reqOpts.method, 'POST'); + assert.strictEqual(reqOpts.url, `${BASE_URI}/${BUCKET}/o`); + assert.deepStrictEqual(reqOpts.params, { + predefinedAcl: up.predefinedAcl, + name: FILE, + uploadType: 'resumable', + ifGenerationMatch: GENERATION, + ifMetagenerationNotMatch: PARAMS.ifMetagenerationNotMatch, + }); + const metadataNoHeaders = {...up.metadata}; + delete metadataNoHeaders.contentLength; + delete metadataNoHeaders.contentType; + assert.deepStrictEqual(reqOpts.data, metadataNoHeaders); + done(); + return {headers: {location: '/foo'}}; + }; + up.createURI(); + }); + + it('should pass through the KMS key name', done => { + const kmsKeyName = 'kms-key-name'; + const up = upload({ + bucket: BUCKET, + file: FILE, + kmsKeyName, + retryOptions: RETRY_OPTIONS, + }); + + up.makeRequest = async (reqOpts: GaxiosOptions) => { + assert.strictEqual(reqOpts.params.kmsKeyName, kmsKeyName); + done(); + return {headers: {location: '/foo'}}; + }; + + up.createURI(); + }); + + it('should respect 0 as a generation', done => { + up.makeRequest = async (reqOpts: GaxiosOptions) => { + assert.strictEqual(reqOpts.params.ifGenerationMatch, 0); + done(); + return {headers: {location: '/foo'}}; + }; + up.generation = 0; + up.createURI(); + }); + + describe('error', () => { + const error = new Error(':('); + + beforeEach(() => { + up.makeRequest = async () => { + throw error; + }; + }); + + it('should exec callback with error', done => { + up.createURI((err: Error) => { + assert.strictEqual(err, error); + done(); + }); + }); + + it('currentInvocationId.uri should remain the same on error', done => { + const beforeCallInvocationId = up.currentInvocationId.uri; + up.createURI((err: Error) => { + assert(err); + assert.equal(beforeCallInvocationId, up.currentInvocationId.uri); + done(); + }); + }); + }); + + describe('success', () => { + const URI = 'uri'; + const RESP = {headers: {location: URI}}; + + beforeEach(() => { + up.makeRequest = async () => { + return RESP; + }; + }); + + it('should localize the uri', done => { + up.createURI((err: Error) => { + assert.ifError(err); + assert.strictEqual(up.uri, URI); + assert.strictEqual(up.offset, 0); + done(); + }); + }); + + it('should default the offset to 0', done => { + up.createURI((err: Error) => { + assert.ifError(err); + assert.strictEqual(up.offset, 0); + done(); + }); + }); + + it('should exec callback with URI', done => { + up.createURI((err: Error, uri: string) => { + assert.ifError(err); + assert.strictEqual(uri, URI); + done(); + }); + }); + + it('currentInvocationId.uri should be different after success', done => { + const beforeCallInvocationId = up.currentInvocationId.uri; + up.createURI(() => { + assert.notEqual(beforeCallInvocationId, up.currentInvocationId.uri); + done(); + }); + }); + }); + }); + + describe('#continueUploading', () => { + it('should start uploading if an offset was set', done => { + up.offset = 0; + up.startUploading = async () => { + done(); + }; + up.continueUploading(); + }); + + it('should get and set offset if no offset was set', done => { + up.getAndSetOffset = async () => { + done(); + }; + up.startUploading = () => Promise.resolve(); + up.continueUploading(); + }); + + it('should start uploading when done', done => { + up.startUploading = async function () { + assert.strictEqual(this, up); + done(); + }; + up.getAndSetOffset = () => Promise.resolve(); + up.continueUploading(); + }); + }); + + describe('#startUploading', () => { + beforeEach(() => { + up.makeRequestStream = async () => null; + up.writeBuffers = [Buffer.alloc(16)]; + }); + + it('should reset `numChunksReadInRequest` to 0', async () => { + up.numChunksReadInRequest = 1; + + await up.startUploading(); + + assert.equal(up.numChunksReadInRequest, 0); + }); + + it('should set `offset` to 0 when not set', async () => { + assert.equal(up.offset, undefined); + + await up.startUploading(); + + assert.equal(up.offset, 0); + }); + + it('should emit error if `offset` < `numBytesWritten`', done => { + up.numBytesWritten = 1; + + const expectedSent = up.numBytesWritten; + const expectedServer = 0; + const expectedDelta = expectedSent - expectedServer; + + up.on('error', (error: Error) => { + assert(error instanceof RangeError); + + const m = error.message; + assert(m.includes('offset is lower than the number of bytes written')); + assert(m.includes(`server has ${expectedServer} bytes`)); + assert(m.includes(`${expectedSent} bytes has been uploaded`)); + assert(m.includes(`${expectedDelta} bytes are missing`)); + done(); + }); + + up.startUploading(); + }); + + it("should 'fast-forward' upstream if `numBytesWritten` < `offset`", async () => { + up.writeBuffers = [Buffer.alloc(24)]; + + up.offset = 9; + up.numBytesWritten = 1; + + await up.startUploading(); + + // Should fast-forward (up.offset - up.numBytesWritten) bytes + assert.equal(up.offset, 9); + assert.equal(up.numBytesWritten, 9); + assert.equal(up.writeBuffers.length, 1); + assert.equal(up.writeBuffers[0].byteLength, 16); + }); + + it('should emit a progress event with the bytes written', done => { + up.writeBuffers = [Buffer.alloc(24)]; + up.upstreamEnded = true; + up.contentLength = 24; + + up.on( + 'progress', + (data: {bytesWritten: number; contentLength: number}) => { + assert.equal(data.bytesWritten, 24); + assert.equal(data.contentLength, 24); + + done(); + } + ); + + up.makeRequestStream = async (reqOpts: GaxiosOptions) => { + reqOpts.body.on('data', () => {}); + }; + + up.startUploading(); + }); + + it('should destroy the stream if the request failed', done => { + const error = new Error('Error.'); + up.on('error', (e: Error) => { + assert.strictEqual(e, error); + done(); + }); + + up.makeRequestStream = async () => { + throw error; + }; + up.startUploading(); + }); + + it('should retry retryable errors if the request failed', done => { + const error = new Error('Error.'); + + // mock as retryable + up.retryOptions.retryableErrorFn = () => true; + + up.on('error', done); + up.attemptDelayedRetry = () => done(); + + up.makeRequestStream = async () => { + throw error; + }; + + up.startUploading(); + }); + + describe('request preparation', () => { + // Simulating the amount of data written from upstream (exhaustive) + const UPSTREAM_BUFFER_SIZE = 512; + const UPSTREAM_ENDED = true; + // a convenient handle for getting the request options + let reqOpts: GaxiosOptions; + + async function getAllDataFromRequest() { + let payload = Buffer.alloc(0); + + await new Promise(resolve => { + reqOpts.body.on('data', (data: Buffer) => { + payload = Buffer.concat([payload, data]); + }); + + reqOpts.body.on('end', () => { + resolve(payload); + }); + }); + + return payload; + } + + beforeEach(() => { + reqOpts = {}; + up.makeRequestStream = async (requestOptions: GaxiosOptions) => { + assert.equal(requestOptions.method, 'PUT'); + assert.equal(requestOptions.url, up.uri); + assert.equal(typeof requestOptions.headers, 'object'); + assert(requestOptions.body instanceof Readable); + + reqOpts = requestOptions; + }; + up.writeBuffers = [Buffer.alloc(UPSTREAM_BUFFER_SIZE)]; + up.upstreamEnded = UPSTREAM_ENDED; + }); + + describe('single chunk', () => { + it('should use `contentLength` and `offset` if set', async () => { + const OFFSET = 100; + const CONTENT_LENGTH = 123; + + up.offset = OFFSET; + up.contentLength = CONTENT_LENGTH; + + await up.startUploading(); + + assert(reqOpts.headers); + assert.equal( + reqOpts.headers['Content-Range'], + `bytes ${OFFSET}-*/${CONTENT_LENGTH}` + ); + assert.ok( + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + ); + assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); + + const data = await getAllDataFromRequest(); + + assert.equal(data.byteLength, 23); + }); + + it('should prepare a valid request if `contentLength` is unknown', async () => { + up.contentLength = '*'; + + await up.startUploading(); + + assert(reqOpts.headers); + assert.equal(reqOpts.headers['Content-Range'], 'bytes 0-*/*'); + assert.ok( + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + ); + assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); + + const data = await getAllDataFromRequest(); + + assert.equal(data.byteLength, 512); + }); + }); + + describe('multiple chunk', () => { + const CHUNK_SIZE = 256; + + beforeEach(() => { + up.chunkSize = CHUNK_SIZE; + }); + + it('should use `chunkSize` if less than `contentLength`', async () => { + const OFFSET = 100; + const CONTENT_LENGTH = 512; + + up.offset = OFFSET; + up.contentLength = CONTENT_LENGTH; + + await up.startUploading(); + + const endByte = OFFSET + CHUNK_SIZE - 1; + assert(reqOpts.headers); + assert.equal(reqOpts.headers['Content-Length'], CHUNK_SIZE); + assert.equal( + reqOpts.headers['Content-Range'], + `bytes ${OFFSET}-${endByte}/${CONTENT_LENGTH}` + ); + assert.ok( + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + ); + assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); + + const data = await getAllDataFromRequest(); + + assert.equal(data.byteLength, CHUNK_SIZE); + }); + + it('should prepare a valid request if `contentLength` is unknown', async () => { + const OFFSET = 100; + const EXPECTED_STREAM_AMOUNT = Math.min( + UPSTREAM_BUFFER_SIZE - OFFSET, + CHUNK_SIZE + ); + const ENDING_BYTE = EXPECTED_STREAM_AMOUNT + OFFSET - 1; + + up.offset = OFFSET; + up.contentLength = '*'; + + await up.startUploading(); + + assert(reqOpts.headers); + assert.equal( + reqOpts.headers['Content-Length'], + EXPECTED_STREAM_AMOUNT + ); + assert.equal( + reqOpts.headers['Content-Range'], + `bytes ${OFFSET}-${ENDING_BYTE}/*` + ); + assert.ok( + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + ); + assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); + + const data = await getAllDataFromRequest(); + + assert.equal(data.byteLength, CHUNK_SIZE); + }); + + it('should prepare a valid request if the remaining data is less than `chunkSize`', async () => { + const NUM_BYTES_WRITTEN = 400; + const OFFSET = NUM_BYTES_WRITTEN; + const CONTENT_LENGTH = 512; + + up.offset = OFFSET; + up.numBytesWritten = NUM_BYTES_WRITTEN; + up.contentLength = CONTENT_LENGTH; + + await up.startUploading(); + + const endByte = CONTENT_LENGTH - NUM_BYTES_WRITTEN + OFFSET - 1; + assert(reqOpts.headers); + assert.equal( + reqOpts.headers['Content-Length'], + CONTENT_LENGTH - NUM_BYTES_WRITTEN + ); + assert.equal( + reqOpts.headers['Content-Range'], + `bytes ${OFFSET}-${endByte}/${CONTENT_LENGTH}` + ); + assert.ok( + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + ); + assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); + const data = await getAllDataFromRequest(); + + assert.equal(data.byteLength, CONTENT_LENGTH - NUM_BYTES_WRITTEN); + }); + }); + }); + + describe('X-Goog-Hash header injection', () => { + const CALCULATED_CRC32C = 'bzKmHw=='; + const CALCULATED_MD5 = 'VpBzljOcorCZvRIkX5Nt3A=='; + const DUMMY_CONTENT = Buffer.alloc(512, 'a'); + const CHUNK_SIZE = 256; + + let requestCount: number; + + /** + * Creates a mocked HashValidator object with forced getters to return + * predefined hash values, bypassing internal stream calculation logic. + */ + function createMockHashValidator( + crc32cEnabled: boolean, + md5Enabled: boolean + ) { + const mockValidator = { + crc32cEnabled: crc32cEnabled, + md5Enabled: md5Enabled, + end: () => {}, // Mock the end method + write: () => {}, + }; + + Object.defineProperty(mockValidator, 'crc32c', { + get: () => CALCULATED_CRC32C, + configurable: true, + }); + Object.defineProperty(mockValidator, 'md5Digest', { + get: () => CALCULATED_MD5, + configurable: true, + }); + return mockValidator; + } + + const MOCK_AUTH_CLIENT = { + // Mock the request method to return a dummy response + request: async (opts: GaxiosOptions) => { + return { + status: 200, + data: {}, + headers: {}, + config: opts, + statusText: 'OK', + } as GaxiosResponse; + }, + getRequestHeaders: async () => ({}), + getRequestMetadata: async () => ({}), + getRequestMetadataAsync: async () => ({}), + getClient: async () => MOCK_AUTH_CLIENT, + }; + + /** + * Sets up the `up` instance for hash injection tests. + * @param configOptions Partial UploadConfig to apply. + */ + function setupHashUploadInstance( + configOptions: Partial & {crc32c?: boolean; md5?: boolean} + ) { + up = upload({ + bucket: BUCKET, + file: FILE, + authClient: MOCK_AUTH_CLIENT, + retryOptions: {...RETRY_OPTIONS, maxRetries: 0}, + metadata: { + contentLength: DUMMY_CONTENT.byteLength, + contentType: 'text/plain', + }, + ...configOptions, + }); + + // Manually inject the mock HashStreamValidator if needed + const calculateCrc32c = + !configOptions.clientCrc32c && configOptions.crc32c; + const calculateMd5 = !configOptions.clientMd5Hash && configOptions.md5; + + if (calculateCrc32c || calculateMd5) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (up as any)['#hashValidator'] = createMockHashValidator( + !!calculateCrc32c, + !!calculateMd5 + ); + } + } + + async function performUpload( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + uploadInstance: any, + data: Buffer, + isMultiChunk: boolean, + expectedCrc32c?: string, + expectedMd5?: string + ): Promise { + const capturedReqOpts: GaxiosOptions[] = []; + requestCount = 0; + + uploadInstance.makeRequestStream = async ( + requestOptions: GaxiosOptions + ) => { + requestCount++; + capturedReqOpts.push(requestOptions); + + await new Promise(resolve => { + requestOptions.body.on('data', () => {}); + requestOptions.body.on('end', resolve); + }); + + const serverCrc32c = expectedCrc32c || CALCULATED_CRC32C; + const serverMd5 = expectedMd5 || CALCULATED_MD5; + if ( + isMultiChunk && + requestCount < Math.ceil(DUMMY_CONTENT.byteLength / CHUNK_SIZE) + ) { + const lastByteReceived = requestCount * CHUNK_SIZE - 1; + return { + data: '', + status: RESUMABLE_INCOMPLETE_STATUS_CODE, + headers: {range: `bytes=0-${lastByteReceived}`}, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; + } else { + return { + status: 200, + data: { + crc32c: serverCrc32c, + md5Hash: serverMd5, + name: FILE, + bucket: BUCKET, + size: DUMMY_CONTENT.byteLength.toString(), + }, + headers: {}, + config: {}, + statusText: 'OK', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; + } + }; + + return new Promise((resolve, reject) => { + uploadInstance.on('error', reject); + uploadInstance.on('uploadFinished', () => { + resolve(capturedReqOpts); + }); + + const upstreamBuffer = new Readable({ + read() { + this.push(data); + this.push(null); + }, + }); + upstreamBuffer.pipe(uploadInstance); + }); + } + + describe('single chunk', () => { + it('should include X-Goog-Hash header with crc32c when crc32c is enabled (via validator)', async () => { + setupHashUploadInstance({crc32c: true}); + const reqOpts = await performUpload(up, DUMMY_CONTENT, false); + assert.strictEqual(reqOpts.length, 1); + assert.equal( + reqOpts[0].headers!['X-Goog-Hash'], + `crc32c=${CALCULATED_CRC32C}` + ); + }); + + it('should include X-Goog-Hash header with md5 when md5 is enabled (via validator)', async () => { + setupHashUploadInstance({md5: true}); + const reqOpts = await performUpload(up, DUMMY_CONTENT, false); + assert.strictEqual(reqOpts.length, 1); + assert.equal( + reqOpts[0].headers!['X-Goog-Hash'], + `md5=${CALCULATED_MD5}` + ); + }); + + it('should include both crc32c and md5 in X-Goog-Hash when both are enabled (via validator)', async () => { + setupHashUploadInstance({crc32c: true, md5: true}); + const reqOpts = await performUpload(up, DUMMY_CONTENT, false); + assert.strictEqual(reqOpts.length, 1); + const xGoogHash = reqOpts[0].headers!['X-Goog-Hash']; + assert.ok(xGoogHash); + const expectedHashes = [ + `crc32c=${CALCULATED_CRC32C}`, + `md5=${CALCULATED_MD5}`, + ]; + const actualHashes = xGoogHash + .split(',') + .map((s: string) => s.trim()); + assert.deepStrictEqual(actualHashes.sort(), expectedHashes.sort()); + }); + + it('should use clientCrc32c if provided (pre-calculated hash)', async () => { + const customCrc32c = 'CUSTOMCRC'; + setupHashUploadInstance({crc32c: true, clientCrc32c: customCrc32c}); + const reqOpts = await performUpload( + up, + DUMMY_CONTENT, + false, + customCrc32c + ); + assert.strictEqual(reqOpts.length, 1); + assert.strictEqual( + reqOpts[0].headers!['X-Goog-Hash'], + `crc32c=${customCrc32c}` + ); + }); + + it('should use clientMd5Hash if provided (pre-calculated hash)', async () => { + const customMd5 = 'CUSTOMMD5'; + setupHashUploadInstance({md5: true, clientMd5Hash: customMd5}); + const reqOpts = await performUpload( + up, + DUMMY_CONTENT, + false, + undefined, + customMd5 + ); + assert.strictEqual(reqOpts.length, 1); + assert.strictEqual( + reqOpts[0].headers!['X-Goog-Hash'], + `md5=${customMd5}` + ); + }); + + it('should not include X-Goog-Hash if neither crc32c nor md5 are enabled', async () => { + setupHashUploadInstance({}); + const reqOpts = await performUpload(up, DUMMY_CONTENT, false); + assert.strictEqual(reqOpts.length, 1); + assert.strictEqual(reqOpts[0].headers!['X-Goog-Hash'], undefined); + }); + }); + + describe('multiple chunk', () => { + beforeEach(() => { + setupHashUploadInstance({ + crc32c: true, + md5: true, + chunkSize: CHUNK_SIZE, + }); + }); + + it('should NOT include X-Goog-Hash header on intermediate multi-chunk requests', async () => { + const reqOpts = await performUpload(up, DUMMY_CONTENT, true); + assert.strictEqual(reqOpts.length, 2); + + assert.strictEqual(reqOpts[0].headers!['Content-Length'], CHUNK_SIZE); + assert.strictEqual(reqOpts[0].headers!['X-Goog-Hash'], undefined); + }); + + it('should include X-Goog-Hash header ONLY on the final multi-chunk request', async () => { + const expectedHashHeader = `crc32c=${CALCULATED_CRC32C},md5=${CALCULATED_MD5}`; + const reqOpts = await performUpload(up, DUMMY_CONTENT, true); + assert.strictEqual(reqOpts.length, 2); + + assert.strictEqual(reqOpts[1].headers!['Content-Length'], CHUNK_SIZE); + assert.equal(reqOpts[1].headers!['X-Goog-Hash'], expectedHashHeader); + }); + }); + }); + }); + + describe('#responseHandler', () => { + it('should emit the metadata', done => { + const BODY = {hi: 1}; + const RESP = {data: BODY, status: 200}; + up.on('metadata', (body: {}) => { + assert.strictEqual(body, BODY); + done(); + }); + up.upstreamEnded = true; + + up.responseHandler(RESP); + }); + + it('should return response data size as number', done => { + const metadata = { + size: '0', + }; + const RESP = {data: metadata, status: 200}; + up.on('metadata', (data: {size: number}) => { + assert.strictEqual(Number(metadata.size), data.size); + assert.strictEqual(typeof data.size, 'number'); + done(); + }); + up.upstreamEnded = true; + + up.responseHandler(RESP); + }); + + it('should destroy the stream if an error occurred', done => { + const RESP = {data: {error: new Error('Error.')}}; + up.on('metadata', done); + // metadata shouldn't be emitted... will blow up test if called + up.destroy = (err: Error) => { + assert.strictEqual(err, RESP.data.error); + done(); + }; + up.upstreamEnded = true; + up.responseHandler(RESP); + }); + + it('should destroy the stream if the status code is out of range', done => { + const RESP = {data: {}, status: 300}; + up.on('metadata', done); + // metadata shouldn't be emitted... will blow up test if called + up.destroy = (err: Error) => { + assert.strictEqual(err.message, 'Upload failed'); + done(); + }; + up.upstreamEnded = true; + up.responseHandler(RESP); + }); + + it('should destroy the stream on CRC32C checksum mismatch', done => { + const CLIENT_CRC = 'client_hash'; + const SERVER_CRC = 'server_hash'; + const RESP = { + data: { + crc32c: SERVER_CRC, + md5Hash: 'md5_match', + size: '100', + }, + status: 200, + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (up as any)['#hashValidator'] = { + crc32cEnabled: true, + md5Enabled: true, + crc32c: CLIENT_CRC, + md5Digest: 'md5_match', + }; + up.upstreamEnded = true; + + up.destroy = (err: Error) => { + assert.strictEqual(err.message, FileExceptionMessages.UPLOAD_MISMATCH); + done(); + }; + + up.responseHandler(RESP); + }); + + it('should destroy the stream on MD5 checksum mismatch', done => { + const CLIENT_MD5 = 'client_md5'; + const SERVER_MD5 = 'server_md5'; + const RESP = { + data: { + crc32c: 'crc32c_match', + md5Hash: SERVER_MD5, + size: '100', + }, + status: 200, + }; + + up.md5 = true; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (up as any)['#hashValidator'] = { + crc32c: 'crc32c_match', + md5Digest: CLIENT_MD5, + }; + up.upstreamEnded = true; + + up.destroy = (err: Error) => { + assert.strictEqual(err.message, FileExceptionMessages.UPLOAD_MISMATCH); + done(); + }; + + up.responseHandler(RESP); + }); + + it('should continue with multi-chunk upload when incomplete', done => { + const lastByteReceived = 9; + + const RESP = { + data: '', + status: RESUMABLE_INCOMPLETE_STATUS_CODE, + headers: { + range: `bytes=0-${lastByteReceived}`, + }, + }; + + up.chunkSize = 1; + up.writeBuffers = [Buffer.alloc(0)]; + + up.continueUploading = () => { + assert.equal(up.offset, lastByteReceived + 1); + + done(); + }; + + up.responseHandler(RESP); + }); + + it('should not continue with multi-chunk upload when incomplete if a partial upload has finished', done => { + const lastByteReceived = 9; + + const RESP = { + data: '', + status: RESUMABLE_INCOMPLETE_STATUS_CODE, + headers: { + range: `bytes=0-${lastByteReceived}`, + }, + }; + + up.chunkSize = 1; + up.upstreamEnded = true; + up.isPartialUpload = true; + + up.on('uploadFinished', done); + + up.responseHandler(RESP); + }); + + it('should error when upload is incomplete and the upstream is not a partial upload', done => { + const lastByteReceived = 9; + + const RESP = { + data: '', + status: RESUMABLE_INCOMPLETE_STATUS_CODE, + headers: { + range: `bytes=0-${lastByteReceived}`, + }, + }; + + up.chunkSize = 1; + up.upstreamEnded = true; + + up.on('error', (e: Error) => { + assert.match(e.message, /Upload failed/); + + done(); + }); + + up.responseHandler(RESP); + }); + + it('should unshift missing data if server did not receive the entire chunk', done => { + const NUM_BYTES_WRITTEN = 20; + const LAST_CHUNK_LENGTH = 256; + const UPSTREAM_BUFFER_LENGTH = 1024; + const lastByteReceived = 9; + const expectedUnshiftAmount = NUM_BYTES_WRITTEN - lastByteReceived - 1; + + const RESP = { + data: '', + status: RESUMABLE_INCOMPLETE_STATUS_CODE, + headers: { + range: `bytes=0-${lastByteReceived}`, + }, + }; + + up.chunkSize = 256; + up.numBytesWritten = NUM_BYTES_WRITTEN; + up.writeBuffers = [Buffer.alloc(UPSTREAM_BUFFER_LENGTH, 'b')]; + + up.localWriteCache = [ + Buffer.alloc(LAST_CHUNK_LENGTH, 'c'), + // different to ensure this is the data that's prepended + Buffer.alloc(expectedUnshiftAmount, 'a'), + ]; + + up.continueUploading = () => { + assert.equal(up.offset, lastByteReceived + 1); + assert.equal( + Buffer.concat(up.writeBuffers).byteLength, + UPSTREAM_BUFFER_LENGTH + expectedUnshiftAmount + ); + assert.equal( + Buffer.concat(up.writeBuffers) + .subarray(0, expectedUnshiftAmount) + .toString(), + 'a'.repeat(expectedUnshiftAmount) + ); + + // we should discard part of the last chunk, as we know what the server + // has at this point. + assert.deepEqual(up.localWriteCache, []); + + done(); + }; + + up.responseHandler(RESP); + }); + + it('currentInvocationId.chunk should be different after success', done => { + const beforeCallInvocationId = up.currentInvocationId.chunk; + const RESP = {data: '', status: 200}; + up.upstreamEnded = true; + + up.on('uploadFinished', () => { + assert.notEqual(beforeCallInvocationId, up.currentInvocationId.chunk); + done(); + }); + up.responseHandler(RESP); + }); + + it('currentInvocationId.chunk should be the same after error', done => { + const beforeCallInvocationId = up.currentInvocationId.chunk; + const RESP = {data: {error: new Error('Error.')}}; + up.destroy = () => { + assert.equal(beforeCallInvocationId, up.currentInvocationId.chunk); + done(); + }; + up.responseHandler(RESP); + }); + }); + + it('currentInvocationId.checkUploadStatus should be different after success', async () => { + const beforeCallInvocationId = up.currentInvocationId.checkUploadStatus; + up.makeRequest = () => { + return {}; + }; + await up.getAndSetOffset(); + assert.notEqual( + beforeCallInvocationId, + up.currentInvocationId.checkUploadStatus + ); + }); + + it('currentInvocationId.checkUploadStatus should be the same on error', done => { + const beforeCallInvocationId = up.currentInvocationId.checkUploadStatus; + up.destroy = () => { + assert.equal( + beforeCallInvocationId, + up.currentInvocationId.checkUploadStatus + ); + done(); + }; + up.makeRequest = () => { + throw new Error() as GaxiosError; + }; + + up.getAndSetOffset().catch(done); + }); + + describe('#getAndSetOffset', () => { + const RANGE = 123456; + const RESP = {status: 308, headers: {range: `range-${RANGE}`}}; + + it('should make the correct request', done => { + const URI = 'uri'; + up.uri = URI; + up.makeRequest = async (reqOpts: GaxiosOptions) => { + assert.strictEqual(reqOpts.method, 'PUT'); + assert.strictEqual(reqOpts.url, URI); + assert(reqOpts.headers); + assert.equal(reqOpts.headers['Content-Length'], 0); + assert.equal(reqOpts.headers['Content-Range'], 'bytes */*'); + assert.ok( + X_GOOG_API_HEADER_REGEX.test(reqOpts.headers['x-goog-api-client']) + ); + assert.ok(USER_AGENT_REGEX.test(reqOpts.headers['User-Agent'])); + done(); + return {}; + }; + up.getAndSetOffset(); + }); + + it('should set the offset from the range', async () => { + up.makeRequest = async () => RESP; + await up.getAndSetOffset(); + assert.strictEqual(up.offset, RANGE + 1); + }); + + it('should set the offset to 0 if no range is back from the API', async () => { + up.makeRequest = async () => { + return {}; + }; + await up.getAndSetOffset(); + assert.strictEqual(up.offset, 0); + }); + + it('should retry retryable errors if the request failed', done => { + const error = new Error('Error.'); + + // mock as retryable + up.retryOptions.retryableErrorFn = () => true; + + up.on('error', done); + up.attemptDelayedRetry = () => done(); + + up.makeRequest = async () => { + throw error; + }; + + up.getAndSetOffset(); + }); + }); + + describe('#makeRequest', () => { + it('should set encryption headers', async () => { + const key = crypto.randomBytes(32); + up = upload({ + bucket: 'BUCKET', + file: FILE, + key, + authConfig: {keyFile}, + retryOptions: RETRY_OPTIONS, + }); + const scopes = [ + mockAuthorizeRequest(), + nock(REQ_OPTS.url!).get('/').reply(200, {}), + ]; + const res = await up.makeRequest(REQ_OPTS); + scopes.forEach(x => x.done()); + const headers = res.config.headers; + assert.strictEqual(headers['x-goog-encryption-algorithm'], 'AES256'); + assert.strictEqual(headers['x-goog-encryption-key'], up.encryption.key); + assert.strictEqual( + headers['x-goog-encryption-key-sha256'], + up.encryption.hash + ); + }); + + it('should set userProject', async () => { + const scopes = [ + mockAuthorizeRequest(), + nock(REQ_OPTS.url!).get(queryPath).reply(200, {}), + ]; + const res: GaxiosResponse = await up.makeRequest(REQ_OPTS); + assert.strictEqual(res.config.url, REQ_OPTS.url + queryPath.slice(1)); + scopes.forEach(x => x.done()); + }); + + it('should set validate status', done => { + up.authClient = { + request: (reqOpts: GaxiosOptions) => { + assert.strictEqual(reqOpts.validateStatus!(100), false); + assert.strictEqual(reqOpts.validateStatus!(199), false); + assert.strictEqual(reqOpts.validateStatus!(300), false); + assert.strictEqual(reqOpts.validateStatus!(400), false); + assert.strictEqual(reqOpts.validateStatus!(500), false); + + assert.strictEqual(reqOpts.validateStatus!(200), true); + assert.strictEqual(reqOpts.validateStatus!(299), true); + assert.strictEqual(reqOpts.validateStatus!(308), true); + + done(); + + return {}; + }, + }; + up.makeRequest(REQ_OPTS); + }); + + it('should make the correct request', async () => { + const scopes = [ + mockAuthorizeRequest(), + nock(REQ_OPTS.url!).get(queryPath).reply(200, undefined, {}), + ]; + const res = await up.makeRequest(REQ_OPTS); + scopes.forEach(x => x.done()); + assert.strictEqual(res.config.url, REQ_OPTS.url + queryPath.slice(1)); + assert.deepStrictEqual(res.headers, {}); + }); + + it('should bypass authentication if emulator context detected', async () => { + up = upload({ + bucket: BUCKET, + file: FILE, + customRequestOptions: CUSTOM_REQUEST_OPTIONS, + generation: GENERATION, + metadata: METADATA, + origin: ORIGIN, + params: PARAMS, + predefinedAcl: PREDEFINED_ACL, + userProject: USER_PROJECT, + authConfig: {keyFile}, + apiEndpoint: 'https://fake.endpoint.com', + retryOptions: RETRY_OPTIONS, + }); + const scopes = [ + nock(REQ_OPTS.url!).get(queryPath).reply(200, undefined, {}), + ]; + const res = await up.makeRequest(REQ_OPTS); + scopes.forEach(x => x.done()); + assert.strictEqual(res.config.url, REQ_OPTS.url + queryPath.slice(1)); + assert.deepStrictEqual(res.headers, {}); + }); + + it('should use authentication with custom endpoint when useAuthWithCustomEndpoint is true', async () => { + up = upload({ + bucket: BUCKET, + file: FILE, + customRequestOptions: CUSTOM_REQUEST_OPTIONS, + generation: GENERATION, + metadata: METADATA, + origin: ORIGIN, + params: PARAMS, + predefinedAcl: PREDEFINED_ACL, + userProject: USER_PROJECT, + authConfig: {keyFile}, + apiEndpoint: 'https://custom-proxy.example.com', + useAuthWithCustomEndpoint: true, + retryOptions: RETRY_OPTIONS, + }); + + // Mock the authorization request + mockAuthorizeRequest(); + + // Mock the actual request with auth header expectation + const scopes = [ + nock(REQ_OPTS.url!) + .matchHeader('authorization', /Bearer .+/) + .get(queryPath) + .reply(200, undefined, {}), + ]; + + const res = await up.makeRequest(REQ_OPTS); + scopes.forEach(x => x.done()); + assert.strictEqual(res.config.url, REQ_OPTS.url + queryPath.slice(1)); + // Headers should include authorization + assert.ok(res.config.headers?.['Authorization']); + }); + + it('should bypass authentication with custom endpoint when useAuthWithCustomEndpoint is false', async () => { + up = upload({ + bucket: BUCKET, + file: FILE, + customRequestOptions: CUSTOM_REQUEST_OPTIONS, + generation: GENERATION, + metadata: METADATA, + origin: ORIGIN, + params: PARAMS, + predefinedAcl: PREDEFINED_ACL, + userProject: USER_PROJECT, + authConfig: {keyFile}, + apiEndpoint: 'https://storage-emulator.local', + useAuthWithCustomEndpoint: false, + retryOptions: RETRY_OPTIONS, + }); + + const scopes = [ + nock(REQ_OPTS.url!).get(queryPath).reply(200, undefined, {}), + ]; + const res = await up.makeRequest(REQ_OPTS); + scopes.forEach(x => x.done()); + assert.strictEqual(res.config.url, REQ_OPTS.url + queryPath.slice(1)); + // When auth is bypassed, no auth headers should be present + assert.deepStrictEqual(res.headers, {}); + }); + + it('should bypass authentication with custom endpoint when useAuthWithCustomEndpoint is undefined (backward compatibility)', async () => { + up = upload({ + bucket: BUCKET, + file: FILE, + customRequestOptions: CUSTOM_REQUEST_OPTIONS, + generation: GENERATION, + metadata: METADATA, + origin: ORIGIN, + params: PARAMS, + predefinedAcl: PREDEFINED_ACL, + userProject: USER_PROJECT, + authConfig: {keyFile}, + apiEndpoint: 'https://storage-emulator.local', + // useAuthWithCustomEndpoint is intentionally not set + retryOptions: RETRY_OPTIONS, + }); + + const scopes = [ + nock(REQ_OPTS.url!).get(queryPath).reply(200, undefined, {}), + ]; + const res = await up.makeRequest(REQ_OPTS); + scopes.forEach(x => x.done()); + assert.strictEqual(res.config.url, REQ_OPTS.url + queryPath.slice(1)); + // When auth is bypassed (backward compatibility), no auth headers should be present + assert.deepStrictEqual(res.headers, {}); + }); + + it('should combine customRequestOptions', done => { + const up = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + customRequestOptions: { + headers: { + 'X-My-Header': 'My custom value', + }, + }, + }); + mockAuthorizeRequest(); + up.authClient = { + request: (reqOpts: GaxiosOptions) => { + const customHeader = + reqOpts.headers && reqOpts.headers['X-My-Header']; + assert.strictEqual(customHeader, 'My custom value'); + setImmediate(done); + return {}; + }, + }; + up.makeRequest(REQ_OPTS); + }); + + it('should execute the callback with a body error & response', async () => { + const error = new GaxiosError('Error message', {}, { + config: {}, + data: {}, + status: 500, + statusText: 'sad trombone', + headers: {}, + } as GaxiosResponse); + mockAuthorizeRequest(); + const scope = nock(REQ_OPTS.url!).get(queryPath).reply(500, {error}); + await assert.rejects(up.makeRequest(REQ_OPTS), (err: GaxiosError) => { + scope.done(); + assert.strictEqual(err.status, 500); + return true; + }); + }); + + it('should execute the callback with a body error & response for non-2xx status codes', async () => { + const error = new GaxiosError('Error message', {}, { + config: {}, + data: {}, + status: 500, + statusText: 'sad trombone', + headers: {}, + } as GaxiosResponse); + mockAuthorizeRequest(); + const scope = nock(REQ_OPTS.url!).get(queryPath).reply(500, {error}); + await assert.rejects(up.makeRequest(REQ_OPTS), (err: GaxiosError) => { + scope.done(); + assert.deepStrictEqual(err.status, 500); + return true; + }); + }); + + it('should execute the callback', async () => { + const data = {red: 'tape'}; + mockAuthorizeRequest(); + up.onResponse = () => true; + const scope = nock(REQ_OPTS.url!).get(queryPath).reply(200, data); + const res = await up.makeRequest(REQ_OPTS); + scope.done(); + assert.strictEqual(res.status, 200); + assert.deepStrictEqual(res.data, data); + }); + }); + + describe('#makeRequestStream', () => { + beforeEach(() => { + up.authClient = {request: () => {}}; + up.onResponse = () => {}; + }); + + it('should pass a signal from the abort controller', done => { + up.authClient = { + request: (reqOpts: GaxiosOptions) => { + assert(reqOpts.signal instanceof AbortController); + done(); + }, + }; + up.makeRequestStream(REQ_OPTS); + }); + + it('should abort on an error', done => { + up.on('error', () => {}); + + let abortController: AbortController; + up.authClient = { + request: (reqOpts: GaxiosOptions) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + abortController = reqOpts.signal as any; + }, + }; + + up.makeRequestStream(REQ_OPTS); + up.emit('error', new Error('Error.')); + + setImmediate(() => { + assert.strictEqual(abortController.aborted, true); + done(); + }); + }); + + it('should set userProject', done => { + up.userProject = 'user-project'; + up.authClient = { + request: (reqOpts: GaxiosOptions) => { + assert.deepStrictEqual(reqOpts.params, {userProject: 'user-project'}); + done(); + }, + }; + up.makeRequestStream(REQ_OPTS); + }); + + it('should not remove existing params when userProject is set', done => { + REQ_OPTS.params = {a: 'b', c: 'd'}; + up.userProject = 'user-project'; + up.authClient = { + request: (reqOpts: GaxiosOptions) => { + assert.deepStrictEqual(reqOpts.params, { + userProject: 'user-project', + a: 'b', + c: 'd', + }); + done(); + }, + }; + up.makeRequestStream(REQ_OPTS); + }); + + it('should always validate the status', done => { + up.authClient = { + request: (reqOpts: GaxiosOptions) => { + assert.strictEqual(reqOpts.validateStatus!(0), true); + done(); + }, + }; + up.makeRequestStream(REQ_OPTS); + }); + + it('should combine customRequestOptions', done => { + const up = upload({ + bucket: BUCKET, + file: FILE, + retryOptions: RETRY_OPTIONS, + customRequestOptions: { + headers: { + 'X-My-Header': 'My custom value', + }, + }, + }); + mockAuthorizeRequest(); + up.authClient = { + request: (reqOpts: GaxiosOptions) => { + const customHeader = + reqOpts.headers && reqOpts.headers['X-My-Header']; + assert.strictEqual(customHeader, 'My custom value'); + setImmediate(done); + return {}; + }, + }; + up.makeRequestStream(REQ_OPTS); + }); + + it('should pass the response to the handler', done => { + const response = {}; + up.authClient = { + request: async () => response, + }; + up.onResponse = (res: GaxiosResponse) => { + assert.strictEqual(res, response); + done(); + }; + up.makeRequestStream(REQ_OPTS); + }); + + it('should return the response if successful', async () => { + const response = {some: 'response'}; + up.authClient = { + request: async () => response, + }; + up.onResponse = () => true; + + const stream = await up.makeRequestStream(REQ_OPTS); + assert.strictEqual(stream, response); + }); + + it('should return `null` if the response is unsuccessful', async () => { + const response = {some: 'response'}; + up.authClient = { + request: async () => response, + }; + up.onResponse = () => false; + + const stream = await up.makeRequestStream(REQ_OPTS); + assert.strictEqual(stream, null); + }); + }); + + describe('#onResponse', () => { + beforeEach(() => { + up.numRetries = 0; + up.startUploading = () => {}; + up.continueUploading = () => {}; + }); + + describe('500s', () => { + const RESP = {status: 500, data: 'error message from server'}; + + it('should increase the retry count if less than limit', () => { + up.getRetryDelay = () => 1; + assert.strictEqual(up.numRetries, 0); + assert.strictEqual(up.onResponse(RESP), false); + assert.strictEqual(up.numRetries, 1); + }); + + it('should destroy the stream if greater than limit', done => { + up.getRetryDelay = () => 1; + up.destroy = (err: Error) => { + assert.strictEqual( + err.message, + `Retry limit exceeded - ${JSON.stringify(RESP.data)}` + ); + done(); + }; + + up.onResponse(RESP); + up.onResponse(RESP); + up.onResponse(RESP); + up.onResponse(RESP); + }); + + describe('exponential back off', () => { + let clock: sinon.SinonFakeTimers; + let setTimeoutSpy: sinon.SinonSpy; + beforeEach(() => { + clock = sinon.useFakeTimers({toFake: ['setTimeout']}); + setTimeoutSpy = sinon.spy(global, 'setTimeout'); + }); + afterEach(() => { + clock.restore(); + }); + + it('should continue uploading after retry count^2 * random', done => { + up.continueUploading = function () { + assert.strictEqual(this, up); + + const minTime = Math.pow(2, up.numRetries - 1) * 1000; + const maxTime = minTime + 1000; + + const delay = setTimeoutSpy.lastCall.args[1]; + assert(delay >= minTime); + assert(delay <= maxTime); + + // make it keep retrying until the limit is reached + up.onResponse(RESP); + }; + + up.on('error', (err: Error) => { + assert.strictEqual(up.numRetries, 3); + assert.strictEqual( + err.message, + `Retry limit exceeded - ${JSON.stringify(RESP.data)}` + ); + done(); + }); + + up.onResponse(RESP); + clock.runAll(); + }); + }); + }); + + describe('all others', () => { + const RESP = {status: 200}; + + it('should emit the response on the stream', done => { + up.getRetryDelay = () => 1; + up.on('response', (resp: {}) => { + assert.strictEqual(resp, RESP); + done(); + }); + up.onResponse(RESP); + }); + + it('should return true', () => { + up.getRetryDelay = () => 1; + assert.strictEqual(up.onResponse(RESP), true); + }); + + it('should handle a custom status code when passed a retry function', () => { + up.getRetryDelay = () => 1; + const RESP = {status: 1000}; + const customHandlerFunction = (err: ApiError) => { + return err.code === 1000; + }; + up.retryOptions.retryableErrorFn = customHandlerFunction; + + assert.strictEqual(up.onResponse(RESP), false); + }); + }); + }); + + describe('#attemptDelayedRetry', () => { + beforeEach(() => { + up.startUploading = () => {}; + up.continueUploading = () => {}; + up.getRetryDelay = () => 1; + }); + + it('should increment numRetries', () => { + assert.equal(up.numRetries, 0); + + up.attemptDelayedRetry({}); + + assert.equal(up.numRetries, 1); + }); + + it('should call `startUploading` on 404 && !this.numChunksReadInRequest', done => { + up.startUploading = done; + up.continueUploading = () => done('wanted `startUploading`'); + + up.attemptDelayedRetry({status: 404}); + }); + + it('should not call `startUploading` when on 404 && this.numChunksReadInRequest != 0', done => { + up.startUploading = () => done('wanted `continueUploading`'); + up.continueUploading = done; + + up.numChunksReadInRequest = 1; + up.attemptDelayedRetry({status: 404}); + }); + + it('should not call `startUploading` when !this.numChunksReadInRequest && status != 404', done => { + up.startUploading = () => done('wanted `continueUploading`'); + up.continueUploading = done; + + up.attemptDelayedRetry({status: 400}); + }); + + it('should call `getRetryDelay` when not calling `startUploading`', done => { + up.startUploading = () => done('wanted `continueUploading`'); + up.getRetryDelay = () => { + process.nextTick(done); + return 1; + }; + + up.attemptDelayedRetry({}); + }); + + it('should unshift the write buffer, unset `offset`, and call `continueUploading` when not calling `startUploading`', done => { + up.startUploading = () => done('wanted `continueUploading`'); + up.continueUploading = () => { + assert.equal(up.numBytesWritten, 4); + assert.equal(up.localWriteCache.length, 0); + assert.equal( + Buffer.concat(up.writeBuffers).toString(), + 'a'.repeat(12) + 'b'.repeat(10) + ); + assert.equal(up.offset, undefined); + + done(); + }; + + up.numBytesWritten = 16; + up.localWriteCache = [Buffer.alloc(12, 'a')]; + up.localWriteCacheByteLength = up.localWriteCache[0].byteLength; + up.writeBuffers = [Buffer.alloc(10, 'b')]; + up.offset = 16; + + up.attemptDelayedRetry({}); + }); + + it('should destroy if retry total time limit exceeded (0)', done => { + up.getRetryDelay = () => 0; + up.on('error', (error: Error) => { + assert(error.message.match(/Retry total time limit exceeded/)); + done(); + }); + + up.attemptDelayedRetry({}); + }); + + it('should destroy if retry total time limit exceeded (< 0)', done => { + up.getRetryDelay = () => -123; + up.on('error', (error: Error) => { + assert(error.message.match(/Retry total time limit exceeded/)); + done(); + }); + + up.attemptDelayedRetry({}); + }); + + it('should destroy the object if this.numRetries > this.retryLimit', done => { + up.startUploading = () => done("shouldn't have called this"); + up.continueUploading = () => done("shouldn't have called this"); + up.getRetryDelay = () => done("shouldn't have called this"); + + up.on('error', (error: Error) => { + assert(error.message.match(/Retry limit exceeded/)); + done(); + }); + + up.numRetries = 4; + up.retryLimit = 3; + + up.attemptDelayedRetry({}); + }); + + it('should destroy the object if this.numRetries === this.retryLimit', done => { + up.startUploading = () => done("shouldn't have called this"); + up.continueUploading = () => done("shouldn't have called this"); + up.getRetryDelay = () => done("shouldn't have called this"); + + up.on('error', (error: Error) => { + assert(error.message.match(/Retry limit exceeded/)); + done(); + }); + + up.numRetries = 3; + up.retryLimit = 3; + + up.attemptDelayedRetry({}); + }); + }); + + describe('PROTOCOL_REGEX', () => { + it('should match a protocol', () => { + const urls = [ + {input: 'http://www.hi.com', match: 'http'}, + {input: 'mysite://www.hi.com', match: 'mysite'}, + {input: 'www.hi.com', match: null}, + ]; + + for (const url of urls) { + assert.strictEqual( + url.input.match(PROTOCOL_REGEX) && + url.input.match(PROTOCOL_REGEX)![1], + url.match + ); + } + }); + }); + + describe('#sanitizeEndpoint', () => { + const USER_DEFINED_SHORT_API_ENDPOINT = 'myapi.com:8080'; + const USER_DEFINED_PROTOCOL = 'myproto'; + const USER_DEFINED_FULL_API_ENDPOINT = `${USER_DEFINED_PROTOCOL}://myapi.com:8080`; + + it('should default protocol to https', () => { + const endpoint = up.sanitizeEndpoint(USER_DEFINED_SHORT_API_ENDPOINT); + assert.strictEqual(endpoint.match(PROTOCOL_REGEX)![1], 'https'); + }); + + it('should not override protocol', () => { + const endpoint = up.sanitizeEndpoint(USER_DEFINED_FULL_API_ENDPOINT); + assert.strictEqual( + endpoint.match(PROTOCOL_REGEX)![1], + USER_DEFINED_PROTOCOL + ); + }); + + it('should remove trailing slashes from URL', () => { + const endpointsWithTrailingSlashes = [ + `${USER_DEFINED_FULL_API_ENDPOINT}/`, + `${USER_DEFINED_FULL_API_ENDPOINT}//`, + ]; + for (const endpointWithTrailingSlashes of endpointsWithTrailingSlashes) { + const endpoint = up.sanitizeEndpoint(endpointWithTrailingSlashes); + assert.strictEqual(endpoint.endsWith('/'), false); + } + }); + }); + + describe('#getRetryDelay', () => { + beforeEach(() => { + up.timeOfFirstRequest = Date.now(); + }); + + it('should return exponential retry delay', () => { + const min = Math.pow(up.retryDelayMultiplier, up.numRetries) * 1000; + const max = + Math.pow(up.retryDelayMultiplier, up.numRetries) * 1000 + 1000; + const delayValue = up.getRetryDelay(); + + assert(delayValue >= min && delayValue <= max); + }); + + it('allows overriding the delay multiplier', () => { + [1, 2, 3].forEach(delayMultiplier => { + up.retryDelayMultiplier = delayMultiplier; + const min = Math.pow(up.retryDelayMultiplier, up.numRetries) * 1000; + const max = + Math.pow(up.retryDelayMultiplier, up.numRetries) * 1000 + 1000; + const delayValue = up.getRetryDelay(); + + assert(delayValue >= min && delayValue <= max); + }); + }); + + it('allows overriding the number of retries', () => { + [1, 2, 3].forEach(numRetry => { + up.retryOptions.maxRetries = numRetry; + const min = Math.pow(up.retryDelayMultiplier, up.numRetries) * 1000; + const max = + Math.pow(up.retryDelayMultiplier, up.numRetries) * 1000 + 1000; + const delayValue = up.getRetryDelay(); + + assert(delayValue >= min && delayValue <= max); + }); + }); + + it('returns the value of totaltimeout when calculated values are larger', () => { + up.retryOptions.totalTimeout = 1; + const delayValue = up.getRetryDelay(); + + // This is a timing-based test, there could be a few milliseconds of lag + assert(delayValue <= 1000 && delayValue >= 995); + }); + }); + + describe('upload', () => { + describe('single chunk', () => { + let uri = ''; + + beforeEach(() => { + uri = 'uri'; + + up.contentLength = CHUNK_SIZE_MULTIPLE * 8; + up.createURI = ( + callback: (error: Error | null, uri: string) => void + ) => { + up.uri = uri; + up.offset = 0; + callback(null, uri); + }; + }); + + it('should make the correct request', done => { + // For additional information: + // - https://cloud.google.com/storage/docs/performing-resumable-uploads#single-chunk-upload + + const CHUNK_SIZE = CHUNK_SIZE_MULTIPLE * 2; + const NON_CHUNK_SIZE_DIVISIBLE_AMOUNT = 2; + const CONTENT_LENGTH = CHUNK_SIZE * 8 + NON_CHUNK_SIZE_DIVISIBLE_AMOUNT; + const EXPECTED_NUM_REQUESTS = 1; + + // We want the class to be able to handle varying chunk sizes uniformly. + let wrote = 0; + let wroteChunkLargerThanChunkSize = false; + let wroteChunkEqualToChunkSize = false; + let wroteChunkLessThanChunkSize = false; + + const upstreamBuffer = new Readable({ + read() { + const remainingToWrite = CONTENT_LENGTH - wrote; + + if (!remainingToWrite) { + // signal finish + this.push(null); + } else if (remainingToWrite > CHUNK_SIZE * 3) { + // write large chunk + const LARGE_CHUNK = Buffer.alloc(CHUNK_SIZE * 2); + + wrote += LARGE_CHUNK.byteLength; + wroteChunkLargerThanChunkSize = true; + + this.push(LARGE_CHUNK); + } else if (remainingToWrite > CHUNK_SIZE) { + // write chunk-sized chunk + const EQUAL_CHUNK = Buffer.alloc(CHUNK_SIZE); + + wrote += EQUAL_CHUNK.byteLength; + wroteChunkEqualToChunkSize = true; + + this.push(EQUAL_CHUNK); + } else { + // write small chunk + const SMALL_CHUNK = Buffer.alloc(remainingToWrite); + + wrote += SMALL_CHUNK.byteLength; + wroteChunkLessThanChunkSize = true; + + this.push(SMALL_CHUNK); + } + }, + }); + + const requests: { + dataReceived: number; + opts: GaxiosOptions; + chunkWritesInRequest: number; + }[] = []; + let overallDataReceived = 0; + + up.contentLength = CONTENT_LENGTH; + + up.makeRequestStream = async (opts: GaxiosOptions) => { + let dataReceived = 0; + let chunkWritesInRequest = 0; + + const res = await new Promise(resolve => { + opts.body.on('data', (data: Buffer) => { + dataReceived += data.byteLength; + overallDataReceived += data.byteLength; + chunkWritesInRequest++; + }); + + opts.body.on('end', () => { + requests.push({dataReceived, opts, chunkWritesInRequest}); + + resolve({ + status: 200, + data: {}, + }); + + resolve(null); + }); + }); + + return res; + }; + + up.on('error', done); + + up.on('finish', () => { + // Ensure the correct number of requests and data look correct + assert.equal(requests.length, EXPECTED_NUM_REQUESTS); + assert.equal(overallDataReceived, CONTENT_LENGTH); + + // Make sure we wrote the desire mix of chunk sizes + assert(wroteChunkLargerThanChunkSize); + assert(wroteChunkEqualToChunkSize); + assert(wroteChunkLessThanChunkSize); + + // Validate the single request + const request = requests[0]; + + assert.strictEqual(request.opts.method, 'PUT'); + assert.strictEqual(request.opts.url, uri); + + // We should be writing multiple buffers down the wire + assert(request.chunkWritesInRequest > 1); + + assert.equal(request.dataReceived, CONTENT_LENGTH); + assert(request.opts.headers); + assert.equal( + request.opts.headers['Content-Range'], + `bytes 0-*/${CONTENT_LENGTH}` + ); + assert.ok( + X_GOOG_API_HEADER_REGEX.test( + request.opts.headers['x-goog-api-client'] + ) + ); + assert.ok(USER_AGENT_REGEX.test(request.opts.headers['User-Agent'])); + + done(); + }); + + // init the request + upstreamBuffer.pipe(up); + }); + }); + + describe('multiple chunk', () => { + let uri = ''; + + beforeEach(() => { + uri = 'uri'; + + up.chunkSize = CHUNK_SIZE_MULTIPLE; + up.contentLength = CHUNK_SIZE_MULTIPLE * 8; + up.createURI = ( + callback: (error: Error | null, uri: string) => void + ) => { + up.uri = uri; + up.offset = 0; + callback(null, uri); + }; + }); + + it('should make the correct requests', done => { + // For additional information: + // - https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload + // - https://cloud.google.com/storage/docs/resumable-uploads#resent-data + + const CHUNK_SIZE = CHUNK_SIZE_MULTIPLE * 2; + // This is important - we want to make sure requests + // where `CONTENT_LENGTH % CHUNK_SIZE !== 0` are fine. + const LAST_REQUEST_SIZE = 2; + const CONTENT_LENGTH = CHUNK_SIZE * 8 + LAST_REQUEST_SIZE; + const EXPECTED_NUM_REQUESTS = + Math.floor(CONTENT_LENGTH / CHUNK_SIZE) + 1; + + // We want the class to be able to handle varying chunk sizes uniformly. + let wrote = 0; + let wroteChunkLargerThanChunkSize = false; + let wroteChunkEqualToChunkSize = false; + let wroteChunkLessThanChunkSize = false; + + const upstreamBuffer = new Readable({ + read() { + const remainingToWrite = CONTENT_LENGTH - wrote; + + if (!remainingToWrite) { + // signal finish + this.push(null); + } else if (remainingToWrite > CHUNK_SIZE * 3) { + // write large chunk + const LARGE_CHUNK = Buffer.alloc(CHUNK_SIZE * 2); + + wrote += LARGE_CHUNK.byteLength; + wroteChunkLargerThanChunkSize = true; + + this.push(LARGE_CHUNK); + } else if (remainingToWrite > CHUNK_SIZE) { + // write chunk-sized chunk + const EQUAL_CHUNK = Buffer.alloc(CHUNK_SIZE); + + wrote += EQUAL_CHUNK.byteLength; + wroteChunkEqualToChunkSize = true; + + this.push(EQUAL_CHUNK); + } else { + // write small chunk + const SMALL_CHUNK = Buffer.alloc(remainingToWrite); + + wrote += SMALL_CHUNK.byteLength; + wroteChunkLessThanChunkSize = true; + + this.push(SMALL_CHUNK); + } + }, + }); + + const requests: { + dataReceived: number; + opts: GaxiosOptions; + chunkWritesInRequest: number; + }[] = []; + let overallDataReceived = 0; + + up.chunkSize = CHUNK_SIZE; + up.contentLength = CONTENT_LENGTH; + + up.makeRequestStream = async (opts: GaxiosOptions) => { + let dataReceived = 0; + let chunkWritesInRequest = 0; + + const res = await new Promise(resolve => { + opts.body.on('data', (data: Buffer) => { + dataReceived += data.byteLength; + overallDataReceived += data.byteLength; + chunkWritesInRequest++; + }); + + opts.body.on('end', () => { + requests.push({dataReceived, opts, chunkWritesInRequest}); + + if (overallDataReceived < CONTENT_LENGTH) { + const lastByteReceived = overallDataReceived + ? overallDataReceived - 1 + : 0; + + resolve({ + status: RESUMABLE_INCOMPLETE_STATUS_CODE, + headers: { + range: `bytes=0-${lastByteReceived}`, + }, + data: {}, + }); + } else { + resolve({ + status: 200, + data: {}, + }); + } + }); + }); + + return res; + }; + + up.on('error', done); + + up.on('finish', () => { + // Ensure the correct number of requests and data look correct + assert.equal(requests.length, EXPECTED_NUM_REQUESTS); + assert.equal(overallDataReceived, CONTENT_LENGTH); + + // Make sure we wrote the desire mix of chunk sizes + assert(wroteChunkLargerThanChunkSize); + assert(wroteChunkEqualToChunkSize); + assert(wroteChunkLessThanChunkSize); + + // Validate each request + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + const offset = i * CHUNK_SIZE; + + assert.strictEqual(request.opts.method, 'PUT'); + assert.strictEqual(request.opts.url, uri); + + // We should be writing N buffers down the wire, although + // the request is "1 chunk" + assert(request.chunkWritesInRequest >= 1); + + if (requests.length - i === 1) { + // The last chunk + const endByte = offset + LAST_REQUEST_SIZE - 1; + + assert.equal(request.dataReceived, LAST_REQUEST_SIZE); + assert(request.opts.headers); + assert.equal( + request.opts.headers['Content-Length'], + LAST_REQUEST_SIZE + ); + assert.equal( + request.opts.headers['Content-Range'], + `bytes ${offset}-${endByte}/${CONTENT_LENGTH}` + ); + assert.ok( + X_GOOG_API_HEADER_REGEX.test( + request.opts.headers['x-goog-api-client'] + ) + ); + assert.ok( + USER_AGENT_REGEX.test(request.opts.headers['User-Agent']) + ); + } else { + // The preceding chunks + const endByte = offset + CHUNK_SIZE - 1; + + assert.equal(request.dataReceived, CHUNK_SIZE); + assert(request.opts.headers); + assert.equal(request.opts.headers['Content-Length'], CHUNK_SIZE); + assert.equal( + request.opts.headers['Content-Range'], + `bytes ${offset}-${endByte}/${CONTENT_LENGTH}` + ); + assert.ok( + X_GOOG_API_HEADER_REGEX.test( + request.opts.headers['x-goog-api-client'] + ) + ); + assert.ok( + USER_AGENT_REGEX.test(request.opts.headers['User-Agent']) + ); + } + } + + done(); + }); + + // init the request + upstreamBuffer.pipe(up); + }); + }); + + describe('empty object', () => { + let uri = ''; + + beforeEach(() => { + uri = 'uri'; + + up.contentLength = 0; + up.createURI = ( + callback: (error: Error | null, uri: string) => void + ) => { + up.uri = uri; + up.offset = 0; + callback(null, uri); + }; + }); + + it('should support uploading empty objects', done => { + const CONTENT_LENGTH = 0; + const EXPECTED_NUM_REQUESTS = 1; + + const upstreamBuffer = new Readable({ + read() { + this.push(null); + }, + }); + + const requests: { + dataReceived: number; + opts: GaxiosOptions; + chunkWritesInRequest: number; + }[] = []; + let overallDataReceived = 0; + + up.makeRequestStream = async (opts: GaxiosOptions) => { + let dataReceived = 0; + let chunkWritesInRequest = 0; + + const res = await new Promise(resolve => { + opts.body.on('data', (data: Buffer) => { + dataReceived += data.byteLength; + overallDataReceived += data.byteLength; + chunkWritesInRequest++; + }); + + opts.body.on('end', () => { + requests.push({dataReceived, opts, chunkWritesInRequest}); + + resolve({ + status: 200, + data: {}, + }); + + resolve(null); + }); + }); + + return res; + }; + + up.on('error', done); + + up.on('finish', () => { + // Ensure the correct number of requests and data look correct + assert.equal(requests.length, EXPECTED_NUM_REQUESTS); + assert.equal(overallDataReceived, CONTENT_LENGTH); + + // Validate the single request + const request = requests[0]; + + assert.strictEqual(request.opts.method, 'PUT'); + assert.strictEqual(request.opts.url, uri); + + // No data should be written + assert(request.chunkWritesInRequest === 0); + + assert.equal(request.dataReceived, CONTENT_LENGTH); + assert(request.opts.headers); + + assert.equal( + request.opts.headers['Content-Range'], + `bytes 0-*/${CONTENT_LENGTH}` + ); + assert.ok( + X_GOOG_API_HEADER_REGEX.test( + request.opts.headers['x-goog-api-client'] + ) + ); + assert.ok(USER_AGENT_REGEX.test(request.opts.headers['User-Agent'])); + + done(); + }); + + // init the request + upstreamBuffer.pipe(up); + }); + }); + }); + + describe('Validation of Client Checksums Against Server Response', () => { + const DUMMY_CONTENT = Buffer.alloc(CHUNK_SIZE_MULTIPLE * 2); + let URI = ''; + beforeEach(() => { + up.contentLength = DUMMY_CONTENT.byteLength; + URI = 'uri'; + up.createURI = (callback: (error: Error | null, uri: string) => void) => { + up.uri = URI; + up.offset = 0; + callback(null, URI); + }; + }); + const checksumScenarios = [ + { + type: 'CRC32C', + match: true, + desc: 'successfully finish the upload if server-reported CRC32C matches client CRC32C', + serverCrc: CORRECT_CLIENT_CRC32C, + serverMd5: CORRECT_CLIENT_MD5, + }, + { + type: 'CRC32C', + match: false, + desc: 'fail and destroy the stream if server-reported CRC32C mismatches client CRC32C', + serverCrc: INCORRECT_SERVER_CRC32C, + serverMd5: CORRECT_CLIENT_MD5, + errorPart: 'CRC32C checksum mismatch.', + }, + { + type: 'MD5', + match: true, + desc: 'successfully finish the upload if server-reported MD5 matches client MD5', + serverCrc: CORRECT_CLIENT_CRC32C, + serverMd5: CORRECT_CLIENT_MD5, + }, + { + type: 'MD5', + match: false, + desc: 'fail and destroy the stream if server-reported MD5 mismatches client MD5', + serverCrc: CORRECT_CLIENT_CRC32C, + serverMd5: INCORRECT_SERVER_MD5, + errorPart: 'MD5 checksum mismatch.', + }, + ]; + + checksumScenarios.forEach(scenario => { + it(`should ${scenario.desc}`, done => { + up.makeRequestStream = async (opts: GaxiosOptions) => { + await new Promise(resolve => { + opts.body.on('data', () => {}); + opts.body.on('end', resolve); + }); + + return { + status: 200, + data: { + crc32c: scenario.serverCrc, + md5Hash: scenario.serverMd5, + name: up.file, + bucket: up.bucket, + size: DUMMY_CONTENT.byteLength.toString(), + }, + headers: {}, + config: opts, + statusText: 'OK', + }; + }; + + if (scenario.match) { + up.on('error', (err: Error) => { + done(new Error(`Upload failed unexpectedly: ${err.message}`)); + }); + up.on('finish', () => { + done(); + }); + } else { + up.on('error', (err: Error) => { + assert.strictEqual( + err.message, + FileExceptionMessages.UPLOAD_MISMATCH + ); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const detailError = (err as any).errors && (err as any).errors[0]; + assert.ok( + detailError && detailError.message.includes(scenario.errorPart!), + `Error message should contain: ${scenario.errorPart}` + ); + assert.strictEqual(up.uri, URI); + done(); + }); + + up.on('finish', () => { + done( + new Error( + `Upload should have failed due to ${scenario.type} mismatch, but emitted finish.` + ) + ); + }); + } + + const upstreamBuffer = new Readable({ + read() { + this.push(DUMMY_CONTENT); + this.push(null); + }, + }); + upstreamBuffer.pipe(up); + }); + }); + }); +}); diff --git a/handwritten/storage/test/signer.ts b/handwritten/storage/test/signer.ts new file mode 100644 index 00000000000..6e840ac6759 --- /dev/null +++ b/handwritten/storage/test/signer.ts @@ -0,0 +1,1074 @@ +// Copyright 2020 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 assert from 'assert'; +import * as crypto from 'crypto'; +import * as sinon from 'sinon'; +import {describe, it, beforeEach, afterEach} from 'mocha'; + +import { + URLSigner, + SigningError, + AuthClient, + BucketI, + FileI, + SignerGetSignedUrlConfig, + PATH_STYLED_HOST, + GetSignedUrlConfigInternal, + Query, + SignerExceptionMessages, +} from '../src/signer.js'; +import {encodeURI, formatAsUTCISO, qsStringify} from '../src/util.js'; +import {ExceptionMessages, Storage} from '../src/storage.js'; +import {OutgoingHttpHeaders} from 'http'; +import {GoogleAuth} from 'google-auth-library'; + +interface SignedUrlArgs { + bucket: string; + method: 'GET' | 'POST' | 'PUT' | 'DELETE'; + contentMd5?: string; + contentType?: string; + extensionHeaders?: OutgoingHttpHeaders; + expiration?: number; + file: string; +} + +describe('signer', () => { + const BUCKET_NAME = 'bucket-name'; + const FILE_NAME = 'file-name.png'; + const CLIENT_EMAIL = 'client-email'; + + let sandbox: sinon.SinonSandbox; + beforeEach(() => (sandbox = sinon.createSandbox())); + afterEach(() => sandbox.restore()); + + describe('URLSigner', () => { + let authClient: GoogleAuth | AuthClient; + let bucket: BucketI; + let file: FileI; + + const NOW = new Date('2019-03-18T00:00:00.999Z'); + let fakeTimers: sinon.SinonFakeTimers; + + beforeEach(() => (fakeTimers = sinon.useFakeTimers(NOW))); + afterEach(() => fakeTimers.restore()); + + beforeEach(() => { + authClient = { + sign: async () => 'signature', + getCredentials: async () => ({client_email: CLIENT_EMAIL}), + }; + bucket = {name: BUCKET_NAME}; + file = {name: FILE_NAME}; + }); + + describe('URLSigner constructor', () => { + let signer: URLSigner; + beforeEach(() => { + signer = new URLSigner(authClient, bucket, file); + }); + + it('should localize authClient', () => { + assert.strictEqual(signer['auth'], authClient); + }); + + it('should localize bucket', () => { + assert.strictEqual(signer['bucket'], bucket); + }); + + it('should localize file', () => { + assert.strictEqual(signer['file'], file); + }); + }); + + describe('getSignedUrl', () => { + let signer: URLSigner; + let storage: Storage; + let CONFIG: SignerGetSignedUrlConfig; + + beforeEach(() => { + storage = new Storage(); + signer = new URLSigner(authClient, bucket, file, storage); + + CONFIG = { + method: 'GET', + expires: new Date().valueOf() + 2000, + }; + }); + + describe('version', () => { + it('should default to v2 if version is not given', async () => { + const v2 = sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(signer, 'getSignedUrlV2') + .resolves({}); + + await signer.getSignedUrl(CONFIG); + assert(v2.calledOnce); + }); + + it('should use v2 if set', async () => { + CONFIG = { + version: 'v2', + contentMd5: 'md5', + contentType: 'application/json', + extensionHeaders: { + key: 'value', + }, + ...CONFIG, + }; + const v2 = sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(signer, 'getSignedUrlV2') + .resolves({}); + + await signer.getSignedUrl(CONFIG); + assert(v2.calledOnce); + const v2arg = v2.getCall(0).args[0] as SignedUrlArgs; + assert.strictEqual(v2arg.bucket, bucket.name); + assert.strictEqual(v2arg.method, CONFIG.method); + assert.strictEqual(v2arg.contentMd5, CONFIG.contentMd5); + assert.strictEqual(v2arg.contentType, CONFIG.contentType); + assert.deepStrictEqual( + v2arg.extensionHeaders, + CONFIG.extensionHeaders + ); + }); + + it('should use v4 if set', async () => { + CONFIG = { + version: 'v4', + contentMd5: 'md5', + contentType: 'application/json', + extensionHeaders: { + key: 'value', + }, + ...CONFIG, + }; + const v4 = sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(signer, 'getSignedUrlV4') + .resolves({}); + + await signer.getSignedUrl(CONFIG); + assert(v4.calledOnce); + const v4arg = v4.getCall(0).args[0] as SignedUrlArgs; + assert.strictEqual(v4arg.bucket, bucket.name); + assert.strictEqual(v4arg.method, CONFIG.method); + assert.strictEqual(v4arg.contentMd5, CONFIG.contentMd5); + assert.strictEqual(v4arg.contentType, CONFIG.contentType); + assert.deepStrictEqual( + v4arg.extensionHeaders, + CONFIG.extensionHeaders + ); + }); + + it('should error for an invalid version', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + CONFIG.version = 'v42' as any; + + assert.throws( + () => signer.getSignedUrl(CONFIG), + /Invalid signed URL version: v42\. Supported versions are 'v2' and 'v4'\./ + ); + }); + }); + + describe('accessibleAt', () => { + const accessibleAtNumber = 1581984000000; //2020-02-17T16:00:00-08:00 + const expiresNumber = accessibleAtNumber + 86400000; //2020-02-18T16:00:00-08:00 + + it('should set correct settings if accessibleAt provided', async () => { + const authClientSign = sandbox + .stub(authClient, 'sign') + .resolves('signature'); + const accessibleAt = new Date(accessibleAtNumber); + await signer.getSignedUrl({ + version: 'v4', + method: 'GET', + accessibleAt, + expires: expiresNumber, + }); + const blobToSign = authClientSign.getCall(0).args[0]; + assert(blobToSign.includes(formatAsUTCISO(accessibleAt, true))); + }); + + it('should throw if an expiration date from the before accessibleAt date is given', () => { + const accessibleAt = accessibleAtNumber; + const expires = accessibleAt - 86400000; + + assert.throws(() => { + signer.getSignedUrl({ + version: 'v4', + method: 'GET', + accessibleAt, + expires, + }), + SignerExceptionMessages.EXPIRATION_BEFORE_ACCESSIBLE_DATE; + }); + }); + + describe('checkInputTypes', () => { + const query = { + 'X-Goog-Date': formatAsUTCISO(new Date(accessibleAtNumber), true), + }; + + it('should accept Date objects', async () => { + const accessibleAt = new Date(accessibleAtNumber); + const signedUrl = await signer.getSignedUrl({ + version: 'v4', + method: 'GET', + accessibleAt, + expires: expiresNumber, + }); + assert(signedUrl.includes(qsStringify(query))); + }); + + it('should accept numbers', async () => { + const accessibleAt = accessibleAtNumber; + const signedUrl = await signer.getSignedUrl({ + version: 'v4', + method: 'GET', + accessibleAt, + expires: expiresNumber, + }); + assert(signedUrl.includes(qsStringify(query))); + }); + + it('should accept strings', async () => { + const accessibleAt = '2020-02-17T16:00:00-08:00'; + const signedUrl = await signer.getSignedUrl({ + version: 'v4', + method: 'GET', + accessibleAt, + expires: expiresNumber, + }); + assert(signedUrl.includes(qsStringify(query))); + }); + + it('should throw if a date is invalid', () => { + const accessibleAt = new Date('31-12-2019'); + + assert.throws(() => { + signer.getSignedUrl({ + version: 'v4', + method: 'GET', + accessibleAt, + expires: expiresNumber, + }), + SignerExceptionMessages.ACCESSIBLE_DATE_INVALID; + }); + }); + }); + }); + + describe('expires', () => { + it('should parse Date object into expiration seconds', async () => { + const parseExpires = sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .spy(signer, 'parseExpires'); + + const v2 = sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(signer, 'getSignedUrlV2') + .resolves({}); + + await signer.getSignedUrl(CONFIG); + assert(parseExpires.calledOnceWith(CONFIG.expires)); + const expiresInSeconds = parseExpires.getCall(0).lastArg; + + assert( + (v2.getCall(0).args[0] as SignedUrlArgs).expiration, + expiresInSeconds + ); + }); + }); + + describe('URL style', () => { + let v2: sinon.SinonStub; + beforeEach(() => { + v2 = sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(signer, 'getSignedUrlV2') + .resolves({}); + }); + + it('should pass cname', async () => { + CONFIG.cname = 'http://www.example.com'; + + const url = await signer.getSignedUrl(CONFIG); + const v2arg = v2.getCall(0).args[0]; + assert.strictEqual(v2arg.cname, CONFIG.cname); + assert(url.startsWith(CONFIG.cname)); + }); + + it('should pass virtual host to cname', async () => { + CONFIG.virtualHostedStyle = true; + const expectedCname = `https://${bucket.name}.storage.googleapis.com`; + + await signer.getSignedUrl(CONFIG); + const v2arg = v2.getCall(0).args[0]; + assert.strictEqual(v2arg.cname, expectedCname); + }); + + it('should use a universe domain with the virtual host', async () => { + storage.universeDomain = 'my-universe.com'; + + CONFIG.virtualHostedStyle = true; + const expectedCname = `https://${bucket.name}.storage.my-universe.com`; + + await signer.getSignedUrl(CONFIG); + const v2arg = v2.getCall(0).args[0]; + assert.strictEqual(v2arg.cname, expectedCname); + }); + + it('should take precedence in cname if both passed', async () => { + CONFIG = { + virtualHostedStyle: true, + cname: 'http://www.example.com', + ...CONFIG, + }; + + await signer.getSignedUrl(CONFIG); + const v2arg = v2.getCall(0).args[0]; + assert.strictEqual(v2arg.cname, CONFIG.cname); + }); + + it('should not pass cname parameter', async () => { + CONFIG = { + virtualHostedStyle: false, + cname: undefined, + ...CONFIG, + }; + + await signer.getSignedUrl(CONFIG); + const v2arg = v2.getCall(0).args[0]; + assert.strictEqual(v2arg.cname, undefined); + }); + }); + + describe('composing signed URL', () => { + const query = { + GoogleAccessId: CLIENT_EMAIL, + Expires: NOW.valueOf() + 2000, + Signature: 'signature', + }; + + beforeEach(() => { + sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(signer, 'getSignedUrlV2') + .resolves(query) as sinon.SinonStub; + }); + + it('should insert user-provided queryParams', async () => { + CONFIG.queryParams = {key: 'AZ!*()*%/f'}; + + const url = await signer.getSignedUrl(CONFIG); + assert( + url.includes( + qsStringify({ + ...query, + ...CONFIG.queryParams, + }) + ) + ); + }); + }); + + it('should URI encode file name with special characters', async () => { + file.name = "special/azAZ!*'()*%/file.jpg"; + const encoded = encodeURI(file.name, false); + const signedUrl = await signer.getSignedUrl(CONFIG); + + const v2 = sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(signer, 'getSignedUrlV2') + .resolves({}); + + await signer.getSignedUrl(CONFIG); + const v2arg = v2.getCall(0).args[0] as SignedUrlArgs; + assert.strictEqual(v2arg.file, encoded); + assert(signedUrl.includes(encoded)); + }); + + it('should generate URL with given cname', async () => { + CONFIG.cname = 'http://www.example.com'; + const signedUrl = await signer.getSignedUrl(CONFIG); + assert(signedUrl.startsWith(CONFIG.cname)); + }); + + it('should remove trailing slashes from cname', async () => { + CONFIG.cname = 'http://www.example.com//'; + const signedUrl = await signer.getSignedUrl(CONFIG); + assert(signedUrl.startsWith(`http://www.example.com/${file.name}`)); + }); + + it('should generate virtual hosted style URL', async () => { + CONFIG.virtualHostedStyle = true; + const signedUrl = await signer.getSignedUrl(CONFIG); + assert( + signedUrl.startsWith( + `https://${bucket.name}.storage.googleapis.com/${file.name}` + ) + ); + }); + + it('should generate path styled URL', async () => { + CONFIG.virtualHostedStyle = false; + const signedUrl = await signer.getSignedUrl(CONFIG); + assert(signedUrl.startsWith(PATH_STYLED_HOST)); + }); + + it('should generate URL with returned query params appended', async () => { + const query = { + 'X-Goog-Foo': 'value', + 'X-Goog-Bar': 'azAZ!*()*%', + }; + sandbox + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .stub(signer, 'getSignedUrlV2') + .resolves(query); + + const signedUrl = await signer.getSignedUrl(CONFIG); + assert(signedUrl.includes(qsStringify(query))); + }); + }); + + describe('getSignedUrlV2', () => { + let signer: URLSigner; + let CONFIG: GetSignedUrlConfigInternal; + + beforeEach(() => { + signer = new URLSigner(authClient, bucket, file); + CONFIG = { + method: 'GET', + expiration: Math.floor((NOW.valueOf() + 2000) / 1000), + bucket: bucket.name, + file: file.name, + }; + }); + + describe('blobToSign', () => { + let authClientSign: sinon.SinonStub; + beforeEach(() => { + authClientSign = sandbox + .stub(authClient, 'sign') + .resolves('signature'); + }); + + it('should sign method', async () => { + await signer['getSignedUrlV2'](CONFIG); + + const blobToSign = authClientSign.getCall(0).args[0]; + assert(blobToSign.startsWith('GET')); + }); + + it('should sign using the `signingEndpoint` when provided', async () => { + const signingEndpoint = 'https://my-endpoint.com'; + + CONFIG = { + ...CONFIG, + signingEndpoint, + }; + + await signer['getSignedUrlV2'](CONFIG); + + const endpoint = authClientSign.getCall(0).args[1]; + assert.equal(endpoint, signingEndpoint); + }); + + it('should sign contentMd5 if given', async () => { + CONFIG.contentMd5 = 'md5-hash'; + + await signer['getSignedUrlV2'](CONFIG); + + const blobToSign = authClientSign.getCall(0).args[0]; + assert(blobToSign.includes(CONFIG.contentMd5)); + }); + + it('should sign contentType if given', async () => { + CONFIG.contentType = 'application/octet-stream'; + + await signer['getSignedUrlV2'](CONFIG); + + const blobToSign = authClientSign.getCall(0).args[0]; + assert(blobToSign.includes(CONFIG.contentType)); + }); + + it('should sign expiration', async () => { + await signer['getSignedUrlV2'](CONFIG); + + const blobToSign = authClientSign.getCall(0).args[0]; + assert(blobToSign.includes(CONFIG.expiration.toString(10))); + }); + + it('should sign canonical headers', async () => { + sandbox + .stub(signer, 'getCanonicalHeaders') + .returns('canonical-headers'); + await signer['getSignedUrlV2'](CONFIG); + + const blobToSign = authClientSign.getCall(0).args[0]; + assert(blobToSign.includes('canonical-headers')); + }); + + it('should sign resource path', async () => { + sandbox.stub(signer, 'getResourcePath').returns('/resource/path'); + await signer['getSignedUrlV2'](CONFIG); + + const blobToSign = authClientSign.getCall(0).args[0]; + assert(blobToSign.endsWith('/resource/path')); + }); + + it('should compose blobToSign without contentMd5 and contentType', async () => { + sandbox + .stub(signer, 'getCanonicalHeaders') + .returns('canonical-headers'); + sandbox.stub(signer, 'getResourcePath').returns('/resource/path'); + await signer['getSignedUrlV2'](CONFIG); + + const blobToSign = authClientSign.getCall(0).args[0]; + assert.strictEqual( + blobToSign, + [ + 'GET', + '', + '', + CONFIG.expiration, + 'canonical-headers' + '/resource/path', + ].join('\n') + ); + }); + }); + + it('should return v2 query', async () => { + const query = (await signer['getSignedUrlV2'](CONFIG)) as Query; + assert.deepStrictEqual(query, { + GoogleAccessId: CLIENT_EMAIL, + Expires: CONFIG.expiration, + Signature: 'signature', + }); + }); + + it('rejects with SigningError on signing Error', () => { + const err = new Error('my-err'); + err.stack = 'some-stack-trace'; + sandbox.stub(authClient, 'sign').rejects(err); + + assert.rejects(() => signer['getSignedUrlV2'](CONFIG), { + name: 'SigningError', + message: 'my-err', + stack: 'some-stack-trace', + }); + }); + }); + + describe('getSignedUrlV4', () => { + let signer: URLSigner; + let CONFIG: GetSignedUrlConfigInternal; + + beforeEach(() => { + signer = new URLSigner(authClient, bucket, file); + CONFIG = { + method: 'GET', + expiration: (NOW.valueOf() + 2000) / 1000, + bucket: bucket.name, + }; + }); + + it('should fail for expirations beyond 7 days', () => { + CONFIG.expiration = NOW.valueOf() + 7.1 * 24 * 60 * 60; + const SEVEN_DAYS = 7 * 24 * 60 * 60; + + assert.throws( + () => { + signer['getSignedUrlV4'](CONFIG); + }, + { + message: `Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`, + } + ); + }); + + it('should not throw with expiration of exactly 7 days', async () => { + const ACCESSIBLE_AT = NOW.valueOf(); + const SEVEN_DAYS_IN_SECONDS = 7 * 24 * 60 * 60; + const SEVEN_DAYS_IN_MS = SEVEN_DAYS_IN_SECONDS * 1000; + await assert.doesNotReject( + async () => { + await signer.getSignedUrl({ + method: 'GET', + expires: ACCESSIBLE_AT + SEVEN_DAYS_IN_MS, + accessibleAt: ACCESSIBLE_AT, + version: 'v4', + }); + }, + err => { + assert(err instanceof Error); + assert.strictEqual( + err.message, + `Max allowed expiration is seven days (${SEVEN_DAYS_IN_SECONDS.toString()} seconds).` + ); + return true; + } + ); + }); + + describe('headers', () => { + it('should add path-styled host header', async () => { + const getCanonicalHeaders = sandbox + .stub(signer, 'getCanonicalHeaders') + .returns(''); + + await signer['getSignedUrlV4'](CONFIG); + const arg = getCanonicalHeaders.getCall(0).args[0]; + assert.strictEqual( + arg.host, + PATH_STYLED_HOST.replace('https://', '') + ); + }); + + it('should add cname as host header', async () => { + CONFIG.cname = 'http://www.example.com'; + const getCanonicalHeaders = sandbox + .stub(signer, 'getCanonicalHeaders') + .returns(''); + + await signer['getSignedUrlV4'](CONFIG); + const arg = getCanonicalHeaders.getCall(0).args[0]; + assert.strictEqual(arg.host, 'www.example.com'); + }); + + it('should strip trailing slashes from host', async () => { + CONFIG.cname = 'http://www.example.com//'; + const getCanonicalHeaders = sandbox + .stub(signer, 'getCanonicalHeaders') + .returns(''); + + await signer['getSignedUrlV4'](CONFIG); + const arg = getCanonicalHeaders.getCall(0).args[0]; + assert.strictEqual(arg.host, 'www.example.com'); + }); + + it('should add Content-MD5 to header', async () => { + CONFIG.contentMd5 = 'md5-hash'; + const getCanonicalHeaders = sandbox + .stub(signer, 'getCanonicalHeaders') + .returns(''); + + await signer['getSignedUrlV4'](CONFIG); + const arg = getCanonicalHeaders.getCall(0).args[0]; + assert.strictEqual(arg['content-md5'], CONFIG.contentMd5); + }); + + it('should add Content-Type to header', async () => { + CONFIG.contentType = 'application/octet-stream'; + const getCanonicalHeaders = sandbox + .stub(signer, 'getCanonicalHeaders') + .returns(''); + + await signer['getSignedUrlV4'](CONFIG); + const arg = getCanonicalHeaders.getCall(0).args[0]; + assert.strictEqual(arg['content-type'], CONFIG.contentType); + }); + + it('should merge extensionHeaders', async () => { + CONFIG = { + extensionHeaders: { + 'x-goog-content-sha256': + '76af7efae0d034d1e3335ed1b90f24b6cadf2bf1', + }, + cname: 'http://www.example.com', + contentMd5: 'md5-hash', + contentType: 'application/octet-stream', + ...CONFIG, + }; + + const getCanonicalHeaders = sandbox + .stub(signer, 'getCanonicalHeaders') + .returns(''); + + await signer['getSignedUrlV4'](CONFIG); + const arg = getCanonicalHeaders.getCall(0).args[0]; + + assert.deepStrictEqual(arg, { + ...CONFIG.extensionHeaders, + host: CONFIG.cname!.replace('http://', ''), + 'content-md5': CONFIG.contentMd5, + 'content-type': CONFIG.contentType, + }); + }); + + it('should throw if x-goog-content-sha256 header is not a hash', () => { + CONFIG = { + extensionHeaders: { + 'x-goog-content-sha256': 'not-a-hash', + }, + ...CONFIG, + }; + + assert.throws(() => { + signer['getSignedUrlV4'](CONFIG), + SignerExceptionMessages.X_GOOG_CONTENT_SHA256; + }); + }); + }); + + describe('query parameters', () => { + let getCanonicalQueryParams: sinon.SinonStub<[Query]>; + beforeEach(() => { + getCanonicalQueryParams = sandbox + .stub(signer, 'getCanonicalQueryParams') + .returns(''); + }); + + it('should populate X-Goog-Algorithm', async () => { + const query = (await signer['getSignedUrlV4'](CONFIG)) as Query; + const arg = getCanonicalQueryParams.getCall(0).args[0]; + + assert.strictEqual(arg['X-Goog-Algorithm'], 'GOOG4-RSA-SHA256'); + assert.strictEqual(query['X-Goog-Algorithm'], 'GOOG4-RSA-SHA256'); + }); + + it('should populate X-Goog-Credential', async () => { + const query = (await signer['getSignedUrlV4'](CONFIG)) as Query; + const arg = getCanonicalQueryParams.getCall(0).args[0]; + + const datestamp = formatAsUTCISO(NOW); + const credentialScope = `${datestamp}/auto/storage/goog4_request`; + const EXPECTED_CREDENTIAL = `${CLIENT_EMAIL}/${credentialScope}`; + + assert.strictEqual(arg['X-Goog-Credential'], EXPECTED_CREDENTIAL); + assert.strictEqual(query['X-Goog-Credential'], EXPECTED_CREDENTIAL); + }); + + it('should populate X-Goog-Date', async () => { + const dateISO = formatAsUTCISO(NOW, true); + + const query = (await signer['getSignedUrlV4'](CONFIG)) as Query; + const arg = getCanonicalQueryParams.getCall(0).args[0]; + + assert.strictEqual(arg['X-Goog-Date'], dateISO); + assert.strictEqual(query['X-Goog-Date'], dateISO); + }); + + it('should populate X-Goog-Expires', async () => { + const query = (await signer['getSignedUrlV4'](CONFIG)) as Query; + const arg = getCanonicalQueryParams.getCall(0).args[0]; + + assert.strictEqual(arg['X-Goog-Expires'], '2'); + assert.strictEqual(query['X-Goog-Expires'], '2'); + }); + + it('should lowercase and sort signed headers, and populate X-Goog-SignedHeaders', async () => { + CONFIG.extensionHeaders = { + 'x-foo': 'bar', + 'X-Goog-acl': 'public-read', + }; + + const query = (await signer['getSignedUrlV4'](CONFIG)) as Query; + const arg = getCanonicalQueryParams.getCall(0).args[0]; + + assert.strictEqual( + arg['X-Goog-SignedHeaders'], + 'host;x-foo;x-goog-acl' + ); + assert.strictEqual( + query['X-Goog-SignedHeaders'], + 'host;x-foo;x-goog-acl' + ); + }); + + it('should merge user-provided queryParams', async () => { + CONFIG.queryParams = { + foo: 'bar', + }; + + const query = (await signer['getSignedUrlV4'](CONFIG)) as Query; + const arg = getCanonicalQueryParams.getCall(0).args[0]; + + assert.strictEqual(arg['foo'], 'bar'); + assert.strictEqual(query['foo'], 'bar'); + }); + }); + + it('should build canonical request', async () => { + CONFIG.extensionHeaders = { + 'x-foo': 'bar', + 'x-goog-content-sha256': '76af7efae0d034d1e3335ed1b90f24b6cadf2bf1', + }; + CONFIG.file = 'file-name.png'; + sinon.stub(signer, 'getCanonicalHeaders').returns('canonical-headers'); + sinon + .stub(signer, 'getCanonicalQueryParams') + .returns('canonical-query'); + const getCanonicalRequest = sinon.spy(signer, 'getCanonicalRequest'); + + await signer['getSignedUrlV4'](CONFIG); + const args = getCanonicalRequest.getCall(0).args; + + assert.strictEqual(args[0], CONFIG.method); + assert.strictEqual(args[1], '/bucket-name/file-name.png'); + assert.strictEqual(args[2], 'canonical-query'); + assert.strictEqual(args[3], 'canonical-headers'); + assert.strictEqual(args[4], 'host;x-foo;x-goog-content-sha256'); + assert.strictEqual(args[5], '76af7efae0d034d1e3335ed1b90f24b6cadf2bf1'); + }); + + it('should compute SHA256 digest in hex on canonical request', async () => { + sinon.stub(signer, 'getCanonicalRequest').returns('canonical-request'); + const authClientSign = sinon + .stub(authClient, 'sign') + .resolves('signature'); + + await signer['getSignedUrlV4'](CONFIG); + const blobToSign = authClientSign.getCall(0).args[0]; + + const canonicalRequestHash = crypto + .createHash('sha256') + .update('canonical-request') + .digest('hex'); + + assert(blobToSign.endsWith(canonicalRequestHash)); + }); + + it('should sign using the `signingEndpoint` when provided', async () => { + const signingEndpoint = 'https://my-endpoint.com'; + + sinon.stub(signer, 'getCanonicalRequest').returns('canonical-request'); + const authClientSign = sinon + .stub(authClient, 'sign') + .resolves('signature'); + + CONFIG = { + ...CONFIG, + signingEndpoint, + }; + + await signer['getSignedUrlV4'](CONFIG); + + const endpoint = authClientSign.getCall(0).args[1]; + assert.equal(endpoint, signingEndpoint); + }); + + it('should compose blobToSign', async () => { + const datestamp = formatAsUTCISO(NOW); + const credentialScope = `${datestamp}/auto/storage/goog4_request`; + const dateISO = formatAsUTCISO(NOW, true); + + const authClientSign = sinon + .stub(authClient, 'sign') + .resolves('signature'); + + await signer['getSignedUrlV4'](CONFIG); + const blobToSign = authClientSign.getCall(0).args[0]; + + assert( + blobToSign.startsWith( + ['GOOG4-RSA-SHA256', dateISO, credentialScope].join('\n') + ) + ); + }); + + it('rejects with SigningError on signing Error', () => { + const err = new Error('my-err'); + err.stack = 'some-stack-trace'; + sinon.stub(authClient, 'sign').rejects(err); + + assert.rejects(() => signer['getSignedUrlV4'](CONFIG), { + name: 'SigningError', + message: 'my-err', + stack: 'some-stack-trace', + }); + }); + + it('should returns query params with signature', async () => { + CONFIG.queryParams = { + foo: 'bar', + }; + + const query = (await signer['getSignedUrlV4'](CONFIG)) as Query; + const signatureInHex = Buffer.from('signature', 'base64').toString( + 'hex' + ); + assert.strictEqual(query['X-Goog-Signature'], signatureInHex); + }); + }); + + describe('getCanonicalHeaders', () => { + const signer = new URLSigner(authClient, bucket, file); + + it('should accept multi-valued header as an array', () => { + const headers = { + foo: ['bar', 'pub'], + }; + + const canonical = signer.getCanonicalHeaders(headers); + assert.strictEqual(canonical, 'foo:bar,pub\n'); + }); + + it('should lowercase and then sort header names', () => { + const headers = { + B: 'foo', + a: 'bar', + }; + + const canonical = signer.getCanonicalHeaders(headers); + assert.strictEqual(canonical, 'a:bar\nb:foo\n'); + }); + + it('should trim leading and trailing space', () => { + const headers = { + foo: ' bar ', + my: '\t header ', + }; + + const canonical = signer.getCanonicalHeaders(headers); + assert.strictEqual(canonical, 'foo:bar\nmy:header\n'); + }); + + it('should convert sequential spaces into single space', () => { + const headers = { + foo: 'a\t\t\tbar pub', + }; + + const canonical = signer.getCanonicalHeaders(headers); + assert.strictEqual(canonical, 'foo:a bar pub\n'); + }); + }); + + describe('getCanonicalRequest', () => { + const signer = new URLSigner(authClient, bucket, file); + + it('should return canonical request string with unsigned-payload', () => { + const args: [string, string, string, string, string] = [ + 'DELETE', + 'path', + 'query', + 'headers', + 'signedHeaders', + ]; + + const canonical = signer.getCanonicalRequest(...args); + + const EXPECTED = [...args, 'UNSIGNED-PAYLOAD'].join('\n'); + assert.strictEqual(canonical, EXPECTED); + }); + + it('should include contentSha256 value if not undefined', () => { + const SHA = '76af7efae0d034d1e3335ed1b90f24b6cadf2bf1'; + const canonical = signer.getCanonicalRequest( + 'DELETE', + 'path', + 'query', + 'headers', + 'signedHeaders', + SHA + ); + + const EXPECTED = [ + 'DELETE', + 'path', + 'query', + 'headers', + 'signedHeaders', + SHA, + ].join('\n'); + assert.strictEqual(canonical, EXPECTED); + }); + }); + + describe('getCanonicalQueryParams', () => { + const signer = new URLSigner(authClient, bucket, file); + + it('should encode key', () => { + const key = 'AZ!*()*%/f'; + const query: Query = {}; + query[key] = 'value'; + const canonical = signer.getCanonicalQueryParams(query); + + const EXPECTED = `${encodeURI(key, true)}=value`; + assert.strictEqual(canonical, EXPECTED); + }); + + it('should encode value', () => { + const value = 'AZ!*()*%/f'; + const query = {key: value}; + const canonical = signer.getCanonicalQueryParams(query); + + const EXPECTED = `key=${encodeURI(value, true)}`; + assert.strictEqual(canonical, EXPECTED); + }); + + it('should sort by key', () => { + const query = { + B: 'bar', + A: 'foo', + }; + + const canonical = signer.getCanonicalQueryParams(query); + const EXPECTED = 'A=foo&B=bar'; + assert.strictEqual(canonical, EXPECTED); + }); + }); + + describe('getResourcePath', () => { + const signer = new URLSigner(authClient, bucket, file); + + it('should not include bucket with cname', () => { + const path = signer.getResourcePath(true, bucket.name, file.name); + assert.strictEqual(path, `/${file.name}`); + }); + + it('should include file name', () => { + const path = signer.getResourcePath(false, bucket.name, file.name); + assert.strictEqual(path, `/${bucket.name}/${file.name}`); + }); + + it('should return path with no file name', () => { + const path = signer.getResourcePath(false, bucket.name); + assert.strictEqual(path, `/${bucket.name}`); + }); + }); + + describe('parseExpires', () => { + const signer = new URLSigner(authClient, bucket, file); + + it('throws invalid date', () => { + assert.throws(() => signer.parseExpires('2019-31-12T25:60:60Z'), { + message: ExceptionMessages.EXPIRATION_DATE_INVALID, + }); + }); + + it('throws if expiration is in the past', () => { + assert.throws(() => signer.parseExpires(NOW.valueOf() - 1, NOW), { + message: ExceptionMessages.EXPIRATION_DATE_PAST, + }); + }); + + it('returns expiration date in seconds', () => { + const expires = signer.parseExpires(NOW); + assert.strictEqual(expires, Math.floor(NOW.valueOf() / 1000)); + }); + }); + }); + + describe('SigningError', () => { + it('should extend from Error', () => { + const err = new SigningError(); + assert(err instanceof Error); + assert.strictEqual(err.name, 'SigningError'); + }); + }); +}); diff --git a/handwritten/storage/test/testdata/testfile.json b/handwritten/storage/test/testdata/testfile.json new file mode 100644 index 00000000000..e69de29bb2d diff --git a/handwritten/storage/test/testdata/textfile.txt b/handwritten/storage/test/testdata/textfile.txt new file mode 100644 index 00000000000..c66d471e359 --- /dev/null +++ b/handwritten/storage/test/testdata/textfile.txt @@ -0,0 +1 @@ +This is a test file! diff --git a/handwritten/storage/test/transfer-manager.ts b/handwritten/storage/test/transfer-manager.ts new file mode 100644 index 00000000000..2582782fa7a --- /dev/null +++ b/handwritten/storage/test/transfer-manager.ts @@ -0,0 +1,734 @@ +/*! + * Copyright 2022 Google LLC. All Rights Reserved. + * + * 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 { + ApiError, + Bucket, + File, + CRC32C, + DownloadCallback, + DownloadOptions, + IdempotencyStrategy, + MultiPartHelperGenerator, + MultiPartUploadError, + MultiPartUploadHelper, + UploadOptions, + TransferManager, + Storage, + DownloadResponse, + DownloadManyFilesOptions, +} from '../src/index.js'; +import assert from 'assert'; +import * as path from 'path'; +import {GaxiosOptions, GaxiosResponse} from 'gaxios'; +import {GCCL_GCS_CMD_KEY} from '../src/nodejs-common/util.js'; +import {AuthClient, GoogleAuth} from 'google-auth-library'; +import {tmpdir} from 'os'; +import fs from 'fs'; +import {promises as fsp, Stats} from 'fs'; + +import * as sinon from 'sinon'; + +describe('Transfer Manager', () => { + const BUCKET_NAME = 'test-bucket'; + const STORAGE = sinon.stub( + new Storage({ + retryOptions: { + autoRetry: true, + maxRetries: 3, + retryDelayMultiplier: 2, + totalTimeout: 600, + maxRetryDelay: 60, + retryableErrorFn: (err: ApiError) => { + return err.code === 500; + }, + idempotencyStrategy: IdempotencyStrategy.RetryConditional, + }, + }) + ); + let sandbox: sinon.SinonSandbox; + let transferManager: TransferManager; + let bucket: Bucket; + + before(() => { + sandbox = sinon.createSandbox(); + }); + + beforeEach(() => { + bucket = new Bucket(STORAGE, BUCKET_NAME); + transferManager = new TransferManager(bucket); + }); + + afterEach(() => { + sandbox.restore(); + }); + + describe('instantiation', () => { + it('should correctly set the bucket', () => { + assert.strictEqual(transferManager.bucket, bucket); + }); + }); + + describe('uploadManyFiles', () => { + beforeEach(() => { + sandbox.stub(fsp, 'lstat').resolves({ + isDirectory: () => { + return false; + }, + } as Stats); + }); + + it('calls upload with the provided file paths', async () => { + const paths = ['/a/b/c', '/d/e/f', '/h/i/j']; + let count = 0; + sandbox.stub(bucket, 'upload').callsFake(path => { + count++; + assert(paths.includes(path)); + }); + + await transferManager.uploadManyFiles(paths); + assert.strictEqual(count, paths.length); + }); + + it('sets ifGenerationMatch to 0 if skipIfExists is set', async () => { + const paths = ['/a/b/c']; + sandbox.stub(bucket, 'upload').callsFake((path, options) => { + assert.strictEqual( + (options as UploadOptions).preconditionOpts?.ifGenerationMatch, + 0 + ); + }); + + await transferManager.uploadManyFiles(paths, {skipIfExists: true}); + }); + + it('sets destination to prefix + filename when prefix is supplied', async () => { + const filePaths = ['a', 'b', 'foo', 'bar.txt'].join(path.sep); + const expectedDestination = [ + 'hello', + 'world', + 'a', + 'b', + 'foo', + 'bar.txt', + ].join(path.posix.sep); + sandbox.stub(bucket, 'upload').callsFake((path, options) => { + assert.strictEqual( + (options as UploadOptions).destination, + expectedDestination + ); + }); + + await transferManager.uploadManyFiles([filePaths], { + prefix: ['hello', 'world'].join(path.sep), + }); + }); + + it('returns a promise with the uploaded file if there is no callback', async () => { + const paths = [['a', 'b', 'foo', 'bar.txt'].join(path.sep)]; + sandbox.stub(bucket, 'upload').callsFake(() => { + const resp = [{name: paths[0].split(path.sep).join(path.posix.sep)}]; + return Promise.resolve(resp); + }); + + const result = await transferManager.uploadManyFiles(paths); + assert.strictEqual( + result[0][0].name, + paths[0].split(path.sep).join(path.posix.sep) + ); + }); + + it('should set the appropriate `GCCL_GCS_CMD_KEY`', async () => { + const paths = ['/a/b/foo/bar.txt']; + + sandbox.stub(bucket, 'upload').callsFake(async (_path, options) => { + assert.strictEqual( + (options as UploadOptions)[GCCL_GCS_CMD_KEY], + 'tm.upload_many' + ); + }); + + await transferManager.uploadManyFiles(paths, {prefix: 'hello/world'}); + }); + + it('replaces OS specific separator with posix separator when calling bucket.upload', async () => { + const filePath = ['a', 'b', 'c'].join(path.sep); + const expected = ['a', 'b', 'c'].join(path.posix.sep); + + sandbox.stub(bucket, 'upload').callsFake((path, options) => { + assert.strictEqual(expected, (options as UploadOptions).destination); + }); + + await transferManager.uploadManyFiles([filePath]); + }); + + it('allows the user to apply a custom destination transformation when supplied a custom function', async () => { + const paths = ['a', 'b', 'foo/bar', 'bar.txt']; + const expected = ['foo/a', 'b/bar', 'foo/foo/bar', 'bar.txt/bar']; + sandbox.stub(bucket, 'upload').callsFake((path, options) => { + const uploadOpts = options as UploadOptions; + assert(expected.includes(uploadOpts.destination as string)); + }); + + let callCount = 0; + const transformationFunc = (path: string) => { + assert.strictEqual(path, paths[callCount]); + return expected[callCount++]; + }; + await transferManager.uploadManyFiles(paths, { + customDestinationBuilder: transformationFunc, + }); + }); + }); + + describe('downloadManyFiles', () => { + beforeEach(() => { + sandbox.stub(fs, 'existsSync').returns(true); + }); + + it('calls download for each provided file', async () => { + let count = 0; + const firstFile = new File(bucket, 'first.txt'); + sandbox.stub(firstFile, 'download').callsFake(() => { + count++; + }); + const secondFile = new File(bucket, 'second.txt'); + sandbox.stub(secondFile, 'download').callsFake(() => { + count++; + }); + + const files = [firstFile, secondFile]; + await transferManager.downloadManyFiles(files); + assert.strictEqual(count, 2); + }); + + it('sets the destination correctly when provided a prefix', async () => { + const prefix = 'test-prefix'; + const filename = 'first.txt'; + const expectedDestination = path.normalize(`${prefix}/${filename}`); + + const file = new File(bucket, filename); + sandbox.stub(file, 'download').callsFake(options => { + assert.strictEqual( + (options as DownloadOptions).destination, + expectedDestination + ); + }); + await transferManager.downloadManyFiles([file], {prefix}); + }); + + it('sets the destination correctly when provided a strip prefix', async () => { + const stripPrefix = 'should-be-removed/'; + const filename = 'should-be-removed/first.txt'; + const expectedDestination = 'first.txt'; + + const file = new File(bucket, filename); + sandbox.stub(file, 'download').callsFake(options => { + assert.strictEqual( + (options as DownloadOptions).destination, + expectedDestination + ); + }); + await transferManager.downloadManyFiles([file], {stripPrefix}); + }); + + it('should set the appropriate `GCCL_GCS_CMD_KEY`', async () => { + const file = new File(bucket, 'first.txt'); + + sandbox.stub(file, 'download').callsFake(async options => { + assert.strictEqual( + (options as DownloadOptions)[GCCL_GCS_CMD_KEY], + 'tm.download_many' + ); + }); + + await transferManager.downloadManyFiles([file]); + }); + + it('sets the destination correctly when provided a passthroughOptions.destination', async () => { + const passthroughOptions = { + destination: 'test-destination', + }; + const filename = 'first.txt'; + const expectedDestination = path.normalize( + `${passthroughOptions.destination}/${filename}` + ); + const download = (optionsOrCb?: DownloadOptions | DownloadCallback) => { + if (typeof optionsOrCb === 'function') { + optionsOrCb(null, Buffer.alloc(0)); + } else if (optionsOrCb) { + assert.strictEqual(optionsOrCb.destination, expectedDestination); + } + return Promise.resolve([Buffer.alloc(0)]) as Promise; + }; + + const file = new File(bucket, filename); + file.download = download; + await transferManager.downloadManyFiles([file], {passthroughOptions}); + }); + + it('does not download files that already exist locally when skipIfExists is true', async () => { + const firstFile = new File(bucket, 'first.txt'); + sandbox.stub(firstFile, 'download').callsFake(options => { + assert.strictEqual( + (options as DownloadManyFilesOptions).skipIfExists, + 0 + ); + }); + const secondFile = new File(bucket, 'second.txt'); + sandbox.stub(secondFile, 'download').callsFake(options => { + assert.strictEqual( + (options as DownloadManyFilesOptions).skipIfExists, + 0 + ); + }); + + const files = [firstFile, secondFile]; + const options = {skipIfExists: true}; + await transferManager.downloadManyFiles(files, options); + }); + + it('does not set the destination when prefix, strip prefix and passthroughOptions.destination are not provided', async () => { + const options = {}; + const filename = 'first.txt'; + const download = (optionsOrCb?: DownloadOptions | DownloadCallback) => { + if (typeof optionsOrCb === 'function') { + optionsOrCb(null, Buffer.alloc(0)); + } else if (optionsOrCb) { + assert.strictEqual(optionsOrCb.destination, undefined); + } + return Promise.resolve([Buffer.alloc(0)]) as Promise; + }; + + const file = new File(bucket, filename); + file.download = download; + await transferManager.downloadManyFiles([file], options); + }); + + it('should recursively create directory and write file contents if destination path is nested', async () => { + const prefix = 'text-prefix'; + const folder = 'nestedFolder/'; + const file = 'first.txt'; + const filesOrFolder = [folder, path.join(folder, file)]; + const expectedFilePath = path.join(prefix, folder, file); + const expectedDir = path.join(prefix, folder); + const mkdirSpy = sandbox.spy(fsp, 'mkdir'); + const download = (optionsOrCb?: DownloadOptions | DownloadCallback) => { + if (typeof optionsOrCb === 'function') { + optionsOrCb(null, Buffer.alloc(0)); + } else if (optionsOrCb) { + assert.strictEqual(optionsOrCb.destination, expectedFilePath); + } + return Promise.resolve([Buffer.alloc(0)]) as Promise; + }; + + sandbox.stub(bucket, 'file').callsFake(filename => { + const file = new File(bucket, filename); + file.download = download; + return file; + }); + await transferManager.downloadManyFiles(filesOrFolder, { + prefix: prefix, + }); + assert.strictEqual( + mkdirSpy.calledOnceWith(expectedDir, { + recursive: true, + }), + true + ); + }); + }); + + describe('downloadFileInChunks', () => { + let file: File; + + beforeEach(() => { + sandbox.stub(fsp, 'open').resolves({ + close: () => Promise.resolve(), + write: (buffer: unknown) => Promise.resolve({buffer}), + } as fsp.FileHandle); + + file = new File(bucket, 'some-large-file'); + sandbox.stub(file, 'get').resolves([ + { + metadata: { + size: 1024, + crc32c: 'AAAAAA==', + }, + }, + ]); + }); + + it('should download a single chunk if file size is below threshold', async () => { + let downloadCallCount = 0; + sandbox.stub(file, 'download').callsFake(() => { + downloadCallCount++; + return Promise.resolve([Buffer.alloc(100)]); + }); + + await transferManager.downloadFileInChunks(file); + assert.strictEqual(downloadCallCount, 1); + }); + + it('should return downloaded data', async () => { + sandbox.stub(file, 'download').callsFake(() => { + return Promise.resolve([Buffer.alloc(100)]); + }); + + const data = await transferManager.downloadFileInChunks(file); + assert.deepStrictEqual(data, [Buffer.alloc(1024)]); + }); + + it('should not return downloaded data when noReturnData flag is set', async () => { + sandbox.stub(file, 'download').callsFake(() => { + return Promise.resolve([Buffer.alloc(100)]); + }); + + const data = await transferManager.downloadFileInChunks(file, { + noReturnData: true, + }); + assert.strictEqual(data, undefined); + }); + + it('should call fromFile when validation is set to crc32c', async () => { + let callCount = 0; + file.download = () => { + return Promise.resolve([Buffer.alloc(0)]) as Promise; + }; + CRC32C.fromFile = () => { + callCount++; + return Promise.resolve(new CRC32C(0)); + }; + + await transferManager.downloadFileInChunks(file, {validation: 'crc32c'}); + assert.strictEqual(callCount, 1); + }); + + it('should throw an error if crc32c validation fails', async () => { + file.download = () => { + return Promise.resolve([Buffer.alloc(0)]) as Promise; + }; + CRC32C.fromFile = () => { + return Promise.resolve(new CRC32C(1)); // Set non-expected initial value + }; + + await assert.rejects( + transferManager.downloadFileInChunks(file, {validation: 'crc32c'}), + { + code: 'CONTENT_DOWNLOAD_MISMATCH', + } + ); + }); + + it('should set the appropriate `GCCL_GCS_CMD_KEY`', async () => { + sandbox.stub(file, 'download').callsFake(async options => { + assert.strictEqual( + (options as DownloadOptions)[GCCL_GCS_CMD_KEY], + 'tm.download_sharded' + ); + return [Buffer.alloc(100)]; + }); + + await transferManager.downloadFileInChunks(file); + }); + }); + + describe('uploadFileInChunks', () => { + let mockGeneratorFunction: MultiPartHelperGenerator; + let fakeHelper: sinon.SinonStubbedInstance; + let readStreamSpy: sinon.SinonSpy; + let directory: string; + let filePath: string; + class FakeXMLHelper implements MultiPartUploadHelper { + bucket: Bucket; + fileName: string; + uploadId?: string | undefined; + partsMap?: Map | undefined; + constructor(bucket: Bucket, fileName: string) { + this.bucket = bucket; + this.fileName = fileName; + } + initiateUpload(): Promise { + throw new Error('Method not implemented.'); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + uploadPart(partNumber: number, chunk: Buffer): Promise { + throw new Error('Method not implemented.'); + } + completeUpload(): Promise { + throw new Error('Method not implemented.'); + } + abortUpload(): Promise { + throw new Error('Method not implemented.'); + } + } + + before(async () => { + directory = await fsp.mkdtemp( + path.join(tmpdir(), 'tm-uploadFileInChunks-') + ); + + filePath = path.join(directory, 't.txt'); + + await fsp.writeFile(filePath, 'hello'); + }); + + beforeEach(async () => { + readStreamSpy = sandbox.spy(fs, 'createReadStream'); + mockGeneratorFunction = (bucket, fileName, uploadId, partsMap) => { + fakeHelper = sandbox.createStubInstance(FakeXMLHelper); + fakeHelper.uploadId = uploadId || ''; + fakeHelper.partsMap = partsMap || new Map(); + fakeHelper.initiateUpload.resolves(); + fakeHelper.uploadPart.resolves(); + fakeHelper.completeUpload.resolves(); + fakeHelper.abortUpload.resolves(); + return fakeHelper; + }; + }); + + after(async () => { + await fsp.rm(directory, {force: true, recursive: true}); + }); + + it('should call initiateUpload, uploadPart, and completeUpload', async () => { + await transferManager.uploadFileInChunks( + filePath, + {}, + mockGeneratorFunction + ); + assert.strictEqual(fakeHelper.initiateUpload.calledOnce, true); + assert.strictEqual(fakeHelper.uploadPart.calledOnce, true); + assert.strictEqual(fakeHelper.completeUpload.calledOnce, true); + }); + + it('should call createReadStream with a highWaterMark equal to chunkSize', async () => { + const options = {highWaterMark: 32 * 1024 * 1024, start: 0}; + + await transferManager.uploadFileInChunks( + filePath, + { + chunkSizeBytes: 32 * 1024 * 1024, + }, + mockGeneratorFunction + ); + + assert.strictEqual(readStreamSpy.calledOnceWith(filePath, options), true); + }); + + it('should set the correct start offset when called with an existing parts map', async () => { + const options = { + highWaterMark: 32 * 1024 * 1024, + start: 64 * 1024 * 1024, + }; + + await transferManager.uploadFileInChunks( + filePath, + { + uploadId: '123', + partsMap: new Map([ + [1, '123'], + [2, '321'], + ]), + chunkSizeBytes: 32 * 1024 * 1024, + }, + mockGeneratorFunction + ); + + assert.strictEqual(readStreamSpy.calledOnceWith(filePath, options), true); + }); + + it('should not call initiateUpload if an uploadId is provided', async () => { + await transferManager.uploadFileInChunks( + filePath, + { + uploadId: '123', + partsMap: new Map([ + [1, '123'], + [2, '321'], + ]), + }, + mockGeneratorFunction + ); + + assert.strictEqual(fakeHelper.uploadId, '123'); + assert.strictEqual(fakeHelper.initiateUpload.notCalled, true); + }); + + it('should reject with an error with empty uploadId and partsMap', async () => { + const expectedErr = new MultiPartUploadError( + 'Hello World', + '', + new Map() + ); + mockGeneratorFunction = (bucket, fileName, uploadId, partsMap) => { + fakeHelper = sandbox.createStubInstance(FakeXMLHelper); + fakeHelper.uploadId = uploadId || ''; + fakeHelper.partsMap = partsMap || new Map(); + fakeHelper.initiateUpload.rejects(new Error(expectedErr.message)); + fakeHelper.uploadPart.resolves(); + fakeHelper.completeUpload.resolves(); + fakeHelper.abortUpload.resolves(); + return fakeHelper; + }; + assert.rejects( + transferManager.uploadFileInChunks( + filePath, + {autoAbortFailure: false}, + mockGeneratorFunction + ), + expectedErr + ); + }); + + it('should pass through headers to initiateUpload', async () => { + const headersToAdd = { + 'Content-Type': 'foo/bar', + 'x-goog-meta-foo': 'foobar', + 'User-Agent': 'barfoo', + }; + + mockGeneratorFunction = (bucket, fileName, uploadId, partsMap) => { + fakeHelper = sandbox.createStubInstance(FakeXMLHelper); + fakeHelper.uploadId = uploadId || ''; + fakeHelper.partsMap = partsMap || new Map(); + fakeHelper.initiateUpload.callsFake(headers => { + assert.deepStrictEqual(headers, headersToAdd); + return Promise.resolve(); + }); + fakeHelper.uploadPart.resolves(); + fakeHelper.completeUpload.resolves(); + fakeHelper.abortUpload.resolves(); + return fakeHelper; + }; + + await transferManager.uploadFileInChunks( + filePath, + {headers: headersToAdd}, + mockGeneratorFunction + ); + }); + + it('should call abortUpload when a failure occurs after an uploadID is established', async () => { + const expectedErr = new MultiPartUploadError( + 'Hello World', + '', + new Map() + ); + const fakeId = '123'; + + mockGeneratorFunction = (bucket, fileName, uploadId, partsMap) => { + fakeHelper = sandbox.createStubInstance(FakeXMLHelper); + fakeHelper.uploadId = uploadId || ''; + fakeHelper.partsMap = partsMap || new Map(); + fakeHelper.initiateUpload.resolves(); + fakeHelper.uploadPart.callsFake(() => { + fakeHelper.uploadId = fakeId; + return Promise.reject(expectedErr); + }); + fakeHelper.completeUpload.resolves(); + fakeHelper.abortUpload.callsFake(() => { + assert.strictEqual(fakeHelper.uploadId, fakeId); + return Promise.resolve(); + }); + return fakeHelper; + }; + + assert.doesNotThrow(() => + transferManager.uploadFileInChunks(filePath, {}, mockGeneratorFunction) + ); + }); + + it('should set the appropriate `GCCL_GCS_CMD_KEY`', async () => { + let called = false; + class TestAuthClient extends AuthClient { + async getAccessToken() { + return {token: '', res: undefined}; + } + + async getRequestHeaders() { + return {}; + } + + async request(opts: GaxiosOptions) { + called = true; + + assert(opts.headers); + assert('x-goog-api-client' in opts.headers); + assert.match( + opts.headers['x-goog-api-client'], + /gccl-gcs-cmd\/tm.upload_sharded/ + ); + + return { + data: Buffer.from( + ` + 1 + ` + ), + headers: {}, + } as GaxiosResponse; + } + } + + transferManager.bucket.storage.authClient = new GoogleAuth({ + authClient: new TestAuthClient(), + }); + + await transferManager.uploadFileInChunks(filePath); + + assert(called); + }); + + it('should set User-Agent correctly based on package.json', async () => { + let called = false; + class TestAuthClient extends AuthClient { + async getAccessToken() { + return {token: '', res: undefined}; + } + + async getRequestHeaders() { + return {}; + } + + async request(opts: GaxiosOptions) { + called = true; + + assert(opts.headers); + assert('User-Agent' in opts.headers); + assert.match(opts.headers['User-Agent'], /gcloud-node/); + + return { + data: Buffer.from( + ` + 1 + ` + ), + headers: {}, + } as GaxiosResponse; + } + } + + transferManager.bucket.storage.authClient = new GoogleAuth({ + authClient: new TestAuthClient(), + }); + + await transferManager.uploadFileInChunks(filePath); + + assert(called); + }); + }); +}); diff --git a/handwritten/storage/tsconfig.cjs.json b/handwritten/storage/tsconfig.cjs.json new file mode 100644 index 00000000000..d0dbd70c64c --- /dev/null +++ b/handwritten/storage/tsconfig.cjs.json @@ -0,0 +1,19 @@ +{ + "extends": "./node_modules/gts/tsconfig-google.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "build/cjs", + "resolveJsonModule": true, + "sourceMap": false, + "esModuleInterop": true, + }, + "include": [ + "src/*.ts", + "src/*.cjs", + "test/**/*.ts", + "system-test/*.ts", + "conformance-test/*.ts", + "conformance-test/scenarios/*.ts", + "internal-tooling/*.ts" + ] +} diff --git a/handwritten/storage/tsconfig.json b/handwritten/storage/tsconfig.json new file mode 100644 index 00000000000..bf65354d9fa --- /dev/null +++ b/handwritten/storage/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "./node_modules/gts/tsconfig-google.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "build/esm", + "resolveJsonModule": true, + "module": "es2020", + "moduleResolution": "node", + "lib": ["ES2020"], + "sourceMap": false, + "esModuleInterop": true, + }, + "include": [ + "src/*.ts", + "src/*.cjs", + "internal-tooling/*.ts", + "system-test/*.ts" + ] +} \ No newline at end of file diff --git a/packages/gapic-node-processing/CHANGELOG.md b/packages/gapic-node-processing/CHANGELOG.md index 6c2f0e0fd88..65627a510fb 100644 --- a/packages/gapic-node-processing/CHANGELOG.md +++ b/packages/gapic-node-processing/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [0.1.7](https://github.com/googleapis/google-cloud-node/compare/gapic-node-processing-v0.1.6...gapic-node-processing-v0.1.7) (2026-03-02) + + +### Bug Fixes + +* Bug preventing apiPath generation when apiId includes letter v ([f1456f9](https://github.com/googleapis/google-cloud-node/commit/f1456f9e8bdd5c2b2d579d6a451036d98b8ee26e)) +* Bug preventing apiPath generation when apiId includes letter v ([6d705f4](https://github.com/googleapis/google-cloud-node/commit/6d705f413ead1e2adfe3dc1d703d4637ab36b6d9)) +* Bug preventing apiPath generation when apiId includes letter v ([76baebb](https://github.com/googleapis/google-cloud-node/commit/76baebbdc05758953af5550b71f3144a7eafbfb4)) + ## [0.1.6](https://github.com/googleapis/google-cloud-node/compare/gapic-node-processing-v0.1.5...gapic-node-processing-v0.1.6) (2025-10-24) diff --git a/packages/gapic-node-processing/package.json b/packages/gapic-node-processing/package.json index f114b7e91f2..f64d06035d3 100644 --- a/packages/gapic-node-processing/package.json +++ b/packages/gapic-node-processing/package.json @@ -1,6 +1,6 @@ { "name": "gapic-node-processing", - "version": "0.1.6", + "version": "0.1.7", "description": "Does various processing functions for Nodejs gapic libraries", "bin": "./build/src/cli.js", "scripts": { diff --git a/packages/google-ads-datamanager/CHANGELOG.md b/packages/google-ads-datamanager/CHANGELOG.md index 3683c982fd4..af243abc47c 100644 --- a/packages/google-ads-datamanager/CHANGELOG.md +++ b/packages/google-ads-datamanager/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.2.0](https://github.com/googleapis/google-cloud-node/compare/datamanager-v0.1.0...datamanager-v0.2.0) (2026-03-02) + + +### Features + +* [datamanager] add `UserListService` for creating and managing user lists ([#7290](https://github.com/googleapis/google-cloud-node/issues/7290)) ([32115d9](https://github.com/googleapis/google-cloud-node/commit/32115d95be2fc2e06da22aa5101c94ddb3bf82db)) + ## 0.1.0 (2025-11-11) diff --git a/packages/google-ads-datamanager/README.md b/packages/google-ads-datamanager/README.md index a3e07d1f8e6..a1888aea2a6 100644 --- a/packages/google-ads-datamanager/README.md +++ b/packages/google-ads-datamanager/README.md @@ -61,7 +61,25 @@ Samples are in the [`samples/`][homepage_samples] directory. Each sample's `READ | ingest events | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/ingestion_service.ingest_events.js) | | remove audience members | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/ingestion_service.remove_audience_members.js) | | retrieve request status | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/ingestion_service.retrieve_request_status.js) | +| retrieve insights | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/marketing_data_insights_service.retrieve_insights.js) | +| create partner link | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.create_partner_link.js) | +| delete partner link | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.delete_partner_link.js) | +| search partner links | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.search_partner_links.js) | | ads | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json) | +| create user list direct license | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.create_user_list_direct_license.js) | +| get user list direct license | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.get_user_list_direct_license.js) | +| list user list direct licenses | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.list_user_list_direct_licenses.js) | +| update user list direct license | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.update_user_list_direct_license.js) | +| create user list global license | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.create_user_list_global_license.js) | +| get user list global license | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.get_user_list_global_license.js) | +| list user list global license customer infos | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.list_user_list_global_license_customer_infos.js) | +| list user list global licenses | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.list_user_list_global_licenses.js) | +| update user list global license | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.update_user_list_global_license.js) | +| create user list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_service.create_user_list.js) | +| delete user list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_service.delete_user_list.js) | +| get user list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_service.get_user_list.js) | +| list user lists | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_service.list_user_lists.js) | +| update user list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/samples/generated/v1/user_list_service.update_user_list.js) | ## Supported Node.js Versions diff --git a/packages/google-ads-datamanager/package.json b/packages/google-ads-datamanager/package.json index 1c410814b1f..3d1cfffa5d6 100644 --- a/packages/google-ads-datamanager/package.json +++ b/packages/google-ads-datamanager/package.json @@ -1,6 +1,6 @@ { "name": "@google-ads/datamanager", - "version": "0.1.0", + "version": "0.2.0", "description": "Data Manager API client for Node.js", "repository": { "type": "git", diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/age_range.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/age_range.proto new file mode 100644 index 00000000000..d0472fcfc8d --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/age_range.proto @@ -0,0 +1,52 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "AgeRangeProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// The demographic age ranges +enum AgeRange { + // Not specified. + AGE_RANGE_UNSPECIFIED = 0; + + // Unknown. + AGE_RANGE_UNKNOWN = 1; + + // Between 18 and 24 years old. + AGE_RANGE_18_24 = 2; + + // Between 25 and 34 years old. + AGE_RANGE_25_34 = 3; + + // Between 35 and 44 years old. + AGE_RANGE_35_44 = 4; + + // Between 45 and 54 years old. + AGE_RANGE_45_54 = 5; + + // Between 55 and 64 years old. + AGE_RANGE_55_64 = 6; + + // 65 years old and beyond. + AGE_RANGE_65_UP = 7; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/audience.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/audience.proto index 8bbda875154..a4a0d368b32 100644 --- a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/audience.proto +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/audience.proto @@ -43,10 +43,21 @@ message AudienceMember { // [Publisher Advertiser Identity Reconciliation (PAIR) // IDs](//support.google.com/admanager/answer/15067908). + // + // This feature is only available to data partners. PairData pair_data = 4; // Data identifying the user's mobile devices. MobileData mobile_data = 5; + + // Data related to unique identifiers for a user, as defined by the + // advertiser. + UserIdData user_id_data = 6; + + // Data related to publisher provided identifiers. + // + // This feature is only available to data partners. + PpidData ppid_data = 7; } // Optional. The consent setting for the user. @@ -55,6 +66,8 @@ message AudienceMember { // [PAIR](//support.google.com/admanager/answer/15067908) IDs for the audience. // At least one PAIR ID is required. +// +// This feature is only available to data partners. message PairData { // Required. Cleanroom-provided PII data, hashed with SHA256, and encrypted // with an EC commutative cipher using publisher key for the @@ -71,3 +84,19 @@ message MobileData { // [AudienceMember][google.ads.datamanager.v1.AudienceMember]. repeated string mobile_ids = 1 [(google.api.field_behavior) = REQUIRED]; } + +// User id data holding the user id. +message UserIdData { + // Required. A unique identifier for a user, as defined by the + // advertiser. + string user_id = 1 [(google.api.field_behavior) = REQUIRED]; +} + +// Publisher provided identifiers data holding the ppids. At least one ppid is +// required. +// +// This feature is only available to data partners. +message PpidData { + // Required. The list of publisher provided identifiers for a user. + repeated string ppids = 1 [(google.api.field_behavior) = REQUIRED]; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/destination.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/destination.proto index 5cdb43a689e..40d204e187c 100644 --- a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/destination.proto +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/destination.proto @@ -17,6 +17,7 @@ syntax = "proto3"; package google.ads.datamanager.v1; import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; option csharp_namespace = "Google.Ads.DataManager.V1"; option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; @@ -25,6 +26,10 @@ option java_outer_classname = "DestinationProto"; option java_package = "com.google.ads.datamanager.v1"; option php_namespace = "Google\\Ads\\DataManager\\V1"; option ruby_package = "Google::Ads::DataManager::V1"; +option (google.api.resource_definition) = { + type: "datamanager.googleapis.com/Account" + pattern: "accountTypes/{account_type}/accounts/{account}" +}; // The Google product you're sending data to. For example, a Google // Ads account. @@ -83,6 +88,9 @@ message ProductAccount { // Google Analytics. GOOGLE_ANALYTICS_PROPERTY = 5; + + // Google Ad Manager audience link. + GOOGLE_AD_MANAGER_AUDIENCE_LINK = 6; } // Deprecated. Use diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/error.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/error.proto index 44c3ed5e79e..8abaf0ad934 100644 --- a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/error.proto +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/error.proto @@ -25,6 +25,7 @@ option php_namespace = "Google\\Ads\\DataManager\\V1"; option ruby_package = "Google::Ads::DataManager::V1"; // Error reasons for Data Manager API. +// NOTE: This enum is not frozen and new values may be added in the future. enum ErrorReason { // Do not use this default value. ERROR_REASON_UNSPECIFIED = 0; @@ -188,4 +189,151 @@ enum ErrorReason { // Too many elements in a list in the request. TOO_MANY_ELEMENTS = 51; + + // The resource already exists. + ALREADY_EXISTS = 52; + + // Attempted to set an immutable field for an update request. + IMMUTABLE_FIELD_FOR_UPDATE = 53; + + // The resource name is invalid. + INVALID_RESOURCE_NAME = 54; + + // The query filter is invalid. + INVALID_FILTER = 55; + + // The update mask is invalid. + INVALID_UPDATE_MASK = 56; + + // The page token is invalid. + INVALID_PAGE_TOKEN = 57; + + // Cannot update a license that has been disabled. + CANNOT_UPDATE_DISABLED_LICENSE = 58; + + // Sensitive user lists cannot be licensed to this client. + CANNOT_CREATE_LICENSE_FOR_SENSITIVE_USERLIST = 59; + + // Cost too low for this license. + INSUFFICIENT_COST = 60; + + // Reseller license cannot be disabled since it is in use. + CANNOT_DISABLE_LICENSE = 61; + + // Invalid client account id. + INVALID_CLIENT_ACCOUNT_ID = 62; + + // Non-zero cost not allowed for this client account. + PRICING_ONLY_ZERO_COST_ALLOWED = 63; + + // Cost too high for this license. + PRICE_TOO_HIGH = 64; + + // Customer not allowed to create license. + CUSTOMER_NOT_ALLOWED_TO_CREATE_LICENSE = 65; + + // Pricing end date is invalid for this license. + INVALID_PRICING_END_DATE = 66; + + // Logical user list with shared or licensed segment cannot be licensed. + CANNOT_LICENSE_LOGICAL_LIST_WITH_LICENSED_OR_SHARED_SEGMENT = 67; + + // Client customer's account type in the request does not match the customer's + // actual account type. + MISMATCHED_ACCOUNT_TYPE = 68; + + // License type does not support media share cost. + MEDIA_SHARE_COST_NOT_ALLOWED_FOR_LICENSE_TYPE = 69; + + // Client customer type does not support media share cost. + MEDIA_SHARE_COST_NOT_ALLOWED_FOR_CLIENT_CUSTOMER = 70; + + // Invalid media share cost. + INVALID_MEDIA_SHARE_COST = 71; + + // Invalid cost type. + INVALID_COST_TYPE = 72; + + // UserList type does not support media share cost. + MEDIA_SHARE_COST_NOT_ALLOWED_FOR_NON_COMMERCE_USER_LIST = 73; + + // Max cost is only allowed for cost_type MEDIA_SHARE. + MAX_COST_NOT_ALLOWED = 74; + + // Commerce audience can only be directly licensed. + COMMERCE_AUDIENCE_CAN_ONLY_BE_DIRECTLY_LICENSED = 75; + + // The description is not valid. + INVALID_DESCRIPTION = 76; + + // The display name is not valid. + INVALID_DISPLAY_NAME = 77; + + // The display name is already being used for another user list for the + // account. + DISPLAY_NAME_ALREADY_USED = 78; + + // Ownership is required to modify the user list. + OWNERSHIP_REQUIRED_FOR_UPDATE = 79; + + // The user list type is read-only and does not support mutation. + USER_LIST_MUTATION_NOT_SUPPORTED = 80; + + // A user list which is privacy sensitive or legal rejected cannot be mutated + // by external users. + SENSITIVE_USER_LIST_IMMUTABLE = 81; + + // The remarketing user list's billable record field cannot be modified once + // it is set. + BILLABLE_RECORD_COUNT_IMMUTABLE = 82; + + // The user list name is reserved for system lists. + USER_LIST_NAME_RESERVED = 83; + + // The advertiser needs to be allowlisted to use remarketing lists created + // from advertiser uploaded data. + ADVERTISER_NOT_ALLOWLISTED_FOR_UPLOADED_DATA = 84; + + // The partner audience source is not supported for the user list type. + UNSUPPORTED_PARTNER_AUDIENCE_SOURCE = 85; + + // Setting the `commerce_partner` field is only supported if the + // `partner_audience_source` is `COMMERCE_AUDIENCE`. + COMMERCE_PARTNER_NOT_ALLOWED = 86; + + // The `partner_audience_info` field is not supported for the user list type. + UNSUPPORTED_PARTNER_AUDIENCE_INFO = 87; + + // Partner Match user lists cannot be created by manager accounts. + PARTNER_MATCH_FOR_MANAGER_ACCOUNT_DISALLOWED = 88; + + // The data partner is not allowlisted for THIRD_PARTY_PARTNER_DATA. + DATA_PARTNER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA = 89; + + // The advertiser has not accepted the partner's terms of service. + ADVERTISER_TOS_NOT_ACCEPTED = 90; + + // The advertiser is not allowlisted for THIRD_PARTY_PARTNER_DATA. + ADVERTISER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA = 91; + + // This user list type is not supported for this account. + USER_LIST_TYPE_NOT_SUPPORTED_FOR_ACCOUNT = 92; + + // The `commerce_partner` field is invalid. + INVALID_COMMERCE_PARTNER = 93; + + // The data provider is not allowlisted to create commerce audiences. + CUSTOMER_NOT_ALLOWLISTED_FOR_COMMERCE_AUDIENCE = 94; + + // The user list upload key types are not supported. + UNSUPPORTED_USER_LIST_UPLOAD_KEY_TYPES = 95; + + // The ingested user list info config is not supported. + UNSUPPORTED_INGESTED_USER_LIST_INFO_CONFIG = 96; + + // The account types are not supported for the user list type. + UNSUPPORTED_ACCOUNT_TYPES_FOR_USER_LIST_TYPE = 97; + + // The account types are not supported for the partner link. + UNSUPPORTED_ACCOUNT_TYPE_FOR_PARTNER_LINK = 98; } diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/event.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/event.proto index 213af3f461c..0bd6ddd9c3a 100644 --- a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/event.proto +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/event.proto @@ -72,7 +72,7 @@ message Event { // Optional. The conversion value associated with the event, for value-based // conversions. - double conversion_value = 9 [(google.api.field_behavior) = OPTIONAL]; + optional double conversion_value = 9 [(google.api.field_behavior) = OPTIONAL]; // Optional. Signal for where the event happened (web, app, in-store, etc.). EventSource event_source = 10 [(google.api.field_behavior) = OPTIONAL]; diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/gender.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/gender.proto new file mode 100644 index 00000000000..c4f1f70a2a3 --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/gender.proto @@ -0,0 +1,40 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "GenderProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// The type of demographic genders (for example, female). +enum Gender { + // Not specified. + GENDER_UNSPECIFIED = 0; + + // Unknown. + GENDER_UNKNOWN = 1; + + // Male. + GENDER_MALE = 2; + + // Female. + GENDER_FEMALE = 3; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/insights_service.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/insights_service.proto new file mode 100644 index 00000000000..514df3aac4a --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/insights_service.proto @@ -0,0 +1,152 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/ads/datamanager/v1/age_range.proto"; +import "google/ads/datamanager/v1/gender.proto"; +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "InsightsServiceProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// Service to return insights on marketing data. +// +// This feature is only available to data partners. +service MarketingDataInsightsService { + option (google.api.default_host) = "datamanager.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/datamanager"; + + // Retrieves marketing data insights for a given user list. + // + // This feature is only available to data partners. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc RetrieveInsights(RetrieveInsightsRequest) + returns (RetrieveInsightsResponse) { + option (google.api.http) = { + post: "/v1/{parent=accountTypes/*/accounts/*}/insights:retrieve" + body: "*" + }; + } +} + +// Request message for DM API MarketingDataInsightsService.RetrieveInsights +message RetrieveInsightsRequest { + // Required. The parent account that owns the user list. + // Format: `accountTypes/{account_type}/accounts/{account}` + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. Baseline for the insights requested. + Baseline baseline = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The user list ID for which insights are requested. + string user_list_id = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// Baseline criteria against which insights are compared. +message Baseline { + // The baseline location of the request. Baseline location is on OR-list of + // ISO 3166-1 alpha-2 region codes of the requested regions. + message Location { + // List of ISO 3166-1 alpha-2 region codes. + repeated string region_codes = 1; + } + + // Baseline location against which insights are compared. + oneof baseline { + // The baseline location of the request. Baseline location is an OR-list + // of the requested regions. + Location baseline_location = 1; + + // If set to true, the service will try to automatically detect the + // baseline location for insights. + bool location_auto_detection_enabled = 2; + } +} + +// Response message for DM API MarketingDataInsightsService.RetrieveInsights +message RetrieveInsightsResponse { + // Insights for marketing data. + // + // This feature is only available to data partners. + message MarketingDataInsight { + // Possible dimensions for use in generating insights. + enum AudienceInsightsDimension { + // Not specified. + AUDIENCE_INSIGHTS_DIMENSION_UNSPECIFIED = 0; + + // The value is unknown in this version. + AUDIENCE_INSIGHTS_DIMENSION_UNKNOWN = 1; + + // An Affinity UserInterest. + AFFINITY_USER_INTEREST = 2; + + // An In-Market UserInterest. + IN_MARKET_USER_INTEREST = 3; + + // An age range. + AGE_RANGE = 4; + + // A gender. + GENDER = 5; + } + + // Insights for a collection of related attributes of the same dimension. + message MarketingDataInsightsAttribute { + // The user interest ID. + optional int64 user_interest_id = 1; + + // Measure of lift that the audience has for the attribute value as + // compared to the baseline. Range [0-1]. + optional float lift = 2; + + // Age range of the audience for which the lift is provided. + optional AgeRange age_range = 3; + + // Gender of the audience for which the lift is provided. + optional Gender gender = 4; + } + + // The dimension to which the insight belongs. + AudienceInsightsDimension dimension = 1; + + // Insights for values of a given dimension. + repeated MarketingDataInsightsAttribute attributes = 2; + } + + // Contains the insights for the marketing data. + repeated MarketingDataInsight marketing_data_insights = 1; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/partner_link_service.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/partner_link_service.proto new file mode 100644 index 00000000000..79a591b776c --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/partner_link_service.proto @@ -0,0 +1,224 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/ads/datamanager/v1/destination.proto"; +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/empty.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "PartnerLinkServiceProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// Service for managing partner links. +service PartnerLinkService { + option (google.api.default_host) = "datamanager.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/datamanager"; + + // Creates a partner link for the given account. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc CreatePartnerLink(CreatePartnerLinkRequest) returns (PartnerLink) { + option (google.api.http) = { + post: "/v1/{parent=accountTypes/*/accounts/*}/partnerLinks" + body: "partner_link" + }; + option (google.api.method_signature) = "parent,partner_link"; + } + + // Deletes a partner link for the given account. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc DeletePartnerLink(DeletePartnerLinkRequest) + returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=accountTypes/*/accounts/*/partnerLinks/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Searches for all partner links to and from a given account. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc SearchPartnerLinks(SearchPartnerLinksRequest) + returns (SearchPartnerLinksResponse) { + option (google.api.http) = { + get: "/v1/{parent=accountTypes/*/accounts/*}/partnerLinks:search" + }; + option (google.api.method_signature) = "parent"; + } +} + +// Request to create a [PartnerLink][google.ads.datamanager.v1.PartnerLink] +// resource. Returns a +// [PartnerLink][google.ads.datamanager.v1.PartnerLink]. +message CreatePartnerLinkRequest { + // Required. The parent, which owns this collection of partner links. + // Format: accountTypes/{account_type}/accounts/{account} + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/PartnerLink" + } + ]; + + // Required. The partner link to create. + PartnerLink partner_link = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// Request to delete a [PartnerLink][google.ads.datamanager.v1.PartnerLink] +// resource. Returns a [google.protobuf.Empty][google.protobuf.Empty]. +message DeletePartnerLinkRequest { + // Required. The resource name of the partner link to delete. + // Format: + // accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link} + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "datamanager.googleapis.com/PartnerLink" + } + ]; +} + +// Request to search for [PartnerLink][google.ads.datamanager.v1.PartnerLink] +// resources. Returns a +// [SearchPartnerLinksResponse][google.ads.datamanager.v1.SearchPartnerLinksResponse]. +message SearchPartnerLinksRequest { + // Required. Account to search for partner links. If no `filter` is specified, + // all partner links where this account is either the `owning_account` or + // `partner_account` are returned. + // + // Format: `accountTypes/{account_type}/accounts/{account}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/PartnerLink" + } + ]; + + // The maximum number of partner links to return. The service may return + // fewer than this value. + // If unspecified, at most 10 partner links will be returned. + // The maximum value is 100; values above 100 will be coerced to 100. + int32 page_size = 2; + + // A page token, received from a previous `SearchPartnerLinks` call. + // Provide this to retrieve the subsequent page. + // + // When paginating, all other parameters provided to `SearchPartnerLinks` + // must match the call that provided the page token. + string page_token = 3; + + // Optional. A [filter string](//google.aip.dev/160). All fields need to be on + // the left hand side of each condition (for example: `partner_link_id = + // 123456789`). + // + // Supported operations: + // + // - `AND` + // - `=` + // - `!=` + // + // Supported fields: + // + // - `partner_link_id` + // - `owning_account.account_type` + // - `owning_account.account_id` + // - `partner_account.account_type` + // - `partner_account.account_id` + // + // Example: + // `owning_account.account_type = "GOOGLE_ADS" OR partner_account.account_id = + // 987654321` + string filter = 4 [(google.api.field_behavior) = OPTIONAL]; +} + +// Response from the +// [SearchPartnerLinksRequest][google.ads.datamanager.v1.SearchPartnerLinksRequest]. +message SearchPartnerLinksResponse { + // The partner links for the given account. + repeated PartnerLink partner_links = 1; + + // A token, which can be sent as `page_token` to retrieve the next page. + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; +} + +// A partner link between an owning account and a partner account. +message PartnerLink { + option (google.api.resource) = { + type: "datamanager.googleapis.com/PartnerLink" + pattern: "accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}" + plural: "partnerLinks" + singular: "partnerLink" + }; + + // Identifier. The name of the partner link. + // Format: + // accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link} + string name = 1 [(google.api.field_behavior) = IDENTIFIER]; + + // Output only. The partner link ID. + string partner_link_id = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Required. The owning account granting access to the partner account. + ProductAccount owning_account = 3 [(google.api.field_behavior) = REQUIRED]; + + // Required. The partner account granted access by the owning account. + ProductAccount partner_account = 4 [(google.api.field_behavior) = REQUIRED]; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/request_status_per_destination.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/request_status_per_destination.proto index 739851242af..64ca0cbe033 100644 --- a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/request_status_per_destination.proto +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/request_status_per_destination.proto @@ -60,6 +60,12 @@ message RequestStatusPerDestination { // The status of the pair data ingestion to the destination. IngestPairDataStatus pair_data_ingestion_status = 3; + + // The status of the user id data ingestion to the destination. + IngestUserIdDataStatus user_id_data_ingestion_status = 4; + + // The status of the ppid data ingestion to the destination. + IngestPpidDataStatus ppid_data_ingestion_status = 5; } } @@ -75,6 +81,12 @@ message RequestStatusPerDestination { // The status of the pair data removal from the destination. RemovePairDataStatus pair_data_removal_status = 3; + + // The status of the user id data removal from the destination. + RemoveUserIdDataStatus user_id_data_removal_status = 4; + + // The status of the ppid data removal from the destination. + RemovePpidDataStatus ppid_data_removal_status = 5; } } @@ -170,6 +182,60 @@ message RequestStatusPerDestination { int64 pair_id_count = 2; } + // The status of the user id data ingestion to the destination containing + // stats related to the ingestion. + message IngestUserIdDataStatus { + // The total count of audience members sent in the upload request for the + // destination. Includes all audience members in the request, regardless of + // whether they were successfully ingested or not. + int64 record_count = 1; + + // The total count of user ids sent in the upload request for the + // destination. Includes all user ids in the request, regardless of + // whether they were successfully ingested or not. + int64 user_id_count = 2; + } + + // The status of the user id data removal from the destination. + message RemoveUserIdDataStatus { + // The total count of audience members sent in the removal request. Includes + // all audience members in the request, regardless of whether they were + // successfully removed or not. + int64 record_count = 1; + + // The total count of user ids sent in the removal request. Includes all + // user ids in the request, regardless of whether they were successfully + // removed or not. + int64 user_id_count = 2; + } + + // The status of the ppid data ingestion to the destination containing stats + // related to the ingestion. + message IngestPpidDataStatus { + // The total count of audience members sent in the upload request for the + // destination. Includes all audience members in the request, regardless of + // whether they were successfully ingested or not. + int64 record_count = 1; + + // The total count of ppids sent in the upload request for the + // destination. Includes all ppids in the request, regardless of + // whether they were successfully ingested or not. + int64 ppid_count = 2; + } + + // The status of the ppid data removal from the destination. + message RemovePpidDataStatus { + // The total count of audience members sent in the removal request. Includes + // all audience members in the request, regardless of whether they were + // successfully removed or not. + int64 record_count = 1; + + // The total count of ppids sent in the removal request. Includes all + // ppids in the request, regardless of whether they were successfully + // removed or not. + int64 ppid_count = 2; + } + // A destination within a DM API request. Destination destination = 1; diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list.proto new file mode 100644 index 00000000000..0f15917653e --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list.proto @@ -0,0 +1,423 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/duration.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// A user list resource. +message UserList { + option (google.api.resource) = { + type: "datamanager.googleapis.com/UserList" + pattern: "accountTypes/{account_type}/accounts/{account}/userLists/{user_list}" + plural: "userLists" + singular: "userList" + }; + + // Status of the user list. + enum MembershipStatus { + // Not specified. + MEMBERSHIP_STATUS_UNSPECIFIED = 0; + + // Open status - User list is accruing members and can be targeted to. + OPEN = 1; + + // Closed status - No new members being added. + CLOSED = 2; + } + + // Indicates the reason why the user list was closed. + // This enum is only used when a list is auto-closed by the system. + enum ClosingReason { + // Not specified. + CLOSING_REASON_UNSPECIFIED = 0; + + // The user list was closed because it has not been used in targeting + // recently. See https://support.google.com/google-ads/answer/2472738 + // for details. + UNUSED = 1; + } + + // Enum describing possible access reasons. + enum AccessReason { + // Not specified. + ACCESS_REASON_UNSPECIFIED = 0; + + // The resource is owned by the user. + OWNED = 1; + + // The resource is shared to the user. + SHARED = 2; + + // The resource is licensed to the user. + LICENSED = 3; + + // The user subscribed to the resource. + SUBSCRIBED = 4; + + // The resource is accessible to the user. + AFFILIATED = 5; + } + + // Indicates if this client still has access to the list. + enum AccessStatus { + // Not specified. + ACCESS_STATUS_UNSPECIFIED = 0; + + // The access is enabled. + ENABLED = 1; + + // The access is disabled. + DISABLED = 2; + } + + // Identifier. The resource name of the user list. + // Format: + // accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + string name = 1 [(google.api.field_behavior) = IDENTIFIER]; + + // Output only. The unique ID of the user list. + int64 id = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. An option that indicates if a user may edit a list. + bool read_only = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Required. The display name of the user list. + optional string display_name = 4 [(google.api.field_behavior) = REQUIRED]; + + // Optional. A description of the user list. + optional string description = 5 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Membership status of this user list. + optional MembershipStatus membership_status = 6 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. An ID from external system. It is used by user list sellers to + // correlate IDs on their systems. + optional string integration_code = 7 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The duration a user remains in the user list. + // Valid durations are exact multiples of 24 hours (86400 seconds). + // Providing a value that is not an exact multiple of 24 hours will result in + // an INVALID_ARGUMENT error. + google.protobuf.Duration membership_duration = 8 + [(google.api.field_behavior) = OPTIONAL]; + + // Output only. The reason why this user list membership status is closed. + optional ClosingReason closing_reason = 9 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The reason this account has been granted access to the list. + AccessReason access_reason = 10 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. Indicates if this share is still enabled. When a user list is + // shared with the account this field is set to `ENABLED`. Later the user list + // owner can decide to revoke the share and make it `DISABLED`. + optional AccessStatus account_access_status = 11 + [(google.api.field_behavior) = OPTIONAL]; + + // Output only. Estimated number of members in this user list in different + // target networks. + SizeInfo size_info = 12 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. Eligibility information for different target networks. + TargetNetworkInfo target_network_info = 13 + [(google.api.field_behavior) = OPTIONAL]; + + // Additional information about the user list. + oneof user_list_info { + // Optional. Represents a user list that is populated by user ingested data. + IngestedUserListInfo ingested_user_list_info = 14 + [(google.api.field_behavior) = OPTIONAL]; + } +} + +// Estimated number of members in this user list in different target networks. +message SizeInfo { + // Output only. Estimated number of members in this user list, on the Google + // Display Network. + int64 display_network_members_count = 1 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Estimated number of members in this user list in the + // google.com domain. These are the members available for targeting in Search + // campaigns. + int64 search_network_members_count = 2 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// Eligibility information for different target networks. +message TargetNetworkInfo { + // Output only. Indicates this user list is eligible for Google Display + // Network. + bool eligible_for_display = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. Indicates if this user list is eligible for Google Search + // Network. + optional bool eligible_for_search = 2 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Represents a user list that is populated by user provided data. +message IngestedUserListInfo { + // Enum containing the possible upload key types of a user list. + enum UploadKeyType { + // Not specified. + UPLOAD_KEY_TYPE_UNSPECIFIED = 0; + + // Customer info such as email address, phone number or physical address. + CONTACT_ID = 1; + + // Mobile advertising ids. + MOBILE_ID = 2; + + // Third party provided user ids. + USER_ID = 3; + + // Publisher advertiser identity reconciliation ids. + PAIR_ID = 4; + + // Data Management Platform IDs: + // - Google User ID + // - Partner Provided ID + // - Publisher Provided ID + // - iOS IDFA + // - Android advertising ID + // - Roku ID + // - Amazon Fire TV ID + // - Xbox or Microsoft ID + PSEUDONYMOUS_ID = 5; + } + + // Required. Immutable. Upload key types of this user list. + repeated UploadKeyType upload_key_types = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.field_behavior) = IMMUTABLE + ]; + + // Optional. Additional information when `CONTACT_ID` is one of the + // `upload_key_types`. + ContactIdInfo contact_id_info = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Additional information when `MOBILE_ID` is one of the + // `upload_key_types`. + MobileIdInfo mobile_id_info = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Additional information when `USER_ID` is one of the + // `upload_key_types`. + UserIdInfo user_id_info = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Additional information when `PAIR_ID` is one of the + // `upload_key_types`. + // + // This feature is only available to data partners. + PairIdInfo pair_id_info = 5 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Additional information for `PSEUDONYMOUS_ID` is one of the + // `upload_key_types`. + PseudonymousIdInfo pseudonymous_id_info = 6 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Additional information for partner audiences. + // + // This feature is only available to data partners. + PartnerAudienceInfo partner_audience_info = 7 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Additional information when `CONTACT_ID` is one of the `upload_key_types`. +message ContactIdInfo { + // Optional. Immutable. Source of the upload data + optional DataSourceType data_source_type = 1 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.field_behavior) = IMMUTABLE + ]; + + // Output only. Match rate for customer match user lists. + int32 match_rate_percentage = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// Additional information when `MOBILE_ID` is one of the `upload_key_types`. +message MobileIdInfo { + // Key space for mobile ID. + enum KeySpace { + // Not specified. + KEY_SPACE_UNSPECIFIED = 0; + + // The iOS keyspace. + IOS = 1; + + // The Android keyspace. + ANDROID = 2; + } + + // Optional. Immutable. Source of the upload data. + optional DataSourceType data_source_type = 1 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.field_behavior) = IMMUTABLE + ]; + + // Required. Immutable. The key space of mobile IDs. + optional KeySpace key_space = 2 [ + (google.api.field_behavior) = REQUIRED, + (google.api.field_behavior) = IMMUTABLE + ]; + + // Required. Immutable. A string that uniquely identifies a mobile application + // from which the data was collected. + optional string app_id = 3 [ + (google.api.field_behavior) = REQUIRED, + (google.api.field_behavior) = IMMUTABLE + ]; +} + +// Additional information when `USER_ID` is one of the `upload_key_types`. +message UserIdInfo { + // Optional. Immutable. Source of the upload data. + optional DataSourceType data_source_type = 1 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.field_behavior) = IMMUTABLE + ]; +} + +// Additional information when `PAIR_ID` is one of the `upload_key_types`. +// +// This feature is only available to data partners. +message PairIdInfo { + // Required. Immutable. Identifies the publisher that the Publisher Advertiser + // Identity Reconciliation user list is reconciled with. This field is + // provided by the cleanroom provider and is only unique in the scope of that + // cleanroom. This cannot be used as a global identifier across multiple + // cleanrooms. + optional int64 publisher_id = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.field_behavior) = IMMUTABLE + ]; + + // Optional. Descriptive name of the publisher to be displayed in the UI for a + // better targeting experience. + optional string publisher_name = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. This field denotes the percentage of membership match of this + // user list with the corresponding publisher's first party data. Must be + // between 0 and 100 inclusive. + int32 match_rate_percentage = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The count of the advertiser's first party data records that + // have been uploaded to a clean room provider. This does not signify the size + // of a PAIR user list. + int64 advertiser_identifier_count = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Required. Immutable. Identifies a unique advertiser to publisher + // relationship with one clean room provider or across multiple clean room + // providers. + optional string clean_room_identifier = 5 [ + (google.api.field_behavior) = REQUIRED, + (google.api.field_behavior) = IMMUTABLE + ]; +} + +// Additional information for partner audiences. +// +// This feature is only available to data partners. +message PartnerAudienceInfo { + // Partner audience source. + enum PartnerAudienceSource { + // Not specified. + PARTNER_AUDIENCE_SOURCE_UNSPECIFIED = 0; + + // Partner Audience source is commerce audience. + COMMERCE_AUDIENCE = 1; + + // Partner Audience source is linear TV audience. + LINEAR_TV_AUDIENCE = 2; + + // Partner Audience source is agency/provider audience. + AGENCY_PROVIDER_AUDIENCE = 3; + } + + // Required. Immutable. The source of the partner audience. + optional PartnerAudienceSource partner_audience_source = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.field_behavior) = IMMUTABLE + ]; + + // Optional. The commerce partner name. + // Only allowed if `partner_audience_source` is `COMMERCE_AUDIENCE`. + optional string commerce_partner = 2 [(google.api.field_behavior) = OPTIONAL]; +} + +// Additional information when `PSEUDONYMOUS_ID` is one of the +// `upload_key_types`. +message PseudonymousIdInfo { + // Sync status of the user list. + enum SyncStatus { + // Not specified. + SYNC_STATUS_UNSPECIFIED = 0; + + // The user list has been created as a placeholder. List contents and/or + // metadata are still being synced. The user list is not ready for use. + CREATED = 1; + + // The user list is ready for use. Contents and cookies have been synced + // correctly. + READY_FOR_USE = 2; + + // An error has occurred syncing user list contents and/or metadata. The + // user list cannot be used. + FAILED = 3; + } + + // Output only. Sync status of the user list. + optional SyncStatus sync_status = 1 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. Immutable. The number of billable records (e.g. uploaded or + // matched). + optional int64 billable_record_count = 2 [ + (google.api.field_behavior) = OPTIONAL, + (google.api.field_behavior) = IMMUTABLE + ]; +} + +// Indicates source of upload data. +enum DataSourceType { + // Not specified. + DATA_SOURCE_TYPE_UNSPECIFIED = 0; + + // The uploaded data is first-party data. + DATA_SOURCE_TYPE_FIRST_PARTY = 1; + + // The uploaded data is from a third-party credit bureau. + DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU = 2; + + // The uploaded data is from a third-party voter file. + DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE = 3; + + // The uploaded data is third party partner data. + DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA = 4; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_direct_license.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_direct_license.proto new file mode 100644 index 00000000000..44962539c41 --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_direct_license.proto @@ -0,0 +1,91 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/ads/datamanager/v1/user_list_license_client_account_type.proto"; +import "google/ads/datamanager/v1/user_list_license_metrics.proto"; +import "google/ads/datamanager/v1/user_list_license_pricing.proto"; +import "google/ads/datamanager/v1/user_list_license_status.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListDirectLicenseProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// A user list direct license. +// +// This feature is only available to data partners. +message UserListDirectLicense { + option (google.api.resource) = { + type: "datamanager.googleapis.com/UserListDirectLicense" + pattern: "accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}" + plural: "userListDirectLicenses" + singular: "userListDirectLicense" + }; + + // Identifier. The resource name of the user list direct license. + string name = 1 [(google.api.field_behavior) = IDENTIFIER]; + + // Immutable. ID of the user list being licensed. + optional int64 user_list_id = 2 [(google.api.field_behavior) = IMMUTABLE]; + + // Output only. Name of the user list being licensed. + // + // This field is read-only. + string user_list_display_name = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Immutable. Account type of client customer which the user list is being + // licensed to. + optional UserListLicenseClientAccountType client_account_type = 4 + [(google.api.field_behavior) = IMMUTABLE]; + + // Immutable. ID of client customer which the user list is being licensed to. + optional int64 client_account_id = 5 + [(google.api.field_behavior) = IMMUTABLE]; + + // Output only. Name of client customer which the user list is being licensed + // to. + // + // This field is read-only. + string client_account_display_name = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. Status of UserListDirectLicense - ENABLED or DISABLED. + optional UserListLicenseStatus status = 7 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. UserListDirectLicense pricing. + UserListLicensePricing pricing = 8 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. Pricing history of this user list license. + // + // This field is read-only. + repeated UserListLicensePricing historical_pricings = 9 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Metrics related to this license + // + // This field is read-only and only populated if the start and end dates are + // set in the ListUserListDirectLicenses call + UserListLicenseMetrics metrics = 10 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_direct_license_service.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_direct_license_service.proto new file mode 100644 index 00000000000..4964f57d276 --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_direct_license_service.proto @@ -0,0 +1,197 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/ads/datamanager/v1/user_list_direct_license.proto"; +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListDirectLicenseServiceProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// Service for managing user list direct licenses. Delete is not a supported +// operation for UserListDirectLicenses. Callers should update the +// license status to DISABLED to instead to deactivate a license. +// +// This feature is only available to data partners. +service UserListDirectLicenseService { + option (google.api.default_host) = "datamanager.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/datamanager"; + + // Creates a user list direct license. + // + // This feature is only available to data partners. + rpc CreateUserListDirectLicense(CreateUserListDirectLicenseRequest) + returns (UserListDirectLicense) { + option (google.api.http) = { + post: "/v1/{parent=accountTypes/*/accounts/*}/userListDirectLicenses" + body: "user_list_direct_license" + }; + option (google.api.method_signature) = "parent,user_list_direct_license"; + } + + // Retrieves a user list direct license. + // + // This feature is only available to data partners. + rpc GetUserListDirectLicense(GetUserListDirectLicenseRequest) + returns (UserListDirectLicense) { + option (google.api.http) = { + get: "/v1/{name=accountTypes/*/accounts/*/userListDirectLicenses/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Updates a user list direct license. + // + // This feature is only available to data partners. + rpc UpdateUserListDirectLicense(UpdateUserListDirectLicenseRequest) + returns (UserListDirectLicense) { + option (google.api.http) = { + patch: "/v1/{user_list_direct_license.name=accountTypes/*/accounts/*/userListDirectLicenses/*}" + body: "user_list_direct_license" + }; + option (google.api.method_signature) = + "user_list_direct_license,update_mask"; + } + + // Lists all user list direct licenses owned by the parent account. + // + // This feature is only available to data partners. + rpc ListUserListDirectLicenses(ListUserListDirectLicensesRequest) + returns (ListUserListDirectLicensesResponse) { + option (google.api.http) = { + get: "/v1/{parent=accountTypes/*/accounts/*}/userListDirectLicenses" + }; + option (google.api.method_signature) = "parent"; + } +} + +// Request to create a +// [UserListDirectLicense][google.ads.datamanager.v1.UserListDirectLicense] +// resource. +message CreateUserListDirectLicenseRequest { + // Required. The account that owns the user list being licensed. Should be in + // the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/UserListDirectLicense" + } + ]; + + // Required. The user list direct license to create. + UserListDirectLicense user_list_direct_license = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// Request to get a +// [UserListDirectLicense][google.ads.datamanager.v1.UserListDirectLicense] +// resource. +message GetUserListDirectLicenseRequest { + // Required. The resource name of the user list direct license. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "datamanager.googleapis.com/UserListDirectLicense" + } + ]; +} + +// Request to update a +// [UserListDirectLicense][google.ads.datamanager.v1.UserListDirectLicense] +// resource. +message UpdateUserListDirectLicenseRequest { + // Required. The licenses' `name` field is used to identify the license to + // update. + UserListDirectLicense user_list_direct_license = 1 + [(google.api.field_behavior) = REQUIRED]; + + // Optional. The list of fields to update. The special character `*` is not + // supported and an `INVALID_UPDATE_MASK` error will be thrown if used. + google.protobuf.FieldMask update_mask = 2 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Request to list all +// [UserListDirectLicense][google.ads.datamanager.v1.UserListDirectLicense] +// resources for a given account. +message ListUserListDirectLicensesRequest { + // Required. The account whose licenses are being queried. Should be in the + // format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/UserListDirectLicense" + } + ]; + + // Optional. Filters to apply to the list request. All fields need to be on + // the left hand side of each condition (for example: user_list_id = 123). + // + // **Supported Operations:** + // + // - `AND` + // - `=` + // - `!=` + // - `>` + // - `>=` + // - `<` + // - `<=` + // + // **Unsupported Fields:** + // + // - `name` (use get method instead) + // - `historical_pricings` and all its subfields + // - `pricing.start_time` + // - `pricing.end_time` + string filter = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The maximum number of licenses to return per page. The service + // may return fewer than this value. If unspecified, at most 50 licenses will + // be returned. The maximum value is 1000; values above 1000 will be coerced + // to 1000. + int32 page_size = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A page token, received from a previous + // `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + // page. + // + // When paginating, all other parameters provided to + // `ListUserListDirectLicense` must match the call that provided the page + // token. + string page_token = 4 [(google.api.field_behavior) = OPTIONAL]; +} + +// Response from the +// [ListUserListDirectLicensesRequest][google.ads.datamanager.v1.ListUserListDirectLicensesRequest]. +message ListUserListDirectLicensesResponse { + // The licenses for the given user list in the request. + repeated UserListDirectLicense user_list_direct_licenses = 1; + + // A token, which can be sent as `page_token` to retrieve the next page. + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license.proto new file mode 100644 index 00000000000..2e0f57ca3cc --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license.proto @@ -0,0 +1,139 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/ads/datamanager/v1/user_list_global_license_type.proto"; +import "google/ads/datamanager/v1/user_list_license_client_account_type.proto"; +import "google/ads/datamanager/v1/user_list_license_metrics.proto"; +import "google/ads/datamanager/v1/user_list_license_pricing.proto"; +import "google/ads/datamanager/v1/user_list_license_status.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListGlobalLicenseProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// A user list global license. +// +// This feature is only available to data partners. +message UserListGlobalLicense { + option (google.api.resource) = { + type: "datamanager.googleapis.com/UserListGlobalLicense" + pattern: "accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}" + plural: "userListGlobalLicenses" + singular: "userListGlobalLicense" + }; + + // Identifier. The resource name of the user list global license. + string name = 1 [(google.api.field_behavior) = IDENTIFIER]; + + // Immutable. ID of the user list being licensed. + optional int64 user_list_id = 2 [(google.api.field_behavior) = IMMUTABLE]; + + // Output only. Name of the user list being licensed. + // + // This field is read-only. + string user_list_display_name = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Immutable. Product type of client customer which the user list is being + // licensed to. + optional UserListGlobalLicenseType license_type = 4 + [(google.api.field_behavior) = IMMUTABLE]; + + // Optional. Status of UserListGlobalLicense - ENABLED or DISABLED. + optional UserListLicenseStatus status = 5 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. UserListGlobalLicense pricing. + UserListLicensePricing pricing = 6 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. Pricing history of this user list license. + // + // This field is read-only. + repeated UserListLicensePricing historical_pricings = 7 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Metrics related to this license + // + // This field is read-only and only populated if the start and end dates are + // set in the ListUserListGlobalLicenses call + UserListLicenseMetrics metrics = 8 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// Information about a customer of a user list global license. This will +// automatically be created by the system when a customer purchases a global +// license. +message UserListGlobalLicenseCustomerInfo { + option (google.api.resource) = { + type: "datamanager.googleapis.com/UserListGlobalLicenseCustomerInfo" + pattern: "accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}" + plural: "userListGlobalLicenseCustomerInfos" + singular: "userListGlobalLicenseCustomerInfo" + }; + + // Identifier. The resource name of the user list global license customer. + string name = 1 [(google.api.field_behavior) = IDENTIFIER]; + + // Output only. ID of the user list being licensed. + int64 user_list_id = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Name of the user list being licensed. + string user_list_display_name = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Product type of client customer which the user list is being + // licensed to. + UserListGlobalLicenseType license_type = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Status of UserListDirectLicense - ENABLED or DISABLED. + UserListLicenseStatus status = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. UserListDirectLicense pricing. + UserListLicensePricing pricing = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Product type of client customer which the user list is being + // licensed to. + UserListLicenseClientAccountType client_account_type = 7 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. ID of client customer which the user list is being licensed + // to. + int64 client_account_id = 8 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Name of client customer which the user list is being licensed + // to. + string client_account_display_name = 9 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Pricing history of this user list license. + repeated UserListLicensePricing historical_pricings = 10 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Metrics related to this license + // + // This field is only populated if the start and end dates are set in the + // ListUserListGlobalLicenseCustomerInfos call. + UserListLicenseMetrics metrics = 11 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license_service.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license_service.proto new file mode 100644 index 00000000000..26d8335ae72 --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license_service.proto @@ -0,0 +1,275 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/ads/datamanager/v1/user_list_global_license.proto"; +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListGlobalLicenseServiceProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// Service for managing user list global licenses. Delete is not a supported +// operation for UserListGlobalLicenses. Callers should update the +// license status to DISABLED to instead to deactivate a license. +// +// This feature is only available to data partners. +service UserListGlobalLicenseService { + option (google.api.default_host) = "datamanager.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/datamanager"; + + // Creates a user list global license. + // + // This feature is only available to data partners. + rpc CreateUserListGlobalLicense(CreateUserListGlobalLicenseRequest) + returns (UserListGlobalLicense) { + option (google.api.http) = { + post: "/v1/{parent=accountTypes/*/accounts/*}/userListGlobalLicenses" + body: "user_list_global_license" + }; + option (google.api.method_signature) = "parent,user_list_global_license"; + } + + // Updates a user list global license. + // + // This feature is only available to data partners. + rpc UpdateUserListGlobalLicense(UpdateUserListGlobalLicenseRequest) + returns (UserListGlobalLicense) { + option (google.api.http) = { + patch: "/v1/{user_list_global_license.name=accountTypes/*/accounts/*/userListGlobalLicenses/*}" + body: "user_list_global_license" + }; + option (google.api.method_signature) = + "user_list_global_license,update_mask"; + } + + // Retrieves a user list global license. + // + // This feature is only available to data partners. + rpc GetUserListGlobalLicense(GetUserListGlobalLicenseRequest) + returns (UserListGlobalLicense) { + option (google.api.http) = { + get: "/v1/{name=accountTypes/*/accounts/*/userListGlobalLicenses/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists all user list global licenses owned by the parent account. + // + // This feature is only available to data partners. + rpc ListUserListGlobalLicenses(ListUserListGlobalLicensesRequest) + returns (ListUserListGlobalLicensesResponse) { + option (google.api.http) = { + get: "/v1/{parent=accountTypes/*/accounts/*}/userListGlobalLicenses" + }; + option (google.api.method_signature) = "parent"; + } + + // Lists all customer info for a user list global license. + // + // This feature is only available to data partners. + rpc ListUserListGlobalLicenseCustomerInfos( + ListUserListGlobalLicenseCustomerInfosRequest) + returns (ListUserListGlobalLicenseCustomerInfosResponse) { + option (google.api.http) = { + get: "/v1/{parent=accountTypes/*/accounts/*/userListGlobalLicenses/*}/userListGlobalLicenseCustomerInfos" + }; + option (google.api.method_signature) = "parent"; + } +} + +// Request to create a +// [UserListGlobalLicense][google.ads.datamanager.v1.UserListGlobalLicense] +// resource. +message CreateUserListGlobalLicenseRequest { + // Required. The account that owns the user list being licensed. Should be in + // the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/UserListGlobalLicense" + } + ]; + + // Required. The user list global license to create. + UserListGlobalLicense user_list_global_license = 2 + [(google.api.field_behavior) = REQUIRED]; +} + +// Request to update a +// [UserListGlobalLicense][google.ads.datamanager.v1.UserListGlobalLicense] +// resource. +message UpdateUserListGlobalLicenseRequest { + // Required. The licenses' `name` field is used to identify the license to + // update. + UserListGlobalLicense user_list_global_license = 1 + [(google.api.field_behavior) = REQUIRED]; + + // Optional. The list of fields to update. The special character `*` is not + // supported and an `INVALID_UPDATE_MASK` error will be thrown if used. + google.protobuf.FieldMask update_mask = 2 + [(google.api.field_behavior) = OPTIONAL]; +} + +// Request to get a +// [UserListGlobalLicense][google.ads.datamanager.v1.UserListGlobalLicense] +// resource. +message GetUserListGlobalLicenseRequest { + // Required. The resource name of the user list global license. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "datamanager.googleapis.com/UserListGlobalLicense" + } + ]; +} + +// Request to list all +// [UserListGlobalLicense][google.ads.datamanager.v1.UserListGlobalLicense] +// resources for a given account. +message ListUserListGlobalLicensesRequest { + // Required. The account whose licenses are being queried. Should be in the + // format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/UserListGlobalLicense" + } + ]; + + // Optional. Filters to apply to the list request. All fields need to be on + // the left hand side of each condition (for example: user_list_id = 123). + // + // **Supported Operations:** + // + // - `AND` + // - `=` + // - `!=` + // - `>` + // - `>=` + // - `<` + // - `<=` + // + // **Unsupported Fields:** + // + // - `name` (use get method instead) + // - `historical_pricings` and all its subfields + // - `pricing.start_time` + // - `pricing.end_time` + string filter = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The maximum number of licenses to return. The service may return + // fewer than this value. If unspecified, at most 50 licenses will be + // returned. The maximum value is 1000; values above 1000 will be coerced to + // 1000. + int32 page_size = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A page token, received from a previous + // `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent + // page. + // + // When paginating, all other parameters provided to + // `ListUserListDirectLicense` must match the call that provided the page + // token. + string page_token = 4 [(google.api.field_behavior) = OPTIONAL]; +} + +// Response from the +// [ListUserListGlobalLicensesRequest][google.ads.datamanager.v1.ListUserListGlobalLicensesRequest]. +message ListUserListGlobalLicensesResponse { + // The licenses for the given user list in the request. + repeated UserListGlobalLicense user_list_global_licenses = 1; + + // A token, which can be sent as `page_token` to retrieve the next page. + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; +} + +// Request to list all +// [UserListGlobalLicenseCustomerInfo][google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo] +// resources for a given user list global license. +message ListUserListGlobalLicenseCustomerInfosRequest { + // Required. The global license whose customer info are being queried. Should + // be in the format + // `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. + // To list all global license customer info under an account, replace the user + // list global license id with a '-' (for example, + // `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/UserListGlobalLicenseCustomerInfo" + } + ]; + + // Optional. Filters to apply to the list request. All fields need to be on + // the left hand side of each condition (for example: user_list_id = 123). + // + // **Supported Operations:** + // + // - `AND` + // - `=` + // - `!=` + // - `>` + // - `>=` + // - `<` + // - `<=` + // + // **Unsupported Fields:** + // + // - `name` (use get method instead) + // - `historical_pricings` and all its subfields + // - `pricing.start_time` + // - `pricing.end_time` + string filter = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The maximum number of licenses to return. The service may return + // fewer than this value. If unspecified, at most 50 licenses will be + // returned. The maximum value is 1000; values above 1000 will be coerced to + // 1000. + int32 page_size = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A page token, received from a previous + // `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + // page. + // + // When paginating, all other parameters provided to + // `ListUserListDirectLicense` must match the call that provided the page + // token. + string page_token = 4 [(google.api.field_behavior) = OPTIONAL]; +} + +// Response from the +// [ListUserListGlobalLicensesCustomerInfoRequest][google.ads.datamanager.v1.ListUserListGlobalLicensesCustomerInfoRequest]. +message ListUserListGlobalLicenseCustomerInfosResponse { + // The customer information for the given license in the request. + repeated UserListGlobalLicenseCustomerInfo + user_list_global_license_customer_infos = 1; + + // A token, which can be sent as `page_token` to retrieve the next page. + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license_type.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license_type.proto new file mode 100644 index 00000000000..f85d9ed6b74 --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_global_license_type.proto @@ -0,0 +1,40 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListGlobalLicenseTypeProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// User list global license types. +enum UserListGlobalLicenseType { + // UNSPECIFIED. + USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED = 0; + + // Reseller license. + USER_LIST_GLOBAL_LICENSE_TYPE_RESELLER = 1; + + // DataMart Sell Side license. + USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_SELL_SIDE = 2; + + // DataMart Buy Side license. + USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_BUY_SIDE = 3; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto new file mode 100644 index 00000000000..b116e0567f4 --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto @@ -0,0 +1,43 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListLicenseClientAccountTypeProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// Possible product of a client account for a user list license. +enum UserListLicenseClientAccountType { + // Unknown. + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN = 0; + + // Google Ads customer. + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_ADS = 1; + + // Display & Video 360 partner. + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_PARTNER = 2; + + // Display & Video 360 advertiser. + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_ADVERTISER = 3; + + // Google Ad Manager audience link. + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_AD_MANAGER_AUDIENCE_LINK = 4; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_metrics.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_metrics.proto new file mode 100644 index 00000000000..0aceb2c6951 --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_metrics.proto @@ -0,0 +1,53 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/api/field_behavior.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListLicenseMetricsProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// Metrics related to a user list license. +message UserListLicenseMetrics { + // Output only. The number of clicks for the user list license. + int64 click_count = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The number of impressions for the user list license. + int64 impression_count = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The revenue for the user list license in USD micros. + int64 revenue_usd_micros = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The start date (inclusive) of the metrics in the format + // YYYYMMDD. For example, 20260102 represents January 2, 2026. If `end_date` + // is used in the filter, `start_date` is also required. If neither + // `start_date` nor `end_date` are included in the filter, the + // UserListLicenseMetrics fields will not be populated in the response. + int64 start_date = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The end date (inclusive) of the metrics in the format + // YYYYMMDD. For example, 20260102 represents January 2, 2026. If `start_date` + // is used in the filter, `end_date` is also required. If neither `start_date` + // nor `end_date` are included in the filter, the UserListLicenseMetrics + // fields will not be populated in the response. + int64 end_date = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_pricing.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_pricing.proto new file mode 100644 index 00000000000..c8712b7de1a --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_pricing.proto @@ -0,0 +1,111 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/api/field_behavior.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListLicensePricingProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// A user list license pricing. +message UserListLicensePricing { + // User list pricing buyer approval state. + enum UserListPricingBuyerApprovalState { + // UNSPECIFIED. + USER_LIST_PRICING_BUYER_APPROVAL_STATE_UNSPECIFIED = 0; + + // User list client has not yet accepted the pricing terms set by the user + // list owner. + PENDING = 1; + + // User list client has accepted the pricing terms set by the user list + // owner. + APPROVED = 2; + + // User list client has rejected the pricing terms set by the user list + // owner. + REJECTED = 3; + } + + // User list pricing cost type. + enum UserListPricingCostType { + // Unspecified. + USER_LIST_PRICING_COST_TYPE_UNSPECIFIED = 0; + + // Cost per click. + CPC = 1; + + // Cost per mille (thousand impressions). + CPM = 2; + + // Media share. + MEDIA_SHARE = 3; + } + + // Output only. The ID of this pricing. + int64 pricing_id = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. The cost associated with the model, in micro units (10^-6), in + // the currency specified by the currency_code field. For example, 2000000 + // means $2 if `currency_code` is `USD`. + optional int64 cost_micros = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The currency in which cost and max_cost is specified. Must be a + // three-letter currency code defined in ISO 4217. + optional string currency_code = 9 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. Start time of the pricing. + google.protobuf.Timestamp start_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Optional. End time of the pricing. + google.protobuf.Timestamp end_time = 4 + [(google.api.field_behavior) = OPTIONAL]; + + // Output only. Whether this pricing is active. + bool pricing_active = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The buyer approval state of this pricing. + // + // This field is read-only. + UserListPricingBuyerApprovalState buyer_approval_state = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Immutable. The cost type of this pricing. + // + // Can be set only in the `create` operation. Can't be updated for + // an existing license. + optional UserListPricingCostType cost_type = 7 + [(google.api.field_behavior) = IMMUTABLE]; + + // Optional. The maximum CPM a commerce audience can be charged when the + // MEDIA_SHARE cost type is used. The value is in micro units (10^-6) and in + // the currency specified by the currency_code field. For example, 2000000 + // means $2 if `currency_code` is `USD`. + // + // This is only relevant when cost_type is MEDIA_SHARE. + // When cost_type is not MEDIA_SHARE, and this field is set, a + // MAX_COST_NOT_ALLOWED error will be returned. + // If not set or set to`0`, there is no cap. + optional int64 max_cost_micros = 8 [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_status.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_status.proto new file mode 100644 index 00000000000..5a16e961d04 --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_license_status.proto @@ -0,0 +1,37 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListLicenseStatusProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// User list license status. +enum UserListLicenseStatus { + // Unknown. + USER_LIST_LICENSE_STATUS_UNSPECIFIED = 0; + + // Active status - user list is still being licensed. + USER_LIST_LICENSE_STATUS_ENABLED = 1; + + // Inactive status - user list is no longer being licensed. + USER_LIST_LICENSE_STATUS_DISABLED = 2; +} diff --git a/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_service.proto b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_service.proto new file mode 100644 index 00000000000..8a7595f46df --- /dev/null +++ b/packages/google-ads-datamanager/protos/google/ads/datamanager/v1/user_list_service.proto @@ -0,0 +1,272 @@ +// Copyright 2026 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. + +syntax = "proto3"; + +package google.ads.datamanager.v1; + +import "google/ads/datamanager/v1/user_list.proto"; +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/empty.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Ads.DataManager.V1"; +option go_package = "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb"; +option java_multiple_files = true; +option java_outer_classname = "UserListServiceProto"; +option java_package = "com.google.ads.datamanager.v1"; +option php_namespace = "Google\\Ads\\DataManager\\V1"; +option ruby_package = "Google::Ads::DataManager::V1"; + +// Service for managing UserList resources. +service UserListService { + option (google.api.default_host) = "datamanager.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/datamanager"; + + // Gets a UserList. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc GetUserList(GetUserListRequest) returns (UserList) { + option (google.api.http) = { + get: "/v1/{name=accountTypes/*/accounts/*/userLists/*}" + }; + option (google.api.method_signature) = "name"; + } + + // Lists UserLists. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc ListUserLists(ListUserListsRequest) returns (ListUserListsResponse) { + option (google.api.http) = { + get: "/v1/{parent=accountTypes/*/accounts/*}/userLists" + }; + option (google.api.method_signature) = "parent"; + } + + // Creates a UserList. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc CreateUserList(CreateUserListRequest) returns (UserList) { + option (google.api.http) = { + post: "/v1/{parent=accountTypes/*/accounts/*}/userLists" + body: "user_list" + }; + option (google.api.method_signature) = "parent,user_list"; + } + + // Updates a UserList. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc UpdateUserList(UpdateUserListRequest) returns (UserList) { + option (google.api.http) = { + patch: "/v1/{user_list.name=accountTypes/*/accounts/*/userLists/*}" + body: "user_list" + }; + option (google.api.method_signature) = "user_list,update_mask"; + } + + // Deletes a UserList. + // + // Authorization Headers: + // + // This method supports the following optional headers to define how the API + // authorizes access for the request: + // + // * `login-account`: (Optional) The resource name of the account where the + // Google Account of the credentials is a user. If not set, defaults to the + // account of the request. Format: + // `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + // * `linked-account`: (Optional) The resource name of the account with an + // established product link to the `login-account`. Format: + // `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + rpc DeleteUserList(DeleteUserListRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=accountTypes/*/accounts/*/userLists/*}" + }; + option (google.api.method_signature) = "name"; + } +} + +// Request message for GetUserList. +message GetUserListRequest { + // Required. The resource name of the UserList to retrieve. + // Format: + // accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "datamanager.googleapis.com/UserList" + } + ]; +} + +// Request message for ListUserLists. +message ListUserListsRequest { + // Required. The parent account which owns this collection of user lists. + // Format: accountTypes/{account_type}/accounts/{account} + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/UserList" + } + ]; + + // Optional. The maximum number of user lists to return. The service may + // return fewer than this value. If unspecified, at most 50 user lists will be + // returned. The maximum value is 1000; values above 1000 will be coerced to + // 1000. + int32 page_size = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A page token, received from a previous `ListUserLists` call. + // Provide this to retrieve the subsequent page. + // + // When paginating, all other parameters provided to `ListUserLists` must + // match the call that provided the page token. + string page_token = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. A [filter string](//google.aip.dev/160). All fields need to be on + // the left hand side of each condition (for example: `display_name = "list + // 1"`). + // + // Supported operations: + // + // - `AND` + // - `=` + // - `!=` + // - `>` + // - `>=` + // - `<` + // - `<=` + // - `:` (has) + // + // Supported fields: + // + // - `id` + // - `display_name` + // - `description` + // - `membership_status` + // - `integration_code` + // - `access_reason` + // - `ingested_user_list_info.upload_key_types` + string filter = 4 [(google.api.field_behavior) = OPTIONAL]; +} + +// Response message for ListUserLists. +message ListUserListsResponse { + // The user lists from the specified account. + repeated UserList user_lists = 1; + + // A token, which can be sent as `page_token` to retrieve the next page. + // If this field is omitted, there are no subsequent pages. + string next_page_token = 2; +} + +// Request message for CreateUserList. +message CreateUserListRequest { + // Required. The parent account where this user list will be created. + // Format: accountTypes/{account_type}/accounts/{account} + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "datamanager.googleapis.com/UserList" + } + ]; + + // Required. The user list to create. + UserList user_list = 2 [(google.api.field_behavior) = REQUIRED]; + + // Optional. If true, the request is validated but not executed. + bool validate_only = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// Request message for UpdateUserList. +message UpdateUserListRequest { + // Required. The user list to update. + // + // The user list's `name` field is used to identify the user list to update. + // Format: + // accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + UserList user_list = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The list of fields to update. + google.protobuf.FieldMask update_mask = 2 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. If true, the request is validated but not executed. + bool validate_only = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// Request message for DeleteUserList. +message DeleteUserListRequest { + // Required. The name of the user list to delete. + // Format: + // accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "datamanager.googleapis.com/UserList" + } + ]; + + // Optional. If true, the request is validated but not executed. + bool validate_only = 2 [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/packages/google-ads-datamanager/protos/protos.d.ts b/packages/google-ads-datamanager/protos/protos.d.ts index 1df2fdf013e..db34d7f0bd5 100644 --- a/packages/google-ads-datamanager/protos/protos.d.ts +++ b/packages/google-ads-datamanager/protos/protos.d.ts @@ -26,6 +26,18 @@ export namespace google { /** Namespace v1. */ namespace v1 { + /** AgeRange enum. */ + enum AgeRange { + AGE_RANGE_UNSPECIFIED = 0, + AGE_RANGE_UNKNOWN = 1, + AGE_RANGE_18_24 = 2, + AGE_RANGE_25_34 = 3, + AGE_RANGE_35_44 = 4, + AGE_RANGE_45_54 = 5, + AGE_RANGE_55_64 = 6, + AGE_RANGE_65_UP = 7 + } + /** Properties of an AudienceMember. */ interface IAudienceMember { @@ -41,6 +53,12 @@ export namespace google { /** AudienceMember mobileData */ mobileData?: (google.ads.datamanager.v1.IMobileData|null); + /** AudienceMember userIdData */ + userIdData?: (google.ads.datamanager.v1.IUserIdData|null); + + /** AudienceMember ppidData */ + ppidData?: (google.ads.datamanager.v1.IPpidData|null); + /** AudienceMember consent */ consent?: (google.ads.datamanager.v1.IConsent|null); } @@ -66,11 +84,17 @@ export namespace google { /** AudienceMember mobileData. */ public mobileData?: (google.ads.datamanager.v1.IMobileData|null); + /** AudienceMember userIdData. */ + public userIdData?: (google.ads.datamanager.v1.IUserIdData|null); + + /** AudienceMember ppidData. */ + public ppidData?: (google.ads.datamanager.v1.IPpidData|null); + /** AudienceMember consent. */ public consent?: (google.ads.datamanager.v1.IConsent|null); /** AudienceMember data. */ - public data?: ("userData"|"pairData"|"mobileData"); + public data?: ("userData"|"pairData"|"mobileData"|"userIdData"|"ppidData"); /** * Creates a new AudienceMember instance using the specified properties. @@ -344,6 +368,200 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a UserIdData. */ + interface IUserIdData { + + /** UserIdData userId */ + userId?: (string|null); + } + + /** Represents a UserIdData. */ + class UserIdData implements IUserIdData { + + /** + * Constructs a new UserIdData. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUserIdData); + + /** UserIdData userId. */ + public userId: string; + + /** + * Creates a new UserIdData instance using the specified properties. + * @param [properties] Properties to set + * @returns UserIdData instance + */ + public static create(properties?: google.ads.datamanager.v1.IUserIdData): google.ads.datamanager.v1.UserIdData; + + /** + * Encodes the specified UserIdData message. Does not implicitly {@link google.ads.datamanager.v1.UserIdData.verify|verify} messages. + * @param message UserIdData message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUserIdData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UserIdData message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserIdData.verify|verify} messages. + * @param message UserIdData message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUserIdData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a UserIdData message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UserIdData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UserIdData; + + /** + * Decodes a UserIdData message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UserIdData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UserIdData; + + /** + * Verifies a UserIdData message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a UserIdData message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserIdData + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UserIdData; + + /** + * Creates a plain object from a UserIdData message. Also converts values to other types if specified. + * @param message UserIdData + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UserIdData, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserIdData to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserIdData + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PpidData. */ + interface IPpidData { + + /** PpidData ppids */ + ppids?: (string[]|null); + } + + /** Represents a PpidData. */ + class PpidData implements IPpidData { + + /** + * Constructs a new PpidData. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IPpidData); + + /** PpidData ppids. */ + public ppids: string[]; + + /** + * Creates a new PpidData instance using the specified properties. + * @param [properties] Properties to set + * @returns PpidData instance + */ + public static create(properties?: google.ads.datamanager.v1.IPpidData): google.ads.datamanager.v1.PpidData; + + /** + * Encodes the specified PpidData message. Does not implicitly {@link google.ads.datamanager.v1.PpidData.verify|verify} messages. + * @param message PpidData message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IPpidData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PpidData message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PpidData.verify|verify} messages. + * @param message PpidData message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IPpidData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PpidData message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PpidData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.PpidData; + + /** + * Decodes a PpidData message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PpidData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.PpidData; + + /** + * Verifies a PpidData message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PpidData message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PpidData + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.PpidData; + + /** + * Creates a plain object from a PpidData message. Also converts values to other types if specified. + * @param message PpidData + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.PpidData, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PpidData to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PpidData + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a Consent. */ interface IConsent { @@ -1362,7 +1580,8 @@ export namespace google { DISPLAY_VIDEO_PARTNER = 2, DISPLAY_VIDEO_ADVERTISER = 3, DATA_PARTNER = 4, - GOOGLE_ANALYTICS_PROPERTY = 5 + GOOGLE_ANALYTICS_PROPERTY = 5, + GOOGLE_AD_MANAGER_AUDIENCE_LINK = 6 } } @@ -1885,7 +2104,54 @@ export namespace google { INVALID_REQUEST_ID = 48, MULTIPLE_DESTINATIONS_FOR_GOOGLE_ANALYTICS_EVENT = 49, FIELD_VALUE_TOO_LONG = 50, - TOO_MANY_ELEMENTS = 51 + TOO_MANY_ELEMENTS = 51, + ALREADY_EXISTS = 52, + IMMUTABLE_FIELD_FOR_UPDATE = 53, + INVALID_RESOURCE_NAME = 54, + INVALID_FILTER = 55, + INVALID_UPDATE_MASK = 56, + INVALID_PAGE_TOKEN = 57, + CANNOT_UPDATE_DISABLED_LICENSE = 58, + CANNOT_CREATE_LICENSE_FOR_SENSITIVE_USERLIST = 59, + INSUFFICIENT_COST = 60, + CANNOT_DISABLE_LICENSE = 61, + INVALID_CLIENT_ACCOUNT_ID = 62, + PRICING_ONLY_ZERO_COST_ALLOWED = 63, + PRICE_TOO_HIGH = 64, + CUSTOMER_NOT_ALLOWED_TO_CREATE_LICENSE = 65, + INVALID_PRICING_END_DATE = 66, + CANNOT_LICENSE_LOGICAL_LIST_WITH_LICENSED_OR_SHARED_SEGMENT = 67, + MISMATCHED_ACCOUNT_TYPE = 68, + MEDIA_SHARE_COST_NOT_ALLOWED_FOR_LICENSE_TYPE = 69, + MEDIA_SHARE_COST_NOT_ALLOWED_FOR_CLIENT_CUSTOMER = 70, + INVALID_MEDIA_SHARE_COST = 71, + INVALID_COST_TYPE = 72, + MEDIA_SHARE_COST_NOT_ALLOWED_FOR_NON_COMMERCE_USER_LIST = 73, + MAX_COST_NOT_ALLOWED = 74, + COMMERCE_AUDIENCE_CAN_ONLY_BE_DIRECTLY_LICENSED = 75, + INVALID_DESCRIPTION = 76, + INVALID_DISPLAY_NAME = 77, + DISPLAY_NAME_ALREADY_USED = 78, + OWNERSHIP_REQUIRED_FOR_UPDATE = 79, + USER_LIST_MUTATION_NOT_SUPPORTED = 80, + SENSITIVE_USER_LIST_IMMUTABLE = 81, + BILLABLE_RECORD_COUNT_IMMUTABLE = 82, + USER_LIST_NAME_RESERVED = 83, + ADVERTISER_NOT_ALLOWLISTED_FOR_UPLOADED_DATA = 84, + UNSUPPORTED_PARTNER_AUDIENCE_SOURCE = 85, + COMMERCE_PARTNER_NOT_ALLOWED = 86, + UNSUPPORTED_PARTNER_AUDIENCE_INFO = 87, + PARTNER_MATCH_FOR_MANAGER_ACCOUNT_DISALLOWED = 88, + DATA_PARTNER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA = 89, + ADVERTISER_TOS_NOT_ACCEPTED = 90, + ADVERTISER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA = 91, + USER_LIST_TYPE_NOT_SUPPORTED_FOR_ACCOUNT = 92, + INVALID_COMMERCE_PARTNER = 93, + CUSTOMER_NOT_ALLOWLISTED_FOR_COMMERCE_AUDIENCE = 94, + UNSUPPORTED_USER_LIST_UPLOAD_KEY_TYPES = 95, + UNSUPPORTED_INGESTED_USER_LIST_INFO_CONFIG = 96, + UNSUPPORTED_ACCOUNT_TYPES_FOR_USER_LIST_TYPE = 97, + UNSUPPORTED_ACCOUNT_TYPE_FOR_PARTNER_LINK = 98 } /** Properties of an Event. */ @@ -1983,7 +2249,7 @@ export namespace google { public currency: string; /** Event conversionValue. */ - public conversionValue: number; + public conversionValue?: (number|null); /** Event eventSource. */ public eventSource: (google.ads.datamanager.v1.EventSource|keyof typeof google.ads.datamanager.v1.EventSource); @@ -2767,6 +3033,14 @@ export namespace google { HIGH = 3 } + /** Gender enum. */ + enum Gender { + GENDER_UNSPECIFIED = 0, + GENDER_UNKNOWN = 1, + GENDER_MALE = 2, + GENDER_FEMALE = 3 + } + /** Represents an IngestionService */ class IngestionService extends $protobuf.rpc.Service { @@ -3906,6 +4180,12 @@ export namespace google { /** IngestAudienceMembersStatus pairDataIngestionStatus */ pairDataIngestionStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPairDataStatus|null); + + /** IngestAudienceMembersStatus userIdDataIngestionStatus */ + userIdDataIngestionStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus|null); + + /** IngestAudienceMembersStatus ppidDataIngestionStatus */ + ppidDataIngestionStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus|null); } /** Represents an IngestAudienceMembersStatus. */ @@ -3926,8 +4206,14 @@ export namespace google { /** IngestAudienceMembersStatus pairDataIngestionStatus. */ public pairDataIngestionStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPairDataStatus|null); + /** IngestAudienceMembersStatus userIdDataIngestionStatus. */ + public userIdDataIngestionStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus|null); + + /** IngestAudienceMembersStatus ppidDataIngestionStatus. */ + public ppidDataIngestionStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus|null); + /** IngestAudienceMembersStatus status. */ - public status?: ("userDataIngestionStatus"|"mobileDataIngestionStatus"|"pairDataIngestionStatus"); + public status?: ("userDataIngestionStatus"|"mobileDataIngestionStatus"|"pairDataIngestionStatus"|"userIdDataIngestionStatus"|"ppidDataIngestionStatus"); /** * Creates a new IngestAudienceMembersStatus instance using the specified properties. @@ -4018,6 +4304,12 @@ export namespace google { /** RemoveAudienceMembersStatus pairDataRemovalStatus */ pairDataRemovalStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePairDataStatus|null); + + /** RemoveAudienceMembersStatus userIdDataRemovalStatus */ + userIdDataRemovalStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus|null); + + /** RemoveAudienceMembersStatus ppidDataRemovalStatus */ + ppidDataRemovalStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus|null); } /** Represents a RemoveAudienceMembersStatus. */ @@ -4038,8 +4330,14 @@ export namespace google { /** RemoveAudienceMembersStatus pairDataRemovalStatus. */ public pairDataRemovalStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePairDataStatus|null); + /** RemoveAudienceMembersStatus userIdDataRemovalStatus. */ + public userIdDataRemovalStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus|null); + + /** RemoveAudienceMembersStatus ppidDataRemovalStatus. */ + public ppidDataRemovalStatus?: (google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus|null); + /** RemoveAudienceMembersStatus status. */ - public status?: ("userDataRemovalStatus"|"mobileDataRemovalStatus"|"pairDataRemovalStatus"); + public status?: ("userDataRemovalStatus"|"mobileDataRemovalStatus"|"pairDataRemovalStatus"|"userIdDataRemovalStatus"|"ppidDataRemovalStatus"); /** * Creates a new RemoveAudienceMembersStatus instance using the specified properties. @@ -4839,590 +5137,6823 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** MatchRateRange enum. */ - enum MatchRateRange { - MATCH_RATE_RANGE_UNKNOWN = 0, - MATCH_RATE_RANGE_NOT_ELIGIBLE = 1, - MATCH_RATE_RANGE_LESS_THAN_20 = 2, - MATCH_RATE_RANGE_20_TO_30 = 3, - MATCH_RATE_RANGE_31_TO_40 = 4, - MATCH_RATE_RANGE_41_TO_50 = 5, - MATCH_RATE_RANGE_51_TO_60 = 6, - MATCH_RATE_RANGE_61_TO_70 = 7, - MATCH_RATE_RANGE_71_TO_80 = 8, - MATCH_RATE_RANGE_81_TO_90 = 9, - MATCH_RATE_RANGE_91_TO_100 = 10 - } + /** Properties of an IngestUserIdDataStatus. */ + interface IIngestUserIdDataStatus { - /** Properties of an ErrorInfo. */ - interface IErrorInfo { + /** IngestUserIdDataStatus recordCount */ + recordCount?: (number|Long|string|null); - /** ErrorInfo errorCounts */ - errorCounts?: (google.ads.datamanager.v1.IErrorCount[]|null); - } + /** IngestUserIdDataStatus userIdCount */ + userIdCount?: (number|Long|string|null); + } - /** Represents an ErrorInfo. */ - class ErrorInfo implements IErrorInfo { + /** Represents an IngestUserIdDataStatus. */ + class IngestUserIdDataStatus implements IIngestUserIdDataStatus { - /** - * Constructs a new ErrorInfo. - * @param [properties] Properties to set - */ - constructor(properties?: google.ads.datamanager.v1.IErrorInfo); + /** + * Constructs a new IngestUserIdDataStatus. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus); - /** ErrorInfo errorCounts. */ - public errorCounts: google.ads.datamanager.v1.IErrorCount[]; + /** IngestUserIdDataStatus recordCount. */ + public recordCount: (number|Long|string); - /** - * Creates a new ErrorInfo instance using the specified properties. - * @param [properties] Properties to set - * @returns ErrorInfo instance - */ - public static create(properties?: google.ads.datamanager.v1.IErrorInfo): google.ads.datamanager.v1.ErrorInfo; + /** IngestUserIdDataStatus userIdCount. */ + public userIdCount: (number|Long|string); - /** - * Encodes the specified ErrorInfo message. Does not implicitly {@link google.ads.datamanager.v1.ErrorInfo.verify|verify} messages. - * @param message ErrorInfo message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.ads.datamanager.v1.IErrorInfo, writer?: $protobuf.Writer): $protobuf.Writer; + /** + * Creates a new IngestUserIdDataStatus instance using the specified properties. + * @param [properties] Properties to set + * @returns IngestUserIdDataStatus instance + */ + public static create(properties?: google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus): google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus; - /** - * Encodes the specified ErrorInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ErrorInfo.verify|verify} messages. - * @param message ErrorInfo message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.ads.datamanager.v1.IErrorInfo, writer?: $protobuf.Writer): $protobuf.Writer; + /** + * Encodes the specified IngestUserIdDataStatus message. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.verify|verify} messages. + * @param message IngestUserIdDataStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus, writer?: $protobuf.Writer): $protobuf.Writer; - /** - * Decodes an ErrorInfo message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns ErrorInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ErrorInfo; + /** + * Encodes the specified IngestUserIdDataStatus message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.verify|verify} messages. + * @param message IngestUserIdDataStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus, writer?: $protobuf.Writer): $protobuf.Writer; - /** - * Decodes an ErrorInfo message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns ErrorInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ErrorInfo; + /** + * Decodes an IngestUserIdDataStatus message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns IngestUserIdDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus; - /** - * Verifies an ErrorInfo message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); + /** + * Decodes an IngestUserIdDataStatus message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns IngestUserIdDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus; - /** - * Creates an ErrorInfo message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ErrorInfo - */ - public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ErrorInfo; + /** + * Verifies an IngestUserIdDataStatus message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); - /** + /** + * Creates an IngestUserIdDataStatus message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IngestUserIdDataStatus + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus; + + /** + * Creates a plain object from an IngestUserIdDataStatus message. Also converts values to other types if specified. + * @param message IngestUserIdDataStatus + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IngestUserIdDataStatus to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IngestUserIdDataStatus + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RemoveUserIdDataStatus. */ + interface IRemoveUserIdDataStatus { + + /** RemoveUserIdDataStatus recordCount */ + recordCount?: (number|Long|string|null); + + /** RemoveUserIdDataStatus userIdCount */ + userIdCount?: (number|Long|string|null); + } + + /** Represents a RemoveUserIdDataStatus. */ + class RemoveUserIdDataStatus implements IRemoveUserIdDataStatus { + + /** + * Constructs a new RemoveUserIdDataStatus. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus); + + /** RemoveUserIdDataStatus recordCount. */ + public recordCount: (number|Long|string); + + /** RemoveUserIdDataStatus userIdCount. */ + public userIdCount: (number|Long|string); + + /** + * Creates a new RemoveUserIdDataStatus instance using the specified properties. + * @param [properties] Properties to set + * @returns RemoveUserIdDataStatus instance + */ + public static create(properties?: google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus): google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus; + + /** + * Encodes the specified RemoveUserIdDataStatus message. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.verify|verify} messages. + * @param message RemoveUserIdDataStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RemoveUserIdDataStatus message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.verify|verify} messages. + * @param message RemoveUserIdDataStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RemoveUserIdDataStatus message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RemoveUserIdDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus; + + /** + * Decodes a RemoveUserIdDataStatus message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RemoveUserIdDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus; + + /** + * Verifies a RemoveUserIdDataStatus message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RemoveUserIdDataStatus message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RemoveUserIdDataStatus + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus; + + /** + * Creates a plain object from a RemoveUserIdDataStatus message. Also converts values to other types if specified. + * @param message RemoveUserIdDataStatus + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RemoveUserIdDataStatus to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RemoveUserIdDataStatus + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an IngestPpidDataStatus. */ + interface IIngestPpidDataStatus { + + /** IngestPpidDataStatus recordCount */ + recordCount?: (number|Long|string|null); + + /** IngestPpidDataStatus ppidCount */ + ppidCount?: (number|Long|string|null); + } + + /** Represents an IngestPpidDataStatus. */ + class IngestPpidDataStatus implements IIngestPpidDataStatus { + + /** + * Constructs a new IngestPpidDataStatus. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus); + + /** IngestPpidDataStatus recordCount. */ + public recordCount: (number|Long|string); + + /** IngestPpidDataStatus ppidCount. */ + public ppidCount: (number|Long|string); + + /** + * Creates a new IngestPpidDataStatus instance using the specified properties. + * @param [properties] Properties to set + * @returns IngestPpidDataStatus instance + */ + public static create(properties?: google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus): google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus; + + /** + * Encodes the specified IngestPpidDataStatus message. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.verify|verify} messages. + * @param message IngestPpidDataStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified IngestPpidDataStatus message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.verify|verify} messages. + * @param message IngestPpidDataStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an IngestPpidDataStatus message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns IngestPpidDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus; + + /** + * Decodes an IngestPpidDataStatus message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns IngestPpidDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus; + + /** + * Verifies an IngestPpidDataStatus message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an IngestPpidDataStatus message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IngestPpidDataStatus + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus; + + /** + * Creates a plain object from an IngestPpidDataStatus message. Also converts values to other types if specified. + * @param message IngestPpidDataStatus + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IngestPpidDataStatus to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IngestPpidDataStatus + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RemovePpidDataStatus. */ + interface IRemovePpidDataStatus { + + /** RemovePpidDataStatus recordCount */ + recordCount?: (number|Long|string|null); + + /** RemovePpidDataStatus ppidCount */ + ppidCount?: (number|Long|string|null); + } + + /** Represents a RemovePpidDataStatus. */ + class RemovePpidDataStatus implements IRemovePpidDataStatus { + + /** + * Constructs a new RemovePpidDataStatus. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus); + + /** RemovePpidDataStatus recordCount. */ + public recordCount: (number|Long|string); + + /** RemovePpidDataStatus ppidCount. */ + public ppidCount: (number|Long|string); + + /** + * Creates a new RemovePpidDataStatus instance using the specified properties. + * @param [properties] Properties to set + * @returns RemovePpidDataStatus instance + */ + public static create(properties?: google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus): google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus; + + /** + * Encodes the specified RemovePpidDataStatus message. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.verify|verify} messages. + * @param message RemovePpidDataStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RemovePpidDataStatus message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.verify|verify} messages. + * @param message RemovePpidDataStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RemovePpidDataStatus message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RemovePpidDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus; + + /** + * Decodes a RemovePpidDataStatus message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RemovePpidDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus; + + /** + * Verifies a RemovePpidDataStatus message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RemovePpidDataStatus message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RemovePpidDataStatus + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus; + + /** + * Creates a plain object from a RemovePpidDataStatus message. Also converts values to other types if specified. + * @param message RemovePpidDataStatus + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RemovePpidDataStatus to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RemovePpidDataStatus + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** MatchRateRange enum. */ + enum MatchRateRange { + MATCH_RATE_RANGE_UNKNOWN = 0, + MATCH_RATE_RANGE_NOT_ELIGIBLE = 1, + MATCH_RATE_RANGE_LESS_THAN_20 = 2, + MATCH_RATE_RANGE_20_TO_30 = 3, + MATCH_RATE_RANGE_31_TO_40 = 4, + MATCH_RATE_RANGE_41_TO_50 = 5, + MATCH_RATE_RANGE_51_TO_60 = 6, + MATCH_RATE_RANGE_61_TO_70 = 7, + MATCH_RATE_RANGE_71_TO_80 = 8, + MATCH_RATE_RANGE_81_TO_90 = 9, + MATCH_RATE_RANGE_91_TO_100 = 10 + } + + /** Properties of an ErrorInfo. */ + interface IErrorInfo { + + /** ErrorInfo errorCounts */ + errorCounts?: (google.ads.datamanager.v1.IErrorCount[]|null); + } + + /** Represents an ErrorInfo. */ + class ErrorInfo implements IErrorInfo { + + /** + * Constructs a new ErrorInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IErrorInfo); + + /** ErrorInfo errorCounts. */ + public errorCounts: google.ads.datamanager.v1.IErrorCount[]; + + /** + * Creates a new ErrorInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns ErrorInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IErrorInfo): google.ads.datamanager.v1.ErrorInfo; + + /** + * Encodes the specified ErrorInfo message. Does not implicitly {@link google.ads.datamanager.v1.ErrorInfo.verify|verify} messages. + * @param message ErrorInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IErrorInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ErrorInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ErrorInfo.verify|verify} messages. + * @param message ErrorInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IErrorInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ErrorInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ErrorInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ErrorInfo; + + /** + * Decodes an ErrorInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ErrorInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ErrorInfo; + + /** + * Verifies an ErrorInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ErrorInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ErrorInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ErrorInfo; + + /** * Creates a plain object from an ErrorInfo message. Also converts values to other types if specified. * @param message ErrorInfo * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.ads.datamanager.v1.ErrorInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.ads.datamanager.v1.ErrorInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ErrorInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ErrorInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ErrorCount. */ + interface IErrorCount { + + /** ErrorCount recordCount */ + recordCount?: (number|Long|string|null); + + /** ErrorCount reason */ + reason?: (google.ads.datamanager.v1.ProcessingErrorReason|keyof typeof google.ads.datamanager.v1.ProcessingErrorReason|null); + } + + /** Represents an ErrorCount. */ + class ErrorCount implements IErrorCount { + + /** + * Constructs a new ErrorCount. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IErrorCount); + + /** ErrorCount recordCount. */ + public recordCount: (number|Long|string); + + /** ErrorCount reason. */ + public reason: (google.ads.datamanager.v1.ProcessingErrorReason|keyof typeof google.ads.datamanager.v1.ProcessingErrorReason); + + /** + * Creates a new ErrorCount instance using the specified properties. + * @param [properties] Properties to set + * @returns ErrorCount instance + */ + public static create(properties?: google.ads.datamanager.v1.IErrorCount): google.ads.datamanager.v1.ErrorCount; + + /** + * Encodes the specified ErrorCount message. Does not implicitly {@link google.ads.datamanager.v1.ErrorCount.verify|verify} messages. + * @param message ErrorCount message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IErrorCount, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ErrorCount message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ErrorCount.verify|verify} messages. + * @param message ErrorCount message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IErrorCount, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ErrorCount message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ErrorCount + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ErrorCount; + + /** + * Decodes an ErrorCount message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ErrorCount + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ErrorCount; + + /** + * Verifies an ErrorCount message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ErrorCount message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ErrorCount + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ErrorCount; + + /** + * Creates a plain object from an ErrorCount message. Also converts values to other types if specified. + * @param message ErrorCount + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ErrorCount, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ErrorCount to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ErrorCount + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WarningInfo. */ + interface IWarningInfo { + + /** WarningInfo warningCounts */ + warningCounts?: (google.ads.datamanager.v1.IWarningCount[]|null); + } + + /** Represents a WarningInfo. */ + class WarningInfo implements IWarningInfo { + + /** + * Constructs a new WarningInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IWarningInfo); + + /** WarningInfo warningCounts. */ + public warningCounts: google.ads.datamanager.v1.IWarningCount[]; + + /** + * Creates a new WarningInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns WarningInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IWarningInfo): google.ads.datamanager.v1.WarningInfo; + + /** + * Encodes the specified WarningInfo message. Does not implicitly {@link google.ads.datamanager.v1.WarningInfo.verify|verify} messages. + * @param message WarningInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IWarningInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WarningInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.WarningInfo.verify|verify} messages. + * @param message WarningInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IWarningInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WarningInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WarningInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.WarningInfo; + + /** + * Decodes a WarningInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WarningInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.WarningInfo; + + /** + * Verifies a WarningInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WarningInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WarningInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.WarningInfo; + + /** + * Creates a plain object from a WarningInfo message. Also converts values to other types if specified. + * @param message WarningInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.WarningInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WarningInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WarningInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WarningCount. */ + interface IWarningCount { + + /** WarningCount recordCount */ + recordCount?: (number|Long|string|null); + + /** WarningCount reason */ + reason?: (google.ads.datamanager.v1.ProcessingWarningReason|keyof typeof google.ads.datamanager.v1.ProcessingWarningReason|null); + } + + /** Represents a WarningCount. */ + class WarningCount implements IWarningCount { + + /** + * Constructs a new WarningCount. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IWarningCount); + + /** WarningCount recordCount. */ + public recordCount: (number|Long|string); + + /** WarningCount reason. */ + public reason: (google.ads.datamanager.v1.ProcessingWarningReason|keyof typeof google.ads.datamanager.v1.ProcessingWarningReason); + + /** + * Creates a new WarningCount instance using the specified properties. + * @param [properties] Properties to set + * @returns WarningCount instance + */ + public static create(properties?: google.ads.datamanager.v1.IWarningCount): google.ads.datamanager.v1.WarningCount; + + /** + * Encodes the specified WarningCount message. Does not implicitly {@link google.ads.datamanager.v1.WarningCount.verify|verify} messages. + * @param message WarningCount message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IWarningCount, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WarningCount message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.WarningCount.verify|verify} messages. + * @param message WarningCount message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IWarningCount, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WarningCount message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WarningCount + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.WarningCount; + + /** + * Decodes a WarningCount message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WarningCount + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.WarningCount; + + /** + * Verifies a WarningCount message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WarningCount message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WarningCount + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.WarningCount; + + /** + * Creates a plain object from a WarningCount message. Also converts values to other types if specified. + * @param message WarningCount + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.WarningCount, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WarningCount to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WarningCount + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** ProcessingErrorReason enum. */ + enum ProcessingErrorReason { + PROCESSING_ERROR_REASON_UNSPECIFIED = 0, + PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE = 1, + PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED = 2, + PROCESSING_ERROR_REASON_EVENT_TOO_OLD = 3, + PROCESSING_ERROR_REASON_DENIED_CONSENT = 4, + PROCESSING_ERROR_REASON_NO_CONSENT = 5, + PROCESSING_ERROR_REASON_UNKNOWN_CONSENT = 6, + PROCESSING_ERROR_REASON_DUPLICATE_GCLID = 7, + PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID = 8, + PROCESSING_ERROR_REASON_INVALID_GBRAID = 9, + PROCESSING_ERROR_REASON_INVALID_GCLID = 10, + PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID = 11, + PROCESSING_ERROR_REASON_INVALID_WBRAID = 12, + PROCESSING_ERROR_REASON_INTERNAL_ERROR = 13, + PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED = 14, + PROCESSING_ERROR_REASON_INVALID_EVENT = 15, + PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS = 16, + PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS = 17, + PROCESSING_ERROR_REASON_INVALID_FORMAT = 18, + PROCESSING_ERROR_REASON_DECRYPTION_ERROR = 19, + PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR = 20, + PROCESSING_ERROR_REASON_INVALID_WIP = 21, + PROCESSING_ERROR_REASON_INVALID_KEK = 22, + PROCESSING_ERROR_REASON_WIP_AUTH_FAILED = 23, + PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED = 24, + PROCESSING_ERROR_REASON_AWS_AUTH_FAILED = 27, + PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR = 25, + PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER = 26 + } + + /** ProcessingWarningReason enum. */ + enum ProcessingWarningReason { + PROCESSING_WARNING_REASON_UNSPECIFIED = 0, + PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED = 1, + PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR = 2, + PROCESSING_WARNING_REASON_DECRYPTION_ERROR = 3, + PROCESSING_WARNING_REASON_WIP_AUTH_FAILED = 4, + PROCESSING_WARNING_REASON_INVALID_WIP = 5, + PROCESSING_WARNING_REASON_INVALID_KEK = 6, + PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR = 7, + PROCESSING_WARNING_REASON_INTERNAL_ERROR = 8, + PROCESSING_WARNING_REASON_AWS_AUTH_FAILED = 9 + } + + /** Properties of a TermsOfService. */ + interface ITermsOfService { + + /** TermsOfService customerMatchTermsOfServiceStatus */ + customerMatchTermsOfServiceStatus?: (google.ads.datamanager.v1.TermsOfServiceStatus|keyof typeof google.ads.datamanager.v1.TermsOfServiceStatus|null); + } + + /** Represents a TermsOfService. */ + class TermsOfService implements ITermsOfService { + + /** + * Constructs a new TermsOfService. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ITermsOfService); + + /** TermsOfService customerMatchTermsOfServiceStatus. */ + public customerMatchTermsOfServiceStatus: (google.ads.datamanager.v1.TermsOfServiceStatus|keyof typeof google.ads.datamanager.v1.TermsOfServiceStatus); + + /** + * Creates a new TermsOfService instance using the specified properties. + * @param [properties] Properties to set + * @returns TermsOfService instance + */ + public static create(properties?: google.ads.datamanager.v1.ITermsOfService): google.ads.datamanager.v1.TermsOfService; + + /** + * Encodes the specified TermsOfService message. Does not implicitly {@link google.ads.datamanager.v1.TermsOfService.verify|verify} messages. + * @param message TermsOfService message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ITermsOfService, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TermsOfService message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.TermsOfService.verify|verify} messages. + * @param message TermsOfService message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ITermsOfService, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TermsOfService message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TermsOfService + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.TermsOfService; + + /** + * Decodes a TermsOfService message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TermsOfService + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.TermsOfService; + + /** + * Verifies a TermsOfService message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TermsOfService message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TermsOfService + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.TermsOfService; + + /** + * Creates a plain object from a TermsOfService message. Also converts values to other types if specified. + * @param message TermsOfService + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.TermsOfService, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TermsOfService to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TermsOfService + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** TermsOfServiceStatus enum. */ + enum TermsOfServiceStatus { + TERMS_OF_SERVICE_STATUS_UNSPECIFIED = 0, + ACCEPTED = 1, + REJECTED = 2 + } + + /** Represents a MarketingDataInsightsService */ + class MarketingDataInsightsService extends $protobuf.rpc.Service { + + /** + * Constructs a new MarketingDataInsightsService service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new MarketingDataInsightsService service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): MarketingDataInsightsService; + + /** + * Calls RetrieveInsights. + * @param request RetrieveInsightsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RetrieveInsightsResponse + */ + public retrieveInsights(request: google.ads.datamanager.v1.IRetrieveInsightsRequest, callback: google.ads.datamanager.v1.MarketingDataInsightsService.RetrieveInsightsCallback): void; + + /** + * Calls RetrieveInsights. + * @param request RetrieveInsightsRequest message or plain object + * @returns Promise + */ + public retrieveInsights(request: google.ads.datamanager.v1.IRetrieveInsightsRequest): Promise; + } + + namespace MarketingDataInsightsService { + + /** + * Callback as used by {@link google.ads.datamanager.v1.MarketingDataInsightsService|retrieveInsights}. + * @param error Error, if any + * @param [response] RetrieveInsightsResponse + */ + type RetrieveInsightsCallback = (error: (Error|null), response?: google.ads.datamanager.v1.RetrieveInsightsResponse) => void; + } + + /** Properties of a RetrieveInsightsRequest. */ + interface IRetrieveInsightsRequest { + + /** RetrieveInsightsRequest parent */ + parent?: (string|null); + + /** RetrieveInsightsRequest baseline */ + baseline?: (google.ads.datamanager.v1.IBaseline|null); + + /** RetrieveInsightsRequest userListId */ + userListId?: (string|null); + } + + /** Represents a RetrieveInsightsRequest. */ + class RetrieveInsightsRequest implements IRetrieveInsightsRequest { + + /** + * Constructs a new RetrieveInsightsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IRetrieveInsightsRequest); + + /** RetrieveInsightsRequest parent. */ + public parent: string; + + /** RetrieveInsightsRequest baseline. */ + public baseline?: (google.ads.datamanager.v1.IBaseline|null); + + /** RetrieveInsightsRequest userListId. */ + public userListId: string; + + /** + * Creates a new RetrieveInsightsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns RetrieveInsightsRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IRetrieveInsightsRequest): google.ads.datamanager.v1.RetrieveInsightsRequest; + + /** + * Encodes the specified RetrieveInsightsRequest message. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsRequest.verify|verify} messages. + * @param message RetrieveInsightsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IRetrieveInsightsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RetrieveInsightsRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsRequest.verify|verify} messages. + * @param message RetrieveInsightsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IRetrieveInsightsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RetrieveInsightsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RetrieveInsightsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.RetrieveInsightsRequest; + + /** + * Decodes a RetrieveInsightsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RetrieveInsightsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.RetrieveInsightsRequest; + + /** + * Verifies a RetrieveInsightsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RetrieveInsightsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RetrieveInsightsRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.RetrieveInsightsRequest; + + /** + * Creates a plain object from a RetrieveInsightsRequest message. Also converts values to other types if specified. + * @param message RetrieveInsightsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.RetrieveInsightsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RetrieveInsightsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RetrieveInsightsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Baseline. */ + interface IBaseline { + + /** Baseline baselineLocation */ + baselineLocation?: (google.ads.datamanager.v1.Baseline.ILocation|null); + + /** Baseline locationAutoDetectionEnabled */ + locationAutoDetectionEnabled?: (boolean|null); + } + + /** Represents a Baseline. */ + class Baseline implements IBaseline { + + /** + * Constructs a new Baseline. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IBaseline); + + /** Baseline baselineLocation. */ + public baselineLocation?: (google.ads.datamanager.v1.Baseline.ILocation|null); + + /** Baseline locationAutoDetectionEnabled. */ + public locationAutoDetectionEnabled?: (boolean|null); + + /** Baseline baseline. */ + public baseline?: ("baselineLocation"|"locationAutoDetectionEnabled"); + + /** + * Creates a new Baseline instance using the specified properties. + * @param [properties] Properties to set + * @returns Baseline instance + */ + public static create(properties?: google.ads.datamanager.v1.IBaseline): google.ads.datamanager.v1.Baseline; + + /** + * Encodes the specified Baseline message. Does not implicitly {@link google.ads.datamanager.v1.Baseline.verify|verify} messages. + * @param message Baseline message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IBaseline, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Baseline message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.Baseline.verify|verify} messages. + * @param message Baseline message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IBaseline, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Baseline message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Baseline + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.Baseline; + + /** + * Decodes a Baseline message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Baseline + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.Baseline; + + /** + * Verifies a Baseline message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Baseline message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Baseline + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.Baseline; + + /** + * Creates a plain object from a Baseline message. Also converts values to other types if specified. + * @param message Baseline + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.Baseline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Baseline to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Baseline + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Baseline { + + /** Properties of a Location. */ + interface ILocation { + + /** Location regionCodes */ + regionCodes?: (string[]|null); + } + + /** Represents a Location. */ + class Location implements ILocation { + + /** + * Constructs a new Location. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.Baseline.ILocation); + + /** Location regionCodes. */ + public regionCodes: string[]; + + /** + * Creates a new Location instance using the specified properties. + * @param [properties] Properties to set + * @returns Location instance + */ + public static create(properties?: google.ads.datamanager.v1.Baseline.ILocation): google.ads.datamanager.v1.Baseline.Location; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.ads.datamanager.v1.Baseline.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.Baseline.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.Baseline.Location.verify|verify} messages. + * @param message Location message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.Baseline.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Location message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.Baseline.Location; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.Baseline.Location; + + /** + * Verifies a Location message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Location + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.Baseline.Location; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.Baseline.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Location to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a RetrieveInsightsResponse. */ + interface IRetrieveInsightsResponse { + + /** RetrieveInsightsResponse marketingDataInsights */ + marketingDataInsights?: (google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight[]|null); + } + + /** Represents a RetrieveInsightsResponse. */ + class RetrieveInsightsResponse implements IRetrieveInsightsResponse { + + /** + * Constructs a new RetrieveInsightsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IRetrieveInsightsResponse); + + /** RetrieveInsightsResponse marketingDataInsights. */ + public marketingDataInsights: google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight[]; + + /** + * Creates a new RetrieveInsightsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns RetrieveInsightsResponse instance + */ + public static create(properties?: google.ads.datamanager.v1.IRetrieveInsightsResponse): google.ads.datamanager.v1.RetrieveInsightsResponse; + + /** + * Encodes the specified RetrieveInsightsResponse message. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.verify|verify} messages. + * @param message RetrieveInsightsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IRetrieveInsightsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RetrieveInsightsResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.verify|verify} messages. + * @param message RetrieveInsightsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IRetrieveInsightsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RetrieveInsightsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RetrieveInsightsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.RetrieveInsightsResponse; + + /** + * Decodes a RetrieveInsightsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RetrieveInsightsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.RetrieveInsightsResponse; + + /** + * Verifies a RetrieveInsightsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RetrieveInsightsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RetrieveInsightsResponse + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.RetrieveInsightsResponse; + + /** + * Creates a plain object from a RetrieveInsightsResponse message. Also converts values to other types if specified. + * @param message RetrieveInsightsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.RetrieveInsightsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RetrieveInsightsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RetrieveInsightsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace RetrieveInsightsResponse { + + /** Properties of a MarketingDataInsight. */ + interface IMarketingDataInsight { + + /** MarketingDataInsight dimension */ + dimension?: (google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension|keyof typeof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension|null); + + /** MarketingDataInsight attributes */ + attributes?: (google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute[]|null); + } + + /** Represents a MarketingDataInsight. */ + class MarketingDataInsight implements IMarketingDataInsight { + + /** + * Constructs a new MarketingDataInsight. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight); + + /** MarketingDataInsight dimension. */ + public dimension: (google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension|keyof typeof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension); + + /** MarketingDataInsight attributes. */ + public attributes: google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute[]; + + /** + * Creates a new MarketingDataInsight instance using the specified properties. + * @param [properties] Properties to set + * @returns MarketingDataInsight instance + */ + public static create(properties?: google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight): google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight; + + /** + * Encodes the specified MarketingDataInsight message. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.verify|verify} messages. + * @param message MarketingDataInsight message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MarketingDataInsight message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.verify|verify} messages. + * @param message MarketingDataInsight message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MarketingDataInsight message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MarketingDataInsight + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight; + + /** + * Decodes a MarketingDataInsight message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MarketingDataInsight + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight; + + /** + * Verifies a MarketingDataInsight message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MarketingDataInsight message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MarketingDataInsight + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight; + + /** + * Creates a plain object from a MarketingDataInsight message. Also converts values to other types if specified. + * @param message MarketingDataInsight + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MarketingDataInsight to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MarketingDataInsight + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MarketingDataInsight { + + /** AudienceInsightsDimension enum. */ + enum AudienceInsightsDimension { + AUDIENCE_INSIGHTS_DIMENSION_UNSPECIFIED = 0, + AUDIENCE_INSIGHTS_DIMENSION_UNKNOWN = 1, + AFFINITY_USER_INTEREST = 2, + IN_MARKET_USER_INTEREST = 3, + AGE_RANGE = 4, + GENDER = 5 + } + + /** Properties of a MarketingDataInsightsAttribute. */ + interface IMarketingDataInsightsAttribute { + + /** MarketingDataInsightsAttribute userInterestId */ + userInterestId?: (number|Long|string|null); + + /** MarketingDataInsightsAttribute lift */ + lift?: (number|null); + + /** MarketingDataInsightsAttribute ageRange */ + ageRange?: (google.ads.datamanager.v1.AgeRange|keyof typeof google.ads.datamanager.v1.AgeRange|null); + + /** MarketingDataInsightsAttribute gender */ + gender?: (google.ads.datamanager.v1.Gender|keyof typeof google.ads.datamanager.v1.Gender|null); + } + + /** Represents a MarketingDataInsightsAttribute. */ + class MarketingDataInsightsAttribute implements IMarketingDataInsightsAttribute { + + /** + * Constructs a new MarketingDataInsightsAttribute. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute); + + /** MarketingDataInsightsAttribute userInterestId. */ + public userInterestId?: (number|Long|string|null); + + /** MarketingDataInsightsAttribute lift. */ + public lift?: (number|null); + + /** MarketingDataInsightsAttribute ageRange. */ + public ageRange?: (google.ads.datamanager.v1.AgeRange|keyof typeof google.ads.datamanager.v1.AgeRange|null); + + /** MarketingDataInsightsAttribute gender. */ + public gender?: (google.ads.datamanager.v1.Gender|keyof typeof google.ads.datamanager.v1.Gender|null); + + /** + * Creates a new MarketingDataInsightsAttribute instance using the specified properties. + * @param [properties] Properties to set + * @returns MarketingDataInsightsAttribute instance + */ + public static create(properties?: google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute): google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute; + + /** + * Encodes the specified MarketingDataInsightsAttribute message. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.verify|verify} messages. + * @param message MarketingDataInsightsAttribute message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MarketingDataInsightsAttribute message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.verify|verify} messages. + * @param message MarketingDataInsightsAttribute message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MarketingDataInsightsAttribute message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MarketingDataInsightsAttribute + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute; + + /** + * Decodes a MarketingDataInsightsAttribute message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MarketingDataInsightsAttribute + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute; + + /** + * Verifies a MarketingDataInsightsAttribute message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MarketingDataInsightsAttribute message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MarketingDataInsightsAttribute + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute; + + /** + * Creates a plain object from a MarketingDataInsightsAttribute message. Also converts values to other types if specified. + * @param message MarketingDataInsightsAttribute + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MarketingDataInsightsAttribute to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MarketingDataInsightsAttribute + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** Represents a PartnerLinkService */ + class PartnerLinkService extends $protobuf.rpc.Service { + + /** + * Constructs a new PartnerLinkService service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new PartnerLinkService service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): PartnerLinkService; + + /** + * Calls CreatePartnerLink. + * @param request CreatePartnerLinkRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartnerLink + */ + public createPartnerLink(request: google.ads.datamanager.v1.ICreatePartnerLinkRequest, callback: google.ads.datamanager.v1.PartnerLinkService.CreatePartnerLinkCallback): void; + + /** + * Calls CreatePartnerLink. + * @param request CreatePartnerLinkRequest message or plain object + * @returns Promise + */ + public createPartnerLink(request: google.ads.datamanager.v1.ICreatePartnerLinkRequest): Promise; + + /** + * Calls DeletePartnerLink. + * @param request DeletePartnerLinkRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deletePartnerLink(request: google.ads.datamanager.v1.IDeletePartnerLinkRequest, callback: google.ads.datamanager.v1.PartnerLinkService.DeletePartnerLinkCallback): void; + + /** + * Calls DeletePartnerLink. + * @param request DeletePartnerLinkRequest message or plain object + * @returns Promise + */ + public deletePartnerLink(request: google.ads.datamanager.v1.IDeletePartnerLinkRequest): Promise; + + /** + * Calls SearchPartnerLinks. + * @param request SearchPartnerLinksRequest message or plain object + * @param callback Node-style callback called with the error, if any, and SearchPartnerLinksResponse + */ + public searchPartnerLinks(request: google.ads.datamanager.v1.ISearchPartnerLinksRequest, callback: google.ads.datamanager.v1.PartnerLinkService.SearchPartnerLinksCallback): void; + + /** + * Calls SearchPartnerLinks. + * @param request SearchPartnerLinksRequest message or plain object + * @returns Promise + */ + public searchPartnerLinks(request: google.ads.datamanager.v1.ISearchPartnerLinksRequest): Promise; + } + + namespace PartnerLinkService { + + /** + * Callback as used by {@link google.ads.datamanager.v1.PartnerLinkService|createPartnerLink}. + * @param error Error, if any + * @param [response] PartnerLink + */ + type CreatePartnerLinkCallback = (error: (Error|null), response?: google.ads.datamanager.v1.PartnerLink) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.PartnerLinkService|deletePartnerLink}. + * @param error Error, if any + * @param [response] Empty + */ + type DeletePartnerLinkCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.PartnerLinkService|searchPartnerLinks}. + * @param error Error, if any + * @param [response] SearchPartnerLinksResponse + */ + type SearchPartnerLinksCallback = (error: (Error|null), response?: google.ads.datamanager.v1.SearchPartnerLinksResponse) => void; + } + + /** Properties of a CreatePartnerLinkRequest. */ + interface ICreatePartnerLinkRequest { + + /** CreatePartnerLinkRequest parent */ + parent?: (string|null); + + /** CreatePartnerLinkRequest partnerLink */ + partnerLink?: (google.ads.datamanager.v1.IPartnerLink|null); + } + + /** Represents a CreatePartnerLinkRequest. */ + class CreatePartnerLinkRequest implements ICreatePartnerLinkRequest { + + /** + * Constructs a new CreatePartnerLinkRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ICreatePartnerLinkRequest); + + /** CreatePartnerLinkRequest parent. */ + public parent: string; + + /** CreatePartnerLinkRequest partnerLink. */ + public partnerLink?: (google.ads.datamanager.v1.IPartnerLink|null); + + /** + * Creates a new CreatePartnerLinkRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreatePartnerLinkRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.ICreatePartnerLinkRequest): google.ads.datamanager.v1.CreatePartnerLinkRequest; + + /** + * Encodes the specified CreatePartnerLinkRequest message. Does not implicitly {@link google.ads.datamanager.v1.CreatePartnerLinkRequest.verify|verify} messages. + * @param message CreatePartnerLinkRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ICreatePartnerLinkRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreatePartnerLinkRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.CreatePartnerLinkRequest.verify|verify} messages. + * @param message CreatePartnerLinkRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ICreatePartnerLinkRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreatePartnerLinkRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreatePartnerLinkRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.CreatePartnerLinkRequest; + + /** + * Decodes a CreatePartnerLinkRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreatePartnerLinkRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.CreatePartnerLinkRequest; + + /** + * Verifies a CreatePartnerLinkRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreatePartnerLinkRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreatePartnerLinkRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.CreatePartnerLinkRequest; + + /** + * Creates a plain object from a CreatePartnerLinkRequest message. Also converts values to other types if specified. + * @param message CreatePartnerLinkRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.CreatePartnerLinkRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreatePartnerLinkRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreatePartnerLinkRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeletePartnerLinkRequest. */ + interface IDeletePartnerLinkRequest { + + /** DeletePartnerLinkRequest name */ + name?: (string|null); + } + + /** Represents a DeletePartnerLinkRequest. */ + class DeletePartnerLinkRequest implements IDeletePartnerLinkRequest { + + /** + * Constructs a new DeletePartnerLinkRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IDeletePartnerLinkRequest); + + /** DeletePartnerLinkRequest name. */ + public name: string; + + /** + * Creates a new DeletePartnerLinkRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeletePartnerLinkRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IDeletePartnerLinkRequest): google.ads.datamanager.v1.DeletePartnerLinkRequest; + + /** + * Encodes the specified DeletePartnerLinkRequest message. Does not implicitly {@link google.ads.datamanager.v1.DeletePartnerLinkRequest.verify|verify} messages. + * @param message DeletePartnerLinkRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IDeletePartnerLinkRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeletePartnerLinkRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.DeletePartnerLinkRequest.verify|verify} messages. + * @param message DeletePartnerLinkRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IDeletePartnerLinkRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeletePartnerLinkRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeletePartnerLinkRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.DeletePartnerLinkRequest; + + /** + * Decodes a DeletePartnerLinkRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeletePartnerLinkRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.DeletePartnerLinkRequest; + + /** + * Verifies a DeletePartnerLinkRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeletePartnerLinkRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeletePartnerLinkRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.DeletePartnerLinkRequest; + + /** + * Creates a plain object from a DeletePartnerLinkRequest message. Also converts values to other types if specified. + * @param message DeletePartnerLinkRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.DeletePartnerLinkRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeletePartnerLinkRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeletePartnerLinkRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SearchPartnerLinksRequest. */ + interface ISearchPartnerLinksRequest { + + /** SearchPartnerLinksRequest parent */ + parent?: (string|null); + + /** SearchPartnerLinksRequest pageSize */ + pageSize?: (number|null); + + /** SearchPartnerLinksRequest pageToken */ + pageToken?: (string|null); + + /** SearchPartnerLinksRequest filter */ + filter?: (string|null); + } + + /** Represents a SearchPartnerLinksRequest. */ + class SearchPartnerLinksRequest implements ISearchPartnerLinksRequest { + + /** + * Constructs a new SearchPartnerLinksRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ISearchPartnerLinksRequest); + + /** SearchPartnerLinksRequest parent. */ + public parent: string; + + /** SearchPartnerLinksRequest pageSize. */ + public pageSize: number; + + /** SearchPartnerLinksRequest pageToken. */ + public pageToken: string; + + /** SearchPartnerLinksRequest filter. */ + public filter: string; + + /** + * Creates a new SearchPartnerLinksRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns SearchPartnerLinksRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.ISearchPartnerLinksRequest): google.ads.datamanager.v1.SearchPartnerLinksRequest; + + /** + * Encodes the specified SearchPartnerLinksRequest message. Does not implicitly {@link google.ads.datamanager.v1.SearchPartnerLinksRequest.verify|verify} messages. + * @param message SearchPartnerLinksRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ISearchPartnerLinksRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SearchPartnerLinksRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.SearchPartnerLinksRequest.verify|verify} messages. + * @param message SearchPartnerLinksRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ISearchPartnerLinksRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SearchPartnerLinksRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SearchPartnerLinksRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.SearchPartnerLinksRequest; + + /** + * Decodes a SearchPartnerLinksRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SearchPartnerLinksRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.SearchPartnerLinksRequest; + + /** + * Verifies a SearchPartnerLinksRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SearchPartnerLinksRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SearchPartnerLinksRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.SearchPartnerLinksRequest; + + /** + * Creates a plain object from a SearchPartnerLinksRequest message. Also converts values to other types if specified. + * @param message SearchPartnerLinksRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.SearchPartnerLinksRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SearchPartnerLinksRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SearchPartnerLinksRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SearchPartnerLinksResponse. */ + interface ISearchPartnerLinksResponse { + + /** SearchPartnerLinksResponse partnerLinks */ + partnerLinks?: (google.ads.datamanager.v1.IPartnerLink[]|null); + + /** SearchPartnerLinksResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a SearchPartnerLinksResponse. */ + class SearchPartnerLinksResponse implements ISearchPartnerLinksResponse { + + /** + * Constructs a new SearchPartnerLinksResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ISearchPartnerLinksResponse); + + /** SearchPartnerLinksResponse partnerLinks. */ + public partnerLinks: google.ads.datamanager.v1.IPartnerLink[]; + + /** SearchPartnerLinksResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new SearchPartnerLinksResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns SearchPartnerLinksResponse instance + */ + public static create(properties?: google.ads.datamanager.v1.ISearchPartnerLinksResponse): google.ads.datamanager.v1.SearchPartnerLinksResponse; + + /** + * Encodes the specified SearchPartnerLinksResponse message. Does not implicitly {@link google.ads.datamanager.v1.SearchPartnerLinksResponse.verify|verify} messages. + * @param message SearchPartnerLinksResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ISearchPartnerLinksResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SearchPartnerLinksResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.SearchPartnerLinksResponse.verify|verify} messages. + * @param message SearchPartnerLinksResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ISearchPartnerLinksResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SearchPartnerLinksResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SearchPartnerLinksResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.SearchPartnerLinksResponse; + + /** + * Decodes a SearchPartnerLinksResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SearchPartnerLinksResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.SearchPartnerLinksResponse; + + /** + * Verifies a SearchPartnerLinksResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SearchPartnerLinksResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SearchPartnerLinksResponse + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.SearchPartnerLinksResponse; + + /** + * Creates a plain object from a SearchPartnerLinksResponse message. Also converts values to other types if specified. + * @param message SearchPartnerLinksResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.SearchPartnerLinksResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SearchPartnerLinksResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SearchPartnerLinksResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartnerLink. */ + interface IPartnerLink { + + /** PartnerLink name */ + name?: (string|null); + + /** PartnerLink partnerLinkId */ + partnerLinkId?: (string|null); + + /** PartnerLink owningAccount */ + owningAccount?: (google.ads.datamanager.v1.IProductAccount|null); + + /** PartnerLink partnerAccount */ + partnerAccount?: (google.ads.datamanager.v1.IProductAccount|null); + } + + /** Represents a PartnerLink. */ + class PartnerLink implements IPartnerLink { + + /** + * Constructs a new PartnerLink. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IPartnerLink); + + /** PartnerLink name. */ + public name: string; + + /** PartnerLink partnerLinkId. */ + public partnerLinkId: string; + + /** PartnerLink owningAccount. */ + public owningAccount?: (google.ads.datamanager.v1.IProductAccount|null); + + /** PartnerLink partnerAccount. */ + public partnerAccount?: (google.ads.datamanager.v1.IProductAccount|null); + + /** + * Creates a new PartnerLink instance using the specified properties. + * @param [properties] Properties to set + * @returns PartnerLink instance + */ + public static create(properties?: google.ads.datamanager.v1.IPartnerLink): google.ads.datamanager.v1.PartnerLink; + + /** + * Encodes the specified PartnerLink message. Does not implicitly {@link google.ads.datamanager.v1.PartnerLink.verify|verify} messages. + * @param message PartnerLink message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IPartnerLink, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartnerLink message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PartnerLink.verify|verify} messages. + * @param message PartnerLink message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IPartnerLink, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartnerLink message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartnerLink + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.PartnerLink; + + /** + * Decodes a PartnerLink message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartnerLink + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.PartnerLink; + + /** + * Verifies a PartnerLink message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartnerLink message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartnerLink + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.PartnerLink; + + /** + * Creates a plain object from a PartnerLink message. Also converts values to other types if specified. + * @param message PartnerLink + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.PartnerLink, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartnerLink to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartnerLink + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UserList. */ + interface IUserList { + + /** UserList name */ + name?: (string|null); + + /** UserList id */ + id?: (number|Long|string|null); + + /** UserList readOnly */ + readOnly?: (boolean|null); + + /** UserList displayName */ + displayName?: (string|null); + + /** UserList description */ + description?: (string|null); + + /** UserList membershipStatus */ + membershipStatus?: (google.ads.datamanager.v1.UserList.MembershipStatus|keyof typeof google.ads.datamanager.v1.UserList.MembershipStatus|null); + + /** UserList integrationCode */ + integrationCode?: (string|null); + + /** UserList membershipDuration */ + membershipDuration?: (google.protobuf.IDuration|null); + + /** UserList closingReason */ + closingReason?: (google.ads.datamanager.v1.UserList.ClosingReason|keyof typeof google.ads.datamanager.v1.UserList.ClosingReason|null); + + /** UserList accessReason */ + accessReason?: (google.ads.datamanager.v1.UserList.AccessReason|keyof typeof google.ads.datamanager.v1.UserList.AccessReason|null); + + /** UserList accountAccessStatus */ + accountAccessStatus?: (google.ads.datamanager.v1.UserList.AccessStatus|keyof typeof google.ads.datamanager.v1.UserList.AccessStatus|null); + + /** UserList sizeInfo */ + sizeInfo?: (google.ads.datamanager.v1.ISizeInfo|null); + + /** UserList targetNetworkInfo */ + targetNetworkInfo?: (google.ads.datamanager.v1.ITargetNetworkInfo|null); + + /** UserList ingestedUserListInfo */ + ingestedUserListInfo?: (google.ads.datamanager.v1.IIngestedUserListInfo|null); + } + + /** Represents a UserList. */ + class UserList implements IUserList { + + /** + * Constructs a new UserList. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUserList); + + /** UserList name. */ + public name: string; + + /** UserList id. */ + public id: (number|Long|string); + + /** UserList readOnly. */ + public readOnly: boolean; + + /** UserList displayName. */ + public displayName?: (string|null); + + /** UserList description. */ + public description?: (string|null); + + /** UserList membershipStatus. */ + public membershipStatus?: (google.ads.datamanager.v1.UserList.MembershipStatus|keyof typeof google.ads.datamanager.v1.UserList.MembershipStatus|null); + + /** UserList integrationCode. */ + public integrationCode?: (string|null); + + /** UserList membershipDuration. */ + public membershipDuration?: (google.protobuf.IDuration|null); + + /** UserList closingReason. */ + public closingReason?: (google.ads.datamanager.v1.UserList.ClosingReason|keyof typeof google.ads.datamanager.v1.UserList.ClosingReason|null); + + /** UserList accessReason. */ + public accessReason: (google.ads.datamanager.v1.UserList.AccessReason|keyof typeof google.ads.datamanager.v1.UserList.AccessReason); + + /** UserList accountAccessStatus. */ + public accountAccessStatus?: (google.ads.datamanager.v1.UserList.AccessStatus|keyof typeof google.ads.datamanager.v1.UserList.AccessStatus|null); + + /** UserList sizeInfo. */ + public sizeInfo?: (google.ads.datamanager.v1.ISizeInfo|null); + + /** UserList targetNetworkInfo. */ + public targetNetworkInfo?: (google.ads.datamanager.v1.ITargetNetworkInfo|null); + + /** UserList ingestedUserListInfo. */ + public ingestedUserListInfo?: (google.ads.datamanager.v1.IIngestedUserListInfo|null); + + /** UserList userListInfo. */ + public userListInfo?: "ingestedUserListInfo"; + + /** + * Creates a new UserList instance using the specified properties. + * @param [properties] Properties to set + * @returns UserList instance + */ + public static create(properties?: google.ads.datamanager.v1.IUserList): google.ads.datamanager.v1.UserList; + + /** + * Encodes the specified UserList message. Does not implicitly {@link google.ads.datamanager.v1.UserList.verify|verify} messages. + * @param message UserList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUserList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UserList message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserList.verify|verify} messages. + * @param message UserList message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUserList, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a UserList message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UserList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UserList; + + /** + * Decodes a UserList message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UserList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UserList; + + /** + * Verifies a UserList message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a UserList message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserList + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UserList; + + /** + * Creates a plain object from a UserList message. Also converts values to other types if specified. + * @param message UserList + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UserList, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserList to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserList + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UserList { + + /** MembershipStatus enum. */ + enum MembershipStatus { + MEMBERSHIP_STATUS_UNSPECIFIED = 0, + OPEN = 1, + CLOSED = 2 + } + + /** ClosingReason enum. */ + enum ClosingReason { + CLOSING_REASON_UNSPECIFIED = 0, + UNUSED = 1 + } + + /** AccessReason enum. */ + enum AccessReason { + ACCESS_REASON_UNSPECIFIED = 0, + OWNED = 1, + SHARED = 2, + LICENSED = 3, + SUBSCRIBED = 4, + AFFILIATED = 5 + } + + /** AccessStatus enum. */ + enum AccessStatus { + ACCESS_STATUS_UNSPECIFIED = 0, + ENABLED = 1, + DISABLED = 2 + } + } + + /** Properties of a SizeInfo. */ + interface ISizeInfo { + + /** SizeInfo displayNetworkMembersCount */ + displayNetworkMembersCount?: (number|Long|string|null); + + /** SizeInfo searchNetworkMembersCount */ + searchNetworkMembersCount?: (number|Long|string|null); + } + + /** Represents a SizeInfo. */ + class SizeInfo implements ISizeInfo { + + /** + * Constructs a new SizeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ISizeInfo); + + /** SizeInfo displayNetworkMembersCount. */ + public displayNetworkMembersCount: (number|Long|string); + + /** SizeInfo searchNetworkMembersCount. */ + public searchNetworkMembersCount: (number|Long|string); + + /** + * Creates a new SizeInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SizeInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.ISizeInfo): google.ads.datamanager.v1.SizeInfo; + + /** + * Encodes the specified SizeInfo message. Does not implicitly {@link google.ads.datamanager.v1.SizeInfo.verify|verify} messages. + * @param message SizeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ISizeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SizeInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.SizeInfo.verify|verify} messages. + * @param message SizeInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ISizeInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SizeInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SizeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.SizeInfo; + + /** + * Decodes a SizeInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SizeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.SizeInfo; + + /** + * Verifies a SizeInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SizeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SizeInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.SizeInfo; + + /** + * Creates a plain object from a SizeInfo message. Also converts values to other types if specified. + * @param message SizeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.SizeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SizeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SizeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TargetNetworkInfo. */ + interface ITargetNetworkInfo { + + /** TargetNetworkInfo eligibleForDisplay */ + eligibleForDisplay?: (boolean|null); + + /** TargetNetworkInfo eligibleForSearch */ + eligibleForSearch?: (boolean|null); + } + + /** Represents a TargetNetworkInfo. */ + class TargetNetworkInfo implements ITargetNetworkInfo { + + /** + * Constructs a new TargetNetworkInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ITargetNetworkInfo); + + /** TargetNetworkInfo eligibleForDisplay. */ + public eligibleForDisplay: boolean; + + /** TargetNetworkInfo eligibleForSearch. */ + public eligibleForSearch?: (boolean|null); + + /** + * Creates a new TargetNetworkInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns TargetNetworkInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.ITargetNetworkInfo): google.ads.datamanager.v1.TargetNetworkInfo; + + /** + * Encodes the specified TargetNetworkInfo message. Does not implicitly {@link google.ads.datamanager.v1.TargetNetworkInfo.verify|verify} messages. + * @param message TargetNetworkInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ITargetNetworkInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TargetNetworkInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.TargetNetworkInfo.verify|verify} messages. + * @param message TargetNetworkInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ITargetNetworkInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TargetNetworkInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TargetNetworkInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.TargetNetworkInfo; + + /** + * Decodes a TargetNetworkInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TargetNetworkInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.TargetNetworkInfo; + + /** + * Verifies a TargetNetworkInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TargetNetworkInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetNetworkInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.TargetNetworkInfo; + + /** + * Creates a plain object from a TargetNetworkInfo message. Also converts values to other types if specified. + * @param message TargetNetworkInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.TargetNetworkInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetNetworkInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetNetworkInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an IngestedUserListInfo. */ + interface IIngestedUserListInfo { + + /** IngestedUserListInfo uploadKeyTypes */ + uploadKeyTypes?: (google.ads.datamanager.v1.IngestedUserListInfo.UploadKeyType[]|null); + + /** IngestedUserListInfo contactIdInfo */ + contactIdInfo?: (google.ads.datamanager.v1.IContactIdInfo|null); + + /** IngestedUserListInfo mobileIdInfo */ + mobileIdInfo?: (google.ads.datamanager.v1.IMobileIdInfo|null); + + /** IngestedUserListInfo userIdInfo */ + userIdInfo?: (google.ads.datamanager.v1.IUserIdInfo|null); + + /** IngestedUserListInfo pairIdInfo */ + pairIdInfo?: (google.ads.datamanager.v1.IPairIdInfo|null); + + /** IngestedUserListInfo pseudonymousIdInfo */ + pseudonymousIdInfo?: (google.ads.datamanager.v1.IPseudonymousIdInfo|null); + + /** IngestedUserListInfo partnerAudienceInfo */ + partnerAudienceInfo?: (google.ads.datamanager.v1.IPartnerAudienceInfo|null); + } + + /** Represents an IngestedUserListInfo. */ + class IngestedUserListInfo implements IIngestedUserListInfo { + + /** + * Constructs a new IngestedUserListInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IIngestedUserListInfo); + + /** IngestedUserListInfo uploadKeyTypes. */ + public uploadKeyTypes: google.ads.datamanager.v1.IngestedUserListInfo.UploadKeyType[]; + + /** IngestedUserListInfo contactIdInfo. */ + public contactIdInfo?: (google.ads.datamanager.v1.IContactIdInfo|null); + + /** IngestedUserListInfo mobileIdInfo. */ + public mobileIdInfo?: (google.ads.datamanager.v1.IMobileIdInfo|null); + + /** IngestedUserListInfo userIdInfo. */ + public userIdInfo?: (google.ads.datamanager.v1.IUserIdInfo|null); + + /** IngestedUserListInfo pairIdInfo. */ + public pairIdInfo?: (google.ads.datamanager.v1.IPairIdInfo|null); + + /** IngestedUserListInfo pseudonymousIdInfo. */ + public pseudonymousIdInfo?: (google.ads.datamanager.v1.IPseudonymousIdInfo|null); + + /** IngestedUserListInfo partnerAudienceInfo. */ + public partnerAudienceInfo?: (google.ads.datamanager.v1.IPartnerAudienceInfo|null); + + /** + * Creates a new IngestedUserListInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns IngestedUserListInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IIngestedUserListInfo): google.ads.datamanager.v1.IngestedUserListInfo; + + /** + * Encodes the specified IngestedUserListInfo message. Does not implicitly {@link google.ads.datamanager.v1.IngestedUserListInfo.verify|verify} messages. + * @param message IngestedUserListInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IIngestedUserListInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified IngestedUserListInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.IngestedUserListInfo.verify|verify} messages. + * @param message IngestedUserListInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IIngestedUserListInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an IngestedUserListInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns IngestedUserListInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.IngestedUserListInfo; + + /** + * Decodes an IngestedUserListInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns IngestedUserListInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.IngestedUserListInfo; + + /** + * Verifies an IngestedUserListInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an IngestedUserListInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IngestedUserListInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.IngestedUserListInfo; + + /** + * Creates a plain object from an IngestedUserListInfo message. Also converts values to other types if specified. + * @param message IngestedUserListInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.IngestedUserListInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IngestedUserListInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IngestedUserListInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IngestedUserListInfo { + + /** UploadKeyType enum. */ + enum UploadKeyType { + UPLOAD_KEY_TYPE_UNSPECIFIED = 0, + CONTACT_ID = 1, + MOBILE_ID = 2, + USER_ID = 3, + PAIR_ID = 4, + PSEUDONYMOUS_ID = 5 + } + } + + /** Properties of a ContactIdInfo. */ + interface IContactIdInfo { + + /** ContactIdInfo dataSourceType */ + dataSourceType?: (google.ads.datamanager.v1.DataSourceType|keyof typeof google.ads.datamanager.v1.DataSourceType|null); + + /** ContactIdInfo matchRatePercentage */ + matchRatePercentage?: (number|null); + } + + /** Represents a ContactIdInfo. */ + class ContactIdInfo implements IContactIdInfo { + + /** + * Constructs a new ContactIdInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IContactIdInfo); + + /** ContactIdInfo dataSourceType. */ + public dataSourceType?: (google.ads.datamanager.v1.DataSourceType|keyof typeof google.ads.datamanager.v1.DataSourceType|null); + + /** ContactIdInfo matchRatePercentage. */ + public matchRatePercentage: number; + + /** + * Creates a new ContactIdInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns ContactIdInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IContactIdInfo): google.ads.datamanager.v1.ContactIdInfo; + + /** + * Encodes the specified ContactIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.ContactIdInfo.verify|verify} messages. + * @param message ContactIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IContactIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ContactIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ContactIdInfo.verify|verify} messages. + * @param message ContactIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IContactIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ContactIdInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ContactIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ContactIdInfo; + + /** + * Decodes a ContactIdInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ContactIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ContactIdInfo; + + /** + * Verifies a ContactIdInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ContactIdInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ContactIdInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ContactIdInfo; + + /** + * Creates a plain object from a ContactIdInfo message. Also converts values to other types if specified. + * @param message ContactIdInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ContactIdInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ContactIdInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ContactIdInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MobileIdInfo. */ + interface IMobileIdInfo { + + /** MobileIdInfo dataSourceType */ + dataSourceType?: (google.ads.datamanager.v1.DataSourceType|keyof typeof google.ads.datamanager.v1.DataSourceType|null); + + /** MobileIdInfo keySpace */ + keySpace?: (google.ads.datamanager.v1.MobileIdInfo.KeySpace|keyof typeof google.ads.datamanager.v1.MobileIdInfo.KeySpace|null); + + /** MobileIdInfo appId */ + appId?: (string|null); + } + + /** Represents a MobileIdInfo. */ + class MobileIdInfo implements IMobileIdInfo { + + /** + * Constructs a new MobileIdInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IMobileIdInfo); + + /** MobileIdInfo dataSourceType. */ + public dataSourceType?: (google.ads.datamanager.v1.DataSourceType|keyof typeof google.ads.datamanager.v1.DataSourceType|null); + + /** MobileIdInfo keySpace. */ + public keySpace?: (google.ads.datamanager.v1.MobileIdInfo.KeySpace|keyof typeof google.ads.datamanager.v1.MobileIdInfo.KeySpace|null); + + /** MobileIdInfo appId. */ + public appId?: (string|null); + + /** + * Creates a new MobileIdInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns MobileIdInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IMobileIdInfo): google.ads.datamanager.v1.MobileIdInfo; + + /** + * Encodes the specified MobileIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.MobileIdInfo.verify|verify} messages. + * @param message MobileIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IMobileIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MobileIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.MobileIdInfo.verify|verify} messages. + * @param message MobileIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IMobileIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MobileIdInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MobileIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.MobileIdInfo; + + /** + * Decodes a MobileIdInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MobileIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.MobileIdInfo; + + /** + * Verifies a MobileIdInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MobileIdInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MobileIdInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.MobileIdInfo; + + /** + * Creates a plain object from a MobileIdInfo message. Also converts values to other types if specified. + * @param message MobileIdInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.MobileIdInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MobileIdInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MobileIdInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MobileIdInfo { + + /** KeySpace enum. */ + enum KeySpace { + KEY_SPACE_UNSPECIFIED = 0, + IOS = 1, + ANDROID = 2 + } + } + + /** Properties of a UserIdInfo. */ + interface IUserIdInfo { + + /** UserIdInfo dataSourceType */ + dataSourceType?: (google.ads.datamanager.v1.DataSourceType|keyof typeof google.ads.datamanager.v1.DataSourceType|null); + } + + /** Represents a UserIdInfo. */ + class UserIdInfo implements IUserIdInfo { + + /** + * Constructs a new UserIdInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUserIdInfo); + + /** UserIdInfo dataSourceType. */ + public dataSourceType?: (google.ads.datamanager.v1.DataSourceType|keyof typeof google.ads.datamanager.v1.DataSourceType|null); + + /** + * Creates a new UserIdInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns UserIdInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IUserIdInfo): google.ads.datamanager.v1.UserIdInfo; + + /** + * Encodes the specified UserIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.UserIdInfo.verify|verify} messages. + * @param message UserIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUserIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UserIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserIdInfo.verify|verify} messages. + * @param message UserIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUserIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a UserIdInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UserIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UserIdInfo; + + /** + * Decodes a UserIdInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UserIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UserIdInfo; + + /** + * Verifies a UserIdInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a UserIdInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserIdInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UserIdInfo; + + /** + * Creates a plain object from a UserIdInfo message. Also converts values to other types if specified. + * @param message UserIdInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UserIdInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserIdInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserIdInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PairIdInfo. */ + interface IPairIdInfo { + + /** PairIdInfo publisherId */ + publisherId?: (number|Long|string|null); + + /** PairIdInfo publisherName */ + publisherName?: (string|null); + + /** PairIdInfo matchRatePercentage */ + matchRatePercentage?: (number|null); + + /** PairIdInfo advertiserIdentifierCount */ + advertiserIdentifierCount?: (number|Long|string|null); + + /** PairIdInfo cleanRoomIdentifier */ + cleanRoomIdentifier?: (string|null); + } + + /** Represents a PairIdInfo. */ + class PairIdInfo implements IPairIdInfo { + + /** + * Constructs a new PairIdInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IPairIdInfo); + + /** PairIdInfo publisherId. */ + public publisherId?: (number|Long|string|null); + + /** PairIdInfo publisherName. */ + public publisherName?: (string|null); + + /** PairIdInfo matchRatePercentage. */ + public matchRatePercentage: number; + + /** PairIdInfo advertiserIdentifierCount. */ + public advertiserIdentifierCount: (number|Long|string); + + /** PairIdInfo cleanRoomIdentifier. */ + public cleanRoomIdentifier?: (string|null); + + /** + * Creates a new PairIdInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns PairIdInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IPairIdInfo): google.ads.datamanager.v1.PairIdInfo; + + /** + * Encodes the specified PairIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.PairIdInfo.verify|verify} messages. + * @param message PairIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IPairIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PairIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PairIdInfo.verify|verify} messages. + * @param message PairIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IPairIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PairIdInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PairIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.PairIdInfo; + + /** + * Decodes a PairIdInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PairIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.PairIdInfo; + + /** + * Verifies a PairIdInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PairIdInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PairIdInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.PairIdInfo; + + /** + * Creates a plain object from a PairIdInfo message. Also converts values to other types if specified. + * @param message PairIdInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.PairIdInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PairIdInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PairIdInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartnerAudienceInfo. */ + interface IPartnerAudienceInfo { + + /** PartnerAudienceInfo partnerAudienceSource */ + partnerAudienceSource?: (google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource|keyof typeof google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource|null); + + /** PartnerAudienceInfo commercePartner */ + commercePartner?: (string|null); + } + + /** Represents a PartnerAudienceInfo. */ + class PartnerAudienceInfo implements IPartnerAudienceInfo { + + /** + * Constructs a new PartnerAudienceInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IPartnerAudienceInfo); + + /** PartnerAudienceInfo partnerAudienceSource. */ + public partnerAudienceSource?: (google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource|keyof typeof google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource|null); + + /** PartnerAudienceInfo commercePartner. */ + public commercePartner?: (string|null); + + /** + * Creates a new PartnerAudienceInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns PartnerAudienceInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IPartnerAudienceInfo): google.ads.datamanager.v1.PartnerAudienceInfo; + + /** + * Encodes the specified PartnerAudienceInfo message. Does not implicitly {@link google.ads.datamanager.v1.PartnerAudienceInfo.verify|verify} messages. + * @param message PartnerAudienceInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IPartnerAudienceInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PartnerAudienceInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PartnerAudienceInfo.verify|verify} messages. + * @param message PartnerAudienceInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IPartnerAudienceInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PartnerAudienceInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PartnerAudienceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.PartnerAudienceInfo; + + /** + * Decodes a PartnerAudienceInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PartnerAudienceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.PartnerAudienceInfo; + + /** + * Verifies a PartnerAudienceInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PartnerAudienceInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartnerAudienceInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.PartnerAudienceInfo; + + /** + * Creates a plain object from a PartnerAudienceInfo message. Also converts values to other types if specified. + * @param message PartnerAudienceInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.PartnerAudienceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartnerAudienceInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartnerAudienceInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PartnerAudienceInfo { + + /** PartnerAudienceSource enum. */ + enum PartnerAudienceSource { + PARTNER_AUDIENCE_SOURCE_UNSPECIFIED = 0, + COMMERCE_AUDIENCE = 1, + LINEAR_TV_AUDIENCE = 2, + AGENCY_PROVIDER_AUDIENCE = 3 + } + } + + /** Properties of a PseudonymousIdInfo. */ + interface IPseudonymousIdInfo { + + /** PseudonymousIdInfo syncStatus */ + syncStatus?: (google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus|keyof typeof google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus|null); + + /** PseudonymousIdInfo billableRecordCount */ + billableRecordCount?: (number|Long|string|null); + } + + /** Represents a PseudonymousIdInfo. */ + class PseudonymousIdInfo implements IPseudonymousIdInfo { + + /** + * Constructs a new PseudonymousIdInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IPseudonymousIdInfo); + + /** PseudonymousIdInfo syncStatus. */ + public syncStatus?: (google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus|keyof typeof google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus|null); + + /** PseudonymousIdInfo billableRecordCount. */ + public billableRecordCount?: (number|Long|string|null); + + /** + * Creates a new PseudonymousIdInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns PseudonymousIdInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IPseudonymousIdInfo): google.ads.datamanager.v1.PseudonymousIdInfo; + + /** + * Encodes the specified PseudonymousIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.PseudonymousIdInfo.verify|verify} messages. + * @param message PseudonymousIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IPseudonymousIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PseudonymousIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PseudonymousIdInfo.verify|verify} messages. + * @param message PseudonymousIdInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IPseudonymousIdInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PseudonymousIdInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PseudonymousIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.PseudonymousIdInfo; + + /** + * Decodes a PseudonymousIdInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PseudonymousIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.PseudonymousIdInfo; + + /** + * Verifies a PseudonymousIdInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PseudonymousIdInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PseudonymousIdInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.PseudonymousIdInfo; + + /** + * Creates a plain object from a PseudonymousIdInfo message. Also converts values to other types if specified. + * @param message PseudonymousIdInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.PseudonymousIdInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PseudonymousIdInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PseudonymousIdInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace PseudonymousIdInfo { + + /** SyncStatus enum. */ + enum SyncStatus { + SYNC_STATUS_UNSPECIFIED = 0, + CREATED = 1, + READY_FOR_USE = 2, + FAILED = 3 + } + } + + /** DataSourceType enum. */ + enum DataSourceType { + DATA_SOURCE_TYPE_UNSPECIFIED = 0, + DATA_SOURCE_TYPE_FIRST_PARTY = 1, + DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU = 2, + DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE = 3, + DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA = 4 + } + + /** Properties of a UserListDirectLicense. */ + interface IUserListDirectLicense { + + /** UserListDirectLicense name */ + name?: (string|null); + + /** UserListDirectLicense userListId */ + userListId?: (number|Long|string|null); + + /** UserListDirectLicense userListDisplayName */ + userListDisplayName?: (string|null); + + /** UserListDirectLicense clientAccountType */ + clientAccountType?: (google.ads.datamanager.v1.UserListLicenseClientAccountType|keyof typeof google.ads.datamanager.v1.UserListLicenseClientAccountType|null); + + /** UserListDirectLicense clientAccountId */ + clientAccountId?: (number|Long|string|null); + + /** UserListDirectLicense clientAccountDisplayName */ + clientAccountDisplayName?: (string|null); + + /** UserListDirectLicense status */ + status?: (google.ads.datamanager.v1.UserListLicenseStatus|keyof typeof google.ads.datamanager.v1.UserListLicenseStatus|null); + + /** UserListDirectLicense pricing */ + pricing?: (google.ads.datamanager.v1.IUserListLicensePricing|null); + + /** UserListDirectLicense historicalPricings */ + historicalPricings?: (google.ads.datamanager.v1.IUserListLicensePricing[]|null); + + /** UserListDirectLicense metrics */ + metrics?: (google.ads.datamanager.v1.IUserListLicenseMetrics|null); + } + + /** Represents a UserListDirectLicense. */ + class UserListDirectLicense implements IUserListDirectLicense { + + /** + * Constructs a new UserListDirectLicense. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUserListDirectLicense); + + /** UserListDirectLicense name. */ + public name: string; + + /** UserListDirectLicense userListId. */ + public userListId?: (number|Long|string|null); + + /** UserListDirectLicense userListDisplayName. */ + public userListDisplayName: string; + + /** UserListDirectLicense clientAccountType. */ + public clientAccountType?: (google.ads.datamanager.v1.UserListLicenseClientAccountType|keyof typeof google.ads.datamanager.v1.UserListLicenseClientAccountType|null); + + /** UserListDirectLicense clientAccountId. */ + public clientAccountId?: (number|Long|string|null); + + /** UserListDirectLicense clientAccountDisplayName. */ + public clientAccountDisplayName: string; + + /** UserListDirectLicense status. */ + public status?: (google.ads.datamanager.v1.UserListLicenseStatus|keyof typeof google.ads.datamanager.v1.UserListLicenseStatus|null); + + /** UserListDirectLicense pricing. */ + public pricing?: (google.ads.datamanager.v1.IUserListLicensePricing|null); + + /** UserListDirectLicense historicalPricings. */ + public historicalPricings: google.ads.datamanager.v1.IUserListLicensePricing[]; + + /** UserListDirectLicense metrics. */ + public metrics?: (google.ads.datamanager.v1.IUserListLicenseMetrics|null); + + /** + * Creates a new UserListDirectLicense instance using the specified properties. + * @param [properties] Properties to set + * @returns UserListDirectLicense instance + */ + public static create(properties?: google.ads.datamanager.v1.IUserListDirectLicense): google.ads.datamanager.v1.UserListDirectLicense; + + /** + * Encodes the specified UserListDirectLicense message. Does not implicitly {@link google.ads.datamanager.v1.UserListDirectLicense.verify|verify} messages. + * @param message UserListDirectLicense message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUserListDirectLicense, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UserListDirectLicense message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListDirectLicense.verify|verify} messages. + * @param message UserListDirectLicense message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUserListDirectLicense, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a UserListDirectLicense message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UserListDirectLicense + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UserListDirectLicense; + + /** + * Decodes a UserListDirectLicense message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UserListDirectLicense + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UserListDirectLicense; + + /** + * Verifies a UserListDirectLicense message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a UserListDirectLicense message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserListDirectLicense + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UserListDirectLicense; + + /** + * Creates a plain object from a UserListDirectLicense message. Also converts values to other types if specified. + * @param message UserListDirectLicense + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UserListDirectLicense, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserListDirectLicense to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserListDirectLicense + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** UserListLicenseClientAccountType enum. */ + enum UserListLicenseClientAccountType { + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN = 0, + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_ADS = 1, + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_PARTNER = 2, + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_ADVERTISER = 3, + USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_AD_MANAGER_AUDIENCE_LINK = 4 + } + + /** Properties of a UserListLicenseMetrics. */ + interface IUserListLicenseMetrics { + + /** UserListLicenseMetrics clickCount */ + clickCount?: (number|Long|string|null); + + /** UserListLicenseMetrics impressionCount */ + impressionCount?: (number|Long|string|null); + + /** UserListLicenseMetrics revenueUsdMicros */ + revenueUsdMicros?: (number|Long|string|null); + + /** UserListLicenseMetrics startDate */ + startDate?: (number|Long|string|null); + + /** UserListLicenseMetrics endDate */ + endDate?: (number|Long|string|null); + } + + /** Represents a UserListLicenseMetrics. */ + class UserListLicenseMetrics implements IUserListLicenseMetrics { + + /** + * Constructs a new UserListLicenseMetrics. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUserListLicenseMetrics); + + /** UserListLicenseMetrics clickCount. */ + public clickCount: (number|Long|string); + + /** UserListLicenseMetrics impressionCount. */ + public impressionCount: (number|Long|string); + + /** UserListLicenseMetrics revenueUsdMicros. */ + public revenueUsdMicros: (number|Long|string); + + /** UserListLicenseMetrics startDate. */ + public startDate: (number|Long|string); + + /** UserListLicenseMetrics endDate. */ + public endDate: (number|Long|string); + + /** + * Creates a new UserListLicenseMetrics instance using the specified properties. + * @param [properties] Properties to set + * @returns UserListLicenseMetrics instance + */ + public static create(properties?: google.ads.datamanager.v1.IUserListLicenseMetrics): google.ads.datamanager.v1.UserListLicenseMetrics; + + /** + * Encodes the specified UserListLicenseMetrics message. Does not implicitly {@link google.ads.datamanager.v1.UserListLicenseMetrics.verify|verify} messages. + * @param message UserListLicenseMetrics message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUserListLicenseMetrics, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UserListLicenseMetrics message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListLicenseMetrics.verify|verify} messages. + * @param message UserListLicenseMetrics message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUserListLicenseMetrics, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a UserListLicenseMetrics message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UserListLicenseMetrics + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UserListLicenseMetrics; + + /** + * Decodes a UserListLicenseMetrics message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UserListLicenseMetrics + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UserListLicenseMetrics; + + /** + * Verifies a UserListLicenseMetrics message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a UserListLicenseMetrics message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserListLicenseMetrics + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UserListLicenseMetrics; + + /** + * Creates a plain object from a UserListLicenseMetrics message. Also converts values to other types if specified. + * @param message UserListLicenseMetrics + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UserListLicenseMetrics, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserListLicenseMetrics to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserListLicenseMetrics + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UserListLicensePricing. */ + interface IUserListLicensePricing { + + /** UserListLicensePricing pricingId */ + pricingId?: (number|Long|string|null); + + /** UserListLicensePricing costMicros */ + costMicros?: (number|Long|string|null); + + /** UserListLicensePricing currencyCode */ + currencyCode?: (string|null); + + /** UserListLicensePricing startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** UserListLicensePricing endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** UserListLicensePricing pricingActive */ + pricingActive?: (boolean|null); + + /** UserListLicensePricing buyerApprovalState */ + buyerApprovalState?: (google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState|keyof typeof google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState|null); + + /** UserListLicensePricing costType */ + costType?: (google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType|keyof typeof google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType|null); + + /** UserListLicensePricing maxCostMicros */ + maxCostMicros?: (number|Long|string|null); + } + + /** Represents a UserListLicensePricing. */ + class UserListLicensePricing implements IUserListLicensePricing { + + /** + * Constructs a new UserListLicensePricing. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUserListLicensePricing); + + /** UserListLicensePricing pricingId. */ + public pricingId: (number|Long|string); + + /** UserListLicensePricing costMicros. */ + public costMicros?: (number|Long|string|null); + + /** UserListLicensePricing currencyCode. */ + public currencyCode?: (string|null); + + /** UserListLicensePricing startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** UserListLicensePricing endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** UserListLicensePricing pricingActive. */ + public pricingActive: boolean; + + /** UserListLicensePricing buyerApprovalState. */ + public buyerApprovalState: (google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState|keyof typeof google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState); + + /** UserListLicensePricing costType. */ + public costType?: (google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType|keyof typeof google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType|null); + + /** UserListLicensePricing maxCostMicros. */ + public maxCostMicros?: (number|Long|string|null); + + /** + * Creates a new UserListLicensePricing instance using the specified properties. + * @param [properties] Properties to set + * @returns UserListLicensePricing instance + */ + public static create(properties?: google.ads.datamanager.v1.IUserListLicensePricing): google.ads.datamanager.v1.UserListLicensePricing; + + /** + * Encodes the specified UserListLicensePricing message. Does not implicitly {@link google.ads.datamanager.v1.UserListLicensePricing.verify|verify} messages. + * @param message UserListLicensePricing message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUserListLicensePricing, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UserListLicensePricing message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListLicensePricing.verify|verify} messages. + * @param message UserListLicensePricing message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUserListLicensePricing, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a UserListLicensePricing message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UserListLicensePricing + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UserListLicensePricing; + + /** + * Decodes a UserListLicensePricing message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UserListLicensePricing + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UserListLicensePricing; + + /** + * Verifies a UserListLicensePricing message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a UserListLicensePricing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserListLicensePricing + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UserListLicensePricing; + + /** + * Creates a plain object from a UserListLicensePricing message. Also converts values to other types if specified. + * @param message UserListLicensePricing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UserListLicensePricing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserListLicensePricing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserListLicensePricing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UserListLicensePricing { + + /** UserListPricingBuyerApprovalState enum. */ + enum UserListPricingBuyerApprovalState { + USER_LIST_PRICING_BUYER_APPROVAL_STATE_UNSPECIFIED = 0, + PENDING = 1, + APPROVED = 2, + REJECTED = 3 + } + + /** UserListPricingCostType enum. */ + enum UserListPricingCostType { + USER_LIST_PRICING_COST_TYPE_UNSPECIFIED = 0, + CPC = 1, + CPM = 2, + MEDIA_SHARE = 3 + } + } + + /** UserListLicenseStatus enum. */ + enum UserListLicenseStatus { + USER_LIST_LICENSE_STATUS_UNSPECIFIED = 0, + USER_LIST_LICENSE_STATUS_ENABLED = 1, + USER_LIST_LICENSE_STATUS_DISABLED = 2 + } + + /** Represents a UserListDirectLicenseService */ + class UserListDirectLicenseService extends $protobuf.rpc.Service { + + /** + * Constructs a new UserListDirectLicenseService service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new UserListDirectLicenseService service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): UserListDirectLicenseService; + + /** + * Calls CreateUserListDirectLicense. + * @param request CreateUserListDirectLicenseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserListDirectLicense + */ + public createUserListDirectLicense(request: google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, callback: google.ads.datamanager.v1.UserListDirectLicenseService.CreateUserListDirectLicenseCallback): void; + + /** + * Calls CreateUserListDirectLicense. + * @param request CreateUserListDirectLicenseRequest message or plain object + * @returns Promise + */ + public createUserListDirectLicense(request: google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest): Promise; + + /** + * Calls GetUserListDirectLicense. + * @param request GetUserListDirectLicenseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserListDirectLicense + */ + public getUserListDirectLicense(request: google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, callback: google.ads.datamanager.v1.UserListDirectLicenseService.GetUserListDirectLicenseCallback): void; + + /** + * Calls GetUserListDirectLicense. + * @param request GetUserListDirectLicenseRequest message or plain object + * @returns Promise + */ + public getUserListDirectLicense(request: google.ads.datamanager.v1.IGetUserListDirectLicenseRequest): Promise; + + /** + * Calls UpdateUserListDirectLicense. + * @param request UpdateUserListDirectLicenseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserListDirectLicense + */ + public updateUserListDirectLicense(request: google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, callback: google.ads.datamanager.v1.UserListDirectLicenseService.UpdateUserListDirectLicenseCallback): void; + + /** + * Calls UpdateUserListDirectLicense. + * @param request UpdateUserListDirectLicenseRequest message or plain object + * @returns Promise + */ + public updateUserListDirectLicense(request: google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest): Promise; + + /** + * Calls ListUserListDirectLicenses. + * @param request ListUserListDirectLicensesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListUserListDirectLicensesResponse + */ + public listUserListDirectLicenses(request: google.ads.datamanager.v1.IListUserListDirectLicensesRequest, callback: google.ads.datamanager.v1.UserListDirectLicenseService.ListUserListDirectLicensesCallback): void; + + /** + * Calls ListUserListDirectLicenses. + * @param request ListUserListDirectLicensesRequest message or plain object + * @returns Promise + */ + public listUserListDirectLicenses(request: google.ads.datamanager.v1.IListUserListDirectLicensesRequest): Promise; + } + + namespace UserListDirectLicenseService { + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListDirectLicenseService|createUserListDirectLicense}. + * @param error Error, if any + * @param [response] UserListDirectLicense + */ + type CreateUserListDirectLicenseCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserListDirectLicense) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListDirectLicenseService|getUserListDirectLicense}. + * @param error Error, if any + * @param [response] UserListDirectLicense + */ + type GetUserListDirectLicenseCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserListDirectLicense) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListDirectLicenseService|updateUserListDirectLicense}. + * @param error Error, if any + * @param [response] UserListDirectLicense + */ + type UpdateUserListDirectLicenseCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserListDirectLicense) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListDirectLicenseService|listUserListDirectLicenses}. + * @param error Error, if any + * @param [response] ListUserListDirectLicensesResponse + */ + type ListUserListDirectLicensesCallback = (error: (Error|null), response?: google.ads.datamanager.v1.ListUserListDirectLicensesResponse) => void; + } + + /** Properties of a CreateUserListDirectLicenseRequest. */ + interface ICreateUserListDirectLicenseRequest { + + /** CreateUserListDirectLicenseRequest parent */ + parent?: (string|null); + + /** CreateUserListDirectLicenseRequest userListDirectLicense */ + userListDirectLicense?: (google.ads.datamanager.v1.IUserListDirectLicense|null); + } + + /** Represents a CreateUserListDirectLicenseRequest. */ + class CreateUserListDirectLicenseRequest implements ICreateUserListDirectLicenseRequest { + + /** + * Constructs a new CreateUserListDirectLicenseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest); + + /** CreateUserListDirectLicenseRequest parent. */ + public parent: string; + + /** CreateUserListDirectLicenseRequest userListDirectLicense. */ + public userListDirectLicense?: (google.ads.datamanager.v1.IUserListDirectLicense|null); + + /** + * Creates a new CreateUserListDirectLicenseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateUserListDirectLicenseRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest): google.ads.datamanager.v1.CreateUserListDirectLicenseRequest; + + /** + * Encodes the specified CreateUserListDirectLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListDirectLicenseRequest.verify|verify} messages. + * @param message CreateUserListDirectLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateUserListDirectLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListDirectLicenseRequest.verify|verify} messages. + * @param message CreateUserListDirectLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateUserListDirectLicenseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.CreateUserListDirectLicenseRequest; + + /** + * Decodes a CreateUserListDirectLicenseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.CreateUserListDirectLicenseRequest; + + /** + * Verifies a CreateUserListDirectLicenseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateUserListDirectLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateUserListDirectLicenseRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.CreateUserListDirectLicenseRequest; + + /** + * Creates a plain object from a CreateUserListDirectLicenseRequest message. Also converts values to other types if specified. + * @param message CreateUserListDirectLicenseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.CreateUserListDirectLicenseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateUserListDirectLicenseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateUserListDirectLicenseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetUserListDirectLicenseRequest. */ + interface IGetUserListDirectLicenseRequest { + + /** GetUserListDirectLicenseRequest name */ + name?: (string|null); + } + + /** Represents a GetUserListDirectLicenseRequest. */ + class GetUserListDirectLicenseRequest implements IGetUserListDirectLicenseRequest { + + /** + * Constructs a new GetUserListDirectLicenseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IGetUserListDirectLicenseRequest); + + /** GetUserListDirectLicenseRequest name. */ + public name: string; + + /** + * Creates a new GetUserListDirectLicenseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetUserListDirectLicenseRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IGetUserListDirectLicenseRequest): google.ads.datamanager.v1.GetUserListDirectLicenseRequest; + + /** + * Encodes the specified GetUserListDirectLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.GetUserListDirectLicenseRequest.verify|verify} messages. + * @param message GetUserListDirectLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetUserListDirectLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.GetUserListDirectLicenseRequest.verify|verify} messages. + * @param message GetUserListDirectLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetUserListDirectLicenseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.GetUserListDirectLicenseRequest; + + /** + * Decodes a GetUserListDirectLicenseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.GetUserListDirectLicenseRequest; + + /** + * Verifies a GetUserListDirectLicenseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetUserListDirectLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetUserListDirectLicenseRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.GetUserListDirectLicenseRequest; + + /** + * Creates a plain object from a GetUserListDirectLicenseRequest message. Also converts values to other types if specified. + * @param message GetUserListDirectLicenseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.GetUserListDirectLicenseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetUserListDirectLicenseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetUserListDirectLicenseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateUserListDirectLicenseRequest. */ + interface IUpdateUserListDirectLicenseRequest { + + /** UpdateUserListDirectLicenseRequest userListDirectLicense */ + userListDirectLicense?: (google.ads.datamanager.v1.IUserListDirectLicense|null); + + /** UpdateUserListDirectLicenseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateUserListDirectLicenseRequest. */ + class UpdateUserListDirectLicenseRequest implements IUpdateUserListDirectLicenseRequest { + + /** + * Constructs a new UpdateUserListDirectLicenseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest); + + /** UpdateUserListDirectLicenseRequest userListDirectLicense. */ + public userListDirectLicense?: (google.ads.datamanager.v1.IUserListDirectLicense|null); + + /** UpdateUserListDirectLicenseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new UpdateUserListDirectLicenseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateUserListDirectLicenseRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest): google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest; + + /** + * Encodes the specified UpdateUserListDirectLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest.verify|verify} messages. + * @param message UpdateUserListDirectLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateUserListDirectLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest.verify|verify} messages. + * @param message UpdateUserListDirectLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateUserListDirectLicenseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest; + + /** + * Decodes an UpdateUserListDirectLicenseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest; + + /** + * Verifies an UpdateUserListDirectLicenseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateUserListDirectLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateUserListDirectLicenseRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest; + + /** + * Creates a plain object from an UpdateUserListDirectLicenseRequest message. Also converts values to other types if specified. + * @param message UpdateUserListDirectLicenseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateUserListDirectLicenseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateUserListDirectLicenseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserListDirectLicensesRequest. */ + interface IListUserListDirectLicensesRequest { + + /** ListUserListDirectLicensesRequest parent */ + parent?: (string|null); + + /** ListUserListDirectLicensesRequest filter */ + filter?: (string|null); + + /** ListUserListDirectLicensesRequest pageSize */ + pageSize?: (number|null); + + /** ListUserListDirectLicensesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListUserListDirectLicensesRequest. */ + class ListUserListDirectLicensesRequest implements IListUserListDirectLicensesRequest { + + /** + * Constructs a new ListUserListDirectLicensesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IListUserListDirectLicensesRequest); + + /** ListUserListDirectLicensesRequest parent. */ + public parent: string; + + /** ListUserListDirectLicensesRequest filter. */ + public filter: string; + + /** ListUserListDirectLicensesRequest pageSize. */ + public pageSize: number; + + /** ListUserListDirectLicensesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListUserListDirectLicensesRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListUserListDirectLicensesRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IListUserListDirectLicensesRequest): google.ads.datamanager.v1.ListUserListDirectLicensesRequest; + + /** + * Encodes the specified ListUserListDirectLicensesRequest message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListDirectLicensesRequest.verify|verify} messages. + * @param message ListUserListDirectLicensesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IListUserListDirectLicensesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListUserListDirectLicensesRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListDirectLicensesRequest.verify|verify} messages. + * @param message ListUserListDirectLicensesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IListUserListDirectLicensesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListUserListDirectLicensesRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListUserListDirectLicensesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ListUserListDirectLicensesRequest; + + /** + * Decodes a ListUserListDirectLicensesRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListUserListDirectLicensesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ListUserListDirectLicensesRequest; + + /** + * Verifies a ListUserListDirectLicensesRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListUserListDirectLicensesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserListDirectLicensesRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ListUserListDirectLicensesRequest; + + /** + * Creates a plain object from a ListUserListDirectLicensesRequest message. Also converts values to other types if specified. + * @param message ListUserListDirectLicensesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ListUserListDirectLicensesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserListDirectLicensesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserListDirectLicensesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserListDirectLicensesResponse. */ + interface IListUserListDirectLicensesResponse { + + /** ListUserListDirectLicensesResponse userListDirectLicenses */ + userListDirectLicenses?: (google.ads.datamanager.v1.IUserListDirectLicense[]|null); + + /** ListUserListDirectLicensesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListUserListDirectLicensesResponse. */ + class ListUserListDirectLicensesResponse implements IListUserListDirectLicensesResponse { + + /** + * Constructs a new ListUserListDirectLicensesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IListUserListDirectLicensesResponse); + + /** ListUserListDirectLicensesResponse userListDirectLicenses. */ + public userListDirectLicenses: google.ads.datamanager.v1.IUserListDirectLicense[]; + + /** ListUserListDirectLicensesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListUserListDirectLicensesResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListUserListDirectLicensesResponse instance + */ + public static create(properties?: google.ads.datamanager.v1.IListUserListDirectLicensesResponse): google.ads.datamanager.v1.ListUserListDirectLicensesResponse; + + /** + * Encodes the specified ListUserListDirectLicensesResponse message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListDirectLicensesResponse.verify|verify} messages. + * @param message ListUserListDirectLicensesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IListUserListDirectLicensesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListUserListDirectLicensesResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListDirectLicensesResponse.verify|verify} messages. + * @param message ListUserListDirectLicensesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IListUserListDirectLicensesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListUserListDirectLicensesResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListUserListDirectLicensesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ListUserListDirectLicensesResponse; + + /** + * Decodes a ListUserListDirectLicensesResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListUserListDirectLicensesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ListUserListDirectLicensesResponse; + + /** + * Verifies a ListUserListDirectLicensesResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListUserListDirectLicensesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserListDirectLicensesResponse + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ListUserListDirectLicensesResponse; + + /** + * Creates a plain object from a ListUserListDirectLicensesResponse message. Also converts values to other types if specified. + * @param message ListUserListDirectLicensesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ListUserListDirectLicensesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserListDirectLicensesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserListDirectLicensesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UserListGlobalLicense. */ + interface IUserListGlobalLicense { + + /** UserListGlobalLicense name */ + name?: (string|null); + + /** UserListGlobalLicense userListId */ + userListId?: (number|Long|string|null); + + /** UserListGlobalLicense userListDisplayName */ + userListDisplayName?: (string|null); + + /** UserListGlobalLicense licenseType */ + licenseType?: (google.ads.datamanager.v1.UserListGlobalLicenseType|keyof typeof google.ads.datamanager.v1.UserListGlobalLicenseType|null); + + /** UserListGlobalLicense status */ + status?: (google.ads.datamanager.v1.UserListLicenseStatus|keyof typeof google.ads.datamanager.v1.UserListLicenseStatus|null); + + /** UserListGlobalLicense pricing */ + pricing?: (google.ads.datamanager.v1.IUserListLicensePricing|null); + + /** UserListGlobalLicense historicalPricings */ + historicalPricings?: (google.ads.datamanager.v1.IUserListLicensePricing[]|null); + + /** UserListGlobalLicense metrics */ + metrics?: (google.ads.datamanager.v1.IUserListLicenseMetrics|null); + } + + /** Represents a UserListGlobalLicense. */ + class UserListGlobalLicense implements IUserListGlobalLicense { + + /** + * Constructs a new UserListGlobalLicense. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUserListGlobalLicense); + + /** UserListGlobalLicense name. */ + public name: string; + + /** UserListGlobalLicense userListId. */ + public userListId?: (number|Long|string|null); + + /** UserListGlobalLicense userListDisplayName. */ + public userListDisplayName: string; + + /** UserListGlobalLicense licenseType. */ + public licenseType?: (google.ads.datamanager.v1.UserListGlobalLicenseType|keyof typeof google.ads.datamanager.v1.UserListGlobalLicenseType|null); + + /** UserListGlobalLicense status. */ + public status?: (google.ads.datamanager.v1.UserListLicenseStatus|keyof typeof google.ads.datamanager.v1.UserListLicenseStatus|null); + + /** UserListGlobalLicense pricing. */ + public pricing?: (google.ads.datamanager.v1.IUserListLicensePricing|null); + + /** UserListGlobalLicense historicalPricings. */ + public historicalPricings: google.ads.datamanager.v1.IUserListLicensePricing[]; + + /** UserListGlobalLicense metrics. */ + public metrics?: (google.ads.datamanager.v1.IUserListLicenseMetrics|null); + + /** + * Creates a new UserListGlobalLicense instance using the specified properties. + * @param [properties] Properties to set + * @returns UserListGlobalLicense instance + */ + public static create(properties?: google.ads.datamanager.v1.IUserListGlobalLicense): google.ads.datamanager.v1.UserListGlobalLicense; + + /** + * Encodes the specified UserListGlobalLicense message. Does not implicitly {@link google.ads.datamanager.v1.UserListGlobalLicense.verify|verify} messages. + * @param message UserListGlobalLicense message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUserListGlobalLicense, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UserListGlobalLicense message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListGlobalLicense.verify|verify} messages. + * @param message UserListGlobalLicense message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUserListGlobalLicense, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a UserListGlobalLicense message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UserListGlobalLicense + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UserListGlobalLicense; + + /** + * Decodes a UserListGlobalLicense message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UserListGlobalLicense + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UserListGlobalLicense; + + /** + * Verifies a UserListGlobalLicense message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a UserListGlobalLicense message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserListGlobalLicense + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UserListGlobalLicense; + + /** + * Creates a plain object from a UserListGlobalLicense message. Also converts values to other types if specified. + * @param message UserListGlobalLicense + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UserListGlobalLicense, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserListGlobalLicense to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserListGlobalLicense + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a UserListGlobalLicenseCustomerInfo. */ + interface IUserListGlobalLicenseCustomerInfo { + + /** UserListGlobalLicenseCustomerInfo name */ + name?: (string|null); + + /** UserListGlobalLicenseCustomerInfo userListId */ + userListId?: (number|Long|string|null); + + /** UserListGlobalLicenseCustomerInfo userListDisplayName */ + userListDisplayName?: (string|null); + + /** UserListGlobalLicenseCustomerInfo licenseType */ + licenseType?: (google.ads.datamanager.v1.UserListGlobalLicenseType|keyof typeof google.ads.datamanager.v1.UserListGlobalLicenseType|null); + + /** UserListGlobalLicenseCustomerInfo status */ + status?: (google.ads.datamanager.v1.UserListLicenseStatus|keyof typeof google.ads.datamanager.v1.UserListLicenseStatus|null); + + /** UserListGlobalLicenseCustomerInfo pricing */ + pricing?: (google.ads.datamanager.v1.IUserListLicensePricing|null); + + /** UserListGlobalLicenseCustomerInfo clientAccountType */ + clientAccountType?: (google.ads.datamanager.v1.UserListLicenseClientAccountType|keyof typeof google.ads.datamanager.v1.UserListLicenseClientAccountType|null); + + /** UserListGlobalLicenseCustomerInfo clientAccountId */ + clientAccountId?: (number|Long|string|null); + + /** UserListGlobalLicenseCustomerInfo clientAccountDisplayName */ + clientAccountDisplayName?: (string|null); + + /** UserListGlobalLicenseCustomerInfo historicalPricings */ + historicalPricings?: (google.ads.datamanager.v1.IUserListLicensePricing[]|null); + + /** UserListGlobalLicenseCustomerInfo metrics */ + metrics?: (google.ads.datamanager.v1.IUserListLicenseMetrics|null); + } + + /** Represents a UserListGlobalLicenseCustomerInfo. */ + class UserListGlobalLicenseCustomerInfo implements IUserListGlobalLicenseCustomerInfo { + + /** + * Constructs a new UserListGlobalLicenseCustomerInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo); + + /** UserListGlobalLicenseCustomerInfo name. */ + public name: string; + + /** UserListGlobalLicenseCustomerInfo userListId. */ + public userListId: (number|Long|string); + + /** UserListGlobalLicenseCustomerInfo userListDisplayName. */ + public userListDisplayName: string; + + /** UserListGlobalLicenseCustomerInfo licenseType. */ + public licenseType: (google.ads.datamanager.v1.UserListGlobalLicenseType|keyof typeof google.ads.datamanager.v1.UserListGlobalLicenseType); + + /** UserListGlobalLicenseCustomerInfo status. */ + public status: (google.ads.datamanager.v1.UserListLicenseStatus|keyof typeof google.ads.datamanager.v1.UserListLicenseStatus); + + /** UserListGlobalLicenseCustomerInfo pricing. */ + public pricing?: (google.ads.datamanager.v1.IUserListLicensePricing|null); + + /** UserListGlobalLicenseCustomerInfo clientAccountType. */ + public clientAccountType: (google.ads.datamanager.v1.UserListLicenseClientAccountType|keyof typeof google.ads.datamanager.v1.UserListLicenseClientAccountType); + + /** UserListGlobalLicenseCustomerInfo clientAccountId. */ + public clientAccountId: (number|Long|string); + + /** UserListGlobalLicenseCustomerInfo clientAccountDisplayName. */ + public clientAccountDisplayName: string; + + /** UserListGlobalLicenseCustomerInfo historicalPricings. */ + public historicalPricings: google.ads.datamanager.v1.IUserListLicensePricing[]; + + /** UserListGlobalLicenseCustomerInfo metrics. */ + public metrics?: (google.ads.datamanager.v1.IUserListLicenseMetrics|null); + + /** + * Creates a new UserListGlobalLicenseCustomerInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns UserListGlobalLicenseCustomerInfo instance + */ + public static create(properties?: google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo): google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo; + + /** + * Encodes the specified UserListGlobalLicenseCustomerInfo message. Does not implicitly {@link google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.verify|verify} messages. + * @param message UserListGlobalLicenseCustomerInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UserListGlobalLicenseCustomerInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.verify|verify} messages. + * @param message UserListGlobalLicenseCustomerInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a UserListGlobalLicenseCustomerInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UserListGlobalLicenseCustomerInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo; + + /** + * Decodes a UserListGlobalLicenseCustomerInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UserListGlobalLicenseCustomerInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo; + + /** + * Verifies a UserListGlobalLicenseCustomerInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a UserListGlobalLicenseCustomerInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserListGlobalLicenseCustomerInfo + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo; + + /** + * Creates a plain object from a UserListGlobalLicenseCustomerInfo message. Also converts values to other types if specified. + * @param message UserListGlobalLicenseCustomerInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserListGlobalLicenseCustomerInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserListGlobalLicenseCustomerInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** UserListGlobalLicenseType enum. */ + enum UserListGlobalLicenseType { + USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED = 0, + USER_LIST_GLOBAL_LICENSE_TYPE_RESELLER = 1, + USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_SELL_SIDE = 2, + USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_BUY_SIDE = 3 + } + + /** Represents a UserListGlobalLicenseService */ + class UserListGlobalLicenseService extends $protobuf.rpc.Service { + + /** + * Constructs a new UserListGlobalLicenseService service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new UserListGlobalLicenseService service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): UserListGlobalLicenseService; + + /** + * Calls CreateUserListGlobalLicense. + * @param request CreateUserListGlobalLicenseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserListGlobalLicense + */ + public createUserListGlobalLicense(request: google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, callback: google.ads.datamanager.v1.UserListGlobalLicenseService.CreateUserListGlobalLicenseCallback): void; + + /** + * Calls CreateUserListGlobalLicense. + * @param request CreateUserListGlobalLicenseRequest message or plain object + * @returns Promise + */ + public createUserListGlobalLicense(request: google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest): Promise; + + /** + * Calls UpdateUserListGlobalLicense. + * @param request UpdateUserListGlobalLicenseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserListGlobalLicense + */ + public updateUserListGlobalLicense(request: google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, callback: google.ads.datamanager.v1.UserListGlobalLicenseService.UpdateUserListGlobalLicenseCallback): void; + + /** + * Calls UpdateUserListGlobalLicense. + * @param request UpdateUserListGlobalLicenseRequest message or plain object + * @returns Promise + */ + public updateUserListGlobalLicense(request: google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest): Promise; + + /** + * Calls GetUserListGlobalLicense. + * @param request GetUserListGlobalLicenseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserListGlobalLicense + */ + public getUserListGlobalLicense(request: google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, callback: google.ads.datamanager.v1.UserListGlobalLicenseService.GetUserListGlobalLicenseCallback): void; + + /** + * Calls GetUserListGlobalLicense. + * @param request GetUserListGlobalLicenseRequest message or plain object + * @returns Promise + */ + public getUserListGlobalLicense(request: google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest): Promise; + + /** + * Calls ListUserListGlobalLicenses. + * @param request ListUserListGlobalLicensesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListUserListGlobalLicensesResponse + */ + public listUserListGlobalLicenses(request: google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, callback: google.ads.datamanager.v1.UserListGlobalLicenseService.ListUserListGlobalLicensesCallback): void; + + /** + * Calls ListUserListGlobalLicenses. + * @param request ListUserListGlobalLicensesRequest message or plain object + * @returns Promise + */ + public listUserListGlobalLicenses(request: google.ads.datamanager.v1.IListUserListGlobalLicensesRequest): Promise; + + /** + * Calls ListUserListGlobalLicenseCustomerInfos. + * @param request ListUserListGlobalLicenseCustomerInfosRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListUserListGlobalLicenseCustomerInfosResponse + */ + public listUserListGlobalLicenseCustomerInfos(request: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, callback: google.ads.datamanager.v1.UserListGlobalLicenseService.ListUserListGlobalLicenseCustomerInfosCallback): void; + + /** + * Calls ListUserListGlobalLicenseCustomerInfos. + * @param request ListUserListGlobalLicenseCustomerInfosRequest message or plain object + * @returns Promise + */ + public listUserListGlobalLicenseCustomerInfos(request: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest): Promise; + } + + namespace UserListGlobalLicenseService { + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|createUserListGlobalLicense}. + * @param error Error, if any + * @param [response] UserListGlobalLicense + */ + type CreateUserListGlobalLicenseCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserListGlobalLicense) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|updateUserListGlobalLicense}. + * @param error Error, if any + * @param [response] UserListGlobalLicense + */ + type UpdateUserListGlobalLicenseCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserListGlobalLicense) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|getUserListGlobalLicense}. + * @param error Error, if any + * @param [response] UserListGlobalLicense + */ + type GetUserListGlobalLicenseCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserListGlobalLicense) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|listUserListGlobalLicenses}. + * @param error Error, if any + * @param [response] ListUserListGlobalLicensesResponse + */ + type ListUserListGlobalLicensesCallback = (error: (Error|null), response?: google.ads.datamanager.v1.ListUserListGlobalLicensesResponse) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|listUserListGlobalLicenseCustomerInfos}. + * @param error Error, if any + * @param [response] ListUserListGlobalLicenseCustomerInfosResponse + */ + type ListUserListGlobalLicenseCustomerInfosCallback = (error: (Error|null), response?: google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse) => void; + } + + /** Properties of a CreateUserListGlobalLicenseRequest. */ + interface ICreateUserListGlobalLicenseRequest { + + /** CreateUserListGlobalLicenseRequest parent */ + parent?: (string|null); + + /** CreateUserListGlobalLicenseRequest userListGlobalLicense */ + userListGlobalLicense?: (google.ads.datamanager.v1.IUserListGlobalLicense|null); + } + + /** Represents a CreateUserListGlobalLicenseRequest. */ + class CreateUserListGlobalLicenseRequest implements ICreateUserListGlobalLicenseRequest { + + /** + * Constructs a new CreateUserListGlobalLicenseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest); + + /** CreateUserListGlobalLicenseRequest parent. */ + public parent: string; + + /** CreateUserListGlobalLicenseRequest userListGlobalLicense. */ + public userListGlobalLicense?: (google.ads.datamanager.v1.IUserListGlobalLicense|null); + + /** + * Creates a new CreateUserListGlobalLicenseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateUserListGlobalLicenseRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest): google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest; + + /** + * Encodes the specified CreateUserListGlobalLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest.verify|verify} messages. + * @param message CreateUserListGlobalLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateUserListGlobalLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest.verify|verify} messages. + * @param message CreateUserListGlobalLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateUserListGlobalLicenseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest; + + /** + * Decodes a CreateUserListGlobalLicenseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest; + + /** + * Verifies a CreateUserListGlobalLicenseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateUserListGlobalLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateUserListGlobalLicenseRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest; + + /** + * Creates a plain object from a CreateUserListGlobalLicenseRequest message. Also converts values to other types if specified. + * @param message CreateUserListGlobalLicenseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateUserListGlobalLicenseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateUserListGlobalLicenseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateUserListGlobalLicenseRequest. */ + interface IUpdateUserListGlobalLicenseRequest { + + /** UpdateUserListGlobalLicenseRequest userListGlobalLicense */ + userListGlobalLicense?: (google.ads.datamanager.v1.IUserListGlobalLicense|null); + + /** UpdateUserListGlobalLicenseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateUserListGlobalLicenseRequest. */ + class UpdateUserListGlobalLicenseRequest implements IUpdateUserListGlobalLicenseRequest { + + /** + * Constructs a new UpdateUserListGlobalLicenseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest); + + /** UpdateUserListGlobalLicenseRequest userListGlobalLicense. */ + public userListGlobalLicense?: (google.ads.datamanager.v1.IUserListGlobalLicense|null); + + /** UpdateUserListGlobalLicenseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates a new UpdateUserListGlobalLicenseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateUserListGlobalLicenseRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest): google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest; + + /** + * Encodes the specified UpdateUserListGlobalLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest.verify|verify} messages. + * @param message UpdateUserListGlobalLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateUserListGlobalLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest.verify|verify} messages. + * @param message UpdateUserListGlobalLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateUserListGlobalLicenseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest; + + /** + * Decodes an UpdateUserListGlobalLicenseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest; + + /** + * Verifies an UpdateUserListGlobalLicenseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateUserListGlobalLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateUserListGlobalLicenseRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest; + + /** + * Creates a plain object from an UpdateUserListGlobalLicenseRequest message. Also converts values to other types if specified. + * @param message UpdateUserListGlobalLicenseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateUserListGlobalLicenseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateUserListGlobalLicenseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetUserListGlobalLicenseRequest. */ + interface IGetUserListGlobalLicenseRequest { + + /** GetUserListGlobalLicenseRequest name */ + name?: (string|null); + } + + /** Represents a GetUserListGlobalLicenseRequest. */ + class GetUserListGlobalLicenseRequest implements IGetUserListGlobalLicenseRequest { + + /** + * Constructs a new GetUserListGlobalLicenseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest); + + /** GetUserListGlobalLicenseRequest name. */ + public name: string; + + /** + * Creates a new GetUserListGlobalLicenseRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetUserListGlobalLicenseRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest): google.ads.datamanager.v1.GetUserListGlobalLicenseRequest; + + /** + * Encodes the specified GetUserListGlobalLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.GetUserListGlobalLicenseRequest.verify|verify} messages. + * @param message GetUserListGlobalLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetUserListGlobalLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.GetUserListGlobalLicenseRequest.verify|verify} messages. + * @param message GetUserListGlobalLicenseRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetUserListGlobalLicenseRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.GetUserListGlobalLicenseRequest; + + /** + * Decodes a GetUserListGlobalLicenseRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.GetUserListGlobalLicenseRequest; + + /** + * Verifies a GetUserListGlobalLicenseRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetUserListGlobalLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetUserListGlobalLicenseRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.GetUserListGlobalLicenseRequest; + + /** + * Creates a plain object from a GetUserListGlobalLicenseRequest message. Also converts values to other types if specified. + * @param message GetUserListGlobalLicenseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.GetUserListGlobalLicenseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetUserListGlobalLicenseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetUserListGlobalLicenseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserListGlobalLicensesRequest. */ + interface IListUserListGlobalLicensesRequest { + + /** ListUserListGlobalLicensesRequest parent */ + parent?: (string|null); + + /** ListUserListGlobalLicensesRequest filter */ + filter?: (string|null); + + /** ListUserListGlobalLicensesRequest pageSize */ + pageSize?: (number|null); + + /** ListUserListGlobalLicensesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListUserListGlobalLicensesRequest. */ + class ListUserListGlobalLicensesRequest implements IListUserListGlobalLicensesRequest { + + /** + * Constructs a new ListUserListGlobalLicensesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IListUserListGlobalLicensesRequest); + + /** ListUserListGlobalLicensesRequest parent. */ + public parent: string; + + /** ListUserListGlobalLicensesRequest filter. */ + public filter: string; + + /** ListUserListGlobalLicensesRequest pageSize. */ + public pageSize: number; + + /** ListUserListGlobalLicensesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListUserListGlobalLicensesRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListUserListGlobalLicensesRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IListUserListGlobalLicensesRequest): google.ads.datamanager.v1.ListUserListGlobalLicensesRequest; + + /** + * Encodes the specified ListUserListGlobalLicensesRequest message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicensesRequest.verify|verify} messages. + * @param message ListUserListGlobalLicensesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListUserListGlobalLicensesRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicensesRequest.verify|verify} messages. + * @param message ListUserListGlobalLicensesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListUserListGlobalLicensesRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListUserListGlobalLicensesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ListUserListGlobalLicensesRequest; + + /** + * Decodes a ListUserListGlobalLicensesRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListUserListGlobalLicensesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ListUserListGlobalLicensesRequest; + + /** + * Verifies a ListUserListGlobalLicensesRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListUserListGlobalLicensesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserListGlobalLicensesRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ListUserListGlobalLicensesRequest; + + /** + * Creates a plain object from a ListUserListGlobalLicensesRequest message. Also converts values to other types if specified. + * @param message ListUserListGlobalLicensesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ListUserListGlobalLicensesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserListGlobalLicensesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserListGlobalLicensesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserListGlobalLicensesResponse. */ + interface IListUserListGlobalLicensesResponse { + + /** ListUserListGlobalLicensesResponse userListGlobalLicenses */ + userListGlobalLicenses?: (google.ads.datamanager.v1.IUserListGlobalLicense[]|null); + + /** ListUserListGlobalLicensesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListUserListGlobalLicensesResponse. */ + class ListUserListGlobalLicensesResponse implements IListUserListGlobalLicensesResponse { + + /** + * Constructs a new ListUserListGlobalLicensesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IListUserListGlobalLicensesResponse); + + /** ListUserListGlobalLicensesResponse userListGlobalLicenses. */ + public userListGlobalLicenses: google.ads.datamanager.v1.IUserListGlobalLicense[]; + + /** ListUserListGlobalLicensesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListUserListGlobalLicensesResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListUserListGlobalLicensesResponse instance + */ + public static create(properties?: google.ads.datamanager.v1.IListUserListGlobalLicensesResponse): google.ads.datamanager.v1.ListUserListGlobalLicensesResponse; + + /** + * Encodes the specified ListUserListGlobalLicensesResponse message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicensesResponse.verify|verify} messages. + * @param message ListUserListGlobalLicensesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IListUserListGlobalLicensesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListUserListGlobalLicensesResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicensesResponse.verify|verify} messages. + * @param message ListUserListGlobalLicensesResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IListUserListGlobalLicensesResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListUserListGlobalLicensesResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListUserListGlobalLicensesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ListUserListGlobalLicensesResponse; + + /** + * Decodes a ListUserListGlobalLicensesResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListUserListGlobalLicensesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ListUserListGlobalLicensesResponse; + + /** + * Verifies a ListUserListGlobalLicensesResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListUserListGlobalLicensesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserListGlobalLicensesResponse + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ListUserListGlobalLicensesResponse; + + /** + * Creates a plain object from a ListUserListGlobalLicensesResponse message. Also converts values to other types if specified. + * @param message ListUserListGlobalLicensesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ListUserListGlobalLicensesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserListGlobalLicensesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserListGlobalLicensesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserListGlobalLicenseCustomerInfosRequest. */ + interface IListUserListGlobalLicenseCustomerInfosRequest { + + /** ListUserListGlobalLicenseCustomerInfosRequest parent */ + parent?: (string|null); + + /** ListUserListGlobalLicenseCustomerInfosRequest filter */ + filter?: (string|null); + + /** ListUserListGlobalLicenseCustomerInfosRequest pageSize */ + pageSize?: (number|null); + + /** ListUserListGlobalLicenseCustomerInfosRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListUserListGlobalLicenseCustomerInfosRequest. */ + class ListUserListGlobalLicenseCustomerInfosRequest implements IListUserListGlobalLicenseCustomerInfosRequest { + + /** + * Constructs a new ListUserListGlobalLicenseCustomerInfosRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest); + + /** ListUserListGlobalLicenseCustomerInfosRequest parent. */ + public parent: string; + + /** ListUserListGlobalLicenseCustomerInfosRequest filter. */ + public filter: string; + + /** ListUserListGlobalLicenseCustomerInfosRequest pageSize. */ + public pageSize: number; + + /** ListUserListGlobalLicenseCustomerInfosRequest pageToken. */ + public pageToken: string; + + /** + * Creates a new ListUserListGlobalLicenseCustomerInfosRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListUserListGlobalLicenseCustomerInfosRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest): google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest; + + /** + * Encodes the specified ListUserListGlobalLicenseCustomerInfosRequest message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest.verify|verify} messages. + * @param message ListUserListGlobalLicenseCustomerInfosRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListUserListGlobalLicenseCustomerInfosRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest.verify|verify} messages. + * @param message ListUserListGlobalLicenseCustomerInfosRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListUserListGlobalLicenseCustomerInfosRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListUserListGlobalLicenseCustomerInfosRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest; + + /** + * Decodes a ListUserListGlobalLicenseCustomerInfosRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListUserListGlobalLicenseCustomerInfosRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest; + + /** + * Verifies a ListUserListGlobalLicenseCustomerInfosRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListUserListGlobalLicenseCustomerInfosRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserListGlobalLicenseCustomerInfosRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest; + + /** + * Creates a plain object from a ListUserListGlobalLicenseCustomerInfosRequest message. Also converts values to other types if specified. + * @param message ListUserListGlobalLicenseCustomerInfosRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserListGlobalLicenseCustomerInfosRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserListGlobalLicenseCustomerInfosRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserListGlobalLicenseCustomerInfosResponse. */ + interface IListUserListGlobalLicenseCustomerInfosResponse { + + /** ListUserListGlobalLicenseCustomerInfosResponse userListGlobalLicenseCustomerInfos */ + userListGlobalLicenseCustomerInfos?: (google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[]|null); + + /** ListUserListGlobalLicenseCustomerInfosResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListUserListGlobalLicenseCustomerInfosResponse. */ + class ListUserListGlobalLicenseCustomerInfosResponse implements IListUserListGlobalLicenseCustomerInfosResponse { + + /** + * Constructs a new ListUserListGlobalLicenseCustomerInfosResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse); + + /** ListUserListGlobalLicenseCustomerInfosResponse userListGlobalLicenseCustomerInfos. */ + public userListGlobalLicenseCustomerInfos: google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[]; + + /** ListUserListGlobalLicenseCustomerInfosResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListUserListGlobalLicenseCustomerInfosResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListUserListGlobalLicenseCustomerInfosResponse instance + */ + public static create(properties?: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse): google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse; + + /** + * Encodes the specified ListUserListGlobalLicenseCustomerInfosResponse message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse.verify|verify} messages. + * @param message ListUserListGlobalLicenseCustomerInfosResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListUserListGlobalLicenseCustomerInfosResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse.verify|verify} messages. + * @param message ListUserListGlobalLicenseCustomerInfosResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListUserListGlobalLicenseCustomerInfosResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListUserListGlobalLicenseCustomerInfosResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse; + + /** + * Decodes a ListUserListGlobalLicenseCustomerInfosResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListUserListGlobalLicenseCustomerInfosResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse; + + /** + * Verifies a ListUserListGlobalLicenseCustomerInfosResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListUserListGlobalLicenseCustomerInfosResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserListGlobalLicenseCustomerInfosResponse + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse; + + /** + * Creates a plain object from a ListUserListGlobalLicenseCustomerInfosResponse message. Also converts values to other types if specified. + * @param message ListUserListGlobalLicenseCustomerInfosResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserListGlobalLicenseCustomerInfosResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserListGlobalLicenseCustomerInfosResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents a UserListService */ + class UserListService extends $protobuf.rpc.Service { + + /** + * Constructs a new UserListService service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new UserListService service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): UserListService; + + /** + * Calls GetUserList. + * @param request GetUserListRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserList + */ + public getUserList(request: google.ads.datamanager.v1.IGetUserListRequest, callback: google.ads.datamanager.v1.UserListService.GetUserListCallback): void; + + /** + * Calls GetUserList. + * @param request GetUserListRequest message or plain object + * @returns Promise + */ + public getUserList(request: google.ads.datamanager.v1.IGetUserListRequest): Promise; + + /** + * Calls ListUserLists. + * @param request ListUserListsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListUserListsResponse + */ + public listUserLists(request: google.ads.datamanager.v1.IListUserListsRequest, callback: google.ads.datamanager.v1.UserListService.ListUserListsCallback): void; + + /** + * Calls ListUserLists. + * @param request ListUserListsRequest message or plain object + * @returns Promise + */ + public listUserLists(request: google.ads.datamanager.v1.IListUserListsRequest): Promise; + + /** + * Calls CreateUserList. + * @param request CreateUserListRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserList + */ + public createUserList(request: google.ads.datamanager.v1.ICreateUserListRequest, callback: google.ads.datamanager.v1.UserListService.CreateUserListCallback): void; + + /** + * Calls CreateUserList. + * @param request CreateUserListRequest message or plain object + * @returns Promise + */ + public createUserList(request: google.ads.datamanager.v1.ICreateUserListRequest): Promise; + + /** + * Calls UpdateUserList. + * @param request UpdateUserListRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserList + */ + public updateUserList(request: google.ads.datamanager.v1.IUpdateUserListRequest, callback: google.ads.datamanager.v1.UserListService.UpdateUserListCallback): void; + + /** + * Calls UpdateUserList. + * @param request UpdateUserListRequest message or plain object + * @returns Promise + */ + public updateUserList(request: google.ads.datamanager.v1.IUpdateUserListRequest): Promise; + + /** + * Calls DeleteUserList. + * @param request DeleteUserListRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteUserList(request: google.ads.datamanager.v1.IDeleteUserListRequest, callback: google.ads.datamanager.v1.UserListService.DeleteUserListCallback): void; + + /** + * Calls DeleteUserList. + * @param request DeleteUserListRequest message or plain object + * @returns Promise + */ + public deleteUserList(request: google.ads.datamanager.v1.IDeleteUserListRequest): Promise; + } + + namespace UserListService { + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|getUserList}. + * @param error Error, if any + * @param [response] UserList + */ + type GetUserListCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserList) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|listUserLists}. + * @param error Error, if any + * @param [response] ListUserListsResponse + */ + type ListUserListsCallback = (error: (Error|null), response?: google.ads.datamanager.v1.ListUserListsResponse) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|createUserList}. + * @param error Error, if any + * @param [response] UserList + */ + type CreateUserListCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserList) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|updateUserList}. + * @param error Error, if any + * @param [response] UserList + */ + type UpdateUserListCallback = (error: (Error|null), response?: google.ads.datamanager.v1.UserList) => void; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|deleteUserList}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteUserListCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + } + + /** Properties of a GetUserListRequest. */ + interface IGetUserListRequest { + + /** GetUserListRequest name */ + name?: (string|null); + } + + /** Represents a GetUserListRequest. */ + class GetUserListRequest implements IGetUserListRequest { + + /** + * Constructs a new GetUserListRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IGetUserListRequest); + + /** GetUserListRequest name. */ + public name: string; + + /** + * Creates a new GetUserListRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetUserListRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.IGetUserListRequest): google.ads.datamanager.v1.GetUserListRequest; + + /** + * Encodes the specified GetUserListRequest message. Does not implicitly {@link google.ads.datamanager.v1.GetUserListRequest.verify|verify} messages. + * @param message GetUserListRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IGetUserListRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetUserListRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.GetUserListRequest.verify|verify} messages. + * @param message GetUserListRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IGetUserListRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetUserListRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetUserListRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.GetUserListRequest; + + /** + * Decodes a GetUserListRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetUserListRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.GetUserListRequest; + + /** + * Verifies a GetUserListRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetUserListRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetUserListRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.GetUserListRequest; + + /** + * Creates a plain object from a GetUserListRequest message. Also converts values to other types if specified. + * @param message GetUserListRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.GetUserListRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ErrorInfo to JSON. + * Converts this GetUserListRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ErrorInfo + * Gets the default type url for GetUserListRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an ErrorCount. */ - interface IErrorCount { + /** Properties of a ListUserListsRequest. */ + interface IListUserListsRequest { - /** ErrorCount recordCount */ - recordCount?: (number|Long|string|null); + /** ListUserListsRequest parent */ + parent?: (string|null); - /** ErrorCount reason */ - reason?: (google.ads.datamanager.v1.ProcessingErrorReason|keyof typeof google.ads.datamanager.v1.ProcessingErrorReason|null); + /** ListUserListsRequest pageSize */ + pageSize?: (number|null); + + /** ListUserListsRequest pageToken */ + pageToken?: (string|null); + + /** ListUserListsRequest filter */ + filter?: (string|null); } - /** Represents an ErrorCount. */ - class ErrorCount implements IErrorCount { + /** Represents a ListUserListsRequest. */ + class ListUserListsRequest implements IListUserListsRequest { /** - * Constructs a new ErrorCount. + * Constructs a new ListUserListsRequest. * @param [properties] Properties to set */ - constructor(properties?: google.ads.datamanager.v1.IErrorCount); + constructor(properties?: google.ads.datamanager.v1.IListUserListsRequest); - /** ErrorCount recordCount. */ - public recordCount: (number|Long|string); + /** ListUserListsRequest parent. */ + public parent: string; - /** ErrorCount reason. */ - public reason: (google.ads.datamanager.v1.ProcessingErrorReason|keyof typeof google.ads.datamanager.v1.ProcessingErrorReason); + /** ListUserListsRequest pageSize. */ + public pageSize: number; + + /** ListUserListsRequest pageToken. */ + public pageToken: string; + + /** ListUserListsRequest filter. */ + public filter: string; /** - * Creates a new ErrorCount instance using the specified properties. + * Creates a new ListUserListsRequest instance using the specified properties. * @param [properties] Properties to set - * @returns ErrorCount instance + * @returns ListUserListsRequest instance */ - public static create(properties?: google.ads.datamanager.v1.IErrorCount): google.ads.datamanager.v1.ErrorCount; + public static create(properties?: google.ads.datamanager.v1.IListUserListsRequest): google.ads.datamanager.v1.ListUserListsRequest; /** - * Encodes the specified ErrorCount message. Does not implicitly {@link google.ads.datamanager.v1.ErrorCount.verify|verify} messages. - * @param message ErrorCount message or plain object to encode + * Encodes the specified ListUserListsRequest message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListsRequest.verify|verify} messages. + * @param message ListUserListsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ - public static encode(message: google.ads.datamanager.v1.IErrorCount, writer?: $protobuf.Writer): $protobuf.Writer; + public static encode(message: google.ads.datamanager.v1.IListUserListsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** - * Encodes the specified ErrorCount message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ErrorCount.verify|verify} messages. - * @param message ErrorCount message or plain object to encode + * Encodes the specified ListUserListsRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListsRequest.verify|verify} messages. + * @param message ListUserListsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ - public static encodeDelimited(message: google.ads.datamanager.v1.IErrorCount, writer?: $protobuf.Writer): $protobuf.Writer; + public static encodeDelimited(message: google.ads.datamanager.v1.IListUserListsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** - * Decodes an ErrorCount message from the specified reader or buffer. + * Decodes a ListUserListsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand - * @returns ErrorCount + * @returns ListUserListsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ListUserListsRequest; + + /** + * Decodes a ListUserListsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListUserListsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ListUserListsRequest; + + /** + * Verifies a ListUserListsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListUserListsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserListsRequest + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ListUserListsRequest; + + /** + * Creates a plain object from a ListUserListsRequest message. Also converts values to other types if specified. + * @param message ListUserListsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ListUserListsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserListsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserListsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserListsResponse. */ + interface IListUserListsResponse { + + /** ListUserListsResponse userLists */ + userLists?: (google.ads.datamanager.v1.IUserList[]|null); + + /** ListUserListsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListUserListsResponse. */ + class ListUserListsResponse implements IListUserListsResponse { + + /** + * Constructs a new ListUserListsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.IListUserListsResponse); + + /** ListUserListsResponse userLists. */ + public userLists: google.ads.datamanager.v1.IUserList[]; + + /** ListUserListsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a new ListUserListsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ListUserListsResponse instance + */ + public static create(properties?: google.ads.datamanager.v1.IListUserListsResponse): google.ads.datamanager.v1.ListUserListsResponse; + + /** + * Encodes the specified ListUserListsResponse message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListsResponse.verify|verify} messages. + * @param message ListUserListsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.IListUserListsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListUserListsResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListsResponse.verify|verify} messages. + * @param message ListUserListsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.IListUserListsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListUserListsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListUserListsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ListUserListsResponse; + + /** + * Decodes a ListUserListsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListUserListsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ListUserListsResponse; + + /** + * Verifies a ListUserListsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListUserListsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserListsResponse + */ + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ListUserListsResponse; + + /** + * Creates a plain object from a ListUserListsResponse message. Also converts values to other types if specified. + * @param message ListUserListsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.ads.datamanager.v1.ListUserListsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserListsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserListsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateUserListRequest. */ + interface ICreateUserListRequest { + + /** CreateUserListRequest parent */ + parent?: (string|null); + + /** CreateUserListRequest userList */ + userList?: (google.ads.datamanager.v1.IUserList|null); + + /** CreateUserListRequest validateOnly */ + validateOnly?: (boolean|null); + } + + /** Represents a CreateUserListRequest. */ + class CreateUserListRequest implements ICreateUserListRequest { + + /** + * Constructs a new CreateUserListRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.ads.datamanager.v1.ICreateUserListRequest); + + /** CreateUserListRequest parent. */ + public parent: string; + + /** CreateUserListRequest userList. */ + public userList?: (google.ads.datamanager.v1.IUserList|null); + + /** CreateUserListRequest validateOnly. */ + public validateOnly: boolean; + + /** + * Creates a new CreateUserListRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateUserListRequest instance + */ + public static create(properties?: google.ads.datamanager.v1.ICreateUserListRequest): google.ads.datamanager.v1.CreateUserListRequest; + + /** + * Encodes the specified CreateUserListRequest message. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListRequest.verify|verify} messages. + * @param message CreateUserListRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.ads.datamanager.v1.ICreateUserListRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateUserListRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListRequest.verify|verify} messages. + * @param message CreateUserListRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.ads.datamanager.v1.ICreateUserListRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateUserListRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.ErrorCount; + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.CreateUserListRequest; /** - * Decodes an ErrorCount message from the specified reader or buffer, length delimited. + * Decodes a CreateUserListRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from - * @returns ErrorCount + * @returns CreateUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.ErrorCount; + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.CreateUserListRequest; /** - * Verifies an ErrorCount message. + * Verifies a CreateUserListRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** - * Creates an ErrorCount message from a plain object. Also converts values to their respective internal types. + * Creates a CreateUserListRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ErrorCount + * @returns CreateUserListRequest */ - public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.ErrorCount; + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.CreateUserListRequest; /** - * Creates a plain object from an ErrorCount message. Also converts values to other types if specified. - * @param message ErrorCount + * Creates a plain object from a CreateUserListRequest message. Also converts values to other types if specified. + * @param message CreateUserListRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.ads.datamanager.v1.ErrorCount, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.ads.datamanager.v1.CreateUserListRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ErrorCount to JSON. + * Converts this CreateUserListRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ErrorCount + * Gets the default type url for CreateUserListRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a WarningInfo. */ - interface IWarningInfo { + /** Properties of an UpdateUserListRequest. */ + interface IUpdateUserListRequest { - /** WarningInfo warningCounts */ - warningCounts?: (google.ads.datamanager.v1.IWarningCount[]|null); + /** UpdateUserListRequest userList */ + userList?: (google.ads.datamanager.v1.IUserList|null); + + /** UpdateUserListRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + + /** UpdateUserListRequest validateOnly */ + validateOnly?: (boolean|null); } - /** Represents a WarningInfo. */ - class WarningInfo implements IWarningInfo { + /** Represents an UpdateUserListRequest. */ + class UpdateUserListRequest implements IUpdateUserListRequest { /** - * Constructs a new WarningInfo. + * Constructs a new UpdateUserListRequest. * @param [properties] Properties to set */ - constructor(properties?: google.ads.datamanager.v1.IWarningInfo); + constructor(properties?: google.ads.datamanager.v1.IUpdateUserListRequest); - /** WarningInfo warningCounts. */ - public warningCounts: google.ads.datamanager.v1.IWarningCount[]; + /** UpdateUserListRequest userList. */ + public userList?: (google.ads.datamanager.v1.IUserList|null); + + /** UpdateUserListRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** UpdateUserListRequest validateOnly. */ + public validateOnly: boolean; /** - * Creates a new WarningInfo instance using the specified properties. + * Creates a new UpdateUserListRequest instance using the specified properties. * @param [properties] Properties to set - * @returns WarningInfo instance + * @returns UpdateUserListRequest instance */ - public static create(properties?: google.ads.datamanager.v1.IWarningInfo): google.ads.datamanager.v1.WarningInfo; + public static create(properties?: google.ads.datamanager.v1.IUpdateUserListRequest): google.ads.datamanager.v1.UpdateUserListRequest; /** - * Encodes the specified WarningInfo message. Does not implicitly {@link google.ads.datamanager.v1.WarningInfo.verify|verify} messages. - * @param message WarningInfo message or plain object to encode + * Encodes the specified UpdateUserListRequest message. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListRequest.verify|verify} messages. + * @param message UpdateUserListRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ - public static encode(message: google.ads.datamanager.v1.IWarningInfo, writer?: $protobuf.Writer): $protobuf.Writer; + public static encode(message: google.ads.datamanager.v1.IUpdateUserListRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** - * Encodes the specified WarningInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.WarningInfo.verify|verify} messages. - * @param message WarningInfo message or plain object to encode + * Encodes the specified UpdateUserListRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListRequest.verify|verify} messages. + * @param message UpdateUserListRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ - public static encodeDelimited(message: google.ads.datamanager.v1.IWarningInfo, writer?: $protobuf.Writer): $protobuf.Writer; + public static encodeDelimited(message: google.ads.datamanager.v1.IUpdateUserListRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** - * Decodes a WarningInfo message from the specified reader or buffer. + * Decodes an UpdateUserListRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand - * @returns WarningInfo + * @returns UpdateUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.WarningInfo; + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.UpdateUserListRequest; /** - * Decodes a WarningInfo message from the specified reader or buffer, length delimited. + * Decodes an UpdateUserListRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from - * @returns WarningInfo + * @returns UpdateUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.WarningInfo; + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.UpdateUserListRequest; /** - * Verifies a WarningInfo message. + * Verifies an UpdateUserListRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** - * Creates a WarningInfo message from a plain object. Also converts values to their respective internal types. + * Creates an UpdateUserListRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns WarningInfo + * @returns UpdateUserListRequest */ - public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.WarningInfo; + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.UpdateUserListRequest; /** - * Creates a plain object from a WarningInfo message. Also converts values to other types if specified. - * @param message WarningInfo + * Creates a plain object from an UpdateUserListRequest message. Also converts values to other types if specified. + * @param message UpdateUserListRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.ads.datamanager.v1.WarningInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.ads.datamanager.v1.UpdateUserListRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this WarningInfo to JSON. + * Converts this UpdateUserListRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for WarningInfo + * Gets the default type url for UpdateUserListRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a WarningCount. */ - interface IWarningCount { + /** Properties of a DeleteUserListRequest. */ + interface IDeleteUserListRequest { - /** WarningCount recordCount */ - recordCount?: (number|Long|string|null); + /** DeleteUserListRequest name */ + name?: (string|null); - /** WarningCount reason */ - reason?: (google.ads.datamanager.v1.ProcessingWarningReason|keyof typeof google.ads.datamanager.v1.ProcessingWarningReason|null); + /** DeleteUserListRequest validateOnly */ + validateOnly?: (boolean|null); } - /** Represents a WarningCount. */ - class WarningCount implements IWarningCount { + /** Represents a DeleteUserListRequest. */ + class DeleteUserListRequest implements IDeleteUserListRequest { /** - * Constructs a new WarningCount. + * Constructs a new DeleteUserListRequest. * @param [properties] Properties to set */ - constructor(properties?: google.ads.datamanager.v1.IWarningCount); + constructor(properties?: google.ads.datamanager.v1.IDeleteUserListRequest); - /** WarningCount recordCount. */ - public recordCount: (number|Long|string); + /** DeleteUserListRequest name. */ + public name: string; - /** WarningCount reason. */ - public reason: (google.ads.datamanager.v1.ProcessingWarningReason|keyof typeof google.ads.datamanager.v1.ProcessingWarningReason); + /** DeleteUserListRequest validateOnly. */ + public validateOnly: boolean; /** - * Creates a new WarningCount instance using the specified properties. + * Creates a new DeleteUserListRequest instance using the specified properties. * @param [properties] Properties to set - * @returns WarningCount instance + * @returns DeleteUserListRequest instance */ - public static create(properties?: google.ads.datamanager.v1.IWarningCount): google.ads.datamanager.v1.WarningCount; + public static create(properties?: google.ads.datamanager.v1.IDeleteUserListRequest): google.ads.datamanager.v1.DeleteUserListRequest; /** - * Encodes the specified WarningCount message. Does not implicitly {@link google.ads.datamanager.v1.WarningCount.verify|verify} messages. - * @param message WarningCount message or plain object to encode + * Encodes the specified DeleteUserListRequest message. Does not implicitly {@link google.ads.datamanager.v1.DeleteUserListRequest.verify|verify} messages. + * @param message DeleteUserListRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ - public static encode(message: google.ads.datamanager.v1.IWarningCount, writer?: $protobuf.Writer): $protobuf.Writer; + public static encode(message: google.ads.datamanager.v1.IDeleteUserListRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** - * Encodes the specified WarningCount message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.WarningCount.verify|verify} messages. - * @param message WarningCount message or plain object to encode + * Encodes the specified DeleteUserListRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.DeleteUserListRequest.verify|verify} messages. + * @param message DeleteUserListRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ - public static encodeDelimited(message: google.ads.datamanager.v1.IWarningCount, writer?: $protobuf.Writer): $protobuf.Writer; + public static encodeDelimited(message: google.ads.datamanager.v1.IDeleteUserListRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** - * Decodes a WarningCount message from the specified reader or buffer. + * Decodes a DeleteUserListRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand - * @returns WarningCount + * @returns DeleteUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.WarningCount; + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.DeleteUserListRequest; /** - * Decodes a WarningCount message from the specified reader or buffer, length delimited. + * Decodes a DeleteUserListRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from - * @returns WarningCount + * @returns DeleteUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.WarningCount; + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.DeleteUserListRequest; /** - * Verifies a WarningCount message. + * Verifies a DeleteUserListRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** - * Creates a WarningCount message from a plain object. Also converts values to their respective internal types. + * Creates a DeleteUserListRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns WarningCount + * @returns DeleteUserListRequest */ - public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.WarningCount; + public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.DeleteUserListRequest; /** - * Creates a plain object from a WarningCount message. Also converts values to other types if specified. - * @param message WarningCount + * Creates a plain object from a DeleteUserListRequest message. Also converts values to other types if specified. + * @param message DeleteUserListRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.ads.datamanager.v1.WarningCount, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.ads.datamanager.v1.DeleteUserListRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this WarningCount to JSON. + * Converts this DeleteUserListRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for WarningCount + * Gets the default type url for DeleteUserListRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + } + } + } - /** ProcessingErrorReason enum. */ - enum ProcessingErrorReason { - PROCESSING_ERROR_REASON_UNSPECIFIED = 0, - PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE = 1, - PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED = 2, - PROCESSING_ERROR_REASON_EVENT_TOO_OLD = 3, - PROCESSING_ERROR_REASON_DENIED_CONSENT = 4, - PROCESSING_ERROR_REASON_NO_CONSENT = 5, - PROCESSING_ERROR_REASON_UNKNOWN_CONSENT = 6, - PROCESSING_ERROR_REASON_DUPLICATE_GCLID = 7, - PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID = 8, - PROCESSING_ERROR_REASON_INVALID_GBRAID = 9, - PROCESSING_ERROR_REASON_INVALID_GCLID = 10, - PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID = 11, - PROCESSING_ERROR_REASON_INVALID_WBRAID = 12, - PROCESSING_ERROR_REASON_INTERNAL_ERROR = 13, - PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED = 14, - PROCESSING_ERROR_REASON_INVALID_EVENT = 15, - PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS = 16, - PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS = 17, - PROCESSING_ERROR_REASON_INVALID_FORMAT = 18, - PROCESSING_ERROR_REASON_DECRYPTION_ERROR = 19, - PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR = 20, - PROCESSING_ERROR_REASON_INVALID_WIP = 21, - PROCESSING_ERROR_REASON_INVALID_KEK = 22, - PROCESSING_ERROR_REASON_WIP_AUTH_FAILED = 23, - PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED = 24, - PROCESSING_ERROR_REASON_AWS_AUTH_FAILED = 27, - PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR = 25, - PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER = 26 - } + /** Namespace api. */ + namespace api { - /** ProcessingWarningReason enum. */ - enum ProcessingWarningReason { - PROCESSING_WARNING_REASON_UNSPECIFIED = 0, - PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED = 1, - PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR = 2, - PROCESSING_WARNING_REASON_DECRYPTION_ERROR = 3, - PROCESSING_WARNING_REASON_WIP_AUTH_FAILED = 4, - PROCESSING_WARNING_REASON_INVALID_WIP = 5, - PROCESSING_WARNING_REASON_INVALID_KEK = 6, - PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR = 7, - PROCESSING_WARNING_REASON_INTERNAL_ERROR = 8, - PROCESSING_WARNING_REASON_AWS_AUTH_FAILED = 9 - } + /** FieldBehavior enum. */ + enum FieldBehavior { + FIELD_BEHAVIOR_UNSPECIFIED = 0, + OPTIONAL = 1, + REQUIRED = 2, + OUTPUT_ONLY = 3, + INPUT_ONLY = 4, + IMMUTABLE = 5, + UNORDERED_LIST = 6, + NON_EMPTY_DEFAULT = 7, + IDENTIFIER = 8 + } - /** Properties of a TermsOfService. */ - interface ITermsOfService { + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { - /** TermsOfService customerMatchTermsOfServiceStatus */ - customerMatchTermsOfServiceStatus?: (google.ads.datamanager.v1.TermsOfServiceStatus|keyof typeof google.ads.datamanager.v1.TermsOfServiceStatus|null); - } + /** ResourceDescriptor type */ + type?: (string|null); - /** Represents a TermsOfService. */ - class TermsOfService implements ITermsOfService { + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); - /** - * Constructs a new TermsOfService. - * @param [properties] Properties to set - */ - constructor(properties?: google.ads.datamanager.v1.ITermsOfService); + /** ResourceDescriptor nameField */ + nameField?: (string|null); - /** TermsOfService customerMatchTermsOfServiceStatus. */ - public customerMatchTermsOfServiceStatus: (google.ads.datamanager.v1.TermsOfServiceStatus|keyof typeof google.ads.datamanager.v1.TermsOfServiceStatus); + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|keyof typeof google.api.ResourceDescriptor.History|null); - /** - * Creates a new TermsOfService instance using the specified properties. - * @param [properties] Properties to set - * @returns TermsOfService instance - */ - public static create(properties?: google.ads.datamanager.v1.ITermsOfService): google.ads.datamanager.v1.TermsOfService; + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); + + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } + + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: (google.api.ResourceDescriptor.History|keyof typeof google.api.ResourceDescriptor.History); + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a new ResourceDescriptor instance using the specified properties. + * @param [properties] Properties to set + * @returns ResourceDescriptor instance + */ + public static create(properties?: google.api.IResourceDescriptor): google.api.ResourceDescriptor; + + /** + * Encodes the specified ResourceDescriptor message. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @param message ResourceDescriptor message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ResourceDescriptor message, length delimited. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @param message ResourceDescriptor message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResourceDescriptor + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceDescriptor; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResourceDescriptor + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceDescriptor; + + /** + * Verifies a ResourceDescriptor message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + enum History { + HISTORY_UNSPECIFIED = 0, + ORIGINALLY_SINGLE_PATTERN = 1, + FUTURE_MULTI_PATTERN = 2 + } + + /** Style enum. */ + enum Style { + STYLE_UNSPECIFIED = 0, + DECLARATIVE_FRIENDLY = 1 + } + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); - /** - * Encodes the specified TermsOfService message. Does not implicitly {@link google.ads.datamanager.v1.TermsOfService.verify|verify} messages. - * @param message TermsOfService message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encode(message: google.ads.datamanager.v1.ITermsOfService, writer?: $protobuf.Writer): $protobuf.Writer; + /** ResourceReference type. */ + public type: string; - /** - * Encodes the specified TermsOfService message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.TermsOfService.verify|verify} messages. - * @param message TermsOfService message or plain object to encode - * @param [writer] Writer to encode to - * @returns Writer - */ - public static encodeDelimited(message: google.ads.datamanager.v1.ITermsOfService, writer?: $protobuf.Writer): $protobuf.Writer; + /** ResourceReference childType. */ + public childType: string; - /** - * Decodes a TermsOfService message from the specified reader or buffer. - * @param reader Reader or buffer to decode from - * @param [length] Message length if known beforehand - * @returns TermsOfService - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.ads.datamanager.v1.TermsOfService; + /** + * Creates a new ResourceReference instance using the specified properties. + * @param [properties] Properties to set + * @returns ResourceReference instance + */ + public static create(properties?: google.api.IResourceReference): google.api.ResourceReference; - /** - * Decodes a TermsOfService message from the specified reader or buffer, length delimited. - * @param reader Reader or buffer to decode from - * @returns TermsOfService - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.ads.datamanager.v1.TermsOfService; + /** + * Encodes the specified ResourceReference message. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @param message ResourceReference message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer; - /** - * Verifies a TermsOfService message. - * @param message Plain object to verify - * @returns `null` if valid, otherwise the reason why it is not - */ - public static verify(message: { [k: string]: any }): (string|null); + /** + * Encodes the specified ResourceReference message, length delimited. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @param message ResourceReference message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer; - /** - * Creates a TermsOfService message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns TermsOfService - */ - public static fromObject(object: { [k: string]: any }): google.ads.datamanager.v1.TermsOfService; + /** + * Decodes a ResourceReference message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ResourceReference + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceReference; - /** - * Creates a plain object from a TermsOfService message. Also converts values to other types if specified. - * @param message TermsOfService - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.ads.datamanager.v1.TermsOfService, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Decodes a ResourceReference message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ResourceReference + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceReference; - /** - * Converts this TermsOfService to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Verifies a ResourceReference message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); - /** - * Gets the default type url for TermsOfService - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; - /** TermsOfServiceStatus enum. */ - enum TermsOfServiceStatus { - TERMS_OF_SERVICE_STATUS_UNSPECIFIED = 0, - ACCEPTED = 1, - REJECTED = 2 - } - } - } - } + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Namespace api. */ - namespace api { + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldBehavior enum. */ - enum FieldBehavior { - FIELD_BEHAVIOR_UNSPECIFIED = 0, - OPTIONAL = 1, - REQUIRED = 2, - OUTPUT_ONLY = 3, - INPUT_ONLY = 4, - IMMUTABLE = 5, - UNORDERED_LIST = 6, - NON_EMPTY_DEFAULT = 7, - IDENTIFIER = 8 + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Http. */ @@ -9103,6 +15634,9 @@ export namespace google { /** FileOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); } /** Represents a FileOptions. */ @@ -9288,6 +15822,9 @@ export namespace google { /** MessageOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); } /** Represents a MessageOptions. */ @@ -9442,6 +15979,9 @@ export namespace google { /** FieldOptions .google.api.fieldBehavior */ ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); } /** Represents a FieldOptions. */ @@ -11583,5 +18123,193 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates a new Empty instance using the specified properties. + * @param [properties] Properties to set + * @returns Empty instance + */ + public static create(properties?: google.protobuf.IEmpty): google.protobuf.Empty; + + /** + * Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @param message Empty message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @param message Empty message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an Empty message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Empty + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Empty; + + /** + * Decodes an Empty message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Empty + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Empty; + + /** + * Verifies an Empty message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FieldMask. */ + interface IFieldMask { + + /** FieldMask paths */ + paths?: (string[]|null); + } + + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { + + /** + * Constructs a new FieldMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldMask); + + /** FieldMask paths. */ + public paths: string[]; + + /** + * Creates a new FieldMask instance using the specified properties. + * @param [properties] Properties to set + * @returns FieldMask instance + */ + public static create(properties?: google.protobuf.IFieldMask): google.protobuf.FieldMask; + + /** + * Encodes the specified FieldMask message. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. + * @param message FieldMask message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FieldMask message, length delimited. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. + * @param message FieldMask message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FieldMask message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FieldMask + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldMask; + + /** + * Decodes a FieldMask message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FieldMask + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldMask; + + /** + * Verifies a FieldMask message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldMask + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } } diff --git a/packages/google-ads-datamanager/protos/protos.js b/packages/google-ads-datamanager/protos/protos.js index e5e9838bf9c..0dfae3dfbd5 100644 --- a/packages/google-ads-datamanager/protos/protos.js +++ b/packages/google-ads-datamanager/protos/protos.js @@ -66,6 +66,32 @@ */ var v1 = {}; + /** + * AgeRange enum. + * @name google.ads.datamanager.v1.AgeRange + * @enum {number} + * @property {number} AGE_RANGE_UNSPECIFIED=0 AGE_RANGE_UNSPECIFIED value + * @property {number} AGE_RANGE_UNKNOWN=1 AGE_RANGE_UNKNOWN value + * @property {number} AGE_RANGE_18_24=2 AGE_RANGE_18_24 value + * @property {number} AGE_RANGE_25_34=3 AGE_RANGE_25_34 value + * @property {number} AGE_RANGE_35_44=4 AGE_RANGE_35_44 value + * @property {number} AGE_RANGE_45_54=5 AGE_RANGE_45_54 value + * @property {number} AGE_RANGE_55_64=6 AGE_RANGE_55_64 value + * @property {number} AGE_RANGE_65_UP=7 AGE_RANGE_65_UP value + */ + v1.AgeRange = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "AGE_RANGE_UNSPECIFIED"] = 0; + values[valuesById[1] = "AGE_RANGE_UNKNOWN"] = 1; + values[valuesById[2] = "AGE_RANGE_18_24"] = 2; + values[valuesById[3] = "AGE_RANGE_25_34"] = 3; + values[valuesById[4] = "AGE_RANGE_35_44"] = 4; + values[valuesById[5] = "AGE_RANGE_45_54"] = 5; + values[valuesById[6] = "AGE_RANGE_55_64"] = 6; + values[valuesById[7] = "AGE_RANGE_65_UP"] = 7; + return values; + })(); + v1.AudienceMember = (function() { /** @@ -76,6 +102,8 @@ * @property {google.ads.datamanager.v1.IUserData|null} [userData] AudienceMember userData * @property {google.ads.datamanager.v1.IPairData|null} [pairData] AudienceMember pairData * @property {google.ads.datamanager.v1.IMobileData|null} [mobileData] AudienceMember mobileData + * @property {google.ads.datamanager.v1.IUserIdData|null} [userIdData] AudienceMember userIdData + * @property {google.ads.datamanager.v1.IPpidData|null} [ppidData] AudienceMember ppidData * @property {google.ads.datamanager.v1.IConsent|null} [consent] AudienceMember consent */ @@ -127,6 +155,22 @@ */ AudienceMember.prototype.mobileData = null; + /** + * AudienceMember userIdData. + * @member {google.ads.datamanager.v1.IUserIdData|null|undefined} userIdData + * @memberof google.ads.datamanager.v1.AudienceMember + * @instance + */ + AudienceMember.prototype.userIdData = null; + + /** + * AudienceMember ppidData. + * @member {google.ads.datamanager.v1.IPpidData|null|undefined} ppidData + * @memberof google.ads.datamanager.v1.AudienceMember + * @instance + */ + AudienceMember.prototype.ppidData = null; + /** * AudienceMember consent. * @member {google.ads.datamanager.v1.IConsent|null|undefined} consent @@ -140,12 +184,12 @@ /** * AudienceMember data. - * @member {"userData"|"pairData"|"mobileData"|undefined} data + * @member {"userData"|"pairData"|"mobileData"|"userIdData"|"ppidData"|undefined} data * @memberof google.ads.datamanager.v1.AudienceMember * @instance */ Object.defineProperty(AudienceMember.prototype, "data", { - get: $util.oneOfGetter($oneOfFields = ["userData", "pairData", "mobileData"]), + get: $util.oneOfGetter($oneOfFields = ["userData", "pairData", "mobileData", "userIdData", "ppidData"]), set: $util.oneOfSetter($oneOfFields) }); @@ -184,6 +228,10 @@ $root.google.ads.datamanager.v1.PairData.encode(message.pairData, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); if (message.mobileData != null && Object.hasOwnProperty.call(message, "mobileData")) $root.google.ads.datamanager.v1.MobileData.encode(message.mobileData, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.userIdData != null && Object.hasOwnProperty.call(message, "userIdData")) + $root.google.ads.datamanager.v1.UserIdData.encode(message.userIdData, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.ppidData != null && Object.hasOwnProperty.call(message, "ppidData")) + $root.google.ads.datamanager.v1.PpidData.encode(message.ppidData, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); return writer; }; @@ -238,6 +286,14 @@ message.mobileData = $root.google.ads.datamanager.v1.MobileData.decode(reader, reader.uint32()); break; } + case 6: { + message.userIdData = $root.google.ads.datamanager.v1.UserIdData.decode(reader, reader.uint32()); + break; + } + case 7: { + message.ppidData = $root.google.ads.datamanager.v1.PpidData.decode(reader, reader.uint32()); + break; + } case 3: { message.consent = $root.google.ads.datamanager.v1.Consent.decode(reader, reader.uint32()); break; @@ -313,6 +369,26 @@ return "mobileData." + error; } } + if (message.userIdData != null && message.hasOwnProperty("userIdData")) { + if (properties.data === 1) + return "data: multiple values"; + properties.data = 1; + { + var error = $root.google.ads.datamanager.v1.UserIdData.verify(message.userIdData); + if (error) + return "userIdData." + error; + } + } + if (message.ppidData != null && message.hasOwnProperty("ppidData")) { + if (properties.data === 1) + return "data: multiple values"; + properties.data = 1; + { + var error = $root.google.ads.datamanager.v1.PpidData.verify(message.ppidData); + if (error) + return "ppidData." + error; + } + } if (message.consent != null && message.hasOwnProperty("consent")) { var error = $root.google.ads.datamanager.v1.Consent.verify(message.consent); if (error) @@ -355,6 +431,16 @@ throw TypeError(".google.ads.datamanager.v1.AudienceMember.mobileData: object expected"); message.mobileData = $root.google.ads.datamanager.v1.MobileData.fromObject(object.mobileData); } + if (object.userIdData != null) { + if (typeof object.userIdData !== "object") + throw TypeError(".google.ads.datamanager.v1.AudienceMember.userIdData: object expected"); + message.userIdData = $root.google.ads.datamanager.v1.UserIdData.fromObject(object.userIdData); + } + if (object.ppidData != null) { + if (typeof object.ppidData !== "object") + throw TypeError(".google.ads.datamanager.v1.AudienceMember.ppidData: object expected"); + message.ppidData = $root.google.ads.datamanager.v1.PpidData.fromObject(object.ppidData); + } if (object.consent != null) { if (typeof object.consent !== "object") throw TypeError(".google.ads.datamanager.v1.AudienceMember.consent: object expected"); @@ -402,6 +488,16 @@ if (options.oneofs) object.data = "mobileData"; } + if (message.userIdData != null && message.hasOwnProperty("userIdData")) { + object.userIdData = $root.google.ads.datamanager.v1.UserIdData.toObject(message.userIdData, options); + if (options.oneofs) + object.data = "userIdData"; + } + if (message.ppidData != null && message.hasOwnProperty("ppidData")) { + object.ppidData = $root.google.ads.datamanager.v1.PpidData.toObject(message.ppidData, options); + if (options.oneofs) + object.data = "ppidData"; + } return object; }; @@ -876,6 +972,432 @@ return MobileData; })(); + v1.UserIdData = (function() { + + /** + * Properties of a UserIdData. + * @memberof google.ads.datamanager.v1 + * @interface IUserIdData + * @property {string|null} [userId] UserIdData userId + */ + + /** + * Constructs a new UserIdData. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserIdData. + * @implements IUserIdData + * @constructor + * @param {google.ads.datamanager.v1.IUserIdData=} [properties] Properties to set + */ + function UserIdData(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserIdData userId. + * @member {string} userId + * @memberof google.ads.datamanager.v1.UserIdData + * @instance + */ + UserIdData.prototype.userId = ""; + + /** + * Creates a new UserIdData instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {google.ads.datamanager.v1.IUserIdData=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UserIdData} UserIdData instance + */ + UserIdData.create = function create(properties) { + return new UserIdData(properties); + }; + + /** + * Encodes the specified UserIdData message. Does not implicitly {@link google.ads.datamanager.v1.UserIdData.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {google.ads.datamanager.v1.IUserIdData} message UserIdData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserIdData.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userId != null && Object.hasOwnProperty.call(message, "userId")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.userId); + return writer; + }; + + /** + * Encodes the specified UserIdData message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserIdData.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {google.ads.datamanager.v1.IUserIdData} message UserIdData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserIdData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a UserIdData message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UserIdData} UserIdData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserIdData.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.ads.datamanager.v1.UserIdData(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.userId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a UserIdData message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UserIdData} UserIdData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserIdData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a UserIdData message. + * @function verify + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UserIdData.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userId != null && message.hasOwnProperty("userId")) + if (!$util.isString(message.userId)) + return "userId: string expected"; + return null; + }; + + /** + * Creates a UserIdData message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UserIdData} UserIdData + */ + UserIdData.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UserIdData) + return object; + var message = new $root.google.ads.datamanager.v1.UserIdData(); + if (object.userId != null) + message.userId = String(object.userId); + return message; + }; + + /** + * Creates a plain object from a UserIdData message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {google.ads.datamanager.v1.UserIdData} message UserIdData + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserIdData.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.userId = ""; + if (message.userId != null && message.hasOwnProperty("userId")) + object.userId = message.userId; + return object; + }; + + /** + * Converts this UserIdData to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UserIdData + * @instance + * @returns {Object.} JSON object + */ + UserIdData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserIdData + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UserIdData + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserIdData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UserIdData"; + }; + + return UserIdData; + })(); + + v1.PpidData = (function() { + + /** + * Properties of a PpidData. + * @memberof google.ads.datamanager.v1 + * @interface IPpidData + * @property {Array.|null} [ppids] PpidData ppids + */ + + /** + * Constructs a new PpidData. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a PpidData. + * @implements IPpidData + * @constructor + * @param {google.ads.datamanager.v1.IPpidData=} [properties] Properties to set + */ + function PpidData(properties) { + this.ppids = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PpidData ppids. + * @member {Array.} ppids + * @memberof google.ads.datamanager.v1.PpidData + * @instance + */ + PpidData.prototype.ppids = $util.emptyArray; + + /** + * Creates a new PpidData instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {google.ads.datamanager.v1.IPpidData=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.PpidData} PpidData instance + */ + PpidData.create = function create(properties) { + return new PpidData(properties); + }; + + /** + * Encodes the specified PpidData message. Does not implicitly {@link google.ads.datamanager.v1.PpidData.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {google.ads.datamanager.v1.IPpidData} message PpidData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PpidData.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.ppids != null && message.ppids.length) + for (var i = 0; i < message.ppids.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.ppids[i]); + return writer; + }; + + /** + * Encodes the specified PpidData message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PpidData.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {google.ads.datamanager.v1.IPpidData} message PpidData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PpidData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PpidData message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.PpidData} PpidData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PpidData.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.ads.datamanager.v1.PpidData(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.ppids && message.ppids.length)) + message.ppids = []; + message.ppids.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PpidData message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.PpidData} PpidData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PpidData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PpidData message. + * @function verify + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PpidData.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.ppids != null && message.hasOwnProperty("ppids")) { + if (!Array.isArray(message.ppids)) + return "ppids: array expected"; + for (var i = 0; i < message.ppids.length; ++i) + if (!$util.isString(message.ppids[i])) + return "ppids: string[] expected"; + } + return null; + }; + + /** + * Creates a PpidData message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.PpidData} PpidData + */ + PpidData.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.PpidData) + return object; + var message = new $root.google.ads.datamanager.v1.PpidData(); + if (object.ppids) { + if (!Array.isArray(object.ppids)) + throw TypeError(".google.ads.datamanager.v1.PpidData.ppids: array expected"); + message.ppids = []; + for (var i = 0; i < object.ppids.length; ++i) + message.ppids[i] = String(object.ppids[i]); + } + return message; + }; + + /** + * Creates a plain object from a PpidData message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {google.ads.datamanager.v1.PpidData} message PpidData + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PpidData.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.ppids = []; + if (message.ppids && message.ppids.length) { + object.ppids = []; + for (var j = 0; j < message.ppids.length; ++j) + object.ppids[j] = message.ppids[j]; + } + return object; + }; + + /** + * Converts this PpidData to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.PpidData + * @instance + * @returns {Object.} JSON object + */ + PpidData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PpidData + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.PpidData + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PpidData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.PpidData"; + }; + + return PpidData; + })(); + v1.Consent = (function() { /** @@ -3340,6 +3862,7 @@ case 3: case 4: case 5: + case 6: break; } return null; @@ -3418,6 +3941,10 @@ case 5: message.accountType = 5; break; + case "GOOGLE_AD_MANAGER_AUDIENCE_LINK": + case 6: + message.accountType = 6; + break; } return message; }; @@ -3485,6 +4012,7 @@ * @property {number} DISPLAY_VIDEO_ADVERTISER=3 DISPLAY_VIDEO_ADVERTISER value * @property {number} DATA_PARTNER=4 DATA_PARTNER value * @property {number} GOOGLE_ANALYTICS_PROPERTY=5 GOOGLE_ANALYTICS_PROPERTY value + * @property {number} GOOGLE_AD_MANAGER_AUDIENCE_LINK=6 GOOGLE_AD_MANAGER_AUDIENCE_LINK value */ ProductAccount.AccountType = (function() { var valuesById = {}, values = Object.create(valuesById); @@ -3494,6 +4022,7 @@ values[valuesById[3] = "DISPLAY_VIDEO_ADVERTISER"] = 3; values[valuesById[4] = "DATA_PARTNER"] = 4; values[valuesById[5] = "GOOGLE_ANALYTICS_PROPERTY"] = 5; + values[valuesById[6] = "GOOGLE_AD_MANAGER_AUDIENCE_LINK"] = 6; return values; })(); @@ -4685,6 +5214,53 @@ * @property {number} MULTIPLE_DESTINATIONS_FOR_GOOGLE_ANALYTICS_EVENT=49 MULTIPLE_DESTINATIONS_FOR_GOOGLE_ANALYTICS_EVENT value * @property {number} FIELD_VALUE_TOO_LONG=50 FIELD_VALUE_TOO_LONG value * @property {number} TOO_MANY_ELEMENTS=51 TOO_MANY_ELEMENTS value + * @property {number} ALREADY_EXISTS=52 ALREADY_EXISTS value + * @property {number} IMMUTABLE_FIELD_FOR_UPDATE=53 IMMUTABLE_FIELD_FOR_UPDATE value + * @property {number} INVALID_RESOURCE_NAME=54 INVALID_RESOURCE_NAME value + * @property {number} INVALID_FILTER=55 INVALID_FILTER value + * @property {number} INVALID_UPDATE_MASK=56 INVALID_UPDATE_MASK value + * @property {number} INVALID_PAGE_TOKEN=57 INVALID_PAGE_TOKEN value + * @property {number} CANNOT_UPDATE_DISABLED_LICENSE=58 CANNOT_UPDATE_DISABLED_LICENSE value + * @property {number} CANNOT_CREATE_LICENSE_FOR_SENSITIVE_USERLIST=59 CANNOT_CREATE_LICENSE_FOR_SENSITIVE_USERLIST value + * @property {number} INSUFFICIENT_COST=60 INSUFFICIENT_COST value + * @property {number} CANNOT_DISABLE_LICENSE=61 CANNOT_DISABLE_LICENSE value + * @property {number} INVALID_CLIENT_ACCOUNT_ID=62 INVALID_CLIENT_ACCOUNT_ID value + * @property {number} PRICING_ONLY_ZERO_COST_ALLOWED=63 PRICING_ONLY_ZERO_COST_ALLOWED value + * @property {number} PRICE_TOO_HIGH=64 PRICE_TOO_HIGH value + * @property {number} CUSTOMER_NOT_ALLOWED_TO_CREATE_LICENSE=65 CUSTOMER_NOT_ALLOWED_TO_CREATE_LICENSE value + * @property {number} INVALID_PRICING_END_DATE=66 INVALID_PRICING_END_DATE value + * @property {number} CANNOT_LICENSE_LOGICAL_LIST_WITH_LICENSED_OR_SHARED_SEGMENT=67 CANNOT_LICENSE_LOGICAL_LIST_WITH_LICENSED_OR_SHARED_SEGMENT value + * @property {number} MISMATCHED_ACCOUNT_TYPE=68 MISMATCHED_ACCOUNT_TYPE value + * @property {number} MEDIA_SHARE_COST_NOT_ALLOWED_FOR_LICENSE_TYPE=69 MEDIA_SHARE_COST_NOT_ALLOWED_FOR_LICENSE_TYPE value + * @property {number} MEDIA_SHARE_COST_NOT_ALLOWED_FOR_CLIENT_CUSTOMER=70 MEDIA_SHARE_COST_NOT_ALLOWED_FOR_CLIENT_CUSTOMER value + * @property {number} INVALID_MEDIA_SHARE_COST=71 INVALID_MEDIA_SHARE_COST value + * @property {number} INVALID_COST_TYPE=72 INVALID_COST_TYPE value + * @property {number} MEDIA_SHARE_COST_NOT_ALLOWED_FOR_NON_COMMERCE_USER_LIST=73 MEDIA_SHARE_COST_NOT_ALLOWED_FOR_NON_COMMERCE_USER_LIST value + * @property {number} MAX_COST_NOT_ALLOWED=74 MAX_COST_NOT_ALLOWED value + * @property {number} COMMERCE_AUDIENCE_CAN_ONLY_BE_DIRECTLY_LICENSED=75 COMMERCE_AUDIENCE_CAN_ONLY_BE_DIRECTLY_LICENSED value + * @property {number} INVALID_DESCRIPTION=76 INVALID_DESCRIPTION value + * @property {number} INVALID_DISPLAY_NAME=77 INVALID_DISPLAY_NAME value + * @property {number} DISPLAY_NAME_ALREADY_USED=78 DISPLAY_NAME_ALREADY_USED value + * @property {number} OWNERSHIP_REQUIRED_FOR_UPDATE=79 OWNERSHIP_REQUIRED_FOR_UPDATE value + * @property {number} USER_LIST_MUTATION_NOT_SUPPORTED=80 USER_LIST_MUTATION_NOT_SUPPORTED value + * @property {number} SENSITIVE_USER_LIST_IMMUTABLE=81 SENSITIVE_USER_LIST_IMMUTABLE value + * @property {number} BILLABLE_RECORD_COUNT_IMMUTABLE=82 BILLABLE_RECORD_COUNT_IMMUTABLE value + * @property {number} USER_LIST_NAME_RESERVED=83 USER_LIST_NAME_RESERVED value + * @property {number} ADVERTISER_NOT_ALLOWLISTED_FOR_UPLOADED_DATA=84 ADVERTISER_NOT_ALLOWLISTED_FOR_UPLOADED_DATA value + * @property {number} UNSUPPORTED_PARTNER_AUDIENCE_SOURCE=85 UNSUPPORTED_PARTNER_AUDIENCE_SOURCE value + * @property {number} COMMERCE_PARTNER_NOT_ALLOWED=86 COMMERCE_PARTNER_NOT_ALLOWED value + * @property {number} UNSUPPORTED_PARTNER_AUDIENCE_INFO=87 UNSUPPORTED_PARTNER_AUDIENCE_INFO value + * @property {number} PARTNER_MATCH_FOR_MANAGER_ACCOUNT_DISALLOWED=88 PARTNER_MATCH_FOR_MANAGER_ACCOUNT_DISALLOWED value + * @property {number} DATA_PARTNER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA=89 DATA_PARTNER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA value + * @property {number} ADVERTISER_TOS_NOT_ACCEPTED=90 ADVERTISER_TOS_NOT_ACCEPTED value + * @property {number} ADVERTISER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA=91 ADVERTISER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA value + * @property {number} USER_LIST_TYPE_NOT_SUPPORTED_FOR_ACCOUNT=92 USER_LIST_TYPE_NOT_SUPPORTED_FOR_ACCOUNT value + * @property {number} INVALID_COMMERCE_PARTNER=93 INVALID_COMMERCE_PARTNER value + * @property {number} CUSTOMER_NOT_ALLOWLISTED_FOR_COMMERCE_AUDIENCE=94 CUSTOMER_NOT_ALLOWLISTED_FOR_COMMERCE_AUDIENCE value + * @property {number} UNSUPPORTED_USER_LIST_UPLOAD_KEY_TYPES=95 UNSUPPORTED_USER_LIST_UPLOAD_KEY_TYPES value + * @property {number} UNSUPPORTED_INGESTED_USER_LIST_INFO_CONFIG=96 UNSUPPORTED_INGESTED_USER_LIST_INFO_CONFIG value + * @property {number} UNSUPPORTED_ACCOUNT_TYPES_FOR_USER_LIST_TYPE=97 UNSUPPORTED_ACCOUNT_TYPES_FOR_USER_LIST_TYPE value + * @property {number} UNSUPPORTED_ACCOUNT_TYPE_FOR_PARTNER_LINK=98 UNSUPPORTED_ACCOUNT_TYPE_FOR_PARTNER_LINK value */ v1.ErrorReason = (function() { var valuesById = {}, values = Object.create(valuesById); @@ -4740,6 +5316,53 @@ values[valuesById[49] = "MULTIPLE_DESTINATIONS_FOR_GOOGLE_ANALYTICS_EVENT"] = 49; values[valuesById[50] = "FIELD_VALUE_TOO_LONG"] = 50; values[valuesById[51] = "TOO_MANY_ELEMENTS"] = 51; + values[valuesById[52] = "ALREADY_EXISTS"] = 52; + values[valuesById[53] = "IMMUTABLE_FIELD_FOR_UPDATE"] = 53; + values[valuesById[54] = "INVALID_RESOURCE_NAME"] = 54; + values[valuesById[55] = "INVALID_FILTER"] = 55; + values[valuesById[56] = "INVALID_UPDATE_MASK"] = 56; + values[valuesById[57] = "INVALID_PAGE_TOKEN"] = 57; + values[valuesById[58] = "CANNOT_UPDATE_DISABLED_LICENSE"] = 58; + values[valuesById[59] = "CANNOT_CREATE_LICENSE_FOR_SENSITIVE_USERLIST"] = 59; + values[valuesById[60] = "INSUFFICIENT_COST"] = 60; + values[valuesById[61] = "CANNOT_DISABLE_LICENSE"] = 61; + values[valuesById[62] = "INVALID_CLIENT_ACCOUNT_ID"] = 62; + values[valuesById[63] = "PRICING_ONLY_ZERO_COST_ALLOWED"] = 63; + values[valuesById[64] = "PRICE_TOO_HIGH"] = 64; + values[valuesById[65] = "CUSTOMER_NOT_ALLOWED_TO_CREATE_LICENSE"] = 65; + values[valuesById[66] = "INVALID_PRICING_END_DATE"] = 66; + values[valuesById[67] = "CANNOT_LICENSE_LOGICAL_LIST_WITH_LICENSED_OR_SHARED_SEGMENT"] = 67; + values[valuesById[68] = "MISMATCHED_ACCOUNT_TYPE"] = 68; + values[valuesById[69] = "MEDIA_SHARE_COST_NOT_ALLOWED_FOR_LICENSE_TYPE"] = 69; + values[valuesById[70] = "MEDIA_SHARE_COST_NOT_ALLOWED_FOR_CLIENT_CUSTOMER"] = 70; + values[valuesById[71] = "INVALID_MEDIA_SHARE_COST"] = 71; + values[valuesById[72] = "INVALID_COST_TYPE"] = 72; + values[valuesById[73] = "MEDIA_SHARE_COST_NOT_ALLOWED_FOR_NON_COMMERCE_USER_LIST"] = 73; + values[valuesById[74] = "MAX_COST_NOT_ALLOWED"] = 74; + values[valuesById[75] = "COMMERCE_AUDIENCE_CAN_ONLY_BE_DIRECTLY_LICENSED"] = 75; + values[valuesById[76] = "INVALID_DESCRIPTION"] = 76; + values[valuesById[77] = "INVALID_DISPLAY_NAME"] = 77; + values[valuesById[78] = "DISPLAY_NAME_ALREADY_USED"] = 78; + values[valuesById[79] = "OWNERSHIP_REQUIRED_FOR_UPDATE"] = 79; + values[valuesById[80] = "USER_LIST_MUTATION_NOT_SUPPORTED"] = 80; + values[valuesById[81] = "SENSITIVE_USER_LIST_IMMUTABLE"] = 81; + values[valuesById[82] = "BILLABLE_RECORD_COUNT_IMMUTABLE"] = 82; + values[valuesById[83] = "USER_LIST_NAME_RESERVED"] = 83; + values[valuesById[84] = "ADVERTISER_NOT_ALLOWLISTED_FOR_UPLOADED_DATA"] = 84; + values[valuesById[85] = "UNSUPPORTED_PARTNER_AUDIENCE_SOURCE"] = 85; + values[valuesById[86] = "COMMERCE_PARTNER_NOT_ALLOWED"] = 86; + values[valuesById[87] = "UNSUPPORTED_PARTNER_AUDIENCE_INFO"] = 87; + values[valuesById[88] = "PARTNER_MATCH_FOR_MANAGER_ACCOUNT_DISALLOWED"] = 88; + values[valuesById[89] = "DATA_PARTNER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA"] = 89; + values[valuesById[90] = "ADVERTISER_TOS_NOT_ACCEPTED"] = 90; + values[valuesById[91] = "ADVERTISER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA"] = 91; + values[valuesById[92] = "USER_LIST_TYPE_NOT_SUPPORTED_FOR_ACCOUNT"] = 92; + values[valuesById[93] = "INVALID_COMMERCE_PARTNER"] = 93; + values[valuesById[94] = "CUSTOMER_NOT_ALLOWLISTED_FOR_COMMERCE_AUDIENCE"] = 94; + values[valuesById[95] = "UNSUPPORTED_USER_LIST_UPLOAD_KEY_TYPES"] = 95; + values[valuesById[96] = "UNSUPPORTED_INGESTED_USER_LIST_INFO_CONFIG"] = 96; + values[valuesById[97] = "UNSUPPORTED_ACCOUNT_TYPES_FOR_USER_LIST_TYPE"] = 97; + values[valuesById[98] = "UNSUPPORTED_ACCOUNT_TYPE_FOR_PARTNER_LINK"] = 98; return values; })(); @@ -4855,11 +5478,11 @@ /** * Event conversionValue. - * @member {number} conversionValue + * @member {number|null|undefined} conversionValue * @memberof google.ads.datamanager.v1.Event * @instance */ - Event.prototype.conversionValue = 0; + Event.prototype.conversionValue = null; /** * Event eventSource. @@ -4941,6 +5564,15 @@ */ Event.prototype.additionalEventParameters = $util.emptyArray; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(Event.prototype, "_conversionValue", { + get: $util.oneOfGetter($oneOfFields = ["conversionValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** * Creates a new Event instance using the specified properties. * @function create @@ -5162,6 +5794,7 @@ Event.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; + var properties = {}; if (message.destinationReferences != null && message.hasOwnProperty("destinationReferences")) { if (!Array.isArray(message.destinationReferences)) return "destinationReferences: array expected"; @@ -5200,9 +5833,11 @@ if (message.currency != null && message.hasOwnProperty("currency")) if (!$util.isString(message.currency)) return "currency: string expected"; - if (message.conversionValue != null && message.hasOwnProperty("conversionValue")) + if (message.conversionValue != null && message.hasOwnProperty("conversionValue")) { + properties._conversionValue = 1; if (typeof message.conversionValue !== "number") return "conversionValue: number expected"; + } if (message.eventSource != null && message.hasOwnProperty("eventSource")) switch (message.eventSource) { default: @@ -5432,7 +6067,6 @@ object.consent = null; object.adIdentifiers = null; object.currency = ""; - object.conversionValue = 0; object.eventSource = options.enums === String ? "EVENT_SOURCE_UNSPECIFIED" : 0; object.eventDeviceInfo = null; object.cartData = null; @@ -5460,8 +6094,11 @@ object.adIdentifiers = $root.google.ads.datamanager.v1.AdIdentifiers.toObject(message.adIdentifiers, options); if (message.currency != null && message.hasOwnProperty("currency")) object.currency = message.currency; - if (message.conversionValue != null && message.hasOwnProperty("conversionValue")) + if (message.conversionValue != null && message.hasOwnProperty("conversionValue")) { object.conversionValue = options.json && !isFinite(message.conversionValue) ? String(message.conversionValue) : message.conversionValue; + if (options.oneofs) + object._conversionValue = "conversionValue"; + } if (message.eventSource != null && message.hasOwnProperty("eventSource")) object.eventSource = options.enums === String ? $root.google.ads.datamanager.v1.EventSource[message.eventSource] === undefined ? message.eventSource : $root.google.ads.datamanager.v1.EventSource[message.eventSource] : message.eventSource; if (message.eventDeviceInfo != null && message.hasOwnProperty("eventDeviceInfo")) @@ -7172,6 +7809,24 @@ return values; })(); + /** + * Gender enum. + * @name google.ads.datamanager.v1.Gender + * @enum {number} + * @property {number} GENDER_UNSPECIFIED=0 GENDER_UNSPECIFIED value + * @property {number} GENDER_UNKNOWN=1 GENDER_UNKNOWN value + * @property {number} GENDER_MALE=2 GENDER_MALE value + * @property {number} GENDER_FEMALE=3 GENDER_FEMALE value + */ + v1.Gender = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "GENDER_UNSPECIFIED"] = 0; + values[valuesById[1] = "GENDER_UNKNOWN"] = 1; + values[valuesById[2] = "GENDER_MALE"] = 2; + values[valuesById[3] = "GENDER_FEMALE"] = 3; + return values; + })(); + v1.IngestionService = (function() { /** @@ -10066,6 +10721,8 @@ * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserDataStatus|null} [userDataIngestionStatus] IngestAudienceMembersStatus userDataIngestionStatus * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestMobileDataStatus|null} [mobileDataIngestionStatus] IngestAudienceMembersStatus mobileDataIngestionStatus * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPairDataStatus|null} [pairDataIngestionStatus] IngestAudienceMembersStatus pairDataIngestionStatus + * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus|null} [userIdDataIngestionStatus] IngestAudienceMembersStatus userIdDataIngestionStatus + * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus|null} [ppidDataIngestionStatus] IngestAudienceMembersStatus ppidDataIngestionStatus */ /** @@ -10107,17 +10764,33 @@ */ IngestAudienceMembersStatus.prototype.pairDataIngestionStatus = null; + /** + * IngestAudienceMembersStatus userIdDataIngestionStatus. + * @member {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus|null|undefined} userIdDataIngestionStatus + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestAudienceMembersStatus + * @instance + */ + IngestAudienceMembersStatus.prototype.userIdDataIngestionStatus = null; + + /** + * IngestAudienceMembersStatus ppidDataIngestionStatus. + * @member {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus|null|undefined} ppidDataIngestionStatus + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestAudienceMembersStatus + * @instance + */ + IngestAudienceMembersStatus.prototype.ppidDataIngestionStatus = null; + // OneOf field names bound to virtual getters and setters var $oneOfFields; /** * IngestAudienceMembersStatus status. - * @member {"userDataIngestionStatus"|"mobileDataIngestionStatus"|"pairDataIngestionStatus"|undefined} status + * @member {"userDataIngestionStatus"|"mobileDataIngestionStatus"|"pairDataIngestionStatus"|"userIdDataIngestionStatus"|"ppidDataIngestionStatus"|undefined} status * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestAudienceMembersStatus * @instance */ Object.defineProperty(IngestAudienceMembersStatus.prototype, "status", { - get: $util.oneOfGetter($oneOfFields = ["userDataIngestionStatus", "mobileDataIngestionStatus", "pairDataIngestionStatus"]), + get: $util.oneOfGetter($oneOfFields = ["userDataIngestionStatus", "mobileDataIngestionStatus", "pairDataIngestionStatus", "userIdDataIngestionStatus", "ppidDataIngestionStatus"]), set: $util.oneOfSetter($oneOfFields) }); @@ -10151,6 +10824,10 @@ $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestMobileDataStatus.encode(message.mobileDataIngestionStatus, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.pairDataIngestionStatus != null && Object.hasOwnProperty.call(message, "pairDataIngestionStatus")) $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPairDataStatus.encode(message.pairDataIngestionStatus, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.userIdDataIngestionStatus != null && Object.hasOwnProperty.call(message, "userIdDataIngestionStatus")) + $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.encode(message.userIdDataIngestionStatus, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.ppidDataIngestionStatus != null && Object.hasOwnProperty.call(message, "ppidDataIngestionStatus")) + $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.encode(message.ppidDataIngestionStatus, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -10199,6 +10876,14 @@ message.pairDataIngestionStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPairDataStatus.decode(reader, reader.uint32()); break; } + case 4: { + message.userIdDataIngestionStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.decode(reader, reader.uint32()); + break; + } + case 5: { + message.ppidDataIngestionStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -10263,6 +10948,26 @@ return "pairDataIngestionStatus." + error; } } + if (message.userIdDataIngestionStatus != null && message.hasOwnProperty("userIdDataIngestionStatus")) { + if (properties.status === 1) + return "status: multiple values"; + properties.status = 1; + { + var error = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.verify(message.userIdDataIngestionStatus); + if (error) + return "userIdDataIngestionStatus." + error; + } + } + if (message.ppidDataIngestionStatus != null && message.hasOwnProperty("ppidDataIngestionStatus")) { + if (properties.status === 1) + return "status: multiple values"; + properties.status = 1; + { + var error = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.verify(message.ppidDataIngestionStatus); + if (error) + return "ppidDataIngestionStatus." + error; + } + } return null; }; @@ -10293,6 +10998,16 @@ throw TypeError(".google.ads.datamanager.v1.RequestStatusPerDestination.IngestAudienceMembersStatus.pairDataIngestionStatus: object expected"); message.pairDataIngestionStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPairDataStatus.fromObject(object.pairDataIngestionStatus); } + if (object.userIdDataIngestionStatus != null) { + if (typeof object.userIdDataIngestionStatus !== "object") + throw TypeError(".google.ads.datamanager.v1.RequestStatusPerDestination.IngestAudienceMembersStatus.userIdDataIngestionStatus: object expected"); + message.userIdDataIngestionStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.fromObject(object.userIdDataIngestionStatus); + } + if (object.ppidDataIngestionStatus != null) { + if (typeof object.ppidDataIngestionStatus !== "object") + throw TypeError(".google.ads.datamanager.v1.RequestStatusPerDestination.IngestAudienceMembersStatus.ppidDataIngestionStatus: object expected"); + message.ppidDataIngestionStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.fromObject(object.ppidDataIngestionStatus); + } return message; }; @@ -10324,6 +11039,16 @@ if (options.oneofs) object.status = "pairDataIngestionStatus"; } + if (message.userIdDataIngestionStatus != null && message.hasOwnProperty("userIdDataIngestionStatus")) { + object.userIdDataIngestionStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.toObject(message.userIdDataIngestionStatus, options); + if (options.oneofs) + object.status = "userIdDataIngestionStatus"; + } + if (message.ppidDataIngestionStatus != null && message.hasOwnProperty("ppidDataIngestionStatus")) { + object.ppidDataIngestionStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.toObject(message.ppidDataIngestionStatus, options); + if (options.oneofs) + object.status = "ppidDataIngestionStatus"; + } return object; }; @@ -10365,6 +11090,8 @@ * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserDataStatus|null} [userDataRemovalStatus] RemoveAudienceMembersStatus userDataRemovalStatus * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveMobileDataStatus|null} [mobileDataRemovalStatus] RemoveAudienceMembersStatus mobileDataRemovalStatus * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePairDataStatus|null} [pairDataRemovalStatus] RemoveAudienceMembersStatus pairDataRemovalStatus + * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus|null} [userIdDataRemovalStatus] RemoveAudienceMembersStatus userIdDataRemovalStatus + * @property {google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus|null} [ppidDataRemovalStatus] RemoveAudienceMembersStatus ppidDataRemovalStatus */ /** @@ -10406,17 +11133,33 @@ */ RemoveAudienceMembersStatus.prototype.pairDataRemovalStatus = null; + /** + * RemoveAudienceMembersStatus userIdDataRemovalStatus. + * @member {google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus|null|undefined} userIdDataRemovalStatus + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveAudienceMembersStatus + * @instance + */ + RemoveAudienceMembersStatus.prototype.userIdDataRemovalStatus = null; + + /** + * RemoveAudienceMembersStatus ppidDataRemovalStatus. + * @member {google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus|null|undefined} ppidDataRemovalStatus + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveAudienceMembersStatus + * @instance + */ + RemoveAudienceMembersStatus.prototype.ppidDataRemovalStatus = null; + // OneOf field names bound to virtual getters and setters var $oneOfFields; /** * RemoveAudienceMembersStatus status. - * @member {"userDataRemovalStatus"|"mobileDataRemovalStatus"|"pairDataRemovalStatus"|undefined} status + * @member {"userDataRemovalStatus"|"mobileDataRemovalStatus"|"pairDataRemovalStatus"|"userIdDataRemovalStatus"|"ppidDataRemovalStatus"|undefined} status * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveAudienceMembersStatus * @instance */ Object.defineProperty(RemoveAudienceMembersStatus.prototype, "status", { - get: $util.oneOfGetter($oneOfFields = ["userDataRemovalStatus", "mobileDataRemovalStatus", "pairDataRemovalStatus"]), + get: $util.oneOfGetter($oneOfFields = ["userDataRemovalStatus", "mobileDataRemovalStatus", "pairDataRemovalStatus", "userIdDataRemovalStatus", "ppidDataRemovalStatus"]), set: $util.oneOfSetter($oneOfFields) }); @@ -10450,6 +11193,10 @@ $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemoveMobileDataStatus.encode(message.mobileDataRemovalStatus, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.pairDataRemovalStatus != null && Object.hasOwnProperty.call(message, "pairDataRemovalStatus")) $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePairDataStatus.encode(message.pairDataRemovalStatus, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.userIdDataRemovalStatus != null && Object.hasOwnProperty.call(message, "userIdDataRemovalStatus")) + $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.encode(message.userIdDataRemovalStatus, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.ppidDataRemovalStatus != null && Object.hasOwnProperty.call(message, "ppidDataRemovalStatus")) + $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.encode(message.ppidDataRemovalStatus, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -10498,6 +11245,14 @@ message.pairDataRemovalStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePairDataStatus.decode(reader, reader.uint32()); break; } + case 4: { + message.userIdDataRemovalStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.decode(reader, reader.uint32()); + break; + } + case 5: { + message.ppidDataRemovalStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -10562,6 +11317,26 @@ return "pairDataRemovalStatus." + error; } } + if (message.userIdDataRemovalStatus != null && message.hasOwnProperty("userIdDataRemovalStatus")) { + if (properties.status === 1) + return "status: multiple values"; + properties.status = 1; + { + var error = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.verify(message.userIdDataRemovalStatus); + if (error) + return "userIdDataRemovalStatus." + error; + } + } + if (message.ppidDataRemovalStatus != null && message.hasOwnProperty("ppidDataRemovalStatus")) { + if (properties.status === 1) + return "status: multiple values"; + properties.status = 1; + { + var error = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.verify(message.ppidDataRemovalStatus); + if (error) + return "ppidDataRemovalStatus." + error; + } + } return null; }; @@ -10592,6 +11367,16 @@ throw TypeError(".google.ads.datamanager.v1.RequestStatusPerDestination.RemoveAudienceMembersStatus.pairDataRemovalStatus: object expected"); message.pairDataRemovalStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePairDataStatus.fromObject(object.pairDataRemovalStatus); } + if (object.userIdDataRemovalStatus != null) { + if (typeof object.userIdDataRemovalStatus !== "object") + throw TypeError(".google.ads.datamanager.v1.RequestStatusPerDestination.RemoveAudienceMembersStatus.userIdDataRemovalStatus: object expected"); + message.userIdDataRemovalStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.fromObject(object.userIdDataRemovalStatus); + } + if (object.ppidDataRemovalStatus != null) { + if (typeof object.ppidDataRemovalStatus !== "object") + throw TypeError(".google.ads.datamanager.v1.RequestStatusPerDestination.RemoveAudienceMembersStatus.ppidDataRemovalStatus: object expected"); + message.ppidDataRemovalStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.fromObject(object.ppidDataRemovalStatus); + } return message; }; @@ -10623,6 +11408,16 @@ if (options.oneofs) object.status = "pairDataRemovalStatus"; } + if (message.userIdDataRemovalStatus != null && message.hasOwnProperty("userIdDataRemovalStatus")) { + object.userIdDataRemovalStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.toObject(message.userIdDataRemovalStatus, options); + if (options.oneofs) + object.status = "userIdDataRemovalStatus"; + } + if (message.ppidDataRemovalStatus != null && message.hasOwnProperty("ppidDataRemovalStatus")) { + object.ppidDataRemovalStatus = $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.toObject(message.ppidDataRemovalStatus, options); + if (options.oneofs) + object.status = "ppidDataRemovalStatus"; + } return object; }; @@ -12503,286 +13298,15669 @@ return RemovePairDataStatus; })(); - return RequestStatusPerDestination; - })(); - - /** - * MatchRateRange enum. - * @name google.ads.datamanager.v1.MatchRateRange - * @enum {number} - * @property {number} MATCH_RATE_RANGE_UNKNOWN=0 MATCH_RATE_RANGE_UNKNOWN value - * @property {number} MATCH_RATE_RANGE_NOT_ELIGIBLE=1 MATCH_RATE_RANGE_NOT_ELIGIBLE value - * @property {number} MATCH_RATE_RANGE_LESS_THAN_20=2 MATCH_RATE_RANGE_LESS_THAN_20 value - * @property {number} MATCH_RATE_RANGE_20_TO_30=3 MATCH_RATE_RANGE_20_TO_30 value - * @property {number} MATCH_RATE_RANGE_31_TO_40=4 MATCH_RATE_RANGE_31_TO_40 value - * @property {number} MATCH_RATE_RANGE_41_TO_50=5 MATCH_RATE_RANGE_41_TO_50 value - * @property {number} MATCH_RATE_RANGE_51_TO_60=6 MATCH_RATE_RANGE_51_TO_60 value - * @property {number} MATCH_RATE_RANGE_61_TO_70=7 MATCH_RATE_RANGE_61_TO_70 value - * @property {number} MATCH_RATE_RANGE_71_TO_80=8 MATCH_RATE_RANGE_71_TO_80 value - * @property {number} MATCH_RATE_RANGE_81_TO_90=9 MATCH_RATE_RANGE_81_TO_90 value - * @property {number} MATCH_RATE_RANGE_91_TO_100=10 MATCH_RATE_RANGE_91_TO_100 value - */ - v1.MatchRateRange = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "MATCH_RATE_RANGE_UNKNOWN"] = 0; - values[valuesById[1] = "MATCH_RATE_RANGE_NOT_ELIGIBLE"] = 1; - values[valuesById[2] = "MATCH_RATE_RANGE_LESS_THAN_20"] = 2; - values[valuesById[3] = "MATCH_RATE_RANGE_20_TO_30"] = 3; - values[valuesById[4] = "MATCH_RATE_RANGE_31_TO_40"] = 4; - values[valuesById[5] = "MATCH_RATE_RANGE_41_TO_50"] = 5; - values[valuesById[6] = "MATCH_RATE_RANGE_51_TO_60"] = 6; - values[valuesById[7] = "MATCH_RATE_RANGE_61_TO_70"] = 7; - values[valuesById[8] = "MATCH_RATE_RANGE_71_TO_80"] = 8; - values[valuesById[9] = "MATCH_RATE_RANGE_81_TO_90"] = 9; - values[valuesById[10] = "MATCH_RATE_RANGE_91_TO_100"] = 10; - return values; - })(); + RequestStatusPerDestination.IngestUserIdDataStatus = (function() { - v1.ErrorInfo = (function() { + /** + * Properties of an IngestUserIdDataStatus. + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination + * @interface IIngestUserIdDataStatus + * @property {number|Long|null} [recordCount] IngestUserIdDataStatus recordCount + * @property {number|Long|null} [userIdCount] IngestUserIdDataStatus userIdCount + */ - /** - * Properties of an ErrorInfo. - * @memberof google.ads.datamanager.v1 - * @interface IErrorInfo - * @property {Array.|null} [errorCounts] ErrorInfo errorCounts - */ + /** + * Constructs a new IngestUserIdDataStatus. + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination + * @classdesc Represents an IngestUserIdDataStatus. + * @implements IIngestUserIdDataStatus + * @constructor + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus=} [properties] Properties to set + */ + function IngestUserIdDataStatus(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new ErrorInfo. - * @memberof google.ads.datamanager.v1 - * @classdesc Represents an ErrorInfo. - * @implements IErrorInfo - * @constructor - * @param {google.ads.datamanager.v1.IErrorInfo=} [properties] Properties to set - */ - function ErrorInfo(properties) { - this.errorCounts = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * IngestUserIdDataStatus recordCount. + * @member {number|Long} recordCount + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @instance + */ + IngestUserIdDataStatus.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - /** - * ErrorInfo errorCounts. - * @member {Array.} errorCounts - * @memberof google.ads.datamanager.v1.ErrorInfo - * @instance - */ - ErrorInfo.prototype.errorCounts = $util.emptyArray; + /** + * IngestUserIdDataStatus userIdCount. + * @member {number|Long} userIdCount + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @instance + */ + IngestUserIdDataStatus.prototype.userIdCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - /** - * Creates a new ErrorInfo instance using the specified properties. - * @function create - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {google.ads.datamanager.v1.IErrorInfo=} [properties] Properties to set - * @returns {google.ads.datamanager.v1.ErrorInfo} ErrorInfo instance - */ - ErrorInfo.create = function create(properties) { - return new ErrorInfo(properties); - }; + /** + * Creates a new IngestUserIdDataStatus instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus} IngestUserIdDataStatus instance + */ + IngestUserIdDataStatus.create = function create(properties) { + return new IngestUserIdDataStatus(properties); + }; - /** - * Encodes the specified ErrorInfo message. Does not implicitly {@link google.ads.datamanager.v1.ErrorInfo.verify|verify} messages. - * @function encode - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {google.ads.datamanager.v1.IErrorInfo} message ErrorInfo message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ErrorInfo.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.errorCounts != null && message.errorCounts.length) - for (var i = 0; i < message.errorCounts.length; ++i) - $root.google.ads.datamanager.v1.ErrorCount.encode(message.errorCounts[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; + /** + * Encodes the specified IngestUserIdDataStatus message. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus} message IngestUserIdDataStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IngestUserIdDataStatus.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.recordCount); + if (message.userIdCount != null && Object.hasOwnProperty.call(message, "userIdCount")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.userIdCount); + return writer; + }; - /** - * Encodes the specified ErrorInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ErrorInfo.verify|verify} messages. - * @function encodeDelimited - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {google.ads.datamanager.v1.IErrorInfo} message ErrorInfo message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ErrorInfo.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + /** + * Encodes the specified IngestUserIdDataStatus message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestUserIdDataStatus} message IngestUserIdDataStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IngestUserIdDataStatus.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; - /** - * Decodes an ErrorInfo message from the specified reader or buffer. - * @function decode - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.ads.datamanager.v1.ErrorInfo} ErrorInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ErrorInfo.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.ads.datamanager.v1.ErrorInfo(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.errorCounts && message.errorCounts.length)) - message.errorCounts = []; - message.errorCounts.push($root.google.ads.datamanager.v1.ErrorCount.decode(reader, reader.uint32())); + /** + * Decodes an IngestUserIdDataStatus message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus} IngestUserIdDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IngestUserIdDataStatus.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.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.recordCount = reader.int64(); + break; + } + case 2: { + message.userIdCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); break; } - default: - reader.skipType(tag & 7); - break; } - } - return message; - }; + return message; + }; - /** - * Decodes an ErrorInfo message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.ads.datamanager.v1.ErrorInfo} ErrorInfo - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ErrorInfo.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + /** + * Decodes an IngestUserIdDataStatus message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus} IngestUserIdDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IngestUserIdDataStatus.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; - /** - * Verifies an ErrorInfo message. - * @function verify - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ErrorInfo.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.errorCounts != null && message.hasOwnProperty("errorCounts")) { - if (!Array.isArray(message.errorCounts)) - return "errorCounts: array expected"; - for (var i = 0; i < message.errorCounts.length; ++i) { - var error = $root.google.ads.datamanager.v1.ErrorCount.verify(message.errorCounts[i]); - if (error) - return "errorCounts." + error; - } - } - return null; - }; + /** + * Verifies an IngestUserIdDataStatus message. + * @function verify + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + IngestUserIdDataStatus.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) + return "recordCount: integer|Long expected"; + if (message.userIdCount != null && message.hasOwnProperty("userIdCount")) + if (!$util.isInteger(message.userIdCount) && !(message.userIdCount && $util.isInteger(message.userIdCount.low) && $util.isInteger(message.userIdCount.high))) + return "userIdCount: integer|Long expected"; + return null; + }; - /** - * Creates an ErrorInfo message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {Object.} object Plain object - * @returns {google.ads.datamanager.v1.ErrorInfo} ErrorInfo - */ - ErrorInfo.fromObject = function fromObject(object) { - if (object instanceof $root.google.ads.datamanager.v1.ErrorInfo) + /** + * Creates an IngestUserIdDataStatus message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus} IngestUserIdDataStatus + */ + IngestUserIdDataStatus.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus) + return object; + var message = new $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus(); + if (object.recordCount != null) + if ($util.Long) + (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; + else if (typeof object.recordCount === "string") + message.recordCount = parseInt(object.recordCount, 10); + else if (typeof object.recordCount === "number") + message.recordCount = object.recordCount; + else if (typeof object.recordCount === "object") + message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); + if (object.userIdCount != null) + if ($util.Long) + (message.userIdCount = $util.Long.fromValue(object.userIdCount)).unsigned = false; + else if (typeof object.userIdCount === "string") + message.userIdCount = parseInt(object.userIdCount, 10); + else if (typeof object.userIdCount === "number") + message.userIdCount = object.userIdCount; + else if (typeof object.userIdCount === "object") + message.userIdCount = new $util.LongBits(object.userIdCount.low >>> 0, object.userIdCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from an IngestUserIdDataStatus message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus} message IngestUserIdDataStatus + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IngestUserIdDataStatus.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.recordCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.userIdCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.userIdCount = options.longs === String ? "0" : 0; + } + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (typeof message.recordCount === "number") + object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; + else + object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; + if (message.userIdCount != null && message.hasOwnProperty("userIdCount")) + if (typeof message.userIdCount === "number") + object.userIdCount = options.longs === String ? String(message.userIdCount) : message.userIdCount; + else + object.userIdCount = options.longs === String ? $util.Long.prototype.toString.call(message.userIdCount) : options.longs === Number ? new $util.LongBits(message.userIdCount.low >>> 0, message.userIdCount.high >>> 0).toNumber() : message.userIdCount; return object; - var message = new $root.google.ads.datamanager.v1.ErrorInfo(); - if (object.errorCounts) { - if (!Array.isArray(object.errorCounts)) - throw TypeError(".google.ads.datamanager.v1.ErrorInfo.errorCounts: array expected"); - message.errorCounts = []; - for (var i = 0; i < object.errorCounts.length; ++i) { - if (typeof object.errorCounts[i] !== "object") - throw TypeError(".google.ads.datamanager.v1.ErrorInfo.errorCounts: object expected"); - message.errorCounts[i] = $root.google.ads.datamanager.v1.ErrorCount.fromObject(object.errorCounts[i]); + }; + + /** + * Converts this IngestUserIdDataStatus to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @instance + * @returns {Object.} JSON object + */ + IngestUserIdDataStatus.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IngestUserIdDataStatus + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IngestUserIdDataStatus.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } - } - return message; - }; + return typeUrlPrefix + "/google.ads.datamanager.v1.RequestStatusPerDestination.IngestUserIdDataStatus"; + }; - /** - * Creates a plain object from an ErrorInfo message. Also converts values to other types if specified. - * @function toObject - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {google.ads.datamanager.v1.ErrorInfo} message ErrorInfo - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ErrorInfo.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.errorCounts = []; - if (message.errorCounts && message.errorCounts.length) { - object.errorCounts = []; - for (var j = 0; j < message.errorCounts.length; ++j) - object.errorCounts[j] = $root.google.ads.datamanager.v1.ErrorCount.toObject(message.errorCounts[j], options); - } - return object; - }; + return IngestUserIdDataStatus; + })(); - /** - * Converts this ErrorInfo to JSON. - * @function toJSON - * @memberof google.ads.datamanager.v1.ErrorInfo - * @instance - * @returns {Object.} JSON object - */ - ErrorInfo.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + RequestStatusPerDestination.RemoveUserIdDataStatus = (function() { - /** - * Gets the default type url for ErrorInfo - * @function getTypeUrl - * @memberof google.ads.datamanager.v1.ErrorInfo - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ErrorInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + /** + * Properties of a RemoveUserIdDataStatus. + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination + * @interface IRemoveUserIdDataStatus + * @property {number|Long|null} [recordCount] RemoveUserIdDataStatus recordCount + * @property {number|Long|null} [userIdCount] RemoveUserIdDataStatus userIdCount + */ + + /** + * Constructs a new RemoveUserIdDataStatus. + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination + * @classdesc Represents a RemoveUserIdDataStatus. + * @implements IRemoveUserIdDataStatus + * @constructor + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus=} [properties] Properties to set + */ + function RemoveUserIdDataStatus(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return typeUrlPrefix + "/google.ads.datamanager.v1.ErrorInfo"; - }; - return ErrorInfo; - })(); + /** + * RemoveUserIdDataStatus recordCount. + * @member {number|Long} recordCount + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @instance + */ + RemoveUserIdDataStatus.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - v1.ErrorCount = (function() { + /** + * RemoveUserIdDataStatus userIdCount. + * @member {number|Long} userIdCount + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @instance + */ + RemoveUserIdDataStatus.prototype.userIdCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - /** - * Properties of an ErrorCount. - * @memberof google.ads.datamanager.v1 - * @interface IErrorCount - * @property {number|Long|null} [recordCount] ErrorCount recordCount - * @property {google.ads.datamanager.v1.ProcessingErrorReason|null} [reason] ErrorCount reason - */ + /** + * Creates a new RemoveUserIdDataStatus instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus} RemoveUserIdDataStatus instance + */ + RemoveUserIdDataStatus.create = function create(properties) { + return new RemoveUserIdDataStatus(properties); + }; + + /** + * Encodes the specified RemoveUserIdDataStatus message. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus} message RemoveUserIdDataStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RemoveUserIdDataStatus.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.recordCount); + if (message.userIdCount != null && Object.hasOwnProperty.call(message, "userIdCount")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.userIdCount); + return writer; + }; + + /** + * Encodes the specified RemoveUserIdDataStatus message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IRemoveUserIdDataStatus} message RemoveUserIdDataStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RemoveUserIdDataStatus.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RemoveUserIdDataStatus message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus} RemoveUserIdDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RemoveUserIdDataStatus.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.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.recordCount = reader.int64(); + break; + } + case 2: { + message.userIdCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RemoveUserIdDataStatus message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus} RemoveUserIdDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RemoveUserIdDataStatus.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RemoveUserIdDataStatus message. + * @function verify + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RemoveUserIdDataStatus.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) + return "recordCount: integer|Long expected"; + if (message.userIdCount != null && message.hasOwnProperty("userIdCount")) + if (!$util.isInteger(message.userIdCount) && !(message.userIdCount && $util.isInteger(message.userIdCount.low) && $util.isInteger(message.userIdCount.high))) + return "userIdCount: integer|Long expected"; + return null; + }; + + /** + * Creates a RemoveUserIdDataStatus message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus} RemoveUserIdDataStatus + */ + RemoveUserIdDataStatus.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus) + return object; + var message = new $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus(); + if (object.recordCount != null) + if ($util.Long) + (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; + else if (typeof object.recordCount === "string") + message.recordCount = parseInt(object.recordCount, 10); + else if (typeof object.recordCount === "number") + message.recordCount = object.recordCount; + else if (typeof object.recordCount === "object") + message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); + if (object.userIdCount != null) + if ($util.Long) + (message.userIdCount = $util.Long.fromValue(object.userIdCount)).unsigned = false; + else if (typeof object.userIdCount === "string") + message.userIdCount = parseInt(object.userIdCount, 10); + else if (typeof object.userIdCount === "number") + message.userIdCount = object.userIdCount; + else if (typeof object.userIdCount === "object") + message.userIdCount = new $util.LongBits(object.userIdCount.low >>> 0, object.userIdCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a RemoveUserIdDataStatus message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus} message RemoveUserIdDataStatus + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RemoveUserIdDataStatus.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.recordCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.userIdCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.userIdCount = options.longs === String ? "0" : 0; + } + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (typeof message.recordCount === "number") + object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; + else + object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; + if (message.userIdCount != null && message.hasOwnProperty("userIdCount")) + if (typeof message.userIdCount === "number") + object.userIdCount = options.longs === String ? String(message.userIdCount) : message.userIdCount; + else + object.userIdCount = options.longs === String ? $util.Long.prototype.toString.call(message.userIdCount) : options.longs === Number ? new $util.LongBits(message.userIdCount.low >>> 0, message.userIdCount.high >>> 0).toNumber() : message.userIdCount; + return object; + }; + + /** + * Converts this RemoveUserIdDataStatus to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @instance + * @returns {Object.} JSON object + */ + RemoveUserIdDataStatus.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RemoveUserIdDataStatus + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RemoveUserIdDataStatus.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.RequestStatusPerDestination.RemoveUserIdDataStatus"; + }; + + return RemoveUserIdDataStatus; + })(); + + RequestStatusPerDestination.IngestPpidDataStatus = (function() { + + /** + * Properties of an IngestPpidDataStatus. + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination + * @interface IIngestPpidDataStatus + * @property {number|Long|null} [recordCount] IngestPpidDataStatus recordCount + * @property {number|Long|null} [ppidCount] IngestPpidDataStatus ppidCount + */ + + /** + * Constructs a new IngestPpidDataStatus. + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination + * @classdesc Represents an IngestPpidDataStatus. + * @implements IIngestPpidDataStatus + * @constructor + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus=} [properties] Properties to set + */ + function IngestPpidDataStatus(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * IngestPpidDataStatus recordCount. + * @member {number|Long} recordCount + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @instance + */ + IngestPpidDataStatus.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * IngestPpidDataStatus ppidCount. + * @member {number|Long} ppidCount + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @instance + */ + IngestPpidDataStatus.prototype.ppidCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new IngestPpidDataStatus instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus} IngestPpidDataStatus instance + */ + IngestPpidDataStatus.create = function create(properties) { + return new IngestPpidDataStatus(properties); + }; + + /** + * Encodes the specified IngestPpidDataStatus message. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus} message IngestPpidDataStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IngestPpidDataStatus.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.recordCount); + if (message.ppidCount != null && Object.hasOwnProperty.call(message, "ppidCount")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.ppidCount); + return writer; + }; + + /** + * Encodes the specified IngestPpidDataStatus message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IIngestPpidDataStatus} message IngestPpidDataStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IngestPpidDataStatus.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an IngestPpidDataStatus message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus} IngestPpidDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IngestPpidDataStatus.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.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.recordCount = reader.int64(); + break; + } + case 2: { + message.ppidCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an IngestPpidDataStatus message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus} IngestPpidDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IngestPpidDataStatus.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an IngestPpidDataStatus message. + * @function verify + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + IngestPpidDataStatus.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) + return "recordCount: integer|Long expected"; + if (message.ppidCount != null && message.hasOwnProperty("ppidCount")) + if (!$util.isInteger(message.ppidCount) && !(message.ppidCount && $util.isInteger(message.ppidCount.low) && $util.isInteger(message.ppidCount.high))) + return "ppidCount: integer|Long expected"; + return null; + }; + + /** + * Creates an IngestPpidDataStatus message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus} IngestPpidDataStatus + */ + IngestPpidDataStatus.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus) + return object; + var message = new $root.google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus(); + if (object.recordCount != null) + if ($util.Long) + (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; + else if (typeof object.recordCount === "string") + message.recordCount = parseInt(object.recordCount, 10); + else if (typeof object.recordCount === "number") + message.recordCount = object.recordCount; + else if (typeof object.recordCount === "object") + message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); + if (object.ppidCount != null) + if ($util.Long) + (message.ppidCount = $util.Long.fromValue(object.ppidCount)).unsigned = false; + else if (typeof object.ppidCount === "string") + message.ppidCount = parseInt(object.ppidCount, 10); + else if (typeof object.ppidCount === "number") + message.ppidCount = object.ppidCount; + else if (typeof object.ppidCount === "object") + message.ppidCount = new $util.LongBits(object.ppidCount.low >>> 0, object.ppidCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from an IngestPpidDataStatus message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus} message IngestPpidDataStatus + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IngestPpidDataStatus.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.recordCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.ppidCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.ppidCount = options.longs === String ? "0" : 0; + } + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (typeof message.recordCount === "number") + object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; + else + object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; + if (message.ppidCount != null && message.hasOwnProperty("ppidCount")) + if (typeof message.ppidCount === "number") + object.ppidCount = options.longs === String ? String(message.ppidCount) : message.ppidCount; + else + object.ppidCount = options.longs === String ? $util.Long.prototype.toString.call(message.ppidCount) : options.longs === Number ? new $util.LongBits(message.ppidCount.low >>> 0, message.ppidCount.high >>> 0).toNumber() : message.ppidCount; + return object; + }; + + /** + * Converts this IngestPpidDataStatus to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @instance + * @returns {Object.} JSON object + */ + IngestPpidDataStatus.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IngestPpidDataStatus + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IngestPpidDataStatus.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.RequestStatusPerDestination.IngestPpidDataStatus"; + }; + + return IngestPpidDataStatus; + })(); + + RequestStatusPerDestination.RemovePpidDataStatus = (function() { + + /** + * Properties of a RemovePpidDataStatus. + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination + * @interface IRemovePpidDataStatus + * @property {number|Long|null} [recordCount] RemovePpidDataStatus recordCount + * @property {number|Long|null} [ppidCount] RemovePpidDataStatus ppidCount + */ + + /** + * Constructs a new RemovePpidDataStatus. + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination + * @classdesc Represents a RemovePpidDataStatus. + * @implements IRemovePpidDataStatus + * @constructor + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus=} [properties] Properties to set + */ + function RemovePpidDataStatus(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RemovePpidDataStatus recordCount. + * @member {number|Long} recordCount + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @instance + */ + RemovePpidDataStatus.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * RemovePpidDataStatus ppidCount. + * @member {number|Long} ppidCount + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @instance + */ + RemovePpidDataStatus.prototype.ppidCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new RemovePpidDataStatus instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus} RemovePpidDataStatus instance + */ + RemovePpidDataStatus.create = function create(properties) { + return new RemovePpidDataStatus(properties); + }; + + /** + * Encodes the specified RemovePpidDataStatus message. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus} message RemovePpidDataStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RemovePpidDataStatus.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.recordCount); + if (message.ppidCount != null && Object.hasOwnProperty.call(message, "ppidCount")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.ppidCount); + return writer; + }; + + /** + * Encodes the specified RemovePpidDataStatus message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.IRemovePpidDataStatus} message RemovePpidDataStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RemovePpidDataStatus.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RemovePpidDataStatus message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus} RemovePpidDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RemovePpidDataStatus.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.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.recordCount = reader.int64(); + break; + } + case 2: { + message.ppidCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RemovePpidDataStatus message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus} RemovePpidDataStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RemovePpidDataStatus.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RemovePpidDataStatus message. + * @function verify + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RemovePpidDataStatus.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) + return "recordCount: integer|Long expected"; + if (message.ppidCount != null && message.hasOwnProperty("ppidCount")) + if (!$util.isInteger(message.ppidCount) && !(message.ppidCount && $util.isInteger(message.ppidCount.low) && $util.isInteger(message.ppidCount.high))) + return "ppidCount: integer|Long expected"; + return null; + }; + + /** + * Creates a RemovePpidDataStatus message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus} RemovePpidDataStatus + */ + RemovePpidDataStatus.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus) + return object; + var message = new $root.google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus(); + if (object.recordCount != null) + if ($util.Long) + (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; + else if (typeof object.recordCount === "string") + message.recordCount = parseInt(object.recordCount, 10); + else if (typeof object.recordCount === "number") + message.recordCount = object.recordCount; + else if (typeof object.recordCount === "object") + message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); + if (object.ppidCount != null) + if ($util.Long) + (message.ppidCount = $util.Long.fromValue(object.ppidCount)).unsigned = false; + else if (typeof object.ppidCount === "string") + message.ppidCount = parseInt(object.ppidCount, 10); + else if (typeof object.ppidCount === "number") + message.ppidCount = object.ppidCount; + else if (typeof object.ppidCount === "object") + message.ppidCount = new $util.LongBits(object.ppidCount.low >>> 0, object.ppidCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a RemovePpidDataStatus message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus} message RemovePpidDataStatus + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RemovePpidDataStatus.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.recordCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.ppidCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.ppidCount = options.longs === String ? "0" : 0; + } + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (typeof message.recordCount === "number") + object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; + else + object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; + if (message.ppidCount != null && message.hasOwnProperty("ppidCount")) + if (typeof message.ppidCount === "number") + object.ppidCount = options.longs === String ? String(message.ppidCount) : message.ppidCount; + else + object.ppidCount = options.longs === String ? $util.Long.prototype.toString.call(message.ppidCount) : options.longs === Number ? new $util.LongBits(message.ppidCount.low >>> 0, message.ppidCount.high >>> 0).toNumber() : message.ppidCount; + return object; + }; + + /** + * Converts this RemovePpidDataStatus to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @instance + * @returns {Object.} JSON object + */ + RemovePpidDataStatus.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RemovePpidDataStatus + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RemovePpidDataStatus.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.RequestStatusPerDestination.RemovePpidDataStatus"; + }; + + return RemovePpidDataStatus; + })(); + + return RequestStatusPerDestination; + })(); + + /** + * MatchRateRange enum. + * @name google.ads.datamanager.v1.MatchRateRange + * @enum {number} + * @property {number} MATCH_RATE_RANGE_UNKNOWN=0 MATCH_RATE_RANGE_UNKNOWN value + * @property {number} MATCH_RATE_RANGE_NOT_ELIGIBLE=1 MATCH_RATE_RANGE_NOT_ELIGIBLE value + * @property {number} MATCH_RATE_RANGE_LESS_THAN_20=2 MATCH_RATE_RANGE_LESS_THAN_20 value + * @property {number} MATCH_RATE_RANGE_20_TO_30=3 MATCH_RATE_RANGE_20_TO_30 value + * @property {number} MATCH_RATE_RANGE_31_TO_40=4 MATCH_RATE_RANGE_31_TO_40 value + * @property {number} MATCH_RATE_RANGE_41_TO_50=5 MATCH_RATE_RANGE_41_TO_50 value + * @property {number} MATCH_RATE_RANGE_51_TO_60=6 MATCH_RATE_RANGE_51_TO_60 value + * @property {number} MATCH_RATE_RANGE_61_TO_70=7 MATCH_RATE_RANGE_61_TO_70 value + * @property {number} MATCH_RATE_RANGE_71_TO_80=8 MATCH_RATE_RANGE_71_TO_80 value + * @property {number} MATCH_RATE_RANGE_81_TO_90=9 MATCH_RATE_RANGE_81_TO_90 value + * @property {number} MATCH_RATE_RANGE_91_TO_100=10 MATCH_RATE_RANGE_91_TO_100 value + */ + v1.MatchRateRange = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MATCH_RATE_RANGE_UNKNOWN"] = 0; + values[valuesById[1] = "MATCH_RATE_RANGE_NOT_ELIGIBLE"] = 1; + values[valuesById[2] = "MATCH_RATE_RANGE_LESS_THAN_20"] = 2; + values[valuesById[3] = "MATCH_RATE_RANGE_20_TO_30"] = 3; + values[valuesById[4] = "MATCH_RATE_RANGE_31_TO_40"] = 4; + values[valuesById[5] = "MATCH_RATE_RANGE_41_TO_50"] = 5; + values[valuesById[6] = "MATCH_RATE_RANGE_51_TO_60"] = 6; + values[valuesById[7] = "MATCH_RATE_RANGE_61_TO_70"] = 7; + values[valuesById[8] = "MATCH_RATE_RANGE_71_TO_80"] = 8; + values[valuesById[9] = "MATCH_RATE_RANGE_81_TO_90"] = 9; + values[valuesById[10] = "MATCH_RATE_RANGE_91_TO_100"] = 10; + return values; + })(); + + v1.ErrorInfo = (function() { + + /** + * Properties of an ErrorInfo. + * @memberof google.ads.datamanager.v1 + * @interface IErrorInfo + * @property {Array.|null} [errorCounts] ErrorInfo errorCounts + */ + + /** + * Constructs a new ErrorInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents an ErrorInfo. + * @implements IErrorInfo + * @constructor + * @param {google.ads.datamanager.v1.IErrorInfo=} [properties] Properties to set + */ + function ErrorInfo(properties) { + this.errorCounts = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ErrorInfo errorCounts. + * @member {Array.} errorCounts + * @memberof google.ads.datamanager.v1.ErrorInfo + * @instance + */ + ErrorInfo.prototype.errorCounts = $util.emptyArray; + + /** + * Creates a new ErrorInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {google.ads.datamanager.v1.IErrorInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ErrorInfo} ErrorInfo instance + */ + ErrorInfo.create = function create(properties) { + return new ErrorInfo(properties); + }; + + /** + * Encodes the specified ErrorInfo message. Does not implicitly {@link google.ads.datamanager.v1.ErrorInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {google.ads.datamanager.v1.IErrorInfo} message ErrorInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ErrorInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.errorCounts != null && message.errorCounts.length) + for (var i = 0; i < message.errorCounts.length; ++i) + $root.google.ads.datamanager.v1.ErrorCount.encode(message.errorCounts[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ErrorInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ErrorInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {google.ads.datamanager.v1.IErrorInfo} message ErrorInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ErrorInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ErrorInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ErrorInfo} ErrorInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ErrorInfo.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.ads.datamanager.v1.ErrorInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.errorCounts && message.errorCounts.length)) + message.errorCounts = []; + message.errorCounts.push($root.google.ads.datamanager.v1.ErrorCount.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ErrorInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ErrorInfo} ErrorInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ErrorInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ErrorInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ErrorInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.errorCounts != null && message.hasOwnProperty("errorCounts")) { + if (!Array.isArray(message.errorCounts)) + return "errorCounts: array expected"; + for (var i = 0; i < message.errorCounts.length; ++i) { + var error = $root.google.ads.datamanager.v1.ErrorCount.verify(message.errorCounts[i]); + if (error) + return "errorCounts." + error; + } + } + return null; + }; + + /** + * Creates an ErrorInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ErrorInfo} ErrorInfo + */ + ErrorInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ErrorInfo) + return object; + var message = new $root.google.ads.datamanager.v1.ErrorInfo(); + if (object.errorCounts) { + if (!Array.isArray(object.errorCounts)) + throw TypeError(".google.ads.datamanager.v1.ErrorInfo.errorCounts: array expected"); + message.errorCounts = []; + for (var i = 0; i < object.errorCounts.length; ++i) { + if (typeof object.errorCounts[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.ErrorInfo.errorCounts: object expected"); + message.errorCounts[i] = $root.google.ads.datamanager.v1.ErrorCount.fromObject(object.errorCounts[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an ErrorInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {google.ads.datamanager.v1.ErrorInfo} message ErrorInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ErrorInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.errorCounts = []; + if (message.errorCounts && message.errorCounts.length) { + object.errorCounts = []; + for (var j = 0; j < message.errorCounts.length; ++j) + object.errorCounts[j] = $root.google.ads.datamanager.v1.ErrorCount.toObject(message.errorCounts[j], options); + } + return object; + }; + + /** + * Converts this ErrorInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ErrorInfo + * @instance + * @returns {Object.} JSON object + */ + ErrorInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ErrorInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ErrorInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ErrorInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ErrorInfo"; + }; + + return ErrorInfo; + })(); + + v1.ErrorCount = (function() { + + /** + * Properties of an ErrorCount. + * @memberof google.ads.datamanager.v1 + * @interface IErrorCount + * @property {number|Long|null} [recordCount] ErrorCount recordCount + * @property {google.ads.datamanager.v1.ProcessingErrorReason|null} [reason] ErrorCount reason + */ + + /** + * Constructs a new ErrorCount. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents an ErrorCount. + * @implements IErrorCount + * @constructor + * @param {google.ads.datamanager.v1.IErrorCount=} [properties] Properties to set + */ + function ErrorCount(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ErrorCount recordCount. + * @member {number|Long} recordCount + * @memberof google.ads.datamanager.v1.ErrorCount + * @instance + */ + ErrorCount.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * ErrorCount reason. + * @member {google.ads.datamanager.v1.ProcessingErrorReason} reason + * @memberof google.ads.datamanager.v1.ErrorCount + * @instance + */ + ErrorCount.prototype.reason = 0; + + /** + * Creates a new ErrorCount instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {google.ads.datamanager.v1.IErrorCount=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ErrorCount} ErrorCount instance + */ + ErrorCount.create = function create(properties) { + return new ErrorCount(properties); + }; + + /** + * Encodes the specified ErrorCount message. Does not implicitly {@link google.ads.datamanager.v1.ErrorCount.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {google.ads.datamanager.v1.IErrorCount} message ErrorCount message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ErrorCount.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.recordCount); + if (message.reason != null && Object.hasOwnProperty.call(message, "reason")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.reason); + return writer; + }; + + /** + * Encodes the specified ErrorCount message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ErrorCount.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {google.ads.datamanager.v1.IErrorCount} message ErrorCount message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ErrorCount.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ErrorCount message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ErrorCount} ErrorCount + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ErrorCount.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.ads.datamanager.v1.ErrorCount(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.recordCount = reader.int64(); + break; + } + case 2: { + message.reason = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ErrorCount message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ErrorCount} ErrorCount + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ErrorCount.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ErrorCount message. + * @function verify + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ErrorCount.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) + return "recordCount: integer|Long expected"; + if (message.reason != null && message.hasOwnProperty("reason")) + switch (message.reason) { + default: + return "reason: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + case 22: + case 23: + case 24: + case 27: + case 25: + case 26: + break; + } + return null; + }; + + /** + * Creates an ErrorCount message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ErrorCount} ErrorCount + */ + ErrorCount.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ErrorCount) + return object; + var message = new $root.google.ads.datamanager.v1.ErrorCount(); + if (object.recordCount != null) + if ($util.Long) + (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; + else if (typeof object.recordCount === "string") + message.recordCount = parseInt(object.recordCount, 10); + else if (typeof object.recordCount === "number") + message.recordCount = object.recordCount; + else if (typeof object.recordCount === "object") + message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); + switch (object.reason) { + default: + if (typeof object.reason === "number") { + message.reason = object.reason; + break; + } + break; + case "PROCESSING_ERROR_REASON_UNSPECIFIED": + case 0: + message.reason = 0; + break; + case "PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE": + case 1: + message.reason = 1; + break; + case "PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED": + case 2: + message.reason = 2; + break; + case "PROCESSING_ERROR_REASON_EVENT_TOO_OLD": + case 3: + message.reason = 3; + break; + case "PROCESSING_ERROR_REASON_DENIED_CONSENT": + case 4: + message.reason = 4; + break; + case "PROCESSING_ERROR_REASON_NO_CONSENT": + case 5: + message.reason = 5; + break; + case "PROCESSING_ERROR_REASON_UNKNOWN_CONSENT": + case 6: + message.reason = 6; + break; + case "PROCESSING_ERROR_REASON_DUPLICATE_GCLID": + case 7: + message.reason = 7; + break; + case "PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID": + case 8: + message.reason = 8; + break; + case "PROCESSING_ERROR_REASON_INVALID_GBRAID": + case 9: + message.reason = 9; + break; + case "PROCESSING_ERROR_REASON_INVALID_GCLID": + case 10: + message.reason = 10; + break; + case "PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID": + case 11: + message.reason = 11; + break; + case "PROCESSING_ERROR_REASON_INVALID_WBRAID": + case 12: + message.reason = 12; + break; + case "PROCESSING_ERROR_REASON_INTERNAL_ERROR": + case 13: + message.reason = 13; + break; + case "PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED": + case 14: + message.reason = 14; + break; + case "PROCESSING_ERROR_REASON_INVALID_EVENT": + case 15: + message.reason = 15; + break; + case "PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS": + case 16: + message.reason = 16; + break; + case "PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS": + case 17: + message.reason = 17; + break; + case "PROCESSING_ERROR_REASON_INVALID_FORMAT": + case 18: + message.reason = 18; + break; + case "PROCESSING_ERROR_REASON_DECRYPTION_ERROR": + case 19: + message.reason = 19; + break; + case "PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR": + case 20: + message.reason = 20; + break; + case "PROCESSING_ERROR_REASON_INVALID_WIP": + case 21: + message.reason = 21; + break; + case "PROCESSING_ERROR_REASON_INVALID_KEK": + case 22: + message.reason = 22; + break; + case "PROCESSING_ERROR_REASON_WIP_AUTH_FAILED": + case 23: + message.reason = 23; + break; + case "PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED": + case 24: + message.reason = 24; + break; + case "PROCESSING_ERROR_REASON_AWS_AUTH_FAILED": + case 27: + message.reason = 27; + break; + case "PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR": + case 25: + message.reason = 25; + break; + case "PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER": + case 26: + message.reason = 26; + break; + } + return message; + }; + + /** + * Creates a plain object from an ErrorCount message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {google.ads.datamanager.v1.ErrorCount} message ErrorCount + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ErrorCount.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.recordCount = options.longs === String ? "0" : 0; + object.reason = options.enums === String ? "PROCESSING_ERROR_REASON_UNSPECIFIED" : 0; + } + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (typeof message.recordCount === "number") + object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; + else + object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; + if (message.reason != null && message.hasOwnProperty("reason")) + object.reason = options.enums === String ? $root.google.ads.datamanager.v1.ProcessingErrorReason[message.reason] === undefined ? message.reason : $root.google.ads.datamanager.v1.ProcessingErrorReason[message.reason] : message.reason; + return object; + }; + + /** + * Converts this ErrorCount to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ErrorCount + * @instance + * @returns {Object.} JSON object + */ + ErrorCount.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ErrorCount + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ErrorCount + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ErrorCount.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ErrorCount"; + }; + + return ErrorCount; + })(); + + v1.WarningInfo = (function() { + + /** + * Properties of a WarningInfo. + * @memberof google.ads.datamanager.v1 + * @interface IWarningInfo + * @property {Array.|null} [warningCounts] WarningInfo warningCounts + */ + + /** + * Constructs a new WarningInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a WarningInfo. + * @implements IWarningInfo + * @constructor + * @param {google.ads.datamanager.v1.IWarningInfo=} [properties] Properties to set + */ + function WarningInfo(properties) { + this.warningCounts = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WarningInfo warningCounts. + * @member {Array.} warningCounts + * @memberof google.ads.datamanager.v1.WarningInfo + * @instance + */ + WarningInfo.prototype.warningCounts = $util.emptyArray; + + /** + * Creates a new WarningInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {google.ads.datamanager.v1.IWarningInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.WarningInfo} WarningInfo instance + */ + WarningInfo.create = function create(properties) { + return new WarningInfo(properties); + }; + + /** + * Encodes the specified WarningInfo message. Does not implicitly {@link google.ads.datamanager.v1.WarningInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {google.ads.datamanager.v1.IWarningInfo} message WarningInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WarningInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.warningCounts != null && message.warningCounts.length) + for (var i = 0; i < message.warningCounts.length; ++i) + $root.google.ads.datamanager.v1.WarningCount.encode(message.warningCounts[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified WarningInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.WarningInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {google.ads.datamanager.v1.IWarningInfo} message WarningInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WarningInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a WarningInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.WarningInfo} WarningInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WarningInfo.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.ads.datamanager.v1.WarningInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.warningCounts && message.warningCounts.length)) + message.warningCounts = []; + message.warningCounts.push($root.google.ads.datamanager.v1.WarningCount.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a WarningInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.WarningInfo} WarningInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WarningInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a WarningInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + WarningInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.warningCounts != null && message.hasOwnProperty("warningCounts")) { + if (!Array.isArray(message.warningCounts)) + return "warningCounts: array expected"; + for (var i = 0; i < message.warningCounts.length; ++i) { + var error = $root.google.ads.datamanager.v1.WarningCount.verify(message.warningCounts[i]); + if (error) + return "warningCounts." + error; + } + } + return null; + }; + + /** + * Creates a WarningInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.WarningInfo} WarningInfo + */ + WarningInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.WarningInfo) + return object; + var message = new $root.google.ads.datamanager.v1.WarningInfo(); + if (object.warningCounts) { + if (!Array.isArray(object.warningCounts)) + throw TypeError(".google.ads.datamanager.v1.WarningInfo.warningCounts: array expected"); + message.warningCounts = []; + for (var i = 0; i < object.warningCounts.length; ++i) { + if (typeof object.warningCounts[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.WarningInfo.warningCounts: object expected"); + message.warningCounts[i] = $root.google.ads.datamanager.v1.WarningCount.fromObject(object.warningCounts[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a WarningInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {google.ads.datamanager.v1.WarningInfo} message WarningInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WarningInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.warningCounts = []; + if (message.warningCounts && message.warningCounts.length) { + object.warningCounts = []; + for (var j = 0; j < message.warningCounts.length; ++j) + object.warningCounts[j] = $root.google.ads.datamanager.v1.WarningCount.toObject(message.warningCounts[j], options); + } + return object; + }; + + /** + * Converts this WarningInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.WarningInfo + * @instance + * @returns {Object.} JSON object + */ + WarningInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WarningInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.WarningInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WarningInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.WarningInfo"; + }; + + return WarningInfo; + })(); + + v1.WarningCount = (function() { + + /** + * Properties of a WarningCount. + * @memberof google.ads.datamanager.v1 + * @interface IWarningCount + * @property {number|Long|null} [recordCount] WarningCount recordCount + * @property {google.ads.datamanager.v1.ProcessingWarningReason|null} [reason] WarningCount reason + */ + + /** + * Constructs a new WarningCount. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a WarningCount. + * @implements IWarningCount + * @constructor + * @param {google.ads.datamanager.v1.IWarningCount=} [properties] Properties to set + */ + function WarningCount(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WarningCount recordCount. + * @member {number|Long} recordCount + * @memberof google.ads.datamanager.v1.WarningCount + * @instance + */ + WarningCount.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * WarningCount reason. + * @member {google.ads.datamanager.v1.ProcessingWarningReason} reason + * @memberof google.ads.datamanager.v1.WarningCount + * @instance + */ + WarningCount.prototype.reason = 0; + + /** + * Creates a new WarningCount instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {google.ads.datamanager.v1.IWarningCount=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.WarningCount} WarningCount instance + */ + WarningCount.create = function create(properties) { + return new WarningCount(properties); + }; + + /** + * Encodes the specified WarningCount message. Does not implicitly {@link google.ads.datamanager.v1.WarningCount.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {google.ads.datamanager.v1.IWarningCount} message WarningCount message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WarningCount.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.recordCount); + if (message.reason != null && Object.hasOwnProperty.call(message, "reason")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.reason); + return writer; + }; + + /** + * Encodes the specified WarningCount message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.WarningCount.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {google.ads.datamanager.v1.IWarningCount} message WarningCount message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WarningCount.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a WarningCount message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.WarningCount} WarningCount + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WarningCount.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.ads.datamanager.v1.WarningCount(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.recordCount = reader.int64(); + break; + } + case 2: { + message.reason = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a WarningCount message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.WarningCount} WarningCount + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WarningCount.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a WarningCount message. + * @function verify + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + WarningCount.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) + return "recordCount: integer|Long expected"; + if (message.reason != null && message.hasOwnProperty("reason")) + switch (message.reason) { + default: + return "reason: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + break; + } + return null; + }; + + /** + * Creates a WarningCount message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.WarningCount} WarningCount + */ + WarningCount.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.WarningCount) + return object; + var message = new $root.google.ads.datamanager.v1.WarningCount(); + if (object.recordCount != null) + if ($util.Long) + (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; + else if (typeof object.recordCount === "string") + message.recordCount = parseInt(object.recordCount, 10); + else if (typeof object.recordCount === "number") + message.recordCount = object.recordCount; + else if (typeof object.recordCount === "object") + message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); + switch (object.reason) { + default: + if (typeof object.reason === "number") { + message.reason = object.reason; + break; + } + break; + case "PROCESSING_WARNING_REASON_UNSPECIFIED": + case 0: + message.reason = 0; + break; + case "PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED": + case 1: + message.reason = 1; + break; + case "PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR": + case 2: + message.reason = 2; + break; + case "PROCESSING_WARNING_REASON_DECRYPTION_ERROR": + case 3: + message.reason = 3; + break; + case "PROCESSING_WARNING_REASON_WIP_AUTH_FAILED": + case 4: + message.reason = 4; + break; + case "PROCESSING_WARNING_REASON_INVALID_WIP": + case 5: + message.reason = 5; + break; + case "PROCESSING_WARNING_REASON_INVALID_KEK": + case 6: + message.reason = 6; + break; + case "PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR": + case 7: + message.reason = 7; + break; + case "PROCESSING_WARNING_REASON_INTERNAL_ERROR": + case 8: + message.reason = 8; + break; + case "PROCESSING_WARNING_REASON_AWS_AUTH_FAILED": + case 9: + message.reason = 9; + break; + } + return message; + }; + + /** + * Creates a plain object from a WarningCount message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {google.ads.datamanager.v1.WarningCount} message WarningCount + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WarningCount.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.recordCount = options.longs === String ? "0" : 0; + object.reason = options.enums === String ? "PROCESSING_WARNING_REASON_UNSPECIFIED" : 0; + } + if (message.recordCount != null && message.hasOwnProperty("recordCount")) + if (typeof message.recordCount === "number") + object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; + else + object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; + if (message.reason != null && message.hasOwnProperty("reason")) + object.reason = options.enums === String ? $root.google.ads.datamanager.v1.ProcessingWarningReason[message.reason] === undefined ? message.reason : $root.google.ads.datamanager.v1.ProcessingWarningReason[message.reason] : message.reason; + return object; + }; + + /** + * Converts this WarningCount to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.WarningCount + * @instance + * @returns {Object.} JSON object + */ + WarningCount.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WarningCount + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.WarningCount + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WarningCount.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.WarningCount"; + }; + + return WarningCount; + })(); + + /** + * ProcessingErrorReason enum. + * @name google.ads.datamanager.v1.ProcessingErrorReason + * @enum {number} + * @property {number} PROCESSING_ERROR_REASON_UNSPECIFIED=0 PROCESSING_ERROR_REASON_UNSPECIFIED value + * @property {number} PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE=1 PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE value + * @property {number} PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED=2 PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED value + * @property {number} PROCESSING_ERROR_REASON_EVENT_TOO_OLD=3 PROCESSING_ERROR_REASON_EVENT_TOO_OLD value + * @property {number} PROCESSING_ERROR_REASON_DENIED_CONSENT=4 PROCESSING_ERROR_REASON_DENIED_CONSENT value + * @property {number} PROCESSING_ERROR_REASON_NO_CONSENT=5 PROCESSING_ERROR_REASON_NO_CONSENT value + * @property {number} PROCESSING_ERROR_REASON_UNKNOWN_CONSENT=6 PROCESSING_ERROR_REASON_UNKNOWN_CONSENT value + * @property {number} PROCESSING_ERROR_REASON_DUPLICATE_GCLID=7 PROCESSING_ERROR_REASON_DUPLICATE_GCLID value + * @property {number} PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID=8 PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID value + * @property {number} PROCESSING_ERROR_REASON_INVALID_GBRAID=9 PROCESSING_ERROR_REASON_INVALID_GBRAID value + * @property {number} PROCESSING_ERROR_REASON_INVALID_GCLID=10 PROCESSING_ERROR_REASON_INVALID_GCLID value + * @property {number} PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID=11 PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID value + * @property {number} PROCESSING_ERROR_REASON_INVALID_WBRAID=12 PROCESSING_ERROR_REASON_INVALID_WBRAID value + * @property {number} PROCESSING_ERROR_REASON_INTERNAL_ERROR=13 PROCESSING_ERROR_REASON_INTERNAL_ERROR value + * @property {number} PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED=14 PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED value + * @property {number} PROCESSING_ERROR_REASON_INVALID_EVENT=15 PROCESSING_ERROR_REASON_INVALID_EVENT value + * @property {number} PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS=16 PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS value + * @property {number} PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS=17 PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS value + * @property {number} PROCESSING_ERROR_REASON_INVALID_FORMAT=18 PROCESSING_ERROR_REASON_INVALID_FORMAT value + * @property {number} PROCESSING_ERROR_REASON_DECRYPTION_ERROR=19 PROCESSING_ERROR_REASON_DECRYPTION_ERROR value + * @property {number} PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR=20 PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR value + * @property {number} PROCESSING_ERROR_REASON_INVALID_WIP=21 PROCESSING_ERROR_REASON_INVALID_WIP value + * @property {number} PROCESSING_ERROR_REASON_INVALID_KEK=22 PROCESSING_ERROR_REASON_INVALID_KEK value + * @property {number} PROCESSING_ERROR_REASON_WIP_AUTH_FAILED=23 PROCESSING_ERROR_REASON_WIP_AUTH_FAILED value + * @property {number} PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED=24 PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED value + * @property {number} PROCESSING_ERROR_REASON_AWS_AUTH_FAILED=27 PROCESSING_ERROR_REASON_AWS_AUTH_FAILED value + * @property {number} PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR=25 PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR value + * @property {number} PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER=26 PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER value + */ + v1.ProcessingErrorReason = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "PROCESSING_ERROR_REASON_UNSPECIFIED"] = 0; + values[valuesById[1] = "PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE"] = 1; + values[valuesById[2] = "PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED"] = 2; + values[valuesById[3] = "PROCESSING_ERROR_REASON_EVENT_TOO_OLD"] = 3; + values[valuesById[4] = "PROCESSING_ERROR_REASON_DENIED_CONSENT"] = 4; + values[valuesById[5] = "PROCESSING_ERROR_REASON_NO_CONSENT"] = 5; + values[valuesById[6] = "PROCESSING_ERROR_REASON_UNKNOWN_CONSENT"] = 6; + values[valuesById[7] = "PROCESSING_ERROR_REASON_DUPLICATE_GCLID"] = 7; + values[valuesById[8] = "PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID"] = 8; + values[valuesById[9] = "PROCESSING_ERROR_REASON_INVALID_GBRAID"] = 9; + values[valuesById[10] = "PROCESSING_ERROR_REASON_INVALID_GCLID"] = 10; + values[valuesById[11] = "PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID"] = 11; + values[valuesById[12] = "PROCESSING_ERROR_REASON_INVALID_WBRAID"] = 12; + values[valuesById[13] = "PROCESSING_ERROR_REASON_INTERNAL_ERROR"] = 13; + values[valuesById[14] = "PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED"] = 14; + values[valuesById[15] = "PROCESSING_ERROR_REASON_INVALID_EVENT"] = 15; + values[valuesById[16] = "PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS"] = 16; + values[valuesById[17] = "PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS"] = 17; + values[valuesById[18] = "PROCESSING_ERROR_REASON_INVALID_FORMAT"] = 18; + values[valuesById[19] = "PROCESSING_ERROR_REASON_DECRYPTION_ERROR"] = 19; + values[valuesById[20] = "PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR"] = 20; + values[valuesById[21] = "PROCESSING_ERROR_REASON_INVALID_WIP"] = 21; + values[valuesById[22] = "PROCESSING_ERROR_REASON_INVALID_KEK"] = 22; + values[valuesById[23] = "PROCESSING_ERROR_REASON_WIP_AUTH_FAILED"] = 23; + values[valuesById[24] = "PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED"] = 24; + values[valuesById[27] = "PROCESSING_ERROR_REASON_AWS_AUTH_FAILED"] = 27; + values[valuesById[25] = "PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR"] = 25; + values[valuesById[26] = "PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER"] = 26; + return values; + })(); + + /** + * ProcessingWarningReason enum. + * @name google.ads.datamanager.v1.ProcessingWarningReason + * @enum {number} + * @property {number} PROCESSING_WARNING_REASON_UNSPECIFIED=0 PROCESSING_WARNING_REASON_UNSPECIFIED value + * @property {number} PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED=1 PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED value + * @property {number} PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR=2 PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR value + * @property {number} PROCESSING_WARNING_REASON_DECRYPTION_ERROR=3 PROCESSING_WARNING_REASON_DECRYPTION_ERROR value + * @property {number} PROCESSING_WARNING_REASON_WIP_AUTH_FAILED=4 PROCESSING_WARNING_REASON_WIP_AUTH_FAILED value + * @property {number} PROCESSING_WARNING_REASON_INVALID_WIP=5 PROCESSING_WARNING_REASON_INVALID_WIP value + * @property {number} PROCESSING_WARNING_REASON_INVALID_KEK=6 PROCESSING_WARNING_REASON_INVALID_KEK value + * @property {number} PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR=7 PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR value + * @property {number} PROCESSING_WARNING_REASON_INTERNAL_ERROR=8 PROCESSING_WARNING_REASON_INTERNAL_ERROR value + * @property {number} PROCESSING_WARNING_REASON_AWS_AUTH_FAILED=9 PROCESSING_WARNING_REASON_AWS_AUTH_FAILED value + */ + v1.ProcessingWarningReason = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "PROCESSING_WARNING_REASON_UNSPECIFIED"] = 0; + values[valuesById[1] = "PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED"] = 1; + values[valuesById[2] = "PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR"] = 2; + values[valuesById[3] = "PROCESSING_WARNING_REASON_DECRYPTION_ERROR"] = 3; + values[valuesById[4] = "PROCESSING_WARNING_REASON_WIP_AUTH_FAILED"] = 4; + values[valuesById[5] = "PROCESSING_WARNING_REASON_INVALID_WIP"] = 5; + values[valuesById[6] = "PROCESSING_WARNING_REASON_INVALID_KEK"] = 6; + values[valuesById[7] = "PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR"] = 7; + values[valuesById[8] = "PROCESSING_WARNING_REASON_INTERNAL_ERROR"] = 8; + values[valuesById[9] = "PROCESSING_WARNING_REASON_AWS_AUTH_FAILED"] = 9; + return values; + })(); + + v1.TermsOfService = (function() { + + /** + * Properties of a TermsOfService. + * @memberof google.ads.datamanager.v1 + * @interface ITermsOfService + * @property {google.ads.datamanager.v1.TermsOfServiceStatus|null} [customerMatchTermsOfServiceStatus] TermsOfService customerMatchTermsOfServiceStatus + */ + + /** + * Constructs a new TermsOfService. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a TermsOfService. + * @implements ITermsOfService + * @constructor + * @param {google.ads.datamanager.v1.ITermsOfService=} [properties] Properties to set + */ + function TermsOfService(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TermsOfService customerMatchTermsOfServiceStatus. + * @member {google.ads.datamanager.v1.TermsOfServiceStatus} customerMatchTermsOfServiceStatus + * @memberof google.ads.datamanager.v1.TermsOfService + * @instance + */ + TermsOfService.prototype.customerMatchTermsOfServiceStatus = 0; + + /** + * Creates a new TermsOfService instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {google.ads.datamanager.v1.ITermsOfService=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.TermsOfService} TermsOfService instance + */ + TermsOfService.create = function create(properties) { + return new TermsOfService(properties); + }; + + /** + * Encodes the specified TermsOfService message. Does not implicitly {@link google.ads.datamanager.v1.TermsOfService.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {google.ads.datamanager.v1.ITermsOfService} message TermsOfService message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TermsOfService.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.customerMatchTermsOfServiceStatus != null && Object.hasOwnProperty.call(message, "customerMatchTermsOfServiceStatus")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.customerMatchTermsOfServiceStatus); + return writer; + }; + + /** + * Encodes the specified TermsOfService message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.TermsOfService.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {google.ads.datamanager.v1.ITermsOfService} message TermsOfService message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TermsOfService.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TermsOfService message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.TermsOfService} TermsOfService + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TermsOfService.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.ads.datamanager.v1.TermsOfService(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.customerMatchTermsOfServiceStatus = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TermsOfService message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.TermsOfService} TermsOfService + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TermsOfService.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TermsOfService message. + * @function verify + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TermsOfService.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.customerMatchTermsOfServiceStatus != null && message.hasOwnProperty("customerMatchTermsOfServiceStatus")) + switch (message.customerMatchTermsOfServiceStatus) { + default: + return "customerMatchTermsOfServiceStatus: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates a TermsOfService message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.TermsOfService} TermsOfService + */ + TermsOfService.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.TermsOfService) + return object; + var message = new $root.google.ads.datamanager.v1.TermsOfService(); + switch (object.customerMatchTermsOfServiceStatus) { + default: + if (typeof object.customerMatchTermsOfServiceStatus === "number") { + message.customerMatchTermsOfServiceStatus = object.customerMatchTermsOfServiceStatus; + break; + } + break; + case "TERMS_OF_SERVICE_STATUS_UNSPECIFIED": + case 0: + message.customerMatchTermsOfServiceStatus = 0; + break; + case "ACCEPTED": + case 1: + message.customerMatchTermsOfServiceStatus = 1; + break; + case "REJECTED": + case 2: + message.customerMatchTermsOfServiceStatus = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from a TermsOfService message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {google.ads.datamanager.v1.TermsOfService} message TermsOfService + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TermsOfService.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.customerMatchTermsOfServiceStatus = options.enums === String ? "TERMS_OF_SERVICE_STATUS_UNSPECIFIED" : 0; + if (message.customerMatchTermsOfServiceStatus != null && message.hasOwnProperty("customerMatchTermsOfServiceStatus")) + object.customerMatchTermsOfServiceStatus = options.enums === String ? $root.google.ads.datamanager.v1.TermsOfServiceStatus[message.customerMatchTermsOfServiceStatus] === undefined ? message.customerMatchTermsOfServiceStatus : $root.google.ads.datamanager.v1.TermsOfServiceStatus[message.customerMatchTermsOfServiceStatus] : message.customerMatchTermsOfServiceStatus; + return object; + }; + + /** + * Converts this TermsOfService to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.TermsOfService + * @instance + * @returns {Object.} JSON object + */ + TermsOfService.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TermsOfService + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.TermsOfService + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TermsOfService.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.TermsOfService"; + }; + + return TermsOfService; + })(); + + /** + * TermsOfServiceStatus enum. + * @name google.ads.datamanager.v1.TermsOfServiceStatus + * @enum {number} + * @property {number} TERMS_OF_SERVICE_STATUS_UNSPECIFIED=0 TERMS_OF_SERVICE_STATUS_UNSPECIFIED value + * @property {number} ACCEPTED=1 ACCEPTED value + * @property {number} REJECTED=2 REJECTED value + */ + v1.TermsOfServiceStatus = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TERMS_OF_SERVICE_STATUS_UNSPECIFIED"] = 0; + values[valuesById[1] = "ACCEPTED"] = 1; + values[valuesById[2] = "REJECTED"] = 2; + return values; + })(); + + v1.MarketingDataInsightsService = (function() { + + /** + * Constructs a new MarketingDataInsightsService service. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a MarketingDataInsightsService + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function MarketingDataInsightsService(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (MarketingDataInsightsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = MarketingDataInsightsService; + + /** + * Creates new MarketingDataInsightsService service using the specified rpc implementation. + * @function create + * @memberof google.ads.datamanager.v1.MarketingDataInsightsService + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {MarketingDataInsightsService} RPC service. Useful where requests and/or responses are streamed. + */ + MarketingDataInsightsService.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.ads.datamanager.v1.MarketingDataInsightsService|retrieveInsights}. + * @memberof google.ads.datamanager.v1.MarketingDataInsightsService + * @typedef RetrieveInsightsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse} [response] RetrieveInsightsResponse + */ + + /** + * Calls RetrieveInsights. + * @function retrieveInsights + * @memberof google.ads.datamanager.v1.MarketingDataInsightsService + * @instance + * @param {google.ads.datamanager.v1.IRetrieveInsightsRequest} request RetrieveInsightsRequest message or plain object + * @param {google.ads.datamanager.v1.MarketingDataInsightsService.RetrieveInsightsCallback} callback Node-style callback called with the error, if any, and RetrieveInsightsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(MarketingDataInsightsService.prototype.retrieveInsights = function retrieveInsights(request, callback) { + return this.rpcCall(retrieveInsights, $root.google.ads.datamanager.v1.RetrieveInsightsRequest, $root.google.ads.datamanager.v1.RetrieveInsightsResponse, request, callback); + }, "name", { value: "RetrieveInsights" }); + + /** + * Calls RetrieveInsights. + * @function retrieveInsights + * @memberof google.ads.datamanager.v1.MarketingDataInsightsService + * @instance + * @param {google.ads.datamanager.v1.IRetrieveInsightsRequest} request RetrieveInsightsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return MarketingDataInsightsService; + })(); + + v1.RetrieveInsightsRequest = (function() { + + /** + * Properties of a RetrieveInsightsRequest. + * @memberof google.ads.datamanager.v1 + * @interface IRetrieveInsightsRequest + * @property {string|null} [parent] RetrieveInsightsRequest parent + * @property {google.ads.datamanager.v1.IBaseline|null} [baseline] RetrieveInsightsRequest baseline + * @property {string|null} [userListId] RetrieveInsightsRequest userListId + */ + + /** + * Constructs a new RetrieveInsightsRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a RetrieveInsightsRequest. + * @implements IRetrieveInsightsRequest + * @constructor + * @param {google.ads.datamanager.v1.IRetrieveInsightsRequest=} [properties] Properties to set + */ + function RetrieveInsightsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RetrieveInsightsRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @instance + */ + RetrieveInsightsRequest.prototype.parent = ""; + + /** + * RetrieveInsightsRequest baseline. + * @member {google.ads.datamanager.v1.IBaseline|null|undefined} baseline + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @instance + */ + RetrieveInsightsRequest.prototype.baseline = null; + + /** + * RetrieveInsightsRequest userListId. + * @member {string} userListId + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @instance + */ + RetrieveInsightsRequest.prototype.userListId = ""; + + /** + * Creates a new RetrieveInsightsRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {google.ads.datamanager.v1.IRetrieveInsightsRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.RetrieveInsightsRequest} RetrieveInsightsRequest instance + */ + RetrieveInsightsRequest.create = function create(properties) { + return new RetrieveInsightsRequest(properties); + }; + + /** + * Encodes the specified RetrieveInsightsRequest message. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {google.ads.datamanager.v1.IRetrieveInsightsRequest} message RetrieveInsightsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RetrieveInsightsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.baseline != null && Object.hasOwnProperty.call(message, "baseline")) + $root.google.ads.datamanager.v1.Baseline.encode(message.baseline, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.userListId != null && Object.hasOwnProperty.call(message, "userListId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.userListId); + return writer; + }; + + /** + * Encodes the specified RetrieveInsightsRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {google.ads.datamanager.v1.IRetrieveInsightsRequest} message RetrieveInsightsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RetrieveInsightsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RetrieveInsightsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.RetrieveInsightsRequest} RetrieveInsightsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RetrieveInsightsRequest.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.ads.datamanager.v1.RetrieveInsightsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.baseline = $root.google.ads.datamanager.v1.Baseline.decode(reader, reader.uint32()); + break; + } + case 3: { + message.userListId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RetrieveInsightsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.RetrieveInsightsRequest} RetrieveInsightsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RetrieveInsightsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RetrieveInsightsRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RetrieveInsightsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.baseline != null && message.hasOwnProperty("baseline")) { + var error = $root.google.ads.datamanager.v1.Baseline.verify(message.baseline); + if (error) + return "baseline." + error; + } + if (message.userListId != null && message.hasOwnProperty("userListId")) + if (!$util.isString(message.userListId)) + return "userListId: string expected"; + return null; + }; + + /** + * Creates a RetrieveInsightsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.RetrieveInsightsRequest} RetrieveInsightsRequest + */ + RetrieveInsightsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.RetrieveInsightsRequest) + return object; + var message = new $root.google.ads.datamanager.v1.RetrieveInsightsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.baseline != null) { + if (typeof object.baseline !== "object") + throw TypeError(".google.ads.datamanager.v1.RetrieveInsightsRequest.baseline: object expected"); + message.baseline = $root.google.ads.datamanager.v1.Baseline.fromObject(object.baseline); + } + if (object.userListId != null) + message.userListId = String(object.userListId); + return message; + }; + + /** + * Creates a plain object from a RetrieveInsightsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsRequest} message RetrieveInsightsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RetrieveInsightsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.baseline = null; + object.userListId = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.baseline != null && message.hasOwnProperty("baseline")) + object.baseline = $root.google.ads.datamanager.v1.Baseline.toObject(message.baseline, options); + if (message.userListId != null && message.hasOwnProperty("userListId")) + object.userListId = message.userListId; + return object; + }; + + /** + * Converts this RetrieveInsightsRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @instance + * @returns {Object.} JSON object + */ + RetrieveInsightsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RetrieveInsightsRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.RetrieveInsightsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RetrieveInsightsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.RetrieveInsightsRequest"; + }; + + return RetrieveInsightsRequest; + })(); + + v1.Baseline = (function() { + + /** + * Properties of a Baseline. + * @memberof google.ads.datamanager.v1 + * @interface IBaseline + * @property {google.ads.datamanager.v1.Baseline.ILocation|null} [baselineLocation] Baseline baselineLocation + * @property {boolean|null} [locationAutoDetectionEnabled] Baseline locationAutoDetectionEnabled + */ + + /** + * Constructs a new Baseline. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a Baseline. + * @implements IBaseline + * @constructor + * @param {google.ads.datamanager.v1.IBaseline=} [properties] Properties to set + */ + function Baseline(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Baseline baselineLocation. + * @member {google.ads.datamanager.v1.Baseline.ILocation|null|undefined} baselineLocation + * @memberof google.ads.datamanager.v1.Baseline + * @instance + */ + Baseline.prototype.baselineLocation = null; + + /** + * Baseline locationAutoDetectionEnabled. + * @member {boolean|null|undefined} locationAutoDetectionEnabled + * @memberof google.ads.datamanager.v1.Baseline + * @instance + */ + Baseline.prototype.locationAutoDetectionEnabled = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Baseline baseline. + * @member {"baselineLocation"|"locationAutoDetectionEnabled"|undefined} baseline + * @memberof google.ads.datamanager.v1.Baseline + * @instance + */ + Object.defineProperty(Baseline.prototype, "baseline", { + get: $util.oneOfGetter($oneOfFields = ["baselineLocation", "locationAutoDetectionEnabled"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new Baseline instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {google.ads.datamanager.v1.IBaseline=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.Baseline} Baseline instance + */ + Baseline.create = function create(properties) { + return new Baseline(properties); + }; + + /** + * Encodes the specified Baseline message. Does not implicitly {@link google.ads.datamanager.v1.Baseline.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {google.ads.datamanager.v1.IBaseline} message Baseline message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Baseline.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.baselineLocation != null && Object.hasOwnProperty.call(message, "baselineLocation")) + $root.google.ads.datamanager.v1.Baseline.Location.encode(message.baselineLocation, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.locationAutoDetectionEnabled != null && Object.hasOwnProperty.call(message, "locationAutoDetectionEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.locationAutoDetectionEnabled); + return writer; + }; + + /** + * Encodes the specified Baseline message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.Baseline.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {google.ads.datamanager.v1.IBaseline} message Baseline message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Baseline.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Baseline message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.Baseline} Baseline + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Baseline.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.ads.datamanager.v1.Baseline(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.baselineLocation = $root.google.ads.datamanager.v1.Baseline.Location.decode(reader, reader.uint32()); + break; + } + case 2: { + message.locationAutoDetectionEnabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Baseline message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.Baseline} Baseline + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Baseline.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Baseline message. + * @function verify + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Baseline.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.baselineLocation != null && message.hasOwnProperty("baselineLocation")) { + properties.baseline = 1; + { + var error = $root.google.ads.datamanager.v1.Baseline.Location.verify(message.baselineLocation); + if (error) + return "baselineLocation." + error; + } + } + if (message.locationAutoDetectionEnabled != null && message.hasOwnProperty("locationAutoDetectionEnabled")) { + if (properties.baseline === 1) + return "baseline: multiple values"; + properties.baseline = 1; + if (typeof message.locationAutoDetectionEnabled !== "boolean") + return "locationAutoDetectionEnabled: boolean expected"; + } + return null; + }; + + /** + * Creates a Baseline message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.Baseline} Baseline + */ + Baseline.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.Baseline) + return object; + var message = new $root.google.ads.datamanager.v1.Baseline(); + if (object.baselineLocation != null) { + if (typeof object.baselineLocation !== "object") + throw TypeError(".google.ads.datamanager.v1.Baseline.baselineLocation: object expected"); + message.baselineLocation = $root.google.ads.datamanager.v1.Baseline.Location.fromObject(object.baselineLocation); + } + if (object.locationAutoDetectionEnabled != null) + message.locationAutoDetectionEnabled = Boolean(object.locationAutoDetectionEnabled); + return message; + }; + + /** + * Creates a plain object from a Baseline message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {google.ads.datamanager.v1.Baseline} message Baseline + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Baseline.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.baselineLocation != null && message.hasOwnProperty("baselineLocation")) { + object.baselineLocation = $root.google.ads.datamanager.v1.Baseline.Location.toObject(message.baselineLocation, options); + if (options.oneofs) + object.baseline = "baselineLocation"; + } + if (message.locationAutoDetectionEnabled != null && message.hasOwnProperty("locationAutoDetectionEnabled")) { + object.locationAutoDetectionEnabled = message.locationAutoDetectionEnabled; + if (options.oneofs) + object.baseline = "locationAutoDetectionEnabled"; + } + return object; + }; + + /** + * Converts this Baseline to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.Baseline + * @instance + * @returns {Object.} JSON object + */ + Baseline.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Baseline + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.Baseline + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Baseline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.Baseline"; + }; + + Baseline.Location = (function() { + + /** + * Properties of a Location. + * @memberof google.ads.datamanager.v1.Baseline + * @interface ILocation + * @property {Array.|null} [regionCodes] Location regionCodes + */ + + /** + * Constructs a new Location. + * @memberof google.ads.datamanager.v1.Baseline + * @classdesc Represents a Location. + * @implements ILocation + * @constructor + * @param {google.ads.datamanager.v1.Baseline.ILocation=} [properties] Properties to set + */ + function Location(properties) { + this.regionCodes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Location regionCodes. + * @member {Array.} regionCodes + * @memberof google.ads.datamanager.v1.Baseline.Location + * @instance + */ + Location.prototype.regionCodes = $util.emptyArray; + + /** + * Creates a new Location instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {google.ads.datamanager.v1.Baseline.ILocation=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.Baseline.Location} Location instance + */ + Location.create = function create(properties) { + return new Location(properties); + }; + + /** + * Encodes the specified Location message. Does not implicitly {@link google.ads.datamanager.v1.Baseline.Location.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {google.ads.datamanager.v1.Baseline.ILocation} message Location message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Location.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.regionCodes != null && message.regionCodes.length) + for (var i = 0; i < message.regionCodes.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.regionCodes[i]); + return writer; + }; + + /** + * Encodes the specified Location message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.Baseline.Location.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {google.ads.datamanager.v1.Baseline.ILocation} message Location message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Location.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Location message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.Baseline.Location} Location + * @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, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.ads.datamanager.v1.Baseline.Location(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.regionCodes && message.regionCodes.length)) + message.regionCodes = []; + message.regionCodes.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a Location message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.Baseline.Location} Location + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Location.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Location message. + * @function verify + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Location.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.regionCodes != null && message.hasOwnProperty("regionCodes")) { + if (!Array.isArray(message.regionCodes)) + return "regionCodes: array expected"; + for (var i = 0; i < message.regionCodes.length; ++i) + if (!$util.isString(message.regionCodes[i])) + return "regionCodes: string[] expected"; + } + return null; + }; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.Baseline.Location} Location + */ + Location.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.Baseline.Location) + return object; + var message = new $root.google.ads.datamanager.v1.Baseline.Location(); + if (object.regionCodes) { + if (!Array.isArray(object.regionCodes)) + throw TypeError(".google.ads.datamanager.v1.Baseline.Location.regionCodes: array expected"); + message.regionCodes = []; + for (var i = 0; i < object.regionCodes.length; ++i) + message.regionCodes[i] = String(object.regionCodes[i]); + } + return message; + }; + + /** + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {google.ads.datamanager.v1.Baseline.Location} message Location + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Location.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.regionCodes = []; + if (message.regionCodes && message.regionCodes.length) { + object.regionCodes = []; + for (var j = 0; j < message.regionCodes.length; ++j) + object.regionCodes[j] = message.regionCodes[j]; + } + return object; + }; + + /** + * Converts this Location to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.Baseline.Location + * @instance + * @returns {Object.} JSON object + */ + Location.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Location + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.Baseline.Location + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Location.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.Baseline.Location"; + }; + + return Location; + })(); + + return Baseline; + })(); + + v1.RetrieveInsightsResponse = (function() { + + /** + * Properties of a RetrieveInsightsResponse. + * @memberof google.ads.datamanager.v1 + * @interface IRetrieveInsightsResponse + * @property {Array.|null} [marketingDataInsights] RetrieveInsightsResponse marketingDataInsights + */ + + /** + * Constructs a new RetrieveInsightsResponse. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a RetrieveInsightsResponse. + * @implements IRetrieveInsightsResponse + * @constructor + * @param {google.ads.datamanager.v1.IRetrieveInsightsResponse=} [properties] Properties to set + */ + function RetrieveInsightsResponse(properties) { + this.marketingDataInsights = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RetrieveInsightsResponse marketingDataInsights. + * @member {Array.} marketingDataInsights + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @instance + */ + RetrieveInsightsResponse.prototype.marketingDataInsights = $util.emptyArray; + + /** + * Creates a new RetrieveInsightsResponse instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {google.ads.datamanager.v1.IRetrieveInsightsResponse=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse} RetrieveInsightsResponse instance + */ + RetrieveInsightsResponse.create = function create(properties) { + return new RetrieveInsightsResponse(properties); + }; + + /** + * Encodes the specified RetrieveInsightsResponse message. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {google.ads.datamanager.v1.IRetrieveInsightsResponse} message RetrieveInsightsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RetrieveInsightsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.marketingDataInsights != null && message.marketingDataInsights.length) + for (var i = 0; i < message.marketingDataInsights.length; ++i) + $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.encode(message.marketingDataInsights[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RetrieveInsightsResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {google.ads.datamanager.v1.IRetrieveInsightsResponse} message RetrieveInsightsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RetrieveInsightsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RetrieveInsightsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse} RetrieveInsightsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RetrieveInsightsResponse.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.ads.datamanager.v1.RetrieveInsightsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.marketingDataInsights && message.marketingDataInsights.length)) + message.marketingDataInsights = []; + message.marketingDataInsights.push($root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RetrieveInsightsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse} RetrieveInsightsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RetrieveInsightsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RetrieveInsightsResponse message. + * @function verify + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RetrieveInsightsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.marketingDataInsights != null && message.hasOwnProperty("marketingDataInsights")) { + if (!Array.isArray(message.marketingDataInsights)) + return "marketingDataInsights: array expected"; + for (var i = 0; i < message.marketingDataInsights.length; ++i) { + var error = $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.verify(message.marketingDataInsights[i]); + if (error) + return "marketingDataInsights." + error; + } + } + return null; + }; + + /** + * Creates a RetrieveInsightsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse} RetrieveInsightsResponse + */ + RetrieveInsightsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.RetrieveInsightsResponse) + return object; + var message = new $root.google.ads.datamanager.v1.RetrieveInsightsResponse(); + if (object.marketingDataInsights) { + if (!Array.isArray(object.marketingDataInsights)) + throw TypeError(".google.ads.datamanager.v1.RetrieveInsightsResponse.marketingDataInsights: array expected"); + message.marketingDataInsights = []; + for (var i = 0; i < object.marketingDataInsights.length; ++i) { + if (typeof object.marketingDataInsights[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.RetrieveInsightsResponse.marketingDataInsights: object expected"); + message.marketingDataInsights[i] = $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.fromObject(object.marketingDataInsights[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a RetrieveInsightsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse} message RetrieveInsightsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RetrieveInsightsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.marketingDataInsights = []; + if (message.marketingDataInsights && message.marketingDataInsights.length) { + object.marketingDataInsights = []; + for (var j = 0; j < message.marketingDataInsights.length; ++j) + object.marketingDataInsights[j] = $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.toObject(message.marketingDataInsights[j], options); + } + return object; + }; + + /** + * Converts this RetrieveInsightsResponse to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @instance + * @returns {Object.} JSON object + */ + RetrieveInsightsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RetrieveInsightsResponse + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RetrieveInsightsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.RetrieveInsightsResponse"; + }; + + RetrieveInsightsResponse.MarketingDataInsight = (function() { + + /** + * Properties of a MarketingDataInsight. + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @interface IMarketingDataInsight + * @property {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension|null} [dimension] MarketingDataInsight dimension + * @property {Array.|null} [attributes] MarketingDataInsight attributes + */ + + /** + * Constructs a new MarketingDataInsight. + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse + * @classdesc Represents a MarketingDataInsight. + * @implements IMarketingDataInsight + * @constructor + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight=} [properties] Properties to set + */ + function MarketingDataInsight(properties) { + this.attributes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MarketingDataInsight dimension. + * @member {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension} dimension + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @instance + */ + MarketingDataInsight.prototype.dimension = 0; + + /** + * MarketingDataInsight attributes. + * @member {Array.} attributes + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @instance + */ + MarketingDataInsight.prototype.attributes = $util.emptyArray; + + /** + * Creates a new MarketingDataInsight instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight} MarketingDataInsight instance + */ + MarketingDataInsight.create = function create(properties) { + return new MarketingDataInsight(properties); + }; + + /** + * Encodes the specified MarketingDataInsight message. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight} message MarketingDataInsight message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MarketingDataInsight.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dimension != null && Object.hasOwnProperty.call(message, "dimension")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.dimension); + if (message.attributes != null && message.attributes.length) + for (var i = 0; i < message.attributes.length; ++i) + $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.encode(message.attributes[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified MarketingDataInsight message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.IMarketingDataInsight} message MarketingDataInsight message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MarketingDataInsight.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MarketingDataInsight message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight} MarketingDataInsight + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MarketingDataInsight.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.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.dimension = reader.int32(); + break; + } + case 2: { + if (!(message.attributes && message.attributes.length)) + message.attributes = []; + message.attributes.push($root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.decode(reader, reader.uint32())); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MarketingDataInsight message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight} MarketingDataInsight + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MarketingDataInsight.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MarketingDataInsight message. + * @function verify + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MarketingDataInsight.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.dimension != null && message.hasOwnProperty("dimension")) + switch (message.dimension) { + default: + return "dimension: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + break; + } + if (message.attributes != null && message.hasOwnProperty("attributes")) { + if (!Array.isArray(message.attributes)) + return "attributes: array expected"; + for (var i = 0; i < message.attributes.length; ++i) { + var error = $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.verify(message.attributes[i]); + if (error) + return "attributes." + error; + } + } + return null; + }; + + /** + * Creates a MarketingDataInsight message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight} MarketingDataInsight + */ + MarketingDataInsight.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight) + return object; + var message = new $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight(); + switch (object.dimension) { + default: + if (typeof object.dimension === "number") { + message.dimension = object.dimension; + break; + } + break; + case "AUDIENCE_INSIGHTS_DIMENSION_UNSPECIFIED": + case 0: + message.dimension = 0; + break; + case "AUDIENCE_INSIGHTS_DIMENSION_UNKNOWN": + case 1: + message.dimension = 1; + break; + case "AFFINITY_USER_INTEREST": + case 2: + message.dimension = 2; + break; + case "IN_MARKET_USER_INTEREST": + case 3: + message.dimension = 3; + break; + case "AGE_RANGE": + case 4: + message.dimension = 4; + break; + case "GENDER": + case 5: + message.dimension = 5; + break; + } + if (object.attributes) { + if (!Array.isArray(object.attributes)) + throw TypeError(".google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.attributes: array expected"); + message.attributes = []; + for (var i = 0; i < object.attributes.length; ++i) { + if (typeof object.attributes[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.attributes: object expected"); + message.attributes[i] = $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.fromObject(object.attributes[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a MarketingDataInsight message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight} message MarketingDataInsight + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MarketingDataInsight.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.attributes = []; + if (options.defaults) + object.dimension = options.enums === String ? "AUDIENCE_INSIGHTS_DIMENSION_UNSPECIFIED" : 0; + if (message.dimension != null && message.hasOwnProperty("dimension")) + object.dimension = options.enums === String ? $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension[message.dimension] === undefined ? message.dimension : $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension[message.dimension] : message.dimension; + if (message.attributes && message.attributes.length) { + object.attributes = []; + for (var j = 0; j < message.attributes.length; ++j) + object.attributes[j] = $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.toObject(message.attributes[j], options); + } + return object; + }; + + /** + * Converts this MarketingDataInsight to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @instance + * @returns {Object.} JSON object + */ + MarketingDataInsight.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MarketingDataInsight + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MarketingDataInsight.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight"; + }; + + /** + * AudienceInsightsDimension enum. + * @name google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.AudienceInsightsDimension + * @enum {number} + * @property {number} AUDIENCE_INSIGHTS_DIMENSION_UNSPECIFIED=0 AUDIENCE_INSIGHTS_DIMENSION_UNSPECIFIED value + * @property {number} AUDIENCE_INSIGHTS_DIMENSION_UNKNOWN=1 AUDIENCE_INSIGHTS_DIMENSION_UNKNOWN value + * @property {number} AFFINITY_USER_INTEREST=2 AFFINITY_USER_INTEREST value + * @property {number} IN_MARKET_USER_INTEREST=3 IN_MARKET_USER_INTEREST value + * @property {number} AGE_RANGE=4 AGE_RANGE value + * @property {number} GENDER=5 GENDER value + */ + MarketingDataInsight.AudienceInsightsDimension = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "AUDIENCE_INSIGHTS_DIMENSION_UNSPECIFIED"] = 0; + values[valuesById[1] = "AUDIENCE_INSIGHTS_DIMENSION_UNKNOWN"] = 1; + values[valuesById[2] = "AFFINITY_USER_INTEREST"] = 2; + values[valuesById[3] = "IN_MARKET_USER_INTEREST"] = 3; + values[valuesById[4] = "AGE_RANGE"] = 4; + values[valuesById[5] = "GENDER"] = 5; + return values; + })(); + + MarketingDataInsight.MarketingDataInsightsAttribute = (function() { + + /** + * Properties of a MarketingDataInsightsAttribute. + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @interface IMarketingDataInsightsAttribute + * @property {number|Long|null} [userInterestId] MarketingDataInsightsAttribute userInterestId + * @property {number|null} [lift] MarketingDataInsightsAttribute lift + * @property {google.ads.datamanager.v1.AgeRange|null} [ageRange] MarketingDataInsightsAttribute ageRange + * @property {google.ads.datamanager.v1.Gender|null} [gender] MarketingDataInsightsAttribute gender + */ + + /** + * Constructs a new MarketingDataInsightsAttribute. + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight + * @classdesc Represents a MarketingDataInsightsAttribute. + * @implements IMarketingDataInsightsAttribute + * @constructor + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute=} [properties] Properties to set + */ + function MarketingDataInsightsAttribute(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MarketingDataInsightsAttribute userInterestId. + * @member {number|Long|null|undefined} userInterestId + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @instance + */ + MarketingDataInsightsAttribute.prototype.userInterestId = null; + + /** + * MarketingDataInsightsAttribute lift. + * @member {number|null|undefined} lift + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @instance + */ + MarketingDataInsightsAttribute.prototype.lift = null; + + /** + * MarketingDataInsightsAttribute ageRange. + * @member {google.ads.datamanager.v1.AgeRange|null|undefined} ageRange + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @instance + */ + MarketingDataInsightsAttribute.prototype.ageRange = null; + + /** + * MarketingDataInsightsAttribute gender. + * @member {google.ads.datamanager.v1.Gender|null|undefined} gender + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @instance + */ + MarketingDataInsightsAttribute.prototype.gender = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(MarketingDataInsightsAttribute.prototype, "_userInterestId", { + get: $util.oneOfGetter($oneOfFields = ["userInterestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(MarketingDataInsightsAttribute.prototype, "_lift", { + get: $util.oneOfGetter($oneOfFields = ["lift"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(MarketingDataInsightsAttribute.prototype, "_ageRange", { + get: $util.oneOfGetter($oneOfFields = ["ageRange"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(MarketingDataInsightsAttribute.prototype, "_gender", { + get: $util.oneOfGetter($oneOfFields = ["gender"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new MarketingDataInsightsAttribute instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute} MarketingDataInsightsAttribute instance + */ + MarketingDataInsightsAttribute.create = function create(properties) { + return new MarketingDataInsightsAttribute(properties); + }; + + /** + * Encodes the specified MarketingDataInsightsAttribute message. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute} message MarketingDataInsightsAttribute message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MarketingDataInsightsAttribute.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userInterestId != null && Object.hasOwnProperty.call(message, "userInterestId")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.userInterestId); + if (message.lift != null && Object.hasOwnProperty.call(message, "lift")) + writer.uint32(/* id 2, wireType 5 =*/21).float(message.lift); + if (message.ageRange != null && Object.hasOwnProperty.call(message, "ageRange")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.ageRange); + if (message.gender != null && Object.hasOwnProperty.call(message, "gender")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.gender); + return writer; + }; + + /** + * Encodes the specified MarketingDataInsightsAttribute message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.IMarketingDataInsightsAttribute} message MarketingDataInsightsAttribute message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MarketingDataInsightsAttribute.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MarketingDataInsightsAttribute message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute} MarketingDataInsightsAttribute + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MarketingDataInsightsAttribute.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.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.userInterestId = reader.int64(); + break; + } + case 2: { + message.lift = reader.float(); + break; + } + case 3: { + message.ageRange = reader.int32(); + break; + } + case 4: { + message.gender = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MarketingDataInsightsAttribute message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute} MarketingDataInsightsAttribute + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MarketingDataInsightsAttribute.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MarketingDataInsightsAttribute message. + * @function verify + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MarketingDataInsightsAttribute.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.userInterestId != null && message.hasOwnProperty("userInterestId")) { + properties._userInterestId = 1; + if (!$util.isInteger(message.userInterestId) && !(message.userInterestId && $util.isInteger(message.userInterestId.low) && $util.isInteger(message.userInterestId.high))) + return "userInterestId: integer|Long expected"; + } + if (message.lift != null && message.hasOwnProperty("lift")) { + properties._lift = 1; + if (typeof message.lift !== "number") + return "lift: number expected"; + } + if (message.ageRange != null && message.hasOwnProperty("ageRange")) { + properties._ageRange = 1; + switch (message.ageRange) { + default: + return "ageRange: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + break; + } + } + if (message.gender != null && message.hasOwnProperty("gender")) { + properties._gender = 1; + switch (message.gender) { + default: + return "gender: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + } + return null; + }; + + /** + * Creates a MarketingDataInsightsAttribute message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute} MarketingDataInsightsAttribute + */ + MarketingDataInsightsAttribute.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute) + return object; + var message = new $root.google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute(); + if (object.userInterestId != null) + if ($util.Long) + (message.userInterestId = $util.Long.fromValue(object.userInterestId)).unsigned = false; + else if (typeof object.userInterestId === "string") + message.userInterestId = parseInt(object.userInterestId, 10); + else if (typeof object.userInterestId === "number") + message.userInterestId = object.userInterestId; + else if (typeof object.userInterestId === "object") + message.userInterestId = new $util.LongBits(object.userInterestId.low >>> 0, object.userInterestId.high >>> 0).toNumber(); + if (object.lift != null) + message.lift = Number(object.lift); + switch (object.ageRange) { + default: + if (typeof object.ageRange === "number") { + message.ageRange = object.ageRange; + break; + } + break; + case "AGE_RANGE_UNSPECIFIED": + case 0: + message.ageRange = 0; + break; + case "AGE_RANGE_UNKNOWN": + case 1: + message.ageRange = 1; + break; + case "AGE_RANGE_18_24": + case 2: + message.ageRange = 2; + break; + case "AGE_RANGE_25_34": + case 3: + message.ageRange = 3; + break; + case "AGE_RANGE_35_44": + case 4: + message.ageRange = 4; + break; + case "AGE_RANGE_45_54": + case 5: + message.ageRange = 5; + break; + case "AGE_RANGE_55_64": + case 6: + message.ageRange = 6; + break; + case "AGE_RANGE_65_UP": + case 7: + message.ageRange = 7; + break; + } + switch (object.gender) { + default: + if (typeof object.gender === "number") { + message.gender = object.gender; + break; + } + break; + case "GENDER_UNSPECIFIED": + case 0: + message.gender = 0; + break; + case "GENDER_UNKNOWN": + case 1: + message.gender = 1; + break; + case "GENDER_MALE": + case 2: + message.gender = 2; + break; + case "GENDER_FEMALE": + case 3: + message.gender = 3; + break; + } + return message; + }; + + /** + * Creates a plain object from a MarketingDataInsightsAttribute message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute} message MarketingDataInsightsAttribute + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MarketingDataInsightsAttribute.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.userInterestId != null && message.hasOwnProperty("userInterestId")) { + if (typeof message.userInterestId === "number") + object.userInterestId = options.longs === String ? String(message.userInterestId) : message.userInterestId; + else + object.userInterestId = options.longs === String ? $util.Long.prototype.toString.call(message.userInterestId) : options.longs === Number ? new $util.LongBits(message.userInterestId.low >>> 0, message.userInterestId.high >>> 0).toNumber() : message.userInterestId; + if (options.oneofs) + object._userInterestId = "userInterestId"; + } + if (message.lift != null && message.hasOwnProperty("lift")) { + object.lift = options.json && !isFinite(message.lift) ? String(message.lift) : message.lift; + if (options.oneofs) + object._lift = "lift"; + } + if (message.ageRange != null && message.hasOwnProperty("ageRange")) { + object.ageRange = options.enums === String ? $root.google.ads.datamanager.v1.AgeRange[message.ageRange] === undefined ? message.ageRange : $root.google.ads.datamanager.v1.AgeRange[message.ageRange] : message.ageRange; + if (options.oneofs) + object._ageRange = "ageRange"; + } + if (message.gender != null && message.hasOwnProperty("gender")) { + object.gender = options.enums === String ? $root.google.ads.datamanager.v1.Gender[message.gender] === undefined ? message.gender : $root.google.ads.datamanager.v1.Gender[message.gender] : message.gender; + if (options.oneofs) + object._gender = "gender"; + } + return object; + }; + + /** + * Converts this MarketingDataInsightsAttribute to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @instance + * @returns {Object.} JSON object + */ + MarketingDataInsightsAttribute.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MarketingDataInsightsAttribute + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MarketingDataInsightsAttribute.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.RetrieveInsightsResponse.MarketingDataInsight.MarketingDataInsightsAttribute"; + }; + + return MarketingDataInsightsAttribute; + })(); + + return MarketingDataInsight; + })(); + + return RetrieveInsightsResponse; + })(); + + v1.PartnerLinkService = (function() { + + /** + * Constructs a new PartnerLinkService service. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a PartnerLinkService + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function PartnerLinkService(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (PartnerLinkService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = PartnerLinkService; + + /** + * Creates new PartnerLinkService service using the specified rpc implementation. + * @function create + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {PartnerLinkService} RPC service. Useful where requests and/or responses are streamed. + */ + PartnerLinkService.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.ads.datamanager.v1.PartnerLinkService|createPartnerLink}. + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @typedef CreatePartnerLinkCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.PartnerLink} [response] PartnerLink + */ + + /** + * Calls CreatePartnerLink. + * @function createPartnerLink + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @instance + * @param {google.ads.datamanager.v1.ICreatePartnerLinkRequest} request CreatePartnerLinkRequest message or plain object + * @param {google.ads.datamanager.v1.PartnerLinkService.CreatePartnerLinkCallback} callback Node-style callback called with the error, if any, and PartnerLink + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(PartnerLinkService.prototype.createPartnerLink = function createPartnerLink(request, callback) { + return this.rpcCall(createPartnerLink, $root.google.ads.datamanager.v1.CreatePartnerLinkRequest, $root.google.ads.datamanager.v1.PartnerLink, request, callback); + }, "name", { value: "CreatePartnerLink" }); + + /** + * Calls CreatePartnerLink. + * @function createPartnerLink + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @instance + * @param {google.ads.datamanager.v1.ICreatePartnerLinkRequest} request CreatePartnerLinkRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.PartnerLinkService|deletePartnerLink}. + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @typedef DeletePartnerLinkCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeletePartnerLink. + * @function deletePartnerLink + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @instance + * @param {google.ads.datamanager.v1.IDeletePartnerLinkRequest} request DeletePartnerLinkRequest message or plain object + * @param {google.ads.datamanager.v1.PartnerLinkService.DeletePartnerLinkCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(PartnerLinkService.prototype.deletePartnerLink = function deletePartnerLink(request, callback) { + return this.rpcCall(deletePartnerLink, $root.google.ads.datamanager.v1.DeletePartnerLinkRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeletePartnerLink" }); + + /** + * Calls DeletePartnerLink. + * @function deletePartnerLink + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @instance + * @param {google.ads.datamanager.v1.IDeletePartnerLinkRequest} request DeletePartnerLinkRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.PartnerLinkService|searchPartnerLinks}. + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @typedef SearchPartnerLinksCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.SearchPartnerLinksResponse} [response] SearchPartnerLinksResponse + */ + + /** + * Calls SearchPartnerLinks. + * @function searchPartnerLinks + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @instance + * @param {google.ads.datamanager.v1.ISearchPartnerLinksRequest} request SearchPartnerLinksRequest message or plain object + * @param {google.ads.datamanager.v1.PartnerLinkService.SearchPartnerLinksCallback} callback Node-style callback called with the error, if any, and SearchPartnerLinksResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(PartnerLinkService.prototype.searchPartnerLinks = function searchPartnerLinks(request, callback) { + return this.rpcCall(searchPartnerLinks, $root.google.ads.datamanager.v1.SearchPartnerLinksRequest, $root.google.ads.datamanager.v1.SearchPartnerLinksResponse, request, callback); + }, "name", { value: "SearchPartnerLinks" }); + + /** + * Calls SearchPartnerLinks. + * @function searchPartnerLinks + * @memberof google.ads.datamanager.v1.PartnerLinkService + * @instance + * @param {google.ads.datamanager.v1.ISearchPartnerLinksRequest} request SearchPartnerLinksRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return PartnerLinkService; + })(); + + v1.CreatePartnerLinkRequest = (function() { + + /** + * Properties of a CreatePartnerLinkRequest. + * @memberof google.ads.datamanager.v1 + * @interface ICreatePartnerLinkRequest + * @property {string|null} [parent] CreatePartnerLinkRequest parent + * @property {google.ads.datamanager.v1.IPartnerLink|null} [partnerLink] CreatePartnerLinkRequest partnerLink + */ + + /** + * Constructs a new CreatePartnerLinkRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a CreatePartnerLinkRequest. + * @implements ICreatePartnerLinkRequest + * @constructor + * @param {google.ads.datamanager.v1.ICreatePartnerLinkRequest=} [properties] Properties to set + */ + function CreatePartnerLinkRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreatePartnerLinkRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @instance + */ + CreatePartnerLinkRequest.prototype.parent = ""; + + /** + * CreatePartnerLinkRequest partnerLink. + * @member {google.ads.datamanager.v1.IPartnerLink|null|undefined} partnerLink + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @instance + */ + CreatePartnerLinkRequest.prototype.partnerLink = null; + + /** + * Creates a new CreatePartnerLinkRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {google.ads.datamanager.v1.ICreatePartnerLinkRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.CreatePartnerLinkRequest} CreatePartnerLinkRequest instance + */ + CreatePartnerLinkRequest.create = function create(properties) { + return new CreatePartnerLinkRequest(properties); + }; + + /** + * Encodes the specified CreatePartnerLinkRequest message. Does not implicitly {@link google.ads.datamanager.v1.CreatePartnerLinkRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {google.ads.datamanager.v1.ICreatePartnerLinkRequest} message CreatePartnerLinkRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreatePartnerLinkRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.partnerLink != null && Object.hasOwnProperty.call(message, "partnerLink")) + $root.google.ads.datamanager.v1.PartnerLink.encode(message.partnerLink, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreatePartnerLinkRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.CreatePartnerLinkRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {google.ads.datamanager.v1.ICreatePartnerLinkRequest} message CreatePartnerLinkRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreatePartnerLinkRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreatePartnerLinkRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.CreatePartnerLinkRequest} CreatePartnerLinkRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreatePartnerLinkRequest.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.ads.datamanager.v1.CreatePartnerLinkRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.partnerLink = $root.google.ads.datamanager.v1.PartnerLink.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreatePartnerLinkRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.CreatePartnerLinkRequest} CreatePartnerLinkRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreatePartnerLinkRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreatePartnerLinkRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreatePartnerLinkRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.partnerLink != null && message.hasOwnProperty("partnerLink")) { + var error = $root.google.ads.datamanager.v1.PartnerLink.verify(message.partnerLink); + if (error) + return "partnerLink." + error; + } + return null; + }; + + /** + * Creates a CreatePartnerLinkRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.CreatePartnerLinkRequest} CreatePartnerLinkRequest + */ + CreatePartnerLinkRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.CreatePartnerLinkRequest) + return object; + var message = new $root.google.ads.datamanager.v1.CreatePartnerLinkRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.partnerLink != null) { + if (typeof object.partnerLink !== "object") + throw TypeError(".google.ads.datamanager.v1.CreatePartnerLinkRequest.partnerLink: object expected"); + message.partnerLink = $root.google.ads.datamanager.v1.PartnerLink.fromObject(object.partnerLink); + } + return message; + }; + + /** + * Creates a plain object from a CreatePartnerLinkRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {google.ads.datamanager.v1.CreatePartnerLinkRequest} message CreatePartnerLinkRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreatePartnerLinkRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.partnerLink = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.partnerLink != null && message.hasOwnProperty("partnerLink")) + object.partnerLink = $root.google.ads.datamanager.v1.PartnerLink.toObject(message.partnerLink, options); + return object; + }; + + /** + * Converts this CreatePartnerLinkRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @instance + * @returns {Object.} JSON object + */ + CreatePartnerLinkRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreatePartnerLinkRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.CreatePartnerLinkRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreatePartnerLinkRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.CreatePartnerLinkRequest"; + }; + + return CreatePartnerLinkRequest; + })(); + + v1.DeletePartnerLinkRequest = (function() { + + /** + * Properties of a DeletePartnerLinkRequest. + * @memberof google.ads.datamanager.v1 + * @interface IDeletePartnerLinkRequest + * @property {string|null} [name] DeletePartnerLinkRequest name + */ + + /** + * Constructs a new DeletePartnerLinkRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a DeletePartnerLinkRequest. + * @implements IDeletePartnerLinkRequest + * @constructor + * @param {google.ads.datamanager.v1.IDeletePartnerLinkRequest=} [properties] Properties to set + */ + function DeletePartnerLinkRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeletePartnerLinkRequest name. + * @member {string} name + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @instance + */ + DeletePartnerLinkRequest.prototype.name = ""; + + /** + * Creates a new DeletePartnerLinkRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {google.ads.datamanager.v1.IDeletePartnerLinkRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.DeletePartnerLinkRequest} DeletePartnerLinkRequest instance + */ + DeletePartnerLinkRequest.create = function create(properties) { + return new DeletePartnerLinkRequest(properties); + }; + + /** + * Encodes the specified DeletePartnerLinkRequest message. Does not implicitly {@link google.ads.datamanager.v1.DeletePartnerLinkRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {google.ads.datamanager.v1.IDeletePartnerLinkRequest} message DeletePartnerLinkRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeletePartnerLinkRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified DeletePartnerLinkRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.DeletePartnerLinkRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {google.ads.datamanager.v1.IDeletePartnerLinkRequest} message DeletePartnerLinkRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeletePartnerLinkRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeletePartnerLinkRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.DeletePartnerLinkRequest} DeletePartnerLinkRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeletePartnerLinkRequest.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.ads.datamanager.v1.DeletePartnerLinkRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeletePartnerLinkRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.DeletePartnerLinkRequest} DeletePartnerLinkRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeletePartnerLinkRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeletePartnerLinkRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeletePartnerLinkRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a DeletePartnerLinkRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.DeletePartnerLinkRequest} DeletePartnerLinkRequest + */ + DeletePartnerLinkRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.DeletePartnerLinkRequest) + return object; + var message = new $root.google.ads.datamanager.v1.DeletePartnerLinkRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DeletePartnerLinkRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {google.ads.datamanager.v1.DeletePartnerLinkRequest} message DeletePartnerLinkRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeletePartnerLinkRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DeletePartnerLinkRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @instance + * @returns {Object.} JSON object + */ + DeletePartnerLinkRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeletePartnerLinkRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.DeletePartnerLinkRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeletePartnerLinkRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.DeletePartnerLinkRequest"; + }; + + return DeletePartnerLinkRequest; + })(); + + v1.SearchPartnerLinksRequest = (function() { + + /** + * Properties of a SearchPartnerLinksRequest. + * @memberof google.ads.datamanager.v1 + * @interface ISearchPartnerLinksRequest + * @property {string|null} [parent] SearchPartnerLinksRequest parent + * @property {number|null} [pageSize] SearchPartnerLinksRequest pageSize + * @property {string|null} [pageToken] SearchPartnerLinksRequest pageToken + * @property {string|null} [filter] SearchPartnerLinksRequest filter + */ + + /** + * Constructs a new SearchPartnerLinksRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a SearchPartnerLinksRequest. + * @implements ISearchPartnerLinksRequest + * @constructor + * @param {google.ads.datamanager.v1.ISearchPartnerLinksRequest=} [properties] Properties to set + */ + function SearchPartnerLinksRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SearchPartnerLinksRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @instance + */ + SearchPartnerLinksRequest.prototype.parent = ""; + + /** + * SearchPartnerLinksRequest pageSize. + * @member {number} pageSize + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @instance + */ + SearchPartnerLinksRequest.prototype.pageSize = 0; + + /** + * SearchPartnerLinksRequest pageToken. + * @member {string} pageToken + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @instance + */ + SearchPartnerLinksRequest.prototype.pageToken = ""; + + /** + * SearchPartnerLinksRequest filter. + * @member {string} filter + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @instance + */ + SearchPartnerLinksRequest.prototype.filter = ""; + + /** + * Creates a new SearchPartnerLinksRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {google.ads.datamanager.v1.ISearchPartnerLinksRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.SearchPartnerLinksRequest} SearchPartnerLinksRequest instance + */ + SearchPartnerLinksRequest.create = function create(properties) { + return new SearchPartnerLinksRequest(properties); + }; + + /** + * Encodes the specified SearchPartnerLinksRequest message. Does not implicitly {@link google.ads.datamanager.v1.SearchPartnerLinksRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {google.ads.datamanager.v1.ISearchPartnerLinksRequest} message SearchPartnerLinksRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SearchPartnerLinksRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.filter); + return writer; + }; + + /** + * Encodes the specified SearchPartnerLinksRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.SearchPartnerLinksRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {google.ads.datamanager.v1.ISearchPartnerLinksRequest} message SearchPartnerLinksRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SearchPartnerLinksRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SearchPartnerLinksRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.SearchPartnerLinksRequest} SearchPartnerLinksRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SearchPartnerLinksRequest.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.ads.datamanager.v1.SearchPartnerLinksRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + case 4: { + message.filter = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SearchPartnerLinksRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.SearchPartnerLinksRequest} SearchPartnerLinksRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SearchPartnerLinksRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SearchPartnerLinksRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SearchPartnerLinksRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + return null; + }; + + /** + * Creates a SearchPartnerLinksRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.SearchPartnerLinksRequest} SearchPartnerLinksRequest + */ + SearchPartnerLinksRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.SearchPartnerLinksRequest) + return object; + var message = new $root.google.ads.datamanager.v1.SearchPartnerLinksRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.filter != null) + message.filter = String(object.filter); + return message; + }; + + /** + * Creates a plain object from a SearchPartnerLinksRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {google.ads.datamanager.v1.SearchPartnerLinksRequest} message SearchPartnerLinksRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SearchPartnerLinksRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + object.filter = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + return object; + }; + + /** + * Converts this SearchPartnerLinksRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @instance + * @returns {Object.} JSON object + */ + SearchPartnerLinksRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SearchPartnerLinksRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.SearchPartnerLinksRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SearchPartnerLinksRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.SearchPartnerLinksRequest"; + }; + + return SearchPartnerLinksRequest; + })(); + + v1.SearchPartnerLinksResponse = (function() { + + /** + * Properties of a SearchPartnerLinksResponse. + * @memberof google.ads.datamanager.v1 + * @interface ISearchPartnerLinksResponse + * @property {Array.|null} [partnerLinks] SearchPartnerLinksResponse partnerLinks + * @property {string|null} [nextPageToken] SearchPartnerLinksResponse nextPageToken + */ + + /** + * Constructs a new SearchPartnerLinksResponse. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a SearchPartnerLinksResponse. + * @implements ISearchPartnerLinksResponse + * @constructor + * @param {google.ads.datamanager.v1.ISearchPartnerLinksResponse=} [properties] Properties to set + */ + function SearchPartnerLinksResponse(properties) { + this.partnerLinks = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SearchPartnerLinksResponse partnerLinks. + * @member {Array.} partnerLinks + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @instance + */ + SearchPartnerLinksResponse.prototype.partnerLinks = $util.emptyArray; + + /** + * SearchPartnerLinksResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @instance + */ + SearchPartnerLinksResponse.prototype.nextPageToken = ""; + + /** + * Creates a new SearchPartnerLinksResponse instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {google.ads.datamanager.v1.ISearchPartnerLinksResponse=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.SearchPartnerLinksResponse} SearchPartnerLinksResponse instance + */ + SearchPartnerLinksResponse.create = function create(properties) { + return new SearchPartnerLinksResponse(properties); + }; + + /** + * Encodes the specified SearchPartnerLinksResponse message. Does not implicitly {@link google.ads.datamanager.v1.SearchPartnerLinksResponse.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {google.ads.datamanager.v1.ISearchPartnerLinksResponse} message SearchPartnerLinksResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SearchPartnerLinksResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partnerLinks != null && message.partnerLinks.length) + for (var i = 0; i < message.partnerLinks.length; ++i) + $root.google.ads.datamanager.v1.PartnerLink.encode(message.partnerLinks[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified SearchPartnerLinksResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.SearchPartnerLinksResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {google.ads.datamanager.v1.ISearchPartnerLinksResponse} message SearchPartnerLinksResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SearchPartnerLinksResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SearchPartnerLinksResponse message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.SearchPartnerLinksResponse} SearchPartnerLinksResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SearchPartnerLinksResponse.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.ads.datamanager.v1.SearchPartnerLinksResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.partnerLinks && message.partnerLinks.length)) + message.partnerLinks = []; + message.partnerLinks.push($root.google.ads.datamanager.v1.PartnerLink.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SearchPartnerLinksResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.SearchPartnerLinksResponse} SearchPartnerLinksResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SearchPartnerLinksResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SearchPartnerLinksResponse message. + * @function verify + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SearchPartnerLinksResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.partnerLinks != null && message.hasOwnProperty("partnerLinks")) { + if (!Array.isArray(message.partnerLinks)) + return "partnerLinks: array expected"; + for (var i = 0; i < message.partnerLinks.length; ++i) { + var error = $root.google.ads.datamanager.v1.PartnerLink.verify(message.partnerLinks[i]); + if (error) + return "partnerLinks." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a SearchPartnerLinksResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.SearchPartnerLinksResponse} SearchPartnerLinksResponse + */ + SearchPartnerLinksResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.SearchPartnerLinksResponse) + return object; + var message = new $root.google.ads.datamanager.v1.SearchPartnerLinksResponse(); + if (object.partnerLinks) { + if (!Array.isArray(object.partnerLinks)) + throw TypeError(".google.ads.datamanager.v1.SearchPartnerLinksResponse.partnerLinks: array expected"); + message.partnerLinks = []; + for (var i = 0; i < object.partnerLinks.length; ++i) { + if (typeof object.partnerLinks[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.SearchPartnerLinksResponse.partnerLinks: object expected"); + message.partnerLinks[i] = $root.google.ads.datamanager.v1.PartnerLink.fromObject(object.partnerLinks[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a SearchPartnerLinksResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {google.ads.datamanager.v1.SearchPartnerLinksResponse} message SearchPartnerLinksResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SearchPartnerLinksResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.partnerLinks = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.partnerLinks && message.partnerLinks.length) { + object.partnerLinks = []; + for (var j = 0; j < message.partnerLinks.length; ++j) + object.partnerLinks[j] = $root.google.ads.datamanager.v1.PartnerLink.toObject(message.partnerLinks[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this SearchPartnerLinksResponse to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @instance + * @returns {Object.} JSON object + */ + SearchPartnerLinksResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SearchPartnerLinksResponse + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.SearchPartnerLinksResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SearchPartnerLinksResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.SearchPartnerLinksResponse"; + }; + + return SearchPartnerLinksResponse; + })(); + + v1.PartnerLink = (function() { + + /** + * Properties of a PartnerLink. + * @memberof google.ads.datamanager.v1 + * @interface IPartnerLink + * @property {string|null} [name] PartnerLink name + * @property {string|null} [partnerLinkId] PartnerLink partnerLinkId + * @property {google.ads.datamanager.v1.IProductAccount|null} [owningAccount] PartnerLink owningAccount + * @property {google.ads.datamanager.v1.IProductAccount|null} [partnerAccount] PartnerLink partnerAccount + */ + + /** + * Constructs a new PartnerLink. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a PartnerLink. + * @implements IPartnerLink + * @constructor + * @param {google.ads.datamanager.v1.IPartnerLink=} [properties] Properties to set + */ + function PartnerLink(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartnerLink name. + * @member {string} name + * @memberof google.ads.datamanager.v1.PartnerLink + * @instance + */ + PartnerLink.prototype.name = ""; + + /** + * PartnerLink partnerLinkId. + * @member {string} partnerLinkId + * @memberof google.ads.datamanager.v1.PartnerLink + * @instance + */ + PartnerLink.prototype.partnerLinkId = ""; + + /** + * PartnerLink owningAccount. + * @member {google.ads.datamanager.v1.IProductAccount|null|undefined} owningAccount + * @memberof google.ads.datamanager.v1.PartnerLink + * @instance + */ + PartnerLink.prototype.owningAccount = null; + + /** + * PartnerLink partnerAccount. + * @member {google.ads.datamanager.v1.IProductAccount|null|undefined} partnerAccount + * @memberof google.ads.datamanager.v1.PartnerLink + * @instance + */ + PartnerLink.prototype.partnerAccount = null; + + /** + * Creates a new PartnerLink instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {google.ads.datamanager.v1.IPartnerLink=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.PartnerLink} PartnerLink instance + */ + PartnerLink.create = function create(properties) { + return new PartnerLink(properties); + }; + + /** + * Encodes the specified PartnerLink message. Does not implicitly {@link google.ads.datamanager.v1.PartnerLink.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {google.ads.datamanager.v1.IPartnerLink} message PartnerLink message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartnerLink.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.partnerLinkId != null && Object.hasOwnProperty.call(message, "partnerLinkId")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.partnerLinkId); + if (message.owningAccount != null && Object.hasOwnProperty.call(message, "owningAccount")) + $root.google.ads.datamanager.v1.ProductAccount.encode(message.owningAccount, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.partnerAccount != null && Object.hasOwnProperty.call(message, "partnerAccount")) + $root.google.ads.datamanager.v1.ProductAccount.encode(message.partnerAccount, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PartnerLink message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PartnerLink.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {google.ads.datamanager.v1.IPartnerLink} message PartnerLink message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartnerLink.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartnerLink message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.PartnerLink} PartnerLink + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartnerLink.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.ads.datamanager.v1.PartnerLink(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.partnerLinkId = reader.string(); + break; + } + case 3: { + message.owningAccount = $root.google.ads.datamanager.v1.ProductAccount.decode(reader, reader.uint32()); + break; + } + case 4: { + message.partnerAccount = $root.google.ads.datamanager.v1.ProductAccount.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartnerLink message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.PartnerLink} PartnerLink + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartnerLink.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartnerLink message. + * @function verify + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartnerLink.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.partnerLinkId != null && message.hasOwnProperty("partnerLinkId")) + if (!$util.isString(message.partnerLinkId)) + return "partnerLinkId: string expected"; + if (message.owningAccount != null && message.hasOwnProperty("owningAccount")) { + var error = $root.google.ads.datamanager.v1.ProductAccount.verify(message.owningAccount); + if (error) + return "owningAccount." + error; + } + if (message.partnerAccount != null && message.hasOwnProperty("partnerAccount")) { + var error = $root.google.ads.datamanager.v1.ProductAccount.verify(message.partnerAccount); + if (error) + return "partnerAccount." + error; + } + return null; + }; + + /** + * Creates a PartnerLink message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.PartnerLink} PartnerLink + */ + PartnerLink.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.PartnerLink) + return object; + var message = new $root.google.ads.datamanager.v1.PartnerLink(); + if (object.name != null) + message.name = String(object.name); + if (object.partnerLinkId != null) + message.partnerLinkId = String(object.partnerLinkId); + if (object.owningAccount != null) { + if (typeof object.owningAccount !== "object") + throw TypeError(".google.ads.datamanager.v1.PartnerLink.owningAccount: object expected"); + message.owningAccount = $root.google.ads.datamanager.v1.ProductAccount.fromObject(object.owningAccount); + } + if (object.partnerAccount != null) { + if (typeof object.partnerAccount !== "object") + throw TypeError(".google.ads.datamanager.v1.PartnerLink.partnerAccount: object expected"); + message.partnerAccount = $root.google.ads.datamanager.v1.ProductAccount.fromObject(object.partnerAccount); + } + return message; + }; + + /** + * Creates a plain object from a PartnerLink message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {google.ads.datamanager.v1.PartnerLink} message PartnerLink + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartnerLink.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.partnerLinkId = ""; + object.owningAccount = null; + object.partnerAccount = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.partnerLinkId != null && message.hasOwnProperty("partnerLinkId")) + object.partnerLinkId = message.partnerLinkId; + if (message.owningAccount != null && message.hasOwnProperty("owningAccount")) + object.owningAccount = $root.google.ads.datamanager.v1.ProductAccount.toObject(message.owningAccount, options); + if (message.partnerAccount != null && message.hasOwnProperty("partnerAccount")) + object.partnerAccount = $root.google.ads.datamanager.v1.ProductAccount.toObject(message.partnerAccount, options); + return object; + }; + + /** + * Converts this PartnerLink to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.PartnerLink + * @instance + * @returns {Object.} JSON object + */ + PartnerLink.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartnerLink + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.PartnerLink + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartnerLink.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.PartnerLink"; + }; + + return PartnerLink; + })(); + + v1.UserList = (function() { + + /** + * Properties of a UserList. + * @memberof google.ads.datamanager.v1 + * @interface IUserList + * @property {string|null} [name] UserList name + * @property {number|Long|null} [id] UserList id + * @property {boolean|null} [readOnly] UserList readOnly + * @property {string|null} [displayName] UserList displayName + * @property {string|null} [description] UserList description + * @property {google.ads.datamanager.v1.UserList.MembershipStatus|null} [membershipStatus] UserList membershipStatus + * @property {string|null} [integrationCode] UserList integrationCode + * @property {google.protobuf.IDuration|null} [membershipDuration] UserList membershipDuration + * @property {google.ads.datamanager.v1.UserList.ClosingReason|null} [closingReason] UserList closingReason + * @property {google.ads.datamanager.v1.UserList.AccessReason|null} [accessReason] UserList accessReason + * @property {google.ads.datamanager.v1.UserList.AccessStatus|null} [accountAccessStatus] UserList accountAccessStatus + * @property {google.ads.datamanager.v1.ISizeInfo|null} [sizeInfo] UserList sizeInfo + * @property {google.ads.datamanager.v1.ITargetNetworkInfo|null} [targetNetworkInfo] UserList targetNetworkInfo + * @property {google.ads.datamanager.v1.IIngestedUserListInfo|null} [ingestedUserListInfo] UserList ingestedUserListInfo + */ + + /** + * Constructs a new UserList. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserList. + * @implements IUserList + * @constructor + * @param {google.ads.datamanager.v1.IUserList=} [properties] Properties to set + */ + function UserList(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserList name. + * @member {string} name + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.name = ""; + + /** + * UserList id. + * @member {number|Long} id + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.id = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UserList readOnly. + * @member {boolean} readOnly + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.readOnly = false; + + /** + * UserList displayName. + * @member {string|null|undefined} displayName + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.displayName = null; + + /** + * UserList description. + * @member {string|null|undefined} description + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.description = null; + + /** + * UserList membershipStatus. + * @member {google.ads.datamanager.v1.UserList.MembershipStatus|null|undefined} membershipStatus + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.membershipStatus = null; + + /** + * UserList integrationCode. + * @member {string|null|undefined} integrationCode + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.integrationCode = null; + + /** + * UserList membershipDuration. + * @member {google.protobuf.IDuration|null|undefined} membershipDuration + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.membershipDuration = null; + + /** + * UserList closingReason. + * @member {google.ads.datamanager.v1.UserList.ClosingReason|null|undefined} closingReason + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.closingReason = null; + + /** + * UserList accessReason. + * @member {google.ads.datamanager.v1.UserList.AccessReason} accessReason + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.accessReason = 0; + + /** + * UserList accountAccessStatus. + * @member {google.ads.datamanager.v1.UserList.AccessStatus|null|undefined} accountAccessStatus + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.accountAccessStatus = null; + + /** + * UserList sizeInfo. + * @member {google.ads.datamanager.v1.ISizeInfo|null|undefined} sizeInfo + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.sizeInfo = null; + + /** + * UserList targetNetworkInfo. + * @member {google.ads.datamanager.v1.ITargetNetworkInfo|null|undefined} targetNetworkInfo + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.targetNetworkInfo = null; + + /** + * UserList ingestedUserListInfo. + * @member {google.ads.datamanager.v1.IIngestedUserListInfo|null|undefined} ingestedUserListInfo + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + UserList.prototype.ingestedUserListInfo = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserList.prototype, "_displayName", { + get: $util.oneOfGetter($oneOfFields = ["displayName"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserList.prototype, "_description", { + get: $util.oneOfGetter($oneOfFields = ["description"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserList.prototype, "_membershipStatus", { + get: $util.oneOfGetter($oneOfFields = ["membershipStatus"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserList.prototype, "_integrationCode", { + get: $util.oneOfGetter($oneOfFields = ["integrationCode"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserList.prototype, "_closingReason", { + get: $util.oneOfGetter($oneOfFields = ["closingReason"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserList.prototype, "_accountAccessStatus", { + get: $util.oneOfGetter($oneOfFields = ["accountAccessStatus"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * UserList userListInfo. + * @member {"ingestedUserListInfo"|undefined} userListInfo + * @memberof google.ads.datamanager.v1.UserList + * @instance + */ + Object.defineProperty(UserList.prototype, "userListInfo", { + get: $util.oneOfGetter($oneOfFields = ["ingestedUserListInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UserList instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {google.ads.datamanager.v1.IUserList=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UserList} UserList instance + */ + UserList.create = function create(properties) { + return new UserList(properties); + }; + + /** + * Encodes the specified UserList message. Does not implicitly {@link google.ads.datamanager.v1.UserList.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {google.ads.datamanager.v1.IUserList} message UserList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserList.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.id); + if (message.readOnly != null && Object.hasOwnProperty.call(message, "readOnly")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.readOnly); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.displayName); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.description); + if (message.membershipStatus != null && Object.hasOwnProperty.call(message, "membershipStatus")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.membershipStatus); + if (message.integrationCode != null && Object.hasOwnProperty.call(message, "integrationCode")) + writer.uint32(/* id 7, wireType 2 =*/58).string(message.integrationCode); + if (message.membershipDuration != null && Object.hasOwnProperty.call(message, "membershipDuration")) + $root.google.protobuf.Duration.encode(message.membershipDuration, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.closingReason != null && Object.hasOwnProperty.call(message, "closingReason")) + writer.uint32(/* id 9, wireType 0 =*/72).int32(message.closingReason); + if (message.accessReason != null && Object.hasOwnProperty.call(message, "accessReason")) + writer.uint32(/* id 10, wireType 0 =*/80).int32(message.accessReason); + if (message.accountAccessStatus != null && Object.hasOwnProperty.call(message, "accountAccessStatus")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.accountAccessStatus); + if (message.sizeInfo != null && Object.hasOwnProperty.call(message, "sizeInfo")) + $root.google.ads.datamanager.v1.SizeInfo.encode(message.sizeInfo, writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim(); + if (message.targetNetworkInfo != null && Object.hasOwnProperty.call(message, "targetNetworkInfo")) + $root.google.ads.datamanager.v1.TargetNetworkInfo.encode(message.targetNetworkInfo, writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim(); + if (message.ingestedUserListInfo != null && Object.hasOwnProperty.call(message, "ingestedUserListInfo")) + $root.google.ads.datamanager.v1.IngestedUserListInfo.encode(message.ingestedUserListInfo, writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UserList message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserList.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {google.ads.datamanager.v1.IUserList} message UserList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserList.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a UserList message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UserList} UserList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserList.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.ads.datamanager.v1.UserList(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.id = reader.int64(); + break; + } + case 3: { + message.readOnly = reader.bool(); + break; + } + case 4: { + message.displayName = reader.string(); + break; + } + case 5: { + message.description = reader.string(); + break; + } + case 6: { + message.membershipStatus = reader.int32(); + break; + } + case 7: { + message.integrationCode = reader.string(); + break; + } + case 8: { + message.membershipDuration = $root.google.protobuf.Duration.decode(reader, reader.uint32()); + break; + } + case 9: { + message.closingReason = reader.int32(); + break; + } + case 10: { + message.accessReason = reader.int32(); + break; + } + case 11: { + message.accountAccessStatus = reader.int32(); + break; + } + case 12: { + message.sizeInfo = $root.google.ads.datamanager.v1.SizeInfo.decode(reader, reader.uint32()); + break; + } + case 13: { + message.targetNetworkInfo = $root.google.ads.datamanager.v1.TargetNetworkInfo.decode(reader, reader.uint32()); + break; + } + case 14: { + message.ingestedUserListInfo = $root.google.ads.datamanager.v1.IngestedUserListInfo.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a UserList message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UserList} UserList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserList.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a UserList message. + * @function verify + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UserList.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.id != null && message.hasOwnProperty("id")) + if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) + return "id: integer|Long expected"; + if (message.readOnly != null && message.hasOwnProperty("readOnly")) + if (typeof message.readOnly !== "boolean") + return "readOnly: boolean expected"; + if (message.displayName != null && message.hasOwnProperty("displayName")) { + properties._displayName = 1; + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + } + if (message.description != null && message.hasOwnProperty("description")) { + properties._description = 1; + if (!$util.isString(message.description)) + return "description: string expected"; + } + if (message.membershipStatus != null && message.hasOwnProperty("membershipStatus")) { + properties._membershipStatus = 1; + switch (message.membershipStatus) { + default: + return "membershipStatus: enum value expected"; + case 0: + case 1: + case 2: + break; + } + } + if (message.integrationCode != null && message.hasOwnProperty("integrationCode")) { + properties._integrationCode = 1; + if (!$util.isString(message.integrationCode)) + return "integrationCode: string expected"; + } + if (message.membershipDuration != null && message.hasOwnProperty("membershipDuration")) { + var error = $root.google.protobuf.Duration.verify(message.membershipDuration); + if (error) + return "membershipDuration." + error; + } + if (message.closingReason != null && message.hasOwnProperty("closingReason")) { + properties._closingReason = 1; + switch (message.closingReason) { + default: + return "closingReason: enum value expected"; + case 0: + case 1: + break; + } + } + if (message.accessReason != null && message.hasOwnProperty("accessReason")) + switch (message.accessReason) { + default: + return "accessReason: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + break; + } + if (message.accountAccessStatus != null && message.hasOwnProperty("accountAccessStatus")) { + properties._accountAccessStatus = 1; + switch (message.accountAccessStatus) { + default: + return "accountAccessStatus: enum value expected"; + case 0: + case 1: + case 2: + break; + } + } + if (message.sizeInfo != null && message.hasOwnProperty("sizeInfo")) { + var error = $root.google.ads.datamanager.v1.SizeInfo.verify(message.sizeInfo); + if (error) + return "sizeInfo." + error; + } + if (message.targetNetworkInfo != null && message.hasOwnProperty("targetNetworkInfo")) { + var error = $root.google.ads.datamanager.v1.TargetNetworkInfo.verify(message.targetNetworkInfo); + if (error) + return "targetNetworkInfo." + error; + } + if (message.ingestedUserListInfo != null && message.hasOwnProperty("ingestedUserListInfo")) { + properties.userListInfo = 1; + { + var error = $root.google.ads.datamanager.v1.IngestedUserListInfo.verify(message.ingestedUserListInfo); + if (error) + return "ingestedUserListInfo." + error; + } + } + return null; + }; + + /** + * Creates a UserList message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UserList} UserList + */ + UserList.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UserList) + return object; + var message = new $root.google.ads.datamanager.v1.UserList(); + if (object.name != null) + message.name = String(object.name); + if (object.id != null) + if ($util.Long) + (message.id = $util.Long.fromValue(object.id)).unsigned = false; + else if (typeof object.id === "string") + message.id = parseInt(object.id, 10); + else if (typeof object.id === "number") + message.id = object.id; + else if (typeof object.id === "object") + message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(); + if (object.readOnly != null) + message.readOnly = Boolean(object.readOnly); + if (object.displayName != null) + message.displayName = String(object.displayName); + if (object.description != null) + message.description = String(object.description); + switch (object.membershipStatus) { + default: + if (typeof object.membershipStatus === "number") { + message.membershipStatus = object.membershipStatus; + break; + } + break; + case "MEMBERSHIP_STATUS_UNSPECIFIED": + case 0: + message.membershipStatus = 0; + break; + case "OPEN": + case 1: + message.membershipStatus = 1; + break; + case "CLOSED": + case 2: + message.membershipStatus = 2; + break; + } + if (object.integrationCode != null) + message.integrationCode = String(object.integrationCode); + if (object.membershipDuration != null) { + if (typeof object.membershipDuration !== "object") + throw TypeError(".google.ads.datamanager.v1.UserList.membershipDuration: object expected"); + message.membershipDuration = $root.google.protobuf.Duration.fromObject(object.membershipDuration); + } + switch (object.closingReason) { + default: + if (typeof object.closingReason === "number") { + message.closingReason = object.closingReason; + break; + } + break; + case "CLOSING_REASON_UNSPECIFIED": + case 0: + message.closingReason = 0; + break; + case "UNUSED": + case 1: + message.closingReason = 1; + break; + } + switch (object.accessReason) { + default: + if (typeof object.accessReason === "number") { + message.accessReason = object.accessReason; + break; + } + break; + case "ACCESS_REASON_UNSPECIFIED": + case 0: + message.accessReason = 0; + break; + case "OWNED": + case 1: + message.accessReason = 1; + break; + case "SHARED": + case 2: + message.accessReason = 2; + break; + case "LICENSED": + case 3: + message.accessReason = 3; + break; + case "SUBSCRIBED": + case 4: + message.accessReason = 4; + break; + case "AFFILIATED": + case 5: + message.accessReason = 5; + break; + } + switch (object.accountAccessStatus) { + default: + if (typeof object.accountAccessStatus === "number") { + message.accountAccessStatus = object.accountAccessStatus; + break; + } + break; + case "ACCESS_STATUS_UNSPECIFIED": + case 0: + message.accountAccessStatus = 0; + break; + case "ENABLED": + case 1: + message.accountAccessStatus = 1; + break; + case "DISABLED": + case 2: + message.accountAccessStatus = 2; + break; + } + if (object.sizeInfo != null) { + if (typeof object.sizeInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.UserList.sizeInfo: object expected"); + message.sizeInfo = $root.google.ads.datamanager.v1.SizeInfo.fromObject(object.sizeInfo); + } + if (object.targetNetworkInfo != null) { + if (typeof object.targetNetworkInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.UserList.targetNetworkInfo: object expected"); + message.targetNetworkInfo = $root.google.ads.datamanager.v1.TargetNetworkInfo.fromObject(object.targetNetworkInfo); + } + if (object.ingestedUserListInfo != null) { + if (typeof object.ingestedUserListInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.UserList.ingestedUserListInfo: object expected"); + message.ingestedUserListInfo = $root.google.ads.datamanager.v1.IngestedUserListInfo.fromObject(object.ingestedUserListInfo); + } + return message; + }; + + /** + * Creates a plain object from a UserList message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {google.ads.datamanager.v1.UserList} message UserList + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserList.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.id = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.id = options.longs === String ? "0" : 0; + object.readOnly = false; + object.membershipDuration = null; + object.accessReason = options.enums === String ? "ACCESS_REASON_UNSPECIFIED" : 0; + object.sizeInfo = null; + object.targetNetworkInfo = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.id != null && message.hasOwnProperty("id")) + if (typeof message.id === "number") + object.id = options.longs === String ? String(message.id) : message.id; + else + object.id = options.longs === String ? $util.Long.prototype.toString.call(message.id) : options.longs === Number ? new $util.LongBits(message.id.low >>> 0, message.id.high >>> 0).toNumber() : message.id; + if (message.readOnly != null && message.hasOwnProperty("readOnly")) + object.readOnly = message.readOnly; + if (message.displayName != null && message.hasOwnProperty("displayName")) { + object.displayName = message.displayName; + if (options.oneofs) + object._displayName = "displayName"; + } + if (message.description != null && message.hasOwnProperty("description")) { + object.description = message.description; + if (options.oneofs) + object._description = "description"; + } + if (message.membershipStatus != null && message.hasOwnProperty("membershipStatus")) { + object.membershipStatus = options.enums === String ? $root.google.ads.datamanager.v1.UserList.MembershipStatus[message.membershipStatus] === undefined ? message.membershipStatus : $root.google.ads.datamanager.v1.UserList.MembershipStatus[message.membershipStatus] : message.membershipStatus; + if (options.oneofs) + object._membershipStatus = "membershipStatus"; + } + if (message.integrationCode != null && message.hasOwnProperty("integrationCode")) { + object.integrationCode = message.integrationCode; + if (options.oneofs) + object._integrationCode = "integrationCode"; + } + if (message.membershipDuration != null && message.hasOwnProperty("membershipDuration")) + object.membershipDuration = $root.google.protobuf.Duration.toObject(message.membershipDuration, options); + if (message.closingReason != null && message.hasOwnProperty("closingReason")) { + object.closingReason = options.enums === String ? $root.google.ads.datamanager.v1.UserList.ClosingReason[message.closingReason] === undefined ? message.closingReason : $root.google.ads.datamanager.v1.UserList.ClosingReason[message.closingReason] : message.closingReason; + if (options.oneofs) + object._closingReason = "closingReason"; + } + if (message.accessReason != null && message.hasOwnProperty("accessReason")) + object.accessReason = options.enums === String ? $root.google.ads.datamanager.v1.UserList.AccessReason[message.accessReason] === undefined ? message.accessReason : $root.google.ads.datamanager.v1.UserList.AccessReason[message.accessReason] : message.accessReason; + if (message.accountAccessStatus != null && message.hasOwnProperty("accountAccessStatus")) { + object.accountAccessStatus = options.enums === String ? $root.google.ads.datamanager.v1.UserList.AccessStatus[message.accountAccessStatus] === undefined ? message.accountAccessStatus : $root.google.ads.datamanager.v1.UserList.AccessStatus[message.accountAccessStatus] : message.accountAccessStatus; + if (options.oneofs) + object._accountAccessStatus = "accountAccessStatus"; + } + if (message.sizeInfo != null && message.hasOwnProperty("sizeInfo")) + object.sizeInfo = $root.google.ads.datamanager.v1.SizeInfo.toObject(message.sizeInfo, options); + if (message.targetNetworkInfo != null && message.hasOwnProperty("targetNetworkInfo")) + object.targetNetworkInfo = $root.google.ads.datamanager.v1.TargetNetworkInfo.toObject(message.targetNetworkInfo, options); + if (message.ingestedUserListInfo != null && message.hasOwnProperty("ingestedUserListInfo")) { + object.ingestedUserListInfo = $root.google.ads.datamanager.v1.IngestedUserListInfo.toObject(message.ingestedUserListInfo, options); + if (options.oneofs) + object.userListInfo = "ingestedUserListInfo"; + } + return object; + }; + + /** + * Converts this UserList to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UserList + * @instance + * @returns {Object.} JSON object + */ + UserList.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserList + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UserList + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserList.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UserList"; + }; + + /** + * MembershipStatus enum. + * @name google.ads.datamanager.v1.UserList.MembershipStatus + * @enum {number} + * @property {number} MEMBERSHIP_STATUS_UNSPECIFIED=0 MEMBERSHIP_STATUS_UNSPECIFIED value + * @property {number} OPEN=1 OPEN value + * @property {number} CLOSED=2 CLOSED value + */ + UserList.MembershipStatus = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MEMBERSHIP_STATUS_UNSPECIFIED"] = 0; + values[valuesById[1] = "OPEN"] = 1; + values[valuesById[2] = "CLOSED"] = 2; + return values; + })(); + + /** + * ClosingReason enum. + * @name google.ads.datamanager.v1.UserList.ClosingReason + * @enum {number} + * @property {number} CLOSING_REASON_UNSPECIFIED=0 CLOSING_REASON_UNSPECIFIED value + * @property {number} UNUSED=1 UNUSED value + */ + UserList.ClosingReason = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLOSING_REASON_UNSPECIFIED"] = 0; + values[valuesById[1] = "UNUSED"] = 1; + return values; + })(); + + /** + * AccessReason enum. + * @name google.ads.datamanager.v1.UserList.AccessReason + * @enum {number} + * @property {number} ACCESS_REASON_UNSPECIFIED=0 ACCESS_REASON_UNSPECIFIED value + * @property {number} OWNED=1 OWNED value + * @property {number} SHARED=2 SHARED value + * @property {number} LICENSED=3 LICENSED value + * @property {number} SUBSCRIBED=4 SUBSCRIBED value + * @property {number} AFFILIATED=5 AFFILIATED value + */ + UserList.AccessReason = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ACCESS_REASON_UNSPECIFIED"] = 0; + values[valuesById[1] = "OWNED"] = 1; + values[valuesById[2] = "SHARED"] = 2; + values[valuesById[3] = "LICENSED"] = 3; + values[valuesById[4] = "SUBSCRIBED"] = 4; + values[valuesById[5] = "AFFILIATED"] = 5; + return values; + })(); + + /** + * AccessStatus enum. + * @name google.ads.datamanager.v1.UserList.AccessStatus + * @enum {number} + * @property {number} ACCESS_STATUS_UNSPECIFIED=0 ACCESS_STATUS_UNSPECIFIED value + * @property {number} ENABLED=1 ENABLED value + * @property {number} DISABLED=2 DISABLED value + */ + UserList.AccessStatus = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ACCESS_STATUS_UNSPECIFIED"] = 0; + values[valuesById[1] = "ENABLED"] = 1; + values[valuesById[2] = "DISABLED"] = 2; + return values; + })(); + + return UserList; + })(); + + v1.SizeInfo = (function() { + + /** + * Properties of a SizeInfo. + * @memberof google.ads.datamanager.v1 + * @interface ISizeInfo + * @property {number|Long|null} [displayNetworkMembersCount] SizeInfo displayNetworkMembersCount + * @property {number|Long|null} [searchNetworkMembersCount] SizeInfo searchNetworkMembersCount + */ + + /** + * Constructs a new SizeInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a SizeInfo. + * @implements ISizeInfo + * @constructor + * @param {google.ads.datamanager.v1.ISizeInfo=} [properties] Properties to set + */ + function SizeInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SizeInfo displayNetworkMembersCount. + * @member {number|Long} displayNetworkMembersCount + * @memberof google.ads.datamanager.v1.SizeInfo + * @instance + */ + SizeInfo.prototype.displayNetworkMembersCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * SizeInfo searchNetworkMembersCount. + * @member {number|Long} searchNetworkMembersCount + * @memberof google.ads.datamanager.v1.SizeInfo + * @instance + */ + SizeInfo.prototype.searchNetworkMembersCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new SizeInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {google.ads.datamanager.v1.ISizeInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.SizeInfo} SizeInfo instance + */ + SizeInfo.create = function create(properties) { + return new SizeInfo(properties); + }; + + /** + * Encodes the specified SizeInfo message. Does not implicitly {@link google.ads.datamanager.v1.SizeInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {google.ads.datamanager.v1.ISizeInfo} message SizeInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SizeInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.displayNetworkMembersCount != null && Object.hasOwnProperty.call(message, "displayNetworkMembersCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.displayNetworkMembersCount); + if (message.searchNetworkMembersCount != null && Object.hasOwnProperty.call(message, "searchNetworkMembersCount")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.searchNetworkMembersCount); + return writer; + }; + + /** + * Encodes the specified SizeInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.SizeInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {google.ads.datamanager.v1.ISizeInfo} message SizeInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SizeInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SizeInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.SizeInfo} SizeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SizeInfo.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.ads.datamanager.v1.SizeInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.displayNetworkMembersCount = reader.int64(); + break; + } + case 2: { + message.searchNetworkMembersCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SizeInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.SizeInfo} SizeInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SizeInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SizeInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SizeInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.displayNetworkMembersCount != null && message.hasOwnProperty("displayNetworkMembersCount")) + if (!$util.isInteger(message.displayNetworkMembersCount) && !(message.displayNetworkMembersCount && $util.isInteger(message.displayNetworkMembersCount.low) && $util.isInteger(message.displayNetworkMembersCount.high))) + return "displayNetworkMembersCount: integer|Long expected"; + if (message.searchNetworkMembersCount != null && message.hasOwnProperty("searchNetworkMembersCount")) + if (!$util.isInteger(message.searchNetworkMembersCount) && !(message.searchNetworkMembersCount && $util.isInteger(message.searchNetworkMembersCount.low) && $util.isInteger(message.searchNetworkMembersCount.high))) + return "searchNetworkMembersCount: integer|Long expected"; + return null; + }; + + /** + * Creates a SizeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.SizeInfo} SizeInfo + */ + SizeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.SizeInfo) + return object; + var message = new $root.google.ads.datamanager.v1.SizeInfo(); + if (object.displayNetworkMembersCount != null) + if ($util.Long) + (message.displayNetworkMembersCount = $util.Long.fromValue(object.displayNetworkMembersCount)).unsigned = false; + else if (typeof object.displayNetworkMembersCount === "string") + message.displayNetworkMembersCount = parseInt(object.displayNetworkMembersCount, 10); + else if (typeof object.displayNetworkMembersCount === "number") + message.displayNetworkMembersCount = object.displayNetworkMembersCount; + else if (typeof object.displayNetworkMembersCount === "object") + message.displayNetworkMembersCount = new $util.LongBits(object.displayNetworkMembersCount.low >>> 0, object.displayNetworkMembersCount.high >>> 0).toNumber(); + if (object.searchNetworkMembersCount != null) + if ($util.Long) + (message.searchNetworkMembersCount = $util.Long.fromValue(object.searchNetworkMembersCount)).unsigned = false; + else if (typeof object.searchNetworkMembersCount === "string") + message.searchNetworkMembersCount = parseInt(object.searchNetworkMembersCount, 10); + else if (typeof object.searchNetworkMembersCount === "number") + message.searchNetworkMembersCount = object.searchNetworkMembersCount; + else if (typeof object.searchNetworkMembersCount === "object") + message.searchNetworkMembersCount = new $util.LongBits(object.searchNetworkMembersCount.low >>> 0, object.searchNetworkMembersCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a SizeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {google.ads.datamanager.v1.SizeInfo} message SizeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SizeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.displayNetworkMembersCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.displayNetworkMembersCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.searchNetworkMembersCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.searchNetworkMembersCount = options.longs === String ? "0" : 0; + } + if (message.displayNetworkMembersCount != null && message.hasOwnProperty("displayNetworkMembersCount")) + if (typeof message.displayNetworkMembersCount === "number") + object.displayNetworkMembersCount = options.longs === String ? String(message.displayNetworkMembersCount) : message.displayNetworkMembersCount; + else + object.displayNetworkMembersCount = options.longs === String ? $util.Long.prototype.toString.call(message.displayNetworkMembersCount) : options.longs === Number ? new $util.LongBits(message.displayNetworkMembersCount.low >>> 0, message.displayNetworkMembersCount.high >>> 0).toNumber() : message.displayNetworkMembersCount; + if (message.searchNetworkMembersCount != null && message.hasOwnProperty("searchNetworkMembersCount")) + if (typeof message.searchNetworkMembersCount === "number") + object.searchNetworkMembersCount = options.longs === String ? String(message.searchNetworkMembersCount) : message.searchNetworkMembersCount; + else + object.searchNetworkMembersCount = options.longs === String ? $util.Long.prototype.toString.call(message.searchNetworkMembersCount) : options.longs === Number ? new $util.LongBits(message.searchNetworkMembersCount.low >>> 0, message.searchNetworkMembersCount.high >>> 0).toNumber() : message.searchNetworkMembersCount; + return object; + }; + + /** + * Converts this SizeInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.SizeInfo + * @instance + * @returns {Object.} JSON object + */ + SizeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SizeInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.SizeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SizeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.SizeInfo"; + }; + + return SizeInfo; + })(); + + v1.TargetNetworkInfo = (function() { + + /** + * Properties of a TargetNetworkInfo. + * @memberof google.ads.datamanager.v1 + * @interface ITargetNetworkInfo + * @property {boolean|null} [eligibleForDisplay] TargetNetworkInfo eligibleForDisplay + * @property {boolean|null} [eligibleForSearch] TargetNetworkInfo eligibleForSearch + */ + + /** + * Constructs a new TargetNetworkInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a TargetNetworkInfo. + * @implements ITargetNetworkInfo + * @constructor + * @param {google.ads.datamanager.v1.ITargetNetworkInfo=} [properties] Properties to set + */ + function TargetNetworkInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TargetNetworkInfo eligibleForDisplay. + * @member {boolean} eligibleForDisplay + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @instance + */ + TargetNetworkInfo.prototype.eligibleForDisplay = false; + + /** + * TargetNetworkInfo eligibleForSearch. + * @member {boolean|null|undefined} eligibleForSearch + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @instance + */ + TargetNetworkInfo.prototype.eligibleForSearch = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(TargetNetworkInfo.prototype, "_eligibleForSearch", { + get: $util.oneOfGetter($oneOfFields = ["eligibleForSearch"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new TargetNetworkInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {google.ads.datamanager.v1.ITargetNetworkInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.TargetNetworkInfo} TargetNetworkInfo instance + */ + TargetNetworkInfo.create = function create(properties) { + return new TargetNetworkInfo(properties); + }; + + /** + * Encodes the specified TargetNetworkInfo message. Does not implicitly {@link google.ads.datamanager.v1.TargetNetworkInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {google.ads.datamanager.v1.ITargetNetworkInfo} message TargetNetworkInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TargetNetworkInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.eligibleForDisplay != null && Object.hasOwnProperty.call(message, "eligibleForDisplay")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.eligibleForDisplay); + if (message.eligibleForSearch != null && Object.hasOwnProperty.call(message, "eligibleForSearch")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.eligibleForSearch); + return writer; + }; + + /** + * Encodes the specified TargetNetworkInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.TargetNetworkInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {google.ads.datamanager.v1.ITargetNetworkInfo} message TargetNetworkInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TargetNetworkInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TargetNetworkInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.TargetNetworkInfo} TargetNetworkInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TargetNetworkInfo.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.ads.datamanager.v1.TargetNetworkInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.eligibleForDisplay = reader.bool(); + break; + } + case 2: { + message.eligibleForSearch = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TargetNetworkInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.TargetNetworkInfo} TargetNetworkInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TargetNetworkInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TargetNetworkInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TargetNetworkInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.eligibleForDisplay != null && message.hasOwnProperty("eligibleForDisplay")) + if (typeof message.eligibleForDisplay !== "boolean") + return "eligibleForDisplay: boolean expected"; + if (message.eligibleForSearch != null && message.hasOwnProperty("eligibleForSearch")) { + properties._eligibleForSearch = 1; + if (typeof message.eligibleForSearch !== "boolean") + return "eligibleForSearch: boolean expected"; + } + return null; + }; + + /** + * Creates a TargetNetworkInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.TargetNetworkInfo} TargetNetworkInfo + */ + TargetNetworkInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.TargetNetworkInfo) + return object; + var message = new $root.google.ads.datamanager.v1.TargetNetworkInfo(); + if (object.eligibleForDisplay != null) + message.eligibleForDisplay = Boolean(object.eligibleForDisplay); + if (object.eligibleForSearch != null) + message.eligibleForSearch = Boolean(object.eligibleForSearch); + return message; + }; + + /** + * Creates a plain object from a TargetNetworkInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {google.ads.datamanager.v1.TargetNetworkInfo} message TargetNetworkInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TargetNetworkInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.eligibleForDisplay = false; + if (message.eligibleForDisplay != null && message.hasOwnProperty("eligibleForDisplay")) + object.eligibleForDisplay = message.eligibleForDisplay; + if (message.eligibleForSearch != null && message.hasOwnProperty("eligibleForSearch")) { + object.eligibleForSearch = message.eligibleForSearch; + if (options.oneofs) + object._eligibleForSearch = "eligibleForSearch"; + } + return object; + }; + + /** + * Converts this TargetNetworkInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @instance + * @returns {Object.} JSON object + */ + TargetNetworkInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TargetNetworkInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.TargetNetworkInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TargetNetworkInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.TargetNetworkInfo"; + }; + + return TargetNetworkInfo; + })(); + + v1.IngestedUserListInfo = (function() { + + /** + * Properties of an IngestedUserListInfo. + * @memberof google.ads.datamanager.v1 + * @interface IIngestedUserListInfo + * @property {Array.|null} [uploadKeyTypes] IngestedUserListInfo uploadKeyTypes + * @property {google.ads.datamanager.v1.IContactIdInfo|null} [contactIdInfo] IngestedUserListInfo contactIdInfo + * @property {google.ads.datamanager.v1.IMobileIdInfo|null} [mobileIdInfo] IngestedUserListInfo mobileIdInfo + * @property {google.ads.datamanager.v1.IUserIdInfo|null} [userIdInfo] IngestedUserListInfo userIdInfo + * @property {google.ads.datamanager.v1.IPairIdInfo|null} [pairIdInfo] IngestedUserListInfo pairIdInfo + * @property {google.ads.datamanager.v1.IPseudonymousIdInfo|null} [pseudonymousIdInfo] IngestedUserListInfo pseudonymousIdInfo + * @property {google.ads.datamanager.v1.IPartnerAudienceInfo|null} [partnerAudienceInfo] IngestedUserListInfo partnerAudienceInfo + */ + + /** + * Constructs a new IngestedUserListInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents an IngestedUserListInfo. + * @implements IIngestedUserListInfo + * @constructor + * @param {google.ads.datamanager.v1.IIngestedUserListInfo=} [properties] Properties to set + */ + function IngestedUserListInfo(properties) { + this.uploadKeyTypes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * IngestedUserListInfo uploadKeyTypes. + * @member {Array.} uploadKeyTypes + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @instance + */ + IngestedUserListInfo.prototype.uploadKeyTypes = $util.emptyArray; + + /** + * IngestedUserListInfo contactIdInfo. + * @member {google.ads.datamanager.v1.IContactIdInfo|null|undefined} contactIdInfo + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @instance + */ + IngestedUserListInfo.prototype.contactIdInfo = null; + + /** + * IngestedUserListInfo mobileIdInfo. + * @member {google.ads.datamanager.v1.IMobileIdInfo|null|undefined} mobileIdInfo + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @instance + */ + IngestedUserListInfo.prototype.mobileIdInfo = null; + + /** + * IngestedUserListInfo userIdInfo. + * @member {google.ads.datamanager.v1.IUserIdInfo|null|undefined} userIdInfo + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @instance + */ + IngestedUserListInfo.prototype.userIdInfo = null; + + /** + * IngestedUserListInfo pairIdInfo. + * @member {google.ads.datamanager.v1.IPairIdInfo|null|undefined} pairIdInfo + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @instance + */ + IngestedUserListInfo.prototype.pairIdInfo = null; + + /** + * IngestedUserListInfo pseudonymousIdInfo. + * @member {google.ads.datamanager.v1.IPseudonymousIdInfo|null|undefined} pseudonymousIdInfo + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @instance + */ + IngestedUserListInfo.prototype.pseudonymousIdInfo = null; + + /** + * IngestedUserListInfo partnerAudienceInfo. + * @member {google.ads.datamanager.v1.IPartnerAudienceInfo|null|undefined} partnerAudienceInfo + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @instance + */ + IngestedUserListInfo.prototype.partnerAudienceInfo = null; + + /** + * Creates a new IngestedUserListInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {google.ads.datamanager.v1.IIngestedUserListInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.IngestedUserListInfo} IngestedUserListInfo instance + */ + IngestedUserListInfo.create = function create(properties) { + return new IngestedUserListInfo(properties); + }; + + /** + * Encodes the specified IngestedUserListInfo message. Does not implicitly {@link google.ads.datamanager.v1.IngestedUserListInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {google.ads.datamanager.v1.IIngestedUserListInfo} message IngestedUserListInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IngestedUserListInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.uploadKeyTypes != null && message.uploadKeyTypes.length) { + writer.uint32(/* id 1, wireType 2 =*/10).fork(); + for (var i = 0; i < message.uploadKeyTypes.length; ++i) + writer.int32(message.uploadKeyTypes[i]); + writer.ldelim(); + } + if (message.contactIdInfo != null && Object.hasOwnProperty.call(message, "contactIdInfo")) + $root.google.ads.datamanager.v1.ContactIdInfo.encode(message.contactIdInfo, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.mobileIdInfo != null && Object.hasOwnProperty.call(message, "mobileIdInfo")) + $root.google.ads.datamanager.v1.MobileIdInfo.encode(message.mobileIdInfo, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.userIdInfo != null && Object.hasOwnProperty.call(message, "userIdInfo")) + $root.google.ads.datamanager.v1.UserIdInfo.encode(message.userIdInfo, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.pairIdInfo != null && Object.hasOwnProperty.call(message, "pairIdInfo")) + $root.google.ads.datamanager.v1.PairIdInfo.encode(message.pairIdInfo, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.pseudonymousIdInfo != null && Object.hasOwnProperty.call(message, "pseudonymousIdInfo")) + $root.google.ads.datamanager.v1.PseudonymousIdInfo.encode(message.pseudonymousIdInfo, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.partnerAudienceInfo != null && Object.hasOwnProperty.call(message, "partnerAudienceInfo")) + $root.google.ads.datamanager.v1.PartnerAudienceInfo.encode(message.partnerAudienceInfo, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified IngestedUserListInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.IngestedUserListInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {google.ads.datamanager.v1.IIngestedUserListInfo} message IngestedUserListInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + IngestedUserListInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an IngestedUserListInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.IngestedUserListInfo} IngestedUserListInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IngestedUserListInfo.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.ads.datamanager.v1.IngestedUserListInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.uploadKeyTypes && message.uploadKeyTypes.length)) + message.uploadKeyTypes = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.uploadKeyTypes.push(reader.int32()); + } else + message.uploadKeyTypes.push(reader.int32()); + break; + } + case 2: { + message.contactIdInfo = $root.google.ads.datamanager.v1.ContactIdInfo.decode(reader, reader.uint32()); + break; + } + case 3: { + message.mobileIdInfo = $root.google.ads.datamanager.v1.MobileIdInfo.decode(reader, reader.uint32()); + break; + } + case 4: { + message.userIdInfo = $root.google.ads.datamanager.v1.UserIdInfo.decode(reader, reader.uint32()); + break; + } + case 5: { + message.pairIdInfo = $root.google.ads.datamanager.v1.PairIdInfo.decode(reader, reader.uint32()); + break; + } + case 6: { + message.pseudonymousIdInfo = $root.google.ads.datamanager.v1.PseudonymousIdInfo.decode(reader, reader.uint32()); + break; + } + case 7: { + message.partnerAudienceInfo = $root.google.ads.datamanager.v1.PartnerAudienceInfo.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an IngestedUserListInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.IngestedUserListInfo} IngestedUserListInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + IngestedUserListInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an IngestedUserListInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + IngestedUserListInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.uploadKeyTypes != null && message.hasOwnProperty("uploadKeyTypes")) { + if (!Array.isArray(message.uploadKeyTypes)) + return "uploadKeyTypes: array expected"; + for (var i = 0; i < message.uploadKeyTypes.length; ++i) + switch (message.uploadKeyTypes[i]) { + default: + return "uploadKeyTypes: enum value[] expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + break; + } + } + if (message.contactIdInfo != null && message.hasOwnProperty("contactIdInfo")) { + var error = $root.google.ads.datamanager.v1.ContactIdInfo.verify(message.contactIdInfo); + if (error) + return "contactIdInfo." + error; + } + if (message.mobileIdInfo != null && message.hasOwnProperty("mobileIdInfo")) { + var error = $root.google.ads.datamanager.v1.MobileIdInfo.verify(message.mobileIdInfo); + if (error) + return "mobileIdInfo." + error; + } + if (message.userIdInfo != null && message.hasOwnProperty("userIdInfo")) { + var error = $root.google.ads.datamanager.v1.UserIdInfo.verify(message.userIdInfo); + if (error) + return "userIdInfo." + error; + } + if (message.pairIdInfo != null && message.hasOwnProperty("pairIdInfo")) { + var error = $root.google.ads.datamanager.v1.PairIdInfo.verify(message.pairIdInfo); + if (error) + return "pairIdInfo." + error; + } + if (message.pseudonymousIdInfo != null && message.hasOwnProperty("pseudonymousIdInfo")) { + var error = $root.google.ads.datamanager.v1.PseudonymousIdInfo.verify(message.pseudonymousIdInfo); + if (error) + return "pseudonymousIdInfo." + error; + } + if (message.partnerAudienceInfo != null && message.hasOwnProperty("partnerAudienceInfo")) { + var error = $root.google.ads.datamanager.v1.PartnerAudienceInfo.verify(message.partnerAudienceInfo); + if (error) + return "partnerAudienceInfo." + error; + } + return null; + }; + + /** + * Creates an IngestedUserListInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.IngestedUserListInfo} IngestedUserListInfo + */ + IngestedUserListInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.IngestedUserListInfo) + return object; + var message = new $root.google.ads.datamanager.v1.IngestedUserListInfo(); + if (object.uploadKeyTypes) { + if (!Array.isArray(object.uploadKeyTypes)) + throw TypeError(".google.ads.datamanager.v1.IngestedUserListInfo.uploadKeyTypes: array expected"); + message.uploadKeyTypes = []; + for (var i = 0; i < object.uploadKeyTypes.length; ++i) + switch (object.uploadKeyTypes[i]) { + default: + if (typeof object.uploadKeyTypes[i] === "number") { + message.uploadKeyTypes[i] = object.uploadKeyTypes[i]; + break; + } + case "UPLOAD_KEY_TYPE_UNSPECIFIED": + case 0: + message.uploadKeyTypes[i] = 0; + break; + case "CONTACT_ID": + case 1: + message.uploadKeyTypes[i] = 1; + break; + case "MOBILE_ID": + case 2: + message.uploadKeyTypes[i] = 2; + break; + case "USER_ID": + case 3: + message.uploadKeyTypes[i] = 3; + break; + case "PAIR_ID": + case 4: + message.uploadKeyTypes[i] = 4; + break; + case "PSEUDONYMOUS_ID": + case 5: + message.uploadKeyTypes[i] = 5; + break; + } + } + if (object.contactIdInfo != null) { + if (typeof object.contactIdInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.IngestedUserListInfo.contactIdInfo: object expected"); + message.contactIdInfo = $root.google.ads.datamanager.v1.ContactIdInfo.fromObject(object.contactIdInfo); + } + if (object.mobileIdInfo != null) { + if (typeof object.mobileIdInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.IngestedUserListInfo.mobileIdInfo: object expected"); + message.mobileIdInfo = $root.google.ads.datamanager.v1.MobileIdInfo.fromObject(object.mobileIdInfo); + } + if (object.userIdInfo != null) { + if (typeof object.userIdInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.IngestedUserListInfo.userIdInfo: object expected"); + message.userIdInfo = $root.google.ads.datamanager.v1.UserIdInfo.fromObject(object.userIdInfo); + } + if (object.pairIdInfo != null) { + if (typeof object.pairIdInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.IngestedUserListInfo.pairIdInfo: object expected"); + message.pairIdInfo = $root.google.ads.datamanager.v1.PairIdInfo.fromObject(object.pairIdInfo); + } + if (object.pseudonymousIdInfo != null) { + if (typeof object.pseudonymousIdInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.IngestedUserListInfo.pseudonymousIdInfo: object expected"); + message.pseudonymousIdInfo = $root.google.ads.datamanager.v1.PseudonymousIdInfo.fromObject(object.pseudonymousIdInfo); + } + if (object.partnerAudienceInfo != null) { + if (typeof object.partnerAudienceInfo !== "object") + throw TypeError(".google.ads.datamanager.v1.IngestedUserListInfo.partnerAudienceInfo: object expected"); + message.partnerAudienceInfo = $root.google.ads.datamanager.v1.PartnerAudienceInfo.fromObject(object.partnerAudienceInfo); + } + return message; + }; + + /** + * Creates a plain object from an IngestedUserListInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {google.ads.datamanager.v1.IngestedUserListInfo} message IngestedUserListInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + IngestedUserListInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uploadKeyTypes = []; + if (options.defaults) { + object.contactIdInfo = null; + object.mobileIdInfo = null; + object.userIdInfo = null; + object.pairIdInfo = null; + object.pseudonymousIdInfo = null; + object.partnerAudienceInfo = null; + } + if (message.uploadKeyTypes && message.uploadKeyTypes.length) { + object.uploadKeyTypes = []; + for (var j = 0; j < message.uploadKeyTypes.length; ++j) + object.uploadKeyTypes[j] = options.enums === String ? $root.google.ads.datamanager.v1.IngestedUserListInfo.UploadKeyType[message.uploadKeyTypes[j]] === undefined ? message.uploadKeyTypes[j] : $root.google.ads.datamanager.v1.IngestedUserListInfo.UploadKeyType[message.uploadKeyTypes[j]] : message.uploadKeyTypes[j]; + } + if (message.contactIdInfo != null && message.hasOwnProperty("contactIdInfo")) + object.contactIdInfo = $root.google.ads.datamanager.v1.ContactIdInfo.toObject(message.contactIdInfo, options); + if (message.mobileIdInfo != null && message.hasOwnProperty("mobileIdInfo")) + object.mobileIdInfo = $root.google.ads.datamanager.v1.MobileIdInfo.toObject(message.mobileIdInfo, options); + if (message.userIdInfo != null && message.hasOwnProperty("userIdInfo")) + object.userIdInfo = $root.google.ads.datamanager.v1.UserIdInfo.toObject(message.userIdInfo, options); + if (message.pairIdInfo != null && message.hasOwnProperty("pairIdInfo")) + object.pairIdInfo = $root.google.ads.datamanager.v1.PairIdInfo.toObject(message.pairIdInfo, options); + if (message.pseudonymousIdInfo != null && message.hasOwnProperty("pseudonymousIdInfo")) + object.pseudonymousIdInfo = $root.google.ads.datamanager.v1.PseudonymousIdInfo.toObject(message.pseudonymousIdInfo, options); + if (message.partnerAudienceInfo != null && message.hasOwnProperty("partnerAudienceInfo")) + object.partnerAudienceInfo = $root.google.ads.datamanager.v1.PartnerAudienceInfo.toObject(message.partnerAudienceInfo, options); + return object; + }; + + /** + * Converts this IngestedUserListInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @instance + * @returns {Object.} JSON object + */ + IngestedUserListInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for IngestedUserListInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.IngestedUserListInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + IngestedUserListInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.IngestedUserListInfo"; + }; + + /** + * UploadKeyType enum. + * @name google.ads.datamanager.v1.IngestedUserListInfo.UploadKeyType + * @enum {number} + * @property {number} UPLOAD_KEY_TYPE_UNSPECIFIED=0 UPLOAD_KEY_TYPE_UNSPECIFIED value + * @property {number} CONTACT_ID=1 CONTACT_ID value + * @property {number} MOBILE_ID=2 MOBILE_ID value + * @property {number} USER_ID=3 USER_ID value + * @property {number} PAIR_ID=4 PAIR_ID value + * @property {number} PSEUDONYMOUS_ID=5 PSEUDONYMOUS_ID value + */ + IngestedUserListInfo.UploadKeyType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UPLOAD_KEY_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "CONTACT_ID"] = 1; + values[valuesById[2] = "MOBILE_ID"] = 2; + values[valuesById[3] = "USER_ID"] = 3; + values[valuesById[4] = "PAIR_ID"] = 4; + values[valuesById[5] = "PSEUDONYMOUS_ID"] = 5; + return values; + })(); + + return IngestedUserListInfo; + })(); + + v1.ContactIdInfo = (function() { + + /** + * Properties of a ContactIdInfo. + * @memberof google.ads.datamanager.v1 + * @interface IContactIdInfo + * @property {google.ads.datamanager.v1.DataSourceType|null} [dataSourceType] ContactIdInfo dataSourceType + * @property {number|null} [matchRatePercentage] ContactIdInfo matchRatePercentage + */ + + /** + * Constructs a new ContactIdInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ContactIdInfo. + * @implements IContactIdInfo + * @constructor + * @param {google.ads.datamanager.v1.IContactIdInfo=} [properties] Properties to set + */ + function ContactIdInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ContactIdInfo dataSourceType. + * @member {google.ads.datamanager.v1.DataSourceType|null|undefined} dataSourceType + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @instance + */ + ContactIdInfo.prototype.dataSourceType = null; + + /** + * ContactIdInfo matchRatePercentage. + * @member {number} matchRatePercentage + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @instance + */ + ContactIdInfo.prototype.matchRatePercentage = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ContactIdInfo.prototype, "_dataSourceType", { + get: $util.oneOfGetter($oneOfFields = ["dataSourceType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ContactIdInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {google.ads.datamanager.v1.IContactIdInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ContactIdInfo} ContactIdInfo instance + */ + ContactIdInfo.create = function create(properties) { + return new ContactIdInfo(properties); + }; + + /** + * Encodes the specified ContactIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.ContactIdInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {google.ads.datamanager.v1.IContactIdInfo} message ContactIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ContactIdInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataSourceType != null && Object.hasOwnProperty.call(message, "dataSourceType")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.dataSourceType); + if (message.matchRatePercentage != null && Object.hasOwnProperty.call(message, "matchRatePercentage")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.matchRatePercentage); + return writer; + }; + + /** + * Encodes the specified ContactIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ContactIdInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {google.ads.datamanager.v1.IContactIdInfo} message ContactIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ContactIdInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ContactIdInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ContactIdInfo} ContactIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ContactIdInfo.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.ads.datamanager.v1.ContactIdInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.dataSourceType = reader.int32(); + break; + } + case 2: { + message.matchRatePercentage = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ContactIdInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ContactIdInfo} ContactIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ContactIdInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ContactIdInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ContactIdInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.dataSourceType != null && message.hasOwnProperty("dataSourceType")) { + properties._dataSourceType = 1; + switch (message.dataSourceType) { + default: + return "dataSourceType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + } + if (message.matchRatePercentage != null && message.hasOwnProperty("matchRatePercentage")) + if (!$util.isInteger(message.matchRatePercentage)) + return "matchRatePercentage: integer expected"; + return null; + }; + + /** + * Creates a ContactIdInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ContactIdInfo} ContactIdInfo + */ + ContactIdInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ContactIdInfo) + return object; + var message = new $root.google.ads.datamanager.v1.ContactIdInfo(); + switch (object.dataSourceType) { + default: + if (typeof object.dataSourceType === "number") { + message.dataSourceType = object.dataSourceType; + break; + } + break; + case "DATA_SOURCE_TYPE_UNSPECIFIED": + case 0: + message.dataSourceType = 0; + break; + case "DATA_SOURCE_TYPE_FIRST_PARTY": + case 1: + message.dataSourceType = 1; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU": + case 2: + message.dataSourceType = 2; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE": + case 3: + message.dataSourceType = 3; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA": + case 4: + message.dataSourceType = 4; + break; + } + if (object.matchRatePercentage != null) + message.matchRatePercentage = object.matchRatePercentage | 0; + return message; + }; + + /** + * Creates a plain object from a ContactIdInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {google.ads.datamanager.v1.ContactIdInfo} message ContactIdInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ContactIdInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.matchRatePercentage = 0; + if (message.dataSourceType != null && message.hasOwnProperty("dataSourceType")) { + object.dataSourceType = options.enums === String ? $root.google.ads.datamanager.v1.DataSourceType[message.dataSourceType] === undefined ? message.dataSourceType : $root.google.ads.datamanager.v1.DataSourceType[message.dataSourceType] : message.dataSourceType; + if (options.oneofs) + object._dataSourceType = "dataSourceType"; + } + if (message.matchRatePercentage != null && message.hasOwnProperty("matchRatePercentage")) + object.matchRatePercentage = message.matchRatePercentage; + return object; + }; + + /** + * Converts this ContactIdInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @instance + * @returns {Object.} JSON object + */ + ContactIdInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ContactIdInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ContactIdInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ContactIdInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ContactIdInfo"; + }; + + return ContactIdInfo; + })(); + + v1.MobileIdInfo = (function() { + + /** + * Properties of a MobileIdInfo. + * @memberof google.ads.datamanager.v1 + * @interface IMobileIdInfo + * @property {google.ads.datamanager.v1.DataSourceType|null} [dataSourceType] MobileIdInfo dataSourceType + * @property {google.ads.datamanager.v1.MobileIdInfo.KeySpace|null} [keySpace] MobileIdInfo keySpace + * @property {string|null} [appId] MobileIdInfo appId + */ + + /** + * Constructs a new MobileIdInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a MobileIdInfo. + * @implements IMobileIdInfo + * @constructor + * @param {google.ads.datamanager.v1.IMobileIdInfo=} [properties] Properties to set + */ + function MobileIdInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MobileIdInfo dataSourceType. + * @member {google.ads.datamanager.v1.DataSourceType|null|undefined} dataSourceType + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @instance + */ + MobileIdInfo.prototype.dataSourceType = null; + + /** + * MobileIdInfo keySpace. + * @member {google.ads.datamanager.v1.MobileIdInfo.KeySpace|null|undefined} keySpace + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @instance + */ + MobileIdInfo.prototype.keySpace = null; + + /** + * MobileIdInfo appId. + * @member {string|null|undefined} appId + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @instance + */ + MobileIdInfo.prototype.appId = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(MobileIdInfo.prototype, "_dataSourceType", { + get: $util.oneOfGetter($oneOfFields = ["dataSourceType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(MobileIdInfo.prototype, "_keySpace", { + get: $util.oneOfGetter($oneOfFields = ["keySpace"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(MobileIdInfo.prototype, "_appId", { + get: $util.oneOfGetter($oneOfFields = ["appId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new MobileIdInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {google.ads.datamanager.v1.IMobileIdInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.MobileIdInfo} MobileIdInfo instance + */ + MobileIdInfo.create = function create(properties) { + return new MobileIdInfo(properties); + }; + + /** + * Encodes the specified MobileIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.MobileIdInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {google.ads.datamanager.v1.IMobileIdInfo} message MobileIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MobileIdInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataSourceType != null && Object.hasOwnProperty.call(message, "dataSourceType")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.dataSourceType); + if (message.keySpace != null && Object.hasOwnProperty.call(message, "keySpace")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.keySpace); + if (message.appId != null && Object.hasOwnProperty.call(message, "appId")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.appId); + return writer; + }; + + /** + * Encodes the specified MobileIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.MobileIdInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {google.ads.datamanager.v1.IMobileIdInfo} message MobileIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MobileIdInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MobileIdInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.MobileIdInfo} MobileIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MobileIdInfo.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.ads.datamanager.v1.MobileIdInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.dataSourceType = reader.int32(); + break; + } + case 2: { + message.keySpace = reader.int32(); + break; + } + case 3: { + message.appId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MobileIdInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.MobileIdInfo} MobileIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MobileIdInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MobileIdInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MobileIdInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.dataSourceType != null && message.hasOwnProperty("dataSourceType")) { + properties._dataSourceType = 1; + switch (message.dataSourceType) { + default: + return "dataSourceType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + } + if (message.keySpace != null && message.hasOwnProperty("keySpace")) { + properties._keySpace = 1; + switch (message.keySpace) { + default: + return "keySpace: enum value expected"; + case 0: + case 1: + case 2: + break; + } + } + if (message.appId != null && message.hasOwnProperty("appId")) { + properties._appId = 1; + if (!$util.isString(message.appId)) + return "appId: string expected"; + } + return null; + }; + + /** + * Creates a MobileIdInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.MobileIdInfo} MobileIdInfo + */ + MobileIdInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.MobileIdInfo) + return object; + var message = new $root.google.ads.datamanager.v1.MobileIdInfo(); + switch (object.dataSourceType) { + default: + if (typeof object.dataSourceType === "number") { + message.dataSourceType = object.dataSourceType; + break; + } + break; + case "DATA_SOURCE_TYPE_UNSPECIFIED": + case 0: + message.dataSourceType = 0; + break; + case "DATA_SOURCE_TYPE_FIRST_PARTY": + case 1: + message.dataSourceType = 1; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU": + case 2: + message.dataSourceType = 2; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE": + case 3: + message.dataSourceType = 3; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA": + case 4: + message.dataSourceType = 4; + break; + } + switch (object.keySpace) { + default: + if (typeof object.keySpace === "number") { + message.keySpace = object.keySpace; + break; + } + break; + case "KEY_SPACE_UNSPECIFIED": + case 0: + message.keySpace = 0; + break; + case "IOS": + case 1: + message.keySpace = 1; + break; + case "ANDROID": + case 2: + message.keySpace = 2; + break; + } + if (object.appId != null) + message.appId = String(object.appId); + return message; + }; + + /** + * Creates a plain object from a MobileIdInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {google.ads.datamanager.v1.MobileIdInfo} message MobileIdInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MobileIdInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.dataSourceType != null && message.hasOwnProperty("dataSourceType")) { + object.dataSourceType = options.enums === String ? $root.google.ads.datamanager.v1.DataSourceType[message.dataSourceType] === undefined ? message.dataSourceType : $root.google.ads.datamanager.v1.DataSourceType[message.dataSourceType] : message.dataSourceType; + if (options.oneofs) + object._dataSourceType = "dataSourceType"; + } + if (message.keySpace != null && message.hasOwnProperty("keySpace")) { + object.keySpace = options.enums === String ? $root.google.ads.datamanager.v1.MobileIdInfo.KeySpace[message.keySpace] === undefined ? message.keySpace : $root.google.ads.datamanager.v1.MobileIdInfo.KeySpace[message.keySpace] : message.keySpace; + if (options.oneofs) + object._keySpace = "keySpace"; + } + if (message.appId != null && message.hasOwnProperty("appId")) { + object.appId = message.appId; + if (options.oneofs) + object._appId = "appId"; + } + return object; + }; + + /** + * Converts this MobileIdInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @instance + * @returns {Object.} JSON object + */ + MobileIdInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MobileIdInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.MobileIdInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MobileIdInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.MobileIdInfo"; + }; + + /** + * KeySpace enum. + * @name google.ads.datamanager.v1.MobileIdInfo.KeySpace + * @enum {number} + * @property {number} KEY_SPACE_UNSPECIFIED=0 KEY_SPACE_UNSPECIFIED value + * @property {number} IOS=1 IOS value + * @property {number} ANDROID=2 ANDROID value + */ + MobileIdInfo.KeySpace = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "KEY_SPACE_UNSPECIFIED"] = 0; + values[valuesById[1] = "IOS"] = 1; + values[valuesById[2] = "ANDROID"] = 2; + return values; + })(); + + return MobileIdInfo; + })(); + + v1.UserIdInfo = (function() { + + /** + * Properties of a UserIdInfo. + * @memberof google.ads.datamanager.v1 + * @interface IUserIdInfo + * @property {google.ads.datamanager.v1.DataSourceType|null} [dataSourceType] UserIdInfo dataSourceType + */ + + /** + * Constructs a new UserIdInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserIdInfo. + * @implements IUserIdInfo + * @constructor + * @param {google.ads.datamanager.v1.IUserIdInfo=} [properties] Properties to set + */ + function UserIdInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserIdInfo dataSourceType. + * @member {google.ads.datamanager.v1.DataSourceType|null|undefined} dataSourceType + * @memberof google.ads.datamanager.v1.UserIdInfo + * @instance + */ + UserIdInfo.prototype.dataSourceType = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserIdInfo.prototype, "_dataSourceType", { + get: $util.oneOfGetter($oneOfFields = ["dataSourceType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UserIdInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {google.ads.datamanager.v1.IUserIdInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UserIdInfo} UserIdInfo instance + */ + UserIdInfo.create = function create(properties) { + return new UserIdInfo(properties); + }; + + /** + * Encodes the specified UserIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.UserIdInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {google.ads.datamanager.v1.IUserIdInfo} message UserIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserIdInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.dataSourceType != null && Object.hasOwnProperty.call(message, "dataSourceType")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.dataSourceType); + return writer; + }; + + /** + * Encodes the specified UserIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserIdInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {google.ads.datamanager.v1.IUserIdInfo} message UserIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserIdInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a UserIdInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UserIdInfo} UserIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserIdInfo.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.ads.datamanager.v1.UserIdInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.dataSourceType = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a UserIdInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UserIdInfo} UserIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserIdInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a UserIdInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UserIdInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.dataSourceType != null && message.hasOwnProperty("dataSourceType")) { + properties._dataSourceType = 1; + switch (message.dataSourceType) { + default: + return "dataSourceType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + } + return null; + }; + + /** + * Creates a UserIdInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UserIdInfo} UserIdInfo + */ + UserIdInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UserIdInfo) + return object; + var message = new $root.google.ads.datamanager.v1.UserIdInfo(); + switch (object.dataSourceType) { + default: + if (typeof object.dataSourceType === "number") { + message.dataSourceType = object.dataSourceType; + break; + } + break; + case "DATA_SOURCE_TYPE_UNSPECIFIED": + case 0: + message.dataSourceType = 0; + break; + case "DATA_SOURCE_TYPE_FIRST_PARTY": + case 1: + message.dataSourceType = 1; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU": + case 2: + message.dataSourceType = 2; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE": + case 3: + message.dataSourceType = 3; + break; + case "DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA": + case 4: + message.dataSourceType = 4; + break; + } + return message; + }; + + /** + * Creates a plain object from a UserIdInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {google.ads.datamanager.v1.UserIdInfo} message UserIdInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserIdInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.dataSourceType != null && message.hasOwnProperty("dataSourceType")) { + object.dataSourceType = options.enums === String ? $root.google.ads.datamanager.v1.DataSourceType[message.dataSourceType] === undefined ? message.dataSourceType : $root.google.ads.datamanager.v1.DataSourceType[message.dataSourceType] : message.dataSourceType; + if (options.oneofs) + object._dataSourceType = "dataSourceType"; + } + return object; + }; + + /** + * Converts this UserIdInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UserIdInfo + * @instance + * @returns {Object.} JSON object + */ + UserIdInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserIdInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UserIdInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserIdInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UserIdInfo"; + }; + + return UserIdInfo; + })(); + + v1.PairIdInfo = (function() { + + /** + * Properties of a PairIdInfo. + * @memberof google.ads.datamanager.v1 + * @interface IPairIdInfo + * @property {number|Long|null} [publisherId] PairIdInfo publisherId + * @property {string|null} [publisherName] PairIdInfo publisherName + * @property {number|null} [matchRatePercentage] PairIdInfo matchRatePercentage + * @property {number|Long|null} [advertiserIdentifierCount] PairIdInfo advertiserIdentifierCount + * @property {string|null} [cleanRoomIdentifier] PairIdInfo cleanRoomIdentifier + */ + + /** + * Constructs a new PairIdInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a PairIdInfo. + * @implements IPairIdInfo + * @constructor + * @param {google.ads.datamanager.v1.IPairIdInfo=} [properties] Properties to set + */ + function PairIdInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PairIdInfo publisherId. + * @member {number|Long|null|undefined} publisherId + * @memberof google.ads.datamanager.v1.PairIdInfo + * @instance + */ + PairIdInfo.prototype.publisherId = null; + + /** + * PairIdInfo publisherName. + * @member {string|null|undefined} publisherName + * @memberof google.ads.datamanager.v1.PairIdInfo + * @instance + */ + PairIdInfo.prototype.publisherName = null; + + /** + * PairIdInfo matchRatePercentage. + * @member {number} matchRatePercentage + * @memberof google.ads.datamanager.v1.PairIdInfo + * @instance + */ + PairIdInfo.prototype.matchRatePercentage = 0; + + /** + * PairIdInfo advertiserIdentifierCount. + * @member {number|Long} advertiserIdentifierCount + * @memberof google.ads.datamanager.v1.PairIdInfo + * @instance + */ + PairIdInfo.prototype.advertiserIdentifierCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * PairIdInfo cleanRoomIdentifier. + * @member {string|null|undefined} cleanRoomIdentifier + * @memberof google.ads.datamanager.v1.PairIdInfo + * @instance + */ + PairIdInfo.prototype.cleanRoomIdentifier = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PairIdInfo.prototype, "_publisherId", { + get: $util.oneOfGetter($oneOfFields = ["publisherId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PairIdInfo.prototype, "_publisherName", { + get: $util.oneOfGetter($oneOfFields = ["publisherName"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PairIdInfo.prototype, "_cleanRoomIdentifier", { + get: $util.oneOfGetter($oneOfFields = ["cleanRoomIdentifier"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new PairIdInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {google.ads.datamanager.v1.IPairIdInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.PairIdInfo} PairIdInfo instance + */ + PairIdInfo.create = function create(properties) { + return new PairIdInfo(properties); + }; + + /** + * Encodes the specified PairIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.PairIdInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {google.ads.datamanager.v1.IPairIdInfo} message PairIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PairIdInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.publisherId != null && Object.hasOwnProperty.call(message, "publisherId")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.publisherId); + if (message.publisherName != null && Object.hasOwnProperty.call(message, "publisherName")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.publisherName); + if (message.matchRatePercentage != null && Object.hasOwnProperty.call(message, "matchRatePercentage")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.matchRatePercentage); + if (message.advertiserIdentifierCount != null && Object.hasOwnProperty.call(message, "advertiserIdentifierCount")) + writer.uint32(/* id 4, wireType 0 =*/32).int64(message.advertiserIdentifierCount); + if (message.cleanRoomIdentifier != null && Object.hasOwnProperty.call(message, "cleanRoomIdentifier")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.cleanRoomIdentifier); + return writer; + }; + + /** + * Encodes the specified PairIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PairIdInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {google.ads.datamanager.v1.IPairIdInfo} message PairIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PairIdInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PairIdInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.PairIdInfo} PairIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PairIdInfo.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.ads.datamanager.v1.PairIdInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.publisherId = reader.int64(); + break; + } + case 2: { + message.publisherName = reader.string(); + break; + } + case 3: { + message.matchRatePercentage = reader.int32(); + break; + } + case 4: { + message.advertiserIdentifierCount = reader.int64(); + break; + } + case 5: { + message.cleanRoomIdentifier = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PairIdInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.PairIdInfo} PairIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PairIdInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PairIdInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PairIdInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.publisherId != null && message.hasOwnProperty("publisherId")) { + properties._publisherId = 1; + if (!$util.isInteger(message.publisherId) && !(message.publisherId && $util.isInteger(message.publisherId.low) && $util.isInteger(message.publisherId.high))) + return "publisherId: integer|Long expected"; + } + if (message.publisherName != null && message.hasOwnProperty("publisherName")) { + properties._publisherName = 1; + if (!$util.isString(message.publisherName)) + return "publisherName: string expected"; + } + if (message.matchRatePercentage != null && message.hasOwnProperty("matchRatePercentage")) + if (!$util.isInteger(message.matchRatePercentage)) + return "matchRatePercentage: integer expected"; + if (message.advertiserIdentifierCount != null && message.hasOwnProperty("advertiserIdentifierCount")) + if (!$util.isInteger(message.advertiserIdentifierCount) && !(message.advertiserIdentifierCount && $util.isInteger(message.advertiserIdentifierCount.low) && $util.isInteger(message.advertiserIdentifierCount.high))) + return "advertiserIdentifierCount: integer|Long expected"; + if (message.cleanRoomIdentifier != null && message.hasOwnProperty("cleanRoomIdentifier")) { + properties._cleanRoomIdentifier = 1; + if (!$util.isString(message.cleanRoomIdentifier)) + return "cleanRoomIdentifier: string expected"; + } + return null; + }; + + /** + * Creates a PairIdInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.PairIdInfo} PairIdInfo + */ + PairIdInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.PairIdInfo) + return object; + var message = new $root.google.ads.datamanager.v1.PairIdInfo(); + if (object.publisherId != null) + if ($util.Long) + (message.publisherId = $util.Long.fromValue(object.publisherId)).unsigned = false; + else if (typeof object.publisherId === "string") + message.publisherId = parseInt(object.publisherId, 10); + else if (typeof object.publisherId === "number") + message.publisherId = object.publisherId; + else if (typeof object.publisherId === "object") + message.publisherId = new $util.LongBits(object.publisherId.low >>> 0, object.publisherId.high >>> 0).toNumber(); + if (object.publisherName != null) + message.publisherName = String(object.publisherName); + if (object.matchRatePercentage != null) + message.matchRatePercentage = object.matchRatePercentage | 0; + if (object.advertiserIdentifierCount != null) + if ($util.Long) + (message.advertiserIdentifierCount = $util.Long.fromValue(object.advertiserIdentifierCount)).unsigned = false; + else if (typeof object.advertiserIdentifierCount === "string") + message.advertiserIdentifierCount = parseInt(object.advertiserIdentifierCount, 10); + else if (typeof object.advertiserIdentifierCount === "number") + message.advertiserIdentifierCount = object.advertiserIdentifierCount; + else if (typeof object.advertiserIdentifierCount === "object") + message.advertiserIdentifierCount = new $util.LongBits(object.advertiserIdentifierCount.low >>> 0, object.advertiserIdentifierCount.high >>> 0).toNumber(); + if (object.cleanRoomIdentifier != null) + message.cleanRoomIdentifier = String(object.cleanRoomIdentifier); + return message; + }; + + /** + * Creates a plain object from a PairIdInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {google.ads.datamanager.v1.PairIdInfo} message PairIdInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PairIdInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.matchRatePercentage = 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.advertiserIdentifierCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.advertiserIdentifierCount = options.longs === String ? "0" : 0; + } + if (message.publisherId != null && message.hasOwnProperty("publisherId")) { + if (typeof message.publisherId === "number") + object.publisherId = options.longs === String ? String(message.publisherId) : message.publisherId; + else + object.publisherId = options.longs === String ? $util.Long.prototype.toString.call(message.publisherId) : options.longs === Number ? new $util.LongBits(message.publisherId.low >>> 0, message.publisherId.high >>> 0).toNumber() : message.publisherId; + if (options.oneofs) + object._publisherId = "publisherId"; + } + if (message.publisherName != null && message.hasOwnProperty("publisherName")) { + object.publisherName = message.publisherName; + if (options.oneofs) + object._publisherName = "publisherName"; + } + if (message.matchRatePercentage != null && message.hasOwnProperty("matchRatePercentage")) + object.matchRatePercentage = message.matchRatePercentage; + if (message.advertiserIdentifierCount != null && message.hasOwnProperty("advertiserIdentifierCount")) + if (typeof message.advertiserIdentifierCount === "number") + object.advertiserIdentifierCount = options.longs === String ? String(message.advertiserIdentifierCount) : message.advertiserIdentifierCount; + else + object.advertiserIdentifierCount = options.longs === String ? $util.Long.prototype.toString.call(message.advertiserIdentifierCount) : options.longs === Number ? new $util.LongBits(message.advertiserIdentifierCount.low >>> 0, message.advertiserIdentifierCount.high >>> 0).toNumber() : message.advertiserIdentifierCount; + if (message.cleanRoomIdentifier != null && message.hasOwnProperty("cleanRoomIdentifier")) { + object.cleanRoomIdentifier = message.cleanRoomIdentifier; + if (options.oneofs) + object._cleanRoomIdentifier = "cleanRoomIdentifier"; + } + return object; + }; + + /** + * Converts this PairIdInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.PairIdInfo + * @instance + * @returns {Object.} JSON object + */ + PairIdInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PairIdInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.PairIdInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PairIdInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.PairIdInfo"; + }; + + return PairIdInfo; + })(); + + v1.PartnerAudienceInfo = (function() { + + /** + * Properties of a PartnerAudienceInfo. + * @memberof google.ads.datamanager.v1 + * @interface IPartnerAudienceInfo + * @property {google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource|null} [partnerAudienceSource] PartnerAudienceInfo partnerAudienceSource + * @property {string|null} [commercePartner] PartnerAudienceInfo commercePartner + */ + + /** + * Constructs a new PartnerAudienceInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a PartnerAudienceInfo. + * @implements IPartnerAudienceInfo + * @constructor + * @param {google.ads.datamanager.v1.IPartnerAudienceInfo=} [properties] Properties to set + */ + function PartnerAudienceInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PartnerAudienceInfo partnerAudienceSource. + * @member {google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource|null|undefined} partnerAudienceSource + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @instance + */ + PartnerAudienceInfo.prototype.partnerAudienceSource = null; + + /** + * PartnerAudienceInfo commercePartner. + * @member {string|null|undefined} commercePartner + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @instance + */ + PartnerAudienceInfo.prototype.commercePartner = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PartnerAudienceInfo.prototype, "_partnerAudienceSource", { + get: $util.oneOfGetter($oneOfFields = ["partnerAudienceSource"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PartnerAudienceInfo.prototype, "_commercePartner", { + get: $util.oneOfGetter($oneOfFields = ["commercePartner"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new PartnerAudienceInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {google.ads.datamanager.v1.IPartnerAudienceInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.PartnerAudienceInfo} PartnerAudienceInfo instance + */ + PartnerAudienceInfo.create = function create(properties) { + return new PartnerAudienceInfo(properties); + }; + + /** + * Encodes the specified PartnerAudienceInfo message. Does not implicitly {@link google.ads.datamanager.v1.PartnerAudienceInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {google.ads.datamanager.v1.IPartnerAudienceInfo} message PartnerAudienceInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartnerAudienceInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.partnerAudienceSource != null && Object.hasOwnProperty.call(message, "partnerAudienceSource")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.partnerAudienceSource); + if (message.commercePartner != null && Object.hasOwnProperty.call(message, "commercePartner")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.commercePartner); + return writer; + }; + + /** + * Encodes the specified PartnerAudienceInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PartnerAudienceInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {google.ads.datamanager.v1.IPartnerAudienceInfo} message PartnerAudienceInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PartnerAudienceInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PartnerAudienceInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.PartnerAudienceInfo} PartnerAudienceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartnerAudienceInfo.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.ads.datamanager.v1.PartnerAudienceInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.partnerAudienceSource = reader.int32(); + break; + } + case 2: { + message.commercePartner = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PartnerAudienceInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.PartnerAudienceInfo} PartnerAudienceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PartnerAudienceInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PartnerAudienceInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PartnerAudienceInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.partnerAudienceSource != null && message.hasOwnProperty("partnerAudienceSource")) { + properties._partnerAudienceSource = 1; + switch (message.partnerAudienceSource) { + default: + return "partnerAudienceSource: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + } + if (message.commercePartner != null && message.hasOwnProperty("commercePartner")) { + properties._commercePartner = 1; + if (!$util.isString(message.commercePartner)) + return "commercePartner: string expected"; + } + return null; + }; + + /** + * Creates a PartnerAudienceInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.PartnerAudienceInfo} PartnerAudienceInfo + */ + PartnerAudienceInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.PartnerAudienceInfo) + return object; + var message = new $root.google.ads.datamanager.v1.PartnerAudienceInfo(); + switch (object.partnerAudienceSource) { + default: + if (typeof object.partnerAudienceSource === "number") { + message.partnerAudienceSource = object.partnerAudienceSource; + break; + } + break; + case "PARTNER_AUDIENCE_SOURCE_UNSPECIFIED": + case 0: + message.partnerAudienceSource = 0; + break; + case "COMMERCE_AUDIENCE": + case 1: + message.partnerAudienceSource = 1; + break; + case "LINEAR_TV_AUDIENCE": + case 2: + message.partnerAudienceSource = 2; + break; + case "AGENCY_PROVIDER_AUDIENCE": + case 3: + message.partnerAudienceSource = 3; + break; + } + if (object.commercePartner != null) + message.commercePartner = String(object.commercePartner); + return message; + }; + + /** + * Creates a plain object from a PartnerAudienceInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {google.ads.datamanager.v1.PartnerAudienceInfo} message PartnerAudienceInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartnerAudienceInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.partnerAudienceSource != null && message.hasOwnProperty("partnerAudienceSource")) { + object.partnerAudienceSource = options.enums === String ? $root.google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource[message.partnerAudienceSource] === undefined ? message.partnerAudienceSource : $root.google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource[message.partnerAudienceSource] : message.partnerAudienceSource; + if (options.oneofs) + object._partnerAudienceSource = "partnerAudienceSource"; + } + if (message.commercePartner != null && message.hasOwnProperty("commercePartner")) { + object.commercePartner = message.commercePartner; + if (options.oneofs) + object._commercePartner = "commercePartner"; + } + return object; + }; + + /** + * Converts this PartnerAudienceInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @instance + * @returns {Object.} JSON object + */ + PartnerAudienceInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartnerAudienceInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.PartnerAudienceInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartnerAudienceInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.PartnerAudienceInfo"; + }; + + /** + * PartnerAudienceSource enum. + * @name google.ads.datamanager.v1.PartnerAudienceInfo.PartnerAudienceSource + * @enum {number} + * @property {number} PARTNER_AUDIENCE_SOURCE_UNSPECIFIED=0 PARTNER_AUDIENCE_SOURCE_UNSPECIFIED value + * @property {number} COMMERCE_AUDIENCE=1 COMMERCE_AUDIENCE value + * @property {number} LINEAR_TV_AUDIENCE=2 LINEAR_TV_AUDIENCE value + * @property {number} AGENCY_PROVIDER_AUDIENCE=3 AGENCY_PROVIDER_AUDIENCE value + */ + PartnerAudienceInfo.PartnerAudienceSource = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "PARTNER_AUDIENCE_SOURCE_UNSPECIFIED"] = 0; + values[valuesById[1] = "COMMERCE_AUDIENCE"] = 1; + values[valuesById[2] = "LINEAR_TV_AUDIENCE"] = 2; + values[valuesById[3] = "AGENCY_PROVIDER_AUDIENCE"] = 3; + return values; + })(); + + return PartnerAudienceInfo; + })(); + + v1.PseudonymousIdInfo = (function() { + + /** + * Properties of a PseudonymousIdInfo. + * @memberof google.ads.datamanager.v1 + * @interface IPseudonymousIdInfo + * @property {google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus|null} [syncStatus] PseudonymousIdInfo syncStatus + * @property {number|Long|null} [billableRecordCount] PseudonymousIdInfo billableRecordCount + */ + + /** + * Constructs a new PseudonymousIdInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a PseudonymousIdInfo. + * @implements IPseudonymousIdInfo + * @constructor + * @param {google.ads.datamanager.v1.IPseudonymousIdInfo=} [properties] Properties to set + */ + function PseudonymousIdInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PseudonymousIdInfo syncStatus. + * @member {google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus|null|undefined} syncStatus + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @instance + */ + PseudonymousIdInfo.prototype.syncStatus = null; + + /** + * PseudonymousIdInfo billableRecordCount. + * @member {number|Long|null|undefined} billableRecordCount + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @instance + */ + PseudonymousIdInfo.prototype.billableRecordCount = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PseudonymousIdInfo.prototype, "_syncStatus", { + get: $util.oneOfGetter($oneOfFields = ["syncStatus"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PseudonymousIdInfo.prototype, "_billableRecordCount", { + get: $util.oneOfGetter($oneOfFields = ["billableRecordCount"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new PseudonymousIdInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {google.ads.datamanager.v1.IPseudonymousIdInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.PseudonymousIdInfo} PseudonymousIdInfo instance + */ + PseudonymousIdInfo.create = function create(properties) { + return new PseudonymousIdInfo(properties); + }; + + /** + * Encodes the specified PseudonymousIdInfo message. Does not implicitly {@link google.ads.datamanager.v1.PseudonymousIdInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {google.ads.datamanager.v1.IPseudonymousIdInfo} message PseudonymousIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PseudonymousIdInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.syncStatus != null && Object.hasOwnProperty.call(message, "syncStatus")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.syncStatus); + if (message.billableRecordCount != null && Object.hasOwnProperty.call(message, "billableRecordCount")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.billableRecordCount); + return writer; + }; + + /** + * Encodes the specified PseudonymousIdInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.PseudonymousIdInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {google.ads.datamanager.v1.IPseudonymousIdInfo} message PseudonymousIdInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PseudonymousIdInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PseudonymousIdInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.PseudonymousIdInfo} PseudonymousIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PseudonymousIdInfo.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.ads.datamanager.v1.PseudonymousIdInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.syncStatus = reader.int32(); + break; + } + case 2: { + message.billableRecordCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PseudonymousIdInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.PseudonymousIdInfo} PseudonymousIdInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PseudonymousIdInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PseudonymousIdInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PseudonymousIdInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.syncStatus != null && message.hasOwnProperty("syncStatus")) { + properties._syncStatus = 1; + switch (message.syncStatus) { + default: + return "syncStatus: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + } + if (message.billableRecordCount != null && message.hasOwnProperty("billableRecordCount")) { + properties._billableRecordCount = 1; + if (!$util.isInteger(message.billableRecordCount) && !(message.billableRecordCount && $util.isInteger(message.billableRecordCount.low) && $util.isInteger(message.billableRecordCount.high))) + return "billableRecordCount: integer|Long expected"; + } + return null; + }; + + /** + * Creates a PseudonymousIdInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.PseudonymousIdInfo} PseudonymousIdInfo + */ + PseudonymousIdInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.PseudonymousIdInfo) + return object; + var message = new $root.google.ads.datamanager.v1.PseudonymousIdInfo(); + switch (object.syncStatus) { + default: + if (typeof object.syncStatus === "number") { + message.syncStatus = object.syncStatus; + break; + } + break; + case "SYNC_STATUS_UNSPECIFIED": + case 0: + message.syncStatus = 0; + break; + case "CREATED": + case 1: + message.syncStatus = 1; + break; + case "READY_FOR_USE": + case 2: + message.syncStatus = 2; + break; + case "FAILED": + case 3: + message.syncStatus = 3; + break; + } + if (object.billableRecordCount != null) + if ($util.Long) + (message.billableRecordCount = $util.Long.fromValue(object.billableRecordCount)).unsigned = false; + else if (typeof object.billableRecordCount === "string") + message.billableRecordCount = parseInt(object.billableRecordCount, 10); + else if (typeof object.billableRecordCount === "number") + message.billableRecordCount = object.billableRecordCount; + else if (typeof object.billableRecordCount === "object") + message.billableRecordCount = new $util.LongBits(object.billableRecordCount.low >>> 0, object.billableRecordCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a PseudonymousIdInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {google.ads.datamanager.v1.PseudonymousIdInfo} message PseudonymousIdInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PseudonymousIdInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.syncStatus != null && message.hasOwnProperty("syncStatus")) { + object.syncStatus = options.enums === String ? $root.google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus[message.syncStatus] === undefined ? message.syncStatus : $root.google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus[message.syncStatus] : message.syncStatus; + if (options.oneofs) + object._syncStatus = "syncStatus"; + } + if (message.billableRecordCount != null && message.hasOwnProperty("billableRecordCount")) { + if (typeof message.billableRecordCount === "number") + object.billableRecordCount = options.longs === String ? String(message.billableRecordCount) : message.billableRecordCount; + else + object.billableRecordCount = options.longs === String ? $util.Long.prototype.toString.call(message.billableRecordCount) : options.longs === Number ? new $util.LongBits(message.billableRecordCount.low >>> 0, message.billableRecordCount.high >>> 0).toNumber() : message.billableRecordCount; + if (options.oneofs) + object._billableRecordCount = "billableRecordCount"; + } + return object; + }; + + /** + * Converts this PseudonymousIdInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @instance + * @returns {Object.} JSON object + */ + PseudonymousIdInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PseudonymousIdInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.PseudonymousIdInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PseudonymousIdInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.PseudonymousIdInfo"; + }; + + /** + * SyncStatus enum. + * @name google.ads.datamanager.v1.PseudonymousIdInfo.SyncStatus + * @enum {number} + * @property {number} SYNC_STATUS_UNSPECIFIED=0 SYNC_STATUS_UNSPECIFIED value + * @property {number} CREATED=1 CREATED value + * @property {number} READY_FOR_USE=2 READY_FOR_USE value + * @property {number} FAILED=3 FAILED value + */ + PseudonymousIdInfo.SyncStatus = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "SYNC_STATUS_UNSPECIFIED"] = 0; + values[valuesById[1] = "CREATED"] = 1; + values[valuesById[2] = "READY_FOR_USE"] = 2; + values[valuesById[3] = "FAILED"] = 3; + return values; + })(); + + return PseudonymousIdInfo; + })(); + + /** + * DataSourceType enum. + * @name google.ads.datamanager.v1.DataSourceType + * @enum {number} + * @property {number} DATA_SOURCE_TYPE_UNSPECIFIED=0 DATA_SOURCE_TYPE_UNSPECIFIED value + * @property {number} DATA_SOURCE_TYPE_FIRST_PARTY=1 DATA_SOURCE_TYPE_FIRST_PARTY value + * @property {number} DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU=2 DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU value + * @property {number} DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE=3 DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE value + * @property {number} DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA=4 DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA value + */ + v1.DataSourceType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DATA_SOURCE_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "DATA_SOURCE_TYPE_FIRST_PARTY"] = 1; + values[valuesById[2] = "DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU"] = 2; + values[valuesById[3] = "DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE"] = 3; + values[valuesById[4] = "DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA"] = 4; + return values; + })(); + + v1.UserListDirectLicense = (function() { + + /** + * Properties of a UserListDirectLicense. + * @memberof google.ads.datamanager.v1 + * @interface IUserListDirectLicense + * @property {string|null} [name] UserListDirectLicense name + * @property {number|Long|null} [userListId] UserListDirectLicense userListId + * @property {string|null} [userListDisplayName] UserListDirectLicense userListDisplayName + * @property {google.ads.datamanager.v1.UserListLicenseClientAccountType|null} [clientAccountType] UserListDirectLicense clientAccountType + * @property {number|Long|null} [clientAccountId] UserListDirectLicense clientAccountId + * @property {string|null} [clientAccountDisplayName] UserListDirectLicense clientAccountDisplayName + * @property {google.ads.datamanager.v1.UserListLicenseStatus|null} [status] UserListDirectLicense status + * @property {google.ads.datamanager.v1.IUserListLicensePricing|null} [pricing] UserListDirectLicense pricing + * @property {Array.|null} [historicalPricings] UserListDirectLicense historicalPricings + * @property {google.ads.datamanager.v1.IUserListLicenseMetrics|null} [metrics] UserListDirectLicense metrics + */ + + /** + * Constructs a new UserListDirectLicense. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserListDirectLicense. + * @implements IUserListDirectLicense + * @constructor + * @param {google.ads.datamanager.v1.IUserListDirectLicense=} [properties] Properties to set + */ + function UserListDirectLicense(properties) { + this.historicalPricings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserListDirectLicense name. + * @member {string} name + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.name = ""; + + /** + * UserListDirectLicense userListId. + * @member {number|Long|null|undefined} userListId + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.userListId = null; + + /** + * UserListDirectLicense userListDisplayName. + * @member {string} userListDisplayName + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.userListDisplayName = ""; + + /** + * UserListDirectLicense clientAccountType. + * @member {google.ads.datamanager.v1.UserListLicenseClientAccountType|null|undefined} clientAccountType + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.clientAccountType = null; + + /** + * UserListDirectLicense clientAccountId. + * @member {number|Long|null|undefined} clientAccountId + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.clientAccountId = null; + + /** + * UserListDirectLicense clientAccountDisplayName. + * @member {string} clientAccountDisplayName + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.clientAccountDisplayName = ""; + + /** + * UserListDirectLicense status. + * @member {google.ads.datamanager.v1.UserListLicenseStatus|null|undefined} status + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.status = null; + + /** + * UserListDirectLicense pricing. + * @member {google.ads.datamanager.v1.IUserListLicensePricing|null|undefined} pricing + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.pricing = null; + + /** + * UserListDirectLicense historicalPricings. + * @member {Array.} historicalPricings + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.historicalPricings = $util.emptyArray; + + /** + * UserListDirectLicense metrics. + * @member {google.ads.datamanager.v1.IUserListLicenseMetrics|null|undefined} metrics + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + */ + UserListDirectLicense.prototype.metrics = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListDirectLicense.prototype, "_userListId", { + get: $util.oneOfGetter($oneOfFields = ["userListId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListDirectLicense.prototype, "_clientAccountType", { + get: $util.oneOfGetter($oneOfFields = ["clientAccountType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListDirectLicense.prototype, "_clientAccountId", { + get: $util.oneOfGetter($oneOfFields = ["clientAccountId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListDirectLicense.prototype, "_status", { + get: $util.oneOfGetter($oneOfFields = ["status"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UserListDirectLicense instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {google.ads.datamanager.v1.IUserListDirectLicense=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UserListDirectLicense} UserListDirectLicense instance + */ + UserListDirectLicense.create = function create(properties) { + return new UserListDirectLicense(properties); + }; + + /** + * Encodes the specified UserListDirectLicense message. Does not implicitly {@link google.ads.datamanager.v1.UserListDirectLicense.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {google.ads.datamanager.v1.IUserListDirectLicense} message UserListDirectLicense message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListDirectLicense.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.userListId != null && Object.hasOwnProperty.call(message, "userListId")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.userListId); + if (message.userListDisplayName != null && Object.hasOwnProperty.call(message, "userListDisplayName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.userListDisplayName); + if (message.clientAccountType != null && Object.hasOwnProperty.call(message, "clientAccountType")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.clientAccountType); + if (message.clientAccountId != null && Object.hasOwnProperty.call(message, "clientAccountId")) + writer.uint32(/* id 5, wireType 0 =*/40).int64(message.clientAccountId); + if (message.clientAccountDisplayName != null && Object.hasOwnProperty.call(message, "clientAccountDisplayName")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.clientAccountDisplayName); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.status); + if (message.pricing != null && Object.hasOwnProperty.call(message, "pricing")) + $root.google.ads.datamanager.v1.UserListLicensePricing.encode(message.pricing, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.historicalPricings != null && message.historicalPricings.length) + for (var i = 0; i < message.historicalPricings.length; ++i) + $root.google.ads.datamanager.v1.UserListLicensePricing.encode(message.historicalPricings[i], writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); + if (message.metrics != null && Object.hasOwnProperty.call(message, "metrics")) + $root.google.ads.datamanager.v1.UserListLicenseMetrics.encode(message.metrics, writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UserListDirectLicense message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListDirectLicense.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {google.ads.datamanager.v1.IUserListDirectLicense} message UserListDirectLicense message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListDirectLicense.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a UserListDirectLicense message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UserListDirectLicense} UserListDirectLicense + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListDirectLicense.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.ads.datamanager.v1.UserListDirectLicense(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.userListId = reader.int64(); + break; + } + case 3: { + message.userListDisplayName = reader.string(); + break; + } + case 4: { + message.clientAccountType = reader.int32(); + break; + } + case 5: { + message.clientAccountId = reader.int64(); + break; + } + case 6: { + message.clientAccountDisplayName = reader.string(); + break; + } + case 7: { + message.status = reader.int32(); + break; + } + case 8: { + message.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.decode(reader, reader.uint32()); + break; + } + case 9: { + if (!(message.historicalPricings && message.historicalPricings.length)) + message.historicalPricings = []; + message.historicalPricings.push($root.google.ads.datamanager.v1.UserListLicensePricing.decode(reader, reader.uint32())); + break; + } + case 10: { + message.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a UserListDirectLicense message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UserListDirectLicense} UserListDirectLicense + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListDirectLicense.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a UserListDirectLicense message. + * @function verify + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UserListDirectLicense.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.userListId != null && message.hasOwnProperty("userListId")) { + properties._userListId = 1; + if (!$util.isInteger(message.userListId) && !(message.userListId && $util.isInteger(message.userListId.low) && $util.isInteger(message.userListId.high))) + return "userListId: integer|Long expected"; + } + if (message.userListDisplayName != null && message.hasOwnProperty("userListDisplayName")) + if (!$util.isString(message.userListDisplayName)) + return "userListDisplayName: string expected"; + if (message.clientAccountType != null && message.hasOwnProperty("clientAccountType")) { + properties._clientAccountType = 1; + switch (message.clientAccountType) { + default: + return "clientAccountType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + } + if (message.clientAccountId != null && message.hasOwnProperty("clientAccountId")) { + properties._clientAccountId = 1; + if (!$util.isInteger(message.clientAccountId) && !(message.clientAccountId && $util.isInteger(message.clientAccountId.low) && $util.isInteger(message.clientAccountId.high))) + return "clientAccountId: integer|Long expected"; + } + if (message.clientAccountDisplayName != null && message.hasOwnProperty("clientAccountDisplayName")) + if (!$util.isString(message.clientAccountDisplayName)) + return "clientAccountDisplayName: string expected"; + if (message.status != null && message.hasOwnProperty("status")) { + properties._status = 1; + switch (message.status) { + default: + return "status: enum value expected"; + case 0: + case 1: + case 2: + break; + } + } + if (message.pricing != null && message.hasOwnProperty("pricing")) { + var error = $root.google.ads.datamanager.v1.UserListLicensePricing.verify(message.pricing); + if (error) + return "pricing." + error; + } + if (message.historicalPricings != null && message.hasOwnProperty("historicalPricings")) { + if (!Array.isArray(message.historicalPricings)) + return "historicalPricings: array expected"; + for (var i = 0; i < message.historicalPricings.length; ++i) { + var error = $root.google.ads.datamanager.v1.UserListLicensePricing.verify(message.historicalPricings[i]); + if (error) + return "historicalPricings." + error; + } + } + if (message.metrics != null && message.hasOwnProperty("metrics")) { + var error = $root.google.ads.datamanager.v1.UserListLicenseMetrics.verify(message.metrics); + if (error) + return "metrics." + error; + } + return null; + }; + + /** + * Creates a UserListDirectLicense message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UserListDirectLicense} UserListDirectLicense + */ + UserListDirectLicense.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UserListDirectLicense) + return object; + var message = new $root.google.ads.datamanager.v1.UserListDirectLicense(); + if (object.name != null) + message.name = String(object.name); + if (object.userListId != null) + if ($util.Long) + (message.userListId = $util.Long.fromValue(object.userListId)).unsigned = false; + else if (typeof object.userListId === "string") + message.userListId = parseInt(object.userListId, 10); + else if (typeof object.userListId === "number") + message.userListId = object.userListId; + else if (typeof object.userListId === "object") + message.userListId = new $util.LongBits(object.userListId.low >>> 0, object.userListId.high >>> 0).toNumber(); + if (object.userListDisplayName != null) + message.userListDisplayName = String(object.userListDisplayName); + switch (object.clientAccountType) { + default: + if (typeof object.clientAccountType === "number") { + message.clientAccountType = object.clientAccountType; + break; + } + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN": + case 0: + message.clientAccountType = 0; + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_ADS": + case 1: + message.clientAccountType = 1; + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_PARTNER": + case 2: + message.clientAccountType = 2; + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_ADVERTISER": + case 3: + message.clientAccountType = 3; + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_AD_MANAGER_AUDIENCE_LINK": + case 4: + message.clientAccountType = 4; + break; + } + if (object.clientAccountId != null) + if ($util.Long) + (message.clientAccountId = $util.Long.fromValue(object.clientAccountId)).unsigned = false; + else if (typeof object.clientAccountId === "string") + message.clientAccountId = parseInt(object.clientAccountId, 10); + else if (typeof object.clientAccountId === "number") + message.clientAccountId = object.clientAccountId; + else if (typeof object.clientAccountId === "object") + message.clientAccountId = new $util.LongBits(object.clientAccountId.low >>> 0, object.clientAccountId.high >>> 0).toNumber(); + if (object.clientAccountDisplayName != null) + message.clientAccountDisplayName = String(object.clientAccountDisplayName); + switch (object.status) { + default: + if (typeof object.status === "number") { + message.status = object.status; + break; + } + break; + case "USER_LIST_LICENSE_STATUS_UNSPECIFIED": + case 0: + message.status = 0; + break; + case "USER_LIST_LICENSE_STATUS_ENABLED": + case 1: + message.status = 1; + break; + case "USER_LIST_LICENSE_STATUS_DISABLED": + case 2: + message.status = 2; + break; + } + if (object.pricing != null) { + if (typeof object.pricing !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListDirectLicense.pricing: object expected"); + message.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.fromObject(object.pricing); + } + if (object.historicalPricings) { + if (!Array.isArray(object.historicalPricings)) + throw TypeError(".google.ads.datamanager.v1.UserListDirectLicense.historicalPricings: array expected"); + message.historicalPricings = []; + for (var i = 0; i < object.historicalPricings.length; ++i) { + if (typeof object.historicalPricings[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListDirectLicense.historicalPricings: object expected"); + message.historicalPricings[i] = $root.google.ads.datamanager.v1.UserListLicensePricing.fromObject(object.historicalPricings[i]); + } + } + if (object.metrics != null) { + if (typeof object.metrics !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListDirectLicense.metrics: object expected"); + message.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.fromObject(object.metrics); + } + return message; + }; + + /** + * Creates a plain object from a UserListDirectLicense message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {google.ads.datamanager.v1.UserListDirectLicense} message UserListDirectLicense + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserListDirectLicense.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.historicalPricings = []; + if (options.defaults) { + object.name = ""; + object.userListDisplayName = ""; + object.clientAccountDisplayName = ""; + object.pricing = null; + object.metrics = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.userListId != null && message.hasOwnProperty("userListId")) { + if (typeof message.userListId === "number") + object.userListId = options.longs === String ? String(message.userListId) : message.userListId; + else + object.userListId = options.longs === String ? $util.Long.prototype.toString.call(message.userListId) : options.longs === Number ? new $util.LongBits(message.userListId.low >>> 0, message.userListId.high >>> 0).toNumber() : message.userListId; + if (options.oneofs) + object._userListId = "userListId"; + } + if (message.userListDisplayName != null && message.hasOwnProperty("userListDisplayName")) + object.userListDisplayName = message.userListDisplayName; + if (message.clientAccountType != null && message.hasOwnProperty("clientAccountType")) { + object.clientAccountType = options.enums === String ? $root.google.ads.datamanager.v1.UserListLicenseClientAccountType[message.clientAccountType] === undefined ? message.clientAccountType : $root.google.ads.datamanager.v1.UserListLicenseClientAccountType[message.clientAccountType] : message.clientAccountType; + if (options.oneofs) + object._clientAccountType = "clientAccountType"; + } + if (message.clientAccountId != null && message.hasOwnProperty("clientAccountId")) { + if (typeof message.clientAccountId === "number") + object.clientAccountId = options.longs === String ? String(message.clientAccountId) : message.clientAccountId; + else + object.clientAccountId = options.longs === String ? $util.Long.prototype.toString.call(message.clientAccountId) : options.longs === Number ? new $util.LongBits(message.clientAccountId.low >>> 0, message.clientAccountId.high >>> 0).toNumber() : message.clientAccountId; + if (options.oneofs) + object._clientAccountId = "clientAccountId"; + } + if (message.clientAccountDisplayName != null && message.hasOwnProperty("clientAccountDisplayName")) + object.clientAccountDisplayName = message.clientAccountDisplayName; + if (message.status != null && message.hasOwnProperty("status")) { + object.status = options.enums === String ? $root.google.ads.datamanager.v1.UserListLicenseStatus[message.status] === undefined ? message.status : $root.google.ads.datamanager.v1.UserListLicenseStatus[message.status] : message.status; + if (options.oneofs) + object._status = "status"; + } + if (message.pricing != null && message.hasOwnProperty("pricing")) + object.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.toObject(message.pricing, options); + if (message.historicalPricings && message.historicalPricings.length) { + object.historicalPricings = []; + for (var j = 0; j < message.historicalPricings.length; ++j) + object.historicalPricings[j] = $root.google.ads.datamanager.v1.UserListLicensePricing.toObject(message.historicalPricings[j], options); + } + if (message.metrics != null && message.hasOwnProperty("metrics")) + object.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.toObject(message.metrics, options); + return object; + }; + + /** + * Converts this UserListDirectLicense to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @instance + * @returns {Object.} JSON object + */ + UserListDirectLicense.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserListDirectLicense + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UserListDirectLicense + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserListDirectLicense.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UserListDirectLicense"; + }; + + return UserListDirectLicense; + })(); + + /** + * UserListLicenseClientAccountType enum. + * @name google.ads.datamanager.v1.UserListLicenseClientAccountType + * @enum {number} + * @property {number} USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN=0 USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN value + * @property {number} USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_ADS=1 USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_ADS value + * @property {number} USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_PARTNER=2 USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_PARTNER value + * @property {number} USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_ADVERTISER=3 USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_ADVERTISER value + * @property {number} USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_AD_MANAGER_AUDIENCE_LINK=4 USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_AD_MANAGER_AUDIENCE_LINK value + */ + v1.UserListLicenseClientAccountType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN"] = 0; + values[valuesById[1] = "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_ADS"] = 1; + values[valuesById[2] = "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_PARTNER"] = 2; + values[valuesById[3] = "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_ADVERTISER"] = 3; + values[valuesById[4] = "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_AD_MANAGER_AUDIENCE_LINK"] = 4; + return values; + })(); + + v1.UserListLicenseMetrics = (function() { + + /** + * Properties of a UserListLicenseMetrics. + * @memberof google.ads.datamanager.v1 + * @interface IUserListLicenseMetrics + * @property {number|Long|null} [clickCount] UserListLicenseMetrics clickCount + * @property {number|Long|null} [impressionCount] UserListLicenseMetrics impressionCount + * @property {number|Long|null} [revenueUsdMicros] UserListLicenseMetrics revenueUsdMicros + * @property {number|Long|null} [startDate] UserListLicenseMetrics startDate + * @property {number|Long|null} [endDate] UserListLicenseMetrics endDate + */ + + /** + * Constructs a new UserListLicenseMetrics. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserListLicenseMetrics. + * @implements IUserListLicenseMetrics + * @constructor + * @param {google.ads.datamanager.v1.IUserListLicenseMetrics=} [properties] Properties to set + */ + function UserListLicenseMetrics(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserListLicenseMetrics clickCount. + * @member {number|Long} clickCount + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @instance + */ + UserListLicenseMetrics.prototype.clickCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UserListLicenseMetrics impressionCount. + * @member {number|Long} impressionCount + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @instance + */ + UserListLicenseMetrics.prototype.impressionCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UserListLicenseMetrics revenueUsdMicros. + * @member {number|Long} revenueUsdMicros + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @instance + */ + UserListLicenseMetrics.prototype.revenueUsdMicros = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UserListLicenseMetrics startDate. + * @member {number|Long} startDate + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @instance + */ + UserListLicenseMetrics.prototype.startDate = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UserListLicenseMetrics endDate. + * @member {number|Long} endDate + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @instance + */ + UserListLicenseMetrics.prototype.endDate = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new UserListLicenseMetrics instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {google.ads.datamanager.v1.IUserListLicenseMetrics=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UserListLicenseMetrics} UserListLicenseMetrics instance + */ + UserListLicenseMetrics.create = function create(properties) { + return new UserListLicenseMetrics(properties); + }; + + /** + * Encodes the specified UserListLicenseMetrics message. Does not implicitly {@link google.ads.datamanager.v1.UserListLicenseMetrics.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {google.ads.datamanager.v1.IUserListLicenseMetrics} message UserListLicenseMetrics message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListLicenseMetrics.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.clickCount != null && Object.hasOwnProperty.call(message, "clickCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.clickCount); + if (message.impressionCount != null && Object.hasOwnProperty.call(message, "impressionCount")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.impressionCount); + if (message.revenueUsdMicros != null && Object.hasOwnProperty.call(message, "revenueUsdMicros")) + writer.uint32(/* id 3, wireType 0 =*/24).int64(message.revenueUsdMicros); + if (message.startDate != null && Object.hasOwnProperty.call(message, "startDate")) + writer.uint32(/* id 4, wireType 0 =*/32).int64(message.startDate); + if (message.endDate != null && Object.hasOwnProperty.call(message, "endDate")) + writer.uint32(/* id 5, wireType 0 =*/40).int64(message.endDate); + return writer; + }; + + /** + * Encodes the specified UserListLicenseMetrics message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListLicenseMetrics.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {google.ads.datamanager.v1.IUserListLicenseMetrics} message UserListLicenseMetrics message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListLicenseMetrics.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a UserListLicenseMetrics message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UserListLicenseMetrics} UserListLicenseMetrics + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListLicenseMetrics.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.ads.datamanager.v1.UserListLicenseMetrics(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.clickCount = reader.int64(); + break; + } + case 2: { + message.impressionCount = reader.int64(); + break; + } + case 3: { + message.revenueUsdMicros = reader.int64(); + break; + } + case 4: { + message.startDate = reader.int64(); + break; + } + case 5: { + message.endDate = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a UserListLicenseMetrics message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UserListLicenseMetrics} UserListLicenseMetrics + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListLicenseMetrics.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a UserListLicenseMetrics message. + * @function verify + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UserListLicenseMetrics.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.clickCount != null && message.hasOwnProperty("clickCount")) + if (!$util.isInteger(message.clickCount) && !(message.clickCount && $util.isInteger(message.clickCount.low) && $util.isInteger(message.clickCount.high))) + return "clickCount: integer|Long expected"; + if (message.impressionCount != null && message.hasOwnProperty("impressionCount")) + if (!$util.isInteger(message.impressionCount) && !(message.impressionCount && $util.isInteger(message.impressionCount.low) && $util.isInteger(message.impressionCount.high))) + return "impressionCount: integer|Long expected"; + if (message.revenueUsdMicros != null && message.hasOwnProperty("revenueUsdMicros")) + if (!$util.isInteger(message.revenueUsdMicros) && !(message.revenueUsdMicros && $util.isInteger(message.revenueUsdMicros.low) && $util.isInteger(message.revenueUsdMicros.high))) + return "revenueUsdMicros: integer|Long expected"; + if (message.startDate != null && message.hasOwnProperty("startDate")) + if (!$util.isInteger(message.startDate) && !(message.startDate && $util.isInteger(message.startDate.low) && $util.isInteger(message.startDate.high))) + return "startDate: integer|Long expected"; + if (message.endDate != null && message.hasOwnProperty("endDate")) + if (!$util.isInteger(message.endDate) && !(message.endDate && $util.isInteger(message.endDate.low) && $util.isInteger(message.endDate.high))) + return "endDate: integer|Long expected"; + return null; + }; + + /** + * Creates a UserListLicenseMetrics message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UserListLicenseMetrics} UserListLicenseMetrics + */ + UserListLicenseMetrics.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UserListLicenseMetrics) + return object; + var message = new $root.google.ads.datamanager.v1.UserListLicenseMetrics(); + if (object.clickCount != null) + if ($util.Long) + (message.clickCount = $util.Long.fromValue(object.clickCount)).unsigned = false; + else if (typeof object.clickCount === "string") + message.clickCount = parseInt(object.clickCount, 10); + else if (typeof object.clickCount === "number") + message.clickCount = object.clickCount; + else if (typeof object.clickCount === "object") + message.clickCount = new $util.LongBits(object.clickCount.low >>> 0, object.clickCount.high >>> 0).toNumber(); + if (object.impressionCount != null) + if ($util.Long) + (message.impressionCount = $util.Long.fromValue(object.impressionCount)).unsigned = false; + else if (typeof object.impressionCount === "string") + message.impressionCount = parseInt(object.impressionCount, 10); + else if (typeof object.impressionCount === "number") + message.impressionCount = object.impressionCount; + else if (typeof object.impressionCount === "object") + message.impressionCount = new $util.LongBits(object.impressionCount.low >>> 0, object.impressionCount.high >>> 0).toNumber(); + if (object.revenueUsdMicros != null) + if ($util.Long) + (message.revenueUsdMicros = $util.Long.fromValue(object.revenueUsdMicros)).unsigned = false; + else if (typeof object.revenueUsdMicros === "string") + message.revenueUsdMicros = parseInt(object.revenueUsdMicros, 10); + else if (typeof object.revenueUsdMicros === "number") + message.revenueUsdMicros = object.revenueUsdMicros; + else if (typeof object.revenueUsdMicros === "object") + message.revenueUsdMicros = new $util.LongBits(object.revenueUsdMicros.low >>> 0, object.revenueUsdMicros.high >>> 0).toNumber(); + if (object.startDate != null) + if ($util.Long) + (message.startDate = $util.Long.fromValue(object.startDate)).unsigned = false; + else if (typeof object.startDate === "string") + message.startDate = parseInt(object.startDate, 10); + else if (typeof object.startDate === "number") + message.startDate = object.startDate; + else if (typeof object.startDate === "object") + message.startDate = new $util.LongBits(object.startDate.low >>> 0, object.startDate.high >>> 0).toNumber(); + if (object.endDate != null) + if ($util.Long) + (message.endDate = $util.Long.fromValue(object.endDate)).unsigned = false; + else if (typeof object.endDate === "string") + message.endDate = parseInt(object.endDate, 10); + else if (typeof object.endDate === "number") + message.endDate = object.endDate; + else if (typeof object.endDate === "object") + message.endDate = new $util.LongBits(object.endDate.low >>> 0, object.endDate.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a UserListLicenseMetrics message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {google.ads.datamanager.v1.UserListLicenseMetrics} message UserListLicenseMetrics + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserListLicenseMetrics.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.clickCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.clickCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.impressionCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.impressionCount = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.revenueUsdMicros = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.revenueUsdMicros = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.startDate = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.startDate = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.endDate = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.endDate = options.longs === String ? "0" : 0; + } + if (message.clickCount != null && message.hasOwnProperty("clickCount")) + if (typeof message.clickCount === "number") + object.clickCount = options.longs === String ? String(message.clickCount) : message.clickCount; + else + object.clickCount = options.longs === String ? $util.Long.prototype.toString.call(message.clickCount) : options.longs === Number ? new $util.LongBits(message.clickCount.low >>> 0, message.clickCount.high >>> 0).toNumber() : message.clickCount; + if (message.impressionCount != null && message.hasOwnProperty("impressionCount")) + if (typeof message.impressionCount === "number") + object.impressionCount = options.longs === String ? String(message.impressionCount) : message.impressionCount; + else + object.impressionCount = options.longs === String ? $util.Long.prototype.toString.call(message.impressionCount) : options.longs === Number ? new $util.LongBits(message.impressionCount.low >>> 0, message.impressionCount.high >>> 0).toNumber() : message.impressionCount; + if (message.revenueUsdMicros != null && message.hasOwnProperty("revenueUsdMicros")) + if (typeof message.revenueUsdMicros === "number") + object.revenueUsdMicros = options.longs === String ? String(message.revenueUsdMicros) : message.revenueUsdMicros; + else + object.revenueUsdMicros = options.longs === String ? $util.Long.prototype.toString.call(message.revenueUsdMicros) : options.longs === Number ? new $util.LongBits(message.revenueUsdMicros.low >>> 0, message.revenueUsdMicros.high >>> 0).toNumber() : message.revenueUsdMicros; + if (message.startDate != null && message.hasOwnProperty("startDate")) + if (typeof message.startDate === "number") + object.startDate = options.longs === String ? String(message.startDate) : message.startDate; + else + object.startDate = options.longs === String ? $util.Long.prototype.toString.call(message.startDate) : options.longs === Number ? new $util.LongBits(message.startDate.low >>> 0, message.startDate.high >>> 0).toNumber() : message.startDate; + if (message.endDate != null && message.hasOwnProperty("endDate")) + if (typeof message.endDate === "number") + object.endDate = options.longs === String ? String(message.endDate) : message.endDate; + else + object.endDate = options.longs === String ? $util.Long.prototype.toString.call(message.endDate) : options.longs === Number ? new $util.LongBits(message.endDate.low >>> 0, message.endDate.high >>> 0).toNumber() : message.endDate; + return object; + }; + + /** + * Converts this UserListLicenseMetrics to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @instance + * @returns {Object.} JSON object + */ + UserListLicenseMetrics.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserListLicenseMetrics + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UserListLicenseMetrics + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserListLicenseMetrics.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UserListLicenseMetrics"; + }; + + return UserListLicenseMetrics; + })(); + + v1.UserListLicensePricing = (function() { + + /** + * Properties of a UserListLicensePricing. + * @memberof google.ads.datamanager.v1 + * @interface IUserListLicensePricing + * @property {number|Long|null} [pricingId] UserListLicensePricing pricingId + * @property {number|Long|null} [costMicros] UserListLicensePricing costMicros + * @property {string|null} [currencyCode] UserListLicensePricing currencyCode + * @property {google.protobuf.ITimestamp|null} [startTime] UserListLicensePricing startTime + * @property {google.protobuf.ITimestamp|null} [endTime] UserListLicensePricing endTime + * @property {boolean|null} [pricingActive] UserListLicensePricing pricingActive + * @property {google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState|null} [buyerApprovalState] UserListLicensePricing buyerApprovalState + * @property {google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType|null} [costType] UserListLicensePricing costType + * @property {number|Long|null} [maxCostMicros] UserListLicensePricing maxCostMicros + */ + + /** + * Constructs a new UserListLicensePricing. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserListLicensePricing. + * @implements IUserListLicensePricing + * @constructor + * @param {google.ads.datamanager.v1.IUserListLicensePricing=} [properties] Properties to set + */ + function UserListLicensePricing(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserListLicensePricing pricingId. + * @member {number|Long} pricingId + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.pricingId = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UserListLicensePricing costMicros. + * @member {number|Long|null|undefined} costMicros + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.costMicros = null; + + /** + * UserListLicensePricing currencyCode. + * @member {string|null|undefined} currencyCode + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.currencyCode = null; + + /** + * UserListLicensePricing startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.startTime = null; + + /** + * UserListLicensePricing endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.endTime = null; + + /** + * UserListLicensePricing pricingActive. + * @member {boolean} pricingActive + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.pricingActive = false; + + /** + * UserListLicensePricing buyerApprovalState. + * @member {google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState} buyerApprovalState + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.buyerApprovalState = 0; + + /** + * UserListLicensePricing costType. + * @member {google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType|null|undefined} costType + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.costType = null; + + /** + * UserListLicensePricing maxCostMicros. + * @member {number|Long|null|undefined} maxCostMicros + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + */ + UserListLicensePricing.prototype.maxCostMicros = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListLicensePricing.prototype, "_costMicros", { + get: $util.oneOfGetter($oneOfFields = ["costMicros"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListLicensePricing.prototype, "_currencyCode", { + get: $util.oneOfGetter($oneOfFields = ["currencyCode"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListLicensePricing.prototype, "_costType", { + get: $util.oneOfGetter($oneOfFields = ["costType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListLicensePricing.prototype, "_maxCostMicros", { + get: $util.oneOfGetter($oneOfFields = ["maxCostMicros"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UserListLicensePricing instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {google.ads.datamanager.v1.IUserListLicensePricing=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UserListLicensePricing} UserListLicensePricing instance + */ + UserListLicensePricing.create = function create(properties) { + return new UserListLicensePricing(properties); + }; + + /** + * Encodes the specified UserListLicensePricing message. Does not implicitly {@link google.ads.datamanager.v1.UserListLicensePricing.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {google.ads.datamanager.v1.IUserListLicensePricing} message UserListLicensePricing message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListLicensePricing.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.pricingId != null && Object.hasOwnProperty.call(message, "pricingId")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.pricingId); + if (message.costMicros != null && Object.hasOwnProperty.call(message, "costMicros")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.costMicros); + if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) + $root.google.protobuf.Timestamp.encode(message.startTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) + $root.google.protobuf.Timestamp.encode(message.endTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.pricingActive != null && Object.hasOwnProperty.call(message, "pricingActive")) + writer.uint32(/* id 5, wireType 0 =*/40).bool(message.pricingActive); + if (message.buyerApprovalState != null && Object.hasOwnProperty.call(message, "buyerApprovalState")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.buyerApprovalState); + if (message.costType != null && Object.hasOwnProperty.call(message, "costType")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.costType); + if (message.maxCostMicros != null && Object.hasOwnProperty.call(message, "maxCostMicros")) + writer.uint32(/* id 8, wireType 0 =*/64).int64(message.maxCostMicros); + if (message.currencyCode != null && Object.hasOwnProperty.call(message, "currencyCode")) + writer.uint32(/* id 9, wireType 2 =*/74).string(message.currencyCode); + return writer; + }; + + /** + * Encodes the specified UserListLicensePricing message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListLicensePricing.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {google.ads.datamanager.v1.IUserListLicensePricing} message UserListLicensePricing message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListLicensePricing.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a UserListLicensePricing message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UserListLicensePricing} UserListLicensePricing + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListLicensePricing.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.ads.datamanager.v1.UserListLicensePricing(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.pricingId = reader.int64(); + break; + } + case 2: { + message.costMicros = reader.int64(); + break; + } + case 9: { + message.currencyCode = reader.string(); + break; + } + case 3: { + message.startTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 4: { + message.endTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); + break; + } + case 5: { + message.pricingActive = reader.bool(); + break; + } + case 6: { + message.buyerApprovalState = reader.int32(); + break; + } + case 7: { + message.costType = reader.int32(); + break; + } + case 8: { + message.maxCostMicros = reader.int64(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a UserListLicensePricing message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UserListLicensePricing} UserListLicensePricing + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListLicensePricing.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a UserListLicensePricing message. + * @function verify + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UserListLicensePricing.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.pricingId != null && message.hasOwnProperty("pricingId")) + if (!$util.isInteger(message.pricingId) && !(message.pricingId && $util.isInteger(message.pricingId.low) && $util.isInteger(message.pricingId.high))) + return "pricingId: integer|Long expected"; + if (message.costMicros != null && message.hasOwnProperty("costMicros")) { + properties._costMicros = 1; + if (!$util.isInteger(message.costMicros) && !(message.costMicros && $util.isInteger(message.costMicros.low) && $util.isInteger(message.costMicros.high))) + return "costMicros: integer|Long expected"; + } + if (message.currencyCode != null && message.hasOwnProperty("currencyCode")) { + properties._currencyCode = 1; + if (!$util.isString(message.currencyCode)) + return "currencyCode: string expected"; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.startTime); + if (error) + return "startTime." + error; + } + if (message.endTime != null && message.hasOwnProperty("endTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.endTime); + if (error) + return "endTime." + error; + } + if (message.pricingActive != null && message.hasOwnProperty("pricingActive")) + if (typeof message.pricingActive !== "boolean") + return "pricingActive: boolean expected"; + if (message.buyerApprovalState != null && message.hasOwnProperty("buyerApprovalState")) + switch (message.buyerApprovalState) { + default: + return "buyerApprovalState: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.costType != null && message.hasOwnProperty("costType")) { + properties._costType = 1; + switch (message.costType) { + default: + return "costType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + } + if (message.maxCostMicros != null && message.hasOwnProperty("maxCostMicros")) { + properties._maxCostMicros = 1; + if (!$util.isInteger(message.maxCostMicros) && !(message.maxCostMicros && $util.isInteger(message.maxCostMicros.low) && $util.isInteger(message.maxCostMicros.high))) + return "maxCostMicros: integer|Long expected"; + } + return null; + }; + + /** + * Creates a UserListLicensePricing message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UserListLicensePricing} UserListLicensePricing + */ + UserListLicensePricing.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UserListLicensePricing) + return object; + var message = new $root.google.ads.datamanager.v1.UserListLicensePricing(); + if (object.pricingId != null) + if ($util.Long) + (message.pricingId = $util.Long.fromValue(object.pricingId)).unsigned = false; + else if (typeof object.pricingId === "string") + message.pricingId = parseInt(object.pricingId, 10); + else if (typeof object.pricingId === "number") + message.pricingId = object.pricingId; + else if (typeof object.pricingId === "object") + message.pricingId = new $util.LongBits(object.pricingId.low >>> 0, object.pricingId.high >>> 0).toNumber(); + if (object.costMicros != null) + if ($util.Long) + (message.costMicros = $util.Long.fromValue(object.costMicros)).unsigned = false; + else if (typeof object.costMicros === "string") + message.costMicros = parseInt(object.costMicros, 10); + else if (typeof object.costMicros === "number") + message.costMicros = object.costMicros; + else if (typeof object.costMicros === "object") + message.costMicros = new $util.LongBits(object.costMicros.low >>> 0, object.costMicros.high >>> 0).toNumber(); + if (object.currencyCode != null) + message.currencyCode = String(object.currencyCode); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListLicensePricing.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListLicensePricing.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + if (object.pricingActive != null) + message.pricingActive = Boolean(object.pricingActive); + switch (object.buyerApprovalState) { + default: + if (typeof object.buyerApprovalState === "number") { + message.buyerApprovalState = object.buyerApprovalState; + break; + } + break; + case "USER_LIST_PRICING_BUYER_APPROVAL_STATE_UNSPECIFIED": + case 0: + message.buyerApprovalState = 0; + break; + case "PENDING": + case 1: + message.buyerApprovalState = 1; + break; + case "APPROVED": + case 2: + message.buyerApprovalState = 2; + break; + case "REJECTED": + case 3: + message.buyerApprovalState = 3; + break; + } + switch (object.costType) { + default: + if (typeof object.costType === "number") { + message.costType = object.costType; + break; + } + break; + case "USER_LIST_PRICING_COST_TYPE_UNSPECIFIED": + case 0: + message.costType = 0; + break; + case "CPC": + case 1: + message.costType = 1; + break; + case "CPM": + case 2: + message.costType = 2; + break; + case "MEDIA_SHARE": + case 3: + message.costType = 3; + break; + } + if (object.maxCostMicros != null) + if ($util.Long) + (message.maxCostMicros = $util.Long.fromValue(object.maxCostMicros)).unsigned = false; + else if (typeof object.maxCostMicros === "string") + message.maxCostMicros = parseInt(object.maxCostMicros, 10); + else if (typeof object.maxCostMicros === "number") + message.maxCostMicros = object.maxCostMicros; + else if (typeof object.maxCostMicros === "object") + message.maxCostMicros = new $util.LongBits(object.maxCostMicros.low >>> 0, object.maxCostMicros.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a UserListLicensePricing message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {google.ads.datamanager.v1.UserListLicensePricing} message UserListLicensePricing + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserListLicensePricing.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.pricingId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.pricingId = options.longs === String ? "0" : 0; + object.startTime = null; + object.endTime = null; + object.pricingActive = false; + object.buyerApprovalState = options.enums === String ? "USER_LIST_PRICING_BUYER_APPROVAL_STATE_UNSPECIFIED" : 0; + } + if (message.pricingId != null && message.hasOwnProperty("pricingId")) + if (typeof message.pricingId === "number") + object.pricingId = options.longs === String ? String(message.pricingId) : message.pricingId; + else + object.pricingId = options.longs === String ? $util.Long.prototype.toString.call(message.pricingId) : options.longs === Number ? new $util.LongBits(message.pricingId.low >>> 0, message.pricingId.high >>> 0).toNumber() : message.pricingId; + if (message.costMicros != null && message.hasOwnProperty("costMicros")) { + if (typeof message.costMicros === "number") + object.costMicros = options.longs === String ? String(message.costMicros) : message.costMicros; + else + object.costMicros = options.longs === String ? $util.Long.prototype.toString.call(message.costMicros) : options.longs === Number ? new $util.LongBits(message.costMicros.low >>> 0, message.costMicros.high >>> 0).toNumber() : message.costMicros; + if (options.oneofs) + object._costMicros = "costMicros"; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.pricingActive != null && message.hasOwnProperty("pricingActive")) + object.pricingActive = message.pricingActive; + if (message.buyerApprovalState != null && message.hasOwnProperty("buyerApprovalState")) + object.buyerApprovalState = options.enums === String ? $root.google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState[message.buyerApprovalState] === undefined ? message.buyerApprovalState : $root.google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState[message.buyerApprovalState] : message.buyerApprovalState; + if (message.costType != null && message.hasOwnProperty("costType")) { + object.costType = options.enums === String ? $root.google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType[message.costType] === undefined ? message.costType : $root.google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType[message.costType] : message.costType; + if (options.oneofs) + object._costType = "costType"; + } + if (message.maxCostMicros != null && message.hasOwnProperty("maxCostMicros")) { + if (typeof message.maxCostMicros === "number") + object.maxCostMicros = options.longs === String ? String(message.maxCostMicros) : message.maxCostMicros; + else + object.maxCostMicros = options.longs === String ? $util.Long.prototype.toString.call(message.maxCostMicros) : options.longs === Number ? new $util.LongBits(message.maxCostMicros.low >>> 0, message.maxCostMicros.high >>> 0).toNumber() : message.maxCostMicros; + if (options.oneofs) + object._maxCostMicros = "maxCostMicros"; + } + if (message.currencyCode != null && message.hasOwnProperty("currencyCode")) { + object.currencyCode = message.currencyCode; + if (options.oneofs) + object._currencyCode = "currencyCode"; + } + return object; + }; + + /** + * Converts this UserListLicensePricing to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @instance + * @returns {Object.} JSON object + */ + UserListLicensePricing.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserListLicensePricing + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UserListLicensePricing + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserListLicensePricing.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UserListLicensePricing"; + }; + + /** + * UserListPricingBuyerApprovalState enum. + * @name google.ads.datamanager.v1.UserListLicensePricing.UserListPricingBuyerApprovalState + * @enum {number} + * @property {number} USER_LIST_PRICING_BUYER_APPROVAL_STATE_UNSPECIFIED=0 USER_LIST_PRICING_BUYER_APPROVAL_STATE_UNSPECIFIED value + * @property {number} PENDING=1 PENDING value + * @property {number} APPROVED=2 APPROVED value + * @property {number} REJECTED=3 REJECTED value + */ + UserListLicensePricing.UserListPricingBuyerApprovalState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "USER_LIST_PRICING_BUYER_APPROVAL_STATE_UNSPECIFIED"] = 0; + values[valuesById[1] = "PENDING"] = 1; + values[valuesById[2] = "APPROVED"] = 2; + values[valuesById[3] = "REJECTED"] = 3; + return values; + })(); + + /** + * UserListPricingCostType enum. + * @name google.ads.datamanager.v1.UserListLicensePricing.UserListPricingCostType + * @enum {number} + * @property {number} USER_LIST_PRICING_COST_TYPE_UNSPECIFIED=0 USER_LIST_PRICING_COST_TYPE_UNSPECIFIED value + * @property {number} CPC=1 CPC value + * @property {number} CPM=2 CPM value + * @property {number} MEDIA_SHARE=3 MEDIA_SHARE value + */ + UserListLicensePricing.UserListPricingCostType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "USER_LIST_PRICING_COST_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "CPC"] = 1; + values[valuesById[2] = "CPM"] = 2; + values[valuesById[3] = "MEDIA_SHARE"] = 3; + return values; + })(); + + return UserListLicensePricing; + })(); + + /** + * UserListLicenseStatus enum. + * @name google.ads.datamanager.v1.UserListLicenseStatus + * @enum {number} + * @property {number} USER_LIST_LICENSE_STATUS_UNSPECIFIED=0 USER_LIST_LICENSE_STATUS_UNSPECIFIED value + * @property {number} USER_LIST_LICENSE_STATUS_ENABLED=1 USER_LIST_LICENSE_STATUS_ENABLED value + * @property {number} USER_LIST_LICENSE_STATUS_DISABLED=2 USER_LIST_LICENSE_STATUS_DISABLED value + */ + v1.UserListLicenseStatus = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "USER_LIST_LICENSE_STATUS_UNSPECIFIED"] = 0; + values[valuesById[1] = "USER_LIST_LICENSE_STATUS_ENABLED"] = 1; + values[valuesById[2] = "USER_LIST_LICENSE_STATUS_DISABLED"] = 2; + return values; + })(); + + v1.UserListDirectLicenseService = (function() { + + /** + * Constructs a new UserListDirectLicenseService service. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserListDirectLicenseService + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function UserListDirectLicenseService(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (UserListDirectLicenseService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = UserListDirectLicenseService; + + /** + * Creates new UserListDirectLicenseService service using the specified rpc implementation. + * @function create + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {UserListDirectLicenseService} RPC service. Useful where requests and/or responses are streamed. + */ + UserListDirectLicenseService.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListDirectLicenseService|createUserListDirectLicense}. + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @typedef CreateUserListDirectLicenseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserListDirectLicense} [response] UserListDirectLicense + */ + + /** + * Calls CreateUserListDirectLicense. + * @function createUserListDirectLicense + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @instance + * @param {google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest} request CreateUserListDirectLicenseRequest message or plain object + * @param {google.ads.datamanager.v1.UserListDirectLicenseService.CreateUserListDirectLicenseCallback} callback Node-style callback called with the error, if any, and UserListDirectLicense + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListDirectLicenseService.prototype.createUserListDirectLicense = function createUserListDirectLicense(request, callback) { + return this.rpcCall(createUserListDirectLicense, $root.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest, $root.google.ads.datamanager.v1.UserListDirectLicense, request, callback); + }, "name", { value: "CreateUserListDirectLicense" }); + + /** + * Calls CreateUserListDirectLicense. + * @function createUserListDirectLicense + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @instance + * @param {google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest} request CreateUserListDirectLicenseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListDirectLicenseService|getUserListDirectLicense}. + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @typedef GetUserListDirectLicenseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserListDirectLicense} [response] UserListDirectLicense + */ + + /** + * Calls GetUserListDirectLicense. + * @function getUserListDirectLicense + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @instance + * @param {google.ads.datamanager.v1.IGetUserListDirectLicenseRequest} request GetUserListDirectLicenseRequest message or plain object + * @param {google.ads.datamanager.v1.UserListDirectLicenseService.GetUserListDirectLicenseCallback} callback Node-style callback called with the error, if any, and UserListDirectLicense + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListDirectLicenseService.prototype.getUserListDirectLicense = function getUserListDirectLicense(request, callback) { + return this.rpcCall(getUserListDirectLicense, $root.google.ads.datamanager.v1.GetUserListDirectLicenseRequest, $root.google.ads.datamanager.v1.UserListDirectLicense, request, callback); + }, "name", { value: "GetUserListDirectLicense" }); + + /** + * Calls GetUserListDirectLicense. + * @function getUserListDirectLicense + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @instance + * @param {google.ads.datamanager.v1.IGetUserListDirectLicenseRequest} request GetUserListDirectLicenseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListDirectLicenseService|updateUserListDirectLicense}. + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @typedef UpdateUserListDirectLicenseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserListDirectLicense} [response] UserListDirectLicense + */ + + /** + * Calls UpdateUserListDirectLicense. + * @function updateUserListDirectLicense + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @instance + * @param {google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest} request UpdateUserListDirectLicenseRequest message or plain object + * @param {google.ads.datamanager.v1.UserListDirectLicenseService.UpdateUserListDirectLicenseCallback} callback Node-style callback called with the error, if any, and UserListDirectLicense + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListDirectLicenseService.prototype.updateUserListDirectLicense = function updateUserListDirectLicense(request, callback) { + return this.rpcCall(updateUserListDirectLicense, $root.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest, $root.google.ads.datamanager.v1.UserListDirectLicense, request, callback); + }, "name", { value: "UpdateUserListDirectLicense" }); + + /** + * Calls UpdateUserListDirectLicense. + * @function updateUserListDirectLicense + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @instance + * @param {google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest} request UpdateUserListDirectLicenseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListDirectLicenseService|listUserListDirectLicenses}. + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @typedef ListUserListDirectLicensesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.ListUserListDirectLicensesResponse} [response] ListUserListDirectLicensesResponse + */ + + /** + * Calls ListUserListDirectLicenses. + * @function listUserListDirectLicenses + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @instance + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesRequest} request ListUserListDirectLicensesRequest message or plain object + * @param {google.ads.datamanager.v1.UserListDirectLicenseService.ListUserListDirectLicensesCallback} callback Node-style callback called with the error, if any, and ListUserListDirectLicensesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListDirectLicenseService.prototype.listUserListDirectLicenses = function listUserListDirectLicenses(request, callback) { + return this.rpcCall(listUserListDirectLicenses, $root.google.ads.datamanager.v1.ListUserListDirectLicensesRequest, $root.google.ads.datamanager.v1.ListUserListDirectLicensesResponse, request, callback); + }, "name", { value: "ListUserListDirectLicenses" }); + + /** + * Calls ListUserListDirectLicenses. + * @function listUserListDirectLicenses + * @memberof google.ads.datamanager.v1.UserListDirectLicenseService + * @instance + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesRequest} request ListUserListDirectLicensesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return UserListDirectLicenseService; + })(); + + v1.CreateUserListDirectLicenseRequest = (function() { + + /** + * Properties of a CreateUserListDirectLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @interface ICreateUserListDirectLicenseRequest + * @property {string|null} [parent] CreateUserListDirectLicenseRequest parent + * @property {google.ads.datamanager.v1.IUserListDirectLicense|null} [userListDirectLicense] CreateUserListDirectLicenseRequest userListDirectLicense + */ + + /** + * Constructs a new CreateUserListDirectLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a CreateUserListDirectLicenseRequest. + * @implements ICreateUserListDirectLicenseRequest + * @constructor + * @param {google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest=} [properties] Properties to set + */ + function CreateUserListDirectLicenseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateUserListDirectLicenseRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @instance + */ + CreateUserListDirectLicenseRequest.prototype.parent = ""; + + /** + * CreateUserListDirectLicenseRequest userListDirectLicense. + * @member {google.ads.datamanager.v1.IUserListDirectLicense|null|undefined} userListDirectLicense + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @instance + */ + CreateUserListDirectLicenseRequest.prototype.userListDirectLicense = null; + + /** + * Creates a new CreateUserListDirectLicenseRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.CreateUserListDirectLicenseRequest} CreateUserListDirectLicenseRequest instance + */ + CreateUserListDirectLicenseRequest.create = function create(properties) { + return new CreateUserListDirectLicenseRequest(properties); + }; + + /** + * Encodes the specified CreateUserListDirectLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListDirectLicenseRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest} message CreateUserListDirectLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateUserListDirectLicenseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.userListDirectLicense != null && Object.hasOwnProperty.call(message, "userListDirectLicense")) + $root.google.ads.datamanager.v1.UserListDirectLicense.encode(message.userListDirectLicense, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateUserListDirectLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListDirectLicenseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest} message CreateUserListDirectLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateUserListDirectLicenseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateUserListDirectLicenseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.CreateUserListDirectLicenseRequest} CreateUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateUserListDirectLicenseRequest.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.ads.datamanager.v1.CreateUserListDirectLicenseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.userListDirectLicense = $root.google.ads.datamanager.v1.UserListDirectLicense.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateUserListDirectLicenseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.CreateUserListDirectLicenseRequest} CreateUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateUserListDirectLicenseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateUserListDirectLicenseRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateUserListDirectLicenseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.userListDirectLicense != null && message.hasOwnProperty("userListDirectLicense")) { + var error = $root.google.ads.datamanager.v1.UserListDirectLicense.verify(message.userListDirectLicense); + if (error) + return "userListDirectLicense." + error; + } + return null; + }; + + /** + * Creates a CreateUserListDirectLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.CreateUserListDirectLicenseRequest} CreateUserListDirectLicenseRequest + */ + CreateUserListDirectLicenseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest) + return object; + var message = new $root.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.userListDirectLicense != null) { + if (typeof object.userListDirectLicense !== "object") + throw TypeError(".google.ads.datamanager.v1.CreateUserListDirectLicenseRequest.userListDirectLicense: object expected"); + message.userListDirectLicense = $root.google.ads.datamanager.v1.UserListDirectLicense.fromObject(object.userListDirectLicense); + } + return message; + }; + + /** + * Creates a plain object from a CreateUserListDirectLicenseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.CreateUserListDirectLicenseRequest} message CreateUserListDirectLicenseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateUserListDirectLicenseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.userListDirectLicense = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.userListDirectLicense != null && message.hasOwnProperty("userListDirectLicense")) + object.userListDirectLicense = $root.google.ads.datamanager.v1.UserListDirectLicense.toObject(message.userListDirectLicense, options); + return object; + }; + + /** + * Converts this CreateUserListDirectLicenseRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @instance + * @returns {Object.} JSON object + */ + CreateUserListDirectLicenseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateUserListDirectLicenseRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.CreateUserListDirectLicenseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateUserListDirectLicenseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.CreateUserListDirectLicenseRequest"; + }; + + return CreateUserListDirectLicenseRequest; + })(); + + v1.GetUserListDirectLicenseRequest = (function() { + + /** + * Properties of a GetUserListDirectLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @interface IGetUserListDirectLicenseRequest + * @property {string|null} [name] GetUserListDirectLicenseRequest name + */ + + /** + * Constructs a new GetUserListDirectLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a GetUserListDirectLicenseRequest. + * @implements IGetUserListDirectLicenseRequest + * @constructor + * @param {google.ads.datamanager.v1.IGetUserListDirectLicenseRequest=} [properties] Properties to set + */ + function GetUserListDirectLicenseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetUserListDirectLicenseRequest name. + * @member {string} name + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @instance + */ + GetUserListDirectLicenseRequest.prototype.name = ""; + + /** + * Creates a new GetUserListDirectLicenseRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListDirectLicenseRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.GetUserListDirectLicenseRequest} GetUserListDirectLicenseRequest instance + */ + GetUserListDirectLicenseRequest.create = function create(properties) { + return new GetUserListDirectLicenseRequest(properties); + }; + + /** + * Encodes the specified GetUserListDirectLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.GetUserListDirectLicenseRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListDirectLicenseRequest} message GetUserListDirectLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetUserListDirectLicenseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetUserListDirectLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.GetUserListDirectLicenseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListDirectLicenseRequest} message GetUserListDirectLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetUserListDirectLicenseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetUserListDirectLicenseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.GetUserListDirectLicenseRequest} GetUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetUserListDirectLicenseRequest.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.ads.datamanager.v1.GetUserListDirectLicenseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetUserListDirectLicenseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.GetUserListDirectLicenseRequest} GetUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetUserListDirectLicenseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetUserListDirectLicenseRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetUserListDirectLicenseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetUserListDirectLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.GetUserListDirectLicenseRequest} GetUserListDirectLicenseRequest + */ + GetUserListDirectLicenseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.GetUserListDirectLicenseRequest) + return object; + var message = new $root.google.ads.datamanager.v1.GetUserListDirectLicenseRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetUserListDirectLicenseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.GetUserListDirectLicenseRequest} message GetUserListDirectLicenseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetUserListDirectLicenseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetUserListDirectLicenseRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @instance + * @returns {Object.} JSON object + */ + GetUserListDirectLicenseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetUserListDirectLicenseRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.GetUserListDirectLicenseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetUserListDirectLicenseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.GetUserListDirectLicenseRequest"; + }; + + return GetUserListDirectLicenseRequest; + })(); + + v1.UpdateUserListDirectLicenseRequest = (function() { + + /** + * Properties of an UpdateUserListDirectLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @interface IUpdateUserListDirectLicenseRequest + * @property {google.ads.datamanager.v1.IUserListDirectLicense|null} [userListDirectLicense] UpdateUserListDirectLicenseRequest userListDirectLicense + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateUserListDirectLicenseRequest updateMask + */ + + /** + * Constructs a new UpdateUserListDirectLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents an UpdateUserListDirectLicenseRequest. + * @implements IUpdateUserListDirectLicenseRequest + * @constructor + * @param {google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest=} [properties] Properties to set + */ + function UpdateUserListDirectLicenseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateUserListDirectLicenseRequest userListDirectLicense. + * @member {google.ads.datamanager.v1.IUserListDirectLicense|null|undefined} userListDirectLicense + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @instance + */ + UpdateUserListDirectLicenseRequest.prototype.userListDirectLicense = null; + + /** + * UpdateUserListDirectLicenseRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @instance + */ + UpdateUserListDirectLicenseRequest.prototype.updateMask = null; + + /** + * Creates a new UpdateUserListDirectLicenseRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest} UpdateUserListDirectLicenseRequest instance + */ + UpdateUserListDirectLicenseRequest.create = function create(properties) { + return new UpdateUserListDirectLicenseRequest(properties); + }; + + /** + * Encodes the specified UpdateUserListDirectLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest} message UpdateUserListDirectLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateUserListDirectLicenseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userListDirectLicense != null && Object.hasOwnProperty.call(message, "userListDirectLicense")) + $root.google.ads.datamanager.v1.UserListDirectLicense.encode(message.userListDirectLicense, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + $root.google.protobuf.FieldMask.encode(message.updateMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateUserListDirectLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest} message UpdateUserListDirectLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateUserListDirectLicenseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateUserListDirectLicenseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest} UpdateUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateUserListDirectLicenseRequest.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.ads.datamanager.v1.UpdateUserListDirectLicenseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.userListDirectLicense = $root.google.ads.datamanager.v1.UserListDirectLicense.decode(reader, reader.uint32()); + break; + } + case 2: { + message.updateMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateUserListDirectLicenseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest} UpdateUserListDirectLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateUserListDirectLicenseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateUserListDirectLicenseRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateUserListDirectLicenseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userListDirectLicense != null && message.hasOwnProperty("userListDirectLicense")) { + var error = $root.google.ads.datamanager.v1.UserListDirectLicense.verify(message.userListDirectLicense); + if (error) + return "userListDirectLicense." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.updateMask); + if (error) + return "updateMask." + error; + } + return null; + }; + + /** + * Creates an UpdateUserListDirectLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest} UpdateUserListDirectLicenseRequest + */ + UpdateUserListDirectLicenseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest) + return object; + var message = new $root.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest(); + if (object.userListDirectLicense != null) { + if (typeof object.userListDirectLicense !== "object") + throw TypeError(".google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest.userListDirectLicense: object expected"); + message.userListDirectLicense = $root.google.ads.datamanager.v1.UserListDirectLicense.fromObject(object.userListDirectLicense); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateUserListDirectLicenseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest} message UpdateUserListDirectLicenseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateUserListDirectLicenseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.userListDirectLicense = null; + object.updateMask = null; + } + if (message.userListDirectLicense != null && message.hasOwnProperty("userListDirectLicense")) + object.userListDirectLicense = $root.google.ads.datamanager.v1.UserListDirectLicense.toObject(message.userListDirectLicense, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this UpdateUserListDirectLicenseRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateUserListDirectLicenseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateUserListDirectLicenseRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateUserListDirectLicenseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest"; + }; + + return UpdateUserListDirectLicenseRequest; + })(); + + v1.ListUserListDirectLicensesRequest = (function() { + + /** + * Properties of a ListUserListDirectLicensesRequest. + * @memberof google.ads.datamanager.v1 + * @interface IListUserListDirectLicensesRequest + * @property {string|null} [parent] ListUserListDirectLicensesRequest parent + * @property {string|null} [filter] ListUserListDirectLicensesRequest filter + * @property {number|null} [pageSize] ListUserListDirectLicensesRequest pageSize + * @property {string|null} [pageToken] ListUserListDirectLicensesRequest pageToken + */ + + /** + * Constructs a new ListUserListDirectLicensesRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ListUserListDirectLicensesRequest. + * @implements IListUserListDirectLicensesRequest + * @constructor + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesRequest=} [properties] Properties to set + */ + function ListUserListDirectLicensesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserListDirectLicensesRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @instance + */ + ListUserListDirectLicensesRequest.prototype.parent = ""; + + /** + * ListUserListDirectLicensesRequest filter. + * @member {string} filter + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @instance + */ + ListUserListDirectLicensesRequest.prototype.filter = ""; + + /** + * ListUserListDirectLicensesRequest pageSize. + * @member {number} pageSize + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @instance + */ + ListUserListDirectLicensesRequest.prototype.pageSize = 0; + + /** + * ListUserListDirectLicensesRequest pageToken. + * @member {string} pageToken + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @instance + */ + ListUserListDirectLicensesRequest.prototype.pageToken = ""; + + /** + * Creates a new ListUserListDirectLicensesRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ListUserListDirectLicensesRequest} ListUserListDirectLicensesRequest instance + */ + ListUserListDirectLicensesRequest.create = function create(properties) { + return new ListUserListDirectLicensesRequest(properties); + }; + + /** + * Encodes the specified ListUserListDirectLicensesRequest message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListDirectLicensesRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesRequest} message ListUserListDirectLicensesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListDirectLicensesRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListUserListDirectLicensesRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListDirectLicensesRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesRequest} message ListUserListDirectLicensesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListDirectLicensesRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListUserListDirectLicensesRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ListUserListDirectLicensesRequest} ListUserListDirectLicensesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListDirectLicensesRequest.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.ads.datamanager.v1.ListUserListDirectLicensesRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListUserListDirectLicensesRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ListUserListDirectLicensesRequest} ListUserListDirectLicensesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListDirectLicensesRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListUserListDirectLicensesRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListUserListDirectLicensesRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListUserListDirectLicensesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ListUserListDirectLicensesRequest} ListUserListDirectLicensesRequest + */ + ListUserListDirectLicensesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ListUserListDirectLicensesRequest) + return object; + var message = new $root.google.ads.datamanager.v1.ListUserListDirectLicensesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListUserListDirectLicensesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {google.ads.datamanager.v1.ListUserListDirectLicensesRequest} message ListUserListDirectLicensesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserListDirectLicensesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListUserListDirectLicensesRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @instance + * @returns {Object.} JSON object + */ + ListUserListDirectLicensesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserListDirectLicensesRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserListDirectLicensesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ListUserListDirectLicensesRequest"; + }; + + return ListUserListDirectLicensesRequest; + })(); + + v1.ListUserListDirectLicensesResponse = (function() { + + /** + * Properties of a ListUserListDirectLicensesResponse. + * @memberof google.ads.datamanager.v1 + * @interface IListUserListDirectLicensesResponse + * @property {Array.|null} [userListDirectLicenses] ListUserListDirectLicensesResponse userListDirectLicenses + * @property {string|null} [nextPageToken] ListUserListDirectLicensesResponse nextPageToken + */ + + /** + * Constructs a new ListUserListDirectLicensesResponse. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ListUserListDirectLicensesResponse. + * @implements IListUserListDirectLicensesResponse + * @constructor + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesResponse=} [properties] Properties to set + */ + function ListUserListDirectLicensesResponse(properties) { + this.userListDirectLicenses = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserListDirectLicensesResponse userListDirectLicenses. + * @member {Array.} userListDirectLicenses + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @instance + */ + ListUserListDirectLicensesResponse.prototype.userListDirectLicenses = $util.emptyArray; + + /** + * ListUserListDirectLicensesResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @instance + */ + ListUserListDirectLicensesResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListUserListDirectLicensesResponse instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesResponse=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ListUserListDirectLicensesResponse} ListUserListDirectLicensesResponse instance + */ + ListUserListDirectLicensesResponse.create = function create(properties) { + return new ListUserListDirectLicensesResponse(properties); + }; + + /** + * Encodes the specified ListUserListDirectLicensesResponse message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListDirectLicensesResponse.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesResponse} message ListUserListDirectLicensesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListDirectLicensesResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userListDirectLicenses != null && message.userListDirectLicenses.length) + for (var i = 0; i < message.userListDirectLicenses.length; ++i) + $root.google.ads.datamanager.v1.UserListDirectLicense.encode(message.userListDirectLicenses[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListUserListDirectLicensesResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListDirectLicensesResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListDirectLicensesResponse} message ListUserListDirectLicensesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListDirectLicensesResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListUserListDirectLicensesResponse message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ListUserListDirectLicensesResponse} ListUserListDirectLicensesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListDirectLicensesResponse.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.ads.datamanager.v1.ListUserListDirectLicensesResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.userListDirectLicenses && message.userListDirectLicenses.length)) + message.userListDirectLicenses = []; + message.userListDirectLicenses.push($root.google.ads.datamanager.v1.UserListDirectLicense.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListUserListDirectLicensesResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ListUserListDirectLicensesResponse} ListUserListDirectLicensesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListDirectLicensesResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListUserListDirectLicensesResponse message. + * @function verify + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListUserListDirectLicensesResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userListDirectLicenses != null && message.hasOwnProperty("userListDirectLicenses")) { + if (!Array.isArray(message.userListDirectLicenses)) + return "userListDirectLicenses: array expected"; + for (var i = 0; i < message.userListDirectLicenses.length; ++i) { + var error = $root.google.ads.datamanager.v1.UserListDirectLicense.verify(message.userListDirectLicenses[i]); + if (error) + return "userListDirectLicenses." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListUserListDirectLicensesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ListUserListDirectLicensesResponse} ListUserListDirectLicensesResponse + */ + ListUserListDirectLicensesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ListUserListDirectLicensesResponse) + return object; + var message = new $root.google.ads.datamanager.v1.ListUserListDirectLicensesResponse(); + if (object.userListDirectLicenses) { + if (!Array.isArray(object.userListDirectLicenses)) + throw TypeError(".google.ads.datamanager.v1.ListUserListDirectLicensesResponse.userListDirectLicenses: array expected"); + message.userListDirectLicenses = []; + for (var i = 0; i < object.userListDirectLicenses.length; ++i) { + if (typeof object.userListDirectLicenses[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.ListUserListDirectLicensesResponse.userListDirectLicenses: object expected"); + message.userListDirectLicenses[i] = $root.google.ads.datamanager.v1.UserListDirectLicense.fromObject(object.userListDirectLicenses[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListUserListDirectLicensesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {google.ads.datamanager.v1.ListUserListDirectLicensesResponse} message ListUserListDirectLicensesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserListDirectLicensesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.userListDirectLicenses = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.userListDirectLicenses && message.userListDirectLicenses.length) { + object.userListDirectLicenses = []; + for (var j = 0; j < message.userListDirectLicenses.length; ++j) + object.userListDirectLicenses[j] = $root.google.ads.datamanager.v1.UserListDirectLicense.toObject(message.userListDirectLicenses[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListUserListDirectLicensesResponse to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @instance + * @returns {Object.} JSON object + */ + ListUserListDirectLicensesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserListDirectLicensesResponse + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ListUserListDirectLicensesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserListDirectLicensesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ListUserListDirectLicensesResponse"; + }; + + return ListUserListDirectLicensesResponse; + })(); + + v1.UserListGlobalLicense = (function() { + + /** + * Properties of a UserListGlobalLicense. + * @memberof google.ads.datamanager.v1 + * @interface IUserListGlobalLicense + * @property {string|null} [name] UserListGlobalLicense name + * @property {number|Long|null} [userListId] UserListGlobalLicense userListId + * @property {string|null} [userListDisplayName] UserListGlobalLicense userListDisplayName + * @property {google.ads.datamanager.v1.UserListGlobalLicenseType|null} [licenseType] UserListGlobalLicense licenseType + * @property {google.ads.datamanager.v1.UserListLicenseStatus|null} [status] UserListGlobalLicense status + * @property {google.ads.datamanager.v1.IUserListLicensePricing|null} [pricing] UserListGlobalLicense pricing + * @property {Array.|null} [historicalPricings] UserListGlobalLicense historicalPricings + * @property {google.ads.datamanager.v1.IUserListLicenseMetrics|null} [metrics] UserListGlobalLicense metrics + */ + + /** + * Constructs a new UserListGlobalLicense. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserListGlobalLicense. + * @implements IUserListGlobalLicense + * @constructor + * @param {google.ads.datamanager.v1.IUserListGlobalLicense=} [properties] Properties to set + */ + function UserListGlobalLicense(properties) { + this.historicalPricings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserListGlobalLicense name. + * @member {string} name + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + */ + UserListGlobalLicense.prototype.name = ""; + + /** + * UserListGlobalLicense userListId. + * @member {number|Long|null|undefined} userListId + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + */ + UserListGlobalLicense.prototype.userListId = null; + + /** + * UserListGlobalLicense userListDisplayName. + * @member {string} userListDisplayName + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + */ + UserListGlobalLicense.prototype.userListDisplayName = ""; + + /** + * UserListGlobalLicense licenseType. + * @member {google.ads.datamanager.v1.UserListGlobalLicenseType|null|undefined} licenseType + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + */ + UserListGlobalLicense.prototype.licenseType = null; + + /** + * UserListGlobalLicense status. + * @member {google.ads.datamanager.v1.UserListLicenseStatus|null|undefined} status + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + */ + UserListGlobalLicense.prototype.status = null; + + /** + * UserListGlobalLicense pricing. + * @member {google.ads.datamanager.v1.IUserListLicensePricing|null|undefined} pricing + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + */ + UserListGlobalLicense.prototype.pricing = null; + + /** + * UserListGlobalLicense historicalPricings. + * @member {Array.} historicalPricings + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + */ + UserListGlobalLicense.prototype.historicalPricings = $util.emptyArray; + + /** + * UserListGlobalLicense metrics. + * @member {google.ads.datamanager.v1.IUserListLicenseMetrics|null|undefined} metrics + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + */ + UserListGlobalLicense.prototype.metrics = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListGlobalLicense.prototype, "_userListId", { + get: $util.oneOfGetter($oneOfFields = ["userListId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListGlobalLicense.prototype, "_licenseType", { + get: $util.oneOfGetter($oneOfFields = ["licenseType"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UserListGlobalLicense.prototype, "_status", { + get: $util.oneOfGetter($oneOfFields = ["status"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UserListGlobalLicense instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {google.ads.datamanager.v1.IUserListGlobalLicense=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UserListGlobalLicense} UserListGlobalLicense instance + */ + UserListGlobalLicense.create = function create(properties) { + return new UserListGlobalLicense(properties); + }; + + /** + * Encodes the specified UserListGlobalLicense message. Does not implicitly {@link google.ads.datamanager.v1.UserListGlobalLicense.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {google.ads.datamanager.v1.IUserListGlobalLicense} message UserListGlobalLicense message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListGlobalLicense.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.userListId != null && Object.hasOwnProperty.call(message, "userListId")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.userListId); + if (message.userListDisplayName != null && Object.hasOwnProperty.call(message, "userListDisplayName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.userListDisplayName); + if (message.licenseType != null && Object.hasOwnProperty.call(message, "licenseType")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.licenseType); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.status); + if (message.pricing != null && Object.hasOwnProperty.call(message, "pricing")) + $root.google.ads.datamanager.v1.UserListLicensePricing.encode(message.pricing, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.historicalPricings != null && message.historicalPricings.length) + for (var i = 0; i < message.historicalPricings.length; ++i) + $root.google.ads.datamanager.v1.UserListLicensePricing.encode(message.historicalPricings[i], writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.metrics != null && Object.hasOwnProperty.call(message, "metrics")) + $root.google.ads.datamanager.v1.UserListLicenseMetrics.encode(message.metrics, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UserListGlobalLicense message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListGlobalLicense.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {google.ads.datamanager.v1.IUserListGlobalLicense} message UserListGlobalLicense message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListGlobalLicense.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a UserListGlobalLicense message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UserListGlobalLicense} UserListGlobalLicense + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListGlobalLicense.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.ads.datamanager.v1.UserListGlobalLicense(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.userListId = reader.int64(); + break; + } + case 3: { + message.userListDisplayName = reader.string(); + break; + } + case 4: { + message.licenseType = reader.int32(); + break; + } + case 5: { + message.status = reader.int32(); + break; + } + case 6: { + message.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.decode(reader, reader.uint32()); + break; + } + case 7: { + if (!(message.historicalPricings && message.historicalPricings.length)) + message.historicalPricings = []; + message.historicalPricings.push($root.google.ads.datamanager.v1.UserListLicensePricing.decode(reader, reader.uint32())); + break; + } + case 8: { + message.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a UserListGlobalLicense message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UserListGlobalLicense} UserListGlobalLicense + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListGlobalLicense.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a UserListGlobalLicense message. + * @function verify + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UserListGlobalLicense.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.userListId != null && message.hasOwnProperty("userListId")) { + properties._userListId = 1; + if (!$util.isInteger(message.userListId) && !(message.userListId && $util.isInteger(message.userListId.low) && $util.isInteger(message.userListId.high))) + return "userListId: integer|Long expected"; + } + if (message.userListDisplayName != null && message.hasOwnProperty("userListDisplayName")) + if (!$util.isString(message.userListDisplayName)) + return "userListDisplayName: string expected"; + if (message.licenseType != null && message.hasOwnProperty("licenseType")) { + properties._licenseType = 1; + switch (message.licenseType) { + default: + return "licenseType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + } + if (message.status != null && message.hasOwnProperty("status")) { + properties._status = 1; + switch (message.status) { + default: + return "status: enum value expected"; + case 0: + case 1: + case 2: + break; + } + } + if (message.pricing != null && message.hasOwnProperty("pricing")) { + var error = $root.google.ads.datamanager.v1.UserListLicensePricing.verify(message.pricing); + if (error) + return "pricing." + error; + } + if (message.historicalPricings != null && message.hasOwnProperty("historicalPricings")) { + if (!Array.isArray(message.historicalPricings)) + return "historicalPricings: array expected"; + for (var i = 0; i < message.historicalPricings.length; ++i) { + var error = $root.google.ads.datamanager.v1.UserListLicensePricing.verify(message.historicalPricings[i]); + if (error) + return "historicalPricings." + error; + } + } + if (message.metrics != null && message.hasOwnProperty("metrics")) { + var error = $root.google.ads.datamanager.v1.UserListLicenseMetrics.verify(message.metrics); + if (error) + return "metrics." + error; + } + return null; + }; + + /** + * Creates a UserListGlobalLicense message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UserListGlobalLicense} UserListGlobalLicense + */ + UserListGlobalLicense.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UserListGlobalLicense) + return object; + var message = new $root.google.ads.datamanager.v1.UserListGlobalLicense(); + if (object.name != null) + message.name = String(object.name); + if (object.userListId != null) + if ($util.Long) + (message.userListId = $util.Long.fromValue(object.userListId)).unsigned = false; + else if (typeof object.userListId === "string") + message.userListId = parseInt(object.userListId, 10); + else if (typeof object.userListId === "number") + message.userListId = object.userListId; + else if (typeof object.userListId === "object") + message.userListId = new $util.LongBits(object.userListId.low >>> 0, object.userListId.high >>> 0).toNumber(); + if (object.userListDisplayName != null) + message.userListDisplayName = String(object.userListDisplayName); + switch (object.licenseType) { + default: + if (typeof object.licenseType === "number") { + message.licenseType = object.licenseType; + break; + } + break; + case "USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED": + case 0: + message.licenseType = 0; + break; + case "USER_LIST_GLOBAL_LICENSE_TYPE_RESELLER": + case 1: + message.licenseType = 1; + break; + case "USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_SELL_SIDE": + case 2: + message.licenseType = 2; + break; + case "USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_BUY_SIDE": + case 3: + message.licenseType = 3; + break; + } + switch (object.status) { + default: + if (typeof object.status === "number") { + message.status = object.status; + break; + } + break; + case "USER_LIST_LICENSE_STATUS_UNSPECIFIED": + case 0: + message.status = 0; + break; + case "USER_LIST_LICENSE_STATUS_ENABLED": + case 1: + message.status = 1; + break; + case "USER_LIST_LICENSE_STATUS_DISABLED": + case 2: + message.status = 2; + break; + } + if (object.pricing != null) { + if (typeof object.pricing !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListGlobalLicense.pricing: object expected"); + message.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.fromObject(object.pricing); + } + if (object.historicalPricings) { + if (!Array.isArray(object.historicalPricings)) + throw TypeError(".google.ads.datamanager.v1.UserListGlobalLicense.historicalPricings: array expected"); + message.historicalPricings = []; + for (var i = 0; i < object.historicalPricings.length; ++i) { + if (typeof object.historicalPricings[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListGlobalLicense.historicalPricings: object expected"); + message.historicalPricings[i] = $root.google.ads.datamanager.v1.UserListLicensePricing.fromObject(object.historicalPricings[i]); + } + } + if (object.metrics != null) { + if (typeof object.metrics !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListGlobalLicense.metrics: object expected"); + message.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.fromObject(object.metrics); + } + return message; + }; + + /** + * Creates a plain object from a UserListGlobalLicense message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {google.ads.datamanager.v1.UserListGlobalLicense} message UserListGlobalLicense + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserListGlobalLicense.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.historicalPricings = []; + if (options.defaults) { + object.name = ""; + object.userListDisplayName = ""; + object.pricing = null; + object.metrics = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.userListId != null && message.hasOwnProperty("userListId")) { + if (typeof message.userListId === "number") + object.userListId = options.longs === String ? String(message.userListId) : message.userListId; + else + object.userListId = options.longs === String ? $util.Long.prototype.toString.call(message.userListId) : options.longs === Number ? new $util.LongBits(message.userListId.low >>> 0, message.userListId.high >>> 0).toNumber() : message.userListId; + if (options.oneofs) + object._userListId = "userListId"; + } + if (message.userListDisplayName != null && message.hasOwnProperty("userListDisplayName")) + object.userListDisplayName = message.userListDisplayName; + if (message.licenseType != null && message.hasOwnProperty("licenseType")) { + object.licenseType = options.enums === String ? $root.google.ads.datamanager.v1.UserListGlobalLicenseType[message.licenseType] === undefined ? message.licenseType : $root.google.ads.datamanager.v1.UserListGlobalLicenseType[message.licenseType] : message.licenseType; + if (options.oneofs) + object._licenseType = "licenseType"; + } + if (message.status != null && message.hasOwnProperty("status")) { + object.status = options.enums === String ? $root.google.ads.datamanager.v1.UserListLicenseStatus[message.status] === undefined ? message.status : $root.google.ads.datamanager.v1.UserListLicenseStatus[message.status] : message.status; + if (options.oneofs) + object._status = "status"; + } + if (message.pricing != null && message.hasOwnProperty("pricing")) + object.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.toObject(message.pricing, options); + if (message.historicalPricings && message.historicalPricings.length) { + object.historicalPricings = []; + for (var j = 0; j < message.historicalPricings.length; ++j) + object.historicalPricings[j] = $root.google.ads.datamanager.v1.UserListLicensePricing.toObject(message.historicalPricings[j], options); + } + if (message.metrics != null && message.hasOwnProperty("metrics")) + object.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.toObject(message.metrics, options); + return object; + }; + + /** + * Converts this UserListGlobalLicense to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @instance + * @returns {Object.} JSON object + */ + UserListGlobalLicense.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserListGlobalLicense + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UserListGlobalLicense + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserListGlobalLicense.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UserListGlobalLicense"; + }; + + return UserListGlobalLicense; + })(); + + v1.UserListGlobalLicenseCustomerInfo = (function() { + + /** + * Properties of a UserListGlobalLicenseCustomerInfo. + * @memberof google.ads.datamanager.v1 + * @interface IUserListGlobalLicenseCustomerInfo + * @property {string|null} [name] UserListGlobalLicenseCustomerInfo name + * @property {number|Long|null} [userListId] UserListGlobalLicenseCustomerInfo userListId + * @property {string|null} [userListDisplayName] UserListGlobalLicenseCustomerInfo userListDisplayName + * @property {google.ads.datamanager.v1.UserListGlobalLicenseType|null} [licenseType] UserListGlobalLicenseCustomerInfo licenseType + * @property {google.ads.datamanager.v1.UserListLicenseStatus|null} [status] UserListGlobalLicenseCustomerInfo status + * @property {google.ads.datamanager.v1.IUserListLicensePricing|null} [pricing] UserListGlobalLicenseCustomerInfo pricing + * @property {google.ads.datamanager.v1.UserListLicenseClientAccountType|null} [clientAccountType] UserListGlobalLicenseCustomerInfo clientAccountType + * @property {number|Long|null} [clientAccountId] UserListGlobalLicenseCustomerInfo clientAccountId + * @property {string|null} [clientAccountDisplayName] UserListGlobalLicenseCustomerInfo clientAccountDisplayName + * @property {Array.|null} [historicalPricings] UserListGlobalLicenseCustomerInfo historicalPricings + * @property {google.ads.datamanager.v1.IUserListLicenseMetrics|null} [metrics] UserListGlobalLicenseCustomerInfo metrics + */ + + /** + * Constructs a new UserListGlobalLicenseCustomerInfo. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserListGlobalLicenseCustomerInfo. + * @implements IUserListGlobalLicenseCustomerInfo + * @constructor + * @param {google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo=} [properties] Properties to set + */ + function UserListGlobalLicenseCustomerInfo(properties) { + this.historicalPricings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserListGlobalLicenseCustomerInfo name. + * @member {string} name + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.name = ""; + + /** + * UserListGlobalLicenseCustomerInfo userListId. + * @member {number|Long} userListId + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.userListId = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UserListGlobalLicenseCustomerInfo userListDisplayName. + * @member {string} userListDisplayName + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.userListDisplayName = ""; + + /** + * UserListGlobalLicenseCustomerInfo licenseType. + * @member {google.ads.datamanager.v1.UserListGlobalLicenseType} licenseType + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.licenseType = 0; + + /** + * UserListGlobalLicenseCustomerInfo status. + * @member {google.ads.datamanager.v1.UserListLicenseStatus} status + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.status = 0; + + /** + * UserListGlobalLicenseCustomerInfo pricing. + * @member {google.ads.datamanager.v1.IUserListLicensePricing|null|undefined} pricing + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.pricing = null; + + /** + * UserListGlobalLicenseCustomerInfo clientAccountType. + * @member {google.ads.datamanager.v1.UserListLicenseClientAccountType} clientAccountType + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.clientAccountType = 0; + + /** + * UserListGlobalLicenseCustomerInfo clientAccountId. + * @member {number|Long} clientAccountId + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.clientAccountId = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * UserListGlobalLicenseCustomerInfo clientAccountDisplayName. + * @member {string} clientAccountDisplayName + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.clientAccountDisplayName = ""; + + /** + * UserListGlobalLicenseCustomerInfo historicalPricings. + * @member {Array.} historicalPricings + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.historicalPricings = $util.emptyArray; + + /** + * UserListGlobalLicenseCustomerInfo metrics. + * @member {google.ads.datamanager.v1.IUserListLicenseMetrics|null|undefined} metrics + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + */ + UserListGlobalLicenseCustomerInfo.prototype.metrics = null; + + /** + * Creates a new UserListGlobalLicenseCustomerInfo instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo} UserListGlobalLicenseCustomerInfo instance + */ + UserListGlobalLicenseCustomerInfo.create = function create(properties) { + return new UserListGlobalLicenseCustomerInfo(properties); + }; + + /** + * Encodes the specified UserListGlobalLicenseCustomerInfo message. Does not implicitly {@link google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo} message UserListGlobalLicenseCustomerInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListGlobalLicenseCustomerInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.userListId != null && Object.hasOwnProperty.call(message, "userListId")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.userListId); + if (message.userListDisplayName != null && Object.hasOwnProperty.call(message, "userListDisplayName")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.userListDisplayName); + if (message.licenseType != null && Object.hasOwnProperty.call(message, "licenseType")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.licenseType); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + writer.uint32(/* id 5, wireType 0 =*/40).int32(message.status); + if (message.pricing != null && Object.hasOwnProperty.call(message, "pricing")) + $root.google.ads.datamanager.v1.UserListLicensePricing.encode(message.pricing, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); + if (message.clientAccountType != null && Object.hasOwnProperty.call(message, "clientAccountType")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.clientAccountType); + if (message.clientAccountId != null && Object.hasOwnProperty.call(message, "clientAccountId")) + writer.uint32(/* id 8, wireType 0 =*/64).int64(message.clientAccountId); + if (message.clientAccountDisplayName != null && Object.hasOwnProperty.call(message, "clientAccountDisplayName")) + writer.uint32(/* id 9, wireType 2 =*/74).string(message.clientAccountDisplayName); + if (message.historicalPricings != null && message.historicalPricings.length) + for (var i = 0; i < message.historicalPricings.length; ++i) + $root.google.ads.datamanager.v1.UserListLicensePricing.encode(message.historicalPricings[i], writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); + if (message.metrics != null && Object.hasOwnProperty.call(message, "metrics")) + $root.google.ads.datamanager.v1.UserListLicenseMetrics.encode(message.metrics, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UserListGlobalLicenseCustomerInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo} message UserListGlobalLicenseCustomerInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UserListGlobalLicenseCustomerInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a UserListGlobalLicenseCustomerInfo message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo} UserListGlobalLicenseCustomerInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListGlobalLicenseCustomerInfo.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.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.userListId = reader.int64(); + break; + } + case 3: { + message.userListDisplayName = reader.string(); + break; + } + case 4: { + message.licenseType = reader.int32(); + break; + } + case 5: { + message.status = reader.int32(); + break; + } + case 6: { + message.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.decode(reader, reader.uint32()); + break; + } + case 7: { + message.clientAccountType = reader.int32(); + break; + } + case 8: { + message.clientAccountId = reader.int64(); + break; + } + case 9: { + message.clientAccountDisplayName = reader.string(); + break; + } + case 10: { + if (!(message.historicalPricings && message.historicalPricings.length)) + message.historicalPricings = []; + message.historicalPricings.push($root.google.ads.datamanager.v1.UserListLicensePricing.decode(reader, reader.uint32())); + break; + } + case 11: { + message.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a UserListGlobalLicenseCustomerInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo} UserListGlobalLicenseCustomerInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UserListGlobalLicenseCustomerInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a UserListGlobalLicenseCustomerInfo message. + * @function verify + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UserListGlobalLicenseCustomerInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.userListId != null && message.hasOwnProperty("userListId")) + if (!$util.isInteger(message.userListId) && !(message.userListId && $util.isInteger(message.userListId.low) && $util.isInteger(message.userListId.high))) + return "userListId: integer|Long expected"; + if (message.userListDisplayName != null && message.hasOwnProperty("userListDisplayName")) + if (!$util.isString(message.userListDisplayName)) + return "userListDisplayName: string expected"; + if (message.licenseType != null && message.hasOwnProperty("licenseType")) + switch (message.licenseType) { + default: + return "licenseType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.status != null && message.hasOwnProperty("status")) + switch (message.status) { + default: + return "status: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.pricing != null && message.hasOwnProperty("pricing")) { + var error = $root.google.ads.datamanager.v1.UserListLicensePricing.verify(message.pricing); + if (error) + return "pricing." + error; + } + if (message.clientAccountType != null && message.hasOwnProperty("clientAccountType")) + switch (message.clientAccountType) { + default: + return "clientAccountType: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } + if (message.clientAccountId != null && message.hasOwnProperty("clientAccountId")) + if (!$util.isInteger(message.clientAccountId) && !(message.clientAccountId && $util.isInteger(message.clientAccountId.low) && $util.isInteger(message.clientAccountId.high))) + return "clientAccountId: integer|Long expected"; + if (message.clientAccountDisplayName != null && message.hasOwnProperty("clientAccountDisplayName")) + if (!$util.isString(message.clientAccountDisplayName)) + return "clientAccountDisplayName: string expected"; + if (message.historicalPricings != null && message.hasOwnProperty("historicalPricings")) { + if (!Array.isArray(message.historicalPricings)) + return "historicalPricings: array expected"; + for (var i = 0; i < message.historicalPricings.length; ++i) { + var error = $root.google.ads.datamanager.v1.UserListLicensePricing.verify(message.historicalPricings[i]); + if (error) + return "historicalPricings." + error; + } + } + if (message.metrics != null && message.hasOwnProperty("metrics")) { + var error = $root.google.ads.datamanager.v1.UserListLicenseMetrics.verify(message.metrics); + if (error) + return "metrics." + error; + } + return null; + }; + + /** + * Creates a UserListGlobalLicenseCustomerInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo} UserListGlobalLicenseCustomerInfo + */ + UserListGlobalLicenseCustomerInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo) + return object; + var message = new $root.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(); + if (object.name != null) + message.name = String(object.name); + if (object.userListId != null) + if ($util.Long) + (message.userListId = $util.Long.fromValue(object.userListId)).unsigned = false; + else if (typeof object.userListId === "string") + message.userListId = parseInt(object.userListId, 10); + else if (typeof object.userListId === "number") + message.userListId = object.userListId; + else if (typeof object.userListId === "object") + message.userListId = new $util.LongBits(object.userListId.low >>> 0, object.userListId.high >>> 0).toNumber(); + if (object.userListDisplayName != null) + message.userListDisplayName = String(object.userListDisplayName); + switch (object.licenseType) { + default: + if (typeof object.licenseType === "number") { + message.licenseType = object.licenseType; + break; + } + break; + case "USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED": + case 0: + message.licenseType = 0; + break; + case "USER_LIST_GLOBAL_LICENSE_TYPE_RESELLER": + case 1: + message.licenseType = 1; + break; + case "USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_SELL_SIDE": + case 2: + message.licenseType = 2; + break; + case "USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_BUY_SIDE": + case 3: + message.licenseType = 3; + break; + } + switch (object.status) { + default: + if (typeof object.status === "number") { + message.status = object.status; + break; + } + break; + case "USER_LIST_LICENSE_STATUS_UNSPECIFIED": + case 0: + message.status = 0; + break; + case "USER_LIST_LICENSE_STATUS_ENABLED": + case 1: + message.status = 1; + break; + case "USER_LIST_LICENSE_STATUS_DISABLED": + case 2: + message.status = 2; + break; + } + if (object.pricing != null) { + if (typeof object.pricing !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.pricing: object expected"); + message.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.fromObject(object.pricing); + } + switch (object.clientAccountType) { + default: + if (typeof object.clientAccountType === "number") { + message.clientAccountType = object.clientAccountType; + break; + } + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN": + case 0: + message.clientAccountType = 0; + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_ADS": + case 1: + message.clientAccountType = 1; + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_PARTNER": + case 2: + message.clientAccountType = 2; + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_ADVERTISER": + case 3: + message.clientAccountType = 3; + break; + case "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_AD_MANAGER_AUDIENCE_LINK": + case 4: + message.clientAccountType = 4; + break; + } + if (object.clientAccountId != null) + if ($util.Long) + (message.clientAccountId = $util.Long.fromValue(object.clientAccountId)).unsigned = false; + else if (typeof object.clientAccountId === "string") + message.clientAccountId = parseInt(object.clientAccountId, 10); + else if (typeof object.clientAccountId === "number") + message.clientAccountId = object.clientAccountId; + else if (typeof object.clientAccountId === "object") + message.clientAccountId = new $util.LongBits(object.clientAccountId.low >>> 0, object.clientAccountId.high >>> 0).toNumber(); + if (object.clientAccountDisplayName != null) + message.clientAccountDisplayName = String(object.clientAccountDisplayName); + if (object.historicalPricings) { + if (!Array.isArray(object.historicalPricings)) + throw TypeError(".google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.historicalPricings: array expected"); + message.historicalPricings = []; + for (var i = 0; i < object.historicalPricings.length; ++i) { + if (typeof object.historicalPricings[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.historicalPricings: object expected"); + message.historicalPricings[i] = $root.google.ads.datamanager.v1.UserListLicensePricing.fromObject(object.historicalPricings[i]); + } + } + if (object.metrics != null) { + if (typeof object.metrics !== "object") + throw TypeError(".google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.metrics: object expected"); + message.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.fromObject(object.metrics); + } + return message; + }; + + /** + * Creates a plain object from a UserListGlobalLicenseCustomerInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo} message UserListGlobalLicenseCustomerInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserListGlobalLicenseCustomerInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.historicalPricings = []; + if (options.defaults) { + object.name = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.userListId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.userListId = options.longs === String ? "0" : 0; + object.userListDisplayName = ""; + object.licenseType = options.enums === String ? "USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED" : 0; + object.status = options.enums === String ? "USER_LIST_LICENSE_STATUS_UNSPECIFIED" : 0; + object.pricing = null; + object.clientAccountType = options.enums === String ? "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.clientAccountId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.clientAccountId = options.longs === String ? "0" : 0; + object.clientAccountDisplayName = ""; + object.metrics = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.userListId != null && message.hasOwnProperty("userListId")) + if (typeof message.userListId === "number") + object.userListId = options.longs === String ? String(message.userListId) : message.userListId; + else + object.userListId = options.longs === String ? $util.Long.prototype.toString.call(message.userListId) : options.longs === Number ? new $util.LongBits(message.userListId.low >>> 0, message.userListId.high >>> 0).toNumber() : message.userListId; + if (message.userListDisplayName != null && message.hasOwnProperty("userListDisplayName")) + object.userListDisplayName = message.userListDisplayName; + if (message.licenseType != null && message.hasOwnProperty("licenseType")) + object.licenseType = options.enums === String ? $root.google.ads.datamanager.v1.UserListGlobalLicenseType[message.licenseType] === undefined ? message.licenseType : $root.google.ads.datamanager.v1.UserListGlobalLicenseType[message.licenseType] : message.licenseType; + if (message.status != null && message.hasOwnProperty("status")) + object.status = options.enums === String ? $root.google.ads.datamanager.v1.UserListLicenseStatus[message.status] === undefined ? message.status : $root.google.ads.datamanager.v1.UserListLicenseStatus[message.status] : message.status; + if (message.pricing != null && message.hasOwnProperty("pricing")) + object.pricing = $root.google.ads.datamanager.v1.UserListLicensePricing.toObject(message.pricing, options); + if (message.clientAccountType != null && message.hasOwnProperty("clientAccountType")) + object.clientAccountType = options.enums === String ? $root.google.ads.datamanager.v1.UserListLicenseClientAccountType[message.clientAccountType] === undefined ? message.clientAccountType : $root.google.ads.datamanager.v1.UserListLicenseClientAccountType[message.clientAccountType] : message.clientAccountType; + if (message.clientAccountId != null && message.hasOwnProperty("clientAccountId")) + if (typeof message.clientAccountId === "number") + object.clientAccountId = options.longs === String ? String(message.clientAccountId) : message.clientAccountId; + else + object.clientAccountId = options.longs === String ? $util.Long.prototype.toString.call(message.clientAccountId) : options.longs === Number ? new $util.LongBits(message.clientAccountId.low >>> 0, message.clientAccountId.high >>> 0).toNumber() : message.clientAccountId; + if (message.clientAccountDisplayName != null && message.hasOwnProperty("clientAccountDisplayName")) + object.clientAccountDisplayName = message.clientAccountDisplayName; + if (message.historicalPricings && message.historicalPricings.length) { + object.historicalPricings = []; + for (var j = 0; j < message.historicalPricings.length; ++j) + object.historicalPricings[j] = $root.google.ads.datamanager.v1.UserListLicensePricing.toObject(message.historicalPricings[j], options); + } + if (message.metrics != null && message.hasOwnProperty("metrics")) + object.metrics = $root.google.ads.datamanager.v1.UserListLicenseMetrics.toObject(message.metrics, options); + return object; + }; + + /** + * Converts this UserListGlobalLicenseCustomerInfo to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @instance + * @returns {Object.} JSON object + */ + UserListGlobalLicenseCustomerInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserListGlobalLicenseCustomerInfo + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserListGlobalLicenseCustomerInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo"; + }; + + return UserListGlobalLicenseCustomerInfo; + })(); + + /** + * UserListGlobalLicenseType enum. + * @name google.ads.datamanager.v1.UserListGlobalLicenseType + * @enum {number} + * @property {number} USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED=0 USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED value + * @property {number} USER_LIST_GLOBAL_LICENSE_TYPE_RESELLER=1 USER_LIST_GLOBAL_LICENSE_TYPE_RESELLER value + * @property {number} USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_SELL_SIDE=2 USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_SELL_SIDE value + * @property {number} USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_BUY_SIDE=3 USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_BUY_SIDE value + */ + v1.UserListGlobalLicenseType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "USER_LIST_GLOBAL_LICENSE_TYPE_RESELLER"] = 1; + values[valuesById[2] = "USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_SELL_SIDE"] = 2; + values[valuesById[3] = "USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_BUY_SIDE"] = 3; + return values; + })(); + + v1.UserListGlobalLicenseService = (function() { + + /** + * Constructs a new UserListGlobalLicenseService service. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserListGlobalLicenseService + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function UserListGlobalLicenseService(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (UserListGlobalLicenseService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = UserListGlobalLicenseService; + + /** + * Creates new UserListGlobalLicenseService service using the specified rpc implementation. + * @function create + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {UserListGlobalLicenseService} RPC service. Useful where requests and/or responses are streamed. + */ + UserListGlobalLicenseService.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|createUserListGlobalLicense}. + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @typedef CreateUserListGlobalLicenseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserListGlobalLicense} [response] UserListGlobalLicense + */ + + /** + * Calls CreateUserListGlobalLicense. + * @function createUserListGlobalLicense + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest} request CreateUserListGlobalLicenseRequest message or plain object + * @param {google.ads.datamanager.v1.UserListGlobalLicenseService.CreateUserListGlobalLicenseCallback} callback Node-style callback called with the error, if any, and UserListGlobalLicense + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListGlobalLicenseService.prototype.createUserListGlobalLicense = function createUserListGlobalLicense(request, callback) { + return this.rpcCall(createUserListGlobalLicense, $root.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest, $root.google.ads.datamanager.v1.UserListGlobalLicense, request, callback); + }, "name", { value: "CreateUserListGlobalLicense" }); + + /** + * Calls CreateUserListGlobalLicense. + * @function createUserListGlobalLicense + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest} request CreateUserListGlobalLicenseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|updateUserListGlobalLicense}. + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @typedef UpdateUserListGlobalLicenseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserListGlobalLicense} [response] UserListGlobalLicense + */ + + /** + * Calls UpdateUserListGlobalLicense. + * @function updateUserListGlobalLicense + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest} request UpdateUserListGlobalLicenseRequest message or plain object + * @param {google.ads.datamanager.v1.UserListGlobalLicenseService.UpdateUserListGlobalLicenseCallback} callback Node-style callback called with the error, if any, and UserListGlobalLicense + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListGlobalLicenseService.prototype.updateUserListGlobalLicense = function updateUserListGlobalLicense(request, callback) { + return this.rpcCall(updateUserListGlobalLicense, $root.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest, $root.google.ads.datamanager.v1.UserListGlobalLicense, request, callback); + }, "name", { value: "UpdateUserListGlobalLicense" }); + + /** + * Calls UpdateUserListGlobalLicense. + * @function updateUserListGlobalLicense + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest} request UpdateUserListGlobalLicenseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|getUserListGlobalLicense}. + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @typedef GetUserListGlobalLicenseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserListGlobalLicense} [response] UserListGlobalLicense + */ + + /** + * Calls GetUserListGlobalLicense. + * @function getUserListGlobalLicense + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest} request GetUserListGlobalLicenseRequest message or plain object + * @param {google.ads.datamanager.v1.UserListGlobalLicenseService.GetUserListGlobalLicenseCallback} callback Node-style callback called with the error, if any, and UserListGlobalLicense + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListGlobalLicenseService.prototype.getUserListGlobalLicense = function getUserListGlobalLicense(request, callback) { + return this.rpcCall(getUserListGlobalLicense, $root.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest, $root.google.ads.datamanager.v1.UserListGlobalLicense, request, callback); + }, "name", { value: "GetUserListGlobalLicense" }); + + /** + * Calls GetUserListGlobalLicense. + * @function getUserListGlobalLicense + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest} request GetUserListGlobalLicenseRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|listUserListGlobalLicenses}. + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @typedef ListUserListGlobalLicensesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.ListUserListGlobalLicensesResponse} [response] ListUserListGlobalLicensesResponse + */ + + /** + * Calls ListUserListGlobalLicenses. + * @function listUserListGlobalLicenses + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesRequest} request ListUserListGlobalLicensesRequest message or plain object + * @param {google.ads.datamanager.v1.UserListGlobalLicenseService.ListUserListGlobalLicensesCallback} callback Node-style callback called with the error, if any, and ListUserListGlobalLicensesResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListGlobalLicenseService.prototype.listUserListGlobalLicenses = function listUserListGlobalLicenses(request, callback) { + return this.rpcCall(listUserListGlobalLicenses, $root.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest, $root.google.ads.datamanager.v1.ListUserListGlobalLicensesResponse, request, callback); + }, "name", { value: "ListUserListGlobalLicenses" }); + + /** + * Calls ListUserListGlobalLicenses. + * @function listUserListGlobalLicenses + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesRequest} request ListUserListGlobalLicensesRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListGlobalLicenseService|listUserListGlobalLicenseCustomerInfos}. + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @typedef ListUserListGlobalLicenseCustomerInfosCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse} [response] ListUserListGlobalLicenseCustomerInfosResponse + */ + + /** + * Calls ListUserListGlobalLicenseCustomerInfos. + * @function listUserListGlobalLicenseCustomerInfos + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest} request ListUserListGlobalLicenseCustomerInfosRequest message or plain object + * @param {google.ads.datamanager.v1.UserListGlobalLicenseService.ListUserListGlobalLicenseCustomerInfosCallback} callback Node-style callback called with the error, if any, and ListUserListGlobalLicenseCustomerInfosResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListGlobalLicenseService.prototype.listUserListGlobalLicenseCustomerInfos = function listUserListGlobalLicenseCustomerInfos(request, callback) { + return this.rpcCall(listUserListGlobalLicenseCustomerInfos, $root.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest, $root.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse, request, callback); + }, "name", { value: "ListUserListGlobalLicenseCustomerInfos" }); + + /** + * Calls ListUserListGlobalLicenseCustomerInfos. + * @function listUserListGlobalLicenseCustomerInfos + * @memberof google.ads.datamanager.v1.UserListGlobalLicenseService + * @instance + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest} request ListUserListGlobalLicenseCustomerInfosRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return UserListGlobalLicenseService; + })(); + + v1.CreateUserListGlobalLicenseRequest = (function() { + + /** + * Properties of a CreateUserListGlobalLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @interface ICreateUserListGlobalLicenseRequest + * @property {string|null} [parent] CreateUserListGlobalLicenseRequest parent + * @property {google.ads.datamanager.v1.IUserListGlobalLicense|null} [userListGlobalLicense] CreateUserListGlobalLicenseRequest userListGlobalLicense + */ + + /** + * Constructs a new CreateUserListGlobalLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a CreateUserListGlobalLicenseRequest. + * @implements ICreateUserListGlobalLicenseRequest + * @constructor + * @param {google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest=} [properties] Properties to set + */ + function CreateUserListGlobalLicenseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateUserListGlobalLicenseRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @instance + */ + CreateUserListGlobalLicenseRequest.prototype.parent = ""; + + /** + * CreateUserListGlobalLicenseRequest userListGlobalLicense. + * @member {google.ads.datamanager.v1.IUserListGlobalLicense|null|undefined} userListGlobalLicense + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @instance + */ + CreateUserListGlobalLicenseRequest.prototype.userListGlobalLicense = null; + + /** + * Creates a new CreateUserListGlobalLicenseRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest} CreateUserListGlobalLicenseRequest instance + */ + CreateUserListGlobalLicenseRequest.create = function create(properties) { + return new CreateUserListGlobalLicenseRequest(properties); + }; + + /** + * Encodes the specified CreateUserListGlobalLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest} message CreateUserListGlobalLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateUserListGlobalLicenseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.userListGlobalLicense != null && Object.hasOwnProperty.call(message, "userListGlobalLicense")) + $root.google.ads.datamanager.v1.UserListGlobalLicense.encode(message.userListGlobalLicense, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateUserListGlobalLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest} message CreateUserListGlobalLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateUserListGlobalLicenseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateUserListGlobalLicenseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest} CreateUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateUserListGlobalLicenseRequest.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.ads.datamanager.v1.CreateUserListGlobalLicenseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.userListGlobalLicense = $root.google.ads.datamanager.v1.UserListGlobalLicense.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CreateUserListGlobalLicenseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest} CreateUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateUserListGlobalLicenseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateUserListGlobalLicenseRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateUserListGlobalLicenseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.userListGlobalLicense != null && message.hasOwnProperty("userListGlobalLicense")) { + var error = $root.google.ads.datamanager.v1.UserListGlobalLicense.verify(message.userListGlobalLicense); + if (error) + return "userListGlobalLicense." + error; + } + return null; + }; + + /** + * Creates a CreateUserListGlobalLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest} CreateUserListGlobalLicenseRequest + */ + CreateUserListGlobalLicenseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest) + return object; + var message = new $root.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.userListGlobalLicense != null) { + if (typeof object.userListGlobalLicense !== "object") + throw TypeError(".google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest.userListGlobalLicense: object expected"); + message.userListGlobalLicense = $root.google.ads.datamanager.v1.UserListGlobalLicense.fromObject(object.userListGlobalLicense); + } + return message; + }; + + /** + * Creates a plain object from a CreateUserListGlobalLicenseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest} message CreateUserListGlobalLicenseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateUserListGlobalLicenseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.userListGlobalLicense = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.userListGlobalLicense != null && message.hasOwnProperty("userListGlobalLicense")) + object.userListGlobalLicense = $root.google.ads.datamanager.v1.UserListGlobalLicense.toObject(message.userListGlobalLicense, options); + return object; + }; + + /** + * Converts this CreateUserListGlobalLicenseRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @instance + * @returns {Object.} JSON object + */ + CreateUserListGlobalLicenseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateUserListGlobalLicenseRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateUserListGlobalLicenseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest"; + }; + + return CreateUserListGlobalLicenseRequest; + })(); + + v1.UpdateUserListGlobalLicenseRequest = (function() { + + /** + * Properties of an UpdateUserListGlobalLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @interface IUpdateUserListGlobalLicenseRequest + * @property {google.ads.datamanager.v1.IUserListGlobalLicense|null} [userListGlobalLicense] UpdateUserListGlobalLicenseRequest userListGlobalLicense + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateUserListGlobalLicenseRequest updateMask + */ + + /** + * Constructs a new UpdateUserListGlobalLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents an UpdateUserListGlobalLicenseRequest. + * @implements IUpdateUserListGlobalLicenseRequest + * @constructor + * @param {google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest=} [properties] Properties to set + */ + function UpdateUserListGlobalLicenseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateUserListGlobalLicenseRequest userListGlobalLicense. + * @member {google.ads.datamanager.v1.IUserListGlobalLicense|null|undefined} userListGlobalLicense + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @instance + */ + UpdateUserListGlobalLicenseRequest.prototype.userListGlobalLicense = null; + + /** + * UpdateUserListGlobalLicenseRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @instance + */ + UpdateUserListGlobalLicenseRequest.prototype.updateMask = null; + + /** + * Creates a new UpdateUserListGlobalLicenseRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest} UpdateUserListGlobalLicenseRequest instance + */ + UpdateUserListGlobalLicenseRequest.create = function create(properties) { + return new UpdateUserListGlobalLicenseRequest(properties); + }; + + /** + * Encodes the specified UpdateUserListGlobalLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest} message UpdateUserListGlobalLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateUserListGlobalLicenseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userListGlobalLicense != null && Object.hasOwnProperty.call(message, "userListGlobalLicense")) + $root.google.ads.datamanager.v1.UserListGlobalLicense.encode(message.userListGlobalLicense, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + $root.google.protobuf.FieldMask.encode(message.updateMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateUserListGlobalLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest} message UpdateUserListGlobalLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateUserListGlobalLicenseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateUserListGlobalLicenseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest} UpdateUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateUserListGlobalLicenseRequest.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.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.userListGlobalLicense = $root.google.ads.datamanager.v1.UserListGlobalLicense.decode(reader, reader.uint32()); + break; + } + case 2: { + message.updateMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateUserListGlobalLicenseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest} UpdateUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateUserListGlobalLicenseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateUserListGlobalLicenseRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateUserListGlobalLicenseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userListGlobalLicense != null && message.hasOwnProperty("userListGlobalLicense")) { + var error = $root.google.ads.datamanager.v1.UserListGlobalLicense.verify(message.userListGlobalLicense); + if (error) + return "userListGlobalLicense." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.updateMask); + if (error) + return "updateMask." + error; + } + return null; + }; + + /** + * Creates an UpdateUserListGlobalLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest} UpdateUserListGlobalLicenseRequest + */ + UpdateUserListGlobalLicenseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest) + return object; + var message = new $root.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest(); + if (object.userListGlobalLicense != null) { + if (typeof object.userListGlobalLicense !== "object") + throw TypeError(".google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest.userListGlobalLicense: object expected"); + message.userListGlobalLicense = $root.google.ads.datamanager.v1.UserListGlobalLicense.fromObject(object.userListGlobalLicense); + } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + return message; + }; + + /** + * Creates a plain object from an UpdateUserListGlobalLicenseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest} message UpdateUserListGlobalLicenseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateUserListGlobalLicenseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.userListGlobalLicense = null; + object.updateMask = null; + } + if (message.userListGlobalLicense != null && message.hasOwnProperty("userListGlobalLicense")) + object.userListGlobalLicense = $root.google.ads.datamanager.v1.UserListGlobalLicense.toObject(message.userListGlobalLicense, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + return object; + }; + + /** + * Converts this UpdateUserListGlobalLicenseRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateUserListGlobalLicenseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateUserListGlobalLicenseRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateUserListGlobalLicenseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest"; + }; + + return UpdateUserListGlobalLicenseRequest; + })(); + + v1.GetUserListGlobalLicenseRequest = (function() { + + /** + * Properties of a GetUserListGlobalLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @interface IGetUserListGlobalLicenseRequest + * @property {string|null} [name] GetUserListGlobalLicenseRequest name + */ + + /** + * Constructs a new GetUserListGlobalLicenseRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a GetUserListGlobalLicenseRequest. + * @implements IGetUserListGlobalLicenseRequest + * @constructor + * @param {google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest=} [properties] Properties to set + */ + function GetUserListGlobalLicenseRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetUserListGlobalLicenseRequest name. + * @member {string} name + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @instance + */ + GetUserListGlobalLicenseRequest.prototype.name = ""; + + /** + * Creates a new GetUserListGlobalLicenseRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.GetUserListGlobalLicenseRequest} GetUserListGlobalLicenseRequest instance + */ + GetUserListGlobalLicenseRequest.create = function create(properties) { + return new GetUserListGlobalLicenseRequest(properties); + }; + + /** + * Encodes the specified GetUserListGlobalLicenseRequest message. Does not implicitly {@link google.ads.datamanager.v1.GetUserListGlobalLicenseRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest} message GetUserListGlobalLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetUserListGlobalLicenseRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetUserListGlobalLicenseRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.GetUserListGlobalLicenseRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest} message GetUserListGlobalLicenseRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetUserListGlobalLicenseRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetUserListGlobalLicenseRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.GetUserListGlobalLicenseRequest} GetUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetUserListGlobalLicenseRequest.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.ads.datamanager.v1.GetUserListGlobalLicenseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetUserListGlobalLicenseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.GetUserListGlobalLicenseRequest} GetUserListGlobalLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetUserListGlobalLicenseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetUserListGlobalLicenseRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetUserListGlobalLicenseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetUserListGlobalLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.GetUserListGlobalLicenseRequest} GetUserListGlobalLicenseRequest + */ + GetUserListGlobalLicenseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest) + return object; + var message = new $root.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetUserListGlobalLicenseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {google.ads.datamanager.v1.GetUserListGlobalLicenseRequest} message GetUserListGlobalLicenseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetUserListGlobalLicenseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetUserListGlobalLicenseRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @instance + * @returns {Object.} JSON object + */ + GetUserListGlobalLicenseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetUserListGlobalLicenseRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.GetUserListGlobalLicenseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetUserListGlobalLicenseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.GetUserListGlobalLicenseRequest"; + }; + + return GetUserListGlobalLicenseRequest; + })(); + + v1.ListUserListGlobalLicensesRequest = (function() { + + /** + * Properties of a ListUserListGlobalLicensesRequest. + * @memberof google.ads.datamanager.v1 + * @interface IListUserListGlobalLicensesRequest + * @property {string|null} [parent] ListUserListGlobalLicensesRequest parent + * @property {string|null} [filter] ListUserListGlobalLicensesRequest filter + * @property {number|null} [pageSize] ListUserListGlobalLicensesRequest pageSize + * @property {string|null} [pageToken] ListUserListGlobalLicensesRequest pageToken + */ + + /** + * Constructs a new ListUserListGlobalLicensesRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ListUserListGlobalLicensesRequest. + * @implements IListUserListGlobalLicensesRequest + * @constructor + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesRequest=} [properties] Properties to set + */ + function ListUserListGlobalLicensesRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserListGlobalLicensesRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @instance + */ + ListUserListGlobalLicensesRequest.prototype.parent = ""; + + /** + * ListUserListGlobalLicensesRequest filter. + * @member {string} filter + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @instance + */ + ListUserListGlobalLicensesRequest.prototype.filter = ""; + + /** + * ListUserListGlobalLicensesRequest pageSize. + * @member {number} pageSize + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @instance + */ + ListUserListGlobalLicensesRequest.prototype.pageSize = 0; + + /** + * ListUserListGlobalLicensesRequest pageToken. + * @member {string} pageToken + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @instance + */ + ListUserListGlobalLicensesRequest.prototype.pageToken = ""; + + /** + * Creates a new ListUserListGlobalLicensesRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicensesRequest} ListUserListGlobalLicensesRequest instance + */ + ListUserListGlobalLicensesRequest.create = function create(properties) { + return new ListUserListGlobalLicensesRequest(properties); + }; + + /** + * Encodes the specified ListUserListGlobalLicensesRequest message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicensesRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesRequest} message ListUserListGlobalLicensesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListGlobalLicensesRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListUserListGlobalLicensesRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicensesRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesRequest} message ListUserListGlobalLicensesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListGlobalLicensesRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListUserListGlobalLicensesRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicensesRequest} ListUserListGlobalLicensesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListGlobalLicensesRequest.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.ads.datamanager.v1.ListUserListGlobalLicensesRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListUserListGlobalLicensesRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicensesRequest} ListUserListGlobalLicensesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListGlobalLicensesRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListUserListGlobalLicensesRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListUserListGlobalLicensesRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListUserListGlobalLicensesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicensesRequest} ListUserListGlobalLicensesRequest + */ + ListUserListGlobalLicensesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest) + return object; + var message = new $root.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListUserListGlobalLicensesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {google.ads.datamanager.v1.ListUserListGlobalLicensesRequest} message ListUserListGlobalLicensesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserListGlobalLicensesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListUserListGlobalLicensesRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @instance + * @returns {Object.} JSON object + */ + ListUserListGlobalLicensesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserListGlobalLicensesRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserListGlobalLicensesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ListUserListGlobalLicensesRequest"; + }; + + return ListUserListGlobalLicensesRequest; + })(); + + v1.ListUserListGlobalLicensesResponse = (function() { + + /** + * Properties of a ListUserListGlobalLicensesResponse. + * @memberof google.ads.datamanager.v1 + * @interface IListUserListGlobalLicensesResponse + * @property {Array.|null} [userListGlobalLicenses] ListUserListGlobalLicensesResponse userListGlobalLicenses + * @property {string|null} [nextPageToken] ListUserListGlobalLicensesResponse nextPageToken + */ + + /** + * Constructs a new ListUserListGlobalLicensesResponse. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ListUserListGlobalLicensesResponse. + * @implements IListUserListGlobalLicensesResponse + * @constructor + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesResponse=} [properties] Properties to set + */ + function ListUserListGlobalLicensesResponse(properties) { + this.userListGlobalLicenses = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserListGlobalLicensesResponse userListGlobalLicenses. + * @member {Array.} userListGlobalLicenses + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @instance + */ + ListUserListGlobalLicensesResponse.prototype.userListGlobalLicenses = $util.emptyArray; + + /** + * ListUserListGlobalLicensesResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @instance + */ + ListUserListGlobalLicensesResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListUserListGlobalLicensesResponse instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesResponse=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicensesResponse} ListUserListGlobalLicensesResponse instance + */ + ListUserListGlobalLicensesResponse.create = function create(properties) { + return new ListUserListGlobalLicensesResponse(properties); + }; + + /** + * Encodes the specified ListUserListGlobalLicensesResponse message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicensesResponse.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesResponse} message ListUserListGlobalLicensesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListGlobalLicensesResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userListGlobalLicenses != null && message.userListGlobalLicenses.length) + for (var i = 0; i < message.userListGlobalLicenses.length; ++i) + $root.google.ads.datamanager.v1.UserListGlobalLicense.encode(message.userListGlobalLicenses[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListUserListGlobalLicensesResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicensesResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicensesResponse} message ListUserListGlobalLicensesResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListGlobalLicensesResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListUserListGlobalLicensesResponse message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicensesResponse} ListUserListGlobalLicensesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListGlobalLicensesResponse.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.ads.datamanager.v1.ListUserListGlobalLicensesResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.userListGlobalLicenses && message.userListGlobalLicenses.length)) + message.userListGlobalLicenses = []; + message.userListGlobalLicenses.push($root.google.ads.datamanager.v1.UserListGlobalLicense.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListUserListGlobalLicensesResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicensesResponse} ListUserListGlobalLicensesResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListGlobalLicensesResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListUserListGlobalLicensesResponse message. + * @function verify + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListUserListGlobalLicensesResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userListGlobalLicenses != null && message.hasOwnProperty("userListGlobalLicenses")) { + if (!Array.isArray(message.userListGlobalLicenses)) + return "userListGlobalLicenses: array expected"; + for (var i = 0; i < message.userListGlobalLicenses.length; ++i) { + var error = $root.google.ads.datamanager.v1.UserListGlobalLicense.verify(message.userListGlobalLicenses[i]); + if (error) + return "userListGlobalLicenses." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListUserListGlobalLicensesResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicensesResponse} ListUserListGlobalLicensesResponse + */ + ListUserListGlobalLicensesResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ListUserListGlobalLicensesResponse) + return object; + var message = new $root.google.ads.datamanager.v1.ListUserListGlobalLicensesResponse(); + if (object.userListGlobalLicenses) { + if (!Array.isArray(object.userListGlobalLicenses)) + throw TypeError(".google.ads.datamanager.v1.ListUserListGlobalLicensesResponse.userListGlobalLicenses: array expected"); + message.userListGlobalLicenses = []; + for (var i = 0; i < object.userListGlobalLicenses.length; ++i) { + if (typeof object.userListGlobalLicenses[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.ListUserListGlobalLicensesResponse.userListGlobalLicenses: object expected"); + message.userListGlobalLicenses[i] = $root.google.ads.datamanager.v1.UserListGlobalLicense.fromObject(object.userListGlobalLicenses[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListUserListGlobalLicensesResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {google.ads.datamanager.v1.ListUserListGlobalLicensesResponse} message ListUserListGlobalLicensesResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserListGlobalLicensesResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.userListGlobalLicenses = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.userListGlobalLicenses && message.userListGlobalLicenses.length) { + object.userListGlobalLicenses = []; + for (var j = 0; j < message.userListGlobalLicenses.length; ++j) + object.userListGlobalLicenses[j] = $root.google.ads.datamanager.v1.UserListGlobalLicense.toObject(message.userListGlobalLicenses[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListUserListGlobalLicensesResponse to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @instance + * @returns {Object.} JSON object + */ + ListUserListGlobalLicensesResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserListGlobalLicensesResponse + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicensesResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserListGlobalLicensesResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ListUserListGlobalLicensesResponse"; + }; + + return ListUserListGlobalLicensesResponse; + })(); + + v1.ListUserListGlobalLicenseCustomerInfosRequest = (function() { + + /** + * Properties of a ListUserListGlobalLicenseCustomerInfosRequest. + * @memberof google.ads.datamanager.v1 + * @interface IListUserListGlobalLicenseCustomerInfosRequest + * @property {string|null} [parent] ListUserListGlobalLicenseCustomerInfosRequest parent + * @property {string|null} [filter] ListUserListGlobalLicenseCustomerInfosRequest filter + * @property {number|null} [pageSize] ListUserListGlobalLicenseCustomerInfosRequest pageSize + * @property {string|null} [pageToken] ListUserListGlobalLicenseCustomerInfosRequest pageToken + */ + + /** + * Constructs a new ListUserListGlobalLicenseCustomerInfosRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ListUserListGlobalLicenseCustomerInfosRequest. + * @implements IListUserListGlobalLicenseCustomerInfosRequest + * @constructor + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest=} [properties] Properties to set + */ + function ListUserListGlobalLicenseCustomerInfosRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserListGlobalLicenseCustomerInfosRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @instance + */ + ListUserListGlobalLicenseCustomerInfosRequest.prototype.parent = ""; + + /** + * ListUserListGlobalLicenseCustomerInfosRequest filter. + * @member {string} filter + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @instance + */ + ListUserListGlobalLicenseCustomerInfosRequest.prototype.filter = ""; + + /** + * ListUserListGlobalLicenseCustomerInfosRequest pageSize. + * @member {number} pageSize + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @instance + */ + ListUserListGlobalLicenseCustomerInfosRequest.prototype.pageSize = 0; + + /** + * ListUserListGlobalLicenseCustomerInfosRequest pageToken. + * @member {string} pageToken + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @instance + */ + ListUserListGlobalLicenseCustomerInfosRequest.prototype.pageToken = ""; + + /** + * Creates a new ListUserListGlobalLicenseCustomerInfosRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest} ListUserListGlobalLicenseCustomerInfosRequest instance + */ + ListUserListGlobalLicenseCustomerInfosRequest.create = function create(properties) { + return new ListUserListGlobalLicenseCustomerInfosRequest(properties); + }; + + /** + * Encodes the specified ListUserListGlobalLicenseCustomerInfosRequest message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest} message ListUserListGlobalLicenseCustomerInfosRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListGlobalLicenseCustomerInfosRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.filter); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.pageToken); + return writer; + }; + + /** + * Encodes the specified ListUserListGlobalLicenseCustomerInfosRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest} message ListUserListGlobalLicenseCustomerInfosRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListGlobalLicenseCustomerInfosRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListUserListGlobalLicenseCustomerInfosRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest} ListUserListGlobalLicenseCustomerInfosRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListGlobalLicenseCustomerInfosRequest.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.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.filter = reader.string(); + break; + } + case 3: { + message.pageSize = reader.int32(); + break; + } + case 4: { + message.pageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListUserListGlobalLicenseCustomerInfosRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest} ListUserListGlobalLicenseCustomerInfosRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListGlobalLicenseCustomerInfosRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListUserListGlobalLicenseCustomerInfosRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListUserListGlobalLicenseCustomerInfosRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + return null; + }; + + /** + * Creates a ListUserListGlobalLicenseCustomerInfosRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest} ListUserListGlobalLicenseCustomerInfosRequest + */ + ListUserListGlobalLicenseCustomerInfosRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest) + return object; + var message = new $root.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.filter != null) + message.filter = String(object.filter); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + return message; + }; + + /** + * Creates a plain object from a ListUserListGlobalLicenseCustomerInfosRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest} message ListUserListGlobalLicenseCustomerInfosRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserListGlobalLicenseCustomerInfosRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.filter = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + return object; + }; + + /** + * Converts this ListUserListGlobalLicenseCustomerInfosRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @instance + * @returns {Object.} JSON object + */ + ListUserListGlobalLicenseCustomerInfosRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserListGlobalLicenseCustomerInfosRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserListGlobalLicenseCustomerInfosRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest"; + }; + + return ListUserListGlobalLicenseCustomerInfosRequest; + })(); + + v1.ListUserListGlobalLicenseCustomerInfosResponse = (function() { + + /** + * Properties of a ListUserListGlobalLicenseCustomerInfosResponse. + * @memberof google.ads.datamanager.v1 + * @interface IListUserListGlobalLicenseCustomerInfosResponse + * @property {Array.|null} [userListGlobalLicenseCustomerInfos] ListUserListGlobalLicenseCustomerInfosResponse userListGlobalLicenseCustomerInfos + * @property {string|null} [nextPageToken] ListUserListGlobalLicenseCustomerInfosResponse nextPageToken + */ + + /** + * Constructs a new ListUserListGlobalLicenseCustomerInfosResponse. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ListUserListGlobalLicenseCustomerInfosResponse. + * @implements IListUserListGlobalLicenseCustomerInfosResponse + * @constructor + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse=} [properties] Properties to set + */ + function ListUserListGlobalLicenseCustomerInfosResponse(properties) { + this.userListGlobalLicenseCustomerInfos = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserListGlobalLicenseCustomerInfosResponse userListGlobalLicenseCustomerInfos. + * @member {Array.} userListGlobalLicenseCustomerInfos + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @instance + */ + ListUserListGlobalLicenseCustomerInfosResponse.prototype.userListGlobalLicenseCustomerInfos = $util.emptyArray; + + /** + * ListUserListGlobalLicenseCustomerInfosResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @instance + */ + ListUserListGlobalLicenseCustomerInfosResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListUserListGlobalLicenseCustomerInfosResponse instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse} ListUserListGlobalLicenseCustomerInfosResponse instance + */ + ListUserListGlobalLicenseCustomerInfosResponse.create = function create(properties) { + return new ListUserListGlobalLicenseCustomerInfosResponse(properties); + }; + + /** + * Encodes the specified ListUserListGlobalLicenseCustomerInfosResponse message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse} message ListUserListGlobalLicenseCustomerInfosResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListGlobalLicenseCustomerInfosResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userListGlobalLicenseCustomerInfos != null && message.userListGlobalLicenseCustomerInfos.length) + for (var i = 0; i < message.userListGlobalLicenseCustomerInfos.length; ++i) + $root.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.encode(message.userListGlobalLicenseCustomerInfos[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListUserListGlobalLicenseCustomerInfosResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse} message ListUserListGlobalLicenseCustomerInfosResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListGlobalLicenseCustomerInfosResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListUserListGlobalLicenseCustomerInfosResponse message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse} ListUserListGlobalLicenseCustomerInfosResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListGlobalLicenseCustomerInfosResponse.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.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.userListGlobalLicenseCustomerInfos && message.userListGlobalLicenseCustomerInfos.length)) + message.userListGlobalLicenseCustomerInfos = []; + message.userListGlobalLicenseCustomerInfos.push($root.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListUserListGlobalLicenseCustomerInfosResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse} ListUserListGlobalLicenseCustomerInfosResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListGlobalLicenseCustomerInfosResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListUserListGlobalLicenseCustomerInfosResponse message. + * @function verify + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListUserListGlobalLicenseCustomerInfosResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userListGlobalLicenseCustomerInfos != null && message.hasOwnProperty("userListGlobalLicenseCustomerInfos")) { + if (!Array.isArray(message.userListGlobalLicenseCustomerInfos)) + return "userListGlobalLicenseCustomerInfos: array expected"; + for (var i = 0; i < message.userListGlobalLicenseCustomerInfos.length; ++i) { + var error = $root.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.verify(message.userListGlobalLicenseCustomerInfos[i]); + if (error) + return "userListGlobalLicenseCustomerInfos." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + return null; + }; + + /** + * Creates a ListUserListGlobalLicenseCustomerInfosResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse} ListUserListGlobalLicenseCustomerInfosResponse + */ + ListUserListGlobalLicenseCustomerInfosResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse) + return object; + var message = new $root.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse(); + if (object.userListGlobalLicenseCustomerInfos) { + if (!Array.isArray(object.userListGlobalLicenseCustomerInfos)) + throw TypeError(".google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse.userListGlobalLicenseCustomerInfos: array expected"); + message.userListGlobalLicenseCustomerInfos = []; + for (var i = 0; i < object.userListGlobalLicenseCustomerInfos.length; ++i) { + if (typeof object.userListGlobalLicenseCustomerInfos[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse.userListGlobalLicenseCustomerInfos: object expected"); + message.userListGlobalLicenseCustomerInfos[i] = $root.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.fromObject(object.userListGlobalLicenseCustomerInfos[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListUserListGlobalLicenseCustomerInfosResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse} message ListUserListGlobalLicenseCustomerInfosResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserListGlobalLicenseCustomerInfosResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.userListGlobalLicenseCustomerInfos = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.userListGlobalLicenseCustomerInfos && message.userListGlobalLicenseCustomerInfos.length) { + object.userListGlobalLicenseCustomerInfos = []; + for (var j = 0; j < message.userListGlobalLicenseCustomerInfos.length; ++j) + object.userListGlobalLicenseCustomerInfos[j] = $root.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo.toObject(message.userListGlobalLicenseCustomerInfos[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListUserListGlobalLicenseCustomerInfosResponse to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @instance + * @returns {Object.} JSON object + */ + ListUserListGlobalLicenseCustomerInfosResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserListGlobalLicenseCustomerInfosResponse + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserListGlobalLicenseCustomerInfosResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse"; + }; + + return ListUserListGlobalLicenseCustomerInfosResponse; + })(); + + v1.UserListService = (function() { + + /** + * Constructs a new UserListService service. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a UserListService + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function UserListService(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (UserListService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = UserListService; + + /** + * Creates new UserListService service using the specified rpc implementation. + * @function create + * @memberof google.ads.datamanager.v1.UserListService + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {UserListService} RPC service. Useful where requests and/or responses are streamed. + */ + UserListService.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|getUserList}. + * @memberof google.ads.datamanager.v1.UserListService + * @typedef GetUserListCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserList} [response] UserList + */ + + /** + * Calls GetUserList. + * @function getUserList + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.IGetUserListRequest} request GetUserListRequest message or plain object + * @param {google.ads.datamanager.v1.UserListService.GetUserListCallback} callback Node-style callback called with the error, if any, and UserList + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListService.prototype.getUserList = function getUserList(request, callback) { + return this.rpcCall(getUserList, $root.google.ads.datamanager.v1.GetUserListRequest, $root.google.ads.datamanager.v1.UserList, request, callback); + }, "name", { value: "GetUserList" }); + + /** + * Calls GetUserList. + * @function getUserList + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.IGetUserListRequest} request GetUserListRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|listUserLists}. + * @memberof google.ads.datamanager.v1.UserListService + * @typedef ListUserListsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.ListUserListsResponse} [response] ListUserListsResponse + */ + + /** + * Calls ListUserLists. + * @function listUserLists + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.IListUserListsRequest} request ListUserListsRequest message or plain object + * @param {google.ads.datamanager.v1.UserListService.ListUserListsCallback} callback Node-style callback called with the error, if any, and ListUserListsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListService.prototype.listUserLists = function listUserLists(request, callback) { + return this.rpcCall(listUserLists, $root.google.ads.datamanager.v1.ListUserListsRequest, $root.google.ads.datamanager.v1.ListUserListsResponse, request, callback); + }, "name", { value: "ListUserLists" }); + + /** + * Calls ListUserLists. + * @function listUserLists + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.IListUserListsRequest} request ListUserListsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|createUserList}. + * @memberof google.ads.datamanager.v1.UserListService + * @typedef CreateUserListCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserList} [response] UserList + */ + + /** + * Calls CreateUserList. + * @function createUserList + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.ICreateUserListRequest} request CreateUserListRequest message or plain object + * @param {google.ads.datamanager.v1.UserListService.CreateUserListCallback} callback Node-style callback called with the error, if any, and UserList + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListService.prototype.createUserList = function createUserList(request, callback) { + return this.rpcCall(createUserList, $root.google.ads.datamanager.v1.CreateUserListRequest, $root.google.ads.datamanager.v1.UserList, request, callback); + }, "name", { value: "CreateUserList" }); + + /** + * Calls CreateUserList. + * @function createUserList + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.ICreateUserListRequest} request CreateUserListRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|updateUserList}. + * @memberof google.ads.datamanager.v1.UserListService + * @typedef UpdateUserListCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.ads.datamanager.v1.UserList} [response] UserList + */ + + /** + * Calls UpdateUserList. + * @function updateUserList + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.IUpdateUserListRequest} request UpdateUserListRequest message or plain object + * @param {google.ads.datamanager.v1.UserListService.UpdateUserListCallback} callback Node-style callback called with the error, if any, and UserList + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListService.prototype.updateUserList = function updateUserList(request, callback) { + return this.rpcCall(updateUserList, $root.google.ads.datamanager.v1.UpdateUserListRequest, $root.google.ads.datamanager.v1.UserList, request, callback); + }, "name", { value: "UpdateUserList" }); + + /** + * Calls UpdateUserList. + * @function updateUserList + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.IUpdateUserListRequest} request UpdateUserListRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.ads.datamanager.v1.UserListService|deleteUserList}. + * @memberof google.ads.datamanager.v1.UserListService + * @typedef DeleteUserListCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteUserList. + * @function deleteUserList + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.IDeleteUserListRequest} request DeleteUserListRequest message or plain object + * @param {google.ads.datamanager.v1.UserListService.DeleteUserListCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(UserListService.prototype.deleteUserList = function deleteUserList(request, callback) { + return this.rpcCall(deleteUserList, $root.google.ads.datamanager.v1.DeleteUserListRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteUserList" }); + + /** + * Calls DeleteUserList. + * @function deleteUserList + * @memberof google.ads.datamanager.v1.UserListService + * @instance + * @param {google.ads.datamanager.v1.IDeleteUserListRequest} request DeleteUserListRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return UserListService; + })(); + + v1.GetUserListRequest = (function() { + + /** + * Properties of a GetUserListRequest. + * @memberof google.ads.datamanager.v1 + * @interface IGetUserListRequest + * @property {string|null} [name] GetUserListRequest name + */ + + /** + * Constructs a new GetUserListRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a GetUserListRequest. + * @implements IGetUserListRequest + * @constructor + * @param {google.ads.datamanager.v1.IGetUserListRequest=} [properties] Properties to set + */ + function GetUserListRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetUserListRequest name. + * @member {string} name + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @instance + */ + GetUserListRequest.prototype.name = ""; + + /** + * Creates a new GetUserListRequest instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.GetUserListRequest} GetUserListRequest instance + */ + GetUserListRequest.create = function create(properties) { + return new GetUserListRequest(properties); + }; + + /** + * Encodes the specified GetUserListRequest message. Does not implicitly {@link google.ads.datamanager.v1.GetUserListRequest.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListRequest} message GetUserListRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetUserListRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetUserListRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.GetUserListRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {google.ads.datamanager.v1.IGetUserListRequest} message GetUserListRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetUserListRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; /** - * Constructs a new ErrorCount. + * Decodes a GetUserListRequest message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.GetUserListRequest} GetUserListRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetUserListRequest.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.ads.datamanager.v1.GetUserListRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetUserListRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.GetUserListRequest} GetUserListRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetUserListRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetUserListRequest message. + * @function verify + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetUserListRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetUserListRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.GetUserListRequest} GetUserListRequest + */ + GetUserListRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.GetUserListRequest) + return object; + var message = new $root.google.ads.datamanager.v1.GetUserListRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetUserListRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {google.ads.datamanager.v1.GetUserListRequest} message GetUserListRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetUserListRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetUserListRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @instance + * @returns {Object.} JSON object + */ + GetUserListRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetUserListRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.GetUserListRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetUserListRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.GetUserListRequest"; + }; + + return GetUserListRequest; + })(); + + v1.ListUserListsRequest = (function() { + + /** + * Properties of a ListUserListsRequest. * @memberof google.ads.datamanager.v1 - * @classdesc Represents an ErrorCount. - * @implements IErrorCount + * @interface IListUserListsRequest + * @property {string|null} [parent] ListUserListsRequest parent + * @property {number|null} [pageSize] ListUserListsRequest pageSize + * @property {string|null} [pageToken] ListUserListsRequest pageToken + * @property {string|null} [filter] ListUserListsRequest filter + */ + + /** + * Constructs a new ListUserListsRequest. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ListUserListsRequest. + * @implements IListUserListsRequest * @constructor - * @param {google.ads.datamanager.v1.IErrorCount=} [properties] Properties to set + * @param {google.ads.datamanager.v1.IListUserListsRequest=} [properties] Properties to set */ - function ErrorCount(properties) { + function ListUserListsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -12790,91 +28968,119 @@ } /** - * ErrorCount recordCount. - * @member {number|Long} recordCount - * @memberof google.ads.datamanager.v1.ErrorCount + * ListUserListsRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.ListUserListsRequest * @instance */ - ErrorCount.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + ListUserListsRequest.prototype.parent = ""; /** - * ErrorCount reason. - * @member {google.ads.datamanager.v1.ProcessingErrorReason} reason - * @memberof google.ads.datamanager.v1.ErrorCount + * ListUserListsRequest pageSize. + * @member {number} pageSize + * @memberof google.ads.datamanager.v1.ListUserListsRequest * @instance */ - ErrorCount.prototype.reason = 0; + ListUserListsRequest.prototype.pageSize = 0; /** - * Creates a new ErrorCount instance using the specified properties. + * ListUserListsRequest pageToken. + * @member {string} pageToken + * @memberof google.ads.datamanager.v1.ListUserListsRequest + * @instance + */ + ListUserListsRequest.prototype.pageToken = ""; + + /** + * ListUserListsRequest filter. + * @member {string} filter + * @memberof google.ads.datamanager.v1.ListUserListsRequest + * @instance + */ + ListUserListsRequest.prototype.filter = ""; + + /** + * Creates a new ListUserListsRequest instance using the specified properties. * @function create - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsRequest * @static - * @param {google.ads.datamanager.v1.IErrorCount=} [properties] Properties to set - * @returns {google.ads.datamanager.v1.ErrorCount} ErrorCount instance + * @param {google.ads.datamanager.v1.IListUserListsRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ListUserListsRequest} ListUserListsRequest instance */ - ErrorCount.create = function create(properties) { - return new ErrorCount(properties); + ListUserListsRequest.create = function create(properties) { + return new ListUserListsRequest(properties); }; /** - * Encodes the specified ErrorCount message. Does not implicitly {@link google.ads.datamanager.v1.ErrorCount.verify|verify} messages. + * Encodes the specified ListUserListsRequest message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListsRequest.verify|verify} messages. * @function encode - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsRequest * @static - * @param {google.ads.datamanager.v1.IErrorCount} message ErrorCount message or plain object to encode + * @param {google.ads.datamanager.v1.IListUserListsRequest} message ListUserListsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ErrorCount.encode = function encode(message, writer) { + ListUserListsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.recordCount); - if (message.reason != null && Object.hasOwnProperty.call(message, "reason")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.reason); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.pageSize != null && Object.hasOwnProperty.call(message, "pageSize")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pageSize); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.pageToken); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.filter); return writer; }; /** - * Encodes the specified ErrorCount message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ErrorCount.verify|verify} messages. + * Encodes the specified ListUserListsRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsRequest * @static - * @param {google.ads.datamanager.v1.IErrorCount} message ErrorCount message or plain object to encode + * @param {google.ads.datamanager.v1.IListUserListsRequest} message ListUserListsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ErrorCount.encodeDelimited = function encodeDelimited(message, writer) { + ListUserListsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes an ErrorCount message from the specified reader or buffer. + * Decodes a ListUserListsRequest message from the specified reader or buffer. * @function decode - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.ads.datamanager.v1.ErrorCount} ErrorCount + * @returns {google.ads.datamanager.v1.ListUserListsRequest} ListUserListsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ErrorCount.decode = function decode(reader, length, error) { + ListUserListsRequest.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.ads.datamanager.v1.ErrorCount(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.ads.datamanager.v1.ListUserListsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { case 1: { - message.recordCount = reader.int64(); + message.parent = reader.string(); break; } case 2: { - message.reason = reader.int32(); + message.pageSize = reader.int32(); + break; + } + case 3: { + message.pageToken = reader.string(); + break; + } + case 4: { + message.filter = reader.string(); break; } default: @@ -12886,295 +29092,399 @@ }; /** - * Decodes an ErrorCount message from the specified reader or buffer, length delimited. + * Decodes a ListUserListsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.ads.datamanager.v1.ErrorCount} ErrorCount + * @returns {google.ads.datamanager.v1.ListUserListsRequest} ListUserListsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ErrorCount.decodeDelimited = function decodeDelimited(reader) { + ListUserListsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies an ErrorCount message. + * Verifies a ListUserListsRequest message. * @function verify - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ErrorCount.verify = function verify(message) { + ListUserListsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; - if (message.recordCount != null && message.hasOwnProperty("recordCount")) - if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) - return "recordCount: integer|Long expected"; - if (message.reason != null && message.hasOwnProperty("reason")) - switch (message.reason) { + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + if (!$util.isInteger(message.pageSize)) + return "pageSize: integer expected"; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + if (message.filter != null && message.hasOwnProperty("filter")) + if (!$util.isString(message.filter)) + return "filter: string expected"; + return null; + }; + + /** + * Creates a ListUserListsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.ads.datamanager.v1.ListUserListsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.ads.datamanager.v1.ListUserListsRequest} ListUserListsRequest + */ + ListUserListsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ListUserListsRequest) + return object; + var message = new $root.google.ads.datamanager.v1.ListUserListsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.filter != null) + message.filter = String(object.filter); + return message; + }; + + /** + * Creates a plain object from a ListUserListsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.ads.datamanager.v1.ListUserListsRequest + * @static + * @param {google.ads.datamanager.v1.ListUserListsRequest} message ListUserListsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserListsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + object.filter = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.filter != null && message.hasOwnProperty("filter")) + object.filter = message.filter; + return object; + }; + + /** + * Converts this ListUserListsRequest to JSON. + * @function toJSON + * @memberof google.ads.datamanager.v1.ListUserListsRequest + * @instance + * @returns {Object.} JSON object + */ + ListUserListsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserListsRequest + * @function getTypeUrl + * @memberof google.ads.datamanager.v1.ListUserListsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserListsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.ads.datamanager.v1.ListUserListsRequest"; + }; + + return ListUserListsRequest; + })(); + + v1.ListUserListsResponse = (function() { + + /** + * Properties of a ListUserListsResponse. + * @memberof google.ads.datamanager.v1 + * @interface IListUserListsResponse + * @property {Array.|null} [userLists] ListUserListsResponse userLists + * @property {string|null} [nextPageToken] ListUserListsResponse nextPageToken + */ + + /** + * Constructs a new ListUserListsResponse. + * @memberof google.ads.datamanager.v1 + * @classdesc Represents a ListUserListsResponse. + * @implements IListUserListsResponse + * @constructor + * @param {google.ads.datamanager.v1.IListUserListsResponse=} [properties] Properties to set + */ + function ListUserListsResponse(properties) { + this.userLists = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserListsResponse userLists. + * @member {Array.} userLists + * @memberof google.ads.datamanager.v1.ListUserListsResponse + * @instance + */ + ListUserListsResponse.prototype.userLists = $util.emptyArray; + + /** + * ListUserListsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.ads.datamanager.v1.ListUserListsResponse + * @instance + */ + ListUserListsResponse.prototype.nextPageToken = ""; + + /** + * Creates a new ListUserListsResponse instance using the specified properties. + * @function create + * @memberof google.ads.datamanager.v1.ListUserListsResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListsResponse=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.ListUserListsResponse} ListUserListsResponse instance + */ + ListUserListsResponse.create = function create(properties) { + return new ListUserListsResponse(properties); + }; + + /** + * Encodes the specified ListUserListsResponse message. Does not implicitly {@link google.ads.datamanager.v1.ListUserListsResponse.verify|verify} messages. + * @function encode + * @memberof google.ads.datamanager.v1.ListUserListsResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListsResponse} message ListUserListsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.userLists != null && message.userLists.length) + for (var i = 0; i < message.userLists.length; ++i) + $root.google.ads.datamanager.v1.UserList.encode(message.userLists[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.nextPageToken); + return writer; + }; + + /** + * Encodes the specified ListUserListsResponse message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.ListUserListsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListsResponse + * @static + * @param {google.ads.datamanager.v1.IListUserListsResponse} message ListUserListsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListUserListsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListUserListsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.ads.datamanager.v1.ListUserListsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.ads.datamanager.v1.ListUserListsResponse} ListUserListsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListsResponse.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.ads.datamanager.v1.ListUserListsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.userLists && message.userLists.length)) + message.userLists = []; + message.userLists.push($root.google.ads.datamanager.v1.UserList.decode(reader, reader.uint32())); + break; + } + case 2: { + message.nextPageToken = reader.string(); + break; + } default: - return "reason: enum value expected"; - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 17: - case 18: - case 19: - case 20: - case 21: - case 22: - case 23: - case 24: - case 27: - case 25: - case 26: + reader.skipType(tag & 7); break; } + } + return message; + }; + + /** + * Decodes a ListUserListsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.ads.datamanager.v1.ListUserListsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.ads.datamanager.v1.ListUserListsResponse} ListUserListsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListUserListsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListUserListsResponse message. + * @function verify + * @memberof google.ads.datamanager.v1.ListUserListsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListUserListsResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.userLists != null && message.hasOwnProperty("userLists")) { + if (!Array.isArray(message.userLists)) + return "userLists: array expected"; + for (var i = 0; i < message.userLists.length; ++i) { + var error = $root.google.ads.datamanager.v1.UserList.verify(message.userLists[i]); + if (error) + return "userLists." + error; + } + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; return null; }; /** - * Creates an ErrorCount message from a plain object. Also converts values to their respective internal types. + * Creates a ListUserListsResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsResponse * @static * @param {Object.} object Plain object - * @returns {google.ads.datamanager.v1.ErrorCount} ErrorCount + * @returns {google.ads.datamanager.v1.ListUserListsResponse} ListUserListsResponse */ - ErrorCount.fromObject = function fromObject(object) { - if (object instanceof $root.google.ads.datamanager.v1.ErrorCount) + ListUserListsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.ListUserListsResponse) return object; - var message = new $root.google.ads.datamanager.v1.ErrorCount(); - if (object.recordCount != null) - if ($util.Long) - (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; - else if (typeof object.recordCount === "string") - message.recordCount = parseInt(object.recordCount, 10); - else if (typeof object.recordCount === "number") - message.recordCount = object.recordCount; - else if (typeof object.recordCount === "object") - message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); - switch (object.reason) { - default: - if (typeof object.reason === "number") { - message.reason = object.reason; - break; + var message = new $root.google.ads.datamanager.v1.ListUserListsResponse(); + if (object.userLists) { + if (!Array.isArray(object.userLists)) + throw TypeError(".google.ads.datamanager.v1.ListUserListsResponse.userLists: array expected"); + message.userLists = []; + for (var i = 0; i < object.userLists.length; ++i) { + if (typeof object.userLists[i] !== "object") + throw TypeError(".google.ads.datamanager.v1.ListUserListsResponse.userLists: object expected"); + message.userLists[i] = $root.google.ads.datamanager.v1.UserList.fromObject(object.userLists[i]); } - break; - case "PROCESSING_ERROR_REASON_UNSPECIFIED": - case 0: - message.reason = 0; - break; - case "PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE": - case 1: - message.reason = 1; - break; - case "PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED": - case 2: - message.reason = 2; - break; - case "PROCESSING_ERROR_REASON_EVENT_TOO_OLD": - case 3: - message.reason = 3; - break; - case "PROCESSING_ERROR_REASON_DENIED_CONSENT": - case 4: - message.reason = 4; - break; - case "PROCESSING_ERROR_REASON_NO_CONSENT": - case 5: - message.reason = 5; - break; - case "PROCESSING_ERROR_REASON_UNKNOWN_CONSENT": - case 6: - message.reason = 6; - break; - case "PROCESSING_ERROR_REASON_DUPLICATE_GCLID": - case 7: - message.reason = 7; - break; - case "PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID": - case 8: - message.reason = 8; - break; - case "PROCESSING_ERROR_REASON_INVALID_GBRAID": - case 9: - message.reason = 9; - break; - case "PROCESSING_ERROR_REASON_INVALID_GCLID": - case 10: - message.reason = 10; - break; - case "PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID": - case 11: - message.reason = 11; - break; - case "PROCESSING_ERROR_REASON_INVALID_WBRAID": - case 12: - message.reason = 12; - break; - case "PROCESSING_ERROR_REASON_INTERNAL_ERROR": - case 13: - message.reason = 13; - break; - case "PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED": - case 14: - message.reason = 14; - break; - case "PROCESSING_ERROR_REASON_INVALID_EVENT": - case 15: - message.reason = 15; - break; - case "PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS": - case 16: - message.reason = 16; - break; - case "PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS": - case 17: - message.reason = 17; - break; - case "PROCESSING_ERROR_REASON_INVALID_FORMAT": - case 18: - message.reason = 18; - break; - case "PROCESSING_ERROR_REASON_DECRYPTION_ERROR": - case 19: - message.reason = 19; - break; - case "PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR": - case 20: - message.reason = 20; - break; - case "PROCESSING_ERROR_REASON_INVALID_WIP": - case 21: - message.reason = 21; - break; - case "PROCESSING_ERROR_REASON_INVALID_KEK": - case 22: - message.reason = 22; - break; - case "PROCESSING_ERROR_REASON_WIP_AUTH_FAILED": - case 23: - message.reason = 23; - break; - case "PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED": - case 24: - message.reason = 24; - break; - case "PROCESSING_ERROR_REASON_AWS_AUTH_FAILED": - case 27: - message.reason = 27; - break; - case "PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR": - case 25: - message.reason = 25; - break; - case "PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER": - case 26: - message.reason = 26; - break; } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); return message; }; /** - * Creates a plain object from an ErrorCount message. Also converts values to other types if specified. + * Creates a plain object from a ListUserListsResponse message. Also converts values to other types if specified. * @function toObject - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsResponse * @static - * @param {google.ads.datamanager.v1.ErrorCount} message ErrorCount + * @param {google.ads.datamanager.v1.ListUserListsResponse} message ListUserListsResponse * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ErrorCount.toObject = function toObject(message, options) { + ListUserListsResponse.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.recordCount = options.longs === String ? "0" : 0; - object.reason = options.enums === String ? "PROCESSING_ERROR_REASON_UNSPECIFIED" : 0; - } - if (message.recordCount != null && message.hasOwnProperty("recordCount")) - if (typeof message.recordCount === "number") - object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; - else - object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; - if (message.reason != null && message.hasOwnProperty("reason")) - object.reason = options.enums === String ? $root.google.ads.datamanager.v1.ProcessingErrorReason[message.reason] === undefined ? message.reason : $root.google.ads.datamanager.v1.ProcessingErrorReason[message.reason] : message.reason; + if (options.arrays || options.defaults) + object.userLists = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.userLists && message.userLists.length) { + object.userLists = []; + for (var j = 0; j < message.userLists.length; ++j) + object.userLists[j] = $root.google.ads.datamanager.v1.UserList.toObject(message.userLists[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; return object; }; /** - * Converts this ErrorCount to JSON. + * Converts this ListUserListsResponse to JSON. * @function toJSON - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsResponse * @instance * @returns {Object.} JSON object */ - ErrorCount.prototype.toJSON = function toJSON() { + ListUserListsResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ErrorCount + * Gets the default type url for ListUserListsResponse * @function getTypeUrl - * @memberof google.ads.datamanager.v1.ErrorCount + * @memberof google.ads.datamanager.v1.ListUserListsResponse * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ErrorCount.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListUserListsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.ads.datamanager.v1.ErrorCount"; + return typeUrlPrefix + "/google.ads.datamanager.v1.ListUserListsResponse"; }; - return ErrorCount; + return ListUserListsResponse; })(); - v1.WarningInfo = (function() { + v1.CreateUserListRequest = (function() { /** - * Properties of a WarningInfo. + * Properties of a CreateUserListRequest. * @memberof google.ads.datamanager.v1 - * @interface IWarningInfo - * @property {Array.|null} [warningCounts] WarningInfo warningCounts + * @interface ICreateUserListRequest + * @property {string|null} [parent] CreateUserListRequest parent + * @property {google.ads.datamanager.v1.IUserList|null} [userList] CreateUserListRequest userList + * @property {boolean|null} [validateOnly] CreateUserListRequest validateOnly */ /** - * Constructs a new WarningInfo. + * Constructs a new CreateUserListRequest. * @memberof google.ads.datamanager.v1 - * @classdesc Represents a WarningInfo. - * @implements IWarningInfo + * @classdesc Represents a CreateUserListRequest. + * @implements ICreateUserListRequest * @constructor - * @param {google.ads.datamanager.v1.IWarningInfo=} [properties] Properties to set + * @param {google.ads.datamanager.v1.ICreateUserListRequest=} [properties] Properties to set */ - function WarningInfo(properties) { - this.warningCounts = []; + function CreateUserListRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13182,80 +29492,105 @@ } /** - * WarningInfo warningCounts. - * @member {Array.} warningCounts - * @memberof google.ads.datamanager.v1.WarningInfo + * CreateUserListRequest parent. + * @member {string} parent + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @instance */ - WarningInfo.prototype.warningCounts = $util.emptyArray; + CreateUserListRequest.prototype.parent = ""; /** - * Creates a new WarningInfo instance using the specified properties. + * CreateUserListRequest userList. + * @member {google.ads.datamanager.v1.IUserList|null|undefined} userList + * @memberof google.ads.datamanager.v1.CreateUserListRequest + * @instance + */ + CreateUserListRequest.prototype.userList = null; + + /** + * CreateUserListRequest validateOnly. + * @member {boolean} validateOnly + * @memberof google.ads.datamanager.v1.CreateUserListRequest + * @instance + */ + CreateUserListRequest.prototype.validateOnly = false; + + /** + * Creates a new CreateUserListRequest instance using the specified properties. * @function create - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static - * @param {google.ads.datamanager.v1.IWarningInfo=} [properties] Properties to set - * @returns {google.ads.datamanager.v1.WarningInfo} WarningInfo instance + * @param {google.ads.datamanager.v1.ICreateUserListRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.CreateUserListRequest} CreateUserListRequest instance */ - WarningInfo.create = function create(properties) { - return new WarningInfo(properties); + CreateUserListRequest.create = function create(properties) { + return new CreateUserListRequest(properties); }; /** - * Encodes the specified WarningInfo message. Does not implicitly {@link google.ads.datamanager.v1.WarningInfo.verify|verify} messages. + * Encodes the specified CreateUserListRequest message. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListRequest.verify|verify} messages. * @function encode - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static - * @param {google.ads.datamanager.v1.IWarningInfo} message WarningInfo message or plain object to encode + * @param {google.ads.datamanager.v1.ICreateUserListRequest} message CreateUserListRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WarningInfo.encode = function encode(message, writer) { + CreateUserListRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.warningCounts != null && message.warningCounts.length) - for (var i = 0; i < message.warningCounts.length; ++i) - $root.google.ads.datamanager.v1.WarningCount.encode(message.warningCounts[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.userList != null && Object.hasOwnProperty.call(message, "userList")) + $root.google.ads.datamanager.v1.UserList.encode(message.userList, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.validateOnly != null && Object.hasOwnProperty.call(message, "validateOnly")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.validateOnly); return writer; }; /** - * Encodes the specified WarningInfo message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.WarningInfo.verify|verify} messages. + * Encodes the specified CreateUserListRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.CreateUserListRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static - * @param {google.ads.datamanager.v1.IWarningInfo} message WarningInfo message or plain object to encode + * @param {google.ads.datamanager.v1.ICreateUserListRequest} message CreateUserListRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WarningInfo.encodeDelimited = function encodeDelimited(message, writer) { + CreateUserListRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a WarningInfo message from the specified reader or buffer. + * Decodes a CreateUserListRequest message from the specified reader or buffer. * @function decode - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.ads.datamanager.v1.WarningInfo} WarningInfo + * @returns {google.ads.datamanager.v1.CreateUserListRequest} CreateUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WarningInfo.decode = function decode(reader, length, error) { + CreateUserListRequest.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.ads.datamanager.v1.WarningInfo(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.ads.datamanager.v1.CreateUserListRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { case 1: { - if (!(message.warningCounts && message.warningCounts.length)) - message.warningCounts = []; - message.warningCounts.push($root.google.ads.datamanager.v1.WarningCount.decode(reader, reader.uint32())); + message.parent = reader.string(); + break; + } + case 2: { + message.userList = $root.google.ads.datamanager.v1.UserList.decode(reader, reader.uint32()); + break; + } + case 3: { + message.validateOnly = reader.bool(); break; } default: @@ -13267,140 +29602,146 @@ }; /** - * Decodes a WarningInfo message from the specified reader or buffer, length delimited. + * Decodes a CreateUserListRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.ads.datamanager.v1.WarningInfo} WarningInfo + * @returns {google.ads.datamanager.v1.CreateUserListRequest} CreateUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WarningInfo.decodeDelimited = function decodeDelimited(reader) { + CreateUserListRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a WarningInfo message. + * Verifies a CreateUserListRequest message. * @function verify - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - WarningInfo.verify = function verify(message) { + CreateUserListRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; - if (message.warningCounts != null && message.hasOwnProperty("warningCounts")) { - if (!Array.isArray(message.warningCounts)) - return "warningCounts: array expected"; - for (var i = 0; i < message.warningCounts.length; ++i) { - var error = $root.google.ads.datamanager.v1.WarningCount.verify(message.warningCounts[i]); - if (error) - return "warningCounts." + error; - } + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.userList != null && message.hasOwnProperty("userList")) { + var error = $root.google.ads.datamanager.v1.UserList.verify(message.userList); + if (error) + return "userList." + error; } + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + if (typeof message.validateOnly !== "boolean") + return "validateOnly: boolean expected"; return null; }; /** - * Creates a WarningInfo message from a plain object. Also converts values to their respective internal types. + * Creates a CreateUserListRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static * @param {Object.} object Plain object - * @returns {google.ads.datamanager.v1.WarningInfo} WarningInfo + * @returns {google.ads.datamanager.v1.CreateUserListRequest} CreateUserListRequest */ - WarningInfo.fromObject = function fromObject(object) { - if (object instanceof $root.google.ads.datamanager.v1.WarningInfo) + CreateUserListRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.CreateUserListRequest) return object; - var message = new $root.google.ads.datamanager.v1.WarningInfo(); - if (object.warningCounts) { - if (!Array.isArray(object.warningCounts)) - throw TypeError(".google.ads.datamanager.v1.WarningInfo.warningCounts: array expected"); - message.warningCounts = []; - for (var i = 0; i < object.warningCounts.length; ++i) { - if (typeof object.warningCounts[i] !== "object") - throw TypeError(".google.ads.datamanager.v1.WarningInfo.warningCounts: object expected"); - message.warningCounts[i] = $root.google.ads.datamanager.v1.WarningCount.fromObject(object.warningCounts[i]); - } + var message = new $root.google.ads.datamanager.v1.CreateUserListRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.userList != null) { + if (typeof object.userList !== "object") + throw TypeError(".google.ads.datamanager.v1.CreateUserListRequest.userList: object expected"); + message.userList = $root.google.ads.datamanager.v1.UserList.fromObject(object.userList); } + if (object.validateOnly != null) + message.validateOnly = Boolean(object.validateOnly); return message; }; /** - * Creates a plain object from a WarningInfo message. Also converts values to other types if specified. + * Creates a plain object from a CreateUserListRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static - * @param {google.ads.datamanager.v1.WarningInfo} message WarningInfo + * @param {google.ads.datamanager.v1.CreateUserListRequest} message CreateUserListRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - WarningInfo.toObject = function toObject(message, options) { + CreateUserListRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.warningCounts = []; - if (message.warningCounts && message.warningCounts.length) { - object.warningCounts = []; - for (var j = 0; j < message.warningCounts.length; ++j) - object.warningCounts[j] = $root.google.ads.datamanager.v1.WarningCount.toObject(message.warningCounts[j], options); + if (options.defaults) { + object.parent = ""; + object.userList = null; + object.validateOnly = false; } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.userList != null && message.hasOwnProperty("userList")) + object.userList = $root.google.ads.datamanager.v1.UserList.toObject(message.userList, options); + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + object.validateOnly = message.validateOnly; return object; }; /** - * Converts this WarningInfo to JSON. + * Converts this CreateUserListRequest to JSON. * @function toJSON - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @instance * @returns {Object.} JSON object */ - WarningInfo.prototype.toJSON = function toJSON() { + CreateUserListRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for WarningInfo + * Gets the default type url for CreateUserListRequest * @function getTypeUrl - * @memberof google.ads.datamanager.v1.WarningInfo + * @memberof google.ads.datamanager.v1.CreateUserListRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - WarningInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + CreateUserListRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.ads.datamanager.v1.WarningInfo"; + return typeUrlPrefix + "/google.ads.datamanager.v1.CreateUserListRequest"; }; - return WarningInfo; + return CreateUserListRequest; })(); - v1.WarningCount = (function() { + v1.UpdateUserListRequest = (function() { /** - * Properties of a WarningCount. + * Properties of an UpdateUserListRequest. * @memberof google.ads.datamanager.v1 - * @interface IWarningCount - * @property {number|Long|null} [recordCount] WarningCount recordCount - * @property {google.ads.datamanager.v1.ProcessingWarningReason|null} [reason] WarningCount reason + * @interface IUpdateUserListRequest + * @property {google.ads.datamanager.v1.IUserList|null} [userList] UpdateUserListRequest userList + * @property {google.protobuf.IFieldMask|null} [updateMask] UpdateUserListRequest updateMask + * @property {boolean|null} [validateOnly] UpdateUserListRequest validateOnly */ /** - * Constructs a new WarningCount. + * Constructs a new UpdateUserListRequest. * @memberof google.ads.datamanager.v1 - * @classdesc Represents a WarningCount. - * @implements IWarningCount + * @classdesc Represents an UpdateUserListRequest. + * @implements IUpdateUserListRequest * @constructor - * @param {google.ads.datamanager.v1.IWarningCount=} [properties] Properties to set + * @param {google.ads.datamanager.v1.IUpdateUserListRequest=} [properties] Properties to set */ - function WarningCount(properties) { + function UpdateUserListRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13408,91 +29749,105 @@ } /** - * WarningCount recordCount. - * @member {number|Long} recordCount - * @memberof google.ads.datamanager.v1.WarningCount + * UpdateUserListRequest userList. + * @member {google.ads.datamanager.v1.IUserList|null|undefined} userList + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @instance */ - WarningCount.prototype.recordCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + UpdateUserListRequest.prototype.userList = null; /** - * WarningCount reason. - * @member {google.ads.datamanager.v1.ProcessingWarningReason} reason - * @memberof google.ads.datamanager.v1.WarningCount + * UpdateUserListRequest updateMask. + * @member {google.protobuf.IFieldMask|null|undefined} updateMask + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @instance */ - WarningCount.prototype.reason = 0; + UpdateUserListRequest.prototype.updateMask = null; /** - * Creates a new WarningCount instance using the specified properties. + * UpdateUserListRequest validateOnly. + * @member {boolean} validateOnly + * @memberof google.ads.datamanager.v1.UpdateUserListRequest + * @instance + */ + UpdateUserListRequest.prototype.validateOnly = false; + + /** + * Creates a new UpdateUserListRequest instance using the specified properties. * @function create - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static - * @param {google.ads.datamanager.v1.IWarningCount=} [properties] Properties to set - * @returns {google.ads.datamanager.v1.WarningCount} WarningCount instance + * @param {google.ads.datamanager.v1.IUpdateUserListRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.UpdateUserListRequest} UpdateUserListRequest instance */ - WarningCount.create = function create(properties) { - return new WarningCount(properties); + UpdateUserListRequest.create = function create(properties) { + return new UpdateUserListRequest(properties); }; /** - * Encodes the specified WarningCount message. Does not implicitly {@link google.ads.datamanager.v1.WarningCount.verify|verify} messages. + * Encodes the specified UpdateUserListRequest message. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListRequest.verify|verify} messages. * @function encode - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static - * @param {google.ads.datamanager.v1.IWarningCount} message WarningCount message or plain object to encode + * @param {google.ads.datamanager.v1.IUpdateUserListRequest} message UpdateUserListRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WarningCount.encode = function encode(message, writer) { + UpdateUserListRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.recordCount != null && Object.hasOwnProperty.call(message, "recordCount")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.recordCount); - if (message.reason != null && Object.hasOwnProperty.call(message, "reason")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.reason); + if (message.userList != null && Object.hasOwnProperty.call(message, "userList")) + $root.google.ads.datamanager.v1.UserList.encode(message.userList, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + $root.google.protobuf.FieldMask.encode(message.updateMask, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.validateOnly != null && Object.hasOwnProperty.call(message, "validateOnly")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.validateOnly); return writer; }; /** - * Encodes the specified WarningCount message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.WarningCount.verify|verify} messages. + * Encodes the specified UpdateUserListRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.UpdateUserListRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static - * @param {google.ads.datamanager.v1.IWarningCount} message WarningCount message or plain object to encode + * @param {google.ads.datamanager.v1.IUpdateUserListRequest} message UpdateUserListRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WarningCount.encodeDelimited = function encodeDelimited(message, writer) { + UpdateUserListRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a WarningCount message from the specified reader or buffer. + * Decodes an UpdateUserListRequest message from the specified reader or buffer. * @function decode - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.ads.datamanager.v1.WarningCount} WarningCount + * @returns {google.ads.datamanager.v1.UpdateUserListRequest} UpdateUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WarningCount.decode = function decode(reader, length, error) { + UpdateUserListRequest.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.ads.datamanager.v1.WarningCount(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.ads.datamanager.v1.UpdateUserListRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { case 1: { - message.recordCount = reader.int64(); + message.userList = $root.google.ads.datamanager.v1.UserList.decode(reader, reader.uint32()); break; } case 2: { - message.reason = reader.int32(); + message.updateMask = $root.google.protobuf.FieldMask.decode(reader, reader.uint32()); + break; + } + case 3: { + message.validateOnly = reader.bool(); break; } default: @@ -13504,300 +29859,150 @@ }; /** - * Decodes a WarningCount message from the specified reader or buffer, length delimited. + * Decodes an UpdateUserListRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.ads.datamanager.v1.WarningCount} WarningCount + * @returns {google.ads.datamanager.v1.UpdateUserListRequest} UpdateUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WarningCount.decodeDelimited = function decodeDelimited(reader) { + UpdateUserListRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a WarningCount message. + * Verifies an UpdateUserListRequest message. * @function verify - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - WarningCount.verify = function verify(message) { + UpdateUserListRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; - if (message.recordCount != null && message.hasOwnProperty("recordCount")) - if (!$util.isInteger(message.recordCount) && !(message.recordCount && $util.isInteger(message.recordCount.low) && $util.isInteger(message.recordCount.high))) - return "recordCount: integer|Long expected"; - if (message.reason != null && message.hasOwnProperty("reason")) - switch (message.reason) { - default: - return "reason: enum value expected"; - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - break; - } + if (message.userList != null && message.hasOwnProperty("userList")) { + var error = $root.google.ads.datamanager.v1.UserList.verify(message.userList); + if (error) + return "userList." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + var error = $root.google.protobuf.FieldMask.verify(message.updateMask); + if (error) + return "updateMask." + error; + } + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + if (typeof message.validateOnly !== "boolean") + return "validateOnly: boolean expected"; return null; }; /** - * Creates a WarningCount message from a plain object. Also converts values to their respective internal types. + * Creates an UpdateUserListRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static * @param {Object.} object Plain object - * @returns {google.ads.datamanager.v1.WarningCount} WarningCount + * @returns {google.ads.datamanager.v1.UpdateUserListRequest} UpdateUserListRequest */ - WarningCount.fromObject = function fromObject(object) { - if (object instanceof $root.google.ads.datamanager.v1.WarningCount) + UpdateUserListRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.UpdateUserListRequest) return object; - var message = new $root.google.ads.datamanager.v1.WarningCount(); - if (object.recordCount != null) - if ($util.Long) - (message.recordCount = $util.Long.fromValue(object.recordCount)).unsigned = false; - else if (typeof object.recordCount === "string") - message.recordCount = parseInt(object.recordCount, 10); - else if (typeof object.recordCount === "number") - message.recordCount = object.recordCount; - else if (typeof object.recordCount === "object") - message.recordCount = new $util.LongBits(object.recordCount.low >>> 0, object.recordCount.high >>> 0).toNumber(); - switch (object.reason) { - default: - if (typeof object.reason === "number") { - message.reason = object.reason; - break; - } - break; - case "PROCESSING_WARNING_REASON_UNSPECIFIED": - case 0: - message.reason = 0; - break; - case "PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED": - case 1: - message.reason = 1; - break; - case "PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR": - case 2: - message.reason = 2; - break; - case "PROCESSING_WARNING_REASON_DECRYPTION_ERROR": - case 3: - message.reason = 3; - break; - case "PROCESSING_WARNING_REASON_WIP_AUTH_FAILED": - case 4: - message.reason = 4; - break; - case "PROCESSING_WARNING_REASON_INVALID_WIP": - case 5: - message.reason = 5; - break; - case "PROCESSING_WARNING_REASON_INVALID_KEK": - case 6: - message.reason = 6; - break; - case "PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR": - case 7: - message.reason = 7; - break; - case "PROCESSING_WARNING_REASON_INTERNAL_ERROR": - case 8: - message.reason = 8; - break; - case "PROCESSING_WARNING_REASON_AWS_AUTH_FAILED": - case 9: - message.reason = 9; - break; + var message = new $root.google.ads.datamanager.v1.UpdateUserListRequest(); + if (object.userList != null) { + if (typeof object.userList !== "object") + throw TypeError(".google.ads.datamanager.v1.UpdateUserListRequest.userList: object expected"); + message.userList = $root.google.ads.datamanager.v1.UserList.fromObject(object.userList); } + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.ads.datamanager.v1.UpdateUserListRequest.updateMask: object expected"); + message.updateMask = $root.google.protobuf.FieldMask.fromObject(object.updateMask); + } + if (object.validateOnly != null) + message.validateOnly = Boolean(object.validateOnly); return message; }; /** - * Creates a plain object from a WarningCount message. Also converts values to other types if specified. + * Creates a plain object from an UpdateUserListRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static - * @param {google.ads.datamanager.v1.WarningCount} message WarningCount + * @param {google.ads.datamanager.v1.UpdateUserListRequest} message UpdateUserListRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - WarningCount.toObject = function toObject(message, options) { + UpdateUserListRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.recordCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.recordCount = options.longs === String ? "0" : 0; - object.reason = options.enums === String ? "PROCESSING_WARNING_REASON_UNSPECIFIED" : 0; + object.userList = null; + object.updateMask = null; + object.validateOnly = false; } - if (message.recordCount != null && message.hasOwnProperty("recordCount")) - if (typeof message.recordCount === "number") - object.recordCount = options.longs === String ? String(message.recordCount) : message.recordCount; - else - object.recordCount = options.longs === String ? $util.Long.prototype.toString.call(message.recordCount) : options.longs === Number ? new $util.LongBits(message.recordCount.low >>> 0, message.recordCount.high >>> 0).toNumber() : message.recordCount; - if (message.reason != null && message.hasOwnProperty("reason")) - object.reason = options.enums === String ? $root.google.ads.datamanager.v1.ProcessingWarningReason[message.reason] === undefined ? message.reason : $root.google.ads.datamanager.v1.ProcessingWarningReason[message.reason] : message.reason; + if (message.userList != null && message.hasOwnProperty("userList")) + object.userList = $root.google.ads.datamanager.v1.UserList.toObject(message.userList, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.protobuf.FieldMask.toObject(message.updateMask, options); + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + object.validateOnly = message.validateOnly; return object; }; /** - * Converts this WarningCount to JSON. + * Converts this UpdateUserListRequest to JSON. * @function toJSON - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @instance * @returns {Object.} JSON object */ - WarningCount.prototype.toJSON = function toJSON() { + UpdateUserListRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for WarningCount + * Gets the default type url for UpdateUserListRequest * @function getTypeUrl - * @memberof google.ads.datamanager.v1.WarningCount + * @memberof google.ads.datamanager.v1.UpdateUserListRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - WarningCount.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + UpdateUserListRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.ads.datamanager.v1.WarningCount"; + return typeUrlPrefix + "/google.ads.datamanager.v1.UpdateUserListRequest"; }; - return WarningCount; - })(); - - /** - * ProcessingErrorReason enum. - * @name google.ads.datamanager.v1.ProcessingErrorReason - * @enum {number} - * @property {number} PROCESSING_ERROR_REASON_UNSPECIFIED=0 PROCESSING_ERROR_REASON_UNSPECIFIED value - * @property {number} PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE=1 PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE value - * @property {number} PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED=2 PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED value - * @property {number} PROCESSING_ERROR_REASON_EVENT_TOO_OLD=3 PROCESSING_ERROR_REASON_EVENT_TOO_OLD value - * @property {number} PROCESSING_ERROR_REASON_DENIED_CONSENT=4 PROCESSING_ERROR_REASON_DENIED_CONSENT value - * @property {number} PROCESSING_ERROR_REASON_NO_CONSENT=5 PROCESSING_ERROR_REASON_NO_CONSENT value - * @property {number} PROCESSING_ERROR_REASON_UNKNOWN_CONSENT=6 PROCESSING_ERROR_REASON_UNKNOWN_CONSENT value - * @property {number} PROCESSING_ERROR_REASON_DUPLICATE_GCLID=7 PROCESSING_ERROR_REASON_DUPLICATE_GCLID value - * @property {number} PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID=8 PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID value - * @property {number} PROCESSING_ERROR_REASON_INVALID_GBRAID=9 PROCESSING_ERROR_REASON_INVALID_GBRAID value - * @property {number} PROCESSING_ERROR_REASON_INVALID_GCLID=10 PROCESSING_ERROR_REASON_INVALID_GCLID value - * @property {number} PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID=11 PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID value - * @property {number} PROCESSING_ERROR_REASON_INVALID_WBRAID=12 PROCESSING_ERROR_REASON_INVALID_WBRAID value - * @property {number} PROCESSING_ERROR_REASON_INTERNAL_ERROR=13 PROCESSING_ERROR_REASON_INTERNAL_ERROR value - * @property {number} PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED=14 PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED value - * @property {number} PROCESSING_ERROR_REASON_INVALID_EVENT=15 PROCESSING_ERROR_REASON_INVALID_EVENT value - * @property {number} PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS=16 PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS value - * @property {number} PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS=17 PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS value - * @property {number} PROCESSING_ERROR_REASON_INVALID_FORMAT=18 PROCESSING_ERROR_REASON_INVALID_FORMAT value - * @property {number} PROCESSING_ERROR_REASON_DECRYPTION_ERROR=19 PROCESSING_ERROR_REASON_DECRYPTION_ERROR value - * @property {number} PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR=20 PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR value - * @property {number} PROCESSING_ERROR_REASON_INVALID_WIP=21 PROCESSING_ERROR_REASON_INVALID_WIP value - * @property {number} PROCESSING_ERROR_REASON_INVALID_KEK=22 PROCESSING_ERROR_REASON_INVALID_KEK value - * @property {number} PROCESSING_ERROR_REASON_WIP_AUTH_FAILED=23 PROCESSING_ERROR_REASON_WIP_AUTH_FAILED value - * @property {number} PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED=24 PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED value - * @property {number} PROCESSING_ERROR_REASON_AWS_AUTH_FAILED=27 PROCESSING_ERROR_REASON_AWS_AUTH_FAILED value - * @property {number} PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR=25 PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR value - * @property {number} PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER=26 PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER value - */ - v1.ProcessingErrorReason = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "PROCESSING_ERROR_REASON_UNSPECIFIED"] = 0; - values[valuesById[1] = "PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE"] = 1; - values[valuesById[2] = "PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED"] = 2; - values[valuesById[3] = "PROCESSING_ERROR_REASON_EVENT_TOO_OLD"] = 3; - values[valuesById[4] = "PROCESSING_ERROR_REASON_DENIED_CONSENT"] = 4; - values[valuesById[5] = "PROCESSING_ERROR_REASON_NO_CONSENT"] = 5; - values[valuesById[6] = "PROCESSING_ERROR_REASON_UNKNOWN_CONSENT"] = 6; - values[valuesById[7] = "PROCESSING_ERROR_REASON_DUPLICATE_GCLID"] = 7; - values[valuesById[8] = "PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID"] = 8; - values[valuesById[9] = "PROCESSING_ERROR_REASON_INVALID_GBRAID"] = 9; - values[valuesById[10] = "PROCESSING_ERROR_REASON_INVALID_GCLID"] = 10; - values[valuesById[11] = "PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID"] = 11; - values[valuesById[12] = "PROCESSING_ERROR_REASON_INVALID_WBRAID"] = 12; - values[valuesById[13] = "PROCESSING_ERROR_REASON_INTERNAL_ERROR"] = 13; - values[valuesById[14] = "PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED"] = 14; - values[valuesById[15] = "PROCESSING_ERROR_REASON_INVALID_EVENT"] = 15; - values[valuesById[16] = "PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS"] = 16; - values[valuesById[17] = "PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS"] = 17; - values[valuesById[18] = "PROCESSING_ERROR_REASON_INVALID_FORMAT"] = 18; - values[valuesById[19] = "PROCESSING_ERROR_REASON_DECRYPTION_ERROR"] = 19; - values[valuesById[20] = "PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR"] = 20; - values[valuesById[21] = "PROCESSING_ERROR_REASON_INVALID_WIP"] = 21; - values[valuesById[22] = "PROCESSING_ERROR_REASON_INVALID_KEK"] = 22; - values[valuesById[23] = "PROCESSING_ERROR_REASON_WIP_AUTH_FAILED"] = 23; - values[valuesById[24] = "PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED"] = 24; - values[valuesById[27] = "PROCESSING_ERROR_REASON_AWS_AUTH_FAILED"] = 27; - values[valuesById[25] = "PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR"] = 25; - values[valuesById[26] = "PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER"] = 26; - return values; - })(); - - /** - * ProcessingWarningReason enum. - * @name google.ads.datamanager.v1.ProcessingWarningReason - * @enum {number} - * @property {number} PROCESSING_WARNING_REASON_UNSPECIFIED=0 PROCESSING_WARNING_REASON_UNSPECIFIED value - * @property {number} PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED=1 PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED value - * @property {number} PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR=2 PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR value - * @property {number} PROCESSING_WARNING_REASON_DECRYPTION_ERROR=3 PROCESSING_WARNING_REASON_DECRYPTION_ERROR value - * @property {number} PROCESSING_WARNING_REASON_WIP_AUTH_FAILED=4 PROCESSING_WARNING_REASON_WIP_AUTH_FAILED value - * @property {number} PROCESSING_WARNING_REASON_INVALID_WIP=5 PROCESSING_WARNING_REASON_INVALID_WIP value - * @property {number} PROCESSING_WARNING_REASON_INVALID_KEK=6 PROCESSING_WARNING_REASON_INVALID_KEK value - * @property {number} PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR=7 PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR value - * @property {number} PROCESSING_WARNING_REASON_INTERNAL_ERROR=8 PROCESSING_WARNING_REASON_INTERNAL_ERROR value - * @property {number} PROCESSING_WARNING_REASON_AWS_AUTH_FAILED=9 PROCESSING_WARNING_REASON_AWS_AUTH_FAILED value - */ - v1.ProcessingWarningReason = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "PROCESSING_WARNING_REASON_UNSPECIFIED"] = 0; - values[valuesById[1] = "PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED"] = 1; - values[valuesById[2] = "PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR"] = 2; - values[valuesById[3] = "PROCESSING_WARNING_REASON_DECRYPTION_ERROR"] = 3; - values[valuesById[4] = "PROCESSING_WARNING_REASON_WIP_AUTH_FAILED"] = 4; - values[valuesById[5] = "PROCESSING_WARNING_REASON_INVALID_WIP"] = 5; - values[valuesById[6] = "PROCESSING_WARNING_REASON_INVALID_KEK"] = 6; - values[valuesById[7] = "PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR"] = 7; - values[valuesById[8] = "PROCESSING_WARNING_REASON_INTERNAL_ERROR"] = 8; - values[valuesById[9] = "PROCESSING_WARNING_REASON_AWS_AUTH_FAILED"] = 9; - return values; + return UpdateUserListRequest; })(); - v1.TermsOfService = (function() { + v1.DeleteUserListRequest = (function() { /** - * Properties of a TermsOfService. + * Properties of a DeleteUserListRequest. * @memberof google.ads.datamanager.v1 - * @interface ITermsOfService - * @property {google.ads.datamanager.v1.TermsOfServiceStatus|null} [customerMatchTermsOfServiceStatus] TermsOfService customerMatchTermsOfServiceStatus + * @interface IDeleteUserListRequest + * @property {string|null} [name] DeleteUserListRequest name + * @property {boolean|null} [validateOnly] DeleteUserListRequest validateOnly */ /** - * Constructs a new TermsOfService. + * Constructs a new DeleteUserListRequest. * @memberof google.ads.datamanager.v1 - * @classdesc Represents a TermsOfService. - * @implements ITermsOfService + * @classdesc Represents a DeleteUserListRequest. + * @implements IDeleteUserListRequest * @constructor - * @param {google.ads.datamanager.v1.ITermsOfService=} [properties] Properties to set + * @param {google.ads.datamanager.v1.IDeleteUserListRequest=} [properties] Properties to set */ - function TermsOfService(properties) { + function DeleteUserListRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13805,77 +30010,91 @@ } /** - * TermsOfService customerMatchTermsOfServiceStatus. - * @member {google.ads.datamanager.v1.TermsOfServiceStatus} customerMatchTermsOfServiceStatus - * @memberof google.ads.datamanager.v1.TermsOfService + * DeleteUserListRequest name. + * @member {string} name + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @instance */ - TermsOfService.prototype.customerMatchTermsOfServiceStatus = 0; + DeleteUserListRequest.prototype.name = ""; /** - * Creates a new TermsOfService instance using the specified properties. + * DeleteUserListRequest validateOnly. + * @member {boolean} validateOnly + * @memberof google.ads.datamanager.v1.DeleteUserListRequest + * @instance + */ + DeleteUserListRequest.prototype.validateOnly = false; + + /** + * Creates a new DeleteUserListRequest instance using the specified properties. * @function create - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static - * @param {google.ads.datamanager.v1.ITermsOfService=} [properties] Properties to set - * @returns {google.ads.datamanager.v1.TermsOfService} TermsOfService instance + * @param {google.ads.datamanager.v1.IDeleteUserListRequest=} [properties] Properties to set + * @returns {google.ads.datamanager.v1.DeleteUserListRequest} DeleteUserListRequest instance */ - TermsOfService.create = function create(properties) { - return new TermsOfService(properties); + DeleteUserListRequest.create = function create(properties) { + return new DeleteUserListRequest(properties); }; /** - * Encodes the specified TermsOfService message. Does not implicitly {@link google.ads.datamanager.v1.TermsOfService.verify|verify} messages. + * Encodes the specified DeleteUserListRequest message. Does not implicitly {@link google.ads.datamanager.v1.DeleteUserListRequest.verify|verify} messages. * @function encode - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static - * @param {google.ads.datamanager.v1.ITermsOfService} message TermsOfService message or plain object to encode + * @param {google.ads.datamanager.v1.IDeleteUserListRequest} message DeleteUserListRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TermsOfService.encode = function encode(message, writer) { + DeleteUserListRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.customerMatchTermsOfServiceStatus != null && Object.hasOwnProperty.call(message, "customerMatchTermsOfServiceStatus")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.customerMatchTermsOfServiceStatus); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.validateOnly != null && Object.hasOwnProperty.call(message, "validateOnly")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.validateOnly); return writer; }; /** - * Encodes the specified TermsOfService message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.TermsOfService.verify|verify} messages. + * Encodes the specified DeleteUserListRequest message, length delimited. Does not implicitly {@link google.ads.datamanager.v1.DeleteUserListRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static - * @param {google.ads.datamanager.v1.ITermsOfService} message TermsOfService message or plain object to encode + * @param {google.ads.datamanager.v1.IDeleteUserListRequest} message DeleteUserListRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TermsOfService.encodeDelimited = function encodeDelimited(message, writer) { + DeleteUserListRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TermsOfService message from the specified reader or buffer. + * Decodes a DeleteUserListRequest message from the specified reader or buffer. * @function decode - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.ads.datamanager.v1.TermsOfService} TermsOfService + * @returns {google.ads.datamanager.v1.DeleteUserListRequest} DeleteUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TermsOfService.decode = function decode(reader, length, error) { + DeleteUserListRequest.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.ads.datamanager.v1.TermsOfService(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.ads.datamanager.v1.DeleteUserListRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { case 1: { - message.customerMatchTermsOfServiceStatus = reader.int32(); + message.name = reader.string(); + break; + } + case 2: { + message.validateOnly = reader.bool(); break; } default: @@ -13887,142 +30106,111 @@ }; /** - * Decodes a TermsOfService message from the specified reader or buffer, length delimited. + * Decodes a DeleteUserListRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.ads.datamanager.v1.TermsOfService} TermsOfService + * @returns {google.ads.datamanager.v1.DeleteUserListRequest} DeleteUserListRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TermsOfService.decodeDelimited = function decodeDelimited(reader) { + DeleteUserListRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TermsOfService message. + * Verifies a DeleteUserListRequest message. * @function verify - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TermsOfService.verify = function verify(message) { + DeleteUserListRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; - if (message.customerMatchTermsOfServiceStatus != null && message.hasOwnProperty("customerMatchTermsOfServiceStatus")) - switch (message.customerMatchTermsOfServiceStatus) { - default: - return "customerMatchTermsOfServiceStatus: enum value expected"; - case 0: - case 1: - case 2: - break; - } + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + if (typeof message.validateOnly !== "boolean") + return "validateOnly: boolean expected"; return null; }; /** - * Creates a TermsOfService message from a plain object. Also converts values to their respective internal types. + * Creates a DeleteUserListRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static * @param {Object.} object Plain object - * @returns {google.ads.datamanager.v1.TermsOfService} TermsOfService + * @returns {google.ads.datamanager.v1.DeleteUserListRequest} DeleteUserListRequest */ - TermsOfService.fromObject = function fromObject(object) { - if (object instanceof $root.google.ads.datamanager.v1.TermsOfService) + DeleteUserListRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.ads.datamanager.v1.DeleteUserListRequest) return object; - var message = new $root.google.ads.datamanager.v1.TermsOfService(); - switch (object.customerMatchTermsOfServiceStatus) { - default: - if (typeof object.customerMatchTermsOfServiceStatus === "number") { - message.customerMatchTermsOfServiceStatus = object.customerMatchTermsOfServiceStatus; - break; - } - break; - case "TERMS_OF_SERVICE_STATUS_UNSPECIFIED": - case 0: - message.customerMatchTermsOfServiceStatus = 0; - break; - case "ACCEPTED": - case 1: - message.customerMatchTermsOfServiceStatus = 1; - break; - case "REJECTED": - case 2: - message.customerMatchTermsOfServiceStatus = 2; - break; - } + var message = new $root.google.ads.datamanager.v1.DeleteUserListRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.validateOnly != null) + message.validateOnly = Boolean(object.validateOnly); return message; }; /** - * Creates a plain object from a TermsOfService message. Also converts values to other types if specified. + * Creates a plain object from a DeleteUserListRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static - * @param {google.ads.datamanager.v1.TermsOfService} message TermsOfService + * @param {google.ads.datamanager.v1.DeleteUserListRequest} message DeleteUserListRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TermsOfService.toObject = function toObject(message, options) { + DeleteUserListRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) - object.customerMatchTermsOfServiceStatus = options.enums === String ? "TERMS_OF_SERVICE_STATUS_UNSPECIFIED" : 0; - if (message.customerMatchTermsOfServiceStatus != null && message.hasOwnProperty("customerMatchTermsOfServiceStatus")) - object.customerMatchTermsOfServiceStatus = options.enums === String ? $root.google.ads.datamanager.v1.TermsOfServiceStatus[message.customerMatchTermsOfServiceStatus] === undefined ? message.customerMatchTermsOfServiceStatus : $root.google.ads.datamanager.v1.TermsOfServiceStatus[message.customerMatchTermsOfServiceStatus] : message.customerMatchTermsOfServiceStatus; + if (options.defaults) { + object.name = ""; + object.validateOnly = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.validateOnly != null && message.hasOwnProperty("validateOnly")) + object.validateOnly = message.validateOnly; return object; }; /** - * Converts this TermsOfService to JSON. + * Converts this DeleteUserListRequest to JSON. * @function toJSON - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @instance * @returns {Object.} JSON object */ - TermsOfService.prototype.toJSON = function toJSON() { + DeleteUserListRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TermsOfService + * Gets the default type url for DeleteUserListRequest * @function getTypeUrl - * @memberof google.ads.datamanager.v1.TermsOfService + * @memberof google.ads.datamanager.v1.DeleteUserListRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TermsOfService.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + DeleteUserListRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.ads.datamanager.v1.TermsOfService"; + return typeUrlPrefix + "/google.ads.datamanager.v1.DeleteUserListRequest"; }; - return TermsOfService; - })(); - - /** - * TermsOfServiceStatus enum. - * @name google.ads.datamanager.v1.TermsOfServiceStatus - * @enum {number} - * @property {number} TERMS_OF_SERVICE_STATUS_UNSPECIFIED=0 TERMS_OF_SERVICE_STATUS_UNSPECIFIED value - * @property {number} ACCEPTED=1 ACCEPTED value - * @property {number} REJECTED=2 REJECTED value - */ - v1.TermsOfServiceStatus = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "TERMS_OF_SERVICE_STATUS_UNSPECIFIED"] = 0; - values[valuesById[1] = "ACCEPTED"] = 1; - values[valuesById[2] = "REJECTED"] = 2; - return values; + return DeleteUserListRequest; })(); return v1; @@ -14071,6 +30259,694 @@ return values; })(); + api.ResourceDescriptor = (function() { + + /** + * Properties of a ResourceDescriptor. + * @memberof google.api + * @interface IResourceDescriptor + * @property {string|null} [type] ResourceDescriptor type + * @property {Array.|null} [pattern] ResourceDescriptor pattern + * @property {string|null} [nameField] ResourceDescriptor nameField + * @property {google.api.ResourceDescriptor.History|null} [history] ResourceDescriptor history + * @property {string|null} [plural] ResourceDescriptor plural + * @property {string|null} [singular] ResourceDescriptor singular + * @property {Array.|null} [style] ResourceDescriptor style + */ + + /** + * Constructs a new ResourceDescriptor. + * @memberof google.api + * @classdesc Represents a ResourceDescriptor. + * @implements IResourceDescriptor + * @constructor + * @param {google.api.IResourceDescriptor=} [properties] Properties to set + */ + function ResourceDescriptor(properties) { + this.pattern = []; + this.style = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceDescriptor type. + * @member {string} type + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.type = ""; + + /** + * ResourceDescriptor pattern. + * @member {Array.} pattern + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.pattern = $util.emptyArray; + + /** + * ResourceDescriptor nameField. + * @member {string} nameField + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.nameField = ""; + + /** + * ResourceDescriptor history. + * @member {google.api.ResourceDescriptor.History} history + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.history = 0; + + /** + * ResourceDescriptor plural. + * @member {string} plural + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.plural = ""; + + /** + * ResourceDescriptor singular. + * @member {string} singular + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.singular = ""; + + /** + * ResourceDescriptor style. + * @member {Array.} style + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.style = $util.emptyArray; + + /** + * Creates a new ResourceDescriptor instance using the specified properties. + * @function create + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.IResourceDescriptor=} [properties] Properties to set + * @returns {google.api.ResourceDescriptor} ResourceDescriptor instance + */ + ResourceDescriptor.create = function create(properties) { + return new ResourceDescriptor(properties); + }; + + /** + * Encodes the specified ResourceDescriptor message. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @function encode + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.IResourceDescriptor} message ResourceDescriptor message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceDescriptor.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.type); + if (message.pattern != null && message.pattern.length) + for (var i = 0; i < message.pattern.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.pattern[i]); + if (message.nameField != null && Object.hasOwnProperty.call(message, "nameField")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.nameField); + if (message.history != null && Object.hasOwnProperty.call(message, "history")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.history); + if (message.plural != null && Object.hasOwnProperty.call(message, "plural")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.plural); + if (message.singular != null && Object.hasOwnProperty.call(message, "singular")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.singular); + if (message.style != null && message.style.length) { + writer.uint32(/* id 10, wireType 2 =*/82).fork(); + for (var i = 0; i < message.style.length; ++i) + writer.int32(message.style[i]); + writer.ldelim(); + } + return writer; + }; + + /** + * Encodes the specified ResourceDescriptor message, length delimited. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.IResourceDescriptor} message ResourceDescriptor message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceDescriptor.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer. + * @function decode + * @memberof google.api.ResourceDescriptor + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + * @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, 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(); + break; + } + case 2: { + if (!(message.pattern && message.pattern.length)) + message.pattern = []; + message.pattern.push(reader.string()); + break; + } + case 3: { + message.nameField = reader.string(); + break; + } + case 4: { + message.history = reader.int32(); + break; + } + case 5: { + message.plural = reader.string(); + break; + } + case 6: { + message.singular = reader.string(); + break; + } + case 10: { + if (!(message.style && message.style.length)) + message.style = []; + if ((tag & 7) === 2) { + var end2 = reader.uint32() + reader.pos; + while (reader.pos < end2) + message.style.push(reader.int32()); + } else + message.style.push(reader.int32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ResourceDescriptor message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.ResourceDescriptor + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceDescriptor.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ResourceDescriptor message. + * @function verify + * @memberof google.api.ResourceDescriptor + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResourceDescriptor.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.pattern != null && message.hasOwnProperty("pattern")) { + if (!Array.isArray(message.pattern)) + return "pattern: array expected"; + for (var i = 0; i < message.pattern.length; ++i) + if (!$util.isString(message.pattern[i])) + return "pattern: string[] expected"; + } + if (message.nameField != null && message.hasOwnProperty("nameField")) + if (!$util.isString(message.nameField)) + return "nameField: string expected"; + if (message.history != null && message.hasOwnProperty("history")) + switch (message.history) { + default: + return "history: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.plural != null && message.hasOwnProperty("plural")) + if (!$util.isString(message.plural)) + return "plural: string expected"; + if (message.singular != null && message.hasOwnProperty("singular")) + if (!$util.isString(message.singular)) + return "singular: string expected"; + if (message.style != null && message.hasOwnProperty("style")) { + if (!Array.isArray(message.style)) + return "style: array expected"; + for (var i = 0; i < message.style.length; ++i) + switch (message.style[i]) { + default: + return "style: enum value[] expected"; + case 0: + case 1: + break; + } + } + return null; + }; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + */ + ResourceDescriptor.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceDescriptor) + return object; + var message = new $root.google.api.ResourceDescriptor(); + if (object.type != null) + message.type = String(object.type); + if (object.pattern) { + if (!Array.isArray(object.pattern)) + throw TypeError(".google.api.ResourceDescriptor.pattern: array expected"); + message.pattern = []; + for (var i = 0; i < object.pattern.length; ++i) + message.pattern[i] = String(object.pattern[i]); + } + if (object.nameField != null) + message.nameField = String(object.nameField); + switch (object.history) { + default: + if (typeof object.history === "number") { + message.history = object.history; + break; + } + break; + case "HISTORY_UNSPECIFIED": + case 0: + message.history = 0; + break; + case "ORIGINALLY_SINGLE_PATTERN": + case 1: + message.history = 1; + break; + case "FUTURE_MULTI_PATTERN": + case 2: + message.history = 2; + break; + } + if (object.plural != null) + message.plural = String(object.plural); + if (object.singular != null) + message.singular = String(object.singular); + if (object.style) { + if (!Array.isArray(object.style)) + throw TypeError(".google.api.ResourceDescriptor.style: array expected"); + message.style = []; + for (var i = 0; i < object.style.length; ++i) + switch (object.style[i]) { + default: + if (typeof object.style[i] === "number") { + message.style[i] = object.style[i]; + break; + } + case "STYLE_UNSPECIFIED": + case 0: + message.style[i] = 0; + break; + case "DECLARATIVE_FRIENDLY": + case 1: + message.style[i] = 1; + break; + } + } + return message; + }; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.ResourceDescriptor} message ResourceDescriptor + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceDescriptor.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.pattern = []; + object.style = []; + } + if (options.defaults) { + object.type = ""; + object.nameField = ""; + object.history = options.enums === String ? "HISTORY_UNSPECIFIED" : 0; + object.plural = ""; + object.singular = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.pattern && message.pattern.length) { + object.pattern = []; + for (var j = 0; j < message.pattern.length; ++j) + object.pattern[j] = message.pattern[j]; + } + if (message.nameField != null && message.hasOwnProperty("nameField")) + object.nameField = message.nameField; + if (message.history != null && message.hasOwnProperty("history")) + object.history = options.enums === String ? $root.google.api.ResourceDescriptor.History[message.history] === undefined ? message.history : $root.google.api.ResourceDescriptor.History[message.history] : message.history; + if (message.plural != null && message.hasOwnProperty("plural")) + object.plural = message.plural; + if (message.singular != null && message.hasOwnProperty("singular")) + object.singular = message.singular; + if (message.style && message.style.length) { + object.style = []; + for (var j = 0; j < message.style.length; ++j) + object.style[j] = options.enums === String ? $root.google.api.ResourceDescriptor.Style[message.style[j]] === undefined ? message.style[j] : $root.google.api.ResourceDescriptor.Style[message.style[j]] : message.style[j]; + } + return object; + }; + + /** + * Converts this ResourceDescriptor to JSON. + * @function toJSON + * @memberof google.api.ResourceDescriptor + * @instance + * @returns {Object.} JSON object + */ + ResourceDescriptor.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceDescriptor + * @function getTypeUrl + * @memberof google.api.ResourceDescriptor + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceDescriptor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceDescriptor"; + }; + + /** + * History enum. + * @name google.api.ResourceDescriptor.History + * @enum {number} + * @property {number} HISTORY_UNSPECIFIED=0 HISTORY_UNSPECIFIED value + * @property {number} ORIGINALLY_SINGLE_PATTERN=1 ORIGINALLY_SINGLE_PATTERN value + * @property {number} FUTURE_MULTI_PATTERN=2 FUTURE_MULTI_PATTERN value + */ + ResourceDescriptor.History = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "HISTORY_UNSPECIFIED"] = 0; + values[valuesById[1] = "ORIGINALLY_SINGLE_PATTERN"] = 1; + values[valuesById[2] = "FUTURE_MULTI_PATTERN"] = 2; + return values; + })(); + + /** + * Style enum. + * @name google.api.ResourceDescriptor.Style + * @enum {number} + * @property {number} STYLE_UNSPECIFIED=0 STYLE_UNSPECIFIED value + * @property {number} DECLARATIVE_FRIENDLY=1 DECLARATIVE_FRIENDLY value + */ + ResourceDescriptor.Style = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STYLE_UNSPECIFIED"] = 0; + values[valuesById[1] = "DECLARATIVE_FRIENDLY"] = 1; + return values; + })(); + + return ResourceDescriptor; + })(); + + api.ResourceReference = (function() { + + /** + * Properties of a ResourceReference. + * @memberof google.api + * @interface IResourceReference + * @property {string|null} [type] ResourceReference type + * @property {string|null} [childType] ResourceReference childType + */ + + /** + * Constructs a new ResourceReference. + * @memberof google.api + * @classdesc Represents a ResourceReference. + * @implements IResourceReference + * @constructor + * @param {google.api.IResourceReference=} [properties] Properties to set + */ + function ResourceReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceReference type. + * @member {string} type + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.type = ""; + + /** + * ResourceReference childType. + * @member {string} childType + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.childType = ""; + + /** + * Creates a new ResourceReference instance using the specified properties. + * @function create + * @memberof google.api.ResourceReference + * @static + * @param {google.api.IResourceReference=} [properties] Properties to set + * @returns {google.api.ResourceReference} ResourceReference instance + */ + ResourceReference.create = function create(properties) { + return new ResourceReference(properties); + }; + + /** + * Encodes the specified ResourceReference message. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @function encode + * @memberof google.api.ResourceReference + * @static + * @param {google.api.IResourceReference} message ResourceReference message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceReference.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.type); + if (message.childType != null && Object.hasOwnProperty.call(message, "childType")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.childType); + return writer; + }; + + /** + * Encodes the specified ResourceReference message, length delimited. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.ResourceReference + * @static + * @param {google.api.IResourceReference} message ResourceReference message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ResourceReference.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ResourceReference message from the specified reader or buffer. + * @function decode + * @memberof google.api.ResourceReference + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.ResourceReference} ResourceReference + * @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, 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(); + break; + } + case 2: { + message.childType = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ResourceReference message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.ResourceReference + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.ResourceReference} ResourceReference + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ResourceReference.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ResourceReference message. + * @function verify + * @memberof google.api.ResourceReference + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ResourceReference.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.type != null && message.hasOwnProperty("type")) + if (!$util.isString(message.type)) + return "type: string expected"; + if (message.childType != null && message.hasOwnProperty("childType")) + if (!$util.isString(message.childType)) + return "childType: string expected"; + return null; + }; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceReference + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceReference} ResourceReference + */ + ResourceReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceReference) + return object; + var message = new $root.google.api.ResourceReference(); + if (object.type != null) + message.type = String(object.type); + if (object.childType != null) + message.childType = String(object.childType); + return message; + }; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceReference + * @static + * @param {google.api.ResourceReference} message ResourceReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type = ""; + object.childType = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.childType != null && message.hasOwnProperty("childType")) + object.childType = message.childType; + return object; + }; + + /** + * Converts this ResourceReference to JSON. + * @function toJSON + * @memberof google.api.ResourceReference + * @instance + * @returns {Object.} JSON object + */ + ResourceReference.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceReference + * @function getTypeUrl + * @memberof google.api.ResourceReference + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceReference"; + }; + + return ResourceReference; + })(); + api.Http = (function() { /** @@ -24053,6 +40929,7 @@ * @property {string|null} [rubyPackage] FileOptions rubyPackage * @property {google.protobuf.IFeatureSet|null} [features] FileOptions features * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption + * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition */ /** @@ -24065,6 +40942,7 @@ */ function FileOptions(properties) { this.uninterpretedOption = []; + this[".google.api.resourceDefinition"] = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -24239,6 +41117,14 @@ */ FileOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * FileOptions .google.api.resourceDefinition. + * @member {Array.} .google.api.resourceDefinition + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; + /** * Creates a new FileOptions instance using the specified properties. * @function create @@ -24306,6 +41192,9 @@ if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + if (message[".google.api.resourceDefinition"] != null && message[".google.api.resourceDefinition"].length) + for (var i = 0; i < message[".google.api.resourceDefinition"].length; ++i) + $root.google.api.ResourceDescriptor.encode(message[".google.api.resourceDefinition"][i], writer.uint32(/* id 1053, wireType 2 =*/8426).fork()).ldelim(); return writer; }; @@ -24428,6 +41317,12 @@ message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); break; } + case 1053: { + if (!(message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length)) + message[".google.api.resourceDefinition"] = []; + message[".google.api.resourceDefinition"].push($root.google.api.ResourceDescriptor.decode(reader, reader.uint32())); + break; + } default: reader.skipType(tag & 7); break; @@ -24540,6 +41435,15 @@ return "uninterpretedOption." + error; } } + if (message[".google.api.resourceDefinition"] != null && message.hasOwnProperty(".google.api.resourceDefinition")) { + if (!Array.isArray(message[".google.api.resourceDefinition"])) + return ".google.api.resourceDefinition: array expected"; + for (var i = 0; i < message[".google.api.resourceDefinition"].length; ++i) { + var error = $root.google.api.ResourceDescriptor.verify(message[".google.api.resourceDefinition"][i]); + if (error) + return ".google.api.resourceDefinition." + error; + } + } return null; }; @@ -24626,6 +41530,16 @@ message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } } + if (object[".google.api.resourceDefinition"]) { + if (!Array.isArray(object[".google.api.resourceDefinition"])) + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: array expected"); + message[".google.api.resourceDefinition"] = []; + for (var i = 0; i < object[".google.api.resourceDefinition"].length; ++i) { + if (typeof object[".google.api.resourceDefinition"][i] !== "object") + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: object expected"); + message[".google.api.resourceDefinition"][i] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resourceDefinition"][i]); + } + } return message; }; @@ -24642,8 +41556,10 @@ if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) + if (options.arrays || options.defaults) { object.uninterpretedOption = []; + object[".google.api.resourceDefinition"] = []; + } if (options.defaults) { object.javaPackage = ""; object.javaOuterClassname = ""; @@ -24711,6 +41627,11 @@ for (var j = 0; j < message.uninterpretedOption.length; ++j) object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); } + if (message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length) { + object[".google.api.resourceDefinition"] = []; + for (var j = 0; j < message[".google.api.resourceDefinition"].length; ++j) + object[".google.api.resourceDefinition"][j] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resourceDefinition"][j], options); + } return object; }; @@ -24772,6 +41693,7 @@ * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] MessageOptions deprecatedLegacyJsonFieldConflicts * @property {google.protobuf.IFeatureSet|null} [features] MessageOptions features * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption + * @property {google.api.IResourceDescriptor|null} [".google.api.resource"] MessageOptions .google.api.resource */ /** @@ -24846,6 +41768,14 @@ */ MessageOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * MessageOptions .google.api.resource. + * @member {google.api.IResourceDescriptor|null|undefined} .google.api.resource + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype[".google.api.resource"] = null; + /** * Creates a new MessageOptions instance using the specified properties. * @function create @@ -24885,6 +41815,8 @@ if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + if (message[".google.api.resource"] != null && Object.hasOwnProperty.call(message, ".google.api.resource")) + $root.google.api.ResourceDescriptor.encode(message[".google.api.resource"], writer.uint32(/* id 1053, wireType 2 =*/8426).fork()).ldelim(); return writer; }; @@ -24951,6 +41883,10 @@ message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); break; } + case 1053: { + message[".google.api.resource"] = $root.google.api.ResourceDescriptor.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -25015,6 +41951,11 @@ return "uninterpretedOption." + error; } } + if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) { + var error = $root.google.api.ResourceDescriptor.verify(message[".google.api.resource"]); + if (error) + return ".google.api.resource." + error; + } return null; }; @@ -25055,6 +41996,11 @@ message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } } + if (object[".google.api.resource"] != null) { + if (typeof object[".google.api.resource"] !== "object") + throw TypeError(".google.protobuf.MessageOptions..google.api.resource: object expected"); + message[".google.api.resource"] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resource"]); + } return message; }; @@ -25080,6 +42026,7 @@ object.mapEntry = false; object.deprecatedLegacyJsonFieldConflicts = false; object.features = null; + object[".google.api.resource"] = null; } if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) object.messageSetWireFormat = message.messageSetWireFormat; @@ -25098,6 +42045,8 @@ for (var j = 0; j < message.uninterpretedOption.length; ++j) object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); } + if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) + object[".google.api.resource"] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resource"], options); return object; }; @@ -25150,6 +42099,7 @@ * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior + * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference */ /** @@ -25283,6 +42233,14 @@ */ FieldOptions.prototype[".google.api.fieldBehavior"] = $util.emptyArray; + /** + * FieldOptions .google.api.resourceReference. + * @member {google.api.IResourceReference|null|undefined} .google.api.resourceReference + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.resourceReference"] = null; + /** * Creates a new FieldOptions instance using the specified properties. * @function create @@ -25339,6 +42297,8 @@ if (message[".google.api.fieldBehavior"] != null && message[".google.api.fieldBehavior"].length) for (var i = 0; i < message[".google.api.fieldBehavior"].length; ++i) writer.uint32(/* id 1052, wireType 0 =*/8416).int32(message[".google.api.fieldBehavior"][i]); + if (message[".google.api.resourceReference"] != null && Object.hasOwnProperty.call(message, ".google.api.resourceReference")) + $root.google.api.ResourceReference.encode(message[".google.api.resourceReference"], writer.uint32(/* id 1055, wireType 2 =*/8442).fork()).ldelim(); return writer; }; @@ -25449,6 +42409,10 @@ message[".google.api.fieldBehavior"].push(reader.int32()); break; } + case 1055: { + message[".google.api.resourceReference"] = $root.google.api.ResourceReference.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -25591,6 +42555,11 @@ break; } } + if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) { + var error = $root.google.api.ResourceReference.verify(message[".google.api.resourceReference"]); + if (error) + return ".google.api.resourceReference." + error; + } return null; }; @@ -25805,6 +42774,11 @@ break; } } + if (object[".google.api.resourceReference"] != null) { + if (typeof object[".google.api.resourceReference"] !== "object") + throw TypeError(".google.protobuf.FieldOptions..google.api.resourceReference: object expected"); + message[".google.api.resourceReference"] = $root.google.api.ResourceReference.fromObject(object[".google.api.resourceReference"]); + } return message; }; @@ -25838,6 +42812,7 @@ object.debugRedact = false; object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; object.features = null; + object[".google.api.resourceReference"] = null; } if (message.ctype != null && message.hasOwnProperty("ctype")) object.ctype = options.enums === String ? $root.google.protobuf.FieldOptions.CType[message.ctype] === undefined ? message.ctype : $root.google.protobuf.FieldOptions.CType[message.ctype] : message.ctype; @@ -25879,6 +42854,8 @@ for (var j = 0; j < message[".google.api.fieldBehavior"].length; ++j) object[".google.api.fieldBehavior"][j] = options.enums === String ? $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] === undefined ? message[".google.api.fieldBehavior"][j] : $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] : message[".google.api.fieldBehavior"][j]; } + if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) + object[".google.api.resourceReference"] = $root.google.api.ResourceReference.toObject(message[".google.api.resourceReference"], options); return object; }; @@ -31487,6 +48464,404 @@ return Duration; })(); + protobuf.Empty = (function() { + + /** + * Properties of an Empty. + * @memberof google.protobuf + * @interface IEmpty + */ + + /** + * Constructs a new Empty. + * @memberof google.protobuf + * @classdesc Represents an Empty. + * @implements IEmpty + * @constructor + * @param {google.protobuf.IEmpty=} [properties] Properties to set + */ + function Empty(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a new Empty instance using the specified properties. + * @function create + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.IEmpty=} [properties] Properties to set + * @returns {google.protobuf.Empty} Empty instance + */ + Empty.create = function create(properties) { + return new Empty(properties); + }; + + /** + * Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @function encode + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.IEmpty} message Empty message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Empty.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.IEmpty} message Empty message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Empty.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an Empty message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.Empty + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.Empty} Empty + * @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, 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); + break; + } + } + return message; + }; + + /** + * Decodes an Empty message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.Empty + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.Empty} Empty + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Empty.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an Empty message. + * @function verify + * @memberof google.protobuf.Empty + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Empty.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Empty + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Empty} Empty + */ + Empty.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Empty) + return object; + return new $root.google.protobuf.Empty(); + }; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.Empty} message Empty + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Empty.toObject = function toObject() { + return {}; + }; + + /** + * Converts this Empty to JSON. + * @function toJSON + * @memberof google.protobuf.Empty + * @instance + * @returns {Object.} JSON object + */ + Empty.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Empty + * @function getTypeUrl + * @memberof google.protobuf.Empty + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Empty"; + }; + + return Empty; + })(); + + protobuf.FieldMask = (function() { + + /** + * Properties of a FieldMask. + * @memberof google.protobuf + * @interface IFieldMask + * @property {Array.|null} [paths] FieldMask paths + */ + + /** + * Constructs a new FieldMask. + * @memberof google.protobuf + * @classdesc Represents a FieldMask. + * @implements IFieldMask + * @constructor + * @param {google.protobuf.IFieldMask=} [properties] Properties to set + */ + function FieldMask(properties) { + this.paths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldMask paths. + * @member {Array.} paths + * @memberof google.protobuf.FieldMask + * @instance + */ + FieldMask.prototype.paths = $util.emptyArray; + + /** + * Creates a new FieldMask instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.IFieldMask=} [properties] Properties to set + * @returns {google.protobuf.FieldMask} FieldMask instance + */ + FieldMask.create = function create(properties) { + return new FieldMask(properties); + }; + + /** + * Encodes the specified FieldMask message. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.IFieldMask} message FieldMask message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldMask.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.paths != null && message.paths.length) + for (var i = 0; i < message.paths.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.paths[i]); + return writer; + }; + + /** + * Encodes the specified FieldMask message, length delimited. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.IFieldMask} message FieldMask message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FieldMask.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FieldMask message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldMask + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldMask} FieldMask + * @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, 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)) + message.paths = []; + message.paths.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FieldMask message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldMask + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldMask} FieldMask + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FieldMask.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FieldMask message. + * @function verify + * @memberof google.protobuf.FieldMask + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FieldMask.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.paths != null && message.hasOwnProperty("paths")) { + if (!Array.isArray(message.paths)) + return "paths: array expected"; + for (var i = 0; i < message.paths.length; ++i) + if (!$util.isString(message.paths[i])) + return "paths: string[] expected"; + } + return null; + }; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldMask + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldMask} FieldMask + */ + FieldMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldMask) + return object; + var message = new $root.google.protobuf.FieldMask(); + if (object.paths) { + if (!Array.isArray(object.paths)) + throw TypeError(".google.protobuf.FieldMask.paths: array expected"); + message.paths = []; + for (var i = 0; i < object.paths.length; ++i) + message.paths[i] = String(object.paths[i]); + } + return message; + }; + + /** + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldMask + * @static + * @param {google.protobuf.FieldMask} message FieldMask + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldMask.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.paths = []; + if (message.paths && message.paths.length) { + object.paths = []; + for (var j = 0; j < message.paths.length; ++j) + object.paths[j] = message.paths[j]; + } + return object; + }; + + /** + * Converts this FieldMask to JSON. + * @function toJSON + * @memberof google.protobuf.FieldMask + * @instance + * @returns {Object.} JSON object + */ + FieldMask.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldMask + * @function getTypeUrl + * @memberof google.protobuf.FieldMask + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldMask"; + }; + + return FieldMask; + })(); + return protobuf; })(); diff --git a/packages/google-ads-datamanager/protos/protos.json b/packages/google-ads-datamanager/protos/protos.json index ffb98553750..2fefbf18e39 100644 --- a/packages/google-ads-datamanager/protos/protos.json +++ b/packages/google-ads-datamanager/protos/protos.json @@ -11,19 +11,35 @@ "csharp_namespace": "Google.Ads.DataManager.V1", "go_package": "cloud.google.com/go/datamanager/apiv1/datamanagerpb;datamanagerpb", "java_multiple_files": true, - "java_outer_classname": "TermsOfServiceProto", + "java_outer_classname": "UserListServiceProto", "java_package": "com.google.ads.datamanager.v1", "php_namespace": "Google\\Ads\\DataManager\\V1", - "ruby_package": "Google::Ads::DataManager::V1" + "ruby_package": "Google::Ads::DataManager::V1", + "(google.api.resource_definition).type": "datamanager.googleapis.com/Account", + "(google.api.resource_definition).pattern": "accountTypes/{account_type}/accounts/{account}" }, "nested": { + "AgeRange": { + "values": { + "AGE_RANGE_UNSPECIFIED": 0, + "AGE_RANGE_UNKNOWN": 1, + "AGE_RANGE_18_24": 2, + "AGE_RANGE_25_34": 3, + "AGE_RANGE_35_44": 4, + "AGE_RANGE_45_54": 5, + "AGE_RANGE_55_64": 6, + "AGE_RANGE_65_UP": 7 + } + }, "AudienceMember": { "oneofs": { "data": { "oneof": [ "userData", "pairData", - "mobileData" + "mobileData", + "userIdData", + "ppidData" ] } }, @@ -48,6 +64,14 @@ "type": "MobileData", "id": 5 }, + "userIdData": { + "type": "UserIdData", + "id": 6 + }, + "ppidData": { + "type": "PpidData", + "id": 7 + }, "consent": { "type": "Consent", "id": 3, @@ -81,6 +105,29 @@ } } }, + "UserIdData": { + "fields": { + "userId": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "PpidData": { + "fields": { + "ppids": { + "rule": "repeated", + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "Consent": { "fields": { "adUserData": { @@ -344,7 +391,8 @@ "DISPLAY_VIDEO_PARTNER": 2, "DISPLAY_VIDEO_ADVERTISER": 3, "DATA_PARTNER": 4, - "GOOGLE_ANALYTICS_PROPERTY": 5 + "GOOGLE_ANALYTICS_PROPERTY": 5, + "GOOGLE_AD_MANAGER_AUDIENCE_LINK": 6 } } } @@ -532,10 +580,64 @@ "INVALID_REQUEST_ID": 48, "MULTIPLE_DESTINATIONS_FOR_GOOGLE_ANALYTICS_EVENT": 49, "FIELD_VALUE_TOO_LONG": 50, - "TOO_MANY_ELEMENTS": 51 + "TOO_MANY_ELEMENTS": 51, + "ALREADY_EXISTS": 52, + "IMMUTABLE_FIELD_FOR_UPDATE": 53, + "INVALID_RESOURCE_NAME": 54, + "INVALID_FILTER": 55, + "INVALID_UPDATE_MASK": 56, + "INVALID_PAGE_TOKEN": 57, + "CANNOT_UPDATE_DISABLED_LICENSE": 58, + "CANNOT_CREATE_LICENSE_FOR_SENSITIVE_USERLIST": 59, + "INSUFFICIENT_COST": 60, + "CANNOT_DISABLE_LICENSE": 61, + "INVALID_CLIENT_ACCOUNT_ID": 62, + "PRICING_ONLY_ZERO_COST_ALLOWED": 63, + "PRICE_TOO_HIGH": 64, + "CUSTOMER_NOT_ALLOWED_TO_CREATE_LICENSE": 65, + "INVALID_PRICING_END_DATE": 66, + "CANNOT_LICENSE_LOGICAL_LIST_WITH_LICENSED_OR_SHARED_SEGMENT": 67, + "MISMATCHED_ACCOUNT_TYPE": 68, + "MEDIA_SHARE_COST_NOT_ALLOWED_FOR_LICENSE_TYPE": 69, + "MEDIA_SHARE_COST_NOT_ALLOWED_FOR_CLIENT_CUSTOMER": 70, + "INVALID_MEDIA_SHARE_COST": 71, + "INVALID_COST_TYPE": 72, + "MEDIA_SHARE_COST_NOT_ALLOWED_FOR_NON_COMMERCE_USER_LIST": 73, + "MAX_COST_NOT_ALLOWED": 74, + "COMMERCE_AUDIENCE_CAN_ONLY_BE_DIRECTLY_LICENSED": 75, + "INVALID_DESCRIPTION": 76, + "INVALID_DISPLAY_NAME": 77, + "DISPLAY_NAME_ALREADY_USED": 78, + "OWNERSHIP_REQUIRED_FOR_UPDATE": 79, + "USER_LIST_MUTATION_NOT_SUPPORTED": 80, + "SENSITIVE_USER_LIST_IMMUTABLE": 81, + "BILLABLE_RECORD_COUNT_IMMUTABLE": 82, + "USER_LIST_NAME_RESERVED": 83, + "ADVERTISER_NOT_ALLOWLISTED_FOR_UPLOADED_DATA": 84, + "UNSUPPORTED_PARTNER_AUDIENCE_SOURCE": 85, + "COMMERCE_PARTNER_NOT_ALLOWED": 86, + "UNSUPPORTED_PARTNER_AUDIENCE_INFO": 87, + "PARTNER_MATCH_FOR_MANAGER_ACCOUNT_DISALLOWED": 88, + "DATA_PARTNER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA": 89, + "ADVERTISER_TOS_NOT_ACCEPTED": 90, + "ADVERTISER_NOT_ALLOWLISTED_FOR_THIRD_PARTY_PARTNER_DATA": 91, + "USER_LIST_TYPE_NOT_SUPPORTED_FOR_ACCOUNT": 92, + "INVALID_COMMERCE_PARTNER": 93, + "CUSTOMER_NOT_ALLOWLISTED_FOR_COMMERCE_AUDIENCE": 94, + "UNSUPPORTED_USER_LIST_UPLOAD_KEY_TYPES": 95, + "UNSUPPORTED_INGESTED_USER_LIST_INFO_CONFIG": 96, + "UNSUPPORTED_ACCOUNT_TYPES_FOR_USER_LIST_TYPE": 97, + "UNSUPPORTED_ACCOUNT_TYPE_FOR_PARTNER_LINK": 98 } }, "Event": { + "oneofs": { + "_conversionValue": { + "oneof": [ + "conversionValue" + ] + } + }, "fields": { "destinationReferences": { "rule": "repeated", @@ -598,7 +700,8 @@ "type": "double", "id": 9, "options": { - "(google.api.field_behavior)": "OPTIONAL" + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true } }, "eventSource": { @@ -847,6 +950,14 @@ "HIGH": 3 } }, + "Gender": { + "values": { + "GENDER_UNSPECIFIED": 0, + "GENDER_UNKNOWN": 1, + "GENDER_MALE": 2, + "GENDER_FEMALE": 3 + } + }, "IngestionService": { "options": { "(google.api.default_host)": "datamanager.googleapis.com", @@ -1168,7 +1279,9 @@ "oneof": [ "userDataIngestionStatus", "mobileDataIngestionStatus", - "pairDataIngestionStatus" + "pairDataIngestionStatus", + "userIdDataIngestionStatus", + "ppidDataIngestionStatus" ] } }, @@ -1184,6 +1297,14 @@ "pairDataIngestionStatus": { "type": "IngestPairDataStatus", "id": 3 + }, + "userIdDataIngestionStatus": { + "type": "IngestUserIdDataStatus", + "id": 4 + }, + "ppidDataIngestionStatus": { + "type": "IngestPpidDataStatus", + "id": 5 } } }, @@ -1193,7 +1314,9 @@ "oneof": [ "userDataRemovalStatus", "mobileDataRemovalStatus", - "pairDataRemovalStatus" + "pairDataRemovalStatus", + "userIdDataRemovalStatus", + "ppidDataRemovalStatus" ] } }, @@ -1209,6 +1332,14 @@ "pairDataRemovalStatus": { "type": "RemovePairDataStatus", "id": 3 + }, + "userIdDataRemovalStatus": { + "type": "RemoveUserIdDataStatus", + "id": 4 + }, + "ppidDataRemovalStatus": { + "type": "RemovePpidDataStatus", + "id": 5 } } }, @@ -1266,157 +1397,2200 @@ "type": "int64", "id": 1 }, - "mobileIdCount": { - "type": "int64", - "id": 2 + "mobileIdCount": { + "type": "int64", + "id": 2 + } + } + }, + "IngestPairDataStatus": { + "fields": { + "recordCount": { + "type": "int64", + "id": 1 + }, + "pairIdCount": { + "type": "int64", + "id": 2 + } + } + }, + "RemovePairDataStatus": { + "fields": { + "recordCount": { + "type": "int64", + "id": 1 + }, + "pairIdCount": { + "type": "int64", + "id": 2 + } + } + }, + "IngestUserIdDataStatus": { + "fields": { + "recordCount": { + "type": "int64", + "id": 1 + }, + "userIdCount": { + "type": "int64", + "id": 2 + } + } + }, + "RemoveUserIdDataStatus": { + "fields": { + "recordCount": { + "type": "int64", + "id": 1 + }, + "userIdCount": { + "type": "int64", + "id": 2 + } + } + }, + "IngestPpidDataStatus": { + "fields": { + "recordCount": { + "type": "int64", + "id": 1 + }, + "ppidCount": { + "type": "int64", + "id": 2 + } + } + }, + "RemovePpidDataStatus": { + "fields": { + "recordCount": { + "type": "int64", + "id": 1 + }, + "ppidCount": { + "type": "int64", + "id": 2 + } + } + } + } + }, + "MatchRateRange": { + "values": { + "MATCH_RATE_RANGE_UNKNOWN": 0, + "MATCH_RATE_RANGE_NOT_ELIGIBLE": 1, + "MATCH_RATE_RANGE_LESS_THAN_20": 2, + "MATCH_RATE_RANGE_20_TO_30": 3, + "MATCH_RATE_RANGE_31_TO_40": 4, + "MATCH_RATE_RANGE_41_TO_50": 5, + "MATCH_RATE_RANGE_51_TO_60": 6, + "MATCH_RATE_RANGE_61_TO_70": 7, + "MATCH_RATE_RANGE_71_TO_80": 8, + "MATCH_RATE_RANGE_81_TO_90": 9, + "MATCH_RATE_RANGE_91_TO_100": 10 + } + }, + "ErrorInfo": { + "fields": { + "errorCounts": { + "rule": "repeated", + "type": "ErrorCount", + "id": 1 + } + } + }, + "ErrorCount": { + "fields": { + "recordCount": { + "type": "int64", + "id": 1 + }, + "reason": { + "type": "ProcessingErrorReason", + "id": 2 + } + } + }, + "WarningInfo": { + "fields": { + "warningCounts": { + "rule": "repeated", + "type": "WarningCount", + "id": 1 + } + } + }, + "WarningCount": { + "fields": { + "recordCount": { + "type": "int64", + "id": 1 + }, + "reason": { + "type": "ProcessingWarningReason", + "id": 2 + } + } + }, + "ProcessingErrorReason": { + "values": { + "PROCESSING_ERROR_REASON_UNSPECIFIED": 0, + "PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE": 1, + "PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED": 2, + "PROCESSING_ERROR_REASON_EVENT_TOO_OLD": 3, + "PROCESSING_ERROR_REASON_DENIED_CONSENT": 4, + "PROCESSING_ERROR_REASON_NO_CONSENT": 5, + "PROCESSING_ERROR_REASON_UNKNOWN_CONSENT": 6, + "PROCESSING_ERROR_REASON_DUPLICATE_GCLID": 7, + "PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID": 8, + "PROCESSING_ERROR_REASON_INVALID_GBRAID": 9, + "PROCESSING_ERROR_REASON_INVALID_GCLID": 10, + "PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID": 11, + "PROCESSING_ERROR_REASON_INVALID_WBRAID": 12, + "PROCESSING_ERROR_REASON_INTERNAL_ERROR": 13, + "PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED": 14, + "PROCESSING_ERROR_REASON_INVALID_EVENT": 15, + "PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS": 16, + "PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS": 17, + "PROCESSING_ERROR_REASON_INVALID_FORMAT": 18, + "PROCESSING_ERROR_REASON_DECRYPTION_ERROR": 19, + "PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR": 20, + "PROCESSING_ERROR_REASON_INVALID_WIP": 21, + "PROCESSING_ERROR_REASON_INVALID_KEK": 22, + "PROCESSING_ERROR_REASON_WIP_AUTH_FAILED": 23, + "PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED": 24, + "PROCESSING_ERROR_REASON_AWS_AUTH_FAILED": 27, + "PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR": 25, + "PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER": 26 + } + }, + "ProcessingWarningReason": { + "values": { + "PROCESSING_WARNING_REASON_UNSPECIFIED": 0, + "PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED": 1, + "PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR": 2, + "PROCESSING_WARNING_REASON_DECRYPTION_ERROR": 3, + "PROCESSING_WARNING_REASON_WIP_AUTH_FAILED": 4, + "PROCESSING_WARNING_REASON_INVALID_WIP": 5, + "PROCESSING_WARNING_REASON_INVALID_KEK": 6, + "PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR": 7, + "PROCESSING_WARNING_REASON_INTERNAL_ERROR": 8, + "PROCESSING_WARNING_REASON_AWS_AUTH_FAILED": 9 + } + }, + "TermsOfService": { + "fields": { + "customerMatchTermsOfServiceStatus": { + "type": "TermsOfServiceStatus", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "TermsOfServiceStatus": { + "values": { + "TERMS_OF_SERVICE_STATUS_UNSPECIFIED": 0, + "ACCEPTED": 1, + "REJECTED": 2 + } + }, + "MarketingDataInsightsService": { + "options": { + "(google.api.default_host)": "datamanager.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/datamanager" + }, + "methods": { + "RetrieveInsights": { + "requestType": "RetrieveInsightsRequest", + "responseType": "RetrieveInsightsResponse", + "options": { + "(google.api.http).post": "/v1/{parent=accountTypes/*/accounts/*}/insights:retrieve", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=accountTypes/*/accounts/*}/insights:retrieve", + "body": "*" + } + } + ] + } + } + }, + "RetrieveInsightsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "baseline": { + "type": "Baseline", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "userListId": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "Baseline": { + "oneofs": { + "baseline": { + "oneof": [ + "baselineLocation", + "locationAutoDetectionEnabled" + ] + } + }, + "fields": { + "baselineLocation": { + "type": "Location", + "id": 1 + }, + "locationAutoDetectionEnabled": { + "type": "bool", + "id": 2 + } + }, + "nested": { + "Location": { + "fields": { + "regionCodes": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } + } + } + }, + "RetrieveInsightsResponse": { + "fields": { + "marketingDataInsights": { + "rule": "repeated", + "type": "MarketingDataInsight", + "id": 1 + } + }, + "nested": { + "MarketingDataInsight": { + "fields": { + "dimension": { + "type": "AudienceInsightsDimension", + "id": 1 + }, + "attributes": { + "rule": "repeated", + "type": "MarketingDataInsightsAttribute", + "id": 2 + } + }, + "nested": { + "AudienceInsightsDimension": { + "values": { + "AUDIENCE_INSIGHTS_DIMENSION_UNSPECIFIED": 0, + "AUDIENCE_INSIGHTS_DIMENSION_UNKNOWN": 1, + "AFFINITY_USER_INTEREST": 2, + "IN_MARKET_USER_INTEREST": 3, + "AGE_RANGE": 4, + "GENDER": 5 + } + }, + "MarketingDataInsightsAttribute": { + "oneofs": { + "_userInterestId": { + "oneof": [ + "userInterestId" + ] + }, + "_lift": { + "oneof": [ + "lift" + ] + }, + "_ageRange": { + "oneof": [ + "ageRange" + ] + }, + "_gender": { + "oneof": [ + "gender" + ] + } + }, + "fields": { + "userInterestId": { + "type": "int64", + "id": 1, + "options": { + "proto3_optional": true + } + }, + "lift": { + "type": "float", + "id": 2, + "options": { + "proto3_optional": true + } + }, + "ageRange": { + "type": "AgeRange", + "id": 3, + "options": { + "proto3_optional": true + } + }, + "gender": { + "type": "Gender", + "id": 4, + "options": { + "proto3_optional": true + } + } + } + } + } + } + } + }, + "PartnerLinkService": { + "options": { + "(google.api.default_host)": "datamanager.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/datamanager" + }, + "methods": { + "CreatePartnerLink": { + "requestType": "CreatePartnerLinkRequest", + "responseType": "PartnerLink", + "options": { + "(google.api.http).post": "/v1/{parent=accountTypes/*/accounts/*}/partnerLinks", + "(google.api.http).body": "partner_link", + "(google.api.method_signature)": "parent,partner_link" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=accountTypes/*/accounts/*}/partnerLinks", + "body": "partner_link" + } + }, + { + "(google.api.method_signature)": "parent,partner_link" + } + ] + }, + "DeletePartnerLink": { + "requestType": "DeletePartnerLinkRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=accountTypes/*/accounts/*/partnerLinks/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=accountTypes/*/accounts/*/partnerLinks/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "SearchPartnerLinks": { + "requestType": "SearchPartnerLinksRequest", + "responseType": "SearchPartnerLinksResponse", + "options": { + "(google.api.http).get": "/v1/{parent=accountTypes/*/accounts/*}/partnerLinks:search", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=accountTypes/*/accounts/*}/partnerLinks:search" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + } + } + }, + "CreatePartnerLinkRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/PartnerLink" + } + }, + "partnerLink": { + "type": "PartnerLink", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "DeletePartnerLinkRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "datamanager.googleapis.com/PartnerLink" + } + } + } + }, + "SearchPartnerLinksRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/PartnerLink" + } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + }, + "filter": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "SearchPartnerLinksResponse": { + "fields": { + "partnerLinks": { + "rule": "repeated", + "type": "PartnerLink", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "PartnerLink": { + "options": { + "(google.api.resource).type": "datamanager.googleapis.com/PartnerLink", + "(google.api.resource).pattern": "accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}", + "(google.api.resource).plural": "partnerLinks", + "(google.api.resource).singular": "partnerLink" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "IDENTIFIER" + } + }, + "partnerLinkId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "owningAccount": { + "type": "ProductAccount", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "partnerAccount": { + "type": "ProductAccount", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "UserList": { + "options": { + "(google.api.resource).type": "datamanager.googleapis.com/UserList", + "(google.api.resource).pattern": "accountTypes/{account_type}/accounts/{account}/userLists/{user_list}", + "(google.api.resource).plural": "userLists", + "(google.api.resource).singular": "userList" + }, + "oneofs": { + "_displayName": { + "oneof": [ + "displayName" + ] + }, + "_description": { + "oneof": [ + "description" + ] + }, + "_membershipStatus": { + "oneof": [ + "membershipStatus" + ] + }, + "_integrationCode": { + "oneof": [ + "integrationCode" + ] + }, + "_closingReason": { + "oneof": [ + "closingReason" + ] + }, + "_accountAccessStatus": { + "oneof": [ + "accountAccessStatus" + ] + }, + "userListInfo": { + "oneof": [ + "ingestedUserListInfo" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "IDENTIFIER" + } + }, + "id": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "readOnly": { + "type": "bool", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "displayName": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "proto3_optional": true + } + }, + "description": { + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "membershipStatus": { + "type": "MembershipStatus", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "integrationCode": { + "type": "string", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "membershipDuration": { + "type": "google.protobuf.Duration", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "closingReason": { + "type": "ClosingReason", + "id": 9, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "proto3_optional": true + } + }, + "accessReason": { + "type": "AccessReason", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "accountAccessStatus": { + "type": "AccessStatus", + "id": 11, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "sizeInfo": { + "type": "SizeInfo", + "id": 12, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "targetNetworkInfo": { + "type": "TargetNetworkInfo", + "id": 13, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "ingestedUserListInfo": { + "type": "IngestedUserListInfo", + "id": 14, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "MembershipStatus": { + "values": { + "MEMBERSHIP_STATUS_UNSPECIFIED": 0, + "OPEN": 1, + "CLOSED": 2 + } + }, + "ClosingReason": { + "values": { + "CLOSING_REASON_UNSPECIFIED": 0, + "UNUSED": 1 + } + }, + "AccessReason": { + "values": { + "ACCESS_REASON_UNSPECIFIED": 0, + "OWNED": 1, + "SHARED": 2, + "LICENSED": 3, + "SUBSCRIBED": 4, + "AFFILIATED": 5 + } + }, + "AccessStatus": { + "values": { + "ACCESS_STATUS_UNSPECIFIED": 0, + "ENABLED": 1, + "DISABLED": 2 + } + } + } + }, + "SizeInfo": { + "fields": { + "displayNetworkMembersCount": { + "type": "int64", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "searchNetworkMembersCount": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "TargetNetworkInfo": { + "oneofs": { + "_eligibleForSearch": { + "oneof": [ + "eligibleForSearch" + ] + } + }, + "fields": { + "eligibleForDisplay": { + "type": "bool", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "eligibleForSearch": { + "type": "bool", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + } + } + }, + "IngestedUserListInfo": { + "fields": { + "uploadKeyTypes": { + "rule": "repeated", + "type": "UploadKeyType", + "id": 1, + "options": { + "(google.api.field_behavior)": "IMMUTABLE" + } + }, + "contactIdInfo": { + "type": "ContactIdInfo", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "mobileIdInfo": { + "type": "MobileIdInfo", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "userIdInfo": { + "type": "UserIdInfo", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pairIdInfo": { + "type": "PairIdInfo", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pseudonymousIdInfo": { + "type": "PseudonymousIdInfo", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "partnerAudienceInfo": { + "type": "PartnerAudienceInfo", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "UploadKeyType": { + "values": { + "UPLOAD_KEY_TYPE_UNSPECIFIED": 0, + "CONTACT_ID": 1, + "MOBILE_ID": 2, + "USER_ID": 3, + "PAIR_ID": 4, + "PSEUDONYMOUS_ID": 5 + } + } + } + }, + "ContactIdInfo": { + "oneofs": { + "_dataSourceType": { + "oneof": [ + "dataSourceType" + ] + } + }, + "fields": { + "dataSourceType": { + "type": "DataSourceType", + "id": 1, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "matchRatePercentage": { + "type": "int32", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "MobileIdInfo": { + "oneofs": { + "_dataSourceType": { + "oneof": [ + "dataSourceType" + ] + }, + "_keySpace": { + "oneof": [ + "keySpace" + ] + }, + "_appId": { + "oneof": [ + "appId" + ] + } + }, + "fields": { + "dataSourceType": { + "type": "DataSourceType", + "id": 1, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "keySpace": { + "type": "KeySpace", + "id": 2, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "appId": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + } + }, + "nested": { + "KeySpace": { + "values": { + "KEY_SPACE_UNSPECIFIED": 0, + "IOS": 1, + "ANDROID": 2 + } + } + } + }, + "UserIdInfo": { + "oneofs": { + "_dataSourceType": { + "oneof": [ + "dataSourceType" + ] + } + }, + "fields": { + "dataSourceType": { + "type": "DataSourceType", + "id": 1, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + } + } + }, + "PairIdInfo": { + "oneofs": { + "_publisherId": { + "oneof": [ + "publisherId" + ] + }, + "_publisherName": { + "oneof": [ + "publisherName" + ] + }, + "_cleanRoomIdentifier": { + "oneof": [ + "cleanRoomIdentifier" + ] + } + }, + "fields": { + "publisherId": { + "type": "int64", + "id": 1, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "publisherName": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "matchRatePercentage": { + "type": "int32", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "advertiserIdentifierCount": { + "type": "int64", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "cleanRoomIdentifier": { + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + } + } + }, + "PartnerAudienceInfo": { + "oneofs": { + "_partnerAudienceSource": { + "oneof": [ + "partnerAudienceSource" + ] + }, + "_commercePartner": { + "oneof": [ + "commercePartner" + ] + } + }, + "fields": { + "partnerAudienceSource": { + "type": "PartnerAudienceSource", + "id": 1, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "commercePartner": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + } + }, + "nested": { + "PartnerAudienceSource": { + "values": { + "PARTNER_AUDIENCE_SOURCE_UNSPECIFIED": 0, + "COMMERCE_AUDIENCE": 1, + "LINEAR_TV_AUDIENCE": 2, + "AGENCY_PROVIDER_AUDIENCE": 3 + } + } + } + }, + "PseudonymousIdInfo": { + "oneofs": { + "_syncStatus": { + "oneof": [ + "syncStatus" + ] + }, + "_billableRecordCount": { + "oneof": [ + "billableRecordCount" + ] + } + }, + "fields": { + "syncStatus": { + "type": "SyncStatus", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "proto3_optional": true + } + }, + "billableRecordCount": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + } + }, + "nested": { + "SyncStatus": { + "values": { + "SYNC_STATUS_UNSPECIFIED": 0, + "CREATED": 1, + "READY_FOR_USE": 2, + "FAILED": 3 + } + } + } + }, + "DataSourceType": { + "values": { + "DATA_SOURCE_TYPE_UNSPECIFIED": 0, + "DATA_SOURCE_TYPE_FIRST_PARTY": 1, + "DATA_SOURCE_TYPE_THIRD_PARTY_CREDIT_BUREAU": 2, + "DATA_SOURCE_TYPE_THIRD_PARTY_VOTER_FILE": 3, + "DATA_SOURCE_TYPE_THIRD_PARTY_PARTNER_DATA": 4 + } + }, + "UserListDirectLicense": { + "options": { + "(google.api.resource).type": "datamanager.googleapis.com/UserListDirectLicense", + "(google.api.resource).pattern": "accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}", + "(google.api.resource).plural": "userListDirectLicenses", + "(google.api.resource).singular": "userListDirectLicense" + }, + "oneofs": { + "_userListId": { + "oneof": [ + "userListId" + ] + }, + "_clientAccountType": { + "oneof": [ + "clientAccountType" + ] + }, + "_clientAccountId": { + "oneof": [ + "clientAccountId" + ] + }, + "_status": { + "oneof": [ + "status" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "IDENTIFIER" + } + }, + "userListId": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "userListDisplayName": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "clientAccountType": { + "type": "UserListLicenseClientAccountType", + "id": 4, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "clientAccountId": { + "type": "int64", + "id": 5, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "clientAccountDisplayName": { + "type": "string", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "status": { + "type": "UserListLicenseStatus", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "pricing": { + "type": "UserListLicensePricing", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "historicalPricings": { + "rule": "repeated", + "type": "UserListLicensePricing", + "id": 9, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "metrics": { + "type": "UserListLicenseMetrics", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "UserListLicenseClientAccountType": { + "values": { + "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_UNKNOWN": 0, + "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_ADS": 1, + "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_PARTNER": 2, + "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_DISPLAY_VIDEO_ADVERTISER": 3, + "USER_LIST_LICENSE_CLIENT_ACCOUNT_TYPE_GOOGLE_AD_MANAGER_AUDIENCE_LINK": 4 + } + }, + "UserListLicenseMetrics": { + "fields": { + "clickCount": { + "type": "int64", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "impressionCount": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "revenueUsdMicros": { + "type": "int64", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "startDate": { + "type": "int64", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "endDate": { + "type": "int64", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "UserListLicensePricing": { + "oneofs": { + "_costMicros": { + "oneof": [ + "costMicros" + ] + }, + "_currencyCode": { + "oneof": [ + "currencyCode" + ] + }, + "_costType": { + "oneof": [ + "costType" + ] + }, + "_maxCostMicros": { + "oneof": [ + "maxCostMicros" + ] + } + }, + "fields": { + "pricingId": { + "type": "int64", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "costMicros": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "currencyCode": { + "type": "string", + "id": 9, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pricingActive": { + "type": "bool", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "buyerApprovalState": { + "type": "UserListPricingBuyerApprovalState", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "costType": { + "type": "UserListPricingCostType", + "id": 7, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "maxCostMicros": { + "type": "int64", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + } + }, + "nested": { + "UserListPricingBuyerApprovalState": { + "values": { + "USER_LIST_PRICING_BUYER_APPROVAL_STATE_UNSPECIFIED": 0, + "PENDING": 1, + "APPROVED": 2, + "REJECTED": 3 + } + }, + "UserListPricingCostType": { + "values": { + "USER_LIST_PRICING_COST_TYPE_UNSPECIFIED": 0, + "CPC": 1, + "CPM": 2, + "MEDIA_SHARE": 3 + } + } + } + }, + "UserListLicenseStatus": { + "values": { + "USER_LIST_LICENSE_STATUS_UNSPECIFIED": 0, + "USER_LIST_LICENSE_STATUS_ENABLED": 1, + "USER_LIST_LICENSE_STATUS_DISABLED": 2 + } + }, + "UserListDirectLicenseService": { + "options": { + "(google.api.default_host)": "datamanager.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/datamanager" + }, + "methods": { + "CreateUserListDirectLicense": { + "requestType": "CreateUserListDirectLicenseRequest", + "responseType": "UserListDirectLicense", + "options": { + "(google.api.http).post": "/v1/{parent=accountTypes/*/accounts/*}/userListDirectLicenses", + "(google.api.http).body": "user_list_direct_license", + "(google.api.method_signature)": "parent,user_list_direct_license" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=accountTypes/*/accounts/*}/userListDirectLicenses", + "body": "user_list_direct_license" + } + }, + { + "(google.api.method_signature)": "parent,user_list_direct_license" + } + ] + }, + "GetUserListDirectLicense": { + "requestType": "GetUserListDirectLicenseRequest", + "responseType": "UserListDirectLicense", + "options": { + "(google.api.http).get": "/v1/{name=accountTypes/*/accounts/*/userListDirectLicenses/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=accountTypes/*/accounts/*/userListDirectLicenses/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "UpdateUserListDirectLicense": { + "requestType": "UpdateUserListDirectLicenseRequest", + "responseType": "UserListDirectLicense", + "options": { + "(google.api.http).patch": "/v1/{user_list_direct_license.name=accountTypes/*/accounts/*/userListDirectLicenses/*}", + "(google.api.http).body": "user_list_direct_license", + "(google.api.method_signature)": "user_list_direct_license,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{user_list_direct_license.name=accountTypes/*/accounts/*/userListDirectLicenses/*}", + "body": "user_list_direct_license" + } + }, + { + "(google.api.method_signature)": "user_list_direct_license,update_mask" + } + ] + }, + "ListUserListDirectLicenses": { + "requestType": "ListUserListDirectLicensesRequest", + "responseType": "ListUserListDirectLicensesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=accountTypes/*/accounts/*}/userListDirectLicenses", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=accountTypes/*/accounts/*}/userListDirectLicenses" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + } + } + }, + "CreateUserListDirectLicenseRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/UserListDirectLicense" + } + }, + "userListDirectLicense": { + "type": "UserListDirectLicense", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "GetUserListDirectLicenseRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "datamanager.googleapis.com/UserListDirectLicense" + } + } + } + }, + "UpdateUserListDirectLicenseRequest": { + "fields": { + "userListDirectLicense": { + "type": "UserListDirectLicense", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ListUserListDirectLicensesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/UserListDirectLicense" + } + }, + "filter": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageSize": { + "type": "int32", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageToken": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ListUserListDirectLicensesResponse": { + "fields": { + "userListDirectLicenses": { + "rule": "repeated", + "type": "UserListDirectLicense", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "UserListGlobalLicense": { + "options": { + "(google.api.resource).type": "datamanager.googleapis.com/UserListGlobalLicense", + "(google.api.resource).pattern": "accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}", + "(google.api.resource).plural": "userListGlobalLicenses", + "(google.api.resource).singular": "userListGlobalLicense" + }, + "oneofs": { + "_userListId": { + "oneof": [ + "userListId" + ] + }, + "_licenseType": { + "oneof": [ + "licenseType" + ] + }, + "_status": { + "oneof": [ + "status" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "IDENTIFIER" + } + }, + "userListId": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "userListDisplayName": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "licenseType": { + "type": "UserListGlobalLicenseType", + "id": 4, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "proto3_optional": true + } + }, + "status": { + "type": "UserListLicenseStatus", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL", + "proto3_optional": true + } + }, + "pricing": { + "type": "UserListLicensePricing", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "historicalPricings": { + "rule": "repeated", + "type": "UserListLicensePricing", + "id": 7, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "metrics": { + "type": "UserListLicenseMetrics", + "id": 8, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "UserListGlobalLicenseCustomerInfo": { + "options": { + "(google.api.resource).type": "datamanager.googleapis.com/UserListGlobalLicenseCustomerInfo", + "(google.api.resource).pattern": "accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}", + "(google.api.resource).plural": "userListGlobalLicenseCustomerInfos", + "(google.api.resource).singular": "userListGlobalLicenseCustomerInfo" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "IDENTIFIER" + } + }, + "userListId": { + "type": "int64", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "userListDisplayName": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "licenseType": { + "type": "UserListGlobalLicenseType", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "status": { + "type": "UserListLicenseStatus", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "pricing": { + "type": "UserListLicensePricing", + "id": 6, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "clientAccountType": { + "type": "UserListLicenseClientAccountType", + "id": 7, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "clientAccountId": { + "type": "int64", + "id": 8, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "clientAccountDisplayName": { + "type": "string", + "id": 9, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "historicalPricings": { + "rule": "repeated", + "type": "UserListLicensePricing", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "metrics": { + "type": "UserListLicenseMetrics", + "id": 11, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "UserListGlobalLicenseType": { + "values": { + "USER_LIST_GLOBAL_LICENSE_TYPE_UNSPECIFIED": 0, + "USER_LIST_GLOBAL_LICENSE_TYPE_RESELLER": 1, + "USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_SELL_SIDE": 2, + "USER_LIST_GLOBAL_LICENSE_TYPE_DATA_MART_BUY_SIDE": 3 + } + }, + "UserListGlobalLicenseService": { + "options": { + "(google.api.default_host)": "datamanager.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/datamanager" + }, + "methods": { + "CreateUserListGlobalLicense": { + "requestType": "CreateUserListGlobalLicenseRequest", + "responseType": "UserListGlobalLicense", + "options": { + "(google.api.http).post": "/v1/{parent=accountTypes/*/accounts/*}/userListGlobalLicenses", + "(google.api.http).body": "user_list_global_license", + "(google.api.method_signature)": "parent,user_list_global_license" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=accountTypes/*/accounts/*}/userListGlobalLicenses", + "body": "user_list_global_license" + } + }, + { + "(google.api.method_signature)": "parent,user_list_global_license" + } + ] + }, + "UpdateUserListGlobalLicense": { + "requestType": "UpdateUserListGlobalLicenseRequest", + "responseType": "UserListGlobalLicense", + "options": { + "(google.api.http).patch": "/v1/{user_list_global_license.name=accountTypes/*/accounts/*/userListGlobalLicenses/*}", + "(google.api.http).body": "user_list_global_license", + "(google.api.method_signature)": "user_list_global_license,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{user_list_global_license.name=accountTypes/*/accounts/*/userListGlobalLicenses/*}", + "body": "user_list_global_license" + } + }, + { + "(google.api.method_signature)": "user_list_global_license,update_mask" + } + ] + }, + "GetUserListGlobalLicense": { + "requestType": "GetUserListGlobalLicenseRequest", + "responseType": "UserListGlobalLicense", + "options": { + "(google.api.http).get": "/v1/{name=accountTypes/*/accounts/*/userListGlobalLicenses/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=accountTypes/*/accounts/*/userListGlobalLicenses/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListUserListGlobalLicenses": { + "requestType": "ListUserListGlobalLicensesRequest", + "responseType": "ListUserListGlobalLicensesResponse", + "options": { + "(google.api.http).get": "/v1/{parent=accountTypes/*/accounts/*}/userListGlobalLicenses", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=accountTypes/*/accounts/*}/userListGlobalLicenses" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "ListUserListGlobalLicenseCustomerInfos": { + "requestType": "ListUserListGlobalLicenseCustomerInfosRequest", + "responseType": "ListUserListGlobalLicenseCustomerInfosResponse", + "options": { + "(google.api.http).get": "/v1/{parent=accountTypes/*/accounts/*/userListGlobalLicenses/*}/userListGlobalLicenseCustomerInfos", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=accountTypes/*/accounts/*/userListGlobalLicenses/*}/userListGlobalLicenseCustomerInfos" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + } + } + }, + "CreateUserListGlobalLicenseRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/UserListGlobalLicense" + } + }, + "userListGlobalLicense": { + "type": "UserListGlobalLicense", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "UpdateUserListGlobalLicenseRequest": { + "fields": { + "userListGlobalLicense": { + "type": "UserListGlobalLicense", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "GetUserListGlobalLicenseRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "datamanager.googleapis.com/UserListGlobalLicense" + } + } + } + }, + "ListUserListGlobalLicensesRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/UserListGlobalLicense" + } + }, + "filter": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageSize": { + "type": "int32", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageToken": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ListUserListGlobalLicensesResponse": { + "fields": { + "userListGlobalLicenses": { + "rule": "repeated", + "type": "UserListGlobalLicense", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "ListUserListGlobalLicenseCustomerInfosRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/UserListGlobalLicenseCustomerInfo" + } + }, + "filter": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageSize": { + "type": "int32", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageToken": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "ListUserListGlobalLicenseCustomerInfosResponse": { + "fields": { + "userListGlobalLicenseCustomerInfos": { + "rule": "repeated", + "type": "UserListGlobalLicenseCustomerInfo", + "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 + } + } + }, + "UserListService": { + "options": { + "(google.api.default_host)": "datamanager.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/datamanager" + }, + "methods": { + "GetUserList": { + "requestType": "GetUserListRequest", + "responseType": "UserList", + "options": { + "(google.api.http).get": "/v1/{name=accountTypes/*/accounts/*/userLists/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=accountTypes/*/accounts/*/userLists/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListUserLists": { + "requestType": "ListUserListsRequest", + "responseType": "ListUserListsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=accountTypes/*/accounts/*}/userLists", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=accountTypes/*/accounts/*}/userLists" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "CreateUserList": { + "requestType": "CreateUserListRequest", + "responseType": "UserList", + "options": { + "(google.api.http).post": "/v1/{parent=accountTypes/*/accounts/*}/userLists", + "(google.api.http).body": "user_list", + "(google.api.method_signature)": "parent,user_list" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=accountTypes/*/accounts/*}/userLists", + "body": "user_list" + } + }, + { + "(google.api.method_signature)": "parent,user_list" } - } + ] }, - "IngestPairDataStatus": { - "fields": { - "recordCount": { - "type": "int64", - "id": 1 + "UpdateUserList": { + "requestType": "UpdateUserListRequest", + "responseType": "UserList", + "options": { + "(google.api.http).patch": "/v1/{user_list.name=accountTypes/*/accounts/*/userLists/*}", + "(google.api.http).body": "user_list", + "(google.api.method_signature)": "user_list,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{user_list.name=accountTypes/*/accounts/*/userLists/*}", + "body": "user_list" + } }, - "pairIdCount": { - "type": "int64", - "id": 2 + { + "(google.api.method_signature)": "user_list,update_mask" } - } + ] }, - "RemovePairDataStatus": { - "fields": { - "recordCount": { - "type": "int64", - "id": 1 + "DeleteUserList": { + "requestType": "DeleteUserListRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=accountTypes/*/accounts/*/userLists/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=accountTypes/*/accounts/*/userLists/*}" + } }, - "pairIdCount": { - "type": "int64", - "id": 2 + { + "(google.api.method_signature)": "name" } - } + ] } } }, - "MatchRateRange": { - "values": { - "MATCH_RATE_RANGE_UNKNOWN": 0, - "MATCH_RATE_RANGE_NOT_ELIGIBLE": 1, - "MATCH_RATE_RANGE_LESS_THAN_20": 2, - "MATCH_RATE_RANGE_20_TO_30": 3, - "MATCH_RATE_RANGE_31_TO_40": 4, - "MATCH_RATE_RANGE_41_TO_50": 5, - "MATCH_RATE_RANGE_51_TO_60": 6, - "MATCH_RATE_RANGE_61_TO_70": 7, - "MATCH_RATE_RANGE_71_TO_80": 8, - "MATCH_RATE_RANGE_81_TO_90": 9, - "MATCH_RATE_RANGE_91_TO_100": 10 - } - }, - "ErrorInfo": { + "GetUserListRequest": { "fields": { - "errorCounts": { - "rule": "repeated", - "type": "ErrorCount", - "id": 1 + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "datamanager.googleapis.com/UserList" + } } } }, - "ErrorCount": { + "ListUserListsRequest": { "fields": { - "recordCount": { - "type": "int64", - "id": 1 + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/UserList" + } }, - "reason": { - "type": "ProcessingErrorReason", - "id": 2 + "pageSize": { + "type": "int32", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageToken": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "filter": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } } } }, - "WarningInfo": { + "ListUserListsResponse": { "fields": { - "warningCounts": { + "userLists": { "rule": "repeated", - "type": "WarningCount", + "type": "UserList", "id": 1 + }, + "nextPageToken": { + "type": "string", + "id": 2 } } }, - "WarningCount": { + "CreateUserListRequest": { "fields": { - "recordCount": { - "type": "int64", - "id": 1 + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "datamanager.googleapis.com/UserList" + } }, - "reason": { - "type": "ProcessingWarningReason", - "id": 2 + "userList": { + "type": "UserList", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "validateOnly": { + "type": "bool", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } } } }, - "ProcessingErrorReason": { - "values": { - "PROCESSING_ERROR_REASON_UNSPECIFIED": 0, - "PROCESSING_ERROR_REASON_INVALID_CUSTOM_VARIABLE": 1, - "PROCESSING_ERROR_REASON_CUSTOM_VARIABLE_NOT_ENABLED": 2, - "PROCESSING_ERROR_REASON_EVENT_TOO_OLD": 3, - "PROCESSING_ERROR_REASON_DENIED_CONSENT": 4, - "PROCESSING_ERROR_REASON_NO_CONSENT": 5, - "PROCESSING_ERROR_REASON_UNKNOWN_CONSENT": 6, - "PROCESSING_ERROR_REASON_DUPLICATE_GCLID": 7, - "PROCESSING_ERROR_REASON_DUPLICATE_TRANSACTION_ID": 8, - "PROCESSING_ERROR_REASON_INVALID_GBRAID": 9, - "PROCESSING_ERROR_REASON_INVALID_GCLID": 10, - "PROCESSING_ERROR_REASON_INVALID_MERCHANT_ID": 11, - "PROCESSING_ERROR_REASON_INVALID_WBRAID": 12, - "PROCESSING_ERROR_REASON_INTERNAL_ERROR": 13, - "PROCESSING_ERROR_REASON_DESTINATION_ACCOUNT_ENHANCED_CONVERSIONS_TERMS_NOT_SIGNED": 14, - "PROCESSING_ERROR_REASON_INVALID_EVENT": 15, - "PROCESSING_ERROR_REASON_INSUFFICIENT_MATCHED_TRANSACTIONS": 16, - "PROCESSING_ERROR_REASON_INSUFFICIENT_TRANSACTIONS": 17, - "PROCESSING_ERROR_REASON_INVALID_FORMAT": 18, - "PROCESSING_ERROR_REASON_DECRYPTION_ERROR": 19, - "PROCESSING_ERROR_REASON_DEK_DECRYPTION_ERROR": 20, - "PROCESSING_ERROR_REASON_INVALID_WIP": 21, - "PROCESSING_ERROR_REASON_INVALID_KEK": 22, - "PROCESSING_ERROR_REASON_WIP_AUTH_FAILED": 23, - "PROCESSING_ERROR_REASON_KEK_PERMISSION_DENIED": 24, - "PROCESSING_ERROR_REASON_AWS_AUTH_FAILED": 27, - "PROCESSING_ERROR_REASON_USER_IDENTIFIER_DECRYPTION_ERROR": 25, - "PROCESSING_ERROR_OPERATING_ACCOUNT_MISMATCH_FOR_AD_IDENTIFIER": 26 - } - }, - "ProcessingWarningReason": { - "values": { - "PROCESSING_WARNING_REASON_UNSPECIFIED": 0, - "PROCESSING_WARNING_REASON_KEK_PERMISSION_DENIED": 1, - "PROCESSING_WARNING_REASON_DEK_DECRYPTION_ERROR": 2, - "PROCESSING_WARNING_REASON_DECRYPTION_ERROR": 3, - "PROCESSING_WARNING_REASON_WIP_AUTH_FAILED": 4, - "PROCESSING_WARNING_REASON_INVALID_WIP": 5, - "PROCESSING_WARNING_REASON_INVALID_KEK": 6, - "PROCESSING_WARNING_REASON_USER_IDENTIFIER_DECRYPTION_ERROR": 7, - "PROCESSING_WARNING_REASON_INTERNAL_ERROR": 8, - "PROCESSING_WARNING_REASON_AWS_AUTH_FAILED": 9 - } - }, - "TermsOfService": { + "UpdateUserListRequest": { "fields": { - "customerMatchTermsOfServiceStatus": { - "type": "TermsOfServiceStatus", + "userList": { + "type": "UserList", "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "google.protobuf.FieldMask", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "validateOnly": { + "type": "bool", + "id": 3, "options": { "(google.api.field_behavior)": "OPTIONAL" } } } }, - "TermsOfServiceStatus": { - "values": { - "TERMS_OF_SERVICE_STATUS_UNSPECIFIED": 0, - "ACCEPTED": 1, - "REJECTED": 2 + "DeleteUserListRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "datamanager.googleapis.com/UserList" + } + }, + "validateOnly": { + "type": "bool", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } } } } @@ -1457,6 +3631,83 @@ "IDENTIFIER": 8 } }, + "resourceReference": { + "type": "google.api.ResourceReference", + "id": 1055, + "extend": "google.protobuf.FieldOptions" + }, + "resourceDefinition": { + "rule": "repeated", + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.FileOptions" + }, + "resource": { + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.MessageOptions" + }, + "ResourceDescriptor": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "pattern": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "nameField": { + "type": "string", + "id": 3 + }, + "history": { + "type": "History", + "id": 4 + }, + "plural": { + "type": "string", + "id": 5 + }, + "singular": { + "type": "string", + "id": 6 + }, + "style": { + "rule": "repeated", + "type": "Style", + "id": 10 + } + }, + "nested": { + "History": { + "values": { + "HISTORY_UNSPECIFIED": 0, + "ORIGINALLY_SINGLE_PATTERN": 1, + "FUTURE_MULTI_PATTERN": 2 + } + }, + "Style": { + "values": { + "STYLE_UNSPECIFIED": 0, + "DECLARATIVE_FRIENDLY": 1 + } + } + } + }, + "ResourceReference": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "childType": { + "type": "string", + "id": 2 + } + } + }, "http": { "type": "HttpRule", "id": 72295728, @@ -3184,6 +5435,18 @@ "id": 2 } } + }, + "Empty": { + "fields": {} + }, + "FieldMask": { + "fields": { + "paths": { + "rule": "repeated", + "type": "string", + "id": 1 + } + } } } } diff --git a/packages/google-ads-datamanager/samples/generated/v1/marketing_data_insights_service.retrieve_insights.js b/packages/google-ads-datamanager/samples/generated/v1/marketing_data_insights_service.retrieve_insights.js new file mode 100644 index 00000000000..ca47194e9a5 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/marketing_data_insights_service.retrieve_insights.js @@ -0,0 +1,72 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent, baseline, userListId) { + // [START datamanager_v1_generated_MarketingDataInsightsService_RetrieveInsights_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The parent account that owns the user list. + * Format: `accountTypes/{account_type}/accounts/{account}` + */ + // const parent = 'abc123' + /** + * Required. Baseline for the insights requested. + */ + // const baseline = {} + /** + * Required. The user list ID for which insights are requested. + */ + // const userListId = 'abc123' + + // Imports the Datamanager library + const {MarketingDataInsightsServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new MarketingDataInsightsServiceClient(); + + async function callRetrieveInsights() { + // Construct request + const request = { + parent, + baseline, + userListId, + }; + + // Run request + const response = await datamanagerClient.retrieveInsights(request); + console.log(response); + } + + callRetrieveInsights(); + // [END datamanager_v1_generated_MarketingDataInsightsService_RetrieveInsights_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.create_partner_link.js b/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.create_partner_link.js new file mode 100644 index 00000000000..86c8cb19ea7 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.create_partner_link.js @@ -0,0 +1,67 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent, partnerLink) { + // [START datamanager_v1_generated_PartnerLinkService_CreatePartnerLink_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The parent, which owns this collection of partner links. + * Format: accountTypes/{account_type}/accounts/{account} + */ + // const parent = 'abc123' + /** + * Required. The partner link to create. + */ + // const partnerLink = {} + + // Imports the Datamanager library + const {PartnerLinkServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new PartnerLinkServiceClient(); + + async function callCreatePartnerLink() { + // Construct request + const request = { + parent, + partnerLink, + }; + + // Run request + const response = await datamanagerClient.createPartnerLink(request); + console.log(response); + } + + callCreatePartnerLink(); + // [END datamanager_v1_generated_PartnerLinkService_CreatePartnerLink_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.delete_partner_link.js b/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.delete_partner_link.js new file mode 100644 index 00000000000..10d70ee0f16 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.delete_partner_link.js @@ -0,0 +1,63 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START datamanager_v1_generated_PartnerLinkService_DeletePartnerLink_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The resource name of the partner link to delete. + * Format: + * accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link} + */ + // const name = 'abc123' + + // Imports the Datamanager library + const {PartnerLinkServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new PartnerLinkServiceClient(); + + async function callDeletePartnerLink() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await datamanagerClient.deletePartnerLink(request); + console.log(response); + } + + callDeletePartnerLink(); + // [END datamanager_v1_generated_PartnerLinkService_DeletePartnerLink_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.search_partner_links.js b/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.search_partner_links.js new file mode 100644 index 00000000000..8ef0b9dbaa5 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/partner_link_service.search_partner_links.js @@ -0,0 +1,99 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent) { + // [START datamanager_v1_generated_PartnerLinkService_SearchPartnerLinks_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. Account to search for partner links. If no `filter` is specified, + * all partner links where this account is either the `owning_account` or + * `partner_account` are returned. + * Format: `accountTypes/{account_type}/accounts/{account}` + */ + // const parent = 'abc123' + /** + * The maximum number of partner links to return. The service may return + * fewer than this value. + * If unspecified, at most 10 partner links will be returned. + * The maximum value is 100; values above 100 will be coerced to 100. + */ + // const pageSize = 1234 + /** + * A page token, received from a previous `SearchPartnerLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `SearchPartnerLinks` + * must match the call that provided the page token. + */ + // const pageToken = 'abc123' + /** + * Optional. A filter string (//google.aip.dev/160). All fields need to be on + * the left hand side of each condition (for example: `partner_link_id = + * 123456789`). + * Supported operations: + * - `AND` + * - `=` + * - `!=` + * Supported fields: + * - `partner_link_id` + * - `owning_account.account_type` + * - `owning_account.account_id` + * - `partner_account.account_type` + * - `partner_account.account_id` + * Example: + * `owning_account.account_type = "GOOGLE_ADS" OR partner_account.account_id = + * 987654321` + */ + // const filter = 'abc123' + + // Imports the Datamanager library + const {PartnerLinkServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new PartnerLinkServiceClient(); + + async function callSearchPartnerLinks() { + // Construct request + const request = { + parent, + }; + + // Run request + const iterable = datamanagerClient.searchPartnerLinksAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callSearchPartnerLinks(); + // [END datamanager_v1_generated_PartnerLinkService_SearchPartnerLinks_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json b/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json index 18c375ea831..08c06e3ea9f 100644 --- a/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json +++ b/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json @@ -230,6 +230,834 @@ } } } + }, + { + "regionTag": "datamanager_v1_generated_MarketingDataInsightsService_RetrieveInsights_async", + "title": "IngestionService retrieveInsights Sample", + "origin": "API_DEFINITION", + "description": " Retrieves marketing data insights for a given user list. This feature is only available to data partners. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "marketing_data_insights_service.retrieve_insights.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 64, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "RetrieveInsights", + "fullName": "google.ads.datamanager.v1.MarketingDataInsightsService.RetrieveInsights", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "baseline", + "type": ".google.ads.datamanager.v1.Baseline" + }, + { + "name": "user_list_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.RetrieveInsightsResponse", + "client": { + "shortName": "MarketingDataInsightsServiceClient", + "fullName": "google.ads.datamanager.v1.MarketingDataInsightsServiceClient" + }, + "method": { + "shortName": "RetrieveInsights", + "fullName": "google.ads.datamanager.v1.MarketingDataInsightsService.RetrieveInsights", + "service": { + "shortName": "MarketingDataInsightsService", + "fullName": "google.ads.datamanager.v1.MarketingDataInsightsService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_PartnerLinkService_CreatePartnerLink_async", + "title": "IngestionService createPartnerLink Sample", + "origin": "API_DEFINITION", + "description": " Creates a partner link for the given account. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "partner_link_service.create_partner_link.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreatePartnerLink", + "fullName": "google.ads.datamanager.v1.PartnerLinkService.CreatePartnerLink", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "partner_link", + "type": ".google.ads.datamanager.v1.PartnerLink" + } + ], + "resultType": ".google.ads.datamanager.v1.PartnerLink", + "client": { + "shortName": "PartnerLinkServiceClient", + "fullName": "google.ads.datamanager.v1.PartnerLinkServiceClient" + }, + "method": { + "shortName": "CreatePartnerLink", + "fullName": "google.ads.datamanager.v1.PartnerLinkService.CreatePartnerLink", + "service": { + "shortName": "PartnerLinkService", + "fullName": "google.ads.datamanager.v1.PartnerLinkService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_PartnerLinkService_DeletePartnerLink_async", + "title": "IngestionService deletePartnerLink Sample", + "origin": "API_DEFINITION", + "description": " Deletes a partner link for the given account. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "partner_link_service.delete_partner_link.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 55, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeletePartnerLink", + "fullName": "google.ads.datamanager.v1.PartnerLinkService.DeletePartnerLink", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "PartnerLinkServiceClient", + "fullName": "google.ads.datamanager.v1.PartnerLinkServiceClient" + }, + "method": { + "shortName": "DeletePartnerLink", + "fullName": "google.ads.datamanager.v1.PartnerLinkService.DeletePartnerLink", + "service": { + "shortName": "PartnerLinkService", + "fullName": "google.ads.datamanager.v1.PartnerLinkService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_PartnerLinkService_SearchPartnerLinks_async", + "title": "IngestionService searchPartnerLinks Sample", + "origin": "API_DEFINITION", + "description": " Searches for all partner links to and from a given account. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "partner_link_service.search_partner_links.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 91, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "SearchPartnerLinks", + "fullName": "google.ads.datamanager.v1.PartnerLinkService.SearchPartnerLinks", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "filter", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.SearchPartnerLinksResponse", + "client": { + "shortName": "PartnerLinkServiceClient", + "fullName": "google.ads.datamanager.v1.PartnerLinkServiceClient" + }, + "method": { + "shortName": "SearchPartnerLinks", + "fullName": "google.ads.datamanager.v1.PartnerLinkService.SearchPartnerLinks", + "service": { + "shortName": "PartnerLinkService", + "fullName": "google.ads.datamanager.v1.PartnerLinkService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListDirectLicenseService_CreateUserListDirectLicense_async", + "title": "IngestionService createUserListDirectLicense Sample", + "origin": "API_DEFINITION", + "description": " Creates a user list direct license. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_direct_license_service.create_user_list_direct_license.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateUserListDirectLicense", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService.CreateUserListDirectLicense", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "user_list_direct_license", + "type": ".google.ads.datamanager.v1.UserListDirectLicense" + } + ], + "resultType": ".google.ads.datamanager.v1.UserListDirectLicense", + "client": { + "shortName": "UserListDirectLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseServiceClient" + }, + "method": { + "shortName": "CreateUserListDirectLicense", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService.CreateUserListDirectLicense", + "service": { + "shortName": "UserListDirectLicenseService", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListDirectLicenseService_GetUserListDirectLicense_async", + "title": "IngestionService getUserListDirectLicense Sample", + "origin": "API_DEFINITION", + "description": " Retrieves a user list direct license. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_direct_license_service.get_user_list_direct_license.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 53, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetUserListDirectLicense", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService.GetUserListDirectLicense", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.UserListDirectLicense", + "client": { + "shortName": "UserListDirectLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseServiceClient" + }, + "method": { + "shortName": "GetUserListDirectLicense", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService.GetUserListDirectLicense", + "service": { + "shortName": "UserListDirectLicenseService", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListDirectLicenseService_UpdateUserListDirectLicense_async", + "title": "IngestionService updateUserListDirectLicense Sample", + "origin": "API_DEFINITION", + "description": " Updates a user list direct license. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_direct_license_service.update_user_list_direct_license.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateUserListDirectLicense", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService.UpdateUserListDirectLicense", + "async": true, + "parameters": [ + { + "name": "user_list_direct_license", + "type": ".google.ads.datamanager.v1.UserListDirectLicense" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.ads.datamanager.v1.UserListDirectLicense", + "client": { + "shortName": "UserListDirectLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseServiceClient" + }, + "method": { + "shortName": "UpdateUserListDirectLicense", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService.UpdateUserListDirectLicense", + "service": { + "shortName": "UserListDirectLicenseService", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListDirectLicenseService_ListUserListDirectLicenses_async", + "title": "IngestionService listUserListDirectLicenses Sample", + "origin": "API_DEFINITION", + "description": " Lists all user list direct licenses owned by the parent account. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_direct_license_service.list_user_list_direct_licenses.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 90, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListUserListDirectLicenses", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService.ListUserListDirectLicenses", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.ListUserListDirectLicensesResponse", + "client": { + "shortName": "UserListDirectLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseServiceClient" + }, + "method": { + "shortName": "ListUserListDirectLicenses", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService.ListUserListDirectLicenses", + "service": { + "shortName": "UserListDirectLicenseService", + "fullName": "google.ads.datamanager.v1.UserListDirectLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListGlobalLicenseService_CreateUserListGlobalLicense_async", + "title": "IngestionService createUserListGlobalLicense Sample", + "origin": "API_DEFINITION", + "description": " Creates a user list global license. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_global_license_service.create_user_list_global_license.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateUserListGlobalLicense", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.CreateUserListGlobalLicense", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "user_list_global_license", + "type": ".google.ads.datamanager.v1.UserListGlobalLicense" + } + ], + "resultType": ".google.ads.datamanager.v1.UserListGlobalLicense", + "client": { + "shortName": "UserListGlobalLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseServiceClient" + }, + "method": { + "shortName": "CreateUserListGlobalLicense", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.CreateUserListGlobalLicense", + "service": { + "shortName": "UserListGlobalLicenseService", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListGlobalLicenseService_UpdateUserListGlobalLicense_async", + "title": "IngestionService updateUserListGlobalLicense Sample", + "origin": "API_DEFINITION", + "description": " Updates a user list global license. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_global_license_service.update_user_list_global_license.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateUserListGlobalLicense", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.UpdateUserListGlobalLicense", + "async": true, + "parameters": [ + { + "name": "user_list_global_license", + "type": ".google.ads.datamanager.v1.UserListGlobalLicense" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.ads.datamanager.v1.UserListGlobalLicense", + "client": { + "shortName": "UserListGlobalLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseServiceClient" + }, + "method": { + "shortName": "UpdateUserListGlobalLicense", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.UpdateUserListGlobalLicense", + "service": { + "shortName": "UserListGlobalLicenseService", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListGlobalLicenseService_GetUserListGlobalLicense_async", + "title": "IngestionService getUserListGlobalLicense Sample", + "origin": "API_DEFINITION", + "description": " Retrieves a user list global license. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_global_license_service.get_user_list_global_license.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 53, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetUserListGlobalLicense", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.GetUserListGlobalLicense", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.UserListGlobalLicense", + "client": { + "shortName": "UserListGlobalLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseServiceClient" + }, + "method": { + "shortName": "GetUserListGlobalLicense", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.GetUserListGlobalLicense", + "service": { + "shortName": "UserListGlobalLicenseService", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenses_async", + "title": "IngestionService listUserListGlobalLicenses Sample", + "origin": "API_DEFINITION", + "description": " Lists all user list global licenses owned by the parent account. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_global_license_service.list_user_list_global_licenses.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 90, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListUserListGlobalLicenses", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.ListUserListGlobalLicenses", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.ListUserListGlobalLicensesResponse", + "client": { + "shortName": "UserListGlobalLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseServiceClient" + }, + "method": { + "shortName": "ListUserListGlobalLicenses", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.ListUserListGlobalLicenses", + "service": { + "shortName": "UserListGlobalLicenseService", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenseCustomerInfos_async", + "title": "IngestionService listUserListGlobalLicenseCustomerInfos Sample", + "origin": "API_DEFINITION", + "description": " Lists all customer info for a user list global license. This feature is only available to data partners.", + "canonical": true, + "file": "user_list_global_license_service.list_user_list_global_license_customer_infos.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 94, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListUserListGlobalLicenseCustomerInfos", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.ListUserListGlobalLicenseCustomerInfos", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosResponse", + "client": { + "shortName": "UserListGlobalLicenseServiceClient", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseServiceClient" + }, + "method": { + "shortName": "ListUserListGlobalLicenseCustomerInfos", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService.ListUserListGlobalLicenseCustomerInfos", + "service": { + "shortName": "UserListGlobalLicenseService", + "fullName": "google.ads.datamanager.v1.UserListGlobalLicenseService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListService_GetUserList_async", + "title": "IngestionService getUserList Sample", + "origin": "API_DEFINITION", + "description": " Gets a UserList. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "user_list_service.get_user_list.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 55, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetUserList", + "fullName": "google.ads.datamanager.v1.UserListService.GetUserList", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.UserList", + "client": { + "shortName": "UserListServiceClient", + "fullName": "google.ads.datamanager.v1.UserListServiceClient" + }, + "method": { + "shortName": "GetUserList", + "fullName": "google.ads.datamanager.v1.UserListService.GetUserList", + "service": { + "shortName": "UserListService", + "fullName": "google.ads.datamanager.v1.UserListService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListService_ListUserLists_async", + "title": "IngestionService listUserLists Sample", + "origin": "API_DEFINITION", + "description": " Lists UserLists. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "user_list_service.list_user_lists.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 93, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListUserLists", + "fullName": "google.ads.datamanager.v1.UserListService.ListUserLists", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "filter", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.ads.datamanager.v1.ListUserListsResponse", + "client": { + "shortName": "UserListServiceClient", + "fullName": "google.ads.datamanager.v1.UserListServiceClient" + }, + "method": { + "shortName": "ListUserLists", + "fullName": "google.ads.datamanager.v1.UserListService.ListUserLists", + "service": { + "shortName": "UserListService", + "fullName": "google.ads.datamanager.v1.UserListService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListService_CreateUserList_async", + "title": "IngestionService createUserList Sample", + "origin": "API_DEFINITION", + "description": " Creates a UserList. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "user_list_service.create_user_list.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateUserList", + "fullName": "google.ads.datamanager.v1.UserListService.CreateUserList", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "user_list", + "type": ".google.ads.datamanager.v1.UserList" + }, + { + "name": "validate_only", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.ads.datamanager.v1.UserList", + "client": { + "shortName": "UserListServiceClient", + "fullName": "google.ads.datamanager.v1.UserListServiceClient" + }, + "method": { + "shortName": "CreateUserList", + "fullName": "google.ads.datamanager.v1.UserListService.CreateUserList", + "service": { + "shortName": "UserListService", + "fullName": "google.ads.datamanager.v1.UserListService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListService_UpdateUserList_async", + "title": "IngestionService updateUserList Sample", + "origin": "API_DEFINITION", + "description": " Updates a UserList. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "user_list_service.update_user_list.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 64, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateUserList", + "fullName": "google.ads.datamanager.v1.UserListService.UpdateUserList", + "async": true, + "parameters": [ + { + "name": "user_list", + "type": ".google.ads.datamanager.v1.UserList" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + }, + { + "name": "validate_only", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.ads.datamanager.v1.UserList", + "client": { + "shortName": "UserListServiceClient", + "fullName": "google.ads.datamanager.v1.UserListServiceClient" + }, + "method": { + "shortName": "UpdateUserList", + "fullName": "google.ads.datamanager.v1.UserListService.UpdateUserList", + "service": { + "shortName": "UserListService", + "fullName": "google.ads.datamanager.v1.UserListService" + } + } + } + }, + { + "regionTag": "datamanager_v1_generated_UserListService_DeleteUserList_async", + "title": "IngestionService deleteUserList Sample", + "origin": "API_DEFINITION", + "description": " Deletes a UserList. Authorization Headers: This method supports the following optional headers to define how the API authorizes access for the request: * `login-account`: (Optional) The resource name of the account where the Google Account of the credentials is a user. If not set, defaults to the account of the request. Format: `accountTypes/{loginAccountType}/accounts/{loginAccountId}` * `linked-account`: (Optional) The resource name of the account with an established product link to the `login-account`. Format: `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}`", + "canonical": true, + "file": "user_list_service.delete_user_list.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeleteUserList", + "fullName": "google.ads.datamanager.v1.UserListService.DeleteUserList", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "validate_only", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "UserListServiceClient", + "fullName": "google.ads.datamanager.v1.UserListServiceClient" + }, + "method": { + "shortName": "DeleteUserList", + "fullName": "google.ads.datamanager.v1.UserListService.DeleteUserList", + "service": { + "shortName": "UserListService", + "fullName": "google.ads.datamanager.v1.UserListService" + } + } + } } ] } diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.create_user_list_direct_license.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.create_user_list_direct_license.js new file mode 100644 index 00000000000..4b513d1787a --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.create_user_list_direct_license.js @@ -0,0 +1,67 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent, userListDirectLicense) { + // [START datamanager_v1_generated_UserListDirectLicenseService_CreateUserListDirectLicense_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The account that owns the user list being licensed. Should be in + * the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + */ + // const parent = 'abc123' + /** + * Required. The user list direct license to create. + */ + // const userListDirectLicense = {} + + // Imports the Datamanager library + const {UserListDirectLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListDirectLicenseServiceClient(); + + async function callCreateUserListDirectLicense() { + // Construct request + const request = { + parent, + userListDirectLicense, + }; + + // Run request + const response = await datamanagerClient.createUserListDirectLicense(request); + console.log(response); + } + + callCreateUserListDirectLicense(); + // [END datamanager_v1_generated_UserListDirectLicenseService_CreateUserListDirectLicense_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.get_user_list_direct_license.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.get_user_list_direct_license.js new file mode 100644 index 00000000000..0e980721de4 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.get_user_list_direct_license.js @@ -0,0 +1,61 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START datamanager_v1_generated_UserListDirectLicenseService_GetUserListDirectLicense_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The resource name of the user list direct license. + */ + // const name = 'abc123' + + // Imports the Datamanager library + const {UserListDirectLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListDirectLicenseServiceClient(); + + async function callGetUserListDirectLicense() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await datamanagerClient.getUserListDirectLicense(request); + console.log(response); + } + + callGetUserListDirectLicense(); + // [END datamanager_v1_generated_UserListDirectLicenseService_GetUserListDirectLicense_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.list_user_list_direct_licenses.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.list_user_list_direct_licenses.js new file mode 100644 index 00000000000..53966c05ebd --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.list_user_list_direct_licenses.js @@ -0,0 +1,98 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent) { + // [START datamanager_v1_generated_UserListDirectLicenseService_ListUserListDirectLicenses_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + */ + // const parent = 'abc123' + /** + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * **Supported Operations:** + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * **Unsupported Fields:** + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + */ + // const filter = 'abc123' + /** + * Optional. The maximum number of licenses to return per page. The service + * may return fewer than this value. If unspecified, at most 50 licenses will + * be returned. The maximum value is 1000; values above 1000 will be coerced + * to 1000. + */ + // const pageSize = 1234 + /** + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + */ + // const pageToken = 'abc123' + + // Imports the Datamanager library + const {UserListDirectLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListDirectLicenseServiceClient(); + + async function callListUserListDirectLicenses() { + // Construct request + const request = { + parent, + }; + + // Run request + const iterable = datamanagerClient.listUserListDirectLicensesAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callListUserListDirectLicenses(); + // [END datamanager_v1_generated_UserListDirectLicenseService_ListUserListDirectLicenses_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.update_user_list_direct_license.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.update_user_list_direct_license.js new file mode 100644 index 00000000000..52d487d06c7 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_direct_license_service.update_user_list_direct_license.js @@ -0,0 +1,67 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(userListDirectLicense) { + // [START datamanager_v1_generated_UserListDirectLicenseService_UpdateUserListDirectLicense_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The licenses' `name` field is used to identify the license to + * update. + */ + // const userListDirectLicense = {} + /** + * Optional. The list of fields to update. The special character `*` is not + * supported and an `INVALID_UPDATE_MASK` error will be thrown if used. + */ + // const updateMask = {} + + // Imports the Datamanager library + const {UserListDirectLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListDirectLicenseServiceClient(); + + async function callUpdateUserListDirectLicense() { + // Construct request + const request = { + userListDirectLicense, + }; + + // Run request + const response = await datamanagerClient.updateUserListDirectLicense(request); + console.log(response); + } + + callUpdateUserListDirectLicense(); + // [END datamanager_v1_generated_UserListDirectLicenseService_UpdateUserListDirectLicense_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.create_user_list_global_license.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.create_user_list_global_license.js new file mode 100644 index 00000000000..7948a9ae927 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.create_user_list_global_license.js @@ -0,0 +1,67 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent, userListGlobalLicense) { + // [START datamanager_v1_generated_UserListGlobalLicenseService_CreateUserListGlobalLicense_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The account that owns the user list being licensed. Should be in + * the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + */ + // const parent = 'abc123' + /** + * Required. The user list global license to create. + */ + // const userListGlobalLicense = {} + + // Imports the Datamanager library + const {UserListGlobalLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListGlobalLicenseServiceClient(); + + async function callCreateUserListGlobalLicense() { + // Construct request + const request = { + parent, + userListGlobalLicense, + }; + + // Run request + const response = await datamanagerClient.createUserListGlobalLicense(request); + console.log(response); + } + + callCreateUserListGlobalLicense(); + // [END datamanager_v1_generated_UserListGlobalLicenseService_CreateUserListGlobalLicense_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.get_user_list_global_license.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.get_user_list_global_license.js new file mode 100644 index 00000000000..a8005ccbf8a --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.get_user_list_global_license.js @@ -0,0 +1,61 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START datamanager_v1_generated_UserListGlobalLicenseService_GetUserListGlobalLicense_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The resource name of the user list global license. + */ + // const name = 'abc123' + + // Imports the Datamanager library + const {UserListGlobalLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListGlobalLicenseServiceClient(); + + async function callGetUserListGlobalLicense() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await datamanagerClient.getUserListGlobalLicense(request); + console.log(response); + } + + callGetUserListGlobalLicense(); + // [END datamanager_v1_generated_UserListGlobalLicenseService_GetUserListGlobalLicense_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.list_user_list_global_license_customer_infos.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.list_user_list_global_license_customer_infos.js new file mode 100644 index 00000000000..b39cfce6a77 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.list_user_list_global_license_customer_infos.js @@ -0,0 +1,102 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent) { + // [START datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenseCustomerInfos_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The global license whose customer info are being queried. Should + * be in the format + * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. + * To list all global license customer info under an account, replace the user + * list global license id with a '-' (for example, + * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) + */ + // const parent = 'abc123' + /** + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * **Supported Operations:** + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * **Unsupported Fields:** + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + */ + // const filter = 'abc123' + /** + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + */ + // const pageSize = 1234 + /** + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + */ + // const pageToken = 'abc123' + + // Imports the Datamanager library + const {UserListGlobalLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListGlobalLicenseServiceClient(); + + async function callListUserListGlobalLicenseCustomerInfos() { + // Construct request + const request = { + parent, + }; + + // Run request + const iterable = datamanagerClient.listUserListGlobalLicenseCustomerInfosAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callListUserListGlobalLicenseCustomerInfos(); + // [END datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenseCustomerInfos_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.list_user_list_global_licenses.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.list_user_list_global_licenses.js new file mode 100644 index 00000000000..183e342fedd --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.list_user_list_global_licenses.js @@ -0,0 +1,98 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent) { + // [START datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenses_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + */ + // const parent = 'abc123' + /** + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * **Supported Operations:** + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * **Unsupported Fields:** + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + */ + // const filter = 'abc123' + /** + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + */ + // const pageSize = 1234 + /** + * Optional. A page token, received from a previous + * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent + * page. + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + */ + // const pageToken = 'abc123' + + // Imports the Datamanager library + const {UserListGlobalLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListGlobalLicenseServiceClient(); + + async function callListUserListGlobalLicenses() { + // Construct request + const request = { + parent, + }; + + // Run request + const iterable = datamanagerClient.listUserListGlobalLicensesAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callListUserListGlobalLicenses(); + // [END datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenses_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.update_user_list_global_license.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.update_user_list_global_license.js new file mode 100644 index 00000000000..f20d08a3ebc --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_global_license_service.update_user_list_global_license.js @@ -0,0 +1,67 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(userListGlobalLicense) { + // [START datamanager_v1_generated_UserListGlobalLicenseService_UpdateUserListGlobalLicense_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The licenses' `name` field is used to identify the license to + * update. + */ + // const userListGlobalLicense = {} + /** + * Optional. The list of fields to update. The special character `*` is not + * supported and an `INVALID_UPDATE_MASK` error will be thrown if used. + */ + // const updateMask = {} + + // Imports the Datamanager library + const {UserListGlobalLicenseServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListGlobalLicenseServiceClient(); + + async function callUpdateUserListGlobalLicense() { + // Construct request + const request = { + userListGlobalLicense, + }; + + // Run request + const response = await datamanagerClient.updateUserListGlobalLicense(request); + console.log(response); + } + + callUpdateUserListGlobalLicense(); + // [END datamanager_v1_generated_UserListGlobalLicenseService_UpdateUserListGlobalLicense_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_service.create_user_list.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.create_user_list.js new file mode 100644 index 00000000000..2be25ee4ba0 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.create_user_list.js @@ -0,0 +1,71 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent, userList) { + // [START datamanager_v1_generated_UserListService_CreateUserList_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The parent account where this user list will be created. + * Format: accountTypes/{account_type}/accounts/{account} + */ + // const parent = 'abc123' + /** + * Required. The user list to create. + */ + // const userList = {} + /** + * Optional. If true, the request is validated but not executed. + */ + // const validateOnly = true + + // Imports the Datamanager library + const {UserListServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListServiceClient(); + + async function callCreateUserList() { + // Construct request + const request = { + parent, + userList, + }; + + // Run request + const response = await datamanagerClient.createUserList(request); + console.log(response); + } + + callCreateUserList(); + // [END datamanager_v1_generated_UserListService_CreateUserList_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_service.delete_user_list.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.delete_user_list.js new file mode 100644 index 00000000000..4b7516e670a --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.delete_user_list.js @@ -0,0 +1,67 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START datamanager_v1_generated_UserListService_DeleteUserList_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The name of the user list to delete. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + */ + // const name = 'abc123' + /** + * Optional. If true, the request is validated but not executed. + */ + // const validateOnly = true + + // Imports the Datamanager library + const {UserListServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListServiceClient(); + + async function callDeleteUserList() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await datamanagerClient.deleteUserList(request); + console.log(response); + } + + callDeleteUserList(); + // [END datamanager_v1_generated_UserListService_DeleteUserList_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_service.get_user_list.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.get_user_list.js new file mode 100644 index 00000000000..12fc66f37d0 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.get_user_list.js @@ -0,0 +1,63 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START datamanager_v1_generated_UserListService_GetUserList_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The resource name of the UserList to retrieve. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + */ + // const name = 'abc123' + + // Imports the Datamanager library + const {UserListServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListServiceClient(); + + async function callGetUserList() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await datamanagerClient.getUserList(request); + console.log(response); + } + + callGetUserList(); + // [END datamanager_v1_generated_UserListService_GetUserList_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_service.list_user_lists.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.list_user_lists.js new file mode 100644 index 00000000000..bf1639eae24 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.list_user_lists.js @@ -0,0 +1,101 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent) { + // [START datamanager_v1_generated_UserListService_ListUserLists_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The parent account which owns this collection of user lists. + * Format: accountTypes/{account_type}/accounts/{account} + */ + // const parent = 'abc123' + /** + * Optional. The maximum number of user lists to return. The service may + * return fewer than this value. If unspecified, at most 50 user lists will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + */ + // const pageSize = 1234 + /** + * Optional. A page token, received from a previous `ListUserLists` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListUserLists` must + * match the call that provided the page token. + */ + // const pageToken = 'abc123' + /** + * Optional. A filter string (//google.aip.dev/160). All fields need to be on + * the left hand side of each condition (for example: `display_name = "list + * 1"`). + * Supported operations: + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * - `:` (has) + * Supported fields: + * - `id` + * - `display_name` + * - `description` + * - `membership_status` + * - `integration_code` + * - `access_reason` + * - `ingested_user_list_info.upload_key_types` + */ + // const filter = 'abc123' + + // Imports the Datamanager library + const {UserListServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListServiceClient(); + + async function callListUserLists() { + // Construct request + const request = { + parent, + }; + + // Run request + const iterable = datamanagerClient.listUserListsAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callListUserLists(); + // [END datamanager_v1_generated_UserListService_ListUserLists_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/samples/generated/v1/user_list_service.update_user_list.js b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.update_user_list.js new file mode 100644 index 00000000000..8b4c2e01336 --- /dev/null +++ b/packages/google-ads-datamanager/samples/generated/v1/user_list_service.update_user_list.js @@ -0,0 +1,72 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(userList) { + // [START datamanager_v1_generated_UserListService_UpdateUserList_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The user list to update. + * The user list's `name` field is used to identify the user list to update. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + */ + // const userList = {} + /** + * Optional. The list of fields to update. + */ + // const updateMask = {} + /** + * Optional. If true, the request is validated but not executed. + */ + // const validateOnly = true + + // Imports the Datamanager library + const {UserListServiceClient} = require('@google-ads/datamanager').v1; + + // Instantiates a client + const datamanagerClient = new UserListServiceClient(); + + async function callUpdateUserList() { + // Construct request + const request = { + userList, + }; + + // Run request + const response = await datamanagerClient.updateUserList(request); + console.log(response); + } + + callUpdateUserList(); + // [END datamanager_v1_generated_UserListService_UpdateUserList_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-ads-datamanager/src/index.ts b/packages/google-ads-datamanager/src/index.ts index fa151fd1fe7..f2dc3b71128 100644 --- a/packages/google-ads-datamanager/src/index.ts +++ b/packages/google-ads-datamanager/src/index.ts @@ -20,8 +20,18 @@ import * as v1 from './v1'; const IngestionServiceClient = v1.IngestionServiceClient; type IngestionServiceClient = v1.IngestionServiceClient; +const MarketingDataInsightsServiceClient = v1.MarketingDataInsightsServiceClient; +type MarketingDataInsightsServiceClient = v1.MarketingDataInsightsServiceClient; +const PartnerLinkServiceClient = v1.PartnerLinkServiceClient; +type PartnerLinkServiceClient = v1.PartnerLinkServiceClient; +const UserListDirectLicenseServiceClient = v1.UserListDirectLicenseServiceClient; +type UserListDirectLicenseServiceClient = v1.UserListDirectLicenseServiceClient; +const UserListGlobalLicenseServiceClient = v1.UserListGlobalLicenseServiceClient; +type UserListGlobalLicenseServiceClient = v1.UserListGlobalLicenseServiceClient; +const UserListServiceClient = v1.UserListServiceClient; +type UserListServiceClient = v1.UserListServiceClient; -export {v1, IngestionServiceClient}; -export default {v1, IngestionServiceClient}; +export {v1, IngestionServiceClient, MarketingDataInsightsServiceClient, PartnerLinkServiceClient, UserListDirectLicenseServiceClient, UserListGlobalLicenseServiceClient, UserListServiceClient}; +export default {v1, IngestionServiceClient, MarketingDataInsightsServiceClient, PartnerLinkServiceClient, UserListDirectLicenseServiceClient, UserListGlobalLicenseServiceClient, UserListServiceClient}; import * as protos from '../protos/protos'; export {protos}; diff --git a/packages/google-ads-datamanager/src/v1/gapic_metadata.json b/packages/google-ads-datamanager/src/v1/gapic_metadata.json index 534830bfeb4..97528f86755 100644 --- a/packages/google-ads-datamanager/src/v1/gapic_metadata.json +++ b/packages/google-ads-datamanager/src/v1/gapic_metadata.json @@ -58,6 +58,276 @@ } } } + }, + "MarketingDataInsightsService": { + "clients": { + "grpc": { + "libraryClient": "MarketingDataInsightsServiceClient", + "rpcs": { + "RetrieveInsights": { + "methods": [ + "retrieveInsights" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "MarketingDataInsightsServiceClient", + "rpcs": { + "RetrieveInsights": { + "methods": [ + "retrieveInsights" + ] + } + } + } + } + }, + "PartnerLinkService": { + "clients": { + "grpc": { + "libraryClient": "PartnerLinkServiceClient", + "rpcs": { + "CreatePartnerLink": { + "methods": [ + "createPartnerLink" + ] + }, + "DeletePartnerLink": { + "methods": [ + "deletePartnerLink" + ] + }, + "SearchPartnerLinks": { + "methods": [ + "searchPartnerLinks", + "searchPartnerLinksStream", + "searchPartnerLinksAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "PartnerLinkServiceClient", + "rpcs": { + "CreatePartnerLink": { + "methods": [ + "createPartnerLink" + ] + }, + "DeletePartnerLink": { + "methods": [ + "deletePartnerLink" + ] + }, + "SearchPartnerLinks": { + "methods": [ + "searchPartnerLinks", + "searchPartnerLinksStream", + "searchPartnerLinksAsync" + ] + } + } + } + } + }, + "UserListDirectLicenseService": { + "clients": { + "grpc": { + "libraryClient": "UserListDirectLicenseServiceClient", + "rpcs": { + "CreateUserListDirectLicense": { + "methods": [ + "createUserListDirectLicense" + ] + }, + "GetUserListDirectLicense": { + "methods": [ + "getUserListDirectLicense" + ] + }, + "UpdateUserListDirectLicense": { + "methods": [ + "updateUserListDirectLicense" + ] + }, + "ListUserListDirectLicenses": { + "methods": [ + "listUserListDirectLicenses", + "listUserListDirectLicensesStream", + "listUserListDirectLicensesAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "UserListDirectLicenseServiceClient", + "rpcs": { + "CreateUserListDirectLicense": { + "methods": [ + "createUserListDirectLicense" + ] + }, + "GetUserListDirectLicense": { + "methods": [ + "getUserListDirectLicense" + ] + }, + "UpdateUserListDirectLicense": { + "methods": [ + "updateUserListDirectLicense" + ] + }, + "ListUserListDirectLicenses": { + "methods": [ + "listUserListDirectLicenses", + "listUserListDirectLicensesStream", + "listUserListDirectLicensesAsync" + ] + } + } + } + } + }, + "UserListGlobalLicenseService": { + "clients": { + "grpc": { + "libraryClient": "UserListGlobalLicenseServiceClient", + "rpcs": { + "CreateUserListGlobalLicense": { + "methods": [ + "createUserListGlobalLicense" + ] + }, + "UpdateUserListGlobalLicense": { + "methods": [ + "updateUserListGlobalLicense" + ] + }, + "GetUserListGlobalLicense": { + "methods": [ + "getUserListGlobalLicense" + ] + }, + "ListUserListGlobalLicenses": { + "methods": [ + "listUserListGlobalLicenses", + "listUserListGlobalLicensesStream", + "listUserListGlobalLicensesAsync" + ] + }, + "ListUserListGlobalLicenseCustomerInfos": { + "methods": [ + "listUserListGlobalLicenseCustomerInfos", + "listUserListGlobalLicenseCustomerInfosStream", + "listUserListGlobalLicenseCustomerInfosAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "UserListGlobalLicenseServiceClient", + "rpcs": { + "CreateUserListGlobalLicense": { + "methods": [ + "createUserListGlobalLicense" + ] + }, + "UpdateUserListGlobalLicense": { + "methods": [ + "updateUserListGlobalLicense" + ] + }, + "GetUserListGlobalLicense": { + "methods": [ + "getUserListGlobalLicense" + ] + }, + "ListUserListGlobalLicenses": { + "methods": [ + "listUserListGlobalLicenses", + "listUserListGlobalLicensesStream", + "listUserListGlobalLicensesAsync" + ] + }, + "ListUserListGlobalLicenseCustomerInfos": { + "methods": [ + "listUserListGlobalLicenseCustomerInfos", + "listUserListGlobalLicenseCustomerInfosStream", + "listUserListGlobalLicenseCustomerInfosAsync" + ] + } + } + } + } + }, + "UserListService": { + "clients": { + "grpc": { + "libraryClient": "UserListServiceClient", + "rpcs": { + "GetUserList": { + "methods": [ + "getUserList" + ] + }, + "CreateUserList": { + "methods": [ + "createUserList" + ] + }, + "UpdateUserList": { + "methods": [ + "updateUserList" + ] + }, + "DeleteUserList": { + "methods": [ + "deleteUserList" + ] + }, + "ListUserLists": { + "methods": [ + "listUserLists", + "listUserListsStream", + "listUserListsAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "UserListServiceClient", + "rpcs": { + "GetUserList": { + "methods": [ + "getUserList" + ] + }, + "CreateUserList": { + "methods": [ + "createUserList" + ] + }, + "UpdateUserList": { + "methods": [ + "updateUserList" + ] + }, + "DeleteUserList": { + "methods": [ + "deleteUserList" + ] + }, + "ListUserLists": { + "methods": [ + "listUserLists", + "listUserListsStream", + "listUserListsAsync" + ] + } + } + } + } } } } diff --git a/packages/google-ads-datamanager/src/v1/index.ts b/packages/google-ads-datamanager/src/v1/index.ts index 7b4fc264b59..b7d57ada5bc 100644 --- a/packages/google-ads-datamanager/src/v1/index.ts +++ b/packages/google-ads-datamanager/src/v1/index.ts @@ -17,3 +17,8 @@ // ** All changes to this file may be overwritten. ** export {IngestionServiceClient} from './ingestion_service_client'; +export {MarketingDataInsightsServiceClient} from './marketing_data_insights_service_client'; +export {PartnerLinkServiceClient} from './partner_link_service_client'; +export {UserListDirectLicenseServiceClient} from './user_list_direct_license_service_client'; +export {UserListGlobalLicenseServiceClient} from './user_list_global_license_service_client'; +export {UserListServiceClient} from './user_list_service_client'; diff --git a/packages/google-ads-datamanager/src/v1/ingestion_service_client.ts b/packages/google-ads-datamanager/src/v1/ingestion_service_client.ts index 54548f713a6..30ad66231cf 100644 --- a/packages/google-ads-datamanager/src/v1/ingestion_service_client.ts +++ b/packages/google-ads-datamanager/src/v1/ingestion_service_client.ts @@ -58,6 +58,7 @@ export class IngestionServiceClient { }; warn: (code: string, message: string, warnType?: string) => void; innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; ingestionServiceStub?: Promise<{[name: string]: Function}>; /** @@ -172,6 +173,27 @@ export class IngestionServiceClient { // Load the applicable protos. this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + partnerLinkPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + ), + userListPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + ), + userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + ), + userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' + ), + userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + ), + }; + // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( 'google.ads.datamanager.v1.IngestionService', gapicConfig as gax.ClientConfig, @@ -745,6 +767,267 @@ export class IngestionServiceClient { }); } + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified partnerLink resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} partner_link + * @returns {string} Resource name string. + */ + partnerLinkPath(accountType:string,account:string,partnerLink:string) { + return this.pathTemplates.partnerLinkPathTemplate.render({ + account_type: accountType, + account: account, + partner_link: partnerLink, + }); + } + + /** + * Parse the account_type from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + } + + /** + * Parse the account from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account. + */ + matchAccountFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + } + + /** + * Parse the partner_link from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the partner_link. + */ + matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + } + + /** + * Return a fully-qualified userList resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list + * @returns {string} Resource name string. + */ + userListPath(accountType:string,account:string,userList:string) { + return this.pathTemplates.userListPathTemplate.render({ + account_type: accountType, + account: account, + user_list: userList, + }); + } + + /** + * Parse the account_type from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + } + + /** + * Parse the account from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account; + } + + /** + * Parse the user_list from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the user_list. + */ + matchUserListFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + } + + /** + * Return a fully-qualified userListDirectLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_direct_license + * @returns {string} Resource name string. + */ + userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + return this.pathTemplates.userListDirectLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_direct_license: userListDirectLicense, + }); + } + + /** + * Parse the account_type from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + } + + /** + * Parse the account from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + } + + /** + * Parse the user_list_direct_license from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the user_list_direct_license. + */ + matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + } + + /** + * Return a fully-qualified userListGlobalLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @returns {string} Resource name string. + */ + userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + }); + } + + /** + * Parse the account_type from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + } + + /** + * Parse the account from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + } + + /** + * Return a fully-qualified userListGlobalLicenseCustomerInfo resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @param {string} license_customer_info + * @returns {string} Resource name string. + */ + userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }); + } + + /** + * Parse the account_type from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + } + + /** + * Parse the account from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + } + + /** + * Parse the license_customer_info from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the license_customer_info. + */ + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + } /** * Terminate the gRPC channel and close the client. diff --git a/packages/google-ads-datamanager/src/v1/ingestion_service_proto_list.json b/packages/google-ads-datamanager/src/v1/ingestion_service_proto_list.json index fe9dcc928fc..ec5cc61b87e 100644 --- a/packages/google-ads-datamanager/src/v1/ingestion_service_proto_list.json +++ b/packages/google-ads-datamanager/src/v1/ingestion_service_proto_list.json @@ -1,4 +1,5 @@ [ + "../../protos/google/ads/datamanager/v1/age_range.proto", "../../protos/google/ads/datamanager/v1/audience.proto", "../../protos/google/ads/datamanager/v1/cart_data.proto", "../../protos/google/ads/datamanager/v1/consent.proto", @@ -8,12 +9,26 @@ "../../protos/google/ads/datamanager/v1/error.proto", "../../protos/google/ads/datamanager/v1/event.proto", "../../protos/google/ads/datamanager/v1/experimental_field.proto", + "../../protos/google/ads/datamanager/v1/gender.proto", "../../protos/google/ads/datamanager/v1/ingestion_service.proto", + "../../protos/google/ads/datamanager/v1/insights_service.proto", "../../protos/google/ads/datamanager/v1/item_parameter.proto", "../../protos/google/ads/datamanager/v1/match_rate.proto", + "../../protos/google/ads/datamanager/v1/partner_link_service.proto", "../../protos/google/ads/datamanager/v1/processing_errors.proto", "../../protos/google/ads/datamanager/v1/request_status_per_destination.proto", "../../protos/google/ads/datamanager/v1/terms_of_service.proto", "../../protos/google/ads/datamanager/v1/user_data.proto", + "../../protos/google/ads/datamanager/v1/user_list.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_metrics.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_pricing.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_status.proto", + "../../protos/google/ads/datamanager/v1/user_list_service.proto", "../../protos/google/ads/datamanager/v1/user_properties.proto" ] diff --git a/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client.ts b/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client.ts new file mode 100644 index 00000000000..e2953da9aa4 --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client.ts @@ -0,0 +1,737 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; + +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/marketing_data_insights_service_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './marketing_data_insights_service_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Service to return insights on marketing data. + * + * This feature is only available to data partners. + * @class + * @memberof v1 + */ +export class MarketingDataInsightsServiceClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('datamanager'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + marketingDataInsightsServiceStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of MarketingDataInsightsServiceClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new MarketingDataInsightsServiceClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof MarketingDataInsightsServiceClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'datamanager.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = opts?.fallback ?? (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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + partnerLinkPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + ), + userListPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + ), + userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + ), + userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' + ), + userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.ads.datamanager.v1.MarketingDataInsightsService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.marketingDataInsightsServiceStub) { + return this.marketingDataInsightsServiceStub; + } + + // Put together the "service stub" for + // google.ads.datamanager.v1.MarketingDataInsightsService. + this.marketingDataInsightsServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.MarketingDataInsightsService') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ads.datamanager.v1.MarketingDataInsightsService, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const marketingDataInsightsServiceStubMethods = + ['retrieveInsights']; + for (const methodName of marketingDataInsightsServiceStubMethods) { + const callPromise = this.marketingDataInsightsServiceStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.marketingDataInsightsServiceStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/datamanager' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * Retrieves marketing data insights for a given user list. + * + * This feature is only available to data partners. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account that owns the user list. + * Format: `accountTypes/{account_type}/accounts/{account}` + * @param {google.ads.datamanager.v1.Baseline} request.baseline + * Required. Baseline for the insights requested. + * @param {string} request.userListId + * Required. The user list ID for which insights are requested. + * @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.ads.datamanager.v1.RetrieveInsightsResponse|RetrieveInsightsResponse}. + * 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/marketing_data_insights_service.retrieve_insights.js + * region_tag:datamanager_v1_generated_MarketingDataInsightsService_RetrieveInsights_async + */ + retrieveInsights( + request?: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|undefined, {}|undefined + ]>; + retrieveInsights( + request: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, + {}|null|undefined>): void; + retrieveInsights( + request: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, + {}|null|undefined>): void; + retrieveInsights( + request?: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('retrieveInsights request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('retrieveInsights response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.retrieveInsights(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|undefined, + {}|undefined + ]) => { + this._log.info('retrieveInsights response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified partnerLink resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} partner_link + * @returns {string} Resource name string. + */ + partnerLinkPath(accountType:string,account:string,partnerLink:string) { + return this.pathTemplates.partnerLinkPathTemplate.render({ + account_type: accountType, + account: account, + partner_link: partnerLink, + }); + } + + /** + * Parse the account_type from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + } + + /** + * Parse the account from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account. + */ + matchAccountFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + } + + /** + * Parse the partner_link from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the partner_link. + */ + matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + } + + /** + * Return a fully-qualified userList resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list + * @returns {string} Resource name string. + */ + userListPath(accountType:string,account:string,userList:string) { + return this.pathTemplates.userListPathTemplate.render({ + account_type: accountType, + account: account, + user_list: userList, + }); + } + + /** + * Parse the account_type from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + } + + /** + * Parse the account from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account; + } + + /** + * Parse the user_list from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the user_list. + */ + matchUserListFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + } + + /** + * Return a fully-qualified userListDirectLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_direct_license + * @returns {string} Resource name string. + */ + userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + return this.pathTemplates.userListDirectLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_direct_license: userListDirectLicense, + }); + } + + /** + * Parse the account_type from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + } + + /** + * Parse the account from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + } + + /** + * Parse the user_list_direct_license from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the user_list_direct_license. + */ + matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + } + + /** + * Return a fully-qualified userListGlobalLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @returns {string} Resource name string. + */ + userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + }); + } + + /** + * Parse the account_type from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + } + + /** + * Parse the account from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + } + + /** + * Return a fully-qualified userListGlobalLicenseCustomerInfo resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @param {string} license_customer_info + * @returns {string} Resource name string. + */ + userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }); + } + + /** + * Parse the account_type from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + } + + /** + * Parse the account from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + } + + /** + * Parse the license_customer_info from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the license_customer_info. + */ + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.marketingDataInsightsServiceStub && !this._terminated) { + return this.marketingDataInsightsServiceStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client_config.json b/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client_config.json new file mode 100644 index 00000000000..2c6feed7fbd --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client_config.json @@ -0,0 +1,30 @@ +{ + "interfaces": { + "google.ads.datamanager.v1.MarketingDataInsightsService": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "RetrieveInsights": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_proto_list.json b/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_proto_list.json new file mode 100644 index 00000000000..ec5cc61b87e --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_proto_list.json @@ -0,0 +1,34 @@ +[ + "../../protos/google/ads/datamanager/v1/age_range.proto", + "../../protos/google/ads/datamanager/v1/audience.proto", + "../../protos/google/ads/datamanager/v1/cart_data.proto", + "../../protos/google/ads/datamanager/v1/consent.proto", + "../../protos/google/ads/datamanager/v1/destination.proto", + "../../protos/google/ads/datamanager/v1/device_info.proto", + "../../protos/google/ads/datamanager/v1/encryption_info.proto", + "../../protos/google/ads/datamanager/v1/error.proto", + "../../protos/google/ads/datamanager/v1/event.proto", + "../../protos/google/ads/datamanager/v1/experimental_field.proto", + "../../protos/google/ads/datamanager/v1/gender.proto", + "../../protos/google/ads/datamanager/v1/ingestion_service.proto", + "../../protos/google/ads/datamanager/v1/insights_service.proto", + "../../protos/google/ads/datamanager/v1/item_parameter.proto", + "../../protos/google/ads/datamanager/v1/match_rate.proto", + "../../protos/google/ads/datamanager/v1/partner_link_service.proto", + "../../protos/google/ads/datamanager/v1/processing_errors.proto", + "../../protos/google/ads/datamanager/v1/request_status_per_destination.proto", + "../../protos/google/ads/datamanager/v1/terms_of_service.proto", + "../../protos/google/ads/datamanager/v1/user_data.proto", + "../../protos/google/ads/datamanager/v1/user_list.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_metrics.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_pricing.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_status.proto", + "../../protos/google/ads/datamanager/v1/user_list_service.proto", + "../../protos/google/ads/datamanager/v1/user_properties.proto" +] diff --git a/packages/google-ads-datamanager/src/v1/partner_link_service_client.ts b/packages/google-ads-datamanager/src/v1/partner_link_service_client.ts new file mode 100644 index 00000000000..091a6ea2985 --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/partner_link_service_client.ts @@ -0,0 +1,1191 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/partner_link_service_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './partner_link_service_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Service for managing partner links. + * @class + * @memberof v1 + */ +export class PartnerLinkServiceClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('datamanager'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + partnerLinkServiceStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of PartnerLinkServiceClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new PartnerLinkServiceClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof PartnerLinkServiceClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'datamanager.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = opts?.fallback ?? (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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + accountPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}' + ), + partnerLinkPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + ), + userListPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + ), + userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + ), + userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' + ), + userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + ), + }; + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + searchPartnerLinks: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'partnerLinks') + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.ads.datamanager.v1.PartnerLinkService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.partnerLinkServiceStub) { + return this.partnerLinkServiceStub; + } + + // Put together the "service stub" for + // google.ads.datamanager.v1.PartnerLinkService. + this.partnerLinkServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.PartnerLinkService') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ads.datamanager.v1.PartnerLinkService, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const partnerLinkServiceStubMethods = + ['createPartnerLink', 'deletePartnerLink', 'searchPartnerLinks']; + for (const methodName of partnerLinkServiceStubMethods) { + const callPromise = this.partnerLinkServiceStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + this.descriptors.page[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.partnerLinkServiceStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/datamanager' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * Creates a partner link for the given account. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent, which owns this collection of partner links. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {google.ads.datamanager.v1.PartnerLink} request.partnerLink + * Required. The partner link to create. + * @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.ads.datamanager.v1.PartnerLink|PartnerLink}. + * 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/partner_link_service.create_partner_link.js + * region_tag:datamanager_v1_generated_PartnerLinkService_CreatePartnerLink_async + */ + createPartnerLink( + request?: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|undefined, {}|undefined + ]>; + createPartnerLink( + request: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, + {}|null|undefined>): void; + createPartnerLink( + request: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, + {}|null|undefined>): void; + createPartnerLink( + request?: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('createPartnerLink request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createPartnerLink response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.createPartnerLink(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|undefined, + {}|undefined + ]) => { + this._log.info('createPartnerLink response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Deletes a partner link for the given account. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the partner link to delete. + * Format: + * accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link} + * @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.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/partner_link_service.delete_partner_link.js + * region_tag:datamanager_v1_generated_PartnerLinkService_DeletePartnerLink_async + */ + deletePartnerLink( + request?: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, + options?: CallOptions): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|undefined, {}|undefined + ]>; + deletePartnerLink( + request: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, + {}|null|undefined>): void; + deletePartnerLink( + request: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, + {}|null|undefined>): void; + deletePartnerLink( + request?: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('deletePartnerLink request %j', request); + const wrappedCallback: Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deletePartnerLink response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.deletePartnerLink(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|undefined, + {}|undefined + ]) => { + this._log.info('deletePartnerLink response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + /** + * Searches for all partner links to and from a given account. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Account to search for partner links. If no `filter` is specified, + * all partner links where this account is either the `owning_account` or + * `partner_account` are returned. + * + * Format: `accountTypes/{account_type}/accounts/{account}` + * @param {number} request.pageSize + * The maximum number of partner links to return. The service may return + * fewer than this value. + * If unspecified, at most 10 partner links will be returned. + * The maximum value is 100; values above 100 will be coerced to 100. + * @param {string} request.pageToken + * A page token, received from a previous `SearchPartnerLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `SearchPartnerLinks` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](//google.aip.dev/160). All fields need to be on + * the left hand side of each condition (for example: `partner_link_id = + * 123456789`). + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * + * Supported fields: + * + * - `partner_link_id` + * - `owning_account.account_type` + * - `owning_account.account_id` + * - `partner_account.account_type` + * - `partner_account.account_id` + * + * Example: + * `owning_account.account_type = "GOOGLE_ADS" OR partner_account.account_id = + * 987654321` + * @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 Array of {@link protos.google.ads.datamanager.v1.PartnerLink|PartnerLink}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `searchPartnerLinksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + searchPartnerLinks( + request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IPartnerLink[], + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest|null, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse + ]>; + searchPartnerLinks( + request: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, + protos.google.ads.datamanager.v1.IPartnerLink>): void; + searchPartnerLinks( + request: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, + protos.google.ads.datamanager.v1.IPartnerLink>): void; + searchPartnerLinks( + request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, + protos.google.ads.datamanager.v1.IPartnerLink>, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, + protos.google.ads.datamanager.v1.IPartnerLink>): + Promise<[ + protos.google.ads.datamanager.v1.IPartnerLink[], + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest|null, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, + protos.google.ads.datamanager.v1.IPartnerLink>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('searchPartnerLinks values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('searchPartnerLinks request %j', request); + return this.innerApiCalls + .searchPartnerLinks(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.ads.datamanager.v1.IPartnerLink[], + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest|null, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse + ]) => { + this._log.info('searchPartnerLinks values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `searchPartnerLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Account to search for partner links. If no `filter` is specified, + * all partner links where this account is either the `owning_account` or + * `partner_account` are returned. + * + * Format: `accountTypes/{account_type}/accounts/{account}` + * @param {number} request.pageSize + * The maximum number of partner links to return. The service may return + * fewer than this value. + * If unspecified, at most 10 partner links will be returned. + * The maximum value is 100; values above 100 will be coerced to 100. + * @param {string} request.pageToken + * A page token, received from a previous `SearchPartnerLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `SearchPartnerLinks` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](//google.aip.dev/160). All fields need to be on + * the left hand side of each condition (for example: `partner_link_id = + * 123456789`). + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * + * Supported fields: + * + * - `partner_link_id` + * - `owning_account.account_type` + * - `owning_account.account_id` + * - `partner_account.account_type` + * - `partner_account.account_id` + * + * Example: + * `owning_account.account_type = "GOOGLE_ADS" OR partner_account.account_id = + * 987654321` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.ads.datamanager.v1.PartnerLink|PartnerLink} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `searchPartnerLinksAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + searchPartnerLinksStream( + request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['searchPartnerLinks']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('searchPartnerLinks stream %j', request); + return this.descriptors.page.searchPartnerLinks.createStream( + this.innerApiCalls.searchPartnerLinks as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `searchPartnerLinks`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Account to search for partner links. If no `filter` is specified, + * all partner links where this account is either the `owning_account` or + * `partner_account` are returned. + * + * Format: `accountTypes/{account_type}/accounts/{account}` + * @param {number} request.pageSize + * The maximum number of partner links to return. The service may return + * fewer than this value. + * If unspecified, at most 10 partner links will be returned. + * The maximum value is 100; values above 100 will be coerced to 100. + * @param {string} request.pageToken + * A page token, received from a previous `SearchPartnerLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `SearchPartnerLinks` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](//google.aip.dev/160). All fields need to be on + * the left hand side of each condition (for example: `partner_link_id = + * 123456789`). + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * + * Supported fields: + * + * - `partner_link_id` + * - `owning_account.account_type` + * - `owning_account.account_id` + * - `partner_account.account_type` + * - `partner_account.account_id` + * + * Example: + * `owning_account.account_type = "GOOGLE_ADS" OR partner_account.account_id = + * 987654321` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.ads.datamanager.v1.PartnerLink|PartnerLink}. The API will be called under the hood as needed, once per the page, + * 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/partner_link_service.search_partner_links.js + * region_tag:datamanager_v1_generated_PartnerLinkService_SearchPartnerLinks_async + */ + searchPartnerLinksAsync( + request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['searchPartnerLinks']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('searchPartnerLinks iterate %j', request); + return this.descriptors.page.searchPartnerLinks.asyncIterate( + this.innerApiCalls['searchPartnerLinks'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified account resource name string. + * + * @param {string} account_type + * @param {string} account + * @returns {string} Resource name string. + */ + accountPath(accountType:string,account:string) { + return this.pathTemplates.accountPathTemplate.render({ + account_type: accountType, + account: account, + }); + } + + /** + * Parse the account_type from Account resource. + * + * @param {string} accountName + * A fully-qualified path representing Account resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromAccountName(accountName: string) { + return this.pathTemplates.accountPathTemplate.match(accountName).account_type; + } + + /** + * Parse the account from Account resource. + * + * @param {string} accountName + * A fully-qualified path representing Account resource. + * @returns {string} A string representing the account. + */ + matchAccountFromAccountName(accountName: string) { + return this.pathTemplates.accountPathTemplate.match(accountName).account; + } + + /** + * Return a fully-qualified partnerLink resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} partner_link + * @returns {string} Resource name string. + */ + partnerLinkPath(accountType:string,account:string,partnerLink:string) { + return this.pathTemplates.partnerLinkPathTemplate.render({ + account_type: accountType, + account: account, + partner_link: partnerLink, + }); + } + + /** + * Parse the account_type from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + } + + /** + * Parse the account from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account. + */ + matchAccountFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + } + + /** + * Parse the partner_link from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the partner_link. + */ + matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + } + + /** + * Return a fully-qualified userList resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list + * @returns {string} Resource name string. + */ + userListPath(accountType:string,account:string,userList:string) { + return this.pathTemplates.userListPathTemplate.render({ + account_type: accountType, + account: account, + user_list: userList, + }); + } + + /** + * Parse the account_type from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + } + + /** + * Parse the account from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account; + } + + /** + * Parse the user_list from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the user_list. + */ + matchUserListFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + } + + /** + * Return a fully-qualified userListDirectLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_direct_license + * @returns {string} Resource name string. + */ + userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + return this.pathTemplates.userListDirectLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_direct_license: userListDirectLicense, + }); + } + + /** + * Parse the account_type from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + } + + /** + * Parse the account from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + } + + /** + * Parse the user_list_direct_license from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the user_list_direct_license. + */ + matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + } + + /** + * Return a fully-qualified userListGlobalLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @returns {string} Resource name string. + */ + userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + }); + } + + /** + * Parse the account_type from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + } + + /** + * Parse the account from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + } + + /** + * Return a fully-qualified userListGlobalLicenseCustomerInfo resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @param {string} license_customer_info + * @returns {string} Resource name string. + */ + userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }); + } + + /** + * Parse the account_type from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + } + + /** + * Parse the account from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + } + + /** + * Parse the license_customer_info from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the license_customer_info. + */ + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.partnerLinkServiceStub && !this._terminated) { + return this.partnerLinkServiceStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-ads-datamanager/src/v1/partner_link_service_client_config.json b/packages/google-ads-datamanager/src/v1/partner_link_service_client_config.json new file mode 100644 index 00000000000..38cbd9a3e8b --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/partner_link_service_client_config.json @@ -0,0 +1,38 @@ +{ + "interfaces": { + "google.ads.datamanager.v1.PartnerLinkService": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreatePartnerLink": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeletePartnerLink": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "SearchPartnerLinks": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-ads-datamanager/src/v1/partner_link_service_proto_list.json b/packages/google-ads-datamanager/src/v1/partner_link_service_proto_list.json new file mode 100644 index 00000000000..ec5cc61b87e --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/partner_link_service_proto_list.json @@ -0,0 +1,34 @@ +[ + "../../protos/google/ads/datamanager/v1/age_range.proto", + "../../protos/google/ads/datamanager/v1/audience.proto", + "../../protos/google/ads/datamanager/v1/cart_data.proto", + "../../protos/google/ads/datamanager/v1/consent.proto", + "../../protos/google/ads/datamanager/v1/destination.proto", + "../../protos/google/ads/datamanager/v1/device_info.proto", + "../../protos/google/ads/datamanager/v1/encryption_info.proto", + "../../protos/google/ads/datamanager/v1/error.proto", + "../../protos/google/ads/datamanager/v1/event.proto", + "../../protos/google/ads/datamanager/v1/experimental_field.proto", + "../../protos/google/ads/datamanager/v1/gender.proto", + "../../protos/google/ads/datamanager/v1/ingestion_service.proto", + "../../protos/google/ads/datamanager/v1/insights_service.proto", + "../../protos/google/ads/datamanager/v1/item_parameter.proto", + "../../protos/google/ads/datamanager/v1/match_rate.proto", + "../../protos/google/ads/datamanager/v1/partner_link_service.proto", + "../../protos/google/ads/datamanager/v1/processing_errors.proto", + "../../protos/google/ads/datamanager/v1/request_status_per_destination.proto", + "../../protos/google/ads/datamanager/v1/terms_of_service.proto", + "../../protos/google/ads/datamanager/v1/user_data.proto", + "../../protos/google/ads/datamanager/v1/user_list.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_metrics.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_pricing.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_status.proto", + "../../protos/google/ads/datamanager/v1/user_list_service.proto", + "../../protos/google/ads/datamanager/v1/user_properties.proto" +] diff --git a/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client.ts b/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client.ts new file mode 100644 index 00000000000..d9382a2d597 --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client.ts @@ -0,0 +1,1251 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/user_list_direct_license_service_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './user_list_direct_license_service_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Service for managing user list direct licenses. Delete is not a supported + * operation for UserListDirectLicenses. Callers should update the + * license status to DISABLED to instead to deactivate a license. + * + * This feature is only available to data partners. + * @class + * @memberof v1 + */ +export class UserListDirectLicenseServiceClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('datamanager'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + userListDirectLicenseServiceStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of UserListDirectLicenseServiceClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new UserListDirectLicenseServiceClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof UserListDirectLicenseServiceClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'datamanager.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = opts?.fallback ?? (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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + accountPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}' + ), + partnerLinkPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + ), + userListPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + ), + userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + ), + userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' + ), + userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + ), + }; + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listUserListDirectLicenses: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'userListDirectLicenses') + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.ads.datamanager.v1.UserListDirectLicenseService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.userListDirectLicenseServiceStub) { + return this.userListDirectLicenseServiceStub; + } + + // Put together the "service stub" for + // google.ads.datamanager.v1.UserListDirectLicenseService. + this.userListDirectLicenseServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.UserListDirectLicenseService') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ads.datamanager.v1.UserListDirectLicenseService, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const userListDirectLicenseServiceStubMethods = + ['createUserListDirectLicense', 'getUserListDirectLicense', 'updateUserListDirectLicense', 'listUserListDirectLicenses']; + for (const methodName of userListDirectLicenseServiceStubMethods) { + const callPromise = this.userListDirectLicenseServiceStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + this.descriptors.page[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.userListDirectLicenseServiceStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/datamanager' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * Creates a user list direct license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account that owns the user list being licensed. Should be in + * the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {google.ads.datamanager.v1.UserListDirectLicense} request.userListDirectLicense + * Required. The user list direct license to create. + * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. + * 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/user_list_direct_license_service.create_user_list_direct_license.js + * region_tag:datamanager_v1_generated_UserListDirectLicenseService_CreateUserListDirectLicense_async + */ + createUserListDirectLicense( + request?: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|undefined, {}|undefined + ]>; + createUserListDirectLicense( + request: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): void; + createUserListDirectLicense( + request: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): void; + createUserListDirectLicense( + request?: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('createUserListDirectLicense request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createUserListDirectLicense response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.createUserListDirectLicense(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|undefined, + {}|undefined + ]) => { + this._log.info('createUserListDirectLicense response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Retrieves a user list direct license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the user list direct license. + * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. + * 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/user_list_direct_license_service.get_user_list_direct_license.js + * region_tag:datamanager_v1_generated_UserListDirectLicenseService_GetUserListDirectLicense_async + */ + getUserListDirectLicense( + request?: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|undefined, {}|undefined + ]>; + getUserListDirectLicense( + request: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): void; + getUserListDirectLicense( + request: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): void; + getUserListDirectLicense( + request?: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getUserListDirectLicense request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getUserListDirectLicense response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getUserListDirectLicense(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|undefined, + {}|undefined + ]) => { + this._log.info('getUserListDirectLicense response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Updates a user list direct license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ads.datamanager.v1.UserListDirectLicense} request.userListDirectLicense + * Required. The licenses' `name` field is used to identify the license to + * update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. The special character `*` is not + * supported and an `INVALID_UPDATE_MASK` error will be thrown if used. + * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. + * 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/user_list_direct_license_service.update_user_list_direct_license.js + * region_tag:datamanager_v1_generated_UserListDirectLicenseService_UpdateUserListDirectLicense_async + */ + updateUserListDirectLicense( + request?: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|undefined, {}|undefined + ]>; + updateUserListDirectLicense( + request: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): void; + updateUserListDirectLicense( + request: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): void; + updateUserListDirectLicense( + request?: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'user_list_direct_license.name': request.userListDirectLicense!.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('updateUserListDirectLicense request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateUserListDirectLicense response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.updateUserListDirectLicense(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|undefined, + {}|undefined + ]) => { + this._log.info('updateUserListDirectLicense response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + /** + * Lists all user list direct licenses owned by the parent account. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return per page. The service + * may return fewer than this value. If unspecified, at most 50 licenses will + * be returned. The maximum value is 1000; values above 1000 will be coerced + * to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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 Array of {@link protos.google.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUserListDirectLicensesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listUserListDirectLicenses( + request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListDirectLicense[], + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest|null, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse + ]>; + listUserListDirectLicenses( + request: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense>): void; + listUserListDirectLicenses( + request: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense>): void; + listUserListDirectLicenses( + request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense>, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListDirectLicense[], + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest|null, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listUserListDirectLicenses values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listUserListDirectLicenses request %j', request); + return this.innerApiCalls + .listUserListDirectLicenses(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.ads.datamanager.v1.IUserListDirectLicense[], + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest|null, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse + ]) => { + this._log.info('listUserListDirectLicenses values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `listUserListDirectLicenses`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return per page. The service + * may return fewer than this value. If unspecified, at most 50 licenses will + * be returned. The maximum value is 1000; values above 1000 will be coerced + * to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUserListDirectLicensesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listUserListDirectLicensesStream( + request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listUserListDirectLicenses']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listUserListDirectLicenses stream %j', request); + return this.descriptors.page.listUserListDirectLicenses.createStream( + this.innerApiCalls.listUserListDirectLicenses as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `listUserListDirectLicenses`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return per page. The service + * may return fewer than this value. If unspecified, at most 50 licenses will + * be returned. The maximum value is 1000; values above 1000 will be coerced + * to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. The API will be called under the hood as needed, once per the page, + * 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/user_list_direct_license_service.list_user_list_direct_licenses.js + * region_tag:datamanager_v1_generated_UserListDirectLicenseService_ListUserListDirectLicenses_async + */ + listUserListDirectLicensesAsync( + request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listUserListDirectLicenses']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listUserListDirectLicenses iterate %j', request); + return this.descriptors.page.listUserListDirectLicenses.asyncIterate( + this.innerApiCalls['listUserListDirectLicenses'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified account resource name string. + * + * @param {string} account_type + * @param {string} account + * @returns {string} Resource name string. + */ + accountPath(accountType:string,account:string) { + return this.pathTemplates.accountPathTemplate.render({ + account_type: accountType, + account: account, + }); + } + + /** + * Parse the account_type from Account resource. + * + * @param {string} accountName + * A fully-qualified path representing Account resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromAccountName(accountName: string) { + return this.pathTemplates.accountPathTemplate.match(accountName).account_type; + } + + /** + * Parse the account from Account resource. + * + * @param {string} accountName + * A fully-qualified path representing Account resource. + * @returns {string} A string representing the account. + */ + matchAccountFromAccountName(accountName: string) { + return this.pathTemplates.accountPathTemplate.match(accountName).account; + } + + /** + * Return a fully-qualified partnerLink resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} partner_link + * @returns {string} Resource name string. + */ + partnerLinkPath(accountType:string,account:string,partnerLink:string) { + return this.pathTemplates.partnerLinkPathTemplate.render({ + account_type: accountType, + account: account, + partner_link: partnerLink, + }); + } + + /** + * Parse the account_type from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + } + + /** + * Parse the account from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account. + */ + matchAccountFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + } + + /** + * Parse the partner_link from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the partner_link. + */ + matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + } + + /** + * Return a fully-qualified userList resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list + * @returns {string} Resource name string. + */ + userListPath(accountType:string,account:string,userList:string) { + return this.pathTemplates.userListPathTemplate.render({ + account_type: accountType, + account: account, + user_list: userList, + }); + } + + /** + * Parse the account_type from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + } + + /** + * Parse the account from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account; + } + + /** + * Parse the user_list from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the user_list. + */ + matchUserListFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + } + + /** + * Return a fully-qualified userListDirectLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_direct_license + * @returns {string} Resource name string. + */ + userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + return this.pathTemplates.userListDirectLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_direct_license: userListDirectLicense, + }); + } + + /** + * Parse the account_type from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + } + + /** + * Parse the account from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + } + + /** + * Parse the user_list_direct_license from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the user_list_direct_license. + */ + matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + } + + /** + * Return a fully-qualified userListGlobalLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @returns {string} Resource name string. + */ + userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + }); + } + + /** + * Parse the account_type from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + } + + /** + * Parse the account from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + } + + /** + * Return a fully-qualified userListGlobalLicenseCustomerInfo resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @param {string} license_customer_info + * @returns {string} Resource name string. + */ + userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }); + } + + /** + * Parse the account_type from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + } + + /** + * Parse the account from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + } + + /** + * Parse the license_customer_info from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the license_customer_info. + */ + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.userListDirectLicenseServiceStub && !this._terminated) { + return this.userListDirectLicenseServiceStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client_config.json b/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client_config.json new file mode 100644 index 00000000000..19705c3315d --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client_config.json @@ -0,0 +1,42 @@ +{ + "interfaces": { + "google.ads.datamanager.v1.UserListDirectLicenseService": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateUserListDirectLicense": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetUserListDirectLicense": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateUserListDirectLicense": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListUserListDirectLicenses": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_proto_list.json b/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_proto_list.json new file mode 100644 index 00000000000..ec5cc61b87e --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_proto_list.json @@ -0,0 +1,34 @@ +[ + "../../protos/google/ads/datamanager/v1/age_range.proto", + "../../protos/google/ads/datamanager/v1/audience.proto", + "../../protos/google/ads/datamanager/v1/cart_data.proto", + "../../protos/google/ads/datamanager/v1/consent.proto", + "../../protos/google/ads/datamanager/v1/destination.proto", + "../../protos/google/ads/datamanager/v1/device_info.proto", + "../../protos/google/ads/datamanager/v1/encryption_info.proto", + "../../protos/google/ads/datamanager/v1/error.proto", + "../../protos/google/ads/datamanager/v1/event.proto", + "../../protos/google/ads/datamanager/v1/experimental_field.proto", + "../../protos/google/ads/datamanager/v1/gender.proto", + "../../protos/google/ads/datamanager/v1/ingestion_service.proto", + "../../protos/google/ads/datamanager/v1/insights_service.proto", + "../../protos/google/ads/datamanager/v1/item_parameter.proto", + "../../protos/google/ads/datamanager/v1/match_rate.proto", + "../../protos/google/ads/datamanager/v1/partner_link_service.proto", + "../../protos/google/ads/datamanager/v1/processing_errors.proto", + "../../protos/google/ads/datamanager/v1/request_status_per_destination.proto", + "../../protos/google/ads/datamanager/v1/terms_of_service.proto", + "../../protos/google/ads/datamanager/v1/user_data.proto", + "../../protos/google/ads/datamanager/v1/user_list.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_metrics.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_pricing.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_status.proto", + "../../protos/google/ads/datamanager/v1/user_list_service.proto", + "../../protos/google/ads/datamanager/v1/user_properties.proto" +] diff --git a/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client.ts b/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client.ts new file mode 100644 index 00000000000..eb92cd4aea4 --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client.ts @@ -0,0 +1,1548 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/user_list_global_license_service_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './user_list_global_license_service_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Service for managing user list global licenses. Delete is not a supported + * operation for UserListGlobalLicenses. Callers should update the + * license status to DISABLED to instead to deactivate a license. + * + * This feature is only available to data partners. + * @class + * @memberof v1 + */ +export class UserListGlobalLicenseServiceClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('datamanager'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + userListGlobalLicenseServiceStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of UserListGlobalLicenseServiceClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new UserListGlobalLicenseServiceClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof UserListGlobalLicenseServiceClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'datamanager.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = opts?.fallback ?? (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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + accountPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}' + ), + partnerLinkPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + ), + userListPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + ), + userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + ), + userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' + ), + userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + ), + }; + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listUserListGlobalLicenses: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'userListGlobalLicenses'), + listUserListGlobalLicenseCustomerInfos: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'userListGlobalLicenseCustomerInfos') + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.ads.datamanager.v1.UserListGlobalLicenseService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.userListGlobalLicenseServiceStub) { + return this.userListGlobalLicenseServiceStub; + } + + // Put together the "service stub" for + // google.ads.datamanager.v1.UserListGlobalLicenseService. + this.userListGlobalLicenseServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.UserListGlobalLicenseService') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ads.datamanager.v1.UserListGlobalLicenseService, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const userListGlobalLicenseServiceStubMethods = + ['createUserListGlobalLicense', 'updateUserListGlobalLicense', 'getUserListGlobalLicense', 'listUserListGlobalLicenses', 'listUserListGlobalLicenseCustomerInfos']; + for (const methodName of userListGlobalLicenseServiceStubMethods) { + const callPromise = this.userListGlobalLicenseServiceStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + this.descriptors.page[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.userListGlobalLicenseServiceStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/datamanager' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * Creates a user list global license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account that owns the user list being licensed. Should be in + * the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {google.ads.datamanager.v1.UserListGlobalLicense} request.userListGlobalLicense + * Required. The user list global license to create. + * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. + * 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/user_list_global_license_service.create_user_list_global_license.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_CreateUserListGlobalLicense_async + */ + createUserListGlobalLicense( + request?: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|undefined, {}|undefined + ]>; + createUserListGlobalLicense( + request: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): void; + createUserListGlobalLicense( + request: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): void; + createUserListGlobalLicense( + request?: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('createUserListGlobalLicense request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createUserListGlobalLicense response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.createUserListGlobalLicense(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|undefined, + {}|undefined + ]) => { + this._log.info('createUserListGlobalLicense response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Updates a user list global license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ads.datamanager.v1.UserListGlobalLicense} request.userListGlobalLicense + * Required. The licenses' `name` field is used to identify the license to + * update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. The special character `*` is not + * supported and an `INVALID_UPDATE_MASK` error will be thrown if used. + * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. + * 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/user_list_global_license_service.update_user_list_global_license.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_UpdateUserListGlobalLicense_async + */ + updateUserListGlobalLicense( + request?: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|undefined, {}|undefined + ]>; + updateUserListGlobalLicense( + request: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): void; + updateUserListGlobalLicense( + request: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): void; + updateUserListGlobalLicense( + request?: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'user_list_global_license.name': request.userListGlobalLicense!.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('updateUserListGlobalLicense request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateUserListGlobalLicense response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.updateUserListGlobalLicense(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|undefined, + {}|undefined + ]) => { + this._log.info('updateUserListGlobalLicense response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Retrieves a user list global license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the user list global license. + * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. + * 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/user_list_global_license_service.get_user_list_global_license.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_GetUserListGlobalLicense_async + */ + getUserListGlobalLicense( + request?: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|undefined, {}|undefined + ]>; + getUserListGlobalLicense( + request: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): void; + getUserListGlobalLicense( + request: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): void; + getUserListGlobalLicense( + request?: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getUserListGlobalLicense request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getUserListGlobalLicense response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getUserListGlobalLicense(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|undefined, + {}|undefined + ]) => { + this._log.info('getUserListGlobalLicense response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + /** + * Lists all user list global licenses owned by the parent account. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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 Array of {@link protos.google.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUserListGlobalLicensesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listUserListGlobalLicenses( + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicense[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest|null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse + ]>; + listUserListGlobalLicenses( + request: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense>): void; + listUserListGlobalLicenses( + request: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense>): void; + listUserListGlobalLicenses( + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense>, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicense[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest|null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listUserListGlobalLicenses values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listUserListGlobalLicenses request %j', request); + return this.innerApiCalls + .listUserListGlobalLicenses(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest|null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse + ]) => { + this._log.info('listUserListGlobalLicenses values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `listUserListGlobalLicenses`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUserListGlobalLicensesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listUserListGlobalLicensesStream( + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listUserListGlobalLicenses']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listUserListGlobalLicenses stream %j', request); + return this.descriptors.page.listUserListGlobalLicenses.createStream( + this.innerApiCalls.listUserListGlobalLicenses as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `listUserListGlobalLicenses`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. The API will be called under the hood as needed, once per the page, + * 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/user_list_global_license_service.list_user_list_global_licenses.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenses_async + */ + listUserListGlobalLicensesAsync( + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listUserListGlobalLicenses']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listUserListGlobalLicenses iterate %j', request); + return this.descriptors.page.listUserListGlobalLicenses.asyncIterate( + this.innerApiCalls['listUserListGlobalLicenses'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + /** + * Lists all customer info for a user list global license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The global license whose customer info are being queried. Should + * be in the format + * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. + * To list all global license customer info under an account, replace the user + * list global license id with a '-' (for example, + * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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 Array of {@link protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUserListGlobalLicenseCustomerInfosAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listUserListGlobalLicenseCustomerInfos( + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest|null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse + ]>; + listUserListGlobalLicenseCustomerInfos( + request: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>): void; + listUserListGlobalLicenseCustomerInfos( + request: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>): void; + listUserListGlobalLicenseCustomerInfos( + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>): + Promise<[ + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest|null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listUserListGlobalLicenseCustomerInfos values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listUserListGlobalLicenseCustomerInfos request %j', request); + return this.innerApiCalls + .listUserListGlobalLicenseCustomerInfos(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest|null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse + ]) => { + this._log.info('listUserListGlobalLicenseCustomerInfos values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `listUserListGlobalLicenseCustomerInfos`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The global license whose customer info are being queried. Should + * be in the format + * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. + * To list all global license customer info under an account, replace the user + * list global license id with a '-' (for example, + * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUserListGlobalLicenseCustomerInfosAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listUserListGlobalLicenseCustomerInfosStream( + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listUserListGlobalLicenseCustomerInfos']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listUserListGlobalLicenseCustomerInfos stream %j', request); + return this.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream( + this.innerApiCalls.listUserListGlobalLicenseCustomerInfos as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `listUserListGlobalLicenseCustomerInfos`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The global license whose customer info are being queried. Should + * be in the format + * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. + * To list all global license customer info under an account, replace the user + * list global license id with a '-' (for example, + * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) + * @param {string} [request.filter] + * Optional. Filters to apply to the list request. All fields need to be on + * the left hand side of each condition (for example: user_list_id = 123). + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo}. The API will be called under the hood as needed, once per the page, + * 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/user_list_global_license_service.list_user_list_global_license_customer_infos.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenseCustomerInfos_async + */ + listUserListGlobalLicenseCustomerInfosAsync( + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listUserListGlobalLicenseCustomerInfos']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listUserListGlobalLicenseCustomerInfos iterate %j', request); + return this.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate( + this.innerApiCalls['listUserListGlobalLicenseCustomerInfos'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified account resource name string. + * + * @param {string} account_type + * @param {string} account + * @returns {string} Resource name string. + */ + accountPath(accountType:string,account:string) { + return this.pathTemplates.accountPathTemplate.render({ + account_type: accountType, + account: account, + }); + } + + /** + * Parse the account_type from Account resource. + * + * @param {string} accountName + * A fully-qualified path representing Account resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromAccountName(accountName: string) { + return this.pathTemplates.accountPathTemplate.match(accountName).account_type; + } + + /** + * Parse the account from Account resource. + * + * @param {string} accountName + * A fully-qualified path representing Account resource. + * @returns {string} A string representing the account. + */ + matchAccountFromAccountName(accountName: string) { + return this.pathTemplates.accountPathTemplate.match(accountName).account; + } + + /** + * Return a fully-qualified partnerLink resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} partner_link + * @returns {string} Resource name string. + */ + partnerLinkPath(accountType:string,account:string,partnerLink:string) { + return this.pathTemplates.partnerLinkPathTemplate.render({ + account_type: accountType, + account: account, + partner_link: partnerLink, + }); + } + + /** + * Parse the account_type from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + } + + /** + * Parse the account from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account. + */ + matchAccountFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + } + + /** + * Parse the partner_link from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the partner_link. + */ + matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + } + + /** + * Return a fully-qualified userList resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list + * @returns {string} Resource name string. + */ + userListPath(accountType:string,account:string,userList:string) { + return this.pathTemplates.userListPathTemplate.render({ + account_type: accountType, + account: account, + user_list: userList, + }); + } + + /** + * Parse the account_type from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + } + + /** + * Parse the account from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account; + } + + /** + * Parse the user_list from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the user_list. + */ + matchUserListFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + } + + /** + * Return a fully-qualified userListDirectLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_direct_license + * @returns {string} Resource name string. + */ + userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + return this.pathTemplates.userListDirectLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_direct_license: userListDirectLicense, + }); + } + + /** + * Parse the account_type from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + } + + /** + * Parse the account from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + } + + /** + * Parse the user_list_direct_license from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the user_list_direct_license. + */ + matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + } + + /** + * Return a fully-qualified userListGlobalLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @returns {string} Resource name string. + */ + userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + }); + } + + /** + * Parse the account_type from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + } + + /** + * Parse the account from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + } + + /** + * Return a fully-qualified userListGlobalLicenseCustomerInfo resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @param {string} license_customer_info + * @returns {string} Resource name string. + */ + userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }); + } + + /** + * Parse the account_type from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + } + + /** + * Parse the account from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + } + + /** + * Parse the license_customer_info from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the license_customer_info. + */ + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.userListGlobalLicenseServiceStub && !this._terminated) { + return this.userListGlobalLicenseServiceStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client_config.json b/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client_config.json new file mode 100644 index 00000000000..c71805278ff --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client_config.json @@ -0,0 +1,46 @@ +{ + "interfaces": { + "google.ads.datamanager.v1.UserListGlobalLicenseService": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateUserListGlobalLicense": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateUserListGlobalLicense": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetUserListGlobalLicense": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListUserListGlobalLicenses": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListUserListGlobalLicenseCustomerInfos": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-ads-datamanager/src/v1/user_list_global_license_service_proto_list.json b/packages/google-ads-datamanager/src/v1/user_list_global_license_service_proto_list.json new file mode 100644 index 00000000000..ec5cc61b87e --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_global_license_service_proto_list.json @@ -0,0 +1,34 @@ +[ + "../../protos/google/ads/datamanager/v1/age_range.proto", + "../../protos/google/ads/datamanager/v1/audience.proto", + "../../protos/google/ads/datamanager/v1/cart_data.proto", + "../../protos/google/ads/datamanager/v1/consent.proto", + "../../protos/google/ads/datamanager/v1/destination.proto", + "../../protos/google/ads/datamanager/v1/device_info.proto", + "../../protos/google/ads/datamanager/v1/encryption_info.proto", + "../../protos/google/ads/datamanager/v1/error.proto", + "../../protos/google/ads/datamanager/v1/event.proto", + "../../protos/google/ads/datamanager/v1/experimental_field.proto", + "../../protos/google/ads/datamanager/v1/gender.proto", + "../../protos/google/ads/datamanager/v1/ingestion_service.proto", + "../../protos/google/ads/datamanager/v1/insights_service.proto", + "../../protos/google/ads/datamanager/v1/item_parameter.proto", + "../../protos/google/ads/datamanager/v1/match_rate.proto", + "../../protos/google/ads/datamanager/v1/partner_link_service.proto", + "../../protos/google/ads/datamanager/v1/processing_errors.proto", + "../../protos/google/ads/datamanager/v1/request_status_per_destination.proto", + "../../protos/google/ads/datamanager/v1/terms_of_service.proto", + "../../protos/google/ads/datamanager/v1/user_data.proto", + "../../protos/google/ads/datamanager/v1/user_list.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_metrics.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_pricing.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_status.proto", + "../../protos/google/ads/datamanager/v1/user_list_service.proto", + "../../protos/google/ads/datamanager/v1/user_properties.proto" +] diff --git a/packages/google-ads-datamanager/src/v1/user_list_service_client.ts b/packages/google-ads-datamanager/src/v1/user_list_service_client.ts new file mode 100644 index 00000000000..7760dc4a860 --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_service_client.ts @@ -0,0 +1,1419 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1/user_list_service_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './user_list_service_client_config.json'; +const version = require('../../../package.json').version; + +/** + * Service for managing UserList resources. + * @class + * @memberof v1 + */ +export class UserListServiceClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('datamanager'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; + userListServiceStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of UserListServiceClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new UserListServiceClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof UserListServiceClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'datamanager.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + const fallback = opts?.fallback ?? (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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + accountPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}' + ), + partnerLinkPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + ), + userListPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + ), + userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + ), + userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' + ), + userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + ), + }; + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + listUserLists: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'userLists') + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.ads.datamanager.v1.UserListService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.userListServiceStub) { + return this.userListServiceStub; + } + + // Put together the "service stub" for + // google.ads.datamanager.v1.UserListService. + this.userListServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.UserListService') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ads.datamanager.v1.UserListService, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const userListServiceStubMethods = + ['getUserList', 'listUserLists', 'createUserList', 'updateUserList', 'deleteUserList']; + for (const methodName of userListServiceStubMethods) { + const callPromise = this.userListServiceStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + this.descriptors.page[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.userListServiceStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'datamanager.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/datamanager' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * Gets a UserList. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the UserList to retrieve. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + * @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.ads.datamanager.v1.UserList|UserList}. + * 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/user_list_service.get_user_list.js + * region_tag:datamanager_v1_generated_UserListService_GetUserList_async + */ + getUserList( + request?: protos.google.ads.datamanager.v1.IGetUserListRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest|undefined, {}|undefined + ]>; + getUserList( + request: protos.google.ads.datamanager.v1.IGetUserListRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, + {}|null|undefined>): void; + getUserList( + request: protos.google.ads.datamanager.v1.IGetUserListRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, + {}|null|undefined>): void; + getUserList( + request?: protos.google.ads.datamanager.v1.IGetUserListRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getUserList request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getUserList response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getUserList(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest|undefined, + {}|undefined + ]) => { + this._log.info('getUserList response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Creates a UserList. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account where this user list will be created. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {google.ads.datamanager.v1.UserList} request.userList + * Required. The user list to create. + * @param {boolean} [request.validateOnly] + * Optional. If true, the request is validated but not executed. + * @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.ads.datamanager.v1.UserList|UserList}. + * 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/user_list_service.create_user_list.js + * region_tag:datamanager_v1_generated_UserListService_CreateUserList_async + */ + createUserList( + request?: protos.google.ads.datamanager.v1.ICreateUserListRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest|undefined, {}|undefined + ]>; + createUserList( + request: protos.google.ads.datamanager.v1.ICreateUserListRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, + {}|null|undefined>): void; + createUserList( + request: protos.google.ads.datamanager.v1.ICreateUserListRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, + {}|null|undefined>): void; + createUserList( + request?: protos.google.ads.datamanager.v1.ICreateUserListRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('createUserList request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createUserList response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.createUserList(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest|undefined, + {}|undefined + ]) => { + this._log.info('createUserList response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Updates a UserList. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ads.datamanager.v1.UserList} request.userList + * Required. The user list to update. + * + * The user list's `name` field is used to identify the user list to update. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. + * @param {boolean} [request.validateOnly] + * Optional. If true, the request is validated but not executed. + * @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.ads.datamanager.v1.UserList|UserList}. + * 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/user_list_service.update_user_list.js + * region_tag:datamanager_v1_generated_UserListService_UpdateUserList_async + */ + updateUserList( + request?: protos.google.ads.datamanager.v1.IUpdateUserListRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest|undefined, {}|undefined + ]>; + updateUserList( + request: protos.google.ads.datamanager.v1.IUpdateUserListRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, + {}|null|undefined>): void; + updateUserList( + request: protos.google.ads.datamanager.v1.IUpdateUserListRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, + {}|null|undefined>): void; + updateUserList( + request?: protos.google.ads.datamanager.v1.IUpdateUserListRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'user_list.name': request.userList!.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('updateUserList request %j', request); + const wrappedCallback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateUserList response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.updateUserList(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest|undefined, + {}|undefined + ]) => { + this._log.info('updateUserList response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Deletes a UserList. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the user list to delete. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + * @param {boolean} [request.validateOnly] + * Optional. If true, the request is validated but not executed. + * @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.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/user_list_service.delete_user_list.js + * region_tag:datamanager_v1_generated_UserListService_DeleteUserList_async + */ + deleteUserList( + request?: protos.google.ads.datamanager.v1.IDeleteUserListRequest, + options?: CallOptions): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest|undefined, {}|undefined + ]>; + deleteUserList( + request: protos.google.ads.datamanager.v1.IDeleteUserListRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, + {}|null|undefined>): void; + deleteUserList( + request: protos.google.ads.datamanager.v1.IDeleteUserListRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, + {}|null|undefined>): void; + deleteUserList( + request?: protos.google.ads.datamanager.v1.IDeleteUserListRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('deleteUserList request %j', request); + const wrappedCallback: Callback< + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteUserList response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.deleteUserList(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest|undefined, + {}|undefined + ]) => { + this._log.info('deleteUserList response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + /** + * Lists UserLists. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account which owns this collection of user lists. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {number} [request.pageSize] + * Optional. The maximum number of user lists to return. The service may + * return fewer than this value. If unspecified, at most 50 user lists will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListUserLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListUserLists` must + * match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](//google.aip.dev/160). All fields need to be on + * the left hand side of each condition (for example: `display_name = "list + * 1"`). + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * - `:` (has) + * + * Supported fields: + * + * - `id` + * - `display_name` + * - `description` + * - `membership_status` + * - `integration_code` + * - `access_reason` + * - `ingested_user_list_info.upload_key_types` + * @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 Array of {@link protos.google.ads.datamanager.v1.UserList|UserList}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listUserListsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listUserLists( + request?: protos.google.ads.datamanager.v1.IListUserListsRequest, + options?: CallOptions): + Promise<[ + protos.google.ads.datamanager.v1.IUserList[], + protos.google.ads.datamanager.v1.IListUserListsRequest|null, + protos.google.ads.datamanager.v1.IListUserListsResponse + ]>; + listUserLists( + request: protos.google.ads.datamanager.v1.IListUserListsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserList>): void; + listUserLists( + request: protos.google.ads.datamanager.v1.IListUserListsRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserList>): void; + listUserLists( + request?: protos.google.ads.datamanager.v1.IListUserListsRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserList>, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserList>): + Promise<[ + protos.google.ads.datamanager.v1.IUserList[], + protos.google.ads.datamanager.v1.IListUserListsRequest|null, + protos.google.ads.datamanager.v1.IListUserListsResponse + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, + protos.google.ads.datamanager.v1.IUserList>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listUserLists values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listUserLists request %j', request); + return this.innerApiCalls + .listUserLists(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.ads.datamanager.v1.IUserList[], + protos.google.ads.datamanager.v1.IListUserListsRequest|null, + protos.google.ads.datamanager.v1.IListUserListsResponse + ]) => { + this._log.info('listUserLists values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `listUserLists`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account which owns this collection of user lists. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {number} [request.pageSize] + * Optional. The maximum number of user lists to return. The service may + * return fewer than this value. If unspecified, at most 50 user lists will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListUserLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListUserLists` must + * match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](//google.aip.dev/160). All fields need to be on + * the left hand side of each condition (for example: `display_name = "list + * 1"`). + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * - `:` (has) + * + * Supported fields: + * + * - `id` + * - `display_name` + * - `description` + * - `membership_status` + * - `integration_code` + * - `access_reason` + * - `ingested_user_list_info.upload_key_types` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.ads.datamanager.v1.UserList|UserList} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listUserListsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listUserListsStream( + request?: protos.google.ads.datamanager.v1.IListUserListsRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listUserLists']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listUserLists stream %j', request); + return this.descriptors.page.listUserLists.createStream( + this.innerApiCalls.listUserLists as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `listUserLists`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account which owns this collection of user lists. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {number} [request.pageSize] + * Optional. The maximum number of user lists to return. The service may + * return fewer than this value. If unspecified, at most 50 user lists will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListUserLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListUserLists` must + * match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](//google.aip.dev/160). All fields need to be on + * the left hand side of each condition (for example: `display_name = "list + * 1"`). + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * - `:` (has) + * + * Supported fields: + * + * - `id` + * - `display_name` + * - `description` + * - `membership_status` + * - `integration_code` + * - `access_reason` + * - `ingested_user_list_info.upload_key_types` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.ads.datamanager.v1.UserList|UserList}. The API will be called under the hood as needed, once per the page, + * 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/user_list_service.list_user_lists.js + * region_tag:datamanager_v1_generated_UserListService_ListUserLists_async + */ + listUserListsAsync( + request?: protos.google.ads.datamanager.v1.IListUserListsRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + const defaultCallSettings = this._defaults['listUserLists']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listUserLists iterate %j', request); + return this.descriptors.page.listUserLists.asyncIterate( + this.innerApiCalls['listUserLists'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified account resource name string. + * + * @param {string} account_type + * @param {string} account + * @returns {string} Resource name string. + */ + accountPath(accountType:string,account:string) { + return this.pathTemplates.accountPathTemplate.render({ + account_type: accountType, + account: account, + }); + } + + /** + * Parse the account_type from Account resource. + * + * @param {string} accountName + * A fully-qualified path representing Account resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromAccountName(accountName: string) { + return this.pathTemplates.accountPathTemplate.match(accountName).account_type; + } + + /** + * Parse the account from Account resource. + * + * @param {string} accountName + * A fully-qualified path representing Account resource. + * @returns {string} A string representing the account. + */ + matchAccountFromAccountName(accountName: string) { + return this.pathTemplates.accountPathTemplate.match(accountName).account; + } + + /** + * Return a fully-qualified partnerLink resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} partner_link + * @returns {string} Resource name string. + */ + partnerLinkPath(accountType:string,account:string,partnerLink:string) { + return this.pathTemplates.partnerLinkPathTemplate.render({ + account_type: accountType, + account: account, + partner_link: partnerLink, + }); + } + + /** + * Parse the account_type from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + } + + /** + * Parse the account from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the account. + */ + matchAccountFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + } + + /** + * Parse the partner_link from PartnerLink resource. + * + * @param {string} partnerLinkName + * A fully-qualified path representing PartnerLink resource. + * @returns {string} A string representing the partner_link. + */ + matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + } + + /** + * Return a fully-qualified userList resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list + * @returns {string} Resource name string. + */ + userListPath(accountType:string,account:string,userList:string) { + return this.pathTemplates.userListPathTemplate.render({ + account_type: accountType, + account: account, + user_list: userList, + }); + } + + /** + * Parse the account_type from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + } + + /** + * Parse the account from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).account; + } + + /** + * Parse the user_list from UserList resource. + * + * @param {string} userListName + * A fully-qualified path representing UserList resource. + * @returns {string} A string representing the user_list. + */ + matchUserListFromUserListName(userListName: string) { + return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + } + + /** + * Return a fully-qualified userListDirectLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_direct_license + * @returns {string} Resource name string. + */ + userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + return this.pathTemplates.userListDirectLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_direct_license: userListDirectLicense, + }); + } + + /** + * Parse the account_type from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + } + + /** + * Parse the account from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + } + + /** + * Parse the user_list_direct_license from UserListDirectLicense resource. + * + * @param {string} userListDirectLicenseName + * A fully-qualified path representing UserListDirectLicense resource. + * @returns {string} A string representing the user_list_direct_license. + */ + matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { + return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + } + + /** + * Return a fully-qualified userListGlobalLicense resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @returns {string} Resource name string. + */ + userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + }); + } + + /** + * Parse the account_type from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + } + + /** + * Parse the account from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicense resource. + * + * @param {string} userListGlobalLicenseName + * A fully-qualified path representing UserListGlobalLicense resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + } + + /** + * Return a fully-qualified userListGlobalLicenseCustomerInfo resource name string. + * + * @param {string} account_type + * @param {string} account + * @param {string} user_list_global_license + * @param {string} license_customer_info + * @returns {string} Resource name string. + */ + userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }); + } + + /** + * Parse the account_type from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account_type. + */ + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + } + + /** + * Parse the account from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the account. + */ + matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + } + + /** + * Parse the user_list_global_license from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the user_list_global_license. + */ + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + } + + /** + * Parse the license_customer_info from UserListGlobalLicenseCustomerInfo resource. + * + * @param {string} userListGlobalLicenseCustomerInfoName + * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. + * @returns {string} A string representing the license_customer_info. + */ + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.userListServiceStub && !this._terminated) { + return this.userListServiceStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-ads-datamanager/src/v1/user_list_service_client_config.json b/packages/google-ads-datamanager/src/v1/user_list_service_client_config.json new file mode 100644 index 00000000000..c8abe723125 --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_service_client_config.json @@ -0,0 +1,46 @@ +{ + "interfaces": { + "google.ads.datamanager.v1.UserListService": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "GetUserList": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListUserLists": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "CreateUserList": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateUserList": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteUserList": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-ads-datamanager/src/v1/user_list_service_proto_list.json b/packages/google-ads-datamanager/src/v1/user_list_service_proto_list.json new file mode 100644 index 00000000000..ec5cc61b87e --- /dev/null +++ b/packages/google-ads-datamanager/src/v1/user_list_service_proto_list.json @@ -0,0 +1,34 @@ +[ + "../../protos/google/ads/datamanager/v1/age_range.proto", + "../../protos/google/ads/datamanager/v1/audience.proto", + "../../protos/google/ads/datamanager/v1/cart_data.proto", + "../../protos/google/ads/datamanager/v1/consent.proto", + "../../protos/google/ads/datamanager/v1/destination.proto", + "../../protos/google/ads/datamanager/v1/device_info.proto", + "../../protos/google/ads/datamanager/v1/encryption_info.proto", + "../../protos/google/ads/datamanager/v1/error.proto", + "../../protos/google/ads/datamanager/v1/event.proto", + "../../protos/google/ads/datamanager/v1/experimental_field.proto", + "../../protos/google/ads/datamanager/v1/gender.proto", + "../../protos/google/ads/datamanager/v1/ingestion_service.proto", + "../../protos/google/ads/datamanager/v1/insights_service.proto", + "../../protos/google/ads/datamanager/v1/item_parameter.proto", + "../../protos/google/ads/datamanager/v1/match_rate.proto", + "../../protos/google/ads/datamanager/v1/partner_link_service.proto", + "../../protos/google/ads/datamanager/v1/processing_errors.proto", + "../../protos/google/ads/datamanager/v1/request_status_per_destination.proto", + "../../protos/google/ads/datamanager/v1/terms_of_service.proto", + "../../protos/google/ads/datamanager/v1/user_data.proto", + "../../protos/google/ads/datamanager/v1/user_list.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_direct_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_service.proto", + "../../protos/google/ads/datamanager/v1/user_list_global_license_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_client_account_type.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_metrics.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_pricing.proto", + "../../protos/google/ads/datamanager/v1/user_list_license_status.proto", + "../../protos/google/ads/datamanager/v1/user_list_service.proto", + "../../protos/google/ads/datamanager/v1/user_properties.proto" +] diff --git a/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.js b/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.js index 09b725fb367..da1c9a355b4 100644 --- a/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.js +++ b/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.js @@ -22,6 +22,11 @@ const datamanager = require('@google-ads/datamanager'); function main() { const ingestionServiceClient = new datamanager.IngestionServiceClient(); + const marketingDataInsightsServiceClient = new datamanager.MarketingDataInsightsServiceClient(); + const partnerLinkServiceClient = new datamanager.PartnerLinkServiceClient(); + const userListDirectLicenseServiceClient = new datamanager.UserListDirectLicenseServiceClient(); + const userListGlobalLicenseServiceClient = new datamanager.UserListGlobalLicenseServiceClient(); + const userListServiceClient = new datamanager.UserListServiceClient(); } main(); diff --git a/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.ts b/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.ts index d12f8482e11..2e2810220ae 100644 --- a/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.ts +++ b/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.ts @@ -16,17 +16,47 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {IngestionServiceClient} from '@google-ads/datamanager'; +import {IngestionServiceClient, MarketingDataInsightsServiceClient, PartnerLinkServiceClient, UserListDirectLicenseServiceClient, UserListGlobalLicenseServiceClient, UserListServiceClient} from '@google-ads/datamanager'; // check that the client class type name can be used function doStuffWithIngestionServiceClient(client: IngestionServiceClient) { client.close(); } +function doStuffWithMarketingDataInsightsServiceClient(client: MarketingDataInsightsServiceClient) { + client.close(); +} +function doStuffWithPartnerLinkServiceClient(client: PartnerLinkServiceClient) { + client.close(); +} +function doStuffWithUserListDirectLicenseServiceClient(client: UserListDirectLicenseServiceClient) { + client.close(); +} +function doStuffWithUserListGlobalLicenseServiceClient(client: UserListGlobalLicenseServiceClient) { + client.close(); +} +function doStuffWithUserListServiceClient(client: UserListServiceClient) { + client.close(); +} function main() { // check that the client instance can be created const ingestionServiceClient = new IngestionServiceClient(); doStuffWithIngestionServiceClient(ingestionServiceClient); + // check that the client instance can be created + const marketingDataInsightsServiceClient = new MarketingDataInsightsServiceClient(); + doStuffWithMarketingDataInsightsServiceClient(marketingDataInsightsServiceClient); + // check that the client instance can be created + const partnerLinkServiceClient = new PartnerLinkServiceClient(); + doStuffWithPartnerLinkServiceClient(partnerLinkServiceClient); + // check that the client instance can be created + const userListDirectLicenseServiceClient = new UserListDirectLicenseServiceClient(); + doStuffWithUserListDirectLicenseServiceClient(userListDirectLicenseServiceClient); + // check that the client instance can be created + const userListGlobalLicenseServiceClient = new UserListGlobalLicenseServiceClient(); + doStuffWithUserListGlobalLicenseServiceClient(userListGlobalLicenseServiceClient); + // check that the client instance can be created + const userListServiceClient = new UserListServiceClient(); + doStuffWithUserListServiceClient(userListServiceClient); } main(); diff --git a/packages/google-ads-datamanager/test/gapic_ingestion_service_v1.ts b/packages/google-ads-datamanager/test/gapic_ingestion_service_v1.ts index 5cb6dc166e8..ab31bea65b7 100644 --- a/packages/google-ads-datamanager/test/gapic_ingestion_service_v1.ts +++ b/packages/google-ads-datamanager/test/gapic_ingestion_service_v1.ts @@ -511,4 +511,245 @@ describe('v1.IngestionServiceClient', () => { await assert.rejects(client.retrieveRequestStatus(request), expectedError); }); }); + + describe('Path templates', () => { + + describe('partnerLink', async () => { + const fakePath = "/rendered/path/partnerLink"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + partner_link: "partnerLinkValue", + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, "partnerLinkValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userList', async () => { + const fakePath = "/rendered/path/userList"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list: "userListValue", + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, "userListValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListDirectLicense', async () => { + const fakePath = "/rendered/path/userListDirectLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_direct_license: "userListDirectLicenseValue", + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "userListDirectLicenseValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicense', async () => { + const fakePath = "/rendered/path/userListGlobalLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + license_customer_info: "licenseCustomerInfoValue", + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "licenseCustomerInfoValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + }); }); diff --git a/packages/google-ads-datamanager/test/gapic_marketing_data_insights_service_v1.ts b/packages/google-ads-datamanager/test/gapic_marketing_data_insights_service_v1.ts new file mode 100644 index 00000000000..eabc01fa865 --- /dev/null +++ b/packages/google-ads-datamanager/test/gapic_marketing_data_insights_service_v1.ts @@ -0,0 +1,563 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as marketingdatainsightsserviceModule from '../src'; + +import {protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +describe('v1.MarketingDataInsightsServiceClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.marketingDataInsightsServiceStub, undefined); + await client.initialize(); + assert(client.marketingDataInsightsServiceStub); + }); + + it('has close method for the initialized client', done => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.marketingDataInsightsServiceStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.marketingDataInsightsServiceStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('retrieveInsights', () => { + it('invokes retrieveInsights without error', async () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.RetrieveInsightsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsResponse() + ); + client.innerApiCalls.retrieveInsights = stubSimpleCall(expectedResponse); + const [response] = await client.retrieveInsights(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.retrieveInsights as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.retrieveInsights as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes retrieveInsights without error using callback', async () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.RetrieveInsightsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsResponse() + ); + client.innerApiCalls.retrieveInsights = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.retrieveInsights( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IRetrieveInsightsResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.retrieveInsights as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.retrieveInsights as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes retrieveInsights with error', async () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.RetrieveInsightsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.retrieveInsights = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.retrieveInsights(request), expectedError); + const actualRequest = (client.innerApiCalls.retrieveInsights as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.retrieveInsights as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes retrieveInsights with closed client', async () => { + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.RetrieveInsightsRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.retrieveInsights(request), expectedError); + }); + }); + + describe('Path templates', () => { + + describe('partnerLink', async () => { + const fakePath = "/rendered/path/partnerLink"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + partner_link: "partnerLinkValue", + }; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, "partnerLinkValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userList', async () => { + const fakePath = "/rendered/path/userList"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list: "userListValue", + }; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, "userListValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListDirectLicense', async () => { + const fakePath = "/rendered/path/userListDirectLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_direct_license: "userListDirectLicenseValue", + }; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "userListDirectLicenseValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicense', async () => { + const fakePath = "/rendered/path/userListGlobalLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + }; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + license_customer_info: "licenseCustomerInfoValue", + }; + const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "licenseCustomerInfoValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + }); +}); diff --git a/packages/google-ads-datamanager/test/gapic_partner_link_service_v1.ts b/packages/google-ads-datamanager/test/gapic_partner_link_service_v1.ts new file mode 100644 index 00000000000..d279f6e51bd --- /dev/null +++ b/packages/google-ads-datamanager/test/gapic_partner_link_service_v1.ts @@ -0,0 +1,1001 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as partnerlinkserviceModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.PartnerLinkServiceClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = partnerlinkserviceModule.v1.PartnerLinkServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = partnerlinkserviceModule.v1.PartnerLinkServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new partnerlinkserviceModule.v1.PartnerLinkServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = partnerlinkserviceModule.v1.PartnerLinkServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.partnerLinkServiceStub, undefined); + await client.initialize(); + assert(client.partnerLinkServiceStub); + }); + + it('has close method for the initialized client', done => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.partnerLinkServiceStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.partnerLinkServiceStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createPartnerLink', () => { + it('invokes createPartnerLink without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreatePartnerLinkRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink() + ); + client.innerApiCalls.createPartnerLink = stubSimpleCall(expectedResponse); + const [response] = await client.createPartnerLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createPartnerLink as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createPartnerLink as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createPartnerLink without error using callback', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreatePartnerLinkRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink() + ); + client.innerApiCalls.createPartnerLink = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createPartnerLink( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IPartnerLink|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createPartnerLink as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createPartnerLink as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createPartnerLink with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreatePartnerLinkRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createPartnerLink = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.createPartnerLink(request), expectedError); + const actualRequest = (client.innerApiCalls.createPartnerLink as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createPartnerLink as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createPartnerLink with closed client', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreatePartnerLinkRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.createPartnerLink(request), expectedError); + }); + }); + + describe('deletePartnerLink', () => { + it('invokes deletePartnerLink without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.DeletePartnerLinkRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deletePartnerLink = stubSimpleCall(expectedResponse); + const [response] = await client.deletePartnerLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deletePartnerLink as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deletePartnerLink as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deletePartnerLink without error using callback', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.DeletePartnerLinkRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deletePartnerLink = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deletePartnerLink( + request, + (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deletePartnerLink as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deletePartnerLink as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deletePartnerLink with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.DeletePartnerLinkRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deletePartnerLink = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deletePartnerLink(request), expectedError); + const actualRequest = (client.innerApiCalls.deletePartnerLink as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deletePartnerLink as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deletePartnerLink with closed client', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.DeletePartnerLinkRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.deletePartnerLink(request), expectedError); + }); + }); + + describe('searchPartnerLinks', () => { + it('invokes searchPartnerLinks without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + ]; + client.innerApiCalls.searchPartnerLinks = stubSimpleCall(expectedResponse); + const [response] = await client.searchPartnerLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.searchPartnerLinks as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.searchPartnerLinks as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes searchPartnerLinks without error using callback', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + ]; + client.innerApiCalls.searchPartnerLinks = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.searchPartnerLinks( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IPartnerLink[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.searchPartnerLinks as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.searchPartnerLinks as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes searchPartnerLinks with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchPartnerLinks = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.searchPartnerLinks(request), expectedError); + const actualRequest = (client.innerApiCalls.searchPartnerLinks as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.searchPartnerLinks as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes searchPartnerLinksStream without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + ]; + client.descriptors.page.searchPartnerLinks.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.searchPartnerLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.PartnerLink[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.PartnerLink) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.searchPartnerLinks.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.searchPartnerLinks, request)); + assert( + (client.descriptors.page.searchPartnerLinks.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes searchPartnerLinksStream with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.searchPartnerLinks.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.searchPartnerLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.PartnerLink[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.PartnerLink) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.searchPartnerLinks.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.searchPartnerLinks, request)); + assert( + (client.descriptors.page.searchPartnerLinks.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with searchPartnerLinks without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), + ]; + client.descriptors.page.searchPartnerLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IPartnerLink[] = []; + const iterable = client.searchPartnerLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with searchPartnerLinks with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.searchPartnerLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.searchPartnerLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IPartnerLink[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); + + describe('Path templates', () => { + + describe('account', async () => { + const fakePath = "/rendered/path/account"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.accountPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath("accountTypeValue", "accountValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromAccountName', () => { + const result = client.matchAccountTypeFromAccountName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('partnerLink', async () => { + const fakePath = "/rendered/path/partnerLink"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + partner_link: "partnerLinkValue", + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, "partnerLinkValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userList', async () => { + const fakePath = "/rendered/path/userList"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list: "userListValue", + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, "userListValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListDirectLicense', async () => { + const fakePath = "/rendered/path/userListDirectLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_direct_license: "userListDirectLicenseValue", + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "userListDirectLicenseValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicense', async () => { + const fakePath = "/rendered/path/userListGlobalLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + license_customer_info: "licenseCustomerInfoValue", + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "licenseCustomerInfoValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + }); +}); diff --git a/packages/google-ads-datamanager/test/gapic_user_list_direct_license_service_v1.ts b/packages/google-ads-datamanager/test/gapic_user_list_direct_license_service_v1.ts new file mode 100644 index 00000000000..7a0268de80f --- /dev/null +++ b/packages/google-ads-datamanager/test/gapic_user_list_direct_license_service_v1.ts @@ -0,0 +1,1113 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as userlistdirectlicenseserviceModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.UserListDirectLicenseServiceClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.userListDirectLicenseServiceStub, undefined); + await client.initialize(); + assert(client.userListDirectLicenseServiceStub); + }); + + it('has close method for the initialized client', done => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.userListDirectLicenseServiceStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.userListDirectLicenseServiceStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createUserListDirectLicense', () => { + it('invokes createUserListDirectLicense without error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense() + ); + client.innerApiCalls.createUserListDirectLicense = stubSimpleCall(expectedResponse); + const [response] = await client.createUserListDirectLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserListDirectLicense without error using callback', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense() + ); + client.innerApiCalls.createUserListDirectLicense = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserListDirectLicense( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListDirectLicense|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserListDirectLicense with error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserListDirectLicense = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.createUserListDirectLicense(request), expectedError); + const actualRequest = (client.innerApiCalls.createUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserListDirectLicense with closed client', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.createUserListDirectLicense(request), expectedError); + }); + }); + + describe('getUserListDirectLicense', () => { + it('invokes getUserListDirectLicense without error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense() + ); + client.innerApiCalls.getUserListDirectLicense = stubSimpleCall(expectedResponse); + const [response] = await client.getUserListDirectLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserListDirectLicense without error using callback', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense() + ); + client.innerApiCalls.getUserListDirectLicense = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserListDirectLicense( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListDirectLicense|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserListDirectLicense with error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserListDirectLicense = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getUserListDirectLicense(request), expectedError); + const actualRequest = (client.innerApiCalls.getUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserListDirectLicense with closed client', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getUserListDirectLicense(request), expectedError); + }); + }); + + describe('updateUserListDirectLicense', () => { + it('invokes updateUserListDirectLicense without error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest() + ); + request.userListDirectLicense ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', ['userListDirectLicense', 'name']); + request.userListDirectLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense() + ); + client.innerApiCalls.updateUserListDirectLicense = stubSimpleCall(expectedResponse); + const [response] = await client.updateUserListDirectLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserListDirectLicense without error using callback', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest() + ); + request.userListDirectLicense ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', ['userListDirectLicense', 'name']); + request.userListDirectLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense() + ); + client.innerApiCalls.updateUserListDirectLicense = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUserListDirectLicense( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListDirectLicense|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserListDirectLicense with error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest() + ); + request.userListDirectLicense ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', ['userListDirectLicense', 'name']); + request.userListDirectLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUserListDirectLicense = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.updateUserListDirectLicense(request), expectedError); + const actualRequest = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserListDirectLicense with closed client', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest() + ); + request.userListDirectLicense ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', ['userListDirectLicense', 'name']); + request.userListDirectLicense.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.updateUserListDirectLicense(request), expectedError); + }); + }); + + describe('listUserListDirectLicenses', () => { + it('invokes listUserListDirectLicenses without error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + ]; + client.innerApiCalls.listUserListDirectLicenses = stubSimpleCall(expectedResponse); + const [response] = await client.listUserListDirectLicenses(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListDirectLicenses without error using callback', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + ]; + client.innerApiCalls.listUserListDirectLicenses = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserListDirectLicenses( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListDirectLicense[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListDirectLicenses with error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserListDirectLicenses = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUserListDirectLicenses(request), expectedError); + const actualRequest = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListDirectLicensesStream without error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + ]; + client.descriptors.page.listUserListDirectLicenses.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listUserListDirectLicensesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListDirectLicense[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.UserListDirectLicense) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listUserListDirectLicenses.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listUserListDirectLicenses, request)); + assert( + (client.descriptors.page.listUserListDirectLicenses.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listUserListDirectLicensesStream with error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListDirectLicenses.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listUserListDirectLicensesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListDirectLicense[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.UserListDirectLicense) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listUserListDirectLicenses.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listUserListDirectLicenses, request)); + assert( + (client.descriptors.page.listUserListDirectLicenses.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listUserListDirectLicenses without error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), + ]; + client.descriptors.page.listUserListDirectLicenses.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IUserListDirectLicense[] = []; + const iterable = client.listUserListDirectLicensesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listUserListDirectLicenses.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listUserListDirectLicenses.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listUserListDirectLicenses with error', async () => { + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListDirectLicenses.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUserListDirectLicensesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IUserListDirectLicense[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listUserListDirectLicenses.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listUserListDirectLicenses.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); + + describe('Path templates', () => { + + describe('account', async () => { + const fakePath = "/rendered/path/account"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + }; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.accountPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath("accountTypeValue", "accountValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromAccountName', () => { + const result = client.matchAccountTypeFromAccountName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('partnerLink', async () => { + const fakePath = "/rendered/path/partnerLink"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + partner_link: "partnerLinkValue", + }; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, "partnerLinkValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userList', async () => { + const fakePath = "/rendered/path/userList"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list: "userListValue", + }; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, "userListValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListDirectLicense', async () => { + const fakePath = "/rendered/path/userListDirectLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_direct_license: "userListDirectLicenseValue", + }; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "userListDirectLicenseValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicense', async () => { + const fakePath = "/rendered/path/userListGlobalLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + }; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + license_customer_info: "licenseCustomerInfoValue", + }; + const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "licenseCustomerInfoValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + }); +}); diff --git a/packages/google-ads-datamanager/test/gapic_user_list_global_license_service_v1.ts b/packages/google-ads-datamanager/test/gapic_user_list_global_license_service_v1.ts new file mode 100644 index 00000000000..22cc88ec5fb --- /dev/null +++ b/packages/google-ads-datamanager/test/gapic_user_list_global_license_service_v1.ts @@ -0,0 +1,1358 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as userlistgloballicenseserviceModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.UserListGlobalLicenseServiceClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.userListGlobalLicenseServiceStub, undefined); + await client.initialize(); + assert(client.userListGlobalLicenseServiceStub); + }); + + it('has close method for the initialized client', done => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.userListGlobalLicenseServiceStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.userListGlobalLicenseServiceStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('createUserListGlobalLicense', () => { + it('invokes createUserListGlobalLicense without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense() + ); + client.innerApiCalls.createUserListGlobalLicense = stubSimpleCall(expectedResponse); + const [response] = await client.createUserListGlobalLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserListGlobalLicense without error using callback', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense() + ); + client.innerApiCalls.createUserListGlobalLicense = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserListGlobalLicense( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserListGlobalLicense with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserListGlobalLicense = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.createUserListGlobalLicense(request), expectedError); + const actualRequest = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserListGlobalLicense with closed client', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.createUserListGlobalLicense(request), expectedError); + }); + }); + + describe('updateUserListGlobalLicense', () => { + it('invokes updateUserListGlobalLicense without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest() + ); + request.userListGlobalLicense ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', ['userListGlobalLicense', 'name']); + request.userListGlobalLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense() + ); + client.innerApiCalls.updateUserListGlobalLicense = stubSimpleCall(expectedResponse); + const [response] = await client.updateUserListGlobalLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserListGlobalLicense without error using callback', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest() + ); + request.userListGlobalLicense ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', ['userListGlobalLicense', 'name']); + request.userListGlobalLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense() + ); + client.innerApiCalls.updateUserListGlobalLicense = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUserListGlobalLicense( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserListGlobalLicense with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest() + ); + request.userListGlobalLicense ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', ['userListGlobalLicense', 'name']); + request.userListGlobalLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUserListGlobalLicense = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.updateUserListGlobalLicense(request), expectedError); + const actualRequest = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserListGlobalLicense with closed client', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest() + ); + request.userListGlobalLicense ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', ['userListGlobalLicense', 'name']); + request.userListGlobalLicense.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.updateUserListGlobalLicense(request), expectedError); + }); + }); + + describe('getUserListGlobalLicense', () => { + it('invokes getUserListGlobalLicense without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense() + ); + client.innerApiCalls.getUserListGlobalLicense = stubSimpleCall(expectedResponse); + const [response] = await client.getUserListGlobalLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserListGlobalLicense without error using callback', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense() + ); + client.innerApiCalls.getUserListGlobalLicense = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserListGlobalLicense( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserListGlobalLicense with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserListGlobalLicense = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getUserListGlobalLicense(request), expectedError); + const actualRequest = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserListGlobalLicense with closed client', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getUserListGlobalLicense(request), expectedError); + }); + }); + + describe('listUserListGlobalLicenses', () => { + it('invokes listUserListGlobalLicenses without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + ]; + client.innerApiCalls.listUserListGlobalLicenses = stubSimpleCall(expectedResponse); + const [response] = await client.listUserListGlobalLicenses(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListGlobalLicenses without error using callback', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + ]; + client.innerApiCalls.listUserListGlobalLicenses = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserListGlobalLicenses( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListGlobalLicenses with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserListGlobalLicenses = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUserListGlobalLicenses(request), expectedError); + const actualRequest = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListGlobalLicensesStream without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + ]; + client.descriptors.page.listUserListGlobalLicenses.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listUserListGlobalLicensesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListGlobalLicense[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.UserListGlobalLicense) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listUserListGlobalLicenses.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listUserListGlobalLicenses, request)); + assert( + (client.descriptors.page.listUserListGlobalLicenses.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listUserListGlobalLicensesStream with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListGlobalLicenses.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listUserListGlobalLicensesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListGlobalLicense[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.UserListGlobalLicense) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listUserListGlobalLicenses.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listUserListGlobalLicenses, request)); + assert( + (client.descriptors.page.listUserListGlobalLicenses.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listUserListGlobalLicenses without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), + ]; + client.descriptors.page.listUserListGlobalLicenses.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicense[] = []; + const iterable = client.listUserListGlobalLicensesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listUserListGlobalLicenses.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listUserListGlobalLicenses.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listUserListGlobalLicenses with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListGlobalLicenses.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUserListGlobalLicensesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicense[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listUserListGlobalLicenses.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listUserListGlobalLicenses.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); + + describe('listUserListGlobalLicenseCustomerInfos', () => { + it('invokes listUserListGlobalLicenseCustomerInfos without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + ]; + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = stubSimpleCall(expectedResponse); + const [response] = await client.listUserListGlobalLicenseCustomerInfos(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListGlobalLicenseCustomerInfos without error using callback', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + ]; + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserListGlobalLicenseCustomerInfos( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListGlobalLicenseCustomerInfos with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUserListGlobalLicenseCustomerInfos(request), expectedError); + const actualRequest = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListGlobalLicenseCustomerInfosStream without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + ]; + client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listUserListGlobalLicenseCustomerInfosStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listUserListGlobalLicenseCustomerInfos, request)); + assert( + (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listUserListGlobalLicenseCustomerInfosStream with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listUserListGlobalLicenseCustomerInfosStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listUserListGlobalLicenseCustomerInfos, request)); + assert( + (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listUserListGlobalLicenseCustomerInfos without error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), + ]; + client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[] = []; + const iterable = client.listUserListGlobalLicenseCustomerInfosAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listUserListGlobalLicenseCustomerInfos with error', async () => { + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUserListGlobalLicenseCustomerInfosAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); + + describe('Path templates', () => { + + describe('account', async () => { + const fakePath = "/rendered/path/account"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + }; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.accountPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath("accountTypeValue", "accountValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromAccountName', () => { + const result = client.matchAccountTypeFromAccountName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('partnerLink', async () => { + const fakePath = "/rendered/path/partnerLink"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + partner_link: "partnerLinkValue", + }; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, "partnerLinkValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userList', async () => { + const fakePath = "/rendered/path/userList"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list: "userListValue", + }; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, "userListValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListDirectLicense', async () => { + const fakePath = "/rendered/path/userListDirectLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_direct_license: "userListDirectLicenseValue", + }; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "userListDirectLicenseValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicense', async () => { + const fakePath = "/rendered/path/userListGlobalLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + }; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + license_customer_info: "licenseCustomerInfoValue", + }; + const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "licenseCustomerInfoValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + }); +}); diff --git a/packages/google-ads-datamanager/test/gapic_user_list_service_v1.ts b/packages/google-ads-datamanager/test/gapic_user_list_service_v1.ts new file mode 100644 index 00000000000..be3072a90ac --- /dev/null +++ b/packages/google-ads-datamanager/test/gapic_user_list_service_v1.ts @@ -0,0 +1,1221 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as userlistserviceModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1.UserListServiceClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new userlistserviceModule.v1.UserListServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new userlistserviceModule.v1.UserListServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = userlistserviceModule.v1.UserListServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = userlistserviceModule.v1.UserListServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new userlistserviceModule.v1.UserListServiceClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new userlistserviceModule.v1.UserListServiceClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new userlistserviceModule.v1.UserListServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new userlistserviceModule.v1.UserListServiceClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new userlistserviceModule.v1.UserListServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = userlistserviceModule.v1.UserListServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new userlistserviceModule.v1.UserListServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.userListServiceStub, undefined); + await client.initialize(); + assert(client.userListServiceStub); + }); + + it('has close method for the initialized client', done => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.userListServiceStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.userListServiceStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getUserList', () => { + it('invokes getUserList without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList() + ); + client.innerApiCalls.getUserList = stubSimpleCall(expectedResponse); + const [response] = await client.getUserList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserList without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList() + ); + client.innerApiCalls.getUserList = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserList( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserList|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserList with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserList = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getUserList(request), expectedError); + const actualRequest = (client.innerApiCalls.getUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserList with closed client', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getUserList(request), expectedError); + }); + }); + + describe('createUserList', () => { + it('invokes createUserList without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList() + ); + client.innerApiCalls.createUserList = stubSimpleCall(expectedResponse); + const [response] = await client.createUserList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserList without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList() + ); + client.innerApiCalls.createUserList = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserList( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserList|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserList with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserList = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.createUserList(request), expectedError); + const actualRequest = (client.innerApiCalls.createUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createUserList with closed client', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.createUserList(request), expectedError); + }); + }); + + describe('updateUserList', () => { + it('invokes updateUserList without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListRequest() + ); + request.userList ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListRequest', ['userList', 'name']); + request.userList.name = defaultValue1; + const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList() + ); + client.innerApiCalls.updateUserList = stubSimpleCall(expectedResponse); + const [response] = await client.updateUserList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserList without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListRequest() + ); + request.userList ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListRequest', ['userList', 'name']); + request.userList.name = defaultValue1; + const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList() + ); + client.innerApiCalls.updateUserList = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUserList( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserList|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserList with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListRequest() + ); + request.userList ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListRequest', ['userList', 'name']); + request.userList.name = defaultValue1; + const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUserList = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.updateUserList(request), expectedError); + const actualRequest = (client.innerApiCalls.updateUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateUserList with closed client', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListRequest() + ); + request.userList ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListRequest', ['userList', 'name']); + request.userList.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.updateUserList(request), expectedError); + }); + }); + + describe('deleteUserList', () => { + it('invokes deleteUserList without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeleteUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.DeleteUserListRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteUserList = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUserList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteUserList without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeleteUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.DeleteUserListRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteUserList = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUserList( + request, + (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteUserList with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeleteUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.DeleteUserListRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUserList = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteUserList(request), expectedError); + const actualRequest = (client.innerApiCalls.deleteUserList as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteUserList as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteUserList with closed client', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeleteUserListRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.DeleteUserListRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.deleteUserList(request), expectedError); + }); + }); + + describe('listUserLists', () => { + it('invokes listUserLists without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + ]; + client.innerApiCalls.listUserLists = stubSimpleCall(expectedResponse); + const [response] = await client.listUserLists(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserLists as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserLists as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserLists without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + ]; + client.innerApiCalls.listUserLists = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserLists( + request, + (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserList[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserLists as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserLists as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserLists with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserLists = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUserLists(request), expectedError); + const actualRequest = (client.innerApiCalls.listUserLists as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserLists as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listUserListsStream without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + ]; + client.descriptors.page.listUserLists.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listUserListsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserList[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.UserList) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listUserLists.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listUserLists, request)); + assert( + (client.descriptors.page.listUserLists.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listUserListsStream with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserLists.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listUserListsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserList[] = []; + stream.on('data', (response: protos.google.ads.datamanager.v1.UserList) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listUserLists.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listUserLists, request)); + assert( + (client.descriptors.page.listUserLists.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listUserLists without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + ]; + client.descriptors.page.listUserLists.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IUserList[] = []; + const iterable = client.listUserListsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listUserLists.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listUserLists.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listUserLists with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserLists.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUserListsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IUserList[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listUserLists.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listUserLists.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); + + describe('Path templates', () => { + + describe('account', async () => { + const fakePath = "/rendered/path/account"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.accountPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath("accountTypeValue", "accountValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromAccountName', () => { + const result = client.matchAccountTypeFromAccountName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('partnerLink', async () => { + const fakePath = "/rendered/path/partnerLink"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + partner_link: "partnerLinkValue", + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, "partnerLinkValue"); + assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userList', async () => { + const fakePath = "/rendered/path/userList"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list: "userListValue", + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, "userListValue"); + assert((client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListDirectLicense', async () => { + const fakePath = "/rendered/path/userListDirectLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_direct_license: "userListDirectLicenseValue", + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, "userListDirectLicenseValue"); + assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicense', async () => { + const fakePath = "/rendered/path/userListGlobalLicense"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; + const expectedParameters = { + account_type: "accountTypeValue", + account: "accountValue", + user_list_global_license: "userListGlobalLicenseValue", + license_customer_info: "licenseCustomerInfoValue", + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountTypeValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "accountValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "userListGlobalLicenseValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); + assert.strictEqual(result, "licenseCustomerInfoValue"); + assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + }); +}); diff --git a/packages/google-cloud-aiplatform/CHANGELOG.md b/packages/google-cloud-aiplatform/CHANGELOG.md index 6d919e968bf..8222629d192 100644 --- a/packages/google-cloud-aiplatform/CHANGELOG.md +++ b/packages/google-cloud-aiplatform/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [6.5.0](https://github.com/googleapis/google-cloud-node/compare/aiplatform-v6.4.0...aiplatform-v6.5.0) (2026-03-02) + + +### Features + +* Add `traffic_type, tool_use_prompt_tokens_details` to message `GenerateContentResponse.UsageMetadata` ([#7266](https://github.com/googleapis/google-cloud-node/issues/7266)) ([9f91e05](https://github.com/googleapis/google-cloud-node/commit/9f91e0513bf7a60239aef5e4222993184c63fbb2)) + ## [6.4.0](https://github.com/googleapis/google-cloud-node/compare/aiplatform-v6.3.0...aiplatform-v6.4.0) (2026-02-03) diff --git a/packages/google-cloud-aiplatform/package.json b/packages/google-cloud-aiplatform/package.json index 68e635900c0..58310014208 100644 --- a/packages/google-cloud-aiplatform/package.json +++ b/packages/google-cloud-aiplatform/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/aiplatform", - "version": "6.4.0", + "version": "6.5.0", "description": "Vertex AI client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-aiplatform/samples/package.json b/packages/google-cloud-aiplatform/samples/package.json index 07b86b99b79..3d098a20d1b 100644 --- a/packages/google-cloud-aiplatform/samples/package.json +++ b/packages/google-cloud-aiplatform/samples/package.json @@ -13,7 +13,7 @@ "test": "mocha --timeout 1200000 test/*.js" }, "dependencies": { - "@google-cloud/aiplatform": "^6.4.0" + "@google-cloud/aiplatform": "^6.5.0" }, "devDependencies": { "chai": "^4.2.0", diff --git a/packages/google-cloud-ces/CHANGELOG.md b/packages/google-cloud-ces/CHANGELOG.md new file mode 100644 index 00000000000..1151d3be505 --- /dev/null +++ b/packages/google-cloud-ces/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +## 0.1.0 (2026-03-02) + + +### Features + +* [ces] add public libraries for CES v1beta ([#7285](https://github.com/googleapis/google-cloud-node/issues/7285)) ([77042f5](https://github.com/googleapis/google-cloud-node/commit/77042f508c0e4d03569ef4eae7e0dd8f235cd469)) +* Add initial files for google.cloud.ces.v1 ([#7241](https://github.com/googleapis/google-cloud-node/issues/7241)) ([9146f27](https://github.com/googleapis/google-cloud-node/commit/9146f2714244d2e7c50220ccb4380b738acab857)) + + +### Bug Fixes + +* [gkeconnect-gateway] remove unused GatewayServiceClient ([#6775](https://github.com/googleapis/google-cloud-node/issues/6775)) ([41c2ff2](https://github.com/googleapis/google-cloud-node/commit/41c2ff2851b5fdadabf4f9bd3500167c34b32ff7)) diff --git a/packages/google-cloud-ces/package.json b/packages/google-cloud-ces/package.json index ebe9ee900b4..3b59309a285 100644 --- a/packages/google-cloud-ces/package.json +++ b/packages/google-cloud-ces/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/ces", - "version": "0.0.0", + "version": "0.1.0", "description": "Gemini Enterprise for Customer Experience API client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-ces/protos/google/cloud/ces/v1beta/deployment.proto b/packages/google-cloud-ces/protos/google/cloud/ces/v1beta/deployment.proto index 988fefd735f..9df98b98e32 100644 --- a/packages/google-cloud-ces/protos/google/cloud/ces/v1beta/deployment.proto +++ b/packages/google-cloud-ces/protos/google/cloud/ces/v1beta/deployment.proto @@ -38,17 +38,19 @@ message Deployment { // Identifier. The resource name of the deployment. // Format: - // projects/{project}/locations/{location}/apps/{app}/deployments/{deployment} + // `projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}` string name = 1 [(google.api.field_behavior) = IDENTIFIER]; // Required. Display name of the deployment. string display_name = 8 [(google.api.field_behavior) = REQUIRED]; - // Required. The resource name of the app version to deploy. + // Optional. The resource name of the app version to deploy. // Format: - // projects/{project}/locations/{location}/apps/{app}/versions/{version} + // `projects/{project}/locations/{location}/apps/{app}/versions/{version}` + // Use `projects/{project}/locations/{location}/apps/{app}/versions/-` to use + // the draft app. string app_version = 2 [ - (google.api.field_behavior) = REQUIRED, + (google.api.field_behavior) = OPTIONAL, (google.api.resource_reference) = { type: "ces.googleapis.com/AppVersion" } ]; diff --git a/packages/google-cloud-ces/protos/google/cloud/ces/v1beta/session_service.proto b/packages/google-cloud-ces/protos/google/cloud/ces/v1beta/session_service.proto index d6d235d4902..b0ab0ccdf87 100644 --- a/packages/google-cloud-ces/protos/google/cloud/ces/v1beta/session_service.proto +++ b/packages/google-cloud-ces/protos/google/cloud/ces/v1beta/session_service.proto @@ -445,7 +445,7 @@ message BidiSessionServerMessage { RecognitionResult recognition_result = 2 [(google.api.field_behavior) = OPTIONAL]; - // Optional. Interruption signal detected from the audio input. + // Optional. Indicates the agent's audio response has been interrupted. InterruptionSignal interruption_signal = 3 [(google.api.field_behavior) = OPTIONAL]; diff --git a/packages/google-cloud-ces/protos/protos.json b/packages/google-cloud-ces/protos/protos.json index 201e3b6d4d3..01ab37ffa53 100644 --- a/packages/google-cloud-ces/protos/protos.json +++ b/packages/google-cloud-ces/protos/protos.json @@ -14846,7 +14846,7 @@ "type": "string", "id": 2, "options": { - "(google.api.field_behavior)": "REQUIRED", + "(google.api.field_behavior)": "OPTIONAL", "(google.api.resource_reference).type": "ces.googleapis.com/AppVersion" } }, diff --git a/packages/google-cloud-compute/CHANGELOG.md b/packages/google-cloud-compute/CHANGELOG.md index 33f998881fe..3ecb7764740 100644 --- a/packages/google-cloud-compute/CHANGELOG.md +++ b/packages/google-cloud-compute/CHANGELOG.md @@ -4,6 +4,14 @@ [1]: https://www.npmjs.com/package/@google-cloud/compute?activeTab=versions +## [6.8.0](https://github.com/googleapis/google-cloud-node/compare/compute-v6.7.0...compute-v6.8.0) (2026-03-02) + + +### Features + +* [compute] Update Compute Engine v1beta API to revision 20260106 ([#1147](https://github.com/googleapis/google-cloud-node/issues/1147)) ([#7272](https://github.com/googleapis/google-cloud-node/issues/7272)) ([2d1a22c](https://github.com/googleapis/google-cloud-node/commit/2d1a22c828cd8dfecb2083d3bc270210a79a41e3)) +* [compute] Update Compute Engine v1beta API to revision 20260213 ([#7296](https://github.com/googleapis/google-cloud-node/issues/7296)) ([1bacdf2](https://github.com/googleapis/google-cloud-node/commit/1bacdf222c3995c0b3e44d972c952645367e3fa0)) + ## [6.7.0](https://github.com/googleapis/google-cloud-node/compare/compute-v6.6.0...compute-v6.7.0) (2026-01-16) diff --git a/packages/google-cloud-compute/README.md b/packages/google-cloud-compute/README.md index 1c8a45e3005..a55b1c4b847 100644 --- a/packages/google-cloud-compute/README.md +++ b/packages/google-cloud-compute/README.md @@ -1154,6 +1154,7 @@ Samples are in the [`samples/`][homepage_samples] directory. Each sample's `READ | abandon instances | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.abandon_instances.js) | | aggregated list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.aggregated_list.js) | | apply updates to instances | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.apply_updates_to_instances.js) | +| configure accelerator topologies | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.configure_accelerator_topologies.js) | | create instances | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.create_instances.js) | | delete | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.delete.js) | | delete instances | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.delete_instances.js) | @@ -1256,6 +1257,13 @@ Samples are in the [`samples/`][homepage_samples] directory. Each sample's `READ | update network interface | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instances.update_network_interface.js) | | update shielded instance config | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instances.update_shielded_instance_config.js) | | update shielded vm config | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instances.update_shielded_vm_config.js) | +| delete | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.delete.js) | +| get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.get.js) | +| get iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.get_iam_policy.js) | +| insert | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.insert.js) | +| list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.list.js) | +| set iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.set_iam_policy.js) | +| test iam permissions | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.test_iam_permissions.js) | | aggregated list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshots.aggregated_list.js) | | delete | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshots.delete.js) | | get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshots.get.js) | @@ -1601,6 +1609,13 @@ Samples are in the [`samples/`][homepage_samples] directory. Each sample's `READ | insert | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instance_templates.insert.js) | | list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instance_templates.list.js) | | bulk insert | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instances.bulk_insert.js) | +| delete | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.delete.js) | +| get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.get.js) | +| get iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.get_iam_policy.js) | +| insert | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.insert.js) | +| list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.list.js) | +| set iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.set_iam_policy.js) | +| test iam permissions | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.test_iam_permissions.js) | | delete | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshots.delete.js) | | get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshots.get.js) | | get iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshots.get_iam_policy.js) | @@ -1731,6 +1746,9 @@ Samples are in the [`samples/`][homepage_samples] directory. Each sample's `READ | perform maintenance | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_blocks.perform_maintenance.js) | | set iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_blocks.set_iam_policy.js) | | test iam permissions | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_blocks.test_iam_permissions.js) | +| get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.get.js) | +| list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.list.js) | +| update | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.update.js) | | get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_sub_blocks.get.js) | | get iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_sub_blocks.get_iam_policy.js) | | list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/reservation_sub_blocks.list.js) | @@ -1768,8 +1786,10 @@ Samples are in the [`samples/`][homepage_samples] directory. Each sample's `READ | list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/rollouts.list.js) | | aggregated list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.aggregated_list.js) | | delete | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.delete.js) | +| delete named set | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.delete_named_set.js) | | delete route policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.delete_route_policy.js) | | get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.get.js) | +| get named set | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.get_named_set.js) | | get nat ip info | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.get_nat_ip_info.js) | | get nat mapping info | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.get_nat_mapping_info.js) | | get route policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.get_route_policy.js) | @@ -1777,12 +1797,15 @@ Samples are in the [`samples/`][homepage_samples] directory. Each sample's `READ | insert | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.insert.js) | | list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.list.js) | | list bgp routes | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.list_bgp_routes.js) | +| list named sets | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.list_named_sets.js) | | list route policies | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.list_route_policies.js) | | patch | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.patch.js) | +| patch named set | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.patch_named_set.js) | | patch route policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.patch_route_policy.js) | | preview | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.preview.js) | | test iam permissions | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.test_iam_permissions.js) | | update | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.update.js) | +| update named set | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.update_named_set.js) | | update route policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routers.update_route_policy.js) | | delete | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routes.delete.js) | | get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/routes.get.js) | @@ -1811,6 +1834,13 @@ Samples are in the [`samples/`][homepage_samples] directory. Each sample's `READ | patch | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/service_attachments.patch.js) | | set iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/service_attachments.set_iam_policy.js) | | test iam permissions | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/service_attachments.test_iam_permissions.js) | +| delete | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.delete.js) | +| get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.get.js) | +| get iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.get_iam_policy.js) | +| insert | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.insert.js) | +| list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.list.js) | +| set iam policy | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.set_iam_policy.js) | +| test iam permissions | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.test_iam_permissions.js) | | get | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_settings_service.get.js) | | patch | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshot_settings_service.patch.js) | | aggregated list | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-compute/samples/generated/v1beta/snapshots.aggregated_list.js) | diff --git a/packages/google-cloud-compute/package.json b/packages/google-cloud-compute/package.json index eb80f630992..1f2953d164b 100644 --- a/packages/google-cloud-compute/package.json +++ b/packages/google-cloud-compute/package.json @@ -1,7 +1,7 @@ { "name": "@google-cloud/compute", "description": "Google Compute Engine Client Library for Node.js", - "version": "6.7.0", + "version": "6.8.0", "license": "Apache-2.0", "author": "Google LLC", "engines": { diff --git a/packages/google-cloud-compute/protos/google/cloud/compute/v1beta/compute.proto b/packages/google-cloud-compute/protos/google/cloud/compute/v1beta/compute.proto index 6ac64a97d78..85989bb8a3d 100644 --- a/packages/google-cloud-compute/protos/google/cloud/compute/v1beta/compute.proto +++ b/packages/google-cloud-compute/protos/google/cloud/compute/v1beta/compute.proto @@ -14,7 +14,7 @@ // Generated by the disco-to-proto3-converter. DO NOT EDIT! // Source Discovery file: compute.v1beta.json -// Source file revision: 20260106 +// Source file revision: 20260213 // API name: compute // API version: v1beta @@ -8030,7 +8030,7 @@ message AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk { } // Properties of the SKU instances being reserved. -// Next ID: 9 +// Next ID: 10 message AllocationSpecificSKUAllocationReservedInstanceProperties { // Specifies the frequency of planned maintenance events. The accepted // values are: `PERIODIC`. @@ -8609,9 +8609,6 @@ message AttachedDisk { // Check the Type enum for the list of possible values. optional string type = 3575610; - // Output only. [Output Only] A list of user provided licenses. It represents a list of - // URLs to the license resource. Unlike regular licenses, user provided - // licenses can be modified after the disk is created. repeated string user_licenses = 388193862; } @@ -8749,7 +8746,7 @@ message AttachedDiskInitializeParams { // as the instance zone. repeated string replica_zones = 48438272; - // Resource manager tags to be bound to the disk. Tag keys and values + // Input only. Resource manager tags to be bound to the disk. Tag keys and values // have the same definition as resource // manager tags. Keys and values can be either in numeric format, // such as `tagKeys/{tag_key_id}` and `tagValues/456` or in namespaced @@ -9910,6 +9907,9 @@ message Backend { // balancing mode. optional float max_utilization = 148192199; + // Information about the resource or system that manages the backend. + optional BackendBackendOrchestrationInfo orchestration_info = 441144300; + // This field indicates whether this backend should be fully utilized before // sending traffic to backends with default preference. The possible values // are: @@ -9929,6 +9929,14 @@ message Backend { } +// A message containing information about the resource or system that manages +// the backend. +message BackendBackendOrchestrationInfo { + // The URI of the resource or system that manages the backend. + optional string resource_uri = 152830395; + +} + // Represents a Cloud Storage Bucket resource. // // This Cloud Storage bucket resource is referenced by a URL map of a load @@ -11107,6 +11115,9 @@ message BackendService { // networkPassThroughLbTrafficPolicy cannot be specified with haPolicy. optional BackendServiceNetworkPassThroughLbTrafficPolicy network_pass_through_lb_traffic_policy = 230323750; + // Information about the resource or system that manages the backend service. + optional BackendServiceOrchestrationInfo orchestration_info = 441144300; + // Settings controlling the ejection of unhealthy backend endpoints from the // load balancing pool of each individual proxy instance that processes the // traffic for the given backend service. If not set, this feature is @@ -12248,6 +12259,15 @@ message BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity { } +// A message containing information about the resource or system that manages +// the backend service. +message BackendServiceOrchestrationInfo { + // The resource URI of the resource or system that manages the backend + // service. + optional string resource_uri = 152830395; + +} + // Additional Backend Service parameters. message BackendServiceParams { // Tag keys/values directly bound to this resource. @@ -12850,6 +12870,12 @@ message BulkInsertDiskRequest { // compute.regionDisks.bulkInsert. It is only used to process // requests and is not persisted. message BulkInsertDiskResource { + // The parameters for the instant snapshot group. + optional InstantSnapshotGroupParameters instant_snapshot_group_parameters = 17051623; + + // The parameters for the snapshot group. + optional SnapshotGroupParameters snapshot_group_parameters = 42252485; + // The URL of the DiskConsistencyGroupPolicy for the group of disks to clone. // This may be a full or partial URL, such as: // @@ -13210,6 +13236,213 @@ message CacheKeyPolicy { } +// Message containing CachePolicy configuration for URL Map's Route Action. +message CachePolicy { + // Specifies the cache setting for all responses from this route. + // If not specified, the default value is CACHE_ALL_STATIC. + enum CacheMode { + // A value indicating that the enum field is not set. + UNDEFINED_CACHE_MODE = 0; + + // Automatically cache static content, including common image formats, + // media (video and audio), and web assets (JavaScript and CSS). + // Requests and responses that are marked as uncacheable, as well as + // dynamic content (including HTML), will not be cached. + CACHE_ALL_STATIC = 355027945; + + // Cache all content, ignoring any "private", "no-store" or "no-cache" + // directives in Cache-Control response headers. + // Warning: this may result in Cloud CDN caching private, + // per-user (user identifiable) content. + FORCE_CACHE_ALL = 486026928; + + // Requires the origin to set valid caching headers to cache content. + // Responses without these headers will not be cached at the edge, and will + // require a full trip to the origin on every request, potentially impacting + // performance and increasing load on the origin server. + USE_ORIGIN_HEADERS = 55380261; + + } + + // Bypass the cache when the specified request headers are matched by name, + // e.g. Pragma or Authorization headers. Values are case-insensitive. Up to 5 + // header names can be specified. The cache is bypassed for all + // cachePolicy.cacheMode settings. + repeated string cache_bypass_request_header_names = 197581440; + + // The CacheKeyPolicy for this CachePolicy. + optional CachePolicyCacheKeyPolicy cache_key_policy = 159263727; + + // Specifies the cache setting for all responses from this route. + // If not specified, the default value is CACHE_ALL_STATIC. + // Check the CacheMode enum for the list of possible values. + optional string cache_mode = 28877888; + + // Specifies a separate client (e.g. browser client) maximum TTL. This is + // used to clamp the max-age (or Expires) value sent to the client. With + // FORCE_CACHE_ALL, the lesser of client_ttl and default_ttl is used for the + // response max-age directive, along with a "public" directive. For + // cacheable content in CACHE_ALL_STATIC mode, client_ttl clamps the max-age + // from the origin (if specified), or else sets the response max-age + // directive to the lesser of the client_ttl and default_ttl, and also + // ensures a "public" cache-control directive is present. + // If a client TTL is not specified, a default value (1 hour) will be used. + // The maximum allowed value is 31,622,400s (1 year). + optional Duration client_ttl = 29034360; + + // Specifies the default TTL for cached content served by this origin for + // responses that do not have an existing valid TTL (max-age or s-maxage). + // Setting a TTL of "0" means "always revalidate". + // The value of defaultTTL cannot be set to a value greater than that of + // maxTTL. + // When the cacheMode is set to FORCE_CACHE_ALL, the defaultTTL + // will overwrite the TTL set in all responses. The maximum allowed value is + // 31,622,400s (1 year). Infrequently accessed objects may be evicted from + // the cache before the defined TTL. + optional Duration default_ttl = 100253422; + + // Specifies the maximum allowed TTL for cached content served by this + // origin. + // Cache directives that attempt to set a max-age or s-maxage higher than + // this, or an Expires header more than maxTTL seconds in the future will + // be capped at the value of maxTTL, as if it were the value of an + // s-maxage Cache-Control directive. + // Headers sent to the client will not be modified. + // Setting a TTL of "0" means "always revalidate". + // The maximum allowed value is 31,622,400s (1 year). Infrequently accessed + // objects may be evicted from the cache before the defined TTL. + optional Duration max_ttl = 307578001; + + // Negative caching allows per-status code TTLs to be set, in order + // to apply fine-grained caching for common errors or redirects. + // This can reduce the load on your origin and improve end-user + // experience by reducing response latency. + // When the cache mode is set to CACHE_ALL_STATIC or USE_ORIGIN_HEADERS, + // negative caching applies to responses with the specified response code + // that lack any Cache-Control, Expires, or Pragma: no-cache directives. + // When the cache mode is set to FORCE_CACHE_ALL, negative caching applies + // to all responses with the specified response code, and override any + // caching headers. + // By default, Cloud CDN will apply the following default TTLs to these + // status codes: + // HTTP 300 (Multiple Choice), 301, 308 (Permanent Redirects): 10m + // HTTP 404 (Not Found), 410 (Gone), + // 451 (Unavailable For Legal Reasons): 120s + // HTTP 405 (Method Not Found), 501 (Not Implemented): 60s. + // These defaults can be overridden in negative_caching_policy. + optional bool negative_caching = 336110005; + + // Sets a cache TTL for the specified HTTP status code. + // negative_caching must be enabled to configure negative_caching_policy. + // Omitting the policy and leaving negative_caching enabled will use + // Cloud CDN's default cache TTLs. + // Note that when specifying an explicit negative_caching_policy, you + // should take care to specify a cache TTL for all response codes + // that you wish to cache. Cloud CDN will not apply any default + // negative caching when a policy exists. + repeated CachePolicyNegativeCachingPolicy negative_caching_policy = 155359996; + + // If true then Cloud CDN will combine multiple concurrent cache fill + // requests into a small number of requests to the origin. + optional bool request_coalescing = 532808276; + + // Serve existing content from the cache (if available) when revalidating + // content with the origin, or when an error is encountered when refreshing + // the cache. + // This setting defines the default "max-stale" duration for any cached + // responses that do not specify a max-stale directive. Stale responses that + // exceed the TTL configured here will not be served. The default limit + // (max-stale) is 86400s (1 day), which will allow stale content to be + // served up to this limit beyond the max-age (or s-maxage) of a cached + // response. + // The maximum allowed value is 604800 (1 week). + // Set this to zero (0) to disable serve-while-stale. + optional Duration serve_while_stale = 236682203; + +} + +// Message containing what to include in the cache key for a request for Cache +// Policy defined on Route Action. +message CachePolicyCacheKeyPolicy { + // Names of query string parameters to exclude in cache keys. All other + // parameters will be included. Either specify excluded_query_parameters or + // included_query_parameters, not both. '&' and '=' will be percent encoded + // and not treated as delimiters. + // + // Note: This field applies to routes that use backend services. Attempting + // to set it on a route that points exclusively to Backend Buckets will + // result in a configuration error. For routes that point to a Backend + // Bucket, use includedQueryParameters to define which parameters should + // be a part of the cache key. + repeated string excluded_query_parameters = 124896150; + + // If true, requests to different hosts will be cached separately. + // + // Note: This setting is only applicable to routes that use a Backend + // Service. It does not affect requests served by a Backend Bucket, as the + // host is never included in a Backend Bucket's cache key. Attempting to set + // it on a route that points exclusively to Backend Buckets will result in a + // configuration error. + optional bool include_host = 486867679; + + // If true, http and https requests will be cached separately. + // + // Note: This setting is only applicable to routes that use a Backend + // Service. It does not affect requests served by a Backend Bucket, as the + // protocol is never included in a Backend Bucket's cache key. Attempting to + // set on a route that points exclusively to Backend Buckets will result in + // a configuration error. + optional bool include_protocol = 303507535; + + // If true, include query string parameters in the cache key according to + // included_query_parameters and excluded_query_parameters. If neither is + // set, the entire query string will be included. If false, the query string + // will be excluded from the cache key entirely. + // + // Note: This field applies to routes that use backend services. Attempting + // to set it on a route that points exclusively to Backend Buckets will + // result in a configuration error. For routes that point to a Backend + // Bucket, use includedQueryParameters to define which parameters should + // be a part of the cache key. + optional bool include_query_string = 474036639; + + // Allows HTTP cookies (by name) to be used in the cache key. + // The name=value pair will be used in the cache key Cloud CDN generates. + // + // Note: This setting is only applicable to routes that use a Backend + // Service. It does not affect requests served by a Backend Bucket. + // Attempting to set it on a route that points exclusively to Backend + // Buckets will result in a configuration error. Up to 5 cookie names can be + // specified. + repeated string included_cookie_names = 66987088; + + // Allows HTTP request headers (by name) to be used in the cache key. + repeated string included_header_names = 533756345; + + // Names of query string parameters to include in cache keys. All other + // parameters will be excluded. Either specify included_query_parameters or + // excluded_query_parameters, not both. '&' and '=' will be percent encoded + // and not treated as delimiters. + repeated string included_query_parameters = 2319076; + +} + +// Specify CDN TTLs for response error codes. +message CachePolicyNegativeCachingPolicy { + // The HTTP status code to define a TTL against. Only HTTP status codes + // 300, 301, 302, 307, 308, 404, 405, 410, 421, 451 and 501 can be + // specified as values, and you cannot specify a status code more than + // once. + optional int32 code = 3059181; + + // The TTL (in seconds) for which to cache responses with the + // corresponding status code. + // The maximum allowed value is 1800s (30 minutes). Infrequently accessed + // objects may be evicted from the cache before the defined TTL. + optional Duration ttl = 115180; + +} + // A request to recommend the best way to consume the specified resources in the // future. message CalendarModeAdviceRequest { @@ -13689,6 +13922,8 @@ message Commitment { GENERAL_PURPOSE_N4 = 301912158; + GENERAL_PURPOSE_N4A = 232471459; + GENERAL_PURPOSE_N4D = 232471462; GENERAL_PURPOSE_T2D = 232477166; @@ -14107,6 +14342,45 @@ message ConfidentialInstanceConfig { } +// A request message for InstanceGroupManagers.ConfigureAcceleratorTopologies. See the method description for details. +message ConfigureAcceleratorTopologiesInstanceGroupManagerRequest { + // The name of the managed instance group. + // It should conform to RFC1035. + string instance_group_manager = 249363395 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + InstanceGroupManagersConfigureAcceleratorTopologiesRequest instance_group_managers_configure_accelerator_topologies_request_resource = 365743316 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The name of thezone + // where the managed instance group is located. + // It should conform to RFC1035. + string zone = 3744684 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "zone" + ]; + +} + // Message containing connection draining configuration. message ConnectionDraining { // Configures a duration timeout for existing requests on a removed backend @@ -15521,6 +15795,40 @@ message DeleteInstancesRegionInstanceGroupManagerRequest { } +// A request message for InstantSnapshotGroups.Delete. See the method description for details. +message DeleteInstantSnapshotGroupRequest { + // Name of the InstantSnapshot resource to delete. + string instant_snapshot_group = 223180386 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The name of the zone for this request. + string zone = 3744684 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "zone" + ]; + +} + // A request message for InstantSnapshots.Delete. See the method description for details. message DeleteInstantSnapshotRequest { // Name of the InstantSnapshot resource to delete. @@ -15731,6 +16039,43 @@ message DeleteMachineImageRequest { } +// A request message for Routers.DeleteNamedSet. See the method description for details. +message DeleteNamedSetRouterRequest { + // The Named Set name for this request. Name must conform to RFC1035 + optional string named_set = 164134492; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // Name of the region for this request. + string region = 138946292 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "region" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // Name of the Router resource where Named Set is defined. + string router = 148608841 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for NetworkAttachments.Delete. See the method description for details. message DeleteNetworkAttachmentRequest { // Name of the NetworkAttachment resource to delete. @@ -16622,10 +16967,10 @@ message DeleteRegionInstanceTemplateRequest { } -// A request message for RegionInstantSnapshots.Delete. See the method description for details. -message DeleteRegionInstantSnapshotRequest { - // Name of the InstantSnapshot resource to delete. - string instant_snapshot = 391638626 [(google.api.field_behavior) = REQUIRED]; +// A request message for RegionInstantSnapshotGroups.Delete. See the method description for details. +message DeleteRegionInstantSnapshotGroupRequest { + // Name of the InstantSnapshotGroup resource to delete. + string instant_snapshot_group = 223180386 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -16656,10 +17001,10 @@ message DeleteRegionInstantSnapshotRequest { } -// A request message for RegionMultiMigs.Delete. See the method description for details. -message DeleteRegionMultiMigRequest { - // Name of the multi-MIG to delete. - string multi_mig = 403990085 [(google.api.field_behavior) = REQUIRED]; +// A request message for RegionInstantSnapshots.Delete. See the method description for details. +message DeleteRegionInstantSnapshotRequest { + // Name of the InstantSnapshot resource to delete. + string instant_snapshot = 391638626 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -16667,7 +17012,41 @@ message DeleteRegionMultiMigRequest { (google.cloud.operation_request_field) = "project" ]; - // Name of the region for this request. + // The name of the region for this request. + string region = 138946292 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "region" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + +} + +// A request message for RegionMultiMigs.Delete. See the method description for details. +message DeleteRegionMultiMigRequest { + // Name of the multi-MIG to delete. + string multi_mig = 403990085 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // Name of the region for this request. string region = 138946292 [ (google.api.field_behavior) = REQUIRED, (google.cloud.operation_request_field) = "region" @@ -17457,6 +17836,34 @@ message DeleteSignedUrlKeyBackendServiceRequest { } +// A request message for SnapshotGroups.Delete. See the method description for details. +message DeleteSnapshotGroupRequest { + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // Name of the SnapshotGroup resource to delete. + string snapshot_group = 84528196 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for Snapshots.Delete. See the method description for details. message DeleteSnapshotRequest { // Project ID for this request. @@ -18845,12 +19252,6 @@ message Disk { // types. optional string type = 3575610; - // A list of publicly visible user-licenses. Unlike regular licenses, user - // provided licenses can be modified after the disk is created. This includes - // a list of URLs to the license resource. For example, to provide a debian - // license: - // - // https://www.googleapis.com/compute/v1/projects/debian-cloud/global/licenses/debian-9-stretch repeated string user_licenses = 388193862; // Output only. [Output Only] Links to the users of the disk (attached instances) @@ -19075,7 +19476,7 @@ message DiskMoveRequest { // Additional disk params. message DiskParams { - // Resource manager tags to be bound to the disk. Tag keys and values + // Input only. Resource manager tags to be bound to the disk. Tag keys and values // have the same definition as resource // manager tags. Keys and values can be either in numeric format, // such as `tagKeys/{tag_key_id}` and `tagValues/456` or in namespaced @@ -19526,7 +19927,7 @@ message EnableXpnResourceProjectRequest { } -// Output only. Errors that prevented the ResizeRequest to be fulfilled. +// Reason why the topology state change failed message Error { // [Output Only] The array of errors encountered while processing this // operation. @@ -19870,6 +20271,10 @@ message ExternalVpnGateway { // be a dash. optional string name = 3373707; + // Input only. [Input Only] Additional params passed with the request, but not persisted + // as part of resource payload. + optional ExternalVpnGatewayParams params = 78313862; + // Indicates the user-supplied redundancy type of this external VPN gateway. // Check the RedundancyType enum for the list of possible values. optional string redundancy_type = 271443740; @@ -19934,6 +20339,26 @@ message ExternalVpnGatewayList { } +// +message ExternalVpnGatewayParams { + // Tag keys/values directly bound to this resource. + // Tag keys and values have the same definition as resource + // manager tags. The field is allowed for INSERT + // only. The keys/values to set on the resource should be specified in + // either ID { : } or Namespaced format + // { : }. + // For example the following are valid inputs: + // * {"tagKeys/333" : "tagValues/444", "tagKeys/123" : "tagValues/456"} + // * {"123/environment" : "production", "345/abc" : "xyz"} + // Note: + // * Invalid combinations of ID & namespaced format is not supported. For + // instance: {"123/environment" : "tagValues/444"} is invalid. + // * Inconsistent format is not supported. For instance: + // {"tagKeys/333" : "tagValues/444", "123/env" : "prod"} is invalid. + map resource_manager_tags = 377671164; + +} + // message FileContentBuffer { // The file type of source file. @@ -20246,8 +20671,12 @@ message FirewallPolicy { // A value indicating that the enum field is not set. UNDEFINED_POLICY_TYPE = 0; + RDMA_FALCON_POLICY = 66315047; + RDMA_ROCE_POLICY = 148757145; + ULL_POLICY = 100494364; + VPC_POLICY = 74319208; } @@ -20820,9 +21249,7 @@ message FixedOrPercent { } -// A flexible specification of a time range that has 3 points of -// flexibility: (1) a flexible start time, (2) a flexible end time, (3) a -// flexible duration. +// Specifies a flexible time range with flexible start time and duration. // // It is possible to specify a contradictory time range that cannot be matched // by any Interval. This causes a validation error. @@ -21087,14 +21514,6 @@ message ForwardingRule { // endpoint can be accessed from another region. optional bool allow_psc_global_access = 263471819; - // This is used in PSC consumer ForwardingRule to control whether the producer - // is allowed to inject packets into the consumer's network. If set to true, - // the target service attachment must have tunneling enabled and - // TunnelingConfig.RoutingMode set to PACKET_INJECTION - // Non-PSC forwarding rules should not use this field. - // - // This field was never released to any customers and is deprecated and - // will be removed in the future. optional bool allow_psc_packet_injection = 272272565; // Identifies the backend service to which the forwarding rule sends traffic. @@ -21593,6 +22012,10 @@ message FutureReservation { } + // Advanced control for cluster management, applicable only to DENSE + // deployment type future reservations. + optional ReservationAdvancedDeploymentControl advanced_deployment_control = 410618144; + // Aggregate reservation details for the future reservation. optional AllocationAggregateReservation aggregate_reservation = 291567948; @@ -23087,6 +23510,22 @@ message GetIamPolicyInstanceTemplateRequest { } +// A request message for InstantSnapshotGroups.GetIamPolicy. See the method description for details. +message GetIamPolicyInstantSnapshotGroupRequest { + // Requested IAM Policy version. + optional int32 options_requested_policy_version = 499220029; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + + // The name of the zone for this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for InstantSnapshots.GetIamPolicy. See the method description for details. message GetIamPolicyInstantSnapshotRequest { // Requested IAM Policy version. @@ -23264,6 +23703,22 @@ message GetIamPolicyRegionDiskRequest { } +// A request message for RegionInstantSnapshotGroups.GetIamPolicy. See the method description for details. +message GetIamPolicyRegionInstantSnapshotGroupRequest { + // Requested IAM Policy version. + optional int32 options_requested_policy_version = 499220029; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // The name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for RegionInstantSnapshots.GetIamPolicy. See the method description for details. message GetIamPolicyRegionInstantSnapshotRequest { // Requested IAM Policy version. @@ -23398,6 +23853,19 @@ message GetIamPolicyServiceAttachmentRequest { } +// A request message for SnapshotGroups.GetIamPolicy. See the method description for details. +message GetIamPolicySnapshotGroupRequest { + // Requested IAM Policy version. + optional int32 options_requested_policy_version = 499220029; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for Snapshots.GetIamPolicy. See the method description for details. message GetIamPolicySnapshotRequest { // Requested IAM Policy version. @@ -23586,6 +24054,19 @@ message GetInstanceTemplateRequest { } +// A request message for InstantSnapshotGroups.Get. See the method description for details. +message GetInstantSnapshotGroupRequest { + // Name of the InstantSnapshotGroup resource to return. + string instant_snapshot_group = 223180386 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // The name of the zone for this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for InstantSnapshots.Get. See the method description for details. message GetInstantSnapshotRequest { // Name of the InstantSnapshot resource to return. @@ -23715,6 +24196,23 @@ message GetMacsecConfigInterconnectRequest { } +// A request message for Routers.GetNamedSet. See the method description for details. +message GetNamedSetRouterRequest { + // The Named Set name for this request. Name must conform to RFC1035 + optional string named_set = 164134492; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + + // Name of the Router resource to query for the named set. The name should + // conform to RFC1035. + string router = 148608841 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for Routers.GetNatIpInfo. See the method description for details. message GetNatIpInfoRouterRequest { // Name of the nat service to filter the NAT IP information. @@ -24306,6 +24804,19 @@ message GetRegionInstanceTemplateRequest { } +// A request message for RegionInstantSnapshotGroups.Get. See the method description for details. +message GetRegionInstantSnapshotGroupRequest { + // Name of the InstantSnapshotGroup resource to return. + string instant_snapshot_group = 223180386 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // The name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for RegionInstantSnapshots.Get. See the method description for details. message GetRegionInstantSnapshotRequest { // Name of the InstantSnapshot resource to return. @@ -24596,6 +25107,24 @@ message GetReservationRequest { } +// A request message for ReservationSlots.Get. See the method description for details. +message GetReservationSlotRequest { + // The name of the parent reservation and parent block, formatted as + // reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} + string parent_name = 478151936 [(google.api.field_behavior) = REQUIRED]; + + // The project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // The name of the reservation slot, formatted as RFC1035 or a resource ID + // number. + string reservation_slot = 277470865 [(google.api.field_behavior) = REQUIRED]; + + // The name of the zone for this request, formatted as RFC1035. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for ReservationSubBlocks.Get. See the method description for details. message GetReservationSubBlockRequest { // View of the subBlock. @@ -24898,6 +25427,16 @@ message GetShieldedVmIdentityInstanceRequest { } +// A request message for SnapshotGroups.Get. See the method description for details. +message GetSnapshotGroupRequest { + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name of the SnapshotGroup resource to return. + string snapshot_group = 84528196 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for Snapshots.Get. See the method description for details. message GetSnapshotRequest { // Project ID for this request. @@ -27483,6 +28022,10 @@ message HttpRetryPolicy { // message HttpRouteAction { + // Cache policy for this URL Map’s route. Available only for Global + // EXTERNAL_MANAGED load balancer schemes. + optional CachePolicy cache_policy = 457366671; + // The specification for allowing client-side cross-origin requests. For more // information about the W3C recommendation for cross-origin resource sharing // (CORS), see Fetch API Living @@ -28122,12 +28665,6 @@ message Image { // multi-regional). repeated string storage_locations = 328005274; - // A list of publicly visible user-licenses. Unlike regular licenses, user - // provided licenses can be modified after the disk is created. This includes - // a list of URLs to the license resource. For example, to provide a debian - // license: - // - // https://www.googleapis.com/compute/v1/projects/debian-cloud/global/licenses/debian-9-stretch repeated string user_licenses = 388193862; } @@ -28168,7 +28705,7 @@ message ImageList { // Additional image params. message ImageParams { - // Resource manager tags to be bound to the image. Tag keys and values have + // Input only. Resource manager tags to be bound to the image. Tag keys and values have // the same definition as resource // manager tags. Keys and values can be either in numeric format, // such as `tagKeys/{tag_key_id}` and `tagValues/456` or in namespaced @@ -28937,10 +29474,10 @@ message InsertInstanceTemplateRequest { } -// A request message for InstantSnapshots.Insert. See the method description for details. -message InsertInstantSnapshotRequest { +// A request message for InstantSnapshotGroups.Insert. See the method description for details. +message InsertInstantSnapshotGroupRequest { // The body resource for this request - InstantSnapshot instant_snapshot_resource = 383915339 [(google.api.field_behavior) = REQUIRED]; + InstantSnapshotGroup instant_snapshot_group_resource = 145067339 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -28963,6 +29500,9 @@ message InsertInstantSnapshotRequest { // (00000000-0000-0000-0000-000000000000). optional string request_id = 37109963; + // begin_interface: MixerMutationRequestBuilder + optional string source_consistency_group = 531359348; + // Name of the zone for this request. string zone = 3744684 [ (google.api.field_behavior) = REQUIRED, @@ -28971,10 +29511,10 @@ message InsertInstantSnapshotRequest { } -// A request message for InterconnectAttachmentGroups.Insert. See the method description for details. -message InsertInterconnectAttachmentGroupRequest { +// A request message for InstantSnapshots.Insert. See the method description for details. +message InsertInstantSnapshotRequest { // The body resource for this request - InterconnectAttachmentGroup interconnect_attachment_group_resource = 9990137 [(google.api.field_behavior) = REQUIRED]; + InstantSnapshot instant_snapshot_resource = 383915339 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -28995,52 +29535,20 @@ message InsertInterconnectAttachmentGroupRequest { // The request ID must be // a valid UUID with the exception that zero UUID is not supported // (00000000-0000-0000-0000-000000000000). - // end_interface: MixerMutationRequestBuilder optional string request_id = 37109963; -} - -// A request message for InterconnectAttachments.Insert. See the method description for details. -message InsertInterconnectAttachmentRequest { - // The body resource for this request - InterconnectAttachment interconnect_attachment_resource = 212341369 [(google.api.field_behavior) = REQUIRED]; - - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // Name of the region for this request. - string region = 138946292 [ + // Name of the zone for this request. + string zone = 3744684 [ (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "region" + (google.cloud.operation_request_field) = "zone" ]; - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - - // If true, the request will not be committed. - optional bool validate_only = 242744629; - } -// A request message for InterconnectGroups.Insert. See the method description for details. -message InsertInterconnectGroupRequest { +// A request message for InterconnectAttachmentGroups.Insert. See the method description for details. +message InsertInterconnectAttachmentGroupRequest { // The body resource for this request - InterconnectGroup interconnect_group_resource = 85571999 [(google.api.field_behavior) = REQUIRED]; + InterconnectAttachmentGroup interconnect_attachment_group_resource = 9990137 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -29066,10 +29574,10 @@ message InsertInterconnectGroupRequest { } -// A request message for Interconnects.Insert. See the method description for details. -message InsertInterconnectRequest { +// A request message for InterconnectAttachments.Insert. See the method description for details. +message InsertInterconnectAttachmentRequest { // The body resource for this request - Interconnect interconnect_resource = 397611167 [(google.api.field_behavior) = REQUIRED]; + InterconnectAttachment interconnect_attachment_resource = 212341369 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -29077,6 +29585,12 @@ message InsertInterconnectRequest { (google.cloud.operation_request_field) = "project" ]; + // Name of the region for this request. + string region = 138946292 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "region" + ]; + // An optional request ID to identify requests. Specify a unique request ID so // that if you must retry your request, the server will know to ignore the // request if it has already been completed. @@ -29092,12 +29606,15 @@ message InsertInterconnectRequest { // (00000000-0000-0000-0000-000000000000). optional string request_id = 37109963; + // If true, the request will not be committed. + optional bool validate_only = 242744629; + } -// A request message for Licenses.Insert. See the method description for details. -message InsertLicenseRequest { +// A request message for InterconnectGroups.Insert. See the method description for details. +message InsertInterconnectGroupRequest { // The body resource for this request - License license_resource = 437955148 [(google.api.field_behavior) = REQUIRED]; + InterconnectGroup interconnect_group_resource = 85571999 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -29118,14 +29635,71 @@ message InsertLicenseRequest { // The request ID must be // a valid UUID with the exception that zero UUID is not supported // (00000000-0000-0000-0000-000000000000). + // end_interface: MixerMutationRequestBuilder optional string request_id = 37109963; } -// A request message for MachineImages.Insert. See the method description for details. -message InsertMachineImageRequest { +// A request message for Interconnects.Insert. See the method description for details. +message InsertInterconnectRequest { // The body resource for this request - MachineImage machine_image_resource = 60740970 [(google.api.field_behavior) = REQUIRED]; + Interconnect interconnect_resource = 397611167 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + +} + +// A request message for Licenses.Insert. See the method description for details. +message InsertLicenseRequest { + // The body resource for this request + License license_resource = 437955148 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + +} + +// A request message for MachineImages.Insert. See the method description for details. +message InsertMachineImageRequest { + // The body resource for this request + MachineImage machine_image_resource = 60740970 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -29961,6 +30535,43 @@ message InsertRegionInstanceTemplateRequest { } +// A request message for RegionInstantSnapshotGroups.Insert. See the method description for details. +message InsertRegionInstantSnapshotGroupRequest { + // The body resource for this request + InstantSnapshotGroup instant_snapshot_group_resource = 145067339 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // Name of the region for this request. + string region = 138946292 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "region" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // begin_interface: MixerMutationRequestBuilder + optional string source_consistency_group = 531359348; + +} + // A request message for RegionInstantSnapshots.Insert. See the method description for details. message InsertRegionInstantSnapshotRequest { // The body resource for this request @@ -30654,64 +31265,8 @@ message InsertServiceAttachmentRequest { } -// A request message for Snapshots.Insert. See the method description for details. -message InsertSnapshotRequest { - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - - // The body resource for this request - Snapshot snapshot_resource = 481319977 [(google.api.field_behavior) = REQUIRED]; - -} - -// A request message for SslCertificates.Insert. See the method description for details. -message InsertSslCertificateRequest { - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - - // The body resource for this request - SslCertificate ssl_certificate_resource = 180709897 [(google.api.field_behavior) = REQUIRED]; - -} - -// A request message for SslPolicies.Insert. See the method description for details. -message InsertSslPolicyRequest { +// A request message for SnapshotGroups.Insert. See the method description for details. +message InsertSnapshotGroupRequest { // Project ID for this request. string project = 227560217 [ (google.api.field_behavior) = REQUIRED, @@ -30734,80 +31289,12 @@ message InsertSslPolicyRequest { optional string request_id = 37109963; // The body resource for this request - SslPolicy ssl_policy_resource = 274891848 [(google.api.field_behavior) = REQUIRED]; + SnapshotGroup snapshot_group_resource = 265205161 [(google.api.field_behavior) = REQUIRED]; } -// A request message for StoragePools.Insert. See the method description for details. -message InsertStoragePoolRequest { - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - - // The body resource for this request - StoragePool storage_pool_resource = 157179405 [(google.api.field_behavior) = REQUIRED]; - - // The name of the zone for this request. - string zone = 3744684 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "zone" - ]; - -} - -// A request message for Subnetworks.Insert. See the method description for details. -message InsertSubnetworkRequest { - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // Name of the region scoping this request. - string region = 138946292 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "region" - ]; - - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - - // The body resource for this request - Subnetwork subnetwork_resource = 42233151 [(google.api.field_behavior) = REQUIRED]; - -} - -// A request message for TargetGrpcProxies.Insert. See the method description for details. -message InsertTargetGrpcProxyRequest { +// A request message for Snapshots.Insert. See the method description for details. +message InsertSnapshotRequest { // Project ID for this request. string project = 227560217 [ (google.api.field_behavior) = REQUIRED, @@ -30830,12 +31317,12 @@ message InsertTargetGrpcProxyRequest { optional string request_id = 37109963; // The body resource for this request - TargetGrpcProxy target_grpc_proxy_resource = 328922450 [(google.api.field_behavior) = REQUIRED]; + Snapshot snapshot_resource = 481319977 [(google.api.field_behavior) = REQUIRED]; } -// A request message for TargetHttpProxies.Insert. See the method description for details. -message InsertTargetHttpProxyRequest { +// A request message for SslCertificates.Insert. See the method description for details. +message InsertSslCertificateRequest { // Project ID for this request. string project = 227560217 [ (google.api.field_behavior) = REQUIRED, @@ -30858,12 +31345,12 @@ message InsertTargetHttpProxyRequest { optional string request_id = 37109963; // The body resource for this request - TargetHttpProxy target_http_proxy_resource = 24696744 [(google.api.field_behavior) = REQUIRED]; + SslCertificate ssl_certificate_resource = 180709897 [(google.api.field_behavior) = REQUIRED]; } -// A request message for TargetHttpsProxies.Insert. See the method description for details. -message InsertTargetHttpsProxyRequest { +// A request message for SslPolicies.Insert. See the method description for details. +message InsertSslPolicyRequest { // Project ID for this request. string project = 227560217 [ (google.api.field_behavior) = REQUIRED, @@ -30886,12 +31373,12 @@ message InsertTargetHttpsProxyRequest { optional string request_id = 37109963; // The body resource for this request - TargetHttpsProxy target_https_proxy_resource = 433657473 [(google.api.field_behavior) = REQUIRED]; + SslPolicy ssl_policy_resource = 274891848 [(google.api.field_behavior) = REQUIRED]; } -// A request message for TargetInstances.Insert. See the method description for details. -message InsertTargetInstanceRequest { +// A request message for StoragePools.Insert. See the method description for details. +message InsertStoragePoolRequest { // Project ID for this request. string project = 227560217 [ (google.api.field_behavior) = REQUIRED, @@ -30914,9 +31401,9 @@ message InsertTargetInstanceRequest { optional string request_id = 37109963; // The body resource for this request - TargetInstance target_instance_resource = 430453066 [(google.api.field_behavior) = REQUIRED]; + StoragePool storage_pool_resource = 157179405 [(google.api.field_behavior) = REQUIRED]; - // Name of the zone scoping this request. + // The name of the zone for this request. string zone = 3744684 [ (google.api.field_behavior) = REQUIRED, (google.cloud.operation_request_field) = "zone" @@ -30924,8 +31411,8 @@ message InsertTargetInstanceRequest { } -// A request message for TargetPools.Insert. See the method description for details. -message InsertTargetPoolRequest { +// A request message for Subnetworks.Insert. See the method description for details. +message InsertSubnetworkRequest { // Project ID for this request. string project = 227560217 [ (google.api.field_behavior) = REQUIRED, @@ -30954,12 +31441,12 @@ message InsertTargetPoolRequest { optional string request_id = 37109963; // The body resource for this request - TargetPool target_pool_resource = 101281443 [(google.api.field_behavior) = REQUIRED]; + Subnetwork subnetwork_resource = 42233151 [(google.api.field_behavior) = REQUIRED]; } -// A request message for TargetSslProxies.Insert. See the method description for details. -message InsertTargetSslProxyRequest { +// A request message for TargetGrpcProxies.Insert. See the method description for details. +message InsertTargetGrpcProxyRequest { // Project ID for this request. string project = 227560217 [ (google.api.field_behavior) = REQUIRED, @@ -30982,12 +31469,164 @@ message InsertTargetSslProxyRequest { optional string request_id = 37109963; // The body resource for this request - TargetSslProxy target_ssl_proxy_resource = 142016192 [(google.api.field_behavior) = REQUIRED]; + TargetGrpcProxy target_grpc_proxy_resource = 328922450 [(google.api.field_behavior) = REQUIRED]; } -// A request message for TargetTcpProxies.Insert. See the method description for details. -message InsertTargetTcpProxyRequest { +// A request message for TargetHttpProxies.Insert. See the method description for details. +message InsertTargetHttpProxyRequest { + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The body resource for this request + TargetHttpProxy target_http_proxy_resource = 24696744 [(google.api.field_behavior) = REQUIRED]; + +} + +// A request message for TargetHttpsProxies.Insert. See the method description for details. +message InsertTargetHttpsProxyRequest { + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The body resource for this request + TargetHttpsProxy target_https_proxy_resource = 433657473 [(google.api.field_behavior) = REQUIRED]; + +} + +// A request message for TargetInstances.Insert. See the method description for details. +message InsertTargetInstanceRequest { + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The body resource for this request + TargetInstance target_instance_resource = 430453066 [(google.api.field_behavior) = REQUIRED]; + + // Name of the zone scoping this request. + string zone = 3744684 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "zone" + ]; + +} + +// A request message for TargetPools.Insert. See the method description for details. +message InsertTargetPoolRequest { + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // Name of the region scoping this request. + string region = 138946292 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "region" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The body resource for this request + TargetPool target_pool_resource = 101281443 [(google.api.field_behavior) = REQUIRED]; + +} + +// A request message for TargetSslProxies.Insert. See the method description for details. +message InsertTargetSslProxyRequest { + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The body resource for this request + TargetSslProxy target_ssl_proxy_resource = 142016192 [(google.api.field_behavior) = REQUIRED]; + +} + +// A request message for TargetTcpProxies.Insert. See the method description for details. +message InsertTargetTcpProxyRequest { // Project ID for this request. string project = 227560217 [ (google.api.field_behavior) = REQUIRED, @@ -31565,6 +32204,8 @@ message Instance { // Multiple tags can be specified via the 'tags.items' field. optional Tags tags = 3552281; + optional WorkloadIdentityConfig workload_identity_config = 338198811; + // Output only. [Output Only] URL of the zone where the instance resides. // You must specify this field as part of the HTTP request URL. It is // not settable as a field in the request body. @@ -32384,7 +33025,7 @@ message InstanceGroupManagerList { // Input only additional params for instance group manager creation. message InstanceGroupManagerParams { - // Resource manager tags to bind to the managed instance group. The tags are + // Input only. Resource manager tags to bind to the managed instance group. The tags are // key-value pairs. Keys and values can be either in numeric format, // such as `tagKeys/{tag_key_id}` and `tagValues/456` or in namespaced // format such as `{org_id|project_id}/{tag_key_short_name}` and @@ -32611,6 +33252,11 @@ message InstanceGroupManagerStatus { // Output only. [Output Only] The status of bulk instance operation. optional InstanceGroupManagerStatusBulkInstanceOperation bulk_instance_operation = 501667466; + // Output only. [Output Only] The list of instance statuses and the number of instances + // in this managed instance group that have the status. Currently only shown + // for TPU MIGs + optional InstanceGroupManagerStatusInstanceStatusSummary current_instance_statuses = 269432644; + // Output only. [Output Only] A bit indicating whether the managed instance group is in a // stable state. A stable state means that: none of the instances in the // managed instance group is currently undergoing any type of change (for @@ -32664,6 +33310,71 @@ message InstanceGroupManagerStatusBulkInstanceOperationLastProgressCheck { } +// The list of instance statuses and the number of instances in this managed +// instance group that have the status. For more information about how to +// interpret each status check the instance lifecycle documentation. +// Currently only shown for TPU MIGs. +message InstanceGroupManagerStatusInstanceStatusSummary { + // Output only. [Output Only] The number of instances in the managed instance group + // that have DEPROVISIONING status. + optional int32 deprovisioning = 462169582; + + // Output only. [Output Only] The number of instances that have not been created yet or + // have been deleted. Includes only instances that would be shown in the + // listManagedInstances method and not all instances that have been + // deleted in the lifetime of the MIG. + // Does not include FlexStart instances that are waiting for the resources + // availability, they are considered as 'pending'. + optional int32 non_existent = 468485062; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have PENDING status, that is FlexStart instances that are waiting + // for resources. Instances that do not exist because of the other reasons + // are counted as 'non_existent'. + optional int32 pending = 391154071; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have PENDING_STOP status. + optional int32 pending_stop = 163159466; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have PROVISIONING status. + optional int32 provisioning = 121098989; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have REPAIRING status. + optional int32 repairing = 311243061; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have RUNNING status. + optional int32 running = 477042111; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have STAGING status. + optional int32 staging = 249960507; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have STOPPED status. + optional int32 stopped = 263164365; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have STOPPING status. + optional int32 stopping = 105035892; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have SUSPENDED status. + optional int32 suspended = 485854683; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have SUSPENDING status. + optional int32 suspending = 29113894; + + // Output only. [Output Only] The number of instances in the managed instance group + // that have TERMINATED status. + optional int32 terminated = 301796899; + +} + // message InstanceGroupManagerStatusStateful { // Output only. [Output Only] A bit indicating whether the managed instance group @@ -33062,6 +33773,15 @@ message InstanceGroupManagersApplyUpdatesRequest { } +// InstanceGroupManagers.ConfigureAcceleratorTopologies +message InstanceGroupManagersConfigureAcceleratorTopologiesRequest { + // Map of accelerator topologies that should have their state changed to + // the specified value. The key is the hashed topology locus id. It can be + // obtained from the GetAvailableAcceleratorTopologies rpc. + map accelerator_topology_actions = 16520833; + +} + // InstanceGroupManagers.createInstances message InstanceGroupManagersCreateInstancesRequest { // [Required] List of specifications of per-instance configs. @@ -33102,6 +33822,9 @@ message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse { // location. map accelerator_topologies_info = 84833420; + // URL to MMIG this MIG belongs to. + optional string multi_mig = 403990085; + } // @@ -33129,6 +33852,22 @@ message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAccelerato // working inter-chip connected group. UNHEALTHY = 462118084; + // No signal available + UNKNOWN = 433141802; + + } + + // + enum InstancesHealth { + // A value indicating that the enum field is not set. + UNDEFINED_INSTANCES_HEALTH = 0; + + // Infrastructure is healthy + ALL_HEALTHY = 519465151; + + // Some VMs are in another state than RUNNING or they are missing. + UNHEALTHY_OR_MISSING = 59982149; + } // Topology in the format of: "16x16", "4x4x4", etc. @@ -33138,6 +33877,54 @@ message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAccelerato // Check the AcceleratorTopologyHealth enum for the list of possible values. optional string accelerator_topology_health = 323449944; + optional InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState accelerator_topology_state = 228860693; + + // + // Check the InstancesHealth enum for the list of possible values. + optional string instances_health = 165893949; + + // Identified by the topology Id in the accelerator_topology_info map. Empty + // for the top-level topology + optional string parent = 78317738; + +} + +// Specifies the topology state +message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState { + // + enum CurrentState { + // A value indicating that the enum field is not set. + UNDEFINED_CURRENT_STATE = 0; + + ACTIVATING = 378825968; + + ACTIVE = 314733318; + + // The topology is active but with potential performance degradation. + ACTIVE_DEGRADED = 471128135; + + DEACTIVATING = 57182257; + + // Critical non-retriable error that the user has to act manually + FAILED = 455706685; + + INACTIVE = 270421099; + + // Not all VMs have been provisioned + INCOMPLETE = 11941214; + + } + + // + // Check the CurrentState enum for the list of possible values. + optional string current_state = 438511179; + + // Reason why the topology state change failed + optional Error error = 96784904; + + // Timestamp when the last error happened + optional string error_timestamp = 219548575; + } // @@ -33610,7 +34397,7 @@ message InstanceParams { // Instances.Insert API. optional Duration request_valid_for_duration = 116247389; - // Resource manager tags to be bound to the instance. Tag keys and values + // Input only. Resource manager tags to be bound to the instance. Tag keys and values // have the same definition as resource // manager tags. Keys and values can be either in numeric format, // such as `tagKeys/{tag_key_id}` and `tagValues/456` or in namespaced @@ -33768,7 +34555,7 @@ message InstanceProperties { // Note that for MachineImage, this is not supported yet. optional ReservationAffinity reservation_affinity = 157850683; - // Resource manager tags to be bound to the instance. Tag keys and values + // Input only. Resource manager tags to be bound to the instance. Tag keys and values // have the same definition as resource // manager tags. Keys must be in the format `tagKeys/{tag_key_id}`, and // values are in the format `tagValues/456`. The field is ignored (both PUT & @@ -33803,6 +34590,8 @@ message InstanceProperties { // the list must comply with RFC1035. optional Tags tags = 3552281; + optional WorkloadIdentityConfig workload_identity_config = 338198811; + } // Represents the change that you want to make to the instance properties. @@ -34192,6 +34981,9 @@ message InstancesReportHostAsFaultyRequestFaultReason { // Public reportable behaviors BEHAVIOR_UNSPECIFIED = 85734570; + // Any GPU or TPU errors or faults where the accelerator becomes unusable + CHIP_ERROR = 263151669; + PERFORMANCE = 135701520; SILENT_DATA_CORRUPTION = 111360678; @@ -34416,6 +35208,10 @@ message InstantSnapshot { // be a dash. optional string name = 3373707; + // Input only. Additional params passed with the request, but not persisted + // as part of resource payload. + optional InstantSnapshotParams params = 78313862; + // Output only. [Output Only] URL of the region where the instant snapshot resides. // You must specify this field as part of the HTTP request URL. It is // not settable as a field in the request body. @@ -34466,6 +35262,17 @@ message InstantSnapshot { // was taken from the current or a previous instance of a given disk name. optional string source_disk_id = 454190809; + // Output only. [Output Only] URL of the source instant snapshot this instant snapshot is + // part of. Note that the source instant snapshot group must be in the same + // zone/region as the instant snapshot to be created. This can be a full or + // valid partial URL. + optional string source_instant_snapshot_group = 525991686; + + // Output only. [Output Only] The ID value of the source instant snapshot group this + // InstantSnapshot is part of. This value may be used to determine whether the + // InstantSnapshot was created as part of an InstantSnapshotGroup creation. + optional string source_instant_snapshot_group_id = 167103732; + // Output only. [Output Only] The status of the instantSnapshot. This can beCREATING, DELETING, FAILED, orREADY. // Check the Status enum for the list of possible values. optional string status = 181260274; @@ -34507,6 +35314,113 @@ message InstantSnapshotAggregatedList { } +// Represents an InstantSnapshotGroup resource. +// +// An instant snapshot group is a set of instant snapshots that represents a +// point in time state of a consistency group. +message InstantSnapshotGroup { + // Output only. [Output Only] + enum Status { + // A value indicating that the enum field is not set. + UNDEFINED_STATUS = 0; + + CREATING = 455564985; + + DELETING = 528602024; + + FAILED = 455706685; + + INVALID = 530283991; + + READY = 77848963; + + UNKNOWN = 433141802; + + } + + // Output only. [Output Only] Creation timestamp inRFC3339 + // text format. + optional string creation_timestamp = 30525366; + + // Optional. An optional description of this resource. Provide this property when you + // create the resource. + optional string description = 422937596; + + // Output only. [Output Only] The unique identifier for the resource. This identifier is + // defined by the server. + optional uint64 id = 3355; + + // Output only. [Output Only] Type of the resource. Alwayscompute#instantSnapshotGroup for InstantSnapshotGroup + // resources. + optional string kind = 3292052; + + // Identifier. Name of the resource; provided by the client when the resource is created. + // The name must be 1-63 characters long, and comply withRFC1035. + // Specifically, the name must be 1-63 characters long and match the regular + // expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first + // character must be a lowercase letter, and all following characters must be + // a dash, lowercase letter, or digit, except the last character, which cannot + // be a dash. + optional string name = 3373707; + + // Output only. [Output Only] URL of the region where the instant snapshot group resides. + // You must specify this field as part of the HTTP request URL. It is + // not settable as a field in the request body. + optional string region = 138946292; + + optional InstantSnapshotGroupResourceStatus resource_status = 249429315; + + // Output only. [Output Only] Server-defined URL for the resource. + optional string self_link = 456214797; + + // Output only. [Output Only] Server-defined URL for this resource's resource id. + optional string self_link_with_id = 44520962; + + optional string source_consistency_group = 531359348; + + // Output only. [Output Only] + // Check the Status enum for the list of possible values. + optional string status = 181260274; + + // Output only. [Output Only] URL of the zone where the instant snapshot group resides. + // You must specify this field as part of the HTTP request URL. It is + // not settable as a field in the request body. + optional string zone = 3744684; + +} + +// +message InstantSnapshotGroupParameters { + // The source instant snapshot group used to create disks. You can provide + // this as a partial or full URL to the resource. For example, the following + // are valid values: + // + // + // - https://www.googleapis.com/compute/v1/projects/project/zones/zone/instantSnapshotGroups/instantSnapshotGroup + // - projects/project/zones/zone/instantSnapshotGroups/instantSnapshotGroup + // - zones/zone/instantSnapshotGroups/instantSnapshotGroup + optional string source_instant_snapshot_group = 525991686; + +} + +// +message InstantSnapshotGroupResourceStatus { + // Output only. [Output Only] + optional string consistency_membership_resolution_time = 346675870; + + // Output only. [Output Only] + optional InstantSnapshotGroupSourceInfo source_info = 451907154; + +} + +// +message InstantSnapshotGroupSourceInfo { + optional string consistency_group = 508183960; + + optional string consistency_group_id = 85599522; + +} + // Contains a list of InstantSnapshot resources. message InstantSnapshotList { // [Output Only] Unique identifier for the resource; defined by the server. @@ -34533,6 +35447,19 @@ message InstantSnapshotList { } +// Additional instant snapshot params. +message InstantSnapshotParams { + // Input only. Resource manager tags to be bound to the instant snapshot. Tag keys and + // values have the same definition as resource + // manager tags. Keys and values can be either in numeric format, + // such as `tagKeys/{tag_key_id}` and `tagValues/{tag_value_id}` or in + // namespaced format such as `{org_id|project_id}/{tag_key_short_name}` and + // `{tag_value_short_name}`. The field is ignored (both PUT & + // PATCH) when empty. + map resource_manager_tags = 377671164; + +} + // message InstantSnapshotResourceStatus { // [Output Only] The storage size of this instant snapshot. @@ -34688,8 +35615,7 @@ message Interconnect { } - // Specific subzone in the InterconnectLocation that represents where - // this connection is to be provisioned. + // To be deprecated. enum Subzone { // A value indicating that the enum field is not set. UNDEFINED_SUBZONE = 0; @@ -34907,8 +35833,7 @@ message Interconnect { // Check the State enum for the list of possible values. optional string state = 109757585; - // Specific subzone in the InterconnectLocation that represents where - // this connection is to be provisioned. + // To be deprecated. // Check the Subzone enum for the list of possible values. optional string subzone = 280084972; @@ -41869,6 +42794,141 @@ message ListInstancesRequest { } +// Contains a list of InstantSnapshotGroup resources. +message ListInstantSnapshotGroups { + optional string etag = 3123477; + + // [Output Only] Unique identifier for the resource; defined by the server. + optional string id = 3355; + + // A list of InstantSnapshotGroup resources. + repeated InstantSnapshotGroup items = 100526016; + + // Output only. Type of resource. + optional string kind = 3292052; + + // [Output Only] This token allows you to get the next page of results for + // list requests. If the number of results is larger thanmaxResults, use the nextPageToken as a value for + // the query parameter pageToken in the next list request. + // Subsequent list requests will have their own nextPageToken to + // continue paging through the results. + optional string next_page_token = 79797525; + + // Output only. [Output Only] Server-defined URL for this resource. + optional string self_link = 456214797; + + // Output only. [Output Only] Unreachable resources. + // end_interface: MixerListResponseWithEtagBuilder + repeated string unreachables = 243372063; + + // [Output Only] Informational warning message. + optional Warning warning = 50704284; + +} + +// A request message for InstantSnapshotGroups.List. See the method description for details. +message ListInstantSnapshotGroupsRequest { + // A filter expression that filters resources listed in the response. Most + // Compute resources support two types of filter expressions: + // expressions that support regular expressions and expressions that follow + // API improvement proposal AIP-160. + // These two types of filter expressions cannot be mixed in one request. + // + // If you want to use AIP-160, your expression must specify the field name, an + // operator, and the value that you want to use for filtering. The value + // must be a string, a number, or a boolean. The operator + // must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + // + // For example, if you are filtering Compute Engine instances, you can + // exclude instances named `example-instance` by specifying + // `name != example-instance`. + // + // The `:*` comparison can be used to test whether a key has been defined. + // For example, to find all objects with `owner` label use: + // ``` + // labels.owner:* + // ``` + // + // You can also filter nested fields. For example, you could specify + // `scheduling.automaticRestart = false` to include instances only + // if they are not scheduled for automatic restarts. You can use filtering + // on nested fields to filter based onresource labels. + // + // To filter on multiple expressions, provide each separate expression within + // parentheses. For example: + // ``` + // (scheduling.automaticRestart = true) + // (cpuPlatform = "Intel Skylake") + // ``` + // By default, each expression is an `AND` expression. However, you + // can include `AND` and `OR` expressions explicitly. + // For example: + // ``` + // (cpuPlatform = "Intel Skylake") OR + // (cpuPlatform = "Intel Broadwell") AND + // (scheduling.automaticRestart = true) + // ``` + // + // If you want to use a regular expression, use the `eq` (equal) or `ne` + // (not equal) operator against a single un-parenthesized expression with or + // without quotes or against multiple parenthesized expressions. Examples: + // + // `fieldname eq unquoted literal` + // `fieldname eq 'single quoted literal'` + // `fieldname eq "double quoted literal"` + // `(fieldname1 eq literal) (fieldname2 ne "literal")` + // + // The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + // The literal value must match the entire field. + // + // For example, to filter for instances that do not end with name "instance", + // you would use `name ne .*instance`. + // + // You cannot combine constraints on multiple fields using regular + // expressions. + optional string filter = 336120696; + + // The maximum number of results per page that should be returned. + // If the number of available results is larger than `maxResults`, + // Compute Engine returns a `nextPageToken` that can be used to get + // the next page of results in subsequent list requests. Acceptable values are + // `0` to `500`, inclusive. (Default: `500`) + optional uint32 max_results = 54715419; + + // Sorts list results by a certain order. By default, results + // are returned in alphanumerical order based on the resource name. + // + // You can also sort results in descending order based on the creation + // timestamp using `orderBy="creationTimestamp desc"`. This sorts + // results based on the `creationTimestamp` field in + // reverse chronological order (newest result first). Use this to sort + // resources like operations so that the newest operation is returned first. + // + // Currently, only sorting by `name` or + // `creationTimestamp desc` is supported. + optional string order_by = 160562920; + + // Specifies a page token to use. Set `pageToken` to the + // `nextPageToken` returned by a previous list request to get + // the next page of results. + optional string page_token = 19994697; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Opt-in for partial success behavior which provides partial results in case + // of failure. The default value is false. + // + // For example, when partial success behavior is enabled, aggregatedList for a + // single zone scope either returns all resources in the zone or no resources, + // with an error code. + optional bool return_partial_success = 517198390; + + // The name of the zone for this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for InstantSnapshots.List. See the method description for details. message ListInstantSnapshotsRequest { // A filter expression that filters resources listed in the response. Most @@ -43091,6 +44151,113 @@ message ListManagedInstancesRegionInstanceGroupManagersRequest { } +// A request message for Routers.ListNamedSets. See the method description for details. +message ListNamedSetsRoutersRequest { + // A filter expression that filters resources listed in the response. Most + // Compute resources support two types of filter expressions: + // expressions that support regular expressions and expressions that follow + // API improvement proposal AIP-160. + // These two types of filter expressions cannot be mixed in one request. + // + // If you want to use AIP-160, your expression must specify the field name, an + // operator, and the value that you want to use for filtering. The value + // must be a string, a number, or a boolean. The operator + // must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + // + // For example, if you are filtering Compute Engine instances, you can + // exclude instances named `example-instance` by specifying + // `name != example-instance`. + // + // The `:*` comparison can be used to test whether a key has been defined. + // For example, to find all objects with `owner` label use: + // ``` + // labels.owner:* + // ``` + // + // You can also filter nested fields. For example, you could specify + // `scheduling.automaticRestart = false` to include instances only + // if they are not scheduled for automatic restarts. You can use filtering + // on nested fields to filter based onresource labels. + // + // To filter on multiple expressions, provide each separate expression within + // parentheses. For example: + // ``` + // (scheduling.automaticRestart = true) + // (cpuPlatform = "Intel Skylake") + // ``` + // By default, each expression is an `AND` expression. However, you + // can include `AND` and `OR` expressions explicitly. + // For example: + // ``` + // (cpuPlatform = "Intel Skylake") OR + // (cpuPlatform = "Intel Broadwell") AND + // (scheduling.automaticRestart = true) + // ``` + // + // If you want to use a regular expression, use the `eq` (equal) or `ne` + // (not equal) operator against a single un-parenthesized expression with or + // without quotes or against multiple parenthesized expressions. Examples: + // + // `fieldname eq unquoted literal` + // `fieldname eq 'single quoted literal'` + // `fieldname eq "double quoted literal"` + // `(fieldname1 eq literal) (fieldname2 ne "literal")` + // + // The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + // The literal value must match the entire field. + // + // For example, to filter for instances that do not end with name "instance", + // you would use `name ne .*instance`. + // + // You cannot combine constraints on multiple fields using regular + // expressions. + optional string filter = 336120696; + + // The maximum number of results per page that should be returned. + // If the number of available results is larger than `maxResults`, + // Compute Engine returns a `nextPageToken` that can be used to get + // the next page of results in subsequent list requests. Acceptable values are + // `0` to `500`, inclusive. (Default: `500`) + optional uint32 max_results = 54715419; + + // Sorts list results by a certain order. By default, results + // are returned in alphanumerical order based on the resource name. + // + // You can also sort results in descending order based on the creation + // timestamp using `orderBy="creationTimestamp desc"`. This sorts + // results based on the `creationTimestamp` field in + // reverse chronological order (newest result first). Use this to sort + // resources like operations so that the newest operation is returned first. + // + // Currently, only sorting by `name` or + // `creationTimestamp desc` is supported. + optional string order_by = 160562920; + + // Specifies a page token to use. Set `pageToken` to the + // `nextPageToken` returned by a previous list request to get + // the next page of results. + optional string page_token = 19994697; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + + // Opt-in for partial success behavior which provides partial results in case + // of failure. The default value is false. + // + // For example, when partial success behavior is enabled, aggregatedList for a + // single zone scope either returns all resources in the zone or no resources, + // with an error code. + optional bool return_partial_success = 517198390; + + // Name or id of the resource for this request. + // Name should conform to RFC1035. + string router = 148608841 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for NetworkAttachments.List. See the method description for details. message ListNetworkAttachmentsRequest { // A filter expression that filters resources listed in the response. Most @@ -47059,8 +48226,8 @@ message ListRegionInstanceTemplatesRequest { } -// A request message for RegionInstantSnapshots.List. See the method description for details. -message ListRegionInstantSnapshotsRequest { +// A request message for RegionInstantSnapshotGroups.List. See the method description for details. +message ListRegionInstantSnapshotGroupsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -47162,8 +48329,8 @@ message ListRegionInstantSnapshotsRequest { } -// A request message for RegionMultiMigMembers.List. See the method description for details. -message ListRegionMultiMigMembersRequest { +// A request message for RegionInstantSnapshots.List. See the method description for details. +message ListRegionInstantSnapshotsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -47231,10 +48398,6 @@ message ListRegionMultiMigMembersRequest { // `0` to `500`, inclusive. (Default: `500`) optional uint32 max_results = 54715419; - // The name of the multi-MIG. - // Name should conform to RFC1035 or be a resource ID. - string multi_mig = 403990085 [(google.api.field_behavior) = REQUIRED]; - // Sorts list results by a certain order. By default, results // are returned in alphanumerical order based on the resource name. // @@ -47256,7 +48419,7 @@ message ListRegionMultiMigMembersRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region for this request. Region name should conform to RFC1035. + // The name of the region for this request. string region = 138946292 [(google.api.field_behavior) = REQUIRED]; // Opt-in for partial success behavior which provides partial results in case @@ -47269,8 +48432,115 @@ message ListRegionMultiMigMembersRequest { } -// A request message for RegionMultiMigs.List. See the method description for details. -message ListRegionMultiMigsRequest { +// A request message for RegionMultiMigMembers.List. See the method description for details. +message ListRegionMultiMigMembersRequest { + // A filter expression that filters resources listed in the response. Most + // Compute resources support two types of filter expressions: + // expressions that support regular expressions and expressions that follow + // API improvement proposal AIP-160. + // These two types of filter expressions cannot be mixed in one request. + // + // If you want to use AIP-160, your expression must specify the field name, an + // operator, and the value that you want to use for filtering. The value + // must be a string, a number, or a boolean. The operator + // must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + // + // For example, if you are filtering Compute Engine instances, you can + // exclude instances named `example-instance` by specifying + // `name != example-instance`. + // + // The `:*` comparison can be used to test whether a key has been defined. + // For example, to find all objects with `owner` label use: + // ``` + // labels.owner:* + // ``` + // + // You can also filter nested fields. For example, you could specify + // `scheduling.automaticRestart = false` to include instances only + // if they are not scheduled for automatic restarts. You can use filtering + // on nested fields to filter based onresource labels. + // + // To filter on multiple expressions, provide each separate expression within + // parentheses. For example: + // ``` + // (scheduling.automaticRestart = true) + // (cpuPlatform = "Intel Skylake") + // ``` + // By default, each expression is an `AND` expression. However, you + // can include `AND` and `OR` expressions explicitly. + // For example: + // ``` + // (cpuPlatform = "Intel Skylake") OR + // (cpuPlatform = "Intel Broadwell") AND + // (scheduling.automaticRestart = true) + // ``` + // + // If you want to use a regular expression, use the `eq` (equal) or `ne` + // (not equal) operator against a single un-parenthesized expression with or + // without quotes or against multiple parenthesized expressions. Examples: + // + // `fieldname eq unquoted literal` + // `fieldname eq 'single quoted literal'` + // `fieldname eq "double quoted literal"` + // `(fieldname1 eq literal) (fieldname2 ne "literal")` + // + // The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + // The literal value must match the entire field. + // + // For example, to filter for instances that do not end with name "instance", + // you would use `name ne .*instance`. + // + // You cannot combine constraints on multiple fields using regular + // expressions. + optional string filter = 336120696; + + // The maximum number of results per page that should be returned. + // If the number of available results is larger than `maxResults`, + // Compute Engine returns a `nextPageToken` that can be used to get + // the next page of results in subsequent list requests. Acceptable values are + // `0` to `500`, inclusive. (Default: `500`) + optional uint32 max_results = 54715419; + + // The name of the multi-MIG. + // Name should conform to RFC1035 or be a resource ID. + string multi_mig = 403990085 [(google.api.field_behavior) = REQUIRED]; + + // Sorts list results by a certain order. By default, results + // are returned in alphanumerical order based on the resource name. + // + // You can also sort results in descending order based on the creation + // timestamp using `orderBy="creationTimestamp desc"`. This sorts + // results based on the `creationTimestamp` field in + // reverse chronological order (newest result first). Use this to sort + // resources like operations so that the newest operation is returned first. + // + // Currently, only sorting by `name` or + // `creationTimestamp desc` is supported. + optional string order_by = 160562920; + + // Specifies a page token to use. Set `pageToken` to the + // `nextPageToken` returned by a previous list request to get + // the next page of results. + optional string page_token = 19994697; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name of the region for this request. Region name should conform to RFC1035. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + + // Opt-in for partial success behavior which provides partial results in case + // of failure. The default value is false. + // + // For example, when partial success behavior is enabled, aggregatedList for a + // single zone scope either returns all resources in the zone or no resources, + // with an error code. + optional bool return_partial_success = 517198390; + +} + +// A request message for RegionMultiMigs.List. See the method description for details. +message ListRegionMultiMigsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49022,8 +50292,8 @@ message ListReservationBlocksRequest { } -// A request message for ReservationSubBlocks.List. See the method description for details. -message ListReservationSubBlocksRequest { +// A request message for ReservationSlots.List. See the method description for details. +message ListReservationSlotsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49109,11 +50379,11 @@ message ListReservationSubBlocksRequest { // the next page of results. optional string page_token = 19994697; - // The name of the parent reservation and parent block. In the format of - // reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + // The name of the parent reservation and parent block, formatted as + // reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} string parent_name = 478151936 [(google.api.field_behavior) = REQUIRED]; - // Project ID for this request. + // The project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; // Opt-in for partial success behavior which provides partial results in case @@ -49124,13 +50394,13 @@ message ListReservationSubBlocksRequest { // with an error code. optional bool return_partial_success = 517198390; - // Name of the zone for this request. Zone name should conform to RFC1035. + // The name of the zone for this request, formatted as RFC1035. string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; } -// A request message for Reservations.List. See the method description for details. -message ListReservationsRequest { +// A request message for ReservationSubBlocks.List. See the method description for details. +message ListReservationSubBlocksRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49216,6 +50486,10 @@ message ListReservationsRequest { // the next page of results. optional string page_token = 19994697; + // The name of the parent reservation and parent block. In the format of + // reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + string parent_name = 478151936 [(google.api.field_behavior) = REQUIRED]; + // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; @@ -49227,13 +50501,13 @@ message ListReservationsRequest { // with an error code. optional bool return_partial_success = 517198390; - // Name of the zone for this request. + // Name of the zone for this request. Zone name should conform to RFC1035. string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; } -// A request message for ResourcePolicies.List. See the method description for details. -message ListResourcePoliciesRequest { +// A request message for Reservations.List. See the method description for details. +message ListReservationsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49322,9 +50596,6 @@ message ListResourcePoliciesRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region for this request. - string region = 138946292 [(google.api.field_behavior) = REQUIRED]; - // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -49333,10 +50604,13 @@ message ListResourcePoliciesRequest { // with an error code. optional bool return_partial_success = 517198390; + // Name of the zone for this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + } -// A request message for RolloutPlans.List. See the method description for details. -message ListRolloutPlansRequest { +// A request message for ResourcePolicies.List. See the method description for details. +message ListResourcePoliciesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49425,6 +50699,9 @@ message ListRolloutPlansRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + // Name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -49435,8 +50712,8 @@ message ListRolloutPlansRequest { } -// A request message for Rollouts.List. See the method description for details. -message ListRolloutsRequest { +// A request message for RolloutPlans.List. See the method description for details. +message ListRolloutPlansRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49535,8 +50812,8 @@ message ListRolloutsRequest { } -// A request message for Routers.ListRoutePolicies. See the method description for details. -message ListRoutePoliciesRoutersRequest { +// A request message for Rollouts.List. See the method description for details. +message ListRolloutsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49625,9 +50902,6 @@ message ListRoutePoliciesRoutersRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region for this request. - string region = 138946292 [(google.api.field_behavior) = REQUIRED]; - // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -49636,14 +50910,10 @@ message ListRoutePoliciesRoutersRequest { // with an error code. optional bool return_partial_success = 517198390; - // Name or id of the resource for this request. - // Name should conform to RFC1035. - string router = 148608841 [(google.api.field_behavior) = REQUIRED]; - } -// A request message for Routers.List. See the method description for details. -message ListRoutersRequest { +// A request message for Routers.ListRoutePolicies. See the method description for details. +message ListRoutePoliciesRoutersRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49743,10 +51013,14 @@ message ListRoutersRequest { // with an error code. optional bool return_partial_success = 517198390; + // Name or id of the resource for this request. + // Name should conform to RFC1035. + string router = 148608841 [(google.api.field_behavior) = REQUIRED]; + } -// A request message for Routes.List. See the method description for details. -message ListRoutesRequest { +// A request message for Routers.List. See the method description for details. +message ListRoutersRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49835,6 +51109,9 @@ message ListRoutesRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + // Name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -49845,8 +51122,8 @@ message ListRoutesRequest { } -// A request message for SecurityPolicies.List. See the method description for details. -message ListSecurityPoliciesRequest { +// A request message for Routes.List. See the method description for details. +message ListRoutesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -49945,8 +51222,8 @@ message ListSecurityPoliciesRequest { } -// A request message for ServiceAttachments.List. See the method description for details. -message ListServiceAttachmentsRequest { +// A request message for SecurityPolicies.List. See the method description for details. +message ListSecurityPoliciesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50035,9 +51312,6 @@ message ListServiceAttachmentsRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region of this request. - string region = 138946292 [(google.api.field_behavior) = REQUIRED]; - // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -50048,8 +51322,8 @@ message ListServiceAttachmentsRequest { } -// A request message for Snapshots.List. See the method description for details. -message ListSnapshotsRequest { +// A request message for ServiceAttachments.List. See the method description for details. +message ListServiceAttachmentsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50138,6 +51412,9 @@ message ListSnapshotsRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + // Name of the region of this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -50148,8 +51425,40 @@ message ListSnapshotsRequest { } -// A request message for SslCertificates.List. See the method description for details. -message ListSslCertificatesRequest { +// Contains a list of SnapshotGroup resources. +message ListSnapshotGroups { + optional string etag = 3123477; + + // [Output Only] Unique identifier for the resource; defined by the server. + optional string id = 3355; + + // A list of SnapshotGroup resources. + repeated SnapshotGroup items = 100526016; + + // Output only. Type of resource. + optional string kind = 3292052; + + // [Output Only] This token allows you to get the next page of results for + // list requests. If the number of results is larger thanmaxResults, use the nextPageToken as a value for + // the query parameter pageToken in the next list request. + // Subsequent list requests will have their own nextPageToken to + // continue paging through the results. + optional string next_page_token = 79797525; + + // Output only. [Output Only] Server-defined URL for this resource. + optional string self_link = 456214797; + + // Output only. [Output Only] Unreachable resources. + // end_interface: MixerListResponseWithEtagBuilder + repeated string unreachables = 243372063; + + // [Output Only] Informational warning message. + optional Warning warning = 50704284; + +} + +// A request message for SnapshotGroups.List. See the method description for details. +message ListSnapshotGroupsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50248,8 +51557,8 @@ message ListSslCertificatesRequest { } -// A request message for SslPolicies.List. See the method description for details. -message ListSslPoliciesRequest { +// A request message for Snapshots.List. See the method description for details. +message ListSnapshotsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50348,8 +51657,8 @@ message ListSslPoliciesRequest { } -// A request message for StoragePoolTypes.List. See the method description for details. -message ListStoragePoolTypesRequest { +// A request message for SslCertificates.List. See the method description for details. +message ListSslCertificatesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50446,13 +51755,10 @@ message ListStoragePoolTypesRequest { // with an error code. optional bool return_partial_success = 517198390; - // The name of the zone for this request. - string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; - } -// A request message for StoragePools.List. See the method description for details. -message ListStoragePoolsRequest { +// A request message for SslPolicies.List. See the method description for details. +message ListSslPoliciesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50549,29 +51855,10 @@ message ListStoragePoolsRequest { // with an error code. optional bool return_partial_success = 517198390; - // The name of the zone for this request. - string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; - } -// A request message for Subnetworks.List. See the method description for details. -message ListSubnetworksRequest { - // Defines the extra views returned back in the subnetwork resource. - // Supported values: - // - // - WITH_UTILIZATION: Utilization data is included in the - // response. - enum Views { - // A value indicating that the enum field is not set. - UNDEFINED_VIEWS = 0; - - DEFAULT = 115302945; - - // Utilization data is included in the response. - WITH_UTILIZATION = 504090633; - - } - +// A request message for StoragePoolTypes.List. See the method description for details. +message ListStoragePoolTypesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50660,8 +51947,108 @@ message ListSubnetworksRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region scoping this request. - string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case + // of failure. The default value is false. + // + // For example, when partial success behavior is enabled, aggregatedList for a + // single zone scope either returns all resources in the zone or no resources, + // with an error code. + optional bool return_partial_success = 517198390; + + // The name of the zone for this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + +} + +// A request message for StoragePools.List. See the method description for details. +message ListStoragePoolsRequest { + // A filter expression that filters resources listed in the response. Most + // Compute resources support two types of filter expressions: + // expressions that support regular expressions and expressions that follow + // API improvement proposal AIP-160. + // These two types of filter expressions cannot be mixed in one request. + // + // If you want to use AIP-160, your expression must specify the field name, an + // operator, and the value that you want to use for filtering. The value + // must be a string, a number, or a boolean. The operator + // must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + // + // For example, if you are filtering Compute Engine instances, you can + // exclude instances named `example-instance` by specifying + // `name != example-instance`. + // + // The `:*` comparison can be used to test whether a key has been defined. + // For example, to find all objects with `owner` label use: + // ``` + // labels.owner:* + // ``` + // + // You can also filter nested fields. For example, you could specify + // `scheduling.automaticRestart = false` to include instances only + // if they are not scheduled for automatic restarts. You can use filtering + // on nested fields to filter based onresource labels. + // + // To filter on multiple expressions, provide each separate expression within + // parentheses. For example: + // ``` + // (scheduling.automaticRestart = true) + // (cpuPlatform = "Intel Skylake") + // ``` + // By default, each expression is an `AND` expression. However, you + // can include `AND` and `OR` expressions explicitly. + // For example: + // ``` + // (cpuPlatform = "Intel Skylake") OR + // (cpuPlatform = "Intel Broadwell") AND + // (scheduling.automaticRestart = true) + // ``` + // + // If you want to use a regular expression, use the `eq` (equal) or `ne` + // (not equal) operator against a single un-parenthesized expression with or + // without quotes or against multiple parenthesized expressions. Examples: + // + // `fieldname eq unquoted literal` + // `fieldname eq 'single quoted literal'` + // `fieldname eq "double quoted literal"` + // `(fieldname1 eq literal) (fieldname2 ne "literal")` + // + // The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + // The literal value must match the entire field. + // + // For example, to filter for instances that do not end with name "instance", + // you would use `name ne .*instance`. + // + // You cannot combine constraints on multiple fields using regular + // expressions. + optional string filter = 336120696; + + // The maximum number of results per page that should be returned. + // If the number of available results is larger than `maxResults`, + // Compute Engine returns a `nextPageToken` that can be used to get + // the next page of results in subsequent list requests. Acceptable values are + // `0` to `500`, inclusive. (Default: `500`) + optional uint32 max_results = 54715419; + + // Sorts list results by a certain order. By default, results + // are returned in alphanumerical order based on the resource name. + // + // You can also sort results in descending order based on the creation + // timestamp using `orderBy="creationTimestamp desc"`. This sorts + // results based on the `creationTimestamp` field in + // reverse chronological order (newest result first). Use this to sort + // resources like operations so that the newest operation is returned first. + // + // Currently, only sorting by `name` or + // `creationTimestamp desc` is supported. + optional string order_by = 160562920; + + // Specifies a page token to use. Set `pageToken` to the + // `nextPageToken` returned by a previous list request to get + // the next page of results. + optional string page_token = 19994697; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. @@ -50671,18 +52058,29 @@ message ListSubnetworksRequest { // with an error code. optional bool return_partial_success = 517198390; + // The name of the zone for this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + +} + +// A request message for Subnetworks.List. See the method description for details. +message ListSubnetworksRequest { // Defines the extra views returned back in the subnetwork resource. // Supported values: // // - WITH_UTILIZATION: Utilization data is included in the // response. - // Check the Views enum for the list of possible values. - optional string views = 112204398; + enum Views { + // A value indicating that the enum field is not set. + UNDEFINED_VIEWS = 0; -} + DEFAULT = 115302945; + + // Utilization data is included in the response. + WITH_UTILIZATION = 504090633; + + } -// A request message for TargetGrpcProxies.List. See the method description for details. -message ListTargetGrpcProxiesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50771,6 +52169,9 @@ message ListTargetGrpcProxiesRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + // Name of the region scoping this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -50779,10 +52180,18 @@ message ListTargetGrpcProxiesRequest { // with an error code. optional bool return_partial_success = 517198390; + // Defines the extra views returned back in the subnetwork resource. + // Supported values: + // + // - WITH_UTILIZATION: Utilization data is included in the + // response. + // Check the Views enum for the list of possible values. + optional string views = 112204398; + } -// A request message for TargetHttpProxies.List. See the method description for details. -message ListTargetHttpProxiesRequest { +// A request message for TargetGrpcProxies.List. See the method description for details. +message ListTargetGrpcProxiesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50881,8 +52290,8 @@ message ListTargetHttpProxiesRequest { } -// A request message for TargetHttpsProxies.List. See the method description for details. -message ListTargetHttpsProxiesRequest { +// A request message for TargetHttpProxies.List. See the method description for details. +message ListTargetHttpProxiesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -50981,8 +52390,8 @@ message ListTargetHttpsProxiesRequest { } -// A request message for TargetInstances.List. See the method description for details. -message ListTargetInstancesRequest { +// A request message for TargetHttpsProxies.List. See the method description for details. +message ListTargetHttpsProxiesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51079,13 +52488,10 @@ message ListTargetInstancesRequest { // with an error code. optional bool return_partial_success = 517198390; - // Name of the zone scoping this request. - string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; - } -// A request message for TargetPools.List. See the method description for details. -message ListTargetPoolsRequest { +// A request message for TargetInstances.List. See the method description for details. +message ListTargetInstancesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51174,9 +52580,6 @@ message ListTargetPoolsRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region scoping this request. - string region = 138946292 [(google.api.field_behavior) = REQUIRED]; - // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -51185,10 +52588,13 @@ message ListTargetPoolsRequest { // with an error code. optional bool return_partial_success = 517198390; + // Name of the zone scoping this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + } -// A request message for TargetSslProxies.List. See the method description for details. -message ListTargetSslProxiesRequest { +// A request message for TargetPools.List. See the method description for details. +message ListTargetPoolsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51277,6 +52683,9 @@ message ListTargetSslProxiesRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + // Name of the region scoping this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -51287,8 +52696,8 @@ message ListTargetSslProxiesRequest { } -// A request message for TargetTcpProxies.List. See the method description for details. -message ListTargetTcpProxiesRequest { +// A request message for TargetSslProxies.List. See the method description for details. +message ListTargetSslProxiesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51387,8 +52796,8 @@ message ListTargetTcpProxiesRequest { } -// A request message for TargetVpnGateways.List. See the method description for details. -message ListTargetVpnGatewaysRequest { +// A request message for TargetTcpProxies.List. See the method description for details. +message ListTargetTcpProxiesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51477,9 +52886,6 @@ message ListTargetVpnGatewaysRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region for this request. - string region = 138946292 [(google.api.field_behavior) = REQUIRED]; - // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -51490,8 +52896,8 @@ message ListTargetVpnGatewaysRequest { } -// A request message for UrlMaps.List. See the method description for details. -message ListUrlMapsRequest { +// A request message for TargetVpnGateways.List. See the method description for details. +message ListTargetVpnGatewaysRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51580,6 +52986,9 @@ message ListUrlMapsRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + // Name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -51590,8 +52999,8 @@ message ListUrlMapsRequest { } -// A request message for BackendBuckets.ListUsable. See the method description for details. -message ListUsableBackendBucketsRequest { +// A request message for UrlMaps.List. See the method description for details. +message ListUrlMapsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51690,8 +53099,8 @@ message ListUsableBackendBucketsRequest { } -// A request message for BackendServices.ListUsable. See the method description for details. -message ListUsableBackendServicesRequest { +// A request message for BackendBuckets.ListUsable. See the method description for details. +message ListUsableBackendBucketsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51790,8 +53199,8 @@ message ListUsableBackendServicesRequest { } -// A request message for RegionBackendBuckets.ListUsable. See the method description for details. -message ListUsableRegionBackendBucketsRequest { +// A request message for BackendServices.ListUsable. See the method description for details. +message ListUsableBackendServicesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51880,10 +53289,6 @@ message ListUsableRegionBackendBucketsRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region scoping this request. - // It must be a string that meets the requirements in RFC1035. - string region = 138946292 [(google.api.field_behavior) = REQUIRED]; - // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -51894,8 +53299,8 @@ message ListUsableRegionBackendBucketsRequest { } -// A request message for RegionBackendServices.ListUsable. See the method description for details. -message ListUsableRegionBackendServicesRequest { +// A request message for RegionBackendBuckets.ListUsable. See the method description for details. +message ListUsableRegionBackendBucketsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -51998,8 +53403,8 @@ message ListUsableRegionBackendServicesRequest { } -// A request message for Subnetworks.ListUsable. See the method description for details. -message ListUsableSubnetworksRequest { +// A request message for RegionBackendServices.ListUsable. See the method description for details. +message ListUsableRegionBackendServicesRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -52088,6 +53493,10 @@ message ListUsableSubnetworksRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + // Name of the region scoping this request. + // It must be a string that meets the requirements in RFC1035. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -52096,15 +53505,10 @@ message ListUsableSubnetworksRequest { // with an error code. optional bool return_partial_success = 517198390; - // The project id or project number in which the subnetwork is intended to be - // used. Only applied for Shared VPC. See [Shared VPC - // documentation](https://cloud.google.com/vpc/docs/shared-vpc/) - optional string service_project = 530592655; - } -// A request message for VpnGateways.List. See the method description for details. -message ListVpnGatewaysRequest { +// A request message for Subnetworks.ListUsable. See the method description for details. +message ListUsableSubnetworksRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -52193,9 +53597,6 @@ message ListVpnGatewaysRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // Name of the region for this request. - string region = 138946292 [(google.api.field_behavior) = REQUIRED]; - // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -52204,10 +53605,15 @@ message ListVpnGatewaysRequest { // with an error code. optional bool return_partial_success = 517198390; + // The project id or project number in which the subnetwork is intended to be + // used. Only applied for Shared VPC. See [Shared VPC + // documentation](https://cloud.google.com/vpc/docs/shared-vpc/) + optional string service_project = 530592655; + } -// A request message for VpnTunnels.List. See the method description for details. -message ListVpnTunnelsRequest { +// A request message for VpnGateways.List. See the method description for details. +message ListVpnGatewaysRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -52309,10 +53715,8 @@ message ListVpnTunnelsRequest { } -// A request message for WireGroups.List. See the method description for details. -message ListWireGroupsRequest { - string cross_site_network = 108192469 [(google.api.field_behavior) = REQUIRED]; - +// A request message for VpnTunnels.List. See the method description for details. +message ListVpnTunnelsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -52401,6 +53805,9 @@ message ListWireGroupsRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + // Name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -52411,8 +53818,10 @@ message ListWireGroupsRequest { } -// A request message for Projects.ListXpnHosts. See the method description for details. -message ListXpnHostsProjectsRequest { +// A request message for WireGroups.List. See the method description for details. +message ListWireGroupsRequest { + string cross_site_network = 108192469 [(google.api.field_behavior) = REQUIRED]; + // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -52501,9 +53910,6 @@ message ListXpnHostsProjectsRequest { // Project ID for this request. string project = 227560217 [(google.api.field_behavior) = REQUIRED]; - // The body resource for this request - ProjectsListXpnHostsRequest projects_list_xpn_hosts_request_resource = 238266391 [(google.api.field_behavior) = REQUIRED]; - // Opt-in for partial success behavior which provides partial results in case // of failure. The default value is false. // @@ -52514,8 +53920,111 @@ message ListXpnHostsProjectsRequest { } -// A request message for ZoneOperations.List. See the method description for details. -message ListZoneOperationsRequest { +// A request message for Projects.ListXpnHosts. See the method description for details. +message ListXpnHostsProjectsRequest { + // A filter expression that filters resources listed in the response. Most + // Compute resources support two types of filter expressions: + // expressions that support regular expressions and expressions that follow + // API improvement proposal AIP-160. + // These two types of filter expressions cannot be mixed in one request. + // + // If you want to use AIP-160, your expression must specify the field name, an + // operator, and the value that you want to use for filtering. The value + // must be a string, a number, or a boolean. The operator + // must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + // + // For example, if you are filtering Compute Engine instances, you can + // exclude instances named `example-instance` by specifying + // `name != example-instance`. + // + // The `:*` comparison can be used to test whether a key has been defined. + // For example, to find all objects with `owner` label use: + // ``` + // labels.owner:* + // ``` + // + // You can also filter nested fields. For example, you could specify + // `scheduling.automaticRestart = false` to include instances only + // if they are not scheduled for automatic restarts. You can use filtering + // on nested fields to filter based onresource labels. + // + // To filter on multiple expressions, provide each separate expression within + // parentheses. For example: + // ``` + // (scheduling.automaticRestart = true) + // (cpuPlatform = "Intel Skylake") + // ``` + // By default, each expression is an `AND` expression. However, you + // can include `AND` and `OR` expressions explicitly. + // For example: + // ``` + // (cpuPlatform = "Intel Skylake") OR + // (cpuPlatform = "Intel Broadwell") AND + // (scheduling.automaticRestart = true) + // ``` + // + // If you want to use a regular expression, use the `eq` (equal) or `ne` + // (not equal) operator against a single un-parenthesized expression with or + // without quotes or against multiple parenthesized expressions. Examples: + // + // `fieldname eq unquoted literal` + // `fieldname eq 'single quoted literal'` + // `fieldname eq "double quoted literal"` + // `(fieldname1 eq literal) (fieldname2 ne "literal")` + // + // The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + // The literal value must match the entire field. + // + // For example, to filter for instances that do not end with name "instance", + // you would use `name ne .*instance`. + // + // You cannot combine constraints on multiple fields using regular + // expressions. + optional string filter = 336120696; + + // The maximum number of results per page that should be returned. + // If the number of available results is larger than `maxResults`, + // Compute Engine returns a `nextPageToken` that can be used to get + // the next page of results in subsequent list requests. Acceptable values are + // `0` to `500`, inclusive. (Default: `500`) + optional uint32 max_results = 54715419; + + // Sorts list results by a certain order. By default, results + // are returned in alphanumerical order based on the resource name. + // + // You can also sort results in descending order based on the creation + // timestamp using `orderBy="creationTimestamp desc"`. This sorts + // results based on the `creationTimestamp` field in + // reverse chronological order (newest result first). Use this to sort + // resources like operations so that the newest operation is returned first. + // + // Currently, only sorting by `name` or + // `creationTimestamp desc` is supported. + optional string order_by = 160562920; + + // Specifies a page token to use. Set `pageToken` to the + // `nextPageToken` returned by a previous list request to get + // the next page of results. + optional string page_token = 19994697; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + ProjectsListXpnHostsRequest projects_list_xpn_hosts_request_resource = 238266391 [(google.api.field_behavior) = REQUIRED]; + + // Opt-in for partial success behavior which provides partial results in case + // of failure. The default value is false. + // + // For example, when partial success behavior is enabled, aggregatedList for a + // single zone scope either returns all resources in the zone or no resources, + // with an error code. + optional bool return_partial_success = 517198390; + +} + +// A request message for ZoneOperations.List. See the method description for details. +message ListZoneOperationsRequest { // A filter expression that filters resources listed in the response. Most // Compute resources support two types of filter expressions: // expressions that support regular expressions and expressions that follow @@ -52880,12 +54389,24 @@ message LocationPolicy { // Location configurations mapped by location name. // Currently only zone names are supported and must be represented as valid // internal URLs, such as zones/us-central1-a. + // The bulkInsert operation doesn't create instances in an AI zone, even if + // an AI zone is available in the specified region. For example, if you set a + // DENY preference for us-central1-a, Compute Engine will consider + // us-central1-b and us-central1-c for instance creation, but not + // us-central1-ai1a. Also, you can't use the locations[] configuration to + // allow instance creation in an AI zone. To include an AI zone in bulkInsert + // operations, use the locationPolicy.zones[] field. map locations = 413423454; // Strategy for distributing VMs across zones in a region. // Check the TargetShape enum for the list of possible values. optional string target_shape = 338621299; + // The bulkInsert operation applies any preferences set in the locations + // field to the specific zones listed in the zones field if the same zones + // are specified in both fields. + repeated LocationPolicyZoneConfiguration zones = 116085319; + } // @@ -52924,6 +54445,16 @@ message LocationPolicyLocationConstraints { } +// +message LocationPolicyZoneConfiguration { + // The URL of the zone. + // The zone must exist in the region where the request is called. + // Zones must be represented as valid partial URLs, + // such as zones/us-central1-a. + optional string zone = 3744684; + +} + // Represents a machine image resource. // // A machine image is a Compute Engine resource that stores all the @@ -53008,6 +54539,10 @@ message MachineImage { // be a dash. optional string name = 3373707; + // Input only. [Input Only] Additional parameters that are passed in the request, but are + // not persisted in the resource. + optional MachineImageParams params = 78313862; + // Output only. Reserved for future use. optional bool satisfies_pzi = 480964257; @@ -53079,6 +54614,19 @@ message MachineImageList { } +// Machine Image parameters +message MachineImageParams { + // Input only. Resource manager tags to be bound to the machine image. Tag keys and values + // have the same definition as resource + // manager tags. Keys and values can be either in numeric format, + // such as `tagKeys/{tag_key_id}` and `tagValues/{tag_value_id}` or in + // namespaced format such as `{org_id|project_id}/{tag_key_short_name}` and + // `{tag_value_short_name}`. The field is ignored (both PUT & + // PATCH) when empty. + map resource_manager_tags = 377671164; + +} + // Represents a Machine Type resource. // // You can use specific machine types for your VM instances based on performance @@ -54096,6 +55644,49 @@ message NamedPort { } +// +message NamedSet { + // This named set's type + enum Type { + // A value indicating that the enum field is not set. + UNDEFINED_TYPE = 0; + + // The Named Set is a Community Named Set. + NAMED_SET_TYPE_COMMUNITY = 263444871; + + // The Named Set is a Prefix Named Set. + NAMED_SET_TYPE_PREFIX = 228038036; + + } + + // An optional description of named set. + optional string description = 422937596; + + // CEL expressions that are comparable to constructs of this set's type + // (see Policy Language). + repeated Expr elements = 528531703; + + // A fingerprint for the Named Set being applied to this Router, which is + // essentially a hash of the Named Set used for optimistic locking. + // The fingerprint is initially generated by Compute Engine and changes + // after every request to modify or update the Named Set. You must always + // provide an up-to-date fingerprint hash in order to update or change + // labels. + // + // To see the latest fingerprint, make a getNamedSet() request + // to retrieve a Named Set. + optional string fingerprint = 234678500; + + // This set's name, which must be a resource ID segment and unique within all + // named sets owned by the Router. Name should conform to RFC1035. + optional string name = 3373707; + + // This named set's type + // Check the Type enum for the list of possible values. + optional string type = 3575610; + +} + // Contains NAT IP information of a NAT config (i.e. usage status, mode). message NatIpInfo { // Output only. A list of all NAT IPs assigned to this NAT config. @@ -54635,6 +56226,20 @@ message NetworkEndpoint { // A network endpoint group (NEG) defines how a set of endpoints should be // reached, whether they are reachable, and where they are located. // For more information about using NEGs for different use cases, seeNetwork endpoint groups overview. +// +// Note: Use the following APIs to manage network endpoint groups: +// +// - +// To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity +// NEGs): zonal +// API +// - +// To manage NEGs with regional scope (such as regional internet NEGs, +// serverless NEGs, Private Service Connect NEGs): regional +// API +// - +// To manage NEGs with global scope (such as global internet NEGs):global +// API message NetworkEndpointGroup { // Type of network endpoints in this network endpoint group. Can be one ofGCE_VM_IP, GCE_VM_IP_PORT,NON_GCP_PRIVATE_IP_PORT, INTERNET_FQDN_PORT,INTERNET_IP_PORT, SERVERLESS,PRIVATE_SERVICE_CONNECT, GCE_VM_IP_PORTMAP. enum NetworkEndpointType { @@ -55279,6 +56884,10 @@ message NetworkInterface { // You can only specify this field for network interfaces in VPC networks. repeated AliasIpRange alias_ip_ranges = 165085631; + // Optional. If true, DNS resolution will be enabled over this interface. Only valid + // with network_attachment. + optional bool enable_vpc_scoped_dns = 283425868; + // Fingerprint hash of contents stored in this network interface. // This field will be ignored when inserting an Instance or // adding a NetworkInterface. An up-to-date @@ -55457,9 +57066,7 @@ message NetworkPeering { } - // Output only. [Output Only] State for the peering, either `ACTIVE` or `INACTIVE`. The - // peering is `ACTIVE` when there's a matching configuration in the peer - // network. + // Output only. [Output Only] State for the peering. enum State { // A value indicating that the enum field is not set. UNDEFINED_STATE = 0; @@ -55558,9 +57165,7 @@ message NetworkPeering { // Check the StackType enum for the list of possible values. optional string stack_type = 425908881; - // Output only. [Output Only] State for the peering, either `ACTIVE` or `INACTIVE`. The - // peering is `ACTIVE` when there's a matching configuration in the peer - // network. + // Output only. [Output Only] State for the peering. // Check the State enum for the list of possible values. optional string state = 109757585; @@ -56443,8 +58048,12 @@ message NetworkProfileNetworkFeatures { // A value indicating that the enum field is not set. UNDEFINED_FIREWALL_POLICY_TYPES = 0; + RDMA_FALCON_POLICY = 66315047; + RDMA_ROCE_POLICY = 148757145; + ULL_POLICY = 100494364; + VPC_POLICY = 74319208; } @@ -59197,6 +60806,43 @@ message PatchInterconnectRequest { } +// A request message for Routers.PatchNamedSet. See the method description for details. +message PatchNamedSetRouterRequest { + // The body resource for this request + NamedSet named_set_resource = 408608401 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // Name of the region for this request. + string region = 138946292 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "region" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // Name of the Router resource where Named Set is defined. + string router = 148608841 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for NetworkAttachments.Patch. See the method description for details. message PatchNetworkAttachmentRequest { // Name of the NetworkAttachment resource to patch. @@ -65093,6 +66739,24 @@ message Reservation { } + // Indicates the early access maintenance for the reservation. + // If this field is absent or set to NO_EARLY_ACCESS, the reservation is not + // enrolled in early access maintenance and the standard notice applies. + enum EarlyAccessMaintenance { + // A value indicating that the enum field is not set. + UNDEFINED_EARLY_ACCESS_MAINTENANCE = 0; + + // No early access. + NO_EARLY_ACCESS = 220751774; + + // Wave 1: Fastest notification period + WAVE1 = 82367576; + + // Wave 2: Medium notification period + WAVE2 = 82367577; + + } + // Protection tier for the workload which specifies the workload expectations // in the event of infrastructure failures at data center (e.g. power // and/or cooling failures). @@ -65216,6 +66880,12 @@ message Reservation { // create the resource. optional string description = 422937596; + // Indicates the early access maintenance for the reservation. + // If this field is absent or set to NO_EARLY_ACCESS, the reservation is not + // enrolled in early access maintenance and the standard notice applies. + // Check the EarlyAccessMaintenance enum for the list of possible values. + optional string early_access_maintenance = 343918356; + // Indicates whether Compute Engine allows unplanned maintenance for your VMs; // for example, to fix hardware errors. optional bool enable_emergent_maintenance = 353759497; @@ -65241,6 +66911,10 @@ message Reservation { // be a dash. optional string name = 3373707; + // Input only. Additional params passed with the request, but not persisted + // as part of resource payload. + optional ReservationParams params = 78313862; + // Protection tier for the workload which specifies the workload expectations // in the event of infrastructure failures at data center (e.g. power // and/or cooling failures). @@ -65617,6 +67291,143 @@ message ReservationList { } +// Additional reservation params. +message ReservationParams { + // Input only. Resource manager tags to be bound to the reservation. Tag keys and + // values have the same definition as resource + // manager tags. Keys and values can be either in numeric format, + // such as `tagKeys/{tag_key_id}` and `tagValues/{tag_value_id}` or in + // namespaced format such as `{org_id|project_id}/{tag_key_short_name}` and + // `{tag_value_short_name}`. The field is ignored (both PUT & + // PATCH) when empty. + map resource_manager_tags = 377671164; + +} + +// Represents a reservation slot resource. +message ReservationSlot { + // Output only. [Output Only] The state of the reservation slot. + enum State { + // A value indicating that the enum field is not set. + UNDEFINED_STATE = 0; + + // The reservation slot has allocated all its resources. + ACTIVE = 314733318; + + // The resources are being allocated for the reservation slot. + CREATING = 455564985; + + // The reservation slot is currently being deleted. + DELETING = 528602024; + + STATE_UNSPECIFIED = 470755401; + + // The reservation slot is currently unavailable. + UNAVAILABLE = 413756464; + + } + + // Output only. [Output Only] The creation timestamp, formatted asRFC3339 text. + optional string creation_timestamp = 30525366; + + // Output only. [Output Only] The unique identifier for this resource. This identifier is + // defined by the server. + optional uint64 id = 3355; + + // Output only. [Output Only] The type of resource. Alwayscompute#reservationSlot for reservation slots. + optional string kind = 3292052; + + // Output only. [Output Only] The name of the reservation slot. + optional string name = 3373707; + + // Output only. [Output Only] The physical topology of the reservation slot. + optional ReservationSlotPhysicalTopology physical_topology = 279778519; + + // Output only. [Output Only] A server-defined fully-qualified URL for this resource. + optional string self_link = 456214797; + + // Output only. [Output Only] A server-defined URL for this resource with the resource ID. + optional string self_link_with_id = 44520962; + + // Specify share settings to create a shared slot. Set to empty + // to inherit the share settings from a parent resource. + optional ShareSettings share_settings = 266668163; + + // Output only. [Output Only] The state of the reservation slot. + // Check the State enum for the list of possible values. + optional string state = 109757585; + + // Output only. [Output Only] The status of the reservation slot. + optional ReservationSlotStatus status = 181260274; + + // Output only. [Output Only] The zone in which the reservation slot resides. + optional string zone = 3744684; + +} + +// +message ReservationSlotPhysicalTopology { + // The unique identifier of the capacity block within the cluster. + optional string block = 93832333; + + // The cluster name of the reservation sub-block. + optional string cluster = 335221242; + + // The unique identifier of the capacity host within the capacity sub-block. + optional string host = 3208616; + + // The unique identifier of the capacity sub-block within the capacity + // block. + optional string sub_block = 478033358; + +} + +// +message ReservationSlotStatus { + // Output only. [Output Only] The physical topology of the reservation sub-block. + optional ReservationSlotPhysicalTopology physical_topology = 279778519; + + // Output only. The RDMA IP address of the physical host. + repeated string rdma_ip_addresses = 167842531; + + // Output only. The URIs of the instances currently running on this slot. + repeated string running_instances = 536292350; + +} + +// +message ReservationSlotsGetResponse { + optional ReservationSlot resource = 195806222; + +} + +// A list of reservation slots within a single reservation. +message ReservationSlotsListResponse { + // The unique identifier for the resource; defined by the server. + optional string id = 3355; + + // A list of reservation slot resources. + repeated ReservationSlot items = 100526016; + + // The type of resource. Alwayscompute#reservationSlot for a list of reservation + // slots. + optional string kind = 3292052; + + // This token allows you to get the next page of results for + // list requests. If the number of results is larger thanmaxResults, use the nextPageToken as a value for + // the query parameter pageToken in the next list request. + // Subsequent list requests will have their own nextPageToken to + // continue paging through the results. + optional string next_page_token = 79797525; + + // The server-defined URL for this resource. + optional string self_link = 456214797; + + // An informational warning message. + optional Warning warning = 50704284; + +} + // Represents a reservation subBlock resource. message ReservationSubBlock { // Output only. [Output Only] Status of the reservation subBlock. @@ -66843,6 +68654,9 @@ message ResourceStatusEffectiveInstanceMetadata { // Effective enable-oslogin value at Instance level. optional bool enable_oslogin_metadata_value = 216603159; + // Effective gce-container-declaration value at Instance level. + optional bool gce_container_declaration_metadata_value = 219617210; + // Effective serial-port-enable value at Instance level. optional bool serial_port_enable_metadata_value = 430536330; @@ -69247,6 +71061,15 @@ message RouterStatusResponse { } +// +message RoutersGetNamedSetResponse { + // end_interface: MixerGetResponseWithEtagBuilder + optional string etag = 3123477; + + optional NamedSet resource = 195806222; + +} + // message RoutersGetRoutePolicyResponse { optional RoutePolicy resource = 195806222; @@ -69285,6 +71108,38 @@ message RoutersListBgpRoutes { } +// +message RoutersListNamedSets { + optional string etag = 3123477; + + // [Output Only] The unique identifier for the resource. This identifier is + // defined by the server. + optional string id = 3355; + + // Output only. [Output Only] Type of resource. Alwayscompute#routersListNamedSets for lists of named sets. + optional string kind = 3292052; + + // [Output Only] This token allows you to get the next page of results for + // list requests. If the number of results is larger thanmaxResults, use the nextPageToken as a value for + // the query parameter pageToken in the next list request. + // Subsequent list requests will have their own nextPageToken to + // continue paging through the results. + optional string next_page_token = 79797525; + + // [Output Only] A list of named sets. + repeated NamedSet result = 139315229; + + // Output only. [Output Only] Server-defined URL for this resource. + optional string self_link = 456214797; + + // Output only. [Output Only] Unreachable resources. + repeated string unreachables = 243372063; + + // [Output Only] Informational warning message. + optional Warning warning = 50704284; + +} + // message RoutersListRoutePolicies { optional string etag = 3123477; @@ -69832,6 +71687,12 @@ message Scheduling { // Cycle for more information on the possible instance states. optional bool preemptible = 324203169; + // Specifies the Metadata Service preemption notice duration before the GCE ACPI G2 Soft + // Off signal is triggered for Spot + // VMs only. If not specified, there will be no wait before the G2 Soft + // Off signal is triggered. + optional Duration preemption_notice_duration = 486176437; + // Specifies the provisioning model of the instance. // Check the ProvisioningModel enum for the list of possible values. optional string provisioning_model = 494423; @@ -72355,6 +74216,22 @@ message SetIamPolicyInstanceTemplateRequest { } +// A request message for InstantSnapshotGroups.SetIamPolicy. See the method description for details. +message SetIamPolicyInstantSnapshotGroupRequest { + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + + // The name of the zone for this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + ZoneSetPolicyRequest zone_set_policy_request_resource = 382082107 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for InstantSnapshots.SetIamPolicy. See the method description for details. message SetIamPolicyInstantSnapshotRequest { // Project ID for this request. @@ -72532,6 +74409,22 @@ message SetIamPolicyRegionDiskRequest { } +// A request message for RegionInstantSnapshotGroups.SetIamPolicy. See the method description for details. +message SetIamPolicyRegionInstantSnapshotGroupRequest { + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // The name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + RegionSetPolicyRequest region_set_policy_request_resource = 276489091 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for RegionInstantSnapshots.SetIamPolicy. See the method description for details. message SetIamPolicyRegionInstantSnapshotRequest { // Project ID for this request. @@ -72666,6 +74559,19 @@ message SetIamPolicyServiceAttachmentRequest { } +// A request message for SnapshotGroups.SetIamPolicy. See the method description for details. +message SetIamPolicySnapshotGroupRequest { + // The body resource for this request + GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for Snapshots.SetIamPolicy. See the method description for details. message SetIamPolicySnapshotRequest { // The body resource for this request @@ -75133,6 +77039,13 @@ message Snapshot { // do not need to provide a key to use the snapshot later. optional CustomerEncryptionKey snapshot_encryption_key = 43334526; + // Output only. [Output Only] The unique ID of the snapshot group that this snapshot + // belongs to. + optional string snapshot_group_id = 255004406; + + // Output only. [Output only] The snapshot group that this snapshot belongs to. + optional string snapshot_group_name = 246247846; + // Indicates the type of the snapshot. // Check the SnapshotType enum for the list of possible values. optional string snapshot_type = 124349653; @@ -75205,8 +77118,6 @@ message Snapshot { // multi-regional). repeated string storage_locations = 328005274; - // [Output Only] A list of user provided licenses represented by a list of - // URLs to the license resource. repeated string user_licenses = 388193862; } @@ -75243,6 +77154,117 @@ message SnapshotAggregatedList { } +// Represents a SnapshotGroup resource. +// +// A snapshot group is a set of snapshots that represents a point in time state +// of a consistency group. +message SnapshotGroup { + // Output only. [Output Only] + enum Status { + // A value indicating that the enum field is not set. + UNDEFINED_STATUS = 0; + + CREATING = 455564985; + + DELETING = 528602024; + + FAILED = 455706685; + + INVALID = 530283991; + + READY = 77848963; + + UNKNOWN = 433141802; + + UPLOADING = 267603489; + + } + + // Output only. [Output Only] Creation timestamp inRFC3339 + // text format. + optional string creation_timestamp = 30525366; + + // Optional. An optional description of this resource. Provide this property when you + // create the resource. + optional string description = 422937596; + + // Output only. [Output Only] The unique identifier for the resource. This identifier is + // defined by the server. + optional uint64 id = 3355; + + // Output only. [Output Only] Type of the resource. Alwayscompute#snapshotGroup for SnapshotGroup + // resources. + optional string kind = 3292052; + + // Identifier. Name of the resource; provided by the client when the resource is created. + // The name must be 1-63 characters long, and comply withRFC1035. + // Specifically, the name must be 1-63 characters long and match the regular + // expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first + // character must be a lowercase letter, and all following characters must be + // a dash, lowercase letter, or digit, except the last character, which cannot + // be a dash. + optional string name = 3373707; + + // Output only. [Output Only] Server-defined URL for the resource. + optional string self_link = 456214797; + + // Output only. [Output Only] Server-defined URL for this resource's resource id. + optional string self_link_with_id = 44520962; + + // Output only. [Output Only] + optional SnapshotGroupSourceInfo source_info = 451907154; + + // Input field for the source instant snapshot group. + optional string source_instant_snapshot_group = 525991686; + + // Output only. [Output Only] + optional SnapshotGroupSourceInstantSnapshotGroupInfo source_instant_snapshot_group_info = 62296647; + + // Output only. [Output Only] + // Check the Status enum for the list of possible values. + optional string status = 181260274; + +} + +// +message SnapshotGroupParameters { + // URLs of the zones where disks should be replicated to. Only applicable + // for regional resources. + repeated string replica_zones = 48438272; + + // The source snapshot group used to create disks. You can provide this as a + // partial or full URL to the resource. For example, the following are valid + // values: + // + // + // - https://www.googleapis.com/compute/v1/projects/project/global/snapshotGroups/snapshotGroup + // - projects/project/global/snapshotGroups/snapshotGroup + // - global/snapshotGroups/snapshotGroup + optional string source_snapshot_group = 225130728; + + // URL of the disk type resource describing which disk type to use to create + // disks. Provide this when creating the disk. For example:projects/project/zones/zone/diskTypes/pd-ssd. See Persistent disk + // types. + optional string type = 3575610; + +} + +// +message SnapshotGroupSourceInfo { + optional string consistency_group = 508183960; + + optional string consistency_group_id = 85599522; + +} + +// +message SnapshotGroupSourceInstantSnapshotGroupInfo { + optional string instant_snapshot_group = 223180386; + + optional string instant_snapshot_group_id = 157599768; + +} + // Contains a list of Snapshot resources. message SnapshotList { // [Output Only] Unique identifier for the resource; defined by the server. @@ -75271,7 +77293,7 @@ message SnapshotList { // Additional snapshot params. message SnapshotParams { - // Resource manager tags to be bound to the snapshot. Tag keys and values have + // Input only. Resource manager tags to be bound to the snapshot. Tag keys and values have // the same definition as resource // manager tags. Keys and values can be either in numeric format, // such as `tagKeys/{tag_key_id}` and `tagValues/456` or in namespaced @@ -76802,13 +78824,13 @@ message StoragePoolDisk { // Exapool provisioned capacities for each SKU type message StoragePoolExapoolProvisionedCapacityGb { - // Output only. Size, in GiB, of provisioned capacity-optimized capacity for this Exapool + // Size, in GiB, of provisioned capacity-optimized capacity for this Exapool optional int64 capacity_optimized = 251131874; - // Output only. Size, in GiB, of provisioned read-optimized capacity for this Exapool + // Size, in GiB, of provisioned read-optimized capacity for this Exapool optional int64 read_optimized = 389863870; - // Output only. Size, in GiB, of provisioned write-optimized capacity for this Exapool + // Size, in GiB, of provisioned write-optimized capacity for this Exapool optional int64 write_optimized = 492523719; } @@ -77261,9 +79283,9 @@ message Subnetwork { } - // Whether this subnetwork's ranges can conflict with existing static routes. + // Whether this subnetwork's ranges can conflict with existing custom routes. // Setting this to true allows this subnetwork's primary and secondary ranges - // to overlap with (and contain) static routes that have already been + // to overlap with (and contain) custom routes that have already been // configured on the corresponding network. // // For example if a static route has range 10.1.0.0/16, a subnet @@ -77279,8 +79301,6 @@ message Subnetwork { // // The default value is false and applies to all existing subnetworks and // automatically created subnetworks. - // - // This field cannot be set to true at resource creation time. optional bool allow_subnet_cidr_routes_overlap = 67856209; // Output only. [Output Only] Creation timestamp inRFC3339 @@ -77436,7 +79456,7 @@ message Subnetwork { // An array of configurations for secondary IP ranges for VM instances // contained in this subnetwork. The primary IP of such VM must belong to the // primary ipCidrRange of the subnetwork. The alias IPs may belong to either - // primary or secondary ranges. This field can be updated with apatch request. + // primary or secondary ranges. This field can be updated with apatch request. Supports both IPv4 and IPv6 ranges. repeated SubnetworkSecondaryRange secondary_ip_ranges = 136658915; // [Output Only] Server-defined URL for the resource. @@ -77631,18 +79651,31 @@ message SubnetworkSecondaryRange { // The range of IP addresses belonging to this subnetwork secondary range. // Provide this property when you create the subnetwork. Ranges must be // unique and non-overlapping with all primary and secondary IP ranges - // within a network. Only IPv4 is supported. The range can be any range - // listed in theValid + // within a network. Both IPv4 and IPv6 ranges are supported. For IPv4, + // the range can be any range listed in theValid // ranges list. + // + // For IPv6: + // The range must have a /64 prefix length. + // The range must be omitted, for auto-allocation from Google-defined ULA + // IPv6 range. + // For BYOGUA internal IPv6 secondary range, the range may be specified + // along with the `ipCollection` field. + // If an `ipCollection` is specified, the requested ip_cidr_range must lie + // within the range of the PDP referenced by the `ipCollection` field for + // allocation. + // If `ipCollection` field is specified, but ip_cidr_range is not, + // the range is auto-allocated from the PDP referenced by the `ipCollection` + // field. optional string ip_cidr_range = 98117322; // The name associated with this subnetwork secondary range, used when adding - // an alias IP range to a VM instance. + // an alias IP/IPv6 range to a VM instance. // The name must be 1-63 characters long, and comply withRFC1035. // The name must be unique within the subnetwork. optional string range_name = 332216397; - // The URL of the reserved internal range. + // The URL of the reserved internal range. Only IPv4 is supported. optional string reserved_internal_range = 286248754; } @@ -79556,6 +81589,10 @@ message TargetVpnGateway { // client when the VPN gateway is created. optional string network = 232872494; + // Input only. [Input Only] Additional params passed with the request, but not persisted + // as part of resource payload. + optional TargetVpnGatewayParams params = 78313862; + // [Output Only] URL of the region where the target VPN gateway resides. // You must specify this field as part of the HTTP request URL. It is // not settable as a field in the request body. @@ -79631,6 +81668,26 @@ message TargetVpnGatewayList { } +// +message TargetVpnGatewayParams { + // Tag keys/values directly bound to this resource. + // Tag keys and values have the same definition as resource + // manager tags. The field is allowed for INSERT + // only. The keys/values to set on the resource should be specified in + // either ID { : } or Namespaced format + // { : }. + // For example the following are valid inputs: + // * {"tagKeys/333" : "tagValues/444", "tagKeys/123" : "tagValues/456"} + // * {"123/environment" : "production", "345/abc" : "xyz"} + // Note: + // * Invalid combinations of ID & namespaced format is not supported. For + // instance: {"123/environment" : "tagValues/444"} is invalid. + // * Inconsistent format is not supported. For instance: + // {"tagKeys/333" : "tagValues/444", "123/env" : "prod"} is invalid. + map resource_manager_tags = 377671164; + +} + // message TargetVpnGatewaysScopedList { // [Output Only] A list of target VPN gateways contained in this scope. @@ -79918,6 +81975,22 @@ message TestIamPermissionsInstanceTemplateRequest { } +// A request message for InstantSnapshotGroups.TestIamPermissions. See the method description for details. +message TestIamPermissionsInstantSnapshotGroupRequest { + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + TestPermissionsRequest test_permissions_request_resource = 439214758 [(google.api.field_behavior) = REQUIRED]; + + // The name of the zone for this request. + string zone = 3744684 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for InstantSnapshots.TestIamPermissions. See the method description for details. message TestIamPermissionsInstantSnapshotRequest { // Project ID for this request. @@ -80326,6 +82399,22 @@ message TestIamPermissionsRegionInstanceGroupRequest { } +// A request message for RegionInstantSnapshotGroups.TestIamPermissions. See the method description for details. +message TestIamPermissionsRegionInstantSnapshotGroupRequest { + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // The name of the region for this request. + string region = 138946292 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + TestPermissionsRequest test_permissions_request_resource = 439214758 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for RegionInstantSnapshots.TestIamPermissions. See the method description for details. message TestIamPermissionsRegionInstantSnapshotRequest { // Project ID for this request. @@ -80614,6 +82703,19 @@ message TestIamPermissionsServiceAttachmentRequest { } +// A request message for SnapshotGroups.TestIamPermissions. See the method description for details. +message TestIamPermissionsSnapshotGroupRequest { + // Project ID for this request. + string project = 227560217 [(google.api.field_behavior) = REQUIRED]; + + // Name or id of the resource for this request. + string resource = 195806222 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + TestPermissionsRequest test_permissions_request_resource = 439214758 [(google.api.field_behavior) = REQUIRED]; + +} + // A request message for Snapshots.TestIamPermissions. See the method description for details. message TestIamPermissionsSnapshotRequest { // Project ID for this request. @@ -81217,44 +83319,267 @@ message UpdateDisplayDeviceInstanceRequest { } -// A request message for Firewalls.Update. See the method description for details. -message UpdateFirewallRequest { - // Name of the firewall rule to update. - string firewall = 511016192 [(google.api.field_behavior) = REQUIRED]; - - // The body resource for this request - Firewall firewall_resource = 41425005 [(google.api.field_behavior) = REQUIRED]; - - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - -} - -// A request message for FutureReservations.Update. See the method description for details. -message UpdateFutureReservationRequest { - // Name of the reservation to update. Name should conform to RFC1035. - string future_reservation = 56206160 [(google.api.field_behavior) = REQUIRED]; +// A request message for Firewalls.Update. See the method description for details. +message UpdateFirewallRequest { + // Name of the firewall rule to update. + string firewall = 511016192 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + Firewall firewall_resource = 41425005 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + +} + +// A request message for FutureReservations.Update. See the method description for details. +message UpdateFutureReservationRequest { + // Name of the reservation to update. Name should conform to RFC1035. + string future_reservation = 56206160 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + FutureReservation future_reservation_resource = 466750493 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // update_mask indicates fields to be updated as part of this request. + optional string update_mask = 500079778; + + // Name of the zone for this request. Name should conform to RFC1035. + string zone = 3744684 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "zone" + ]; + +} + +// A request message for GlobalVmExtensionPolicies.Update. See the method description for details. +message UpdateGlobalVmExtensionPolicyRequest { + // Name of the global VM extension policy to update. + string global_vm_extension_policy = 8334110 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + GlobalVmExtensionPolicy global_vm_extension_policy_resource = 101542927 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + +} + +// A request message for HealthChecks.Update. See the method description for details. +message UpdateHealthCheckRequest { + // Name of the HealthCheck resource to update. + string health_check = 308876645 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + HealthCheck health_check_resource = 201925032 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + +} + +// A request message for InstanceGroupManagers.Update. See the method description for details. +message UpdateInstanceGroupManagerRequest { + // The name of the instance group manager. + string instance_group_manager = 249363395 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + InstanceGroupManager instance_group_manager_resource = 261063946 [(google.api.field_behavior) = REQUIRED]; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The name of the zone + // where you want to create the managed instance group. + string zone = 3744684 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "zone" + ]; + +} + +// A request message for Instances.Update. See the method description for details. +message UpdateInstanceRequest { + // Specifies the action to take when updating an instance even if the + // updated properties do not require it. If not specified, then + // Compute Engine acts based on the minimum action that the updated + // properties require. + // Additional supported values which may be not listed in the enum directly due to technical reasons: + // INVALID + // NO_EFFECT + // REFRESH + // RESTART + enum MinimalAction { + // A value indicating that the enum field is not set. + UNDEFINED_MINIMAL_ACTION = 0; + + } + + // Specifies the most disruptive action that can be taken on the instance + // as part of the update. Compute Engine returns an error if the + // instance properties require a more disruptive action as part of the + // instance update. Valid options from lowest to highest are + // NO_EFFECT, REFRESH, and RESTART. + // Additional supported values which may be not listed in the enum directly due to technical reasons: + // INVALID + // NO_EFFECT + // REFRESH + // RESTART + enum MostDisruptiveAllowedAction { + // A value indicating that the enum field is not set. + UNDEFINED_MOST_DISRUPTIVE_ALLOWED_ACTION = 0; + + } + + // Name of the instance resource to update. + string instance = 18257045 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + Instance instance_resource = 215988344 [(google.api.field_behavior) = REQUIRED]; + + // Specifies the action to take when updating an instance even if the + // updated properties do not require it. If not specified, then + // Compute Engine acts based on the minimum action that the updated + // properties require. + // Check the MinimalAction enum for the list of possible values. + optional string minimal_action = 270567060; + + // Specifies the most disruptive action that can be taken on the instance + // as part of the update. Compute Engine returns an error if the + // instance properties require a more disruptive action as part of the + // instance update. Valid options from lowest to highest are + // NO_EFFECT, REFRESH, and RESTART. + // Check the MostDisruptiveAllowedAction enum for the list of possible values. + optional string most_disruptive_allowed_action = 66103053; + + // Project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // An optional request ID to identify requests. Specify a unique request ID so + // that if you must retry your request, the server will know to ignore the + // request if it has already been completed. + // + // For example, consider a situation where you make an initial request and + // the request times out. If you make the request again with the same + // request ID, the server can check if original operation with the same + // request ID was received, and if so, will ignore the second request. This + // prevents clients from accidentally creating duplicate commitments. + // + // The request ID must be + // a valid UUID with the exception that zero UUID is not supported + // (00000000-0000-0000-0000-000000000000). + optional string request_id = 37109963; + + // The name of the zone for this request. + string zone = 3744684 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "zone" + ]; + +} + +// A request message for Licenses.Update. See the method description for details. +message UpdateLicenseRequest { + // The license name for this request. + string license = 166757441 [(google.api.field_behavior) = REQUIRED]; // The body resource for this request - FutureReservation future_reservation_resource = 466750493 [(google.api.field_behavior) = REQUIRED]; + License license_resource = 437955148 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -81280,167 +83605,12 @@ message UpdateFutureReservationRequest { // update_mask indicates fields to be updated as part of this request. optional string update_mask = 500079778; - // Name of the zone for this request. Name should conform to RFC1035. - string zone = 3744684 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "zone" - ]; - -} - -// A request message for GlobalVmExtensionPolicies.Update. See the method description for details. -message UpdateGlobalVmExtensionPolicyRequest { - // Name of the global VM extension policy to update. - string global_vm_extension_policy = 8334110 [(google.api.field_behavior) = REQUIRED]; - - // The body resource for this request - GlobalVmExtensionPolicy global_vm_extension_policy_resource = 101542927 [(google.api.field_behavior) = REQUIRED]; - - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - -} - -// A request message for HealthChecks.Update. See the method description for details. -message UpdateHealthCheckRequest { - // Name of the HealthCheck resource to update. - string health_check = 308876645 [(google.api.field_behavior) = REQUIRED]; - - // The body resource for this request - HealthCheck health_check_resource = 201925032 [(google.api.field_behavior) = REQUIRED]; - - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - -} - -// A request message for InstanceGroupManagers.Update. See the method description for details. -message UpdateInstanceGroupManagerRequest { - // The name of the instance group manager. - string instance_group_manager = 249363395 [(google.api.field_behavior) = REQUIRED]; - - // The body resource for this request - InstanceGroupManager instance_group_manager_resource = 261063946 [(google.api.field_behavior) = REQUIRED]; - - // Project ID for this request. - string project = 227560217 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" - ]; - - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - - // The name of the zone - // where you want to create the managed instance group. - string zone = 3744684 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "zone" - ]; - } -// A request message for Instances.Update. See the method description for details. -message UpdateInstanceRequest { - // Specifies the action to take when updating an instance even if the - // updated properties do not require it. If not specified, then - // Compute Engine acts based on the minimum action that the updated - // properties require. - // Additional supported values which may be not listed in the enum directly due to technical reasons: - // INVALID - // NO_EFFECT - // REFRESH - // RESTART - enum MinimalAction { - // A value indicating that the enum field is not set. - UNDEFINED_MINIMAL_ACTION = 0; - - } - - // Specifies the most disruptive action that can be taken on the instance - // as part of the update. Compute Engine returns an error if the - // instance properties require a more disruptive action as part of the - // instance update. Valid options from lowest to highest are - // NO_EFFECT, REFRESH, and RESTART. - // Additional supported values which may be not listed in the enum directly due to technical reasons: - // INVALID - // NO_EFFECT - // REFRESH - // RESTART - enum MostDisruptiveAllowedAction { - // A value indicating that the enum field is not set. - UNDEFINED_MOST_DISRUPTIVE_ALLOWED_ACTION = 0; - - } - - // Name of the instance resource to update. - string instance = 18257045 [(google.api.field_behavior) = REQUIRED]; - +// A request message for Routers.UpdateNamedSet. See the method description for details. +message UpdateNamedSetRouterRequest { // The body resource for this request - Instance instance_resource = 215988344 [(google.api.field_behavior) = REQUIRED]; - - // Specifies the action to take when updating an instance even if the - // updated properties do not require it. If not specified, then - // Compute Engine acts based on the minimum action that the updated - // properties require. - // Check the MinimalAction enum for the list of possible values. - optional string minimal_action = 270567060; - - // Specifies the most disruptive action that can be taken on the instance - // as part of the update. Compute Engine returns an error if the - // instance properties require a more disruptive action as part of the - // instance update. Valid options from lowest to highest are - // NO_EFFECT, REFRESH, and RESTART. - // Check the MostDisruptiveAllowedAction enum for the list of possible values. - optional string most_disruptive_allowed_action = 66103053; + NamedSet named_set_resource = 408608401 [(google.api.field_behavior) = REQUIRED]; // Project ID for this request. string project = 227560217 [ @@ -81448,41 +83618,10 @@ message UpdateInstanceRequest { (google.cloud.operation_request_field) = "project" ]; - // An optional request ID to identify requests. Specify a unique request ID so - // that if you must retry your request, the server will know to ignore the - // request if it has already been completed. - // - // For example, consider a situation where you make an initial request and - // the request times out. If you make the request again with the same - // request ID, the server can check if original operation with the same - // request ID was received, and if so, will ignore the second request. This - // prevents clients from accidentally creating duplicate commitments. - // - // The request ID must be - // a valid UUID with the exception that zero UUID is not supported - // (00000000-0000-0000-0000-000000000000). - optional string request_id = 37109963; - - // The name of the zone for this request. - string zone = 3744684 [ - (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "zone" - ]; - -} - -// A request message for Licenses.Update. See the method description for details. -message UpdateLicenseRequest { - // The license name for this request. - string license = 166757441 [(google.api.field_behavior) = REQUIRED]; - - // The body resource for this request - License license_resource = 437955148 [(google.api.field_behavior) = REQUIRED]; - - // Project ID for this request. - string project = 227560217 [ + // Name of the region for this request. + string region = 138946292 [ (google.api.field_behavior) = REQUIRED, - (google.cloud.operation_request_field) = "project" + (google.cloud.operation_request_field) = "region" ]; // An optional request ID to identify requests. Specify a unique request ID so @@ -81500,8 +83639,8 @@ message UpdateLicenseRequest { // (00000000-0000-0000-0000-000000000000). optional string request_id = 37109963; - // update_mask indicates fields to be updated as part of this request. - optional string update_mask = 500079778; + // Name of the Router resource where Named Set is defined. + string router = 148608841 [(google.api.field_behavior) = REQUIRED]; } @@ -81985,6 +84124,34 @@ message UpdateReservationRequest { } +// A request message for ReservationSlots.Update. See the method description for details. +message UpdateReservationSlotRequest { + // The name of the sub-block resource. + string parent_name = 478151936 [(google.api.field_behavior) = REQUIRED]; + + // The project ID for this request. + string project = 227560217 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "project" + ]; + + // The name of the slot resource. + string reservation_slot = 277470865 [(google.api.field_behavior) = REQUIRED]; + + // The body resource for this request + ReservationSlot reservation_slot_resource = 408545788 [(google.api.field_behavior) = REQUIRED]; + + // The fields to be updated as part of this request. + optional string update_mask = 500079778; + + // The name of the zone for this request, formatted as RFC1035. + string zone = 3744684 [ + (google.api.field_behavior) = REQUIRED, + (google.cloud.operation_request_field) = "zone" + ]; + +} + // A request message for RegionCommitments.UpdateReservations. See the method description for details. message UpdateReservationsRegionCommitmentRequest { // Name of the commitment for which the reservations are being updated. @@ -82843,6 +85010,7 @@ message UsableSubnetwork { // Secondary IP range of a usable subnetwork. message UsableSubnetworkSecondaryRange { // The range of IP addresses belonging to this subnetwork secondary range. + // Can be Ipv4 or Ipv6 range. optional string ip_cidr_range = 98117322; // The name associated with this subnetwork secondary range, used when adding @@ -83080,8 +85248,8 @@ message VmExtensionPolicy { // An optional description of this resource. optional string description = 422937596; - // Required. A map of extension names (e.g., "cloudops") to their corresponding policy - // configurations. + // Required. A map of extension names (for example, "ops-agent") to their corresponding + // policy configurations. map extension_policies = 227761488; // Optional. Output only. [Output Only] Link to the global policy that manages this zone policy, if @@ -83117,7 +85285,7 @@ message VmExtensionPolicy { // The policy priority is an integer from 0 to 65535, inclusive. Lower // integers indicate higher priorities. If you do not specify a priority when // creating a rule, it is assigned a priority of 1000. If priorities are - // equal, the policy with the more recent creation timestamp takes precedence. + // equal, the policy with the most recent creation timestamp takes precedence. optional int32 priority = 445151652; // Output only. [Output Only] Server-defined fully-qualified URL for this resource. @@ -83329,6 +85497,10 @@ message VpnGateway { // client when the VPN gateway is created. optional string network = 232872494; + // Input only. [Input Only] Additional params passed with the request, but not persisted + // as part of resource payload. + optional VpnGatewayParams params = 78313862; + // Output only. [Output Only] URL of the region where the VPN gateway resides. optional string region = 138946292; @@ -83402,6 +85574,26 @@ message VpnGatewayList { } +// +message VpnGatewayParams { + // Tag keys/values directly bound to this resource. + // Tag keys and values have the same definition as resource + // manager tags. The field is allowed for INSERT + // only. The keys/values to set on the resource should be specified in + // either ID { : } or Namespaced format + // { : }. + // For example the following are valid inputs: + // * {"tagKeys/333" : "tagValues/444", "tagKeys/123" : "tagValues/456"} + // * {"123/environment" : "production", "345/abc" : "xyz"} + // Note: + // * Invalid combinations of ID & namespaced format is not supported. For + // instance: {"123/environment" : "tagValues/444"} is invalid. + // * Inconsistent format is not supported. For instance: + // {"tagKeys/333" : "tagValues/444", "123/env" : "prod"} is invalid. + map resource_manager_tags = 377671164; + +} + // message VpnGatewayStatus { // Output only. List of VPN connection for this VpnGateway. @@ -83707,6 +85899,10 @@ message VpnTunnel { // cannot be a dash. optional string name = 3373707; + // Input only. [Input Only] Additional params passed with the request, but not persisted + // as part of resource payload. + optional VpnTunnelParams params = 78313862; + // URL of the peer side external VPN gateway to which this VPN tunnel is // connected. // Provided by the client when the VPN tunnel is created. @@ -83874,6 +86070,26 @@ message VpnTunnelList { } +// +message VpnTunnelParams { + // Tag keys/values directly bound to this resource. + // Tag keys and values have the same definition as resource + // manager tags. The field is allowed for INSERT + // only. The keys/values to set on the resource should be specified in + // either ID { : } or Namespaced format + // { : }. + // For example the following are valid inputs: + // * {"tagKeys/333" : "tagValues/444", "tagKeys/123" : "tagValues/456"} + // * {"123/environment" : "production", "345/abc" : "xyz"} + // Note: + // * Invalid combinations of ID & namespaced format is not supported. For + // instance: {"123/environment" : "tagValues/444"} is invalid. + // * Inconsistent format is not supported. For instance: + // {"tagKeys/333" : "tagValues/444", "123/env" : "prod"} is invalid. + map resource_manager_tags = 377671164; + +} + // message VpnTunnelPhase1Algorithms { repeated string dh = 3204; @@ -84690,6 +86906,14 @@ message WithdrawPublicDelegatedPrefixeRequest { } +// +message WorkloadIdentityConfig { + optional string identity = 401109182; + + optional bool identity_certificate_enabled = 342892440; + +} + // message XpnHostList { // [Output Only] Unique identifier for the resource; defined by the server. @@ -85793,7 +88017,7 @@ service Disks { // Updates the specified disk with the data included in the request. // The update is performed only on selected fields included as part - // of update-mask. Only the following fields can be modified: user_license. + // of update-mask. rpc Update(UpdateDiskRequest) returns (Operation) { option (google.api.http) = { body: "disk_resource" @@ -86574,6 +88798,20 @@ service GlobalNetworkEndpointGroups { // Creates a network endpoint group in the specified project using the // parameters that are included in the request. + // + // Note: Use the following APIs to manage network endpoint groups: + // + // - + // To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity + // NEGs): zonal + // API + // - + // To manage NEGs with regional scope (such as regional internet NEGs, + // serverless NEGs, Private Service Connect NEGs): regional + // API + // - + // To manage NEGs with global scope (such as global internet NEGs):global + // API rpc Insert(InsertGlobalNetworkEndpointGroupRequest) returns (Operation) { option (google.api.http) = { body: "network_endpoint_group_resource" @@ -87202,6 +89440,16 @@ service InstanceGroupManagers { option (google.cloud.operation_service) = "ZoneOperations"; } + // Updates the accelerator topologies configuration. + rpc ConfigureAcceleratorTopologies(ConfigureAcceleratorTopologiesInstanceGroupManagerRequest) returns (Operation) { + option (google.api.http) = { + body: "instance_group_managers_configure_accelerator_topologies_request_resource" + post: "/compute/beta/projects/{project}/zones/{zone}/instanceGroupManagers/{instance_group_manager}/configureAcceleratorTopologies" + }; + option (google.api.method_signature) = "project,zone,instance_group_manager,instance_group_managers_configure_accelerator_topologies_request_resource"; + option (google.cloud.operation_service) = "ZoneOperations"; + } + // Creates instances with per-instance configurations in this managed instance // group. Instances are created using the current instance template. Thecreate instances operation is marked DONE if thecreateInstances request is successful. The underlying actions // take additional time. You must separately verify the status of thecreating or actions with the listmanagedinstances @@ -88530,6 +90778,81 @@ service Instances { } +// The InstantSnapshotGroups API. +service InstantSnapshotGroups { + option (google.api.default_host) = + "compute.googleapis.com"; + + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/compute," + "https://www.googleapis.com/auth/cloud-platform"; + + // deletes a Zonal InstantSnapshotGroup resource + rpc Delete(DeleteInstantSnapshotGroupRequest) returns (Operation) { + option (google.api.http) = { + delete: "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{instant_snapshot_group}" + }; + option (google.api.method_signature) = "project,zone,instant_snapshot_group"; + option (google.cloud.operation_service) = "ZoneOperations"; + } + + // returns the specified InstantSnapshotGroup resource in the specified zone. + rpc Get(GetInstantSnapshotGroupRequest) returns (InstantSnapshotGroup) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{instant_snapshot_group}" + }; + option (google.api.method_signature) = "project,zone,instant_snapshot_group"; + } + + // Gets the access control policy for a resource. May be empty if no such + // policy or resource exists. + rpc GetIamPolicy(GetIamPolicyInstantSnapshotGroupRequest) returns (Policy) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/getIamPolicy" + }; + option (google.api.method_signature) = "project,zone,resource"; + } + + // inserts a Zonal InstantSnapshotGroup resource + rpc Insert(InsertInstantSnapshotGroupRequest) returns (Operation) { + option (google.api.http) = { + body: "instant_snapshot_group_resource" + post: "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups" + }; + option (google.api.method_signature) = "project,zone,instant_snapshot_group_resource"; + option (google.cloud.operation_service) = "ZoneOperations"; + } + + // retrieves the list of InstantSnapshotGroup resources contained within + // the specified zone. + rpc List(ListInstantSnapshotGroupsRequest) returns (ListInstantSnapshotGroups) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups" + }; + option (google.api.method_signature) = "project,zone"; + } + + // Sets the access control policy on the specified resource. + // Replaces any existing policy. + rpc SetIamPolicy(SetIamPolicyInstantSnapshotGroupRequest) returns (Policy) { + option (google.api.http) = { + body: "zone_set_policy_request_resource" + post: "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/setIamPolicy" + }; + option (google.api.method_signature) = "project,zone,resource,zone_set_policy_request_resource"; + } + + // Returns permissions that a caller has on the specified resource. + rpc TestIamPermissions(TestIamPermissionsInstantSnapshotGroupRequest) returns (TestPermissionsResponse) { + option (google.api.http) = { + body: "test_permissions_request_resource" + post: "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/testIamPermissions" + }; + option (google.api.method_signature) = "project,zone,resource,test_permissions_request_resource"; + } + +} + // The InstantSnapshots API. service InstantSnapshots { option (google.api.default_host) = @@ -89606,6 +91929,20 @@ service NetworkEndpointGroups { // Creates a network endpoint group in the specified project using the // parameters that are included in the request. + // + // Note: Use the following APIs to manage network endpoint groups: + // + // - + // To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity + // NEGs): zonal + // API + // - + // To manage NEGs with regional scope (such as regional internet NEGs, + // serverless NEGs, Private Service Connect NEGs): regional + // API + // - + // To manage NEGs with global scope (such as global internet NEGs):global + // API rpc Insert(InsertNetworkEndpointGroupRequest) returns (Operation) { option (google.api.http) = { body: "network_endpoint_group_resource" @@ -91734,8 +94071,7 @@ service RegionDisks { } // Update the specified disk with the data included in the request. Update is - // performed only on selected fields included as part of update-mask. Only the - // following fields can be modified: user_license. + // performed only on selected fields included as part of update-mask. rpc Update(UpdateRegionDiskRequest) returns (Operation) { option (google.api.http) = { body: "disk_resource" @@ -92738,6 +95074,82 @@ service RegionInstances { } +// The RegionInstantSnapshotGroups API. +service RegionInstantSnapshotGroups { + option (google.api.default_host) = + "compute.googleapis.com"; + + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/compute," + "https://www.googleapis.com/auth/cloud-platform"; + + // deletes a Regional InstantSnapshotGroup resource + rpc Delete(DeleteRegionInstantSnapshotGroupRequest) returns (Operation) { + option (google.api.http) = { + delete: "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{instant_snapshot_group}" + }; + option (google.api.method_signature) = "project,region,instant_snapshot_group"; + option (google.cloud.operation_service) = "RegionOperations"; + } + + // returns the specified InstantSnapshotGroup resource in the specified + // region. + rpc Get(GetRegionInstantSnapshotGroupRequest) returns (InstantSnapshotGroup) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{instant_snapshot_group}" + }; + option (google.api.method_signature) = "project,region,instant_snapshot_group"; + } + + // Gets the access control policy for a resource. May be empty if no such + // policy or resource exists. + rpc GetIamPolicy(GetIamPolicyRegionInstantSnapshotGroupRequest) returns (Policy) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/getIamPolicy" + }; + option (google.api.method_signature) = "project,region,resource"; + } + + // creates a Regional InstantSnapshotGroup resource + rpc Insert(InsertRegionInstantSnapshotGroupRequest) returns (Operation) { + option (google.api.http) = { + body: "instant_snapshot_group_resource" + post: "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups" + }; + option (google.api.method_signature) = "project,region,instant_snapshot_group_resource"; + option (google.cloud.operation_service) = "RegionOperations"; + } + + // retrieves the list of InstantSnapshotGroup resources contained within + // the specified region. + rpc List(ListRegionInstantSnapshotGroupsRequest) returns (ListInstantSnapshotGroups) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups" + }; + option (google.api.method_signature) = "project,region"; + } + + // Sets the access control policy on the specified resource. + // Replaces any existing policy. + rpc SetIamPolicy(SetIamPolicyRegionInstantSnapshotGroupRequest) returns (Policy) { + option (google.api.http) = { + body: "region_set_policy_request_resource" + post: "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/setIamPolicy" + }; + option (google.api.method_signature) = "project,region,resource,region_set_policy_request_resource"; + } + + // Returns permissions that a caller has on the specified resource. + rpc TestIamPermissions(TestIamPermissionsRegionInstantSnapshotGroupRequest) returns (TestPermissionsResponse) { + option (google.api.http) = { + body: "test_permissions_request_resource" + post: "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/testIamPermissions" + }; + option (google.api.method_signature) = "project,region,resource,test_permissions_request_resource"; + } + +} + // The RegionInstantSnapshots API. service RegionInstantSnapshots { option (google.api.default_host) = @@ -92955,6 +95367,20 @@ service RegionNetworkEndpointGroups { // Creates a network endpoint group in the specified project using the // parameters that are included in the request. + // + // Note: Use the following APIs to manage network endpoint groups: + // + // - + // To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity + // NEGs): zonal + // API + // - + // To manage NEGs with regional scope (such as regional internet NEGs, + // serverless NEGs, Private Service Connect NEGs): regional + // API + // - + // To manage NEGs with global scope (such as global internet NEGs):global + // API rpc Insert(InsertRegionNetworkEndpointGroupRequest) returns (Operation) { option (google.api.http) = { body: "network_endpoint_group_resource" @@ -94251,6 +96677,43 @@ service ReservationBlocks { } +// The ReservationSlots API. +service ReservationSlots { + option (google.api.default_host) = + "compute.googleapis.com"; + + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/compute," + "https://www.googleapis.com/auth/cloud-platform"; + + // Retrieves information about the specified reservation slot. + rpc Get(GetReservationSlotRequest) returns (ReservationSlotsGetResponse) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots/{reservation_slot}" + }; + option (google.api.method_signature) = "project,zone,parent_name,reservation_slot"; + } + + // Retrieves a list of reservation slots under a single reservation. + rpc List(ListReservationSlotsRequest) returns (ReservationSlotsListResponse) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots" + }; + option (google.api.method_signature) = "project,zone,parent_name"; + } + + // Update a reservation slot in the specified sub-block. + rpc Update(UpdateReservationSlotRequest) returns (Operation) { + option (google.api.http) = { + body: "reservation_slot_resource" + post: "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots/{reservation_slot}" + }; + option (google.api.method_signature) = "project,zone,parent_name,reservation_slot,reservation_slot_resource"; + option (google.cloud.operation_service) = "ZoneOperations"; + } + +} + // The ReservationSubBlocks API. service ReservationSubBlocks { option (google.api.default_host) = @@ -94263,7 +96726,7 @@ service ReservationSubBlocks { // Retrieves information about the specified reservation subBlock. rpc Get(GetReservationSubBlockRequest) returns (ReservationSubBlocksGetResponse) { option (google.api.http) = { - get: "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}" + get: "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}" }; option (google.api.method_signature) = "project,zone,parent_name,reservation_sub_block"; } @@ -94272,7 +96735,7 @@ service ReservationSubBlocks { // policy or resource exists. rpc GetIamPolicy(GetIamPolicyReservationSubBlockRequest) returns (Policy) { option (google.api.http) = { - get: "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/getIamPolicy" + get: "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/getIamPolicy" }; option (google.api.method_signature) = "project,zone,parent_resource,resource"; } @@ -94280,7 +96743,7 @@ service ReservationSubBlocks { // Retrieves a list of reservation subBlocks under a single reservation. rpc List(ListReservationSubBlocksRequest) returns (ReservationSubBlocksListResponse) { option (google.api.http) = { - get: "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks" + get: "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks" }; option (google.api.method_signature) = "project,zone,parent_name"; } @@ -94288,7 +96751,7 @@ service ReservationSubBlocks { // Allows customers to perform maintenance on a reservation subBlock rpc PerformMaintenance(PerformMaintenanceReservationSubBlockRequest) returns (Operation) { option (google.api.http) = { - post: "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/performMaintenance" + post: "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}/performMaintenance" }; option (google.api.method_signature) = "project,zone,parent_name,reservation_sub_block"; option (google.cloud.operation_service) = "ZoneOperations"; @@ -94298,7 +96761,7 @@ service ReservationSubBlocks { rpc ReportFaulty(ReportFaultyReservationSubBlockRequest) returns (Operation) { option (google.api.http) = { body: "reservation_sub_blocks_report_faulty_request_resource" - post: "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty" + post: "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}/reportFaulty" }; option (google.api.method_signature) = "project,zone,parent_name,reservation_sub_block,reservation_sub_blocks_report_faulty_request_resource"; option (google.cloud.operation_service) = "ZoneOperations"; @@ -94309,7 +96772,7 @@ service ReservationSubBlocks { rpc SetIamPolicy(SetIamPolicyReservationSubBlockRequest) returns (Policy) { option (google.api.http) = { body: "zone_set_nested_policy_request_resource" - post: "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/setIamPolicy" + post: "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/setIamPolicy" }; option (google.api.method_signature) = "project,zone,parent_resource,resource,zone_set_nested_policy_request_resource"; } @@ -94318,7 +96781,7 @@ service ReservationSubBlocks { rpc TestIamPermissions(TestIamPermissionsReservationSubBlockRequest) returns (TestPermissionsResponse) { option (google.api.http) = { body: "test_permissions_request_resource" - post: "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/testIamPermissions" + post: "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/testIamPermissions" }; option (google.api.method_signature) = "project,zone,parent_resource,resource,test_permissions_request_resource"; } @@ -94660,6 +97123,15 @@ service Routers { option (google.cloud.operation_service) = "RegionOperations"; } + // Deletes Named Set + rpc DeleteNamedSet(DeleteNamedSetRouterRequest) returns (Operation) { + option (google.api.http) = { + post: "/compute/beta/projects/{project}/regions/{region}/routers/{router}/deleteNamedSet" + }; + option (google.api.method_signature) = "project,region,router"; + option (google.cloud.operation_service) = "RegionOperations"; + } + // Deletes Route Policy rpc DeleteRoutePolicy(DeleteRoutePolicyRouterRequest) returns (Operation) { option (google.api.http) = { @@ -94677,6 +97149,14 @@ service Routers { option (google.api.method_signature) = "project,region,router"; } + // Returns specified Named Set + rpc GetNamedSet(GetNamedSetRouterRequest) returns (RoutersGetNamedSetResponse) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/regions/{region}/routers/{router}/getNamedSet" + }; + option (google.api.method_signature) = "project,region,router"; + } + // Retrieves runtime NAT IP information. rpc GetNatIpInfo(GetNatIpInfoRouterRequest) returns (NatIpInfoResponse) { option (google.api.http) = { @@ -94736,6 +97216,15 @@ service Routers { option (google.api.method_signature) = "project,region,router"; } + // Retrieves a list of router named set subresources available to the + // specified project. + rpc ListNamedSets(ListNamedSetsRoutersRequest) returns (RoutersListNamedSets) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/regions/{region}/routers/{router}/listNamedSets" + }; + option (google.api.method_signature) = "project,region,router"; + } + // Retrieves a list of router route policy subresources available to the // specified project. rpc ListRoutePolicies(ListRoutePoliciesRoutersRequest) returns (RoutersListRoutePolicies) { @@ -94758,6 +97247,16 @@ service Routers { option (google.cloud.operation_service) = "RegionOperations"; } + // Patches Named Set + rpc PatchNamedSet(PatchNamedSetRouterRequest) returns (Operation) { + option (google.api.http) = { + body: "named_set_resource" + post: "/compute/beta/projects/{project}/regions/{region}/routers/{router}/patchNamedSet" + }; + option (google.api.method_signature) = "project,region,router,named_set_resource"; + option (google.cloud.operation_service) = "RegionOperations"; + } + // Patches Route Policy rpc PatchRoutePolicy(PatchRoutePolicyRouterRequest) returns (Operation) { option (google.api.http) = { @@ -94800,6 +97299,16 @@ service Routers { option (google.cloud.operation_service) = "RegionOperations"; } + // Updates or creates new Named Set + rpc UpdateNamedSet(UpdateNamedSetRouterRequest) returns (Operation) { + option (google.api.http) = { + body: "named_set_resource" + post: "/compute/beta/projects/{project}/regions/{region}/routers/{router}/updateNamedSet" + }; + option (google.api.method_signature) = "project,region,router,named_set_resource"; + option (google.cloud.operation_service) = "RegionOperations"; + } + // Updates or creates new Route Policy rpc UpdateRoutePolicy(UpdateRoutePolicyRouterRequest) returns (Operation) { option (google.api.http) = { @@ -95109,6 +97618,82 @@ service ServiceAttachments { } +// The SnapshotGroups API. +service SnapshotGroups { + option (google.api.default_host) = + "compute.googleapis.com"; + + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/compute," + "https://www.googleapis.com/auth/cloud-platform"; + + // Deletes the specified SnapshotGroup resource + rpc Delete(DeleteSnapshotGroupRequest) returns (Operation) { + option (google.api.http) = { + delete: "/compute/beta/projects/{project}/global/snapshotGroups/{snapshot_group}" + }; + option (google.api.method_signature) = "project,snapshot_group"; + option (google.cloud.operation_service) = "GlobalOperations"; + } + + // returns the specified SnapshotGroup resource. + rpc Get(GetSnapshotGroupRequest) returns (SnapshotGroup) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/global/snapshotGroups/{snapshot_group}" + }; + option (google.api.method_signature) = "project,snapshot_group"; + } + + // Gets the access control policy for a resource. May be empty if no such + // policy or resource exists. + rpc GetIamPolicy(GetIamPolicySnapshotGroupRequest) returns (Policy) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/getIamPolicy" + }; + option (google.api.method_signature) = "project,resource"; + } + + // Creates a snapshot group in the specified project using the data included + // in the request. + rpc Insert(InsertSnapshotGroupRequest) returns (Operation) { + option (google.api.http) = { + body: "snapshot_group_resource" + post: "/compute/beta/projects/{project}/global/snapshotGroups" + }; + option (google.api.method_signature) = "project,snapshot_group_resource"; + option (google.cloud.operation_service) = "GlobalOperations"; + } + + // retrieves the list of SnapshotGroup resources contained within + // the specified project. + rpc List(ListSnapshotGroupsRequest) returns (ListSnapshotGroups) { + option (google.api.http) = { + get: "/compute/beta/projects/{project}/global/snapshotGroups" + }; + option (google.api.method_signature) = "project"; + } + + // Sets the access control policy on the specified resource. + // Replaces any existing policy. + rpc SetIamPolicy(SetIamPolicySnapshotGroupRequest) returns (Policy) { + option (google.api.http) = { + body: "global_set_policy_request_resource" + post: "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/setIamPolicy" + }; + option (google.api.method_signature) = "project,resource,global_set_policy_request_resource"; + } + + // Returns permissions that a caller has on the specified resource. + rpc TestIamPermissions(TestIamPermissionsSnapshotGroupRequest) returns (TestPermissionsResponse) { + option (google.api.http) = { + body: "test_permissions_request_resource" + post: "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/testIamPermissions" + }; + option (google.api.method_signature) = "project,resource,test_permissions_request_resource"; + } + +} + // The SnapshotSettings API. service SnapshotSettingsService { option (google.api.default_host) = diff --git a/packages/google-cloud-compute/protos/protos.d.ts b/packages/google-cloud-compute/protos/protos.d.ts index 5ef046ac5d1..132209733f3 100644 --- a/packages/google-cloud-compute/protos/protos.d.ts +++ b/packages/google-cloud-compute/protos/protos.d.ts @@ -257920,6 +257920,9 @@ export namespace google { /** Backend maxUtilization */ maxUtilization?: (number|null); + /** Backend orchestrationInfo */ + orchestrationInfo?: (google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo|null); + /** Backend preference */ preference?: (string|null); @@ -257984,6 +257987,9 @@ export namespace google { /** Backend maxUtilization. */ public maxUtilization?: (number|null); + /** Backend orchestrationInfo. */ + public orchestrationInfo?: (google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo|null); + /** Backend preference. */ public preference?: (string|null); @@ -258097,6 +258103,103 @@ export namespace google { } } + /** Properties of a BackendBackendOrchestrationInfo. */ + interface IBackendBackendOrchestrationInfo { + + /** BackendBackendOrchestrationInfo resourceUri */ + resourceUri?: (string|null); + } + + /** Represents a BackendBackendOrchestrationInfo. */ + class BackendBackendOrchestrationInfo implements IBackendBackendOrchestrationInfo { + + /** + * Constructs a new BackendBackendOrchestrationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo); + + /** BackendBackendOrchestrationInfo resourceUri. */ + public resourceUri?: (string|null); + + /** + * Creates a new BackendBackendOrchestrationInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns BackendBackendOrchestrationInfo instance + */ + public static create(properties?: google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo): google.cloud.compute.v1beta.BackendBackendOrchestrationInfo; + + /** + * Encodes the specified BackendBackendOrchestrationInfo message. Does not implicitly {@link google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.verify|verify} messages. + * @param message BackendBackendOrchestrationInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BackendBackendOrchestrationInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.verify|verify} messages. + * @param message BackendBackendOrchestrationInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BackendBackendOrchestrationInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BackendBackendOrchestrationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.BackendBackendOrchestrationInfo; + + /** + * Decodes a BackendBackendOrchestrationInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BackendBackendOrchestrationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.BackendBackendOrchestrationInfo; + + /** + * Verifies a BackendBackendOrchestrationInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BackendBackendOrchestrationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackendBackendOrchestrationInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.BackendBackendOrchestrationInfo; + + /** + * Creates a plain object from a BackendBackendOrchestrationInfo message. Also converts values to other types if specified. + * @param message BackendBackendOrchestrationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.BackendBackendOrchestrationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackendBackendOrchestrationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackendBackendOrchestrationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a BackendBucket. */ interface IBackendBucket { @@ -259674,6 +259777,9 @@ export namespace google { /** BackendService networkPassThroughLbTrafficPolicy */ networkPassThroughLbTrafficPolicy?: (google.cloud.compute.v1beta.IBackendServiceNetworkPassThroughLbTrafficPolicy|null); + /** BackendService orchestrationInfo */ + orchestrationInfo?: (google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo|null); + /** BackendService outlierDetection */ outlierDetection?: (google.cloud.compute.v1beta.IOutlierDetection|null); @@ -259840,6 +259946,9 @@ export namespace google { /** BackendService networkPassThroughLbTrafficPolicy. */ public networkPassThroughLbTrafficPolicy?: (google.cloud.compute.v1beta.IBackendServiceNetworkPassThroughLbTrafficPolicy|null); + /** BackendService orchestrationInfo. */ + public orchestrationInfo?: (google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo|null); + /** BackendService outlierDetection. */ public outlierDetection?: (google.cloud.compute.v1beta.IOutlierDetection|null); @@ -262656,6 +262765,103 @@ export namespace google { } } + /** Properties of a BackendServiceOrchestrationInfo. */ + interface IBackendServiceOrchestrationInfo { + + /** BackendServiceOrchestrationInfo resourceUri */ + resourceUri?: (string|null); + } + + /** Represents a BackendServiceOrchestrationInfo. */ + class BackendServiceOrchestrationInfo implements IBackendServiceOrchestrationInfo { + + /** + * Constructs a new BackendServiceOrchestrationInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo); + + /** BackendServiceOrchestrationInfo resourceUri. */ + public resourceUri?: (string|null); + + /** + * Creates a new BackendServiceOrchestrationInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns BackendServiceOrchestrationInfo instance + */ + public static create(properties?: google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo): google.cloud.compute.v1beta.BackendServiceOrchestrationInfo; + + /** + * Encodes the specified BackendServiceOrchestrationInfo message. Does not implicitly {@link google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.verify|verify} messages. + * @param message BackendServiceOrchestrationInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BackendServiceOrchestrationInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.verify|verify} messages. + * @param message BackendServiceOrchestrationInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BackendServiceOrchestrationInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BackendServiceOrchestrationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.BackendServiceOrchestrationInfo; + + /** + * Decodes a BackendServiceOrchestrationInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BackendServiceOrchestrationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.BackendServiceOrchestrationInfo; + + /** + * Verifies a BackendServiceOrchestrationInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BackendServiceOrchestrationInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BackendServiceOrchestrationInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.BackendServiceOrchestrationInfo; + + /** + * Creates a plain object from a BackendServiceOrchestrationInfo message. Also converts values to other types if specified. + * @param message BackendServiceOrchestrationInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.BackendServiceOrchestrationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BackendServiceOrchestrationInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BackendServiceOrchestrationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a BackendServiceParams. */ interface IBackendServiceParams { @@ -264469,6 +264675,12 @@ export namespace google { /** Properties of a BulkInsertDiskResource. */ interface IBulkInsertDiskResource { + /** BulkInsertDiskResource instantSnapshotGroupParameters */ + instantSnapshotGroupParameters?: (google.cloud.compute.v1beta.IInstantSnapshotGroupParameters|null); + + /** BulkInsertDiskResource snapshotGroupParameters */ + snapshotGroupParameters?: (google.cloud.compute.v1beta.ISnapshotGroupParameters|null); + /** BulkInsertDiskResource sourceConsistencyGroupPolicy */ sourceConsistencyGroupPolicy?: (string|null); } @@ -264482,6 +264694,12 @@ export namespace google { */ constructor(properties?: google.cloud.compute.v1beta.IBulkInsertDiskResource); + /** BulkInsertDiskResource instantSnapshotGroupParameters. */ + public instantSnapshotGroupParameters?: (google.cloud.compute.v1beta.IInstantSnapshotGroupParameters|null); + + /** BulkInsertDiskResource snapshotGroupParameters. */ + public snapshotGroupParameters?: (google.cloud.compute.v1beta.ISnapshotGroupParameters|null); + /** BulkInsertDiskResource sourceConsistencyGroupPolicy. */ public sourceConsistencyGroupPolicy?: (string|null); @@ -265949,6 +266167,404 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a CachePolicy. */ + interface ICachePolicy { + + /** CachePolicy cacheBypassRequestHeaderNames */ + cacheBypassRequestHeaderNames?: (string[]|null); + + /** CachePolicy cacheKeyPolicy */ + cacheKeyPolicy?: (google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy|null); + + /** CachePolicy cacheMode */ + cacheMode?: (string|null); + + /** CachePolicy clientTtl */ + clientTtl?: (google.cloud.compute.v1beta.IDuration|null); + + /** CachePolicy defaultTtl */ + defaultTtl?: (google.cloud.compute.v1beta.IDuration|null); + + /** CachePolicy maxTtl */ + maxTtl?: (google.cloud.compute.v1beta.IDuration|null); + + /** CachePolicy negativeCaching */ + negativeCaching?: (boolean|null); + + /** CachePolicy negativeCachingPolicy */ + negativeCachingPolicy?: (google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy[]|null); + + /** CachePolicy requestCoalescing */ + requestCoalescing?: (boolean|null); + + /** CachePolicy serveWhileStale */ + serveWhileStale?: (google.cloud.compute.v1beta.IDuration|null); + } + + /** Represents a CachePolicy. */ + class CachePolicy implements ICachePolicy { + + /** + * Constructs a new CachePolicy. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ICachePolicy); + + /** CachePolicy cacheBypassRequestHeaderNames. */ + public cacheBypassRequestHeaderNames: string[]; + + /** CachePolicy cacheKeyPolicy. */ + public cacheKeyPolicy?: (google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy|null); + + /** CachePolicy cacheMode. */ + public cacheMode?: (string|null); + + /** CachePolicy clientTtl. */ + public clientTtl?: (google.cloud.compute.v1beta.IDuration|null); + + /** CachePolicy defaultTtl. */ + public defaultTtl?: (google.cloud.compute.v1beta.IDuration|null); + + /** CachePolicy maxTtl. */ + public maxTtl?: (google.cloud.compute.v1beta.IDuration|null); + + /** CachePolicy negativeCaching. */ + public negativeCaching?: (boolean|null); + + /** CachePolicy negativeCachingPolicy. */ + public negativeCachingPolicy: google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy[]; + + /** CachePolicy requestCoalescing. */ + public requestCoalescing?: (boolean|null); + + /** CachePolicy serveWhileStale. */ + public serveWhileStale?: (google.cloud.compute.v1beta.IDuration|null); + + /** + * Creates a new CachePolicy instance using the specified properties. + * @param [properties] Properties to set + * @returns CachePolicy instance + */ + public static create(properties?: google.cloud.compute.v1beta.ICachePolicy): google.cloud.compute.v1beta.CachePolicy; + + /** + * Encodes the specified CachePolicy message. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicy.verify|verify} messages. + * @param message CachePolicy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ICachePolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CachePolicy message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicy.verify|verify} messages. + * @param message CachePolicy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ICachePolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CachePolicy message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CachePolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.CachePolicy; + + /** + * Decodes a CachePolicy message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CachePolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.CachePolicy; + + /** + * Verifies a CachePolicy message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CachePolicy message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CachePolicy + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.CachePolicy; + + /** + * Creates a plain object from a CachePolicy message. Also converts values to other types if specified. + * @param message CachePolicy + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.CachePolicy, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CachePolicy to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CachePolicy + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace CachePolicy { + + /** CacheMode enum. */ + enum CacheMode { + UNDEFINED_CACHE_MODE = 0, + CACHE_ALL_STATIC = 355027945, + FORCE_CACHE_ALL = 486026928, + USE_ORIGIN_HEADERS = 55380261 + } + } + + /** Properties of a CachePolicyCacheKeyPolicy. */ + interface ICachePolicyCacheKeyPolicy { + + /** CachePolicyCacheKeyPolicy excludedQueryParameters */ + excludedQueryParameters?: (string[]|null); + + /** CachePolicyCacheKeyPolicy includeHost */ + includeHost?: (boolean|null); + + /** CachePolicyCacheKeyPolicy includeProtocol */ + includeProtocol?: (boolean|null); + + /** CachePolicyCacheKeyPolicy includeQueryString */ + includeQueryString?: (boolean|null); + + /** CachePolicyCacheKeyPolicy includedCookieNames */ + includedCookieNames?: (string[]|null); + + /** CachePolicyCacheKeyPolicy includedHeaderNames */ + includedHeaderNames?: (string[]|null); + + /** CachePolicyCacheKeyPolicy includedQueryParameters */ + includedQueryParameters?: (string[]|null); + } + + /** Represents a CachePolicyCacheKeyPolicy. */ + class CachePolicyCacheKeyPolicy implements ICachePolicyCacheKeyPolicy { + + /** + * Constructs a new CachePolicyCacheKeyPolicy. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy); + + /** CachePolicyCacheKeyPolicy excludedQueryParameters. */ + public excludedQueryParameters: string[]; + + /** CachePolicyCacheKeyPolicy includeHost. */ + public includeHost?: (boolean|null); + + /** CachePolicyCacheKeyPolicy includeProtocol. */ + public includeProtocol?: (boolean|null); + + /** CachePolicyCacheKeyPolicy includeQueryString. */ + public includeQueryString?: (boolean|null); + + /** CachePolicyCacheKeyPolicy includedCookieNames. */ + public includedCookieNames: string[]; + + /** CachePolicyCacheKeyPolicy includedHeaderNames. */ + public includedHeaderNames: string[]; + + /** CachePolicyCacheKeyPolicy includedQueryParameters. */ + public includedQueryParameters: string[]; + + /** + * Creates a new CachePolicyCacheKeyPolicy instance using the specified properties. + * @param [properties] Properties to set + * @returns CachePolicyCacheKeyPolicy instance + */ + public static create(properties?: google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy): google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy; + + /** + * Encodes the specified CachePolicyCacheKeyPolicy message. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.verify|verify} messages. + * @param message CachePolicyCacheKeyPolicy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CachePolicyCacheKeyPolicy message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.verify|verify} messages. + * @param message CachePolicyCacheKeyPolicy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CachePolicyCacheKeyPolicy message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CachePolicyCacheKeyPolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy; + + /** + * Decodes a CachePolicyCacheKeyPolicy message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CachePolicyCacheKeyPolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy; + + /** + * Verifies a CachePolicyCacheKeyPolicy message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CachePolicyCacheKeyPolicy message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CachePolicyCacheKeyPolicy + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy; + + /** + * Creates a plain object from a CachePolicyCacheKeyPolicy message. Also converts values to other types if specified. + * @param message CachePolicyCacheKeyPolicy + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CachePolicyCacheKeyPolicy to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CachePolicyCacheKeyPolicy + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CachePolicyNegativeCachingPolicy. */ + interface ICachePolicyNegativeCachingPolicy { + + /** CachePolicyNegativeCachingPolicy code */ + code?: (number|null); + + /** CachePolicyNegativeCachingPolicy ttl */ + ttl?: (google.cloud.compute.v1beta.IDuration|null); + } + + /** Represents a CachePolicyNegativeCachingPolicy. */ + class CachePolicyNegativeCachingPolicy implements ICachePolicyNegativeCachingPolicy { + + /** + * Constructs a new CachePolicyNegativeCachingPolicy. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy); + + /** CachePolicyNegativeCachingPolicy code. */ + public code?: (number|null); + + /** CachePolicyNegativeCachingPolicy ttl. */ + public ttl?: (google.cloud.compute.v1beta.IDuration|null); + + /** + * Creates a new CachePolicyNegativeCachingPolicy instance using the specified properties. + * @param [properties] Properties to set + * @returns CachePolicyNegativeCachingPolicy instance + */ + public static create(properties?: google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy): google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy; + + /** + * Encodes the specified CachePolicyNegativeCachingPolicy message. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.verify|verify} messages. + * @param message CachePolicyNegativeCachingPolicy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CachePolicyNegativeCachingPolicy message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.verify|verify} messages. + * @param message CachePolicyNegativeCachingPolicy message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CachePolicyNegativeCachingPolicy message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CachePolicyNegativeCachingPolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy; + + /** + * Decodes a CachePolicyNegativeCachingPolicy message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CachePolicyNegativeCachingPolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy; + + /** + * Verifies a CachePolicyNegativeCachingPolicy message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CachePolicyNegativeCachingPolicy message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CachePolicyNegativeCachingPolicy + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy; + + /** + * Creates a plain object from a CachePolicyNegativeCachingPolicy message. Also converts values to other types if specified. + * @param message CachePolicyNegativeCachingPolicy + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CachePolicyNegativeCachingPolicy to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CachePolicyNegativeCachingPolicy + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a CalendarModeAdviceRequest. */ interface ICalendarModeAdviceRequest { @@ -267687,6 +268303,7 @@ export namespace google { GENERAL_PURPOSE_N2 = 301912156, GENERAL_PURPOSE_N2D = 232471400, GENERAL_PURPOSE_N4 = 301912158, + GENERAL_PURPOSE_N4A = 232471459, GENERAL_PURPOSE_N4D = 232471462, GENERAL_PURPOSE_T2D = 232477166, GRAPHICS_OPTIMIZED = 68500563, @@ -268804,6 +269421,127 @@ export namespace google { } } + /** Properties of a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest. */ + interface IConfigureAcceleratorTopologiesInstanceGroupManagerRequest { + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instanceGroupManager */ + instanceGroupManager?: (string|null); + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instanceGroupManagersConfigureAcceleratorTopologiesRequestResource */ + instanceGroupManagersConfigureAcceleratorTopologiesRequestResource?: (google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest|null); + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest project */ + project?: (string|null); + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest requestId */ + requestId?: (string|null); + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest zone */ + zone?: (string|null); + } + + /** Represents a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest. */ + class ConfigureAcceleratorTopologiesInstanceGroupManagerRequest implements IConfigureAcceleratorTopologiesInstanceGroupManagerRequest { + + /** + * Constructs a new ConfigureAcceleratorTopologiesInstanceGroupManagerRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest); + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instanceGroupManager. */ + public instanceGroupManager: string; + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instanceGroupManagersConfigureAcceleratorTopologiesRequestResource. */ + public instanceGroupManagersConfigureAcceleratorTopologiesRequestResource?: (google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest|null); + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest project. */ + public project: string; + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest requestId. */ + public requestId?: (string|null); + + /** ConfigureAcceleratorTopologiesInstanceGroupManagerRequest zone. */ + public zone: string; + + /** + * Creates a new ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest): google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest; + + /** + * Encodes the specified ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.verify|verify} messages. + * @param message ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.verify|verify} messages. + * @param message ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest; + + /** + * Decodes a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest; + + /** + * Verifies a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest; + + /** + * Creates a plain object from a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message. Also converts values to other types if specified. + * @param message ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ConfigureAcceleratorTopologiesInstanceGroupManagerRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a ConnectionDraining. */ interface IConnectionDraining { @@ -274210,6 +274948,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a DeleteInstantSnapshotGroupRequest. */ + interface IDeleteInstantSnapshotGroupRequest { + + /** DeleteInstantSnapshotGroupRequest instantSnapshotGroup */ + instantSnapshotGroup?: (string|null); + + /** DeleteInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** DeleteInstantSnapshotGroupRequest requestId */ + requestId?: (string|null); + + /** DeleteInstantSnapshotGroupRequest zone */ + zone?: (string|null); + } + + /** Represents a DeleteInstantSnapshotGroupRequest. */ + class DeleteInstantSnapshotGroupRequest implements IDeleteInstantSnapshotGroupRequest { + + /** + * Constructs a new DeleteInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest); + + /** DeleteInstantSnapshotGroupRequest instantSnapshotGroup. */ + public instantSnapshotGroup: string; + + /** DeleteInstantSnapshotGroupRequest project. */ + public project: string; + + /** DeleteInstantSnapshotGroupRequest requestId. */ + public requestId?: (string|null); + + /** DeleteInstantSnapshotGroupRequest zone. */ + public zone: string; + + /** + * Creates a new DeleteInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest): google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest; + + /** + * Encodes the specified DeleteInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest.verify|verify} messages. + * @param message DeleteInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest.verify|verify} messages. + * @param message DeleteInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest; + + /** + * Decodes a DeleteInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest; + + /** + * Verifies a DeleteInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a DeleteInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message DeleteInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a DeleteInstantSnapshotRequest. */ interface IDeleteInstantSnapshotRequest { @@ -274985,6 +275838,127 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a DeleteNamedSetRouterRequest. */ + interface IDeleteNamedSetRouterRequest { + + /** DeleteNamedSetRouterRequest namedSet */ + namedSet?: (string|null); + + /** DeleteNamedSetRouterRequest project */ + project?: (string|null); + + /** DeleteNamedSetRouterRequest region */ + region?: (string|null); + + /** DeleteNamedSetRouterRequest requestId */ + requestId?: (string|null); + + /** DeleteNamedSetRouterRequest router */ + router?: (string|null); + } + + /** Represents a DeleteNamedSetRouterRequest. */ + class DeleteNamedSetRouterRequest implements IDeleteNamedSetRouterRequest { + + /** + * Constructs a new DeleteNamedSetRouterRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest); + + /** DeleteNamedSetRouterRequest namedSet. */ + public namedSet?: (string|null); + + /** DeleteNamedSetRouterRequest project. */ + public project: string; + + /** DeleteNamedSetRouterRequest region. */ + public region: string; + + /** DeleteNamedSetRouterRequest requestId. */ + public requestId?: (string|null); + + /** DeleteNamedSetRouterRequest router. */ + public router: string; + + /** + * Creates a new DeleteNamedSetRouterRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteNamedSetRouterRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest): google.cloud.compute.v1beta.DeleteNamedSetRouterRequest; + + /** + * Encodes the specified DeleteNamedSetRouterRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNamedSetRouterRequest.verify|verify} messages. + * @param message DeleteNamedSetRouterRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteNamedSetRouterRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNamedSetRouterRequest.verify|verify} messages. + * @param message DeleteNamedSetRouterRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteNamedSetRouterRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.DeleteNamedSetRouterRequest; + + /** + * Decodes a DeleteNamedSetRouterRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.DeleteNamedSetRouterRequest; + + /** + * Verifies a DeleteNamedSetRouterRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteNamedSetRouterRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteNamedSetRouterRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.DeleteNamedSetRouterRequest; + + /** + * Creates a plain object from a DeleteNamedSetRouterRequest message. Also converts values to other types if specified. + * @param message DeleteNamedSetRouterRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.DeleteNamedSetRouterRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteNamedSetRouterRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteNamedSetRouterRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a DeleteNetworkAttachmentRequest. */ interface IDeleteNetworkAttachmentRequest { @@ -278084,6 +279058,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a DeleteRegionInstantSnapshotGroupRequest. */ + interface IDeleteRegionInstantSnapshotGroupRequest { + + /** DeleteRegionInstantSnapshotGroupRequest instantSnapshotGroup */ + instantSnapshotGroup?: (string|null); + + /** DeleteRegionInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** DeleteRegionInstantSnapshotGroupRequest region */ + region?: (string|null); + + /** DeleteRegionInstantSnapshotGroupRequest requestId */ + requestId?: (string|null); + } + + /** Represents a DeleteRegionInstantSnapshotGroupRequest. */ + class DeleteRegionInstantSnapshotGroupRequest implements IDeleteRegionInstantSnapshotGroupRequest { + + /** + * Constructs a new DeleteRegionInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest); + + /** DeleteRegionInstantSnapshotGroupRequest instantSnapshotGroup. */ + public instantSnapshotGroup: string; + + /** DeleteRegionInstantSnapshotGroupRequest project. */ + public project: string; + + /** DeleteRegionInstantSnapshotGroupRequest region. */ + public region: string; + + /** DeleteRegionInstantSnapshotGroupRequest requestId. */ + public requestId?: (string|null); + + /** + * Creates a new DeleteRegionInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteRegionInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest): google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest; + + /** + * Encodes the specified DeleteRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message DeleteRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message DeleteRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest; + + /** + * Decodes a DeleteRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest; + + /** + * Verifies a DeleteRegionInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteRegionInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a DeleteRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message DeleteRegionInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteRegionInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteRegionInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a DeleteRegionInstantSnapshotRequest. */ interface IDeleteRegionInstantSnapshotRequest { @@ -281141,6 +282230,115 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a DeleteSnapshotGroupRequest. */ + interface IDeleteSnapshotGroupRequest { + + /** DeleteSnapshotGroupRequest project */ + project?: (string|null); + + /** DeleteSnapshotGroupRequest requestId */ + requestId?: (string|null); + + /** DeleteSnapshotGroupRequest snapshotGroup */ + snapshotGroup?: (string|null); + } + + /** Represents a DeleteSnapshotGroupRequest. */ + class DeleteSnapshotGroupRequest implements IDeleteSnapshotGroupRequest { + + /** + * Constructs a new DeleteSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest); + + /** DeleteSnapshotGroupRequest project. */ + public project: string; + + /** DeleteSnapshotGroupRequest requestId. */ + public requestId?: (string|null); + + /** DeleteSnapshotGroupRequest snapshotGroup. */ + public snapshotGroup: string; + + /** + * Creates a new DeleteSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns DeleteSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest): google.cloud.compute.v1beta.DeleteSnapshotGroupRequest; + + /** + * Encodes the specified DeleteSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteSnapshotGroupRequest.verify|verify} messages. + * @param message DeleteSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified DeleteSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteSnapshotGroupRequest.verify|verify} messages. + * @param message DeleteSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a DeleteSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns DeleteSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.DeleteSnapshotGroupRequest; + + /** + * Decodes a DeleteSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns DeleteSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.DeleteSnapshotGroupRequest; + + /** + * Verifies a DeleteSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a DeleteSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.DeleteSnapshotGroupRequest; + + /** + * Creates a plain object from a DeleteSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message DeleteSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.DeleteSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a DeleteSnapshotRequest. */ interface IDeleteSnapshotRequest { @@ -288890,6 +290088,9 @@ export namespace google { /** ExternalVpnGateway name */ name?: (string|null); + /** ExternalVpnGateway params */ + params?: (google.cloud.compute.v1beta.IExternalVpnGatewayParams|null); + /** ExternalVpnGateway redundancyType */ redundancyType?: (string|null); @@ -288930,6 +290131,9 @@ export namespace google { /** ExternalVpnGateway name. */ public name?: (string|null); + /** ExternalVpnGateway params. */ + public params?: (google.cloud.compute.v1beta.IExternalVpnGatewayParams|null); + /** ExternalVpnGateway redundancyType. */ public redundancyType?: (string|null); @@ -289267,6 +290471,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an ExternalVpnGatewayParams. */ + interface IExternalVpnGatewayParams { + + /** ExternalVpnGatewayParams resourceManagerTags */ + resourceManagerTags?: ({ [k: string]: string }|null); + } + + /** Represents an ExternalVpnGatewayParams. */ + class ExternalVpnGatewayParams implements IExternalVpnGatewayParams { + + /** + * Constructs a new ExternalVpnGatewayParams. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IExternalVpnGatewayParams); + + /** ExternalVpnGatewayParams resourceManagerTags. */ + public resourceManagerTags: { [k: string]: string }; + + /** + * Creates a new ExternalVpnGatewayParams instance using the specified properties. + * @param [properties] Properties to set + * @returns ExternalVpnGatewayParams instance + */ + public static create(properties?: google.cloud.compute.v1beta.IExternalVpnGatewayParams): google.cloud.compute.v1beta.ExternalVpnGatewayParams; + + /** + * Encodes the specified ExternalVpnGatewayParams message. Does not implicitly {@link google.cloud.compute.v1beta.ExternalVpnGatewayParams.verify|verify} messages. + * @param message ExternalVpnGatewayParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IExternalVpnGatewayParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExternalVpnGatewayParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ExternalVpnGatewayParams.verify|verify} messages. + * @param message ExternalVpnGatewayParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IExternalVpnGatewayParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExternalVpnGatewayParams message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExternalVpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ExternalVpnGatewayParams; + + /** + * Decodes an ExternalVpnGatewayParams message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExternalVpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ExternalVpnGatewayParams; + + /** + * Verifies an ExternalVpnGatewayParams message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ExternalVpnGatewayParams message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExternalVpnGatewayParams + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ExternalVpnGatewayParams; + + /** + * Creates a plain object from an ExternalVpnGatewayParams message. Also converts values to other types if specified. + * @param message ExternalVpnGatewayParams + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ExternalVpnGatewayParams, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExternalVpnGatewayParams to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExternalVpnGatewayParams + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a FileContentBuffer. */ interface IFileContentBuffer { @@ -290362,7 +291663,9 @@ export namespace google { /** PolicyType enum. */ enum PolicyType { UNDEFINED_POLICY_TYPE = 0, + RDMA_FALCON_POLICY = 66315047, RDMA_ROCE_POLICY = 148757145, + ULL_POLICY = 100494364, VPC_POLICY = 74319208 } } @@ -292474,6 +293777,9 @@ export namespace google { /** Properties of a FutureReservation. */ interface IFutureReservation { + /** FutureReservation advancedDeploymentControl */ + advancedDeploymentControl?: (google.cloud.compute.v1beta.IReservationAdvancedDeploymentControl|null); + /** FutureReservation aggregateReservation */ aggregateReservation?: (google.cloud.compute.v1beta.IAllocationAggregateReservation|null); @@ -292562,6 +293868,9 @@ export namespace google { */ constructor(properties?: google.cloud.compute.v1beta.IFutureReservation); + /** FutureReservation advancedDeploymentControl. */ + public advancedDeploymentControl?: (google.cloud.compute.v1beta.IReservationAdvancedDeploymentControl|null); + /** FutureReservation aggregateReservation. */ public aggregateReservation?: (google.cloud.compute.v1beta.IAllocationAggregateReservation|null); @@ -300222,6 +301531,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a GetIamPolicyInstantSnapshotGroupRequest. */ + interface IGetIamPolicyInstantSnapshotGroupRequest { + + /** GetIamPolicyInstantSnapshotGroupRequest optionsRequestedPolicyVersion */ + optionsRequestedPolicyVersion?: (number|null); + + /** GetIamPolicyInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** GetIamPolicyInstantSnapshotGroupRequest resource */ + resource?: (string|null); + + /** GetIamPolicyInstantSnapshotGroupRequest zone */ + zone?: (string|null); + } + + /** Represents a GetIamPolicyInstantSnapshotGroupRequest. */ + class GetIamPolicyInstantSnapshotGroupRequest implements IGetIamPolicyInstantSnapshotGroupRequest { + + /** + * Constructs a new GetIamPolicyInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest); + + /** GetIamPolicyInstantSnapshotGroupRequest optionsRequestedPolicyVersion. */ + public optionsRequestedPolicyVersion?: (number|null); + + /** GetIamPolicyInstantSnapshotGroupRequest project. */ + public project: string; + + /** GetIamPolicyInstantSnapshotGroupRequest resource. */ + public resource: string; + + /** GetIamPolicyInstantSnapshotGroupRequest zone. */ + public zone: string; + + /** + * Creates a new GetIamPolicyInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetIamPolicyInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest): google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest; + + /** + * Encodes the specified GetIamPolicyInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest.verify|verify} messages. + * @param message GetIamPolicyInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetIamPolicyInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest.verify|verify} messages. + * @param message GetIamPolicyInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetIamPolicyInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetIamPolicyInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest; + + /** + * Decodes a GetIamPolicyInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetIamPolicyInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest; + + /** + * Verifies a GetIamPolicyInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetIamPolicyInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIamPolicyInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a GetIamPolicyInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message GetIamPolicyInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIamPolicyInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIamPolicyInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetIamPolicyInstantSnapshotRequest. */ interface IGetIamPolicyInstantSnapshotRequest { @@ -301572,6 +302996,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a GetIamPolicyRegionInstantSnapshotGroupRequest. */ + interface IGetIamPolicyRegionInstantSnapshotGroupRequest { + + /** GetIamPolicyRegionInstantSnapshotGroupRequest optionsRequestedPolicyVersion */ + optionsRequestedPolicyVersion?: (number|null); + + /** GetIamPolicyRegionInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** GetIamPolicyRegionInstantSnapshotGroupRequest region */ + region?: (string|null); + + /** GetIamPolicyRegionInstantSnapshotGroupRequest resource */ + resource?: (string|null); + } + + /** Represents a GetIamPolicyRegionInstantSnapshotGroupRequest. */ + class GetIamPolicyRegionInstantSnapshotGroupRequest implements IGetIamPolicyRegionInstantSnapshotGroupRequest { + + /** + * Constructs a new GetIamPolicyRegionInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest); + + /** GetIamPolicyRegionInstantSnapshotGroupRequest optionsRequestedPolicyVersion. */ + public optionsRequestedPolicyVersion?: (number|null); + + /** GetIamPolicyRegionInstantSnapshotGroupRequest project. */ + public project: string; + + /** GetIamPolicyRegionInstantSnapshotGroupRequest region. */ + public region: string; + + /** GetIamPolicyRegionInstantSnapshotGroupRequest resource. */ + public resource: string; + + /** + * Creates a new GetIamPolicyRegionInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetIamPolicyRegionInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest): google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest; + + /** + * Encodes the specified GetIamPolicyRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message GetIamPolicyRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetIamPolicyRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message GetIamPolicyRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetIamPolicyRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetIamPolicyRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest; + + /** + * Decodes a GetIamPolicyRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetIamPolicyRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest; + + /** + * Verifies a GetIamPolicyRegionInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetIamPolicyRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIamPolicyRegionInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a GetIamPolicyRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message GetIamPolicyRegionInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIamPolicyRegionInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIamPolicyRegionInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetIamPolicyRegionInstantSnapshotRequest. */ interface IGetIamPolicyRegionInstantSnapshotRequest { @@ -302504,6 +304043,115 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a GetIamPolicySnapshotGroupRequest. */ + interface IGetIamPolicySnapshotGroupRequest { + + /** GetIamPolicySnapshotGroupRequest optionsRequestedPolicyVersion */ + optionsRequestedPolicyVersion?: (number|null); + + /** GetIamPolicySnapshotGroupRequest project */ + project?: (string|null); + + /** GetIamPolicySnapshotGroupRequest resource */ + resource?: (string|null); + } + + /** Represents a GetIamPolicySnapshotGroupRequest. */ + class GetIamPolicySnapshotGroupRequest implements IGetIamPolicySnapshotGroupRequest { + + /** + * Constructs a new GetIamPolicySnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest); + + /** GetIamPolicySnapshotGroupRequest optionsRequestedPolicyVersion. */ + public optionsRequestedPolicyVersion?: (number|null); + + /** GetIamPolicySnapshotGroupRequest project. */ + public project: string; + + /** GetIamPolicySnapshotGroupRequest resource. */ + public resource: string; + + /** + * Creates a new GetIamPolicySnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetIamPolicySnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest): google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest; + + /** + * Encodes the specified GetIamPolicySnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest.verify|verify} messages. + * @param message GetIamPolicySnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetIamPolicySnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest.verify|verify} messages. + * @param message GetIamPolicySnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetIamPolicySnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetIamPolicySnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest; + + /** + * Decodes a GetIamPolicySnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetIamPolicySnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest; + + /** + * Verifies a GetIamPolicySnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetIamPolicySnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIamPolicySnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest; + + /** + * Creates a plain object from a GetIamPolicySnapshotGroupRequest message. Also converts values to other types if specified. + * @param message GetIamPolicySnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIamPolicySnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIamPolicySnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetIamPolicySnapshotRequest. */ interface IGetIamPolicySnapshotRequest { @@ -303737,6 +305385,115 @@ export namespace google { } } + /** Properties of a GetInstantSnapshotGroupRequest. */ + interface IGetInstantSnapshotGroupRequest { + + /** GetInstantSnapshotGroupRequest instantSnapshotGroup */ + instantSnapshotGroup?: (string|null); + + /** GetInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** GetInstantSnapshotGroupRequest zone */ + zone?: (string|null); + } + + /** Represents a GetInstantSnapshotGroupRequest. */ + class GetInstantSnapshotGroupRequest implements IGetInstantSnapshotGroupRequest { + + /** + * Constructs a new GetInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest); + + /** GetInstantSnapshotGroupRequest instantSnapshotGroup. */ + public instantSnapshotGroup: string; + + /** GetInstantSnapshotGroupRequest project. */ + public project: string; + + /** GetInstantSnapshotGroupRequest zone. */ + public zone: string; + + /** + * Creates a new GetInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest): google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest; + + /** + * Encodes the specified GetInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest.verify|verify} messages. + * @param message GetInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest.verify|verify} messages. + * @param message GetInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest; + + /** + * Decodes a GetInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest; + + /** + * Verifies a GetInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a GetInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message GetInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetInstantSnapshotRequest. */ interface IGetInstantSnapshotRequest { @@ -304991,6 +306748,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a GetNamedSetRouterRequest. */ + interface IGetNamedSetRouterRequest { + + /** GetNamedSetRouterRequest namedSet */ + namedSet?: (string|null); + + /** GetNamedSetRouterRequest project */ + project?: (string|null); + + /** GetNamedSetRouterRequest region */ + region?: (string|null); + + /** GetNamedSetRouterRequest router */ + router?: (string|null); + } + + /** Represents a GetNamedSetRouterRequest. */ + class GetNamedSetRouterRequest implements IGetNamedSetRouterRequest { + + /** + * Constructs a new GetNamedSetRouterRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IGetNamedSetRouterRequest); + + /** GetNamedSetRouterRequest namedSet. */ + public namedSet?: (string|null); + + /** GetNamedSetRouterRequest project. */ + public project: string; + + /** GetNamedSetRouterRequest region. */ + public region: string; + + /** GetNamedSetRouterRequest router. */ + public router: string; + + /** + * Creates a new GetNamedSetRouterRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetNamedSetRouterRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IGetNamedSetRouterRequest): google.cloud.compute.v1beta.GetNamedSetRouterRequest; + + /** + * Encodes the specified GetNamedSetRouterRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetNamedSetRouterRequest.verify|verify} messages. + * @param message GetNamedSetRouterRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IGetNamedSetRouterRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetNamedSetRouterRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetNamedSetRouterRequest.verify|verify} messages. + * @param message GetNamedSetRouterRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IGetNamedSetRouterRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetNamedSetRouterRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.GetNamedSetRouterRequest; + + /** + * Decodes a GetNamedSetRouterRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.GetNamedSetRouterRequest; + + /** + * Verifies a GetNamedSetRouterRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetNamedSetRouterRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetNamedSetRouterRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.GetNamedSetRouterRequest; + + /** + * Creates a plain object from a GetNamedSetRouterRequest message. Also converts values to other types if specified. + * @param message GetNamedSetRouterRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.GetNamedSetRouterRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetNamedSetRouterRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetNamedSetRouterRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetNatIpInfoRouterRequest. */ interface IGetNatIpInfoRouterRequest { @@ -309126,6 +310998,115 @@ export namespace google { } } + /** Properties of a GetRegionInstantSnapshotGroupRequest. */ + interface IGetRegionInstantSnapshotGroupRequest { + + /** GetRegionInstantSnapshotGroupRequest instantSnapshotGroup */ + instantSnapshotGroup?: (string|null); + + /** GetRegionInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** GetRegionInstantSnapshotGroupRequest region */ + region?: (string|null); + } + + /** Represents a GetRegionInstantSnapshotGroupRequest. */ + class GetRegionInstantSnapshotGroupRequest implements IGetRegionInstantSnapshotGroupRequest { + + /** + * Constructs a new GetRegionInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest); + + /** GetRegionInstantSnapshotGroupRequest instantSnapshotGroup. */ + public instantSnapshotGroup: string; + + /** GetRegionInstantSnapshotGroupRequest project. */ + public project: string; + + /** GetRegionInstantSnapshotGroupRequest region. */ + public region: string; + + /** + * Creates a new GetRegionInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetRegionInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest): google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest; + + /** + * Encodes the specified GetRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message GetRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message GetRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest; + + /** + * Decodes a GetRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest; + + /** + * Verifies a GetRegionInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetRegionInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a GetRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message GetRegionInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetRegionInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetRegionInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetRegionInstantSnapshotRequest. */ interface IGetRegionInstantSnapshotRequest { @@ -311323,6 +313304,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a GetReservationSlotRequest. */ + interface IGetReservationSlotRequest { + + /** GetReservationSlotRequest parentName */ + parentName?: (string|null); + + /** GetReservationSlotRequest project */ + project?: (string|null); + + /** GetReservationSlotRequest reservationSlot */ + reservationSlot?: (string|null); + + /** GetReservationSlotRequest zone */ + zone?: (string|null); + } + + /** Represents a GetReservationSlotRequest. */ + class GetReservationSlotRequest implements IGetReservationSlotRequest { + + /** + * Constructs a new GetReservationSlotRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IGetReservationSlotRequest); + + /** GetReservationSlotRequest parentName. */ + public parentName: string; + + /** GetReservationSlotRequest project. */ + public project: string; + + /** GetReservationSlotRequest reservationSlot. */ + public reservationSlot: string; + + /** GetReservationSlotRequest zone. */ + public zone: string; + + /** + * Creates a new GetReservationSlotRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetReservationSlotRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IGetReservationSlotRequest): google.cloud.compute.v1beta.GetReservationSlotRequest; + + /** + * Encodes the specified GetReservationSlotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetReservationSlotRequest.verify|verify} messages. + * @param message GetReservationSlotRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IGetReservationSlotRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetReservationSlotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetReservationSlotRequest.verify|verify} messages. + * @param message GetReservationSlotRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IGetReservationSlotRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetReservationSlotRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetReservationSlotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.GetReservationSlotRequest; + + /** + * Decodes a GetReservationSlotRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetReservationSlotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.GetReservationSlotRequest; + + /** + * Verifies a GetReservationSlotRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetReservationSlotRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetReservationSlotRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.GetReservationSlotRequest; + + /** + * Creates a plain object from a GetReservationSlotRequest message. Also converts values to other types if specified. + * @param message GetReservationSlotRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.GetReservationSlotRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetReservationSlotRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetReservationSlotRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetReservationSubBlockRequest. */ interface IGetReservationSubBlockRequest { @@ -313526,6 +315622,109 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a GetSnapshotGroupRequest. */ + interface IGetSnapshotGroupRequest { + + /** GetSnapshotGroupRequest project */ + project?: (string|null); + + /** GetSnapshotGroupRequest snapshotGroup */ + snapshotGroup?: (string|null); + } + + /** Represents a GetSnapshotGroupRequest. */ + class GetSnapshotGroupRequest implements IGetSnapshotGroupRequest { + + /** + * Constructs a new GetSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IGetSnapshotGroupRequest); + + /** GetSnapshotGroupRequest project. */ + public project: string; + + /** GetSnapshotGroupRequest snapshotGroup. */ + public snapshotGroup: string; + + /** + * Creates a new GetSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IGetSnapshotGroupRequest): google.cloud.compute.v1beta.GetSnapshotGroupRequest; + + /** + * Encodes the specified GetSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetSnapshotGroupRequest.verify|verify} messages. + * @param message GetSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IGetSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetSnapshotGroupRequest.verify|verify} messages. + * @param message GetSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IGetSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.GetSnapshotGroupRequest; + + /** + * Decodes a GetSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.GetSnapshotGroupRequest; + + /** + * Verifies a GetSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.GetSnapshotGroupRequest; + + /** + * Creates a plain object from a GetSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message GetSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.GetSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetSnapshotRequest. */ interface IGetSnapshotRequest { @@ -323112,6 +325311,9 @@ export namespace google { /** Properties of a HttpRouteAction. */ interface IHttpRouteAction { + /** HttpRouteAction cachePolicy */ + cachePolicy?: (google.cloud.compute.v1beta.ICachePolicy|null); + /** HttpRouteAction corsPolicy */ corsPolicy?: (google.cloud.compute.v1beta.ICorsPolicy|null); @@ -323146,6 +325348,9 @@ export namespace google { */ constructor(properties?: google.cloud.compute.v1beta.IHttpRouteAction); + /** HttpRouteAction cachePolicy. */ + public cachePolicy?: (google.cloud.compute.v1beta.ICachePolicy|null); + /** HttpRouteAction corsPolicy. */ public corsPolicy?: (google.cloud.compute.v1beta.ICorsPolicy|null); @@ -326916,6 +329121,127 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an InsertInstantSnapshotGroupRequest. */ + interface IInsertInstantSnapshotGroupRequest { + + /** InsertInstantSnapshotGroupRequest instantSnapshotGroupResource */ + instantSnapshotGroupResource?: (google.cloud.compute.v1beta.IInstantSnapshotGroup|null); + + /** InsertInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** InsertInstantSnapshotGroupRequest requestId */ + requestId?: (string|null); + + /** InsertInstantSnapshotGroupRequest sourceConsistencyGroup */ + sourceConsistencyGroup?: (string|null); + + /** InsertInstantSnapshotGroupRequest zone */ + zone?: (string|null); + } + + /** Represents an InsertInstantSnapshotGroupRequest. */ + class InsertInstantSnapshotGroupRequest implements IInsertInstantSnapshotGroupRequest { + + /** + * Constructs a new InsertInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest); + + /** InsertInstantSnapshotGroupRequest instantSnapshotGroupResource. */ + public instantSnapshotGroupResource?: (google.cloud.compute.v1beta.IInstantSnapshotGroup|null); + + /** InsertInstantSnapshotGroupRequest project. */ + public project: string; + + /** InsertInstantSnapshotGroupRequest requestId. */ + public requestId?: (string|null); + + /** InsertInstantSnapshotGroupRequest sourceConsistencyGroup. */ + public sourceConsistencyGroup?: (string|null); + + /** InsertInstantSnapshotGroupRequest zone. */ + public zone: string; + + /** + * Creates a new InsertInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns InsertInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest): google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest; + + /** + * Encodes the specified InsertInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest.verify|verify} messages. + * @param message InsertInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InsertInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest.verify|verify} messages. + * @param message InsertInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InsertInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InsertInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest; + + /** + * Decodes an InsertInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InsertInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest; + + /** + * Verifies an InsertInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InsertInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InsertInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest; + + /** + * Creates a plain object from an InsertInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message InsertInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InsertInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InsertInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an InsertInstantSnapshotRequest. */ interface IInsertInstantSnapshotRequest { @@ -330463,6 +332789,127 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an InsertRegionInstantSnapshotGroupRequest. */ + interface IInsertRegionInstantSnapshotGroupRequest { + + /** InsertRegionInstantSnapshotGroupRequest instantSnapshotGroupResource */ + instantSnapshotGroupResource?: (google.cloud.compute.v1beta.IInstantSnapshotGroup|null); + + /** InsertRegionInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** InsertRegionInstantSnapshotGroupRequest region */ + region?: (string|null); + + /** InsertRegionInstantSnapshotGroupRequest requestId */ + requestId?: (string|null); + + /** InsertRegionInstantSnapshotGroupRequest sourceConsistencyGroup */ + sourceConsistencyGroup?: (string|null); + } + + /** Represents an InsertRegionInstantSnapshotGroupRequest. */ + class InsertRegionInstantSnapshotGroupRequest implements IInsertRegionInstantSnapshotGroupRequest { + + /** + * Constructs a new InsertRegionInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest); + + /** InsertRegionInstantSnapshotGroupRequest instantSnapshotGroupResource. */ + public instantSnapshotGroupResource?: (google.cloud.compute.v1beta.IInstantSnapshotGroup|null); + + /** InsertRegionInstantSnapshotGroupRequest project. */ + public project: string; + + /** InsertRegionInstantSnapshotGroupRequest region. */ + public region: string; + + /** InsertRegionInstantSnapshotGroupRequest requestId. */ + public requestId?: (string|null); + + /** InsertRegionInstantSnapshotGroupRequest sourceConsistencyGroup. */ + public sourceConsistencyGroup?: (string|null); + + /** + * Creates a new InsertRegionInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns InsertRegionInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest): google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest; + + /** + * Encodes the specified InsertRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message InsertRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InsertRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message InsertRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InsertRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InsertRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest; + + /** + * Decodes an InsertRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InsertRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest; + + /** + * Verifies an InsertRegionInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InsertRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InsertRegionInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest; + + /** + * Creates a plain object from an InsertRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message InsertRegionInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InsertRegionInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InsertRegionInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an InsertRegionInstantSnapshotRequest. */ interface IInsertRegionInstantSnapshotRequest { @@ -332872,6 +335319,115 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an InsertSnapshotGroupRequest. */ + interface IInsertSnapshotGroupRequest { + + /** InsertSnapshotGroupRequest project */ + project?: (string|null); + + /** InsertSnapshotGroupRequest requestId */ + requestId?: (string|null); + + /** InsertSnapshotGroupRequest snapshotGroupResource */ + snapshotGroupResource?: (google.cloud.compute.v1beta.ISnapshotGroup|null); + } + + /** Represents an InsertSnapshotGroupRequest. */ + class InsertSnapshotGroupRequest implements IInsertSnapshotGroupRequest { + + /** + * Constructs a new InsertSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInsertSnapshotGroupRequest); + + /** InsertSnapshotGroupRequest project. */ + public project: string; + + /** InsertSnapshotGroupRequest requestId. */ + public requestId?: (string|null); + + /** InsertSnapshotGroupRequest snapshotGroupResource. */ + public snapshotGroupResource?: (google.cloud.compute.v1beta.ISnapshotGroup|null); + + /** + * Creates a new InsertSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns InsertSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInsertSnapshotGroupRequest): google.cloud.compute.v1beta.InsertSnapshotGroupRequest; + + /** + * Encodes the specified InsertSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertSnapshotGroupRequest.verify|verify} messages. + * @param message InsertSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInsertSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InsertSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertSnapshotGroupRequest.verify|verify} messages. + * @param message InsertSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInsertSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InsertSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InsertSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InsertSnapshotGroupRequest; + + /** + * Decodes an InsertSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InsertSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InsertSnapshotGroupRequest; + + /** + * Verifies an InsertSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InsertSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InsertSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InsertSnapshotGroupRequest; + + /** + * Creates a plain object from an InsertSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message InsertSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InsertSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InsertSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InsertSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an InsertSnapshotRequest. */ interface IInsertSnapshotRequest { @@ -335047,6 +337603,9 @@ export namespace google { /** Instance tags */ tags?: (google.cloud.compute.v1beta.ITags|null); + /** Instance workloadIdentityConfig */ + workloadIdentityConfig?: (google.cloud.compute.v1beta.IWorkloadIdentityConfig|null); + /** Instance zone */ zone?: (string|null); } @@ -335210,6 +337769,9 @@ export namespace google { /** Instance tags. */ public tags?: (google.cloud.compute.v1beta.ITags|null); + /** Instance workloadIdentityConfig. */ + public workloadIdentityConfig?: (google.cloud.compute.v1beta.IWorkloadIdentityConfig|null); + /** Instance zone. */ public zone?: (string|null); @@ -338695,6 +341257,9 @@ export namespace google { /** InstanceGroupManagerStatus bulkInstanceOperation */ bulkInstanceOperation?: (google.cloud.compute.v1beta.IInstanceGroupManagerStatusBulkInstanceOperation|null); + /** InstanceGroupManagerStatus currentInstanceStatuses */ + currentInstanceStatuses?: (google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary|null); + /** InstanceGroupManagerStatus isStable */ isStable?: (boolean|null); @@ -338723,6 +341288,9 @@ export namespace google { /** InstanceGroupManagerStatus bulkInstanceOperation. */ public bulkInstanceOperation?: (google.cloud.compute.v1beta.IInstanceGroupManagerStatusBulkInstanceOperation|null); + /** InstanceGroupManagerStatus currentInstanceStatuses. */ + public currentInstanceStatuses?: (google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary|null); + /** InstanceGroupManagerStatus isStable. */ public isStable?: (boolean|null); @@ -339119,6 +341687,175 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an InstanceGroupManagerStatusInstanceStatusSummary. */ + interface IInstanceGroupManagerStatusInstanceStatusSummary { + + /** InstanceGroupManagerStatusInstanceStatusSummary deprovisioning */ + deprovisioning?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary nonExistent */ + nonExistent?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary pending */ + pending?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary pendingStop */ + pendingStop?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary provisioning */ + provisioning?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary repairing */ + repairing?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary running */ + running?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary staging */ + staging?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary stopped */ + stopped?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary stopping */ + stopping?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary suspended */ + suspended?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary suspending */ + suspending?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary terminated */ + terminated?: (number|null); + } + + /** Represents an InstanceGroupManagerStatusInstanceStatusSummary. */ + class InstanceGroupManagerStatusInstanceStatusSummary implements IInstanceGroupManagerStatusInstanceStatusSummary { + + /** + * Constructs a new InstanceGroupManagerStatusInstanceStatusSummary. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary); + + /** InstanceGroupManagerStatusInstanceStatusSummary deprovisioning. */ + public deprovisioning?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary nonExistent. */ + public nonExistent?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary pending. */ + public pending?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary pendingStop. */ + public pendingStop?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary provisioning. */ + public provisioning?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary repairing. */ + public repairing?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary running. */ + public running?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary staging. */ + public staging?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary stopped. */ + public stopped?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary stopping. */ + public stopping?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary suspended. */ + public suspended?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary suspending. */ + public suspending?: (number|null); + + /** InstanceGroupManagerStatusInstanceStatusSummary terminated. */ + public terminated?: (number|null); + + /** + * Creates a new InstanceGroupManagerStatusInstanceStatusSummary instance using the specified properties. + * @param [properties] Properties to set + * @returns InstanceGroupManagerStatusInstanceStatusSummary instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary): google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary; + + /** + * Encodes the specified InstanceGroupManagerStatusInstanceStatusSummary message. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.verify|verify} messages. + * @param message InstanceGroupManagerStatusInstanceStatusSummary message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstanceGroupManagerStatusInstanceStatusSummary message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.verify|verify} messages. + * @param message InstanceGroupManagerStatusInstanceStatusSummary message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstanceGroupManagerStatusInstanceStatusSummary message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstanceGroupManagerStatusInstanceStatusSummary + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary; + + /** + * Decodes an InstanceGroupManagerStatusInstanceStatusSummary message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstanceGroupManagerStatusInstanceStatusSummary + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary; + + /** + * Verifies an InstanceGroupManagerStatusInstanceStatusSummary message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstanceGroupManagerStatusInstanceStatusSummary message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstanceGroupManagerStatusInstanceStatusSummary + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary; + + /** + * Creates a plain object from an InstanceGroupManagerStatusInstanceStatusSummary message. Also converts values to other types if specified. + * @param message InstanceGroupManagerStatusInstanceStatusSummary + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstanceGroupManagerStatusInstanceStatusSummary to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstanceGroupManagerStatusInstanceStatusSummary + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an InstanceGroupManagerStatusStateful. */ interface IInstanceGroupManagerStatusStateful { @@ -340034,6 +342771,103 @@ export namespace google { } } + /** Properties of an InstanceGroupManagersConfigureAcceleratorTopologiesRequest. */ + interface IInstanceGroupManagersConfigureAcceleratorTopologiesRequest { + + /** InstanceGroupManagersConfigureAcceleratorTopologiesRequest acceleratorTopologyActions */ + acceleratorTopologyActions?: ({ [k: string]: string }|null); + } + + /** Represents an InstanceGroupManagersConfigureAcceleratorTopologiesRequest. */ + class InstanceGroupManagersConfigureAcceleratorTopologiesRequest implements IInstanceGroupManagersConfigureAcceleratorTopologiesRequest { + + /** + * Constructs a new InstanceGroupManagersConfigureAcceleratorTopologiesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest); + + /** InstanceGroupManagersConfigureAcceleratorTopologiesRequest acceleratorTopologyActions. */ + public acceleratorTopologyActions: { [k: string]: string }; + + /** + * Creates a new InstanceGroupManagersConfigureAcceleratorTopologiesRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns InstanceGroupManagersConfigureAcceleratorTopologiesRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest): google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest; + + /** + * Encodes the specified InstanceGroupManagersConfigureAcceleratorTopologiesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.verify|verify} messages. + * @param message InstanceGroupManagersConfigureAcceleratorTopologiesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstanceGroupManagersConfigureAcceleratorTopologiesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.verify|verify} messages. + * @param message InstanceGroupManagersConfigureAcceleratorTopologiesRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest; + + /** + * Decodes an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest; + + /** + * Verifies an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstanceGroupManagersConfigureAcceleratorTopologiesRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest; + + /** + * Creates a plain object from an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message. Also converts values to other types if specified. + * @param message InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstanceGroupManagersConfigureAcceleratorTopologiesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an InstanceGroupManagersCreateInstancesRequest. */ interface IInstanceGroupManagersCreateInstancesRequest { @@ -340336,6 +343170,9 @@ export namespace google { /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse acceleratorTopologiesInfo */ acceleratorTopologiesInfo?: ({ [k: string]: google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo }|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse multiMig */ + multiMig?: (string|null); } /** Represents an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse. */ @@ -340350,6 +343187,9 @@ export namespace google { /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse acceleratorTopologiesInfo. */ public acceleratorTopologiesInfo: { [k: string]: google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo }; + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse multiMig. */ + public multiMig?: (string|null); + /** * Creates a new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse instance using the specified properties. * @param [properties] Properties to set @@ -340436,6 +343276,15 @@ export namespace google { /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo acceleratorTopologyHealth */ acceleratorTopologyHealth?: (string|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo acceleratorTopologyState */ + acceleratorTopologyState?: (google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo instancesHealth */ + instancesHealth?: (string|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo parent */ + parent?: (string|null); } /** Represents an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo. */ @@ -340453,6 +343302,15 @@ export namespace google { /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo acceleratorTopologyHealth. */ public acceleratorTopologyHealth?: (string|null); + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo acceleratorTopologyState. */ + public acceleratorTopologyState?: (google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo instancesHealth. */ + public instancesHealth?: (string|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo parent. */ + public parent?: (string|null); + /** * Creates a new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo instance using the specified properties. * @param [properties] Properties to set @@ -340538,7 +343396,139 @@ export namespace google { UNDEFINED_ACCELERATOR_TOPOLOGY_HEALTH = 0, DEGRADED = 396890926, HEALTHY = 439801213, - UNHEALTHY = 462118084 + UNHEALTHY = 462118084, + UNKNOWN = 433141802 + } + + /** InstancesHealth enum. */ + enum InstancesHealth { + UNDEFINED_INSTANCES_HEALTH = 0, + ALL_HEALTHY = 519465151, + UNHEALTHY_OR_MISSING = 59982149 + } + } + + /** Properties of an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState. */ + interface IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState { + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState currentState */ + currentState?: (string|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState error */ + error?: (google.cloud.compute.v1beta.IError|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState errorTimestamp */ + errorTimestamp?: (string|null); + } + + /** Represents an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState. */ + class InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState implements IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState { + + /** + * Constructs a new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState currentState. */ + public currentState?: (string|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState error. */ + public error?: (google.cloud.compute.v1beta.IError|null); + + /** InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState errorTimestamp. */ + public errorTimestamp?: (string|null); + + /** + * Creates a new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState instance using the specified properties. + * @param [properties] Properties to set + * @returns InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState): google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState; + + /** + * Encodes the specified InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.verify|verify} messages. + * @param message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.verify|verify} messages. + * @param message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState; + + /** + * Decodes an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState; + + /** + * Verifies an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState; + + /** + * Creates a plain object from an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message. Also converts values to other types if specified. + * @param message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState { + + /** CurrentState enum. */ + enum CurrentState { + UNDEFINED_CURRENT_STATE = 0, + ACTIVATING = 378825968, + ACTIVE = 314733318, + ACTIVE_DEGRADED = 471128135, + DEACTIVATING = 57182257, + FAILED = 455706685, + INACTIVE = 270421099, + INCOMPLETE = 11941214 } } @@ -343565,6 +346555,9 @@ export namespace google { /** InstanceProperties tags */ tags?: (google.cloud.compute.v1beta.ITags|null); + + /** InstanceProperties workloadIdentityConfig */ + workloadIdentityConfig?: (google.cloud.compute.v1beta.IWorkloadIdentityConfig|null); } /** Represents an InstanceProperties. */ @@ -343651,6 +346644,9 @@ export namespace google { /** InstanceProperties tags. */ public tags?: (google.cloud.compute.v1beta.ITags|null); + /** InstanceProperties workloadIdentityConfig. */ + public workloadIdentityConfig?: (google.cloud.compute.v1beta.IWorkloadIdentityConfig|null); + /** * Creates a new InstanceProperties instance using the specified properties. * @param [properties] Properties to set @@ -345684,6 +348680,7 @@ export namespace google { enum Behavior { UNDEFINED_BEHAVIOR = 0, BEHAVIOR_UNSPECIFIED = 85734570, + CHIP_ERROR = 263151669, PERFORMANCE = 135701520, SILENT_DATA_CORRUPTION = 111360678, UNRECOVERABLE_GPU_ERROR = 363710747 @@ -346726,6 +349723,9 @@ export namespace google { /** InstantSnapshot name */ name?: (string|null); + /** InstantSnapshot params */ + params?: (google.cloud.compute.v1beta.IInstantSnapshotParams|null); + /** InstantSnapshot region */ region?: (string|null); @@ -346750,6 +349750,12 @@ export namespace google { /** InstantSnapshot sourceDiskId */ sourceDiskId?: (string|null); + /** InstantSnapshot sourceInstantSnapshotGroup */ + sourceInstantSnapshotGroup?: (string|null); + + /** InstantSnapshot sourceInstantSnapshotGroupId */ + sourceInstantSnapshotGroupId?: (string|null); + /** InstantSnapshot status */ status?: (string|null); @@ -346793,6 +349799,9 @@ export namespace google { /** InstantSnapshot name. */ public name?: (string|null); + /** InstantSnapshot params. */ + public params?: (google.cloud.compute.v1beta.IInstantSnapshotParams|null); + /** InstantSnapshot region. */ public region?: (string|null); @@ -346817,6 +349826,12 @@ export namespace google { /** InstantSnapshot sourceDiskId. */ public sourceDiskId?: (string|null); + /** InstantSnapshot sourceInstantSnapshotGroup. */ + public sourceInstantSnapshotGroup?: (string|null); + + /** InstantSnapshot sourceInstantSnapshotGroupId. */ + public sourceInstantSnapshotGroupId?: (string|null); + /** InstantSnapshot status. */ public status?: (string|null); @@ -347055,6 +350070,486 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an InstantSnapshotGroup. */ + interface IInstantSnapshotGroup { + + /** InstantSnapshotGroup creationTimestamp */ + creationTimestamp?: (string|null); + + /** InstantSnapshotGroup description */ + description?: (string|null); + + /** InstantSnapshotGroup id */ + id?: (number|Long|string|null); + + /** InstantSnapshotGroup kind */ + kind?: (string|null); + + /** InstantSnapshotGroup name */ + name?: (string|null); + + /** InstantSnapshotGroup region */ + region?: (string|null); + + /** InstantSnapshotGroup resourceStatus */ + resourceStatus?: (google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus|null); + + /** InstantSnapshotGroup selfLink */ + selfLink?: (string|null); + + /** InstantSnapshotGroup selfLinkWithId */ + selfLinkWithId?: (string|null); + + /** InstantSnapshotGroup sourceConsistencyGroup */ + sourceConsistencyGroup?: (string|null); + + /** InstantSnapshotGroup status */ + status?: (string|null); + + /** InstantSnapshotGroup zone */ + zone?: (string|null); + } + + /** Represents an InstantSnapshotGroup. */ + class InstantSnapshotGroup implements IInstantSnapshotGroup { + + /** + * Constructs a new InstantSnapshotGroup. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInstantSnapshotGroup); + + /** InstantSnapshotGroup creationTimestamp. */ + public creationTimestamp?: (string|null); + + /** InstantSnapshotGroup description. */ + public description?: (string|null); + + /** InstantSnapshotGroup id. */ + public id?: (number|Long|string|null); + + /** InstantSnapshotGroup kind. */ + public kind?: (string|null); + + /** InstantSnapshotGroup name. */ + public name?: (string|null); + + /** InstantSnapshotGroup region. */ + public region?: (string|null); + + /** InstantSnapshotGroup resourceStatus. */ + public resourceStatus?: (google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus|null); + + /** InstantSnapshotGroup selfLink. */ + public selfLink?: (string|null); + + /** InstantSnapshotGroup selfLinkWithId. */ + public selfLinkWithId?: (string|null); + + /** InstantSnapshotGroup sourceConsistencyGroup. */ + public sourceConsistencyGroup?: (string|null); + + /** InstantSnapshotGroup status. */ + public status?: (string|null); + + /** InstantSnapshotGroup zone. */ + public zone?: (string|null); + + /** + * Creates a new InstantSnapshotGroup instance using the specified properties. + * @param [properties] Properties to set + * @returns InstantSnapshotGroup instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInstantSnapshotGroup): google.cloud.compute.v1beta.InstantSnapshotGroup; + + /** + * Encodes the specified InstantSnapshotGroup message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroup.verify|verify} messages. + * @param message InstantSnapshotGroup message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInstantSnapshotGroup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstantSnapshotGroup message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroup.verify|verify} messages. + * @param message InstantSnapshotGroup message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInstantSnapshotGroup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstantSnapshotGroup message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstantSnapshotGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InstantSnapshotGroup; + + /** + * Decodes an InstantSnapshotGroup message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstantSnapshotGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InstantSnapshotGroup; + + /** + * Verifies an InstantSnapshotGroup message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstantSnapshotGroup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstantSnapshotGroup + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InstantSnapshotGroup; + + /** + * Creates a plain object from an InstantSnapshotGroup message. Also converts values to other types if specified. + * @param message InstantSnapshotGroup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InstantSnapshotGroup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstantSnapshotGroup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstantSnapshotGroup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace InstantSnapshotGroup { + + /** Status enum. */ + enum Status { + UNDEFINED_STATUS = 0, + CREATING = 455564985, + DELETING = 528602024, + FAILED = 455706685, + INVALID = 530283991, + READY = 77848963, + UNKNOWN = 433141802 + } + } + + /** Properties of an InstantSnapshotGroupParameters. */ + interface IInstantSnapshotGroupParameters { + + /** InstantSnapshotGroupParameters sourceInstantSnapshotGroup */ + sourceInstantSnapshotGroup?: (string|null); + } + + /** Represents an InstantSnapshotGroupParameters. */ + class InstantSnapshotGroupParameters implements IInstantSnapshotGroupParameters { + + /** + * Constructs a new InstantSnapshotGroupParameters. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInstantSnapshotGroupParameters); + + /** InstantSnapshotGroupParameters sourceInstantSnapshotGroup. */ + public sourceInstantSnapshotGroup?: (string|null); + + /** + * Creates a new InstantSnapshotGroupParameters instance using the specified properties. + * @param [properties] Properties to set + * @returns InstantSnapshotGroupParameters instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInstantSnapshotGroupParameters): google.cloud.compute.v1beta.InstantSnapshotGroupParameters; + + /** + * Encodes the specified InstantSnapshotGroupParameters message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupParameters.verify|verify} messages. + * @param message InstantSnapshotGroupParameters message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInstantSnapshotGroupParameters, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstantSnapshotGroupParameters message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupParameters.verify|verify} messages. + * @param message InstantSnapshotGroupParameters message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInstantSnapshotGroupParameters, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstantSnapshotGroupParameters message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstantSnapshotGroupParameters + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InstantSnapshotGroupParameters; + + /** + * Decodes an InstantSnapshotGroupParameters message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstantSnapshotGroupParameters + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InstantSnapshotGroupParameters; + + /** + * Verifies an InstantSnapshotGroupParameters message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstantSnapshotGroupParameters message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstantSnapshotGroupParameters + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InstantSnapshotGroupParameters; + + /** + * Creates a plain object from an InstantSnapshotGroupParameters message. Also converts values to other types if specified. + * @param message InstantSnapshotGroupParameters + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InstantSnapshotGroupParameters, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstantSnapshotGroupParameters to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstantSnapshotGroupParameters + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an InstantSnapshotGroupResourceStatus. */ + interface IInstantSnapshotGroupResourceStatus { + + /** InstantSnapshotGroupResourceStatus consistencyMembershipResolutionTime */ + consistencyMembershipResolutionTime?: (string|null); + + /** InstantSnapshotGroupResourceStatus sourceInfo */ + sourceInfo?: (google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo|null); + } + + /** Represents an InstantSnapshotGroupResourceStatus. */ + class InstantSnapshotGroupResourceStatus implements IInstantSnapshotGroupResourceStatus { + + /** + * Constructs a new InstantSnapshotGroupResourceStatus. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus); + + /** InstantSnapshotGroupResourceStatus consistencyMembershipResolutionTime. */ + public consistencyMembershipResolutionTime?: (string|null); + + /** InstantSnapshotGroupResourceStatus sourceInfo. */ + public sourceInfo?: (google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo|null); + + /** + * Creates a new InstantSnapshotGroupResourceStatus instance using the specified properties. + * @param [properties] Properties to set + * @returns InstantSnapshotGroupResourceStatus instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus): google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus; + + /** + * Encodes the specified InstantSnapshotGroupResourceStatus message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.verify|verify} messages. + * @param message InstantSnapshotGroupResourceStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstantSnapshotGroupResourceStatus message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.verify|verify} messages. + * @param message InstantSnapshotGroupResourceStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstantSnapshotGroupResourceStatus message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstantSnapshotGroupResourceStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus; + + /** + * Decodes an InstantSnapshotGroupResourceStatus message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstantSnapshotGroupResourceStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus; + + /** + * Verifies an InstantSnapshotGroupResourceStatus message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstantSnapshotGroupResourceStatus message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstantSnapshotGroupResourceStatus + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus; + + /** + * Creates a plain object from an InstantSnapshotGroupResourceStatus message. Also converts values to other types if specified. + * @param message InstantSnapshotGroupResourceStatus + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstantSnapshotGroupResourceStatus to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstantSnapshotGroupResourceStatus + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an InstantSnapshotGroupSourceInfo. */ + interface IInstantSnapshotGroupSourceInfo { + + /** InstantSnapshotGroupSourceInfo consistencyGroup */ + consistencyGroup?: (string|null); + + /** InstantSnapshotGroupSourceInfo consistencyGroupId */ + consistencyGroupId?: (string|null); + } + + /** Represents an InstantSnapshotGroupSourceInfo. */ + class InstantSnapshotGroupSourceInfo implements IInstantSnapshotGroupSourceInfo { + + /** + * Constructs a new InstantSnapshotGroupSourceInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo); + + /** InstantSnapshotGroupSourceInfo consistencyGroup. */ + public consistencyGroup?: (string|null); + + /** InstantSnapshotGroupSourceInfo consistencyGroupId. */ + public consistencyGroupId?: (string|null); + + /** + * Creates a new InstantSnapshotGroupSourceInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns InstantSnapshotGroupSourceInfo instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo): google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo; + + /** + * Encodes the specified InstantSnapshotGroupSourceInfo message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.verify|verify} messages. + * @param message InstantSnapshotGroupSourceInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstantSnapshotGroupSourceInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.verify|verify} messages. + * @param message InstantSnapshotGroupSourceInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstantSnapshotGroupSourceInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstantSnapshotGroupSourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo; + + /** + * Decodes an InstantSnapshotGroupSourceInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstantSnapshotGroupSourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo; + + /** + * Verifies an InstantSnapshotGroupSourceInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstantSnapshotGroupSourceInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstantSnapshotGroupSourceInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo; + + /** + * Creates a plain object from an InstantSnapshotGroupSourceInfo message. Also converts values to other types if specified. + * @param message InstantSnapshotGroupSourceInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstantSnapshotGroupSourceInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstantSnapshotGroupSourceInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an InstantSnapshotList. */ interface IInstantSnapshotList { @@ -347182,6 +350677,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an InstantSnapshotParams. */ + interface IInstantSnapshotParams { + + /** InstantSnapshotParams resourceManagerTags */ + resourceManagerTags?: ({ [k: string]: string }|null); + } + + /** Represents an InstantSnapshotParams. */ + class InstantSnapshotParams implements IInstantSnapshotParams { + + /** + * Constructs a new InstantSnapshotParams. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IInstantSnapshotParams); + + /** InstantSnapshotParams resourceManagerTags. */ + public resourceManagerTags: { [k: string]: string }; + + /** + * Creates a new InstantSnapshotParams instance using the specified properties. + * @param [properties] Properties to set + * @returns InstantSnapshotParams instance + */ + public static create(properties?: google.cloud.compute.v1beta.IInstantSnapshotParams): google.cloud.compute.v1beta.InstantSnapshotParams; + + /** + * Encodes the specified InstantSnapshotParams message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotParams.verify|verify} messages. + * @param message InstantSnapshotParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IInstantSnapshotParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified InstantSnapshotParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotParams.verify|verify} messages. + * @param message InstantSnapshotParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IInstantSnapshotParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an InstantSnapshotParams message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns InstantSnapshotParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.InstantSnapshotParams; + + /** + * Decodes an InstantSnapshotParams message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns InstantSnapshotParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.InstantSnapshotParams; + + /** + * Verifies an InstantSnapshotParams message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an InstantSnapshotParams message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns InstantSnapshotParams + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.InstantSnapshotParams; + + /** + * Creates a plain object from an InstantSnapshotParams message. Also converts values to other types if specified. + * @param message InstantSnapshotParams + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.InstantSnapshotParams, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this InstantSnapshotParams to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for InstantSnapshotParams + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an InstantSnapshotResourceStatus. */ interface IInstantSnapshotResourceStatus { @@ -363105,6 +366697,278 @@ export namespace google { } } + /** Properties of a ListInstantSnapshotGroups. */ + interface IListInstantSnapshotGroups { + + /** ListInstantSnapshotGroups etag */ + etag?: (string|null); + + /** ListInstantSnapshotGroups id */ + id?: (string|null); + + /** ListInstantSnapshotGroups items */ + items?: (google.cloud.compute.v1beta.IInstantSnapshotGroup[]|null); + + /** ListInstantSnapshotGroups kind */ + kind?: (string|null); + + /** ListInstantSnapshotGroups nextPageToken */ + nextPageToken?: (string|null); + + /** ListInstantSnapshotGroups selfLink */ + selfLink?: (string|null); + + /** ListInstantSnapshotGroups unreachables */ + unreachables?: (string[]|null); + + /** ListInstantSnapshotGroups warning */ + warning?: (google.cloud.compute.v1beta.IWarning|null); + } + + /** Represents a ListInstantSnapshotGroups. */ + class ListInstantSnapshotGroups implements IListInstantSnapshotGroups { + + /** + * Constructs a new ListInstantSnapshotGroups. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IListInstantSnapshotGroups); + + /** ListInstantSnapshotGroups etag. */ + public etag?: (string|null); + + /** ListInstantSnapshotGroups id. */ + public id?: (string|null); + + /** ListInstantSnapshotGroups items. */ + public items: google.cloud.compute.v1beta.IInstantSnapshotGroup[]; + + /** ListInstantSnapshotGroups kind. */ + public kind?: (string|null); + + /** ListInstantSnapshotGroups nextPageToken. */ + public nextPageToken?: (string|null); + + /** ListInstantSnapshotGroups selfLink. */ + public selfLink?: (string|null); + + /** ListInstantSnapshotGroups unreachables. */ + public unreachables: string[]; + + /** ListInstantSnapshotGroups warning. */ + public warning?: (google.cloud.compute.v1beta.IWarning|null); + + /** + * Creates a new ListInstantSnapshotGroups instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstantSnapshotGroups instance + */ + public static create(properties?: google.cloud.compute.v1beta.IListInstantSnapshotGroups): google.cloud.compute.v1beta.ListInstantSnapshotGroups; + + /** + * Encodes the specified ListInstantSnapshotGroups message. Does not implicitly {@link google.cloud.compute.v1beta.ListInstantSnapshotGroups.verify|verify} messages. + * @param message ListInstantSnapshotGroups message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IListInstantSnapshotGroups, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstantSnapshotGroups message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListInstantSnapshotGroups.verify|verify} messages. + * @param message ListInstantSnapshotGroups message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IListInstantSnapshotGroups, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstantSnapshotGroups message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstantSnapshotGroups + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ListInstantSnapshotGroups; + + /** + * Decodes a ListInstantSnapshotGroups message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstantSnapshotGroups + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ListInstantSnapshotGroups; + + /** + * Verifies a ListInstantSnapshotGroups message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstantSnapshotGroups message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstantSnapshotGroups + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ListInstantSnapshotGroups; + + /** + * Creates a plain object from a ListInstantSnapshotGroups message. Also converts values to other types if specified. + * @param message ListInstantSnapshotGroups + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ListInstantSnapshotGroups, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstantSnapshotGroups to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstantSnapshotGroups + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListInstantSnapshotGroupsRequest. */ + interface IListInstantSnapshotGroupsRequest { + + /** ListInstantSnapshotGroupsRequest filter */ + filter?: (string|null); + + /** ListInstantSnapshotGroupsRequest maxResults */ + maxResults?: (number|null); + + /** ListInstantSnapshotGroupsRequest orderBy */ + orderBy?: (string|null); + + /** ListInstantSnapshotGroupsRequest pageToken */ + pageToken?: (string|null); + + /** ListInstantSnapshotGroupsRequest project */ + project?: (string|null); + + /** ListInstantSnapshotGroupsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + + /** ListInstantSnapshotGroupsRequest zone */ + zone?: (string|null); + } + + /** Represents a ListInstantSnapshotGroupsRequest. */ + class ListInstantSnapshotGroupsRequest implements IListInstantSnapshotGroupsRequest { + + /** + * Constructs a new ListInstantSnapshotGroupsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest); + + /** ListInstantSnapshotGroupsRequest filter. */ + public filter?: (string|null); + + /** ListInstantSnapshotGroupsRequest maxResults. */ + public maxResults?: (number|null); + + /** ListInstantSnapshotGroupsRequest orderBy. */ + public orderBy?: (string|null); + + /** ListInstantSnapshotGroupsRequest pageToken. */ + public pageToken?: (string|null); + + /** ListInstantSnapshotGroupsRequest project. */ + public project: string; + + /** ListInstantSnapshotGroupsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** ListInstantSnapshotGroupsRequest zone. */ + public zone: string; + + /** + * Creates a new ListInstantSnapshotGroupsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListInstantSnapshotGroupsRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest): google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest; + + /** + * Encodes the specified ListInstantSnapshotGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest.verify|verify} messages. + * @param message ListInstantSnapshotGroupsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListInstantSnapshotGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest.verify|verify} messages. + * @param message ListInstantSnapshotGroupsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListInstantSnapshotGroupsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListInstantSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest; + + /** + * Decodes a ListInstantSnapshotGroupsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListInstantSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest; + + /** + * Verifies a ListInstantSnapshotGroupsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListInstantSnapshotGroupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListInstantSnapshotGroupsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest; + + /** + * Creates a plain object from a ListInstantSnapshotGroupsRequest message. Also converts values to other types if specified. + * @param message ListInstantSnapshotGroupsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListInstantSnapshotGroupsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListInstantSnapshotGroupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a ListInstantSnapshotsRequest. */ interface IListInstantSnapshotsRequest { @@ -364671,6 +368535,145 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a ListNamedSetsRoutersRequest. */ + interface IListNamedSetsRoutersRequest { + + /** ListNamedSetsRoutersRequest filter */ + filter?: (string|null); + + /** ListNamedSetsRoutersRequest maxResults */ + maxResults?: (number|null); + + /** ListNamedSetsRoutersRequest orderBy */ + orderBy?: (string|null); + + /** ListNamedSetsRoutersRequest pageToken */ + pageToken?: (string|null); + + /** ListNamedSetsRoutersRequest project */ + project?: (string|null); + + /** ListNamedSetsRoutersRequest region */ + region?: (string|null); + + /** ListNamedSetsRoutersRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + + /** ListNamedSetsRoutersRequest router */ + router?: (string|null); + } + + /** Represents a ListNamedSetsRoutersRequest. */ + class ListNamedSetsRoutersRequest implements IListNamedSetsRoutersRequest { + + /** + * Constructs a new ListNamedSetsRoutersRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IListNamedSetsRoutersRequest); + + /** ListNamedSetsRoutersRequest filter. */ + public filter?: (string|null); + + /** ListNamedSetsRoutersRequest maxResults. */ + public maxResults?: (number|null); + + /** ListNamedSetsRoutersRequest orderBy. */ + public orderBy?: (string|null); + + /** ListNamedSetsRoutersRequest pageToken. */ + public pageToken?: (string|null); + + /** ListNamedSetsRoutersRequest project. */ + public project: string; + + /** ListNamedSetsRoutersRequest region. */ + public region: string; + + /** ListNamedSetsRoutersRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** ListNamedSetsRoutersRequest router. */ + public router: string; + + /** + * Creates a new ListNamedSetsRoutersRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListNamedSetsRoutersRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IListNamedSetsRoutersRequest): google.cloud.compute.v1beta.ListNamedSetsRoutersRequest; + + /** + * Encodes the specified ListNamedSetsRoutersRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListNamedSetsRoutersRequest.verify|verify} messages. + * @param message ListNamedSetsRoutersRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListNamedSetsRoutersRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListNamedSetsRoutersRequest.verify|verify} messages. + * @param message ListNamedSetsRoutersRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListNamedSetsRoutersRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListNamedSetsRoutersRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ListNamedSetsRoutersRequest; + + /** + * Decodes a ListNamedSetsRoutersRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListNamedSetsRoutersRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ListNamedSetsRoutersRequest; + + /** + * Verifies a ListNamedSetsRoutersRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListNamedSetsRoutersRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListNamedSetsRoutersRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ListNamedSetsRoutersRequest; + + /** + * Creates a plain object from a ListNamedSetsRoutersRequest message. Also converts values to other types if specified. + * @param message ListNamedSetsRoutersRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ListNamedSetsRoutersRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListNamedSetsRoutersRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListNamedSetsRoutersRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a ListNetworkAttachmentsRequest. */ interface IListNetworkAttachmentsRequest { @@ -369770,6 +373773,139 @@ export namespace google { } } + /** Properties of a ListRegionInstantSnapshotGroupsRequest. */ + interface IListRegionInstantSnapshotGroupsRequest { + + /** ListRegionInstantSnapshotGroupsRequest filter */ + filter?: (string|null); + + /** ListRegionInstantSnapshotGroupsRequest maxResults */ + maxResults?: (number|null); + + /** ListRegionInstantSnapshotGroupsRequest orderBy */ + orderBy?: (string|null); + + /** ListRegionInstantSnapshotGroupsRequest pageToken */ + pageToken?: (string|null); + + /** ListRegionInstantSnapshotGroupsRequest project */ + project?: (string|null); + + /** ListRegionInstantSnapshotGroupsRequest region */ + region?: (string|null); + + /** ListRegionInstantSnapshotGroupsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListRegionInstantSnapshotGroupsRequest. */ + class ListRegionInstantSnapshotGroupsRequest implements IListRegionInstantSnapshotGroupsRequest { + + /** + * Constructs a new ListRegionInstantSnapshotGroupsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest); + + /** ListRegionInstantSnapshotGroupsRequest filter. */ + public filter?: (string|null); + + /** ListRegionInstantSnapshotGroupsRequest maxResults. */ + public maxResults?: (number|null); + + /** ListRegionInstantSnapshotGroupsRequest orderBy. */ + public orderBy?: (string|null); + + /** ListRegionInstantSnapshotGroupsRequest pageToken. */ + public pageToken?: (string|null); + + /** ListRegionInstantSnapshotGroupsRequest project. */ + public project: string; + + /** ListRegionInstantSnapshotGroupsRequest region. */ + public region: string; + + /** ListRegionInstantSnapshotGroupsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** + * Creates a new ListRegionInstantSnapshotGroupsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListRegionInstantSnapshotGroupsRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest): google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest; + + /** + * Encodes the specified ListRegionInstantSnapshotGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest.verify|verify} messages. + * @param message ListRegionInstantSnapshotGroupsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListRegionInstantSnapshotGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest.verify|verify} messages. + * @param message ListRegionInstantSnapshotGroupsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListRegionInstantSnapshotGroupsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListRegionInstantSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest; + + /** + * Decodes a ListRegionInstantSnapshotGroupsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListRegionInstantSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest; + + /** + * Verifies a ListRegionInstantSnapshotGroupsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListRegionInstantSnapshotGroupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListRegionInstantSnapshotGroupsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest; + + /** + * Creates a plain object from a ListRegionInstantSnapshotGroupsRequest message. Also converts values to other types if specified. + * @param message ListRegionInstantSnapshotGroupsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListRegionInstantSnapshotGroupsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListRegionInstantSnapshotGroupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a ListRegionInstantSnapshotsRequest. */ interface IListRegionInstantSnapshotsRequest { @@ -372303,6 +376439,145 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a ListReservationSlotsRequest. */ + interface IListReservationSlotsRequest { + + /** ListReservationSlotsRequest filter */ + filter?: (string|null); + + /** ListReservationSlotsRequest maxResults */ + maxResults?: (number|null); + + /** ListReservationSlotsRequest orderBy */ + orderBy?: (string|null); + + /** ListReservationSlotsRequest pageToken */ + pageToken?: (string|null); + + /** ListReservationSlotsRequest parentName */ + parentName?: (string|null); + + /** ListReservationSlotsRequest project */ + project?: (string|null); + + /** ListReservationSlotsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + + /** ListReservationSlotsRequest zone */ + zone?: (string|null); + } + + /** Represents a ListReservationSlotsRequest. */ + class ListReservationSlotsRequest implements IListReservationSlotsRequest { + + /** + * Constructs a new ListReservationSlotsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IListReservationSlotsRequest); + + /** ListReservationSlotsRequest filter. */ + public filter?: (string|null); + + /** ListReservationSlotsRequest maxResults. */ + public maxResults?: (number|null); + + /** ListReservationSlotsRequest orderBy. */ + public orderBy?: (string|null); + + /** ListReservationSlotsRequest pageToken. */ + public pageToken?: (string|null); + + /** ListReservationSlotsRequest parentName. */ + public parentName: string; + + /** ListReservationSlotsRequest project. */ + public project: string; + + /** ListReservationSlotsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** ListReservationSlotsRequest zone. */ + public zone: string; + + /** + * Creates a new ListReservationSlotsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListReservationSlotsRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IListReservationSlotsRequest): google.cloud.compute.v1beta.ListReservationSlotsRequest; + + /** + * Encodes the specified ListReservationSlotsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationSlotsRequest.verify|verify} messages. + * @param message ListReservationSlotsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IListReservationSlotsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListReservationSlotsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationSlotsRequest.verify|verify} messages. + * @param message ListReservationSlotsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IListReservationSlotsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListReservationSlotsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListReservationSlotsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ListReservationSlotsRequest; + + /** + * Decodes a ListReservationSlotsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListReservationSlotsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ListReservationSlotsRequest; + + /** + * Verifies a ListReservationSlotsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListReservationSlotsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListReservationSlotsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ListReservationSlotsRequest; + + /** + * Creates a plain object from a ListReservationSlotsRequest message. Also converts values to other types if specified. + * @param message ListReservationSlotsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ListReservationSlotsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListReservationSlotsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListReservationSlotsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a ListReservationSubBlocksRequest. */ interface IListReservationSubBlocksRequest { @@ -373621,6 +377896,272 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a ListSnapshotGroups. */ + interface IListSnapshotGroups { + + /** ListSnapshotGroups etag */ + etag?: (string|null); + + /** ListSnapshotGroups id */ + id?: (string|null); + + /** ListSnapshotGroups items */ + items?: (google.cloud.compute.v1beta.ISnapshotGroup[]|null); + + /** ListSnapshotGroups kind */ + kind?: (string|null); + + /** ListSnapshotGroups nextPageToken */ + nextPageToken?: (string|null); + + /** ListSnapshotGroups selfLink */ + selfLink?: (string|null); + + /** ListSnapshotGroups unreachables */ + unreachables?: (string[]|null); + + /** ListSnapshotGroups warning */ + warning?: (google.cloud.compute.v1beta.IWarning|null); + } + + /** Represents a ListSnapshotGroups. */ + class ListSnapshotGroups implements IListSnapshotGroups { + + /** + * Constructs a new ListSnapshotGroups. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IListSnapshotGroups); + + /** ListSnapshotGroups etag. */ + public etag?: (string|null); + + /** ListSnapshotGroups id. */ + public id?: (string|null); + + /** ListSnapshotGroups items. */ + public items: google.cloud.compute.v1beta.ISnapshotGroup[]; + + /** ListSnapshotGroups kind. */ + public kind?: (string|null); + + /** ListSnapshotGroups nextPageToken. */ + public nextPageToken?: (string|null); + + /** ListSnapshotGroups selfLink. */ + public selfLink?: (string|null); + + /** ListSnapshotGroups unreachables. */ + public unreachables: string[]; + + /** ListSnapshotGroups warning. */ + public warning?: (google.cloud.compute.v1beta.IWarning|null); + + /** + * Creates a new ListSnapshotGroups instance using the specified properties. + * @param [properties] Properties to set + * @returns ListSnapshotGroups instance + */ + public static create(properties?: google.cloud.compute.v1beta.IListSnapshotGroups): google.cloud.compute.v1beta.ListSnapshotGroups; + + /** + * Encodes the specified ListSnapshotGroups message. Does not implicitly {@link google.cloud.compute.v1beta.ListSnapshotGroups.verify|verify} messages. + * @param message ListSnapshotGroups message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IListSnapshotGroups, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListSnapshotGroups message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListSnapshotGroups.verify|verify} messages. + * @param message ListSnapshotGroups message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IListSnapshotGroups, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListSnapshotGroups message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListSnapshotGroups + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ListSnapshotGroups; + + /** + * Decodes a ListSnapshotGroups message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListSnapshotGroups + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ListSnapshotGroups; + + /** + * Verifies a ListSnapshotGroups message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListSnapshotGroups message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListSnapshotGroups + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ListSnapshotGroups; + + /** + * Creates a plain object from a ListSnapshotGroups message. Also converts values to other types if specified. + * @param message ListSnapshotGroups + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ListSnapshotGroups, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListSnapshotGroups to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListSnapshotGroups + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListSnapshotGroupsRequest. */ + interface IListSnapshotGroupsRequest { + + /** ListSnapshotGroupsRequest filter */ + filter?: (string|null); + + /** ListSnapshotGroupsRequest maxResults */ + maxResults?: (number|null); + + /** ListSnapshotGroupsRequest orderBy */ + orderBy?: (string|null); + + /** ListSnapshotGroupsRequest pageToken */ + pageToken?: (string|null); + + /** ListSnapshotGroupsRequest project */ + project?: (string|null); + + /** ListSnapshotGroupsRequest returnPartialSuccess */ + returnPartialSuccess?: (boolean|null); + } + + /** Represents a ListSnapshotGroupsRequest. */ + class ListSnapshotGroupsRequest implements IListSnapshotGroupsRequest { + + /** + * Constructs a new ListSnapshotGroupsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IListSnapshotGroupsRequest); + + /** ListSnapshotGroupsRequest filter. */ + public filter?: (string|null); + + /** ListSnapshotGroupsRequest maxResults. */ + public maxResults?: (number|null); + + /** ListSnapshotGroupsRequest orderBy. */ + public orderBy?: (string|null); + + /** ListSnapshotGroupsRequest pageToken. */ + public pageToken?: (string|null); + + /** ListSnapshotGroupsRequest project. */ + public project: string; + + /** ListSnapshotGroupsRequest returnPartialSuccess. */ + public returnPartialSuccess?: (boolean|null); + + /** + * Creates a new ListSnapshotGroupsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ListSnapshotGroupsRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IListSnapshotGroupsRequest): google.cloud.compute.v1beta.ListSnapshotGroupsRequest; + + /** + * Encodes the specified ListSnapshotGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListSnapshotGroupsRequest.verify|verify} messages. + * @param message ListSnapshotGroupsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IListSnapshotGroupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ListSnapshotGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListSnapshotGroupsRequest.verify|verify} messages. + * @param message ListSnapshotGroupsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IListSnapshotGroupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ListSnapshotGroupsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ListSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ListSnapshotGroupsRequest; + + /** + * Decodes a ListSnapshotGroupsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ListSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ListSnapshotGroupsRequest; + + /** + * Verifies a ListSnapshotGroupsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ListSnapshotGroupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListSnapshotGroupsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ListSnapshotGroupsRequest; + + /** + * Creates a plain object from a ListSnapshotGroupsRequest message. Also converts values to other types if specified. + * @param message ListSnapshotGroupsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ListSnapshotGroupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListSnapshotGroupsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListSnapshotGroupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a ListSnapshotsRequest. */ interface IListSnapshotsRequest { @@ -377376,6 +381917,9 @@ export namespace google { /** LocationPolicy targetShape */ targetShape?: (string|null); + + /** LocationPolicy zones */ + zones?: (google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration[]|null); } /** Represents a LocationPolicy. */ @@ -377393,6 +381937,9 @@ export namespace google { /** LocationPolicy targetShape. */ public targetShape?: (string|null); + /** LocationPolicy zones. */ + public zones: google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration[]; + /** * Creates a new LocationPolicy instance using the specified properties. * @param [properties] Properties to set @@ -377693,6 +382240,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a LocationPolicyZoneConfiguration. */ + interface ILocationPolicyZoneConfiguration { + + /** LocationPolicyZoneConfiguration zone */ + zone?: (string|null); + } + + /** Represents a LocationPolicyZoneConfiguration. */ + class LocationPolicyZoneConfiguration implements ILocationPolicyZoneConfiguration { + + /** + * Constructs a new LocationPolicyZoneConfiguration. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration); + + /** LocationPolicyZoneConfiguration zone. */ + public zone?: (string|null); + + /** + * Creates a new LocationPolicyZoneConfiguration instance using the specified properties. + * @param [properties] Properties to set + * @returns LocationPolicyZoneConfiguration instance + */ + public static create(properties?: google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration): google.cloud.compute.v1beta.LocationPolicyZoneConfiguration; + + /** + * Encodes the specified LocationPolicyZoneConfiguration message. Does not implicitly {@link google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.verify|verify} messages. + * @param message LocationPolicyZoneConfiguration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified LocationPolicyZoneConfiguration message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.verify|verify} messages. + * @param message LocationPolicyZoneConfiguration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a LocationPolicyZoneConfiguration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns LocationPolicyZoneConfiguration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.LocationPolicyZoneConfiguration; + + /** + * Decodes a LocationPolicyZoneConfiguration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns LocationPolicyZoneConfiguration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.LocationPolicyZoneConfiguration; + + /** + * Verifies a LocationPolicyZoneConfiguration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a LocationPolicyZoneConfiguration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LocationPolicyZoneConfiguration + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.LocationPolicyZoneConfiguration; + + /** + * Creates a plain object from a LocationPolicyZoneConfiguration message. Also converts values to other types if specified. + * @param message LocationPolicyZoneConfiguration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.LocationPolicyZoneConfiguration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LocationPolicyZoneConfiguration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LocationPolicyZoneConfiguration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a MachineImage. */ interface IMachineImage { @@ -377726,6 +382370,9 @@ export namespace google { /** MachineImage name */ name?: (string|null); + /** MachineImage params */ + params?: (google.cloud.compute.v1beta.IMachineImageParams|null); + /** MachineImage satisfiesPzi */ satisfiesPzi?: (boolean|null); @@ -377796,6 +382443,9 @@ export namespace google { /** MachineImage name. */ public name?: (string|null); + /** MachineImage params. */ + public params?: (google.cloud.compute.v1beta.IMachineImageParams|null); + /** MachineImage satisfiesPzi. */ public satisfiesPzi?: (boolean|null); @@ -378044,6 +382694,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a MachineImageParams. */ + interface IMachineImageParams { + + /** MachineImageParams resourceManagerTags */ + resourceManagerTags?: ({ [k: string]: string }|null); + } + + /** Represents a MachineImageParams. */ + class MachineImageParams implements IMachineImageParams { + + /** + * Constructs a new MachineImageParams. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IMachineImageParams); + + /** MachineImageParams resourceManagerTags. */ + public resourceManagerTags: { [k: string]: string }; + + /** + * Creates a new MachineImageParams instance using the specified properties. + * @param [properties] Properties to set + * @returns MachineImageParams instance + */ + public static create(properties?: google.cloud.compute.v1beta.IMachineImageParams): google.cloud.compute.v1beta.MachineImageParams; + + /** + * Encodes the specified MachineImageParams message. Does not implicitly {@link google.cloud.compute.v1beta.MachineImageParams.verify|verify} messages. + * @param message MachineImageParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IMachineImageParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified MachineImageParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.MachineImageParams.verify|verify} messages. + * @param message MachineImageParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IMachineImageParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a MachineImageParams message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns MachineImageParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.MachineImageParams; + + /** + * Decodes a MachineImageParams message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns MachineImageParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.MachineImageParams; + + /** + * Verifies a MachineImageParams message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a MachineImageParams message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MachineImageParams + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.MachineImageParams; + + /** + * Creates a plain object from a MachineImageParams message. Also converts values to other types if specified. + * @param message MachineImageParams + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.MachineImageParams, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MachineImageParams to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MachineImageParams + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a MachineType. */ interface IMachineType { @@ -381732,6 +386479,137 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a NamedSet. */ + interface INamedSet { + + /** NamedSet description */ + description?: (string|null); + + /** NamedSet elements */ + elements?: (google.cloud.compute.v1beta.IExpr[]|null); + + /** NamedSet fingerprint */ + fingerprint?: (string|null); + + /** NamedSet name */ + name?: (string|null); + + /** NamedSet type */ + type?: (string|null); + } + + /** Represents a NamedSet. */ + class NamedSet implements INamedSet { + + /** + * Constructs a new NamedSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.INamedSet); + + /** NamedSet description. */ + public description?: (string|null); + + /** NamedSet elements. */ + public elements: google.cloud.compute.v1beta.IExpr[]; + + /** NamedSet fingerprint. */ + public fingerprint?: (string|null); + + /** NamedSet name. */ + public name?: (string|null); + + /** NamedSet type. */ + public type?: (string|null); + + /** + * Creates a new NamedSet instance using the specified properties. + * @param [properties] Properties to set + * @returns NamedSet instance + */ + public static create(properties?: google.cloud.compute.v1beta.INamedSet): google.cloud.compute.v1beta.NamedSet; + + /** + * Encodes the specified NamedSet message. Does not implicitly {@link google.cloud.compute.v1beta.NamedSet.verify|verify} messages. + * @param message NamedSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.INamedSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NamedSet message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.NamedSet.verify|verify} messages. + * @param message NamedSet message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.INamedSet, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NamedSet message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NamedSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.NamedSet; + + /** + * Decodes a NamedSet message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NamedSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.NamedSet; + + /** + * Verifies a NamedSet message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NamedSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamedSet + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.NamedSet; + + /** + * Creates a plain object from a NamedSet message. Also converts values to other types if specified. + * @param message NamedSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.NamedSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamedSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamedSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace NamedSet { + + /** Type enum. */ + enum Type { + UNDEFINED_TYPE = 0, + NAMED_SET_TYPE_COMMUNITY = 263444871, + NAMED_SET_TYPE_PREFIX = 228038036 + } + } + /** Properties of a NatIpInfo. */ interface INatIpInfo { @@ -385547,6 +390425,9 @@ export namespace google { /** NetworkInterface aliasIpRanges */ aliasIpRanges?: (google.cloud.compute.v1beta.IAliasIpRange[]|null); + /** NetworkInterface enableVpcScopedDns */ + enableVpcScopedDns?: (boolean|null); + /** NetworkInterface fingerprint */ fingerprint?: (string|null); @@ -385617,6 +390498,9 @@ export namespace google { /** NetworkInterface aliasIpRanges. */ public aliasIpRanges: google.cloud.compute.v1beta.IAliasIpRange[]; + /** NetworkInterface enableVpcScopedDns. */ + public enableVpcScopedDns?: (boolean|null); + /** NetworkInterface fingerprint. */ public fingerprint?: (string|null); @@ -388721,7 +393605,9 @@ export namespace google { /** FirewallPolicyTypes enum. */ enum FirewallPolicyTypes { UNDEFINED_FIREWALL_POLICY_TYPES = 0, + RDMA_FALCON_POLICY = 66315047, RDMA_ROCE_POLICY = 148757145, + ULL_POLICY = 100494364, VPC_POLICY = 74319208 } @@ -397972,6 +402858,127 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a PatchNamedSetRouterRequest. */ + interface IPatchNamedSetRouterRequest { + + /** PatchNamedSetRouterRequest namedSetResource */ + namedSetResource?: (google.cloud.compute.v1beta.INamedSet|null); + + /** PatchNamedSetRouterRequest project */ + project?: (string|null); + + /** PatchNamedSetRouterRequest region */ + region?: (string|null); + + /** PatchNamedSetRouterRequest requestId */ + requestId?: (string|null); + + /** PatchNamedSetRouterRequest router */ + router?: (string|null); + } + + /** Represents a PatchNamedSetRouterRequest. */ + class PatchNamedSetRouterRequest implements IPatchNamedSetRouterRequest { + + /** + * Constructs a new PatchNamedSetRouterRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IPatchNamedSetRouterRequest); + + /** PatchNamedSetRouterRequest namedSetResource. */ + public namedSetResource?: (google.cloud.compute.v1beta.INamedSet|null); + + /** PatchNamedSetRouterRequest project. */ + public project: string; + + /** PatchNamedSetRouterRequest region. */ + public region: string; + + /** PatchNamedSetRouterRequest requestId. */ + public requestId?: (string|null); + + /** PatchNamedSetRouterRequest router. */ + public router: string; + + /** + * Creates a new PatchNamedSetRouterRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns PatchNamedSetRouterRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IPatchNamedSetRouterRequest): google.cloud.compute.v1beta.PatchNamedSetRouterRequest; + + /** + * Encodes the specified PatchNamedSetRouterRequest message. Does not implicitly {@link google.cloud.compute.v1beta.PatchNamedSetRouterRequest.verify|verify} messages. + * @param message PatchNamedSetRouterRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IPatchNamedSetRouterRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified PatchNamedSetRouterRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.PatchNamedSetRouterRequest.verify|verify} messages. + * @param message PatchNamedSetRouterRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IPatchNamedSetRouterRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a PatchNamedSetRouterRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns PatchNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.PatchNamedSetRouterRequest; + + /** + * Decodes a PatchNamedSetRouterRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns PatchNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.PatchNamedSetRouterRequest; + + /** + * Verifies a PatchNamedSetRouterRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a PatchNamedSetRouterRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PatchNamedSetRouterRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.PatchNamedSetRouterRequest; + + /** + * Creates a plain object from a PatchNamedSetRouterRequest message. Also converts values to other types if specified. + * @param message PatchNamedSetRouterRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.PatchNamedSetRouterRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PatchNamedSetRouterRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PatchNamedSetRouterRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a PatchNetworkAttachmentRequest. */ interface IPatchNetworkAttachmentRequest { @@ -417595,6 +422602,9 @@ export namespace google { /** Reservation description */ description?: (string|null); + /** Reservation earlyAccessMaintenance */ + earlyAccessMaintenance?: (string|null); + /** Reservation enableEmergentMaintenance */ enableEmergentMaintenance?: (boolean|null); @@ -417610,6 +422620,9 @@ export namespace google { /** Reservation name */ name?: (string|null); + /** Reservation params */ + params?: (google.cloud.compute.v1beta.IReservationParams|null); + /** Reservation protectionTier */ protectionTier?: (string|null); @@ -417683,6 +422696,9 @@ export namespace google { /** Reservation description. */ public description?: (string|null); + /** Reservation earlyAccessMaintenance. */ + public earlyAccessMaintenance?: (string|null); + /** Reservation enableEmergentMaintenance. */ public enableEmergentMaintenance?: (boolean|null); @@ -417698,6 +422714,9 @@ export namespace google { /** Reservation name. */ public name?: (string|null); + /** Reservation params. */ + public params?: (google.cloud.compute.v1beta.IReservationParams|null); + /** Reservation protectionTier. */ public protectionTier?: (string|null); @@ -417825,6 +422844,14 @@ export namespace google { FLEXIBLE = 379880395 } + /** EarlyAccessMaintenance enum. */ + enum EarlyAccessMaintenance { + UNDEFINED_EARLY_ACCESS_MAINTENANCE = 0, + NO_EARLY_ACCESS = 220751774, + WAVE1 = 82367576, + WAVE2 = 82367577 + } + /** ProtectionTier enum. */ enum ProtectionTier { UNDEFINED_PROTECTION_TIER = 0, @@ -419215,6 +424242,721 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a ReservationParams. */ + interface IReservationParams { + + /** ReservationParams resourceManagerTags */ + resourceManagerTags?: ({ [k: string]: string }|null); + } + + /** Represents a ReservationParams. */ + class ReservationParams implements IReservationParams { + + /** + * Constructs a new ReservationParams. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IReservationParams); + + /** ReservationParams resourceManagerTags. */ + public resourceManagerTags: { [k: string]: string }; + + /** + * Creates a new ReservationParams instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservationParams instance + */ + public static create(properties?: google.cloud.compute.v1beta.IReservationParams): google.cloud.compute.v1beta.ReservationParams; + + /** + * Encodes the specified ReservationParams message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationParams.verify|verify} messages. + * @param message ReservationParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IReservationParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservationParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationParams.verify|verify} messages. + * @param message ReservationParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IReservationParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservationParams message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservationParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ReservationParams; + + /** + * Decodes a ReservationParams message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservationParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ReservationParams; + + /** + * Verifies a ReservationParams message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservationParams message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservationParams + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ReservationParams; + + /** + * Creates a plain object from a ReservationParams message. Also converts values to other types if specified. + * @param message ReservationParams + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ReservationParams, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservationParams to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservationParams + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservationSlot. */ + interface IReservationSlot { + + /** ReservationSlot creationTimestamp */ + creationTimestamp?: (string|null); + + /** ReservationSlot id */ + id?: (number|Long|string|null); + + /** ReservationSlot kind */ + kind?: (string|null); + + /** ReservationSlot name */ + name?: (string|null); + + /** ReservationSlot physicalTopology */ + physicalTopology?: (google.cloud.compute.v1beta.IReservationSlotPhysicalTopology|null); + + /** ReservationSlot selfLink */ + selfLink?: (string|null); + + /** ReservationSlot selfLinkWithId */ + selfLinkWithId?: (string|null); + + /** ReservationSlot shareSettings */ + shareSettings?: (google.cloud.compute.v1beta.IShareSettings|null); + + /** ReservationSlot state */ + state?: (string|null); + + /** ReservationSlot status */ + status?: (google.cloud.compute.v1beta.IReservationSlotStatus|null); + + /** ReservationSlot zone */ + zone?: (string|null); + } + + /** Represents a ReservationSlot. */ + class ReservationSlot implements IReservationSlot { + + /** + * Constructs a new ReservationSlot. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IReservationSlot); + + /** ReservationSlot creationTimestamp. */ + public creationTimestamp?: (string|null); + + /** ReservationSlot id. */ + public id?: (number|Long|string|null); + + /** ReservationSlot kind. */ + public kind?: (string|null); + + /** ReservationSlot name. */ + public name?: (string|null); + + /** ReservationSlot physicalTopology. */ + public physicalTopology?: (google.cloud.compute.v1beta.IReservationSlotPhysicalTopology|null); + + /** ReservationSlot selfLink. */ + public selfLink?: (string|null); + + /** ReservationSlot selfLinkWithId. */ + public selfLinkWithId?: (string|null); + + /** ReservationSlot shareSettings. */ + public shareSettings?: (google.cloud.compute.v1beta.IShareSettings|null); + + /** ReservationSlot state. */ + public state?: (string|null); + + /** ReservationSlot status. */ + public status?: (google.cloud.compute.v1beta.IReservationSlotStatus|null); + + /** ReservationSlot zone. */ + public zone?: (string|null); + + /** + * Creates a new ReservationSlot instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservationSlot instance + */ + public static create(properties?: google.cloud.compute.v1beta.IReservationSlot): google.cloud.compute.v1beta.ReservationSlot; + + /** + * Encodes the specified ReservationSlot message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlot.verify|verify} messages. + * @param message ReservationSlot message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IReservationSlot, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservationSlot message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlot.verify|verify} messages. + * @param message ReservationSlot message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IReservationSlot, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservationSlot message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservationSlot + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ReservationSlot; + + /** + * Decodes a ReservationSlot message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservationSlot + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ReservationSlot; + + /** + * Verifies a ReservationSlot message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservationSlot message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservationSlot + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ReservationSlot; + + /** + * Creates a plain object from a ReservationSlot message. Also converts values to other types if specified. + * @param message ReservationSlot + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ReservationSlot, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservationSlot to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservationSlot + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ReservationSlot { + + /** State enum. */ + enum State { + UNDEFINED_STATE = 0, + ACTIVE = 314733318, + CREATING = 455564985, + DELETING = 528602024, + STATE_UNSPECIFIED = 470755401, + UNAVAILABLE = 413756464 + } + } + + /** Properties of a ReservationSlotPhysicalTopology. */ + interface IReservationSlotPhysicalTopology { + + /** ReservationSlotPhysicalTopology block */ + block?: (string|null); + + /** ReservationSlotPhysicalTopology cluster */ + cluster?: (string|null); + + /** ReservationSlotPhysicalTopology host */ + host?: (string|null); + + /** ReservationSlotPhysicalTopology subBlock */ + subBlock?: (string|null); + } + + /** Represents a ReservationSlotPhysicalTopology. */ + class ReservationSlotPhysicalTopology implements IReservationSlotPhysicalTopology { + + /** + * Constructs a new ReservationSlotPhysicalTopology. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IReservationSlotPhysicalTopology); + + /** ReservationSlotPhysicalTopology block. */ + public block?: (string|null); + + /** ReservationSlotPhysicalTopology cluster. */ + public cluster?: (string|null); + + /** ReservationSlotPhysicalTopology host. */ + public host?: (string|null); + + /** ReservationSlotPhysicalTopology subBlock. */ + public subBlock?: (string|null); + + /** + * Creates a new ReservationSlotPhysicalTopology instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservationSlotPhysicalTopology instance + */ + public static create(properties?: google.cloud.compute.v1beta.IReservationSlotPhysicalTopology): google.cloud.compute.v1beta.ReservationSlotPhysicalTopology; + + /** + * Encodes the specified ReservationSlotPhysicalTopology message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.verify|verify} messages. + * @param message ReservationSlotPhysicalTopology message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IReservationSlotPhysicalTopology, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservationSlotPhysicalTopology message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.verify|verify} messages. + * @param message ReservationSlotPhysicalTopology message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IReservationSlotPhysicalTopology, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservationSlotPhysicalTopology message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservationSlotPhysicalTopology + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ReservationSlotPhysicalTopology; + + /** + * Decodes a ReservationSlotPhysicalTopology message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservationSlotPhysicalTopology + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ReservationSlotPhysicalTopology; + + /** + * Verifies a ReservationSlotPhysicalTopology message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservationSlotPhysicalTopology message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservationSlotPhysicalTopology + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ReservationSlotPhysicalTopology; + + /** + * Creates a plain object from a ReservationSlotPhysicalTopology message. Also converts values to other types if specified. + * @param message ReservationSlotPhysicalTopology + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ReservationSlotPhysicalTopology, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservationSlotPhysicalTopology to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservationSlotPhysicalTopology + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservationSlotStatus. */ + interface IReservationSlotStatus { + + /** ReservationSlotStatus physicalTopology */ + physicalTopology?: (google.cloud.compute.v1beta.IReservationSlotPhysicalTopology|null); + + /** ReservationSlotStatus rdmaIpAddresses */ + rdmaIpAddresses?: (string[]|null); + + /** ReservationSlotStatus runningInstances */ + runningInstances?: (string[]|null); + } + + /** Represents a ReservationSlotStatus. */ + class ReservationSlotStatus implements IReservationSlotStatus { + + /** + * Constructs a new ReservationSlotStatus. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IReservationSlotStatus); + + /** ReservationSlotStatus physicalTopology. */ + public physicalTopology?: (google.cloud.compute.v1beta.IReservationSlotPhysicalTopology|null); + + /** ReservationSlotStatus rdmaIpAddresses. */ + public rdmaIpAddresses: string[]; + + /** ReservationSlotStatus runningInstances. */ + public runningInstances: string[]; + + /** + * Creates a new ReservationSlotStatus instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservationSlotStatus instance + */ + public static create(properties?: google.cloud.compute.v1beta.IReservationSlotStatus): google.cloud.compute.v1beta.ReservationSlotStatus; + + /** + * Encodes the specified ReservationSlotStatus message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotStatus.verify|verify} messages. + * @param message ReservationSlotStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IReservationSlotStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservationSlotStatus message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotStatus.verify|verify} messages. + * @param message ReservationSlotStatus message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IReservationSlotStatus, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservationSlotStatus message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservationSlotStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ReservationSlotStatus; + + /** + * Decodes a ReservationSlotStatus message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservationSlotStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ReservationSlotStatus; + + /** + * Verifies a ReservationSlotStatus message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservationSlotStatus message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservationSlotStatus + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ReservationSlotStatus; + + /** + * Creates a plain object from a ReservationSlotStatus message. Also converts values to other types if specified. + * @param message ReservationSlotStatus + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ReservationSlotStatus, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservationSlotStatus to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservationSlotStatus + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservationSlotsGetResponse. */ + interface IReservationSlotsGetResponse { + + /** ReservationSlotsGetResponse resource */ + resource?: (google.cloud.compute.v1beta.IReservationSlot|null); + } + + /** Represents a ReservationSlotsGetResponse. */ + class ReservationSlotsGetResponse implements IReservationSlotsGetResponse { + + /** + * Constructs a new ReservationSlotsGetResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IReservationSlotsGetResponse); + + /** ReservationSlotsGetResponse resource. */ + public resource?: (google.cloud.compute.v1beta.IReservationSlot|null); + + /** + * Creates a new ReservationSlotsGetResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservationSlotsGetResponse instance + */ + public static create(properties?: google.cloud.compute.v1beta.IReservationSlotsGetResponse): google.cloud.compute.v1beta.ReservationSlotsGetResponse; + + /** + * Encodes the specified ReservationSlotsGetResponse message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotsGetResponse.verify|verify} messages. + * @param message ReservationSlotsGetResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IReservationSlotsGetResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservationSlotsGetResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotsGetResponse.verify|verify} messages. + * @param message ReservationSlotsGetResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IReservationSlotsGetResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservationSlotsGetResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservationSlotsGetResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ReservationSlotsGetResponse; + + /** + * Decodes a ReservationSlotsGetResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservationSlotsGetResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ReservationSlotsGetResponse; + + /** + * Verifies a ReservationSlotsGetResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservationSlotsGetResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservationSlotsGetResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ReservationSlotsGetResponse; + + /** + * Creates a plain object from a ReservationSlotsGetResponse message. Also converts values to other types if specified. + * @param message ReservationSlotsGetResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ReservationSlotsGetResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservationSlotsGetResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservationSlotsGetResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReservationSlotsListResponse. */ + interface IReservationSlotsListResponse { + + /** ReservationSlotsListResponse id */ + id?: (string|null); + + /** ReservationSlotsListResponse items */ + items?: (google.cloud.compute.v1beta.IReservationSlot[]|null); + + /** ReservationSlotsListResponse kind */ + kind?: (string|null); + + /** ReservationSlotsListResponse nextPageToken */ + nextPageToken?: (string|null); + + /** ReservationSlotsListResponse selfLink */ + selfLink?: (string|null); + + /** ReservationSlotsListResponse warning */ + warning?: (google.cloud.compute.v1beta.IWarning|null); + } + + /** Represents a ReservationSlotsListResponse. */ + class ReservationSlotsListResponse implements IReservationSlotsListResponse { + + /** + * Constructs a new ReservationSlotsListResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IReservationSlotsListResponse); + + /** ReservationSlotsListResponse id. */ + public id?: (string|null); + + /** ReservationSlotsListResponse items. */ + public items: google.cloud.compute.v1beta.IReservationSlot[]; + + /** ReservationSlotsListResponse kind. */ + public kind?: (string|null); + + /** ReservationSlotsListResponse nextPageToken. */ + public nextPageToken?: (string|null); + + /** ReservationSlotsListResponse selfLink. */ + public selfLink?: (string|null); + + /** ReservationSlotsListResponse warning. */ + public warning?: (google.cloud.compute.v1beta.IWarning|null); + + /** + * Creates a new ReservationSlotsListResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ReservationSlotsListResponse instance + */ + public static create(properties?: google.cloud.compute.v1beta.IReservationSlotsListResponse): google.cloud.compute.v1beta.ReservationSlotsListResponse; + + /** + * Encodes the specified ReservationSlotsListResponse message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotsListResponse.verify|verify} messages. + * @param message ReservationSlotsListResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IReservationSlotsListResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReservationSlotsListResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotsListResponse.verify|verify} messages. + * @param message ReservationSlotsListResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IReservationSlotsListResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReservationSlotsListResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReservationSlotsListResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.ReservationSlotsListResponse; + + /** + * Decodes a ReservationSlotsListResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReservationSlotsListResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.ReservationSlotsListResponse; + + /** + * Verifies a ReservationSlotsListResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReservationSlotsListResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReservationSlotsListResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.ReservationSlotsListResponse; + + /** + * Creates a plain object from a ReservationSlotsListResponse message. Also converts values to other types if specified. + * @param message ReservationSlotsListResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.ReservationSlotsListResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReservationSlotsListResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservationSlotsListResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a ReservationSubBlock. */ interface IReservationSubBlock { @@ -424127,6 +429869,9 @@ export namespace google { /** ResourceStatusEffectiveInstanceMetadata enableOsloginMetadataValue */ enableOsloginMetadataValue?: (boolean|null); + /** ResourceStatusEffectiveInstanceMetadata gceContainerDeclarationMetadataValue */ + gceContainerDeclarationMetadataValue?: (boolean|null); + /** ResourceStatusEffectiveInstanceMetadata serialPortEnableMetadataValue */ serialPortEnableMetadataValue?: (boolean|null); @@ -424161,6 +429906,9 @@ export namespace google { /** ResourceStatusEffectiveInstanceMetadata enableOsloginMetadataValue. */ public enableOsloginMetadataValue?: (boolean|null); + /** ResourceStatusEffectiveInstanceMetadata gceContainerDeclarationMetadataValue. */ + public gceContainerDeclarationMetadataValue?: (boolean|null); + /** ResourceStatusEffectiveInstanceMetadata serialPortEnableMetadataValue. */ public serialPortEnableMetadataValue?: (boolean|null); @@ -431051,6 +436799,109 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a RoutersGetNamedSetResponse. */ + interface IRoutersGetNamedSetResponse { + + /** RoutersGetNamedSetResponse etag */ + etag?: (string|null); + + /** RoutersGetNamedSetResponse resource */ + resource?: (google.cloud.compute.v1beta.INamedSet|null); + } + + /** Represents a RoutersGetNamedSetResponse. */ + class RoutersGetNamedSetResponse implements IRoutersGetNamedSetResponse { + + /** + * Constructs a new RoutersGetNamedSetResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IRoutersGetNamedSetResponse); + + /** RoutersGetNamedSetResponse etag. */ + public etag?: (string|null); + + /** RoutersGetNamedSetResponse resource. */ + public resource?: (google.cloud.compute.v1beta.INamedSet|null); + + /** + * Creates a new RoutersGetNamedSetResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns RoutersGetNamedSetResponse instance + */ + public static create(properties?: google.cloud.compute.v1beta.IRoutersGetNamedSetResponse): google.cloud.compute.v1beta.RoutersGetNamedSetResponse; + + /** + * Encodes the specified RoutersGetNamedSetResponse message. Does not implicitly {@link google.cloud.compute.v1beta.RoutersGetNamedSetResponse.verify|verify} messages. + * @param message RoutersGetNamedSetResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RoutersGetNamedSetResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.RoutersGetNamedSetResponse.verify|verify} messages. + * @param message RoutersGetNamedSetResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RoutersGetNamedSetResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RoutersGetNamedSetResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.RoutersGetNamedSetResponse; + + /** + * Decodes a RoutersGetNamedSetResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RoutersGetNamedSetResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.RoutersGetNamedSetResponse; + + /** + * Verifies a RoutersGetNamedSetResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RoutersGetNamedSetResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutersGetNamedSetResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.RoutersGetNamedSetResponse; + + /** + * Creates a plain object from a RoutersGetNamedSetResponse message. Also converts values to other types if specified. + * @param message RoutersGetNamedSetResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.RoutersGetNamedSetResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutersGetNamedSetResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutersGetNamedSetResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a RoutersGetRoutePolicyResponse. */ interface IRoutersGetRoutePolicyResponse { @@ -431287,6 +437138,145 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a RoutersListNamedSets. */ + interface IRoutersListNamedSets { + + /** RoutersListNamedSets etag */ + etag?: (string|null); + + /** RoutersListNamedSets id */ + id?: (string|null); + + /** RoutersListNamedSets kind */ + kind?: (string|null); + + /** RoutersListNamedSets nextPageToken */ + nextPageToken?: (string|null); + + /** RoutersListNamedSets result */ + result?: (google.cloud.compute.v1beta.INamedSet[]|null); + + /** RoutersListNamedSets selfLink */ + selfLink?: (string|null); + + /** RoutersListNamedSets unreachables */ + unreachables?: (string[]|null); + + /** RoutersListNamedSets warning */ + warning?: (google.cloud.compute.v1beta.IWarning|null); + } + + /** Represents a RoutersListNamedSets. */ + class RoutersListNamedSets implements IRoutersListNamedSets { + + /** + * Constructs a new RoutersListNamedSets. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IRoutersListNamedSets); + + /** RoutersListNamedSets etag. */ + public etag?: (string|null); + + /** RoutersListNamedSets id. */ + public id?: (string|null); + + /** RoutersListNamedSets kind. */ + public kind?: (string|null); + + /** RoutersListNamedSets nextPageToken. */ + public nextPageToken?: (string|null); + + /** RoutersListNamedSets result. */ + public result: google.cloud.compute.v1beta.INamedSet[]; + + /** RoutersListNamedSets selfLink. */ + public selfLink?: (string|null); + + /** RoutersListNamedSets unreachables. */ + public unreachables: string[]; + + /** RoutersListNamedSets warning. */ + public warning?: (google.cloud.compute.v1beta.IWarning|null); + + /** + * Creates a new RoutersListNamedSets instance using the specified properties. + * @param [properties] Properties to set + * @returns RoutersListNamedSets instance + */ + public static create(properties?: google.cloud.compute.v1beta.IRoutersListNamedSets): google.cloud.compute.v1beta.RoutersListNamedSets; + + /** + * Encodes the specified RoutersListNamedSets message. Does not implicitly {@link google.cloud.compute.v1beta.RoutersListNamedSets.verify|verify} messages. + * @param message RoutersListNamedSets message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IRoutersListNamedSets, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified RoutersListNamedSets message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.RoutersListNamedSets.verify|verify} messages. + * @param message RoutersListNamedSets message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IRoutersListNamedSets, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a RoutersListNamedSets message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns RoutersListNamedSets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.RoutersListNamedSets; + + /** + * Decodes a RoutersListNamedSets message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns RoutersListNamedSets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.RoutersListNamedSets; + + /** + * Verifies a RoutersListNamedSets message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a RoutersListNamedSets message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutersListNamedSets + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.RoutersListNamedSets; + + /** + * Creates a plain object from a RoutersListNamedSets message. Also converts values to other types if specified. + * @param message RoutersListNamedSets + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.RoutersListNamedSets, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutersListNamedSets to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutersListNamedSets + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a RoutersListRoutePolicies. */ interface IRoutersListRoutePolicies { @@ -432297,6 +438287,9 @@ export namespace google { /** Scheduling preemptible */ preemptible?: (boolean|null); + /** Scheduling preemptionNoticeDuration */ + preemptionNoticeDuration?: (google.cloud.compute.v1beta.IDuration|null); + /** Scheduling provisioningModel */ provisioningModel?: (string|null); @@ -432361,6 +438354,9 @@ export namespace google { /** Scheduling preemptible. */ public preemptible?: (boolean|null); + /** Scheduling preemptionNoticeDuration. */ + public preemptionNoticeDuration?: (google.cloud.compute.v1beta.IDuration|null); + /** Scheduling provisioningModel. */ public provisioningModel?: (string|null); @@ -441413,6 +447409,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a SetIamPolicyInstantSnapshotGroupRequest. */ + interface ISetIamPolicyInstantSnapshotGroupRequest { + + /** SetIamPolicyInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** SetIamPolicyInstantSnapshotGroupRequest resource */ + resource?: (string|null); + + /** SetIamPolicyInstantSnapshotGroupRequest zone */ + zone?: (string|null); + + /** SetIamPolicyInstantSnapshotGroupRequest zoneSetPolicyRequestResource */ + zoneSetPolicyRequestResource?: (google.cloud.compute.v1beta.IZoneSetPolicyRequest|null); + } + + /** Represents a SetIamPolicyInstantSnapshotGroupRequest. */ + class SetIamPolicyInstantSnapshotGroupRequest implements ISetIamPolicyInstantSnapshotGroupRequest { + + /** + * Constructs a new SetIamPolicyInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest); + + /** SetIamPolicyInstantSnapshotGroupRequest project. */ + public project: string; + + /** SetIamPolicyInstantSnapshotGroupRequest resource. */ + public resource: string; + + /** SetIamPolicyInstantSnapshotGroupRequest zone. */ + public zone: string; + + /** SetIamPolicyInstantSnapshotGroupRequest zoneSetPolicyRequestResource. */ + public zoneSetPolicyRequestResource?: (google.cloud.compute.v1beta.IZoneSetPolicyRequest|null); + + /** + * Creates a new SetIamPolicyInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns SetIamPolicyInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest): google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest; + + /** + * Encodes the specified SetIamPolicyInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest.verify|verify} messages. + * @param message SetIamPolicyInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SetIamPolicyInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest.verify|verify} messages. + * @param message SetIamPolicyInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SetIamPolicyInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SetIamPolicyInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest; + + /** + * Decodes a SetIamPolicyInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SetIamPolicyInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest; + + /** + * Verifies a SetIamPolicyInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SetIamPolicyInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SetIamPolicyInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a SetIamPolicyInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message SetIamPolicyInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SetIamPolicyInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SetIamPolicyInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a SetIamPolicyInstantSnapshotRequest. */ interface ISetIamPolicyInstantSnapshotRequest { @@ -442763,6 +448874,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a SetIamPolicyRegionInstantSnapshotGroupRequest. */ + interface ISetIamPolicyRegionInstantSnapshotGroupRequest { + + /** SetIamPolicyRegionInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** SetIamPolicyRegionInstantSnapshotGroupRequest region */ + region?: (string|null); + + /** SetIamPolicyRegionInstantSnapshotGroupRequest regionSetPolicyRequestResource */ + regionSetPolicyRequestResource?: (google.cloud.compute.v1beta.IRegionSetPolicyRequest|null); + + /** SetIamPolicyRegionInstantSnapshotGroupRequest resource */ + resource?: (string|null); + } + + /** Represents a SetIamPolicyRegionInstantSnapshotGroupRequest. */ + class SetIamPolicyRegionInstantSnapshotGroupRequest implements ISetIamPolicyRegionInstantSnapshotGroupRequest { + + /** + * Constructs a new SetIamPolicyRegionInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest); + + /** SetIamPolicyRegionInstantSnapshotGroupRequest project. */ + public project: string; + + /** SetIamPolicyRegionInstantSnapshotGroupRequest region. */ + public region: string; + + /** SetIamPolicyRegionInstantSnapshotGroupRequest regionSetPolicyRequestResource. */ + public regionSetPolicyRequestResource?: (google.cloud.compute.v1beta.IRegionSetPolicyRequest|null); + + /** SetIamPolicyRegionInstantSnapshotGroupRequest resource. */ + public resource: string; + + /** + * Creates a new SetIamPolicyRegionInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns SetIamPolicyRegionInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest): google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest; + + /** + * Encodes the specified SetIamPolicyRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message SetIamPolicyRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SetIamPolicyRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message SetIamPolicyRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SetIamPolicyRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SetIamPolicyRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest; + + /** + * Decodes a SetIamPolicyRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SetIamPolicyRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest; + + /** + * Verifies a SetIamPolicyRegionInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SetIamPolicyRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SetIamPolicyRegionInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a SetIamPolicyRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message SetIamPolicyRegionInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SetIamPolicyRegionInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SetIamPolicyRegionInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a SetIamPolicyRegionInstantSnapshotRequest. */ interface ISetIamPolicyRegionInstantSnapshotRequest { @@ -443695,6 +449921,115 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a SetIamPolicySnapshotGroupRequest. */ + interface ISetIamPolicySnapshotGroupRequest { + + /** SetIamPolicySnapshotGroupRequest globalSetPolicyRequestResource */ + globalSetPolicyRequestResource?: (google.cloud.compute.v1beta.IGlobalSetPolicyRequest|null); + + /** SetIamPolicySnapshotGroupRequest project */ + project?: (string|null); + + /** SetIamPolicySnapshotGroupRequest resource */ + resource?: (string|null); + } + + /** Represents a SetIamPolicySnapshotGroupRequest. */ + class SetIamPolicySnapshotGroupRequest implements ISetIamPolicySnapshotGroupRequest { + + /** + * Constructs a new SetIamPolicySnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest); + + /** SetIamPolicySnapshotGroupRequest globalSetPolicyRequestResource. */ + public globalSetPolicyRequestResource?: (google.cloud.compute.v1beta.IGlobalSetPolicyRequest|null); + + /** SetIamPolicySnapshotGroupRequest project. */ + public project: string; + + /** SetIamPolicySnapshotGroupRequest resource. */ + public resource: string; + + /** + * Creates a new SetIamPolicySnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns SetIamPolicySnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest): google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest; + + /** + * Encodes the specified SetIamPolicySnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest.verify|verify} messages. + * @param message SetIamPolicySnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SetIamPolicySnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest.verify|verify} messages. + * @param message SetIamPolicySnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SetIamPolicySnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SetIamPolicySnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest; + + /** + * Decodes a SetIamPolicySnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SetIamPolicySnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest; + + /** + * Verifies a SetIamPolicySnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SetIamPolicySnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SetIamPolicySnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest; + + /** + * Creates a plain object from a SetIamPolicySnapshotGroupRequest message. Also converts values to other types if specified. + * @param message SetIamPolicySnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SetIamPolicySnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SetIamPolicySnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a SetIamPolicySnapshotRequest. */ interface ISetIamPolicySnapshotRequest { @@ -452597,6 +458932,12 @@ export namespace google { /** Snapshot snapshotEncryptionKey */ snapshotEncryptionKey?: (google.cloud.compute.v1beta.ICustomerEncryptionKey|null); + /** Snapshot snapshotGroupId */ + snapshotGroupId?: (string|null); + + /** Snapshot snapshotGroupName */ + snapshotGroupName?: (string|null); + /** Snapshot snapshotType */ snapshotType?: (string|null); @@ -452727,6 +459068,12 @@ export namespace google { /** Snapshot snapshotEncryptionKey. */ public snapshotEncryptionKey?: (google.cloud.compute.v1beta.ICustomerEncryptionKey|null); + /** Snapshot snapshotGroupId. */ + public snapshotGroupId?: (string|null); + + /** Snapshot snapshotGroupName. */ + public snapshotGroupName?: (string|null); + /** Snapshot snapshotType. */ public snapshotType?: (string|null); @@ -453024,6 +459371,493 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a SnapshotGroup. */ + interface ISnapshotGroup { + + /** SnapshotGroup creationTimestamp */ + creationTimestamp?: (string|null); + + /** SnapshotGroup description */ + description?: (string|null); + + /** SnapshotGroup id */ + id?: (number|Long|string|null); + + /** SnapshotGroup kind */ + kind?: (string|null); + + /** SnapshotGroup name */ + name?: (string|null); + + /** SnapshotGroup selfLink */ + selfLink?: (string|null); + + /** SnapshotGroup selfLinkWithId */ + selfLinkWithId?: (string|null); + + /** SnapshotGroup sourceInfo */ + sourceInfo?: (google.cloud.compute.v1beta.ISnapshotGroupSourceInfo|null); + + /** SnapshotGroup sourceInstantSnapshotGroup */ + sourceInstantSnapshotGroup?: (string|null); + + /** SnapshotGroup sourceInstantSnapshotGroupInfo */ + sourceInstantSnapshotGroupInfo?: (google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo|null); + + /** SnapshotGroup status */ + status?: (string|null); + } + + /** Represents a SnapshotGroup. */ + class SnapshotGroup implements ISnapshotGroup { + + /** + * Constructs a new SnapshotGroup. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ISnapshotGroup); + + /** SnapshotGroup creationTimestamp. */ + public creationTimestamp?: (string|null); + + /** SnapshotGroup description. */ + public description?: (string|null); + + /** SnapshotGroup id. */ + public id?: (number|Long|string|null); + + /** SnapshotGroup kind. */ + public kind?: (string|null); + + /** SnapshotGroup name. */ + public name?: (string|null); + + /** SnapshotGroup selfLink. */ + public selfLink?: (string|null); + + /** SnapshotGroup selfLinkWithId. */ + public selfLinkWithId?: (string|null); + + /** SnapshotGroup sourceInfo. */ + public sourceInfo?: (google.cloud.compute.v1beta.ISnapshotGroupSourceInfo|null); + + /** SnapshotGroup sourceInstantSnapshotGroup. */ + public sourceInstantSnapshotGroup?: (string|null); + + /** SnapshotGroup sourceInstantSnapshotGroupInfo. */ + public sourceInstantSnapshotGroupInfo?: (google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo|null); + + /** SnapshotGroup status. */ + public status?: (string|null); + + /** + * Creates a new SnapshotGroup instance using the specified properties. + * @param [properties] Properties to set + * @returns SnapshotGroup instance + */ + public static create(properties?: google.cloud.compute.v1beta.ISnapshotGroup): google.cloud.compute.v1beta.SnapshotGroup; + + /** + * Encodes the specified SnapshotGroup message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroup.verify|verify} messages. + * @param message SnapshotGroup message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ISnapshotGroup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SnapshotGroup message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroup.verify|verify} messages. + * @param message SnapshotGroup message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ISnapshotGroup, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SnapshotGroup message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SnapshotGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.SnapshotGroup; + + /** + * Decodes a SnapshotGroup message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SnapshotGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.SnapshotGroup; + + /** + * Verifies a SnapshotGroup message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SnapshotGroup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SnapshotGroup + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.SnapshotGroup; + + /** + * Creates a plain object from a SnapshotGroup message. Also converts values to other types if specified. + * @param message SnapshotGroup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.SnapshotGroup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SnapshotGroup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SnapshotGroup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace SnapshotGroup { + + /** Status enum. */ + enum Status { + UNDEFINED_STATUS = 0, + CREATING = 455564985, + DELETING = 528602024, + FAILED = 455706685, + INVALID = 530283991, + READY = 77848963, + UNKNOWN = 433141802, + UPLOADING = 267603489 + } + } + + /** Properties of a SnapshotGroupParameters. */ + interface ISnapshotGroupParameters { + + /** SnapshotGroupParameters replicaZones */ + replicaZones?: (string[]|null); + + /** SnapshotGroupParameters sourceSnapshotGroup */ + sourceSnapshotGroup?: (string|null); + + /** SnapshotGroupParameters type */ + type?: (string|null); + } + + /** Represents a SnapshotGroupParameters. */ + class SnapshotGroupParameters implements ISnapshotGroupParameters { + + /** + * Constructs a new SnapshotGroupParameters. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ISnapshotGroupParameters); + + /** SnapshotGroupParameters replicaZones. */ + public replicaZones: string[]; + + /** SnapshotGroupParameters sourceSnapshotGroup. */ + public sourceSnapshotGroup?: (string|null); + + /** SnapshotGroupParameters type. */ + public type?: (string|null); + + /** + * Creates a new SnapshotGroupParameters instance using the specified properties. + * @param [properties] Properties to set + * @returns SnapshotGroupParameters instance + */ + public static create(properties?: google.cloud.compute.v1beta.ISnapshotGroupParameters): google.cloud.compute.v1beta.SnapshotGroupParameters; + + /** + * Encodes the specified SnapshotGroupParameters message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupParameters.verify|verify} messages. + * @param message SnapshotGroupParameters message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ISnapshotGroupParameters, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SnapshotGroupParameters message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupParameters.verify|verify} messages. + * @param message SnapshotGroupParameters message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ISnapshotGroupParameters, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SnapshotGroupParameters message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SnapshotGroupParameters + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.SnapshotGroupParameters; + + /** + * Decodes a SnapshotGroupParameters message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SnapshotGroupParameters + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.SnapshotGroupParameters; + + /** + * Verifies a SnapshotGroupParameters message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SnapshotGroupParameters message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SnapshotGroupParameters + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.SnapshotGroupParameters; + + /** + * Creates a plain object from a SnapshotGroupParameters message. Also converts values to other types if specified. + * @param message SnapshotGroupParameters + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.SnapshotGroupParameters, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SnapshotGroupParameters to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SnapshotGroupParameters + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SnapshotGroupSourceInfo. */ + interface ISnapshotGroupSourceInfo { + + /** SnapshotGroupSourceInfo consistencyGroup */ + consistencyGroup?: (string|null); + + /** SnapshotGroupSourceInfo consistencyGroupId */ + consistencyGroupId?: (string|null); + } + + /** Represents a SnapshotGroupSourceInfo. */ + class SnapshotGroupSourceInfo implements ISnapshotGroupSourceInfo { + + /** + * Constructs a new SnapshotGroupSourceInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ISnapshotGroupSourceInfo); + + /** SnapshotGroupSourceInfo consistencyGroup. */ + public consistencyGroup?: (string|null); + + /** SnapshotGroupSourceInfo consistencyGroupId. */ + public consistencyGroupId?: (string|null); + + /** + * Creates a new SnapshotGroupSourceInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SnapshotGroupSourceInfo instance + */ + public static create(properties?: google.cloud.compute.v1beta.ISnapshotGroupSourceInfo): google.cloud.compute.v1beta.SnapshotGroupSourceInfo; + + /** + * Encodes the specified SnapshotGroupSourceInfo message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupSourceInfo.verify|verify} messages. + * @param message SnapshotGroupSourceInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ISnapshotGroupSourceInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SnapshotGroupSourceInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupSourceInfo.verify|verify} messages. + * @param message SnapshotGroupSourceInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ISnapshotGroupSourceInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SnapshotGroupSourceInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SnapshotGroupSourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.SnapshotGroupSourceInfo; + + /** + * Decodes a SnapshotGroupSourceInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SnapshotGroupSourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.SnapshotGroupSourceInfo; + + /** + * Verifies a SnapshotGroupSourceInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SnapshotGroupSourceInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SnapshotGroupSourceInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.SnapshotGroupSourceInfo; + + /** + * Creates a plain object from a SnapshotGroupSourceInfo message. Also converts values to other types if specified. + * @param message SnapshotGroupSourceInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.SnapshotGroupSourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SnapshotGroupSourceInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SnapshotGroupSourceInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SnapshotGroupSourceInstantSnapshotGroupInfo. */ + interface ISnapshotGroupSourceInstantSnapshotGroupInfo { + + /** SnapshotGroupSourceInstantSnapshotGroupInfo instantSnapshotGroup */ + instantSnapshotGroup?: (string|null); + + /** SnapshotGroupSourceInstantSnapshotGroupInfo instantSnapshotGroupId */ + instantSnapshotGroupId?: (string|null); + } + + /** Represents a SnapshotGroupSourceInstantSnapshotGroupInfo. */ + class SnapshotGroupSourceInstantSnapshotGroupInfo implements ISnapshotGroupSourceInstantSnapshotGroupInfo { + + /** + * Constructs a new SnapshotGroupSourceInstantSnapshotGroupInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo); + + /** SnapshotGroupSourceInstantSnapshotGroupInfo instantSnapshotGroup. */ + public instantSnapshotGroup?: (string|null); + + /** SnapshotGroupSourceInstantSnapshotGroupInfo instantSnapshotGroupId. */ + public instantSnapshotGroupId?: (string|null); + + /** + * Creates a new SnapshotGroupSourceInstantSnapshotGroupInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns SnapshotGroupSourceInstantSnapshotGroupInfo instance + */ + public static create(properties?: google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo): google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo; + + /** + * Encodes the specified SnapshotGroupSourceInstantSnapshotGroupInfo message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.verify|verify} messages. + * @param message SnapshotGroupSourceInstantSnapshotGroupInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SnapshotGroupSourceInstantSnapshotGroupInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.verify|verify} messages. + * @param message SnapshotGroupSourceInstantSnapshotGroupInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SnapshotGroupSourceInstantSnapshotGroupInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SnapshotGroupSourceInstantSnapshotGroupInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo; + + /** + * Decodes a SnapshotGroupSourceInstantSnapshotGroupInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SnapshotGroupSourceInstantSnapshotGroupInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo; + + /** + * Verifies a SnapshotGroupSourceInstantSnapshotGroupInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SnapshotGroupSourceInstantSnapshotGroupInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SnapshotGroupSourceInstantSnapshotGroupInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo; + + /** + * Creates a plain object from a SnapshotGroupSourceInstantSnapshotGroupInfo message. Also converts values to other types if specified. + * @param message SnapshotGroupSourceInstantSnapshotGroupInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SnapshotGroupSourceInstantSnapshotGroupInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SnapshotGroupSourceInstantSnapshotGroupInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a SnapshotList. */ interface ISnapshotList { @@ -467211,6 +474045,9 @@ export namespace google { /** TargetVpnGateway network */ network?: (string|null); + /** TargetVpnGateway params */ + params?: (google.cloud.compute.v1beta.ITargetVpnGatewayParams|null); + /** TargetVpnGateway region */ region?: (string|null); @@ -467260,6 +474097,9 @@ export namespace google { /** TargetVpnGateway network. */ public network?: (string|null); + /** TargetVpnGateway params. */ + public params?: (google.cloud.compute.v1beta.ITargetVpnGatewayParams|null); + /** TargetVpnGateway region. */ public region?: (string|null); @@ -467622,6 +474462,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a TargetVpnGatewayParams. */ + interface ITargetVpnGatewayParams { + + /** TargetVpnGatewayParams resourceManagerTags */ + resourceManagerTags?: ({ [k: string]: string }|null); + } + + /** Represents a TargetVpnGatewayParams. */ + class TargetVpnGatewayParams implements ITargetVpnGatewayParams { + + /** + * Constructs a new TargetVpnGatewayParams. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ITargetVpnGatewayParams); + + /** TargetVpnGatewayParams resourceManagerTags. */ + public resourceManagerTags: { [k: string]: string }; + + /** + * Creates a new TargetVpnGatewayParams instance using the specified properties. + * @param [properties] Properties to set + * @returns TargetVpnGatewayParams instance + */ + public static create(properties?: google.cloud.compute.v1beta.ITargetVpnGatewayParams): google.cloud.compute.v1beta.TargetVpnGatewayParams; + + /** + * Encodes the specified TargetVpnGatewayParams message. Does not implicitly {@link google.cloud.compute.v1beta.TargetVpnGatewayParams.verify|verify} messages. + * @param message TargetVpnGatewayParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ITargetVpnGatewayParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TargetVpnGatewayParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TargetVpnGatewayParams.verify|verify} messages. + * @param message TargetVpnGatewayParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ITargetVpnGatewayParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TargetVpnGatewayParams message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TargetVpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.TargetVpnGatewayParams; + + /** + * Decodes a TargetVpnGatewayParams message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TargetVpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.TargetVpnGatewayParams; + + /** + * Verifies a TargetVpnGatewayParams message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TargetVpnGatewayParams message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetVpnGatewayParams + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.TargetVpnGatewayParams; + + /** + * Creates a plain object from a TargetVpnGatewayParams message. Also converts values to other types if specified. + * @param message TargetVpnGatewayParams + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.TargetVpnGatewayParams, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetVpnGatewayParams to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetVpnGatewayParams + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a TargetVpnGatewaysScopedList. */ interface ITargetVpnGatewaysScopedList { @@ -469759,6 +476696,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a TestIamPermissionsInstantSnapshotGroupRequest. */ + interface ITestIamPermissionsInstantSnapshotGroupRequest { + + /** TestIamPermissionsInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** TestIamPermissionsInstantSnapshotGroupRequest resource */ + resource?: (string|null); + + /** TestIamPermissionsInstantSnapshotGroupRequest testPermissionsRequestResource */ + testPermissionsRequestResource?: (google.cloud.compute.v1beta.ITestPermissionsRequest|null); + + /** TestIamPermissionsInstantSnapshotGroupRequest zone */ + zone?: (string|null); + } + + /** Represents a TestIamPermissionsInstantSnapshotGroupRequest. */ + class TestIamPermissionsInstantSnapshotGroupRequest implements ITestIamPermissionsInstantSnapshotGroupRequest { + + /** + * Constructs a new TestIamPermissionsInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest); + + /** TestIamPermissionsInstantSnapshotGroupRequest project. */ + public project: string; + + /** TestIamPermissionsInstantSnapshotGroupRequest resource. */ + public resource: string; + + /** TestIamPermissionsInstantSnapshotGroupRequest testPermissionsRequestResource. */ + public testPermissionsRequestResource?: (google.cloud.compute.v1beta.ITestPermissionsRequest|null); + + /** TestIamPermissionsInstantSnapshotGroupRequest zone. */ + public zone: string; + + /** + * Creates a new TestIamPermissionsInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns TestIamPermissionsInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest): google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest; + + /** + * Encodes the specified TestIamPermissionsInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest.verify|verify} messages. + * @param message TestIamPermissionsInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TestIamPermissionsInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest.verify|verify} messages. + * @param message TestIamPermissionsInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TestIamPermissionsInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TestIamPermissionsInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest; + + /** + * Decodes a TestIamPermissionsInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TestIamPermissionsInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest; + + /** + * Verifies a TestIamPermissionsInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TestIamPermissionsInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TestIamPermissionsInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a TestIamPermissionsInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message TestIamPermissionsInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TestIamPermissionsInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TestIamPermissionsInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a TestIamPermissionsInstantSnapshotRequest. */ interface ITestIamPermissionsInstantSnapshotRequest { @@ -472816,6 +479868,121 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a TestIamPermissionsRegionInstantSnapshotGroupRequest. */ + interface ITestIamPermissionsRegionInstantSnapshotGroupRequest { + + /** TestIamPermissionsRegionInstantSnapshotGroupRequest project */ + project?: (string|null); + + /** TestIamPermissionsRegionInstantSnapshotGroupRequest region */ + region?: (string|null); + + /** TestIamPermissionsRegionInstantSnapshotGroupRequest resource */ + resource?: (string|null); + + /** TestIamPermissionsRegionInstantSnapshotGroupRequest testPermissionsRequestResource */ + testPermissionsRequestResource?: (google.cloud.compute.v1beta.ITestPermissionsRequest|null); + } + + /** Represents a TestIamPermissionsRegionInstantSnapshotGroupRequest. */ + class TestIamPermissionsRegionInstantSnapshotGroupRequest implements ITestIamPermissionsRegionInstantSnapshotGroupRequest { + + /** + * Constructs a new TestIamPermissionsRegionInstantSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest); + + /** TestIamPermissionsRegionInstantSnapshotGroupRequest project. */ + public project: string; + + /** TestIamPermissionsRegionInstantSnapshotGroupRequest region. */ + public region: string; + + /** TestIamPermissionsRegionInstantSnapshotGroupRequest resource. */ + public resource: string; + + /** TestIamPermissionsRegionInstantSnapshotGroupRequest testPermissionsRequestResource. */ + public testPermissionsRequestResource?: (google.cloud.compute.v1beta.ITestPermissionsRequest|null); + + /** + * Creates a new TestIamPermissionsRegionInstantSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns TestIamPermissionsRegionInstantSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest): google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest; + + /** + * Encodes the specified TestIamPermissionsRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message TestIamPermissionsRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TestIamPermissionsRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @param message TestIamPermissionsRegionInstantSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TestIamPermissionsRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TestIamPermissionsRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest; + + /** + * Decodes a TestIamPermissionsRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TestIamPermissionsRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest; + + /** + * Verifies a TestIamPermissionsRegionInstantSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TestIamPermissionsRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TestIamPermissionsRegionInstantSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest; + + /** + * Creates a plain object from a TestIamPermissionsRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message TestIamPermissionsRegionInstantSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TestIamPermissionsRegionInstantSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TestIamPermissionsRegionInstantSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a TestIamPermissionsRegionInstantSnapshotRequest. */ interface ITestIamPermissionsRegionInstantSnapshotRequest { @@ -474886,6 +482053,115 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a TestIamPermissionsSnapshotGroupRequest. */ + interface ITestIamPermissionsSnapshotGroupRequest { + + /** TestIamPermissionsSnapshotGroupRequest project */ + project?: (string|null); + + /** TestIamPermissionsSnapshotGroupRequest resource */ + resource?: (string|null); + + /** TestIamPermissionsSnapshotGroupRequest testPermissionsRequestResource */ + testPermissionsRequestResource?: (google.cloud.compute.v1beta.ITestPermissionsRequest|null); + } + + /** Represents a TestIamPermissionsSnapshotGroupRequest. */ + class TestIamPermissionsSnapshotGroupRequest implements ITestIamPermissionsSnapshotGroupRequest { + + /** + * Constructs a new TestIamPermissionsSnapshotGroupRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest); + + /** TestIamPermissionsSnapshotGroupRequest project. */ + public project: string; + + /** TestIamPermissionsSnapshotGroupRequest resource. */ + public resource: string; + + /** TestIamPermissionsSnapshotGroupRequest testPermissionsRequestResource. */ + public testPermissionsRequestResource?: (google.cloud.compute.v1beta.ITestPermissionsRequest|null); + + /** + * Creates a new TestIamPermissionsSnapshotGroupRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns TestIamPermissionsSnapshotGroupRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest): google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest; + + /** + * Encodes the specified TestIamPermissionsSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest.verify|verify} messages. + * @param message TestIamPermissionsSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TestIamPermissionsSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest.verify|verify} messages. + * @param message TestIamPermissionsSnapshotGroupRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TestIamPermissionsSnapshotGroupRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TestIamPermissionsSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest; + + /** + * Decodes a TestIamPermissionsSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TestIamPermissionsSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest; + + /** + * Verifies a TestIamPermissionsSnapshotGroupRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TestIamPermissionsSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TestIamPermissionsSnapshotGroupRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest; + + /** + * Creates a plain object from a TestIamPermissionsSnapshotGroupRequest message. Also converts values to other types if specified. + * @param message TestIamPermissionsSnapshotGroupRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TestIamPermissionsSnapshotGroupRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TestIamPermissionsSnapshotGroupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a TestIamPermissionsSnapshotRequest. */ interface ITestIamPermissionsSnapshotRequest { @@ -478742,6 +486018,127 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an UpdateNamedSetRouterRequest. */ + interface IUpdateNamedSetRouterRequest { + + /** UpdateNamedSetRouterRequest namedSetResource */ + namedSetResource?: (google.cloud.compute.v1beta.INamedSet|null); + + /** UpdateNamedSetRouterRequest project */ + project?: (string|null); + + /** UpdateNamedSetRouterRequest region */ + region?: (string|null); + + /** UpdateNamedSetRouterRequest requestId */ + requestId?: (string|null); + + /** UpdateNamedSetRouterRequest router */ + router?: (string|null); + } + + /** Represents an UpdateNamedSetRouterRequest. */ + class UpdateNamedSetRouterRequest implements IUpdateNamedSetRouterRequest { + + /** + * Constructs a new UpdateNamedSetRouterRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest); + + /** UpdateNamedSetRouterRequest namedSetResource. */ + public namedSetResource?: (google.cloud.compute.v1beta.INamedSet|null); + + /** UpdateNamedSetRouterRequest project. */ + public project: string; + + /** UpdateNamedSetRouterRequest region. */ + public region: string; + + /** UpdateNamedSetRouterRequest requestId. */ + public requestId?: (string|null); + + /** UpdateNamedSetRouterRequest router. */ + public router: string; + + /** + * Creates a new UpdateNamedSetRouterRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateNamedSetRouterRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest): google.cloud.compute.v1beta.UpdateNamedSetRouterRequest; + + /** + * Encodes the specified UpdateNamedSetRouterRequest message. Does not implicitly {@link google.cloud.compute.v1beta.UpdateNamedSetRouterRequest.verify|verify} messages. + * @param message UpdateNamedSetRouterRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateNamedSetRouterRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.UpdateNamedSetRouterRequest.verify|verify} messages. + * @param message UpdateNamedSetRouterRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateNamedSetRouterRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.UpdateNamedSetRouterRequest; + + /** + * Decodes an UpdateNamedSetRouterRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.UpdateNamedSetRouterRequest; + + /** + * Verifies an UpdateNamedSetRouterRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateNamedSetRouterRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateNamedSetRouterRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.UpdateNamedSetRouterRequest; + + /** + * Creates a plain object from an UpdateNamedSetRouterRequest message. Also converts values to other types if specified. + * @param message UpdateNamedSetRouterRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.UpdateNamedSetRouterRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateNamedSetRouterRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateNamedSetRouterRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an UpdateNetworkInterfaceInstanceRequest. */ interface IUpdateNetworkInterfaceInstanceRequest { @@ -480345,6 +487742,133 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an UpdateReservationSlotRequest. */ + interface IUpdateReservationSlotRequest { + + /** UpdateReservationSlotRequest parentName */ + parentName?: (string|null); + + /** UpdateReservationSlotRequest project */ + project?: (string|null); + + /** UpdateReservationSlotRequest reservationSlot */ + reservationSlot?: (string|null); + + /** UpdateReservationSlotRequest reservationSlotResource */ + reservationSlotResource?: (google.cloud.compute.v1beta.IReservationSlot|null); + + /** UpdateReservationSlotRequest updateMask */ + updateMask?: (string|null); + + /** UpdateReservationSlotRequest zone */ + zone?: (string|null); + } + + /** Represents an UpdateReservationSlotRequest. */ + class UpdateReservationSlotRequest implements IUpdateReservationSlotRequest { + + /** + * Constructs a new UpdateReservationSlotRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IUpdateReservationSlotRequest); + + /** UpdateReservationSlotRequest parentName. */ + public parentName: string; + + /** UpdateReservationSlotRequest project. */ + public project: string; + + /** UpdateReservationSlotRequest reservationSlot. */ + public reservationSlot: string; + + /** UpdateReservationSlotRequest reservationSlotResource. */ + public reservationSlotResource?: (google.cloud.compute.v1beta.IReservationSlot|null); + + /** UpdateReservationSlotRequest updateMask. */ + public updateMask?: (string|null); + + /** UpdateReservationSlotRequest zone. */ + public zone: string; + + /** + * Creates a new UpdateReservationSlotRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateReservationSlotRequest instance + */ + public static create(properties?: google.cloud.compute.v1beta.IUpdateReservationSlotRequest): google.cloud.compute.v1beta.UpdateReservationSlotRequest; + + /** + * Encodes the specified UpdateReservationSlotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.UpdateReservationSlotRequest.verify|verify} messages. + * @param message UpdateReservationSlotRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IUpdateReservationSlotRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateReservationSlotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.UpdateReservationSlotRequest.verify|verify} messages. + * @param message UpdateReservationSlotRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IUpdateReservationSlotRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateReservationSlotRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateReservationSlotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.UpdateReservationSlotRequest; + + /** + * Decodes an UpdateReservationSlotRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateReservationSlotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.UpdateReservationSlotRequest; + + /** + * Verifies an UpdateReservationSlotRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateReservationSlotRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateReservationSlotRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.UpdateReservationSlotRequest; + + /** + * Creates a plain object from an UpdateReservationSlotRequest message. Also converts values to other types if specified. + * @param message UpdateReservationSlotRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.UpdateReservationSlotRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateReservationSlotRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateReservationSlotRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an UpdateReservationsRegionCommitmentRequest. */ interface IUpdateReservationsRegionCommitmentRequest { @@ -484767,6 +492291,9 @@ export namespace google { /** VpnGateway network */ network?: (string|null); + /** VpnGateway params */ + params?: (google.cloud.compute.v1beta.IVpnGatewayParams|null); + /** VpnGateway region */ region?: (string|null); @@ -484816,6 +492343,9 @@ export namespace google { /** VpnGateway network. */ public network?: (string|null); + /** VpnGateway params. */ + public params?: (google.cloud.compute.v1beta.IVpnGatewayParams|null); + /** VpnGateway region. */ public region?: (string|null); @@ -485184,6 +492714,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a VpnGatewayParams. */ + interface IVpnGatewayParams { + + /** VpnGatewayParams resourceManagerTags */ + resourceManagerTags?: ({ [k: string]: string }|null); + } + + /** Represents a VpnGatewayParams. */ + class VpnGatewayParams implements IVpnGatewayParams { + + /** + * Constructs a new VpnGatewayParams. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IVpnGatewayParams); + + /** VpnGatewayParams resourceManagerTags. */ + public resourceManagerTags: { [k: string]: string }; + + /** + * Creates a new VpnGatewayParams instance using the specified properties. + * @param [properties] Properties to set + * @returns VpnGatewayParams instance + */ + public static create(properties?: google.cloud.compute.v1beta.IVpnGatewayParams): google.cloud.compute.v1beta.VpnGatewayParams; + + /** + * Encodes the specified VpnGatewayParams message. Does not implicitly {@link google.cloud.compute.v1beta.VpnGatewayParams.verify|verify} messages. + * @param message VpnGatewayParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IVpnGatewayParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VpnGatewayParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.VpnGatewayParams.verify|verify} messages. + * @param message VpnGatewayParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IVpnGatewayParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VpnGatewayParams message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.VpnGatewayParams; + + /** + * Decodes a VpnGatewayParams message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.VpnGatewayParams; + + /** + * Verifies a VpnGatewayParams message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VpnGatewayParams message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VpnGatewayParams + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.VpnGatewayParams; + + /** + * Creates a plain object from a VpnGatewayParams message. Also converts values to other types if specified. + * @param message VpnGatewayParams + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.VpnGatewayParams, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VpnGatewayParams to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VpnGatewayParams + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a VpnGatewayStatus. */ interface IVpnGatewayStatus { @@ -485978,6 +493605,9 @@ export namespace google { /** VpnTunnel name */ name?: (string|null); + /** VpnTunnel params */ + params?: (google.cloud.compute.v1beta.IVpnTunnelParams|null); + /** VpnTunnel peerExternalGateway */ peerExternalGateway?: (string|null); @@ -486066,6 +493696,9 @@ export namespace google { /** VpnTunnel name. */ public name?: (string|null); + /** VpnTunnel params. */ + public params?: (google.cloud.compute.v1beta.IVpnTunnelParams|null); + /** VpnTunnel peerExternalGateway. */ public peerExternalGateway?: (string|null); @@ -486577,6 +494210,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a VpnTunnelParams. */ + interface IVpnTunnelParams { + + /** VpnTunnelParams resourceManagerTags */ + resourceManagerTags?: ({ [k: string]: string }|null); + } + + /** Represents a VpnTunnelParams. */ + class VpnTunnelParams implements IVpnTunnelParams { + + /** + * Constructs a new VpnTunnelParams. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IVpnTunnelParams); + + /** VpnTunnelParams resourceManagerTags. */ + public resourceManagerTags: { [k: string]: string }; + + /** + * Creates a new VpnTunnelParams instance using the specified properties. + * @param [properties] Properties to set + * @returns VpnTunnelParams instance + */ + public static create(properties?: google.cloud.compute.v1beta.IVpnTunnelParams): google.cloud.compute.v1beta.VpnTunnelParams; + + /** + * Encodes the specified VpnTunnelParams message. Does not implicitly {@link google.cloud.compute.v1beta.VpnTunnelParams.verify|verify} messages. + * @param message VpnTunnelParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IVpnTunnelParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VpnTunnelParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.VpnTunnelParams.verify|verify} messages. + * @param message VpnTunnelParams message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IVpnTunnelParams, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VpnTunnelParams message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VpnTunnelParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.VpnTunnelParams; + + /** + * Decodes a VpnTunnelParams message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VpnTunnelParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.VpnTunnelParams; + + /** + * Verifies a VpnTunnelParams message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VpnTunnelParams message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VpnTunnelParams + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.VpnTunnelParams; + + /** + * Creates a plain object from a VpnTunnelParams message. Also converts values to other types if specified. + * @param message VpnTunnelParams + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.VpnTunnelParams, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VpnTunnelParams to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VpnTunnelParams + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a VpnTunnelPhase1Algorithms. */ interface IVpnTunnelPhase1Algorithms { @@ -489222,6 +496952,109 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a WorkloadIdentityConfig. */ + interface IWorkloadIdentityConfig { + + /** WorkloadIdentityConfig identity */ + identity?: (string|null); + + /** WorkloadIdentityConfig identityCertificateEnabled */ + identityCertificateEnabled?: (boolean|null); + } + + /** Represents a WorkloadIdentityConfig. */ + class WorkloadIdentityConfig implements IWorkloadIdentityConfig { + + /** + * Constructs a new WorkloadIdentityConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.compute.v1beta.IWorkloadIdentityConfig); + + /** WorkloadIdentityConfig identity. */ + public identity?: (string|null); + + /** WorkloadIdentityConfig identityCertificateEnabled. */ + public identityCertificateEnabled?: (boolean|null); + + /** + * Creates a new WorkloadIdentityConfig instance using the specified properties. + * @param [properties] Properties to set + * @returns WorkloadIdentityConfig instance + */ + public static create(properties?: google.cloud.compute.v1beta.IWorkloadIdentityConfig): google.cloud.compute.v1beta.WorkloadIdentityConfig; + + /** + * Encodes the specified WorkloadIdentityConfig message. Does not implicitly {@link google.cloud.compute.v1beta.WorkloadIdentityConfig.verify|verify} messages. + * @param message WorkloadIdentityConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.compute.v1beta.IWorkloadIdentityConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WorkloadIdentityConfig message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.WorkloadIdentityConfig.verify|verify} messages. + * @param message WorkloadIdentityConfig message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.compute.v1beta.IWorkloadIdentityConfig, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WorkloadIdentityConfig message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WorkloadIdentityConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.compute.v1beta.WorkloadIdentityConfig; + + /** + * Decodes a WorkloadIdentityConfig message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WorkloadIdentityConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.compute.v1beta.WorkloadIdentityConfig; + + /** + * Verifies a WorkloadIdentityConfig message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WorkloadIdentityConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WorkloadIdentityConfig + */ + public static fromObject(object: { [k: string]: any }): google.cloud.compute.v1beta.WorkloadIdentityConfig; + + /** + * Creates a plain object from a WorkloadIdentityConfig message. Also converts values to other types if specified. + * @param message WorkloadIdentityConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.compute.v1beta.WorkloadIdentityConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WorkloadIdentityConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WorkloadIdentityConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a XpnHostList. */ interface IXpnHostList { @@ -494900,6 +502733,20 @@ export namespace google { */ public applyUpdatesToInstances(request: google.cloud.compute.v1beta.IApplyUpdatesToInstancesInstanceGroupManagerRequest): Promise; + /** + * Calls ConfigureAcceleratorTopologies. + * @param request ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public configureAcceleratorTopologies(request: google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest, callback: google.cloud.compute.v1beta.InstanceGroupManagers.ConfigureAcceleratorTopologiesCallback): void; + + /** + * Calls ConfigureAcceleratorTopologies. + * @param request ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message or plain object + * @returns Promise + */ + public configureAcceleratorTopologies(request: google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest): Promise; + /** * Calls CreateInstances. * @param request CreateInstancesInstanceGroupManagerRequest message or plain object @@ -495288,6 +503135,13 @@ export namespace google { */ type ApplyUpdatesToInstancesCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstanceGroupManagers|configureAcceleratorTopologies}. + * @param error Error, if any + * @param [response] Operation + */ + type ConfigureAcceleratorTopologiesCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + /** * Callback as used by {@link google.cloud.compute.v1beta.InstanceGroupManagers|createInstances}. * @param error Error, if any @@ -497163,6 +505017,177 @@ export namespace google { type UpdateShieldedVmConfigCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; } + /** Represents an InstantSnapshotGroups */ + class InstantSnapshotGroups extends $protobuf.rpc.Service { + + /** + * Constructs a new InstantSnapshotGroups service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new InstantSnapshotGroups service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): InstantSnapshotGroups; + + /** + * Calls Delete. + * @param request DeleteInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public delete(request: google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.InstantSnapshotGroups.DeleteCallback): void; + + /** + * Calls Delete. + * @param request DeleteInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public delete(request: google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest): Promise; + + /** + * Calls Get. + * @param request GetInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and InstantSnapshotGroup + */ + public get(request: google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.InstantSnapshotGroups.GetCallback): void; + + /** + * Calls Get. + * @param request GetInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public get(request: google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest): Promise; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public getIamPolicy(request: google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.InstantSnapshotGroups.GetIamPolicyCallback): void; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public getIamPolicy(request: google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest): Promise; + + /** + * Calls Insert. + * @param request InsertInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public insert(request: google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.InstantSnapshotGroups.InsertCallback): void; + + /** + * Calls Insert. + * @param request InsertInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public insert(request: google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest): Promise; + + /** + * Calls List. + * @param request ListInstantSnapshotGroupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListInstantSnapshotGroups + */ + public list(request: google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, callback: google.cloud.compute.v1beta.InstantSnapshotGroups.ListCallback): void; + + /** + * Calls List. + * @param request ListInstantSnapshotGroupsRequest message or plain object + * @returns Promise + */ + public list(request: google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest): Promise; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public setIamPolicy(request: google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.InstantSnapshotGroups.SetIamPolicyCallback): void; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public setIamPolicy(request: google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest): Promise; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and TestPermissionsResponse + */ + public testIamPermissions(request: google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.InstantSnapshotGroups.TestIamPermissionsCallback): void; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public testIamPermissions(request: google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest): Promise; + } + + namespace InstantSnapshotGroups { + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|delete_}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|get}. + * @param error Error, if any + * @param [response] InstantSnapshotGroup + */ + type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.InstantSnapshotGroup) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|getIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type GetIamPolicyCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Policy) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|insert}. + * @param error Error, if any + * @param [response] Operation + */ + type InsertCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|list}. + * @param error Error, if any + * @param [response] ListInstantSnapshotGroups + */ + type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.ListInstantSnapshotGroups) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|setIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type SetIamPolicyCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Policy) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|testIamPermissions}. + * @param error Error, if any + * @param [response] TestPermissionsResponse + */ + type TestIamPermissionsCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.TestPermissionsResponse) => void; + } + /** Represents an InstantSnapshots */ class InstantSnapshots extends $protobuf.rpc.Service { @@ -505440,6 +513465,177 @@ export namespace google { type BulkInsertCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; } + /** Represents a RegionInstantSnapshotGroups */ + class RegionInstantSnapshotGroups extends $protobuf.rpc.Service { + + /** + * Constructs a new RegionInstantSnapshotGroups service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new RegionInstantSnapshotGroups service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): RegionInstantSnapshotGroups; + + /** + * Calls Delete. + * @param request DeleteRegionInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public delete(request: google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.RegionInstantSnapshotGroups.DeleteCallback): void; + + /** + * Calls Delete. + * @param request DeleteRegionInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public delete(request: google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest): Promise; + + /** + * Calls Get. + * @param request GetRegionInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and InstantSnapshotGroup + */ + public get(request: google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.RegionInstantSnapshotGroups.GetCallback): void; + + /** + * Calls Get. + * @param request GetRegionInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public get(request: google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest): Promise; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRegionInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public getIamPolicy(request: google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.RegionInstantSnapshotGroups.GetIamPolicyCallback): void; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicyRegionInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public getIamPolicy(request: google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest): Promise; + + /** + * Calls Insert. + * @param request InsertRegionInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public insert(request: google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.RegionInstantSnapshotGroups.InsertCallback): void; + + /** + * Calls Insert. + * @param request InsertRegionInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public insert(request: google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest): Promise; + + /** + * Calls List. + * @param request ListRegionInstantSnapshotGroupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListInstantSnapshotGroups + */ + public list(request: google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, callback: google.cloud.compute.v1beta.RegionInstantSnapshotGroups.ListCallback): void; + + /** + * Calls List. + * @param request ListRegionInstantSnapshotGroupsRequest message or plain object + * @returns Promise + */ + public list(request: google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest): Promise; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRegionInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public setIamPolicy(request: google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.RegionInstantSnapshotGroups.SetIamPolicyCallback): void; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicyRegionInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public setIamPolicy(request: google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest): Promise; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRegionInstantSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and TestPermissionsResponse + */ + public testIamPermissions(request: google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest, callback: google.cloud.compute.v1beta.RegionInstantSnapshotGroups.TestIamPermissionsCallback): void; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsRegionInstantSnapshotGroupRequest message or plain object + * @returns Promise + */ + public testIamPermissions(request: google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest): Promise; + } + + namespace RegionInstantSnapshotGroups { + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|delete_}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|get}. + * @param error Error, if any + * @param [response] InstantSnapshotGroup + */ + type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.InstantSnapshotGroup) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|getIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type GetIamPolicyCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Policy) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|insert}. + * @param error Error, if any + * @param [response] Operation + */ + type InsertCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|list}. + * @param error Error, if any + * @param [response] ListInstantSnapshotGroups + */ + type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.ListInstantSnapshotGroups) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|setIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type SetIamPolicyCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Policy) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|testIamPermissions}. + * @param error Error, if any + * @param [response] TestPermissionsResponse + */ + type TestIamPermissionsCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.TestPermissionsResponse) => void; + } + /** Represents a RegionInstantSnapshots */ class RegionInstantSnapshots extends $protobuf.rpc.Service { @@ -508650,6 +516846,93 @@ export namespace google { type TestIamPermissionsCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.TestPermissionsResponse) => void; } + /** Represents a ReservationSlots */ + class ReservationSlots extends $protobuf.rpc.Service { + + /** + * Constructs a new ReservationSlots service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new ReservationSlots service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): ReservationSlots; + + /** + * Calls Get. + * @param request GetReservationSlotRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ReservationSlotsGetResponse + */ + public get(request: google.cloud.compute.v1beta.IGetReservationSlotRequest, callback: google.cloud.compute.v1beta.ReservationSlots.GetCallback): void; + + /** + * Calls Get. + * @param request GetReservationSlotRequest message or plain object + * @returns Promise + */ + public get(request: google.cloud.compute.v1beta.IGetReservationSlotRequest): Promise; + + /** + * Calls List. + * @param request ListReservationSlotsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ReservationSlotsListResponse + */ + public list(request: google.cloud.compute.v1beta.IListReservationSlotsRequest, callback: google.cloud.compute.v1beta.ReservationSlots.ListCallback): void; + + /** + * Calls List. + * @param request ListReservationSlotsRequest message or plain object + * @returns Promise + */ + public list(request: google.cloud.compute.v1beta.IListReservationSlotsRequest): Promise; + + /** + * Calls Update. + * @param request UpdateReservationSlotRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public update(request: google.cloud.compute.v1beta.IUpdateReservationSlotRequest, callback: google.cloud.compute.v1beta.ReservationSlots.UpdateCallback): void; + + /** + * Calls Update. + * @param request UpdateReservationSlotRequest message or plain object + * @returns Promise + */ + public update(request: google.cloud.compute.v1beta.IUpdateReservationSlotRequest): Promise; + } + + namespace ReservationSlots { + + /** + * Callback as used by {@link google.cloud.compute.v1beta.ReservationSlots|get}. + * @param error Error, if any + * @param [response] ReservationSlotsGetResponse + */ + type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.ReservationSlotsGetResponse) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.ReservationSlots|list}. + * @param error Error, if any + * @param [response] ReservationSlotsListResponse + */ + type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.ReservationSlotsListResponse) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.ReservationSlots|update}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + } + /** Represents a ReservationSubBlocks */ class ReservationSubBlocks extends $protobuf.rpc.Service { @@ -509553,6 +517836,20 @@ export namespace google { */ public delete(request: google.cloud.compute.v1beta.IDeleteRouterRequest): Promise; + /** + * Calls DeleteNamedSet. + * @param request DeleteNamedSetRouterRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public deleteNamedSet(request: google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest, callback: google.cloud.compute.v1beta.Routers.DeleteNamedSetCallback): void; + + /** + * Calls DeleteNamedSet. + * @param request DeleteNamedSetRouterRequest message or plain object + * @returns Promise + */ + public deleteNamedSet(request: google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest): Promise; + /** * Calls DeleteRoutePolicy. * @param request DeleteRoutePolicyRouterRequest message or plain object @@ -509581,6 +517878,20 @@ export namespace google { */ public get(request: google.cloud.compute.v1beta.IGetRouterRequest): Promise; + /** + * Calls GetNamedSet. + * @param request GetNamedSetRouterRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RoutersGetNamedSetResponse + */ + public getNamedSet(request: google.cloud.compute.v1beta.IGetNamedSetRouterRequest, callback: google.cloud.compute.v1beta.Routers.GetNamedSetCallback): void; + + /** + * Calls GetNamedSet. + * @param request GetNamedSetRouterRequest message or plain object + * @returns Promise + */ + public getNamedSet(request: google.cloud.compute.v1beta.IGetNamedSetRouterRequest): Promise; + /** * Calls GetNatIpInfo. * @param request GetNatIpInfoRouterRequest message or plain object @@ -509679,6 +517990,20 @@ export namespace google { */ public listBgpRoutes(request: google.cloud.compute.v1beta.IListBgpRoutesRoutersRequest): Promise; + /** + * Calls ListNamedSets. + * @param request ListNamedSetsRoutersRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RoutersListNamedSets + */ + public listNamedSets(request: google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, callback: google.cloud.compute.v1beta.Routers.ListNamedSetsCallback): void; + + /** + * Calls ListNamedSets. + * @param request ListNamedSetsRoutersRequest message or plain object + * @returns Promise + */ + public listNamedSets(request: google.cloud.compute.v1beta.IListNamedSetsRoutersRequest): Promise; + /** * Calls ListRoutePolicies. * @param request ListRoutePoliciesRoutersRequest message or plain object @@ -509707,6 +518032,20 @@ export namespace google { */ public patch(request: google.cloud.compute.v1beta.IPatchRouterRequest): Promise; + /** + * Calls PatchNamedSet. + * @param request PatchNamedSetRouterRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public patchNamedSet(request: google.cloud.compute.v1beta.IPatchNamedSetRouterRequest, callback: google.cloud.compute.v1beta.Routers.PatchNamedSetCallback): void; + + /** + * Calls PatchNamedSet. + * @param request PatchNamedSetRouterRequest message or plain object + * @returns Promise + */ + public patchNamedSet(request: google.cloud.compute.v1beta.IPatchNamedSetRouterRequest): Promise; + /** * Calls PatchRoutePolicy. * @param request PatchRoutePolicyRouterRequest message or plain object @@ -509763,6 +518102,20 @@ export namespace google { */ public update(request: google.cloud.compute.v1beta.IUpdateRouterRequest): Promise; + /** + * Calls UpdateNamedSet. + * @param request UpdateNamedSetRouterRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateNamedSet(request: google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest, callback: google.cloud.compute.v1beta.Routers.UpdateNamedSetCallback): void; + + /** + * Calls UpdateNamedSet. + * @param request UpdateNamedSetRouterRequest message or plain object + * @returns Promise + */ + public updateNamedSet(request: google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest): Promise; + /** * Calls UpdateRoutePolicy. * @param request UpdateRoutePolicyRouterRequest message or plain object @@ -509794,6 +518147,13 @@ export namespace google { */ type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|deleteNamedSet}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteNamedSetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|deleteRoutePolicy}. * @param error Error, if any @@ -509808,6 +518168,13 @@ export namespace google { */ type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Router) => void; + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|getNamedSet}. + * @param error Error, if any + * @param [response] RoutersGetNamedSetResponse + */ + type GetNamedSetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.RoutersGetNamedSetResponse) => void; + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|getNatIpInfo}. * @param error Error, if any @@ -509857,6 +518224,13 @@ export namespace google { */ type ListBgpRoutesCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.RoutersListBgpRoutes) => void; + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|listNamedSets}. + * @param error Error, if any + * @param [response] RoutersListNamedSets + */ + type ListNamedSetsCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.RoutersListNamedSets) => void; + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|listRoutePolicies}. * @param error Error, if any @@ -509871,6 +518245,13 @@ export namespace google { */ type PatchCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|patchNamedSet}. + * @param error Error, if any + * @param [response] Operation + */ + type PatchNamedSetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|patchRoutePolicy}. * @param error Error, if any @@ -509899,6 +518280,13 @@ export namespace google { */ type UpdateCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|updateNamedSet}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateNamedSetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|updateRoutePolicy}. * @param error Error, if any @@ -510546,6 +518934,177 @@ export namespace google { type TestIamPermissionsCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.TestPermissionsResponse) => void; } + /** Represents a SnapshotGroups */ + class SnapshotGroups extends $protobuf.rpc.Service { + + /** + * Constructs a new SnapshotGroups service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Creates new SnapshotGroups service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): SnapshotGroups; + + /** + * Calls Delete. + * @param request DeleteSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public delete(request: google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest, callback: google.cloud.compute.v1beta.SnapshotGroups.DeleteCallback): void; + + /** + * Calls Delete. + * @param request DeleteSnapshotGroupRequest message or plain object + * @returns Promise + */ + public delete(request: google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest): Promise; + + /** + * Calls Get. + * @param request GetSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and SnapshotGroup + */ + public get(request: google.cloud.compute.v1beta.IGetSnapshotGroupRequest, callback: google.cloud.compute.v1beta.SnapshotGroups.GetCallback): void; + + /** + * Calls Get. + * @param request GetSnapshotGroupRequest message or plain object + * @returns Promise + */ + public get(request: google.cloud.compute.v1beta.IGetSnapshotGroupRequest): Promise; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicySnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public getIamPolicy(request: google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest, callback: google.cloud.compute.v1beta.SnapshotGroups.GetIamPolicyCallback): void; + + /** + * Calls GetIamPolicy. + * @param request GetIamPolicySnapshotGroupRequest message or plain object + * @returns Promise + */ + public getIamPolicy(request: google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest): Promise; + + /** + * Calls Insert. + * @param request InsertSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public insert(request: google.cloud.compute.v1beta.IInsertSnapshotGroupRequest, callback: google.cloud.compute.v1beta.SnapshotGroups.InsertCallback): void; + + /** + * Calls Insert. + * @param request InsertSnapshotGroupRequest message or plain object + * @returns Promise + */ + public insert(request: google.cloud.compute.v1beta.IInsertSnapshotGroupRequest): Promise; + + /** + * Calls List. + * @param request ListSnapshotGroupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListSnapshotGroups + */ + public list(request: google.cloud.compute.v1beta.IListSnapshotGroupsRequest, callback: google.cloud.compute.v1beta.SnapshotGroups.ListCallback): void; + + /** + * Calls List. + * @param request ListSnapshotGroupsRequest message or plain object + * @returns Promise + */ + public list(request: google.cloud.compute.v1beta.IListSnapshotGroupsRequest): Promise; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicySnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Policy + */ + public setIamPolicy(request: google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest, callback: google.cloud.compute.v1beta.SnapshotGroups.SetIamPolicyCallback): void; + + /** + * Calls SetIamPolicy. + * @param request SetIamPolicySnapshotGroupRequest message or plain object + * @returns Promise + */ + public setIamPolicy(request: google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest): Promise; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsSnapshotGroupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and TestPermissionsResponse + */ + public testIamPermissions(request: google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest, callback: google.cloud.compute.v1beta.SnapshotGroups.TestIamPermissionsCallback): void; + + /** + * Calls TestIamPermissions. + * @param request TestIamPermissionsSnapshotGroupRequest message or plain object + * @returns Promise + */ + public testIamPermissions(request: google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest): Promise; + } + + namespace SnapshotGroups { + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|delete_}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|get}. + * @param error Error, if any + * @param [response] SnapshotGroup + */ + type GetCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.SnapshotGroup) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|getIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type GetIamPolicyCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Policy) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|insert}. + * @param error Error, if any + * @param [response] Operation + */ + type InsertCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Operation) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|list}. + * @param error Error, if any + * @param [response] ListSnapshotGroups + */ + type ListCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.ListSnapshotGroups) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|setIamPolicy}. + * @param error Error, if any + * @param [response] Policy + */ + type SetIamPolicyCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.Policy) => void; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|testIamPermissions}. + * @param error Error, if any + * @param [response] TestPermissionsResponse + */ + type TestIamPermissionsCallback = (error: (Error|null), response?: google.cloud.compute.v1beta.TestPermissionsResponse) => void; + } + /** Represents a SnapshotSettingsService */ class SnapshotSettingsService extends $protobuf.rpc.Service { diff --git a/packages/google-cloud-compute/protos/protos.js b/packages/google-cloud-compute/protos/protos.js index 1ebf99b08a1..ba409bccf9d 100644 --- a/packages/google-cloud-compute/protos/protos.js +++ b/packages/google-cloud-compute/protos/protos.js @@ -700841,6 +700841,7 @@ * @property {number|null} [maxRatePerEndpoint] Backend maxRatePerEndpoint * @property {number|null} [maxRatePerInstance] Backend maxRatePerInstance * @property {number|null} [maxUtilization] Backend maxUtilization + * @property {google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo|null} [orchestrationInfo] Backend orchestrationInfo * @property {string|null} [preference] Backend preference * @property {string|null} [trafficDuration] Backend trafficDuration */ @@ -700989,6 +700990,14 @@ */ Backend.prototype.maxUtilization = null; + /** + * Backend orchestrationInfo. + * @member {google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo|null|undefined} orchestrationInfo + * @memberof google.cloud.compute.v1beta.Backend + * @instance + */ + Backend.prototype.orchestrationInfo = null; + /** * Backend preference. * @member {string|null|undefined} preference @@ -701098,6 +701107,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(Backend.prototype, "_orchestrationInfo", { + get: $util.oneOfGetter($oneOfFields = ["orchestrationInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(Backend.prototype, "_preference", { get: $util.oneOfGetter($oneOfFields = ["preference"]), @@ -701171,6 +701186,8 @@ $root.google.cloud.compute.v1beta.BackendCustomMetric.encode(message.customMetrics[i], writer.uint32(/* id 429453813, wireType 2 =*/3435630506).fork()).ldelim(); if (message.balancingMode != null && Object.hasOwnProperty.call(message, "balancingMode")) writer.uint32(/* id 430286217, wireType 2 =*/3442289738).string(message.balancingMode); + if (message.orchestrationInfo != null && Object.hasOwnProperty.call(message, "orchestrationInfo")) + $root.google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.encode(message.orchestrationInfo, writer.uint32(/* id 441144300, wireType 2 =*/3529154402).fork()).ldelim(); return writer; }; @@ -701273,6 +701290,10 @@ message.maxUtilization = reader.float(); break; } + case 441144300: { + message.orchestrationInfo = $root.google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.decode(reader, reader.uint32()); + break; + } case 150781147: { message.preference = reader.string(); break; @@ -701401,6 +701422,14 @@ if (typeof message.maxUtilization !== "number") return "maxUtilization: number expected"; } + if (message.orchestrationInfo != null && message.hasOwnProperty("orchestrationInfo")) { + properties._orchestrationInfo = 1; + { + var error = $root.google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.verify(message.orchestrationInfo); + if (error) + return "orchestrationInfo." + error; + } + } if (message.preference != null && message.hasOwnProperty("preference")) { properties._preference = 1; if (!$util.isString(message.preference)) @@ -701466,6 +701495,11 @@ message.maxRatePerInstance = Number(object.maxRatePerInstance); if (object.maxUtilization != null) message.maxUtilization = Number(object.maxUtilization); + if (object.orchestrationInfo != null) { + if (typeof object.orchestrationInfo !== "object") + throw TypeError(".google.cloud.compute.v1beta.Backend.orchestrationInfo: object expected"); + message.orchestrationInfo = $root.google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.fromObject(object.orchestrationInfo); + } if (object.preference != null) message.preference = String(object.preference); if (object.trafficDuration != null) @@ -701578,6 +701612,11 @@ if (options.oneofs) object._balancingMode = "balancingMode"; } + if (message.orchestrationInfo != null && message.hasOwnProperty("orchestrationInfo")) { + object.orchestrationInfo = $root.google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.toObject(message.orchestrationInfo, options); + if (options.oneofs) + object._orchestrationInfo = "orchestrationInfo"; + } return object; }; @@ -701668,6 +701707,224 @@ return Backend; })(); + v1beta.BackendBackendOrchestrationInfo = (function() { + + /** + * Properties of a BackendBackendOrchestrationInfo. + * @memberof google.cloud.compute.v1beta + * @interface IBackendBackendOrchestrationInfo + * @property {string|null} [resourceUri] BackendBackendOrchestrationInfo resourceUri + */ + + /** + * Constructs a new BackendBackendOrchestrationInfo. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a BackendBackendOrchestrationInfo. + * @implements IBackendBackendOrchestrationInfo + * @constructor + * @param {google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo=} [properties] Properties to set + */ + function BackendBackendOrchestrationInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BackendBackendOrchestrationInfo resourceUri. + * @member {string|null|undefined} resourceUri + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @instance + */ + BackendBackendOrchestrationInfo.prototype.resourceUri = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(BackendBackendOrchestrationInfo.prototype, "_resourceUri", { + get: $util.oneOfGetter($oneOfFields = ["resourceUri"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new BackendBackendOrchestrationInfo instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.BackendBackendOrchestrationInfo} BackendBackendOrchestrationInfo instance + */ + BackendBackendOrchestrationInfo.create = function create(properties) { + return new BackendBackendOrchestrationInfo(properties); + }; + + /** + * Encodes the specified BackendBackendOrchestrationInfo message. Does not implicitly {@link google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo} message BackendBackendOrchestrationInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackendBackendOrchestrationInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceUri != null && Object.hasOwnProperty.call(message, "resourceUri")) + writer.uint32(/* id 152830395, wireType 2 =*/1222643162).string(message.resourceUri); + return writer; + }; + + /** + * Encodes the specified BackendBackendOrchestrationInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.BackendBackendOrchestrationInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {google.cloud.compute.v1beta.IBackendBackendOrchestrationInfo} message BackendBackendOrchestrationInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackendBackendOrchestrationInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BackendBackendOrchestrationInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.BackendBackendOrchestrationInfo} BackendBackendOrchestrationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackendBackendOrchestrationInfo.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.cloud.compute.v1beta.BackendBackendOrchestrationInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 152830395: { + message.resourceUri = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BackendBackendOrchestrationInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.BackendBackendOrchestrationInfo} BackendBackendOrchestrationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackendBackendOrchestrationInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BackendBackendOrchestrationInfo message. + * @function verify + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BackendBackendOrchestrationInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.resourceUri != null && message.hasOwnProperty("resourceUri")) { + properties._resourceUri = 1; + if (!$util.isString(message.resourceUri)) + return "resourceUri: string expected"; + } + return null; + }; + + /** + * Creates a BackendBackendOrchestrationInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.BackendBackendOrchestrationInfo} BackendBackendOrchestrationInfo + */ + BackendBackendOrchestrationInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.BackendBackendOrchestrationInfo) + return object; + var message = new $root.google.cloud.compute.v1beta.BackendBackendOrchestrationInfo(); + if (object.resourceUri != null) + message.resourceUri = String(object.resourceUri); + return message; + }; + + /** + * Creates a plain object from a BackendBackendOrchestrationInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {google.cloud.compute.v1beta.BackendBackendOrchestrationInfo} message BackendBackendOrchestrationInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BackendBackendOrchestrationInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.resourceUri != null && message.hasOwnProperty("resourceUri")) { + object.resourceUri = message.resourceUri; + if (options.oneofs) + object._resourceUri = "resourceUri"; + } + return object; + }; + + /** + * Converts this BackendBackendOrchestrationInfo to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @instance + * @returns {Object.} JSON object + */ + BackendBackendOrchestrationInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BackendBackendOrchestrationInfo + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.BackendBackendOrchestrationInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BackendBackendOrchestrationInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.BackendBackendOrchestrationInfo"; + }; + + return BackendBackendOrchestrationInfo; + })(); + v1beta.BackendBucket = (function() { /** @@ -706107,6 +706364,7 @@ * @property {string|null} [name] BackendService name * @property {string|null} [network] BackendService network * @property {google.cloud.compute.v1beta.IBackendServiceNetworkPassThroughLbTrafficPolicy|null} [networkPassThroughLbTrafficPolicy] BackendService networkPassThroughLbTrafficPolicy + * @property {google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo|null} [orchestrationInfo] BackendService orchestrationInfo * @property {google.cloud.compute.v1beta.IOutlierDetection|null} [outlierDetection] BackendService outlierDetection * @property {google.cloud.compute.v1beta.IBackendServiceParams|null} [params] BackendService params * @property {number|null} [port] BackendService port @@ -706430,6 +706688,14 @@ */ BackendService.prototype.networkPassThroughLbTrafficPolicy = null; + /** + * BackendService orchestrationInfo. + * @member {google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo|null|undefined} orchestrationInfo + * @memberof google.cloud.compute.v1beta.BackendService + * @instance + */ + BackendService.prototype.orchestrationInfo = null; + /** * BackendService outlierDetection. * @member {google.cloud.compute.v1beta.IOutlierDetection|null|undefined} outlierDetection @@ -706737,6 +707003,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(BackendService.prototype, "_orchestrationInfo", { + get: $util.oneOfGetter($oneOfFields = ["orchestrationInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(BackendService.prototype, "_outlierDetection", { get: $util.oneOfGetter($oneOfFields = ["outlierDetection"]), @@ -706944,6 +707216,8 @@ if (message.customMetrics != null && message.customMetrics.length) for (var i = 0; i < message.customMetrics.length; ++i) $root.google.cloud.compute.v1beta.BackendServiceCustomMetric.encode(message.customMetrics[i], writer.uint32(/* id 429453813, wireType 2 =*/3435630506).fork()).ldelim(); + if (message.orchestrationInfo != null && Object.hasOwnProperty.call(message, "orchestrationInfo")) + $root.google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.encode(message.orchestrationInfo, writer.uint32(/* id 441144300, wireType 2 =*/3529154402).fork()).ldelim(); if (message.healthChecks != null && message.healthChecks.length) for (var i = 0; i < message.healthChecks.length; ++i) writer.uint32(/* id 448370606, wireType 2 =*/3586964850).string(message.healthChecks[i]); @@ -707171,6 +707445,10 @@ message.networkPassThroughLbTrafficPolicy = $root.google.cloud.compute.v1beta.BackendServiceNetworkPassThroughLbTrafficPolicy.decode(reader, reader.uint32()); break; } + case 441144300: { + message.orchestrationInfo = $root.google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.decode(reader, reader.uint32()); + break; + } case 354625086: { message.outlierDetection = $root.google.cloud.compute.v1beta.OutlierDetection.decode(reader, reader.uint32()); break; @@ -707511,6 +707789,14 @@ return "networkPassThroughLbTrafficPolicy." + error; } } + if (message.orchestrationInfo != null && message.hasOwnProperty("orchestrationInfo")) { + properties._orchestrationInfo = 1; + { + var error = $root.google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.verify(message.orchestrationInfo); + if (error) + return "orchestrationInfo." + error; + } + } if (message.outlierDetection != null && message.hasOwnProperty("outlierDetection")) { properties._outlierDetection = 1; { @@ -707792,6 +708078,11 @@ throw TypeError(".google.cloud.compute.v1beta.BackendService.networkPassThroughLbTrafficPolicy: object expected"); message.networkPassThroughLbTrafficPolicy = $root.google.cloud.compute.v1beta.BackendServiceNetworkPassThroughLbTrafficPolicy.fromObject(object.networkPassThroughLbTrafficPolicy); } + if (object.orchestrationInfo != null) { + if (typeof object.orchestrationInfo !== "object") + throw TypeError(".google.cloud.compute.v1beta.BackendService.orchestrationInfo: object expected"); + message.orchestrationInfo = $root.google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.fromObject(object.orchestrationInfo); + } if (object.outlierDetection != null) { if (typeof object.outlierDetection !== "object") throw TypeError(".google.cloud.compute.v1beta.BackendService.outlierDetection: object expected"); @@ -708104,6 +708395,11 @@ for (var j = 0; j < message.customMetrics.length; ++j) object.customMetrics[j] = $root.google.cloud.compute.v1beta.BackendServiceCustomMetric.toObject(message.customMetrics[j], options); } + if (message.orchestrationInfo != null && message.hasOwnProperty("orchestrationInfo")) { + object.orchestrationInfo = $root.google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.toObject(message.orchestrationInfo, options); + if (options.oneofs) + object._orchestrationInfo = "orchestrationInfo"; + } if (message.healthChecks && message.healthChecks.length) { object.healthChecks = []; for (var j = 0; j < message.healthChecks.length; ++j) @@ -715337,6 +715633,224 @@ return BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity; })(); + v1beta.BackendServiceOrchestrationInfo = (function() { + + /** + * Properties of a BackendServiceOrchestrationInfo. + * @memberof google.cloud.compute.v1beta + * @interface IBackendServiceOrchestrationInfo + * @property {string|null} [resourceUri] BackendServiceOrchestrationInfo resourceUri + */ + + /** + * Constructs a new BackendServiceOrchestrationInfo. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a BackendServiceOrchestrationInfo. + * @implements IBackendServiceOrchestrationInfo + * @constructor + * @param {google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo=} [properties] Properties to set + */ + function BackendServiceOrchestrationInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BackendServiceOrchestrationInfo resourceUri. + * @member {string|null|undefined} resourceUri + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @instance + */ + BackendServiceOrchestrationInfo.prototype.resourceUri = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(BackendServiceOrchestrationInfo.prototype, "_resourceUri", { + get: $util.oneOfGetter($oneOfFields = ["resourceUri"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new BackendServiceOrchestrationInfo instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.BackendServiceOrchestrationInfo} BackendServiceOrchestrationInfo instance + */ + BackendServiceOrchestrationInfo.create = function create(properties) { + return new BackendServiceOrchestrationInfo(properties); + }; + + /** + * Encodes the specified BackendServiceOrchestrationInfo message. Does not implicitly {@link google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo} message BackendServiceOrchestrationInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackendServiceOrchestrationInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceUri != null && Object.hasOwnProperty.call(message, "resourceUri")) + writer.uint32(/* id 152830395, wireType 2 =*/1222643162).string(message.resourceUri); + return writer; + }; + + /** + * Encodes the specified BackendServiceOrchestrationInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.BackendServiceOrchestrationInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {google.cloud.compute.v1beta.IBackendServiceOrchestrationInfo} message BackendServiceOrchestrationInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BackendServiceOrchestrationInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BackendServiceOrchestrationInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.BackendServiceOrchestrationInfo} BackendServiceOrchestrationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackendServiceOrchestrationInfo.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.cloud.compute.v1beta.BackendServiceOrchestrationInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 152830395: { + message.resourceUri = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a BackendServiceOrchestrationInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.BackendServiceOrchestrationInfo} BackendServiceOrchestrationInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BackendServiceOrchestrationInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BackendServiceOrchestrationInfo message. + * @function verify + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BackendServiceOrchestrationInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.resourceUri != null && message.hasOwnProperty("resourceUri")) { + properties._resourceUri = 1; + if (!$util.isString(message.resourceUri)) + return "resourceUri: string expected"; + } + return null; + }; + + /** + * Creates a BackendServiceOrchestrationInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.BackendServiceOrchestrationInfo} BackendServiceOrchestrationInfo + */ + BackendServiceOrchestrationInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.BackendServiceOrchestrationInfo) + return object; + var message = new $root.google.cloud.compute.v1beta.BackendServiceOrchestrationInfo(); + if (object.resourceUri != null) + message.resourceUri = String(object.resourceUri); + return message; + }; + + /** + * Creates a plain object from a BackendServiceOrchestrationInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {google.cloud.compute.v1beta.BackendServiceOrchestrationInfo} message BackendServiceOrchestrationInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BackendServiceOrchestrationInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.resourceUri != null && message.hasOwnProperty("resourceUri")) { + object.resourceUri = message.resourceUri; + if (options.oneofs) + object._resourceUri = "resourceUri"; + } + return object; + }; + + /** + * Converts this BackendServiceOrchestrationInfo to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @instance + * @returns {Object.} JSON object + */ + BackendServiceOrchestrationInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BackendServiceOrchestrationInfo + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.BackendServiceOrchestrationInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BackendServiceOrchestrationInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.BackendServiceOrchestrationInfo"; + }; + + return BackendServiceOrchestrationInfo; + })(); + v1beta.BackendServiceParams = (function() { /** @@ -720413,6 +720927,8 @@ * Properties of a BulkInsertDiskResource. * @memberof google.cloud.compute.v1beta * @interface IBulkInsertDiskResource + * @property {google.cloud.compute.v1beta.IInstantSnapshotGroupParameters|null} [instantSnapshotGroupParameters] BulkInsertDiskResource instantSnapshotGroupParameters + * @property {google.cloud.compute.v1beta.ISnapshotGroupParameters|null} [snapshotGroupParameters] BulkInsertDiskResource snapshotGroupParameters * @property {string|null} [sourceConsistencyGroupPolicy] BulkInsertDiskResource sourceConsistencyGroupPolicy */ @@ -720431,6 +720947,22 @@ this[keys[i]] = properties[keys[i]]; } + /** + * BulkInsertDiskResource instantSnapshotGroupParameters. + * @member {google.cloud.compute.v1beta.IInstantSnapshotGroupParameters|null|undefined} instantSnapshotGroupParameters + * @memberof google.cloud.compute.v1beta.BulkInsertDiskResource + * @instance + */ + BulkInsertDiskResource.prototype.instantSnapshotGroupParameters = null; + + /** + * BulkInsertDiskResource snapshotGroupParameters. + * @member {google.cloud.compute.v1beta.ISnapshotGroupParameters|null|undefined} snapshotGroupParameters + * @memberof google.cloud.compute.v1beta.BulkInsertDiskResource + * @instance + */ + BulkInsertDiskResource.prototype.snapshotGroupParameters = null; + /** * BulkInsertDiskResource sourceConsistencyGroupPolicy. * @member {string|null|undefined} sourceConsistencyGroupPolicy @@ -720442,6 +720974,18 @@ // OneOf field names bound to virtual getters and setters var $oneOfFields; + // Virtual OneOf for proto3 optional field + Object.defineProperty(BulkInsertDiskResource.prototype, "_instantSnapshotGroupParameters", { + get: $util.oneOfGetter($oneOfFields = ["instantSnapshotGroupParameters"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(BulkInsertDiskResource.prototype, "_snapshotGroupParameters", { + get: $util.oneOfGetter($oneOfFields = ["snapshotGroupParameters"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(BulkInsertDiskResource.prototype, "_sourceConsistencyGroupPolicy", { get: $util.oneOfGetter($oneOfFields = ["sourceConsistencyGroupPolicy"]), @@ -720472,8 +721016,12 @@ BulkInsertDiskResource.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); + if (message.instantSnapshotGroupParameters != null && Object.hasOwnProperty.call(message, "instantSnapshotGroupParameters")) + $root.google.cloud.compute.v1beta.InstantSnapshotGroupParameters.encode(message.instantSnapshotGroupParameters, writer.uint32(/* id 17051623, wireType 2 =*/136412986).fork()).ldelim(); if (message.sourceConsistencyGroupPolicy != null && Object.hasOwnProperty.call(message, "sourceConsistencyGroupPolicy")) writer.uint32(/* id 19616093, wireType 2 =*/156928746).string(message.sourceConsistencyGroupPolicy); + if (message.snapshotGroupParameters != null && Object.hasOwnProperty.call(message, "snapshotGroupParameters")) + $root.google.cloud.compute.v1beta.SnapshotGroupParameters.encode(message.snapshotGroupParameters, writer.uint32(/* id 42252485, wireType 2 =*/338019882).fork()).ldelim(); return writer; }; @@ -720510,6 +721058,14 @@ if (tag === error) break; switch (tag >>> 3) { + case 17051623: { + message.instantSnapshotGroupParameters = $root.google.cloud.compute.v1beta.InstantSnapshotGroupParameters.decode(reader, reader.uint32()); + break; + } + case 42252485: { + message.snapshotGroupParameters = $root.google.cloud.compute.v1beta.SnapshotGroupParameters.decode(reader, reader.uint32()); + break; + } case 19616093: { message.sourceConsistencyGroupPolicy = reader.string(); break; @@ -720550,6 +721106,22 @@ if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; + if (message.instantSnapshotGroupParameters != null && message.hasOwnProperty("instantSnapshotGroupParameters")) { + properties._instantSnapshotGroupParameters = 1; + { + var error = $root.google.cloud.compute.v1beta.InstantSnapshotGroupParameters.verify(message.instantSnapshotGroupParameters); + if (error) + return "instantSnapshotGroupParameters." + error; + } + } + if (message.snapshotGroupParameters != null && message.hasOwnProperty("snapshotGroupParameters")) { + properties._snapshotGroupParameters = 1; + { + var error = $root.google.cloud.compute.v1beta.SnapshotGroupParameters.verify(message.snapshotGroupParameters); + if (error) + return "snapshotGroupParameters." + error; + } + } if (message.sourceConsistencyGroupPolicy != null && message.hasOwnProperty("sourceConsistencyGroupPolicy")) { properties._sourceConsistencyGroupPolicy = 1; if (!$util.isString(message.sourceConsistencyGroupPolicy)) @@ -720570,6 +721142,16 @@ if (object instanceof $root.google.cloud.compute.v1beta.BulkInsertDiskResource) return object; var message = new $root.google.cloud.compute.v1beta.BulkInsertDiskResource(); + if (object.instantSnapshotGroupParameters != null) { + if (typeof object.instantSnapshotGroupParameters !== "object") + throw TypeError(".google.cloud.compute.v1beta.BulkInsertDiskResource.instantSnapshotGroupParameters: object expected"); + message.instantSnapshotGroupParameters = $root.google.cloud.compute.v1beta.InstantSnapshotGroupParameters.fromObject(object.instantSnapshotGroupParameters); + } + if (object.snapshotGroupParameters != null) { + if (typeof object.snapshotGroupParameters !== "object") + throw TypeError(".google.cloud.compute.v1beta.BulkInsertDiskResource.snapshotGroupParameters: object expected"); + message.snapshotGroupParameters = $root.google.cloud.compute.v1beta.SnapshotGroupParameters.fromObject(object.snapshotGroupParameters); + } if (object.sourceConsistencyGroupPolicy != null) message.sourceConsistencyGroupPolicy = String(object.sourceConsistencyGroupPolicy); return message; @@ -720588,11 +721170,21 @@ if (!options) options = {}; var object = {}; + if (message.instantSnapshotGroupParameters != null && message.hasOwnProperty("instantSnapshotGroupParameters")) { + object.instantSnapshotGroupParameters = $root.google.cloud.compute.v1beta.InstantSnapshotGroupParameters.toObject(message.instantSnapshotGroupParameters, options); + if (options.oneofs) + object._instantSnapshotGroupParameters = "instantSnapshotGroupParameters"; + } if (message.sourceConsistencyGroupPolicy != null && message.hasOwnProperty("sourceConsistencyGroupPolicy")) { object.sourceConsistencyGroupPolicy = message.sourceConsistencyGroupPolicy; if (options.oneofs) object._sourceConsistencyGroupPolicy = "sourceConsistencyGroupPolicy"; } + if (message.snapshotGroupParameters != null && message.hasOwnProperty("snapshotGroupParameters")) { + object.snapshotGroupParameters = $root.google.cloud.compute.v1beta.SnapshotGroupParameters.toObject(message.snapshotGroupParameters, options); + if (options.oneofs) + object._snapshotGroupParameters = "snapshotGroupParameters"; + } return object; }; @@ -724462,6 +725054,1287 @@ return CacheKeyPolicy; })(); + v1beta.CachePolicy = (function() { + + /** + * Properties of a CachePolicy. + * @memberof google.cloud.compute.v1beta + * @interface ICachePolicy + * @property {Array.|null} [cacheBypassRequestHeaderNames] CachePolicy cacheBypassRequestHeaderNames + * @property {google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy|null} [cacheKeyPolicy] CachePolicy cacheKeyPolicy + * @property {string|null} [cacheMode] CachePolicy cacheMode + * @property {google.cloud.compute.v1beta.IDuration|null} [clientTtl] CachePolicy clientTtl + * @property {google.cloud.compute.v1beta.IDuration|null} [defaultTtl] CachePolicy defaultTtl + * @property {google.cloud.compute.v1beta.IDuration|null} [maxTtl] CachePolicy maxTtl + * @property {boolean|null} [negativeCaching] CachePolicy negativeCaching + * @property {Array.|null} [negativeCachingPolicy] CachePolicy negativeCachingPolicy + * @property {boolean|null} [requestCoalescing] CachePolicy requestCoalescing + * @property {google.cloud.compute.v1beta.IDuration|null} [serveWhileStale] CachePolicy serveWhileStale + */ + + /** + * Constructs a new CachePolicy. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a CachePolicy. + * @implements ICachePolicy + * @constructor + * @param {google.cloud.compute.v1beta.ICachePolicy=} [properties] Properties to set + */ + function CachePolicy(properties) { + this.cacheBypassRequestHeaderNames = []; + this.negativeCachingPolicy = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CachePolicy cacheBypassRequestHeaderNames. + * @member {Array.} cacheBypassRequestHeaderNames + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.cacheBypassRequestHeaderNames = $util.emptyArray; + + /** + * CachePolicy cacheKeyPolicy. + * @member {google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy|null|undefined} cacheKeyPolicy + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.cacheKeyPolicy = null; + + /** + * CachePolicy cacheMode. + * @member {string|null|undefined} cacheMode + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.cacheMode = null; + + /** + * CachePolicy clientTtl. + * @member {google.cloud.compute.v1beta.IDuration|null|undefined} clientTtl + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.clientTtl = null; + + /** + * CachePolicy defaultTtl. + * @member {google.cloud.compute.v1beta.IDuration|null|undefined} defaultTtl + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.defaultTtl = null; + + /** + * CachePolicy maxTtl. + * @member {google.cloud.compute.v1beta.IDuration|null|undefined} maxTtl + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.maxTtl = null; + + /** + * CachePolicy negativeCaching. + * @member {boolean|null|undefined} negativeCaching + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.negativeCaching = null; + + /** + * CachePolicy negativeCachingPolicy. + * @member {Array.} negativeCachingPolicy + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.negativeCachingPolicy = $util.emptyArray; + + /** + * CachePolicy requestCoalescing. + * @member {boolean|null|undefined} requestCoalescing + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.requestCoalescing = null; + + /** + * CachePolicy serveWhileStale. + * @member {google.cloud.compute.v1beta.IDuration|null|undefined} serveWhileStale + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + */ + CachePolicy.prototype.serveWhileStale = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicy.prototype, "_cacheKeyPolicy", { + get: $util.oneOfGetter($oneOfFields = ["cacheKeyPolicy"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicy.prototype, "_cacheMode", { + get: $util.oneOfGetter($oneOfFields = ["cacheMode"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicy.prototype, "_clientTtl", { + get: $util.oneOfGetter($oneOfFields = ["clientTtl"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicy.prototype, "_defaultTtl", { + get: $util.oneOfGetter($oneOfFields = ["defaultTtl"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicy.prototype, "_maxTtl", { + get: $util.oneOfGetter($oneOfFields = ["maxTtl"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicy.prototype, "_negativeCaching", { + get: $util.oneOfGetter($oneOfFields = ["negativeCaching"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicy.prototype, "_requestCoalescing", { + get: $util.oneOfGetter($oneOfFields = ["requestCoalescing"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicy.prototype, "_serveWhileStale", { + get: $util.oneOfGetter($oneOfFields = ["serveWhileStale"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new CachePolicy instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicy=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.CachePolicy} CachePolicy instance + */ + CachePolicy.create = function create(properties) { + return new CachePolicy(properties); + }; + + /** + * Encodes the specified CachePolicy message. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicy.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicy} message CachePolicy message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CachePolicy.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.cacheMode != null && Object.hasOwnProperty.call(message, "cacheMode")) + writer.uint32(/* id 28877888, wireType 2 =*/231023106).string(message.cacheMode); + if (message.clientTtl != null && Object.hasOwnProperty.call(message, "clientTtl")) + $root.google.cloud.compute.v1beta.Duration.encode(message.clientTtl, writer.uint32(/* id 29034360, wireType 2 =*/232274882).fork()).ldelim(); + if (message.defaultTtl != null && Object.hasOwnProperty.call(message, "defaultTtl")) + $root.google.cloud.compute.v1beta.Duration.encode(message.defaultTtl, writer.uint32(/* id 100253422, wireType 2 =*/802027378).fork()).ldelim(); + if (message.negativeCachingPolicy != null && message.negativeCachingPolicy.length) + for (var i = 0; i < message.negativeCachingPolicy.length; ++i) + $root.google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.encode(message.negativeCachingPolicy[i], writer.uint32(/* id 155359996, wireType 2 =*/1242879970).fork()).ldelim(); + if (message.cacheKeyPolicy != null && Object.hasOwnProperty.call(message, "cacheKeyPolicy")) + $root.google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.encode(message.cacheKeyPolicy, writer.uint32(/* id 159263727, wireType 2 =*/1274109818).fork()).ldelim(); + if (message.cacheBypassRequestHeaderNames != null && message.cacheBypassRequestHeaderNames.length) + for (var i = 0; i < message.cacheBypassRequestHeaderNames.length; ++i) + writer.uint32(/* id 197581440, wireType 2 =*/1580651522).string(message.cacheBypassRequestHeaderNames[i]); + if (message.serveWhileStale != null && Object.hasOwnProperty.call(message, "serveWhileStale")) + $root.google.cloud.compute.v1beta.Duration.encode(message.serveWhileStale, writer.uint32(/* id 236682203, wireType 2 =*/1893457626).fork()).ldelim(); + if (message.maxTtl != null && Object.hasOwnProperty.call(message, "maxTtl")) + $root.google.cloud.compute.v1beta.Duration.encode(message.maxTtl, writer.uint32(/* id 307578001, wireType 2 =*/2460624010).fork()).ldelim(); + if (message.negativeCaching != null && Object.hasOwnProperty.call(message, "negativeCaching")) + writer.uint32(/* id 336110005, wireType 0 =*/2688880040).bool(message.negativeCaching); + if (message.requestCoalescing != null && Object.hasOwnProperty.call(message, "requestCoalescing")) + writer.uint32(/* id 532808276, wireType 0 =*/4262466208).bool(message.requestCoalescing); + return writer; + }; + + /** + * Encodes the specified CachePolicy message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicy.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicy} message CachePolicy message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CachePolicy.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CachePolicy message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.CachePolicy} CachePolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CachePolicy.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.cloud.compute.v1beta.CachePolicy(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 197581440: { + if (!(message.cacheBypassRequestHeaderNames && message.cacheBypassRequestHeaderNames.length)) + message.cacheBypassRequestHeaderNames = []; + message.cacheBypassRequestHeaderNames.push(reader.string()); + break; + } + case 159263727: { + message.cacheKeyPolicy = $root.google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.decode(reader, reader.uint32()); + break; + } + case 28877888: { + message.cacheMode = reader.string(); + break; + } + case 29034360: { + message.clientTtl = $root.google.cloud.compute.v1beta.Duration.decode(reader, reader.uint32()); + break; + } + case 100253422: { + message.defaultTtl = $root.google.cloud.compute.v1beta.Duration.decode(reader, reader.uint32()); + break; + } + case 307578001: { + message.maxTtl = $root.google.cloud.compute.v1beta.Duration.decode(reader, reader.uint32()); + break; + } + case 336110005: { + message.negativeCaching = reader.bool(); + break; + } + case 155359996: { + if (!(message.negativeCachingPolicy && message.negativeCachingPolicy.length)) + message.negativeCachingPolicy = []; + message.negativeCachingPolicy.push($root.google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.decode(reader, reader.uint32())); + break; + } + case 532808276: { + message.requestCoalescing = reader.bool(); + break; + } + case 236682203: { + message.serveWhileStale = $root.google.cloud.compute.v1beta.Duration.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CachePolicy message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.CachePolicy} CachePolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CachePolicy.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CachePolicy message. + * @function verify + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CachePolicy.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.cacheBypassRequestHeaderNames != null && message.hasOwnProperty("cacheBypassRequestHeaderNames")) { + if (!Array.isArray(message.cacheBypassRequestHeaderNames)) + return "cacheBypassRequestHeaderNames: array expected"; + for (var i = 0; i < message.cacheBypassRequestHeaderNames.length; ++i) + if (!$util.isString(message.cacheBypassRequestHeaderNames[i])) + return "cacheBypassRequestHeaderNames: string[] expected"; + } + if (message.cacheKeyPolicy != null && message.hasOwnProperty("cacheKeyPolicy")) { + properties._cacheKeyPolicy = 1; + { + var error = $root.google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.verify(message.cacheKeyPolicy); + if (error) + return "cacheKeyPolicy." + error; + } + } + if (message.cacheMode != null && message.hasOwnProperty("cacheMode")) { + properties._cacheMode = 1; + if (!$util.isString(message.cacheMode)) + return "cacheMode: string expected"; + } + if (message.clientTtl != null && message.hasOwnProperty("clientTtl")) { + properties._clientTtl = 1; + { + var error = $root.google.cloud.compute.v1beta.Duration.verify(message.clientTtl); + if (error) + return "clientTtl." + error; + } + } + if (message.defaultTtl != null && message.hasOwnProperty("defaultTtl")) { + properties._defaultTtl = 1; + { + var error = $root.google.cloud.compute.v1beta.Duration.verify(message.defaultTtl); + if (error) + return "defaultTtl." + error; + } + } + if (message.maxTtl != null && message.hasOwnProperty("maxTtl")) { + properties._maxTtl = 1; + { + var error = $root.google.cloud.compute.v1beta.Duration.verify(message.maxTtl); + if (error) + return "maxTtl." + error; + } + } + if (message.negativeCaching != null && message.hasOwnProperty("negativeCaching")) { + properties._negativeCaching = 1; + if (typeof message.negativeCaching !== "boolean") + return "negativeCaching: boolean expected"; + } + if (message.negativeCachingPolicy != null && message.hasOwnProperty("negativeCachingPolicy")) { + if (!Array.isArray(message.negativeCachingPolicy)) + return "negativeCachingPolicy: array expected"; + for (var i = 0; i < message.negativeCachingPolicy.length; ++i) { + var error = $root.google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.verify(message.negativeCachingPolicy[i]); + if (error) + return "negativeCachingPolicy." + error; + } + } + if (message.requestCoalescing != null && message.hasOwnProperty("requestCoalescing")) { + properties._requestCoalescing = 1; + if (typeof message.requestCoalescing !== "boolean") + return "requestCoalescing: boolean expected"; + } + if (message.serveWhileStale != null && message.hasOwnProperty("serveWhileStale")) { + properties._serveWhileStale = 1; + { + var error = $root.google.cloud.compute.v1beta.Duration.verify(message.serveWhileStale); + if (error) + return "serveWhileStale." + error; + } + } + return null; + }; + + /** + * Creates a CachePolicy message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.CachePolicy} CachePolicy + */ + CachePolicy.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.CachePolicy) + return object; + var message = new $root.google.cloud.compute.v1beta.CachePolicy(); + if (object.cacheBypassRequestHeaderNames) { + if (!Array.isArray(object.cacheBypassRequestHeaderNames)) + throw TypeError(".google.cloud.compute.v1beta.CachePolicy.cacheBypassRequestHeaderNames: array expected"); + message.cacheBypassRequestHeaderNames = []; + for (var i = 0; i < object.cacheBypassRequestHeaderNames.length; ++i) + message.cacheBypassRequestHeaderNames[i] = String(object.cacheBypassRequestHeaderNames[i]); + } + if (object.cacheKeyPolicy != null) { + if (typeof object.cacheKeyPolicy !== "object") + throw TypeError(".google.cloud.compute.v1beta.CachePolicy.cacheKeyPolicy: object expected"); + message.cacheKeyPolicy = $root.google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.fromObject(object.cacheKeyPolicy); + } + if (object.cacheMode != null) + message.cacheMode = String(object.cacheMode); + if (object.clientTtl != null) { + if (typeof object.clientTtl !== "object") + throw TypeError(".google.cloud.compute.v1beta.CachePolicy.clientTtl: object expected"); + message.clientTtl = $root.google.cloud.compute.v1beta.Duration.fromObject(object.clientTtl); + } + if (object.defaultTtl != null) { + if (typeof object.defaultTtl !== "object") + throw TypeError(".google.cloud.compute.v1beta.CachePolicy.defaultTtl: object expected"); + message.defaultTtl = $root.google.cloud.compute.v1beta.Duration.fromObject(object.defaultTtl); + } + if (object.maxTtl != null) { + if (typeof object.maxTtl !== "object") + throw TypeError(".google.cloud.compute.v1beta.CachePolicy.maxTtl: object expected"); + message.maxTtl = $root.google.cloud.compute.v1beta.Duration.fromObject(object.maxTtl); + } + if (object.negativeCaching != null) + message.negativeCaching = Boolean(object.negativeCaching); + if (object.negativeCachingPolicy) { + if (!Array.isArray(object.negativeCachingPolicy)) + throw TypeError(".google.cloud.compute.v1beta.CachePolicy.negativeCachingPolicy: array expected"); + message.negativeCachingPolicy = []; + for (var i = 0; i < object.negativeCachingPolicy.length; ++i) { + if (typeof object.negativeCachingPolicy[i] !== "object") + throw TypeError(".google.cloud.compute.v1beta.CachePolicy.negativeCachingPolicy: object expected"); + message.negativeCachingPolicy[i] = $root.google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.fromObject(object.negativeCachingPolicy[i]); + } + } + if (object.requestCoalescing != null) + message.requestCoalescing = Boolean(object.requestCoalescing); + if (object.serveWhileStale != null) { + if (typeof object.serveWhileStale !== "object") + throw TypeError(".google.cloud.compute.v1beta.CachePolicy.serveWhileStale: object expected"); + message.serveWhileStale = $root.google.cloud.compute.v1beta.Duration.fromObject(object.serveWhileStale); + } + return message; + }; + + /** + * Creates a plain object from a CachePolicy message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {google.cloud.compute.v1beta.CachePolicy} message CachePolicy + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CachePolicy.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.negativeCachingPolicy = []; + object.cacheBypassRequestHeaderNames = []; + } + if (message.cacheMode != null && message.hasOwnProperty("cacheMode")) { + object.cacheMode = message.cacheMode; + if (options.oneofs) + object._cacheMode = "cacheMode"; + } + if (message.clientTtl != null && message.hasOwnProperty("clientTtl")) { + object.clientTtl = $root.google.cloud.compute.v1beta.Duration.toObject(message.clientTtl, options); + if (options.oneofs) + object._clientTtl = "clientTtl"; + } + if (message.defaultTtl != null && message.hasOwnProperty("defaultTtl")) { + object.defaultTtl = $root.google.cloud.compute.v1beta.Duration.toObject(message.defaultTtl, options); + if (options.oneofs) + object._defaultTtl = "defaultTtl"; + } + if (message.negativeCachingPolicy && message.negativeCachingPolicy.length) { + object.negativeCachingPolicy = []; + for (var j = 0; j < message.negativeCachingPolicy.length; ++j) + object.negativeCachingPolicy[j] = $root.google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.toObject(message.negativeCachingPolicy[j], options); + } + if (message.cacheKeyPolicy != null && message.hasOwnProperty("cacheKeyPolicy")) { + object.cacheKeyPolicy = $root.google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.toObject(message.cacheKeyPolicy, options); + if (options.oneofs) + object._cacheKeyPolicy = "cacheKeyPolicy"; + } + if (message.cacheBypassRequestHeaderNames && message.cacheBypassRequestHeaderNames.length) { + object.cacheBypassRequestHeaderNames = []; + for (var j = 0; j < message.cacheBypassRequestHeaderNames.length; ++j) + object.cacheBypassRequestHeaderNames[j] = message.cacheBypassRequestHeaderNames[j]; + } + if (message.serveWhileStale != null && message.hasOwnProperty("serveWhileStale")) { + object.serveWhileStale = $root.google.cloud.compute.v1beta.Duration.toObject(message.serveWhileStale, options); + if (options.oneofs) + object._serveWhileStale = "serveWhileStale"; + } + if (message.maxTtl != null && message.hasOwnProperty("maxTtl")) { + object.maxTtl = $root.google.cloud.compute.v1beta.Duration.toObject(message.maxTtl, options); + if (options.oneofs) + object._maxTtl = "maxTtl"; + } + if (message.negativeCaching != null && message.hasOwnProperty("negativeCaching")) { + object.negativeCaching = message.negativeCaching; + if (options.oneofs) + object._negativeCaching = "negativeCaching"; + } + if (message.requestCoalescing != null && message.hasOwnProperty("requestCoalescing")) { + object.requestCoalescing = message.requestCoalescing; + if (options.oneofs) + object._requestCoalescing = "requestCoalescing"; + } + return object; + }; + + /** + * Converts this CachePolicy to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.CachePolicy + * @instance + * @returns {Object.} JSON object + */ + CachePolicy.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CachePolicy + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.CachePolicy + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CachePolicy.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.CachePolicy"; + }; + + /** + * CacheMode enum. + * @name google.cloud.compute.v1beta.CachePolicy.CacheMode + * @enum {number} + * @property {number} UNDEFINED_CACHE_MODE=0 UNDEFINED_CACHE_MODE value + * @property {number} CACHE_ALL_STATIC=355027945 CACHE_ALL_STATIC value + * @property {number} FORCE_CACHE_ALL=486026928 FORCE_CACHE_ALL value + * @property {number} USE_ORIGIN_HEADERS=55380261 USE_ORIGIN_HEADERS value + */ + CachePolicy.CacheMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_CACHE_MODE"] = 0; + values[valuesById[355027945] = "CACHE_ALL_STATIC"] = 355027945; + values[valuesById[486026928] = "FORCE_CACHE_ALL"] = 486026928; + values[valuesById[55380261] = "USE_ORIGIN_HEADERS"] = 55380261; + return values; + })(); + + return CachePolicy; + })(); + + v1beta.CachePolicyCacheKeyPolicy = (function() { + + /** + * Properties of a CachePolicyCacheKeyPolicy. + * @memberof google.cloud.compute.v1beta + * @interface ICachePolicyCacheKeyPolicy + * @property {Array.|null} [excludedQueryParameters] CachePolicyCacheKeyPolicy excludedQueryParameters + * @property {boolean|null} [includeHost] CachePolicyCacheKeyPolicy includeHost + * @property {boolean|null} [includeProtocol] CachePolicyCacheKeyPolicy includeProtocol + * @property {boolean|null} [includeQueryString] CachePolicyCacheKeyPolicy includeQueryString + * @property {Array.|null} [includedCookieNames] CachePolicyCacheKeyPolicy includedCookieNames + * @property {Array.|null} [includedHeaderNames] CachePolicyCacheKeyPolicy includedHeaderNames + * @property {Array.|null} [includedQueryParameters] CachePolicyCacheKeyPolicy includedQueryParameters + */ + + /** + * Constructs a new CachePolicyCacheKeyPolicy. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a CachePolicyCacheKeyPolicy. + * @implements ICachePolicyCacheKeyPolicy + * @constructor + * @param {google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy=} [properties] Properties to set + */ + function CachePolicyCacheKeyPolicy(properties) { + this.excludedQueryParameters = []; + this.includedCookieNames = []; + this.includedHeaderNames = []; + this.includedQueryParameters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CachePolicyCacheKeyPolicy excludedQueryParameters. + * @member {Array.} excludedQueryParameters + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @instance + */ + CachePolicyCacheKeyPolicy.prototype.excludedQueryParameters = $util.emptyArray; + + /** + * CachePolicyCacheKeyPolicy includeHost. + * @member {boolean|null|undefined} includeHost + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @instance + */ + CachePolicyCacheKeyPolicy.prototype.includeHost = null; + + /** + * CachePolicyCacheKeyPolicy includeProtocol. + * @member {boolean|null|undefined} includeProtocol + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @instance + */ + CachePolicyCacheKeyPolicy.prototype.includeProtocol = null; + + /** + * CachePolicyCacheKeyPolicy includeQueryString. + * @member {boolean|null|undefined} includeQueryString + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @instance + */ + CachePolicyCacheKeyPolicy.prototype.includeQueryString = null; + + /** + * CachePolicyCacheKeyPolicy includedCookieNames. + * @member {Array.} includedCookieNames + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @instance + */ + CachePolicyCacheKeyPolicy.prototype.includedCookieNames = $util.emptyArray; + + /** + * CachePolicyCacheKeyPolicy includedHeaderNames. + * @member {Array.} includedHeaderNames + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @instance + */ + CachePolicyCacheKeyPolicy.prototype.includedHeaderNames = $util.emptyArray; + + /** + * CachePolicyCacheKeyPolicy includedQueryParameters. + * @member {Array.} includedQueryParameters + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @instance + */ + CachePolicyCacheKeyPolicy.prototype.includedQueryParameters = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicyCacheKeyPolicy.prototype, "_includeHost", { + get: $util.oneOfGetter($oneOfFields = ["includeHost"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicyCacheKeyPolicy.prototype, "_includeProtocol", { + get: $util.oneOfGetter($oneOfFields = ["includeProtocol"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicyCacheKeyPolicy.prototype, "_includeQueryString", { + get: $util.oneOfGetter($oneOfFields = ["includeQueryString"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new CachePolicyCacheKeyPolicy instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy} CachePolicyCacheKeyPolicy instance + */ + CachePolicyCacheKeyPolicy.create = function create(properties) { + return new CachePolicyCacheKeyPolicy(properties); + }; + + /** + * Encodes the specified CachePolicyCacheKeyPolicy message. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy} message CachePolicyCacheKeyPolicy message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CachePolicyCacheKeyPolicy.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.includedQueryParameters != null && message.includedQueryParameters.length) + for (var i = 0; i < message.includedQueryParameters.length; ++i) + writer.uint32(/* id 2319076, wireType 2 =*/18552610).string(message.includedQueryParameters[i]); + if (message.includedCookieNames != null && message.includedCookieNames.length) + for (var i = 0; i < message.includedCookieNames.length; ++i) + writer.uint32(/* id 66987088, wireType 2 =*/535896706).string(message.includedCookieNames[i]); + if (message.excludedQueryParameters != null && message.excludedQueryParameters.length) + for (var i = 0; i < message.excludedQueryParameters.length; ++i) + writer.uint32(/* id 124896150, wireType 2 =*/999169202).string(message.excludedQueryParameters[i]); + if (message.includeProtocol != null && Object.hasOwnProperty.call(message, "includeProtocol")) + writer.uint32(/* id 303507535, wireType 0 =*/2428060280).bool(message.includeProtocol); + if (message.includeQueryString != null && Object.hasOwnProperty.call(message, "includeQueryString")) + writer.uint32(/* id 474036639, wireType 0 =*/3792293112).bool(message.includeQueryString); + if (message.includeHost != null && Object.hasOwnProperty.call(message, "includeHost")) + writer.uint32(/* id 486867679, wireType 0 =*/3894941432).bool(message.includeHost); + if (message.includedHeaderNames != null && message.includedHeaderNames.length) + for (var i = 0; i < message.includedHeaderNames.length; ++i) + writer.uint32(/* id 533756345, wireType 2 =*/4270050762).string(message.includedHeaderNames[i]); + return writer; + }; + + /** + * Encodes the specified CachePolicyCacheKeyPolicy message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicyCacheKeyPolicy} message CachePolicyCacheKeyPolicy message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CachePolicyCacheKeyPolicy.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CachePolicyCacheKeyPolicy message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy} CachePolicyCacheKeyPolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CachePolicyCacheKeyPolicy.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.cloud.compute.v1beta.CachePolicyCacheKeyPolicy(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 124896150: { + if (!(message.excludedQueryParameters && message.excludedQueryParameters.length)) + message.excludedQueryParameters = []; + message.excludedQueryParameters.push(reader.string()); + break; + } + case 486867679: { + message.includeHost = reader.bool(); + break; + } + case 303507535: { + message.includeProtocol = reader.bool(); + break; + } + case 474036639: { + message.includeQueryString = reader.bool(); + break; + } + case 66987088: { + if (!(message.includedCookieNames && message.includedCookieNames.length)) + message.includedCookieNames = []; + message.includedCookieNames.push(reader.string()); + break; + } + case 533756345: { + if (!(message.includedHeaderNames && message.includedHeaderNames.length)) + message.includedHeaderNames = []; + message.includedHeaderNames.push(reader.string()); + break; + } + case 2319076: { + if (!(message.includedQueryParameters && message.includedQueryParameters.length)) + message.includedQueryParameters = []; + message.includedQueryParameters.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CachePolicyCacheKeyPolicy message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy} CachePolicyCacheKeyPolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CachePolicyCacheKeyPolicy.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CachePolicyCacheKeyPolicy message. + * @function verify + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CachePolicyCacheKeyPolicy.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.excludedQueryParameters != null && message.hasOwnProperty("excludedQueryParameters")) { + if (!Array.isArray(message.excludedQueryParameters)) + return "excludedQueryParameters: array expected"; + for (var i = 0; i < message.excludedQueryParameters.length; ++i) + if (!$util.isString(message.excludedQueryParameters[i])) + return "excludedQueryParameters: string[] expected"; + } + if (message.includeHost != null && message.hasOwnProperty("includeHost")) { + properties._includeHost = 1; + if (typeof message.includeHost !== "boolean") + return "includeHost: boolean expected"; + } + if (message.includeProtocol != null && message.hasOwnProperty("includeProtocol")) { + properties._includeProtocol = 1; + if (typeof message.includeProtocol !== "boolean") + return "includeProtocol: boolean expected"; + } + if (message.includeQueryString != null && message.hasOwnProperty("includeQueryString")) { + properties._includeQueryString = 1; + if (typeof message.includeQueryString !== "boolean") + return "includeQueryString: boolean expected"; + } + if (message.includedCookieNames != null && message.hasOwnProperty("includedCookieNames")) { + if (!Array.isArray(message.includedCookieNames)) + return "includedCookieNames: array expected"; + for (var i = 0; i < message.includedCookieNames.length; ++i) + if (!$util.isString(message.includedCookieNames[i])) + return "includedCookieNames: string[] expected"; + } + if (message.includedHeaderNames != null && message.hasOwnProperty("includedHeaderNames")) { + if (!Array.isArray(message.includedHeaderNames)) + return "includedHeaderNames: array expected"; + for (var i = 0; i < message.includedHeaderNames.length; ++i) + if (!$util.isString(message.includedHeaderNames[i])) + return "includedHeaderNames: string[] expected"; + } + if (message.includedQueryParameters != null && message.hasOwnProperty("includedQueryParameters")) { + if (!Array.isArray(message.includedQueryParameters)) + return "includedQueryParameters: array expected"; + for (var i = 0; i < message.includedQueryParameters.length; ++i) + if (!$util.isString(message.includedQueryParameters[i])) + return "includedQueryParameters: string[] expected"; + } + return null; + }; + + /** + * Creates a CachePolicyCacheKeyPolicy message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy} CachePolicyCacheKeyPolicy + */ + CachePolicyCacheKeyPolicy.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy) + return object; + var message = new $root.google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy(); + if (object.excludedQueryParameters) { + if (!Array.isArray(object.excludedQueryParameters)) + throw TypeError(".google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.excludedQueryParameters: array expected"); + message.excludedQueryParameters = []; + for (var i = 0; i < object.excludedQueryParameters.length; ++i) + message.excludedQueryParameters[i] = String(object.excludedQueryParameters[i]); + } + if (object.includeHost != null) + message.includeHost = Boolean(object.includeHost); + if (object.includeProtocol != null) + message.includeProtocol = Boolean(object.includeProtocol); + if (object.includeQueryString != null) + message.includeQueryString = Boolean(object.includeQueryString); + if (object.includedCookieNames) { + if (!Array.isArray(object.includedCookieNames)) + throw TypeError(".google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.includedCookieNames: array expected"); + message.includedCookieNames = []; + for (var i = 0; i < object.includedCookieNames.length; ++i) + message.includedCookieNames[i] = String(object.includedCookieNames[i]); + } + if (object.includedHeaderNames) { + if (!Array.isArray(object.includedHeaderNames)) + throw TypeError(".google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.includedHeaderNames: array expected"); + message.includedHeaderNames = []; + for (var i = 0; i < object.includedHeaderNames.length; ++i) + message.includedHeaderNames[i] = String(object.includedHeaderNames[i]); + } + if (object.includedQueryParameters) { + if (!Array.isArray(object.includedQueryParameters)) + throw TypeError(".google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy.includedQueryParameters: array expected"); + message.includedQueryParameters = []; + for (var i = 0; i < object.includedQueryParameters.length; ++i) + message.includedQueryParameters[i] = String(object.includedQueryParameters[i]); + } + return message; + }; + + /** + * Creates a plain object from a CachePolicyCacheKeyPolicy message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy} message CachePolicyCacheKeyPolicy + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CachePolicyCacheKeyPolicy.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.includedQueryParameters = []; + object.includedCookieNames = []; + object.excludedQueryParameters = []; + object.includedHeaderNames = []; + } + if (message.includedQueryParameters && message.includedQueryParameters.length) { + object.includedQueryParameters = []; + for (var j = 0; j < message.includedQueryParameters.length; ++j) + object.includedQueryParameters[j] = message.includedQueryParameters[j]; + } + if (message.includedCookieNames && message.includedCookieNames.length) { + object.includedCookieNames = []; + for (var j = 0; j < message.includedCookieNames.length; ++j) + object.includedCookieNames[j] = message.includedCookieNames[j]; + } + if (message.excludedQueryParameters && message.excludedQueryParameters.length) { + object.excludedQueryParameters = []; + for (var j = 0; j < message.excludedQueryParameters.length; ++j) + object.excludedQueryParameters[j] = message.excludedQueryParameters[j]; + } + if (message.includeProtocol != null && message.hasOwnProperty("includeProtocol")) { + object.includeProtocol = message.includeProtocol; + if (options.oneofs) + object._includeProtocol = "includeProtocol"; + } + if (message.includeQueryString != null && message.hasOwnProperty("includeQueryString")) { + object.includeQueryString = message.includeQueryString; + if (options.oneofs) + object._includeQueryString = "includeQueryString"; + } + if (message.includeHost != null && message.hasOwnProperty("includeHost")) { + object.includeHost = message.includeHost; + if (options.oneofs) + object._includeHost = "includeHost"; + } + if (message.includedHeaderNames && message.includedHeaderNames.length) { + object.includedHeaderNames = []; + for (var j = 0; j < message.includedHeaderNames.length; ++j) + object.includedHeaderNames[j] = message.includedHeaderNames[j]; + } + return object; + }; + + /** + * Converts this CachePolicyCacheKeyPolicy to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @instance + * @returns {Object.} JSON object + */ + CachePolicyCacheKeyPolicy.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CachePolicyCacheKeyPolicy + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CachePolicyCacheKeyPolicy.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.CachePolicyCacheKeyPolicy"; + }; + + return CachePolicyCacheKeyPolicy; + })(); + + v1beta.CachePolicyNegativeCachingPolicy = (function() { + + /** + * Properties of a CachePolicyNegativeCachingPolicy. + * @memberof google.cloud.compute.v1beta + * @interface ICachePolicyNegativeCachingPolicy + * @property {number|null} [code] CachePolicyNegativeCachingPolicy code + * @property {google.cloud.compute.v1beta.IDuration|null} [ttl] CachePolicyNegativeCachingPolicy ttl + */ + + /** + * Constructs a new CachePolicyNegativeCachingPolicy. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a CachePolicyNegativeCachingPolicy. + * @implements ICachePolicyNegativeCachingPolicy + * @constructor + * @param {google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy=} [properties] Properties to set + */ + function CachePolicyNegativeCachingPolicy(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CachePolicyNegativeCachingPolicy code. + * @member {number|null|undefined} code + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @instance + */ + CachePolicyNegativeCachingPolicy.prototype.code = null; + + /** + * CachePolicyNegativeCachingPolicy ttl. + * @member {google.cloud.compute.v1beta.IDuration|null|undefined} ttl + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @instance + */ + CachePolicyNegativeCachingPolicy.prototype.ttl = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicyNegativeCachingPolicy.prototype, "_code", { + get: $util.oneOfGetter($oneOfFields = ["code"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(CachePolicyNegativeCachingPolicy.prototype, "_ttl", { + get: $util.oneOfGetter($oneOfFields = ["ttl"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new CachePolicyNegativeCachingPolicy instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy} CachePolicyNegativeCachingPolicy instance + */ + CachePolicyNegativeCachingPolicy.create = function create(properties) { + return new CachePolicyNegativeCachingPolicy(properties); + }; + + /** + * Encodes the specified CachePolicyNegativeCachingPolicy message. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy} message CachePolicyNegativeCachingPolicy message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CachePolicyNegativeCachingPolicy.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.ttl != null && Object.hasOwnProperty.call(message, "ttl")) + $root.google.cloud.compute.v1beta.Duration.encode(message.ttl, writer.uint32(/* id 115180, wireType 2 =*/921442).fork()).ldelim(); + if (message.code != null && Object.hasOwnProperty.call(message, "code")) + writer.uint32(/* id 3059181, wireType 0 =*/24473448).int32(message.code); + return writer; + }; + + /** + * Encodes the specified CachePolicyNegativeCachingPolicy message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {google.cloud.compute.v1beta.ICachePolicyNegativeCachingPolicy} message CachePolicyNegativeCachingPolicy message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CachePolicyNegativeCachingPolicy.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CachePolicyNegativeCachingPolicy message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy} CachePolicyNegativeCachingPolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CachePolicyNegativeCachingPolicy.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.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3059181: { + message.code = reader.int32(); + break; + } + case 115180: { + message.ttl = $root.google.cloud.compute.v1beta.Duration.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CachePolicyNegativeCachingPolicy message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy} CachePolicyNegativeCachingPolicy + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CachePolicyNegativeCachingPolicy.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CachePolicyNegativeCachingPolicy message. + * @function verify + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CachePolicyNegativeCachingPolicy.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.code != null && message.hasOwnProperty("code")) { + properties._code = 1; + if (!$util.isInteger(message.code)) + return "code: integer expected"; + } + if (message.ttl != null && message.hasOwnProperty("ttl")) { + properties._ttl = 1; + { + var error = $root.google.cloud.compute.v1beta.Duration.verify(message.ttl); + if (error) + return "ttl." + error; + } + } + return null; + }; + + /** + * Creates a CachePolicyNegativeCachingPolicy message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy} CachePolicyNegativeCachingPolicy + */ + CachePolicyNegativeCachingPolicy.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy) + return object; + var message = new $root.google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy(); + if (object.code != null) + message.code = object.code | 0; + if (object.ttl != null) { + if (typeof object.ttl !== "object") + throw TypeError(".google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy.ttl: object expected"); + message.ttl = $root.google.cloud.compute.v1beta.Duration.fromObject(object.ttl); + } + return message; + }; + + /** + * Creates a plain object from a CachePolicyNegativeCachingPolicy message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy} message CachePolicyNegativeCachingPolicy + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CachePolicyNegativeCachingPolicy.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.ttl != null && message.hasOwnProperty("ttl")) { + object.ttl = $root.google.cloud.compute.v1beta.Duration.toObject(message.ttl, options); + if (options.oneofs) + object._ttl = "ttl"; + } + if (message.code != null && message.hasOwnProperty("code")) { + object.code = message.code; + if (options.oneofs) + object._code = "code"; + } + return object; + }; + + /** + * Converts this CachePolicyNegativeCachingPolicy to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @instance + * @returns {Object.} JSON object + */ + CachePolicyNegativeCachingPolicy.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CachePolicyNegativeCachingPolicy + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CachePolicyNegativeCachingPolicy.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.CachePolicyNegativeCachingPolicy"; + }; + + return CachePolicyNegativeCachingPolicy; + })(); + v1beta.CalendarModeAdviceRequest = (function() { /** @@ -729311,6 +731184,7 @@ * @property {number} GENERAL_PURPOSE_N2=301912156 GENERAL_PURPOSE_N2 value * @property {number} GENERAL_PURPOSE_N2D=232471400 GENERAL_PURPOSE_N2D value * @property {number} GENERAL_PURPOSE_N4=301912158 GENERAL_PURPOSE_N4 value + * @property {number} GENERAL_PURPOSE_N4A=232471459 GENERAL_PURPOSE_N4A value * @property {number} GENERAL_PURPOSE_N4D=232471462 GENERAL_PURPOSE_N4D value * @property {number} GENERAL_PURPOSE_T2D=232477166 GENERAL_PURPOSE_T2D value * @property {number} GRAPHICS_OPTIMIZED=68500563 GRAPHICS_OPTIMIZED value @@ -729353,6 +731227,7 @@ values[valuesById[301912156] = "GENERAL_PURPOSE_N2"] = 301912156; values[valuesById[232471400] = "GENERAL_PURPOSE_N2D"] = 232471400; values[valuesById[301912158] = "GENERAL_PURPOSE_N4"] = 301912158; + values[valuesById[232471459] = "GENERAL_PURPOSE_N4A"] = 232471459; values[valuesById[232471462] = "GENERAL_PURPOSE_N4D"] = 232471462; values[valuesById[232477166] = "GENERAL_PURPOSE_T2D"] = 232477166; values[valuesById[68500563] = "GRAPHICS_OPTIMIZED"] = 68500563; @@ -732696,6 +734571,323 @@ return ConfidentialInstanceConfig; })(); + v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest = (function() { + + /** + * Properties of a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest. + * @memberof google.cloud.compute.v1beta + * @interface IConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @property {string|null} [instanceGroupManager] ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instanceGroupManager + * @property {google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest|null} [instanceGroupManagersConfigureAcceleratorTopologiesRequestResource] ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instanceGroupManagersConfigureAcceleratorTopologiesRequestResource + * @property {string|null} [project] ConfigureAcceleratorTopologiesInstanceGroupManagerRequest project + * @property {string|null} [requestId] ConfigureAcceleratorTopologiesInstanceGroupManagerRequest requestId + * @property {string|null} [zone] ConfigureAcceleratorTopologiesInstanceGroupManagerRequest zone + */ + + /** + * Constructs a new ConfigureAcceleratorTopologiesInstanceGroupManagerRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest. + * @implements IConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @constructor + * @param {google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest=} [properties] Properties to set + */ + function ConfigureAcceleratorTopologiesInstanceGroupManagerRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instanceGroupManager. + * @member {string} instanceGroupManager + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @instance + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.prototype.instanceGroupManager = ""; + + /** + * ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instanceGroupManagersConfigureAcceleratorTopologiesRequestResource. + * @member {google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest|null|undefined} instanceGroupManagersConfigureAcceleratorTopologiesRequestResource + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @instance + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.prototype.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource = null; + + /** + * ConfigureAcceleratorTopologiesInstanceGroupManagerRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @instance + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.prototype.project = ""; + + /** + * ConfigureAcceleratorTopologiesInstanceGroupManagerRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @instance + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.prototype.requestId = null; + + /** + * ConfigureAcceleratorTopologiesInstanceGroupManagerRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @instance + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.prototype.zone = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest} ConfigureAcceleratorTopologiesInstanceGroupManagerRequest instance + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.create = function create(properties) { + return new ConfigureAcceleratorTopologiesInstanceGroupManagerRequest(properties); + }; + + /** + * Encodes the specified ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest} message ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.instanceGroupManager != null && Object.hasOwnProperty.call(message, "instanceGroupManager")) + writer.uint32(/* id 249363395, wireType 2 =*/1994907162).string(message.instanceGroupManager); + if (message.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource != null && Object.hasOwnProperty.call(message, "instanceGroupManagersConfigureAcceleratorTopologiesRequestResource")) + $root.google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.encode(message.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource, writer.uint32(/* id 365743316, wireType 2 =*/2925946530).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest} message ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest} ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.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.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 249363395: { + message.instanceGroupManager = reader.string(); + break; + } + case 365743316: { + message.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource = $root.google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.decode(reader, reader.uint32()); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest} ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instanceGroupManager != null && message.hasOwnProperty("instanceGroupManager")) + if (!$util.isString(message.instanceGroupManager)) + return "instanceGroupManager: string expected"; + if (message.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource != null && message.hasOwnProperty("instanceGroupManagersConfigureAcceleratorTopologiesRequestResource")) { + var error = $root.google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.verify(message.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource); + if (error) + return "instanceGroupManagersConfigureAcceleratorTopologiesRequestResource." + error; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest} ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest(); + if (object.instanceGroupManager != null) + message.instanceGroupManager = String(object.instanceGroupManager); + if (object.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource != null) { + if (typeof object.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource: object expected"); + message.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource = $root.google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.fromObject(object.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource); + } + if (object.project != null) + message.project = String(object.project); + if (object.requestId != null) + message.requestId = String(object.requestId); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest} message ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.project = ""; + object.instanceGroupManager = ""; + object.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource = null; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.instanceGroupManager != null && message.hasOwnProperty("instanceGroupManager")) + object.instanceGroupManager = message.instanceGroupManager; + if (message.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource != null && message.hasOwnProperty("instanceGroupManagersConfigureAcceleratorTopologiesRequestResource")) + object.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource = $root.google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.toObject(message.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource, options); + return object; + }; + + /** + * Converts this ConfigureAcceleratorTopologiesInstanceGroupManagerRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @instance + * @returns {Object.} JSON object + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ConfigureAcceleratorTopologiesInstanceGroupManagerRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest"; + }; + + return ConfigureAcceleratorTopologiesInstanceGroupManagerRequest; + })(); + v1beta.ConnectionDraining = (function() { /** @@ -746560,27 +748752,27 @@ return DeleteInstancesRegionInstanceGroupManagerRequest; })(); - v1beta.DeleteInstantSnapshotRequest = (function() { + v1beta.DeleteInstantSnapshotGroupRequest = (function() { /** - * Properties of a DeleteInstantSnapshotRequest. + * Properties of a DeleteInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface IDeleteInstantSnapshotRequest - * @property {string|null} [instantSnapshot] DeleteInstantSnapshotRequest instantSnapshot - * @property {string|null} [project] DeleteInstantSnapshotRequest project - * @property {string|null} [requestId] DeleteInstantSnapshotRequest requestId - * @property {string|null} [zone] DeleteInstantSnapshotRequest zone + * @interface IDeleteInstantSnapshotGroupRequest + * @property {string|null} [instantSnapshotGroup] DeleteInstantSnapshotGroupRequest instantSnapshotGroup + * @property {string|null} [project] DeleteInstantSnapshotGroupRequest project + * @property {string|null} [requestId] DeleteInstantSnapshotGroupRequest requestId + * @property {string|null} [zone] DeleteInstantSnapshotGroupRequest zone */ /** - * Constructs a new DeleteInstantSnapshotRequest. + * Constructs a new DeleteInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a DeleteInstantSnapshotRequest. - * @implements IDeleteInstantSnapshotRequest + * @classdesc Represents a DeleteInstantSnapshotGroupRequest. + * @implements IDeleteInstantSnapshotGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest=} [properties] Properties to set */ - function DeleteInstantSnapshotRequest(properties) { + function DeleteInstantSnapshotGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -746588,116 +748780,405 @@ } /** - * DeleteInstantSnapshotRequest instantSnapshot. - * @member {string} instantSnapshot - * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * DeleteInstantSnapshotGroupRequest instantSnapshotGroup. + * @member {string} instantSnapshotGroup + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest * @instance */ - DeleteInstantSnapshotRequest.prototype.instantSnapshot = ""; + DeleteInstantSnapshotGroupRequest.prototype.instantSnapshotGroup = ""; /** - * DeleteInstantSnapshotRequest project. + * DeleteInstantSnapshotGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest * @instance */ - DeleteInstantSnapshotRequest.prototype.project = ""; + DeleteInstantSnapshotGroupRequest.prototype.project = ""; /** - * DeleteInstantSnapshotRequest requestId. + * DeleteInstantSnapshotGroupRequest requestId. * @member {string|null|undefined} requestId - * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest * @instance */ - DeleteInstantSnapshotRequest.prototype.requestId = null; + DeleteInstantSnapshotGroupRequest.prototype.requestId = null; /** - * DeleteInstantSnapshotRequest zone. + * DeleteInstantSnapshotGroupRequest zone. * @member {string} zone - * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest * @instance */ - DeleteInstantSnapshotRequest.prototype.zone = ""; + DeleteInstantSnapshotGroupRequest.prototype.zone = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(DeleteInstantSnapshotRequest.prototype, "_requestId", { + Object.defineProperty(DeleteInstantSnapshotGroupRequest.prototype, "_requestId", { get: $util.oneOfGetter($oneOfFields = ["requestId"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new DeleteInstantSnapshotRequest instance using the specified properties. + * Creates a new DeleteInstantSnapshotGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.DeleteInstantSnapshotRequest} DeleteInstantSnapshotRequest instance + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest} DeleteInstantSnapshotGroupRequest instance */ - DeleteInstantSnapshotRequest.create = function create(properties) { - return new DeleteInstantSnapshotRequest(properties); + DeleteInstantSnapshotGroupRequest.create = function create(properties) { + return new DeleteInstantSnapshotGroupRequest(properties); }; /** - * Encodes the specified DeleteInstantSnapshotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteInstantSnapshotRequest.verify|verify} messages. + * Encodes the specified DeleteInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotRequest} message DeleteInstantSnapshotRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest} message DeleteInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - DeleteInstantSnapshotRequest.encode = function encode(message, writer) { + DeleteInstantSnapshotGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.instantSnapshotGroup != null && Object.hasOwnProperty.call(message, "instantSnapshotGroup")) + writer.uint32(/* id 223180386, wireType 2 =*/1785443090).string(message.instantSnapshotGroup); if (message.project != null && Object.hasOwnProperty.call(message, "project")) writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); - if (message.instantSnapshot != null && Object.hasOwnProperty.call(message, "instantSnapshot")) - writer.uint32(/* id 391638626, wireType 2 =*/3133109010).string(message.instantSnapshot); return writer; }; /** - * Encodes the specified DeleteInstantSnapshotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteInstantSnapshotRequest.verify|verify} messages. + * Encodes the specified DeleteInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotRequest} message DeleteInstantSnapshotRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest} message DeleteInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - DeleteInstantSnapshotRequest.encodeDelimited = function encodeDelimited(message, writer) { + DeleteInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a DeleteInstantSnapshotRequest message from the specified reader or buffer. + * Decodes a DeleteInstantSnapshotGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.DeleteInstantSnapshotRequest} DeleteInstantSnapshotRequest + * @returns {google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest} DeleteInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteInstantSnapshotRequest.decode = function decode(reader, length, error) { + DeleteInstantSnapshotGroupRequest.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.cloud.compute.v1beta.DeleteInstantSnapshotRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { - case 391638626: { - message.instantSnapshot = reader.string(); + case 223180386: { + message.instantSnapshotGroup = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest} DeleteInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteInstantSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteInstantSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) + if (!$util.isString(message.instantSnapshotGroup)) + return "instantSnapshotGroup: string expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates a DeleteInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest} DeleteInstantSnapshotGroupRequest + */ + DeleteInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest(); + if (object.instantSnapshotGroup != null) + message.instantSnapshotGroup = String(object.instantSnapshotGroup); + if (object.project != null) + message.project = String(object.project); + if (object.requestId != null) + message.requestId = String(object.requestId); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a DeleteInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest} message DeleteInstantSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteInstantSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.instantSnapshotGroup = ""; + object.project = ""; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) + object.instantSnapshotGroup = message.instantSnapshotGroup; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + return object; + }; + + /** + * Converts this DeleteInstantSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteInstantSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest"; + }; + + return DeleteInstantSnapshotGroupRequest; + })(); + + v1beta.DeleteInstantSnapshotRequest = (function() { + + /** + * Properties of a DeleteInstantSnapshotRequest. + * @memberof google.cloud.compute.v1beta + * @interface IDeleteInstantSnapshotRequest + * @property {string|null} [instantSnapshot] DeleteInstantSnapshotRequest instantSnapshot + * @property {string|null} [project] DeleteInstantSnapshotRequest project + * @property {string|null} [requestId] DeleteInstantSnapshotRequest requestId + * @property {string|null} [zone] DeleteInstantSnapshotRequest zone + */ + + /** + * Constructs a new DeleteInstantSnapshotRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a DeleteInstantSnapshotRequest. + * @implements IDeleteInstantSnapshotRequest + * @constructor + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotRequest=} [properties] Properties to set + */ + function DeleteInstantSnapshotRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteInstantSnapshotRequest instantSnapshot. + * @member {string} instantSnapshot + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @instance + */ + DeleteInstantSnapshotRequest.prototype.instantSnapshot = ""; + + /** + * DeleteInstantSnapshotRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @instance + */ + DeleteInstantSnapshotRequest.prototype.project = ""; + + /** + * DeleteInstantSnapshotRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @instance + */ + DeleteInstantSnapshotRequest.prototype.requestId = null; + + /** + * DeleteInstantSnapshotRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @instance + */ + DeleteInstantSnapshotRequest.prototype.zone = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(DeleteInstantSnapshotRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new DeleteInstantSnapshotRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.DeleteInstantSnapshotRequest} DeleteInstantSnapshotRequest instance + */ + DeleteInstantSnapshotRequest.create = function create(properties) { + return new DeleteInstantSnapshotRequest(properties); + }; + + /** + * Encodes the specified DeleteInstantSnapshotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteInstantSnapshotRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotRequest} message DeleteInstantSnapshotRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteInstantSnapshotRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.instantSnapshot != null && Object.hasOwnProperty.call(message, "instantSnapshot")) + writer.uint32(/* id 391638626, wireType 2 =*/3133109010).string(message.instantSnapshot); + return writer; + }; + + /** + * Encodes the specified DeleteInstantSnapshotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteInstantSnapshotRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotRequest} message DeleteInstantSnapshotRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteInstantSnapshotRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteInstantSnapshotRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.DeleteInstantSnapshotRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.DeleteInstantSnapshotRequest} DeleteInstantSnapshotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteInstantSnapshotRequest.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.cloud.compute.v1beta.DeleteInstantSnapshotRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 391638626: { + message.instantSnapshot = reader.string(); break; } case 227560217: { @@ -748468,27 +750949,28 @@ return DeleteMachineImageRequest; })(); - v1beta.DeleteNetworkAttachmentRequest = (function() { + v1beta.DeleteNamedSetRouterRequest = (function() { /** - * Properties of a DeleteNetworkAttachmentRequest. + * Properties of a DeleteNamedSetRouterRequest. * @memberof google.cloud.compute.v1beta - * @interface IDeleteNetworkAttachmentRequest - * @property {string|null} [networkAttachment] DeleteNetworkAttachmentRequest networkAttachment - * @property {string|null} [project] DeleteNetworkAttachmentRequest project - * @property {string|null} [region] DeleteNetworkAttachmentRequest region - * @property {string|null} [requestId] DeleteNetworkAttachmentRequest requestId + * @interface IDeleteNamedSetRouterRequest + * @property {string|null} [namedSet] DeleteNamedSetRouterRequest namedSet + * @property {string|null} [project] DeleteNamedSetRouterRequest project + * @property {string|null} [region] DeleteNamedSetRouterRequest region + * @property {string|null} [requestId] DeleteNamedSetRouterRequest requestId + * @property {string|null} [router] DeleteNamedSetRouterRequest router */ /** - * Constructs a new DeleteNetworkAttachmentRequest. + * Constructs a new DeleteNamedSetRouterRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a DeleteNetworkAttachmentRequest. - * @implements IDeleteNetworkAttachmentRequest + * @classdesc Represents a DeleteNamedSetRouterRequest. + * @implements IDeleteNamedSetRouterRequest * @constructor - * @param {google.cloud.compute.v1beta.IDeleteNetworkAttachmentRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest=} [properties] Properties to set */ - function DeleteNetworkAttachmentRequest(properties) { + function DeleteNamedSetRouterRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -748496,116 +750978,132 @@ } /** - * DeleteNetworkAttachmentRequest networkAttachment. - * @member {string} networkAttachment - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * DeleteNamedSetRouterRequest namedSet. + * @member {string|null|undefined} namedSet + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @instance */ - DeleteNetworkAttachmentRequest.prototype.networkAttachment = ""; + DeleteNamedSetRouterRequest.prototype.namedSet = null; /** - * DeleteNetworkAttachmentRequest project. + * DeleteNamedSetRouterRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @instance */ - DeleteNetworkAttachmentRequest.prototype.project = ""; + DeleteNamedSetRouterRequest.prototype.project = ""; /** - * DeleteNetworkAttachmentRequest region. + * DeleteNamedSetRouterRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @instance */ - DeleteNetworkAttachmentRequest.prototype.region = ""; + DeleteNamedSetRouterRequest.prototype.region = ""; /** - * DeleteNetworkAttachmentRequest requestId. + * DeleteNamedSetRouterRequest requestId. * @member {string|null|undefined} requestId - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @instance */ - DeleteNetworkAttachmentRequest.prototype.requestId = null; + DeleteNamedSetRouterRequest.prototype.requestId = null; + + /** + * DeleteNamedSetRouterRequest router. + * @member {string} router + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest + * @instance + */ + DeleteNamedSetRouterRequest.prototype.router = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(DeleteNetworkAttachmentRequest.prototype, "_requestId", { + Object.defineProperty(DeleteNamedSetRouterRequest.prototype, "_namedSet", { + get: $util.oneOfGetter($oneOfFields = ["namedSet"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(DeleteNamedSetRouterRequest.prototype, "_requestId", { get: $util.oneOfGetter($oneOfFields = ["requestId"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new DeleteNetworkAttachmentRequest instance using the specified properties. + * Creates a new DeleteNamedSetRouterRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteNetworkAttachmentRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} DeleteNetworkAttachmentRequest instance + * @param {google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.DeleteNamedSetRouterRequest} DeleteNamedSetRouterRequest instance */ - DeleteNetworkAttachmentRequest.create = function create(properties) { - return new DeleteNetworkAttachmentRequest(properties); + DeleteNamedSetRouterRequest.create = function create(properties) { + return new DeleteNamedSetRouterRequest(properties); }; /** - * Encodes the specified DeleteNetworkAttachmentRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest.verify|verify} messages. + * Encodes the specified DeleteNamedSetRouterRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNamedSetRouterRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteNetworkAttachmentRequest} message DeleteNetworkAttachmentRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest} message DeleteNamedSetRouterRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - DeleteNetworkAttachmentRequest.encode = function encode(message, writer) { + DeleteNamedSetRouterRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); if (message.region != null && Object.hasOwnProperty.call(message, "region")) writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); - if (message.networkAttachment != null && Object.hasOwnProperty.call(message, "networkAttachment")) - writer.uint32(/* id 224644052, wireType 2 =*/1797152418).string(message.networkAttachment); + if (message.router != null && Object.hasOwnProperty.call(message, "router")) + writer.uint32(/* id 148608841, wireType 2 =*/1188870730).string(message.router); + if (message.namedSet != null && Object.hasOwnProperty.call(message, "namedSet")) + writer.uint32(/* id 164134492, wireType 2 =*/1313075938).string(message.namedSet); if (message.project != null && Object.hasOwnProperty.call(message, "project")) writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); return writer; }; /** - * Encodes the specified DeleteNetworkAttachmentRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest.verify|verify} messages. + * Encodes the specified DeleteNamedSetRouterRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNamedSetRouterRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteNetworkAttachmentRequest} message DeleteNetworkAttachmentRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest} message DeleteNamedSetRouterRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - DeleteNetworkAttachmentRequest.encodeDelimited = function encodeDelimited(message, writer) { + DeleteNamedSetRouterRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a DeleteNetworkAttachmentRequest message from the specified reader or buffer. + * Decodes a DeleteNamedSetRouterRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} DeleteNetworkAttachmentRequest + * @returns {google.cloud.compute.v1beta.DeleteNamedSetRouterRequest} DeleteNamedSetRouterRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteNetworkAttachmentRequest.decode = function decode(reader, length, error) { + DeleteNamedSetRouterRequest.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.cloud.compute.v1beta.DeleteNetworkAttachmentRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { - case 224644052: { - message.networkAttachment = reader.string(); + case 164134492: { + message.namedSet = reader.string(); break; } case 227560217: { @@ -748620,6 +751118,10 @@ message.requestId = reader.string(); break; } + case 148608841: { + message.router = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -748629,36 +751131,38 @@ }; /** - * Decodes a DeleteNetworkAttachmentRequest message from the specified reader or buffer, length delimited. + * Decodes a DeleteNamedSetRouterRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} DeleteNetworkAttachmentRequest + * @returns {google.cloud.compute.v1beta.DeleteNamedSetRouterRequest} DeleteNamedSetRouterRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteNetworkAttachmentRequest.decodeDelimited = function decodeDelimited(reader) { + DeleteNamedSetRouterRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a DeleteNetworkAttachmentRequest message. + * Verifies a DeleteNamedSetRouterRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - DeleteNetworkAttachmentRequest.verify = function verify(message) { + DeleteNamedSetRouterRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; - if (message.networkAttachment != null && message.hasOwnProperty("networkAttachment")) - if (!$util.isString(message.networkAttachment)) - return "networkAttachment: string expected"; + if (message.namedSet != null && message.hasOwnProperty("namedSet")) { + properties._namedSet = 1; + if (!$util.isString(message.namedSet)) + return "namedSet: string expected"; + } if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) return "project: string expected"; @@ -748670,48 +751174,53 @@ if (!$util.isString(message.requestId)) return "requestId: string expected"; } + if (message.router != null && message.hasOwnProperty("router")) + if (!$util.isString(message.router)) + return "router: string expected"; return null; }; /** - * Creates a DeleteNetworkAttachmentRequest message from a plain object. Also converts values to their respective internal types. + * Creates a DeleteNamedSetRouterRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} DeleteNetworkAttachmentRequest + * @returns {google.cloud.compute.v1beta.DeleteNamedSetRouterRequest} DeleteNamedSetRouterRequest */ - DeleteNetworkAttachmentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest) + DeleteNamedSetRouterRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest) return object; - var message = new $root.google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest(); - if (object.networkAttachment != null) - message.networkAttachment = String(object.networkAttachment); + var message = new $root.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest(); + if (object.namedSet != null) + message.namedSet = String(object.namedSet); if (object.project != null) message.project = String(object.project); if (object.region != null) message.region = String(object.region); if (object.requestId != null) message.requestId = String(object.requestId); + if (object.router != null) + message.router = String(object.router); return message; }; /** - * Creates a plain object from a DeleteNetworkAttachmentRequest message. Also converts values to other types if specified. + * Creates a plain object from a DeleteNamedSetRouterRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static - * @param {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} message DeleteNetworkAttachmentRequest + * @param {google.cloud.compute.v1beta.DeleteNamedSetRouterRequest} message DeleteNamedSetRouterRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - DeleteNetworkAttachmentRequest.toObject = function toObject(message, options) { + DeleteNamedSetRouterRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { object.region = ""; - object.networkAttachment = ""; + object.router = ""; object.project = ""; } if (message.requestId != null && message.hasOwnProperty("requestId")) { @@ -748721,63 +751230,68 @@ } if (message.region != null && message.hasOwnProperty("region")) object.region = message.region; - if (message.networkAttachment != null && message.hasOwnProperty("networkAttachment")) - object.networkAttachment = message.networkAttachment; + if (message.router != null && message.hasOwnProperty("router")) + object.router = message.router; + if (message.namedSet != null && message.hasOwnProperty("namedSet")) { + object.namedSet = message.namedSet; + if (options.oneofs) + object._namedSet = "namedSet"; + } if (message.project != null && message.hasOwnProperty("project")) object.project = message.project; return object; }; /** - * Converts this DeleteNetworkAttachmentRequest to JSON. + * Converts this DeleteNamedSetRouterRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @instance * @returns {Object.} JSON object */ - DeleteNetworkAttachmentRequest.prototype.toJSON = function toJSON() { + DeleteNamedSetRouterRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for DeleteNetworkAttachmentRequest + * Gets the default type url for DeleteNamedSetRouterRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @memberof google.cloud.compute.v1beta.DeleteNamedSetRouterRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - DeleteNetworkAttachmentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + DeleteNamedSetRouterRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.DeleteNamedSetRouterRequest"; }; - return DeleteNetworkAttachmentRequest; + return DeleteNamedSetRouterRequest; })(); - v1beta.DeleteNetworkEdgeSecurityServiceRequest = (function() { + v1beta.DeleteNetworkAttachmentRequest = (function() { /** - * Properties of a DeleteNetworkEdgeSecurityServiceRequest. + * Properties of a DeleteNetworkAttachmentRequest. * @memberof google.cloud.compute.v1beta - * @interface IDeleteNetworkEdgeSecurityServiceRequest - * @property {string|null} [networkEdgeSecurityService] DeleteNetworkEdgeSecurityServiceRequest networkEdgeSecurityService - * @property {string|null} [project] DeleteNetworkEdgeSecurityServiceRequest project - * @property {string|null} [region] DeleteNetworkEdgeSecurityServiceRequest region - * @property {string|null} [requestId] DeleteNetworkEdgeSecurityServiceRequest requestId + * @interface IDeleteNetworkAttachmentRequest + * @property {string|null} [networkAttachment] DeleteNetworkAttachmentRequest networkAttachment + * @property {string|null} [project] DeleteNetworkAttachmentRequest project + * @property {string|null} [region] DeleteNetworkAttachmentRequest region + * @property {string|null} [requestId] DeleteNetworkAttachmentRequest requestId */ /** - * Constructs a new DeleteNetworkEdgeSecurityServiceRequest. + * Constructs a new DeleteNetworkAttachmentRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a DeleteNetworkEdgeSecurityServiceRequest. - * @implements IDeleteNetworkEdgeSecurityServiceRequest + * @classdesc Represents a DeleteNetworkAttachmentRequest. + * @implements IDeleteNetworkAttachmentRequest * @constructor - * @param {google.cloud.compute.v1beta.IDeleteNetworkEdgeSecurityServiceRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IDeleteNetworkAttachmentRequest=} [properties] Properties to set */ - function DeleteNetworkEdgeSecurityServiceRequest(properties) { + function DeleteNetworkAttachmentRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -748785,116 +751299,405 @@ } /** - * DeleteNetworkEdgeSecurityServiceRequest networkEdgeSecurityService. - * @member {string} networkEdgeSecurityService - * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * DeleteNetworkAttachmentRequest networkAttachment. + * @member {string} networkAttachment + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest * @instance */ - DeleteNetworkEdgeSecurityServiceRequest.prototype.networkEdgeSecurityService = ""; + DeleteNetworkAttachmentRequest.prototype.networkAttachment = ""; /** - * DeleteNetworkEdgeSecurityServiceRequest project. + * DeleteNetworkAttachmentRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest * @instance */ - DeleteNetworkEdgeSecurityServiceRequest.prototype.project = ""; + DeleteNetworkAttachmentRequest.prototype.project = ""; /** - * DeleteNetworkEdgeSecurityServiceRequest region. + * DeleteNetworkAttachmentRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest * @instance */ - DeleteNetworkEdgeSecurityServiceRequest.prototype.region = ""; + DeleteNetworkAttachmentRequest.prototype.region = ""; /** - * DeleteNetworkEdgeSecurityServiceRequest requestId. + * DeleteNetworkAttachmentRequest requestId. * @member {string|null|undefined} requestId - * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest * @instance */ - DeleteNetworkEdgeSecurityServiceRequest.prototype.requestId = null; + DeleteNetworkAttachmentRequest.prototype.requestId = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(DeleteNetworkEdgeSecurityServiceRequest.prototype, "_requestId", { + Object.defineProperty(DeleteNetworkAttachmentRequest.prototype, "_requestId", { get: $util.oneOfGetter($oneOfFields = ["requestId"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new DeleteNetworkEdgeSecurityServiceRequest instance using the specified properties. + * Creates a new DeleteNetworkAttachmentRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteNetworkEdgeSecurityServiceRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest} DeleteNetworkEdgeSecurityServiceRequest instance + * @param {google.cloud.compute.v1beta.IDeleteNetworkAttachmentRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} DeleteNetworkAttachmentRequest instance */ - DeleteNetworkEdgeSecurityServiceRequest.create = function create(properties) { - return new DeleteNetworkEdgeSecurityServiceRequest(properties); + DeleteNetworkAttachmentRequest.create = function create(properties) { + return new DeleteNetworkAttachmentRequest(properties); }; /** - * Encodes the specified DeleteNetworkEdgeSecurityServiceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest.verify|verify} messages. + * Encodes the specified DeleteNetworkAttachmentRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteNetworkEdgeSecurityServiceRequest} message DeleteNetworkEdgeSecurityServiceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IDeleteNetworkAttachmentRequest} message DeleteNetworkAttachmentRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - DeleteNetworkEdgeSecurityServiceRequest.encode = function encode(message, writer) { + DeleteNetworkAttachmentRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); if (message.region != null && Object.hasOwnProperty.call(message, "region")) writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); - if (message.networkEdgeSecurityService != null && Object.hasOwnProperty.call(message, "networkEdgeSecurityService")) - writer.uint32(/* id 157011879, wireType 2 =*/1256095034).string(message.networkEdgeSecurityService); + if (message.networkAttachment != null && Object.hasOwnProperty.call(message, "networkAttachment")) + writer.uint32(/* id 224644052, wireType 2 =*/1797152418).string(message.networkAttachment); if (message.project != null && Object.hasOwnProperty.call(message, "project")) writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); return writer; }; /** - * Encodes the specified DeleteNetworkEdgeSecurityServiceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest.verify|verify} messages. + * Encodes the specified DeleteNetworkAttachmentRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest * @static - * @param {google.cloud.compute.v1beta.IDeleteNetworkEdgeSecurityServiceRequest} message DeleteNetworkEdgeSecurityServiceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IDeleteNetworkAttachmentRequest} message DeleteNetworkAttachmentRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - DeleteNetworkEdgeSecurityServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { + DeleteNetworkAttachmentRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a DeleteNetworkEdgeSecurityServiceRequest message from the specified reader or buffer. + * Decodes a DeleteNetworkAttachmentRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest} DeleteNetworkEdgeSecurityServiceRequest + * @returns {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} DeleteNetworkAttachmentRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - DeleteNetworkEdgeSecurityServiceRequest.decode = function decode(reader, length, error) { + DeleteNetworkAttachmentRequest.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.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { - case 157011879: { - message.networkEdgeSecurityService = reader.string(); + case 224644052: { + message.networkAttachment = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteNetworkAttachmentRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} DeleteNetworkAttachmentRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteNetworkAttachmentRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteNetworkAttachmentRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteNetworkAttachmentRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.networkAttachment != null && message.hasOwnProperty("networkAttachment")) + if (!$util.isString(message.networkAttachment)) + return "networkAttachment: string expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + return null; + }; + + /** + * Creates a DeleteNetworkAttachmentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} DeleteNetworkAttachmentRequest + */ + DeleteNetworkAttachmentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest(); + if (object.networkAttachment != null) + message.networkAttachment = String(object.networkAttachment); + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.requestId != null) + message.requestId = String(object.requestId); + return message; + }; + + /** + * Creates a plain object from a DeleteNetworkAttachmentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @static + * @param {google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest} message DeleteNetworkAttachmentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteNetworkAttachmentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.networkAttachment = ""; + object.project = ""; + } + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.networkAttachment != null && message.hasOwnProperty("networkAttachment")) + object.networkAttachment = message.networkAttachment; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + return object; + }; + + /** + * Converts this DeleteNetworkAttachmentRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteNetworkAttachmentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteNetworkAttachmentRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteNetworkAttachmentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.DeleteNetworkAttachmentRequest"; + }; + + return DeleteNetworkAttachmentRequest; + })(); + + v1beta.DeleteNetworkEdgeSecurityServiceRequest = (function() { + + /** + * Properties of a DeleteNetworkEdgeSecurityServiceRequest. + * @memberof google.cloud.compute.v1beta + * @interface IDeleteNetworkEdgeSecurityServiceRequest + * @property {string|null} [networkEdgeSecurityService] DeleteNetworkEdgeSecurityServiceRequest networkEdgeSecurityService + * @property {string|null} [project] DeleteNetworkEdgeSecurityServiceRequest project + * @property {string|null} [region] DeleteNetworkEdgeSecurityServiceRequest region + * @property {string|null} [requestId] DeleteNetworkEdgeSecurityServiceRequest requestId + */ + + /** + * Constructs a new DeleteNetworkEdgeSecurityServiceRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a DeleteNetworkEdgeSecurityServiceRequest. + * @implements IDeleteNetworkEdgeSecurityServiceRequest + * @constructor + * @param {google.cloud.compute.v1beta.IDeleteNetworkEdgeSecurityServiceRequest=} [properties] Properties to set + */ + function DeleteNetworkEdgeSecurityServiceRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteNetworkEdgeSecurityServiceRequest networkEdgeSecurityService. + * @member {string} networkEdgeSecurityService + * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @instance + */ + DeleteNetworkEdgeSecurityServiceRequest.prototype.networkEdgeSecurityService = ""; + + /** + * DeleteNetworkEdgeSecurityServiceRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @instance + */ + DeleteNetworkEdgeSecurityServiceRequest.prototype.project = ""; + + /** + * DeleteNetworkEdgeSecurityServiceRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @instance + */ + DeleteNetworkEdgeSecurityServiceRequest.prototype.region = ""; + + /** + * DeleteNetworkEdgeSecurityServiceRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @instance + */ + DeleteNetworkEdgeSecurityServiceRequest.prototype.requestId = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(DeleteNetworkEdgeSecurityServiceRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new DeleteNetworkEdgeSecurityServiceRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteNetworkEdgeSecurityServiceRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest} DeleteNetworkEdgeSecurityServiceRequest instance + */ + DeleteNetworkEdgeSecurityServiceRequest.create = function create(properties) { + return new DeleteNetworkEdgeSecurityServiceRequest(properties); + }; + + /** + * Encodes the specified DeleteNetworkEdgeSecurityServiceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteNetworkEdgeSecurityServiceRequest} message DeleteNetworkEdgeSecurityServiceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteNetworkEdgeSecurityServiceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.networkEdgeSecurityService != null && Object.hasOwnProperty.call(message, "networkEdgeSecurityService")) + writer.uint32(/* id 157011879, wireType 2 =*/1256095034).string(message.networkEdgeSecurityService); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + return writer; + }; + + /** + * Encodes the specified DeleteNetworkEdgeSecurityServiceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteNetworkEdgeSecurityServiceRequest} message DeleteNetworkEdgeSecurityServiceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteNetworkEdgeSecurityServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteNetworkEdgeSecurityServiceRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest} DeleteNetworkEdgeSecurityServiceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteNetworkEdgeSecurityServiceRequest.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.cloud.compute.v1beta.DeleteNetworkEdgeSecurityServiceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 157011879: { + message.networkEdgeSecurityService = reader.string(); break; } case 227560217: { @@ -756244,6 +759047,295 @@ return DeleteRegionInstanceTemplateRequest; })(); + v1beta.DeleteRegionInstantSnapshotGroupRequest = (function() { + + /** + * Properties of a DeleteRegionInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface IDeleteRegionInstantSnapshotGroupRequest + * @property {string|null} [instantSnapshotGroup] DeleteRegionInstantSnapshotGroupRequest instantSnapshotGroup + * @property {string|null} [project] DeleteRegionInstantSnapshotGroupRequest project + * @property {string|null} [region] DeleteRegionInstantSnapshotGroupRequest region + * @property {string|null} [requestId] DeleteRegionInstantSnapshotGroupRequest requestId + */ + + /** + * Constructs a new DeleteRegionInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a DeleteRegionInstantSnapshotGroupRequest. + * @implements IDeleteRegionInstantSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest=} [properties] Properties to set + */ + function DeleteRegionInstantSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteRegionInstantSnapshotGroupRequest instantSnapshotGroup. + * @member {string} instantSnapshotGroup + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @instance + */ + DeleteRegionInstantSnapshotGroupRequest.prototype.instantSnapshotGroup = ""; + + /** + * DeleteRegionInstantSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @instance + */ + DeleteRegionInstantSnapshotGroupRequest.prototype.project = ""; + + /** + * DeleteRegionInstantSnapshotGroupRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @instance + */ + DeleteRegionInstantSnapshotGroupRequest.prototype.region = ""; + + /** + * DeleteRegionInstantSnapshotGroupRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @instance + */ + DeleteRegionInstantSnapshotGroupRequest.prototype.requestId = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(DeleteRegionInstantSnapshotGroupRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new DeleteRegionInstantSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest} DeleteRegionInstantSnapshotGroupRequest instance + */ + DeleteRegionInstantSnapshotGroupRequest.create = function create(properties) { + return new DeleteRegionInstantSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified DeleteRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest} message DeleteRegionInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteRegionInstantSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.instantSnapshotGroup != null && Object.hasOwnProperty.call(message, "instantSnapshotGroup")) + writer.uint32(/* id 223180386, wireType 2 =*/1785443090).string(message.instantSnapshotGroup); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + return writer; + }; + + /** + * Encodes the specified DeleteRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest} message DeleteRegionInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteRegionInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest} DeleteRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteRegionInstantSnapshotGroupRequest.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.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 223180386: { + message.instantSnapshotGroup = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest} DeleteRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteRegionInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteRegionInstantSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteRegionInstantSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) + if (!$util.isString(message.instantSnapshotGroup)) + return "instantSnapshotGroup: string expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + return null; + }; + + /** + * Creates a DeleteRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest} DeleteRegionInstantSnapshotGroupRequest + */ + DeleteRegionInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest(); + if (object.instantSnapshotGroup != null) + message.instantSnapshotGroup = String(object.instantSnapshotGroup); + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.requestId != null) + message.requestId = String(object.requestId); + return message; + }; + + /** + * Creates a plain object from a DeleteRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest} message DeleteRegionInstantSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteRegionInstantSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.instantSnapshotGroup = ""; + object.project = ""; + } + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) + object.instantSnapshotGroup = message.instantSnapshotGroup; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + return object; + }; + + /** + * Converts this DeleteRegionInstantSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteRegionInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteRegionInstantSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteRegionInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest"; + }; + + return DeleteRegionInstantSnapshotGroupRequest; + })(); + v1beta.DeleteRegionInstantSnapshotRequest = (function() { /** @@ -763839,6 +766931,272 @@ return DeleteSignedUrlKeyBackendServiceRequest; })(); + v1beta.DeleteSnapshotGroupRequest = (function() { + + /** + * Properties of a DeleteSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface IDeleteSnapshotGroupRequest + * @property {string|null} [project] DeleteSnapshotGroupRequest project + * @property {string|null} [requestId] DeleteSnapshotGroupRequest requestId + * @property {string|null} [snapshotGroup] DeleteSnapshotGroupRequest snapshotGroup + */ + + /** + * Constructs a new DeleteSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a DeleteSnapshotGroupRequest. + * @implements IDeleteSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest=} [properties] Properties to set + */ + function DeleteSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DeleteSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @instance + */ + DeleteSnapshotGroupRequest.prototype.project = ""; + + /** + * DeleteSnapshotGroupRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @instance + */ + DeleteSnapshotGroupRequest.prototype.requestId = null; + + /** + * DeleteSnapshotGroupRequest snapshotGroup. + * @member {string} snapshotGroup + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @instance + */ + DeleteSnapshotGroupRequest.prototype.snapshotGroup = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(DeleteSnapshotGroupRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new DeleteSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.DeleteSnapshotGroupRequest} DeleteSnapshotGroupRequest instance + */ + DeleteSnapshotGroupRequest.create = function create(properties) { + return new DeleteSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified DeleteSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.DeleteSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest} message DeleteSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.snapshotGroup != null && Object.hasOwnProperty.call(message, "snapshotGroup")) + writer.uint32(/* id 84528196, wireType 2 =*/676225570).string(message.snapshotGroup); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + return writer; + }; + + /** + * Encodes the specified DeleteSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.DeleteSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest} message DeleteSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + DeleteSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a DeleteSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.DeleteSnapshotGroupRequest} DeleteSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteSnapshotGroupRequest.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.cloud.compute.v1beta.DeleteSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 227560217: { + message.project = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + case 84528196: { + message.snapshotGroup = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a DeleteSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.DeleteSnapshotGroupRequest} DeleteSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + DeleteSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a DeleteSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + DeleteSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + if (message.snapshotGroup != null && message.hasOwnProperty("snapshotGroup")) + if (!$util.isString(message.snapshotGroup)) + return "snapshotGroup: string expected"; + return null; + }; + + /** + * Creates a DeleteSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.DeleteSnapshotGroupRequest} DeleteSnapshotGroupRequest + */ + DeleteSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest(); + if (object.project != null) + message.project = String(object.project); + if (object.requestId != null) + message.requestId = String(object.requestId); + if (object.snapshotGroup != null) + message.snapshotGroup = String(object.snapshotGroup); + return message; + }; + + /** + * Creates a plain object from a DeleteSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.DeleteSnapshotGroupRequest} message DeleteSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.snapshotGroup = ""; + object.project = ""; + } + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.snapshotGroup != null && message.hasOwnProperty("snapshotGroup")) + object.snapshotGroup = message.snapshotGroup; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + return object; + }; + + /** + * Converts this DeleteSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.DeleteSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.DeleteSnapshotGroupRequest"; + }; + + return DeleteSnapshotGroupRequest; + })(); + v1beta.DeleteSnapshotRequest = (function() { /** @@ -785026,6 +788384,7 @@ * @property {string|null} [labelFingerprint] ExternalVpnGateway labelFingerprint * @property {Object.|null} [labels] ExternalVpnGateway labels * @property {string|null} [name] ExternalVpnGateway name + * @property {google.cloud.compute.v1beta.IExternalVpnGatewayParams|null} [params] ExternalVpnGateway params * @property {string|null} [redundancyType] ExternalVpnGateway redundancyType * @property {string|null} [selfLink] ExternalVpnGateway selfLink */ @@ -785111,6 +788470,14 @@ */ ExternalVpnGateway.prototype.name = null; + /** + * ExternalVpnGateway params. + * @member {google.cloud.compute.v1beta.IExternalVpnGatewayParams|null|undefined} params + * @memberof google.cloud.compute.v1beta.ExternalVpnGateway + * @instance + */ + ExternalVpnGateway.prototype.params = null; + /** * ExternalVpnGateway redundancyType. * @member {string|null|undefined} redundancyType @@ -785166,6 +788533,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(ExternalVpnGateway.prototype, "_params", { + get: $util.oneOfGetter($oneOfFields = ["params"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(ExternalVpnGateway.prototype, "_redundancyType", { get: $util.oneOfGetter($oneOfFields = ["redundancyType"]), @@ -785213,6 +788586,8 @@ $root.google.cloud.compute.v1beta.ExternalVpnGatewayInterface.encode(message.interfaces[i], writer.uint32(/* id 12073562, wireType 2 =*/96588498).fork()).ldelim(); if (message.creationTimestamp != null && Object.hasOwnProperty.call(message, "creationTimestamp")) writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.cloud.compute.v1beta.ExternalVpnGatewayParams.encode(message.params, writer.uint32(/* id 78313862, wireType 2 =*/626510898).fork()).ldelim(); if (message.labelFingerprint != null && Object.hasOwnProperty.call(message, "labelFingerprint")) writer.uint32(/* id 178124825, wireType 2 =*/1424998602).string(message.labelFingerprint); if (message.redundancyType != null && Object.hasOwnProperty.call(message, "redundancyType")) @@ -785313,6 +788688,10 @@ message.name = reader.string(); break; } + case 78313862: { + message.params = $root.google.cloud.compute.v1beta.ExternalVpnGatewayParams.decode(reader, reader.uint32()); + break; + } case 271443740: { message.redundancyType = reader.string(); break; @@ -785404,6 +788783,14 @@ if (!$util.isString(message.name)) return "name: string expected"; } + if (message.params != null && message.hasOwnProperty("params")) { + properties._params = 1; + { + var error = $root.google.cloud.compute.v1beta.ExternalVpnGatewayParams.verify(message.params); + if (error) + return "params." + error; + } + } if (message.redundancyType != null && message.hasOwnProperty("redundancyType")) { properties._redundancyType = 1; if (!$util.isString(message.redundancyType)) @@ -785465,6 +788852,11 @@ } if (object.name != null) message.name = String(object.name); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.cloud.compute.v1beta.ExternalVpnGateway.params: object expected"); + message.params = $root.google.cloud.compute.v1beta.ExternalVpnGatewayParams.fromObject(object.params); + } if (object.redundancyType != null) message.redundancyType = String(object.redundancyType); if (object.selfLink != null) @@ -785517,6 +788909,11 @@ if (options.oneofs) object._creationTimestamp = "creationTimestamp"; } + if (message.params != null && message.hasOwnProperty("params")) { + object.params = $root.google.cloud.compute.v1beta.ExternalVpnGatewayParams.toObject(message.params, options); + if (options.oneofs) + object._params = "params"; + } if (message.labelFingerprint != null && message.hasOwnProperty("labelFingerprint")) { object.labelFingerprint = message.labelFingerprint; if (options.oneofs) @@ -786311,6 +789708,246 @@ return ExternalVpnGatewayList; })(); + v1beta.ExternalVpnGatewayParams = (function() { + + /** + * Properties of an ExternalVpnGatewayParams. + * @memberof google.cloud.compute.v1beta + * @interface IExternalVpnGatewayParams + * @property {Object.|null} [resourceManagerTags] ExternalVpnGatewayParams resourceManagerTags + */ + + /** + * Constructs a new ExternalVpnGatewayParams. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an ExternalVpnGatewayParams. + * @implements IExternalVpnGatewayParams + * @constructor + * @param {google.cloud.compute.v1beta.IExternalVpnGatewayParams=} [properties] Properties to set + */ + function ExternalVpnGatewayParams(properties) { + this.resourceManagerTags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExternalVpnGatewayParams resourceManagerTags. + * @member {Object.} resourceManagerTags + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @instance + */ + ExternalVpnGatewayParams.prototype.resourceManagerTags = $util.emptyObject; + + /** + * Creates a new ExternalVpnGatewayParams instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.IExternalVpnGatewayParams=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ExternalVpnGatewayParams} ExternalVpnGatewayParams instance + */ + ExternalVpnGatewayParams.create = function create(properties) { + return new ExternalVpnGatewayParams(properties); + }; + + /** + * Encodes the specified ExternalVpnGatewayParams message. Does not implicitly {@link google.cloud.compute.v1beta.ExternalVpnGatewayParams.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.IExternalVpnGatewayParams} message ExternalVpnGatewayParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExternalVpnGatewayParams.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceManagerTags != null && Object.hasOwnProperty.call(message, "resourceManagerTags")) + for (var keys = Object.keys(message.resourceManagerTags), i = 0; i < keys.length; ++i) + writer.uint32(/* id 377671164, wireType 2 =*/3021369314).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourceManagerTags[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified ExternalVpnGatewayParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ExternalVpnGatewayParams.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.IExternalVpnGatewayParams} message ExternalVpnGatewayParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExternalVpnGatewayParams.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExternalVpnGatewayParams message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ExternalVpnGatewayParams} ExternalVpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExternalVpnGatewayParams.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.cloud.compute.v1beta.ExternalVpnGatewayParams(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 377671164: { + if (message.resourceManagerTags === $util.emptyObject) + message.resourceManagerTags = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.resourceManagerTags[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExternalVpnGatewayParams message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ExternalVpnGatewayParams} ExternalVpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExternalVpnGatewayParams.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExternalVpnGatewayParams message. + * @function verify + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExternalVpnGatewayParams.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceManagerTags != null && message.hasOwnProperty("resourceManagerTags")) { + if (!$util.isObject(message.resourceManagerTags)) + return "resourceManagerTags: object expected"; + var key = Object.keys(message.resourceManagerTags); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.resourceManagerTags[key[i]])) + return "resourceManagerTags: string{k:string} expected"; + } + return null; + }; + + /** + * Creates an ExternalVpnGatewayParams message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ExternalVpnGatewayParams} ExternalVpnGatewayParams + */ + ExternalVpnGatewayParams.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ExternalVpnGatewayParams) + return object; + var message = new $root.google.cloud.compute.v1beta.ExternalVpnGatewayParams(); + if (object.resourceManagerTags) { + if (typeof object.resourceManagerTags !== "object") + throw TypeError(".google.cloud.compute.v1beta.ExternalVpnGatewayParams.resourceManagerTags: object expected"); + message.resourceManagerTags = {}; + for (var keys = Object.keys(object.resourceManagerTags), i = 0; i < keys.length; ++i) + message.resourceManagerTags[keys[i]] = String(object.resourceManagerTags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from an ExternalVpnGatewayParams message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.ExternalVpnGatewayParams} message ExternalVpnGatewayParams + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExternalVpnGatewayParams.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.resourceManagerTags = {}; + var keys2; + if (message.resourceManagerTags && (keys2 = Object.keys(message.resourceManagerTags)).length) { + object.resourceManagerTags = {}; + for (var j = 0; j < keys2.length; ++j) + object.resourceManagerTags[keys2[j]] = message.resourceManagerTags[keys2[j]]; + } + return object; + }; + + /** + * Converts this ExternalVpnGatewayParams to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @instance + * @returns {Object.} JSON object + */ + ExternalVpnGatewayParams.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExternalVpnGatewayParams + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ExternalVpnGatewayParams + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExternalVpnGatewayParams.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ExternalVpnGatewayParams"; + }; + + return ExternalVpnGatewayParams; + })(); + v1beta.FileContentBuffer = (function() { /** @@ -789838,13 +793475,17 @@ * @name google.cloud.compute.v1beta.FirewallPolicy.PolicyType * @enum {number} * @property {number} UNDEFINED_POLICY_TYPE=0 UNDEFINED_POLICY_TYPE value + * @property {number} RDMA_FALCON_POLICY=66315047 RDMA_FALCON_POLICY value * @property {number} RDMA_ROCE_POLICY=148757145 RDMA_ROCE_POLICY value + * @property {number} ULL_POLICY=100494364 ULL_POLICY value * @property {number} VPC_POLICY=74319208 VPC_POLICY value */ FirewallPolicy.PolicyType = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "UNDEFINED_POLICY_TYPE"] = 0; + values[valuesById[66315047] = "RDMA_FALCON_POLICY"] = 66315047; values[valuesById[148757145] = "RDMA_ROCE_POLICY"] = 148757145; + values[valuesById[100494364] = "ULL_POLICY"] = 100494364; values[valuesById[74319208] = "VPC_POLICY"] = 74319208; return values; })(); @@ -796908,6 +800549,7 @@ * Properties of a FutureReservation. * @memberof google.cloud.compute.v1beta * @interface IFutureReservation + * @property {google.cloud.compute.v1beta.IReservationAdvancedDeploymentControl|null} [advancedDeploymentControl] FutureReservation advancedDeploymentControl * @property {google.cloud.compute.v1beta.IAllocationAggregateReservation|null} [aggregateReservation] FutureReservation aggregateReservation * @property {string|null} [autoCreatedReservationsDeleteTime] FutureReservation autoCreatedReservationsDeleteTime * @property {google.cloud.compute.v1beta.IDuration|null} [autoCreatedReservationsDuration] FutureReservation autoCreatedReservationsDuration @@ -796951,6 +800593,14 @@ this[keys[i]] = properties[keys[i]]; } + /** + * FutureReservation advancedDeploymentControl. + * @member {google.cloud.compute.v1beta.IReservationAdvancedDeploymentControl|null|undefined} advancedDeploymentControl + * @memberof google.cloud.compute.v1beta.FutureReservation + * @instance + */ + FutureReservation.prototype.advancedDeploymentControl = null; + /** * FutureReservation aggregateReservation. * @member {google.cloud.compute.v1beta.IAllocationAggregateReservation|null|undefined} aggregateReservation @@ -797162,6 +800812,12 @@ // OneOf field names bound to virtual getters and setters var $oneOfFields; + // Virtual OneOf for proto3 optional field + Object.defineProperty(FutureReservation.prototype, "_advancedDeploymentControl", { + get: $util.oneOfGetter($oneOfFields = ["advancedDeploymentControl"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(FutureReservation.prototype, "_aggregateReservation", { get: $util.oneOfGetter($oneOfFields = ["aggregateReservation"]), @@ -797382,6 +801038,8 @@ writer.uint32(/* id 353759497, wireType 0 =*/2830075976).bool(message.enableEmergentMaintenance); if (message.deploymentType != null && Object.hasOwnProperty.call(message, "deploymentType")) writer.uint32(/* id 396722292, wireType 2 =*/3173778338).string(message.deploymentType); + if (message.advancedDeploymentControl != null && Object.hasOwnProperty.call(message, "advancedDeploymentControl")) + $root.google.cloud.compute.v1beta.ReservationAdvancedDeploymentControl.encode(message.advancedDeploymentControl, writer.uint32(/* id 410618144, wireType 2 =*/3284945154).fork()).ldelim(); if (message.description != null && Object.hasOwnProperty.call(message, "description")) writer.uint32(/* id 422937596, wireType 2 =*/3383500770).string(message.description); if (message.timeWindow != null && Object.hasOwnProperty.call(message, "timeWindow")) @@ -797430,6 +801088,10 @@ if (tag === error) break; switch (tag >>> 3) { + case 410618144: { + message.advancedDeploymentControl = $root.google.cloud.compute.v1beta.ReservationAdvancedDeploymentControl.decode(reader, reader.uint32()); + break; + } case 291567948: { message.aggregateReservation = $root.google.cloud.compute.v1beta.AllocationAggregateReservation.decode(reader, reader.uint32()); break; @@ -797570,6 +801232,14 @@ if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; + if (message.advancedDeploymentControl != null && message.hasOwnProperty("advancedDeploymentControl")) { + properties._advancedDeploymentControl = 1; + { + var error = $root.google.cloud.compute.v1beta.ReservationAdvancedDeploymentControl.verify(message.advancedDeploymentControl); + if (error) + return "advancedDeploymentControl." + error; + } + } if (message.aggregateReservation != null && message.hasOwnProperty("aggregateReservation")) { properties._aggregateReservation = 1; { @@ -797736,6 +801406,11 @@ if (object instanceof $root.google.cloud.compute.v1beta.FutureReservation) return object; var message = new $root.google.cloud.compute.v1beta.FutureReservation(); + if (object.advancedDeploymentControl != null) { + if (typeof object.advancedDeploymentControl !== "object") + throw TypeError(".google.cloud.compute.v1beta.FutureReservation.advancedDeploymentControl: object expected"); + message.advancedDeploymentControl = $root.google.cloud.compute.v1beta.ReservationAdvancedDeploymentControl.fromObject(object.advancedDeploymentControl); + } if (object.aggregateReservation != null) { if (typeof object.aggregateReservation !== "object") throw TypeError(".google.cloud.compute.v1beta.FutureReservation.aggregateReservation: object expected"); @@ -797935,6 +801610,11 @@ if (options.oneofs) object._deploymentType = "deploymentType"; } + if (message.advancedDeploymentControl != null && message.hasOwnProperty("advancedDeploymentControl")) { + object.advancedDeploymentControl = $root.google.cloud.compute.v1beta.ReservationAdvancedDeploymentControl.toObject(message.advancedDeploymentControl, options); + if (options.oneofs) + object._advancedDeploymentControl = "advancedDeploymentControl"; + } if (message.description != null && message.hasOwnProperty("description")) { object.description = message.description; if (options.oneofs) @@ -816587,27 +820267,27 @@ return GetIamPolicyInstanceTemplateRequest; })(); - v1beta.GetIamPolicyInstantSnapshotRequest = (function() { + v1beta.GetIamPolicyInstantSnapshotGroupRequest = (function() { /** - * Properties of a GetIamPolicyInstantSnapshotRequest. + * Properties of a GetIamPolicyInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface IGetIamPolicyInstantSnapshotRequest - * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyInstantSnapshotRequest optionsRequestedPolicyVersion - * @property {string|null} [project] GetIamPolicyInstantSnapshotRequest project - * @property {string|null} [resource] GetIamPolicyInstantSnapshotRequest resource - * @property {string|null} [zone] GetIamPolicyInstantSnapshotRequest zone + * @interface IGetIamPolicyInstantSnapshotGroupRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyInstantSnapshotGroupRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicyInstantSnapshotGroupRequest project + * @property {string|null} [resource] GetIamPolicyInstantSnapshotGroupRequest resource + * @property {string|null} [zone] GetIamPolicyInstantSnapshotGroupRequest zone */ /** - * Constructs a new GetIamPolicyInstantSnapshotRequest. + * Constructs a new GetIamPolicyInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a GetIamPolicyInstantSnapshotRequest. - * @implements IGetIamPolicyInstantSnapshotRequest + * @classdesc Represents a GetIamPolicyInstantSnapshotGroupRequest. + * @implements IGetIamPolicyInstantSnapshotGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest=} [properties] Properties to set */ - function GetIamPolicyInstantSnapshotRequest(properties) { + function GetIamPolicyInstantSnapshotGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -816615,68 +820295,68 @@ } /** - * GetIamPolicyInstantSnapshotRequest optionsRequestedPolicyVersion. + * GetIamPolicyInstantSnapshotGroupRequest optionsRequestedPolicyVersion. * @member {number|null|undefined} optionsRequestedPolicyVersion - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @instance */ - GetIamPolicyInstantSnapshotRequest.prototype.optionsRequestedPolicyVersion = null; + GetIamPolicyInstantSnapshotGroupRequest.prototype.optionsRequestedPolicyVersion = null; /** - * GetIamPolicyInstantSnapshotRequest project. + * GetIamPolicyInstantSnapshotGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @instance */ - GetIamPolicyInstantSnapshotRequest.prototype.project = ""; + GetIamPolicyInstantSnapshotGroupRequest.prototype.project = ""; /** - * GetIamPolicyInstantSnapshotRequest resource. + * GetIamPolicyInstantSnapshotGroupRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @instance */ - GetIamPolicyInstantSnapshotRequest.prototype.resource = ""; + GetIamPolicyInstantSnapshotGroupRequest.prototype.resource = ""; /** - * GetIamPolicyInstantSnapshotRequest zone. + * GetIamPolicyInstantSnapshotGroupRequest zone. * @member {string} zone - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @instance */ - GetIamPolicyInstantSnapshotRequest.prototype.zone = ""; + GetIamPolicyInstantSnapshotGroupRequest.prototype.zone = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(GetIamPolicyInstantSnapshotRequest.prototype, "_optionsRequestedPolicyVersion", { + Object.defineProperty(GetIamPolicyInstantSnapshotGroupRequest.prototype, "_optionsRequestedPolicyVersion", { get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new GetIamPolicyInstantSnapshotRequest instance using the specified properties. + * Creates a new GetIamPolicyInstantSnapshotGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} GetIamPolicyInstantSnapshotRequest instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest} GetIamPolicyInstantSnapshotGroupRequest instance */ - GetIamPolicyInstantSnapshotRequest.create = function create(properties) { - return new GetIamPolicyInstantSnapshotRequest(properties); + GetIamPolicyInstantSnapshotGroupRequest.create = function create(properties) { + return new GetIamPolicyInstantSnapshotGroupRequest(properties); }; /** - * Encodes the specified GetIamPolicyInstantSnapshotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotRequest} message GetIamPolicyInstantSnapshotRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest} message GetIamPolicyInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyInstantSnapshotRequest.encode = function encode(message, writer) { + GetIamPolicyInstantSnapshotGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) @@ -816691,33 +820371,33 @@ }; /** - * Encodes the specified GetIamPolicyInstantSnapshotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotRequest} message GetIamPolicyInstantSnapshotRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest} message GetIamPolicyInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyInstantSnapshotRequest.encodeDelimited = function encodeDelimited(message, writer) { + GetIamPolicyInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a GetIamPolicyInstantSnapshotRequest message from the specified reader or buffer. + * Decodes a GetIamPolicyInstantSnapshotGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} GetIamPolicyInstantSnapshotRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest} GetIamPolicyInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyInstantSnapshotRequest.decode = function decode(reader, length, error) { + GetIamPolicyInstantSnapshotGroupRequest.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.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -816748,30 +820428,30 @@ }; /** - * Decodes a GetIamPolicyInstantSnapshotRequest message from the specified reader or buffer, length delimited. + * Decodes a GetIamPolicyInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} GetIamPolicyInstantSnapshotRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest} GetIamPolicyInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyInstantSnapshotRequest.decodeDelimited = function decodeDelimited(reader) { + GetIamPolicyInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a GetIamPolicyInstantSnapshotRequest message. + * Verifies a GetIamPolicyInstantSnapshotGroupRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GetIamPolicyInstantSnapshotRequest.verify = function verify(message) { + GetIamPolicyInstantSnapshotGroupRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -816793,17 +820473,17 @@ }; /** - * Creates a GetIamPolicyInstantSnapshotRequest message from a plain object. Also converts values to their respective internal types. + * Creates a GetIamPolicyInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} GetIamPolicyInstantSnapshotRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest} GetIamPolicyInstantSnapshotGroupRequest */ - GetIamPolicyInstantSnapshotRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest) + GetIamPolicyInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest) return object; - var message = new $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest(); + var message = new $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest(); if (object.optionsRequestedPolicyVersion != null) message.optionsRequestedPolicyVersion = object.optionsRequestedPolicyVersion | 0; if (object.project != null) @@ -816816,15 +820496,15 @@ }; /** - * Creates a plain object from a GetIamPolicyInstantSnapshotRequest message. Also converts values to other types if specified. + * Creates a plain object from a GetIamPolicyInstantSnapshotGroupRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} message GetIamPolicyInstantSnapshotRequest + * @param {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest} message GetIamPolicyInstantSnapshotGroupRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GetIamPolicyInstantSnapshotRequest.toObject = function toObject(message, options) { + GetIamPolicyInstantSnapshotGroupRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -816848,54 +820528,55 @@ }; /** - * Converts this GetIamPolicyInstantSnapshotRequest to JSON. + * Converts this GetIamPolicyInstantSnapshotGroupRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @instance * @returns {Object.} JSON object */ - GetIamPolicyInstantSnapshotRequest.prototype.toJSON = function toJSON() { + GetIamPolicyInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for GetIamPolicyInstantSnapshotRequest + * Gets the default type url for GetIamPolicyInstantSnapshotGroupRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - GetIamPolicyInstantSnapshotRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + GetIamPolicyInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest"; }; - return GetIamPolicyInstantSnapshotRequest; + return GetIamPolicyInstantSnapshotGroupRequest; })(); - v1beta.GetIamPolicyInterconnectAttachmentGroupRequest = (function() { + v1beta.GetIamPolicyInstantSnapshotRequest = (function() { /** - * Properties of a GetIamPolicyInterconnectAttachmentGroupRequest. + * Properties of a GetIamPolicyInstantSnapshotRequest. * @memberof google.cloud.compute.v1beta - * @interface IGetIamPolicyInterconnectAttachmentGroupRequest - * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyInterconnectAttachmentGroupRequest optionsRequestedPolicyVersion - * @property {string|null} [project] GetIamPolicyInterconnectAttachmentGroupRequest project - * @property {string|null} [resource] GetIamPolicyInterconnectAttachmentGroupRequest resource + * @interface IGetIamPolicyInstantSnapshotRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyInstantSnapshotRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicyInstantSnapshotRequest project + * @property {string|null} [resource] GetIamPolicyInstantSnapshotRequest resource + * @property {string|null} [zone] GetIamPolicyInstantSnapshotRequest zone */ /** - * Constructs a new GetIamPolicyInterconnectAttachmentGroupRequest. + * Constructs a new GetIamPolicyInstantSnapshotRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a GetIamPolicyInterconnectAttachmentGroupRequest. - * @implements IGetIamPolicyInterconnectAttachmentGroupRequest + * @classdesc Represents a GetIamPolicyInstantSnapshotRequest. + * @implements IGetIamPolicyInstantSnapshotRequest * @constructor - * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectAttachmentGroupRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotRequest=} [properties] Properties to set */ - function GetIamPolicyInterconnectAttachmentGroupRequest(properties) { + function GetIamPolicyInstantSnapshotRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -816903,62 +820584,72 @@ } /** - * GetIamPolicyInterconnectAttachmentGroupRequest optionsRequestedPolicyVersion. + * GetIamPolicyInstantSnapshotRequest optionsRequestedPolicyVersion. * @member {number|null|undefined} optionsRequestedPolicyVersion - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @instance */ - GetIamPolicyInterconnectAttachmentGroupRequest.prototype.optionsRequestedPolicyVersion = null; + GetIamPolicyInstantSnapshotRequest.prototype.optionsRequestedPolicyVersion = null; /** - * GetIamPolicyInterconnectAttachmentGroupRequest project. + * GetIamPolicyInstantSnapshotRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @instance */ - GetIamPolicyInterconnectAttachmentGroupRequest.prototype.project = ""; + GetIamPolicyInstantSnapshotRequest.prototype.project = ""; /** - * GetIamPolicyInterconnectAttachmentGroupRequest resource. + * GetIamPolicyInstantSnapshotRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @instance */ - GetIamPolicyInterconnectAttachmentGroupRequest.prototype.resource = ""; + GetIamPolicyInstantSnapshotRequest.prototype.resource = ""; + + /** + * GetIamPolicyInstantSnapshotRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest + * @instance + */ + GetIamPolicyInstantSnapshotRequest.prototype.zone = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(GetIamPolicyInterconnectAttachmentGroupRequest.prototype, "_optionsRequestedPolicyVersion", { + Object.defineProperty(GetIamPolicyInstantSnapshotRequest.prototype, "_optionsRequestedPolicyVersion", { get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new GetIamPolicyInterconnectAttachmentGroupRequest instance using the specified properties. + * Creates a new GetIamPolicyInstantSnapshotRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectAttachmentGroupRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} GetIamPolicyInterconnectAttachmentGroupRequest instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} GetIamPolicyInstantSnapshotRequest instance */ - GetIamPolicyInterconnectAttachmentGroupRequest.create = function create(properties) { - return new GetIamPolicyInterconnectAttachmentGroupRequest(properties); + GetIamPolicyInstantSnapshotRequest.create = function create(properties) { + return new GetIamPolicyInstantSnapshotRequest(properties); }; /** - * Encodes the specified GetIamPolicyInterconnectAttachmentGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyInstantSnapshotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectAttachmentGroupRequest} message GetIamPolicyInterconnectAttachmentGroupRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotRequest} message GetIamPolicyInstantSnapshotRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyInterconnectAttachmentGroupRequest.encode = function encode(message, writer) { + GetIamPolicyInstantSnapshotRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); if (message.project != null && Object.hasOwnProperty.call(message, "project")) @@ -816969,33 +820660,33 @@ }; /** - * Encodes the specified GetIamPolicyInterconnectAttachmentGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyInstantSnapshotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectAttachmentGroupRequest} message GetIamPolicyInterconnectAttachmentGroupRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotRequest} message GetIamPolicyInstantSnapshotRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyInterconnectAttachmentGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + GetIamPolicyInstantSnapshotRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a GetIamPolicyInterconnectAttachmentGroupRequest message from the specified reader or buffer. + * Decodes a GetIamPolicyInstantSnapshotRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} GetIamPolicyInterconnectAttachmentGroupRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} GetIamPolicyInstantSnapshotRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyInterconnectAttachmentGroupRequest.decode = function decode(reader, length, error) { + GetIamPolicyInstantSnapshotRequest.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.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -817013,6 +820704,10 @@ message.resource = reader.string(); break; } + case 3744684: { + message.zone = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -817022,30 +820717,30 @@ }; /** - * Decodes a GetIamPolicyInterconnectAttachmentGroupRequest message from the specified reader or buffer, length delimited. + * Decodes a GetIamPolicyInstantSnapshotRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} GetIamPolicyInterconnectAttachmentGroupRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} GetIamPolicyInstantSnapshotRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyInterconnectAttachmentGroupRequest.decodeDelimited = function decodeDelimited(reader) { + GetIamPolicyInstantSnapshotRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a GetIamPolicyInterconnectAttachmentGroupRequest message. + * Verifies a GetIamPolicyInstantSnapshotRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GetIamPolicyInterconnectAttachmentGroupRequest.verify = function verify(message) { + GetIamPolicyInstantSnapshotRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -817060,47 +820755,55 @@ if (message.resource != null && message.hasOwnProperty("resource")) if (!$util.isString(message.resource)) return "resource: string expected"; + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; return null; }; /** - * Creates a GetIamPolicyInterconnectAttachmentGroupRequest message from a plain object. Also converts values to their respective internal types. + * Creates a GetIamPolicyInstantSnapshotRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} GetIamPolicyInterconnectAttachmentGroupRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} GetIamPolicyInstantSnapshotRequest */ - GetIamPolicyInterconnectAttachmentGroupRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest) + GetIamPolicyInstantSnapshotRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest) return object; - var message = new $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest(); + var message = new $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest(); if (object.optionsRequestedPolicyVersion != null) message.optionsRequestedPolicyVersion = object.optionsRequestedPolicyVersion | 0; if (object.project != null) message.project = String(object.project); if (object.resource != null) message.resource = String(object.resource); + if (object.zone != null) + message.zone = String(object.zone); return message; }; /** - * Creates a plain object from a GetIamPolicyInterconnectAttachmentGroupRequest message. Also converts values to other types if specified. + * Creates a plain object from a GetIamPolicyInstantSnapshotRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static - * @param {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} message GetIamPolicyInterconnectAttachmentGroupRequest + * @param {google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest} message GetIamPolicyInstantSnapshotRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GetIamPolicyInterconnectAttachmentGroupRequest.toObject = function toObject(message, options) { + GetIamPolicyInstantSnapshotRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { + object.zone = ""; object.resource = ""; object.project = ""; } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; if (message.resource != null && message.hasOwnProperty("resource")) object.resource = message.resource; if (message.project != null && message.hasOwnProperty("project")) @@ -817114,54 +820817,54 @@ }; /** - * Converts this GetIamPolicyInterconnectAttachmentGroupRequest to JSON. + * Converts this GetIamPolicyInstantSnapshotRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @instance * @returns {Object.} JSON object */ - GetIamPolicyInterconnectAttachmentGroupRequest.prototype.toJSON = function toJSON() { + GetIamPolicyInstantSnapshotRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for GetIamPolicyInterconnectAttachmentGroupRequest + * Gets the default type url for GetIamPolicyInstantSnapshotRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - GetIamPolicyInterconnectAttachmentGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + GetIamPolicyInstantSnapshotRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotRequest"; }; - return GetIamPolicyInterconnectAttachmentGroupRequest; + return GetIamPolicyInstantSnapshotRequest; })(); - v1beta.GetIamPolicyInterconnectGroupRequest = (function() { + v1beta.GetIamPolicyInterconnectAttachmentGroupRequest = (function() { /** - * Properties of a GetIamPolicyInterconnectGroupRequest. + * Properties of a GetIamPolicyInterconnectAttachmentGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface IGetIamPolicyInterconnectGroupRequest - * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyInterconnectGroupRequest optionsRequestedPolicyVersion - * @property {string|null} [project] GetIamPolicyInterconnectGroupRequest project - * @property {string|null} [resource] GetIamPolicyInterconnectGroupRequest resource + * @interface IGetIamPolicyInterconnectAttachmentGroupRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyInterconnectAttachmentGroupRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicyInterconnectAttachmentGroupRequest project + * @property {string|null} [resource] GetIamPolicyInterconnectAttachmentGroupRequest resource */ /** - * Constructs a new GetIamPolicyInterconnectGroupRequest. + * Constructs a new GetIamPolicyInterconnectAttachmentGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a GetIamPolicyInterconnectGroupRequest. - * @implements IGetIamPolicyInterconnectGroupRequest + * @classdesc Represents a GetIamPolicyInterconnectAttachmentGroupRequest. + * @implements IGetIamPolicyInterconnectAttachmentGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectGroupRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectAttachmentGroupRequest=} [properties] Properties to set */ - function GetIamPolicyInterconnectGroupRequest(properties) { + function GetIamPolicyInterconnectAttachmentGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -817169,60 +820872,60 @@ } /** - * GetIamPolicyInterconnectGroupRequest optionsRequestedPolicyVersion. + * GetIamPolicyInterconnectAttachmentGroupRequest optionsRequestedPolicyVersion. * @member {number|null|undefined} optionsRequestedPolicyVersion - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @instance */ - GetIamPolicyInterconnectGroupRequest.prototype.optionsRequestedPolicyVersion = null; + GetIamPolicyInterconnectAttachmentGroupRequest.prototype.optionsRequestedPolicyVersion = null; /** - * GetIamPolicyInterconnectGroupRequest project. + * GetIamPolicyInterconnectAttachmentGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @instance */ - GetIamPolicyInterconnectGroupRequest.prototype.project = ""; + GetIamPolicyInterconnectAttachmentGroupRequest.prototype.project = ""; /** - * GetIamPolicyInterconnectGroupRequest resource. + * GetIamPolicyInterconnectAttachmentGroupRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @instance */ - GetIamPolicyInterconnectGroupRequest.prototype.resource = ""; + GetIamPolicyInterconnectAttachmentGroupRequest.prototype.resource = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(GetIamPolicyInterconnectGroupRequest.prototype, "_optionsRequestedPolicyVersion", { + Object.defineProperty(GetIamPolicyInterconnectAttachmentGroupRequest.prototype, "_optionsRequestedPolicyVersion", { get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new GetIamPolicyInterconnectGroupRequest instance using the specified properties. + * Creates a new GetIamPolicyInterconnectAttachmentGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectGroupRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} GetIamPolicyInterconnectGroupRequest instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectAttachmentGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} GetIamPolicyInterconnectAttachmentGroupRequest instance */ - GetIamPolicyInterconnectGroupRequest.create = function create(properties) { - return new GetIamPolicyInterconnectGroupRequest(properties); + GetIamPolicyInterconnectAttachmentGroupRequest.create = function create(properties) { + return new GetIamPolicyInterconnectAttachmentGroupRequest(properties); }; /** - * Encodes the specified GetIamPolicyInterconnectGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyInterconnectAttachmentGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectGroupRequest} message GetIamPolicyInterconnectGroupRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectAttachmentGroupRequest} message GetIamPolicyInterconnectAttachmentGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyInterconnectGroupRequest.encode = function encode(message, writer) { + GetIamPolicyInterconnectAttachmentGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) @@ -817235,33 +820938,33 @@ }; /** - * Encodes the specified GetIamPolicyInterconnectGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyInterconnectAttachmentGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectGroupRequest} message GetIamPolicyInterconnectGroupRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectAttachmentGroupRequest} message GetIamPolicyInterconnectAttachmentGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyInterconnectGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + GetIamPolicyInterconnectAttachmentGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a GetIamPolicyInterconnectGroupRequest message from the specified reader or buffer. + * Decodes a GetIamPolicyInterconnectAttachmentGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} GetIamPolicyInterconnectGroupRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} GetIamPolicyInterconnectAttachmentGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyInterconnectGroupRequest.decode = function decode(reader, length, error) { + GetIamPolicyInterconnectAttachmentGroupRequest.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.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -817288,30 +820991,30 @@ }; /** - * Decodes a GetIamPolicyInterconnectGroupRequest message from the specified reader or buffer, length delimited. + * Decodes a GetIamPolicyInterconnectAttachmentGroupRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} GetIamPolicyInterconnectGroupRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} GetIamPolicyInterconnectAttachmentGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyInterconnectGroupRequest.decodeDelimited = function decodeDelimited(reader) { + GetIamPolicyInterconnectAttachmentGroupRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a GetIamPolicyInterconnectGroupRequest message. + * Verifies a GetIamPolicyInterconnectAttachmentGroupRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GetIamPolicyInterconnectGroupRequest.verify = function verify(message) { + GetIamPolicyInterconnectAttachmentGroupRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -817330,17 +821033,17 @@ }; /** - * Creates a GetIamPolicyInterconnectGroupRequest message from a plain object. Also converts values to their respective internal types. + * Creates a GetIamPolicyInterconnectAttachmentGroupRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} GetIamPolicyInterconnectGroupRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} GetIamPolicyInterconnectAttachmentGroupRequest */ - GetIamPolicyInterconnectGroupRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest) + GetIamPolicyInterconnectAttachmentGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest) return object; - var message = new $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest(); + var message = new $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest(); if (object.optionsRequestedPolicyVersion != null) message.optionsRequestedPolicyVersion = object.optionsRequestedPolicyVersion | 0; if (object.project != null) @@ -817351,15 +821054,15 @@ }; /** - * Creates a plain object from a GetIamPolicyInterconnectGroupRequest message. Also converts values to other types if specified. + * Creates a plain object from a GetIamPolicyInterconnectAttachmentGroupRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static - * @param {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} message GetIamPolicyInterconnectGroupRequest + * @param {google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest} message GetIamPolicyInterconnectAttachmentGroupRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GetIamPolicyInterconnectGroupRequest.toObject = function toObject(message, options) { + GetIamPolicyInterconnectAttachmentGroupRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -817380,54 +821083,54 @@ }; /** - * Converts this GetIamPolicyInterconnectGroupRequest to JSON. + * Converts this GetIamPolicyInterconnectAttachmentGroupRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @instance * @returns {Object.} JSON object */ - GetIamPolicyInterconnectGroupRequest.prototype.toJSON = function toJSON() { + GetIamPolicyInterconnectAttachmentGroupRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for GetIamPolicyInterconnectGroupRequest + * Gets the default type url for GetIamPolicyInterconnectAttachmentGroupRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - GetIamPolicyInterconnectGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + GetIamPolicyInterconnectAttachmentGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyInterconnectAttachmentGroupRequest"; }; - return GetIamPolicyInterconnectGroupRequest; + return GetIamPolicyInterconnectAttachmentGroupRequest; })(); - v1beta.GetIamPolicyLicenseRequest = (function() { + v1beta.GetIamPolicyInterconnectGroupRequest = (function() { /** - * Properties of a GetIamPolicyLicenseRequest. + * Properties of a GetIamPolicyInterconnectGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface IGetIamPolicyLicenseRequest - * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyLicenseRequest optionsRequestedPolicyVersion - * @property {string|null} [project] GetIamPolicyLicenseRequest project - * @property {string|null} [resource] GetIamPolicyLicenseRequest resource + * @interface IGetIamPolicyInterconnectGroupRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyInterconnectGroupRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicyInterconnectGroupRequest project + * @property {string|null} [resource] GetIamPolicyInterconnectGroupRequest resource */ /** - * Constructs a new GetIamPolicyLicenseRequest. + * Constructs a new GetIamPolicyInterconnectGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a GetIamPolicyLicenseRequest. - * @implements IGetIamPolicyLicenseRequest + * @classdesc Represents a GetIamPolicyInterconnectGroupRequest. + * @implements IGetIamPolicyInterconnectGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.IGetIamPolicyLicenseRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectGroupRequest=} [properties] Properties to set */ - function GetIamPolicyLicenseRequest(properties) { + function GetIamPolicyInterconnectGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -817435,60 +821138,60 @@ } /** - * GetIamPolicyLicenseRequest optionsRequestedPolicyVersion. + * GetIamPolicyInterconnectGroupRequest optionsRequestedPolicyVersion. * @member {number|null|undefined} optionsRequestedPolicyVersion - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @instance */ - GetIamPolicyLicenseRequest.prototype.optionsRequestedPolicyVersion = null; + GetIamPolicyInterconnectGroupRequest.prototype.optionsRequestedPolicyVersion = null; /** - * GetIamPolicyLicenseRequest project. + * GetIamPolicyInterconnectGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @instance */ - GetIamPolicyLicenseRequest.prototype.project = ""; + GetIamPolicyInterconnectGroupRequest.prototype.project = ""; /** - * GetIamPolicyLicenseRequest resource. + * GetIamPolicyInterconnectGroupRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @instance */ - GetIamPolicyLicenseRequest.prototype.resource = ""; + GetIamPolicyInterconnectGroupRequest.prototype.resource = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(GetIamPolicyLicenseRequest.prototype, "_optionsRequestedPolicyVersion", { + Object.defineProperty(GetIamPolicyInterconnectGroupRequest.prototype, "_optionsRequestedPolicyVersion", { get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new GetIamPolicyLicenseRequest instance using the specified properties. + * Creates a new GetIamPolicyInterconnectGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyLicenseRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} GetIamPolicyLicenseRequest instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} GetIamPolicyInterconnectGroupRequest instance */ - GetIamPolicyLicenseRequest.create = function create(properties) { - return new GetIamPolicyLicenseRequest(properties); + GetIamPolicyInterconnectGroupRequest.create = function create(properties) { + return new GetIamPolicyInterconnectGroupRequest(properties); }; /** - * Encodes the specified GetIamPolicyLicenseRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyLicenseRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyInterconnectGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyLicenseRequest} message GetIamPolicyLicenseRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectGroupRequest} message GetIamPolicyInterconnectGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyLicenseRequest.encode = function encode(message, writer) { + GetIamPolicyInterconnectGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) @@ -817501,33 +821204,33 @@ }; /** - * Encodes the specified GetIamPolicyLicenseRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyLicenseRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyInterconnectGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyLicenseRequest} message GetIamPolicyLicenseRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyInterconnectGroupRequest} message GetIamPolicyInterconnectGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyLicenseRequest.encodeDelimited = function encodeDelimited(message, writer) { + GetIamPolicyInterconnectGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a GetIamPolicyLicenseRequest message from the specified reader or buffer. + * Decodes a GetIamPolicyInterconnectGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} GetIamPolicyLicenseRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} GetIamPolicyInterconnectGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyLicenseRequest.decode = function decode(reader, length, error) { + GetIamPolicyInterconnectGroupRequest.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.cloud.compute.v1beta.GetIamPolicyLicenseRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -817554,30 +821257,30 @@ }; /** - * Decodes a GetIamPolicyLicenseRequest message from the specified reader or buffer, length delimited. + * Decodes a GetIamPolicyInterconnectGroupRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} GetIamPolicyLicenseRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} GetIamPolicyInterconnectGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyLicenseRequest.decodeDelimited = function decodeDelimited(reader) { + GetIamPolicyInterconnectGroupRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a GetIamPolicyLicenseRequest message. + * Verifies a GetIamPolicyInterconnectGroupRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GetIamPolicyLicenseRequest.verify = function verify(message) { + GetIamPolicyInterconnectGroupRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -817596,17 +821299,17 @@ }; /** - * Creates a GetIamPolicyLicenseRequest message from a plain object. Also converts values to their respective internal types. + * Creates a GetIamPolicyInterconnectGroupRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} GetIamPolicyLicenseRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} GetIamPolicyInterconnectGroupRequest */ - GetIamPolicyLicenseRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyLicenseRequest) + GetIamPolicyInterconnectGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest) return object; - var message = new $root.google.cloud.compute.v1beta.GetIamPolicyLicenseRequest(); + var message = new $root.google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest(); if (object.optionsRequestedPolicyVersion != null) message.optionsRequestedPolicyVersion = object.optionsRequestedPolicyVersion | 0; if (object.project != null) @@ -817617,15 +821320,15 @@ }; /** - * Creates a plain object from a GetIamPolicyLicenseRequest message. Also converts values to other types if specified. + * Creates a plain object from a GetIamPolicyInterconnectGroupRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static - * @param {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} message GetIamPolicyLicenseRequest + * @param {google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest} message GetIamPolicyInterconnectGroupRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GetIamPolicyLicenseRequest.toObject = function toObject(message, options) { + GetIamPolicyInterconnectGroupRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -817646,54 +821349,54 @@ }; /** - * Converts this GetIamPolicyLicenseRequest to JSON. + * Converts this GetIamPolicyInterconnectGroupRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @instance * @returns {Object.} JSON object */ - GetIamPolicyLicenseRequest.prototype.toJSON = function toJSON() { + GetIamPolicyInterconnectGroupRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for GetIamPolicyLicenseRequest + * Gets the default type url for GetIamPolicyInterconnectGroupRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - GetIamPolicyLicenseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + GetIamPolicyInterconnectGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyLicenseRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyInterconnectGroupRequest"; }; - return GetIamPolicyLicenseRequest; + return GetIamPolicyInterconnectGroupRequest; })(); - v1beta.GetIamPolicyMachineImageRequest = (function() { + v1beta.GetIamPolicyLicenseRequest = (function() { /** - * Properties of a GetIamPolicyMachineImageRequest. + * Properties of a GetIamPolicyLicenseRequest. * @memberof google.cloud.compute.v1beta - * @interface IGetIamPolicyMachineImageRequest - * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyMachineImageRequest optionsRequestedPolicyVersion - * @property {string|null} [project] GetIamPolicyMachineImageRequest project - * @property {string|null} [resource] GetIamPolicyMachineImageRequest resource + * @interface IGetIamPolicyLicenseRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyLicenseRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicyLicenseRequest project + * @property {string|null} [resource] GetIamPolicyLicenseRequest resource */ /** - * Constructs a new GetIamPolicyMachineImageRequest. + * Constructs a new GetIamPolicyLicenseRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a GetIamPolicyMachineImageRequest. - * @implements IGetIamPolicyMachineImageRequest + * @classdesc Represents a GetIamPolicyLicenseRequest. + * @implements IGetIamPolicyLicenseRequest * @constructor - * @param {google.cloud.compute.v1beta.IGetIamPolicyMachineImageRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IGetIamPolicyLicenseRequest=} [properties] Properties to set */ - function GetIamPolicyMachineImageRequest(properties) { + function GetIamPolicyLicenseRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -817701,60 +821404,60 @@ } /** - * GetIamPolicyMachineImageRequest optionsRequestedPolicyVersion. + * GetIamPolicyLicenseRequest optionsRequestedPolicyVersion. * @member {number|null|undefined} optionsRequestedPolicyVersion - * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest * @instance */ - GetIamPolicyMachineImageRequest.prototype.optionsRequestedPolicyVersion = null; + GetIamPolicyLicenseRequest.prototype.optionsRequestedPolicyVersion = null; /** - * GetIamPolicyMachineImageRequest project. + * GetIamPolicyLicenseRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest * @instance */ - GetIamPolicyMachineImageRequest.prototype.project = ""; + GetIamPolicyLicenseRequest.prototype.project = ""; /** - * GetIamPolicyMachineImageRequest resource. + * GetIamPolicyLicenseRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest * @instance */ - GetIamPolicyMachineImageRequest.prototype.resource = ""; + GetIamPolicyLicenseRequest.prototype.resource = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(GetIamPolicyMachineImageRequest.prototype, "_optionsRequestedPolicyVersion", { + Object.defineProperty(GetIamPolicyLicenseRequest.prototype, "_optionsRequestedPolicyVersion", { get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new GetIamPolicyMachineImageRequest instance using the specified properties. + * Creates a new GetIamPolicyLicenseRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyMachineImageRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest} GetIamPolicyMachineImageRequest instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyLicenseRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} GetIamPolicyLicenseRequest instance */ - GetIamPolicyMachineImageRequest.create = function create(properties) { - return new GetIamPolicyMachineImageRequest(properties); + GetIamPolicyLicenseRequest.create = function create(properties) { + return new GetIamPolicyLicenseRequest(properties); }; /** - * Encodes the specified GetIamPolicyMachineImageRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyLicenseRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyLicenseRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyMachineImageRequest} message GetIamPolicyMachineImageRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyLicenseRequest} message GetIamPolicyLicenseRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyMachineImageRequest.encode = function encode(message, writer) { + GetIamPolicyLicenseRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) @@ -817767,33 +821470,299 @@ }; /** - * Encodes the specified GetIamPolicyMachineImageRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest.verify|verify} messages. + * Encodes the specified GetIamPolicyLicenseRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyLicenseRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicyMachineImageRequest} message GetIamPolicyMachineImageRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicyLicenseRequest} message GetIamPolicyLicenseRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicyMachineImageRequest.encodeDelimited = function encodeDelimited(message, writer) { + GetIamPolicyLicenseRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a GetIamPolicyMachineImageRequest message from the specified reader or buffer. + * Decodes a GetIamPolicyLicenseRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest} GetIamPolicyMachineImageRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} GetIamPolicyLicenseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicyMachineImageRequest.decode = function decode(reader, length, error) { + GetIamPolicyLicenseRequest.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.cloud.compute.v1beta.GetIamPolicyMachineImageRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.GetIamPolicyLicenseRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 499220029: { + message.optionsRequestedPolicyVersion = reader.int32(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetIamPolicyLicenseRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} GetIamPolicyLicenseRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetIamPolicyLicenseRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetIamPolicyLicenseRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetIamPolicyLicenseRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.optionsRequestedPolicyVersion != null && message.hasOwnProperty("optionsRequestedPolicyVersion")) { + properties._optionsRequestedPolicyVersion = 1; + if (!$util.isInteger(message.optionsRequestedPolicyVersion)) + return "optionsRequestedPolicyVersion: integer expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + return null; + }; + + /** + * Creates a GetIamPolicyLicenseRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} GetIamPolicyLicenseRequest + */ + GetIamPolicyLicenseRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyLicenseRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.GetIamPolicyLicenseRequest(); + if (object.optionsRequestedPolicyVersion != null) + message.optionsRequestedPolicyVersion = object.optionsRequestedPolicyVersion | 0; + if (object.project != null) + message.project = String(object.project); + if (object.resource != null) + message.resource = String(object.resource); + return message; + }; + + /** + * Creates a plain object from a GetIamPolicyLicenseRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @static + * @param {google.cloud.compute.v1beta.GetIamPolicyLicenseRequest} message GetIamPolicyLicenseRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetIamPolicyLicenseRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.resource = ""; + object.project = ""; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.optionsRequestedPolicyVersion != null && message.hasOwnProperty("optionsRequestedPolicyVersion")) { + object.optionsRequestedPolicyVersion = message.optionsRequestedPolicyVersion; + if (options.oneofs) + object._optionsRequestedPolicyVersion = "optionsRequestedPolicyVersion"; + } + return object; + }; + + /** + * Converts this GetIamPolicyLicenseRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @instance + * @returns {Object.} JSON object + */ + GetIamPolicyLicenseRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetIamPolicyLicenseRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.GetIamPolicyLicenseRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetIamPolicyLicenseRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyLicenseRequest"; + }; + + return GetIamPolicyLicenseRequest; + })(); + + v1beta.GetIamPolicyMachineImageRequest = (function() { + + /** + * Properties of a GetIamPolicyMachineImageRequest. + * @memberof google.cloud.compute.v1beta + * @interface IGetIamPolicyMachineImageRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyMachineImageRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicyMachineImageRequest project + * @property {string|null} [resource] GetIamPolicyMachineImageRequest resource + */ + + /** + * Constructs a new GetIamPolicyMachineImageRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a GetIamPolicyMachineImageRequest. + * @implements IGetIamPolicyMachineImageRequest + * @constructor + * @param {google.cloud.compute.v1beta.IGetIamPolicyMachineImageRequest=} [properties] Properties to set + */ + function GetIamPolicyMachineImageRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetIamPolicyMachineImageRequest optionsRequestedPolicyVersion. + * @member {number|null|undefined} optionsRequestedPolicyVersion + * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @instance + */ + GetIamPolicyMachineImageRequest.prototype.optionsRequestedPolicyVersion = null; + + /** + * GetIamPolicyMachineImageRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @instance + */ + GetIamPolicyMachineImageRequest.prototype.project = ""; + + /** + * GetIamPolicyMachineImageRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @instance + */ + GetIamPolicyMachineImageRequest.prototype.resource = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(GetIamPolicyMachineImageRequest.prototype, "_optionsRequestedPolicyVersion", { + get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new GetIamPolicyMachineImageRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicyMachineImageRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest} GetIamPolicyMachineImageRequest instance + */ + GetIamPolicyMachineImageRequest.create = function create(properties) { + return new GetIamPolicyMachineImageRequest(properties); + }; + + /** + * Encodes the specified GetIamPolicyMachineImageRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicyMachineImageRequest} message GetIamPolicyMachineImageRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetIamPolicyMachineImageRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.optionsRequestedPolicyVersion != null && Object.hasOwnProperty.call(message, "optionsRequestedPolicyVersion")) + writer.uint32(/* id 499220029, wireType 0 =*/3993760232).int32(message.optionsRequestedPolicyVersion); + return writer; + }; + + /** + * Encodes the specified GetIamPolicyMachineImageRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicyMachineImageRequest} message GetIamPolicyMachineImageRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetIamPolicyMachineImageRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetIamPolicyMachineImageRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.GetIamPolicyMachineImageRequest} GetIamPolicyMachineImageRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetIamPolicyMachineImageRequest.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.cloud.compute.v1beta.GetIamPolicyMachineImageRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -819940,6 +823909,295 @@ return GetIamPolicyRegionDiskRequest; })(); + v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest = (function() { + + /** + * Properties of a GetIamPolicyRegionInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface IGetIamPolicyRegionInstantSnapshotGroupRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicyRegionInstantSnapshotGroupRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicyRegionInstantSnapshotGroupRequest project + * @property {string|null} [region] GetIamPolicyRegionInstantSnapshotGroupRequest region + * @property {string|null} [resource] GetIamPolicyRegionInstantSnapshotGroupRequest resource + */ + + /** + * Constructs a new GetIamPolicyRegionInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a GetIamPolicyRegionInstantSnapshotGroupRequest. + * @implements IGetIamPolicyRegionInstantSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest=} [properties] Properties to set + */ + function GetIamPolicyRegionInstantSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetIamPolicyRegionInstantSnapshotGroupRequest optionsRequestedPolicyVersion. + * @member {number|null|undefined} optionsRequestedPolicyVersion + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @instance + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.prototype.optionsRequestedPolicyVersion = null; + + /** + * GetIamPolicyRegionInstantSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @instance + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.prototype.project = ""; + + /** + * GetIamPolicyRegionInstantSnapshotGroupRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @instance + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.prototype.region = ""; + + /** + * GetIamPolicyRegionInstantSnapshotGroupRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @instance + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.prototype.resource = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(GetIamPolicyRegionInstantSnapshotGroupRequest.prototype, "_optionsRequestedPolicyVersion", { + get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new GetIamPolicyRegionInstantSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest} GetIamPolicyRegionInstantSnapshotGroupRequest instance + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.create = function create(properties) { + return new GetIamPolicyRegionInstantSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified GetIamPolicyRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest} message GetIamPolicyRegionInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.optionsRequestedPolicyVersion != null && Object.hasOwnProperty.call(message, "optionsRequestedPolicyVersion")) + writer.uint32(/* id 499220029, wireType 0 =*/3993760232).int32(message.optionsRequestedPolicyVersion); + return writer; + }; + + /** + * Encodes the specified GetIamPolicyRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest} message GetIamPolicyRegionInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetIamPolicyRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest} GetIamPolicyRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.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.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 499220029: { + message.optionsRequestedPolicyVersion = reader.int32(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetIamPolicyRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest} GetIamPolicyRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetIamPolicyRegionInstantSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.optionsRequestedPolicyVersion != null && message.hasOwnProperty("optionsRequestedPolicyVersion")) { + properties._optionsRequestedPolicyVersion = 1; + if (!$util.isInteger(message.optionsRequestedPolicyVersion)) + return "optionsRequestedPolicyVersion: integer expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + return null; + }; + + /** + * Creates a GetIamPolicyRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest} GetIamPolicyRegionInstantSnapshotGroupRequest + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest(); + if (object.optionsRequestedPolicyVersion != null) + message.optionsRequestedPolicyVersion = object.optionsRequestedPolicyVersion | 0; + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.resource != null) + message.resource = String(object.resource); + return message; + }; + + /** + * Creates a plain object from a GetIamPolicyRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest} message GetIamPolicyRegionInstantSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.resource = ""; + object.project = ""; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.optionsRequestedPolicyVersion != null && message.hasOwnProperty("optionsRequestedPolicyVersion")) { + object.optionsRequestedPolicyVersion = message.optionsRequestedPolicyVersion; + if (options.oneofs) + object._optionsRequestedPolicyVersion = "optionsRequestedPolicyVersion"; + } + return object; + }; + + /** + * Converts this GetIamPolicyRegionInstantSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetIamPolicyRegionInstantSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetIamPolicyRegionInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest"; + }; + + return GetIamPolicyRegionInstantSnapshotGroupRequest; + })(); + v1beta.GetIamPolicyRegionInstantSnapshotRequest = (function() { /** @@ -822298,26 +826556,26 @@ return GetIamPolicyServiceAttachmentRequest; })(); - v1beta.GetIamPolicySnapshotRequest = (function() { + v1beta.GetIamPolicySnapshotGroupRequest = (function() { /** - * Properties of a GetIamPolicySnapshotRequest. + * Properties of a GetIamPolicySnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface IGetIamPolicySnapshotRequest - * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicySnapshotRequest optionsRequestedPolicyVersion - * @property {string|null} [project] GetIamPolicySnapshotRequest project - * @property {string|null} [resource] GetIamPolicySnapshotRequest resource + * @interface IGetIamPolicySnapshotGroupRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicySnapshotGroupRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicySnapshotGroupRequest project + * @property {string|null} [resource] GetIamPolicySnapshotGroupRequest resource */ /** - * Constructs a new GetIamPolicySnapshotRequest. + * Constructs a new GetIamPolicySnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a GetIamPolicySnapshotRequest. - * @implements IGetIamPolicySnapshotRequest + * @classdesc Represents a GetIamPolicySnapshotGroupRequest. + * @implements IGetIamPolicySnapshotGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest=} [properties] Properties to set */ - function GetIamPolicySnapshotRequest(properties) { + function GetIamPolicySnapshotGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -822325,60 +826583,60 @@ } /** - * GetIamPolicySnapshotRequest optionsRequestedPolicyVersion. + * GetIamPolicySnapshotGroupRequest optionsRequestedPolicyVersion. * @member {number|null|undefined} optionsRequestedPolicyVersion - * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest * @instance */ - GetIamPolicySnapshotRequest.prototype.optionsRequestedPolicyVersion = null; + GetIamPolicySnapshotGroupRequest.prototype.optionsRequestedPolicyVersion = null; /** - * GetIamPolicySnapshotRequest project. + * GetIamPolicySnapshotGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest * @instance */ - GetIamPolicySnapshotRequest.prototype.project = ""; + GetIamPolicySnapshotGroupRequest.prototype.project = ""; /** - * GetIamPolicySnapshotRequest resource. + * GetIamPolicySnapshotGroupRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest * @instance */ - GetIamPolicySnapshotRequest.prototype.resource = ""; + GetIamPolicySnapshotGroupRequest.prototype.resource = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(GetIamPolicySnapshotRequest.prototype, "_optionsRequestedPolicyVersion", { + Object.defineProperty(GetIamPolicySnapshotGroupRequest.prototype, "_optionsRequestedPolicyVersion", { get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new GetIamPolicySnapshotRequest instance using the specified properties. + * Creates a new GetIamPolicySnapshotGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.GetIamPolicySnapshotRequest} GetIamPolicySnapshotRequest instance + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest} GetIamPolicySnapshotGroupRequest instance */ - GetIamPolicySnapshotRequest.create = function create(properties) { - return new GetIamPolicySnapshotRequest(properties); + GetIamPolicySnapshotGroupRequest.create = function create(properties) { + return new GetIamPolicySnapshotGroupRequest(properties); }; /** - * Encodes the specified GetIamPolicySnapshotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicySnapshotRequest.verify|verify} messages. + * Encodes the specified GetIamPolicySnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotRequest} message GetIamPolicySnapshotRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest} message GetIamPolicySnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicySnapshotRequest.encode = function encode(message, writer) { + GetIamPolicySnapshotGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) @@ -822391,33 +826649,299 @@ }; /** - * Encodes the specified GetIamPolicySnapshotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicySnapshotRequest.verify|verify} messages. + * Encodes the specified GetIamPolicySnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotRequest} message GetIamPolicySnapshotRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest} message GetIamPolicySnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetIamPolicySnapshotRequest.encodeDelimited = function encodeDelimited(message, writer) { + GetIamPolicySnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a GetIamPolicySnapshotRequest message from the specified reader or buffer. + * Decodes a GetIamPolicySnapshotGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.GetIamPolicySnapshotRequest} GetIamPolicySnapshotRequest + * @returns {google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest} GetIamPolicySnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetIamPolicySnapshotRequest.decode = function decode(reader, length, error) { + GetIamPolicySnapshotGroupRequest.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.cloud.compute.v1beta.GetIamPolicySnapshotRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 499220029: { + message.optionsRequestedPolicyVersion = reader.int32(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetIamPolicySnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest} GetIamPolicySnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetIamPolicySnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetIamPolicySnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetIamPolicySnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.optionsRequestedPolicyVersion != null && message.hasOwnProperty("optionsRequestedPolicyVersion")) { + properties._optionsRequestedPolicyVersion = 1; + if (!$util.isInteger(message.optionsRequestedPolicyVersion)) + return "optionsRequestedPolicyVersion: integer expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + return null; + }; + + /** + * Creates a GetIamPolicySnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest} GetIamPolicySnapshotGroupRequest + */ + GetIamPolicySnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest(); + if (object.optionsRequestedPolicyVersion != null) + message.optionsRequestedPolicyVersion = object.optionsRequestedPolicyVersion | 0; + if (object.project != null) + message.project = String(object.project); + if (object.resource != null) + message.resource = String(object.resource); + return message; + }; + + /** + * Creates a plain object from a GetIamPolicySnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest} message GetIamPolicySnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetIamPolicySnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.resource = ""; + object.project = ""; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.optionsRequestedPolicyVersion != null && message.hasOwnProperty("optionsRequestedPolicyVersion")) { + object.optionsRequestedPolicyVersion = message.optionsRequestedPolicyVersion; + if (options.oneofs) + object._optionsRequestedPolicyVersion = "optionsRequestedPolicyVersion"; + } + return object; + }; + + /** + * Converts this GetIamPolicySnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + GetIamPolicySnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetIamPolicySnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetIamPolicySnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest"; + }; + + return GetIamPolicySnapshotGroupRequest; + })(); + + v1beta.GetIamPolicySnapshotRequest = (function() { + + /** + * Properties of a GetIamPolicySnapshotRequest. + * @memberof google.cloud.compute.v1beta + * @interface IGetIamPolicySnapshotRequest + * @property {number|null} [optionsRequestedPolicyVersion] GetIamPolicySnapshotRequest optionsRequestedPolicyVersion + * @property {string|null} [project] GetIamPolicySnapshotRequest project + * @property {string|null} [resource] GetIamPolicySnapshotRequest resource + */ + + /** + * Constructs a new GetIamPolicySnapshotRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a GetIamPolicySnapshotRequest. + * @implements IGetIamPolicySnapshotRequest + * @constructor + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotRequest=} [properties] Properties to set + */ + function GetIamPolicySnapshotRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetIamPolicySnapshotRequest optionsRequestedPolicyVersion. + * @member {number|null|undefined} optionsRequestedPolicyVersion + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @instance + */ + GetIamPolicySnapshotRequest.prototype.optionsRequestedPolicyVersion = null; + + /** + * GetIamPolicySnapshotRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @instance + */ + GetIamPolicySnapshotRequest.prototype.project = ""; + + /** + * GetIamPolicySnapshotRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @instance + */ + GetIamPolicySnapshotRequest.prototype.resource = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(GetIamPolicySnapshotRequest.prototype, "_optionsRequestedPolicyVersion", { + get: $util.oneOfGetter($oneOfFields = ["optionsRequestedPolicyVersion"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new GetIamPolicySnapshotRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetIamPolicySnapshotRequest} GetIamPolicySnapshotRequest instance + */ + GetIamPolicySnapshotRequest.create = function create(properties) { + return new GetIamPolicySnapshotRequest(properties); + }; + + /** + * Encodes the specified GetIamPolicySnapshotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicySnapshotRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotRequest} message GetIamPolicySnapshotRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetIamPolicySnapshotRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.optionsRequestedPolicyVersion != null && Object.hasOwnProperty.call(message, "optionsRequestedPolicyVersion")) + writer.uint32(/* id 499220029, wireType 0 =*/3993760232).int32(message.optionsRequestedPolicyVersion); + return writer; + }; + + /** + * Encodes the specified GetIamPolicySnapshotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetIamPolicySnapshotRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @static + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotRequest} message GetIamPolicySnapshotRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetIamPolicySnapshotRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetIamPolicySnapshotRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.GetIamPolicySnapshotRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.GetIamPolicySnapshotRequest} GetIamPolicySnapshotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetIamPolicySnapshotRequest.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.cloud.compute.v1beta.GetIamPolicySnapshotRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -825222,6 +829746,258 @@ return GetInstanceTemplateRequest; })(); + v1beta.GetInstantSnapshotGroupRequest = (function() { + + /** + * Properties of a GetInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface IGetInstantSnapshotGroupRequest + * @property {string|null} [instantSnapshotGroup] GetInstantSnapshotGroupRequest instantSnapshotGroup + * @property {string|null} [project] GetInstantSnapshotGroupRequest project + * @property {string|null} [zone] GetInstantSnapshotGroupRequest zone + */ + + /** + * Constructs a new GetInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a GetInstantSnapshotGroupRequest. + * @implements IGetInstantSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest=} [properties] Properties to set + */ + function GetInstantSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetInstantSnapshotGroupRequest instantSnapshotGroup. + * @member {string} instantSnapshotGroup + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @instance + */ + GetInstantSnapshotGroupRequest.prototype.instantSnapshotGroup = ""; + + /** + * GetInstantSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @instance + */ + GetInstantSnapshotGroupRequest.prototype.project = ""; + + /** + * GetInstantSnapshotGroupRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @instance + */ + GetInstantSnapshotGroupRequest.prototype.zone = ""; + + /** + * Creates a new GetInstantSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest} GetInstantSnapshotGroupRequest instance + */ + GetInstantSnapshotGroupRequest.create = function create(properties) { + return new GetInstantSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified GetInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest} message GetInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetInstantSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.instantSnapshotGroup != null && Object.hasOwnProperty.call(message, "instantSnapshotGroup")) + writer.uint32(/* id 223180386, wireType 2 =*/1785443090).string(message.instantSnapshotGroup); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + return writer; + }; + + /** + * Encodes the specified GetInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest} message GetInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetInstantSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest} GetInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetInstantSnapshotGroupRequest.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.cloud.compute.v1beta.GetInstantSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 223180386: { + message.instantSnapshotGroup = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest} GetInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetInstantSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetInstantSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) + if (!$util.isString(message.instantSnapshotGroup)) + return "instantSnapshotGroup: string expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates a GetInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest} GetInstantSnapshotGroupRequest + */ + GetInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest(); + if (object.instantSnapshotGroup != null) + message.instantSnapshotGroup = String(object.instantSnapshotGroup); + if (object.project != null) + message.project = String(object.project); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a GetInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest} message GetInstantSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetInstantSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.instantSnapshotGroup = ""; + object.project = ""; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) + object.instantSnapshotGroup = message.instantSnapshotGroup; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + return object; + }; + + /** + * Converts this GetInstantSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + GetInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetInstantSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest"; + }; + + return GetInstantSnapshotGroupRequest; + })(); + v1beta.GetInstantSnapshotRequest = (function() { /** @@ -828039,6 +832815,295 @@ return GetMacsecConfigInterconnectRequest; })(); + v1beta.GetNamedSetRouterRequest = (function() { + + /** + * Properties of a GetNamedSetRouterRequest. + * @memberof google.cloud.compute.v1beta + * @interface IGetNamedSetRouterRequest + * @property {string|null} [namedSet] GetNamedSetRouterRequest namedSet + * @property {string|null} [project] GetNamedSetRouterRequest project + * @property {string|null} [region] GetNamedSetRouterRequest region + * @property {string|null} [router] GetNamedSetRouterRequest router + */ + + /** + * Constructs a new GetNamedSetRouterRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a GetNamedSetRouterRequest. + * @implements IGetNamedSetRouterRequest + * @constructor + * @param {google.cloud.compute.v1beta.IGetNamedSetRouterRequest=} [properties] Properties to set + */ + function GetNamedSetRouterRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetNamedSetRouterRequest namedSet. + * @member {string|null|undefined} namedSet + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @instance + */ + GetNamedSetRouterRequest.prototype.namedSet = null; + + /** + * GetNamedSetRouterRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @instance + */ + GetNamedSetRouterRequest.prototype.project = ""; + + /** + * GetNamedSetRouterRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @instance + */ + GetNamedSetRouterRequest.prototype.region = ""; + + /** + * GetNamedSetRouterRequest router. + * @member {string} router + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @instance + */ + GetNamedSetRouterRequest.prototype.router = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(GetNamedSetRouterRequest.prototype, "_namedSet", { + get: $util.oneOfGetter($oneOfFields = ["namedSet"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new GetNamedSetRouterRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IGetNamedSetRouterRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetNamedSetRouterRequest} GetNamedSetRouterRequest instance + */ + GetNamedSetRouterRequest.create = function create(properties) { + return new GetNamedSetRouterRequest(properties); + }; + + /** + * Encodes the specified GetNamedSetRouterRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetNamedSetRouterRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IGetNamedSetRouterRequest} message GetNamedSetRouterRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetNamedSetRouterRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.router != null && Object.hasOwnProperty.call(message, "router")) + writer.uint32(/* id 148608841, wireType 2 =*/1188870730).string(message.router); + if (message.namedSet != null && Object.hasOwnProperty.call(message, "namedSet")) + writer.uint32(/* id 164134492, wireType 2 =*/1313075938).string(message.namedSet); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + return writer; + }; + + /** + * Encodes the specified GetNamedSetRouterRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetNamedSetRouterRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IGetNamedSetRouterRequest} message GetNamedSetRouterRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetNamedSetRouterRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetNamedSetRouterRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.GetNamedSetRouterRequest} GetNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetNamedSetRouterRequest.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.cloud.compute.v1beta.GetNamedSetRouterRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 164134492: { + message.namedSet = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 148608841: { + message.router = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetNamedSetRouterRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.GetNamedSetRouterRequest} GetNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetNamedSetRouterRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetNamedSetRouterRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetNamedSetRouterRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.namedSet != null && message.hasOwnProperty("namedSet")) { + properties._namedSet = 1; + if (!$util.isString(message.namedSet)) + return "namedSet: string expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.router != null && message.hasOwnProperty("router")) + if (!$util.isString(message.router)) + return "router: string expected"; + return null; + }; + + /** + * Creates a GetNamedSetRouterRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.GetNamedSetRouterRequest} GetNamedSetRouterRequest + */ + GetNamedSetRouterRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetNamedSetRouterRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.GetNamedSetRouterRequest(); + if (object.namedSet != null) + message.namedSet = String(object.namedSet); + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.router != null) + message.router = String(object.router); + return message; + }; + + /** + * Creates a plain object from a GetNamedSetRouterRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.GetNamedSetRouterRequest} message GetNamedSetRouterRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetNamedSetRouterRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.router = ""; + object.project = ""; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.router != null && message.hasOwnProperty("router")) + object.router = message.router; + if (message.namedSet != null && message.hasOwnProperty("namedSet")) { + object.namedSet = message.namedSet; + if (options.oneofs) + object._namedSet = "namedSet"; + } + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + return object; + }; + + /** + * Converts this GetNamedSetRouterRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @instance + * @returns {Object.} JSON object + */ + GetNamedSetRouterRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetNamedSetRouterRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.GetNamedSetRouterRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetNamedSetRouterRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetNamedSetRouterRequest"; + }; + + return GetNamedSetRouterRequest; + })(); + v1beta.GetNatIpInfoRouterRequest = (function() { /** @@ -837695,6 +842760,258 @@ return GetRegionInstanceTemplateRequest; })(); + v1beta.GetRegionInstantSnapshotGroupRequest = (function() { + + /** + * Properties of a GetRegionInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface IGetRegionInstantSnapshotGroupRequest + * @property {string|null} [instantSnapshotGroup] GetRegionInstantSnapshotGroupRequest instantSnapshotGroup + * @property {string|null} [project] GetRegionInstantSnapshotGroupRequest project + * @property {string|null} [region] GetRegionInstantSnapshotGroupRequest region + */ + + /** + * Constructs a new GetRegionInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a GetRegionInstantSnapshotGroupRequest. + * @implements IGetRegionInstantSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest=} [properties] Properties to set + */ + function GetRegionInstantSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetRegionInstantSnapshotGroupRequest instantSnapshotGroup. + * @member {string} instantSnapshotGroup + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @instance + */ + GetRegionInstantSnapshotGroupRequest.prototype.instantSnapshotGroup = ""; + + /** + * GetRegionInstantSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @instance + */ + GetRegionInstantSnapshotGroupRequest.prototype.project = ""; + + /** + * GetRegionInstantSnapshotGroupRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @instance + */ + GetRegionInstantSnapshotGroupRequest.prototype.region = ""; + + /** + * Creates a new GetRegionInstantSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest} GetRegionInstantSnapshotGroupRequest instance + */ + GetRegionInstantSnapshotGroupRequest.create = function create(properties) { + return new GetRegionInstantSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified GetRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest} message GetRegionInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetRegionInstantSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.instantSnapshotGroup != null && Object.hasOwnProperty.call(message, "instantSnapshotGroup")) + writer.uint32(/* id 223180386, wireType 2 =*/1785443090).string(message.instantSnapshotGroup); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + return writer; + }; + + /** + * Encodes the specified GetRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest} message GetRegionInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetRegionInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetRegionInstantSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest} GetRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetRegionInstantSnapshotGroupRequest.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.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 223180386: { + message.instantSnapshotGroup = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest} GetRegionInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetRegionInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetRegionInstantSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetRegionInstantSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) + if (!$util.isString(message.instantSnapshotGroup)) + return "instantSnapshotGroup: string expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + return null; + }; + + /** + * Creates a GetRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest} GetRegionInstantSnapshotGroupRequest + */ + GetRegionInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest(); + if (object.instantSnapshotGroup != null) + message.instantSnapshotGroup = String(object.instantSnapshotGroup); + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + return message; + }; + + /** + * Creates a plain object from a GetRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest} message GetRegionInstantSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetRegionInstantSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.instantSnapshotGroup = ""; + object.project = ""; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) + object.instantSnapshotGroup = message.instantSnapshotGroup; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + return object; + }; + + /** + * Converts this GetRegionInstantSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + GetRegionInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetRegionInstantSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetRegionInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest"; + }; + + return GetRegionInstantSnapshotGroupRequest; + })(); + v1beta.GetRegionInstantSnapshotRequest = (function() { /** @@ -842790,6 +848107,281 @@ return GetReservationRequest; })(); + v1beta.GetReservationSlotRequest = (function() { + + /** + * Properties of a GetReservationSlotRequest. + * @memberof google.cloud.compute.v1beta + * @interface IGetReservationSlotRequest + * @property {string|null} [parentName] GetReservationSlotRequest parentName + * @property {string|null} [project] GetReservationSlotRequest project + * @property {string|null} [reservationSlot] GetReservationSlotRequest reservationSlot + * @property {string|null} [zone] GetReservationSlotRequest zone + */ + + /** + * Constructs a new GetReservationSlotRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a GetReservationSlotRequest. + * @implements IGetReservationSlotRequest + * @constructor + * @param {google.cloud.compute.v1beta.IGetReservationSlotRequest=} [properties] Properties to set + */ + function GetReservationSlotRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetReservationSlotRequest parentName. + * @member {string} parentName + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @instance + */ + GetReservationSlotRequest.prototype.parentName = ""; + + /** + * GetReservationSlotRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @instance + */ + GetReservationSlotRequest.prototype.project = ""; + + /** + * GetReservationSlotRequest reservationSlot. + * @member {string} reservationSlot + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @instance + */ + GetReservationSlotRequest.prototype.reservationSlot = ""; + + /** + * GetReservationSlotRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @instance + */ + GetReservationSlotRequest.prototype.zone = ""; + + /** + * Creates a new GetReservationSlotRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {google.cloud.compute.v1beta.IGetReservationSlotRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetReservationSlotRequest} GetReservationSlotRequest instance + */ + GetReservationSlotRequest.create = function create(properties) { + return new GetReservationSlotRequest(properties); + }; + + /** + * Encodes the specified GetReservationSlotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetReservationSlotRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {google.cloud.compute.v1beta.IGetReservationSlotRequest} message GetReservationSlotRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetReservationSlotRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.reservationSlot != null && Object.hasOwnProperty.call(message, "reservationSlot")) + writer.uint32(/* id 277470865, wireType 2 =*/2219766922).string(message.reservationSlot); + if (message.parentName != null && Object.hasOwnProperty.call(message, "parentName")) + writer.uint32(/* id 478151936, wireType 2 =*/3825215490).string(message.parentName); + return writer; + }; + + /** + * Encodes the specified GetReservationSlotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetReservationSlotRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {google.cloud.compute.v1beta.IGetReservationSlotRequest} message GetReservationSlotRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetReservationSlotRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetReservationSlotRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.GetReservationSlotRequest} GetReservationSlotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetReservationSlotRequest.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.cloud.compute.v1beta.GetReservationSlotRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 478151936: { + message.parentName = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 277470865: { + message.reservationSlot = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetReservationSlotRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.GetReservationSlotRequest} GetReservationSlotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetReservationSlotRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetReservationSlotRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetReservationSlotRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.parentName != null && message.hasOwnProperty("parentName")) + if (!$util.isString(message.parentName)) + return "parentName: string expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.reservationSlot != null && message.hasOwnProperty("reservationSlot")) + if (!$util.isString(message.reservationSlot)) + return "reservationSlot: string expected"; + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates a GetReservationSlotRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.GetReservationSlotRequest} GetReservationSlotRequest + */ + GetReservationSlotRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetReservationSlotRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.GetReservationSlotRequest(); + if (object.parentName != null) + message.parentName = String(object.parentName); + if (object.project != null) + message.project = String(object.project); + if (object.reservationSlot != null) + message.reservationSlot = String(object.reservationSlot); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a GetReservationSlotRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {google.cloud.compute.v1beta.GetReservationSlotRequest} message GetReservationSlotRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetReservationSlotRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.project = ""; + object.reservationSlot = ""; + object.parentName = ""; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.reservationSlot != null && message.hasOwnProperty("reservationSlot")) + object.reservationSlot = message.reservationSlot; + if (message.parentName != null && message.hasOwnProperty("parentName")) + object.parentName = message.parentName; + return object; + }; + + /** + * Converts this GetReservationSlotRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @instance + * @returns {Object.} JSON object + */ + GetReservationSlotRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetReservationSlotRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.GetReservationSlotRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetReservationSlotRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetReservationSlotRequest"; + }; + + return GetReservationSlotRequest; + })(); + v1beta.GetReservationSubBlockRequest = (function() { /** @@ -848052,6 +853644,235 @@ return GetShieldedVmIdentityInstanceRequest; })(); + v1beta.GetSnapshotGroupRequest = (function() { + + /** + * Properties of a GetSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface IGetSnapshotGroupRequest + * @property {string|null} [project] GetSnapshotGroupRequest project + * @property {string|null} [snapshotGroup] GetSnapshotGroupRequest snapshotGroup + */ + + /** + * Constructs a new GetSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a GetSnapshotGroupRequest. + * @implements IGetSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.IGetSnapshotGroupRequest=} [properties] Properties to set + */ + function GetSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @instance + */ + GetSnapshotGroupRequest.prototype.project = ""; + + /** + * GetSnapshotGroupRequest snapshotGroup. + * @member {string} snapshotGroup + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @instance + */ + GetSnapshotGroupRequest.prototype.snapshotGroup = ""; + + /** + * Creates a new GetSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.GetSnapshotGroupRequest} GetSnapshotGroupRequest instance + */ + GetSnapshotGroupRequest.create = function create(properties) { + return new GetSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified GetSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.GetSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetSnapshotGroupRequest} message GetSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.snapshotGroup != null && Object.hasOwnProperty.call(message, "snapshotGroup")) + writer.uint32(/* id 84528196, wireType 2 =*/676225570).string(message.snapshotGroup); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + return writer; + }; + + /** + * Encodes the specified GetSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.GetSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IGetSnapshotGroupRequest} message GetSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.GetSnapshotGroupRequest} GetSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetSnapshotGroupRequest.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.cloud.compute.v1beta.GetSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 227560217: { + message.project = reader.string(); + break; + } + case 84528196: { + message.snapshotGroup = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GetSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.GetSnapshotGroupRequest} GetSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.snapshotGroup != null && message.hasOwnProperty("snapshotGroup")) + if (!$util.isString(message.snapshotGroup)) + return "snapshotGroup: string expected"; + return null; + }; + + /** + * Creates a GetSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.GetSnapshotGroupRequest} GetSnapshotGroupRequest + */ + GetSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.GetSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.GetSnapshotGroupRequest(); + if (object.project != null) + message.project = String(object.project); + if (object.snapshotGroup != null) + message.snapshotGroup = String(object.snapshotGroup); + return message; + }; + + /** + * Creates a plain object from a GetSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.GetSnapshotGroupRequest} message GetSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.snapshotGroup = ""; + object.project = ""; + } + if (message.snapshotGroup != null && message.hasOwnProperty("snapshotGroup")) + object.snapshotGroup = message.snapshotGroup; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + return object; + }; + + /** + * Converts this GetSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + GetSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.GetSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.GetSnapshotGroupRequest"; + }; + + return GetSnapshotGroupRequest; + })(); + v1beta.GetSnapshotRequest = (function() { /** @@ -874425,6 +880246,7 @@ * Properties of a HttpRouteAction. * @memberof google.cloud.compute.v1beta * @interface IHttpRouteAction + * @property {google.cloud.compute.v1beta.ICachePolicy|null} [cachePolicy] HttpRouteAction cachePolicy * @property {google.cloud.compute.v1beta.ICorsPolicy|null} [corsPolicy] HttpRouteAction corsPolicy * @property {google.cloud.compute.v1beta.IHttpFaultInjection|null} [faultInjectionPolicy] HttpRouteAction faultInjectionPolicy * @property {google.cloud.compute.v1beta.IDuration|null} [maxStreamDuration] HttpRouteAction maxStreamDuration @@ -874451,6 +880273,14 @@ this[keys[i]] = properties[keys[i]]; } + /** + * HttpRouteAction cachePolicy. + * @member {google.cloud.compute.v1beta.ICachePolicy|null|undefined} cachePolicy + * @memberof google.cloud.compute.v1beta.HttpRouteAction + * @instance + */ + HttpRouteAction.prototype.cachePolicy = null; + /** * HttpRouteAction corsPolicy. * @member {google.cloud.compute.v1beta.ICorsPolicy|null|undefined} corsPolicy @@ -874518,6 +880348,12 @@ // OneOf field names bound to virtual getters and setters var $oneOfFields; + // Virtual OneOf for proto3 optional field + Object.defineProperty(HttpRouteAction.prototype, "_cachePolicy", { + get: $util.oneOfGetter($oneOfFields = ["cachePolicy"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(HttpRouteAction.prototype, "_corsPolicy", { get: $util.oneOfGetter($oneOfFields = ["corsPolicy"]), @@ -874601,6 +880437,8 @@ $root.google.cloud.compute.v1beta.CorsPolicy.encode(message.corsPolicy, writer.uint32(/* id 398943748, wireType 2 =*/3191549986).fork()).ldelim(); if (message.faultInjectionPolicy != null && Object.hasOwnProperty.call(message, "faultInjectionPolicy")) $root.google.cloud.compute.v1beta.HttpFaultInjection.encode(message.faultInjectionPolicy, writer.uint32(/* id 412781079, wireType 2 =*/3302248634).fork()).ldelim(); + if (message.cachePolicy != null && Object.hasOwnProperty.call(message, "cachePolicy")) + $root.google.cloud.compute.v1beta.CachePolicy.encode(message.cachePolicy, writer.uint32(/* id 457366671, wireType 2 =*/3658933370).fork()).ldelim(); return writer; }; @@ -874637,6 +880475,10 @@ if (tag === error) break; switch (tag >>> 3) { + case 457366671: { + message.cachePolicy = $root.google.cloud.compute.v1beta.CachePolicy.decode(reader, reader.uint32()); + break; + } case 398943748: { message.corsPolicy = $root.google.cloud.compute.v1beta.CorsPolicy.decode(reader, reader.uint32()); break; @@ -874707,6 +880549,14 @@ if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; + if (message.cachePolicy != null && message.hasOwnProperty("cachePolicy")) { + properties._cachePolicy = 1; + { + var error = $root.google.cloud.compute.v1beta.CachePolicy.verify(message.cachePolicy); + if (error) + return "cachePolicy." + error; + } + } if (message.corsPolicy != null && message.hasOwnProperty("corsPolicy")) { properties._corsPolicy = 1; { @@ -874787,6 +880637,11 @@ if (object instanceof $root.google.cloud.compute.v1beta.HttpRouteAction) return object; var message = new $root.google.cloud.compute.v1beta.HttpRouteAction(); + if (object.cachePolicy != null) { + if (typeof object.cachePolicy !== "object") + throw TypeError(".google.cloud.compute.v1beta.HttpRouteAction.cachePolicy: object expected"); + message.cachePolicy = $root.google.cloud.compute.v1beta.CachePolicy.fromObject(object.cachePolicy); + } if (object.corsPolicy != null) { if (typeof object.corsPolicy !== "object") throw TypeError(".google.cloud.compute.v1beta.HttpRouteAction.corsPolicy: object expected"); @@ -874890,6 +880745,11 @@ if (options.oneofs) object._faultInjectionPolicy = "faultInjectionPolicy"; } + if (message.cachePolicy != null && message.hasOwnProperty("cachePolicy")) { + object.cachePolicy = $root.google.cloud.compute.v1beta.CachePolicy.toObject(message.cachePolicy, options); + if (options.oneofs) + object._cachePolicy = "cachePolicy"; + } return object; }; @@ -885487,6 +891347,333 @@ return InsertInstanceTemplateRequest; })(); + v1beta.InsertInstantSnapshotGroupRequest = (function() { + + /** + * Properties of an InsertInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface IInsertInstantSnapshotGroupRequest + * @property {google.cloud.compute.v1beta.IInstantSnapshotGroup|null} [instantSnapshotGroupResource] InsertInstantSnapshotGroupRequest instantSnapshotGroupResource + * @property {string|null} [project] InsertInstantSnapshotGroupRequest project + * @property {string|null} [requestId] InsertInstantSnapshotGroupRequest requestId + * @property {string|null} [sourceConsistencyGroup] InsertInstantSnapshotGroupRequest sourceConsistencyGroup + * @property {string|null} [zone] InsertInstantSnapshotGroupRequest zone + */ + + /** + * Constructs a new InsertInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InsertInstantSnapshotGroupRequest. + * @implements IInsertInstantSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest=} [properties] Properties to set + */ + function InsertInstantSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InsertInstantSnapshotGroupRequest instantSnapshotGroupResource. + * @member {google.cloud.compute.v1beta.IInstantSnapshotGroup|null|undefined} instantSnapshotGroupResource + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @instance + */ + InsertInstantSnapshotGroupRequest.prototype.instantSnapshotGroupResource = null; + + /** + * InsertInstantSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @instance + */ + InsertInstantSnapshotGroupRequest.prototype.project = ""; + + /** + * InsertInstantSnapshotGroupRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @instance + */ + InsertInstantSnapshotGroupRequest.prototype.requestId = null; + + /** + * InsertInstantSnapshotGroupRequest sourceConsistencyGroup. + * @member {string|null|undefined} sourceConsistencyGroup + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @instance + */ + InsertInstantSnapshotGroupRequest.prototype.sourceConsistencyGroup = null; + + /** + * InsertInstantSnapshotGroupRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @instance + */ + InsertInstantSnapshotGroupRequest.prototype.zone = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InsertInstantSnapshotGroupRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InsertInstantSnapshotGroupRequest.prototype, "_sourceConsistencyGroup", { + get: $util.oneOfGetter($oneOfFields = ["sourceConsistencyGroup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InsertInstantSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest} InsertInstantSnapshotGroupRequest instance + */ + InsertInstantSnapshotGroupRequest.create = function create(properties) { + return new InsertInstantSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified InsertInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest} message InsertInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InsertInstantSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.instantSnapshotGroupResource != null && Object.hasOwnProperty.call(message, "instantSnapshotGroupResource")) + $root.google.cloud.compute.v1beta.InstantSnapshotGroup.encode(message.instantSnapshotGroupResource, writer.uint32(/* id 145067339, wireType 2 =*/1160538714).fork()).ldelim(); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.sourceConsistencyGroup != null && Object.hasOwnProperty.call(message, "sourceConsistencyGroup")) + writer.uint32(/* id 531359348, wireType 2 =*/4250874786).string(message.sourceConsistencyGroup); + return writer; + }; + + /** + * Encodes the specified InsertInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest} message InsertInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InsertInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InsertInstantSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest} InsertInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InsertInstantSnapshotGroupRequest.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.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 145067339: { + message.instantSnapshotGroupResource = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.decode(reader, reader.uint32()); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + case 531359348: { + message.sourceConsistencyGroup = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InsertInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest} InsertInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InsertInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InsertInstantSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InsertInstantSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instantSnapshotGroupResource != null && message.hasOwnProperty("instantSnapshotGroupResource")) { + var error = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.verify(message.instantSnapshotGroupResource); + if (error) + return "instantSnapshotGroupResource." + error; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + if (message.sourceConsistencyGroup != null && message.hasOwnProperty("sourceConsistencyGroup")) { + properties._sourceConsistencyGroup = 1; + if (!$util.isString(message.sourceConsistencyGroup)) + return "sourceConsistencyGroup: string expected"; + } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates an InsertInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest} InsertInstantSnapshotGroupRequest + */ + InsertInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest(); + if (object.instantSnapshotGroupResource != null) { + if (typeof object.instantSnapshotGroupResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest.instantSnapshotGroupResource: object expected"); + message.instantSnapshotGroupResource = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.fromObject(object.instantSnapshotGroupResource); + } + if (object.project != null) + message.project = String(object.project); + if (object.requestId != null) + message.requestId = String(object.requestId); + if (object.sourceConsistencyGroup != null) + message.sourceConsistencyGroup = String(object.sourceConsistencyGroup); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from an InsertInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest} message InsertInstantSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InsertInstantSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.instantSnapshotGroupResource = null; + object.project = ""; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.instantSnapshotGroupResource != null && message.hasOwnProperty("instantSnapshotGroupResource")) + object.instantSnapshotGroupResource = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.toObject(message.instantSnapshotGroupResource, options); + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.sourceConsistencyGroup != null && message.hasOwnProperty("sourceConsistencyGroup")) { + object.sourceConsistencyGroup = message.sourceConsistencyGroup; + if (options.oneofs) + object._sourceConsistencyGroup = "sourceConsistencyGroup"; + } + return object; + }; + + /** + * Converts this InsertInstantSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + InsertInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InsertInstantSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InsertInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest"; + }; + + return InsertInstantSnapshotGroupRequest; + })(); + v1beta.InsertInstantSnapshotRequest = (function() { /** @@ -894581,27 +900768,28 @@ return InsertRegionInstanceTemplateRequest; })(); - v1beta.InsertRegionInstantSnapshotRequest = (function() { + v1beta.InsertRegionInstantSnapshotGroupRequest = (function() { /** - * Properties of an InsertRegionInstantSnapshotRequest. + * Properties of an InsertRegionInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface IInsertRegionInstantSnapshotRequest - * @property {google.cloud.compute.v1beta.IInstantSnapshot|null} [instantSnapshotResource] InsertRegionInstantSnapshotRequest instantSnapshotResource - * @property {string|null} [project] InsertRegionInstantSnapshotRequest project - * @property {string|null} [region] InsertRegionInstantSnapshotRequest region - * @property {string|null} [requestId] InsertRegionInstantSnapshotRequest requestId + * @interface IInsertRegionInstantSnapshotGroupRequest + * @property {google.cloud.compute.v1beta.IInstantSnapshotGroup|null} [instantSnapshotGroupResource] InsertRegionInstantSnapshotGroupRequest instantSnapshotGroupResource + * @property {string|null} [project] InsertRegionInstantSnapshotGroupRequest project + * @property {string|null} [region] InsertRegionInstantSnapshotGroupRequest region + * @property {string|null} [requestId] InsertRegionInstantSnapshotGroupRequest requestId + * @property {string|null} [sourceConsistencyGroup] InsertRegionInstantSnapshotGroupRequest sourceConsistencyGroup */ /** - * Constructs a new InsertRegionInstantSnapshotRequest. + * Constructs a new InsertRegionInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents an InsertRegionInstantSnapshotRequest. - * @implements IInsertRegionInstantSnapshotRequest + * @classdesc Represents an InsertRegionInstantSnapshotGroupRequest. + * @implements IInsertRegionInstantSnapshotGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest=} [properties] Properties to set */ - function InsertRegionInstantSnapshotRequest(properties) { + function InsertRegionInstantSnapshotGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -894609,116 +900797,132 @@ } /** - * InsertRegionInstantSnapshotRequest instantSnapshotResource. - * @member {google.cloud.compute.v1beta.IInstantSnapshot|null|undefined} instantSnapshotResource - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * InsertRegionInstantSnapshotGroupRequest instantSnapshotGroupResource. + * @member {google.cloud.compute.v1beta.IInstantSnapshotGroup|null|undefined} instantSnapshotGroupResource + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @instance */ - InsertRegionInstantSnapshotRequest.prototype.instantSnapshotResource = null; + InsertRegionInstantSnapshotGroupRequest.prototype.instantSnapshotGroupResource = null; /** - * InsertRegionInstantSnapshotRequest project. + * InsertRegionInstantSnapshotGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @instance */ - InsertRegionInstantSnapshotRequest.prototype.project = ""; + InsertRegionInstantSnapshotGroupRequest.prototype.project = ""; /** - * InsertRegionInstantSnapshotRequest region. + * InsertRegionInstantSnapshotGroupRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @instance */ - InsertRegionInstantSnapshotRequest.prototype.region = ""; + InsertRegionInstantSnapshotGroupRequest.prototype.region = ""; /** - * InsertRegionInstantSnapshotRequest requestId. + * InsertRegionInstantSnapshotGroupRequest requestId. * @member {string|null|undefined} requestId - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @instance */ - InsertRegionInstantSnapshotRequest.prototype.requestId = null; + InsertRegionInstantSnapshotGroupRequest.prototype.requestId = null; + + /** + * InsertRegionInstantSnapshotGroupRequest sourceConsistencyGroup. + * @member {string|null|undefined} sourceConsistencyGroup + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest + * @instance + */ + InsertRegionInstantSnapshotGroupRequest.prototype.sourceConsistencyGroup = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(InsertRegionInstantSnapshotRequest.prototype, "_requestId", { + Object.defineProperty(InsertRegionInstantSnapshotGroupRequest.prototype, "_requestId", { get: $util.oneOfGetter($oneOfFields = ["requestId"]), set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(InsertRegionInstantSnapshotGroupRequest.prototype, "_sourceConsistencyGroup", { + get: $util.oneOfGetter($oneOfFields = ["sourceConsistencyGroup"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** - * Creates a new InsertRegionInstantSnapshotRequest instance using the specified properties. + * Creates a new InsertRegionInstantSnapshotGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} InsertRegionInstantSnapshotRequest instance + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest} InsertRegionInstantSnapshotGroupRequest instance */ - InsertRegionInstantSnapshotRequest.create = function create(properties) { - return new InsertRegionInstantSnapshotRequest(properties); + InsertRegionInstantSnapshotGroupRequest.create = function create(properties) { + return new InsertRegionInstantSnapshotGroupRequest(properties); }; /** - * Encodes the specified InsertRegionInstantSnapshotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest.verify|verify} messages. + * Encodes the specified InsertRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotRequest} message InsertRegionInstantSnapshotRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest} message InsertRegionInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - InsertRegionInstantSnapshotRequest.encode = function encode(message, writer) { + InsertRegionInstantSnapshotGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); if (message.region != null && Object.hasOwnProperty.call(message, "region")) writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.instantSnapshotGroupResource != null && Object.hasOwnProperty.call(message, "instantSnapshotGroupResource")) + $root.google.cloud.compute.v1beta.InstantSnapshotGroup.encode(message.instantSnapshotGroupResource, writer.uint32(/* id 145067339, wireType 2 =*/1160538714).fork()).ldelim(); if (message.project != null && Object.hasOwnProperty.call(message, "project")) writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); - if (message.instantSnapshotResource != null && Object.hasOwnProperty.call(message, "instantSnapshotResource")) - $root.google.cloud.compute.v1beta.InstantSnapshot.encode(message.instantSnapshotResource, writer.uint32(/* id 383915339, wireType 2 =*/3071322714).fork()).ldelim(); + if (message.sourceConsistencyGroup != null && Object.hasOwnProperty.call(message, "sourceConsistencyGroup")) + writer.uint32(/* id 531359348, wireType 2 =*/4250874786).string(message.sourceConsistencyGroup); return writer; }; /** - * Encodes the specified InsertRegionInstantSnapshotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest.verify|verify} messages. + * Encodes the specified InsertRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotRequest} message InsertRegionInstantSnapshotRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest} message InsertRegionInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - InsertRegionInstantSnapshotRequest.encodeDelimited = function encodeDelimited(message, writer) { + InsertRegionInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes an InsertRegionInstantSnapshotRequest message from the specified reader or buffer. + * Decodes an InsertRegionInstantSnapshotGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} InsertRegionInstantSnapshotRequest + * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest} InsertRegionInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - InsertRegionInstantSnapshotRequest.decode = function decode(reader, length, error) { + InsertRegionInstantSnapshotGroupRequest.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.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { - case 383915339: { - message.instantSnapshotResource = $root.google.cloud.compute.v1beta.InstantSnapshot.decode(reader, reader.uint32()); + case 145067339: { + message.instantSnapshotGroupResource = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.decode(reader, reader.uint32()); break; } case 227560217: { @@ -894733,6 +900937,10 @@ message.requestId = reader.string(); break; } + case 531359348: { + message.sourceConsistencyGroup = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -894742,37 +900950,37 @@ }; /** - * Decodes an InsertRegionInstantSnapshotRequest message from the specified reader or buffer, length delimited. + * Decodes an InsertRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} InsertRegionInstantSnapshotRequest + * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest} InsertRegionInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - InsertRegionInstantSnapshotRequest.decodeDelimited = function decodeDelimited(reader) { + InsertRegionInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies an InsertRegionInstantSnapshotRequest message. + * Verifies an InsertRegionInstantSnapshotGroupRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - InsertRegionInstantSnapshotRequest.verify = function verify(message) { + InsertRegionInstantSnapshotGroupRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; - if (message.instantSnapshotResource != null && message.hasOwnProperty("instantSnapshotResource")) { - var error = $root.google.cloud.compute.v1beta.InstantSnapshot.verify(message.instantSnapshotResource); + if (message.instantSnapshotGroupResource != null && message.hasOwnProperty("instantSnapshotGroupResource")) { + var error = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.verify(message.instantSnapshotGroupResource); if (error) - return "instantSnapshotResource." + error; + return "instantSnapshotGroupResource." + error; } if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) @@ -894785,25 +900993,30 @@ if (!$util.isString(message.requestId)) return "requestId: string expected"; } + if (message.sourceConsistencyGroup != null && message.hasOwnProperty("sourceConsistencyGroup")) { + properties._sourceConsistencyGroup = 1; + if (!$util.isString(message.sourceConsistencyGroup)) + return "sourceConsistencyGroup: string expected"; + } return null; }; /** - * Creates an InsertRegionInstantSnapshotRequest message from a plain object. Also converts values to their respective internal types. + * Creates an InsertRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} InsertRegionInstantSnapshotRequest + * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest} InsertRegionInstantSnapshotGroupRequest */ - InsertRegionInstantSnapshotRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest) + InsertRegionInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest) return object; - var message = new $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest(); - if (object.instantSnapshotResource != null) { - if (typeof object.instantSnapshotResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest.instantSnapshotResource: object expected"); - message.instantSnapshotResource = $root.google.cloud.compute.v1beta.InstantSnapshot.fromObject(object.instantSnapshotResource); + var message = new $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest(); + if (object.instantSnapshotGroupResource != null) { + if (typeof object.instantSnapshotGroupResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest.instantSnapshotGroupResource: object expected"); + message.instantSnapshotGroupResource = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.fromObject(object.instantSnapshotGroupResource); } if (object.project != null) message.project = String(object.project); @@ -894811,26 +901024,28 @@ message.region = String(object.region); if (object.requestId != null) message.requestId = String(object.requestId); + if (object.sourceConsistencyGroup != null) + message.sourceConsistencyGroup = String(object.sourceConsistencyGroup); return message; }; /** - * Creates a plain object from an InsertRegionInstantSnapshotRequest message. Also converts values to other types if specified. + * Creates a plain object from an InsertRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} message InsertRegionInstantSnapshotRequest + * @param {google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest} message InsertRegionInstantSnapshotGroupRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - InsertRegionInstantSnapshotRequest.toObject = function toObject(message, options) { + InsertRegionInstantSnapshotGroupRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { object.region = ""; + object.instantSnapshotGroupResource = null; object.project = ""; - object.instantSnapshotResource = null; } if (message.requestId != null && message.hasOwnProperty("requestId")) { object.requestId = message.requestId; @@ -894839,63 +901054,68 @@ } if (message.region != null && message.hasOwnProperty("region")) object.region = message.region; + if (message.instantSnapshotGroupResource != null && message.hasOwnProperty("instantSnapshotGroupResource")) + object.instantSnapshotGroupResource = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.toObject(message.instantSnapshotGroupResource, options); if (message.project != null && message.hasOwnProperty("project")) object.project = message.project; - if (message.instantSnapshotResource != null && message.hasOwnProperty("instantSnapshotResource")) - object.instantSnapshotResource = $root.google.cloud.compute.v1beta.InstantSnapshot.toObject(message.instantSnapshotResource, options); + if (message.sourceConsistencyGroup != null && message.hasOwnProperty("sourceConsistencyGroup")) { + object.sourceConsistencyGroup = message.sourceConsistencyGroup; + if (options.oneofs) + object._sourceConsistencyGroup = "sourceConsistencyGroup"; + } return object; }; /** - * Converts this InsertRegionInstantSnapshotRequest to JSON. + * Converts this InsertRegionInstantSnapshotGroupRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @instance * @returns {Object.} JSON object */ - InsertRegionInstantSnapshotRequest.prototype.toJSON = function toJSON() { + InsertRegionInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for InsertRegionInstantSnapshotRequest + * Gets the default type url for InsertRegionInstantSnapshotGroupRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - InsertRegionInstantSnapshotRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + InsertRegionInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest"; }; - return InsertRegionInstantSnapshotRequest; + return InsertRegionInstantSnapshotGroupRequest; })(); - v1beta.InsertRegionMultiMigRequest = (function() { + v1beta.InsertRegionInstantSnapshotRequest = (function() { /** - * Properties of an InsertRegionMultiMigRequest. + * Properties of an InsertRegionInstantSnapshotRequest. * @memberof google.cloud.compute.v1beta - * @interface IInsertRegionMultiMigRequest - * @property {google.cloud.compute.v1beta.IMultiMig|null} [multiMigResource] InsertRegionMultiMigRequest multiMigResource - * @property {string|null} [project] InsertRegionMultiMigRequest project - * @property {string|null} [region] InsertRegionMultiMigRequest region - * @property {string|null} [requestId] InsertRegionMultiMigRequest requestId + * @interface IInsertRegionInstantSnapshotRequest + * @property {google.cloud.compute.v1beta.IInstantSnapshot|null} [instantSnapshotResource] InsertRegionInstantSnapshotRequest instantSnapshotResource + * @property {string|null} [project] InsertRegionInstantSnapshotRequest project + * @property {string|null} [region] InsertRegionInstantSnapshotRequest region + * @property {string|null} [requestId] InsertRegionInstantSnapshotRequest requestId */ /** - * Constructs a new InsertRegionMultiMigRequest. + * Constructs a new InsertRegionInstantSnapshotRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents an InsertRegionMultiMigRequest. - * @implements IInsertRegionMultiMigRequest + * @classdesc Represents an InsertRegionInstantSnapshotRequest. + * @implements IInsertRegionInstantSnapshotRequest * @constructor - * @param {google.cloud.compute.v1beta.IInsertRegionMultiMigRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotRequest=} [properties] Properties to set */ - function InsertRegionMultiMigRequest(properties) { + function InsertRegionInstantSnapshotRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -894903,116 +901123,410 @@ } /** - * InsertRegionMultiMigRequest multiMigResource. - * @member {google.cloud.compute.v1beta.IMultiMig|null|undefined} multiMigResource - * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * InsertRegionInstantSnapshotRequest instantSnapshotResource. + * @member {google.cloud.compute.v1beta.IInstantSnapshot|null|undefined} instantSnapshotResource + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest * @instance */ - InsertRegionMultiMigRequest.prototype.multiMigResource = null; + InsertRegionInstantSnapshotRequest.prototype.instantSnapshotResource = null; /** - * InsertRegionMultiMigRequest project. + * InsertRegionInstantSnapshotRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest * @instance */ - InsertRegionMultiMigRequest.prototype.project = ""; + InsertRegionInstantSnapshotRequest.prototype.project = ""; /** - * InsertRegionMultiMigRequest region. + * InsertRegionInstantSnapshotRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest * @instance */ - InsertRegionMultiMigRequest.prototype.region = ""; + InsertRegionInstantSnapshotRequest.prototype.region = ""; /** - * InsertRegionMultiMigRequest requestId. + * InsertRegionInstantSnapshotRequest requestId. * @member {string|null|undefined} requestId - * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest * @instance */ - InsertRegionMultiMigRequest.prototype.requestId = null; + InsertRegionInstantSnapshotRequest.prototype.requestId = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(InsertRegionMultiMigRequest.prototype, "_requestId", { + Object.defineProperty(InsertRegionInstantSnapshotRequest.prototype, "_requestId", { get: $util.oneOfGetter($oneOfFields = ["requestId"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new InsertRegionMultiMigRequest instance using the specified properties. + * Creates a new InsertRegionInstantSnapshotRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest * @static - * @param {google.cloud.compute.v1beta.IInsertRegionMultiMigRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.InsertRegionMultiMigRequest} InsertRegionMultiMigRequest instance + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} InsertRegionInstantSnapshotRequest instance */ - InsertRegionMultiMigRequest.create = function create(properties) { - return new InsertRegionMultiMigRequest(properties); + InsertRegionInstantSnapshotRequest.create = function create(properties) { + return new InsertRegionInstantSnapshotRequest(properties); }; /** - * Encodes the specified InsertRegionMultiMigRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionMultiMigRequest.verify|verify} messages. + * Encodes the specified InsertRegionInstantSnapshotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest * @static - * @param {google.cloud.compute.v1beta.IInsertRegionMultiMigRequest} message InsertRegionMultiMigRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotRequest} message InsertRegionInstantSnapshotRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - InsertRegionMultiMigRequest.encode = function encode(message, writer) { + InsertRegionInstantSnapshotRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); if (message.region != null && Object.hasOwnProperty.call(message, "region")) writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); - if (message.multiMigResource != null && Object.hasOwnProperty.call(message, "multiMigResource")) - $root.google.cloud.compute.v1beta.MultiMig.encode(message.multiMigResource, writer.uint32(/* id 173722824, wireType 2 =*/1389782594).fork()).ldelim(); if (message.project != null && Object.hasOwnProperty.call(message, "project")) writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.instantSnapshotResource != null && Object.hasOwnProperty.call(message, "instantSnapshotResource")) + $root.google.cloud.compute.v1beta.InstantSnapshot.encode(message.instantSnapshotResource, writer.uint32(/* id 383915339, wireType 2 =*/3071322714).fork()).ldelim(); return writer; }; /** - * Encodes the specified InsertRegionMultiMigRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionMultiMigRequest.verify|verify} messages. + * Encodes the specified InsertRegionInstantSnapshotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest * @static - * @param {google.cloud.compute.v1beta.IInsertRegionMultiMigRequest} message InsertRegionMultiMigRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotRequest} message InsertRegionInstantSnapshotRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - InsertRegionMultiMigRequest.encodeDelimited = function encodeDelimited(message, writer) { + InsertRegionInstantSnapshotRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes an InsertRegionMultiMigRequest message from the specified reader or buffer. + * Decodes an InsertRegionInstantSnapshotRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.InsertRegionMultiMigRequest} InsertRegionMultiMigRequest + * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} InsertRegionInstantSnapshotRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - InsertRegionMultiMigRequest.decode = function decode(reader, length, error) { + InsertRegionInstantSnapshotRequest.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.cloud.compute.v1beta.InsertRegionMultiMigRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { - case 173722824: { - message.multiMigResource = $root.google.cloud.compute.v1beta.MultiMig.decode(reader, reader.uint32()); + case 383915339: { + message.instantSnapshotResource = $root.google.cloud.compute.v1beta.InstantSnapshot.decode(reader, reader.uint32()); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InsertRegionInstantSnapshotRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} InsertRegionInstantSnapshotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InsertRegionInstantSnapshotRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InsertRegionInstantSnapshotRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InsertRegionInstantSnapshotRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.instantSnapshotResource != null && message.hasOwnProperty("instantSnapshotResource")) { + var error = $root.google.cloud.compute.v1beta.InstantSnapshot.verify(message.instantSnapshotResource); + if (error) + return "instantSnapshotResource." + error; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + return null; + }; + + /** + * Creates an InsertRegionInstantSnapshotRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} InsertRegionInstantSnapshotRequest + */ + InsertRegionInstantSnapshotRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest(); + if (object.instantSnapshotResource != null) { + if (typeof object.instantSnapshotResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest.instantSnapshotResource: object expected"); + message.instantSnapshotResource = $root.google.cloud.compute.v1beta.InstantSnapshot.fromObject(object.instantSnapshotResource); + } + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.requestId != null) + message.requestId = String(object.requestId); + return message; + }; + + /** + * Creates a plain object from an InsertRegionInstantSnapshotRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @static + * @param {google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest} message InsertRegionInstantSnapshotRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InsertRegionInstantSnapshotRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.project = ""; + object.instantSnapshotResource = null; + } + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.instantSnapshotResource != null && message.hasOwnProperty("instantSnapshotResource")) + object.instantSnapshotResource = $root.google.cloud.compute.v1beta.InstantSnapshot.toObject(message.instantSnapshotResource, options); + return object; + }; + + /** + * Converts this InsertRegionInstantSnapshotRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @instance + * @returns {Object.} JSON object + */ + InsertRegionInstantSnapshotRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InsertRegionInstantSnapshotRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InsertRegionInstantSnapshotRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InsertRegionInstantSnapshotRequest"; + }; + + return InsertRegionInstantSnapshotRequest; + })(); + + v1beta.InsertRegionMultiMigRequest = (function() { + + /** + * Properties of an InsertRegionMultiMigRequest. + * @memberof google.cloud.compute.v1beta + * @interface IInsertRegionMultiMigRequest + * @property {google.cloud.compute.v1beta.IMultiMig|null} [multiMigResource] InsertRegionMultiMigRequest multiMigResource + * @property {string|null} [project] InsertRegionMultiMigRequest project + * @property {string|null} [region] InsertRegionMultiMigRequest region + * @property {string|null} [requestId] InsertRegionMultiMigRequest requestId + */ + + /** + * Constructs a new InsertRegionMultiMigRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InsertRegionMultiMigRequest. + * @implements IInsertRegionMultiMigRequest + * @constructor + * @param {google.cloud.compute.v1beta.IInsertRegionMultiMigRequest=} [properties] Properties to set + */ + function InsertRegionMultiMigRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InsertRegionMultiMigRequest multiMigResource. + * @member {google.cloud.compute.v1beta.IMultiMig|null|undefined} multiMigResource + * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @instance + */ + InsertRegionMultiMigRequest.prototype.multiMigResource = null; + + /** + * InsertRegionMultiMigRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @instance + */ + InsertRegionMultiMigRequest.prototype.project = ""; + + /** + * InsertRegionMultiMigRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @instance + */ + InsertRegionMultiMigRequest.prototype.region = ""; + + /** + * InsertRegionMultiMigRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @instance + */ + InsertRegionMultiMigRequest.prototype.requestId = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InsertRegionMultiMigRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InsertRegionMultiMigRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertRegionMultiMigRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InsertRegionMultiMigRequest} InsertRegionMultiMigRequest instance + */ + InsertRegionMultiMigRequest.create = function create(properties) { + return new InsertRegionMultiMigRequest(properties); + }; + + /** + * Encodes the specified InsertRegionMultiMigRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionMultiMigRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertRegionMultiMigRequest} message InsertRegionMultiMigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InsertRegionMultiMigRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.multiMigResource != null && Object.hasOwnProperty.call(message, "multiMigResource")) + $root.google.cloud.compute.v1beta.MultiMig.encode(message.multiMigResource, writer.uint32(/* id 173722824, wireType 2 =*/1389782594).fork()).ldelim(); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + return writer; + }; + + /** + * Encodes the specified InsertRegionMultiMigRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertRegionMultiMigRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertRegionMultiMigRequest} message InsertRegionMultiMigRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InsertRegionMultiMigRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InsertRegionMultiMigRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InsertRegionMultiMigRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InsertRegionMultiMigRequest} InsertRegionMultiMigRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InsertRegionMultiMigRequest.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.cloud.compute.v1beta.InsertRegionMultiMigRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 173722824: { + message.multiMigResource = $root.google.cloud.compute.v1beta.MultiMig.decode(reader, reader.uint32()); break; } case 227560217: { @@ -900752,6 +907266,277 @@ return InsertServiceAttachmentRequest; })(); + v1beta.InsertSnapshotGroupRequest = (function() { + + /** + * Properties of an InsertSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface IInsertSnapshotGroupRequest + * @property {string|null} [project] InsertSnapshotGroupRequest project + * @property {string|null} [requestId] InsertSnapshotGroupRequest requestId + * @property {google.cloud.compute.v1beta.ISnapshotGroup|null} [snapshotGroupResource] InsertSnapshotGroupRequest snapshotGroupResource + */ + + /** + * Constructs a new InsertSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InsertSnapshotGroupRequest. + * @implements IInsertSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.IInsertSnapshotGroupRequest=} [properties] Properties to set + */ + function InsertSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InsertSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @instance + */ + InsertSnapshotGroupRequest.prototype.project = ""; + + /** + * InsertSnapshotGroupRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @instance + */ + InsertSnapshotGroupRequest.prototype.requestId = null; + + /** + * InsertSnapshotGroupRequest snapshotGroupResource. + * @member {google.cloud.compute.v1beta.ISnapshotGroup|null|undefined} snapshotGroupResource + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @instance + */ + InsertSnapshotGroupRequest.prototype.snapshotGroupResource = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InsertSnapshotGroupRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InsertSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InsertSnapshotGroupRequest} InsertSnapshotGroupRequest instance + */ + InsertSnapshotGroupRequest.create = function create(properties) { + return new InsertSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified InsertSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InsertSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertSnapshotGroupRequest} message InsertSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InsertSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.snapshotGroupResource != null && Object.hasOwnProperty.call(message, "snapshotGroupResource")) + $root.google.cloud.compute.v1beta.SnapshotGroup.encode(message.snapshotGroupResource, writer.uint32(/* id 265205161, wireType 2 =*/2121641290).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified InsertSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InsertSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.IInsertSnapshotGroupRequest} message InsertSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InsertSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InsertSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InsertSnapshotGroupRequest} InsertSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InsertSnapshotGroupRequest.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.cloud.compute.v1beta.InsertSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 227560217: { + message.project = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + case 265205161: { + message.snapshotGroupResource = $root.google.cloud.compute.v1beta.SnapshotGroup.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InsertSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InsertSnapshotGroupRequest} InsertSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InsertSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InsertSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InsertSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + if (message.snapshotGroupResource != null && message.hasOwnProperty("snapshotGroupResource")) { + var error = $root.google.cloud.compute.v1beta.SnapshotGroup.verify(message.snapshotGroupResource); + if (error) + return "snapshotGroupResource." + error; + } + return null; + }; + + /** + * Creates an InsertSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InsertSnapshotGroupRequest} InsertSnapshotGroupRequest + */ + InsertSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InsertSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.InsertSnapshotGroupRequest(); + if (object.project != null) + message.project = String(object.project); + if (object.requestId != null) + message.requestId = String(object.requestId); + if (object.snapshotGroupResource != null) { + if (typeof object.snapshotGroupResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.InsertSnapshotGroupRequest.snapshotGroupResource: object expected"); + message.snapshotGroupResource = $root.google.cloud.compute.v1beta.SnapshotGroup.fromObject(object.snapshotGroupResource); + } + return message; + }; + + /** + * Creates a plain object from an InsertSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.InsertSnapshotGroupRequest} message InsertSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InsertSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.project = ""; + object.snapshotGroupResource = null; + } + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.snapshotGroupResource != null && message.hasOwnProperty("snapshotGroupResource")) + object.snapshotGroupResource = $root.google.cloud.compute.v1beta.SnapshotGroup.toObject(message.snapshotGroupResource, options); + return object; + }; + + /** + * Converts this InsertSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + InsertSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InsertSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InsertSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InsertSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InsertSnapshotGroupRequest"; + }; + + return InsertSnapshotGroupRequest; + })(); + v1beta.InsertSnapshotRequest = (function() { /** @@ -905926,6 +912711,7 @@ * @property {string|null} [status] Instance status * @property {string|null} [statusMessage] Instance statusMessage * @property {google.cloud.compute.v1beta.ITags|null} [tags] Instance tags + * @property {google.cloud.compute.v1beta.IWorkloadIdentityConfig|null} [workloadIdentityConfig] Instance workloadIdentityConfig * @property {string|null} [zone] Instance zone */ @@ -906351,6 +913137,14 @@ */ Instance.prototype.tags = null; + /** + * Instance workloadIdentityConfig. + * @member {google.cloud.compute.v1beta.IWorkloadIdentityConfig|null|undefined} workloadIdentityConfig + * @memberof google.cloud.compute.v1beta.Instance + * @instance + */ + Instance.prototype.workloadIdentityConfig = null; + /** * Instance zone. * @member {string|null|undefined} zone @@ -906620,6 +913414,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(Instance.prototype, "_workloadIdentityConfig", { + get: $util.oneOfGetter($oneOfFields = ["workloadIdentityConfig"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(Instance.prototype, "_zone", { get: $util.oneOfGetter($oneOfFields = ["zone"]), @@ -906725,6 +913525,8 @@ writer.uint32(/* id 292972897, wireType 2 =*/2343783178).string(message.postKeyRevocationActionType); if (message.statusMessage != null && Object.hasOwnProperty.call(message, "statusMessage")) writer.uint32(/* id 297428154, wireType 2 =*/2379425234).string(message.statusMessage); + if (message.workloadIdentityConfig != null && Object.hasOwnProperty.call(message, "workloadIdentityConfig")) + $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.encode(message.workloadIdentityConfig, writer.uint32(/* id 338198811, wireType 2 =*/2705590490).fork()).ldelim(); if (message.lastSuspendedTimestamp != null && Object.hasOwnProperty.call(message, "lastSuspendedTimestamp")) writer.uint32(/* id 356275337, wireType 2 =*/2850202698).string(message.lastSuspendedTimestamp); if (message.scheduling != null && Object.hasOwnProperty.call(message, "scheduling")) @@ -907045,6 +913847,10 @@ message.tags = $root.google.cloud.compute.v1beta.Tags.decode(reader, reader.uint32()); break; } + case 338198811: { + message.workloadIdentityConfig = $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.decode(reader, reader.uint32()); + break; + } case 3744684: { message.zone = reader.string(); break; @@ -907409,6 +914215,14 @@ return "tags." + error; } } + if (message.workloadIdentityConfig != null && message.hasOwnProperty("workloadIdentityConfig")) { + properties._workloadIdentityConfig = 1; + { + var error = $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.verify(message.workloadIdentityConfig); + if (error) + return "workloadIdentityConfig." + error; + } + } if (message.zone != null && message.hasOwnProperty("zone")) { properties._zone = 1; if (!$util.isString(message.zone)) @@ -907634,6 +914448,11 @@ throw TypeError(".google.cloud.compute.v1beta.Instance.tags: object expected"); message.tags = $root.google.cloud.compute.v1beta.Tags.fromObject(object.tags); } + if (object.workloadIdentityConfig != null) { + if (typeof object.workloadIdentityConfig !== "object") + throw TypeError(".google.cloud.compute.v1beta.Instance.workloadIdentityConfig: object expected"); + message.workloadIdentityConfig = $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.fromObject(object.workloadIdentityConfig); + } if (object.zone != null) message.zone = String(object.zone); return message; @@ -907837,6 +914656,11 @@ if (options.oneofs) object._statusMessage = "statusMessage"; } + if (message.workloadIdentityConfig != null && message.hasOwnProperty("workloadIdentityConfig")) { + object.workloadIdentityConfig = $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.toObject(message.workloadIdentityConfig, options); + if (options.oneofs) + object._workloadIdentityConfig = "workloadIdentityConfig"; + } if (message.lastSuspendedTimestamp != null && message.hasOwnProperty("lastSuspendedTimestamp")) { object.lastSuspendedTimestamp = message.lastSuspendedTimestamp; if (options.oneofs) @@ -918529,6 +925353,7 @@ * @property {google.cloud.compute.v1beta.IInstanceGroupManagerStatusAllInstancesConfig|null} [allInstancesConfig] InstanceGroupManagerStatus allInstancesConfig * @property {string|null} [autoscaler] InstanceGroupManagerStatus autoscaler * @property {google.cloud.compute.v1beta.IInstanceGroupManagerStatusBulkInstanceOperation|null} [bulkInstanceOperation] InstanceGroupManagerStatus bulkInstanceOperation + * @property {google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary|null} [currentInstanceStatuses] InstanceGroupManagerStatus currentInstanceStatuses * @property {boolean|null} [isStable] InstanceGroupManagerStatus isStable * @property {google.cloud.compute.v1beta.IInstanceGroupManagerStatusStateful|null} [stateful] InstanceGroupManagerStatus stateful * @property {google.cloud.compute.v1beta.IInstanceGroupManagerStatusVersionTarget|null} [versionTarget] InstanceGroupManagerStatus versionTarget @@ -918573,6 +925398,14 @@ */ InstanceGroupManagerStatus.prototype.bulkInstanceOperation = null; + /** + * InstanceGroupManagerStatus currentInstanceStatuses. + * @member {google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary|null|undefined} currentInstanceStatuses + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatus + * @instance + */ + InstanceGroupManagerStatus.prototype.currentInstanceStatuses = null; + /** * InstanceGroupManagerStatus isStable. * @member {boolean|null|undefined} isStable @@ -918618,6 +925451,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatus.prototype, "_currentInstanceStatuses", { + get: $util.oneOfGetter($oneOfFields = ["currentInstanceStatuses"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(InstanceGroupManagerStatus.prototype, "_isStable", { get: $util.oneOfGetter($oneOfFields = ["isStable"]), @@ -918666,6 +925505,8 @@ $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusAllInstancesConfig.encode(message.allInstancesConfig, writer.uint32(/* id 112596737, wireType 2 =*/900773898).fork()).ldelim(); if (message.stateful != null && Object.hasOwnProperty.call(message, "stateful")) $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusStateful.encode(message.stateful, writer.uint32(/* id 244462412, wireType 2 =*/1955699298).fork()).ldelim(); + if (message.currentInstanceStatuses != null && Object.hasOwnProperty.call(message, "currentInstanceStatuses")) + $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.encode(message.currentInstanceStatuses, writer.uint32(/* id 269432644, wireType 2 =*/2155461154).fork()).ldelim(); if (message.versionTarget != null && Object.hasOwnProperty.call(message, "versionTarget")) $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusVersionTarget.encode(message.versionTarget, writer.uint32(/* id 289386200, wireType 2 =*/2315089602).fork()).ldelim(); if (message.bulkInstanceOperation != null && Object.hasOwnProperty.call(message, "bulkInstanceOperation")) @@ -918720,6 +925561,10 @@ message.bulkInstanceOperation = $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusBulkInstanceOperation.decode(reader, reader.uint32()); break; } + case 269432644: { + message.currentInstanceStatuses = $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.decode(reader, reader.uint32()); + break; + } case 108410864: { message.isStable = reader.bool(); break; @@ -918789,6 +925634,14 @@ return "bulkInstanceOperation." + error; } } + if (message.currentInstanceStatuses != null && message.hasOwnProperty("currentInstanceStatuses")) { + properties._currentInstanceStatuses = 1; + { + var error = $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.verify(message.currentInstanceStatuses); + if (error) + return "currentInstanceStatuses." + error; + } + } if (message.isStable != null && message.hasOwnProperty("isStable")) { properties._isStable = 1; if (typeof message.isStable !== "boolean") @@ -918837,6 +925690,11 @@ throw TypeError(".google.cloud.compute.v1beta.InstanceGroupManagerStatus.bulkInstanceOperation: object expected"); message.bulkInstanceOperation = $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusBulkInstanceOperation.fromObject(object.bulkInstanceOperation); } + if (object.currentInstanceStatuses != null) { + if (typeof object.currentInstanceStatuses !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstanceGroupManagerStatus.currentInstanceStatuses: object expected"); + message.currentInstanceStatuses = $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.fromObject(object.currentInstanceStatuses); + } if (object.isStable != null) message.isStable = Boolean(object.isStable); if (object.stateful != null) { @@ -918880,6 +925738,11 @@ if (options.oneofs) object._stateful = "stateful"; } + if (message.currentInstanceStatuses != null && message.hasOwnProperty("currentInstanceStatuses")) { + object.currentInstanceStatuses = $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.toObject(message.currentInstanceStatuses, options); + if (options.oneofs) + object._currentInstanceStatuses = "currentInstanceStatuses"; + } if (message.versionTarget != null && message.hasOwnProperty("versionTarget")) { object.versionTarget = $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusVersionTarget.toObject(message.versionTarget, options); if (options.oneofs) @@ -919692,6 +926555,620 @@ return InstanceGroupManagerStatusBulkInstanceOperationLastProgressCheck; })(); + v1beta.InstanceGroupManagerStatusInstanceStatusSummary = (function() { + + /** + * Properties of an InstanceGroupManagerStatusInstanceStatusSummary. + * @memberof google.cloud.compute.v1beta + * @interface IInstanceGroupManagerStatusInstanceStatusSummary + * @property {number|null} [deprovisioning] InstanceGroupManagerStatusInstanceStatusSummary deprovisioning + * @property {number|null} [nonExistent] InstanceGroupManagerStatusInstanceStatusSummary nonExistent + * @property {number|null} [pending] InstanceGroupManagerStatusInstanceStatusSummary pending + * @property {number|null} [pendingStop] InstanceGroupManagerStatusInstanceStatusSummary pendingStop + * @property {number|null} [provisioning] InstanceGroupManagerStatusInstanceStatusSummary provisioning + * @property {number|null} [repairing] InstanceGroupManagerStatusInstanceStatusSummary repairing + * @property {number|null} [running] InstanceGroupManagerStatusInstanceStatusSummary running + * @property {number|null} [staging] InstanceGroupManagerStatusInstanceStatusSummary staging + * @property {number|null} [stopped] InstanceGroupManagerStatusInstanceStatusSummary stopped + * @property {number|null} [stopping] InstanceGroupManagerStatusInstanceStatusSummary stopping + * @property {number|null} [suspended] InstanceGroupManagerStatusInstanceStatusSummary suspended + * @property {number|null} [suspending] InstanceGroupManagerStatusInstanceStatusSummary suspending + * @property {number|null} [terminated] InstanceGroupManagerStatusInstanceStatusSummary terminated + */ + + /** + * Constructs a new InstanceGroupManagerStatusInstanceStatusSummary. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstanceGroupManagerStatusInstanceStatusSummary. + * @implements IInstanceGroupManagerStatusInstanceStatusSummary + * @constructor + * @param {google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary=} [properties] Properties to set + */ + function InstanceGroupManagerStatusInstanceStatusSummary(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstanceGroupManagerStatusInstanceStatusSummary deprovisioning. + * @member {number|null|undefined} deprovisioning + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.deprovisioning = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary nonExistent. + * @member {number|null|undefined} nonExistent + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.nonExistent = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary pending. + * @member {number|null|undefined} pending + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.pending = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary pendingStop. + * @member {number|null|undefined} pendingStop + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.pendingStop = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary provisioning. + * @member {number|null|undefined} provisioning + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.provisioning = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary repairing. + * @member {number|null|undefined} repairing + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.repairing = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary running. + * @member {number|null|undefined} running + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.running = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary staging. + * @member {number|null|undefined} staging + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.staging = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary stopped. + * @member {number|null|undefined} stopped + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.stopped = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary stopping. + * @member {number|null|undefined} stopping + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.stopping = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary suspended. + * @member {number|null|undefined} suspended + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.suspended = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary suspending. + * @member {number|null|undefined} suspending + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.suspending = null; + + /** + * InstanceGroupManagerStatusInstanceStatusSummary terminated. + * @member {number|null|undefined} terminated + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.terminated = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_deprovisioning", { + get: $util.oneOfGetter($oneOfFields = ["deprovisioning"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_nonExistent", { + get: $util.oneOfGetter($oneOfFields = ["nonExistent"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_pending", { + get: $util.oneOfGetter($oneOfFields = ["pending"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_pendingStop", { + get: $util.oneOfGetter($oneOfFields = ["pendingStop"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_provisioning", { + get: $util.oneOfGetter($oneOfFields = ["provisioning"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_repairing", { + get: $util.oneOfGetter($oneOfFields = ["repairing"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_running", { + get: $util.oneOfGetter($oneOfFields = ["running"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_staging", { + get: $util.oneOfGetter($oneOfFields = ["staging"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_stopped", { + get: $util.oneOfGetter($oneOfFields = ["stopped"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_stopping", { + get: $util.oneOfGetter($oneOfFields = ["stopping"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_suspended", { + get: $util.oneOfGetter($oneOfFields = ["suspended"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_suspending", { + get: $util.oneOfGetter($oneOfFields = ["suspending"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagerStatusInstanceStatusSummary.prototype, "_terminated", { + get: $util.oneOfGetter($oneOfFields = ["terminated"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InstanceGroupManagerStatusInstanceStatusSummary instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary} InstanceGroupManagerStatusInstanceStatusSummary instance + */ + InstanceGroupManagerStatusInstanceStatusSummary.create = function create(properties) { + return new InstanceGroupManagerStatusInstanceStatusSummary(properties); + }; + + /** + * Encodes the specified InstanceGroupManagerStatusInstanceStatusSummary message. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary} message InstanceGroupManagerStatusInstanceStatusSummary message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstanceGroupManagerStatusInstanceStatusSummary.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.suspending != null && Object.hasOwnProperty.call(message, "suspending")) + writer.uint32(/* id 29113894, wireType 0 =*/232911152).int32(message.suspending); + if (message.stopping != null && Object.hasOwnProperty.call(message, "stopping")) + writer.uint32(/* id 105035892, wireType 0 =*/840287136).int32(message.stopping); + if (message.provisioning != null && Object.hasOwnProperty.call(message, "provisioning")) + writer.uint32(/* id 121098989, wireType 0 =*/968791912).int32(message.provisioning); + if (message.pendingStop != null && Object.hasOwnProperty.call(message, "pendingStop")) + writer.uint32(/* id 163159466, wireType 0 =*/1305275728).int32(message.pendingStop); + if (message.staging != null && Object.hasOwnProperty.call(message, "staging")) + writer.uint32(/* id 249960507, wireType 0 =*/1999684056).int32(message.staging); + if (message.stopped != null && Object.hasOwnProperty.call(message, "stopped")) + writer.uint32(/* id 263164365, wireType 0 =*/2105314920).int32(message.stopped); + if (message.terminated != null && Object.hasOwnProperty.call(message, "terminated")) + writer.uint32(/* id 301796899, wireType 0 =*/2414375192).int32(message.terminated); + if (message.repairing != null && Object.hasOwnProperty.call(message, "repairing")) + writer.uint32(/* id 311243061, wireType 0 =*/2489944488).int32(message.repairing); + if (message.pending != null && Object.hasOwnProperty.call(message, "pending")) + writer.uint32(/* id 391154071, wireType 0 =*/3129232568).int32(message.pending); + if (message.deprovisioning != null && Object.hasOwnProperty.call(message, "deprovisioning")) + writer.uint32(/* id 462169582, wireType 0 =*/3697356656).int32(message.deprovisioning); + if (message.nonExistent != null && Object.hasOwnProperty.call(message, "nonExistent")) + writer.uint32(/* id 468485062, wireType 0 =*/3747880496).int32(message.nonExistent); + if (message.running != null && Object.hasOwnProperty.call(message, "running")) + writer.uint32(/* id 477042111, wireType 0 =*/3816336888).int32(message.running); + if (message.suspended != null && Object.hasOwnProperty.call(message, "suspended")) + writer.uint32(/* id 485854683, wireType 0 =*/3886837464).int32(message.suspended); + return writer; + }; + + /** + * Encodes the specified InstanceGroupManagerStatusInstanceStatusSummary message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagerStatusInstanceStatusSummary} message InstanceGroupManagerStatusInstanceStatusSummary message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstanceGroupManagerStatusInstanceStatusSummary.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstanceGroupManagerStatusInstanceStatusSummary message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary} InstanceGroupManagerStatusInstanceStatusSummary + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstanceGroupManagerStatusInstanceStatusSummary.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.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 462169582: { + message.deprovisioning = reader.int32(); + break; + } + case 468485062: { + message.nonExistent = reader.int32(); + break; + } + case 391154071: { + message.pending = reader.int32(); + break; + } + case 163159466: { + message.pendingStop = reader.int32(); + break; + } + case 121098989: { + message.provisioning = reader.int32(); + break; + } + case 311243061: { + message.repairing = reader.int32(); + break; + } + case 477042111: { + message.running = reader.int32(); + break; + } + case 249960507: { + message.staging = reader.int32(); + break; + } + case 263164365: { + message.stopped = reader.int32(); + break; + } + case 105035892: { + message.stopping = reader.int32(); + break; + } + case 485854683: { + message.suspended = reader.int32(); + break; + } + case 29113894: { + message.suspending = reader.int32(); + break; + } + case 301796899: { + message.terminated = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstanceGroupManagerStatusInstanceStatusSummary message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary} InstanceGroupManagerStatusInstanceStatusSummary + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstanceGroupManagerStatusInstanceStatusSummary.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstanceGroupManagerStatusInstanceStatusSummary message. + * @function verify + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstanceGroupManagerStatusInstanceStatusSummary.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.deprovisioning != null && message.hasOwnProperty("deprovisioning")) { + properties._deprovisioning = 1; + if (!$util.isInteger(message.deprovisioning)) + return "deprovisioning: integer expected"; + } + if (message.nonExistent != null && message.hasOwnProperty("nonExistent")) { + properties._nonExistent = 1; + if (!$util.isInteger(message.nonExistent)) + return "nonExistent: integer expected"; + } + if (message.pending != null && message.hasOwnProperty("pending")) { + properties._pending = 1; + if (!$util.isInteger(message.pending)) + return "pending: integer expected"; + } + if (message.pendingStop != null && message.hasOwnProperty("pendingStop")) { + properties._pendingStop = 1; + if (!$util.isInteger(message.pendingStop)) + return "pendingStop: integer expected"; + } + if (message.provisioning != null && message.hasOwnProperty("provisioning")) { + properties._provisioning = 1; + if (!$util.isInteger(message.provisioning)) + return "provisioning: integer expected"; + } + if (message.repairing != null && message.hasOwnProperty("repairing")) { + properties._repairing = 1; + if (!$util.isInteger(message.repairing)) + return "repairing: integer expected"; + } + if (message.running != null && message.hasOwnProperty("running")) { + properties._running = 1; + if (!$util.isInteger(message.running)) + return "running: integer expected"; + } + if (message.staging != null && message.hasOwnProperty("staging")) { + properties._staging = 1; + if (!$util.isInteger(message.staging)) + return "staging: integer expected"; + } + if (message.stopped != null && message.hasOwnProperty("stopped")) { + properties._stopped = 1; + if (!$util.isInteger(message.stopped)) + return "stopped: integer expected"; + } + if (message.stopping != null && message.hasOwnProperty("stopping")) { + properties._stopping = 1; + if (!$util.isInteger(message.stopping)) + return "stopping: integer expected"; + } + if (message.suspended != null && message.hasOwnProperty("suspended")) { + properties._suspended = 1; + if (!$util.isInteger(message.suspended)) + return "suspended: integer expected"; + } + if (message.suspending != null && message.hasOwnProperty("suspending")) { + properties._suspending = 1; + if (!$util.isInteger(message.suspending)) + return "suspending: integer expected"; + } + if (message.terminated != null && message.hasOwnProperty("terminated")) { + properties._terminated = 1; + if (!$util.isInteger(message.terminated)) + return "terminated: integer expected"; + } + return null; + }; + + /** + * Creates an InstanceGroupManagerStatusInstanceStatusSummary message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary} InstanceGroupManagerStatusInstanceStatusSummary + */ + InstanceGroupManagerStatusInstanceStatusSummary.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary) + return object; + var message = new $root.google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary(); + if (object.deprovisioning != null) + message.deprovisioning = object.deprovisioning | 0; + if (object.nonExistent != null) + message.nonExistent = object.nonExistent | 0; + if (object.pending != null) + message.pending = object.pending | 0; + if (object.pendingStop != null) + message.pendingStop = object.pendingStop | 0; + if (object.provisioning != null) + message.provisioning = object.provisioning | 0; + if (object.repairing != null) + message.repairing = object.repairing | 0; + if (object.running != null) + message.running = object.running | 0; + if (object.staging != null) + message.staging = object.staging | 0; + if (object.stopped != null) + message.stopped = object.stopped | 0; + if (object.stopping != null) + message.stopping = object.stopping | 0; + if (object.suspended != null) + message.suspended = object.suspended | 0; + if (object.suspending != null) + message.suspending = object.suspending | 0; + if (object.terminated != null) + message.terminated = object.terminated | 0; + return message; + }; + + /** + * Creates a plain object from an InstanceGroupManagerStatusInstanceStatusSummary message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary} message InstanceGroupManagerStatusInstanceStatusSummary + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstanceGroupManagerStatusInstanceStatusSummary.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.suspending != null && message.hasOwnProperty("suspending")) { + object.suspending = message.suspending; + if (options.oneofs) + object._suspending = "suspending"; + } + if (message.stopping != null && message.hasOwnProperty("stopping")) { + object.stopping = message.stopping; + if (options.oneofs) + object._stopping = "stopping"; + } + if (message.provisioning != null && message.hasOwnProperty("provisioning")) { + object.provisioning = message.provisioning; + if (options.oneofs) + object._provisioning = "provisioning"; + } + if (message.pendingStop != null && message.hasOwnProperty("pendingStop")) { + object.pendingStop = message.pendingStop; + if (options.oneofs) + object._pendingStop = "pendingStop"; + } + if (message.staging != null && message.hasOwnProperty("staging")) { + object.staging = message.staging; + if (options.oneofs) + object._staging = "staging"; + } + if (message.stopped != null && message.hasOwnProperty("stopped")) { + object.stopped = message.stopped; + if (options.oneofs) + object._stopped = "stopped"; + } + if (message.terminated != null && message.hasOwnProperty("terminated")) { + object.terminated = message.terminated; + if (options.oneofs) + object._terminated = "terminated"; + } + if (message.repairing != null && message.hasOwnProperty("repairing")) { + object.repairing = message.repairing; + if (options.oneofs) + object._repairing = "repairing"; + } + if (message.pending != null && message.hasOwnProperty("pending")) { + object.pending = message.pending; + if (options.oneofs) + object._pending = "pending"; + } + if (message.deprovisioning != null && message.hasOwnProperty("deprovisioning")) { + object.deprovisioning = message.deprovisioning; + if (options.oneofs) + object._deprovisioning = "deprovisioning"; + } + if (message.nonExistent != null && message.hasOwnProperty("nonExistent")) { + object.nonExistent = message.nonExistent; + if (options.oneofs) + object._nonExistent = "nonExistent"; + } + if (message.running != null && message.hasOwnProperty("running")) { + object.running = message.running; + if (options.oneofs) + object._running = "running"; + } + if (message.suspended != null && message.hasOwnProperty("suspended")) { + object.suspended = message.suspended; + if (options.oneofs) + object._suspended = "suspended"; + } + return object; + }; + + /** + * Converts this InstanceGroupManagerStatusInstanceStatusSummary to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @instance + * @returns {Object.} JSON object + */ + InstanceGroupManagerStatusInstanceStatusSummary.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstanceGroupManagerStatusInstanceStatusSummary + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstanceGroupManagerStatusInstanceStatusSummary.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InstanceGroupManagerStatusInstanceStatusSummary"; + }; + + return InstanceGroupManagerStatusInstanceStatusSummary; + })(); + v1beta.InstanceGroupManagerStatusStateful = (function() { /** @@ -922040,6 +929517,246 @@ return InstanceGroupManagersApplyUpdatesRequest; })(); + v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest = (function() { + + /** + * Properties of an InstanceGroupManagersConfigureAcceleratorTopologiesRequest. + * @memberof google.cloud.compute.v1beta + * @interface IInstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @property {Object.|null} [acceleratorTopologyActions] InstanceGroupManagersConfigureAcceleratorTopologiesRequest acceleratorTopologyActions + */ + + /** + * Constructs a new InstanceGroupManagersConfigureAcceleratorTopologiesRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstanceGroupManagersConfigureAcceleratorTopologiesRequest. + * @implements IInstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @constructor + * @param {google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest=} [properties] Properties to set + */ + function InstanceGroupManagersConfigureAcceleratorTopologiesRequest(properties) { + this.acceleratorTopologyActions = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstanceGroupManagersConfigureAcceleratorTopologiesRequest acceleratorTopologyActions. + * @member {Object.} acceleratorTopologyActions + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @instance + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.prototype.acceleratorTopologyActions = $util.emptyObject; + + /** + * Creates a new InstanceGroupManagersConfigureAcceleratorTopologiesRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest} InstanceGroupManagersConfigureAcceleratorTopologiesRequest instance + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.create = function create(properties) { + return new InstanceGroupManagersConfigureAcceleratorTopologiesRequest(properties); + }; + + /** + * Encodes the specified InstanceGroupManagersConfigureAcceleratorTopologiesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest} message InstanceGroupManagersConfigureAcceleratorTopologiesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.acceleratorTopologyActions != null && Object.hasOwnProperty.call(message, "acceleratorTopologyActions")) + for (var keys = Object.keys(message.acceleratorTopologyActions), i = 0; i < keys.length; ++i) + writer.uint32(/* id 16520833, wireType 2 =*/132166666).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.acceleratorTopologyActions[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified InstanceGroupManagersConfigureAcceleratorTopologiesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagersConfigureAcceleratorTopologiesRequest} message InstanceGroupManagersConfigureAcceleratorTopologiesRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest} InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.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.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 16520833: { + if (message.acceleratorTopologyActions === $util.emptyObject) + message.acceleratorTopologyActions = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.acceleratorTopologyActions[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest} InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.acceleratorTopologyActions != null && message.hasOwnProperty("acceleratorTopologyActions")) { + if (!$util.isObject(message.acceleratorTopologyActions)) + return "acceleratorTopologyActions: object expected"; + var key = Object.keys(message.acceleratorTopologyActions); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.acceleratorTopologyActions[key[i]])) + return "acceleratorTopologyActions: string{k:string} expected"; + } + return null; + }; + + /** + * Creates an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest} InstanceGroupManagersConfigureAcceleratorTopologiesRequest + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest(); + if (object.acceleratorTopologyActions) { + if (typeof object.acceleratorTopologyActions !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest.acceleratorTopologyActions: object expected"); + message.acceleratorTopologyActions = {}; + for (var keys = Object.keys(object.acceleratorTopologyActions), i = 0; i < keys.length; ++i) + message.acceleratorTopologyActions[keys[i]] = String(object.acceleratorTopologyActions[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from an InstanceGroupManagersConfigureAcceleratorTopologiesRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest} message InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.acceleratorTopologyActions = {}; + var keys2; + if (message.acceleratorTopologyActions && (keys2 = Object.keys(message.acceleratorTopologyActions)).length) { + object.acceleratorTopologyActions = {}; + for (var j = 0; j < keys2.length; ++j) + object.acceleratorTopologyActions[keys2[j]] = message.acceleratorTopologyActions[keys2[j]]; + } + return object; + }; + + /** + * Converts this InstanceGroupManagersConfigureAcceleratorTopologiesRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @instance + * @returns {Object.} JSON object + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstanceGroupManagersConfigureAcceleratorTopologiesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest"; + }; + + return InstanceGroupManagersConfigureAcceleratorTopologiesRequest; + })(); + v1beta.InstanceGroupManagersCreateInstancesRequest = (function() { /** @@ -922752,6 +930469,7 @@ * @memberof google.cloud.compute.v1beta * @interface IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponse * @property {Object.|null} [acceleratorTopologiesInfo] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse acceleratorTopologiesInfo + * @property {string|null} [multiMig] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse multiMig */ /** @@ -922778,6 +930496,23 @@ */ InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse.prototype.acceleratorTopologiesInfo = $util.emptyObject; + /** + * InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse multiMig. + * @member {string|null|undefined} multiMig + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse + * @instance + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse.prototype.multiMig = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse.prototype, "_multiMig", { + get: $util.oneOfGetter($oneOfFields = ["multiMig"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** * Creates a new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse instance using the specified properties. * @function create @@ -922807,6 +930542,8 @@ writer.uint32(/* id 84833420, wireType 2 =*/678667362).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.encode(message.acceleratorTopologiesInfo[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); } + if (message.multiMig != null && Object.hasOwnProperty.call(message, "multiMig")) + writer.uint32(/* id 403990085, wireType 2 =*/3231920682).string(message.multiMig); return writer; }; @@ -922866,6 +930603,10 @@ message.acceleratorTopologiesInfo[key] = value; break; } + case 403990085: { + message.multiMig = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -922901,6 +930642,7 @@ InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; + var properties = {}; if (message.acceleratorTopologiesInfo != null && message.hasOwnProperty("acceleratorTopologiesInfo")) { if (!$util.isObject(message.acceleratorTopologiesInfo)) return "acceleratorTopologiesInfo: object expected"; @@ -922911,6 +930653,11 @@ return "acceleratorTopologiesInfo." + error; } } + if (message.multiMig != null && message.hasOwnProperty("multiMig")) { + properties._multiMig = 1; + if (!$util.isString(message.multiMig)) + return "multiMig: string expected"; + } return null; }; @@ -922936,6 +930683,8 @@ message.acceleratorTopologiesInfo[keys[i]] = $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.fromObject(object.acceleratorTopologiesInfo[keys[i]]); } } + if (object.multiMig != null) + message.multiMig = String(object.multiMig); return message; }; @@ -922960,6 +930709,11 @@ for (var j = 0; j < keys2.length; ++j) object.acceleratorTopologiesInfo[keys2[j]] = $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.toObject(message.acceleratorTopologiesInfo[keys2[j]], options); } + if (message.multiMig != null && message.hasOwnProperty("multiMig")) { + object.multiMig = message.multiMig; + if (options.oneofs) + object._multiMig = "multiMig"; + } return object; }; @@ -923000,6 +930754,9 @@ * @interface IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo * @property {string|null} [acceleratorTopology] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo acceleratorTopology * @property {string|null} [acceleratorTopologyHealth] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo acceleratorTopologyHealth + * @property {google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState|null} [acceleratorTopologyState] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo acceleratorTopologyState + * @property {string|null} [instancesHealth] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo instancesHealth + * @property {string|null} [parent] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo parent */ /** @@ -923033,6 +930790,30 @@ */ InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.prototype.acceleratorTopologyHealth = null; + /** + * InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo acceleratorTopologyState. + * @member {google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState|null|undefined} acceleratorTopologyState + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo + * @instance + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.prototype.acceleratorTopologyState = null; + + /** + * InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo instancesHealth. + * @member {string|null|undefined} instancesHealth + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo + * @instance + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.prototype.instancesHealth = null; + + /** + * InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo parent. + * @member {string|null|undefined} parent + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo + * @instance + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.prototype.parent = null; + // OneOf field names bound to virtual getters and setters var $oneOfFields; @@ -923048,6 +930829,24 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.prototype, "_acceleratorTopologyState", { + get: $util.oneOfGetter($oneOfFields = ["acceleratorTopologyState"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.prototype, "_instancesHealth", { + get: $util.oneOfGetter($oneOfFields = ["instancesHealth"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.prototype, "_parent", { + get: $util.oneOfGetter($oneOfFields = ["parent"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** * Creates a new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo instance using the specified properties. * @function create @@ -923072,6 +930871,12 @@ InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 78317738, wireType 2 =*/626541906).string(message.parent); + if (message.instancesHealth != null && Object.hasOwnProperty.call(message, "instancesHealth")) + writer.uint32(/* id 165893949, wireType 2 =*/1327151594).string(message.instancesHealth); + if (message.acceleratorTopologyState != null && Object.hasOwnProperty.call(message, "acceleratorTopologyState")) + $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.encode(message.acceleratorTopologyState, writer.uint32(/* id 228860693, wireType 2 =*/1830885546).fork()).ldelim(); if (message.acceleratorTopologyHealth != null && Object.hasOwnProperty.call(message, "acceleratorTopologyHealth")) writer.uint32(/* id 323449944, wireType 2 =*/2587599554).string(message.acceleratorTopologyHealth); if (message.acceleratorTopology != null && Object.hasOwnProperty.call(message, "acceleratorTopology")) @@ -923120,6 +930925,18 @@ message.acceleratorTopologyHealth = reader.string(); break; } + case 228860693: { + message.acceleratorTopologyState = $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.decode(reader, reader.uint32()); + break; + } + case 165893949: { + message.instancesHealth = reader.string(); + break; + } + case 78317738: { + message.parent = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -923166,6 +930983,24 @@ if (!$util.isString(message.acceleratorTopologyHealth)) return "acceleratorTopologyHealth: string expected"; } + if (message.acceleratorTopologyState != null && message.hasOwnProperty("acceleratorTopologyState")) { + properties._acceleratorTopologyState = 1; + { + var error = $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.verify(message.acceleratorTopologyState); + if (error) + return "acceleratorTopologyState." + error; + } + } + if (message.instancesHealth != null && message.hasOwnProperty("instancesHealth")) { + properties._instancesHealth = 1; + if (!$util.isString(message.instancesHealth)) + return "instancesHealth: string expected"; + } + if (message.parent != null && message.hasOwnProperty("parent")) { + properties._parent = 1; + if (!$util.isString(message.parent)) + return "parent: string expected"; + } return null; }; @@ -923185,6 +931020,15 @@ message.acceleratorTopology = String(object.acceleratorTopology); if (object.acceleratorTopologyHealth != null) message.acceleratorTopologyHealth = String(object.acceleratorTopologyHealth); + if (object.acceleratorTopologyState != null) { + if (typeof object.acceleratorTopologyState !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.acceleratorTopologyState: object expected"); + message.acceleratorTopologyState = $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.fromObject(object.acceleratorTopologyState); + } + if (object.instancesHealth != null) + message.instancesHealth = String(object.instancesHealth); + if (object.parent != null) + message.parent = String(object.parent); return message; }; @@ -923201,6 +931045,21 @@ if (!options) options = {}; var object = {}; + if (message.parent != null && message.hasOwnProperty("parent")) { + object.parent = message.parent; + if (options.oneofs) + object._parent = "parent"; + } + if (message.instancesHealth != null && message.hasOwnProperty("instancesHealth")) { + object.instancesHealth = message.instancesHealth; + if (options.oneofs) + object._instancesHealth = "instancesHealth"; + } + if (message.acceleratorTopologyState != null && message.hasOwnProperty("acceleratorTopologyState")) { + object.acceleratorTopologyState = $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.toObject(message.acceleratorTopologyState, options); + if (options.oneofs) + object._acceleratorTopologyState = "acceleratorTopologyState"; + } if (message.acceleratorTopologyHealth != null && message.hasOwnProperty("acceleratorTopologyHealth")) { object.acceleratorTopologyHealth = message.acceleratorTopologyHealth; if (options.oneofs) @@ -923248,6 +931107,7 @@ * @property {number} DEGRADED=396890926 DEGRADED value * @property {number} HEALTHY=439801213 HEALTHY value * @property {number} UNHEALTHY=462118084 UNHEALTHY value + * @property {number} UNKNOWN=433141802 UNKNOWN value */ InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.AcceleratorTopologyHealth = (function() { var valuesById = {}, values = Object.create(valuesById); @@ -923255,12 +931115,345 @@ values[valuesById[396890926] = "DEGRADED"] = 396890926; values[valuesById[439801213] = "HEALTHY"] = 439801213; values[valuesById[462118084] = "UNHEALTHY"] = 462118084; + values[valuesById[433141802] = "UNKNOWN"] = 433141802; + return values; + })(); + + /** + * InstancesHealth enum. + * @name google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.InstancesHealth + * @enum {number} + * @property {number} UNDEFINED_INSTANCES_HEALTH=0 UNDEFINED_INSTANCES_HEALTH value + * @property {number} ALL_HEALTHY=519465151 ALL_HEALTHY value + * @property {number} UNHEALTHY_OR_MISSING=59982149 UNHEALTHY_OR_MISSING value + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo.InstancesHealth = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_INSTANCES_HEALTH"] = 0; + values[valuesById[519465151] = "ALL_HEALTHY"] = 519465151; + values[valuesById[59982149] = "UNHEALTHY_OR_MISSING"] = 59982149; return values; })(); return InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo; })(); + v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState = (function() { + + /** + * Properties of an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState. + * @memberof google.cloud.compute.v1beta + * @interface IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @property {string|null} [currentState] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState currentState + * @property {google.cloud.compute.v1beta.IError|null} [error] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState error + * @property {string|null} [errorTimestamp] InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState errorTimestamp + */ + + /** + * Constructs a new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState. + * @implements IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @constructor + * @param {google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState=} [properties] Properties to set + */ + function InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState currentState. + * @member {string|null|undefined} currentState + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @instance + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.prototype.currentState = null; + + /** + * InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState error. + * @member {google.cloud.compute.v1beta.IError|null|undefined} error + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @instance + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.prototype.error = null; + + /** + * InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState errorTimestamp. + * @member {string|null|undefined} errorTimestamp + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @instance + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.prototype.errorTimestamp = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.prototype, "_currentState", { + get: $util.oneOfGetter($oneOfFields = ["currentState"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.prototype, "_error", { + get: $util.oneOfGetter($oneOfFields = ["error"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.prototype, "_errorTimestamp", { + get: $util.oneOfGetter($oneOfFields = ["errorTimestamp"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState} InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState instance + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.create = function create(properties) { + return new InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState(properties); + }; + + /** + * Encodes the specified InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState} message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.error != null && Object.hasOwnProperty.call(message, "error")) + $root.google.cloud.compute.v1beta.Error.encode(message.error, writer.uint32(/* id 96784904, wireType 2 =*/774279234).fork()).ldelim(); + if (message.errorTimestamp != null && Object.hasOwnProperty.call(message, "errorTimestamp")) + writer.uint32(/* id 219548575, wireType 2 =*/1756388602).string(message.errorTimestamp); + if (message.currentState != null && Object.hasOwnProperty.call(message, "currentState")) + writer.uint32(/* id 438511179, wireType 2 =*/3508089434).string(message.currentState); + return writer; + }; + + /** + * Encodes the specified InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {google.cloud.compute.v1beta.IInstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState} message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState} InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.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.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 438511179: { + message.currentState = reader.string(); + break; + } + case 96784904: { + message.error = $root.google.cloud.compute.v1beta.Error.decode(reader, reader.uint32()); + break; + } + case 219548575: { + message.errorTimestamp = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState} InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message. + * @function verify + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.currentState != null && message.hasOwnProperty("currentState")) { + properties._currentState = 1; + if (!$util.isString(message.currentState)) + return "currentState: string expected"; + } + if (message.error != null && message.hasOwnProperty("error")) { + properties._error = 1; + { + var error = $root.google.cloud.compute.v1beta.Error.verify(message.error); + if (error) + return "error." + error; + } + } + if (message.errorTimestamp != null && message.hasOwnProperty("errorTimestamp")) { + properties._errorTimestamp = 1; + if (!$util.isString(message.errorTimestamp)) + return "errorTimestamp: string expected"; + } + return null; + }; + + /** + * Creates an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState} InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState) + return object; + var message = new $root.google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState(); + if (object.currentState != null) + message.currentState = String(object.currentState); + if (object.error != null) { + if (typeof object.error !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.error: object expected"); + message.error = $root.google.cloud.compute.v1beta.Error.fromObject(object.error); + } + if (object.errorTimestamp != null) + message.errorTimestamp = String(object.errorTimestamp); + return message; + }; + + /** + * Creates a plain object from an InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState} message InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.error != null && message.hasOwnProperty("error")) { + object.error = $root.google.cloud.compute.v1beta.Error.toObject(message.error, options); + if (options.oneofs) + object._error = "error"; + } + if (message.errorTimestamp != null && message.hasOwnProperty("errorTimestamp")) { + object.errorTimestamp = message.errorTimestamp; + if (options.oneofs) + object._errorTimestamp = "errorTimestamp"; + } + if (message.currentState != null && message.hasOwnProperty("currentState")) { + object.currentState = message.currentState; + if (options.oneofs) + object._currentState = "currentState"; + } + return object; + }; + + /** + * Converts this InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @instance + * @returns {Object.} JSON object + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState"; + }; + + /** + * CurrentState enum. + * @name google.cloud.compute.v1beta.InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.CurrentState + * @enum {number} + * @property {number} UNDEFINED_CURRENT_STATE=0 UNDEFINED_CURRENT_STATE value + * @property {number} ACTIVATING=378825968 ACTIVATING value + * @property {number} ACTIVE=314733318 ACTIVE value + * @property {number} ACTIVE_DEGRADED=471128135 ACTIVE_DEGRADED value + * @property {number} DEACTIVATING=57182257 DEACTIVATING value + * @property {number} FAILED=455706685 FAILED value + * @property {number} INACTIVE=270421099 INACTIVE value + * @property {number} INCOMPLETE=11941214 INCOMPLETE value + */ + InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState.CurrentState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_CURRENT_STATE"] = 0; + values[valuesById[378825968] = "ACTIVATING"] = 378825968; + values[valuesById[314733318] = "ACTIVE"] = 314733318; + values[valuesById[471128135] = "ACTIVE_DEGRADED"] = 471128135; + values[valuesById[57182257] = "DEACTIVATING"] = 57182257; + values[valuesById[455706685] = "FAILED"] = 455706685; + values[valuesById[270421099] = "INACTIVE"] = 270421099; + values[valuesById[11941214] = "INCOMPLETE"] = 11941214; + return values; + })(); + + return InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState; + })(); + v1beta.InstanceGroupManagersListErrorsResponse = (function() { /** @@ -930805,6 +938998,7 @@ * @property {google.cloud.compute.v1beta.IShieldedInstanceConfig|null} [shieldedInstanceConfig] InstanceProperties shieldedInstanceConfig * @property {google.cloud.compute.v1beta.IShieldedVmConfig|null} [shieldedVmConfig] InstanceProperties shieldedVmConfig * @property {google.cloud.compute.v1beta.ITags|null} [tags] InstanceProperties tags + * @property {google.cloud.compute.v1beta.IWorkloadIdentityConfig|null} [workloadIdentityConfig] InstanceProperties workloadIdentityConfig */ /** @@ -931030,6 +939224,14 @@ */ InstanceProperties.prototype.tags = null; + /** + * InstanceProperties workloadIdentityConfig. + * @member {google.cloud.compute.v1beta.IWorkloadIdentityConfig|null|undefined} workloadIdentityConfig + * @memberof google.cloud.compute.v1beta.InstanceProperties + * @instance + */ + InstanceProperties.prototype.workloadIdentityConfig = null; + // OneOf field names bound to virtual getters and setters var $oneOfFields; @@ -931135,6 +939337,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstanceProperties.prototype, "_workloadIdentityConfig", { + get: $util.oneOfGetter($oneOfFields = ["workloadIdentityConfig"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** * Creates a new InstanceProperties instance using the specified properties. * @function create @@ -931196,6 +939404,8 @@ $root.google.cloud.compute.v1beta.ServiceAccount.encode(message.serviceAccounts[i], writer.uint32(/* id 277537328, wireType 2 =*/2220298626).fork()).ldelim(); if (message.postKeyRevocationActionType != null && Object.hasOwnProperty.call(message, "postKeyRevocationActionType")) writer.uint32(/* id 292972897, wireType 2 =*/2343783178).string(message.postKeyRevocationActionType); + if (message.workloadIdentityConfig != null && Object.hasOwnProperty.call(message, "workloadIdentityConfig")) + $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.encode(message.workloadIdentityConfig, writer.uint32(/* id 338198811, wireType 2 =*/2705590490).fork()).ldelim(); if (message.resourceManagerTags != null && Object.hasOwnProperty.call(message, "resourceManagerTags")) for (var keys = Object.keys(message.resourceManagerTags), i = 0; i < keys.length; ++i) writer.uint32(/* id 377671164, wireType 2 =*/3021369314).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourceManagerTags[keys[i]]).ldelim(); @@ -931422,6 +939632,10 @@ message.tags = $root.google.cloud.compute.v1beta.Tags.decode(reader, reader.uint32()); break; } + case 338198811: { + message.workloadIdentityConfig = $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -931642,6 +939856,14 @@ return "tags." + error; } } + if (message.workloadIdentityConfig != null && message.hasOwnProperty("workloadIdentityConfig")) { + properties._workloadIdentityConfig = 1; + { + var error = $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.verify(message.workloadIdentityConfig); + if (error) + return "workloadIdentityConfig." + error; + } + } return null; }; @@ -931792,6 +940014,11 @@ throw TypeError(".google.cloud.compute.v1beta.InstanceProperties.tags: object expected"); message.tags = $root.google.cloud.compute.v1beta.Tags.fromObject(object.tags); } + if (object.workloadIdentityConfig != null) { + if (typeof object.workloadIdentityConfig !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstanceProperties.workloadIdentityConfig: object expected"); + message.workloadIdentityConfig = $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.fromObject(object.workloadIdentityConfig); + } return message; }; @@ -931896,6 +940123,11 @@ if (options.oneofs) object._postKeyRevocationActionType = "postKeyRevocationActionType"; } + if (message.workloadIdentityConfig != null && message.hasOwnProperty("workloadIdentityConfig")) { + object.workloadIdentityConfig = $root.google.cloud.compute.v1beta.WorkloadIdentityConfig.toObject(message.workloadIdentityConfig, options); + if (options.oneofs) + object._workloadIdentityConfig = "workloadIdentityConfig"; + } if (message.resourceManagerTags && (keys2 = Object.keys(message.resourceManagerTags)).length) { object.resourceManagerTags = {}; for (var j = 0; j < keys2.length; ++j) @@ -937385,6 +945617,7 @@ * @enum {number} * @property {number} UNDEFINED_BEHAVIOR=0 UNDEFINED_BEHAVIOR value * @property {number} BEHAVIOR_UNSPECIFIED=85734570 BEHAVIOR_UNSPECIFIED value + * @property {number} CHIP_ERROR=263151669 CHIP_ERROR value * @property {number} PERFORMANCE=135701520 PERFORMANCE value * @property {number} SILENT_DATA_CORRUPTION=111360678 SILENT_DATA_CORRUPTION value * @property {number} UNRECOVERABLE_GPU_ERROR=363710747 UNRECOVERABLE_GPU_ERROR value @@ -937393,6 +945626,7 @@ var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "UNDEFINED_BEHAVIOR"] = 0; values[valuesById[85734570] = "BEHAVIOR_UNSPECIFIED"] = 85734570; + values[valuesById[263151669] = "CHIP_ERROR"] = 263151669; values[valuesById[135701520] = "PERFORMANCE"] = 135701520; values[valuesById[111360678] = "SILENT_DATA_CORRUPTION"] = 111360678; values[valuesById[363710747] = "UNRECOVERABLE_GPU_ERROR"] = 363710747; @@ -939887,6 +948121,7 @@ * @property {string|null} [labelFingerprint] InstantSnapshot labelFingerprint * @property {Object.|null} [labels] InstantSnapshot labels * @property {string|null} [name] InstantSnapshot name + * @property {google.cloud.compute.v1beta.IInstantSnapshotParams|null} [params] InstantSnapshot params * @property {string|null} [region] InstantSnapshot region * @property {google.cloud.compute.v1beta.IInstantSnapshotResourceStatus|null} [resourceStatus] InstantSnapshot resourceStatus * @property {boolean|null} [satisfiesPzi] InstantSnapshot satisfiesPzi @@ -939895,6 +948130,8 @@ * @property {string|null} [selfLinkWithId] InstantSnapshot selfLinkWithId * @property {string|null} [sourceDisk] InstantSnapshot sourceDisk * @property {string|null} [sourceDiskId] InstantSnapshot sourceDiskId + * @property {string|null} [sourceInstantSnapshotGroup] InstantSnapshot sourceInstantSnapshotGroup + * @property {string|null} [sourceInstantSnapshotGroupId] InstantSnapshot sourceInstantSnapshotGroupId * @property {string|null} [status] InstantSnapshot status * @property {string|null} [zone] InstantSnapshot zone */ @@ -939987,6 +948224,14 @@ */ InstantSnapshot.prototype.name = null; + /** + * InstantSnapshot params. + * @member {google.cloud.compute.v1beta.IInstantSnapshotParams|null|undefined} params + * @memberof google.cloud.compute.v1beta.InstantSnapshot + * @instance + */ + InstantSnapshot.prototype.params = null; + /** * InstantSnapshot region. * @member {string|null|undefined} region @@ -940051,6 +948296,22 @@ */ InstantSnapshot.prototype.sourceDiskId = null; + /** + * InstantSnapshot sourceInstantSnapshotGroup. + * @member {string|null|undefined} sourceInstantSnapshotGroup + * @memberof google.cloud.compute.v1beta.InstantSnapshot + * @instance + */ + InstantSnapshot.prototype.sourceInstantSnapshotGroup = null; + + /** + * InstantSnapshot sourceInstantSnapshotGroupId. + * @member {string|null|undefined} sourceInstantSnapshotGroupId + * @memberof google.cloud.compute.v1beta.InstantSnapshot + * @instance + */ + InstantSnapshot.prototype.sourceInstantSnapshotGroupId = null; + /** * InstantSnapshot status. * @member {string|null|undefined} status @@ -940118,6 +948379,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshot.prototype, "_params", { + get: $util.oneOfGetter($oneOfFields = ["params"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(InstantSnapshot.prototype, "_region", { get: $util.oneOfGetter($oneOfFields = ["region"]), @@ -940166,6 +948433,18 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshot.prototype, "_sourceInstantSnapshotGroup", { + get: $util.oneOfGetter($oneOfFields = ["sourceInstantSnapshotGroup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshot.prototype, "_sourceInstantSnapshotGroupId", { + get: $util.oneOfGetter($oneOfFields = ["sourceInstantSnapshotGroupId"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(InstantSnapshot.prototype, "_status", { get: $util.oneOfGetter($oneOfFields = ["status"]), @@ -940214,8 +948493,12 @@ writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); if (message.selfLinkWithId != null && Object.hasOwnProperty.call(message, "selfLinkWithId")) writer.uint32(/* id 44520962, wireType 2 =*/356167698).string(message.selfLinkWithId); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.cloud.compute.v1beta.InstantSnapshotParams.encode(message.params, writer.uint32(/* id 78313862, wireType 2 =*/626510898).fork()).ldelim(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.sourceInstantSnapshotGroupId != null && Object.hasOwnProperty.call(message, "sourceInstantSnapshotGroupId")) + writer.uint32(/* id 167103732, wireType 2 =*/1336829858).string(message.sourceInstantSnapshotGroupId); if (message.labelFingerprint != null && Object.hasOwnProperty.call(message, "labelFingerprint")) writer.uint32(/* id 178124825, wireType 2 =*/1424998602).string(message.labelFingerprint); if (message.status != null && Object.hasOwnProperty.call(message, "status")) @@ -940241,6 +948524,8 @@ if (message.labels != null && Object.hasOwnProperty.call(message, "labels")) for (var keys = Object.keys(message.labels), i = 0; i < keys.length; ++i) writer.uint32(/* id 500195327, wireType 2 =*/4001562618).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.labels[keys[i]]).ldelim(); + if (message.sourceInstantSnapshotGroup != null && Object.hasOwnProperty.call(message, "sourceInstantSnapshotGroup")) + writer.uint32(/* id 525991686, wireType 2 =*/4207933490).string(message.sourceInstantSnapshotGroup); return writer; }; @@ -940332,6 +948617,10 @@ message.name = reader.string(); break; } + case 78313862: { + message.params = $root.google.cloud.compute.v1beta.InstantSnapshotParams.decode(reader, reader.uint32()); + break; + } case 138946292: { message.region = reader.string(); break; @@ -940364,6 +948653,14 @@ message.sourceDiskId = reader.string(); break; } + case 525991686: { + message.sourceInstantSnapshotGroup = reader.string(); + break; + } + case 167103732: { + message.sourceInstantSnapshotGroupId = reader.string(); + break; + } case 181260274: { message.status = reader.string(); break; @@ -940456,6 +948753,14 @@ if (!$util.isString(message.name)) return "name: string expected"; } + if (message.params != null && message.hasOwnProperty("params")) { + properties._params = 1; + { + var error = $root.google.cloud.compute.v1beta.InstantSnapshotParams.verify(message.params); + if (error) + return "params." + error; + } + } if (message.region != null && message.hasOwnProperty("region")) { properties._region = 1; if (!$util.isString(message.region)) @@ -940499,6 +948804,16 @@ if (!$util.isString(message.sourceDiskId)) return "sourceDiskId: string expected"; } + if (message.sourceInstantSnapshotGroup != null && message.hasOwnProperty("sourceInstantSnapshotGroup")) { + properties._sourceInstantSnapshotGroup = 1; + if (!$util.isString(message.sourceInstantSnapshotGroup)) + return "sourceInstantSnapshotGroup: string expected"; + } + if (message.sourceInstantSnapshotGroupId != null && message.hasOwnProperty("sourceInstantSnapshotGroupId")) { + properties._sourceInstantSnapshotGroupId = 1; + if (!$util.isString(message.sourceInstantSnapshotGroupId)) + return "sourceInstantSnapshotGroupId: string expected"; + } if (message.status != null && message.hasOwnProperty("status")) { properties._status = 1; if (!$util.isString(message.status)) @@ -940561,6 +948876,11 @@ } if (object.name != null) message.name = String(object.name); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstantSnapshot.params: object expected"); + message.params = $root.google.cloud.compute.v1beta.InstantSnapshotParams.fromObject(object.params); + } if (object.region != null) message.region = String(object.region); if (object.resourceStatus != null) { @@ -940580,6 +948900,10 @@ message.sourceDisk = String(object.sourceDisk); if (object.sourceDiskId != null) message.sourceDiskId = String(object.sourceDiskId); + if (object.sourceInstantSnapshotGroup != null) + message.sourceInstantSnapshotGroup = String(object.sourceInstantSnapshotGroup); + if (object.sourceInstantSnapshotGroupId != null) + message.sourceInstantSnapshotGroupId = String(object.sourceInstantSnapshotGroupId); if (object.status != null) message.status = String(object.status); if (object.zone != null) @@ -940635,11 +948959,21 @@ if (options.oneofs) object._selfLinkWithId = "selfLinkWithId"; } + if (message.params != null && message.hasOwnProperty("params")) { + object.params = $root.google.cloud.compute.v1beta.InstantSnapshotParams.toObject(message.params, options); + if (options.oneofs) + object._params = "params"; + } if (message.region != null && message.hasOwnProperty("region")) { object.region = message.region; if (options.oneofs) object._region = "region"; } + if (message.sourceInstantSnapshotGroupId != null && message.hasOwnProperty("sourceInstantSnapshotGroupId")) { + object.sourceInstantSnapshotGroupId = message.sourceInstantSnapshotGroupId; + if (options.oneofs) + object._sourceInstantSnapshotGroupId = "sourceInstantSnapshotGroupId"; + } if (message.labelFingerprint != null && message.hasOwnProperty("labelFingerprint")) { object.labelFingerprint = message.labelFingerprint; if (options.oneofs) @@ -940704,6 +949038,11 @@ for (var j = 0; j < keys2.length; ++j) object.labels[keys2[j]] = message.labels[keys2[j]]; } + if (message.sourceInstantSnapshotGroup != null && message.hasOwnProperty("sourceInstantSnapshotGroup")) { + object.sourceInstantSnapshotGroup = message.sourceInstantSnapshotGroup; + if (options.oneofs) + object._sourceInstantSnapshotGroup = "sourceInstantSnapshotGroup"; + } return object; }; @@ -941238,6 +949577,1353 @@ return InstantSnapshotAggregatedList; })(); + v1beta.InstantSnapshotGroup = (function() { + + /** + * Properties of an InstantSnapshotGroup. + * @memberof google.cloud.compute.v1beta + * @interface IInstantSnapshotGroup + * @property {string|null} [creationTimestamp] InstantSnapshotGroup creationTimestamp + * @property {string|null} [description] InstantSnapshotGroup description + * @property {number|Long|null} [id] InstantSnapshotGroup id + * @property {string|null} [kind] InstantSnapshotGroup kind + * @property {string|null} [name] InstantSnapshotGroup name + * @property {string|null} [region] InstantSnapshotGroup region + * @property {google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus|null} [resourceStatus] InstantSnapshotGroup resourceStatus + * @property {string|null} [selfLink] InstantSnapshotGroup selfLink + * @property {string|null} [selfLinkWithId] InstantSnapshotGroup selfLinkWithId + * @property {string|null} [sourceConsistencyGroup] InstantSnapshotGroup sourceConsistencyGroup + * @property {string|null} [status] InstantSnapshotGroup status + * @property {string|null} [zone] InstantSnapshotGroup zone + */ + + /** + * Constructs a new InstantSnapshotGroup. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstantSnapshotGroup. + * @implements IInstantSnapshotGroup + * @constructor + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroup=} [properties] Properties to set + */ + function InstantSnapshotGroup(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstantSnapshotGroup creationTimestamp. + * @member {string|null|undefined} creationTimestamp + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.creationTimestamp = null; + + /** + * InstantSnapshotGroup description. + * @member {string|null|undefined} description + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.description = null; + + /** + * InstantSnapshotGroup id. + * @member {number|Long|null|undefined} id + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.id = null; + + /** + * InstantSnapshotGroup kind. + * @member {string|null|undefined} kind + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.kind = null; + + /** + * InstantSnapshotGroup name. + * @member {string|null|undefined} name + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.name = null; + + /** + * InstantSnapshotGroup region. + * @member {string|null|undefined} region + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.region = null; + + /** + * InstantSnapshotGroup resourceStatus. + * @member {google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus|null|undefined} resourceStatus + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.resourceStatus = null; + + /** + * InstantSnapshotGroup selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.selfLink = null; + + /** + * InstantSnapshotGroup selfLinkWithId. + * @member {string|null|undefined} selfLinkWithId + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.selfLinkWithId = null; + + /** + * InstantSnapshotGroup sourceConsistencyGroup. + * @member {string|null|undefined} sourceConsistencyGroup + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.sourceConsistencyGroup = null; + + /** + * InstantSnapshotGroup status. + * @member {string|null|undefined} status + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.status = null; + + /** + * InstantSnapshotGroup zone. + * @member {string|null|undefined} zone + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + */ + InstantSnapshotGroup.prototype.zone = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_creationTimestamp", { + get: $util.oneOfGetter($oneOfFields = ["creationTimestamp"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_description", { + get: $util.oneOfGetter($oneOfFields = ["description"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_id", { + get: $util.oneOfGetter($oneOfFields = ["id"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_name", { + get: $util.oneOfGetter($oneOfFields = ["name"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_region", { + get: $util.oneOfGetter($oneOfFields = ["region"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_resourceStatus", { + get: $util.oneOfGetter($oneOfFields = ["resourceStatus"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_selfLinkWithId", { + get: $util.oneOfGetter($oneOfFields = ["selfLinkWithId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_sourceConsistencyGroup", { + get: $util.oneOfGetter($oneOfFields = ["sourceConsistencyGroup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_status", { + get: $util.oneOfGetter($oneOfFields = ["status"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroup.prototype, "_zone", { + get: $util.oneOfGetter($oneOfFields = ["zone"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InstantSnapshotGroup instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroup=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroup} InstantSnapshotGroup instance + */ + InstantSnapshotGroup.create = function create(properties) { + return new InstantSnapshotGroup(properties); + }; + + /** + * Encodes the specified InstantSnapshotGroup message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroup.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroup} message InstantSnapshotGroup message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotGroup.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 3355, wireType 0 =*/26840).uint64(message.id); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 3373707, wireType 2 =*/26989658).string(message.name); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.creationTimestamp != null && Object.hasOwnProperty.call(message, "creationTimestamp")) + writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); + if (message.selfLinkWithId != null && Object.hasOwnProperty.call(message, "selfLinkWithId")) + writer.uint32(/* id 44520962, wireType 2 =*/356167698).string(message.selfLinkWithId); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + writer.uint32(/* id 181260274, wireType 2 =*/1450082194).string(message.status); + if (message.resourceStatus != null && Object.hasOwnProperty.call(message, "resourceStatus")) + $root.google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.encode(message.resourceStatus, writer.uint32(/* id 249429315, wireType 2 =*/1995434522).fork()).ldelim(); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 422937596, wireType 2 =*/3383500770).string(message.description); + if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) + writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + if (message.sourceConsistencyGroup != null && Object.hasOwnProperty.call(message, "sourceConsistencyGroup")) + writer.uint32(/* id 531359348, wireType 2 =*/4250874786).string(message.sourceConsistencyGroup); + return writer; + }; + + /** + * Encodes the specified InstantSnapshotGroup message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroup.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroup} message InstantSnapshotGroup message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotGroup.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstantSnapshotGroup message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroup} InstantSnapshotGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotGroup.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.cloud.compute.v1beta.InstantSnapshotGroup(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 30525366: { + message.creationTimestamp = reader.string(); + break; + } + case 422937596: { + message.description = reader.string(); + break; + } + case 3355: { + message.id = reader.uint64(); + break; + } + case 3292052: { + message.kind = reader.string(); + break; + } + case 3373707: { + message.name = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 249429315: { + message.resourceStatus = $root.google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.decode(reader, reader.uint32()); + break; + } + case 456214797: { + message.selfLink = reader.string(); + break; + } + case 44520962: { + message.selfLinkWithId = reader.string(); + break; + } + case 531359348: { + message.sourceConsistencyGroup = reader.string(); + break; + } + case 181260274: { + message.status = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstantSnapshotGroup message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroup} InstantSnapshotGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotGroup.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstantSnapshotGroup message. + * @function verify + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstantSnapshotGroup.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.creationTimestamp != null && message.hasOwnProperty("creationTimestamp")) { + properties._creationTimestamp = 1; + if (!$util.isString(message.creationTimestamp)) + return "creationTimestamp: string expected"; + } + if (message.description != null && message.hasOwnProperty("description")) { + properties._description = 1; + if (!$util.isString(message.description)) + return "description: string expected"; + } + if (message.id != null && message.hasOwnProperty("id")) { + properties._id = 1; + if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) + return "id: integer|Long expected"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + properties._kind = 1; + if (!$util.isString(message.kind)) + return "kind: string expected"; + } + if (message.name != null && message.hasOwnProperty("name")) { + properties._name = 1; + if (!$util.isString(message.name)) + return "name: string expected"; + } + if (message.region != null && message.hasOwnProperty("region")) { + properties._region = 1; + if (!$util.isString(message.region)) + return "region: string expected"; + } + if (message.resourceStatus != null && message.hasOwnProperty("resourceStatus")) { + properties._resourceStatus = 1; + { + var error = $root.google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.verify(message.resourceStatus); + if (error) + return "resourceStatus." + error; + } + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + properties._selfLink = 1; + if (!$util.isString(message.selfLink)) + return "selfLink: string expected"; + } + if (message.selfLinkWithId != null && message.hasOwnProperty("selfLinkWithId")) { + properties._selfLinkWithId = 1; + if (!$util.isString(message.selfLinkWithId)) + return "selfLinkWithId: string expected"; + } + if (message.sourceConsistencyGroup != null && message.hasOwnProperty("sourceConsistencyGroup")) { + properties._sourceConsistencyGroup = 1; + if (!$util.isString(message.sourceConsistencyGroup)) + return "sourceConsistencyGroup: string expected"; + } + if (message.status != null && message.hasOwnProperty("status")) { + properties._status = 1; + if (!$util.isString(message.status)) + return "status: string expected"; + } + if (message.zone != null && message.hasOwnProperty("zone")) { + properties._zone = 1; + if (!$util.isString(message.zone)) + return "zone: string expected"; + } + return null; + }; + + /** + * Creates an InstantSnapshotGroup message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroup} InstantSnapshotGroup + */ + InstantSnapshotGroup.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InstantSnapshotGroup) + return object; + var message = new $root.google.cloud.compute.v1beta.InstantSnapshotGroup(); + if (object.creationTimestamp != null) + message.creationTimestamp = String(object.creationTimestamp); + if (object.description != null) + message.description = String(object.description); + if (object.id != null) + if ($util.Long) + (message.id = $util.Long.fromValue(object.id)).unsigned = true; + else if (typeof object.id === "string") + message.id = parseInt(object.id, 10); + else if (typeof object.id === "number") + message.id = object.id; + else if (typeof object.id === "object") + message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(true); + if (object.kind != null) + message.kind = String(object.kind); + if (object.name != null) + message.name = String(object.name); + if (object.region != null) + message.region = String(object.region); + if (object.resourceStatus != null) { + if (typeof object.resourceStatus !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstantSnapshotGroup.resourceStatus: object expected"); + message.resourceStatus = $root.google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.fromObject(object.resourceStatus); + } + if (object.selfLink != null) + message.selfLink = String(object.selfLink); + if (object.selfLinkWithId != null) + message.selfLinkWithId = String(object.selfLinkWithId); + if (object.sourceConsistencyGroup != null) + message.sourceConsistencyGroup = String(object.sourceConsistencyGroup); + if (object.status != null) + message.status = String(object.status); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from an InstantSnapshotGroup message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {google.cloud.compute.v1beta.InstantSnapshotGroup} message InstantSnapshotGroup + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstantSnapshotGroup.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.id != null && message.hasOwnProperty("id")) { + if (typeof message.id === "number") + object.id = options.longs === String ? String(message.id) : message.id; + else + object.id = options.longs === String ? $util.Long.prototype.toString.call(message.id) : options.longs === Number ? new $util.LongBits(message.id.low >>> 0, message.id.high >>> 0).toNumber(true) : message.id; + if (options.oneofs) + object._id = "id"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + object.kind = message.kind; + if (options.oneofs) + object._kind = "kind"; + } + if (message.name != null && message.hasOwnProperty("name")) { + object.name = message.name; + if (options.oneofs) + object._name = "name"; + } + if (message.zone != null && message.hasOwnProperty("zone")) { + object.zone = message.zone; + if (options.oneofs) + object._zone = "zone"; + } + if (message.creationTimestamp != null && message.hasOwnProperty("creationTimestamp")) { + object.creationTimestamp = message.creationTimestamp; + if (options.oneofs) + object._creationTimestamp = "creationTimestamp"; + } + if (message.selfLinkWithId != null && message.hasOwnProperty("selfLinkWithId")) { + object.selfLinkWithId = message.selfLinkWithId; + if (options.oneofs) + object._selfLinkWithId = "selfLinkWithId"; + } + if (message.region != null && message.hasOwnProperty("region")) { + object.region = message.region; + if (options.oneofs) + object._region = "region"; + } + if (message.status != null && message.hasOwnProperty("status")) { + object.status = message.status; + if (options.oneofs) + object._status = "status"; + } + if (message.resourceStatus != null && message.hasOwnProperty("resourceStatus")) { + object.resourceStatus = $root.google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.toObject(message.resourceStatus, options); + if (options.oneofs) + object._resourceStatus = "resourceStatus"; + } + if (message.description != null && message.hasOwnProperty("description")) { + object.description = message.description; + if (options.oneofs) + object._description = "description"; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + object.selfLink = message.selfLink; + if (options.oneofs) + object._selfLink = "selfLink"; + } + if (message.sourceConsistencyGroup != null && message.hasOwnProperty("sourceConsistencyGroup")) { + object.sourceConsistencyGroup = message.sourceConsistencyGroup; + if (options.oneofs) + object._sourceConsistencyGroup = "sourceConsistencyGroup"; + } + return object; + }; + + /** + * Converts this InstantSnapshotGroup to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @instance + * @returns {Object.} JSON object + */ + InstantSnapshotGroup.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstantSnapshotGroup + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroup + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstantSnapshotGroup.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InstantSnapshotGroup"; + }; + + /** + * Status enum. + * @name google.cloud.compute.v1beta.InstantSnapshotGroup.Status + * @enum {number} + * @property {number} UNDEFINED_STATUS=0 UNDEFINED_STATUS value + * @property {number} CREATING=455564985 CREATING value + * @property {number} DELETING=528602024 DELETING value + * @property {number} FAILED=455706685 FAILED value + * @property {number} INVALID=530283991 INVALID value + * @property {number} READY=77848963 READY value + * @property {number} UNKNOWN=433141802 UNKNOWN value + */ + InstantSnapshotGroup.Status = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_STATUS"] = 0; + values[valuesById[455564985] = "CREATING"] = 455564985; + values[valuesById[528602024] = "DELETING"] = 528602024; + values[valuesById[455706685] = "FAILED"] = 455706685; + values[valuesById[530283991] = "INVALID"] = 530283991; + values[valuesById[77848963] = "READY"] = 77848963; + values[valuesById[433141802] = "UNKNOWN"] = 433141802; + return values; + })(); + + return InstantSnapshotGroup; + })(); + + v1beta.InstantSnapshotGroupParameters = (function() { + + /** + * Properties of an InstantSnapshotGroupParameters. + * @memberof google.cloud.compute.v1beta + * @interface IInstantSnapshotGroupParameters + * @property {string|null} [sourceInstantSnapshotGroup] InstantSnapshotGroupParameters sourceInstantSnapshotGroup + */ + + /** + * Constructs a new InstantSnapshotGroupParameters. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstantSnapshotGroupParameters. + * @implements IInstantSnapshotGroupParameters + * @constructor + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupParameters=} [properties] Properties to set + */ + function InstantSnapshotGroupParameters(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstantSnapshotGroupParameters sourceInstantSnapshotGroup. + * @member {string|null|undefined} sourceInstantSnapshotGroup + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @instance + */ + InstantSnapshotGroupParameters.prototype.sourceInstantSnapshotGroup = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroupParameters.prototype, "_sourceInstantSnapshotGroup", { + get: $util.oneOfGetter($oneOfFields = ["sourceInstantSnapshotGroup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InstantSnapshotGroupParameters instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupParameters=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupParameters} InstantSnapshotGroupParameters instance + */ + InstantSnapshotGroupParameters.create = function create(properties) { + return new InstantSnapshotGroupParameters(properties); + }; + + /** + * Encodes the specified InstantSnapshotGroupParameters message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupParameters.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupParameters} message InstantSnapshotGroupParameters message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotGroupParameters.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.sourceInstantSnapshotGroup != null && Object.hasOwnProperty.call(message, "sourceInstantSnapshotGroup")) + writer.uint32(/* id 525991686, wireType 2 =*/4207933490).string(message.sourceInstantSnapshotGroup); + return writer; + }; + + /** + * Encodes the specified InstantSnapshotGroupParameters message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupParameters.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupParameters} message InstantSnapshotGroupParameters message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotGroupParameters.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstantSnapshotGroupParameters message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupParameters} InstantSnapshotGroupParameters + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotGroupParameters.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.cloud.compute.v1beta.InstantSnapshotGroupParameters(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 525991686: { + message.sourceInstantSnapshotGroup = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstantSnapshotGroupParameters message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupParameters} InstantSnapshotGroupParameters + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotGroupParameters.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstantSnapshotGroupParameters message. + * @function verify + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstantSnapshotGroupParameters.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.sourceInstantSnapshotGroup != null && message.hasOwnProperty("sourceInstantSnapshotGroup")) { + properties._sourceInstantSnapshotGroup = 1; + if (!$util.isString(message.sourceInstantSnapshotGroup)) + return "sourceInstantSnapshotGroup: string expected"; + } + return null; + }; + + /** + * Creates an InstantSnapshotGroupParameters message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupParameters} InstantSnapshotGroupParameters + */ + InstantSnapshotGroupParameters.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InstantSnapshotGroupParameters) + return object; + var message = new $root.google.cloud.compute.v1beta.InstantSnapshotGroupParameters(); + if (object.sourceInstantSnapshotGroup != null) + message.sourceInstantSnapshotGroup = String(object.sourceInstantSnapshotGroup); + return message; + }; + + /** + * Creates a plain object from an InstantSnapshotGroupParameters message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {google.cloud.compute.v1beta.InstantSnapshotGroupParameters} message InstantSnapshotGroupParameters + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstantSnapshotGroupParameters.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.sourceInstantSnapshotGroup != null && message.hasOwnProperty("sourceInstantSnapshotGroup")) { + object.sourceInstantSnapshotGroup = message.sourceInstantSnapshotGroup; + if (options.oneofs) + object._sourceInstantSnapshotGroup = "sourceInstantSnapshotGroup"; + } + return object; + }; + + /** + * Converts this InstantSnapshotGroupParameters to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @instance + * @returns {Object.} JSON object + */ + InstantSnapshotGroupParameters.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstantSnapshotGroupParameters + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupParameters + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstantSnapshotGroupParameters.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InstantSnapshotGroupParameters"; + }; + + return InstantSnapshotGroupParameters; + })(); + + v1beta.InstantSnapshotGroupResourceStatus = (function() { + + /** + * Properties of an InstantSnapshotGroupResourceStatus. + * @memberof google.cloud.compute.v1beta + * @interface IInstantSnapshotGroupResourceStatus + * @property {string|null} [consistencyMembershipResolutionTime] InstantSnapshotGroupResourceStatus consistencyMembershipResolutionTime + * @property {google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo|null} [sourceInfo] InstantSnapshotGroupResourceStatus sourceInfo + */ + + /** + * Constructs a new InstantSnapshotGroupResourceStatus. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstantSnapshotGroupResourceStatus. + * @implements IInstantSnapshotGroupResourceStatus + * @constructor + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus=} [properties] Properties to set + */ + function InstantSnapshotGroupResourceStatus(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstantSnapshotGroupResourceStatus consistencyMembershipResolutionTime. + * @member {string|null|undefined} consistencyMembershipResolutionTime + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @instance + */ + InstantSnapshotGroupResourceStatus.prototype.consistencyMembershipResolutionTime = null; + + /** + * InstantSnapshotGroupResourceStatus sourceInfo. + * @member {google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo|null|undefined} sourceInfo + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @instance + */ + InstantSnapshotGroupResourceStatus.prototype.sourceInfo = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroupResourceStatus.prototype, "_consistencyMembershipResolutionTime", { + get: $util.oneOfGetter($oneOfFields = ["consistencyMembershipResolutionTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroupResourceStatus.prototype, "_sourceInfo", { + get: $util.oneOfGetter($oneOfFields = ["sourceInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InstantSnapshotGroupResourceStatus instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus} InstantSnapshotGroupResourceStatus instance + */ + InstantSnapshotGroupResourceStatus.create = function create(properties) { + return new InstantSnapshotGroupResourceStatus(properties); + }; + + /** + * Encodes the specified InstantSnapshotGroupResourceStatus message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus} message InstantSnapshotGroupResourceStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotGroupResourceStatus.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.consistencyMembershipResolutionTime != null && Object.hasOwnProperty.call(message, "consistencyMembershipResolutionTime")) + writer.uint32(/* id 346675870, wireType 2 =*/2773406962).string(message.consistencyMembershipResolutionTime); + if (message.sourceInfo != null && Object.hasOwnProperty.call(message, "sourceInfo")) + $root.google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.encode(message.sourceInfo, writer.uint32(/* id 451907154, wireType 2 =*/3615257234).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified InstantSnapshotGroupResourceStatus message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupResourceStatus} message InstantSnapshotGroupResourceStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotGroupResourceStatus.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstantSnapshotGroupResourceStatus message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus} InstantSnapshotGroupResourceStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotGroupResourceStatus.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.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 346675870: { + message.consistencyMembershipResolutionTime = reader.string(); + break; + } + case 451907154: { + message.sourceInfo = $root.google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstantSnapshotGroupResourceStatus message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus} InstantSnapshotGroupResourceStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotGroupResourceStatus.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstantSnapshotGroupResourceStatus message. + * @function verify + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstantSnapshotGroupResourceStatus.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.consistencyMembershipResolutionTime != null && message.hasOwnProperty("consistencyMembershipResolutionTime")) { + properties._consistencyMembershipResolutionTime = 1; + if (!$util.isString(message.consistencyMembershipResolutionTime)) + return "consistencyMembershipResolutionTime: string expected"; + } + if (message.sourceInfo != null && message.hasOwnProperty("sourceInfo")) { + properties._sourceInfo = 1; + { + var error = $root.google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.verify(message.sourceInfo); + if (error) + return "sourceInfo." + error; + } + } + return null; + }; + + /** + * Creates an InstantSnapshotGroupResourceStatus message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus} InstantSnapshotGroupResourceStatus + */ + InstantSnapshotGroupResourceStatus.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus) + return object; + var message = new $root.google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus(); + if (object.consistencyMembershipResolutionTime != null) + message.consistencyMembershipResolutionTime = String(object.consistencyMembershipResolutionTime); + if (object.sourceInfo != null) { + if (typeof object.sourceInfo !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus.sourceInfo: object expected"); + message.sourceInfo = $root.google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.fromObject(object.sourceInfo); + } + return message; + }; + + /** + * Creates a plain object from an InstantSnapshotGroupResourceStatus message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus} message InstantSnapshotGroupResourceStatus + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstantSnapshotGroupResourceStatus.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.consistencyMembershipResolutionTime != null && message.hasOwnProperty("consistencyMembershipResolutionTime")) { + object.consistencyMembershipResolutionTime = message.consistencyMembershipResolutionTime; + if (options.oneofs) + object._consistencyMembershipResolutionTime = "consistencyMembershipResolutionTime"; + } + if (message.sourceInfo != null && message.hasOwnProperty("sourceInfo")) { + object.sourceInfo = $root.google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.toObject(message.sourceInfo, options); + if (options.oneofs) + object._sourceInfo = "sourceInfo"; + } + return object; + }; + + /** + * Converts this InstantSnapshotGroupResourceStatus to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @instance + * @returns {Object.} JSON object + */ + InstantSnapshotGroupResourceStatus.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstantSnapshotGroupResourceStatus + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstantSnapshotGroupResourceStatus.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InstantSnapshotGroupResourceStatus"; + }; + + return InstantSnapshotGroupResourceStatus; + })(); + + v1beta.InstantSnapshotGroupSourceInfo = (function() { + + /** + * Properties of an InstantSnapshotGroupSourceInfo. + * @memberof google.cloud.compute.v1beta + * @interface IInstantSnapshotGroupSourceInfo + * @property {string|null} [consistencyGroup] InstantSnapshotGroupSourceInfo consistencyGroup + * @property {string|null} [consistencyGroupId] InstantSnapshotGroupSourceInfo consistencyGroupId + */ + + /** + * Constructs a new InstantSnapshotGroupSourceInfo. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstantSnapshotGroupSourceInfo. + * @implements IInstantSnapshotGroupSourceInfo + * @constructor + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo=} [properties] Properties to set + */ + function InstantSnapshotGroupSourceInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstantSnapshotGroupSourceInfo consistencyGroup. + * @member {string|null|undefined} consistencyGroup + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @instance + */ + InstantSnapshotGroupSourceInfo.prototype.consistencyGroup = null; + + /** + * InstantSnapshotGroupSourceInfo consistencyGroupId. + * @member {string|null|undefined} consistencyGroupId + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @instance + */ + InstantSnapshotGroupSourceInfo.prototype.consistencyGroupId = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroupSourceInfo.prototype, "_consistencyGroup", { + get: $util.oneOfGetter($oneOfFields = ["consistencyGroup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(InstantSnapshotGroupSourceInfo.prototype, "_consistencyGroupId", { + get: $util.oneOfGetter($oneOfFields = ["consistencyGroupId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new InstantSnapshotGroupSourceInfo instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo} InstantSnapshotGroupSourceInfo instance + */ + InstantSnapshotGroupSourceInfo.create = function create(properties) { + return new InstantSnapshotGroupSourceInfo(properties); + }; + + /** + * Encodes the specified InstantSnapshotGroupSourceInfo message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo} message InstantSnapshotGroupSourceInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotGroupSourceInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.consistencyGroupId != null && Object.hasOwnProperty.call(message, "consistencyGroupId")) + writer.uint32(/* id 85599522, wireType 2 =*/684796178).string(message.consistencyGroupId); + if (message.consistencyGroup != null && Object.hasOwnProperty.call(message, "consistencyGroup")) + writer.uint32(/* id 508183960, wireType 2 =*/4065471682).string(message.consistencyGroup); + return writer; + }; + + /** + * Encodes the specified InstantSnapshotGroupSourceInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotGroupSourceInfo} message InstantSnapshotGroupSourceInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotGroupSourceInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstantSnapshotGroupSourceInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo} InstantSnapshotGroupSourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotGroupSourceInfo.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.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 508183960: { + message.consistencyGroup = reader.string(); + break; + } + case 85599522: { + message.consistencyGroupId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstantSnapshotGroupSourceInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo} InstantSnapshotGroupSourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotGroupSourceInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstantSnapshotGroupSourceInfo message. + * @function verify + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstantSnapshotGroupSourceInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.consistencyGroup != null && message.hasOwnProperty("consistencyGroup")) { + properties._consistencyGroup = 1; + if (!$util.isString(message.consistencyGroup)) + return "consistencyGroup: string expected"; + } + if (message.consistencyGroupId != null && message.hasOwnProperty("consistencyGroupId")) { + properties._consistencyGroupId = 1; + if (!$util.isString(message.consistencyGroupId)) + return "consistencyGroupId: string expected"; + } + return null; + }; + + /** + * Creates an InstantSnapshotGroupSourceInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo} InstantSnapshotGroupSourceInfo + */ + InstantSnapshotGroupSourceInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo) + return object; + var message = new $root.google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo(); + if (object.consistencyGroup != null) + message.consistencyGroup = String(object.consistencyGroup); + if (object.consistencyGroupId != null) + message.consistencyGroupId = String(object.consistencyGroupId); + return message; + }; + + /** + * Creates a plain object from an InstantSnapshotGroupSourceInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo} message InstantSnapshotGroupSourceInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstantSnapshotGroupSourceInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.consistencyGroupId != null && message.hasOwnProperty("consistencyGroupId")) { + object.consistencyGroupId = message.consistencyGroupId; + if (options.oneofs) + object._consistencyGroupId = "consistencyGroupId"; + } + if (message.consistencyGroup != null && message.hasOwnProperty("consistencyGroup")) { + object.consistencyGroup = message.consistencyGroup; + if (options.oneofs) + object._consistencyGroup = "consistencyGroup"; + } + return object; + }; + + /** + * Converts this InstantSnapshotGroupSourceInfo to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @instance + * @returns {Object.} JSON object + */ + InstantSnapshotGroupSourceInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstantSnapshotGroupSourceInfo + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstantSnapshotGroupSourceInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InstantSnapshotGroupSourceInfo"; + }; + + return InstantSnapshotGroupSourceInfo; + })(); + v1beta.InstantSnapshotList = (function() { /** @@ -941639,6 +951325,246 @@ return InstantSnapshotList; })(); + v1beta.InstantSnapshotParams = (function() { + + /** + * Properties of an InstantSnapshotParams. + * @memberof google.cloud.compute.v1beta + * @interface IInstantSnapshotParams + * @property {Object.|null} [resourceManagerTags] InstantSnapshotParams resourceManagerTags + */ + + /** + * Constructs a new InstantSnapshotParams. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstantSnapshotParams. + * @implements IInstantSnapshotParams + * @constructor + * @param {google.cloud.compute.v1beta.IInstantSnapshotParams=} [properties] Properties to set + */ + function InstantSnapshotParams(properties) { + this.resourceManagerTags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * InstantSnapshotParams resourceManagerTags. + * @member {Object.} resourceManagerTags + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @instance + */ + InstantSnapshotParams.prototype.resourceManagerTags = $util.emptyObject; + + /** + * Creates a new InstantSnapshotParams instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotParams=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.InstantSnapshotParams} InstantSnapshotParams instance + */ + InstantSnapshotParams.create = function create(properties) { + return new InstantSnapshotParams(properties); + }; + + /** + * Encodes the specified InstantSnapshotParams message. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotParams.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotParams} message InstantSnapshotParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotParams.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceManagerTags != null && Object.hasOwnProperty.call(message, "resourceManagerTags")) + for (var keys = Object.keys(message.resourceManagerTags), i = 0; i < keys.length; ++i) + writer.uint32(/* id 377671164, wireType 2 =*/3021369314).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourceManagerTags[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified InstantSnapshotParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.InstantSnapshotParams.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {google.cloud.compute.v1beta.IInstantSnapshotParams} message InstantSnapshotParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + InstantSnapshotParams.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an InstantSnapshotParams message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.InstantSnapshotParams} InstantSnapshotParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotParams.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.cloud.compute.v1beta.InstantSnapshotParams(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 377671164: { + if (message.resourceManagerTags === $util.emptyObject) + message.resourceManagerTags = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.resourceManagerTags[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an InstantSnapshotParams message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.InstantSnapshotParams} InstantSnapshotParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + InstantSnapshotParams.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an InstantSnapshotParams message. + * @function verify + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + InstantSnapshotParams.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceManagerTags != null && message.hasOwnProperty("resourceManagerTags")) { + if (!$util.isObject(message.resourceManagerTags)) + return "resourceManagerTags: object expected"; + var key = Object.keys(message.resourceManagerTags); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.resourceManagerTags[key[i]])) + return "resourceManagerTags: string{k:string} expected"; + } + return null; + }; + + /** + * Creates an InstantSnapshotParams message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.InstantSnapshotParams} InstantSnapshotParams + */ + InstantSnapshotParams.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.InstantSnapshotParams) + return object; + var message = new $root.google.cloud.compute.v1beta.InstantSnapshotParams(); + if (object.resourceManagerTags) { + if (typeof object.resourceManagerTags !== "object") + throw TypeError(".google.cloud.compute.v1beta.InstantSnapshotParams.resourceManagerTags: object expected"); + message.resourceManagerTags = {}; + for (var keys = Object.keys(object.resourceManagerTags), i = 0; i < keys.length; ++i) + message.resourceManagerTags[keys[i]] = String(object.resourceManagerTags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from an InstantSnapshotParams message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {google.cloud.compute.v1beta.InstantSnapshotParams} message InstantSnapshotParams + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + InstantSnapshotParams.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.resourceManagerTags = {}; + var keys2; + if (message.resourceManagerTags && (keys2 = Object.keys(message.resourceManagerTags)).length) { + object.resourceManagerTags = {}; + for (var j = 0; j < keys2.length; ++j) + object.resourceManagerTags[keys2[j]] = message.resourceManagerTags[keys2[j]]; + } + return object; + }; + + /** + * Converts this InstantSnapshotParams to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @instance + * @returns {Object.} JSON object + */ + InstantSnapshotParams.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for InstantSnapshotParams + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.InstantSnapshotParams + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + InstantSnapshotParams.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.InstantSnapshotParams"; + }; + + return InstantSnapshotParams; + })(); + v1beta.InstantSnapshotResourceStatus = (function() { /** @@ -988500,6 +998426,878 @@ return ListInstancesRequest; })(); + v1beta.ListInstantSnapshotGroups = (function() { + + /** + * Properties of a ListInstantSnapshotGroups. + * @memberof google.cloud.compute.v1beta + * @interface IListInstantSnapshotGroups + * @property {string|null} [etag] ListInstantSnapshotGroups etag + * @property {string|null} [id] ListInstantSnapshotGroups id + * @property {Array.|null} [items] ListInstantSnapshotGroups items + * @property {string|null} [kind] ListInstantSnapshotGroups kind + * @property {string|null} [nextPageToken] ListInstantSnapshotGroups nextPageToken + * @property {string|null} [selfLink] ListInstantSnapshotGroups selfLink + * @property {Array.|null} [unreachables] ListInstantSnapshotGroups unreachables + * @property {google.cloud.compute.v1beta.IWarning|null} [warning] ListInstantSnapshotGroups warning + */ + + /** + * Constructs a new ListInstantSnapshotGroups. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ListInstantSnapshotGroups. + * @implements IListInstantSnapshotGroups + * @constructor + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroups=} [properties] Properties to set + */ + function ListInstantSnapshotGroups(properties) { + this.items = []; + this.unreachables = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstantSnapshotGroups etag. + * @member {string|null|undefined} etag + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + */ + ListInstantSnapshotGroups.prototype.etag = null; + + /** + * ListInstantSnapshotGroups id. + * @member {string|null|undefined} id + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + */ + ListInstantSnapshotGroups.prototype.id = null; + + /** + * ListInstantSnapshotGroups items. + * @member {Array.} items + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + */ + ListInstantSnapshotGroups.prototype.items = $util.emptyArray; + + /** + * ListInstantSnapshotGroups kind. + * @member {string|null|undefined} kind + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + */ + ListInstantSnapshotGroups.prototype.kind = null; + + /** + * ListInstantSnapshotGroups nextPageToken. + * @member {string|null|undefined} nextPageToken + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + */ + ListInstantSnapshotGroups.prototype.nextPageToken = null; + + /** + * ListInstantSnapshotGroups selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + */ + ListInstantSnapshotGroups.prototype.selfLink = null; + + /** + * ListInstantSnapshotGroups unreachables. + * @member {Array.} unreachables + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + */ + ListInstantSnapshotGroups.prototype.unreachables = $util.emptyArray; + + /** + * ListInstantSnapshotGroups warning. + * @member {google.cloud.compute.v1beta.IWarning|null|undefined} warning + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + */ + ListInstantSnapshotGroups.prototype.warning = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroups.prototype, "_etag", { + get: $util.oneOfGetter($oneOfFields = ["etag"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroups.prototype, "_id", { + get: $util.oneOfGetter($oneOfFields = ["id"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroups.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroups.prototype, "_nextPageToken", { + get: $util.oneOfGetter($oneOfFields = ["nextPageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroups.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroups.prototype, "_warning", { + get: $util.oneOfGetter($oneOfFields = ["warning"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListInstantSnapshotGroups instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroups=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListInstantSnapshotGroups} ListInstantSnapshotGroups instance + */ + ListInstantSnapshotGroups.create = function create(properties) { + return new ListInstantSnapshotGroups(properties); + }; + + /** + * Encodes the specified ListInstantSnapshotGroups message. Does not implicitly {@link google.cloud.compute.v1beta.ListInstantSnapshotGroups.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroups} message ListInstantSnapshotGroups message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstantSnapshotGroups.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 3355, wireType 2 =*/26842).string(message.id); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 3123477, wireType 2 =*/24987818).string(message.etag); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); + if (message.warning != null && Object.hasOwnProperty.call(message, "warning")) + $root.google.cloud.compute.v1beta.Warning.encode(message.warning, writer.uint32(/* id 50704284, wireType 2 =*/405634274).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 79797525, wireType 2 =*/638380202).string(message.nextPageToken); + if (message.items != null && message.items.length) + for (var i = 0; i < message.items.length; ++i) + $root.google.cloud.compute.v1beta.InstantSnapshotGroup.encode(message.items[i], writer.uint32(/* id 100526016, wireType 2 =*/804208130).fork()).ldelim(); + if (message.unreachables != null && message.unreachables.length) + for (var i = 0; i < message.unreachables.length; ++i) + writer.uint32(/* id 243372063, wireType 2 =*/1946976506).string(message.unreachables[i]); + if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) + writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + return writer; + }; + + /** + * Encodes the specified ListInstantSnapshotGroups message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListInstantSnapshotGroups.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroups} message ListInstantSnapshotGroups message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstantSnapshotGroups.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstantSnapshotGroups message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ListInstantSnapshotGroups} ListInstantSnapshotGroups + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstantSnapshotGroups.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.cloud.compute.v1beta.ListInstantSnapshotGroups(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3123477: { + message.etag = reader.string(); + break; + } + case 3355: { + message.id = reader.string(); + break; + } + case 100526016: { + if (!(message.items && message.items.length)) + message.items = []; + message.items.push($root.google.cloud.compute.v1beta.InstantSnapshotGroup.decode(reader, reader.uint32())); + break; + } + case 3292052: { + message.kind = reader.string(); + break; + } + case 79797525: { + message.nextPageToken = reader.string(); + break; + } + case 456214797: { + message.selfLink = reader.string(); + break; + } + case 243372063: { + if (!(message.unreachables && message.unreachables.length)) + message.unreachables = []; + message.unreachables.push(reader.string()); + break; + } + case 50704284: { + message.warning = $root.google.cloud.compute.v1beta.Warning.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstantSnapshotGroups message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ListInstantSnapshotGroups} ListInstantSnapshotGroups + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstantSnapshotGroups.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstantSnapshotGroups message. + * @function verify + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstantSnapshotGroups.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.etag != null && message.hasOwnProperty("etag")) { + properties._etag = 1; + if (!$util.isString(message.etag)) + return "etag: string expected"; + } + if (message.id != null && message.hasOwnProperty("id")) { + properties._id = 1; + if (!$util.isString(message.id)) + return "id: string expected"; + } + if (message.items != null && message.hasOwnProperty("items")) { + if (!Array.isArray(message.items)) + return "items: array expected"; + for (var i = 0; i < message.items.length; ++i) { + var error = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.verify(message.items[i]); + if (error) + return "items." + error; + } + } + if (message.kind != null && message.hasOwnProperty("kind")) { + properties._kind = 1; + if (!$util.isString(message.kind)) + return "kind: string expected"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + properties._nextPageToken = 1; + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + properties._selfLink = 1; + if (!$util.isString(message.selfLink)) + return "selfLink: string expected"; + } + if (message.unreachables != null && message.hasOwnProperty("unreachables")) { + if (!Array.isArray(message.unreachables)) + return "unreachables: array expected"; + for (var i = 0; i < message.unreachables.length; ++i) + if (!$util.isString(message.unreachables[i])) + return "unreachables: string[] expected"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + properties._warning = 1; + { + var error = $root.google.cloud.compute.v1beta.Warning.verify(message.warning); + if (error) + return "warning." + error; + } + } + return null; + }; + + /** + * Creates a ListInstantSnapshotGroups message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ListInstantSnapshotGroups} ListInstantSnapshotGroups + */ + ListInstantSnapshotGroups.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListInstantSnapshotGroups) + return object; + var message = new $root.google.cloud.compute.v1beta.ListInstantSnapshotGroups(); + if (object.etag != null) + message.etag = String(object.etag); + if (object.id != null) + message.id = String(object.id); + if (object.items) { + if (!Array.isArray(object.items)) + throw TypeError(".google.cloud.compute.v1beta.ListInstantSnapshotGroups.items: array expected"); + message.items = []; + for (var i = 0; i < object.items.length; ++i) { + if (typeof object.items[i] !== "object") + throw TypeError(".google.cloud.compute.v1beta.ListInstantSnapshotGroups.items: object expected"); + message.items[i] = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.fromObject(object.items[i]); + } + } + if (object.kind != null) + message.kind = String(object.kind); + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.selfLink != null) + message.selfLink = String(object.selfLink); + if (object.unreachables) { + if (!Array.isArray(object.unreachables)) + throw TypeError(".google.cloud.compute.v1beta.ListInstantSnapshotGroups.unreachables: array expected"); + message.unreachables = []; + for (var i = 0; i < object.unreachables.length; ++i) + message.unreachables[i] = String(object.unreachables[i]); + } + if (object.warning != null) { + if (typeof object.warning !== "object") + throw TypeError(".google.cloud.compute.v1beta.ListInstantSnapshotGroups.warning: object expected"); + message.warning = $root.google.cloud.compute.v1beta.Warning.fromObject(object.warning); + } + return message; + }; + + /** + * Creates a plain object from a ListInstantSnapshotGroups message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {google.cloud.compute.v1beta.ListInstantSnapshotGroups} message ListInstantSnapshotGroups + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstantSnapshotGroups.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.items = []; + object.unreachables = []; + } + if (message.id != null && message.hasOwnProperty("id")) { + object.id = message.id; + if (options.oneofs) + object._id = "id"; + } + if (message.etag != null && message.hasOwnProperty("etag")) { + object.etag = message.etag; + if (options.oneofs) + object._etag = "etag"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + object.kind = message.kind; + if (options.oneofs) + object._kind = "kind"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + object.warning = $root.google.cloud.compute.v1beta.Warning.toObject(message.warning, options); + if (options.oneofs) + object._warning = "warning"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + object.nextPageToken = message.nextPageToken; + if (options.oneofs) + object._nextPageToken = "nextPageToken"; + } + if (message.items && message.items.length) { + object.items = []; + for (var j = 0; j < message.items.length; ++j) + object.items[j] = $root.google.cloud.compute.v1beta.InstantSnapshotGroup.toObject(message.items[j], options); + } + if (message.unreachables && message.unreachables.length) { + object.unreachables = []; + for (var j = 0; j < message.unreachables.length; ++j) + object.unreachables[j] = message.unreachables[j]; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + object.selfLink = message.selfLink; + if (options.oneofs) + object._selfLink = "selfLink"; + } + return object; + }; + + /** + * Converts this ListInstantSnapshotGroups to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @instance + * @returns {Object.} JSON object + */ + ListInstantSnapshotGroups.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstantSnapshotGroups + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroups + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstantSnapshotGroups.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListInstantSnapshotGroups"; + }; + + return ListInstantSnapshotGroups; + })(); + + v1beta.ListInstantSnapshotGroupsRequest = (function() { + + /** + * Properties of a ListInstantSnapshotGroupsRequest. + * @memberof google.cloud.compute.v1beta + * @interface IListInstantSnapshotGroupsRequest + * @property {string|null} [filter] ListInstantSnapshotGroupsRequest filter + * @property {number|null} [maxResults] ListInstantSnapshotGroupsRequest maxResults + * @property {string|null} [orderBy] ListInstantSnapshotGroupsRequest orderBy + * @property {string|null} [pageToken] ListInstantSnapshotGroupsRequest pageToken + * @property {string|null} [project] ListInstantSnapshotGroupsRequest project + * @property {boolean|null} [returnPartialSuccess] ListInstantSnapshotGroupsRequest returnPartialSuccess + * @property {string|null} [zone] ListInstantSnapshotGroupsRequest zone + */ + + /** + * Constructs a new ListInstantSnapshotGroupsRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ListInstantSnapshotGroupsRequest. + * @implements IListInstantSnapshotGroupsRequest + * @constructor + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest=} [properties] Properties to set + */ + function ListInstantSnapshotGroupsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListInstantSnapshotGroupsRequest filter. + * @member {string|null|undefined} filter + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @instance + */ + ListInstantSnapshotGroupsRequest.prototype.filter = null; + + /** + * ListInstantSnapshotGroupsRequest maxResults. + * @member {number|null|undefined} maxResults + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @instance + */ + ListInstantSnapshotGroupsRequest.prototype.maxResults = null; + + /** + * ListInstantSnapshotGroupsRequest orderBy. + * @member {string|null|undefined} orderBy + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @instance + */ + ListInstantSnapshotGroupsRequest.prototype.orderBy = null; + + /** + * ListInstantSnapshotGroupsRequest pageToken. + * @member {string|null|undefined} pageToken + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @instance + */ + ListInstantSnapshotGroupsRequest.prototype.pageToken = null; + + /** + * ListInstantSnapshotGroupsRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @instance + */ + ListInstantSnapshotGroupsRequest.prototype.project = ""; + + /** + * ListInstantSnapshotGroupsRequest returnPartialSuccess. + * @member {boolean|null|undefined} returnPartialSuccess + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @instance + */ + ListInstantSnapshotGroupsRequest.prototype.returnPartialSuccess = null; + + /** + * ListInstantSnapshotGroupsRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @instance + */ + ListInstantSnapshotGroupsRequest.prototype.zone = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroupsRequest.prototype, "_filter", { + get: $util.oneOfGetter($oneOfFields = ["filter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroupsRequest.prototype, "_maxResults", { + get: $util.oneOfGetter($oneOfFields = ["maxResults"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroupsRequest.prototype, "_orderBy", { + get: $util.oneOfGetter($oneOfFields = ["orderBy"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroupsRequest.prototype, "_pageToken", { + get: $util.oneOfGetter($oneOfFields = ["pageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListInstantSnapshotGroupsRequest.prototype, "_returnPartialSuccess", { + get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListInstantSnapshotGroupsRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest} ListInstantSnapshotGroupsRequest instance + */ + ListInstantSnapshotGroupsRequest.create = function create(properties) { + return new ListInstantSnapshotGroupsRequest(properties); + }; + + /** + * Encodes the specified ListInstantSnapshotGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest} message ListInstantSnapshotGroupsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstantSnapshotGroupsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); + if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) + writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); + if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) + writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); + if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) + writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); + return writer; + }; + + /** + * Encodes the specified ListInstantSnapshotGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest} message ListInstantSnapshotGroupsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListInstantSnapshotGroupsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListInstantSnapshotGroupsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest} ListInstantSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstantSnapshotGroupsRequest.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.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 336120696: { + message.filter = reader.string(); + break; + } + case 54715419: { + message.maxResults = reader.uint32(); + break; + } + case 160562920: { + message.orderBy = reader.string(); + break; + } + case 19994697: { + message.pageToken = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 517198390: { + message.returnPartialSuccess = reader.bool(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListInstantSnapshotGroupsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest} ListInstantSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListInstantSnapshotGroupsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListInstantSnapshotGroupsRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListInstantSnapshotGroupsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.filter != null && message.hasOwnProperty("filter")) { + properties._filter = 1; + if (!$util.isString(message.filter)) + return "filter: string expected"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + properties._maxResults = 1; + if (!$util.isInteger(message.maxResults)) + return "maxResults: integer expected"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + properties._orderBy = 1; + if (!$util.isString(message.orderBy)) + return "orderBy: string expected"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + properties._pageToken = 1; + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + properties._returnPartialSuccess = 1; + if (typeof message.returnPartialSuccess !== "boolean") + return "returnPartialSuccess: boolean expected"; + } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates a ListInstantSnapshotGroupsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest} ListInstantSnapshotGroupsRequest + */ + ListInstantSnapshotGroupsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest(); + if (object.filter != null) + message.filter = String(object.filter); + if (object.maxResults != null) + message.maxResults = object.maxResults >>> 0; + if (object.orderBy != null) + message.orderBy = String(object.orderBy); + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.project != null) + message.project = String(object.project); + if (object.returnPartialSuccess != null) + message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a ListInstantSnapshotGroupsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest} message ListInstantSnapshotGroupsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListInstantSnapshotGroupsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.project = ""; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + object.pageToken = message.pageToken; + if (options.oneofs) + object._pageToken = "pageToken"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + object.maxResults = message.maxResults; + if (options.oneofs) + object._maxResults = "maxResults"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + object.orderBy = message.orderBy; + if (options.oneofs) + object._orderBy = "orderBy"; + } + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = message.filter; + if (options.oneofs) + object._filter = "filter"; + } + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + object.returnPartialSuccess = message.returnPartialSuccess; + if (options.oneofs) + object._returnPartialSuccess = "returnPartialSuccess"; + } + return object; + }; + + /** + * Converts this ListInstantSnapshotGroupsRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @instance + * @returns {Object.} JSON object + */ + ListInstantSnapshotGroupsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListInstantSnapshotGroupsRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListInstantSnapshotGroupsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest"; + }; + + return ListInstantSnapshotGroupsRequest; + })(); + v1beta.ListInstantSnapshotsRequest = (function() { /** @@ -993154,30 +1003952,31 @@ return ListManagedInstancesRegionInstanceGroupManagersRequest; })(); - v1beta.ListNetworkAttachmentsRequest = (function() { + v1beta.ListNamedSetsRoutersRequest = (function() { /** - * Properties of a ListNetworkAttachmentsRequest. + * Properties of a ListNamedSetsRoutersRequest. * @memberof google.cloud.compute.v1beta - * @interface IListNetworkAttachmentsRequest - * @property {string|null} [filter] ListNetworkAttachmentsRequest filter - * @property {number|null} [maxResults] ListNetworkAttachmentsRequest maxResults - * @property {string|null} [orderBy] ListNetworkAttachmentsRequest orderBy - * @property {string|null} [pageToken] ListNetworkAttachmentsRequest pageToken - * @property {string|null} [project] ListNetworkAttachmentsRequest project - * @property {string|null} [region] ListNetworkAttachmentsRequest region - * @property {boolean|null} [returnPartialSuccess] ListNetworkAttachmentsRequest returnPartialSuccess + * @interface IListNamedSetsRoutersRequest + * @property {string|null} [filter] ListNamedSetsRoutersRequest filter + * @property {number|null} [maxResults] ListNamedSetsRoutersRequest maxResults + * @property {string|null} [orderBy] ListNamedSetsRoutersRequest orderBy + * @property {string|null} [pageToken] ListNamedSetsRoutersRequest pageToken + * @property {string|null} [project] ListNamedSetsRoutersRequest project + * @property {string|null} [region] ListNamedSetsRoutersRequest region + * @property {boolean|null} [returnPartialSuccess] ListNamedSetsRoutersRequest returnPartialSuccess + * @property {string|null} [router] ListNamedSetsRoutersRequest router */ /** - * Constructs a new ListNetworkAttachmentsRequest. + * Constructs a new ListNamedSetsRoutersRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListNetworkAttachmentsRequest. - * @implements IListNetworkAttachmentsRequest + * @classdesc Represents a ListNamedSetsRoutersRequest. + * @implements IListNamedSetsRoutersRequest * @constructor - * @param {google.cloud.compute.v1beta.IListNetworkAttachmentsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListNamedSetsRoutersRequest=} [properties] Properties to set */ - function ListNetworkAttachmentsRequest(properties) { + function ListNamedSetsRoutersRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -993185,116 +1003984,124 @@ } /** - * ListNetworkAttachmentsRequest filter. + * ListNamedSetsRoutersRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @instance */ - ListNetworkAttachmentsRequest.prototype.filter = null; + ListNamedSetsRoutersRequest.prototype.filter = null; /** - * ListNetworkAttachmentsRequest maxResults. + * ListNamedSetsRoutersRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @instance */ - ListNetworkAttachmentsRequest.prototype.maxResults = null; + ListNamedSetsRoutersRequest.prototype.maxResults = null; /** - * ListNetworkAttachmentsRequest orderBy. + * ListNamedSetsRoutersRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @instance */ - ListNetworkAttachmentsRequest.prototype.orderBy = null; + ListNamedSetsRoutersRequest.prototype.orderBy = null; /** - * ListNetworkAttachmentsRequest pageToken. + * ListNamedSetsRoutersRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @instance */ - ListNetworkAttachmentsRequest.prototype.pageToken = null; + ListNamedSetsRoutersRequest.prototype.pageToken = null; /** - * ListNetworkAttachmentsRequest project. + * ListNamedSetsRoutersRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @instance */ - ListNetworkAttachmentsRequest.prototype.project = ""; + ListNamedSetsRoutersRequest.prototype.project = ""; /** - * ListNetworkAttachmentsRequest region. + * ListNamedSetsRoutersRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @instance */ - ListNetworkAttachmentsRequest.prototype.region = ""; + ListNamedSetsRoutersRequest.prototype.region = ""; /** - * ListNetworkAttachmentsRequest returnPartialSuccess. + * ListNamedSetsRoutersRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @instance */ - ListNetworkAttachmentsRequest.prototype.returnPartialSuccess = null; + ListNamedSetsRoutersRequest.prototype.returnPartialSuccess = null; + + /** + * ListNamedSetsRoutersRequest router. + * @member {string} router + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest + * @instance + */ + ListNamedSetsRoutersRequest.prototype.router = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_filter", { + Object.defineProperty(ListNamedSetsRoutersRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_maxResults", { + Object.defineProperty(ListNamedSetsRoutersRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_orderBy", { + Object.defineProperty(ListNamedSetsRoutersRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_pageToken", { + Object.defineProperty(ListNamedSetsRoutersRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListNamedSetsRoutersRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListNetworkAttachmentsRequest instance using the specified properties. + * Creates a new ListNamedSetsRoutersRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static - * @param {google.cloud.compute.v1beta.IListNetworkAttachmentsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} ListNetworkAttachmentsRequest instance + * @param {google.cloud.compute.v1beta.IListNamedSetsRoutersRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListNamedSetsRoutersRequest} ListNamedSetsRoutersRequest instance */ - ListNetworkAttachmentsRequest.create = function create(properties) { - return new ListNetworkAttachmentsRequest(properties); + ListNamedSetsRoutersRequest.create = function create(properties) { + return new ListNamedSetsRoutersRequest(properties); }; /** - * Encodes the specified ListNetworkAttachmentsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListNetworkAttachmentsRequest.verify|verify} messages. + * Encodes the specified ListNamedSetsRoutersRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListNamedSetsRoutersRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static - * @param {google.cloud.compute.v1beta.IListNetworkAttachmentsRequest} message ListNetworkAttachmentsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListNamedSetsRoutersRequest} message ListNamedSetsRoutersRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListNetworkAttachmentsRequest.encode = function encode(message, writer) { + ListNamedSetsRoutersRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -993303,6 +1004110,8 @@ writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); if (message.region != null && Object.hasOwnProperty.call(message, "region")) writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.router != null && Object.hasOwnProperty.call(message, "router")) + writer.uint32(/* id 148608841, wireType 2 =*/1188870730).string(message.router); if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); if (message.project != null && Object.hasOwnProperty.call(message, "project")) @@ -993315,33 +1004124,33 @@ }; /** - * Encodes the specified ListNetworkAttachmentsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListNetworkAttachmentsRequest.verify|verify} messages. + * Encodes the specified ListNamedSetsRoutersRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListNamedSetsRoutersRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static - * @param {google.cloud.compute.v1beta.IListNetworkAttachmentsRequest} message ListNetworkAttachmentsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListNamedSetsRoutersRequest} message ListNamedSetsRoutersRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListNetworkAttachmentsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListNamedSetsRoutersRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListNetworkAttachmentsRequest message from the specified reader or buffer. + * Decodes a ListNamedSetsRoutersRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} ListNetworkAttachmentsRequest + * @returns {google.cloud.compute.v1beta.ListNamedSetsRoutersRequest} ListNamedSetsRoutersRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListNetworkAttachmentsRequest.decode = function decode(reader, length, error) { + ListNamedSetsRoutersRequest.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.cloud.compute.v1beta.ListNetworkAttachmentsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -993375,6 +1004184,10 @@ message.returnPartialSuccess = reader.bool(); break; } + case 148608841: { + message.router = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -993384,30 +1004197,30 @@ }; /** - * Decodes a ListNetworkAttachmentsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListNamedSetsRoutersRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} ListNetworkAttachmentsRequest + * @returns {google.cloud.compute.v1beta.ListNamedSetsRoutersRequest} ListNamedSetsRoutersRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListNetworkAttachmentsRequest.decodeDelimited = function decodeDelimited(reader) { + ListNamedSetsRoutersRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListNetworkAttachmentsRequest message. + * Verifies a ListNamedSetsRoutersRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListNetworkAttachmentsRequest.verify = function verify(message) { + ListNamedSetsRoutersRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -993442,21 +1004255,24 @@ if (typeof message.returnPartialSuccess !== "boolean") return "returnPartialSuccess: boolean expected"; } + if (message.router != null && message.hasOwnProperty("router")) + if (!$util.isString(message.router)) + return "router: string expected"; return null; }; /** - * Creates a ListNetworkAttachmentsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListNamedSetsRoutersRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} ListNetworkAttachmentsRequest + * @returns {google.cloud.compute.v1beta.ListNamedSetsRoutersRequest} ListNamedSetsRoutersRequest */ - ListNetworkAttachmentsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListNetworkAttachmentsRequest) + ListNamedSetsRoutersRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListNetworkAttachmentsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -993471,24 +1004287,27 @@ message.region = String(object.region); if (object.returnPartialSuccess != null) message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + if (object.router != null) + message.router = String(object.router); return message; }; /** - * Creates a plain object from a ListNetworkAttachmentsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListNamedSetsRoutersRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static - * @param {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} message ListNetworkAttachmentsRequest + * @param {google.cloud.compute.v1beta.ListNamedSetsRoutersRequest} message ListNamedSetsRoutersRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListNetworkAttachmentsRequest.toObject = function toObject(message, options) { + ListNamedSetsRoutersRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { object.region = ""; + object.router = ""; object.project = ""; } if (message.pageToken != null && message.hasOwnProperty("pageToken")) { @@ -993503,6 +1004322,8 @@ } if (message.region != null && message.hasOwnProperty("region")) object.region = message.region; + if (message.router != null && message.hasOwnProperty("router")) + object.router = message.router; if (message.orderBy != null && message.hasOwnProperty("orderBy")) { object.orderBy = message.orderBy; if (options.oneofs) @@ -993524,58 +1004345,58 @@ }; /** - * Converts this ListNetworkAttachmentsRequest to JSON. + * Converts this ListNamedSetsRoutersRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @instance * @returns {Object.} JSON object */ - ListNetworkAttachmentsRequest.prototype.toJSON = function toJSON() { + ListNamedSetsRoutersRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListNetworkAttachmentsRequest + * Gets the default type url for ListNamedSetsRoutersRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @memberof google.cloud.compute.v1beta.ListNamedSetsRoutersRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListNetworkAttachmentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListNamedSetsRoutersRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListNetworkAttachmentsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListNamedSetsRoutersRequest"; }; - return ListNetworkAttachmentsRequest; + return ListNamedSetsRoutersRequest; })(); - v1beta.ListNetworkEndpointGroupsRequest = (function() { + v1beta.ListNetworkAttachmentsRequest = (function() { /** - * Properties of a ListNetworkEndpointGroupsRequest. + * Properties of a ListNetworkAttachmentsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListNetworkEndpointGroupsRequest - * @property {string|null} [filter] ListNetworkEndpointGroupsRequest filter - * @property {number|null} [maxResults] ListNetworkEndpointGroupsRequest maxResults - * @property {string|null} [orderBy] ListNetworkEndpointGroupsRequest orderBy - * @property {string|null} [pageToken] ListNetworkEndpointGroupsRequest pageToken - * @property {string|null} [project] ListNetworkEndpointGroupsRequest project - * @property {boolean|null} [returnPartialSuccess] ListNetworkEndpointGroupsRequest returnPartialSuccess - * @property {string|null} [zone] ListNetworkEndpointGroupsRequest zone + * @interface IListNetworkAttachmentsRequest + * @property {string|null} [filter] ListNetworkAttachmentsRequest filter + * @property {number|null} [maxResults] ListNetworkAttachmentsRequest maxResults + * @property {string|null} [orderBy] ListNetworkAttachmentsRequest orderBy + * @property {string|null} [pageToken] ListNetworkAttachmentsRequest pageToken + * @property {string|null} [project] ListNetworkAttachmentsRequest project + * @property {string|null} [region] ListNetworkAttachmentsRequest region + * @property {boolean|null} [returnPartialSuccess] ListNetworkAttachmentsRequest returnPartialSuccess */ /** - * Constructs a new ListNetworkEndpointGroupsRequest. + * Constructs a new ListNetworkAttachmentsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListNetworkEndpointGroupsRequest. - * @implements IListNetworkEndpointGroupsRequest + * @classdesc Represents a ListNetworkAttachmentsRequest. + * @implements IListNetworkAttachmentsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListNetworkEndpointGroupsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListNetworkAttachmentsRequest=} [properties] Properties to set */ - function ListNetworkEndpointGroupsRequest(properties) { + function ListNetworkAttachmentsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -993583,124 +1004404,124 @@ } /** - * ListNetworkEndpointGroupsRequest filter. + * ListNetworkAttachmentsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @instance */ - ListNetworkEndpointGroupsRequest.prototype.filter = null; + ListNetworkAttachmentsRequest.prototype.filter = null; /** - * ListNetworkEndpointGroupsRequest maxResults. + * ListNetworkAttachmentsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @instance */ - ListNetworkEndpointGroupsRequest.prototype.maxResults = null; + ListNetworkAttachmentsRequest.prototype.maxResults = null; /** - * ListNetworkEndpointGroupsRequest orderBy. + * ListNetworkAttachmentsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @instance */ - ListNetworkEndpointGroupsRequest.prototype.orderBy = null; + ListNetworkAttachmentsRequest.prototype.orderBy = null; /** - * ListNetworkEndpointGroupsRequest pageToken. + * ListNetworkAttachmentsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @instance */ - ListNetworkEndpointGroupsRequest.prototype.pageToken = null; + ListNetworkAttachmentsRequest.prototype.pageToken = null; /** - * ListNetworkEndpointGroupsRequest project. + * ListNetworkAttachmentsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @instance */ - ListNetworkEndpointGroupsRequest.prototype.project = ""; + ListNetworkAttachmentsRequest.prototype.project = ""; /** - * ListNetworkEndpointGroupsRequest returnPartialSuccess. - * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * ListNetworkAttachmentsRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @instance */ - ListNetworkEndpointGroupsRequest.prototype.returnPartialSuccess = null; + ListNetworkAttachmentsRequest.prototype.region = ""; /** - * ListNetworkEndpointGroupsRequest zone. - * @member {string} zone - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * ListNetworkAttachmentsRequest returnPartialSuccess. + * @member {boolean|null|undefined} returnPartialSuccess + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @instance */ - ListNetworkEndpointGroupsRequest.prototype.zone = ""; + ListNetworkAttachmentsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_filter", { + Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_maxResults", { + Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_orderBy", { + Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_pageToken", { + Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListNetworkAttachmentsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListNetworkEndpointGroupsRequest instance using the specified properties. + * Creates a new ListNetworkAttachmentsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @static - * @param {google.cloud.compute.v1beta.IListNetworkEndpointGroupsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} ListNetworkEndpointGroupsRequest instance + * @param {google.cloud.compute.v1beta.IListNetworkAttachmentsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} ListNetworkAttachmentsRequest instance */ - ListNetworkEndpointGroupsRequest.create = function create(properties) { - return new ListNetworkEndpointGroupsRequest(properties); + ListNetworkAttachmentsRequest.create = function create(properties) { + return new ListNetworkAttachmentsRequest(properties); }; /** - * Encodes the specified ListNetworkEndpointGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest.verify|verify} messages. + * Encodes the specified ListNetworkAttachmentsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListNetworkAttachmentsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @static - * @param {google.cloud.compute.v1beta.IListNetworkEndpointGroupsRequest} message ListNetworkEndpointGroupsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListNetworkAttachmentsRequest} message ListNetworkAttachmentsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListNetworkEndpointGroupsRequest.encode = function encode(message, writer) { + ListNetworkAttachmentsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) - writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); if (message.project != null && Object.hasOwnProperty.call(message, "project")) @@ -993713,33 +1004534,33 @@ }; /** - * Encodes the specified ListNetworkEndpointGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest.verify|verify} messages. + * Encodes the specified ListNetworkAttachmentsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListNetworkAttachmentsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @static - * @param {google.cloud.compute.v1beta.IListNetworkEndpointGroupsRequest} message ListNetworkEndpointGroupsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListNetworkAttachmentsRequest} message ListNetworkAttachmentsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListNetworkEndpointGroupsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListNetworkAttachmentsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListNetworkEndpointGroupsRequest message from the specified reader or buffer. + * Decodes a ListNetworkAttachmentsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} ListNetworkEndpointGroupsRequest + * @returns {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} ListNetworkAttachmentsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListNetworkEndpointGroupsRequest.decode = function decode(reader, length, error) { + ListNetworkAttachmentsRequest.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.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListNetworkAttachmentsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -993765,12 +1004586,12 @@ message.project = reader.string(); break; } - case 517198390: { - message.returnPartialSuccess = reader.bool(); + case 138946292: { + message.region = reader.string(); break; } - case 3744684: { - message.zone = reader.string(); + case 517198390: { + message.returnPartialSuccess = reader.bool(); break; } default: @@ -993782,30 +1004603,30 @@ }; /** - * Decodes a ListNetworkEndpointGroupsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListNetworkAttachmentsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} ListNetworkEndpointGroupsRequest + * @returns {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} ListNetworkAttachmentsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListNetworkEndpointGroupsRequest.decodeDelimited = function decodeDelimited(reader) { + ListNetworkAttachmentsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListNetworkEndpointGroupsRequest message. + * Verifies a ListNetworkAttachmentsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListNetworkEndpointGroupsRequest.verify = function verify(message) { + ListNetworkAttachmentsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -993832,29 +1004653,29 @@ if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { properties._returnPartialSuccess = 1; if (typeof message.returnPartialSuccess !== "boolean") return "returnPartialSuccess: boolean expected"; } - if (message.zone != null && message.hasOwnProperty("zone")) - if (!$util.isString(message.zone)) - return "zone: string expected"; return null; }; /** - * Creates a ListNetworkEndpointGroupsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListNetworkAttachmentsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} ListNetworkEndpointGroupsRequest + * @returns {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} ListNetworkAttachmentsRequest */ - ListNetworkEndpointGroupsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest) + ListNetworkAttachmentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListNetworkAttachmentsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListNetworkAttachmentsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -993865,32 +1004686,430 @@ message.pageToken = String(object.pageToken); if (object.project != null) message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); if (object.returnPartialSuccess != null) message.returnPartialSuccess = Boolean(object.returnPartialSuccess); - if (object.zone != null) - message.zone = String(object.zone); return message; }; /** - * Creates a plain object from a ListNetworkEndpointGroupsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListNetworkAttachmentsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest * @static - * @param {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} message ListNetworkEndpointGroupsRequest + * @param {google.cloud.compute.v1beta.ListNetworkAttachmentsRequest} message ListNetworkAttachmentsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListNetworkEndpointGroupsRequest.toObject = function toObject(message, options) { + ListNetworkAttachmentsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.zone = ""; + object.region = ""; object.project = ""; } - if (message.zone != null && message.hasOwnProperty("zone")) - object.zone = message.zone; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + object.pageToken = message.pageToken; + if (options.oneofs) + object._pageToken = "pageToken"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + object.maxResults = message.maxResults; + if (options.oneofs) + object._maxResults = "maxResults"; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + object.orderBy = message.orderBy; + if (options.oneofs) + object._orderBy = "orderBy"; + } + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = message.filter; + if (options.oneofs) + object._filter = "filter"; + } + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + object.returnPartialSuccess = message.returnPartialSuccess; + if (options.oneofs) + object._returnPartialSuccess = "returnPartialSuccess"; + } + return object; + }; + + /** + * Converts this ListNetworkAttachmentsRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @instance + * @returns {Object.} JSON object + */ + ListNetworkAttachmentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListNetworkAttachmentsRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ListNetworkAttachmentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListNetworkAttachmentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListNetworkAttachmentsRequest"; + }; + + return ListNetworkAttachmentsRequest; + })(); + + v1beta.ListNetworkEndpointGroupsRequest = (function() { + + /** + * Properties of a ListNetworkEndpointGroupsRequest. + * @memberof google.cloud.compute.v1beta + * @interface IListNetworkEndpointGroupsRequest + * @property {string|null} [filter] ListNetworkEndpointGroupsRequest filter + * @property {number|null} [maxResults] ListNetworkEndpointGroupsRequest maxResults + * @property {string|null} [orderBy] ListNetworkEndpointGroupsRequest orderBy + * @property {string|null} [pageToken] ListNetworkEndpointGroupsRequest pageToken + * @property {string|null} [project] ListNetworkEndpointGroupsRequest project + * @property {boolean|null} [returnPartialSuccess] ListNetworkEndpointGroupsRequest returnPartialSuccess + * @property {string|null} [zone] ListNetworkEndpointGroupsRequest zone + */ + + /** + * Constructs a new ListNetworkEndpointGroupsRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ListNetworkEndpointGroupsRequest. + * @implements IListNetworkEndpointGroupsRequest + * @constructor + * @param {google.cloud.compute.v1beta.IListNetworkEndpointGroupsRequest=} [properties] Properties to set + */ + function ListNetworkEndpointGroupsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListNetworkEndpointGroupsRequest filter. + * @member {string|null|undefined} filter + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @instance + */ + ListNetworkEndpointGroupsRequest.prototype.filter = null; + + /** + * ListNetworkEndpointGroupsRequest maxResults. + * @member {number|null|undefined} maxResults + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @instance + */ + ListNetworkEndpointGroupsRequest.prototype.maxResults = null; + + /** + * ListNetworkEndpointGroupsRequest orderBy. + * @member {string|null|undefined} orderBy + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @instance + */ + ListNetworkEndpointGroupsRequest.prototype.orderBy = null; + + /** + * ListNetworkEndpointGroupsRequest pageToken. + * @member {string|null|undefined} pageToken + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @instance + */ + ListNetworkEndpointGroupsRequest.prototype.pageToken = null; + + /** + * ListNetworkEndpointGroupsRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @instance + */ + ListNetworkEndpointGroupsRequest.prototype.project = ""; + + /** + * ListNetworkEndpointGroupsRequest returnPartialSuccess. + * @member {boolean|null|undefined} returnPartialSuccess + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @instance + */ + ListNetworkEndpointGroupsRequest.prototype.returnPartialSuccess = null; + + /** + * ListNetworkEndpointGroupsRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @instance + */ + ListNetworkEndpointGroupsRequest.prototype.zone = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_filter", { + get: $util.oneOfGetter($oneOfFields = ["filter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_maxResults", { + get: $util.oneOfGetter($oneOfFields = ["maxResults"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_orderBy", { + get: $util.oneOfGetter($oneOfFields = ["orderBy"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_pageToken", { + get: $util.oneOfGetter($oneOfFields = ["pageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListNetworkEndpointGroupsRequest.prototype, "_returnPartialSuccess", { + get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListNetworkEndpointGroupsRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListNetworkEndpointGroupsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} ListNetworkEndpointGroupsRequest instance + */ + ListNetworkEndpointGroupsRequest.create = function create(properties) { + return new ListNetworkEndpointGroupsRequest(properties); + }; + + /** + * Encodes the specified ListNetworkEndpointGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListNetworkEndpointGroupsRequest} message ListNetworkEndpointGroupsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListNetworkEndpointGroupsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); + if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) + writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); + if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) + writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); + if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) + writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); + return writer; + }; + + /** + * Encodes the specified ListNetworkEndpointGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListNetworkEndpointGroupsRequest} message ListNetworkEndpointGroupsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListNetworkEndpointGroupsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListNetworkEndpointGroupsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} ListNetworkEndpointGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListNetworkEndpointGroupsRequest.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.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 336120696: { + message.filter = reader.string(); + break; + } + case 54715419: { + message.maxResults = reader.uint32(); + break; + } + case 160562920: { + message.orderBy = reader.string(); + break; + } + case 19994697: { + message.pageToken = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 517198390: { + message.returnPartialSuccess = reader.bool(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListNetworkEndpointGroupsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} ListNetworkEndpointGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListNetworkEndpointGroupsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListNetworkEndpointGroupsRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListNetworkEndpointGroupsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.filter != null && message.hasOwnProperty("filter")) { + properties._filter = 1; + if (!$util.isString(message.filter)) + return "filter: string expected"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + properties._maxResults = 1; + if (!$util.isInteger(message.maxResults)) + return "maxResults: integer expected"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + properties._orderBy = 1; + if (!$util.isString(message.orderBy)) + return "orderBy: string expected"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + properties._pageToken = 1; + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + properties._returnPartialSuccess = 1; + if (typeof message.returnPartialSuccess !== "boolean") + return "returnPartialSuccess: boolean expected"; + } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates a ListNetworkEndpointGroupsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} ListNetworkEndpointGroupsRequest + */ + ListNetworkEndpointGroupsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest(); + if (object.filter != null) + message.filter = String(object.filter); + if (object.maxResults != null) + message.maxResults = object.maxResults >>> 0; + if (object.orderBy != null) + message.orderBy = String(object.orderBy); + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.project != null) + message.project = String(object.project); + if (object.returnPartialSuccess != null) + message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a ListNetworkEndpointGroupsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.ListNetworkEndpointGroupsRequest} message ListNetworkEndpointGroupsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListNetworkEndpointGroupsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.project = ""; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; if (message.pageToken != null && message.hasOwnProperty("pageToken")) { object.pageToken = message.pageToken; if (options.oneofs) @@ -1008459,30 +1019678,30 @@ return ListRegionInstanceTemplatesRequest; })(); - v1beta.ListRegionInstantSnapshotsRequest = (function() { + v1beta.ListRegionInstantSnapshotGroupsRequest = (function() { /** - * Properties of a ListRegionInstantSnapshotsRequest. + * Properties of a ListRegionInstantSnapshotGroupsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionInstantSnapshotsRequest - * @property {string|null} [filter] ListRegionInstantSnapshotsRequest filter - * @property {number|null} [maxResults] ListRegionInstantSnapshotsRequest maxResults - * @property {string|null} [orderBy] ListRegionInstantSnapshotsRequest orderBy - * @property {string|null} [pageToken] ListRegionInstantSnapshotsRequest pageToken - * @property {string|null} [project] ListRegionInstantSnapshotsRequest project - * @property {string|null} [region] ListRegionInstantSnapshotsRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionInstantSnapshotsRequest returnPartialSuccess + * @interface IListRegionInstantSnapshotGroupsRequest + * @property {string|null} [filter] ListRegionInstantSnapshotGroupsRequest filter + * @property {number|null} [maxResults] ListRegionInstantSnapshotGroupsRequest maxResults + * @property {string|null} [orderBy] ListRegionInstantSnapshotGroupsRequest orderBy + * @property {string|null} [pageToken] ListRegionInstantSnapshotGroupsRequest pageToken + * @property {string|null} [project] ListRegionInstantSnapshotGroupsRequest project + * @property {string|null} [region] ListRegionInstantSnapshotGroupsRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionInstantSnapshotGroupsRequest returnPartialSuccess */ /** - * Constructs a new ListRegionInstantSnapshotsRequest. + * Constructs a new ListRegionInstantSnapshotGroupsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionInstantSnapshotsRequest. - * @implements IListRegionInstantSnapshotsRequest + * @classdesc Represents a ListRegionInstantSnapshotGroupsRequest. + * @implements IListRegionInstantSnapshotGroupsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest=} [properties] Properties to set */ - function ListRegionInstantSnapshotsRequest(properties) { + function ListRegionInstantSnapshotGroupsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1008490,116 +1019709,116 @@ } /** - * ListRegionInstantSnapshotsRequest filter. + * ListRegionInstantSnapshotGroupsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @instance */ - ListRegionInstantSnapshotsRequest.prototype.filter = null; + ListRegionInstantSnapshotGroupsRequest.prototype.filter = null; /** - * ListRegionInstantSnapshotsRequest maxResults. + * ListRegionInstantSnapshotGroupsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @instance */ - ListRegionInstantSnapshotsRequest.prototype.maxResults = null; + ListRegionInstantSnapshotGroupsRequest.prototype.maxResults = null; /** - * ListRegionInstantSnapshotsRequest orderBy. + * ListRegionInstantSnapshotGroupsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @instance */ - ListRegionInstantSnapshotsRequest.prototype.orderBy = null; + ListRegionInstantSnapshotGroupsRequest.prototype.orderBy = null; /** - * ListRegionInstantSnapshotsRequest pageToken. + * ListRegionInstantSnapshotGroupsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @instance */ - ListRegionInstantSnapshotsRequest.prototype.pageToken = null; + ListRegionInstantSnapshotGroupsRequest.prototype.pageToken = null; /** - * ListRegionInstantSnapshotsRequest project. + * ListRegionInstantSnapshotGroupsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @instance */ - ListRegionInstantSnapshotsRequest.prototype.project = ""; + ListRegionInstantSnapshotGroupsRequest.prototype.project = ""; /** - * ListRegionInstantSnapshotsRequest region. + * ListRegionInstantSnapshotGroupsRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @instance */ - ListRegionInstantSnapshotsRequest.prototype.region = ""; + ListRegionInstantSnapshotGroupsRequest.prototype.region = ""; /** - * ListRegionInstantSnapshotsRequest returnPartialSuccess. + * ListRegionInstantSnapshotGroupsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @instance */ - ListRegionInstantSnapshotsRequest.prototype.returnPartialSuccess = null; + ListRegionInstantSnapshotGroupsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_filter", { + Object.defineProperty(ListRegionInstantSnapshotGroupsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionInstantSnapshotGroupsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionInstantSnapshotGroupsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionInstantSnapshotGroupsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionInstantSnapshotGroupsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionInstantSnapshotsRequest instance using the specified properties. + * Creates a new ListRegionInstantSnapshotGroupsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} ListRegionInstantSnapshotsRequest instance + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest} ListRegionInstantSnapshotGroupsRequest instance */ - ListRegionInstantSnapshotsRequest.create = function create(properties) { - return new ListRegionInstantSnapshotsRequest(properties); + ListRegionInstantSnapshotGroupsRequest.create = function create(properties) { + return new ListRegionInstantSnapshotGroupsRequest(properties); }; /** - * Encodes the specified ListRegionInstantSnapshotsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest.verify|verify} messages. + * Encodes the specified ListRegionInstantSnapshotGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotsRequest} message ListRegionInstantSnapshotsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest} message ListRegionInstantSnapshotGroupsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionInstantSnapshotsRequest.encode = function encode(message, writer) { + ListRegionInstantSnapshotGroupsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1008620,33 +1019839,33 @@ }; /** - * Encodes the specified ListRegionInstantSnapshotsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest.verify|verify} messages. + * Encodes the specified ListRegionInstantSnapshotGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotsRequest} message ListRegionInstantSnapshotsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest} message ListRegionInstantSnapshotGroupsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionInstantSnapshotsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionInstantSnapshotGroupsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionInstantSnapshotsRequest message from the specified reader or buffer. + * Decodes a ListRegionInstantSnapshotGroupsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} ListRegionInstantSnapshotsRequest + * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest} ListRegionInstantSnapshotGroupsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionInstantSnapshotsRequest.decode = function decode(reader, length, error) { + ListRegionInstantSnapshotGroupsRequest.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.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1008689,30 +1019908,30 @@ }; /** - * Decodes a ListRegionInstantSnapshotsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionInstantSnapshotGroupsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} ListRegionInstantSnapshotsRequest + * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest} ListRegionInstantSnapshotGroupsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionInstantSnapshotsRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionInstantSnapshotGroupsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionInstantSnapshotsRequest message. + * Verifies a ListRegionInstantSnapshotGroupsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionInstantSnapshotsRequest.verify = function verify(message) { + ListRegionInstantSnapshotGroupsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1008751,17 +1019970,17 @@ }; /** - * Creates a ListRegionInstantSnapshotsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionInstantSnapshotGroupsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} ListRegionInstantSnapshotsRequest + * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest} ListRegionInstantSnapshotGroupsRequest */ - ListRegionInstantSnapshotsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest) + ListRegionInstantSnapshotGroupsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1008780,15 +1019999,15 @@ }; /** - * Creates a plain object from a ListRegionInstantSnapshotsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionInstantSnapshotGroupsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} message ListRegionInstantSnapshotsRequest + * @param {google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest} message ListRegionInstantSnapshotGroupsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionInstantSnapshotsRequest.toObject = function toObject(message, options) { + ListRegionInstantSnapshotGroupsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1008829,59 +1020048,58 @@ }; /** - * Converts this ListRegionInstantSnapshotsRequest to JSON. + * Converts this ListRegionInstantSnapshotGroupsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @instance * @returns {Object.} JSON object */ - ListRegionInstantSnapshotsRequest.prototype.toJSON = function toJSON() { + ListRegionInstantSnapshotGroupsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionInstantSnapshotsRequest + * Gets the default type url for ListRegionInstantSnapshotGroupsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionInstantSnapshotsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionInstantSnapshotGroupsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest"; }; - return ListRegionInstantSnapshotsRequest; + return ListRegionInstantSnapshotGroupsRequest; })(); - v1beta.ListRegionMultiMigMembersRequest = (function() { + v1beta.ListRegionInstantSnapshotsRequest = (function() { /** - * Properties of a ListRegionMultiMigMembersRequest. + * Properties of a ListRegionInstantSnapshotsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionMultiMigMembersRequest - * @property {string|null} [filter] ListRegionMultiMigMembersRequest filter - * @property {number|null} [maxResults] ListRegionMultiMigMembersRequest maxResults - * @property {string|null} [multiMig] ListRegionMultiMigMembersRequest multiMig - * @property {string|null} [orderBy] ListRegionMultiMigMembersRequest orderBy - * @property {string|null} [pageToken] ListRegionMultiMigMembersRequest pageToken - * @property {string|null} [project] ListRegionMultiMigMembersRequest project - * @property {string|null} [region] ListRegionMultiMigMembersRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionMultiMigMembersRequest returnPartialSuccess + * @interface IListRegionInstantSnapshotsRequest + * @property {string|null} [filter] ListRegionInstantSnapshotsRequest filter + * @property {number|null} [maxResults] ListRegionInstantSnapshotsRequest maxResults + * @property {string|null} [orderBy] ListRegionInstantSnapshotsRequest orderBy + * @property {string|null} [pageToken] ListRegionInstantSnapshotsRequest pageToken + * @property {string|null} [project] ListRegionInstantSnapshotsRequest project + * @property {string|null} [region] ListRegionInstantSnapshotsRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionInstantSnapshotsRequest returnPartialSuccess */ /** - * Constructs a new ListRegionMultiMigMembersRequest. + * Constructs a new ListRegionInstantSnapshotsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionMultiMigMembersRequest. - * @implements IListRegionMultiMigMembersRequest + * @classdesc Represents a ListRegionInstantSnapshotsRequest. + * @implements IListRegionInstantSnapshotsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionMultiMigMembersRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotsRequest=} [properties] Properties to set */ - function ListRegionMultiMigMembersRequest(properties) { + function ListRegionInstantSnapshotsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1008889,124 +1020107,116 @@ } /** - * ListRegionMultiMigMembersRequest filter. + * ListRegionInstantSnapshotsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @instance */ - ListRegionMultiMigMembersRequest.prototype.filter = null; + ListRegionInstantSnapshotsRequest.prototype.filter = null; /** - * ListRegionMultiMigMembersRequest maxResults. + * ListRegionInstantSnapshotsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest - * @instance - */ - ListRegionMultiMigMembersRequest.prototype.maxResults = null; - - /** - * ListRegionMultiMigMembersRequest multiMig. - * @member {string} multiMig - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @instance */ - ListRegionMultiMigMembersRequest.prototype.multiMig = ""; + ListRegionInstantSnapshotsRequest.prototype.maxResults = null; /** - * ListRegionMultiMigMembersRequest orderBy. + * ListRegionInstantSnapshotsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @instance */ - ListRegionMultiMigMembersRequest.prototype.orderBy = null; + ListRegionInstantSnapshotsRequest.prototype.orderBy = null; /** - * ListRegionMultiMigMembersRequest pageToken. + * ListRegionInstantSnapshotsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @instance */ - ListRegionMultiMigMembersRequest.prototype.pageToken = null; + ListRegionInstantSnapshotsRequest.prototype.pageToken = null; /** - * ListRegionMultiMigMembersRequest project. + * ListRegionInstantSnapshotsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @instance */ - ListRegionMultiMigMembersRequest.prototype.project = ""; + ListRegionInstantSnapshotsRequest.prototype.project = ""; /** - * ListRegionMultiMigMembersRequest region. + * ListRegionInstantSnapshotsRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @instance */ - ListRegionMultiMigMembersRequest.prototype.region = ""; + ListRegionInstantSnapshotsRequest.prototype.region = ""; /** - * ListRegionMultiMigMembersRequest returnPartialSuccess. + * ListRegionInstantSnapshotsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @instance */ - ListRegionMultiMigMembersRequest.prototype.returnPartialSuccess = null; + ListRegionInstantSnapshotsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_filter", { + Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionInstantSnapshotsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionMultiMigMembersRequest instance using the specified properties. + * Creates a new ListRegionInstantSnapshotsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionMultiMigMembersRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} ListRegionMultiMigMembersRequest instance + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} ListRegionInstantSnapshotsRequest instance */ - ListRegionMultiMigMembersRequest.create = function create(properties) { - return new ListRegionMultiMigMembersRequest(properties); + ListRegionInstantSnapshotsRequest.create = function create(properties) { + return new ListRegionInstantSnapshotsRequest(properties); }; /** - * Encodes the specified ListRegionMultiMigMembersRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest.verify|verify} messages. + * Encodes the specified ListRegionInstantSnapshotsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionMultiMigMembersRequest} message ListRegionMultiMigMembersRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotsRequest} message ListRegionInstantSnapshotsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionMultiMigMembersRequest.encode = function encode(message, writer) { + ListRegionInstantSnapshotsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1009021,41 +1020231,39 @@ writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); - if (message.multiMig != null && Object.hasOwnProperty.call(message, "multiMig")) - writer.uint32(/* id 403990085, wireType 2 =*/3231920682).string(message.multiMig); if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); return writer; }; /** - * Encodes the specified ListRegionMultiMigMembersRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest.verify|verify} messages. + * Encodes the specified ListRegionInstantSnapshotsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionMultiMigMembersRequest} message ListRegionMultiMigMembersRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotsRequest} message ListRegionInstantSnapshotsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionMultiMigMembersRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionInstantSnapshotsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionMultiMigMembersRequest message from the specified reader or buffer. + * Decodes a ListRegionInstantSnapshotsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} ListRegionMultiMigMembersRequest + * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} ListRegionInstantSnapshotsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionMultiMigMembersRequest.decode = function decode(reader, length, error) { + ListRegionInstantSnapshotsRequest.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.cloud.compute.v1beta.ListRegionMultiMigMembersRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1009069,10 +1020277,6 @@ message.maxResults = reader.uint32(); break; } - case 403990085: { - message.multiMig = reader.string(); - break; - } case 160562920: { message.orderBy = reader.string(); break; @@ -1009102,30 +1020306,30 @@ }; /** - * Decodes a ListRegionMultiMigMembersRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionInstantSnapshotsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} ListRegionMultiMigMembersRequest + * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} ListRegionInstantSnapshotsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionMultiMigMembersRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionInstantSnapshotsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionMultiMigMembersRequest message. + * Verifies a ListRegionInstantSnapshotsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionMultiMigMembersRequest.verify = function verify(message) { + ListRegionInstantSnapshotsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1009139,9 +1020343,6 @@ if (!$util.isInteger(message.maxResults)) return "maxResults: integer expected"; } - if (message.multiMig != null && message.hasOwnProperty("multiMig")) - if (!$util.isString(message.multiMig)) - return "multiMig: string expected"; if (message.orderBy != null && message.hasOwnProperty("orderBy")) { properties._orderBy = 1; if (!$util.isString(message.orderBy)) @@ -1009167,23 +1020368,21 @@ }; /** - * Creates a ListRegionMultiMigMembersRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionInstantSnapshotsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} ListRegionMultiMigMembersRequest + * @returns {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} ListRegionInstantSnapshotsRequest */ - ListRegionMultiMigMembersRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest) + ListRegionInstantSnapshotsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) message.maxResults = object.maxResults >>> 0; - if (object.multiMig != null) - message.multiMig = String(object.multiMig); if (object.orderBy != null) message.orderBy = String(object.orderBy); if (object.pageToken != null) @@ -1009198,22 +1020397,21 @@ }; /** - * Creates a plain object from a ListRegionMultiMigMembersRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionInstantSnapshotsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} message ListRegionMultiMigMembersRequest + * @param {google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest} message ListRegionInstantSnapshotsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionMultiMigMembersRequest.toObject = function toObject(message, options) { + ListRegionInstantSnapshotsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { object.region = ""; object.project = ""; - object.multiMig = ""; } if (message.pageToken != null && message.hasOwnProperty("pageToken")) { object.pageToken = message.pageToken; @@ -1009239,8 +1020437,6 @@ if (options.oneofs) object._filter = "filter"; } - if (message.multiMig != null && message.hasOwnProperty("multiMig")) - object.multiMig = message.multiMig; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { object.returnPartialSuccess = message.returnPartialSuccess; if (options.oneofs) @@ -1009250,58 +1020446,59 @@ }; /** - * Converts this ListRegionMultiMigMembersRequest to JSON. + * Converts this ListRegionInstantSnapshotsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @instance * @returns {Object.} JSON object */ - ListRegionMultiMigMembersRequest.prototype.toJSON = function toJSON() { + ListRegionInstantSnapshotsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionMultiMigMembersRequest + * Gets the default type url for ListRegionInstantSnapshotsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @memberof google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionMultiMigMembersRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionInstantSnapshotsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionInstantSnapshotsRequest"; }; - return ListRegionMultiMigMembersRequest; + return ListRegionInstantSnapshotsRequest; })(); - v1beta.ListRegionMultiMigsRequest = (function() { + v1beta.ListRegionMultiMigMembersRequest = (function() { /** - * Properties of a ListRegionMultiMigsRequest. + * Properties of a ListRegionMultiMigMembersRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionMultiMigsRequest - * @property {string|null} [filter] ListRegionMultiMigsRequest filter - * @property {number|null} [maxResults] ListRegionMultiMigsRequest maxResults - * @property {string|null} [orderBy] ListRegionMultiMigsRequest orderBy - * @property {string|null} [pageToken] ListRegionMultiMigsRequest pageToken - * @property {string|null} [project] ListRegionMultiMigsRequest project - * @property {string|null} [region] ListRegionMultiMigsRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionMultiMigsRequest returnPartialSuccess + * @interface IListRegionMultiMigMembersRequest + * @property {string|null} [filter] ListRegionMultiMigMembersRequest filter + * @property {number|null} [maxResults] ListRegionMultiMigMembersRequest maxResults + * @property {string|null} [multiMig] ListRegionMultiMigMembersRequest multiMig + * @property {string|null} [orderBy] ListRegionMultiMigMembersRequest orderBy + * @property {string|null} [pageToken] ListRegionMultiMigMembersRequest pageToken + * @property {string|null} [project] ListRegionMultiMigMembersRequest project + * @property {string|null} [region] ListRegionMultiMigMembersRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionMultiMigMembersRequest returnPartialSuccess */ /** - * Constructs a new ListRegionMultiMigsRequest. + * Constructs a new ListRegionMultiMigMembersRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionMultiMigsRequest. - * @implements IListRegionMultiMigsRequest + * @classdesc Represents a ListRegionMultiMigMembersRequest. + * @implements IListRegionMultiMigMembersRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionMultiMigsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionMultiMigMembersRequest=} [properties] Properties to set */ - function ListRegionMultiMigsRequest(properties) { + function ListRegionMultiMigMembersRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1009309,116 +1020506,124 @@ } /** - * ListRegionMultiMigsRequest filter. + * ListRegionMultiMigMembersRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @instance */ - ListRegionMultiMigsRequest.prototype.filter = null; + ListRegionMultiMigMembersRequest.prototype.filter = null; /** - * ListRegionMultiMigsRequest maxResults. + * ListRegionMultiMigMembersRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @instance */ - ListRegionMultiMigsRequest.prototype.maxResults = null; + ListRegionMultiMigMembersRequest.prototype.maxResults = null; /** - * ListRegionMultiMigsRequest orderBy. + * ListRegionMultiMigMembersRequest multiMig. + * @member {string} multiMig + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest + * @instance + */ + ListRegionMultiMigMembersRequest.prototype.multiMig = ""; + + /** + * ListRegionMultiMigMembersRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @instance */ - ListRegionMultiMigsRequest.prototype.orderBy = null; + ListRegionMultiMigMembersRequest.prototype.orderBy = null; /** - * ListRegionMultiMigsRequest pageToken. + * ListRegionMultiMigMembersRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @instance */ - ListRegionMultiMigsRequest.prototype.pageToken = null; + ListRegionMultiMigMembersRequest.prototype.pageToken = null; /** - * ListRegionMultiMigsRequest project. + * ListRegionMultiMigMembersRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @instance */ - ListRegionMultiMigsRequest.prototype.project = ""; + ListRegionMultiMigMembersRequest.prototype.project = ""; /** - * ListRegionMultiMigsRequest region. + * ListRegionMultiMigMembersRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @instance */ - ListRegionMultiMigsRequest.prototype.region = ""; + ListRegionMultiMigMembersRequest.prototype.region = ""; /** - * ListRegionMultiMigsRequest returnPartialSuccess. + * ListRegionMultiMigMembersRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @instance */ - ListRegionMultiMigsRequest.prototype.returnPartialSuccess = null; + ListRegionMultiMigMembersRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_filter", { + Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionMultiMigMembersRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionMultiMigsRequest instance using the specified properties. + * Creates a new ListRegionMultiMigMembersRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionMultiMigsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} ListRegionMultiMigsRequest instance + * @param {google.cloud.compute.v1beta.IListRegionMultiMigMembersRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} ListRegionMultiMigMembersRequest instance */ - ListRegionMultiMigsRequest.create = function create(properties) { - return new ListRegionMultiMigsRequest(properties); + ListRegionMultiMigMembersRequest.create = function create(properties) { + return new ListRegionMultiMigMembersRequest(properties); }; /** - * Encodes the specified ListRegionMultiMigsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionMultiMigsRequest.verify|verify} messages. + * Encodes the specified ListRegionMultiMigMembersRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionMultiMigsRequest} message ListRegionMultiMigsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionMultiMigMembersRequest} message ListRegionMultiMigMembersRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionMultiMigsRequest.encode = function encode(message, writer) { + ListRegionMultiMigMembersRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1009433,39 +1020638,41 @@ writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); + if (message.multiMig != null && Object.hasOwnProperty.call(message, "multiMig")) + writer.uint32(/* id 403990085, wireType 2 =*/3231920682).string(message.multiMig); if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); return writer; }; /** - * Encodes the specified ListRegionMultiMigsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionMultiMigsRequest.verify|verify} messages. + * Encodes the specified ListRegionMultiMigMembersRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionMultiMigsRequest} message ListRegionMultiMigsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionMultiMigMembersRequest} message ListRegionMultiMigMembersRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionMultiMigsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionMultiMigMembersRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionMultiMigsRequest message from the specified reader or buffer. + * Decodes a ListRegionMultiMigMembersRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} ListRegionMultiMigsRequest + * @returns {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} ListRegionMultiMigMembersRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionMultiMigsRequest.decode = function decode(reader, length, error) { + ListRegionMultiMigMembersRequest.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.cloud.compute.v1beta.ListRegionMultiMigsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1009479,6 +1020686,10 @@ message.maxResults = reader.uint32(); break; } + case 403990085: { + message.multiMig = reader.string(); + break; + } case 160562920: { message.orderBy = reader.string(); break; @@ -1009508,30 +1020719,30 @@ }; /** - * Decodes a ListRegionMultiMigsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionMultiMigMembersRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} ListRegionMultiMigsRequest + * @returns {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} ListRegionMultiMigMembersRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionMultiMigsRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionMultiMigMembersRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionMultiMigsRequest message. + * Verifies a ListRegionMultiMigMembersRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionMultiMigsRequest.verify = function verify(message) { + ListRegionMultiMigMembersRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1009545,6 +1020756,9 @@ if (!$util.isInteger(message.maxResults)) return "maxResults: integer expected"; } + if (message.multiMig != null && message.hasOwnProperty("multiMig")) + if (!$util.isString(message.multiMig)) + return "multiMig: string expected"; if (message.orderBy != null && message.hasOwnProperty("orderBy")) { properties._orderBy = 1; if (!$util.isString(message.orderBy)) @@ -1009570,21 +1020784,23 @@ }; /** - * Creates a ListRegionMultiMigsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionMultiMigMembersRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} ListRegionMultiMigsRequest + * @returns {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} ListRegionMultiMigMembersRequest */ - ListRegionMultiMigsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionMultiMigsRequest) + ListRegionMultiMigMembersRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionMultiMigsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) message.maxResults = object.maxResults >>> 0; + if (object.multiMig != null) + message.multiMig = String(object.multiMig); if (object.orderBy != null) message.orderBy = String(object.orderBy); if (object.pageToken != null) @@ -1009599,21 +1020815,22 @@ }; /** - * Creates a plain object from a ListRegionMultiMigsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionMultiMigMembersRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} message ListRegionMultiMigsRequest + * @param {google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest} message ListRegionMultiMigMembersRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionMultiMigsRequest.toObject = function toObject(message, options) { + ListRegionMultiMigMembersRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { object.region = ""; object.project = ""; + object.multiMig = ""; } if (message.pageToken != null && message.hasOwnProperty("pageToken")) { object.pageToken = message.pageToken; @@ -1009639,6 +1020856,8 @@ if (options.oneofs) object._filter = "filter"; } + if (message.multiMig != null && message.hasOwnProperty("multiMig")) + object.multiMig = message.multiMig; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { object.returnPartialSuccess = message.returnPartialSuccess; if (options.oneofs) @@ -1009648,58 +1020867,58 @@ }; /** - * Converts this ListRegionMultiMigsRequest to JSON. + * Converts this ListRegionMultiMigMembersRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @instance * @returns {Object.} JSON object */ - ListRegionMultiMigsRequest.prototype.toJSON = function toJSON() { + ListRegionMultiMigMembersRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionMultiMigsRequest + * Gets the default type url for ListRegionMultiMigMembersRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionMultiMigsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionMultiMigMembersRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionMultiMigsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionMultiMigMembersRequest"; }; - return ListRegionMultiMigsRequest; + return ListRegionMultiMigMembersRequest; })(); - v1beta.ListRegionNetworkEndpointGroupsRequest = (function() { + v1beta.ListRegionMultiMigsRequest = (function() { /** - * Properties of a ListRegionNetworkEndpointGroupsRequest. + * Properties of a ListRegionMultiMigsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionNetworkEndpointGroupsRequest - * @property {string|null} [filter] ListRegionNetworkEndpointGroupsRequest filter - * @property {number|null} [maxResults] ListRegionNetworkEndpointGroupsRequest maxResults - * @property {string|null} [orderBy] ListRegionNetworkEndpointGroupsRequest orderBy - * @property {string|null} [pageToken] ListRegionNetworkEndpointGroupsRequest pageToken - * @property {string|null} [project] ListRegionNetworkEndpointGroupsRequest project - * @property {string|null} [region] ListRegionNetworkEndpointGroupsRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionNetworkEndpointGroupsRequest returnPartialSuccess + * @interface IListRegionMultiMigsRequest + * @property {string|null} [filter] ListRegionMultiMigsRequest filter + * @property {number|null} [maxResults] ListRegionMultiMigsRequest maxResults + * @property {string|null} [orderBy] ListRegionMultiMigsRequest orderBy + * @property {string|null} [pageToken] ListRegionMultiMigsRequest pageToken + * @property {string|null} [project] ListRegionMultiMigsRequest project + * @property {string|null} [region] ListRegionMultiMigsRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionMultiMigsRequest returnPartialSuccess */ /** - * Constructs a new ListRegionNetworkEndpointGroupsRequest. + * Constructs a new ListRegionMultiMigsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionNetworkEndpointGroupsRequest. - * @implements IListRegionNetworkEndpointGroupsRequest + * @classdesc Represents a ListRegionMultiMigsRequest. + * @implements IListRegionMultiMigsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionNetworkEndpointGroupsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionMultiMigsRequest=} [properties] Properties to set */ - function ListRegionNetworkEndpointGroupsRequest(properties) { + function ListRegionMultiMigsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1009707,116 +1020926,116 @@ } /** - * ListRegionNetworkEndpointGroupsRequest filter. + * ListRegionMultiMigsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @instance */ - ListRegionNetworkEndpointGroupsRequest.prototype.filter = null; + ListRegionMultiMigsRequest.prototype.filter = null; /** - * ListRegionNetworkEndpointGroupsRequest maxResults. + * ListRegionMultiMigsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @instance */ - ListRegionNetworkEndpointGroupsRequest.prototype.maxResults = null; + ListRegionMultiMigsRequest.prototype.maxResults = null; /** - * ListRegionNetworkEndpointGroupsRequest orderBy. + * ListRegionMultiMigsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @instance */ - ListRegionNetworkEndpointGroupsRequest.prototype.orderBy = null; + ListRegionMultiMigsRequest.prototype.orderBy = null; /** - * ListRegionNetworkEndpointGroupsRequest pageToken. + * ListRegionMultiMigsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @instance */ - ListRegionNetworkEndpointGroupsRequest.prototype.pageToken = null; + ListRegionMultiMigsRequest.prototype.pageToken = null; /** - * ListRegionNetworkEndpointGroupsRequest project. + * ListRegionMultiMigsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @instance */ - ListRegionNetworkEndpointGroupsRequest.prototype.project = ""; + ListRegionMultiMigsRequest.prototype.project = ""; /** - * ListRegionNetworkEndpointGroupsRequest region. + * ListRegionMultiMigsRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @instance */ - ListRegionNetworkEndpointGroupsRequest.prototype.region = ""; + ListRegionMultiMigsRequest.prototype.region = ""; /** - * ListRegionNetworkEndpointGroupsRequest returnPartialSuccess. + * ListRegionMultiMigsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @instance */ - ListRegionNetworkEndpointGroupsRequest.prototype.returnPartialSuccess = null; + ListRegionMultiMigsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_filter", { + Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionMultiMigsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionNetworkEndpointGroupsRequest instance using the specified properties. + * Creates a new ListRegionMultiMigsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkEndpointGroupsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} ListRegionNetworkEndpointGroupsRequest instance + * @param {google.cloud.compute.v1beta.IListRegionMultiMigsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} ListRegionMultiMigsRequest instance */ - ListRegionNetworkEndpointGroupsRequest.create = function create(properties) { - return new ListRegionNetworkEndpointGroupsRequest(properties); + ListRegionMultiMigsRequest.create = function create(properties) { + return new ListRegionMultiMigsRequest(properties); }; /** - * Encodes the specified ListRegionNetworkEndpointGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest.verify|verify} messages. + * Encodes the specified ListRegionMultiMigsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionMultiMigsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkEndpointGroupsRequest} message ListRegionNetworkEndpointGroupsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionMultiMigsRequest} message ListRegionMultiMigsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionNetworkEndpointGroupsRequest.encode = function encode(message, writer) { + ListRegionMultiMigsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1009837,33 +1021056,33 @@ }; /** - * Encodes the specified ListRegionNetworkEndpointGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest.verify|verify} messages. + * Encodes the specified ListRegionMultiMigsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionMultiMigsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkEndpointGroupsRequest} message ListRegionNetworkEndpointGroupsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionMultiMigsRequest} message ListRegionMultiMigsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionNetworkEndpointGroupsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionMultiMigsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionNetworkEndpointGroupsRequest message from the specified reader or buffer. + * Decodes a ListRegionMultiMigsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} ListRegionNetworkEndpointGroupsRequest + * @returns {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} ListRegionMultiMigsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionNetworkEndpointGroupsRequest.decode = function decode(reader, length, error) { + ListRegionMultiMigsRequest.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.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionMultiMigsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1009906,30 +1021125,30 @@ }; /** - * Decodes a ListRegionNetworkEndpointGroupsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionMultiMigsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} ListRegionNetworkEndpointGroupsRequest + * @returns {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} ListRegionMultiMigsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionNetworkEndpointGroupsRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionMultiMigsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionNetworkEndpointGroupsRequest message. + * Verifies a ListRegionMultiMigsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionNetworkEndpointGroupsRequest.verify = function verify(message) { + ListRegionMultiMigsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1009968,17 +1021187,17 @@ }; /** - * Creates a ListRegionNetworkEndpointGroupsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionMultiMigsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} ListRegionNetworkEndpointGroupsRequest + * @returns {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} ListRegionMultiMigsRequest */ - ListRegionNetworkEndpointGroupsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest) + ListRegionMultiMigsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionMultiMigsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionMultiMigsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1009997,15 +1021216,15 @@ }; /** - * Creates a plain object from a ListRegionNetworkEndpointGroupsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionMultiMigsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} message ListRegionNetworkEndpointGroupsRequest + * @param {google.cloud.compute.v1beta.ListRegionMultiMigsRequest} message ListRegionMultiMigsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionNetworkEndpointGroupsRequest.toObject = function toObject(message, options) { + ListRegionMultiMigsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1010046,58 +1021265,58 @@ }; /** - * Converts this ListRegionNetworkEndpointGroupsRequest to JSON. + * Converts this ListRegionMultiMigsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @instance * @returns {Object.} JSON object */ - ListRegionNetworkEndpointGroupsRequest.prototype.toJSON = function toJSON() { + ListRegionMultiMigsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionNetworkEndpointGroupsRequest + * Gets the default type url for ListRegionMultiMigsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest + * @memberof google.cloud.compute.v1beta.ListRegionMultiMigsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionNetworkEndpointGroupsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionMultiMigsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionMultiMigsRequest"; }; - return ListRegionNetworkEndpointGroupsRequest; + return ListRegionMultiMigsRequest; })(); - v1beta.ListRegionNetworkFirewallPoliciesRequest = (function() { + v1beta.ListRegionNetworkEndpointGroupsRequest = (function() { /** - * Properties of a ListRegionNetworkFirewallPoliciesRequest. + * Properties of a ListRegionNetworkEndpointGroupsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionNetworkFirewallPoliciesRequest - * @property {string|null} [filter] ListRegionNetworkFirewallPoliciesRequest filter - * @property {number|null} [maxResults] ListRegionNetworkFirewallPoliciesRequest maxResults - * @property {string|null} [orderBy] ListRegionNetworkFirewallPoliciesRequest orderBy - * @property {string|null} [pageToken] ListRegionNetworkFirewallPoliciesRequest pageToken - * @property {string|null} [project] ListRegionNetworkFirewallPoliciesRequest project - * @property {string|null} [region] ListRegionNetworkFirewallPoliciesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionNetworkFirewallPoliciesRequest returnPartialSuccess + * @interface IListRegionNetworkEndpointGroupsRequest + * @property {string|null} [filter] ListRegionNetworkEndpointGroupsRequest filter + * @property {number|null} [maxResults] ListRegionNetworkEndpointGroupsRequest maxResults + * @property {string|null} [orderBy] ListRegionNetworkEndpointGroupsRequest orderBy + * @property {string|null} [pageToken] ListRegionNetworkEndpointGroupsRequest pageToken + * @property {string|null} [project] ListRegionNetworkEndpointGroupsRequest project + * @property {string|null} [region] ListRegionNetworkEndpointGroupsRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionNetworkEndpointGroupsRequest returnPartialSuccess */ /** - * Constructs a new ListRegionNetworkFirewallPoliciesRequest. + * Constructs a new ListRegionNetworkEndpointGroupsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionNetworkFirewallPoliciesRequest. - * @implements IListRegionNetworkFirewallPoliciesRequest + * @classdesc Represents a ListRegionNetworkEndpointGroupsRequest. + * @implements IListRegionNetworkEndpointGroupsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionNetworkFirewallPoliciesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionNetworkEndpointGroupsRequest=} [properties] Properties to set */ - function ListRegionNetworkFirewallPoliciesRequest(properties) { + function ListRegionNetworkEndpointGroupsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1010105,116 +1021324,116 @@ } /** - * ListRegionNetworkFirewallPoliciesRequest filter. + * ListRegionNetworkEndpointGroupsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @instance */ - ListRegionNetworkFirewallPoliciesRequest.prototype.filter = null; + ListRegionNetworkEndpointGroupsRequest.prototype.filter = null; /** - * ListRegionNetworkFirewallPoliciesRequest maxResults. + * ListRegionNetworkEndpointGroupsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @instance */ - ListRegionNetworkFirewallPoliciesRequest.prototype.maxResults = null; + ListRegionNetworkEndpointGroupsRequest.prototype.maxResults = null; /** - * ListRegionNetworkFirewallPoliciesRequest orderBy. + * ListRegionNetworkEndpointGroupsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @instance */ - ListRegionNetworkFirewallPoliciesRequest.prototype.orderBy = null; + ListRegionNetworkEndpointGroupsRequest.prototype.orderBy = null; /** - * ListRegionNetworkFirewallPoliciesRequest pageToken. + * ListRegionNetworkEndpointGroupsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @instance */ - ListRegionNetworkFirewallPoliciesRequest.prototype.pageToken = null; + ListRegionNetworkEndpointGroupsRequest.prototype.pageToken = null; /** - * ListRegionNetworkFirewallPoliciesRequest project. + * ListRegionNetworkEndpointGroupsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @instance */ - ListRegionNetworkFirewallPoliciesRequest.prototype.project = ""; + ListRegionNetworkEndpointGroupsRequest.prototype.project = ""; /** - * ListRegionNetworkFirewallPoliciesRequest region. + * ListRegionNetworkEndpointGroupsRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @instance */ - ListRegionNetworkFirewallPoliciesRequest.prototype.region = ""; + ListRegionNetworkEndpointGroupsRequest.prototype.region = ""; /** - * ListRegionNetworkFirewallPoliciesRequest returnPartialSuccess. + * ListRegionNetworkEndpointGroupsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @instance */ - ListRegionNetworkFirewallPoliciesRequest.prototype.returnPartialSuccess = null; + ListRegionNetworkEndpointGroupsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionNetworkEndpointGroupsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionNetworkFirewallPoliciesRequest instance using the specified properties. + * Creates a new ListRegionNetworkEndpointGroupsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkFirewallPoliciesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} ListRegionNetworkFirewallPoliciesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionNetworkEndpointGroupsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} ListRegionNetworkEndpointGroupsRequest instance */ - ListRegionNetworkFirewallPoliciesRequest.create = function create(properties) { - return new ListRegionNetworkFirewallPoliciesRequest(properties); + ListRegionNetworkEndpointGroupsRequest.create = function create(properties) { + return new ListRegionNetworkEndpointGroupsRequest(properties); }; /** - * Encodes the specified ListRegionNetworkFirewallPoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest.verify|verify} messages. + * Encodes the specified ListRegionNetworkEndpointGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkFirewallPoliciesRequest} message ListRegionNetworkFirewallPoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionNetworkEndpointGroupsRequest} message ListRegionNetworkEndpointGroupsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionNetworkFirewallPoliciesRequest.encode = function encode(message, writer) { + ListRegionNetworkEndpointGroupsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1010235,33 +1021454,33 @@ }; /** - * Encodes the specified ListRegionNetworkFirewallPoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest.verify|verify} messages. + * Encodes the specified ListRegionNetworkEndpointGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkFirewallPoliciesRequest} message ListRegionNetworkFirewallPoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionNetworkEndpointGroupsRequest} message ListRegionNetworkEndpointGroupsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionNetworkFirewallPoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionNetworkEndpointGroupsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionNetworkFirewallPoliciesRequest message from the specified reader or buffer. + * Decodes a ListRegionNetworkEndpointGroupsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} ListRegionNetworkFirewallPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} ListRegionNetworkEndpointGroupsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionNetworkFirewallPoliciesRequest.decode = function decode(reader, length, error) { + ListRegionNetworkEndpointGroupsRequest.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.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1010304,30 +1021523,30 @@ }; /** - * Decodes a ListRegionNetworkFirewallPoliciesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionNetworkEndpointGroupsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} ListRegionNetworkFirewallPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} ListRegionNetworkEndpointGroupsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionNetworkFirewallPoliciesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionNetworkEndpointGroupsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionNetworkFirewallPoliciesRequest message. + * Verifies a ListRegionNetworkEndpointGroupsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionNetworkFirewallPoliciesRequest.verify = function verify(message) { + ListRegionNetworkEndpointGroupsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1010366,17 +1021585,17 @@ }; /** - * Creates a ListRegionNetworkFirewallPoliciesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionNetworkEndpointGroupsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} ListRegionNetworkFirewallPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} ListRegionNetworkEndpointGroupsRequest */ - ListRegionNetworkFirewallPoliciesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest) + ListRegionNetworkEndpointGroupsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1010395,15 +1021614,15 @@ }; /** - * Creates a plain object from a ListRegionNetworkFirewallPoliciesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionNetworkEndpointGroupsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} message ListRegionNetworkFirewallPoliciesRequest + * @param {google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest} message ListRegionNetworkEndpointGroupsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionNetworkFirewallPoliciesRequest.toObject = function toObject(message, options) { + ListRegionNetworkEndpointGroupsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1010444,58 +1021663,58 @@ }; /** - * Converts this ListRegionNetworkFirewallPoliciesRequest to JSON. + * Converts this ListRegionNetworkEndpointGroupsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @instance * @returns {Object.} JSON object */ - ListRegionNetworkFirewallPoliciesRequest.prototype.toJSON = function toJSON() { + ListRegionNetworkEndpointGroupsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionNetworkFirewallPoliciesRequest + * Gets the default type url for ListRegionNetworkEndpointGroupsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionNetworkFirewallPoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionNetworkEndpointGroupsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionNetworkEndpointGroupsRequest"; }; - return ListRegionNetworkFirewallPoliciesRequest; + return ListRegionNetworkEndpointGroupsRequest; })(); - v1beta.ListRegionNetworkPoliciesRequest = (function() { + v1beta.ListRegionNetworkFirewallPoliciesRequest = (function() { /** - * Properties of a ListRegionNetworkPoliciesRequest. + * Properties of a ListRegionNetworkFirewallPoliciesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionNetworkPoliciesRequest - * @property {string|null} [filter] ListRegionNetworkPoliciesRequest filter - * @property {number|null} [maxResults] ListRegionNetworkPoliciesRequest maxResults - * @property {string|null} [orderBy] ListRegionNetworkPoliciesRequest orderBy - * @property {string|null} [pageToken] ListRegionNetworkPoliciesRequest pageToken - * @property {string|null} [project] ListRegionNetworkPoliciesRequest project - * @property {string|null} [region] ListRegionNetworkPoliciesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionNetworkPoliciesRequest returnPartialSuccess + * @interface IListRegionNetworkFirewallPoliciesRequest + * @property {string|null} [filter] ListRegionNetworkFirewallPoliciesRequest filter + * @property {number|null} [maxResults] ListRegionNetworkFirewallPoliciesRequest maxResults + * @property {string|null} [orderBy] ListRegionNetworkFirewallPoliciesRequest orderBy + * @property {string|null} [pageToken] ListRegionNetworkFirewallPoliciesRequest pageToken + * @property {string|null} [project] ListRegionNetworkFirewallPoliciesRequest project + * @property {string|null} [region] ListRegionNetworkFirewallPoliciesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionNetworkFirewallPoliciesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionNetworkPoliciesRequest. + * Constructs a new ListRegionNetworkFirewallPoliciesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionNetworkPoliciesRequest. - * @implements IListRegionNetworkPoliciesRequest + * @classdesc Represents a ListRegionNetworkFirewallPoliciesRequest. + * @implements IListRegionNetworkFirewallPoliciesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionNetworkPoliciesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionNetworkFirewallPoliciesRequest=} [properties] Properties to set */ - function ListRegionNetworkPoliciesRequest(properties) { + function ListRegionNetworkFirewallPoliciesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1010503,116 +1021722,116 @@ } /** - * ListRegionNetworkPoliciesRequest filter. + * ListRegionNetworkFirewallPoliciesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @instance */ - ListRegionNetworkPoliciesRequest.prototype.filter = null; + ListRegionNetworkFirewallPoliciesRequest.prototype.filter = null; /** - * ListRegionNetworkPoliciesRequest maxResults. + * ListRegionNetworkFirewallPoliciesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @instance */ - ListRegionNetworkPoliciesRequest.prototype.maxResults = null; + ListRegionNetworkFirewallPoliciesRequest.prototype.maxResults = null; /** - * ListRegionNetworkPoliciesRequest orderBy. + * ListRegionNetworkFirewallPoliciesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @instance */ - ListRegionNetworkPoliciesRequest.prototype.orderBy = null; + ListRegionNetworkFirewallPoliciesRequest.prototype.orderBy = null; /** - * ListRegionNetworkPoliciesRequest pageToken. + * ListRegionNetworkFirewallPoliciesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @instance */ - ListRegionNetworkPoliciesRequest.prototype.pageToken = null; + ListRegionNetworkFirewallPoliciesRequest.prototype.pageToken = null; /** - * ListRegionNetworkPoliciesRequest project. + * ListRegionNetworkFirewallPoliciesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @instance */ - ListRegionNetworkPoliciesRequest.prototype.project = ""; + ListRegionNetworkFirewallPoliciesRequest.prototype.project = ""; /** - * ListRegionNetworkPoliciesRequest region. + * ListRegionNetworkFirewallPoliciesRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @instance */ - ListRegionNetworkPoliciesRequest.prototype.region = ""; + ListRegionNetworkFirewallPoliciesRequest.prototype.region = ""; /** - * ListRegionNetworkPoliciesRequest returnPartialSuccess. + * ListRegionNetworkFirewallPoliciesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @instance */ - ListRegionNetworkPoliciesRequest.prototype.returnPartialSuccess = null; + ListRegionNetworkFirewallPoliciesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionNetworkFirewallPoliciesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionNetworkPoliciesRequest instance using the specified properties. + * Creates a new ListRegionNetworkFirewallPoliciesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkPoliciesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} ListRegionNetworkPoliciesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionNetworkFirewallPoliciesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} ListRegionNetworkFirewallPoliciesRequest instance */ - ListRegionNetworkPoliciesRequest.create = function create(properties) { - return new ListRegionNetworkPoliciesRequest(properties); + ListRegionNetworkFirewallPoliciesRequest.create = function create(properties) { + return new ListRegionNetworkFirewallPoliciesRequest(properties); }; /** - * Encodes the specified ListRegionNetworkPoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest.verify|verify} messages. + * Encodes the specified ListRegionNetworkFirewallPoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkPoliciesRequest} message ListRegionNetworkPoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionNetworkFirewallPoliciesRequest} message ListRegionNetworkFirewallPoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionNetworkPoliciesRequest.encode = function encode(message, writer) { + ListRegionNetworkFirewallPoliciesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1010633,33 +1021852,33 @@ }; /** - * Encodes the specified ListRegionNetworkPoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest.verify|verify} messages. + * Encodes the specified ListRegionNetworkFirewallPoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNetworkPoliciesRequest} message ListRegionNetworkPoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionNetworkFirewallPoliciesRequest} message ListRegionNetworkFirewallPoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionNetworkPoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionNetworkFirewallPoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionNetworkPoliciesRequest message from the specified reader or buffer. + * Decodes a ListRegionNetworkFirewallPoliciesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} ListRegionNetworkPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} ListRegionNetworkFirewallPoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionNetworkPoliciesRequest.decode = function decode(reader, length, error) { + ListRegionNetworkFirewallPoliciesRequest.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.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1010702,30 +1021921,30 @@ }; /** - * Decodes a ListRegionNetworkPoliciesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionNetworkFirewallPoliciesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} ListRegionNetworkPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} ListRegionNetworkFirewallPoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionNetworkPoliciesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionNetworkFirewallPoliciesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionNetworkPoliciesRequest message. + * Verifies a ListRegionNetworkFirewallPoliciesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionNetworkPoliciesRequest.verify = function verify(message) { + ListRegionNetworkFirewallPoliciesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1010764,17 +1021983,17 @@ }; /** - * Creates a ListRegionNetworkPoliciesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionNetworkFirewallPoliciesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} ListRegionNetworkPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} ListRegionNetworkFirewallPoliciesRequest */ - ListRegionNetworkPoliciesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest) + ListRegionNetworkFirewallPoliciesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1010793,15 +1022012,15 @@ }; /** - * Creates a plain object from a ListRegionNetworkPoliciesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionNetworkFirewallPoliciesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} message ListRegionNetworkPoliciesRequest + * @param {google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest} message ListRegionNetworkFirewallPoliciesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionNetworkPoliciesRequest.toObject = function toObject(message, options) { + ListRegionNetworkFirewallPoliciesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1010842,58 +1022061,58 @@ }; /** - * Converts this ListRegionNetworkPoliciesRequest to JSON. + * Converts this ListRegionNetworkFirewallPoliciesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @instance * @returns {Object.} JSON object */ - ListRegionNetworkPoliciesRequest.prototype.toJSON = function toJSON() { + ListRegionNetworkFirewallPoliciesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionNetworkPoliciesRequest + * Gets the default type url for ListRegionNetworkFirewallPoliciesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionNetworkPoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionNetworkFirewallPoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionNetworkFirewallPoliciesRequest"; }; - return ListRegionNetworkPoliciesRequest; + return ListRegionNetworkFirewallPoliciesRequest; })(); - v1beta.ListRegionNotificationEndpointsRequest = (function() { + v1beta.ListRegionNetworkPoliciesRequest = (function() { /** - * Properties of a ListRegionNotificationEndpointsRequest. + * Properties of a ListRegionNetworkPoliciesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionNotificationEndpointsRequest - * @property {string|null} [filter] ListRegionNotificationEndpointsRequest filter - * @property {number|null} [maxResults] ListRegionNotificationEndpointsRequest maxResults - * @property {string|null} [orderBy] ListRegionNotificationEndpointsRequest orderBy - * @property {string|null} [pageToken] ListRegionNotificationEndpointsRequest pageToken - * @property {string|null} [project] ListRegionNotificationEndpointsRequest project - * @property {string|null} [region] ListRegionNotificationEndpointsRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionNotificationEndpointsRequest returnPartialSuccess + * @interface IListRegionNetworkPoliciesRequest + * @property {string|null} [filter] ListRegionNetworkPoliciesRequest filter + * @property {number|null} [maxResults] ListRegionNetworkPoliciesRequest maxResults + * @property {string|null} [orderBy] ListRegionNetworkPoliciesRequest orderBy + * @property {string|null} [pageToken] ListRegionNetworkPoliciesRequest pageToken + * @property {string|null} [project] ListRegionNetworkPoliciesRequest project + * @property {string|null} [region] ListRegionNetworkPoliciesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionNetworkPoliciesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionNotificationEndpointsRequest. + * Constructs a new ListRegionNetworkPoliciesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionNotificationEndpointsRequest. - * @implements IListRegionNotificationEndpointsRequest + * @classdesc Represents a ListRegionNetworkPoliciesRequest. + * @implements IListRegionNetworkPoliciesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionNotificationEndpointsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionNetworkPoliciesRequest=} [properties] Properties to set */ - function ListRegionNotificationEndpointsRequest(properties) { + function ListRegionNetworkPoliciesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1010901,116 +1022120,116 @@ } /** - * ListRegionNotificationEndpointsRequest filter. + * ListRegionNetworkPoliciesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @instance */ - ListRegionNotificationEndpointsRequest.prototype.filter = null; + ListRegionNetworkPoliciesRequest.prototype.filter = null; /** - * ListRegionNotificationEndpointsRequest maxResults. + * ListRegionNetworkPoliciesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @instance */ - ListRegionNotificationEndpointsRequest.prototype.maxResults = null; + ListRegionNetworkPoliciesRequest.prototype.maxResults = null; /** - * ListRegionNotificationEndpointsRequest orderBy. + * ListRegionNetworkPoliciesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @instance */ - ListRegionNotificationEndpointsRequest.prototype.orderBy = null; + ListRegionNetworkPoliciesRequest.prototype.orderBy = null; /** - * ListRegionNotificationEndpointsRequest pageToken. + * ListRegionNetworkPoliciesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @instance */ - ListRegionNotificationEndpointsRequest.prototype.pageToken = null; + ListRegionNetworkPoliciesRequest.prototype.pageToken = null; /** - * ListRegionNotificationEndpointsRequest project. + * ListRegionNetworkPoliciesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @instance */ - ListRegionNotificationEndpointsRequest.prototype.project = ""; + ListRegionNetworkPoliciesRequest.prototype.project = ""; /** - * ListRegionNotificationEndpointsRequest region. + * ListRegionNetworkPoliciesRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @instance */ - ListRegionNotificationEndpointsRequest.prototype.region = ""; + ListRegionNetworkPoliciesRequest.prototype.region = ""; /** - * ListRegionNotificationEndpointsRequest returnPartialSuccess. + * ListRegionNetworkPoliciesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @instance */ - ListRegionNotificationEndpointsRequest.prototype.returnPartialSuccess = null; + ListRegionNetworkPoliciesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_filter", { + Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionNetworkPoliciesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionNotificationEndpointsRequest instance using the specified properties. + * Creates a new ListRegionNetworkPoliciesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNotificationEndpointsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} ListRegionNotificationEndpointsRequest instance + * @param {google.cloud.compute.v1beta.IListRegionNetworkPoliciesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} ListRegionNetworkPoliciesRequest instance */ - ListRegionNotificationEndpointsRequest.create = function create(properties) { - return new ListRegionNotificationEndpointsRequest(properties); + ListRegionNetworkPoliciesRequest.create = function create(properties) { + return new ListRegionNetworkPoliciesRequest(properties); }; /** - * Encodes the specified ListRegionNotificationEndpointsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest.verify|verify} messages. + * Encodes the specified ListRegionNetworkPoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNotificationEndpointsRequest} message ListRegionNotificationEndpointsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionNetworkPoliciesRequest} message ListRegionNetworkPoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionNotificationEndpointsRequest.encode = function encode(message, writer) { + ListRegionNetworkPoliciesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1011031,33 +1022250,33 @@ }; /** - * Encodes the specified ListRegionNotificationEndpointsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest.verify|verify} messages. + * Encodes the specified ListRegionNetworkPoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionNotificationEndpointsRequest} message ListRegionNotificationEndpointsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionNetworkPoliciesRequest} message ListRegionNetworkPoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionNotificationEndpointsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionNetworkPoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionNotificationEndpointsRequest message from the specified reader or buffer. + * Decodes a ListRegionNetworkPoliciesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} ListRegionNotificationEndpointsRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} ListRegionNetworkPoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionNotificationEndpointsRequest.decode = function decode(reader, length, error) { + ListRegionNetworkPoliciesRequest.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.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1011100,30 +1022319,30 @@ }; /** - * Decodes a ListRegionNotificationEndpointsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionNetworkPoliciesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} ListRegionNotificationEndpointsRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} ListRegionNetworkPoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionNotificationEndpointsRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionNetworkPoliciesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionNotificationEndpointsRequest message. + * Verifies a ListRegionNetworkPoliciesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionNotificationEndpointsRequest.verify = function verify(message) { + ListRegionNetworkPoliciesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1011162,17 +1022381,17 @@ }; /** - * Creates a ListRegionNotificationEndpointsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionNetworkPoliciesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} ListRegionNotificationEndpointsRequest + * @returns {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} ListRegionNetworkPoliciesRequest */ - ListRegionNotificationEndpointsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest) + ListRegionNetworkPoliciesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1011191,15 +1022410,15 @@ }; /** - * Creates a plain object from a ListRegionNotificationEndpointsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionNetworkPoliciesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} message ListRegionNotificationEndpointsRequest + * @param {google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest} message ListRegionNetworkPoliciesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionNotificationEndpointsRequest.toObject = function toObject(message, options) { + ListRegionNetworkPoliciesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1011240,58 +1022459,58 @@ }; /** - * Converts this ListRegionNotificationEndpointsRequest to JSON. + * Converts this ListRegionNetworkPoliciesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @instance * @returns {Object.} JSON object */ - ListRegionNotificationEndpointsRequest.prototype.toJSON = function toJSON() { + ListRegionNetworkPoliciesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionNotificationEndpointsRequest + * Gets the default type url for ListRegionNetworkPoliciesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionNotificationEndpointsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionNetworkPoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionNetworkPoliciesRequest"; }; - return ListRegionNotificationEndpointsRequest; + return ListRegionNetworkPoliciesRequest; })(); - v1beta.ListRegionOperationsRequest = (function() { + v1beta.ListRegionNotificationEndpointsRequest = (function() { /** - * Properties of a ListRegionOperationsRequest. + * Properties of a ListRegionNotificationEndpointsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionOperationsRequest - * @property {string|null} [filter] ListRegionOperationsRequest filter - * @property {number|null} [maxResults] ListRegionOperationsRequest maxResults - * @property {string|null} [orderBy] ListRegionOperationsRequest orderBy - * @property {string|null} [pageToken] ListRegionOperationsRequest pageToken - * @property {string|null} [project] ListRegionOperationsRequest project - * @property {string|null} [region] ListRegionOperationsRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionOperationsRequest returnPartialSuccess + * @interface IListRegionNotificationEndpointsRequest + * @property {string|null} [filter] ListRegionNotificationEndpointsRequest filter + * @property {number|null} [maxResults] ListRegionNotificationEndpointsRequest maxResults + * @property {string|null} [orderBy] ListRegionNotificationEndpointsRequest orderBy + * @property {string|null} [pageToken] ListRegionNotificationEndpointsRequest pageToken + * @property {string|null} [project] ListRegionNotificationEndpointsRequest project + * @property {string|null} [region] ListRegionNotificationEndpointsRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionNotificationEndpointsRequest returnPartialSuccess */ /** - * Constructs a new ListRegionOperationsRequest. + * Constructs a new ListRegionNotificationEndpointsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionOperationsRequest. - * @implements IListRegionOperationsRequest + * @classdesc Represents a ListRegionNotificationEndpointsRequest. + * @implements IListRegionNotificationEndpointsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionOperationsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionNotificationEndpointsRequest=} [properties] Properties to set */ - function ListRegionOperationsRequest(properties) { + function ListRegionNotificationEndpointsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1011299,116 +1022518,116 @@ } /** - * ListRegionOperationsRequest filter. + * ListRegionNotificationEndpointsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @instance */ - ListRegionOperationsRequest.prototype.filter = null; + ListRegionNotificationEndpointsRequest.prototype.filter = null; /** - * ListRegionOperationsRequest maxResults. + * ListRegionNotificationEndpointsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @instance */ - ListRegionOperationsRequest.prototype.maxResults = null; + ListRegionNotificationEndpointsRequest.prototype.maxResults = null; /** - * ListRegionOperationsRequest orderBy. + * ListRegionNotificationEndpointsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @instance */ - ListRegionOperationsRequest.prototype.orderBy = null; + ListRegionNotificationEndpointsRequest.prototype.orderBy = null; /** - * ListRegionOperationsRequest pageToken. + * ListRegionNotificationEndpointsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @instance */ - ListRegionOperationsRequest.prototype.pageToken = null; + ListRegionNotificationEndpointsRequest.prototype.pageToken = null; /** - * ListRegionOperationsRequest project. + * ListRegionNotificationEndpointsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @instance */ - ListRegionOperationsRequest.prototype.project = ""; + ListRegionNotificationEndpointsRequest.prototype.project = ""; /** - * ListRegionOperationsRequest region. + * ListRegionNotificationEndpointsRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @instance */ - ListRegionOperationsRequest.prototype.region = ""; + ListRegionNotificationEndpointsRequest.prototype.region = ""; /** - * ListRegionOperationsRequest returnPartialSuccess. + * ListRegionNotificationEndpointsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @instance */ - ListRegionOperationsRequest.prototype.returnPartialSuccess = null; + ListRegionNotificationEndpointsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionOperationsRequest.prototype, "_filter", { + Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionOperationsRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionOperationsRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionOperationsRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionOperationsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionNotificationEndpointsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionOperationsRequest instance using the specified properties. + * Creates a new ListRegionNotificationEndpointsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionOperationsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionOperationsRequest} ListRegionOperationsRequest instance + * @param {google.cloud.compute.v1beta.IListRegionNotificationEndpointsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} ListRegionNotificationEndpointsRequest instance */ - ListRegionOperationsRequest.create = function create(properties) { - return new ListRegionOperationsRequest(properties); + ListRegionNotificationEndpointsRequest.create = function create(properties) { + return new ListRegionNotificationEndpointsRequest(properties); }; /** - * Encodes the specified ListRegionOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionOperationsRequest.verify|verify} messages. + * Encodes the specified ListRegionNotificationEndpointsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionOperationsRequest} message ListRegionOperationsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionNotificationEndpointsRequest} message ListRegionNotificationEndpointsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionOperationsRequest.encode = function encode(message, writer) { + ListRegionNotificationEndpointsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1011429,33 +1022648,33 @@ }; /** - * Encodes the specified ListRegionOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionOperationsRequest.verify|verify} messages. + * Encodes the specified ListRegionNotificationEndpointsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionOperationsRequest} message ListRegionOperationsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionNotificationEndpointsRequest} message ListRegionNotificationEndpointsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionOperationsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionNotificationEndpointsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionOperationsRequest message from the specified reader or buffer. + * Decodes a ListRegionNotificationEndpointsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionOperationsRequest} ListRegionOperationsRequest + * @returns {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} ListRegionNotificationEndpointsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionOperationsRequest.decode = function decode(reader, length, error) { + ListRegionNotificationEndpointsRequest.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.cloud.compute.v1beta.ListRegionOperationsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1011498,30 +1022717,30 @@ }; /** - * Decodes a ListRegionOperationsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionNotificationEndpointsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionOperationsRequest} ListRegionOperationsRequest + * @returns {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} ListRegionNotificationEndpointsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionOperationsRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionNotificationEndpointsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionOperationsRequest message. + * Verifies a ListRegionNotificationEndpointsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionOperationsRequest.verify = function verify(message) { + ListRegionNotificationEndpointsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1011560,17 +1022779,17 @@ }; /** - * Creates a ListRegionOperationsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionNotificationEndpointsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionOperationsRequest} ListRegionOperationsRequest + * @returns {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} ListRegionNotificationEndpointsRequest */ - ListRegionOperationsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionOperationsRequest) + ListRegionNotificationEndpointsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionOperationsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1011589,15 +1022808,15 @@ }; /** - * Creates a plain object from a ListRegionOperationsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionNotificationEndpointsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionOperationsRequest} message ListRegionOperationsRequest + * @param {google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest} message ListRegionNotificationEndpointsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionOperationsRequest.toObject = function toObject(message, options) { + ListRegionNotificationEndpointsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1011638,58 +1022857,58 @@ }; /** - * Converts this ListRegionOperationsRequest to JSON. + * Converts this ListRegionNotificationEndpointsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @instance * @returns {Object.} JSON object */ - ListRegionOperationsRequest.prototype.toJSON = function toJSON() { + ListRegionNotificationEndpointsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionOperationsRequest + * Gets the default type url for ListRegionNotificationEndpointsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest + * @memberof google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionNotificationEndpointsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionOperationsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionNotificationEndpointsRequest"; }; - return ListRegionOperationsRequest; + return ListRegionNotificationEndpointsRequest; })(); - v1beta.ListRegionSecurityPoliciesRequest = (function() { + v1beta.ListRegionOperationsRequest = (function() { /** - * Properties of a ListRegionSecurityPoliciesRequest. + * Properties of a ListRegionOperationsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionSecurityPoliciesRequest - * @property {string|null} [filter] ListRegionSecurityPoliciesRequest filter - * @property {number|null} [maxResults] ListRegionSecurityPoliciesRequest maxResults - * @property {string|null} [orderBy] ListRegionSecurityPoliciesRequest orderBy - * @property {string|null} [pageToken] ListRegionSecurityPoliciesRequest pageToken - * @property {string|null} [project] ListRegionSecurityPoliciesRequest project - * @property {string|null} [region] ListRegionSecurityPoliciesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionSecurityPoliciesRequest returnPartialSuccess + * @interface IListRegionOperationsRequest + * @property {string|null} [filter] ListRegionOperationsRequest filter + * @property {number|null} [maxResults] ListRegionOperationsRequest maxResults + * @property {string|null} [orderBy] ListRegionOperationsRequest orderBy + * @property {string|null} [pageToken] ListRegionOperationsRequest pageToken + * @property {string|null} [project] ListRegionOperationsRequest project + * @property {string|null} [region] ListRegionOperationsRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionOperationsRequest returnPartialSuccess */ /** - * Constructs a new ListRegionSecurityPoliciesRequest. + * Constructs a new ListRegionOperationsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionSecurityPoliciesRequest. - * @implements IListRegionSecurityPoliciesRequest + * @classdesc Represents a ListRegionOperationsRequest. + * @implements IListRegionOperationsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionSecurityPoliciesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionOperationsRequest=} [properties] Properties to set */ - function ListRegionSecurityPoliciesRequest(properties) { + function ListRegionOperationsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1011697,116 +1022916,116 @@ } /** - * ListRegionSecurityPoliciesRequest filter. + * ListRegionOperationsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @instance */ - ListRegionSecurityPoliciesRequest.prototype.filter = null; + ListRegionOperationsRequest.prototype.filter = null; /** - * ListRegionSecurityPoliciesRequest maxResults. + * ListRegionOperationsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @instance */ - ListRegionSecurityPoliciesRequest.prototype.maxResults = null; + ListRegionOperationsRequest.prototype.maxResults = null; /** - * ListRegionSecurityPoliciesRequest orderBy. + * ListRegionOperationsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @instance */ - ListRegionSecurityPoliciesRequest.prototype.orderBy = null; + ListRegionOperationsRequest.prototype.orderBy = null; /** - * ListRegionSecurityPoliciesRequest pageToken. + * ListRegionOperationsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @instance */ - ListRegionSecurityPoliciesRequest.prototype.pageToken = null; + ListRegionOperationsRequest.prototype.pageToken = null; /** - * ListRegionSecurityPoliciesRequest project. + * ListRegionOperationsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @instance */ - ListRegionSecurityPoliciesRequest.prototype.project = ""; + ListRegionOperationsRequest.prototype.project = ""; /** - * ListRegionSecurityPoliciesRequest region. + * ListRegionOperationsRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @instance */ - ListRegionSecurityPoliciesRequest.prototype.region = ""; + ListRegionOperationsRequest.prototype.region = ""; /** - * ListRegionSecurityPoliciesRequest returnPartialSuccess. + * ListRegionOperationsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @instance */ - ListRegionSecurityPoliciesRequest.prototype.returnPartialSuccess = null; + ListRegionOperationsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionOperationsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionOperationsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionOperationsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionOperationsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionOperationsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionSecurityPoliciesRequest instance using the specified properties. + * Creates a new ListRegionOperationsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSecurityPoliciesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} ListRegionSecurityPoliciesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionOperationsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionOperationsRequest} ListRegionOperationsRequest instance */ - ListRegionSecurityPoliciesRequest.create = function create(properties) { - return new ListRegionSecurityPoliciesRequest(properties); + ListRegionOperationsRequest.create = function create(properties) { + return new ListRegionOperationsRequest(properties); }; /** - * Encodes the specified ListRegionSecurityPoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest.verify|verify} messages. + * Encodes the specified ListRegionOperationsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionOperationsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSecurityPoliciesRequest} message ListRegionSecurityPoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionOperationsRequest} message ListRegionOperationsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionSecurityPoliciesRequest.encode = function encode(message, writer) { + ListRegionOperationsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1011827,33 +1023046,33 @@ }; /** - * Encodes the specified ListRegionSecurityPoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest.verify|verify} messages. + * Encodes the specified ListRegionOperationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionOperationsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSecurityPoliciesRequest} message ListRegionSecurityPoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionOperationsRequest} message ListRegionOperationsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionSecurityPoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionOperationsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionSecurityPoliciesRequest message from the specified reader or buffer. + * Decodes a ListRegionOperationsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} ListRegionSecurityPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionOperationsRequest} ListRegionOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionSecurityPoliciesRequest.decode = function decode(reader, length, error) { + ListRegionOperationsRequest.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.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionOperationsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1011896,30 +1023115,30 @@ }; /** - * Decodes a ListRegionSecurityPoliciesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionOperationsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} ListRegionSecurityPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionOperationsRequest} ListRegionOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionSecurityPoliciesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionOperationsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionSecurityPoliciesRequest message. + * Verifies a ListRegionOperationsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionSecurityPoliciesRequest.verify = function verify(message) { + ListRegionOperationsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1011958,17 +1023177,17 @@ }; /** - * Creates a ListRegionSecurityPoliciesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionOperationsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} ListRegionSecurityPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionOperationsRequest} ListRegionOperationsRequest */ - ListRegionSecurityPoliciesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest) + ListRegionOperationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionOperationsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionOperationsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1011987,15 +1023206,15 @@ }; /** - * Creates a plain object from a ListRegionSecurityPoliciesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionOperationsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} message ListRegionSecurityPoliciesRequest + * @param {google.cloud.compute.v1beta.ListRegionOperationsRequest} message ListRegionOperationsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionSecurityPoliciesRequest.toObject = function toObject(message, options) { + ListRegionOperationsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1012036,58 +1023255,58 @@ }; /** - * Converts this ListRegionSecurityPoliciesRequest to JSON. + * Converts this ListRegionOperationsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @instance * @returns {Object.} JSON object */ - ListRegionSecurityPoliciesRequest.prototype.toJSON = function toJSON() { + ListRegionOperationsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionSecurityPoliciesRequest + * Gets the default type url for ListRegionOperationsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionOperationsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionSecurityPoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionOperationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionOperationsRequest"; }; - return ListRegionSecurityPoliciesRequest; + return ListRegionOperationsRequest; })(); - v1beta.ListRegionSnapshotsRequest = (function() { + v1beta.ListRegionSecurityPoliciesRequest = (function() { /** - * Properties of a ListRegionSnapshotsRequest. + * Properties of a ListRegionSecurityPoliciesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionSnapshotsRequest - * @property {string|null} [filter] ListRegionSnapshotsRequest filter - * @property {number|null} [maxResults] ListRegionSnapshotsRequest maxResults - * @property {string|null} [orderBy] ListRegionSnapshotsRequest orderBy - * @property {string|null} [pageToken] ListRegionSnapshotsRequest pageToken - * @property {string|null} [project] ListRegionSnapshotsRequest project - * @property {string|null} [region] ListRegionSnapshotsRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionSnapshotsRequest returnPartialSuccess + * @interface IListRegionSecurityPoliciesRequest + * @property {string|null} [filter] ListRegionSecurityPoliciesRequest filter + * @property {number|null} [maxResults] ListRegionSecurityPoliciesRequest maxResults + * @property {string|null} [orderBy] ListRegionSecurityPoliciesRequest orderBy + * @property {string|null} [pageToken] ListRegionSecurityPoliciesRequest pageToken + * @property {string|null} [project] ListRegionSecurityPoliciesRequest project + * @property {string|null} [region] ListRegionSecurityPoliciesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionSecurityPoliciesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionSnapshotsRequest. + * Constructs a new ListRegionSecurityPoliciesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionSnapshotsRequest. - * @implements IListRegionSnapshotsRequest + * @classdesc Represents a ListRegionSecurityPoliciesRequest. + * @implements IListRegionSecurityPoliciesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionSnapshotsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionSecurityPoliciesRequest=} [properties] Properties to set */ - function ListRegionSnapshotsRequest(properties) { + function ListRegionSecurityPoliciesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1012095,116 +1023314,116 @@ } /** - * ListRegionSnapshotsRequest filter. + * ListRegionSecurityPoliciesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @instance */ - ListRegionSnapshotsRequest.prototype.filter = null; + ListRegionSecurityPoliciesRequest.prototype.filter = null; /** - * ListRegionSnapshotsRequest maxResults. + * ListRegionSecurityPoliciesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @instance */ - ListRegionSnapshotsRequest.prototype.maxResults = null; + ListRegionSecurityPoliciesRequest.prototype.maxResults = null; /** - * ListRegionSnapshotsRequest orderBy. + * ListRegionSecurityPoliciesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @instance */ - ListRegionSnapshotsRequest.prototype.orderBy = null; + ListRegionSecurityPoliciesRequest.prototype.orderBy = null; /** - * ListRegionSnapshotsRequest pageToken. + * ListRegionSecurityPoliciesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @instance */ - ListRegionSnapshotsRequest.prototype.pageToken = null; + ListRegionSecurityPoliciesRequest.prototype.pageToken = null; /** - * ListRegionSnapshotsRequest project. + * ListRegionSecurityPoliciesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @instance */ - ListRegionSnapshotsRequest.prototype.project = ""; + ListRegionSecurityPoliciesRequest.prototype.project = ""; /** - * ListRegionSnapshotsRequest region. + * ListRegionSecurityPoliciesRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @instance */ - ListRegionSnapshotsRequest.prototype.region = ""; + ListRegionSecurityPoliciesRequest.prototype.region = ""; /** - * ListRegionSnapshotsRequest returnPartialSuccess. + * ListRegionSecurityPoliciesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @instance */ - ListRegionSnapshotsRequest.prototype.returnPartialSuccess = null; + ListRegionSecurityPoliciesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_filter", { + Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionSecurityPoliciesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionSnapshotsRequest instance using the specified properties. + * Creates a new ListRegionSecurityPoliciesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSnapshotsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} ListRegionSnapshotsRequest instance + * @param {google.cloud.compute.v1beta.IListRegionSecurityPoliciesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} ListRegionSecurityPoliciesRequest instance */ - ListRegionSnapshotsRequest.create = function create(properties) { - return new ListRegionSnapshotsRequest(properties); + ListRegionSecurityPoliciesRequest.create = function create(properties) { + return new ListRegionSecurityPoliciesRequest(properties); }; /** - * Encodes the specified ListRegionSnapshotsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSnapshotsRequest.verify|verify} messages. + * Encodes the specified ListRegionSecurityPoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSnapshotsRequest} message ListRegionSnapshotsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionSecurityPoliciesRequest} message ListRegionSecurityPoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionSnapshotsRequest.encode = function encode(message, writer) { + ListRegionSecurityPoliciesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1012225,33 +1023444,33 @@ }; /** - * Encodes the specified ListRegionSnapshotsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSnapshotsRequest.verify|verify} messages. + * Encodes the specified ListRegionSecurityPoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSnapshotsRequest} message ListRegionSnapshotsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionSecurityPoliciesRequest} message ListRegionSecurityPoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionSnapshotsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionSecurityPoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionSnapshotsRequest message from the specified reader or buffer. + * Decodes a ListRegionSecurityPoliciesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} ListRegionSnapshotsRequest + * @returns {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} ListRegionSecurityPoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionSnapshotsRequest.decode = function decode(reader, length, error) { + ListRegionSecurityPoliciesRequest.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.cloud.compute.v1beta.ListRegionSnapshotsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1012294,30 +1023513,30 @@ }; /** - * Decodes a ListRegionSnapshotsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionSecurityPoliciesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} ListRegionSnapshotsRequest + * @returns {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} ListRegionSecurityPoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionSnapshotsRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionSecurityPoliciesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionSnapshotsRequest message. + * Verifies a ListRegionSecurityPoliciesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionSnapshotsRequest.verify = function verify(message) { + ListRegionSecurityPoliciesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1012356,17 +1023575,17 @@ }; /** - * Creates a ListRegionSnapshotsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionSecurityPoliciesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} ListRegionSnapshotsRequest + * @returns {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} ListRegionSecurityPoliciesRequest */ - ListRegionSnapshotsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionSnapshotsRequest) + ListRegionSecurityPoliciesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionSnapshotsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1012385,15 +1023604,15 @@ }; /** - * Creates a plain object from a ListRegionSnapshotsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionSecurityPoliciesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} message ListRegionSnapshotsRequest + * @param {google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest} message ListRegionSecurityPoliciesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionSnapshotsRequest.toObject = function toObject(message, options) { + ListRegionSecurityPoliciesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1012434,58 +1023653,58 @@ }; /** - * Converts this ListRegionSnapshotsRequest to JSON. + * Converts this ListRegionSecurityPoliciesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @instance * @returns {Object.} JSON object */ - ListRegionSnapshotsRequest.prototype.toJSON = function toJSON() { + ListRegionSecurityPoliciesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionSnapshotsRequest + * Gets the default type url for ListRegionSecurityPoliciesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest + * @memberof google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionSnapshotsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionSecurityPoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionSnapshotsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionSecurityPoliciesRequest"; }; - return ListRegionSnapshotsRequest; + return ListRegionSecurityPoliciesRequest; })(); - v1beta.ListRegionSslCertificatesRequest = (function() { + v1beta.ListRegionSnapshotsRequest = (function() { /** - * Properties of a ListRegionSslCertificatesRequest. + * Properties of a ListRegionSnapshotsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionSslCertificatesRequest - * @property {string|null} [filter] ListRegionSslCertificatesRequest filter - * @property {number|null} [maxResults] ListRegionSslCertificatesRequest maxResults - * @property {string|null} [orderBy] ListRegionSslCertificatesRequest orderBy - * @property {string|null} [pageToken] ListRegionSslCertificatesRequest pageToken - * @property {string|null} [project] ListRegionSslCertificatesRequest project - * @property {string|null} [region] ListRegionSslCertificatesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionSslCertificatesRequest returnPartialSuccess + * @interface IListRegionSnapshotsRequest + * @property {string|null} [filter] ListRegionSnapshotsRequest filter + * @property {number|null} [maxResults] ListRegionSnapshotsRequest maxResults + * @property {string|null} [orderBy] ListRegionSnapshotsRequest orderBy + * @property {string|null} [pageToken] ListRegionSnapshotsRequest pageToken + * @property {string|null} [project] ListRegionSnapshotsRequest project + * @property {string|null} [region] ListRegionSnapshotsRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionSnapshotsRequest returnPartialSuccess */ /** - * Constructs a new ListRegionSslCertificatesRequest. + * Constructs a new ListRegionSnapshotsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionSslCertificatesRequest. - * @implements IListRegionSslCertificatesRequest + * @classdesc Represents a ListRegionSnapshotsRequest. + * @implements IListRegionSnapshotsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionSslCertificatesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionSnapshotsRequest=} [properties] Properties to set */ - function ListRegionSslCertificatesRequest(properties) { + function ListRegionSnapshotsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1012493,116 +1023712,116 @@ } /** - * ListRegionSslCertificatesRequest filter. + * ListRegionSnapshotsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @instance */ - ListRegionSslCertificatesRequest.prototype.filter = null; + ListRegionSnapshotsRequest.prototype.filter = null; /** - * ListRegionSslCertificatesRequest maxResults. + * ListRegionSnapshotsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @instance */ - ListRegionSslCertificatesRequest.prototype.maxResults = null; + ListRegionSnapshotsRequest.prototype.maxResults = null; /** - * ListRegionSslCertificatesRequest orderBy. + * ListRegionSnapshotsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @instance */ - ListRegionSslCertificatesRequest.prototype.orderBy = null; + ListRegionSnapshotsRequest.prototype.orderBy = null; /** - * ListRegionSslCertificatesRequest pageToken. + * ListRegionSnapshotsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @instance */ - ListRegionSslCertificatesRequest.prototype.pageToken = null; + ListRegionSnapshotsRequest.prototype.pageToken = null; /** - * ListRegionSslCertificatesRequest project. + * ListRegionSnapshotsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @instance */ - ListRegionSslCertificatesRequest.prototype.project = ""; + ListRegionSnapshotsRequest.prototype.project = ""; /** - * ListRegionSslCertificatesRequest region. + * ListRegionSnapshotsRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @instance */ - ListRegionSslCertificatesRequest.prototype.region = ""; + ListRegionSnapshotsRequest.prototype.region = ""; /** - * ListRegionSslCertificatesRequest returnPartialSuccess. + * ListRegionSnapshotsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @instance */ - ListRegionSslCertificatesRequest.prototype.returnPartialSuccess = null; + ListRegionSnapshotsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionSnapshotsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionSslCertificatesRequest instance using the specified properties. + * Creates a new ListRegionSnapshotsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSslCertificatesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} ListRegionSslCertificatesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionSnapshotsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} ListRegionSnapshotsRequest instance */ - ListRegionSslCertificatesRequest.create = function create(properties) { - return new ListRegionSslCertificatesRequest(properties); + ListRegionSnapshotsRequest.create = function create(properties) { + return new ListRegionSnapshotsRequest(properties); }; /** - * Encodes the specified ListRegionSslCertificatesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSslCertificatesRequest.verify|verify} messages. + * Encodes the specified ListRegionSnapshotsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSnapshotsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSslCertificatesRequest} message ListRegionSslCertificatesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionSnapshotsRequest} message ListRegionSnapshotsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionSslCertificatesRequest.encode = function encode(message, writer) { + ListRegionSnapshotsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1012623,33 +1023842,33 @@ }; /** - * Encodes the specified ListRegionSslCertificatesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSslCertificatesRequest.verify|verify} messages. + * Encodes the specified ListRegionSnapshotsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSnapshotsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSslCertificatesRequest} message ListRegionSslCertificatesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionSnapshotsRequest} message ListRegionSnapshotsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionSslCertificatesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionSnapshotsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionSslCertificatesRequest message from the specified reader or buffer. + * Decodes a ListRegionSnapshotsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} ListRegionSslCertificatesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} ListRegionSnapshotsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionSslCertificatesRequest.decode = function decode(reader, length, error) { + ListRegionSnapshotsRequest.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.cloud.compute.v1beta.ListRegionSslCertificatesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionSnapshotsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1012692,30 +1023911,30 @@ }; /** - * Decodes a ListRegionSslCertificatesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionSnapshotsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} ListRegionSslCertificatesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} ListRegionSnapshotsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionSslCertificatesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionSnapshotsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionSslCertificatesRequest message. + * Verifies a ListRegionSnapshotsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionSslCertificatesRequest.verify = function verify(message) { + ListRegionSnapshotsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1012754,17 +1023973,17 @@ }; /** - * Creates a ListRegionSslCertificatesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionSnapshotsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} ListRegionSslCertificatesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} ListRegionSnapshotsRequest */ - ListRegionSslCertificatesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionSslCertificatesRequest) + ListRegionSnapshotsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionSnapshotsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionSslCertificatesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionSnapshotsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1012783,15 +1024002,15 @@ }; /** - * Creates a plain object from a ListRegionSslCertificatesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionSnapshotsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} message ListRegionSslCertificatesRequest + * @param {google.cloud.compute.v1beta.ListRegionSnapshotsRequest} message ListRegionSnapshotsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionSslCertificatesRequest.toObject = function toObject(message, options) { + ListRegionSnapshotsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1012832,58 +1024051,58 @@ }; /** - * Converts this ListRegionSslCertificatesRequest to JSON. + * Converts this ListRegionSnapshotsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @instance * @returns {Object.} JSON object */ - ListRegionSslCertificatesRequest.prototype.toJSON = function toJSON() { + ListRegionSnapshotsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionSslCertificatesRequest + * Gets the default type url for ListRegionSnapshotsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSnapshotsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionSslCertificatesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionSnapshotsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionSslCertificatesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionSnapshotsRequest"; }; - return ListRegionSslCertificatesRequest; + return ListRegionSnapshotsRequest; })(); - v1beta.ListRegionSslPoliciesRequest = (function() { + v1beta.ListRegionSslCertificatesRequest = (function() { /** - * Properties of a ListRegionSslPoliciesRequest. + * Properties of a ListRegionSslCertificatesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionSslPoliciesRequest - * @property {string|null} [filter] ListRegionSslPoliciesRequest filter - * @property {number|null} [maxResults] ListRegionSslPoliciesRequest maxResults - * @property {string|null} [orderBy] ListRegionSslPoliciesRequest orderBy - * @property {string|null} [pageToken] ListRegionSslPoliciesRequest pageToken - * @property {string|null} [project] ListRegionSslPoliciesRequest project - * @property {string|null} [region] ListRegionSslPoliciesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionSslPoliciesRequest returnPartialSuccess + * @interface IListRegionSslCertificatesRequest + * @property {string|null} [filter] ListRegionSslCertificatesRequest filter + * @property {number|null} [maxResults] ListRegionSslCertificatesRequest maxResults + * @property {string|null} [orderBy] ListRegionSslCertificatesRequest orderBy + * @property {string|null} [pageToken] ListRegionSslCertificatesRequest pageToken + * @property {string|null} [project] ListRegionSslCertificatesRequest project + * @property {string|null} [region] ListRegionSslCertificatesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionSslCertificatesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionSslPoliciesRequest. + * Constructs a new ListRegionSslCertificatesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionSslPoliciesRequest. - * @implements IListRegionSslPoliciesRequest + * @classdesc Represents a ListRegionSslCertificatesRequest. + * @implements IListRegionSslCertificatesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionSslPoliciesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionSslCertificatesRequest=} [properties] Properties to set */ - function ListRegionSslPoliciesRequest(properties) { + function ListRegionSslCertificatesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1012891,116 +1024110,116 @@ } /** - * ListRegionSslPoliciesRequest filter. + * ListRegionSslCertificatesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @instance */ - ListRegionSslPoliciesRequest.prototype.filter = null; + ListRegionSslCertificatesRequest.prototype.filter = null; /** - * ListRegionSslPoliciesRequest maxResults. + * ListRegionSslCertificatesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @instance */ - ListRegionSslPoliciesRequest.prototype.maxResults = null; + ListRegionSslCertificatesRequest.prototype.maxResults = null; /** - * ListRegionSslPoliciesRequest orderBy. + * ListRegionSslCertificatesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @instance */ - ListRegionSslPoliciesRequest.prototype.orderBy = null; + ListRegionSslCertificatesRequest.prototype.orderBy = null; /** - * ListRegionSslPoliciesRequest pageToken. + * ListRegionSslCertificatesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @instance */ - ListRegionSslPoliciesRequest.prototype.pageToken = null; + ListRegionSslCertificatesRequest.prototype.pageToken = null; /** - * ListRegionSslPoliciesRequest project. + * ListRegionSslCertificatesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @instance */ - ListRegionSslPoliciesRequest.prototype.project = ""; + ListRegionSslCertificatesRequest.prototype.project = ""; /** - * ListRegionSslPoliciesRequest region. + * ListRegionSslCertificatesRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @instance */ - ListRegionSslPoliciesRequest.prototype.region = ""; + ListRegionSslCertificatesRequest.prototype.region = ""; /** - * ListRegionSslPoliciesRequest returnPartialSuccess. + * ListRegionSslCertificatesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @instance */ - ListRegionSslPoliciesRequest.prototype.returnPartialSuccess = null; + ListRegionSslCertificatesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionSslCertificatesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionSslPoliciesRequest instance using the specified properties. + * Creates a new ListRegionSslCertificatesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSslPoliciesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} ListRegionSslPoliciesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionSslCertificatesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} ListRegionSslCertificatesRequest instance */ - ListRegionSslPoliciesRequest.create = function create(properties) { - return new ListRegionSslPoliciesRequest(properties); + ListRegionSslCertificatesRequest.create = function create(properties) { + return new ListRegionSslCertificatesRequest(properties); }; /** - * Encodes the specified ListRegionSslPoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSslPoliciesRequest.verify|verify} messages. + * Encodes the specified ListRegionSslCertificatesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSslCertificatesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSslPoliciesRequest} message ListRegionSslPoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionSslCertificatesRequest} message ListRegionSslCertificatesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionSslPoliciesRequest.encode = function encode(message, writer) { + ListRegionSslCertificatesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1013021,33 +1024240,33 @@ }; /** - * Encodes the specified ListRegionSslPoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSslPoliciesRequest.verify|verify} messages. + * Encodes the specified ListRegionSslCertificatesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSslCertificatesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionSslPoliciesRequest} message ListRegionSslPoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionSslCertificatesRequest} message ListRegionSslCertificatesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionSslPoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionSslCertificatesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionSslPoliciesRequest message from the specified reader or buffer. + * Decodes a ListRegionSslCertificatesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} ListRegionSslPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} ListRegionSslCertificatesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionSslPoliciesRequest.decode = function decode(reader, length, error) { + ListRegionSslCertificatesRequest.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.cloud.compute.v1beta.ListRegionSslPoliciesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionSslCertificatesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1013090,30 +1024309,30 @@ }; /** - * Decodes a ListRegionSslPoliciesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionSslCertificatesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} ListRegionSslPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} ListRegionSslCertificatesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionSslPoliciesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionSslCertificatesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionSslPoliciesRequest message. + * Verifies a ListRegionSslCertificatesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionSslPoliciesRequest.verify = function verify(message) { + ListRegionSslCertificatesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1013152,17 +1024371,17 @@ }; /** - * Creates a ListRegionSslPoliciesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionSslCertificatesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} ListRegionSslPoliciesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} ListRegionSslCertificatesRequest */ - ListRegionSslPoliciesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionSslPoliciesRequest) + ListRegionSslCertificatesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionSslCertificatesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionSslPoliciesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionSslCertificatesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1013181,15 +1024400,15 @@ }; /** - * Creates a plain object from a ListRegionSslPoliciesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionSslCertificatesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} message ListRegionSslPoliciesRequest + * @param {google.cloud.compute.v1beta.ListRegionSslCertificatesRequest} message ListRegionSslCertificatesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionSslPoliciesRequest.toObject = function toObject(message, options) { + ListRegionSslCertificatesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1013230,58 +1024449,58 @@ }; /** - * Converts this ListRegionSslPoliciesRequest to JSON. + * Converts this ListRegionSslCertificatesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @instance * @returns {Object.} JSON object */ - ListRegionSslPoliciesRequest.prototype.toJSON = function toJSON() { + ListRegionSslCertificatesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionSslPoliciesRequest + * Gets the default type url for ListRegionSslCertificatesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslCertificatesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionSslPoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionSslCertificatesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionSslPoliciesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionSslCertificatesRequest"; }; - return ListRegionSslPoliciesRequest; + return ListRegionSslCertificatesRequest; })(); - v1beta.ListRegionTargetHttpProxiesRequest = (function() { + v1beta.ListRegionSslPoliciesRequest = (function() { /** - * Properties of a ListRegionTargetHttpProxiesRequest. + * Properties of a ListRegionSslPoliciesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionTargetHttpProxiesRequest - * @property {string|null} [filter] ListRegionTargetHttpProxiesRequest filter - * @property {number|null} [maxResults] ListRegionTargetHttpProxiesRequest maxResults - * @property {string|null} [orderBy] ListRegionTargetHttpProxiesRequest orderBy - * @property {string|null} [pageToken] ListRegionTargetHttpProxiesRequest pageToken - * @property {string|null} [project] ListRegionTargetHttpProxiesRequest project - * @property {string|null} [region] ListRegionTargetHttpProxiesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionTargetHttpProxiesRequest returnPartialSuccess + * @interface IListRegionSslPoliciesRequest + * @property {string|null} [filter] ListRegionSslPoliciesRequest filter + * @property {number|null} [maxResults] ListRegionSslPoliciesRequest maxResults + * @property {string|null} [orderBy] ListRegionSslPoliciesRequest orderBy + * @property {string|null} [pageToken] ListRegionSslPoliciesRequest pageToken + * @property {string|null} [project] ListRegionSslPoliciesRequest project + * @property {string|null} [region] ListRegionSslPoliciesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionSslPoliciesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionTargetHttpProxiesRequest. + * Constructs a new ListRegionSslPoliciesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionTargetHttpProxiesRequest. - * @implements IListRegionTargetHttpProxiesRequest + * @classdesc Represents a ListRegionSslPoliciesRequest. + * @implements IListRegionSslPoliciesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionTargetHttpProxiesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionSslPoliciesRequest=} [properties] Properties to set */ - function ListRegionTargetHttpProxiesRequest(properties) { + function ListRegionSslPoliciesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1013289,116 +1024508,116 @@ } /** - * ListRegionTargetHttpProxiesRequest filter. + * ListRegionSslPoliciesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @instance */ - ListRegionTargetHttpProxiesRequest.prototype.filter = null; + ListRegionSslPoliciesRequest.prototype.filter = null; /** - * ListRegionTargetHttpProxiesRequest maxResults. + * ListRegionSslPoliciesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @instance */ - ListRegionTargetHttpProxiesRequest.prototype.maxResults = null; + ListRegionSslPoliciesRequest.prototype.maxResults = null; /** - * ListRegionTargetHttpProxiesRequest orderBy. + * ListRegionSslPoliciesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @instance */ - ListRegionTargetHttpProxiesRequest.prototype.orderBy = null; + ListRegionSslPoliciesRequest.prototype.orderBy = null; /** - * ListRegionTargetHttpProxiesRequest pageToken. + * ListRegionSslPoliciesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @instance */ - ListRegionTargetHttpProxiesRequest.prototype.pageToken = null; + ListRegionSslPoliciesRequest.prototype.pageToken = null; /** - * ListRegionTargetHttpProxiesRequest project. + * ListRegionSslPoliciesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @instance */ - ListRegionTargetHttpProxiesRequest.prototype.project = ""; + ListRegionSslPoliciesRequest.prototype.project = ""; /** - * ListRegionTargetHttpProxiesRequest region. + * ListRegionSslPoliciesRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @instance */ - ListRegionTargetHttpProxiesRequest.prototype.region = ""; + ListRegionSslPoliciesRequest.prototype.region = ""; /** - * ListRegionTargetHttpProxiesRequest returnPartialSuccess. + * ListRegionSslPoliciesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @instance */ - ListRegionTargetHttpProxiesRequest.prototype.returnPartialSuccess = null; + ListRegionSslPoliciesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionSslPoliciesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionTargetHttpProxiesRequest instance using the specified properties. + * Creates a new ListRegionSslPoliciesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetHttpProxiesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} ListRegionTargetHttpProxiesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionSslPoliciesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} ListRegionSslPoliciesRequest instance */ - ListRegionTargetHttpProxiesRequest.create = function create(properties) { - return new ListRegionTargetHttpProxiesRequest(properties); + ListRegionSslPoliciesRequest.create = function create(properties) { + return new ListRegionSslPoliciesRequest(properties); }; /** - * Encodes the specified ListRegionTargetHttpProxiesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest.verify|verify} messages. + * Encodes the specified ListRegionSslPoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSslPoliciesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetHttpProxiesRequest} message ListRegionTargetHttpProxiesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionSslPoliciesRequest} message ListRegionSslPoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionTargetHttpProxiesRequest.encode = function encode(message, writer) { + ListRegionSslPoliciesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1013419,33 +1024638,33 @@ }; /** - * Encodes the specified ListRegionTargetHttpProxiesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest.verify|verify} messages. + * Encodes the specified ListRegionSslPoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionSslPoliciesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetHttpProxiesRequest} message ListRegionTargetHttpProxiesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionSslPoliciesRequest} message ListRegionSslPoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionTargetHttpProxiesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionSslPoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionTargetHttpProxiesRequest message from the specified reader or buffer. + * Decodes a ListRegionSslPoliciesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} ListRegionTargetHttpProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} ListRegionSslPoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionTargetHttpProxiesRequest.decode = function decode(reader, length, error) { + ListRegionSslPoliciesRequest.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.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionSslPoliciesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1013488,30 +1024707,30 @@ }; /** - * Decodes a ListRegionTargetHttpProxiesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionSslPoliciesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} ListRegionTargetHttpProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} ListRegionSslPoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionTargetHttpProxiesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionSslPoliciesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionTargetHttpProxiesRequest message. + * Verifies a ListRegionSslPoliciesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionTargetHttpProxiesRequest.verify = function verify(message) { + ListRegionSslPoliciesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1013550,17 +1024769,17 @@ }; /** - * Creates a ListRegionTargetHttpProxiesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionSslPoliciesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} ListRegionTargetHttpProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} ListRegionSslPoliciesRequest */ - ListRegionTargetHttpProxiesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest) + ListRegionSslPoliciesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionSslPoliciesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionSslPoliciesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1013579,15 +1024798,15 @@ }; /** - * Creates a plain object from a ListRegionTargetHttpProxiesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionSslPoliciesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} message ListRegionTargetHttpProxiesRequest + * @param {google.cloud.compute.v1beta.ListRegionSslPoliciesRequest} message ListRegionSslPoliciesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionTargetHttpProxiesRequest.toObject = function toObject(message, options) { + ListRegionSslPoliciesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1013628,58 +1024847,58 @@ }; /** - * Converts this ListRegionTargetHttpProxiesRequest to JSON. + * Converts this ListRegionSslPoliciesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @instance * @returns {Object.} JSON object */ - ListRegionTargetHttpProxiesRequest.prototype.toJSON = function toJSON() { + ListRegionSslPoliciesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionTargetHttpProxiesRequest + * Gets the default type url for ListRegionSslPoliciesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionSslPoliciesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionTargetHttpProxiesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionSslPoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionSslPoliciesRequest"; }; - return ListRegionTargetHttpProxiesRequest; + return ListRegionSslPoliciesRequest; })(); - v1beta.ListRegionTargetHttpsProxiesRequest = (function() { + v1beta.ListRegionTargetHttpProxiesRequest = (function() { /** - * Properties of a ListRegionTargetHttpsProxiesRequest. + * Properties of a ListRegionTargetHttpProxiesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionTargetHttpsProxiesRequest - * @property {string|null} [filter] ListRegionTargetHttpsProxiesRequest filter - * @property {number|null} [maxResults] ListRegionTargetHttpsProxiesRequest maxResults - * @property {string|null} [orderBy] ListRegionTargetHttpsProxiesRequest orderBy - * @property {string|null} [pageToken] ListRegionTargetHttpsProxiesRequest pageToken - * @property {string|null} [project] ListRegionTargetHttpsProxiesRequest project - * @property {string|null} [region] ListRegionTargetHttpsProxiesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionTargetHttpsProxiesRequest returnPartialSuccess + * @interface IListRegionTargetHttpProxiesRequest + * @property {string|null} [filter] ListRegionTargetHttpProxiesRequest filter + * @property {number|null} [maxResults] ListRegionTargetHttpProxiesRequest maxResults + * @property {string|null} [orderBy] ListRegionTargetHttpProxiesRequest orderBy + * @property {string|null} [pageToken] ListRegionTargetHttpProxiesRequest pageToken + * @property {string|null} [project] ListRegionTargetHttpProxiesRequest project + * @property {string|null} [region] ListRegionTargetHttpProxiesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionTargetHttpProxiesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionTargetHttpsProxiesRequest. + * Constructs a new ListRegionTargetHttpProxiesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionTargetHttpsProxiesRequest. - * @implements IListRegionTargetHttpsProxiesRequest + * @classdesc Represents a ListRegionTargetHttpProxiesRequest. + * @implements IListRegionTargetHttpProxiesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionTargetHttpsProxiesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionTargetHttpProxiesRequest=} [properties] Properties to set */ - function ListRegionTargetHttpsProxiesRequest(properties) { + function ListRegionTargetHttpProxiesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1013687,116 +1024906,116 @@ } /** - * ListRegionTargetHttpsProxiesRequest filter. + * ListRegionTargetHttpProxiesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @instance */ - ListRegionTargetHttpsProxiesRequest.prototype.filter = null; + ListRegionTargetHttpProxiesRequest.prototype.filter = null; /** - * ListRegionTargetHttpsProxiesRequest maxResults. + * ListRegionTargetHttpProxiesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @instance */ - ListRegionTargetHttpsProxiesRequest.prototype.maxResults = null; + ListRegionTargetHttpProxiesRequest.prototype.maxResults = null; /** - * ListRegionTargetHttpsProxiesRequest orderBy. + * ListRegionTargetHttpProxiesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @instance */ - ListRegionTargetHttpsProxiesRequest.prototype.orderBy = null; + ListRegionTargetHttpProxiesRequest.prototype.orderBy = null; /** - * ListRegionTargetHttpsProxiesRequest pageToken. + * ListRegionTargetHttpProxiesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @instance */ - ListRegionTargetHttpsProxiesRequest.prototype.pageToken = null; + ListRegionTargetHttpProxiesRequest.prototype.pageToken = null; /** - * ListRegionTargetHttpsProxiesRequest project. + * ListRegionTargetHttpProxiesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @instance */ - ListRegionTargetHttpsProxiesRequest.prototype.project = ""; + ListRegionTargetHttpProxiesRequest.prototype.project = ""; /** - * ListRegionTargetHttpsProxiesRequest region. + * ListRegionTargetHttpProxiesRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @instance */ - ListRegionTargetHttpsProxiesRequest.prototype.region = ""; + ListRegionTargetHttpProxiesRequest.prototype.region = ""; /** - * ListRegionTargetHttpsProxiesRequest returnPartialSuccess. + * ListRegionTargetHttpProxiesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @instance */ - ListRegionTargetHttpsProxiesRequest.prototype.returnPartialSuccess = null; + ListRegionTargetHttpProxiesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionTargetHttpProxiesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionTargetHttpsProxiesRequest instance using the specified properties. + * Creates a new ListRegionTargetHttpProxiesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetHttpsProxiesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} ListRegionTargetHttpsProxiesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionTargetHttpProxiesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} ListRegionTargetHttpProxiesRequest instance */ - ListRegionTargetHttpsProxiesRequest.create = function create(properties) { - return new ListRegionTargetHttpsProxiesRequest(properties); + ListRegionTargetHttpProxiesRequest.create = function create(properties) { + return new ListRegionTargetHttpProxiesRequest(properties); }; /** - * Encodes the specified ListRegionTargetHttpsProxiesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest.verify|verify} messages. + * Encodes the specified ListRegionTargetHttpProxiesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetHttpsProxiesRequest} message ListRegionTargetHttpsProxiesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionTargetHttpProxiesRequest} message ListRegionTargetHttpProxiesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionTargetHttpsProxiesRequest.encode = function encode(message, writer) { + ListRegionTargetHttpProxiesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1013817,33 +1025036,33 @@ }; /** - * Encodes the specified ListRegionTargetHttpsProxiesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest.verify|verify} messages. + * Encodes the specified ListRegionTargetHttpProxiesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetHttpsProxiesRequest} message ListRegionTargetHttpsProxiesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionTargetHttpProxiesRequest} message ListRegionTargetHttpProxiesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionTargetHttpsProxiesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionTargetHttpProxiesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionTargetHttpsProxiesRequest message from the specified reader or buffer. + * Decodes a ListRegionTargetHttpProxiesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} ListRegionTargetHttpsProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} ListRegionTargetHttpProxiesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionTargetHttpsProxiesRequest.decode = function decode(reader, length, error) { + ListRegionTargetHttpProxiesRequest.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.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1013886,30 +1025105,30 @@ }; /** - * Decodes a ListRegionTargetHttpsProxiesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionTargetHttpProxiesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} ListRegionTargetHttpsProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} ListRegionTargetHttpProxiesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionTargetHttpsProxiesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionTargetHttpProxiesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionTargetHttpsProxiesRequest message. + * Verifies a ListRegionTargetHttpProxiesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionTargetHttpsProxiesRequest.verify = function verify(message) { + ListRegionTargetHttpProxiesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1013948,17 +1025167,17 @@ }; /** - * Creates a ListRegionTargetHttpsProxiesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionTargetHttpProxiesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} ListRegionTargetHttpsProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} ListRegionTargetHttpProxiesRequest */ - ListRegionTargetHttpsProxiesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest) + ListRegionTargetHttpProxiesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1013977,15 +1025196,15 @@ }; /** - * Creates a plain object from a ListRegionTargetHttpsProxiesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionTargetHttpProxiesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} message ListRegionTargetHttpsProxiesRequest + * @param {google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest} message ListRegionTargetHttpProxiesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionTargetHttpsProxiesRequest.toObject = function toObject(message, options) { + ListRegionTargetHttpProxiesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1014026,58 +1025245,58 @@ }; /** - * Converts this ListRegionTargetHttpsProxiesRequest to JSON. + * Converts this ListRegionTargetHttpProxiesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @instance * @returns {Object.} JSON object */ - ListRegionTargetHttpsProxiesRequest.prototype.toJSON = function toJSON() { + ListRegionTargetHttpProxiesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionTargetHttpsProxiesRequest + * Gets the default type url for ListRegionTargetHttpProxiesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionTargetHttpsProxiesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionTargetHttpProxiesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionTargetHttpProxiesRequest"; }; - return ListRegionTargetHttpsProxiesRequest; + return ListRegionTargetHttpProxiesRequest; })(); - v1beta.ListRegionTargetTcpProxiesRequest = (function() { + v1beta.ListRegionTargetHttpsProxiesRequest = (function() { /** - * Properties of a ListRegionTargetTcpProxiesRequest. + * Properties of a ListRegionTargetHttpsProxiesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionTargetTcpProxiesRequest - * @property {string|null} [filter] ListRegionTargetTcpProxiesRequest filter - * @property {number|null} [maxResults] ListRegionTargetTcpProxiesRequest maxResults - * @property {string|null} [orderBy] ListRegionTargetTcpProxiesRequest orderBy - * @property {string|null} [pageToken] ListRegionTargetTcpProxiesRequest pageToken - * @property {string|null} [project] ListRegionTargetTcpProxiesRequest project - * @property {string|null} [region] ListRegionTargetTcpProxiesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionTargetTcpProxiesRequest returnPartialSuccess + * @interface IListRegionTargetHttpsProxiesRequest + * @property {string|null} [filter] ListRegionTargetHttpsProxiesRequest filter + * @property {number|null} [maxResults] ListRegionTargetHttpsProxiesRequest maxResults + * @property {string|null} [orderBy] ListRegionTargetHttpsProxiesRequest orderBy + * @property {string|null} [pageToken] ListRegionTargetHttpsProxiesRequest pageToken + * @property {string|null} [project] ListRegionTargetHttpsProxiesRequest project + * @property {string|null} [region] ListRegionTargetHttpsProxiesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionTargetHttpsProxiesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionTargetTcpProxiesRequest. + * Constructs a new ListRegionTargetHttpsProxiesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionTargetTcpProxiesRequest. - * @implements IListRegionTargetTcpProxiesRequest + * @classdesc Represents a ListRegionTargetHttpsProxiesRequest. + * @implements IListRegionTargetHttpsProxiesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionTargetTcpProxiesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionTargetHttpsProxiesRequest=} [properties] Properties to set */ - function ListRegionTargetTcpProxiesRequest(properties) { + function ListRegionTargetHttpsProxiesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1014085,116 +1025304,116 @@ } /** - * ListRegionTargetTcpProxiesRequest filter. + * ListRegionTargetHttpsProxiesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @instance */ - ListRegionTargetTcpProxiesRequest.prototype.filter = null; + ListRegionTargetHttpsProxiesRequest.prototype.filter = null; /** - * ListRegionTargetTcpProxiesRequest maxResults. + * ListRegionTargetHttpsProxiesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @instance */ - ListRegionTargetTcpProxiesRequest.prototype.maxResults = null; + ListRegionTargetHttpsProxiesRequest.prototype.maxResults = null; /** - * ListRegionTargetTcpProxiesRequest orderBy. + * ListRegionTargetHttpsProxiesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @instance */ - ListRegionTargetTcpProxiesRequest.prototype.orderBy = null; + ListRegionTargetHttpsProxiesRequest.prototype.orderBy = null; /** - * ListRegionTargetTcpProxiesRequest pageToken. + * ListRegionTargetHttpsProxiesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @instance */ - ListRegionTargetTcpProxiesRequest.prototype.pageToken = null; + ListRegionTargetHttpsProxiesRequest.prototype.pageToken = null; /** - * ListRegionTargetTcpProxiesRequest project. + * ListRegionTargetHttpsProxiesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @instance */ - ListRegionTargetTcpProxiesRequest.prototype.project = ""; + ListRegionTargetHttpsProxiesRequest.prototype.project = ""; /** - * ListRegionTargetTcpProxiesRequest region. + * ListRegionTargetHttpsProxiesRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @instance */ - ListRegionTargetTcpProxiesRequest.prototype.region = ""; + ListRegionTargetHttpsProxiesRequest.prototype.region = ""; /** - * ListRegionTargetTcpProxiesRequest returnPartialSuccess. + * ListRegionTargetHttpsProxiesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @instance */ - ListRegionTargetTcpProxiesRequest.prototype.returnPartialSuccess = null; + ListRegionTargetHttpsProxiesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionTargetHttpsProxiesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionTargetTcpProxiesRequest instance using the specified properties. + * Creates a new ListRegionTargetHttpsProxiesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetTcpProxiesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} ListRegionTargetTcpProxiesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionTargetHttpsProxiesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} ListRegionTargetHttpsProxiesRequest instance */ - ListRegionTargetTcpProxiesRequest.create = function create(properties) { - return new ListRegionTargetTcpProxiesRequest(properties); + ListRegionTargetHttpsProxiesRequest.create = function create(properties) { + return new ListRegionTargetHttpsProxiesRequest(properties); }; /** - * Encodes the specified ListRegionTargetTcpProxiesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest.verify|verify} messages. + * Encodes the specified ListRegionTargetHttpsProxiesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetTcpProxiesRequest} message ListRegionTargetTcpProxiesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionTargetHttpsProxiesRequest} message ListRegionTargetHttpsProxiesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionTargetTcpProxiesRequest.encode = function encode(message, writer) { + ListRegionTargetHttpsProxiesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1014215,33 +1025434,33 @@ }; /** - * Encodes the specified ListRegionTargetTcpProxiesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest.verify|verify} messages. + * Encodes the specified ListRegionTargetHttpsProxiesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionTargetTcpProxiesRequest} message ListRegionTargetTcpProxiesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionTargetHttpsProxiesRequest} message ListRegionTargetHttpsProxiesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionTargetTcpProxiesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionTargetHttpsProxiesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionTargetTcpProxiesRequest message from the specified reader or buffer. + * Decodes a ListRegionTargetHttpsProxiesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} ListRegionTargetTcpProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} ListRegionTargetHttpsProxiesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionTargetTcpProxiesRequest.decode = function decode(reader, length, error) { + ListRegionTargetHttpsProxiesRequest.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.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1014284,30 +1025503,30 @@ }; /** - * Decodes a ListRegionTargetTcpProxiesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionTargetHttpsProxiesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} ListRegionTargetTcpProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} ListRegionTargetHttpsProxiesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionTargetTcpProxiesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionTargetHttpsProxiesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionTargetTcpProxiesRequest message. + * Verifies a ListRegionTargetHttpsProxiesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionTargetTcpProxiesRequest.verify = function verify(message) { + ListRegionTargetHttpsProxiesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1014346,17 +1025565,17 @@ }; /** - * Creates a ListRegionTargetTcpProxiesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionTargetHttpsProxiesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} ListRegionTargetTcpProxiesRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} ListRegionTargetHttpsProxiesRequest */ - ListRegionTargetTcpProxiesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest) + ListRegionTargetHttpsProxiesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1014375,15 +1025594,15 @@ }; /** - * Creates a plain object from a ListRegionTargetTcpProxiesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionTargetHttpsProxiesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} message ListRegionTargetTcpProxiesRequest + * @param {google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest} message ListRegionTargetHttpsProxiesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionTargetTcpProxiesRequest.toObject = function toObject(message, options) { + ListRegionTargetHttpsProxiesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1014424,58 +1025643,58 @@ }; /** - * Converts this ListRegionTargetTcpProxiesRequest to JSON. + * Converts this ListRegionTargetHttpsProxiesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @instance * @returns {Object.} JSON object */ - ListRegionTargetTcpProxiesRequest.prototype.toJSON = function toJSON() { + ListRegionTargetHttpsProxiesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionTargetTcpProxiesRequest + * Gets the default type url for ListRegionTargetHttpsProxiesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionTargetTcpProxiesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionTargetHttpsProxiesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionTargetHttpsProxiesRequest"; }; - return ListRegionTargetTcpProxiesRequest; + return ListRegionTargetHttpsProxiesRequest; })(); - v1beta.ListRegionUrlMapsRequest = (function() { + v1beta.ListRegionTargetTcpProxiesRequest = (function() { /** - * Properties of a ListRegionUrlMapsRequest. + * Properties of a ListRegionTargetTcpProxiesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionUrlMapsRequest - * @property {string|null} [filter] ListRegionUrlMapsRequest filter - * @property {number|null} [maxResults] ListRegionUrlMapsRequest maxResults - * @property {string|null} [orderBy] ListRegionUrlMapsRequest orderBy - * @property {string|null} [pageToken] ListRegionUrlMapsRequest pageToken - * @property {string|null} [project] ListRegionUrlMapsRequest project - * @property {string|null} [region] ListRegionUrlMapsRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionUrlMapsRequest returnPartialSuccess + * @interface IListRegionTargetTcpProxiesRequest + * @property {string|null} [filter] ListRegionTargetTcpProxiesRequest filter + * @property {number|null} [maxResults] ListRegionTargetTcpProxiesRequest maxResults + * @property {string|null} [orderBy] ListRegionTargetTcpProxiesRequest orderBy + * @property {string|null} [pageToken] ListRegionTargetTcpProxiesRequest pageToken + * @property {string|null} [project] ListRegionTargetTcpProxiesRequest project + * @property {string|null} [region] ListRegionTargetTcpProxiesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionTargetTcpProxiesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionUrlMapsRequest. + * Constructs a new ListRegionTargetTcpProxiesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionUrlMapsRequest. - * @implements IListRegionUrlMapsRequest + * @classdesc Represents a ListRegionTargetTcpProxiesRequest. + * @implements IListRegionTargetTcpProxiesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionUrlMapsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionTargetTcpProxiesRequest=} [properties] Properties to set */ - function ListRegionUrlMapsRequest(properties) { + function ListRegionTargetTcpProxiesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1014483,116 +1025702,116 @@ } /** - * ListRegionUrlMapsRequest filter. + * ListRegionTargetTcpProxiesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @instance */ - ListRegionUrlMapsRequest.prototype.filter = null; + ListRegionTargetTcpProxiesRequest.prototype.filter = null; /** - * ListRegionUrlMapsRequest maxResults. + * ListRegionTargetTcpProxiesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @instance */ - ListRegionUrlMapsRequest.prototype.maxResults = null; + ListRegionTargetTcpProxiesRequest.prototype.maxResults = null; /** - * ListRegionUrlMapsRequest orderBy. + * ListRegionTargetTcpProxiesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @instance */ - ListRegionUrlMapsRequest.prototype.orderBy = null; + ListRegionTargetTcpProxiesRequest.prototype.orderBy = null; /** - * ListRegionUrlMapsRequest pageToken. + * ListRegionTargetTcpProxiesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @instance */ - ListRegionUrlMapsRequest.prototype.pageToken = null; + ListRegionTargetTcpProxiesRequest.prototype.pageToken = null; /** - * ListRegionUrlMapsRequest project. + * ListRegionTargetTcpProxiesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @instance */ - ListRegionUrlMapsRequest.prototype.project = ""; + ListRegionTargetTcpProxiesRequest.prototype.project = ""; /** - * ListRegionUrlMapsRequest region. + * ListRegionTargetTcpProxiesRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @instance */ - ListRegionUrlMapsRequest.prototype.region = ""; + ListRegionTargetTcpProxiesRequest.prototype.region = ""; /** - * ListRegionUrlMapsRequest returnPartialSuccess. + * ListRegionTargetTcpProxiesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @instance */ - ListRegionUrlMapsRequest.prototype.returnPartialSuccess = null; + ListRegionTargetTcpProxiesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_filter", { + Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionTargetTcpProxiesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionUrlMapsRequest instance using the specified properties. + * Creates a new ListRegionTargetTcpProxiesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionUrlMapsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} ListRegionUrlMapsRequest instance + * @param {google.cloud.compute.v1beta.IListRegionTargetTcpProxiesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} ListRegionTargetTcpProxiesRequest instance */ - ListRegionUrlMapsRequest.create = function create(properties) { - return new ListRegionUrlMapsRequest(properties); + ListRegionTargetTcpProxiesRequest.create = function create(properties) { + return new ListRegionTargetTcpProxiesRequest(properties); }; /** - * Encodes the specified ListRegionUrlMapsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionUrlMapsRequest.verify|verify} messages. + * Encodes the specified ListRegionTargetTcpProxiesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionUrlMapsRequest} message ListRegionUrlMapsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionTargetTcpProxiesRequest} message ListRegionTargetTcpProxiesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionUrlMapsRequest.encode = function encode(message, writer) { + ListRegionTargetTcpProxiesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1014613,33 +1025832,33 @@ }; /** - * Encodes the specified ListRegionUrlMapsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionUrlMapsRequest.verify|verify} messages. + * Encodes the specified ListRegionTargetTcpProxiesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionUrlMapsRequest} message ListRegionUrlMapsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionTargetTcpProxiesRequest} message ListRegionTargetTcpProxiesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionUrlMapsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionTargetTcpProxiesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionUrlMapsRequest message from the specified reader or buffer. + * Decodes a ListRegionTargetTcpProxiesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} ListRegionUrlMapsRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} ListRegionTargetTcpProxiesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionUrlMapsRequest.decode = function decode(reader, length, error) { + ListRegionTargetTcpProxiesRequest.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.cloud.compute.v1beta.ListRegionUrlMapsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1014682,30 +1025901,30 @@ }; /** - * Decodes a ListRegionUrlMapsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionTargetTcpProxiesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} ListRegionUrlMapsRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} ListRegionTargetTcpProxiesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionUrlMapsRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionTargetTcpProxiesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionUrlMapsRequest message. + * Verifies a ListRegionTargetTcpProxiesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionUrlMapsRequest.verify = function verify(message) { + ListRegionTargetTcpProxiesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1014744,17 +1025963,17 @@ }; /** - * Creates a ListRegionUrlMapsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionTargetTcpProxiesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} ListRegionUrlMapsRequest + * @returns {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} ListRegionTargetTcpProxiesRequest */ - ListRegionUrlMapsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionUrlMapsRequest) + ListRegionTargetTcpProxiesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionUrlMapsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1014773,15 +1025992,15 @@ }; /** - * Creates a plain object from a ListRegionUrlMapsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionTargetTcpProxiesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} message ListRegionUrlMapsRequest + * @param {google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest} message ListRegionTargetTcpProxiesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionUrlMapsRequest.toObject = function toObject(message, options) { + ListRegionTargetTcpProxiesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1014822,58 +1026041,58 @@ }; /** - * Converts this ListRegionUrlMapsRequest to JSON. + * Converts this ListRegionTargetTcpProxiesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @instance * @returns {Object.} JSON object */ - ListRegionUrlMapsRequest.prototype.toJSON = function toJSON() { + ListRegionTargetTcpProxiesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionUrlMapsRequest + * Gets the default type url for ListRegionTargetTcpProxiesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest + * @memberof google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionUrlMapsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionTargetTcpProxiesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionUrlMapsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionTargetTcpProxiesRequest"; }; - return ListRegionUrlMapsRequest; + return ListRegionTargetTcpProxiesRequest; })(); - v1beta.ListRegionZonesRequest = (function() { + v1beta.ListRegionUrlMapsRequest = (function() { /** - * Properties of a ListRegionZonesRequest. + * Properties of a ListRegionUrlMapsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionZonesRequest - * @property {string|null} [filter] ListRegionZonesRequest filter - * @property {number|null} [maxResults] ListRegionZonesRequest maxResults - * @property {string|null} [orderBy] ListRegionZonesRequest orderBy - * @property {string|null} [pageToken] ListRegionZonesRequest pageToken - * @property {string|null} [project] ListRegionZonesRequest project - * @property {string|null} [region] ListRegionZonesRequest region - * @property {boolean|null} [returnPartialSuccess] ListRegionZonesRequest returnPartialSuccess + * @interface IListRegionUrlMapsRequest + * @property {string|null} [filter] ListRegionUrlMapsRequest filter + * @property {number|null} [maxResults] ListRegionUrlMapsRequest maxResults + * @property {string|null} [orderBy] ListRegionUrlMapsRequest orderBy + * @property {string|null} [pageToken] ListRegionUrlMapsRequest pageToken + * @property {string|null} [project] ListRegionUrlMapsRequest project + * @property {string|null} [region] ListRegionUrlMapsRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionUrlMapsRequest returnPartialSuccess */ /** - * Constructs a new ListRegionZonesRequest. + * Constructs a new ListRegionUrlMapsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionZonesRequest. - * @implements IListRegionZonesRequest + * @classdesc Represents a ListRegionUrlMapsRequest. + * @implements IListRegionUrlMapsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionZonesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionUrlMapsRequest=} [properties] Properties to set */ - function ListRegionZonesRequest(properties) { + function ListRegionUrlMapsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1014881,116 +1026100,116 @@ } /** - * ListRegionZonesRequest filter. + * ListRegionUrlMapsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @instance */ - ListRegionZonesRequest.prototype.filter = null; + ListRegionUrlMapsRequest.prototype.filter = null; /** - * ListRegionZonesRequest maxResults. + * ListRegionUrlMapsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @instance */ - ListRegionZonesRequest.prototype.maxResults = null; + ListRegionUrlMapsRequest.prototype.maxResults = null; /** - * ListRegionZonesRequest orderBy. + * ListRegionUrlMapsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @instance */ - ListRegionZonesRequest.prototype.orderBy = null; + ListRegionUrlMapsRequest.prototype.orderBy = null; /** - * ListRegionZonesRequest pageToken. + * ListRegionUrlMapsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @instance */ - ListRegionZonesRequest.prototype.pageToken = null; + ListRegionUrlMapsRequest.prototype.pageToken = null; /** - * ListRegionZonesRequest project. + * ListRegionUrlMapsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @instance */ - ListRegionZonesRequest.prototype.project = ""; + ListRegionUrlMapsRequest.prototype.project = ""; /** - * ListRegionZonesRequest region. + * ListRegionUrlMapsRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @instance */ - ListRegionZonesRequest.prototype.region = ""; + ListRegionUrlMapsRequest.prototype.region = ""; /** - * ListRegionZonesRequest returnPartialSuccess. + * ListRegionUrlMapsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @instance */ - ListRegionZonesRequest.prototype.returnPartialSuccess = null; + ListRegionUrlMapsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionZonesRequest.prototype, "_filter", { + Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionZonesRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionZonesRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionZonesRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionZonesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionUrlMapsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionZonesRequest instance using the specified properties. + * Creates a new ListRegionUrlMapsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionZonesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionZonesRequest} ListRegionZonesRequest instance + * @param {google.cloud.compute.v1beta.IListRegionUrlMapsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} ListRegionUrlMapsRequest instance */ - ListRegionZonesRequest.create = function create(properties) { - return new ListRegionZonesRequest(properties); + ListRegionUrlMapsRequest.create = function create(properties) { + return new ListRegionUrlMapsRequest(properties); }; /** - * Encodes the specified ListRegionZonesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionZonesRequest.verify|verify} messages. + * Encodes the specified ListRegionUrlMapsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionUrlMapsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionZonesRequest} message ListRegionZonesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionUrlMapsRequest} message ListRegionUrlMapsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionZonesRequest.encode = function encode(message, writer) { + ListRegionUrlMapsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) @@ -1015011,33 +1026230,33 @@ }; /** - * Encodes the specified ListRegionZonesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionZonesRequest.verify|verify} messages. + * Encodes the specified ListRegionUrlMapsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionUrlMapsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionZonesRequest} message ListRegionZonesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionUrlMapsRequest} message ListRegionUrlMapsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionZonesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionUrlMapsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionZonesRequest message from the specified reader or buffer. + * Decodes a ListRegionUrlMapsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionZonesRequest} ListRegionZonesRequest + * @returns {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} ListRegionUrlMapsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionZonesRequest.decode = function decode(reader, length, error) { + ListRegionUrlMapsRequest.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.cloud.compute.v1beta.ListRegionZonesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionUrlMapsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1015080,30 +1026299,30 @@ }; /** - * Decodes a ListRegionZonesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionUrlMapsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionZonesRequest} ListRegionZonesRequest + * @returns {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} ListRegionUrlMapsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionZonesRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionUrlMapsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionZonesRequest message. + * Verifies a ListRegionUrlMapsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionZonesRequest.verify = function verify(message) { + ListRegionUrlMapsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1015142,17 +1026361,17 @@ }; /** - * Creates a ListRegionZonesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionUrlMapsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionZonesRequest} ListRegionZonesRequest + * @returns {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} ListRegionUrlMapsRequest */ - ListRegionZonesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionZonesRequest) + ListRegionUrlMapsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionUrlMapsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionZonesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionUrlMapsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1015171,15 +1026390,15 @@ }; /** - * Creates a plain object from a ListRegionZonesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionUrlMapsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionZonesRequest} message ListRegionZonesRequest + * @param {google.cloud.compute.v1beta.ListRegionUrlMapsRequest} message ListRegionUrlMapsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionZonesRequest.toObject = function toObject(message, options) { + ListRegionUrlMapsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1015220,57 +1026439,58 @@ }; /** - * Converts this ListRegionZonesRequest to JSON. + * Converts this ListRegionUrlMapsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @instance * @returns {Object.} JSON object */ - ListRegionZonesRequest.prototype.toJSON = function toJSON() { + ListRegionUrlMapsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionZonesRequest + * Gets the default type url for ListRegionUrlMapsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @memberof google.cloud.compute.v1beta.ListRegionUrlMapsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionZonesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionUrlMapsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionZonesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionUrlMapsRequest"; }; - return ListRegionZonesRequest; + return ListRegionUrlMapsRequest; })(); - v1beta.ListRegionsRequest = (function() { + v1beta.ListRegionZonesRequest = (function() { /** - * Properties of a ListRegionsRequest. + * Properties of a ListRegionZonesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRegionsRequest - * @property {string|null} [filter] ListRegionsRequest filter - * @property {number|null} [maxResults] ListRegionsRequest maxResults - * @property {string|null} [orderBy] ListRegionsRequest orderBy - * @property {string|null} [pageToken] ListRegionsRequest pageToken - * @property {string|null} [project] ListRegionsRequest project - * @property {boolean|null} [returnPartialSuccess] ListRegionsRequest returnPartialSuccess + * @interface IListRegionZonesRequest + * @property {string|null} [filter] ListRegionZonesRequest filter + * @property {number|null} [maxResults] ListRegionZonesRequest maxResults + * @property {string|null} [orderBy] ListRegionZonesRequest orderBy + * @property {string|null} [pageToken] ListRegionZonesRequest pageToken + * @property {string|null} [project] ListRegionZonesRequest project + * @property {string|null} [region] ListRegionZonesRequest region + * @property {boolean|null} [returnPartialSuccess] ListRegionZonesRequest returnPartialSuccess */ /** - * Constructs a new ListRegionsRequest. + * Constructs a new ListRegionZonesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRegionsRequest. - * @implements IListRegionsRequest + * @classdesc Represents a ListRegionZonesRequest. + * @implements IListRegionZonesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRegionsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionZonesRequest=} [properties] Properties to set */ - function ListRegionsRequest(properties) { + function ListRegionZonesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1015278,114 +1026498,124 @@ } /** - * ListRegionsRequest filter. + * ListRegionZonesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @instance */ - ListRegionsRequest.prototype.filter = null; + ListRegionZonesRequest.prototype.filter = null; /** - * ListRegionsRequest maxResults. + * ListRegionZonesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @instance */ - ListRegionsRequest.prototype.maxResults = null; + ListRegionZonesRequest.prototype.maxResults = null; /** - * ListRegionsRequest orderBy. + * ListRegionZonesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @instance */ - ListRegionsRequest.prototype.orderBy = null; + ListRegionZonesRequest.prototype.orderBy = null; /** - * ListRegionsRequest pageToken. + * ListRegionZonesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @instance */ - ListRegionsRequest.prototype.pageToken = null; + ListRegionZonesRequest.prototype.pageToken = null; /** - * ListRegionsRequest project. + * ListRegionZonesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @instance */ - ListRegionsRequest.prototype.project = ""; + ListRegionZonesRequest.prototype.project = ""; /** - * ListRegionsRequest returnPartialSuccess. + * ListRegionZonesRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest + * @instance + */ + ListRegionZonesRequest.prototype.region = ""; + + /** + * ListRegionZonesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @instance */ - ListRegionsRequest.prototype.returnPartialSuccess = null; + ListRegionZonesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionsRequest.prototype, "_filter", { + Object.defineProperty(ListRegionZonesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionsRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionZonesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionsRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionZonesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionsRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionZonesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRegionsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionZonesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRegionsRequest instance using the specified properties. + * Creates a new ListRegionZonesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRegionsRequest} ListRegionsRequest instance + * @param {google.cloud.compute.v1beta.IListRegionZonesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionZonesRequest} ListRegionZonesRequest instance */ - ListRegionsRequest.create = function create(properties) { - return new ListRegionsRequest(properties); + ListRegionZonesRequest.create = function create(properties) { + return new ListRegionZonesRequest(properties); }; /** - * Encodes the specified ListRegionsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionsRequest.verify|verify} messages. + * Encodes the specified ListRegionZonesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionZonesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionsRequest} message ListRegionsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionZonesRequest} message ListRegionZonesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionsRequest.encode = function encode(message, writer) { + ListRegionZonesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); if (message.project != null && Object.hasOwnProperty.call(message, "project")) @@ -1015398,33 +1026628,33 @@ }; /** - * Encodes the specified ListRegionsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionsRequest.verify|verify} messages. + * Encodes the specified ListRegionZonesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionZonesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static - * @param {google.cloud.compute.v1beta.IListRegionsRequest} message ListRegionsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionZonesRequest} message ListRegionZonesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRegionsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionZonesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRegionsRequest message from the specified reader or buffer. + * Decodes a ListRegionZonesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRegionsRequest} ListRegionsRequest + * @returns {google.cloud.compute.v1beta.ListRegionZonesRequest} ListRegionZonesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionsRequest.decode = function decode(reader, length, error) { + ListRegionZonesRequest.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.cloud.compute.v1beta.ListRegionsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionZonesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1015450,6 +1026680,10 @@ message.project = reader.string(); break; } + case 138946292: { + message.region = reader.string(); + break; + } case 517198390: { message.returnPartialSuccess = reader.bool(); break; @@ -1015463,30 +1026697,30 @@ }; /** - * Decodes a ListRegionsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionZonesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRegionsRequest} ListRegionsRequest + * @returns {google.cloud.compute.v1beta.ListRegionZonesRequest} ListRegionZonesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRegionsRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionZonesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRegionsRequest message. + * Verifies a ListRegionZonesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRegionsRequest.verify = function verify(message) { + ListRegionZonesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1015513,6 +1026747,9 @@ if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { properties._returnPartialSuccess = 1; if (typeof message.returnPartialSuccess !== "boolean") @@ -1015522,17 +1026759,17 @@ }; /** - * Creates a ListRegionsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionZonesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRegionsRequest} ListRegionsRequest + * @returns {google.cloud.compute.v1beta.ListRegionZonesRequest} ListRegionZonesRequest */ - ListRegionsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRegionsRequest) + ListRegionZonesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionZonesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRegionsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionZonesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1015543,26 +1026780,30 @@ message.pageToken = String(object.pageToken); if (object.project != null) message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); if (object.returnPartialSuccess != null) message.returnPartialSuccess = Boolean(object.returnPartialSuccess); return message; }; /** - * Creates a plain object from a ListRegionsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionZonesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static - * @param {google.cloud.compute.v1beta.ListRegionsRequest} message ListRegionsRequest + * @param {google.cloud.compute.v1beta.ListRegionZonesRequest} message ListRegionZonesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRegionsRequest.toObject = function toObject(message, options) { + ListRegionZonesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) + if (options.defaults) { + object.region = ""; object.project = ""; + } if (message.pageToken != null && message.hasOwnProperty("pageToken")) { object.pageToken = message.pageToken; if (options.oneofs) @@ -1015573,6 +1026814,8 @@ if (options.oneofs) object._maxResults = "maxResults"; } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; if (message.orderBy != null && message.hasOwnProperty("orderBy")) { object.orderBy = message.orderBy; if (options.oneofs) @@ -1015594,59 +1026837,57 @@ }; /** - * Converts this ListRegionsRequest to JSON. + * Converts this ListRegionZonesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @instance * @returns {Object.} JSON object */ - ListRegionsRequest.prototype.toJSON = function toJSON() { + ListRegionZonesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRegionsRequest + * Gets the default type url for ListRegionZonesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRegionsRequest + * @memberof google.cloud.compute.v1beta.ListRegionZonesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRegionsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionZonesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionZonesRequest"; }; - return ListRegionsRequest; + return ListRegionZonesRequest; })(); - v1beta.ListReservationBlocksRequest = (function() { + v1beta.ListRegionsRequest = (function() { /** - * Properties of a ListReservationBlocksRequest. + * Properties of a ListRegionsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListReservationBlocksRequest - * @property {string|null} [filter] ListReservationBlocksRequest filter - * @property {number|null} [maxResults] ListReservationBlocksRequest maxResults - * @property {string|null} [orderBy] ListReservationBlocksRequest orderBy - * @property {string|null} [pageToken] ListReservationBlocksRequest pageToken - * @property {string|null} [project] ListReservationBlocksRequest project - * @property {string|null} [reservation] ListReservationBlocksRequest reservation - * @property {boolean|null} [returnPartialSuccess] ListReservationBlocksRequest returnPartialSuccess - * @property {string|null} [zone] ListReservationBlocksRequest zone + * @interface IListRegionsRequest + * @property {string|null} [filter] ListRegionsRequest filter + * @property {number|null} [maxResults] ListRegionsRequest maxResults + * @property {string|null} [orderBy] ListRegionsRequest orderBy + * @property {string|null} [pageToken] ListRegionsRequest pageToken + * @property {string|null} [project] ListRegionsRequest project + * @property {boolean|null} [returnPartialSuccess] ListRegionsRequest returnPartialSuccess */ /** - * Constructs a new ListReservationBlocksRequest. + * Constructs a new ListRegionsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListReservationBlocksRequest. - * @implements IListReservationBlocksRequest + * @classdesc Represents a ListRegionsRequest. + * @implements IListRegionsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListReservationBlocksRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRegionsRequest=} [properties] Properties to set */ - function ListReservationBlocksRequest(properties) { + function ListRegionsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1015654,132 +1026895,112 @@ } /** - * ListReservationBlocksRequest filter. + * ListRegionsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @instance */ - ListReservationBlocksRequest.prototype.filter = null; + ListRegionsRequest.prototype.filter = null; /** - * ListReservationBlocksRequest maxResults. + * ListRegionsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @instance */ - ListReservationBlocksRequest.prototype.maxResults = null; + ListRegionsRequest.prototype.maxResults = null; /** - * ListReservationBlocksRequest orderBy. + * ListRegionsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @instance */ - ListReservationBlocksRequest.prototype.orderBy = null; + ListRegionsRequest.prototype.orderBy = null; /** - * ListReservationBlocksRequest pageToken. + * ListRegionsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @instance */ - ListReservationBlocksRequest.prototype.pageToken = null; + ListRegionsRequest.prototype.pageToken = null; /** - * ListReservationBlocksRequest project. + * ListRegionsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest - * @instance - */ - ListReservationBlocksRequest.prototype.project = ""; - - /** - * ListReservationBlocksRequest reservation. - * @member {string} reservation - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @instance */ - ListReservationBlocksRequest.prototype.reservation = ""; + ListRegionsRequest.prototype.project = ""; /** - * ListReservationBlocksRequest returnPartialSuccess. + * ListRegionsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest - * @instance - */ - ListReservationBlocksRequest.prototype.returnPartialSuccess = null; - - /** - * ListReservationBlocksRequest zone. - * @member {string} zone - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @instance */ - ListReservationBlocksRequest.prototype.zone = ""; + ListRegionsRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationBlocksRequest.prototype, "_filter", { + Object.defineProperty(ListRegionsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationBlocksRequest.prototype, "_maxResults", { + Object.defineProperty(ListRegionsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationBlocksRequest.prototype, "_orderBy", { + Object.defineProperty(ListRegionsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationBlocksRequest.prototype, "_pageToken", { + Object.defineProperty(ListRegionsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationBlocksRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRegionsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListReservationBlocksRequest instance using the specified properties. + * Creates a new ListRegionsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationBlocksRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListReservationBlocksRequest} ListReservationBlocksRequest instance + * @param {google.cloud.compute.v1beta.IListRegionsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRegionsRequest} ListRegionsRequest instance */ - ListReservationBlocksRequest.create = function create(properties) { - return new ListReservationBlocksRequest(properties); + ListRegionsRequest.create = function create(properties) { + return new ListRegionsRequest(properties); }; /** - * Encodes the specified ListReservationBlocksRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationBlocksRequest.verify|verify} messages. + * Encodes the specified ListRegionsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationBlocksRequest} message ListReservationBlocksRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionsRequest} message ListRegionsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListReservationBlocksRequest.encode = function encode(message, writer) { + ListRegionsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) - writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); - if (message.reservation != null && Object.hasOwnProperty.call(message, "reservation")) - writer.uint32(/* id 47530956, wireType 2 =*/380247650).string(message.reservation); if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) @@ -1015794,33 +1027015,33 @@ }; /** - * Encodes the specified ListReservationBlocksRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationBlocksRequest.verify|verify} messages. + * Encodes the specified ListRegionsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRegionsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationBlocksRequest} message ListReservationBlocksRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRegionsRequest} message ListRegionsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListReservationBlocksRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRegionsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListReservationBlocksRequest message from the specified reader or buffer. + * Decodes a ListRegionsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListReservationBlocksRequest} ListReservationBlocksRequest + * @returns {google.cloud.compute.v1beta.ListRegionsRequest} ListRegionsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListReservationBlocksRequest.decode = function decode(reader, length, error) { + ListRegionsRequest.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.cloud.compute.v1beta.ListReservationBlocksRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRegionsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1015846,18 +1027067,10 @@ message.project = reader.string(); break; } - case 47530956: { - message.reservation = reader.string(); - break; - } case 517198390: { message.returnPartialSuccess = reader.bool(); break; } - case 3744684: { - message.zone = reader.string(); - break; - } default: reader.skipType(tag & 7); break; @@ -1015867,30 +1027080,30 @@ }; /** - * Decodes a ListReservationBlocksRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRegionsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListReservationBlocksRequest} ListReservationBlocksRequest + * @returns {google.cloud.compute.v1beta.ListRegionsRequest} ListRegionsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListReservationBlocksRequest.decodeDelimited = function decodeDelimited(reader) { + ListRegionsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListReservationBlocksRequest message. + * Verifies a ListRegionsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListReservationBlocksRequest.verify = function verify(message) { + ListRegionsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1015917,32 +1027130,26 @@ if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) return "project: string expected"; - if (message.reservation != null && message.hasOwnProperty("reservation")) - if (!$util.isString(message.reservation)) - return "reservation: string expected"; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { properties._returnPartialSuccess = 1; if (typeof message.returnPartialSuccess !== "boolean") return "returnPartialSuccess: boolean expected"; } - if (message.zone != null && message.hasOwnProperty("zone")) - if (!$util.isString(message.zone)) - return "zone: string expected"; return null; }; /** - * Creates a ListReservationBlocksRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListRegionsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListReservationBlocksRequest} ListReservationBlocksRequest + * @returns {google.cloud.compute.v1beta.ListRegionsRequest} ListRegionsRequest */ - ListReservationBlocksRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListReservationBlocksRequest) + ListRegionsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRegionsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListReservationBlocksRequest(); + var message = new $root.google.cloud.compute.v1beta.ListRegionsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1015953,42 +1027160,31 @@ message.pageToken = String(object.pageToken); if (object.project != null) message.project = String(object.project); - if (object.reservation != null) - message.reservation = String(object.reservation); if (object.returnPartialSuccess != null) message.returnPartialSuccess = Boolean(object.returnPartialSuccess); - if (object.zone != null) - message.zone = String(object.zone); return message; }; /** - * Creates a plain object from a ListReservationBlocksRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListRegionsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static - * @param {google.cloud.compute.v1beta.ListReservationBlocksRequest} message ListReservationBlocksRequest + * @param {google.cloud.compute.v1beta.ListRegionsRequest} message ListRegionsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListReservationBlocksRequest.toObject = function toObject(message, options) { + ListRegionsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.zone = ""; - object.reservation = ""; + if (options.defaults) object.project = ""; - } - if (message.zone != null && message.hasOwnProperty("zone")) - object.zone = message.zone; if (message.pageToken != null && message.hasOwnProperty("pageToken")) { object.pageToken = message.pageToken; if (options.oneofs) object._pageToken = "pageToken"; } - if (message.reservation != null && message.hasOwnProperty("reservation")) - object.reservation = message.reservation; if (message.maxResults != null && message.hasOwnProperty("maxResults")) { object.maxResults = message.maxResults; if (options.oneofs) @@ -1016015,59 +1027211,59 @@ }; /** - * Converts this ListReservationBlocksRequest to JSON. + * Converts this ListRegionsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @instance * @returns {Object.} JSON object */ - ListReservationBlocksRequest.prototype.toJSON = function toJSON() { + ListRegionsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListReservationBlocksRequest + * Gets the default type url for ListRegionsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest + * @memberof google.cloud.compute.v1beta.ListRegionsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListReservationBlocksRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListRegionsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListReservationBlocksRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRegionsRequest"; }; - return ListReservationBlocksRequest; + return ListRegionsRequest; })(); - v1beta.ListReservationSubBlocksRequest = (function() { + v1beta.ListReservationBlocksRequest = (function() { /** - * Properties of a ListReservationSubBlocksRequest. + * Properties of a ListReservationBlocksRequest. * @memberof google.cloud.compute.v1beta - * @interface IListReservationSubBlocksRequest - * @property {string|null} [filter] ListReservationSubBlocksRequest filter - * @property {number|null} [maxResults] ListReservationSubBlocksRequest maxResults - * @property {string|null} [orderBy] ListReservationSubBlocksRequest orderBy - * @property {string|null} [pageToken] ListReservationSubBlocksRequest pageToken - * @property {string|null} [parentName] ListReservationSubBlocksRequest parentName - * @property {string|null} [project] ListReservationSubBlocksRequest project - * @property {boolean|null} [returnPartialSuccess] ListReservationSubBlocksRequest returnPartialSuccess - * @property {string|null} [zone] ListReservationSubBlocksRequest zone + * @interface IListReservationBlocksRequest + * @property {string|null} [filter] ListReservationBlocksRequest filter + * @property {number|null} [maxResults] ListReservationBlocksRequest maxResults + * @property {string|null} [orderBy] ListReservationBlocksRequest orderBy + * @property {string|null} [pageToken] ListReservationBlocksRequest pageToken + * @property {string|null} [project] ListReservationBlocksRequest project + * @property {string|null} [reservation] ListReservationBlocksRequest reservation + * @property {boolean|null} [returnPartialSuccess] ListReservationBlocksRequest returnPartialSuccess + * @property {string|null} [zone] ListReservationBlocksRequest zone */ /** - * Constructs a new ListReservationSubBlocksRequest. + * Constructs a new ListReservationBlocksRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListReservationSubBlocksRequest. - * @implements IListReservationSubBlocksRequest + * @classdesc Represents a ListReservationBlocksRequest. + * @implements IListReservationBlocksRequest * @constructor - * @param {google.cloud.compute.v1beta.IListReservationSubBlocksRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListReservationBlocksRequest=} [properties] Properties to set */ - function ListReservationSubBlocksRequest(properties) { + function ListReservationBlocksRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1016075,130 +1027271,132 @@ } /** - * ListReservationSubBlocksRequest filter. + * ListReservationBlocksRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance */ - ListReservationSubBlocksRequest.prototype.filter = null; + ListReservationBlocksRequest.prototype.filter = null; /** - * ListReservationSubBlocksRequest maxResults. + * ListReservationBlocksRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance */ - ListReservationSubBlocksRequest.prototype.maxResults = null; + ListReservationBlocksRequest.prototype.maxResults = null; /** - * ListReservationSubBlocksRequest orderBy. + * ListReservationBlocksRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance */ - ListReservationSubBlocksRequest.prototype.orderBy = null; + ListReservationBlocksRequest.prototype.orderBy = null; /** - * ListReservationSubBlocksRequest pageToken. + * ListReservationBlocksRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance */ - ListReservationSubBlocksRequest.prototype.pageToken = null; + ListReservationBlocksRequest.prototype.pageToken = null; /** - * ListReservationSubBlocksRequest parentName. - * @member {string} parentName - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * ListReservationBlocksRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance */ - ListReservationSubBlocksRequest.prototype.parentName = ""; + ListReservationBlocksRequest.prototype.project = ""; /** - * ListReservationSubBlocksRequest project. - * @member {string} project - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * ListReservationBlocksRequest reservation. + * @member {string} reservation + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance */ - ListReservationSubBlocksRequest.prototype.project = ""; + ListReservationBlocksRequest.prototype.reservation = ""; /** - * ListReservationSubBlocksRequest returnPartialSuccess. + * ListReservationBlocksRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance */ - ListReservationSubBlocksRequest.prototype.returnPartialSuccess = null; + ListReservationBlocksRequest.prototype.returnPartialSuccess = null; /** - * ListReservationSubBlocksRequest zone. + * ListReservationBlocksRequest zone. * @member {string} zone - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance */ - ListReservationSubBlocksRequest.prototype.zone = ""; + ListReservationBlocksRequest.prototype.zone = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_filter", { + Object.defineProperty(ListReservationBlocksRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_maxResults", { + Object.defineProperty(ListReservationBlocksRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_orderBy", { + Object.defineProperty(ListReservationBlocksRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_pageToken", { + Object.defineProperty(ListReservationBlocksRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListReservationBlocksRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListReservationSubBlocksRequest instance using the specified properties. + * Creates a new ListReservationBlocksRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationSubBlocksRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} ListReservationSubBlocksRequest instance + * @param {google.cloud.compute.v1beta.IListReservationBlocksRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListReservationBlocksRequest} ListReservationBlocksRequest instance */ - ListReservationSubBlocksRequest.create = function create(properties) { - return new ListReservationSubBlocksRequest(properties); + ListReservationBlocksRequest.create = function create(properties) { + return new ListReservationBlocksRequest(properties); }; /** - * Encodes the specified ListReservationSubBlocksRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationSubBlocksRequest.verify|verify} messages. + * Encodes the specified ListReservationBlocksRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationBlocksRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationSubBlocksRequest} message ListReservationSubBlocksRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListReservationBlocksRequest} message ListReservationBlocksRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListReservationSubBlocksRequest.encode = function encode(message, writer) { + ListReservationBlocksRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); + if (message.reservation != null && Object.hasOwnProperty.call(message, "reservation")) + writer.uint32(/* id 47530956, wireType 2 =*/380247650).string(message.reservation); if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) @@ -1016207,41 +1027405,39 @@ writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); - if (message.parentName != null && Object.hasOwnProperty.call(message, "parentName")) - writer.uint32(/* id 478151936, wireType 2 =*/3825215490).string(message.parentName); if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); return writer; }; /** - * Encodes the specified ListReservationSubBlocksRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationSubBlocksRequest.verify|verify} messages. + * Encodes the specified ListReservationBlocksRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationBlocksRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationSubBlocksRequest} message ListReservationSubBlocksRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListReservationBlocksRequest} message ListReservationBlocksRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListReservationSubBlocksRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListReservationBlocksRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListReservationSubBlocksRequest message from the specified reader or buffer. + * Decodes a ListReservationBlocksRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} ListReservationSubBlocksRequest + * @returns {google.cloud.compute.v1beta.ListReservationBlocksRequest} ListReservationBlocksRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListReservationSubBlocksRequest.decode = function decode(reader, length, error) { + ListReservationBlocksRequest.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.cloud.compute.v1beta.ListReservationSubBlocksRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListReservationBlocksRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1016263,14 +1027459,14 @@ message.pageToken = reader.string(); break; } - case 478151936: { - message.parentName = reader.string(); - break; - } case 227560217: { message.project = reader.string(); break; } + case 47530956: { + message.reservation = reader.string(); + break; + } case 517198390: { message.returnPartialSuccess = reader.bool(); break; @@ -1016288,30 +1027484,30 @@ }; /** - * Decodes a ListReservationSubBlocksRequest message from the specified reader or buffer, length delimited. + * Decodes a ListReservationBlocksRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} ListReservationSubBlocksRequest + * @returns {google.cloud.compute.v1beta.ListReservationBlocksRequest} ListReservationBlocksRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListReservationSubBlocksRequest.decodeDelimited = function decodeDelimited(reader) { + ListReservationBlocksRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListReservationSubBlocksRequest message. + * Verifies a ListReservationBlocksRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListReservationSubBlocksRequest.verify = function verify(message) { + ListReservationBlocksRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1016335,12 +1027531,12 @@ if (!$util.isString(message.pageToken)) return "pageToken: string expected"; } - if (message.parentName != null && message.hasOwnProperty("parentName")) - if (!$util.isString(message.parentName)) - return "parentName: string expected"; if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) return "project: string expected"; + if (message.reservation != null && message.hasOwnProperty("reservation")) + if (!$util.isString(message.reservation)) + return "reservation: string expected"; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { properties._returnPartialSuccess = 1; if (typeof message.returnPartialSuccess !== "boolean") @@ -1016353,17 +1027549,17 @@ }; /** - * Creates a ListReservationSubBlocksRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListReservationBlocksRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} ListReservationSubBlocksRequest + * @returns {google.cloud.compute.v1beta.ListReservationBlocksRequest} ListReservationBlocksRequest */ - ListReservationSubBlocksRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListReservationSubBlocksRequest) + ListReservationBlocksRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListReservationBlocksRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListReservationSubBlocksRequest(); + var message = new $root.google.cloud.compute.v1beta.ListReservationBlocksRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1016372,10 +1027568,10 @@ message.orderBy = String(object.orderBy); if (object.pageToken != null) message.pageToken = String(object.pageToken); - if (object.parentName != null) - message.parentName = String(object.parentName); if (object.project != null) message.project = String(object.project); + if (object.reservation != null) + message.reservation = String(object.reservation); if (object.returnPartialSuccess != null) message.returnPartialSuccess = Boolean(object.returnPartialSuccess); if (object.zone != null) @@ -1016384,22 +1027580,22 @@ }; /** - * Creates a plain object from a ListReservationSubBlocksRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListReservationBlocksRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static - * @param {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} message ListReservationSubBlocksRequest + * @param {google.cloud.compute.v1beta.ListReservationBlocksRequest} message ListReservationBlocksRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListReservationSubBlocksRequest.toObject = function toObject(message, options) { + ListReservationBlocksRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { object.zone = ""; + object.reservation = ""; object.project = ""; - object.parentName = ""; } if (message.zone != null && message.hasOwnProperty("zone")) object.zone = message.zone; @@ -1016408,6 +1027604,8 @@ if (options.oneofs) object._pageToken = "pageToken"; } + if (message.reservation != null && message.hasOwnProperty("reservation")) + object.reservation = message.reservation; if (message.maxResults != null && message.hasOwnProperty("maxResults")) { object.maxResults = message.maxResults; if (options.oneofs) @@ -1016425,8 +1027623,6 @@ if (options.oneofs) object._filter = "filter"; } - if (message.parentName != null && message.hasOwnProperty("parentName")) - object.parentName = message.parentName; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { object.returnPartialSuccess = message.returnPartialSuccess; if (options.oneofs) @@ -1016436,58 +1027632,59 @@ }; /** - * Converts this ListReservationSubBlocksRequest to JSON. + * Converts this ListReservationBlocksRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @instance * @returns {Object.} JSON object */ - ListReservationSubBlocksRequest.prototype.toJSON = function toJSON() { + ListReservationBlocksRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListReservationSubBlocksRequest + * Gets the default type url for ListReservationBlocksRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @memberof google.cloud.compute.v1beta.ListReservationBlocksRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListReservationSubBlocksRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListReservationBlocksRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListReservationSubBlocksRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListReservationBlocksRequest"; }; - return ListReservationSubBlocksRequest; + return ListReservationBlocksRequest; })(); - v1beta.ListReservationsRequest = (function() { + v1beta.ListReservationSlotsRequest = (function() { /** - * Properties of a ListReservationsRequest. + * Properties of a ListReservationSlotsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListReservationsRequest - * @property {string|null} [filter] ListReservationsRequest filter - * @property {number|null} [maxResults] ListReservationsRequest maxResults - * @property {string|null} [orderBy] ListReservationsRequest orderBy - * @property {string|null} [pageToken] ListReservationsRequest pageToken - * @property {string|null} [project] ListReservationsRequest project - * @property {boolean|null} [returnPartialSuccess] ListReservationsRequest returnPartialSuccess - * @property {string|null} [zone] ListReservationsRequest zone + * @interface IListReservationSlotsRequest + * @property {string|null} [filter] ListReservationSlotsRequest filter + * @property {number|null} [maxResults] ListReservationSlotsRequest maxResults + * @property {string|null} [orderBy] ListReservationSlotsRequest orderBy + * @property {string|null} [pageToken] ListReservationSlotsRequest pageToken + * @property {string|null} [parentName] ListReservationSlotsRequest parentName + * @property {string|null} [project] ListReservationSlotsRequest project + * @property {boolean|null} [returnPartialSuccess] ListReservationSlotsRequest returnPartialSuccess + * @property {string|null} [zone] ListReservationSlotsRequest zone */ /** - * Constructs a new ListReservationsRequest. + * Constructs a new ListReservationSlotsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListReservationsRequest. - * @implements IListReservationsRequest + * @classdesc Represents a ListReservationSlotsRequest. + * @implements IListReservationSlotsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListReservationsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListReservationSlotsRequest=} [properties] Properties to set */ - function ListReservationsRequest(properties) { + function ListReservationSlotsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1016495,116 +1027692,124 @@ } /** - * ListReservationsRequest filter. + * ListReservationSlotsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @instance */ - ListReservationsRequest.prototype.filter = null; + ListReservationSlotsRequest.prototype.filter = null; /** - * ListReservationsRequest maxResults. + * ListReservationSlotsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @instance */ - ListReservationsRequest.prototype.maxResults = null; + ListReservationSlotsRequest.prototype.maxResults = null; /** - * ListReservationsRequest orderBy. + * ListReservationSlotsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @instance */ - ListReservationsRequest.prototype.orderBy = null; + ListReservationSlotsRequest.prototype.orderBy = null; /** - * ListReservationsRequest pageToken. + * ListReservationSlotsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @instance */ - ListReservationsRequest.prototype.pageToken = null; + ListReservationSlotsRequest.prototype.pageToken = null; /** - * ListReservationsRequest project. + * ListReservationSlotsRequest parentName. + * @member {string} parentName + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest + * @instance + */ + ListReservationSlotsRequest.prototype.parentName = ""; + + /** + * ListReservationSlotsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @instance */ - ListReservationsRequest.prototype.project = ""; + ListReservationSlotsRequest.prototype.project = ""; /** - * ListReservationsRequest returnPartialSuccess. + * ListReservationSlotsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @instance */ - ListReservationsRequest.prototype.returnPartialSuccess = null; + ListReservationSlotsRequest.prototype.returnPartialSuccess = null; /** - * ListReservationsRequest zone. + * ListReservationSlotsRequest zone. * @member {string} zone - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @instance */ - ListReservationsRequest.prototype.zone = ""; + ListReservationSlotsRequest.prototype.zone = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationsRequest.prototype, "_filter", { + Object.defineProperty(ListReservationSlotsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationsRequest.prototype, "_maxResults", { + Object.defineProperty(ListReservationSlotsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationsRequest.prototype, "_orderBy", { + Object.defineProperty(ListReservationSlotsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationsRequest.prototype, "_pageToken", { + Object.defineProperty(ListReservationSlotsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListReservationsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListReservationSlotsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListReservationsRequest instance using the specified properties. + * Creates a new ListReservationSlotsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListReservationsRequest} ListReservationsRequest instance + * @param {google.cloud.compute.v1beta.IListReservationSlotsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListReservationSlotsRequest} ListReservationSlotsRequest instance */ - ListReservationsRequest.create = function create(properties) { - return new ListReservationsRequest(properties); + ListReservationSlotsRequest.create = function create(properties) { + return new ListReservationSlotsRequest(properties); }; /** - * Encodes the specified ListReservationsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationsRequest.verify|verify} messages. + * Encodes the specified ListReservationSlotsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationSlotsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationsRequest} message ListReservationsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListReservationSlotsRequest} message ListReservationSlotsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListReservationsRequest.encode = function encode(message, writer) { + ListReservationSlotsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) @@ -1016619,39 +1027824,41 @@ writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); + if (message.parentName != null && Object.hasOwnProperty.call(message, "parentName")) + writer.uint32(/* id 478151936, wireType 2 =*/3825215490).string(message.parentName); if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); return writer; }; /** - * Encodes the specified ListReservationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationsRequest.verify|verify} messages. + * Encodes the specified ListReservationSlotsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationSlotsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static - * @param {google.cloud.compute.v1beta.IListReservationsRequest} message ListReservationsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListReservationSlotsRequest} message ListReservationSlotsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListReservationsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListReservationSlotsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListReservationsRequest message from the specified reader or buffer. + * Decodes a ListReservationSlotsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListReservationsRequest} ListReservationsRequest + * @returns {google.cloud.compute.v1beta.ListReservationSlotsRequest} ListReservationSlotsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListReservationsRequest.decode = function decode(reader, length, error) { + ListReservationSlotsRequest.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.cloud.compute.v1beta.ListReservationsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListReservationSlotsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1016673,6 +1027880,10 @@ message.pageToken = reader.string(); break; } + case 478151936: { + message.parentName = reader.string(); + break; + } case 227560217: { message.project = reader.string(); break; @@ -1016694,30 +1027905,30 @@ }; /** - * Decodes a ListReservationsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListReservationSlotsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListReservationsRequest} ListReservationsRequest + * @returns {google.cloud.compute.v1beta.ListReservationSlotsRequest} ListReservationSlotsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListReservationsRequest.decodeDelimited = function decodeDelimited(reader) { + ListReservationSlotsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListReservationsRequest message. + * Verifies a ListReservationSlotsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListReservationsRequest.verify = function verify(message) { + ListReservationSlotsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1016741,6 +1027952,9 @@ if (!$util.isString(message.pageToken)) return "pageToken: string expected"; } + if (message.parentName != null && message.hasOwnProperty("parentName")) + if (!$util.isString(message.parentName)) + return "parentName: string expected"; if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) return "project: string expected"; @@ -1016756,17 +1027970,17 @@ }; /** - * Creates a ListReservationsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListReservationSlotsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListReservationsRequest} ListReservationsRequest + * @returns {google.cloud.compute.v1beta.ListReservationSlotsRequest} ListReservationSlotsRequest */ - ListReservationsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListReservationsRequest) + ListReservationSlotsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListReservationSlotsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListReservationsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListReservationSlotsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1016775,6 +1027989,8 @@ message.orderBy = String(object.orderBy); if (object.pageToken != null) message.pageToken = String(object.pageToken); + if (object.parentName != null) + message.parentName = String(object.parentName); if (object.project != null) message.project = String(object.project); if (object.returnPartialSuccess != null) @@ -1016785,21 +1028001,22 @@ }; /** - * Creates a plain object from a ListReservationsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListReservationSlotsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static - * @param {google.cloud.compute.v1beta.ListReservationsRequest} message ListReservationsRequest + * @param {google.cloud.compute.v1beta.ListReservationSlotsRequest} message ListReservationSlotsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListReservationsRequest.toObject = function toObject(message, options) { + ListReservationSlotsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { object.zone = ""; object.project = ""; + object.parentName = ""; } if (message.zone != null && message.hasOwnProperty("zone")) object.zone = message.zone; @@ -1016825,6 +1028042,8 @@ if (options.oneofs) object._filter = "filter"; } + if (message.parentName != null && message.hasOwnProperty("parentName")) + object.parentName = message.parentName; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { object.returnPartialSuccess = message.returnPartialSuccess; if (options.oneofs) @@ -1016834,58 +1028053,59 @@ }; /** - * Converts this ListReservationsRequest to JSON. + * Converts this ListReservationSlotsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @instance * @returns {Object.} JSON object */ - ListReservationsRequest.prototype.toJSON = function toJSON() { + ListReservationSlotsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListReservationsRequest + * Gets the default type url for ListReservationSlotsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @memberof google.cloud.compute.v1beta.ListReservationSlotsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListReservationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListReservationSlotsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListReservationsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListReservationSlotsRequest"; }; - return ListReservationsRequest; + return ListReservationSlotsRequest; })(); - v1beta.ListResourcePoliciesRequest = (function() { + v1beta.ListReservationSubBlocksRequest = (function() { /** - * Properties of a ListResourcePoliciesRequest. + * Properties of a ListReservationSubBlocksRequest. * @memberof google.cloud.compute.v1beta - * @interface IListResourcePoliciesRequest - * @property {string|null} [filter] ListResourcePoliciesRequest filter - * @property {number|null} [maxResults] ListResourcePoliciesRequest maxResults - * @property {string|null} [orderBy] ListResourcePoliciesRequest orderBy - * @property {string|null} [pageToken] ListResourcePoliciesRequest pageToken - * @property {string|null} [project] ListResourcePoliciesRequest project - * @property {string|null} [region] ListResourcePoliciesRequest region - * @property {boolean|null} [returnPartialSuccess] ListResourcePoliciesRequest returnPartialSuccess + * @interface IListReservationSubBlocksRequest + * @property {string|null} [filter] ListReservationSubBlocksRequest filter + * @property {number|null} [maxResults] ListReservationSubBlocksRequest maxResults + * @property {string|null} [orderBy] ListReservationSubBlocksRequest orderBy + * @property {string|null} [pageToken] ListReservationSubBlocksRequest pageToken + * @property {string|null} [parentName] ListReservationSubBlocksRequest parentName + * @property {string|null} [project] ListReservationSubBlocksRequest project + * @property {boolean|null} [returnPartialSuccess] ListReservationSubBlocksRequest returnPartialSuccess + * @property {string|null} [zone] ListReservationSubBlocksRequest zone */ /** - * Constructs a new ListResourcePoliciesRequest. + * Constructs a new ListReservationSubBlocksRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListResourcePoliciesRequest. - * @implements IListResourcePoliciesRequest + * @classdesc Represents a ListReservationSubBlocksRequest. + * @implements IListReservationSubBlocksRequest * @constructor - * @param {google.cloud.compute.v1beta.IListResourcePoliciesRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListReservationSubBlocksRequest=} [properties] Properties to set */ - function ListResourcePoliciesRequest(properties) { + function ListReservationSubBlocksRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1016893,163 +1028113,173 @@ } /** - * ListResourcePoliciesRequest filter. + * ListReservationSubBlocksRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @instance */ - ListResourcePoliciesRequest.prototype.filter = null; + ListReservationSubBlocksRequest.prototype.filter = null; /** - * ListResourcePoliciesRequest maxResults. + * ListReservationSubBlocksRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @instance */ - ListResourcePoliciesRequest.prototype.maxResults = null; + ListReservationSubBlocksRequest.prototype.maxResults = null; /** - * ListResourcePoliciesRequest orderBy. + * ListReservationSubBlocksRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @instance */ - ListResourcePoliciesRequest.prototype.orderBy = null; + ListReservationSubBlocksRequest.prototype.orderBy = null; /** - * ListResourcePoliciesRequest pageToken. + * ListReservationSubBlocksRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @instance */ - ListResourcePoliciesRequest.prototype.pageToken = null; + ListReservationSubBlocksRequest.prototype.pageToken = null; /** - * ListResourcePoliciesRequest project. - * @member {string} project - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * ListReservationSubBlocksRequest parentName. + * @member {string} parentName + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @instance */ - ListResourcePoliciesRequest.prototype.project = ""; + ListReservationSubBlocksRequest.prototype.parentName = ""; /** - * ListResourcePoliciesRequest region. - * @member {string} region - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * ListReservationSubBlocksRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @instance */ - ListResourcePoliciesRequest.prototype.region = ""; + ListReservationSubBlocksRequest.prototype.project = ""; /** - * ListResourcePoliciesRequest returnPartialSuccess. + * ListReservationSubBlocksRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @instance */ - ListResourcePoliciesRequest.prototype.returnPartialSuccess = null; + ListReservationSubBlocksRequest.prototype.returnPartialSuccess = null; + + /** + * ListReservationSubBlocksRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest + * @instance + */ + ListReservationSubBlocksRequest.prototype.zone = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListResourcePoliciesRequest.prototype, "_filter", { + Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListResourcePoliciesRequest.prototype, "_maxResults", { + Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListResourcePoliciesRequest.prototype, "_orderBy", { + Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListResourcePoliciesRequest.prototype, "_pageToken", { + Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListResourcePoliciesRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListReservationSubBlocksRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListResourcePoliciesRequest instance using the specified properties. + * Creates a new ListReservationSubBlocksRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static - * @param {google.cloud.compute.v1beta.IListResourcePoliciesRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListResourcePoliciesRequest} ListResourcePoliciesRequest instance + * @param {google.cloud.compute.v1beta.IListReservationSubBlocksRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} ListReservationSubBlocksRequest instance */ - ListResourcePoliciesRequest.create = function create(properties) { - return new ListResourcePoliciesRequest(properties); + ListReservationSubBlocksRequest.create = function create(properties) { + return new ListReservationSubBlocksRequest(properties); }; /** - * Encodes the specified ListResourcePoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListResourcePoliciesRequest.verify|verify} messages. + * Encodes the specified ListReservationSubBlocksRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationSubBlocksRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static - * @param {google.cloud.compute.v1beta.IListResourcePoliciesRequest} message ListResourcePoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListReservationSubBlocksRequest} message ListReservationSubBlocksRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListResourcePoliciesRequest.encode = function encode(message, writer) { + ListReservationSubBlocksRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); - if (message.region != null && Object.hasOwnProperty.call(message, "region")) - writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); if (message.project != null && Object.hasOwnProperty.call(message, "project")) writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); + if (message.parentName != null && Object.hasOwnProperty.call(message, "parentName")) + writer.uint32(/* id 478151936, wireType 2 =*/3825215490).string(message.parentName); if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); return writer; }; /** - * Encodes the specified ListResourcePoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListResourcePoliciesRequest.verify|verify} messages. + * Encodes the specified ListReservationSubBlocksRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationSubBlocksRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static - * @param {google.cloud.compute.v1beta.IListResourcePoliciesRequest} message ListResourcePoliciesRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListReservationSubBlocksRequest} message ListReservationSubBlocksRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListResourcePoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListReservationSubBlocksRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListResourcePoliciesRequest message from the specified reader or buffer. + * Decodes a ListReservationSubBlocksRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListResourcePoliciesRequest} ListResourcePoliciesRequest + * @returns {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} ListReservationSubBlocksRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListResourcePoliciesRequest.decode = function decode(reader, length, error) { + ListReservationSubBlocksRequest.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.cloud.compute.v1beta.ListResourcePoliciesRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListReservationSubBlocksRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1017071,18 +1028301,22 @@ message.pageToken = reader.string(); break; } - case 227560217: { - message.project = reader.string(); + case 478151936: { + message.parentName = reader.string(); break; } - case 138946292: { - message.region = reader.string(); + case 227560217: { + message.project = reader.string(); break; } case 517198390: { message.returnPartialSuccess = reader.bool(); break; } + case 3744684: { + message.zone = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -1017092,30 +1028326,30 @@ }; /** - * Decodes a ListResourcePoliciesRequest message from the specified reader or buffer, length delimited. + * Decodes a ListReservationSubBlocksRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListResourcePoliciesRequest} ListResourcePoliciesRequest + * @returns {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} ListReservationSubBlocksRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListResourcePoliciesRequest.decodeDelimited = function decodeDelimited(reader) { + ListReservationSubBlocksRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListResourcePoliciesRequest message. + * Verifies a ListReservationSubBlocksRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListResourcePoliciesRequest.verify = function verify(message) { + ListReservationSubBlocksRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1017139,32 +1028373,35 @@ if (!$util.isString(message.pageToken)) return "pageToken: string expected"; } + if (message.parentName != null && message.hasOwnProperty("parentName")) + if (!$util.isString(message.parentName)) + return "parentName: string expected"; if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) return "project: string expected"; - if (message.region != null && message.hasOwnProperty("region")) - if (!$util.isString(message.region)) - return "region: string expected"; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { properties._returnPartialSuccess = 1; if (typeof message.returnPartialSuccess !== "boolean") return "returnPartialSuccess: boolean expected"; } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; return null; }; /** - * Creates a ListResourcePoliciesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListReservationSubBlocksRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListResourcePoliciesRequest} ListResourcePoliciesRequest + * @returns {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} ListReservationSubBlocksRequest */ - ListResourcePoliciesRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListResourcePoliciesRequest) + ListReservationSubBlocksRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListReservationSubBlocksRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListResourcePoliciesRequest(); + var message = new $root.google.cloud.compute.v1beta.ListReservationSubBlocksRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1017173,32 +1028410,37 @@ message.orderBy = String(object.orderBy); if (object.pageToken != null) message.pageToken = String(object.pageToken); + if (object.parentName != null) + message.parentName = String(object.parentName); if (object.project != null) message.project = String(object.project); - if (object.region != null) - message.region = String(object.region); if (object.returnPartialSuccess != null) message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + if (object.zone != null) + message.zone = String(object.zone); return message; }; /** - * Creates a plain object from a ListResourcePoliciesRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListReservationSubBlocksRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static - * @param {google.cloud.compute.v1beta.ListResourcePoliciesRequest} message ListResourcePoliciesRequest + * @param {google.cloud.compute.v1beta.ListReservationSubBlocksRequest} message ListReservationSubBlocksRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListResourcePoliciesRequest.toObject = function toObject(message, options) { + ListReservationSubBlocksRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.region = ""; + object.zone = ""; object.project = ""; + object.parentName = ""; } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; if (message.pageToken != null && message.hasOwnProperty("pageToken")) { object.pageToken = message.pageToken; if (options.oneofs) @@ -1017209,8 +1028451,6 @@ if (options.oneofs) object._maxResults = "maxResults"; } - if (message.region != null && message.hasOwnProperty("region")) - object.region = message.region; if (message.orderBy != null && message.hasOwnProperty("orderBy")) { object.orderBy = message.orderBy; if (options.oneofs) @@ -1017223,6 +1028463,8 @@ if (options.oneofs) object._filter = "filter"; } + if (message.parentName != null && message.hasOwnProperty("parentName")) + object.parentName = message.parentName; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { object.returnPartialSuccess = message.returnPartialSuccess; if (options.oneofs) @@ -1017232,57 +1028474,58 @@ }; /** - * Converts this ListResourcePoliciesRequest to JSON. + * Converts this ListReservationSubBlocksRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @instance * @returns {Object.} JSON object */ - ListResourcePoliciesRequest.prototype.toJSON = function toJSON() { + ListReservationSubBlocksRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListResourcePoliciesRequest + * Gets the default type url for ListReservationSubBlocksRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @memberof google.cloud.compute.v1beta.ListReservationSubBlocksRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListResourcePoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListReservationSubBlocksRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListResourcePoliciesRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListReservationSubBlocksRequest"; }; - return ListResourcePoliciesRequest; + return ListReservationSubBlocksRequest; })(); - v1beta.ListRolloutPlansRequest = (function() { + v1beta.ListReservationsRequest = (function() { /** - * Properties of a ListRolloutPlansRequest. + * Properties of a ListReservationsRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRolloutPlansRequest - * @property {string|null} [filter] ListRolloutPlansRequest filter - * @property {number|null} [maxResults] ListRolloutPlansRequest maxResults - * @property {string|null} [orderBy] ListRolloutPlansRequest orderBy - * @property {string|null} [pageToken] ListRolloutPlansRequest pageToken - * @property {string|null} [project] ListRolloutPlansRequest project - * @property {boolean|null} [returnPartialSuccess] ListRolloutPlansRequest returnPartialSuccess + * @interface IListReservationsRequest + * @property {string|null} [filter] ListReservationsRequest filter + * @property {number|null} [maxResults] ListReservationsRequest maxResults + * @property {string|null} [orderBy] ListReservationsRequest orderBy + * @property {string|null} [pageToken] ListReservationsRequest pageToken + * @property {string|null} [project] ListReservationsRequest project + * @property {boolean|null} [returnPartialSuccess] ListReservationsRequest returnPartialSuccess + * @property {string|null} [zone] ListReservationsRequest zone */ /** - * Constructs a new ListRolloutPlansRequest. + * Constructs a new ListReservationsRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRolloutPlansRequest. - * @implements IListRolloutPlansRequest + * @classdesc Represents a ListReservationsRequest. + * @implements IListReservationsRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRolloutPlansRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListReservationsRequest=} [properties] Properties to set */ - function ListRolloutPlansRequest(properties) { + function ListReservationsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1017290,110 +1028533,120 @@ } /** - * ListRolloutPlansRequest filter. + * ListReservationsRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @instance */ - ListRolloutPlansRequest.prototype.filter = null; + ListReservationsRequest.prototype.filter = null; /** - * ListRolloutPlansRequest maxResults. + * ListReservationsRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @instance */ - ListRolloutPlansRequest.prototype.maxResults = null; + ListReservationsRequest.prototype.maxResults = null; /** - * ListRolloutPlansRequest orderBy. + * ListReservationsRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @instance */ - ListRolloutPlansRequest.prototype.orderBy = null; + ListReservationsRequest.prototype.orderBy = null; /** - * ListRolloutPlansRequest pageToken. + * ListReservationsRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @instance */ - ListRolloutPlansRequest.prototype.pageToken = null; + ListReservationsRequest.prototype.pageToken = null; /** - * ListRolloutPlansRequest project. + * ListReservationsRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @instance */ - ListRolloutPlansRequest.prototype.project = ""; + ListReservationsRequest.prototype.project = ""; /** - * ListRolloutPlansRequest returnPartialSuccess. + * ListReservationsRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @instance */ - ListRolloutPlansRequest.prototype.returnPartialSuccess = null; + ListReservationsRequest.prototype.returnPartialSuccess = null; + + /** + * ListReservationsRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.ListReservationsRequest + * @instance + */ + ListReservationsRequest.prototype.zone = ""; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutPlansRequest.prototype, "_filter", { + Object.defineProperty(ListReservationsRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutPlansRequest.prototype, "_maxResults", { + Object.defineProperty(ListReservationsRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutPlansRequest.prototype, "_orderBy", { + Object.defineProperty(ListReservationsRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutPlansRequest.prototype, "_pageToken", { + Object.defineProperty(ListReservationsRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutPlansRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListReservationsRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRolloutPlansRequest instance using the specified properties. + * Creates a new ListReservationsRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static - * @param {google.cloud.compute.v1beta.IListRolloutPlansRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRolloutPlansRequest} ListRolloutPlansRequest instance + * @param {google.cloud.compute.v1beta.IListReservationsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListReservationsRequest} ListReservationsRequest instance */ - ListRolloutPlansRequest.create = function create(properties) { - return new ListRolloutPlansRequest(properties); + ListReservationsRequest.create = function create(properties) { + return new ListReservationsRequest(properties); }; /** - * Encodes the specified ListRolloutPlansRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRolloutPlansRequest.verify|verify} messages. + * Encodes the specified ListReservationsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationsRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static - * @param {google.cloud.compute.v1beta.IListRolloutPlansRequest} message ListRolloutPlansRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListReservationsRequest} message ListReservationsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRolloutPlansRequest.encode = function encode(message, writer) { + ListReservationsRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) @@ -1017410,33 +1028663,33 @@ }; /** - * Encodes the specified ListRolloutPlansRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRolloutPlansRequest.verify|verify} messages. + * Encodes the specified ListReservationsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListReservationsRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static - * @param {google.cloud.compute.v1beta.IListRolloutPlansRequest} message ListRolloutPlansRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListReservationsRequest} message ListReservationsRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRolloutPlansRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListReservationsRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRolloutPlansRequest message from the specified reader or buffer. + * Decodes a ListReservationsRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRolloutPlansRequest} ListRolloutPlansRequest + * @returns {google.cloud.compute.v1beta.ListReservationsRequest} ListReservationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRolloutPlansRequest.decode = function decode(reader, length, error) { + ListReservationsRequest.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.cloud.compute.v1beta.ListRolloutPlansRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListReservationsRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1017466,6 +1028719,10 @@ message.returnPartialSuccess = reader.bool(); break; } + case 3744684: { + message.zone = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -1017475,30 +1028732,30 @@ }; /** - * Decodes a ListRolloutPlansRequest message from the specified reader or buffer, length delimited. + * Decodes a ListReservationsRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRolloutPlansRequest} ListRolloutPlansRequest + * @returns {google.cloud.compute.v1beta.ListReservationsRequest} ListReservationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRolloutPlansRequest.decodeDelimited = function decodeDelimited(reader) { + ListReservationsRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRolloutPlansRequest message. + * Verifies a ListReservationsRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRolloutPlansRequest.verify = function verify(message) { + ListReservationsRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1017530,21 +1028787,24 @@ if (typeof message.returnPartialSuccess !== "boolean") return "returnPartialSuccess: boolean expected"; } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; return null; }; /** - * Creates a ListRolloutPlansRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListReservationsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRolloutPlansRequest} ListRolloutPlansRequest + * @returns {google.cloud.compute.v1beta.ListReservationsRequest} ListReservationsRequest */ - ListRolloutPlansRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRolloutPlansRequest) + ListReservationsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListReservationsRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRolloutPlansRequest(); + var message = new $root.google.cloud.compute.v1beta.ListReservationsRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1017557,24 +1028817,30 @@ message.project = String(object.project); if (object.returnPartialSuccess != null) message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + if (object.zone != null) + message.zone = String(object.zone); return message; }; /** - * Creates a plain object from a ListRolloutPlansRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListReservationsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static - * @param {google.cloud.compute.v1beta.ListRolloutPlansRequest} message ListRolloutPlansRequest + * @param {google.cloud.compute.v1beta.ListReservationsRequest} message ListReservationsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRolloutPlansRequest.toObject = function toObject(message, options) { + ListReservationsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) + if (options.defaults) { + object.zone = ""; object.project = ""; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; if (message.pageToken != null && message.hasOwnProperty("pageToken")) { object.pageToken = message.pageToken; if (options.oneofs) @@ -1017606,57 +1028872,58 @@ }; /** - * Converts this ListRolloutPlansRequest to JSON. + * Converts this ListReservationsRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @instance * @returns {Object.} JSON object */ - ListRolloutPlansRequest.prototype.toJSON = function toJSON() { + ListReservationsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRolloutPlansRequest + * Gets the default type url for ListReservationsRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @memberof google.cloud.compute.v1beta.ListReservationsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRolloutPlansRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListReservationsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRolloutPlansRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListReservationsRequest"; }; - return ListRolloutPlansRequest; + return ListReservationsRequest; })(); - v1beta.ListRolloutsRequest = (function() { + v1beta.ListResourcePoliciesRequest = (function() { /** - * Properties of a ListRolloutsRequest. + * Properties of a ListResourcePoliciesRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRolloutsRequest - * @property {string|null} [filter] ListRolloutsRequest filter - * @property {number|null} [maxResults] ListRolloutsRequest maxResults - * @property {string|null} [orderBy] ListRolloutsRequest orderBy - * @property {string|null} [pageToken] ListRolloutsRequest pageToken - * @property {string|null} [project] ListRolloutsRequest project - * @property {boolean|null} [returnPartialSuccess] ListRolloutsRequest returnPartialSuccess + * @interface IListResourcePoliciesRequest + * @property {string|null} [filter] ListResourcePoliciesRequest filter + * @property {number|null} [maxResults] ListResourcePoliciesRequest maxResults + * @property {string|null} [orderBy] ListResourcePoliciesRequest orderBy + * @property {string|null} [pageToken] ListResourcePoliciesRequest pageToken + * @property {string|null} [project] ListResourcePoliciesRequest project + * @property {string|null} [region] ListResourcePoliciesRequest region + * @property {boolean|null} [returnPartialSuccess] ListResourcePoliciesRequest returnPartialSuccess */ /** - * Constructs a new ListRolloutsRequest. + * Constructs a new ListResourcePoliciesRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRolloutsRequest. - * @implements IListRolloutsRequest + * @classdesc Represents a ListResourcePoliciesRequest. + * @implements IListResourcePoliciesRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRolloutsRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListResourcePoliciesRequest=} [properties] Properties to set */ - function ListRolloutsRequest(properties) { + function ListResourcePoliciesRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1017664,114 +1028931,124 @@ } /** - * ListRolloutsRequest filter. + * ListResourcePoliciesRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @instance */ - ListRolloutsRequest.prototype.filter = null; + ListResourcePoliciesRequest.prototype.filter = null; /** - * ListRolloutsRequest maxResults. + * ListResourcePoliciesRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @instance */ - ListRolloutsRequest.prototype.maxResults = null; + ListResourcePoliciesRequest.prototype.maxResults = null; /** - * ListRolloutsRequest orderBy. + * ListResourcePoliciesRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @instance */ - ListRolloutsRequest.prototype.orderBy = null; + ListResourcePoliciesRequest.prototype.orderBy = null; /** - * ListRolloutsRequest pageToken. + * ListResourcePoliciesRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @instance */ - ListRolloutsRequest.prototype.pageToken = null; + ListResourcePoliciesRequest.prototype.pageToken = null; /** - * ListRolloutsRequest project. + * ListResourcePoliciesRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @instance */ - ListRolloutsRequest.prototype.project = ""; + ListResourcePoliciesRequest.prototype.project = ""; /** - * ListRolloutsRequest returnPartialSuccess. + * ListResourcePoliciesRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest + * @instance + */ + ListResourcePoliciesRequest.prototype.region = ""; + + /** + * ListResourcePoliciesRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @instance */ - ListRolloutsRequest.prototype.returnPartialSuccess = null; + ListResourcePoliciesRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutsRequest.prototype, "_filter", { + Object.defineProperty(ListResourcePoliciesRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutsRequest.prototype, "_maxResults", { + Object.defineProperty(ListResourcePoliciesRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutsRequest.prototype, "_orderBy", { + Object.defineProperty(ListResourcePoliciesRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutsRequest.prototype, "_pageToken", { + Object.defineProperty(ListResourcePoliciesRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRolloutsRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListResourcePoliciesRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRolloutsRequest instance using the specified properties. + * Creates a new ListResourcePoliciesRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRolloutsRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRolloutsRequest} ListRolloutsRequest instance + * @param {google.cloud.compute.v1beta.IListResourcePoliciesRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListResourcePoliciesRequest} ListResourcePoliciesRequest instance */ - ListRolloutsRequest.create = function create(properties) { - return new ListRolloutsRequest(properties); + ListResourcePoliciesRequest.create = function create(properties) { + return new ListResourcePoliciesRequest(properties); }; /** - * Encodes the specified ListRolloutsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRolloutsRequest.verify|verify} messages. + * Encodes the specified ListResourcePoliciesRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListResourcePoliciesRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRolloutsRequest} message ListRolloutsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListResourcePoliciesRequest} message ListResourcePoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRolloutsRequest.encode = function encode(message, writer) { + ListResourcePoliciesRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); if (message.project != null && Object.hasOwnProperty.call(message, "project")) @@ -1017784,33 +1029061,33 @@ }; /** - * Encodes the specified ListRolloutsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRolloutsRequest.verify|verify} messages. + * Encodes the specified ListResourcePoliciesRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListResourcePoliciesRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static - * @param {google.cloud.compute.v1beta.IListRolloutsRequest} message ListRolloutsRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListResourcePoliciesRequest} message ListResourcePoliciesRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRolloutsRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListResourcePoliciesRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRolloutsRequest message from the specified reader or buffer. + * Decodes a ListResourcePoliciesRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRolloutsRequest} ListRolloutsRequest + * @returns {google.cloud.compute.v1beta.ListResourcePoliciesRequest} ListResourcePoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRolloutsRequest.decode = function decode(reader, length, error) { + ListResourcePoliciesRequest.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.cloud.compute.v1beta.ListRolloutsRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListResourcePoliciesRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1017836,6 +1029113,10 @@ message.project = reader.string(); break; } + case 138946292: { + message.region = reader.string(); + break; + } case 517198390: { message.returnPartialSuccess = reader.bool(); break; @@ -1017849,30 +1029130,30 @@ }; /** - * Decodes a ListRolloutsRequest message from the specified reader or buffer, length delimited. + * Decodes a ListResourcePoliciesRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRolloutsRequest} ListRolloutsRequest + * @returns {google.cloud.compute.v1beta.ListResourcePoliciesRequest} ListResourcePoliciesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRolloutsRequest.decodeDelimited = function decodeDelimited(reader) { + ListResourcePoliciesRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRolloutsRequest message. + * Verifies a ListResourcePoliciesRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRolloutsRequest.verify = function verify(message) { + ListResourcePoliciesRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1017899,6 +1029180,9 @@ if (message.project != null && message.hasOwnProperty("project")) if (!$util.isString(message.project)) return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { properties._returnPartialSuccess = 1; if (typeof message.returnPartialSuccess !== "boolean") @@ -1017908,17 +1029192,17 @@ }; /** - * Creates a ListRolloutsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListResourcePoliciesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ListRolloutsRequest} ListRolloutsRequest + * @returns {google.cloud.compute.v1beta.ListResourcePoliciesRequest} ListResourcePoliciesRequest */ - ListRolloutsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ListRolloutsRequest) + ListResourcePoliciesRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListResourcePoliciesRequest) return object; - var message = new $root.google.cloud.compute.v1beta.ListRolloutsRequest(); + var message = new $root.google.cloud.compute.v1beta.ListResourcePoliciesRequest(); if (object.filter != null) message.filter = String(object.filter); if (object.maxResults != null) @@ -1017929,26 +1029213,30 @@ message.pageToken = String(object.pageToken); if (object.project != null) message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); if (object.returnPartialSuccess != null) message.returnPartialSuccess = Boolean(object.returnPartialSuccess); return message; }; /** - * Creates a plain object from a ListRolloutsRequest message. Also converts values to other types if specified. + * Creates a plain object from a ListResourcePoliciesRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static - * @param {google.cloud.compute.v1beta.ListRolloutsRequest} message ListRolloutsRequest + * @param {google.cloud.compute.v1beta.ListResourcePoliciesRequest} message ListResourcePoliciesRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListRolloutsRequest.toObject = function toObject(message, options) { + ListResourcePoliciesRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) + if (options.defaults) { + object.region = ""; object.project = ""; + } if (message.pageToken != null && message.hasOwnProperty("pageToken")) { object.pageToken = message.pageToken; if (options.oneofs) @@ -1017959,6 +1029247,8 @@ if (options.oneofs) object._maxResults = "maxResults"; } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; if (message.orderBy != null && message.hasOwnProperty("orderBy")) { object.orderBy = message.orderBy; if (options.oneofs) @@ -1017980,59 +1029270,57 @@ }; /** - * Converts this ListRolloutsRequest to JSON. + * Converts this ListResourcePoliciesRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @instance * @returns {Object.} JSON object */ - ListRolloutsRequest.prototype.toJSON = function toJSON() { + ListResourcePoliciesRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListRolloutsRequest + * Gets the default type url for ListResourcePoliciesRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @memberof google.cloud.compute.v1beta.ListResourcePoliciesRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListRolloutsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListResourcePoliciesRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRolloutsRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListResourcePoliciesRequest"; }; - return ListRolloutsRequest; + return ListResourcePoliciesRequest; })(); - v1beta.ListRoutePoliciesRoutersRequest = (function() { + v1beta.ListRolloutPlansRequest = (function() { /** - * Properties of a ListRoutePoliciesRoutersRequest. + * Properties of a ListRolloutPlansRequest. * @memberof google.cloud.compute.v1beta - * @interface IListRoutePoliciesRoutersRequest - * @property {string|null} [filter] ListRoutePoliciesRoutersRequest filter - * @property {number|null} [maxResults] ListRoutePoliciesRoutersRequest maxResults - * @property {string|null} [orderBy] ListRoutePoliciesRoutersRequest orderBy - * @property {string|null} [pageToken] ListRoutePoliciesRoutersRequest pageToken - * @property {string|null} [project] ListRoutePoliciesRoutersRequest project - * @property {string|null} [region] ListRoutePoliciesRoutersRequest region - * @property {boolean|null} [returnPartialSuccess] ListRoutePoliciesRoutersRequest returnPartialSuccess - * @property {string|null} [router] ListRoutePoliciesRoutersRequest router + * @interface IListRolloutPlansRequest + * @property {string|null} [filter] ListRolloutPlansRequest filter + * @property {number|null} [maxResults] ListRolloutPlansRequest maxResults + * @property {string|null} [orderBy] ListRolloutPlansRequest orderBy + * @property {string|null} [pageToken] ListRolloutPlansRequest pageToken + * @property {string|null} [project] ListRolloutPlansRequest project + * @property {boolean|null} [returnPartialSuccess] ListRolloutPlansRequest returnPartialSuccess */ /** - * Constructs a new ListRoutePoliciesRoutersRequest. + * Constructs a new ListRolloutPlansRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ListRoutePoliciesRoutersRequest. - * @implements IListRoutePoliciesRoutersRequest + * @classdesc Represents a ListRolloutPlansRequest. + * @implements IListRolloutPlansRequest * @constructor - * @param {google.cloud.compute.v1beta.IListRoutePoliciesRoutersRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IListRolloutPlansRequest=} [properties] Properties to set */ - function ListRoutePoliciesRoutersRequest(properties) { + function ListRolloutPlansRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1018040,134 +1029328,114 @@ } /** - * ListRoutePoliciesRoutersRequest filter. + * ListRolloutPlansRequest filter. * @member {string|null|undefined} filter - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @instance */ - ListRoutePoliciesRoutersRequest.prototype.filter = null; + ListRolloutPlansRequest.prototype.filter = null; /** - * ListRoutePoliciesRoutersRequest maxResults. + * ListRolloutPlansRequest maxResults. * @member {number|null|undefined} maxResults - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @instance */ - ListRoutePoliciesRoutersRequest.prototype.maxResults = null; + ListRolloutPlansRequest.prototype.maxResults = null; /** - * ListRoutePoliciesRoutersRequest orderBy. + * ListRolloutPlansRequest orderBy. * @member {string|null|undefined} orderBy - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @instance */ - ListRoutePoliciesRoutersRequest.prototype.orderBy = null; + ListRolloutPlansRequest.prototype.orderBy = null; /** - * ListRoutePoliciesRoutersRequest pageToken. + * ListRolloutPlansRequest pageToken. * @member {string|null|undefined} pageToken - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @instance */ - ListRoutePoliciesRoutersRequest.prototype.pageToken = null; + ListRolloutPlansRequest.prototype.pageToken = null; /** - * ListRoutePoliciesRoutersRequest project. + * ListRolloutPlansRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest - * @instance - */ - ListRoutePoliciesRoutersRequest.prototype.project = ""; - - /** - * ListRoutePoliciesRoutersRequest region. - * @member {string} region - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @instance */ - ListRoutePoliciesRoutersRequest.prototype.region = ""; + ListRolloutPlansRequest.prototype.project = ""; /** - * ListRoutePoliciesRoutersRequest returnPartialSuccess. + * ListRolloutPlansRequest returnPartialSuccess. * @member {boolean|null|undefined} returnPartialSuccess - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest - * @instance - */ - ListRoutePoliciesRoutersRequest.prototype.returnPartialSuccess = null; - - /** - * ListRoutePoliciesRoutersRequest router. - * @member {string} router - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @instance */ - ListRoutePoliciesRoutersRequest.prototype.router = ""; + ListRolloutPlansRequest.prototype.returnPartialSuccess = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_filter", { + Object.defineProperty(ListRolloutPlansRequest.prototype, "_filter", { get: $util.oneOfGetter($oneOfFields = ["filter"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_maxResults", { + Object.defineProperty(ListRolloutPlansRequest.prototype, "_maxResults", { get: $util.oneOfGetter($oneOfFields = ["maxResults"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_orderBy", { + Object.defineProperty(ListRolloutPlansRequest.prototype, "_orderBy", { get: $util.oneOfGetter($oneOfFields = ["orderBy"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_pageToken", { + Object.defineProperty(ListRolloutPlansRequest.prototype, "_pageToken", { get: $util.oneOfGetter($oneOfFields = ["pageToken"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_returnPartialSuccess", { + Object.defineProperty(ListRolloutPlansRequest.prototype, "_returnPartialSuccess", { get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ListRoutePoliciesRoutersRequest instance using the specified properties. + * Creates a new ListRolloutPlansRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @static - * @param {google.cloud.compute.v1beta.IListRoutePoliciesRoutersRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest} ListRoutePoliciesRoutersRequest instance + * @param {google.cloud.compute.v1beta.IListRolloutPlansRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRolloutPlansRequest} ListRolloutPlansRequest instance */ - ListRoutePoliciesRoutersRequest.create = function create(properties) { - return new ListRoutePoliciesRoutersRequest(properties); + ListRolloutPlansRequest.create = function create(properties) { + return new ListRolloutPlansRequest(properties); }; /** - * Encodes the specified ListRoutePoliciesRoutersRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest.verify|verify} messages. + * Encodes the specified ListRolloutPlansRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRolloutPlansRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @static - * @param {google.cloud.compute.v1beta.IListRoutePoliciesRoutersRequest} message ListRoutePoliciesRoutersRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRolloutPlansRequest} message ListRolloutPlansRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRoutePoliciesRoutersRequest.encode = function encode(message, writer) { + ListRolloutPlansRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); - if (message.region != null && Object.hasOwnProperty.call(message, "region")) - writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); - if (message.router != null && Object.hasOwnProperty.call(message, "router")) - writer.uint32(/* id 148608841, wireType 2 =*/1188870730).string(message.router); if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); if (message.project != null && Object.hasOwnProperty.call(message, "project")) @@ -1018180,33 +1029448,33 @@ }; /** - * Encodes the specified ListRoutePoliciesRoutersRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest.verify|verify} messages. + * Encodes the specified ListRolloutPlansRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRolloutPlansRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @static - * @param {google.cloud.compute.v1beta.IListRoutePoliciesRoutersRequest} message ListRoutePoliciesRoutersRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.IListRolloutPlansRequest} message ListRolloutPlansRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ListRoutePoliciesRoutersRequest.encodeDelimited = function encodeDelimited(message, writer) { + ListRolloutPlansRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ListRoutePoliciesRoutersRequest message from the specified reader or buffer. + * Decodes a ListRolloutPlansRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest} ListRoutePoliciesRoutersRequest + * @returns {google.cloud.compute.v1beta.ListRolloutPlansRequest} ListRolloutPlansRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRoutePoliciesRoutersRequest.decode = function decode(reader, length, error) { + ListRolloutPlansRequest.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.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ListRolloutPlansRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1018232,18 +1029500,10 @@ message.project = reader.string(); break; } - case 138946292: { - message.region = reader.string(); - break; - } case 517198390: { message.returnPartialSuccess = reader.bool(); break; } - case 148608841: { - message.router = reader.string(); - break; - } default: reader.skipType(tag & 7); break; @@ -1018253,30 +1029513,808 @@ }; /** - * Decodes a ListRoutePoliciesRoutersRequest message from the specified reader or buffer, length delimited. + * Decodes a ListRolloutPlansRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest} ListRoutePoliciesRoutersRequest + * @returns {google.cloud.compute.v1beta.ListRolloutPlansRequest} ListRolloutPlansRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ListRoutePoliciesRoutersRequest.decodeDelimited = function decodeDelimited(reader) { + ListRolloutPlansRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ListRoutePoliciesRoutersRequest message. + * Verifies a ListRolloutPlansRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ListRoutePoliciesRoutersRequest.verify = function verify(message) { + ListRolloutPlansRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.filter != null && message.hasOwnProperty("filter")) { + properties._filter = 1; + if (!$util.isString(message.filter)) + return "filter: string expected"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + properties._maxResults = 1; + if (!$util.isInteger(message.maxResults)) + return "maxResults: integer expected"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + properties._orderBy = 1; + if (!$util.isString(message.orderBy)) + return "orderBy: string expected"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + properties._pageToken = 1; + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + properties._returnPartialSuccess = 1; + if (typeof message.returnPartialSuccess !== "boolean") + return "returnPartialSuccess: boolean expected"; + } + return null; + }; + + /** + * Creates a ListRolloutPlansRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ListRolloutPlansRequest} ListRolloutPlansRequest + */ + ListRolloutPlansRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRolloutPlansRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.ListRolloutPlansRequest(); + if (object.filter != null) + message.filter = String(object.filter); + if (object.maxResults != null) + message.maxResults = object.maxResults >>> 0; + if (object.orderBy != null) + message.orderBy = String(object.orderBy); + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.project != null) + message.project = String(object.project); + if (object.returnPartialSuccess != null) + message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + return message; + }; + + /** + * Creates a plain object from a ListRolloutPlansRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @static + * @param {google.cloud.compute.v1beta.ListRolloutPlansRequest} message ListRolloutPlansRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListRolloutPlansRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.project = ""; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + object.pageToken = message.pageToken; + if (options.oneofs) + object._pageToken = "pageToken"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + object.maxResults = message.maxResults; + if (options.oneofs) + object._maxResults = "maxResults"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + object.orderBy = message.orderBy; + if (options.oneofs) + object._orderBy = "orderBy"; + } + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = message.filter; + if (options.oneofs) + object._filter = "filter"; + } + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + object.returnPartialSuccess = message.returnPartialSuccess; + if (options.oneofs) + object._returnPartialSuccess = "returnPartialSuccess"; + } + return object; + }; + + /** + * Converts this ListRolloutPlansRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @instance + * @returns {Object.} JSON object + */ + ListRolloutPlansRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListRolloutPlansRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ListRolloutPlansRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListRolloutPlansRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRolloutPlansRequest"; + }; + + return ListRolloutPlansRequest; + })(); + + v1beta.ListRolloutsRequest = (function() { + + /** + * Properties of a ListRolloutsRequest. + * @memberof google.cloud.compute.v1beta + * @interface IListRolloutsRequest + * @property {string|null} [filter] ListRolloutsRequest filter + * @property {number|null} [maxResults] ListRolloutsRequest maxResults + * @property {string|null} [orderBy] ListRolloutsRequest orderBy + * @property {string|null} [pageToken] ListRolloutsRequest pageToken + * @property {string|null} [project] ListRolloutsRequest project + * @property {boolean|null} [returnPartialSuccess] ListRolloutsRequest returnPartialSuccess + */ + + /** + * Constructs a new ListRolloutsRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ListRolloutsRequest. + * @implements IListRolloutsRequest + * @constructor + * @param {google.cloud.compute.v1beta.IListRolloutsRequest=} [properties] Properties to set + */ + function ListRolloutsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListRolloutsRequest filter. + * @member {string|null|undefined} filter + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @instance + */ + ListRolloutsRequest.prototype.filter = null; + + /** + * ListRolloutsRequest maxResults. + * @member {number|null|undefined} maxResults + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @instance + */ + ListRolloutsRequest.prototype.maxResults = null; + + /** + * ListRolloutsRequest orderBy. + * @member {string|null|undefined} orderBy + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @instance + */ + ListRolloutsRequest.prototype.orderBy = null; + + /** + * ListRolloutsRequest pageToken. + * @member {string|null|undefined} pageToken + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @instance + */ + ListRolloutsRequest.prototype.pageToken = null; + + /** + * ListRolloutsRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @instance + */ + ListRolloutsRequest.prototype.project = ""; + + /** + * ListRolloutsRequest returnPartialSuccess. + * @member {boolean|null|undefined} returnPartialSuccess + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @instance + */ + ListRolloutsRequest.prototype.returnPartialSuccess = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRolloutsRequest.prototype, "_filter", { + get: $util.oneOfGetter($oneOfFields = ["filter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRolloutsRequest.prototype, "_maxResults", { + get: $util.oneOfGetter($oneOfFields = ["maxResults"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRolloutsRequest.prototype, "_orderBy", { + get: $util.oneOfGetter($oneOfFields = ["orderBy"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRolloutsRequest.prototype, "_pageToken", { + get: $util.oneOfGetter($oneOfFields = ["pageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRolloutsRequest.prototype, "_returnPartialSuccess", { + get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListRolloutsRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {google.cloud.compute.v1beta.IListRolloutsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRolloutsRequest} ListRolloutsRequest instance + */ + ListRolloutsRequest.create = function create(properties) { + return new ListRolloutsRequest(properties); + }; + + /** + * Encodes the specified ListRolloutsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRolloutsRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {google.cloud.compute.v1beta.IListRolloutsRequest} message ListRolloutsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListRolloutsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); + if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) + writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); + if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) + writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); + if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) + writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); + return writer; + }; + + /** + * Encodes the specified ListRolloutsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRolloutsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {google.cloud.compute.v1beta.IListRolloutsRequest} message ListRolloutsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListRolloutsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListRolloutsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ListRolloutsRequest} ListRolloutsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListRolloutsRequest.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.cloud.compute.v1beta.ListRolloutsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 336120696: { + message.filter = reader.string(); + break; + } + case 54715419: { + message.maxResults = reader.uint32(); + break; + } + case 160562920: { + message.orderBy = reader.string(); + break; + } + case 19994697: { + message.pageToken = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 517198390: { + message.returnPartialSuccess = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListRolloutsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ListRolloutsRequest} ListRolloutsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListRolloutsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListRolloutsRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListRolloutsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.filter != null && message.hasOwnProperty("filter")) { + properties._filter = 1; + if (!$util.isString(message.filter)) + return "filter: string expected"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + properties._maxResults = 1; + if (!$util.isInteger(message.maxResults)) + return "maxResults: integer expected"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + properties._orderBy = 1; + if (!$util.isString(message.orderBy)) + return "orderBy: string expected"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + properties._pageToken = 1; + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + properties._returnPartialSuccess = 1; + if (typeof message.returnPartialSuccess !== "boolean") + return "returnPartialSuccess: boolean expected"; + } + return null; + }; + + /** + * Creates a ListRolloutsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ListRolloutsRequest} ListRolloutsRequest + */ + ListRolloutsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListRolloutsRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.ListRolloutsRequest(); + if (object.filter != null) + message.filter = String(object.filter); + if (object.maxResults != null) + message.maxResults = object.maxResults >>> 0; + if (object.orderBy != null) + message.orderBy = String(object.orderBy); + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.project != null) + message.project = String(object.project); + if (object.returnPartialSuccess != null) + message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + return message; + }; + + /** + * Creates a plain object from a ListRolloutsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {google.cloud.compute.v1beta.ListRolloutsRequest} message ListRolloutsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListRolloutsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.project = ""; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + object.pageToken = message.pageToken; + if (options.oneofs) + object._pageToken = "pageToken"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + object.maxResults = message.maxResults; + if (options.oneofs) + object._maxResults = "maxResults"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + object.orderBy = message.orderBy; + if (options.oneofs) + object._orderBy = "orderBy"; + } + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = message.filter; + if (options.oneofs) + object._filter = "filter"; + } + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + object.returnPartialSuccess = message.returnPartialSuccess; + if (options.oneofs) + object._returnPartialSuccess = "returnPartialSuccess"; + } + return object; + }; + + /** + * Converts this ListRolloutsRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @instance + * @returns {Object.} JSON object + */ + ListRolloutsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListRolloutsRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ListRolloutsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListRolloutsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListRolloutsRequest"; + }; + + return ListRolloutsRequest; + })(); + + v1beta.ListRoutePoliciesRoutersRequest = (function() { + + /** + * Properties of a ListRoutePoliciesRoutersRequest. + * @memberof google.cloud.compute.v1beta + * @interface IListRoutePoliciesRoutersRequest + * @property {string|null} [filter] ListRoutePoliciesRoutersRequest filter + * @property {number|null} [maxResults] ListRoutePoliciesRoutersRequest maxResults + * @property {string|null} [orderBy] ListRoutePoliciesRoutersRequest orderBy + * @property {string|null} [pageToken] ListRoutePoliciesRoutersRequest pageToken + * @property {string|null} [project] ListRoutePoliciesRoutersRequest project + * @property {string|null} [region] ListRoutePoliciesRoutersRequest region + * @property {boolean|null} [returnPartialSuccess] ListRoutePoliciesRoutersRequest returnPartialSuccess + * @property {string|null} [router] ListRoutePoliciesRoutersRequest router + */ + + /** + * Constructs a new ListRoutePoliciesRoutersRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ListRoutePoliciesRoutersRequest. + * @implements IListRoutePoliciesRoutersRequest + * @constructor + * @param {google.cloud.compute.v1beta.IListRoutePoliciesRoutersRequest=} [properties] Properties to set + */ + function ListRoutePoliciesRoutersRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListRoutePoliciesRoutersRequest filter. + * @member {string|null|undefined} filter + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @instance + */ + ListRoutePoliciesRoutersRequest.prototype.filter = null; + + /** + * ListRoutePoliciesRoutersRequest maxResults. + * @member {number|null|undefined} maxResults + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @instance + */ + ListRoutePoliciesRoutersRequest.prototype.maxResults = null; + + /** + * ListRoutePoliciesRoutersRequest orderBy. + * @member {string|null|undefined} orderBy + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @instance + */ + ListRoutePoliciesRoutersRequest.prototype.orderBy = null; + + /** + * ListRoutePoliciesRoutersRequest pageToken. + * @member {string|null|undefined} pageToken + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @instance + */ + ListRoutePoliciesRoutersRequest.prototype.pageToken = null; + + /** + * ListRoutePoliciesRoutersRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @instance + */ + ListRoutePoliciesRoutersRequest.prototype.project = ""; + + /** + * ListRoutePoliciesRoutersRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @instance + */ + ListRoutePoliciesRoutersRequest.prototype.region = ""; + + /** + * ListRoutePoliciesRoutersRequest returnPartialSuccess. + * @member {boolean|null|undefined} returnPartialSuccess + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @instance + */ + ListRoutePoliciesRoutersRequest.prototype.returnPartialSuccess = null; + + /** + * ListRoutePoliciesRoutersRequest router. + * @member {string} router + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @instance + */ + ListRoutePoliciesRoutersRequest.prototype.router = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_filter", { + get: $util.oneOfGetter($oneOfFields = ["filter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_maxResults", { + get: $util.oneOfGetter($oneOfFields = ["maxResults"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_orderBy", { + get: $util.oneOfGetter($oneOfFields = ["orderBy"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_pageToken", { + get: $util.oneOfGetter($oneOfFields = ["pageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListRoutePoliciesRoutersRequest.prototype, "_returnPartialSuccess", { + get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListRoutePoliciesRoutersRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @static + * @param {google.cloud.compute.v1beta.IListRoutePoliciesRoutersRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest} ListRoutePoliciesRoutersRequest instance + */ + ListRoutePoliciesRoutersRequest.create = function create(properties) { + return new ListRoutePoliciesRoutersRequest(properties); + }; + + /** + * Encodes the specified ListRoutePoliciesRoutersRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @static + * @param {google.cloud.compute.v1beta.IListRoutePoliciesRoutersRequest} message ListRoutePoliciesRoutersRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListRoutePoliciesRoutersRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); + if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) + writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.router != null && Object.hasOwnProperty.call(message, "router")) + writer.uint32(/* id 148608841, wireType 2 =*/1188870730).string(message.router); + if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) + writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); + if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) + writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); + return writer; + }; + + /** + * Encodes the specified ListRoutePoliciesRoutersRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @static + * @param {google.cloud.compute.v1beta.IListRoutePoliciesRoutersRequest} message ListRoutePoliciesRoutersRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListRoutePoliciesRoutersRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListRoutePoliciesRoutersRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest} ListRoutePoliciesRoutersRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListRoutePoliciesRoutersRequest.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.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 336120696: { + message.filter = reader.string(); + break; + } + case 54715419: { + message.maxResults = reader.uint32(); + break; + } + case 160562920: { + message.orderBy = reader.string(); + break; + } + case 19994697: { + message.pageToken = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 517198390: { + message.returnPartialSuccess = reader.bool(); + break; + } + case 148608841: { + message.router = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListRoutePoliciesRoutersRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest} ListRoutePoliciesRoutersRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListRoutePoliciesRoutersRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListRoutePoliciesRoutersRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.ListRoutePoliciesRoutersRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListRoutePoliciesRoutersRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1019973,6 +1032011,854 @@ return ListServiceAttachmentsRequest; })(); + v1beta.ListSnapshotGroups = (function() { + + /** + * Properties of a ListSnapshotGroups. + * @memberof google.cloud.compute.v1beta + * @interface IListSnapshotGroups + * @property {string|null} [etag] ListSnapshotGroups etag + * @property {string|null} [id] ListSnapshotGroups id + * @property {Array.|null} [items] ListSnapshotGroups items + * @property {string|null} [kind] ListSnapshotGroups kind + * @property {string|null} [nextPageToken] ListSnapshotGroups nextPageToken + * @property {string|null} [selfLink] ListSnapshotGroups selfLink + * @property {Array.|null} [unreachables] ListSnapshotGroups unreachables + * @property {google.cloud.compute.v1beta.IWarning|null} [warning] ListSnapshotGroups warning + */ + + /** + * Constructs a new ListSnapshotGroups. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ListSnapshotGroups. + * @implements IListSnapshotGroups + * @constructor + * @param {google.cloud.compute.v1beta.IListSnapshotGroups=} [properties] Properties to set + */ + function ListSnapshotGroups(properties) { + this.items = []; + this.unreachables = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListSnapshotGroups etag. + * @member {string|null|undefined} etag + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + */ + ListSnapshotGroups.prototype.etag = null; + + /** + * ListSnapshotGroups id. + * @member {string|null|undefined} id + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + */ + ListSnapshotGroups.prototype.id = null; + + /** + * ListSnapshotGroups items. + * @member {Array.} items + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + */ + ListSnapshotGroups.prototype.items = $util.emptyArray; + + /** + * ListSnapshotGroups kind. + * @member {string|null|undefined} kind + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + */ + ListSnapshotGroups.prototype.kind = null; + + /** + * ListSnapshotGroups nextPageToken. + * @member {string|null|undefined} nextPageToken + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + */ + ListSnapshotGroups.prototype.nextPageToken = null; + + /** + * ListSnapshotGroups selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + */ + ListSnapshotGroups.prototype.selfLink = null; + + /** + * ListSnapshotGroups unreachables. + * @member {Array.} unreachables + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + */ + ListSnapshotGroups.prototype.unreachables = $util.emptyArray; + + /** + * ListSnapshotGroups warning. + * @member {google.cloud.compute.v1beta.IWarning|null|undefined} warning + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + */ + ListSnapshotGroups.prototype.warning = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroups.prototype, "_etag", { + get: $util.oneOfGetter($oneOfFields = ["etag"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroups.prototype, "_id", { + get: $util.oneOfGetter($oneOfFields = ["id"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroups.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroups.prototype, "_nextPageToken", { + get: $util.oneOfGetter($oneOfFields = ["nextPageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroups.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroups.prototype, "_warning", { + get: $util.oneOfGetter($oneOfFields = ["warning"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListSnapshotGroups instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {google.cloud.compute.v1beta.IListSnapshotGroups=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListSnapshotGroups} ListSnapshotGroups instance + */ + ListSnapshotGroups.create = function create(properties) { + return new ListSnapshotGroups(properties); + }; + + /** + * Encodes the specified ListSnapshotGroups message. Does not implicitly {@link google.cloud.compute.v1beta.ListSnapshotGroups.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {google.cloud.compute.v1beta.IListSnapshotGroups} message ListSnapshotGroups message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSnapshotGroups.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 3355, wireType 2 =*/26842).string(message.id); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 3123477, wireType 2 =*/24987818).string(message.etag); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); + if (message.warning != null && Object.hasOwnProperty.call(message, "warning")) + $root.google.cloud.compute.v1beta.Warning.encode(message.warning, writer.uint32(/* id 50704284, wireType 2 =*/405634274).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 79797525, wireType 2 =*/638380202).string(message.nextPageToken); + if (message.items != null && message.items.length) + for (var i = 0; i < message.items.length; ++i) + $root.google.cloud.compute.v1beta.SnapshotGroup.encode(message.items[i], writer.uint32(/* id 100526016, wireType 2 =*/804208130).fork()).ldelim(); + if (message.unreachables != null && message.unreachables.length) + for (var i = 0; i < message.unreachables.length; ++i) + writer.uint32(/* id 243372063, wireType 2 =*/1946976506).string(message.unreachables[i]); + if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) + writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + return writer; + }; + + /** + * Encodes the specified ListSnapshotGroups message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListSnapshotGroups.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {google.cloud.compute.v1beta.IListSnapshotGroups} message ListSnapshotGroups message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSnapshotGroups.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListSnapshotGroups message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ListSnapshotGroups} ListSnapshotGroups + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSnapshotGroups.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.cloud.compute.v1beta.ListSnapshotGroups(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3123477: { + message.etag = reader.string(); + break; + } + case 3355: { + message.id = reader.string(); + break; + } + case 100526016: { + if (!(message.items && message.items.length)) + message.items = []; + message.items.push($root.google.cloud.compute.v1beta.SnapshotGroup.decode(reader, reader.uint32())); + break; + } + case 3292052: { + message.kind = reader.string(); + break; + } + case 79797525: { + message.nextPageToken = reader.string(); + break; + } + case 456214797: { + message.selfLink = reader.string(); + break; + } + case 243372063: { + if (!(message.unreachables && message.unreachables.length)) + message.unreachables = []; + message.unreachables.push(reader.string()); + break; + } + case 50704284: { + message.warning = $root.google.cloud.compute.v1beta.Warning.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListSnapshotGroups message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ListSnapshotGroups} ListSnapshotGroups + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSnapshotGroups.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListSnapshotGroups message. + * @function verify + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListSnapshotGroups.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.etag != null && message.hasOwnProperty("etag")) { + properties._etag = 1; + if (!$util.isString(message.etag)) + return "etag: string expected"; + } + if (message.id != null && message.hasOwnProperty("id")) { + properties._id = 1; + if (!$util.isString(message.id)) + return "id: string expected"; + } + if (message.items != null && message.hasOwnProperty("items")) { + if (!Array.isArray(message.items)) + return "items: array expected"; + for (var i = 0; i < message.items.length; ++i) { + var error = $root.google.cloud.compute.v1beta.SnapshotGroup.verify(message.items[i]); + if (error) + return "items." + error; + } + } + if (message.kind != null && message.hasOwnProperty("kind")) { + properties._kind = 1; + if (!$util.isString(message.kind)) + return "kind: string expected"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + properties._nextPageToken = 1; + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + properties._selfLink = 1; + if (!$util.isString(message.selfLink)) + return "selfLink: string expected"; + } + if (message.unreachables != null && message.hasOwnProperty("unreachables")) { + if (!Array.isArray(message.unreachables)) + return "unreachables: array expected"; + for (var i = 0; i < message.unreachables.length; ++i) + if (!$util.isString(message.unreachables[i])) + return "unreachables: string[] expected"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + properties._warning = 1; + { + var error = $root.google.cloud.compute.v1beta.Warning.verify(message.warning); + if (error) + return "warning." + error; + } + } + return null; + }; + + /** + * Creates a ListSnapshotGroups message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ListSnapshotGroups} ListSnapshotGroups + */ + ListSnapshotGroups.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListSnapshotGroups) + return object; + var message = new $root.google.cloud.compute.v1beta.ListSnapshotGroups(); + if (object.etag != null) + message.etag = String(object.etag); + if (object.id != null) + message.id = String(object.id); + if (object.items) { + if (!Array.isArray(object.items)) + throw TypeError(".google.cloud.compute.v1beta.ListSnapshotGroups.items: array expected"); + message.items = []; + for (var i = 0; i < object.items.length; ++i) { + if (typeof object.items[i] !== "object") + throw TypeError(".google.cloud.compute.v1beta.ListSnapshotGroups.items: object expected"); + message.items[i] = $root.google.cloud.compute.v1beta.SnapshotGroup.fromObject(object.items[i]); + } + } + if (object.kind != null) + message.kind = String(object.kind); + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.selfLink != null) + message.selfLink = String(object.selfLink); + if (object.unreachables) { + if (!Array.isArray(object.unreachables)) + throw TypeError(".google.cloud.compute.v1beta.ListSnapshotGroups.unreachables: array expected"); + message.unreachables = []; + for (var i = 0; i < object.unreachables.length; ++i) + message.unreachables[i] = String(object.unreachables[i]); + } + if (object.warning != null) { + if (typeof object.warning !== "object") + throw TypeError(".google.cloud.compute.v1beta.ListSnapshotGroups.warning: object expected"); + message.warning = $root.google.cloud.compute.v1beta.Warning.fromObject(object.warning); + } + return message; + }; + + /** + * Creates a plain object from a ListSnapshotGroups message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {google.cloud.compute.v1beta.ListSnapshotGroups} message ListSnapshotGroups + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListSnapshotGroups.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.items = []; + object.unreachables = []; + } + if (message.id != null && message.hasOwnProperty("id")) { + object.id = message.id; + if (options.oneofs) + object._id = "id"; + } + if (message.etag != null && message.hasOwnProperty("etag")) { + object.etag = message.etag; + if (options.oneofs) + object._etag = "etag"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + object.kind = message.kind; + if (options.oneofs) + object._kind = "kind"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + object.warning = $root.google.cloud.compute.v1beta.Warning.toObject(message.warning, options); + if (options.oneofs) + object._warning = "warning"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + object.nextPageToken = message.nextPageToken; + if (options.oneofs) + object._nextPageToken = "nextPageToken"; + } + if (message.items && message.items.length) { + object.items = []; + for (var j = 0; j < message.items.length; ++j) + object.items[j] = $root.google.cloud.compute.v1beta.SnapshotGroup.toObject(message.items[j], options); + } + if (message.unreachables && message.unreachables.length) { + object.unreachables = []; + for (var j = 0; j < message.unreachables.length; ++j) + object.unreachables[j] = message.unreachables[j]; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + object.selfLink = message.selfLink; + if (options.oneofs) + object._selfLink = "selfLink"; + } + return object; + }; + + /** + * Converts this ListSnapshotGroups to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @instance + * @returns {Object.} JSON object + */ + ListSnapshotGroups.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListSnapshotGroups + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ListSnapshotGroups + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListSnapshotGroups.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListSnapshotGroups"; + }; + + return ListSnapshotGroups; + })(); + + v1beta.ListSnapshotGroupsRequest = (function() { + + /** + * Properties of a ListSnapshotGroupsRequest. + * @memberof google.cloud.compute.v1beta + * @interface IListSnapshotGroupsRequest + * @property {string|null} [filter] ListSnapshotGroupsRequest filter + * @property {number|null} [maxResults] ListSnapshotGroupsRequest maxResults + * @property {string|null} [orderBy] ListSnapshotGroupsRequest orderBy + * @property {string|null} [pageToken] ListSnapshotGroupsRequest pageToken + * @property {string|null} [project] ListSnapshotGroupsRequest project + * @property {boolean|null} [returnPartialSuccess] ListSnapshotGroupsRequest returnPartialSuccess + */ + + /** + * Constructs a new ListSnapshotGroupsRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ListSnapshotGroupsRequest. + * @implements IListSnapshotGroupsRequest + * @constructor + * @param {google.cloud.compute.v1beta.IListSnapshotGroupsRequest=} [properties] Properties to set + */ + function ListSnapshotGroupsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListSnapshotGroupsRequest filter. + * @member {string|null|undefined} filter + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @instance + */ + ListSnapshotGroupsRequest.prototype.filter = null; + + /** + * ListSnapshotGroupsRequest maxResults. + * @member {number|null|undefined} maxResults + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @instance + */ + ListSnapshotGroupsRequest.prototype.maxResults = null; + + /** + * ListSnapshotGroupsRequest orderBy. + * @member {string|null|undefined} orderBy + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @instance + */ + ListSnapshotGroupsRequest.prototype.orderBy = null; + + /** + * ListSnapshotGroupsRequest pageToken. + * @member {string|null|undefined} pageToken + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @instance + */ + ListSnapshotGroupsRequest.prototype.pageToken = null; + + /** + * ListSnapshotGroupsRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @instance + */ + ListSnapshotGroupsRequest.prototype.project = ""; + + /** + * ListSnapshotGroupsRequest returnPartialSuccess. + * @member {boolean|null|undefined} returnPartialSuccess + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @instance + */ + ListSnapshotGroupsRequest.prototype.returnPartialSuccess = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroupsRequest.prototype, "_filter", { + get: $util.oneOfGetter($oneOfFields = ["filter"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroupsRequest.prototype, "_maxResults", { + get: $util.oneOfGetter($oneOfFields = ["maxResults"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroupsRequest.prototype, "_orderBy", { + get: $util.oneOfGetter($oneOfFields = ["orderBy"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroupsRequest.prototype, "_pageToken", { + get: $util.oneOfGetter($oneOfFields = ["pageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ListSnapshotGroupsRequest.prototype, "_returnPartialSuccess", { + get: $util.oneOfGetter($oneOfFields = ["returnPartialSuccess"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ListSnapshotGroupsRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListSnapshotGroupsRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ListSnapshotGroupsRequest} ListSnapshotGroupsRequest instance + */ + ListSnapshotGroupsRequest.create = function create(properties) { + return new ListSnapshotGroupsRequest(properties); + }; + + /** + * Encodes the specified ListSnapshotGroupsRequest message. Does not implicitly {@link google.cloud.compute.v1beta.ListSnapshotGroupsRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListSnapshotGroupsRequest} message ListSnapshotGroupsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSnapshotGroupsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.pageToken != null && Object.hasOwnProperty.call(message, "pageToken")) + writer.uint32(/* id 19994697, wireType 2 =*/159957578).string(message.pageToken); + if (message.maxResults != null && Object.hasOwnProperty.call(message, "maxResults")) + writer.uint32(/* id 54715419, wireType 0 =*/437723352).uint32(message.maxResults); + if (message.orderBy != null && Object.hasOwnProperty.call(message, "orderBy")) + writer.uint32(/* id 160562920, wireType 2 =*/1284503362).string(message.orderBy); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.filter != null && Object.hasOwnProperty.call(message, "filter")) + writer.uint32(/* id 336120696, wireType 2 =*/2688965570).string(message.filter); + if (message.returnPartialSuccess != null && Object.hasOwnProperty.call(message, "returnPartialSuccess")) + writer.uint32(/* id 517198390, wireType 0 =*/4137587120).bool(message.returnPartialSuccess); + return writer; + }; + + /** + * Encodes the specified ListSnapshotGroupsRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ListSnapshotGroupsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.IListSnapshotGroupsRequest} message ListSnapshotGroupsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ListSnapshotGroupsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ListSnapshotGroupsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ListSnapshotGroupsRequest} ListSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSnapshotGroupsRequest.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.cloud.compute.v1beta.ListSnapshotGroupsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 336120696: { + message.filter = reader.string(); + break; + } + case 54715419: { + message.maxResults = reader.uint32(); + break; + } + case 160562920: { + message.orderBy = reader.string(); + break; + } + case 19994697: { + message.pageToken = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 517198390: { + message.returnPartialSuccess = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ListSnapshotGroupsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ListSnapshotGroupsRequest} ListSnapshotGroupsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ListSnapshotGroupsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ListSnapshotGroupsRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ListSnapshotGroupsRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.filter != null && message.hasOwnProperty("filter")) { + properties._filter = 1; + if (!$util.isString(message.filter)) + return "filter: string expected"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + properties._maxResults = 1; + if (!$util.isInteger(message.maxResults)) + return "maxResults: integer expected"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + properties._orderBy = 1; + if (!$util.isString(message.orderBy)) + return "orderBy: string expected"; + } + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + properties._pageToken = 1; + if (!$util.isString(message.pageToken)) + return "pageToken: string expected"; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + properties._returnPartialSuccess = 1; + if (typeof message.returnPartialSuccess !== "boolean") + return "returnPartialSuccess: boolean expected"; + } + return null; + }; + + /** + * Creates a ListSnapshotGroupsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ListSnapshotGroupsRequest} ListSnapshotGroupsRequest + */ + ListSnapshotGroupsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ListSnapshotGroupsRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.ListSnapshotGroupsRequest(); + if (object.filter != null) + message.filter = String(object.filter); + if (object.maxResults != null) + message.maxResults = object.maxResults >>> 0; + if (object.orderBy != null) + message.orderBy = String(object.orderBy); + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.project != null) + message.project = String(object.project); + if (object.returnPartialSuccess != null) + message.returnPartialSuccess = Boolean(object.returnPartialSuccess); + return message; + }; + + /** + * Creates a plain object from a ListSnapshotGroupsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {google.cloud.compute.v1beta.ListSnapshotGroupsRequest} message ListSnapshotGroupsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListSnapshotGroupsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.project = ""; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) { + object.pageToken = message.pageToken; + if (options.oneofs) + object._pageToken = "pageToken"; + } + if (message.maxResults != null && message.hasOwnProperty("maxResults")) { + object.maxResults = message.maxResults; + if (options.oneofs) + object._maxResults = "maxResults"; + } + if (message.orderBy != null && message.hasOwnProperty("orderBy")) { + object.orderBy = message.orderBy; + if (options.oneofs) + object._orderBy = "orderBy"; + } + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = message.filter; + if (options.oneofs) + object._filter = "filter"; + } + if (message.returnPartialSuccess != null && message.hasOwnProperty("returnPartialSuccess")) { + object.returnPartialSuccess = message.returnPartialSuccess; + if (options.oneofs) + object._returnPartialSuccess = "returnPartialSuccess"; + } + return object; + }; + + /** + * Converts this ListSnapshotGroupsRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @instance + * @returns {Object.} JSON object + */ + ListSnapshotGroupsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListSnapshotGroupsRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ListSnapshotGroupsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListSnapshotGroupsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ListSnapshotGroupsRequest"; + }; + + return ListSnapshotGroupsRequest; + })(); + v1beta.ListSnapshotsRequest = (function() { /** @@ -1031037,6 +1043923,7 @@ * @interface ILocationPolicy * @property {Object.|null} [locations] LocationPolicy locations * @property {string|null} [targetShape] LocationPolicy targetShape + * @property {Array.|null} [zones] LocationPolicy zones */ /** @@ -1031049,6 +1043936,7 @@ */ function LocationPolicy(properties) { this.locations = {}; + this.zones = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1031071,6 +1043959,14 @@ */ LocationPolicy.prototype.targetShape = null; + /** + * LocationPolicy zones. + * @member {Array.} zones + * @memberof google.cloud.compute.v1beta.LocationPolicy + * @instance + */ + LocationPolicy.prototype.zones = $util.emptyArray; + // OneOf field names bound to virtual getters and setters var $oneOfFields; @@ -1031104,6 +1044000,9 @@ LocationPolicy.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); + if (message.zones != null && message.zones.length) + for (var i = 0; i < message.zones.length; ++i) + $root.google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.encode(message.zones[i], writer.uint32(/* id 116085319, wireType 2 =*/928682554).fork()).ldelim(); if (message.targetShape != null && Object.hasOwnProperty.call(message, "targetShape")) writer.uint32(/* id 338621299, wireType 2 =*/2708970394).string(message.targetShape); if (message.locations != null && Object.hasOwnProperty.call(message, "locations")) @@ -1031174,6 +1044073,12 @@ message.targetShape = reader.string(); break; } + case 116085319: { + if (!(message.zones && message.zones.length)) + message.zones = []; + message.zones.push($root.google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.decode(reader, reader.uint32())); + break; + } default: reader.skipType(tag & 7); break; @@ -1031225,6 +1044130,15 @@ if (!$util.isString(message.targetShape)) return "targetShape: string expected"; } + if (message.zones != null && message.hasOwnProperty("zones")) { + if (!Array.isArray(message.zones)) + return "zones: array expected"; + for (var i = 0; i < message.zones.length; ++i) { + var error = $root.google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.verify(message.zones[i]); + if (error) + return "zones." + error; + } + } return null; }; @@ -1031252,6 +1044166,16 @@ } if (object.targetShape != null) message.targetShape = String(object.targetShape); + if (object.zones) { + if (!Array.isArray(object.zones)) + throw TypeError(".google.cloud.compute.v1beta.LocationPolicy.zones: array expected"); + message.zones = []; + for (var i = 0; i < object.zones.length; ++i) { + if (typeof object.zones[i] !== "object") + throw TypeError(".google.cloud.compute.v1beta.LocationPolicy.zones: object expected"); + message.zones[i] = $root.google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.fromObject(object.zones[i]); + } + } return message; }; @@ -1031268,8 +1044192,15 @@ if (!options) options = {}; var object = {}; + if (options.arrays || options.defaults) + object.zones = []; if (options.objects || options.defaults) object.locations = {}; + if (message.zones && message.zones.length) { + object.zones = []; + for (var j = 0; j < message.zones.length; ++j) + object.zones[j] = $root.google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.toObject(message.zones[j], options); + } if (message.targetShape != null && message.hasOwnProperty("targetShape")) { object.targetShape = message.targetShape; if (options.oneofs) @@ -1031824,6 +1044755,224 @@ return LocationPolicyLocationConstraints; })(); + v1beta.LocationPolicyZoneConfiguration = (function() { + + /** + * Properties of a LocationPolicyZoneConfiguration. + * @memberof google.cloud.compute.v1beta + * @interface ILocationPolicyZoneConfiguration + * @property {string|null} [zone] LocationPolicyZoneConfiguration zone + */ + + /** + * Constructs a new LocationPolicyZoneConfiguration. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a LocationPolicyZoneConfiguration. + * @implements ILocationPolicyZoneConfiguration + * @constructor + * @param {google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration=} [properties] Properties to set + */ + function LocationPolicyZoneConfiguration(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * LocationPolicyZoneConfiguration zone. + * @member {string|null|undefined} zone + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @instance + */ + LocationPolicyZoneConfiguration.prototype.zone = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(LocationPolicyZoneConfiguration.prototype, "_zone", { + get: $util.oneOfGetter($oneOfFields = ["zone"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new LocationPolicyZoneConfiguration instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.LocationPolicyZoneConfiguration} LocationPolicyZoneConfiguration instance + */ + LocationPolicyZoneConfiguration.create = function create(properties) { + return new LocationPolicyZoneConfiguration(properties); + }; + + /** + * Encodes the specified LocationPolicyZoneConfiguration message. Does not implicitly {@link google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration} message LocationPolicyZoneConfiguration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LocationPolicyZoneConfiguration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + return writer; + }; + + /** + * Encodes the specified LocationPolicyZoneConfiguration message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.LocationPolicyZoneConfiguration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {google.cloud.compute.v1beta.ILocationPolicyZoneConfiguration} message LocationPolicyZoneConfiguration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + LocationPolicyZoneConfiguration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a LocationPolicyZoneConfiguration message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.LocationPolicyZoneConfiguration} LocationPolicyZoneConfiguration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LocationPolicyZoneConfiguration.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.cloud.compute.v1beta.LocationPolicyZoneConfiguration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a LocationPolicyZoneConfiguration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.LocationPolicyZoneConfiguration} LocationPolicyZoneConfiguration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + LocationPolicyZoneConfiguration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a LocationPolicyZoneConfiguration message. + * @function verify + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + LocationPolicyZoneConfiguration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.zone != null && message.hasOwnProperty("zone")) { + properties._zone = 1; + if (!$util.isString(message.zone)) + return "zone: string expected"; + } + return null; + }; + + /** + * Creates a LocationPolicyZoneConfiguration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.LocationPolicyZoneConfiguration} LocationPolicyZoneConfiguration + */ + LocationPolicyZoneConfiguration.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.LocationPolicyZoneConfiguration) + return object; + var message = new $root.google.cloud.compute.v1beta.LocationPolicyZoneConfiguration(); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a LocationPolicyZoneConfiguration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {google.cloud.compute.v1beta.LocationPolicyZoneConfiguration} message LocationPolicyZoneConfiguration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + LocationPolicyZoneConfiguration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.zone != null && message.hasOwnProperty("zone")) { + object.zone = message.zone; + if (options.oneofs) + object._zone = "zone"; + } + return object; + }; + + /** + * Converts this LocationPolicyZoneConfiguration to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @instance + * @returns {Object.} JSON object + */ + LocationPolicyZoneConfiguration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for LocationPolicyZoneConfiguration + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.LocationPolicyZoneConfiguration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + LocationPolicyZoneConfiguration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.LocationPolicyZoneConfiguration"; + }; + + return LocationPolicyZoneConfiguration; + })(); + v1beta.MachineImage = (function() { /** @@ -1031840,6 +1044989,7 @@ * @property {Object.|null} [labels] MachineImage labels * @property {google.cloud.compute.v1beta.ICustomerEncryptionKey|null} [machineImageEncryptionKey] MachineImage machineImageEncryptionKey * @property {string|null} [name] MachineImage name + * @property {google.cloud.compute.v1beta.IMachineImageParams|null} [params] MachineImage params * @property {boolean|null} [satisfiesPzi] MachineImage satisfiesPzi * @property {boolean|null} [satisfiesPzs] MachineImage satisfiesPzs * @property {Array.|null} [savedDisks] MachineImage savedDisks @@ -1031951,6 +1045101,14 @@ */ MachineImage.prototype.name = null; + /** + * MachineImage params. + * @member {google.cloud.compute.v1beta.IMachineImageParams|null|undefined} params + * @memberof google.cloud.compute.v1beta.MachineImage + * @instance + */ + MachineImage.prototype.params = null; + /** * MachineImage satisfiesPzi. * @member {boolean|null|undefined} satisfiesPzi @@ -1032088,6 +1045246,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(MachineImage.prototype, "_params", { + get: $util.oneOfGetter($oneOfFields = ["params"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(MachineImage.prototype, "_satisfiesPzi", { get: $util.oneOfGetter($oneOfFields = ["satisfiesPzi"]), @@ -1032162,6 +1045326,8 @@ writer.uint32(/* id 3373707, wireType 2 =*/26989658).string(message.name); if (message.creationTimestamp != null && Object.hasOwnProperty.call(message, "creationTimestamp")) writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.cloud.compute.v1beta.MachineImageParams.encode(message.params, writer.uint32(/* id 78313862, wireType 2 =*/626510898).fork()).ldelim(); if (message.totalStorageBytes != null && Object.hasOwnProperty.call(message, "totalStorageBytes")) writer.uint32(/* id 81855468, wireType 0 =*/654843744).int64(message.totalStorageBytes); if (message.labelFingerprint != null && Object.hasOwnProperty.call(message, "labelFingerprint")) @@ -1032293,6 +1045459,10 @@ message.name = reader.string(); break; } + case 78313862: { + message.params = $root.google.cloud.compute.v1beta.MachineImageParams.decode(reader, reader.uint32()); + break; + } case 480964257: { message.satisfiesPzi = reader.bool(); break; @@ -1032434,6 +1045604,14 @@ if (!$util.isString(message.name)) return "name: string expected"; } + if (message.params != null && message.hasOwnProperty("params")) { + properties._params = 1; + { + var error = $root.google.cloud.compute.v1beta.MachineImageParams.verify(message.params); + if (error) + return "params." + error; + } + } if (message.satisfiesPzi != null && message.hasOwnProperty("satisfiesPzi")) { properties._satisfiesPzi = 1; if (typeof message.satisfiesPzi !== "boolean") @@ -1032550,6 +1045728,11 @@ } if (object.name != null) message.name = String(object.name); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.cloud.compute.v1beta.MachineImage.params: object expected"); + message.params = $root.google.cloud.compute.v1beta.MachineImageParams.fromObject(object.params); + } if (object.satisfiesPzi != null) message.satisfiesPzi = Boolean(object.satisfiesPzi); if (object.satisfiesPzs != null) @@ -1032647,6 +1045830,11 @@ if (options.oneofs) object._creationTimestamp = "creationTimestamp"; } + if (message.params != null && message.hasOwnProperty("params")) { + object.params = $root.google.cloud.compute.v1beta.MachineImageParams.toObject(message.params, options); + if (options.oneofs) + object._params = "params"; + } if (message.totalStorageBytes != null && message.hasOwnProperty("totalStorageBytes")) { if (typeof message.totalStorageBytes === "number") object.totalStorageBytes = options.longs === String ? String(message.totalStorageBytes) : message.totalStorageBytes; @@ -1033186,6 +1046374,246 @@ return MachineImageList; })(); + v1beta.MachineImageParams = (function() { + + /** + * Properties of a MachineImageParams. + * @memberof google.cloud.compute.v1beta + * @interface IMachineImageParams + * @property {Object.|null} [resourceManagerTags] MachineImageParams resourceManagerTags + */ + + /** + * Constructs a new MachineImageParams. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a MachineImageParams. + * @implements IMachineImageParams + * @constructor + * @param {google.cloud.compute.v1beta.IMachineImageParams=} [properties] Properties to set + */ + function MachineImageParams(properties) { + this.resourceManagerTags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * MachineImageParams resourceManagerTags. + * @member {Object.} resourceManagerTags + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @instance + */ + MachineImageParams.prototype.resourceManagerTags = $util.emptyObject; + + /** + * Creates a new MachineImageParams instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {google.cloud.compute.v1beta.IMachineImageParams=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.MachineImageParams} MachineImageParams instance + */ + MachineImageParams.create = function create(properties) { + return new MachineImageParams(properties); + }; + + /** + * Encodes the specified MachineImageParams message. Does not implicitly {@link google.cloud.compute.v1beta.MachineImageParams.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {google.cloud.compute.v1beta.IMachineImageParams} message MachineImageParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MachineImageParams.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceManagerTags != null && Object.hasOwnProperty.call(message, "resourceManagerTags")) + for (var keys = Object.keys(message.resourceManagerTags), i = 0; i < keys.length; ++i) + writer.uint32(/* id 377671164, wireType 2 =*/3021369314).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourceManagerTags[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified MachineImageParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.MachineImageParams.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {google.cloud.compute.v1beta.IMachineImageParams} message MachineImageParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + MachineImageParams.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a MachineImageParams message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.MachineImageParams} MachineImageParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MachineImageParams.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.cloud.compute.v1beta.MachineImageParams(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 377671164: { + if (message.resourceManagerTags === $util.emptyObject) + message.resourceManagerTags = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.resourceManagerTags[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a MachineImageParams message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.MachineImageParams} MachineImageParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + MachineImageParams.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a MachineImageParams message. + * @function verify + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + MachineImageParams.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceManagerTags != null && message.hasOwnProperty("resourceManagerTags")) { + if (!$util.isObject(message.resourceManagerTags)) + return "resourceManagerTags: object expected"; + var key = Object.keys(message.resourceManagerTags); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.resourceManagerTags[key[i]])) + return "resourceManagerTags: string{k:string} expected"; + } + return null; + }; + + /** + * Creates a MachineImageParams message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.MachineImageParams} MachineImageParams + */ + MachineImageParams.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.MachineImageParams) + return object; + var message = new $root.google.cloud.compute.v1beta.MachineImageParams(); + if (object.resourceManagerTags) { + if (typeof object.resourceManagerTags !== "object") + throw TypeError(".google.cloud.compute.v1beta.MachineImageParams.resourceManagerTags: object expected"); + message.resourceManagerTags = {}; + for (var keys = Object.keys(object.resourceManagerTags), i = 0; i < keys.length; ++i) + message.resourceManagerTags[keys[i]] = String(object.resourceManagerTags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a MachineImageParams message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {google.cloud.compute.v1beta.MachineImageParams} message MachineImageParams + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MachineImageParams.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.resourceManagerTags = {}; + var keys2; + if (message.resourceManagerTags && (keys2 = Object.keys(message.resourceManagerTags)).length) { + object.resourceManagerTags = {}; + for (var j = 0; j < keys2.length; ++j) + object.resourceManagerTags[keys2[j]] = message.resourceManagerTags[keys2[j]]; + } + return object; + }; + + /** + * Converts this MachineImageParams to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @instance + * @returns {Object.} JSON object + */ + MachineImageParams.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MachineImageParams + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.MachineImageParams + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MachineImageParams.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.MachineImageParams"; + }; + + return MachineImageParams; + })(); + v1beta.MachineType = (function() { /** @@ -1043538,6 +1056966,384 @@ return NamedPort; })(); + v1beta.NamedSet = (function() { + + /** + * Properties of a NamedSet. + * @memberof google.cloud.compute.v1beta + * @interface INamedSet + * @property {string|null} [description] NamedSet description + * @property {Array.|null} [elements] NamedSet elements + * @property {string|null} [fingerprint] NamedSet fingerprint + * @property {string|null} [name] NamedSet name + * @property {string|null} [type] NamedSet type + */ + + /** + * Constructs a new NamedSet. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a NamedSet. + * @implements INamedSet + * @constructor + * @param {google.cloud.compute.v1beta.INamedSet=} [properties] Properties to set + */ + function NamedSet(properties) { + this.elements = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NamedSet description. + * @member {string|null|undefined} description + * @memberof google.cloud.compute.v1beta.NamedSet + * @instance + */ + NamedSet.prototype.description = null; + + /** + * NamedSet elements. + * @member {Array.} elements + * @memberof google.cloud.compute.v1beta.NamedSet + * @instance + */ + NamedSet.prototype.elements = $util.emptyArray; + + /** + * NamedSet fingerprint. + * @member {string|null|undefined} fingerprint + * @memberof google.cloud.compute.v1beta.NamedSet + * @instance + */ + NamedSet.prototype.fingerprint = null; + + /** + * NamedSet name. + * @member {string|null|undefined} name + * @memberof google.cloud.compute.v1beta.NamedSet + * @instance + */ + NamedSet.prototype.name = null; + + /** + * NamedSet type. + * @member {string|null|undefined} type + * @memberof google.cloud.compute.v1beta.NamedSet + * @instance + */ + NamedSet.prototype.type = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(NamedSet.prototype, "_description", { + get: $util.oneOfGetter($oneOfFields = ["description"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(NamedSet.prototype, "_fingerprint", { + get: $util.oneOfGetter($oneOfFields = ["fingerprint"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(NamedSet.prototype, "_name", { + get: $util.oneOfGetter($oneOfFields = ["name"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(NamedSet.prototype, "_type", { + get: $util.oneOfGetter($oneOfFields = ["type"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new NamedSet instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {google.cloud.compute.v1beta.INamedSet=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.NamedSet} NamedSet instance + */ + NamedSet.create = function create(properties) { + return new NamedSet(properties); + }; + + /** + * Encodes the specified NamedSet message. Does not implicitly {@link google.cloud.compute.v1beta.NamedSet.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {google.cloud.compute.v1beta.INamedSet} message NamedSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NamedSet.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 3373707, wireType 2 =*/26989658).string(message.name); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 3575610, wireType 2 =*/28604882).string(message.type); + if (message.fingerprint != null && Object.hasOwnProperty.call(message, "fingerprint")) + writer.uint32(/* id 234678500, wireType 2 =*/1877428002).string(message.fingerprint); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 422937596, wireType 2 =*/3383500770).string(message.description); + if (message.elements != null && message.elements.length) + for (var i = 0; i < message.elements.length; ++i) + $root.google.cloud.compute.v1beta.Expr.encode(message.elements[i], writer.uint32(/* id 528531703, wireType 2 =*/4228253626).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified NamedSet message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.NamedSet.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {google.cloud.compute.v1beta.INamedSet} message NamedSet message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NamedSet.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a NamedSet message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.NamedSet} NamedSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NamedSet.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.cloud.compute.v1beta.NamedSet(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 422937596: { + message.description = reader.string(); + break; + } + case 528531703: { + if (!(message.elements && message.elements.length)) + message.elements = []; + message.elements.push($root.google.cloud.compute.v1beta.Expr.decode(reader, reader.uint32())); + break; + } + case 234678500: { + message.fingerprint = reader.string(); + break; + } + case 3373707: { + message.name = reader.string(); + break; + } + case 3575610: { + message.type = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a NamedSet message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.NamedSet} NamedSet + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NamedSet.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a NamedSet message. + * @function verify + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + NamedSet.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.description != null && message.hasOwnProperty("description")) { + properties._description = 1; + if (!$util.isString(message.description)) + return "description: string expected"; + } + if (message.elements != null && message.hasOwnProperty("elements")) { + if (!Array.isArray(message.elements)) + return "elements: array expected"; + for (var i = 0; i < message.elements.length; ++i) { + var error = $root.google.cloud.compute.v1beta.Expr.verify(message.elements[i]); + if (error) + return "elements." + error; + } + } + if (message.fingerprint != null && message.hasOwnProperty("fingerprint")) { + properties._fingerprint = 1; + if (!$util.isString(message.fingerprint)) + return "fingerprint: string expected"; + } + if (message.name != null && message.hasOwnProperty("name")) { + properties._name = 1; + if (!$util.isString(message.name)) + return "name: string expected"; + } + if (message.type != null && message.hasOwnProperty("type")) { + properties._type = 1; + if (!$util.isString(message.type)) + return "type: string expected"; + } + return null; + }; + + /** + * Creates a NamedSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.NamedSet} NamedSet + */ + NamedSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.NamedSet) + return object; + var message = new $root.google.cloud.compute.v1beta.NamedSet(); + if (object.description != null) + message.description = String(object.description); + if (object.elements) { + if (!Array.isArray(object.elements)) + throw TypeError(".google.cloud.compute.v1beta.NamedSet.elements: array expected"); + message.elements = []; + for (var i = 0; i < object.elements.length; ++i) { + if (typeof object.elements[i] !== "object") + throw TypeError(".google.cloud.compute.v1beta.NamedSet.elements: object expected"); + message.elements[i] = $root.google.cloud.compute.v1beta.Expr.fromObject(object.elements[i]); + } + } + if (object.fingerprint != null) + message.fingerprint = String(object.fingerprint); + if (object.name != null) + message.name = String(object.name); + if (object.type != null) + message.type = String(object.type); + return message; + }; + + /** + * Creates a plain object from a NamedSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {google.cloud.compute.v1beta.NamedSet} message NamedSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NamedSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.elements = []; + if (message.name != null && message.hasOwnProperty("name")) { + object.name = message.name; + if (options.oneofs) + object._name = "name"; + } + if (message.type != null && message.hasOwnProperty("type")) { + object.type = message.type; + if (options.oneofs) + object._type = "type"; + } + if (message.fingerprint != null && message.hasOwnProperty("fingerprint")) { + object.fingerprint = message.fingerprint; + if (options.oneofs) + object._fingerprint = "fingerprint"; + } + if (message.description != null && message.hasOwnProperty("description")) { + object.description = message.description; + if (options.oneofs) + object._description = "description"; + } + if (message.elements && message.elements.length) { + object.elements = []; + for (var j = 0; j < message.elements.length; ++j) + object.elements[j] = $root.google.cloud.compute.v1beta.Expr.toObject(message.elements[j], options); + } + return object; + }; + + /** + * Converts this NamedSet to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.NamedSet + * @instance + * @returns {Object.} JSON object + */ + NamedSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NamedSet + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.NamedSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NamedSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.NamedSet"; + }; + + /** + * Type enum. + * @name google.cloud.compute.v1beta.NamedSet.Type + * @enum {number} + * @property {number} UNDEFINED_TYPE=0 UNDEFINED_TYPE value + * @property {number} NAMED_SET_TYPE_COMMUNITY=263444871 NAMED_SET_TYPE_COMMUNITY value + * @property {number} NAMED_SET_TYPE_PREFIX=228038036 NAMED_SET_TYPE_PREFIX value + */ + NamedSet.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_TYPE"] = 0; + values[valuesById[263444871] = "NAMED_SET_TYPE_COMMUNITY"] = 263444871; + values[valuesById[228038036] = "NAMED_SET_TYPE_PREFIX"] = 228038036; + return values; + })(); + + return NamedSet; + })(); + v1beta.NatIpInfo = (function() { /** @@ -1055230,6 +1069036,7 @@ * @interface INetworkInterface * @property {Array.|null} [accessConfigs] NetworkInterface accessConfigs * @property {Array.|null} [aliasIpRanges] NetworkInterface aliasIpRanges + * @property {boolean|null} [enableVpcScopedDns] NetworkInterface enableVpcScopedDns * @property {string|null} [fingerprint] NetworkInterface fingerprint * @property {string|null} [igmpQuery] NetworkInterface igmpQuery * @property {number|null} [internalIpv6PrefixLength] NetworkInterface internalIpv6PrefixLength @@ -1055284,6 +1069091,14 @@ */ NetworkInterface.prototype.aliasIpRanges = $util.emptyArray; + /** + * NetworkInterface enableVpcScopedDns. + * @member {boolean|null|undefined} enableVpcScopedDns + * @memberof google.cloud.compute.v1beta.NetworkInterface + * @instance + */ + NetworkInterface.prototype.enableVpcScopedDns = null; + /** * NetworkInterface fingerprint. * @member {string|null|undefined} fingerprint @@ -1055431,6 +1069246,12 @@ // OneOf field names bound to virtual getters and setters var $oneOfFields; + // Virtual OneOf for proto3 optional field + Object.defineProperty(NetworkInterface.prototype, "_enableVpcScopedDns", { + get: $util.oneOfGetter($oneOfFields = ["enableVpcScopedDns"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(NetworkInterface.prototype, "_fingerprint", { get: $util.oneOfGetter($oneOfFields = ["fingerprint"]), @@ -1055583,6 +1069404,8 @@ writer.uint32(/* id 232872494, wireType 2 =*/1862979954).string(message.network); if (message.fingerprint != null && Object.hasOwnProperty.call(message, "fingerprint")) writer.uint32(/* id 234678500, wireType 2 =*/1877428002).string(message.fingerprint); + if (message.enableVpcScopedDns != null && Object.hasOwnProperty.call(message, "enableVpcScopedDns")) + writer.uint32(/* id 283425868, wireType 0 =*/2267406944).bool(message.enableVpcScopedDns); if (message.subnetwork != null && Object.hasOwnProperty.call(message, "subnetwork")) writer.uint32(/* id 307827694, wireType 2 =*/2462621554).string(message.subnetwork); if (message.macAddress != null && Object.hasOwnProperty.call(message, "macAddress")) @@ -1055648,6 +1069471,10 @@ message.aliasIpRanges.push($root.google.cloud.compute.v1beta.AliasIpRange.decode(reader, reader.uint32())); break; } + case 283425868: { + message.enableVpcScopedDns = reader.bool(); + break; + } case 234678500: { message.fingerprint = reader.string(); break; @@ -1055776,6 +1069603,11 @@ return "aliasIpRanges." + error; } } + if (message.enableVpcScopedDns != null && message.hasOwnProperty("enableVpcScopedDns")) { + properties._enableVpcScopedDns = 1; + if (typeof message.enableVpcScopedDns !== "boolean") + return "enableVpcScopedDns: boolean expected"; + } if (message.fingerprint != null && message.hasOwnProperty("fingerprint")) { properties._fingerprint = 1; if (!$util.isString(message.fingerprint)) @@ -1055905,6 +1069737,8 @@ message.aliasIpRanges[i] = $root.google.cloud.compute.v1beta.AliasIpRange.fromObject(object.aliasIpRanges[i]); } } + if (object.enableVpcScopedDns != null) + message.enableVpcScopedDns = Boolean(object.enableVpcScopedDns); if (object.fingerprint != null) message.fingerprint = String(object.fingerprint); if (object.igmpQuery != null) @@ -1056030,6 +1069864,11 @@ if (options.oneofs) object._fingerprint = "fingerprint"; } + if (message.enableVpcScopedDns != null && message.hasOwnProperty("enableVpcScopedDns")) { + object.enableVpcScopedDns = message.enableVpcScopedDns; + if (options.oneofs) + object._enableVpcScopedDns = "enableVpcScopedDns"; + } if (message.subnetwork != null && message.hasOwnProperty("subnetwork")) { object.subnetwork = message.subnetwork; if (options.oneofs) @@ -1065199,13 +1079038,17 @@ * @name google.cloud.compute.v1beta.NetworkProfileNetworkFeatures.FirewallPolicyTypes * @enum {number} * @property {number} UNDEFINED_FIREWALL_POLICY_TYPES=0 UNDEFINED_FIREWALL_POLICY_TYPES value + * @property {number} RDMA_FALCON_POLICY=66315047 RDMA_FALCON_POLICY value * @property {number} RDMA_ROCE_POLICY=148757145 RDMA_ROCE_POLICY value + * @property {number} ULL_POLICY=100494364 ULL_POLICY value * @property {number} VPC_POLICY=74319208 VPC_POLICY value */ NetworkProfileNetworkFeatures.FirewallPolicyTypes = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "UNDEFINED_FIREWALL_POLICY_TYPES"] = 0; + values[valuesById[66315047] = "RDMA_FALCON_POLICY"] = 66315047; values[valuesById[148757145] = "RDMA_ROCE_POLICY"] = 148757145; + values[valuesById[100494364] = "ULL_POLICY"] = 100494364; values[valuesById[74319208] = "VPC_POLICY"] = 74319208; return values; })(); @@ -1092338,6 +1106181,323 @@ return PatchInterconnectRequest; })(); + v1beta.PatchNamedSetRouterRequest = (function() { + + /** + * Properties of a PatchNamedSetRouterRequest. + * @memberof google.cloud.compute.v1beta + * @interface IPatchNamedSetRouterRequest + * @property {google.cloud.compute.v1beta.INamedSet|null} [namedSetResource] PatchNamedSetRouterRequest namedSetResource + * @property {string|null} [project] PatchNamedSetRouterRequest project + * @property {string|null} [region] PatchNamedSetRouterRequest region + * @property {string|null} [requestId] PatchNamedSetRouterRequest requestId + * @property {string|null} [router] PatchNamedSetRouterRequest router + */ + + /** + * Constructs a new PatchNamedSetRouterRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a PatchNamedSetRouterRequest. + * @implements IPatchNamedSetRouterRequest + * @constructor + * @param {google.cloud.compute.v1beta.IPatchNamedSetRouterRequest=} [properties] Properties to set + */ + function PatchNamedSetRouterRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PatchNamedSetRouterRequest namedSetResource. + * @member {google.cloud.compute.v1beta.INamedSet|null|undefined} namedSetResource + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @instance + */ + PatchNamedSetRouterRequest.prototype.namedSetResource = null; + + /** + * PatchNamedSetRouterRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @instance + */ + PatchNamedSetRouterRequest.prototype.project = ""; + + /** + * PatchNamedSetRouterRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @instance + */ + PatchNamedSetRouterRequest.prototype.region = ""; + + /** + * PatchNamedSetRouterRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @instance + */ + PatchNamedSetRouterRequest.prototype.requestId = null; + + /** + * PatchNamedSetRouterRequest router. + * @member {string} router + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @instance + */ + PatchNamedSetRouterRequest.prototype.router = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(PatchNamedSetRouterRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new PatchNamedSetRouterRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IPatchNamedSetRouterRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.PatchNamedSetRouterRequest} PatchNamedSetRouterRequest instance + */ + PatchNamedSetRouterRequest.create = function create(properties) { + return new PatchNamedSetRouterRequest(properties); + }; + + /** + * Encodes the specified PatchNamedSetRouterRequest message. Does not implicitly {@link google.cloud.compute.v1beta.PatchNamedSetRouterRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IPatchNamedSetRouterRequest} message PatchNamedSetRouterRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PatchNamedSetRouterRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.router != null && Object.hasOwnProperty.call(message, "router")) + writer.uint32(/* id 148608841, wireType 2 =*/1188870730).string(message.router); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.namedSetResource != null && Object.hasOwnProperty.call(message, "namedSetResource")) + $root.google.cloud.compute.v1beta.NamedSet.encode(message.namedSetResource, writer.uint32(/* id 408608401, wireType 2 =*/3268867210).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified PatchNamedSetRouterRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.PatchNamedSetRouterRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IPatchNamedSetRouterRequest} message PatchNamedSetRouterRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + PatchNamedSetRouterRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a PatchNamedSetRouterRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.PatchNamedSetRouterRequest} PatchNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PatchNamedSetRouterRequest.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.cloud.compute.v1beta.PatchNamedSetRouterRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 408608401: { + message.namedSetResource = $root.google.cloud.compute.v1beta.NamedSet.decode(reader, reader.uint32()); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + case 148608841: { + message.router = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a PatchNamedSetRouterRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.PatchNamedSetRouterRequest} PatchNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + PatchNamedSetRouterRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a PatchNamedSetRouterRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + PatchNamedSetRouterRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.namedSetResource != null && message.hasOwnProperty("namedSetResource")) { + var error = $root.google.cloud.compute.v1beta.NamedSet.verify(message.namedSetResource); + if (error) + return "namedSetResource." + error; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + if (message.router != null && message.hasOwnProperty("router")) + if (!$util.isString(message.router)) + return "router: string expected"; + return null; + }; + + /** + * Creates a PatchNamedSetRouterRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.PatchNamedSetRouterRequest} PatchNamedSetRouterRequest + */ + PatchNamedSetRouterRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.PatchNamedSetRouterRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.PatchNamedSetRouterRequest(); + if (object.namedSetResource != null) { + if (typeof object.namedSetResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.PatchNamedSetRouterRequest.namedSetResource: object expected"); + message.namedSetResource = $root.google.cloud.compute.v1beta.NamedSet.fromObject(object.namedSetResource); + } + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.requestId != null) + message.requestId = String(object.requestId); + if (object.router != null) + message.router = String(object.router); + return message; + }; + + /** + * Creates a plain object from a PatchNamedSetRouterRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.PatchNamedSetRouterRequest} message PatchNamedSetRouterRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PatchNamedSetRouterRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.router = ""; + object.project = ""; + object.namedSetResource = null; + } + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.router != null && message.hasOwnProperty("router")) + object.router = message.router; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.namedSetResource != null && message.hasOwnProperty("namedSetResource")) + object.namedSetResource = $root.google.cloud.compute.v1beta.NamedSet.toObject(message.namedSetResource, options); + return object; + }; + + /** + * Converts this PatchNamedSetRouterRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @instance + * @returns {Object.} JSON object + */ + PatchNamedSetRouterRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PatchNamedSetRouterRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.PatchNamedSetRouterRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PatchNamedSetRouterRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.PatchNamedSetRouterRequest"; + }; + + return PatchNamedSetRouterRequest; + })(); + v1beta.PatchNetworkAttachmentRequest = (function() { /** @@ -1145182,11 +1159342,13 @@ * @property {string|null} [deleteAtTime] Reservation deleteAtTime * @property {string|null} [deploymentType] Reservation deploymentType * @property {string|null} [description] Reservation description + * @property {string|null} [earlyAccessMaintenance] Reservation earlyAccessMaintenance * @property {boolean|null} [enableEmergentMaintenance] Reservation enableEmergentMaintenance * @property {number|Long|null} [id] Reservation id * @property {string|null} [kind] Reservation kind * @property {Array.|null} [linkedCommitments] Reservation linkedCommitments * @property {string|null} [name] Reservation name + * @property {google.cloud.compute.v1beta.IReservationParams|null} [params] Reservation params * @property {string|null} [protectionTier] Reservation protectionTier * @property {string|null} [reservationMode] Reservation reservationMode * @property {google.cloud.compute.v1beta.IAllocationReservationSharingPolicy|null} [reservationSharingPolicy] Reservation reservationSharingPolicy @@ -1145283,6 +1159445,14 @@ */ Reservation.prototype.description = null; + /** + * Reservation earlyAccessMaintenance. + * @member {string|null|undefined} earlyAccessMaintenance + * @memberof google.cloud.compute.v1beta.Reservation + * @instance + */ + Reservation.prototype.earlyAccessMaintenance = null; + /** * Reservation enableEmergentMaintenance. * @member {boolean|null|undefined} enableEmergentMaintenance @@ -1145323,6 +1159493,14 @@ */ Reservation.prototype.name = null; + /** + * Reservation params. + * @member {google.cloud.compute.v1beta.IReservationParams|null|undefined} params + * @memberof google.cloud.compute.v1beta.Reservation + * @instance + */ + Reservation.prototype.params = null; + /** * Reservation protectionTier. * @member {string|null|undefined} protectionTier @@ -1145478,6 +1159656,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(Reservation.prototype, "_earlyAccessMaintenance", { + get: $util.oneOfGetter($oneOfFields = ["earlyAccessMaintenance"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(Reservation.prototype, "_enableEmergentMaintenance", { get: $util.oneOfGetter($oneOfFields = ["enableEmergentMaintenance"]), @@ -1145502,6 +1159686,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(Reservation.prototype, "_params", { + get: $util.oneOfGetter($oneOfFields = ["params"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(Reservation.prototype, "_protectionTier", { get: $util.oneOfGetter($oneOfFields = ["protectionTier"]), @@ -1145611,6 +1159801,8 @@ writer.uint32(/* id 22220385, wireType 2 =*/177763082).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourcePolicies[keys[i]]).ldelim(); if (message.creationTimestamp != null && Object.hasOwnProperty.call(message, "creationTimestamp")) writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.cloud.compute.v1beta.ReservationParams.encode(message.params, writer.uint32(/* id 78313862, wireType 2 =*/626510898).fork()).ldelim(); if (message.deleteAtTime != null && Object.hasOwnProperty.call(message, "deleteAtTime")) writer.uint32(/* id 83294405, wireType 2 =*/666355242).string(message.deleteAtTime); if (message.status != null && Object.hasOwnProperty.call(message, "status")) @@ -1145631,6 +1159823,8 @@ $root.google.cloud.compute.v1beta.AllocationAggregateReservation.encode(message.aggregateReservation, writer.uint32(/* id 291567948, wireType 2 =*/2332543586).fork()).ldelim(); if (message.deleteAfterDuration != null && Object.hasOwnProperty.call(message, "deleteAfterDuration")) $root.google.cloud.compute.v1beta.Duration.encode(message.deleteAfterDuration, writer.uint32(/* id 323997099, wireType 2 =*/2591976794).fork()).ldelim(); + if (message.earlyAccessMaintenance != null && Object.hasOwnProperty.call(message, "earlyAccessMaintenance")) + writer.uint32(/* id 343918356, wireType 2 =*/2751346850).string(message.earlyAccessMaintenance); if (message.enableEmergentMaintenance != null && Object.hasOwnProperty.call(message, "enableEmergentMaintenance")) writer.uint32(/* id 353759497, wireType 0 =*/2830075976).bool(message.enableEmergentMaintenance); if (message.deploymentType != null && Object.hasOwnProperty.call(message, "deploymentType")) @@ -1145720,6 +1159914,10 @@ message.description = reader.string(); break; } + case 343918356: { + message.earlyAccessMaintenance = reader.string(); + break; + } case 353759497: { message.enableEmergentMaintenance = reader.bool(); break; @@ -1145742,6 +1159940,10 @@ message.name = reader.string(); break; } + case 78313862: { + message.params = $root.google.cloud.compute.v1beta.ReservationParams.decode(reader, reader.uint32()); + break; + } case 503959432: { message.protectionTier = reader.string(); break; @@ -1145898,6 +1160100,11 @@ if (!$util.isString(message.description)) return "description: string expected"; } + if (message.earlyAccessMaintenance != null && message.hasOwnProperty("earlyAccessMaintenance")) { + properties._earlyAccessMaintenance = 1; + if (!$util.isString(message.earlyAccessMaintenance)) + return "earlyAccessMaintenance: string expected"; + } if (message.enableEmergentMaintenance != null && message.hasOwnProperty("enableEmergentMaintenance")) { properties._enableEmergentMaintenance = 1; if (typeof message.enableEmergentMaintenance !== "boolean") @@ -1145925,6 +1160132,14 @@ if (!$util.isString(message.name)) return "name: string expected"; } + if (message.params != null && message.hasOwnProperty("params")) { + properties._params = 1; + { + var error = $root.google.cloud.compute.v1beta.ReservationParams.verify(message.params); + if (error) + return "params." + error; + } + } if (message.protectionTier != null && message.hasOwnProperty("protectionTier")) { properties._protectionTier = 1; if (!$util.isString(message.protectionTier)) @@ -1146045,6 +1160260,8 @@ message.deploymentType = String(object.deploymentType); if (object.description != null) message.description = String(object.description); + if (object.earlyAccessMaintenance != null) + message.earlyAccessMaintenance = String(object.earlyAccessMaintenance); if (object.enableEmergentMaintenance != null) message.enableEmergentMaintenance = Boolean(object.enableEmergentMaintenance); if (object.id != null) @@ -1146067,6 +1160284,11 @@ } if (object.name != null) message.name = String(object.name); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.cloud.compute.v1beta.Reservation.params: object expected"); + message.params = $root.google.cloud.compute.v1beta.ReservationParams.fromObject(object.params); + } if (object.protectionTier != null) message.protectionTier = String(object.protectionTier); if (object.reservationMode != null) @@ -1146164,6 +1160386,11 @@ if (options.oneofs) object._creationTimestamp = "creationTimestamp"; } + if (message.params != null && message.hasOwnProperty("params")) { + object.params = $root.google.cloud.compute.v1beta.ReservationParams.toObject(message.params, options); + if (options.oneofs) + object._params = "params"; + } if (message.deleteAtTime != null && message.hasOwnProperty("deleteAtTime")) { object.deleteAtTime = message.deleteAtTime; if (options.oneofs) @@ -1146214,6 +1160441,11 @@ if (options.oneofs) object._deleteAfterDuration = "deleteAfterDuration"; } + if (message.earlyAccessMaintenance != null && message.hasOwnProperty("earlyAccessMaintenance")) { + object.earlyAccessMaintenance = message.earlyAccessMaintenance; + if (options.oneofs) + object._earlyAccessMaintenance = "earlyAccessMaintenance"; + } if (message.enableEmergentMaintenance != null && message.hasOwnProperty("enableEmergentMaintenance")) { object.enableEmergentMaintenance = message.enableEmergentMaintenance; if (options.oneofs) @@ -1146311,6 +1160543,24 @@ return values; })(); + /** + * EarlyAccessMaintenance enum. + * @name google.cloud.compute.v1beta.Reservation.EarlyAccessMaintenance + * @enum {number} + * @property {number} UNDEFINED_EARLY_ACCESS_MAINTENANCE=0 UNDEFINED_EARLY_ACCESS_MAINTENANCE value + * @property {number} NO_EARLY_ACCESS=220751774 NO_EARLY_ACCESS value + * @property {number} WAVE1=82367576 WAVE1 value + * @property {number} WAVE2=82367577 WAVE2 value + */ + Reservation.EarlyAccessMaintenance = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_EARLY_ACCESS_MAINTENANCE"] = 0; + values[valuesById[220751774] = "NO_EARLY_ACCESS"] = 220751774; + values[valuesById[82367576] = "WAVE1"] = 82367576; + values[valuesById[82367577] = "WAVE2"] = 82367577; + return values; + })(); + /** * ProtectionTier enum. * @name google.cloud.compute.v1beta.Reservation.ProtectionTier @@ -1150349,38 +1164599,25 @@ return ReservationList; })(); - v1beta.ReservationSubBlock = (function() { + v1beta.ReservationParams = (function() { /** - * Properties of a ReservationSubBlock. + * Properties of a ReservationParams. * @memberof google.cloud.compute.v1beta - * @interface IReservationSubBlock - * @property {google.cloud.compute.v1beta.IAcceleratorTopologiesInfo|null} [acceleratorTopologiesInfo] ReservationSubBlock acceleratorTopologiesInfo - * @property {number|null} [count] ReservationSubBlock count - * @property {string|null} [creationTimestamp] ReservationSubBlock creationTimestamp - * @property {google.cloud.compute.v1beta.IReservationSubBlockHealthInfo|null} [healthInfo] ReservationSubBlock healthInfo - * @property {number|Long|null} [id] ReservationSubBlock id - * @property {number|null} [inUseCount] ReservationSubBlock inUseCount - * @property {number|null} [inUseHostCount] ReservationSubBlock inUseHostCount - * @property {string|null} [kind] ReservationSubBlock kind - * @property {string|null} [name] ReservationSubBlock name - * @property {google.cloud.compute.v1beta.IReservationSubBlockPhysicalTopology|null} [physicalTopology] ReservationSubBlock physicalTopology - * @property {google.cloud.compute.v1beta.IGroupMaintenanceInfo|null} [reservationSubBlockMaintenance] ReservationSubBlock reservationSubBlockMaintenance - * @property {string|null} [selfLink] ReservationSubBlock selfLink - * @property {string|null} [selfLinkWithId] ReservationSubBlock selfLinkWithId - * @property {string|null} [status] ReservationSubBlock status - * @property {string|null} [zone] ReservationSubBlock zone + * @interface IReservationParams + * @property {Object.|null} [resourceManagerTags] ReservationParams resourceManagerTags */ /** - * Constructs a new ReservationSubBlock. + * Constructs a new ReservationParams. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a ReservationSubBlock. - * @implements IReservationSubBlock + * @classdesc Represents a ReservationParams. + * @implements IReservationParams * @constructor - * @param {google.cloud.compute.v1beta.IReservationSubBlock=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.IReservationParams=} [properties] Properties to set */ - function ReservationSubBlock(properties) { + function ReservationParams(properties) { + this.resourceManagerTags = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1150388,240 +1164625,433 @@ } /** - * ReservationSubBlock acceleratorTopologiesInfo. - * @member {google.cloud.compute.v1beta.IAcceleratorTopologiesInfo|null|undefined} acceleratorTopologiesInfo - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * ReservationParams resourceManagerTags. + * @member {Object.} resourceManagerTags + * @memberof google.cloud.compute.v1beta.ReservationParams * @instance */ - ReservationSubBlock.prototype.acceleratorTopologiesInfo = null; + ReservationParams.prototype.resourceManagerTags = $util.emptyObject; /** - * ReservationSubBlock count. - * @member {number|null|undefined} count - * @memberof google.cloud.compute.v1beta.ReservationSubBlock - * @instance + * Creates a new ReservationParams instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {google.cloud.compute.v1beta.IReservationParams=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ReservationParams} ReservationParams instance */ - ReservationSubBlock.prototype.count = null; + ReservationParams.create = function create(properties) { + return new ReservationParams(properties); + }; /** - * ReservationSubBlock creationTimestamp. - * @member {string|null|undefined} creationTimestamp - * @memberof google.cloud.compute.v1beta.ReservationSubBlock - * @instance + * Encodes the specified ReservationParams message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationParams.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {google.cloud.compute.v1beta.IReservationParams} message ReservationParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer */ - ReservationSubBlock.prototype.creationTimestamp = null; + ReservationParams.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceManagerTags != null && Object.hasOwnProperty.call(message, "resourceManagerTags")) + for (var keys = Object.keys(message.resourceManagerTags), i = 0; i < keys.length; ++i) + writer.uint32(/* id 377671164, wireType 2 =*/3021369314).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourceManagerTags[keys[i]]).ldelim(); + return writer; + }; /** - * ReservationSubBlock healthInfo. - * @member {google.cloud.compute.v1beta.IReservationSubBlockHealthInfo|null|undefined} healthInfo - * @memberof google.cloud.compute.v1beta.ReservationSubBlock - * @instance + * Encodes the specified ReservationParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationParams.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {google.cloud.compute.v1beta.IReservationParams} message ReservationParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer */ - ReservationSubBlock.prototype.healthInfo = null; + ReservationParams.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; /** - * ReservationSubBlock id. - * @member {number|Long|null|undefined} id - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * Decodes a ReservationParams message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ReservationParams} ReservationParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationParams.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.cloud.compute.v1beta.ReservationParams(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 377671164: { + if (message.resourceManagerTags === $util.emptyObject) + message.resourceManagerTags = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.resourceManagerTags[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReservationParams message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ReservationParams} ReservationParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationParams.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReservationParams message. + * @function verify + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReservationParams.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceManagerTags != null && message.hasOwnProperty("resourceManagerTags")) { + if (!$util.isObject(message.resourceManagerTags)) + return "resourceManagerTags: object expected"; + var key = Object.keys(message.resourceManagerTags); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.resourceManagerTags[key[i]])) + return "resourceManagerTags: string{k:string} expected"; + } + return null; + }; + + /** + * Creates a ReservationParams message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ReservationParams} ReservationParams + */ + ReservationParams.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ReservationParams) + return object; + var message = new $root.google.cloud.compute.v1beta.ReservationParams(); + if (object.resourceManagerTags) { + if (typeof object.resourceManagerTags !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationParams.resourceManagerTags: object expected"); + message.resourceManagerTags = {}; + for (var keys = Object.keys(object.resourceManagerTags), i = 0; i < keys.length; ++i) + message.resourceManagerTags[keys[i]] = String(object.resourceManagerTags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a ReservationParams message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {google.cloud.compute.v1beta.ReservationParams} message ReservationParams + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservationParams.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.resourceManagerTags = {}; + var keys2; + if (message.resourceManagerTags && (keys2 = Object.keys(message.resourceManagerTags)).length) { + object.resourceManagerTags = {}; + for (var j = 0; j < keys2.length; ++j) + object.resourceManagerTags[keys2[j]] = message.resourceManagerTags[keys2[j]]; + } + return object; + }; + + /** + * Converts this ReservationParams to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ReservationParams * @instance + * @returns {Object.} JSON object */ - ReservationSubBlock.prototype.id = null; + ReservationParams.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; /** - * ReservationSubBlock inUseCount. - * @member {number|null|undefined} inUseCount - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * Gets the default type url for ReservationParams + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ReservationParams + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservationParams.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ReservationParams"; + }; + + return ReservationParams; + })(); + + v1beta.ReservationSlot = (function() { + + /** + * Properties of a ReservationSlot. + * @memberof google.cloud.compute.v1beta + * @interface IReservationSlot + * @property {string|null} [creationTimestamp] ReservationSlot creationTimestamp + * @property {number|Long|null} [id] ReservationSlot id + * @property {string|null} [kind] ReservationSlot kind + * @property {string|null} [name] ReservationSlot name + * @property {google.cloud.compute.v1beta.IReservationSlotPhysicalTopology|null} [physicalTopology] ReservationSlot physicalTopology + * @property {string|null} [selfLink] ReservationSlot selfLink + * @property {string|null} [selfLinkWithId] ReservationSlot selfLinkWithId + * @property {google.cloud.compute.v1beta.IShareSettings|null} [shareSettings] ReservationSlot shareSettings + * @property {string|null} [state] ReservationSlot state + * @property {google.cloud.compute.v1beta.IReservationSlotStatus|null} [status] ReservationSlot status + * @property {string|null} [zone] ReservationSlot zone + */ + + /** + * Constructs a new ReservationSlot. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ReservationSlot. + * @implements IReservationSlot + * @constructor + * @param {google.cloud.compute.v1beta.IReservationSlot=} [properties] Properties to set + */ + function ReservationSlot(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservationSlot creationTimestamp. + * @member {string|null|undefined} creationTimestamp + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.inUseCount = null; + ReservationSlot.prototype.creationTimestamp = null; /** - * ReservationSubBlock inUseHostCount. - * @member {number|null|undefined} inUseHostCount - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * ReservationSlot id. + * @member {number|Long|null|undefined} id + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.inUseHostCount = null; + ReservationSlot.prototype.id = null; /** - * ReservationSubBlock kind. + * ReservationSlot kind. * @member {string|null|undefined} kind - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.kind = null; + ReservationSlot.prototype.kind = null; /** - * ReservationSubBlock name. + * ReservationSlot name. * @member {string|null|undefined} name - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.name = null; + ReservationSlot.prototype.name = null; /** - * ReservationSubBlock physicalTopology. - * @member {google.cloud.compute.v1beta.IReservationSubBlockPhysicalTopology|null|undefined} physicalTopology - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * ReservationSlot physicalTopology. + * @member {google.cloud.compute.v1beta.IReservationSlotPhysicalTopology|null|undefined} physicalTopology + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.physicalTopology = null; + ReservationSlot.prototype.physicalTopology = null; /** - * ReservationSubBlock reservationSubBlockMaintenance. - * @member {google.cloud.compute.v1beta.IGroupMaintenanceInfo|null|undefined} reservationSubBlockMaintenance - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * ReservationSlot selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.reservationSubBlockMaintenance = null; + ReservationSlot.prototype.selfLink = null; /** - * ReservationSubBlock selfLink. - * @member {string|null|undefined} selfLink - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * ReservationSlot selfLinkWithId. + * @member {string|null|undefined} selfLinkWithId + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.selfLink = null; + ReservationSlot.prototype.selfLinkWithId = null; /** - * ReservationSubBlock selfLinkWithId. - * @member {string|null|undefined} selfLinkWithId - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * ReservationSlot shareSettings. + * @member {google.cloud.compute.v1beta.IShareSettings|null|undefined} shareSettings + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.selfLinkWithId = null; + ReservationSlot.prototype.shareSettings = null; /** - * ReservationSubBlock status. - * @member {string|null|undefined} status - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * ReservationSlot state. + * @member {string|null|undefined} state + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.status = null; + ReservationSlot.prototype.state = null; /** - * ReservationSubBlock zone. + * ReservationSlot status. + * @member {google.cloud.compute.v1beta.IReservationSlotStatus|null|undefined} status + * @memberof google.cloud.compute.v1beta.ReservationSlot + * @instance + */ + ReservationSlot.prototype.status = null; + + /** + * ReservationSlot zone. * @member {string|null|undefined} zone - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @instance */ - ReservationSubBlock.prototype.zone = null; + ReservationSlot.prototype.zone = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_acceleratorTopologiesInfo", { - get: $util.oneOfGetter($oneOfFields = ["acceleratorTopologiesInfo"]), - set: $util.oneOfSetter($oneOfFields) - }); - - // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_count", { - get: $util.oneOfGetter($oneOfFields = ["count"]), - set: $util.oneOfSetter($oneOfFields) - }); - - // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_creationTimestamp", { + Object.defineProperty(ReservationSlot.prototype, "_creationTimestamp", { get: $util.oneOfGetter($oneOfFields = ["creationTimestamp"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_healthInfo", { - get: $util.oneOfGetter($oneOfFields = ["healthInfo"]), - set: $util.oneOfSetter($oneOfFields) - }); - - // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_id", { + Object.defineProperty(ReservationSlot.prototype, "_id", { get: $util.oneOfGetter($oneOfFields = ["id"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_inUseCount", { - get: $util.oneOfGetter($oneOfFields = ["inUseCount"]), - set: $util.oneOfSetter($oneOfFields) - }); - - // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_inUseHostCount", { - get: $util.oneOfGetter($oneOfFields = ["inUseHostCount"]), + Object.defineProperty(ReservationSlot.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_kind", { - get: $util.oneOfGetter($oneOfFields = ["kind"]), + Object.defineProperty(ReservationSlot.prototype, "_name", { + get: $util.oneOfGetter($oneOfFields = ["name"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_name", { - get: $util.oneOfGetter($oneOfFields = ["name"]), + Object.defineProperty(ReservationSlot.prototype, "_physicalTopology", { + get: $util.oneOfGetter($oneOfFields = ["physicalTopology"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_physicalTopology", { - get: $util.oneOfGetter($oneOfFields = ["physicalTopology"]), + Object.defineProperty(ReservationSlot.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_reservationSubBlockMaintenance", { - get: $util.oneOfGetter($oneOfFields = ["reservationSubBlockMaintenance"]), + Object.defineProperty(ReservationSlot.prototype, "_selfLinkWithId", { + get: $util.oneOfGetter($oneOfFields = ["selfLinkWithId"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_selfLink", { - get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + Object.defineProperty(ReservationSlot.prototype, "_shareSettings", { + get: $util.oneOfGetter($oneOfFields = ["shareSettings"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_selfLinkWithId", { - get: $util.oneOfGetter($oneOfFields = ["selfLinkWithId"]), + Object.defineProperty(ReservationSlot.prototype, "_state", { + get: $util.oneOfGetter($oneOfFields = ["state"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_status", { + Object.defineProperty(ReservationSlot.prototype, "_status", { get: $util.oneOfGetter($oneOfFields = ["status"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(ReservationSubBlock.prototype, "_zone", { + Object.defineProperty(ReservationSlot.prototype, "_zone", { get: $util.oneOfGetter($oneOfFields = ["zone"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new ReservationSubBlock instance using the specified properties. + * Creates a new ReservationSlot instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @static - * @param {google.cloud.compute.v1beta.IReservationSubBlock=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.ReservationSubBlock} ReservationSubBlock instance + * @param {google.cloud.compute.v1beta.IReservationSlot=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ReservationSlot} ReservationSlot instance */ - ReservationSubBlock.create = function create(properties) { - return new ReservationSubBlock(properties); + ReservationSlot.create = function create(properties) { + return new ReservationSlot(properties); }; /** - * Encodes the specified ReservationSubBlock message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSubBlock.verify|verify} messages. + * Encodes the specified ReservationSlot message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlot.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @static - * @param {google.cloud.compute.v1beta.IReservationSubBlock} message ReservationSubBlock message or plain object to encode + * @param {google.cloud.compute.v1beta.IReservationSlot} message ReservationSlot message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ReservationSubBlock.encode = function encode(message, writer) { + ReservationSlot.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.id != null && Object.hasOwnProperty.call(message, "id")) @@ -1150636,88 +1165066,60 @@ writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); if (message.selfLinkWithId != null && Object.hasOwnProperty.call(message, "selfLinkWithId")) writer.uint32(/* id 44520962, wireType 2 =*/356167698).string(message.selfLinkWithId); - if (message.acceleratorTopologiesInfo != null && Object.hasOwnProperty.call(message, "acceleratorTopologiesInfo")) - $root.google.cloud.compute.v1beta.AcceleratorTopologiesInfo.encode(message.acceleratorTopologiesInfo, writer.uint32(/* id 84833420, wireType 2 =*/678667362).fork()).ldelim(); - if (message.count != null && Object.hasOwnProperty.call(message, "count")) - writer.uint32(/* id 94851343, wireType 0 =*/758810744).int32(message.count); + if (message.state != null && Object.hasOwnProperty.call(message, "state")) + writer.uint32(/* id 109757585, wireType 2 =*/878060682).string(message.state); if (message.status != null && Object.hasOwnProperty.call(message, "status")) - writer.uint32(/* id 181260274, wireType 2 =*/1450082194).string(message.status); - if (message.healthInfo != null && Object.hasOwnProperty.call(message, "healthInfo")) - $root.google.cloud.compute.v1beta.ReservationSubBlockHealthInfo.encode(message.healthInfo, writer.uint32(/* id 235287729, wireType 2 =*/1882301834).fork()).ldelim(); + $root.google.cloud.compute.v1beta.ReservationSlotStatus.encode(message.status, writer.uint32(/* id 181260274, wireType 2 =*/1450082194).fork()).ldelim(); + if (message.shareSettings != null && Object.hasOwnProperty.call(message, "shareSettings")) + $root.google.cloud.compute.v1beta.ShareSettings.encode(message.shareSettings, writer.uint32(/* id 266668163, wireType 2 =*/2133345306).fork()).ldelim(); if (message.physicalTopology != null && Object.hasOwnProperty.call(message, "physicalTopology")) - $root.google.cloud.compute.v1beta.ReservationSubBlockPhysicalTopology.encode(message.physicalTopology, writer.uint32(/* id 279778519, wireType 2 =*/2238228154).fork()).ldelim(); - if (message.inUseHostCount != null && Object.hasOwnProperty.call(message, "inUseHostCount")) - writer.uint32(/* id 364069834, wireType 0 =*/2912558672).int32(message.inUseHostCount); - if (message.reservationSubBlockMaintenance != null && Object.hasOwnProperty.call(message, "reservationSubBlockMaintenance")) - $root.google.cloud.compute.v1beta.GroupMaintenanceInfo.encode(message.reservationSubBlockMaintenance, writer.uint32(/* id 377005551, wireType 2 =*/3016044410).fork()).ldelim(); + $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.encode(message.physicalTopology, writer.uint32(/* id 279778519, wireType 2 =*/2238228154).fork()).ldelim(); if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); - if (message.inUseCount != null && Object.hasOwnProperty.call(message, "inUseCount")) - writer.uint32(/* id 493458877, wireType 0 =*/3947671016).int32(message.inUseCount); return writer; }; /** - * Encodes the specified ReservationSubBlock message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSubBlock.verify|verify} messages. + * Encodes the specified ReservationSlot message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlot.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @static - * @param {google.cloud.compute.v1beta.IReservationSubBlock} message ReservationSubBlock message or plain object to encode + * @param {google.cloud.compute.v1beta.IReservationSlot} message ReservationSlot message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ReservationSubBlock.encodeDelimited = function encodeDelimited(message, writer) { + ReservationSlot.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a ReservationSubBlock message from the specified reader or buffer. + * Decodes a ReservationSlot message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.ReservationSubBlock} ReservationSubBlock + * @returns {google.cloud.compute.v1beta.ReservationSlot} ReservationSlot * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ReservationSubBlock.decode = function decode(reader, length, error) { + ReservationSlot.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.cloud.compute.v1beta.ReservationSubBlock(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.ReservationSlot(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { - case 84833420: { - message.acceleratorTopologiesInfo = $root.google.cloud.compute.v1beta.AcceleratorTopologiesInfo.decode(reader, reader.uint32()); - break; - } - case 94851343: { - message.count = reader.int32(); - break; - } case 30525366: { message.creationTimestamp = reader.string(); break; } - case 235287729: { - message.healthInfo = $root.google.cloud.compute.v1beta.ReservationSubBlockHealthInfo.decode(reader, reader.uint32()); - break; - } case 3355: { message.id = reader.uint64(); break; } - case 493458877: { - message.inUseCount = reader.int32(); - break; - } - case 364069834: { - message.inUseHostCount = reader.int32(); - break; - } case 3292052: { message.kind = reader.string(); break; @@ -1150727,11 +1165129,7 @@ break; } case 279778519: { - message.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSubBlockPhysicalTopology.decode(reader, reader.uint32()); - break; - } - case 377005551: { - message.reservationSubBlockMaintenance = $root.google.cloud.compute.v1beta.GroupMaintenanceInfo.decode(reader, reader.uint32()); + message.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.decode(reader, reader.uint32()); break; } case 456214797: { @@ -1150742,8 +1165140,16 @@ message.selfLinkWithId = reader.string(); break; } + case 266668163: { + message.shareSettings = $root.google.cloud.compute.v1beta.ShareSettings.decode(reader, reader.uint32()); + break; + } + case 109757585: { + message.state = reader.string(); + break; + } case 181260274: { - message.status = reader.string(); + message.status = $root.google.cloud.compute.v1beta.ReservationSlotStatus.decode(reader, reader.uint32()); break; } case 3744684: { @@ -1150759,74 +1165165,43 @@ }; /** - * Decodes a ReservationSubBlock message from the specified reader or buffer, length delimited. + * Decodes a ReservationSlot message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.ReservationSubBlock} ReservationSubBlock + * @returns {google.cloud.compute.v1beta.ReservationSlot} ReservationSlot * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ReservationSubBlock.decodeDelimited = function decodeDelimited(reader) { + ReservationSlot.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a ReservationSubBlock message. + * Verifies a ReservationSlot message. * @function verify - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ReservationSubBlock.verify = function verify(message) { + ReservationSlot.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; - if (message.acceleratorTopologiesInfo != null && message.hasOwnProperty("acceleratorTopologiesInfo")) { - properties._acceleratorTopologiesInfo = 1; - { - var error = $root.google.cloud.compute.v1beta.AcceleratorTopologiesInfo.verify(message.acceleratorTopologiesInfo); - if (error) - return "acceleratorTopologiesInfo." + error; - } - } - if (message.count != null && message.hasOwnProperty("count")) { - properties._count = 1; - if (!$util.isInteger(message.count)) - return "count: integer expected"; - } if (message.creationTimestamp != null && message.hasOwnProperty("creationTimestamp")) { properties._creationTimestamp = 1; if (!$util.isString(message.creationTimestamp)) return "creationTimestamp: string expected"; } - if (message.healthInfo != null && message.hasOwnProperty("healthInfo")) { - properties._healthInfo = 1; - { - var error = $root.google.cloud.compute.v1beta.ReservationSubBlockHealthInfo.verify(message.healthInfo); - if (error) - return "healthInfo." + error; - } - } if (message.id != null && message.hasOwnProperty("id")) { properties._id = 1; if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) return "id: integer|Long expected"; } - if (message.inUseCount != null && message.hasOwnProperty("inUseCount")) { - properties._inUseCount = 1; - if (!$util.isInteger(message.inUseCount)) - return "inUseCount: integer expected"; - } - if (message.inUseHostCount != null && message.hasOwnProperty("inUseHostCount")) { - properties._inUseHostCount = 1; - if (!$util.isInteger(message.inUseHostCount)) - return "inUseHostCount: integer expected"; - } if (message.kind != null && message.hasOwnProperty("kind")) { properties._kind = 1; if (!$util.isString(message.kind)) @@ -1150840,19 +1165215,11 @@ if (message.physicalTopology != null && message.hasOwnProperty("physicalTopology")) { properties._physicalTopology = 1; { - var error = $root.google.cloud.compute.v1beta.ReservationSubBlockPhysicalTopology.verify(message.physicalTopology); + var error = $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.verify(message.physicalTopology); if (error) return "physicalTopology." + error; } } - if (message.reservationSubBlockMaintenance != null && message.hasOwnProperty("reservationSubBlockMaintenance")) { - properties._reservationSubBlockMaintenance = 1; - { - var error = $root.google.cloud.compute.v1beta.GroupMaintenanceInfo.verify(message.reservationSubBlockMaintenance); - if (error) - return "reservationSubBlockMaintenance." + error; - } - } if (message.selfLink != null && message.hasOwnProperty("selfLink")) { properties._selfLink = 1; if (!$util.isString(message.selfLink)) @@ -1150863,10 +1165230,26 @@ if (!$util.isString(message.selfLinkWithId)) return "selfLinkWithId: string expected"; } + if (message.shareSettings != null && message.hasOwnProperty("shareSettings")) { + properties._shareSettings = 1; + { + var error = $root.google.cloud.compute.v1beta.ShareSettings.verify(message.shareSettings); + if (error) + return "shareSettings." + error; + } + } + if (message.state != null && message.hasOwnProperty("state")) { + properties._state = 1; + if (!$util.isString(message.state)) + return "state: string expected"; + } if (message.status != null && message.hasOwnProperty("status")) { properties._status = 1; - if (!$util.isString(message.status)) - return "status: string expected"; + { + var error = $root.google.cloud.compute.v1beta.ReservationSlotStatus.verify(message.status); + if (error) + return "status." + error; + } } if (message.zone != null && message.hasOwnProperty("zone")) { properties._zone = 1; @@ -1150877,31 +1165260,19 @@ }; /** - * Creates a ReservationSubBlock message from a plain object. Also converts values to their respective internal types. + * Creates a ReservationSlot message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.ReservationSubBlock} ReservationSubBlock + * @returns {google.cloud.compute.v1beta.ReservationSlot} ReservationSlot */ - ReservationSubBlock.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.ReservationSubBlock) + ReservationSlot.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ReservationSlot) return object; - var message = new $root.google.cloud.compute.v1beta.ReservationSubBlock(); - if (object.acceleratorTopologiesInfo != null) { - if (typeof object.acceleratorTopologiesInfo !== "object") - throw TypeError(".google.cloud.compute.v1beta.ReservationSubBlock.acceleratorTopologiesInfo: object expected"); - message.acceleratorTopologiesInfo = $root.google.cloud.compute.v1beta.AcceleratorTopologiesInfo.fromObject(object.acceleratorTopologiesInfo); - } - if (object.count != null) - message.count = object.count | 0; + var message = new $root.google.cloud.compute.v1beta.ReservationSlot(); if (object.creationTimestamp != null) message.creationTimestamp = String(object.creationTimestamp); - if (object.healthInfo != null) { - if (typeof object.healthInfo !== "object") - throw TypeError(".google.cloud.compute.v1beta.ReservationSubBlock.healthInfo: object expected"); - message.healthInfo = $root.google.cloud.compute.v1beta.ReservationSubBlockHealthInfo.fromObject(object.healthInfo); - } if (object.id != null) if ($util.Long) (message.id = $util.Long.fromValue(object.id)).unsigned = true; @@ -1150911,45 +1165282,2008 @@ message.id = object.id; else if (typeof object.id === "object") message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(true); - if (object.inUseCount != null) - message.inUseCount = object.inUseCount | 0; - if (object.inUseHostCount != null) - message.inUseHostCount = object.inUseHostCount | 0; if (object.kind != null) message.kind = String(object.kind); if (object.name != null) message.name = String(object.name); if (object.physicalTopology != null) { if (typeof object.physicalTopology !== "object") - throw TypeError(".google.cloud.compute.v1beta.ReservationSubBlock.physicalTopology: object expected"); - message.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSubBlockPhysicalTopology.fromObject(object.physicalTopology); - } - if (object.reservationSubBlockMaintenance != null) { - if (typeof object.reservationSubBlockMaintenance !== "object") - throw TypeError(".google.cloud.compute.v1beta.ReservationSubBlock.reservationSubBlockMaintenance: object expected"); - message.reservationSubBlockMaintenance = $root.google.cloud.compute.v1beta.GroupMaintenanceInfo.fromObject(object.reservationSubBlockMaintenance); + throw TypeError(".google.cloud.compute.v1beta.ReservationSlot.physicalTopology: object expected"); + message.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.fromObject(object.physicalTopology); } if (object.selfLink != null) message.selfLink = String(object.selfLink); if (object.selfLinkWithId != null) message.selfLinkWithId = String(object.selfLinkWithId); - if (object.status != null) - message.status = String(object.status); + if (object.shareSettings != null) { + if (typeof object.shareSettings !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSlot.shareSettings: object expected"); + message.shareSettings = $root.google.cloud.compute.v1beta.ShareSettings.fromObject(object.shareSettings); + } + if (object.state != null) + message.state = String(object.state); + if (object.status != null) { + if (typeof object.status !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSlot.status: object expected"); + message.status = $root.google.cloud.compute.v1beta.ReservationSlotStatus.fromObject(object.status); + } if (object.zone != null) message.zone = String(object.zone); return message; }; /** - * Creates a plain object from a ReservationSubBlock message. Also converts values to other types if specified. + * Creates a plain object from a ReservationSlot message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @memberof google.cloud.compute.v1beta.ReservationSlot * @static - * @param {google.cloud.compute.v1beta.ReservationSubBlock} message ReservationSubBlock + * @param {google.cloud.compute.v1beta.ReservationSlot} message ReservationSlot * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ReservationSubBlock.toObject = function toObject(message, options) { + ReservationSlot.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.id != null && message.hasOwnProperty("id")) { + if (typeof message.id === "number") + object.id = options.longs === String ? String(message.id) : message.id; + else + object.id = options.longs === String ? $util.Long.prototype.toString.call(message.id) : options.longs === Number ? new $util.LongBits(message.id.low >>> 0, message.id.high >>> 0).toNumber(true) : message.id; + if (options.oneofs) + object._id = "id"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + object.kind = message.kind; + if (options.oneofs) + object._kind = "kind"; + } + if (message.name != null && message.hasOwnProperty("name")) { + object.name = message.name; + if (options.oneofs) + object._name = "name"; + } + if (message.zone != null && message.hasOwnProperty("zone")) { + object.zone = message.zone; + if (options.oneofs) + object._zone = "zone"; + } + if (message.creationTimestamp != null && message.hasOwnProperty("creationTimestamp")) { + object.creationTimestamp = message.creationTimestamp; + if (options.oneofs) + object._creationTimestamp = "creationTimestamp"; + } + if (message.selfLinkWithId != null && message.hasOwnProperty("selfLinkWithId")) { + object.selfLinkWithId = message.selfLinkWithId; + if (options.oneofs) + object._selfLinkWithId = "selfLinkWithId"; + } + if (message.state != null && message.hasOwnProperty("state")) { + object.state = message.state; + if (options.oneofs) + object._state = "state"; + } + if (message.status != null && message.hasOwnProperty("status")) { + object.status = $root.google.cloud.compute.v1beta.ReservationSlotStatus.toObject(message.status, options); + if (options.oneofs) + object._status = "status"; + } + if (message.shareSettings != null && message.hasOwnProperty("shareSettings")) { + object.shareSettings = $root.google.cloud.compute.v1beta.ShareSettings.toObject(message.shareSettings, options); + if (options.oneofs) + object._shareSettings = "shareSettings"; + } + if (message.physicalTopology != null && message.hasOwnProperty("physicalTopology")) { + object.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.toObject(message.physicalTopology, options); + if (options.oneofs) + object._physicalTopology = "physicalTopology"; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + object.selfLink = message.selfLink; + if (options.oneofs) + object._selfLink = "selfLink"; + } + return object; + }; + + /** + * Converts this ReservationSlot to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ReservationSlot + * @instance + * @returns {Object.} JSON object + */ + ReservationSlot.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservationSlot + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ReservationSlot + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservationSlot.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ReservationSlot"; + }; + + /** + * State enum. + * @name google.cloud.compute.v1beta.ReservationSlot.State + * @enum {number} + * @property {number} UNDEFINED_STATE=0 UNDEFINED_STATE value + * @property {number} ACTIVE=314733318 ACTIVE value + * @property {number} CREATING=455564985 CREATING value + * @property {number} DELETING=528602024 DELETING value + * @property {number} STATE_UNSPECIFIED=470755401 STATE_UNSPECIFIED value + * @property {number} UNAVAILABLE=413756464 UNAVAILABLE value + */ + ReservationSlot.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_STATE"] = 0; + values[valuesById[314733318] = "ACTIVE"] = 314733318; + values[valuesById[455564985] = "CREATING"] = 455564985; + values[valuesById[528602024] = "DELETING"] = 528602024; + values[valuesById[470755401] = "STATE_UNSPECIFIED"] = 470755401; + values[valuesById[413756464] = "UNAVAILABLE"] = 413756464; + return values; + })(); + + return ReservationSlot; + })(); + + v1beta.ReservationSlotPhysicalTopology = (function() { + + /** + * Properties of a ReservationSlotPhysicalTopology. + * @memberof google.cloud.compute.v1beta + * @interface IReservationSlotPhysicalTopology + * @property {string|null} [block] ReservationSlotPhysicalTopology block + * @property {string|null} [cluster] ReservationSlotPhysicalTopology cluster + * @property {string|null} [host] ReservationSlotPhysicalTopology host + * @property {string|null} [subBlock] ReservationSlotPhysicalTopology subBlock + */ + + /** + * Constructs a new ReservationSlotPhysicalTopology. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ReservationSlotPhysicalTopology. + * @implements IReservationSlotPhysicalTopology + * @constructor + * @param {google.cloud.compute.v1beta.IReservationSlotPhysicalTopology=} [properties] Properties to set + */ + function ReservationSlotPhysicalTopology(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservationSlotPhysicalTopology block. + * @member {string|null|undefined} block + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @instance + */ + ReservationSlotPhysicalTopology.prototype.block = null; + + /** + * ReservationSlotPhysicalTopology cluster. + * @member {string|null|undefined} cluster + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @instance + */ + ReservationSlotPhysicalTopology.prototype.cluster = null; + + /** + * ReservationSlotPhysicalTopology host. + * @member {string|null|undefined} host + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @instance + */ + ReservationSlotPhysicalTopology.prototype.host = null; + + /** + * ReservationSlotPhysicalTopology subBlock. + * @member {string|null|undefined} subBlock + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @instance + */ + ReservationSlotPhysicalTopology.prototype.subBlock = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotPhysicalTopology.prototype, "_block", { + get: $util.oneOfGetter($oneOfFields = ["block"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotPhysicalTopology.prototype, "_cluster", { + get: $util.oneOfGetter($oneOfFields = ["cluster"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotPhysicalTopology.prototype, "_host", { + get: $util.oneOfGetter($oneOfFields = ["host"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotPhysicalTopology.prototype, "_subBlock", { + get: $util.oneOfGetter($oneOfFields = ["subBlock"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReservationSlotPhysicalTopology instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotPhysicalTopology=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ReservationSlotPhysicalTopology} ReservationSlotPhysicalTopology instance + */ + ReservationSlotPhysicalTopology.create = function create(properties) { + return new ReservationSlotPhysicalTopology(properties); + }; + + /** + * Encodes the specified ReservationSlotPhysicalTopology message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotPhysicalTopology} message ReservationSlotPhysicalTopology message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSlotPhysicalTopology.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.host != null && Object.hasOwnProperty.call(message, "host")) + writer.uint32(/* id 3208616, wireType 2 =*/25668930).string(message.host); + if (message.block != null && Object.hasOwnProperty.call(message, "block")) + writer.uint32(/* id 93832333, wireType 2 =*/750658666).string(message.block); + if (message.cluster != null && Object.hasOwnProperty.call(message, "cluster")) + writer.uint32(/* id 335221242, wireType 2 =*/2681769938).string(message.cluster); + if (message.subBlock != null && Object.hasOwnProperty.call(message, "subBlock")) + writer.uint32(/* id 478033358, wireType 2 =*/3824266866).string(message.subBlock); + return writer; + }; + + /** + * Encodes the specified ReservationSlotPhysicalTopology message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotPhysicalTopology} message ReservationSlotPhysicalTopology message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSlotPhysicalTopology.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReservationSlotPhysicalTopology message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ReservationSlotPhysicalTopology} ReservationSlotPhysicalTopology + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSlotPhysicalTopology.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.cloud.compute.v1beta.ReservationSlotPhysicalTopology(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 93832333: { + message.block = reader.string(); + break; + } + case 335221242: { + message.cluster = reader.string(); + break; + } + case 3208616: { + message.host = reader.string(); + break; + } + case 478033358: { + message.subBlock = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReservationSlotPhysicalTopology message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ReservationSlotPhysicalTopology} ReservationSlotPhysicalTopology + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSlotPhysicalTopology.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReservationSlotPhysicalTopology message. + * @function verify + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReservationSlotPhysicalTopology.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.block != null && message.hasOwnProperty("block")) { + properties._block = 1; + if (!$util.isString(message.block)) + return "block: string expected"; + } + if (message.cluster != null && message.hasOwnProperty("cluster")) { + properties._cluster = 1; + if (!$util.isString(message.cluster)) + return "cluster: string expected"; + } + if (message.host != null && message.hasOwnProperty("host")) { + properties._host = 1; + if (!$util.isString(message.host)) + return "host: string expected"; + } + if (message.subBlock != null && message.hasOwnProperty("subBlock")) { + properties._subBlock = 1; + if (!$util.isString(message.subBlock)) + return "subBlock: string expected"; + } + return null; + }; + + /** + * Creates a ReservationSlotPhysicalTopology message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ReservationSlotPhysicalTopology} ReservationSlotPhysicalTopology + */ + ReservationSlotPhysicalTopology.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology) + return object; + var message = new $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology(); + if (object.block != null) + message.block = String(object.block); + if (object.cluster != null) + message.cluster = String(object.cluster); + if (object.host != null) + message.host = String(object.host); + if (object.subBlock != null) + message.subBlock = String(object.subBlock); + return message; + }; + + /** + * Creates a plain object from a ReservationSlotPhysicalTopology message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {google.cloud.compute.v1beta.ReservationSlotPhysicalTopology} message ReservationSlotPhysicalTopology + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservationSlotPhysicalTopology.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.host != null && message.hasOwnProperty("host")) { + object.host = message.host; + if (options.oneofs) + object._host = "host"; + } + if (message.block != null && message.hasOwnProperty("block")) { + object.block = message.block; + if (options.oneofs) + object._block = "block"; + } + if (message.cluster != null && message.hasOwnProperty("cluster")) { + object.cluster = message.cluster; + if (options.oneofs) + object._cluster = "cluster"; + } + if (message.subBlock != null && message.hasOwnProperty("subBlock")) { + object.subBlock = message.subBlock; + if (options.oneofs) + object._subBlock = "subBlock"; + } + return object; + }; + + /** + * Converts this ReservationSlotPhysicalTopology to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @instance + * @returns {Object.} JSON object + */ + ReservationSlotPhysicalTopology.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservationSlotPhysicalTopology + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ReservationSlotPhysicalTopology + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservationSlotPhysicalTopology.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ReservationSlotPhysicalTopology"; + }; + + return ReservationSlotPhysicalTopology; + })(); + + v1beta.ReservationSlotStatus = (function() { + + /** + * Properties of a ReservationSlotStatus. + * @memberof google.cloud.compute.v1beta + * @interface IReservationSlotStatus + * @property {google.cloud.compute.v1beta.IReservationSlotPhysicalTopology|null} [physicalTopology] ReservationSlotStatus physicalTopology + * @property {Array.|null} [rdmaIpAddresses] ReservationSlotStatus rdmaIpAddresses + * @property {Array.|null} [runningInstances] ReservationSlotStatus runningInstances + */ + + /** + * Constructs a new ReservationSlotStatus. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ReservationSlotStatus. + * @implements IReservationSlotStatus + * @constructor + * @param {google.cloud.compute.v1beta.IReservationSlotStatus=} [properties] Properties to set + */ + function ReservationSlotStatus(properties) { + this.rdmaIpAddresses = []; + this.runningInstances = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservationSlotStatus physicalTopology. + * @member {google.cloud.compute.v1beta.IReservationSlotPhysicalTopology|null|undefined} physicalTopology + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @instance + */ + ReservationSlotStatus.prototype.physicalTopology = null; + + /** + * ReservationSlotStatus rdmaIpAddresses. + * @member {Array.} rdmaIpAddresses + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @instance + */ + ReservationSlotStatus.prototype.rdmaIpAddresses = $util.emptyArray; + + /** + * ReservationSlotStatus runningInstances. + * @member {Array.} runningInstances + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @instance + */ + ReservationSlotStatus.prototype.runningInstances = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotStatus.prototype, "_physicalTopology", { + get: $util.oneOfGetter($oneOfFields = ["physicalTopology"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReservationSlotStatus instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotStatus=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ReservationSlotStatus} ReservationSlotStatus instance + */ + ReservationSlotStatus.create = function create(properties) { + return new ReservationSlotStatus(properties); + }; + + /** + * Encodes the specified ReservationSlotStatus message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotStatus.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotStatus} message ReservationSlotStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSlotStatus.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.rdmaIpAddresses != null && message.rdmaIpAddresses.length) + for (var i = 0; i < message.rdmaIpAddresses.length; ++i) + writer.uint32(/* id 167842531, wireType 2 =*/1342740250).string(message.rdmaIpAddresses[i]); + if (message.physicalTopology != null && Object.hasOwnProperty.call(message, "physicalTopology")) + $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.encode(message.physicalTopology, writer.uint32(/* id 279778519, wireType 2 =*/2238228154).fork()).ldelim(); + if (message.runningInstances != null && message.runningInstances.length) + for (var i = 0; i < message.runningInstances.length; ++i) + writer.uint32(/* id 536292350, wireType 2 =*/4290338802).string(message.runningInstances[i]); + return writer; + }; + + /** + * Encodes the specified ReservationSlotStatus message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotStatus.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotStatus} message ReservationSlotStatus message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSlotStatus.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReservationSlotStatus message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ReservationSlotStatus} ReservationSlotStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSlotStatus.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.cloud.compute.v1beta.ReservationSlotStatus(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 279778519: { + message.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.decode(reader, reader.uint32()); + break; + } + case 167842531: { + if (!(message.rdmaIpAddresses && message.rdmaIpAddresses.length)) + message.rdmaIpAddresses = []; + message.rdmaIpAddresses.push(reader.string()); + break; + } + case 536292350: { + if (!(message.runningInstances && message.runningInstances.length)) + message.runningInstances = []; + message.runningInstances.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReservationSlotStatus message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ReservationSlotStatus} ReservationSlotStatus + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSlotStatus.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReservationSlotStatus message. + * @function verify + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReservationSlotStatus.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.physicalTopology != null && message.hasOwnProperty("physicalTopology")) { + properties._physicalTopology = 1; + { + var error = $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.verify(message.physicalTopology); + if (error) + return "physicalTopology." + error; + } + } + if (message.rdmaIpAddresses != null && message.hasOwnProperty("rdmaIpAddresses")) { + if (!Array.isArray(message.rdmaIpAddresses)) + return "rdmaIpAddresses: array expected"; + for (var i = 0; i < message.rdmaIpAddresses.length; ++i) + if (!$util.isString(message.rdmaIpAddresses[i])) + return "rdmaIpAddresses: string[] expected"; + } + if (message.runningInstances != null && message.hasOwnProperty("runningInstances")) { + if (!Array.isArray(message.runningInstances)) + return "runningInstances: array expected"; + for (var i = 0; i < message.runningInstances.length; ++i) + if (!$util.isString(message.runningInstances[i])) + return "runningInstances: string[] expected"; + } + return null; + }; + + /** + * Creates a ReservationSlotStatus message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ReservationSlotStatus} ReservationSlotStatus + */ + ReservationSlotStatus.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ReservationSlotStatus) + return object; + var message = new $root.google.cloud.compute.v1beta.ReservationSlotStatus(); + if (object.physicalTopology != null) { + if (typeof object.physicalTopology !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSlotStatus.physicalTopology: object expected"); + message.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.fromObject(object.physicalTopology); + } + if (object.rdmaIpAddresses) { + if (!Array.isArray(object.rdmaIpAddresses)) + throw TypeError(".google.cloud.compute.v1beta.ReservationSlotStatus.rdmaIpAddresses: array expected"); + message.rdmaIpAddresses = []; + for (var i = 0; i < object.rdmaIpAddresses.length; ++i) + message.rdmaIpAddresses[i] = String(object.rdmaIpAddresses[i]); + } + if (object.runningInstances) { + if (!Array.isArray(object.runningInstances)) + throw TypeError(".google.cloud.compute.v1beta.ReservationSlotStatus.runningInstances: array expected"); + message.runningInstances = []; + for (var i = 0; i < object.runningInstances.length; ++i) + message.runningInstances[i] = String(object.runningInstances[i]); + } + return message; + }; + + /** + * Creates a plain object from a ReservationSlotStatus message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {google.cloud.compute.v1beta.ReservationSlotStatus} message ReservationSlotStatus + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservationSlotStatus.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.rdmaIpAddresses = []; + object.runningInstances = []; + } + if (message.rdmaIpAddresses && message.rdmaIpAddresses.length) { + object.rdmaIpAddresses = []; + for (var j = 0; j < message.rdmaIpAddresses.length; ++j) + object.rdmaIpAddresses[j] = message.rdmaIpAddresses[j]; + } + if (message.physicalTopology != null && message.hasOwnProperty("physicalTopology")) { + object.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSlotPhysicalTopology.toObject(message.physicalTopology, options); + if (options.oneofs) + object._physicalTopology = "physicalTopology"; + } + if (message.runningInstances && message.runningInstances.length) { + object.runningInstances = []; + for (var j = 0; j < message.runningInstances.length; ++j) + object.runningInstances[j] = message.runningInstances[j]; + } + return object; + }; + + /** + * Converts this ReservationSlotStatus to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @instance + * @returns {Object.} JSON object + */ + ReservationSlotStatus.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservationSlotStatus + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ReservationSlotStatus + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservationSlotStatus.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ReservationSlotStatus"; + }; + + return ReservationSlotStatus; + })(); + + v1beta.ReservationSlotsGetResponse = (function() { + + /** + * Properties of a ReservationSlotsGetResponse. + * @memberof google.cloud.compute.v1beta + * @interface IReservationSlotsGetResponse + * @property {google.cloud.compute.v1beta.IReservationSlot|null} [resource] ReservationSlotsGetResponse resource + */ + + /** + * Constructs a new ReservationSlotsGetResponse. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ReservationSlotsGetResponse. + * @implements IReservationSlotsGetResponse + * @constructor + * @param {google.cloud.compute.v1beta.IReservationSlotsGetResponse=} [properties] Properties to set + */ + function ReservationSlotsGetResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservationSlotsGetResponse resource. + * @member {google.cloud.compute.v1beta.IReservationSlot|null|undefined} resource + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @instance + */ + ReservationSlotsGetResponse.prototype.resource = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotsGetResponse.prototype, "_resource", { + get: $util.oneOfGetter($oneOfFields = ["resource"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReservationSlotsGetResponse instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotsGetResponse=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ReservationSlotsGetResponse} ReservationSlotsGetResponse instance + */ + ReservationSlotsGetResponse.create = function create(properties) { + return new ReservationSlotsGetResponse(properties); + }; + + /** + * Encodes the specified ReservationSlotsGetResponse message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotsGetResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotsGetResponse} message ReservationSlotsGetResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSlotsGetResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + $root.google.cloud.compute.v1beta.ReservationSlot.encode(message.resource, writer.uint32(/* id 195806222, wireType 2 =*/1566449778).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ReservationSlotsGetResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotsGetResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotsGetResponse} message ReservationSlotsGetResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSlotsGetResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReservationSlotsGetResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ReservationSlotsGetResponse} ReservationSlotsGetResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSlotsGetResponse.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.cloud.compute.v1beta.ReservationSlotsGetResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 195806222: { + message.resource = $root.google.cloud.compute.v1beta.ReservationSlot.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReservationSlotsGetResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ReservationSlotsGetResponse} ReservationSlotsGetResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSlotsGetResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReservationSlotsGetResponse message. + * @function verify + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReservationSlotsGetResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.resource != null && message.hasOwnProperty("resource")) { + properties._resource = 1; + { + var error = $root.google.cloud.compute.v1beta.ReservationSlot.verify(message.resource); + if (error) + return "resource." + error; + } + } + return null; + }; + + /** + * Creates a ReservationSlotsGetResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ReservationSlotsGetResponse} ReservationSlotsGetResponse + */ + ReservationSlotsGetResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ReservationSlotsGetResponse) + return object; + var message = new $root.google.cloud.compute.v1beta.ReservationSlotsGetResponse(); + if (object.resource != null) { + if (typeof object.resource !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSlotsGetResponse.resource: object expected"); + message.resource = $root.google.cloud.compute.v1beta.ReservationSlot.fromObject(object.resource); + } + return message; + }; + + /** + * Creates a plain object from a ReservationSlotsGetResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {google.cloud.compute.v1beta.ReservationSlotsGetResponse} message ReservationSlotsGetResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservationSlotsGetResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.resource != null && message.hasOwnProperty("resource")) { + object.resource = $root.google.cloud.compute.v1beta.ReservationSlot.toObject(message.resource, options); + if (options.oneofs) + object._resource = "resource"; + } + return object; + }; + + /** + * Converts this ReservationSlotsGetResponse to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @instance + * @returns {Object.} JSON object + */ + ReservationSlotsGetResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservationSlotsGetResponse + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ReservationSlotsGetResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservationSlotsGetResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ReservationSlotsGetResponse"; + }; + + return ReservationSlotsGetResponse; + })(); + + v1beta.ReservationSlotsListResponse = (function() { + + /** + * Properties of a ReservationSlotsListResponse. + * @memberof google.cloud.compute.v1beta + * @interface IReservationSlotsListResponse + * @property {string|null} [id] ReservationSlotsListResponse id + * @property {Array.|null} [items] ReservationSlotsListResponse items + * @property {string|null} [kind] ReservationSlotsListResponse kind + * @property {string|null} [nextPageToken] ReservationSlotsListResponse nextPageToken + * @property {string|null} [selfLink] ReservationSlotsListResponse selfLink + * @property {google.cloud.compute.v1beta.IWarning|null} [warning] ReservationSlotsListResponse warning + */ + + /** + * Constructs a new ReservationSlotsListResponse. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ReservationSlotsListResponse. + * @implements IReservationSlotsListResponse + * @constructor + * @param {google.cloud.compute.v1beta.IReservationSlotsListResponse=} [properties] Properties to set + */ + function ReservationSlotsListResponse(properties) { + this.items = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservationSlotsListResponse id. + * @member {string|null|undefined} id + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @instance + */ + ReservationSlotsListResponse.prototype.id = null; + + /** + * ReservationSlotsListResponse items. + * @member {Array.} items + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @instance + */ + ReservationSlotsListResponse.prototype.items = $util.emptyArray; + + /** + * ReservationSlotsListResponse kind. + * @member {string|null|undefined} kind + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @instance + */ + ReservationSlotsListResponse.prototype.kind = null; + + /** + * ReservationSlotsListResponse nextPageToken. + * @member {string|null|undefined} nextPageToken + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @instance + */ + ReservationSlotsListResponse.prototype.nextPageToken = null; + + /** + * ReservationSlotsListResponse selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @instance + */ + ReservationSlotsListResponse.prototype.selfLink = null; + + /** + * ReservationSlotsListResponse warning. + * @member {google.cloud.compute.v1beta.IWarning|null|undefined} warning + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @instance + */ + ReservationSlotsListResponse.prototype.warning = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotsListResponse.prototype, "_id", { + get: $util.oneOfGetter($oneOfFields = ["id"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotsListResponse.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotsListResponse.prototype, "_nextPageToken", { + get: $util.oneOfGetter($oneOfFields = ["nextPageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotsListResponse.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSlotsListResponse.prototype, "_warning", { + get: $util.oneOfGetter($oneOfFields = ["warning"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReservationSlotsListResponse instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotsListResponse=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ReservationSlotsListResponse} ReservationSlotsListResponse instance + */ + ReservationSlotsListResponse.create = function create(properties) { + return new ReservationSlotsListResponse(properties); + }; + + /** + * Encodes the specified ReservationSlotsListResponse message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotsListResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotsListResponse} message ReservationSlotsListResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSlotsListResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 3355, wireType 2 =*/26842).string(message.id); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); + if (message.warning != null && Object.hasOwnProperty.call(message, "warning")) + $root.google.cloud.compute.v1beta.Warning.encode(message.warning, writer.uint32(/* id 50704284, wireType 2 =*/405634274).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 79797525, wireType 2 =*/638380202).string(message.nextPageToken); + if (message.items != null && message.items.length) + for (var i = 0; i < message.items.length; ++i) + $root.google.cloud.compute.v1beta.ReservationSlot.encode(message.items[i], writer.uint32(/* id 100526016, wireType 2 =*/804208130).fork()).ldelim(); + if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) + writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + return writer; + }; + + /** + * Encodes the specified ReservationSlotsListResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSlotsListResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {google.cloud.compute.v1beta.IReservationSlotsListResponse} message ReservationSlotsListResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSlotsListResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReservationSlotsListResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ReservationSlotsListResponse} ReservationSlotsListResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSlotsListResponse.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.cloud.compute.v1beta.ReservationSlotsListResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3355: { + message.id = reader.string(); + break; + } + case 100526016: { + if (!(message.items && message.items.length)) + message.items = []; + message.items.push($root.google.cloud.compute.v1beta.ReservationSlot.decode(reader, reader.uint32())); + break; + } + case 3292052: { + message.kind = reader.string(); + break; + } + case 79797525: { + message.nextPageToken = reader.string(); + break; + } + case 456214797: { + message.selfLink = reader.string(); + break; + } + case 50704284: { + message.warning = $root.google.cloud.compute.v1beta.Warning.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReservationSlotsListResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ReservationSlotsListResponse} ReservationSlotsListResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSlotsListResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReservationSlotsListResponse message. + * @function verify + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReservationSlotsListResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.id != null && message.hasOwnProperty("id")) { + properties._id = 1; + if (!$util.isString(message.id)) + return "id: string expected"; + } + if (message.items != null && message.hasOwnProperty("items")) { + if (!Array.isArray(message.items)) + return "items: array expected"; + for (var i = 0; i < message.items.length; ++i) { + var error = $root.google.cloud.compute.v1beta.ReservationSlot.verify(message.items[i]); + if (error) + return "items." + error; + } + } + if (message.kind != null && message.hasOwnProperty("kind")) { + properties._kind = 1; + if (!$util.isString(message.kind)) + return "kind: string expected"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + properties._nextPageToken = 1; + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + properties._selfLink = 1; + if (!$util.isString(message.selfLink)) + return "selfLink: string expected"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + properties._warning = 1; + { + var error = $root.google.cloud.compute.v1beta.Warning.verify(message.warning); + if (error) + return "warning." + error; + } + } + return null; + }; + + /** + * Creates a ReservationSlotsListResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ReservationSlotsListResponse} ReservationSlotsListResponse + */ + ReservationSlotsListResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ReservationSlotsListResponse) + return object; + var message = new $root.google.cloud.compute.v1beta.ReservationSlotsListResponse(); + if (object.id != null) + message.id = String(object.id); + if (object.items) { + if (!Array.isArray(object.items)) + throw TypeError(".google.cloud.compute.v1beta.ReservationSlotsListResponse.items: array expected"); + message.items = []; + for (var i = 0; i < object.items.length; ++i) { + if (typeof object.items[i] !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSlotsListResponse.items: object expected"); + message.items[i] = $root.google.cloud.compute.v1beta.ReservationSlot.fromObject(object.items[i]); + } + } + if (object.kind != null) + message.kind = String(object.kind); + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.selfLink != null) + message.selfLink = String(object.selfLink); + if (object.warning != null) { + if (typeof object.warning !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSlotsListResponse.warning: object expected"); + message.warning = $root.google.cloud.compute.v1beta.Warning.fromObject(object.warning); + } + return message; + }; + + /** + * Creates a plain object from a ReservationSlotsListResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {google.cloud.compute.v1beta.ReservationSlotsListResponse} message ReservationSlotsListResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservationSlotsListResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.items = []; + if (message.id != null && message.hasOwnProperty("id")) { + object.id = message.id; + if (options.oneofs) + object._id = "id"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + object.kind = message.kind; + if (options.oneofs) + object._kind = "kind"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + object.warning = $root.google.cloud.compute.v1beta.Warning.toObject(message.warning, options); + if (options.oneofs) + object._warning = "warning"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + object.nextPageToken = message.nextPageToken; + if (options.oneofs) + object._nextPageToken = "nextPageToken"; + } + if (message.items && message.items.length) { + object.items = []; + for (var j = 0; j < message.items.length; ++j) + object.items[j] = $root.google.cloud.compute.v1beta.ReservationSlot.toObject(message.items[j], options); + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + object.selfLink = message.selfLink; + if (options.oneofs) + object._selfLink = "selfLink"; + } + return object; + }; + + /** + * Converts this ReservationSlotsListResponse to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @instance + * @returns {Object.} JSON object + */ + ReservationSlotsListResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReservationSlotsListResponse + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.ReservationSlotsListResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReservationSlotsListResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.ReservationSlotsListResponse"; + }; + + return ReservationSlotsListResponse; + })(); + + v1beta.ReservationSubBlock = (function() { + + /** + * Properties of a ReservationSubBlock. + * @memberof google.cloud.compute.v1beta + * @interface IReservationSubBlock + * @property {google.cloud.compute.v1beta.IAcceleratorTopologiesInfo|null} [acceleratorTopologiesInfo] ReservationSubBlock acceleratorTopologiesInfo + * @property {number|null} [count] ReservationSubBlock count + * @property {string|null} [creationTimestamp] ReservationSubBlock creationTimestamp + * @property {google.cloud.compute.v1beta.IReservationSubBlockHealthInfo|null} [healthInfo] ReservationSubBlock healthInfo + * @property {number|Long|null} [id] ReservationSubBlock id + * @property {number|null} [inUseCount] ReservationSubBlock inUseCount + * @property {number|null} [inUseHostCount] ReservationSubBlock inUseHostCount + * @property {string|null} [kind] ReservationSubBlock kind + * @property {string|null} [name] ReservationSubBlock name + * @property {google.cloud.compute.v1beta.IReservationSubBlockPhysicalTopology|null} [physicalTopology] ReservationSubBlock physicalTopology + * @property {google.cloud.compute.v1beta.IGroupMaintenanceInfo|null} [reservationSubBlockMaintenance] ReservationSubBlock reservationSubBlockMaintenance + * @property {string|null} [selfLink] ReservationSubBlock selfLink + * @property {string|null} [selfLinkWithId] ReservationSubBlock selfLinkWithId + * @property {string|null} [status] ReservationSubBlock status + * @property {string|null} [zone] ReservationSubBlock zone + */ + + /** + * Constructs a new ReservationSubBlock. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ReservationSubBlock. + * @implements IReservationSubBlock + * @constructor + * @param {google.cloud.compute.v1beta.IReservationSubBlock=} [properties] Properties to set + */ + function ReservationSubBlock(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReservationSubBlock acceleratorTopologiesInfo. + * @member {google.cloud.compute.v1beta.IAcceleratorTopologiesInfo|null|undefined} acceleratorTopologiesInfo + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.acceleratorTopologiesInfo = null; + + /** + * ReservationSubBlock count. + * @member {number|null|undefined} count + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.count = null; + + /** + * ReservationSubBlock creationTimestamp. + * @member {string|null|undefined} creationTimestamp + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.creationTimestamp = null; + + /** + * ReservationSubBlock healthInfo. + * @member {google.cloud.compute.v1beta.IReservationSubBlockHealthInfo|null|undefined} healthInfo + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.healthInfo = null; + + /** + * ReservationSubBlock id. + * @member {number|Long|null|undefined} id + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.id = null; + + /** + * ReservationSubBlock inUseCount. + * @member {number|null|undefined} inUseCount + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.inUseCount = null; + + /** + * ReservationSubBlock inUseHostCount. + * @member {number|null|undefined} inUseHostCount + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.inUseHostCount = null; + + /** + * ReservationSubBlock kind. + * @member {string|null|undefined} kind + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.kind = null; + + /** + * ReservationSubBlock name. + * @member {string|null|undefined} name + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.name = null; + + /** + * ReservationSubBlock physicalTopology. + * @member {google.cloud.compute.v1beta.IReservationSubBlockPhysicalTopology|null|undefined} physicalTopology + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.physicalTopology = null; + + /** + * ReservationSubBlock reservationSubBlockMaintenance. + * @member {google.cloud.compute.v1beta.IGroupMaintenanceInfo|null|undefined} reservationSubBlockMaintenance + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.reservationSubBlockMaintenance = null; + + /** + * ReservationSubBlock selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.selfLink = null; + + /** + * ReservationSubBlock selfLinkWithId. + * @member {string|null|undefined} selfLinkWithId + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.selfLinkWithId = null; + + /** + * ReservationSubBlock status. + * @member {string|null|undefined} status + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.status = null; + + /** + * ReservationSubBlock zone. + * @member {string|null|undefined} zone + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @instance + */ + ReservationSubBlock.prototype.zone = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_acceleratorTopologiesInfo", { + get: $util.oneOfGetter($oneOfFields = ["acceleratorTopologiesInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_count", { + get: $util.oneOfGetter($oneOfFields = ["count"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_creationTimestamp", { + get: $util.oneOfGetter($oneOfFields = ["creationTimestamp"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_healthInfo", { + get: $util.oneOfGetter($oneOfFields = ["healthInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_id", { + get: $util.oneOfGetter($oneOfFields = ["id"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_inUseCount", { + get: $util.oneOfGetter($oneOfFields = ["inUseCount"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_inUseHostCount", { + get: $util.oneOfGetter($oneOfFields = ["inUseHostCount"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_name", { + get: $util.oneOfGetter($oneOfFields = ["name"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_physicalTopology", { + get: $util.oneOfGetter($oneOfFields = ["physicalTopology"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_reservationSubBlockMaintenance", { + get: $util.oneOfGetter($oneOfFields = ["reservationSubBlockMaintenance"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_selfLinkWithId", { + get: $util.oneOfGetter($oneOfFields = ["selfLinkWithId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_status", { + get: $util.oneOfGetter($oneOfFields = ["status"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ReservationSubBlock.prototype, "_zone", { + get: $util.oneOfGetter($oneOfFields = ["zone"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReservationSubBlock instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @static + * @param {google.cloud.compute.v1beta.IReservationSubBlock=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.ReservationSubBlock} ReservationSubBlock instance + */ + ReservationSubBlock.create = function create(properties) { + return new ReservationSubBlock(properties); + }; + + /** + * Encodes the specified ReservationSubBlock message. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSubBlock.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @static + * @param {google.cloud.compute.v1beta.IReservationSubBlock} message ReservationSubBlock message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSubBlock.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 3355, wireType 0 =*/26840).uint64(message.id); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 3373707, wireType 2 =*/26989658).string(message.name); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.creationTimestamp != null && Object.hasOwnProperty.call(message, "creationTimestamp")) + writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); + if (message.selfLinkWithId != null && Object.hasOwnProperty.call(message, "selfLinkWithId")) + writer.uint32(/* id 44520962, wireType 2 =*/356167698).string(message.selfLinkWithId); + if (message.acceleratorTopologiesInfo != null && Object.hasOwnProperty.call(message, "acceleratorTopologiesInfo")) + $root.google.cloud.compute.v1beta.AcceleratorTopologiesInfo.encode(message.acceleratorTopologiesInfo, writer.uint32(/* id 84833420, wireType 2 =*/678667362).fork()).ldelim(); + if (message.count != null && Object.hasOwnProperty.call(message, "count")) + writer.uint32(/* id 94851343, wireType 0 =*/758810744).int32(message.count); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + writer.uint32(/* id 181260274, wireType 2 =*/1450082194).string(message.status); + if (message.healthInfo != null && Object.hasOwnProperty.call(message, "healthInfo")) + $root.google.cloud.compute.v1beta.ReservationSubBlockHealthInfo.encode(message.healthInfo, writer.uint32(/* id 235287729, wireType 2 =*/1882301834).fork()).ldelim(); + if (message.physicalTopology != null && Object.hasOwnProperty.call(message, "physicalTopology")) + $root.google.cloud.compute.v1beta.ReservationSubBlockPhysicalTopology.encode(message.physicalTopology, writer.uint32(/* id 279778519, wireType 2 =*/2238228154).fork()).ldelim(); + if (message.inUseHostCount != null && Object.hasOwnProperty.call(message, "inUseHostCount")) + writer.uint32(/* id 364069834, wireType 0 =*/2912558672).int32(message.inUseHostCount); + if (message.reservationSubBlockMaintenance != null && Object.hasOwnProperty.call(message, "reservationSubBlockMaintenance")) + $root.google.cloud.compute.v1beta.GroupMaintenanceInfo.encode(message.reservationSubBlockMaintenance, writer.uint32(/* id 377005551, wireType 2 =*/3016044410).fork()).ldelim(); + if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) + writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + if (message.inUseCount != null && Object.hasOwnProperty.call(message, "inUseCount")) + writer.uint32(/* id 493458877, wireType 0 =*/3947671016).int32(message.inUseCount); + return writer; + }; + + /** + * Encodes the specified ReservationSubBlock message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.ReservationSubBlock.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @static + * @param {google.cloud.compute.v1beta.IReservationSubBlock} message ReservationSubBlock message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReservationSubBlock.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReservationSubBlock message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.ReservationSubBlock} ReservationSubBlock + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSubBlock.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.cloud.compute.v1beta.ReservationSubBlock(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 84833420: { + message.acceleratorTopologiesInfo = $root.google.cloud.compute.v1beta.AcceleratorTopologiesInfo.decode(reader, reader.uint32()); + break; + } + case 94851343: { + message.count = reader.int32(); + break; + } + case 30525366: { + message.creationTimestamp = reader.string(); + break; + } + case 235287729: { + message.healthInfo = $root.google.cloud.compute.v1beta.ReservationSubBlockHealthInfo.decode(reader, reader.uint32()); + break; + } + case 3355: { + message.id = reader.uint64(); + break; + } + case 493458877: { + message.inUseCount = reader.int32(); + break; + } + case 364069834: { + message.inUseHostCount = reader.int32(); + break; + } + case 3292052: { + message.kind = reader.string(); + break; + } + case 3373707: { + message.name = reader.string(); + break; + } + case 279778519: { + message.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSubBlockPhysicalTopology.decode(reader, reader.uint32()); + break; + } + case 377005551: { + message.reservationSubBlockMaintenance = $root.google.cloud.compute.v1beta.GroupMaintenanceInfo.decode(reader, reader.uint32()); + break; + } + case 456214797: { + message.selfLink = reader.string(); + break; + } + case 44520962: { + message.selfLinkWithId = reader.string(); + break; + } + case 181260274: { + message.status = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a ReservationSubBlock message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.ReservationSubBlock} ReservationSubBlock + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReservationSubBlock.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReservationSubBlock message. + * @function verify + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReservationSubBlock.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.acceleratorTopologiesInfo != null && message.hasOwnProperty("acceleratorTopologiesInfo")) { + properties._acceleratorTopologiesInfo = 1; + { + var error = $root.google.cloud.compute.v1beta.AcceleratorTopologiesInfo.verify(message.acceleratorTopologiesInfo); + if (error) + return "acceleratorTopologiesInfo." + error; + } + } + if (message.count != null && message.hasOwnProperty("count")) { + properties._count = 1; + if (!$util.isInteger(message.count)) + return "count: integer expected"; + } + if (message.creationTimestamp != null && message.hasOwnProperty("creationTimestamp")) { + properties._creationTimestamp = 1; + if (!$util.isString(message.creationTimestamp)) + return "creationTimestamp: string expected"; + } + if (message.healthInfo != null && message.hasOwnProperty("healthInfo")) { + properties._healthInfo = 1; + { + var error = $root.google.cloud.compute.v1beta.ReservationSubBlockHealthInfo.verify(message.healthInfo); + if (error) + return "healthInfo." + error; + } + } + if (message.id != null && message.hasOwnProperty("id")) { + properties._id = 1; + if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) + return "id: integer|Long expected"; + } + if (message.inUseCount != null && message.hasOwnProperty("inUseCount")) { + properties._inUseCount = 1; + if (!$util.isInteger(message.inUseCount)) + return "inUseCount: integer expected"; + } + if (message.inUseHostCount != null && message.hasOwnProperty("inUseHostCount")) { + properties._inUseHostCount = 1; + if (!$util.isInteger(message.inUseHostCount)) + return "inUseHostCount: integer expected"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + properties._kind = 1; + if (!$util.isString(message.kind)) + return "kind: string expected"; + } + if (message.name != null && message.hasOwnProperty("name")) { + properties._name = 1; + if (!$util.isString(message.name)) + return "name: string expected"; + } + if (message.physicalTopology != null && message.hasOwnProperty("physicalTopology")) { + properties._physicalTopology = 1; + { + var error = $root.google.cloud.compute.v1beta.ReservationSubBlockPhysicalTopology.verify(message.physicalTopology); + if (error) + return "physicalTopology." + error; + } + } + if (message.reservationSubBlockMaintenance != null && message.hasOwnProperty("reservationSubBlockMaintenance")) { + properties._reservationSubBlockMaintenance = 1; + { + var error = $root.google.cloud.compute.v1beta.GroupMaintenanceInfo.verify(message.reservationSubBlockMaintenance); + if (error) + return "reservationSubBlockMaintenance." + error; + } + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + properties._selfLink = 1; + if (!$util.isString(message.selfLink)) + return "selfLink: string expected"; + } + if (message.selfLinkWithId != null && message.hasOwnProperty("selfLinkWithId")) { + properties._selfLinkWithId = 1; + if (!$util.isString(message.selfLinkWithId)) + return "selfLinkWithId: string expected"; + } + if (message.status != null && message.hasOwnProperty("status")) { + properties._status = 1; + if (!$util.isString(message.status)) + return "status: string expected"; + } + if (message.zone != null && message.hasOwnProperty("zone")) { + properties._zone = 1; + if (!$util.isString(message.zone)) + return "zone: string expected"; + } + return null; + }; + + /** + * Creates a ReservationSubBlock message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.ReservationSubBlock} ReservationSubBlock + */ + ReservationSubBlock.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.ReservationSubBlock) + return object; + var message = new $root.google.cloud.compute.v1beta.ReservationSubBlock(); + if (object.acceleratorTopologiesInfo != null) { + if (typeof object.acceleratorTopologiesInfo !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSubBlock.acceleratorTopologiesInfo: object expected"); + message.acceleratorTopologiesInfo = $root.google.cloud.compute.v1beta.AcceleratorTopologiesInfo.fromObject(object.acceleratorTopologiesInfo); + } + if (object.count != null) + message.count = object.count | 0; + if (object.creationTimestamp != null) + message.creationTimestamp = String(object.creationTimestamp); + if (object.healthInfo != null) { + if (typeof object.healthInfo !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSubBlock.healthInfo: object expected"); + message.healthInfo = $root.google.cloud.compute.v1beta.ReservationSubBlockHealthInfo.fromObject(object.healthInfo); + } + if (object.id != null) + if ($util.Long) + (message.id = $util.Long.fromValue(object.id)).unsigned = true; + else if (typeof object.id === "string") + message.id = parseInt(object.id, 10); + else if (typeof object.id === "number") + message.id = object.id; + else if (typeof object.id === "object") + message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(true); + if (object.inUseCount != null) + message.inUseCount = object.inUseCount | 0; + if (object.inUseHostCount != null) + message.inUseHostCount = object.inUseHostCount | 0; + if (object.kind != null) + message.kind = String(object.kind); + if (object.name != null) + message.name = String(object.name); + if (object.physicalTopology != null) { + if (typeof object.physicalTopology !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSubBlock.physicalTopology: object expected"); + message.physicalTopology = $root.google.cloud.compute.v1beta.ReservationSubBlockPhysicalTopology.fromObject(object.physicalTopology); + } + if (object.reservationSubBlockMaintenance != null) { + if (typeof object.reservationSubBlockMaintenance !== "object") + throw TypeError(".google.cloud.compute.v1beta.ReservationSubBlock.reservationSubBlockMaintenance: object expected"); + message.reservationSubBlockMaintenance = $root.google.cloud.compute.v1beta.GroupMaintenanceInfo.fromObject(object.reservationSubBlockMaintenance); + } + if (object.selfLink != null) + message.selfLink = String(object.selfLink); + if (object.selfLinkWithId != null) + message.selfLinkWithId = String(object.selfLinkWithId); + if (object.status != null) + message.status = String(object.status); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a ReservationSubBlock message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.ReservationSubBlock + * @static + * @param {google.cloud.compute.v1beta.ReservationSubBlock} message ReservationSubBlock + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReservationSubBlock.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1163786,6 +1180120,7 @@ * @property {boolean|null} [enableOsInventoryMetadataValue] ResourceStatusEffectiveInstanceMetadata enableOsInventoryMetadataValue * @property {boolean|null} [enableOsconfigMetadataValue] ResourceStatusEffectiveInstanceMetadata enableOsconfigMetadataValue * @property {boolean|null} [enableOsloginMetadataValue] ResourceStatusEffectiveInstanceMetadata enableOsloginMetadataValue + * @property {boolean|null} [gceContainerDeclarationMetadataValue] ResourceStatusEffectiveInstanceMetadata gceContainerDeclarationMetadataValue * @property {boolean|null} [serialPortEnableMetadataValue] ResourceStatusEffectiveInstanceMetadata serialPortEnableMetadataValue * @property {boolean|null} [serialPortLoggingEnableMetadataValue] ResourceStatusEffectiveInstanceMetadata serialPortLoggingEnableMetadataValue * @property {string|null} [vmDnsSettingMetadataValue] ResourceStatusEffectiveInstanceMetadata vmDnsSettingMetadataValue @@ -1163846,6 +1180181,14 @@ */ ResourceStatusEffectiveInstanceMetadata.prototype.enableOsloginMetadataValue = null; + /** + * ResourceStatusEffectiveInstanceMetadata gceContainerDeclarationMetadataValue. + * @member {boolean|null|undefined} gceContainerDeclarationMetadataValue + * @memberof google.cloud.compute.v1beta.ResourceStatusEffectiveInstanceMetadata + * @instance + */ + ResourceStatusEffectiveInstanceMetadata.prototype.gceContainerDeclarationMetadataValue = null; + /** * ResourceStatusEffectiveInstanceMetadata serialPortEnableMetadataValue. * @member {boolean|null|undefined} serialPortEnableMetadataValue @@ -1163903,6 +1180246,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(ResourceStatusEffectiveInstanceMetadata.prototype, "_gceContainerDeclarationMetadataValue", { + get: $util.oneOfGetter($oneOfFields = ["gceContainerDeclarationMetadataValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(ResourceStatusEffectiveInstanceMetadata.prototype, "_serialPortEnableMetadataValue", { get: $util.oneOfGetter($oneOfFields = ["serialPortEnableMetadataValue"]), @@ -1163947,6 +1180296,8 @@ writer = $Writer.create(); if (message.enableOsloginMetadataValue != null && Object.hasOwnProperty.call(message, "enableOsloginMetadataValue")) writer.uint32(/* id 216603159, wireType 0 =*/1732825272).bool(message.enableOsloginMetadataValue); + if (message.gceContainerDeclarationMetadataValue != null && Object.hasOwnProperty.call(message, "gceContainerDeclarationMetadataValue")) + writer.uint32(/* id 219617210, wireType 0 =*/1756937680).bool(message.gceContainerDeclarationMetadataValue); if (message.serialPortLoggingEnableMetadataValue != null && Object.hasOwnProperty.call(message, "serialPortLoggingEnableMetadataValue")) writer.uint32(/* id 311813290, wireType 0 =*/2494506320).bool(message.serialPortLoggingEnableMetadataValue); if (message.blockProjectSshKeysMetadataValue != null && Object.hasOwnProperty.call(message, "blockProjectSshKeysMetadataValue")) @@ -1164017,6 +1180368,10 @@ message.enableOsloginMetadataValue = reader.bool(); break; } + case 219617210: { + message.gceContainerDeclarationMetadataValue = reader.bool(); + break; + } case 430536330: { message.serialPortEnableMetadataValue = reader.bool(); break; @@ -1164090,6 +1180445,11 @@ if (typeof message.enableOsloginMetadataValue !== "boolean") return "enableOsloginMetadataValue: boolean expected"; } + if (message.gceContainerDeclarationMetadataValue != null && message.hasOwnProperty("gceContainerDeclarationMetadataValue")) { + properties._gceContainerDeclarationMetadataValue = 1; + if (typeof message.gceContainerDeclarationMetadataValue !== "boolean") + return "gceContainerDeclarationMetadataValue: boolean expected"; + } if (message.serialPortEnableMetadataValue != null && message.hasOwnProperty("serialPortEnableMetadataValue")) { properties._serialPortEnableMetadataValue = 1; if (typeof message.serialPortEnableMetadataValue !== "boolean") @@ -1164130,6 +1180490,8 @@ message.enableOsconfigMetadataValue = Boolean(object.enableOsconfigMetadataValue); if (object.enableOsloginMetadataValue != null) message.enableOsloginMetadataValue = Boolean(object.enableOsloginMetadataValue); + if (object.gceContainerDeclarationMetadataValue != null) + message.gceContainerDeclarationMetadataValue = Boolean(object.gceContainerDeclarationMetadataValue); if (object.serialPortEnableMetadataValue != null) message.serialPortEnableMetadataValue = Boolean(object.serialPortEnableMetadataValue); if (object.serialPortLoggingEnableMetadataValue != null) @@ -1164157,6 +1180519,11 @@ if (options.oneofs) object._enableOsloginMetadataValue = "enableOsloginMetadataValue"; } + if (message.gceContainerDeclarationMetadataValue != null && message.hasOwnProperty("gceContainerDeclarationMetadataValue")) { + object.gceContainerDeclarationMetadataValue = message.gceContainerDeclarationMetadataValue; + if (options.oneofs) + object._gceContainerDeclarationMetadataValue = "gceContainerDeclarationMetadataValue"; + } if (message.serialPortLoggingEnableMetadataValue != null && message.hasOwnProperty("serialPortLoggingEnableMetadataValue")) { object.serialPortLoggingEnableMetadataValue = message.serialPortLoggingEnableMetadataValue; if (options.oneofs) @@ -1184978,6 +1201345,263 @@ return RouterStatusResponse; })(); + v1beta.RoutersGetNamedSetResponse = (function() { + + /** + * Properties of a RoutersGetNamedSetResponse. + * @memberof google.cloud.compute.v1beta + * @interface IRoutersGetNamedSetResponse + * @property {string|null} [etag] RoutersGetNamedSetResponse etag + * @property {google.cloud.compute.v1beta.INamedSet|null} [resource] RoutersGetNamedSetResponse resource + */ + + /** + * Constructs a new RoutersGetNamedSetResponse. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a RoutersGetNamedSetResponse. + * @implements IRoutersGetNamedSetResponse + * @constructor + * @param {google.cloud.compute.v1beta.IRoutersGetNamedSetResponse=} [properties] Properties to set + */ + function RoutersGetNamedSetResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutersGetNamedSetResponse etag. + * @member {string|null|undefined} etag + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @instance + */ + RoutersGetNamedSetResponse.prototype.etag = null; + + /** + * RoutersGetNamedSetResponse resource. + * @member {google.cloud.compute.v1beta.INamedSet|null|undefined} resource + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @instance + */ + RoutersGetNamedSetResponse.prototype.resource = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(RoutersGetNamedSetResponse.prototype, "_etag", { + get: $util.oneOfGetter($oneOfFields = ["etag"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(RoutersGetNamedSetResponse.prototype, "_resource", { + get: $util.oneOfGetter($oneOfFields = ["resource"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new RoutersGetNamedSetResponse instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {google.cloud.compute.v1beta.IRoutersGetNamedSetResponse=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.RoutersGetNamedSetResponse} RoutersGetNamedSetResponse instance + */ + RoutersGetNamedSetResponse.create = function create(properties) { + return new RoutersGetNamedSetResponse(properties); + }; + + /** + * Encodes the specified RoutersGetNamedSetResponse message. Does not implicitly {@link google.cloud.compute.v1beta.RoutersGetNamedSetResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {google.cloud.compute.v1beta.IRoutersGetNamedSetResponse} message RoutersGetNamedSetResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RoutersGetNamedSetResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 3123477, wireType 2 =*/24987818).string(message.etag); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + $root.google.cloud.compute.v1beta.NamedSet.encode(message.resource, writer.uint32(/* id 195806222, wireType 2 =*/1566449778).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified RoutersGetNamedSetResponse message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.RoutersGetNamedSetResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {google.cloud.compute.v1beta.IRoutersGetNamedSetResponse} message RoutersGetNamedSetResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RoutersGetNamedSetResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RoutersGetNamedSetResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.RoutersGetNamedSetResponse} RoutersGetNamedSetResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RoutersGetNamedSetResponse.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.cloud.compute.v1beta.RoutersGetNamedSetResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3123477: { + message.etag = reader.string(); + break; + } + case 195806222: { + message.resource = $root.google.cloud.compute.v1beta.NamedSet.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RoutersGetNamedSetResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.RoutersGetNamedSetResponse} RoutersGetNamedSetResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RoutersGetNamedSetResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RoutersGetNamedSetResponse message. + * @function verify + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RoutersGetNamedSetResponse.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.etag != null && message.hasOwnProperty("etag")) { + properties._etag = 1; + if (!$util.isString(message.etag)) + return "etag: string expected"; + } + if (message.resource != null && message.hasOwnProperty("resource")) { + properties._resource = 1; + { + var error = $root.google.cloud.compute.v1beta.NamedSet.verify(message.resource); + if (error) + return "resource." + error; + } + } + return null; + }; + + /** + * Creates a RoutersGetNamedSetResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.RoutersGetNamedSetResponse} RoutersGetNamedSetResponse + */ + RoutersGetNamedSetResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.RoutersGetNamedSetResponse) + return object; + var message = new $root.google.cloud.compute.v1beta.RoutersGetNamedSetResponse(); + if (object.etag != null) + message.etag = String(object.etag); + if (object.resource != null) { + if (typeof object.resource !== "object") + throw TypeError(".google.cloud.compute.v1beta.RoutersGetNamedSetResponse.resource: object expected"); + message.resource = $root.google.cloud.compute.v1beta.NamedSet.fromObject(object.resource); + } + return message; + }; + + /** + * Creates a plain object from a RoutersGetNamedSetResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {google.cloud.compute.v1beta.RoutersGetNamedSetResponse} message RoutersGetNamedSetResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutersGetNamedSetResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.etag != null && message.hasOwnProperty("etag")) { + object.etag = message.etag; + if (options.oneofs) + object._etag = "etag"; + } + if (message.resource != null && message.hasOwnProperty("resource")) { + object.resource = $root.google.cloud.compute.v1beta.NamedSet.toObject(message.resource, options); + if (options.oneofs) + object._resource = "resource"; + } + return object; + }; + + /** + * Converts this RoutersGetNamedSetResponse to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @instance + * @returns {Object.} JSON object + */ + RoutersGetNamedSetResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutersGetNamedSetResponse + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.RoutersGetNamedSetResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutersGetNamedSetResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.RoutersGetNamedSetResponse"; + }; + + return RoutersGetNamedSetResponse; + })(); + v1beta.RoutersGetRoutePolicyResponse = (function() { /** @@ -1185461,30 +1202085,504 @@ }; /** - * Decodes a RoutersListBgpRoutes message from the specified reader or buffer, length delimited. + * Decodes a RoutersListBgpRoutes message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.RoutersListBgpRoutes} RoutersListBgpRoutes + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RoutersListBgpRoutes.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a RoutersListBgpRoutes message. + * @function verify + * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + RoutersListBgpRoutes.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.etag != null && message.hasOwnProperty("etag")) { + properties._etag = 1; + if (!$util.isString(message.etag)) + return "etag: string expected"; + } + if (message.id != null && message.hasOwnProperty("id")) { + properties._id = 1; + if (!$util.isString(message.id)) + return "id: string expected"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + properties._kind = 1; + if (!$util.isString(message.kind)) + return "kind: string expected"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + properties._nextPageToken = 1; + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + } + if (message.result != null && message.hasOwnProperty("result")) { + if (!Array.isArray(message.result)) + return "result: array expected"; + for (var i = 0; i < message.result.length; ++i) { + var error = $root.google.cloud.compute.v1beta.BgpRoute.verify(message.result[i]); + if (error) + return "result." + error; + } + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + properties._selfLink = 1; + if (!$util.isString(message.selfLink)) + return "selfLink: string expected"; + } + if (message.unreachables != null && message.hasOwnProperty("unreachables")) { + if (!Array.isArray(message.unreachables)) + return "unreachables: array expected"; + for (var i = 0; i < message.unreachables.length; ++i) + if (!$util.isString(message.unreachables[i])) + return "unreachables: string[] expected"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + properties._warning = 1; + { + var error = $root.google.cloud.compute.v1beta.Warning.verify(message.warning); + if (error) + return "warning." + error; + } + } + return null; + }; + + /** + * Creates a RoutersListBgpRoutes message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.RoutersListBgpRoutes} RoutersListBgpRoutes + */ + RoutersListBgpRoutes.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.RoutersListBgpRoutes) + return object; + var message = new $root.google.cloud.compute.v1beta.RoutersListBgpRoutes(); + if (object.etag != null) + message.etag = String(object.etag); + if (object.id != null) + message.id = String(object.id); + if (object.kind != null) + message.kind = String(object.kind); + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.result) { + if (!Array.isArray(object.result)) + throw TypeError(".google.cloud.compute.v1beta.RoutersListBgpRoutes.result: array expected"); + message.result = []; + for (var i = 0; i < object.result.length; ++i) { + if (typeof object.result[i] !== "object") + throw TypeError(".google.cloud.compute.v1beta.RoutersListBgpRoutes.result: object expected"); + message.result[i] = $root.google.cloud.compute.v1beta.BgpRoute.fromObject(object.result[i]); + } + } + if (object.selfLink != null) + message.selfLink = String(object.selfLink); + if (object.unreachables) { + if (!Array.isArray(object.unreachables)) + throw TypeError(".google.cloud.compute.v1beta.RoutersListBgpRoutes.unreachables: array expected"); + message.unreachables = []; + for (var i = 0; i < object.unreachables.length; ++i) + message.unreachables[i] = String(object.unreachables[i]); + } + if (object.warning != null) { + if (typeof object.warning !== "object") + throw TypeError(".google.cloud.compute.v1beta.RoutersListBgpRoutes.warning: object expected"); + message.warning = $root.google.cloud.compute.v1beta.Warning.fromObject(object.warning); + } + return message; + }; + + /** + * Creates a plain object from a RoutersListBgpRoutes message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @static + * @param {google.cloud.compute.v1beta.RoutersListBgpRoutes} message RoutersListBgpRoutes + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutersListBgpRoutes.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.result = []; + object.unreachables = []; + } + if (message.id != null && message.hasOwnProperty("id")) { + object.id = message.id; + if (options.oneofs) + object._id = "id"; + } + if (message.etag != null && message.hasOwnProperty("etag")) { + object.etag = message.etag; + if (options.oneofs) + object._etag = "etag"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + object.kind = message.kind; + if (options.oneofs) + object._kind = "kind"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + object.warning = $root.google.cloud.compute.v1beta.Warning.toObject(message.warning, options); + if (options.oneofs) + object._warning = "warning"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + object.nextPageToken = message.nextPageToken; + if (options.oneofs) + object._nextPageToken = "nextPageToken"; + } + if (message.result && message.result.length) { + object.result = []; + for (var j = 0; j < message.result.length; ++j) + object.result[j] = $root.google.cloud.compute.v1beta.BgpRoute.toObject(message.result[j], options); + } + if (message.unreachables && message.unreachables.length) { + object.unreachables = []; + for (var j = 0; j < message.unreachables.length; ++j) + object.unreachables[j] = message.unreachables[j]; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + object.selfLink = message.selfLink; + if (options.oneofs) + object._selfLink = "selfLink"; + } + return object; + }; + + /** + * Converts this RoutersListBgpRoutes to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @instance + * @returns {Object.} JSON object + */ + RoutersListBgpRoutes.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutersListBgpRoutes + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutersListBgpRoutes.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.RoutersListBgpRoutes"; + }; + + return RoutersListBgpRoutes; + })(); + + v1beta.RoutersListNamedSets = (function() { + + /** + * Properties of a RoutersListNamedSets. + * @memberof google.cloud.compute.v1beta + * @interface IRoutersListNamedSets + * @property {string|null} [etag] RoutersListNamedSets etag + * @property {string|null} [id] RoutersListNamedSets id + * @property {string|null} [kind] RoutersListNamedSets kind + * @property {string|null} [nextPageToken] RoutersListNamedSets nextPageToken + * @property {Array.|null} [result] RoutersListNamedSets result + * @property {string|null} [selfLink] RoutersListNamedSets selfLink + * @property {Array.|null} [unreachables] RoutersListNamedSets unreachables + * @property {google.cloud.compute.v1beta.IWarning|null} [warning] RoutersListNamedSets warning + */ + + /** + * Constructs a new RoutersListNamedSets. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a RoutersListNamedSets. + * @implements IRoutersListNamedSets + * @constructor + * @param {google.cloud.compute.v1beta.IRoutersListNamedSets=} [properties] Properties to set + */ + function RoutersListNamedSets(properties) { + this.result = []; + this.unreachables = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutersListNamedSets etag. + * @member {string|null|undefined} etag + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @instance + */ + RoutersListNamedSets.prototype.etag = null; + + /** + * RoutersListNamedSets id. + * @member {string|null|undefined} id + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @instance + */ + RoutersListNamedSets.prototype.id = null; + + /** + * RoutersListNamedSets kind. + * @member {string|null|undefined} kind + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @instance + */ + RoutersListNamedSets.prototype.kind = null; + + /** + * RoutersListNamedSets nextPageToken. + * @member {string|null|undefined} nextPageToken + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @instance + */ + RoutersListNamedSets.prototype.nextPageToken = null; + + /** + * RoutersListNamedSets result. + * @member {Array.} result + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @instance + */ + RoutersListNamedSets.prototype.result = $util.emptyArray; + + /** + * RoutersListNamedSets selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @instance + */ + RoutersListNamedSets.prototype.selfLink = null; + + /** + * RoutersListNamedSets unreachables. + * @member {Array.} unreachables + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @instance + */ + RoutersListNamedSets.prototype.unreachables = $util.emptyArray; + + /** + * RoutersListNamedSets warning. + * @member {google.cloud.compute.v1beta.IWarning|null|undefined} warning + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @instance + */ + RoutersListNamedSets.prototype.warning = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(RoutersListNamedSets.prototype, "_etag", { + get: $util.oneOfGetter($oneOfFields = ["etag"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(RoutersListNamedSets.prototype, "_id", { + get: $util.oneOfGetter($oneOfFields = ["id"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(RoutersListNamedSets.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(RoutersListNamedSets.prototype, "_nextPageToken", { + get: $util.oneOfGetter($oneOfFields = ["nextPageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(RoutersListNamedSets.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(RoutersListNamedSets.prototype, "_warning", { + get: $util.oneOfGetter($oneOfFields = ["warning"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new RoutersListNamedSets instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @static + * @param {google.cloud.compute.v1beta.IRoutersListNamedSets=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.RoutersListNamedSets} RoutersListNamedSets instance + */ + RoutersListNamedSets.create = function create(properties) { + return new RoutersListNamedSets(properties); + }; + + /** + * Encodes the specified RoutersListNamedSets message. Does not implicitly {@link google.cloud.compute.v1beta.RoutersListNamedSets.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @static + * @param {google.cloud.compute.v1beta.IRoutersListNamedSets} message RoutersListNamedSets message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RoutersListNamedSets.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 3355, wireType 2 =*/26842).string(message.id); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 3123477, wireType 2 =*/24987818).string(message.etag); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); + if (message.warning != null && Object.hasOwnProperty.call(message, "warning")) + $root.google.cloud.compute.v1beta.Warning.encode(message.warning, writer.uint32(/* id 50704284, wireType 2 =*/405634274).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 79797525, wireType 2 =*/638380202).string(message.nextPageToken); + if (message.result != null && message.result.length) + for (var i = 0; i < message.result.length; ++i) + $root.google.cloud.compute.v1beta.NamedSet.encode(message.result[i], writer.uint32(/* id 139315229, wireType 2 =*/1114521834).fork()).ldelim(); + if (message.unreachables != null && message.unreachables.length) + for (var i = 0; i < message.unreachables.length; ++i) + writer.uint32(/* id 243372063, wireType 2 =*/1946976506).string(message.unreachables[i]); + if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) + writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + return writer; + }; + + /** + * Encodes the specified RoutersListNamedSets message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.RoutersListNamedSets.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @static + * @param {google.cloud.compute.v1beta.IRoutersListNamedSets} message RoutersListNamedSets message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + RoutersListNamedSets.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a RoutersListNamedSets message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.RoutersListNamedSets} RoutersListNamedSets + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + RoutersListNamedSets.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.cloud.compute.v1beta.RoutersListNamedSets(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3123477: { + message.etag = reader.string(); + break; + } + case 3355: { + message.id = reader.string(); + break; + } + case 3292052: { + message.kind = reader.string(); + break; + } + case 79797525: { + message.nextPageToken = reader.string(); + break; + } + case 139315229: { + if (!(message.result && message.result.length)) + message.result = []; + message.result.push($root.google.cloud.compute.v1beta.NamedSet.decode(reader, reader.uint32())); + break; + } + case 456214797: { + message.selfLink = reader.string(); + break; + } + case 243372063: { + if (!(message.unreachables && message.unreachables.length)) + message.unreachables = []; + message.unreachables.push(reader.string()); + break; + } + case 50704284: { + message.warning = $root.google.cloud.compute.v1beta.Warning.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a RoutersListNamedSets message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.RoutersListBgpRoutes} RoutersListBgpRoutes + * @returns {google.cloud.compute.v1beta.RoutersListNamedSets} RoutersListNamedSets * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - RoutersListBgpRoutes.decodeDelimited = function decodeDelimited(reader) { + RoutersListNamedSets.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a RoutersListBgpRoutes message. + * Verifies a RoutersListNamedSets message. * @function verify - * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - RoutersListBgpRoutes.verify = function verify(message) { + RoutersListNamedSets.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; @@ -1185512,7 +1202610,7 @@ if (!Array.isArray(message.result)) return "result: array expected"; for (var i = 0; i < message.result.length; ++i) { - var error = $root.google.cloud.compute.v1beta.BgpRoute.verify(message.result[i]); + var error = $root.google.cloud.compute.v1beta.NamedSet.verify(message.result[i]); if (error) return "result." + error; } @@ -1185541,17 +1202639,17 @@ }; /** - * Creates a RoutersListBgpRoutes message from a plain object. Also converts values to their respective internal types. + * Creates a RoutersListNamedSets message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.RoutersListBgpRoutes} RoutersListBgpRoutes + * @returns {google.cloud.compute.v1beta.RoutersListNamedSets} RoutersListNamedSets */ - RoutersListBgpRoutes.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.RoutersListBgpRoutes) + RoutersListNamedSets.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.RoutersListNamedSets) return object; - var message = new $root.google.cloud.compute.v1beta.RoutersListBgpRoutes(); + var message = new $root.google.cloud.compute.v1beta.RoutersListNamedSets(); if (object.etag != null) message.etag = String(object.etag); if (object.id != null) @@ -1185562,41 +1202660,41 @@ message.nextPageToken = String(object.nextPageToken); if (object.result) { if (!Array.isArray(object.result)) - throw TypeError(".google.cloud.compute.v1beta.RoutersListBgpRoutes.result: array expected"); + throw TypeError(".google.cloud.compute.v1beta.RoutersListNamedSets.result: array expected"); message.result = []; for (var i = 0; i < object.result.length; ++i) { if (typeof object.result[i] !== "object") - throw TypeError(".google.cloud.compute.v1beta.RoutersListBgpRoutes.result: object expected"); - message.result[i] = $root.google.cloud.compute.v1beta.BgpRoute.fromObject(object.result[i]); + throw TypeError(".google.cloud.compute.v1beta.RoutersListNamedSets.result: object expected"); + message.result[i] = $root.google.cloud.compute.v1beta.NamedSet.fromObject(object.result[i]); } } if (object.selfLink != null) message.selfLink = String(object.selfLink); if (object.unreachables) { if (!Array.isArray(object.unreachables)) - throw TypeError(".google.cloud.compute.v1beta.RoutersListBgpRoutes.unreachables: array expected"); + throw TypeError(".google.cloud.compute.v1beta.RoutersListNamedSets.unreachables: array expected"); message.unreachables = []; for (var i = 0; i < object.unreachables.length; ++i) message.unreachables[i] = String(object.unreachables[i]); } if (object.warning != null) { if (typeof object.warning !== "object") - throw TypeError(".google.cloud.compute.v1beta.RoutersListBgpRoutes.warning: object expected"); + throw TypeError(".google.cloud.compute.v1beta.RoutersListNamedSets.warning: object expected"); message.warning = $root.google.cloud.compute.v1beta.Warning.fromObject(object.warning); } return message; }; /** - * Creates a plain object from a RoutersListBgpRoutes message. Also converts values to other types if specified. + * Creates a plain object from a RoutersListNamedSets message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets * @static - * @param {google.cloud.compute.v1beta.RoutersListBgpRoutes} message RoutersListBgpRoutes + * @param {google.cloud.compute.v1beta.RoutersListNamedSets} message RoutersListNamedSets * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - RoutersListBgpRoutes.toObject = function toObject(message, options) { + RoutersListNamedSets.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1185632,7 +1202730,7 @@ if (message.result && message.result.length) { object.result = []; for (var j = 0; j < message.result.length; ++j) - object.result[j] = $root.google.cloud.compute.v1beta.BgpRoute.toObject(message.result[j], options); + object.result[j] = $root.google.cloud.compute.v1beta.NamedSet.toObject(message.result[j], options); } if (message.unreachables && message.unreachables.length) { object.unreachables = []; @@ -1185648,32 +1202746,32 @@ }; /** - * Converts this RoutersListBgpRoutes to JSON. + * Converts this RoutersListNamedSets to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets * @instance * @returns {Object.} JSON object */ - RoutersListBgpRoutes.prototype.toJSON = function toJSON() { + RoutersListNamedSets.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for RoutersListBgpRoutes + * Gets the default type url for RoutersListNamedSets * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.RoutersListBgpRoutes + * @memberof google.cloud.compute.v1beta.RoutersListNamedSets * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - RoutersListBgpRoutes.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + RoutersListNamedSets.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.RoutersListBgpRoutes"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.RoutersListNamedSets"; }; - return RoutersListBgpRoutes; + return RoutersListNamedSets; })(); v1beta.RoutersListRoutePolicies = (function() { @@ -1188601,6 +1205699,7 @@ * @property {string|null} [onHostMaintenance] Scheduling onHostMaintenance * @property {google.cloud.compute.v1beta.ISchedulingOnInstanceStopAction|null} [onInstanceStopAction] Scheduling onInstanceStopAction * @property {boolean|null} [preemptible] Scheduling preemptible + * @property {google.cloud.compute.v1beta.IDuration|null} [preemptionNoticeDuration] Scheduling preemptionNoticeDuration * @property {string|null} [provisioningModel] Scheduling provisioningModel * @property {boolean|null} [skipGuestOsShutdown] Scheduling skipGuestOsShutdown * @property {string|null} [terminationTime] Scheduling terminationTime @@ -1188742,6 +1205841,14 @@ */ Scheduling.prototype.preemptible = null; + /** + * Scheduling preemptionNoticeDuration. + * @member {google.cloud.compute.v1beta.IDuration|null|undefined} preemptionNoticeDuration + * @memberof google.cloud.compute.v1beta.Scheduling + * @instance + */ + Scheduling.prototype.preemptionNoticeDuration = null; + /** * Scheduling provisioningModel. * @member {string|null|undefined} provisioningModel @@ -1188853,6 +1205960,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(Scheduling.prototype, "_preemptionNoticeDuration", { + get: $util.oneOfGetter($oneOfFields = ["preemptionNoticeDuration"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(Scheduling.prototype, "_provisioningModel", { get: $util.oneOfGetter($oneOfFields = ["provisioningModel"]), @@ -1188930,6 +1206043,8 @@ if (message.nodeAffinities != null && message.nodeAffinities.length) for (var i = 0; i < message.nodeAffinities.length; ++i) $root.google.cloud.compute.v1beta.SchedulingNodeAffinity.encode(message.nodeAffinities[i], writer.uint32(/* id 461799971, wireType 2 =*/3694399770).fork()).ldelim(); + if (message.preemptionNoticeDuration != null && Object.hasOwnProperty.call(message, "preemptionNoticeDuration")) + $root.google.cloud.compute.v1beta.Duration.encode(message.preemptionNoticeDuration, writer.uint32(/* id 486176437, wireType 2 =*/3889411498).fork()).ldelim(); if (message.onInstanceStopAction != null && Object.hasOwnProperty.call(message, "onInstanceStopAction")) $root.google.cloud.compute.v1beta.SchedulingOnInstanceStopAction.encode(message.onInstanceStopAction, writer.uint32(/* id 529876681, wireType 2 =*/4239013450).fork()).ldelim(); return writer; @@ -1189030,6 +1206145,10 @@ message.preemptible = reader.bool(); break; } + case 486176437: { + message.preemptionNoticeDuration = $root.google.cloud.compute.v1beta.Duration.decode(reader, reader.uint32()); + break; + } case 494423: { message.provisioningModel = reader.string(); break; @@ -1189169,6 +1206288,14 @@ if (typeof message.preemptible !== "boolean") return "preemptible: boolean expected"; } + if (message.preemptionNoticeDuration != null && message.hasOwnProperty("preemptionNoticeDuration")) { + properties._preemptionNoticeDuration = 1; + { + var error = $root.google.cloud.compute.v1beta.Duration.verify(message.preemptionNoticeDuration); + if (error) + return "preemptionNoticeDuration." + error; + } + } if (message.provisioningModel != null && message.hasOwnProperty("provisioningModel")) { properties._provisioningModel = 1; if (!$util.isString(message.provisioningModel)) @@ -1189249,6 +1206376,11 @@ } if (object.preemptible != null) message.preemptible = Boolean(object.preemptible); + if (object.preemptionNoticeDuration != null) { + if (typeof object.preemptionNoticeDuration !== "object") + throw TypeError(".google.cloud.compute.v1beta.Scheduling.preemptionNoticeDuration: object expected"); + message.preemptionNoticeDuration = $root.google.cloud.compute.v1beta.Duration.fromObject(object.preemptionNoticeDuration); + } if (object.provisioningModel != null) message.provisioningModel = String(object.provisioningModel); if (object.skipGuestOsShutdown != null) @@ -1189358,6 +1206490,11 @@ for (var j = 0; j < message.nodeAffinities.length; ++j) object.nodeAffinities[j] = $root.google.cloud.compute.v1beta.SchedulingNodeAffinity.toObject(message.nodeAffinities[j], options); } + if (message.preemptionNoticeDuration != null && message.hasOwnProperty("preemptionNoticeDuration")) { + object.preemptionNoticeDuration = $root.google.cloud.compute.v1beta.Duration.toObject(message.preemptionNoticeDuration, options); + if (options.oneofs) + object._preemptionNoticeDuration = "preemptionNoticeDuration"; + } if (message.onInstanceStopAction != null && message.hasOwnProperty("onInstanceStopAction")) { object.onInstanceStopAction = $root.google.cloud.compute.v1beta.SchedulingOnInstanceStopAction.toObject(message.onInstanceStopAction, options); if (options.oneofs) @@ -1214238,6 +1231375,286 @@ return SetIamPolicyInstanceTemplateRequest; })(); + v1beta.SetIamPolicyInstantSnapshotGroupRequest = (function() { + + /** + * Properties of a SetIamPolicyInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface ISetIamPolicyInstantSnapshotGroupRequest + * @property {string|null} [project] SetIamPolicyInstantSnapshotGroupRequest project + * @property {string|null} [resource] SetIamPolicyInstantSnapshotGroupRequest resource + * @property {string|null} [zone] SetIamPolicyInstantSnapshotGroupRequest zone + * @property {google.cloud.compute.v1beta.IZoneSetPolicyRequest|null} [zoneSetPolicyRequestResource] SetIamPolicyInstantSnapshotGroupRequest zoneSetPolicyRequestResource + */ + + /** + * Constructs a new SetIamPolicyInstantSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a SetIamPolicyInstantSnapshotGroupRequest. + * @implements ISetIamPolicyInstantSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest=} [properties] Properties to set + */ + function SetIamPolicyInstantSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SetIamPolicyInstantSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @instance + */ + SetIamPolicyInstantSnapshotGroupRequest.prototype.project = ""; + + /** + * SetIamPolicyInstantSnapshotGroupRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @instance + */ + SetIamPolicyInstantSnapshotGroupRequest.prototype.resource = ""; + + /** + * SetIamPolicyInstantSnapshotGroupRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @instance + */ + SetIamPolicyInstantSnapshotGroupRequest.prototype.zone = ""; + + /** + * SetIamPolicyInstantSnapshotGroupRequest zoneSetPolicyRequestResource. + * @member {google.cloud.compute.v1beta.IZoneSetPolicyRequest|null|undefined} zoneSetPolicyRequestResource + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @instance + */ + SetIamPolicyInstantSnapshotGroupRequest.prototype.zoneSetPolicyRequestResource = null; + + /** + * Creates a new SetIamPolicyInstantSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest} SetIamPolicyInstantSnapshotGroupRequest instance + */ + SetIamPolicyInstantSnapshotGroupRequest.create = function create(properties) { + return new SetIamPolicyInstantSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified SetIamPolicyInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest} message SetIamPolicyInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SetIamPolicyInstantSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.zoneSetPolicyRequestResource != null && Object.hasOwnProperty.call(message, "zoneSetPolicyRequestResource")) + $root.google.cloud.compute.v1beta.ZoneSetPolicyRequest.encode(message.zoneSetPolicyRequestResource, writer.uint32(/* id 382082107, wireType 2 =*/3056656858).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SetIamPolicyInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest} message SetIamPolicyInstantSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SetIamPolicyInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SetIamPolicyInstantSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest} SetIamPolicyInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SetIamPolicyInstantSnapshotGroupRequest.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.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 227560217: { + message.project = reader.string(); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + case 382082107: { + message.zoneSetPolicyRequestResource = $root.google.cloud.compute.v1beta.ZoneSetPolicyRequest.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SetIamPolicyInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest} SetIamPolicyInstantSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SetIamPolicyInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SetIamPolicyInstantSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SetIamPolicyInstantSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + if (message.zoneSetPolicyRequestResource != null && message.hasOwnProperty("zoneSetPolicyRequestResource")) { + var error = $root.google.cloud.compute.v1beta.ZoneSetPolicyRequest.verify(message.zoneSetPolicyRequestResource); + if (error) + return "zoneSetPolicyRequestResource." + error; + } + return null; + }; + + /** + * Creates a SetIamPolicyInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest} SetIamPolicyInstantSnapshotGroupRequest + */ + SetIamPolicyInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest(); + if (object.project != null) + message.project = String(object.project); + if (object.resource != null) + message.resource = String(object.resource); + if (object.zone != null) + message.zone = String(object.zone); + if (object.zoneSetPolicyRequestResource != null) { + if (typeof object.zoneSetPolicyRequestResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest.zoneSetPolicyRequestResource: object expected"); + message.zoneSetPolicyRequestResource = $root.google.cloud.compute.v1beta.ZoneSetPolicyRequest.fromObject(object.zoneSetPolicyRequestResource); + } + return message; + }; + + /** + * Creates a plain object from a SetIamPolicyInstantSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest} message SetIamPolicyInstantSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SetIamPolicyInstantSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.resource = ""; + object.project = ""; + object.zoneSetPolicyRequestResource = null; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.zoneSetPolicyRequestResource != null && message.hasOwnProperty("zoneSetPolicyRequestResource")) + object.zoneSetPolicyRequestResource = $root.google.cloud.compute.v1beta.ZoneSetPolicyRequest.toObject(message.zoneSetPolicyRequestResource, options); + return object; + }; + + /** + * Converts this SetIamPolicyInstantSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + SetIamPolicyInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SetIamPolicyInstantSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SetIamPolicyInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest"; + }; + + return SetIamPolicyInstantSnapshotGroupRequest; + })(); + v1beta.SetIamPolicyInstantSnapshotRequest = (function() { /** @@ -1216615,55 +1234032,335 @@ }; /** - * Converts this SetIamPolicyNodeTemplateRequest to JSON. + * Converts this SetIamPolicyNodeTemplateRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.SetIamPolicyNodeTemplateRequest + * @instance + * @returns {Object.} JSON object + */ + SetIamPolicyNodeTemplateRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SetIamPolicyNodeTemplateRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.SetIamPolicyNodeTemplateRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SetIamPolicyNodeTemplateRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyNodeTemplateRequest"; + }; + + return SetIamPolicyNodeTemplateRequest; + })(); + + v1beta.SetIamPolicyRegionBackendBucketRequest = (function() { + + /** + * Properties of a SetIamPolicyRegionBackendBucketRequest. + * @memberof google.cloud.compute.v1beta + * @interface ISetIamPolicyRegionBackendBucketRequest + * @property {string|null} [project] SetIamPolicyRegionBackendBucketRequest project + * @property {string|null} [region] SetIamPolicyRegionBackendBucketRequest region + * @property {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null} [regionSetPolicyRequestResource] SetIamPolicyRegionBackendBucketRequest regionSetPolicyRequestResource + * @property {string|null} [resource] SetIamPolicyRegionBackendBucketRequest resource + */ + + /** + * Constructs a new SetIamPolicyRegionBackendBucketRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a SetIamPolicyRegionBackendBucketRequest. + * @implements ISetIamPolicyRegionBackendBucketRequest + * @constructor + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendBucketRequest=} [properties] Properties to set + */ + function SetIamPolicyRegionBackendBucketRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SetIamPolicyRegionBackendBucketRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @instance + */ + SetIamPolicyRegionBackendBucketRequest.prototype.project = ""; + + /** + * SetIamPolicyRegionBackendBucketRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @instance + */ + SetIamPolicyRegionBackendBucketRequest.prototype.region = ""; + + /** + * SetIamPolicyRegionBackendBucketRequest regionSetPolicyRequestResource. + * @member {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null|undefined} regionSetPolicyRequestResource + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @instance + */ + SetIamPolicyRegionBackendBucketRequest.prototype.regionSetPolicyRequestResource = null; + + /** + * SetIamPolicyRegionBackendBucketRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @instance + */ + SetIamPolicyRegionBackendBucketRequest.prototype.resource = ""; + + /** + * Creates a new SetIamPolicyRegionBackendBucketRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendBucketRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} SetIamPolicyRegionBackendBucketRequest instance + */ + SetIamPolicyRegionBackendBucketRequest.create = function create(properties) { + return new SetIamPolicyRegionBackendBucketRequest(properties); + }; + + /** + * Encodes the specified SetIamPolicyRegionBackendBucketRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendBucketRequest} message SetIamPolicyRegionBackendBucketRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SetIamPolicyRegionBackendBucketRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.regionSetPolicyRequestResource != null && Object.hasOwnProperty.call(message, "regionSetPolicyRequestResource")) + $root.google.cloud.compute.v1beta.RegionSetPolicyRequest.encode(message.regionSetPolicyRequestResource, writer.uint32(/* id 276489091, wireType 2 =*/2211912730).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SetIamPolicyRegionBackendBucketRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendBucketRequest} message SetIamPolicyRegionBackendBucketRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SetIamPolicyRegionBackendBucketRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SetIamPolicyRegionBackendBucketRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} SetIamPolicyRegionBackendBucketRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SetIamPolicyRegionBackendBucketRequest.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.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 276489091: { + message.regionSetPolicyRequestResource = $root.google.cloud.compute.v1beta.RegionSetPolicyRequest.decode(reader, reader.uint32()); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SetIamPolicyRegionBackendBucketRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} SetIamPolicyRegionBackendBucketRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SetIamPolicyRegionBackendBucketRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SetIamPolicyRegionBackendBucketRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SetIamPolicyRegionBackendBucketRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.regionSetPolicyRequestResource != null && message.hasOwnProperty("regionSetPolicyRequestResource")) { + var error = $root.google.cloud.compute.v1beta.RegionSetPolicyRequest.verify(message.regionSetPolicyRequestResource); + if (error) + return "regionSetPolicyRequestResource." + error; + } + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + return null; + }; + + /** + * Creates a SetIamPolicyRegionBackendBucketRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} SetIamPolicyRegionBackendBucketRequest + */ + SetIamPolicyRegionBackendBucketRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest(); + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.regionSetPolicyRequestResource != null) { + if (typeof object.regionSetPolicyRequestResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest.regionSetPolicyRequestResource: object expected"); + message.regionSetPolicyRequestResource = $root.google.cloud.compute.v1beta.RegionSetPolicyRequest.fromObject(object.regionSetPolicyRequestResource); + } + if (object.resource != null) + message.resource = String(object.resource); + return message; + }; + + /** + * Creates a plain object from a SetIamPolicyRegionBackendBucketRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @static + * @param {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} message SetIamPolicyRegionBackendBucketRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SetIamPolicyRegionBackendBucketRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.resource = ""; + object.project = ""; + object.regionSetPolicyRequestResource = null; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.regionSetPolicyRequestResource != null && message.hasOwnProperty("regionSetPolicyRequestResource")) + object.regionSetPolicyRequestResource = $root.google.cloud.compute.v1beta.RegionSetPolicyRequest.toObject(message.regionSetPolicyRequestResource, options); + return object; + }; + + /** + * Converts this SetIamPolicyRegionBackendBucketRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.SetIamPolicyNodeTemplateRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest * @instance * @returns {Object.} JSON object */ - SetIamPolicyNodeTemplateRequest.prototype.toJSON = function toJSON() { + SetIamPolicyRegionBackendBucketRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for SetIamPolicyNodeTemplateRequest + * Gets the default type url for SetIamPolicyRegionBackendBucketRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.SetIamPolicyNodeTemplateRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - SetIamPolicyNodeTemplateRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + SetIamPolicyRegionBackendBucketRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyNodeTemplateRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest"; }; - return SetIamPolicyNodeTemplateRequest; + return SetIamPolicyRegionBackendBucketRequest; })(); - v1beta.SetIamPolicyRegionBackendBucketRequest = (function() { + v1beta.SetIamPolicyRegionBackendServiceRequest = (function() { /** - * Properties of a SetIamPolicyRegionBackendBucketRequest. + * Properties of a SetIamPolicyRegionBackendServiceRequest. * @memberof google.cloud.compute.v1beta - * @interface ISetIamPolicyRegionBackendBucketRequest - * @property {string|null} [project] SetIamPolicyRegionBackendBucketRequest project - * @property {string|null} [region] SetIamPolicyRegionBackendBucketRequest region - * @property {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null} [regionSetPolicyRequestResource] SetIamPolicyRegionBackendBucketRequest regionSetPolicyRequestResource - * @property {string|null} [resource] SetIamPolicyRegionBackendBucketRequest resource + * @interface ISetIamPolicyRegionBackendServiceRequest + * @property {string|null} [project] SetIamPolicyRegionBackendServiceRequest project + * @property {string|null} [region] SetIamPolicyRegionBackendServiceRequest region + * @property {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null} [regionSetPolicyRequestResource] SetIamPolicyRegionBackendServiceRequest regionSetPolicyRequestResource + * @property {string|null} [resource] SetIamPolicyRegionBackendServiceRequest resource */ /** - * Constructs a new SetIamPolicyRegionBackendBucketRequest. + * Constructs a new SetIamPolicyRegionBackendServiceRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a SetIamPolicyRegionBackendBucketRequest. - * @implements ISetIamPolicyRegionBackendBucketRequest + * @classdesc Represents a SetIamPolicyRegionBackendServiceRequest. + * @implements ISetIamPolicyRegionBackendServiceRequest * @constructor - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendBucketRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendServiceRequest=} [properties] Properties to set */ - function SetIamPolicyRegionBackendBucketRequest(properties) { + function SetIamPolicyRegionBackendServiceRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1216671,59 +1234368,59 @@ } /** - * SetIamPolicyRegionBackendBucketRequest project. + * SetIamPolicyRegionBackendServiceRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @instance */ - SetIamPolicyRegionBackendBucketRequest.prototype.project = ""; + SetIamPolicyRegionBackendServiceRequest.prototype.project = ""; /** - * SetIamPolicyRegionBackendBucketRequest region. + * SetIamPolicyRegionBackendServiceRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @instance */ - SetIamPolicyRegionBackendBucketRequest.prototype.region = ""; + SetIamPolicyRegionBackendServiceRequest.prototype.region = ""; /** - * SetIamPolicyRegionBackendBucketRequest regionSetPolicyRequestResource. + * SetIamPolicyRegionBackendServiceRequest regionSetPolicyRequestResource. * @member {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null|undefined} regionSetPolicyRequestResource - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @instance */ - SetIamPolicyRegionBackendBucketRequest.prototype.regionSetPolicyRequestResource = null; + SetIamPolicyRegionBackendServiceRequest.prototype.regionSetPolicyRequestResource = null; /** - * SetIamPolicyRegionBackendBucketRequest resource. + * SetIamPolicyRegionBackendServiceRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @instance */ - SetIamPolicyRegionBackendBucketRequest.prototype.resource = ""; + SetIamPolicyRegionBackendServiceRequest.prototype.resource = ""; /** - * Creates a new SetIamPolicyRegionBackendBucketRequest instance using the specified properties. + * Creates a new SetIamPolicyRegionBackendServiceRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendBucketRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} SetIamPolicyRegionBackendBucketRequest instance + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendServiceRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} SetIamPolicyRegionBackendServiceRequest instance */ - SetIamPolicyRegionBackendBucketRequest.create = function create(properties) { - return new SetIamPolicyRegionBackendBucketRequest(properties); + SetIamPolicyRegionBackendServiceRequest.create = function create(properties) { + return new SetIamPolicyRegionBackendServiceRequest(properties); }; /** - * Encodes the specified SetIamPolicyRegionBackendBucketRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest.verify|verify} messages. + * Encodes the specified SetIamPolicyRegionBackendServiceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendBucketRequest} message SetIamPolicyRegionBackendBucketRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendServiceRequest} message SetIamPolicyRegionBackendServiceRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SetIamPolicyRegionBackendBucketRequest.encode = function encode(message, writer) { + SetIamPolicyRegionBackendServiceRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1216738,33 +1234435,33 @@ }; /** - * Encodes the specified SetIamPolicyRegionBackendBucketRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest.verify|verify} messages. + * Encodes the specified SetIamPolicyRegionBackendServiceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendBucketRequest} message SetIamPolicyRegionBackendBucketRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendServiceRequest} message SetIamPolicyRegionBackendServiceRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SetIamPolicyRegionBackendBucketRequest.encodeDelimited = function encodeDelimited(message, writer) { + SetIamPolicyRegionBackendServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a SetIamPolicyRegionBackendBucketRequest message from the specified reader or buffer. + * Decodes a SetIamPolicyRegionBackendServiceRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} SetIamPolicyRegionBackendBucketRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} SetIamPolicyRegionBackendServiceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SetIamPolicyRegionBackendBucketRequest.decode = function decode(reader, length, error) { + SetIamPolicyRegionBackendServiceRequest.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.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1216795,30 +1234492,30 @@ }; /** - * Decodes a SetIamPolicyRegionBackendBucketRequest message from the specified reader or buffer, length delimited. + * Decodes a SetIamPolicyRegionBackendServiceRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} SetIamPolicyRegionBackendBucketRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} SetIamPolicyRegionBackendServiceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SetIamPolicyRegionBackendBucketRequest.decodeDelimited = function decodeDelimited(reader) { + SetIamPolicyRegionBackendServiceRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a SetIamPolicyRegionBackendBucketRequest message. + * Verifies a SetIamPolicyRegionBackendServiceRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - SetIamPolicyRegionBackendBucketRequest.verify = function verify(message) { + SetIamPolicyRegionBackendServiceRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1216839,24 +1234536,24 @@ }; /** - * Creates a SetIamPolicyRegionBackendBucketRequest message from a plain object. Also converts values to their respective internal types. + * Creates a SetIamPolicyRegionBackendServiceRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} SetIamPolicyRegionBackendBucketRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} SetIamPolicyRegionBackendServiceRequest */ - SetIamPolicyRegionBackendBucketRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest) + SetIamPolicyRegionBackendServiceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest) return object; - var message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest(); + var message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) message.region = String(object.region); if (object.regionSetPolicyRequestResource != null) { if (typeof object.regionSetPolicyRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest.regionSetPolicyRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest.regionSetPolicyRequestResource: object expected"); message.regionSetPolicyRequestResource = $root.google.cloud.compute.v1beta.RegionSetPolicyRequest.fromObject(object.regionSetPolicyRequestResource); } if (object.resource != null) @@ -1216865,15 +1234562,15 @@ }; /** - * Creates a plain object from a SetIamPolicyRegionBackendBucketRequest message. Also converts values to other types if specified. + * Creates a plain object from a SetIamPolicyRegionBackendServiceRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static - * @param {google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest} message SetIamPolicyRegionBackendBucketRequest + * @param {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} message SetIamPolicyRegionBackendServiceRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - SetIamPolicyRegionBackendBucketRequest.toObject = function toObject(message, options) { + SetIamPolicyRegionBackendServiceRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1216895,55 +1234592,55 @@ }; /** - * Converts this SetIamPolicyRegionBackendBucketRequest to JSON. + * Converts this SetIamPolicyRegionBackendServiceRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @instance * @returns {Object.} JSON object */ - SetIamPolicyRegionBackendBucketRequest.prototype.toJSON = function toJSON() { + SetIamPolicyRegionBackendServiceRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for SetIamPolicyRegionBackendBucketRequest + * Gets the default type url for SetIamPolicyRegionBackendServiceRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - SetIamPolicyRegionBackendBucketRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + SetIamPolicyRegionBackendServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyRegionBackendBucketRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest"; }; - return SetIamPolicyRegionBackendBucketRequest; + return SetIamPolicyRegionBackendServiceRequest; })(); - v1beta.SetIamPolicyRegionBackendServiceRequest = (function() { + v1beta.SetIamPolicyRegionDiskRequest = (function() { /** - * Properties of a SetIamPolicyRegionBackendServiceRequest. + * Properties of a SetIamPolicyRegionDiskRequest. * @memberof google.cloud.compute.v1beta - * @interface ISetIamPolicyRegionBackendServiceRequest - * @property {string|null} [project] SetIamPolicyRegionBackendServiceRequest project - * @property {string|null} [region] SetIamPolicyRegionBackendServiceRequest region - * @property {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null} [regionSetPolicyRequestResource] SetIamPolicyRegionBackendServiceRequest regionSetPolicyRequestResource - * @property {string|null} [resource] SetIamPolicyRegionBackendServiceRequest resource + * @interface ISetIamPolicyRegionDiskRequest + * @property {string|null} [project] SetIamPolicyRegionDiskRequest project + * @property {string|null} [region] SetIamPolicyRegionDiskRequest region + * @property {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null} [regionSetPolicyRequestResource] SetIamPolicyRegionDiskRequest regionSetPolicyRequestResource + * @property {string|null} [resource] SetIamPolicyRegionDiskRequest resource */ /** - * Constructs a new SetIamPolicyRegionBackendServiceRequest. + * Constructs a new SetIamPolicyRegionDiskRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a SetIamPolicyRegionBackendServiceRequest. - * @implements ISetIamPolicyRegionBackendServiceRequest + * @classdesc Represents a SetIamPolicyRegionDiskRequest. + * @implements ISetIamPolicyRegionDiskRequest * @constructor - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendServiceRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionDiskRequest=} [properties] Properties to set */ - function SetIamPolicyRegionBackendServiceRequest(properties) { + function SetIamPolicyRegionDiskRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1216951,59 +1234648,59 @@ } /** - * SetIamPolicyRegionBackendServiceRequest project. + * SetIamPolicyRegionDiskRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @instance */ - SetIamPolicyRegionBackendServiceRequest.prototype.project = ""; + SetIamPolicyRegionDiskRequest.prototype.project = ""; /** - * SetIamPolicyRegionBackendServiceRequest region. + * SetIamPolicyRegionDiskRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @instance */ - SetIamPolicyRegionBackendServiceRequest.prototype.region = ""; + SetIamPolicyRegionDiskRequest.prototype.region = ""; /** - * SetIamPolicyRegionBackendServiceRequest regionSetPolicyRequestResource. + * SetIamPolicyRegionDiskRequest regionSetPolicyRequestResource. * @member {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null|undefined} regionSetPolicyRequestResource - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @instance */ - SetIamPolicyRegionBackendServiceRequest.prototype.regionSetPolicyRequestResource = null; + SetIamPolicyRegionDiskRequest.prototype.regionSetPolicyRequestResource = null; /** - * SetIamPolicyRegionBackendServiceRequest resource. + * SetIamPolicyRegionDiskRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @instance */ - SetIamPolicyRegionBackendServiceRequest.prototype.resource = ""; + SetIamPolicyRegionDiskRequest.prototype.resource = ""; /** - * Creates a new SetIamPolicyRegionBackendServiceRequest instance using the specified properties. + * Creates a new SetIamPolicyRegionDiskRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendServiceRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} SetIamPolicyRegionBackendServiceRequest instance + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionDiskRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} SetIamPolicyRegionDiskRequest instance */ - SetIamPolicyRegionBackendServiceRequest.create = function create(properties) { - return new SetIamPolicyRegionBackendServiceRequest(properties); + SetIamPolicyRegionDiskRequest.create = function create(properties) { + return new SetIamPolicyRegionDiskRequest(properties); }; /** - * Encodes the specified SetIamPolicyRegionBackendServiceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest.verify|verify} messages. + * Encodes the specified SetIamPolicyRegionDiskRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendServiceRequest} message SetIamPolicyRegionBackendServiceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionDiskRequest} message SetIamPolicyRegionDiskRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SetIamPolicyRegionBackendServiceRequest.encode = function encode(message, writer) { + SetIamPolicyRegionDiskRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1217018,33 +1234715,33 @@ }; /** - * Encodes the specified SetIamPolicyRegionBackendServiceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest.verify|verify} messages. + * Encodes the specified SetIamPolicyRegionDiskRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionBackendServiceRequest} message SetIamPolicyRegionBackendServiceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionDiskRequest} message SetIamPolicyRegionDiskRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SetIamPolicyRegionBackendServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { + SetIamPolicyRegionDiskRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a SetIamPolicyRegionBackendServiceRequest message from the specified reader or buffer. + * Decodes a SetIamPolicyRegionDiskRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} SetIamPolicyRegionBackendServiceRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} SetIamPolicyRegionDiskRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SetIamPolicyRegionBackendServiceRequest.decode = function decode(reader, length, error) { + SetIamPolicyRegionDiskRequest.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.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1217075,30 +1234772,30 @@ }; /** - * Decodes a SetIamPolicyRegionBackendServiceRequest message from the specified reader or buffer, length delimited. + * Decodes a SetIamPolicyRegionDiskRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} SetIamPolicyRegionBackendServiceRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} SetIamPolicyRegionDiskRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SetIamPolicyRegionBackendServiceRequest.decodeDelimited = function decodeDelimited(reader) { + SetIamPolicyRegionDiskRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a SetIamPolicyRegionBackendServiceRequest message. + * Verifies a SetIamPolicyRegionDiskRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - SetIamPolicyRegionBackendServiceRequest.verify = function verify(message) { + SetIamPolicyRegionDiskRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1217119,24 +1234816,24 @@ }; /** - * Creates a SetIamPolicyRegionBackendServiceRequest message from a plain object. Also converts values to their respective internal types. + * Creates a SetIamPolicyRegionDiskRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} SetIamPolicyRegionBackendServiceRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} SetIamPolicyRegionDiskRequest */ - SetIamPolicyRegionBackendServiceRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest) + SetIamPolicyRegionDiskRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest) return object; - var message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest(); + var message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) message.region = String(object.region); if (object.regionSetPolicyRequestResource != null) { if (typeof object.regionSetPolicyRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest.regionSetPolicyRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest.regionSetPolicyRequestResource: object expected"); message.regionSetPolicyRequestResource = $root.google.cloud.compute.v1beta.RegionSetPolicyRequest.fromObject(object.regionSetPolicyRequestResource); } if (object.resource != null) @@ -1217145,15 +1234842,15 @@ }; /** - * Creates a plain object from a SetIamPolicyRegionBackendServiceRequest message. Also converts values to other types if specified. + * Creates a plain object from a SetIamPolicyRegionDiskRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static - * @param {google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest} message SetIamPolicyRegionBackendServiceRequest + * @param {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} message SetIamPolicyRegionDiskRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - SetIamPolicyRegionBackendServiceRequest.toObject = function toObject(message, options) { + SetIamPolicyRegionDiskRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1217175,55 +1234872,55 @@ }; /** - * Converts this SetIamPolicyRegionBackendServiceRequest to JSON. + * Converts this SetIamPolicyRegionDiskRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @instance * @returns {Object.} JSON object */ - SetIamPolicyRegionBackendServiceRequest.prototype.toJSON = function toJSON() { + SetIamPolicyRegionDiskRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for SetIamPolicyRegionBackendServiceRequest + * Gets the default type url for SetIamPolicyRegionDiskRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - SetIamPolicyRegionBackendServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + SetIamPolicyRegionDiskRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyRegionBackendServiceRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest"; }; - return SetIamPolicyRegionBackendServiceRequest; + return SetIamPolicyRegionDiskRequest; })(); - v1beta.SetIamPolicyRegionDiskRequest = (function() { + v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest = (function() { /** - * Properties of a SetIamPolicyRegionDiskRequest. + * Properties of a SetIamPolicyRegionInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface ISetIamPolicyRegionDiskRequest - * @property {string|null} [project] SetIamPolicyRegionDiskRequest project - * @property {string|null} [region] SetIamPolicyRegionDiskRequest region - * @property {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null} [regionSetPolicyRequestResource] SetIamPolicyRegionDiskRequest regionSetPolicyRequestResource - * @property {string|null} [resource] SetIamPolicyRegionDiskRequest resource + * @interface ISetIamPolicyRegionInstantSnapshotGroupRequest + * @property {string|null} [project] SetIamPolicyRegionInstantSnapshotGroupRequest project + * @property {string|null} [region] SetIamPolicyRegionInstantSnapshotGroupRequest region + * @property {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null} [regionSetPolicyRequestResource] SetIamPolicyRegionInstantSnapshotGroupRequest regionSetPolicyRequestResource + * @property {string|null} [resource] SetIamPolicyRegionInstantSnapshotGroupRequest resource */ /** - * Constructs a new SetIamPolicyRegionDiskRequest. + * Constructs a new SetIamPolicyRegionInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a SetIamPolicyRegionDiskRequest. - * @implements ISetIamPolicyRegionDiskRequest + * @classdesc Represents a SetIamPolicyRegionInstantSnapshotGroupRequest. + * @implements ISetIamPolicyRegionInstantSnapshotGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionDiskRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest=} [properties] Properties to set */ - function SetIamPolicyRegionDiskRequest(properties) { + function SetIamPolicyRegionInstantSnapshotGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1217231,59 +1234928,59 @@ } /** - * SetIamPolicyRegionDiskRequest project. + * SetIamPolicyRegionInstantSnapshotGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @instance */ - SetIamPolicyRegionDiskRequest.prototype.project = ""; + SetIamPolicyRegionInstantSnapshotGroupRequest.prototype.project = ""; /** - * SetIamPolicyRegionDiskRequest region. + * SetIamPolicyRegionInstantSnapshotGroupRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @instance */ - SetIamPolicyRegionDiskRequest.prototype.region = ""; + SetIamPolicyRegionInstantSnapshotGroupRequest.prototype.region = ""; /** - * SetIamPolicyRegionDiskRequest regionSetPolicyRequestResource. + * SetIamPolicyRegionInstantSnapshotGroupRequest regionSetPolicyRequestResource. * @member {google.cloud.compute.v1beta.IRegionSetPolicyRequest|null|undefined} regionSetPolicyRequestResource - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @instance */ - SetIamPolicyRegionDiskRequest.prototype.regionSetPolicyRequestResource = null; + SetIamPolicyRegionInstantSnapshotGroupRequest.prototype.regionSetPolicyRequestResource = null; /** - * SetIamPolicyRegionDiskRequest resource. + * SetIamPolicyRegionInstantSnapshotGroupRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @instance */ - SetIamPolicyRegionDiskRequest.prototype.resource = ""; + SetIamPolicyRegionInstantSnapshotGroupRequest.prototype.resource = ""; /** - * Creates a new SetIamPolicyRegionDiskRequest instance using the specified properties. + * Creates a new SetIamPolicyRegionInstantSnapshotGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionDiskRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} SetIamPolicyRegionDiskRequest instance + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest} SetIamPolicyRegionInstantSnapshotGroupRequest instance */ - SetIamPolicyRegionDiskRequest.create = function create(properties) { - return new SetIamPolicyRegionDiskRequest(properties); + SetIamPolicyRegionInstantSnapshotGroupRequest.create = function create(properties) { + return new SetIamPolicyRegionInstantSnapshotGroupRequest(properties); }; /** - * Encodes the specified SetIamPolicyRegionDiskRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest.verify|verify} messages. + * Encodes the specified SetIamPolicyRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionDiskRequest} message SetIamPolicyRegionDiskRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest} message SetIamPolicyRegionInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SetIamPolicyRegionDiskRequest.encode = function encode(message, writer) { + SetIamPolicyRegionInstantSnapshotGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1217298,33 +1234995,33 @@ }; /** - * Encodes the specified SetIamPolicyRegionDiskRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest.verify|verify} messages. + * Encodes the specified SetIamPolicyRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionDiskRequest} message SetIamPolicyRegionDiskRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest} message SetIamPolicyRegionInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SetIamPolicyRegionDiskRequest.encodeDelimited = function encodeDelimited(message, writer) { + SetIamPolicyRegionInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a SetIamPolicyRegionDiskRequest message from the specified reader or buffer. + * Decodes a SetIamPolicyRegionInstantSnapshotGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} SetIamPolicyRegionDiskRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest} SetIamPolicyRegionInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SetIamPolicyRegionDiskRequest.decode = function decode(reader, length, error) { + SetIamPolicyRegionInstantSnapshotGroupRequest.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.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1217355,30 +1235052,30 @@ }; /** - * Decodes a SetIamPolicyRegionDiskRequest message from the specified reader or buffer, length delimited. + * Decodes a SetIamPolicyRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} SetIamPolicyRegionDiskRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest} SetIamPolicyRegionInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SetIamPolicyRegionDiskRequest.decodeDelimited = function decodeDelimited(reader) { + SetIamPolicyRegionInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a SetIamPolicyRegionDiskRequest message. + * Verifies a SetIamPolicyRegionInstantSnapshotGroupRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - SetIamPolicyRegionDiskRequest.verify = function verify(message) { + SetIamPolicyRegionInstantSnapshotGroupRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1217399,24 +1235096,24 @@ }; /** - * Creates a SetIamPolicyRegionDiskRequest message from a plain object. Also converts values to their respective internal types. + * Creates a SetIamPolicyRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} SetIamPolicyRegionDiskRequest + * @returns {google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest} SetIamPolicyRegionInstantSnapshotGroupRequest */ - SetIamPolicyRegionDiskRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest) + SetIamPolicyRegionInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest) return object; - var message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest(); + var message = new $root.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) message.region = String(object.region); if (object.regionSetPolicyRequestResource != null) { if (typeof object.regionSetPolicyRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest.regionSetPolicyRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest.regionSetPolicyRequestResource: object expected"); message.regionSetPolicyRequestResource = $root.google.cloud.compute.v1beta.RegionSetPolicyRequest.fromObject(object.regionSetPolicyRequestResource); } if (object.resource != null) @@ -1217425,15 +1235122,15 @@ }; /** - * Creates a plain object from a SetIamPolicyRegionDiskRequest message. Also converts values to other types if specified. + * Creates a plain object from a SetIamPolicyRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest} message SetIamPolicyRegionDiskRequest + * @param {google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest} message SetIamPolicyRegionInstantSnapshotGroupRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - SetIamPolicyRegionDiskRequest.toObject = function toObject(message, options) { + SetIamPolicyRegionInstantSnapshotGroupRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1217455,32 +1235152,32 @@ }; /** - * Converts this SetIamPolicyRegionDiskRequest to JSON. + * Converts this SetIamPolicyRegionInstantSnapshotGroupRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @instance * @returns {Object.} JSON object */ - SetIamPolicyRegionDiskRequest.prototype.toJSON = function toJSON() { + SetIamPolicyRegionInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for SetIamPolicyRegionDiskRequest + * Gets the default type url for SetIamPolicyRegionInstantSnapshotGroupRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest + * @memberof google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - SetIamPolicyRegionDiskRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + SetIamPolicyRegionInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyRegionDiskRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest"; }; - return SetIamPolicyRegionDiskRequest; + return SetIamPolicyRegionInstantSnapshotGroupRequest; })(); v1beta.SetIamPolicyRegionInstantSnapshotRequest = (function() { @@ -1219769,6 +1237466,263 @@ return SetIamPolicyServiceAttachmentRequest; })(); + v1beta.SetIamPolicySnapshotGroupRequest = (function() { + + /** + * Properties of a SetIamPolicySnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface ISetIamPolicySnapshotGroupRequest + * @property {google.cloud.compute.v1beta.IGlobalSetPolicyRequest|null} [globalSetPolicyRequestResource] SetIamPolicySnapshotGroupRequest globalSetPolicyRequestResource + * @property {string|null} [project] SetIamPolicySnapshotGroupRequest project + * @property {string|null} [resource] SetIamPolicySnapshotGroupRequest resource + */ + + /** + * Constructs a new SetIamPolicySnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a SetIamPolicySnapshotGroupRequest. + * @implements ISetIamPolicySnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest=} [properties] Properties to set + */ + function SetIamPolicySnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SetIamPolicySnapshotGroupRequest globalSetPolicyRequestResource. + * @member {google.cloud.compute.v1beta.IGlobalSetPolicyRequest|null|undefined} globalSetPolicyRequestResource + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @instance + */ + SetIamPolicySnapshotGroupRequest.prototype.globalSetPolicyRequestResource = null; + + /** + * SetIamPolicySnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @instance + */ + SetIamPolicySnapshotGroupRequest.prototype.project = ""; + + /** + * SetIamPolicySnapshotGroupRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @instance + */ + SetIamPolicySnapshotGroupRequest.prototype.resource = ""; + + /** + * Creates a new SetIamPolicySnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest} SetIamPolicySnapshotGroupRequest instance + */ + SetIamPolicySnapshotGroupRequest.create = function create(properties) { + return new SetIamPolicySnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified SetIamPolicySnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest} message SetIamPolicySnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SetIamPolicySnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.globalSetPolicyRequestResource != null && Object.hasOwnProperty.call(message, "globalSetPolicyRequestResource")) + $root.google.cloud.compute.v1beta.GlobalSetPolicyRequest.encode(message.globalSetPolicyRequestResource, writer.uint32(/* id 337048498, wireType 2 =*/2696387986).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SetIamPolicySnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest} message SetIamPolicySnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SetIamPolicySnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SetIamPolicySnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest} SetIamPolicySnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SetIamPolicySnapshotGroupRequest.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.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 337048498: { + message.globalSetPolicyRequestResource = $root.google.cloud.compute.v1beta.GlobalSetPolicyRequest.decode(reader, reader.uint32()); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SetIamPolicySnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest} SetIamPolicySnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SetIamPolicySnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SetIamPolicySnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SetIamPolicySnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.globalSetPolicyRequestResource != null && message.hasOwnProperty("globalSetPolicyRequestResource")) { + var error = $root.google.cloud.compute.v1beta.GlobalSetPolicyRequest.verify(message.globalSetPolicyRequestResource); + if (error) + return "globalSetPolicyRequestResource." + error; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + return null; + }; + + /** + * Creates a SetIamPolicySnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest} SetIamPolicySnapshotGroupRequest + */ + SetIamPolicySnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest(); + if (object.globalSetPolicyRequestResource != null) { + if (typeof object.globalSetPolicyRequestResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest.globalSetPolicyRequestResource: object expected"); + message.globalSetPolicyRequestResource = $root.google.cloud.compute.v1beta.GlobalSetPolicyRequest.fromObject(object.globalSetPolicyRequestResource); + } + if (object.project != null) + message.project = String(object.project); + if (object.resource != null) + message.resource = String(object.resource); + return message; + }; + + /** + * Creates a plain object from a SetIamPolicySnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest} message SetIamPolicySnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SetIamPolicySnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.resource = ""; + object.project = ""; + object.globalSetPolicyRequestResource = null; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.globalSetPolicyRequestResource != null && message.hasOwnProperty("globalSetPolicyRequestResource")) + object.globalSetPolicyRequestResource = $root.google.cloud.compute.v1beta.GlobalSetPolicyRequest.toObject(message.globalSetPolicyRequestResource, options); + return object; + }; + + /** + * Converts this SetIamPolicySnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + SetIamPolicySnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SetIamPolicySnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SetIamPolicySnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest"; + }; + + return SetIamPolicySnapshotGroupRequest; + })(); + v1beta.SetIamPolicySnapshotRequest = (function() { /** @@ -1242440,6 +1260394,8 @@ * @property {boolean|null} [satisfiesPzs] Snapshot satisfiesPzs * @property {string|null} [selfLink] Snapshot selfLink * @property {google.cloud.compute.v1beta.ICustomerEncryptionKey|null} [snapshotEncryptionKey] Snapshot snapshotEncryptionKey + * @property {string|null} [snapshotGroupId] Snapshot snapshotGroupId + * @property {string|null} [snapshotGroupName] Snapshot snapshotGroupName * @property {string|null} [snapshotType] Snapshot snapshotType * @property {string|null} [sourceDisk] Snapshot sourceDisk * @property {google.cloud.compute.v1beta.ICustomerEncryptionKey|null} [sourceDiskEncryptionKey] Snapshot sourceDiskEncryptionKey @@ -1242678,6 +1260634,22 @@ */ Snapshot.prototype.snapshotEncryptionKey = null; + /** + * Snapshot snapshotGroupId. + * @member {string|null|undefined} snapshotGroupId + * @memberof google.cloud.compute.v1beta.Snapshot + * @instance + */ + Snapshot.prototype.snapshotGroupId = null; + + /** + * Snapshot snapshotGroupName. + * @member {string|null|undefined} snapshotGroupName + * @memberof google.cloud.compute.v1beta.Snapshot + * @instance + */ + Snapshot.prototype.snapshotGroupName = null; + /** * Snapshot snapshotType. * @member {string|null|undefined} snapshotType @@ -1242927,6 +1260899,18 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(Snapshot.prototype, "_snapshotGroupId", { + get: $util.oneOfGetter($oneOfFields = ["snapshotGroupId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(Snapshot.prototype, "_snapshotGroupName", { + get: $util.oneOfGetter($oneOfFields = ["snapshotGroupName"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(Snapshot.prototype, "_snapshotType", { get: $util.oneOfGetter($oneOfFields = ["snapshotType"]), @@ -1243070,6 +1261054,10 @@ writer.uint32(/* id 219202054, wireType 2 =*/1753616434).string(message.sourceInstantSnapshot); if (message.sourceSnapshotSchedulePolicy != null && Object.hasOwnProperty.call(message, "sourceSnapshotSchedulePolicy")) writer.uint32(/* id 235756291, wireType 2 =*/1886050330).string(message.sourceSnapshotSchedulePolicy); + if (message.snapshotGroupName != null && Object.hasOwnProperty.call(message, "snapshotGroupName")) + writer.uint32(/* id 246247846, wireType 2 =*/1969982770).string(message.snapshotGroupName); + if (message.snapshotGroupId != null && Object.hasOwnProperty.call(message, "snapshotGroupId")) + writer.uint32(/* id 255004406, wireType 2 =*/2040035250).string(message.snapshotGroupId); if (message.sourceInstantSnapshotId != null && Object.hasOwnProperty.call(message, "sourceInstantSnapshotId")) writer.uint32(/* id 287582708, wireType 2 =*/2300661666).string(message.sourceInstantSnapshotId); if (message.architecture != null && Object.hasOwnProperty.call(message, "architecture")) @@ -1243284,6 +1261272,14 @@ message.snapshotEncryptionKey = $root.google.cloud.compute.v1beta.CustomerEncryptionKey.decode(reader, reader.uint32()); break; } + case 255004406: { + message.snapshotGroupId = reader.string(); + break; + } + case 246247846: { + message.snapshotGroupName = reader.string(); + break; + } case 124349653: { message.snapshotType = reader.string(); break; @@ -1243526,6 +1261522,16 @@ return "snapshotEncryptionKey." + error; } } + if (message.snapshotGroupId != null && message.hasOwnProperty("snapshotGroupId")) { + properties._snapshotGroupId = 1; + if (!$util.isString(message.snapshotGroupId)) + return "snapshotGroupId: string expected"; + } + if (message.snapshotGroupName != null && message.hasOwnProperty("snapshotGroupName")) { + properties._snapshotGroupName = 1; + if (!$util.isString(message.snapshotGroupName)) + return "snapshotGroupName: string expected"; + } if (message.snapshotType != null && message.hasOwnProperty("snapshotType")) { properties._snapshotType = 1; if (!$util.isString(message.snapshotType)) @@ -1243740,6 +1261746,10 @@ throw TypeError(".google.cloud.compute.v1beta.Snapshot.snapshotEncryptionKey: object expected"); message.snapshotEncryptionKey = $root.google.cloud.compute.v1beta.CustomerEncryptionKey.fromObject(object.snapshotEncryptionKey); } + if (object.snapshotGroupId != null) + message.snapshotGroupId = String(object.snapshotGroupId); + if (object.snapshotGroupName != null) + message.snapshotGroupName = String(object.snapshotGroupName); if (object.snapshotType != null) message.snapshotType = String(object.snapshotType); if (object.sourceDisk != null) @@ -1243841,333 +1261851,1428 @@ if (options.oneofs) object._creationTimestamp = "creationTimestamp"; } - if (message.snapshotEncryptionKey != null && message.hasOwnProperty("snapshotEncryptionKey")) { - object.snapshotEncryptionKey = $root.google.cloud.compute.v1beta.CustomerEncryptionKey.toObject(message.snapshotEncryptionKey, options); - if (options.oneofs) - object._snapshotEncryptionKey = "snapshotEncryptionKey"; - } - if (message.licenseCodes && message.licenseCodes.length) { - object.licenseCodes = []; - for (var j = 0; j < message.licenseCodes.length; ++j) - if (typeof message.licenseCodes[j] === "number") - object.licenseCodes[j] = options.longs === String ? String(message.licenseCodes[j]) : message.licenseCodes[j]; - else - object.licenseCodes[j] = options.longs === String ? $util.Long.prototype.toString.call(message.licenseCodes[j]) : options.longs === Number ? new $util.LongBits(message.licenseCodes[j].low >>> 0, message.licenseCodes[j].high >>> 0).toNumber() : message.licenseCodes[j]; - } - if (message.chainName != null && message.hasOwnProperty("chainName")) { - object.chainName = message.chainName; - if (options.oneofs) - object._chainName = "chainName"; - } - if (message.sourceSnapshotSchedulePolicyId != null && message.hasOwnProperty("sourceSnapshotSchedulePolicyId")) { - object.sourceSnapshotSchedulePolicyId = message.sourceSnapshotSchedulePolicyId; - if (options.oneofs) - object._sourceSnapshotSchedulePolicyId = "sourceSnapshotSchedulePolicyId"; - } - if (message.params != null && message.hasOwnProperty("params")) { - object.params = $root.google.cloud.compute.v1beta.SnapshotParams.toObject(message.params, options); - if (options.oneofs) - object._params = "params"; - } - if (message.guestOsFeatures && message.guestOsFeatures.length) { - object.guestOsFeatures = []; - for (var j = 0; j < message.guestOsFeatures.length; ++j) - object.guestOsFeatures[j] = $root.google.cloud.compute.v1beta.GuestOsFeature.toObject(message.guestOsFeatures[j], options); - } - if (message.enableConfidentialCompute != null && message.hasOwnProperty("enableConfidentialCompute")) { - object.enableConfidentialCompute = message.enableConfidentialCompute; - if (options.oneofs) - object._enableConfidentialCompute = "enableConfidentialCompute"; - } - if (message.snapshotType != null && message.hasOwnProperty("snapshotType")) { - object.snapshotType = message.snapshotType; - if (options.oneofs) - object._snapshotType = "snapshotType"; - } - if (message.creationSizeBytes != null && message.hasOwnProperty("creationSizeBytes")) { - if (typeof message.creationSizeBytes === "number") - object.creationSizeBytes = options.longs === String ? String(message.creationSizeBytes) : message.creationSizeBytes; - else - object.creationSizeBytes = options.longs === String ? $util.Long.prototype.toString.call(message.creationSizeBytes) : options.longs === Number ? new $util.LongBits(message.creationSizeBytes.low >>> 0, message.creationSizeBytes.high >>> 0).toNumber() : message.creationSizeBytes; - if (options.oneofs) - object._creationSizeBytes = "creationSizeBytes"; - } - if (message.region != null && message.hasOwnProperty("region")) { - object.region = message.region; + if (message.snapshotEncryptionKey != null && message.hasOwnProperty("snapshotEncryptionKey")) { + object.snapshotEncryptionKey = $root.google.cloud.compute.v1beta.CustomerEncryptionKey.toObject(message.snapshotEncryptionKey, options); + if (options.oneofs) + object._snapshotEncryptionKey = "snapshotEncryptionKey"; + } + if (message.licenseCodes && message.licenseCodes.length) { + object.licenseCodes = []; + for (var j = 0; j < message.licenseCodes.length; ++j) + if (typeof message.licenseCodes[j] === "number") + object.licenseCodes[j] = options.longs === String ? String(message.licenseCodes[j]) : message.licenseCodes[j]; + else + object.licenseCodes[j] = options.longs === String ? $util.Long.prototype.toString.call(message.licenseCodes[j]) : options.longs === Number ? new $util.LongBits(message.licenseCodes[j].low >>> 0, message.licenseCodes[j].high >>> 0).toNumber() : message.licenseCodes[j]; + } + if (message.chainName != null && message.hasOwnProperty("chainName")) { + object.chainName = message.chainName; + if (options.oneofs) + object._chainName = "chainName"; + } + if (message.sourceSnapshotSchedulePolicyId != null && message.hasOwnProperty("sourceSnapshotSchedulePolicyId")) { + object.sourceSnapshotSchedulePolicyId = message.sourceSnapshotSchedulePolicyId; + if (options.oneofs) + object._sourceSnapshotSchedulePolicyId = "sourceSnapshotSchedulePolicyId"; + } + if (message.params != null && message.hasOwnProperty("params")) { + object.params = $root.google.cloud.compute.v1beta.SnapshotParams.toObject(message.params, options); + if (options.oneofs) + object._params = "params"; + } + if (message.guestOsFeatures && message.guestOsFeatures.length) { + object.guestOsFeatures = []; + for (var j = 0; j < message.guestOsFeatures.length; ++j) + object.guestOsFeatures[j] = $root.google.cloud.compute.v1beta.GuestOsFeature.toObject(message.guestOsFeatures[j], options); + } + if (message.enableConfidentialCompute != null && message.hasOwnProperty("enableConfidentialCompute")) { + object.enableConfidentialCompute = message.enableConfidentialCompute; + if (options.oneofs) + object._enableConfidentialCompute = "enableConfidentialCompute"; + } + if (message.snapshotType != null && message.hasOwnProperty("snapshotType")) { + object.snapshotType = message.snapshotType; + if (options.oneofs) + object._snapshotType = "snapshotType"; + } + if (message.creationSizeBytes != null && message.hasOwnProperty("creationSizeBytes")) { + if (typeof message.creationSizeBytes === "number") + object.creationSizeBytes = options.longs === String ? String(message.creationSizeBytes) : message.creationSizeBytes; + else + object.creationSizeBytes = options.longs === String ? $util.Long.prototype.toString.call(message.creationSizeBytes) : options.longs === Number ? new $util.LongBits(message.creationSizeBytes.low >>> 0, message.creationSizeBytes.high >>> 0).toNumber() : message.creationSizeBytes; + if (options.oneofs) + object._creationSizeBytes = "creationSizeBytes"; + } + if (message.region != null && message.hasOwnProperty("region")) { + object.region = message.region; + if (options.oneofs) + object._region = "region"; + } + if (message.labelFingerprint != null && message.hasOwnProperty("labelFingerprint")) { + object.labelFingerprint = message.labelFingerprint; + if (options.oneofs) + object._labelFingerprint = "labelFingerprint"; + } + if (message.status != null && message.hasOwnProperty("status")) { + object.status = message.status; + if (options.oneofs) + object._status = "status"; + } + if (message.sourceInstantSnapshot != null && message.hasOwnProperty("sourceInstantSnapshot")) { + object.sourceInstantSnapshot = message.sourceInstantSnapshot; + if (options.oneofs) + object._sourceInstantSnapshot = "sourceInstantSnapshot"; + } + if (message.sourceSnapshotSchedulePolicy != null && message.hasOwnProperty("sourceSnapshotSchedulePolicy")) { + object.sourceSnapshotSchedulePolicy = message.sourceSnapshotSchedulePolicy; + if (options.oneofs) + object._sourceSnapshotSchedulePolicy = "sourceSnapshotSchedulePolicy"; + } + if (message.snapshotGroupName != null && message.hasOwnProperty("snapshotGroupName")) { + object.snapshotGroupName = message.snapshotGroupName; + if (options.oneofs) + object._snapshotGroupName = "snapshotGroupName"; + } + if (message.snapshotGroupId != null && message.hasOwnProperty("snapshotGroupId")) { + object.snapshotGroupId = message.snapshotGroupId; + if (options.oneofs) + object._snapshotGroupId = "snapshotGroupId"; + } + if (message.sourceInstantSnapshotId != null && message.hasOwnProperty("sourceInstantSnapshotId")) { + object.sourceInstantSnapshotId = message.sourceInstantSnapshotId; + if (options.oneofs) + object._sourceInstantSnapshotId = "sourceInstantSnapshotId"; + } + if (message.architecture != null && message.hasOwnProperty("architecture")) { + object.architecture = message.architecture; + if (options.oneofs) + object._architecture = "architecture"; + } + if (message.diskSizeGb != null && message.hasOwnProperty("diskSizeGb")) { + if (typeof message.diskSizeGb === "number") + object.diskSizeGb = options.longs === String ? String(message.diskSizeGb) : message.diskSizeGb; + else + object.diskSizeGb = options.longs === String ? $util.Long.prototype.toString.call(message.diskSizeGb) : options.longs === Number ? new $util.LongBits(message.diskSizeGb.low >>> 0, message.diskSizeGb.high >>> 0).toNumber() : message.diskSizeGb; + if (options.oneofs) + object._diskSizeGb = "diskSizeGb"; + } + if (message.storageLocations && message.storageLocations.length) { + object.storageLocations = []; + for (var j = 0; j < message.storageLocations.length; ++j) + object.storageLocations[j] = message.storageLocations[j]; + } + if (message.licenses && message.licenses.length) { + object.licenses = []; + for (var j = 0; j < message.licenses.length; ++j) + object.licenses[j] = message.licenses[j]; + } + if (message.locationHint != null && message.hasOwnProperty("locationHint")) { + object.locationHint = message.locationHint; + if (options.oneofs) + object._locationHint = "locationHint"; + } + if (message.sourceDiskForRecoveryCheckpoint != null && message.hasOwnProperty("sourceDiskForRecoveryCheckpoint")) { + object.sourceDiskForRecoveryCheckpoint = message.sourceDiskForRecoveryCheckpoint; + if (options.oneofs) + object._sourceDiskForRecoveryCheckpoint = "sourceDiskForRecoveryCheckpoint"; + } + if (message.guestFlush != null && message.hasOwnProperty("guestFlush")) { + object.guestFlush = message.guestFlush; + if (options.oneofs) + object._guestFlush = "guestFlush"; + } + if (message.userLicenses && message.userLicenses.length) { + object.userLicenses = []; + for (var j = 0; j < message.userLicenses.length; ++j) + object.userLicenses[j] = message.userLicenses[j]; + } + if (message.description != null && message.hasOwnProperty("description")) { + object.description = message.description; + if (options.oneofs) + object._description = "description"; + } + if (message.storageBytes != null && message.hasOwnProperty("storageBytes")) { + if (typeof message.storageBytes === "number") + object.storageBytes = options.longs === String ? String(message.storageBytes) : message.storageBytes; + else + object.storageBytes = options.longs === String ? $util.Long.prototype.toString.call(message.storageBytes) : options.longs === Number ? new $util.LongBits(message.storageBytes.low >>> 0, message.storageBytes.high >>> 0).toNumber() : message.storageBytes; + if (options.oneofs) + object._storageBytes = "storageBytes"; + } + if (message.downloadBytes != null && message.hasOwnProperty("downloadBytes")) { + if (typeof message.downloadBytes === "number") + object.downloadBytes = options.longs === String ? String(message.downloadBytes) : message.downloadBytes; + else + object.downloadBytes = options.longs === String ? $util.Long.prototype.toString.call(message.downloadBytes) : options.longs === Number ? new $util.LongBits(message.downloadBytes.low >>> 0, message.downloadBytes.high >>> 0).toNumber() : message.downloadBytes; + if (options.oneofs) + object._downloadBytes = "downloadBytes"; + } + if (message.sourceInstantSnapshotEncryptionKey != null && message.hasOwnProperty("sourceInstantSnapshotEncryptionKey")) { + object.sourceInstantSnapshotEncryptionKey = $root.google.cloud.compute.v1beta.CustomerEncryptionKey.toObject(message.sourceInstantSnapshotEncryptionKey, options); + if (options.oneofs) + object._sourceInstantSnapshotEncryptionKey = "sourceInstantSnapshotEncryptionKey"; + } + if (message.sourceDisk != null && message.hasOwnProperty("sourceDisk")) { + object.sourceDisk = message.sourceDisk; + if (options.oneofs) + object._sourceDisk = "sourceDisk"; + } + if (message.sourceDiskId != null && message.hasOwnProperty("sourceDiskId")) { + object.sourceDiskId = message.sourceDiskId; + if (options.oneofs) + object._sourceDiskId = "sourceDiskId"; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + object.selfLink = message.selfLink; + if (options.oneofs) + object._selfLink = "selfLink"; + } + if (message.autoCreated != null && message.hasOwnProperty("autoCreated")) { + object.autoCreated = message.autoCreated; + if (options.oneofs) + object._autoCreated = "autoCreated"; + } + if (message.satisfiesPzi != null && message.hasOwnProperty("satisfiesPzi")) { + object.satisfiesPzi = message.satisfiesPzi; + if (options.oneofs) + object._satisfiesPzi = "satisfiesPzi"; + } + if (message.satisfiesPzs != null && message.hasOwnProperty("satisfiesPzs")) { + object.satisfiesPzs = message.satisfiesPzs; + if (options.oneofs) + object._satisfiesPzs = "satisfiesPzs"; + } + if (message.storageBytesStatus != null && message.hasOwnProperty("storageBytesStatus")) { + object.storageBytesStatus = message.storageBytesStatus; + if (options.oneofs) + object._storageBytesStatus = "storageBytesStatus"; + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + if (message.sourceDiskEncryptionKey != null && message.hasOwnProperty("sourceDiskEncryptionKey")) { + object.sourceDiskEncryptionKey = $root.google.cloud.compute.v1beta.CustomerEncryptionKey.toObject(message.sourceDiskEncryptionKey, options); + if (options.oneofs) + object._sourceDiskEncryptionKey = "sourceDiskEncryptionKey"; + } + return object; + }; + + /** + * Converts this Snapshot to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.Snapshot + * @instance + * @returns {Object.} JSON object + */ + Snapshot.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Snapshot + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.Snapshot + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Snapshot.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.Snapshot"; + }; + + /** + * Architecture enum. + * @name google.cloud.compute.v1beta.Snapshot.Architecture + * @enum {number} + * @property {number} UNDEFINED_ARCHITECTURE=0 UNDEFINED_ARCHITECTURE value + * @property {number} ARCHITECTURE_UNSPECIFIED=394750507 ARCHITECTURE_UNSPECIFIED value + * @property {number} ARM64=62547450 ARM64 value + * @property {number} X86_64=425300551 X86_64 value + */ + Snapshot.Architecture = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_ARCHITECTURE"] = 0; + values[valuesById[394750507] = "ARCHITECTURE_UNSPECIFIED"] = 394750507; + values[valuesById[62547450] = "ARM64"] = 62547450; + values[valuesById[425300551] = "X86_64"] = 425300551; + return values; + })(); + + /** + * SnapshotType enum. + * @name google.cloud.compute.v1beta.Snapshot.SnapshotType + * @enum {number} + * @property {number} UNDEFINED_SNAPSHOT_TYPE=0 UNDEFINED_SNAPSHOT_TYPE value + * @property {number} ARCHIVE=506752162 ARCHIVE value + * @property {number} STANDARD=484642493 STANDARD value + */ + Snapshot.SnapshotType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_SNAPSHOT_TYPE"] = 0; + values[valuesById[506752162] = "ARCHIVE"] = 506752162; + values[valuesById[484642493] = "STANDARD"] = 484642493; + return values; + })(); + + /** + * Status enum. + * @name google.cloud.compute.v1beta.Snapshot.Status + * @enum {number} + * @property {number} UNDEFINED_STATUS=0 UNDEFINED_STATUS value + * @property {number} CREATING=455564985 CREATING value + * @property {number} DELETING=528602024 DELETING value + * @property {number} FAILED=455706685 FAILED value + * @property {number} READY=77848963 READY value + * @property {number} UPLOADING=267603489 UPLOADING value + */ + Snapshot.Status = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_STATUS"] = 0; + values[valuesById[455564985] = "CREATING"] = 455564985; + values[valuesById[528602024] = "DELETING"] = 528602024; + values[valuesById[455706685] = "FAILED"] = 455706685; + values[valuesById[77848963] = "READY"] = 77848963; + values[valuesById[267603489] = "UPLOADING"] = 267603489; + return values; + })(); + + /** + * StorageBytesStatus enum. + * @name google.cloud.compute.v1beta.Snapshot.StorageBytesStatus + * @enum {number} + * @property {number} UNDEFINED_STORAGE_BYTES_STATUS=0 UNDEFINED_STORAGE_BYTES_STATUS value + * @property {number} UPDATING=494614342 UPDATING value + * @property {number} UP_TO_DATE=101306702 UP_TO_DATE value + */ + Snapshot.StorageBytesStatus = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UNDEFINED_STORAGE_BYTES_STATUS"] = 0; + values[valuesById[494614342] = "UPDATING"] = 494614342; + values[valuesById[101306702] = "UP_TO_DATE"] = 101306702; + return values; + })(); + + return Snapshot; + })(); + + v1beta.SnapshotAggregatedList = (function() { + + /** + * Properties of a SnapshotAggregatedList. + * @memberof google.cloud.compute.v1beta + * @interface ISnapshotAggregatedList + * @property {string|null} [etag] SnapshotAggregatedList etag + * @property {string|null} [id] SnapshotAggregatedList id + * @property {Object.|null} [items] SnapshotAggregatedList items + * @property {string|null} [kind] SnapshotAggregatedList kind + * @property {string|null} [nextPageToken] SnapshotAggregatedList nextPageToken + * @property {string|null} [selfLink] SnapshotAggregatedList selfLink + * @property {Array.|null} [unreachables] SnapshotAggregatedList unreachables + * @property {google.cloud.compute.v1beta.IWarning|null} [warning] SnapshotAggregatedList warning + */ + + /** + * Constructs a new SnapshotAggregatedList. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a SnapshotAggregatedList. + * @implements ISnapshotAggregatedList + * @constructor + * @param {google.cloud.compute.v1beta.ISnapshotAggregatedList=} [properties] Properties to set + */ + function SnapshotAggregatedList(properties) { + this.items = {}; + this.unreachables = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SnapshotAggregatedList etag. + * @member {string|null|undefined} etag + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + */ + SnapshotAggregatedList.prototype.etag = null; + + /** + * SnapshotAggregatedList id. + * @member {string|null|undefined} id + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + */ + SnapshotAggregatedList.prototype.id = null; + + /** + * SnapshotAggregatedList items. + * @member {Object.} items + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + */ + SnapshotAggregatedList.prototype.items = $util.emptyObject; + + /** + * SnapshotAggregatedList kind. + * @member {string|null|undefined} kind + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + */ + SnapshotAggregatedList.prototype.kind = null; + + /** + * SnapshotAggregatedList nextPageToken. + * @member {string|null|undefined} nextPageToken + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + */ + SnapshotAggregatedList.prototype.nextPageToken = null; + + /** + * SnapshotAggregatedList selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + */ + SnapshotAggregatedList.prototype.selfLink = null; + + /** + * SnapshotAggregatedList unreachables. + * @member {Array.} unreachables + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + */ + SnapshotAggregatedList.prototype.unreachables = $util.emptyArray; + + /** + * SnapshotAggregatedList warning. + * @member {google.cloud.compute.v1beta.IWarning|null|undefined} warning + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + */ + SnapshotAggregatedList.prototype.warning = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotAggregatedList.prototype, "_etag", { + get: $util.oneOfGetter($oneOfFields = ["etag"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotAggregatedList.prototype, "_id", { + get: $util.oneOfGetter($oneOfFields = ["id"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotAggregatedList.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotAggregatedList.prototype, "_nextPageToken", { + get: $util.oneOfGetter($oneOfFields = ["nextPageToken"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotAggregatedList.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotAggregatedList.prototype, "_warning", { + get: $util.oneOfGetter($oneOfFields = ["warning"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new SnapshotAggregatedList instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {google.cloud.compute.v1beta.ISnapshotAggregatedList=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SnapshotAggregatedList} SnapshotAggregatedList instance + */ + SnapshotAggregatedList.create = function create(properties) { + return new SnapshotAggregatedList(properties); + }; + + /** + * Encodes the specified SnapshotAggregatedList message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotAggregatedList.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {google.cloud.compute.v1beta.ISnapshotAggregatedList} message SnapshotAggregatedList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SnapshotAggregatedList.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 3355, wireType 2 =*/26842).string(message.id); + if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) + writer.uint32(/* id 3123477, wireType 2 =*/24987818).string(message.etag); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); + if (message.warning != null && Object.hasOwnProperty.call(message, "warning")) + $root.google.cloud.compute.v1beta.Warning.encode(message.warning, writer.uint32(/* id 50704284, wireType 2 =*/405634274).fork()).ldelim(); + if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) + writer.uint32(/* id 79797525, wireType 2 =*/638380202).string(message.nextPageToken); + if (message.items != null && Object.hasOwnProperty.call(message, "items")) + for (var keys = Object.keys(message.items), i = 0; i < keys.length; ++i) { + writer.uint32(/* id 100526016, wireType 2 =*/804208130).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); + $root.google.cloud.compute.v1beta.SnapshotsScopedList.encode(message.items[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); + } + if (message.unreachables != null && message.unreachables.length) + for (var i = 0; i < message.unreachables.length; ++i) + writer.uint32(/* id 243372063, wireType 2 =*/1946976506).string(message.unreachables[i]); + if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) + writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + return writer; + }; + + /** + * Encodes the specified SnapshotAggregatedList message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotAggregatedList.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {google.cloud.compute.v1beta.ISnapshotAggregatedList} message SnapshotAggregatedList message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SnapshotAggregatedList.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SnapshotAggregatedList message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.SnapshotAggregatedList} SnapshotAggregatedList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SnapshotAggregatedList.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.cloud.compute.v1beta.SnapshotAggregatedList(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3123477: { + message.etag = reader.string(); + break; + } + case 3355: { + message.id = reader.string(); + break; + } + case 100526016: { + if (message.items === $util.emptyObject) + message.items = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = null; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = $root.google.cloud.compute.v1beta.SnapshotsScopedList.decode(reader, reader.uint32()); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.items[key] = value; + break; + } + case 3292052: { + message.kind = reader.string(); + break; + } + case 79797525: { + message.nextPageToken = reader.string(); + break; + } + case 456214797: { + message.selfLink = reader.string(); + break; + } + case 243372063: { + if (!(message.unreachables && message.unreachables.length)) + message.unreachables = []; + message.unreachables.push(reader.string()); + break; + } + case 50704284: { + message.warning = $root.google.cloud.compute.v1beta.Warning.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SnapshotAggregatedList message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.SnapshotAggregatedList} SnapshotAggregatedList + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SnapshotAggregatedList.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SnapshotAggregatedList message. + * @function verify + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SnapshotAggregatedList.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.etag != null && message.hasOwnProperty("etag")) { + properties._etag = 1; + if (!$util.isString(message.etag)) + return "etag: string expected"; + } + if (message.id != null && message.hasOwnProperty("id")) { + properties._id = 1; + if (!$util.isString(message.id)) + return "id: string expected"; + } + if (message.items != null && message.hasOwnProperty("items")) { + if (!$util.isObject(message.items)) + return "items: object expected"; + var key = Object.keys(message.items); + for (var i = 0; i < key.length; ++i) { + var error = $root.google.cloud.compute.v1beta.SnapshotsScopedList.verify(message.items[key[i]]); + if (error) + return "items." + error; + } + } + if (message.kind != null && message.hasOwnProperty("kind")) { + properties._kind = 1; + if (!$util.isString(message.kind)) + return "kind: string expected"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + properties._nextPageToken = 1; + if (!$util.isString(message.nextPageToken)) + return "nextPageToken: string expected"; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + properties._selfLink = 1; + if (!$util.isString(message.selfLink)) + return "selfLink: string expected"; + } + if (message.unreachables != null && message.hasOwnProperty("unreachables")) { + if (!Array.isArray(message.unreachables)) + return "unreachables: array expected"; + for (var i = 0; i < message.unreachables.length; ++i) + if (!$util.isString(message.unreachables[i])) + return "unreachables: string[] expected"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + properties._warning = 1; + { + var error = $root.google.cloud.compute.v1beta.Warning.verify(message.warning); + if (error) + return "warning." + error; + } + } + return null; + }; + + /** + * Creates a SnapshotAggregatedList message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.SnapshotAggregatedList} SnapshotAggregatedList + */ + SnapshotAggregatedList.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SnapshotAggregatedList) + return object; + var message = new $root.google.cloud.compute.v1beta.SnapshotAggregatedList(); + if (object.etag != null) + message.etag = String(object.etag); + if (object.id != null) + message.id = String(object.id); + if (object.items) { + if (typeof object.items !== "object") + throw TypeError(".google.cloud.compute.v1beta.SnapshotAggregatedList.items: object expected"); + message.items = {}; + for (var keys = Object.keys(object.items), i = 0; i < keys.length; ++i) { + if (typeof object.items[keys[i]] !== "object") + throw TypeError(".google.cloud.compute.v1beta.SnapshotAggregatedList.items: object expected"); + message.items[keys[i]] = $root.google.cloud.compute.v1beta.SnapshotsScopedList.fromObject(object.items[keys[i]]); + } + } + if (object.kind != null) + message.kind = String(object.kind); + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + if (object.selfLink != null) + message.selfLink = String(object.selfLink); + if (object.unreachables) { + if (!Array.isArray(object.unreachables)) + throw TypeError(".google.cloud.compute.v1beta.SnapshotAggregatedList.unreachables: array expected"); + message.unreachables = []; + for (var i = 0; i < object.unreachables.length; ++i) + message.unreachables[i] = String(object.unreachables[i]); + } + if (object.warning != null) { + if (typeof object.warning !== "object") + throw TypeError(".google.cloud.compute.v1beta.SnapshotAggregatedList.warning: object expected"); + message.warning = $root.google.cloud.compute.v1beta.Warning.fromObject(object.warning); + } + return message; + }; + + /** + * Creates a plain object from a SnapshotAggregatedList message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {google.cloud.compute.v1beta.SnapshotAggregatedList} message SnapshotAggregatedList + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SnapshotAggregatedList.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.unreachables = []; + if (options.objects || options.defaults) + object.items = {}; + if (message.id != null && message.hasOwnProperty("id")) { + object.id = message.id; + if (options.oneofs) + object._id = "id"; + } + if (message.etag != null && message.hasOwnProperty("etag")) { + object.etag = message.etag; + if (options.oneofs) + object._etag = "etag"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + object.kind = message.kind; + if (options.oneofs) + object._kind = "kind"; + } + if (message.warning != null && message.hasOwnProperty("warning")) { + object.warning = $root.google.cloud.compute.v1beta.Warning.toObject(message.warning, options); + if (options.oneofs) + object._warning = "warning"; + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { + object.nextPageToken = message.nextPageToken; + if (options.oneofs) + object._nextPageToken = "nextPageToken"; + } + var keys2; + if (message.items && (keys2 = Object.keys(message.items)).length) { + object.items = {}; + for (var j = 0; j < keys2.length; ++j) + object.items[keys2[j]] = $root.google.cloud.compute.v1beta.SnapshotsScopedList.toObject(message.items[keys2[j]], options); + } + if (message.unreachables && message.unreachables.length) { + object.unreachables = []; + for (var j = 0; j < message.unreachables.length; ++j) + object.unreachables[j] = message.unreachables[j]; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + object.selfLink = message.selfLink; + if (options.oneofs) + object._selfLink = "selfLink"; + } + return object; + }; + + /** + * Converts this SnapshotAggregatedList to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @instance + * @returns {Object.} JSON object + */ + SnapshotAggregatedList.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SnapshotAggregatedList + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SnapshotAggregatedList.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.SnapshotAggregatedList"; + }; + + return SnapshotAggregatedList; + })(); + + v1beta.SnapshotGroup = (function() { + + /** + * Properties of a SnapshotGroup. + * @memberof google.cloud.compute.v1beta + * @interface ISnapshotGroup + * @property {string|null} [creationTimestamp] SnapshotGroup creationTimestamp + * @property {string|null} [description] SnapshotGroup description + * @property {number|Long|null} [id] SnapshotGroup id + * @property {string|null} [kind] SnapshotGroup kind + * @property {string|null} [name] SnapshotGroup name + * @property {string|null} [selfLink] SnapshotGroup selfLink + * @property {string|null} [selfLinkWithId] SnapshotGroup selfLinkWithId + * @property {google.cloud.compute.v1beta.ISnapshotGroupSourceInfo|null} [sourceInfo] SnapshotGroup sourceInfo + * @property {string|null} [sourceInstantSnapshotGroup] SnapshotGroup sourceInstantSnapshotGroup + * @property {google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo|null} [sourceInstantSnapshotGroupInfo] SnapshotGroup sourceInstantSnapshotGroupInfo + * @property {string|null} [status] SnapshotGroup status + */ + + /** + * Constructs a new SnapshotGroup. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a SnapshotGroup. + * @implements ISnapshotGroup + * @constructor + * @param {google.cloud.compute.v1beta.ISnapshotGroup=} [properties] Properties to set + */ + function SnapshotGroup(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SnapshotGroup creationTimestamp. + * @member {string|null|undefined} creationTimestamp + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.creationTimestamp = null; + + /** + * SnapshotGroup description. + * @member {string|null|undefined} description + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.description = null; + + /** + * SnapshotGroup id. + * @member {number|Long|null|undefined} id + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.id = null; + + /** + * SnapshotGroup kind. + * @member {string|null|undefined} kind + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.kind = null; + + /** + * SnapshotGroup name. + * @member {string|null|undefined} name + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.name = null; + + /** + * SnapshotGroup selfLink. + * @member {string|null|undefined} selfLink + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.selfLink = null; + + /** + * SnapshotGroup selfLinkWithId. + * @member {string|null|undefined} selfLinkWithId + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.selfLinkWithId = null; + + /** + * SnapshotGroup sourceInfo. + * @member {google.cloud.compute.v1beta.ISnapshotGroupSourceInfo|null|undefined} sourceInfo + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.sourceInfo = null; + + /** + * SnapshotGroup sourceInstantSnapshotGroup. + * @member {string|null|undefined} sourceInstantSnapshotGroup + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.sourceInstantSnapshotGroup = null; + + /** + * SnapshotGroup sourceInstantSnapshotGroupInfo. + * @member {google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo|null|undefined} sourceInstantSnapshotGroupInfo + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.sourceInstantSnapshotGroupInfo = null; + + /** + * SnapshotGroup status. + * @member {string|null|undefined} status + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @instance + */ + SnapshotGroup.prototype.status = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_creationTimestamp", { + get: $util.oneOfGetter($oneOfFields = ["creationTimestamp"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_description", { + get: $util.oneOfGetter($oneOfFields = ["description"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_id", { + get: $util.oneOfGetter($oneOfFields = ["id"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_kind", { + get: $util.oneOfGetter($oneOfFields = ["kind"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_name", { + get: $util.oneOfGetter($oneOfFields = ["name"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_selfLink", { + get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_selfLinkWithId", { + get: $util.oneOfGetter($oneOfFields = ["selfLinkWithId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_sourceInfo", { + get: $util.oneOfGetter($oneOfFields = ["sourceInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_sourceInstantSnapshotGroup", { + get: $util.oneOfGetter($oneOfFields = ["sourceInstantSnapshotGroup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_sourceInstantSnapshotGroupInfo", { + get: $util.oneOfGetter($oneOfFields = ["sourceInstantSnapshotGroupInfo"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroup.prototype, "_status", { + get: $util.oneOfGetter($oneOfFields = ["status"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new SnapshotGroup instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroup=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SnapshotGroup} SnapshotGroup instance + */ + SnapshotGroup.create = function create(properties) { + return new SnapshotGroup(properties); + }; + + /** + * Encodes the specified SnapshotGroup message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroup.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroup} message SnapshotGroup message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SnapshotGroup.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.id != null && Object.hasOwnProperty.call(message, "id")) + writer.uint32(/* id 3355, wireType 0 =*/26840).uint64(message.id); + if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) + writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 3373707, wireType 2 =*/26989658).string(message.name); + if (message.creationTimestamp != null && Object.hasOwnProperty.call(message, "creationTimestamp")) + writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); + if (message.selfLinkWithId != null && Object.hasOwnProperty.call(message, "selfLinkWithId")) + writer.uint32(/* id 44520962, wireType 2 =*/356167698).string(message.selfLinkWithId); + if (message.sourceInstantSnapshotGroupInfo != null && Object.hasOwnProperty.call(message, "sourceInstantSnapshotGroupInfo")) + $root.google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.encode(message.sourceInstantSnapshotGroupInfo, writer.uint32(/* id 62296647, wireType 2 =*/498373178).fork()).ldelim(); + if (message.status != null && Object.hasOwnProperty.call(message, "status")) + writer.uint32(/* id 181260274, wireType 2 =*/1450082194).string(message.status); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 422937596, wireType 2 =*/3383500770).string(message.description); + if (message.sourceInfo != null && Object.hasOwnProperty.call(message, "sourceInfo")) + $root.google.cloud.compute.v1beta.SnapshotGroupSourceInfo.encode(message.sourceInfo, writer.uint32(/* id 451907154, wireType 2 =*/3615257234).fork()).ldelim(); + if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) + writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + if (message.sourceInstantSnapshotGroup != null && Object.hasOwnProperty.call(message, "sourceInstantSnapshotGroup")) + writer.uint32(/* id 525991686, wireType 2 =*/4207933490).string(message.sourceInstantSnapshotGroup); + return writer; + }; + + /** + * Encodes the specified SnapshotGroup message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroup.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroup} message SnapshotGroup message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SnapshotGroup.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SnapshotGroup message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.SnapshotGroup} SnapshotGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SnapshotGroup.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.cloud.compute.v1beta.SnapshotGroup(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 30525366: { + message.creationTimestamp = reader.string(); + break; + } + case 422937596: { + message.description = reader.string(); + break; + } + case 3355: { + message.id = reader.uint64(); + break; + } + case 3292052: { + message.kind = reader.string(); + break; + } + case 3373707: { + message.name = reader.string(); + break; + } + case 456214797: { + message.selfLink = reader.string(); + break; + } + case 44520962: { + message.selfLinkWithId = reader.string(); + break; + } + case 451907154: { + message.sourceInfo = $root.google.cloud.compute.v1beta.SnapshotGroupSourceInfo.decode(reader, reader.uint32()); + break; + } + case 525991686: { + message.sourceInstantSnapshotGroup = reader.string(); + break; + } + case 62296647: { + message.sourceInstantSnapshotGroupInfo = $root.google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.decode(reader, reader.uint32()); + break; + } + case 181260274: { + message.status = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SnapshotGroup message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.SnapshotGroup} SnapshotGroup + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SnapshotGroup.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SnapshotGroup message. + * @function verify + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SnapshotGroup.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.creationTimestamp != null && message.hasOwnProperty("creationTimestamp")) { + properties._creationTimestamp = 1; + if (!$util.isString(message.creationTimestamp)) + return "creationTimestamp: string expected"; + } + if (message.description != null && message.hasOwnProperty("description")) { + properties._description = 1; + if (!$util.isString(message.description)) + return "description: string expected"; + } + if (message.id != null && message.hasOwnProperty("id")) { + properties._id = 1; + if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) + return "id: integer|Long expected"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + properties._kind = 1; + if (!$util.isString(message.kind)) + return "kind: string expected"; + } + if (message.name != null && message.hasOwnProperty("name")) { + properties._name = 1; + if (!$util.isString(message.name)) + return "name: string expected"; + } + if (message.selfLink != null && message.hasOwnProperty("selfLink")) { + properties._selfLink = 1; + if (!$util.isString(message.selfLink)) + return "selfLink: string expected"; + } + if (message.selfLinkWithId != null && message.hasOwnProperty("selfLinkWithId")) { + properties._selfLinkWithId = 1; + if (!$util.isString(message.selfLinkWithId)) + return "selfLinkWithId: string expected"; + } + if (message.sourceInfo != null && message.hasOwnProperty("sourceInfo")) { + properties._sourceInfo = 1; + { + var error = $root.google.cloud.compute.v1beta.SnapshotGroupSourceInfo.verify(message.sourceInfo); + if (error) + return "sourceInfo." + error; + } + } + if (message.sourceInstantSnapshotGroup != null && message.hasOwnProperty("sourceInstantSnapshotGroup")) { + properties._sourceInstantSnapshotGroup = 1; + if (!$util.isString(message.sourceInstantSnapshotGroup)) + return "sourceInstantSnapshotGroup: string expected"; + } + if (message.sourceInstantSnapshotGroupInfo != null && message.hasOwnProperty("sourceInstantSnapshotGroupInfo")) { + properties._sourceInstantSnapshotGroupInfo = 1; + { + var error = $root.google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.verify(message.sourceInstantSnapshotGroupInfo); + if (error) + return "sourceInstantSnapshotGroupInfo." + error; + } + } + if (message.status != null && message.hasOwnProperty("status")) { + properties._status = 1; + if (!$util.isString(message.status)) + return "status: string expected"; + } + return null; + }; + + /** + * Creates a SnapshotGroup message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.SnapshotGroup} SnapshotGroup + */ + SnapshotGroup.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SnapshotGroup) + return object; + var message = new $root.google.cloud.compute.v1beta.SnapshotGroup(); + if (object.creationTimestamp != null) + message.creationTimestamp = String(object.creationTimestamp); + if (object.description != null) + message.description = String(object.description); + if (object.id != null) + if ($util.Long) + (message.id = $util.Long.fromValue(object.id)).unsigned = true; + else if (typeof object.id === "string") + message.id = parseInt(object.id, 10); + else if (typeof object.id === "number") + message.id = object.id; + else if (typeof object.id === "object") + message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(true); + if (object.kind != null) + message.kind = String(object.kind); + if (object.name != null) + message.name = String(object.name); + if (object.selfLink != null) + message.selfLink = String(object.selfLink); + if (object.selfLinkWithId != null) + message.selfLinkWithId = String(object.selfLinkWithId); + if (object.sourceInfo != null) { + if (typeof object.sourceInfo !== "object") + throw TypeError(".google.cloud.compute.v1beta.SnapshotGroup.sourceInfo: object expected"); + message.sourceInfo = $root.google.cloud.compute.v1beta.SnapshotGroupSourceInfo.fromObject(object.sourceInfo); + } + if (object.sourceInstantSnapshotGroup != null) + message.sourceInstantSnapshotGroup = String(object.sourceInstantSnapshotGroup); + if (object.sourceInstantSnapshotGroupInfo != null) { + if (typeof object.sourceInstantSnapshotGroupInfo !== "object") + throw TypeError(".google.cloud.compute.v1beta.SnapshotGroup.sourceInstantSnapshotGroupInfo: object expected"); + message.sourceInstantSnapshotGroupInfo = $root.google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.fromObject(object.sourceInstantSnapshotGroupInfo); + } + if (object.status != null) + message.status = String(object.status); + return message; + }; + + /** + * Creates a plain object from a SnapshotGroup message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.SnapshotGroup + * @static + * @param {google.cloud.compute.v1beta.SnapshotGroup} message SnapshotGroup + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SnapshotGroup.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.id != null && message.hasOwnProperty("id")) { + if (typeof message.id === "number") + object.id = options.longs === String ? String(message.id) : message.id; + else + object.id = options.longs === String ? $util.Long.prototype.toString.call(message.id) : options.longs === Number ? new $util.LongBits(message.id.low >>> 0, message.id.high >>> 0).toNumber(true) : message.id; + if (options.oneofs) + object._id = "id"; + } + if (message.kind != null && message.hasOwnProperty("kind")) { + object.kind = message.kind; + if (options.oneofs) + object._kind = "kind"; + } + if (message.name != null && message.hasOwnProperty("name")) { + object.name = message.name; + if (options.oneofs) + object._name = "name"; + } + if (message.creationTimestamp != null && message.hasOwnProperty("creationTimestamp")) { + object.creationTimestamp = message.creationTimestamp; + if (options.oneofs) + object._creationTimestamp = "creationTimestamp"; + } + if (message.selfLinkWithId != null && message.hasOwnProperty("selfLinkWithId")) { + object.selfLinkWithId = message.selfLinkWithId; if (options.oneofs) - object._region = "region"; + object._selfLinkWithId = "selfLinkWithId"; } - if (message.labelFingerprint != null && message.hasOwnProperty("labelFingerprint")) { - object.labelFingerprint = message.labelFingerprint; + if (message.sourceInstantSnapshotGroupInfo != null && message.hasOwnProperty("sourceInstantSnapshotGroupInfo")) { + object.sourceInstantSnapshotGroupInfo = $root.google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.toObject(message.sourceInstantSnapshotGroupInfo, options); if (options.oneofs) - object._labelFingerprint = "labelFingerprint"; + object._sourceInstantSnapshotGroupInfo = "sourceInstantSnapshotGroupInfo"; } if (message.status != null && message.hasOwnProperty("status")) { object.status = message.status; if (options.oneofs) object._status = "status"; } - if (message.sourceInstantSnapshot != null && message.hasOwnProperty("sourceInstantSnapshot")) { - object.sourceInstantSnapshot = message.sourceInstantSnapshot; - if (options.oneofs) - object._sourceInstantSnapshot = "sourceInstantSnapshot"; - } - if (message.sourceSnapshotSchedulePolicy != null && message.hasOwnProperty("sourceSnapshotSchedulePolicy")) { - object.sourceSnapshotSchedulePolicy = message.sourceSnapshotSchedulePolicy; - if (options.oneofs) - object._sourceSnapshotSchedulePolicy = "sourceSnapshotSchedulePolicy"; - } - if (message.sourceInstantSnapshotId != null && message.hasOwnProperty("sourceInstantSnapshotId")) { - object.sourceInstantSnapshotId = message.sourceInstantSnapshotId; - if (options.oneofs) - object._sourceInstantSnapshotId = "sourceInstantSnapshotId"; - } - if (message.architecture != null && message.hasOwnProperty("architecture")) { - object.architecture = message.architecture; - if (options.oneofs) - object._architecture = "architecture"; - } - if (message.diskSizeGb != null && message.hasOwnProperty("diskSizeGb")) { - if (typeof message.diskSizeGb === "number") - object.diskSizeGb = options.longs === String ? String(message.diskSizeGb) : message.diskSizeGb; - else - object.diskSizeGb = options.longs === String ? $util.Long.prototype.toString.call(message.diskSizeGb) : options.longs === Number ? new $util.LongBits(message.diskSizeGb.low >>> 0, message.diskSizeGb.high >>> 0).toNumber() : message.diskSizeGb; - if (options.oneofs) - object._diskSizeGb = "diskSizeGb"; - } - if (message.storageLocations && message.storageLocations.length) { - object.storageLocations = []; - for (var j = 0; j < message.storageLocations.length; ++j) - object.storageLocations[j] = message.storageLocations[j]; - } - if (message.licenses && message.licenses.length) { - object.licenses = []; - for (var j = 0; j < message.licenses.length; ++j) - object.licenses[j] = message.licenses[j]; - } - if (message.locationHint != null && message.hasOwnProperty("locationHint")) { - object.locationHint = message.locationHint; - if (options.oneofs) - object._locationHint = "locationHint"; - } - if (message.sourceDiskForRecoveryCheckpoint != null && message.hasOwnProperty("sourceDiskForRecoveryCheckpoint")) { - object.sourceDiskForRecoveryCheckpoint = message.sourceDiskForRecoveryCheckpoint; - if (options.oneofs) - object._sourceDiskForRecoveryCheckpoint = "sourceDiskForRecoveryCheckpoint"; - } - if (message.guestFlush != null && message.hasOwnProperty("guestFlush")) { - object.guestFlush = message.guestFlush; - if (options.oneofs) - object._guestFlush = "guestFlush"; - } - if (message.userLicenses && message.userLicenses.length) { - object.userLicenses = []; - for (var j = 0; j < message.userLicenses.length; ++j) - object.userLicenses[j] = message.userLicenses[j]; - } if (message.description != null && message.hasOwnProperty("description")) { object.description = message.description; if (options.oneofs) object._description = "description"; } - if (message.storageBytes != null && message.hasOwnProperty("storageBytes")) { - if (typeof message.storageBytes === "number") - object.storageBytes = options.longs === String ? String(message.storageBytes) : message.storageBytes; - else - object.storageBytes = options.longs === String ? $util.Long.prototype.toString.call(message.storageBytes) : options.longs === Number ? new $util.LongBits(message.storageBytes.low >>> 0, message.storageBytes.high >>> 0).toNumber() : message.storageBytes; - if (options.oneofs) - object._storageBytes = "storageBytes"; - } - if (message.downloadBytes != null && message.hasOwnProperty("downloadBytes")) { - if (typeof message.downloadBytes === "number") - object.downloadBytes = options.longs === String ? String(message.downloadBytes) : message.downloadBytes; - else - object.downloadBytes = options.longs === String ? $util.Long.prototype.toString.call(message.downloadBytes) : options.longs === Number ? new $util.LongBits(message.downloadBytes.low >>> 0, message.downloadBytes.high >>> 0).toNumber() : message.downloadBytes; - if (options.oneofs) - object._downloadBytes = "downloadBytes"; - } - if (message.sourceInstantSnapshotEncryptionKey != null && message.hasOwnProperty("sourceInstantSnapshotEncryptionKey")) { - object.sourceInstantSnapshotEncryptionKey = $root.google.cloud.compute.v1beta.CustomerEncryptionKey.toObject(message.sourceInstantSnapshotEncryptionKey, options); + if (message.sourceInfo != null && message.hasOwnProperty("sourceInfo")) { + object.sourceInfo = $root.google.cloud.compute.v1beta.SnapshotGroupSourceInfo.toObject(message.sourceInfo, options); if (options.oneofs) - object._sourceInstantSnapshotEncryptionKey = "sourceInstantSnapshotEncryptionKey"; - } - if (message.sourceDisk != null && message.hasOwnProperty("sourceDisk")) { - object.sourceDisk = message.sourceDisk; - if (options.oneofs) - object._sourceDisk = "sourceDisk"; - } - if (message.sourceDiskId != null && message.hasOwnProperty("sourceDiskId")) { - object.sourceDiskId = message.sourceDiskId; - if (options.oneofs) - object._sourceDiskId = "sourceDiskId"; + object._sourceInfo = "sourceInfo"; } if (message.selfLink != null && message.hasOwnProperty("selfLink")) { object.selfLink = message.selfLink; if (options.oneofs) object._selfLink = "selfLink"; } - if (message.autoCreated != null && message.hasOwnProperty("autoCreated")) { - object.autoCreated = message.autoCreated; - if (options.oneofs) - object._autoCreated = "autoCreated"; - } - if (message.satisfiesPzi != null && message.hasOwnProperty("satisfiesPzi")) { - object.satisfiesPzi = message.satisfiesPzi; - if (options.oneofs) - object._satisfiesPzi = "satisfiesPzi"; - } - if (message.satisfiesPzs != null && message.hasOwnProperty("satisfiesPzs")) { - object.satisfiesPzs = message.satisfiesPzs; - if (options.oneofs) - object._satisfiesPzs = "satisfiesPzs"; - } - if (message.storageBytesStatus != null && message.hasOwnProperty("storageBytesStatus")) { - object.storageBytesStatus = message.storageBytesStatus; - if (options.oneofs) - object._storageBytesStatus = "storageBytesStatus"; - } - var keys2; - if (message.labels && (keys2 = Object.keys(message.labels)).length) { - object.labels = {}; - for (var j = 0; j < keys2.length; ++j) - object.labels[keys2[j]] = message.labels[keys2[j]]; - } - if (message.sourceDiskEncryptionKey != null && message.hasOwnProperty("sourceDiskEncryptionKey")) { - object.sourceDiskEncryptionKey = $root.google.cloud.compute.v1beta.CustomerEncryptionKey.toObject(message.sourceDiskEncryptionKey, options); + if (message.sourceInstantSnapshotGroup != null && message.hasOwnProperty("sourceInstantSnapshotGroup")) { + object.sourceInstantSnapshotGroup = message.sourceInstantSnapshotGroup; if (options.oneofs) - object._sourceDiskEncryptionKey = "sourceDiskEncryptionKey"; + object._sourceInstantSnapshotGroup = "sourceInstantSnapshotGroup"; } return object; }; /** - * Converts this Snapshot to JSON. + * Converts this SnapshotGroup to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.Snapshot + * @memberof google.cloud.compute.v1beta.SnapshotGroup * @instance * @returns {Object.} JSON object */ - Snapshot.prototype.toJSON = function toJSON() { + SnapshotGroup.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Snapshot + * Gets the default type url for SnapshotGroup * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.Snapshot + * @memberof google.cloud.compute.v1beta.SnapshotGroup * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Snapshot.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + SnapshotGroup.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.Snapshot"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.SnapshotGroup"; }; - /** - * Architecture enum. - * @name google.cloud.compute.v1beta.Snapshot.Architecture - * @enum {number} - * @property {number} UNDEFINED_ARCHITECTURE=0 UNDEFINED_ARCHITECTURE value - * @property {number} ARCHITECTURE_UNSPECIFIED=394750507 ARCHITECTURE_UNSPECIFIED value - * @property {number} ARM64=62547450 ARM64 value - * @property {number} X86_64=425300551 X86_64 value - */ - Snapshot.Architecture = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "UNDEFINED_ARCHITECTURE"] = 0; - values[valuesById[394750507] = "ARCHITECTURE_UNSPECIFIED"] = 394750507; - values[valuesById[62547450] = "ARM64"] = 62547450; - values[valuesById[425300551] = "X86_64"] = 425300551; - return values; - })(); - - /** - * SnapshotType enum. - * @name google.cloud.compute.v1beta.Snapshot.SnapshotType - * @enum {number} - * @property {number} UNDEFINED_SNAPSHOT_TYPE=0 UNDEFINED_SNAPSHOT_TYPE value - * @property {number} ARCHIVE=506752162 ARCHIVE value - * @property {number} STANDARD=484642493 STANDARD value - */ - Snapshot.SnapshotType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "UNDEFINED_SNAPSHOT_TYPE"] = 0; - values[valuesById[506752162] = "ARCHIVE"] = 506752162; - values[valuesById[484642493] = "STANDARD"] = 484642493; - return values; - })(); - /** * Status enum. - * @name google.cloud.compute.v1beta.Snapshot.Status + * @name google.cloud.compute.v1beta.SnapshotGroup.Status * @enum {number} * @property {number} UNDEFINED_STATUS=0 UNDEFINED_STATUS value * @property {number} CREATING=455564985 CREATING value * @property {number} DELETING=528602024 DELETING value * @property {number} FAILED=455706685 FAILED value + * @property {number} INVALID=530283991 INVALID value * @property {number} READY=77848963 READY value + * @property {number} UNKNOWN=433141802 UNKNOWN value * @property {number} UPLOADING=267603489 UPLOADING value */ - Snapshot.Status = (function() { + SnapshotGroup.Status = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "UNDEFINED_STATUS"] = 0; values[valuesById[455564985] = "CREATING"] = 455564985; values[valuesById[528602024] = "DELETING"] = 528602024; values[valuesById[455706685] = "FAILED"] = 455706685; + values[valuesById[530283991] = "INVALID"] = 530283991; values[valuesById[77848963] = "READY"] = 77848963; + values[valuesById[433141802] = "UNKNOWN"] = 433141802; values[valuesById[267603489] = "UPLOADING"] = 267603489; return values; })(); - /** - * StorageBytesStatus enum. - * @name google.cloud.compute.v1beta.Snapshot.StorageBytesStatus - * @enum {number} - * @property {number} UNDEFINED_STORAGE_BYTES_STATUS=0 UNDEFINED_STORAGE_BYTES_STATUS value - * @property {number} UPDATING=494614342 UPDATING value - * @property {number} UP_TO_DATE=101306702 UP_TO_DATE value - */ - Snapshot.StorageBytesStatus = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "UNDEFINED_STORAGE_BYTES_STATUS"] = 0; - values[valuesById[494614342] = "UPDATING"] = 494614342; - values[valuesById[101306702] = "UP_TO_DATE"] = 101306702; - return values; - })(); - - return Snapshot; + return SnapshotGroup; })(); - v1beta.SnapshotAggregatedList = (function() { + v1beta.SnapshotGroupParameters = (function() { /** - * Properties of a SnapshotAggregatedList. + * Properties of a SnapshotGroupParameters. * @memberof google.cloud.compute.v1beta - * @interface ISnapshotAggregatedList - * @property {string|null} [etag] SnapshotAggregatedList etag - * @property {string|null} [id] SnapshotAggregatedList id - * @property {Object.|null} [items] SnapshotAggregatedList items - * @property {string|null} [kind] SnapshotAggregatedList kind - * @property {string|null} [nextPageToken] SnapshotAggregatedList nextPageToken - * @property {string|null} [selfLink] SnapshotAggregatedList selfLink - * @property {Array.|null} [unreachables] SnapshotAggregatedList unreachables - * @property {google.cloud.compute.v1beta.IWarning|null} [warning] SnapshotAggregatedList warning + * @interface ISnapshotGroupParameters + * @property {Array.|null} [replicaZones] SnapshotGroupParameters replicaZones + * @property {string|null} [sourceSnapshotGroup] SnapshotGroupParameters sourceSnapshotGroup + * @property {string|null} [type] SnapshotGroupParameters type */ /** - * Constructs a new SnapshotAggregatedList. + * Constructs a new SnapshotGroupParameters. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a SnapshotAggregatedList. - * @implements ISnapshotAggregatedList + * @classdesc Represents a SnapshotGroupParameters. + * @implements ISnapshotGroupParameters * @constructor - * @param {google.cloud.compute.v1beta.ISnapshotAggregatedList=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ISnapshotGroupParameters=} [properties] Properties to set */ - function SnapshotAggregatedList(properties) { - this.items = {}; - this.unreachables = []; + function SnapshotGroupParameters(properties) { + this.replicaZones = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1244175,239 +1263280,646 @@ } /** - * SnapshotAggregatedList etag. - * @member {string|null|undefined} etag - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * SnapshotGroupParameters replicaZones. + * @member {Array.} replicaZones + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters * @instance */ - SnapshotAggregatedList.prototype.etag = null; + SnapshotGroupParameters.prototype.replicaZones = $util.emptyArray; /** - * SnapshotAggregatedList id. - * @member {string|null|undefined} id - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * SnapshotGroupParameters sourceSnapshotGroup. + * @member {string|null|undefined} sourceSnapshotGroup + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters * @instance */ - SnapshotAggregatedList.prototype.id = null; + SnapshotGroupParameters.prototype.sourceSnapshotGroup = null; /** - * SnapshotAggregatedList items. - * @member {Object.} items - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * SnapshotGroupParameters type. + * @member {string|null|undefined} type + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters * @instance */ - SnapshotAggregatedList.prototype.items = $util.emptyObject; + SnapshotGroupParameters.prototype.type = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroupParameters.prototype, "_sourceSnapshotGroup", { + get: $util.oneOfGetter($oneOfFields = ["sourceSnapshotGroup"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(SnapshotGroupParameters.prototype, "_type", { + get: $util.oneOfGetter($oneOfFields = ["type"]), + set: $util.oneOfSetter($oneOfFields) + }); /** - * SnapshotAggregatedList kind. - * @member {string|null|undefined} kind - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList - * @instance + * Creates a new SnapshotGroupParameters instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroupParameters=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SnapshotGroupParameters} SnapshotGroupParameters instance */ - SnapshotAggregatedList.prototype.kind = null; + SnapshotGroupParameters.create = function create(properties) { + return new SnapshotGroupParameters(properties); + }; /** - * SnapshotAggregatedList nextPageToken. - * @member {string|null|undefined} nextPageToken - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList - * @instance + * Encodes the specified SnapshotGroupParameters message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupParameters.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroupParameters} message SnapshotGroupParameters message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer */ - SnapshotAggregatedList.prototype.nextPageToken = null; + SnapshotGroupParameters.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 3575610, wireType 2 =*/28604882).string(message.type); + if (message.replicaZones != null && message.replicaZones.length) + for (var i = 0; i < message.replicaZones.length; ++i) + writer.uint32(/* id 48438272, wireType 2 =*/387506178).string(message.replicaZones[i]); + if (message.sourceSnapshotGroup != null && Object.hasOwnProperty.call(message, "sourceSnapshotGroup")) + writer.uint32(/* id 225130728, wireType 2 =*/1801045826).string(message.sourceSnapshotGroup); + return writer; + }; /** - * SnapshotAggregatedList selfLink. - * @member {string|null|undefined} selfLink - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * Encodes the specified SnapshotGroupParameters message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupParameters.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroupParameters} message SnapshotGroupParameters message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SnapshotGroupParameters.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SnapshotGroupParameters message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.SnapshotGroupParameters} SnapshotGroupParameters + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SnapshotGroupParameters.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.cloud.compute.v1beta.SnapshotGroupParameters(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 48438272: { + if (!(message.replicaZones && message.replicaZones.length)) + message.replicaZones = []; + message.replicaZones.push(reader.string()); + break; + } + case 225130728: { + message.sourceSnapshotGroup = reader.string(); + break; + } + case 3575610: { + message.type = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SnapshotGroupParameters message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.SnapshotGroupParameters} SnapshotGroupParameters + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SnapshotGroupParameters.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SnapshotGroupParameters message. + * @function verify + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SnapshotGroupParameters.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.replicaZones != null && message.hasOwnProperty("replicaZones")) { + if (!Array.isArray(message.replicaZones)) + return "replicaZones: array expected"; + for (var i = 0; i < message.replicaZones.length; ++i) + if (!$util.isString(message.replicaZones[i])) + return "replicaZones: string[] expected"; + } + if (message.sourceSnapshotGroup != null && message.hasOwnProperty("sourceSnapshotGroup")) { + properties._sourceSnapshotGroup = 1; + if (!$util.isString(message.sourceSnapshotGroup)) + return "sourceSnapshotGroup: string expected"; + } + if (message.type != null && message.hasOwnProperty("type")) { + properties._type = 1; + if (!$util.isString(message.type)) + return "type: string expected"; + } + return null; + }; + + /** + * Creates a SnapshotGroupParameters message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.SnapshotGroupParameters} SnapshotGroupParameters + */ + SnapshotGroupParameters.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SnapshotGroupParameters) + return object; + var message = new $root.google.cloud.compute.v1beta.SnapshotGroupParameters(); + if (object.replicaZones) { + if (!Array.isArray(object.replicaZones)) + throw TypeError(".google.cloud.compute.v1beta.SnapshotGroupParameters.replicaZones: array expected"); + message.replicaZones = []; + for (var i = 0; i < object.replicaZones.length; ++i) + message.replicaZones[i] = String(object.replicaZones[i]); + } + if (object.sourceSnapshotGroup != null) + message.sourceSnapshotGroup = String(object.sourceSnapshotGroup); + if (object.type != null) + message.type = String(object.type); + return message; + }; + + /** + * Creates a plain object from a SnapshotGroupParameters message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {google.cloud.compute.v1beta.SnapshotGroupParameters} message SnapshotGroupParameters + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SnapshotGroupParameters.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.replicaZones = []; + if (message.type != null && message.hasOwnProperty("type")) { + object.type = message.type; + if (options.oneofs) + object._type = "type"; + } + if (message.replicaZones && message.replicaZones.length) { + object.replicaZones = []; + for (var j = 0; j < message.replicaZones.length; ++j) + object.replicaZones[j] = message.replicaZones[j]; + } + if (message.sourceSnapshotGroup != null && message.hasOwnProperty("sourceSnapshotGroup")) { + object.sourceSnapshotGroup = message.sourceSnapshotGroup; + if (options.oneofs) + object._sourceSnapshotGroup = "sourceSnapshotGroup"; + } + return object; + }; + + /** + * Converts this SnapshotGroupParameters to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters * @instance + * @returns {Object.} JSON object */ - SnapshotAggregatedList.prototype.selfLink = null; + SnapshotGroupParameters.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; /** - * SnapshotAggregatedList unreachables. - * @member {Array.} unreachables - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * Gets the default type url for SnapshotGroupParameters + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.SnapshotGroupParameters + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SnapshotGroupParameters.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.SnapshotGroupParameters"; + }; + + return SnapshotGroupParameters; + })(); + + v1beta.SnapshotGroupSourceInfo = (function() { + + /** + * Properties of a SnapshotGroupSourceInfo. + * @memberof google.cloud.compute.v1beta + * @interface ISnapshotGroupSourceInfo + * @property {string|null} [consistencyGroup] SnapshotGroupSourceInfo consistencyGroup + * @property {string|null} [consistencyGroupId] SnapshotGroupSourceInfo consistencyGroupId + */ + + /** + * Constructs a new SnapshotGroupSourceInfo. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a SnapshotGroupSourceInfo. + * @implements ISnapshotGroupSourceInfo + * @constructor + * @param {google.cloud.compute.v1beta.ISnapshotGroupSourceInfo=} [properties] Properties to set + */ + function SnapshotGroupSourceInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SnapshotGroupSourceInfo consistencyGroup. + * @member {string|null|undefined} consistencyGroup + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo * @instance */ - SnapshotAggregatedList.prototype.unreachables = $util.emptyArray; + SnapshotGroupSourceInfo.prototype.consistencyGroup = null; /** - * SnapshotAggregatedList warning. - * @member {google.cloud.compute.v1beta.IWarning|null|undefined} warning - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * SnapshotGroupSourceInfo consistencyGroupId. + * @member {string|null|undefined} consistencyGroupId + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo * @instance */ - SnapshotAggregatedList.prototype.warning = null; + SnapshotGroupSourceInfo.prototype.consistencyGroupId = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(SnapshotAggregatedList.prototype, "_etag", { - get: $util.oneOfGetter($oneOfFields = ["etag"]), + Object.defineProperty(SnapshotGroupSourceInfo.prototype, "_consistencyGroup", { + get: $util.oneOfGetter($oneOfFields = ["consistencyGroup"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(SnapshotAggregatedList.prototype, "_id", { - get: $util.oneOfGetter($oneOfFields = ["id"]), + Object.defineProperty(SnapshotGroupSourceInfo.prototype, "_consistencyGroupId", { + get: $util.oneOfGetter($oneOfFields = ["consistencyGroupId"]), set: $util.oneOfSetter($oneOfFields) }); - // Virtual OneOf for proto3 optional field - Object.defineProperty(SnapshotAggregatedList.prototype, "_kind", { - get: $util.oneOfGetter($oneOfFields = ["kind"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Creates a new SnapshotGroupSourceInfo instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroupSourceInfo=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SnapshotGroupSourceInfo} SnapshotGroupSourceInfo instance + */ + SnapshotGroupSourceInfo.create = function create(properties) { + return new SnapshotGroupSourceInfo(properties); + }; - // Virtual OneOf for proto3 optional field - Object.defineProperty(SnapshotAggregatedList.prototype, "_nextPageToken", { - get: $util.oneOfGetter($oneOfFields = ["nextPageToken"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Encodes the specified SnapshotGroupSourceInfo message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupSourceInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroupSourceInfo} message SnapshotGroupSourceInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SnapshotGroupSourceInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.consistencyGroupId != null && Object.hasOwnProperty.call(message, "consistencyGroupId")) + writer.uint32(/* id 85599522, wireType 2 =*/684796178).string(message.consistencyGroupId); + if (message.consistencyGroup != null && Object.hasOwnProperty.call(message, "consistencyGroup")) + writer.uint32(/* id 508183960, wireType 2 =*/4065471682).string(message.consistencyGroup); + return writer; + }; + + /** + * Encodes the specified SnapshotGroupSourceInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupSourceInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {google.cloud.compute.v1beta.ISnapshotGroupSourceInfo} message SnapshotGroupSourceInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SnapshotGroupSourceInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SnapshotGroupSourceInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.SnapshotGroupSourceInfo} SnapshotGroupSourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SnapshotGroupSourceInfo.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.cloud.compute.v1beta.SnapshotGroupSourceInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 508183960: { + message.consistencyGroup = reader.string(); + break; + } + case 85599522: { + message.consistencyGroupId = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SnapshotGroupSourceInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.SnapshotGroupSourceInfo} SnapshotGroupSourceInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SnapshotGroupSourceInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SnapshotGroupSourceInfo message. + * @function verify + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SnapshotGroupSourceInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.consistencyGroup != null && message.hasOwnProperty("consistencyGroup")) { + properties._consistencyGroup = 1; + if (!$util.isString(message.consistencyGroup)) + return "consistencyGroup: string expected"; + } + if (message.consistencyGroupId != null && message.hasOwnProperty("consistencyGroupId")) { + properties._consistencyGroupId = 1; + if (!$util.isString(message.consistencyGroupId)) + return "consistencyGroupId: string expected"; + } + return null; + }; + + /** + * Creates a SnapshotGroupSourceInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.SnapshotGroupSourceInfo} SnapshotGroupSourceInfo + */ + SnapshotGroupSourceInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SnapshotGroupSourceInfo) + return object; + var message = new $root.google.cloud.compute.v1beta.SnapshotGroupSourceInfo(); + if (object.consistencyGroup != null) + message.consistencyGroup = String(object.consistencyGroup); + if (object.consistencyGroupId != null) + message.consistencyGroupId = String(object.consistencyGroupId); + return message; + }; + + /** + * Creates a plain object from a SnapshotGroupSourceInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {google.cloud.compute.v1beta.SnapshotGroupSourceInfo} message SnapshotGroupSourceInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SnapshotGroupSourceInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.consistencyGroupId != null && message.hasOwnProperty("consistencyGroupId")) { + object.consistencyGroupId = message.consistencyGroupId; + if (options.oneofs) + object._consistencyGroupId = "consistencyGroupId"; + } + if (message.consistencyGroup != null && message.hasOwnProperty("consistencyGroup")) { + object.consistencyGroup = message.consistencyGroup; + if (options.oneofs) + object._consistencyGroup = "consistencyGroup"; + } + return object; + }; + + /** + * Converts this SnapshotGroupSourceInfo to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @instance + * @returns {Object.} JSON object + */ + SnapshotGroupSourceInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SnapshotGroupSourceInfo + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SnapshotGroupSourceInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.SnapshotGroupSourceInfo"; + }; + + return SnapshotGroupSourceInfo; + })(); + + v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo = (function() { + + /** + * Properties of a SnapshotGroupSourceInstantSnapshotGroupInfo. + * @memberof google.cloud.compute.v1beta + * @interface ISnapshotGroupSourceInstantSnapshotGroupInfo + * @property {string|null} [instantSnapshotGroup] SnapshotGroupSourceInstantSnapshotGroupInfo instantSnapshotGroup + * @property {string|null} [instantSnapshotGroupId] SnapshotGroupSourceInstantSnapshotGroupInfo instantSnapshotGroupId + */ + + /** + * Constructs a new SnapshotGroupSourceInstantSnapshotGroupInfo. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a SnapshotGroupSourceInstantSnapshotGroupInfo. + * @implements ISnapshotGroupSourceInstantSnapshotGroupInfo + * @constructor + * @param {google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo=} [properties] Properties to set + */ + function SnapshotGroupSourceInstantSnapshotGroupInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SnapshotGroupSourceInstantSnapshotGroupInfo instantSnapshotGroup. + * @member {string|null|undefined} instantSnapshotGroup + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo + * @instance + */ + SnapshotGroupSourceInstantSnapshotGroupInfo.prototype.instantSnapshotGroup = null; + + /** + * SnapshotGroupSourceInstantSnapshotGroupInfo instantSnapshotGroupId. + * @member {string|null|undefined} instantSnapshotGroupId + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo + * @instance + */ + SnapshotGroupSourceInstantSnapshotGroupInfo.prototype.instantSnapshotGroupId = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; // Virtual OneOf for proto3 optional field - Object.defineProperty(SnapshotAggregatedList.prototype, "_selfLink", { - get: $util.oneOfGetter($oneOfFields = ["selfLink"]), + Object.defineProperty(SnapshotGroupSourceInstantSnapshotGroupInfo.prototype, "_instantSnapshotGroup", { + get: $util.oneOfGetter($oneOfFields = ["instantSnapshotGroup"]), set: $util.oneOfSetter($oneOfFields) }); // Virtual OneOf for proto3 optional field - Object.defineProperty(SnapshotAggregatedList.prototype, "_warning", { - get: $util.oneOfGetter($oneOfFields = ["warning"]), + Object.defineProperty(SnapshotGroupSourceInstantSnapshotGroupInfo.prototype, "_instantSnapshotGroupId", { + get: $util.oneOfGetter($oneOfFields = ["instantSnapshotGroupId"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a new SnapshotAggregatedList instance using the specified properties. + * Creates a new SnapshotGroupSourceInstantSnapshotGroupInfo instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static - * @param {google.cloud.compute.v1beta.ISnapshotAggregatedList=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.SnapshotAggregatedList} SnapshotAggregatedList instance + * @param {google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo} SnapshotGroupSourceInstantSnapshotGroupInfo instance */ - SnapshotAggregatedList.create = function create(properties) { - return new SnapshotAggregatedList(properties); + SnapshotGroupSourceInstantSnapshotGroupInfo.create = function create(properties) { + return new SnapshotGroupSourceInstantSnapshotGroupInfo(properties); }; /** - * Encodes the specified SnapshotAggregatedList message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotAggregatedList.verify|verify} messages. + * Encodes the specified SnapshotGroupSourceInstantSnapshotGroupInfo message. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static - * @param {google.cloud.compute.v1beta.ISnapshotAggregatedList} message SnapshotAggregatedList message or plain object to encode + * @param {google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo} message SnapshotGroupSourceInstantSnapshotGroupInfo message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SnapshotAggregatedList.encode = function encode(message, writer) { + SnapshotGroupSourceInstantSnapshotGroupInfo.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 3355, wireType 2 =*/26842).string(message.id); - if (message.etag != null && Object.hasOwnProperty.call(message, "etag")) - writer.uint32(/* id 3123477, wireType 2 =*/24987818).string(message.etag); - if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) - writer.uint32(/* id 3292052, wireType 2 =*/26336418).string(message.kind); - if (message.warning != null && Object.hasOwnProperty.call(message, "warning")) - $root.google.cloud.compute.v1beta.Warning.encode(message.warning, writer.uint32(/* id 50704284, wireType 2 =*/405634274).fork()).ldelim(); - if (message.nextPageToken != null && Object.hasOwnProperty.call(message, "nextPageToken")) - writer.uint32(/* id 79797525, wireType 2 =*/638380202).string(message.nextPageToken); - if (message.items != null && Object.hasOwnProperty.call(message, "items")) - for (var keys = Object.keys(message.items), i = 0; i < keys.length; ++i) { - writer.uint32(/* id 100526016, wireType 2 =*/804208130).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); - $root.google.cloud.compute.v1beta.SnapshotsScopedList.encode(message.items[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); - } - if (message.unreachables != null && message.unreachables.length) - for (var i = 0; i < message.unreachables.length; ++i) - writer.uint32(/* id 243372063, wireType 2 =*/1946976506).string(message.unreachables[i]); - if (message.selfLink != null && Object.hasOwnProperty.call(message, "selfLink")) - writer.uint32(/* id 456214797, wireType 2 =*/3649718378).string(message.selfLink); + if (message.instantSnapshotGroupId != null && Object.hasOwnProperty.call(message, "instantSnapshotGroupId")) + writer.uint32(/* id 157599768, wireType 2 =*/1260798146).string(message.instantSnapshotGroupId); + if (message.instantSnapshotGroup != null && Object.hasOwnProperty.call(message, "instantSnapshotGroup")) + writer.uint32(/* id 223180386, wireType 2 =*/1785443090).string(message.instantSnapshotGroup); return writer; }; /** - * Encodes the specified SnapshotAggregatedList message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotAggregatedList.verify|verify} messages. + * Encodes the specified SnapshotGroupSourceInstantSnapshotGroupInfo message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static - * @param {google.cloud.compute.v1beta.ISnapshotAggregatedList} message SnapshotAggregatedList message or plain object to encode + * @param {google.cloud.compute.v1beta.ISnapshotGroupSourceInstantSnapshotGroupInfo} message SnapshotGroupSourceInstantSnapshotGroupInfo message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SnapshotAggregatedList.encodeDelimited = function encodeDelimited(message, writer) { + SnapshotGroupSourceInstantSnapshotGroupInfo.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a SnapshotAggregatedList message from the specified reader or buffer. + * Decodes a SnapshotGroupSourceInstantSnapshotGroupInfo message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.SnapshotAggregatedList} SnapshotAggregatedList + * @returns {google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo} SnapshotGroupSourceInstantSnapshotGroupInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SnapshotAggregatedList.decode = function decode(reader, length, error) { + SnapshotGroupSourceInstantSnapshotGroupInfo.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.cloud.compute.v1beta.SnapshotAggregatedList(), key, value; + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) break; switch (tag >>> 3) { - case 3123477: { - message.etag = reader.string(); - break; - } - case 3355: { - message.id = reader.string(); - break; - } - case 100526016: { - if (message.items === $util.emptyObject) - message.items = {}; - var end2 = reader.uint32() + reader.pos; - key = ""; - value = null; - while (reader.pos < end2) { - var tag2 = reader.uint32(); - switch (tag2 >>> 3) { - case 1: - key = reader.string(); - break; - case 2: - value = $root.google.cloud.compute.v1beta.SnapshotsScopedList.decode(reader, reader.uint32()); - break; - default: - reader.skipType(tag2 & 7); - break; - } - } - message.items[key] = value; - break; - } - case 3292052: { - message.kind = reader.string(); - break; - } - case 79797525: { - message.nextPageToken = reader.string(); - break; - } - case 456214797: { - message.selfLink = reader.string(); + case 223180386: { + message.instantSnapshotGroup = reader.string(); break; } - case 243372063: { - if (!(message.unreachables && message.unreachables.length)) - message.unreachables = []; - message.unreachables.push(reader.string()); - break; - } - case 50704284: { - message.warning = $root.google.cloud.compute.v1beta.Warning.decode(reader, reader.uint32()); + case 157599768: { + message.instantSnapshotGroupId = reader.string(); break; } default: @@ -1244419,221 +1263931,118 @@ }; /** - * Decodes a SnapshotAggregatedList message from the specified reader or buffer, length delimited. + * Decodes a SnapshotGroupSourceInstantSnapshotGroupInfo message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.SnapshotAggregatedList} SnapshotAggregatedList + * @returns {google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo} SnapshotGroupSourceInstantSnapshotGroupInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SnapshotAggregatedList.decodeDelimited = function decodeDelimited(reader) { + SnapshotGroupSourceInstantSnapshotGroupInfo.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a SnapshotAggregatedList message. + * Verifies a SnapshotGroupSourceInstantSnapshotGroupInfo message. * @function verify - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - SnapshotAggregatedList.verify = function verify(message) { + SnapshotGroupSourceInstantSnapshotGroupInfo.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; var properties = {}; - if (message.etag != null && message.hasOwnProperty("etag")) { - properties._etag = 1; - if (!$util.isString(message.etag)) - return "etag: string expected"; - } - if (message.id != null && message.hasOwnProperty("id")) { - properties._id = 1; - if (!$util.isString(message.id)) - return "id: string expected"; - } - if (message.items != null && message.hasOwnProperty("items")) { - if (!$util.isObject(message.items)) - return "items: object expected"; - var key = Object.keys(message.items); - for (var i = 0; i < key.length; ++i) { - var error = $root.google.cloud.compute.v1beta.SnapshotsScopedList.verify(message.items[key[i]]); - if (error) - return "items." + error; - } - } - if (message.kind != null && message.hasOwnProperty("kind")) { - properties._kind = 1; - if (!$util.isString(message.kind)) - return "kind: string expected"; - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { - properties._nextPageToken = 1; - if (!$util.isString(message.nextPageToken)) - return "nextPageToken: string expected"; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) { + properties._instantSnapshotGroup = 1; + if (!$util.isString(message.instantSnapshotGroup)) + return "instantSnapshotGroup: string expected"; } - if (message.selfLink != null && message.hasOwnProperty("selfLink")) { - properties._selfLink = 1; - if (!$util.isString(message.selfLink)) - return "selfLink: string expected"; - } - if (message.unreachables != null && message.hasOwnProperty("unreachables")) { - if (!Array.isArray(message.unreachables)) - return "unreachables: array expected"; - for (var i = 0; i < message.unreachables.length; ++i) - if (!$util.isString(message.unreachables[i])) - return "unreachables: string[] expected"; - } - if (message.warning != null && message.hasOwnProperty("warning")) { - properties._warning = 1; - { - var error = $root.google.cloud.compute.v1beta.Warning.verify(message.warning); - if (error) - return "warning." + error; - } + if (message.instantSnapshotGroupId != null && message.hasOwnProperty("instantSnapshotGroupId")) { + properties._instantSnapshotGroupId = 1; + if (!$util.isString(message.instantSnapshotGroupId)) + return "instantSnapshotGroupId: string expected"; } return null; }; /** - * Creates a SnapshotAggregatedList message from a plain object. Also converts values to their respective internal types. + * Creates a SnapshotGroupSourceInstantSnapshotGroupInfo message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.SnapshotAggregatedList} SnapshotAggregatedList + * @returns {google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo} SnapshotGroupSourceInstantSnapshotGroupInfo */ - SnapshotAggregatedList.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.SnapshotAggregatedList) + SnapshotGroupSourceInstantSnapshotGroupInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo) return object; - var message = new $root.google.cloud.compute.v1beta.SnapshotAggregatedList(); - if (object.etag != null) - message.etag = String(object.etag); - if (object.id != null) - message.id = String(object.id); - if (object.items) { - if (typeof object.items !== "object") - throw TypeError(".google.cloud.compute.v1beta.SnapshotAggregatedList.items: object expected"); - message.items = {}; - for (var keys = Object.keys(object.items), i = 0; i < keys.length; ++i) { - if (typeof object.items[keys[i]] !== "object") - throw TypeError(".google.cloud.compute.v1beta.SnapshotAggregatedList.items: object expected"); - message.items[keys[i]] = $root.google.cloud.compute.v1beta.SnapshotsScopedList.fromObject(object.items[keys[i]]); - } - } - if (object.kind != null) - message.kind = String(object.kind); - if (object.nextPageToken != null) - message.nextPageToken = String(object.nextPageToken); - if (object.selfLink != null) - message.selfLink = String(object.selfLink); - if (object.unreachables) { - if (!Array.isArray(object.unreachables)) - throw TypeError(".google.cloud.compute.v1beta.SnapshotAggregatedList.unreachables: array expected"); - message.unreachables = []; - for (var i = 0; i < object.unreachables.length; ++i) - message.unreachables[i] = String(object.unreachables[i]); - } - if (object.warning != null) { - if (typeof object.warning !== "object") - throw TypeError(".google.cloud.compute.v1beta.SnapshotAggregatedList.warning: object expected"); - message.warning = $root.google.cloud.compute.v1beta.Warning.fromObject(object.warning); - } + var message = new $root.google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo(); + if (object.instantSnapshotGroup != null) + message.instantSnapshotGroup = String(object.instantSnapshotGroup); + if (object.instantSnapshotGroupId != null) + message.instantSnapshotGroupId = String(object.instantSnapshotGroupId); return message; }; /** - * Creates a plain object from a SnapshotAggregatedList message. Also converts values to other types if specified. + * Creates a plain object from a SnapshotGroupSourceInstantSnapshotGroupInfo message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static - * @param {google.cloud.compute.v1beta.SnapshotAggregatedList} message SnapshotAggregatedList + * @param {google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo} message SnapshotGroupSourceInstantSnapshotGroupInfo * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - SnapshotAggregatedList.toObject = function toObject(message, options) { + SnapshotGroupSourceInstantSnapshotGroupInfo.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.unreachables = []; - if (options.objects || options.defaults) - object.items = {}; - if (message.id != null && message.hasOwnProperty("id")) { - object.id = message.id; - if (options.oneofs) - object._id = "id"; - } - if (message.etag != null && message.hasOwnProperty("etag")) { - object.etag = message.etag; - if (options.oneofs) - object._etag = "etag"; - } - if (message.kind != null && message.hasOwnProperty("kind")) { - object.kind = message.kind; - if (options.oneofs) - object._kind = "kind"; - } - if (message.warning != null && message.hasOwnProperty("warning")) { - object.warning = $root.google.cloud.compute.v1beta.Warning.toObject(message.warning, options); - if (options.oneofs) - object._warning = "warning"; - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) { - object.nextPageToken = message.nextPageToken; + if (message.instantSnapshotGroupId != null && message.hasOwnProperty("instantSnapshotGroupId")) { + object.instantSnapshotGroupId = message.instantSnapshotGroupId; if (options.oneofs) - object._nextPageToken = "nextPageToken"; + object._instantSnapshotGroupId = "instantSnapshotGroupId"; } - var keys2; - if (message.items && (keys2 = Object.keys(message.items)).length) { - object.items = {}; - for (var j = 0; j < keys2.length; ++j) - object.items[keys2[j]] = $root.google.cloud.compute.v1beta.SnapshotsScopedList.toObject(message.items[keys2[j]], options); - } - if (message.unreachables && message.unreachables.length) { - object.unreachables = []; - for (var j = 0; j < message.unreachables.length; ++j) - object.unreachables[j] = message.unreachables[j]; - } - if (message.selfLink != null && message.hasOwnProperty("selfLink")) { - object.selfLink = message.selfLink; + if (message.instantSnapshotGroup != null && message.hasOwnProperty("instantSnapshotGroup")) { + object.instantSnapshotGroup = message.instantSnapshotGroup; if (options.oneofs) - object._selfLink = "selfLink"; + object._instantSnapshotGroup = "instantSnapshotGroup"; } return object; }; /** - * Converts this SnapshotAggregatedList to JSON. + * Converts this SnapshotGroupSourceInstantSnapshotGroupInfo to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @instance * @returns {Object.} JSON object */ - SnapshotAggregatedList.prototype.toJSON = function toJSON() { + SnapshotGroupSourceInstantSnapshotGroupInfo.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for SnapshotAggregatedList + * Gets the default type url for SnapshotGroupSourceInstantSnapshotGroupInfo * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.SnapshotAggregatedList + * @memberof google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - SnapshotAggregatedList.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + SnapshotGroupSourceInstantSnapshotGroupInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.SnapshotAggregatedList"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.SnapshotGroupSourceInstantSnapshotGroupInfo"; }; - return SnapshotAggregatedList; + return SnapshotGroupSourceInstantSnapshotGroupInfo; })(); v1beta.SnapshotList = (function() { @@ -1286795,6 +1306204,7 @@ * @property {Object.|null} [labels] TargetVpnGateway labels * @property {string|null} [name] TargetVpnGateway name * @property {string|null} [network] TargetVpnGateway network + * @property {google.cloud.compute.v1beta.ITargetVpnGatewayParams|null} [params] TargetVpnGateway params * @property {string|null} [region] TargetVpnGateway region * @property {string|null} [selfLink] TargetVpnGateway selfLink * @property {string|null} [status] TargetVpnGateway status @@ -1286891,6 +1306301,14 @@ */ TargetVpnGateway.prototype.network = null; + /** + * TargetVpnGateway params. + * @member {google.cloud.compute.v1beta.ITargetVpnGatewayParams|null|undefined} params + * @memberof google.cloud.compute.v1beta.TargetVpnGateway + * @instance + */ + TargetVpnGateway.prototype.params = null; + /** * TargetVpnGateway region. * @member {string|null|undefined} region @@ -1286968,6 +1306386,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(TargetVpnGateway.prototype, "_params", { + get: $util.oneOfGetter($oneOfFields = ["params"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(TargetVpnGateway.prototype, "_region", { get: $util.oneOfGetter($oneOfFields = ["region"]), @@ -1287018,6 +1306442,8 @@ writer.uint32(/* id 3373707, wireType 2 =*/26989658).string(message.name); if (message.creationTimestamp != null && Object.hasOwnProperty.call(message, "creationTimestamp")) writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.cloud.compute.v1beta.TargetVpnGatewayParams.encode(message.params, writer.uint32(/* id 78313862, wireType 2 =*/626510898).fork()).ldelim(); if (message.tunnels != null && message.tunnels.length) for (var i = 0; i < message.tunnels.length; ++i) writer.uint32(/* id 104561931, wireType 2 =*/836495450).string(message.tunnels[i]); @@ -1287132,6 +1306558,10 @@ message.network = reader.string(); break; } + case 78313862: { + message.params = $root.google.cloud.compute.v1beta.TargetVpnGatewayParams.decode(reader, reader.uint32()); + break; + } case 138946292: { message.region = reader.string(); break; @@ -1287236,6 +1306666,14 @@ if (!$util.isString(message.network)) return "network: string expected"; } + if (message.params != null && message.hasOwnProperty("params")) { + properties._params = 1; + { + var error = $root.google.cloud.compute.v1beta.TargetVpnGatewayParams.verify(message.params); + if (error) + return "params." + error; + } + } if (message.region != null && message.hasOwnProperty("region")) { properties._region = 1; if (!$util.isString(message.region)) @@ -1287308,6 +1306746,11 @@ message.name = String(object.name); if (object.network != null) message.network = String(object.network); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.cloud.compute.v1beta.TargetVpnGateway.params: object expected"); + message.params = $root.google.cloud.compute.v1beta.TargetVpnGatewayParams.fromObject(object.params); + } if (object.region != null) message.region = String(object.region); if (object.selfLink != null) @@ -1287366,6 +1306809,11 @@ if (options.oneofs) object._creationTimestamp = "creationTimestamp"; } + if (message.params != null && message.hasOwnProperty("params")) { + object.params = $root.google.cloud.compute.v1beta.TargetVpnGatewayParams.toObject(message.params, options); + if (options.oneofs) + object._params = "params"; + } if (message.tunnels && message.tunnels.length) { object.tunnels = []; for (var j = 0; j < message.tunnels.length; ++j) @@ -1288327,6 +1307775,246 @@ return TargetVpnGatewayList; })(); + v1beta.TargetVpnGatewayParams = (function() { + + /** + * Properties of a TargetVpnGatewayParams. + * @memberof google.cloud.compute.v1beta + * @interface ITargetVpnGatewayParams + * @property {Object.|null} [resourceManagerTags] TargetVpnGatewayParams resourceManagerTags + */ + + /** + * Constructs a new TargetVpnGatewayParams. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a TargetVpnGatewayParams. + * @implements ITargetVpnGatewayParams + * @constructor + * @param {google.cloud.compute.v1beta.ITargetVpnGatewayParams=} [properties] Properties to set + */ + function TargetVpnGatewayParams(properties) { + this.resourceManagerTags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TargetVpnGatewayParams resourceManagerTags. + * @member {Object.} resourceManagerTags + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @instance + */ + TargetVpnGatewayParams.prototype.resourceManagerTags = $util.emptyObject; + + /** + * Creates a new TargetVpnGatewayParams instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.ITargetVpnGatewayParams=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TargetVpnGatewayParams} TargetVpnGatewayParams instance + */ + TargetVpnGatewayParams.create = function create(properties) { + return new TargetVpnGatewayParams(properties); + }; + + /** + * Encodes the specified TargetVpnGatewayParams message. Does not implicitly {@link google.cloud.compute.v1beta.TargetVpnGatewayParams.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.ITargetVpnGatewayParams} message TargetVpnGatewayParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TargetVpnGatewayParams.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceManagerTags != null && Object.hasOwnProperty.call(message, "resourceManagerTags")) + for (var keys = Object.keys(message.resourceManagerTags), i = 0; i < keys.length; ++i) + writer.uint32(/* id 377671164, wireType 2 =*/3021369314).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourceManagerTags[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified TargetVpnGatewayParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TargetVpnGatewayParams.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.ITargetVpnGatewayParams} message TargetVpnGatewayParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TargetVpnGatewayParams.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TargetVpnGatewayParams message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.TargetVpnGatewayParams} TargetVpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TargetVpnGatewayParams.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.cloud.compute.v1beta.TargetVpnGatewayParams(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 377671164: { + if (message.resourceManagerTags === $util.emptyObject) + message.resourceManagerTags = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.resourceManagerTags[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TargetVpnGatewayParams message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.TargetVpnGatewayParams} TargetVpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TargetVpnGatewayParams.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TargetVpnGatewayParams message. + * @function verify + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TargetVpnGatewayParams.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceManagerTags != null && message.hasOwnProperty("resourceManagerTags")) { + if (!$util.isObject(message.resourceManagerTags)) + return "resourceManagerTags: object expected"; + var key = Object.keys(message.resourceManagerTags); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.resourceManagerTags[key[i]])) + return "resourceManagerTags: string{k:string} expected"; + } + return null; + }; + + /** + * Creates a TargetVpnGatewayParams message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.TargetVpnGatewayParams} TargetVpnGatewayParams + */ + TargetVpnGatewayParams.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TargetVpnGatewayParams) + return object; + var message = new $root.google.cloud.compute.v1beta.TargetVpnGatewayParams(); + if (object.resourceManagerTags) { + if (typeof object.resourceManagerTags !== "object") + throw TypeError(".google.cloud.compute.v1beta.TargetVpnGatewayParams.resourceManagerTags: object expected"); + message.resourceManagerTags = {}; + for (var keys = Object.keys(object.resourceManagerTags), i = 0; i < keys.length; ++i) + message.resourceManagerTags[keys[i]] = String(object.resourceManagerTags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a TargetVpnGatewayParams message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.TargetVpnGatewayParams} message TargetVpnGatewayParams + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TargetVpnGatewayParams.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.resourceManagerTags = {}; + var keys2; + if (message.resourceManagerTags && (keys2 = Object.keys(message.resourceManagerTags)).length) { + object.resourceManagerTags = {}; + for (var j = 0; j < keys2.length; ++j) + object.resourceManagerTags[keys2[j]] = message.resourceManagerTags[keys2[j]]; + } + return object; + }; + + /** + * Converts this TargetVpnGatewayParams to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @instance + * @returns {Object.} JSON object + */ + TargetVpnGatewayParams.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TargetVpnGatewayParams + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.TargetVpnGatewayParams + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TargetVpnGatewayParams.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.TargetVpnGatewayParams"; + }; + + return TargetVpnGatewayParams; + })(); + v1beta.TargetVpnGatewaysScopedList = (function() { /** @@ -1292932,30 +1312620,310 @@ }; /** - * Decodes a TestIamPermissionsInstanceGroupRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsInstanceGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest} TestIamPermissionsInstanceGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsInstanceGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TestIamPermissionsInstanceGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TestIamPermissionsInstanceGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + if (message.testPermissionsRequestResource != null && message.hasOwnProperty("testPermissionsRequestResource")) { + var error = $root.google.cloud.compute.v1beta.TestPermissionsRequest.verify(message.testPermissionsRequestResource); + if (error) + return "testPermissionsRequestResource." + error; + } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates a TestIamPermissionsInstanceGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest} TestIamPermissionsInstanceGroupRequest + */ + TestIamPermissionsInstanceGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest(); + if (object.project != null) + message.project = String(object.project); + if (object.resource != null) + message.resource = String(object.resource); + if (object.testPermissionsRequestResource != null) { + if (typeof object.testPermissionsRequestResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest.testPermissionsRequestResource: object expected"); + message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); + } + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from a TestIamPermissionsInstanceGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @static + * @param {google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest} message TestIamPermissionsInstanceGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TestIamPermissionsInstanceGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.resource = ""; + object.project = ""; + object.testPermissionsRequestResource = null; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.testPermissionsRequestResource != null && message.hasOwnProperty("testPermissionsRequestResource")) + object.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.toObject(message.testPermissionsRequestResource, options); + return object; + }; + + /** + * Converts this TestIamPermissionsInstanceGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @instance + * @returns {Object.} JSON object + */ + TestIamPermissionsInstanceGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TestIamPermissionsInstanceGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TestIamPermissionsInstanceGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest"; + }; + + return TestIamPermissionsInstanceGroupRequest; + })(); + + v1beta.TestIamPermissionsInstanceRequest = (function() { + + /** + * Properties of a TestIamPermissionsInstanceRequest. + * @memberof google.cloud.compute.v1beta + * @interface ITestIamPermissionsInstanceRequest + * @property {string|null} [project] TestIamPermissionsInstanceRequest project + * @property {string|null} [resource] TestIamPermissionsInstanceRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsInstanceRequest testPermissionsRequestResource + * @property {string|null} [zone] TestIamPermissionsInstanceRequest zone + */ + + /** + * Constructs a new TestIamPermissionsInstanceRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a TestIamPermissionsInstanceRequest. + * @implements ITestIamPermissionsInstanceRequest + * @constructor + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceRequest=} [properties] Properties to set + */ + function TestIamPermissionsInstanceRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TestIamPermissionsInstanceRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @instance + */ + TestIamPermissionsInstanceRequest.prototype.project = ""; + + /** + * TestIamPermissionsInstanceRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @instance + */ + TestIamPermissionsInstanceRequest.prototype.resource = ""; + + /** + * TestIamPermissionsInstanceRequest testPermissionsRequestResource. + * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @instance + */ + TestIamPermissionsInstanceRequest.prototype.testPermissionsRequestResource = null; + + /** + * TestIamPermissionsInstanceRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @instance + */ + TestIamPermissionsInstanceRequest.prototype.zone = ""; + + /** + * Creates a new TestIamPermissionsInstanceRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} TestIamPermissionsInstanceRequest instance + */ + TestIamPermissionsInstanceRequest.create = function create(properties) { + return new TestIamPermissionsInstanceRequest(properties); + }; + + /** + * Encodes the specified TestIamPermissionsInstanceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceRequest} message TestIamPermissionsInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsInstanceRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.testPermissionsRequestResource != null && Object.hasOwnProperty.call(message, "testPermissionsRequestResource")) + $root.google.cloud.compute.v1beta.TestPermissionsRequest.encode(message.testPermissionsRequestResource, writer.uint32(/* id 439214758, wireType 2 =*/3513718066).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified TestIamPermissionsInstanceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceRequest} message TestIamPermissionsInstanceRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsInstanceRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TestIamPermissionsInstanceRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} TestIamPermissionsInstanceRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsInstanceRequest.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.cloud.compute.v1beta.TestIamPermissionsInstanceRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 227560217: { + message.project = reader.string(); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + case 439214758: { + message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.decode(reader, reader.uint32()); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TestIamPermissionsInstanceRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest} TestIamPermissionsInstanceGroupRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} TestIamPermissionsInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsInstanceGroupRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsInstanceRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsInstanceGroupRequest message. + * Verifies a TestIamPermissionsInstanceRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsInstanceGroupRequest.verify = function verify(message) { + TestIamPermissionsInstanceRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1292976,24 +1312944,24 @@ }; /** - * Creates a TestIamPermissionsInstanceGroupRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsInstanceRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest} TestIamPermissionsInstanceGroupRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} TestIamPermissionsInstanceRequest */ - TestIamPermissionsInstanceGroupRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest) + TestIamPermissionsInstanceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest(); if (object.project != null) message.project = String(object.project); if (object.resource != null) message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } if (object.zone != null) @@ -1293002,15 +1312970,15 @@ }; /** - * Creates a plain object from a TestIamPermissionsInstanceGroupRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsInstanceRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest} message TestIamPermissionsInstanceGroupRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} message TestIamPermissionsInstanceRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsInstanceGroupRequest.toObject = function toObject(message, options) { + TestIamPermissionsInstanceRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1293032,55 +1313000,54 @@ }; /** - * Converts this TestIamPermissionsInstanceGroupRequest to JSON. + * Converts this TestIamPermissionsInstanceRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsInstanceGroupRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsInstanceRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsInstanceGroupRequest + * Gets the default type url for TestIamPermissionsInstanceRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsInstanceGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsInstanceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsInstanceGroupRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest"; }; - return TestIamPermissionsInstanceGroupRequest; + return TestIamPermissionsInstanceRequest; })(); - v1beta.TestIamPermissionsInstanceRequest = (function() { + v1beta.TestIamPermissionsInstanceTemplateRequest = (function() { /** - * Properties of a TestIamPermissionsInstanceRequest. + * Properties of a TestIamPermissionsInstanceTemplateRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsInstanceRequest - * @property {string|null} [project] TestIamPermissionsInstanceRequest project - * @property {string|null} [resource] TestIamPermissionsInstanceRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsInstanceRequest testPermissionsRequestResource - * @property {string|null} [zone] TestIamPermissionsInstanceRequest zone + * @interface ITestIamPermissionsInstanceTemplateRequest + * @property {string|null} [project] TestIamPermissionsInstanceTemplateRequest project + * @property {string|null} [resource] TestIamPermissionsInstanceTemplateRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsInstanceTemplateRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsInstanceRequest. + * Constructs a new TestIamPermissionsInstanceTemplateRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsInstanceRequest. - * @implements ITestIamPermissionsInstanceRequest + * @classdesc Represents a TestIamPermissionsInstanceTemplateRequest. + * @implements ITestIamPermissionsInstanceTemplateRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceTemplateRequest=} [properties] Properties to set */ - function TestIamPermissionsInstanceRequest(properties) { + function TestIamPermissionsInstanceTemplateRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1293088,63 +1313055,53 @@ } /** - * TestIamPermissionsInstanceRequest project. + * TestIamPermissionsInstanceTemplateRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @instance */ - TestIamPermissionsInstanceRequest.prototype.project = ""; + TestIamPermissionsInstanceTemplateRequest.prototype.project = ""; /** - * TestIamPermissionsInstanceRequest resource. + * TestIamPermissionsInstanceTemplateRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @instance */ - TestIamPermissionsInstanceRequest.prototype.resource = ""; + TestIamPermissionsInstanceTemplateRequest.prototype.resource = ""; /** - * TestIamPermissionsInstanceRequest testPermissionsRequestResource. + * TestIamPermissionsInstanceTemplateRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest - * @instance - */ - TestIamPermissionsInstanceRequest.prototype.testPermissionsRequestResource = null; - - /** - * TestIamPermissionsInstanceRequest zone. - * @member {string} zone - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @instance */ - TestIamPermissionsInstanceRequest.prototype.zone = ""; + TestIamPermissionsInstanceTemplateRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsInstanceRequest instance using the specified properties. + * Creates a new TestIamPermissionsInstanceTemplateRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} TestIamPermissionsInstanceRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceTemplateRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} TestIamPermissionsInstanceTemplateRequest instance */ - TestIamPermissionsInstanceRequest.create = function create(properties) { - return new TestIamPermissionsInstanceRequest(properties); + TestIamPermissionsInstanceTemplateRequest.create = function create(properties) { + return new TestIamPermissionsInstanceTemplateRequest(properties); }; /** - * Encodes the specified TestIamPermissionsInstanceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsInstanceTemplateRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceRequest} message TestIamPermissionsInstanceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceTemplateRequest} message TestIamPermissionsInstanceTemplateRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsInstanceRequest.encode = function encode(message, writer) { + TestIamPermissionsInstanceTemplateRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) - writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); if (message.project != null && Object.hasOwnProperty.call(message, "project")) @@ -1293155,33 +1313112,33 @@ }; /** - * Encodes the specified TestIamPermissionsInstanceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsInstanceTemplateRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceRequest} message TestIamPermissionsInstanceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceTemplateRequest} message TestIamPermissionsInstanceTemplateRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsInstanceRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsInstanceTemplateRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsInstanceRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsInstanceTemplateRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} TestIamPermissionsInstanceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} TestIamPermissionsInstanceTemplateRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsInstanceRequest.decode = function decode(reader, length, error) { + TestIamPermissionsInstanceTemplateRequest.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.cloud.compute.v1beta.TestIamPermissionsInstanceRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1293199,10 +1313156,6 @@ message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.decode(reader, reader.uint32()); break; } - case 3744684: { - message.zone = reader.string(); - break; - } default: reader.skipType(tag & 7); break; @@ -1293212,30 +1313165,30 @@ }; /** - * Decodes a TestIamPermissionsInstanceRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsInstanceTemplateRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} TestIamPermissionsInstanceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} TestIamPermissionsInstanceTemplateRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsInstanceRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsInstanceTemplateRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsInstanceRequest message. + * Verifies a TestIamPermissionsInstanceTemplateRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsInstanceRequest.verify = function verify(message) { + TestIamPermissionsInstanceTemplateRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1293249,59 +1313202,51 @@ if (error) return "testPermissionsRequestResource." + error; } - if (message.zone != null && message.hasOwnProperty("zone")) - if (!$util.isString(message.zone)) - return "zone: string expected"; return null; }; /** - * Creates a TestIamPermissionsInstanceRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsInstanceTemplateRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} TestIamPermissionsInstanceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} TestIamPermissionsInstanceTemplateRequest */ - TestIamPermissionsInstanceRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest) + TestIamPermissionsInstanceTemplateRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest(); if (object.project != null) message.project = String(object.project); if (object.resource != null) message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } - if (object.zone != null) - message.zone = String(object.zone); return message; }; /** - * Creates a plain object from a TestIamPermissionsInstanceRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsInstanceTemplateRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest} message TestIamPermissionsInstanceRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} message TestIamPermissionsInstanceTemplateRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsInstanceRequest.toObject = function toObject(message, options) { + TestIamPermissionsInstanceTemplateRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.zone = ""; object.resource = ""; object.project = ""; object.testPermissionsRequestResource = null; } - if (message.zone != null && message.hasOwnProperty("zone")) - object.zone = message.zone; if (message.resource != null && message.hasOwnProperty("resource")) object.resource = message.resource; if (message.project != null && message.hasOwnProperty("project")) @@ -1293312,54 +1313257,55 @@ }; /** - * Converts this TestIamPermissionsInstanceRequest to JSON. + * Converts this TestIamPermissionsInstanceTemplateRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsInstanceRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsInstanceTemplateRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsInstanceRequest + * Gets the default type url for TestIamPermissionsInstanceTemplateRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsInstanceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsInstanceTemplateRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsInstanceRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest"; }; - return TestIamPermissionsInstanceRequest; + return TestIamPermissionsInstanceTemplateRequest; })(); - v1beta.TestIamPermissionsInstanceTemplateRequest = (function() { + v1beta.TestIamPermissionsInstantSnapshotGroupRequest = (function() { /** - * Properties of a TestIamPermissionsInstanceTemplateRequest. + * Properties of a TestIamPermissionsInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsInstanceTemplateRequest - * @property {string|null} [project] TestIamPermissionsInstanceTemplateRequest project - * @property {string|null} [resource] TestIamPermissionsInstanceTemplateRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsInstanceTemplateRequest testPermissionsRequestResource + * @interface ITestIamPermissionsInstantSnapshotGroupRequest + * @property {string|null} [project] TestIamPermissionsInstantSnapshotGroupRequest project + * @property {string|null} [resource] TestIamPermissionsInstantSnapshotGroupRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsInstantSnapshotGroupRequest testPermissionsRequestResource + * @property {string|null} [zone] TestIamPermissionsInstantSnapshotGroupRequest zone */ /** - * Constructs a new TestIamPermissionsInstanceTemplateRequest. + * Constructs a new TestIamPermissionsInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsInstanceTemplateRequest. - * @implements ITestIamPermissionsInstanceTemplateRequest + * @classdesc Represents a TestIamPermissionsInstantSnapshotGroupRequest. + * @implements ITestIamPermissionsInstantSnapshotGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceTemplateRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest=} [properties] Properties to set */ - function TestIamPermissionsInstanceTemplateRequest(properties) { + function TestIamPermissionsInstantSnapshotGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1293367,53 +1313313,63 @@ } /** - * TestIamPermissionsInstanceTemplateRequest project. + * TestIamPermissionsInstantSnapshotGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @instance */ - TestIamPermissionsInstanceTemplateRequest.prototype.project = ""; + TestIamPermissionsInstantSnapshotGroupRequest.prototype.project = ""; /** - * TestIamPermissionsInstanceTemplateRequest resource. + * TestIamPermissionsInstantSnapshotGroupRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @instance */ - TestIamPermissionsInstanceTemplateRequest.prototype.resource = ""; + TestIamPermissionsInstantSnapshotGroupRequest.prototype.resource = ""; /** - * TestIamPermissionsInstanceTemplateRequest testPermissionsRequestResource. + * TestIamPermissionsInstantSnapshotGroupRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @instance */ - TestIamPermissionsInstanceTemplateRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsInstantSnapshotGroupRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsInstanceTemplateRequest instance using the specified properties. + * TestIamPermissionsInstantSnapshotGroupRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest + * @instance + */ + TestIamPermissionsInstantSnapshotGroupRequest.prototype.zone = ""; + + /** + * Creates a new TestIamPermissionsInstantSnapshotGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceTemplateRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} TestIamPermissionsInstanceTemplateRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest} TestIamPermissionsInstantSnapshotGroupRequest instance */ - TestIamPermissionsInstanceTemplateRequest.create = function create(properties) { - return new TestIamPermissionsInstanceTemplateRequest(properties); + TestIamPermissionsInstantSnapshotGroupRequest.create = function create(properties) { + return new TestIamPermissionsInstantSnapshotGroupRequest(properties); }; /** - * Encodes the specified TestIamPermissionsInstanceTemplateRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceTemplateRequest} message TestIamPermissionsInstanceTemplateRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest} message TestIamPermissionsInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsInstanceTemplateRequest.encode = function encode(message, writer) { + TestIamPermissionsInstantSnapshotGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); if (message.project != null && Object.hasOwnProperty.call(message, "project")) @@ -1293424,33 +1313380,33 @@ }; /** - * Encodes the specified TestIamPermissionsInstanceTemplateRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstanceTemplateRequest} message TestIamPermissionsInstanceTemplateRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest} message TestIamPermissionsInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsInstanceTemplateRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsInstanceTemplateRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsInstantSnapshotGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} TestIamPermissionsInstanceTemplateRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest} TestIamPermissionsInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsInstanceTemplateRequest.decode = function decode(reader, length, error) { + TestIamPermissionsInstantSnapshotGroupRequest.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.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1293468,6 +1313424,10 @@ message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.decode(reader, reader.uint32()); break; } + case 3744684: { + message.zone = reader.string(); + break; + } default: reader.skipType(tag & 7); break; @@ -1293477,30 +1313437,30 @@ }; /** - * Decodes a TestIamPermissionsInstanceTemplateRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} TestIamPermissionsInstanceTemplateRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest} TestIamPermissionsInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsInstanceTemplateRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsInstanceTemplateRequest message. + * Verifies a TestIamPermissionsInstantSnapshotGroupRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsInstanceTemplateRequest.verify = function verify(message) { + TestIamPermissionsInstantSnapshotGroupRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1293514,51 +1313474,59 @@ if (error) return "testPermissionsRequestResource." + error; } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; return null; }; /** - * Creates a TestIamPermissionsInstanceTemplateRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} TestIamPermissionsInstanceTemplateRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest} TestIamPermissionsInstantSnapshotGroupRequest */ - TestIamPermissionsInstanceTemplateRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest) + TestIamPermissionsInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest(); if (object.project != null) message.project = String(object.project); if (object.resource != null) message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } + if (object.zone != null) + message.zone = String(object.zone); return message; }; /** - * Creates a plain object from a TestIamPermissionsInstanceTemplateRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsInstantSnapshotGroupRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest} message TestIamPermissionsInstanceTemplateRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest} message TestIamPermissionsInstantSnapshotGroupRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsInstanceTemplateRequest.toObject = function toObject(message, options) { + TestIamPermissionsInstantSnapshotGroupRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { + object.zone = ""; object.resource = ""; object.project = ""; object.testPermissionsRequestResource = null; } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; if (message.resource != null && message.hasOwnProperty("resource")) object.resource = message.resource; if (message.project != null && message.hasOwnProperty("project")) @@ -1293569,32 +1313537,32 @@ }; /** - * Converts this TestIamPermissionsInstanceTemplateRequest to JSON. + * Converts this TestIamPermissionsInstantSnapshotGroupRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsInstanceTemplateRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsInstanceTemplateRequest + * Gets the default type url for TestIamPermissionsInstantSnapshotGroupRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsInstanceTemplateRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsInstanceTemplateRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest"; }; - return TestIamPermissionsInstanceTemplateRequest; + return TestIamPermissionsInstantSnapshotGroupRequest; })(); v1beta.TestIamPermissionsInstantSnapshotRequest = (function() { @@ -1297485,30 +1317453,310 @@ }; /** - * Decodes a TestIamPermissionsPacketMirroringRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsPacketMirroringRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest} TestIamPermissionsPacketMirroringRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsPacketMirroringRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TestIamPermissionsPacketMirroringRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TestIamPermissionsPacketMirroringRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + if (message.testPermissionsRequestResource != null && message.hasOwnProperty("testPermissionsRequestResource")) { + var error = $root.google.cloud.compute.v1beta.TestPermissionsRequest.verify(message.testPermissionsRequestResource); + if (error) + return "testPermissionsRequestResource." + error; + } + return null; + }; + + /** + * Creates a TestIamPermissionsPacketMirroringRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest} TestIamPermissionsPacketMirroringRequest + */ + TestIamPermissionsPacketMirroringRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest(); + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.resource != null) + message.resource = String(object.resource); + if (object.testPermissionsRequestResource != null) { + if (typeof object.testPermissionsRequestResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest.testPermissionsRequestResource: object expected"); + message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); + } + return message; + }; + + /** + * Creates a plain object from a TestIamPermissionsPacketMirroringRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @static + * @param {google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest} message TestIamPermissionsPacketMirroringRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TestIamPermissionsPacketMirroringRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.resource = ""; + object.project = ""; + object.testPermissionsRequestResource = null; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.testPermissionsRequestResource != null && message.hasOwnProperty("testPermissionsRequestResource")) + object.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.toObject(message.testPermissionsRequestResource, options); + return object; + }; + + /** + * Converts this TestIamPermissionsPacketMirroringRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @instance + * @returns {Object.} JSON object + */ + TestIamPermissionsPacketMirroringRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TestIamPermissionsPacketMirroringRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TestIamPermissionsPacketMirroringRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest"; + }; + + return TestIamPermissionsPacketMirroringRequest; + })(); + + v1beta.TestIamPermissionsRegionAutoscalerRequest = (function() { + + /** + * Properties of a TestIamPermissionsRegionAutoscalerRequest. + * @memberof google.cloud.compute.v1beta + * @interface ITestIamPermissionsRegionAutoscalerRequest + * @property {string|null} [project] TestIamPermissionsRegionAutoscalerRequest project + * @property {string|null} [region] TestIamPermissionsRegionAutoscalerRequest region + * @property {string|null} [resource] TestIamPermissionsRegionAutoscalerRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionAutoscalerRequest testPermissionsRequestResource + */ + + /** + * Constructs a new TestIamPermissionsRegionAutoscalerRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a TestIamPermissionsRegionAutoscalerRequest. + * @implements ITestIamPermissionsRegionAutoscalerRequest + * @constructor + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionAutoscalerRequest=} [properties] Properties to set + */ + function TestIamPermissionsRegionAutoscalerRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TestIamPermissionsRegionAutoscalerRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @instance + */ + TestIamPermissionsRegionAutoscalerRequest.prototype.project = ""; + + /** + * TestIamPermissionsRegionAutoscalerRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @instance + */ + TestIamPermissionsRegionAutoscalerRequest.prototype.region = ""; + + /** + * TestIamPermissionsRegionAutoscalerRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @instance + */ + TestIamPermissionsRegionAutoscalerRequest.prototype.resource = ""; + + /** + * TestIamPermissionsRegionAutoscalerRequest testPermissionsRequestResource. + * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @instance + */ + TestIamPermissionsRegionAutoscalerRequest.prototype.testPermissionsRequestResource = null; + + /** + * Creates a new TestIamPermissionsRegionAutoscalerRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionAutoscalerRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} TestIamPermissionsRegionAutoscalerRequest instance + */ + TestIamPermissionsRegionAutoscalerRequest.create = function create(properties) { + return new TestIamPermissionsRegionAutoscalerRequest(properties); + }; + + /** + * Encodes the specified TestIamPermissionsRegionAutoscalerRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionAutoscalerRequest} message TestIamPermissionsRegionAutoscalerRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsRegionAutoscalerRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.testPermissionsRequestResource != null && Object.hasOwnProperty.call(message, "testPermissionsRequestResource")) + $root.google.cloud.compute.v1beta.TestPermissionsRequest.encode(message.testPermissionsRequestResource, writer.uint32(/* id 439214758, wireType 2 =*/3513718066).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified TestIamPermissionsRegionAutoscalerRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionAutoscalerRequest} message TestIamPermissionsRegionAutoscalerRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsRegionAutoscalerRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TestIamPermissionsRegionAutoscalerRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} TestIamPermissionsRegionAutoscalerRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsRegionAutoscalerRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + case 439214758: { + message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TestIamPermissionsRegionAutoscalerRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest} TestIamPermissionsPacketMirroringRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} TestIamPermissionsRegionAutoscalerRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsPacketMirroringRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionAutoscalerRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsPacketMirroringRequest message. + * Verifies a TestIamPermissionsRegionAutoscalerRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsPacketMirroringRequest.verify = function verify(message) { + TestIamPermissionsRegionAutoscalerRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1297529,17 +1317777,17 @@ }; /** - * Creates a TestIamPermissionsPacketMirroringRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionAutoscalerRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest} TestIamPermissionsPacketMirroringRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} TestIamPermissionsRegionAutoscalerRequest */ - TestIamPermissionsPacketMirroringRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest) + TestIamPermissionsRegionAutoscalerRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1297548,22 +1317796,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsPacketMirroringRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionAutoscalerRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest} message TestIamPermissionsPacketMirroringRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} message TestIamPermissionsRegionAutoscalerRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsPacketMirroringRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionAutoscalerRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1297585,55 +1317833,55 @@ }; /** - * Converts this TestIamPermissionsPacketMirroringRequest to JSON. + * Converts this TestIamPermissionsRegionAutoscalerRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsPacketMirroringRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionAutoscalerRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsPacketMirroringRequest + * Gets the default type url for TestIamPermissionsRegionAutoscalerRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsPacketMirroringRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionAutoscalerRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsPacketMirroringRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest"; }; - return TestIamPermissionsPacketMirroringRequest; + return TestIamPermissionsRegionAutoscalerRequest; })(); - v1beta.TestIamPermissionsRegionAutoscalerRequest = (function() { + v1beta.TestIamPermissionsRegionBackendBucketRequest = (function() { /** - * Properties of a TestIamPermissionsRegionAutoscalerRequest. + * Properties of a TestIamPermissionsRegionBackendBucketRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionAutoscalerRequest - * @property {string|null} [project] TestIamPermissionsRegionAutoscalerRequest project - * @property {string|null} [region] TestIamPermissionsRegionAutoscalerRequest region - * @property {string|null} [resource] TestIamPermissionsRegionAutoscalerRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionAutoscalerRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionBackendBucketRequest + * @property {string|null} [project] TestIamPermissionsRegionBackendBucketRequest project + * @property {string|null} [region] TestIamPermissionsRegionBackendBucketRequest region + * @property {string|null} [resource] TestIamPermissionsRegionBackendBucketRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionBackendBucketRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionAutoscalerRequest. + * Constructs a new TestIamPermissionsRegionBackendBucketRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionAutoscalerRequest. - * @implements ITestIamPermissionsRegionAutoscalerRequest + * @classdesc Represents a TestIamPermissionsRegionBackendBucketRequest. + * @implements ITestIamPermissionsRegionBackendBucketRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionAutoscalerRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendBucketRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionAutoscalerRequest(properties) { + function TestIamPermissionsRegionBackendBucketRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1297641,59 +1317889,59 @@ } /** - * TestIamPermissionsRegionAutoscalerRequest project. + * TestIamPermissionsRegionBackendBucketRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @instance */ - TestIamPermissionsRegionAutoscalerRequest.prototype.project = ""; + TestIamPermissionsRegionBackendBucketRequest.prototype.project = ""; /** - * TestIamPermissionsRegionAutoscalerRequest region. + * TestIamPermissionsRegionBackendBucketRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @instance */ - TestIamPermissionsRegionAutoscalerRequest.prototype.region = ""; + TestIamPermissionsRegionBackendBucketRequest.prototype.region = ""; /** - * TestIamPermissionsRegionAutoscalerRequest resource. + * TestIamPermissionsRegionBackendBucketRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @instance */ - TestIamPermissionsRegionAutoscalerRequest.prototype.resource = ""; + TestIamPermissionsRegionBackendBucketRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionAutoscalerRequest testPermissionsRequestResource. + * TestIamPermissionsRegionBackendBucketRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @instance */ - TestIamPermissionsRegionAutoscalerRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionBackendBucketRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionAutoscalerRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionBackendBucketRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionAutoscalerRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} TestIamPermissionsRegionAutoscalerRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendBucketRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} TestIamPermissionsRegionBackendBucketRequest instance */ - TestIamPermissionsRegionAutoscalerRequest.create = function create(properties) { - return new TestIamPermissionsRegionAutoscalerRequest(properties); + TestIamPermissionsRegionBackendBucketRequest.create = function create(properties) { + return new TestIamPermissionsRegionBackendBucketRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionAutoscalerRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionBackendBucketRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionAutoscalerRequest} message TestIamPermissionsRegionAutoscalerRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendBucketRequest} message TestIamPermissionsRegionBackendBucketRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionAutoscalerRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionBackendBucketRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1297708,33 +1317956,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionAutoscalerRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionBackendBucketRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionAutoscalerRequest} message TestIamPermissionsRegionAutoscalerRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendBucketRequest} message TestIamPermissionsRegionBackendBucketRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionAutoscalerRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionBackendBucketRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionAutoscalerRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionBackendBucketRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} TestIamPermissionsRegionAutoscalerRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} TestIamPermissionsRegionBackendBucketRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionAutoscalerRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionBackendBucketRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1297765,30 +1318013,30 @@ }; /** - * Decodes a TestIamPermissionsRegionAutoscalerRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionBackendBucketRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} TestIamPermissionsRegionAutoscalerRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} TestIamPermissionsRegionBackendBucketRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionAutoscalerRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionBackendBucketRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionAutoscalerRequest message. + * Verifies a TestIamPermissionsRegionBackendBucketRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionAutoscalerRequest.verify = function verify(message) { + TestIamPermissionsRegionBackendBucketRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1297809,17 +1318057,17 @@ }; /** - * Creates a TestIamPermissionsRegionAutoscalerRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionBackendBucketRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} TestIamPermissionsRegionAutoscalerRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} TestIamPermissionsRegionBackendBucketRequest */ - TestIamPermissionsRegionAutoscalerRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest) + TestIamPermissionsRegionBackendBucketRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1297828,22 +1318076,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionAutoscalerRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionBackendBucketRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest} message TestIamPermissionsRegionAutoscalerRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} message TestIamPermissionsRegionBackendBucketRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionAutoscalerRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionBackendBucketRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1297865,55 +1318113,55 @@ }; /** - * Converts this TestIamPermissionsRegionAutoscalerRequest to JSON. + * Converts this TestIamPermissionsRegionBackendBucketRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionAutoscalerRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionBackendBucketRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionAutoscalerRequest + * Gets the default type url for TestIamPermissionsRegionBackendBucketRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionAutoscalerRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionBackendBucketRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionAutoscalerRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest"; }; - return TestIamPermissionsRegionAutoscalerRequest; + return TestIamPermissionsRegionBackendBucketRequest; })(); - v1beta.TestIamPermissionsRegionBackendBucketRequest = (function() { + v1beta.TestIamPermissionsRegionBackendServiceRequest = (function() { /** - * Properties of a TestIamPermissionsRegionBackendBucketRequest. + * Properties of a TestIamPermissionsRegionBackendServiceRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionBackendBucketRequest - * @property {string|null} [project] TestIamPermissionsRegionBackendBucketRequest project - * @property {string|null} [region] TestIamPermissionsRegionBackendBucketRequest region - * @property {string|null} [resource] TestIamPermissionsRegionBackendBucketRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionBackendBucketRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionBackendServiceRequest + * @property {string|null} [project] TestIamPermissionsRegionBackendServiceRequest project + * @property {string|null} [region] TestIamPermissionsRegionBackendServiceRequest region + * @property {string|null} [resource] TestIamPermissionsRegionBackendServiceRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionBackendServiceRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionBackendBucketRequest. + * Constructs a new TestIamPermissionsRegionBackendServiceRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionBackendBucketRequest. - * @implements ITestIamPermissionsRegionBackendBucketRequest + * @classdesc Represents a TestIamPermissionsRegionBackendServiceRequest. + * @implements ITestIamPermissionsRegionBackendServiceRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendBucketRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendServiceRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionBackendBucketRequest(properties) { + function TestIamPermissionsRegionBackendServiceRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1297921,59 +1318169,59 @@ } /** - * TestIamPermissionsRegionBackendBucketRequest project. + * TestIamPermissionsRegionBackendServiceRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @instance */ - TestIamPermissionsRegionBackendBucketRequest.prototype.project = ""; + TestIamPermissionsRegionBackendServiceRequest.prototype.project = ""; /** - * TestIamPermissionsRegionBackendBucketRequest region. + * TestIamPermissionsRegionBackendServiceRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @instance */ - TestIamPermissionsRegionBackendBucketRequest.prototype.region = ""; + TestIamPermissionsRegionBackendServiceRequest.prototype.region = ""; /** - * TestIamPermissionsRegionBackendBucketRequest resource. + * TestIamPermissionsRegionBackendServiceRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @instance */ - TestIamPermissionsRegionBackendBucketRequest.prototype.resource = ""; + TestIamPermissionsRegionBackendServiceRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionBackendBucketRequest testPermissionsRequestResource. + * TestIamPermissionsRegionBackendServiceRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @instance */ - TestIamPermissionsRegionBackendBucketRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionBackendServiceRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionBackendBucketRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionBackendServiceRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendBucketRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} TestIamPermissionsRegionBackendBucketRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendServiceRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} TestIamPermissionsRegionBackendServiceRequest instance */ - TestIamPermissionsRegionBackendBucketRequest.create = function create(properties) { - return new TestIamPermissionsRegionBackendBucketRequest(properties); + TestIamPermissionsRegionBackendServiceRequest.create = function create(properties) { + return new TestIamPermissionsRegionBackendServiceRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionBackendBucketRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionBackendServiceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendBucketRequest} message TestIamPermissionsRegionBackendBucketRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendServiceRequest} message TestIamPermissionsRegionBackendServiceRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionBackendBucketRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionBackendServiceRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1297988,33 +1318236,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionBackendBucketRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionBackendServiceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendBucketRequest} message TestIamPermissionsRegionBackendBucketRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendServiceRequest} message TestIamPermissionsRegionBackendServiceRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionBackendBucketRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionBackendServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionBackendBucketRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionBackendServiceRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} TestIamPermissionsRegionBackendBucketRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} TestIamPermissionsRegionBackendServiceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionBackendBucketRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionBackendServiceRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1298045,30 +1318293,30 @@ }; /** - * Decodes a TestIamPermissionsRegionBackendBucketRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionBackendServiceRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} TestIamPermissionsRegionBackendBucketRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} TestIamPermissionsRegionBackendServiceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionBackendBucketRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionBackendServiceRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionBackendBucketRequest message. + * Verifies a TestIamPermissionsRegionBackendServiceRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionBackendBucketRequest.verify = function verify(message) { + TestIamPermissionsRegionBackendServiceRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1298089,17 +1318337,17 @@ }; /** - * Creates a TestIamPermissionsRegionBackendBucketRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionBackendServiceRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} TestIamPermissionsRegionBackendBucketRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} TestIamPermissionsRegionBackendServiceRequest */ - TestIamPermissionsRegionBackendBucketRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest) + TestIamPermissionsRegionBackendServiceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1298108,22 +1318356,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionBackendBucketRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionBackendServiceRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest} message TestIamPermissionsRegionBackendBucketRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} message TestIamPermissionsRegionBackendServiceRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionBackendBucketRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionBackendServiceRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1298145,55 +1318393,55 @@ }; /** - * Converts this TestIamPermissionsRegionBackendBucketRequest to JSON. + * Converts this TestIamPermissionsRegionBackendServiceRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionBackendBucketRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionBackendServiceRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionBackendBucketRequest + * Gets the default type url for TestIamPermissionsRegionBackendServiceRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionBackendBucketRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionBackendServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionBackendBucketRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest"; }; - return TestIamPermissionsRegionBackendBucketRequest; + return TestIamPermissionsRegionBackendServiceRequest; })(); - v1beta.TestIamPermissionsRegionBackendServiceRequest = (function() { + v1beta.TestIamPermissionsRegionCommitmentRequest = (function() { /** - * Properties of a TestIamPermissionsRegionBackendServiceRequest. + * Properties of a TestIamPermissionsRegionCommitmentRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionBackendServiceRequest - * @property {string|null} [project] TestIamPermissionsRegionBackendServiceRequest project - * @property {string|null} [region] TestIamPermissionsRegionBackendServiceRequest region - * @property {string|null} [resource] TestIamPermissionsRegionBackendServiceRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionBackendServiceRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionCommitmentRequest + * @property {string|null} [project] TestIamPermissionsRegionCommitmentRequest project + * @property {string|null} [region] TestIamPermissionsRegionCommitmentRequest region + * @property {string|null} [resource] TestIamPermissionsRegionCommitmentRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionCommitmentRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionBackendServiceRequest. + * Constructs a new TestIamPermissionsRegionCommitmentRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionBackendServiceRequest. - * @implements ITestIamPermissionsRegionBackendServiceRequest + * @classdesc Represents a TestIamPermissionsRegionCommitmentRequest. + * @implements ITestIamPermissionsRegionCommitmentRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendServiceRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCommitmentRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionBackendServiceRequest(properties) { + function TestIamPermissionsRegionCommitmentRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1298201,59 +1318449,59 @@ } /** - * TestIamPermissionsRegionBackendServiceRequest project. + * TestIamPermissionsRegionCommitmentRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @instance */ - TestIamPermissionsRegionBackendServiceRequest.prototype.project = ""; + TestIamPermissionsRegionCommitmentRequest.prototype.project = ""; /** - * TestIamPermissionsRegionBackendServiceRequest region. + * TestIamPermissionsRegionCommitmentRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @instance */ - TestIamPermissionsRegionBackendServiceRequest.prototype.region = ""; + TestIamPermissionsRegionCommitmentRequest.prototype.region = ""; /** - * TestIamPermissionsRegionBackendServiceRequest resource. + * TestIamPermissionsRegionCommitmentRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @instance */ - TestIamPermissionsRegionBackendServiceRequest.prototype.resource = ""; + TestIamPermissionsRegionCommitmentRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionBackendServiceRequest testPermissionsRequestResource. + * TestIamPermissionsRegionCommitmentRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @instance */ - TestIamPermissionsRegionBackendServiceRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionCommitmentRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionBackendServiceRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionCommitmentRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendServiceRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} TestIamPermissionsRegionBackendServiceRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCommitmentRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} TestIamPermissionsRegionCommitmentRequest instance */ - TestIamPermissionsRegionBackendServiceRequest.create = function create(properties) { - return new TestIamPermissionsRegionBackendServiceRequest(properties); + TestIamPermissionsRegionCommitmentRequest.create = function create(properties) { + return new TestIamPermissionsRegionCommitmentRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionBackendServiceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionCommitmentRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendServiceRequest} message TestIamPermissionsRegionBackendServiceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCommitmentRequest} message TestIamPermissionsRegionCommitmentRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionBackendServiceRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionCommitmentRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1298268,33 +1318516,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionBackendServiceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionCommitmentRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionBackendServiceRequest} message TestIamPermissionsRegionBackendServiceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCommitmentRequest} message TestIamPermissionsRegionCommitmentRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionBackendServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionCommitmentRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionBackendServiceRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionCommitmentRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} TestIamPermissionsRegionBackendServiceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} TestIamPermissionsRegionCommitmentRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionBackendServiceRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionCommitmentRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1298325,30 +1318573,30 @@ }; /** - * Decodes a TestIamPermissionsRegionBackendServiceRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionCommitmentRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} TestIamPermissionsRegionBackendServiceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} TestIamPermissionsRegionCommitmentRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionBackendServiceRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionCommitmentRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionBackendServiceRequest message. + * Verifies a TestIamPermissionsRegionCommitmentRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionBackendServiceRequest.verify = function verify(message) { + TestIamPermissionsRegionCommitmentRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1298369,17 +1318617,17 @@ }; /** - * Creates a TestIamPermissionsRegionBackendServiceRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionCommitmentRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} TestIamPermissionsRegionBackendServiceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} TestIamPermissionsRegionCommitmentRequest */ - TestIamPermissionsRegionBackendServiceRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest) + TestIamPermissionsRegionCommitmentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1298388,22 +1318636,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionBackendServiceRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionCommitmentRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest} message TestIamPermissionsRegionBackendServiceRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} message TestIamPermissionsRegionCommitmentRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionBackendServiceRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionCommitmentRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1298425,55 +1318673,55 @@ }; /** - * Converts this TestIamPermissionsRegionBackendServiceRequest to JSON. + * Converts this TestIamPermissionsRegionCommitmentRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionBackendServiceRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionCommitmentRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionBackendServiceRequest + * Gets the default type url for TestIamPermissionsRegionCommitmentRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionBackendServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionCommitmentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionBackendServiceRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest"; }; - return TestIamPermissionsRegionBackendServiceRequest; + return TestIamPermissionsRegionCommitmentRequest; })(); - v1beta.TestIamPermissionsRegionCommitmentRequest = (function() { + v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest = (function() { /** - * Properties of a TestIamPermissionsRegionCommitmentRequest. + * Properties of a TestIamPermissionsRegionCompositeHealthCheckRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionCommitmentRequest - * @property {string|null} [project] TestIamPermissionsRegionCommitmentRequest project - * @property {string|null} [region] TestIamPermissionsRegionCommitmentRequest region - * @property {string|null} [resource] TestIamPermissionsRegionCommitmentRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionCommitmentRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionCompositeHealthCheckRequest + * @property {string|null} [project] TestIamPermissionsRegionCompositeHealthCheckRequest project + * @property {string|null} [region] TestIamPermissionsRegionCompositeHealthCheckRequest region + * @property {string|null} [resource] TestIamPermissionsRegionCompositeHealthCheckRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionCompositeHealthCheckRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionCommitmentRequest. + * Constructs a new TestIamPermissionsRegionCompositeHealthCheckRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionCommitmentRequest. - * @implements ITestIamPermissionsRegionCommitmentRequest + * @classdesc Represents a TestIamPermissionsRegionCompositeHealthCheckRequest. + * @implements ITestIamPermissionsRegionCompositeHealthCheckRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCommitmentRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCompositeHealthCheckRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionCommitmentRequest(properties) { + function TestIamPermissionsRegionCompositeHealthCheckRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1298481,59 +1318729,59 @@ } /** - * TestIamPermissionsRegionCommitmentRequest project. + * TestIamPermissionsRegionCompositeHealthCheckRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @instance */ - TestIamPermissionsRegionCommitmentRequest.prototype.project = ""; + TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.project = ""; /** - * TestIamPermissionsRegionCommitmentRequest region. + * TestIamPermissionsRegionCompositeHealthCheckRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @instance */ - TestIamPermissionsRegionCommitmentRequest.prototype.region = ""; + TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.region = ""; /** - * TestIamPermissionsRegionCommitmentRequest resource. + * TestIamPermissionsRegionCompositeHealthCheckRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @instance */ - TestIamPermissionsRegionCommitmentRequest.prototype.resource = ""; + TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionCommitmentRequest testPermissionsRequestResource. + * TestIamPermissionsRegionCompositeHealthCheckRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @instance */ - TestIamPermissionsRegionCommitmentRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionCommitmentRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionCompositeHealthCheckRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCommitmentRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} TestIamPermissionsRegionCommitmentRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCompositeHealthCheckRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} TestIamPermissionsRegionCompositeHealthCheckRequest instance */ - TestIamPermissionsRegionCommitmentRequest.create = function create(properties) { - return new TestIamPermissionsRegionCommitmentRequest(properties); + TestIamPermissionsRegionCompositeHealthCheckRequest.create = function create(properties) { + return new TestIamPermissionsRegionCompositeHealthCheckRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionCommitmentRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionCompositeHealthCheckRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCommitmentRequest} message TestIamPermissionsRegionCommitmentRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCompositeHealthCheckRequest} message TestIamPermissionsRegionCompositeHealthCheckRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionCommitmentRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionCompositeHealthCheckRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1298548,33 +1318796,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionCommitmentRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionCompositeHealthCheckRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCommitmentRequest} message TestIamPermissionsRegionCommitmentRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCompositeHealthCheckRequest} message TestIamPermissionsRegionCompositeHealthCheckRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionCommitmentRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionCompositeHealthCheckRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionCommitmentRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionCompositeHealthCheckRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} TestIamPermissionsRegionCommitmentRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} TestIamPermissionsRegionCompositeHealthCheckRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionCommitmentRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionCompositeHealthCheckRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1298605,30 +1318853,30 @@ }; /** - * Decodes a TestIamPermissionsRegionCommitmentRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionCompositeHealthCheckRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} TestIamPermissionsRegionCommitmentRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} TestIamPermissionsRegionCompositeHealthCheckRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionCommitmentRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionCompositeHealthCheckRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionCommitmentRequest message. + * Verifies a TestIamPermissionsRegionCompositeHealthCheckRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionCommitmentRequest.verify = function verify(message) { + TestIamPermissionsRegionCompositeHealthCheckRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1298649,17 +1318897,17 @@ }; /** - * Creates a TestIamPermissionsRegionCommitmentRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionCompositeHealthCheckRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} TestIamPermissionsRegionCommitmentRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} TestIamPermissionsRegionCompositeHealthCheckRequest */ - TestIamPermissionsRegionCommitmentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest) + TestIamPermissionsRegionCompositeHealthCheckRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1298668,22 +1318916,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionCommitmentRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionCompositeHealthCheckRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest} message TestIamPermissionsRegionCommitmentRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} message TestIamPermissionsRegionCompositeHealthCheckRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionCommitmentRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionCompositeHealthCheckRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1298705,55 +1318953,55 @@ }; /** - * Converts this TestIamPermissionsRegionCommitmentRequest to JSON. + * Converts this TestIamPermissionsRegionCompositeHealthCheckRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionCommitmentRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionCommitmentRequest + * Gets the default type url for TestIamPermissionsRegionCompositeHealthCheckRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionCommitmentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionCompositeHealthCheckRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionCommitmentRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest"; }; - return TestIamPermissionsRegionCommitmentRequest; + return TestIamPermissionsRegionCompositeHealthCheckRequest; })(); - v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest = (function() { + v1beta.TestIamPermissionsRegionDiskRequest = (function() { /** - * Properties of a TestIamPermissionsRegionCompositeHealthCheckRequest. + * Properties of a TestIamPermissionsRegionDiskRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionCompositeHealthCheckRequest - * @property {string|null} [project] TestIamPermissionsRegionCompositeHealthCheckRequest project - * @property {string|null} [region] TestIamPermissionsRegionCompositeHealthCheckRequest region - * @property {string|null} [resource] TestIamPermissionsRegionCompositeHealthCheckRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionCompositeHealthCheckRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionDiskRequest + * @property {string|null} [project] TestIamPermissionsRegionDiskRequest project + * @property {string|null} [region] TestIamPermissionsRegionDiskRequest region + * @property {string|null} [resource] TestIamPermissionsRegionDiskRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionDiskRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionCompositeHealthCheckRequest. + * Constructs a new TestIamPermissionsRegionDiskRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionCompositeHealthCheckRequest. - * @implements ITestIamPermissionsRegionCompositeHealthCheckRequest + * @classdesc Represents a TestIamPermissionsRegionDiskRequest. + * @implements ITestIamPermissionsRegionDiskRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCompositeHealthCheckRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionDiskRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionCompositeHealthCheckRequest(properties) { + function TestIamPermissionsRegionDiskRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1298761,59 +1319009,59 @@ } /** - * TestIamPermissionsRegionCompositeHealthCheckRequest project. + * TestIamPermissionsRegionDiskRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @instance */ - TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.project = ""; + TestIamPermissionsRegionDiskRequest.prototype.project = ""; /** - * TestIamPermissionsRegionCompositeHealthCheckRequest region. + * TestIamPermissionsRegionDiskRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @instance */ - TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.region = ""; + TestIamPermissionsRegionDiskRequest.prototype.region = ""; /** - * TestIamPermissionsRegionCompositeHealthCheckRequest resource. + * TestIamPermissionsRegionDiskRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @instance */ - TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.resource = ""; + TestIamPermissionsRegionDiskRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionCompositeHealthCheckRequest testPermissionsRequestResource. + * TestIamPermissionsRegionDiskRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @instance */ - TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionDiskRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionCompositeHealthCheckRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionDiskRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCompositeHealthCheckRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} TestIamPermissionsRegionCompositeHealthCheckRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionDiskRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} TestIamPermissionsRegionDiskRequest instance */ - TestIamPermissionsRegionCompositeHealthCheckRequest.create = function create(properties) { - return new TestIamPermissionsRegionCompositeHealthCheckRequest(properties); + TestIamPermissionsRegionDiskRequest.create = function create(properties) { + return new TestIamPermissionsRegionDiskRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionCompositeHealthCheckRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionDiskRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCompositeHealthCheckRequest} message TestIamPermissionsRegionCompositeHealthCheckRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionDiskRequest} message TestIamPermissionsRegionDiskRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionCompositeHealthCheckRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionDiskRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1298828,33 +1319076,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionCompositeHealthCheckRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionDiskRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionCompositeHealthCheckRequest} message TestIamPermissionsRegionCompositeHealthCheckRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionDiskRequest} message TestIamPermissionsRegionDiskRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionCompositeHealthCheckRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionDiskRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionCompositeHealthCheckRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionDiskRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} TestIamPermissionsRegionCompositeHealthCheckRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} TestIamPermissionsRegionDiskRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionCompositeHealthCheckRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionDiskRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1298885,30 +1319133,30 @@ }; /** - * Decodes a TestIamPermissionsRegionCompositeHealthCheckRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionDiskRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} TestIamPermissionsRegionCompositeHealthCheckRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} TestIamPermissionsRegionDiskRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionCompositeHealthCheckRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionDiskRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionCompositeHealthCheckRequest message. + * Verifies a TestIamPermissionsRegionDiskRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionCompositeHealthCheckRequest.verify = function verify(message) { + TestIamPermissionsRegionDiskRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1298929,17 +1319177,17 @@ }; /** - * Creates a TestIamPermissionsRegionCompositeHealthCheckRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionDiskRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} TestIamPermissionsRegionCompositeHealthCheckRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} TestIamPermissionsRegionDiskRequest */ - TestIamPermissionsRegionCompositeHealthCheckRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest) + TestIamPermissionsRegionDiskRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1298948,22 +1319196,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionCompositeHealthCheckRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionDiskRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest} message TestIamPermissionsRegionCompositeHealthCheckRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} message TestIamPermissionsRegionDiskRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionCompositeHealthCheckRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionDiskRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1298985,55 +1319233,55 @@ }; /** - * Converts this TestIamPermissionsRegionCompositeHealthCheckRequest to JSON. + * Converts this TestIamPermissionsRegionDiskRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionCompositeHealthCheckRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionDiskRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionCompositeHealthCheckRequest + * Gets the default type url for TestIamPermissionsRegionDiskRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionCompositeHealthCheckRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionDiskRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionCompositeHealthCheckRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest"; }; - return TestIamPermissionsRegionCompositeHealthCheckRequest; + return TestIamPermissionsRegionDiskRequest; })(); - v1beta.TestIamPermissionsRegionDiskRequest = (function() { + v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest = (function() { /** - * Properties of a TestIamPermissionsRegionDiskRequest. + * Properties of a TestIamPermissionsRegionHealthAggregationPolicyRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionDiskRequest - * @property {string|null} [project] TestIamPermissionsRegionDiskRequest project - * @property {string|null} [region] TestIamPermissionsRegionDiskRequest region - * @property {string|null} [resource] TestIamPermissionsRegionDiskRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionDiskRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionHealthAggregationPolicyRequest + * @property {string|null} [project] TestIamPermissionsRegionHealthAggregationPolicyRequest project + * @property {string|null} [region] TestIamPermissionsRegionHealthAggregationPolicyRequest region + * @property {string|null} [resource] TestIamPermissionsRegionHealthAggregationPolicyRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionHealthAggregationPolicyRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionDiskRequest. + * Constructs a new TestIamPermissionsRegionHealthAggregationPolicyRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionDiskRequest. - * @implements ITestIamPermissionsRegionDiskRequest + * @classdesc Represents a TestIamPermissionsRegionHealthAggregationPolicyRequest. + * @implements ITestIamPermissionsRegionHealthAggregationPolicyRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionDiskRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthAggregationPolicyRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionDiskRequest(properties) { + function TestIamPermissionsRegionHealthAggregationPolicyRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1299041,59 +1319289,59 @@ } /** - * TestIamPermissionsRegionDiskRequest project. + * TestIamPermissionsRegionHealthAggregationPolicyRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @instance */ - TestIamPermissionsRegionDiskRequest.prototype.project = ""; + TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.project = ""; /** - * TestIamPermissionsRegionDiskRequest region. + * TestIamPermissionsRegionHealthAggregationPolicyRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @instance */ - TestIamPermissionsRegionDiskRequest.prototype.region = ""; + TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.region = ""; /** - * TestIamPermissionsRegionDiskRequest resource. + * TestIamPermissionsRegionHealthAggregationPolicyRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @instance */ - TestIamPermissionsRegionDiskRequest.prototype.resource = ""; + TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionDiskRequest testPermissionsRequestResource. + * TestIamPermissionsRegionHealthAggregationPolicyRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @instance */ - TestIamPermissionsRegionDiskRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionDiskRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionHealthAggregationPolicyRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionDiskRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} TestIamPermissionsRegionDiskRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthAggregationPolicyRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} TestIamPermissionsRegionHealthAggregationPolicyRequest instance */ - TestIamPermissionsRegionDiskRequest.create = function create(properties) { - return new TestIamPermissionsRegionDiskRequest(properties); + TestIamPermissionsRegionHealthAggregationPolicyRequest.create = function create(properties) { + return new TestIamPermissionsRegionHealthAggregationPolicyRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionDiskRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionHealthAggregationPolicyRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionDiskRequest} message TestIamPermissionsRegionDiskRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthAggregationPolicyRequest} message TestIamPermissionsRegionHealthAggregationPolicyRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionDiskRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionHealthAggregationPolicyRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1299108,33 +1319356,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionDiskRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionHealthAggregationPolicyRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionDiskRequest} message TestIamPermissionsRegionDiskRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthAggregationPolicyRequest} message TestIamPermissionsRegionHealthAggregationPolicyRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionDiskRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionHealthAggregationPolicyRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionDiskRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionHealthAggregationPolicyRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} TestIamPermissionsRegionDiskRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} TestIamPermissionsRegionHealthAggregationPolicyRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionDiskRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionHealthAggregationPolicyRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1299165,30 +1319413,30 @@ }; /** - * Decodes a TestIamPermissionsRegionDiskRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionHealthAggregationPolicyRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} TestIamPermissionsRegionDiskRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} TestIamPermissionsRegionHealthAggregationPolicyRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionDiskRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionHealthAggregationPolicyRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionDiskRequest message. + * Verifies a TestIamPermissionsRegionHealthAggregationPolicyRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionDiskRequest.verify = function verify(message) { + TestIamPermissionsRegionHealthAggregationPolicyRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1299209,17 +1319457,17 @@ }; /** - * Creates a TestIamPermissionsRegionDiskRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionHealthAggregationPolicyRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} TestIamPermissionsRegionDiskRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} TestIamPermissionsRegionHealthAggregationPolicyRequest */ - TestIamPermissionsRegionDiskRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest) + TestIamPermissionsRegionHealthAggregationPolicyRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1299228,22 +1319476,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionDiskRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionHealthAggregationPolicyRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest} message TestIamPermissionsRegionDiskRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} message TestIamPermissionsRegionHealthAggregationPolicyRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionDiskRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionHealthAggregationPolicyRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1299265,55 +1319513,55 @@ }; /** - * Converts this TestIamPermissionsRegionDiskRequest to JSON. + * Converts this TestIamPermissionsRegionHealthAggregationPolicyRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionDiskRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionDiskRequest + * Gets the default type url for TestIamPermissionsRegionHealthAggregationPolicyRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionDiskRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionHealthAggregationPolicyRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionDiskRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest"; }; - return TestIamPermissionsRegionDiskRequest; + return TestIamPermissionsRegionHealthAggregationPolicyRequest; })(); - v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest = (function() { + v1beta.TestIamPermissionsRegionHealthCheckRequest = (function() { /** - * Properties of a TestIamPermissionsRegionHealthAggregationPolicyRequest. + * Properties of a TestIamPermissionsRegionHealthCheckRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionHealthAggregationPolicyRequest - * @property {string|null} [project] TestIamPermissionsRegionHealthAggregationPolicyRequest project - * @property {string|null} [region] TestIamPermissionsRegionHealthAggregationPolicyRequest region - * @property {string|null} [resource] TestIamPermissionsRegionHealthAggregationPolicyRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionHealthAggregationPolicyRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionHealthCheckRequest + * @property {string|null} [project] TestIamPermissionsRegionHealthCheckRequest project + * @property {string|null} [region] TestIamPermissionsRegionHealthCheckRequest region + * @property {string|null} [resource] TestIamPermissionsRegionHealthCheckRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionHealthCheckRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionHealthAggregationPolicyRequest. + * Constructs a new TestIamPermissionsRegionHealthCheckRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionHealthAggregationPolicyRequest. - * @implements ITestIamPermissionsRegionHealthAggregationPolicyRequest + * @classdesc Represents a TestIamPermissionsRegionHealthCheckRequest. + * @implements ITestIamPermissionsRegionHealthCheckRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthAggregationPolicyRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionHealthAggregationPolicyRequest(properties) { + function TestIamPermissionsRegionHealthCheckRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1299321,59 +1319569,59 @@ } /** - * TestIamPermissionsRegionHealthAggregationPolicyRequest project. + * TestIamPermissionsRegionHealthCheckRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @instance */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.project = ""; + TestIamPermissionsRegionHealthCheckRequest.prototype.project = ""; /** - * TestIamPermissionsRegionHealthAggregationPolicyRequest region. + * TestIamPermissionsRegionHealthCheckRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @instance */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.region = ""; + TestIamPermissionsRegionHealthCheckRequest.prototype.region = ""; /** - * TestIamPermissionsRegionHealthAggregationPolicyRequest resource. + * TestIamPermissionsRegionHealthCheckRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @instance */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.resource = ""; + TestIamPermissionsRegionHealthCheckRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionHealthAggregationPolicyRequest testPermissionsRequestResource. + * TestIamPermissionsRegionHealthCheckRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @instance */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionHealthCheckRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionHealthAggregationPolicyRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionHealthCheckRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthAggregationPolicyRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} TestIamPermissionsRegionHealthAggregationPolicyRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} TestIamPermissionsRegionHealthCheckRequest instance */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.create = function create(properties) { - return new TestIamPermissionsRegionHealthAggregationPolicyRequest(properties); + TestIamPermissionsRegionHealthCheckRequest.create = function create(properties) { + return new TestIamPermissionsRegionHealthCheckRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionHealthAggregationPolicyRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionHealthCheckRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthAggregationPolicyRequest} message TestIamPermissionsRegionHealthAggregationPolicyRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckRequest} message TestIamPermissionsRegionHealthCheckRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionHealthCheckRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1299388,33 +1319636,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionHealthAggregationPolicyRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionHealthCheckRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthAggregationPolicyRequest} message TestIamPermissionsRegionHealthAggregationPolicyRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckRequest} message TestIamPermissionsRegionHealthCheckRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionHealthCheckRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionHealthAggregationPolicyRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionHealthCheckRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} TestIamPermissionsRegionHealthAggregationPolicyRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} TestIamPermissionsRegionHealthCheckRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionHealthCheckRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1299445,30 +1319693,30 @@ }; /** - * Decodes a TestIamPermissionsRegionHealthAggregationPolicyRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionHealthCheckRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} TestIamPermissionsRegionHealthAggregationPolicyRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} TestIamPermissionsRegionHealthCheckRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionHealthCheckRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionHealthAggregationPolicyRequest message. + * Verifies a TestIamPermissionsRegionHealthCheckRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.verify = function verify(message) { + TestIamPermissionsRegionHealthCheckRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1299489,17 +1319737,17 @@ }; /** - * Creates a TestIamPermissionsRegionHealthAggregationPolicyRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionHealthCheckRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} TestIamPermissionsRegionHealthAggregationPolicyRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} TestIamPermissionsRegionHealthCheckRequest */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest) + TestIamPermissionsRegionHealthCheckRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1299508,22 +1319756,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionHealthAggregationPolicyRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionHealthCheckRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest} message TestIamPermissionsRegionHealthAggregationPolicyRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} message TestIamPermissionsRegionHealthCheckRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionHealthCheckRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1299545,55 +1319793,55 @@ }; /** - * Converts this TestIamPermissionsRegionHealthAggregationPolicyRequest to JSON. + * Converts this TestIamPermissionsRegionHealthCheckRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionHealthCheckRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionHealthAggregationPolicyRequest + * Gets the default type url for TestIamPermissionsRegionHealthCheckRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionHealthAggregationPolicyRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionHealthCheckRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionHealthAggregationPolicyRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest"; }; - return TestIamPermissionsRegionHealthAggregationPolicyRequest; + return TestIamPermissionsRegionHealthCheckRequest; })(); - v1beta.TestIamPermissionsRegionHealthCheckRequest = (function() { + v1beta.TestIamPermissionsRegionHealthCheckServiceRequest = (function() { /** - * Properties of a TestIamPermissionsRegionHealthCheckRequest. + * Properties of a TestIamPermissionsRegionHealthCheckServiceRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionHealthCheckRequest - * @property {string|null} [project] TestIamPermissionsRegionHealthCheckRequest project - * @property {string|null} [region] TestIamPermissionsRegionHealthCheckRequest region - * @property {string|null} [resource] TestIamPermissionsRegionHealthCheckRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionHealthCheckRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionHealthCheckServiceRequest + * @property {string|null} [project] TestIamPermissionsRegionHealthCheckServiceRequest project + * @property {string|null} [region] TestIamPermissionsRegionHealthCheckServiceRequest region + * @property {string|null} [resource] TestIamPermissionsRegionHealthCheckServiceRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionHealthCheckServiceRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionHealthCheckRequest. + * Constructs a new TestIamPermissionsRegionHealthCheckServiceRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionHealthCheckRequest. - * @implements ITestIamPermissionsRegionHealthCheckRequest + * @classdesc Represents a TestIamPermissionsRegionHealthCheckServiceRequest. + * @implements ITestIamPermissionsRegionHealthCheckServiceRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckServiceRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionHealthCheckRequest(properties) { + function TestIamPermissionsRegionHealthCheckServiceRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1299601,59 +1319849,59 @@ } /** - * TestIamPermissionsRegionHealthCheckRequest project. + * TestIamPermissionsRegionHealthCheckServiceRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @instance */ - TestIamPermissionsRegionHealthCheckRequest.prototype.project = ""; + TestIamPermissionsRegionHealthCheckServiceRequest.prototype.project = ""; /** - * TestIamPermissionsRegionHealthCheckRequest region. + * TestIamPermissionsRegionHealthCheckServiceRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @instance */ - TestIamPermissionsRegionHealthCheckRequest.prototype.region = ""; + TestIamPermissionsRegionHealthCheckServiceRequest.prototype.region = ""; /** - * TestIamPermissionsRegionHealthCheckRequest resource. + * TestIamPermissionsRegionHealthCheckServiceRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @instance */ - TestIamPermissionsRegionHealthCheckRequest.prototype.resource = ""; + TestIamPermissionsRegionHealthCheckServiceRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionHealthCheckRequest testPermissionsRequestResource. + * TestIamPermissionsRegionHealthCheckServiceRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @instance */ - TestIamPermissionsRegionHealthCheckRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionHealthCheckServiceRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionHealthCheckRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionHealthCheckServiceRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} TestIamPermissionsRegionHealthCheckRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckServiceRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} TestIamPermissionsRegionHealthCheckServiceRequest instance */ - TestIamPermissionsRegionHealthCheckRequest.create = function create(properties) { - return new TestIamPermissionsRegionHealthCheckRequest(properties); + TestIamPermissionsRegionHealthCheckServiceRequest.create = function create(properties) { + return new TestIamPermissionsRegionHealthCheckServiceRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionHealthCheckRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionHealthCheckServiceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckRequest} message TestIamPermissionsRegionHealthCheckRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckServiceRequest} message TestIamPermissionsRegionHealthCheckServiceRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionHealthCheckRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionHealthCheckServiceRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1299668,33 +1319916,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionHealthCheckRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionHealthCheckServiceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckRequest} message TestIamPermissionsRegionHealthCheckRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckServiceRequest} message TestIamPermissionsRegionHealthCheckServiceRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionHealthCheckRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionHealthCheckServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionHealthCheckRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionHealthCheckServiceRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} TestIamPermissionsRegionHealthCheckRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} TestIamPermissionsRegionHealthCheckServiceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionHealthCheckRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionHealthCheckServiceRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1299725,30 +1319973,30 @@ }; /** - * Decodes a TestIamPermissionsRegionHealthCheckRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionHealthCheckServiceRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} TestIamPermissionsRegionHealthCheckRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} TestIamPermissionsRegionHealthCheckServiceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionHealthCheckRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionHealthCheckServiceRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionHealthCheckRequest message. + * Verifies a TestIamPermissionsRegionHealthCheckServiceRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionHealthCheckRequest.verify = function verify(message) { + TestIamPermissionsRegionHealthCheckServiceRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1299769,17 +1320017,17 @@ }; /** - * Creates a TestIamPermissionsRegionHealthCheckRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionHealthCheckServiceRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} TestIamPermissionsRegionHealthCheckRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} TestIamPermissionsRegionHealthCheckServiceRequest */ - TestIamPermissionsRegionHealthCheckRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest) + TestIamPermissionsRegionHealthCheckServiceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1299788,22 +1320036,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionHealthCheckRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionHealthCheckServiceRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest} message TestIamPermissionsRegionHealthCheckRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} message TestIamPermissionsRegionHealthCheckServiceRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionHealthCheckRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionHealthCheckServiceRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1299825,55 +1320073,55 @@ }; /** - * Converts this TestIamPermissionsRegionHealthCheckRequest to JSON. + * Converts this TestIamPermissionsRegionHealthCheckServiceRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionHealthCheckRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionHealthCheckServiceRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionHealthCheckRequest + * Gets the default type url for TestIamPermissionsRegionHealthCheckServiceRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionHealthCheckRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionHealthCheckServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest"; }; - return TestIamPermissionsRegionHealthCheckRequest; + return TestIamPermissionsRegionHealthCheckServiceRequest; })(); - v1beta.TestIamPermissionsRegionHealthCheckServiceRequest = (function() { + v1beta.TestIamPermissionsRegionHealthSourceRequest = (function() { /** - * Properties of a TestIamPermissionsRegionHealthCheckServiceRequest. + * Properties of a TestIamPermissionsRegionHealthSourceRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionHealthCheckServiceRequest - * @property {string|null} [project] TestIamPermissionsRegionHealthCheckServiceRequest project - * @property {string|null} [region] TestIamPermissionsRegionHealthCheckServiceRequest region - * @property {string|null} [resource] TestIamPermissionsRegionHealthCheckServiceRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionHealthCheckServiceRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionHealthSourceRequest + * @property {string|null} [project] TestIamPermissionsRegionHealthSourceRequest project + * @property {string|null} [region] TestIamPermissionsRegionHealthSourceRequest region + * @property {string|null} [resource] TestIamPermissionsRegionHealthSourceRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionHealthSourceRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionHealthCheckServiceRequest. + * Constructs a new TestIamPermissionsRegionHealthSourceRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionHealthCheckServiceRequest. - * @implements ITestIamPermissionsRegionHealthCheckServiceRequest + * @classdesc Represents a TestIamPermissionsRegionHealthSourceRequest. + * @implements ITestIamPermissionsRegionHealthSourceRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckServiceRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthSourceRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionHealthCheckServiceRequest(properties) { + function TestIamPermissionsRegionHealthSourceRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1299881,59 +1320129,59 @@ } /** - * TestIamPermissionsRegionHealthCheckServiceRequest project. + * TestIamPermissionsRegionHealthSourceRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @instance */ - TestIamPermissionsRegionHealthCheckServiceRequest.prototype.project = ""; + TestIamPermissionsRegionHealthSourceRequest.prototype.project = ""; /** - * TestIamPermissionsRegionHealthCheckServiceRequest region. + * TestIamPermissionsRegionHealthSourceRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @instance */ - TestIamPermissionsRegionHealthCheckServiceRequest.prototype.region = ""; + TestIamPermissionsRegionHealthSourceRequest.prototype.region = ""; /** - * TestIamPermissionsRegionHealthCheckServiceRequest resource. + * TestIamPermissionsRegionHealthSourceRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @instance */ - TestIamPermissionsRegionHealthCheckServiceRequest.prototype.resource = ""; + TestIamPermissionsRegionHealthSourceRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionHealthCheckServiceRequest testPermissionsRequestResource. + * TestIamPermissionsRegionHealthSourceRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @instance */ - TestIamPermissionsRegionHealthCheckServiceRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionHealthSourceRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionHealthCheckServiceRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionHealthSourceRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckServiceRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} TestIamPermissionsRegionHealthCheckServiceRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthSourceRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} TestIamPermissionsRegionHealthSourceRequest instance */ - TestIamPermissionsRegionHealthCheckServiceRequest.create = function create(properties) { - return new TestIamPermissionsRegionHealthCheckServiceRequest(properties); + TestIamPermissionsRegionHealthSourceRequest.create = function create(properties) { + return new TestIamPermissionsRegionHealthSourceRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionHealthCheckServiceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionHealthSourceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckServiceRequest} message TestIamPermissionsRegionHealthCheckServiceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthSourceRequest} message TestIamPermissionsRegionHealthSourceRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionHealthCheckServiceRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionHealthSourceRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1299948,33 +1320196,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionHealthCheckServiceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionHealthSourceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthCheckServiceRequest} message TestIamPermissionsRegionHealthCheckServiceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthSourceRequest} message TestIamPermissionsRegionHealthSourceRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionHealthCheckServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionHealthSourceRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionHealthCheckServiceRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionHealthSourceRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} TestIamPermissionsRegionHealthCheckServiceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} TestIamPermissionsRegionHealthSourceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionHealthCheckServiceRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionHealthSourceRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1300005,30 +1320253,30 @@ }; /** - * Decodes a TestIamPermissionsRegionHealthCheckServiceRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionHealthSourceRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} TestIamPermissionsRegionHealthCheckServiceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} TestIamPermissionsRegionHealthSourceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionHealthCheckServiceRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionHealthSourceRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionHealthCheckServiceRequest message. + * Verifies a TestIamPermissionsRegionHealthSourceRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionHealthCheckServiceRequest.verify = function verify(message) { + TestIamPermissionsRegionHealthSourceRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1300049,17 +1320297,17 @@ }; /** - * Creates a TestIamPermissionsRegionHealthCheckServiceRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionHealthSourceRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} TestIamPermissionsRegionHealthCheckServiceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} TestIamPermissionsRegionHealthSourceRequest */ - TestIamPermissionsRegionHealthCheckServiceRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest) + TestIamPermissionsRegionHealthSourceRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1300068,22 +1320316,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionHealthCheckServiceRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionHealthSourceRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest} message TestIamPermissionsRegionHealthCheckServiceRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} message TestIamPermissionsRegionHealthSourceRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionHealthCheckServiceRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionHealthSourceRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1300105,55 +1320353,55 @@ }; /** - * Converts this TestIamPermissionsRegionHealthCheckServiceRequest to JSON. + * Converts this TestIamPermissionsRegionHealthSourceRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionHealthCheckServiceRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionHealthSourceRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionHealthCheckServiceRequest + * Gets the default type url for TestIamPermissionsRegionHealthSourceRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionHealthCheckServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionHealthSourceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionHealthCheckServiceRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest"; }; - return TestIamPermissionsRegionHealthCheckServiceRequest; + return TestIamPermissionsRegionHealthSourceRequest; })(); - v1beta.TestIamPermissionsRegionHealthSourceRequest = (function() { + v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest = (function() { /** - * Properties of a TestIamPermissionsRegionHealthSourceRequest. + * Properties of a TestIamPermissionsRegionInstanceGroupManagerRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionHealthSourceRequest - * @property {string|null} [project] TestIamPermissionsRegionHealthSourceRequest project - * @property {string|null} [region] TestIamPermissionsRegionHealthSourceRequest region - * @property {string|null} [resource] TestIamPermissionsRegionHealthSourceRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionHealthSourceRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionInstanceGroupManagerRequest + * @property {string|null} [project] TestIamPermissionsRegionInstanceGroupManagerRequest project + * @property {string|null} [region] TestIamPermissionsRegionInstanceGroupManagerRequest region + * @property {string|null} [resource] TestIamPermissionsRegionInstanceGroupManagerRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionInstanceGroupManagerRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionHealthSourceRequest. + * Constructs a new TestIamPermissionsRegionInstanceGroupManagerRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionHealthSourceRequest. - * @implements ITestIamPermissionsRegionHealthSourceRequest + * @classdesc Represents a TestIamPermissionsRegionInstanceGroupManagerRequest. + * @implements ITestIamPermissionsRegionInstanceGroupManagerRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthSourceRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupManagerRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionHealthSourceRequest(properties) { + function TestIamPermissionsRegionInstanceGroupManagerRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1300161,59 +1320409,59 @@ } /** - * TestIamPermissionsRegionHealthSourceRequest project. + * TestIamPermissionsRegionInstanceGroupManagerRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @instance */ - TestIamPermissionsRegionHealthSourceRequest.prototype.project = ""; + TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.project = ""; /** - * TestIamPermissionsRegionHealthSourceRequest region. + * TestIamPermissionsRegionInstanceGroupManagerRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @instance */ - TestIamPermissionsRegionHealthSourceRequest.prototype.region = ""; + TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.region = ""; /** - * TestIamPermissionsRegionHealthSourceRequest resource. + * TestIamPermissionsRegionInstanceGroupManagerRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @instance */ - TestIamPermissionsRegionHealthSourceRequest.prototype.resource = ""; + TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionHealthSourceRequest testPermissionsRequestResource. + * TestIamPermissionsRegionInstanceGroupManagerRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @instance */ - TestIamPermissionsRegionHealthSourceRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionHealthSourceRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionInstanceGroupManagerRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthSourceRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} TestIamPermissionsRegionHealthSourceRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupManagerRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} TestIamPermissionsRegionInstanceGroupManagerRequest instance */ - TestIamPermissionsRegionHealthSourceRequest.create = function create(properties) { - return new TestIamPermissionsRegionHealthSourceRequest(properties); + TestIamPermissionsRegionInstanceGroupManagerRequest.create = function create(properties) { + return new TestIamPermissionsRegionInstanceGroupManagerRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionHealthSourceRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionInstanceGroupManagerRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthSourceRequest} message TestIamPermissionsRegionHealthSourceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupManagerRequest} message TestIamPermissionsRegionInstanceGroupManagerRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionHealthSourceRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionInstanceGroupManagerRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1300228,33 +1320476,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionHealthSourceRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionInstanceGroupManagerRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionHealthSourceRequest} message TestIamPermissionsRegionHealthSourceRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupManagerRequest} message TestIamPermissionsRegionInstanceGroupManagerRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionHealthSourceRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionInstanceGroupManagerRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionHealthSourceRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionInstanceGroupManagerRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} TestIamPermissionsRegionHealthSourceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} TestIamPermissionsRegionInstanceGroupManagerRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionHealthSourceRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionInstanceGroupManagerRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1300285,30 +1320533,30 @@ }; /** - * Decodes a TestIamPermissionsRegionHealthSourceRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionInstanceGroupManagerRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} TestIamPermissionsRegionHealthSourceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} TestIamPermissionsRegionInstanceGroupManagerRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionHealthSourceRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionInstanceGroupManagerRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionHealthSourceRequest message. + * Verifies a TestIamPermissionsRegionInstanceGroupManagerRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionHealthSourceRequest.verify = function verify(message) { + TestIamPermissionsRegionInstanceGroupManagerRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1300329,17 +1320577,17 @@ }; /** - * Creates a TestIamPermissionsRegionHealthSourceRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionInstanceGroupManagerRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} TestIamPermissionsRegionHealthSourceRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} TestIamPermissionsRegionInstanceGroupManagerRequest */ - TestIamPermissionsRegionHealthSourceRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest) + TestIamPermissionsRegionInstanceGroupManagerRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1300348,22 +1320596,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionHealthSourceRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionInstanceGroupManagerRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest} message TestIamPermissionsRegionHealthSourceRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} message TestIamPermissionsRegionInstanceGroupManagerRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionHealthSourceRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionInstanceGroupManagerRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1300385,55 +1320633,55 @@ }; /** - * Converts this TestIamPermissionsRegionHealthSourceRequest to JSON. + * Converts this TestIamPermissionsRegionInstanceGroupManagerRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionHealthSourceRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionHealthSourceRequest + * Gets the default type url for TestIamPermissionsRegionInstanceGroupManagerRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionHealthSourceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionInstanceGroupManagerRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionHealthSourceRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest"; }; - return TestIamPermissionsRegionHealthSourceRequest; + return TestIamPermissionsRegionInstanceGroupManagerRequest; })(); - v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest = (function() { + v1beta.TestIamPermissionsRegionInstanceGroupRequest = (function() { /** - * Properties of a TestIamPermissionsRegionInstanceGroupManagerRequest. + * Properties of a TestIamPermissionsRegionInstanceGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionInstanceGroupManagerRequest - * @property {string|null} [project] TestIamPermissionsRegionInstanceGroupManagerRequest project - * @property {string|null} [region] TestIamPermissionsRegionInstanceGroupManagerRequest region - * @property {string|null} [resource] TestIamPermissionsRegionInstanceGroupManagerRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionInstanceGroupManagerRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionInstanceGroupRequest + * @property {string|null} [project] TestIamPermissionsRegionInstanceGroupRequest project + * @property {string|null} [region] TestIamPermissionsRegionInstanceGroupRequest region + * @property {string|null} [resource] TestIamPermissionsRegionInstanceGroupRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionInstanceGroupRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionInstanceGroupManagerRequest. + * Constructs a new TestIamPermissionsRegionInstanceGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionInstanceGroupManagerRequest. - * @implements ITestIamPermissionsRegionInstanceGroupManagerRequest + * @classdesc Represents a TestIamPermissionsRegionInstanceGroupRequest. + * @implements ITestIamPermissionsRegionInstanceGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupManagerRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionInstanceGroupManagerRequest(properties) { + function TestIamPermissionsRegionInstanceGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1300441,59 +1320689,59 @@ } /** - * TestIamPermissionsRegionInstanceGroupManagerRequest project. + * TestIamPermissionsRegionInstanceGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @instance */ - TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.project = ""; + TestIamPermissionsRegionInstanceGroupRequest.prototype.project = ""; /** - * TestIamPermissionsRegionInstanceGroupManagerRequest region. + * TestIamPermissionsRegionInstanceGroupRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @instance */ - TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.region = ""; + TestIamPermissionsRegionInstanceGroupRequest.prototype.region = ""; /** - * TestIamPermissionsRegionInstanceGroupManagerRequest resource. + * TestIamPermissionsRegionInstanceGroupRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @instance */ - TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.resource = ""; + TestIamPermissionsRegionInstanceGroupRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionInstanceGroupManagerRequest testPermissionsRequestResource. + * TestIamPermissionsRegionInstanceGroupRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @instance */ - TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionInstanceGroupRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionInstanceGroupManagerRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionInstanceGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupManagerRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} TestIamPermissionsRegionInstanceGroupManagerRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} TestIamPermissionsRegionInstanceGroupRequest instance */ - TestIamPermissionsRegionInstanceGroupManagerRequest.create = function create(properties) { - return new TestIamPermissionsRegionInstanceGroupManagerRequest(properties); + TestIamPermissionsRegionInstanceGroupRequest.create = function create(properties) { + return new TestIamPermissionsRegionInstanceGroupRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionInstanceGroupManagerRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionInstanceGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupManagerRequest} message TestIamPermissionsRegionInstanceGroupManagerRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupRequest} message TestIamPermissionsRegionInstanceGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionInstanceGroupManagerRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionInstanceGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1300508,33 +1320756,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionInstanceGroupManagerRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionInstanceGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupManagerRequest} message TestIamPermissionsRegionInstanceGroupManagerRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupRequest} message TestIamPermissionsRegionInstanceGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionInstanceGroupManagerRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionInstanceGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionInstanceGroupManagerRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionInstanceGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} TestIamPermissionsRegionInstanceGroupManagerRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} TestIamPermissionsRegionInstanceGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionInstanceGroupManagerRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionInstanceGroupRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1300565,30 +1320813,30 @@ }; /** - * Decodes a TestIamPermissionsRegionInstanceGroupManagerRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionInstanceGroupRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} TestIamPermissionsRegionInstanceGroupManagerRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} TestIamPermissionsRegionInstanceGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionInstanceGroupManagerRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionInstanceGroupRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionInstanceGroupManagerRequest message. + * Verifies a TestIamPermissionsRegionInstanceGroupRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionInstanceGroupManagerRequest.verify = function verify(message) { + TestIamPermissionsRegionInstanceGroupRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1300609,17 +1320857,17 @@ }; /** - * Creates a TestIamPermissionsRegionInstanceGroupManagerRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionInstanceGroupRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} TestIamPermissionsRegionInstanceGroupManagerRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} TestIamPermissionsRegionInstanceGroupRequest */ - TestIamPermissionsRegionInstanceGroupManagerRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest) + TestIamPermissionsRegionInstanceGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1300628,22 +1320876,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionInstanceGroupManagerRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionInstanceGroupRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest} message TestIamPermissionsRegionInstanceGroupManagerRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} message TestIamPermissionsRegionInstanceGroupRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionInstanceGroupManagerRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionInstanceGroupRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1300665,55 +1320913,55 @@ }; /** - * Converts this TestIamPermissionsRegionInstanceGroupManagerRequest to JSON. + * Converts this TestIamPermissionsRegionInstanceGroupRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionInstanceGroupManagerRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionInstanceGroupRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionInstanceGroupManagerRequest + * Gets the default type url for TestIamPermissionsRegionInstanceGroupRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionInstanceGroupManagerRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionInstanceGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupManagerRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest"; }; - return TestIamPermissionsRegionInstanceGroupManagerRequest; + return TestIamPermissionsRegionInstanceGroupRequest; })(); - v1beta.TestIamPermissionsRegionInstanceGroupRequest = (function() { + v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest = (function() { /** - * Properties of a TestIamPermissionsRegionInstanceGroupRequest. + * Properties of a TestIamPermissionsRegionInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @interface ITestIamPermissionsRegionInstanceGroupRequest - * @property {string|null} [project] TestIamPermissionsRegionInstanceGroupRequest project - * @property {string|null} [region] TestIamPermissionsRegionInstanceGroupRequest region - * @property {string|null} [resource] TestIamPermissionsRegionInstanceGroupRequest resource - * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionInstanceGroupRequest testPermissionsRequestResource + * @interface ITestIamPermissionsRegionInstantSnapshotGroupRequest + * @property {string|null} [project] TestIamPermissionsRegionInstantSnapshotGroupRequest project + * @property {string|null} [region] TestIamPermissionsRegionInstantSnapshotGroupRequest region + * @property {string|null} [resource] TestIamPermissionsRegionInstantSnapshotGroupRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsRegionInstantSnapshotGroupRequest testPermissionsRequestResource */ /** - * Constructs a new TestIamPermissionsRegionInstanceGroupRequest. + * Constructs a new TestIamPermissionsRegionInstantSnapshotGroupRequest. * @memberof google.cloud.compute.v1beta - * @classdesc Represents a TestIamPermissionsRegionInstanceGroupRequest. - * @implements ITestIamPermissionsRegionInstanceGroupRequest + * @classdesc Represents a TestIamPermissionsRegionInstantSnapshotGroupRequest. + * @implements ITestIamPermissionsRegionInstantSnapshotGroupRequest * @constructor - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupRequest=} [properties] Properties to set + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest=} [properties] Properties to set */ - function TestIamPermissionsRegionInstanceGroupRequest(properties) { + function TestIamPermissionsRegionInstantSnapshotGroupRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -1300721,59 +1320969,59 @@ } /** - * TestIamPermissionsRegionInstanceGroupRequest project. + * TestIamPermissionsRegionInstantSnapshotGroupRequest project. * @member {string} project - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @instance */ - TestIamPermissionsRegionInstanceGroupRequest.prototype.project = ""; + TestIamPermissionsRegionInstantSnapshotGroupRequest.prototype.project = ""; /** - * TestIamPermissionsRegionInstanceGroupRequest region. + * TestIamPermissionsRegionInstantSnapshotGroupRequest region. * @member {string} region - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @instance */ - TestIamPermissionsRegionInstanceGroupRequest.prototype.region = ""; + TestIamPermissionsRegionInstantSnapshotGroupRequest.prototype.region = ""; /** - * TestIamPermissionsRegionInstanceGroupRequest resource. + * TestIamPermissionsRegionInstantSnapshotGroupRequest resource. * @member {string} resource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @instance */ - TestIamPermissionsRegionInstanceGroupRequest.prototype.resource = ""; + TestIamPermissionsRegionInstantSnapshotGroupRequest.prototype.resource = ""; /** - * TestIamPermissionsRegionInstanceGroupRequest testPermissionsRequestResource. + * TestIamPermissionsRegionInstantSnapshotGroupRequest testPermissionsRequestResource. * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @instance */ - TestIamPermissionsRegionInstanceGroupRequest.prototype.testPermissionsRequestResource = null; + TestIamPermissionsRegionInstantSnapshotGroupRequest.prototype.testPermissionsRequestResource = null; /** - * Creates a new TestIamPermissionsRegionInstanceGroupRequest instance using the specified properties. + * Creates a new TestIamPermissionsRegionInstantSnapshotGroupRequest instance using the specified properties. * @function create - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupRequest=} [properties] Properties to set - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} TestIamPermissionsRegionInstanceGroupRequest instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest} TestIamPermissionsRegionInstantSnapshotGroupRequest instance */ - TestIamPermissionsRegionInstanceGroupRequest.create = function create(properties) { - return new TestIamPermissionsRegionInstanceGroupRequest(properties); + TestIamPermissionsRegionInstantSnapshotGroupRequest.create = function create(properties) { + return new TestIamPermissionsRegionInstantSnapshotGroupRequest(properties); }; /** - * Encodes the specified TestIamPermissionsRegionInstanceGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionInstantSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest.verify|verify} messages. * @function encode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupRequest} message TestIamPermissionsRegionInstanceGroupRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest} message TestIamPermissionsRegionInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionInstanceGroupRequest.encode = function encode(message, writer) { + TestIamPermissionsRegionInstantSnapshotGroupRequest.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1300788,33 +1321036,33 @@ }; /** - * Encodes the specified TestIamPermissionsRegionInstanceGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest.verify|verify} messages. + * Encodes the specified TestIamPermissionsRegionInstantSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest.verify|verify} messages. * @function encodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstanceGroupRequest} message TestIamPermissionsRegionInstanceGroupRequest message or plain object to encode + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest} message TestIamPermissionsRegionInstantSnapshotGroupRequest message or plain object to encode * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TestIamPermissionsRegionInstanceGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + TestIamPermissionsRegionInstantSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer).ldelim(); }; /** - * Decodes a TestIamPermissionsRegionInstanceGroupRequest message from the specified reader or buffer. + * Decodes a TestIamPermissionsRegionInstantSnapshotGroupRequest message from the specified reader or buffer. * @function decode - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Message length if known beforehand - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} TestIamPermissionsRegionInstanceGroupRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest} TestIamPermissionsRegionInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionInstanceGroupRequest.decode = function decode(reader, length, error) { + TestIamPermissionsRegionInstantSnapshotGroupRequest.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.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest(); while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -1300845,30 +1321093,30 @@ }; /** - * Decodes a TestIamPermissionsRegionInstanceGroupRequest message from the specified reader or buffer, length delimited. + * Decodes a TestIamPermissionsRegionInstantSnapshotGroupRequest message from the specified reader or buffer, length delimited. * @function decodeDelimited - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} TestIamPermissionsRegionInstanceGroupRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest} TestIamPermissionsRegionInstantSnapshotGroupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TestIamPermissionsRegionInstanceGroupRequest.decodeDelimited = function decodeDelimited(reader) { + TestIamPermissionsRegionInstantSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof $Reader)) reader = new $Reader(reader); return this.decode(reader, reader.uint32()); }; /** - * Verifies a TestIamPermissionsRegionInstanceGroupRequest message. + * Verifies a TestIamPermissionsRegionInstantSnapshotGroupRequest message. * @function verify - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TestIamPermissionsRegionInstanceGroupRequest.verify = function verify(message) { + TestIamPermissionsRegionInstantSnapshotGroupRequest.verify = function verify(message) { if (typeof message !== "object" || message === null) return "object expected"; if (message.project != null && message.hasOwnProperty("project")) @@ -1300889,17 +1321137,17 @@ }; /** - * Creates a TestIamPermissionsRegionInstanceGroupRequest message from a plain object. Also converts values to their respective internal types. + * Creates a TestIamPermissionsRegionInstantSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static * @param {Object.} object Plain object - * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} TestIamPermissionsRegionInstanceGroupRequest + * @returns {google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest} TestIamPermissionsRegionInstantSnapshotGroupRequest */ - TestIamPermissionsRegionInstanceGroupRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest) + TestIamPermissionsRegionInstantSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest) return object; - var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest(); + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest(); if (object.project != null) message.project = String(object.project); if (object.region != null) @@ -1300908,22 +1321156,22 @@ message.resource = String(object.resource); if (object.testPermissionsRequestResource != null) { if (typeof object.testPermissionsRequestResource !== "object") - throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest.testPermissionsRequestResource: object expected"); + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest.testPermissionsRequestResource: object expected"); message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); } return message; }; /** - * Creates a plain object from a TestIamPermissionsRegionInstanceGroupRequest message. Also converts values to other types if specified. + * Creates a plain object from a TestIamPermissionsRegionInstantSnapshotGroupRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static - * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest} message TestIamPermissionsRegionInstanceGroupRequest + * @param {google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest} message TestIamPermissionsRegionInstantSnapshotGroupRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TestIamPermissionsRegionInstanceGroupRequest.toObject = function toObject(message, options) { + TestIamPermissionsRegionInstantSnapshotGroupRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -1300945,32 +1321193,32 @@ }; /** - * Converts this TestIamPermissionsRegionInstanceGroupRequest to JSON. + * Converts this TestIamPermissionsRegionInstantSnapshotGroupRequest to JSON. * @function toJSON - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @instance * @returns {Object.} JSON object */ - TestIamPermissionsRegionInstanceGroupRequest.prototype.toJSON = function toJSON() { + TestIamPermissionsRegionInstantSnapshotGroupRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for TestIamPermissionsRegionInstanceGroupRequest + * Gets the default type url for TestIamPermissionsRegionInstantSnapshotGroupRequest * @function getTypeUrl - * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest + * @memberof google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - TestIamPermissionsRegionInstanceGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TestIamPermissionsRegionInstantSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionInstanceGroupRequest"; + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest"; }; - return TestIamPermissionsRegionInstanceGroupRequest; + return TestIamPermissionsRegionInstantSnapshotGroupRequest; })(); v1beta.TestIamPermissionsRegionInstantSnapshotRequest = (function() { @@ -1306013,6 +1326261,263 @@ return TestIamPermissionsServiceAttachmentRequest; })(); + v1beta.TestIamPermissionsSnapshotGroupRequest = (function() { + + /** + * Properties of a TestIamPermissionsSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @interface ITestIamPermissionsSnapshotGroupRequest + * @property {string|null} [project] TestIamPermissionsSnapshotGroupRequest project + * @property {string|null} [resource] TestIamPermissionsSnapshotGroupRequest resource + * @property {google.cloud.compute.v1beta.ITestPermissionsRequest|null} [testPermissionsRequestResource] TestIamPermissionsSnapshotGroupRequest testPermissionsRequestResource + */ + + /** + * Constructs a new TestIamPermissionsSnapshotGroupRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a TestIamPermissionsSnapshotGroupRequest. + * @implements ITestIamPermissionsSnapshotGroupRequest + * @constructor + * @param {google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest=} [properties] Properties to set + */ + function TestIamPermissionsSnapshotGroupRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TestIamPermissionsSnapshotGroupRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @instance + */ + TestIamPermissionsSnapshotGroupRequest.prototype.project = ""; + + /** + * TestIamPermissionsSnapshotGroupRequest resource. + * @member {string} resource + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @instance + */ + TestIamPermissionsSnapshotGroupRequest.prototype.resource = ""; + + /** + * TestIamPermissionsSnapshotGroupRequest testPermissionsRequestResource. + * @member {google.cloud.compute.v1beta.ITestPermissionsRequest|null|undefined} testPermissionsRequestResource + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @instance + */ + TestIamPermissionsSnapshotGroupRequest.prototype.testPermissionsRequestResource = null; + + /** + * Creates a new TestIamPermissionsSnapshotGroupRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest} TestIamPermissionsSnapshotGroupRequest instance + */ + TestIamPermissionsSnapshotGroupRequest.create = function create(properties) { + return new TestIamPermissionsSnapshotGroupRequest(properties); + }; + + /** + * Encodes the specified TestIamPermissionsSnapshotGroupRequest message. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest} message TestIamPermissionsSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsSnapshotGroupRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) + writer.uint32(/* id 195806222, wireType 2 =*/1566449778).string(message.resource); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.testPermissionsRequestResource != null && Object.hasOwnProperty.call(message, "testPermissionsRequestResource")) + $root.google.cloud.compute.v1beta.TestPermissionsRequest.encode(message.testPermissionsRequestResource, writer.uint32(/* id 439214758, wireType 2 =*/3513718066).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified TestIamPermissionsSnapshotGroupRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest} message TestIamPermissionsSnapshotGroupRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TestIamPermissionsSnapshotGroupRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TestIamPermissionsSnapshotGroupRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest} TestIamPermissionsSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsSnapshotGroupRequest.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.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 227560217: { + message.project = reader.string(); + break; + } + case 195806222: { + message.resource = reader.string(); + break; + } + case 439214758: { + message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.decode(reader, reader.uint32()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a TestIamPermissionsSnapshotGroupRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest} TestIamPermissionsSnapshotGroupRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TestIamPermissionsSnapshotGroupRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TestIamPermissionsSnapshotGroupRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TestIamPermissionsSnapshotGroupRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.resource != null && message.hasOwnProperty("resource")) + if (!$util.isString(message.resource)) + return "resource: string expected"; + if (message.testPermissionsRequestResource != null && message.hasOwnProperty("testPermissionsRequestResource")) { + var error = $root.google.cloud.compute.v1beta.TestPermissionsRequest.verify(message.testPermissionsRequestResource); + if (error) + return "testPermissionsRequestResource." + error; + } + return null; + }; + + /** + * Creates a TestIamPermissionsSnapshotGroupRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest} TestIamPermissionsSnapshotGroupRequest + */ + TestIamPermissionsSnapshotGroupRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest(); + if (object.project != null) + message.project = String(object.project); + if (object.resource != null) + message.resource = String(object.resource); + if (object.testPermissionsRequestResource != null) { + if (typeof object.testPermissionsRequestResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest.testPermissionsRequestResource: object expected"); + message.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.fromObject(object.testPermissionsRequestResource); + } + return message; + }; + + /** + * Creates a plain object from a TestIamPermissionsSnapshotGroupRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest} message TestIamPermissionsSnapshotGroupRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TestIamPermissionsSnapshotGroupRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.resource = ""; + object.project = ""; + object.testPermissionsRequestResource = null; + } + if (message.resource != null && message.hasOwnProperty("resource")) + object.resource = message.resource; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.testPermissionsRequestResource != null && message.hasOwnProperty("testPermissionsRequestResource")) + object.testPermissionsRequestResource = $root.google.cloud.compute.v1beta.TestPermissionsRequest.toObject(message.testPermissionsRequestResource, options); + return object; + }; + + /** + * Converts this TestIamPermissionsSnapshotGroupRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @instance + * @returns {Object.} JSON object + */ + TestIamPermissionsSnapshotGroupRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TestIamPermissionsSnapshotGroupRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TestIamPermissionsSnapshotGroupRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest"; + }; + + return TestIamPermissionsSnapshotGroupRequest; + })(); + v1beta.TestIamPermissionsSnapshotRequest = (function() { /** @@ -1315777,6 +1336282,323 @@ return UpdateLicenseRequest; })(); + v1beta.UpdateNamedSetRouterRequest = (function() { + + /** + * Properties of an UpdateNamedSetRouterRequest. + * @memberof google.cloud.compute.v1beta + * @interface IUpdateNamedSetRouterRequest + * @property {google.cloud.compute.v1beta.INamedSet|null} [namedSetResource] UpdateNamedSetRouterRequest namedSetResource + * @property {string|null} [project] UpdateNamedSetRouterRequest project + * @property {string|null} [region] UpdateNamedSetRouterRequest region + * @property {string|null} [requestId] UpdateNamedSetRouterRequest requestId + * @property {string|null} [router] UpdateNamedSetRouterRequest router + */ + + /** + * Constructs a new UpdateNamedSetRouterRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an UpdateNamedSetRouterRequest. + * @implements IUpdateNamedSetRouterRequest + * @constructor + * @param {google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest=} [properties] Properties to set + */ + function UpdateNamedSetRouterRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateNamedSetRouterRequest namedSetResource. + * @member {google.cloud.compute.v1beta.INamedSet|null|undefined} namedSetResource + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @instance + */ + UpdateNamedSetRouterRequest.prototype.namedSetResource = null; + + /** + * UpdateNamedSetRouterRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @instance + */ + UpdateNamedSetRouterRequest.prototype.project = ""; + + /** + * UpdateNamedSetRouterRequest region. + * @member {string} region + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @instance + */ + UpdateNamedSetRouterRequest.prototype.region = ""; + + /** + * UpdateNamedSetRouterRequest requestId. + * @member {string|null|undefined} requestId + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @instance + */ + UpdateNamedSetRouterRequest.prototype.requestId = null; + + /** + * UpdateNamedSetRouterRequest router. + * @member {string} router + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @instance + */ + UpdateNamedSetRouterRequest.prototype.router = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UpdateNamedSetRouterRequest.prototype, "_requestId", { + get: $util.oneOfGetter($oneOfFields = ["requestId"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UpdateNamedSetRouterRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.UpdateNamedSetRouterRequest} UpdateNamedSetRouterRequest instance + */ + UpdateNamedSetRouterRequest.create = function create(properties) { + return new UpdateNamedSetRouterRequest(properties); + }; + + /** + * Encodes the specified UpdateNamedSetRouterRequest message. Does not implicitly {@link google.cloud.compute.v1beta.UpdateNamedSetRouterRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest} message UpdateNamedSetRouterRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateNamedSetRouterRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.requestId != null && Object.hasOwnProperty.call(message, "requestId")) + writer.uint32(/* id 37109963, wireType 2 =*/296879706).string(message.requestId); + if (message.region != null && Object.hasOwnProperty.call(message, "region")) + writer.uint32(/* id 138946292, wireType 2 =*/1111570338).string(message.region); + if (message.router != null && Object.hasOwnProperty.call(message, "router")) + writer.uint32(/* id 148608841, wireType 2 =*/1188870730).string(message.router); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.namedSetResource != null && Object.hasOwnProperty.call(message, "namedSetResource")) + $root.google.cloud.compute.v1beta.NamedSet.encode(message.namedSetResource, writer.uint32(/* id 408608401, wireType 2 =*/3268867210).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified UpdateNamedSetRouterRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.UpdateNamedSetRouterRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest} message UpdateNamedSetRouterRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateNamedSetRouterRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateNamedSetRouterRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.UpdateNamedSetRouterRequest} UpdateNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateNamedSetRouterRequest.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.cloud.compute.v1beta.UpdateNamedSetRouterRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 408608401: { + message.namedSetResource = $root.google.cloud.compute.v1beta.NamedSet.decode(reader, reader.uint32()); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 138946292: { + message.region = reader.string(); + break; + } + case 37109963: { + message.requestId = reader.string(); + break; + } + case 148608841: { + message.router = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateNamedSetRouterRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.UpdateNamedSetRouterRequest} UpdateNamedSetRouterRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateNamedSetRouterRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateNamedSetRouterRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateNamedSetRouterRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.namedSetResource != null && message.hasOwnProperty("namedSetResource")) { + var error = $root.google.cloud.compute.v1beta.NamedSet.verify(message.namedSetResource); + if (error) + return "namedSetResource." + error; + } + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.region != null && message.hasOwnProperty("region")) + if (!$util.isString(message.region)) + return "region: string expected"; + if (message.requestId != null && message.hasOwnProperty("requestId")) { + properties._requestId = 1; + if (!$util.isString(message.requestId)) + return "requestId: string expected"; + } + if (message.router != null && message.hasOwnProperty("router")) + if (!$util.isString(message.router)) + return "router: string expected"; + return null; + }; + + /** + * Creates an UpdateNamedSetRouterRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.UpdateNamedSetRouterRequest} UpdateNamedSetRouterRequest + */ + UpdateNamedSetRouterRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest(); + if (object.namedSetResource != null) { + if (typeof object.namedSetResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.UpdateNamedSetRouterRequest.namedSetResource: object expected"); + message.namedSetResource = $root.google.cloud.compute.v1beta.NamedSet.fromObject(object.namedSetResource); + } + if (object.project != null) + message.project = String(object.project); + if (object.region != null) + message.region = String(object.region); + if (object.requestId != null) + message.requestId = String(object.requestId); + if (object.router != null) + message.router = String(object.router); + return message; + }; + + /** + * Creates a plain object from an UpdateNamedSetRouterRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {google.cloud.compute.v1beta.UpdateNamedSetRouterRequest} message UpdateNamedSetRouterRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateNamedSetRouterRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.region = ""; + object.router = ""; + object.project = ""; + object.namedSetResource = null; + } + if (message.requestId != null && message.hasOwnProperty("requestId")) { + object.requestId = message.requestId; + if (options.oneofs) + object._requestId = "requestId"; + } + if (message.region != null && message.hasOwnProperty("region")) + object.region = message.region; + if (message.router != null && message.hasOwnProperty("router")) + object.router = message.router; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.namedSetResource != null && message.hasOwnProperty("namedSetResource")) + object.namedSetResource = $root.google.cloud.compute.v1beta.NamedSet.toObject(message.namedSetResource, options); + return object; + }; + + /** + * Converts this UpdateNamedSetRouterRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateNamedSetRouterRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateNamedSetRouterRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.UpdateNamedSetRouterRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateNamedSetRouterRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.UpdateNamedSetRouterRequest"; + }; + + return UpdateNamedSetRouterRequest; + })(); + v1beta.UpdateNetworkInterfaceInstanceRequest = (function() { /** @@ -1320083,6 +1340905,346 @@ return UpdateReservationRequest; })(); + v1beta.UpdateReservationSlotRequest = (function() { + + /** + * Properties of an UpdateReservationSlotRequest. + * @memberof google.cloud.compute.v1beta + * @interface IUpdateReservationSlotRequest + * @property {string|null} [parentName] UpdateReservationSlotRequest parentName + * @property {string|null} [project] UpdateReservationSlotRequest project + * @property {string|null} [reservationSlot] UpdateReservationSlotRequest reservationSlot + * @property {google.cloud.compute.v1beta.IReservationSlot|null} [reservationSlotResource] UpdateReservationSlotRequest reservationSlotResource + * @property {string|null} [updateMask] UpdateReservationSlotRequest updateMask + * @property {string|null} [zone] UpdateReservationSlotRequest zone + */ + + /** + * Constructs a new UpdateReservationSlotRequest. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an UpdateReservationSlotRequest. + * @implements IUpdateReservationSlotRequest + * @constructor + * @param {google.cloud.compute.v1beta.IUpdateReservationSlotRequest=} [properties] Properties to set + */ + function UpdateReservationSlotRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateReservationSlotRequest parentName. + * @member {string} parentName + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @instance + */ + UpdateReservationSlotRequest.prototype.parentName = ""; + + /** + * UpdateReservationSlotRequest project. + * @member {string} project + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @instance + */ + UpdateReservationSlotRequest.prototype.project = ""; + + /** + * UpdateReservationSlotRequest reservationSlot. + * @member {string} reservationSlot + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @instance + */ + UpdateReservationSlotRequest.prototype.reservationSlot = ""; + + /** + * UpdateReservationSlotRequest reservationSlotResource. + * @member {google.cloud.compute.v1beta.IReservationSlot|null|undefined} reservationSlotResource + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @instance + */ + UpdateReservationSlotRequest.prototype.reservationSlotResource = null; + + /** + * UpdateReservationSlotRequest updateMask. + * @member {string|null|undefined} updateMask + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @instance + */ + UpdateReservationSlotRequest.prototype.updateMask = null; + + /** + * UpdateReservationSlotRequest zone. + * @member {string} zone + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @instance + */ + UpdateReservationSlotRequest.prototype.zone = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(UpdateReservationSlotRequest.prototype, "_updateMask", { + get: $util.oneOfGetter($oneOfFields = ["updateMask"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UpdateReservationSlotRequest instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {google.cloud.compute.v1beta.IUpdateReservationSlotRequest=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.UpdateReservationSlotRequest} UpdateReservationSlotRequest instance + */ + UpdateReservationSlotRequest.create = function create(properties) { + return new UpdateReservationSlotRequest(properties); + }; + + /** + * Encodes the specified UpdateReservationSlotRequest message. Does not implicitly {@link google.cloud.compute.v1beta.UpdateReservationSlotRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {google.cloud.compute.v1beta.IUpdateReservationSlotRequest} message UpdateReservationSlotRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateReservationSlotRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.zone != null && Object.hasOwnProperty.call(message, "zone")) + writer.uint32(/* id 3744684, wireType 2 =*/29957474).string(message.zone); + if (message.project != null && Object.hasOwnProperty.call(message, "project")) + writer.uint32(/* id 227560217, wireType 2 =*/1820481738).string(message.project); + if (message.reservationSlot != null && Object.hasOwnProperty.call(message, "reservationSlot")) + writer.uint32(/* id 277470865, wireType 2 =*/2219766922).string(message.reservationSlot); + if (message.reservationSlotResource != null && Object.hasOwnProperty.call(message, "reservationSlotResource")) + $root.google.cloud.compute.v1beta.ReservationSlot.encode(message.reservationSlotResource, writer.uint32(/* id 408545788, wireType 2 =*/3268366306).fork()).ldelim(); + if (message.parentName != null && Object.hasOwnProperty.call(message, "parentName")) + writer.uint32(/* id 478151936, wireType 2 =*/3825215490).string(message.parentName); + if (message.updateMask != null && Object.hasOwnProperty.call(message, "updateMask")) + writer.uint32(/* id 500079778, wireType 2 =*/4000638226).string(message.updateMask); + return writer; + }; + + /** + * Encodes the specified UpdateReservationSlotRequest message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.UpdateReservationSlotRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {google.cloud.compute.v1beta.IUpdateReservationSlotRequest} message UpdateReservationSlotRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateReservationSlotRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateReservationSlotRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.UpdateReservationSlotRequest} UpdateReservationSlotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateReservationSlotRequest.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.cloud.compute.v1beta.UpdateReservationSlotRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 478151936: { + message.parentName = reader.string(); + break; + } + case 227560217: { + message.project = reader.string(); + break; + } + case 277470865: { + message.reservationSlot = reader.string(); + break; + } + case 408545788: { + message.reservationSlotResource = $root.google.cloud.compute.v1beta.ReservationSlot.decode(reader, reader.uint32()); + break; + } + case 500079778: { + message.updateMask = reader.string(); + break; + } + case 3744684: { + message.zone = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateReservationSlotRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.UpdateReservationSlotRequest} UpdateReservationSlotRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateReservationSlotRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateReservationSlotRequest message. + * @function verify + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateReservationSlotRequest.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.parentName != null && message.hasOwnProperty("parentName")) + if (!$util.isString(message.parentName)) + return "parentName: string expected"; + if (message.project != null && message.hasOwnProperty("project")) + if (!$util.isString(message.project)) + return "project: string expected"; + if (message.reservationSlot != null && message.hasOwnProperty("reservationSlot")) + if (!$util.isString(message.reservationSlot)) + return "reservationSlot: string expected"; + if (message.reservationSlotResource != null && message.hasOwnProperty("reservationSlotResource")) { + var error = $root.google.cloud.compute.v1beta.ReservationSlot.verify(message.reservationSlotResource); + if (error) + return "reservationSlotResource." + error; + } + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + properties._updateMask = 1; + if (!$util.isString(message.updateMask)) + return "updateMask: string expected"; + } + if (message.zone != null && message.hasOwnProperty("zone")) + if (!$util.isString(message.zone)) + return "zone: string expected"; + return null; + }; + + /** + * Creates an UpdateReservationSlotRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.UpdateReservationSlotRequest} UpdateReservationSlotRequest + */ + UpdateReservationSlotRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.UpdateReservationSlotRequest) + return object; + var message = new $root.google.cloud.compute.v1beta.UpdateReservationSlotRequest(); + if (object.parentName != null) + message.parentName = String(object.parentName); + if (object.project != null) + message.project = String(object.project); + if (object.reservationSlot != null) + message.reservationSlot = String(object.reservationSlot); + if (object.reservationSlotResource != null) { + if (typeof object.reservationSlotResource !== "object") + throw TypeError(".google.cloud.compute.v1beta.UpdateReservationSlotRequest.reservationSlotResource: object expected"); + message.reservationSlotResource = $root.google.cloud.compute.v1beta.ReservationSlot.fromObject(object.reservationSlotResource); + } + if (object.updateMask != null) + message.updateMask = String(object.updateMask); + if (object.zone != null) + message.zone = String(object.zone); + return message; + }; + + /** + * Creates a plain object from an UpdateReservationSlotRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {google.cloud.compute.v1beta.UpdateReservationSlotRequest} message UpdateReservationSlotRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateReservationSlotRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.zone = ""; + object.project = ""; + object.reservationSlot = ""; + object.reservationSlotResource = null; + object.parentName = ""; + } + if (message.zone != null && message.hasOwnProperty("zone")) + object.zone = message.zone; + if (message.project != null && message.hasOwnProperty("project")) + object.project = message.project; + if (message.reservationSlot != null && message.hasOwnProperty("reservationSlot")) + object.reservationSlot = message.reservationSlot; + if (message.reservationSlotResource != null && message.hasOwnProperty("reservationSlotResource")) + object.reservationSlotResource = $root.google.cloud.compute.v1beta.ReservationSlot.toObject(message.reservationSlotResource, options); + if (message.parentName != null && message.hasOwnProperty("parentName")) + object.parentName = message.parentName; + if (message.updateMask != null && message.hasOwnProperty("updateMask")) { + object.updateMask = message.updateMask; + if (options.oneofs) + object._updateMask = "updateMask"; + } + return object; + }; + + /** + * Converts this UpdateReservationSlotRequest to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @instance + * @returns {Object.} JSON object + */ + UpdateReservationSlotRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateReservationSlotRequest + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.UpdateReservationSlotRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateReservationSlotRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.UpdateReservationSlotRequest"; + }; + + return UpdateReservationSlotRequest; + })(); + v1beta.UpdateReservationsRegionCommitmentRequest = (function() { /** @@ -1332852,6 +1354014,7 @@ * @property {Object.|null} [labels] VpnGateway labels * @property {string|null} [name] VpnGateway name * @property {string|null} [network] VpnGateway network + * @property {google.cloud.compute.v1beta.IVpnGatewayParams|null} [params] VpnGateway params * @property {string|null} [region] VpnGateway region * @property {string|null} [selfLink] VpnGateway selfLink * @property {string|null} [stackType] VpnGateway stackType @@ -1332947,6 +1354110,14 @@ */ VpnGateway.prototype.network = null; + /** + * VpnGateway params. + * @member {google.cloud.compute.v1beta.IVpnGatewayParams|null|undefined} params + * @memberof google.cloud.compute.v1beta.VpnGateway + * @instance + */ + VpnGateway.prototype.params = null; + /** * VpnGateway region. * @member {string|null|undefined} region @@ -1333030,6 +1354201,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(VpnGateway.prototype, "_params", { + get: $util.oneOfGetter($oneOfFields = ["params"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(VpnGateway.prototype, "_region", { get: $util.oneOfGetter($oneOfFields = ["region"]), @@ -1333082,6 +1354259,8 @@ writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); if (message.gatewayIpVersion != null && Object.hasOwnProperty.call(message, "gatewayIpVersion")) writer.uint32(/* id 65074843, wireType 2 =*/520598746).string(message.gatewayIpVersion); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.cloud.compute.v1beta.VpnGatewayParams.encode(message.params, writer.uint32(/* id 78313862, wireType 2 =*/626510898).fork()).ldelim(); if (message.vpnInterfaces != null && message.vpnInterfaces.length) for (var i = 0; i < message.vpnInterfaces.length; ++i) $root.google.cloud.compute.v1beta.VpnGatewayVpnGatewayInterface.encode(message.vpnInterfaces[i], writer.uint32(/* id 91842181, wireType 2 =*/734737450).fork()).ldelim(); @@ -1333191,6 +1354370,10 @@ message.network = reader.string(); break; } + case 78313862: { + message.params = $root.google.cloud.compute.v1beta.VpnGatewayParams.decode(reader, reader.uint32()); + break; + } case 138946292: { message.region = reader.string(); break; @@ -1333293,6 +1354476,14 @@ if (!$util.isString(message.network)) return "network: string expected"; } + if (message.params != null && message.hasOwnProperty("params")) { + properties._params = 1; + { + var error = $root.google.cloud.compute.v1beta.VpnGatewayParams.verify(message.params); + if (error) + return "params." + error; + } + } if (message.region != null && message.hasOwnProperty("region")) { properties._region = 1; if (!$util.isString(message.region)) @@ -1333362,6 +1354553,11 @@ message.name = String(object.name); if (object.network != null) message.network = String(object.network); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.cloud.compute.v1beta.VpnGateway.params: object expected"); + message.params = $root.google.cloud.compute.v1beta.VpnGatewayParams.fromObject(object.params); + } if (object.region != null) message.region = String(object.region); if (object.selfLink != null) @@ -1333426,6 +1354622,11 @@ if (options.oneofs) object._gatewayIpVersion = "gatewayIpVersion"; } + if (message.params != null && message.hasOwnProperty("params")) { + object.params = $root.google.cloud.compute.v1beta.VpnGatewayParams.toObject(message.params, options); + if (options.oneofs) + object._params = "params"; + } if (message.vpnInterfaces && message.vpnInterfaces.length) { object.vpnInterfaces = []; for (var j = 0; j < message.vpnInterfaces.length; ++j) @@ -1334396,6 +1355597,246 @@ return VpnGatewayList; })(); + v1beta.VpnGatewayParams = (function() { + + /** + * Properties of a VpnGatewayParams. + * @memberof google.cloud.compute.v1beta + * @interface IVpnGatewayParams + * @property {Object.|null} [resourceManagerTags] VpnGatewayParams resourceManagerTags + */ + + /** + * Constructs a new VpnGatewayParams. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a VpnGatewayParams. + * @implements IVpnGatewayParams + * @constructor + * @param {google.cloud.compute.v1beta.IVpnGatewayParams=} [properties] Properties to set + */ + function VpnGatewayParams(properties) { + this.resourceManagerTags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * VpnGatewayParams resourceManagerTags. + * @member {Object.} resourceManagerTags + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @instance + */ + VpnGatewayParams.prototype.resourceManagerTags = $util.emptyObject; + + /** + * Creates a new VpnGatewayParams instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.IVpnGatewayParams=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.VpnGatewayParams} VpnGatewayParams instance + */ + VpnGatewayParams.create = function create(properties) { + return new VpnGatewayParams(properties); + }; + + /** + * Encodes the specified VpnGatewayParams message. Does not implicitly {@link google.cloud.compute.v1beta.VpnGatewayParams.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.IVpnGatewayParams} message VpnGatewayParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VpnGatewayParams.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceManagerTags != null && Object.hasOwnProperty.call(message, "resourceManagerTags")) + for (var keys = Object.keys(message.resourceManagerTags), i = 0; i < keys.length; ++i) + writer.uint32(/* id 377671164, wireType 2 =*/3021369314).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourceManagerTags[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified VpnGatewayParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.VpnGatewayParams.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.IVpnGatewayParams} message VpnGatewayParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VpnGatewayParams.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VpnGatewayParams message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.VpnGatewayParams} VpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VpnGatewayParams.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.cloud.compute.v1beta.VpnGatewayParams(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 377671164: { + if (message.resourceManagerTags === $util.emptyObject) + message.resourceManagerTags = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.resourceManagerTags[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VpnGatewayParams message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.VpnGatewayParams} VpnGatewayParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VpnGatewayParams.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VpnGatewayParams message. + * @function verify + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VpnGatewayParams.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceManagerTags != null && message.hasOwnProperty("resourceManagerTags")) { + if (!$util.isObject(message.resourceManagerTags)) + return "resourceManagerTags: object expected"; + var key = Object.keys(message.resourceManagerTags); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.resourceManagerTags[key[i]])) + return "resourceManagerTags: string{k:string} expected"; + } + return null; + }; + + /** + * Creates a VpnGatewayParams message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.VpnGatewayParams} VpnGatewayParams + */ + VpnGatewayParams.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.VpnGatewayParams) + return object; + var message = new $root.google.cloud.compute.v1beta.VpnGatewayParams(); + if (object.resourceManagerTags) { + if (typeof object.resourceManagerTags !== "object") + throw TypeError(".google.cloud.compute.v1beta.VpnGatewayParams.resourceManagerTags: object expected"); + message.resourceManagerTags = {}; + for (var keys = Object.keys(object.resourceManagerTags), i = 0; i < keys.length; ++i) + message.resourceManagerTags[keys[i]] = String(object.resourceManagerTags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a VpnGatewayParams message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {google.cloud.compute.v1beta.VpnGatewayParams} message VpnGatewayParams + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VpnGatewayParams.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.resourceManagerTags = {}; + var keys2; + if (message.resourceManagerTags && (keys2 = Object.keys(message.resourceManagerTags)).length) { + object.resourceManagerTags = {}; + for (var j = 0; j < keys2.length; ++j) + object.resourceManagerTags[keys2[j]] = message.resourceManagerTags[keys2[j]]; + } + return object; + }; + + /** + * Converts this VpnGatewayParams to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @instance + * @returns {Object.} JSON object + */ + VpnGatewayParams.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VpnGatewayParams + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.VpnGatewayParams + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VpnGatewayParams.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.VpnGatewayParams"; + }; + + return VpnGatewayParams; + })(); + v1beta.VpnGatewayStatus = (function() { /** @@ -1336350,6 +1357791,7 @@ * @property {Object.|null} [labels] VpnTunnel labels * @property {Array.|null} [localTrafficSelector] VpnTunnel localTrafficSelector * @property {string|null} [name] VpnTunnel name + * @property {google.cloud.compute.v1beta.IVpnTunnelParams|null} [params] VpnTunnel params * @property {string|null} [peerExternalGateway] VpnTunnel peerExternalGateway * @property {number|null} [peerExternalGatewayInterface] VpnTunnel peerExternalGatewayInterface * @property {string|null} [peerGcpGateway] VpnTunnel peerGcpGateway @@ -1336480,6 +1357922,14 @@ */ VpnTunnel.prototype.name = null; + /** + * VpnTunnel params. + * @member {google.cloud.compute.v1beta.IVpnTunnelParams|null|undefined} params + * @memberof google.cloud.compute.v1beta.VpnTunnel + * @instance + */ + VpnTunnel.prototype.params = null; + /** * VpnTunnel peerExternalGateway. * @member {string|null|undefined} peerExternalGateway @@ -1336655,6 +1358105,12 @@ set: $util.oneOfSetter($oneOfFields) }); + // Virtual OneOf for proto3 optional field + Object.defineProperty(VpnTunnel.prototype, "_params", { + get: $util.oneOfGetter($oneOfFields = ["params"]), + set: $util.oneOfSetter($oneOfFields) + }); + // Virtual OneOf for proto3 optional field Object.defineProperty(VpnTunnel.prototype, "_peerExternalGateway", { get: $util.oneOfGetter($oneOfFields = ["peerExternalGateway"]), @@ -1336765,6 +1358221,8 @@ writer.uint32(/* id 3373707, wireType 2 =*/26989658).string(message.name); if (message.creationTimestamp != null && Object.hasOwnProperty.call(message, "creationTimestamp")) writer.uint32(/* id 30525366, wireType 2 =*/244202930).string(message.creationTimestamp); + if (message.params != null && Object.hasOwnProperty.call(message, "params")) + $root.google.cloud.compute.v1beta.VpnTunnelParams.encode(message.params, writer.uint32(/* id 78313862, wireType 2 =*/626510898).fork()).ldelim(); if (message.vpnGatewayInterface != null && Object.hasOwnProperty.call(message, "vpnGatewayInterface")) writer.uint32(/* id 95979123, wireType 0 =*/767832984).int32(message.vpnGatewayInterface); if (message.region != null && Object.hasOwnProperty.call(message, "region")) @@ -1336917,6 +1358375,10 @@ message.name = reader.string(); break; } + case 78313862: { + message.params = $root.google.cloud.compute.v1beta.VpnTunnelParams.decode(reader, reader.uint32()); + break; + } case 384956173: { message.peerExternalGateway = reader.string(); break; @@ -1337079,6 +1358541,14 @@ if (!$util.isString(message.name)) return "name: string expected"; } + if (message.params != null && message.hasOwnProperty("params")) { + properties._params = 1; + { + var error = $root.google.cloud.compute.v1beta.VpnTunnelParams.verify(message.params); + if (error) + return "params." + error; + } + } if (message.peerExternalGateway != null && message.hasOwnProperty("peerExternalGateway")) { properties._peerExternalGateway = 1; if (!$util.isString(message.peerExternalGateway)) @@ -1337210,6 +1358680,11 @@ } if (object.name != null) message.name = String(object.name); + if (object.params != null) { + if (typeof object.params !== "object") + throw TypeError(".google.cloud.compute.v1beta.VpnTunnel.params: object expected"); + message.params = $root.google.cloud.compute.v1beta.VpnTunnelParams.fromObject(object.params); + } if (object.peerExternalGateway != null) message.peerExternalGateway = String(object.peerExternalGateway); if (object.peerExternalGatewayInterface != null) @@ -1337288,6 +1358763,11 @@ if (options.oneofs) object._creationTimestamp = "creationTimestamp"; } + if (message.params != null && message.hasOwnProperty("params")) { + object.params = $root.google.cloud.compute.v1beta.VpnTunnelParams.toObject(message.params, options); + if (options.oneofs) + object._params = "params"; + } if (message.vpnGatewayInterface != null && message.hasOwnProperty("vpnGatewayInterface")) { object.vpnGatewayInterface = message.vpnGatewayInterface; if (options.oneofs) @@ -1338611,6 +1360091,246 @@ return VpnTunnelList; })(); + v1beta.VpnTunnelParams = (function() { + + /** + * Properties of a VpnTunnelParams. + * @memberof google.cloud.compute.v1beta + * @interface IVpnTunnelParams + * @property {Object.|null} [resourceManagerTags] VpnTunnelParams resourceManagerTags + */ + + /** + * Constructs a new VpnTunnelParams. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a VpnTunnelParams. + * @implements IVpnTunnelParams + * @constructor + * @param {google.cloud.compute.v1beta.IVpnTunnelParams=} [properties] Properties to set + */ + function VpnTunnelParams(properties) { + this.resourceManagerTags = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * VpnTunnelParams resourceManagerTags. + * @member {Object.} resourceManagerTags + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @instance + */ + VpnTunnelParams.prototype.resourceManagerTags = $util.emptyObject; + + /** + * Creates a new VpnTunnelParams instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {google.cloud.compute.v1beta.IVpnTunnelParams=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.VpnTunnelParams} VpnTunnelParams instance + */ + VpnTunnelParams.create = function create(properties) { + return new VpnTunnelParams(properties); + }; + + /** + * Encodes the specified VpnTunnelParams message. Does not implicitly {@link google.cloud.compute.v1beta.VpnTunnelParams.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {google.cloud.compute.v1beta.IVpnTunnelParams} message VpnTunnelParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VpnTunnelParams.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.resourceManagerTags != null && Object.hasOwnProperty.call(message, "resourceManagerTags")) + for (var keys = Object.keys(message.resourceManagerTags), i = 0; i < keys.length; ++i) + writer.uint32(/* id 377671164, wireType 2 =*/3021369314).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.resourceManagerTags[keys[i]]).ldelim(); + return writer; + }; + + /** + * Encodes the specified VpnTunnelParams message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.VpnTunnelParams.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {google.cloud.compute.v1beta.IVpnTunnelParams} message VpnTunnelParams message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VpnTunnelParams.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VpnTunnelParams message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.VpnTunnelParams} VpnTunnelParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VpnTunnelParams.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.cloud.compute.v1beta.VpnTunnelParams(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 377671164: { + if (message.resourceManagerTags === $util.emptyObject) + message.resourceManagerTags = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.resourceManagerTags[key] = value; + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VpnTunnelParams message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.VpnTunnelParams} VpnTunnelParams + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VpnTunnelParams.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VpnTunnelParams message. + * @function verify + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VpnTunnelParams.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.resourceManagerTags != null && message.hasOwnProperty("resourceManagerTags")) { + if (!$util.isObject(message.resourceManagerTags)) + return "resourceManagerTags: object expected"; + var key = Object.keys(message.resourceManagerTags); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.resourceManagerTags[key[i]])) + return "resourceManagerTags: string{k:string} expected"; + } + return null; + }; + + /** + * Creates a VpnTunnelParams message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.VpnTunnelParams} VpnTunnelParams + */ + VpnTunnelParams.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.VpnTunnelParams) + return object; + var message = new $root.google.cloud.compute.v1beta.VpnTunnelParams(); + if (object.resourceManagerTags) { + if (typeof object.resourceManagerTags !== "object") + throw TypeError(".google.cloud.compute.v1beta.VpnTunnelParams.resourceManagerTags: object expected"); + message.resourceManagerTags = {}; + for (var keys = Object.keys(object.resourceManagerTags), i = 0; i < keys.length; ++i) + message.resourceManagerTags[keys[i]] = String(object.resourceManagerTags[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a VpnTunnelParams message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {google.cloud.compute.v1beta.VpnTunnelParams} message VpnTunnelParams + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VpnTunnelParams.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.resourceManagerTags = {}; + var keys2; + if (message.resourceManagerTags && (keys2 = Object.keys(message.resourceManagerTags)).length) { + object.resourceManagerTags = {}; + for (var j = 0; j < keys2.length; ++j) + object.resourceManagerTags[keys2[j]] = message.resourceManagerTags[keys2[j]]; + } + return object; + }; + + /** + * Converts this VpnTunnelParams to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @instance + * @returns {Object.} JSON object + */ + VpnTunnelParams.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VpnTunnelParams + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.VpnTunnelParams + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VpnTunnelParams.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.VpnTunnelParams"; + }; + + return VpnTunnelParams; + })(); + v1beta.VpnTunnelPhase1Algorithms = (function() { /** @@ -1345682,6 +1367402,257 @@ return WithdrawPublicDelegatedPrefixeRequest; })(); + v1beta.WorkloadIdentityConfig = (function() { + + /** + * Properties of a WorkloadIdentityConfig. + * @memberof google.cloud.compute.v1beta + * @interface IWorkloadIdentityConfig + * @property {string|null} [identity] WorkloadIdentityConfig identity + * @property {boolean|null} [identityCertificateEnabled] WorkloadIdentityConfig identityCertificateEnabled + */ + + /** + * Constructs a new WorkloadIdentityConfig. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a WorkloadIdentityConfig. + * @implements IWorkloadIdentityConfig + * @constructor + * @param {google.cloud.compute.v1beta.IWorkloadIdentityConfig=} [properties] Properties to set + */ + function WorkloadIdentityConfig(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * WorkloadIdentityConfig identity. + * @member {string|null|undefined} identity + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @instance + */ + WorkloadIdentityConfig.prototype.identity = null; + + /** + * WorkloadIdentityConfig identityCertificateEnabled. + * @member {boolean|null|undefined} identityCertificateEnabled + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @instance + */ + WorkloadIdentityConfig.prototype.identityCertificateEnabled = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(WorkloadIdentityConfig.prototype, "_identity", { + get: $util.oneOfGetter($oneOfFields = ["identity"]), + set: $util.oneOfSetter($oneOfFields) + }); + + // Virtual OneOf for proto3 optional field + Object.defineProperty(WorkloadIdentityConfig.prototype, "_identityCertificateEnabled", { + get: $util.oneOfGetter($oneOfFields = ["identityCertificateEnabled"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new WorkloadIdentityConfig instance using the specified properties. + * @function create + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {google.cloud.compute.v1beta.IWorkloadIdentityConfig=} [properties] Properties to set + * @returns {google.cloud.compute.v1beta.WorkloadIdentityConfig} WorkloadIdentityConfig instance + */ + WorkloadIdentityConfig.create = function create(properties) { + return new WorkloadIdentityConfig(properties); + }; + + /** + * Encodes the specified WorkloadIdentityConfig message. Does not implicitly {@link google.cloud.compute.v1beta.WorkloadIdentityConfig.verify|verify} messages. + * @function encode + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {google.cloud.compute.v1beta.IWorkloadIdentityConfig} message WorkloadIdentityConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WorkloadIdentityConfig.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.identityCertificateEnabled != null && Object.hasOwnProperty.call(message, "identityCertificateEnabled")) + writer.uint32(/* id 342892440, wireType 0 =*/2743139520).bool(message.identityCertificateEnabled); + if (message.identity != null && Object.hasOwnProperty.call(message, "identity")) + writer.uint32(/* id 401109182, wireType 2 =*/3208873458).string(message.identity); + return writer; + }; + + /** + * Encodes the specified WorkloadIdentityConfig message, length delimited. Does not implicitly {@link google.cloud.compute.v1beta.WorkloadIdentityConfig.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {google.cloud.compute.v1beta.IWorkloadIdentityConfig} message WorkloadIdentityConfig message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WorkloadIdentityConfig.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a WorkloadIdentityConfig message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.compute.v1beta.WorkloadIdentityConfig} WorkloadIdentityConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WorkloadIdentityConfig.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.cloud.compute.v1beta.WorkloadIdentityConfig(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 401109182: { + message.identity = reader.string(); + break; + } + case 342892440: { + message.identityCertificateEnabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a WorkloadIdentityConfig message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.compute.v1beta.WorkloadIdentityConfig} WorkloadIdentityConfig + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WorkloadIdentityConfig.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a WorkloadIdentityConfig message. + * @function verify + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + WorkloadIdentityConfig.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.identity != null && message.hasOwnProperty("identity")) { + properties._identity = 1; + if (!$util.isString(message.identity)) + return "identity: string expected"; + } + if (message.identityCertificateEnabled != null && message.hasOwnProperty("identityCertificateEnabled")) { + properties._identityCertificateEnabled = 1; + if (typeof message.identityCertificateEnabled !== "boolean") + return "identityCertificateEnabled: boolean expected"; + } + return null; + }; + + /** + * Creates a WorkloadIdentityConfig message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.compute.v1beta.WorkloadIdentityConfig} WorkloadIdentityConfig + */ + WorkloadIdentityConfig.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.compute.v1beta.WorkloadIdentityConfig) + return object; + var message = new $root.google.cloud.compute.v1beta.WorkloadIdentityConfig(); + if (object.identity != null) + message.identity = String(object.identity); + if (object.identityCertificateEnabled != null) + message.identityCertificateEnabled = Boolean(object.identityCertificateEnabled); + return message; + }; + + /** + * Creates a plain object from a WorkloadIdentityConfig message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {google.cloud.compute.v1beta.WorkloadIdentityConfig} message WorkloadIdentityConfig + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WorkloadIdentityConfig.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.identityCertificateEnabled != null && message.hasOwnProperty("identityCertificateEnabled")) { + object.identityCertificateEnabled = message.identityCertificateEnabled; + if (options.oneofs) + object._identityCertificateEnabled = "identityCertificateEnabled"; + } + if (message.identity != null && message.hasOwnProperty("identity")) { + object.identity = message.identity; + if (options.oneofs) + object._identity = "identity"; + } + return object; + }; + + /** + * Converts this WorkloadIdentityConfig to JSON. + * @function toJSON + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @instance + * @returns {Object.} JSON object + */ + WorkloadIdentityConfig.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WorkloadIdentityConfig + * @function getTypeUrl + * @memberof google.cloud.compute.v1beta.WorkloadIdentityConfig + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WorkloadIdentityConfig.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.compute.v1beta.WorkloadIdentityConfig"; + }; + + return WorkloadIdentityConfig; + })(); + v1beta.XpnHostList = (function() { /** @@ -1355761,6 +1377732,39 @@ * @variation 2 */ + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstanceGroupManagers|configureAcceleratorTopologies}. + * @memberof google.cloud.compute.v1beta.InstanceGroupManagers + * @typedef ConfigureAcceleratorTopologiesCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls ConfigureAcceleratorTopologies. + * @function configureAcceleratorTopologies + * @memberof google.cloud.compute.v1beta.InstanceGroupManagers + * @instance + * @param {google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest} request ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message or plain object + * @param {google.cloud.compute.v1beta.InstanceGroupManagers.ConfigureAcceleratorTopologiesCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstanceGroupManagers.prototype.configureAcceleratorTopologies = function configureAcceleratorTopologies(request, callback) { + return this.rpcCall(configureAcceleratorTopologies, $root.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "ConfigureAcceleratorTopologies" }); + + /** + * Calls ConfigureAcceleratorTopologies. + * @function configureAcceleratorTopologies + * @memberof google.cloud.compute.v1beta.InstanceGroupManagers + * @instance + * @param {google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest} request ConfigureAcceleratorTopologiesInstanceGroupManagerRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + /** * Callback as used by {@link google.cloud.compute.v1beta.InstanceGroupManagers|createInstances}. * @memberof google.cloud.compute.v1beta.InstanceGroupManagers @@ -1359270,6 +1381274,272 @@ return Instances; })(); + v1beta.InstantSnapshotGroups = (function() { + + /** + * Constructs a new InstantSnapshotGroups service. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents an InstantSnapshotGroups + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function InstantSnapshotGroups(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (InstantSnapshotGroups.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = InstantSnapshotGroups; + + /** + * Creates new InstantSnapshotGroups service using the specified rpc implementation. + * @function create + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {InstantSnapshotGroups} RPC service. Useful where requests and/or responses are streamed. + */ + InstantSnapshotGroups.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|delete_}. + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @typedef DeleteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls Delete. + * @function delete + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest} request DeleteInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.InstantSnapshotGroups.DeleteCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstantSnapshotGroups.prototype["delete"] = function delete_(request, callback) { + return this.rpcCall(delete_, $root.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "Delete" }); + + /** + * Calls Delete. + * @function delete + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest} request DeleteInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|get}. + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @typedef GetCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.InstantSnapshotGroup} [response] InstantSnapshotGroup + */ + + /** + * Calls Get. + * @function get + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest} request GetInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.InstantSnapshotGroups.GetCallback} callback Node-style callback called with the error, if any, and InstantSnapshotGroup + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstantSnapshotGroups.prototype.get = function get(request, callback) { + return this.rpcCall(get, $root.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.InstantSnapshotGroup, request, callback); + }, "name", { value: "Get" }); + + /** + * Calls Get. + * @function get + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest} request GetInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|getIamPolicy}. + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @typedef GetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Policy} [response] Policy + */ + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest} request GetIamPolicyInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.InstantSnapshotGroups.GetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstantSnapshotGroups.prototype.getIamPolicy = function getIamPolicy(request, callback) { + return this.rpcCall(getIamPolicy, $root.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Policy, request, callback); + }, "name", { value: "GetIamPolicy" }); + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest} request GetIamPolicyInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|insert}. + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @typedef InsertCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls Insert. + * @function insert + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest} request InsertInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.InstantSnapshotGroups.InsertCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstantSnapshotGroups.prototype.insert = function insert(request, callback) { + return this.rpcCall(insert, $root.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "Insert" }); + + /** + * Calls Insert. + * @function insert + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest} request InsertInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|list}. + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @typedef ListCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.ListInstantSnapshotGroups} [response] ListInstantSnapshotGroups + */ + + /** + * Calls List. + * @function list + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest} request ListInstantSnapshotGroupsRequest message or plain object + * @param {google.cloud.compute.v1beta.InstantSnapshotGroups.ListCallback} callback Node-style callback called with the error, if any, and ListInstantSnapshotGroups + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstantSnapshotGroups.prototype.list = function list(request, callback) { + return this.rpcCall(list, $root.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest, $root.google.cloud.compute.v1beta.ListInstantSnapshotGroups, request, callback); + }, "name", { value: "List" }); + + /** + * Calls List. + * @function list + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest} request ListInstantSnapshotGroupsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|setIamPolicy}. + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @typedef SetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Policy} [response] Policy + */ + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest} request SetIamPolicyInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.InstantSnapshotGroups.SetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstantSnapshotGroups.prototype.setIamPolicy = function setIamPolicy(request, callback) { + return this.rpcCall(setIamPolicy, $root.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Policy, request, callback); + }, "name", { value: "SetIamPolicy" }); + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest} request SetIamPolicyInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.InstantSnapshotGroups|testIamPermissions}. + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @typedef TestIamPermissionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.TestPermissionsResponse} [response] TestPermissionsResponse + */ + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest} request TestIamPermissionsInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.InstantSnapshotGroups.TestIamPermissionsCallback} callback Node-style callback called with the error, if any, and TestPermissionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(InstantSnapshotGroups.prototype.testIamPermissions = function testIamPermissions(request, callback) { + return this.rpcCall(testIamPermissions, $root.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.TestPermissionsResponse, request, callback); + }, "name", { value: "TestIamPermissions" }); + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.cloud.compute.v1beta.InstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest} request TestIamPermissionsInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return InstantSnapshotGroups; + })(); + v1beta.InstantSnapshots = (function() { /** @@ -1372160,6 +1394430,272 @@ return RegionInstances; })(); + v1beta.RegionInstantSnapshotGroups = (function() { + + /** + * Constructs a new RegionInstantSnapshotGroups service. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a RegionInstantSnapshotGroups + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function RegionInstantSnapshotGroups(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (RegionInstantSnapshotGroups.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = RegionInstantSnapshotGroups; + + /** + * Creates new RegionInstantSnapshotGroups service using the specified rpc implementation. + * @function create + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {RegionInstantSnapshotGroups} RPC service. Useful where requests and/or responses are streamed. + */ + RegionInstantSnapshotGroups.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|delete_}. + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @typedef DeleteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls Delete. + * @function delete + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest} request DeleteRegionInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.RegionInstantSnapshotGroups.DeleteCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(RegionInstantSnapshotGroups.prototype["delete"] = function delete_(request, callback) { + return this.rpcCall(delete_, $root.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "Delete" }); + + /** + * Calls Delete. + * @function delete + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest} request DeleteRegionInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|get}. + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @typedef GetCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.InstantSnapshotGroup} [response] InstantSnapshotGroup + */ + + /** + * Calls Get. + * @function get + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest} request GetRegionInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.RegionInstantSnapshotGroups.GetCallback} callback Node-style callback called with the error, if any, and InstantSnapshotGroup + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(RegionInstantSnapshotGroups.prototype.get = function get(request, callback) { + return this.rpcCall(get, $root.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.InstantSnapshotGroup, request, callback); + }, "name", { value: "Get" }); + + /** + * Calls Get. + * @function get + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest} request GetRegionInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|getIamPolicy}. + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @typedef GetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Policy} [response] Policy + */ + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest} request GetIamPolicyRegionInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.RegionInstantSnapshotGroups.GetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(RegionInstantSnapshotGroups.prototype.getIamPolicy = function getIamPolicy(request, callback) { + return this.rpcCall(getIamPolicy, $root.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Policy, request, callback); + }, "name", { value: "GetIamPolicy" }); + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest} request GetIamPolicyRegionInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|insert}. + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @typedef InsertCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls Insert. + * @function insert + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest} request InsertRegionInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.RegionInstantSnapshotGroups.InsertCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(RegionInstantSnapshotGroups.prototype.insert = function insert(request, callback) { + return this.rpcCall(insert, $root.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "Insert" }); + + /** + * Calls Insert. + * @function insert + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest} request InsertRegionInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|list}. + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @typedef ListCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.ListInstantSnapshotGroups} [response] ListInstantSnapshotGroups + */ + + /** + * Calls List. + * @function list + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest} request ListRegionInstantSnapshotGroupsRequest message or plain object + * @param {google.cloud.compute.v1beta.RegionInstantSnapshotGroups.ListCallback} callback Node-style callback called with the error, if any, and ListInstantSnapshotGroups + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(RegionInstantSnapshotGroups.prototype.list = function list(request, callback) { + return this.rpcCall(list, $root.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest, $root.google.cloud.compute.v1beta.ListInstantSnapshotGroups, request, callback); + }, "name", { value: "List" }); + + /** + * Calls List. + * @function list + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest} request ListRegionInstantSnapshotGroupsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|setIamPolicy}. + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @typedef SetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Policy} [response] Policy + */ + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest} request SetIamPolicyRegionInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.RegionInstantSnapshotGroups.SetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(RegionInstantSnapshotGroups.prototype.setIamPolicy = function setIamPolicy(request, callback) { + return this.rpcCall(setIamPolicy, $root.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Policy, request, callback); + }, "name", { value: "SetIamPolicy" }); + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest} request SetIamPolicyRegionInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.RegionInstantSnapshotGroups|testIamPermissions}. + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @typedef TestIamPermissionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.TestPermissionsResponse} [response] TestPermissionsResponse + */ + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest} request TestIamPermissionsRegionInstantSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.RegionInstantSnapshotGroups.TestIamPermissionsCallback} callback Node-style callback called with the error, if any, and TestPermissionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(RegionInstantSnapshotGroups.prototype.testIamPermissions = function testIamPermissions(request, callback) { + return this.rpcCall(testIamPermissions, $root.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest, $root.google.cloud.compute.v1beta.TestPermissionsResponse, request, callback); + }, "name", { value: "TestIamPermissions" }); + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.cloud.compute.v1beta.RegionInstantSnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest} request TestIamPermissionsRegionInstantSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return RegionInstantSnapshotGroups; + })(); + v1beta.RegionInstantSnapshots = (function() { /** @@ -1377150,6 +1399686,140 @@ return ReservationBlocks; })(); + v1beta.ReservationSlots = (function() { + + /** + * Constructs a new ReservationSlots service. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a ReservationSlots + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function ReservationSlots(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (ReservationSlots.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = ReservationSlots; + + /** + * Creates new ReservationSlots service using the specified rpc implementation. + * @function create + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {ReservationSlots} RPC service. Useful where requests and/or responses are streamed. + */ + ReservationSlots.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.ReservationSlots|get}. + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @typedef GetCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.ReservationSlotsGetResponse} [response] ReservationSlotsGetResponse + */ + + /** + * Calls Get. + * @function get + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @instance + * @param {google.cloud.compute.v1beta.IGetReservationSlotRequest} request GetReservationSlotRequest message or plain object + * @param {google.cloud.compute.v1beta.ReservationSlots.GetCallback} callback Node-style callback called with the error, if any, and ReservationSlotsGetResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(ReservationSlots.prototype.get = function get(request, callback) { + return this.rpcCall(get, $root.google.cloud.compute.v1beta.GetReservationSlotRequest, $root.google.cloud.compute.v1beta.ReservationSlotsGetResponse, request, callback); + }, "name", { value: "Get" }); + + /** + * Calls Get. + * @function get + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @instance + * @param {google.cloud.compute.v1beta.IGetReservationSlotRequest} request GetReservationSlotRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.ReservationSlots|list}. + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @typedef ListCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.ReservationSlotsListResponse} [response] ReservationSlotsListResponse + */ + + /** + * Calls List. + * @function list + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @instance + * @param {google.cloud.compute.v1beta.IListReservationSlotsRequest} request ListReservationSlotsRequest message or plain object + * @param {google.cloud.compute.v1beta.ReservationSlots.ListCallback} callback Node-style callback called with the error, if any, and ReservationSlotsListResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(ReservationSlots.prototype.list = function list(request, callback) { + return this.rpcCall(list, $root.google.cloud.compute.v1beta.ListReservationSlotsRequest, $root.google.cloud.compute.v1beta.ReservationSlotsListResponse, request, callback); + }, "name", { value: "List" }); + + /** + * Calls List. + * @function list + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @instance + * @param {google.cloud.compute.v1beta.IListReservationSlotsRequest} request ListReservationSlotsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.ReservationSlots|update}. + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @typedef UpdateCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls Update. + * @function update + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @instance + * @param {google.cloud.compute.v1beta.IUpdateReservationSlotRequest} request UpdateReservationSlotRequest message or plain object + * @param {google.cloud.compute.v1beta.ReservationSlots.UpdateCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(ReservationSlots.prototype.update = function update(request, callback) { + return this.rpcCall(update, $root.google.cloud.compute.v1beta.UpdateReservationSlotRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "Update" }); + + /** + * Calls Update. + * @function update + * @memberof google.cloud.compute.v1beta.ReservationSlots + * @instance + * @param {google.cloud.compute.v1beta.IUpdateReservationSlotRequest} request UpdateReservationSlotRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return ReservationSlots; + })(); + v1beta.ReservationSubBlocks = (function() { /** @@ -1378578,6 +1401248,39 @@ * @variation 2 */ + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|deleteNamedSet}. + * @memberof google.cloud.compute.v1beta.Routers + * @typedef DeleteNamedSetCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls DeleteNamedSet. + * @function deleteNamedSet + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest} request DeleteNamedSetRouterRequest message or plain object + * @param {google.cloud.compute.v1beta.Routers.DeleteNamedSetCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Routers.prototype.deleteNamedSet = function deleteNamedSet(request, callback) { + return this.rpcCall(deleteNamedSet, $root.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "DeleteNamedSet" }); + + /** + * Calls DeleteNamedSet. + * @function deleteNamedSet + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest} request DeleteNamedSetRouterRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|deleteRoutePolicy}. * @memberof google.cloud.compute.v1beta.Routers @@ -1378644,6 +1401347,39 @@ * @variation 2 */ + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|getNamedSet}. + * @memberof google.cloud.compute.v1beta.Routers + * @typedef GetNamedSetCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.RoutersGetNamedSetResponse} [response] RoutersGetNamedSetResponse + */ + + /** + * Calls GetNamedSet. + * @function getNamedSet + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IGetNamedSetRouterRequest} request GetNamedSetRouterRequest message or plain object + * @param {google.cloud.compute.v1beta.Routers.GetNamedSetCallback} callback Node-style callback called with the error, if any, and RoutersGetNamedSetResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Routers.prototype.getNamedSet = function getNamedSet(request, callback) { + return this.rpcCall(getNamedSet, $root.google.cloud.compute.v1beta.GetNamedSetRouterRequest, $root.google.cloud.compute.v1beta.RoutersGetNamedSetResponse, request, callback); + }, "name", { value: "GetNamedSet" }); + + /** + * Calls GetNamedSet. + * @function getNamedSet + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IGetNamedSetRouterRequest} request GetNamedSetRouterRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|getNatIpInfo}. * @memberof google.cloud.compute.v1beta.Routers @@ -1378875,6 +1401611,39 @@ * @variation 2 */ + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|listNamedSets}. + * @memberof google.cloud.compute.v1beta.Routers + * @typedef ListNamedSetsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.RoutersListNamedSets} [response] RoutersListNamedSets + */ + + /** + * Calls ListNamedSets. + * @function listNamedSets + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IListNamedSetsRoutersRequest} request ListNamedSetsRoutersRequest message or plain object + * @param {google.cloud.compute.v1beta.Routers.ListNamedSetsCallback} callback Node-style callback called with the error, if any, and RoutersListNamedSets + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Routers.prototype.listNamedSets = function listNamedSets(request, callback) { + return this.rpcCall(listNamedSets, $root.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest, $root.google.cloud.compute.v1beta.RoutersListNamedSets, request, callback); + }, "name", { value: "ListNamedSets" }); + + /** + * Calls ListNamedSets. + * @function listNamedSets + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IListNamedSetsRoutersRequest} request ListNamedSetsRoutersRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|listRoutePolicies}. * @memberof google.cloud.compute.v1beta.Routers @@ -1378941,6 +1401710,39 @@ * @variation 2 */ + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|patchNamedSet}. + * @memberof google.cloud.compute.v1beta.Routers + * @typedef PatchNamedSetCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls PatchNamedSet. + * @function patchNamedSet + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IPatchNamedSetRouterRequest} request PatchNamedSetRouterRequest message or plain object + * @param {google.cloud.compute.v1beta.Routers.PatchNamedSetCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Routers.prototype.patchNamedSet = function patchNamedSet(request, callback) { + return this.rpcCall(patchNamedSet, $root.google.cloud.compute.v1beta.PatchNamedSetRouterRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "PatchNamedSet" }); + + /** + * Calls PatchNamedSet. + * @function patchNamedSet + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IPatchNamedSetRouterRequest} request PatchNamedSetRouterRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|patchRoutePolicy}. * @memberof google.cloud.compute.v1beta.Routers @@ -1379073,6 +1401875,39 @@ * @variation 2 */ + /** + * Callback as used by {@link google.cloud.compute.v1beta.Routers|updateNamedSet}. + * @memberof google.cloud.compute.v1beta.Routers + * @typedef UpdateNamedSetCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls UpdateNamedSet. + * @function updateNamedSet + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest} request UpdateNamedSetRouterRequest message or plain object + * @param {google.cloud.compute.v1beta.Routers.UpdateNamedSetCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Routers.prototype.updateNamedSet = function updateNamedSet(request, callback) { + return this.rpcCall(updateNamedSet, $root.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "UpdateNamedSet" }); + + /** + * Calls UpdateNamedSet. + * @function updateNamedSet + * @memberof google.cloud.compute.v1beta.Routers + * @instance + * @param {google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest} request UpdateNamedSetRouterRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + /** * Callback as used by {@link google.cloud.compute.v1beta.Routers|updateRoutePolicy}. * @memberof google.cloud.compute.v1beta.Routers @@ -1380105,6 +1402940,272 @@ return ServiceAttachments; })(); + v1beta.SnapshotGroups = (function() { + + /** + * Constructs a new SnapshotGroups service. + * @memberof google.cloud.compute.v1beta + * @classdesc Represents a SnapshotGroups + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function SnapshotGroups(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (SnapshotGroups.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = SnapshotGroups; + + /** + * Creates new SnapshotGroups service using the specified rpc implementation. + * @function create + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {SnapshotGroups} RPC service. Useful where requests and/or responses are streamed. + */ + SnapshotGroups.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|delete_}. + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @typedef DeleteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls Delete. + * @function delete + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest} request DeleteSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.SnapshotGroups.DeleteCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(SnapshotGroups.prototype["delete"] = function delete_(request, callback) { + return this.rpcCall(delete_, $root.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "Delete" }); + + /** + * Calls Delete. + * @function delete + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest} request DeleteSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|get}. + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @typedef GetCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.SnapshotGroup} [response] SnapshotGroup + */ + + /** + * Calls Get. + * @function get + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetSnapshotGroupRequest} request GetSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.SnapshotGroups.GetCallback} callback Node-style callback called with the error, if any, and SnapshotGroup + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(SnapshotGroups.prototype.get = function get(request, callback) { + return this.rpcCall(get, $root.google.cloud.compute.v1beta.GetSnapshotGroupRequest, $root.google.cloud.compute.v1beta.SnapshotGroup, request, callback); + }, "name", { value: "Get" }); + + /** + * Calls Get. + * @function get + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetSnapshotGroupRequest} request GetSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|getIamPolicy}. + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @typedef GetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Policy} [response] Policy + */ + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest} request GetIamPolicySnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.SnapshotGroups.GetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(SnapshotGroups.prototype.getIamPolicy = function getIamPolicy(request, callback) { + return this.rpcCall(getIamPolicy, $root.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest, $root.google.cloud.compute.v1beta.Policy, request, callback); + }, "name", { value: "GetIamPolicy" }); + + /** + * Calls GetIamPolicy. + * @function getIamPolicy + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest} request GetIamPolicySnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|insert}. + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @typedef InsertCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Operation} [response] Operation + */ + + /** + * Calls Insert. + * @function insert + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IInsertSnapshotGroupRequest} request InsertSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.SnapshotGroups.InsertCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(SnapshotGroups.prototype.insert = function insert(request, callback) { + return this.rpcCall(insert, $root.google.cloud.compute.v1beta.InsertSnapshotGroupRequest, $root.google.cloud.compute.v1beta.Operation, request, callback); + }, "name", { value: "Insert" }); + + /** + * Calls Insert. + * @function insert + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IInsertSnapshotGroupRequest} request InsertSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|list}. + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @typedef ListCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.ListSnapshotGroups} [response] ListSnapshotGroups + */ + + /** + * Calls List. + * @function list + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IListSnapshotGroupsRequest} request ListSnapshotGroupsRequest message or plain object + * @param {google.cloud.compute.v1beta.SnapshotGroups.ListCallback} callback Node-style callback called with the error, if any, and ListSnapshotGroups + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(SnapshotGroups.prototype.list = function list(request, callback) { + return this.rpcCall(list, $root.google.cloud.compute.v1beta.ListSnapshotGroupsRequest, $root.google.cloud.compute.v1beta.ListSnapshotGroups, request, callback); + }, "name", { value: "List" }); + + /** + * Calls List. + * @function list + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.IListSnapshotGroupsRequest} request ListSnapshotGroupsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|setIamPolicy}. + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @typedef SetIamPolicyCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.Policy} [response] Policy + */ + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest} request SetIamPolicySnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.SnapshotGroups.SetIamPolicyCallback} callback Node-style callback called with the error, if any, and Policy + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(SnapshotGroups.prototype.setIamPolicy = function setIamPolicy(request, callback) { + return this.rpcCall(setIamPolicy, $root.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest, $root.google.cloud.compute.v1beta.Policy, request, callback); + }, "name", { value: "SetIamPolicy" }); + + /** + * Calls SetIamPolicy. + * @function setIamPolicy + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest} request SetIamPolicySnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.compute.v1beta.SnapshotGroups|testIamPermissions}. + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @typedef TestIamPermissionsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.compute.v1beta.TestPermissionsResponse} [response] TestPermissionsResponse + */ + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest} request TestIamPermissionsSnapshotGroupRequest message or plain object + * @param {google.cloud.compute.v1beta.SnapshotGroups.TestIamPermissionsCallback} callback Node-style callback called with the error, if any, and TestPermissionsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(SnapshotGroups.prototype.testIamPermissions = function testIamPermissions(request, callback) { + return this.rpcCall(testIamPermissions, $root.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest, $root.google.cloud.compute.v1beta.TestPermissionsResponse, request, callback); + }, "name", { value: "TestIamPermissions" }); + + /** + * Calls TestIamPermissions. + * @function testIamPermissions + * @memberof google.cloud.compute.v1beta.SnapshotGroups + * @instance + * @param {google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest} request TestIamPermissionsSnapshotGroupRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return SnapshotGroups; + })(); + v1beta.SnapshotSettingsService = (function() { /** diff --git a/packages/google-cloud-compute/protos/protos.json b/packages/google-cloud-compute/protos/protos.json index 46f923b7702..a26cbf6c9b8 100644 --- a/packages/google-cloud-compute/protos/protos.json +++ b/packages/google-cloud-compute/protos/protos.json @@ -128403,6 +128403,11 @@ "maxUtilization" ] }, + "_orchestrationInfo": { + "oneof": [ + "orchestrationInfo" + ] + }, "_preference": { "oneof": [ "preference" @@ -128525,6 +128530,13 @@ "proto3_optional": true } }, + "orchestrationInfo": { + "type": "BackendBackendOrchestrationInfo", + "id": 441144300, + "options": { + "proto3_optional": true + } + }, "preference": { "type": "string", "id": 150781147, @@ -128569,6 +128581,24 @@ } } }, + "BackendBackendOrchestrationInfo": { + "oneofs": { + "_resourceUri": { + "oneof": [ + "resourceUri" + ] + } + }, + "fields": { + "resourceUri": { + "type": "string", + "id": 152830395, + "options": { + "proto3_optional": true + } + } + } + }, "BackendBucket": { "oneofs": { "_bucketName": { @@ -129418,6 +129448,11 @@ "networkPassThroughLbTrafficPolicy" ] }, + "_orchestrationInfo": { + "oneof": [ + "orchestrationInfo" + ] + }, "_outlierDetection": { "oneof": [ "outlierDetection" @@ -129726,6 +129761,13 @@ "proto3_optional": true } }, + "orchestrationInfo": { + "type": "BackendServiceOrchestrationInfo", + "id": 441144300, + "options": { + "proto3_optional": true + } + }, "outlierDetection": { "type": "OutlierDetection", "id": 354625086, @@ -130930,6 +130972,24 @@ } } }, + "BackendServiceOrchestrationInfo": { + "oneofs": { + "_resourceUri": { + "oneof": [ + "resourceUri" + ] + } + }, + "fields": { + "resourceUri": { + "type": "string", + "id": 152830395, + "options": { + "proto3_optional": true + } + } + } + }, "BackendServiceParams": { "fields": { "resourceManagerTags": { @@ -131736,6 +131796,16 @@ }, "BulkInsertDiskResource": { "oneofs": { + "_instantSnapshotGroupParameters": { + "oneof": [ + "instantSnapshotGroupParameters" + ] + }, + "_snapshotGroupParameters": { + "oneof": [ + "snapshotGroupParameters" + ] + }, "_sourceConsistencyGroupPolicy": { "oneof": [ "sourceConsistencyGroupPolicy" @@ -131743,6 +131813,20 @@ } }, "fields": { + "instantSnapshotGroupParameters": { + "type": "InstantSnapshotGroupParameters", + "id": 17051623, + "options": { + "proto3_optional": true + } + }, + "snapshotGroupParameters": { + "type": "SnapshotGroupParameters", + "id": 42252485, + "options": { + "proto3_optional": true + } + }, "sourceConsistencyGroupPolicy": { "type": "string", "id": 19616093, @@ -132289,6 +132373,220 @@ } } }, + "CachePolicy": { + "oneofs": { + "_cacheKeyPolicy": { + "oneof": [ + "cacheKeyPolicy" + ] + }, + "_cacheMode": { + "oneof": [ + "cacheMode" + ] + }, + "_clientTtl": { + "oneof": [ + "clientTtl" + ] + }, + "_defaultTtl": { + "oneof": [ + "defaultTtl" + ] + }, + "_maxTtl": { + "oneof": [ + "maxTtl" + ] + }, + "_negativeCaching": { + "oneof": [ + "negativeCaching" + ] + }, + "_requestCoalescing": { + "oneof": [ + "requestCoalescing" + ] + }, + "_serveWhileStale": { + "oneof": [ + "serveWhileStale" + ] + } + }, + "fields": { + "cacheBypassRequestHeaderNames": { + "rule": "repeated", + "type": "string", + "id": 197581440 + }, + "cacheKeyPolicy": { + "type": "CachePolicyCacheKeyPolicy", + "id": 159263727, + "options": { + "proto3_optional": true + } + }, + "cacheMode": { + "type": "string", + "id": 28877888, + "options": { + "proto3_optional": true + } + }, + "clientTtl": { + "type": "Duration", + "id": 29034360, + "options": { + "proto3_optional": true + } + }, + "defaultTtl": { + "type": "Duration", + "id": 100253422, + "options": { + "proto3_optional": true + } + }, + "maxTtl": { + "type": "Duration", + "id": 307578001, + "options": { + "proto3_optional": true + } + }, + "negativeCaching": { + "type": "bool", + "id": 336110005, + "options": { + "proto3_optional": true + } + }, + "negativeCachingPolicy": { + "rule": "repeated", + "type": "CachePolicyNegativeCachingPolicy", + "id": 155359996 + }, + "requestCoalescing": { + "type": "bool", + "id": 532808276, + "options": { + "proto3_optional": true + } + }, + "serveWhileStale": { + "type": "Duration", + "id": 236682203, + "options": { + "proto3_optional": true + } + } + }, + "nested": { + "CacheMode": { + "values": { + "UNDEFINED_CACHE_MODE": 0, + "CACHE_ALL_STATIC": 355027945, + "FORCE_CACHE_ALL": 486026928, + "USE_ORIGIN_HEADERS": 55380261 + } + } + } + }, + "CachePolicyCacheKeyPolicy": { + "oneofs": { + "_includeHost": { + "oneof": [ + "includeHost" + ] + }, + "_includeProtocol": { + "oneof": [ + "includeProtocol" + ] + }, + "_includeQueryString": { + "oneof": [ + "includeQueryString" + ] + } + }, + "fields": { + "excludedQueryParameters": { + "rule": "repeated", + "type": "string", + "id": 124896150 + }, + "includeHost": { + "type": "bool", + "id": 486867679, + "options": { + "proto3_optional": true + } + }, + "includeProtocol": { + "type": "bool", + "id": 303507535, + "options": { + "proto3_optional": true + } + }, + "includeQueryString": { + "type": "bool", + "id": 474036639, + "options": { + "proto3_optional": true + } + }, + "includedCookieNames": { + "rule": "repeated", + "type": "string", + "id": 66987088 + }, + "includedHeaderNames": { + "rule": "repeated", + "type": "string", + "id": 533756345 + }, + "includedQueryParameters": { + "rule": "repeated", + "type": "string", + "id": 2319076 + } + } + }, + "CachePolicyNegativeCachingPolicy": { + "oneofs": { + "_code": { + "oneof": [ + "code" + ] + }, + "_ttl": { + "oneof": [ + "ttl" + ] + } + }, + "fields": { + "code": { + "type": "int32", + "id": 3059181, + "options": { + "proto3_optional": true + } + }, + "ttl": { + "type": "Duration", + "id": 115180, + "options": { + "proto3_optional": true + } + } + } + }, "CalendarModeAdviceRequest": { "fields": { "futureResourcesSpecs": { @@ -133078,6 +133376,7 @@ "GENERAL_PURPOSE_N2": 301912156, "GENERAL_PURPOSE_N2D": 232471400, "GENERAL_PURPOSE_N4": 301912158, + "GENERAL_PURPOSE_N4A": 232471459, "GENERAL_PURPOSE_N4D": 232471462, "GENERAL_PURPOSE_T2D": 232477166, "GRAPHICS_OPTIMIZED": 68500563, @@ -133631,6 +133930,54 @@ } } }, + "ConfigureAcceleratorTopologiesInstanceGroupManagerRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "instanceGroupManager": { + "type": "string", + "id": 249363395, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "instanceGroupManagersConfigureAcceleratorTopologiesRequestResource": { + "type": "InstanceGroupManagersConfigureAcceleratorTopologiesRequest", + "id": 365743316, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "zone" + } + } + } + }, "ConnectionDraining": { "oneofs": { "_drainingTimeoutSec": { @@ -135508,6 +135855,47 @@ } } }, + "DeleteInstantSnapshotGroupRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "instantSnapshotGroup": { + "type": "string", + "id": 223180386, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "zone" + } + } + } + }, "DeleteInstantSnapshotRequest": { "oneofs": { "_requestId": { @@ -135755,6 +136143,59 @@ } } }, + "DeleteNamedSetRouterRequest": { + "oneofs": { + "_namedSet": { + "oneof": [ + "namedSet" + ] + }, + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "namedSet": { + "type": "string", + "id": 164134492, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "region" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "router": { + "type": "string", + "id": 148608841, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "DeleteNetworkAttachmentRequest": { "oneofs": { "_requestId": { @@ -136841,6 +137282,47 @@ } } }, + "DeleteRegionInstantSnapshotGroupRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "instantSnapshotGroup": { + "type": "string", + "id": 223180386, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "region" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + } + } + }, "DeleteRegionInstantSnapshotRequest": { "oneofs": { "_requestId": { @@ -137872,6 +138354,39 @@ } } }, + "DeleteSnapshotGroupRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "snapshotGroup": { + "type": "string", + "id": 84528196, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "DeleteSnapshotRequest": { "oneofs": { "_requestId": { @@ -141056,6 +141571,11 @@ "name" ] }, + "_params": { + "oneof": [ + "params" + ] + }, "_redundancyType": { "oneof": [ "redundancyType" @@ -141120,6 +141640,13 @@ "proto3_optional": true } }, + "params": { + "type": "ExternalVpnGatewayParams", + "id": 78313862, + "options": { + "proto3_optional": true + } + }, "redundancyType": { "type": "string", "id": 271443740, @@ -141271,6 +141798,15 @@ } } }, + "ExternalVpnGatewayParams": { + "fields": { + "resourceManagerTags": { + "keyType": "string", + "type": "string", + "id": 377671164 + } + } + }, "FileContentBuffer": { "oneofs": { "_content": { @@ -141898,7 +142434,9 @@ "PolicyType": { "values": { "UNDEFINED_POLICY_TYPE": 0, + "RDMA_FALCON_POLICY": 66315047, "RDMA_ROCE_POLICY": 148757145, + "ULL_POLICY": 100494364, "VPC_POLICY": 74319208 } } @@ -143328,6 +143866,11 @@ }, "FutureReservation": { "oneofs": { + "_advancedDeploymentControl": { + "oneof": [ + "advancedDeploymentControl" + ] + }, "_aggregateReservation": { "oneof": [ "aggregateReservation" @@ -143460,6 +144003,13 @@ } }, "fields": { + "advancedDeploymentControl": { + "type": "ReservationAdvancedDeploymentControl", + "id": 410618144, + "options": { + "proto3_optional": true + } + }, "aggregateReservation": { "type": "AllocationAggregateReservation", "id": 291567948, @@ -145980,6 +146530,45 @@ } } }, + "GetIamPolicyInstantSnapshotGroupRequest": { + "oneofs": { + "_optionsRequestedPolicyVersion": { + "oneof": [ + "optionsRequestedPolicyVersion" + ] + } + }, + "fields": { + "optionsRequestedPolicyVersion": { + "type": "int32", + "id": 499220029, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "GetIamPolicyInstantSnapshotRequest": { "oneofs": { "_optionsRequestedPolicyVersion": { @@ -146413,6 +147002,45 @@ } } }, + "GetIamPolicyRegionInstantSnapshotGroupRequest": { + "oneofs": { + "_optionsRequestedPolicyVersion": { + "oneof": [ + "optionsRequestedPolicyVersion" + ] + } + }, + "fields": { + "optionsRequestedPolicyVersion": { + "type": "int32", + "id": 499220029, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "GetIamPolicyRegionInstantSnapshotRequest": { "oneofs": { "_optionsRequestedPolicyVersion": { @@ -146739,6 +147367,38 @@ } } }, + "GetIamPolicySnapshotGroupRequest": { + "oneofs": { + "_optionsRequestedPolicyVersion": { + "oneof": [ + "optionsRequestedPolicyVersion" + ] + } + }, + "fields": { + "optionsRequestedPolicyVersion": { + "type": "int32", + "id": 499220029, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "GetIamPolicySnapshotRequest": { "oneofs": { "_optionsRequestedPolicyVersion": { @@ -147083,6 +147743,31 @@ } } }, + "GetInstantSnapshotGroupRequest": { + "fields": { + "instantSnapshotGroup": { + "type": "string", + "id": 223180386, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "GetInstantSnapshotRequest": { "fields": { "instantSnapshot": { @@ -147320,6 +148005,45 @@ } } }, + "GetNamedSetRouterRequest": { + "oneofs": { + "_namedSet": { + "oneof": [ + "namedSet" + ] + } + }, + "fields": { + "namedSet": { + "type": "string", + "id": 164134492, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "router": { + "type": "string", + "id": 148608841, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "GetNatIpInfoRouterRequest": { "oneofs": { "_natName": { @@ -148326,6 +149050,31 @@ } } }, + "GetRegionInstantSnapshotGroupRequest": { + "fields": { + "instantSnapshotGroup": { + "type": "string", + "id": 223180386, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "GetRegionInstantSnapshotRequest": { "fields": { "instantSnapshot": { @@ -148851,6 +149600,38 @@ } } }, + "GetReservationSlotRequest": { + "fields": { + "parentName": { + "type": "string", + "id": 478151936, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "reservationSlot": { + "type": "string", + "id": 277470865, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "GetReservationSubBlockRequest": { "oneofs": { "_view": { @@ -149450,6 +150231,24 @@ } } }, + "GetSnapshotGroupRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "snapshotGroup": { + "type": "string", + "id": 84528196, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "GetSnapshotRequest": { "fields": { "project": { @@ -153475,6 +154274,11 @@ }, "HttpRouteAction": { "oneofs": { + "_cachePolicy": { + "oneof": [ + "cachePolicy" + ] + }, "_corsPolicy": { "oneof": [ "corsPolicy" @@ -153512,6 +154316,13 @@ } }, "fields": { + "cachePolicy": { + "type": "CachePolicy", + "id": 457366671, + "options": { + "proto3_optional": true + } + }, "corsPolicy": { "type": "CorsPolicy", "id": 398943748, @@ -155228,6 +156039,59 @@ } } }, + "InsertInstantSnapshotGroupRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + }, + "_sourceConsistencyGroup": { + "oneof": [ + "sourceConsistencyGroup" + ] + } + }, + "fields": { + "instantSnapshotGroupResource": { + "type": "InstantSnapshotGroup", + "id": 145067339, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "sourceConsistencyGroup": { + "type": "string", + "id": 531359348, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "zone" + } + } + } + }, "InsertInstantSnapshotRequest": { "oneofs": { "_requestId": { @@ -156494,18 +157358,23 @@ } } }, - "InsertRegionInstantSnapshotRequest": { + "InsertRegionInstantSnapshotGroupRequest": { "oneofs": { "_requestId": { "oneof": [ "requestId" ] + }, + "_sourceConsistencyGroup": { + "oneof": [ + "sourceConsistencyGroup" + ] } }, "fields": { - "instantSnapshotResource": { - "type": "InstantSnapshot", - "id": 383915339, + "instantSnapshotGroupResource": { + "type": "InstantSnapshotGroup", + "id": 145067339, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -156532,10 +157401,17 @@ "options": { "proto3_optional": true } + }, + "sourceConsistencyGroup": { + "type": "string", + "id": 531359348, + "options": { + "proto3_optional": true + } } } }, - "InsertRegionMultiMigRequest": { + "InsertRegionInstantSnapshotRequest": { "oneofs": { "_requestId": { "oneof": [ @@ -156544,9 +157420,9 @@ } }, "fields": { - "multiMigResource": { - "type": "MultiMig", - "id": 173722824, + "instantSnapshotResource": { + "type": "InstantSnapshot", + "id": 383915339, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -156576,7 +157452,7 @@ } } }, - "InsertRegionNetworkEndpointGroupRequest": { + "InsertRegionMultiMigRequest": { "oneofs": { "_requestId": { "oneof": [ @@ -156585,9 +157461,9 @@ } }, "fields": { - "networkEndpointGroupResource": { - "type": "NetworkEndpointGroup", - "id": 525788839, + "multiMigResource": { + "type": "MultiMig", + "id": 173722824, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -156617,7 +157493,7 @@ } } }, - "InsertRegionNetworkFirewallPolicyRequest": { + "InsertRegionNetworkEndpointGroupRequest": { "oneofs": { "_requestId": { "oneof": [ @@ -156626,9 +157502,9 @@ } }, "fields": { - "firewallPolicyResource": { - "type": "FirewallPolicy", - "id": 495049532, + "networkEndpointGroupResource": { + "type": "NetworkEndpointGroup", + "id": 525788839, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -156658,7 +157534,7 @@ } } }, - "InsertRegionNetworkPolicyRequest": { + "InsertRegionNetworkFirewallPolicyRequest": { "oneofs": { "_requestId": { "oneof": [ @@ -156667,9 +157543,9 @@ } }, "fields": { - "networkPolicyResource": { - "type": "NetworkPolicy", - "id": 437886058, + "firewallPolicyResource": { + "type": "FirewallPolicy", + "id": 495049532, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -156699,7 +157575,7 @@ } } }, - "InsertRegionNotificationEndpointRequest": { + "InsertRegionNetworkPolicyRequest": { "oneofs": { "_requestId": { "oneof": [ @@ -156708,9 +157584,50 @@ } }, "fields": { - "notificationEndpointResource": { - "type": "NotificationEndpoint", - "id": 338459940, + "networkPolicyResource": { + "type": "NetworkPolicy", + "id": 437886058, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "region" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + } + } + }, + "InsertRegionNotificationEndpointRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "notificationEndpointResource": { + "type": "NotificationEndpoint", + "id": 338459940, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -157355,6 +158272,39 @@ } } }, + "InsertSnapshotGroupRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "snapshotGroupResource": { + "type": "SnapshotGroup", + "id": 265205161, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "InsertSnapshotRequest": { "oneofs": { "_requestId": { @@ -158249,6 +159199,11 @@ "tags" ] }, + "_workloadIdentityConfig": { + "oneof": [ + "workloadIdentityConfig" + ] + }, "_zone": { "oneof": [ "zone" @@ -158592,6 +159547,13 @@ "proto3_optional": true } }, + "workloadIdentityConfig": { + "type": "WorkloadIdentityConfig", + "id": 338198811, + "options": { + "proto3_optional": true + } + }, "zone": { "type": "string", "id": 3744684, @@ -160542,6 +161504,11 @@ "bulkInstanceOperation" ] }, + "_currentInstanceStatuses": { + "oneof": [ + "currentInstanceStatuses" + ] + }, "_isStable": { "oneof": [ "isStable" @@ -160580,6 +161547,13 @@ "proto3_optional": true } }, + "currentInstanceStatuses": { + "type": "InstanceGroupManagerStatusInstanceStatusSummary", + "id": 269432644, + "options": { + "proto3_optional": true + } + }, "isStable": { "type": "bool", "id": 108410864, @@ -160693,6 +161667,168 @@ } } }, + "InstanceGroupManagerStatusInstanceStatusSummary": { + "oneofs": { + "_deprovisioning": { + "oneof": [ + "deprovisioning" + ] + }, + "_nonExistent": { + "oneof": [ + "nonExistent" + ] + }, + "_pending": { + "oneof": [ + "pending" + ] + }, + "_pendingStop": { + "oneof": [ + "pendingStop" + ] + }, + "_provisioning": { + "oneof": [ + "provisioning" + ] + }, + "_repairing": { + "oneof": [ + "repairing" + ] + }, + "_running": { + "oneof": [ + "running" + ] + }, + "_staging": { + "oneof": [ + "staging" + ] + }, + "_stopped": { + "oneof": [ + "stopped" + ] + }, + "_stopping": { + "oneof": [ + "stopping" + ] + }, + "_suspended": { + "oneof": [ + "suspended" + ] + }, + "_suspending": { + "oneof": [ + "suspending" + ] + }, + "_terminated": { + "oneof": [ + "terminated" + ] + } + }, + "fields": { + "deprovisioning": { + "type": "int32", + "id": 462169582, + "options": { + "proto3_optional": true + } + }, + "nonExistent": { + "type": "int32", + "id": 468485062, + "options": { + "proto3_optional": true + } + }, + "pending": { + "type": "int32", + "id": 391154071, + "options": { + "proto3_optional": true + } + }, + "pendingStop": { + "type": "int32", + "id": 163159466, + "options": { + "proto3_optional": true + } + }, + "provisioning": { + "type": "int32", + "id": 121098989, + "options": { + "proto3_optional": true + } + }, + "repairing": { + "type": "int32", + "id": 311243061, + "options": { + "proto3_optional": true + } + }, + "running": { + "type": "int32", + "id": 477042111, + "options": { + "proto3_optional": true + } + }, + "staging": { + "type": "int32", + "id": 249960507, + "options": { + "proto3_optional": true + } + }, + "stopped": { + "type": "int32", + "id": 263164365, + "options": { + "proto3_optional": true + } + }, + "stopping": { + "type": "int32", + "id": 105035892, + "options": { + "proto3_optional": true + } + }, + "suspended": { + "type": "int32", + "id": 485854683, + "options": { + "proto3_optional": true + } + }, + "suspending": { + "type": "int32", + "id": 29113894, + "options": { + "proto3_optional": true + } + }, + "terminated": { + "type": "int32", + "id": 301796899, + "options": { + "proto3_optional": true + } + } + } + }, "InstanceGroupManagerStatusStateful": { "oneofs": { "_hasStatefulConfig": { @@ -161041,6 +162177,15 @@ } } }, + "InstanceGroupManagersConfigureAcceleratorTopologiesRequest": { + "fields": { + "acceleratorTopologyActions": { + "keyType": "string", + "type": "string", + "id": 16520833 + } + } + }, "InstanceGroupManagersCreateInstancesRequest": { "fields": { "instances": { @@ -161083,11 +162228,25 @@ } }, "InstanceGroupManagersGetAvailableAcceleratorTopologiesResponse": { + "oneofs": { + "_multiMig": { + "oneof": [ + "multiMig" + ] + } + }, "fields": { "acceleratorTopologiesInfo": { "keyType": "string", "type": "InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyInfo", "id": 84833420 + }, + "multiMig": { + "type": "string", + "id": 403990085, + "options": { + "proto3_optional": true + } } } }, @@ -161102,6 +162261,21 @@ "oneof": [ "acceleratorTopologyHealth" ] + }, + "_acceleratorTopologyState": { + "oneof": [ + "acceleratorTopologyState" + ] + }, + "_instancesHealth": { + "oneof": [ + "instancesHealth" + ] + }, + "_parent": { + "oneof": [ + "parent" + ] } }, "fields": { @@ -161118,6 +162292,27 @@ "options": { "proto3_optional": true } + }, + "acceleratorTopologyState": { + "type": "InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState", + "id": 228860693, + "options": { + "proto3_optional": true + } + }, + "instancesHealth": { + "type": "string", + "id": 165893949, + "options": { + "proto3_optional": true + } + }, + "parent": { + "type": "string", + "id": 78317738, + "options": { + "proto3_optional": true + } } }, "nested": { @@ -161126,7 +162321,71 @@ "UNDEFINED_ACCELERATOR_TOPOLOGY_HEALTH": 0, "DEGRADED": 396890926, "HEALTHY": 439801213, - "UNHEALTHY": 462118084 + "UNHEALTHY": 462118084, + "UNKNOWN": 433141802 + } + }, + "InstancesHealth": { + "values": { + "UNDEFINED_INSTANCES_HEALTH": 0, + "ALL_HEALTHY": 519465151, + "UNHEALTHY_OR_MISSING": 59982149 + } + } + } + }, + "InstanceGroupManagersGetAvailableAcceleratorTopologiesResponseAcceleratorTopologyState": { + "oneofs": { + "_currentState": { + "oneof": [ + "currentState" + ] + }, + "_error": { + "oneof": [ + "error" + ] + }, + "_errorTimestamp": { + "oneof": [ + "errorTimestamp" + ] + } + }, + "fields": { + "currentState": { + "type": "string", + "id": 438511179, + "options": { + "proto3_optional": true + } + }, + "error": { + "type": "Error", + "id": 96784904, + "options": { + "proto3_optional": true + } + }, + "errorTimestamp": { + "type": "string", + "id": 219548575, + "options": { + "proto3_optional": true + } + } + }, + "nested": { + "CurrentState": { + "values": { + "UNDEFINED_CURRENT_STATE": 0, + "ACTIVATING": 378825968, + "ACTIVE": 314733318, + "ACTIVE_DEGRADED": 471128135, + "DEACTIVATING": 57182257, + "FAILED": 455706685, + "INACTIVE": 270421099, + "INCOMPLETE": 11941214 } } } @@ -161984,6 +163243,11 @@ "oneof": [ "tags" ] + }, + "_workloadIdentityConfig": { + "oneof": [ + "workloadIdentityConfig" + ] } }, "fields": { @@ -162145,6 +163409,13 @@ "options": { "proto3_optional": true } + }, + "workloadIdentityConfig": { + "type": "WorkloadIdentityConfig", + "id": 338198811, + "options": { + "proto3_optional": true + } } }, "nested": { @@ -162853,6 +164124,7 @@ "values": { "UNDEFINED_BEHAVIOR": 0, "BEHAVIOR_UNSPECIFIED": 85734570, + "CHIP_ERROR": 263151669, "PERFORMANCE": 135701520, "SILENT_DATA_CORRUPTION": 111360678, "UNRECOVERABLE_GPU_ERROR": 363710747 @@ -163101,6 +164373,11 @@ "name" ] }, + "_params": { + "oneof": [ + "params" + ] + }, "_region": { "oneof": [ "region" @@ -163141,6 +164418,16 @@ "sourceDiskId" ] }, + "_sourceInstantSnapshotGroup": { + "oneof": [ + "sourceInstantSnapshotGroup" + ] + }, + "_sourceInstantSnapshotGroupId": { + "oneof": [ + "sourceInstantSnapshotGroupId" + ] + }, "_status": { "oneof": [ "status" @@ -163214,6 +164501,13 @@ "proto3_optional": true } }, + "params": { + "type": "InstantSnapshotParams", + "id": 78313862, + "options": { + "proto3_optional": true + } + }, "region": { "type": "string", "id": 138946292, @@ -163270,6 +164564,20 @@ "proto3_optional": true } }, + "sourceInstantSnapshotGroup": { + "type": "string", + "id": 525991686, + "options": { + "proto3_optional": true + } + }, + "sourceInstantSnapshotGroupId": { + "type": "string", + "id": 167103732, + "options": { + "proto3_optional": true + } + }, "status": { "type": "string", "id": 181260274, @@ -163382,6 +164690,247 @@ } } }, + "InstantSnapshotGroup": { + "oneofs": { + "_creationTimestamp": { + "oneof": [ + "creationTimestamp" + ] + }, + "_description": { + "oneof": [ + "description" + ] + }, + "_id": { + "oneof": [ + "id" + ] + }, + "_kind": { + "oneof": [ + "kind" + ] + }, + "_name": { + "oneof": [ + "name" + ] + }, + "_region": { + "oneof": [ + "region" + ] + }, + "_resourceStatus": { + "oneof": [ + "resourceStatus" + ] + }, + "_selfLink": { + "oneof": [ + "selfLink" + ] + }, + "_selfLinkWithId": { + "oneof": [ + "selfLinkWithId" + ] + }, + "_sourceConsistencyGroup": { + "oneof": [ + "sourceConsistencyGroup" + ] + }, + "_status": { + "oneof": [ + "status" + ] + }, + "_zone": { + "oneof": [ + "zone" + ] + } + }, + "fields": { + "creationTimestamp": { + "type": "string", + "id": 30525366, + "options": { + "proto3_optional": true + } + }, + "description": { + "type": "string", + "id": 422937596, + "options": { + "proto3_optional": true + } + }, + "id": { + "type": "uint64", + "id": 3355, + "options": { + "proto3_optional": true + } + }, + "kind": { + "type": "string", + "id": 3292052, + "options": { + "proto3_optional": true + } + }, + "name": { + "type": "string", + "id": 3373707, + "options": { + "proto3_optional": true + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "proto3_optional": true + } + }, + "resourceStatus": { + "type": "InstantSnapshotGroupResourceStatus", + "id": 249429315, + "options": { + "proto3_optional": true + } + }, + "selfLink": { + "type": "string", + "id": 456214797, + "options": { + "proto3_optional": true + } + }, + "selfLinkWithId": { + "type": "string", + "id": 44520962, + "options": { + "proto3_optional": true + } + }, + "sourceConsistencyGroup": { + "type": "string", + "id": 531359348, + "options": { + "proto3_optional": true + } + }, + "status": { + "type": "string", + "id": 181260274, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "proto3_optional": true + } + } + }, + "nested": { + "Status": { + "values": { + "UNDEFINED_STATUS": 0, + "CREATING": 455564985, + "DELETING": 528602024, + "FAILED": 455706685, + "INVALID": 530283991, + "READY": 77848963, + "UNKNOWN": 433141802 + } + } + } + }, + "InstantSnapshotGroupParameters": { + "oneofs": { + "_sourceInstantSnapshotGroup": { + "oneof": [ + "sourceInstantSnapshotGroup" + ] + } + }, + "fields": { + "sourceInstantSnapshotGroup": { + "type": "string", + "id": 525991686, + "options": { + "proto3_optional": true + } + } + } + }, + "InstantSnapshotGroupResourceStatus": { + "oneofs": { + "_consistencyMembershipResolutionTime": { + "oneof": [ + "consistencyMembershipResolutionTime" + ] + }, + "_sourceInfo": { + "oneof": [ + "sourceInfo" + ] + } + }, + "fields": { + "consistencyMembershipResolutionTime": { + "type": "string", + "id": 346675870, + "options": { + "proto3_optional": true + } + }, + "sourceInfo": { + "type": "InstantSnapshotGroupSourceInfo", + "id": 451907154, + "options": { + "proto3_optional": true + } + } + } + }, + "InstantSnapshotGroupSourceInfo": { + "oneofs": { + "_consistencyGroup": { + "oneof": [ + "consistencyGroup" + ] + }, + "_consistencyGroupId": { + "oneof": [ + "consistencyGroupId" + ] + } + }, + "fields": { + "consistencyGroup": { + "type": "string", + "id": 508183960, + "options": { + "proto3_optional": true + } + }, + "consistencyGroupId": { + "type": "string", + "id": 85599522, + "options": { + "proto3_optional": true + } + } + } + }, "InstantSnapshotList": { "oneofs": { "_id": { @@ -163453,6 +165002,15 @@ } } }, + "InstantSnapshotParams": { + "fields": { + "resourceManagerTags": { + "keyType": "string", + "type": "string", + "id": 377671164 + } + } + }, "InstantSnapshotResourceStatus": { "oneofs": { "_storageSizeBytes": { @@ -171838,87 +173396,255 @@ } } }, - "ListInstantSnapshotsRequest": { + "ListInstantSnapshotGroups": { "oneofs": { - "_filter": { + "_etag": { "oneof": [ - "filter" + "etag" ] }, - "_maxResults": { + "_id": { "oneof": [ - "maxResults" + "id" ] }, - "_orderBy": { + "_kind": { "oneof": [ - "orderBy" + "kind" ] }, - "_pageToken": { + "_nextPageToken": { "oneof": [ - "pageToken" + "nextPageToken" ] }, - "_returnPartialSuccess": { + "_selfLink": { "oneof": [ - "returnPartialSuccess" + "selfLink" + ] + }, + "_warning": { + "oneof": [ + "warning" ] } }, "fields": { - "filter": { + "etag": { "type": "string", - "id": 336120696, + "id": 3123477, "options": { "proto3_optional": true } }, - "maxResults": { - "type": "uint32", - "id": 54715419, + "id": { + "type": "string", + "id": 3355, "options": { "proto3_optional": true } }, - "orderBy": { + "items": { + "rule": "repeated", + "type": "InstantSnapshotGroup", + "id": 100526016 + }, + "kind": { "type": "string", - "id": 160562920, + "id": 3292052, "options": { "proto3_optional": true } }, - "pageToken": { + "nextPageToken": { "type": "string", - "id": 19994697, + "id": 79797525, "options": { "proto3_optional": true } }, - "project": { + "selfLink": { "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "returnPartialSuccess": { - "type": "bool", - "id": 517198390, + "id": 456214797, "options": { "proto3_optional": true } }, - "zone": { + "unreachables": { + "rule": "repeated", "type": "string", - "id": 3744684, + "id": 243372063 + }, + "warning": { + "type": "Warning", + "id": 50704284, "options": { - "(google.api.field_behavior)": "REQUIRED" + "proto3_optional": true } } } }, - "ListInterconnectAttachmentGroupsRequest": { + "ListInstantSnapshotGroupsRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + } + }, + "fields": { + "filter": { + "type": "string", + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "ListInstantSnapshotsRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + } + }, + "fields": { + "filter": { + "type": "string", + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "ListInterconnectAttachmentGroupsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -172763,7 +174489,7 @@ } } }, - "ListNetworkAttachmentsRequest": { + "ListNamedSetsRoutersRequest": { "oneofs": { "_filter": { "oneof": [ @@ -172840,10 +174566,17 @@ "options": { "proto3_optional": true } + }, + "router": { + "type": "string", + "id": 148608841, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } } }, - "ListNetworkEndpointGroupsRequest": { + "ListNetworkAttachmentsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -172907,23 +174640,23 @@ "(google.api.field_behavior)": "REQUIRED" } }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "returnPartialSuccess": { "type": "bool", "id": 517198390, "options": { "proto3_optional": true } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } } } }, - "ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest": { + "ListNetworkEndpointGroupsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -172966,13 +174699,6 @@ "proto3_optional": true } }, - "networkEndpointGroup": { - "type": "string", - "id": 433907078, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "orderBy": { "type": "string", "id": 160562920, @@ -173000,10 +174726,17 @@ "options": { "proto3_optional": true } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } } }, - "ListNetworkEndpointsNetworkEndpointGroupsRequest": { + "ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -173053,13 +174786,6 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "networkEndpointGroupsListEndpointsRequestResource": { - "type": "NetworkEndpointGroupsListEndpointsRequest", - "id": 59493390, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "orderBy": { "type": "string", "id": 160562920, @@ -173087,17 +174813,10 @@ "options": { "proto3_optional": true } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } } } }, - "ListNetworkEndpointsRegionNetworkEndpointGroupsRequest": { + "ListNetworkEndpointsNetworkEndpointGroupsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -173147,6 +174866,13 @@ "(google.api.field_behavior)": "REQUIRED" } }, + "networkEndpointGroupsListEndpointsRequestResource": { + "type": "NetworkEndpointGroupsListEndpointsRequest", + "id": 59493390, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "orderBy": { "type": "string", "id": 160562920, @@ -173168,23 +174894,23 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "region": { - "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "returnPartialSuccess": { "type": "bool", "id": 517198390, "options": { "proto3_optional": true } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } } }, - "ListNetworkFirewallPoliciesRequest": { + "ListNetworkEndpointsRegionNetworkEndpointGroupsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -173227,6 +174953,13 @@ "proto3_optional": true } }, + "networkEndpointGroup": { + "type": "string", + "id": 433907078, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "orderBy": { "type": "string", "id": 160562920, @@ -173248,6 +174981,13 @@ "(google.api.field_behavior)": "REQUIRED" } }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "returnPartialSuccess": { "type": "bool", "id": 517198390, @@ -173257,7 +174997,80 @@ } } }, - "ListNetworkProfilesRequest": { + "ListNetworkFirewallPoliciesRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + } + }, + "fields": { + "filter": { + "type": "string", + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + } + } + }, + "ListNetworkProfilesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -175880,87 +177693,7 @@ } } }, - "ListRegionInstantSnapshotsRequest": { - "oneofs": { - "_filter": { - "oneof": [ - "filter" - ] - }, - "_maxResults": { - "oneof": [ - "maxResults" - ] - }, - "_orderBy": { - "oneof": [ - "orderBy" - ] - }, - "_pageToken": { - "oneof": [ - "pageToken" - ] - }, - "_returnPartialSuccess": { - "oneof": [ - "returnPartialSuccess" - ] - } - }, - "fields": { - "filter": { - "type": "string", - "id": 336120696, - "options": { - "proto3_optional": true - } - }, - "maxResults": { - "type": "uint32", - "id": 54715419, - "options": { - "proto3_optional": true - } - }, - "orderBy": { - "type": "string", - "id": 160562920, - "options": { - "proto3_optional": true - } - }, - "pageToken": { - "type": "string", - "id": 19994697, - "options": { - "proto3_optional": true - } - }, - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "region": { - "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "returnPartialSuccess": { - "type": "bool", - "id": 517198390, - "options": { - "proto3_optional": true - } - } - } - }, - "ListRegionMultiMigMembersRequest": { + "ListRegionInstantSnapshotGroupsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176003,13 +177736,6 @@ "proto3_optional": true } }, - "multiMig": { - "type": "string", - "id": 403990085, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "orderBy": { "type": "string", "id": 160562920, @@ -176047,7 +177773,7 @@ } } }, - "ListRegionMultiMigsRequest": { + "ListRegionInstantSnapshotsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176127,7 +177853,7 @@ } } }, - "ListRegionNetworkEndpointGroupsRequest": { + "ListRegionMultiMigMembersRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176170,86 +177896,13 @@ "proto3_optional": true } }, - "orderBy": { - "type": "string", - "id": 160562920, - "options": { - "proto3_optional": true - } - }, - "pageToken": { - "type": "string", - "id": 19994697, - "options": { - "proto3_optional": true - } - }, - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "region": { + "multiMig": { "type": "string", - "id": 138946292, + "id": 403990085, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "returnPartialSuccess": { - "type": "bool", - "id": 517198390, - "options": { - "proto3_optional": true - } - } - } - }, - "ListRegionNetworkFirewallPoliciesRequest": { - "oneofs": { - "_filter": { - "oneof": [ - "filter" - ] - }, - "_maxResults": { - "oneof": [ - "maxResults" - ] - }, - "_orderBy": { - "oneof": [ - "orderBy" - ] - }, - "_pageToken": { - "oneof": [ - "pageToken" - ] - }, - "_returnPartialSuccess": { - "oneof": [ - "returnPartialSuccess" - ] - } - }, - "fields": { - "filter": { - "type": "string", - "id": 336120696, - "options": { - "proto3_optional": true - } - }, - "maxResults": { - "type": "uint32", - "id": 54715419, - "options": { - "proto3_optional": true - } - }, "orderBy": { "type": "string", "id": 160562920, @@ -176287,7 +177940,7 @@ } } }, - "ListRegionNetworkPoliciesRequest": { + "ListRegionMultiMigsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176367,7 +178020,7 @@ } } }, - "ListRegionNotificationEndpointsRequest": { + "ListRegionNetworkEndpointGroupsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176447,7 +178100,7 @@ } } }, - "ListRegionOperationsRequest": { + "ListRegionNetworkFirewallPoliciesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176527,7 +178180,7 @@ } } }, - "ListRegionSecurityPoliciesRequest": { + "ListRegionNetworkPoliciesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176607,7 +178260,7 @@ } } }, - "ListRegionSnapshotsRequest": { + "ListRegionNotificationEndpointsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176687,7 +178340,7 @@ } } }, - "ListRegionSslCertificatesRequest": { + "ListRegionOperationsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176767,7 +178420,7 @@ } } }, - "ListRegionSslPoliciesRequest": { + "ListRegionSecurityPoliciesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176847,7 +178500,7 @@ } } }, - "ListRegionTargetHttpProxiesRequest": { + "ListRegionSnapshotsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -176927,7 +178580,7 @@ } } }, - "ListRegionTargetHttpsProxiesRequest": { + "ListRegionSslCertificatesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177007,7 +178660,7 @@ } } }, - "ListRegionTargetTcpProxiesRequest": { + "ListRegionSslPoliciesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177087,7 +178740,7 @@ } } }, - "ListRegionUrlMapsRequest": { + "ListRegionTargetHttpProxiesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177167,7 +178820,7 @@ } } }, - "ListRegionZonesRequest": { + "ListRegionTargetHttpsProxiesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177247,7 +178900,7 @@ } } }, - "ListRegionsRequest": { + "ListRegionTargetTcpProxiesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177311,6 +178964,13 @@ "(google.api.field_behavior)": "REQUIRED" } }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "returnPartialSuccess": { "type": "bool", "id": 517198390, @@ -177320,7 +178980,7 @@ } } }, - "ListReservationBlocksRequest": { + "ListRegionUrlMapsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177384,9 +179044,9 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "reservation": { + "region": { "type": "string", - "id": 47530956, + "id": 138946292, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -177397,17 +179057,10 @@ "options": { "proto3_optional": true } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } } } }, - "ListReservationSubBlocksRequest": { + "ListRegionZonesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177464,16 +179117,16 @@ "proto3_optional": true } }, - "parentName": { + "project": { "type": "string", - "id": 478151936, + "id": 227560217, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "project": { + "region": { "type": "string", - "id": 227560217, + "id": 138946292, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -177484,17 +179137,10 @@ "options": { "proto3_optional": true } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } } } }, - "ListReservationsRequest": { + "ListRegionsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177564,17 +179210,10 @@ "options": { "proto3_optional": true } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } } } }, - "ListResourcePoliciesRequest": { + "ListReservationBlocksRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177638,9 +179277,9 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "region": { + "reservation": { "type": "string", - "id": 138946292, + "id": 47530956, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -177651,10 +179290,17 @@ "options": { "proto3_optional": true } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } } }, - "ListRolloutPlansRequest": { + "ListReservationSlotsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177711,6 +179357,13 @@ "proto3_optional": true } }, + "parentName": { + "type": "string", + "id": 478151936, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "project": { "type": "string", "id": 227560217, @@ -177724,10 +179377,17 @@ "options": { "proto3_optional": true } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } } }, - "ListRolloutsRequest": { + "ListReservationSubBlocksRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177784,6 +179444,13 @@ "proto3_optional": true } }, + "parentName": { + "type": "string", + "id": 478151936, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "project": { "type": "string", "id": 227560217, @@ -177797,10 +179464,17 @@ "options": { "proto3_optional": true } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } } }, - "ListRoutePoliciesRoutersRequest": { + "ListReservationsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177864,13 +179538,6 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "region": { - "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "returnPartialSuccess": { "type": "bool", "id": 517198390, @@ -177878,16 +179545,16 @@ "proto3_optional": true } }, - "router": { + "zone": { "type": "string", - "id": 148608841, + "id": 3744684, "options": { "(google.api.field_behavior)": "REQUIRED" } } } }, - "ListRoutersRequest": { + "ListResourcePoliciesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -177967,7 +179634,7 @@ } } }, - "ListRoutesRequest": { + "ListRolloutPlansRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178040,7 +179707,7 @@ } } }, - "ListSecurityPoliciesRequest": { + "ListRolloutsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178113,7 +179780,7 @@ } } }, - "ListServiceAttachmentsRequest": { + "ListRoutePoliciesRoutersRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178190,10 +179857,17 @@ "options": { "proto3_optional": true } + }, + "router": { + "type": "string", + "id": 148608841, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } } }, - "ListSnapshotsRequest": { + "ListRoutersRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178257,6 +179931,13 @@ "(google.api.field_behavior)": "REQUIRED" } }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "returnPartialSuccess": { "type": "bool", "id": 517198390, @@ -178266,7 +179947,7 @@ } } }, - "ListSslCertificatesRequest": { + "ListRoutesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178339,7 +180020,7 @@ } } }, - "ListSslPoliciesRequest": { + "ListSecurityPoliciesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178412,7 +180093,7 @@ } } }, - "ListStoragePoolTypesRequest": { + "ListServiceAttachmentsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178476,103 +180157,111 @@ "(google.api.field_behavior)": "REQUIRED" } }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "returnPartialSuccess": { "type": "bool", "id": 517198390, "options": { "proto3_optional": true } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } } } }, - "ListStoragePoolsRequest": { + "ListSnapshotGroups": { "oneofs": { - "_filter": { + "_etag": { "oneof": [ - "filter" + "etag" ] }, - "_maxResults": { + "_id": { "oneof": [ - "maxResults" + "id" ] }, - "_orderBy": { + "_kind": { "oneof": [ - "orderBy" + "kind" ] }, - "_pageToken": { + "_nextPageToken": { "oneof": [ - "pageToken" + "nextPageToken" ] }, - "_returnPartialSuccess": { + "_selfLink": { "oneof": [ - "returnPartialSuccess" + "selfLink" + ] + }, + "_warning": { + "oneof": [ + "warning" ] } }, "fields": { - "filter": { + "etag": { "type": "string", - "id": 336120696, + "id": 3123477, "options": { "proto3_optional": true } }, - "maxResults": { - "type": "uint32", - "id": 54715419, + "id": { + "type": "string", + "id": 3355, "options": { "proto3_optional": true } }, - "orderBy": { + "items": { + "rule": "repeated", + "type": "SnapshotGroup", + "id": 100526016 + }, + "kind": { "type": "string", - "id": 160562920, + "id": 3292052, "options": { "proto3_optional": true } }, - "pageToken": { + "nextPageToken": { "type": "string", - "id": 19994697, + "id": 79797525, "options": { "proto3_optional": true } }, - "project": { + "selfLink": { "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "returnPartialSuccess": { - "type": "bool", - "id": 517198390, + "id": 456214797, "options": { "proto3_optional": true } }, - "zone": { + "unreachables": { + "rule": "repeated", "type": "string", - "id": 3744684, + "id": 243372063 + }, + "warning": { + "type": "Warning", + "id": 50704284, "options": { - "(google.api.field_behavior)": "REQUIRED" + "proto3_optional": true } } } }, - "ListSubnetworksRequest": { + "ListSnapshotGroupsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178598,11 +180287,6 @@ "oneof": [ "returnPartialSuccess" ] - }, - "_views": { - "oneof": [ - "views" - ] } }, "fields": { @@ -178641,39 +180325,16 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "region": { - "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "returnPartialSuccess": { "type": "bool", "id": 517198390, "options": { "proto3_optional": true } - }, - "views": { - "type": "string", - "id": 112204398, - "options": { - "proto3_optional": true - } - } - }, - "nested": { - "Views": { - "values": { - "UNDEFINED_VIEWS": 0, - "DEFAULT": 115302945, - "WITH_UTILIZATION": 504090633 - } } } }, - "ListTargetGrpcProxiesRequest": { + "ListSnapshotsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178746,7 +180407,7 @@ } } }, - "ListTargetHttpProxiesRequest": { + "ListSslCertificatesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178819,7 +180480,7 @@ } } }, - "ListTargetHttpsProxiesRequest": { + "ListSslPoliciesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178892,7 +180553,7 @@ } } }, - "ListTargetInstancesRequest": { + "ListStoragePoolTypesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178972,7 +180633,87 @@ } } }, - "ListTargetPoolsRequest": { + "ListStoragePoolsRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + } + }, + "fields": { + "filter": { + "type": "string", + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "ListSubnetworksRequest": { "oneofs": { "_filter": { "oneof": [ @@ -178998,6 +180739,11 @@ "oneof": [ "returnPartialSuccess" ] + }, + "_views": { + "oneof": [ + "views" + ] } }, "fields": { @@ -179049,10 +180795,26 @@ "options": { "proto3_optional": true } + }, + "views": { + "type": "string", + "id": 112204398, + "options": { + "proto3_optional": true + } + } + }, + "nested": { + "Views": { + "values": { + "UNDEFINED_VIEWS": 0, + "DEFAULT": 115302945, + "WITH_UTILIZATION": 504090633 + } } } }, - "ListTargetSslProxiesRequest": { + "ListTargetGrpcProxiesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179125,7 +180887,7 @@ } } }, - "ListTargetTcpProxiesRequest": { + "ListTargetHttpProxiesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179198,7 +180960,7 @@ } } }, - "ListTargetVpnGatewaysRequest": { + "ListTargetHttpsProxiesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179262,13 +181024,6 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "region": { - "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "returnPartialSuccess": { "type": "bool", "id": 517198390, @@ -179278,7 +181033,7 @@ } } }, - "ListUrlMapsRequest": { + "ListTargetInstancesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179348,10 +181103,17 @@ "options": { "proto3_optional": true } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } } }, - "ListUsableBackendBucketsRequest": { + "ListTargetPoolsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179415,6 +181177,13 @@ "(google.api.field_behavior)": "REQUIRED" } }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "returnPartialSuccess": { "type": "bool", "id": 517198390, @@ -179424,7 +181193,7 @@ } } }, - "ListUsableBackendServicesRequest": { + "ListTargetSslProxiesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179497,7 +181266,7 @@ } } }, - "ListUsableRegionBackendBucketsRequest": { + "ListTargetTcpProxiesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179561,13 +181330,6 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "region": { - "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "returnPartialSuccess": { "type": "bool", "id": 517198390, @@ -179577,7 +181339,7 @@ } } }, - "ListUsableRegionBackendServicesRequest": { + "ListTargetVpnGatewaysRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179657,7 +181419,7 @@ } } }, - "ListUsableSubnetworksRequest": { + "ListUrlMapsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179683,11 +181445,6 @@ "oneof": [ "returnPartialSuccess" ] - }, - "_serviceProject": { - "oneof": [ - "serviceProject" - ] } }, "fields": { @@ -179732,17 +181489,10 @@ "options": { "proto3_optional": true } - }, - "serviceProject": { - "type": "string", - "id": 530592655, - "options": { - "proto3_optional": true - } } } }, - "ListVpnGatewaysRequest": { + "ListUsableBackendBucketsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179806,9 +181556,75 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "region": { + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + } + } + }, + "ListUsableBackendServicesRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + } + }, + "fields": { + "filter": { "type": "string", - "id": 138946292, + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -179822,7 +181638,7 @@ } } }, - "ListVpnTunnelsRequest": { + "ListUsableRegionBackendBucketsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179902,7 +181718,7 @@ } } }, - "ListWireGroupsRequest": { + "ListUsableRegionBackendServicesRequest": { "oneofs": { "_filter": { "oneof": [ @@ -179931,13 +181747,6 @@ } }, "fields": { - "crossSiteNetwork": { - "type": "string", - "id": 108192469, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "filter": { "type": "string", "id": 336120696, @@ -179973,6 +181782,13 @@ "(google.api.field_behavior)": "REQUIRED" } }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "returnPartialSuccess": { "type": "bool", "id": 517198390, @@ -179982,7 +181798,332 @@ } } }, - "ListXpnHostsProjectsRequest": { + "ListUsableSubnetworksRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + }, + "_serviceProject": { + "oneof": [ + "serviceProject" + ] + } + }, + "fields": { + "filter": { + "type": "string", + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + }, + "serviceProject": { + "type": "string", + "id": 530592655, + "options": { + "proto3_optional": true + } + } + } + }, + "ListVpnGatewaysRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + } + }, + "fields": { + "filter": { + "type": "string", + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + } + } + }, + "ListVpnTunnelsRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + } + }, + "fields": { + "filter": { + "type": "string", + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + } + } + }, + "ListWireGroupsRequest": { + "oneofs": { + "_filter": { + "oneof": [ + "filter" + ] + }, + "_maxResults": { + "oneof": [ + "maxResults" + ] + }, + "_orderBy": { + "oneof": [ + "orderBy" + ] + }, + "_pageToken": { + "oneof": [ + "pageToken" + ] + }, + "_returnPartialSuccess": { + "oneof": [ + "returnPartialSuccess" + ] + } + }, + "fields": { + "crossSiteNetwork": { + "type": "string", + "id": 108192469, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "filter": { + "type": "string", + "id": 336120696, + "options": { + "proto3_optional": true + } + }, + "maxResults": { + "type": "uint32", + "id": 54715419, + "options": { + "proto3_optional": true + } + }, + "orderBy": { + "type": "string", + "id": 160562920, + "options": { + "proto3_optional": true + } + }, + "pageToken": { + "type": "string", + "id": 19994697, + "options": { + "proto3_optional": true + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "returnPartialSuccess": { + "type": "bool", + "id": 517198390, + "options": { + "proto3_optional": true + } + } + } + }, + "ListXpnHostsProjectsRequest": { "oneofs": { "_filter": { "oneof": [ @@ -180387,6 +182528,11 @@ "options": { "proto3_optional": true } + }, + "zones": { + "rule": "repeated", + "type": "LocationPolicyZoneConfiguration", + "id": 116085319 } }, "nested": { @@ -180458,6 +182604,24 @@ } } }, + "LocationPolicyZoneConfiguration": { + "oneofs": { + "_zone": { + "oneof": [ + "zone" + ] + } + }, + "fields": { + "zone": { + "type": "string", + "id": 3744684, + "options": { + "proto3_optional": true + } + } + } + }, "MachineImage": { "oneofs": { "_creationTimestamp": { @@ -180505,6 +182669,11 @@ "name" ] }, + "_params": { + "oneof": [ + "params" + ] + }, "_satisfiesPzi": { "oneof": [ "satisfiesPzi" @@ -180610,6 +182779,13 @@ "proto3_optional": true } }, + "params": { + "type": "MachineImageParams", + "id": 78313862, + "options": { + "proto3_optional": true + } + }, "satisfiesPzi": { "type": "bool", "id": 480964257, @@ -180759,6 +182935,15 @@ } } }, + "MachineImageParams": { + "fields": { + "resourceManagerTags": { + "keyType": "string", + "type": "string", + "id": 377671164 + } + } + }, "MachineType": { "oneofs": { "_architecture": { @@ -182405,6 +184590,74 @@ } } }, + "NamedSet": { + "oneofs": { + "_description": { + "oneof": [ + "description" + ] + }, + "_fingerprint": { + "oneof": [ + "fingerprint" + ] + }, + "_name": { + "oneof": [ + "name" + ] + }, + "_type": { + "oneof": [ + "type" + ] + } + }, + "fields": { + "description": { + "type": "string", + "id": 422937596, + "options": { + "proto3_optional": true + } + }, + "elements": { + "rule": "repeated", + "type": "Expr", + "id": 528531703 + }, + "fingerprint": { + "type": "string", + "id": 234678500, + "options": { + "proto3_optional": true + } + }, + "name": { + "type": "string", + "id": 3373707, + "options": { + "proto3_optional": true + } + }, + "type": { + "type": "string", + "id": 3575610, + "options": { + "proto3_optional": true + } + } + }, + "nested": { + "Type": { + "values": { + "UNDEFINED_TYPE": 0, + "NAMED_SET_TYPE_COMMUNITY": 263444871, + "NAMED_SET_TYPE_PREFIX": 228038036 + } + } + } + }, "NatIpInfo": { "oneofs": { "_natName": { @@ -184438,6 +186691,11 @@ }, "NetworkInterface": { "oneofs": { + "_enableVpcScopedDns": { + "oneof": [ + "enableVpcScopedDns" + ] + }, "_fingerprint": { "oneof": [ "fingerprint" @@ -184535,6 +186793,13 @@ "type": "AliasIpRange", "id": 165085631 }, + "enableVpcScopedDns": { + "type": "bool", + "id": 283425868, + "options": { + "proto3_optional": true + } + }, "fingerprint": { "type": "string", "id": 234678500, @@ -186550,7 +188815,9 @@ "FirewallPolicyTypes": { "values": { "UNDEFINED_FIREWALL_POLICY_TYPES": 0, + "RDMA_FALCON_POLICY": 66315047, "RDMA_ROCE_POLICY": 148757145, + "ULL_POLICY": 100494364, "VPC_POLICY": 74319208 } }, @@ -191130,7 +193397,7 @@ } } }, - "PatchNetworkAttachmentRequest": { + "PatchNamedSetRouterRequest": { "oneofs": { "_requestId": { "oneof": [ @@ -191139,16 +193406,9 @@ } }, "fields": { - "networkAttachment": { - "type": "string", - "id": 224644052, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "networkAttachmentResource": { - "type": "NetworkAttachment", - "id": 210974745, + "namedSetResource": { + "type": "NamedSet", + "id": 408608401, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -191175,82 +193435,17 @@ "options": { "proto3_optional": true } - } - } - }, - "PatchNetworkEdgeSecurityServiceRequest": { - "oneofs": { - "_paths": { - "oneof": [ - "paths" - ] - }, - "_requestId": { - "oneof": [ - "requestId" - ] }, - "_updateMask": { - "oneof": [ - "updateMask" - ] - } - }, - "fields": { - "networkEdgeSecurityService": { + "router": { "type": "string", - "id": 157011879, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "networkEdgeSecurityServiceResource": { - "type": "NetworkEdgeSecurityService", - "id": 477548966, + "id": 148608841, "options": { "(google.api.field_behavior)": "REQUIRED" } - }, - "paths": { - "type": "string", - "id": 106438894, - "options": { - "proto3_optional": true - } - }, - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED", - "(google.cloud.operation_request_field)": "project" - } - }, - "region": { - "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED", - "(google.cloud.operation_request_field)": "region" - } - }, - "requestId": { - "type": "string", - "id": 37109963, - "options": { - "proto3_optional": true - } - }, - "updateMask": { - "type": "string", - "id": 500079778, - "options": { - "proto3_optional": true - } } } }, - "PatchNetworkFirewallPolicyRequest": { + "PatchNetworkAttachmentRequest": { "oneofs": { "_requestId": { "oneof": [ @@ -191259,16 +193454,16 @@ } }, "fields": { - "firewallPolicy": { + "networkAttachment": { "type": "string", - "id": 498173265, + "id": 224644052, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "firewallPolicyResource": { - "type": "FirewallPolicy", - "id": 495049532, + "networkAttachmentResource": { + "type": "NetworkAttachment", + "id": 210974745, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -191281,44 +193476,12 @@ "(google.cloud.operation_request_field)": "project" } }, - "requestId": { - "type": "string", - "id": 37109963, - "options": { - "proto3_optional": true - } - } - } - }, - "PatchNetworkRequest": { - "oneofs": { - "_requestId": { - "oneof": [ - "requestId" - ] - } - }, - "fields": { - "network": { - "type": "string", - "id": 232872494, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "networkResource": { - "type": "Network", - "id": 122105599, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "project": { + "region": { "type": "string", - "id": 227560217, + "id": 138946292, "options": { "(google.api.field_behavior)": "REQUIRED", - "(google.cloud.operation_request_field)": "project" + "(google.cloud.operation_request_field)": "region" } }, "requestId": { @@ -191330,56 +193493,13 @@ } } }, - "PatchNodeGroupRequest": { + "PatchNetworkEdgeSecurityServiceRequest": { "oneofs": { - "_requestId": { + "_paths": { "oneof": [ - "requestId" + "paths" ] - } - }, - "fields": { - "nodeGroup": { - "type": "string", - "id": 469958146, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "nodeGroupResource": { - "type": "NodeGroup", - "id": 505321899, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } }, - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED", - "(google.cloud.operation_request_field)": "project" - } - }, - "requestId": { - "type": "string", - "id": 37109963, - "options": { - "proto3_optional": true - } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED", - "(google.cloud.operation_request_field)": "zone" - } - } - } - }, - "PatchOrganizationSecurityPolicyRequest": { - "oneofs": { "_requestId": { "oneof": [ "requestId" @@ -191392,58 +193512,253 @@ } }, "fields": { - "requestId": { - "type": "string", - "id": 37109963, - "options": { - "proto3_optional": true - } - }, - "securityPolicy": { + "networkEdgeSecurityService": { "type": "string", - "id": 171082513, + "id": 157011879, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "securityPolicyResource": { - "type": "SecurityPolicy", - "id": 216159612, + "networkEdgeSecurityServiceResource": { + "type": "NetworkEdgeSecurityService", + "id": 477548966, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "updateMask": { + "paths": { "type": "string", - "id": 500079778, + "id": 106438894, "options": { "proto3_optional": true } - } - } - }, - "PatchPacketMirroringRequest": { - "oneofs": { - "_requestId": { - "oneof": [ - "requestId" - ] - } - }, - "fields": { - "packetMirroring": { - "type": "string", - "id": 22305996, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "packetMirroringResource": { - "type": "PacketMirroring", - "id": 493501985, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "region" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "updateMask": { + "type": "string", + "id": 500079778, + "options": { + "proto3_optional": true + } + } + } + }, + "PatchNetworkFirewallPolicyRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "firewallPolicy": { + "type": "string", + "id": 498173265, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "firewallPolicyResource": { + "type": "FirewallPolicy", + "id": 495049532, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + } + } + }, + "PatchNetworkRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "network": { + "type": "string", + "id": 232872494, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "networkResource": { + "type": "Network", + "id": 122105599, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + } + } + }, + "PatchNodeGroupRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "nodeGroup": { + "type": "string", + "id": 469958146, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "nodeGroupResource": { + "type": "NodeGroup", + "id": 505321899, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "zone" + } + } + } + }, + "PatchOrganizationSecurityPolicyRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + }, + "_updateMask": { + "oneof": [ + "updateMask" + ] + } + }, + "fields": { + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "securityPolicy": { + "type": "string", + "id": 171082513, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "securityPolicyResource": { + "type": "SecurityPolicy", + "id": 216159612, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "string", + "id": 500079778, + "options": { + "proto3_optional": true + } + } + } + }, + "PatchPacketMirroringRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "packetMirroring": { + "type": "string", + "id": 22305996, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "packetMirroringResource": { + "type": "PacketMirroring", + "id": 493501985, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, "project": { "type": "string", @@ -199188,6 +201503,11 @@ "description" ] }, + "_earlyAccessMaintenance": { + "oneof": [ + "earlyAccessMaintenance" + ] + }, "_enableEmergentMaintenance": { "oneof": [ "enableEmergentMaintenance" @@ -199208,6 +201528,11 @@ "name" ] }, + "_params": { + "oneof": [ + "params" + ] + }, "_protectionTier": { "oneof": [ "protectionTier" @@ -199326,6 +201651,13 @@ "proto3_optional": true } }, + "earlyAccessMaintenance": { + "type": "string", + "id": 343918356, + "options": { + "proto3_optional": true + } + }, "enableEmergentMaintenance": { "type": "bool", "id": 353759497, @@ -199359,6 +201691,13 @@ "proto3_optional": true } }, + "params": { + "type": "ReservationParams", + "id": 78313862, + "options": { + "proto3_optional": true + } + }, "protectionTier": { "type": "string", "id": 503959432, @@ -199458,6 +201797,14 @@ "FLEXIBLE": 379880395 } }, + "EarlyAccessMaintenance": { + "values": { + "UNDEFINED_EARLY_ACCESS_MAINTENANCE": 0, + "NO_EARLY_ACCESS": 220751774, + "WAVE1": 82367576, + "WAVE2": 82367577 + } + }, "ProtectionTier": { "values": { "UNDEFINED_PROTECTION_TIER": 0, @@ -200103,7 +202450,337 @@ } } }, - "ReservationList": { + "ReservationList": { + "oneofs": { + "_id": { + "oneof": [ + "id" + ] + }, + "_kind": { + "oneof": [ + "kind" + ] + }, + "_nextPageToken": { + "oneof": [ + "nextPageToken" + ] + }, + "_selfLink": { + "oneof": [ + "selfLink" + ] + }, + "_warning": { + "oneof": [ + "warning" + ] + } + }, + "fields": { + "id": { + "type": "string", + "id": 3355, + "options": { + "proto3_optional": true + } + }, + "items": { + "rule": "repeated", + "type": "Reservation", + "id": 100526016 + }, + "kind": { + "type": "string", + "id": 3292052, + "options": { + "proto3_optional": true + } + }, + "nextPageToken": { + "type": "string", + "id": 79797525, + "options": { + "proto3_optional": true + } + }, + "selfLink": { + "type": "string", + "id": 456214797, + "options": { + "proto3_optional": true + } + }, + "warning": { + "type": "Warning", + "id": 50704284, + "options": { + "proto3_optional": true + } + } + } + }, + "ReservationParams": { + "fields": { + "resourceManagerTags": { + "keyType": "string", + "type": "string", + "id": 377671164 + } + } + }, + "ReservationSlot": { + "oneofs": { + "_creationTimestamp": { + "oneof": [ + "creationTimestamp" + ] + }, + "_id": { + "oneof": [ + "id" + ] + }, + "_kind": { + "oneof": [ + "kind" + ] + }, + "_name": { + "oneof": [ + "name" + ] + }, + "_physicalTopology": { + "oneof": [ + "physicalTopology" + ] + }, + "_selfLink": { + "oneof": [ + "selfLink" + ] + }, + "_selfLinkWithId": { + "oneof": [ + "selfLinkWithId" + ] + }, + "_shareSettings": { + "oneof": [ + "shareSettings" + ] + }, + "_state": { + "oneof": [ + "state" + ] + }, + "_status": { + "oneof": [ + "status" + ] + }, + "_zone": { + "oneof": [ + "zone" + ] + } + }, + "fields": { + "creationTimestamp": { + "type": "string", + "id": 30525366, + "options": { + "proto3_optional": true + } + }, + "id": { + "type": "uint64", + "id": 3355, + "options": { + "proto3_optional": true + } + }, + "kind": { + "type": "string", + "id": 3292052, + "options": { + "proto3_optional": true + } + }, + "name": { + "type": "string", + "id": 3373707, + "options": { + "proto3_optional": true + } + }, + "physicalTopology": { + "type": "ReservationSlotPhysicalTopology", + "id": 279778519, + "options": { + "proto3_optional": true + } + }, + "selfLink": { + "type": "string", + "id": 456214797, + "options": { + "proto3_optional": true + } + }, + "selfLinkWithId": { + "type": "string", + "id": 44520962, + "options": { + "proto3_optional": true + } + }, + "shareSettings": { + "type": "ShareSettings", + "id": 266668163, + "options": { + "proto3_optional": true + } + }, + "state": { + "type": "string", + "id": 109757585, + "options": { + "proto3_optional": true + } + }, + "status": { + "type": "ReservationSlotStatus", + "id": 181260274, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "proto3_optional": true + } + } + }, + "nested": { + "State": { + "values": { + "UNDEFINED_STATE": 0, + "ACTIVE": 314733318, + "CREATING": 455564985, + "DELETING": 528602024, + "STATE_UNSPECIFIED": 470755401, + "UNAVAILABLE": 413756464 + } + } + } + }, + "ReservationSlotPhysicalTopology": { + "oneofs": { + "_block": { + "oneof": [ + "block" + ] + }, + "_cluster": { + "oneof": [ + "cluster" + ] + }, + "_host": { + "oneof": [ + "host" + ] + }, + "_subBlock": { + "oneof": [ + "subBlock" + ] + } + }, + "fields": { + "block": { + "type": "string", + "id": 93832333, + "options": { + "proto3_optional": true + } + }, + "cluster": { + "type": "string", + "id": 335221242, + "options": { + "proto3_optional": true + } + }, + "host": { + "type": "string", + "id": 3208616, + "options": { + "proto3_optional": true + } + }, + "subBlock": { + "type": "string", + "id": 478033358, + "options": { + "proto3_optional": true + } + } + } + }, + "ReservationSlotStatus": { + "oneofs": { + "_physicalTopology": { + "oneof": [ + "physicalTopology" + ] + } + }, + "fields": { + "physicalTopology": { + "type": "ReservationSlotPhysicalTopology", + "id": 279778519, + "options": { + "proto3_optional": true + } + }, + "rdmaIpAddresses": { + "rule": "repeated", + "type": "string", + "id": 167842531 + }, + "runningInstances": { + "rule": "repeated", + "type": "string", + "id": 536292350 + } + } + }, + "ReservationSlotsGetResponse": { + "oneofs": { + "_resource": { + "oneof": [ + "resource" + ] + } + }, + "fields": { + "resource": { + "type": "ReservationSlot", + "id": 195806222, + "options": { + "proto3_optional": true + } + } + } + }, + "ReservationSlotsListResponse": { "oneofs": { "_id": { "oneof": [ @@ -200141,7 +202818,7 @@ }, "items": { "rule": "repeated", - "type": "Reservation", + "type": "ReservationSlot", "id": 100526016 }, "kind": { @@ -202374,6 +205051,11 @@ "enableOsloginMetadataValue" ] }, + "_gceContainerDeclarationMetadataValue": { + "oneof": [ + "gceContainerDeclarationMetadataValue" + ] + }, "_serialPortEnableMetadataValue": { "oneof": [ "serialPortEnableMetadataValue" @@ -202426,6 +205108,13 @@ "proto3_optional": true } }, + "gceContainerDeclarationMetadataValue": { + "type": "bool", + "id": 219617210, + "options": { + "proto3_optional": true + } + }, "serialPortEnableMetadataValue": { "type": "bool", "id": 430536330, @@ -206101,6 +208790,36 @@ } } }, + "RoutersGetNamedSetResponse": { + "oneofs": { + "_etag": { + "oneof": [ + "etag" + ] + }, + "_resource": { + "oneof": [ + "resource" + ] + } + }, + "fields": { + "etag": { + "type": "string", + "id": 3123477, + "options": { + "proto3_optional": true + } + }, + "resource": { + "type": "NamedSet", + "id": 195806222, + "options": { + "proto3_optional": true + } + } + } + }, "RoutersGetRoutePolicyResponse": { "oneofs": { "_resource": { @@ -206207,6 +208926,94 @@ } } }, + "RoutersListNamedSets": { + "oneofs": { + "_etag": { + "oneof": [ + "etag" + ] + }, + "_id": { + "oneof": [ + "id" + ] + }, + "_kind": { + "oneof": [ + "kind" + ] + }, + "_nextPageToken": { + "oneof": [ + "nextPageToken" + ] + }, + "_selfLink": { + "oneof": [ + "selfLink" + ] + }, + "_warning": { + "oneof": [ + "warning" + ] + } + }, + "fields": { + "etag": { + "type": "string", + "id": 3123477, + "options": { + "proto3_optional": true + } + }, + "id": { + "type": "string", + "id": 3355, + "options": { + "proto3_optional": true + } + }, + "kind": { + "type": "string", + "id": 3292052, + "options": { + "proto3_optional": true + } + }, + "nextPageToken": { + "type": "string", + "id": 79797525, + "options": { + "proto3_optional": true + } + }, + "result": { + "rule": "repeated", + "type": "NamedSet", + "id": 139315229 + }, + "selfLink": { + "type": "string", + "id": 456214797, + "options": { + "proto3_optional": true + } + }, + "unreachables": { + "rule": "repeated", + "type": "string", + "id": 243372063 + }, + "warning": { + "type": "Warning", + "id": 50704284, + "options": { + "proto3_optional": true + } + } + } + }, "RoutersListRoutePolicies": { "oneofs": { "_etag": { @@ -206853,6 +209660,11 @@ "preemptible" ] }, + "_preemptionNoticeDuration": { + "oneof": [ + "preemptionNoticeDuration" + ] + }, "_provisioningModel": { "oneof": [ "provisioningModel" @@ -206973,6 +209785,13 @@ "proto3_optional": true } }, + "preemptionNoticeDuration": { + "type": "Duration", + "id": 486176437, + "options": { + "proto3_optional": true + } + }, "provisioningModel": { "type": "string", "id": 494423, @@ -210528,7 +213347,253 @@ } } }, - "SetIamPolicyBackendServiceRequest": { + "SetIamPolicyBackendServiceRequest": { + "fields": { + "globalSetPolicyRequestResource": { + "type": "GlobalSetPolicyRequest", + "id": 337048498, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyDiskRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zoneSetPolicyRequestResource": { + "type": "ZoneSetPolicyRequest", + "id": 382082107, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyFirewallPolicyRequest": { + "fields": { + "globalOrganizationSetPolicyRequestResource": { + "type": "GlobalOrganizationSetPolicyRequest", + "id": 177408606, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyImageRequest": { + "fields": { + "globalSetPolicyRequestResource": { + "type": "GlobalSetPolicyRequest", + "id": 337048498, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyInstanceRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zoneSetPolicyRequestResource": { + "type": "ZoneSetPolicyRequest", + "id": 382082107, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyInstanceTemplateRequest": { + "fields": { + "globalSetPolicyRequestResource": { + "type": "GlobalSetPolicyRequest", + "id": 337048498, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyInstantSnapshotGroupRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zoneSetPolicyRequestResource": { + "type": "ZoneSetPolicyRequest", + "id": 382082107, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyInstantSnapshotRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zoneSetPolicyRequestResource": { + "type": "ZoneSetPolicyRequest", + "id": 382082107, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyInterconnectAttachmentGroupRequest": { + "fields": { + "globalSetPolicyRequestResource": { + "type": "GlobalSetPolicyRequest", + "id": 337048498, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "SetIamPolicyInterconnectGroupRequest": { "fields": { "globalSetPolicyRequestResource": { "type": "GlobalSetPolicyRequest", @@ -210553,57 +213618,7 @@ } } }, - "SetIamPolicyDiskRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "zoneSetPolicyRequestResource": { - "type": "ZoneSetPolicyRequest", - "id": 382082107, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "SetIamPolicyFirewallPolicyRequest": { - "fields": { - "globalOrganizationSetPolicyRequestResource": { - "type": "GlobalOrganizationSetPolicyRequest", - "id": 177408606, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "SetIamPolicyImageRequest": { + "SetIamPolicyLicenseRequest": { "fields": { "globalSetPolicyRequestResource": { "type": "GlobalSetPolicyRequest", @@ -210628,39 +213643,7 @@ } } }, - "SetIamPolicyInstanceRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "zoneSetPolicyRequestResource": { - "type": "ZoneSetPolicyRequest", - "id": 382082107, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "SetIamPolicyInstanceTemplateRequest": { + "SetIamPolicyMachineImageRequest": { "fields": { "globalSetPolicyRequestResource": { "type": "GlobalSetPolicyRequest", @@ -210685,7 +213668,7 @@ } } }, - "SetIamPolicyInstantSnapshotRequest": { + "SetIamPolicyNetworkAttachmentRequest": { "fields": { "project": { "type": "string", @@ -210694,41 +213677,16 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "zone": { + "region": { "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "zoneSetPolicyRequestResource": { - "type": "ZoneSetPolicyRequest", - "id": 382082107, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "SetIamPolicyInterconnectAttachmentGroupRequest": { - "fields": { - "globalSetPolicyRequestResource": { - "type": "GlobalSetPolicyRequest", - "id": 337048498, + "id": 138946292, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "project": { - "type": "string", - "id": 227560217, + "regionSetPolicyRequestResource": { + "type": "RegionSetPolicyRequest", + "id": 276489091, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -210742,7 +213700,7 @@ } } }, - "SetIamPolicyInterconnectGroupRequest": { + "SetIamPolicyNetworkFirewallPolicyRequest": { "fields": { "globalSetPolicyRequestResource": { "type": "GlobalSetPolicyRequest", @@ -210767,15 +213725,8 @@ } } }, - "SetIamPolicyLicenseRequest": { + "SetIamPolicyNodeGroupRequest": { "fields": { - "globalSetPolicyRequestResource": { - "type": "GlobalSetPolicyRequest", - "id": 337048498, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "project": { "type": "string", "id": 227560217, @@ -210789,35 +213740,24 @@ "options": { "(google.api.field_behavior)": "REQUIRED" } - } - } - }, - "SetIamPolicyMachineImageRequest": { - "fields": { - "globalSetPolicyRequestResource": { - "type": "GlobalSetPolicyRequest", - "id": 337048498, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } }, - "project": { + "zone": { "type": "string", - "id": 227560217, + "id": 3744684, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "resource": { - "type": "string", - "id": 195806222, + "zoneSetPolicyRequestResource": { + "type": "ZoneSetPolicyRequest", + "id": 382082107, "options": { "(google.api.field_behavior)": "REQUIRED" } } } }, - "SetIamPolicyNetworkAttachmentRequest": { + "SetIamPolicyNodeTemplateRequest": { "fields": { "project": { "type": "string", @@ -210849,15 +213789,8 @@ } } }, - "SetIamPolicyNetworkFirewallPolicyRequest": { + "SetIamPolicyRegionBackendBucketRequest": { "fields": { - "globalSetPolicyRequestResource": { - "type": "GlobalSetPolicyRequest", - "id": 337048498, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "project": { "type": "string", "id": 227560217, @@ -210865,20 +213798,16 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "resource": { + "region": { "type": "string", - "id": 195806222, + "id": 138946292, "options": { "(google.api.field_behavior)": "REQUIRED" } - } - } - }, - "SetIamPolicyNodeGroupRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, + }, + "regionSetPolicyRequestResource": { + "type": "RegionSetPolicyRequest", + "id": 276489091, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -210889,24 +213818,10 @@ "options": { "(google.api.field_behavior)": "REQUIRED" } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "zoneSetPolicyRequestResource": { - "type": "ZoneSetPolicyRequest", - "id": 382082107, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } } } }, - "SetIamPolicyNodeTemplateRequest": { + "SetIamPolicyRegionBackendServiceRequest": { "fields": { "project": { "type": "string", @@ -210938,7 +213853,7 @@ } } }, - "SetIamPolicyRegionBackendBucketRequest": { + "SetIamPolicyRegionDiskRequest": { "fields": { "project": { "type": "string", @@ -210970,7 +213885,7 @@ } } }, - "SetIamPolicyRegionBackendServiceRequest": { + "SetIamPolicyRegionInstantSnapshotGroupRequest": { "fields": { "project": { "type": "string", @@ -211002,7 +213917,7 @@ } } }, - "SetIamPolicyRegionDiskRequest": { + "SetIamPolicyRegionInstantSnapshotRequest": { "fields": { "project": { "type": "string", @@ -211034,7 +213949,7 @@ } } }, - "SetIamPolicyRegionInstantSnapshotRequest": { + "SetIamPolicyRegionNetworkFirewallPolicyRequest": { "fields": { "project": { "type": "string", @@ -211066,7 +213981,7 @@ } } }, - "SetIamPolicyRegionNetworkFirewallPolicyRequest": { + "SetIamPolicyRegionSnapshotRequest": { "fields": { "project": { "type": "string", @@ -211098,8 +214013,15 @@ } } }, - "SetIamPolicyRegionSnapshotRequest": { + "SetIamPolicyReservationBlockRequest": { "fields": { + "parentResource": { + "type": "string", + "id": 18091011, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "project": { "type": "string", "id": 227560217, @@ -211107,38 +214029,31 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "region": { + "resource": { "type": "string", - "id": 138946292, + "id": 195806222, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "regionSetPolicyRequestResource": { - "type": "RegionSetPolicyRequest", - "id": 276489091, + "zone": { + "type": "string", + "id": 3744684, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "resource": { - "type": "string", - "id": 195806222, + "zoneSetNestedPolicyRequestResource": { + "type": "ZoneSetNestedPolicyRequest", + "id": 266352851, "options": { "(google.api.field_behavior)": "REQUIRED" } } } }, - "SetIamPolicyReservationBlockRequest": { + "SetIamPolicyReservationRequest": { "fields": { - "parentResource": { - "type": "string", - "id": 18091011, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "project": { "type": "string", "id": 227560217, @@ -211160,17 +214075,24 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "zoneSetNestedPolicyRequestResource": { - "type": "ZoneSetNestedPolicyRequest", - "id": 266352851, + "zoneSetPolicyRequestResource": { + "type": "ZoneSetPolicyRequest", + "id": 382082107, "options": { "(google.api.field_behavior)": "REQUIRED" } } } }, - "SetIamPolicyReservationRequest": { + "SetIamPolicyReservationSubBlockRequest": { "fields": { + "parentResource": { + "type": "string", + "id": 18091011, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, "project": { "type": "string", "id": 227560217, @@ -211192,24 +214114,17 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "zoneSetPolicyRequestResource": { - "type": "ZoneSetPolicyRequest", - "id": 382082107, + "zoneSetNestedPolicyRequestResource": { + "type": "ZoneSetNestedPolicyRequest", + "id": 266352851, "options": { "(google.api.field_behavior)": "REQUIRED" } } } }, - "SetIamPolicyReservationSubBlockRequest": { + "SetIamPolicyResourcePolicyRequest": { "fields": { - "parentResource": { - "type": "string", - "id": 18091011, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, "project": { "type": "string", "id": 227560217, @@ -211217,30 +214132,30 @@ "(google.api.field_behavior)": "REQUIRED" } }, - "resource": { + "region": { "type": "string", - "id": 195806222, + "id": 138946292, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "zone": { - "type": "string", - "id": 3744684, + "regionSetPolicyRequestResource": { + "type": "RegionSetPolicyRequest", + "id": 276489091, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "zoneSetNestedPolicyRequestResource": { - "type": "ZoneSetNestedPolicyRequest", - "id": 266352851, + "resource": { + "type": "string", + "id": 195806222, "options": { "(google.api.field_behavior)": "REQUIRED" } } } }, - "SetIamPolicyResourcePolicyRequest": { + "SetIamPolicyServiceAttachmentRequest": { "fields": { "project": { "type": "string", @@ -211272,25 +214187,18 @@ } } }, - "SetIamPolicyServiceAttachmentRequest": { + "SetIamPolicySnapshotGroupRequest": { "fields": { - "project": { - "type": "string", - "id": 227560217, + "globalSetPolicyRequestResource": { + "type": "GlobalSetPolicyRequest", + "id": 337048498, "options": { "(google.api.field_behavior)": "REQUIRED" } }, - "region": { + "project": { "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "regionSetPolicyRequestResource": { - "type": "RegionSetPolicyRequest", - "id": 276489091, + "id": 227560217, "options": { "(google.api.field_behavior)": "REQUIRED" } @@ -214562,6 +217470,16 @@ "snapshotEncryptionKey" ] }, + "_snapshotGroupId": { + "oneof": [ + "snapshotGroupId" + ] + }, + "_snapshotGroupName": { + "oneof": [ + "snapshotGroupName" + ] + }, "_snapshotType": { "oneof": [ "snapshotType" @@ -214796,6 +217714,20 @@ "proto3_optional": true } }, + "snapshotGroupId": { + "type": "string", + "id": 255004406, + "options": { + "proto3_optional": true + } + }, + "snapshotGroupName": { + "type": "string", + "id": 246247846, + "options": { + "proto3_optional": true + } + }, "snapshotType": { "type": "string", "id": 124349653, @@ -215021,6 +217953,253 @@ } } }, + "SnapshotGroup": { + "oneofs": { + "_creationTimestamp": { + "oneof": [ + "creationTimestamp" + ] + }, + "_description": { + "oneof": [ + "description" + ] + }, + "_id": { + "oneof": [ + "id" + ] + }, + "_kind": { + "oneof": [ + "kind" + ] + }, + "_name": { + "oneof": [ + "name" + ] + }, + "_selfLink": { + "oneof": [ + "selfLink" + ] + }, + "_selfLinkWithId": { + "oneof": [ + "selfLinkWithId" + ] + }, + "_sourceInfo": { + "oneof": [ + "sourceInfo" + ] + }, + "_sourceInstantSnapshotGroup": { + "oneof": [ + "sourceInstantSnapshotGroup" + ] + }, + "_sourceInstantSnapshotGroupInfo": { + "oneof": [ + "sourceInstantSnapshotGroupInfo" + ] + }, + "_status": { + "oneof": [ + "status" + ] + } + }, + "fields": { + "creationTimestamp": { + "type": "string", + "id": 30525366, + "options": { + "proto3_optional": true + } + }, + "description": { + "type": "string", + "id": 422937596, + "options": { + "proto3_optional": true + } + }, + "id": { + "type": "uint64", + "id": 3355, + "options": { + "proto3_optional": true + } + }, + "kind": { + "type": "string", + "id": 3292052, + "options": { + "proto3_optional": true + } + }, + "name": { + "type": "string", + "id": 3373707, + "options": { + "proto3_optional": true + } + }, + "selfLink": { + "type": "string", + "id": 456214797, + "options": { + "proto3_optional": true + } + }, + "selfLinkWithId": { + "type": "string", + "id": 44520962, + "options": { + "proto3_optional": true + } + }, + "sourceInfo": { + "type": "SnapshotGroupSourceInfo", + "id": 451907154, + "options": { + "proto3_optional": true + } + }, + "sourceInstantSnapshotGroup": { + "type": "string", + "id": 525991686, + "options": { + "proto3_optional": true + } + }, + "sourceInstantSnapshotGroupInfo": { + "type": "SnapshotGroupSourceInstantSnapshotGroupInfo", + "id": 62296647, + "options": { + "proto3_optional": true + } + }, + "status": { + "type": "string", + "id": 181260274, + "options": { + "proto3_optional": true + } + } + }, + "nested": { + "Status": { + "values": { + "UNDEFINED_STATUS": 0, + "CREATING": 455564985, + "DELETING": 528602024, + "FAILED": 455706685, + "INVALID": 530283991, + "READY": 77848963, + "UNKNOWN": 433141802, + "UPLOADING": 267603489 + } + } + } + }, + "SnapshotGroupParameters": { + "oneofs": { + "_sourceSnapshotGroup": { + "oneof": [ + "sourceSnapshotGroup" + ] + }, + "_type": { + "oneof": [ + "type" + ] + } + }, + "fields": { + "replicaZones": { + "rule": "repeated", + "type": "string", + "id": 48438272 + }, + "sourceSnapshotGroup": { + "type": "string", + "id": 225130728, + "options": { + "proto3_optional": true + } + }, + "type": { + "type": "string", + "id": 3575610, + "options": { + "proto3_optional": true + } + } + } + }, + "SnapshotGroupSourceInfo": { + "oneofs": { + "_consistencyGroup": { + "oneof": [ + "consistencyGroup" + ] + }, + "_consistencyGroupId": { + "oneof": [ + "consistencyGroupId" + ] + } + }, + "fields": { + "consistencyGroup": { + "type": "string", + "id": 508183960, + "options": { + "proto3_optional": true + } + }, + "consistencyGroupId": { + "type": "string", + "id": 85599522, + "options": { + "proto3_optional": true + } + } + } + }, + "SnapshotGroupSourceInstantSnapshotGroupInfo": { + "oneofs": { + "_instantSnapshotGroup": { + "oneof": [ + "instantSnapshotGroup" + ] + }, + "_instantSnapshotGroupId": { + "oneof": [ + "instantSnapshotGroupId" + ] + } + }, + "fields": { + "instantSnapshotGroup": { + "type": "string", + "id": 223180386, + "options": { + "proto3_optional": true + } + }, + "instantSnapshotGroupId": { + "type": "string", + "id": 157599768, + "options": { + "proto3_optional": true + } + } + } + }, "SnapshotList": { "oneofs": { "_id": { @@ -221985,6 +225164,11 @@ "network" ] }, + "_params": { + "oneof": [ + "params" + ] + }, "_region": { "oneof": [ "region" @@ -222061,6 +225245,13 @@ "proto3_optional": true } }, + "params": { + "type": "TargetVpnGatewayParams", + "id": 78313862, + "options": { + "proto3_optional": true + } + }, "region": { "type": "string", "id": 138946292, @@ -222247,6 +225438,15 @@ } } }, + "TargetVpnGatewayParams": { + "fields": { + "resourceManagerTags": { + "keyType": "string", + "type": "string", + "id": 377671164 + } + } + }, "TargetVpnGatewaysScopedList": { "oneofs": { "_warning": { @@ -222523,207 +225723,271 @@ } } }, - "TestIamPermissionsExternalVpnGatewayRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "TestIamPermissionsFirewallPolicyRequest": { - "fields": { - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "TestIamPermissionsFirewallRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "TestIamPermissionsForwardingRuleRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "region": { - "type": "string", - "id": 138946292, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "TestIamPermissionsGlobalAddressRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "TestIamPermissionsGlobalForwardingRuleRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "TestIamPermissionsHealthCheckRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "TestIamPermissionsImageRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, - "TestIamPermissionsInstanceGroupManagerRequest": { + "TestIamPermissionsExternalVpnGatewayRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsFirewallPolicyRequest": { + "fields": { + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsFirewallRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsForwardingRuleRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsGlobalAddressRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsGlobalForwardingRuleRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsHealthCheckRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsImageRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsInstanceGroupManagerRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsInstanceGroupRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsInstanceRequest": { "fields": { "project": { "type": "string", @@ -222755,7 +226019,7 @@ } } }, - "TestIamPermissionsInstanceGroupRequest": { + "TestIamPermissionsInstanceTemplateRequest": { "fields": { "project": { "type": "string", @@ -222777,17 +226041,10 @@ "options": { "(google.api.field_behavior)": "REQUIRED" } - }, - "zone": { - "type": "string", - "id": 3744684, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } } } }, - "TestIamPermissionsInstanceRequest": { + "TestIamPermissionsInstantSnapshotGroupRequest": { "fields": { "project": { "type": "string", @@ -222819,31 +226076,6 @@ } } }, - "TestIamPermissionsInstanceTemplateRequest": { - "fields": { - "project": { - "type": "string", - "id": 227560217, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "resource": { - "type": "string", - "id": 195806222, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "testPermissionsRequestResource": { - "type": "TestPermissionsRequest", - "id": 439214758, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } - }, "TestIamPermissionsInstantSnapshotRequest": { "fields": { "project": { @@ -223556,7 +226788,39 @@ } } }, - "TestIamPermissionsRegionHealthSourceRequest": { + "TestIamPermissionsRegionHealthSourceRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "TestIamPermissionsRegionInstanceGroupManagerRequest": { "fields": { "project": { "type": "string", @@ -223588,7 +226852,7 @@ } } }, - "TestIamPermissionsRegionInstanceGroupManagerRequest": { + "TestIamPermissionsRegionInstanceGroupRequest": { "fields": { "project": { "type": "string", @@ -223620,7 +226884,7 @@ } } }, - "TestIamPermissionsRegionInstanceGroupRequest": { + "TestIamPermissionsRegionInstantSnapshotGroupRequest": { "fields": { "project": { "type": "string", @@ -224228,6 +227492,31 @@ } } }, + "TestIamPermissionsSnapshotGroupRequest": { + "fields": { + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "resource": { + "type": "string", + "id": 195806222, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "testPermissionsRequestResource": { + "type": "TestPermissionsRequest", + "id": 439214758, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "TestIamPermissionsSnapshotRequest": { "fields": { "project": { @@ -225533,6 +228822,54 @@ } } }, + "UpdateNamedSetRouterRequest": { + "oneofs": { + "_requestId": { + "oneof": [ + "requestId" + ] + } + }, + "fields": { + "namedSetResource": { + "type": "NamedSet", + "id": 408608401, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "region": { + "type": "string", + "id": 138946292, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "region" + } + }, + "requestId": { + "type": "string", + "id": 37109963, + "options": { + "proto3_optional": true + } + }, + "router": { + "type": "string", + "id": 148608841, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, "UpdateNetworkInterfaceInstanceRequest": { "oneofs": { "_requestId": { @@ -226225,6 +229562,61 @@ } } }, + "UpdateReservationSlotRequest": { + "oneofs": { + "_updateMask": { + "oneof": [ + "updateMask" + ] + } + }, + "fields": { + "parentName": { + "type": "string", + "id": 478151936, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "project": { + "type": "string", + "id": 227560217, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "project" + } + }, + "reservationSlot": { + "type": "string", + "id": 277470865, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "reservationSlotResource": { + "type": "ReservationSlot", + "id": 408545788, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "string", + "id": 500079778, + "options": { + "proto3_optional": true + } + }, + "zone": { + "type": "string", + "id": 3744684, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.cloud.operation_request_field)": "zone" + } + } + } + }, "UpdateReservationsRegionCommitmentRequest": { "oneofs": { "_requestId": { @@ -228261,6 +231653,11 @@ "network" ] }, + "_params": { + "oneof": [ + "params" + ] + }, "_region": { "oneof": [ "region" @@ -228339,6 +231736,13 @@ "proto3_optional": true } }, + "params": { + "type": "VpnGatewayParams", + "id": 78313862, + "options": { + "proto3_optional": true + } + }, "region": { "type": "string", "id": 138946292, @@ -228531,6 +231935,15 @@ } } }, + "VpnGatewayParams": { + "fields": { + "resourceManagerTags": { + "keyType": "string", + "type": "string", + "id": 377671164 + } + } + }, "VpnGatewayStatus": { "fields": { "vpnConnections": { @@ -228821,6 +232234,11 @@ "name" ] }, + "_params": { + "oneof": [ + "params" + ] + }, "_peerExternalGateway": { "oneof": [ "peerExternalGateway" @@ -228968,6 +232386,13 @@ "proto3_optional": true } }, + "params": { + "type": "VpnTunnelParams", + "id": 78313862, + "options": { + "proto3_optional": true + } + }, "peerExternalGateway": { "type": "string", "id": 384956173, @@ -229155,11 +232580,112 @@ "proto3_optional": true } }, - "unreachables": { - "rule": "repeated", - "type": "string", - "id": 243372063 - }, + "unreachables": { + "rule": "repeated", + "type": "string", + "id": 243372063 + }, + "warning": { + "type": "Warning", + "id": 50704284, + "options": { + "proto3_optional": true + } + } + } + }, + "VpnTunnelCipherSuite": { + "oneofs": { + "_phase1": { + "oneof": [ + "phase1" + ] + }, + "_phase2": { + "oneof": [ + "phase2" + ] + } + }, + "fields": { + "phase1": { + "type": "VpnTunnelPhase1Algorithms", + "id": 84289046, + "options": { + "proto3_optional": true + } + }, + "phase2": { + "type": "VpnTunnelPhase2Algorithms", + "id": 84289047, + "options": { + "proto3_optional": true + } + } + } + }, + "VpnTunnelList": { + "oneofs": { + "_id": { + "oneof": [ + "id" + ] + }, + "_kind": { + "oneof": [ + "kind" + ] + }, + "_nextPageToken": { + "oneof": [ + "nextPageToken" + ] + }, + "_selfLink": { + "oneof": [ + "selfLink" + ] + }, + "_warning": { + "oneof": [ + "warning" + ] + } + }, + "fields": { + "id": { + "type": "string", + "id": 3355, + "options": { + "proto3_optional": true + } + }, + "items": { + "rule": "repeated", + "type": "VpnTunnel", + "id": 100526016 + }, + "kind": { + "type": "string", + "id": 3292052, + "options": { + "proto3_optional": true + } + }, + "nextPageToken": { + "type": "string", + "id": 79797525, + "options": { + "proto3_optional": true + } + }, + "selfLink": { + "type": "string", + "id": 456214797, + "options": { + "proto3_optional": true + } + }, "warning": { "type": "Warning", "id": 50704284, @@ -229169,104 +232695,12 @@ } } }, - "VpnTunnelCipherSuite": { - "oneofs": { - "_phase1": { - "oneof": [ - "phase1" - ] - }, - "_phase2": { - "oneof": [ - "phase2" - ] - } - }, - "fields": { - "phase1": { - "type": "VpnTunnelPhase1Algorithms", - "id": 84289046, - "options": { - "proto3_optional": true - } - }, - "phase2": { - "type": "VpnTunnelPhase2Algorithms", - "id": 84289047, - "options": { - "proto3_optional": true - } - } - } - }, - "VpnTunnelList": { - "oneofs": { - "_id": { - "oneof": [ - "id" - ] - }, - "_kind": { - "oneof": [ - "kind" - ] - }, - "_nextPageToken": { - "oneof": [ - "nextPageToken" - ] - }, - "_selfLink": { - "oneof": [ - "selfLink" - ] - }, - "_warning": { - "oneof": [ - "warning" - ] - } - }, + "VpnTunnelParams": { "fields": { - "id": { - "type": "string", - "id": 3355, - "options": { - "proto3_optional": true - } - }, - "items": { - "rule": "repeated", - "type": "VpnTunnel", - "id": 100526016 - }, - "kind": { - "type": "string", - "id": 3292052, - "options": { - "proto3_optional": true - } - }, - "nextPageToken": { - "type": "string", - "id": 79797525, - "options": { - "proto3_optional": true - } - }, - "selfLink": { + "resourceManagerTags": { + "keyType": "string", "type": "string", - "id": 456214797, - "options": { - "proto3_optional": true - } - }, - "warning": { - "type": "Warning", - "id": 50704284, - "options": { - "proto3_optional": true - } + "id": 377671164 } } }, @@ -230190,6 +233624,36 @@ } } }, + "WorkloadIdentityConfig": { + "oneofs": { + "_identity": { + "oneof": [ + "identity" + ] + }, + "_identityCertificateEnabled": { + "oneof": [ + "identityCertificateEnabled" + ] + } + }, + "fields": { + "identity": { + "type": "string", + "id": 401109182, + "options": { + "proto3_optional": true + } + }, + "identityCertificateEnabled": { + "type": "bool", + "id": 342892440, + "options": { + "proto3_optional": true + } + } + } + }, "XpnHostList": { "oneofs": { "_id": { @@ -235022,6 +238486,30 @@ } ] }, + "ConfigureAcceleratorTopologies": { + "requestType": "ConfigureAcceleratorTopologiesInstanceGroupManagerRequest", + "responseType": "Operation", + "options": { + "(google.api.http).body": "instance_group_managers_configure_accelerator_topologies_request_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/instanceGroupManagers/{instance_group_manager}/configureAcceleratorTopologies", + "(google.api.method_signature)": "project,zone,instance_group_manager,instance_group_managers_configure_accelerator_topologies_request_resource", + "(google.cloud.operation_service)": "ZoneOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "instance_group_managers_configure_accelerator_topologies_request_resource", + "post": "/compute/beta/projects/{project}/zones/{zone}/instanceGroupManagers/{instance_group_manager}/configureAcceleratorTopologies" + } + }, + { + "(google.api.method_signature)": "project,zone,instance_group_manager,instance_group_managers_configure_accelerator_topologies_request_resource" + }, + { + "(google.cloud.operation_service)": "ZoneOperations" + } + ] + }, "CreateInstances": { "requestType": "CreateInstancesInstanceGroupManagerRequest", "responseType": "Operation", @@ -237282,6 +240770,154 @@ } } }, + "InstantSnapshotGroups": { + "options": { + "(google.api.default_host)": "compute.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/cloud-platform" + }, + "methods": { + "Delete": { + "requestType": "DeleteInstantSnapshotGroupRequest", + "responseType": "Operation", + "options": { + "(google.api.http).delete": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{instant_snapshot_group}", + "(google.api.method_signature)": "project,zone,instant_snapshot_group", + "(google.cloud.operation_service)": "ZoneOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{instant_snapshot_group}" + } + }, + { + "(google.api.method_signature)": "project,zone,instant_snapshot_group" + }, + { + "(google.cloud.operation_service)": "ZoneOperations" + } + ] + }, + "Get": { + "requestType": "GetInstantSnapshotGroupRequest", + "responseType": "InstantSnapshotGroup", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{instant_snapshot_group}", + "(google.api.method_signature)": "project,zone,instant_snapshot_group" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{instant_snapshot_group}" + } + }, + { + "(google.api.method_signature)": "project,zone,instant_snapshot_group" + } + ] + }, + "GetIamPolicy": { + "requestType": "GetIamPolicyInstantSnapshotGroupRequest", + "responseType": "Policy", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/getIamPolicy", + "(google.api.method_signature)": "project,zone,resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/getIamPolicy" + } + }, + { + "(google.api.method_signature)": "project,zone,resource" + } + ] + }, + "Insert": { + "requestType": "InsertInstantSnapshotGroupRequest", + "responseType": "Operation", + "options": { + "(google.api.http).body": "instant_snapshot_group_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups", + "(google.api.method_signature)": "project,zone,instant_snapshot_group_resource", + "(google.cloud.operation_service)": "ZoneOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "instant_snapshot_group_resource", + "post": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups" + } + }, + { + "(google.api.method_signature)": "project,zone,instant_snapshot_group_resource" + }, + { + "(google.cloud.operation_service)": "ZoneOperations" + } + ] + }, + "List": { + "requestType": "ListInstantSnapshotGroupsRequest", + "responseType": "ListInstantSnapshotGroups", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups", + "(google.api.method_signature)": "project,zone" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups" + } + }, + { + "(google.api.method_signature)": "project,zone" + } + ] + }, + "SetIamPolicy": { + "requestType": "SetIamPolicyInstantSnapshotGroupRequest", + "responseType": "Policy", + "options": { + "(google.api.http).body": "zone_set_policy_request_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/setIamPolicy", + "(google.api.method_signature)": "project,zone,resource,zone_set_policy_request_resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "zone_set_policy_request_resource", + "post": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/setIamPolicy" + } + }, + { + "(google.api.method_signature)": "project,zone,resource,zone_set_policy_request_resource" + } + ] + }, + "TestIamPermissions": { + "requestType": "TestIamPermissionsInstantSnapshotGroupRequest", + "responseType": "TestPermissionsResponse", + "options": { + "(google.api.http).body": "test_permissions_request_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/testIamPermissions", + "(google.api.method_signature)": "project,zone,resource,test_permissions_request_resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "test_permissions_request_resource", + "post": "/compute/beta/projects/{project}/zones/{zone}/instantSnapshotGroups/{resource}/testIamPermissions" + } + }, + { + "(google.api.method_signature)": "project,zone,resource,test_permissions_request_resource" + } + ] + } + } + }, "InstantSnapshots": { "options": { "(google.api.default_host)": "compute.googleapis.com", @@ -244864,6 +248500,154 @@ } } }, + "RegionInstantSnapshotGroups": { + "options": { + "(google.api.default_host)": "compute.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/cloud-platform" + }, + "methods": { + "Delete": { + "requestType": "DeleteRegionInstantSnapshotGroupRequest", + "responseType": "Operation", + "options": { + "(google.api.http).delete": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{instant_snapshot_group}", + "(google.api.method_signature)": "project,region,instant_snapshot_group", + "(google.cloud.operation_service)": "RegionOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{instant_snapshot_group}" + } + }, + { + "(google.api.method_signature)": "project,region,instant_snapshot_group" + }, + { + "(google.cloud.operation_service)": "RegionOperations" + } + ] + }, + "Get": { + "requestType": "GetRegionInstantSnapshotGroupRequest", + "responseType": "InstantSnapshotGroup", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{instant_snapshot_group}", + "(google.api.method_signature)": "project,region,instant_snapshot_group" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{instant_snapshot_group}" + } + }, + { + "(google.api.method_signature)": "project,region,instant_snapshot_group" + } + ] + }, + "GetIamPolicy": { + "requestType": "GetIamPolicyRegionInstantSnapshotGroupRequest", + "responseType": "Policy", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/getIamPolicy", + "(google.api.method_signature)": "project,region,resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/getIamPolicy" + } + }, + { + "(google.api.method_signature)": "project,region,resource" + } + ] + }, + "Insert": { + "requestType": "InsertRegionInstantSnapshotGroupRequest", + "responseType": "Operation", + "options": { + "(google.api.http).body": "instant_snapshot_group_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups", + "(google.api.method_signature)": "project,region,instant_snapshot_group_resource", + "(google.cloud.operation_service)": "RegionOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "instant_snapshot_group_resource", + "post": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups" + } + }, + { + "(google.api.method_signature)": "project,region,instant_snapshot_group_resource" + }, + { + "(google.cloud.operation_service)": "RegionOperations" + } + ] + }, + "List": { + "requestType": "ListRegionInstantSnapshotGroupsRequest", + "responseType": "ListInstantSnapshotGroups", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups", + "(google.api.method_signature)": "project,region" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups" + } + }, + { + "(google.api.method_signature)": "project,region" + } + ] + }, + "SetIamPolicy": { + "requestType": "SetIamPolicyRegionInstantSnapshotGroupRequest", + "responseType": "Policy", + "options": { + "(google.api.http).body": "region_set_policy_request_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/setIamPolicy", + "(google.api.method_signature)": "project,region,resource,region_set_policy_request_resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "region_set_policy_request_resource", + "post": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/setIamPolicy" + } + }, + { + "(google.api.method_signature)": "project,region,resource,region_set_policy_request_resource" + } + ] + }, + "TestIamPermissions": { + "requestType": "TestIamPermissionsRegionInstantSnapshotGroupRequest", + "responseType": "TestPermissionsResponse", + "options": { + "(google.api.http).body": "test_permissions_request_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/testIamPermissions", + "(google.api.method_signature)": "project,region,resource,test_permissions_request_resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "test_permissions_request_resource", + "post": "/compute/beta/projects/{project}/regions/{region}/instantSnapshotGroups/{resource}/testIamPermissions" + } + }, + { + "(google.api.method_signature)": "project,region,resource,test_permissions_request_resource" + } + ] + } + } + }, "RegionInstantSnapshots": { "options": { "(google.api.default_host)": "compute.googleapis.com", @@ -247726,6 +251510,74 @@ } } }, + "ReservationSlots": { + "options": { + "(google.api.default_host)": "compute.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/cloud-platform" + }, + "methods": { + "Get": { + "requestType": "GetReservationSlotRequest", + "responseType": "ReservationSlotsGetResponse", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots/{reservation_slot}", + "(google.api.method_signature)": "project,zone,parent_name,reservation_slot" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots/{reservation_slot}" + } + }, + { + "(google.api.method_signature)": "project,zone,parent_name,reservation_slot" + } + ] + }, + "List": { + "requestType": "ListReservationSlotsRequest", + "responseType": "ReservationSlotsListResponse", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots", + "(google.api.method_signature)": "project,zone,parent_name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots" + } + }, + { + "(google.api.method_signature)": "project,zone,parent_name" + } + ] + }, + "Update": { + "requestType": "UpdateReservationSlotRequest", + "responseType": "Operation", + "options": { + "(google.api.http).body": "reservation_slot_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots/{reservation_slot}", + "(google.api.method_signature)": "project,zone,parent_name,reservation_slot,reservation_slot_resource", + "(google.cloud.operation_service)": "ZoneOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "reservation_slot_resource", + "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*/reservationSubBlocks/*}/reservationSlots/{reservation_slot}" + } + }, + { + "(google.api.method_signature)": "project,zone,parent_name,reservation_slot,reservation_slot_resource" + }, + { + "(google.cloud.operation_service)": "ZoneOperations" + } + ] + } + } + }, "ReservationSubBlocks": { "options": { "(google.api.default_host)": "compute.googleapis.com", @@ -247736,13 +251588,13 @@ "requestType": "GetReservationSubBlockRequest", "responseType": "ReservationSubBlocksGetResponse", "options": { - "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}", + "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}", "(google.api.method_signature)": "project,zone,parent_name,reservation_sub_block" }, "parsedOptions": [ { "(google.api.http)": { - "get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}" + "get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}" } }, { @@ -247754,13 +251606,13 @@ "requestType": "GetIamPolicyReservationSubBlockRequest", "responseType": "Policy", "options": { - "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/getIamPolicy", + "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/getIamPolicy", "(google.api.method_signature)": "project,zone,parent_resource,resource" }, "parsedOptions": [ { "(google.api.http)": { - "get": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/getIamPolicy" + "get": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/getIamPolicy" } }, { @@ -247772,13 +251624,13 @@ "requestType": "ListReservationSubBlocksRequest", "responseType": "ReservationSubBlocksListResponse", "options": { - "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks", + "(google.api.http).get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks", "(google.api.method_signature)": "project,zone,parent_name" }, "parsedOptions": [ { "(google.api.http)": { - "get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks" + "get": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks" } }, { @@ -247790,14 +251642,14 @@ "requestType": "PerformMaintenanceReservationSubBlockRequest", "responseType": "Operation", "options": { - "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/performMaintenance", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}/performMaintenance", "(google.api.method_signature)": "project,zone,parent_name,reservation_sub_block", "(google.cloud.operation_service)": "ZoneOperations" }, "parsedOptions": [ { "(google.api.http)": { - "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/performMaintenance" + "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}/performMaintenance" } }, { @@ -247813,7 +251665,7 @@ "responseType": "Operation", "options": { "(google.api.http).body": "reservation_sub_blocks_report_faulty_request_resource", - "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}/reportFaulty", "(google.api.method_signature)": "project,zone,parent_name,reservation_sub_block,reservation_sub_blocks_report_faulty_request_resource", "(google.cloud.operation_service)": "ZoneOperations" }, @@ -247821,7 +251673,7 @@ { "(google.api.http)": { "body": "reservation_sub_blocks_report_faulty_request_resource", - "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}/reportFaulty" + "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_name=reservations/*/reservationBlocks/*}/reservationSubBlocks/{reservation_sub_block}/reportFaulty" } }, { @@ -247837,14 +251689,14 @@ "responseType": "Policy", "options": { "(google.api.http).body": "zone_set_nested_policy_request_resource", - "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/setIamPolicy", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/setIamPolicy", "(google.api.method_signature)": "project,zone,parent_resource,resource,zone_set_nested_policy_request_resource" }, "parsedOptions": [ { "(google.api.http)": { "body": "zone_set_nested_policy_request_resource", - "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/setIamPolicy" + "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/setIamPolicy" } }, { @@ -247857,14 +251709,14 @@ "responseType": "TestPermissionsResponse", "options": { "(google.api.http).body": "test_permissions_request_resource", - "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/testIamPermissions", + "(google.api.http).post": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/testIamPermissions", "(google.api.method_signature)": "project,zone,parent_resource,resource,test_permissions_request_resource" }, "parsedOptions": [ { "(google.api.http)": { "body": "test_permissions_request_resource", - "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource}/reservationSubBlocks/{resource}/testIamPermissions" + "post": "/compute/beta/projects/{project}/zones/{zone}/{parent_resource=reservations/*/reservationBlocks/*}/reservationSubBlocks/{resource}/testIamPermissions" } }, { @@ -248526,6 +252378,28 @@ } ] }, + "DeleteNamedSet": { + "requestType": "DeleteNamedSetRouterRequest", + "responseType": "Operation", + "options": { + "(google.api.http).post": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/deleteNamedSet", + "(google.api.method_signature)": "project,region,router", + "(google.cloud.operation_service)": "RegionOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/deleteNamedSet" + } + }, + { + "(google.api.method_signature)": "project,region,router" + }, + { + "(google.cloud.operation_service)": "RegionOperations" + } + ] + }, "DeleteRoutePolicy": { "requestType": "DeleteRoutePolicyRouterRequest", "responseType": "Operation", @@ -248566,6 +252440,24 @@ } ] }, + "GetNamedSet": { + "requestType": "GetNamedSetRouterRequest", + "responseType": "RoutersGetNamedSetResponse", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/getNamedSet", + "(google.api.method_signature)": "project,region,router" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/getNamedSet" + } + }, + { + "(google.api.method_signature)": "project,region,router" + } + ] + }, "GetNatIpInfo": { "requestType": "GetNatIpInfoRouterRequest", "responseType": "NatIpInfoResponse", @@ -248698,6 +252590,24 @@ } ] }, + "ListNamedSets": { + "requestType": "ListNamedSetsRoutersRequest", + "responseType": "RoutersListNamedSets", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/listNamedSets", + "(google.api.method_signature)": "project,region,router" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/listNamedSets" + } + }, + { + "(google.api.method_signature)": "project,region,router" + } + ] + }, "ListRoutePolicies": { "requestType": "ListRoutePoliciesRoutersRequest", "responseType": "RoutersListRoutePolicies", @@ -248740,6 +252650,30 @@ } ] }, + "PatchNamedSet": { + "requestType": "PatchNamedSetRouterRequest", + "responseType": "Operation", + "options": { + "(google.api.http).body": "named_set_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/patchNamedSet", + "(google.api.method_signature)": "project,region,router,named_set_resource", + "(google.cloud.operation_service)": "RegionOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "named_set_resource", + "post": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/patchNamedSet" + } + }, + { + "(google.api.method_signature)": "project,region,router,named_set_resource" + }, + { + "(google.cloud.operation_service)": "RegionOperations" + } + ] + }, "PatchRoutePolicy": { "requestType": "PatchRoutePolicyRouterRequest", "responseType": "Operation", @@ -248828,6 +252762,30 @@ } ] }, + "UpdateNamedSet": { + "requestType": "UpdateNamedSetRouterRequest", + "responseType": "Operation", + "options": { + "(google.api.http).body": "named_set_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/updateNamedSet", + "(google.api.method_signature)": "project,region,router,named_set_resource", + "(google.cloud.operation_service)": "RegionOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "named_set_resource", + "post": "/compute/beta/projects/{project}/regions/{region}/routers/{router}/updateNamedSet" + } + }, + { + "(google.api.method_signature)": "project,region,router,named_set_resource" + }, + { + "(google.cloud.operation_service)": "RegionOperations" + } + ] + }, "UpdateRoutePolicy": { "requestType": "UpdateRoutePolicyRouterRequest", "responseType": "Operation", @@ -249436,6 +253394,154 @@ } } }, + "SnapshotGroups": { + "options": { + "(google.api.default_host)": "compute.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/cloud-platform" + }, + "methods": { + "Delete": { + "requestType": "DeleteSnapshotGroupRequest", + "responseType": "Operation", + "options": { + "(google.api.http).delete": "/compute/beta/projects/{project}/global/snapshotGroups/{snapshot_group}", + "(google.api.method_signature)": "project,snapshot_group", + "(google.cloud.operation_service)": "GlobalOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/compute/beta/projects/{project}/global/snapshotGroups/{snapshot_group}" + } + }, + { + "(google.api.method_signature)": "project,snapshot_group" + }, + { + "(google.cloud.operation_service)": "GlobalOperations" + } + ] + }, + "Get": { + "requestType": "GetSnapshotGroupRequest", + "responseType": "SnapshotGroup", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/global/snapshotGroups/{snapshot_group}", + "(google.api.method_signature)": "project,snapshot_group" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/global/snapshotGroups/{snapshot_group}" + } + }, + { + "(google.api.method_signature)": "project,snapshot_group" + } + ] + }, + "GetIamPolicy": { + "requestType": "GetIamPolicySnapshotGroupRequest", + "responseType": "Policy", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/getIamPolicy", + "(google.api.method_signature)": "project,resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/getIamPolicy" + } + }, + { + "(google.api.method_signature)": "project,resource" + } + ] + }, + "Insert": { + "requestType": "InsertSnapshotGroupRequest", + "responseType": "Operation", + "options": { + "(google.api.http).body": "snapshot_group_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/global/snapshotGroups", + "(google.api.method_signature)": "project,snapshot_group_resource", + "(google.cloud.operation_service)": "GlobalOperations" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "snapshot_group_resource", + "post": "/compute/beta/projects/{project}/global/snapshotGroups" + } + }, + { + "(google.api.method_signature)": "project,snapshot_group_resource" + }, + { + "(google.cloud.operation_service)": "GlobalOperations" + } + ] + }, + "List": { + "requestType": "ListSnapshotGroupsRequest", + "responseType": "ListSnapshotGroups", + "options": { + "(google.api.http).get": "/compute/beta/projects/{project}/global/snapshotGroups", + "(google.api.method_signature)": "project" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/compute/beta/projects/{project}/global/snapshotGroups" + } + }, + { + "(google.api.method_signature)": "project" + } + ] + }, + "SetIamPolicy": { + "requestType": "SetIamPolicySnapshotGroupRequest", + "responseType": "Policy", + "options": { + "(google.api.http).body": "global_set_policy_request_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/setIamPolicy", + "(google.api.method_signature)": "project,resource,global_set_policy_request_resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "global_set_policy_request_resource", + "post": "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/setIamPolicy" + } + }, + { + "(google.api.method_signature)": "project,resource,global_set_policy_request_resource" + } + ] + }, + "TestIamPermissions": { + "requestType": "TestIamPermissionsSnapshotGroupRequest", + "responseType": "TestPermissionsResponse", + "options": { + "(google.api.http).body": "test_permissions_request_resource", + "(google.api.http).post": "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/testIamPermissions", + "(google.api.method_signature)": "project,resource,test_permissions_request_resource" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "body": "test_permissions_request_resource", + "post": "/compute/beta/projects/{project}/global/snapshotGroups/{resource}/testIamPermissions" + } + }, + { + "(google.api.method_signature)": "project,resource,test_permissions_request_resource" + } + ] + } + } + }, "SnapshotSettingsService": { "options": { "(google.api.default_host)": "compute.googleapis.com", diff --git a/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.configure_accelerator_topologies.js b/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.configure_accelerator_topologies.js new file mode 100644 index 00000000000..b0749903bbf --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/instance_group_managers.configure_accelerator_topologies.js @@ -0,0 +1,92 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(instanceGroupManager, instanceGroupManagersConfigureAcceleratorTopologiesRequestResource, project, zone) { + // [START compute_v1beta_generated_InstanceGroupManagers_ConfigureAcceleratorTopologies_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The name of the managed instance group. + * It should conform to RFC1035. + */ + // const instanceGroupManager = 'abc123' + /** + * The body resource for this request + */ + // const instanceGroupManagersConfigureAcceleratorTopologiesRequestResource = {} + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * The name of thezone + * where the managed instance group is located. + * It should conform to RFC1035. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {InstanceGroupManagersClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new InstanceGroupManagersClient(); + + async function callConfigureAcceleratorTopologies() { + // Construct request + const request = { + instanceGroupManager, + instanceGroupManagersConfigureAcceleratorTopologiesRequestResource, + project, + zone, + }; + + // Run request + const response = await computeClient.configureAcceleratorTopologies(request); + console.log(response); + } + + callConfigureAcceleratorTopologies(); + // [END compute_v1beta_generated_InstanceGroupManagers_ConfigureAcceleratorTopologies_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.delete.js b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.delete.js new file mode 100644 index 00000000000..05d6cf51fb5 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.delete.js @@ -0,0 +1,85 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(instantSnapshotGroup, project, zone) { + // [START compute_v1beta_generated_InstantSnapshotGroups_Delete_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Name of the InstantSnapshot resource to delete. + */ + // const instantSnapshotGroup = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * The name of the zone for this request. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {InstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new InstantSnapshotGroupsClient(); + + async function callDelete() { + // Construct request + const request = { + instantSnapshotGroup, + project, + zone, + }; + + // Run request + const response = await computeClient.delete(request); + console.log(response); + } + + callDelete(); + // [END compute_v1beta_generated_InstantSnapshotGroups_Delete_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.get.js b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.get.js new file mode 100644 index 00000000000..08cb00549ff --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.get.js @@ -0,0 +1,71 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(instantSnapshotGroup, project, zone) { + // [START compute_v1beta_generated_InstantSnapshotGroups_Get_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Name of the InstantSnapshotGroup resource to return. + */ + // const instantSnapshotGroup = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the zone for this request. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {InstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new InstantSnapshotGroupsClient(); + + async function callGet() { + // Construct request + const request = { + instantSnapshotGroup, + project, + zone, + }; + + // Run request + const response = await computeClient.get(request); + console.log(response); + } + + callGet(); + // [END compute_v1beta_generated_InstantSnapshotGroups_Get_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.get_iam_policy.js b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.get_iam_policy.js new file mode 100644 index 00000000000..144be3471ac --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.get_iam_policy.js @@ -0,0 +1,75 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, resource, zone) { + // [START compute_v1beta_generated_InstantSnapshotGroups_GetIamPolicy_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Requested IAM Policy version. + */ + // const optionsRequestedPolicyVersion = 1234 + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + /** + * The name of the zone for this request. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {InstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new InstantSnapshotGroupsClient(); + + async function callGetIamPolicy() { + // Construct request + const request = { + project, + resource, + zone, + }; + + // Run request + const response = await computeClient.getIamPolicy(request); + console.log(response); + } + + callGetIamPolicy(); + // [END compute_v1beta_generated_InstantSnapshotGroups_GetIamPolicy_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.insert.js b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.insert.js new file mode 100644 index 00000000000..dd23fb3866f --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.insert.js @@ -0,0 +1,89 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(instantSnapshotGroupResource, project, zone) { + // [START compute_v1beta_generated_InstantSnapshotGroups_Insert_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The body resource for this request + */ + // const instantSnapshotGroupResource = {} + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * begin_interface: MixerMutationRequestBuilder + */ + // const sourceConsistencyGroup = 'abc123' + /** + * Name of the zone for this request. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {InstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new InstantSnapshotGroupsClient(); + + async function callInsert() { + // Construct request + const request = { + instantSnapshotGroupResource, + project, + zone, + }; + + // Run request + const response = await computeClient.insert(request); + console.log(response); + } + + callInsert(); + // [END compute_v1beta_generated_InstantSnapshotGroups_Insert_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.list.js b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.list.js new file mode 100644 index 00000000000..9d9ee0a1672 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.list.js @@ -0,0 +1,153 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, zone) { + // [START compute_v1beta_generated_InstantSnapshotGroups_List_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * You cannot combine constraints on multiple fields using regular + * expressions. + */ + // const filter = 'abc123' + /** + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + */ + // const maxResults = 1234 + /** + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + */ + // const orderBy = 'abc123' + /** + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + */ + // const pageToken = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + */ + // const returnPartialSuccess = true + /** + * The name of the zone for this request. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {InstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new InstantSnapshotGroupsClient(); + + async function callList() { + // Construct request + const request = { + project, + zone, + }; + + // Run request + const iterable = computeClient.listAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callList(); + // [END compute_v1beta_generated_InstantSnapshotGroups_List_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.set_iam_policy.js b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.set_iam_policy.js new file mode 100644 index 00000000000..de0aa287eaf --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.set_iam_policy.js @@ -0,0 +1,76 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, resource, zone, zoneSetPolicyRequestResource) { + // [START compute_v1beta_generated_InstantSnapshotGroups_SetIamPolicy_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + /** + * The name of the zone for this request. + */ + // const zone = 'abc123' + /** + * The body resource for this request + */ + // const zoneSetPolicyRequestResource = {} + + // Imports the Compute library + const {InstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new InstantSnapshotGroupsClient(); + + async function callSetIamPolicy() { + // Construct request + const request = { + project, + resource, + zone, + zoneSetPolicyRequestResource, + }; + + // Run request + const response = await computeClient.setIamPolicy(request); + console.log(response); + } + + callSetIamPolicy(); + // [END compute_v1beta_generated_InstantSnapshotGroups_SetIamPolicy_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.test_iam_permissions.js b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.test_iam_permissions.js new file mode 100644 index 00000000000..c4749831916 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/instant_snapshot_groups.test_iam_permissions.js @@ -0,0 +1,76 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, resource, testPermissionsRequestResource, zone) { + // [START compute_v1beta_generated_InstantSnapshotGroups_TestIamPermissions_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + /** + * The body resource for this request + */ + // const testPermissionsRequestResource = {} + /** + * The name of the zone for this request. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {InstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new InstantSnapshotGroupsClient(); + + async function callTestIamPermissions() { + // Construct request + const request = { + project, + resource, + testPermissionsRequestResource, + zone, + }; + + // Run request + const response = await computeClient.testIamPermissions(request); + console.log(response); + } + + callTestIamPermissions(); + // [END compute_v1beta_generated_InstantSnapshotGroups_TestIamPermissions_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.delete.js b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.delete.js new file mode 100644 index 00000000000..d52706087b5 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.delete.js @@ -0,0 +1,85 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(instantSnapshotGroup, project, region) { + // [START compute_v1beta_generated_RegionInstantSnapshotGroups_Delete_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Name of the InstantSnapshotGroup resource to delete. + */ + // const instantSnapshotGroup = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the region for this request. + */ + // const region = 'us-central1' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + + // Imports the Compute library + const {RegionInstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RegionInstantSnapshotGroupsClient(); + + async function callDelete() { + // Construct request + const request = { + instantSnapshotGroup, + project, + region, + }; + + // Run request + const response = await computeClient.delete(request); + console.log(response); + } + + callDelete(); + // [END compute_v1beta_generated_RegionInstantSnapshotGroups_Delete_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.get.js b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.get.js new file mode 100644 index 00000000000..f50146de32d --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.get.js @@ -0,0 +1,71 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(instantSnapshotGroup, project, region) { + // [START compute_v1beta_generated_RegionInstantSnapshotGroups_Get_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Name of the InstantSnapshotGroup resource to return. + */ + // const instantSnapshotGroup = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the region for this request. + */ + // const region = 'us-central1' + + // Imports the Compute library + const {RegionInstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RegionInstantSnapshotGroupsClient(); + + async function callGet() { + // Construct request + const request = { + instantSnapshotGroup, + project, + region, + }; + + // Run request + const response = await computeClient.get(request); + console.log(response); + } + + callGet(); + // [END compute_v1beta_generated_RegionInstantSnapshotGroups_Get_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.get_iam_policy.js b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.get_iam_policy.js new file mode 100644 index 00000000000..c0bd5ef8182 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.get_iam_policy.js @@ -0,0 +1,75 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, region, resource) { + // [START compute_v1beta_generated_RegionInstantSnapshotGroups_GetIamPolicy_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Requested IAM Policy version. + */ + // const optionsRequestedPolicyVersion = 1234 + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the region for this request. + */ + // const region = 'us-central1' + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + + // Imports the Compute library + const {RegionInstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RegionInstantSnapshotGroupsClient(); + + async function callGetIamPolicy() { + // Construct request + const request = { + project, + region, + resource, + }; + + // Run request + const response = await computeClient.getIamPolicy(request); + console.log(response); + } + + callGetIamPolicy(); + // [END compute_v1beta_generated_RegionInstantSnapshotGroups_GetIamPolicy_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.insert.js b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.insert.js new file mode 100644 index 00000000000..d82bdd41be0 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.insert.js @@ -0,0 +1,89 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(instantSnapshotGroupResource, project, region) { + // [START compute_v1beta_generated_RegionInstantSnapshotGroups_Insert_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The body resource for this request + */ + // const instantSnapshotGroupResource = {} + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name of the region for this request. + */ + // const region = 'us-central1' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * begin_interface: MixerMutationRequestBuilder + */ + // const sourceConsistencyGroup = 'abc123' + + // Imports the Compute library + const {RegionInstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RegionInstantSnapshotGroupsClient(); + + async function callInsert() { + // Construct request + const request = { + instantSnapshotGroupResource, + project, + region, + }; + + // Run request + const response = await computeClient.insert(request); + console.log(response); + } + + callInsert(); + // [END compute_v1beta_generated_RegionInstantSnapshotGroups_Insert_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.list.js b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.list.js new file mode 100644 index 00000000000..d1990e266f2 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.list.js @@ -0,0 +1,153 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, region) { + // [START compute_v1beta_generated_RegionInstantSnapshotGroups_List_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * You cannot combine constraints on multiple fields using regular + * expressions. + */ + // const filter = 'abc123' + /** + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + */ + // const maxResults = 1234 + /** + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + */ + // const orderBy = 'abc123' + /** + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + */ + // const pageToken = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the region for this request. + */ + // const region = 'us-central1' + /** + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + */ + // const returnPartialSuccess = true + + // Imports the Compute library + const {RegionInstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RegionInstantSnapshotGroupsClient(); + + async function callList() { + // Construct request + const request = { + project, + region, + }; + + // Run request + const iterable = computeClient.listAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callList(); + // [END compute_v1beta_generated_RegionInstantSnapshotGroups_List_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.set_iam_policy.js b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.set_iam_policy.js new file mode 100644 index 00000000000..eed00b72b9d --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.set_iam_policy.js @@ -0,0 +1,76 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, region, regionSetPolicyRequestResource, resource) { + // [START compute_v1beta_generated_RegionInstantSnapshotGroups_SetIamPolicy_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the region for this request. + */ + // const region = 'us-central1' + /** + * The body resource for this request + */ + // const regionSetPolicyRequestResource = {} + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + + // Imports the Compute library + const {RegionInstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RegionInstantSnapshotGroupsClient(); + + async function callSetIamPolicy() { + // Construct request + const request = { + project, + region, + regionSetPolicyRequestResource, + resource, + }; + + // Run request + const response = await computeClient.setIamPolicy(request); + console.log(response); + } + + callSetIamPolicy(); + // [END compute_v1beta_generated_RegionInstantSnapshotGroups_SetIamPolicy_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.test_iam_permissions.js b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.test_iam_permissions.js new file mode 100644 index 00000000000..a20949f6741 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/region_instant_snapshot_groups.test_iam_permissions.js @@ -0,0 +1,76 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, region, resource, testPermissionsRequestResource) { + // [START compute_v1beta_generated_RegionInstantSnapshotGroups_TestIamPermissions_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the region for this request. + */ + // const region = 'us-central1' + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + /** + * The body resource for this request + */ + // const testPermissionsRequestResource = {} + + // Imports the Compute library + const {RegionInstantSnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RegionInstantSnapshotGroupsClient(); + + async function callTestIamPermissions() { + // Construct request + const request = { + project, + region, + resource, + testPermissionsRequestResource, + }; + + // Run request + const response = await computeClient.testIamPermissions(request); + console.log(response); + } + + callTestIamPermissions(); + // [END compute_v1beta_generated_RegionInstantSnapshotGroups_TestIamPermissions_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.get.js b/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.get.js new file mode 100644 index 00000000000..462d5428014 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.get.js @@ -0,0 +1,78 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parentName, project, reservationSlot, zone) { + // [START compute_v1beta_generated_ReservationSlots_Get_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The name of the parent reservation and parent block, formatted as + * reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} + */ + // const parentName = 'abc123' + /** + * The project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the reservation slot, formatted as RFC1035 or a resource ID + * number. + */ + // const reservationSlot = 'abc123' + /** + * The name of the zone for this request, formatted as RFC1035. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {ReservationSlotsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new ReservationSlotsClient(); + + async function callGet() { + // Construct request + const request = { + parentName, + project, + reservationSlot, + zone, + }; + + // Run request + const response = await computeClient.get(request); + console.log(response); + } + + callGet(); + // [END compute_v1beta_generated_ReservationSlots_Get_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.list.js b/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.list.js new file mode 100644 index 00000000000..036d2be471b --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.list.js @@ -0,0 +1,159 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parentName, project, zone) { + // [START compute_v1beta_generated_ReservationSlots_List_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * You cannot combine constraints on multiple fields using regular + * expressions. + */ + // const filter = 'abc123' + /** + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + */ + // const maxResults = 1234 + /** + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + */ + // const orderBy = 'abc123' + /** + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + */ + // const pageToken = 'abc123' + /** + * The name of the parent reservation and parent block, formatted as + * reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} + */ + // const parentName = 'abc123' + /** + * The project ID for this request. + */ + // const project = 'my-project' + /** + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + */ + // const returnPartialSuccess = true + /** + * The name of the zone for this request, formatted as RFC1035. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {ReservationSlotsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new ReservationSlotsClient(); + + async function callList() { + // Construct request + const request = { + parentName, + project, + zone, + }; + + // Run request + const iterable = computeClient.listAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callList(); + // [END compute_v1beta_generated_ReservationSlots_List_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.update.js b/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.update.js new file mode 100644 index 00000000000..56056c2b143 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/reservation_slots.update.js @@ -0,0 +1,85 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parentName, project, reservationSlot, reservationSlotResource, zone) { + // [START compute_v1beta_generated_ReservationSlots_Update_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The name of the sub-block resource. + */ + // const parentName = 'abc123' + /** + * The project ID for this request. + */ + // const project = 'my-project' + /** + * The name of the slot resource. + */ + // const reservationSlot = 'abc123' + /** + * The body resource for this request + */ + // const reservationSlotResource = {} + /** + * The fields to be updated as part of this request. + */ + // const updateMask = 'abc123' + /** + * The name of the zone for this request, formatted as RFC1035. + */ + // const zone = 'abc123' + + // Imports the Compute library + const {ReservationSlotsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new ReservationSlotsClient(); + + async function callUpdate() { + // Construct request + const request = { + parentName, + project, + reservationSlot, + reservationSlotResource, + zone, + }; + + // Run request + const response = await computeClient.update(request); + console.log(response); + } + + callUpdate(); + // [END compute_v1beta_generated_ReservationSlots_Update_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/routers.delete_named_set.js b/packages/google-cloud-compute/samples/generated/v1beta/routers.delete_named_set.js new file mode 100644 index 00000000000..a6d30e11e29 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/routers.delete_named_set.js @@ -0,0 +1,89 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, region, router) { + // [START compute_v1beta_generated_Routers_DeleteNamedSet_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The Named Set name for this request. Name must conform to RFC1035 + */ + // const namedSet = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name of the region for this request. + */ + // const region = 'us-central1' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * Name of the Router resource where Named Set is defined. + */ + // const router = 'abc123' + + // Imports the Compute library + const {RoutersClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RoutersClient(); + + async function callDeleteNamedSet() { + // Construct request + const request = { + project, + region, + router, + }; + + // Run request + const response = await computeClient.deleteNamedSet(request); + console.log(response); + } + + callDeleteNamedSet(); + // [END compute_v1beta_generated_Routers_DeleteNamedSet_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/routers.get_named_set.js b/packages/google-cloud-compute/samples/generated/v1beta/routers.get_named_set.js new file mode 100644 index 00000000000..8ff8e3946e5 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/routers.get_named_set.js @@ -0,0 +1,76 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, region, router) { + // [START compute_v1beta_generated_Routers_GetNamedSet_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The Named Set name for this request. Name must conform to RFC1035 + */ + // const namedSet = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name of the region for this request. + */ + // const region = 'us-central1' + /** + * Name of the Router resource to query for the named set. The name should + * conform to RFC1035. + */ + // const router = 'abc123' + + // Imports the Compute library + const {RoutersClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RoutersClient(); + + async function callGetNamedSet() { + // Construct request + const request = { + project, + region, + router, + }; + + // Run request + const response = await computeClient.getNamedSet(request); + console.log(response); + } + + callGetNamedSet(); + // [END compute_v1beta_generated_Routers_GetNamedSet_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/routers.list_named_sets.js b/packages/google-cloud-compute/samples/generated/v1beta/routers.list_named_sets.js new file mode 100644 index 00000000000..c96c3cb7ccb --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/routers.list_named_sets.js @@ -0,0 +1,159 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, region, router) { + // [START compute_v1beta_generated_Routers_ListNamedSets_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * You cannot combine constraints on multiple fields using regular + * expressions. + */ + // const filter = 'abc123' + /** + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + */ + // const maxResults = 1234 + /** + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + */ + // const orderBy = 'abc123' + /** + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + */ + // const pageToken = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name of the region for this request. + */ + // const region = 'us-central1' + /** + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + */ + // const returnPartialSuccess = true + /** + * Name or id of the resource for this request. + * Name should conform to RFC1035. + */ + // const router = 'abc123' + + // Imports the Compute library + const {RoutersClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RoutersClient(); + + async function callListNamedSets() { + // Construct request + const request = { + project, + region, + router, + }; + + // Run request + const iterable = computeClient.listNamedSetsAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callListNamedSets(); + // [END compute_v1beta_generated_Routers_ListNamedSets_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/routers.patch_named_set.js b/packages/google-cloud-compute/samples/generated/v1beta/routers.patch_named_set.js new file mode 100644 index 00000000000..990e01c8849 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/routers.patch_named_set.js @@ -0,0 +1,90 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(namedSetResource, project, region, router) { + // [START compute_v1beta_generated_Routers_PatchNamedSet_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The body resource for this request + */ + // const namedSetResource = {} + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name of the region for this request. + */ + // const region = 'us-central1' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * Name of the Router resource where Named Set is defined. + */ + // const router = 'abc123' + + // Imports the Compute library + const {RoutersClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RoutersClient(); + + async function callPatchNamedSet() { + // Construct request + const request = { + namedSetResource, + project, + region, + router, + }; + + // Run request + const response = await computeClient.patchNamedSet(request); + console.log(response); + } + + callPatchNamedSet(); + // [END compute_v1beta_generated_Routers_PatchNamedSet_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/routers.update_named_set.js b/packages/google-cloud-compute/samples/generated/v1beta/routers.update_named_set.js new file mode 100644 index 00000000000..0681b59c6ab --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/routers.update_named_set.js @@ -0,0 +1,90 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(namedSetResource, project, region, router) { + // [START compute_v1beta_generated_Routers_UpdateNamedSet_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The body resource for this request + */ + // const namedSetResource = {} + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name of the region for this request. + */ + // const region = 'us-central1' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * Name of the Router resource where Named Set is defined. + */ + // const router = 'abc123' + + // Imports the Compute library + const {RoutersClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new RoutersClient(); + + async function callUpdateNamedSet() { + // Construct request + const request = { + namedSetResource, + project, + region, + router, + }; + + // Run request + const response = await computeClient.updateNamedSet(request); + console.log(response); + } + + callUpdateNamedSet(); + // [END compute_v1beta_generated_Routers_UpdateNamedSet_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.delete.js b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.delete.js new file mode 100644 index 00000000000..f5a80e8bfb5 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.delete.js @@ -0,0 +1,80 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, snapshotGroup) { + // [START compute_v1beta_generated_SnapshotGroups_Delete_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * Name of the SnapshotGroup resource to delete. + */ + // const snapshotGroup = 'abc123' + + // Imports the Compute library + const {SnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new SnapshotGroupsClient(); + + async function callDelete() { + // Construct request + const request = { + project, + snapshotGroup, + }; + + // Run request + const response = await computeClient.delete(request); + console.log(response); + } + + callDelete(); + // [END compute_v1beta_generated_SnapshotGroups_Delete_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.get.js b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.get.js new file mode 100644 index 00000000000..4f4281f40fe --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.get.js @@ -0,0 +1,66 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, snapshotGroup) { + // [START compute_v1beta_generated_SnapshotGroups_Get_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name of the SnapshotGroup resource to return. + */ + // const snapshotGroup = 'abc123' + + // Imports the Compute library + const {SnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new SnapshotGroupsClient(); + + async function callGet() { + // Construct request + const request = { + project, + snapshotGroup, + }; + + // Run request + const response = await computeClient.get(request); + console.log(response); + } + + callGet(); + // [END compute_v1beta_generated_SnapshotGroups_Get_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.get_iam_policy.js b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.get_iam_policy.js new file mode 100644 index 00000000000..53264fcb922 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.get_iam_policy.js @@ -0,0 +1,70 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, resource) { + // [START compute_v1beta_generated_SnapshotGroups_GetIamPolicy_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Requested IAM Policy version. + */ + // const optionsRequestedPolicyVersion = 1234 + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + + // Imports the Compute library + const {SnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new SnapshotGroupsClient(); + + async function callGetIamPolicy() { + // Construct request + const request = { + project, + resource, + }; + + // Run request + const response = await computeClient.getIamPolicy(request); + console.log(response); + } + + callGetIamPolicy(); + // [END compute_v1beta_generated_SnapshotGroups_GetIamPolicy_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.insert.js b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.insert.js new file mode 100644 index 00000000000..2515f3c2a51 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.insert.js @@ -0,0 +1,80 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, snapshotGroupResource) { + // [START compute_v1beta_generated_SnapshotGroups_Insert_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + */ + // const requestId = 'abc123' + /** + * The body resource for this request + */ + // const snapshotGroupResource = {} + + // Imports the Compute library + const {SnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new SnapshotGroupsClient(); + + async function callInsert() { + // Construct request + const request = { + project, + snapshotGroupResource, + }; + + // Run request + const response = await computeClient.insert(request); + console.log(response); + } + + callInsert(); + // [END compute_v1beta_generated_SnapshotGroups_Insert_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.list.js b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.list.js new file mode 100644 index 00000000000..c77df2238c4 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.list.js @@ -0,0 +1,148 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project) { + // [START compute_v1beta_generated_SnapshotGroups_List_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * You cannot combine constraints on multiple fields using regular + * expressions. + */ + // const filter = 'abc123' + /** + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + */ + // const maxResults = 1234 + /** + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + */ + // const orderBy = 'abc123' + /** + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + */ + // const pageToken = 'abc123' + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + */ + // const returnPartialSuccess = true + + // Imports the Compute library + const {SnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new SnapshotGroupsClient(); + + async function callList() { + // Construct request + const request = { + project, + }; + + // Run request + const iterable = computeClient.listAsync(request); + for await (const response of iterable) { + console.log(response); + } + } + + callList(); + // [END compute_v1beta_generated_SnapshotGroups_List_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.set_iam_policy.js b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.set_iam_policy.js new file mode 100644 index 00000000000..9418d808d86 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.set_iam_policy.js @@ -0,0 +1,71 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(globalSetPolicyRequestResource, project, resource) { + // [START compute_v1beta_generated_SnapshotGroups_SetIamPolicy_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * The body resource for this request + */ + // const globalSetPolicyRequestResource = {} + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + + // Imports the Compute library + const {SnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new SnapshotGroupsClient(); + + async function callSetIamPolicy() { + // Construct request + const request = { + globalSetPolicyRequestResource, + project, + resource, + }; + + // Run request + const response = await computeClient.setIamPolicy(request); + console.log(response); + } + + callSetIamPolicy(); + // [END compute_v1beta_generated_SnapshotGroups_SetIamPolicy_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.test_iam_permissions.js b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.test_iam_permissions.js new file mode 100644 index 00000000000..e159cab9fd9 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated/v1beta/snapshot_groups.test_iam_permissions.js @@ -0,0 +1,71 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(project, resource, testPermissionsRequestResource) { + // [START compute_v1beta_generated_SnapshotGroups_TestIamPermissions_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Project ID for this request. + */ + // const project = 'my-project' + /** + * Name or id of the resource for this request. + */ + // const resource = 'abc123' + /** + * The body resource for this request + */ + // const testPermissionsRequestResource = {} + + // Imports the Compute library + const {SnapshotGroupsClient} = require('@google-cloud/compute').v1beta; + + // Instantiates a client + const computeClient = new SnapshotGroupsClient(); + + async function callTestIamPermissions() { + // Construct request + const request = { + project, + resource, + testPermissionsRequestResource, + }; + + // Run request + const response = await computeClient.testIamPermissions(request); + console.log(response); + } + + callTestIamPermissions(); + // [END compute_v1beta_generated_SnapshotGroups_TestIamPermissions_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/packages/google-cloud-compute/samples/generated/v1beta/snippet_metadata_google.cloud.compute.v1beta.json b/packages/google-cloud-compute/samples/generated/v1beta/snippet_metadata_google.cloud.compute.v1beta.json index 442b89fd996..4a9d891f2b2 100644 --- a/packages/google-cloud-compute/samples/generated/v1beta/snippet_metadata_google.cloud.compute.v1beta.json +++ b/packages/google-cloud-compute/samples/generated/v1beta/snippet_metadata_google.cloud.compute.v1beta.json @@ -4007,7 +4007,7 @@ "regionTag": "compute_v1beta_generated_Disks_Update_async", "title": "AcceleratorTypes update Sample", "origin": "API_DEFINITION", - "description": " Updates the specified disk with the data included in the request. The update is performed only on selected fields included as part of update-mask. Only the following fields can be modified: user_license.", + "description": " Updates the specified disk with the data included in the request. The update is performed only on selected fields included as part of update-mask.", "canonical": true, "file": "disks.update.js", "language": "JAVASCRIPT", @@ -7883,7 +7883,7 @@ "regionTag": "compute_v1beta_generated_GlobalNetworkEndpointGroups_Insert_async", "title": "AcceleratorTypes insert Sample", "origin": "API_DEFINITION", - "description": " Creates a network endpoint group in the specified project using the parameters that are included in the request.", + "description": " Creates a network endpoint group in the specified project using the parameters that are included in the request. Note: Use the following APIs to manage network endpoint groups: - To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity NEGs): zonal API - To manage NEGs with regional scope (such as regional internet NEGs, serverless NEGs, Private Service Connect NEGs): regional API - To manage NEGs with global scope (such as global internet NEGs):global API", "canonical": true, "file": "global_network_endpoint_groups.insert.js", "language": "JAVASCRIPT", @@ -10515,6 +10515,62 @@ } } }, + { + "regionTag": "compute_v1beta_generated_InstanceGroupManagers_ConfigureAcceleratorTopologies_async", + "title": "AcceleratorTypes configureAcceleratorTopologies Sample", + "origin": "API_DEFINITION", + "description": " Updates the accelerator topologies configuration.", + "canonical": true, + "file": "instance_group_managers.configure_accelerator_topologies.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 84, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ConfigureAcceleratorTopologies", + "fullName": "google.cloud.compute.v1beta.InstanceGroupManagers.ConfigureAcceleratorTopologies", + "async": true, + "parameters": [ + { + "name": "instance_group_manager", + "type": "TYPE_STRING" + }, + { + "name": "instance_group_managers_configure_accelerator_topologies_request_resource", + "type": ".google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "InstanceGroupManagersClient", + "fullName": "google.cloud.compute.v1beta.InstanceGroupManagersClient" + }, + "method": { + "shortName": "ConfigureAcceleratorTopologies", + "fullName": "google.cloud.compute.v1beta.InstanceGroupManagers.ConfigureAcceleratorTopologies", + "service": { + "shortName": "InstanceGroupManagers", + "fullName": "google.cloud.compute.v1beta.InstanceGroupManagers" + } + } + } + }, { "regionTag": "compute_v1beta_generated_InstanceGroupManagers_CreateInstances_async", "title": "AcceleratorTypes createInstances Sample", @@ -16219,6 +16275,382 @@ } } }, + { + "regionTag": "compute_v1beta_generated_InstantSnapshotGroups_Delete_async", + "title": "AcceleratorTypes delete Sample", + "origin": "API_DEFINITION", + "description": " deletes a Zonal InstantSnapshotGroup resource", + "canonical": true, + "file": "instant_snapshot_groups.delete.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 77, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Delete", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.Delete", + "async": true, + "parameters": [ + { + "name": "instant_snapshot_group", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "InstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroupsClient" + }, + "method": { + "shortName": "Delete", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.Delete", + "service": { + "shortName": "InstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_InstantSnapshotGroups_Get_async", + "title": "AcceleratorTypes get Sample", + "origin": "API_DEFINITION", + "description": " returns the specified InstantSnapshotGroup resource in the specified zone.", + "canonical": true, + "file": "instant_snapshot_groups.get.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Get", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.Get", + "async": true, + "parameters": [ + { + "name": "instant_snapshot_group", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.InstantSnapshotGroup", + "client": { + "shortName": "InstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroupsClient" + }, + "method": { + "shortName": "Get", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.Get", + "service": { + "shortName": "InstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_InstantSnapshotGroups_GetIamPolicy_async", + "title": "AcceleratorTypes getIamPolicy Sample", + "origin": "API_DEFINITION", + "description": " Gets the access control policy for a resource. May be empty if no such policy or resource exists.", + "canonical": true, + "file": "instant_snapshot_groups.get_iam_policy.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 67, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.GetIamPolicy", + "async": true, + "parameters": [ + { + "name": "options_requested_policy_version", + "type": "TYPE_INT32" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": "TYPE_STRING" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Policy", + "client": { + "shortName": "InstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroupsClient" + }, + "method": { + "shortName": "GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.GetIamPolicy", + "service": { + "shortName": "InstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_InstantSnapshotGroups_Insert_async", + "title": "AcceleratorTypes insert Sample", + "origin": "API_DEFINITION", + "description": " inserts a Zonal InstantSnapshotGroup resource", + "canonical": true, + "file": "instant_snapshot_groups.insert.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 81, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Insert", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.Insert", + "async": true, + "parameters": [ + { + "name": "instant_snapshot_group_resource", + "type": ".google.cloud.compute.v1beta.InstantSnapshotGroup" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "source_consistency_group", + "type": "TYPE_STRING" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "InstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroupsClient" + }, + "method": { + "shortName": "Insert", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.Insert", + "service": { + "shortName": "InstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_InstantSnapshotGroups_List_async", + "title": "AcceleratorTypes list Sample", + "origin": "API_DEFINITION", + "description": " retrieves the list of InstantSnapshotGroup resources contained within the specified zone.", + "canonical": true, + "file": "instant_snapshot_groups.list.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 145, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "List", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.List", + "async": true, + "parameters": [ + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "max_results", + "type": "TYPE_UINT32" + }, + { + "name": "order_by", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "return_partial_success", + "type": "TYPE_BOOL" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.ListInstantSnapshotGroups", + "client": { + "shortName": "InstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroupsClient" + }, + "method": { + "shortName": "List", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.List", + "service": { + "shortName": "InstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_InstantSnapshotGroups_SetIamPolicy_async", + "title": "AcceleratorTypes setIamPolicy Sample", + "origin": "API_DEFINITION", + "description": " Sets the access control policy on the specified resource. Replaces any existing policy.", + "canonical": true, + "file": "instant_snapshot_groups.set_iam_policy.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "SetIamPolicy", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.SetIamPolicy", + "async": true, + "parameters": [ + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": "TYPE_STRING" + }, + { + "name": "zone", + "type": "TYPE_STRING" + }, + { + "name": "zone_set_policy_request_resource", + "type": ".google.cloud.compute.v1beta.ZoneSetPolicyRequest" + } + ], + "resultType": ".google.cloud.compute.v1beta.Policy", + "client": { + "shortName": "InstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroupsClient" + }, + "method": { + "shortName": "SetIamPolicy", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.SetIamPolicy", + "service": { + "shortName": "InstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_InstantSnapshotGroups_TestIamPermissions_async", + "title": "AcceleratorTypes testIamPermissions Sample", + "origin": "API_DEFINITION", + "description": " Returns permissions that a caller has on the specified resource.", + "canonical": true, + "file": "instant_snapshot_groups.test_iam_permissions.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.TestIamPermissions", + "async": true, + "parameters": [ + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": "TYPE_STRING" + }, + { + "name": "test_permissions_request_resource", + "type": ".google.cloud.compute.v1beta.TestPermissionsRequest" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.TestPermissionsResponse", + "client": { + "shortName": "InstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroupsClient" + }, + "method": { + "shortName": "TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups.TestIamPermissions", + "service": { + "shortName": "InstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.InstantSnapshotGroups" + } + } + } + }, { "regionTag": "compute_v1beta_generated_InstantSnapshots_AggregatedList_async", "title": "AcceleratorTypes aggregatedList Sample", @@ -20883,7 +21315,7 @@ "regionTag": "compute_v1beta_generated_NetworkEndpointGroups_Insert_async", "title": "AcceleratorTypes insert Sample", "origin": "API_DEFINITION", - "description": " Creates a network endpoint group in the specified project using the parameters that are included in the request.", + "description": " Creates a network endpoint group in the specified project using the parameters that are included in the request. Note: Use the following APIs to manage network endpoint groups: - To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity NEGs): zonal API - To manage NEGs with regional scope (such as regional internet NEGs, serverless NEGs, Private Service Connect NEGs): regional API - To manage NEGs with global scope (such as global internet NEGs):global API", "canonical": true, "file": "network_endpoint_groups.insert.js", "language": "JAVASCRIPT", @@ -30567,7 +30999,7 @@ "regionTag": "compute_v1beta_generated_RegionDisks_Update_async", "title": "AcceleratorTypes update Sample", "origin": "API_DEFINITION", - "description": " Update the specified disk with the data included in the request. Update is performed only on selected fields included as part of update-mask. Only the following fields can be modified: user_license.", + "description": " Update the specified disk with the data included in the request. Update is performed only on selected fields included as part of update-mask.", "canonical": true, "file": "region_disks.update.js", "language": "JAVASCRIPT", @@ -34767,6 +35199,382 @@ } } }, + { + "regionTag": "compute_v1beta_generated_RegionInstantSnapshotGroups_Delete_async", + "title": "AcceleratorTypes delete Sample", + "origin": "API_DEFINITION", + "description": " deletes a Regional InstantSnapshotGroup resource", + "canonical": true, + "file": "region_instant_snapshot_groups.delete.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 77, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Delete", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.Delete", + "async": true, + "parameters": [ + { + "name": "instant_snapshot_group", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "RegionInstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroupsClient" + }, + "method": { + "shortName": "Delete", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.Delete", + "service": { + "shortName": "RegionInstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_RegionInstantSnapshotGroups_Get_async", + "title": "AcceleratorTypes get Sample", + "origin": "API_DEFINITION", + "description": " returns the specified InstantSnapshotGroup resource in the specified region.", + "canonical": true, + "file": "region_instant_snapshot_groups.get.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Get", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.Get", + "async": true, + "parameters": [ + { + "name": "instant_snapshot_group", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.InstantSnapshotGroup", + "client": { + "shortName": "RegionInstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroupsClient" + }, + "method": { + "shortName": "Get", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.Get", + "service": { + "shortName": "RegionInstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_RegionInstantSnapshotGroups_GetIamPolicy_async", + "title": "AcceleratorTypes getIamPolicy Sample", + "origin": "API_DEFINITION", + "description": " Gets the access control policy for a resource. May be empty if no such policy or resource exists.", + "canonical": true, + "file": "region_instant_snapshot_groups.get_iam_policy.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 67, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.GetIamPolicy", + "async": true, + "parameters": [ + { + "name": "options_requested_policy_version", + "type": "TYPE_INT32" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Policy", + "client": { + "shortName": "RegionInstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroupsClient" + }, + "method": { + "shortName": "GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.GetIamPolicy", + "service": { + "shortName": "RegionInstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_RegionInstantSnapshotGroups_Insert_async", + "title": "AcceleratorTypes insert Sample", + "origin": "API_DEFINITION", + "description": " creates a Regional InstantSnapshotGroup resource", + "canonical": true, + "file": "region_instant_snapshot_groups.insert.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 81, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Insert", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.Insert", + "async": true, + "parameters": [ + { + "name": "instant_snapshot_group_resource", + "type": ".google.cloud.compute.v1beta.InstantSnapshotGroup" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "source_consistency_group", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "RegionInstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroupsClient" + }, + "method": { + "shortName": "Insert", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.Insert", + "service": { + "shortName": "RegionInstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_RegionInstantSnapshotGroups_List_async", + "title": "AcceleratorTypes list Sample", + "origin": "API_DEFINITION", + "description": " retrieves the list of InstantSnapshotGroup resources contained within the specified region.", + "canonical": true, + "file": "region_instant_snapshot_groups.list.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 145, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "List", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.List", + "async": true, + "parameters": [ + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "max_results", + "type": "TYPE_UINT32" + }, + { + "name": "order_by", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "return_partial_success", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.cloud.compute.v1beta.ListInstantSnapshotGroups", + "client": { + "shortName": "RegionInstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroupsClient" + }, + "method": { + "shortName": "List", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.List", + "service": { + "shortName": "RegionInstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_RegionInstantSnapshotGroups_SetIamPolicy_async", + "title": "AcceleratorTypes setIamPolicy Sample", + "origin": "API_DEFINITION", + "description": " Sets the access control policy on the specified resource. Replaces any existing policy.", + "canonical": true, + "file": "region_instant_snapshot_groups.set_iam_policy.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "SetIamPolicy", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.SetIamPolicy", + "async": true, + "parameters": [ + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "region_set_policy_request_resource", + "type": ".google.cloud.compute.v1beta.RegionSetPolicyRequest" + }, + { + "name": "resource", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Policy", + "client": { + "shortName": "RegionInstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroupsClient" + }, + "method": { + "shortName": "SetIamPolicy", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.SetIamPolicy", + "service": { + "shortName": "RegionInstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_RegionInstantSnapshotGroups_TestIamPermissions_async", + "title": "AcceleratorTypes testIamPermissions Sample", + "origin": "API_DEFINITION", + "description": " Returns permissions that a caller has on the specified resource.", + "canonical": true, + "file": "region_instant_snapshot_groups.test_iam_permissions.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.TestIamPermissions", + "async": true, + "parameters": [ + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": "TYPE_STRING" + }, + { + "name": "test_permissions_request_resource", + "type": ".google.cloud.compute.v1beta.TestPermissionsRequest" + } + ], + "resultType": ".google.cloud.compute.v1beta.TestPermissionsResponse", + "client": { + "shortName": "RegionInstantSnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroupsClient" + }, + "method": { + "shortName": "TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups.TestIamPermissions", + "service": { + "shortName": "RegionInstantSnapshotGroups", + "fullName": "google.cloud.compute.v1beta.RegionInstantSnapshotGroups" + } + } + } + }, { "regionTag": "compute_v1beta_generated_RegionInstantSnapshots_Delete_async", "title": "AcceleratorTypes delete Sample", @@ -35747,7 +36555,7 @@ "regionTag": "compute_v1beta_generated_RegionNetworkEndpointGroups_Insert_async", "title": "AcceleratorTypes insert Sample", "origin": "API_DEFINITION", - "description": " Creates a network endpoint group in the specified project using the parameters that are included in the request.", + "description": " Creates a network endpoint group in the specified project using the parameters that are included in the request. Note: Use the following APIs to manage network endpoint groups: - To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity NEGs): zonal API - To manage NEGs with regional scope (such as regional internet NEGs, serverless NEGs, Private Service Connect NEGs): regional API - To manage NEGs with global scope (such as global internet NEGs):global API", "canonical": true, "file": "region_network_endpoint_groups.insert.js", "language": "JAVASCRIPT", @@ -42519,6 +43327,186 @@ } } }, + { + "regionTag": "compute_v1beta_generated_ReservationSlots_Get_async", + "title": "AcceleratorTypes get Sample", + "origin": "API_DEFINITION", + "description": " Retrieves information about the specified reservation slot.", + "canonical": true, + "file": "reservation_slots.get.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 70, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Get", + "fullName": "google.cloud.compute.v1beta.ReservationSlots.Get", + "async": true, + "parameters": [ + { + "name": "parent_name", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "reservation_slot", + "type": "TYPE_STRING" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.ReservationSlotsGetResponse", + "client": { + "shortName": "ReservationSlotsClient", + "fullName": "google.cloud.compute.v1beta.ReservationSlotsClient" + }, + "method": { + "shortName": "Get", + "fullName": "google.cloud.compute.v1beta.ReservationSlots.Get", + "service": { + "shortName": "ReservationSlots", + "fullName": "google.cloud.compute.v1beta.ReservationSlots" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_ReservationSlots_List_async", + "title": "AcceleratorTypes list Sample", + "origin": "API_DEFINITION", + "description": " Retrieves a list of reservation slots under a single reservation.", + "canonical": true, + "file": "reservation_slots.list.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 151, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "List", + "fullName": "google.cloud.compute.v1beta.ReservationSlots.List", + "async": true, + "parameters": [ + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "max_results", + "type": "TYPE_UINT32" + }, + { + "name": "order_by", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "parent_name", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "return_partial_success", + "type": "TYPE_BOOL" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.ReservationSlotsListResponse", + "client": { + "shortName": "ReservationSlotsClient", + "fullName": "google.cloud.compute.v1beta.ReservationSlotsClient" + }, + "method": { + "shortName": "List", + "fullName": "google.cloud.compute.v1beta.ReservationSlots.List", + "service": { + "shortName": "ReservationSlots", + "fullName": "google.cloud.compute.v1beta.ReservationSlots" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_ReservationSlots_Update_async", + "title": "AcceleratorTypes update Sample", + "origin": "API_DEFINITION", + "description": " Update a reservation slot in the specified sub-block.", + "canonical": true, + "file": "reservation_slots.update.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 77, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Update", + "fullName": "google.cloud.compute.v1beta.ReservationSlots.Update", + "async": true, + "parameters": [ + { + "name": "parent_name", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "reservation_slot", + "type": "TYPE_STRING" + }, + { + "name": "reservation_slot_resource", + "type": ".google.cloud.compute.v1beta.ReservationSlot" + }, + { + "name": "update_mask", + "type": "TYPE_STRING" + }, + { + "name": "zone", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "ReservationSlotsClient", + "fullName": "google.cloud.compute.v1beta.ReservationSlotsClient" + }, + "method": { + "shortName": "Update", + "fullName": "google.cloud.compute.v1beta.ReservationSlots.Update", + "service": { + "shortName": "ReservationSlots", + "fullName": "google.cloud.compute.v1beta.ReservationSlots" + } + } + } + }, { "regionTag": "compute_v1beta_generated_ReservationSubBlocks_Get_async", "title": "AcceleratorTypes get Sample", @@ -43951,6 +44939,62 @@ } } }, + { + "regionTag": "compute_v1beta_generated_Routers_DeleteNamedSet_async", + "title": "AcceleratorTypes deleteNamedSet Sample", + "origin": "API_DEFINITION", + "description": " Deletes Named Set", + "canonical": true, + "file": "routers.delete_named_set.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 81, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeleteNamedSet", + "fullName": "google.cloud.compute.v1beta.Routers.DeleteNamedSet", + "async": true, + "parameters": [ + { + "name": "named_set", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "router", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "RoutersClient", + "fullName": "google.cloud.compute.v1beta.RoutersClient" + }, + "method": { + "shortName": "DeleteNamedSet", + "fullName": "google.cloud.compute.v1beta.Routers.DeleteNamedSet", + "service": { + "shortName": "Routers", + "fullName": "google.cloud.compute.v1beta.Routers" + } + } + } + }, { "regionTag": "compute_v1beta_generated_Routers_DeleteRoutePolicy_async", "title": "AcceleratorTypes deleteRoutePolicy Sample", @@ -44055,6 +45099,58 @@ } } }, + { + "regionTag": "compute_v1beta_generated_Routers_GetNamedSet_async", + "title": "AcceleratorTypes getNamedSet Sample", + "origin": "API_DEFINITION", + "description": " Returns specified Named Set", + "canonical": true, + "file": "routers.get_named_set.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetNamedSet", + "fullName": "google.cloud.compute.v1beta.Routers.GetNamedSet", + "async": true, + "parameters": [ + { + "name": "named_set", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "router", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.RoutersGetNamedSetResponse", + "client": { + "shortName": "RoutersClient", + "fullName": "google.cloud.compute.v1beta.RoutersClient" + }, + "method": { + "shortName": "GetNamedSet", + "fullName": "google.cloud.compute.v1beta.Routers.GetNamedSet", + "service": { + "shortName": "Routers", + "fullName": "google.cloud.compute.v1beta.Routers" + } + } + } + }, { "regionTag": "compute_v1beta_generated_Routers_GetNatIpInfo_async", "title": "AcceleratorTypes getNatIpInfo Sample", @@ -44483,6 +45579,74 @@ } } }, + { + "regionTag": "compute_v1beta_generated_Routers_ListNamedSets_async", + "title": "AcceleratorTypes listNamedSets Sample", + "origin": "API_DEFINITION", + "description": " Retrieves a list of router named set subresources available to the specified project.", + "canonical": true, + "file": "routers.list_named_sets.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 151, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListNamedSets", + "fullName": "google.cloud.compute.v1beta.Routers.ListNamedSets", + "async": true, + "parameters": [ + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "max_results", + "type": "TYPE_UINT32" + }, + { + "name": "order_by", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "return_partial_success", + "type": "TYPE_BOOL" + }, + { + "name": "router", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.RoutersListNamedSets", + "client": { + "shortName": "RoutersClient", + "fullName": "google.cloud.compute.v1beta.RoutersClient" + }, + "method": { + "shortName": "ListNamedSets", + "fullName": "google.cloud.compute.v1beta.Routers.ListNamedSets", + "service": { + "shortName": "Routers", + "fullName": "google.cloud.compute.v1beta.Routers" + } + } + } + }, { "regionTag": "compute_v1beta_generated_Routers_ListRoutePolicies_async", "title": "AcceleratorTypes listRoutePolicies Sample", @@ -44607,6 +45771,62 @@ } } }, + { + "regionTag": "compute_v1beta_generated_Routers_PatchNamedSet_async", + "title": "AcceleratorTypes patchNamedSet Sample", + "origin": "API_DEFINITION", + "description": " Patches Named Set", + "canonical": true, + "file": "routers.patch_named_set.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 82, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "PatchNamedSet", + "fullName": "google.cloud.compute.v1beta.Routers.PatchNamedSet", + "async": true, + "parameters": [ + { + "name": "named_set_resource", + "type": ".google.cloud.compute.v1beta.NamedSet" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "router", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "RoutersClient", + "fullName": "google.cloud.compute.v1beta.RoutersClient" + }, + "method": { + "shortName": "PatchNamedSet", + "fullName": "google.cloud.compute.v1beta.Routers.PatchNamedSet", + "service": { + "shortName": "Routers", + "fullName": "google.cloud.compute.v1beta.Routers" + } + } + } + }, { "regionTag": "compute_v1beta_generated_Routers_PatchRoutePolicy_async", "title": "AcceleratorTypes patchRoutePolicy Sample", @@ -44823,6 +46043,62 @@ } } }, + { + "regionTag": "compute_v1beta_generated_Routers_UpdateNamedSet_async", + "title": "AcceleratorTypes updateNamedSet Sample", + "origin": "API_DEFINITION", + "description": " Updates or creates new Named Set", + "canonical": true, + "file": "routers.update_named_set.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 82, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateNamedSet", + "fullName": "google.cloud.compute.v1beta.Routers.UpdateNamedSet", + "async": true, + "parameters": [ + { + "name": "named_set_resource", + "type": ".google.cloud.compute.v1beta.NamedSet" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "region", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "router", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "RoutersClient", + "fullName": "google.cloud.compute.v1beta.RoutersClient" + }, + "method": { + "shortName": "UpdateNamedSet", + "fullName": "google.cloud.compute.v1beta.Routers.UpdateNamedSet", + "service": { + "shortName": "Routers", + "fullName": "google.cloud.compute.v1beta.Routers" + } + } + } + }, { "regionTag": "compute_v1beta_generated_Routers_UpdateRoutePolicy_async", "title": "AcceleratorTypes updateRoutePolicy Sample", @@ -46319,6 +47595,350 @@ } } }, + { + "regionTag": "compute_v1beta_generated_SnapshotGroups_Delete_async", + "title": "AcceleratorTypes delete Sample", + "origin": "API_DEFINITION", + "description": " Deletes the specified SnapshotGroup resource", + "canonical": true, + "file": "snapshot_groups.delete.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 72, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Delete", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.Delete", + "async": true, + "parameters": [ + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "snapshot_group", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "SnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.SnapshotGroupsClient" + }, + "method": { + "shortName": "Delete", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.Delete", + "service": { + "shortName": "SnapshotGroups", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_SnapshotGroups_Get_async", + "title": "AcceleratorTypes get Sample", + "origin": "API_DEFINITION", + "description": " returns the specified SnapshotGroup resource.", + "canonical": true, + "file": "snapshot_groups.get.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 58, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Get", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.Get", + "async": true, + "parameters": [ + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "snapshot_group", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.SnapshotGroup", + "client": { + "shortName": "SnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.SnapshotGroupsClient" + }, + "method": { + "shortName": "Get", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.Get", + "service": { + "shortName": "SnapshotGroups", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_SnapshotGroups_GetIamPolicy_async", + "title": "AcceleratorTypes getIamPolicy Sample", + "origin": "API_DEFINITION", + "description": " Gets the access control policy for a resource. May be empty if no such policy or resource exists.", + "canonical": true, + "file": "snapshot_groups.get_iam_policy.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 62, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.GetIamPolicy", + "async": true, + "parameters": [ + { + "name": "options_requested_policy_version", + "type": "TYPE_INT32" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Policy", + "client": { + "shortName": "SnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.SnapshotGroupsClient" + }, + "method": { + "shortName": "GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.GetIamPolicy", + "service": { + "shortName": "SnapshotGroups", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_SnapshotGroups_Insert_async", + "title": "AcceleratorTypes insert Sample", + "origin": "API_DEFINITION", + "description": " Creates a snapshot group in the specified project using the data included in the request.", + "canonical": true, + "file": "snapshot_groups.insert.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 72, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "Insert", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.Insert", + "async": true, + "parameters": [ + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "request_id", + "type": "TYPE_STRING" + }, + { + "name": "snapshot_group_resource", + "type": ".google.cloud.compute.v1beta.SnapshotGroup" + } + ], + "resultType": ".google.cloud.compute.v1beta.Operation", + "client": { + "shortName": "SnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.SnapshotGroupsClient" + }, + "method": { + "shortName": "Insert", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.Insert", + "service": { + "shortName": "SnapshotGroups", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_SnapshotGroups_List_async", + "title": "AcceleratorTypes list Sample", + "origin": "API_DEFINITION", + "description": " retrieves the list of SnapshotGroup resources contained within the specified project.", + "canonical": true, + "file": "snapshot_groups.list.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 140, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "List", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.List", + "async": true, + "parameters": [ + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "max_results", + "type": "TYPE_UINT32" + }, + { + "name": "order_by", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "return_partial_success", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.cloud.compute.v1beta.ListSnapshotGroups", + "client": { + "shortName": "SnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.SnapshotGroupsClient" + }, + "method": { + "shortName": "List", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.List", + "service": { + "shortName": "SnapshotGroups", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_SnapshotGroups_SetIamPolicy_async", + "title": "AcceleratorTypes setIamPolicy Sample", + "origin": "API_DEFINITION", + "description": " Sets the access control policy on the specified resource. Replaces any existing policy.", + "canonical": true, + "file": "snapshot_groups.set_iam_policy.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "SetIamPolicy", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.SetIamPolicy", + "async": true, + "parameters": [ + { + "name": "global_set_policy_request_resource", + "type": ".google.cloud.compute.v1beta.GlobalSetPolicyRequest" + }, + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.compute.v1beta.Policy", + "client": { + "shortName": "SnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.SnapshotGroupsClient" + }, + "method": { + "shortName": "SetIamPolicy", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.SetIamPolicy", + "service": { + "shortName": "SnapshotGroups", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups" + } + } + } + }, + { + "regionTag": "compute_v1beta_generated_SnapshotGroups_TestIamPermissions_async", + "title": "AcceleratorTypes testIamPermissions Sample", + "origin": "API_DEFINITION", + "description": " Returns permissions that a caller has on the specified resource.", + "canonical": true, + "file": "snapshot_groups.test_iam_permissions.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.TestIamPermissions", + "async": true, + "parameters": [ + { + "name": "project", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": "TYPE_STRING" + }, + { + "name": "test_permissions_request_resource", + "type": ".google.cloud.compute.v1beta.TestPermissionsRequest" + } + ], + "resultType": ".google.cloud.compute.v1beta.TestPermissionsResponse", + "client": { + "shortName": "SnapshotGroupsClient", + "fullName": "google.cloud.compute.v1beta.SnapshotGroupsClient" + }, + "method": { + "shortName": "TestIamPermissions", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups.TestIamPermissions", + "service": { + "shortName": "SnapshotGroups", + "fullName": "google.cloud.compute.v1beta.SnapshotGroups" + } + } + } + }, { "regionTag": "compute_v1beta_generated_Snapshots_AggregatedList_async", "title": "AcceleratorTypes aggregatedList Sample", diff --git a/packages/google-cloud-compute/samples/package.json b/packages/google-cloud-compute/samples/package.json index 41379e07a5f..42b36ae40f1 100644 --- a/packages/google-cloud-compute/samples/package.json +++ b/packages/google-cloud-compute/samples/package.json @@ -14,7 +14,7 @@ "test": "mocha test --timeout 1200000" }, "dependencies": { - "@google-cloud/compute": "^6.7.0", + "@google-cloud/compute": "^6.8.0", "@sendgrid/mail": "^8.0.0", "nodemailer": "^7.0.0", "nodemailer-smtp-transport": "^2.7.4" diff --git a/packages/google-cloud-compute/src/v1beta/disks_client.ts b/packages/google-cloud-compute/src/v1beta/disks_client.ts index 5a360d89a1d..5b9fe262f45 100644 --- a/packages/google-cloud-compute/src/v1beta/disks_client.ts +++ b/packages/google-cloud-compute/src/v1beta/disks_client.ts @@ -2191,7 +2191,7 @@ export class DisksClient { /** * Updates the specified disk with the data included in the request. * The update is performed only on selected fields included as part - * of update-mask. Only the following fields can be modified: user_license. + * of update-mask. * * @param {Object} request * The request object that will be sent. diff --git a/packages/google-cloud-compute/src/v1beta/gapic_metadata.json b/packages/google-cloud-compute/src/v1beta/gapic_metadata.json index 2a937e75fd9..aac7d5ab9a3 100644 --- a/packages/google-cloud-compute/src/v1beta/gapic_metadata.json +++ b/packages/google-cloud-compute/src/v1beta/gapic_metadata.json @@ -2506,6 +2506,11 @@ "applyUpdatesToInstances" ] }, + "ConfigureAcceleratorTopologies": { + "methods": [ + "configureAcceleratorTopologies" + ] + }, "CreateInstances": { "methods": [ "createInstances" @@ -2666,6 +2671,11 @@ "applyUpdatesToInstances" ] }, + "ConfigureAcceleratorTopologies": { + "methods": [ + "configureAcceleratorTopologies" + ] + }, "CreateInstances": { "methods": [ "createInstances" @@ -3663,6 +3673,94 @@ } } }, + "InstantSnapshotGroups": { + "clients": { + "grpc": { + "libraryClient": "InstantSnapshotGroupsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "getIamPolicy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "SetIamPolicy": { + "methods": [ + "setIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "testIamPermissions" + ] + }, + "List": { + "methods": [ + "list", + "listStream", + "listAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "InstantSnapshotGroupsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "getIamPolicy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "SetIamPolicy": { + "methods": [ + "setIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "testIamPermissions" + ] + }, + "List": { + "methods": [ + "list", + "listStream", + "listAsync" + ] + } + } + } + } + }, "InstantSnapshots": { "clients": { "grpc": { @@ -7975,6 +8073,94 @@ } } }, + "RegionInstantSnapshotGroups": { + "clients": { + "grpc": { + "libraryClient": "RegionInstantSnapshotGroupsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "getIamPolicy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "SetIamPolicy": { + "methods": [ + "setIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "testIamPermissions" + ] + }, + "List": { + "methods": [ + "list", + "listStream", + "listAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "RegionInstantSnapshotGroupsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "getIamPolicy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "SetIamPolicy": { + "methods": [ + "setIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "testIamPermissions" + ] + }, + "List": { + "methods": [ + "list", + "listStream", + "listAsync" + ] + } + } + } + } + }, "RegionInstantSnapshots": { "clients": { "grpc": { @@ -9771,6 +9957,54 @@ } } }, + "ReservationSlots": { + "clients": { + "grpc": { + "libraryClient": "ReservationSlotsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "Update": { + "methods": [ + "update" + ] + }, + "List": { + "methods": [ + "list", + "listStream", + "listAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "ReservationSlotsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "Update": { + "methods": [ + "update" + ] + }, + "List": { + "methods": [ + "list", + "listStream", + "listAsync" + ] + } + } + } + } + }, "ReservationSubBlocks": { "clients": { "grpc": { @@ -10097,6 +10331,11 @@ "delete" ] }, + "DeleteNamedSet": { + "methods": [ + "deleteNamedSet" + ] + }, "DeleteRoutePolicy": { "methods": [ "deleteRoutePolicy" @@ -10107,6 +10346,11 @@ "get" ] }, + "GetNamedSet": { + "methods": [ + "getNamedSet" + ] + }, "GetNatIpInfo": { "methods": [ "getNatIpInfo" @@ -10132,6 +10376,11 @@ "patch" ] }, + "PatchNamedSet": { + "methods": [ + "patchNamedSet" + ] + }, "PatchRoutePolicy": { "methods": [ "patchRoutePolicy" @@ -10152,6 +10401,11 @@ "update" ] }, + "UpdateNamedSet": { + "methods": [ + "updateNamedSet" + ] + }, "UpdateRoutePolicy": { "methods": [ "updateRoutePolicy" @@ -10185,6 +10439,13 @@ "listBgpRoutesAsync" ] }, + "ListNamedSets": { + "methods": [ + "listNamedSets", + "listNamedSetsStream", + "listNamedSetsAsync" + ] + }, "ListRoutePolicies": { "methods": [ "listRoutePolicies", @@ -10202,6 +10463,11 @@ "delete" ] }, + "DeleteNamedSet": { + "methods": [ + "deleteNamedSet" + ] + }, "DeleteRoutePolicy": { "methods": [ "deleteRoutePolicy" @@ -10212,6 +10478,11 @@ "get" ] }, + "GetNamedSet": { + "methods": [ + "getNamedSet" + ] + }, "GetNatIpInfo": { "methods": [ "getNatIpInfo" @@ -10237,6 +10508,11 @@ "patch" ] }, + "PatchNamedSet": { + "methods": [ + "patchNamedSet" + ] + }, "PatchRoutePolicy": { "methods": [ "patchRoutePolicy" @@ -10257,6 +10533,11 @@ "update" ] }, + "UpdateNamedSet": { + "methods": [ + "updateNamedSet" + ] + }, "UpdateRoutePolicy": { "methods": [ "updateRoutePolicy" @@ -10290,6 +10571,13 @@ "listBgpRoutesAsync" ] }, + "ListNamedSets": { + "methods": [ + "listNamedSets", + "listNamedSetsStream", + "listNamedSetsAsync" + ] + }, "ListRoutePolicies": { "methods": [ "listRoutePolicies", @@ -10633,6 +10921,94 @@ } } }, + "SnapshotGroups": { + "clients": { + "grpc": { + "libraryClient": "SnapshotGroupsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "getIamPolicy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "SetIamPolicy": { + "methods": [ + "setIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "testIamPermissions" + ] + }, + "List": { + "methods": [ + "list", + "listStream", + "listAsync" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "SnapshotGroupsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "getIamPolicy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "SetIamPolicy": { + "methods": [ + "setIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "testIamPermissions" + ] + }, + "List": { + "methods": [ + "list", + "listStream", + "listAsync" + ] + } + } + } + } + }, "Snapshots": { "clients": { "grpc": { diff --git a/packages/google-cloud-compute/src/v1beta/global_network_endpoint_groups_client.ts b/packages/google-cloud-compute/src/v1beta/global_network_endpoint_groups_client.ts index 4bd7d5b7ec9..5130517e2b8 100644 --- a/packages/google-cloud-compute/src/v1beta/global_network_endpoint_groups_client.ts +++ b/packages/google-cloud-compute/src/v1beta/global_network_endpoint_groups_client.ts @@ -783,6 +783,20 @@ export class GlobalNetworkEndpointGroupsClient { * Creates a network endpoint group in the specified project using the * parameters that are included in the request. * + * Note: Use the following APIs to manage network endpoint groups: + * + * - + * To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity + * NEGs): zonal + * API + * - + * To manage NEGs with regional scope (such as regional internet NEGs, + * serverless NEGs, Private Service Connect NEGs): regional + * API + * - + * To manage NEGs with global scope (such as global internet NEGs):global + * API + * * @param {Object} request * The request object that will be sent. * @param {google.cloud.compute.v1beta.NetworkEndpointGroup} request.networkEndpointGroupResource diff --git a/packages/google-cloud-compute/src/v1beta/index.ts b/packages/google-cloud-compute/src/v1beta/index.ts index d84d804673e..6259de8b95a 100644 --- a/packages/google-cloud-compute/src/v1beta/index.ts +++ b/packages/google-cloud-compute/src/v1beta/index.ts @@ -47,6 +47,7 @@ export {InstanceGroupsClient} from './instance_groups_client'; export {InstancesClient} from './instances_client'; export {InstanceSettingsServiceClient} from './instance_settings_service_client'; export {InstanceTemplatesClient} from './instance_templates_client'; +export {InstantSnapshotGroupsClient} from './instant_snapshot_groups_client'; export {InstantSnapshotsClient} from './instant_snapshots_client'; export {InterconnectAttachmentGroupsClient} from './interconnect_attachment_groups_client'; export {InterconnectAttachmentsClient} from './interconnect_attachments_client'; @@ -90,6 +91,7 @@ export {RegionInstanceGroupManagersClient} from './region_instance_group_manager export {RegionInstanceGroupsClient} from './region_instance_groups_client'; export {RegionInstancesClient} from './region_instances_client'; export {RegionInstanceTemplatesClient} from './region_instance_templates_client'; +export {RegionInstantSnapshotGroupsClient} from './region_instant_snapshot_groups_client'; export {RegionInstantSnapshotsClient} from './region_instant_snapshots_client'; export {RegionMultiMigMembersClient} from './region_multi_mig_members_client'; export {RegionMultiMigsClient} from './region_multi_migs_client'; @@ -111,6 +113,7 @@ export {RegionUrlMapsClient} from './region_url_maps_client'; export {RegionZonesClient} from './region_zones_client'; export {ReservationBlocksClient} from './reservation_blocks_client'; export {ReservationsClient} from './reservations_client'; +export {ReservationSlotsClient} from './reservation_slots_client'; export {ReservationSubBlocksClient} from './reservation_sub_blocks_client'; export {ResourcePoliciesClient} from './resource_policies_client'; export {RolloutPlansClient} from './rollout_plans_client'; @@ -119,6 +122,7 @@ export {RoutersClient} from './routers_client'; export {RoutesClient} from './routes_client'; export {SecurityPoliciesClient} from './security_policies_client'; export {ServiceAttachmentsClient} from './service_attachments_client'; +export {SnapshotGroupsClient} from './snapshot_groups_client'; export {SnapshotsClient} from './snapshots_client'; export {SnapshotSettingsServiceClient} from './snapshot_settings_service_client'; export {SslCertificatesClient} from './ssl_certificates_client'; diff --git a/packages/google-cloud-compute/src/v1beta/instance_group_managers_client.ts b/packages/google-cloud-compute/src/v1beta/instance_group_managers_client.ts index 2672bc65a45..135231f6ad0 100644 --- a/packages/google-cloud-compute/src/v1beta/instance_group_managers_client.ts +++ b/packages/google-cloud-compute/src/v1beta/instance_group_managers_client.ts @@ -231,7 +231,7 @@ export class InstanceGroupManagersClient { // Iterate over each of the methods that the service provides // and create an API call method for each. const instanceGroupManagersStubMethods = - ['abandonInstances', 'aggregatedList', 'applyUpdatesToInstances', 'createInstances', 'delete', 'deleteInstances', 'deletePerInstanceConfigs', 'get', 'getAvailableAcceleratorTopologies', 'insert', 'list', 'listErrors', 'listManagedInstances', 'listPerInstanceConfigs', 'patch', 'patchPerInstanceConfigs', 'recreateInstances', 'resize', 'resizeAdvanced', 'resumeInstances', 'setAutoHealingPolicies', 'setInstanceTemplate', 'setTargetPools', 'startInstances', 'stopInstances', 'suspendInstances', 'testIamPermissions', 'update', 'updatePerInstanceConfigs']; + ['abandonInstances', 'aggregatedList', 'applyUpdatesToInstances', 'configureAcceleratorTopologies', 'createInstances', 'delete', 'deleteInstances', 'deletePerInstanceConfigs', 'get', 'getAvailableAcceleratorTopologies', 'insert', 'list', 'listErrors', 'listManagedInstances', 'listPerInstanceConfigs', 'patch', 'patchPerInstanceConfigs', 'recreateInstances', 'resize', 'resizeAdvanced', 'resumeInstances', 'setAutoHealingPolicies', 'setInstanceTemplate', 'setTargetPools', 'startInstances', 'stopInstances', 'suspendInstances', 'testIamPermissions', 'update', 'updatePerInstanceConfigs']; for (const methodName of instanceGroupManagersStubMethods) { const callPromise = this.instanceGroupManagersStub.then( stub => (...args: Array<{}>) => { @@ -578,6 +578,128 @@ export class InstanceGroupManagersClient { throw error; }); } +/** + * Updates the accelerator topologies configuration. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.instanceGroupManager + * The name of the managed instance group. + * It should conform to RFC1035. + * @param {google.cloud.compute.v1beta.InstanceGroupManagersConfigureAcceleratorTopologiesRequest} request.instanceGroupManagersConfigureAcceleratorTopologiesRequestResource + * The body resource for this request + * @param {string} request.project + * Project ID for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {string} request.zone + * The name of thezone + * where the managed instance group is located. + * It should conform to RFC1035. + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/instance_group_managers.configure_accelerator_topologies.js + * region_tag:compute_v1beta_generated_InstanceGroupManagers_ConfigureAcceleratorTopologies_async + */ + configureAcceleratorTopologies( + request?: protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + configureAcceleratorTopologies( + request: protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest|null|undefined, + {}|null|undefined>): void; + configureAcceleratorTopologies( + request: protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest|null|undefined, + {}|null|undefined>): void; + configureAcceleratorTopologies( + request?: protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'instance_group_manager': request.instanceGroupManager ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('configureAcceleratorTopologies request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IConfigureAcceleratorTopologiesInstanceGroupManagerRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('configureAcceleratorTopologies response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.configureAcceleratorTopologies(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } /** * Creates instances with per-instance configurations in this managed instance * group. Instances are created using the current instance template. Thecreate instances operation is marked DONE if thecreateInstances request is successful. The underlying actions diff --git a/packages/google-cloud-compute/src/v1beta/instance_group_managers_client_config.json b/packages/google-cloud-compute/src/v1beta/instance_group_managers_client_config.json index 6ac5588038e..ba4a05c7666 100644 --- a/packages/google-cloud-compute/src/v1beta/instance_group_managers_client_config.json +++ b/packages/google-cloud-compute/src/v1beta/instance_group_managers_client_config.json @@ -32,6 +32,10 @@ "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, + "ConfigureAcceleratorTopologies": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, "CreateInstances": { "retry_codes_name": "non_idempotent", "retry_params_name": "default" diff --git a/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_client.ts b/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_client.ts new file mode 100644 index 00000000000..aa03f049db5 --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_client.ts @@ -0,0 +1,1446 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1beta/instant_snapshot_groups_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './instant_snapshot_groups_client_config.json'; +const version = require('../../../package.json').version; + +/** + * The InstantSnapshotGroups API. + * @class + * @memberof v1beta + */ +export class InstantSnapshotGroupsClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('compute'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + instantSnapshotGroupsStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of InstantSnapshotGroupsClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new InstantSnapshotGroupsClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof InstantSnapshotGroupsClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'compute.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + // Implicitly enable HTTP transport for the APIs that use REST as transport (e.g. Google Cloud Compute). + if (!opts) { + opts = {fallback: true}; + } else { + opts.fallback = opts.fallback ?? true; + } + const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + + // 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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + list: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items') + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.compute.v1beta.InstantSnapshotGroups', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.instantSnapshotGroupsStub) { + return this.instantSnapshotGroupsStub; + } + + // Put together the "service stub" for + // google.cloud.compute.v1beta.InstantSnapshotGroups. + this.instantSnapshotGroupsStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.compute.v1beta.InstantSnapshotGroups') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.compute.v1beta.InstantSnapshotGroups, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const instantSnapshotGroupsStubMethods = + ['delete', 'get', 'getIamPolicy', 'insert', 'list', 'setIamPolicy', 'testIamPermissions']; + for (const methodName of instantSnapshotGroupsStubMethods) { + const callPromise = this.instantSnapshotGroupsStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + this.descriptors.page[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.instantSnapshotGroupsStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'compute.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'compute.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/compute', + 'https://www.googleapis.com/auth/cloud-platform' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * deletes a Zonal InstantSnapshotGroup resource + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.instantSnapshotGroup + * Name of the InstantSnapshot resource to delete. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {string} request.zone + * The name of the zone for this request. + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/instant_snapshot_groups.delete.js + * region_tag:compute_v1beta_generated_InstantSnapshotGroups_Delete_async + */ + delete( + request?: protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + delete( + request: protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + delete( + request: protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + delete( + request?: protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'instant_snapshot_group': request.instantSnapshotGroup ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('delete request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('delete response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.delete(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * returns the specified InstantSnapshotGroup resource in the specified zone. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.instantSnapshotGroup + * Name of the InstantSnapshotGroup resource to return. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.zone + * The name of the zone for this request. + * @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.cloud.compute.v1beta.InstantSnapshotGroup|InstantSnapshotGroup}. + * 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/v1beta/instant_snapshot_groups.get.js + * region_tag:compute_v1beta_generated_InstantSnapshotGroups_Get_async + */ + get( + request?: protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest|undefined, {}|undefined + ]>; + get( + request: protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + get( + request: protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + get( + request?: protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'instant_snapshot_group': request.instantSnapshotGroup ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('get request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('get response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.get(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetInstantSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('get response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Gets the access control policy for a resource. May be empty if no such + * policy or resource exists. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.optionsRequestedPolicyVersion + * Requested IAM Policy version. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.resource + * Name or id of the resource for this request. + * @param {string} request.zone + * The name of the zone for this request. + * @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.cloud.compute.v1beta.Policy|Policy}. + * 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/v1beta/instant_snapshot_groups.get_iam_policy.js + * region_tag:compute_v1beta_generated_InstantSnapshotGroups_GetIamPolicy_async + */ + getIamPolicy( + request?: protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest|undefined, {}|undefined + ]>; + getIamPolicy( + request: protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + getIamPolicy( + request: protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + getIamPolicy( + request?: protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getIamPolicy request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getIamPolicy(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyInstantSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * inserts a Zonal InstantSnapshotGroup resource + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.compute.v1beta.InstantSnapshotGroup} request.instantSnapshotGroupResource + * The body resource for this request + * @param {string} request.project + * Project ID for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {string} request.sourceConsistencyGroup + * begin_interface: MixerMutationRequestBuilder + * @param {string} request.zone + * Name of the zone for this request. + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/instant_snapshot_groups.insert.js + * region_tag:compute_v1beta_generated_InstantSnapshotGroups_Insert_async + */ + insert( + request?: protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + insert( + request: protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + insert( + request: protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + insert( + request?: protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('insert request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('insert response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.insert(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Sets the access control policy on the specified resource. + * Replaces any existing policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.resource + * Name or id of the resource for this request. + * @param {string} request.zone + * The name of the zone for this request. + * @param {google.cloud.compute.v1beta.ZoneSetPolicyRequest} request.zoneSetPolicyRequestResource + * The body resource for this request + * @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.cloud.compute.v1beta.Policy|Policy}. + * 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/v1beta/instant_snapshot_groups.set_iam_policy.js + * region_tag:compute_v1beta_generated_InstantSnapshotGroups_SetIamPolicy_async + */ + setIamPolicy( + request?: protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest|undefined, {}|undefined + ]>; + setIamPolicy( + request: protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + setIamPolicy( + request: protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + setIamPolicy( + request?: protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('setIamPolicy request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('setIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.setIamPolicy(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyInstantSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('setIamPolicy response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Returns permissions that a caller has on the specified resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.resource + * Name or id of the resource for this request. + * @param {google.cloud.compute.v1beta.TestPermissionsRequest} request.testPermissionsRequestResource + * The body resource for this request + * @param {string} request.zone + * The name of the zone for this request. + * @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.cloud.compute.v1beta.TestPermissionsResponse|TestPermissionsResponse}. + * 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/v1beta/instant_snapshot_groups.test_iam_permissions.js + * region_tag:compute_v1beta_generated_InstantSnapshotGroups_TestIamPermissions_async + */ + testIamPermissions( + request?: protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest|undefined, {}|undefined + ]>; + testIamPermissions( + request: protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + testIamPermissions( + request: protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + testIamPermissions( + request?: protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('testIamPermissions request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('testIamPermissions response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.testIamPermissions(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsInstantSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('testIamPermissions response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + /** + * retrieves the list of InstantSnapshotGroup resources contained within + * the specified zone. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.zone + * The name of the zone for this request. + * @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 Array of {@link protos.google.cloud.compute.v1beta.InstantSnapshotGroup|InstantSnapshotGroup}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + list( + request?: protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[], + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups + ]>; + list( + request: protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>): void; + list( + request: protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>): void; + list( + request?: protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>, + callback?: PaginationCallback< + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>): + Promise<[ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[], + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('list values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('list request %j', request); + return this.innerApiCalls + .list(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[], + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups + ]) => { + this._log.info('list values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `list`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.zone + * The name of the zone for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.compute.v1beta.InstantSnapshotGroup|InstantSnapshotGroup} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listStream( + request?: protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + }); + const defaultCallSettings = this._defaults['list']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('list stream %j', request); + return this.descriptors.page.list.createStream( + this.innerApiCalls.list as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `list`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.zone + * The name of the zone for this request. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.compute.v1beta.InstantSnapshotGroup|InstantSnapshotGroup}. The API will be called under the hood as needed, once per the page, + * 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/v1beta/instant_snapshot_groups.list.js + * region_tag:compute_v1beta_generated_InstantSnapshotGroups_List_async + */ + listAsync( + request?: protos.google.cloud.compute.v1beta.IListInstantSnapshotGroupsRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + }); + const defaultCallSettings = this._defaults['list']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('list iterate %j', request); + return this.descriptors.page.list.asyncIterate( + this.innerApiCalls['list'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.instantSnapshotGroupsStub && !this._terminated) { + return this.instantSnapshotGroupsStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_client_config.json b/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_client_config.json new file mode 100644 index 00000000000..ee5731b4fc6 --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_client_config.json @@ -0,0 +1,54 @@ +{ + "interfaces": { + "google.cloud.compute.v1beta.InstantSnapshotGroups": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "Delete": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Get": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Insert": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "List": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "SetIamPolicy": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "TestIamPermissions": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_proto_list.json b/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_proto_list.json new file mode 100644 index 00000000000..ecbfc90443e --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/instant_snapshot_groups_proto_list.json @@ -0,0 +1,3 @@ +[ + "../../protos/google/cloud/compute/v1beta/compute.proto" +] diff --git a/packages/google-cloud-compute/src/v1beta/network_endpoint_groups_client.ts b/packages/google-cloud-compute/src/v1beta/network_endpoint_groups_client.ts index 00560512983..8bbf2aa3de5 100644 --- a/packages/google-cloud-compute/src/v1beta/network_endpoint_groups_client.ts +++ b/packages/google-cloud-compute/src/v1beta/network_endpoint_groups_client.ts @@ -804,6 +804,20 @@ export class NetworkEndpointGroupsClient { * Creates a network endpoint group in the specified project using the * parameters that are included in the request. * + * Note: Use the following APIs to manage network endpoint groups: + * + * - + * To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity + * NEGs): zonal + * API + * - + * To manage NEGs with regional scope (such as regional internet NEGs, + * serverless NEGs, Private Service Connect NEGs): regional + * API + * - + * To manage NEGs with global scope (such as global internet NEGs):global + * API + * * @param {Object} request * The request object that will be sent. * @param {google.cloud.compute.v1beta.NetworkEndpointGroup} request.networkEndpointGroupResource diff --git a/packages/google-cloud-compute/src/v1beta/region_disks_client.ts b/packages/google-cloud-compute/src/v1beta/region_disks_client.ts index 25c5c35d569..c7d221907d4 100644 --- a/packages/google-cloud-compute/src/v1beta/region_disks_client.ts +++ b/packages/google-cloud-compute/src/v1beta/region_disks_client.ts @@ -2060,8 +2060,7 @@ export class RegionDisksClient { } /** * Update the specified disk with the data included in the request. Update is - * performed only on selected fields included as part of update-mask. Only the - * following fields can be modified: user_license. + * performed only on selected fields included as part of update-mask. * * @param {Object} request * The request object that will be sent. diff --git a/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_client.ts b/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_client.ts new file mode 100644 index 00000000000..bf85d9ea71d --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_client.ts @@ -0,0 +1,1447 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1beta/region_instant_snapshot_groups_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './region_instant_snapshot_groups_client_config.json'; +const version = require('../../../package.json').version; + +/** + * The RegionInstantSnapshotGroups API. + * @class + * @memberof v1beta + */ +export class RegionInstantSnapshotGroupsClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('compute'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + regionInstantSnapshotGroupsStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of RegionInstantSnapshotGroupsClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new RegionInstantSnapshotGroupsClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof RegionInstantSnapshotGroupsClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'compute.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + // Implicitly enable HTTP transport for the APIs that use REST as transport (e.g. Google Cloud Compute). + if (!opts) { + opts = {fallback: true}; + } else { + opts.fallback = opts.fallback ?? true; + } + const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + + // 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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + list: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items') + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.compute.v1beta.RegionInstantSnapshotGroups', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.regionInstantSnapshotGroupsStub) { + return this.regionInstantSnapshotGroupsStub; + } + + // Put together the "service stub" for + // google.cloud.compute.v1beta.RegionInstantSnapshotGroups. + this.regionInstantSnapshotGroupsStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.compute.v1beta.RegionInstantSnapshotGroups') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.compute.v1beta.RegionInstantSnapshotGroups, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const regionInstantSnapshotGroupsStubMethods = + ['delete', 'get', 'getIamPolicy', 'insert', 'list', 'setIamPolicy', 'testIamPermissions']; + for (const methodName of regionInstantSnapshotGroupsStubMethods) { + const callPromise = this.regionInstantSnapshotGroupsStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + this.descriptors.page[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.regionInstantSnapshotGroupsStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'compute.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'compute.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/compute', + 'https://www.googleapis.com/auth/cloud-platform' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * deletes a Regional InstantSnapshotGroup resource + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.instantSnapshotGroup + * Name of the InstantSnapshotGroup resource to delete. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * The name of the region for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/region_instant_snapshot_groups.delete.js + * region_tag:compute_v1beta_generated_RegionInstantSnapshotGroups_Delete_async + */ + delete( + request?: protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + delete( + request: protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + delete( + request: protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + delete( + request?: protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'instant_snapshot_group': request.instantSnapshotGroup ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('delete request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('delete response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.delete(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * returns the specified InstantSnapshotGroup resource in the specified + * region. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.instantSnapshotGroup + * Name of the InstantSnapshotGroup resource to return. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * The name of the region for this request. + * @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.cloud.compute.v1beta.InstantSnapshotGroup|InstantSnapshotGroup}. + * 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/v1beta/region_instant_snapshot_groups.get.js + * region_tag:compute_v1beta_generated_RegionInstantSnapshotGroups_Get_async + */ + get( + request?: protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest|undefined, {}|undefined + ]>; + get( + request: protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + get( + request: protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + get( + request?: protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'instant_snapshot_group': request.instantSnapshotGroup ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('get request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('get response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.get(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup, + protos.google.cloud.compute.v1beta.IGetRegionInstantSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('get response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Gets the access control policy for a resource. May be empty if no such + * policy or resource exists. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.optionsRequestedPolicyVersion + * Requested IAM Policy version. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * The name of the region for this request. + * @param {string} request.resource + * Name or id of the resource for this request. + * @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.cloud.compute.v1beta.Policy|Policy}. + * 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/v1beta/region_instant_snapshot_groups.get_iam_policy.js + * region_tag:compute_v1beta_generated_RegionInstantSnapshotGroups_GetIamPolicy_async + */ + getIamPolicy( + request?: protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest|undefined, {}|undefined + ]>; + getIamPolicy( + request: protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + getIamPolicy( + request: protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + getIamPolicy( + request?: protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getIamPolicy request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getIamPolicy(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicyRegionInstantSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * creates a Regional InstantSnapshotGroup resource + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.compute.v1beta.InstantSnapshotGroup} request.instantSnapshotGroupResource + * The body resource for this request + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {string} request.sourceConsistencyGroup + * begin_interface: MixerMutationRequestBuilder + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/region_instant_snapshot_groups.insert.js + * region_tag:compute_v1beta_generated_RegionInstantSnapshotGroups_Insert_async + */ + insert( + request?: protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + insert( + request: protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + insert( + request: protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + insert( + request?: protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('insert request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('insert response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.insert(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Sets the access control policy on the specified resource. + * Replaces any existing policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * The name of the region for this request. + * @param {google.cloud.compute.v1beta.RegionSetPolicyRequest} request.regionSetPolicyRequestResource + * The body resource for this request + * @param {string} request.resource + * Name or id of the resource for this request. + * @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.cloud.compute.v1beta.Policy|Policy}. + * 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/v1beta/region_instant_snapshot_groups.set_iam_policy.js + * region_tag:compute_v1beta_generated_RegionInstantSnapshotGroups_SetIamPolicy_async + */ + setIamPolicy( + request?: protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest|undefined, {}|undefined + ]>; + setIamPolicy( + request: protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + setIamPolicy( + request: protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + setIamPolicy( + request?: protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('setIamPolicy request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('setIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.setIamPolicy(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicyRegionInstantSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('setIamPolicy response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Returns permissions that a caller has on the specified resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * The name of the region for this request. + * @param {string} request.resource + * Name or id of the resource for this request. + * @param {google.cloud.compute.v1beta.TestPermissionsRequest} request.testPermissionsRequestResource + * The body resource for this request + * @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.cloud.compute.v1beta.TestPermissionsResponse|TestPermissionsResponse}. + * 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/v1beta/region_instant_snapshot_groups.test_iam_permissions.js + * region_tag:compute_v1beta_generated_RegionInstantSnapshotGroups_TestIamPermissions_async + */ + testIamPermissions( + request?: protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest|undefined, {}|undefined + ]>; + testIamPermissions( + request: protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + testIamPermissions( + request: protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + testIamPermissions( + request?: protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('testIamPermissions request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('testIamPermissions response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.testIamPermissions(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsRegionInstantSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('testIamPermissions response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + /** + * retrieves the list of InstantSnapshotGroup resources contained within + * the specified region. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * The name of the region for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @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 Array of {@link protos.google.cloud.compute.v1beta.InstantSnapshotGroup|InstantSnapshotGroup}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + list( + request?: protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[], + protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups + ]>; + list( + request: protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>): void; + list( + request: protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>): void; + list( + request?: protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>, + callback?: PaginationCallback< + protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>): + Promise<[ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[], + protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('list values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('list request %j', request); + return this.innerApiCalls + .list(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[], + protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListInstantSnapshotGroups + ]) => { + this._log.info('list values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `list`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * The name of the region for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.compute.v1beta.InstantSnapshotGroup|InstantSnapshotGroup} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listStream( + request?: protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + }); + const defaultCallSettings = this._defaults['list']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('list stream %j', request); + return this.descriptors.page.list.createStream( + this.innerApiCalls.list as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `list`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * The name of the region for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.compute.v1beta.InstantSnapshotGroup|InstantSnapshotGroup}. The API will be called under the hood as needed, once per the page, + * 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/v1beta/region_instant_snapshot_groups.list.js + * region_tag:compute_v1beta_generated_RegionInstantSnapshotGroups_List_async + */ + listAsync( + request?: protos.google.cloud.compute.v1beta.IListRegionInstantSnapshotGroupsRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + }); + const defaultCallSettings = this._defaults['list']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('list iterate %j', request); + return this.descriptors.page.list.asyncIterate( + this.innerApiCalls['list'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.regionInstantSnapshotGroupsStub && !this._terminated) { + return this.regionInstantSnapshotGroupsStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_client_config.json b/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_client_config.json new file mode 100644 index 00000000000..4cb576c1146 --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_client_config.json @@ -0,0 +1,54 @@ +{ + "interfaces": { + "google.cloud.compute.v1beta.RegionInstantSnapshotGroups": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "Delete": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Get": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Insert": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "List": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "SetIamPolicy": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "TestIamPermissions": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_proto_list.json b/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_proto_list.json new file mode 100644 index 00000000000..ecbfc90443e --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/region_instant_snapshot_groups_proto_list.json @@ -0,0 +1,3 @@ +[ + "../../protos/google/cloud/compute/v1beta/compute.proto" +] diff --git a/packages/google-cloud-compute/src/v1beta/region_network_endpoint_groups_client.ts b/packages/google-cloud-compute/src/v1beta/region_network_endpoint_groups_client.ts index c3ce5629d5f..e240f3349c9 100644 --- a/packages/google-cloud-compute/src/v1beta/region_network_endpoint_groups_client.ts +++ b/packages/google-cloud-compute/src/v1beta/region_network_endpoint_groups_client.ts @@ -802,6 +802,20 @@ export class RegionNetworkEndpointGroupsClient { * Creates a network endpoint group in the specified project using the * parameters that are included in the request. * + * Note: Use the following APIs to manage network endpoint groups: + * + * - + * To manage NEGs with zonal scope (such as zonal NEGs, hybrid connectivity + * NEGs): zonal + * API + * - + * To manage NEGs with regional scope (such as regional internet NEGs, + * serverless NEGs, Private Service Connect NEGs): regional + * API + * - + * To manage NEGs with global scope (such as global internet NEGs):global + * API + * * @param {Object} request * The request object that will be sent. * @param {google.cloud.compute.v1beta.NetworkEndpointGroup} request.networkEndpointGroupResource diff --git a/packages/google-cloud-compute/src/v1beta/reservation_slots_client.ts b/packages/google-cloud-compute/src/v1beta/reservation_slots_client.ts new file mode 100644 index 00000000000..5b9d0c212b0 --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/reservation_slots_client.ts @@ -0,0 +1,1028 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1beta/reservation_slots_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './reservation_slots_client_config.json'; +const version = require('../../../package.json').version; + +/** + * The ReservationSlots API. + * @class + * @memberof v1beta + */ +export class ReservationSlotsClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('compute'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + reservationSlotsStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of ReservationSlotsClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new ReservationSlotsClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof ReservationSlotsClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'compute.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + // Implicitly enable HTTP transport for the APIs that use REST as transport (e.g. Google Cloud Compute). + if (!opts) { + opts = {fallback: true}; + } else { + opts.fallback = opts.fallback ?? true; + } + const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + + // 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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + list: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items') + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.compute.v1beta.ReservationSlots', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.reservationSlotsStub) { + return this.reservationSlotsStub; + } + + // Put together the "service stub" for + // google.cloud.compute.v1beta.ReservationSlots. + this.reservationSlotsStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.compute.v1beta.ReservationSlots') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.compute.v1beta.ReservationSlots, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const reservationSlotsStubMethods = + ['get', 'list', 'update']; + for (const methodName of reservationSlotsStubMethods) { + const callPromise = this.reservationSlotsStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + this.descriptors.page[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.reservationSlotsStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'compute.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'compute.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/compute', + 'https://www.googleapis.com/auth/cloud-platform' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * Retrieves information about the specified reservation slot. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parentName + * The name of the parent reservation and parent block, formatted as + * reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} + * @param {string} request.project + * The project ID for this request. + * @param {string} request.reservationSlot + * The name of the reservation slot, formatted as RFC1035 or a resource ID + * number. + * @param {string} request.zone + * The name of the zone for this request, formatted as RFC1035. + * @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.cloud.compute.v1beta.ReservationSlotsGetResponse|ReservationSlotsGetResponse}. + * 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/v1beta/reservation_slots.get.js + * region_tag:compute_v1beta_generated_ReservationSlots_Get_async + */ + get( + request?: protos.google.cloud.compute.v1beta.IGetReservationSlotRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse, + protos.google.cloud.compute.v1beta.IGetReservationSlotRequest|undefined, {}|undefined + ]>; + get( + request: protos.google.cloud.compute.v1beta.IGetReservationSlotRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse, + protos.google.cloud.compute.v1beta.IGetReservationSlotRequest|null|undefined, + {}|null|undefined>): void; + get( + request: protos.google.cloud.compute.v1beta.IGetReservationSlotRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse, + protos.google.cloud.compute.v1beta.IGetReservationSlotRequest|null|undefined, + {}|null|undefined>): void; + get( + request?: protos.google.cloud.compute.v1beta.IGetReservationSlotRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse, + protos.google.cloud.compute.v1beta.IGetReservationSlotRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse, + protos.google.cloud.compute.v1beta.IGetReservationSlotRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse, + protos.google.cloud.compute.v1beta.IGetReservationSlotRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'parent_name': request.parentName ?? '', + 'reservation_slot': request.reservationSlot ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('get request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse, + protos.google.cloud.compute.v1beta.IGetReservationSlotRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('get response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.get(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse, + protos.google.cloud.compute.v1beta.IGetReservationSlotRequest|undefined, + {}|undefined + ]) => { + this._log.info('get response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Update a reservation slot in the specified sub-block. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parentName + * The name of the sub-block resource. + * @param {string} request.project + * The project ID for this request. + * @param {string} request.reservationSlot + * The name of the slot resource. + * @param {google.cloud.compute.v1beta.ReservationSlot} request.reservationSlotResource + * The body resource for this request + * @param {string} request.updateMask + * The fields to be updated as part of this request. + * @param {string} request.zone + * The name of the zone for this request, formatted as RFC1035. + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/reservation_slots.update.js + * region_tag:compute_v1beta_generated_ReservationSlots_Update_async + */ + update( + request?: protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + update( + request: protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest|null|undefined, + {}|null|undefined>): void; + update( + request: protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest|null|undefined, + {}|null|undefined>): void; + update( + request?: protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'parent_name': request.parentName ?? '', + 'reservation_slot': request.reservationSlot ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('update request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateReservationSlotRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('update response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.update(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + /** + * Retrieves a list of reservation slots under a single reservation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.parentName + * The name of the parent reservation and parent block, formatted as + * reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} + * @param {string} request.project + * The project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.zone + * The name of the zone for this request, formatted as RFC1035. + * @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 Array of {@link protos.google.cloud.compute.v1beta.ReservationSlot|ReservationSlot}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + list( + request?: protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IReservationSlot[], + protos.google.cloud.compute.v1beta.IListReservationSlotsRequest|null, + protos.google.cloud.compute.v1beta.IReservationSlotsListResponse + ]>; + list( + request: protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + protos.google.cloud.compute.v1beta.IReservationSlotsListResponse|null|undefined, + protos.google.cloud.compute.v1beta.IReservationSlot>): void; + list( + request: protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + protos.google.cloud.compute.v1beta.IReservationSlotsListResponse|null|undefined, + protos.google.cloud.compute.v1beta.IReservationSlot>): void; + list( + request?: protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + protos.google.cloud.compute.v1beta.IReservationSlotsListResponse|null|undefined, + protos.google.cloud.compute.v1beta.IReservationSlot>, + callback?: PaginationCallback< + protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + protos.google.cloud.compute.v1beta.IReservationSlotsListResponse|null|undefined, + protos.google.cloud.compute.v1beta.IReservationSlot>): + Promise<[ + protos.google.cloud.compute.v1beta.IReservationSlot[], + protos.google.cloud.compute.v1beta.IListReservationSlotsRequest|null, + protos.google.cloud.compute.v1beta.IReservationSlotsListResponse + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'parent_name': request.parentName ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + protos.google.cloud.compute.v1beta.IReservationSlotsListResponse|null|undefined, + protos.google.cloud.compute.v1beta.IReservationSlot>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('list values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('list request %j', request); + return this.innerApiCalls + .list(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.cloud.compute.v1beta.IReservationSlot[], + protos.google.cloud.compute.v1beta.IListReservationSlotsRequest|null, + protos.google.cloud.compute.v1beta.IReservationSlotsListResponse + ]) => { + this._log.info('list values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `list`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.parentName + * The name of the parent reservation and parent block, formatted as + * reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} + * @param {string} request.project + * The project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.zone + * The name of the zone for this request, formatted as RFC1035. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.compute.v1beta.ReservationSlot|ReservationSlot} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listStream( + request?: protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'parent_name': request.parentName ?? '', + }); + const defaultCallSettings = this._defaults['list']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('list stream %j', request); + return this.descriptors.page.list.createStream( + this.innerApiCalls.list as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `list`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.parentName + * The name of the parent reservation and parent block, formatted as + * reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} + * @param {string} request.project + * The project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.zone + * The name of the zone for this request, formatted as RFC1035. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.compute.v1beta.ReservationSlot|ReservationSlot}. The API will be called under the hood as needed, once per the page, + * 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/v1beta/reservation_slots.list.js + * region_tag:compute_v1beta_generated_ReservationSlots_List_async + */ + listAsync( + request?: protos.google.cloud.compute.v1beta.IListReservationSlotsRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'zone': request.zone ?? '', + 'parent_name': request.parentName ?? '', + }); + const defaultCallSettings = this._defaults['list']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('list iterate %j', request); + return this.descriptors.page.list.asyncIterate( + this.innerApiCalls['list'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.reservationSlotsStub && !this._terminated) { + return this.reservationSlotsStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-cloud-compute/src/v1beta/reservation_slots_client_config.json b/packages/google-cloud-compute/src/v1beta/reservation_slots_client_config.json new file mode 100644 index 00000000000..a7abd5c1bc4 --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/reservation_slots_client_config.json @@ -0,0 +1,38 @@ +{ + "interfaces": { + "google.cloud.compute.v1beta.ReservationSlots": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "Get": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "List": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Update": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-cloud-compute/src/v1beta/reservation_slots_proto_list.json b/packages/google-cloud-compute/src/v1beta/reservation_slots_proto_list.json new file mode 100644 index 00000000000..ecbfc90443e --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/reservation_slots_proto_list.json @@ -0,0 +1,3 @@ +[ + "../../protos/google/cloud/compute/v1beta/compute.proto" +] diff --git a/packages/google-cloud-compute/src/v1beta/routers_client.ts b/packages/google-cloud-compute/src/v1beta/routers_client.ts index 5f46ab04a9b..886638d2a2e 100644 --- a/packages/google-cloud-compute/src/v1beta/routers_client.ts +++ b/packages/google-cloud-compute/src/v1beta/routers_client.ts @@ -184,6 +184,8 @@ export class RoutersClient { new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items'), listBgpRoutes: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'result'), + listNamedSets: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'result'), listRoutePolicies: new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'result') }; @@ -231,7 +233,7 @@ export class RoutersClient { // Iterate over each of the methods that the service provides // and create an API call method for each. const routersStubMethods = - ['aggregatedList', 'delete', 'deleteRoutePolicy', 'get', 'getNatIpInfo', 'getNatMappingInfo', 'getRoutePolicy', 'getRouterStatus', 'insert', 'list', 'listBgpRoutes', 'listRoutePolicies', 'patch', 'patchRoutePolicy', 'preview', 'testIamPermissions', 'update', 'updateRoutePolicy']; + ['aggregatedList', 'delete', 'deleteNamedSet', 'deleteRoutePolicy', 'get', 'getNamedSet', 'getNatIpInfo', 'getNatMappingInfo', 'getRoutePolicy', 'getRouterStatus', 'insert', 'list', 'listBgpRoutes', 'listNamedSets', 'listRoutePolicies', 'patch', 'patchNamedSet', 'patchRoutePolicy', 'preview', 'testIamPermissions', 'update', 'updateNamedSet', 'updateRoutePolicy']; for (const methodName of routersStubMethods) { const callPromise = this.routersStub.then( stub => (...args: Array<{}>) => { @@ -453,6 +455,126 @@ export class RoutersClient { throw error; }); } +/** + * Deletes Named Set + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.namedSet + * The Named Set name for this request. Name must conform to RFC1035 + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {string} request.router + * Name of the Router resource where Named Set is defined. + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/routers.delete_named_set.js + * region_tag:compute_v1beta_generated_Routers_DeleteNamedSet_async + */ + deleteNamedSet( + request?: protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + deleteNamedSet( + request: protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest|null|undefined, + {}|null|undefined>): void; + deleteNamedSet( + request: protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest|null|undefined, + {}|null|undefined>): void; + deleteNamedSet( + request?: protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'router': request.router ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('deleteNamedSet request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteNamedSetRouterRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('deleteNamedSet response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.deleteNamedSet(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } /** * Deletes Route Policy * @@ -673,6 +795,109 @@ export class RoutersClient { throw error; }); } +/** + * Returns specified Named Set + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.namedSet + * The Named Set name for this request. Name must conform to RFC1035 + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.router + * Name of the Router resource to query for the named set. The name should + * conform to RFC1035. + * @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.cloud.compute.v1beta.RoutersGetNamedSetResponse|RoutersGetNamedSetResponse}. + * 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/v1beta/routers.get_named_set.js + * region_tag:compute_v1beta_generated_Routers_GetNamedSet_async + */ + getNamedSet( + request?: protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, + protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest|undefined, {}|undefined + ]>; + getNamedSet( + request: protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, + protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest|null|undefined, + {}|null|undefined>): void; + getNamedSet( + request: protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, + protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest|null|undefined, + {}|null|undefined>): void; + getNamedSet( + request?: protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, + protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, + protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, + protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'router': request.router ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getNamedSet request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, + protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getNamedSet response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getNamedSet(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse, + protos.google.cloud.compute.v1beta.IGetNamedSetRouterRequest|undefined, + {}|undefined + ]) => { + this._log.info('getNamedSet response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } /** * Retrieves runtime NAT IP information. * @@ -1223,10 +1448,12 @@ export class RoutersClient { }); } /** - * Patches Route Policy + * Patches Named Set * * @param {Object} request * The request object that will be sent. + * @param {google.cloud.compute.v1beta.NamedSet} request.namedSetResource + * The body resource for this request * @param {string} request.project * Project ID for this request. * @param {string} request.region @@ -1245,10 +1472,8 @@ export class RoutersClient { * The request ID must be * a valid UUID with the exception that zero UUID is not supported * (00000000-0000-0000-0000-000000000000). - * @param {google.cloud.compute.v1beta.RoutePolicy} request.routePolicyResource - * The body resource for this request * @param {string} request.router - * Name of the Router resource where Route Policy is defined. + * Name of the Router resource where Named Set is defined. * @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. @@ -1260,38 +1485,38 @@ export class RoutersClient { * stable it is still a work-in-progress and under active development, * and might get backwards-incompatible changes at any time. * `.promise()` is not supported yet. - * @example include:samples/generated/v1beta/routers.patch_route_policy.js - * region_tag:compute_v1beta_generated_Routers_PatchRoutePolicy_async + * @example include:samples/generated/v1beta/routers.patch_named_set.js + * region_tag:compute_v1beta_generated_Routers_PatchNamedSet_async */ - patchRoutePolicy( - request?: protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest, + patchNamedSet( + request?: protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest, options?: CallOptions): Promise<[ LROperation, protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined ]>; - patchRoutePolicy( - request: protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest, + patchNamedSet( + request: protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest, options: CallOptions, callback: Callback< protos.google.cloud.compute.v1beta.IOperation, - protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, + protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest|null|undefined, {}|null|undefined>): void; - patchRoutePolicy( - request: protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest, + patchNamedSet( + request: protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest, callback: Callback< protos.google.cloud.compute.v1beta.IOperation, - protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, + protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest|null|undefined, {}|null|undefined>): void; - patchRoutePolicy( - request?: protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest, + patchNamedSet( + request?: protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest, optionsOrCallback?: CallOptions|Callback< protos.google.cloud.compute.v1beta.IOperation, - protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, + protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest|null|undefined, {}|null|undefined>, callback?: Callback< protos.google.cloud.compute.v1beta.IOperation, - protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, + protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest|null|undefined, {}|null|undefined>): Promise<[ LROperation, @@ -1317,17 +1542,17 @@ export class RoutersClient { 'router': request.router ?? '', }); this.initialize().catch(err => {throw err}); - this._log.info('patchRoutePolicy request %j', request); + this._log.info('patchNamedSet request %j', request); const wrappedCallback: Callback< protos.google.cloud.compute.v1beta.IOperation, - protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, + protos.google.cloud.compute.v1beta.IPatchNamedSetRouterRequest|null|undefined, {}|null|undefined>|undefined = callback ? (error, response, nextRequest, rawResponse) => { - this._log.info('patchRoutePolicy response %j', rawResponse); + this._log.info('patchNamedSet response %j', rawResponse); callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. } : undefined; - return this.innerApiCalls.patchRoutePolicy(request, options, wrappedCallback) + return this.innerApiCalls.patchNamedSet(request, options, wrappedCallback) ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { return [ { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, @@ -1343,8 +1568,7 @@ export class RoutersClient { }); } /** - * Preview fields auto-generated during router create andupdate operations. - * Calling this method does NOT create or update the router. + * Patches Route Policy * * @param {Object} request * The request object that will be sent. @@ -1352,44 +1576,165 @@ export class RoutersClient { * Project ID for this request. * @param {string} request.region * Name of the region for this request. - * @param {string} request.router - * Name of the Router resource to query. - * @param {google.cloud.compute.v1beta.Router} request.routerResource + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {google.cloud.compute.v1beta.RoutePolicy} request.routePolicyResource * The body resource for this request + * @param {string} request.router + * Name of the Router resource where Route Policy is defined. * @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.cloud.compute.v1beta.RoutersPreviewResponse|RoutersPreviewResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * The first element of the array is an object representing + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. - * @example include:samples/generated/v1beta/routers.preview.js - * region_tag:compute_v1beta_generated_Routers_Preview_async + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/routers.patch_route_policy.js + * region_tag:compute_v1beta_generated_Routers_PatchRoutePolicy_async */ - preview( - request?: protos.google.cloud.compute.v1beta.IPreviewRouterRequest, + patchRoutePolicy( + request?: protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest, options?: CallOptions): Promise<[ - protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, - protos.google.cloud.compute.v1beta.IPreviewRouterRequest|undefined, {}|undefined + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined ]>; - preview( - request: protos.google.cloud.compute.v1beta.IPreviewRouterRequest, + patchRoutePolicy( + request: protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest, options: CallOptions, callback: Callback< - protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, - protos.google.cloud.compute.v1beta.IPreviewRouterRequest|null|undefined, + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, {}|null|undefined>): void; - preview( - request: protos.google.cloud.compute.v1beta.IPreviewRouterRequest, + patchRoutePolicy( + request: protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest, callback: Callback< - protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, - protos.google.cloud.compute.v1beta.IPreviewRouterRequest|null|undefined, + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, {}|null|undefined>): void; - preview( - request?: protos.google.cloud.compute.v1beta.IPreviewRouterRequest, + patchRoutePolicy( + request?: protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest, optionsOrCallback?: CallOptions|Callback< - protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, - protos.google.cloud.compute.v1beta.IPreviewRouterRequest|null|undefined, + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'router': request.router ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('patchRoutePolicy request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IPatchRoutePolicyRouterRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('patchRoutePolicy response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.patchRoutePolicy(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Preview fields auto-generated during router create andupdate operations. + * Calling this method does NOT create or update the router. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.router + * Name of the Router resource to query. + * @param {google.cloud.compute.v1beta.Router} request.routerResource + * The body resource for this request + * @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.cloud.compute.v1beta.RoutersPreviewResponse|RoutersPreviewResponse}. + * 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/v1beta/routers.preview.js + * region_tag:compute_v1beta_generated_Routers_Preview_async + */ + preview( + request?: protos.google.cloud.compute.v1beta.IPreviewRouterRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, + protos.google.cloud.compute.v1beta.IPreviewRouterRequest|undefined, {}|undefined + ]>; + preview( + request: protos.google.cloud.compute.v1beta.IPreviewRouterRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, + protos.google.cloud.compute.v1beta.IPreviewRouterRequest|null|undefined, + {}|null|undefined>): void; + preview( + request: protos.google.cloud.compute.v1beta.IPreviewRouterRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, + protos.google.cloud.compute.v1beta.IPreviewRouterRequest|null|undefined, + {}|null|undefined>): void; + preview( + request?: protos.google.cloud.compute.v1beta.IPreviewRouterRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, + protos.google.cloud.compute.v1beta.IPreviewRouterRequest|null|undefined, {}|null|undefined>, callback?: Callback< protos.google.cloud.compute.v1beta.IRoutersPreviewResponse, @@ -1670,6 +2015,126 @@ export class RoutersClient { throw error; }); } +/** + * Updates or creates new Named Set + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.compute.v1beta.NamedSet} request.namedSetResource + * The body resource for this request + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {string} request.router + * Name of the Router resource where Named Set is defined. + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/routers.update_named_set.js + * region_tag:compute_v1beta_generated_Routers_UpdateNamedSet_async + */ + updateNamedSet( + request?: protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + updateNamedSet( + request: protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest|null|undefined, + {}|null|undefined>): void; + updateNamedSet( + request: protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest|null|undefined, + {}|null|undefined>): void; + updateNamedSet( + request?: protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'router': request.router ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('updateNamedSet request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IUpdateNamedSetRouterRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('updateNamedSet response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.updateNamedSet(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } /** * Updates or creates new Route Policy * @@ -3375,6 +3840,471 @@ export class RoutersClient { ) as AsyncIterable; } /** + * Retrieves a list of router named set subresources available to the + * specified project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.router + * Name or id of the resource for this request. + * Name should conform to RFC1035. + * @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 Array of {@link protos.google.cloud.compute.v1beta.NamedSet|NamedSet}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listNamedSetsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listNamedSets( + request?: protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.INamedSet[], + protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest|null, + protos.google.cloud.compute.v1beta.IRoutersListNamedSets + ]>; + listNamedSets( + request: protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + protos.google.cloud.compute.v1beta.IRoutersListNamedSets|null|undefined, + protos.google.cloud.compute.v1beta.INamedSet>): void; + listNamedSets( + request: protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + protos.google.cloud.compute.v1beta.IRoutersListNamedSets|null|undefined, + protos.google.cloud.compute.v1beta.INamedSet>): void; + listNamedSets( + request?: protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + protos.google.cloud.compute.v1beta.IRoutersListNamedSets|null|undefined, + protos.google.cloud.compute.v1beta.INamedSet>, + callback?: PaginationCallback< + protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + protos.google.cloud.compute.v1beta.IRoutersListNamedSets|null|undefined, + protos.google.cloud.compute.v1beta.INamedSet>): + Promise<[ + protos.google.cloud.compute.v1beta.INamedSet[], + protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest|null, + protos.google.cloud.compute.v1beta.IRoutersListNamedSets + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'router': request.router ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + protos.google.cloud.compute.v1beta.IRoutersListNamedSets|null|undefined, + protos.google.cloud.compute.v1beta.INamedSet>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listNamedSets values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listNamedSets request %j', request); + return this.innerApiCalls + .listNamedSets(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.cloud.compute.v1beta.INamedSet[], + protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest|null, + protos.google.cloud.compute.v1beta.IRoutersListNamedSets + ]) => { + this._log.info('listNamedSets values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `listNamedSets`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.router + * Name or id of the resource for this request. + * Name should conform to RFC1035. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.compute.v1beta.NamedSet|NamedSet} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listNamedSetsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listNamedSetsStream( + request?: protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'router': request.router ?? '', + }); + const defaultCallSettings = this._defaults['listNamedSets']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listNamedSets stream %j', request); + return this.descriptors.page.listNamedSets.createStream( + this.innerApiCalls.listNamedSets as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `listNamedSets`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.region + * Name of the region for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {string} request.router + * Name or id of the resource for this request. + * Name should conform to RFC1035. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.compute.v1beta.NamedSet|NamedSet}. The API will be called under the hood as needed, once per the page, + * 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/v1beta/routers.list_named_sets.js + * region_tag:compute_v1beta_generated_Routers_ListNamedSets_async + */ + listNamedSetsAsync( + request?: protos.google.cloud.compute.v1beta.IListNamedSetsRoutersRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'region': request.region ?? '', + 'router': request.router ?? '', + }); + const defaultCallSettings = this._defaults['listNamedSets']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('listNamedSets iterate %j', request); + return this.descriptors.page.listNamedSets.asyncIterate( + this.innerApiCalls['listNamedSets'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + /** * Retrieves a list of router route policy subresources available to the * specified project. * diff --git a/packages/google-cloud-compute/src/v1beta/routers_client_config.json b/packages/google-cloud-compute/src/v1beta/routers_client_config.json index 3ac157122a2..b36b83ccdef 100644 --- a/packages/google-cloud-compute/src/v1beta/routers_client_config.json +++ b/packages/google-cloud-compute/src/v1beta/routers_client_config.json @@ -28,6 +28,10 @@ "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, + "DeleteNamedSet": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, "DeleteRoutePolicy": { "retry_codes_name": "non_idempotent", "retry_params_name": "default" @@ -36,6 +40,10 @@ "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, + "GetNamedSet": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, "GetNatIpInfo": { "retry_codes_name": "non_idempotent", "retry_params_name": "default" @@ -64,6 +72,10 @@ "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, + "ListNamedSets": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, "ListRoutePolicies": { "retry_codes_name": "non_idempotent", "retry_params_name": "default" @@ -72,6 +84,10 @@ "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, + "PatchNamedSet": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, "PatchRoutePolicy": { "retry_codes_name": "non_idempotent", "retry_params_name": "default" @@ -88,6 +104,10 @@ "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, + "UpdateNamedSet": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, "UpdateRoutePolicy": { "retry_codes_name": "non_idempotent", "retry_params_name": "default" diff --git a/packages/google-cloud-compute/src/v1beta/snapshot_groups_client.ts b/packages/google-cloud-compute/src/v1beta/snapshot_groups_client.ts new file mode 100644 index 00000000000..49e556b13b7 --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/snapshot_groups_client.ts @@ -0,0 +1,1418 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; +import {Transform} from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1beta/snapshot_groups_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './snapshot_groups_client_config.json'; +const version = require('../../../package.json').version; + +/** + * The SnapshotGroups API. + * @class + * @memberof v1beta + */ +export class SnapshotGroupsClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('compute'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: {[name: string]: Function}; + snapshotGroupsStub?: Promise<{[name: string]: Function}>; + + /** + * Construct an instance of SnapshotGroupsClient. + * + * @param {object} [options] - The configuration object. + * The options accepted by the constructor are described in detail + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new SnapshotGroupsClient({fallback: true}, gax); + * ``` + */ + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof SnapshotGroupsClient; + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); + } + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + this._servicePath = 'compute.' + this._universeDomain; + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const port = opts?.port || staticMembers.port; + const clientConfig = opts?.clientConfig ?? {}; + // Implicitly enable HTTP transport for the APIs that use REST as transport (e.g. Google Cloud Compute). + if (!opts) { + opts = {fallback: true}; + } else { + opts.fallback = opts.fallback ?? true; + } + const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + + // 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; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // Some of the methods on this service return "paged" results, + // (e.g. 50 results at a time, with tokens to get subsequent + // pages). Denote the keys used for pagination and results. + this.descriptors.page = { + list: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'items') + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.compute.v1beta.SnapshotGroups', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + + // Set up a dictionary of "inner API calls"; the core implementation + // of calling the API is handled in `google-gax`, with this code + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.snapshotGroupsStub) { + return this.snapshotGroupsStub; + } + + // Put together the "service stub" for + // google.cloud.compute.v1beta.SnapshotGroups. + this.snapshotGroupsStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.compute.v1beta.SnapshotGroups') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.compute.v1beta.SnapshotGroups, + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + + // Iterate over each of the methods that the service provides + // and create an API call method for each. + const snapshotGroupsStubMethods = + ['delete', 'get', 'getIamPolicy', 'insert', 'list', 'setIamPolicy', 'testIamPermissions']; + for (const methodName of snapshotGroupsStubMethods) { + const callPromise = this.snapshotGroupsStub.then( + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { + throw err; + }); + + const descriptor = + this.descriptors.page[methodName] || + undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.snapshotGroupsStub; + } + + /** + * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get servicePath() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'compute.googleapis.com'; + } + + /** + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. + * @returns {string} The DNS address for this service. + */ + static get apiEndpoint() { + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + } + return 'compute.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/compute', + 'https://www.googleapis.com/auth/cloud-platform' + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * Return the project ID used by this class. + * @returns {Promise} A promise that resolves to string containing the project ID. + */ + getProjectId(callback?: Callback): + Promise|void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- +/** + * Deletes the specified SnapshotGroup resource + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {string} request.snapshotGroup + * Name of the SnapshotGroup resource to delete. + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/snapshot_groups.delete.js + * region_tag:compute_v1beta_generated_SnapshotGroups_Delete_async + */ + delete( + request?: protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + delete( + request: protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + delete( + request: protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + delete( + request?: protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'snapshot_group': request.snapshotGroup ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('delete request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IDeleteSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('delete response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.delete(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * returns the specified SnapshotGroup resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.snapshotGroup + * Name of the SnapshotGroup resource to return. + * @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.cloud.compute.v1beta.SnapshotGroup|SnapshotGroup}. + * 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/v1beta/snapshot_groups.get.js + * region_tag:compute_v1beta_generated_SnapshotGroups_Get_async + */ + get( + request?: protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.ISnapshotGroup, + protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest|undefined, {}|undefined + ]>; + get( + request: protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.ISnapshotGroup, + protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + get( + request: protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.ISnapshotGroup, + protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + get( + request?: protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.ISnapshotGroup, + protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.ISnapshotGroup, + protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.ISnapshotGroup, + protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'snapshot_group': request.snapshotGroup ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('get request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.ISnapshotGroup, + protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('get response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.get(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.ISnapshotGroup, + protos.google.cloud.compute.v1beta.IGetSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('get response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Gets the access control policy for a resource. May be empty if no such + * policy or resource exists. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.optionsRequestedPolicyVersion + * Requested IAM Policy version. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.resource + * Name or id of the resource for this request. + * @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.cloud.compute.v1beta.Policy|Policy}. + * 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/v1beta/snapshot_groups.get_iam_policy.js + * region_tag:compute_v1beta_generated_SnapshotGroups_GetIamPolicy_async + */ + getIamPolicy( + request?: protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest|undefined, {}|undefined + ]>; + getIamPolicy( + request: protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + getIamPolicy( + request: protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + getIamPolicy( + request?: protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getIamPolicy request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getIamPolicy(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.IGetIamPolicySnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('getIamPolicy response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Creates a snapshot group in the specified project using the data included + * in the request. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.requestId + * An optional request ID to identify requests. Specify a unique request ID so + * that if you must retry your request, the server will know to ignore the + * request if it has already been completed. + * + * For example, consider a situation where you make an initial request and + * the request times out. If you make the request again with the same + * request ID, the server can check if original operation with the same + * request ID was received, and if so, will ignore the second request. This + * prevents clients from accidentally creating duplicate commitments. + * + * The request ID must be + * a valid UUID with the exception that zero UUID is not supported + * (00000000-0000-0000-0000-000000000000). + * @param {google.cloud.compute.v1beta.SnapshotGroup} request.snapshotGroupResource + * The body resource for this request + * @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 + * a long running operation. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * This method is considered to be in beta. This means while + * stable it is still a work-in-progress and under active development, + * and might get backwards-incompatible changes at any time. + * `.promise()` is not supported yet. + * @example include:samples/generated/v1beta/snapshot_groups.insert.js + * region_tag:compute_v1beta_generated_SnapshotGroups_Insert_async + */ + insert( + request?: protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>; + insert( + request: protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + insert( + request: protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + insert( + request?: protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.cloud.compute.v1beta.IOperation|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('insert request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IOperation, + protos.google.cloud.compute.v1beta.IInsertSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, nextRequest, rawResponse) => { + this._log.info('insert response %j', rawResponse); + callback!(error, response, nextRequest, rawResponse); // We verified `callback` above. + } + : undefined; + return this.innerApiCalls.insert(request, options, wrappedCallback) + ?.then(([response, operation, rawResponse]: [protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation, protos.google.cloud.compute.v1.IOperation]) => { + return [ + { latestResponse: response, done: false, name: response.id, metadata: null, result: {}}, + operation, + rawResponse + ]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Sets the access control policy on the specified resource. + * Replaces any existing policy. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.cloud.compute.v1beta.GlobalSetPolicyRequest} request.globalSetPolicyRequestResource + * The body resource for this request + * @param {string} request.project + * Project ID for this request. + * @param {string} request.resource + * Name or id of the resource for this request. + * @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.cloud.compute.v1beta.Policy|Policy}. + * 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/v1beta/snapshot_groups.set_iam_policy.js + * region_tag:compute_v1beta_generated_SnapshotGroups_SetIamPolicy_async + */ + setIamPolicy( + request?: protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest|undefined, {}|undefined + ]>; + setIamPolicy( + request: protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + setIamPolicy( + request: protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + setIamPolicy( + request?: protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('setIamPolicy request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('setIamPolicy response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.setIamPolicy(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.IPolicy, + protos.google.cloud.compute.v1beta.ISetIamPolicySnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('setIamPolicy response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } +/** + * Returns permissions that a caller has on the specified resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.project + * Project ID for this request. + * @param {string} request.resource + * Name or id of the resource for this request. + * @param {google.cloud.compute.v1beta.TestPermissionsRequest} request.testPermissionsRequestResource + * The body resource for this request + * @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.cloud.compute.v1beta.TestPermissionsResponse|TestPermissionsResponse}. + * 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/v1beta/snapshot_groups.test_iam_permissions.js + * region_tag:compute_v1beta_generated_SnapshotGroups_TestIamPermissions_async + */ + testIamPermissions( + request?: protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest|undefined, {}|undefined + ]>; + testIamPermissions( + request: protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + testIamPermissions( + request: protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest, + callback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest|null|undefined, + {}|null|undefined>): void; + testIamPermissions( + request?: protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + 'resource': request.resource ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('testIamPermissions request %j', request); + const wrappedCallback: Callback< + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('testIamPermissions response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.testIamPermissions(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.cloud.compute.v1beta.ITestPermissionsResponse, + protos.google.cloud.compute.v1beta.ITestIamPermissionsSnapshotGroupRequest|undefined, + {}|undefined + ]) => { + this._log.info('testIamPermissions response %j', response); + return [response, options, rawResponse]; + }).catch((error: any) => { + if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { + const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + } + throw error; + }); + } + + /** + * retrieves the list of SnapshotGroup resources contained within + * the specified project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @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 Array of {@link protos.google.cloud.compute.v1beta.SnapshotGroup|SnapshotGroup}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + list( + request?: protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + options?: CallOptions): + Promise<[ + protos.google.cloud.compute.v1beta.ISnapshotGroup[], + protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListSnapshotGroups + ]>; + list( + request: protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.ISnapshotGroup>): void; + list( + request: protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + callback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.ISnapshotGroup>): void; + list( + request?: protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + optionsOrCallback?: CallOptions|PaginationCallback< + protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.ISnapshotGroup>, + callback?: PaginationCallback< + protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.ISnapshotGroup>): + Promise<[ + protos.google.cloud.compute.v1beta.ISnapshotGroup[], + protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListSnapshotGroups + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + protos.google.cloud.compute.v1beta.IListSnapshotGroups|null|undefined, + protos.google.cloud.compute.v1beta.ISnapshotGroup>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('list values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('list request %j', request); + return this.innerApiCalls + .list(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.cloud.compute.v1beta.ISnapshotGroup[], + protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest|null, + protos.google.cloud.compute.v1beta.IListSnapshotGroups + ]) => { + this._log.info('list values %j', response); + return [response, input, output]; + }); + } + +/** + * Equivalent to `list`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.cloud.compute.v1beta.SnapshotGroup|SnapshotGroup} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ + listStream( + request?: protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + options?: CallOptions): + Transform{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + }); + const defaultCallSettings = this._defaults['list']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('list stream %j', request); + return this.descriptors.page.list.createStream( + this.innerApiCalls.list as GaxCall, + request, + callSettings + ); + } + +/** + * Equivalent to `list`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * A filter expression that filters resources listed in the response. Most + * Compute resources support two types of filter expressions: + * expressions that support regular expressions and expressions that follow + * API improvement proposal AIP-160. + * These two types of filter expressions cannot be mixed in one request. + * + * If you want to use AIP-160, your expression must specify the field name, an + * operator, and the value that you want to use for filtering. The value + * must be a string, a number, or a boolean. The operator + * must be either `=`, `!=`, `>`, `<`, `<=`, `>=` or `:`. + * + * For example, if you are filtering Compute Engine instances, you can + * exclude instances named `example-instance` by specifying + * `name != example-instance`. + * + * The `:*` comparison can be used to test whether a key has been defined. + * For example, to find all objects with `owner` label use: + * ``` + * labels.owner:* + * ``` + * + * You can also filter nested fields. For example, you could specify + * `scheduling.automaticRestart = false` to include instances only + * if they are not scheduled for automatic restarts. You can use filtering + * on nested fields to filter based onresource labels. + * + * To filter on multiple expressions, provide each separate expression within + * parentheses. For example: + * ``` + * (scheduling.automaticRestart = true) + * (cpuPlatform = "Intel Skylake") + * ``` + * By default, each expression is an `AND` expression. However, you + * can include `AND` and `OR` expressions explicitly. + * For example: + * ``` + * (cpuPlatform = "Intel Skylake") OR + * (cpuPlatform = "Intel Broadwell") AND + * (scheduling.automaticRestart = true) + * ``` + * + * If you want to use a regular expression, use the `eq` (equal) or `ne` + * (not equal) operator against a single un-parenthesized expression with or + * without quotes or against multiple parenthesized expressions. Examples: + * + * `fieldname eq unquoted literal` + * `fieldname eq 'single quoted literal'` + * `fieldname eq "double quoted literal"` + * `(fieldname1 eq literal) (fieldname2 ne "literal")` + * + * The literal value is interpreted as a regular expression using GoogleRE2 library syntax. + * The literal value must match the entire field. + * + * For example, to filter for instances that do not end with name "instance", + * you would use `name ne .*instance`. + * + * You cannot combine constraints on multiple fields using regular + * expressions. + * @param {number} request.maxResults + * The maximum number of results per page that should be returned. + * If the number of available results is larger than `maxResults`, + * Compute Engine returns a `nextPageToken` that can be used to get + * the next page of results in subsequent list requests. Acceptable values are + * `0` to `500`, inclusive. (Default: `500`) + * @param {string} request.orderBy + * Sorts list results by a certain order. By default, results + * are returned in alphanumerical order based on the resource name. + * + * You can also sort results in descending order based on the creation + * timestamp using `orderBy="creationTimestamp desc"`. This sorts + * results based on the `creationTimestamp` field in + * reverse chronological order (newest result first). Use this to sort + * resources like operations so that the newest operation is returned first. + * + * Currently, only sorting by `name` or + * `creationTimestamp desc` is supported. + * @param {string} request.pageToken + * Specifies a page token to use. Set `pageToken` to the + * `nextPageToken` returned by a previous list request to get + * the next page of results. + * @param {string} request.project + * Project ID for this request. + * @param {boolean} request.returnPartialSuccess + * Opt-in for partial success behavior which provides partial results in case + * of failure. The default value is false. + * + * For example, when partial success behavior is enabled, aggregatedList for a + * single zone scope either returns all resources in the zone or no resources, + * with an error code. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.cloud.compute.v1beta.SnapshotGroup|SnapshotGroup}. The API will be called under the hood as needed, once per the page, + * 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/v1beta/snapshot_groups.list.js + * region_tag:compute_v1beta_generated_SnapshotGroups_List_async + */ + listAsync( + request?: protos.google.cloud.compute.v1beta.IListSnapshotGroupsRequest, + options?: CallOptions): + AsyncIterable{ + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'project': request.project ?? '', + }); + const defaultCallSettings = this._defaults['list']; + const callSettings = defaultCallSettings.merge(options); + this.initialize().catch(err => {throw err}); + this._log.info('list iterate %j', request); + return this.descriptors.page.list.asyncIterate( + this.innerApiCalls['list'] as GaxCall, + request as {}, + callSettings + ) as AsyncIterable; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.snapshotGroupsStub && !this._terminated) { + return this.snapshotGroupsStub.then(stub => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} \ No newline at end of file diff --git a/packages/google-cloud-compute/src/v1beta/snapshot_groups_client_config.json b/packages/google-cloud-compute/src/v1beta/snapshot_groups_client_config.json new file mode 100644 index 00000000000..ee300b17d88 --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/snapshot_groups_client_config.json @@ -0,0 +1,54 @@ +{ + "interfaces": { + "google.cloud.compute.v1beta.SnapshotGroups": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "Delete": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Get": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Insert": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "List": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "SetIamPolicy": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "TestIamPermissions": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/packages/google-cloud-compute/src/v1beta/snapshot_groups_proto_list.json b/packages/google-cloud-compute/src/v1beta/snapshot_groups_proto_list.json new file mode 100644 index 00000000000..ecbfc90443e --- /dev/null +++ b/packages/google-cloud-compute/src/v1beta/snapshot_groups_proto_list.json @@ -0,0 +1,3 @@ +[ + "../../protos/google/cloud/compute/v1beta/compute.proto" +] diff --git a/packages/google-cloud-compute/test/gapic_instance_group_managers_v1beta.ts b/packages/google-cloud-compute/test/gapic_instance_group_managers_v1beta.ts index 695a6456e17..4c8ca7ebe59 100644 --- a/packages/google-cloud-compute/test/gapic_instance_group_managers_v1beta.ts +++ b/packages/google-cloud-compute/test/gapic_instance_group_managers_v1beta.ts @@ -534,6 +534,138 @@ describe('v1beta.InstanceGroupManagersClient', () => { }); }); + describe('configureAcceleratorTopologies', () => { + it('invokes configureAcceleratorTopologies without error', async () => { + const client = new instancegroupmanagersModule.v1beta.InstanceGroupManagersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['instanceGroupManager']); + request.instanceGroupManager = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instance_group_manager=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.configureAcceleratorTopologies = stubSimpleCall(expectedResponse); + const [response] = await client.configureAcceleratorTopologies(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.configureAcceleratorTopologies as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.configureAcceleratorTopologies as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes configureAcceleratorTopologies without error using callback', async () => { + const client = new instancegroupmanagersModule.v1beta.InstanceGroupManagersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['instanceGroupManager']); + request.instanceGroupManager = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instance_group_manager=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.configureAcceleratorTopologies = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.configureAcceleratorTopologies( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.configureAcceleratorTopologies as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.configureAcceleratorTopologies as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes configureAcceleratorTopologies with error', async () => { + const client = new instancegroupmanagersModule.v1beta.InstanceGroupManagersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['instanceGroupManager']); + request.instanceGroupManager = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instance_group_manager=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.configureAcceleratorTopologies = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.configureAcceleratorTopologies(request), expectedError); + const actualRequest = (client.innerApiCalls.configureAcceleratorTopologies as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.configureAcceleratorTopologies as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes configureAcceleratorTopologies with closed client', async () => { + const client = new instancegroupmanagersModule.v1beta.InstanceGroupManagersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ConfigureAcceleratorTopologiesInstanceGroupManagerRequest', ['instanceGroupManager']); + request.instanceGroupManager = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.configureAcceleratorTopologies(request), expectedError); + }); + }); + describe('createInstances', () => { it('invokes createInstances without error', async () => { const client = new instancegroupmanagersModule.v1beta.InstanceGroupManagersClient({ diff --git a/packages/google-cloud-compute/test/gapic_instant_snapshot_groups_v1beta.ts b/packages/google-cloud-compute/test/gapic_instant_snapshot_groups_v1beta.ts new file mode 100644 index 00000000000..62ce7231a2c --- /dev/null +++ b/packages/google-cloud-compute/test/gapic_instant_snapshot_groups_v1beta.ts @@ -0,0 +1,1318 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it, beforeEach, afterEach} from 'mocha'; +import * as instantsnapshotgroupsModule from '../src'; + +import {PassThrough} from 'stream'; + +import {GoogleAuth, protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1beta.InstantSnapshotGroupsClient', () => { + let googleAuth: GoogleAuth; + beforeEach(() => { + googleAuth = { + getClient: sinon.stub().resolves({ + getRequestHeaders: sinon.stub().resolves({Authorization: 'Bearer SOME_TOKEN'}), + }) + } as unknown as GoogleAuth; + }); + afterEach(() => { + sinon.restore(); + }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient.servicePath; + assert.strictEqual(servicePath, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.instantSnapshotGroupsStub, undefined); + await client.initialize(); + assert(client.instantSnapshotGroupsStub); + }); + + it('has close method for the initialized client', done => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.instantSnapshotGroupsStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.instantSnapshotGroupsStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('delete', () => { + it('invokes delete without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.delete = stubSimpleCall(expectedResponse); + const [response] = await client.delete(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete without error using callback', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.delete = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.delete( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.delete(request), expectedError); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete with closed client', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.delete(request), expectedError); + }); + }); + + describe('get', () => { + it('invokes get without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InstantSnapshotGroup() + ); + client.innerApiCalls.get = stubSimpleCall(expectedResponse); + const [response] = await client.get(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get without error using callback', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InstantSnapshotGroup() + ); + client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.get( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IInstantSnapshotGroup|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.get(request), expectedError); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get with closed client', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.get(request), expectedError); + }); + }); + + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy without error using callback', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IPolicy|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with closed client', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getIamPolicy(request), expectedError); + }); + }); + + describe('insert', () => { + it('invokes insert without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.insert = stubSimpleCall(expectedResponse); + const [response] = await client.insert(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert without error using callback', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.insert = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insert( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.insert(request), expectedError); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert with closed client', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.insert(request), expectedError); + }); + }); + + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.setIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy without error using callback', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.setIamPolicy = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setIamPolicy( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IPolicy|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.setIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.setIamPolicy(request), expectedError); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with closed client', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.setIamPolicy(request), expectedError); + }); + }); + + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestPermissionsResponse() + ); + client.innerApiCalls.testIamPermissions = stubSimpleCall(expectedResponse); + const [response] = await client.testIamPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions without error using callback', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestPermissionsResponse() + ); + client.innerApiCalls.testIamPermissions = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.testIamPermissions( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.ITestPermissionsResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.testIamPermissions = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.testIamPermissions(request), expectedError); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with closed client', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.testIamPermissions(request), expectedError); + }); + }); + + describe('list', () => { + it('invokes list without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + ]; + client.innerApiCalls.list = stubSimpleCall(expectedResponse); + const [response] = await client.list(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list without error using callback', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + ]; + client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.list( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.list(request), expectedError); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listStream without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + ]; + client.descriptors.page.list.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.InstantSnapshotGroup[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.InstantSnapshotGroup) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.list.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.list, request)); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listStream with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.list.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.InstantSnapshotGroup[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.InstantSnapshotGroup) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.list.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.list, request)); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with list without error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + ]; + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[] = []; + const iterable = client.listAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with list with error', async () => { + const client = new instantsnapshotgroupsModule.v1beta.InstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListInstantSnapshotGroupsRequest', ['zone']); + request.zone = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); +}); diff --git a/packages/google-cloud-compute/test/gapic_region_instant_snapshot_groups_v1beta.ts b/packages/google-cloud-compute/test/gapic_region_instant_snapshot_groups_v1beta.ts new file mode 100644 index 00000000000..e1ff2091c33 --- /dev/null +++ b/packages/google-cloud-compute/test/gapic_region_instant_snapshot_groups_v1beta.ts @@ -0,0 +1,1318 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it, beforeEach, afterEach} from 'mocha'; +import * as regioninstantsnapshotgroupsModule from '../src'; + +import {PassThrough} from 'stream'; + +import {GoogleAuth, protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1beta.RegionInstantSnapshotGroupsClient', () => { + let googleAuth: GoogleAuth; + beforeEach(() => { + googleAuth = { + getClient: sinon.stub().resolves({ + getRequestHeaders: sinon.stub().resolves({Authorization: 'Bearer SOME_TOKEN'}), + }) + } as unknown as GoogleAuth; + }); + afterEach(() => { + sinon.restore(); + }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient.servicePath; + assert.strictEqual(servicePath, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.regionInstantSnapshotGroupsStub, undefined); + await client.initialize(); + assert(client.regionInstantSnapshotGroupsStub); + }); + + it('has close method for the initialized client', done => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.regionInstantSnapshotGroupsStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.regionInstantSnapshotGroupsStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('delete', () => { + it('invokes delete without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.delete = stubSimpleCall(expectedResponse); + const [response] = await client.delete(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete without error using callback', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.delete = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.delete( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.delete(request), expectedError); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete with closed client', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteRegionInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.delete(request), expectedError); + }); + }); + + describe('get', () => { + it('invokes get without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InstantSnapshotGroup() + ); + client.innerApiCalls.get = stubSimpleCall(expectedResponse); + const [response] = await client.get(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get without error using callback', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InstantSnapshotGroup() + ); + client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.get( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IInstantSnapshotGroup|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&instant_snapshot_group=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.get(request), expectedError); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get with closed client', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetRegionInstantSnapshotGroupRequest', ['instantSnapshotGroup']); + request.instantSnapshotGroup = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.get(request), expectedError); + }); + }); + + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy without error using callback', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IPolicy|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with closed client', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicyRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getIamPolicy(request), expectedError); + }); + }); + + describe('insert', () => { + it('invokes insert without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.insert = stubSimpleCall(expectedResponse); + const [response] = await client.insert(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert without error using callback', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.insert = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insert( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.insert(request), expectedError); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert with closed client', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.insert(request), expectedError); + }); + }); + + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.setIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy without error using callback', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.setIamPolicy = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setIamPolicy( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IPolicy|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.setIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.setIamPolicy(request), expectedError); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with closed client', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicyRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.setIamPolicy(request), expectedError); + }); + }); + + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestPermissionsResponse() + ); + client.innerApiCalls.testIamPermissions = stubSimpleCall(expectedResponse); + const [response] = await client.testIamPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions without error using callback', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestPermissionsResponse() + ); + client.innerApiCalls.testIamPermissions = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.testIamPermissions( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.ITestPermissionsResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&resource=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.testIamPermissions = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.testIamPermissions(request), expectedError); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with closed client', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRegionInstantSnapshotGroupRequest', ['resource']); + request.resource = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.testIamPermissions(request), expectedError); + }); + }); + + describe('list', () => { + it('invokes list without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + ]; + client.innerApiCalls.list = stubSimpleCall(expectedResponse); + const [response] = await client.list(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list without error using callback', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + ]; + client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.list( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.list(request), expectedError); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listStream without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + ]; + client.descriptors.page.list.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.InstantSnapshotGroup[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.InstantSnapshotGroup) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.list.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.list, request)); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listStream with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.list.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.InstantSnapshotGroup[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.InstantSnapshotGroup) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.list.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.list, request)); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with list without error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.InstantSnapshotGroup()), + ]; + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[] = []; + const iterable = client.listAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with list with error', async () => { + const client = new regioninstantsnapshotgroupsModule.v1beta.RegionInstantSnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListRegionInstantSnapshotGroupsRequest', ['region']); + request.region = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.compute.v1beta.IInstantSnapshotGroup[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); +}); diff --git a/packages/google-cloud-compute/test/gapic_reservation_slots_v1beta.ts b/packages/google-cloud-compute/test/gapic_reservation_slots_v1beta.ts new file mode 100644 index 00000000000..38e72d2470a --- /dev/null +++ b/packages/google-cloud-compute/test/gapic_reservation_slots_v1beta.ts @@ -0,0 +1,847 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it, beforeEach, afterEach} from 'mocha'; +import * as reservationslotsModule from '../src'; + +import {PassThrough} from 'stream'; + +import {GoogleAuth, protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1beta.ReservationSlotsClient', () => { + let googleAuth: GoogleAuth; + beforeEach(() => { + googleAuth = { + getClient: sinon.stub().resolves({ + getRequestHeaders: sinon.stub().resolves({Authorization: 'Bearer SOME_TOKEN'}), + }) + } as unknown as GoogleAuth; + }); + afterEach(() => { + sinon.restore(); + }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = reservationslotsModule.v1beta.ReservationSlotsClient.servicePath; + assert.strictEqual(servicePath, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = reservationslotsModule.v1beta.ReservationSlotsClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new reservationslotsModule.v1beta.ReservationSlotsClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new reservationslotsModule.v1beta.ReservationSlotsClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = reservationslotsModule.v1beta.ReservationSlotsClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.reservationSlotsStub, undefined); + await client.initialize(); + assert(client.reservationSlotsStub); + }); + + it('has close method for the initialized client', done => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.reservationSlotsStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.reservationSlotsStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('get', () => { + it('invokes get without error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetReservationSlotRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['parentName']); + request.parentName = defaultValue3; + const defaultValue4 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['reservationSlot']); + request.reservationSlot = defaultValue4; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }&reservation_slot=${defaultValue4 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ReservationSlotsGetResponse() + ); + client.innerApiCalls.get = stubSimpleCall(expectedResponse); + const [response] = await client.get(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get without error using callback', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetReservationSlotRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['parentName']); + request.parentName = defaultValue3; + const defaultValue4 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['reservationSlot']); + request.reservationSlot = defaultValue4; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }&reservation_slot=${defaultValue4 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ReservationSlotsGetResponse() + ); + client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.get( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IReservationSlotsGetResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get with error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetReservationSlotRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['parentName']); + request.parentName = defaultValue3; + const defaultValue4 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['reservationSlot']); + request.reservationSlot = defaultValue4; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }&reservation_slot=${defaultValue4 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.get(request), expectedError); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get with closed client', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetReservationSlotRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['parentName']); + request.parentName = defaultValue3; + const defaultValue4 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetReservationSlotRequest', ['reservationSlot']); + request.reservationSlot = defaultValue4; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.get(request), expectedError); + }); + }); + + describe('update', () => { + it('invokes update without error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.UpdateReservationSlotRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['parentName']); + request.parentName = defaultValue3; + const defaultValue4 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['reservationSlot']); + request.reservationSlot = defaultValue4; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }&reservation_slot=${defaultValue4 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.update = stubSimpleCall(expectedResponse); + const [response] = await client.update(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes update without error using callback', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.UpdateReservationSlotRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['parentName']); + request.parentName = defaultValue3; + const defaultValue4 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['reservationSlot']); + request.reservationSlot = defaultValue4; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }&reservation_slot=${defaultValue4 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.update = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.update( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes update with error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.UpdateReservationSlotRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['parentName']); + request.parentName = defaultValue3; + const defaultValue4 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['reservationSlot']); + request.reservationSlot = defaultValue4; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }&reservation_slot=${defaultValue4 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.update = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.update(request), expectedError); + const actualRequest = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes update with closed client', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.UpdateReservationSlotRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['parentName']); + request.parentName = defaultValue3; + const defaultValue4 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateReservationSlotRequest', ['reservationSlot']); + request.reservationSlot = defaultValue4; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.update(request), expectedError); + }); + }); + + describe('list', () => { + it('invokes list without error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListReservationSlotsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['parentName']); + request.parentName = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + ]; + client.innerApiCalls.list = stubSimpleCall(expectedResponse); + const [response] = await client.list(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list without error using callback', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListReservationSlotsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['parentName']); + request.parentName = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + ]; + client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.list( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IReservationSlot[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list with error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListReservationSlotsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['parentName']); + request.parentName = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.list(request), expectedError); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listStream without error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListReservationSlotsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['parentName']); + request.parentName = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + ]; + client.descriptors.page.list.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.ReservationSlot[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.ReservationSlot) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.list.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.list, request)); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listStream with error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListReservationSlotsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['parentName']); + request.parentName = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.list.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.ReservationSlot[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.ReservationSlot) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.list.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.list, request)); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with list without error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListReservationSlotsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['parentName']); + request.parentName = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.ReservationSlot()), + ]; + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.compute.v1beta.IReservationSlot[] = []; + const iterable = client.listAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with list with error', async () => { + const client = new reservationslotsModule.v1beta.ReservationSlotsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListReservationSlotsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['zone']); + request.zone = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListReservationSlotsRequest', ['parentName']); + request.parentName = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&zone=${defaultValue2 ?? '' }&parent_name=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.compute.v1beta.IReservationSlot[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); +}); diff --git a/packages/google-cloud-compute/test/gapic_routers_v1beta.ts b/packages/google-cloud-compute/test/gapic_routers_v1beta.ts index 96faeef9b80..2e01b7f1260 100644 --- a/packages/google-cloud-compute/test/gapic_routers_v1beta.ts +++ b/packages/google-cloud-compute/test/gapic_routers_v1beta.ts @@ -402,6 +402,138 @@ describe('v1beta.RoutersClient', () => { }); }); + describe('deleteNamedSet', () => { + it('invokes deleteNamedSet without error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.deleteNamedSet = stubSimpleCall(expectedResponse); + const [response] = await client.deleteNamedSet(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteNamedSet without error using callback', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.deleteNamedSet = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteNamedSet( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteNamedSet with error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteNamedSet = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteNamedSet(request), expectedError); + const actualRequest = (client.innerApiCalls.deleteNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteNamedSet with closed client', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.deleteNamedSet(request), expectedError); + }); + }); + describe('deleteRoutePolicy', () => { it('invokes deleteRoutePolicy without error', async () => { const client = new routersModule.v1beta.RoutersClient({ @@ -666,6 +798,138 @@ describe('v1beta.RoutersClient', () => { }); }); + describe('getNamedSet', () => { + it('invokes getNamedSet without error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.RoutersGetNamedSetResponse() + ); + client.innerApiCalls.getNamedSet = stubSimpleCall(expectedResponse); + const [response] = await client.getNamedSet(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getNamedSet without error using callback', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.RoutersGetNamedSetResponse() + ); + client.innerApiCalls.getNamedSet = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getNamedSet( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IRoutersGetNamedSetResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getNamedSet with error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getNamedSet = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getNamedSet(request), expectedError); + const actualRequest = (client.innerApiCalls.getNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getNamedSet with closed client', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getNamedSet(request), expectedError); + }); + }); + describe('getNatIpInfo', () => { it('invokes getNatIpInfo without error', async () => { const client = new routersModule.v1beta.RoutersClient({ @@ -1314,6 +1578,138 @@ describe('v1beta.RoutersClient', () => { }); }); + describe('patchNamedSet', () => { + it('invokes patchNamedSet without error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.PatchNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.patchNamedSet = stubSimpleCall(expectedResponse); + const [response] = await client.patchNamedSet(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.patchNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.patchNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes patchNamedSet without error using callback', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.PatchNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.patchNamedSet = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.patchNamedSet( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.patchNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.patchNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes patchNamedSet with error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.PatchNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.patchNamedSet = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.patchNamedSet(request), expectedError); + const actualRequest = (client.innerApiCalls.patchNamedSet as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.patchNamedSet as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes patchNamedSet with closed client', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.PatchNamedSetRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.PatchNamedSetRouterRequest', ['router']); + request.router = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.patchNamedSet(request), expectedError); + }); + }); + describe('patchRoutePolicy', () => { it('invokes patchRoutePolicy without error', async () => { const client = new routersModule.v1beta.RoutersClient({ @@ -1681,94 +2077,226 @@ describe('v1beta.RoutersClient', () => { const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) .getCall(0).args[0]; assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with closed client', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRouterRequest', ['resource']); + request.resource = defaultValue3; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.testIamPermissions(request), expectedError); + }); + }); + + describe('update', () => { + it('invokes update without error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.UpdateRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.update = stubSimpleCall(expectedResponse); + const [response] = await client.update(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes update without error using callback', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.UpdateRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.update = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.update( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes update with error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.UpdateRouterRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.update = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.update(request), expectedError); + const actualRequest = (client.innerApiCalls.update as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - it('invokes testIamPermissions with closed client', async () => { + it('invokes update with closed client', async () => { const client = new routersModule.v1beta.RoutersClient({ auth: googleAuth, projectId: 'bogus', }); await client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.compute.v1beta.TestIamPermissionsRouterRequest() + new protos.google.cloud.compute.v1beta.UpdateRouterRequest() ); const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRouterRequest', ['project']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['project']); request.project = defaultValue1; const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRouterRequest', ['region']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['region']); request.region = defaultValue2; const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsRouterRequest', ['resource']); - request.resource = defaultValue3; + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['router']); + request.router = defaultValue3; const expectedError = new Error('The client has already been closed.'); client.close().catch(err => {throw err}); - await assert.rejects(client.testIamPermissions(request), expectedError); + await assert.rejects(client.update(request), expectedError); }); }); - describe('update', () => { - it('invokes update without error', async () => { + describe('updateNamedSet', () => { + it('invokes updateNamedSet without error', async () => { const client = new routersModule.v1beta.RoutersClient({ auth: googleAuth, projectId: 'bogus', }); await client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.compute.v1beta.UpdateRouterRequest() + new protos.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest() ); const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['project']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['project']); request.project = defaultValue1; const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['region']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['region']); request.region = defaultValue2; const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['router']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['router']); request.router = defaultValue3; const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1beta.Operation() ); - client.innerApiCalls.update = stubSimpleCall(expectedResponse); - const [response] = await client.update(request); + client.innerApiCalls.updateNamedSet = stubSimpleCall(expectedResponse); + const [response] = await client.updateNamedSet(request); assert.deepStrictEqual(response.latestResponse, expectedResponse); - const actualRequest = (client.innerApiCalls.update as SinonStub) + const actualRequest = (client.innerApiCalls.updateNamedSet as SinonStub) .getCall(0).args[0]; assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) + const actualHeaderRequestParams = (client.innerApiCalls.updateNamedSet as SinonStub) .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - it('invokes update without error using callback', async () => { + it('invokes updateNamedSet without error using callback', async () => { const client = new routersModule.v1beta.RoutersClient({ auth: googleAuth, projectId: 'bogus', }); await client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.compute.v1beta.UpdateRouterRequest() + new protos.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest() ); const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['project']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['project']); request.project = defaultValue1; const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['region']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['region']); request.region = defaultValue2; const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['router']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['router']); request.router = defaultValue3; const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; const expectedResponse = generateSampleMessage( new protos.google.cloud.compute.v1beta.Operation() ); - client.innerApiCalls.update = stubSimpleCallWithCallback(expectedResponse); + client.innerApiCalls.updateNamedSet = stubSimpleCallWithCallback(expectedResponse); const promise = new Promise((resolve, reject) => { - client.update( + client.updateNamedSet( request, (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { if (err) { @@ -1780,65 +2308,65 @@ describe('v1beta.RoutersClient', () => { }); const response = await promise; assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.update as SinonStub) + const actualRequest = (client.innerApiCalls.updateNamedSet as SinonStub) .getCall(0).args[0]; assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) + const actualHeaderRequestParams = (client.innerApiCalls.updateNamedSet as SinonStub) .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - it('invokes update with error', async () => { + it('invokes updateNamedSet with error', async () => { const client = new routersModule.v1beta.RoutersClient({ auth: googleAuth, projectId: 'bogus', }); await client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.compute.v1beta.UpdateRouterRequest() + new protos.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest() ); const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['project']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['project']); request.project = defaultValue1; const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['region']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['region']); request.region = defaultValue2; const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['router']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['router']); request.router = defaultValue3; const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; const expectedError = new Error('expected'); - client.innerApiCalls.update = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.update(request), expectedError); - const actualRequest = (client.innerApiCalls.update as SinonStub) + client.innerApiCalls.updateNamedSet = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.updateNamedSet(request), expectedError); + const actualRequest = (client.innerApiCalls.updateNamedSet as SinonStub) .getCall(0).args[0]; assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.update as SinonStub) + const actualHeaderRequestParams = (client.innerApiCalls.updateNamedSet as SinonStub) .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - it('invokes update with closed client', async () => { + it('invokes updateNamedSet with closed client', async () => { const client = new routersModule.v1beta.RoutersClient({ auth: googleAuth, projectId: 'bogus', }); await client.initialize(); const request = generateSampleMessage( - new protos.google.cloud.compute.v1beta.UpdateRouterRequest() + new protos.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest() ); const defaultValue1 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['project']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['project']); request.project = defaultValue1; const defaultValue2 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['region']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['region']); request.region = defaultValue2; const defaultValue3 = - getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateRouterRequest', ['router']); + getTypeDefaultValue('.google.cloud.compute.v1beta.UpdateNamedSetRouterRequest', ['router']); request.router = defaultValue3; const expectedError = new Error('The client has already been closed.'); client.close().catch(err => {throw err}); - await assert.rejects(client.update(request), expectedError); + await assert.rejects(client.updateNamedSet(request), expectedError); }); }); @@ -2886,6 +3414,293 @@ describe('v1beta.RoutersClient', () => { }); }); + describe('listNamedSets', () => { + it('invokes listNamedSets without error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + ]; + client.innerApiCalls.listNamedSets = stubSimpleCall(expectedResponse); + const [response] = await client.listNamedSets(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listNamedSets as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listNamedSets as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listNamedSets without error using callback', async () => { + const client = new routersModule.v1beta.RoutersClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + ]; + client.innerApiCalls.listNamedSets = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listNamedSets( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.INamedSet[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listNamedSets as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listNamedSets as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listNamedSets with error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listNamedSets = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listNamedSets(request), expectedError); + const actualRequest = (client.innerApiCalls.listNamedSets as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listNamedSets as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listNamedSetsStream without error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + ]; + client.descriptors.page.listNamedSets.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listNamedSetsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.NamedSet[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.NamedSet) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listNamedSets.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listNamedSets, request)); + assert( + (client.descriptors.page.listNamedSets.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listNamedSetsStream with error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listNamedSets.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listNamedSetsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.NamedSet[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.NamedSet) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listNamedSets.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listNamedSets, request)); + assert( + (client.descriptors.page.listNamedSets.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listNamedSets without error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.NamedSet()), + ]; + client.descriptors.page.listNamedSets.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.compute.v1beta.INamedSet[] = []; + const iterable = client.listNamedSetsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listNamedSets.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listNamedSets.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listNamedSets with error', async () => { + const client = new routersModule.v1beta.RoutersClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['region']); + request.region = defaultValue2; + const defaultValue3 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListNamedSetsRoutersRequest', ['router']); + request.router = defaultValue3; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }®ion=${defaultValue2 ?? '' }&router=${defaultValue3 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listNamedSets.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listNamedSetsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.compute.v1beta.INamedSet[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listNamedSets.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listNamedSets.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); + describe('listRoutePolicies', () => { it('invokes listRoutePolicies without error', async () => { const client = new routersModule.v1beta.RoutersClient({ diff --git a/packages/google-cloud-compute/test/gapic_snapshot_groups_v1beta.ts b/packages/google-cloud-compute/test/gapic_snapshot_groups_v1beta.ts new file mode 100644 index 00000000000..86b98cfb716 --- /dev/null +++ b/packages/google-cloud-compute/test/gapic_snapshot_groups_v1beta.ts @@ -0,0 +1,1225 @@ +// Copyright 2026 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. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it, beforeEach, afterEach} from 'mocha'; +import * as snapshotgroupsModule from '../src'; + +import {PassThrough} from 'stream'; + +import {GoogleAuth, protobuf} 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')).resolveAll(); + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function getTypeDefaultValue(typeName: string, fields: string[]) { + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; +} + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +} + +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v1beta.SnapshotGroupsClient', () => { + let googleAuth: GoogleAuth; + beforeEach(() => { + googleAuth = { + getClient: sinon.stub().resolves({ + getRequestHeaders: sinon.stub().resolves({Authorization: 'Bearer SOME_TOKEN'}), + }) + } as unknown as GoogleAuth; + }); + afterEach(() => { + sinon.restore(); + }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); + + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = snapshotgroupsModule.v1beta.SnapshotGroupsClient.servicePath; + assert.strictEqual(servicePath, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = snapshotgroupsModule.v1beta.SnapshotGroupsClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'compute.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + }); + + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'compute.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new snapshotgroupsModule.v1beta.SnapshotGroupsClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + }); + + it('has port', () => { + const port = snapshotgroupsModule.v1beta.SnapshotGroupsClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.snapshotGroupsStub, undefined); + await client.initialize(); + assert(client.snapshotGroupsStub); + }); + + it('has close method for the initialized client', done => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.snapshotGroupsStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has close method for the non-initialized client', done => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + assert.strictEqual(client.snapshotGroupsStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('delete', () => { + it('invokes delete without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest', ['snapshotGroup']); + request.snapshotGroup = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&snapshot_group=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.delete = stubSimpleCall(expectedResponse); + const [response] = await client.delete(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete without error using callback', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest', ['snapshotGroup']); + request.snapshotGroup = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&snapshot_group=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.delete = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.delete( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest', ['snapshotGroup']); + request.snapshotGroup = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&snapshot_group=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.delete(request), expectedError); + const actualRequest = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.delete as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes delete with closed client', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.DeleteSnapshotGroupRequest', ['snapshotGroup']); + request.snapshotGroup = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.delete(request), expectedError); + }); + }); + + describe('get', () => { + it('invokes get without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetSnapshotGroupRequest', ['snapshotGroup']); + request.snapshotGroup = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&snapshot_group=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SnapshotGroup() + ); + client.innerApiCalls.get = stubSimpleCall(expectedResponse); + const [response] = await client.get(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get without error using callback', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetSnapshotGroupRequest', ['snapshotGroup']); + request.snapshotGroup = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&snapshot_group=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SnapshotGroup() + ); + client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.get( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.ISnapshotGroup|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetSnapshotGroupRequest', ['snapshotGroup']); + request.snapshotGroup = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&snapshot_group=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.get = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.get(request), expectedError); + const actualRequest = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.get as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes get with closed client', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetSnapshotGroupRequest', ['snapshotGroup']); + request.snapshotGroup = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.get(request), expectedError); + }); + }); + + describe('getIamPolicy', () => { + it('invokes getIamPolicy without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.getIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy without error using callback', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.getIamPolicy = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIamPolicy( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IPolicy|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getIamPolicy(request), expectedError); + const actualRequest = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getIamPolicy with closed client', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.GetIamPolicySnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getIamPolicy(request), expectedError); + }); + }); + + describe('insert', () => { + it('invokes insert without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.insert = stubSimpleCall(expectedResponse); + const [response] = await client.insert(request); + assert.deepStrictEqual(response.latestResponse, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert without error using callback', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Operation() + ); + client.innerApiCalls.insert = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.insert( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IOperation|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.insert(request), expectedError); + const actualRequest = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.insert as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes insert with closed client', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.InsertSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.InsertSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.insert(request), expectedError); + }); + }); + + describe('setIamPolicy', () => { + it('invokes setIamPolicy without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse); + const [response] = await client.setIamPolicy(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy without error using callback', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.Policy() + ); + client.innerApiCalls.setIamPolicy = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.setIamPolicy( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.IPolicy|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.setIamPolicy = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.setIamPolicy(request), expectedError); + const actualRequest = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.setIamPolicy as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes setIamPolicy with closed client', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.SetIamPolicySnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.setIamPolicy(request), expectedError); + }); + }); + + describe('testIamPermissions', () => { + it('invokes testIamPermissions without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestPermissionsResponse() + ); + client.innerApiCalls.testIamPermissions = stubSimpleCall(expectedResponse); + const [response] = await client.testIamPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions without error using callback', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestPermissionsResponse() + ); + client.innerApiCalls.testIamPermissions = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.testIamPermissions( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.ITestPermissionsResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }&resource=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.testIamPermissions = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.testIamPermissions(request), expectedError); + const actualRequest = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.testIamPermissions as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes testIamPermissions with closed client', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest', ['project']); + request.project = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.cloud.compute.v1beta.TestIamPermissionsSnapshotGroupRequest', ['resource']); + request.resource = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.testIamPermissions(request), expectedError); + }); + }); + + describe('list', () => { + it('invokes list without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + ]; + client.innerApiCalls.list = stubSimpleCall(expectedResponse); + const [response] = await client.list(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list without error using callback', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + ]; + client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.list( + request, + (err?: Error|null, result?: protos.google.cloud.compute.v1beta.ISnapshotGroup[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes list with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.list = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.list(request), expectedError); + const actualRequest = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.list as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listStream without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + ]; + client.descriptors.page.list.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.SnapshotGroup[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.SnapshotGroup) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.list.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.list, request)); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listStream with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.list.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.compute.v1beta.SnapshotGroup[] = []; + stream.on('data', (response: protos.google.cloud.compute.v1beta.SnapshotGroup) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.list.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.list, request)); + assert( + (client.descriptors.page.list.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with list without error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + auth: googleAuth, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + generateSampleMessage(new protos.google.cloud.compute.v1beta.SnapshotGroup()), + ]; + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.cloud.compute.v1beta.ISnapshotGroup[] = []; + const iterable = client.listAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with list with error', async () => { + const client = new snapshotgroupsModule.v1beta.SnapshotGroupsClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.compute.v1beta.ListSnapshotGroupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.cloud.compute.v1beta.ListSnapshotGroupsRequest', ['project']); + request.project = defaultValue1; + const expectedHeaderRequestParams = `project=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAsync(request); + await assert.rejects(async () => { + const responses: protos.google.cloud.compute.v1beta.ISnapshotGroup[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.list.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); +}); diff --git a/packages/google-cloud-developerconnect/CHANGELOG.md b/packages/google-cloud-developerconnect/CHANGELOG.md index a441c57d7af..6e132eb9ea7 100644 --- a/packages/google-cloud-developerconnect/CHANGELOG.md +++ b/packages/google-cloud-developerconnect/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.7.0](https://github.com/googleapis/google-cloud-node/compare/developerconnect-v0.6.1...developerconnect-v0.7.0) (2026-03-02) + + +### Features + +* [developerconnect] Add Secure Source Manager and Generic HTTP Endpoint connection types ([#7284](https://github.com/googleapis/google-cloud-node/issues/7284)) ([b23e571](https://github.com/googleapis/google-cloud-node/commit/b23e571f96992f373cc6c413d026f322e8e58176)) + ## [0.6.1](https://github.com/googleapis/google-cloud-node/compare/developerconnect-v0.6.0...developerconnect-v0.6.1) (2025-10-13) diff --git a/packages/google-cloud-developerconnect/package.json b/packages/google-cloud-developerconnect/package.json index ce3dbcf173a..750afd6f1f5 100644 --- a/packages/google-cloud-developerconnect/package.json +++ b/packages/google-cloud-developerconnect/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/developerconnect", - "version": "0.6.1", + "version": "0.7.0", "description": "Developer Connect API client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-developerconnect/samples/package.json b/packages/google-cloud-developerconnect/samples/package.json index 717497edfa1..479c03ea750 100644 --- a/packages/google-cloud-developerconnect/samples/package.json +++ b/packages/google-cloud-developerconnect/samples/package.json @@ -14,7 +14,7 @@ "publish": "echo 'sample test; do not publish'" }, "dependencies": { - "@google-cloud/developerconnect": "^0.6.1" + "@google-cloud/developerconnect": "^0.7.0" }, "devDependencies": { "c8": "^10.0.0", diff --git a/packages/google-cloud-discoveryengine/CHANGELOG.md b/packages/google-cloud-discoveryengine/CHANGELOG.md index 51fea245f3b..2c80797e103 100644 --- a/packages/google-cloud-discoveryengine/CHANGELOG.md +++ b/packages/google-cloud-discoveryengine/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [2.5.3](https://github.com/googleapis/google-cloud-node/compare/discoveryengine-v2.5.2...discoveryengine-v2.5.3) (2026-03-02) + + +### Bug Fixes + +* Enable google-cloud-discoveryengine tests to run on windows ([a28d23f](https://github.com/googleapis/google-cloud-node/commit/a28d23fde5441c969b380dbd0dff0dc48836c01e)) +* Enable google-cloud-discoveryengine tests to run on windows ([23b81e4](https://github.com/googleapis/google-cloud-node/commit/23b81e4ae4c2dbe26f3731df4bd6cac9c687753b)) +* Try an alternative bash script for windows compatibility without an additional dependency ([f9b1ee9](https://github.com/googleapis/google-cloud-node/commit/f9b1ee9a92eb12f57a56db1bf591d3ec3afb4864)) + ## [2.5.2](https://github.com/googleapis/google-cloud-node/compare/discoveryengine-v2.5.1...discoveryengine-v2.5.2) (2025-10-21) diff --git a/packages/google-cloud-discoveryengine/package.json b/packages/google-cloud-discoveryengine/package.json index bfd83d4b8a3..008e6fde5e8 100644 --- a/packages/google-cloud-discoveryengine/package.json +++ b/packages/google-cloud-discoveryengine/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/discoveryengine", - "version": "2.5.2", + "version": "2.5.3", "description": "Discovery Engine API client for Node.js", "repository": { "type": "git", @@ -43,7 +43,7 @@ "postpack": "minifyProtoJson", "samples-test": "cd samples/ && npm link ../ && npm i && npm test", "system-test": "c8 mocha build/system-test", - "test": "NODE_OPTIONS=--max-old-space-size=16384 c8 mocha build/test" + "test": "NODE_OPTIONS=--max-old-space-size=16384 c8 mocha build/test || set NODE_OPTIONS=--max-old-space-size=16384 && c8 mocha build/test" }, "dependencies": { "google-gax": "^5.0.0" diff --git a/packages/google-cloud-discoveryengine/samples/package.json b/packages/google-cloud-discoveryengine/samples/package.json index 6ea07874a8c..ed97e9ea31c 100644 --- a/packages/google-cloud-discoveryengine/samples/package.json +++ b/packages/google-cloud-discoveryengine/samples/package.json @@ -14,7 +14,7 @@ "publish": "echo 'sample test; do not publish'" }, "dependencies": { - "@google-cloud/discoveryengine": "^2.5.2" + "@google-cloud/discoveryengine": "^2.5.3" }, "devDependencies": { "c8": "^10.0.0", diff --git a/packages/google-cloud-kms-inventory/CHANGELOG.md b/packages/google-cloud-kms-inventory/CHANGELOG.md index 7afd632566c..33953b7eded 100644 --- a/packages/google-cloud-kms-inventory/CHANGELOG.md +++ b/packages/google-cloud-kms-inventory/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [2.5.0](https://github.com/googleapis/google-cloud-node/compare/kms-inventory-v2.4.0...kms-inventory-v2.5.0) (2026-03-02) + + +### Features + +* [inventory] Add support for project level key usage tracking ([34a3659](https://github.com/googleapis/google-cloud-node/commit/34a365988184038c96de95cf0d8bf4bb5d8a8ccf)) + ## [2.4.0](https://github.com/googleapis/google-cloud-node/compare/kms-inventory-v2.3.0...kms-inventory-v2.4.0) (2026-02-19) diff --git a/packages/google-cloud-kms-inventory/package.json b/packages/google-cloud-kms-inventory/package.json index 12f0fc8a049..ff008ed3cb7 100644 --- a/packages/google-cloud-kms-inventory/package.json +++ b/packages/google-cloud-kms-inventory/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/kms-inventory", - "version": "2.4.0", + "version": "2.5.0", "description": "Inventory client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-kms-inventory/samples/package.json b/packages/google-cloud-kms-inventory/samples/package.json index eb371a127e3..56cdd1b474a 100644 --- a/packages/google-cloud-kms-inventory/samples/package.json +++ b/packages/google-cloud-kms-inventory/samples/package.json @@ -14,7 +14,7 @@ "publish": "echo 'sample test; do not publish'" }, "dependencies": { - "@google-cloud/kms-inventory": "^2.4.0" + "@google-cloud/kms-inventory": "^2.5.0" }, "devDependencies": { "c8": "^10.0.0", diff --git a/packages/google-cloud-networkmanagement/CHANGELOG.md b/packages/google-cloud-networkmanagement/CHANGELOG.md index 49bb1aa7943..d6c3d5deac6 100644 --- a/packages/google-cloud-networkmanagement/CHANGELOG.md +++ b/packages/google-cloud-networkmanagement/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [5.3.0](https://github.com/googleapis/google-cloud-node/compare/network-management-v5.2.0...network-management-v5.3.0) (2026-03-02) + + +### Features + +* [networkmanagement] Add API fields related to GKE Pods and Network Policies ([#7292](https://github.com/googleapis/google-cloud-node/issues/7292)) ([d6fb466](https://github.com/googleapis/google-cloud-node/commit/d6fb4665242b13e9c8b29ae3df6696155076297d)) + ## [5.2.0](https://github.com/googleapis/google-cloud-node/compare/network-management-v5.1.1...network-management-v5.2.0) (2026-01-31) diff --git a/packages/google-cloud-networkmanagement/package.json b/packages/google-cloud-networkmanagement/package.json index c527272b6f0..62f638412ce 100644 --- a/packages/google-cloud-networkmanagement/package.json +++ b/packages/google-cloud-networkmanagement/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/network-management", - "version": "5.2.0", + "version": "5.3.0", "description": "networkmanagement client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-networkmanagement/protos/google/cloud/networkmanagement/v1/trace.proto b/packages/google-cloud-networkmanagement/protos/google/cloud/networkmanagement/v1/trace.proto index 0b2c9fc66d3..eeaba9cb7ce 100644 --- a/packages/google-cloud-networkmanagement/protos/google/cloud/networkmanagement/v1/trace.proto +++ b/packages/google-cloud-networkmanagement/protos/google/cloud/networkmanagement/v1/trace.proto @@ -176,6 +176,9 @@ message Step { // Forwarding state: arriving at a VPC connector. ARRIVE_AT_VPC_CONNECTOR = 24; + // Forwarding state: arriving at a GKE Pod. + ARRIVE_AT_GKE_POD = 44; + // Forwarding state: for packets originating from a serverless endpoint // forwarded through Direct VPC egress. DIRECT_VPC_EGRESS_CONNECTION = 35; @@ -184,6 +187,10 @@ message Step { // forwarded through public (external) connectivity. SERVERLESS_EXTERNAL_CONNECTION = 36; + // Forwarding state: Layer 7 packet inspection by the firewall endpoint + // based on the configured security profile group. + NGFW_PACKET_INSPECTION = 47; + // Transition state: packet header translated. The `nat` field is populated // with the translation information. NAT = 14; @@ -192,6 +199,20 @@ message Step { // `ip_masquerading_skipped` field is populated with the reason. SKIP_GKE_POD_IP_MASQUERADING = 40; + // Transition state: GKE Ingress Network Policy is skipped. The + // `gke_network_policy_skipped` field is populated with the reason. + SKIP_GKE_INGRESS_NETWORK_POLICY = 41; + + // Transition state: GKE Egress Network Policy is skipped. The + // `gke_network_policy_skipped` field is populated with the reason. + SKIP_GKE_EGRESS_NETWORK_POLICY = 42; + + // Config checking state: verify ingress GKE network policy. + APPLY_INGRESS_GKE_NETWORK_POLICY = 45; + + // Config checking state: verify egress GKE network policy. + APPLY_EGRESS_GKE_NETWORK_POLICY = 46; + // Transition state: original connection is terminated and a new proxied // connection is initiated. PROXY_CONNECTION = 15; @@ -303,6 +324,13 @@ message Step { // skipped. IpMasqueradingSkippedInfo ip_masquerading_skipped = 38; + // Display information of a GKE Network Policy. + GkeNetworkPolicyInfo gke_network_policy = 39; + + // Display information of the reason why GKE Network Policy evaluation was + // skipped. + GkeNetworkPolicySkippedInfo gke_network_policy_skipped = 40; + // Display information of a Cloud SQL instance. CloudSQLInstanceInfo cloud_sql_instance = 19; @@ -336,6 +364,9 @@ message Step { // Display information of a Serverless network endpoint group backend. Used // only for return traces. ServerlessNegInfo serverless_neg = 29; + + // Display information of a layer 7 packet inspection by the firewall. + NgfwPacketInspectionInfo ngfw_packet_inspection = 42; } } @@ -1825,6 +1856,13 @@ message DropInfo { // Packet is dropped because no matching route was found in the hybrid // subnet. HYBRID_SUBNET_NO_ROUTE = 106; + + // Packet is dropped by GKE Network Policy. + GKE_NETWORK_POLICY = 108; + + // Packet is dropped because there is no valid matching route from the + // network of the Google-managed service to the destination. + NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION = 110; } // Cause that the packet is dropped. @@ -1929,6 +1967,57 @@ message IpMasqueradingSkippedInfo { string non_masquerade_range = 2; } +// For display only. Metadata associated with a GKE Network Policy. +message GkeNetworkPolicyInfo { + // The name of the Network Policy. + string display_name = 1; + + // The URI of the Network Policy. + // Format for a Network Policy in a zonal cluster: + // `projects//zones//clusters//k8s/namespaces//networking.k8s.io/networkpolicies/` + // Format for a Network Policy in a regional cluster: + // `projects//locations//clusters//k8s/namespaces//networking.k8s.io/networkpolicies/` + string uri = 2; + + // Possible values: INGRESS, EGRESS + string direction = 3; + + // Possible values: ALLOW, DENY + string action = 4; +} + +// For display only. Contains information about why GKE Network Policy +// evaluation was skipped. +message GkeNetworkPolicySkippedInfo { + enum Reason { + // Unused default value. + REASON_UNSPECIFIED = 0; + + // Network Policy is disabled on the cluster. + NETWORK_POLICY_DISABLED = 1; + + // Ingress traffic to a Pod from a source on the same Node is always + // allowed. + INGRESS_SOURCE_ON_SAME_NODE = 2; + + // Egress traffic from a Pod that uses the Node's network namespace is not + // subject to Network Policy. + EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD = 3; + + // Network Policy is not applied to response traffic. This is because GKE + // Network Policy evaluation is stateful in both GKE Dataplane V2 (eBPF) and + // legacy (iptables) implementations. + NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC = 4; + + // Network Policy evaluation is currently not supported for clusters with + // FQDN Network Policies enabled. + NETWORK_POLICY_ANALYSIS_UNSUPPORTED = 100; + } + + // Reason why Network Policy evaluation was skipped. + Reason reason = 1; +} + // For display only. Metadata associated with a Cloud SQL instance. message CloudSQLInstanceInfo { // Name of a Cloud SQL instance. @@ -2330,3 +2419,11 @@ message ServerlessNegInfo { // URI of the serverless network endpoint group. string neg_uri = 1; } + +// For display only. Metadata associated with a layer 7 packet inspection by the +// firewall. +message NgfwPacketInspectionInfo { + // URI of the security profile group associated with this firewall packet + // inspection. + string security_profile_group_uri = 1; +} diff --git a/packages/google-cloud-networkmanagement/protos/google/cloud/networkmanagement/v1beta1/trace.proto b/packages/google-cloud-networkmanagement/protos/google/cloud/networkmanagement/v1beta1/trace.proto index 9dde226c1a9..bd1feefbda5 100644 --- a/packages/google-cloud-networkmanagement/protos/google/cloud/networkmanagement/v1beta1/trace.proto +++ b/packages/google-cloud-networkmanagement/protos/google/cloud/networkmanagement/v1beta1/trace.proto @@ -180,6 +180,9 @@ message Step { // Forwarding state: arriving at a VPC connector. ARRIVE_AT_VPC_CONNECTOR = 24; + // Forwarding state: arriving at a GKE Pod. + ARRIVE_AT_GKE_POD = 44; + // Forwarding state: for packets originating from a serverless endpoint // forwarded through Direct VPC egress. DIRECT_VPC_EGRESS_CONNECTION = 35; @@ -188,6 +191,10 @@ message Step { // forwarded through public (external) connectivity. SERVERLESS_EXTERNAL_CONNECTION = 36; + // Forwarding state: Layer 7 packet inspection by the firewall endpoint + // based on the configured security profile group. + NGFW_PACKET_INSPECTION = 47; + // Transition state: packet header translated. The `nat` field is populated // with the translation information. NAT = 14; @@ -196,6 +203,20 @@ message Step { // `ip_masquerading_skipped` field is populated with the reason. SKIP_GKE_POD_IP_MASQUERADING = 40; + // Transition state: GKE Ingress Network Policy is skipped. The + // `gke_network_policy_skipped` field is populated with the reason. + SKIP_GKE_INGRESS_NETWORK_POLICY = 41; + + // Transition state: GKE Egress Network Policy is skipped. The + // `gke_network_policy_skipped` field is populated with the reason. + SKIP_GKE_EGRESS_NETWORK_POLICY = 42; + + // Config checking state: verify ingress GKE network policy. + APPLY_INGRESS_GKE_NETWORK_POLICY = 45; + + // Config checking state: verify egress GKE network policy. + APPLY_EGRESS_GKE_NETWORK_POLICY = 46; + // Transition state: original connection is terminated and a new proxied // connection is initiated. PROXY_CONNECTION = 15; @@ -307,6 +328,13 @@ message Step { // skipped. IpMasqueradingSkippedInfo ip_masquerading_skipped = 38; + // Display information of a GKE Network Policy. + GkeNetworkPolicyInfo gke_network_policy = 39; + + // Display information of the reason why GKE Network Policy evaluation was + // skipped. + GkeNetworkPolicySkippedInfo gke_network_policy_skipped = 40; + // Display information of a Cloud SQL instance. CloudSQLInstanceInfo cloud_sql_instance = 19; @@ -340,6 +368,9 @@ message Step { // Display information of a Serverless network endpoint group backend. Used // only for return traces. ServerlessNegInfo serverless_neg = 29; + + // Display information of a layer 7 packet inspection by the firewall. + NgfwPacketInspectionInfo ngfw_packet_inspection = 42; } } @@ -1827,6 +1858,13 @@ message DropInfo { // Packet is dropped because no matching route was found in the hybrid // subnet. HYBRID_SUBNET_NO_ROUTE = 106; + + // Packet is dropped by GKE Network Policy. + GKE_NETWORK_POLICY = 108; + + // Packet is dropped because there is no valid matching route from the + // network of the Google-managed service to the destination. + NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION = 110; } // Cause that the packet is dropped. @@ -1931,6 +1969,57 @@ message IpMasqueradingSkippedInfo { string non_masquerade_range = 2; } +// For display only. Metadata associated with a GKE Network Policy. +message GkeNetworkPolicyInfo { + // The name of the Network Policy. + string display_name = 1; + + // The URI of the Network Policy. + // Format for a Network Policy in a zonal cluster: + // `projects//zones//clusters//k8s/namespaces//networking.k8s.io/networkpolicies/` + // Format for a Network Policy in a regional cluster: + // `projects//locations//clusters//k8s/namespaces//networking.k8s.io/networkpolicies/` + string uri = 2; + + // Possible values: INGRESS, EGRESS + string direction = 3; + + // Possible values: ALLOW, DENY + string action = 4; +} + +// For display only. Contains information about why GKE Network Policy +// evaluation was skipped. +message GkeNetworkPolicySkippedInfo { + enum Reason { + // Unused default value. + REASON_UNSPECIFIED = 0; + + // Network Policy is disabled on the cluster. + NETWORK_POLICY_DISABLED = 1; + + // Ingress traffic to a Pod from a source on the same Node is always + // allowed. + INGRESS_SOURCE_ON_SAME_NODE = 2; + + // Egress traffic from a Pod that uses the Node's network namespace is not + // subject to Network Policy. + EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD = 3; + + // Network Policy is not applied to response traffic. This is because GKE + // Network Policy evaluation is stateful in both GKE Dataplane V2 (eBPF) and + // legacy (iptables) implementations. + NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC = 4; + + // Network Policy evaluation is currently not supported for clusters with + // FQDN Network Policies enabled. + NETWORK_POLICY_ANALYSIS_UNSUPPORTED = 100; + } + + // Reason why Network Policy evaluation was skipped. + Reason reason = 1; +} + // For display only. Metadata associated with a Cloud SQL instance. message CloudSQLInstanceInfo { // Name of a Cloud SQL instance. @@ -2332,3 +2421,11 @@ message ServerlessNegInfo { // URI of the serverless network endpoint group. string neg_uri = 1; } + +// For display only. Metadata associated with a layer 7 packet inspection by the +// firewall. +message NgfwPacketInspectionInfo { + // URI of the security profile group associated with this firewall packet + // inspection. + string security_profile_group_uri = 1; +} diff --git a/packages/google-cloud-networkmanagement/protos/protos.d.ts b/packages/google-cloud-networkmanagement/protos/protos.d.ts index c504a1f6317..55319e26fa8 100644 --- a/packages/google-cloud-networkmanagement/protos/protos.d.ts +++ b/packages/google-cloud-networkmanagement/protos/protos.d.ts @@ -1646,6 +1646,12 @@ export namespace google { /** Step ipMasqueradingSkipped */ ipMasqueradingSkipped?: (google.cloud.networkmanagement.v1.IIpMasqueradingSkippedInfo|null); + /** Step gkeNetworkPolicy */ + gkeNetworkPolicy?: (google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo|null); + + /** Step gkeNetworkPolicySkipped */ + gkeNetworkPolicySkipped?: (google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo|null); + /** Step cloudSqlInstance */ cloudSqlInstance?: (google.cloud.networkmanagement.v1.ICloudSQLInstanceInfo|null); @@ -1678,6 +1684,9 @@ export namespace google { /** Step serverlessNeg */ serverlessNeg?: (google.cloud.networkmanagement.v1.IServerlessNegInfo|null); + + /** Step ngfwPacketInspection */ + ngfwPacketInspection?: (google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo|null); } /** Represents a Step. */ @@ -1767,6 +1776,12 @@ export namespace google { /** Step ipMasqueradingSkipped. */ public ipMasqueradingSkipped?: (google.cloud.networkmanagement.v1.IIpMasqueradingSkippedInfo|null); + /** Step gkeNetworkPolicy. */ + public gkeNetworkPolicy?: (google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo|null); + + /** Step gkeNetworkPolicySkipped. */ + public gkeNetworkPolicySkipped?: (google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo|null); + /** Step cloudSqlInstance. */ public cloudSqlInstance?: (google.cloud.networkmanagement.v1.ICloudSQLInstanceInfo|null); @@ -1800,8 +1815,11 @@ export namespace google { /** Step serverlessNeg. */ public serverlessNeg?: (google.cloud.networkmanagement.v1.IServerlessNegInfo|null); + /** Step ngfwPacketInspection. */ + public ngfwPacketInspection?: (google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo|null); + /** Step stepInfo. */ - public stepInfo?: ("instance"|"firewall"|"route"|"endpoint"|"googleService"|"forwardingRule"|"hybridSubnet"|"vpnGateway"|"vpnTunnel"|"interconnectAttachment"|"vpcConnector"|"directVpcEgressConnection"|"serverlessExternalConnection"|"deliver"|"forward"|"abort"|"drop"|"loadBalancer"|"network"|"gkeMaster"|"gkePod"|"ipMasqueradingSkipped"|"cloudSqlInstance"|"redisInstance"|"redisCluster"|"cloudFunction"|"appEngineVersion"|"cloudRunRevision"|"nat"|"proxyConnection"|"loadBalancerBackendInfo"|"storageBucket"|"serverlessNeg"); + public stepInfo?: ("instance"|"firewall"|"route"|"endpoint"|"googleService"|"forwardingRule"|"hybridSubnet"|"vpnGateway"|"vpnTunnel"|"interconnectAttachment"|"vpcConnector"|"directVpcEgressConnection"|"serverlessExternalConnection"|"deliver"|"forward"|"abort"|"drop"|"loadBalancer"|"network"|"gkeMaster"|"gkePod"|"ipMasqueradingSkipped"|"gkeNetworkPolicy"|"gkeNetworkPolicySkipped"|"cloudSqlInstance"|"redisInstance"|"redisCluster"|"cloudFunction"|"appEngineVersion"|"cloudRunRevision"|"nat"|"proxyConnection"|"loadBalancerBackendInfo"|"storageBucket"|"serverlessNeg"|"ngfwPacketInspection"); /** * Creates a new Step instance using the specified properties. @@ -1915,10 +1933,16 @@ export namespace google { ARRIVE_AT_VPN_TUNNEL = 13, ARRIVE_AT_INTERCONNECT_ATTACHMENT = 37, ARRIVE_AT_VPC_CONNECTOR = 24, + ARRIVE_AT_GKE_POD = 44, DIRECT_VPC_EGRESS_CONNECTION = 35, SERVERLESS_EXTERNAL_CONNECTION = 36, + NGFW_PACKET_INSPECTION = 47, NAT = 14, SKIP_GKE_POD_IP_MASQUERADING = 40, + SKIP_GKE_INGRESS_NETWORK_POLICY = 41, + SKIP_GKE_EGRESS_NETWORK_POLICY = 42, + APPLY_INGRESS_GKE_NETWORK_POLICY = 45, + APPLY_EGRESS_GKE_NETWORK_POLICY = 46, PROXY_CONNECTION = 15, DELIVER = 16, DROP = 17, @@ -4606,7 +4630,9 @@ export namespace google { L2_INTERCONNECT_DESTINATION_IP_MISMATCH = 102, NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED = 104, HYBRID_SUBNET_REGION_MISMATCH = 105, - HYBRID_SUBNET_NO_ROUTE = 106 + HYBRID_SUBNET_NO_ROUTE = 106, + GKE_NETWORK_POLICY = 108, + NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION = 110 } } @@ -4958,6 +4984,231 @@ export namespace google { } } + /** Properties of a GkeNetworkPolicyInfo. */ + interface IGkeNetworkPolicyInfo { + + /** GkeNetworkPolicyInfo displayName */ + displayName?: (string|null); + + /** GkeNetworkPolicyInfo uri */ + uri?: (string|null); + + /** GkeNetworkPolicyInfo direction */ + direction?: (string|null); + + /** GkeNetworkPolicyInfo action */ + action?: (string|null); + } + + /** Represents a GkeNetworkPolicyInfo. */ + class GkeNetworkPolicyInfo implements IGkeNetworkPolicyInfo { + + /** + * Constructs a new GkeNetworkPolicyInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo); + + /** GkeNetworkPolicyInfo displayName. */ + public displayName: string; + + /** GkeNetworkPolicyInfo uri. */ + public uri: string; + + /** GkeNetworkPolicyInfo direction. */ + public direction: string; + + /** GkeNetworkPolicyInfo action. */ + public action: string; + + /** + * Creates a new GkeNetworkPolicyInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GkeNetworkPolicyInfo instance + */ + public static create(properties?: google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo): google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo; + + /** + * Encodes the specified GkeNetworkPolicyInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.verify|verify} messages. + * @param message GkeNetworkPolicyInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GkeNetworkPolicyInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.verify|verify} messages. + * @param message GkeNetworkPolicyInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GkeNetworkPolicyInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GkeNetworkPolicyInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo; + + /** + * Decodes a GkeNetworkPolicyInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GkeNetworkPolicyInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo; + + /** + * Verifies a GkeNetworkPolicyInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GkeNetworkPolicyInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GkeNetworkPolicyInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo; + + /** + * Creates a plain object from a GkeNetworkPolicyInfo message. Also converts values to other types if specified. + * @param message GkeNetworkPolicyInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GkeNetworkPolicyInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GkeNetworkPolicyInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GkeNetworkPolicySkippedInfo. */ + interface IGkeNetworkPolicySkippedInfo { + + /** GkeNetworkPolicySkippedInfo reason */ + reason?: (google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason|keyof typeof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason|null); + } + + /** Represents a GkeNetworkPolicySkippedInfo. */ + class GkeNetworkPolicySkippedInfo implements IGkeNetworkPolicySkippedInfo { + + /** + * Constructs a new GkeNetworkPolicySkippedInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo); + + /** GkeNetworkPolicySkippedInfo reason. */ + public reason: (google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason|keyof typeof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason); + + /** + * Creates a new GkeNetworkPolicySkippedInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GkeNetworkPolicySkippedInfo instance + */ + public static create(properties?: google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo): google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo; + + /** + * Encodes the specified GkeNetworkPolicySkippedInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.verify|verify} messages. + * @param message GkeNetworkPolicySkippedInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GkeNetworkPolicySkippedInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.verify|verify} messages. + * @param message GkeNetworkPolicySkippedInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GkeNetworkPolicySkippedInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GkeNetworkPolicySkippedInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo; + + /** + * Decodes a GkeNetworkPolicySkippedInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GkeNetworkPolicySkippedInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo; + + /** + * Verifies a GkeNetworkPolicySkippedInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GkeNetworkPolicySkippedInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GkeNetworkPolicySkippedInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo; + + /** + * Creates a plain object from a GkeNetworkPolicySkippedInfo message. Also converts values to other types if specified. + * @param message GkeNetworkPolicySkippedInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GkeNetworkPolicySkippedInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GkeNetworkPolicySkippedInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GkeNetworkPolicySkippedInfo { + + /** Reason enum. */ + enum Reason { + REASON_UNSPECIFIED = 0, + NETWORK_POLICY_DISABLED = 1, + INGRESS_SOURCE_ON_SAME_NODE = 2, + EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD = 3, + NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC = 4, + NETWORK_POLICY_ANALYSIS_UNSUPPORTED = 100 + } + } + /** Properties of a CloudSQLInstanceInfo. */ interface ICloudSQLInstanceInfo { @@ -6738,6 +6989,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a NgfwPacketInspectionInfo. */ + interface INgfwPacketInspectionInfo { + + /** NgfwPacketInspectionInfo securityProfileGroupUri */ + securityProfileGroupUri?: (string|null); + } + + /** Represents a NgfwPacketInspectionInfo. */ + class NgfwPacketInspectionInfo implements INgfwPacketInspectionInfo { + + /** + * Constructs a new NgfwPacketInspectionInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo); + + /** NgfwPacketInspectionInfo securityProfileGroupUri. */ + public securityProfileGroupUri: string; + + /** + * Creates a new NgfwPacketInspectionInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns NgfwPacketInspectionInfo instance + */ + public static create(properties?: google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo): google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo; + + /** + * Encodes the specified NgfwPacketInspectionInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.verify|verify} messages. + * @param message NgfwPacketInspectionInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NgfwPacketInspectionInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.verify|verify} messages. + * @param message NgfwPacketInspectionInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NgfwPacketInspectionInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NgfwPacketInspectionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo; + + /** + * Decodes a NgfwPacketInspectionInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NgfwPacketInspectionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo; + + /** + * Verifies a NgfwPacketInspectionInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NgfwPacketInspectionInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NgfwPacketInspectionInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo; + + /** + * Creates a plain object from a NgfwPacketInspectionInfo message. Also converts values to other types if specified. + * @param message NgfwPacketInspectionInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NgfwPacketInspectionInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NgfwPacketInspectionInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Represents a ReachabilityService */ class ReachabilityService extends $protobuf.rpc.Service { @@ -11193,6 +11541,12 @@ export namespace google { /** Step ipMasqueradingSkipped */ ipMasqueradingSkipped?: (google.cloud.networkmanagement.v1beta1.IIpMasqueradingSkippedInfo|null); + /** Step gkeNetworkPolicy */ + gkeNetworkPolicy?: (google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo|null); + + /** Step gkeNetworkPolicySkipped */ + gkeNetworkPolicySkipped?: (google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo|null); + /** Step cloudSqlInstance */ cloudSqlInstance?: (google.cloud.networkmanagement.v1beta1.ICloudSQLInstanceInfo|null); @@ -11225,6 +11579,9 @@ export namespace google { /** Step serverlessNeg */ serverlessNeg?: (google.cloud.networkmanagement.v1beta1.IServerlessNegInfo|null); + + /** Step ngfwPacketInspection */ + ngfwPacketInspection?: (google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo|null); } /** Represents a Step. */ @@ -11314,6 +11671,12 @@ export namespace google { /** Step ipMasqueradingSkipped. */ public ipMasqueradingSkipped?: (google.cloud.networkmanagement.v1beta1.IIpMasqueradingSkippedInfo|null); + /** Step gkeNetworkPolicy. */ + public gkeNetworkPolicy?: (google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo|null); + + /** Step gkeNetworkPolicySkipped. */ + public gkeNetworkPolicySkipped?: (google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo|null); + /** Step cloudSqlInstance. */ public cloudSqlInstance?: (google.cloud.networkmanagement.v1beta1.ICloudSQLInstanceInfo|null); @@ -11347,8 +11710,11 @@ export namespace google { /** Step serverlessNeg. */ public serverlessNeg?: (google.cloud.networkmanagement.v1beta1.IServerlessNegInfo|null); + /** Step ngfwPacketInspection. */ + public ngfwPacketInspection?: (google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo|null); + /** Step stepInfo. */ - public stepInfo?: ("instance"|"firewall"|"route"|"endpoint"|"googleService"|"forwardingRule"|"hybridSubnet"|"vpnGateway"|"vpnTunnel"|"interconnectAttachment"|"vpcConnector"|"directVpcEgressConnection"|"serverlessExternalConnection"|"deliver"|"forward"|"abort"|"drop"|"loadBalancer"|"network"|"gkeMaster"|"gkePod"|"ipMasqueradingSkipped"|"cloudSqlInstance"|"redisInstance"|"redisCluster"|"cloudFunction"|"appEngineVersion"|"cloudRunRevision"|"nat"|"proxyConnection"|"loadBalancerBackendInfo"|"storageBucket"|"serverlessNeg"); + public stepInfo?: ("instance"|"firewall"|"route"|"endpoint"|"googleService"|"forwardingRule"|"hybridSubnet"|"vpnGateway"|"vpnTunnel"|"interconnectAttachment"|"vpcConnector"|"directVpcEgressConnection"|"serverlessExternalConnection"|"deliver"|"forward"|"abort"|"drop"|"loadBalancer"|"network"|"gkeMaster"|"gkePod"|"ipMasqueradingSkipped"|"gkeNetworkPolicy"|"gkeNetworkPolicySkipped"|"cloudSqlInstance"|"redisInstance"|"redisCluster"|"cloudFunction"|"appEngineVersion"|"cloudRunRevision"|"nat"|"proxyConnection"|"loadBalancerBackendInfo"|"storageBucket"|"serverlessNeg"|"ngfwPacketInspection"); /** * Creates a new Step instance using the specified properties. @@ -11462,10 +11828,16 @@ export namespace google { ARRIVE_AT_VPN_TUNNEL = 13, ARRIVE_AT_INTERCONNECT_ATTACHMENT = 37, ARRIVE_AT_VPC_CONNECTOR = 24, + ARRIVE_AT_GKE_POD = 44, DIRECT_VPC_EGRESS_CONNECTION = 35, SERVERLESS_EXTERNAL_CONNECTION = 36, + NGFW_PACKET_INSPECTION = 47, NAT = 14, SKIP_GKE_POD_IP_MASQUERADING = 40, + SKIP_GKE_INGRESS_NETWORK_POLICY = 41, + SKIP_GKE_EGRESS_NETWORK_POLICY = 42, + APPLY_INGRESS_GKE_NETWORK_POLICY = 45, + APPLY_EGRESS_GKE_NETWORK_POLICY = 46, PROXY_CONNECTION = 15, DELIVER = 16, DROP = 17, @@ -14153,7 +14525,9 @@ export namespace google { L2_INTERCONNECT_DESTINATION_IP_MISMATCH = 102, NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED = 104, HYBRID_SUBNET_REGION_MISMATCH = 105, - HYBRID_SUBNET_NO_ROUTE = 106 + HYBRID_SUBNET_NO_ROUTE = 106, + GKE_NETWORK_POLICY = 108, + NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION = 110 } } @@ -14505,6 +14879,231 @@ export namespace google { } } + /** Properties of a GkeNetworkPolicyInfo. */ + interface IGkeNetworkPolicyInfo { + + /** GkeNetworkPolicyInfo displayName */ + displayName?: (string|null); + + /** GkeNetworkPolicyInfo uri */ + uri?: (string|null); + + /** GkeNetworkPolicyInfo direction */ + direction?: (string|null); + + /** GkeNetworkPolicyInfo action */ + action?: (string|null); + } + + /** Represents a GkeNetworkPolicyInfo. */ + class GkeNetworkPolicyInfo implements IGkeNetworkPolicyInfo { + + /** + * Constructs a new GkeNetworkPolicyInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo); + + /** GkeNetworkPolicyInfo displayName. */ + public displayName: string; + + /** GkeNetworkPolicyInfo uri. */ + public uri: string; + + /** GkeNetworkPolicyInfo direction. */ + public direction: string; + + /** GkeNetworkPolicyInfo action. */ + public action: string; + + /** + * Creates a new GkeNetworkPolicyInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GkeNetworkPolicyInfo instance + */ + public static create(properties?: google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo): google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo; + + /** + * Encodes the specified GkeNetworkPolicyInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.verify|verify} messages. + * @param message GkeNetworkPolicyInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GkeNetworkPolicyInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.verify|verify} messages. + * @param message GkeNetworkPolicyInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GkeNetworkPolicyInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GkeNetworkPolicyInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo; + + /** + * Decodes a GkeNetworkPolicyInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GkeNetworkPolicyInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo; + + /** + * Verifies a GkeNetworkPolicyInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GkeNetworkPolicyInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GkeNetworkPolicyInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo; + + /** + * Creates a plain object from a GkeNetworkPolicyInfo message. Also converts values to other types if specified. + * @param message GkeNetworkPolicyInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GkeNetworkPolicyInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GkeNetworkPolicyInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GkeNetworkPolicySkippedInfo. */ + interface IGkeNetworkPolicySkippedInfo { + + /** GkeNetworkPolicySkippedInfo reason */ + reason?: (google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason|keyof typeof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason|null); + } + + /** Represents a GkeNetworkPolicySkippedInfo. */ + class GkeNetworkPolicySkippedInfo implements IGkeNetworkPolicySkippedInfo { + + /** + * Constructs a new GkeNetworkPolicySkippedInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo); + + /** GkeNetworkPolicySkippedInfo reason. */ + public reason: (google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason|keyof typeof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason); + + /** + * Creates a new GkeNetworkPolicySkippedInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns GkeNetworkPolicySkippedInfo instance + */ + public static create(properties?: google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo): google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo; + + /** + * Encodes the specified GkeNetworkPolicySkippedInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.verify|verify} messages. + * @param message GkeNetworkPolicySkippedInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GkeNetworkPolicySkippedInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.verify|verify} messages. + * @param message GkeNetworkPolicySkippedInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GkeNetworkPolicySkippedInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GkeNetworkPolicySkippedInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo; + + /** + * Decodes a GkeNetworkPolicySkippedInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GkeNetworkPolicySkippedInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo; + + /** + * Verifies a GkeNetworkPolicySkippedInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GkeNetworkPolicySkippedInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GkeNetworkPolicySkippedInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo; + + /** + * Creates a plain object from a GkeNetworkPolicySkippedInfo message. Also converts values to other types if specified. + * @param message GkeNetworkPolicySkippedInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GkeNetworkPolicySkippedInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GkeNetworkPolicySkippedInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GkeNetworkPolicySkippedInfo { + + /** Reason enum. */ + enum Reason { + REASON_UNSPECIFIED = 0, + NETWORK_POLICY_DISABLED = 1, + INGRESS_SOURCE_ON_SAME_NODE = 2, + EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD = 3, + NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC = 4, + NETWORK_POLICY_ANALYSIS_UNSUPPORTED = 100 + } + } + /** Properties of a CloudSQLInstanceInfo. */ interface ICloudSQLInstanceInfo { @@ -16285,6 +16884,103 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a NgfwPacketInspectionInfo. */ + interface INgfwPacketInspectionInfo { + + /** NgfwPacketInspectionInfo securityProfileGroupUri */ + securityProfileGroupUri?: (string|null); + } + + /** Represents a NgfwPacketInspectionInfo. */ + class NgfwPacketInspectionInfo implements INgfwPacketInspectionInfo { + + /** + * Constructs a new NgfwPacketInspectionInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo); + + /** NgfwPacketInspectionInfo securityProfileGroupUri. */ + public securityProfileGroupUri: string; + + /** + * Creates a new NgfwPacketInspectionInfo instance using the specified properties. + * @param [properties] Properties to set + * @returns NgfwPacketInspectionInfo instance + */ + public static create(properties?: google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo): google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo; + + /** + * Encodes the specified NgfwPacketInspectionInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.verify|verify} messages. + * @param message NgfwPacketInspectionInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified NgfwPacketInspectionInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.verify|verify} messages. + * @param message NgfwPacketInspectionInfo message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a NgfwPacketInspectionInfo message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns NgfwPacketInspectionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo; + + /** + * Decodes a NgfwPacketInspectionInfo message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns NgfwPacketInspectionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo; + + /** + * Verifies a NgfwPacketInspectionInfo message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a NgfwPacketInspectionInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NgfwPacketInspectionInfo + */ + public static fromObject(object: { [k: string]: any }): google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo; + + /** + * Creates a plain object from a NgfwPacketInspectionInfo message. Also converts values to other types if specified. + * @param message NgfwPacketInspectionInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NgfwPacketInspectionInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NgfwPacketInspectionInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Represents a ReachabilityService */ class ReachabilityService extends $protobuf.rpc.Service { diff --git a/packages/google-cloud-networkmanagement/protos/protos.js b/packages/google-cloud-networkmanagement/protos/protos.js index 44a54ec270b..2c66bb61956 100644 --- a/packages/google-cloud-networkmanagement/protos/protos.js +++ b/packages/google-cloud-networkmanagement/protos/protos.js @@ -4443,6 +4443,8 @@ * @property {google.cloud.networkmanagement.v1.IGKEMasterInfo|null} [gkeMaster] Step gkeMaster * @property {google.cloud.networkmanagement.v1.IGkePodInfo|null} [gkePod] Step gkePod * @property {google.cloud.networkmanagement.v1.IIpMasqueradingSkippedInfo|null} [ipMasqueradingSkipped] Step ipMasqueradingSkipped + * @property {google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo|null} [gkeNetworkPolicy] Step gkeNetworkPolicy + * @property {google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo|null} [gkeNetworkPolicySkipped] Step gkeNetworkPolicySkipped * @property {google.cloud.networkmanagement.v1.ICloudSQLInstanceInfo|null} [cloudSqlInstance] Step cloudSqlInstance * @property {google.cloud.networkmanagement.v1.IRedisInstanceInfo|null} [redisInstance] Step redisInstance * @property {google.cloud.networkmanagement.v1.IRedisClusterInfo|null} [redisCluster] Step redisCluster @@ -4454,6 +4456,7 @@ * @property {google.cloud.networkmanagement.v1.ILoadBalancerBackendInfo|null} [loadBalancerBackendInfo] Step loadBalancerBackendInfo * @property {google.cloud.networkmanagement.v1.IStorageBucketInfo|null} [storageBucket] Step storageBucket * @property {google.cloud.networkmanagement.v1.IServerlessNegInfo|null} [serverlessNeg] Step serverlessNeg + * @property {google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo|null} [ngfwPacketInspection] Step ngfwPacketInspection */ /** @@ -4679,6 +4682,22 @@ */ Step.prototype.ipMasqueradingSkipped = null; + /** + * Step gkeNetworkPolicy. + * @member {google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo|null|undefined} gkeNetworkPolicy + * @memberof google.cloud.networkmanagement.v1.Step + * @instance + */ + Step.prototype.gkeNetworkPolicy = null; + + /** + * Step gkeNetworkPolicySkipped. + * @member {google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo|null|undefined} gkeNetworkPolicySkipped + * @memberof google.cloud.networkmanagement.v1.Step + * @instance + */ + Step.prototype.gkeNetworkPolicySkipped = null; + /** * Step cloudSqlInstance. * @member {google.cloud.networkmanagement.v1.ICloudSQLInstanceInfo|null|undefined} cloudSqlInstance @@ -4767,17 +4786,25 @@ */ Step.prototype.serverlessNeg = null; + /** + * Step ngfwPacketInspection. + * @member {google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo|null|undefined} ngfwPacketInspection + * @memberof google.cloud.networkmanagement.v1.Step + * @instance + */ + Step.prototype.ngfwPacketInspection = null; + // OneOf field names bound to virtual getters and setters var $oneOfFields; /** * Step stepInfo. - * @member {"instance"|"firewall"|"route"|"endpoint"|"googleService"|"forwardingRule"|"hybridSubnet"|"vpnGateway"|"vpnTunnel"|"interconnectAttachment"|"vpcConnector"|"directVpcEgressConnection"|"serverlessExternalConnection"|"deliver"|"forward"|"abort"|"drop"|"loadBalancer"|"network"|"gkeMaster"|"gkePod"|"ipMasqueradingSkipped"|"cloudSqlInstance"|"redisInstance"|"redisCluster"|"cloudFunction"|"appEngineVersion"|"cloudRunRevision"|"nat"|"proxyConnection"|"loadBalancerBackendInfo"|"storageBucket"|"serverlessNeg"|undefined} stepInfo + * @member {"instance"|"firewall"|"route"|"endpoint"|"googleService"|"forwardingRule"|"hybridSubnet"|"vpnGateway"|"vpnTunnel"|"interconnectAttachment"|"vpcConnector"|"directVpcEgressConnection"|"serverlessExternalConnection"|"deliver"|"forward"|"abort"|"drop"|"loadBalancer"|"network"|"gkeMaster"|"gkePod"|"ipMasqueradingSkipped"|"gkeNetworkPolicy"|"gkeNetworkPolicySkipped"|"cloudSqlInstance"|"redisInstance"|"redisCluster"|"cloudFunction"|"appEngineVersion"|"cloudRunRevision"|"nat"|"proxyConnection"|"loadBalancerBackendInfo"|"storageBucket"|"serverlessNeg"|"ngfwPacketInspection"|undefined} stepInfo * @memberof google.cloud.networkmanagement.v1.Step * @instance */ Object.defineProperty(Step.prototype, "stepInfo", { - get: $util.oneOfGetter($oneOfFields = ["instance", "firewall", "route", "endpoint", "googleService", "forwardingRule", "hybridSubnet", "vpnGateway", "vpnTunnel", "interconnectAttachment", "vpcConnector", "directVpcEgressConnection", "serverlessExternalConnection", "deliver", "forward", "abort", "drop", "loadBalancer", "network", "gkeMaster", "gkePod", "ipMasqueradingSkipped", "cloudSqlInstance", "redisInstance", "redisCluster", "cloudFunction", "appEngineVersion", "cloudRunRevision", "nat", "proxyConnection", "loadBalancerBackendInfo", "storageBucket", "serverlessNeg"]), + get: $util.oneOfGetter($oneOfFields = ["instance", "firewall", "route", "endpoint", "googleService", "forwardingRule", "hybridSubnet", "vpnGateway", "vpnTunnel", "interconnectAttachment", "vpcConnector", "directVpcEgressConnection", "serverlessExternalConnection", "deliver", "forward", "abort", "drop", "loadBalancer", "network", "gkeMaster", "gkePod", "ipMasqueradingSkipped", "gkeNetworkPolicy", "gkeNetworkPolicySkipped", "cloudSqlInstance", "redisInstance", "redisCluster", "cloudFunction", "appEngineVersion", "cloudRunRevision", "nat", "proxyConnection", "loadBalancerBackendInfo", "storageBucket", "serverlessNeg", "ngfwPacketInspection"]), set: $util.oneOfSetter($oneOfFields) }); @@ -4879,6 +4906,12 @@ $root.google.cloud.networkmanagement.v1.GkePodInfo.encode(message.gkePod, writer.uint32(/* id 37, wireType 2 =*/298).fork()).ldelim(); if (message.ipMasqueradingSkipped != null && Object.hasOwnProperty.call(message, "ipMasqueradingSkipped")) $root.google.cloud.networkmanagement.v1.IpMasqueradingSkippedInfo.encode(message.ipMasqueradingSkipped, writer.uint32(/* id 38, wireType 2 =*/306).fork()).ldelim(); + if (message.gkeNetworkPolicy != null && Object.hasOwnProperty.call(message, "gkeNetworkPolicy")) + $root.google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.encode(message.gkeNetworkPolicy, writer.uint32(/* id 39, wireType 2 =*/314).fork()).ldelim(); + if (message.gkeNetworkPolicySkipped != null && Object.hasOwnProperty.call(message, "gkeNetworkPolicySkipped")) + $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.encode(message.gkeNetworkPolicySkipped, writer.uint32(/* id 40, wireType 2 =*/322).fork()).ldelim(); + if (message.ngfwPacketInspection != null && Object.hasOwnProperty.call(message, "ngfwPacketInspection")) + $root.google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.encode(message.ngfwPacketInspection, writer.uint32(/* id 42, wireType 2 =*/338).fork()).ldelim(); return writer; }; @@ -5019,6 +5052,14 @@ message.ipMasqueradingSkipped = $root.google.cloud.networkmanagement.v1.IpMasqueradingSkippedInfo.decode(reader, reader.uint32()); break; } + case 39: { + message.gkeNetworkPolicy = $root.google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.decode(reader, reader.uint32()); + break; + } + case 40: { + message.gkeNetworkPolicySkipped = $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.decode(reader, reader.uint32()); + break; + } case 19: { message.cloudSqlInstance = $root.google.cloud.networkmanagement.v1.CloudSQLInstanceInfo.decode(reader, reader.uint32()); break; @@ -5063,6 +5104,10 @@ message.serverlessNeg = $root.google.cloud.networkmanagement.v1.ServerlessNegInfo.decode(reader, reader.uint32()); break; } + case 42: { + message.ngfwPacketInspection = $root.google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -5136,10 +5181,16 @@ case 13: case 37: case 24: + case 44: case 35: case 36: + case 47: case 14: case 40: + case 41: + case 42: + case 45: + case 46: case 15: case 16: case 17: @@ -5372,6 +5423,26 @@ return "ipMasqueradingSkipped." + error; } } + if (message.gkeNetworkPolicy != null && message.hasOwnProperty("gkeNetworkPolicy")) { + if (properties.stepInfo === 1) + return "stepInfo: multiple values"; + properties.stepInfo = 1; + { + var error = $root.google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.verify(message.gkeNetworkPolicy); + if (error) + return "gkeNetworkPolicy." + error; + } + } + if (message.gkeNetworkPolicySkipped != null && message.hasOwnProperty("gkeNetworkPolicySkipped")) { + if (properties.stepInfo === 1) + return "stepInfo: multiple values"; + properties.stepInfo = 1; + { + var error = $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.verify(message.gkeNetworkPolicySkipped); + if (error) + return "gkeNetworkPolicySkipped." + error; + } + } if (message.cloudSqlInstance != null && message.hasOwnProperty("cloudSqlInstance")) { if (properties.stepInfo === 1) return "stepInfo: multiple values"; @@ -5482,6 +5553,16 @@ return "serverlessNeg." + error; } } + if (message.ngfwPacketInspection != null && message.hasOwnProperty("ngfwPacketInspection")) { + if (properties.stepInfo === 1) + return "stepInfo: multiple values"; + properties.stepInfo = 1; + { + var error = $root.google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.verify(message.ngfwPacketInspection); + if (error) + return "ngfwPacketInspection." + error; + } + } return null; }; @@ -5626,6 +5707,10 @@ case 24: message.state = 24; break; + case "ARRIVE_AT_GKE_POD": + case 44: + message.state = 44; + break; case "DIRECT_VPC_EGRESS_CONNECTION": case 35: message.state = 35; @@ -5634,6 +5719,10 @@ case 36: message.state = 36; break; + case "NGFW_PACKET_INSPECTION": + case 47: + message.state = 47; + break; case "NAT": case 14: message.state = 14; @@ -5642,6 +5731,22 @@ case 40: message.state = 40; break; + case "SKIP_GKE_INGRESS_NETWORK_POLICY": + case 41: + message.state = 41; + break; + case "SKIP_GKE_EGRESS_NETWORK_POLICY": + case 42: + message.state = 42; + break; + case "APPLY_INGRESS_GKE_NETWORK_POLICY": + case 45: + message.state = 45; + break; + case "APPLY_EGRESS_GKE_NETWORK_POLICY": + case 46: + message.state = 46; + break; case "PROXY_CONNECTION": case 15: message.state = 15; @@ -5781,6 +5886,16 @@ throw TypeError(".google.cloud.networkmanagement.v1.Step.ipMasqueradingSkipped: object expected"); message.ipMasqueradingSkipped = $root.google.cloud.networkmanagement.v1.IpMasqueradingSkippedInfo.fromObject(object.ipMasqueradingSkipped); } + if (object.gkeNetworkPolicy != null) { + if (typeof object.gkeNetworkPolicy !== "object") + throw TypeError(".google.cloud.networkmanagement.v1.Step.gkeNetworkPolicy: object expected"); + message.gkeNetworkPolicy = $root.google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.fromObject(object.gkeNetworkPolicy); + } + if (object.gkeNetworkPolicySkipped != null) { + if (typeof object.gkeNetworkPolicySkipped !== "object") + throw TypeError(".google.cloud.networkmanagement.v1.Step.gkeNetworkPolicySkipped: object expected"); + message.gkeNetworkPolicySkipped = $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.fromObject(object.gkeNetworkPolicySkipped); + } if (object.cloudSqlInstance != null) { if (typeof object.cloudSqlInstance !== "object") throw TypeError(".google.cloud.networkmanagement.v1.Step.cloudSqlInstance: object expected"); @@ -5836,6 +5951,11 @@ throw TypeError(".google.cloud.networkmanagement.v1.Step.serverlessNeg: object expected"); message.serverlessNeg = $root.google.cloud.networkmanagement.v1.ServerlessNegInfo.fromObject(object.serverlessNeg); } + if (object.ngfwPacketInspection != null) { + if (typeof object.ngfwPacketInspection !== "object") + throw TypeError(".google.cloud.networkmanagement.v1.Step.ngfwPacketInspection: object expected"); + message.ngfwPacketInspection = $root.google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.fromObject(object.ngfwPacketInspection); + } return message; }; @@ -6031,6 +6151,21 @@ if (options.oneofs) object.stepInfo = "ipMasqueradingSkipped"; } + if (message.gkeNetworkPolicy != null && message.hasOwnProperty("gkeNetworkPolicy")) { + object.gkeNetworkPolicy = $root.google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.toObject(message.gkeNetworkPolicy, options); + if (options.oneofs) + object.stepInfo = "gkeNetworkPolicy"; + } + if (message.gkeNetworkPolicySkipped != null && message.hasOwnProperty("gkeNetworkPolicySkipped")) { + object.gkeNetworkPolicySkipped = $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.toObject(message.gkeNetworkPolicySkipped, options); + if (options.oneofs) + object.stepInfo = "gkeNetworkPolicySkipped"; + } + if (message.ngfwPacketInspection != null && message.hasOwnProperty("ngfwPacketInspection")) { + object.ngfwPacketInspection = $root.google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.toObject(message.ngfwPacketInspection, options); + if (options.oneofs) + object.stepInfo = "ngfwPacketInspection"; + } return object; }; @@ -6094,10 +6229,16 @@ * @property {number} ARRIVE_AT_VPN_TUNNEL=13 ARRIVE_AT_VPN_TUNNEL value * @property {number} ARRIVE_AT_INTERCONNECT_ATTACHMENT=37 ARRIVE_AT_INTERCONNECT_ATTACHMENT value * @property {number} ARRIVE_AT_VPC_CONNECTOR=24 ARRIVE_AT_VPC_CONNECTOR value + * @property {number} ARRIVE_AT_GKE_POD=44 ARRIVE_AT_GKE_POD value * @property {number} DIRECT_VPC_EGRESS_CONNECTION=35 DIRECT_VPC_EGRESS_CONNECTION value * @property {number} SERVERLESS_EXTERNAL_CONNECTION=36 SERVERLESS_EXTERNAL_CONNECTION value + * @property {number} NGFW_PACKET_INSPECTION=47 NGFW_PACKET_INSPECTION value * @property {number} NAT=14 NAT value * @property {number} SKIP_GKE_POD_IP_MASQUERADING=40 SKIP_GKE_POD_IP_MASQUERADING value + * @property {number} SKIP_GKE_INGRESS_NETWORK_POLICY=41 SKIP_GKE_INGRESS_NETWORK_POLICY value + * @property {number} SKIP_GKE_EGRESS_NETWORK_POLICY=42 SKIP_GKE_EGRESS_NETWORK_POLICY value + * @property {number} APPLY_INGRESS_GKE_NETWORK_POLICY=45 APPLY_INGRESS_GKE_NETWORK_POLICY value + * @property {number} APPLY_EGRESS_GKE_NETWORK_POLICY=46 APPLY_EGRESS_GKE_NETWORK_POLICY value * @property {number} PROXY_CONNECTION=15 PROXY_CONNECTION value * @property {number} DELIVER=16 DELIVER value * @property {number} DROP=17 DROP value @@ -6137,10 +6278,16 @@ values[valuesById[13] = "ARRIVE_AT_VPN_TUNNEL"] = 13; values[valuesById[37] = "ARRIVE_AT_INTERCONNECT_ATTACHMENT"] = 37; values[valuesById[24] = "ARRIVE_AT_VPC_CONNECTOR"] = 24; + values[valuesById[44] = "ARRIVE_AT_GKE_POD"] = 44; values[valuesById[35] = "DIRECT_VPC_EGRESS_CONNECTION"] = 35; values[valuesById[36] = "SERVERLESS_EXTERNAL_CONNECTION"] = 36; + values[valuesById[47] = "NGFW_PACKET_INSPECTION"] = 47; values[valuesById[14] = "NAT"] = 14; values[valuesById[40] = "SKIP_GKE_POD_IP_MASQUERADING"] = 40; + values[valuesById[41] = "SKIP_GKE_INGRESS_NETWORK_POLICY"] = 41; + values[valuesById[42] = "SKIP_GKE_EGRESS_NETWORK_POLICY"] = 42; + values[valuesById[45] = "APPLY_INGRESS_GKE_NETWORK_POLICY"] = 45; + values[valuesById[46] = "APPLY_EGRESS_GKE_NETWORK_POLICY"] = 46; values[valuesById[15] = "PROXY_CONNECTION"] = 15; values[valuesById[16] = "DELIVER"] = 16; values[valuesById[17] = "DROP"] = 17; @@ -13833,6 +13980,8 @@ case 104: case 105: case 106: + case 108: + case 110: break; } if (message.resourceUri != null && message.hasOwnProperty("resourceUri")) @@ -14287,6 +14436,14 @@ case 106: message.cause = 106; break; + case "GKE_NETWORK_POLICY": + case 108: + message.cause = 108; + break; + case "NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION": + case 110: + message.cause = 110; + break; } if (object.resourceUri != null) message.resourceUri = String(object.resourceUri); @@ -14475,6 +14632,8 @@ * @property {number} NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED=104 NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED value * @property {number} HYBRID_SUBNET_REGION_MISMATCH=105 HYBRID_SUBNET_REGION_MISMATCH value * @property {number} HYBRID_SUBNET_NO_ROUTE=106 HYBRID_SUBNET_NO_ROUTE value + * @property {number} GKE_NETWORK_POLICY=108 GKE_NETWORK_POLICY value + * @property {number} NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION=110 NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION value */ DropInfo.Cause = (function() { var valuesById = {}, values = Object.create(valuesById); @@ -14581,6 +14740,8 @@ values[valuesById[104] = "NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED"] = 104; values[valuesById[105] = "HYBRID_SUBNET_REGION_MISMATCH"] = 105; values[valuesById[106] = "HYBRID_SUBNET_NO_ROUTE"] = 106; + values[valuesById[108] = "GKE_NETWORK_POLICY"] = 108; + values[valuesById[110] = "NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION"] = 110; return values; })(); @@ -15441,6 +15602,547 @@ return IpMasqueradingSkippedInfo; })(); + v1.GkeNetworkPolicyInfo = (function() { + + /** + * Properties of a GkeNetworkPolicyInfo. + * @memberof google.cloud.networkmanagement.v1 + * @interface IGkeNetworkPolicyInfo + * @property {string|null} [displayName] GkeNetworkPolicyInfo displayName + * @property {string|null} [uri] GkeNetworkPolicyInfo uri + * @property {string|null} [direction] GkeNetworkPolicyInfo direction + * @property {string|null} [action] GkeNetworkPolicyInfo action + */ + + /** + * Constructs a new GkeNetworkPolicyInfo. + * @memberof google.cloud.networkmanagement.v1 + * @classdesc Represents a GkeNetworkPolicyInfo. + * @implements IGkeNetworkPolicyInfo + * @constructor + * @param {google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo=} [properties] Properties to set + */ + function GkeNetworkPolicyInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GkeNetworkPolicyInfo displayName. + * @member {string} displayName + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @instance + */ + GkeNetworkPolicyInfo.prototype.displayName = ""; + + /** + * GkeNetworkPolicyInfo uri. + * @member {string} uri + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @instance + */ + GkeNetworkPolicyInfo.prototype.uri = ""; + + /** + * GkeNetworkPolicyInfo direction. + * @member {string} direction + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @instance + */ + GkeNetworkPolicyInfo.prototype.direction = ""; + + /** + * GkeNetworkPolicyInfo action. + * @member {string} action + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @instance + */ + GkeNetworkPolicyInfo.prototype.action = ""; + + /** + * Creates a new GkeNetworkPolicyInfo instance using the specified properties. + * @function create + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo=} [properties] Properties to set + * @returns {google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo} GkeNetworkPolicyInfo instance + */ + GkeNetworkPolicyInfo.create = function create(properties) { + return new GkeNetworkPolicyInfo(properties); + }; + + /** + * Encodes the specified GkeNetworkPolicyInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo} message GkeNetworkPolicyInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GkeNetworkPolicyInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.displayName); + if (message.uri != null && Object.hasOwnProperty.call(message, "uri")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.uri); + if (message.direction != null && Object.hasOwnProperty.call(message, "direction")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.direction); + if (message.action != null && Object.hasOwnProperty.call(message, "action")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.action); + return writer; + }; + + /** + * Encodes the specified GkeNetworkPolicyInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {google.cloud.networkmanagement.v1.IGkeNetworkPolicyInfo} message GkeNetworkPolicyInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GkeNetworkPolicyInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GkeNetworkPolicyInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo} GkeNetworkPolicyInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GkeNetworkPolicyInfo.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.cloud.networkmanagement.v1.GkeNetworkPolicyInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.displayName = reader.string(); + break; + } + case 2: { + message.uri = reader.string(); + break; + } + case 3: { + message.direction = reader.string(); + break; + } + case 4: { + message.action = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GkeNetworkPolicyInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo} GkeNetworkPolicyInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GkeNetworkPolicyInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GkeNetworkPolicyInfo message. + * @function verify + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GkeNetworkPolicyInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.displayName != null && message.hasOwnProperty("displayName")) + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + if (message.uri != null && message.hasOwnProperty("uri")) + if (!$util.isString(message.uri)) + return "uri: string expected"; + if (message.direction != null && message.hasOwnProperty("direction")) + if (!$util.isString(message.direction)) + return "direction: string expected"; + if (message.action != null && message.hasOwnProperty("action")) + if (!$util.isString(message.action)) + return "action: string expected"; + return null; + }; + + /** + * Creates a GkeNetworkPolicyInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo} GkeNetworkPolicyInfo + */ + GkeNetworkPolicyInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo) + return object; + var message = new $root.google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo(); + if (object.displayName != null) + message.displayName = String(object.displayName); + if (object.uri != null) + message.uri = String(object.uri); + if (object.direction != null) + message.direction = String(object.direction); + if (object.action != null) + message.action = String(object.action); + return message; + }; + + /** + * Creates a plain object from a GkeNetworkPolicyInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo} message GkeNetworkPolicyInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GkeNetworkPolicyInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.displayName = ""; + object.uri = ""; + object.direction = ""; + object.action = ""; + } + if (message.displayName != null && message.hasOwnProperty("displayName")) + object.displayName = message.displayName; + if (message.uri != null && message.hasOwnProperty("uri")) + object.uri = message.uri; + if (message.direction != null && message.hasOwnProperty("direction")) + object.direction = message.direction; + if (message.action != null && message.hasOwnProperty("action")) + object.action = message.action; + return object; + }; + + /** + * Converts this GkeNetworkPolicyInfo to JSON. + * @function toJSON + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @instance + * @returns {Object.} JSON object + */ + GkeNetworkPolicyInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GkeNetworkPolicyInfo + * @function getTypeUrl + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GkeNetworkPolicyInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.networkmanagement.v1.GkeNetworkPolicyInfo"; + }; + + return GkeNetworkPolicyInfo; + })(); + + v1.GkeNetworkPolicySkippedInfo = (function() { + + /** + * Properties of a GkeNetworkPolicySkippedInfo. + * @memberof google.cloud.networkmanagement.v1 + * @interface IGkeNetworkPolicySkippedInfo + * @property {google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason|null} [reason] GkeNetworkPolicySkippedInfo reason + */ + + /** + * Constructs a new GkeNetworkPolicySkippedInfo. + * @memberof google.cloud.networkmanagement.v1 + * @classdesc Represents a GkeNetworkPolicySkippedInfo. + * @implements IGkeNetworkPolicySkippedInfo + * @constructor + * @param {google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo=} [properties] Properties to set + */ + function GkeNetworkPolicySkippedInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GkeNetworkPolicySkippedInfo reason. + * @member {google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason} reason + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @instance + */ + GkeNetworkPolicySkippedInfo.prototype.reason = 0; + + /** + * Creates a new GkeNetworkPolicySkippedInfo instance using the specified properties. + * @function create + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo=} [properties] Properties to set + * @returns {google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo} GkeNetworkPolicySkippedInfo instance + */ + GkeNetworkPolicySkippedInfo.create = function create(properties) { + return new GkeNetworkPolicySkippedInfo(properties); + }; + + /** + * Encodes the specified GkeNetworkPolicySkippedInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo} message GkeNetworkPolicySkippedInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GkeNetworkPolicySkippedInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.reason != null && Object.hasOwnProperty.call(message, "reason")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.reason); + return writer; + }; + + /** + * Encodes the specified GkeNetworkPolicySkippedInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {google.cloud.networkmanagement.v1.IGkeNetworkPolicySkippedInfo} message GkeNetworkPolicySkippedInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GkeNetworkPolicySkippedInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GkeNetworkPolicySkippedInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo} GkeNetworkPolicySkippedInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GkeNetworkPolicySkippedInfo.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.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.reason = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GkeNetworkPolicySkippedInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo} GkeNetworkPolicySkippedInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GkeNetworkPolicySkippedInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GkeNetworkPolicySkippedInfo message. + * @function verify + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GkeNetworkPolicySkippedInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.reason != null && message.hasOwnProperty("reason")) + switch (message.reason) { + default: + return "reason: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 100: + break; + } + return null; + }; + + /** + * Creates a GkeNetworkPolicySkippedInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo} GkeNetworkPolicySkippedInfo + */ + GkeNetworkPolicySkippedInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo) + return object; + var message = new $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo(); + switch (object.reason) { + default: + if (typeof object.reason === "number") { + message.reason = object.reason; + break; + } + break; + case "REASON_UNSPECIFIED": + case 0: + message.reason = 0; + break; + case "NETWORK_POLICY_DISABLED": + case 1: + message.reason = 1; + break; + case "INGRESS_SOURCE_ON_SAME_NODE": + case 2: + message.reason = 2; + break; + case "EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD": + case 3: + message.reason = 3; + break; + case "NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC": + case 4: + message.reason = 4; + break; + case "NETWORK_POLICY_ANALYSIS_UNSUPPORTED": + case 100: + message.reason = 100; + break; + } + return message; + }; + + /** + * Creates a plain object from a GkeNetworkPolicySkippedInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo} message GkeNetworkPolicySkippedInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GkeNetworkPolicySkippedInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.reason = options.enums === String ? "REASON_UNSPECIFIED" : 0; + if (message.reason != null && message.hasOwnProperty("reason")) + object.reason = options.enums === String ? $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason[message.reason] === undefined ? message.reason : $root.google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason[message.reason] : message.reason; + return object; + }; + + /** + * Converts this GkeNetworkPolicySkippedInfo to JSON. + * @function toJSON + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @instance + * @returns {Object.} JSON object + */ + GkeNetworkPolicySkippedInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GkeNetworkPolicySkippedInfo + * @function getTypeUrl + * @memberof google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GkeNetworkPolicySkippedInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo"; + }; + + /** + * Reason enum. + * @name google.cloud.networkmanagement.v1.GkeNetworkPolicySkippedInfo.Reason + * @enum {number} + * @property {number} REASON_UNSPECIFIED=0 REASON_UNSPECIFIED value + * @property {number} NETWORK_POLICY_DISABLED=1 NETWORK_POLICY_DISABLED value + * @property {number} INGRESS_SOURCE_ON_SAME_NODE=2 INGRESS_SOURCE_ON_SAME_NODE value + * @property {number} EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD=3 EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD value + * @property {number} NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC=4 NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC value + * @property {number} NETWORK_POLICY_ANALYSIS_UNSUPPORTED=100 NETWORK_POLICY_ANALYSIS_UNSUPPORTED value + */ + GkeNetworkPolicySkippedInfo.Reason = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "REASON_UNSPECIFIED"] = 0; + values[valuesById[1] = "NETWORK_POLICY_DISABLED"] = 1; + values[valuesById[2] = "INGRESS_SOURCE_ON_SAME_NODE"] = 2; + values[valuesById[3] = "EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD"] = 3; + values[valuesById[4] = "NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC"] = 4; + values[valuesById[100] = "NETWORK_POLICY_ANALYSIS_UNSUPPORTED"] = 100; + return values; + })(); + + return GkeNetworkPolicySkippedInfo; + })(); + v1.CloudSQLInstanceInfo = (function() { /** @@ -19970,6 +20672,211 @@ return ServerlessNegInfo; })(); + v1.NgfwPacketInspectionInfo = (function() { + + /** + * Properties of a NgfwPacketInspectionInfo. + * @memberof google.cloud.networkmanagement.v1 + * @interface INgfwPacketInspectionInfo + * @property {string|null} [securityProfileGroupUri] NgfwPacketInspectionInfo securityProfileGroupUri + */ + + /** + * Constructs a new NgfwPacketInspectionInfo. + * @memberof google.cloud.networkmanagement.v1 + * @classdesc Represents a NgfwPacketInspectionInfo. + * @implements INgfwPacketInspectionInfo + * @constructor + * @param {google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo=} [properties] Properties to set + */ + function NgfwPacketInspectionInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NgfwPacketInspectionInfo securityProfileGroupUri. + * @member {string} securityProfileGroupUri + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @instance + */ + NgfwPacketInspectionInfo.prototype.securityProfileGroupUri = ""; + + /** + * Creates a new NgfwPacketInspectionInfo instance using the specified properties. + * @function create + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo=} [properties] Properties to set + * @returns {google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo} NgfwPacketInspectionInfo instance + */ + NgfwPacketInspectionInfo.create = function create(properties) { + return new NgfwPacketInspectionInfo(properties); + }; + + /** + * Encodes the specified NgfwPacketInspectionInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo} message NgfwPacketInspectionInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NgfwPacketInspectionInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.securityProfileGroupUri != null && Object.hasOwnProperty.call(message, "securityProfileGroupUri")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.securityProfileGroupUri); + return writer; + }; + + /** + * Encodes the specified NgfwPacketInspectionInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {google.cloud.networkmanagement.v1.INgfwPacketInspectionInfo} message NgfwPacketInspectionInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NgfwPacketInspectionInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a NgfwPacketInspectionInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo} NgfwPacketInspectionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NgfwPacketInspectionInfo.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.cloud.networkmanagement.v1.NgfwPacketInspectionInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.securityProfileGroupUri = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a NgfwPacketInspectionInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo} NgfwPacketInspectionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NgfwPacketInspectionInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a NgfwPacketInspectionInfo message. + * @function verify + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + NgfwPacketInspectionInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.securityProfileGroupUri != null && message.hasOwnProperty("securityProfileGroupUri")) + if (!$util.isString(message.securityProfileGroupUri)) + return "securityProfileGroupUri: string expected"; + return null; + }; + + /** + * Creates a NgfwPacketInspectionInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo} NgfwPacketInspectionInfo + */ + NgfwPacketInspectionInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo) + return object; + var message = new $root.google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo(); + if (object.securityProfileGroupUri != null) + message.securityProfileGroupUri = String(object.securityProfileGroupUri); + return message; + }; + + /** + * Creates a plain object from a NgfwPacketInspectionInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo} message NgfwPacketInspectionInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NgfwPacketInspectionInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.securityProfileGroupUri = ""; + if (message.securityProfileGroupUri != null && message.hasOwnProperty("securityProfileGroupUri")) + object.securityProfileGroupUri = message.securityProfileGroupUri; + return object; + }; + + /** + * Converts this NgfwPacketInspectionInfo to JSON. + * @function toJSON + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @instance + * @returns {Object.} JSON object + */ + NgfwPacketInspectionInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NgfwPacketInspectionInfo + * @function getTypeUrl + * @memberof google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NgfwPacketInspectionInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.networkmanagement.v1.NgfwPacketInspectionInfo"; + }; + + return NgfwPacketInspectionInfo; + })(); + v1.ReachabilityService = (function() { /** @@ -31541,6 +32448,8 @@ * @property {google.cloud.networkmanagement.v1beta1.IGKEMasterInfo|null} [gkeMaster] Step gkeMaster * @property {google.cloud.networkmanagement.v1beta1.IGkePodInfo|null} [gkePod] Step gkePod * @property {google.cloud.networkmanagement.v1beta1.IIpMasqueradingSkippedInfo|null} [ipMasqueradingSkipped] Step ipMasqueradingSkipped + * @property {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo|null} [gkeNetworkPolicy] Step gkeNetworkPolicy + * @property {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo|null} [gkeNetworkPolicySkipped] Step gkeNetworkPolicySkipped * @property {google.cloud.networkmanagement.v1beta1.ICloudSQLInstanceInfo|null} [cloudSqlInstance] Step cloudSqlInstance * @property {google.cloud.networkmanagement.v1beta1.IRedisInstanceInfo|null} [redisInstance] Step redisInstance * @property {google.cloud.networkmanagement.v1beta1.IRedisClusterInfo|null} [redisCluster] Step redisCluster @@ -31552,6 +32461,7 @@ * @property {google.cloud.networkmanagement.v1beta1.ILoadBalancerBackendInfo|null} [loadBalancerBackendInfo] Step loadBalancerBackendInfo * @property {google.cloud.networkmanagement.v1beta1.IStorageBucketInfo|null} [storageBucket] Step storageBucket * @property {google.cloud.networkmanagement.v1beta1.IServerlessNegInfo|null} [serverlessNeg] Step serverlessNeg + * @property {google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo|null} [ngfwPacketInspection] Step ngfwPacketInspection */ /** @@ -31777,6 +32687,22 @@ */ Step.prototype.ipMasqueradingSkipped = null; + /** + * Step gkeNetworkPolicy. + * @member {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo|null|undefined} gkeNetworkPolicy + * @memberof google.cloud.networkmanagement.v1beta1.Step + * @instance + */ + Step.prototype.gkeNetworkPolicy = null; + + /** + * Step gkeNetworkPolicySkipped. + * @member {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo|null|undefined} gkeNetworkPolicySkipped + * @memberof google.cloud.networkmanagement.v1beta1.Step + * @instance + */ + Step.prototype.gkeNetworkPolicySkipped = null; + /** * Step cloudSqlInstance. * @member {google.cloud.networkmanagement.v1beta1.ICloudSQLInstanceInfo|null|undefined} cloudSqlInstance @@ -31865,17 +32791,25 @@ */ Step.prototype.serverlessNeg = null; + /** + * Step ngfwPacketInspection. + * @member {google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo|null|undefined} ngfwPacketInspection + * @memberof google.cloud.networkmanagement.v1beta1.Step + * @instance + */ + Step.prototype.ngfwPacketInspection = null; + // OneOf field names bound to virtual getters and setters var $oneOfFields; /** * Step stepInfo. - * @member {"instance"|"firewall"|"route"|"endpoint"|"googleService"|"forwardingRule"|"hybridSubnet"|"vpnGateway"|"vpnTunnel"|"interconnectAttachment"|"vpcConnector"|"directVpcEgressConnection"|"serverlessExternalConnection"|"deliver"|"forward"|"abort"|"drop"|"loadBalancer"|"network"|"gkeMaster"|"gkePod"|"ipMasqueradingSkipped"|"cloudSqlInstance"|"redisInstance"|"redisCluster"|"cloudFunction"|"appEngineVersion"|"cloudRunRevision"|"nat"|"proxyConnection"|"loadBalancerBackendInfo"|"storageBucket"|"serverlessNeg"|undefined} stepInfo + * @member {"instance"|"firewall"|"route"|"endpoint"|"googleService"|"forwardingRule"|"hybridSubnet"|"vpnGateway"|"vpnTunnel"|"interconnectAttachment"|"vpcConnector"|"directVpcEgressConnection"|"serverlessExternalConnection"|"deliver"|"forward"|"abort"|"drop"|"loadBalancer"|"network"|"gkeMaster"|"gkePod"|"ipMasqueradingSkipped"|"gkeNetworkPolicy"|"gkeNetworkPolicySkipped"|"cloudSqlInstance"|"redisInstance"|"redisCluster"|"cloudFunction"|"appEngineVersion"|"cloudRunRevision"|"nat"|"proxyConnection"|"loadBalancerBackendInfo"|"storageBucket"|"serverlessNeg"|"ngfwPacketInspection"|undefined} stepInfo * @memberof google.cloud.networkmanagement.v1beta1.Step * @instance */ Object.defineProperty(Step.prototype, "stepInfo", { - get: $util.oneOfGetter($oneOfFields = ["instance", "firewall", "route", "endpoint", "googleService", "forwardingRule", "hybridSubnet", "vpnGateway", "vpnTunnel", "interconnectAttachment", "vpcConnector", "directVpcEgressConnection", "serverlessExternalConnection", "deliver", "forward", "abort", "drop", "loadBalancer", "network", "gkeMaster", "gkePod", "ipMasqueradingSkipped", "cloudSqlInstance", "redisInstance", "redisCluster", "cloudFunction", "appEngineVersion", "cloudRunRevision", "nat", "proxyConnection", "loadBalancerBackendInfo", "storageBucket", "serverlessNeg"]), + get: $util.oneOfGetter($oneOfFields = ["instance", "firewall", "route", "endpoint", "googleService", "forwardingRule", "hybridSubnet", "vpnGateway", "vpnTunnel", "interconnectAttachment", "vpcConnector", "directVpcEgressConnection", "serverlessExternalConnection", "deliver", "forward", "abort", "drop", "loadBalancer", "network", "gkeMaster", "gkePod", "ipMasqueradingSkipped", "gkeNetworkPolicy", "gkeNetworkPolicySkipped", "cloudSqlInstance", "redisInstance", "redisCluster", "cloudFunction", "appEngineVersion", "cloudRunRevision", "nat", "proxyConnection", "loadBalancerBackendInfo", "storageBucket", "serverlessNeg", "ngfwPacketInspection"]), set: $util.oneOfSetter($oneOfFields) }); @@ -31977,6 +32911,12 @@ $root.google.cloud.networkmanagement.v1beta1.GkePodInfo.encode(message.gkePod, writer.uint32(/* id 37, wireType 2 =*/298).fork()).ldelim(); if (message.ipMasqueradingSkipped != null && Object.hasOwnProperty.call(message, "ipMasqueradingSkipped")) $root.google.cloud.networkmanagement.v1beta1.IpMasqueradingSkippedInfo.encode(message.ipMasqueradingSkipped, writer.uint32(/* id 38, wireType 2 =*/306).fork()).ldelim(); + if (message.gkeNetworkPolicy != null && Object.hasOwnProperty.call(message, "gkeNetworkPolicy")) + $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.encode(message.gkeNetworkPolicy, writer.uint32(/* id 39, wireType 2 =*/314).fork()).ldelim(); + if (message.gkeNetworkPolicySkipped != null && Object.hasOwnProperty.call(message, "gkeNetworkPolicySkipped")) + $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.encode(message.gkeNetworkPolicySkipped, writer.uint32(/* id 40, wireType 2 =*/322).fork()).ldelim(); + if (message.ngfwPacketInspection != null && Object.hasOwnProperty.call(message, "ngfwPacketInspection")) + $root.google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.encode(message.ngfwPacketInspection, writer.uint32(/* id 42, wireType 2 =*/338).fork()).ldelim(); return writer; }; @@ -32117,6 +33057,14 @@ message.ipMasqueradingSkipped = $root.google.cloud.networkmanagement.v1beta1.IpMasqueradingSkippedInfo.decode(reader, reader.uint32()); break; } + case 39: { + message.gkeNetworkPolicy = $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.decode(reader, reader.uint32()); + break; + } + case 40: { + message.gkeNetworkPolicySkipped = $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.decode(reader, reader.uint32()); + break; + } case 19: { message.cloudSqlInstance = $root.google.cloud.networkmanagement.v1beta1.CloudSQLInstanceInfo.decode(reader, reader.uint32()); break; @@ -32161,6 +33109,10 @@ message.serverlessNeg = $root.google.cloud.networkmanagement.v1beta1.ServerlessNegInfo.decode(reader, reader.uint32()); break; } + case 42: { + message.ngfwPacketInspection = $root.google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -32234,10 +33186,16 @@ case 13: case 37: case 24: + case 44: case 35: case 36: + case 47: case 14: case 40: + case 41: + case 42: + case 45: + case 46: case 15: case 16: case 17: @@ -32470,6 +33428,26 @@ return "ipMasqueradingSkipped." + error; } } + if (message.gkeNetworkPolicy != null && message.hasOwnProperty("gkeNetworkPolicy")) { + if (properties.stepInfo === 1) + return "stepInfo: multiple values"; + properties.stepInfo = 1; + { + var error = $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.verify(message.gkeNetworkPolicy); + if (error) + return "gkeNetworkPolicy." + error; + } + } + if (message.gkeNetworkPolicySkipped != null && message.hasOwnProperty("gkeNetworkPolicySkipped")) { + if (properties.stepInfo === 1) + return "stepInfo: multiple values"; + properties.stepInfo = 1; + { + var error = $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.verify(message.gkeNetworkPolicySkipped); + if (error) + return "gkeNetworkPolicySkipped." + error; + } + } if (message.cloudSqlInstance != null && message.hasOwnProperty("cloudSqlInstance")) { if (properties.stepInfo === 1) return "stepInfo: multiple values"; @@ -32580,6 +33558,16 @@ return "serverlessNeg." + error; } } + if (message.ngfwPacketInspection != null && message.hasOwnProperty("ngfwPacketInspection")) { + if (properties.stepInfo === 1) + return "stepInfo: multiple values"; + properties.stepInfo = 1; + { + var error = $root.google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.verify(message.ngfwPacketInspection); + if (error) + return "ngfwPacketInspection." + error; + } + } return null; }; @@ -32724,6 +33712,10 @@ case 24: message.state = 24; break; + case "ARRIVE_AT_GKE_POD": + case 44: + message.state = 44; + break; case "DIRECT_VPC_EGRESS_CONNECTION": case 35: message.state = 35; @@ -32732,6 +33724,10 @@ case 36: message.state = 36; break; + case "NGFW_PACKET_INSPECTION": + case 47: + message.state = 47; + break; case "NAT": case 14: message.state = 14; @@ -32740,6 +33736,22 @@ case 40: message.state = 40; break; + case "SKIP_GKE_INGRESS_NETWORK_POLICY": + case 41: + message.state = 41; + break; + case "SKIP_GKE_EGRESS_NETWORK_POLICY": + case 42: + message.state = 42; + break; + case "APPLY_INGRESS_GKE_NETWORK_POLICY": + case 45: + message.state = 45; + break; + case "APPLY_EGRESS_GKE_NETWORK_POLICY": + case 46: + message.state = 46; + break; case "PROXY_CONNECTION": case 15: message.state = 15; @@ -32879,6 +33891,16 @@ throw TypeError(".google.cloud.networkmanagement.v1beta1.Step.ipMasqueradingSkipped: object expected"); message.ipMasqueradingSkipped = $root.google.cloud.networkmanagement.v1beta1.IpMasqueradingSkippedInfo.fromObject(object.ipMasqueradingSkipped); } + if (object.gkeNetworkPolicy != null) { + if (typeof object.gkeNetworkPolicy !== "object") + throw TypeError(".google.cloud.networkmanagement.v1beta1.Step.gkeNetworkPolicy: object expected"); + message.gkeNetworkPolicy = $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.fromObject(object.gkeNetworkPolicy); + } + if (object.gkeNetworkPolicySkipped != null) { + if (typeof object.gkeNetworkPolicySkipped !== "object") + throw TypeError(".google.cloud.networkmanagement.v1beta1.Step.gkeNetworkPolicySkipped: object expected"); + message.gkeNetworkPolicySkipped = $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.fromObject(object.gkeNetworkPolicySkipped); + } if (object.cloudSqlInstance != null) { if (typeof object.cloudSqlInstance !== "object") throw TypeError(".google.cloud.networkmanagement.v1beta1.Step.cloudSqlInstance: object expected"); @@ -32934,6 +33956,11 @@ throw TypeError(".google.cloud.networkmanagement.v1beta1.Step.serverlessNeg: object expected"); message.serverlessNeg = $root.google.cloud.networkmanagement.v1beta1.ServerlessNegInfo.fromObject(object.serverlessNeg); } + if (object.ngfwPacketInspection != null) { + if (typeof object.ngfwPacketInspection !== "object") + throw TypeError(".google.cloud.networkmanagement.v1beta1.Step.ngfwPacketInspection: object expected"); + message.ngfwPacketInspection = $root.google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.fromObject(object.ngfwPacketInspection); + } return message; }; @@ -33129,6 +34156,21 @@ if (options.oneofs) object.stepInfo = "ipMasqueradingSkipped"; } + if (message.gkeNetworkPolicy != null && message.hasOwnProperty("gkeNetworkPolicy")) { + object.gkeNetworkPolicy = $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.toObject(message.gkeNetworkPolicy, options); + if (options.oneofs) + object.stepInfo = "gkeNetworkPolicy"; + } + if (message.gkeNetworkPolicySkipped != null && message.hasOwnProperty("gkeNetworkPolicySkipped")) { + object.gkeNetworkPolicySkipped = $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.toObject(message.gkeNetworkPolicySkipped, options); + if (options.oneofs) + object.stepInfo = "gkeNetworkPolicySkipped"; + } + if (message.ngfwPacketInspection != null && message.hasOwnProperty("ngfwPacketInspection")) { + object.ngfwPacketInspection = $root.google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.toObject(message.ngfwPacketInspection, options); + if (options.oneofs) + object.stepInfo = "ngfwPacketInspection"; + } return object; }; @@ -33192,10 +34234,16 @@ * @property {number} ARRIVE_AT_VPN_TUNNEL=13 ARRIVE_AT_VPN_TUNNEL value * @property {number} ARRIVE_AT_INTERCONNECT_ATTACHMENT=37 ARRIVE_AT_INTERCONNECT_ATTACHMENT value * @property {number} ARRIVE_AT_VPC_CONNECTOR=24 ARRIVE_AT_VPC_CONNECTOR value + * @property {number} ARRIVE_AT_GKE_POD=44 ARRIVE_AT_GKE_POD value * @property {number} DIRECT_VPC_EGRESS_CONNECTION=35 DIRECT_VPC_EGRESS_CONNECTION value * @property {number} SERVERLESS_EXTERNAL_CONNECTION=36 SERVERLESS_EXTERNAL_CONNECTION value + * @property {number} NGFW_PACKET_INSPECTION=47 NGFW_PACKET_INSPECTION value * @property {number} NAT=14 NAT value * @property {number} SKIP_GKE_POD_IP_MASQUERADING=40 SKIP_GKE_POD_IP_MASQUERADING value + * @property {number} SKIP_GKE_INGRESS_NETWORK_POLICY=41 SKIP_GKE_INGRESS_NETWORK_POLICY value + * @property {number} SKIP_GKE_EGRESS_NETWORK_POLICY=42 SKIP_GKE_EGRESS_NETWORK_POLICY value + * @property {number} APPLY_INGRESS_GKE_NETWORK_POLICY=45 APPLY_INGRESS_GKE_NETWORK_POLICY value + * @property {number} APPLY_EGRESS_GKE_NETWORK_POLICY=46 APPLY_EGRESS_GKE_NETWORK_POLICY value * @property {number} PROXY_CONNECTION=15 PROXY_CONNECTION value * @property {number} DELIVER=16 DELIVER value * @property {number} DROP=17 DROP value @@ -33235,10 +34283,16 @@ values[valuesById[13] = "ARRIVE_AT_VPN_TUNNEL"] = 13; values[valuesById[37] = "ARRIVE_AT_INTERCONNECT_ATTACHMENT"] = 37; values[valuesById[24] = "ARRIVE_AT_VPC_CONNECTOR"] = 24; + values[valuesById[44] = "ARRIVE_AT_GKE_POD"] = 44; values[valuesById[35] = "DIRECT_VPC_EGRESS_CONNECTION"] = 35; values[valuesById[36] = "SERVERLESS_EXTERNAL_CONNECTION"] = 36; + values[valuesById[47] = "NGFW_PACKET_INSPECTION"] = 47; values[valuesById[14] = "NAT"] = 14; values[valuesById[40] = "SKIP_GKE_POD_IP_MASQUERADING"] = 40; + values[valuesById[41] = "SKIP_GKE_INGRESS_NETWORK_POLICY"] = 41; + values[valuesById[42] = "SKIP_GKE_EGRESS_NETWORK_POLICY"] = 42; + values[valuesById[45] = "APPLY_INGRESS_GKE_NETWORK_POLICY"] = 45; + values[valuesById[46] = "APPLY_EGRESS_GKE_NETWORK_POLICY"] = 46; values[valuesById[15] = "PROXY_CONNECTION"] = 15; values[valuesById[16] = "DELIVER"] = 16; values[valuesById[17] = "DROP"] = 17; @@ -40931,6 +41985,8 @@ case 104: case 105: case 106: + case 108: + case 110: break; } if (message.resourceUri != null && message.hasOwnProperty("resourceUri")) @@ -41385,6 +42441,14 @@ case 106: message.cause = 106; break; + case "GKE_NETWORK_POLICY": + case 108: + message.cause = 108; + break; + case "NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION": + case 110: + message.cause = 110; + break; } if (object.resourceUri != null) message.resourceUri = String(object.resourceUri); @@ -41573,6 +42637,8 @@ * @property {number} NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED=104 NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED value * @property {number} HYBRID_SUBNET_REGION_MISMATCH=105 HYBRID_SUBNET_REGION_MISMATCH value * @property {number} HYBRID_SUBNET_NO_ROUTE=106 HYBRID_SUBNET_NO_ROUTE value + * @property {number} GKE_NETWORK_POLICY=108 GKE_NETWORK_POLICY value + * @property {number} NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION=110 NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION value */ DropInfo.Cause = (function() { var valuesById = {}, values = Object.create(valuesById); @@ -41679,6 +42745,8 @@ values[valuesById[104] = "NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED"] = 104; values[valuesById[105] = "HYBRID_SUBNET_REGION_MISMATCH"] = 105; values[valuesById[106] = "HYBRID_SUBNET_NO_ROUTE"] = 106; + values[valuesById[108] = "GKE_NETWORK_POLICY"] = 108; + values[valuesById[110] = "NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION"] = 110; return values; })(); @@ -42539,6 +43607,547 @@ return IpMasqueradingSkippedInfo; })(); + v1beta1.GkeNetworkPolicyInfo = (function() { + + /** + * Properties of a GkeNetworkPolicyInfo. + * @memberof google.cloud.networkmanagement.v1beta1 + * @interface IGkeNetworkPolicyInfo + * @property {string|null} [displayName] GkeNetworkPolicyInfo displayName + * @property {string|null} [uri] GkeNetworkPolicyInfo uri + * @property {string|null} [direction] GkeNetworkPolicyInfo direction + * @property {string|null} [action] GkeNetworkPolicyInfo action + */ + + /** + * Constructs a new GkeNetworkPolicyInfo. + * @memberof google.cloud.networkmanagement.v1beta1 + * @classdesc Represents a GkeNetworkPolicyInfo. + * @implements IGkeNetworkPolicyInfo + * @constructor + * @param {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo=} [properties] Properties to set + */ + function GkeNetworkPolicyInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GkeNetworkPolicyInfo displayName. + * @member {string} displayName + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @instance + */ + GkeNetworkPolicyInfo.prototype.displayName = ""; + + /** + * GkeNetworkPolicyInfo uri. + * @member {string} uri + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @instance + */ + GkeNetworkPolicyInfo.prototype.uri = ""; + + /** + * GkeNetworkPolicyInfo direction. + * @member {string} direction + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @instance + */ + GkeNetworkPolicyInfo.prototype.direction = ""; + + /** + * GkeNetworkPolicyInfo action. + * @member {string} action + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @instance + */ + GkeNetworkPolicyInfo.prototype.action = ""; + + /** + * Creates a new GkeNetworkPolicyInfo instance using the specified properties. + * @function create + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo=} [properties] Properties to set + * @returns {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo} GkeNetworkPolicyInfo instance + */ + GkeNetworkPolicyInfo.create = function create(properties) { + return new GkeNetworkPolicyInfo(properties); + }; + + /** + * Encodes the specified GkeNetworkPolicyInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo} message GkeNetworkPolicyInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GkeNetworkPolicyInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.displayName != null && Object.hasOwnProperty.call(message, "displayName")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.displayName); + if (message.uri != null && Object.hasOwnProperty.call(message, "uri")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.uri); + if (message.direction != null && Object.hasOwnProperty.call(message, "direction")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.direction); + if (message.action != null && Object.hasOwnProperty.call(message, "action")) + writer.uint32(/* id 4, wireType 2 =*/34).string(message.action); + return writer; + }; + + /** + * Encodes the specified GkeNetworkPolicyInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicyInfo} message GkeNetworkPolicyInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GkeNetworkPolicyInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GkeNetworkPolicyInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo} GkeNetworkPolicyInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GkeNetworkPolicyInfo.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.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.displayName = reader.string(); + break; + } + case 2: { + message.uri = reader.string(); + break; + } + case 3: { + message.direction = reader.string(); + break; + } + case 4: { + message.action = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GkeNetworkPolicyInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo} GkeNetworkPolicyInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GkeNetworkPolicyInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GkeNetworkPolicyInfo message. + * @function verify + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GkeNetworkPolicyInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.displayName != null && message.hasOwnProperty("displayName")) + if (!$util.isString(message.displayName)) + return "displayName: string expected"; + if (message.uri != null && message.hasOwnProperty("uri")) + if (!$util.isString(message.uri)) + return "uri: string expected"; + if (message.direction != null && message.hasOwnProperty("direction")) + if (!$util.isString(message.direction)) + return "direction: string expected"; + if (message.action != null && message.hasOwnProperty("action")) + if (!$util.isString(message.action)) + return "action: string expected"; + return null; + }; + + /** + * Creates a GkeNetworkPolicyInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo} GkeNetworkPolicyInfo + */ + GkeNetworkPolicyInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo) + return object; + var message = new $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo(); + if (object.displayName != null) + message.displayName = String(object.displayName); + if (object.uri != null) + message.uri = String(object.uri); + if (object.direction != null) + message.direction = String(object.direction); + if (object.action != null) + message.action = String(object.action); + return message; + }; + + /** + * Creates a plain object from a GkeNetworkPolicyInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo} message GkeNetworkPolicyInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GkeNetworkPolicyInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.displayName = ""; + object.uri = ""; + object.direction = ""; + object.action = ""; + } + if (message.displayName != null && message.hasOwnProperty("displayName")) + object.displayName = message.displayName; + if (message.uri != null && message.hasOwnProperty("uri")) + object.uri = message.uri; + if (message.direction != null && message.hasOwnProperty("direction")) + object.direction = message.direction; + if (message.action != null && message.hasOwnProperty("action")) + object.action = message.action; + return object; + }; + + /** + * Converts this GkeNetworkPolicyInfo to JSON. + * @function toJSON + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @instance + * @returns {Object.} JSON object + */ + GkeNetworkPolicyInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GkeNetworkPolicyInfo + * @function getTypeUrl + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GkeNetworkPolicyInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.networkmanagement.v1beta1.GkeNetworkPolicyInfo"; + }; + + return GkeNetworkPolicyInfo; + })(); + + v1beta1.GkeNetworkPolicySkippedInfo = (function() { + + /** + * Properties of a GkeNetworkPolicySkippedInfo. + * @memberof google.cloud.networkmanagement.v1beta1 + * @interface IGkeNetworkPolicySkippedInfo + * @property {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason|null} [reason] GkeNetworkPolicySkippedInfo reason + */ + + /** + * Constructs a new GkeNetworkPolicySkippedInfo. + * @memberof google.cloud.networkmanagement.v1beta1 + * @classdesc Represents a GkeNetworkPolicySkippedInfo. + * @implements IGkeNetworkPolicySkippedInfo + * @constructor + * @param {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo=} [properties] Properties to set + */ + function GkeNetworkPolicySkippedInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GkeNetworkPolicySkippedInfo reason. + * @member {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason} reason + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @instance + */ + GkeNetworkPolicySkippedInfo.prototype.reason = 0; + + /** + * Creates a new GkeNetworkPolicySkippedInfo instance using the specified properties. + * @function create + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo=} [properties] Properties to set + * @returns {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo} GkeNetworkPolicySkippedInfo instance + */ + GkeNetworkPolicySkippedInfo.create = function create(properties) { + return new GkeNetworkPolicySkippedInfo(properties); + }; + + /** + * Encodes the specified GkeNetworkPolicySkippedInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo} message GkeNetworkPolicySkippedInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GkeNetworkPolicySkippedInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.reason != null && Object.hasOwnProperty.call(message, "reason")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.reason); + return writer; + }; + + /** + * Encodes the specified GkeNetworkPolicySkippedInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.IGkeNetworkPolicySkippedInfo} message GkeNetworkPolicySkippedInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GkeNetworkPolicySkippedInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GkeNetworkPolicySkippedInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo} GkeNetworkPolicySkippedInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GkeNetworkPolicySkippedInfo.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.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.reason = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a GkeNetworkPolicySkippedInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo} GkeNetworkPolicySkippedInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GkeNetworkPolicySkippedInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GkeNetworkPolicySkippedInfo message. + * @function verify + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GkeNetworkPolicySkippedInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.reason != null && message.hasOwnProperty("reason")) + switch (message.reason) { + default: + return "reason: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 100: + break; + } + return null; + }; + + /** + * Creates a GkeNetworkPolicySkippedInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo} GkeNetworkPolicySkippedInfo + */ + GkeNetworkPolicySkippedInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo) + return object; + var message = new $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo(); + switch (object.reason) { + default: + if (typeof object.reason === "number") { + message.reason = object.reason; + break; + } + break; + case "REASON_UNSPECIFIED": + case 0: + message.reason = 0; + break; + case "NETWORK_POLICY_DISABLED": + case 1: + message.reason = 1; + break; + case "INGRESS_SOURCE_ON_SAME_NODE": + case 2: + message.reason = 2; + break; + case "EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD": + case 3: + message.reason = 3; + break; + case "NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC": + case 4: + message.reason = 4; + break; + case "NETWORK_POLICY_ANALYSIS_UNSUPPORTED": + case 100: + message.reason = 100; + break; + } + return message; + }; + + /** + * Creates a plain object from a GkeNetworkPolicySkippedInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo} message GkeNetworkPolicySkippedInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GkeNetworkPolicySkippedInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.reason = options.enums === String ? "REASON_UNSPECIFIED" : 0; + if (message.reason != null && message.hasOwnProperty("reason")) + object.reason = options.enums === String ? $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason[message.reason] === undefined ? message.reason : $root.google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason[message.reason] : message.reason; + return object; + }; + + /** + * Converts this GkeNetworkPolicySkippedInfo to JSON. + * @function toJSON + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @instance + * @returns {Object.} JSON object + */ + GkeNetworkPolicySkippedInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GkeNetworkPolicySkippedInfo + * @function getTypeUrl + * @memberof google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GkeNetworkPolicySkippedInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo"; + }; + + /** + * Reason enum. + * @name google.cloud.networkmanagement.v1beta1.GkeNetworkPolicySkippedInfo.Reason + * @enum {number} + * @property {number} REASON_UNSPECIFIED=0 REASON_UNSPECIFIED value + * @property {number} NETWORK_POLICY_DISABLED=1 NETWORK_POLICY_DISABLED value + * @property {number} INGRESS_SOURCE_ON_SAME_NODE=2 INGRESS_SOURCE_ON_SAME_NODE value + * @property {number} EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD=3 EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD value + * @property {number} NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC=4 NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC value + * @property {number} NETWORK_POLICY_ANALYSIS_UNSUPPORTED=100 NETWORK_POLICY_ANALYSIS_UNSUPPORTED value + */ + GkeNetworkPolicySkippedInfo.Reason = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "REASON_UNSPECIFIED"] = 0; + values[valuesById[1] = "NETWORK_POLICY_DISABLED"] = 1; + values[valuesById[2] = "INGRESS_SOURCE_ON_SAME_NODE"] = 2; + values[valuesById[3] = "EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD"] = 3; + values[valuesById[4] = "NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC"] = 4; + values[valuesById[100] = "NETWORK_POLICY_ANALYSIS_UNSUPPORTED"] = 100; + return values; + })(); + + return GkeNetworkPolicySkippedInfo; + })(); + v1beta1.CloudSQLInstanceInfo = (function() { /** @@ -47068,6 +48677,211 @@ return ServerlessNegInfo; })(); + v1beta1.NgfwPacketInspectionInfo = (function() { + + /** + * Properties of a NgfwPacketInspectionInfo. + * @memberof google.cloud.networkmanagement.v1beta1 + * @interface INgfwPacketInspectionInfo + * @property {string|null} [securityProfileGroupUri] NgfwPacketInspectionInfo securityProfileGroupUri + */ + + /** + * Constructs a new NgfwPacketInspectionInfo. + * @memberof google.cloud.networkmanagement.v1beta1 + * @classdesc Represents a NgfwPacketInspectionInfo. + * @implements INgfwPacketInspectionInfo + * @constructor + * @param {google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo=} [properties] Properties to set + */ + function NgfwPacketInspectionInfo(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * NgfwPacketInspectionInfo securityProfileGroupUri. + * @member {string} securityProfileGroupUri + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @instance + */ + NgfwPacketInspectionInfo.prototype.securityProfileGroupUri = ""; + + /** + * Creates a new NgfwPacketInspectionInfo instance using the specified properties. + * @function create + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo=} [properties] Properties to set + * @returns {google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo} NgfwPacketInspectionInfo instance + */ + NgfwPacketInspectionInfo.create = function create(properties) { + return new NgfwPacketInspectionInfo(properties); + }; + + /** + * Encodes the specified NgfwPacketInspectionInfo message. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.verify|verify} messages. + * @function encode + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo} message NgfwPacketInspectionInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NgfwPacketInspectionInfo.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.securityProfileGroupUri != null && Object.hasOwnProperty.call(message, "securityProfileGroupUri")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.securityProfileGroupUri); + return writer; + }; + + /** + * Encodes the specified NgfwPacketInspectionInfo message, length delimited. Does not implicitly {@link google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.INgfwPacketInspectionInfo} message NgfwPacketInspectionInfo message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + NgfwPacketInspectionInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a NgfwPacketInspectionInfo message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo} NgfwPacketInspectionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NgfwPacketInspectionInfo.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.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.securityProfileGroupUri = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a NgfwPacketInspectionInfo message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo} NgfwPacketInspectionInfo + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + NgfwPacketInspectionInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a NgfwPacketInspectionInfo message. + * @function verify + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + NgfwPacketInspectionInfo.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.securityProfileGroupUri != null && message.hasOwnProperty("securityProfileGroupUri")) + if (!$util.isString(message.securityProfileGroupUri)) + return "securityProfileGroupUri: string expected"; + return null; + }; + + /** + * Creates a NgfwPacketInspectionInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo} NgfwPacketInspectionInfo + */ + NgfwPacketInspectionInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo) + return object; + var message = new $root.google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo(); + if (object.securityProfileGroupUri != null) + message.securityProfileGroupUri = String(object.securityProfileGroupUri); + return message; + }; + + /** + * Creates a plain object from a NgfwPacketInspectionInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo} message NgfwPacketInspectionInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NgfwPacketInspectionInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.securityProfileGroupUri = ""; + if (message.securityProfileGroupUri != null && message.hasOwnProperty("securityProfileGroupUri")) + object.securityProfileGroupUri = message.securityProfileGroupUri; + return object; + }; + + /** + * Converts this NgfwPacketInspectionInfo to JSON. + * @function toJSON + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @instance + * @returns {Object.} JSON object + */ + NgfwPacketInspectionInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NgfwPacketInspectionInfo + * @function getTypeUrl + * @memberof google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NgfwPacketInspectionInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.networkmanagement.v1beta1.NgfwPacketInspectionInfo"; + }; + + return NgfwPacketInspectionInfo; + })(); + v1beta1.ReachabilityService = (function() { /** diff --git a/packages/google-cloud-networkmanagement/protos/protos.json b/packages/google-cloud-networkmanagement/protos/protos.json index 9887ff7e64c..59297a19541 100644 --- a/packages/google-cloud-networkmanagement/protos/protos.json +++ b/packages/google-cloud-networkmanagement/protos/protos.json @@ -474,6 +474,8 @@ "gkeMaster", "gkePod", "ipMasqueradingSkipped", + "gkeNetworkPolicy", + "gkeNetworkPolicySkipped", "cloudSqlInstance", "redisInstance", "redisCluster", @@ -484,7 +486,8 @@ "proxyConnection", "loadBalancerBackendInfo", "storageBucket", - "serverlessNeg" + "serverlessNeg", + "ngfwPacketInspection" ] } }, @@ -596,6 +599,14 @@ "type": "IpMasqueradingSkippedInfo", "id": 38 }, + "gkeNetworkPolicy": { + "type": "GkeNetworkPolicyInfo", + "id": 39 + }, + "gkeNetworkPolicySkipped": { + "type": "GkeNetworkPolicySkippedInfo", + "id": 40 + }, "cloudSqlInstance": { "type": "CloudSQLInstanceInfo", "id": 19 @@ -639,6 +650,10 @@ "serverlessNeg": { "type": "ServerlessNegInfo", "id": 29 + }, + "ngfwPacketInspection": { + "type": "NgfwPacketInspectionInfo", + "id": 42 } }, "nested": { @@ -682,10 +697,16 @@ "ARRIVE_AT_VPN_TUNNEL": 13, "ARRIVE_AT_INTERCONNECT_ATTACHMENT": 37, "ARRIVE_AT_VPC_CONNECTOR": 24, + "ARRIVE_AT_GKE_POD": 44, "DIRECT_VPC_EGRESS_CONNECTION": 35, "SERVERLESS_EXTERNAL_CONNECTION": 36, + "NGFW_PACKET_INSPECTION": 47, "NAT": 14, "SKIP_GKE_POD_IP_MASQUERADING": 40, + "SKIP_GKE_INGRESS_NETWORK_POLICY": 41, + "SKIP_GKE_EGRESS_NETWORK_POLICY": 42, + "APPLY_INGRESS_GKE_NETWORK_POLICY": 45, + "APPLY_EGRESS_GKE_NETWORK_POLICY": 46, "PROXY_CONNECTION": 15, "DELIVER": 16, "DROP": 17, @@ -1731,7 +1752,9 @@ "L2_INTERCONNECT_DESTINATION_IP_MISMATCH": 102, "NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED": 104, "HYBRID_SUBNET_REGION_MISMATCH": 105, - "HYBRID_SUBNET_NO_ROUTE": 106 + "HYBRID_SUBNET_NO_ROUTE": 106, + "GKE_NETWORK_POLICY": 108, + "NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION": 110 } } } @@ -1805,6 +1828,46 @@ } } }, + "GkeNetworkPolicyInfo": { + "fields": { + "displayName": { + "type": "string", + "id": 1 + }, + "uri": { + "type": "string", + "id": 2 + }, + "direction": { + "type": "string", + "id": 3 + }, + "action": { + "type": "string", + "id": 4 + } + } + }, + "GkeNetworkPolicySkippedInfo": { + "fields": { + "reason": { + "type": "Reason", + "id": 1 + } + }, + "nested": { + "Reason": { + "values": { + "REASON_UNSPECIFIED": 0, + "NETWORK_POLICY_DISABLED": 1, + "INGRESS_SOURCE_ON_SAME_NODE": 2, + "EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD": 3, + "NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC": 4, + "NETWORK_POLICY_ANALYSIS_UNSUPPORTED": 100 + } + } + } + }, "CloudSQLInstanceInfo": { "fields": { "displayName": { @@ -2231,6 +2294,14 @@ } } }, + "NgfwPacketInspectionInfo": { + "fields": { + "securityProfileGroupUri": { + "type": "string", + "id": 1 + } + } + }, "ReachabilityService": { "options": { "(google.api.default_host)": "networkmanagement.googleapis.com", @@ -3880,6 +3951,8 @@ "gkeMaster", "gkePod", "ipMasqueradingSkipped", + "gkeNetworkPolicy", + "gkeNetworkPolicySkipped", "cloudSqlInstance", "redisInstance", "redisCluster", @@ -3890,7 +3963,8 @@ "proxyConnection", "loadBalancerBackendInfo", "storageBucket", - "serverlessNeg" + "serverlessNeg", + "ngfwPacketInspection" ] } }, @@ -4002,6 +4076,14 @@ "type": "IpMasqueradingSkippedInfo", "id": 38 }, + "gkeNetworkPolicy": { + "type": "GkeNetworkPolicyInfo", + "id": 39 + }, + "gkeNetworkPolicySkipped": { + "type": "GkeNetworkPolicySkippedInfo", + "id": 40 + }, "cloudSqlInstance": { "type": "CloudSQLInstanceInfo", "id": 19 @@ -4045,6 +4127,10 @@ "serverlessNeg": { "type": "ServerlessNegInfo", "id": 29 + }, + "ngfwPacketInspection": { + "type": "NgfwPacketInspectionInfo", + "id": 42 } }, "nested": { @@ -4088,10 +4174,16 @@ "ARRIVE_AT_VPN_TUNNEL": 13, "ARRIVE_AT_INTERCONNECT_ATTACHMENT": 37, "ARRIVE_AT_VPC_CONNECTOR": 24, + "ARRIVE_AT_GKE_POD": 44, "DIRECT_VPC_EGRESS_CONNECTION": 35, "SERVERLESS_EXTERNAL_CONNECTION": 36, + "NGFW_PACKET_INSPECTION": 47, "NAT": 14, "SKIP_GKE_POD_IP_MASQUERADING": 40, + "SKIP_GKE_INGRESS_NETWORK_POLICY": 41, + "SKIP_GKE_EGRESS_NETWORK_POLICY": 42, + "APPLY_INGRESS_GKE_NETWORK_POLICY": 45, + "APPLY_EGRESS_GKE_NETWORK_POLICY": 46, "PROXY_CONNECTION": 15, "DELIVER": 16, "DROP": 17, @@ -5137,7 +5229,9 @@ "L2_INTERCONNECT_DESTINATION_IP_MISMATCH": 102, "NCC_ROUTE_WITHIN_HYBRID_SUBNET_UNSUPPORTED": 104, "HYBRID_SUBNET_REGION_MISMATCH": 105, - "HYBRID_SUBNET_NO_ROUTE": 106 + "HYBRID_SUBNET_NO_ROUTE": 106, + "GKE_NETWORK_POLICY": 108, + "NO_VALID_ROUTE_FROM_GOOGLE_MANAGED_NETWORK_TO_DESTINATION": 110 } } } @@ -5211,6 +5305,46 @@ } } }, + "GkeNetworkPolicyInfo": { + "fields": { + "displayName": { + "type": "string", + "id": 1 + }, + "uri": { + "type": "string", + "id": 2 + }, + "direction": { + "type": "string", + "id": 3 + }, + "action": { + "type": "string", + "id": 4 + } + } + }, + "GkeNetworkPolicySkippedInfo": { + "fields": { + "reason": { + "type": "Reason", + "id": 1 + } + }, + "nested": { + "Reason": { + "values": { + "REASON_UNSPECIFIED": 0, + "NETWORK_POLICY_DISABLED": 1, + "INGRESS_SOURCE_ON_SAME_NODE": 2, + "EGRESS_FROM_NODE_NETWORK_NAMESPACE_POD": 3, + "NETWORK_POLICY_NOT_APPLIED_TO_RESPONSE_TRAFFIC": 4, + "NETWORK_POLICY_ANALYSIS_UNSUPPORTED": 100 + } + } + } + }, "CloudSQLInstanceInfo": { "fields": { "displayName": { @@ -5637,6 +5771,14 @@ } } }, + "NgfwPacketInspectionInfo": { + "fields": { + "securityProfileGroupUri": { + "type": "string", + "id": 1 + } + } + }, "ReachabilityService": { "options": { "(google.api.default_host)": "networkmanagement.googleapis.com", diff --git a/packages/google-cloud-networkmanagement/samples/package.json b/packages/google-cloud-networkmanagement/samples/package.json index 868d1d402fa..1b4f473ce43 100644 --- a/packages/google-cloud-networkmanagement/samples/package.json +++ b/packages/google-cloud-networkmanagement/samples/package.json @@ -13,7 +13,7 @@ "test": "c8 mocha --timeout 600000 test/*.js" }, "dependencies": { - "@google-cloud/network-management": "^5.2.0" + "@google-cloud/network-management": "^5.3.0" }, "devDependencies": { "c8": "^10.0.0", diff --git a/packages/google-cloud-speech/CHANGELOG.md b/packages/google-cloud-speech/CHANGELOG.md index 541c13b3a9c..ba4ec5f4845 100644 --- a/packages/google-cloud-speech/CHANGELOG.md +++ b/packages/google-cloud-speech/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://www.npmjs.com/package/@google-cloud/speech?activeTab=versions +## [7.3.0](https://github.com/googleapis/google-cloud-node/compare/speech-v7.2.1...speech-v7.3.0) (2026-03-02) + + +### Features + +* Adds endpointing sensitivity to streaming recognition features ([#7270](https://github.com/googleapis/google-cloud-node/issues/7270)) ([4373c58](https://github.com/googleapis/google-cloud-node/commit/4373c581d895ad3785f1b3493bda83def6a0024c)) + ## [7.2.1](https://github.com/googleapis/google-cloud-node/compare/speech-v7.2.0...speech-v7.2.1) (2025-10-13) diff --git a/packages/google-cloud-speech/package.json b/packages/google-cloud-speech/package.json index 0f14ae701b2..b2334eb1351 100644 --- a/packages/google-cloud-speech/package.json +++ b/packages/google-cloud-speech/package.json @@ -1,7 +1,7 @@ { "name": "@google-cloud/speech", "description": "Cloud Speech Client Library for Node.js", - "version": "7.2.1", + "version": "7.3.0", "license": "Apache-2.0", "author": "Google Inc.", "engines": { diff --git a/packages/google-cloud-speech/samples/package.json b/packages/google-cloud-speech/samples/package.json index 8346d4ff3b6..a134f15b273 100644 --- a/packages/google-cloud-speech/samples/package.json +++ b/packages/google-cloud-speech/samples/package.json @@ -15,7 +15,7 @@ "test": "c8 mocha test --timeout 600000" }, "dependencies": { - "@google-cloud/speech": "^7.2.1", + "@google-cloud/speech": "^7.3.0", "@google-cloud/storage": "^7.0.0", "chalk": "^5.0.0", "fs.promises": "^0.1.2", diff --git a/packages/google-cloud-storagebatchoperations/CHANGELOG.md b/packages/google-cloud-storagebatchoperations/CHANGELOG.md index e321d4a12ce..f1e21acd4ea 100644 --- a/packages/google-cloud-storagebatchoperations/CHANGELOG.md +++ b/packages/google-cloud-storagebatchoperations/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.0](https://github.com/googleapis/google-cloud-node/compare/storagebatchoperations-v0.2.0...storagebatchoperations-v0.3.0) (2026-03-02) + + +### Features + +* [storagebatchoperations] add new transformation `update_object_custom_context` ([#7309](https://github.com/googleapis/google-cloud-node/issues/7309)) ([4b8da3e](https://github.com/googleapis/google-cloud-node/commit/4b8da3eefef2c4af0f39f186b4d60257fa146eae)) + ## [0.2.0](https://github.com/googleapis/google-cloud-node/compare/storagebatchoperations-v0.1.1...storagebatchoperations-v0.2.0) (2026-02-19) diff --git a/packages/google-cloud-storagebatchoperations/package.json b/packages/google-cloud-storagebatchoperations/package.json index 7a5195e8593..8c79f2364de 100644 --- a/packages/google-cloud-storagebatchoperations/package.json +++ b/packages/google-cloud-storagebatchoperations/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/storagebatchoperations", - "version": "0.2.0", + "version": "0.3.0", "description": "Storage Batch Operations API client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-storagebatchoperations/protos/google/cloud/storagebatchoperations/v1/storage_batch_operations_types.proto b/packages/google-cloud-storagebatchoperations/protos/google/cloud/storagebatchoperations/v1/storage_batch_operations_types.proto index f661216bcb3..d403da26b62 100644 --- a/packages/google-cloud-storagebatchoperations/protos/google/cloud/storagebatchoperations/v1/storage_batch_operations_types.proto +++ b/packages/google-cloud-storagebatchoperations/protos/google/cloud/storagebatchoperations/v1/storage_batch_operations_types.proto @@ -95,6 +95,9 @@ message Job { // Rewrite the object and updates metadata like KMS key. RewriteObject rewrite_object = 20; + + // Update object custom context. + UpdateObjectCustomContext update_object_custom_context = 23; } // Optional. Logging configuration. @@ -194,6 +197,9 @@ message BucketOperation { // Rewrite the object and updates metadata like KMS key. RewriteObject rewrite_object = 14; + + // Update object custom context. + UpdateObjectCustomContext update_object_custom_context = 15; } // Output only. The time that the BucketOperation was created. @@ -407,6 +413,41 @@ message PutMetadata { [(google.api.field_behavior) = OPTIONAL]; } +// Describes the payload of a user defined object custom context. +message ObjectCustomContextPayload { + // The value of the object custom context. + // If set, `value` must NOT be an empty string since it is a required field in + // custom context. If unset, `value` will be ignored and no changes will be + // made to the `value` field of the custom context payload. + optional string value = 1; +} + +// Describes a collection of updates to apply to custom contexts identified +// by key. +message CustomContextUpdates { + // Optional. Insert or update the existing custom contexts. + map updates = 1 + [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Custom contexts to clear by key. + // A key cannot be present in both `updates` and `keys_to_clear`. + repeated string keys_to_clear = 2 [(google.api.field_behavior) = OPTIONAL]; +} + +// Describes options to update object custom contexts. +message UpdateObjectCustomContext { + // One of the actions must be set. + oneof action { + // A collection of updates to apply to specific custom contexts. + // Use this to add, update or delete individual contexts by key. + CustomContextUpdates custom_context_updates = 1; + + // If set, must be set to true and all existing object custom contexts will + // be deleted. + bool clear_all = 2; + } +} + // A summary of errors by error code, plus a count and sample error log // entries. message ErrorSummary { diff --git a/packages/google-cloud-storagebatchoperations/protos/protos.d.ts b/packages/google-cloud-storagebatchoperations/protos/protos.d.ts index 049a6feeb12..18ae7b8cf2c 100644 --- a/packages/google-cloud-storagebatchoperations/protos/protos.d.ts +++ b/packages/google-cloud-storagebatchoperations/protos/protos.d.ts @@ -1420,6 +1420,9 @@ export namespace google { /** Job rewriteObject */ rewriteObject?: (google.cloud.storagebatchoperations.v1.IRewriteObject|null); + /** Job updateObjectCustomContext */ + updateObjectCustomContext?: (google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext|null); + /** Job loggingConfig */ loggingConfig?: (google.cloud.storagebatchoperations.v1.ILoggingConfig|null); @@ -1478,6 +1481,9 @@ export namespace google { /** Job rewriteObject. */ public rewriteObject?: (google.cloud.storagebatchoperations.v1.IRewriteObject|null); + /** Job updateObjectCustomContext. */ + public updateObjectCustomContext?: (google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext|null); + /** Job loggingConfig. */ public loggingConfig?: (google.cloud.storagebatchoperations.v1.ILoggingConfig|null); @@ -1509,7 +1515,7 @@ export namespace google { public source?: "bucketList"; /** Job transformation. */ - public transformation?: ("putObjectHold"|"deleteObject"|"putMetadata"|"rewriteObject"); + public transformation?: ("putObjectHold"|"deleteObject"|"putMetadata"|"rewriteObject"|"updateObjectCustomContext"); /** * Creates a new Job instance using the specified properties. @@ -1629,6 +1635,9 @@ export namespace google { /** BucketOperation rewriteObject */ rewriteObject?: (google.cloud.storagebatchoperations.v1.IRewriteObject|null); + /** BucketOperation updateObjectCustomContext */ + updateObjectCustomContext?: (google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext|null); + /** BucketOperation createTime */ createTime?: (google.protobuf.ITimestamp|null); @@ -1681,6 +1690,9 @@ export namespace google { /** BucketOperation rewriteObject. */ public rewriteObject?: (google.cloud.storagebatchoperations.v1.IRewriteObject|null); + /** BucketOperation updateObjectCustomContext. */ + public updateObjectCustomContext?: (google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext|null); + /** BucketOperation createTime. */ public createTime?: (google.protobuf.ITimestamp|null); @@ -1703,7 +1715,7 @@ export namespace google { public objectConfiguration?: ("prefixList"|"manifest"); /** BucketOperation transformation. */ - public transformation?: ("putObjectHold"|"deleteObject"|"putMetadata"|"rewriteObject"); + public transformation?: ("putObjectHold"|"deleteObject"|"putMetadata"|"rewriteObject"|"updateObjectCustomContext"); /** * Creates a new BucketOperation instance using the specified properties. @@ -2761,6 +2773,312 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an ObjectCustomContextPayload. */ + interface IObjectCustomContextPayload { + + /** ObjectCustomContextPayload value */ + value?: (string|null); + } + + /** Represents an ObjectCustomContextPayload. */ + class ObjectCustomContextPayload implements IObjectCustomContextPayload { + + /** + * Constructs a new ObjectCustomContextPayload. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload); + + /** ObjectCustomContextPayload value. */ + public value?: (string|null); + + /** + * Creates a new ObjectCustomContextPayload instance using the specified properties. + * @param [properties] Properties to set + * @returns ObjectCustomContextPayload instance + */ + public static create(properties?: google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload): google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload; + + /** + * Encodes the specified ObjectCustomContextPayload message. Does not implicitly {@link google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.verify|verify} messages. + * @param message ObjectCustomContextPayload message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ObjectCustomContextPayload message, length delimited. Does not implicitly {@link google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.verify|verify} messages. + * @param message ObjectCustomContextPayload message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ObjectCustomContextPayload message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ObjectCustomContextPayload + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload; + + /** + * Decodes an ObjectCustomContextPayload message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ObjectCustomContextPayload + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload; + + /** + * Verifies an ObjectCustomContextPayload message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ObjectCustomContextPayload message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ObjectCustomContextPayload + */ + public static fromObject(object: { [k: string]: any }): google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload; + + /** + * Creates a plain object from an ObjectCustomContextPayload message. Also converts values to other types if specified. + * @param message ObjectCustomContextPayload + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ObjectCustomContextPayload to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ObjectCustomContextPayload + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomContextUpdates. */ + interface ICustomContextUpdates { + + /** CustomContextUpdates updates */ + updates?: ({ [k: string]: google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload }|null); + + /** CustomContextUpdates keysToClear */ + keysToClear?: (string[]|null); + } + + /** Represents a CustomContextUpdates. */ + class CustomContextUpdates implements ICustomContextUpdates { + + /** + * Constructs a new CustomContextUpdates. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.storagebatchoperations.v1.ICustomContextUpdates); + + /** CustomContextUpdates updates. */ + public updates: { [k: string]: google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload }; + + /** CustomContextUpdates keysToClear. */ + public keysToClear: string[]; + + /** + * Creates a new CustomContextUpdates instance using the specified properties. + * @param [properties] Properties to set + * @returns CustomContextUpdates instance + */ + public static create(properties?: google.cloud.storagebatchoperations.v1.ICustomContextUpdates): google.cloud.storagebatchoperations.v1.CustomContextUpdates; + + /** + * Encodes the specified CustomContextUpdates message. Does not implicitly {@link google.cloud.storagebatchoperations.v1.CustomContextUpdates.verify|verify} messages. + * @param message CustomContextUpdates message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.storagebatchoperations.v1.ICustomContextUpdates, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CustomContextUpdates message, length delimited. Does not implicitly {@link google.cloud.storagebatchoperations.v1.CustomContextUpdates.verify|verify} messages. + * @param message CustomContextUpdates message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.storagebatchoperations.v1.ICustomContextUpdates, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CustomContextUpdates message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CustomContextUpdates + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.storagebatchoperations.v1.CustomContextUpdates; + + /** + * Decodes a CustomContextUpdates message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CustomContextUpdates + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.storagebatchoperations.v1.CustomContextUpdates; + + /** + * Verifies a CustomContextUpdates message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CustomContextUpdates message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomContextUpdates + */ + public static fromObject(object: { [k: string]: any }): google.cloud.storagebatchoperations.v1.CustomContextUpdates; + + /** + * Creates a plain object from a CustomContextUpdates message. Also converts values to other types if specified. + * @param message CustomContextUpdates + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.storagebatchoperations.v1.CustomContextUpdates, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomContextUpdates to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomContextUpdates + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateObjectCustomContext. */ + interface IUpdateObjectCustomContext { + + /** UpdateObjectCustomContext customContextUpdates */ + customContextUpdates?: (google.cloud.storagebatchoperations.v1.ICustomContextUpdates|null); + + /** UpdateObjectCustomContext clearAll */ + clearAll?: (boolean|null); + } + + /** Represents an UpdateObjectCustomContext. */ + class UpdateObjectCustomContext implements IUpdateObjectCustomContext { + + /** + * Constructs a new UpdateObjectCustomContext. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext); + + /** UpdateObjectCustomContext customContextUpdates. */ + public customContextUpdates?: (google.cloud.storagebatchoperations.v1.ICustomContextUpdates|null); + + /** UpdateObjectCustomContext clearAll. */ + public clearAll?: (boolean|null); + + /** UpdateObjectCustomContext action. */ + public action?: ("customContextUpdates"|"clearAll"); + + /** + * Creates a new UpdateObjectCustomContext instance using the specified properties. + * @param [properties] Properties to set + * @returns UpdateObjectCustomContext instance + */ + public static create(properties?: google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext): google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext; + + /** + * Encodes the specified UpdateObjectCustomContext message. Does not implicitly {@link google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.verify|verify} messages. + * @param message UpdateObjectCustomContext message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified UpdateObjectCustomContext message, length delimited. Does not implicitly {@link google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.verify|verify} messages. + * @param message UpdateObjectCustomContext message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an UpdateObjectCustomContext message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns UpdateObjectCustomContext + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext; + + /** + * Decodes an UpdateObjectCustomContext message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns UpdateObjectCustomContext + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext; + + /** + * Verifies an UpdateObjectCustomContext message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an UpdateObjectCustomContext message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateObjectCustomContext + */ + public static fromObject(object: { [k: string]: any }): google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext; + + /** + * Creates a plain object from an UpdateObjectCustomContext message. Also converts values to other types if specified. + * @param message UpdateObjectCustomContext + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateObjectCustomContext to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateObjectCustomContext + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an ErrorSummary. */ interface IErrorSummary { diff --git a/packages/google-cloud-storagebatchoperations/protos/protos.js b/packages/google-cloud-storagebatchoperations/protos/protos.js index dbb142bc29d..4d5317ab2f7 100644 --- a/packages/google-cloud-storagebatchoperations/protos/protos.js +++ b/packages/google-cloud-storagebatchoperations/protos/protos.js @@ -3205,6 +3205,7 @@ * @property {google.cloud.storagebatchoperations.v1.IDeleteObject|null} [deleteObject] Job deleteObject * @property {google.cloud.storagebatchoperations.v1.IPutMetadata|null} [putMetadata] Job putMetadata * @property {google.cloud.storagebatchoperations.v1.IRewriteObject|null} [rewriteObject] Job rewriteObject + * @property {google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext|null} [updateObjectCustomContext] Job updateObjectCustomContext * @property {google.cloud.storagebatchoperations.v1.ILoggingConfig|null} [loggingConfig] Job loggingConfig * @property {google.protobuf.ITimestamp|null} [createTime] Job createTime * @property {google.protobuf.ITimestamp|null} [scheduleTime] Job scheduleTime @@ -3288,6 +3289,14 @@ */ Job.prototype.rewriteObject = null; + /** + * Job updateObjectCustomContext. + * @member {google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext|null|undefined} updateObjectCustomContext + * @memberof google.cloud.storagebatchoperations.v1.Job + * @instance + */ + Job.prototype.updateObjectCustomContext = null; + /** * Job loggingConfig. * @member {google.cloud.storagebatchoperations.v1.ILoggingConfig|null|undefined} loggingConfig @@ -3376,12 +3385,12 @@ /** * Job transformation. - * @member {"putObjectHold"|"deleteObject"|"putMetadata"|"rewriteObject"|undefined} transformation + * @member {"putObjectHold"|"deleteObject"|"putMetadata"|"rewriteObject"|"updateObjectCustomContext"|undefined} transformation * @memberof google.cloud.storagebatchoperations.v1.Job * @instance */ Object.defineProperty(Job.prototype, "transformation", { - get: $util.oneOfGetter($oneOfFields = ["putObjectHold", "deleteObject", "putMetadata", "rewriteObject"]), + get: $util.oneOfGetter($oneOfFields = ["putObjectHold", "deleteObject", "putMetadata", "rewriteObject", "updateObjectCustomContext"]), set: $util.oneOfSetter($oneOfFields) }); @@ -3440,6 +3449,8 @@ $root.google.cloud.storagebatchoperations.v1.RewriteObject.encode(message.rewriteObject, writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); if (message.dryRun != null && Object.hasOwnProperty.call(message, "dryRun")) writer.uint32(/* id 22, wireType 0 =*/176).bool(message.dryRun); + if (message.updateObjectCustomContext != null && Object.hasOwnProperty.call(message, "updateObjectCustomContext")) + $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.encode(message.updateObjectCustomContext, writer.uint32(/* id 23, wireType 2 =*/186).fork()).ldelim(); if (message.isMultiBucketJob != null && Object.hasOwnProperty.call(message, "isMultiBucketJob")) writer.uint32(/* id 24, wireType 0 =*/192).bool(message.isMultiBucketJob); return writer; @@ -3506,6 +3517,10 @@ message.rewriteObject = $root.google.cloud.storagebatchoperations.v1.RewriteObject.decode(reader, reader.uint32()); break; } + case 23: { + message.updateObjectCustomContext = $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.decode(reader, reader.uint32()); + break; + } case 9: { message.loggingConfig = $root.google.cloud.storagebatchoperations.v1.LoggingConfig.decode(reader, reader.uint32()); break; @@ -3632,6 +3647,16 @@ return "rewriteObject." + error; } } + if (message.updateObjectCustomContext != null && message.hasOwnProperty("updateObjectCustomContext")) { + if (properties.transformation === 1) + return "transformation: multiple values"; + properties.transformation = 1; + { + var error = $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.verify(message.updateObjectCustomContext); + if (error) + return "updateObjectCustomContext." + error; + } + } if (message.loggingConfig != null && message.hasOwnProperty("loggingConfig")) { var error = $root.google.cloud.storagebatchoperations.v1.LoggingConfig.verify(message.loggingConfig); if (error) @@ -3728,6 +3753,11 @@ throw TypeError(".google.cloud.storagebatchoperations.v1.Job.rewriteObject: object expected"); message.rewriteObject = $root.google.cloud.storagebatchoperations.v1.RewriteObject.fromObject(object.rewriteObject); } + if (object.updateObjectCustomContext != null) { + if (typeof object.updateObjectCustomContext !== "object") + throw TypeError(".google.cloud.storagebatchoperations.v1.Job.updateObjectCustomContext: object expected"); + message.updateObjectCustomContext = $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.fromObject(object.updateObjectCustomContext); + } if (object.loggingConfig != null) { if (typeof object.loggingConfig !== "object") throw TypeError(".google.cloud.storagebatchoperations.v1.Job.loggingConfig: object expected"); @@ -3877,6 +3907,11 @@ } if (message.dryRun != null && message.hasOwnProperty("dryRun")) object.dryRun = message.dryRun; + if (message.updateObjectCustomContext != null && message.hasOwnProperty("updateObjectCustomContext")) { + object.updateObjectCustomContext = $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.toObject(message.updateObjectCustomContext, options); + if (options.oneofs) + object.transformation = "updateObjectCustomContext"; + } if (message.isMultiBucketJob != null && message.hasOwnProperty("isMultiBucketJob")) object.isMultiBucketJob = message.isMultiBucketJob; return object; @@ -3947,6 +3982,7 @@ * @property {google.cloud.storagebatchoperations.v1.IDeleteObject|null} [deleteObject] BucketOperation deleteObject * @property {google.cloud.storagebatchoperations.v1.IPutMetadata|null} [putMetadata] BucketOperation putMetadata * @property {google.cloud.storagebatchoperations.v1.IRewriteObject|null} [rewriteObject] BucketOperation rewriteObject + * @property {google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext|null} [updateObjectCustomContext] BucketOperation updateObjectCustomContext * @property {google.protobuf.ITimestamp|null} [createTime] BucketOperation createTime * @property {google.protobuf.ITimestamp|null} [startTime] BucketOperation startTime * @property {google.protobuf.ITimestamp|null} [completeTime] BucketOperation completeTime @@ -4035,6 +4071,14 @@ */ BucketOperation.prototype.rewriteObject = null; + /** + * BucketOperation updateObjectCustomContext. + * @member {google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext|null|undefined} updateObjectCustomContext + * @memberof google.cloud.storagebatchoperations.v1.BucketOperation + * @instance + */ + BucketOperation.prototype.updateObjectCustomContext = null; + /** * BucketOperation createTime. * @member {google.protobuf.ITimestamp|null|undefined} createTime @@ -4099,12 +4143,12 @@ /** * BucketOperation transformation. - * @member {"putObjectHold"|"deleteObject"|"putMetadata"|"rewriteObject"|undefined} transformation + * @member {"putObjectHold"|"deleteObject"|"putMetadata"|"rewriteObject"|"updateObjectCustomContext"|undefined} transformation * @memberof google.cloud.storagebatchoperations.v1.BucketOperation * @instance */ Object.defineProperty(BucketOperation.prototype, "transformation", { - get: $util.oneOfGetter($oneOfFields = ["putObjectHold", "deleteObject", "putMetadata", "rewriteObject"]), + get: $util.oneOfGetter($oneOfFields = ["putObjectHold", "deleteObject", "putMetadata", "rewriteObject", "updateObjectCustomContext"]), set: $util.oneOfSetter($oneOfFields) }); @@ -4161,6 +4205,8 @@ $root.google.cloud.storagebatchoperations.v1.PutMetadata.encode(message.putMetadata, writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim(); if (message.rewriteObject != null && Object.hasOwnProperty.call(message, "rewriteObject")) $root.google.cloud.storagebatchoperations.v1.RewriteObject.encode(message.rewriteObject, writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim(); + if (message.updateObjectCustomContext != null && Object.hasOwnProperty.call(message, "updateObjectCustomContext")) + $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.encode(message.updateObjectCustomContext, writer.uint32(/* id 15, wireType 2 =*/122).fork()).ldelim(); return writer; }; @@ -4229,6 +4275,10 @@ message.rewriteObject = $root.google.cloud.storagebatchoperations.v1.RewriteObject.decode(reader, reader.uint32()); break; } + case 15: { + message.updateObjectCustomContext = $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.decode(reader, reader.uint32()); + break; + } case 5: { message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32()); break; @@ -4353,6 +4403,16 @@ return "rewriteObject." + error; } } + if (message.updateObjectCustomContext != null && message.hasOwnProperty("updateObjectCustomContext")) { + if (properties.transformation === 1) + return "transformation: multiple values"; + properties.transformation = 1; + { + var error = $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.verify(message.updateObjectCustomContext); + if (error) + return "updateObjectCustomContext." + error; + } + } if (message.createTime != null && message.hasOwnProperty("createTime")) { var error = $root.google.protobuf.Timestamp.verify(message.createTime); if (error) @@ -4443,6 +4503,11 @@ throw TypeError(".google.cloud.storagebatchoperations.v1.BucketOperation.rewriteObject: object expected"); message.rewriteObject = $root.google.cloud.storagebatchoperations.v1.RewriteObject.fromObject(object.rewriteObject); } + if (object.updateObjectCustomContext != null) { + if (typeof object.updateObjectCustomContext !== "object") + throw TypeError(".google.cloud.storagebatchoperations.v1.BucketOperation.updateObjectCustomContext: object expected"); + message.updateObjectCustomContext = $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.fromObject(object.updateObjectCustomContext); + } if (object.createTime != null) { if (typeof object.createTime !== "object") throw TypeError(".google.cloud.storagebatchoperations.v1.BucketOperation.createTime: object expected"); @@ -4581,6 +4646,11 @@ if (options.oneofs) object.transformation = "rewriteObject"; } + if (message.updateObjectCustomContext != null && message.hasOwnProperty("updateObjectCustomContext")) { + object.updateObjectCustomContext = $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.toObject(message.updateObjectCustomContext, options); + if (options.oneofs) + object.transformation = "updateObjectCustomContext"; + } return object; }; @@ -7063,6 +7133,769 @@ return PutMetadata; })(); + v1.ObjectCustomContextPayload = (function() { + + /** + * Properties of an ObjectCustomContextPayload. + * @memberof google.cloud.storagebatchoperations.v1 + * @interface IObjectCustomContextPayload + * @property {string|null} [value] ObjectCustomContextPayload value + */ + + /** + * Constructs a new ObjectCustomContextPayload. + * @memberof google.cloud.storagebatchoperations.v1 + * @classdesc Represents an ObjectCustomContextPayload. + * @implements IObjectCustomContextPayload + * @constructor + * @param {google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload=} [properties] Properties to set + */ + function ObjectCustomContextPayload(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ObjectCustomContextPayload value. + * @member {string|null|undefined} value + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @instance + */ + ObjectCustomContextPayload.prototype.value = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + // Virtual OneOf for proto3 optional field + Object.defineProperty(ObjectCustomContextPayload.prototype, "_value", { + get: $util.oneOfGetter($oneOfFields = ["value"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ObjectCustomContextPayload instance using the specified properties. + * @function create + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload=} [properties] Properties to set + * @returns {google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload} ObjectCustomContextPayload instance + */ + ObjectCustomContextPayload.create = function create(properties) { + return new ObjectCustomContextPayload(properties); + }; + + /** + * Encodes the specified ObjectCustomContextPayload message. Does not implicitly {@link google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.verify|verify} messages. + * @function encode + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload} message ObjectCustomContextPayload message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ObjectCustomContextPayload.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.value != null && Object.hasOwnProperty.call(message, "value")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.value); + return writer; + }; + + /** + * Encodes the specified ObjectCustomContextPayload message, length delimited. Does not implicitly {@link google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {google.cloud.storagebatchoperations.v1.IObjectCustomContextPayload} message ObjectCustomContextPayload message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ObjectCustomContextPayload.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ObjectCustomContextPayload message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload} ObjectCustomContextPayload + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ObjectCustomContextPayload.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.cloud.storagebatchoperations.v1.ObjectCustomContextPayload(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.value = reader.string(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ObjectCustomContextPayload message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload} ObjectCustomContextPayload + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ObjectCustomContextPayload.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ObjectCustomContextPayload message. + * @function verify + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ObjectCustomContextPayload.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.value != null && message.hasOwnProperty("value")) { + properties._value = 1; + if (!$util.isString(message.value)) + return "value: string expected"; + } + return null; + }; + + /** + * Creates an ObjectCustomContextPayload message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload} ObjectCustomContextPayload + */ + ObjectCustomContextPayload.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload) + return object; + var message = new $root.google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload(); + if (object.value != null) + message.value = String(object.value); + return message; + }; + + /** + * Creates a plain object from an ObjectCustomContextPayload message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload} message ObjectCustomContextPayload + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ObjectCustomContextPayload.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.value != null && message.hasOwnProperty("value")) { + object.value = message.value; + if (options.oneofs) + object._value = "value"; + } + return object; + }; + + /** + * Converts this ObjectCustomContextPayload to JSON. + * @function toJSON + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @instance + * @returns {Object.} JSON object + */ + ObjectCustomContextPayload.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ObjectCustomContextPayload + * @function getTypeUrl + * @memberof google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ObjectCustomContextPayload.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload"; + }; + + return ObjectCustomContextPayload; + })(); + + v1.CustomContextUpdates = (function() { + + /** + * Properties of a CustomContextUpdates. + * @memberof google.cloud.storagebatchoperations.v1 + * @interface ICustomContextUpdates + * @property {Object.|null} [updates] CustomContextUpdates updates + * @property {Array.|null} [keysToClear] CustomContextUpdates keysToClear + */ + + /** + * Constructs a new CustomContextUpdates. + * @memberof google.cloud.storagebatchoperations.v1 + * @classdesc Represents a CustomContextUpdates. + * @implements ICustomContextUpdates + * @constructor + * @param {google.cloud.storagebatchoperations.v1.ICustomContextUpdates=} [properties] Properties to set + */ + function CustomContextUpdates(properties) { + this.updates = {}; + this.keysToClear = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CustomContextUpdates updates. + * @member {Object.} updates + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @instance + */ + CustomContextUpdates.prototype.updates = $util.emptyObject; + + /** + * CustomContextUpdates keysToClear. + * @member {Array.} keysToClear + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @instance + */ + CustomContextUpdates.prototype.keysToClear = $util.emptyArray; + + /** + * Creates a new CustomContextUpdates instance using the specified properties. + * @function create + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {google.cloud.storagebatchoperations.v1.ICustomContextUpdates=} [properties] Properties to set + * @returns {google.cloud.storagebatchoperations.v1.CustomContextUpdates} CustomContextUpdates instance + */ + CustomContextUpdates.create = function create(properties) { + return new CustomContextUpdates(properties); + }; + + /** + * Encodes the specified CustomContextUpdates message. Does not implicitly {@link google.cloud.storagebatchoperations.v1.CustomContextUpdates.verify|verify} messages. + * @function encode + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {google.cloud.storagebatchoperations.v1.ICustomContextUpdates} message CustomContextUpdates message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CustomContextUpdates.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.updates != null && Object.hasOwnProperty.call(message, "updates")) + for (var keys = Object.keys(message.updates), i = 0; i < keys.length; ++i) { + writer.uint32(/* id 1, wireType 2 =*/10).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]); + $root.google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.encode(message.updates[keys[i]], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim(); + } + if (message.keysToClear != null && message.keysToClear.length) + for (var i = 0; i < message.keysToClear.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.keysToClear[i]); + return writer; + }; + + /** + * Encodes the specified CustomContextUpdates message, length delimited. Does not implicitly {@link google.cloud.storagebatchoperations.v1.CustomContextUpdates.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {google.cloud.storagebatchoperations.v1.ICustomContextUpdates} message CustomContextUpdates message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CustomContextUpdates.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CustomContextUpdates message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.storagebatchoperations.v1.CustomContextUpdates} CustomContextUpdates + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CustomContextUpdates.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.cloud.storagebatchoperations.v1.CustomContextUpdates(), key, value; + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (message.updates === $util.emptyObject) + message.updates = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = null; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = $root.google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.decode(reader, reader.uint32()); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.updates[key] = value; + break; + } + case 2: { + if (!(message.keysToClear && message.keysToClear.length)) + message.keysToClear = []; + message.keysToClear.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a CustomContextUpdates message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.storagebatchoperations.v1.CustomContextUpdates} CustomContextUpdates + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CustomContextUpdates.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CustomContextUpdates message. + * @function verify + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CustomContextUpdates.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.updates != null && message.hasOwnProperty("updates")) { + if (!$util.isObject(message.updates)) + return "updates: object expected"; + var key = Object.keys(message.updates); + for (var i = 0; i < key.length; ++i) { + var error = $root.google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.verify(message.updates[key[i]]); + if (error) + return "updates." + error; + } + } + if (message.keysToClear != null && message.hasOwnProperty("keysToClear")) { + if (!Array.isArray(message.keysToClear)) + return "keysToClear: array expected"; + for (var i = 0; i < message.keysToClear.length; ++i) + if (!$util.isString(message.keysToClear[i])) + return "keysToClear: string[] expected"; + } + return null; + }; + + /** + * Creates a CustomContextUpdates message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.storagebatchoperations.v1.CustomContextUpdates} CustomContextUpdates + */ + CustomContextUpdates.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.storagebatchoperations.v1.CustomContextUpdates) + return object; + var message = new $root.google.cloud.storagebatchoperations.v1.CustomContextUpdates(); + if (object.updates) { + if (typeof object.updates !== "object") + throw TypeError(".google.cloud.storagebatchoperations.v1.CustomContextUpdates.updates: object expected"); + message.updates = {}; + for (var keys = Object.keys(object.updates), i = 0; i < keys.length; ++i) { + if (typeof object.updates[keys[i]] !== "object") + throw TypeError(".google.cloud.storagebatchoperations.v1.CustomContextUpdates.updates: object expected"); + message.updates[keys[i]] = $root.google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.fromObject(object.updates[keys[i]]); + } + } + if (object.keysToClear) { + if (!Array.isArray(object.keysToClear)) + throw TypeError(".google.cloud.storagebatchoperations.v1.CustomContextUpdates.keysToClear: array expected"); + message.keysToClear = []; + for (var i = 0; i < object.keysToClear.length; ++i) + message.keysToClear[i] = String(object.keysToClear[i]); + } + return message; + }; + + /** + * Creates a plain object from a CustomContextUpdates message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {google.cloud.storagebatchoperations.v1.CustomContextUpdates} message CustomContextUpdates + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CustomContextUpdates.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.keysToClear = []; + if (options.objects || options.defaults) + object.updates = {}; + var keys2; + if (message.updates && (keys2 = Object.keys(message.updates)).length) { + object.updates = {}; + for (var j = 0; j < keys2.length; ++j) + object.updates[keys2[j]] = $root.google.cloud.storagebatchoperations.v1.ObjectCustomContextPayload.toObject(message.updates[keys2[j]], options); + } + if (message.keysToClear && message.keysToClear.length) { + object.keysToClear = []; + for (var j = 0; j < message.keysToClear.length; ++j) + object.keysToClear[j] = message.keysToClear[j]; + } + return object; + }; + + /** + * Converts this CustomContextUpdates to JSON. + * @function toJSON + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @instance + * @returns {Object.} JSON object + */ + CustomContextUpdates.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CustomContextUpdates + * @function getTypeUrl + * @memberof google.cloud.storagebatchoperations.v1.CustomContextUpdates + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CustomContextUpdates.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.storagebatchoperations.v1.CustomContextUpdates"; + }; + + return CustomContextUpdates; + })(); + + v1.UpdateObjectCustomContext = (function() { + + /** + * Properties of an UpdateObjectCustomContext. + * @memberof google.cloud.storagebatchoperations.v1 + * @interface IUpdateObjectCustomContext + * @property {google.cloud.storagebatchoperations.v1.ICustomContextUpdates|null} [customContextUpdates] UpdateObjectCustomContext customContextUpdates + * @property {boolean|null} [clearAll] UpdateObjectCustomContext clearAll + */ + + /** + * Constructs a new UpdateObjectCustomContext. + * @memberof google.cloud.storagebatchoperations.v1 + * @classdesc Represents an UpdateObjectCustomContext. + * @implements IUpdateObjectCustomContext + * @constructor + * @param {google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext=} [properties] Properties to set + */ + function UpdateObjectCustomContext(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UpdateObjectCustomContext customContextUpdates. + * @member {google.cloud.storagebatchoperations.v1.ICustomContextUpdates|null|undefined} customContextUpdates + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @instance + */ + UpdateObjectCustomContext.prototype.customContextUpdates = null; + + /** + * UpdateObjectCustomContext clearAll. + * @member {boolean|null|undefined} clearAll + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @instance + */ + UpdateObjectCustomContext.prototype.clearAll = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * UpdateObjectCustomContext action. + * @member {"customContextUpdates"|"clearAll"|undefined} action + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @instance + */ + Object.defineProperty(UpdateObjectCustomContext.prototype, "action", { + get: $util.oneOfGetter($oneOfFields = ["customContextUpdates", "clearAll"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new UpdateObjectCustomContext instance using the specified properties. + * @function create + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext=} [properties] Properties to set + * @returns {google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext} UpdateObjectCustomContext instance + */ + UpdateObjectCustomContext.create = function create(properties) { + return new UpdateObjectCustomContext(properties); + }; + + /** + * Encodes the specified UpdateObjectCustomContext message. Does not implicitly {@link google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.verify|verify} messages. + * @function encode + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext} message UpdateObjectCustomContext message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateObjectCustomContext.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.customContextUpdates != null && Object.hasOwnProperty.call(message, "customContextUpdates")) + $root.google.cloud.storagebatchoperations.v1.CustomContextUpdates.encode(message.customContextUpdates, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.clearAll != null && Object.hasOwnProperty.call(message, "clearAll")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.clearAll); + return writer; + }; + + /** + * Encodes the specified UpdateObjectCustomContext message, length delimited. Does not implicitly {@link google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {google.cloud.storagebatchoperations.v1.IUpdateObjectCustomContext} message UpdateObjectCustomContext message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + UpdateObjectCustomContext.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an UpdateObjectCustomContext message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext} UpdateObjectCustomContext + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateObjectCustomContext.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.cloud.storagebatchoperations.v1.UpdateObjectCustomContext(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.customContextUpdates = $root.google.cloud.storagebatchoperations.v1.CustomContextUpdates.decode(reader, reader.uint32()); + break; + } + case 2: { + message.clearAll = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an UpdateObjectCustomContext message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext} UpdateObjectCustomContext + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + UpdateObjectCustomContext.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an UpdateObjectCustomContext message. + * @function verify + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + UpdateObjectCustomContext.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + var properties = {}; + if (message.customContextUpdates != null && message.hasOwnProperty("customContextUpdates")) { + properties.action = 1; + { + var error = $root.google.cloud.storagebatchoperations.v1.CustomContextUpdates.verify(message.customContextUpdates); + if (error) + return "customContextUpdates." + error; + } + } + if (message.clearAll != null && message.hasOwnProperty("clearAll")) { + if (properties.action === 1) + return "action: multiple values"; + properties.action = 1; + if (typeof message.clearAll !== "boolean") + return "clearAll: boolean expected"; + } + return null; + }; + + /** + * Creates an UpdateObjectCustomContext message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext} UpdateObjectCustomContext + */ + UpdateObjectCustomContext.fromObject = function fromObject(object) { + if (object instanceof $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext) + return object; + var message = new $root.google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext(); + if (object.customContextUpdates != null) { + if (typeof object.customContextUpdates !== "object") + throw TypeError(".google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext.customContextUpdates: object expected"); + message.customContextUpdates = $root.google.cloud.storagebatchoperations.v1.CustomContextUpdates.fromObject(object.customContextUpdates); + } + if (object.clearAll != null) + message.clearAll = Boolean(object.clearAll); + return message; + }; + + /** + * Creates a plain object from an UpdateObjectCustomContext message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext} message UpdateObjectCustomContext + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UpdateObjectCustomContext.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.customContextUpdates != null && message.hasOwnProperty("customContextUpdates")) { + object.customContextUpdates = $root.google.cloud.storagebatchoperations.v1.CustomContextUpdates.toObject(message.customContextUpdates, options); + if (options.oneofs) + object.action = "customContextUpdates"; + } + if (message.clearAll != null && message.hasOwnProperty("clearAll")) { + object.clearAll = message.clearAll; + if (options.oneofs) + object.action = "clearAll"; + } + return object; + }; + + /** + * Converts this UpdateObjectCustomContext to JSON. + * @function toJSON + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @instance + * @returns {Object.} JSON object + */ + UpdateObjectCustomContext.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UpdateObjectCustomContext + * @function getTypeUrl + * @memberof google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UpdateObjectCustomContext.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.storagebatchoperations.v1.UpdateObjectCustomContext"; + }; + + return UpdateObjectCustomContext; + })(); + v1.ErrorSummary = (function() { /** diff --git a/packages/google-cloud-storagebatchoperations/protos/protos.json b/packages/google-cloud-storagebatchoperations/protos/protos.json index e8d372a2429..9d7e1eb0db2 100644 --- a/packages/google-cloud-storagebatchoperations/protos/protos.json +++ b/packages/google-cloud-storagebatchoperations/protos/protos.json @@ -453,7 +453,8 @@ "putObjectHold", "deleteObject", "putMetadata", - "rewriteObject" + "rewriteObject", + "updateObjectCustomContext" ] } }, @@ -492,6 +493,10 @@ "type": "RewriteObject", "id": 20 }, + "updateObjectCustomContext": { + "type": "UpdateObjectCustomContext", + "id": 23 + }, "loggingConfig": { "type": "LoggingConfig", "id": 9, @@ -589,7 +594,8 @@ "putObjectHold", "deleteObject", "putMetadata", - "rewriteObject" + "rewriteObject", + "updateObjectCustomContext" ] } }, @@ -629,6 +635,10 @@ "type": "RewriteObject", "id": 14 }, + "updateObjectCustomContext": { + "type": "UpdateObjectCustomContext", + "id": 15 + }, "createTime": { "type": "google.protobuf.Timestamp", "id": 5, @@ -954,6 +964,64 @@ } } }, + "ObjectCustomContextPayload": { + "oneofs": { + "_value": { + "oneof": [ + "value" + ] + } + }, + "fields": { + "value": { + "type": "string", + "id": 1, + "options": { + "proto3_optional": true + } + } + } + }, + "CustomContextUpdates": { + "fields": { + "updates": { + "keyType": "string", + "type": "ObjectCustomContextPayload", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "keysToClear": { + "rule": "repeated", + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "UpdateObjectCustomContext": { + "oneofs": { + "action": { + "oneof": [ + "customContextUpdates", + "clearAll" + ] + } + }, + "fields": { + "customContextUpdates": { + "type": "CustomContextUpdates", + "id": 1 + }, + "clearAll": { + "type": "bool", + "id": 2 + } + } + }, "ErrorSummary": { "fields": { "errorCode": { diff --git a/packages/google-cloud-storagebatchoperations/samples/package.json b/packages/google-cloud-storagebatchoperations/samples/package.json index d2078bddc04..105d8beabaa 100644 --- a/packages/google-cloud-storagebatchoperations/samples/package.json +++ b/packages/google-cloud-storagebatchoperations/samples/package.json @@ -14,7 +14,7 @@ "publish": "echo 'sample test; do not publish'" }, "dependencies": { - "@google-cloud/storagebatchoperations": "^0.2.0" + "@google-cloud/storagebatchoperations": "^0.3.0" }, "devDependencies": { "c8": "^10.0.0", diff --git a/packages/google-cloud-vectorsearch/CHANGELOG.md b/packages/google-cloud-vectorsearch/CHANGELOG.md index fb498f34f58..650547b5a64 100644 --- a/packages/google-cloud-vectorsearch/CHANGELOG.md +++ b/packages/google-cloud-vectorsearch/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [0.3.0](https://github.com/googleapis/google-cloud-node/compare/vectorsearch-v0.2.0...vectorsearch-v0.3.0) (2026-03-02) + + +### ⚠ BREAKING CHANGES + +* [vectorsearch] introduce new v1 vectorsearch surface and make it default version ([#7273](https://github.com/googleapis/google-cloud-node/issues/7273)) + +### Features + +* [vectorsearch] introduce new v1 vectorsearch surface and make it default version ([#7273](https://github.com/googleapis/google-cloud-node/issues/7273)) ([0faaf8c](https://github.com/googleapis/google-cloud-node/commit/0faaf8cf11c10c807fad495758c33e601589cf4c)) + ## [0.2.0](https://github.com/googleapis/google-cloud-node/compare/vectorsearch-v0.1.0...vectorsearch-v0.2.0) (2026-02-03) diff --git a/packages/google-cloud-vectorsearch/package.json b/packages/google-cloud-vectorsearch/package.json index a2995c64f81..427fba495df 100644 --- a/packages/google-cloud-vectorsearch/package.json +++ b/packages/google-cloud-vectorsearch/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/vectorsearch", - "version": "0.2.0", + "version": "0.3.0", "description": "Vector Search API client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-visionai/CHANGELOG.md b/packages/google-cloud-visionai/CHANGELOG.md new file mode 100644 index 00000000000..60d2446303f --- /dev/null +++ b/packages/google-cloud-visionai/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +## 0.1.0 (2026-03-02) + + +### Features + +* Add initial files for google.cloud.visionai.v1 ([#7275](https://github.com/googleapis/google-cloud-node/issues/7275)) ([1cc4a84](https://github.com/googleapis/google-cloud-node/commit/1cc4a84c3cab7894d8877488dcd7454aef62a8a2)) + + +### Bug Fixes + +* [gkeconnect-gateway] remove unused GatewayServiceClient ([#6775](https://github.com/googleapis/google-cloud-node/issues/6775)) ([41c2ff2](https://github.com/googleapis/google-cloud-node/commit/41c2ff2851b5fdadabf4f9bd3500167c34b32ff7)) diff --git a/packages/google-cloud-visionai/package.json b/packages/google-cloud-visionai/package.json index 59a1f21d470..52f7998c6f8 100644 --- a/packages/google-cloud-visionai/package.json +++ b/packages/google-cloud-visionai/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/visionai", - "version": "0.0.0", + "version": "0.1.0", "description": "Vision AI API client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-workflows/CHANGELOG.md b/packages/google-cloud-workflows/CHANGELOG.md index 459723fc830..12f71b59e3b 100644 --- a/packages/google-cloud-workflows/CHANGELOG.md +++ b/packages/google-cloud-workflows/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## [5.1.0](https://github.com/googleapis/google-cloud-node/compare/workflows-v5.0.0...workflows-v5.1.0) (2026-03-02) + + +### Features + +* Expand workflows to receive both workflows and executions ([#7271](https://github.com/googleapis/google-cloud-node/issues/7271)) ([faf79df](https://github.com/googleapis/google-cloud-node/commit/faf79df319ddd7d732413aa0b745160bfb815198)) + + +### Bug Fixes + +* [gkeconnect-gateway] remove unused GatewayServiceClient ([#6775](https://github.com/googleapis/google-cloud-node/issues/6775)) ([41c2ff2](https://github.com/googleapis/google-cloud-node/commit/41c2ff2851b5fdadabf4f9bd3500167c34b32ff7)) + ## [5.0.0](https://github.com/googleapis/google-cloud-node/compare/workflows-v4.4.0...workflows-v5.0.0) (2025-10-13) diff --git a/packages/google-cloud-workflows/package.json b/packages/google-cloud-workflows/package.json index 42aecfd67f9..2b4b90fed7f 100644 --- a/packages/google-cloud-workflows/package.json +++ b/packages/google-cloud-workflows/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/workflows", - "version": "5.0.0", + "version": "5.1.0", "description": "Workflows client for Node.js", "repository": { "type": "git", diff --git a/packages/google-cloud-workflows/samples/package.json b/packages/google-cloud-workflows/samples/package.json index cc0d34b3183..6ef3573d63a 100644 --- a/packages/google-cloud-workflows/samples/package.json +++ b/packages/google-cloud-workflows/samples/package.json @@ -13,7 +13,7 @@ "test": "c8 mocha --timeout 600000 test/*.js" }, "dependencies": { - "@google-cloud/workflows": "^5.0.0" + "@google-cloud/workflows": "^5.1.0" }, "devDependencies": { "c8": "^10.0.0", diff --git a/packages/google-cloud-workloadmanager/CHANGELOG.md b/packages/google-cloud-workloadmanager/CHANGELOG.md new file mode 100644 index 00000000000..b38012d71ea --- /dev/null +++ b/packages/google-cloud-workloadmanager/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +## 0.1.0 (2026-03-02) + + +### Features + +* Add initial files for google.cloud.workloadmanager.v1 ([#7265](https://github.com/googleapis/google-cloud-node/issues/7265)) ([8a30212](https://github.com/googleapis/google-cloud-node/commit/8a30212142e5403294368da827cb33d3b167209d)) + + +### Bug Fixes + +* [gkeconnect-gateway] remove unused GatewayServiceClient ([#6775](https://github.com/googleapis/google-cloud-node/issues/6775)) ([41c2ff2](https://github.com/googleapis/google-cloud-node/commit/41c2ff2851b5fdadabf4f9bd3500167c34b32ff7)) diff --git a/packages/google-cloud-workloadmanager/package.json b/packages/google-cloud-workloadmanager/package.json index 0e4f4de0bf9..dfde7316936 100644 --- a/packages/google-cloud-workloadmanager/package.json +++ b/packages/google-cloud-workloadmanager/package.json @@ -1,6 +1,6 @@ { "name": "@google-cloud/workloadmanager", - "version": "0.0.0", + "version": "0.1.0", "description": "Workload Manager API client for Node.js", "repository": { "type": "git", diff --git a/packages/google-storage-control/.OwlBot.yaml b/packages/google-storage-control/.OwlBot.yaml index 688844a25c1..d963237aaa1 100644 --- a/packages/google-storage-control/.OwlBot.yaml +++ b/packages/google-storage-control/.OwlBot.yaml @@ -15,5 +15,7 @@ deep-copy-regex: - source: /google/storage/control/google-storage-control-nodejs dest: /owl-bot-staging/google-storage-control +deep-preserve-regex: + - /.*\.jsdoc\.js api-name: control \ No newline at end of file diff --git a/packages/google-storage-control/.jsdoc.js b/packages/google-storage-control/.jsdoc.js index 583fbc1f81a..9d032c203f2 100644 --- a/packages/google-storage-control/.jsdoc.js +++ b/packages/google-storage-control/.jsdoc.js @@ -37,6 +37,10 @@ module.exports = { 'build/src', 'protos' ], + exclude: [ + 'build/src/v2/storage_client.js', + 'build/src/v2/storage_control_client.js' + ], includePattern: '\\.js$' }, templates: { diff --git a/release-please-submodules.json b/release-please-submodules.json index 31841c0d0fd..1ffd86d72d5 100644 --- a/release-please-submodules.json +++ b/release-please-submodules.json @@ -1,13 +1,7 @@ { - "release-type": "node", - "separate-pull-requests": true, "commit-batch-size": 1, "include-component-in-tag": true, - "tag-separator": "-", "packages": { - "handwritten/logging-winston": { - "component": "logging-winston" - }, "handwritten/bigquery": { "component": "bigquery" }, @@ -19,11 +13,23 @@ }, "handwritten/logging-bunyan": { "component": "logging-bunyan" + }, + "handwritten/logging-winston": { + "component": "logging-winston" + }, + "handwritten/spanner": { + "component": "spanner" + }, + "handwritten/storage": { + "component": "storage" } }, "plugins": [ { "type": "sentence-case" } - ] + ], + "release-type": "node", + "separate-pull-requests": true, + "tag-separator": "-" }